API リファレンスはソースコード内の Go ドキュメントコメントから生成されており、英語で記述されています。
package render3d
import "github.com/nsgo-dev/game/pkg/render3d"概要
Package render3d provides the GPU-agnostic pure-Go 3D render-queue pipeline and developer tools for NSGo 3D games.
Render Pipeline (#244–#248)
Queue.Build executes the complete CPU-side frame preparation stage with zero steady-state allocations:
- Frustum culling (#244): extracts six view-frustum planes via math3d.FrustumFromMat4 (or math3d.FrustumFromMat4NO when Queue.FrustumNO is set) and discards items whose world AABB lies outside the view volume.
- Software occlusion culling (#380): OcclusionBuffer rasterizes static Occluder volumes conservatively into a low-resolution CPU depth buffer, builds a max-Z Hi-Z mip pyramid, and performs O(1) zero-false-negative AABB visibility queries integrated into Queue.BuildWithOcclusion.
- Levels of detail (#247): selects the active LODLevel per visible item from camera distance and projected screen-height ratio with configurable hysteresis (SelectLOD) to eliminate boundary popping.
- Opaque sorting & batching (#245): orders opaque and alpha-masked draws by (PipelineID, MaterialID, MeshID, Blend, front-to-back distance) to minimize pipeline/material state switches and early-Z overdraw.
- Instancing (#246): merges consecutive opaque draws sharing the same (PipelineID, MaterialID, MeshID, Blend) into InstanceBatch entries holding contiguous math3d.Mat4 transform slices.
- Transparency (#248): separates BlendAlphaBlend draws and sorts them strictly back-to-front by distance from the camera.
Developer Tools (#286–#289)
- Debug drawing & performance (#286): DebugDraw records 3D wireframe primitives (lines, AABBs, spheres, rays, axes, grids, frustums) and projects them with near-plane clipping into *core.Drawing; FrameProfiler tracks rolling frame-time and draw-call metrics.
- Gizmos & wireframes (#287): Gizmo generates 3D translate/rotate/scale handles, performs ray-based axis picking, computes constrained drag deltas with optional snapping, and renders into *core.Drawing via DrawGizmo.
- Render statistics (#288) & mobile GPU budgets (#289): RenderStats captures exact per-frame culling, batching, geometry, state-switch, and memory totals; CheckBudget validates frames against MobileBudget, DesktopBudget, or custom Budget limits.
Mesh Buffers (#112)
Mesh holds triangle geometry (positions, optional normals and UVs, optional indices) on the CPU. UploadMesh validates it and uploads it into the vertex and index buffers of NSGo's GPU view (gpu.Device, nsgo-dev/nsgo#1059) as a GPUMesh, whose buffers belong to a core.Scope. Every mesh shares one interleaved vertex layout, MeshVertexLayout, so one pipeline draws any of them, and GPUMesh.Draw binds the buffers and issues the draw inside a gpu.RenderPass. The index width is chosen per mesh (uint16 below 0xFFFF vertices, otherwise uint32), which every GPU view backend accepts, WebGL 2 included.
Textures and Samplers (#114)
UploadTexture converts any image.Image into a straight-alpha RGBA8 PixelBuffer (PixelBufferFromImage) and uploads it as a scope-owned GPUTexture on gpu.Device; UploadTexturePixels uploads raw RGBA8, RG8, or R8 pixel buffers directly with optional row padding. Setting TextureUpload.SRGB uses gpu.FormatRGBA8UnormSRGB for color maps while keeping linear formats for data maps; setting TextureUpload.Mipmaps builds a CPU area-weighted box mipmap chain (in linear light when sRGB) and uploads every level via gpu.Device.WriteTextureMip, so mipmapping works on every GPU backend and survives device loss when Retained is set. NewGPUSampler validates filtering, wrapping, LOD bounds, and WebGPU anisotropy constraints from SamplerOptions (with presets such as SamplerLinearRepeat and SamplerNearestClamp); TextureBindingLayout and BindTexture bind a texture and sampler to a shader group.
Budgeted Async Uploads (#387)
Uploader streams large assets without frame hitches: Uploader.QueueMesh, Uploader.QueueTexture, Uploader.QueueTexturePixels, Uploader.QueueRawBuffer and Uploader.QueueRawTexture run the caller's decode function and the CPU packing (mesh validation and interleaving, image conversion, mip generation) on background workers, and Uploader.Step, called once per frame on the engine goroutine, writes the results to the gpu.Device in chunks without exceeding a per-frame byte budget. Streamed meshes and textures are the same GPUMesh and GPUTexture that UploadMesh and UploadTexture return, uploads run in UploadPriority order, and each UploadHandle reports progress and can cancel its upload.
Effects (#281)
- Billboards: Billboard builds a quad facing a CameraBasis in view-plane, view-point or axis-locked mode, BillboardQuad.DrawItem feeds it to transparent sorting, and BillboardRenderer fills billboards back to front into *core.Drawing with near-plane clipping.
- Ribbon trails: Trail records world positions and builds a triangle strip whose edges run along tangent × toCamera, so the ribbon faces the viewer at every angle, with width and color from the particles package's curves.
GPU Submission Integration
CameraBuffer (#115) keeps a scene3d.Camera's view, projection and eye point in a uniform buffer on an NSGo gpu.Device and binds it at CameraGroup, with CameraWGSL declaring the matching block for 3D shaders.
GPULightBuffer (#116) keeps a scene's LightRig (ambient fill, up to MaxDirectionalLights directional lights, up to MaxPointLights point lights with glTF KHR_lights_punctual smooth range windowing, and up to MaxSpotLights SpotLight cones with glTF KHR_lights_punctual inner and outer cone falloff, #252) in a uniform buffer bound at LightGroup, with LightWGSL providing the matching block and glTF 2.0 metallic-roughness Cook-Torrance GGX PBR shading functions, LitPBRWGSL and NewLitPBRPipeline offering a complete lit PBR shader pipeline, and EvaluatePBR / ShadePoint providing the matching CPU reference evaluator.
GPUFogBuffer (#254) keeps a Fog (linear, exponential or exponential-squared distance fog, analytical exponential height fog, or both) in a uniform buffer. NewLitPBRFogPipeline draws LitPBRWGSL's lighting with fog with the buffer at FogGroup, and NewMaterialPipeline does the same for materials when MaterialPipelineOptions.FogLayout is set, with the buffer at MaterialFogGroup. FogWGSL holds the shader functions for custom shaders, and Fog.Apply with FogCameraPos is the matching CPU reference.
SpotShadowMap and PointShadowMap (#255) shadow the first spot light and the first point light of a LightRig: a perspective depth map for the spot cone and a 3x2 depth atlas holding the six cube faces of the point light, updated from the rig's SpotLight and PointLight. NewLitPBRSpotShadowPipeline and NewLitPBRPointShadowPipeline draw LitPBRWGSL's lighting with the map bound at LocalShadowGroup; SpotShadowWGSL and PointShadowWGSL (or SpotShadowWGSLForGroup and PointShadowWGSLForGroup at another group) add the shadow to custom shaders, and EvaluateSpotShadow, EvaluatePointShadow and ShadePointVisibility are the matching CPU references.
SkyboxPipeline (#253) draws a GPUCubemap as a background behind opaque geometry (including linear float16 HDR environments built with HDRCubemap, CubemapFromHDR, and UploadCubemapHDR), and GPUIBLBuffer holds an environment's IrradianceSH diffuse irradiance and PrefilterEnvironment / PrefilterEnvironmentHDR specular cubemap for image-based lighting. NewLitPBRIBLPipeline adds that lighting to LitPBRWGSL's with the buffer at IBLGroup, NewMaterialIBLPipeline pairs textured glTF [GPUMaterial]s with IBL at MaterialIBLGroup, IBLWGSL holds the shader functions for custom shaders, and EvaluateIBL / EvaluateIBLHDR / EvaluateMaterialIBL are the matching CPU references.
The CPU culling, LOD, sorting, instancing, gizmo, debug, statistics, and budget pipeline stays deterministic, pure Go, and independent of the GPU view, so it runs the same in headless tests and servers; the camera, light, mesh, texture, and sampler helpers are the parts that talk to gpu.Device.
目次
- 定数
- 変数
- func AppendFogUniforms(dst []byte, u FogUniforms) []byte
- func AppendJointMatrices(dst []byte, joints []math3d.Mat4) ([]byte, error)
- func AppendShadowUniforms(dst []byte, u ShadowUniforms) []byte
- func AppendToneMapUniforms(dst []byte, opts ToneMapOptions) []byte
- func AppendUnlitUniforms(dst []byte, m UnlitMaterial) []byte
- func ApplyFXAA(src *image.RGBA, opts FXAAOptions) *image.RGBA
- func ApplyToneMap(rgb math3d.Vec3, opts ToneMapOptions) math3d.Vec3
- func BakeReflectionProbe(cx *core.Scope, dev *gpu.Device, probe *ReflectionProbe, opts ProbeBakeOptions, sample func(origin, dir math3d.Vec3) [3]float32) error
- func BakeReflectionProbeGPU( cx *core.Scope, dev *gpu.Device, probe *ReflectionProbe, opts ProbeBakeOptions, renderFace func(pass *gpu.RenderPass, face gpu.CubeFace, cam CameraUniform), onDone func(error), )
- func BindTexture(cx *core.Scope, dev *gpu.Device, layout *gpu.BindGroupLayout, tex *GPUTexture, samp *GPUSampler) (*gpu.BindGroup, error)
- func BoxProjectDirection(worldPos, reflDir, probePos, boxMin, boxMax math3d.Vec3) math3d.Vec3
- func CSMWGSLForGroup(group uint32) string
- func ClampSampleCount(dev *gpu.Device, requested int) int
- func ColoredVertexLayout() gpu.VertexBufferLayout
- func CompileCheck(source string, lang ShaderLanguage, params []ShaderParamDesc) error
- func CompileCheckDesc(desc CustomShaderDesc) error
- func ComputeCSMSplits(near, far float32, count int, lambda float32) []float32
- func CubeDirectionToFaceUV(dir math3d.Vec3) (face gpu.CubeFace, u, v float32)
- func CubeFaceDirection(face gpu.CubeFace, u, v float32) math3d.Vec3
- func CustomShaderWGSL(desc CustomShaderDesc) (string, error)
- func DecodeDepth32Float(raw []byte) []float32
- func DecodeLightmapSample(sample [4]float32, encoding LightmapEncoding, rgbmMaxRange float32, hardwareSRGB bool) math3d.Vec3
- func DecodeRGBD(rgba [4]uint8) math3d.Vec3
- func DecodeRGBM(rgba [4]uint8, maxRange float32) math3d.Vec3
- func DeviceSupportsClusteredLighting(dev *gpu.Device) bool
- func DrawGizmo(d *core.Drawing, viewProj math3d.Mat4, viewport core.Bounds, origin math3d.Vec3, scale float32, mode GizmoMode, activeAxis GizmoAxis)
- func EncodeCubemapHDR(w io.Writer, cm *HDRCubemap) error
- func EncodeHDR(w io.Writer, img *HDRImage) error
- func EncodeLightProbeGrid(d *LightProbeGridDoc) ([]byte, error)
- func EncodeRGBD(rgb math3d.Vec3) [4]uint8
- func EncodeRGBDImage(hdr []math3d.Vec3, width, height int) (*image.NRGBA, error)
- func EncodeRGBM(rgb math3d.Vec3, maxRange float32) [4]uint8
- func EncodeRGBMImage(hdr []math3d.Vec3, width, height int, maxRange float32) (*image.NRGBA, error)
- func EnvBRDFApprox(f0 [3]float32, roughness, nDotV float32) [3]float32
- func EvaluateCSMShadow(frame CSMFrame, atlas CSMDepthAtlas, worldPos, worldNormal math3d.Vec3, viewDepth float32) float32
- func EvaluateDirectionalShadow(worldPos, worldNormal math3d.Vec3, u ShadowUniforms, grid ShadowDepthGrid) float32
- func EvaluateIBL( sh IrradianceSH, prefilter *Cubemap, intensity float32, normal, viewDir math3d.Vec3, baseColor [3]float32, metallic, roughness, ao float32, ) [3]float32
- func EvaluateIBLHDR( sh IrradianceSH, prefilter *HDRCubemap, intensity float32, normal, viewDir math3d.Vec3, baseColor [3]float32, metallic, roughness, ao float32, ) [3]float32
- func EvaluateLightAttenuation(light ClusterLight, worldPos math3d.Vec3) (dirToLight math3d.Vec3, attenuation float32)
- func EvaluatePBR(n, v, l math3d.Vec3, mat PBRMaterial) math3d.Vec3
- func EvaluatePointShadow(u PointShadowUniform, atlasDepth []float32, faceRes uint32, worldPos, worldNormal math3d.Vec3) float32
- func EvaluateProbeIBL( sh IrradianceSH, blend ProbeBlendResult, skyPrefilter *Cubemap, intensity float32, worldPos, normal, viewDir math3d.Vec3, baseColor [3]float32, metallic, roughness, ao float32, ) [3]float32
- func EvaluateSpotShadow(u SpotShadowUniform, depth []float32, res uint32, worldPos, worldNormal math3d.Vec3) float32
- func EvaluateTerrainTriplanarFactor(geomN math3d.Vec3, tp TerrainTriplanar) float32
- func EvaluateTerrainTriplanarWeights(geomN math3d.Vec3, sharpness float32) math3d.Vec3
- func EvaluateToon(mat ToonMaterial, in ToonEvalInput) [4]float32
- func ExposureFromEV(ev float32) float32
- func ExtendedMaterialBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)
- func FilterNodesByLayer(src []*scene3d.Node, mask uint32, dst []*scene3d.Node) []*scene3d.Node
- func FogCameraPos(cam CameraUniform, worldPos math3d.Vec3) math3d.Vec3
- func GenerateBRDFLUT(size int) (*image.RGBA, error)
- func GenerateBRDFLUTWithSamples(size, sampleCount int) (*image.RGBA, error)
- func HalfToFloat32(h uint16) float32
- func IBLWGSLForGroup(group uint32) string
- func LayerMatches(objectLayer, cameraMask uint32) bool
- func LightWGSLForGroup(group uint32) string
- func LightmapVertexLayout() gpu.VertexBufferLayout
- func LinearToSRGB(rgb math3d.Vec3) math3d.Vec3
- func LinearToSRGBChannel(c float32) float32
- func LoadKTX2(cx *core.Scope, dev *gpu.Device, data []byte, opts KTX2Upload) (*GPUTexture, SamplerOptions, error)
- func MaterialBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)
- func MaterialBindingsWGSLForGroup(group uint32) string
- func MeshVertexLayout() gpu.VertexBufferLayout
- func NewClusteredLitPBRPipeline(cx *core.Scope, dev *gpu.Device, camLayout *gpu.BindGroupLayout, sys *ClusteredLightSystem, drawLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)
- func NewExtendedMaterialPipeline(cx *core.Scope, dev *gpu.Device, camLayout, matLayout *gpu.BindGroupLayout, opts ExtendedMaterialPipelineOptions) (*gpu.Pipeline, error)
- func NewLitPBRCSMPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, csmLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)
- func NewLitPBRFogPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, fogLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)
- func NewLitPBRIBLPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, iblLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)
- func NewLitPBRPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)
- func NewLitPBRPipelineWithOptions(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout *gpu.BindGroupLayout, opts LitPBRPipelineOptions) (*gpu.Pipeline, error)
- func NewLitPBRPointShadowPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, pointLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)
- func NewLitPBRProbeIBLPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, probeIBLLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)
- func NewLitPBRProbeIBLPipelineWithOptions(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, probeIBLLayout *gpu.BindGroupLayout, opts ProbeIBLPipelineOptions) (*gpu.Pipeline, error)
- func NewLitPBRShadowPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, shadowLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)
- func NewLitPBRSpotShadowPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, spotLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)
- func NewMaterialIBLPipeline(cx *core.Scope, dev *gpu.Device, camLayout, matLayout, iblLayout *gpu.BindGroupLayout, opts MaterialIBLPipelineOptions) (*gpu.Pipeline, error)
- func NewMaterialPipeline(cx *core.Scope, dev *gpu.Device, camLayout, matLayout *gpu.BindGroupLayout, opts MaterialPipelineOptions) (*gpu.Pipeline, error)
- func NewPBRLightmapPipeline( cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, matLayout, lmLayout *gpu.BindGroupLayout, opts PBRLightmapPipelineOptions, ) (*gpu.Pipeline, error)
- func NewSkinnedMeshPipeline(cx *core.Scope, dev *gpu.Device, camLayout, skinLayout *gpu.BindGroupLayout, opts SkinnedMeshPipelineOptions) (*gpu.Pipeline, error)
- func NewTerrainMaterialPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, terrainLayout *gpu.BindGroupLayout, opts TerrainPipelineOptions) (*gpu.Pipeline, error)
- func NewToonOutlinePipeline(cx *core.Scope, dev *gpu.Device, opts ToonPipelineOptions) (*gpu.Pipeline, error)
- func NewToonPipeline(cx *core.Scope, dev *gpu.Device, opts ToonPipelineOptions) (*gpu.Pipeline, error)
- func NewUnlitPipeline(cx *core.Scope, dev *gpu.Device, camLayout, matLayout *gpu.BindGroupLayout, opts UnlitPipelineOptions) (*gpu.Pipeline, error)
- func NormalizeSkinWeights(w math3d.Vec4) math3d.Vec4
- func OrderCameraViews(views []CameraView, dst []int) []int
- func PBRLightmapBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)
- func PBRLightmapBindingsWGSLForGroup(group uint32) string
- func PBRLightmapLinearWGSL() string
- func PBRLightmapWGSL() string
- func PointLightAttenuation(distSq, lightRange float32) float32
- func PointShadowSelectFace(v math3d.Vec3) (face gpu.CubeFace, localU, localV, axisDist float32)
- func PointShadowWGSLForGroup(group uint32) string
- func PreferredHDRFormat(dev *gpu.Device) gpu.TextureFormat
- func ProbeFaceViewProj(pos math3d.Vec3, face gpu.CubeFace, near, far float32) (view, proj math3d.Mat4)
- func ProbeIBLBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)
- func ProbeIBLWGSLForGroup(group uint32) string
- func ProjectScreenRatio(bounds math3d.AABB, viewProj math3d.Mat4) float32
- func ProjectSegment(a, b math3d.Vec3, viewProj math3d.Mat4, viewport core.Bounds) (ax, ay, bx, by float32, visible bool)
- func ProjectSegmentNO(a, b math3d.Vec3, viewProj math3d.Mat4, viewport core.Bounds) (ax, ay, bx, by float32, visible bool)
- func ReadCSMDepthAtlasAsync(dev *gpu.Device, csm *CascadedShadowMap, fn func(CSMDepthAtlas, error))
- func SRGBToLinear(rgb math3d.Vec3) math3d.Vec3
- func SRGBToLinearChannel(c float32) float32
- func SelectLOD(levels []LODLevel, dist float32, screenRatio float32, hysteresis float32, prevIndex int) int
- func ShadeClusteredGridPoint(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, grid *ClusterGrid, view, proj math3d.Mat4, viewportW, viewportH float32) math3d.Vec3
- func ShadeClusteredPoint(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, lights []ClusterLight) math3d.Vec3
- func ShadePoint(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig) math3d.Vec3
- func ShadePointShadowed(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, shadowVisibility float32) math3d.Vec3
- func ShadePointVisibility(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, vis LightVisibility) math3d.Vec3
- func ShadePointWithBackground(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, background math3d.Vec3) math3d.Vec3
- func ShadowBindingLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)
- func ShadowWGSLForGroup(group uint32) string
- func SkinJointMatrices(doc *gltf.Document, skinIndex int, dst []math3d.Mat4) ([]math3d.Mat4, error)
- func SkinJointMatricesWithTransform(doc *gltf.Document, skinIndex int, worldTransform math3d.Mat4, dst []math3d.Mat4) ([]math3d.Mat4, error)
- func SkinVertex(pos, normal math3d.Vec3, joints [4]uint16, weights math3d.Vec4, matrices []math3d.Mat4) (skinnedPos, skinnedNormal math3d.Vec3)
- func SkinnedBounds(bind math3d.AABB, joints []math3d.Mat4) math3d.AABB
- func SkinnedVertexLayout() gpu.VertexBufferLayout
- func SpotConeAttenuation(spotDir, toLight math3d.Vec3, angleScale, angleOffset float32) float32
- func SpotShadowViewProj(light SpotLight, near, far float32) math3d.Mat4
- func SpotShadowWGSLForGroup(group uint32) string
- func SupportsHDR(dev *gpu.Device) bool
- func TerrainMaterialBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)
- func TextureBindingLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)
- func ToonMaterialBindingLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)
- func ToonQuantizeBand(ndl float32, bands int, smoothness float32) float32
- func ToonSceneBindingLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)
- func ToonSceneDynamicBindingLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)
- func TransmissionBackgroundWGSLForGroup(group uint32) string
- func UnlitMaterialBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)
- func ValidateLightProbeGridDoc(d *LightProbeGridDoc) error
- type AAMode
- type AlphaMode
- type AmbientLight
- type Billboard
- type BillboardMode
- type BillboardQuad
- type BillboardRenderer
- type BlendMode
- type BloomConfig
- type BloomPass
- func NewBloomPass(cx *core.Scope, dev *gpu.Device, opts BloomPassOptions) (*BloomPass, error)
- func (p *BloomPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, dstColor *gpu.Texture) error
- func (p *BloomPass) Close() error
- func (p *BloomPass) Config() BloomConfig
- func (p *BloomPass) Height() uint32
- func (p *BloomPass) Resize(dev *gpu.Device, width, height uint32) error
- func (p *BloomPass) SetConfig(cfg BloomConfig) error
- func (p *BloomPass) Valid() bool
- func (p *BloomPass) Width() uint32
- type BloomPassOptions
- type Budget
- type BudgetViolation
- type CSMCascade
- type CSMConfig
- type CSMDepthAtlas
- type CSMFrame
- func FitCascades(camView, camProj math3d.Mat4, near, far float32, lightDir math3d.Vec3, cfg CSMConfig) CSMFrame
- func FitCascadesFromCamera(cam *scene3d.Camera, lightDir math3d.Vec3, cfg CSMConfig) CSMFrame
- func (f *CSMFrame) DebugTint(viewDepth float32) math3d.Vec3
- func (f *CSMFrame) EncodeUniforms(dst []byte) []byte
- func (f *CSMFrame) SelectCascade(viewDepth float32) (index int, nextIndex int, blend float32)
- type CameraBasis
- type CameraBuffer
- func NewCameraBuffer(cx *core.Scope, dev *gpu.Device) (*CameraBuffer, error)
- func (b *CameraBuffer) BindGroup() *gpu.BindGroup
- func (b *CameraBuffer) Buffer() *gpu.Buffer
- func (b *CameraBuffer) Close() error
- func (b *CameraBuffer) Layout() *gpu.BindGroupLayout
- func (b *CameraBuffer) Write(u CameraUniform)
- func (b *CameraBuffer) WriteCamera(cam *scene3d.Camera)
- type CameraUniform
- type CameraView
- type CascadedShadowMap
- func NewCascadedShadowMap(cx *core.Scope, dev *gpu.Device, cfg CSMConfig) (*CascadedShadowMap, error)
- func (c *CascadedShadowMap) AtlasHeight() uint32
- func (c *CascadedShadowMap) AtlasWidth() uint32
- func (c *CascadedShadowMap) BeginCascadePass(enc RenderPassStarter, cascadeIdx int) *gpu.RenderPass
- func (c *CascadedShadowMap) BindGroup() *gpu.BindGroup
- func (c *CascadedShadowMap) ByteSize() uint64
- func (c *CascadedShadowMap) CascadeBindGroup(idx int) *gpu.BindGroup
- func (c *CascadedShadowMap) CascadeCount() int
- func (c *CascadedShadowMap) CasterModelLayout() *gpu.BindGroupLayout
- func (c *CascadedShadowMap) Close() error
- func (c *CascadedShadowMap) Config() CSMConfig
- func (c *CascadedShadowMap) DepthPipeline() *gpu.Pipeline
- func (c *CascadedShadowMap) DepthTexture() *gpu.Texture
- func (c *CascadedShadowMap) DrawCaster(pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) bool
- func (c *CascadedShadowMap) DrawCasterGroup(pass *gpu.RenderPass, mesh *GPUMesh, modelGroup *gpu.BindGroup, dynamicOffsets ...uint32)
- func (c *CascadedShadowMap) Frame() CSMFrame
- func (c *CascadedShadowMap) Layout() *gpu.BindGroupLayout
- func (c *CascadedShadowMap) Sampler() *gpu.Sampler
- func (c *CascadedShadowMap) UniformBuffer() *gpu.Buffer
- func (c *CascadedShadowMap) Update(dev *gpu.Device, frame CSMFrame) error
- func (c *CascadedShadowMap) Valid() bool
- type ClusterConfig
- type ClusterGrid
- func NewClusterGrid(cfg ClusterConfig) (*ClusterGrid, error)
- func (g *ClusterGrid) ActiveLights() []ClusterLight
- func (g *ClusterGrid) AssignLights(view, proj math3d.Mat4, near, far float32, lights []ClusterLight) ClusterStats
- func (g *ClusterGrid) BuildFrustum(proj math3d.Mat4, near, far float32) bool
- func (g *ClusterGrid) ClusterAABB(tileX, tileY, sliceZ int) math3d.AABB
- func (g *ClusterGrid) ClusterCount() int
- func (g *ClusterGrid) ClusterIndex(tileX, tileY, sliceZ int) int
- func (g *ClusterGrid) ClusterLightIndices(tileX, tileY, sliceZ int) []uint32
- func (g *ClusterGrid) Config() ClusterConfig
- func (g *ClusterGrid) LastStats() ClusterStats
- func (g *ClusterGrid) LightIndices() []uint32
- func (g *ClusterGrid) Offsets() []ClusterOffsetCount
- func (g *ClusterGrid) SliceDepths() []float32
- func (g *ClusterGrid) SliceForDepth(viewZ float32) int
- type ClusterLight
- func ClusterLightFromPoint(l PointLight) (ClusterLight, error)
- func ClusterLightFromSpot(l SpotLight) (ClusterLight, error)
- func NewPointClusterLight(pos, color math3d.Vec3, intensity, lightRange float32) ClusterLight
- func NewSpotClusterLight(pos, dir, color math3d.Vec3, intensity, lightRange, innerConeRad, outerConeRad float32) ClusterLight
- func SelectFallbackLights(dst []ClusterLight, view, proj math3d.Mat4, lights []ClusterLight, maxLights int) []ClusterLight
- func (l ClusterLight) Validate() error
- type ClusterLightKind
- type ClusterOffsetCount
- type ClusterStats
- type ClusteredLightSystem
- func NewClusteredLightSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig) (*ClusteredLightSystem, error)
- func (s *ClusteredLightSystem) Bind(pass *gpu.RenderPass)
- func (s *ClusteredLightSystem) BindGroup() *gpu.BindGroup
- func (s *ClusteredLightSystem) BindingsWGSL() string
- func (s *ClusteredLightSystem) ByteSize() uint64
- func (s *ClusteredLightSystem) Close() error
- func (s *ClusteredLightSystem) Config() ClusterConfig
- func (s *ClusteredLightSystem) FallbackLights() []ClusterLight
- func (s *ClusteredLightSystem) Grid() *ClusterGrid
- func (s *ClusteredLightSystem) IsClustered() bool
- func (s *ClusteredLightSystem) IsFallback() bool
- func (s *ClusteredLightSystem) LastStats() ClusterStats
- func (s *ClusteredLightSystem) Layout() *gpu.BindGroupLayout
- func (s *ClusteredLightSystem) Update(dev *gpu.Device, view, proj math3d.Mat4, near, far, viewportW, viewportH float32, rig LightRig, lights []ClusterLight) (ClusterStats, error)
- func (s *ClusteredLightSystem) UpdateCamera(dev *gpu.Device, cam *scene3d.Camera, viewportW, viewportH float32, rig LightRig, lights []ClusterLight) (ClusterStats, error)
- func (s *ClusteredLightSystem) Valid() bool
- func (s *ClusteredLightSystem) WGSL() string
- type ColoredMesh
- func ColoredMeshFromGLTF(doc *gltf.Document, meshIndex, primIndex int) (ColoredMesh, error)
- func (m ColoredMesh) AppendIndexData(dst []byte) []byte
- func (m ColoredMesh) AppendVertexData(dst []byte) []byte
- func (m ColoredMesh) Bounds() math3d.AABB
- func (m ColoredMesh) HasVertexColors() bool
- func (m ColoredMesh) IndexDataSize() int
- func (m ColoredMesh) IndexFormat() gpu.IndexFormat
- func (m ColoredMesh) Indexed() bool
- func (m ColoredMesh) Mesh() Mesh
- func (m ColoredMesh) Validate() error
- func (m ColoredMesh) VertexCount() int
- func (m ColoredMesh) VertexDataSize() int
- type Cubemap
- func BakeReflectionProbeCPU(probe *ReflectionProbe, size int, srgb bool, sample func(origin, dir math3d.Vec3) [3]float32) (*Cubemap, error)
- func CubemapFromEquirectangular(img image.Image, faceSize int, srgb bool) (*Cubemap, error)
- func CubemapFromImages(faces [6]image.Image, srgb bool) (*Cubemap, error)
- func GradientSkyCubemap(zenith, horizon, ground [3]float32, faceSize int) (*Cubemap, error)
- func PrefilterEnvironment(env *Cubemap, opts PrefilterOptions) (*Cubemap, error)
- func (c *Cubemap) MipLevels() int
- func (c *Cubemap) Sample(dir math3d.Vec3) [3]float32
- func (c *Cubemap) SampleLOD(dir math3d.Vec3, lod float32) [3]float32
- func (c *Cubemap) Size() int
- func (c *Cubemap) Validate() error
- type CubemapUpload
- type CustomMaterial
- func NewCustomMaterial(cx *core.Scope, dev *gpu.Device, desc CustomShaderDesc) (*CustomMaterial, error)
- func (m *CustomMaterial) ApplyMap(values map[string]any) error
- func (m *CustomMaterial) Bind(pass *gpu.RenderPass)
- func (m *CustomMaterial) BindGroup() *gpu.BindGroup
- func (m *CustomMaterial) ByteSize() uint64
- func (m *CustomMaterial) Close() error
- func (m *CustomMaterial) Dirty() bool
- func (m *CustomMaterial) Draw(pass *gpu.RenderPass, mesh *GPUMesh)
- func (m *CustomMaterial) Layout() *gpu.BindGroupLayout
- func (m *CustomMaterial) ParamBinding(name string) (texBinding, samplerBinding uint32, ok bool)
- func (m *CustomMaterial) ParamOffset(name string) (int, bool)
- func (m *CustomMaterial) Params() []ShaderParamDesc
- func (m *CustomMaterial) Pipeline() *gpu.Pipeline
- func (m *CustomMaterial) SetBool(name string, v bool) error
- func (m *CustomMaterial) SetColor(name string, c core.Color) error
- func (m *CustomMaterial) SetFloat(name string, v float32) error
- func (m *CustomMaterial) SetInt(name string, v int32) error
- func (m *CustomMaterial) SetTexture(name string, tex *GPUTexture, samp *GPUSampler) error
- func (m *CustomMaterial) SetVec2(name string, v math3d.Vec2) error
- func (m *CustomMaterial) SetVec3(name string, v math3d.Vec3) error
- func (m *CustomMaterial) SetVec4(name string, v math3d.Vec4) error
- func (m *CustomMaterial) Sync(dev *gpu.Device) error
- func (m *CustomMaterial) UniformBytes() []byte
- func (m *CustomMaterial) UniformSize() int
- func (m *CustomMaterial) Update(dev *gpu.Device) error
- func (m *CustomMaterial) Valid() bool
- func (m *CustomMaterial) WGSL() string
- type CustomMaterialError
- type CustomParamLayout
- type CustomShaderDesc
- type CustomUniformLayout
- type DebugDraw
- func (dd *DebugDraw) AABB(box math3d.AABB, color core.Color)
- func (dd *DebugDraw) Axes(origin math3d.Vec3, length float32)
- func (dd *DebugDraw) Clear()
- func (dd *DebugDraw) Flush(d *core.Drawing, viewProj math3d.Mat4, viewport core.Bounds)
- func (dd *DebugDraw) Frustum(invViewProj math3d.Mat4, color core.Color)
- func (dd *DebugDraw) Grid(center math3d.Vec3, halfExtent float32, divisions int, color core.Color)
- func (dd *DebugDraw) Line(a, b math3d.Vec3, color core.Color)
- func (dd *DebugDraw) LineWidth(a, b math3d.Vec3, color core.Color, width float32)
- func (dd *DebugDraw) Lines() []DebugLine
- func (dd *DebugDraw) Ray(ray math3d.Ray, length float32, color core.Color)
- func (dd *DebugDraw) Sphere(center math3d.Vec3, radius float32, color core.Color, segments int)
- type DebugLine
- type DepthOfFieldConfig
- type DepthOfFieldPass
- func NewDepthOfFieldPass(cx *core.Scope, dev *gpu.Device, opts DepthOfFieldPassOptions) (*DepthOfFieldPass, error)
- func (p *DepthOfFieldPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error
- func (p *DepthOfFieldPass) Close() error
- func (p *DepthOfFieldPass) Config() DepthOfFieldConfig
- func (p *DepthOfFieldPass) Height() uint32
- func (p *DepthOfFieldPass) Resize(dev *gpu.Device, width, height uint32) error
- func (p *DepthOfFieldPass) SetConfig(cfg DepthOfFieldConfig) error
- func (p *DepthOfFieldPass) Valid() bool
- func (p *DepthOfFieldPass) Width() uint32
- type DepthOfFieldPassOptions
- type DirectionalLight
- type DirectionalShadowConfig
- func DefaultDirectionalShadowConfig() DirectionalShadowConfig
- func (c DirectionalShadowConfig) FitBounds(lightDir math3d.Vec3, sceneBounds math3d.AABB) (math3d.Mat4, error)
- func (c DirectionalShadowConfig) LightViewProj() (math3d.Mat4, error)
- func (c DirectionalShadowConfig) Uniforms(lightViewProj math3d.Mat4) ShadowUniforms
- func (c DirectionalShadowConfig) UniformsForBounds(sceneBounds math3d.AABB) (ShadowUniforms, error)
- func (c DirectionalShadowConfig) Validate() error
- type DirectionalShadowMap
- func NewDirectionalShadowMap(cx *core.Scope, dev *gpu.Device, opts ShadowMapOptions) (*DirectionalShadowMap, error)
- func (s *DirectionalShadowMap) BeginShadowPass(dev *gpu.Device, target ShadowPassTarget) *gpu.RenderPass
- func (s *DirectionalShadowMap) BindGroup() *gpu.BindGroup
- func (s *DirectionalShadowMap) ByteSize() uint64
- func (s *DirectionalShadowMap) Close() error
- func (s *DirectionalShadowMap) DepthPipeline() *gpu.Pipeline
- func (s *DirectionalShadowMap) DepthTexture() *gpu.Texture
- func (s *DirectionalShadowMap) DrawCaster(pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) bool
- func (s *DirectionalShadowMap) Layout() *gpu.BindGroupLayout
- func (s *DirectionalShadowMap) MaxCasters() uint32
- func (s *DirectionalShadowMap) RenderTarget() *gpu.RenderTarget
- func (s *DirectionalShadowMap) Resolution() uint32
- func (s *DirectionalShadowMap) UniformBuffer() *gpu.Buffer
- func (s *DirectionalShadowMap) Uniforms() ShadowUniforms
- func (s *DirectionalShadowMap) Update(dev *gpu.Device, cfg DirectionalShadowConfig) (ShadowUniforms, error)
- func (s *DirectionalShadowMap) UpdateBounds(dev *gpu.Device, cfg DirectionalShadowConfig, sceneBounds math3d.AABB) (ShadowUniforms, error)
- func (s *DirectionalShadowMap) Valid() bool
- func (s *DirectionalShadowMap) WriteUniforms(dev *gpu.Device, u ShadowUniforms)
- type DrawItem
- type DynamicResolutionConfig
- type DynamicResolutionFilter
- type DynamicResolutionScaler
- func NewDynamicResolutionScaler(cfg DynamicResolutionConfig) (*DynamicResolutionScaler, error)
- func (s *DynamicResolutionScaler) ClearFixedScale()
- func (s *DynamicResolutionScaler) Config() DynamicResolutionConfig
- func (s *DynamicResolutionScaler) Enabled() bool
- func (s *DynamicResolutionScaler) RecordFrameTime(gpuFrameTime time.Duration) float32
- func (s *DynamicResolutionScaler) RecordPassTimings(timings []gpu.PassTiming, labels ...string) float32
- func (s *DynamicResolutionScaler) Reset()
- func (s *DynamicResolutionScaler) Scale() float32
- func (s *DynamicResolutionScaler) ScaledSize(nativeW, nativeH int) (w, h int)
- func (s *DynamicResolutionScaler) SetEnabled(enabled bool)
- func (s *DynamicResolutionScaler) SetFixedScale(scale float32)
- func (s *DynamicResolutionScaler) SetScaleBounds(minScale, maxScale float32) error
- func (s *DynamicResolutionScaler) SmoothedFrameTime() time.Duration
- func (s *DynamicResolutionScaler) Stats() DynamicResolutionStats
- type DynamicResolutionStats
- type DynamicResolutionTarget
- func NewDynamicResolutionTarget(cx *core.Scope, dev *gpu.Device, opts DynamicResolutionTargetOptions) (*DynamicResolutionTarget, error)
- func (t *DynamicResolutionTarget) AllocatedSize() (w, h int)
- func (t *DynamicResolutionTarget) Begin3D(rec RenderPassRecorder, nativeW, nativeH int, clearColor core.Color) (*gpu.RenderPass, error)
- func (t *DynamicResolutionTarget) ByteSize() uint64
- func (t *DynamicResolutionTarget) Close() error
- func (t *DynamicResolutionTarget) ColorFormat() gpu.TextureFormat
- func (t *DynamicResolutionTarget) ColorTexture() *gpu.Texture
- func (t *DynamicResolutionTarget) DepthFormat() gpu.TextureFormat
- func (t *DynamicResolutionTarget) DepthTexture() *gpu.Texture
- func (t *DynamicResolutionTarget) EnsureCapacity(nativeW, nativeH int) error
- func (t *DynamicResolutionTarget) Filter() DynamicResolutionFilter
- func (t *DynamicResolutionTarget) NativeSize() (w, h int)
- func (t *DynamicResolutionTarget) OutputFormat() gpu.TextureFormat
- func (t *DynamicResolutionTarget) RecordFrameTime(gpuFrameTime time.Duration) float32
- func (t *DynamicResolutionTarget) RecordPassTimings(timings []gpu.PassTiming, labels ...string) float32
- func (t *DynamicResolutionTarget) RenderTarget() *gpu.RenderTarget
- func (t *DynamicResolutionTarget) Scale() float32
- func (t *DynamicResolutionTarget) ScaledSize() (w, h int)
- func (t *DynamicResolutionTarget) Scaler() *DynamicResolutionScaler
- func (t *DynamicResolutionTarget) SetFilter(f DynamicResolutionFilter)
- func (t *DynamicResolutionTarget) SetSharpness(s float32)
- func (t *DynamicResolutionTarget) Sharpness() float32
- func (t *DynamicResolutionTarget) Upscale(rec RenderPassRecorder, dst *gpu.Texture, nativeW, nativeH int) error
- func (t *DynamicResolutionTarget) UpscaleIntoPass(pass *gpu.RenderPass, nativeW, nativeH int) error
- func (t *DynamicResolutionTarget) Valid() bool
- type DynamicResolutionTargetOptions
- type ExtendedMaterialDefaults
- func NewExtendedMaterialDefaults(cx *core.Scope, dev *gpu.Device, opts MaterialDefaultsOptions) (*ExtendedMaterialDefaults, error)
- func (d *ExtendedMaterialDefaults) Base() *MaterialDefaults
- func (d *ExtendedMaterialDefaults) Black() *GPUTexture
- func (d *ExtendedMaterialDefaults) ByteSize() uint64
- func (d *ExtendedMaterialDefaults) Close() error
- func (d *ExtendedMaterialDefaults) FlatNormal() *GPUTexture
- func (d *ExtendedMaterialDefaults) Layout() *gpu.BindGroupLayout
- func (d *ExtendedMaterialDefaults) Sampler() *GPUSampler
- func (d *ExtendedMaterialDefaults) Valid() bool
- func (d *ExtendedMaterialDefaults) WhiteLinear() *GPUTexture
- func (d *ExtendedMaterialDefaults) WhiteSRGB() *GPUTexture
- type ExtendedMaterialPipelineOptions
- type ExtendedMaterialUniforms
- type FXAAOptions
- type FXAAPass
- func NewFXAAPass(cx *core.Scope, dev *gpu.Device, desc FXAAPassDesc) (*FXAAPass, error)
- func (p *FXAAPass) Close() error
- func (p *FXAAPass) Draw(pass *gpu.RenderPass, src *gpu.Texture) error
- func (p *FXAAPass) Encode(enc *gpu.Encoder, src, dst *gpu.Texture) error
- func (p *FXAAPass) Layout() *gpu.BindGroupLayout
- func (p *FXAAPass) Options() FXAAOptions
- func (p *FXAAPass) Pipeline() *gpu.Pipeline
- func (p *FXAAPass) Retained() bool
- func (p *FXAAPass) Sampler() *gpu.Sampler
- func (p *FXAAPass) SetDevice(dev *gpu.Device)
- func (p *FXAAPass) SetOptions(opts FXAAOptions)
- func (p *FXAAPass) TargetFormat() gpu.TextureFormat
- func (p *FXAAPass) Valid() bool
- type FXAAPassDesc
- type Fog
- type FogBufferOptions
- type FogMode
- type FogUniforms
- type FrameProfiler
- func NewFrameProfiler(capacity int) *FrameProfiler
- func (p *FrameProfiler) AverageFrameTime() time.Duration
- func (p *FrameProfiler) Count() int
- func (p *FrameProfiler) FPS() float64
- func (p *FrameProfiler) P95FrameTime() time.Duration
- func (p *FrameProfiler) PeakDrawCalls() int
- func (p *FrameProfiler) PeakTriangles() uint64
- func (p *FrameProfiler) Record(frameTime time.Duration, stats RenderStats)
- func (p *FrameProfiler) Reset()
- type FrameSample
- type GLTFMaterialInfo
- type GLTFMaterialSet
- func UploadGLTFExtendedMaterials(cx *core.Scope, dev *gpu.Device, defaults *ExtendedMaterialDefaults, doc *gltf.Document, opts GLTFMaterialUpload) (*GLTFMaterialSet, error)
- func UploadGLTFMaterials(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, doc *gltf.Document, opts GLTFMaterialUpload) (*GLTFMaterialSet, error)
- func (s *GLTFMaterialSet) ByteSize() uint64
- func (s *GLTFMaterialSet) Close() error
- func (s *GLTFMaterialSet) DefaultExtendedMaterial() *GPUExtendedMaterial
- func (s *GLTFMaterialSet) DefaultMaterial() *GPUMaterial
- func (s *GLTFMaterialSet) ExtendedMaterial(index int) *GPUExtendedMaterial
- func (s *GLTFMaterialSet) ExtendedMaterialForPrimitive(prim gltf.Primitive, variantIndex int) *GPUExtendedMaterial
- func (s *GLTFMaterialSet) ExtendedMaterialForVariant(prim gltf.Primitive, variantName string) *GPUExtendedMaterial
- func (s *GLTFMaterialSet) Info(index int) (GLTFMaterialInfo, bool)
- func (s *GLTFMaterialSet) InfoForPrimitive(prim gltf.Primitive, variantIndex int) (GLTFMaterialInfo, bool)
- func (s *GLTFMaterialSet) InfoForVariant(prim gltf.Primitive, variantName string) (GLTFMaterialInfo, bool)
- func (s *GLTFMaterialSet) Len() int
- func (s *GLTFMaterialSet) Material(index int) *GPUMaterial
- func (s *GLTFMaterialSet) MaterialForPrimitive(prim gltf.Primitive, variantIndex int) *GPUMaterial
- func (s *GLTFMaterialSet) MaterialForVariant(prim gltf.Primitive, variantName string) *GPUMaterial
- func (s *GLTFMaterialSet) Sampler(samplerIndex int) *GPUSampler
- func (s *GLTFMaterialSet) SamplerCount() int
- func (s *GLTFMaterialSet) Texture(imageIndex int, srgb bool) *GPUTexture
- func (s *GLTFMaterialSet) TextureCount() int
- func (s *GLTFMaterialSet) Valid() bool
- type GLTFMaterialUpload
- type GLTFPBRLightmapInfo
- type GLTFPBRLightmapSet
- func UploadGLTFPBRLightmaps(cx *core.Scope, dev *gpu.Device, doc *gltf.Document, opts GLTFPBRLightmapUpload) (*GLTFPBRLightmapSet, error)
- func (s *GLTFPBRLightmapSet) ByteSize() uint64
- func (s *GLTFPBRLightmapSet) Close() error
- func (s *GLTFPBRLightmapSet) DefaultLightmap() *GPUPBRLightmap
- func (s *GLTFPBRLightmapSet) Info(index int) (GLTFPBRLightmapInfo, bool)
- func (s *GLTFPBRLightmapSet) Layout() *gpu.BindGroupLayout
- func (s *GLTFPBRLightmapSet) Len() int
- func (s *GLTFPBRLightmapSet) Lightmap(index int) *GPUPBRLightmap
- func (s *GLTFPBRLightmapSet) LightmapForPrimitive(prim gltf.Primitive, variantIndex int) *GPUPBRLightmap
- func (s *GLTFPBRLightmapSet) LightmapForVariant(prim gltf.Primitive, variantName string) *GPUPBRLightmap
- func (s *GLTFPBRLightmapSet) NewInstance(cx *core.Scope, dev *gpu.Device, materialIndex int, model math3d.Mat4, opts PBRLightmapOptions) (*GPUPBRLightmap, error)
- func (s *GLTFPBRLightmapSet) SamplerCount() int
- func (s *GLTFPBRLightmapSet) TextureCount() int
- func (s *GLTFPBRLightmapSet) Valid() bool
- type GLTFPBRLightmapUpload
- type GLTFTextureSlot
- type GPUColoredMesh
- func UploadColoredMesh(cx *core.Scope, dev *gpu.Device, m ColoredMesh, opts MeshUpload) (*GPUColoredMesh, error)
- func (g *GPUColoredMesh) Bind(pass *gpu.RenderPass)
- func (g *GPUColoredMesh) Bounds() math3d.AABB
- func (g *GPUColoredMesh) ByteSize() uint64
- func (g *GPUColoredMesh) Close() error
- func (g *GPUColoredMesh) Draw(pass *gpu.RenderPass)
- func (g *GPUColoredMesh) HasVertexColors() bool
- func (g *GPUColoredMesh) IndexBuffer() *gpu.Buffer
- func (g *GPUColoredMesh) IndexCount() uint32
- func (g *GPUColoredMesh) IndexFormat() gpu.IndexFormat
- func (g *GPUColoredMesh) Indexed() bool
- func (g *GPUColoredMesh) Triangles() uint32
- func (g *GPUColoredMesh) Valid() bool
- func (g *GPUColoredMesh) VertexBuffer() *gpu.Buffer
- func (g *GPUColoredMesh) VertexCount() uint32
- type GPUCubemap
- func UploadCubemap(cx *core.Scope, dev *gpu.Device, cm *Cubemap, opts CubemapUpload) (*GPUCubemap, error)
- func UploadCubemapHDR(cx *core.Scope, dev *gpu.Device, cm *HDRCubemap, opts CubemapUpload) (*GPUCubemap, error)
- func (g *GPUCubemap) ByteSize() uint64
- func (g *GPUCubemap) Close() error
- func (g *GPUCubemap) Format() gpu.TextureFormat
- func (g *GPUCubemap) MaxLOD() float32
- func (g *GPUCubemap) MipLevels() uint32
- func (g *GPUCubemap) Sampler() *gpu.Sampler
- func (g *GPUCubemap) Size() uint32
- func (g *GPUCubemap) Texture() *gpu.Texture
- func (g *GPUCubemap) Valid() bool
- type GPUDirectionalLight
- type GPUExtendedMaterial
- func NewGPUExtendedMaterial(cx *core.Scope, dev *gpu.Device, defaults *ExtendedMaterialDefaults, m Material, opts MaterialUpload) (*GPUExtendedMaterial, error)
- func (g *GPUExtendedMaterial) AlphaMode() AlphaMode
- func (g *GPUExtendedMaterial) Bind(pass *gpu.RenderPass)
- func (g *GPUExtendedMaterial) BindGroup() *gpu.BindGroup
- func (g *GPUExtendedMaterial) ByteSize() uint64
- func (g *GPUExtendedMaterial) Close() error
- func (g *GPUExtendedMaterial) DoubleSided() bool
- func (g *GPUExtendedMaterial) HasClearcoat() bool
- func (g *GPUExtendedMaterial) HasTransmission() bool
- func (g *GPUExtendedMaterial) Material() Material
- func (g *GPUExtendedMaterial) UniformBuffer() *gpu.Buffer
- func (g *GPUExtendedMaterial) Update(dev *gpu.Device, m Material) error
- func (g *GPUExtendedMaterial) Valid() bool
- type GPUFogBuffer
- func NewGPUFogBuffer(cx *core.Scope, dev *gpu.Device, fog Fog, opts FogBufferOptions) (*GPUFogBuffer, error)
- func (b *GPUFogBuffer) Bind(pass *gpu.RenderPass)
- func (b *GPUFogBuffer) BindGroup() *gpu.BindGroup
- func (b *GPUFogBuffer) Buffer() *gpu.Buffer
- func (b *GPUFogBuffer) ByteSize() uint64
- func (b *GPUFogBuffer) Close() error
- func (b *GPUFogBuffer) Layout() *gpu.BindGroupLayout
- func (b *GPUFogBuffer) Update(dev *gpu.Device, fog Fog) error
- func (b *GPUFogBuffer) Valid() bool
- type GPUIBLBuffer
- func NewGPUIBLBuffer(cx *core.Scope, dev *gpu.Device, prefilter *GPUCubemap, initial IBLUniform, opts IBLBufferOptions) (*GPUIBLBuffer, error)
- func (b *GPUIBLBuffer) Bind(pass *gpu.RenderPass)
- func (b *GPUIBLBuffer) BindGroup() *gpu.BindGroup
- func (b *GPUIBLBuffer) Buffer() *gpu.Buffer
- func (b *GPUIBLBuffer) ByteSize() uint64
- func (b *GPUIBLBuffer) Close() error
- func (b *GPUIBLBuffer) Layout() *gpu.BindGroupLayout
- func (b *GPUIBLBuffer) Update(dev *gpu.Device, u IBLUniform) error
- func (b *GPUIBLBuffer) Valid() bool
- type GPULightBuffer
- func NewLightBuffer(cx *core.Scope, dev *gpu.Device, initial LightRig, opts LightBufferOptions) (*GPULightBuffer, error)
- func (b *GPULightBuffer) Bind(pass *gpu.RenderPass)
- func (b *GPULightBuffer) BindGroup() *gpu.BindGroup
- func (b *GPULightBuffer) Buffer() *gpu.Buffer
- func (b *GPULightBuffer) ByteSize() uint64
- func (b *GPULightBuffer) Close() error
- func (b *GPULightBuffer) Layout() *gpu.BindGroupLayout
- func (b *GPULightBuffer) Update(dev *gpu.Device, rig LightRig) error
- func (b *GPULightBuffer) Valid() bool
- type GPULightmapMesh
- func UploadLightmapMesh(cx *core.Scope, dev *gpu.Device, m LightmapMesh, opts MeshUpload) (*GPULightmapMesh, error)
- func UploadLightmapVertices(cx *core.Scope, dev *gpu.Device, vertices []LightmapVertex, indices []uint32, opts MeshUpload) (*GPULightmapMesh, error)
- func (g *GPULightmapMesh) Bind(pass *gpu.RenderPass)
- func (g *GPULightmapMesh) Bounds() math3d.AABB
- func (g *GPULightmapMesh) ByteSize() uint64
- func (g *GPULightmapMesh) Close() error
- func (g *GPULightmapMesh) Draw(pass *gpu.RenderPass)
- func (g *GPULightmapMesh) IndexBuffer() *gpu.Buffer
- func (g *GPULightmapMesh) IndexCount() uint32
- func (g *GPULightmapMesh) IndexFormat() gpu.IndexFormat
- func (g *GPULightmapMesh) Indexed() bool
- func (g *GPULightmapMesh) Triangles() uint32
- func (g *GPULightmapMesh) UsedUV0Fallback() bool
- func (g *GPULightmapMesh) Valid() bool
- func (g *GPULightmapMesh) VertexBuffer() *gpu.Buffer
- func (g *GPULightmapMesh) VertexCount() uint32
- type GPUMaterial
- func NewGPUMaterial(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, m Material, opts MaterialUpload) (*GPUMaterial, error)
- func (g *GPUMaterial) AlphaMode() AlphaMode
- func (g *GPUMaterial) Bind(pass *gpu.RenderPass)
- func (g *GPUMaterial) BindGroup() *gpu.BindGroup
- func (g *GPUMaterial) ByteSize() uint64
- func (g *GPUMaterial) Close() error
- func (g *GPUMaterial) DoubleSided() bool
- func (g *GPUMaterial) Material() Material
- func (g *GPUMaterial) UniformBuffer() *gpu.Buffer
- func (g *GPUMaterial) Update(dev *gpu.Device, m Material) error
- func (g *GPUMaterial) Valid() bool
- type GPUMesh
- func UploadMesh(cx *core.Scope, dev *gpu.Device, m Mesh, opts MeshUpload) (*GPUMesh, error)
- func (g *GPUMesh) Bind(pass *gpu.RenderPass)
- func (g *GPUMesh) Bounds() math3d.AABB
- func (g *GPUMesh) ByteSize() uint64
- func (g *GPUMesh) Close() error
- func (g *GPUMesh) Draw(pass *gpu.RenderPass)
- func (g *GPUMesh) IndexBuffer() *gpu.Buffer
- func (g *GPUMesh) IndexCount() uint32
- func (g *GPUMesh) IndexFormat() gpu.IndexFormat
- func (g *GPUMesh) Indexed() bool
- func (g *GPUMesh) Triangles() uint32
- func (g *GPUMesh) Valid() bool
- func (g *GPUMesh) VertexBuffer() *gpu.Buffer
- func (g *GPUMesh) VertexCount() uint32
- type GPUMorphMesh
- func UploadMorphMesh(cx *core.Scope, dev *gpu.Device, m MorphMesh, opts MeshUpload) (*GPUMorphMesh, error)
- func (m *GPUMorphMesh) Bind(pass *gpu.RenderPass)
- func (m *GPUMorphMesh) Bounds() math3d.AABB
- func (m *GPUMorphMesh) ByteSize() uint64
- func (m *GPUMorphMesh) Close() error
- func (m *GPUMorphMesh) Dirty() bool
- func (m *GPUMorphMesh) Draw(pass *gpu.RenderPass)
- func (m *GPUMorphMesh) IndexBuffer() *gpu.Buffer
- func (m *GPUMorphMesh) IndexCount() uint32
- func (m *GPUMorphMesh) IndexFormat() gpu.IndexFormat
- func (m *GPUMorphMesh) Indexed() bool
- func (m *GPUMorphMesh) Mesh() *GPUMesh
- func (m *GPUMorphMesh) SetWeights(weights []float32) error
- func (m *GPUMorphMesh) TargetCount() int
- func (m *GPUMorphMesh) Triangles() uint32
- func (m *GPUMorphMesh) Update(dev *gpu.Device) bool
- func (m *GPUMorphMesh) Valid() bool
- func (m *GPUMorphMesh) VertexBuffer() *gpu.Buffer
- func (m *GPUMorphMesh) VertexCount() uint32
- func (m *GPUMorphMesh) Weights(dst []float32) []float32
- type GPUPBRLightmap
- func NewGPUPBRLightmap(cx *core.Scope, dev *gpu.Device, lm PBRLightmap, opts PBRLightmapOptions) (*GPUPBRLightmap, error)
- func (g *GPUPBRLightmap) Bind(pass *gpu.RenderPass)
- func (g *GPUPBRLightmap) BindAt(pass *gpu.RenderPass, group uint32)
- func (g *GPUPBRLightmap) BindGroup() *gpu.BindGroup
- func (g *GPUPBRLightmap) ByteSize() uint64
- func (g *GPUPBRLightmap) Close() error
- func (g *GPUPBRLightmap) Config() PBRLightmap
- func (g *GPUPBRLightmap) Layout() *gpu.BindGroupLayout
- func (g *GPUPBRLightmap) SetModel(dev *gpu.Device, model math3d.Mat4) error
- func (g *GPUPBRLightmap) UniformBuffer() *gpu.Buffer
- func (g *GPUPBRLightmap) Update(dev *gpu.Device, lm PBRLightmap) error
- func (g *GPUPBRLightmap) Valid() bool
- type GPUPointLight
- type GPUProbeIBLBuffer
- func NewGPUProbeIBLBuffer(cx *core.Scope, dev *gpu.Device, opts ProbeIBLBufferOptions) (*GPUProbeIBLBuffer, error)
- func (b *GPUProbeIBLBuffer) Bind(pass *gpu.RenderPass)
- func (b *GPUProbeIBLBuffer) BindGroup() *gpu.BindGroup
- func (b *GPUProbeIBLBuffer) Buffer() *gpu.Buffer
- func (b *GPUProbeIBLBuffer) ByteSize() uint64
- func (b *GPUProbeIBLBuffer) Close() error
- func (b *GPUProbeIBLBuffer) Layout() *gpu.BindGroupLayout
- func (b *GPUProbeIBLBuffer) Update(dev *gpu.Device, u ProbeIBLUniform, probe0, probe1, sky *GPUCubemap) error
- func (b *GPUProbeIBLBuffer) UpdateBlend(dev *gpu.Device, sh IrradianceSH, blend ProbeBlendResult, sky *GPUCubemap, intensity float32) error
- func (b *GPUProbeIBLBuffer) UpdateForPoint( dev *gpu.Device, worldPos math3d.Vec3, reflectionProbes *ReflectionProbeSet, lightProbes *LightProbeVolume, sky *GPUCubemap, intensity float32, ) error
- func (b *GPUProbeIBLBuffer) Valid() bool
- type GPUSampler
- type GPUSkinPalette
- func NewGPUSkinPalette(cx *core.Scope, dev *gpu.Device, opts SkinPaletteOptions) (*GPUSkinPalette, error)
- func (p *GPUSkinPalette) BindGroup() *gpu.BindGroup
- func (p *GPUSkinPalette) Buffer() *gpu.Buffer
- func (p *GPUSkinPalette) ByteSize() uint64
- func (p *GPUSkinPalette) Close() error
- func (p *GPUSkinPalette) JointCount() int
- func (p *GPUSkinPalette) Layout() *gpu.BindGroupLayout
- func (p *GPUSkinPalette) Update(dev *gpu.Device, joints []math3d.Mat4) error
- func (p *GPUSkinPalette) UpdateFromGLTF(dev *gpu.Device, doc *gltf.Document, skinIndex int) error
- func (p *GPUSkinPalette) UpdateFromGLTFWithTransform(dev *gpu.Device, doc *gltf.Document, skinIndex int, worldTransform math3d.Mat4) error
- func (p *GPUSkinPalette) UpdateWithTransform(dev *gpu.Device, worldTransform math3d.Mat4, joints []math3d.Mat4) error
- func (p *GPUSkinPalette) Valid() bool
- type GPUSkinnedMesh
- func UploadSkinnedMesh(cx *core.Scope, dev *gpu.Device, m SkinnedMesh, opts MeshUpload) (*GPUSkinnedMesh, error)
- func (g *GPUSkinnedMesh) Bind(pass *gpu.RenderPass)
- func (g *GPUSkinnedMesh) Bounds() math3d.AABB
- func (g *GPUSkinnedMesh) ByteSize() uint64
- func (g *GPUSkinnedMesh) Close() error
- func (g *GPUSkinnedMesh) Draw(pass *gpu.RenderPass)
- func (g *GPUSkinnedMesh) IndexBuffer() *gpu.Buffer
- func (g *GPUSkinnedMesh) IndexCount() uint32
- func (g *GPUSkinnedMesh) IndexFormat() gpu.IndexFormat
- func (g *GPUSkinnedMesh) Indexed() bool
- func (g *GPUSkinnedMesh) JointCount() int
- func (g *GPUSkinnedMesh) Triangles() uint32
- func (g *GPUSkinnedMesh) Valid() bool
- func (g *GPUSkinnedMesh) VertexBuffer() *gpu.Buffer
- func (g *GPUSkinnedMesh) VertexCount() uint32
- type GPUSpotLight
- type GPUTerrainMaterial
- func NewGPUTerrainMaterial(cx *core.Scope, dev *gpu.Device, m TerrainMaterial, opts TerrainMaterialUpload) (*GPUTerrainMaterial, error)
- func (g *GPUTerrainMaterial) Bind(pass *gpu.RenderPass)
- func (g *GPUTerrainMaterial) BindGroup() *gpu.BindGroup
- func (g *GPUTerrainMaterial) ByteSize() uint64
- func (g *GPUTerrainMaterial) Close() error
- func (g *GPUTerrainMaterial) LayerCount() int
- func (g *GPUTerrainMaterial) Layout() *gpu.BindGroupLayout
- func (g *GPUTerrainMaterial) UniformBuffer() *gpu.Buffer
- func (g *GPUTerrainMaterial) UpdateSplatMaps(dev *gpu.Device, splat0, splat1 image.Image) error
- func (g *GPUTerrainMaterial) UpdateUniforms(dev *gpu.Device, m TerrainMaterial) error
- func (g *GPUTerrainMaterial) Valid() bool
- type GPUTexture
- func UploadLightmapRGBA16F(cx *core.Scope, dev *gpu.Device, hdr []math3d.Vec3, width, height int, opts TextureUpload) (*GPUTexture, error)
- func UploadTexture(cx *core.Scope, dev *gpu.Device, img image.Image, opts TextureUpload) (*GPUTexture, error)
- func UploadTexturePixels(cx *core.Scope, dev *gpu.Device, buf PixelBuffer, opts TextureUpload) (*GPUTexture, error)
- func (t *GPUTexture) ByteSize() uint64
- func (t *GPUTexture) Close() error
- func (t *GPUTexture) Format() gpu.TextureFormat
- func (t *GPUTexture) Height() uint32
- func (t *GPUTexture) MipLevels() uint32
- func (t *GPUTexture) SRGB() bool
- func (t *GPUTexture) Texture() *gpu.Texture
- func (t *GPUTexture) UpdateImage(dev *gpu.Device, img image.Image) error
- func (t *GPUTexture) UpdatePixels(dev *gpu.Device, buf PixelBuffer) error
- func (t *GPUTexture) Valid() bool
- func (t *GPUTexture) Width() uint32
- type GPUToonMaterial
- func NewGPUToonMaterial(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, mat ToonMaterial, opts ToonMaterialOptions) (*GPUToonMaterial, error)
- func (m *GPUToonMaterial) Bind(pass *gpu.RenderPass)
- func (m *GPUToonMaterial) BindAt(pass *gpu.RenderPass, group uint32)
- func (m *GPUToonMaterial) BindGroup() *gpu.BindGroup
- func (m *GPUToonMaterial) ByteSize() uint64
- func (m *GPUToonMaterial) Close() error
- func (m *GPUToonMaterial) HasOutline() bool
- func (m *GPUToonMaterial) Layout() *gpu.BindGroupLayout
- func (m *GPUToonMaterial) Material() ToonMaterial
- func (m *GPUToonMaterial) Update(dev *gpu.Device, mat ToonMaterial) error
- func (m *GPUToonMaterial) Valid() bool
- type GPUUnlitMaterial
- func NewGPUUnlitMaterial(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, m UnlitMaterial, opts MaterialUpload) (*GPUUnlitMaterial, error)
- func UploadGLTFUnlitMaterial(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, doc *gltf.Document, matIndex int, opts GLTFMaterialUpload) (*GPUUnlitMaterial, error)
- func (m *GPUUnlitMaterial) Bind(pass *gpu.RenderPass)
- func (m *GPUUnlitMaterial) BindAt(pass *gpu.RenderPass, group uint32)
- func (m *GPUUnlitMaterial) BindGroup() *gpu.BindGroup
- func (m *GPUUnlitMaterial) ByteSize() uint64
- func (m *GPUUnlitMaterial) Close() error
- func (m *GPUUnlitMaterial) Material() UnlitMaterial
- func (m *GPUUnlitMaterial) UniformBuffer() *gpu.Buffer
- func (m *GPUUnlitMaterial) Update(dev *gpu.Device, mat UnlitMaterial) error
- func (m *GPUUnlitMaterial) Valid() bool
- type Gizmo
- func (g Gizmo) AppendSegments(dst []GizmoSegment, origin math3d.Vec3, scale float32, mode GizmoMode) []GizmoSegment
- func (g Gizmo) DragRotate(origin math3d.Vec3, axis GizmoAxis, startRay, currentRay math3d.Ray, snap float32) float32
- func (g Gizmo) DragRotateQuat(origin math3d.Vec3, axis GizmoAxis, startRay, currentRay math3d.Ray, snap float32) math3d.Quat
- func (g Gizmo) DragScale(origin math3d.Vec3, axis GizmoAxis, startRay, currentRay math3d.Ray, snap float32) math3d.Vec3
- func (g Gizmo) DragTranslate(origin math3d.Vec3, axis GizmoAxis, startRay, currentRay math3d.Ray, snap float32) math3d.Vec3
- func (g Gizmo) DrawGizmo(d *core.Drawing, viewProj math3d.Mat4, viewport core.Bounds, origin math3d.Vec3, scale float32, mode GizmoMode, activeAxis GizmoAxis)
- func (g Gizmo) PickAxis(ray math3d.Ray, origin math3d.Vec3, scale float32, mode GizmoMode) (GizmoAxis, float32)
- func (g Gizmo) Segments(origin math3d.Vec3, scale float32, mode GizmoMode) []GizmoSegment
- type GizmoAxis
- type GizmoMode
- type GizmoSegment
- type HDRCubemap
- func CubemapFromHDR(r io.Reader, faceSize int) (*HDRCubemap, error)
- func CubemapFromHDREquirectangular(img *HDRImage, faceSize int) (*HDRCubemap, error)
- func CubemapFromHDRImage(img *HDRImage) (*HDRCubemap, error)
- func DecodeCubemapHDR(r io.Reader) (*HDRCubemap, error)
- func GradientSkyHDRCubemap(zenith, horizon, ground [3]float32, faceSize int) (*HDRCubemap, error)
- func HDRCubemapFromCubemap(cm *Cubemap) (*HDRCubemap, error)
- func NewHDRCubemap(size int) (*HDRCubemap, error)
- func PrefilterEnvironmentHDR(env *HDRCubemap, opts PrefilterOptions) (*HDRCubemap, error)
- func (c *HDRCubemap) At(face gpu.CubeFace, x, y int) [3]float32
- func (c *HDRCubemap) MipLevels() int
- func (c *HDRCubemap) Sample(dir math3d.Vec3) [3]float32
- func (c *HDRCubemap) SampleLOD(dir math3d.Vec3, lod float32) [3]float32
- func (c *HDRCubemap) Set(face gpu.CubeFace, x, y int, rgb [3]float32)
- func (c *HDRCubemap) Validate() error
- type HDRImage
- type HDRTarget
- func NewHDRTarget(cx *core.Scope, dev *gpu.Device, desc HDRTargetDesc) (*HDRTarget, error)
- func (t *HDRTarget) ByteSize() uint64
- func (t *HDRTarget) Close() error
- func (t *HDRTarget) ColorAttachment(clearColor core.Color) gpu.ColorAttachment
- func (t *HDRTarget) ColorAttachmentTexture() *gpu.Texture
- func (t *HDRTarget) ColorTexture() *gpu.Texture
- func (t *HDRTarget) DepthFormat() gpu.TextureFormat
- func (t *HDRTarget) DepthTexture() *gpu.Texture
- func (t *HDRTarget) Format() gpu.TextureFormat
- func (t *HDRTarget) Height() uint32
- func (t *HDRTarget) IsHDR() bool
- func (t *HDRTarget) RenderPassDesc(clearColor core.Color, clearDepth float32) gpu.RenderPassDesc
- func (t *HDRTarget) RenderTarget() *gpu.RenderTarget
- func (t *HDRTarget) Resize(dev *gpu.Device, width, height uint32) error
- func (t *HDRTarget) SampleCount() int
- func (t *HDRTarget) Valid() bool
- func (t *HDRTarget) Width() uint32
- type HDRTargetDesc
- type IBLBufferOptions
- type IBLUniform
- type InstanceBatch
- type IrradianceSH
- func ComputeIrradianceSH(env *Cubemap) (IrradianceSH, error)
- func ComputeIrradianceSHFromFunc(size int, sample func(dir math3d.Vec3) [3]float32) (IrradianceSH, error)
- func ComputeIrradianceSHHDR(env *HDRCubemap) (IrradianceSH, error)
- func ProjectDirectionIrradianceSH(dir math3d.Vec3, radiance [3]float32) IrradianceSH
- func (sh IrradianceSH) Add(other IrradianceSH) IrradianceSH
- func (sh IrradianceSH) Evaluate(normal math3d.Vec3) [3]float32
- func (sh IrradianceSH) Lerp(other IrradianceSH, t float32) IrradianceSH
- func (sh IrradianceSH) Scale(k float32) IrradianceSH
- func (sh IrradianceSH) ToCubemap(faceSize int) (*Cubemap, error)
- type KTX2Upload
- type LODLevel
- type LayeredDrawItem
- type LightBufferOptions
- type LightProbe
- type LightProbeGrid
- func LoadLightProbeGridFS(fsys fs.FS, name string) (*LightProbeGrid, error)
- func NewLightProbeGrid(bounds math3d.AABB, nx, ny, nz int) (*LightProbeGrid, error)
- func (g *LightProbeGrid) At(ix, iy, iz int) IrradianceSH
- func (g *LightProbeGrid) Bake(size int, sample func(pos, dir math3d.Vec3) [3]float32) error
- func (g *LightProbeGrid) ProbePosition(ix, iy, iz int) math3d.Vec3
- func (g *LightProbeGrid) Sample(worldPos math3d.Vec3) IrradianceSH
- func (g *LightProbeGrid) Set(ix, iy, iz int, sh IrradianceSH)
- func (g *LightProbeGrid) Validate() error
- type LightProbeGridDoc
- type LightProbeSHDoc
- type LightProbeVolume
- type LightRig
- type LightUniforms
- type LightVisibility
- type LightmapEncoding
- type LightmapMaterial
- type LightmapMesh
- func LightmapMeshFromAttributes(positions, normals []math3d.Vec3, uv0, uv1 []math3d.Vec2, indices []uint32) LightmapMesh
- func LightmapMeshFromGLTF(doc *gltf.Document, prim gltf.Primitive) (LightmapMesh, error)
- func LightmapMeshFromVertices(vertices []LightmapVertex, indices []uint32) LightmapMesh
- func (m LightmapMesh) AppendIndexData(dst []byte) []byte
- func (m LightmapMesh) AppendVertexData(dst []byte) []byte
- func (m LightmapMesh) Bounds() math3d.AABB
- func (m LightmapMesh) HasUV1() bool
- func (m LightmapMesh) IndexDataSize() int
- func (m LightmapMesh) IndexFormat() gpu.IndexFormat
- func (m LightmapMesh) Indexed() bool
- func (m LightmapMesh) Validate() error
- func (m LightmapMesh) VertexCount() int
- func (m LightmapMesh) VertexDataSize() int
- func (m LightmapMesh) Vertices() []LightmapVertex
- type LightmapRenderer
- func NewLightmapRenderer(cx *core.Scope, dev *gpu.Device, camLayout *gpu.BindGroupLayout, opts LightmapRendererOptions) (*LightmapRenderer, error)
- func (r *LightmapRenderer) BeginFrame()
- func (r *LightmapRenderer) Close() error
- func (r *LightmapRenderer) Draw(pass *gpu.RenderPass, cam *CameraBuffer, mesh *GPULightmapMesh, model math3d.Mat4, mat LightmapMaterial) error
- func (r *LightmapRenderer) Pipeline() *gpu.Pipeline
- func (r *LightmapRenderer) Valid() bool
- type LightmapRendererOptions
- type LightmapVertex
- type LitPBRPipelineOptions
- type LocalShadowFilter
- type MSAATarget
- func NewMSAATarget(cx *core.Scope, dev *gpu.Device, desc MSAATargetDesc) (*MSAATarget, error)
- func (t *MSAATarget) Close() error
- func (t *MSAATarget) ColorAttachment(clearColor core.Color) (gpu.ColorAttachment, error)
- func (t *MSAATarget) ColorFormat() gpu.TextureFormat
- func (t *MSAATarget) ColorTexture() *gpu.Texture
- func (t *MSAATarget) DepthFormat() gpu.TextureFormat
- func (t *MSAATarget) DepthStencilAttachment(clearDepth float32) *gpu.DepthStencilAttachment
- func (t *MSAATarget) DepthTexture() *gpu.Texture
- func (t *MSAATarget) Height() uint32
- func (t *MSAATarget) OutputTexture() *gpu.Texture
- func (t *MSAATarget) RenderPassDesc(clearColor core.Color, clearDepth float32) (gpu.RenderPassDesc, error)
- func (t *MSAATarget) RenderTarget() *gpu.RenderTarget
- func (t *MSAATarget) Resize(width, height uint32) error
- func (t *MSAATarget) ResolveTexture() *gpu.Texture
- func (t *MSAATarget) Retained() bool
- func (t *MSAATarget) SampleCount() int
- func (t *MSAATarget) SetDevice(dev *gpu.Device)
- func (t *MSAATarget) Valid() bool
- func (t *MSAATarget) Width() uint32
- type MSAATargetDesc
- type Material
- func DefaultMaterial() Material
- func (m Material) AppendUniformData(dst []byte) []byte
- func (m Material) EffectiveIOR() float32
- func (m Material) ExtendedUniforms() ExtendedMaterialUniforms
- func (m Material) Uniforms() MaterialUniforms
- func (m Material) UsesExtensions() bool
- func (m Material) Validate() error
- type MaterialDefaults
- func NewMaterialDefaults(cx *core.Scope, dev *gpu.Device, opts MaterialDefaultsOptions) (*MaterialDefaults, error)
- func (d *MaterialDefaults) Black() *GPUTexture
- func (d *MaterialDefaults) ByteSize() uint64
- func (d *MaterialDefaults) Close() error
- func (d *MaterialDefaults) FlatNormal() *GPUTexture
- func (d *MaterialDefaults) Layout() *gpu.BindGroupLayout
- func (d *MaterialDefaults) Sampler() *GPUSampler
- func (d *MaterialDefaults) UnlitLayout() *gpu.BindGroupLayout
- func (d *MaterialDefaults) Valid() bool
- func (d *MaterialDefaults) WhiteLinear() *GPUTexture
- func (d *MaterialDefaults) WhiteSRGB() *GPUTexture
- type MaterialDefaultsOptions
- type MaterialEvalInput
- type MaterialEvalResult
- type MaterialIBLPipelineOptions
- type MaterialLight
- type MaterialPipelineOptions
- type MaterialUniforms
- type MaterialUpload
- type Mesh
- func MeshFromTerrainMesh(tm world3d.TerrainMesh) Mesh
- func SmoothOutlineNormals(m Mesh) (Mesh, error)
- func (m Mesh) AppendIndexData(dst []byte) []byte
- func (m Mesh) AppendVertexData(dst []byte) []byte
- func (m Mesh) Bounds() math3d.AABB
- func (m Mesh) IndexDataSize() int
- func (m Mesh) IndexFormat() gpu.IndexFormat
- func (m Mesh) Indexed() bool
- func (m Mesh) Validate() error
- func (m Mesh) VertexCount() int
- func (m Mesh) VertexDataSize() int
- type MeshUpload
- type MetallicRoughnessMaterial
- type MorphMesh
- type MorphTarget
- type Occluder
- type OcclusionBuffer
- func NewOcclusionBuffer(width, height int) *OcclusionBuffer
- func (b *OcclusionBuffer) BuildPyramid()
- func (b *OcclusionBuffer) Clear()
- func (b *OcclusionBuffer) DepthAt(x, y int) float32
- func (b *OcclusionBuffer) Height() int
- func (b *OcclusionBuffer) Levels() int
- func (b *OcclusionBuffer) Rasterize(viewProj math3d.Mat4, occluders ...Occluder)
- func (b *OcclusionBuffer) TestAABB(bounds math3d.AABB, viewProj math3d.Mat4) bool
- func (b *OcclusionBuffer) Width() int
- type PBRDrawBuffer
- func NewPBRDrawBuffer(cx *core.Scope, dev *gpu.Device, sharedLayout *gpu.BindGroupLayout, initial PBRDrawUniform, retained bool) (*PBRDrawBuffer, error)
- func (b *PBRDrawBuffer) BindGroup() *gpu.BindGroup
- func (b *PBRDrawBuffer) Close() error
- func (b *PBRDrawBuffer) Layout() *gpu.BindGroupLayout
- func (b *PBRDrawBuffer) Valid() bool
- func (b *PBRDrawBuffer) Write(dev *gpu.Device, u PBRDrawUniform)
- type PBRDrawUniform
- type PBRLightmap
- type PBRLightmapEvalInput
- type PBRLightmapEvalResult
- type PBRLightmapOptions
- type PBRLightmapPipelineOptions
- type PBRMaterial
- type PixelBuffer
- type PixelViewport
- type PointLight
- type PointShadowConfig
- type PointShadowMap
- func NewPointShadowMap(cx *core.Scope, dev *gpu.Device, cfg PointShadowConfig) (*PointShadowMap, error)
- func (p *PointShadowMap) AtlasHeight() uint32
- func (p *PointShadowMap) AtlasWidth() uint32
- func (p *PointShadowMap) BeginFacePass(dev *gpu.Device, target ShadowPassTarget, face gpu.CubeFace) *gpu.RenderPass
- func (p *PointShadowMap) BindGroup() *gpu.BindGroup
- func (p *PointShadowMap) ByteSize() uint64
- func (p *PointShadowMap) Close() error
- func (p *PointShadowMap) Config() PointShadowConfig
- func (p *PointShadowMap) DepthTexture() *gpu.Texture
- func (p *PointShadowMap) DrawCaster(pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) bool
- func (p *PointShadowMap) FaceViewProj(face gpu.CubeFace) math3d.Mat4
- func (p *PointShadowMap) FaceViewport(face gpu.CubeFace) (x, y, width, height uint32)
- func (p *PointShadowMap) Layout() *gpu.BindGroupLayout
- func (p *PointShadowMap) MaxCasters() uint32
- func (p *PointShadowMap) RenderTarget() *gpu.RenderTarget
- func (p *PointShadowMap) Sampler() *gpu.Sampler
- func (p *PointShadowMap) Uniforms() PointShadowUniform
- func (p *PointShadowMap) Update(dev *gpu.Device, light PointLight) error
- func (p *PointShadowMap) Valid() bool
- type PointShadowUniform
- type PostStack3D
- func NewPostStack3D(cx *core.Scope, dev *gpu.Device, opts PostStack3DOptions) (*PostStack3D, error)
- func (s *PostStack3D) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error
- func (s *PostStack3D) ApplyScene(dev *gpu.Device, rec RenderPassRecorder, dstColor *gpu.Texture) error
- func (s *PostStack3D) BeginScenePass(rec RenderPassRecorder, clearColor core.Color) *gpu.RenderPass
- func (s *PostStack3D) Bloom() *BloomPass
- func (s *PostStack3D) Close() error
- func (s *PostStack3D) ColorFormat() gpu.TextureFormat
- func (s *PostStack3D) DepthFormat() gpu.TextureFormat
- func (s *PostStack3D) DepthOfField() *DepthOfFieldPass
- func (s *PostStack3D) Height() uint32
- func (s *PostStack3D) OutputFormat() gpu.TextureFormat
- func (s *PostStack3D) Resize(dev *gpu.Device, width, height uint32) error
- func (s *PostStack3D) SSAO() *SSAOPass
- func (s *PostStack3D) SceneTarget() *gpu.RenderTarget
- func (s *PostStack3D) SetBloom(enabled bool, cfg BloomConfig) error
- func (s *PostStack3D) SetCamera(cam *scene3d.Camera) error
- func (s *PostStack3D) SetDepthOfField(enabled bool, cfg DepthOfFieldConfig) error
- func (s *PostStack3D) SetSSAO(enabled bool, cfg SSAOConfig) error
- func (s *PostStack3D) Valid() bool
- func (s *PostStack3D) Width() uint32
- type PostStack3DOptions
- type PrefilterOptions
- type ProbeBakeOptions
- type ProbeBlendResult
- type ProbeCounts
- type ProbeIBLBufferOptions
- type ProbeIBLPipelineOptions
- type ProbeIBLUniform
- type ProbeVec3
- type Queue
- type RawBufferUpload
- type RawTextureUpload
- type ReflectionProbe
- type ReflectionProbeSet
- type RenderPassRecorder
- type RenderPassStarter
- type RenderPlan
- type RenderStats
- type RenderTexture
- func NewRenderTexture(cx *core.Scope, dev *gpu.Device, desc RenderTextureDesc) (*RenderTexture, error)
- func (rt *RenderTexture) Aspect() float32
- func (rt *RenderTexture) BeginFramePass(frame *gpu.Frame, clearColor core.Color) *gpu.RenderPass
- func (rt *RenderTexture) BeginPass(enc *gpu.Encoder, clearColor core.Color) *gpu.RenderPass
- func (rt *RenderTexture) ByteSize() uint64
- func (rt *RenderTexture) Close() error
- func (rt *RenderTexture) ColorFormat() gpu.TextureFormat
- func (rt *RenderTexture) ColorTexture() *gpu.Texture
- func (rt *RenderTexture) DepthFormat() gpu.TextureFormat
- func (rt *RenderTexture) DepthTexture() *gpu.Texture
- func (rt *RenderTexture) GPUTexture() *GPUTexture
- func (rt *RenderTexture) Generation() uint64
- func (rt *RenderTexture) Height() uint32
- func (rt *RenderTexture) PassDesc(label string, clearColor core.Color, clearDepth float32) gpu.RenderPassDesc
- func (rt *RenderTexture) Resize(dev *gpu.Device, width, height uint32) (bool, error)
- func (rt *RenderTexture) SampleCount() int
- func (rt *RenderTexture) Target() *gpu.RenderTarget
- func (rt *RenderTexture) Texture() *gpu.Texture
- func (rt *RenderTexture) Valid() bool
- func (rt *RenderTexture) Width() uint32
- type RenderTextureDesc
- type ResolvedDraw
- type SSAOConfig
- type SSAOPass
- func NewSSAOPass(cx *core.Scope, dev *gpu.Device, opts SSAOPassOptions) (*SSAOPass, error)
- func (p *SSAOPass) AOTexture() *gpu.Texture
- func (p *SSAOPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) error
- func (p *SSAOPass) Close() error
- func (p *SSAOPass) ComputeAO(dev *gpu.Device, rec RenderPassRecorder, depthTex *gpu.Texture) (*gpu.Texture, error)
- func (p *SSAOPass) Config() SSAOConfig
- func (p *SSAOPass) Height() uint32
- func (p *SSAOPass) Resize(dev *gpu.Device, width, height uint32) error
- func (p *SSAOPass) SetConfig(cfg SSAOConfig) error
- func (p *SSAOPass) Valid() bool
- func (p *SSAOPass) Width() uint32
- type SSAOPassOptions
- type SamplerOptions
- func KTX2Sampler(data []byte, base SamplerOptions) (SamplerOptions, error)
- func SamplerLinearClamp() SamplerOptions
- func SamplerLinearMirror() SamplerOptions
- func SamplerLinearRepeat() SamplerOptions
- func SamplerNearestClamp() SamplerOptions
- func SamplerNearestRepeat() SamplerOptions
- func SamplerOptionsFromGLTF(s gltf.Sampler) (opts SamplerOptions, wantMipmaps bool, err error)
- func (o SamplerOptions) Desc() gpu.SamplerDesc
- func (o SamplerOptions) Validate() error
- type ShaderLanguage
- type ShaderParamDesc
- type ShaderParamKind
- type ShadowDepthGrid
- type ShadowFilter
- type ShadowMapOptions
- type ShadowPassTarget
- type ShadowUniforms
- type SkinPaletteOptions
- type SkinnedMesh
- func SkinnedMeshFromGLTF(prim gltf.Primitive, skin gltf.Skin) (SkinnedMesh, error)
- func SkinnedMeshesFromGLTFNode(doc *gltf.Document, nodeIndex int) ([]SkinnedMesh, error)
- func (m SkinnedMesh) AppendIndexData(dst []byte) []byte
- func (m SkinnedMesh) AppendVertexData(dst []byte) []byte
- func (m SkinnedMesh) Bounds() math3d.AABB
- func (m SkinnedMesh) IndexDataSize() int
- func (m SkinnedMesh) IndexFormat() gpu.IndexFormat
- func (m SkinnedMesh) Indexed() bool
- func (m SkinnedMesh) Validate() error
- func (m SkinnedMesh) VertexCount() int
- func (m SkinnedMesh) VertexDataSize() int
- type SkinnedMeshPipelineOptions
- type SkyboxPipeline
- func NewSkyboxPipeline(cx *core.Scope, dev *gpu.Device, desc SkyboxPipelineDesc) (*SkyboxPipeline, error)
- func (s *SkyboxPipeline) BindCubemap(cx *core.Scope, cube *GPUCubemap) (*gpu.BindGroup, error)
- func (s *SkyboxPipeline) Close() error
- func (s *SkyboxPipeline) Draw(pass *gpu.RenderPass, group *gpu.BindGroup)
- func (s *SkyboxPipeline) Layout() *gpu.BindGroupLayout
- func (s *SkyboxPipeline) Pipeline() *gpu.Pipeline
- func (s *SkyboxPipeline) SetDevice(dev *gpu.Device)
- func (s *SkyboxPipeline) Valid() bool
- func (s *SkyboxPipeline) Write(u SkyboxUniform)
- func (s *SkyboxPipeline) WriteCamera(cam *scene3d.Camera)
- type SkyboxPipelineDesc
- type SkyboxUniform
- type SpotLight
- type SpotShadowConfig
- type SpotShadowMap
- func NewSpotShadowMap(cx *core.Scope, dev *gpu.Device, cfg SpotShadowConfig) (*SpotShadowMap, error)
- func (s *SpotShadowMap) BeginShadowPass(dev *gpu.Device, target ShadowPassTarget) *gpu.RenderPass
- func (s *SpotShadowMap) BindGroup() *gpu.BindGroup
- func (s *SpotShadowMap) ByteSize() uint64
- func (s *SpotShadowMap) Close() error
- func (s *SpotShadowMap) Config() SpotShadowConfig
- func (s *SpotShadowMap) DepthTexture() *gpu.Texture
- func (s *SpotShadowMap) DrawCaster(pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) bool
- func (s *SpotShadowMap) Layout() *gpu.BindGroupLayout
- func (s *SpotShadowMap) MaxCasters() uint32
- func (s *SpotShadowMap) RenderTarget() *gpu.RenderTarget
- func (s *SpotShadowMap) Sampler() *gpu.Sampler
- func (s *SpotShadowMap) Uniforms() SpotShadowUniform
- func (s *SpotShadowMap) Update(dev *gpu.Device, light SpotLight) error
- func (s *SpotShadowMap) Valid() bool
- type SpotShadowUniform
- type SurfaceDesc
- type TerrainEvalInput
- type TerrainEvalLayerSample
- type TerrainEvalResult
- type TerrainLayer
- type TerrainMaterial
- type TerrainMaterialUpload
- type TerrainPipelineOptions
- type TerrainTriplanar
- type TextureMipData
- type TextureUpload
- type ToneMapOperator
- type ToneMapOptions
- type ToneMapPass
- func NewToneMapPass(cx *core.Scope, dev *gpu.Device, desc ToneMapPassDesc) (*ToneMapPass, error)
- func (p *ToneMapPass) BindGroupFor(dev *gpu.Device, src *gpu.Texture) (*gpu.BindGroup, error)
- func (p *ToneMapPass) Close() error
- func (p *ToneMapPass) Draw(pass *gpu.RenderPass, dev *gpu.Device, src *gpu.Texture, opts ToneMapOptions) error
- func (p *ToneMapPass) DrawDynamicResolution(pass *gpu.RenderPass, dev *gpu.Device, src *DynamicResolutionTarget, opts ToneMapOptions) error
- func (p *ToneMapPass) DrawTarget(pass *gpu.RenderPass, dev *gpu.Device, src *HDRTarget, opts ToneMapOptions) error
- func (p *ToneMapPass) Layout() *gpu.BindGroupLayout
- func (p *ToneMapPass) Pipeline() *gpu.Pipeline
- func (p *ToneMapPass) Sampler() *gpu.Sampler
- func (p *ToneMapPass) SetDevice(dev *gpu.Device)
- func (p *ToneMapPass) TargetFormat() gpu.TextureFormat
- func (p *ToneMapPass) UniformBuffer() *gpu.Buffer
- func (p *ToneMapPass) Valid() bool
- func (p *ToneMapPass) Write(dev *gpu.Device, opts ToneMapOptions)
- type ToneMapPassDesc
- type ToonDraw
- type ToonEvalInput
- type ToonLight
- type ToonMaterial
- type ToonMaterialOptions
- type ToonPipelineOptions
- type ToonRenderer
- func NewToonRenderer(cx *core.Scope, dev *gpu.Device, opts ToonRendererOptions) (*ToonRenderer, error)
- func (r *ToonRenderer) Begin()
- func (r *ToonRenderer) Close() error
- func (r *ToonRenderer) Draw(dev *gpu.Device, pass *gpu.RenderPass, camGroup *gpu.BindGroup, light ToonLight, draws ...ToonDraw) error
- func (r *ToonRenderer) MaterialLayout() *gpu.BindGroupLayout
- func (r *ToonRenderer) NewMaterial(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, mat ToonMaterial, label string) (*GPUToonMaterial, error)
- func (r *ToonRenderer) OutlinePipeline() *gpu.Pipeline
- func (r *ToonRenderer) ToonPipeline() *gpu.Pipeline
- func (r *ToonRenderer) Valid() bool
- type ToonRendererOptions
- type ToonSceneUniform
- type Trail
- func NewTrail(cfg TrailConfig) *Trail
- func (t *Trail) AddPoint(p math3d.Vec3)
- func (t *Trail) Bounds() math3d.AABB
- func (t *Trail) Build(cam CameraBasis) []TrailVertex
- func (t *Trail) Clear()
- func (t *Trail) Config() TrailConfig
- func (t *Trail) Draw(d *core.Drawing, cam CameraBasis, viewProj math3d.Mat4, viewport core.Bounds) int
- func (t *Trail) DrawItem(template DrawItem) DrawItem
- func (t *Trail) EvaluateAt(u float32) (width float32, color core.Color)
- func (t *Trail) PointCount() int
- func (t *Trail) Points() []TrailPoint
- func (t *Trail) SetConfig(cfg TrailConfig)
- func (t *Trail) Update(dt time.Duration)
- type TrailConfig
- type TrailPoint
- type TrailVertex
- type TransmissionBackground
- func NewTransmissionBackground(cx *core.Scope, dev *gpu.Device, opts TransmissionBackgroundOptions) (*TransmissionBackground, error)
- func (tb *TransmissionBackground) Bind(pass *gpu.RenderPass)
- func (tb *TransmissionBackground) BindAt(pass *gpu.RenderPass, group uint32)
- func (tb *TransmissionBackground) BindGroup() *gpu.BindGroup
- func (tb *TransmissionBackground) Close() error
- func (tb *TransmissionBackground) Layout() *gpu.BindGroupLayout
- func (tb *TransmissionBackground) SetDynamicResolution(dev *gpu.Device, target *DynamicResolutionTarget, snapshot *gpu.Texture, viewportW, viewportH int, srgb bool) error
- func (tb *TransmissionBackground) SetTexture(dev *gpu.Device, tex *gpu.Texture, srgb bool) error
- func (tb *TransmissionBackground) SetViewport(dev *gpu.Device, tex *gpu.Texture, viewportW, viewportH, activeW, activeH, texW, texH int, srgb bool) error
- func (tb *TransmissionBackground) Valid() bool
- type TransmissionBackgroundOptions
- type UVTransform
- type UnlitMaterial
- type UnlitPipelineOptions
- type UnlitSample
- type UploadFrameStats
- type UploadHandle
- type UploadPriority
- type UploadState
- type Uploader
- func NewUploader(cx *core.Scope, dev *gpu.Device, opts UploaderOptions) *Uploader
- func (u *Uploader) BytesPerFrame() int
- func (u *Uploader) ChunkBytes() int
- func (u *Uploader) Close() error
- func (u *Uploader) InFlightDecodes() int
- func (u *Uploader) Pending() int
- func (u *Uploader) QueueMesh(ctx context.Context, priority UploadPriority, decode func(context.Context) (Mesh, error), onReady func(*GPUMesh, error), opts MeshUpload) *UploadHandle
- func (u *Uploader) QueueRawBuffer(ctx context.Context, priority UploadPriority, decode func(context.Context) (RawBufferUpload, error), onReady func(*gpu.Buffer, error)) *UploadHandle
- func (u *Uploader) QueueRawTexture(ctx context.Context, priority UploadPriority, decode func(context.Context) (RawTextureUpload, error), onReady func(*gpu.Texture, error)) *UploadHandle
- func (u *Uploader) QueueTexture(ctx context.Context, priority UploadPriority, decode func(context.Context) (image.Image, error), onReady func(*GPUTexture, error), opts TextureUpload) *UploadHandle
- func (u *Uploader) QueueTexturePixels(ctx context.Context, priority UploadPriority, decode func(context.Context) (PixelBuffer, error), onReady func(*GPUTexture, error), opts TextureUpload) *UploadHandle
- func (u *Uploader) SetBytesPerFrame(n int)
- func (u *Uploader) SetChunkBytes(n int)
- func (u *Uploader) Step() UploadFrameStats
- type UploaderOptions
- type ViewportContext
- type ViewportRect
- func FullViewport() ViewportRect
- func SplitScreenHorizontal(count int) []ViewportRect
- func SplitScreenQuad() [4]ViewportRect
- func SplitScreenSideBySide(count int) []ViewportRect
- func SplitScreenStacked(count int) []ViewportRect
- func SplitScreenVertical(count int) []ViewportRect
- func ViewportFromPixels(x, y, width, height float32, targetWidth, targetHeight int) ViewportRect
- func (r ViewportRect) Aspect(targetWidth, targetHeight int) float32
- func (r ViewportRect) Normalized() ViewportRect
- func (r ViewportRect) Resolve(targetWidth, targetHeight int) (PixelViewport, bool)
- func (r ViewportRect) Validate() error
- type ViewportRenderer
- func NewViewportRenderer(cx *core.Scope, dev *gpu.Device) (*ViewportRenderer, error)
- func NewViewportRendererWithLayout(cx *core.Scope, dev *gpu.Device, camLayout *gpu.BindGroupLayout) (*ViewportRenderer, error)
- func (r *ViewportRenderer) CameraLayout() *gpu.BindGroupLayout
- func (r *ViewportRenderer) Close() error
- func (r *ViewportRenderer) RenderEncoder(dev *gpu.Device, enc *gpu.Encoder, surface SurfaceDesc, views []CameraView, draw func(ViewportContext)) error
- func (r *ViewportRenderer) RenderFrame(frame *gpu.Frame, surface SurfaceDesc, views []CameraView, draw func(ViewportContext)) error
- func (r *ViewportRenderer) Valid() bool
定数
const (
// DefaultClusterTilesX is the default number of horizontal screen-space tiles.
DefaultClusterTilesX = 16
// DefaultClusterTilesY is the default number of vertical screen-space tiles.
DefaultClusterTilesY = 9
// DefaultClusterSlicesZ is the default number of logarithmic view-space depth slices.
DefaultClusterSlicesZ = 24
// DefaultClusterMaxLights is the default storage-buffer light capacity in clustered mode.
DefaultClusterMaxLights = 512
// DefaultMaxLightsPerCluster is the default maximum number of lights recorded per cluster cell.
DefaultMaxLightsPerCluster = 64
// DefaultFallbackMaxLights is the default uniform-buffer light cap for mobile / WebGL 2 / GLES 3.0 fallback.
DefaultFallbackMaxLights = 16
// MaxClusterSlicesZ is the maximum depth slice count supported by the uniform split-depth table (65 slice boundaries packed into 17 vec4<f32> entries).
MaxClusterSlicesZ = 64
// MaxFallbackLights is the uniform-buffer array capacity of [ClusteredFallbackWGSL].
MaxFallbackLights = 16
// MaxClusterLights is the largest [ClusterConfig.MaxLights] accepted.
MaxClusterLights = 1 << 16
// MaxClusterIndexEntries bounds TilesX * TilesY * SlicesZ * MaxLightsPerCluster, the number of light-index slots [ClusterGrid] preallocates (64 MiB of uint32 indices).
MaxClusterIndexEntries = 1 << 24
// ClusterLightGPUSize is the byte size of one GPU light record (4 vec4<f32>, 16-byte aligned in both std140 and std430).
ClusterLightGPUSize = 64
// ClusterParamsUniformSize is the byte size of the clustered-path ClusterParams uniform block at [LightGroup] binding 1: grid_info (16) + viewport_depth (16) + 17*vec4 slice_depths (272) = 304 bytes.
ClusterParamsUniformSize = 304
// ClusterCellGPUSize is the byte size of one cluster cell offset/count entry (vec4<u32>, 16-byte aligned across all backends).
ClusterCellGPUSize = 16
// ClusteredFallbackUniformSize is the byte size of the fallback uniform block at [LightGroup] binding 1: info (16) + 16*ClusterLightGPUSize (1024) = 1040 bytes.
ClusteredFallbackUniformSize = 16 + MaxFallbackLights*ClusterLightGPUSize
// ClusterRangeCutoff is the radiance below which [ClusterLightFromPoint] and [ClusterLightFromSpot] treat a light with Range 0 (unbounded, the glTF default) as finished: the derived range is sqrt(Intensity * max(Color) / ClusterRangeCutoff).
ClusterRangeCutoff = 1.0 / 256
)Defaults and buffer layout constants for clustered forward lighting.
const (
// MaxCascades is the maximum number of shadow cascades supported by [CascadedShadowMap], [CSMFrame], and [CSMWGSL].
MaxCascades = 4
// CSMGroup is the bind group index [CSMWGSL] and [LitPBRCSMWGSL] use for the cascaded shadow map (uniform buffer at binding 0, depth atlas at binding 1, comparison sampler at binding 2). It is [ShadowGroup] (3), after [CameraGroup], [LightGroup] and [PBRDrawGroup], so a lit PBR pipeline takes the cascaded shadow map instead of the single directional shadow map, fog, IBL or skinning. Custom shaders that need group 3 for something else place the bindings elsewhere with [CSMWGSLForGroup].
CSMGroup = ShadowGroup
// CSMUniformSize is the byte size of the CSMUniforms block encoded by [CSMFrame.EncodeUniforms] and declared by [CSMWGSL]: four mat4x4<f32> matrices (256 bytes) plus ten vec4<f32> vectors (160 bytes).
CSMUniformSize = 4*64 + 10*16
// DefaultCSMCascadeCount is the default number of cascades used when [CSMConfig.CascadeCount] is zero.
DefaultCSMCascadeCount = 4
// DefaultCSMResolution is the default per-cascade shadow-map resolution in texels used when [CSMConfig.Resolution] is zero.
DefaultCSMResolution = 1024
// DefaultCSMSplitLambda is the practical split blend factor returned by [DefaultCSMConfig], blending 75% logarithmic and 25% uniform splits.
DefaultCSMSplitLambda float32 = 0.75
// DefaultCSMDepthBias is the constant receiver depth bias returned by [DefaultCSMConfig].
DefaultCSMDepthBias float32 = 0.0015
// DefaultCSMNormalBias is the world-space normal offset bias (for cascade 0, scaled proportionally to texel size for farther cascades) returned by [DefaultCSMConfig].
DefaultCSMNormalBias float32 = 0.02
// DefaultCSMCascadeBlendRange is the fractional cascade transition zone ([0, 0.5] of each cascade's depth span) returned by [DefaultCSMConfig].
DefaultCSMCascadeBlendRange float32 = 0.1
// DefaultCSMCasterPadding is the distance in world units pulled back toward the light source when fitting cascade orthographic near planes, so off-frustum casters behind the camera still cast shadows into view.
DefaultCSMCasterPadding float32 = 25.0
// DefaultCSMMaxCasters is the default per-frame dynamic caster transform capacity allocated by [NewCascadedShadowMap] when [CSMConfig.MaxCasters] is 0.
DefaultCSMMaxCasters = 256
)const (
// DefaultDynamicResolutionTargetFrameTime is the 60 FPS frame budget (~16.67ms).
DefaultDynamicResolutionTargetFrameTime = time.Second / 60
// DefaultDynamicResolutionMinScale is the default lower bound on linear scale (50% per axis, 25% pixels).
DefaultDynamicResolutionMinScale float32 = 0.5
// DefaultDynamicResolutionMaxScale is the default upper bound on linear scale (100% native).
DefaultDynamicResolutionMaxScale float32 = 1.0
// DefaultDynamicResolutionDeadband is the ±5% hysteresis deadband around TargetFrameTime.
DefaultDynamicResolutionDeadband float32 = 0.05
// DefaultDynamicResolutionSmoothingAlpha is the EMA smoothing factor for GPU frame times.
DefaultDynamicResolutionSmoothingAlpha float32 = 0.25
// DefaultDynamicResolutionStepDown is the maximum per-step scale drop under GPU overload.
DefaultDynamicResolutionStepDown float32 = 0.12
// DefaultDynamicResolutionStepUp is the maximum per-step scale recovery under GPU headroom.
DefaultDynamicResolutionStepUp float32 = 0.04
// DefaultDynamicResolutionCooldownDown is the minimum frame gap between consecutive scale-down steps.
DefaultDynamicResolutionCooldownDown = 2
// DefaultDynamicResolutionCooldownUp is the minimum consecutive headroom frames before stepping up.
DefaultDynamicResolutionCooldownUp = 12
// DefaultDynamicResolutionHitchLimit discards GPU frame times above 250ms as hitches.
DefaultDynamicResolutionHitchLimit = 250 * time.Millisecond
// DefaultDynamicResolutionAlignment rounds scaled dimensions to even pixel counts.
DefaultDynamicResolutionAlignment = 2
// DefaultDynamicResolutionSharpness is the default CAS sharpening strength for DynamicResolutionSharpen.
DefaultDynamicResolutionSharpness float32 = 0.25
)Default values applied by DefaultDynamicResolutionConfig and when a zero field is supplied to NewDynamicResolutionScaler.
const (
// FogGroup is the bind group index [LitPBRFogWGSL] and [FogBindingWGSL] reserve for the fog uniform block, after [CameraGroup], [LightGroup] and [PBRDrawGroup]. [GPUFogBuffer.Bind] binds at this slot.
FogGroup = 3
// MaterialFogGroup is the bind group index [MaterialFogWGSL] and [MaterialFogBindingWGSL] reserve for the fog uniform block, after [CameraGroup] and [MaterialGroup]. Bind [GPUFogBuffer.BindGroup] here when drawing with a fogged [NewMaterialPipeline].
MaterialFogGroup = 2
// FogUniformSize is the byte size of [FogUniforms] as written by [AppendFogUniforms] and declared by [FogWGSL] (three vec4<f32> blocks).
FogUniformSize = 48
)Bind group slots and byte size for GPU fog uniforms.
const (
// LightGroup is the bind group index the 3D shaders in this repository reserve for scene lights:
// [GPULightBuffer.BindGroup] goes in this slot of lit 3D pipelines' Layouts, and [LightWGSL] declares it there.
LightGroup = 1
// PBRDrawGroup is the bind group index [LitPBRWGSL] reserves for the per-draw transform and
// [PBRMaterial] uniform block ([PBRDrawBuffer.BindGroup]).
PBRDrawGroup = 2
// MaxDirectionalLights is the maximum number of directional lights a [LightRig] encodes into the GPU uniform block.
MaxDirectionalLights = 4
// MaxPointLights is the maximum number of point lights a [LightRig] encodes into the GPU uniform block.
MaxPointLights = 16
// LightUniformSize is the byte size of the light uniform block that [LightRig.AppendUniformData] and [LightUniforms.Encode] write and [LightWGSL] declares: ambient (16) + counts (16) + MaxDirectionalLights*32 + MaxPointLights*32 + [MaxSpotLights]*48 = 1056 bytes.
LightUniformSize = 16 + 16 + MaxDirectionalLights*32 + MaxPointLights*32 + MaxSpotLights*48
// PBRDrawUniformSize is the byte size of the per-draw PBR uniform block that [PBRDrawUniform.Encode]
// writes and [LitPBRWGSL] declares: model (64) + normal_matrix (64) + base_color (16) +
// pbr_params (16) + emissive (16) = 176 bytes.
PBRDrawUniformSize = 64 + 64 + 16 + 16 + 16
)const (
// LightmapVertexStride is the byte size of one interleaved lightmapped vertex: position (12 bytes), normal (12 bytes), UV0 (8 bytes), UV1 (8 bytes).
LightmapVertexStride = 40
// LightmapPositionOffset is the byte offset of the float32x3 position inside a vertex.
LightmapPositionOffset = 0
// LightmapNormalOffset is the byte offset of the float32x3 normal inside a vertex.
LightmapNormalOffset = 12
// LightmapUV0Offset is the byte offset of the float32x2 primary (albedo) UV inside a vertex.
LightmapUV0Offset = 24
// LightmapUV1Offset is the byte offset of the float32x2 secondary (lightmap) UV inside a vertex.
LightmapUV1Offset = 32
// LightmapPositionLocation is the shader @location of the position attribute.
LightmapPositionLocation = 0
// LightmapNormalLocation is the shader @location of the normal attribute.
LightmapNormalLocation = 1
// LightmapUV0Location is the shader @location of the primary (albedo) UV attribute.
LightmapUV0Location = 2
// LightmapUV1Location is the shader @location of the secondary (lightmap) UV attribute.
LightmapUV1Location = 3
)Interleaved vertex layout written by LightmapMesh.AppendVertexData and described by LightmapVertexLayout. Every lightmapped mesh uses this 40-byte layout so one pipeline draws any GPULightmapMesh with distinct UV0 (albedo) and UV1 (baked lightmap) channels.
const (
// LightmapDrawGroup is the bind group slot carrying the per-draw dynamic uniform buffer.
LightmapDrawGroup = 1
// LightmapTextureGroup is the bind group slot carrying the base color and lightmap textures and samplers.
LightmapTextureGroup = 2
// LightmapDrawUniformSize is the byte size of the WGSL LightmapDraw uniform struct (224 bytes): model and normal matrices followed by six vec4 parameters.
LightmapDrawUniformSize = 2*64 + 6*16
// LightmapDrawUniformStride is the byte stride between per-draw uniform slots (256 bytes, matching WebGPU's minimum dynamic uniform buffer offset alignment).
LightmapDrawUniformStride = 256
// DefaultRGBMMaxRange is the default HDR multiplier for [LightmapRGBM] lightmaps.
DefaultRGBMMaxRange float32 = 8.0
)Bind group slots and uniform layout constants for LightmapRenderer and LightmapWGSL.
const (
// LocalShadowGroup is the bind group index [SpotShadowWGSL], [PointShadowWGSL], [LitPBRSpotShadowWGSL] and [LitPBRPointShadowWGSL] reserve for a spot or point shadow map (uniform buffer at binding 0, depth texture at binding 1, comparison sampler at binding 2). It is [ShadowGroup], the group after [CameraGroup] (0), [LightGroup] (1) and [PBRDrawGroup] (2), so a lit PBR pipeline takes one shadow map, fog, IBL or skin palette there. Custom shaders that need group 3 for something else, or that combine a spot and a point shadow, place the bindings elsewhere with [SpotShadowWGSLForGroup] and [PointShadowWGSLForGroup].
LocalShadowGroup = ShadowGroup
// PointShadowFaceCount is the number of cube faces rendered for a point light.
PointShadowFaceCount = 6
// PointShadowAtlasCols is the horizontal tile count of the 3x2 point shadow atlas.
PointShadowAtlasCols = 3
// PointShadowAtlasRows is the vertical tile count of the 3x2 point shadow atlas.
PointShadowAtlasRows = 2
// SpotShadowUniformSize is the byte size of [SpotShadowUniform.Encode] and the WGSL SpotShadow block: one mat4x4<f32> and one vec4<f32> (80 bytes).
SpotShadowUniformSize = 64 + 16
// PointShadowUniformSize is the byte size of [PointShadowUniform.Encode] and the WGSL PointShadow block: three vec4<f32> (48 bytes).
PointShadowUniformSize = 3 * 16
// DefaultLocalShadowNear is the default near plane distance of spot and point shadow projections.
DefaultLocalShadowNear float32 = 0.1
// DefaultLocalShadowFar is the default far plane distance used for a light whose Range is 0 (unbounded inverse-square falloff). Lit surfaces farther than this from the light are left unshadowed.
DefaultLocalShadowFar float32 = 50
// DefaultLocalShadowMaxCasters is the default number of caster draws per spot shadow pass, and per cube face of a point shadow, when MaxCasters is zero.
DefaultLocalShadowMaxCasters uint32 = 256
// MaxLocalShadowCasters is the largest MaxCasters [SpotShadowConfig.Validate] and [PointShadowConfig.Validate] accept. Each caster takes a 256-byte uniform slot, so a spot shadow at this limit holds a 1 MiB caster buffer and a point shadow six times that.
MaxLocalShadowCasters uint32 = 4096
// MaxSpotShadowConeAngle is the widest spot light OuterConeAngle (in radians, just under 90 degrees) a [SpotShadowMap] can project: its perspective field of view is twice the cone angle. Use a [PointShadowMap] for wider cones.
MaxSpotShadowConeAngle float32 = math.Pi/2 - 0.01
)Spot and point light shadow constants and defaults (#255).
const (
MaterialUniformBinding uint32 = 0
MaterialBaseColorTextureBinding uint32 = 1
MaterialBaseColorSamplerBinding uint32 = 2
MaterialMetallicRoughnessTextureBinding uint32 = 3
MaterialMetallicRoughnessSamplerBinding uint32 = 4
MaterialNormalTextureBinding uint32 = 5
MaterialNormalSamplerBinding uint32 = 6
MaterialOcclusionTextureBinding uint32 = 7
MaterialOcclusionSamplerBinding uint32 = 8
MaterialEmissiveTextureBinding uint32 = 9
MaterialEmissiveSamplerBinding uint32 = 10
)Binding indices inside MaterialGroup declared by MaterialBindGroupLayout and MaterialBindingsWGSL.
const (
ExtendedMaterialClearcoatTextureBinding uint32 = 11
ExtendedMaterialClearcoatSamplerBinding uint32 = 12
ExtendedMaterialClearcoatRoughnessTextureBinding uint32 = 13
ExtendedMaterialClearcoatRoughnessSamplerBinding uint32 = 14
ExtendedMaterialClearcoatNormalTextureBinding uint32 = 15
ExtendedMaterialClearcoatNormalSamplerBinding uint32 = 16
ExtendedMaterialTransmissionTextureBinding uint32 = 17
ExtendedMaterialTransmissionSamplerBinding uint32 = 18
)Binding indices inside MaterialGroup (group 1) added by ExtendedMaterialBindGroupLayout after the base bindings 0..10 of MaterialBindGroupLayout.
const (
// ExtendedLightGroup is the bind group slot [NewExtendedMaterialPipeline] assigns to [GPULightBuffer] when [ExtendedMaterialPipelineOptions].LightLayout is set, after [CameraGroup] (0) and [MaterialGroup] (1).
ExtendedLightGroup = 2
// TransmissionBackgroundGroup is the bind group slot [NewExtendedMaterialPipeline] assigns to [TransmissionBackground] when paired with [ExtendedMaterialPipelineOptions].LightLayout (groups 0..3: Camera, Material, Light, TransmissionBackground).
TransmissionBackgroundGroup = 3
// MaterialTransmissionBackgroundGroup is the bind group slot [NewExtendedMaterialPipeline] assigns to [TransmissionBackground] when [ExtendedMaterialPipelineOptions].LightLayout is nil (groups 0..2: Camera, Material, TransmissionBackground), mirroring [MaterialFogGroup].
MaterialTransmissionBackgroundGroup = 2
// TransmissionBackgroundUniformSize is the byte size of TransmissionBackgroundParams in [TransmissionBackgroundWGSL] (two vec4<f32> vectors = 32 bytes).
TransmissionBackgroundUniformSize = 32
)Bind group slots and uniform size for extended PBR pipelines (NewExtendedMaterialPipeline) and per-frame transmission background passes (TransmissionBackground).
const (
// MeshVertexStride is the byte size of one interleaved vertex: position (12 bytes), normal (12 bytes) and UV (8 bytes).
MeshVertexStride = 32
// MeshPositionOffset is the byte offset of the float32x3 position inside a vertex.
MeshPositionOffset = 0
// MeshNormalOffset is the byte offset of the float32x3 normal inside a vertex.
MeshNormalOffset = 12
// MeshUVOffset is the byte offset of the float32x2 texture coordinate inside a vertex.
MeshUVOffset = 24
// MeshPositionLocation is the shader @location of the position attribute.
MeshPositionLocation = 0
// MeshNormalLocation is the shader @location of the normal attribute.
MeshNormalLocation = 1
// MeshUVLocation is the shader @location of the texture coordinate attribute.
MeshUVLocation = 2
)Interleaved vertex layout written by Mesh.AppendVertexData and described by MeshVertexLayout. Every mesh uses the same layout, so one pipeline draws any GPUMesh; a missing normal or UV is written as zeros.
const (
// DefaultOcclusionWidth is the default horizontal resolution of an
// [OcclusionBuffer] when a non-positive width is passed to [NewOcclusionBuffer].
DefaultOcclusionWidth = 128
// DefaultOcclusionHeight is the default vertical resolution of an
// [OcclusionBuffer] when a non-positive height is passed to [NewOcclusionBuffer].
DefaultOcclusionHeight = 72
)const (
// PBRLightmapMaterialGroup is the bind group index [PBRLightmapWGSL] reserves for a [GPUMaterial] (material uniform buffer plus base color, metallic-roughness, normal, occlusion, and emissive texture/sampler pairs) alongside [CameraGroup] (group 0) and [LightGroup] (group 1). It occupies group 2, matching [PBRDrawGroup] in [LitPBRWGSL].
PBRLightmapMaterialGroup = 2
// PBRLightmapGroup is the bind group index [PBRLightmapWGSL] and [PBRLightmapBindingsWGSL] reserve for [GPUPBRLightmap] (per-draw transform, atlas UV transform, lightmap encoding parameters, and baked lightmap texture/sampler), parallel to [FogGroup] and [IBLGroup] at group 3.
PBRLightmapGroup = 3
// PBRLightmapUniformBinding is the @binding index of the uniform block inside [PBRLightmapGroup].
PBRLightmapUniformBinding uint32 = 0
// PBRLightmapTextureBinding is the @binding index of the 2D baked lightmap texture inside [PBRLightmapGroup].
PBRLightmapTextureBinding uint32 = 1
// PBRLightmapSamplerBinding is the @binding index of the baked lightmap sampler inside [PBRLightmapGroup].
PBRLightmapSamplerBinding uint32 = 2
// PBRLightmapUniformSize is the byte size of struct PBRLightmapUniform in [PBRLightmapBindingsWGSL]: model (64) + normal_matrix (64) + uv_transform (16) + lm_params (16) + ambient_fallback (16) = 176 bytes.
PBRLightmapUniformSize = 2*64 + 3*16
)Bind group slots, binding indices, and uniform byte size for the baked-lightmap PBR pipeline (PBRLightmapWGSL, NewPBRLightmapPipeline, and GPUPBRLightmap).
const (
// LightProbeGridVersion is the baked light probe grid YAML schema version this package reads and writes.
LightProbeGridVersion = 1
// LightProbeGridSchemaURL is where the JSON Schema of version 1 baked light probe grid YAML files is published.
LightProbeGridSchemaURL = "https://game.nsgo.dev/schemas/lightprobes.v1.json"
// LightProbeGridSchemaComment is the first line [EncodeLightProbeGrid] writes so YAML editors and AI tools validate and complete baked light probe files.
LightProbeGridSchemaComment = "# yaml-language-server: $schema=" + LightProbeGridSchemaURL
// MaxLightProbeGridProbes caps the total probe count (nx * ny * nz) accepted when decoding a baked [LightProbeGridDoc].
MaxLightProbeGridProbes = 65536
)const (
// ProbeCubeFaceCount is the six canonical faces of a cubemap (+X, -X, +Y, -Y, +Z, -Z).
ProbeCubeFaceCount = 6
// ProbeIBLUniformSize is the byte size of the ProbeIBLUniform block written by [ProbeIBLUniform.Encode] and declared by [ProbeIBLWGSL]: nine vec4<f32> L2 spherical harmonic irradiance coefficients followed by six probe geometry/weight vec4<f32>s and one global parameter vec4<f32> (256 bytes).
ProbeIBLUniformSize = 9*16 + 7*16
)const (
// ShadowGroup is the bind group index [ShadowWGSL] and [LitPBRShadowWGSL] reserve for directional shadow data (uniform buffer at binding 0, depth texture at binding 1, comparison sampler at binding 2). It is the last of the four bind groups every NSGo backend offers, after [CameraGroup] (0), [LightGroup] (1) and [PBRDrawGroup] (2), so it is the same slot [FogGroup], [IBLGroup] and [LitPBRSkinGroup] use and a lit PBR pipeline takes only one of them. Custom shaders that need group 3 for something else can place the shadow bindings elsewhere with [ShadowWGSLForGroup].
ShadowGroup = 3
// ShadowUniformSize is the byte size of the [ShadowUniforms] block written by [AppendShadowUniforms] and declared by [ShadowWGSL]: one mat4x4<f32> plus two vec4<f32> vectors (96 bytes).
ShadowUniformSize = 64 + 16 + 16
// ShadowCasterUniformSize is the byte size of one caster's light-space MVP matrix in [ShadowDepthWGSL].
ShadowCasterUniformSize = 64
// DefaultShadowResolution is the default width and height in texels of a [DirectionalShadowMap].
DefaultShadowResolution uint32 = 1024
// MinShadowResolution is the smallest shadow map resolution accepted by [DirectionalShadowConfig.Validate] and [ShadowMapOptions.Validate].
MinShadowResolution uint32 = 16
// MaxShadowResolution is the largest shadow map resolution accepted by [DirectionalShadowConfig.Validate] and [ShadowMapOptions.Validate].
MaxShadowResolution uint32 = 8192
// DefaultShadowMaxCasters is the default number of caster draws supported per shadow pass when [ShadowMapOptions.MaxCasters] is zero.
DefaultShadowMaxCasters uint32 = 256
// DefaultShadowDepthBias is the default receiver-side clip-space depth bias applied in [ShadowWGSL] and [EvaluateDirectionalShadow].
DefaultShadowDepthBias float32 = 0.0015
// DefaultShadowNormalBias is the default world-space surface-normal offset applied before light-space projection to suppress shadow acne on sloped surfaces.
DefaultShadowNormalBias float32 = 0.02
// DefaultShadowStrength is the default shadow intensity in [0, 1] (1 = full occlusion of direct directional light).
DefaultShadowStrength float32 = 1.0
)Directional shadow mapping constants and defaults (#117).
const (
// MaxSkinJoints is the maximum number of joint matrices stored in one [GPUSkinPalette] uniform buffer. 128 mat4x4<f32> entries occupy 8192 bytes ([SkinUniformSize]), staying comfortably below WebGL 2 and OpenGL ES 3.0's 16 KiB minimum MAX_UNIFORM_BLOCK_SIZE while covering full character rigs.
MaxSkinJoints = 128
// SkinUniformSize is the byte size of the skin uniform block that [AppendJointMatrices] writes and [SkinWGSL] declares: MaxSkinJoints * 64 = 8192 bytes.
SkinUniformSize = MaxSkinJoints * 64
// SkinGroup is the bind group index of the joint palette ([GPUSkinPalette.BindGroup]) in [SkinWGSL] and the unlit [NewSkinnedMeshPipeline], which binds only [CameraGroup] and the palette. Lit and material pipelines keep group 1 for lights and materials, so they bind the palette at [LitPBRSkinGroup] or [MaterialSkinGroup] instead.
SkinGroup = 1
// LitPBRSkinGroup is the bind group index of the joint palette in [LitPBRSkinnedWGSL] ([LitPBRPipelineOptions].SkinLayout), after [CameraGroup], [LightGroup] and [PBRDrawGroup]. It is the slot [FogGroup] and [IBLGroup] use, the last of the four bind groups WebGPU and WebGL 2 guarantee, so a skinned lit PBR draw has neither fog nor IBL.
LitPBRSkinGroup = 3
// MaterialSkinGroup is the bind group index of the joint palette in [MaterialSkinnedWGSL] ([MaterialPipelineOptions].SkinLayout), after [CameraGroup] and [MaterialGroup]. It is the slot [MaterialFogGroup] uses, so a skinned material draw has no fog.
MaterialSkinGroup = 2
// SkinnedVertexStride is the byte size of one interleaved skinned vertex: position (12 bytes), normal (12 bytes), UV (8 bytes), four joint indices (16 bytes), and four normalized weights (16 bytes).
SkinnedVertexStride = 64
// SkinnedPositionOffset is the byte offset of the float32x3 position inside a skinned vertex.
SkinnedPositionOffset = 0
// SkinnedNormalOffset is the byte offset of the float32x3 normal inside a skinned vertex.
SkinnedNormalOffset = 12
// SkinnedUVOffset is the byte offset of the float32x2 texture coordinate inside a skinned vertex.
SkinnedUVOffset = 24
// SkinnedJointsOffset is the byte offset of the uint32x4 joint indices inside a skinned vertex.
SkinnedJointsOffset = 32
// SkinnedWeightsOffset is the byte offset of the float32x4 joint weights inside a skinned vertex.
SkinnedWeightsOffset = 48
// SkinnedPositionLocation is the shader @location of the position attribute.
SkinnedPositionLocation = MeshPositionLocation
// SkinnedNormalLocation is the shader @location of the normal attribute.
SkinnedNormalLocation = MeshNormalLocation
// SkinnedUVLocation is the shader @location of the texture coordinate attribute.
SkinnedUVLocation = MeshUVLocation
// SkinnedJointsLocation is the shader @location of the uint32x4 joint indices attribute.
SkinnedJointsLocation = 3
// SkinnedWeightsLocation is the shader @location of the float32x4 joint weights attribute.
SkinnedWeightsLocation = 4
)Portable GPU skinning limits, uniform layout, bind group slots, and interleaved vertex layout.
const (
// SkyboxUniformSize is the byte size of the skybox uniform block written by [SkyboxUniform.Encode] and declared by [SkyboxWGSL].
SkyboxUniformSize = 64 + 16
// IBLGroup is the bind group index [IBLWGSL] and [LitPBRIBLWGSL] declare for image-based lighting ([GPUIBLBuffer.BindGroup]), after [CameraGroup], [LightGroup] and [PBRDrawGroup]. [FogGroup] uses the same index, so a lit pipeline has either IBL or fog. Use [IBLWGSLForGroup] when a custom shader binds the [GPUIBLBuffer] at another group.
IBLGroup = 3
// IBLUniformSize is the byte size of the IBL uniform block written by [IBLUniform.Encode] and declared by [IBLWGSL]: nine vec4<f32> L2 spherical harmonic irradiance coefficients followed by intensity, max_lod, and two padding floats.
IBLUniformSize = 9*16 + 16
)const (
// TerrainMaterialGroup is the bind group index reserved for [GPUTerrainMaterial]
// alongside [CameraGroup] (group 0) and [LightGroup] (group 1). It occupies
// group 2 (matching [PBRDrawGroup]), leaving group 3 free for [ShadowGroup],
// [CSMGroup], or [FogGroup].
TerrainMaterialGroup = PBRDrawGroup
// MaxTerrainLayers is the maximum number of PBR material layers blended by a
// [TerrainMaterial] (4 RGBA channels per splat map × up to 2 splat maps).
MaxTerrainLayers = 8
// TerrainMaterialUniformSize is the byte size of struct TerrainMaterialUniforms
// in [TerrainMaterialBindingsWGSL]: model (64) + normal_matrix (64) + params (16)
// + triplanar_params (16) + 8 × TerrainLayerUniform (8 × 48 = 384) = 544 bytes.
TerrainMaterialUniformSize = 64 + 64 + 16 + 16 + MaxTerrainLayers*48
// Binding indices inside [TerrainMaterialGroup] declared by
// [TerrainMaterialBindGroupLayout] and [TerrainMaterialBindingsWGSL].
TerrainUniformBinding uint32 = 0
TerrainSplat0TextureBinding uint32 = 1
TerrainSplat1TextureBinding uint32 = 2
TerrainSplatSamplerBinding uint32 = 3
TerrainAlbedoArrayBinding uint32 = 4
TerrainNormalArrayBinding uint32 = 5
TerrainMRHeightArrayBinding uint32 = 6
TerrainLayerSamplerBinding uint32 = 7
)Bind group slot, binding indices, limits, and uniform byte size for splat-map multi-layer PBR terrain materials (TerrainMaterial, GPUTerrainMaterial, TerrainMaterialWGSL, and NewTerrainMaterialPipeline).
const (
DefaultTerrainRoughness float32 = 0.85
DefaultTerrainTriplanarSlope float32 = 0.70
DefaultTerrainTriplanarBlend float32 = 0.15
DefaultTerrainTriplanarSharp float32 = 4.0
DefaultTerrainTriplanarScale float32 = 0.25
)Default terrain layer and triplanar constants.
const (
// ToneMapGroup is the @group index that [ToneMapWGSL] binds the HDR texture, sampler, and uniform parameters at.
ToneMapGroup = 0
// ToneMapUniformSize is the byte size of the uniform block written by [AppendToneMapUniforms] and declared by [ToneMapWGSL]: twelve little-endian float32 values (exposure, inv_gamma, operator_id, padding, then the source region's uv_scale, uv_min and uv_max as vec2 pairs, and two padding floats).
ToneMapUniformSize = 48
)Tone mapping uniform layout and bind-group constants (#250).
const (
// ToonMaterialGroup is the bind group index [ToonWGSL] and [ToonOutlineWGSL] reserve for [GPUToonMaterial] (uniform + base and ramp textures/samplers), alongside [CameraGroup] at group 0. It is the same slot as [MaterialGroup], where the other material pipelines bind their material.
ToonMaterialGroup = 1
// ToonSceneGroup is the bind group index [ToonWGSL] and [ToonOutlineWGSL] reserve for the per-draw transform and the key light ([ToonSceneUniform]). Toon shading bands the light of one key light, so it takes that light from a [ToonLight] in this per-draw block rather than binding a whole [LightRig] at [LightGroup].
ToonSceneGroup = 2
// ToonUniformSize is the little-endian byte size of the material uniform block [ToonMaterial.AppendUniformData] writes and [ToonWGSL] declares (7 vec4<f32> = 112 bytes).
ToonUniformSize = 7 * 16
// ToonSceneUniformSize is the little-endian byte size of the per-draw scene uniform block [ToonSceneUniform.AppendUniformData] writes and [ToonWGSL] declares (2 mat4x4<f32> + 3 vec4<f32> = 176 bytes).
ToonSceneUniformSize = 2*64 + 3*16
// DefaultToonBands is the discrete diffuse band count used when [ToonMaterial.Bands] is zero.
DefaultToonBands = 3
// MinToonBands is the smallest explicit diffuse band count [ToonMaterial.Validate] accepts.
MinToonBands = 2
// MaxToonBands is the largest diffuse band count [ToonMaterial.Validate] accepts.
MaxToonBands = 8
// DefaultToonSpecularPower is the Blinn-Phong exponent used when [ToonMaterial.SpecularPower] is zero.
DefaultToonSpecularPower = 32
// MaxToonDrawsPerFrame is the most draws [ToonRenderer.Draw] accepts between two calls of [ToonRenderer.Begin] (or two frames), which bounds the scene uniform buffer when a caller that submits with [gpu.Device.Submit] directly forgets to call Begin.
MaxToonDrawsPerFrame = 1 << 16
)Bind group slots, uniform sizes, and defaults for cel/toon shading (#262).
const (
// ColoredVertexStride is the byte size of one interleaved colored vertex: position (12), normal (12), UV (8), and linear RGBA color (16).
ColoredVertexStride = 48
// ColoredPositionOffset is the byte offset of the float32x3 position inside a colored vertex.
ColoredPositionOffset = MeshPositionOffset
// ColoredNormalOffset is the byte offset of the float32x3 normal inside a colored vertex.
ColoredNormalOffset = MeshNormalOffset
// ColoredUVOffset is the byte offset of the float32x2 texture coordinate inside a colored vertex.
ColoredUVOffset = MeshUVOffset
// ColoredColorOffset is the byte offset of the float32x4 linear RGBA vertex color inside a colored vertex.
ColoredColorOffset = 32
// ColoredPositionLocation is the shader @location of the position attribute.
ColoredPositionLocation = MeshPositionLocation
// ColoredNormalLocation is the shader @location of the normal attribute.
ColoredNormalLocation = MeshNormalLocation
// ColoredUVLocation is the shader @location of the texture coordinate attribute.
ColoredUVLocation = MeshUVLocation
// ColoredColorLocation is the shader @location of the linear RGBA vertex color attribute (glTF COLOR_0).
ColoredColorLocation = 3
)Interleaved vertex layout written by ColoredMesh.AppendVertexData and described by ColoredVertexLayout. Locations 0..2 match MeshVertexLayout identically, extended with linear RGBA vertex color at @location(3). Missing normals and UVs are written as zeros; missing vertex colors are written as linear white (1, 1, 1, 1).
const (
// DefaultUploadBytesPerFrame is the default per-frame GPU upload budget (4 MiB) used by [NewUploader] when [UploaderOptions.BytesPerFrame] is <= 0.
DefaultUploadBytesPerFrame = 4 * mib
// DefaultUploadChunkBytes is the default per-write chunk size (256 KiB) used to split large buffers and textures smoothly across frames.
DefaultUploadChunkBytes = 256 * 1024
)const CSMDepthWGSL = `struct CSMCascadeUniform {
light_view_proj: mat4x4<f32>,
}
struct CSMModelUniform {
world: mat4x4<f32>,
}
@group(0) @binding(0) var<uniform> csm_cascade: CSMCascadeUniform;
@group(1) @binding(0) var<uniform> csm_model: CSMModelUniform;
struct CSMDepthIn {
@location(0) pos: vec3<f32>,
@location(1) normal: vec3<f32>,
@location(2) uv: vec2<f32>,
}
@vertex
fn vs_csm_depth(in: CSMDepthIn) -> @builtin(position) vec4<f32> {
let world_pos = csm_model.world * vec4<f32>(in.pos, 1.0);
return csm_cascade.light_view_proj * world_pos;
}
`CSMDepthWGSL is the depth-only vertex shader used by CascadedShadowMap to rasterize shadow casters into a cascade tile of the 2D depth atlas.
Bind groups:
- @group(0) @binding(0): CSMCascadeUniform (light_view_proj: mat4x4<f32>)
- @group(1) @binding(0): CSMModelUniform (world: mat4x4<f32>)
Vertex buffer 0 matches MeshVertexLayout.
const CSMWGSL = csmStructWGSL + `
@group(3) @binding(0) var<uniform> csm: CSMUniforms;
@group(3) @binding(1) var csm_shadow_map: texture_depth_2d;
@group(3) @binding(2) var csm_shadow_sampler: sampler_comparison;
` + csmSampleFnWGSLCSMWGSL declares the cascaded shadow map uniform block, 2D depth atlas and comparison sampler at CSMGroup (@group(3)), and portable helpers for sampling them with optional 3x3 PCF, smooth inter-cascade blending, a fade toward CSMConfig.MaxShadowDistance and optional debug cascade tinting. It equals CSMWGSLForGroup(CSMGroup).
The helpers read the camera's view matrix, so prepend CameraWGSL first. sample_csm_shadow(world_pos, world_normal) returns the visibility in [0, 1] of the light the cascades were fitted to, like sample_directional_shadow in ShadowWGSL: pass it as the shadow_vis of shade_pbr_shadowed in LightWGSL to shadow the LightRig's first directional light. csm_shadow_factor(world_pos, unit_normal, view_depth) takes the view depth directly, and csm_debug_tint(world_pos) returns the per-cascade color multiplier CSMConfig.DebugCascades enables (white when it is off). LitPBRCSMWGSL is the ready-made PBR shader built on it.
It uses only algebraic WGSL operations and textureSampleCompareLevel (no exp, exp2, log2 or texture_depth_2d_array), so it runs identically on Metal, Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0 and the software GPU renderer.
const CameraGroup = 0CameraGroup is the bind group index the 3D shaders in this repository reserve for the camera: CameraBuffer.BindGroup goes in this slot of every 3D pipeline's layouts, and CameraWGSL declares it there.
const CameraUniformSize = 3*64 + 16CameraUniformSize is the byte size of the camera uniform block that CameraUniform.Encode writes and CameraWGSL declares.
const CameraWGSL = `struct Camera {
view: mat4x4<f32>,
proj: mat4x4<f32>,
view_proj: mat4x4<f32>,
eye: vec4<f32>,
}
@group(0) @binding(0) var<uniform> camera: Camera;
`CameraWGSL declares the camera uniform block at @group(0) @binding(0) as the variable camera. Prepend it to a WGSL module whose vertex stage places points with camera.view_proj; the block's layout matches CameraUniform.Encode byte for byte.
The eye field is the homogeneous eye point from scene3d.Camera.Eye, so normalize(camera.eye.xyz - p * camera.eye.w) is the unit vector from a world point p toward the viewer under both perspective and orthographic cameras.
const ClusteredBindingsWGSL = LightWGSL + clusteredStorageWGSLClusteredBindingsWGSL is LightWGSL (the LightRig block at LightGroup binding 0 and its PBR helpers) plus the clustered forward bindings at bindings 1 to 4 of the same group and this helper:
- shade_pbr_clustered(world_pos, normal, view_dir, base_color, metallic, roughness, frag_pos) -> vec3<f32>
It returns shade_pbr for the rig plus every local light binned into the cluster that holds the fragment, each shaded with pbr_brdf, point_light_attenuation and spot_cone_attenuation, so it matches ShadeClusteredGridPoint. frag_pos is the fragment's @builtin(position). Prepend CameraWGSL, which supplies camera.view for the depth slice, and pair it with a ClusteredLightSystem in clustered mode; ClusteredFallbackBindingsWGSL declares the same helper for the fallback path.
Depth slicing is a 6-step binary search over the uniform split-depth table rather than log2 and exp, because NSGo v0.3.0's software GPU VM has no log, log2, exp or exp2 builtin and silently evaluates them to zero (internal/driver/gpu_software.go, evalCall) (nsgo-dev/nsgo#2334).
const ClusteredFallbackBindingsWGSL = LightWGSL + clusteredFallbackWGSLClusteredFallbackBindingsWGSL is LightWGSL plus the fallback uniform block at LightGroup binding 1 and shade_pbr_clustered with the same signature as in ClusteredBindingsWGSL, using no storage buffers or compute, for WebGL 2 and OpenGL ES 3.0 targets. frag_pos is ignored: every uploaded light is evaluated for every fragment.
const ClusteredFallbackWGSL = litPBRPreludeWGSL + clusteredFallbackWGSL + clusteredLitFragmentWGSLClusteredFallbackWGSL is ClusteredLitWGSL built on ClusteredFallbackBindingsWGSL, for devices without storage buffers or compute.
const ClusteredLitWGSL = litPBRPreludeWGSL + clusteredStorageWGSL + clusteredLitFragmentWGSLClusteredLitWGSL is LitPBRWGSL with clustered local lights: the same metallic-roughness module on CameraWGSL, MeshVertexLayout and a per-draw PBRDrawUniform at PBRDrawGroup, whose fragment stage shades with shade_pbr_clustered from ClusteredBindingsWGSL and writes sRGB. NewClusteredLitPBRPipeline creates a pipeline from it.
const CustomMaterialGroup = MaterialGroupCustomMaterialGroup is the bind group slot (@group(1)) that holds a custom material's uniform buffer and texture/sampler bindings alongside CameraGroup (@group(0)). It is MaterialGroup, the slot every material in this package binds at.
const CustomMaterialUniformBinding = 0CustomMaterialUniformBinding is the @binding index inside CustomMaterialGroup used for the generated MaterialParams uniform struct when a custom material declares at least one non-texture parameter.
const DefaultMaterialIOR float32 = 1.5DefaultMaterialIOR is the glTF 2.0 default dielectric index of refraction (1.5, corresponding to F0 = 0.04).
const ExtendedMaterialBindingsWGSL = `struct ExtendedMaterialUniforms {
base_color_factor: vec4<f32>,
emissive_factor: vec4<f32>,
params: vec4<f32>,
flags: vec4<f32>,
ext_params: vec4<f32>,
ext_flags: vec4<f32>,
}
@group(1) @binding(0) var<uniform> material: ExtendedMaterialUniforms;
@group(1) @binding(1) var base_color_tex: texture_2d<f32>;
@group(1) @binding(2) var base_color_samp: sampler;
@group(1) @binding(3) var metallic_roughness_tex: texture_2d<f32>;
@group(1) @binding(4) var metallic_roughness_samp: sampler;
@group(1) @binding(5) var normal_tex: texture_2d<f32>;
@group(1) @binding(6) var normal_samp: sampler;
@group(1) @binding(7) var occlusion_tex: texture_2d<f32>;
@group(1) @binding(8) var occlusion_samp: sampler;
@group(1) @binding(9) var emissive_tex: texture_2d<f32>;
@group(1) @binding(10) var emissive_samp: sampler;
@group(1) @binding(11) var clearcoat_tex: texture_2d<f32>;
@group(1) @binding(12) var clearcoat_samp: sampler;
@group(1) @binding(13) var clearcoat_roughness_tex: texture_2d<f32>;
@group(1) @binding(14) var clearcoat_roughness_samp: sampler;
@group(1) @binding(15) var clearcoat_normal_tex: texture_2d<f32>;
@group(1) @binding(16) var clearcoat_normal_samp: sampler;
@group(1) @binding(17) var transmission_tex: texture_2d<f32>;
@group(1) @binding(18) var transmission_samp: sampler;
fn ext_pow5(x: f32) -> f32 {
let c = clamp(x, 0.0, 1.0);
let c2 = c * c;
return c2 * c2 * c;
}
fn ext_dielectric_f0(ior: f32) -> f32 {
if (ior <= 0.0) {
return 0.04;
}
let r = (ior - 1.0) / (ior + 1.0);
return r * r;
}
// ext_perturb_normal builds the same API-independent Cramer's-rule cotangent frame as material_perturb_normal (with deterministic orthonormal fallback when screen-space derivatives or UVs are degenerate) and is shared by both base and clearcoat normal maps.
fn ext_perturb_normal(
geom_n: vec3<f32>,
dp1: vec3<f32>,
dp2: vec3<f32>,
duv1: vec2<f32>,
duv2: vec2<f32>,
normal_sample: vec3<f32>,
normal_scale: f32,
) -> vec3<f32> {
var up_ref = vec3<f32>(0.0, 1.0, 0.0);
if (geom_n.y > 0.99) {
up_ref = vec3<f32>(0.0, 0.0, -1.0);
} else if (geom_n.y < -0.99) {
up_ref = vec3<f32>(0.0, 0.0, 1.0);
}
var t_vec = normalize(cross(up_ref, geom_n));
var b_vec = cross(geom_n, t_vec);
let det = duv1.x * duv2.y - duv1.y * duv2.x;
if (abs(det) > 1e-10) {
let inv_det = 1.0 / det;
let t_raw = (dp1 * duv2.y - dp2 * duv1.y) * inv_det;
let b_dv = (dp2 * duv1.x - dp1 * duv2.x) * inv_det;
let t_ortho = t_raw - geom_n * dot(geom_n, t_raw);
let b_raw = -b_dv;
let b_ortho = b_raw - geom_n * dot(geom_n, b_raw);
if (dot(t_ortho, t_ortho) > 1e-10 && dot(b_ortho, b_ortho) > 1e-10) {
t_vec = normalize(t_ortho);
b_vec = normalize(b_ortho);
}
}
let n_unpacked = normal_sample * 2.0 - vec3<f32>(1.0, 1.0, 1.0);
let n_ts = normalize(vec3<f32>(n_unpacked.x * normal_scale, n_unpacked.y * normal_scale, n_unpacked.z));
return normalize(t_vec * n_ts.x + b_vec * n_ts.y + geom_n * n_ts.z);
}
fn ext_pbr_direct(
n: vec3<f32>,
v: vec3<f32>,
l: vec3<f32>,
light_color: vec3<f32>,
base_color: vec3<f32>,
metallic: f32,
roughness: f32,
f0_dielectric: f32,
transmission: f32,
) -> vec3<f32> {
let ndl = max(dot(n, l), 0.0);
if (ndl <= 0.0) {
return vec3<f32>(0.0, 0.0, 0.0);
}
let ndv = max(dot(n, v), 1e-4);
let h_raw = v + l;
let h_len2 = dot(h_raw, h_raw);
let f0 = mix(vec3<f32>(f0_dielectric, f0_dielectric, f0_dielectric), base_color, metallic);
let pi = 3.14159265359;
if (h_len2 <= 1e-8) {
let diff_only = (vec3<f32>(1.0, 1.0, 1.0) - f0) * ((1.0 - metallic) * (1.0 - transmission) / pi) * base_color;
return diff_only * light_color * ndl;
}
let h = h_raw / sqrt(h_len2);
let ndh = max(dot(n, h), 0.0);
let vdh = max(dot(v, h), 0.0);
let alpha = roughness * roughness;
let alpha2 = alpha * alpha;
let denom = ndh * ndh * (alpha2 - 1.0) + 1.0;
let d_term = alpha2 / max(pi * denom * denom, 1e-7);
let ggx_v = ndl * sqrt(ndv * ndv * (1.0 - alpha2) + alpha2);
let ggx_l = ndv * sqrt(ndl * ndl * (1.0 - alpha2) + alpha2);
let vis = 0.5 / max(ggx_v + ggx_l, 1e-5);
let f_term = f0 + (vec3<f32>(1.0, 1.0, 1.0) - f0) * ext_pow5(1.0 - vdh);
let spec = f_term * (d_term * vis);
let diff = (vec3<f32>(1.0, 1.0, 1.0) - f_term) * ((1.0 - metallic) * (1.0 - transmission) / pi) * base_color;
return (diff + spec) * light_color * ndl;
}
fn ext_clearcoat_direct(
nc: vec3<f32>,
v: vec3<f32>,
l: vec3<f32>,
light_color: vec3<f32>,
cc_roughness: f32,
) -> vec3<f32> {
let ndl = max(dot(nc, l), 0.0);
if (ndl <= 0.0) {
return vec3<f32>(0.0, 0.0, 0.0);
}
let ndv = max(dot(nc, v), 1e-4);
let h_raw = v + l;
let h_len2 = dot(h_raw, h_raw);
if (h_len2 <= 1e-8) {
return vec3<f32>(0.0, 0.0, 0.0);
}
let h = h_raw / sqrt(h_len2);
let ndh = max(dot(nc, h), 0.0);
let vdh = max(dot(v, h), 0.0);
let alpha = cc_roughness * cc_roughness;
let alpha2 = alpha * alpha;
let pi = 3.14159265359;
let denom = ndh * ndh * (alpha2 - 1.0) + 1.0;
let d_term = alpha2 / max(pi * denom * denom, 1e-7);
let ggx_v = ndl * sqrt(ndv * ndv * (1.0 - alpha2) + alpha2);
let ggx_l = ndv * sqrt(ndl * ndl * (1.0 - alpha2) + alpha2);
let vis = 0.5 / max(ggx_v + ggx_l, 1e-5);
let f_term = 0.04 + (1.0 - 0.04) * ext_pow5(1.0 - vdh);
return light_color * (f_term * d_term * vis * ndl);
}
fn ext_pbr_ambient(
n: vec3<f32>,
v: vec3<f32>,
sky_color: vec3<f32>,
ground_color: vec3<f32>,
base_color: vec3<f32>,
metallic: f32,
roughness: f32,
occlusion: f32,
f0_dielectric: f32,
transmission: f32,
) -> vec3<f32> {
let ndv = max(dot(n, v), 1e-4);
let f0 = mix(vec3<f32>(f0_dielectric, f0_dielectric, f0_dielectric), base_color, metallic);
let f_max = max(vec3<f32>(1.0 - roughness, 1.0 - roughness, 1.0 - roughness), f0);
let f_amb = f0 + (f_max - f0) * ext_pow5(1.0 - ndv);
let sky_t = clamp(n.y * 0.5 + 0.5, 0.0, 1.0);
let amb_env = mix(ground_color, sky_color, sky_t);
let amb_diff = (vec3<f32>(1.0, 1.0, 1.0) - f_amb) * ((1.0 - metallic) * (1.0 - transmission)) * base_color * amb_env;
let refl = reflect(-v, n);
let refl_t = clamp(refl.y * 0.5 + 0.5, 0.0, 1.0);
let refl_env = mix(ground_color, sky_color, mix(refl_t, 0.5, roughness * roughness));
let amb_spec = refl_env * f_amb * (1.0 - 0.5 * roughness);
return (amb_diff + amb_spec) * occlusion;
}
fn ext_clearcoat_ambient(
nc: vec3<f32>,
v: vec3<f32>,
sky_color: vec3<f32>,
ground_color: vec3<f32>,
cc_roughness: f32,
occlusion: f32,
) -> vec3<f32> {
let ndv = max(dot(nc, v), 1e-4);
let f0 = 0.04;
let f_max = max(1.0 - cc_roughness, f0);
let f_amb = f0 + (f_max - f0) * ext_pow5(1.0 - ndv);
let refl = reflect(-v, nc);
let refl_t = clamp(refl.y * 0.5 + 0.5, 0.0, 1.0);
let refl_env = mix(ground_color, sky_color, mix(refl_t, 0.5, cc_roughness * cc_roughness));
return refl_env * (f_amb * (1.0 - 0.5 * cc_roughness) * occlusion);
}
fn ext_transmission_term(
n: vec3<f32>,
v: vec3<f32>,
base_color: vec3<f32>,
metallic: f32,
f0_dielectric: f32,
transmission: f32,
bg_linear: vec3<f32>,
) -> vec3<f32> {
if (transmission <= 0.0) {
return vec3<f32>(0.0, 0.0, 0.0);
}
let ndv = max(dot(n, v), 1e-4);
let f0 = mix(vec3<f32>(f0_dielectric, f0_dielectric, f0_dielectric), base_color, metallic);
let f_view = f0 + (vec3<f32>(1.0, 1.0, 1.0) - f0) * ext_pow5(1.0 - ndv);
return (vec3<f32>(1.0, 1.0, 1.0) - f_view) * ((1.0 - metallic) * transmission) * base_color * bg_linear;
}
fn ext_tonemap_srgb(linear_rgb: vec3<f32>) -> vec3<f32> {
let c = max(linear_rgb, vec3<f32>(0.0, 0.0, 0.0));
let mapped = c / (c + vec3<f32>(1.0, 1.0, 1.0));
return pow(clamp(mapped, vec3<f32>(0.0, 0.0, 0.0), vec3<f32>(1.0, 1.0, 1.0)), vec3<f32>(1.0 / 2.2, 1.0 / 2.2, 1.0 / 2.2));
}
`ExtendedMaterialBindingsWGSL declares MaterialGroup (group 1) bindings 0..18 for GPUExtendedMaterial together with portable glTF 2.0 metallic-roughness + KHR_materials_clearcoat + KHR_materials_transmission shading helpers and the UV-aligned Cramer cotangent-frame normal perturbation helper (reused for both base and clearcoat normal maps).
const ExtendedMaterialUniformSize = 96ExtendedMaterialUniformSize is the byte size of the 16-byte-aligned uniform block ExtendedMaterialUniforms.AppendUniformData and ExtendedMaterialUniforms.Encode write, matching struct ExtendedMaterialUniforms in ExtendedMaterialBindingsWGSL (64 bytes of MaterialUniforms plus 32 bytes of clearcoat, transmission, and IOR parameters).
const ExtendedMaterialWGSL = CameraWGSL + ExtendedMaterialBindingsWGSL + materialVertexStageWGSL + extFragmentPreludeWGSL + extNoBGWGSL + extDefaultLightingBodyWGSL + ` let srgb_rgb = ext_tonemap_srgb(linear_rgb);
` + materialStagesTailWGSLExtendedMaterialWGSL is the default-light extended PBR shader compiled by NewExtendedMaterialPipeline when neither LightLayout nor TransmissionLayout is set (groups 0: Camera, 1: ExtendedMaterial).
const FXAAUniformSize = 16FXAAUniformSize is the byte size of the FXAAParams uniform block declared by FXAAWGSL (one vec4<f32> = 16 bytes: subpixel quality, edge threshold, edge threshold minimum, and padding). The source's texel size is not part of it: the shader reads it with textureDimensions, so one pass can filter sources of different sizes in the same frame.
const FXAAWGSL = `struct FXAAParams {
params: vec4<f32>,
}
@group(0) @binding(0) var<uniform> fxaa_params: FXAAParams;
@group(0) @binding(1) var fxaa_tex: texture_2d<f32>;
@group(0) @binding(2) var fxaa_sampler: sampler;
struct FXAAVertexOut {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
}
@vertex
fn vs_main(@builtin(vertex_index) vid: u32) -> FXAAVertexOut {
var out: FXAAVertexOut;
let x = select(-1.0, 3.0, vid == 1u);
let y = select(-1.0, 3.0, vid == 2u);
out.clip = vec4<f32>(x, y, 0.0, 1.0);
out.uv = vec2<f32>(x * 0.5 + 0.5, 0.5 - y * 0.5);
return out;
}
fn fxaa_luma(rgb: vec3<f32>) -> f32 {
return dot(rgb, vec3<f32>(0.299, 0.587, 0.114));
}
fn fxaa_step(i: i32) -> f32 {
if (i < 4) {
return 1.0;
}
if (i == 4) {
return 1.5;
}
if (i < 9) {
return 2.0;
}
if (i == 9) {
return 4.0;
}
return 8.0;
}
@fragment
fn fs_main(in: FXAAVertexOut) -> @location(0) vec4<f32> {
let dims = textureDimensions(fxaa_tex);
let inv = vec2<f32>(1.0 / f32(dims.x), 1.0 / f32(dims.y));
let subpixQuality = fxaa_params.params.x;
let edgeThreshold = fxaa_params.params.y;
let edgeThresholdMin = fxaa_params.params.z;
let uv = in.uv;
let center = textureSampleLevel(fxaa_tex, fxaa_sampler, uv, 0.0);
let lumaM = fxaa_luma(center.rgb);
let lumaN = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv + vec2<f32>(0.0, -inv.y), 0.0).rgb);
let lumaS = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv + vec2<f32>(0.0, inv.y), 0.0).rgb);
let lumaW = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv + vec2<f32>(-inv.x, 0.0), 0.0).rgb);
let lumaE = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv + vec2<f32>(inv.x, 0.0), 0.0).rgb);
let lumaMin = min(lumaM, min(min(lumaN, lumaS), min(lumaW, lumaE)));
let lumaMax = max(lumaM, max(max(lumaN, lumaS), max(lumaW, lumaE)));
let lumaRange = lumaMax - lumaMin;
if (lumaRange < max(edgeThresholdMin, lumaMax * edgeThreshold)) {
return center;
}
let lumaNW = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv + vec2<f32>(-inv.x, -inv.y), 0.0).rgb);
let lumaNE = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv + vec2<f32>(inv.x, -inv.y), 0.0).rgb);
let lumaSW = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv + vec2<f32>(-inv.x, inv.y), 0.0).rgb);
let lumaSE = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv + vec2<f32>(inv.x, inv.y), 0.0).rgb);
let lumaDownUp = lumaN + lumaS;
let lumaLeftRight = lumaW + lumaE;
let lumaLeftCorners = lumaNW + lumaSW;
let lumaRightCorners = lumaNE + lumaSE;
let lumaTopCorners = lumaNW + lumaNE;
let lumaBottomCorners = lumaSW + lumaSE;
let lumaAvg = (2.0 * (lumaDownUp + lumaLeftRight) + (lumaLeftCorners + lumaRightCorners)) * (1.0 / 12.0);
let subpix1 = clamp(abs(lumaAvg - lumaM) / lumaRange, 0.0, 1.0);
let subpix2 = (-2.0 * subpix1 + 3.0) * subpix1 * subpix1;
let subpixOffset = subpix2 * subpix2 * subpixQuality;
let edgeHorz = abs(-2.0 * lumaW + lumaLeftCorners) +
2.0 * abs(-2.0 * lumaM + lumaDownUp) +
abs(-2.0 * lumaE + lumaRightCorners);
let edgeVert = abs(-2.0 * lumaN + lumaTopCorners) +
2.0 * abs(-2.0 * lumaM + lumaLeftRight) +
abs(-2.0 * lumaS + lumaBottomCorners);
let isHorizontal = edgeHorz >= edgeVert;
let luma1 = select(lumaW, lumaN, isHorizontal);
let luma2 = select(lumaE, lumaS, isHorizontal);
let grad1 = abs(luma1 - lumaM);
let grad2 = abs(luma2 - lumaM);
let is1Steepest = grad1 >= grad2;
let gradScaled = 0.25 * max(grad1, grad2);
var stepLength = select(inv.x, inv.y, isHorizontal);
var lumaLocalAvg = 0.5 * (luma2 + lumaM);
if (is1Steepest) {
stepLength = -stepLength;
lumaLocalAvg = 0.5 * (luma1 + lumaM);
}
var currentUv = uv;
if (isHorizontal) {
currentUv.y = currentUv.y + stepLength * 0.5;
} else {
currentUv.x = currentUv.x + stepLength * 0.5;
}
let offset = select(vec2<f32>(0.0, inv.y), vec2<f32>(inv.x, 0.0), isHorizontal);
var uv1 = currentUv - offset;
var uv2 = currentUv + offset;
var lumaEnd1 = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv1, 0.0).rgb) - lumaLocalAvg;
var lumaEnd2 = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv2, 0.0).rgb) - lumaLocalAvg;
var reached1 = abs(lumaEnd1) >= gradScaled;
var reached2 = abs(lumaEnd2) >= gradScaled;
for (var i: i32 = 1; i < 11; i = i + 1) {
if (reached1 && reached2) {
break;
}
let step = fxaa_step(i);
if (!reached1) {
uv1 = uv1 - offset * step;
lumaEnd1 = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv1, 0.0).rgb) - lumaLocalAvg;
reached1 = abs(lumaEnd1) >= gradScaled;
}
if (!reached2) {
uv2 = uv2 + offset * step;
lumaEnd2 = fxaa_luma(textureSampleLevel(fxaa_tex, fxaa_sampler, uv2, 0.0).rgb) - lumaLocalAvg;
reached2 = abs(lumaEnd2) >= gradScaled;
}
}
let dist1 = select(uv.y - uv1.y, uv.x - uv1.x, isHorizontal);
let dist2 = select(uv2.y - uv.y, uv2.x - uv.x, isHorizontal);
let isDir1 = dist1 < dist2;
let distFinal = min(dist1, dist2);
let edgeThickness = dist1 + dist2;
let lumaCenterSmaller = lumaM < lumaLocalAvg;
let endLuma = select(lumaEnd2, lumaEnd1, isDir1);
let endSmaller = endLuma < 0.0;
// Spelled out instead of endSmaller != lumaCenterSmaller: NSGo v0.3.0's software VM compares bool operands as equal (cmpVal in internal/driver/gpu_software.go ignores irVal.b) (nsgo-dev/nsgo#2335).
let correctVariation = (endSmaller && !lumaCenterSmaller) || (!endSmaller && lumaCenterSmaller);
var pixelOffset = 0.0;
if (correctVariation && edgeThickness > 0.0) {
pixelOffset = max(-distFinal / edgeThickness + 0.5, 0.0);
}
let finalOffset = max(pixelOffset, subpixOffset);
var finalUv = uv;
if (isHorizontal) {
finalUv.y = finalUv.y + finalOffset * stepLength;
} else {
finalUv.x = finalUv.x + finalOffset * stepLength;
}
let finalRgb = textureSampleLevel(fxaa_tex, fxaa_sampler, finalUv, 0.0).rgb;
return vec4<f32>(finalRgb, center.a);
}
`FXAAWGSL is a portable FXAA 3.11 full-screen post-processing WGSL shader module compiled by NewFXAAPass.
It draws a single bufferless full-screen triangle via @builtin(vertex_index) (Draw(3, 0)), uses only textureSampleLevel(..., 0.0) so non-uniform early exits and edge-search loops remain valid on every GPU backend (Metal, Direct3D 11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and the software device), and matches ApplyFXAA on the CPU for a non-sRGB, gamma-encoded source (see FXAAPass).
Bind group 0 layout:
- @binding(0): uniform FXAAParams (16 bytes: params = (subpixel, edgeThreshold, edgeThresholdMin, 0)); the texel size comes from textureDimensions(fxaa_tex)
- @binding(1): texture_2d<f32> source color texture (single-sampled)
- @binding(2): sampler (FilterLinear, AddressClampToEdge)
const FogBindingWGSL = `@group(3) @binding(0) var<uniform> fog: Fog;
`FogBindingWGSL declares the Fog uniform binding at @group(3) @binding(0) as the variable fog, matching FogGroup and GPUFogBuffer. Prepend FogWGSL first.
const FogCameraWGSL = `fn fog_camera_pos(world_pos: vec3<f32>) -> vec3<f32> {
if camera.eye.w > 0.5 {
return camera.eye.xyz;
}
let view_pos = camera.view * vec4<f32>(world_pos, 1.0);
return world_pos + camera.eye.xyz * max(-view_pos.z, 0.0);
}
`FogCameraWGSL declares fog_camera_pos(world_pos) -> vec3<f32>, the point a fogged view ray starts from, read from the camera block CameraWGSL declares (prepend that first). It matches FogCameraPos:
- a perspective camera (camera.eye.w = 1) returns the eye position, so fog grows with the distance from the eye;
- an orthographic camera (camera.eye.w = 0) returns world_pos moved back along camera.eye.xyz (the direction toward the viewer) by its view depth, which is the point on the camera's plane the parallel ray starts from, so fog grows with the distance from that plane.
const FogWGSL = `struct Fog {
color_opacity: vec4<f32>,
distance_params: vec4<f32>,
height_params: vec4<f32>,
}
// pow with base e instead of exp: NSGo v0.3.0's software GPU VM evaluates exp, exp2, log, log2 and atan as 0 (internal/driver/gpu_software.go evalCall has no case for them) (nsgo-dev/nsgo#2334). Switch back to exp once NSGo handles it.
fn fog_exp(x: f32) -> f32 {
return pow(2.718281828, x);
}
fn fog_factor(cam_pos: vec3<f32>, world_pos: vec3<f32>, fog: Fog) -> f32 {
let d = length(world_pos - cam_pos);
var f_dist: f32 = 0.0;
let mode = fog.distance_params.x;
if mode > 0.5 && mode < 1.5 {
let start = fog.distance_params.y;
let end = fog.distance_params.z;
if end <= start {
if d >= start {
f_dist = 1.0;
}
} else {
f_dist = clamp((d - start) / (end - start), 0.0, 1.0);
}
} else if mode >= 1.5 && mode < 2.5 {
let density = max(fog.distance_params.w, 0.0);
if density > 0.0 {
let x = max(d * density, 0.0);
f_dist = clamp(1.0 - fog_exp(-min(x, 80.0)), 0.0, 1.0);
}
} else if mode >= 2.5 {
let density = max(fog.distance_params.w, 0.0);
if density > 0.0 {
let x = max(d * density, 0.0);
f_dist = clamp(1.0 - fog_exp(-min(x * x, 80.0)), 0.0, 1.0);
}
}
var f_height: f32 = 0.0;
if fog.height_params.x > 0.5 {
let h_base = fog.height_params.y;
let h_falloff = max(fog.height_params.z, 0.0);
let h_density = max(fog.height_params.w, 0.0);
if d > 0.0 && h_density > 0.0 {
let h0 = cam_pos.y - h_base;
let h1 = world_pos.y - h_base;
let h_min = min(h0, h1);
let delta = abs(h1 - h0);
let u = h_falloff * delta;
var integral: f32 = 1.0;
if u < 0.05 {
let u2 = u * u;
integral = 1.0 - 0.5 * u + u2 / 6.0 - (u2 * u) / 24.0;
} else {
integral = (1.0 - fog_exp(-min(u, 80.0))) / u;
}
let exp_arg = clamp(-h_falloff * h_min, -80.0, 40.0);
let tau = max(h_density * d * fog_exp(exp_arg) * integral, 0.0);
f_height = clamp(1.0 - fog_exp(-min(tau, 80.0)), 0.0, 1.0);
}
}
let combined = 1.0 - (1.0 - f_dist) * (1.0 - f_height);
return clamp(combined, 0.0, clamp(fog.color_opacity.w, 0.0, 1.0));
}
fn apply_fog(color: vec3<f32>, cam_pos: vec3<f32>, world_pos: vec3<f32>, fog: Fog) -> vec3<f32> {
let f = fog_factor(cam_pos, world_pos, fog);
return mix(color, fog.color_opacity.xyz, vec3<f32>(f));
}
`FogWGSL declares the portable WGSL Fog uniform struct and its evaluation helpers:
- fog_factor(cam_pos, world_pos, fog) -> f32
- apply_fog(color, cam_pos, world_pos, fog) -> vec3<f32>
It intentionally declares no @group/@binding variable so any shader can embed Fog in its own uniform layout or prepend FogBindingWGSL (or MaterialFogBindingWGSL) to bind GPUFogBuffer. Its struct layout matches AppendFogUniforms byte for byte, and its formulas match Fog.Factor and Fog.Apply.
const IBLWGSL = iblWGSLDecl3 + iblWGSLFuncsIBLWGSL declares the IBL uniform block, prefiltered environment cubemap, and sampler at IBLGroup (@group(3)), together with evaluate_irradiance_sh, env_brdf_approx, fresnel_schlick_roughness, and evaluate_ibl. Prepend it to a PBR fragment shader whose pipeline binds GPUIBLBuffer.BindGroup at IBLGroup; LitPBRIBLWGSL does this for the repository's lit PBR shader.
const KTX2FilterKey = "game.filter"KTX2FilterKey is the key of a KTX2 file's key/value data that holds the sampling filter the image's import settings ask for, "linear" or "nearest", as game assets and game tex write it from the filter of the image's sidecar.
const LightWGSL = `struct DirectionalLightUniform {
to_light: vec4<f32>,
color: vec4<f32>,
}
struct PointLightUniform {
position_range: vec4<f32>,
color: vec4<f32>,
}
struct SpotLightUniform {
position_range: vec4<f32>,
direction_scale: vec4<f32>,
color_offset: vec4<f32>,
}
struct LightRigUniform {
ambient: vec4<f32>,
counts: vec4<u32>,
directional: array<DirectionalLightUniform, 4>,
point: array<PointLightUniform, 16>,
spot: array<SpotLightUniform, 8>,
}
@group(1) @binding(0) var<uniform> lights: LightRigUniform;
fn point_light_attenuation(dist_sq: f32, light_range: f32) -> f32 {
let inv_d2 = 1.0 / max(dist_sq, 1e-4);
if (light_range > 0.0) {
let ratio = sqrt(max(dist_sq, 0.0)) / light_range;
let ratio2 = ratio * ratio;
let window = clamp(1.0 - ratio2 * ratio2, 0.0, 1.0);
return inv_d2 * window * window;
}
return inv_d2;
}
fn spot_cone_attenuation(spot_dir: vec3<f32>, l: vec3<f32>, angle_scale: f32, angle_offset: f32) -> f32 {
let t = clamp(dot(spot_dir, -l) * angle_scale + angle_offset, 0.0, 1.0);
return t * t;
}
fn pbr_brdf(n: vec3<f32>, v: vec3<f32>, l: vec3<f32>, base_color: vec3<f32>, metallic: f32, roughness: f32) -> vec3<f32> {
let ndotl = dot(n, l);
let ndotv_raw = dot(n, v);
if (ndotl <= 0.0 || ndotv_raw <= 0.0) {
return vec3<f32>(0.0, 0.0, 0.0);
}
let ndotv = max(ndotv_raw, 1e-4);
let m = clamp(metallic, 0.0, 1.0);
let r = clamp(roughness, 0.045, 1.0);
let a = r * r;
let a2 = a * a;
let pi = 3.14159265;
let f0 = mix(vec3<f32>(0.04, 0.04, 0.04), base_color, m);
let h_raw = v + l;
let h_len2 = dot(h_raw, h_raw);
if (h_len2 <= 1e-8) {
return (vec3<f32>(1.0, 1.0, 1.0) - f0) * (1.0 - m) * base_color / pi;
}
let h = h_raw / sqrt(h_len2);
let ndoth = max(dot(n, h), 0.0);
let vdoth = max(dot(v, h), 0.0);
let denom = ndoth * ndoth * (a2 - 1.0) + 1.0;
let d = a2 / (pi * denom * denom);
let gv = ndotl * sqrt(ndotv * ndotv * (1.0 - a2) + a2);
let gl = ndotv * sqrt(ndotl * ndotl * (1.0 - a2) + a2);
let vis = 0.5 / max(gv + gl, 1e-6);
let t = clamp(1.0 - vdoth, 0.0, 1.0);
let t2 = t * t;
let f = f0 + (vec3<f32>(1.0, 1.0, 1.0) - f0) * (t2 * t2 * t);
let spec = d * vis * f;
let diff = (vec3<f32>(1.0, 1.0, 1.0) - f) * (1.0 - m) * base_color / pi;
return diff + spec;
}
fn shade_pbr_visibility(world_pos: vec3<f32>, normal: vec3<f32>, view_dir: vec3<f32>, base_color: vec3<f32>, metallic: f32, roughness: f32, shadow_vis: f32, point0_vis: f32, spot0_vis: f32) -> vec3<f32> {
let n = normalize(normal);
let v = normalize(view_dir);
var lo = lights.ambient.xyz * base_color;
let dir_count = lights.counts.x;
for (var di: u32 = 0u; di < 4u; di = di + 1u) {
if (di >= dir_count) {
break;
}
let dl = lights.directional[di];
let l = dl.to_light.xyz;
let ndotl = max(dot(n, l), 0.0);
var vis = 1.0;
if (di == 0u) {
vis = shadow_vis;
}
if (ndotl > 0.0) {
lo = lo + pbr_brdf(n, v, l, base_color, metallic, roughness) * dl.color.xyz * (ndotl * vis);
}
}
let pt_count = lights.counts.y;
for (var pi_idx: u32 = 0u; pi_idx < 16u; pi_idx = pi_idx + 1u) {
if (pi_idx >= pt_count) {
break;
}
let pl = lights.point[pi_idx];
let to_light = pl.position_range.xyz - world_pos;
let dist_sq = dot(to_light, to_light);
let atten = point_light_attenuation(dist_sq, pl.position_range.w);
if (atten > 0.0 && dist_sq > 1e-12) {
let l = to_light / sqrt(dist_sq);
let ndotl = max(dot(n, l), 0.0);
var pvis = 1.0;
if (pi_idx == 0u) {
pvis = point0_vis;
}
if (ndotl > 0.0) {
lo = lo + pbr_brdf(n, v, l, base_color, metallic, roughness) * (pl.color.xyz * atten * ndotl * pvis);
}
}
}
let spot_count = lights.counts.z;
for (var si: u32 = 0u; si < 8u; si = si + 1u) {
if (si >= spot_count) {
break;
}
let sl = lights.spot[si];
let to_light = sl.position_range.xyz - world_pos;
let dist_sq = dot(to_light, to_light);
if (dist_sq > 1e-12) {
let l = to_light / sqrt(dist_sq);
let atten = point_light_attenuation(dist_sq, sl.position_range.w) * spot_cone_attenuation(sl.direction_scale.xyz, l, sl.direction_scale.w, sl.color_offset.w);
let ndotl = max(dot(n, l), 0.0);
var svis = 1.0;
if (si == 0u) {
svis = spot0_vis;
}
if (atten > 0.0 && ndotl > 0.0) {
lo = lo + pbr_brdf(n, v, l, base_color, metallic, roughness) * (sl.color_offset.xyz * atten * ndotl * svis);
}
}
}
return lo;
}
fn shade_pbr_shadowed(world_pos: vec3<f32>, normal: vec3<f32>, view_dir: vec3<f32>, base_color: vec3<f32>, metallic: f32, roughness: f32, shadow_vis: f32) -> vec3<f32> {
return shade_pbr_visibility(world_pos, normal, view_dir, base_color, metallic, roughness, shadow_vis, 1.0, 1.0);
}
fn shade_pbr(world_pos: vec3<f32>, normal: vec3<f32>, view_dir: vec3<f32>, base_color: vec3<f32>, metallic: f32, roughness: f32) -> vec3<f32> {
return shade_pbr_shadowed(world_pos, normal, view_dir, base_color, metallic, roughness, 1.0);
}
` + linearToSRGBWGSLLightWGSL declares the scene lighting uniform block at @group(1) @binding(0) as the variable lights, along with portable glTF 2.0 metallic-roughness PBR shading helpers:
- point_light_attenuation(dist_sq, light_range) -> f32
- spot_cone_attenuation(spot_dir, l, angle_scale, angle_offset) -> f32
- pbr_brdf(n, v, l, base_color, metallic, roughness) -> vec3<f32>
- shade_pbr(world_pos, normal, view_dir, base_color, metallic, roughness) -> vec3<f32>
- shade_pbr_shadowed(world_pos, normal, view_dir, base_color, metallic, roughness, shadow_vis) -> vec3<f32>
- shade_pbr_visibility(world_pos, normal, view_dir, base_color, metallic, roughness, directional0_vis, point0_vis, spot0_vis) -> vec3<f32>
- linear_to_srgb_channel(c) -> f32
- linear_to_srgb(rgb) -> vec3<f32>
Prepend CameraWGSL and LightWGSL to any 3D shader that reads scene lights; the block's layout matches LightUniforms.Encode and LightRig.AppendUniformData byte for byte, and the shading math matches EvaluatePBR, ShadePoint, ShadePointShadowed, ShadePointVisibility, PointLightAttenuation, SpotConeAttenuation, and LinearToSRGB.
const LightmapWGSL = lightmapBodyWGSL + `
return vec4<f32>(linear_to_srgb(lit), albedo.a);
}
`LightmapWGSL is the WGSL shader module compiled by NewLightmapRenderer for a non-sRGB color target. It encodes the linear result with linear_to_srgb before writing, as LitPBRWGSL does, so lightmapped and PBR-lit draws in one pass match; for an sRGB target the renderer compiles a variant that leaves the encode to the hardware. It uses only pow and algebraic math (no exp/exp2/log2) so it executes identically across hardware GPU backends and NSGo's software GPU VM (nsgo-dev/nsgo#2334).
const LitPBRCSMWGSL = litPBRPreludeWGSL + CSMWGSL + litPBRCSMFragmentHeadWGSL + ` return vec4<f32>(linear_to_srgb(lit), pbr_draw.base_color.a);
}
`LitPBRCSMWGSL is LitPBRWGSL with cascaded directional shadows: the same vertex stage, bind groups CameraGroup, LightGroup and PBRDrawGroup, and lighting, plus CSMWGSL at CSMGroup. The fragment stage multiplies the first directional light of the LightRig (lights.directional[0]) by sample_csm_shadow and the lit color by csm_debug_tint before encoding to sRGB; every other light, the ambient term and emission are unshadowed. ShadePointShadowed with EvaluateCSMShadow as the visibility, times CSMFrame.DebugTint, is its CPU reference. Fit the cascades with that light's Direction. Use NewLitPBRCSMPipeline or LitPBRPipelineOptions.CSMLayout to create a pipeline from it.
const LitPBRColoredWGSL = litPBRColoredPreludeWGSL + litPBRColoredFragmentHeadWGSL + ` return vec4<f32>(linear_to_srgb(lit), (pbr_draw.base_color.a * in.color.a));
}
`LitPBRColoredWGSL is LitPBRWGSL taking ColoredVertexLayout vertices (@location(3) linear RGBA vertex color for glTF COLOR_0) and multiplying pbr_draw.base_color (both RGB and alpha) by in.color in linear space before PBR shading. NewLitPBRPipelineWithOptions compiles it (or the corresponding fog, IBL, shadow, spot-shadow, point-shadow, CSM, or linear-output variant) when LitPBRPipelineOptions.VertexColors is set.
const LitPBRFogWGSL = litPBRPreludeWGSL + FogWGSL + FogBindingWGSL + FogCameraWGSL + litPBRFragmentHeadWGSL + ` let fogged = apply_fog(lit, fog_camera_pos(in.world_pos), in.world_pos, fog);
return vec4<f32>(linear_to_srgb(fogged), pbr_draw.base_color.a);
}
`LitPBRFogWGSL is LitPBRWGSL with distance and height fog: the same vertex stage, bind groups CameraGroup, LightGroup and PBRDrawGroup, and lighting, plus a GPUFogBuffer at FogGroup. The fragment stage blends the lit linear color toward the fog color with FogWGSL's apply_fog from FogCameraWGSL's ray origin before encoding to sRGB. Use NewLitPBRFogPipeline to create a pipeline from it.
const LitPBRIBLWGSL = litPBRPreludeWGSL + "\n" + IBLWGSL + litPBRFragmentHeadWGSL + ` let ibl_lit = lit + evaluate_ibl(in.world_normal, view_dir, pbr_draw.base_color.rgb, pbr_draw.pbr_params.x, pbr_draw.pbr_params.y, 1.0);
return vec4<f32>(linear_to_srgb(ibl_lit), pbr_draw.base_color.a);
}
`LitPBRIBLWGSL is LitPBRWGSL with image-based lighting: the same vertex stage, bind groups CameraGroup, LightGroup and PBRDrawGroup, and direct lighting, plus a GPUIBLBuffer at IBLGroup. The fragment stage adds IBLWGSL's evaluate_ibl (diffuse spherical harmonic irradiance and prefiltered specular, with ambient occlusion 1) to the directly lit color before encoding to sRGB, so ShadePoint plus EvaluateIBL reproduces it on the CPU. Set the LightRig's ambient light to zero when the environment provides the ambient term. Use NewLitPBRIBLPipeline to create a pipeline from it.
IBL and fog both use bind group 3 (IBLGroup and FogGroup), the last of the four groups every backend guarantees, so this module has no fog.
const LitPBRPointShadowWGSL = litPBRPreludeWGSL + PointShadowWGSL + litPBRPointShadowFragmentHeadWGSL + ` return vec4<f32>(linear_to_srgb(lit), pbr_draw.base_color.a);
}
`LitPBRPointShadowWGSL is LitPBRWGSL with a point light shadow: the same vertex stage, bind groups and lighting, plus PointShadowWGSL at LocalShadowGroup. The fragment stage multiplies the first point light of the LightRig (lights.point[0]) by sample_point_shadow; every other light, the ambient term and emission are unshadowed. ShadePointVisibility with Point0 set is its CPU reference. Use NewLitPBRPointShadowPipeline or LitPBRPipelineOptions.PointShadowLayout to create a pipeline from it.
const LitPBRProbeIBLWGSL = litPBRPreludeWGSL + "\n" + ProbeIBLWGSL + litPBRFragmentHeadWGSL + ` let ibl_lit = lit + evaluate_probe_ibl(in.world_pos, in.world_normal, view_dir, pbr_draw.base_color.rgb, pbr_draw.pbr_params.x, pbr_draw.pbr_params.y, 1.0);
return vec4<f32>(linear_to_srgb(ibl_lit), pbr_draw.base_color.a);
}
`LitPBRProbeIBLWGSL is LitPBRWGSL extended with local reflection probes and interpolated light-probe irradiance at IBLGroup (group 3). It keeps the exact vertex stage (including the inverse-transpose normal matrix), LightRig direct lighting, emissive term, and IEC 61966-2-1 sRGB output encode of LitPBRWGSL and LitPBRIBLWGSL, adding evaluate_probe_ibl before linear_to_srgb so ShadePoint plus EvaluateProbeIBL reproduces it on the CPU.
Set the LightRig's ambient light to zero when probes or the sky supply the ambient term. Use NewLitPBRProbeIBLPipeline or NewLitPBRProbeIBLPipelineWithOptions to build a pipeline from it.
const LitPBRShadowWGSL = litPBRPreludeWGSL + ShadowWGSL + litPBRShadowFragmentHeadWGSL + ` return vec4<f32>(linear_to_srgb(lit), pbr_draw.base_color.a);
}
`LitPBRShadowWGSL is LitPBRWGSL with a directional shadow: the same vertex stage, bind groups CameraGroup, LightGroup and PBRDrawGroup, and lighting, plus ShadowWGSL at ShadowGroup. The fragment stage multiplies the first directional light of the LightRig (lights.directional[0]) by sample_directional_shadow before encoding to sRGB; every other light, the ambient term and emission are unshadowed. ShadePointShadowed is its CPU reference. Use NewLitPBRShadowPipeline or LitPBRPipelineOptions.ShadowLayout to create a pipeline from it.
const LitPBRSkinnedWGSL = litPBRSkinnedPreludeWGSL + litPBRFragmentHeadWGSL + ` return vec4<f32>(linear_to_srgb(lit), pbr_draw.base_color.a);
}
`LitPBRSkinnedWGSL is LitPBRWGSL for GPUSkinnedMesh vertices (SkinnedVertexLayout): it binds the joint palette at LitPBRSkinGroup (group 3) and shades with the scene lights at LightGroup and the per-draw PBRDrawUniform at PBRDrawGroup. NewLitPBRPipelineWithOptions compiles it when LitPBRPipelineOptions.SkinLayout is set.
const LitPBRSpotShadowWGSL = litPBRPreludeWGSL + SpotShadowWGSL + litPBRSpotShadowFragmentHeadWGSL + ` return vec4<f32>(linear_to_srgb(lit), pbr_draw.base_color.a);
}
`LitPBRSpotShadowWGSL is LitPBRWGSL with a spot light shadow: the same vertex stage (per-draw model and normal matrices from PBRDrawUniform), bind groups CameraGroup, LightGroup and PBRDrawGroup, and lighting, plus SpotShadowWGSL at LocalShadowGroup. The fragment stage multiplies the first spot light of the LightRig (lights.spot[0]) by sample_spot_shadow; every other light, the ambient term and emission are unshadowed. ShadePointVisibility with Spot0 set is its CPU reference. Use NewLitPBRSpotShadowPipeline or LitPBRPipelineOptions.SpotShadowLayout to create a pipeline from it.
const LitPBRWGSL = litPBRPreludeWGSL + litPBRFragmentHeadWGSL + ` return vec4<f32>(linear_to_srgb(lit), pbr_draw.base_color.a);
}
`LitPBRWGSL is a complete, portable metallic-roughness PBR WGSL module built on CameraWGSL, LightWGSL, MeshVertexLayout, and a per-draw PBRDrawUniform at PBRDrawGroup. Entry points are vs_main and fs_main; use NewLitPBRPipeline to create a pipeline from it. LitPBRFogWGSL is the same module with fog, and LitPBRColoredWGSL is the ColoredVertexLayout variant with glTF COLOR_0 vertex colors.
const MaterialBindingsWGSL = `struct MaterialUniforms {
base_color_factor: vec4<f32>,
emissive_factor: vec4<f32>,
params: vec4<f32>,
flags: vec4<f32>,
}
@group(1) @binding(0) var<uniform> material: MaterialUniforms;
@group(1) @binding(1) var base_color_tex: texture_2d<f32>;
@group(1) @binding(2) var base_color_samp: sampler;
@group(1) @binding(3) var metallic_roughness_tex: texture_2d<f32>;
@group(1) @binding(4) var metallic_roughness_samp: sampler;
@group(1) @binding(5) var normal_tex: texture_2d<f32>;
@group(1) @binding(6) var normal_samp: sampler;
@group(1) @binding(7) var occlusion_tex: texture_2d<f32>;
@group(1) @binding(8) var occlusion_samp: sampler;
@group(1) @binding(9) var emissive_tex: texture_2d<f32>;
@group(1) @binding(10) var emissive_samp: sampler;
fn pbr_pow5(x: f32) -> f32 {
let c = clamp(x, 0.0, 1.0);
let c2 = c * c;
return c2 * c2 * c;
}
// material_perturb_normal builds an API-independent tangent frame from precomputed screen-space derivatives (Cramer's rule on dp1/dp2/duv1/duv2) and falls back to a deterministic orthonormal frame from geom_n when derivatives or UVs are degenerate (such as meshes without UVs or software rendering).
fn material_perturb_normal(
geom_n: vec3<f32>,
dp1: vec3<f32>,
dp2: vec3<f32>,
duv1: vec2<f32>,
duv2: vec2<f32>,
normal_sample: vec3<f32>,
normal_scale: f32,
) -> vec3<f32> {
var up_ref = vec3<f32>(0.0, 1.0, 0.0);
if (geom_n.y > 0.99) {
up_ref = vec3<f32>(0.0, 0.0, -1.0);
} else if (geom_n.y < -0.99) {
up_ref = vec3<f32>(0.0, 0.0, 1.0);
}
var t_vec = normalize(cross(up_ref, geom_n));
var b_vec = cross(geom_n, t_vec);
let det = duv1.x * duv2.y - duv1.y * duv2.x;
if (abs(det) > 1e-10) {
let inv_det = 1.0 / det;
let t_raw = (dp1 * duv2.y - dp2 * duv1.y) * inv_det;
let b_dv = (dp2 * duv1.x - dp1 * duv2.x) * inv_det;
let t_ortho = t_raw - geom_n * dot(geom_n, t_raw);
let b_raw = -b_dv;
let b_ortho = b_raw - geom_n * dot(geom_n, b_raw);
if (dot(t_ortho, t_ortho) > 1e-10 && dot(b_ortho, b_ortho) > 1e-10) {
t_vec = normalize(t_ortho);
b_vec = normalize(b_ortho);
}
}
let n_unpacked = normal_sample * 2.0 - vec3<f32>(1.0, 1.0, 1.0);
let n_ts = normalize(vec3<f32>(n_unpacked.x * normal_scale, n_unpacked.y * normal_scale, n_unpacked.z));
return normalize(t_vec * n_ts.x + b_vec * n_ts.y + geom_n * n_ts.z);
}
// pbr_metallic_roughness_direct evaluates glTF 2.0 metallic-roughness Cook-Torrance GGX (Trowbridge-Reitz D, height-correlated Smith-GGX Visibility, Schlick Fresnel, energy-conserving Lambertian diffuse) for one directional light.
fn pbr_metallic_roughness_direct(
n: vec3<f32>,
v: vec3<f32>,
l: vec3<f32>,
light_color: vec3<f32>,
base_color: vec3<f32>,
metallic: f32,
roughness: f32,
) -> vec3<f32> {
let ndl = max(dot(n, l), 0.0);
if (ndl <= 0.0) {
return vec3<f32>(0.0, 0.0, 0.0);
}
let ndv = max(dot(n, v), 1e-4);
let h = normalize(v + l);
let ndh = max(dot(n, h), 0.0);
let vdh = max(dot(v, h), 0.0);
let alpha = roughness * roughness;
let alpha2 = alpha * alpha;
let f0 = mix(vec3<f32>(0.04, 0.04, 0.04), base_color, metallic);
let pi = 3.14159265359;
let denom = ndh * ndh * (alpha2 - 1.0) + 1.0;
let d_term = alpha2 / max(pi * denom * denom, 1e-7);
let ggx_v = ndl * sqrt(ndv * ndv * (1.0 - alpha2) + alpha2);
let ggx_l = ndv * sqrt(ndl * ndl * (1.0 - alpha2) + alpha2);
let vis = 0.5 / max(ggx_v + ggx_l, 1e-5);
let f_term = f0 + (vec3<f32>(1.0, 1.0, 1.0) - f0) * pbr_pow5(1.0 - vdh);
let spec = f_term * (d_term * vis);
let diff = (vec3<f32>(1.0, 1.0, 1.0) - f_term) * (1.0 - metallic) * base_color * (1.0 / pi);
return (diff + spec) * light_color * ndl;
}
// pbr_metallic_roughness_ambient evaluates an analytic hemisphere diffuse + roughness-filtered specular ambient contribution scaled by ambient occlusion.
fn pbr_metallic_roughness_ambient(
n: vec3<f32>,
v: vec3<f32>,
sky_color: vec3<f32>,
ground_color: vec3<f32>,
base_color: vec3<f32>,
metallic: f32,
roughness: f32,
occlusion: f32,
) -> vec3<f32> {
let ndv = max(dot(n, v), 1e-4);
let f0 = mix(vec3<f32>(0.04, 0.04, 0.04), base_color, metallic);
let f_max = max(vec3<f32>(1.0 - roughness, 1.0 - roughness, 1.0 - roughness), f0);
let f_amb = f0 + (f_max - f0) * pbr_pow5(1.0 - ndv);
let sky_t = clamp(n.y * 0.5 + 0.5, 0.0, 1.0);
let amb_env = mix(ground_color, sky_color, sky_t);
let amb_diff = (vec3<f32>(1.0, 1.0, 1.0) - f_amb) * (1.0 - metallic) * base_color * amb_env;
let refl = reflect(-v, n);
let refl_t = clamp(refl.y * 0.5 + 0.5, 0.0, 1.0);
let refl_env = mix(ground_color, sky_color, mix(refl_t, 0.5, roughness * roughness));
let amb_spec = refl_env * f_amb * (1.0 - 0.5 * roughness);
return (amb_diff + amb_spec) * occlusion;
}
fn material_tonemap_srgb(linear_rgb: vec3<f32>) -> vec3<f32> {
let c = max(linear_rgb, vec3<f32>(0.0, 0.0, 0.0));
let mapped = c / (c + vec3<f32>(1.0, 1.0, 1.0));
return pow(clamp(mapped, vec3<f32>(0.0, 0.0, 0.0), vec3<f32>(1.0, 1.0, 1.0)), vec3<f32>(1.0 / 2.2, 1.0 / 2.2, 1.0 / 2.2));
}
`MaterialBindingsWGSL declares MaterialGroup (group 1) uniform/texture/sampler bindings together with portable glTF 2.0 metallic-roughness Cook-Torrance GGX shading and cotangent-frame normal-mapping helpers. Prepend CameraWGSL and MaterialBindingsWGSL to build custom lighting shaders that share GPUMaterial.
const MaterialColoredWGSL = CameraWGSL + MaterialBindingsWGSL + materialColoredStagesHeadWGSL + ` let srgb_rgb = material_tonemap_srgb(linear_rgb);
` + materialStagesTailWGSLMaterialColoredWGSL is MaterialWGSL taking ColoredVertexLayout vertices (@location(3) linear RGBA color for glTF COLOR_0) and multiplying base_color (base_color_factor * base_sample) by in.color in linear space (both RGB and alpha) before alpha-mask discard and PBR shading. NewMaterialPipeline compiles it when MaterialPipelineOptions.VertexColors is set.
const MaterialFogBindingWGSL = `@group(2) @binding(0) var<uniform> fog: Fog;
`MaterialFogBindingWGSL declares the Fog uniform binding at @group(2) @binding(0) as the variable fog, matching MaterialFogGroup and GPUFogBuffer. Prepend FogWGSL first.
const MaterialFogWGSL = CameraWGSL + MaterialBindingsWGSL + FogWGSL + MaterialFogBindingWGSL + FogCameraWGSL + materialStagesHeadWGSL + ` let srgb_rgb = material_tonemap_srgb(apply_fog(linear_rgb, fog_camera_pos(in.world_pos), in.world_pos, fog));
` + materialStagesTailWGSLMaterialFogWGSL is MaterialWGSL with distance and height fog: the same vertex stage, bind groups CameraGroup and MaterialGroup, and shading, plus a GPUFogBuffer at MaterialFogGroup. The fragment stage blends the linear radiance toward the fog color with FogWGSL's apply_fog from FogCameraWGSL's ray origin, then tone-maps and encodes it as MaterialWGSL does, so the fog color is tone-mapped with the scene. NewMaterialPipeline compiles it when MaterialPipelineOptions.FogLayout is set.
const MaterialGroup = 1MaterialGroup is the bind group index reserved for metallic-roughness materials alongside CameraGroup (group 0). GPUMaterial.Bind binds at this slot, and MaterialBindingsWGSL / MaterialWGSL declare every material binding there.
const MaterialIBLGroup = 2MaterialIBLGroup is the bind group index MaterialIBLWGSL and MaterialIBLLinearWGSL reserve for image-based lighting (GPUIBLBuffer.BindGroup), after CameraGroup (group 0) and MaterialGroup (group 1).
const MaterialIBLLinearWGSL = CameraWGSL + MaterialBindingsWGSL + "\n" + materialIBLDeclWGSL + materialVertexStageWGSL + materialIBLFragmentHeadWGSL + ` let srgb_rgb = linear_rgb;
` + materialStagesTailWGSLMaterialIBLLinearWGSL is MaterialIBLWGSL writing unclamped linear HDR radiance without tone mapping or gamma encoding, compiled by NewMaterialIBLPipeline when MaterialIBLPipelineOptions.LinearOutput is set for rendering into an HDRTarget resolved by ToneMapPass.
const MaterialIBLWGSL = CameraWGSL + MaterialBindingsWGSL + "\n" + materialIBLDeclWGSL + materialVertexStageWGSL + materialIBLFragmentHeadWGSL + ` let srgb_rgb = material_tonemap_srgb(linear_rgb);
` + materialStagesTailWGSLMaterialIBLWGSL is the textured glTF 2.0 metallic-roughness PBR shader driven by image-based lighting: CameraWGSL at CameraGroup (group 0), MaterialBindingsWGSL at MaterialGroup (group 1), and a GPUIBLBuffer at MaterialIBLGroup (group 2). It evaluates all five glTF maps (base color, metallic-roughness, tangent-space normal, occlusion, emissive), alpha masking/blending, double-sided normal flipping, and split-sum IBL (L2 SH diffuse irradiance + GGX prefiltered specular), followed by Reinhard tone mapping and gamma 2.2 encoding. Use NewMaterialIBLPipeline to create a pipeline from it.
const MaterialSkinnedWGSL = materialSkinnedHeadWGSL + ` let srgb_rgb = material_tonemap_srgb(linear_rgb);
` + materialStagesTailWGSLMaterialSkinnedWGSL is MaterialWGSL for GPUSkinnedMesh vertices (SkinnedVertexLayout): it binds the joint palette at MaterialSkinGroup (group 2) next to a GPUMaterial at MaterialGroup, so a skinned glTF character draws with its textures. NewMaterialPipeline compiles it when MaterialPipelineOptions.SkinLayout is set.
const MaterialUniformSize = 64MaterialUniformSize is the byte size of the 16-byte-aligned uniform block MaterialUniforms.AppendUniformData and MaterialUniforms.Encode write, matching struct MaterialUniforms in MaterialBindingsWGSL.
const MaterialWGSL = CameraWGSL + MaterialBindingsWGSL + materialStagesHeadWGSL + ` let srgb_rgb = material_tonemap_srgb(linear_rgb);
` + materialStagesTailWGSLMaterialWGSL is the complete portable WGSL shader module compiled by NewMaterialPipeline, combining CameraWGSL at CameraGroup (group 0), MaterialBindingsWGSL at MaterialGroup (group 1), MeshVertexLayout inputs, tangent-space normal mapping, glTF 2.0 metallic-roughness Cook-Torrance GGX shading under DefaultMaterialLight, alpha masking/blending, and double-sided normal flipping.
const (
// MaxSpotLights is the maximum number of spot lights a [LightRig] encodes into the GPU uniform block.
MaxSpotLights = 8
)const PBRLightmapBindingsWGSL = pbrLightmapUniformStructWGSL + `@group(3) @binding(0) var<uniform> pbr_lm: PBRLightmapUniform;
@group(3) @binding(1) var pbr_lightmap_tex: texture_2d<f32>;
@group(3) @binding(2) var pbr_lightmap_samp: sampler;
` + pbrLightmapDecodeWGSLPBRLightmapBindingsWGSL declares the PBRLightmapGroup (@group(3)) uniform buffer, lightmap texture, and lightmap sampler together with pbr_decode_lightmap and shade_pbr_direct. Prepend CameraWGSL, LightWGSL, and MaterialBindingsWGSLForGroup(2) before it.
const PointShadowWGSL = pointShadowStructWGSL + `
@group(3) @binding(0) var<uniform> point_shadow: PointShadow;
@group(3) @binding(1) var point_shadow_map: texture_depth_2d;
@group(3) @binding(2) var point_shadow_sampler: sampler_comparison;
` + pointShadowSampleFnWGSLPointShadowWGSL declares the point shadow uniform block, 3x2 depth atlas and comparison sampler at LocalShadowGroup (@group(3)) and the portable sample_point_shadow(world_pos, world_normal) helper returning the point light's visibility in [0, 1]. It equals PointShadowWGSLForGroup(LocalShadowGroup). All six cube faces live in one texture_depth_2d atlas with per-tile UV clamping, so sampling and 3x3 PCF work on every NSGo backend without depth cube maps. LitPBRPointShadowWGSL is the ready-made PBR shader built on it.
const ProbeIBLWGSL = probeIBLWGSLDecl3 + probeIBLWGSLFuncsProbeIBLWGSL declares the reflection-probe and light-probe IBL uniform block, two local reflection cubemaps, sky cubemap, and trilinear sampler at IBLGroup (@group(3)), together with box_project_dir, evaluate_probe_irradiance_sh, sample_probe_specular, and evaluate_probe_ibl.
Prepend it to a PBR fragment shader whose pipeline binds GPUProbeIBLBuffer.BindGroup at IBLGroup; LitPBRProbeIBLWGSL does this for LitPBRWGSL. Use ProbeIBLWGSLForGroup when a custom shader places the bindings at another group.
const ShadowDepthWGSL = `struct ShadowCasterUniform {
light_mvp: mat4x4<f32>,
}
@group(0) @binding(0) var<uniform> shadow_caster: ShadowCasterUniform;
struct ShadowVertexIn {
@location(0) pos: vec3<f32>,
}
@vertex
fn vs_shadow(in: ShadowVertexIn) -> @builtin(position) vec4<f32> {
return shadow_caster.light_mvp * vec4<f32>(in.pos, 1.0);
}
`ShadowDepthWGSL is the depth-only caster vertex shader used by DirectionalShadowMap. It transforms MeshVertexLayout position attributes (@location(0)) by shadow_caster.light_mvp at @group(0) @binding(0). Entry point: "vs_shadow".
const ShadowWGSL = shadowStructWGSL + `
@group(3) @binding(0) var<uniform> shadow: ShadowUniforms;
@group(3) @binding(1) var shadow_map: texture_depth_2d;
@group(3) @binding(2) var shadow_sampler: sampler_comparison;
` + shadowSampleFnWGSLShadowWGSL declares the directional shadow uniform block, depth map and comparison sampler at ShadowGroup (@group(3)), and the portable sample_directional_shadow(world_pos, world_normal) helper returning directional light visibility in [0, 1]. It equals ShadowWGSLForGroup(ShadowGroup). Prepend CameraWGSL and ShadowWGSL to a custom 3D lit shader to add directional shadows without compute shaders or backend-specific intrinsics; LitPBRShadowWGSL is the ready-made PBR shader built on it.
const SkinWGSL = skinPaletteStructWGSL + "@group(1) @binding(0) var<uniform> skin: SkinPalette;\n" + skinFunctionsWGSLSkinWGSL declares the portable joint palette uniform block at @group(1) @binding(0) (SkinGroup) and linear blend skinning helpers matching CPU SkinVertex. Prepend CameraWGSL and SkinWGSL to a custom skinned vertex shader that binds nothing else at group 1, or use SkinnedMeshWGSL via NewSkinnedMeshPipeline. To draw a skinned mesh with lights or a material, use LitPBRPipelineOptions.SkinLayout or MaterialPipelineOptions.SkinLayout, which declare the same helpers at LitPBRSkinGroup and MaterialSkinGroup.
Blending is evaluated per influence as sum_i (skin.joints[j_i] * v) * w_i rather than summing scaled 4x4 matrices first, which is both fewer scalar operations on GPU hardware and exact across every NSGo backend (Metal, D3D11, OpenGL 3.3, WebGPU, WebGL 2, OpenGL ES 3.0, and the software rasterizer).
const SkinnedMeshWGSL = CameraWGSL + "\n" + SkinWGSL + skinnedVertexInWGSL + `
struct SkinnedVertexOut {
@builtin(position) clip: vec4<f32>,
@location(0) world: vec3<f32>,
@location(1) normal: vec3<f32>,
@location(2) uv: vec2<f32>,
}
@vertex
fn vs_main(in: SkinnedVertexIn) -> SkinnedVertexOut {
var out: SkinnedVertexOut;
let world_pos = skin_position(in.pos, in.joints, in.weights);
let world_nrm = skin_normal(in.normal, in.joints, in.weights);
out.clip = camera.view_proj * vec4<f32>(world_pos, 1.0);
out.world = world_pos;
out.normal = world_nrm;
out.uv = in.uv;
return out;
}
@fragment
fn fs_main(in: SkinnedVertexOut) -> @location(0) vec4<f32> {
var n = vec3<f32>(0.0, 1.0, 0.0);
if (dot(in.normal, in.normal) > 1e-12) {
n = normalize(in.normal);
}
let v = normalize(camera.eye.xyz - in.world * camera.eye.w);
let ndotl = max(dot(n, v), 0.0);
let shade = 0.25 + 0.75 * ndotl;
let base = vec3<f32>(0.55 + 0.25 * n.x, 0.55 + 0.25 * n.y, 0.6 + 0.25 * n.z);
return vec4<f32>(base * shade, 1.0);
}
`SkinnedMeshWGSL is the default ready-to-use WGSL module compiled by NewSkinnedMeshPipeline. It binds CameraBuffer at CameraGroup (group 0) and GPUSkinPalette at SkinGroup (group 1), skins positions and normals with SkinWGSL, and applies view-aligned shading with normal-based coloring. It has no lights or materials; use LitPBRSkinnedWGSL or MaterialSkinnedWGSL for those.
const SkyboxToneMapWGSL = `struct SkyboxParams {
inv_view_proj: mat4x4<f32>,
exposure: f32,
lod: f32,
_pad0: f32,
_pad1: f32,
}
@group(0) @binding(0) var<uniform> skybox: SkyboxParams;
@group(0) @binding(1) var skybox_tex: texture_cube<f32>;
@group(0) @binding(2) var skybox_sampler: sampler;
struct SkyboxVertexOut {
@builtin(position) pos: vec4<f32>,
@location(0) dir: vec3<f32>,
}
@vertex
fn vs_skybox(@builtin(vertex_index) vid: u32) -> SkyboxVertexOut {
var ndc = vec2<f32>(-1.0, -1.0);
if (vid == 1u) {
ndc = vec2<f32>(3.0, -1.0);
} else if (vid == 2u) {
ndc = vec2<f32>(-1.0, 3.0);
}
let world = skybox.inv_view_proj * vec4<f32>(ndc, 1.0, 1.0);
var out: SkyboxVertexOut;
out.pos = vec4<f32>(ndc, 1.0, 1.0);
out.dir = world.xyz;
return out;
}
@fragment
fn fs_skybox(in: SkyboxVertexOut) -> @location(0) vec4<f32> {
let dir = normalize(in.dir);
let sampled = textureSampleLevel(skybox_tex, skybox_sampler, dir, skybox.lod);
let c = max(sampled.rgb * skybox.exposure, vec3<f32>(0.0, 0.0, 0.0));
let mapped = c / (c + vec3<f32>(1.0, 1.0, 1.0));
let srgb = pow(clamp(mapped, vec3<f32>(0.0, 0.0, 0.0), vec3<f32>(1.0, 1.0, 1.0)), vec3<f32>(1.0 / 2.2, 1.0 / 2.2, 1.0 / 2.2));
return vec4<f32>(srgb, 1.0);
}
`SkyboxToneMapWGSL is SkyboxWGSL with Reinhard tone mapping and gamma 2.2 encoding applied after exposure, matching MaterialWGSL and MaterialIBLWGSL so an HDR GPUCubemap draws consistently directly to an LDR render target. NewSkyboxPipeline compiles it when SkyboxPipelineDesc.ToneMap is true.
const SkyboxWGSL = `struct SkyboxParams {
inv_view_proj: mat4x4<f32>,
exposure: f32,
lod: f32,
_pad0: f32,
_pad1: f32,
}
@group(0) @binding(0) var<uniform> skybox: SkyboxParams;
@group(0) @binding(1) var skybox_tex: texture_cube<f32>;
@group(0) @binding(2) var skybox_sampler: sampler;
struct SkyboxVertexOut {
@builtin(position) pos: vec4<f32>,
@location(0) dir: vec3<f32>,
}
@vertex
fn vs_skybox(@builtin(vertex_index) vid: u32) -> SkyboxVertexOut {
var ndc = vec2<f32>(-1.0, -1.0);
if (vid == 1u) {
ndc = vec2<f32>(3.0, -1.0);
} else if (vid == 2u) {
ndc = vec2<f32>(-1.0, 3.0);
}
let world = skybox.inv_view_proj * vec4<f32>(ndc, 1.0, 1.0);
var out: SkyboxVertexOut;
out.pos = vec4<f32>(ndc, 1.0, 1.0);
out.dir = world.xyz;
return out;
}
@fragment
fn fs_skybox(in: SkyboxVertexOut) -> @location(0) vec4<f32> {
let dir = normalize(in.dir);
let sampled = textureSampleLevel(skybox_tex, skybox_sampler, dir, skybox.lod);
return vec4<f32>(sampled.rgb * skybox.exposure, 1.0);
}
`SkyboxWGSL renders a cubemap as an infinitely distant background using a single fullscreen triangle driven by @builtin(vertex_index) (zero vertex buffers). It emits depth z = 1.0, the far plane, so a pipeline with gpu.CompareLessEqual and DepthWrite disabled draws the skybox after opaque geometry without shading occluded pixels: it passes only where the depth buffer still holds its clear value of 1.0, and paints over no geometry nearer than the far plane.
const SpotShadowWGSL = spotShadowStructWGSL + `
@group(3) @binding(0) var<uniform> spot_shadow: SpotShadow;
@group(3) @binding(1) var spot_shadow_map: texture_depth_2d;
@group(3) @binding(2) var spot_shadow_sampler: sampler_comparison;
` + spotShadowSampleFnWGSLSpotShadowWGSL declares the spot shadow uniform block, depth map and comparison sampler at LocalShadowGroup (@group(3)) and the portable sample_spot_shadow(world_pos, world_normal) helper returning the spot light's visibility in [0, 1]. It equals SpotShadowWGSLForGroup(LocalShadowGroup). LitPBRSpotShadowWGSL is the ready-made PBR shader built on it; a custom lit shader multiplies its spot light's contribution by the helper's result, for example through shade_pbr_visibility in LightWGSL. It uses only textureSampleCompareLevel, so it runs on every NSGo backend, the WebGL 2 / GLES 3 profile and the software renderer included.
const TerrainMaterialBindingsWGSL = `struct TerrainLayerUniform {
color_metallic: vec4<f32>,
pbr_params: vec4<f32>,
uv_params: vec4<f32>,
}
struct TerrainMaterialUniforms {
model: mat4x4<f32>,
normal_matrix: mat4x4<f32>,
params: vec4<f32>,
triplanar_params: vec4<f32>,
layers: array<TerrainLayerUniform, 8>,
}
@group(2) @binding(0) var<uniform> terrain: TerrainMaterialUniforms;
@group(2) @binding(1) var terrain_splat0_tex: texture_2d<f32>;
@group(2) @binding(2) var terrain_splat1_tex: texture_2d<f32>;
@group(2) @binding(3) var terrain_splat_samp: sampler;
@group(2) @binding(4) var terrain_albedo_arr: texture_2d_array<f32>;
@group(2) @binding(5) var terrain_normal_arr: texture_2d_array<f32>;
@group(2) @binding(6) var terrain_mrh_arr: texture_2d_array<f32>;
@group(2) @binding(7) var terrain_layer_samp: sampler;
fn terrain_splat_weight(s0: vec4<f32>, s1: vec4<f32>, idx: u32) -> f32 {
if (idx == 0u) {
return s0.x;
}
if (idx == 1u) {
return s0.y;
}
if (idx == 2u) {
return s0.z;
}
if (idx == 3u) {
return s0.w;
}
if (idx == 4u) {
return s1.x;
}
if (idx == 5u) {
return s1.y;
}
if (idx == 6u) {
return s1.z;
}
return s1.w;
}
fn terrain_set_channel(v: vec4<f32>, ch: u32, val: f32) -> vec4<f32> {
if (ch == 0u) {
return vec4<f32>(val, v.y, v.z, v.w);
}
if (ch == 1u) {
return vec4<f32>(v.x, val, v.z, v.w);
}
if (ch == 2u) {
return vec4<f32>(v.x, v.y, val, v.w);
}
return vec4<f32>(v.x, v.y, v.z, val);
}
fn terrain_triplanar_factor(geom_n: vec3<f32>, enabled: f32, threshold: f32, blend_w: f32) -> f32 {
if (enabled <= 0.5) {
return 0.0;
}
let up = clamp(abs(geom_n.y), 0.0, 1.0);
let half_b = max(blend_w, 0.001) * 0.5;
let lo = clamp(threshold - half_b, 0.0, 1.0);
let hi = clamp(threshold + half_b, lo + 0.001, 1.0);
let t = clamp((hi - up) / (hi - lo), 0.0, 1.0);
return t * t * (3.0 - 2.0 * t);
}
fn terrain_triplanar_weights(geom_n: vec3<f32>, sharpness: f32) -> vec3<f32> {
let an = max(abs(geom_n), vec3<f32>(0.0001, 0.0001, 0.0001));
let sh = max(sharpness, 0.5);
let pw = pow(an, vec3<f32>(sh, sh, sh));
let sum = max(pw.x + pw.y + pw.z, 1e-6);
return pw / sum;
}
fn terrain_perturb_normal(
geom_n: vec3<f32>,
dp1: vec3<f32>,
dp2: vec3<f32>,
duv1: vec2<f32>,
duv2: vec2<f32>,
normal_sample: vec3<f32>,
normal_scale: f32,
) -> vec3<f32> {
var up_ref = vec3<f32>(0.0, 1.0, 0.0);
if (geom_n.y > 0.99) {
up_ref = vec3<f32>(0.0, 0.0, -1.0);
} else if (geom_n.y < -0.99) {
up_ref = vec3<f32>(0.0, 0.0, 1.0);
}
var t_vec = normalize(cross(up_ref, geom_n));
var b_vec = cross(geom_n, t_vec);
let det = duv1.x * duv2.y - duv1.y * duv2.x;
if (abs(det) > 1e-10) {
let inv_det = 1.0 / det;
let t_raw = (dp1 * duv2.y - dp2 * duv1.y) * inv_det;
let b_dv = (dp2 * duv1.x - dp1 * duv2.x) * inv_det;
let t_ortho = t_raw - geom_n * dot(geom_n, t_raw);
let b_raw = -b_dv;
let b_ortho = b_raw - geom_n * dot(geom_n, b_raw);
if (dot(t_ortho, t_ortho) > 1e-10 && dot(b_ortho, b_ortho) > 1e-10) {
t_vec = normalize(t_ortho);
b_vec = normalize(b_ortho);
}
}
let n_unpacked = normal_sample * 2.0 - vec3<f32>(1.0, 1.0, 1.0);
let n_ts = normalize(vec3<f32>(n_unpacked.x * normal_scale, n_unpacked.y * normal_scale, n_unpacked.z));
return normalize(t_vec * n_ts.x + b_vec * n_ts.y + geom_n * n_ts.z);
}
fn terrain_triplanar_normal(
geom_n: vec3<f32>,
nx_sample: vec3<f32>,
ny_sample: vec3<f32>,
nz_sample: vec3<f32>,
normal_scale: f32,
tw: vec3<f32>,
) -> vec3<f32> {
let ux = nx_sample * 2.0 - vec3<f32>(1.0, 1.0, 1.0);
let uy = ny_sample * 2.0 - vec3<f32>(1.0, 1.0, 1.0);
let uz = nz_sample * 2.0 - vec3<f32>(1.0, 1.0, 1.0);
let n_x = normalize(vec3<f32>(ux.x * normal_scale, ux.y * normal_scale, ux.z));
let n_y = normalize(vec3<f32>(uy.x * normal_scale, uy.y * normal_scale, uy.z));
let n_z = normalize(vec3<f32>(uz.x * normal_scale, uz.y * normal_scale, uz.z));
// Whiteout-style per-axis world normal blending: preserves geom_n exactly on flat maps.
let wx = normalize(vec3<f32>(geom_n.x * n_x.z, geom_n.y + n_x.y, geom_n.z + n_x.x));
let wy = normalize(vec3<f32>(geom_n.x + n_y.x, geom_n.y * n_y.z, geom_n.z - n_y.y));
let wz = normalize(vec3<f32>(geom_n.x + n_z.x, geom_n.y + n_z.y, geom_n.z * n_z.z));
return normalize(wx * tw.x + wy * tw.y + wz * tw.z);
}
`TerrainMaterialBindingsWGSL declares the TerrainMaterialGroup (@group(2)) uniform buffer, splat maps, 2D texture arrays, samplers, and portable helper functions (with every helper declared before its callers for MSL/WGSL compatibility).
const TerrainMaterialCSMWGSL = terrainPreludeWGSL + CSMWGSL + terrainFragmentBlendWGSL + ` let view_depth = csm_view_depth(in.world_pos);
let shadow_vis = csm_shadow_factor(in.world_pos, geom_n, view_depth);
let lit = shade_pbr_shadowed(in.world_pos, n, view_dir, blend_albedo, blend_metallic, blend_roughness, shadow_vis) * csm_debug_tint(in.world_pos);
return vec4<f32>(linear_to_srgb(lit), 1.0);
}
`TerrainMaterialCSMWGSL is TerrainMaterialWGSL with cascaded directional shadows via CSMWGSL at CSMGroup (group 3).
const TerrainMaterialFogWGSL = terrainPreludeWGSL + FogWGSL + FogBindingWGSL + FogCameraWGSL + terrainFragmentBlendWGSL + ` let lit = shade_pbr(in.world_pos, n, view_dir, blend_albedo, blend_metallic, blend_roughness);
let fogged = apply_fog(lit, fog_camera_pos(in.world_pos), in.world_pos, fog);
return vec4<f32>(linear_to_srgb(fogged), 1.0);
}
`TerrainMaterialFogWGSL is TerrainMaterialWGSL with distance and height fog via FogWGSL at FogGroup (group 3).
const TerrainMaterialShadowWGSL = terrainPreludeWGSL + ShadowWGSL + terrainFragmentBlendWGSL + ` let shadow_vis = sample_directional_shadow(in.world_pos, geom_n);
let lit = shade_pbr_shadowed(in.world_pos, n, view_dir, blend_albedo, blend_metallic, blend_roughness, shadow_vis);
return vec4<f32>(linear_to_srgb(lit), 1.0);
}
`TerrainMaterialShadowWGSL is TerrainMaterialWGSL with directional shadow mapping via ShadowWGSL at ShadowGroup (group 3).
const TerrainMaterialWGSL = terrainPreludeWGSL + terrainFragmentBlendWGSL + ` let lit = shade_pbr(in.world_pos, n, view_dir, blend_albedo, blend_metallic, blend_roughness);
return vec4<f32>(linear_to_srgb(lit), 1.0);
}
`TerrainMaterialWGSL is the complete portable WGSL shader module for lit splat-map multi-layer PBR terrain combining CameraWGSL (group 0), LightWGSL (group 1), and TerrainMaterialBindingsWGSL (group 2).
const ToneMapWGSL = `struct ToneMapParams {
exposure: f32,
inv_gamma: f32,
operator_id: f32,
_pad: f32,
uv_scale: vec2<f32>,
uv_min: vec2<f32>,
uv_max: vec2<f32>,
_pad2: vec2<f32>,
}
@group(0) @binding(0) var hdr_tex: texture_2d<f32>;
@group(0) @binding(1) var hdr_samp: sampler;
@group(0) @binding(2) var<uniform> params: ToneMapParams;
struct VertexOut {
@builtin(position) pos: vec4<f32>,
@location(0) uv: vec2<f32>,
}
@vertex
fn vs_main(@builtin(vertex_index) vid: u32) -> VertexOut {
var out: VertexOut;
var x: f32 = -1.0;
var y: f32 = -1.0;
if (vid == 1u) {
x = 3.0;
} else if (vid == 2u) {
y = 3.0;
}
out.pos = vec4<f32>(x, y, 0.0, 1.0);
out.uv = vec2<f32>((x + 1.0) * 0.5, (1.0 - y) * 0.5);
return out;
}
fn safe_pow_scalar(x: f32, p: f32) -> f32 {
if (x <= 0.0) {
return 0.0;
}
return pow(x, p);
}
fn linear_to_srgb_scalar(x: f32) -> f32 {
let c = clamp(x, 0.0, 1.0);
if (c <= 0.0031308) {
return c * 12.92;
}
return 1.055 * pow(c, 0.41666667) - 0.055;
}
fn tonemap_reinhard(c: vec3<f32>) -> vec3<f32> {
return c / (vec3<f32>(1.0, 1.0, 1.0) + c);
}
fn tonemap_aces(c: vec3<f32>) -> vec3<f32> {
let num = c * (2.51 * c + vec3<f32>(0.03, 0.03, 0.03));
let den = c * (2.43 * c + vec3<f32>(0.59, 0.59, 0.59)) + vec3<f32>(0.14, 0.14, 0.14);
return clamp(num / den, vec3<f32>(0.0, 0.0, 0.0), vec3<f32>(1.0, 1.0, 1.0));
}
fn tonemap_neutral(color: vec3<f32>) -> vec3<f32> {
let start_compression = 0.76;
let desaturation = 0.15;
let x = min(color.x, min(color.y, color.z));
var offset: f32 = 0.04;
if (x < 0.08) {
offset = x - 6.25 * x * x;
}
var c = color - vec3<f32>(offset, offset, offset);
let peak = max(c.x, max(c.y, c.z));
if (peak < start_compression) {
return clamp(c, vec3<f32>(0.0, 0.0, 0.0), vec3<f32>(1.0, 1.0, 1.0));
}
let d = 1.0 - start_compression;
let new_peak = 1.0 - (d * d) / (peak + d - start_compression);
c = c * (new_peak / peak);
let g = 1.0 - 1.0 / (desaturation * (peak - new_peak) + 1.0);
return clamp(mix(c, vec3<f32>(new_peak, new_peak, new_peak), vec3<f32>(g, g, g)), vec3<f32>(0.0, 0.0, 0.0), vec3<f32>(1.0, 1.0, 1.0));
}
// fast_log2_agx computes log2 over AgX's input range with power-of-two range reduction and an atanh series, because NSGo v0.3.0's software GPU has no case for the log2, exp2, log and exp builtins and silently returns 0 for them (nsgo-dev/nsgo#2334).
fn fast_log2_agx(v: f32) -> f32 {
var m = clamp(v, 0.0001757761, 16.291573);
var e: f32 = 0.0;
if (m >= 16.0) {
m = m * 0.0625;
e = e + 4.0;
}
if (m >= 4.0) {
m = m * 0.25;
e = e + 2.0;
}
if (m >= 2.0) {
m = m * 0.5;
e = e + 1.0;
}
if (m < 0.00390625) {
m = m * 256.0;
e = e - 8.0;
}
if (m < 0.0625) {
m = m * 16.0;
e = e - 4.0;
}
if (m < 0.25) {
m = m * 4.0;
e = e - 2.0;
}
if (m < 0.5) {
m = m * 2.0;
e = e - 1.0;
}
if (m < 1.0) {
m = m * 2.0;
e = e - 1.0;
}
if (m >= 1.41421356) {
m = m * 0.5;
e = e + 1.0;
}
let t = (m - 1.0) / (m + 1.0);
let t2 = t * t;
let poly = 1.0 + t2 * (0.33333334 + t2 * (0.2 + t2 * 0.14285715));
return e + 2.88539008 * t * poly;
}
fn agx_curve(x: vec3<f32>) -> vec3<f32> {
let x2 = x * x;
let x4 = x2 * x2;
return 15.5 * x4 * x2
- 40.14 * x4 * x
+ 31.96 * x4
- 6.868 * x2 * x
+ 0.4298 * x2
+ 0.1191 * x
- vec3<f32>(0.00232, 0.00232, 0.00232);
}
fn tonemap_agx(c: vec3<f32>) -> vec3<f32> {
let inset = vec3<f32>(
0.84247906 * c.x + 0.07843360 * c.y + 0.07922375 * c.z,
0.04232824 * c.x + 0.87846864 * c.y + 0.07916613 * c.z,
0.04237565 * c.x + 0.07843360 * c.y + 0.87914297 * c.z,
);
let min_ev = -12.47393;
let inv_range = 0.06060606;
let lx = clamp((fast_log2_agx(inset.x) - min_ev) * inv_range, 0.0, 1.0);
let ly = clamp((fast_log2_agx(inset.y) - min_ev) * inv_range, 0.0, 1.0);
let lz = clamp((fast_log2_agx(inset.z) - min_ev) * inv_range, 0.0, 1.0);
let curved = agx_curve(vec3<f32>(lx, ly, lz));
let outset = vec3<f32>(
1.19687901 * curved.x - 0.09802088 * curved.y - 0.09902974 * curved.z,
-0.05289685 * curved.x + 1.15190313 * curved.y - 0.09896118 * curved.z,
-0.05297164 * curved.x - 0.09804345 * curved.y + 1.15107367 * curved.z,
);
let clamped = clamp(outset, vec3<f32>(0.0, 0.0, 0.0), vec3<f32>(1.0, 1.0, 1.0));
return vec3<f32>(
safe_pow_scalar(clamped.x, 2.2),
safe_pow_scalar(clamped.y, 2.2),
safe_pow_scalar(clamped.z, 2.2),
);
}
// sanitize_hdr maps NaN and non-positive values to 0 and clamps the rest to the largest finite half float, so overflowed RGBA16Float highlights (+Inf) and extreme exposures never reach the operators as Inf or NaN. It tests NaN with a strict comparison, which is false for NaN under IEEE 754, instead of relying on how max and min treat NaN; NSGo v0.3.0's software VM also treats NaN as equal to every value, so >= and <= would let it through there (nsgo-dev/nsgo#2335).
fn sanitize_hdr(x: f32) -> f32 {
if (x > 0.0) {
return min(x, 65504.0);
}
return 0.0;
}
@fragment
fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
let src = textureSample(hdr_tex, hdr_samp, clamp(in.uv * params.uv_scale, params.uv_min, params.uv_max));
let raw = src.xyz * params.exposure;
let exposed = vec3<f32>(sanitize_hdr(raw.x), sanitize_hdr(raw.y), sanitize_hdr(raw.z));
var mapped: vec3<f32>;
if (params.operator_id < 0.5) {
mapped = clamp(exposed, vec3<f32>(0.0, 0.0, 0.0), vec3<f32>(1.0, 1.0, 1.0));
} else if (params.operator_id < 1.5) {
mapped = tonemap_reinhard(exposed);
} else if (params.operator_id < 2.5) {
mapped = tonemap_aces(exposed);
} else if (params.operator_id < 3.5) {
mapped = tonemap_neutral(exposed);
} else {
mapped = tonemap_agx(exposed);
}
if (params.inv_gamma < 0.0) {
return vec4<f32>(mapped, src.w);
}
var display: vec3<f32>;
if (params.inv_gamma > 0.0) {
display = vec3<f32>(
safe_pow_scalar(clamp(mapped.x, 0.0, 1.0), params.inv_gamma),
safe_pow_scalar(clamp(mapped.y, 0.0, 1.0), params.inv_gamma),
safe_pow_scalar(clamp(mapped.z, 0.0, 1.0), params.inv_gamma),
);
} else {
display = vec3<f32>(
linear_to_srgb_scalar(mapped.x),
linear_to_srgb_scalar(mapped.y),
linear_to_srgb_scalar(mapped.z),
);
}
return vec4<f32>(display, src.w);
}
`ToneMapWGSL is the full-screen triangle WGSL shader used by ToneMapPass.
It binds the HDR source texture at @group(0) @binding(0), its sampler at @group(0) @binding(1), and the ToneMapUniformSize-byte uniform block written by AppendToneMapUniforms at @group(0) @binding(2).
Entry points: vs_main (vertexless full-screen triangle via @builtin(vertex_index), drawn with pass.Draw(3, 0)) and fs_main (exposure, operator dispatch across None/Reinhard/ACES/Neutral/AgX, and exact sRGB or power-law gamma encoding).
All math uses only operations supported across WebGPU, Metal, D3D11, OpenGL 3.3, WebGL 2, OpenGL ES 3.0, and NSGo's software GPU VM (no exp or log2 builtins) (nsgo-dev/nsgo#2334).
const ToonOutlineWGSL = CameraWGSL + `
struct ToonMaterialUniform {
base_color: vec4<f32>,
shadow_bands: vec4<f32>,
spec_color_pow: vec4<f32>,
thresholds: vec4<f32>,
rim_outline: vec4<f32>,
outline_color: vec4<f32>,
flags: vec4<f32>,
}
struct ToonSceneUniform {
model: mat4x4<f32>,
normal_mat: mat4x4<f32>,
to_light: vec4<f32>,
light_color: vec4<f32>,
ambient_color: vec4<f32>,
}
@group(1) @binding(0) var<uniform> material: ToonMaterialUniform;
@group(2) @binding(0) var<uniform> scene: ToonSceneUniform;
struct ToonOutlineIn {
@location(0) pos: vec3<f32>,
@location(1) normal: vec3<f32>,
@location(2) uv: vec2<f32>,
}
struct ToonOutlineOut {
@builtin(position) clip: vec4<f32>,
@location(0) color: vec4<f32>,
}
@vertex
fn vs_outline(in: ToonOutlineIn) -> ToonOutlineOut {
var out: ToonOutlineOut;
let world_pos = (scene.model * vec4<f32>(in.pos, 1.0)).xyz;
let raw_n = (scene.normal_mat * vec4<f32>(in.normal, 0.0)).xyz;
let n_len = length(raw_n);
var world_n = vec3<f32>(0.0, 0.0, 0.0);
if (n_len > 0.00001) {
world_n = raw_n / n_len;
}
let width = material.rim_outline.w;
if (material.flags.y > 0.5) {
let base_clip = camera.view_proj * vec4<f32>(world_pos, 1.0);
let clip_n = (camera.view_proj * vec4<f32>(world_n, 0.0)).xy;
// The projection's width-to-height ratio. NDC x spans the viewport's width and y its height, so the offset is made isotropic in pixels by measuring it in units of NDC y.
var aspect = 1.0;
if (abs(camera.proj[0][0]) > 0.00001) {
aspect = abs(camera.proj[1][1] / camera.proj[0][0]);
}
let screen_n = vec2<f32>(clip_n.x * aspect, clip_n.y);
let sn_len = length(screen_n);
var offset = vec2<f32>(0.0, 0.0);
if (sn_len > 0.00001) {
let dir = screen_n / sn_len;
offset = vec2<f32>(dir.x / aspect, dir.y) * (width * base_clip.w);
}
out.clip = vec4<f32>(base_clip.xy + offset, base_clip.z, base_clip.w);
} else {
let extruded = world_pos + world_n * width;
out.clip = camera.view_proj * vec4<f32>(extruded, 1.0);
}
out.color = material.outline_color;
return out;
}
@fragment
fn fs_outline(in: ToonOutlineOut) -> @location(0) vec4<f32> {
return in.color;
}
`ToonOutlineWGSL is the inverted-hull outline WGSL shader paired with ToonWGSL (#262). Built into a pipeline with gpu.CullFront via NewToonOutlinePipeline, it extrudes each vertex outward along its world-space normal (or projected clip-space normal when ToonMaterial.OutlineClipSpace is set) by ToonMaterial.OutlineWidth and shades back faces with ToonMaterial.OutlineColor. It shares the exact bind group layouts of ToonWGSL so the same camera, material, and scene bind groups draw both passes.
const ToonWGSL = CameraWGSL + `
struct ToonMaterialUniform {
base_color: vec4<f32>,
shadow_bands: vec4<f32>,
spec_color_pow: vec4<f32>,
thresholds: vec4<f32>,
rim_outline: vec4<f32>,
outline_color: vec4<f32>,
flags: vec4<f32>,
}
struct ToonSceneUniform {
model: mat4x4<f32>,
normal_mat: mat4x4<f32>,
to_light: vec4<f32>,
light_color: vec4<f32>,
ambient_color: vec4<f32>,
}
@group(1) @binding(0) var<uniform> material: ToonMaterialUniform;
@group(1) @binding(1) var base_tex: texture_2d<f32>;
@group(1) @binding(2) var base_samp: sampler;
@group(1) @binding(3) var ramp_tex: texture_2d<f32>;
@group(1) @binding(4) var ramp_samp: sampler;
@group(2) @binding(0) var<uniform> scene: ToonSceneUniform;
struct ToonVertexIn {
@location(0) pos: vec3<f32>,
@location(1) normal: vec3<f32>,
@location(2) uv: vec2<f32>,
}
struct ToonVertexOut {
@builtin(position) clip: vec4<f32>,
@location(0) world_pos: vec3<f32>,
@location(1) world_normal: vec3<f32>,
@location(2) uv: vec2<f32>,
}
fn toon_smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {
let denom = max(edge1 - edge0, 0.00001);
let t = clamp((x - edge0) / denom, 0.0, 1.0);
return t * t * (3.0 - 2.0 * t);
}
fn toon_quantize_band(ndl: f32, bands: f32, smoothness: f32) -> f32 {
let c = clamp(ndl, 0.0, 1.0);
let n = max(bands, 2.0);
let x = c * n;
if (smoothness <= 0.00001) {
let idx = min(floor(x), n - 1.0);
return idx / (n - 1.0);
}
let w = min(smoothness, 0.5);
let k = clamp(floor(x + 0.5), 1.0, n - 1.0);
let t = toon_smoothstep(k - w, k + w, x);
return (k - 1.0 + t) / (n - 1.0);
}
@vertex
fn vs_main(in: ToonVertexIn) -> ToonVertexOut {
var out: ToonVertexOut;
let world = scene.model * vec4<f32>(in.pos, 1.0);
out.clip = camera.view_proj * world;
out.world_pos = world.xyz;
out.world_normal = (scene.normal_mat * vec4<f32>(in.normal, 0.0)).xyz;
out.uv = in.uv;
return out;
}
@fragment
fn fs_main(in: ToonVertexOut) -> @location(0) vec4<f32> {
let texel = textureSample(base_tex, base_samp, in.uv);
let albedo = material.base_color * texel;
let n_len = length(in.world_normal);
var n = vec3<f32>(0.0, 1.0, 0.0);
if (n_len > 0.00001) {
n = in.world_normal / n_len;
}
let l_len = length(scene.to_light.xyz);
var l = vec3<f32>(0.0, 1.0, 0.0);
if (l_len > 0.00001) {
l = scene.to_light.xyz / l_len;
}
let to_eye = camera.eye.xyz - in.world_pos * camera.eye.w;
let v_len = length(to_eye);
var v = vec3<f32>(0.0, 0.0, 1.0);
if (v_len > 0.00001) {
v = to_eye / v_len;
}
let ndl = clamp(dot(n, l), 0.0, 1.0);
let ramp_sample = textureSample(ramp_tex, ramp_samp, vec2<f32>(ndl, 0.5));
var diffuse_tint: vec3<f32>;
if (material.flags.x > 0.5) {
diffuse_tint = ramp_sample.rgb;
} else {
let band = toon_quantize_band(ndl, material.shadow_bands.w, material.thresholds.x);
diffuse_tint = mix(material.shadow_bands.xyz, vec3<f32>(1.0, 1.0, 1.0), band);
}
let lit_diffuse = albedo.rgb * (diffuse_tint * scene.light_color.xyz + scene.ambient_color.xyz);
var spec_factor: f32 = 0.0;
if (ndl > 0.0) {
let half_sum = l + v;
let half_len = length(half_sum);
if (half_len > 0.00001) {
let h = half_sum / half_len;
let ndh = max(dot(n, h), 0.0);
if (ndh > 0.0) {
let spec_raw = pow(ndh, material.spec_color_pow.w);
let spec_thresh = material.thresholds.y;
let spec_smooth = material.thresholds.z;
if (spec_smooth <= 0.00001) {
if (spec_raw >= spec_thresh) {
spec_factor = 1.0;
}
} else {
spec_factor = toon_smoothstep(spec_thresh - spec_smooth, spec_thresh + spec_smooth, spec_raw);
}
}
}
}
let lit_spec = material.spec_color_pow.xyz * scene.light_color.xyz * spec_factor;
let ndv = clamp(dot(n, v), 0.0, 1.0);
let fresnel = 1.0 - ndv;
let rim_thresh = material.thresholds.w;
let rim_smooth = material.flags.z;
var rim_factor: f32 = 0.0;
if (rim_smooth <= 0.00001) {
if (fresnel >= rim_thresh) {
rim_factor = 1.0;
}
} else {
rim_factor = toon_smoothstep(rim_thresh - rim_smooth, rim_thresh + rim_smooth, fresnel);
}
let lit_rim = material.rim_outline.xyz * rim_factor;
let rgb = clamp(lit_diffuse + lit_spec + lit_rim, vec3<f32>(0.0, 0.0, 0.0), vec3<f32>(1.0, 1.0, 1.0));
return vec4<f32>(rgb, albedo.a);
}
`ToonWGSL is the portable cel/toon shading WGSL shader (#262). It uses CameraWGSL at @group(0), GPUToonMaterial at @group(1), and ToonSceneUniform at @group(2), with MeshVertexLayout on vertex buffer 0. It uses only standard vertex/fragment stages and arithmetic/pow builtins so it runs identically on WebGPU, Metal, Vulkan, Direct3D 11, OpenGL 3.3, OpenGL ES 3.0, WebGL 2, and NSGo's software renderer.
const TransmissionBackgroundWGSL = `struct TransmissionBackgroundParams {
uv_scale_min: vec4<f32>,
uv_max_flags: vec4<f32>,
}
@group(3) @binding(0) var<uniform> transmission_bg: TransmissionBackgroundParams;
@group(3) @binding(1) var transmission_bg_tex: texture_2d<f32>;
@group(3) @binding(2) var transmission_bg_samp: sampler;
fn ext_srgb_to_linear_ch(c: f32) -> f32 {
let x = clamp(c, 0.0, 1.0);
if (x <= 0.04045) {
return x / 12.92;
}
return pow((x + 0.055) / 1.055, 2.4);
}
fn ext_decode_bg(rgb: vec3<f32>) -> vec3<f32> {
if (transmission_bg.uv_max_flags.z > 0.5) {
return vec3<f32>(
ext_srgb_to_linear_ch(rgb.x),
ext_srgb_to_linear_ch(rgb.y),
ext_srgb_to_linear_ch(rgb.z),
);
}
return rgb;
}
fn ext_sample_transmission_bg(frag_xy: vec2<f32>, roughness: f32) -> vec3<f32> {
let dims = textureDimensions(transmission_bg_tex);
let bg_dims = vec2<f32>(max(f32(dims.x), 1.0), max(f32(dims.y), 1.0));
let uv_min = transmission_bg.uv_scale_min.zw;
let uv_max = transmission_bg.uv_max_flags.xy;
let base_uv = clamp((frag_xy / bg_dims) * transmission_bg.uv_scale_min.xy, uv_min, uv_max);
let c0 = ext_decode_bg(textureSampleLevel(transmission_bg_tex, transmission_bg_samp, base_uv, 0.0).rgb);
if (roughness <= 0.08) {
return c0;
}
let r2 = roughness * roughness;
let step_uv = (vec2<f32>(1.0, 1.0) / bg_dims) * (r2 * 3.0);
let c1 = ext_decode_bg(textureSampleLevel(transmission_bg_tex, transmission_bg_samp, clamp(base_uv + vec2<f32>( step_uv.x, 0.0), uv_min, uv_max), 0.0).rgb);
let c2 = ext_decode_bg(textureSampleLevel(transmission_bg_tex, transmission_bg_samp, clamp(base_uv + vec2<f32>(-step_uv.x, 0.0), uv_min, uv_max), 0.0).rgb);
let c3 = ext_decode_bg(textureSampleLevel(transmission_bg_tex, transmission_bg_samp, clamp(base_uv + vec2<f32>(0.0, step_uv.y), uv_min, uv_max), 0.0).rgb);
let c4 = ext_decode_bg(textureSampleLevel(transmission_bg_tex, transmission_bg_samp, clamp(base_uv + vec2<f32>(0.0, -step_uv.y), uv_min, uv_max), 0.0).rgb);
return (c0 * 2.0 + c1 + c2 + c3 + c4) * (1.0 / 6.0);
}
`TransmissionBackgroundWGSL declares the per-frame transmission background bindings at TransmissionBackgroundGroup (group 3) and the helper ext_sample_transmission_bg(frag_xy, roughness) -> vec3<f32>. Use TransmissionBackgroundWGSLForGroup to place it at another bind group (such as MaterialTransmissionBackgroundGroup = 2).
const UnlitUniformSize = 32UnlitUniformSize is the byte size of the unlit material uniform block written by AppendUnlitUniforms and declared by UnlitWGSL:
- base_color_factor: vec4<f32> (16 bytes, offset 0)
- params: vec4<f32> (16 bytes, offset 16) holding (alpha_cutoff, alpha_mode, use_vertex_color, 0)
const UnlitWGSL = CameraWGSL + `
struct UnlitUniforms {
base_color_factor: vec4<f32>,
params: vec4<f32>,
}
@group(1) @binding(0) var<uniform> unlit_mat: UnlitUniforms;
@group(1) @binding(1) var unlit_tex: texture_2d<f32>;
@group(1) @binding(2) var unlit_samp: sampler;
struct UnlitVertexIn {
@location(0) pos: vec3<f32>,
@location(1) normal: vec3<f32>,
@location(2) uv: vec2<f32>,
@location(3) color: vec4<f32>,
}
struct UnlitVertexOut {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) color: vec4<f32>,
}
@vertex
fn vs_main(in: UnlitVertexIn) -> UnlitVertexOut {
var out: UnlitVertexOut;
out.clip = camera.view_proj * vec4<f32>(in.pos, 1.0);
out.uv = in.uv;
out.color = in.color;
return out;
}
fn unlit_linear_to_srgb_ch(c: f32) -> f32 {
let v = clamp(c, 0.0, 1.0);
if v <= 0.0031308 {
return v * 12.92;
}
return 1.055 * pow(v, 1.0 / 2.4) - 0.055;
}
fn unlit_linear_to_srgb(rgb: vec3<f32>) -> vec3<f32> {
return vec3<f32>(
unlit_linear_to_srgb_ch(rgb.x),
unlit_linear_to_srgb_ch(rgb.y),
unlit_linear_to_srgb_ch(rgb.z),
);
}
@fragment
fn fs_main(in: UnlitVertexOut) -> @location(0) vec4<f32> {
let texel = textureSample(unlit_tex, unlit_samp, in.uv);
var vcol = vec4<f32>(1.0, 1.0, 1.0, 1.0);
if unlit_mat.params.z > 0.5 {
vcol = in.color;
}
let base = unlit_mat.base_color_factor * texel * vcol;
var out_alpha = 1.0;
if unlit_mat.params.y > 0.5 && unlit_mat.params.y < 1.5 {
if base.a < unlit_mat.params.x {
discard;
}
out_alpha = 1.0;
} else if unlit_mat.params.y >= 1.5 {
out_alpha = clamp(base.a, 0.0, 1.0);
}
return vec4<f32>(unlit_linear_to_srgb(base.rgb), out_alpha);
}
@fragment
fn fs_linear(in: UnlitVertexOut) -> @location(0) vec4<f32> {
let texel = textureSample(unlit_tex, unlit_samp, in.uv);
var vcol = vec4<f32>(1.0, 1.0, 1.0, 1.0);
if unlit_mat.params.z > 0.5 {
vcol = in.color;
}
let base = unlit_mat.base_color_factor * texel * vcol;
var out_alpha = 1.0;
if unlit_mat.params.y > 0.5 && unlit_mat.params.y < 1.5 {
if base.a < unlit_mat.params.x {
discard;
}
out_alpha = 1.0;
} else if unlit_mat.params.y >= 1.5 {
out_alpha = clamp(base.a, 0.0, 1.0);
}
return vec4<f32>(base.rgb, out_alpha);
}
`UnlitWGSL is the built-in WGSL shader module for glTF KHR_materials_unlit surfaces with linear RGBA vertex colors (COLOR_0).
Bind groups:
- @group(0) @binding(0): CameraWGSL camera uniform block (CameraBuffer)
- @group(1) @binding(0..2): UnlitUniforms, base-color texture, and sampler (MaterialDefaults.UnlitLayout at MaterialGroup)
Vertex inputs match ColoredVertexLayout (@location(0) pos, @location(1) normal, @location(2) uv, @location(3) color).
Entry points:
- "vs_main": transforms positions by camera.view_proj and forwards UV and linear vertex color
- "fs_main": evaluates baseColorFactor * baseColorTexture * vertexColor, applies alpha-mask discard and alpha mode, and encodes linear RGB to sRGB (for non-sRGB targets such as FormatRGBA8Unorm)
- "fs_linear": evaluates the same unlit color and outputs linear RGBA directly (for sRGB targets, where the GPU encodes linear -> sRGB on write, and for UnlitPipelineOptions.LinearOutput)
変数
var (
// ErrInvalidClusterConfig is wrapped by every error [ClusterConfig.Validate], [NewClusterGrid], and [NewClusteredLightSystem] return for malformed cluster settings.
ErrInvalidClusterConfig = errors.New("render3d: invalid cluster config")
// ErrInvalidClusterLight is wrapped by every error [ClusterLight.Validate] returns for malformed light data.
ErrInvalidClusterLight = errors.New("render3d: invalid cluster light")
)Sentinel errors returned for invalid clustered lighting configuration or light data.
var (
// ErrUploaderClosed is returned when queueing on a closed [Uploader] or when an unfinished upload is aborted because the uploader or its scope closed.
ErrUploaderClosed = errors.New("render3d: uploader closed")
// ErrUploadCanceled is wrapped by errors returned when an upload is canceled via [UploadHandle.Cancel] or its caller context.
ErrUploadCanceled = errors.New("render3d: upload canceled")
// ErrUploadQueueFull is returned when queueing an upload would exceed [UploaderOptions.MaxPending].
ErrUploadQueueFull = errors.New("render3d: upload queue full")
)var ErrInvalidCSM = errors.New("render3d: invalid cascaded shadow map")ErrInvalidCSM is wrapped by every validation or invalid-argument error returned by the cascaded shadow map API.
var ErrInvalidCubemap = errors.New("render3d: invalid cubemap")ErrInvalidCubemap is wrapped by every error returned for malformed cubemap inputs, invalid prefilter parameters, or invalid BRDF LUT dimensions.
var ErrInvalidCustomMaterial = errors.New("render3d: invalid custom material")ErrInvalidCustomMaterial is wrapped by every error returned when validating, compiling, or updating a CustomMaterial. Those errors also match ErrInvalidMaterial.
var ErrInvalidDynamicResolution = errors.New("render3d: invalid dynamic resolution config")ErrInvalidDynamicResolution is wrapped by every error returned when validating DynamicResolutionConfig or configuring DynamicResolutionScaler and DynamicResolutionTarget.
var ErrInvalidFog = errors.New("render3d: invalid fog")ErrInvalidFog is wrapped by every error Fog.Validate, NewGPUFogBuffer and GPUFogBuffer.Update return for malformed parameters.
var ErrInvalidHDRTarget = errors.New("render3d: invalid HDR target")ErrInvalidHDRTarget is wrapped by errors returned when an HDRTargetDesc has invalid dimensions or parameters.
var ErrInvalidIBL = errors.New("render3d: invalid image-based lighting")ErrInvalidIBL is wrapped by every error IBLUniform.Validate, NewGPUIBLBuffer and GPUIBLBuffer.Update return for malformed image-based lighting parameters.
var ErrInvalidLight = errors.New("render3d: invalid light")ErrInvalidLight is wrapped by every error light validation or upload returns for malformed light definitions.
var ErrInvalidLightmap = errors.New("render3d: invalid lightmap")ErrInvalidLightmap is wrapped by errors returned when lightmap encoding, material parameters, UV transforms, or renderer descriptors are invalid.
var ErrInvalidLocalShadow = errors.New("render3d: invalid local shadow")ErrInvalidLocalShadow is wrapped by every validation error returned for spot or point light shadow maps and their configurations.
var ErrInvalidMaterial = errors.New("render3d: invalid material")ErrInvalidMaterial is wrapped by every error Material.Validate, NewGPUMaterial, GPUMaterial.Update, and NewMaterialPipeline return for malformed material parameters or invalid texture/sampler handles.
var ErrInvalidMesh = errors.New("render3d: invalid mesh")ErrInvalidMesh is wrapped by every error Mesh.Validate and UploadMesh return for malformed geometry.
var ErrInvalidPostProcess = errors.New("render3d: invalid post-processing configuration")ErrInvalidPostProcess is wrapped by every validation error returned by 3D post-processing configurations and constructors (BloomConfig.Validate, SSAOConfig.Validate, DepthOfFieldConfig.Validate, NewBloomPass, NewSSAOPass, NewDepthOfFieldPass, and NewPostStack3D).
var ErrInvalidProbe = errors.New("render3d: invalid probe")ErrInvalidProbe is wrapped by errors returned when reflection or light probe geometry, grid dimensions, bake options, or probe IBL uniforms are malformed.
var ErrInvalidRenderTexture = errors.New("render3d: invalid render texture")ErrInvalidRenderTexture is wrapped by errors returned by RenderTextureDesc.Validate, NewRenderTexture, RenderTexture.Resize, and ViewportRenderer when an offscreen render texture descriptor or handle is invalid.
var ErrInvalidSampler = errors.New("render3d: invalid sampler")ErrInvalidSampler is wrapped by every error SamplerOptions.Validate, NewGPUSampler and BindTexture return for malformed sampler settings or an invalid sampler handle.
var ErrInvalidShadow = errors.New("render3d: invalid directional shadow")ErrInvalidShadow is wrapped by validation errors returned by DirectionalShadowConfig, ShadowMapOptions, NewDirectionalShadowMap, and ShadowDepthGridFromBytes.
var ErrInvalidSkin = errors.New("render3d: invalid skin")ErrInvalidSkin is wrapped by errors returned for malformed skinning attributes, out-of-range joint indices, invalid glTF skin definitions, or oversized joint palettes.
var ErrInvalidTerrainMaterial = errors.New("render3d: invalid terrain material")ErrInvalidTerrainMaterial is wrapped by validation and construction errors returned by TerrainMaterial, NewGPUTerrainMaterial, and NewTerrainMaterialPipeline.
var ErrInvalidTexture = errors.New("render3d: invalid texture")ErrInvalidTexture is wrapped by every error PixelBuffer.Validate, PixelBufferFromImage, UploadTexture, UploadTexturePixels, GPUTexture.UpdateImage, GPUTexture.UpdatePixels and BindTexture return for malformed texture data or an invalid texture handle.
var ErrInvalidToonMaterial = errors.New("render3d: invalid toon material")ErrInvalidToonMaterial is wrapped by every error ToonMaterial.Validate, NewGPUToonMaterial, and GPUToonMaterial.Update return for malformed material parameters. Light errors wrap ErrInvalidLight.
var ErrInvalidUnlitMaterial = errors.New("render3d: invalid unlit material")ErrInvalidUnlitMaterial is wrapped by every error returned when validating, converting, creating, or updating an unlit material or unlit pipeline.
var ErrInvalidViewport = errors.New("render3d: invalid viewport")ErrInvalidViewport is wrapped by errors returned by ViewportRect.Validate and ViewportRenderer when a viewport rectangle, surface size, or camera view is invalid.
var ExtendedMaterialLitTransmissionWGSL = CameraWGSL + ExtendedMaterialBindingsWGSL + LightWGSLForGroup(ExtendedLightGroup) + TransmissionBackgroundWGSL + materialVertexStageWGSL + extFragmentPreludeWGSL + extWithBGWGSL + extRigLightingBodyWGSL + ` let srgb_rgb = linear_to_srgb(linear_rgb);
` + materialStagesTailWGSLExtendedMaterialLitTransmissionWGSL is the full LightRig-lit extended PBR shader with per-frame TransmissionBackground at TransmissionBackgroundGroup (groups 0: Camera, 1: ExtendedMaterial, 2: LightRig, 3: TransmissionBackground).
var ExtendedMaterialLitWGSL = CameraWGSL + ExtendedMaterialBindingsWGSL + LightWGSLForGroup(ExtendedLightGroup) + materialVertexStageWGSL + extFragmentPreludeWGSL + extNoBGWGSL + extRigLightingBodyWGSL + ` let srgb_rgb = linear_to_srgb(linear_rgb);
` + materialStagesTailWGSLExtendedMaterialLitWGSL is the LightRig-lit extended PBR shader compiled by NewExtendedMaterialPipeline when LightLayout is set (groups 0: Camera, 1: ExtendedMaterial, 2: LightRig).
var ExtendedMaterialTransmissionWGSL = CameraWGSL + ExtendedMaterialBindingsWGSL + TransmissionBackgroundWGSLForGroup(MaterialTransmissionBackgroundGroup) + materialVertexStageWGSL + extFragmentPreludeWGSL + extWithBGWGSL + extDefaultLightingBodyWGSL + ` let srgb_rgb = ext_tonemap_srgb(linear_rgb);
` + materialStagesTailWGSLExtendedMaterialTransmissionWGSL is the default-light extended PBR shader with a per-frame TransmissionBackground at MaterialTransmissionBackgroundGroup (group 2).
関数
func AppendFogUniforms(dst []byte, u FogUniforms) []byteAppendFogUniforms appends u to dst in the little-endian layout FogWGSL declares (FogUniformSize bytes) and returns the extended slice. It allocates only when dst lacks capacity for FogUniformSize more bytes.
func AppendJointMatrices(dst []byte, joints []math3d.Mat4) ([]byte, error)AppendJointMatrices encodes joints into dst as the fixed SkinUniformSize (8192-byte) little-endian uniform block declared by SkinWGSL, padding slots [len(joints), MaxSkinJoints) with identity matrices. It returns an error wrapping ErrInvalidSkin when len(joints) > MaxSkinJoints or any matrix entry is non-finite. It performs zero heap allocations when cap(dst)-len(dst) is at least SkinUniformSize.
func AppendShadowUniforms(dst []byte, u ShadowUniforms) []byteAppendShadowUniforms appends u to dst in the little-endian layout declared by ShadowWGSL (ShadowUniformSize bytes) and returns the extended slice. It allocates only when dst lacks capacity for ShadowUniformSize more bytes.
func AppendToneMapUniforms(dst []byte, opts ToneMapOptions) []byteAppendToneMapUniforms appends the ToneMapUniformSize little-endian bytes matching ToneMapWGSL's uniform struct, sampling the whole source texture, to dst and returns the extended slice. It allocates nothing when cap(dst)-len(dst) >= ToneMapUniformSize.
func AppendUnlitUniforms(dst []byte, m UnlitMaterial) []byteAppendUnlitUniforms appends the 32-byte little-endian uniform block matching UnlitWGSL's UnlitUniforms struct to dst and returns the extended slice. It allocates zero bytes when cap(dst)-len(dst) >= UnlitUniformSize.
func ApplyFXAA(src *image.RGBA, opts FXAAOptions) *image.RGBAApplyFXAA executes the CPU reference implementation of FXAAWGSL (FXAA 3.11 Quality) on src and returns a newly allocated anti-aliased *image.RGBA with the same bounds. Flat regions below the contrast threshold copy their source pixels unchanged; diagonal edges are smoothed along the detected edge span using bilinear clamp-to-edge sampling identical to the GPU pass.
func ApplyToneMap(rgb math3d.Vec3, opts ToneMapOptions) math3d.Vec3ApplyToneMap evaluates the CPU reference tone-mapping and display-encoding pipeline matching ToneMapWGSL:
- Scale linear HDR rgb by normalized Exposure and clamp it to [0, 65504], mapping NaN to 0 (sanitize_hdr in the shader).
- Apply opts.Operator (None, Reinhard, ACES, Khronos PBR Neutral, or AgX).
- Unless opts.LinearOutput is true, encode to display space using exact sRGB (Gamma <= 0) or power-law pow(c, 1/Gamma) (Gamma > 0).
func BakeReflectionProbe(cx *core.Scope, dev *gpu.Device, probe *ReflectionProbe, opts ProbeBakeOptions, sample func(origin, dir math3d.Vec3) [3]float32) errorBakeReflectionProbe bakes probe on request using sample(origin, dir), prefilters roughness mips with PrefilterEnvironment (unless opts.SkipPrefilter is set), uploads the resulting GPUCubemap to dev, closes any previous probe.GPUCubemap to prevent leaks, and marks probe Baked = true and Dirty = false.
func BakeReflectionProbeGPU(
cx *core.Scope,
dev *gpu.Device,
probe *ReflectionProbe,
opts ProbeBakeOptions,
renderFace func(pass *gpu.RenderPass, face gpu.CubeFace, cam CameraUniform),
onDone func(error),
)BakeReflectionProbeGPU asynchronously bakes probe on request by rendering all six cubemap faces on dev into temporary offscreen render targets via renderFace, queueing gpu.Device.ReadTexture for each face, flipping rows to canonical cubemap orientation, prefiltering roughness mips with PrefilterEnvironment (unless opts.SkipPrefilter is set), uploading the GPUCubemap, closing any previous probe.GPUCubemap, and invoking onDone on the engine goroutine once all six readbacks complete.
Temporary offscreen render targets use gpu.FormatRGBA8Unorm (when opts.SRGB is false) or gpu.FormatRGBA8UnormSRGB (when opts.SRGB is true) paired with gpu.FormatDepth24Plus. They are closed automatically once all six readbacks finish. Because gpu.Device.ReadTexture is asynchronous inside a live gpu.View, callers must wait for onDone rather than assuming probe.GPUCubemap is populated immediately upon return.
func BindTexture(cx *core.Scope, dev *gpu.Device, layout *gpu.BindGroupLayout, tex *GPUTexture, samp *GPUSampler) (*gpu.BindGroup, error)BindTexture creates a bind group matching TextureBindingLayout, binding tex at binding 0 and samp at binding 1. When both tex and samp were created with Retained set, NSGo automatically restores the bind group after a device loss.
func BoxProjectDirection(worldPos, reflDir, probePos, boxMin, boxMax math3d.Vec3) math3d.Vec3BoxProjectDirection computes the parallax-corrected cubemap lookup direction for a reflection ray originating at worldPos along reflDir inside the box [boxMin, boxMax] around probePos. Non-finite inputs never produce NaN.
func CSMWGSLForGroup(group uint32) stringfunc ClampSampleCount(dev *gpu.Device, requested int) intClampSampleCount returns a sample count accepted by dev for requested: 1 when requested <= 1 or dev is nil or lacks Features.MSAA4x, and 4 when requested >= 2 and dev supports Features.MSAA4x. This matches WebGPU and NSGo's portable 1x/4x sample-count set so the returned value is always valid for gpu.TextureDesc.SampleCount, gpu.RenderTargetDesc.SampleCount, and gpu.PipelineDesc.SampleCount.
func ColoredVertexLayout() gpu.VertexBufferLayoutColoredVertexLayout returns the vertex buffer layout of every GPUColoredMesh for gpu.PipelineDesc.VertexBuffers: one per-vertex buffer of ColoredVertexStride bytes with position at location 0, normal at location 1, UV at location 2, and linear RGBA color at location 3. Each call returns a fresh Attributes slice.
func CompileCheck(source string, lang ShaderLanguage, params []ShaderParamDesc) errorCompileCheck validates source, lang, and params, generates portable WGSL, compiles it via gpu.CompileWGSL, and verifies cross-backend pipeline lowering (MSL, HLSL, GLSL 3.30, GLSL ES 3.00 / WebGL 2, and WGSL) using an in-memory pipeline cache on a headless software device.
func CompileCheckDesc(desc CustomShaderDesc) errorCompileCheckDesc validates desc and verifies full shader and cross-backend pipeline compilation without requiring an active gpu.View. It checks DrawLayout as PBRDrawBuffer's layout (one uniform buffer at binding 0); with ExtraLayout set it compiles the shader but skips the pipeline check, because that layout's bindings belong to the caller's device.
func ComputeCSMSplits(near, far float32, count int, lambda float32) []float32ComputeCSMSplits computes count+1 view-space split depths [d_0, ..., d_count] spanning [near, far] using the practical split scheme (Zhang et al., 2006):
d_i = lambda * near * (far/near)^(i/count) + (1 - lambda) * (near + (far - near) * i / count)
lambda=0 produces uniform splits; lambda=1 produces logarithmic splits. Returns nil when count <= 0, near <= 0, far <= near, or either bound is non-finite. Non-finite lambda falls back to DefaultCSMSplitLambda; out-of-range finite lambda is clamped to [0, 1].
func CubeDirectionToFaceUV(dir math3d.Vec3) (face gpu.CubeFace, u, v float32)CubeDirectionToFaceUV maps a 3D direction to its cubemap face index (gpu.CubeFacePosX..gpu.CubeFaceNegZ) and face-local [0, 1] coordinates, matching the NSGo GPU cubemap sampler convention.
func CubeFaceDirection(face gpu.CubeFace, u, v float32) math3d.Vec3CubeFaceDirection returns the unit 3D direction corresponding to face-local coordinates (u, v) in [0, 1] on face (gpu.CubeFacePosX..gpu.CubeFaceNegZ) under the canonical WebGPU / Metal / Direct3D / OpenGL cubemap conventions.
func CustomShaderWGSL(desc CustomShaderDesc) (string, error)CustomShaderWGSL validates desc and returns the portable WGSL source that NewCustomMaterial compiles (translating Kage surface shaders or prepending auto-generated @group(1) declarations for WGSL).
func DecodeDepth32Float(raw []byte) []float32DecodeDepth32Float decodes tightly packed little-endian float32 depth texels returned by gpu.Device.ReadTexture on a gpu.FormatDepth32Float texture.
func DecodeLightmapSample(sample [4]float32, encoding LightmapEncoding, rgbmMaxRange float32, hardwareSRGB bool) math3d.Vec3DecodeLightmapSample decodes a sampled RGBA lightmap texel into linear HDR RGB irradiance using the exact same rules as LightmapWGSL and PBRLightmapWGSL. Set hardwareSRGB true when encoding is LightmapSRGB and the GPU texture format already decoded sRGB on sample.
func DecodeRGBD(rgba [4]uint8) math3d.Vec3DecodeRGBD unpacks an 8-bit RGBD texel back to linear HDR RGB irradiance.
func DecodeRGBM(rgba [4]uint8, maxRange float32) math3d.Vec3DecodeRGBM unpacks an 8-bit RGBM texel back to linear HDR RGB irradiance using maxRange (defaults to DefaultRGBMMaxRange when <= 0).
func DeviceSupportsClusteredLighting(dev *gpu.Device) boolDeviceSupportsClusteredLighting reports whether dev exposes the fragment storage-buffer capability and binding size needed for the clustered forward shading path. Because cluster assignment runs on the CPU, compute shaders are not required (so Apple Metal devices exposing StorageBuffers without Compute use the full clustered path). Devices without storage buffers (such as WebGL 2, OpenGL ES 3.0, Linux GtkGLArea, or headless tests under nsgotest.NoGPUCompute) fall back to the uniform-buffer path automatically.
func DrawGizmo(d *core.Drawing, viewProj math3d.Mat4, viewport core.Bounds, origin math3d.Vec3, scale float32, mode GizmoMode, activeAxis GizmoAxis)DrawGizmo projects and draws a 3D gizmo into d using default Gizmo settings, clipping segments against the near plane and highlighting activeAxis on top.
func EncodeCubemapHDR(w io.Writer, cm *HDRCubemap) errorEncodeCubemapHDR writes cm's base mip level (six canonical faces +X, -X, +Y, -Y, +Z, -Z) as a deterministic Radiance RGBE (.hdr) horizontal 6x1 cubemap strip of width 6*cm.Size and height cm.Size. DecodeCubemapHDR reads the strip back without resampling loss while preserving HDR radiance above 1.0.
func EncodeHDR(w io.Writer, img *HDRImage) errorEncodeHDR writes img in Radiance RGBE (.hdr) format (using adaptive RLE for widths in [8, 32767] and uncompressed scanlines otherwise). Invalid images return an error wrapping ErrInvalidCubemap.
func EncodeLightProbeGrid(d *LightProbeGridDoc) ([]byte, error)EncodeLightProbeGrid validates d and serializes it as deterministic 2-space YAML starting with LightProbeGridSchemaComment. A round trip through ParseLightProbeGrid and EncodeLightProbeGrid produces identical bytes.
func EncodeRGBD(rgb math3d.Vec3) [4]uint8EncodeRGBD packs a linear HDR RGB irradiance value into 8-bit RGBD bytes. LDR values (max channel <= 1) store D = 255 with full 8-bit precision; HDR values > 1 store D = floor(255 / maxChannel) and decode via rgb / max(d, 1/255).
func EncodeRGBDImage(hdr []math3d.Vec3, width, height int) (*image.NRGBA, error)EncodeRGBDImage encodes a row-major slice of width*height linear HDR RGB irradiance pixels into a straight-alpha *image.NRGBA suitable for upload with UploadTexture (SRGB: false) and LightmapRGBD.
func EncodeRGBM(rgb math3d.Vec3, maxRange float32) [4]uint8EncodeRGBM packs a linear HDR RGB irradiance value into 8-bit RGBM bytes using maxRange (defaults to DefaultRGBMMaxRange when <= 0). Decoding is linearRGB = (rgb / 255) * ((a / 255) * maxRange).
func EncodeRGBMImage(hdr []math3d.Vec3, width, height int, maxRange float32) (*image.NRGBA, error)EncodeRGBMImage encodes a row-major slice of width*height linear HDR RGB irradiance pixels into a straight-alpha *image.NRGBA suitable for upload with UploadTexture (SRGB: false) and LightmapRGBM.
func EnvBRDFApprox(f0 [3]float32, roughness, nDotV float32) [3]float32EnvBRDFApprox evaluates the Karis (2014) analytical split-sum GGX BRDF approximation, matching IBLWGSL's env_brdf_approx.
func EvaluateCSMShadow(frame CSMFrame, atlas CSMDepthAtlas, worldPos, worldNormal math3d.Vec3, viewDepth float32) float32EvaluateCSMShadow is the pure-Go CPU reference matching csm_shadow_factor in CSMWGSL. It returns the shadow visibility factor in [0, 1] (0 = fully in shadow, 1 = fully lit) for a world-space surface point, unit world normal, and positive camera view-space depth.
func EvaluateDirectionalShadow(worldPos, worldNormal math3d.Vec3, u ShadowUniforms, grid ShadowDepthGrid) float32EvaluateDirectionalShadow is the pure-Go CPU reference matching sample_directional_shadow in ShadowWGSL for the uniforms AppendShadowUniforms encodes from u (including its handling of non-finite values and unknown filters). It returns directional light visibility in [0, 1]: 1.0 when unoccluded, outside the light frustum, or when u.Strength <= 0, and (1 - u.Strength) when fully occluded.
func EvaluateIBL(
sh IrradianceSH,
prefilter *Cubemap,
intensity float32,
normal, viewDir math3d.Vec3,
baseColor [3]float32,
metallic, roughness, ao float32,
) [3]float32EvaluateIBL evaluates the exact CPU reference for IBLWGSL's evaluate_ibl function: L2 spherical harmonic diffuse irradiance combined with split-sum GGX prefiltered specular reflection using EnvBRDFApprox. A NaN or infinite metallic, roughness, ao or intensity counts as 0, and a negative intensity as 0, so the result stays finite.
func EvaluateIBLHDR(
sh IrradianceSH,
prefilter *HDRCubemap,
intensity float32,
normal, viewDir math3d.Vec3,
baseColor [3]float32,
metallic, roughness, ao float32,
) [3]float32EvaluateIBLHDR evaluates the exact CPU reference for IBLWGSL's evaluate_ibl function using an unclamped linear *HDRCubemap prefiltered specular environment.
func EvaluateLightAttenuation(light ClusterLight, worldPos math3d.Vec3) (dirToLight math3d.Vec3, attenuation float32)EvaluateLightAttenuation returns the unit direction from worldPos toward light and the light's attenuation times its Intensity: PointLightAttenuation with Range, times SpotConeAttenuation for a ClusterLightSpot. It returns zeros for a light with no power or an invalid record, and when worldPos coincides with the light.
func EvaluatePBR(n, v, l math3d.Vec3, mat PBRMaterial) math3d.Vec3EvaluatePBR evaluates the glTF 2.0 metallic-roughness Cook-Torrance GGX BRDF (diffuse + specular, before multiplying by light radiance and NdotL) for unit surface normal n, unit view direction v toward the eye, and unit light direction l toward the light.
It uses dielectric F0 = 0.04, Schlick Fresnel, Trowbridge-Reitz GGX normal distribution, height-correlated Smith-GGX visibility, and energy-conserving Lambertian diffuse, matching pbr_brdf in LightWGSL.
func EvaluatePointShadow(u PointShadowUniform, atlasDepth []float32, faceRes uint32, worldPos, worldNormal math3d.Vec3) float32EvaluatePointShadow is the CPU reference of sample_point_shadow in PointShadowWGSL: the point light's visibility in [0, 1] at worldPos against a row-major (3*faceRes) x (2*faceRes) Depth32Float atlas buffer, such as DecodeDepth32Float of the PointShadowMap.DepthTexture readback.
func EvaluateProbeIBL(
sh IrradianceSH,
blend ProbeBlendResult,
skyPrefilter *Cubemap,
intensity float32,
worldPos, normal, viewDir math3d.Vec3,
baseColor [3]float32,
metallic, roughness, ao float32,
) [3]float32EvaluateProbeIBL evaluates the exact CPU reference for evaluate_probe_ibl in ProbeIBLWGSL: L2 spherical harmonic diffuse irradiance combined with parallax-corrected, blended specular reflections across up to two local reflection probes and an optional global sky cubemap.
Add the result to ShadePoint and apply LinearToSRGB to reproduce LitPBRProbeIBLWGSL pixel-for-pixel. Unbaked, dirty, disabled, or nil-cubemap probes and a nil skyPrefilter all contribute black (0, 0, 0), matching GPUProbeIBLBuffer identically. Non-finite metallic, roughness, ao, or intensity values count as 0.
func EvaluateSpotShadow(u SpotShadowUniform, depth []float32, res uint32, worldPos, worldNormal math3d.Vec3) float32EvaluateSpotShadow is the CPU reference of sample_spot_shadow in SpotShadowWGSL: the spot light's visibility in [0, 1] at worldPos against a row-major res x res Depth32Float buffer, such as DecodeDepth32Float of the SpotShadowMap.DepthTexture readback.
func EvaluateTerrainTriplanarFactor(geomN math3d.Vec3, tp TerrainTriplanar) float32EvaluateTerrainTriplanarFactor computes the slope-driven triplanar blend factor in [0, 1] matching terrain_triplanar_factor in TerrainMaterialBindingsWGSL.
func EvaluateTerrainTriplanarWeights(geomN math3d.Vec3, sharpness float32) math3d.Vec3EvaluateTerrainTriplanarWeights computes the normalized X/Y/Z axis blend weights matching terrain_triplanar_weights in TerrainMaterialBindingsWGSL.
func EvaluateToon(mat ToonMaterial, in ToonEvalInput) [4]float32EvaluateToon is the pure-Go CPU reference implementation of ToonWGSL for deterministic unit testing and golden-render parity checks. It returns linear RGBA with RGB clamped to [0, 1].
func ExposureFromEV(ev float32) float32ExposureFromEV converts photographic exposure compensation in stops (EV) to a linear exposure multiplier 2^ev (0 -> 1.0, +1 -> 2.0, -1 -> 0.5). NaN returns 1.0, and ev is clamped to [-126, 126] (including the infinities), so the result is always finite and positive; set ToneMapOptions.Exposure to 0 for black.
func ExtendedMaterialBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)ExtendedMaterialBindGroupLayout creates the MaterialGroup bind group layout shared by every GPUExtendedMaterial: the uniform buffer at binding 0, the five base metallic-roughness texture/sampler pairs at bindings 1..10, and four extension texture/sampler pairs (clearcoat, clearcoat roughness, clearcoat normal, transmission) at bindings 11..18.
func FilterNodesByLayer(src []*scene3d.Node, mask uint32, dst []*scene3d.Node) []*scene3d.NodeFilterNodesByLayer appends every non-nil node in src whose Layer intersects mask to dst and returns the extended slice. It tests the layer only: hidden or disabled nodes (Visible or Enabled false on the node or an ancestor) are included, so skip them yourself as the scene3d decal path does. A zero mask matches nothing, unlike a zero CameraView.LayerMask; pass ViewportContext.LayerMask. Pass dst[:0] with preallocated capacity for zero steady-state allocations per camera view.
func FogCameraPos(cam CameraUniform, worldPos math3d.Vec3) math3d.Vec3FogCameraPos returns the point the view ray toward worldPos starts from under cam, matching fog_camera_pos in FogCameraWGSL: cam's eye for a perspective camera, and for an orthographic camera the point on the camera's plane that worldPos projects from. Pass it as camPos to Fog.Factor or Fog.Apply to reproduce on the CPU the fog the fogged pipelines draw.
func GenerateBRDFLUT(size int) (*image.RGBA, error)GenerateBRDFLUT generates a square 2D split-sum GGX BRDF integration lookup table (NoV along X in [0, 1], roughness along Y in [0, 1]), storing the Fresnel scale in R and bias in G using 128 Hammersley samples per texel.
func GenerateBRDFLUTWithSamples(size, sampleCount int) (*image.RGBA, error)GenerateBRDFLUTWithSamples generates a 2D split-sum GGX BRDF integration lookup table with an explicit Hammersley sample count per texel.
func HalfToFloat32(h uint16) float32HalfToFloat32 converts an IEEE 754 binary16 half-float bit pattern into a float32.
func IBLWGSLForGroup(group uint32) stringIBLWGSLForGroup returns the same WGSL declarations and helper functions as IBLWGSL with the uniform, cubemap, and sampler placed at the given @group index.
func LayerMatches(objectLayer, cameraMask uint32) boolLayerMatches reports whether an object's layer bitmask intersects a camera's layer mask, using the same bitmask convention as scene3d.Node.Layer.
func LightWGSLForGroup(group uint32) stringLightWGSLForGroup returns LightWGSL with the lights binding placed at @group(group) instead of LightGroup, for custom shaders whose group 1 already holds something else, such as a CustomMaterial with its ExtraLayout at group 3.
func LightmapVertexLayout() gpu.VertexBufferLayoutLightmapVertexLayout returns the vertex buffer layout for GPULightmapMesh: one 40-byte per-vertex buffer with position at location 0, normal at 1, UV0 at 2, and UV1 at 3. Each call returns a fresh Attributes slice.
func LinearToSRGB(rgb math3d.Vec3) math3d.Vec3LinearToSRGB converts a linear RGB triple (clamped to [0, 1] per channel) to sRGB, matching linear_to_srgb in LightWGSL.
func LinearToSRGBChannel(c float32) float32LinearToSRGBChannel converts a single linear light channel in [0, 1] (clamped) to sRGB using the IEC 61966-2-1 transfer function, matching linear_to_srgb_channel in LightWGSL.
func LoadKTX2(cx *core.Scope, dev *gpu.Device, data []byte, opts KTX2Upload) (*GPUTexture, SamplerOptions, error)LoadKTX2 uploads the 2D texture in data, a KTX2 file such as game assets and game tex write or a Basis Universal UASTC or BasisLZ/ETC1S file, to dev, scoped to cx, and returns it with the sampler to draw it with: opts.Sampler with its filters set from the file's KTX2FilterKey, as KTX2Sampler sets them, so an image's import settings decide whether it is drawn sharp or smooth.
Every mip level the file holds is uploaded, in its sRGB or linear format, after undoing the file's BasisLZ, Zstandard or ZLIB supercompression. A block-compressed level (BC1, BC3, BC7, ETC2 RGB8 or RGBA8, or ASTC 4x4) is uploaded compressed when dev supports its format (gpu.Device.SupportsCompressedFormat) and otherwise decoded to RGBA8 on the CPU, so the texture loads on every backend. A UASTC or BasisLZ/ETC1S level is transcoded to the best block format dev supports, in the order BC7, BC1 for an opaque texture, BC3, ETC2 (linear only) and ASTC 4x4, and decoded to RGBA8 when dev supports none of them or the base level's width or height is not a multiple of 4. Transcoding decodes each level and encodes it again on the calling goroutine, which costs time at load for a large texture.
A file that is not a valid 2D KTX2 texture in one of those formats, or whose filter is unknown, returns an error wrapping ErrInvalidTexture before anything is created; a device error is returned as the gpu.Error NSGo reports.
func MaterialBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)MaterialBindGroupLayout creates the uniform MaterialGroup bind group layout shared by every GPUMaterial: one fragment uniform buffer at binding 0 followed by five sampled 2D texture/sampler pairs (base color, metallic-roughness, normal, occlusion, emissive) at bindings 1..10.
func MaterialBindingsWGSLForGroup(group uint32) stringMaterialBindingsWGSLForGroup returns MaterialBindingsWGSL with every @group(1) binding moved to @group(group), for pipelines whose group 1 already holds another bind group such as LightGroup.
func MeshVertexLayout() gpu.VertexBufferLayoutMeshVertexLayout returns the vertex buffer layout of every GPUMesh for gpu.PipelineDesc.VertexBuffers: one per-vertex buffer of MeshVertexStride bytes with the position at MeshPositionLocation, the normal at MeshNormalLocation and the UV at MeshUVLocation. Each call returns a fresh Attributes slice.
func NewClusteredLitPBRPipeline(cx *core.Scope, dev *gpu.Device, camLayout *gpu.BindGroupLayout, sys *ClusteredLightSystem, drawLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)NewClusteredLitPBRPipeline compiles sys's ready-made shader (ClusteredLitWGSL or ClusteredFallbackWGSL) and creates the same back-face-culled pipeline as NewLitPBRPipeline, with sys's layout at LightGroup in place of a GPULightBuffer's. Pass depthFormat = gpu.FormatUndefined when rendering without a depth attachment.
func NewExtendedMaterialPipeline(cx *core.Scope, dev *gpu.Device, camLayout, matLayout *gpu.BindGroupLayout, opts ExtendedMaterialPipelineOptions) (*gpu.Pipeline, error)NewExtendedMaterialPipeline compiles the extended PBR shader variant matching opts and creates a render pipeline taking MeshVertexLayout at vertex slot 0, camLayout at CameraGroup (0), and matLayout (ExtendedMaterialDefaults.Layout) at MaterialGroup (1), with optional GPULightBuffer at ExtendedLightGroup (2) and/or TransmissionBackground at group 2 or TransmissionBackgroundGroup (3).
func NewLitPBRCSMPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, csmLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)NewLitPBRCSMPipeline compiles LitPBRCSMWGSL and creates a pipeline configured like NewLitPBRPipeline with csmLayout (CascadedShadowMap.Layout) added at CSMGroup.
func NewLitPBRFogPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, fogLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)NewLitPBRFogPipeline compiles LitPBRFogWGSL and creates a pipeline configured like NewLitPBRPipeline with fogLayout (GPUFogBuffer.Layout) added at FogGroup.
func NewLitPBRIBLPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, iblLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)NewLitPBRIBLPipeline compiles LitPBRIBLWGSL and creates a pipeline configured like NewLitPBRPipeline with iblLayout (GPUIBLBuffer.Layout) added at IBLGroup.
func NewLitPBRPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)NewLitPBRPipeline compiles LitPBRWGSL and creates a back-face-culled triangle-list pipeline configured for MeshVertexLayout with bind groups CameraGroup, LightGroup, and PBRDrawGroup. Pass depthFormat = gpu.FormatUndefined when rendering without a depth attachment.
func NewLitPBRPipelineWithOptions(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout *gpu.BindGroupLayout, opts LitPBRPipelineOptions) (*gpu.Pipeline, error)NewLitPBRPipelineWithOptions creates a lit PBR pipeline like NewLitPBRPipeline, NewLitPBRFogPipeline, NewLitPBRIBLPipeline, NewLitPBRShadowPipeline, NewLitPBRSpotShadowPipeline, NewLitPBRPointShadowPipeline or NewLitPBRCSMPipeline, with a configurable color format, with LitPBRPipelineOptions.VertexColors linear vertex colors, with LitPBRPipelineOptions.LinearOutput linear HDR output for an HDRTarget, and with LitPBRPipelineOptions.SkinLayout GPU skinning.
func NewLitPBRPointShadowPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, pointLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)NewLitPBRPointShadowPipeline compiles LitPBRPointShadowWGSL and creates a pipeline configured like NewLitPBRPipeline with pointLayout (PointShadowMap.Layout) added at LocalShadowGroup.
func NewLitPBRProbeIBLPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, probeIBLLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)NewLitPBRProbeIBLPipeline compiles LitPBRProbeIBLWGSL and creates a back-face-culled lit PBR pipeline configured like NewLitPBRIBLPipeline with probeIBLLayout (GPUProbeIBLBuffer.Layout or ProbeIBLBindGroupLayout) at IBLGroup (group 3).
func NewLitPBRProbeIBLPipelineWithOptions(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, probeIBLLayout *gpu.BindGroupLayout, opts ProbeIBLPipelineOptions) (*gpu.Pipeline, error)NewLitPBRProbeIBLPipelineWithOptions compiles LitPBRProbeIBLWGSL (or its linear HDR variant when opts.LinearOutput is set) and creates a lit PBR pipeline with probeIBLLayout at IBLGroup (group 3).
func NewLitPBRShadowPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, shadowLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)NewLitPBRShadowPipeline compiles LitPBRShadowWGSL and creates a pipeline configured like NewLitPBRPipeline with shadowLayout (DirectionalShadowMap.Layout) added at ShadowGroup.
func NewLitPBRSpotShadowPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, drawLayout, spotLayout *gpu.BindGroupLayout, depthFormat gpu.TextureFormat) (*gpu.Pipeline, error)NewLitPBRSpotShadowPipeline compiles LitPBRSpotShadowWGSL and creates a pipeline configured like NewLitPBRPipeline with spotLayout (SpotShadowMap.Layout) added at LocalShadowGroup.
func NewMaterialIBLPipeline(cx *core.Scope, dev *gpu.Device, camLayout, matLayout, iblLayout *gpu.BindGroupLayout, opts MaterialIBLPipelineOptions) (*gpu.Pipeline, error)NewMaterialIBLPipeline compiles MaterialIBLWGSL (or MaterialIBLLinearWGSL when opts.LinearOutput is true) and builds a render pipeline using MeshVertexLayout at vertex slot 0, camLayout at CameraGroup (group 0), matLayout at MaterialGroup (group 1), and iblLayout (GPUIBLBuffer.Layout) at MaterialIBLGroup (group 2).
func NewMaterialPipeline(cx *core.Scope, dev *gpu.Device, camLayout, matLayout *gpu.BindGroupLayout, opts MaterialPipelineOptions) (*gpu.Pipeline, error)NewMaterialPipeline compiles MaterialWGSL and builds a render pipeline using MeshVertexLayout at vertex slot 0, camLayout at CameraGroup (group 0), and matLayout at MaterialGroup (group 1). With MaterialPipelineOptions.VertexColors set it compiles MaterialColoredWGSL and takes ColoredVertexLayout vertices; with MaterialPipelineOptions.FogLayout set it compiles MaterialFogWGSL (or its colored variant when VertexColors is also set) and adds the fog layout at MaterialFogGroup (group 2); with MaterialPipelineOptions.SkinLayout set it compiles MaterialSkinnedWGSL, takes SkinnedVertexLayout vertices and adds the skin layout at MaterialSkinGroup (group 2).
func NewPBRLightmapPipeline(
cx *core.Scope,
dev *gpu.Device,
camLayout, lightLayout, matLayout, lmLayout *gpu.BindGroupLayout,
opts PBRLightmapPipelineOptions,
) (*gpu.Pipeline, error)NewPBRLightmapPipeline compiles PBRLightmapWGSL (or PBRLightmapLinearWGSL when LinearOutput is true or ColorFormat is sRGB) and creates a render pipeline taking LightmapVertexLayout vertices at slot 0 with:
- camLayout at CameraGroup (group 0)
- lightLayout (GPULightBuffer.Layout) at LightGroup (group 1)
- matLayout (MaterialDefaults.Layout) at PBRLightmapMaterialGroup (group 2)
- lmLayout (PBRLightmapBindGroupLayout / GPUPBRLightmap.Layout / GLTFPBRLightmapSet.Layout) at PBRLightmapGroup (group 3)
func NewSkinnedMeshPipeline(cx *core.Scope, dev *gpu.Device, camLayout, skinLayout *gpu.BindGroupLayout, opts SkinnedMeshPipelineOptions) (*gpu.Pipeline, error)NewSkinnedMeshPipeline compiles SkinnedMeshWGSL and creates a render pipeline using SkinnedVertexLayout, camLayout at CameraGroup (group 0), and skinLayout at SkinGroup (group 1).
func NewTerrainMaterialPipeline(cx *core.Scope, dev *gpu.Device, camLayout, lightLayout, terrainLayout *gpu.BindGroupLayout, opts TerrainPipelineOptions) (*gpu.Pipeline, error)NewTerrainMaterialPipeline compiles the portable WGSL terrain shader matching opts and builds a render pipeline using MeshVertexLayout at vertex slot 0, camLayout at CameraGroup (group 0), lightLayout at LightGroup (group 1), terrainLayout at TerrainMaterialGroup (group 2), and an optional shadow, CSM, or fog layout at group 3.
func NewToonOutlinePipeline(cx *core.Scope, dev *gpu.Device, opts ToonPipelineOptions) (*gpu.Pipeline, error)NewToonOutlinePipeline compiles ToonOutlineWGSL and creates the inverted-hull outline render pipeline (gpu.CullFront) on dev, scoped to cx.
func NewToonPipeline(cx *core.Scope, dev *gpu.Device, opts ToonPipelineOptions) (*gpu.Pipeline, error)NewToonPipeline compiles ToonWGSL and creates the main cel-shaded render pipeline on dev, scoped to cx.
func NewUnlitPipeline(cx *core.Scope, dev *gpu.Device, camLayout, matLayout *gpu.BindGroupLayout, opts UnlitPipelineOptions) (*gpu.Pipeline, error)NewUnlitPipeline compiles UnlitWGSL and builds a render pipeline using ColoredVertexLayout at vertex slot 0, camLayout at CameraGroup (group 0), and matLayout (MaterialDefaults.UnlitLayout) at MaterialGroup (group 1).
func NormalizeSkinWeights(w math3d.Vec4) math3d.Vec4NormalizeSkinWeights normalizes non-negative joint weights so their sum equals 1. The weights are divided by their largest component before summing, so large finite weights such as 4 x 3e38 normalize to (0.25, 0.25, 0.25, 0.25) instead of overflowing. If a weight is not finite or the sum is zero or negative, it falls back to (1, 0, 0, 0) so vertices stay rigidly attached to their first joint instead of collapsing to the origin.
func OrderCameraViews(views []CameraView, dst []int) []intOrderCameraViews appends the indices of active (non-disabled) views from views to dst in deterministic execution order: offscreen views (Target != nil) first, then main-surface views (Target == nil), each ordered stably by ascending Priority. Passing dst[:0] with capacity len(views) allocates nothing.
func PBRLightmapBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)PBRLightmapBindGroupLayout creates the PBRLightmapGroup (@group(3)) bind group layout shared by every GPUPBRLightmap: a vertex+fragment uniform buffer at binding 0, a sampled 2D lightmap texture at binding 1, and a sampler at binding 2.
func PBRLightmapBindingsWGSLForGroup(group uint32) stringPBRLightmapBindingsWGSLForGroup returns PBRLightmapBindingsWGSL with the lightmap uniform, texture, and sampler placed at @group(group).
func PBRLightmapLinearWGSL() stringPBRLightmapLinearWGSL returns the linear-output variant of PBRLightmapWGSL that skips linear_to_srgb, compiled by NewPBRLightmapPipeline when PBRLightmapPipelineOptions.LinearOutput is set or when ColorFormat is an sRGB target.
func PBRLightmapWGSL() stringPBRLightmapWGSL returns the complete portable WGSL shader module compiled by NewPBRLightmapPipeline for non-sRGB color targets. It combines:
- CameraWGSL at CameraGroup (group 0)
- LightWGSL at LightGroup (group 1) for dynamic directional, point, and spot lights
- MaterialBindingsWGSL shifted to PBRLightmapMaterialGroup (group 2) for GPUMaterial base color, metallic-roughness, normal, occlusion, and emissive maps on UV0
- PBRLightmapBindingsWGSL at PBRLightmapGroup (group 3) for the per-object transform and baked lightmap on UV1 * UVScale + UVOffset
- LightmapVertexLayout (40 bytes: position, normal, UV0, UV1)
The decoded lightmap replaces the ambient / indirect diffuse term as (1 - metallic) * baseColor * decodedLightmap * intensity * occlusion while the LightRig dynamic lights supply the Cook-Torrance GGX direct term plus emissive, encoded with linear_to_srgb matching LitPBRWGSL and LightmapWGSL.
func PointLightAttenuation(distSq, lightRange float32) float32PointLightAttenuation computes the glTF KHR_lights_punctual inverse-square distance attenuation with smooth range windowing:
max(min(1 - (d / lightRange)^4, 1), 0)^2 / max(distSq, 1e-4)
When lightRange <= 0, pure clamped inverse-square attenuation 1 / max(distSq, 1e-4) is returned. This matches point_light_attenuation in LightWGSL.
func PointShadowSelectFace(v math3d.Vec3) (face gpu.CubeFace, localU, localV, axisDist float32)PointShadowSelectFace projects light-to-fragment vector v onto the dominant cube face (0..5) and returns the face index, face-local UV in [0, 1]^2, and positive major-axis distance matching PointShadowWGSL.
func PointShadowWGSLForGroup(group uint32) stringPointShadowWGSLForGroup returns PointShadowWGSL with its bindings placed at @group(group) instead of LocalShadowGroup.
func PreferredHDRFormat(dev *gpu.Device) gpu.TextureFormatPreferredHDRFormat returns gpu.FormatRGBA16Float when dev supports it, and falls back to gpu.FormatRGBA8Unorm otherwise.
func ProbeFaceViewProj(pos math3d.Vec3, face gpu.CubeFace, near, far float32) (view, proj math3d.Mat4)ProbeFaceViewProj builds the right-handed 90-degree FOV view and [0, 1]-depth projection matrices for rendering one cubemap face from pos. The orientations preserve counter-clockwise triangle winding so backface culling works unchanged; when reading back a render target (top-down rows) to upload into a cubemap face, flip the rows vertically (BakeReflectionProbeGPU handles this automatically).
func ProbeIBLBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)ProbeIBLBindGroupLayout creates the IBLGroup bind group layout shared by GPUProbeIBLBuffer and LitPBRProbeIBLWGSL: binding 0 uniform buffer, bindings 1..3 cube textures (probe0, probe1, sky), and binding 4 trilinear sampler.
func ProbeIBLWGSLForGroup(group uint32) stringProbeIBLWGSLForGroup returns the same WGSL declarations and helper functions as ProbeIBLWGSL with the uniform, cubemaps, and sampler placed at the given @group index.
func ProjectScreenRatio(bounds math3d.AABB, viewProj math3d.Mat4) float32ProjectScreenRatio estimates the fraction of viewport height [0, 1] covered by the bounding sphere of bounds under viewProj. It returns 0 if bounds is empty or lies behind the camera.
func ProjectSegment(a, b math3d.Vec3, viewProj math3d.Mat4, viewport core.Bounds) (ax, ay, bx, by float32, visible bool)ProjectSegment projects the 3D world-space line segment (a, b) through viewProj into 2D screen coordinates within viewport, clipping against the near plane so segments crossing behind the camera never invert across the screen.
The near plane is clip z >= 0, which is right for the [0, 1] depth projections this package uses by default, math3d.Perspective and math3d.Ortho. Use ProjectSegmentNO for an OpenGL-style [-1, 1] projection such as math3d.PerspectiveNO or math3d.OrthoNO; this one would hide the near half of its depth range.
func ProjectSegmentNO(a, b math3d.Vec3, viewProj math3d.Mat4, viewport core.Bounds) (ax, ay, bx, by float32, visible bool)ProjectSegmentNO is ProjectSegment for an OpenGL-style [-1, 1] depth projection such as math3d.PerspectiveNO or math3d.OrthoNO: it clips at clip z >= -w. Used with a [0, 1] orthographic projection it would keep geometry behind the camera, because w is 1 there everywhere (#546).
func ReadCSMDepthAtlasAsync(dev *gpu.Device, csm *CascadedShadowMap, fn func(CSMDepthAtlas, error))ReadCSMDepthAtlasAsync asynchronously reads back c's gpu.FormatDepth32Float shadow atlas into a CPU CSMDepthAtlas and invokes fn on the engine goroutine (matching gpu.Device.ReadTexture).
func SRGBToLinear(rgb math3d.Vec3) math3d.Vec3SRGBToLinear decodes an sRGB triple (clamped to [0, 1] per channel) to linear RGB; it is the inverse of LinearToSRGB.
func SRGBToLinearChannel(c float32) float32SRGBToLinearChannel decodes a single sRGB-encoded channel in [0, 1] (clamped, NaN to 0) to linear light using the IEC 61966-2-1 transfer function; it is the inverse of LinearToSRGBChannel.
func SelectLOD(levels []LODLevel, dist float32, screenRatio float32, hysteresis float32, prevIndex int) intSelectLOD chooses the index of the appropriate LODLevel from levels (ordered finest to coarsest) given camera distance dist and projected screen-height ratio screenRatio.
Threshold checks are skipped for any negative metric (dist < 0 disables MaxDistance checks; screenRatio < 0 disables MinScreenRatio checks) or when a level leaves that threshold <= 0.
When 0 <= prevIndex < len(levels) and hysteresis > 0 (clamped to [0, 0.5]), transitions away from prevIndex require crossing the boundary by a relative deadband of hysteresis:
- Degrading to a coarser LOD requires exceeding MaxDistance*(1+h) or falling below MinScreenRatio*(1-h).
- Upgrading to a finer LOD requires entering MaxDistance*(1-h) and MinScreenRatio*(1+h).
SelectLOD returns -1 when levels is empty.
func ShadeClusteredGridPoint(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, grid *ClusterGrid, view, proj math3d.Mat4, viewportW, viewportH float32) math3d.Vec3ShadeClusteredGridPoint is ShadeClusteredPoint restricted to the lights grid assigned, on its last ClusterGrid.AssignLights, to the cluster that holds worldPos in a viewportW x viewportH viewport, looked up exactly as shade_pbr_clustered in ClusteredBindingsWGSL looks it up.
func ShadeClusteredPoint(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, lights []ClusterLight) math3d.Vec3ShadeClusteredPoint is ShadePoint for rig plus every light in lights, shaded with the same Cook-Torrance BRDF (EvaluatePBR). It is the brute-force reference for shade_pbr_clustered in ClusteredBindingsWGSL and ClusteredFallbackBindingsWGSL when no light is culled or truncated; call LinearToSRGB on the result to compare it with what ClusteredLitWGSL writes.
func ShadePoint(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig) math3d.Vec3ShadePoint evaluates total outgoing linear RGB radiance at worldPos with surface normal and view direction viewDir (from surface toward the eye) under rig (ambient, directional, point, and spot lights) and mat, matching shade_pbr + emissive in LitPBRWGSL.
normal and viewDir do not need to be unit length; if either is degenerate, only ambient and emissive terms contribute. Call LinearToSRGB on the returned linear color to encode sRGB display output.
func ShadePointShadowed(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, shadowVisibility float32) math3d.Vec3ShadePointShadowed is ShadePoint with the first directional light (rig.Directional[0]) scaled by shadowVisibility, matching shade_pbr_shadowed in LightWGSL and the lighting of LitPBRShadowWGSL. Pass EvaluateDirectionalShadow's result as shadowVisibility to reproduce a shadowed pixel on the CPU; 1 gives exactly ShadePoint.
func ShadePointVisibility(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, vis LightVisibility) math3d.Vec3ShadePointVisibility is ShadePoint with rig.Directional[0], rig.Point[0] and rig.Spot[0] scaled by the matching fields of vis, matching shade_pbr_visibility in LightWGSL and the lighting of LitPBRShadowWGSL, LitPBRSpotShadowWGSL and LitPBRPointShadowWGSL. Pass EvaluateSpotShadow or EvaluatePointShadow results to reproduce a pixel those shaders draw.
func ShadePointWithBackground(worldPos, normal, viewDir math3d.Vec3, mat PBRMaterial, rig LightRig, background math3d.Vec3) math3d.Vec3ShadePointWithBackground evaluates ShadePoint and composites optical transmission from a linear RGB opaque scene background color behind the surface when mat.Transmission > 0, matching ExtendedMaterialLitTransmissionWGSL when clearcoat and base normals coincide.
func ShadowBindingLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)ShadowBindingLayout creates the bind group layout declared by ShadowWGSL: binding 0 = vertex/fragment uniform buffer (ShadowUniforms), binding 1 = fragment depth texture (texture_depth_2d), binding 2 = fragment comparison sampler (sampler_comparison). Place it at ShadowGroup (2) in a pipeline's Layouts (or at whichever group ShadowWGSLForGroup uses).
func ShadowWGSLForGroup(group uint32) stringShadowWGSLForGroup returns ShadowWGSL with its shadow bindings placed at @group(group) instead of ShadowGroup, for custom shaders whose group 3 already holds something else.
func SkinJointMatrices(doc *gltf.Document, skinIndex int, dst []math3d.Mat4) ([]math3d.Mat4, error)SkinJointMatrices computes glTF 2.0 world-space joint skinning matrices for doc.Skins[skinIndex] as jointNode.WorldMatrix * InverseBindMatrices[i] (with identity when InverseBindMatrices is omitted). Per glTF 2.0 section 3.7.3.2, only joint transforms apply to a skinned mesh and the mesh node's own transform is ignored. Call gltf.Document.ComputeWorldMatrices before calling SkinJointMatrices after modifying node transforms or applying an animation with gltf.Animation.Apply. anim3d's Player keeps its own world matrices instead of writing doc.Nodes[].WorldMatrix, and its SkinMatricesForNode returns mesh-local matrices (inverse(meshWorld) * jointWorld * inverseBind); upload those with GPUSkinPalette.UpdateWithTransform and the mesh node's world matrix, or draw them through LitPBRPipelineOptions.SkinLayout with that matrix as the model.
Results are appended to dst[:0]; when cap(dst) >= len(skin.Joints), this function performs zero heap allocations.
func SkinJointMatricesWithTransform(doc *gltf.Document, skinIndex int, worldTransform math3d.Mat4, dst []math3d.Mat4) ([]math3d.Mat4, error)SkinJointMatricesWithTransform is like SkinJointMatrices but pre-multiplies each joint matrix by worldTransform so the skinned character can be placed anywhere in the scene. It performs zero heap allocations when cap(dst) >= len(skin.Joints).
func SkinVertex(pos, normal math3d.Vec3, joints [4]uint16, weights math3d.Vec4, matrices []math3d.Mat4) (skinnedPos, skinnedNormal math3d.Vec3)SkinVertex evaluates linear blend skinning on the CPU, matching SkinWGSL's skin_position and skin_normal helpers. Weights are normalized via NormalizeSkinWeights; any joint index at or beyond len(matrices) evaluates as the identity matrix, matching how GPUSkinPalette pads unused slots.
func SkinnedBounds(bind math3d.AABB, joints []math3d.Mat4) math3d.AABBSkinnedBounds returns a conservative axis-aligned box around a skinned mesh drawn with joints: the union of bind (the mesh's SkinnedMesh.Bounds or GPUSkinnedMesh.Bounds) transformed by every joint matrix. Each skinned vertex is a weighted average of the vertex under its joints' matrices, so it lies inside that union for any pose. With an empty joints slice it returns bind unchanged, matching how GPUSkinPalette pads unused slots with identity matrices. It does not allocate.
func SkinnedVertexLayout() gpu.VertexBufferLayoutSkinnedVertexLayout returns the vertex buffer layout of every GPUSkinnedMesh for gpu.PipelineDesc.VertexBuffers: one per-vertex buffer of SkinnedVertexStride (64) bytes with position (@location(0)), normal (@location(1)), UV (@location(2)), joint indices (@location(3), uint32x4), and normalized weights (@location(4), float32x4). Each call returns a fresh Attributes slice.
func SpotConeAttenuation(spotDir, toLight math3d.Vec3, angleScale, angleOffset float32) float32SpotConeAttenuation returns the glTF KHR_lights_punctual angular falloff of a spot light in [0, 1]: t = clamp(dot(spotDir, -toLight) * angleScale + angleOffset, 0, 1), squared. spotDir is the light's unit cone direction, toLight is the unit vector from the surface toward the light, and angleScale and angleOffset come from SpotLight.ConeScaleOffset. It is 1 inside the inner cone and 0 outside the outer cone or behind the light, and it matches spot_cone_attenuation in LightWGSL.
func SpotShadowViewProj(light SpotLight, near, far float32) math3d.Mat4SpotShadowViewProj returns the [0, 1]-depth perspective view-projection matrix a SpotShadowMap renders light with: looking from light.Position along light.Direction with a square field of view of 2 * light.OuterConeAngle, from near to far.
func SpotShadowWGSLForGroup(group uint32) stringSpotShadowWGSLForGroup returns SpotShadowWGSL with its bindings placed at @group(group) instead of LocalShadowGroup.
func SupportsHDR(dev *gpu.Device) boolSupportsHDR reports whether dev supports rendering to and sampling from gpu.FormatRGBA16Float textures.
func TerrainMaterialBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)TerrainMaterialBindGroupLayout creates the TerrainMaterialGroup (group 2) bind group layout shared by every GPUTerrainMaterial:
- binding 0: vertex/fragment uniform buffer ([TerrainMaterialUniforms])
- binding 1: splat0 texture_2d<f32> (layers 0..3 RGBA weights)
- binding 2: splat1 texture_2d<f32> (layers 4..7 RGBA weights)
- binding 3: splat sampler (linear clamp-to-edge)
- binding 4: albedo texture_2d_array<f32> (sRGB RGBA8)
- binding 5: normal texture_2d_array<f32> (linear RGBA8)
- binding 6: metallic-roughness-height texture_2d_array<f32> (R=height, G=roughness, B=metallic)
- binding 7: layer sampler (linear repeat)
func TextureBindingLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)TextureBindingLayout creates a bind group layout with a fragment-visible sampled 2D texture at binding 0 and its sampler at binding 1. Place it at whichever group slot your pipeline reserves for textures (for example group 1 alongside CameraGroup at group 0).
func ToonMaterialBindingLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)ToonMaterialBindingLayout creates the @group(1) bind group layout for GPUToonMaterial: binding 0 uniform buffer (vertex + fragment), binding 1 base color texture, binding 2 base sampler, binding 3 cel ramp texture, binding 4 ramp sampler (bindings 1..4 fragment-visible).
func ToonQuantizeBand(ndl float32, bands int, smoothness float32) float32ToonQuantizeBand evaluates the discrete cel-shading band factor in [0, 1] for ndl = N·L, matching ToonWGSL's toon_quantize_band function. Bands < MinToonBands default to DefaultToonBands. Smoothness 0 produces hard steps; values in (0, 0.5] anti-alias each band boundary smoothly.
func ToonSceneBindingLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)ToonSceneBindingLayout creates the @group(2) bind group layout for a single ToonSceneUniform buffer (non-dynamic offset). For multi-object drawing within one render pass, see ToonSceneDynamicBindingLayout and ToonRenderer.
func ToonSceneDynamicBindingLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)ToonSceneDynamicBindingLayout creates the @group(2) bind group layout with a dynamic uniform offset, allowing one uniform buffer to supply distinct ToonSceneUniform transforms for many draws in the same render pass.
func TransmissionBackgroundWGSLForGroup(group uint32) stringTransmissionBackgroundWGSLForGroup returns TransmissionBackgroundWGSL with its bindings placed at @group(group) instead of TransmissionBackgroundGroup (3).
func UnlitMaterialBindGroupLayout(cx *core.Scope, dev *gpu.Device) (*gpu.BindGroupLayout, error)UnlitMaterialBindGroupLayout creates the gpu.BindGroupLayout expected at MaterialGroup (@group(1)) by UnlitWGSL. NewMaterialDefaults creates one per device and shares it through MaterialDefaults.UnlitLayout; call this only to build a custom pipeline layout.
- binding 0: uniform buffer (UnlitUniformSize bytes, vertex & fragment visible)
- binding 1: sampled 2D base-color texture (fragment visible)
- binding 2: sampler (fragment visible)
func ValidateLightProbeGridDoc(d *LightProbeGridDoc) errorValidateLightProbeGridDoc validates d against the version 1 baked light probe grid schema. Every error wraps ErrInvalidProbe.
型
type AAMode uint8AAMode selects the anti-aliasing strategy for a 3D render pass (#249).
const (
// AANone disables anti-aliasing (single-sampled, no post-processing).
AANone AAMode = iota
// AAFXAA applies a full-screen FXAA 3.11 post-processing pass over a single-sampled color texture, suitable for deferred pipelines, post-FX chains, or devices without hardware MSAA.
AAFXAA
// AAMSAA2x requests 2x hardware multisample anti-aliasing. Because WebGPU and NSGo's portable GPU API expose 1x and 4x sample counts (guarded by Features.MSAA4x), [ClampSampleCount] promotes 2x to 4x when MSAA4x is supported and falls back to 1x otherwise.
AAMSAA2x
// AAMSAA4x requests 4x hardware multisample anti-aliasing, resolving to 4x when the device supports Features.MSAA4x and falling back to 1x otherwise.
AAMSAA4x
)func (m AAMode) IsMSAA() boolIsMSAA reports whether m requests hardware multisampling.
func (m AAMode) SampleCount() intSampleCount returns the requested hardware sample count for m (1 for AANone and AAFXAA, 2 for AAMSAA2x, 4 for AAMSAA4x). Pass it through ClampSampleCount before creating a GPU render target or pipeline.
func (m AAMode) String() stringString returns a stable lowercase identifier for m ("none", "fxaa", "msaa2x", "msaa4x", or "unknown").
func (m AAMode) UsesFXAA() boolUsesFXAA reports whether m requests the FXAA post-processing pass.
type AlphaMode uint8AlphaMode controls how a Material's alpha channel is interpreted during rendering, matching the glTF 2.0 specification.
const (
// AlphaOpaque ignores alpha and outputs an opaque surface (alpha = 1.0) with depth writes enabled.
AlphaOpaque AlphaMode = iota
// AlphaMask discards fragments whose effective base-color alpha is less than [Material.AlphaCutoff], outputting alpha = 1.0 for surviving fragments with depth writes enabled.
AlphaMask
// AlphaBlend composites fragments over the color target using straight alpha blending ([gpu.BlendAlpha]) with depth writes disabled.
AlphaBlend
)func AlphaModeFromGLTF(mode gltf.AlphaMode) (AlphaMode, error)AlphaModeFromGLTF maps a glTF 2.0 alpha mode string ("", "OPAQUE", "MASK", or "BLEND") to AlphaMode. Unknown values return an error wrapping ErrInvalidMaterial.
func (m AlphaMode) BlendMode() BlendModeBlendMode converts m into the corresponding render-queue BlendMode for DrawItem.Blend.
func (m AlphaMode) String() stringString returns the canonical lowercase name of m.
type AmbientLight struct {
Color math3d.Vec3
Intensity float32
}AmbientLight is a uniform isotropic fill light applied across surfaces in linear RGB space.
func (l AmbientLight) Validate() errorValidate reports whether l has finite non-negative color channels and intensity. Every error wraps ErrInvalidLight.
type Billboard struct {
// Center is the world-space point the quad's Pivot is placed at.
Center math3d.Vec3
// Width and Height are the quad's size in world units. A quad with a non-positive or non-finite size is not built.
Width, Height float32
// Pivot is the point of the quad placed at Center, in quad units where (0, 0) is the middle and ±0.5 are the edges; (0, -0.5) stands the quad on its bottom edge.
Pivot math3d.Vec2
// Rotation rolls the quad counter-clockwise as seen by the viewer, in radians, about its normal. Axial billboards ignore it so they stay aligned with their axis.
Rotation float32
// Mode selects how the quad turns toward the camera; the zero value is [BillboardViewPlane].
Mode BillboardMode
// Axis is the world-space axis an axial billboard rotates about and points its up edge along; a zero or non-finite axis means +Y.
Axis math3d.Vec3
// Color fills the quad on the [*core.Drawing] path, and its alpha fades a textured quad; zero means opaque white.
Color core.Color
// Texture is an optional image mapped across the quad on the [*core.Drawing] path, with its top-left at the quad's top-left corner.
Texture core.ImageSource
}Billboard is a camera-facing quad in world space (#281).
func (b Billboard) Quad(cam CameraBasis) (BillboardQuad, bool)Quad builds the billboard's geometry facing cam. It reports false when the billboard's size or center is non-finite, its size is not positive, or a corner overflows to a non-finite position.
type BillboardMode uint8BillboardMode selects how a Billboard turns toward the camera.
const (
// BillboardViewPlane lies in the camera's view plane, using the camera's right and up axes. Every quad is parallel to the screen and never shears, which suits particles, sprites and impostors.
BillboardViewPlane BillboardMode = iota
// BillboardViewPoint turns its normal straight at the camera's position, keeping the camera's up as the roll reference. Large quads near the screen edge stay undistorted, at the cost of neighbouring quads no longer being parallel.
BillboardViewPoint
// BillboardAxial rotates only about [Billboard.Axis] (cylindrical billboarding), for trees, grass, flames and beams that must stay upright. Its normal is the direction to the camera with the axis component removed, so a camera looking straight along the axis sees the quad edge-on.
BillboardAxial
)func (m BillboardMode) String() stringString returns a human-readable billboard mode name.
type BillboardQuad struct {
// Corners are the quad's world-space corners in the order above.
Corners [4]math3d.Vec3
// Center is the quad's geometric middle, which differs from Billboard.Center when Pivot is not zero.
Center math3d.Vec3
// Right, Up and Normal are the quad's unit axes; Normal points toward the camera.
Right, Up, Normal math3d.Vec3
// Width and Height are the quad's size in world units.
Width, Height float32
}BillboardQuad is the world-space geometry of a Billboard facing a camera.
Corners run counter-clockwise as seen by the viewer: bottom-left, bottom-right, top-right, top-left, with texture coordinates (0, 1), (1, 1), (1, 0) and (0, 0). Right × Up == Normal, so a back-face-culling pipeline keeps the quad.
func (q BillboardQuad) Bounds() math3d.AABBBounds returns the world-space AABB of q's corners.
func (q BillboardQuad) DrawItem(template DrawItem) DrawItemDrawItem returns template with Transform, WorldBounds, Triangles and Vertices taken from q, so the quad can be sorted by Queue.Build. A zero template Blend is replaced by BlendAlphaBlend, since billboards are usually translucent.
func (q BillboardQuad) Transform() math3d.Mat4Transform returns the matrix that maps the unit quad [-0.5, 0.5]² in its XY plane onto q, with +Z along q.Normal, for instancing a shared quad mesh.
type BillboardRenderer struct {
// contains filtered or unexported fields
}BillboardRenderer draws billboards into a *core.Drawing back to front, reusing its scratch storage across frames. Its zero value is ready to use.
func (r *BillboardRenderer) Draw(d *core.Drawing, items []Billboard, cam CameraBasis, viewProj math3d.Mat4, viewport core.Bounds) intDraw builds every billboard facing cam, sorts them back to front by view depth (keeping slice order on ties), clips each against the near plane and fills it into d through viewProj and viewport. It returns the number of quads drawn.
A textured quad is mapped with an affine transform, which is exact under an orthographic projection and a close approximation for quads that are small on screen under perspective; a textured quad that crosses the near plane is skipped.
type BlendMode uint8BlendMode controls how a DrawItem is partitioned and sorted in the render queue (#245, #248).
const (
// BlendOpaque renders fully opaque geometry with depth writes enabled,
// sorted by pipeline/material/mesh and front-to-back depth.
BlendOpaque BlendMode = iota
// BlendAlphaMask renders alpha-tested cutout geometry in the opaque pass
// (separate batch key from BlendOpaque).
BlendAlphaMask
// BlendAlphaBlend renders translucent geometry strictly back-to-front by
// distance from the camera.
BlendAlphaBlend
)func (b BlendMode) String() stringString returns a human-readable blend mode name.
type BloomConfig struct {
// Threshold is the minimum max-channel brightness that contributes to bloom (>= 0). Values above 1.0 target HDR emissive pixels in floating-point color targets.
Threshold float32
// SoftKnee controls the smooth transition width around Threshold in [0, 1]. 0 produces a hard cutoff; 0.5 produces a gradual shoulder.
SoftKnee float32
// Intensity scales the blurred glow added onto the scene color (>= 0). 0 leaves the scene unchanged.
Intensity float32
// Radius scales the separable Gaussian blur tap stride in texels (>= 0).
Radius float32
// BlurPasses is the number of horizontal+vertical separable Gaussian iterations in [1, 8]. 0 defaults to 2.
BlurPasses int
// HalfRes runs bright extraction and Gaussian blur at half resolution (max(1, w/2) x max(1, h/2)) for wider soft halos at a quarter of the pixel cost.
HalfRes bool
}BloomConfig tunes the 3D bloom post-processing pass.
func DefaultBloomConfig() BloomConfigDefaultBloomConfig returns balanced defaults for 3D bloom.
func (c BloomConfig) Validate() errorValidate checks that every field of c is finite and within its valid range. Every error wraps ErrInvalidPostProcess.
type BloomPass struct {
// contains filtered or unexported fields
}BloomPass executes bright-pixel extraction, separable 9-tap Gaussian blur across offscreen ping-pong render targets, and additive composition onto a destination target or swapchain.
func NewBloomPass(cx *core.Scope, dev *gpu.Device, opts BloomPassOptions) (*BloomPass, error)NewBloomPass creates a scope-owned BloomPass on dev.
func (p *BloomPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, dstColor *gpu.Texture) errorApply runs bright extraction, separable blur, and additive composite from srcColor into dstColor. A nil dstColor writes to the swapchain in OutputFormat, and a texture dstColor must be in ColorFormat or OutputFormat. Every texture must have the pass size and dstColor cannot also be an input; otherwise Apply returns an error wrapping ErrInvalidPostProcess.
func (p *BloomPass) Close() errorClose releases all GPU resources owned by p. It is safe to call on a nil receiver or more than once.
func (p *BloomPass) Config() BloomConfigConfig returns the pass's current normalized BloomConfig.
func (p *BloomPass) Height() uint32Height returns the configured scene height in pixels.
func (p *BloomPass) Resize(dev *gpu.Device, width, height uint32) errorResize recreates the pass's offscreen blur render targets for a new scene size.
func (p *BloomPass) SetConfig(cfg BloomConfig) errorSetConfig validates and updates the bloom parameters. Changing BloomConfig.HalfRes takes effect on the next BloomPass.Resize or BloomPass.Apply.
func (p *BloomPass) Valid() boolValid reports whether the pass is open and its GPU resources are live.
func (p *BloomPass) Width() uint32Width returns the configured scene width in pixels.
type BloomPassOptions struct {
Label string
Width uint32
Height uint32
ColorFormat gpu.TextureFormat // internal blur target format: RGBA16Float (the default), RGBA8Unorm, RGBA8UnormSRGB, BGRA8Unorm or BGRA8UnormSRGB
OutputFormat gpu.TextureFormat // destination format; defaults to dev.SurfaceFormat() or FormatRGBA8Unorm
Retained bool
Config BloomConfig
}BloomPassOptions configures NewBloomPass.
type Budget struct {
MaxDrawCalls int
MaxTriangles uint64
MaxVertices uint64
MaxMaterialSwitches int
MaxPipelineSwitches int
MaxTextureBytes uint64
MaxBufferBytes uint64
}Budget defines upper limits on per-frame draw submission and GPU memory consumption (#289). Any field set to 0 disables checking for that metric.
func DesktopBudget() BudgetDesktopBudget returns a desktop GPU budget preset suitable for mid-range discrete and integrated GPUs.
func MobileBudget() BudgetMobileBudget returns a conservative 60 fps mobile GPU budget preset (<= 150 draw calls, <= 150k triangles, <= 300k vertices, <= 60 material switches, <= 32 pipeline switches, <= 128 MiB textures, <= 64 MiB buffers).
type BudgetViolation struct {
Metric string
Actual uint64
Limit uint64
}BudgetViolation reports a single Budget threshold exceeded by RenderStats.
func CheckBudget(stats RenderStats, b Budget) []BudgetViolationCheckBudget compares stats against every non-zero limit in b and returns all violations in deterministic order. It returns nil when stats stays within b.
func (v BudgetViolation) String() stringString formats v as a human-readable budget overrun message.
type CSMCascade struct {
// Near and Far are positive view-space distances covered by this cascade.
Near float32
Far float32
// LightView transforms world space into light view space (origin at world 0).
LightView math3d.Mat4
// LightProj is the orthographic projection mapping light view space into [0, 1] NDC depth.
LightProj math3d.Mat4
// LightViewProj is LightProj * LightView.
LightViewProj math3d.Mat4
// AtlasRect is the normalized UV sub-rectangle (u0, v0, uScale, vScale) of this cascade's tile inside the 2D depth atlas.
AtlasRect math3d.Vec4
// Viewport is [x, y, width, height] in atlas pixels for SetViewport/SetScissor.
Viewport [4]float32
// TexelSize is the world-space width of one shadow-map texel.
TexelSize float32
// Center and Radius describe the cascade sub-frustum's bounding sphere in world space.
Center math3d.Vec3
Radius float32
}CSMCascade holds the fitted light-space projection, depth bounds, atlas tile placement, and bounding sphere of a single shadow cascade.
type CSMConfig struct {
// Label names GPU resources in capture tools.
Label string
// CascadeCount is the number of cascades in [1, MaxCascades]. Zero defaults to 4.
CascadeCount int
// Resolution is the width and height in texels of each cascade tile in the 2D depth atlas. Zero defaults to 1024.
Resolution int
// SplitLambda blends uniform (0.0) and logarithmic (1.0) cascade split distances using the practical split scheme. Must lie in [0, 1].
SplitLambda float32
// MaxShadowDistance caps the farthest view-space depth covered by shadows. When zero, the camera's far clip plane is used.
MaxShadowDistance float32
// DepthBias subtracts a small constant (modulated by surface slope) from receiver light-space depth to prevent shadow acne. Must be >= 0.
DepthBias float32
// NormalBias offsets receiver world positions along their surface normal (scaled by each cascade's texel size relative to cascade 0) before projecting into light space. Must be >= 0.
NormalBias float32
// CascadeBlendRange is the fraction in [0, 0.5] of each cascade's depth interval used to smoothly cross-fade into the next cascade (and fade out shadows smoothly approaching MaxShadowDistance). Zero disables blending.
CascadeBlendRange float32
// TexelSnap fits each cascade with a rotation-invariant bounding sphere and snaps its light-space projection origin to whole shadow-map texel increments, eliminating shadow-edge swimming as the camera moves.
TexelSnap bool
// Filter selects hard 1-tap shadows ([ShadowFilterHard]) or 3x3 PCF ([ShadowFilterPCF3x3]).
Filter ShadowFilter
// CasterPadding extends each cascade's orthographic near plane backward along -lightDir by this many world units so tall or off-frustum casters behind the camera still cast shadows into view. Must be >= 0.
CasterPadding float32
// DebugCascades tints lit surfaces by active cascade (0=red, 1=green, 2=blue, 3=yellow) in [LitPBRCSMWGSL] for inspecting cascade boundaries; [CSMFrame.DebugTint] is its CPU reference.
DebugCascades bool
// MaxCasters is the number of distinct non-identity caster model matrices [CascadedShadowMap.DrawCaster] can hold between two [CascadedShadowMap.Update] calls. A model drawn into several cascades takes one slot. Zero defaults to [DefaultCSMMaxCasters] (256).
MaxCasters int
// Retained opts every GPU buffer, depth atlas, sampler, and pipeline owned by [CascadedShadowMap] into automatic recreation across GPU device loss.
Retained bool
}CSMConfig configures FitCascades and NewCascadedShadowMap.
Use DefaultCSMConfig for balanced outdoor defaults (4 cascades, 1024x1024 per cascade, lambda 0.75, texel snapping enabled, 3x3 PCF, 10% cascade blend). Zero values for CascadeCount, Resolution, and MaxCasters fall back to DefaultCSMCascadeCount, DefaultCSMResolution, and DefaultCSMMaxCasters.
func DefaultCSMConfig() CSMConfigDefaultCSMConfig returns balanced defaults for cascaded directional shadows.
func (c CSMConfig) AtlasSize() (width, height uint32)AtlasSize returns the pixel dimensions (width, height) of the 2D depth atlas that packs c's cascades: 1x1 for 1 cascade, 2x1 for 2 cascades, and 2x2 for 3 or 4 cascades.
func (c CSMConfig) Validate() errorValidate checks every field of c and returns an error wrapping ErrInvalidCSM if any value is out of range or non-finite.
type CSMDepthAtlas struct {
Width int
Height int
Depth []float32
}CSMDepthAtlas holds a CPU copy of a 2D float32 shadow depth atlas (row-major, top-left origin, depth values in [0, 1]) for pure-Go reference evaluation via EvaluateCSMShadow.
func ReadCSMDepthAtlas(dev *gpu.Device, csm *CascadedShadowMap) (CSMDepthAtlas, error)ReadCSMDepthAtlas reads back c's gpu.FormatDepth32Float shadow atlas synchronously (for gpu.SoftwareRenderer tests where gpu.Device.ReadTexture completes immediately). Inside a gpu.View, use ReadCSMDepthAtlasAsync.
type CSMFrame struct {
CascadeCount int
Cascades [MaxCascades]CSMCascade
Splits [MaxCascades + 1]float32
LightDir math3d.Vec3
MaxShadowDistance float32
AtlasWidth uint32
AtlasHeight uint32
Config CSMConfig
}CSMFrame holds the complete per-frame cascade solution computed by FitCascades or FitCascadesFromCamera, ready to upload to a CascadedShadowMap via CascadedShadowMap.Update or evaluate on the CPU with EvaluateCSMShadow and CSMFrame.DebugTint.
func FitCascades(camView, camProj math3d.Mat4, near, far float32, lightDir math3d.Vec3, cfg CSMConfig) CSMFrameFitCascades fits directional shadow cascades to the camera frustum defined by camView, camProj (using [0, 1] NDC depth as produced by math3d.Perspective and math3d.Ortho), and positive view-space clip distances [near, far].
lightDir is the world-space direction light rays travel (from the directional light toward the scene, e.g. {0.3, -1, -0.4}). It is normalized internally; a zero or non-finite vector falls back to (0, -1, 0).
When cfg.TexelSnap is true, each cascade uses a rotation-invariant bounding sphere quantized to 1/16 world unit and snaps its light-space projection origin to whole shadow-map texel steps, preventing shadow-edge swimming under camera motion. FitCascades performs zero heap allocations.
func FitCascadesFromCamera(cam *scene3d.Camera, lightDir math3d.Vec3, cfg CSMConfig) CSMFrameFitCascadesFromCamera fits cascades to a scene3d.Camera with the same near and far planes its scene3d.Camera.ProjMatrix uses (the defaults scene3d.Projection.Matrix fills in for zero or out-of-range fields included). Shadows cover view depths from max(near, 0.1) to the far plane or CSMConfig.MaxShadowDistance, so an orthographic camera whose near plane is at or behind it (Near <= 0) is shadowed from 0.1 on. When cam is nil, a default perspective camera at the origin looking down -Z is used. lightDir is the world-space direction light rays travel; with LitPBRCSMWGSL pass the Direction of the LightRig's first directional light, the one the cascades shadow.
func (f *CSMFrame) DebugTint(viewDepth float32) math3d.Vec3DebugTint returns the color multiplier csm_debug_tint in CSMWGSL applies at a positive camera view depth: white (1, 1, 1) when CSMConfig.DebugCascades is off or viewDepth is outside the shadowed range, otherwise the active cascade's tint (0 red, 1 green, 2 blue, 3 yellow) mixed 55% into white.
func (f *CSMFrame) EncodeUniforms(dst []byte) []byteEncodeUniforms writes f into dst as the little-endian CSMUniformSize-byte uniform block matching CSMWGSL's CSMUniforms struct and returns dst[:CSMUniformSize]. It panics if len(dst) < CSMUniformSize. It makes zero heap allocations.
func (f *CSMFrame) SelectCascade(viewDepth float32) (index int, nextIndex int, blend float32)SelectCascade returns the primary cascade index for a positive camera view-space depth, along with the next cascade index (or -1 if none / fading out past the final cascade) and blend factor in [0, 1].
When viewDepth <= 0 or viewDepth >= f.MaxShadowDistance (or f.CascadeCount <= 0), SelectCascade returns (-1, -1, 0).
type CameraBasis struct {
// Pos is the camera's world-space position.
Pos math3d.Vec3
// Right is the camera's unit world-space right axis (+X in view space).
Right math3d.Vec3
// Up is the camera's unit world-space up axis (+Y in view space).
Up math3d.Vec3
// Forward is the camera's unit world-space viewing direction (-Z in view space).
Forward math3d.Vec3
// Orthographic makes every point see the camera along -Forward instead of along the line to Pos.
Orthographic bool
}CameraBasis is a camera's world-space position and unit axes, the input that billboards and trails turn toward (#281).
Build one from a view and projection matrix with NewCameraBasis, or fill it from a scene3d camera as CameraBasis{Pos: cam.Pos, Right: cam.Right(), Up: cam.Up(), Forward: cam.Forward(), Orthographic: cam.Projection.Kind == scene3d.ProjectionOrthographic}.
func NewCameraBasis(view, proj math3d.Mat4) (CameraBasis, bool)NewCameraBasis derives a CameraBasis from a right-handed view matrix and its projection matrix. It reports false when view is singular or yields a non-finite or degenerate basis. A projection whose bottom row is (0, 0, 0, w != 0) marks the basis orthographic.
func (c CameraBasis) ToCamera(p math3d.Vec3) math3d.Vec3ToCamera returns the unit direction from p toward the viewer: -Forward for an orthographic basis, or when p coincides with Pos, and the normalized line from p to Pos otherwise.
type CameraBuffer struct {
// contains filtered or unexported fields
}CameraBuffer holds one camera's uniform buffer on a GPU device together with the bind group layout and bind group that expose it to vertex and fragment shaders at CameraGroup.
Create it once when the device is ready, call Write with the frame's camera before recording draws, and bind BindGroup at CameraGroup; pipelines list Layout at that index of their PipelineDesc.Layouts. Its resources belong to the scope it was created with and are released with it, or earlier by Close.
func NewCameraBuffer(cx *core.Scope, dev *gpu.Device) (*CameraBuffer, error)NewCameraBuffer creates a camera uniform buffer, its bind group layout and its bind group on dev, owned by cx (nil for resources the caller closes itself, as in headless tests).
func (b *CameraBuffer) BindGroup() *gpu.BindGroupBindGroup returns the bind group a render pass sets at CameraGroup.
func (b *CameraBuffer) Buffer() *gpu.BufferBuffer returns the underlying uniform buffer.
func (b *CameraBuffer) Close() errorClose releases the bind group, layout and buffer now rather than with the owning scope. It returns the first error and is safe to call more than once.
func (b *CameraBuffer) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout a pipeline lists at CameraGroup.
func (b *CameraBuffer) Write(u CameraUniform)Write uploads u to the buffer; draws recorded after it read the new values. It encodes into storage the CameraBuffer owns, so the only copy made is the one gpu.Device.WriteBuffer takes of the bytes it queues.
func (b *CameraBuffer) WriteCamera(cam *scene3d.Camera)WriteCamera uploads cam's current pose and projection; it is Write(NewCameraUniform(cam)).
type CameraUniform struct {
View math3d.Mat4
Proj math3d.Mat4
ViewProj math3d.Mat4
// Eye is (position, 1) for a perspective camera and (direction toward the viewer, 0) for an orthographic one; see [scene3d.Camera.Eye].
Eye math3d.Vec4
}CameraUniform is the per-view camera data a 3D shader reads: the view, projection and combined matrices in math3d's column-major layout with [0, 1] clip depth, and the homogeneous eye point.
func NewCameraUniform(cam *scene3d.Camera) CameraUniformNewCameraUniform returns the uniform data for cam's current pose and projection.
func ProbeFaceCamera(pos math3d.Vec3, face gpu.CubeFace, near, far float32) CameraUniformProbeFaceCamera returns a CameraUniform configured to render one cubemap face from pos with a 90-degree field of view.
func (u *CameraUniform) Encode(dst []byte) []byteEncode writes u into dst as the little-endian float32 block CameraWGSL declares and returns dst[:CameraUniformSize]. It panics if len(dst) is less than CameraUniformSize, whatever dst's capacity.
type CameraView struct {
// Name is an optional label used in GPU pass labels and diagnostics.
Name string
// Camera supplies the viewpoint and projection. Required for active views.
Camera *scene3d.Camera
// Target directs this camera into an offscreen [RenderTexture]. Offscreen views always execute before main-surface views (Target == nil) so their textures are ready to sample as material textures in the same frame.
Target *RenderTexture
// Viewport selects the normalized sub-rectangle of Target (or the main surface) to render into. The zero value covers the entire target.
Viewport ViewportRect
// LayerMask selects which [scene3d.Node.Layer] bits this camera sees. Zero defaults to [scene3d.LayerAll] via [CameraView.EffectiveLayerMask] so struct literals render all layers unless restricted; to render nothing, set Disabled. This differs from [FilterLayeredItems], [FilterNodesByLayer] and [scene3d.Decal.LayerMask], where a zero mask matches nothing, so filter with [ViewportContext.LayerMask], which is already the effective mask.
LayerMask uint32
// Priority orders views ascending within the offscreen phase and within the main-surface phase; ties preserve input slice order.
Priority int
// ClearColor sets the clear color when this view opens a clearing pass. Only the view that opens a pass clears: a view that shares the pass of the view before it (consecutive viewports on one target, such as split-screen players) or continues it with ResetDepth keeps the color already there, so give such views distinct backgrounds by drawing a full-viewport quad first. On the main surface, zero falls back to [SurfaceDesc.ClearColor], so an explicit transparent black clear is not expressible there while SurfaceDesc.ClearColor is set.
ClearColor core.Color
// ClearDepth sets the depth clear value for a pass this view opens, or for the depth clear ResetDepth requests. Zero defaults to 1.0 (on the main surface, to [SurfaceDesc.ClearDepth] first), so a reversed-Z clear to 0 is not expressible.
ClearDepth float32
// LoadColor controls whether the first pass targeting this view's target in a frame clears color ([gpu.LoadClear], the zero default) or preserves existing contents ([gpu.LoadLoad]). A later view that returns to an offscreen target after views on another target always loads color and depth, so what the earlier views drew is kept; set ResetDepth on it to clear depth instead.
LoadColor gpu.LoadOp
// ResetDepth forces a continuation pass with preserved color ([gpu.LoadLoad]) and a fresh depth clear ([gpu.LoadClear]) when this view shares a target with a preceding view (for example, an overlapping picture-in-picture 3D minimap drawn over a full-screen 3D view). Leave false for non-overlapping split-screen viewports so they share a single GPU render pass.
ResetDepth bool
// PreserveAspect keeps Camera.Projection.Aspect unchanged instead of adjusting a per-view copy of the camera to match the resolved viewport's pixel aspect ratio.
PreserveAspect bool
// Disabled skips this view when true.
Disabled bool
}CameraView describes one camera pass rendered by ViewportRenderer: either an offscreen render-to-texture pass (Target != nil) or a viewport on the main surface (Target == nil).
func NewCameraView(cam *scene3d.Camera) CameraViewNewCameraView returns a CameraView targeting the full main surface with scene3d.LayerAll and ClearDepth 1.
func (v CameraView) EffectiveLayerMask() uint32EffectiveLayerMask returns v.LayerMask, defaulting zero to scene3d.LayerAll.
type CascadedShadowMap struct {
// contains filtered or unexported fields
}CascadedShadowMap owns the portable 2D gpu.FormatDepth32Float depth atlas, comparison sampler, uniform buffers, bind groups, and depth-only caster pipeline for directional cascaded shadow maps on an NSGo gpu.Device.
Typical per-frame usage:
frame := render3d.FitCascadesFromCamera(cam, rig.Directional[0].Direction, csm.Config())
_ = csm.Update(dev, frame)
for i := range csm.CascadeCount() {
if pass := csm.BeginCascadePass(enc, i); pass != nil {
csm.DrawCaster(pass, mesh, modelMat)
pass.End()
}
}
// Then in the main lit pass, with a pipeline from NewLitPBRCSMPipeline:
mainPass.SetBindGroup(render3d.CSMGroup, csm.BindGroup())
func NewCascadedShadowMap(cx *core.Scope, dev *gpu.Device, cfg CSMConfig) (*CascadedShadowMap, error)NewCascadedShadowMap validates cfg and allocates the 2D depth atlas, comparison sampler, uniform buffers, bind groups, and depth-only caster pipeline on dev, scoped to cx.
Invalid configuration returns an error wrapping ErrInvalidCSM before any GPU resource is created. A nil or lost device returns gpu.ErrDeviceLost.
func (c *CascadedShadowMap) AtlasHeight() uint32AtlasHeight returns the depth atlas height in texels.
func (c *CascadedShadowMap) AtlasWidth() uint32AtlasWidth returns the depth atlas width in texels.
func (c *CascadedShadowMap) BeginCascadePass(enc RenderPassStarter, cascadeIdx int) *gpu.RenderPassBeginCascadePass starts a depth-only render pass targeting cascadeIdx's tile in the 2D depth atlas, sets the tile viewport and scissor rectangle, binds the depth-only caster pipeline, and binds cascadeIdx's light view-projection at group 0.
The first cascade pass after CascadedShadowMap.Update, whichever cascade it is, clears the whole depth atlas to 1.0 (a clear is not limited by the scissor); every later pass keeps the tiles already drawn with gpu.LoadLoad. Render every cascade after each Update, in any order. Returns nil when c, enc, or cascadeIdx is invalid.
func (c *CascadedShadowMap) BindGroup() *gpu.BindGroupBindGroup returns the bind group a lit render pass sets at CSMGroup.
func (c *CascadedShadowMap) ByteSize() uint64ByteSize returns the GPU memory held by c's depth atlas and uniform buffers, for RenderStats and Budget accounting.
func (c *CascadedShadowMap) CascadeBindGroup(idx int) *gpu.BindGroupCascadeBindGroup returns the group-0 bind group holding cascade idx's light_view_proj uniform buffer, or nil if idx is out of range.
func (c *CascadedShadowMap) CascadeCount() intCascadeCount returns the number of cascades of the frame last passed to CascadedShadowMap.Update, which CascadedShadowMap.BeginCascadePass accepts; it always equals CSMConfig.CascadeCount of CascadedShadowMap.Config.
func (c *CascadedShadowMap) CasterModelLayout() *gpu.BindGroupLayoutCasterModelLayout returns the group-1 bind group layout expected by CascadedShadowMap.DepthPipeline and CascadedShadowMap.DrawCasterGroup.
func (c *CascadedShadowMap) Close() errorClose releases every GPU resource owned by c now rather than waiting for its owning scope. It is safe to call on a nil receiver or more than once.
func (c *CascadedShadowMap) Config() CSMConfigConfig returns the normalized CSMConfig used to create c.
func (c *CascadedShadowMap) DepthPipeline() *gpu.PipelineDepthPipeline returns the depth-only caster pipeline used by [BeginCascadePass].
func (c *CascadedShadowMap) DepthTexture() *gpu.TextureDepthTexture returns the underlying 2D gpu.FormatDepth32Float atlas texture.
func (c *CascadedShadowMap) DrawCaster(pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) boolDrawCaster renders mesh as a shadow caster inside a pass opened by CascadedShadowMap.BeginCascadePass, transforming its vertices by model, and reports whether it drew.
A zero or identity model uses a pre-filled identity slot. Every other model takes one slot of the caster transform buffer the first time it is drawn after CascadedShadowMap.Update; drawing the same model again, for example into the next cascade, reuses that slot, so CSMConfig.MaxCasters counts distinct models per frame, not draws. Once every slot is taken, DrawCaster draws nothing and returns false rather than overwrite a transform an earlier draw of the same command buffer still reads; raise MaxCasters, or bind caller-owned transforms with CascadedShadowMap.DrawCasterGroup.
func (c *CascadedShadowMap) DrawCasterGroup(pass *gpu.RenderPass, mesh *GPUMesh, modelGroup *gpu.BindGroup, dynamicOffsets ...uint32)DrawCasterGroup renders mesh inside a pass opened by CascadedShadowMap.BeginCascadePass using a caller-owned model bind group matching CascadedShadowMap.CasterModelLayout at group 1.
func (c *CascadedShadowMap) Frame() CSMFrameFrame returns the most recently uploaded CSMFrame.
func (c *CascadedShadowMap) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout a lit pipeline places at CSMGroup.
func (c *CascadedShadowMap) Sampler() *gpu.SamplerSampler returns the comparison sampler bound with the depth atlas.
func (c *CascadedShadowMap) UniformBuffer() *gpu.BufferUniformBuffer returns the CSMUniformSize-byte uniform buffer.
func (c *CascadedShadowMap) Update(dev *gpu.Device, frame CSMFrame) errorUpdate uploads frame's cascade matrices, split distances, atlas rects and shading parameters onto dev with zero heap allocations, and frees every caster slot CascadedShadowMap.DrawCaster took since the last Update. Call it once per frame before CascadedShadowMap.BeginCascadePass.
frame must be fitted with c's cascade count, resolution and filter (CascadedShadowMap.Config), because its atlas tiles, viewports, texel size and filter mode index c's atlas and sampler; any other frame returns an error wrapping ErrInvalidCSM and leaves c unchanged. The other CSMConfig fields (splits, biases, blend range, padding, debug tint) may change from frame to frame.
func (c *CascadedShadowMap) Valid() boolValid reports whether every GPU resource owned by c is open and belongs to a live device.
type ClusterConfig struct {
// TilesX is the number of screen-space horizontal tiles (default 16).
TilesX int
// TilesY is the number of screen-space vertical tiles (default 9).
TilesY int
// SlicesZ is the number of logarithmic view-space depth slices (default 24, max 64).
SlicesZ int
// MaxLights is the maximum number of visible local lights stored in clustered mode (default 512).
MaxLights int
// MaxLightsPerCluster caps how many lights can be assigned to one cluster cell (default 64).
MaxLightsPerCluster int
// FallbackMaxLights caps how many prioritized lights are uploaded in uniform-buffer fallback mode (default 16, max 16).
FallbackMaxLights int
// ForceFallback forces the uniform-buffer fallback path even on devices that support storage buffers and compute.
ForceFallback bool
// Retained keeps CPU copies of GPU buffers so NSGo recreates them after a device loss.
Retained bool
// Label prefixes GPU resource debug labels.
Label string
}ClusterConfig configures the 3D frustum-cluster grid and its mobile uniform-buffer fallback. Zero fields use defaults from DefaultClusterConfig.
func DefaultClusterConfig() ClusterConfigDefaultClusterConfig returns the standard 16x9x24 frustum-cluster grid supporting 512 lights (64 per cluster) and a 16-light mobile/WebGL 2 fallback.
func (c ClusterConfig) ClusterCount() intClusterCount returns the total number of 3D frustum clusters (TilesX * TilesY * SlicesZ) after applying defaults.
func (c ClusterConfig) Validate() errorValidate checks that every field (after applying defaults to zero fields) is within supported limits. Every error wraps ErrInvalidClusterConfig.
type ClusterGrid struct {
// contains filtered or unexported fields
}ClusterGrid builds a 3D view-space frustum cluster grid and assigns local point and spot lights to intersecting cells with zero steady-state allocations.
Cluster AABBs are cached by (proj, near, far) so camera rotation/translation frames reuse the frustum cells without recomputing them.
func NewClusterGrid(cfg ClusterConfig) (*ClusterGrid, error)NewClusterGrid validates cfg and allocates reusable storage for frustum clusters and light assignment.
func (g *ClusterGrid) ActiveLights() []ClusterLightActiveLights returns the frustum-visible lights packed by the most recent ClusterGrid.AssignLights call (indices in ClusterGrid.LightIndices reference this slice).
func (g *ClusterGrid) AssignLights(view, proj math3d.Mat4, near, far float32, lights []ClusterLight) ClusterStatsAssignLights transforms lights into view space, culls lights outside the camera frustum, tests each visible light against its candidate frustum clusters (sphere-vs-AABB for all lights plus exact cone-vs-AABB rejection for spot lights), and packs compact offset/count and index arrays.
Lights that fail ClusterLight.Validate or have no power are skipped and counted in CulledLights; ClusteredLightSystem.Update validates first and reports them as errors. Once MaxLights lights are visible, further lights are dropped in input order (TruncatedLights), and once a cell holds MaxLightsPerCluster lights it drops the rest in input order (TruncatedClusters), so put the most important lights first when a scene can exceed either cap. Steady-state calls perform zero heap allocations.
func (g *ClusterGrid) BuildFrustum(proj math3d.Mat4, near, far float32) boolBuildFrustum computes view-space depth slice boundaries and per-cluster view-space AABBs for (proj, near, far), caching the result until any of those inputs change.
func (g *ClusterGrid) ClusterAABB(tileX, tileY, sliceZ int) math3d.AABBClusterAABB returns the cached view-space AABB of cluster (tileX, tileY, sliceZ).
func (g *ClusterGrid) ClusterCount() intClusterCount returns the total number of frustum cells (TilesX * TilesY * SlicesZ).
func (g *ClusterGrid) ClusterIndex(tileX, tileY, sliceZ int) intClusterIndex returns the flat linear index for cluster coordinates (tileX, tileY, sliceZ).
func (g *ClusterGrid) ClusterLightIndices(tileX, tileY, sliceZ int) []uint32ClusterLightIndices returns the light indices assigned to cluster (tileX, tileY, sliceZ) on the last ClusterGrid.AssignLights call.
func (g *ClusterGrid) Config() ClusterConfigConfig returns the normalized ClusterConfig of g.
func (g *ClusterGrid) LastStats() ClusterStatsLastStats returns the ClusterStats from the most recent ClusterGrid.AssignLights call.
func (g *ClusterGrid) LightIndices() []uint32LightIndices returns the flat packed light-index list referenced by ClusterGrid.Offsets.
func (g *ClusterGrid) Offsets() []ClusterOffsetCountOffsets returns the per-cluster offset/count table packed by the most recent ClusterGrid.AssignLights call.
func (g *ClusterGrid) SliceDepths() []float32SliceDepths returns the positive view-space depth boundaries [near .. far] of length SlicesZ+1 computed on the most recent ClusterGrid.AssignLights or ClusterGrid.BuildFrustum.
func (g *ClusterGrid) SliceForDepth(viewZ float32) intSliceForDepth maps a positive view-space depth viewZ to its depth slice index in [0, SlicesZ-1] using the exact same binary search over ClusterGrid.SliceDepths as the GPU fragment shader.
type ClusterLight struct {
Kind ClusterLightKind
Position math3d.Vec3
Range float32
Color math3d.Vec3
Intensity float32
// Direction is the world-space emission axis for [ClusterLightSpot]. Normalized automatically; zero defaults to (0, -1, 0).
Direction math3d.Vec3
// InnerConeCos and OuterConeCos are cos(innerHalfAngle) and cos(outerHalfAngle) for [ClusterLightSpot] with 1 >= InnerConeCos >= OuterConeCos >= -1.
InnerConeCos float32
OuterConeCos float32
}ClusterLight is the record ClusterGrid bins and ClusteredLightSystem uploads for one local point or spot light in world space. Build it from a PointLight or SpotLight with ClusterLightFromPoint or ClusterLightFromSpot, or directly with NewPointClusterLight and NewSpotClusterLight.
Distance falloff is PointLightAttenuation with Range, and spot lights also multiply by SpotConeAttenuation, so a light shades exactly as the PointLight or SpotLight it came from. Unlike those, Range must be positive: clustering needs a bounding sphere, so a light with Range 0 (unbounded) is refused by ClusterLight.Validate and ClusteredLightSystem.Update; the converters derive a range for it from ClusterRangeCutoff.
func ClusterLightFromPoint(l PointLight) (ClusterLight, error)ClusterLightFromPoint validates l and converts it to a ClusterLightPoint. When l.Range is 0 (unbounded), the range is derived as sqrt(Intensity * max(Color) / ClusterRangeCutoff), where the light's unwindowed radiance falls to the cutoff; the windowed falloff then reaches exactly zero there instead of trailing off forever. Errors wrap ErrInvalidLight.
func ClusterLightFromSpot(l SpotLight) (ClusterLight, error)ClusterLightFromSpot validates l and converts it to a ClusterLightSpot with the same cone, deriving a range for Range 0 as ClusterLightFromPoint does. Errors wrap ErrInvalidLight.
func NewPointClusterLight(pos, color math3d.Vec3, intensity, lightRange float32) ClusterLightNewPointClusterLight returns a ClusterLightPoint with finite range and linear RGB color.
func NewSpotClusterLight(pos, dir, color math3d.Vec3, intensity, lightRange, innerConeRad, outerConeRad float32) ClusterLightNewSpotClusterLight returns a ClusterLightSpot aiming along dir with inner and outer cone half-angles in radians (clamped so 0 <= inner <= outer <= pi).
func SelectFallbackLights(dst []ClusterLight, view, proj math3d.Mat4, lights []ClusterLight, maxLights int) []ClusterLightSelectFallbackLights chooses up to maxLights local lights for the uniform-buffer fallback path (mobile, WebGL 2, OpenGL ES 3.0) and appends them to dst[:0].
Lights whose bounding sphere lies outside the view frustum of proj * view, or that fail ClusterLight.Validate or have no power, are dropped first, so off-screen lights never take a slot from visible ones. The rest are ranked deterministically by luminous power, range, and distance to the camera, breaking ties by input order. This allocates a scratch slice per call; ClusteredLightSystem.Update reuses one.
func (l ClusterLight) Validate() errorValidate checks that l has finite parameters, a known kind, positive Range, non-negative Color and Intensity, and valid cone cosines for spot lights. Every error wraps ErrInvalidClusterLight.
type ClusterLightKind uint32ClusterLightKind selects the emission geometry of a ClusterLight.
const (
// ClusterLightPoint radiates isotropically within Range.
ClusterLightPoint ClusterLightKind = 0
// ClusterLightSpot radiates within a cone around Direction with smooth inner-to-outer angular attenuation.
ClusterLightSpot ClusterLightKind = 1
)type ClusterOffsetCount struct {
Offset uint32
Count uint32
}ClusterOffsetCount identifies the contiguous slice of ClusterGrid.LightIndices assigned to one cluster cell: indices[Offset : Offset+Count].
type ClusterStats struct {
InputLights int
VisibleLights int
CulledLights int
ActiveClusters int
TotalAssignments int
MaxClusterLights int
AvgLightsPerActive float32
TruncatedClusters int
TruncatedLights int
}ClusterStats reports per-frame light culling and cluster packing metrics.
type ClusteredLightSystem struct {
// contains filtered or unexported fields
}ClusteredLightSystem owns the whole LightGroup bind group for clustered forward shading: the LightRig uniform LightWGSL reads at binding 0 (ambient, directional, and the rig's own point and spot lights) and the local-light buffers at bindings 1 to 4. On devices without storage buffers or compute (WebGL 2, OpenGL ES 3.0, nsgotest.NoGPUCompute) it falls back to one uniform buffer at binding 1 holding the ClusterConfig.FallbackMaxLights most important visible lights.
Create it once the device is ready, call ClusteredLightSystem.Update or ClusteredLightSystem.UpdateCamera each frame, and draw with NewClusteredLitPBRPipeline or a custom shader that prepends CameraWGSL and ClusteredLightSystem.BindingsWGSL, binding the system with ClusteredLightSystem.Bind in place of a GPULightBuffer.
func NewClusteredLightSystem(cx *core.Scope, dev *gpu.Device, cfg ClusterConfig) (*ClusteredLightSystem, error)NewClusteredLightSystem validates cfg, inspects dev's GPU capabilities, and allocates either the storage-buffer clustered lighting path or the uniform-buffer fallback path scoped to cx. In clustered mode it returns an error wrapping ErrInvalidClusterConfig when the light or index storage buffer cfg needs exceeds dev's MaxStorageBufferBindingSize.
func (s *ClusteredLightSystem) Bind(pass *gpu.RenderPass)Bind sets s's bind group at LightGroup on pass, like GPULightBuffer.Bind. It records nothing when s is not ClusteredLightSystem.Valid.
func (s *ClusteredLightSystem) BindGroup() *gpu.BindGroupBindGroup returns the bind group a render pass sets at LightGroup.
func (s *ClusteredLightSystem) BindingsWGSL() stringBindingsWGSL returns the LightGroup declarations and shade_pbr_clustered helper matching s's active path (ClusteredBindingsWGSL or ClusteredFallbackBindingsWGSL).
func (s *ClusteredLightSystem) ByteSize() uint64ByteSize returns the total GPU buffer memory owned by s, for RenderStats and Budget accounting.
func (s *ClusteredLightSystem) Close() errorClose releases all GPU resources owned by s now instead of when their scope is disposed. Safe to call on nil or more than once.
func (s *ClusteredLightSystem) Config() ClusterConfigConfig returns the normalized ClusterConfig used to construct s.
func (s *ClusteredLightSystem) FallbackLights() []ClusterLightFallbackLights returns the prioritized lights uploaded on the most recent update in fallback mode (nil in clustered mode).
func (s *ClusteredLightSystem) Grid() *ClusterGridGrid returns the underlying ClusterGrid in clustered mode, or nil in fallback mode.
func (s *ClusteredLightSystem) IsClustered() boolIsClustered reports whether s is running the storage-buffer clustered forward shading path.
func (s *ClusteredLightSystem) IsFallback() boolIsFallback reports whether s is running the uniform-buffer mobile / WebGL 2 / GLES 3.0 fallback path.
func (s *ClusteredLightSystem) LastStats() ClusterStatsLastStats returns the ClusterStats from the most recent ClusteredLightSystem.Update or ClusteredLightSystem.UpdateCamera call.
func (s *ClusteredLightSystem) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout a pipeline lists at LightGroup.
func (s *ClusteredLightSystem) Update(dev *gpu.Device, view, proj math3d.Mat4, near, far, viewportW, viewportH float32, rig LightRig, lights []ClusterLight) (ClusterStats, error)Update validates rig and lights, assigns lights for the frame, and uploads the rig and the resulting light buffers to dev. viewportW and viewportH are the size of the rendered area the fragment shader's @builtin(position) covers, starting at its origin: under a DynamicResolutionTarget pass DynamicResolutionTarget.ScaledSize, not the native size.
It returns an error wrapping ErrInvalidLight for a malformed rig, or ErrInvalidClusterLight for a light that fails ClusterLight.Validate (including Range 0; see ClusterLightFromPoint), and uploads nothing in that case. Lights with zero intensity or color are culled.
In clustered mode, lights are binned into view-space frustum clusters via ClusterGrid.AssignLights. In fallback mode, the top ClusterConfig.FallbackMaxLights visible lights are selected as SelectFallbackLights does; CulledLights counts lights outside the frustum or without power and TruncatedLights those dropped by the cap. Steady-state calls allocate nothing beyond the copies gpu.Device.WriteBuffer queues.
func (s *ClusteredLightSystem) UpdateCamera(dev *gpu.Device, cam *scene3d.Camera, viewportW, viewportH float32, rig LightRig, lights []ClusterLight) (ClusterStats, error)UpdateCamera is ClusteredLightSystem.Update with view, projection, near, and far taken from cam.
func (s *ClusteredLightSystem) Valid() boolValid reports whether s's GPU resources are open and belong to a live device.
func (s *ClusteredLightSystem) WGSL() stringWGSL returns the ready-made shader matching s's active path (ClusteredLitWGSL or ClusteredFallbackWGSL).
type ColoredMesh struct {
Positions []math3d.Vec3
Normals []math3d.Vec3
UVs []math3d.Vec2
Colors []math3d.Vec4
Indices []uint32
}ColoredMesh is indexed or non-indexed triangle-list geometry with optional linear RGBA vertex colors (glTF COLOR_0), ready to upload to a gpu.Device via UploadColoredMesh.
Positions is required. Normals, UVs, and Colors are optional: each must be empty or have one entry per position. When Colors is empty, ColoredMesh.AppendVertexData fills every vertex with linear opaque white (1, 1, 1, 1) so meshes with and without vertex colors share one ColoredVertexLayout and pipeline.
func ColoredMeshFromGLTF(doc *gltf.Document, meshIndex, primIndex int) (ColoredMesh, error)ColoredMeshFromGLTF extracts a triangle-list ColoredMesh from doc.Meshes[meshIndex].Primitives[primIndex], including decoded linear RGB/RGBA vertex colors from COLOR_0 (where glTF VEC3 colors have alpha 1.0) and optional KHR_texture_transform UVs when the primitive's material specifies a baseColorTexture transform or UV set.
Returns an error wrapping ErrInvalidMesh if doc is nil, either index is out of range, the primitive topology is not gltf.ModeTriangles, or the resulting mesh fails validation.
func (m ColoredMesh) AppendIndexData(dst []byte) []byteAppendIndexData appends m's indices to dst at ColoredMesh.IndexFormat width, little-endian and zero-padded to ColoredMesh.IndexDataSize. It allocates only when dst lacks capacity. Call ColoredMesh.Validate first.
func (m ColoredMesh) AppendVertexData(dst []byte) []byteAppendVertexData appends m's vertices to dst in the little-endian interleaved layout of ColoredVertexLayout and returns the extended slice. Missing normals and UVs are written as zeros; missing vertex colors are written as linear white (1, 1, 1, 1). It allocates only when dst lacks capacity for ColoredMesh.VertexDataSize more bytes. Call ColoredMesh.Validate first.
func (m ColoredMesh) Bounds() math3d.AABBBounds returns the axis-aligned box around m's positions, or math3d.AABBEmpty when m has none.
func (m ColoredMesh) HasVertexColors() boolHasVertexColors reports whether m carries explicit per-vertex colors.
func (m ColoredMesh) IndexDataSize() intIndexDataSize returns the byte length ColoredMesh.AppendIndexData appends, zero-padded to a multiple of four bytes.
func (m ColoredMesh) IndexFormat() gpu.IndexFormatIndexFormat returns gpu.IndexUint16 when every vertex fits below 0xFFFF (kept free for WebGL 2 primitive restart), otherwise gpu.IndexUint32.
func (m ColoredMesh) Indexed() boolIndexed reports whether m has an index list.
func (m ColoredMesh) Mesh() MeshMesh returns the base Mesh geometry (positions, normals, UVs, and indices) without vertex colors.
func (m ColoredMesh) Validate() errorValidate reports whether m can be uploaded: all Mesh.Validate rules plus Colors empty or matching len(Positions) with finite components. Every error wraps ErrInvalidMesh.
func (m ColoredMesh) VertexCount() intVertexCount returns the number of vertices, len(m.Positions).
func (m ColoredMesh) VertexDataSize() intVertexDataSize returns the byte length ColoredMesh.AppendVertexData appends.
type Cubemap struct {
Faces [6]*image.RGBA
Mips [][6]*image.RGBA
SRGB bool
}Cubemap holds a 6-face square cubemap on the CPU in canonical WebGPU / Metal / Direct3D / OpenGL order (gpu.CubeFacePosX..gpu.CubeFaceNegZ), ready to upload with UploadCubemap or process into IBL data with ComputeIrradianceSH and PrefilterEnvironment.
Faces holds mip level 0: six non-nil square RGBA images of equal dimensions. Mips optionally holds additional precomputed mip levels starting at level 1 (so Mips[0] is mip level 1 of edge max(Size>>1, 1)), such as GGX-prefiltered specular environment levels. When SRGB is true, texel RGB channels are sRGB-encoded and CPU integration decodes to linear before filtering.
Texels are 8 bits per channel, so a Cubemap holds a low dynamic range environment: radiance above 1 is clamped, here and in the faces PrefilterEnvironment and IrradianceSH.ToCubemap write, which flattens bright sun or sky highlights in image-based lighting. Use HDRCubemap and UploadCubemapHDR when the environment needs radiance above 1.
func BakeReflectionProbeCPU(probe *ReflectionProbe, size int, srgb bool, sample func(origin, dir math3d.Vec3) [3]float32) (*Cubemap, error)BakeReflectionProbeCPU samples a 6-face Cubemap of resolution size x size from probe.Position using sample(origin, dir), which returns linear RGB radiance in [0, 1]. When srgb is true, texels are sRGB-encoded and Cubemap.SRGB is set.
func CubemapFromEquirectangular(img image.Image, faceSize int, srgb bool) (*Cubemap, error)CubemapFromEquirectangular projects a latitude-longitude (equirectangular) panorama into a 6-face cubemap of resolution faceSize x faceSize per face using seamless horizontal wrapping and bilinear filtering.
Longitude u = 0.5 + atan2(z, x) / (2*pi) maps +X to u = 0.5 and +Z to u = 0.75; latitude v = acos(y) / pi maps +Y (zenith) to the top row (v = 0) and -Y (nadir) to the bottom row (v = 1). Texels are copied unchanged, and srgb marks them as sRGB-encoded, as in CubemapFromImages: pass true for a typical PNG or JPEG panorama.
func CubemapFromImages(faces [6]image.Image, srgb bool) (*Cubemap, error)CubemapFromImages copies six square image.Image faces (+X, -X, +Y, -Y, +Z, -Z) into a normalized Cubemap. Every face must be non-nil, square, and of identical resolution.
func GradientSkyCubemap(zenith, horizon, ground [3]float32, faceSize int) (*Cubemap, error)GradientSkyCubemap builds a procedural 3-band sky cubemap interpolating smoothly from horizon to zenith across the upper hemisphere (y >= 0) and from horizon to ground across the lower hemisphere (y < 0). Colors are linear RGB values; they must be finite and non-negative, and the RGBA8 faces clamp them to [0, 1].
func PrefilterEnvironment(env *Cubemap, opts PrefilterOptions) (*Cubemap, error)PrefilterEnvironment builds a split-sum GGX prefiltered specular cubemap mip chain from env (Karis 2013). Mip level 0 corresponds to roughness 0 (mirror reflection) and mip level MipLevels-1 corresponds to roughness 1. The process is deterministic (Hammersley quasi-Monte-Carlo) and uses filtered source mip lookups to suppress fireflies.
func (c *Cubemap) MipLevels() intMipLevels returns the total number of mip levels stored in c (1 when Mips is empty), or 0 if c has no base face.
func (c *Cubemap) Sample(dir math3d.Vec3) [3]float32Sample bilinearly samples mip level 0 of c in direction dir and returns linear RGB values.
func (c *Cubemap) SampleLOD(dir math3d.Vec3, lod float32) [3]float32SampleLOD trilinearly samples c at mip level lod (clamped to [0, MipLevels-1]) in direction dir and returns linear RGB values.
func (c *Cubemap) Size() intSize returns the edge length in texels of mip level 0, or 0 if invalid.
func (c *Cubemap) Validate() errorValidate checks that c is non-nil, every base face is non-nil and square with matching positive dimensions, and every optional mip level has the exact expected dimensions down to 1x1. Every error wraps ErrInvalidCubemap.
type CubemapUpload struct {
// Label names the GPU texture and sampler in GPU capture tools.
Label string
// Format overrides the GPU texture format. When [gpu.FormatUndefined], [gpu.FormatRGBA8UnormSRGB] is selected when cm.SRGB is true and [gpu.FormatRGBA8Unorm] otherwise.
Format gpu.TextureFormat
// GenerateMips builds a full 2x2 box-filtered mip chain on the CPU before uploading when cm only carries mip level 0. Ignored when cm already has precomputed Mips (such as from [PrefilterEnvironment]).
GenerateMips bool
// Retained keeps CPU shadow copies of the texture and sampler so NSGo recreates them automatically after a device loss.
Retained bool
}CubemapUpload configures UploadCubemap.
type CustomMaterial struct {
// contains filtered or unexported fields
}CustomMaterial is a compiled WGSL or Kage 3D material with declared, strongly-typed uniform and texture parameters on an NSGo gpu.Device.
Its uniform buffer, fallback 1x1 textures, default sampler, bind group, and pipeline belong to the core.Scope passed to NewCustomMaterial and are released automatically on scope disposal or earlier via CustomMaterial.Close. Call CustomMaterial.Sync (or CustomMaterial.Update) before drawing whenever parameters have been modified, then bind with CustomMaterial.Bind or draw directly with CustomMaterial.Draw.
func NewCustomMaterial(cx *core.Scope, dev *gpu.Device, desc CustomShaderDesc) (*CustomMaterial, error)NewCustomMaterial validates desc, compiles the WGSL or Kage shader, computes the std140 uniform layout, allocates GPU resources scoped to cx, and builds the render pipeline on dev.
func (m *CustomMaterial) ApplyMap(values map[string]any) errorApplyMap validates and applies a batch of named parameters atomically (in deterministic sorted key order). If any key is unknown or has an incompatible type or out-of-range value, no parameter is mutated and an error wrapping ErrInvalidCustomMaterial is returned.
func (m *CustomMaterial) Bind(pass *gpu.RenderPass)Bind sets the material's pipeline and, when it has one, binds its @group(1) bind group on pass. The caller binds group 0 (the camera) and, when the material was created with DrawLayout or ExtraLayout, groups 2 and 3. It records nothing when the material is invalid.
func (m *CustomMaterial) BindGroup() *gpu.BindGroupBindGroup returns the material's @group(1) gpu.BindGroup, or nil when the material declares no parameters and has no DrawLayout.
func (m *CustomMaterial) ByteSize() uint64ByteSize returns the GPU memory the material owns, in bytes: its uniform buffer plus its 1x1 fallback textures, for RenderStats and Budget accounting. Textures bound with CustomMaterial.SetTexture belong to the caller and are not counted.
func (m *CustomMaterial) Close() errorClose releases every GPU resource owned by the material now rather than waiting for its owning scope to dispose. It is safe to call on a nil receiver or more than once.
func (m *CustomMaterial) Dirty() boolDirty reports whether parameter updates are waiting for CustomMaterial.Sync.
func (m *CustomMaterial) Draw(pass *gpu.RenderPass, mesh *GPUMesh)Draw binds the material on pass and draws mesh. It records nothing if either the material or mesh is invalid.
func (m *CustomMaterial) Layout() *gpu.BindGroupLayoutLayout returns the material's @group(1) gpu.BindGroupLayout, or nil when the material declares no parameters and has no DrawLayout.
func (m *CustomMaterial) ParamBinding(name string) (texBinding, samplerBinding uint32, ok bool)ParamBinding returns the @group(1) texture and sampler binding numbers for the ParamTexture parameter named name.
func (m *CustomMaterial) ParamOffset(name string) (int, bool)ParamOffset returns the std140 byte offset of the uniform parameter named name, or (0, false) if absent or not a uniform parameter.
func (m *CustomMaterial) Params() []ShaderParamDescParams returns a copy of the material's declared parameters.
func (m *CustomMaterial) Pipeline() *gpu.PipelinePipeline returns the material's compiled gpu.Pipeline, or nil.
func (m *CustomMaterial) SetBool(name string, v bool) errorSetBool sets a declared ParamBool parameter (encoded as u32 1 or 0).
func (m *CustomMaterial) SetColor(name string, c core.Color) errorSetColor sets a declared ParamColor parameter from an sRGB core.Color, normalized into [0, 1] RGBA float32 components.
func (m *CustomMaterial) SetFloat(name string, v float32) errorSetFloat sets a declared ParamFloat parameter.
func (m *CustomMaterial) SetInt(name string, v int32) errorSetInt sets a declared ParamInt parameter.
func (m *CustomMaterial) SetTexture(name string, tex *GPUTexture, samp *GPUSampler) errorSetTexture binds tex and samp to a declared ParamTexture parameter. Passing a nil tex resets the slot to its 1x1 fallback texture; passing a nil samp uses the material's default linear-repeat sampler. Call CustomMaterial.Sync before drawing to upload the updated bind group.
func (m *CustomMaterial) SetVec2(name string, v math3d.Vec2) errorSetVec2 sets a declared ParamVec2 parameter.
func (m *CustomMaterial) SetVec3(name string, v math3d.Vec3) errorSetVec3 sets a declared ParamVec3 parameter.
func (m *CustomMaterial) SetVec4(name string, v math3d.Vec4) errorSetVec4 sets a declared ParamVec4 or ParamColor parameter.
func (m *CustomMaterial) Sync(dev *gpu.Device) errorSync uploads dirty uniform bytes to the GPU uniform buffer and, when texture bindings changed, switches to the @group(1) bind group for the new textures and samplers. The material keeps bind groups for its 8 most recently bound combinations, so alternating between a few textures (a flipbook, a ping-pong render target) creates no new GPU objects once each combination has been bound. When nothing is dirty it returns nil with zero allocations.
func (m *CustomMaterial) UniformBytes() []byteUniformBytes returns a copy of the current CPU-side std140 uniform buffer.
func (m *CustomMaterial) UniformSize() intUniformSize returns the byte size of the material's std140 uniform buffer (a multiple of 16, or 0 when the material declares no uniform parameters).
func (m *CustomMaterial) Update(dev *gpu.Device) errorUpdate is an alias for CustomMaterial.Sync.
func (m *CustomMaterial) Valid() boolValid reports whether the material's GPU pipeline, uniform buffer, and bind group are open and belong to a live device.
func (m *CustomMaterial) WGSL() stringWGSL returns the final portable WGSL source compiled for this material.
type CustomMaterialError struct {
Material string
Param string
Line int
Column int
Message string
Err error
}CustomMaterialError reports a validation, shader-compilation, or parameter update error for a CustomMaterial. It always matches ErrInvalidCustomMaterial and ErrInvalidMaterial via errors.Is and unwraps to Err when an underlying error is present.
func (e *CustomMaterialError) Error() stringError formats the custom material diagnostic with optional material name, parameter name, and 1-based shader source line/column.
func (e *CustomMaterialError) Is(target error) boolIs reports that every CustomMaterialError matches ErrInvalidCustomMaterial and ErrInvalidMaterial.
func (e *CustomMaterialError) Unwrap() errorUnwrap returns the underlying error, if any.
type CustomParamLayout struct {
Name string
Kind ShaderParamKind
Offset int // byte offset in uniform buffer (0 for ParamTexture)
Align int // std140 alignment in bytes (0 for ParamTexture)
Size int // byte size in uniform buffer (0 for ParamTexture)
TextureBinding uint32 // @binding index in CustomMaterialGroup (ParamTexture only)
SamplerBinding uint32 // @binding index in CustomMaterialGroup (ParamTexture only)
}CustomParamLayout records the computed GPU location of one declared parameter.
type CustomShaderDesc struct {
Label string
Language ShaderLanguage
Source string
VertexEntry string // defaults to "vs_main"
FragmentEntry string // defaults to "fs_main" (or "Surface" / "Fragment" for ShaderKage)
Params []ShaderParamDesc
// CameraLayout optionally supplies the @group(0) bind group layout (such as CameraBuffer.Layout()). When it is set and Source declares nothing in @group(0), [CameraWGSL] is prepended, with or without ManualBindings. When it is nil, a source that declares @group(0) gets a layout with one uniform buffer at binding 0, the layout [CameraBuffer] uses; any other group 0 binding is refused.
CameraLayout *gpu.BindGroupLayout
// DrawLayout, when set, is placed at [PBRDrawGroup] (group 2) so the shader can read a per-draw transform: pass [PBRDrawBuffer.Layout], and bind [PBRDrawBuffer.BindGroup] at [PBRDrawGroup] before each draw. A ShaderKage shader then declares the [PBRDrawUniform] block as pbr_draw and transforms positions by its model matrix and normals by its normal matrix, so Surface's normal and worldPos are in world space. A ShaderWGSL source declares the block itself, as [LitPBRWGSL] does. Without DrawLayout, the Kage vertex stage passes positions and normals through unchanged, so worldPos and normal are in object space and the mesh draws where its vertices are.
DrawLayout *gpu.BindGroupLayout
// ExtraLayout, when set, is placed at group 3 for bindings the shader declares itself and the caller binds before drawing, such as a [GPULightBuffer] declared with [LightWGSLForGroup](3) (group 1, where [LightWGSL] puts lights, holds the material) or a [DirectionalShadowMap] declared with [ShadowWGSL]. It requires DrawLayout, since group 2 then needs a layout too.
ExtraLayout *gpu.BindGroupLayout
// ManualBindings disables automatic generation of the @group(1) MaterialParams uniform struct and texture/sampler declarations for ShaderWGSL when the shader source declares them explicitly. It does not affect the [CameraWGSL] preamble.
ManualBindings bool
// Pipeline render state.
Blend *gpu.BlendState // nil defaults to gpu.BlendOpaque()
Cull gpu.CullMode // zero value is gpu.CullNone
FrontFace gpu.FrontFace // zero value is gpu.FrontCCW
DepthWrite *bool // nil defaults to true when DepthFormat != gpu.FormatUndefined
DepthCompare gpu.CompareFunc // zero value defaults to gpu.CompareLess
ColorFormat gpu.TextureFormat // zero value defaults to dev.SurfaceFormat()
DepthFormat gpu.TextureFormat // FormatUndefined disables depth testing
SampleCount int // 0 defaults to 1
Retained bool // opt in to automatic restoration across device loss
}CustomShaderDesc configures a CustomMaterial compiled on a gpu.Device.
type CustomUniformLayout struct {
Params []CustomParamLayout
Offsets map[string]int
UniformSize int // total uniform buffer size in bytes (multiple of 16, or 0 if no uniform params)
HasUniforms bool
TextureNum int
}CustomUniformLayout holds the deterministic std140 uniform layout and texture/sampler binding indices computed for a list of ShaderParamDesc.
func ComputeUniformLayout(params []ShaderParamDesc) (CustomUniformLayout, error)ComputeUniformLayout validates params and computes their deterministic WGSL/std140 uniform offsets and @group(1) texture/sampler bindings in declared order.
type DebugDraw struct {
// DefaultWidth is the stroke width in points used when a line has Width <= 0
// (defaults to 1.5 when zero).
DefaultWidth float32
// DepthNO clips at the near plane of an OpenGL-style [-1, 1] depth projection, as [ProjectSegmentNO] does. By default lines clip for [0, 1] depth, matching [math3d.Perspective] and [math3d.Ortho].
DepthNO bool
// contains filtered or unexported fields
}DebugDraw collects 3D wireframe debug primitives (lines, boxes, spheres, rays, coordinate axes, grids, and camera frustums) and projects them into *core.Drawing (#286). Its backing slice is reused across frames via DebugDraw.Clear.
func (dd *DebugDraw) AABB(box math3d.AABB, color core.Color)AABB appends the 12 wireframe edges of box. Empty boxes emit no lines.
func (dd *DebugDraw) Axes(origin math3d.Vec3, length float32)Axes appends RGB right-handed X/Y/Z coordinate axes at origin.
func (dd *DebugDraw) Clear()Clear resets the recorded debug lines while retaining slice capacity.
func (dd *DebugDraw) Flush(d *core.Drawing, viewProj math3d.Mat4, viewport core.Bounds)Flush projects all recorded 3D debug lines through viewProj into d, batching consecutive segments that share the same color and stroke width.
func (dd *DebugDraw) Frustum(invViewProj math3d.Mat4, color core.Color)Frustum appends the 12 wireframe edges of a camera frustum given its inverse view-projection matrix (assuming WebGPU/Metal [0, 1] NDC depth).
func (dd *DebugDraw) Grid(center math3d.Vec3, halfExtent float32, divisions int, color core.Color)Grid appends an XZ reference grid centered at center spanning [-halfExtent, +halfExtent] with divisions cells per side.
func (dd *DebugDraw) Line(a, b math3d.Vec3, color core.Color)Line appends a 3D line segment from a to b in color.
func (dd *DebugDraw) LineWidth(a, b math3d.Vec3, color core.Color, width float32)LineWidth appends a 3D line segment with an explicit stroke width in points.
func (dd *DebugDraw) Lines() []DebugLineLines returns the currently queued 3D wireframe segments.
func (dd *DebugDraw) Ray(ray math3d.Ray, length float32, color core.Color)Ray appends a line segment along ray of length length.
func (dd *DebugDraw) Sphere(center math3d.Vec3, radius float32, color core.Color, segments int)Sphere appends three orthogonal great circles (XY, XZ, YZ) centered at center with radius. Segments defaults to 24 when <= 0.
type DebugLine struct {
A, B math3d.Vec3
Color core.Color
Width float32
}DebugLine is a single 3D wireframe segment queued in DebugDraw.
type DepthOfFieldConfig struct {
// FocusDistance is the view-space distance from the camera that renders sharpest (> 0). Default: 5.0.
FocusDistance float32
// FocusRange is the half-width around FocusDistance over which the Circle of Confusion ramps from 0 (in focus) to 1 (maximum blur). Must be > 0. Default: 2.0.
FocusRange float32
// MaxBlurRadius is the maximum bokeh disc radius in pixels at CoC = 1 (>= 0). 0 leaves the scene unchanged. Default: 6.0.
MaxBlurRadius float32
// Near and Far are the camera clip planes used to linearize [0, 1] depth values: Near < Far, and Near > 0 for a perspective projection. They must match the projection that wrote the depth buffer; [DepthOfFieldConfigFromCamera] and [PostStack3D.SetCamera] read them from the camera's projection matrix.
Near float32
Far float32
// Orthographic selects linear orthographic depth reconstruction instead of perspective.
Orthographic bool
}DepthOfFieldConfig tunes depth-aware disc bokeh Depth of Field.
func DefaultDepthOfFieldConfig() DepthOfFieldConfigDefaultDepthOfFieldConfig returns balanced defaults for 3D Depth of Field.
func DepthOfFieldConfigFromCamera(cam *scene3d.Camera, focusDistance, focusRange, maxBlurRadius float32) DepthOfFieldConfigDepthOfFieldConfigFromCamera initializes a DepthOfFieldConfig with the clip planes and projection kind of cam's projection matrix, so a projection whose fields scene3d.Projection.Matrix fills in with defaults still linearizes depth correctly.
func (c DepthOfFieldConfig) Validate() errorValidate checks that every field of c is finite and within its valid range. Every error wraps ErrInvalidPostProcess.
type DepthOfFieldPass struct {
// contains filtered or unexported fields
}DepthOfFieldPass computes per-pixel signed Circle of Confusion from depth and gathers a depth-aware disc bokeh blur that keeps in-focus silhouettes sharp.
func NewDepthOfFieldPass(cx *core.Scope, dev *gpu.Device, opts DepthOfFieldPassOptions) (*DepthOfFieldPass, error)NewDepthOfFieldPass creates a scope-owned DepthOfFieldPass on dev.
func (p *DepthOfFieldPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) errorApply runs the CoC prepass and depth-aware disc bokeh gather from srcColor and depthTex into dstColor. A nil dstColor writes to the swapchain in OutputFormat, and a texture dstColor must be in ColorFormat or OutputFormat. Every texture must have the pass size and dstColor cannot also be an input; otherwise Apply returns an error wrapping ErrInvalidPostProcess.
func (p *DepthOfFieldPass) Close() errorClose releases all GPU resources owned by p. It is safe to call on a nil receiver or more than once.
func (p *DepthOfFieldPass) Config() DepthOfFieldConfigConfig returns the pass's current DepthOfFieldConfig.
func (p *DepthOfFieldPass) Height() uint32Height returns the configured target height in pixels.
func (p *DepthOfFieldPass) Resize(dev *gpu.Device, width, height uint32) errorResize recreates the pass's offscreen CoC target for a new viewport size.
func (p *DepthOfFieldPass) SetConfig(cfg DepthOfFieldConfig) errorSetConfig validates and updates the Depth of Field parameters.
func (p *DepthOfFieldPass) Valid() boolValid reports whether the pass is open and its GPU resources are live.
func (p *DepthOfFieldPass) Width() uint32Width returns the configured target width in pixels.
type DepthOfFieldPassOptions struct {
Label string
Width uint32
Height uint32
ColorFormat gpu.TextureFormat // intermediate color/CoC format: RGBA16Float (the default), RGBA8Unorm, RGBA8UnormSRGB, BGRA8Unorm or BGRA8UnormSRGB
OutputFormat gpu.TextureFormat // destination format; defaults to dev.SurfaceFormat() or FormatRGBA8Unorm
Retained bool
Config DepthOfFieldConfig
}DepthOfFieldPassOptions configures NewDepthOfFieldPass.
type DirectionalLight struct {
Direction math3d.Vec3
Color math3d.Vec3
Intensity float32
}DirectionalLight is an infinitely distant light source whose parallel rays travel along Direction.
Direction is the world-space travel direction of light rays (for example, (0, -1, 0) shines straight down onto a horizontal +Y surface); it does not need to be unit length and is normalized when shaded or packed for the GPU. Color is linear RGB tint (non-negative finite channels), and Intensity scales Color to produce linear illuminance.
func (l DirectionalLight) Validate() errorValidate reports whether l has a finite non-zero direction, finite non-negative color channels, and a finite non-negative intensity. Every error wraps ErrInvalidLight.
type DirectionalShadowConfig struct {
// Direction is the world-space direction light rays travel (from the sun toward the scene). It need not be unit length, but must be finite and non-zero. With [LitPBRShadowWGSL] set it to the Direction of the [LightRig]'s first directional light, the one the shadow attenuates.
Direction math3d.Vec3
// Target is the world-space center of the orthographic shadow volume used by [DirectionalShadowConfig.LightViewProj] (ignored by [DirectionalShadowConfig.FitBounds]).
Target math3d.Vec3
// OrthoSize is the full width and height (in world units) of the square orthographic frustum used by [DirectionalShadowConfig.LightViewProj]. When zero, defaults to 20.
OrthoSize float32
// DepthRange is the full depth of the orthographic volume of [DirectionalShadowConfig.LightViewProj] along Direction, centred on Target: points DepthRange/2 toward the light from Target map to depth 0 and points DepthRange/2 past it map to depth 1, so casters and receivers must lie within that slab. Zero defaults to max(OrthoSize*2, 100). [DirectionalShadowConfig.FitBounds] ignores it and derives the depth range from the bounds.
DepthRange float32
// Resolution is the shadow map width and height in texels used to compute TexelSize and texel snapping. Zero defaults to [DefaultShadowResolution] (1024).
Resolution uint32
// DepthBias is the receiver-side depth bias in [0, 1] clip depth units (non-negative).
DepthBias float32
// NormalBias is the world-space offset applied along the receiver's surface normal before projecting into light space (non-negative).
NormalBias float32
// PCFKernel selects [ShadowFilterHard] (1-tap) or [ShadowFilterPCF3x3] (9-tap 3x3 PCF).
PCFKernel ShadowFilter
// Strength scales shadow darkness in [0, 1] (0 disables shadows; 1 fully occludes the directional light in shadow).
Strength float32
// TexelSnap keeps the shadow map's texel grid fixed in world space so shadow edges do not shimmer as the framing moves: the light-space XY center snaps to whole shadow-map texels, and [DirectionalShadowConfig.FitBounds] sizes the frustum from the bounds' bounding sphere, rounded up to a coarse step, instead of their exact light-space extent, so the texel size stays constant while the bounds move or the light turns.
TexelSnap bool
// CasterPadding extends the near plane of [DirectionalShadowConfig.FitBounds] backward toward the light (in world units, non-negative) so occluders slightly behind the fitted bounds still cast shadows.
CasterPadding float32
}DirectionalShadowConfig holds the mathematical and shading parameters for a directional light's orthographic shadow frustum.
func DefaultDirectionalShadowConfig() DirectionalShadowConfigDefaultDirectionalShadowConfig returns a ready-to-use directional shadow configuration with 1024x1024 3x3 PCF shadows, texel snapping, and balanced depth/normal bias.
func (c DirectionalShadowConfig) FitBounds(lightDir math3d.Vec3, sceneBounds math3d.AABB) (math3d.Mat4, error)FitBounds computes an orthographic light-space view-projection matrix (with [0, 1] NDC depth) framing sceneBounds along lightDir (falling back to c.Direction when lightDir is zero).
Without c.TexelSnap the frustum hugs the bounds' light-space extent, which gives the most shadow-map texels per world unit but changes the texel size whenever the bounds or the light move. With c.TexelSnap the frustum width is the diameter of the bounds' bounding sphere plus a margin, rounded up to a multiple of a sixteenth of the next power of two: that width does not change as the light turns and changes only in coarse steps as the bounds grow or shrink, and the light-space XY center then snaps to whole texels, so between two fits with the same width every static world point moves by a whole number of texels and shadow edges do not shimmer. Every corner of sceneBounds stays inside [0, 1]^2 either way.
func (c DirectionalShadowConfig) LightViewProj() (math3d.Mat4, error)LightViewProj computes the orthographic light-space view-projection matrix (with [0, 1] NDC depth) centered on c.Target, c.OrthoSize wide and high and c.DepthRange deep, with c.Target at depth 0.5. When c.TexelSnap is true, the light-space XY center is snapped to exact texel increments of c.Resolution to eliminate shadow swimming.
func (c DirectionalShadowConfig) Uniforms(lightViewProj math3d.Mat4) ShadowUniformsUniforms packages c and lightViewProj into a ShadowUniforms ready to upload with AppendShadowUniforms or DirectionalShadowMap.WriteUniforms.
func (c DirectionalShadowConfig) UniformsForBounds(sceneBounds math3d.AABB) (ShadowUniforms, error)UniformsForBounds fits c to sceneBounds via DirectionalShadowConfig.FitBounds and returns the resulting ShadowUniforms.
func (c DirectionalShadowConfig) Validate() errorValidate checks that every field of c is finite and within valid ranges. Every error wraps ErrInvalidShadow.
type DirectionalShadowMap struct {
// contains filtered or unexported fields
}DirectionalShadowMap manages an offscreen depth-only shadow map *gpu.RenderTarget, a depth-only caster pipeline (ShadowDepthWGSL), a dynamic-offset caster transform buffer, the directional ShadowUniforms buffer, and both nearest (hard) and linear (PCF) comparison samplers/bind groups.
Create it once when the GPU device is ready (with Retained: true to survive device loss automatically), call DirectionalShadowMap.Update or DirectionalShadowMap.UpdateBounds each frame, record casters between DirectionalShadowMap.BeginShadowPass and pass.End(), and bind DirectionalShadowMap.BindGroup at ShadowGroup during the main lit render pass. Its resources belong to the *core.Scope passed to NewDirectionalShadowMap and are released when that scope is disposed or when DirectionalShadowMap.Close is called.
func NewDirectionalShadowMap(cx *core.Scope, dev *gpu.Device, opts ShadowMapOptions) (*DirectionalShadowMap, error)NewDirectionalShadowMap validates opts and allocates all GPU resources for directional shadow mapping on dev, scoped to cx. Invalid options return an error wrapping ErrInvalidShadow before creating any GPU object; a nil or lost device returns gpu.ErrDeviceLost.
func (s *DirectionalShadowMap) BeginShadowPass(dev *gpu.Device, target ShadowPassTarget) *gpu.RenderPassBeginShadowPass resets the per-pass caster slot cursor, opens a depth-only render pass clearing the shadow map depth to 1.0, and binds the shadow depth pipeline. Pass the live *gpu.Device and either a *gpu.Encoder or *gpu.Frame as target. Returns nil when s, dev, or target is nil or s is invalid (after DirectionalShadowMap.Close, or while the device is lost for a map that is not Retained), so check the result before drawing casters and calling End.
func (s *DirectionalShadowMap) BindGroup() *gpu.BindGroupBindGroup returns the bind group for sampling the shadow map at ShadowGroup, automatically selecting the nearest comparison sampler for ShadowFilterHard and the linear comparison sampler for ShadowFilterPCF3x3.
func (s *DirectionalShadowMap) ByteSize() uint64ByteSize returns the GPU memory held by the shadow map depth texture (4 bytes per texel for Depth32Float) and uniform buffers, for RenderStats and Budget accounting.
func (s *DirectionalShadowMap) Close() errorClose releases all GPU resources owned by s now rather than waiting for its scope to be disposed. Safe to call on a nil receiver or more than once.
func (s *DirectionalShadowMap) DepthPipeline() *gpu.PipelineDepthPipeline returns the depth-only shadow caster *gpu.Pipeline, or nil for a nil receiver.
func (s *DirectionalShadowMap) DepthTexture() *gpu.TextureDepthTexture returns the depth *gpu.Texture of the shadow map, or nil for a nil receiver.
func (s *DirectionalShadowMap) DrawCaster(pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) boolDrawCaster records one shadow-casting GPUMesh with world transform model inside the shadow pass started by DirectionalShadowMap.BeginShadowPass. Each call writes lightViewProj * model into its own dynamic-offset uniform slot so multiple casters can be drawn in one pass without overwriting earlier draws. Returns false if any argument is invalid or DirectionalShadowMap.MaxCasters slots have been exhausted.
func (s *DirectionalShadowMap) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout for sampling the shadow map (to place at ShadowGroup in lit pipelines), or nil for a nil receiver.
func (s *DirectionalShadowMap) MaxCasters() uint32MaxCasters returns the maximum number of DirectionalShadowMap.DrawCaster calls supported per shadow pass, or zero for a nil receiver.
func (s *DirectionalShadowMap) RenderTarget() *gpu.RenderTargetRenderTarget returns the underlying depth-only *gpu.RenderTarget, or nil for a nil receiver.
func (s *DirectionalShadowMap) Resolution() uint32Resolution returns the shadow map width and height in texels, or zero for a nil receiver.
func (s *DirectionalShadowMap) UniformBuffer() *gpu.BufferUniformBuffer returns the *gpu.Buffer holding ShadowUniforms, or nil for a nil receiver.
func (s *DirectionalShadowMap) Uniforms() ShadowUniformsUniforms returns the most recently written ShadowUniforms.
func (s *DirectionalShadowMap) Update(dev *gpu.Device, cfg DirectionalShadowConfig) (ShadowUniforms, error)Update computes the orthographic light matrix from cfg (using s.Resolution() if cfg.Resolution is zero), uploads the resulting ShadowUniforms on dev, and returns them.
func (s *DirectionalShadowMap) UpdateBounds(dev *gpu.Device, cfg DirectionalShadowConfig, sceneBounds math3d.AABB) (ShadowUniforms, error)UpdateBounds fits the orthographic light frustum to sceneBounds via DirectionalShadowConfig.FitBounds (using s.Resolution() if cfg.Resolution is zero), uploads the resulting ShadowUniforms on dev, and returns them.
func (s *DirectionalShadowMap) Valid() boolValid reports whether all GPU resources owned by s are open and belong to a live device.
func (s *DirectionalShadowMap) WriteUniforms(dev *gpu.Device, u ShadowUniforms)WriteUniforms encodes u into the shadow uniform buffer on dev without heap allocation and selects the matching hard or PCF comparison sampler bind group. Values the shader cannot use are made safe first: a NaN or infinite matrix or Strength disables the shadow, non-finite biases become 0, a missing TexelSize becomes 1/DirectionalShadowMap.Resolution, and an unknown PCFKernel falls back to ShadowFilterHard. DirectionalShadowMap.Uniforms returns the values as written.
type DrawItem struct {
ID uint64
MeshID uint32
MaterialID uint32
PipelineID uint32
Blend BlendMode
Transform math3d.Mat4
WorldBounds math3d.AABB
Triangles uint32
Vertices uint32
LODs []LODLevel // optional; ordered from finest (index 0) to coarsest
}DrawItem describes a single renderable 3D object submitted to Queue.Build.
func FilterLayeredItems(src []LayeredDrawItem, mask uint32, dst []DrawItem) []DrawItemFilterLayeredItems appends every item in src whose Layer intersects mask to dst and returns the extended slice. A zero mask matches nothing, unlike a zero CameraView.LayerMask; pass ViewportContext.LayerMask. Pass dst[:0] with preallocated capacity for zero steady-state allocations per camera view.
type DynamicResolutionConfig struct {
// TargetFrameTime is the GPU frame-time budget the scaler aims to hold.
// Zero defaults to DefaultDynamicResolutionTargetFrameTime (~16.67ms, 60 FPS).
TargetFrameTime time.Duration
// MinScale is the lowest linear resolution scale in (0, 1].
// Zero defaults to DefaultDynamicResolutionMinScale (0.5).
MinScale float32
// MaxScale is the highest linear resolution scale in [MinScale, 1].
// Zero defaults to DefaultDynamicResolutionMaxScale (1.0).
MaxScale float32
// InitialScale optionally sets the starting scale in [MinScale, MaxScale].
// Zero defaults to MaxScale.
InitialScale float32
// Deadband is the fractional hysteresis tolerance in [0, 0.5) around
// TargetFrameTime inside which scale holds steady. Overload triggers above
// TargetFrameTime*(1+Deadband); headroom triggers below TargetFrameTime*(1-Deadband).
// Zero defaults to DefaultDynamicResolutionDeadband (0.05).
Deadband float32
// SmoothingAlpha is the exponential moving average weight in (0, 1] for
// incoming GPU frame-time samples. Zero defaults to DefaultDynamicResolutionSmoothingAlpha (0.25).
SmoothingAlpha float32
// StepDown is the maximum linear scale reduction per adjustment step in (0, 1].
// Zero defaults to DefaultDynamicResolutionStepDown (0.12).
StepDown float32
// StepUp is the maximum linear scale increase per adjustment step in (0, 1].
// Zero defaults to DefaultDynamicResolutionStepUp (0.04).
StepUp float32
// CooldownDown is the minimum number of frames between consecutive
// scale-down steps. Zero defaults to DefaultDynamicResolutionCooldownDown (2);
// set 1 to permit stepping down on every consecutive overloaded frame.
CooldownDown int
// CooldownUp is the minimum number of consecutive headroom frames (and frames
// since the last scale change) required before stepping up. Zero defaults to
// DefaultDynamicResolutionCooldownUp (12); set 1 for immediate recovery.
CooldownUp int
// HitchLimit discards GPU frame-time outliers longer than HitchLimit as
// loading or resume hitches. Zero defaults to DefaultDynamicResolutionHitchLimit (250ms);
// a negative duration disables hitch filtering.
HitchLimit time.Duration
// Alignment rounds scaled widths and heights to a multiple of Alignment
// (clamped to [1, native]) whenever scale < 1. Zero defaults to
// DefaultDynamicResolutionAlignment (2); 1 disables alignment rounding.
Alignment int
// Filter selects the upscaling filter used by [DynamicResolutionTarget].
Filter DynamicResolutionFilter
// Sharpness controls contrast-adaptive sharpening strength in [0, 1] when
// Filter is DynamicResolutionSharpen. Zero defaults to DefaultDynamicResolutionSharpness (0.25).
Sharpness float32
}DynamicResolutionConfig configures DynamicResolutionScaler and DynamicResolutionTarget. Zero-valued numeric fields take defaults from DefaultDynamicResolutionConfig.
func DefaultDynamicResolutionConfig() DynamicResolutionConfigDefaultDynamicResolutionConfig returns the default 60 FPS dynamic resolution configuration (scale in [0.5, 1.0], ±5% deadband, fast scale-down, smooth scale-up, even pixel alignment, bilinear upscaling).
func (c DynamicResolutionConfig) Validate() errorValidate checks c after applying zero-value defaults. Every error wraps ErrInvalidDynamicResolution.
type DynamicResolutionFilter uint8DynamicResolutionFilter selects how DynamicResolutionTarget resamples the scaled 3D render target when upscaling onto the native output surface.
const (
// DynamicResolutionBilinear uses hardware bilinear filtering clamped to the
// active scaled sub-viewport so out-of-viewport texels never bleed inward.
DynamicResolutionBilinear DynamicResolutionFilter = iota
// DynamicResolutionNearest uses nearest-neighbor point sampling for crisp
// pixel-art or retro 3D presentation.
DynamicResolutionNearest
// DynamicResolutionSharpen applies bilinear upscaling followed by a
// contrast-adaptive 5-tap sharpening pass clamped to the local
// neighborhood min/max to restore detail without ringing halos.
DynamicResolutionSharpen
)func (f DynamicResolutionFilter) String() stringString returns the filter name: "bilinear", "nearest", or "sharpen".
func (f DynamicResolutionFilter) Valid() boolValid reports whether f is a recognized filter mode.
type DynamicResolutionScaler struct {
// contains filtered or unexported fields
}DynamicResolutionScaler adapts a linear 3D render resolution scale in [MinScale, MaxScale] to hold a GPU frame-time target (#383).
Because fill-rate cost grows quadratically with linear scale (area = scale²), the controller scales proportionally toward scale * sqrt(target / smoothed) with a symmetric hysteresis deadband around TargetFrameTime, fast response on overload (CooldownDown, StepDown), and conservative recovery under sustained headroom (CooldownUp, StepUp).
DynamicResolutionScaler is pure Go, deterministic, and independent of the GPU device so it can be driven from GPU pass timings, frame timers, or unit tests. It is not safe for concurrent use; call it from the render/loop goroutine.
func NewDynamicResolutionScaler(cfg DynamicResolutionConfig) (*DynamicResolutionScaler, error)NewDynamicResolutionScaler creates a scaler from cfg (applying defaults for zero fields). It returns an error wrapping ErrInvalidDynamicResolution if cfg is invalid.
func (s *DynamicResolutionScaler) ClearFixedScale()ClearFixedScale removes any pinned scale set by [SetFixedScale] and resumes automatic adaptation.
func (s *DynamicResolutionScaler) Config() DynamicResolutionConfigConfig returns the normalized configuration in use by s.
func (s *DynamicResolutionScaler) Enabled() boolEnabled reports whether dynamic resolution scaling is currently active.
func (s *DynamicResolutionScaler) RecordFrameTime(gpuFrameTime time.Duration) float32RecordFrameTime updates the smoothed GPU frame time with gpuFrameTime and adapts Scale() to hold TargetFrameTime, returning the resulting Scale().
Non-positive durations are ignored. Durations exceeding HitchLimit (when HitchLimit > 0) are counted as ignored hitches and do not disturb the EMA or resolution scale. When disabled or pinned via SetFixedScale, the current Scale() is returned without modifying adaptive scale.
func (s *DynamicResolutionScaler) RecordPassTimings(timings []gpu.PassTiming, labels ...string) float32RecordPassTimings sums GPU pass durations from timings (for example from gpu.Device.LastPassTimings or gpu.Frame.PassTimings) and feeds the total into [RecordFrameTime]. When labels are provided, only passes whose Label matches one of labels are summed; when no labels are provided, all positive pass durations are summed.
func (s *DynamicResolutionScaler) Reset()Reset restores the adaptive scale to InitialScale and clears smoothed timing, cooldowns, and counters. Enabled and fixed-scale overrides are preserved.
func (s *DynamicResolutionScaler) Scale() float32Scale returns the active linear resolution scale in (0, 1]. It returns 1.0 when s is nil or disabled, the pinned value when a fixed scale is set, or the adaptive scale otherwise.
func (s *DynamicResolutionScaler) ScaledSize(nativeW, nativeH int) (w, h int)ScaledSize returns the scaled 3D pixel dimensions for a native output target of size (nativeW, nativeH) using the current [Scale] and configured alignment. Returns (0, 0) when either native dimension is non-positive. When Scale() >= 1, (nativeW, nativeH) is returned unchanged.
func (s *DynamicResolutionScaler) SetEnabled(enabled bool)SetEnabled enables or disables dynamic resolution scaling. When disabled, Scale returns 1.0 (native resolution) and RecordFrameTime makes no scale adjustments.
func (s *DynamicResolutionScaler) SetFixedScale(scale float32)SetFixedScale pins the reported scale to a fixed value while dynamic scaling is enabled, disabling automatic frame-time adjustments. Passing a value <= 0 clears the override and resumes automatic adaptation. Positive values are clamped to [MinScale, MaxScale].
func (s *DynamicResolutionScaler) SetScaleBounds(minScale, maxScale float32) errorSetScaleBounds updates MinScale and MaxScale at runtime (for example, when a quality.Selector switches presets and caps MaxScale to Preset.ResolutionScale). Existing scale and fixedScale values are clamped into the new bounds.
func (s *DynamicResolutionScaler) SmoothedFrameTime() time.DurationSmoothedFrameTime returns the current exponential moving average of recorded GPU frame times, or 0 before any valid sample has been recorded.
func (s *DynamicResolutionScaler) Stats() DynamicResolutionStatsStats returns a point-in-time snapshot of s's scale, timings, and counters.
type DynamicResolutionStats struct {
Scale float32
MinScale float32
MaxScale float32
Enabled bool
Fixed bool
LastFrameTime time.Duration
SmoothedFrameTime time.Duration
TargetFrameTime time.Duration
FramesRecorded uint64
HitchesIgnored uint64
ScaleDowns uint64
ScaleUps uint64
}DynamicResolutionStats captures a snapshot of a DynamicResolutionScaler's current scale, frame-time metrics, and adjustment counters.
type DynamicResolutionTarget struct {
// contains filtered or unexported fields
}DynamicResolutionTarget manages an offscreen 3D render target and a full-screen upscale pass so the 3D scene renders at an adaptive resolution scale while the native swapchain and 2D HUD overlays (such as scene.Overlay3D or a follow-up native GPU HUD pass) stay at crisp 1:1 native resolution (#383).
To avoid GPU texture reallocation churn as the resolution scale fluctuates frame to frame, the offscreen RenderTarget is allocated at native capacity and 3D rendering is restricted via SetViewport and SetScissor to the active scaled sub-rectangle [0, 0, scaledW, scaledH]. The upscale pass maps that sub-rectangle across the full native viewport with half-texel UV clamping so unused padding texels never bleed into the image.
func NewDynamicResolutionTarget(cx *core.Scope, dev *gpu.Device, opts DynamicResolutionTargetOptions) (*DynamicResolutionTarget, error)NewDynamicResolutionTarget creates the upscale pipelines, static quad buffer, and samplers on dev owned by cx (nil for caller-closed resources). The offscreen render target itself is allocated lazily on the first [Begin3D] or [EnsureCapacity] call once native dimensions are known.
func (t *DynamicResolutionTarget) AllocatedSize() (w, h int)AllocatedSize returns the backing offscreen render target's pixel capacity.
func (t *DynamicResolutionTarget) Begin3D(rec RenderPassRecorder, nativeW, nativeH int, clearColor core.Color) (*gpu.RenderPass, error)Begin3D ensures offscreen capacity for (nativeW, nativeH), begins a render pass targeting the offscreen color (and optional depth) buffer cleared to clearColor, and configures SetViewport and SetScissor to the current scaled sub-rectangle [0, 0, scaledW, scaledH].
Draw your 3D scene into the returned *gpu.RenderPass and call pass.End(), then call [Upscale] (or [UpscaleIntoPass]) to present the scaled 3D image at native resolution before drawing native-resolution HUD overlays.
func (t *DynamicResolutionTarget) ByteSize() uint64ByteSize estimates the resident GPU memory (in bytes) of the offscreen color and depth attachments for RenderStats.TextureBytes and Budget checks.
func (t *DynamicResolutionTarget) Close() errorClose releases all GPU resources owned by t now rather than waiting for its owning scope. It is safe to call more than once and returns the first error.
func (t *DynamicResolutionTarget) ColorFormat() gpu.TextureFormatColorFormat returns the offscreen 3D color attachment format.
func (t *DynamicResolutionTarget) ColorTexture() *gpu.TextureColorTexture returns the offscreen 3D color attachment texture, or nil before allocation.
func (t *DynamicResolutionTarget) DepthFormat() gpu.TextureFormatDepthFormat returns the offscreen 3D depth attachment format, or gpu.FormatUndefined when depth is disabled.
func (t *DynamicResolutionTarget) DepthTexture() *gpu.TextureDepthTexture returns the offscreen 3D depth attachment texture, or nil when depth is disabled or before allocation.
func (t *DynamicResolutionTarget) EnsureCapacity(nativeW, nativeH int) errorEnsureCapacity guarantees the backing offscreen render target can cover a native resolution of (nativeW, nativeH). The backing target grows on demand and shrinks only when native dimensions drop below half of the allocated capacity, avoiding texture reallocations when scale changes frame to frame.
func (t *DynamicResolutionTarget) Filter() DynamicResolutionFilterFilter returns the active upscale sampling mode.
func (t *DynamicResolutionTarget) NativeSize() (w, h int)NativeSize returns the native output dimensions from the most recent [Begin3D] call.
func (t *DynamicResolutionTarget) OutputFormat() gpu.TextureFormatOutputFormat returns the native color format targeted by [Upscale].
func (t *DynamicResolutionTarget) RecordFrameTime(gpuFrameTime time.Duration) float32RecordFrameTime forwards gpuFrameTime to the target's scaler and returns the updated linear resolution scale.
func (t *DynamicResolutionTarget) RecordPassTimings(timings []gpu.PassTiming, labels ...string) float32RecordPassTimings forwards GPU pass timings to the target's scaler. When no labels are supplied and t was configured with a non-empty TimingLabel, that TimingLabel is matched automatically.
func (t *DynamicResolutionTarget) RenderTarget() *gpu.RenderTargetRenderTarget returns the underlying offscreen *gpu.RenderTarget, or nil before the first [Begin3D] or [EnsureCapacity] call.
func (t *DynamicResolutionTarget) Scale() float32Scale returns the current linear resolution scale from the target's scaler.
func (t *DynamicResolutionTarget) ScaledSize() (w, h int)ScaledSize returns the active scaled 3D viewport dimensions from the most recent [Begin3D] call.
func (t *DynamicResolutionTarget) Scaler() *DynamicResolutionScalerScaler returns the DynamicResolutionScaler controlling t.
func (t *DynamicResolutionTarget) SetFilter(f DynamicResolutionFilter)SetFilter changes the upscale sampling mode without reallocating GPU resources.
func (t *DynamicResolutionTarget) SetSharpness(s float32)SetSharpness updates the sharpening strength in [0, 1] for DynamicResolutionSharpen. Non-finite inputs are ignored.
func (t *DynamicResolutionTarget) Sharpness() float32Sharpness returns the contrast-adaptive sharpening strength used when Filter is DynamicResolutionSharpen.
func (t *DynamicResolutionTarget) Upscale(rec RenderPassRecorder, dst *gpu.Texture, nativeW, nativeH int) errorUpscale opens a native-resolution color render pass targeting dst (or the view's swapchain drawable when dst is nil), draws the full-screen upscale pass from the active scaled 3D sub-viewport to (nativeW, nativeH), and ends the pass.
To composite a native-resolution HUD on top without losing pixel sharpness:
- Mount github.com/nsgo-dev/game/pkg/scene.Overlay3D above the gpu.View, which draws 2D HUD layers in a native-resolution core.Canvas, OR
- Record a follow-up native GPU HUD render pass with gpu.LoadLoad on dst, OR
- Call [UpscaleIntoPass] inside a single native render pass and draw GPU HUD elements directly afterward in the same pass.
func (t *DynamicResolutionTarget) UpscaleIntoPass(pass *gpu.RenderPass, nativeW, nativeH int) errorUpscaleIntoPass records the full-screen upscale draw directly into an active color-only *gpu.RenderPass targeting a native (nativeW, nativeH) surface, setting the viewport and scissor to the full native rectangle. This lets a caller draw native-resolution GPU HUD elements in the same render pass right after the upscaled 3D scene.
func (t *DynamicResolutionTarget) Valid() boolValid reports whether t has not been closed and its core GPU pipelines and buffers are still live on its device.
type DynamicResolutionTargetOptions struct {
// Label prefixes GPU resource labels for capture tools. Defaults to "render3d.dynres".
Label string
// ColorFormat is the offscreen 3D color attachment format.
// Defaults to gpu.FormatRGBA8Unorm when FormatUndefined.
ColorFormat gpu.TextureFormat
// DepthFormat is the offscreen 3D depth attachment format.
// Defaults to gpu.FormatDepth24Plus when FormatUndefined unless DisableDepth is true.
DepthFormat gpu.TextureFormat
// DisableDepth creates a color-only offscreen target with no depth attachment.
DisableDepth bool
// OutputFormat is the color format of the native target passed to Upscale.
// Defaults to dev.SurfaceFormat() (or gpu.FormatRGBA8Unorm when undefined).
OutputFormat gpu.TextureFormat
// TimingLabel optionally sets RenderPassDesc.TimingLabel on Begin3D passes so
// GPU pass timings can be matched in RecordPassTimings.
TimingLabel string
// Config configures the internal scaler when Scaler is nil.
Config DynamicResolutionConfig
// Scaler optionally supplies an external [DynamicResolutionScaler] to share
// or control directly. When nil, a new scaler is constructed from Config.
Scaler *DynamicResolutionScaler
}DynamicResolutionTargetOptions configures NewDynamicResolutionTarget.
type ExtendedMaterialDefaults struct {
// contains filtered or unexported fields
}ExtendedMaterialDefaults owns the extended MaterialGroup bind group layout (19 entries) and the shared 1x1 fallback textures and default linear-repeat sampler used by NewGPUExtendedMaterial, while keeping plain MaterialDefaults unchanged for ordinary GPUMaterial pipelines.
func NewExtendedMaterialDefaults(cx *core.Scope, dev *gpu.Device, opts MaterialDefaultsOptions) (*ExtendedMaterialDefaults, error)NewExtendedMaterialDefaults allocates an ExtendedMaterialDefaults on dev owned by cx, sharing the 1x1 fallback textures (white sRGB, white linear, flat normal, black) and linear-repeat sampler of MaterialDefaults alongside ExtendedMaterialBindGroupLayout.
func (d *ExtendedMaterialDefaults) Base() *MaterialDefaultsBase returns the underlying lean MaterialDefaults for ordinary GPUMaterial and GPUUnlitMaterial instances.
func (d *ExtendedMaterialDefaults) Black() *GPUTextureBlack returns the shared 1x1 sRGB black fallback texture.
func (d *ExtendedMaterialDefaults) ByteSize() uint64ByteSize returns the GPU texture memory held by the fallback textures.
func (d *ExtendedMaterialDefaults) Close() errorClose releases the extended layout and underlying fallback resources. Safe to call on nil or more than once.
func (d *ExtendedMaterialDefaults) FlatNormal() *GPUTextureFlatNormal returns the shared 1x1 linear flat tangent-space normal fallback texture.
func (d *ExtendedMaterialDefaults) Layout() *gpu.BindGroupLayoutLayout returns the extended MaterialGroup bind group layout for NewExtendedMaterialPipeline.
func (d *ExtendedMaterialDefaults) Sampler() *GPUSamplerSampler returns the shared default linear-repeat sampler.
func (d *ExtendedMaterialDefaults) Valid() boolValid reports whether the extended layout and shared fallback textures/sampler are open on a live device.
func (d *ExtendedMaterialDefaults) WhiteLinear() *GPUTextureWhiteLinear returns the shared 1x1 linear white fallback texture.
func (d *ExtendedMaterialDefaults) WhiteSRGB() *GPUTextureWhiteSRGB returns the shared 1x1 sRGB white fallback texture.
type ExtendedMaterialPipelineOptions struct {
// Label names the pipeline in GPU capture tools.
Label string
// ColorFormat sets the color attachment format; [gpu.FormatUndefined] defaults to dev.SurfaceFormat().
ColorFormat gpu.TextureFormat
// DepthFormat enables depth testing (and depth writes for opaque/alpha-mask modes) when non-zero.
DepthFormat gpu.TextureFormat
// AlphaMode selects blending and depth-write state, matching [MaterialPipelineOptions].AlphaMode.
AlphaMode AlphaMode
// DoubleSided disables backface culling ([gpu.CullNone]); when false, back faces are culled ([gpu.CullBack]).
DoubleSided bool
// LightLayout, when set, binds a [GPULightBuffer] at [ExtendedLightGroup] (group 2) so extended materials are shaded by the scene's [LightRig] (ambient + directional + point + spot lights) with full clearcoat and transmission evaluation. When nil, the built-in [DefaultMaterialLight] is used.
LightLayout *gpu.BindGroupLayout
// TransmissionLayout, when set, binds [TransmissionBackground] at [TransmissionBackgroundGroup] (group 3 when LightLayout is set) or [MaterialTransmissionBackgroundGroup] (group 2 when LightLayout is nil) so transmissive surfaces sample the opaque scene color pass.
TransmissionLayout *gpu.BindGroupLayout
// LinearOutput skips tone mapping and sRGB encoding and writes unclamped linear radiance for an [HDRTarget] resolved by [ToneMapPass] (and optional [BloomPass] for HDR emissives).
LinearOutput bool
}ExtendedMaterialPipelineOptions configures NewExtendedMaterialPipeline.
type ExtendedMaterialUniforms struct {
MaterialUniforms
ClearcoatFactor float32
ClearcoatRoughnessFactor float32
ClearcoatNormalScale float32
TransmissionFactor float32
IOR float32
HasClearcoatNormalMap bool
HasClearcoatMap bool
HasTransmissionMap bool
}ExtendedMaterialUniforms holds the 96-byte uniform payload encoded for struct ExtendedMaterialUniforms in ExtendedMaterialBindingsWGSL.
func (u ExtendedMaterialUniforms) AppendUniformData(dst []byte) []byteAppendUniformData appends u's 96-byte little-endian uniform block to dst and returns the extended slice. It allocates only when dst lacks capacity for ExtendedMaterialUniformSize additional bytes.
func (u *ExtendedMaterialUniforms) Encode(dst []byte) []byteEncode writes u into dst[:ExtendedMaterialUniformSize] in the 16-byte-aligned little-endian layout declared by ExtendedMaterialBindingsWGSL. It panics if len(dst) < ExtendedMaterialUniformSize.
type FXAAOptions struct {
// SubpixelQuality controls sub-pixel aliasing removal in [0, 1]. Zero uses the FXAA 3.11 default (0.75) unless DisableSubpixel is true. Negative or non-finite values clamp to 0; values above 1 clamp to 1.
SubpixelQuality float32
// DisableSubpixel forces SubpixelQuality to 0 (edge-only smoothing) even when SubpixelQuality is zero.
DisableSubpixel bool
// EdgeThreshold is the minimum relative local luma contrast required to process a pixel as an edge, in (0, 1]. Non-positive or non-finite values default to 0.166; values above 1 clamp to 1.
EdgeThreshold float32
// EdgeThresholdMin skips very dark regions whose local luma range falls below this absolute floor, in (0, 1]. Non-positive or non-finite values default to 0.0833; values above 1 clamp to 1.
EdgeThresholdMin float32
}FXAAOptions configures FXAA 3.11 edge detection and sub-pixel anti-aliasing. Zero values fall back to DefaultFXAAOptions (SubpixelQuality 0.75, EdgeThreshold 0.166, EdgeThresholdMin 0.0833).
func DefaultFXAAOptions() FXAAOptionsDefaultFXAAOptions returns the standard FXAA 3.11 quality defaults (SubpixelQuality: 0.75, EdgeThreshold: 0.166, EdgeThresholdMin: 0.0833).
func (o FXAAOptions) Sanitize() FXAAOptionsSanitize returns a copy of o with zero, out-of-range, and non-finite fields resolved to valid FXAA 3.11 parameters.
type FXAAPass struct {
// contains filtered or unexported fields
}FXAAPass owns the compiled pipeline, sampler, uniform buffer, and cached bind groups for full-screen FXAA 3.11 post-processing on a gpu.Device (#249).
Create it once in OnReady and call FXAAPass.Draw (inside an open single-sampled render pass) or FXAAPass.Encode (to open and close the render pass automatically) with any single-sampled color texture (such as an offscreen render target or MSAATarget.OutputTexture). The pass keeps one bind group per source texture, so it can filter several sources of different sizes in the same frame, and steady-state draws of sources it has seen do not allocate.
FXAA's thresholds are tuned for gamma-encoded luma and ApplyFXAA works on stored bytes, so give the pass a non-sRGB source holding gamma-encoded (for example tone-mapped LDR) color and a target of the same kind: an sRGB source is sampled as linear values and no longer matches ApplyFXAA, and a gamma-encoded source drawn into an sRGB target is encoded twice.
The options are one uniform block, and buffer writes are applied before the submission's commands, so every draw one pass records into a submission uses the options set at its last draw. To filter several views with different options in one frame, create one FXAAPass per option set.
func NewFXAAPass(cx *core.Scope, dev *gpu.Device, desc FXAAPassDesc) (*FXAAPass, error)NewFXAAPass compiles FXAAWGSL and creates the sampler, uniform buffer, bind group layout, and full-screen pipeline on dev, scoped to cx.
func (p *FXAAPass) Close() errorClose releases the pass's GPU resources immediately instead of waiting for scope disposal. It is safe to call more than once or on a nil pass.
func (p *FXAAPass) Draw(pass *gpu.RenderPass, src *gpu.Texture) errorDraw binds the FXAA pipeline and source texture on pass and issues a bufferless full-screen triangle draw (Draw(3, 0)). The caller owns the render pass, which must target a single-sampled attachment matching FXAAPass.TargetFormat.
func (p *FXAAPass) Encode(enc *gpu.Encoder, src, dst *gpu.Texture) errorEncode opens a single-attachment render pass on enc targeting dst (or the view's swapchain when dst == nil), draws FXAA from src, and ends the pass.
func (p *FXAAPass) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout at group 0 (uniform, texture, sampler).
func (p *FXAAPass) Options() FXAAOptionsOptions returns the current sanitized FXAA 3.11 options.
func (p *FXAAPass) Pipeline() *gpu.PipelinePipeline returns the underlying full-screen FXAA pipeline.
func (p *FXAAPass) Retained() boolRetained reports whether the pass was created with device-loss retention.
func (p *FXAAPass) Sampler() *gpu.SamplerSampler returns the linear clamp-to-edge sampler used by the pass.
func (p *FXAAPass) SetDevice(dev *gpu.Device)SetDevice updates the device pointer after NSGo restores a lost device onto a fresh *gpu.Device for a retained pass.
func (p *FXAAPass) SetOptions(opts FXAAOptions)SetOptions updates the FXAA 3.11 parameters used by subsequent draws.
func (p *FXAAPass) TargetFormat() gpu.TextureFormatTargetFormat returns the color format the pipeline was built for.
func (p *FXAAPass) Valid() boolValid reports whether the pass's GPU resources are open and belong to a live device.
type FXAAPassDesc struct {
// Label names the pass's GPU resources in capture tools.
Label string
// TargetFormat is the color format of the render pass into which [FXAAPass] draws. FormatUndefined defaults to dev.SurfaceFormat() (or FormatRGBA8Unorm), which is an sRGB format on some platforms; see [FXAAPass] for the color space the pass expects.
TargetFormat gpu.TextureFormat
// Options configures FXAA 3.11 edge detection and sub-pixel blending. Zero uses [DefaultFXAAOptions].
Options FXAAOptions
// Retained opts the pass's GPU resources into automatic recreation after a device loss.
Retained bool
}FXAAPassDesc configures NewFXAAPass.
type Fog struct {
Mode FogMode
Color math3d.Vec3
Start float32
End float32
Density float32
MaxOpacity float32
HeightEnabled bool
HeightBase float32
HeightFalloff float32
HeightDensity float32
}Fog configures distance fog, analytical exponential height fog along the view ray, or both combined.
Color is in linear RGB. MaxOpacity caps the combined fog blend factor in (0, 1]; a zero value defaults to 1.0 so struct literals that omit MaxOpacity apply full fog.
When both distance fog and height fog are enabled, their transmittances multiply:
factor = clamp(1 - (1 - f_dist) * (1 - f_height), 0, MaxOpacity)
Height fog models exponential vertical extinction σ(y) = HeightDensity * exp(-HeightFalloff * (y - HeightBase)) analytically integrated along the segment from camPos to worldPos, so it is smooth at grazing angles and symmetric between endpoints.
func (f Fog) Apply(color, camPos, worldPos math3d.Vec3) math3d.Vec3Apply blends linear RGB color toward f.Color using Fog.Factor(camPos, worldPos), matching apply_fog in FogWGSL. camPos follows the rule Fog.Factor states.
func (f Fog) Factor(camPos, worldPos math3d.Vec3) float32Factor evaluates the CPU reference fog blend factor in [0, MaxOpacity] along the view ray from camPos to worldPos, matching fog_factor in FogWGSL. Non-finite coordinates return 0.
camPos is where the ray starts: the eye for a perspective camera, and for an orthographic camera the point on the camera's plane that worldPos projects from, not the camera's position. FogCameraPos computes it from a CameraUniform the way the fogged pipelines do.
func (f Fog) Sanitized() FogSanitized returns a copy of f with non-finite values replaced by safe defaults, negative magnitudes clamped to 0, unrecognized modes mapped to FogOff, MaxOpacity defaulted to 1.0 when <= 0 and clamped to 1.0 when > 1, and linear End raised to at least Start.
func (f Fog) Uniforms() FogUniformsUniforms packs a sanitized copy of f into the GPU uniform layout declared by FogWGSL.
func (f Fog) Validate() errorValidate checks that every field of f is finite and in range: recognized FogMode, non-negative linear RGB color, non-negative Start/End/Density/HeightFalloff/HeightDensity, MaxOpacity in [0, 1] (0 means default 1.0), and End > Start when Mode is FogLinear. Every error wraps ErrInvalidFog.
type FogBufferOptions struct {
// Label names the buffer and bind group in GPU capture tools.
Label string
// Retained keeps a CPU shadow copy so NSGo recreates the buffer, layout, and bind group with their latest data after a device loss.
Retained bool
}FogBufferOptions configures NewGPUFogBuffer.
type FogMode uint8FogMode selects how distance fog attenuates visibility with camera distance.
const (
// FogOff disables distance fog attenuation. Analytical height fog may still apply when [Fog.HeightEnabled] is true.
FogOff FogMode = iota
// FogLinear ramps distance fog linearly from 0 at [Fog.Start] to 1 at [Fog.End].
FogLinear
// FogExp applies exponential distance fog: 1 - exp(-distance * Density).
FogExp
// FogExp2 applies exponential-squared distance fog: 1 - exp(-(distance * Density)^2).
FogExp2
)func (m FogMode) String() stringString returns the mode's lowercase name ("off", "linear", "exp", "exp2") or "unknown" for out-of-range values.
type FogUniforms struct {
// ColorOpacity holds linear RGB fog color in [0..2] and clamped MaxOpacity in [3].
ColorOpacity [4]float32
// DistanceParams holds mode (0=off, 1=linear, 2=exp, 3=exp2) in [0], Start in [1], End in [2], and Density in [3].
DistanceParams [4]float32
// HeightParams holds enabled (0 or 1) in [0], HeightBase in [1], HeightFalloff in [2], and HeightDensity in [3].
HeightParams [4]float32
}FogUniforms is the std140/WGSL-aligned uniform block declared by FogWGSL (three vec4<f32> vectors, FogUniformSize bytes).
func (u FogUniforms) Encode(dst []byte) []byteEncode writes u into dst[:FogUniformSize] as little-endian float32s and returns dst[:FogUniformSize]. It panics if len(dst) < FogUniformSize.
type FrameProfiler struct {
// contains filtered or unexported fields
}FrameProfiler maintains a fixed-capacity ring buffer of recent [FrameSample]s for 3D performance overlays and regression checks (#286).
func NewFrameProfiler(capacity int) *FrameProfilerNewFrameProfiler creates a FrameProfiler retaining up to capacity recent frames (defaulting to 120 when capacity <= 0).
func (p *FrameProfiler) AverageFrameTime() time.DurationAverageFrameTime returns the arithmetic mean frame duration in the window.
func (p *FrameProfiler) Count() intCount returns the number of recorded frames currently in the window.
func (p *FrameProfiler) FPS() float64FPS returns the average frames per second across the window, or 0 if empty.
func (p *FrameProfiler) P95FrameTime() time.DurationP95FrameTime returns the 95th-percentile frame duration in the window.
func (p *FrameProfiler) PeakDrawCalls() intPeakDrawCalls returns the highest draw call count recorded in the window.
func (p *FrameProfiler) PeakTriangles() uint64PeakTriangles returns the highest triangle count recorded in the window.
func (p *FrameProfiler) Record(frameTime time.Duration, stats RenderStats)Record stores one frame's duration and RenderStats without allocating.
func (p *FrameProfiler) Reset()Reset clears all recorded samples while retaining buffer capacity.
type FrameSample struct {
FrameTime time.Duration
DrawCalls int
Triangles uint64
}FrameSample records timing and render telemetry for a single frame (#286).
type GLTFMaterialInfo struct {
Name string
Material Material
GPU *GPUMaterial
ExtendedGPU *GPUExtendedMaterial
Unlit bool
BaseColor GLTFTextureSlot
MetallicRoughness GLTFTextureSlot
Normal GLTFTextureSlot
Occlusion GLTFTextureSlot
Emissive GLTFTextureSlot
Clearcoat GLTFTextureSlot
ClearcoatRoughness GLTFTextureSlot
ClearcoatNormal GLTFTextureSlot
Transmission GLTFTextureSlot
}GLTFMaterialInfo holds the mapped CPU Material, uploaded GPUMaterial (from UploadGLTFMaterials) or GPUExtendedMaterial (from UploadGLTFExtendedMaterials), and glTF-specific metadata (material name, KHR_materials_unlit flag, and per-slot UV/transform info) for one entry in GLTFMaterialSet.
func (i GLTFMaterialInfo) Unsupported() []stringUnsupported lists what MaterialWGSL does not draw as the glTF material specifies: "KHR_materials_unlit" when the material is unlit (the shader always applies metallic-roughness lighting), and "<slot> UVs" for each texture slot whose GLTFTextureSlot.NeedsUVBake is true. It returns nil when the shader draws the material as written.
type GLTFMaterialSet struct {
// contains filtered or unexported fields
}GLTFMaterialSet owns every GPUTexture, GPUSampler, and GPUMaterial (or GPUExtendedMaterial) uploaded from a *gltf.Document by UploadGLTFMaterials or UploadGLTFExtendedMaterials.
Referenced glTF images are decoded once per image index and uploaded once per unique (imageIndex, sRGB) key: color slots (baseColorTexture, emissiveTexture) upload as sRGB (gpu.FormatRGBA8UnormSRGB) while data slots (metallicRoughnessTexture, normalTexture, occlusionTexture, clearcoatTexture, clearcoatRoughnessTexture, clearcoatNormalTexture, transmissionTexture) upload as linear (gpu.FormatRGBA8Unorm). Packed textures shared across linear slots (such as occlusion + metallic-roughness) or across multiple materials are uploaded only once. Samplers are deduplicated by glTF sampler index, and every texture without a sampler shares one sampler built from the glTF 2.0 default (repeat wrapping, automatic filtering).
func UploadGLTFExtendedMaterials(cx *core.Scope, dev *gpu.Device, defaults *ExtendedMaterialDefaults, doc *gltf.Document, opts GLTFMaterialUpload) (*GLTFMaterialSet, error)UploadGLTFExtendedMaterials decodes and uploads all textures, samplers, and extended PBR materials (base metallic-roughness plus KHR_materials_emissive_strength, KHR_materials_clearcoat, KHR_materials_transmission, and KHR_materials_ior) referenced by doc onto dev, owned by cx.
Extension maps (clearcoatTexture, clearcoatRoughnessTexture, clearcoatNormalTexture, transmissionTexture) are uploaded as linear (gpu.FormatRGBA8Unorm) and deduplicated with the base linear slots by (imageIndex, sRGB). Access the uploaded materials via GLTFMaterialSet.ExtendedMaterial, GLTFMaterialSet.ExtendedMaterialForPrimitive, GLTFMaterialSet.ExtendedMaterialForVariant, and GLTFMaterialSet.DefaultExtendedMaterial.
func UploadGLTFMaterials(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, doc *gltf.Document, opts GLTFMaterialUpload) (*GLTFMaterialSet, error)UploadGLTFMaterials decodes and uploads all textures, samplers, and PBR metallic-roughness materials referenced by doc onto dev, owned by cx.
Omitted texture slots, and textures without an image source, fall back to defaults. A glTF 2.0 default material is always created and returned by GLTFMaterialSet.DefaultMaterial (and by GLTFMaterialSet.Material(-1)) for primitives with Material == -1.
If any material, sampler, or image fails validation, decoding, or GPU upload, every GPU resource allocated during the call is closed before returning the error.
func (s *GLTFMaterialSet) ByteSize() uint64ByteSize returns the total GPU memory held by all uploaded textures and material uniform buffers in s (excluding shared MaterialDefaults / ExtendedMaterialDefaults).
func (s *GLTFMaterialSet) Close() errorClose releases every GPUMaterial, GPUExtendedMaterial, GPUSampler, and GPUTexture owned by s immediately instead of waiting for scope disposal. Safe to call on nil or more than once.
func (s *GLTFMaterialSet) DefaultExtendedMaterial() *GPUExtendedMaterialDefaultExtendedMaterial returns the uploaded glTF 2.0 default GPUExtendedMaterial created by UploadGLTFExtendedMaterials for primitives with Material == -1, or nil for a nil receiver or a plain UploadGLTFMaterials set.
func (s *GLTFMaterialSet) DefaultMaterial() *GPUMaterialDefaultMaterial returns the uploaded glTF 2.0 default GPUMaterial used when a primitive has Material == -1, or nil for a nil receiver or a set created by UploadGLTFExtendedMaterials.
func (s *GLTFMaterialSet) ExtendedMaterial(index int) *GPUExtendedMaterialExtendedMaterial returns the uploaded *GPUExtendedMaterial for glTF material index, or GLTFMaterialSet.DefaultExtendedMaterial when index == -1. Out-of-range indices, nil receivers, and plain UploadGLTFMaterials sets return nil.
func (s *GLTFMaterialSet) ExtendedMaterialForPrimitive(prim gltf.Primitive, variantIndex int) *GPUExtendedMaterialExtendedMaterialForPrimitive resolves the active extended material for prim under the KHR_materials_variants variantIndex (falling back to prim.Material and then GLTFMaterialSet.DefaultExtendedMaterial when -1).
func (s *GLTFMaterialSet) ExtendedMaterialForVariant(prim gltf.Primitive, variantName string) *GPUExtendedMaterialExtendedMaterialForVariant resolves the active extended material for prim under the named KHR_materials_variants variant (falling back to prim.Material and then GLTFMaterialSet.DefaultExtendedMaterial when -1).
func (s *GLTFMaterialSet) Info(index int) (GLTFMaterialInfo, bool)Info returns the full GLTFMaterialInfo for glTF material index.
func (s *GLTFMaterialSet) InfoForPrimitive(prim gltf.Primitive, variantIndex int) (GLTFMaterialInfo, bool)InfoForPrimitive returns the GLTFMaterialInfo for prim under variantIndex, returning false when the resolved material index is -1 (default material) or out of range.
func (s *GLTFMaterialSet) InfoForVariant(prim gltf.Primitive, variantName string) (GLTFMaterialInfo, bool)InfoForVariant returns the GLTFMaterialInfo for prim under variantName, returning false when the resolved material index is -1 (default material) or out of range.
func (s *GLTFMaterialSet) Len() intLen returns the number of glTF materials uploaded from the document (excluding the built-in glTF default material returned by GLTFMaterialSet.DefaultMaterial).
func (s *GLTFMaterialSet) Material(index int) *GPUMaterialMaterial returns the uploaded *GPUMaterial for glTF material index, or GLTFMaterialSet.DefaultMaterial when index == -1 (the glTF sentinel for an unassigned material). Out-of-range indices and nil receivers return nil.
func (s *GLTFMaterialSet) MaterialForPrimitive(prim gltf.Primitive, variantIndex int) *GPUMaterialMaterialForPrimitive resolves the active material for prim under the KHR_materials_variants variantIndex (falling back to prim.Material and then GLTFMaterialSet.DefaultMaterial when -1).
func (s *GLTFMaterialSet) MaterialForVariant(prim gltf.Primitive, variantName string) *GPUMaterialMaterialForVariant resolves the active material for prim under the named KHR_materials_variants variant (falling back to prim.Material and then GLTFMaterialSet.DefaultMaterial when -1).
func (s *GLTFMaterialSet) Sampler(samplerIndex int) *GPUSamplerSampler returns the deduplicated *GPUSampler created for glTF samplerIndex, or nil if that sampler was not referenced by any uploaded material.
func (s *GLTFMaterialSet) SamplerCount() intSamplerCount returns the number of unique GPU samplers created for the document, counting the shared glTF default sampler when a texture without a sampler is referenced.
func (s *GLTFMaterialSet) Texture(imageIndex int, srgb bool) *GPUTextureTexture returns the deduplicated *GPUTexture uploaded for glTF imageIndex in the requested sRGB/linear color space, or nil if that pair was not uploaded.
func (s *GLTFMaterialSet) TextureCount() intTextureCount returns the number of unique GPU textures uploaded for the document.
func (s *GLTFMaterialSet) Valid() boolValid reports whether every material, texture, and sampler owned by s is currently open on a live GPU device.
type GLTFMaterialUpload struct {
// Label prefixes debug labels on uploaded textures, samplers, and GPU materials.
Label string
// Mipmaps forces CPU mipmap generation on every uploaded glTF texture when true (unless DisableMipmaps is also set). When false, mipmaps are generated for any texture sampled with a mipmapped or unspecified glTF minFilter.
Mipmaps bool
// DisableMipmaps disables mipmap generation even when glTF samplers request mipmaps.
DisableMipmaps bool
// MaxMipLevels caps generated mipmap chains when mipmaps are enabled; 0 builds the full chain.
MaxMipLevels uint32
// MaxAnisotropy sets anisotropic filtering on all-linear glTF samplers, including the glTF default sampler used by textures that name none (0 or 1 disables it). Samplers that use nearest min, mag, or mipmap filtering keep MaxAnisotropy = 1 to satisfy WebGPU validation rules.
MaxAnisotropy uint16
// Retained keeps CPU shadow copies of every uploaded texture, sampler, and material uniform buffer so the returned [GLTFMaterialSet] recovers automatically after a GPU device loss. Pair with [MaterialDefaultsOptions.Retained] on defaults.
Retained bool
}GLTFMaterialUpload configures UploadGLTFMaterials.
type GLTFPBRLightmapInfo struct {
HasLightmap bool
Ref *gltf.LightmapRef
Encoding LightmapEncoding
TextureIndex int
ImageIndex int
SamplerIndex int
Texture *GPUTexture
Sampler *GPUSampler
Config PBRLightmap
GPU *GPUPBRLightmap
}GLTFPBRLightmapInfo holds the extracted glTF gltf.LightmapRef, decoded LightmapEncoding, uploaded GPU texture/sampler, and bound GPUPBRLightmap for one material entry in GLTFPBRLightmapSet.
type GLTFPBRLightmapSet struct {
// contains filtered or unexported fields
}GLTFPBRLightmapSet owns every lightmap GPUTexture, GPUSampler, and GPUPBRLightmap uploaded from a *gltf.Document by UploadGLTFPBRLightmaps. Pair it with GLTFMaterialSet from UploadGLTFMaterials to draw glTF assets with both their metallic-roughness maps and their baked lightmaps in one NewPBRLightmapPipeline.
func UploadGLTFPBRLightmaps(cx *core.Scope, dev *gpu.Device, doc *gltf.Document, opts GLTFPBRLightmapUpload) (*GLTFPBRLightmapSet, error)UploadGLTFPBRLightmaps inspects every material in doc via gltf.Document.MaterialLightmap (MOZ_lightmap, EXT_lightmap, extras.lightmap), deduplicates and uploads referenced lightmap images and samplers onto dev, and builds one GPUPBRLightmap per material (plus a default unlightmapped binding for primitives with Material == -1) sharing a single PBRLightmapGroup layout.
If any material, lightmap extension, sampler, or image fails validation, decoding, or GPU upload, every GPU resource allocated during the call is closed before returning the error.
func (s *GLTFPBRLightmapSet) ByteSize() uint64ByteSize returns the total GPU memory held by all uploaded lightmap textures, fallback texture, and uniform buffers in s.
func (s *GLTFPBRLightmapSet) Close() errorClose releases every GPU resource owned by s immediately instead of waiting for scope disposal. Safe to call on nil or more than once.
func (s *GLTFPBRLightmapSet) DefaultLightmap() *GPUPBRLightmapDefaultLightmap returns the fallback unlightmapped *GPUPBRLightmap used for primitives with Material == -1.
func (s *GLTFPBRLightmapSet) Info(index int) (GLTFPBRLightmapInfo, bool)Info returns the full GLTFPBRLightmapInfo for glTF material index.
func (s *GLTFPBRLightmapSet) Layout() *gpu.BindGroupLayoutLayout returns the shared PBRLightmapGroup bind group layout to pass to NewPBRLightmapPipeline.
func (s *GLTFPBRLightmapSet) Len() intLen returns the number of document materials tracked by s (excluding GLTFPBRLightmapSet.DefaultLightmap).
func (s *GLTFPBRLightmapSet) Lightmap(index int) *GPUPBRLightmapLightmap returns the *GPUPBRLightmap for glTF material index, or GLTFPBRLightmapSet.DefaultLightmap when index == -1. Out-of-range indices and nil receivers return nil.
func (s *GLTFPBRLightmapSet) LightmapForPrimitive(prim gltf.Primitive, variantIndex int) *GPUPBRLightmapLightmapForPrimitive resolves the active *GPUPBRLightmap for prim under the KHR_materials_variants variantIndex.
func (s *GLTFPBRLightmapSet) LightmapForVariant(prim gltf.Primitive, variantName string) *GPUPBRLightmapLightmapForVariant resolves the active *GPUPBRLightmap for prim under the named KHR_materials_variants variant.
func (s *GLTFPBRLightmapSet) NewInstance(cx *core.Scope, dev *gpu.Device, materialIndex int, model math3d.Mat4, opts PBRLightmapOptions) (*GPUPBRLightmap, error)NewInstance creates an independent *GPUPBRLightmap for materialIndex with its own Model matrix while reusing s's shared bind group layout, lightmap texture, and sampler. Useful when multiple scene nodes share one glTF material at different world transforms.
func (s *GLTFPBRLightmapSet) SamplerCount() intSamplerCount returns the number of deduplicated glTF lightmap samplers uploaded from the document (excluding the internal clamp default sampler).
func (s *GLTFPBRLightmapSet) TextureCount() intTextureCount returns the number of unique baked lightmap textures uploaded from the document (excluding the internal 1x1 fallback).
func (s *GLTFPBRLightmapSet) Valid() boolValid reports whether every layout, texture, sampler, and lightmap binding owned by s is open on a live device.
type GLTFPBRLightmapUpload struct {
// Label prefixes debug labels on uploaded lightmap textures, samplers, buffers, and bind groups.
Label string
// SharedLayout reuses an existing [PBRLightmapGroup] bind group layout instead of creating one.
// DefaultEncoding selects the [LightmapEncoding] used when a glTF material's lightmap metadata omits an explicit encoding string (defaults to [LightmapLinear]).
DefaultEncoding LightmapEncoding
// DisableMipmaps disables mipmap generation on linear and sRGB lightmaps even when glTF samplers request mipmaps. Packed HDR formats ([LightmapRGBM], [LightmapRGBD]) never generate CPU box mipmaps because linear averaging corrupts shared-exponent channels.
DisableMipmaps bool
// MaxMipLevels caps generated mipmap chains when mipmaps are enabled; 0 builds the full chain.
MaxMipLevels uint32
// Retained keeps CPU shadow copies of every uploaded lightmap texture, sampler, and uniform buffer so the returned [GLTFPBRLightmapSet] recovers automatically after a GPU device loss.
Retained bool
}GLTFPBRLightmapUpload configures UploadGLTFPBRLightmaps.
type GLTFTextureSlot struct {
Present bool
TextureIndex int
ImageIndex int
SamplerIndex int
TexCoord int
Transform *gltf.TextureTransform
SRGB bool
Texture *GPUTexture
Sampler *GPUSampler
}GLTFTextureSlot records the mapped GPU handles and glTF UV metadata for one texture slot on an uploaded glTF material.
func (s GLTFTextureSlot) EffectiveTexCoord() intEffectiveTexCoord returns Transform.TexCoord when KHR_texture_transform overrides the UV channel, otherwise TexCoord.
func (s GLTFTextureSlot) NeedsUVBake() boolNeedsUVBake reports whether MaterialWGSL samples this slot differently from the asset. The shader reads every texture with the mesh's first UV set (TEXCOORD_0) and no transform, so a present slot whose GLTFTextureSlot.EffectiveTexCoord is not 0 or whose KHR_texture_transform is not the identity draws with the wrong UVs unless the mesh's UVs are baked for it (for example with gltf.Document.TransformTexCoords) or a custom shader applies them.
type GPUColoredMesh struct {
// contains filtered or unexported fields
}GPUColoredMesh is a ColoredMesh uploaded to a GPU device's vertex and optional index buffers using ColoredVertexLayout. Its buffers belong to the scope passed to UploadColoredMesh and are released when that scope is disposed or when GPUColoredMesh.Close is called.
func UploadColoredMesh(cx *core.Scope, dev *gpu.Device, m ColoredMesh, opts MeshUpload) (*GPUColoredMesh, error)UploadColoredMesh validates m and creates its vertex buffer and, when m is indexed, its index buffer on dev, scoped to cx. A malformed mesh returns an error wrapping ErrInvalidMesh before anything is created; a nil or lost device returns gpu.ErrDeviceLost.
func (g *GPUColoredMesh) Bind(pass *gpu.RenderPass)Bind binds the vertex buffer to slot 0 and, when indexed, the index buffer to pass. It records nothing when the mesh is not GPUColoredMesh.Valid.
func (g *GPUColoredMesh) Bounds() math3d.AABBBounds returns the object-space box around the mesh's positions, computed at upload.
func (g *GPUColoredMesh) ByteSize() uint64ByteSize returns the GPU memory held by the mesh's buffers for RenderStats and Budget accounting. It is zero for a nil mesh.
func (g *GPUColoredMesh) Close() errorClose releases the mesh's buffers now rather than when their scope is disposed. It is safe to call on a nil receiver or more than once.
func (g *GPUColoredMesh) Draw(pass *gpu.RenderPass)Draw binds the mesh to pass and draws all of its triangles once. It records nothing when the mesh is not GPUColoredMesh.Valid.
func (g *GPUColoredMesh) HasVertexColors() boolHasVertexColors reports whether the uploaded ColoredMesh provided explicit vertex colors (as opposed to default white).
func (g *GPUColoredMesh) IndexBuffer() *gpu.BufferIndexBuffer returns the index buffer, or nil for a nil or non-indexed mesh.
func (g *GPUColoredMesh) IndexCount() uint32IndexCount returns the number of indices, or zero for a non-indexed mesh.
func (g *GPUColoredMesh) IndexFormat() gpu.IndexFormatIndexFormat returns the width of the index buffer's entries.
func (g *GPUColoredMesh) Indexed() boolIndexed reports whether the mesh draws through an index buffer.
func (g *GPUColoredMesh) Triangles() uint32Triangles returns the number of triangles one draw of the mesh rasterizes.
func (g *GPUColoredMesh) Valid() boolValid reports whether the mesh's buffers are open and belong to a live device.
func (g *GPUColoredMesh) VertexBuffer() *gpu.BufferVertexBuffer returns the interleaved vertex buffer laid out as ColoredVertexLayout describes, or nil for a nil receiver.
func (g *GPUColoredMesh) VertexCount() uint32VertexCount returns the number of vertices in the vertex buffer.
type GPUCubemap struct {
// contains filtered or unexported fields
}GPUCubemap is a 6-face cubemap texture and its trilinear clamp-to-edge sampler uploaded to an NSGo gpu.Device. Its resources belong to the core.Scope passed to UploadCubemap and are released when that scope is disposed or when GPUCubemap.Close is called.
func UploadCubemap(cx *core.Scope, dev *gpu.Device, cm *Cubemap, opts CubemapUpload) (*GPUCubemap, error)UploadCubemap validates cm and uploads all six faces and their mip chain to dev, scoped to cx. A malformed cubemap returns an error wrapping ErrInvalidCubemap before creating any GPU resources.
func UploadCubemapHDR(cx *core.Scope, dev *gpu.Device, cm *HDRCubemap, opts CubemapUpload) (*GPUCubemap, error)UploadCubemapHDR validates cm and uploads all six faces and their mip chain to dev as a linear floating-point GPUCubemap, scoped to cx.
When opts.Format is gpu.FormatUndefined, gpu.FormatRGBA16Float is used whenever dev supports it (preserving HDR radiance up to 65504.0 per channel), falling back to gpu.FormatRGBA8Unorm only on devices that lack half-float texture support. Explicit opts.Format may select gpu.FormatRGBA16Float, gpu.FormatRGBA32Float (when supported by dev), or gpu.FormatRGBA8Unorm. When opts.GenerateMips is true and cm has no precomputed Mips, a linear-light 2x2 box-filtered mip chain is built on the CPU before uploading.
func (g *GPUCubemap) ByteSize() uint64ByteSize returns the GPU memory occupied by all six faces and all mip levels.
func (g *GPUCubemap) Close() errorClose releases the sampler and texture immediately. Safe to call more than once.
func (g *GPUCubemap) Format() gpu.TextureFormatFormat returns the GPU texture format.
func (g *GPUCubemap) MaxLOD() float32MaxLOD returns float32(MipLevels - 1), the maximum valid LOD index for textureSampleLevel.
func (g *GPUCubemap) MipLevels() uint32MipLevels returns the number of uploaded mip levels.
func (g *GPUCubemap) Sampler() *gpu.SamplerSampler returns the trilinear clamp-to-edge sampler created for the cubemap.
func (g *GPUCubemap) Size() uint32Size returns the base mip edge length in texels.
func (g *GPUCubemap) Texture() *gpu.TextureTexture returns the underlying gpu.DimCube texture.
func (g *GPUCubemap) Valid() boolValid reports whether both the texture and sampler are open and belong to a live device.
type GPUDirectionalLight struct {
// ToLight holds the unit vector pointing from the surface toward the light (-normalize(Direction)) in xyz.
ToLight math3d.Vec4
// Color holds premultiplied linear radiance (Color * Intensity) in rgb and Intensity in w.
Color math3d.Vec4
}GPUDirectionalLight is the 32-byte GPU uniform representation of one DirectionalLight.
type GPUExtendedMaterial struct {
// contains filtered or unexported fields
}GPUExtendedMaterial is a scope-owned extended PBR material bound at MaterialGroup (group 1) supporting base metallic-roughness maps plus KHR_materials_emissive_strength (folded into EmissiveFactor), KHR_materials_clearcoat (factor, roughness, normal map), and KHR_materials_transmission (factor, map, IOR).
Like GPUMaterial, GPUExtendedMaterial does not cache a *gpu.Device pointer so retained materials remain updatable via GPUExtendedMaterial.Update after a device loss and restore. The opaque scene background texture for transmission is NOT baked into GPUExtendedMaterial; bind TransmissionBackground once per frame/pass instead.
func NewGPUExtendedMaterial(cx *core.Scope, dev *gpu.Device, defaults *ExtendedMaterialDefaults, m Material, opts MaterialUpload) (*GPUExtendedMaterial, error)NewGPUExtendedMaterial validates m and creates its 96-byte uniform buffer and extended MaterialGroup bind group on dev, owned by cx. Omitted textures and samplers fall back to defaults.
func (g *GPUExtendedMaterial) AlphaMode() AlphaModeAlphaMode returns g's current AlphaMode.
func (g *GPUExtendedMaterial) Bind(pass *gpu.RenderPass)Bind sets g's bind group at MaterialGroup (group 1) on pass.
func (g *GPUExtendedMaterial) BindGroup() *gpu.BindGroupBindGroup returns the underlying gpu.BindGroup, or nil for a nil receiver.
func (g *GPUExtendedMaterial) ByteSize() uint64ByteSize returns the GPU buffer memory owned by g's uniform buffer.
func (g *GPUExtendedMaterial) Close() errorClose releases g's bind group and uniform buffer. Safe to call on nil or more than once.
func (g *GPUExtendedMaterial) DoubleSided() boolDoubleSided reports whether g renders both front and back faces.
func (g *GPUExtendedMaterial) HasClearcoat() boolHasClearcoat reports whether g has a non-zero clearcoat factor.
func (g *GPUExtendedMaterial) HasTransmission() boolHasTransmission reports whether g has a non-zero transmission factor.
func (g *GPUExtendedMaterial) Material() MaterialMaterial returns the latest Material parameters uploaded to g.
func (g *GPUExtendedMaterial) UniformBuffer() *gpu.BufferUniformBuffer returns the underlying uniform *gpu.Buffer, or nil for a nil receiver.
func (g *GPUExtendedMaterial) Update(dev *gpu.Device, m Material) errorUpdate validates m and writes its updated 96-byte uniform parameters into g's uniform buffer in place without rebuilding the bind group.
func (g *GPUExtendedMaterial) Valid() boolValid reports whether g's uniform buffer and bind group are open on a live device.
type GPUFogBuffer struct {
// contains filtered or unexported fields
}GPUFogBuffer holds a Fog uniform buffer, its bind group layout, and its bind group on an NSGo gpu.Device, scoped to the core.Scope passed to NewGPUFogBuffer.
Bind it at FogGroup for NewLitPBRFogPipeline and FogBindingWGSL (GPUFogBuffer.Bind), at MaterialFogGroup for a fogged NewMaterialPipeline, or at any group a custom shader that embeds FogWGSL chooses.
func NewGPUFogBuffer(cx *core.Scope, dev *gpu.Device, fog Fog, opts FogBufferOptions) (*GPUFogBuffer, error)NewGPUFogBuffer validates fog and creates its uniform buffer, bind group layout, and bind group on dev, owned by cx (nil for resources closed manually). An invalid fog returns an error wrapping ErrInvalidFog before creating any GPU resource.
func (b *GPUFogBuffer) Bind(pass *gpu.RenderPass)Bind sets b's bind group at FogGroup on pass. It records nothing when b is not GPUFogBuffer.Valid.
func (b *GPUFogBuffer) BindGroup() *gpu.BindGroupBindGroup returns the bind group to pass to gpu.RenderPass.SetBindGroup.
func (b *GPUFogBuffer) Buffer() *gpu.BufferBuffer returns the underlying uniform buffer, or nil when b is nil.
func (b *GPUFogBuffer) ByteSize() uint64ByteSize returns the GPU memory held by the fog uniform buffer (for RenderStats and Budget accounting), or zero for a nil buffer.
func (b *GPUFogBuffer) Close() errorClose releases the bind group, layout, and buffer now instead of waiting for their owning scope. It is safe to call on nil or more than once.
func (b *GPUFogBuffer) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout for pipelines that bind b.
func (b *GPUFogBuffer) Update(dev *gpu.Device, fog Fog) errorUpdate validates fog and writes its packed uniforms to the GPU buffer without allocating into scratch storage. Pass the active gpu.Device (for example frame.Device()) so a retained buffer continues accepting updates after a device loss and restore; passing nil reuses the last device.
func (b *GPUFogBuffer) Valid() boolValid reports whether the buffer, layout, and bind group are open on a live device.
type GPUIBLBuffer struct {
// contains filtered or unexported fields
}GPUIBLBuffer holds the uniform buffer, bind group layout, and bind group that expose diffuse L2 spherical harmonic irradiance and a prefiltered specular cubemap to shaders that prepend IBLWGSL (or IBLWGSLForGroup).
Create it once when the device is ready, call GPUIBLBuffer.Update when the environment or intensity changes, and bind it at IBLGroup for NewLitPBRIBLPipeline (GPUIBLBuffer.Bind) or at the group a custom shader chose with IBLWGSLForGroup. Its resources belong to the scope passed to NewGPUIBLBuffer and are released with it, or earlier by Close.
func NewGPUIBLBuffer(cx *core.Scope, dev *gpu.Device, prefilter *GPUCubemap, initial IBLUniform, opts IBLBufferOptions) (*GPUIBLBuffer, error)NewGPUIBLBuffer validates initial and creates the IBL uniform buffer, bind group layout, and bind group on dev, owned by cx (nil for resources closed manually), binding the uniform at binding 0, prefilter's cubemap at binding 1, and its sampler at binding 2. An invalid uniform returns an error wrapping ErrInvalidIBL, and a nil or closed prefilter one wrapping ErrInvalidCubemap, before any GPU resource is created.
func (b *GPUIBLBuffer) Bind(pass *gpu.RenderPass)Bind sets b's bind group at IBLGroup on pass. It records nothing when b is not GPUIBLBuffer.Valid.
func (b *GPUIBLBuffer) BindGroup() *gpu.BindGroupBindGroup returns the bind group a render pass sets at IBLGroup (or the group chosen with IBLWGSLForGroup).
func (b *GPUIBLBuffer) Buffer() *gpu.BufferBuffer returns the underlying uniform buffer, or nil when b is nil.
func (b *GPUIBLBuffer) ByteSize() uint64ByteSize returns the GPU memory held by the IBL uniform buffer (for RenderStats and Budget accounting), or zero for a nil buffer. The prefiltered cubemap is counted by its own GPUCubemap.ByteSize.
func (b *GPUIBLBuffer) Close() errorClose releases the bind group, layout, and uniform buffer now instead of waiting for their owning scope. It is safe to call on nil or more than once.
func (b *GPUIBLBuffer) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout a pipeline lists at IBLGroup (or the group chosen with IBLWGSLForGroup).
func (b *GPUIBLBuffer) Update(dev *gpu.Device, u IBLUniform) errorUpdate validates u and writes it to the uniform buffer; the only copy made is the one gpu.Device.WriteBuffer takes of the bytes it queues. Pass the active gpu.Device (for example frame.Device()) so a retained buffer keeps accepting updates after a device loss and restore; passing nil reuses the last device.
func (b *GPUIBLBuffer) Valid() boolValid reports whether the uniform buffer, layout, and bind group are open and belong to a live device.
type GPULightBuffer struct {
// contains filtered or unexported fields
}GPULightBuffer holds a scene's LightRig uniform buffer on a GPU device together with the bind group layout and bind group that expose it to shaders at LightGroup.
Create it once when the device is ready, call GPULightBuffer.Update whenever the scene lights change, and bind GPULightBuffer.BindGroup at LightGroup (or call GPULightBuffer.Bind). Pipelines list GPULightBuffer.Layout at LightGroup in their PipelineDesc.Layouts. Its resources belong to the scope passed to NewLightBuffer and are released with it, or earlier by Close.
func NewLightBuffer(cx *core.Scope, dev *gpu.Device, initial LightRig, opts LightBufferOptions) (*GPULightBuffer, error)NewLightBuffer validates initial and creates a light uniform buffer, bind group layout, and bind group on dev, scoped to cx (nil for resources closed manually). A malformed rig returns an error wrapping ErrInvalidLight before any GPU resource is created.
func (b *GPULightBuffer) Bind(pass *gpu.RenderPass)Bind sets the light bind group at LightGroup on pass when b is valid.
func (b *GPULightBuffer) BindGroup() *gpu.BindGroupBindGroup returns the bind group a render pass sets at LightGroup.
func (b *GPULightBuffer) Buffer() *gpu.BufferBuffer returns the underlying uniform buffer.
func (b *GPULightBuffer) ByteSize() uint64ByteSize returns the GPU memory held by the light uniform buffer, or zero for a nil buffer.
func (b *GPULightBuffer) Close() errorClose releases the bind group, layout, and uniform buffer now rather than with the owning scope. It is nil-safe and safe to call more than once.
func (b *GPULightBuffer) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout a pipeline lists at LightGroup.
func (b *GPULightBuffer) Update(dev *gpu.Device, rig LightRig) errorUpdate validates rig and uploads it into the uniform buffer without allocating into Go heap memory beyond the copy gpu.Device.WriteBuffer queues. Pass the current *gpu.Device (such as frame.Device()) so updates continue working after a retained device-loss recovery, or pass nil to reuse the device from creation or the previous Update.
func (b *GPULightBuffer) Valid() boolValid reports whether the buffer, bind group layout, and bind group are all open and live.
type GPULightmapMesh struct {
// contains filtered or unexported fields
}GPULightmapMesh is a LightmapMesh uploaded to GPU vertex and optional index buffers using LightmapVertexLayout.
func UploadLightmapMesh(cx *core.Scope, dev *gpu.Device, m LightmapMesh, opts MeshUpload) (*GPULightmapMesh, error)UploadLightmapMesh validates m and uploads its 40-byte interleaved vertex buffer (position, normal, UV0, UV1) and optional index buffer onto dev, scoped to cx. When m.UV1 is empty, UV0 is copied into the UV1 attribute slot and GPULightmapMesh.UsedUV0Fallback reports true.
func UploadLightmapVertices(cx *core.Scope, dev *gpu.Device, vertices []LightmapVertex, indices []uint32, opts MeshUpload) (*GPULightmapMesh, error)UploadLightmapVertices uploads interleaved LightmapVertex data and optional triangle indices as a GPULightmapMesh.
func (g *GPULightmapMesh) Bind(pass *gpu.RenderPass)Bind binds g's vertex buffer to slot 0 and optional index buffer to pass.
func (g *GPULightmapMesh) Bounds() math3d.AABBBounds returns the object-space bounding box of g.
func (g *GPULightmapMesh) ByteSize() uint64ByteSize returns the GPU buffer bytes held by g.
func (g *GPULightmapMesh) Close() errorClose releases g's GPU buffers. It is safe to call more than once.
func (g *GPULightmapMesh) Draw(pass *gpu.RenderPass)Draw binds g to pass and draws all of its triangles once.
func (g *GPULightmapMesh) IndexBuffer() *gpu.BufferIndexBuffer returns the index buffer, or nil for a non-indexed mesh.
func (g *GPULightmapMesh) IndexCount() uint32IndexCount returns the number of uploaded indices, or zero when non-indexed.
func (g *GPULightmapMesh) IndexFormat() gpu.IndexFormatIndexFormat returns the index element width.
func (g *GPULightmapMesh) Indexed() boolIndexed reports whether g draws through an index buffer.
func (g *GPULightmapMesh) Triangles() uint32Triangles returns the triangle count rasterized by one draw of g.
func (g *GPULightmapMesh) UsedUV0Fallback() boolUsedUV0Fallback reports whether g was uploaded without dedicated UV1 coordinates and therefore reused UV0 in the lightmap UV slot.
func (g *GPULightmapMesh) Valid() boolValid reports whether g's buffers are open and belong to a live device.
func (g *GPULightmapMesh) VertexBuffer() *gpu.BufferVertexBuffer returns the interleaved 40-byte vertex buffer.
func (g *GPULightmapMesh) VertexCount() uint32VertexCount returns the number of uploaded vertices.
type GPUMaterial struct {
// contains filtered or unexported fields
}GPUMaterial is a scope-owned metallic-roughness material bound to MaterialGroup: one uniform buffer storing MaterialUniforms plus one gpu.BindGroup wiring the uniform buffer and all five texture/sampler slots (using MaterialDefaults for omitted maps).
Like GPUTexture, GPUMaterial does not cache a *gpu.Device pointer so retained materials remain updatable through GPUMaterial.Update after a device loss and restore.
func NewGPUMaterial(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, m Material, opts MaterialUpload) (*GPUMaterial, error)NewGPUMaterial validates m and creates its uniform buffer and MaterialGroup bind group on dev, owned by cx. Omitted textures and samplers fall back to defaults. Invalid parameters or handles return an error wrapping ErrInvalidMaterial before any GPU object is created.
func (g *GPUMaterial) AlphaMode() AlphaModeAlphaMode returns g's current AlphaMode.
func (g *GPUMaterial) Bind(pass *gpu.RenderPass)Bind sets g's bind group at MaterialGroup (group 1) on pass. It records nothing when g is not GPUMaterial.Valid, matching GPUMesh.Bind.
func (g *GPUMaterial) BindGroup() *gpu.BindGroupBindGroup returns the underlying gpu.BindGroup, or nil for a nil receiver.
func (g *GPUMaterial) ByteSize() uint64ByteSize returns the GPU buffer memory owned by g's uniform buffer (for RenderStats and Budget accounting). Bound textures are accounted for separately through GPUTexture.ByteSize.
func (g *GPUMaterial) Close() errorClose releases g's bind group and uniform buffer now instead of waiting for scope disposal. Safe to call on nil or more than once.
func (g *GPUMaterial) DoubleSided() boolDoubleSided reports whether g renders both front and back faces.
func (g *GPUMaterial) Material() MaterialMaterial returns the latest Material parameters uploaded to g, or the zero value for a nil receiver.
func (g *GPUMaterial) UniformBuffer() *gpu.BufferUniformBuffer returns the underlying uniform *gpu.Buffer, or nil for a nil receiver.
func (g *GPUMaterial) Update(dev *gpu.Device, m Material) errorUpdate validates m and writes its updated uniform parameters into g's uniform buffer without reallocating the bind group.
Texture and sampler pointers must match those g was created with (to rebind textures or samplers, create a new GPUMaterial). Pass the active *gpu.Device so retained materials continue updating cleanly after a device loss and restore.
func (g *GPUMaterial) Valid() boolValid reports whether g's uniform buffer and bind group are open on a live device.
type GPUMesh struct {
// contains filtered or unexported fields
}GPUMesh is a Mesh uploaded to a GPU view's vertex and, when indexed, index buffers. Its buffers belong to the scope passed to UploadMesh and are released when that scope is disposed or when GPUMesh.Close is called. Use it from the engine goroutine, like the gpu.Device it came from.
func UploadMesh(cx *core.Scope, dev *gpu.Device, m Mesh, opts MeshUpload) (*GPUMesh, error)UploadMesh validates m and creates its vertex buffer and, when m is indexed, its index buffer on dev, scoped to cx. A malformed mesh returns an error wrapping ErrInvalidMesh before anything is created; a device error (such as gpu.ErrDeviceLost or a buffer size over gpu.Limits.MaxBufferSize) is returned as the gpu.Error NSGo reports, with no buffer left behind.
func (g *GPUMesh) Bind(pass *gpu.RenderPass)Bind binds the vertex buffer to slot 0 and, for an indexed mesh, the index buffer to pass, so a caller can issue its own draw (for example an instanced one) after setting a pipeline built with MeshVertexLayout. It binds nothing when the mesh is not GPUMesh.Valid (nil, closed, its scope disposed, or not retained across a device loss), so check Valid before issuing a draw of your own.
func (g *GPUMesh) Bounds() math3d.AABBBounds returns the object-space box around the mesh's positions, as Mesh.Bounds computed it at upload.
func (g *GPUMesh) ByteSize() uint64ByteSize returns the GPU memory the mesh's buffers hold, for RenderStats and Budget accounting. It is zero for a nil mesh.
func (g *GPUMesh) Close() errorClose releases the mesh's buffers now instead of when their scope is disposed. It is safe to call more than once.
func (g *GPUMesh) Draw(pass *gpu.RenderPass)Draw binds the mesh to pass and draws all of its triangles once. The pass must already have a pipeline whose vertex buffer 0 is MeshVertexLayout and whose bind groups are set. When the mesh is not GPUMesh.Valid it records nothing, so it never draws with buffers an earlier mesh left bound: NSGo skips binding an invalid buffer but still records the draw (nsgo-dev/nsgo#2253).
func (g *GPUMesh) IndexBuffer() *gpu.BufferIndexBuffer returns the index buffer, or nil for a non-indexed mesh.
func (g *GPUMesh) IndexCount() uint32IndexCount returns the number of indices, or zero for a non-indexed mesh.
func (g *GPUMesh) IndexFormat() gpu.IndexFormatIndexFormat returns the width of the index buffer's entries.
func (g *GPUMesh) Indexed() boolIndexed reports whether the mesh draws through an index buffer.
func (g *GPUMesh) Triangles() uint32Triangles returns the number of triangles one draw of the mesh rasterizes.
func (g *GPUMesh) Valid() boolValid reports whether the mesh's buffers are open and belong to a live device, so it can be drawn.
func (g *GPUMesh) VertexBuffer() *gpu.BufferVertexBuffer returns the interleaved vertex buffer, laid out as MeshVertexLayout describes.
func (g *GPUMesh) VertexCount() uint32VertexCount returns the number of vertices in the vertex buffer.
type GPUMorphMesh struct {
// contains filtered or unexported fields
}GPUMorphMesh is a GPUMesh whose vertex buffer is updated from a base mesh and morph target deltas whenever its weights change.
It writes blended positions and renormalized normals into the same interleaved 32-byte MeshVertexLayout buffer that GPUMesh uses, so any pipeline built for GPUMesh draws a GPUMorphMesh without shader changes across every NSGo GPU backend (including WebGL 2 and OpenGL ES 3.0 without compute shaders).
Call GPUMorphMesh.SetWeights when animation or gameplay updates morph weights, then GPUMorphMesh.Update on the engine goroutine before recording draws; Update is a no-op when weights have not changed. Use it from the engine goroutine, like the gpu.Device it came from.
func UploadMorphMesh(cx *core.Scope, dev *gpu.Device, m MorphMesh, opts MeshUpload) (*GPUMorphMesh, error)UploadMorphMesh validates m, blends its initial weights, and uploads its vertex buffer and optional index buffer onto dev, scoped to cx.
A malformed mesh returns an error wrapping ErrInvalidMesh before any GPU resource is created; a device error is returned as reported by NSGo with no buffer left behind. Setting MeshUpload.Retained preserves the latest uploaded morphed vertex bytes across GPU device loss.
func (m *GPUMorphMesh) Bind(pass *gpu.RenderPass)Bind binds the vertex buffer to slot 0 and, for an indexed mesh, the index buffer to pass.
func (m *GPUMorphMesh) Bounds() math3d.AABBBounds returns the object-space bounding box of the mesh for its current morph weights.
func (m *GPUMorphMesh) ByteSize() uint64ByteSize returns the GPU memory the mesh's buffers hold, for RenderStats and Budget accounting.
func (m *GPUMorphMesh) Close() errorClose releases the mesh's GPU buffers now instead of when their scope is disposed. It is safe to call more than once.
func (m *GPUMorphMesh) Dirty() boolDirty reports whether m has weight changes that have not yet been uploaded to the GPU vertex buffer via GPUMorphMesh.Update.
func (m *GPUMorphMesh) Draw(pass *gpu.RenderPass)Draw binds the mesh to pass and draws all of its triangles once.
func (m *GPUMorphMesh) IndexBuffer() *gpu.BufferIndexBuffer returns the index buffer, or nil for a non-indexed mesh.
func (m *GPUMorphMesh) IndexCount() uint32IndexCount returns the number of indices, or zero for a non-indexed mesh.
func (m *GPUMorphMesh) IndexFormat() gpu.IndexFormatIndexFormat returns the width of the index buffer's entries.
func (m *GPUMorphMesh) Indexed() boolIndexed reports whether the mesh draws through an index buffer.
func (m *GPUMorphMesh) Mesh() *GPUMeshMesh returns the underlying GPUMesh, or nil if m is nil.
func (m *GPUMorphMesh) SetWeights(weights []float32) errorSetWeights updates the active morph target weights and marks the mesh dirty when any weight changes. Passing fewer weights than GPUMorphMesh.TargetCount (including nil) sets the remaining trailing weights to 0; passing more weights than targets, any non-finite weight, or calling on a nil receiver returns an error wrapping ErrInvalidMesh without modifying the current weights.
func (m *GPUMorphMesh) TargetCount() intTargetCount returns the number of morph targets on m, or 0 for a nil mesh.
func (m *GPUMorphMesh) Triangles() uint32Triangles returns the number of triangles one draw of the mesh rasterizes.
func (m *GPUMorphMesh) Update(dev *gpu.Device) boolUpdate blends any pending weight changes on the CPU and writes the updated interleaved vertex buffer onto dev, returning true when a GPU upload took place. It returns false without touching the GPU when weights have not changed or when dev or m is invalid; if the device is temporarily lost, m remains dirty so the next Update after restore uploads the pending weights.
func (m *GPUMorphMesh) Valid() boolValid reports whether the mesh's GPU buffers are open and belong to a live device.
func (m *GPUMorphMesh) VertexBuffer() *gpu.BufferVertexBuffer returns the morphed interleaved vertex buffer, laid out as MeshVertexLayout describes.
func (m *GPUMorphMesh) VertexCount() uint32VertexCount returns the number of vertices in the vertex buffer.
func (m *GPUMorphMesh) Weights(dst []float32) []float32Weights copies m's active morph weights into dst[:0] and returns the slice, reusing dst's backing array when it has enough capacity.
type GPUPBRLightmap struct {
// contains filtered or unexported fields
}GPUPBRLightmap holds a scope-owned PBRLightmap uniform buffer and PBRLightmapGroup bind group wiring the per-object transform, atlas UV transform, lightmap encoding parameters, and baked lightmap texture/sampler.
func NewGPUPBRLightmap(cx *core.Scope, dev *gpu.Device, lm PBRLightmap, opts PBRLightmapOptions) (*GPUPBRLightmap, error)NewGPUPBRLightmap validates lm and creates its uniform buffer, optional bind group layout, and PBRLightmapGroup bind group on dev, owned by cx. When lm.Lightmap or lm.LightmapSampler is nil, FallbackTexture / FallbackSampler from opts is used or a retained-aware 1x1 linear fallback texture / linear-clamp sampler is created and owned by the returned handle.
func (g *GPUPBRLightmap) Bind(pass *gpu.RenderPass)Bind binds g at PBRLightmapGroup (group 3) on pass. It records nothing when g is not valid.
func (g *GPUPBRLightmap) BindAt(pass *gpu.RenderPass, group uint32)BindAt binds g at the specified bind group slot on pass. It records nothing when g is not valid.
func (g *GPUPBRLightmap) BindGroup() *gpu.BindGroupBindGroup returns the underlying *gpu.BindGroup, or nil for a nil receiver.
func (g *GPUPBRLightmap) ByteSize() uint64ByteSize returns the GPU memory held by g's uniform buffer and any owned fallback texture.
func (g *GPUPBRLightmap) Close() errorClose releases g's bind group, uniform buffer, and any owned fallback resources. It is nil-safe and safe to call more than once.
func (g *GPUPBRLightmap) Config() PBRLightmapConfig returns the latest PBRLightmap parameters uploaded to g.
func (g *GPUPBRLightmap) Layout() *gpu.BindGroupLayoutLayout returns the PBRLightmapGroup *gpu.BindGroupLayout, or nil for a nil receiver.
func (g *GPUPBRLightmap) SetModel(dev *gpu.Device, model math3d.Mat4) errorSetModel updates only the object-to-world Model matrix (and derived normal matrix) of g.
func (g *GPUPBRLightmap) UniformBuffer() *gpu.BufferUniformBuffer returns the underlying uniform *gpu.Buffer, or nil for a nil receiver.
func (g *GPUPBRLightmap) Update(dev *gpu.Device, lm PBRLightmap) errorUpdate validates lm and writes its updated uniform parameters (model matrix, UV transform, encoding, intensity, RGBM range, ambient fallback) into g's uniform buffer without reallocating the bind group. Lightmap and LightmapSampler pointers must match those g was created with. Pass the active *gpu.Device (or nil to reuse the stored device) so retained handles continue updating cleanly after a device loss and restore.
func (g *GPUPBRLightmap) Valid() boolValid reports whether g's uniform buffer, layout, and bind group are open on a live device.
type GPUPointLight struct {
// PositionRange holds world-space Position in xyz and Range in w (0 for unbounded falloff).
PositionRange math3d.Vec4
// Color holds premultiplied linear radiant intensity (Color * Intensity) in rgb and Intensity in w.
Color math3d.Vec4
}GPUPointLight is the 32-byte GPU uniform representation of one PointLight.
type GPUProbeIBLBuffer struct {
// contains filtered or unexported fields
}GPUProbeIBLBuffer holds a per-object ProbeIBLUniform buffer, 1x1 black fallback cubemap, and IBLGroup bind group wiring two local reflection probe cubemaps and a sky cubemap into ProbeIBLWGSL / LitPBRProbeIBLWGSL.
Any omitted, unbaked, dirty, or nil cubemap slot is bound to the 1x1 black (0, 0, 0, 255) fallback cubemap (never white), guaranteeing exact CPU/GPU parity with EvaluateProbeIBL. Calling GPUProbeIBLBuffer.Update writes only the uniform buffer without recreating the bind group whenever the three bound cubemap textures are unchanged.
func NewGPUProbeIBLBuffer(cx *core.Scope, dev *gpu.Device, opts ProbeIBLBufferOptions) (*GPUProbeIBLBuffer, error)NewGPUProbeIBLBuffer allocates a GPUProbeIBLBuffer on dev, owned by cx (nil for manual Close), initially bound to a zero uniform and the 1x1 black fallback cubemap across all three cube slots.
func (b *GPUProbeIBLBuffer) Bind(pass *gpu.RenderPass)Bind sets b's bind group at IBLGroup (group 3) on pass. Records nothing when b is not valid.
func (b *GPUProbeIBLBuffer) BindGroup() *gpu.BindGroupBindGroup returns the current gpu.BindGroup for IBLGroup, or nil for a nil receiver.
func (b *GPUProbeIBLBuffer) Buffer() *gpu.BufferBuffer returns the underlying uniform buffer, or nil for a nil receiver.
func (b *GPUProbeIBLBuffer) ByteSize() uint64ByteSize returns the GPU memory held by b's uniform buffer and 1x1 black fallback cubemap.
func (b *GPUProbeIBLBuffer) Close() errorClose releases the bind group, fallback cubemap, owned layout (when not shared), and uniform buffer. Safe to call on nil or more than once.
func (b *GPUProbeIBLBuffer) Layout() *gpu.BindGroupLayoutLayout returns the IBLGroup bind group layout for pipelines using ProbeIBLWGSL or LitPBRProbeIBLWGSL.
func (b *GPUProbeIBLBuffer) Update(dev *gpu.Device, u ProbeIBLUniform, probe0, probe1, sky *GPUCubemap) errorUpdate validates u, writes it to the uniform buffer, and updates the bound cubemaps when any of probe0, probe1, or sky changes. Any nil or invalid cubemap binds the 1x1 black fallback cubemap so GPU sampling returns (0, 0, 0). Pass the active *gpu.Device (or nil to reuse the last device).
func (b *GPUProbeIBLBuffer) UpdateBlend(dev *gpu.Device, sh IrradianceSH, blend ProbeBlendResult, sky *GPUCubemap, intensity float32) errorUpdateBlend builds a ProbeIBLUniform from sh, blend, sky, and intensity and uploads it to b, binding blend's ready primary and secondary probe cubemaps (or the black fallback when nil/unbaked/dirty) and sky.
func (b *GPUProbeIBLBuffer) UpdateForPoint(
dev *gpu.Device,
worldPos math3d.Vec3,
reflectionProbes *ReflectionProbeSet,
lightProbes *LightProbeVolume,
sky *GPUCubemap,
intensity float32,
) errorUpdateForPoint selects reflection probes from reflectionProbes and samples diffuse IrradianceSH from lightProbes at worldPos, then updates b with the blended probe IBL state.
func (b *GPUProbeIBLBuffer) Valid() boolValid reports whether the uniform buffer, layout, fallback cubemap, and bind group are open on a live device.
type GPUSampler struct {
// contains filtered or unexported fields
}GPUSampler is a sampler allocated on an NSGo gpu.Device. Its underlying gpu.Sampler belongs to the core.Scope passed to NewGPUSampler and is released when that scope is disposed or when GPUSampler.Close is called.
func NewGPUSampler(cx *core.Scope, dev *gpu.Device, opts SamplerOptions) (*GPUSampler, error)NewGPUSampler validates opts and creates a GPUSampler on dev, scoped to cx. Invalid options return an error wrapping ErrInvalidSampler before anything is created; a nil or lost device returns gpu.ErrDeviceLost.
func (s *GPUSampler) Close() errorClose releases the underlying gpu.Sampler now rather than when its scope is disposed. It is safe to call on a nil receiver or more than once.
func (s *GPUSampler) Options() SamplerOptionsOptions returns the normalized SamplerOptions used to create s, or the zero value for a nil receiver.
func (s *GPUSampler) Sampler() *gpu.SamplerSampler returns the underlying gpu.Sampler, or nil for a nil receiver.
func (s *GPUSampler) Valid() boolValid reports whether the sampler is open and belongs to a live device.
type GPUSkinPalette struct {
// contains filtered or unexported fields
}GPUSkinPalette holds up to MaxSkinJoints joint matrices in a portable uniform buffer (SkinUniformSize = 8192 bytes, fitting WebGL 2 and OpenGL ES 3.0's 16 KiB uniform block limit) together with the bind group layout and bind group exposed at SkinGroup.
Create it once on device readiness, call GPUSkinPalette.Update or GPUSkinPalette.UpdateFromGLTF when joint poses change, and bind GPUSkinPalette.BindGroup at the pipeline's skin group (SkinGroup, LitPBRSkinGroup or MaterialSkinGroup). Resources belong to the scope passed to NewGPUSkinPalette and are released on scope disposal or Close.
func NewGPUSkinPalette(cx *core.Scope, dev *gpu.Device, opts SkinPaletteOptions) (*GPUSkinPalette, error)NewGPUSkinPalette creates a GPUSkinPalette initialized to identity matrices for all MaxSkinJoints slots on dev, owned by cx.
func (p *GPUSkinPalette) BindGroup() *gpu.BindGroupBindGroup returns the bind group a render pass sets at SkinGroup.
func (p *GPUSkinPalette) Buffer() *gpu.BufferBuffer returns the underlying uniform buffer (SkinUniformSize bytes).
func (p *GPUSkinPalette) ByteSize() uint64ByteSize returns the GPU memory held by the uniform buffer, or 0 for a nil palette.
func (p *GPUSkinPalette) Close() errorClose releases the bind group, layout, and uniform buffer immediately. Safe to call more than once.
func (p *GPUSkinPalette) JointCount() intJointCount returns the number of active joints uploaded by the last Update.
func (p *GPUSkinPalette) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout a pipeline lists at SkinGroup.
func (p *GPUSkinPalette) Update(dev *gpu.Device, joints []math3d.Mat4) errorUpdate validates and uploads joints into the palette's uniform buffer, filling remaining slots up to MaxSkinJoints with identity matrices. If dev is nil, the device passed to NewGPUSkinPalette is used. It encodes into internal storage without heap allocations.
func (p *GPUSkinPalette) UpdateFromGLTF(dev *gpu.Device, doc *gltf.Document, skinIndex int) errorUpdateFromGLTF computes joint matrices for doc.Skins[skinIndex] into internal scratch storage and uploads them with GPUSkinPalette.Update, with zero steady-state heap allocations. Call gltf.Document.ComputeWorldMatrices first whenever node transforms or animations change.
func (p *GPUSkinPalette) UpdateFromGLTFWithTransform(dev *gpu.Device, doc *gltf.Document, skinIndex int, worldTransform math3d.Mat4) errorUpdateFromGLTFWithTransform computes joint matrices for doc.Skins[skinIndex] pre-multiplied by worldTransform and uploads them into the palette.
func (p *GPUSkinPalette) UpdateWithTransform(dev *gpu.Device, worldTransform math3d.Mat4, joints []math3d.Mat4) errorUpdateWithTransform uploads worldTransform * joints[i] for every joint, like GPUSkinPalette.Update. Use it for mesh-local joint matrices, such as anim3d's Player.SkinMatricesForNode (inverse(meshWorld) * jointWorld * inverseBind), with the mesh node's world matrix (Player.WorldTransform), so pipelines without a model matrix (NewSkinnedMeshPipeline, MaterialPipelineOptions.SkinLayout) draw the mesh where its node is. It reuses internal storage and does not modify joints.
func (p *GPUSkinPalette) Valid() boolValid reports whether the palette's GPU resources are open and live.
type GPUSkinnedMesh struct {
// contains filtered or unexported fields
}GPUSkinnedMesh is a SkinnedMesh uploaded to GPU vertex and optional index buffers scoped to the *core.Scope passed to UploadSkinnedMesh.
func UploadSkinnedMesh(cx *core.Scope, dev *gpu.Device, m SkinnedMesh, opts MeshUpload) (*GPUSkinnedMesh, error)UploadSkinnedMesh validates m and uploads its interleaved skinned vertex buffer and optional index buffer to dev, owned by cx. Set opts.Retained to keep a CPU copy so NSGo recreates the buffers automatically after a device loss.
func (g *GPUSkinnedMesh) Bind(pass *gpu.RenderPass)Bind binds the vertex buffer to slot 0 and, for an indexed mesh, the index buffer to pass. It binds nothing when the mesh is not GPUSkinnedMesh.Valid.
func (g *GPUSkinnedMesh) Bounds() math3d.AABBBounds returns the unskinned box SkinnedMesh.Bounds computed at upload. Pass it to SkinnedBounds with the frame's joint matrices to get a box around the drawn mesh for culling.
func (g *GPUSkinnedMesh) ByteSize() uint64ByteSize returns the GPU memory held by the mesh's buffers, or 0 for a nil mesh.
func (g *GPUSkinnedMesh) Close() errorClose releases the mesh's GPU buffers immediately. It is safe to call more than once.
func (g *GPUSkinnedMesh) Draw(pass *gpu.RenderPass)Draw binds the skinned mesh to pass and issues one draw call. The pass must already have a pipeline whose vertex buffer 0 is SkinnedVertexLayout and a GPUSkinPalette bound at the pipeline's skin group (SkinGroup, LitPBRSkinGroup or MaterialSkinGroup). When the mesh is not valid it records nothing.
func (g *GPUSkinnedMesh) IndexBuffer() *gpu.BufferIndexBuffer returns the index buffer, or nil for a non-indexed skinned mesh.
func (g *GPUSkinnedMesh) IndexCount() uint32IndexCount returns the number of indices, or zero for a non-indexed mesh.
func (g *GPUSkinnedMesh) IndexFormat() gpu.IndexFormatIndexFormat returns the width of the index buffer's entries.
func (g *GPUSkinnedMesh) Indexed() boolIndexed reports whether the skinned mesh draws through an index buffer.
func (g *GPUSkinnedMesh) JointCount() intJointCount returns the joint count recorded on the source SkinnedMesh (0 if unspecified).
func (g *GPUSkinnedMesh) Triangles() uint32Triangles returns the number of triangles one draw of the mesh rasterizes.
func (g *GPUSkinnedMesh) Valid() boolValid reports whether the skinned mesh's buffers are open and belong to a live device.
func (g *GPUSkinnedMesh) VertexBuffer() *gpu.BufferVertexBuffer returns the interleaved skinned vertex buffer described by SkinnedVertexLayout.
func (g *GPUSkinnedMesh) VertexCount() uint32VertexCount returns the number of vertices in the vertex buffer.
type GPUSpotLight struct {
// PositionRange holds world-space Position in xyz and Range in w (0 for unbounded falloff).
PositionRange math3d.Vec4
// DirectionScale holds the unit cone direction in xyz and the angular scale from [SpotLight.ConeScaleOffset] in w.
DirectionScale math3d.Vec4
// ColorOffset holds premultiplied linear radiant intensity (Color * Intensity) in rgb and the angular offset from [SpotLight.ConeScaleOffset] in w.
ColorOffset math3d.Vec4
}GPUSpotLight is the 48-byte GPU uniform representation of one SpotLight.
type GPUTerrainMaterial struct {
// contains filtered or unexported fields
}GPUTerrainMaterial owns the uniform buffer, splat textures, 2D texture arrays, samplers, bind group layout, and bind group for rendering a splat-blended multi-layer PBR terrain at TerrainMaterialGroup (group 2).
func NewGPUTerrainMaterial(cx *core.Scope, dev *gpu.Device, m TerrainMaterial, opts TerrainMaterialUpload) (*GPUTerrainMaterial, error)NewGPUTerrainMaterial validates m and uploads its uniform buffer, splat map textures, per-layer 2D texture arrays (albedo, normal, and packed height/roughness/metallic), samplers, and TerrainMaterialGroup bind group onto dev, owned by cx.
func (g *GPUTerrainMaterial) Bind(pass *gpu.RenderPass)Bind binds g's bind group at TerrainMaterialGroup (group 2) on pass.
func (g *GPUTerrainMaterial) BindGroup() *gpu.BindGroupBindGroup returns g's gpu.BindGroup, or nil for a nil receiver.
func (g *GPUTerrainMaterial) ByteSize() uint64ByteSize returns the approximate GPU memory owned by g (uniform buffer, splat maps, and all 3 layer texture arrays including mip chains).
func (g *GPUTerrainMaterial) Close() errorClose releases every GPU resource owned by g now rather than waiting for scope disposal. Safe to call on nil or more than once.
func (g *GPUTerrainMaterial) LayerCount() intLayerCount returns the number of material layers uploaded into g.
func (g *GPUTerrainMaterial) Layout() *gpu.BindGroupLayoutLayout returns g's TerrainMaterialGroup bind group layout, or nil for a nil receiver.
func (g *GPUTerrainMaterial) UniformBuffer() *gpu.BufferUniformBuffer returns g's uniform *gpu.Buffer, or nil for a nil receiver.
func (g *GPUTerrainMaterial) UpdateSplatMaps(dev *gpu.Device, splat0, splat1 image.Image) errorUpdateSplatMaps uploads new RGBA splat map image data into g's splat textures in place (e.g., after interactive terrain painting). Non-nil images must match the dimensions of the existing splat texture.
func (g *GPUTerrainMaterial) UpdateUniforms(dev *gpu.Device, m TerrainMaterial) errorUpdateUniforms validates m and updates g's uniform buffer in place (model transform, height blend contrast, triplanar parameters, and per-layer scalar factors / UV scales) without reallocating textures or bind groups. The layer count must match the count g was created with.
func (g *GPUTerrainMaterial) Valid() boolValid reports whether every GPU resource owned by g is open on a live device.
type GPUTexture struct {
// contains filtered or unexported fields
}GPUTexture is a 2D texture uploaded to an NSGo gpu.Device. Its underlying gpu.Texture belongs to the core.Scope passed at upload and is released when that scope is disposed or when GPUTexture.Close is called. Use it from the engine goroutine, like the gpu.Device it came from.
func UploadLightmapRGBA16F(cx *core.Scope, dev *gpu.Device, hdr []math3d.Vec3, width, height int, opts TextureUpload) (*GPUTexture, error)UploadLightmapRGBA16F packs linear HDR RGB irradiance pixels into an IEEE-754 float16 RGBA16F texture (gpu.FormatRGBA16Float) and uploads it to dev, scoped to cx, for use with LightmapLinear.
func UploadTexture(cx *core.Scope, dev *gpu.Device, img image.Image, opts TextureUpload) (*GPUTexture, error)UploadTexture converts img to straight-alpha RGBA8 and uploads it to dev, scoped to cx. An invalid image returns an error wrapping ErrInvalidTexture before anything is created; a device error (such as gpu.ErrDeviceLost or dimensions over gpu.Limits.MaxTextureDimension2D) is returned as the gpu.Error NSGo reports.
func UploadTexturePixels(cx *core.Scope, dev *gpu.Device, buf PixelBuffer, opts TextureUpload) (*GPUTexture, error)UploadTexturePixels validates buf and uploads it to dev as a sampled 2D texture, scoped to cx. When opts.Mipmaps is true, every level of the mipmap chain is generated on the CPU (in linear light for sRGB textures) and uploaded with gpu.Device.WriteTextureMip.
func (t *GPUTexture) ByteSize() uint64ByteSize returns the total GPU memory across all uploaded mipmap levels, for RenderStats and Budget accounting. It is zero for a nil texture.
func (t *GPUTexture) Close() errorClose releases the underlying gpu.Texture now rather than when its scope is disposed. It is safe to call on a nil receiver or more than once.
func (t *GPUTexture) Format() gpu.TextureFormatFormat returns the GPU texture format, or gpu.FormatUndefined for a nil receiver.
func (t *GPUTexture) Height() uint32Height returns the base level height in texels, or zero for a nil receiver.
func (t *GPUTexture) MipLevels() uint32MipLevels returns the number of mipmap levels uploaded (1 without mipmaps), or zero for a nil receiver.
func (t *GPUTexture) SRGB() boolSRGB reports whether the texture decodes sRGB RGB channels to linear light on sample.
func (t *GPUTexture) Texture() *gpu.TextureTexture returns the underlying gpu.Texture, or nil for a nil receiver.
func (t *GPUTexture) UpdateImage(dev *gpu.Device, img image.Image) errorUpdateImage replaces t's pixels from img (and regenerates its mip chain when t has more than one mip level). img must have the same dimensions as t, and t must have an RGBA8 format.
func (t *GPUTexture) UpdatePixels(dev *gpu.Device, buf PixelBuffer) errorUpdatePixels replaces t's pixels from buf (and regenerates its mip chain when t has more than one mip level). buf must match t's dimensions and pixel format (passing gpu.FormatUndefined or gpu.FormatRGBA8Unorm is accepted for both linear and sRGB RGBA8 textures).
func (t *GPUTexture) Valid() boolValid reports whether the texture is open and belongs to a live device.
func (t *GPUTexture) Width() uint32Width returns the base level width in texels, or zero for a nil receiver.
type GPUToonMaterial struct {
// contains filtered or unexported fields
}GPUToonMaterial holds a ToonMaterial's uniform buffer and its bind group for @group(ToonMaterialGroup). Omitted textures and samplers come from a shared MaterialDefaults. Resources belong to the core.Scope passed to NewGPUToonMaterial and are released when that scope is disposed or when GPUToonMaterial.Close is called.
func NewGPUToonMaterial(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, mat ToonMaterial, opts ToonMaterialOptions) (*GPUToonMaterial, error)NewGPUToonMaterial validates mat and allocates its uniform buffer and @group(1) bind group on dev, scoped to cx, binding defaults' 1x1 white textures and sampler for omitted textures and samplers, as NewGPUMaterial does. Create one MaterialDefaults per device and share it. Invalid parameters or defaults return an error wrapping ErrInvalidToonMaterial before touching the device.
func (m *GPUToonMaterial) Bind(pass *gpu.RenderPass)Bind binds the material's bind group at ToonMaterialGroup (group 1) on pass. It does nothing when m is not GPUToonMaterial.Valid.
func (m *GPUToonMaterial) BindAt(pass *gpu.RenderPass, group uint32)BindAt binds the material's bind group at the specified group index on pass. It does nothing when m is not GPUToonMaterial.Valid.
func (m *GPUToonMaterial) BindGroup() *gpu.BindGroupBindGroup returns the underlying gpu.BindGroup, or nil for a nil receiver.
func (m *GPUToonMaterial) ByteSize() uint64ByteSize returns the GPU buffer memory owned by m (excluding shared defaults and caller-owned textures).
func (m *GPUToonMaterial) Close() errorClose releases all GPU resources owned by m (never closing the shared defaults, caller-owned textures and samplers, or shared layouts). It is safe to call on a nil receiver or more than once.
func (m *GPUToonMaterial) HasOutline() boolHasOutline reports whether m's current material enables the inverted-hull outline pass.
func (m *GPUToonMaterial) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout for @group(ToonMaterialGroup).
func (m *GPUToonMaterial) Material() ToonMaterialMaterial returns the latest ToonMaterial uploaded to m.
func (m *GPUToonMaterial) Update(dev *gpu.Device, mat ToonMaterial) errorUpdate validates mat and uploads its updated uniform parameters into m's uniform buffer on dev without allocating. It takes dev explicitly so a retained material remains updatable after a GPU device loss and restore. Texture and sampler handles bound in the bind group cannot be changed in-place; create a new GPUToonMaterial to swap textures or samplers.
func (m *GPUToonMaterial) Valid() boolValid reports whether m's GPU resources are open and belong to a live device.
type GPUUnlitMaterial struct {
// contains filtered or unexported fields
}GPUUnlitMaterial holds the GPU uniform buffer and MaterialGroup bind group for an UnlitMaterial. A nil base color texture or sampler binds the shared fallbacks of the MaterialDefaults it was created with.
Its resources belong to the core.Scope passed at creation and are released when that scope is disposed or when GPUUnlitMaterial.Close is called. It does not cache a *gpu.Device pointer, so a retained material remains updatable via GPUUnlitMaterial.Update after a device loss and restore.
func NewGPUUnlitMaterial(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, m UnlitMaterial, opts MaterialUpload) (*GPUUnlitMaterial, error)NewGPUUnlitMaterial validates m, uploads its uniform block, and creates a bind group on MaterialDefaults.UnlitLayout, owned by cx. A nil BaseColorTexture or BaseColorSampler binds MaterialDefaults.WhiteSRGB or MaterialDefaults.Sampler. Invalid parameters or handles return an error wrapping ErrInvalidUnlitMaterial before any GPU object is created.
func UploadGLTFUnlitMaterial(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, doc *gltf.Document, matIndex int, opts GLTFMaterialUpload) (*GPUUnlitMaterial, error)UploadGLTFUnlitMaterial extracts a KHR_materials_unlit material from doc.Materials[matIndex], decodes and uploads its baseColorTexture as an sRGB GPUTexture with a sampler converted by SamplerOptionsFromGLTF (the glTF default sampler when the texture names none), and creates a scope-owned GPUUnlitMaterial. Without a baseColorTexture the material binds the fallbacks of defaults.
opts applies as in UploadGLTFMaterials: Label prefixes the debug labels, Mipmaps forces mipmaps, DisableMipmaps turns them off, mipmaps are otherwise generated when the sampler's minFilter is mipmapped or unset, and MaxMipLevels, MaxAnisotropy and Retained carry over. The decoded texture and created sampler are owned by the returned material and closed with it.
A baseColorTexture whose image comes only from an extension (such as KHR_texture_basisu or EXT_texture_webp, which glTF expresses as a texture without a source) returns an error wrapping ErrInvalidUnlitMaterial instead of silently drawing white.
func (m *GPUUnlitMaterial) Bind(pass *gpu.RenderPass)Bind binds m's bind group at MaterialGroup (group 1) on pass. It records nothing when m is not GPUUnlitMaterial.Valid.
func (m *GPUUnlitMaterial) BindAt(pass *gpu.RenderPass, group uint32)BindAt binds m's bind group at group on pass. It records nothing when m is not GPUUnlitMaterial.Valid.
func (m *GPUUnlitMaterial) BindGroup() *gpu.BindGroupBindGroup returns the underlying bind group, or nil for a nil receiver.
func (m *GPUUnlitMaterial) ByteSize() uint64ByteSize returns the GPU memory held by m's uniform buffer and the glTF-decoded texture it owns (the shared MaterialDefaults are counted there). It is zero for a nil receiver.
func (m *GPUUnlitMaterial) Close() errorClose releases the material's bind group, uniform buffer, and any glTF-decoded texture and sampler it owns (leaving caller-supplied textures and samplers and the shared MaterialDefaults untouched). Safe to call on a nil receiver or more than once.
func (m *GPUUnlitMaterial) Material() UnlitMaterialMaterial returns a copy of the current UnlitMaterial settings stored in m, or the zero value for a nil receiver.
func (m *GPUUnlitMaterial) UniformBuffer() *gpu.BufferUniformBuffer returns the underlying material uniform buffer, or nil for a nil receiver.
func (m *GPUUnlitMaterial) Update(dev *gpu.Device, mat UnlitMaterial) errorUpdate writes updated uniform parameters (BaseColorFactor, AlphaMode, AlphaCutoff, DoubleSided, UseVertexColor) to the GPU uniform buffer with zero allocations.
Texture and sampler bindings are immutable per GPUUnlitMaterial: pass either the same handles bound at creation or nil (to keep the existing bindings). Passing a different texture or sampler handle returns an error wrapping ErrInvalidUnlitMaterial.
func (m *GPUUnlitMaterial) Valid() boolValid reports whether the material's uniform buffer, bind group, and bound texture and sampler are open and belong to a live device.
type Gizmo struct {
// RingSegments controls rotation ring tessellation (default 32).
RingSegments int
// PickThreshold is the ray-hit tolerance as a fraction of scale (default 0.12).
PickThreshold float32
// LineWidth is the stroke width in points for inactive axes (default 2.0).
LineWidth float32
// ActiveLineWidth is the stroke width in points for the active axis (default 3.5).
ActiveLineWidth float32
// DepthNO clips at the near plane of an OpenGL-style [-1, 1] depth projection, as [ProjectSegmentNO] does. By default handles clip for [0, 1] depth, matching [math3d.Perspective] and [math3d.Ortho].
DepthNO bool
}Gizmo generates 3D translate/rotate/scale wireframe handles, performs ray picking against axes and rings, computes constrained drag deltas with optional snapping, and renders into *core.Drawing (#287).
The zero value is ready to use with sensible defaults.
func (g Gizmo) AppendSegments(dst []GizmoSegment, origin math3d.Vec3, scale float32, mode GizmoMode) []GizmoSegmentAppendSegments appends the segments Gizmo.Segments would return to dst and returns the extended slice, allocating nothing when dst has room.
func (g Gizmo) DragRotate(origin math3d.Vec3, axis GizmoAxis, startRay, currentRay math3d.Ray, snap float32) float32DragRotate computes the signed right-handed rotation angle in radians around axis (AxisX, AxisY, or AxisZ) from startRay to currentRay relative to origin. When snap > 0, the angle is rounded to the nearest multiple of snap radians.
func (g Gizmo) DragRotateQuat(origin math3d.Vec3, axis GizmoAxis, startRay, currentRay math3d.Ray, snap float32) math3d.QuatDragRotateQuat is a convenience wrapper around Gizmo.DragRotate returning the rotation delta as a unit math3d.Quat.
func (g Gizmo) DragScale(origin math3d.Vec3, axis GizmoAxis, startRay, currentRay math3d.Ray, snap float32) math3d.Vec3DragScale computes the constrained additive 3D scale delta along axis from startRay to currentRay relative to origin (zero when the rays match; apply as startScale.Add(delta)).
For single axes (AxisX/AxisY/AxisZ) and planes (AxisXY/AxisXZ/AxisYZ), only the active components vary. For AxisAll, all three components receive the same uniform delta. When snap > 0, active components are rounded to the nearest multiple of snap.
func (g Gizmo) DragTranslate(origin math3d.Vec3, axis GizmoAxis, startRay, currentRay math3d.Ray, snap float32) math3d.Vec3DragTranslate computes the exact constrained 3D world-space translation delta along axis from startRay to currentRay relative to origin. When snap > 0, each active delta component is rounded to the nearest multiple of snap.
func (g Gizmo) DrawGizmo(d *core.Drawing, viewProj math3d.Mat4, viewport core.Bounds, origin math3d.Vec3, scale float32, mode GizmoMode, activeAxis GizmoAxis)DrawGizmo projects and draws g's 3D wireframe handles into d with near-plane clipping, drawing activeAxis segments highlighted and thicker on top.
func (g Gizmo) PickAxis(ray math3d.Ray, origin math3d.Vec3, scale float32, mode GizmoMode) (GizmoAxis, float32)PickAxis tests ray against the gizmo handles at origin with size scale in mode and returns the picked GizmoAxis and the hit ray parameter t >= 0. If no handle lies within the pick threshold, it returns (AxisNone, 0).
func (g Gizmo) Segments(origin math3d.Vec3, scale float32, mode GizmoMode) []GizmoSegmentSegments generates the 3D wireframe line segments for a gizmo at origin scaled by scale in mode. It allocates a new slice; use Gizmo.AppendSegments to reuse one.
type GizmoAxis uint8GizmoAxis identifies a picked or active handle on a Gizmo (#287).
const (
AxisNone GizmoAxis = iota
AxisX
AxisY
AxisZ
AxisXY
AxisXZ
AxisYZ
AxisAll
)type GizmoMode uint8GizmoMode selects the transformation tool represented by a Gizmo (#287).
const (
GizmoTranslate GizmoMode = iota
GizmoRotate
GizmoScale
)type GizmoSegment struct {
A, B math3d.Vec3
Axis GizmoAxis
Color core.Color
}GizmoSegment is one colored 3D wireframe edge belonging to a GizmoAxis.
type HDRCubemap struct {
Size int
Faces [6][][3]float32
Mips [][6][][3]float32
}HDRCubemap holds a 6-face square linear floating-point cubemap on the CPU in canonical WebGPU / Metal / Direct3D / OpenGL order (gpu.CubeFacePosX..gpu.CubeFaceNegZ), preserving high dynamic range radiance above 1.0 without clamping.
Faces holds mip level 0: six slices of Size*Size linear RGB radiance triples in row-major order. Mips optionally holds precomputed mip levels starting at level 1 (such as GGX-prefiltered HDR specular levels from PrefilterEnvironmentHDR). Upload to the GPU with UploadCubemapHDR (preferring gpu.FormatRGBA16Float).
func CubemapFromHDR(r io.Reader, faceSize int) (*HDRCubemap, error)CubemapFromHDR decodes a Radiance .hdr (RGBE) equirectangular panorama from r and projects it into a 6-face linear float32 HDRCubemap of resolution faceSize x faceSize per face.
func CubemapFromHDREquirectangular(img *HDRImage, faceSize int) (*HDRCubemap, error)CubemapFromHDREquirectangular projects a linear floating-point latitude-longitude (equirectangular) HDRImage into a 6-face HDRCubemap of resolution faceSize x faceSize per face using seamless horizontal wrapping and bilinear filtering in linear light, preserving HDR radiance above 1.0.
Longitude u = 0.5 + atan2(z, x) / (2*pi) maps +X to u = 0.5 and +Z to u = 0.75; latitude v = acos(y) / pi maps +Y (zenith) to the top row (v = 0) and -Y (nadir) to the bottom row (v = 1).
func CubemapFromHDRImage(img *HDRImage) (*HDRCubemap, error)CubemapFromHDRImage converts a decoded Radiance *HDRImage into a 6-face linear *HDRCubemap. When img is a 6x1 horizontal cubemap strip (img.Width == 6*img.Height, as written by EncodeCubemapHDR), its six faces (+X, -X, +Y, -Y, +Z, -Z) are extracted directly with zero resampling. Otherwise img is treated as an equirectangular panorama and projected via CubemapFromHDREquirectangular.
func DecodeCubemapHDR(r io.Reader) (*HDRCubemap, error)DecodeCubemapHDR decodes a Radiance .hdr (RGBE) cubemap strip (as written by EncodeCubemapHDR) or equirectangular panorama from r into a 6-face linear float32 *HDRCubemap.
func GradientSkyHDRCubemap(zenith, horizon, ground [3]float32, faceSize int) (*HDRCubemap, error)GradientSkyHDRCubemap builds a procedural 3-band linear HDR sky cubemap interpolating smoothly from horizon to zenith across the upper hemisphere (y >= 0) and from horizon to ground across the lower hemisphere (y < 0). Unlike GradientSkyCubemap, linear RGB values above 1.0 are preserved without clamping.
func HDRCubemapFromCubemap(cm *Cubemap) (*HDRCubemap, error)HDRCubemapFromCubemap promotes an LDR RGBA8 *Cubemap (decoding sRGB when cm.SRGB is true) into a linear float32 *HDRCubemap, preserving any precomputed mip levels.
func NewHDRCubemap(size int) (*HDRCubemap, error)NewHDRCubemap allocates a zeroed linear float32 HDRCubemap with face edge length size.
func PrefilterEnvironmentHDR(env *HDRCubemap, opts PrefilterOptions) (*HDRCubemap, error)PrefilterEnvironmentHDR builds a split-sum GGX prefiltered specular HDRCubemap mip chain from env (Karis 2013), preserving high dynamic range radiance above 1.0 across all roughness levels. Mip level 0 corresponds to roughness 0 (mirror reflection) and mip level MipLevels-1 corresponds to roughness 1.
func (c *HDRCubemap) At(face gpu.CubeFace, x, y int) [3]float32At returns the linear RGB radiance at mip 0 texel (x, y) on face, or zero when out of bounds.
func (c *HDRCubemap) MipLevels() intMipLevels returns the total number of mip levels stored in c (1 when Mips is empty), or 0 if invalid.
func (c *HDRCubemap) Sample(dir math3d.Vec3) [3]float32Sample bilinearly samples mip level 0 of c in direction dir and returns unclamped linear RGB radiance.
func (c *HDRCubemap) SampleLOD(dir math3d.Vec3, lod float32) [3]float32SampleLOD trilinearly samples c at mip level lod (clamped to [0, MipLevels-1]) in direction dir and returns unclamped linear RGB radiance.
func (c *HDRCubemap) Set(face gpu.CubeFace, x, y int, rgb [3]float32)Set writes the linear RGB radiance at mip 0 texel (x, y) on face when in bounds.
func (c *HDRCubemap) Validate() errorValidate checks that c is non-nil, Size is positive, every base face has Size*Size finite non-negative linear RGB texels, and every optional mip level has the exact expected dimensions down to 1x1. Every error wraps ErrInvalidCubemap.
type HDRImage struct {
Width int
Height int
RGB [][3]float32
}HDRImage holds a 2D linear floating-point RGB image (such as a decoded Radiance .hdr equirectangular environment map) in row-major order, top row first.
func DecodeHDR(r io.Reader) (*HDRImage, error)DecodeHDR decodes a Radiance RGBE (.hdr / .pic) image stream into linear floating-point RGB radiance values. It supports standard adaptive RLE, old-style RLE, and uncompressed scanlines, as well as the standard Radiance EXPOSURE header and +/-Y +/-X scanline orientations. Malformed streams return an error wrapping ErrInvalidCubemap.
func NewHDRImage(width, height int) (*HDRImage, error)NewHDRImage allocates a zeroed linear RGB HDRImage of dimensions width x height. Non-positive dimensions return an error wrapping ErrInvalidCubemap.
func (img *HDRImage) At(x, y int) [3]float32At returns the linear RGB radiance at (x, y), or zero when out of bounds.
func (img *HDRImage) Set(x, y int, rgb [3]float32)Set writes the linear RGB radiance at (x, y) when in bounds.
func (img *HDRImage) Validate() errorValidate checks that img is non-nil, has positive dimensions matching len(RGB), and contains only finite non-negative linear radiance values. Every error wraps ErrInvalidCubemap.
type HDRTarget struct {
// contains filtered or unexported fields
}HDRTarget owns an offscreen linear floating-point gpu.RenderTarget (gpu.FormatRGBA16Float with automatic fallback to gpu.FormatRGBA8Unorm on devices without half-float support) for rendering 3D scenes before tone mapping (#250).
func NewHDRTarget(cx *core.Scope, dev *gpu.Device, desc HDRTargetDesc) (*HDRTarget, error)NewHDRTarget allocates an HDRTarget on dev scoped to cx (nil for resources the caller closes manually, as in headless tests).
It prefers gpu.FormatRGBA16Float when SupportsHDR(dev) is true and gracefully falls back to gpu.FormatRGBA8Unorm otherwise unless desc.DisableFallback is set.
func (t *HDRTarget) ByteSize() uint64ByteSize returns the estimated GPU memory in bytes held by the target's color, resolve, and depth attachments, for RenderStats and Budget accounting.
func (t *HDRTarget) Close() errorClose releases the target's GPU attachments. It is safe to call on nil or more than once.
func (t *HDRTarget) ColorAttachment(clearColor core.Color) gpu.ColorAttachmentColorAttachment returns a gpu.ColorAttachment configured to clear and draw into t (automatically wiring ResolveTarget when multisampled).
func (t *HDRTarget) ColorAttachmentTexture() *gpu.TextureColorAttachmentTexture returns the color texture rendered into by the 3D scene pass (multisampled when SampleCount > 1).
func (t *HDRTarget) ColorTexture() *gpu.TextureColorTexture returns the resolved texture suitable for sampling in ToneMapPass: the MSAA resolve texture when multisampled, otherwise the color attachment texture.
func (t *HDRTarget) DepthFormat() gpu.TextureFormatDepthFormat returns the depth/stencil format, or gpu.FormatUndefined if none.
func (t *HDRTarget) DepthTexture() *gpu.TextureDepthTexture returns the optional depth/stencil texture, or nil when created without a DepthFormat.
func (t *HDRTarget) Format() gpu.TextureFormatFormat returns the actual color format allocated (gpu.FormatRGBA16Float on HDR-capable devices, or gpu.FormatRGBA8Unorm when fallen back).
func (t *HDRTarget) Height() uint32Height returns the target height in physical pixels.
func (t *HDRTarget) IsHDR() boolIsHDR reports whether the target uses a floating-point color format capable of storing linear values above 1.0 without clamping.
func (t *HDRTarget) RenderPassDesc(clearColor core.Color, clearDepth float32) gpu.RenderPassDescRenderPassDesc returns a gpu.RenderPassDesc targeting t's color attachment and, when present, its depth attachment.
func (t *HDRTarget) RenderTarget() *gpu.RenderTargetRenderTarget returns the underlying *gpu.RenderTarget.
func (t *HDRTarget) Resize(dev *gpu.Device, width, height uint32) errorResize recreates t's attachments at width x height when the dimensions differ or the existing target is no longer valid. Pass dev (for example frame.Device()) after a device restore, or nil to reuse the original device.
func (t *HDRTarget) SampleCount() intSampleCount returns the effective MSAA sample count (1 or 4).
func (t *HDRTarget) Valid() boolValid reports whether the target's GPU textures are open and belong to a live device.
func (t *HDRTarget) Width() uint32Width returns the target width in physical pixels.
type HDRTargetDesc struct {
// Label names the offscreen textures in GPU capture tools.
Label string
// Width and Height are the target dimensions in physical pixels. Both must be positive.
Width uint32
Height uint32
// DepthFormat optionally creates a matching depth/stencil attachment (for example [gpu.FormatDepth24Plus]). Leave [gpu.FormatUndefined] for a color-only HDR target.
DepthFormat gpu.TextureFormat
// SampleCount enables MSAA when > 1 (for example 4). If the device does not report [gpu.Features].MSAA4x, it falls back to 1.
SampleCount int
// DisableFallback prevents falling back to [gpu.FormatRGBA8Unorm] when [gpu.FormatRGBA16Float] is unsupported, returning [gpu.ErrUnsupported].
DisableFallback bool
// Retained opts into automatic recreation after a GPU device loss (see [gpu.RenderTargetDesc].Retained).
Retained bool
}HDRTargetDesc configures NewHDRTarget.
type IBLBufferOptions struct {
// Label names the buffer, bind group layout, and bind group in GPU capture tools.
Label string
// Retained keeps a CPU shadow copy so NSGo recreates the uniform buffer, layout, and bind group with their latest data after a device loss. The prefiltered cubemap must be retained too.
Retained bool
}IBLBufferOptions configures NewGPUIBLBuffer.
type IBLUniform struct {
SH IrradianceSH
Intensity float32
MaxLOD float32
}IBLUniform holds the diffuse L2 spherical harmonic irradiance coefficients and specular prefilter parameters bound by GPUIBLBuffer and read by IBLWGSL.
func NewIBLUniform(sh IrradianceSH, prefilter *GPUCubemap, intensity float32) IBLUniformNewIBLUniform populates an IBLUniform from sh, prefilter's maximum mip LOD, and intensity.
func (u *IBLUniform) Encode(dst []byte) []byteEncode writes u into dst as the little-endian IBLUniformSize-byte block matching IBLWGSL and returns dst[:IBLUniformSize]. It panics if len(dst) < IBLUniformSize.
func (u IBLUniform) Validate() errorValidate reports whether every spherical harmonic coefficient is finite and Intensity and MaxLOD are finite and non-negative. Every error wraps ErrInvalidIBL.
type InstanceBatch struct {
PipelineID uint32
MaterialID uint32
MeshID uint32
Blend BlendMode
Transforms []math3d.Mat4
Triangles uint32 // per-instance triangle count
Vertices uint32 // per-instance vertex count
}InstanceBatch groups consecutive opaque/alpha-mask draws sharing an identical (PipelineID, MaterialID, MeshID, Blend) state key so a GPU backend can submit them in a single instanced draw call (#246).
type IrradianceSH struct {
Coeff [9][3]float32
}IrradianceSH stores the 9 pre-convolved L2 real spherical harmonic RGB coefficients representing diffuse cosine-weighted irradiance E(n) = integral L(w) * max(n·w, 0) dw (Ramamoorthi & Hanrahan 2001).
For a uniform environment with linear radiance C, IrradianceSH.Evaluate returns pi * C at every normal; Lambertian diffuse shading multiplies by albedo / pi.
func ComputeIrradianceSH(env *Cubemap) (IrradianceSH, error)ComputeIrradianceSH projects env's base mip level onto L2 spherical harmonics using exact per-texel cubemap solid angles (which sum to exactly 4*pi across all six faces) and applies the Lambertian cosine-lobe convolution weights (pi, 2*pi/3, pi/4).
func ComputeIrradianceSHFromFunc(size int, sample func(dir math3d.Vec3) [3]float32) (IrradianceSH, error)ComputeIrradianceSHFromFunc integrates linear RGB radiance returned by sample(dir) over a size x size cubemap using exact per-texel solid angles and cosine-lobe convolution weights, matching ComputeIrradianceSH without clamping radiance to 8-bit LDR.
func ComputeIrradianceSHHDR(env *HDRCubemap) (IrradianceSH, error)ComputeIrradianceSHHDR projects env's base mip level onto L2 spherical harmonics using exact analytical per-texel cubemap solid angles (summing to 4*pi across all six faces) and applies the Lambertian cosine-lobe convolution weights (pi, 2*pi/3, pi/4), preserving HDR radiance above 1.0.
func ProjectDirectionIrradianceSH(dir math3d.Vec3, radiance [3]float32) IrradianceSHProjectDirectionIrradianceSH projects a directional radiance sample along dir onto the cosine-convolved L2 spherical harmonic basis used by IrradianceSH. Scale each sample by its solid angle dOmega and sum with IrradianceSH.Add to integrate an arbitrary directional environment.
func (sh IrradianceSH) Add(other IrradianceSH) IrradianceSHAdd returns the component-wise sum sh + other.
func (sh IrradianceSH) Evaluate(normal math3d.Vec3) [3]float32Evaluate evaluates the diffuse irradiance E(normal) from sh, matching IBLWGSL's evaluate_irradiance_sh. Negative values from high-contrast ringing are clamped to zero.
func (sh IrradianceSH) Lerp(other IrradianceSH, t float32) IrradianceSHLerp linearly interpolates between sh (t = 0) and other (t = 1).
func (sh IrradianceSH) Scale(k float32) IrradianceSHScale returns sh multiplied by scalar k.
func (sh IrradianceSH) ToCubemap(faceSize int) (*Cubemap, error)ToCubemap renders sh into a low-resolution diffuse radiance cubemap storing E(n) / pi per texel (so a uniform [0, 1] environment maps back into [0, 1] without clipping).
type KTX2Upload struct {
// Label names the texture in GPU capture tools.
Label string
// Retained keeps a CPU copy of every mip level so NSGo recreates the texture after a device loss (see [gpu.TextureDesc].Retained).
Retained bool
// Sampler is the sampler the texture is drawn with before the file's filter is applied: its wrapping, LOD bounds and label are kept, and its filters are kept when the file names none.
Sampler SamplerOptions
// ForceRGBA8 uploads every level decoded to RGBA8 even when dev supports the file's block format or one a UASTC or ETC1S file could be transcoded to.
ForceRGBA8 bool
}KTX2Upload configures LoadKTX2.
type LODLevel struct {
MeshID uint32
MaxDistance float32
MinScreenRatio float32
Triangles uint32
Vertices uint32
}LODLevel describes one mesh detail level for a DrawItem, ordered from finest (index 0) to coarsest (last index).
A level is eligible when its active thresholds are satisfied:
- If MaxDistance > 0, camera distance must be <= MaxDistance.
- If MinScreenRatio > 0, projected screen-height ratio must be >= MinScreenRatio.
- Leaving both zero marks an unbounded coarsest fallback level.
type LayeredDrawItem struct {
Item DrawItem
Layer uint32
}LayeredDrawItem pairs a DrawItem with a 32-bit layer bitmask matching scene3d.Node.Layer for per-camera layer filtering before Queue.Build.
type LightBufferOptions struct {
// Label names the buffer, bind group layout and bind group in GPU capture tools.
Label string
// Retained keeps a CPU copy of the uniform buffer so NSGo automatically recreates the buffer,
// its bind group layout, and its bind group after a device loss (see [gpu.BufferDesc].Retained).
Retained bool
}LightBufferOptions configures NewLightBuffer.
type LightProbe struct {
ID string
Position math3d.Vec3
Radius float32 // optional influence radius; <= 0 means unbounded inverse-distance blending
SH IrradianceSH
Dirty bool
Baked bool
}LightProbe stores baked L2 diffuse spherical harmonic irradiance (IrradianceSH) at a world-space sample point for shading dynamic objects.
func (p LightProbe) Validate() errorValidate checks that p's position, radius, and SH coefficients are finite and non-negative where required. Every error wraps ErrInvalidProbe.
type LightProbeGrid struct {
Bounds math3d.AABB
Counts [3]int // probe counts along X, Y, Z (each >= 1)
Probes []IrradianceSH // flattened (iz*ny + iy)*nx + ix
}LightProbeGrid is a regular 3D axis-aligned lattice of L2 IrradianceSH light probes interpolated trilinearly at runtime.
Light probe bakes are runtime-only data generated on load or on request rather than persisted in text scene files.
func LoadLightProbeGridFS(fsys fs.FS, name string) (*LightProbeGrid, error)LoadLightProbeGridFS reads, parses, and converts a baked light probe grid YAML file from fsys into a runtime *LightProbeGrid.
func NewLightProbeGrid(bounds math3d.AABB, nx, ny, nz int) (*LightProbeGrid, error)NewLightProbeGrid allocates a zeroed nx x ny x nz LightProbeGrid covering bounds.
func (g *LightProbeGrid) At(ix, iy, iz int) IrradianceSHAt returns the IrradianceSH coefficients stored at grid cell (ix, iy, iz), clamping coordinates into range. Returns a zero IrradianceSH without panicking when g is nil, has non-positive Counts, or has fewer entries in Probes than Counts requires.
func (g *LightProbeGrid) Bake(size int, sample func(pos, dir math3d.Vec3) [3]float32) errorBake populates every probe in g by integrating sample(probePos, dir) over a cubemap of resolution size x size per probe via ComputeIrradianceSHFromFunc.
func (g *LightProbeGrid) ProbePosition(ix, iy, iz int) math3d.Vec3ProbePosition returns the world position of grid probe (ix, iy, iz), or the zero vector if g is nil.
func (g *LightProbeGrid) Sample(worldPos math3d.Vec3) IrradianceSHSample trilinearly interpolates IrradianceSH coefficients at worldPos, clamping positions outside Bounds to the boundary cell. Returns a zero IrradianceSH without panicking when g has invalid storage or worldPos is non-finite.
func (g *LightProbeGrid) Set(ix, iy, iz int, sh IrradianceSH)Set writes sh to grid cell (ix, iy, iz). Out-of-range coordinates or a grid whose Probes slice is smaller than Counts are ignored safely without panicking.
func (g *LightProbeGrid) Validate() errorValidate checks that g has finite non-empty bounds, positive counts, and len(Probes) == Counts[0]*Counts[1]*Counts[2]. Every error wraps ErrInvalidProbe.
type LightProbeGridDoc struct {
// Version is the schema version; it must be [LightProbeGridVersion] (1).
Version int `yaml:"version" schema:"required"`
// BoundsMin is the minimum [x, y, z] corner of the grid's world-space AABB.
BoundsMin ProbeVec3 `yaml:"boundsMin" schema:"required"`
// BoundsMax is the maximum [x, y, z] corner of the grid's world-space AABB.
BoundsMax ProbeVec3 `yaml:"boundsMax" schema:"required"`
// Counts holds the [nx, ny, nz] probe counts along the X, Y, and Z axes (each >= 1).
Counts ProbeCounts `yaml:"counts" schema:"required"`
// Probes holds the nx*ny*nz baked irradiance probes in (iz*ny + iy)*nx + ix order.
Probes []LightProbeSHDoc `yaml:"probes" schema:"required"`
}LightProbeGridDoc is the versioned YAML document storing a baked LightProbeGrid: its world-space axis-aligned bounds, [nx, ny, nz] lattice counts, and nx*ny*nz per-probe L2 spherical harmonic irradiance entries in (iz*ny + iy)*nx + ix order.
func LightProbeGridToDoc(g *LightProbeGrid) (*LightProbeGridDoc, error)LightProbeGridToDoc converts a validated *LightProbeGrid into a versioned *LightProbeGridDoc ready to serialize with EncodeLightProbeGrid.
func ParseLightProbeGrid(data []byte) (*LightProbeGridDoc, error)ParseLightProbeGrid strictly decodes and validates a versioned baked light probe grid YAML file, refusing unknown fields, trailing documents, invalid versions, and non-finite coefficients.
func (d *LightProbeGridDoc) ToGrid() (*LightProbeGrid, error)ToGrid converts a validated LightProbeGridDoc into a runtime *LightProbeGrid.
type LightProbeSHDoc struct {
// SH holds the 9 cosine-convolved L2 spherical harmonic RGB coefficients matching [IrradianceSH.Coeff].
SH [9]ProbeVec3 `yaml:"sh" schema:"required"`
}LightProbeSHDoc stores the 9 RGB L2 spherical harmonic irradiance coefficients of one baked light probe.
type LightProbeVolume struct {
Grid *LightProbeGrid
Probes []LightProbe
FallbackSH IrradianceSH
}LightProbeVolume combines an optional regular LightProbeGrid and/or scattered LightProbe points (plus an optional FallbackSH) so dynamic objects pick up smoothly interpolated baked indirect lighting anywhere in a scene.
Light probe volumes are runtime-only data generated on load or on request rather than persisted in text scene files.
func (v *LightProbeVolume) Add(probes ...LightProbe)Add appends scattered probes to the volume.
func (v *LightProbeVolume) SampleLightProbes(worldPos math3d.Vec3) IrradianceSHSampleLightProbes returns the interpolated IrradianceSH lighting at worldPos. Regular grid probes use trilinear interpolation; scattered probes use smooth inverse-distance weighting (respecting per-probe Radius when positive) and blend seamlessly into Grid or FallbackSH outside finite probe radii. Non-finite worldPos safely returns FallbackSH.
type LightRig struct {
Ambient AmbientLight
Directional []DirectionalLight
Point []PointLight
Spot []SpotLight
}LightRig holds the active lights for a 3D scene: an ambient fill, up to MaxDirectionalLights directional lights, up to MaxPointLights point lights, and up to MaxSpotLights spot lights, all shaded together by one pass.
func (r LightRig) AppendUniformData(dst []byte) []byteAppendUniformData appends r's lights to dst in the little-endian std140/WGSL layout of LightWGSL and returns the extended slice. It allocates only when dst lacks capacity for LightUniformSize more bytes. Call LightRig.Validate first: lights beyond MaxDirectionalLights, MaxPointLights or MaxSpotLights are omitted, and a directional or spot light with a degenerate direction writes zero radiance.
func (r LightRig) UniformDataSize() intUniformDataSize returns the byte length LightRig.AppendUniformData appends (LightUniformSize).
func (r LightRig) Validate() errorValidate checks ambient, directional, point, and spot lights and enforces MaxDirectionalLights, MaxPointLights, and MaxSpotLights. Every error wraps ErrInvalidLight.
type LightUniforms struct {
// Ambient holds premultiplied linear ambient radiance (Color * Intensity) in rgb and Intensity in w.
Ambient math3d.Vec4
DirectionalCount uint32
PointCount uint32
SpotCount uint32
Directional [MaxDirectionalLights]GPUDirectionalLight
Point [MaxPointLights]GPUPointLight
Spot [MaxSpotLights]GPUSpotLight
}LightUniforms is the fixed-size, 16-byte-aligned GPU uniform payload matching LightWGSL.
func NewLightUniforms(rig LightRig) (LightUniforms, error)NewLightUniforms validates rig and packs it into a GPU-ready LightUniforms.
func (u *LightUniforms) Encode(dst []byte) []byteEncode writes u into dst as the little-endian std140/WGSL block LightWGSL declares and returns dst[:LightUniformSize] without allocating. It panics if len(dst) < LightUniformSize, whatever dst's capacity.
type LightVisibility struct {
Directional0 float32
Point0 float32
Spot0 float32
}LightVisibility holds the shadow visibility in [0, 1] of the LightRig lights a shadow map can cover: the first directional light (DirectionalShadowMap), the first point light (PointShadowMap) and the first spot light (SpotShadowMap). 1 leaves a light unshadowed and 0 removes its contribution; the ambient term and every other light are never shadowed.
type LightmapEncoding uint8LightmapEncoding identifies how a baked lightmap texture encodes linear irradiance values.
const (
// LightmapLinear indicates the lightmap texture stores linear irradiance directly (for example in FormatRGBA16Float HDR or linear FormatRGBA8Unorm).
LightmapLinear LightmapEncoding = iota
// LightmapSRGB indicates the lightmap texture stores sRGB-encoded LDR irradiance. When uploaded as FormatRGBA8Unorm, the shader decodes sRGB to linear; when uploaded as FormatRGBA8UnormSRGB, hardware sampling already decodes to linear and the shader avoids double-decoding.
LightmapSRGB
// LightmapRGBM indicates an 8-bit linear RGBA8Unorm texture packed with a shared multiplier in alpha: linearRGB = rgb * (a * RGBMMaxRange). This allows HDR baked lightmaps in standard 8-bit PNGs across mobile and WebGL 2 backends without float textures.
LightmapRGBM
// LightmapRGBD indicates an 8-bit linear RGBA8Unorm texture packed with a shared divisor in alpha: linearRGB = rgb / max(a, 1/255), preserving full 8-bit precision for LDR values <= 1 while representing HDR highlights.
LightmapRGBD
)func ParseLightmapEncoding(s string) (LightmapEncoding, error)ParseLightmapEncoding converts an encoding string ("", "linear", "srgb", "rgbm", "rgbd"), ignoring case and surrounding white space, into a LightmapEncoding. An empty string resolves to LightmapLinear, so the Encoding of a gltf.LightmapRef can be passed straight through.
func (e LightmapEncoding) String() stringString returns a human-readable name for e.
func (e LightmapEncoding) Valid() boolValid reports whether e is a recognized LightmapEncoding.
type LightmapMaterial struct {
// BaseColor is a linear RGBA multiplier on BaseColorTexture. An all-zero value defaults to opaque white {1, 1, 1, 1}.
BaseColor [4]float32
// BaseColorTexture is an optional albedo texture sampled at UV0. When nil, a 1x1 white texture is bound.
BaseColorTexture *GPUTexture
// BaseColorSampler is an optional sampler for BaseColorTexture (defaults to linear repeat).
BaseColorSampler *GPUSampler
// Lightmap is the baked irradiance texture sampled at UV1*UVScale+UVOffset. When nil, AmbientFallback provides the baked irradiance term.
Lightmap *GPUTexture
// LightmapSampler is an optional sampler for Lightmap (defaults to linear clamp-to-edge).
LightmapSampler *GPUSampler
// Encoding specifies how Lightmap texels are decoded to linear irradiance.
Encoding LightmapEncoding
// Intensity scales decoded lightmap irradiance. Zero means zero (no baked light); [DefaultLightmapMaterial] sets 1. It does not scale AmbientFallback.
Intensity float32
// RGBMMaxRange sets the HDR peak scale for [LightmapRGBM]. Zero defaults to [DefaultRGBMMaxRange] (8.0).
RGBMMaxRange float32
// UVScale scales UV1 before sampling Lightmap (defaults to {1, 1} when {0, 0}).
UVScale [2]float32
// UVOffset offsets scaled UV1 before sampling Lightmap, allowing multiple objects to share a single baked lightmap atlas.
UVOffset [2]float32
// AmbientFallback is linear RGB irradiance used when Lightmap is nil.
AmbientFallback [3]float32
// DirectLight is an optional dynamic directional light whose Lambertian N·L diffuse term is added to the baked irradiance, so baked indirect lighting combines with a dynamic sun or key light. It uses the same [DirectionalLight] as a [LightRig]: Direction is the direction the light travels, so a light from a scene's rig can be passed as is. Nil disables direct lighting.
DirectLight *DirectionalLight
}LightmapMaterial configures albedo, baked lightmap sampling, encoding, atlas UV sub-rectangle transform, fallback ambient irradiance, and optional additive direct light for LightmapRenderer.Draw.
func DefaultLightmapMaterial() LightmapMaterialDefaultLightmapMaterial returns a LightmapMaterial with opaque white base color, LightmapLinear encoding, unit intensity, default RGBM range, and identity atlas UV scale/offset.
func (m *LightmapMaterial) SetUVTransform(t UVTransform)SetUVTransform assigns t.Scale and t.Offset onto m.
func (m LightmapMaterial) UVTransform() UVTransformUVTransform returns m's atlas lightmap UVTransform.
func (m LightmapMaterial) Validate() errorValidate checks that m's numeric fields, encoding, and non-nil GPU handles are valid. Every error wraps ErrInvalidLightmap.
type LightmapMesh struct {
Positions []math3d.Vec3
Normals []math3d.Vec3
UV0 []math3d.Vec2
UV1 []math3d.Vec2
Indices []uint32
}LightmapMesh is triangle-list geometry carrying two UV sets: UV0 for tiled material maps (matching glTF TEXCOORD_0) and UV1 for baked lightmaps (matching glTF TEXCOORD_1).
Positions is required. Normals, UV0, and UV1 are optional: each is either empty or holds one entry per position. When UV1 is empty, UploadLightmapMesh and LightmapMesh.AppendVertexData fall back cleanly to UV0 (or zeros if UV0 is also empty). A glTF primitive's Positions, Normals, TexCoords0, TexCoords1, and Indices fields map directly onto LightmapMesh.
func LightmapMeshFromAttributes(positions, normals []math3d.Vec3, uv0, uv1 []math3d.Vec2, indices []uint32) LightmapMeshLightmapMeshFromAttributes constructs a LightmapMesh from separate attribute slices (such as a glTF primitive's Positions, Normals, TexCoords0, TexCoords1, and Indices). When uv1 is empty, UV1 falls back cleanly to uv0 during upload.
func LightmapMeshFromGLTF(doc *gltf.Document, prim gltf.Primitive) (LightmapMesh, error)LightmapMeshFromGLTF builds a 40-byte dual-UV LightmapMesh from a glTF primitive, extracting the material's lightmap UV channel (TEXCOORD_1 or explicit texCoord from MOZ_lightmap / EXT_lightmap / extras.lightmap, falling back cleanly to TEXCOORD_0 when TEXCOORD_1 is absent).
func LightmapMeshFromVertices(vertices []LightmapVertex, indices []uint32) LightmapMeshLightmapMeshFromVertices converts interleaved LightmapVertex values and optional indices into a LightmapMesh.
func (m LightmapMesh) AppendIndexData(dst []byte) []byteAppendIndexData appends m's indices to dst at LightmapMesh.IndexFormat width, little-endian and zero-padded to a 4-byte multiple.
func (m LightmapMesh) AppendVertexData(dst []byte) []byteAppendVertexData appends m's vertices to dst in the little-endian 40-byte interleaved layout of LightmapVertexLayout and returns the extended slice. Missing normals are written as zeros; missing UV1 falls back cleanly to UV0 (or zeros if UV0 is also absent). Call LightmapMesh.Validate first.
func (m LightmapMesh) Bounds() math3d.AABBBounds returns the object-space AABB enclosing m.Positions.
func (m LightmapMesh) HasUV1() boolHasUV1 reports whether m provides a dedicated secondary UV1 channel rather than falling back to UV0.
func (m LightmapMesh) IndexDataSize() intIndexDataSize returns the byte length LightmapMesh.AppendIndexData appends, padded to a multiple of four bytes as WebGPU requires.
func (m LightmapMesh) IndexFormat() gpu.IndexFormatIndexFormat returns gpu.IndexUint16 while all vertex indices fit below 0xFFFF (WebGL 2 primitive restart), otherwise gpu.IndexUint32.
func (m LightmapMesh) Indexed() boolIndexed reports whether m has an index list.
func (m LightmapMesh) Validate() errorValidate reports whether m can be uploaded: at least one whole triangle, optional attributes empty or matching len(Positions) with finite values, and every index in range. Every error wraps ErrInvalidMesh.
func (m LightmapMesh) VertexCount() intVertexCount returns the number of vertices, len(m.Positions).
func (m LightmapMesh) VertexDataSize() intVertexDataSize returns the byte length LightmapMesh.AppendVertexData appends.
func (m LightmapMesh) Vertices() []LightmapVertexVertices materializes m as a slice of interleaved LightmapVertex values, falling back from empty UV1 to UV0.
type LightmapRenderer struct {
// contains filtered or unexported fields
}LightmapRenderer draws GPULightmapMesh geometry shaded with baked lightmaps (sampling albedo at UV0 and baked irradiance at UV1 * UVScale + UVOffset), supporting linear/HDR RGBA16F, sRGB LDR, RGBM, and RGBD lightmaps as well as optional additive dynamic directional lighting.
It is a standalone path: the shading is albedo times (baked irradiance plus one Lambertian DirectionalLight), with no metallic-roughness, normal, occlusion or emissive maps and no LightRig. Feeding lightmaps into the PBR material path as its indirect term is tracked in https://github.com/nsgo-dev/game/issues/752.
Call LightmapRenderer.BeginFrame at the start of each frame to reuse the dynamic uniform buffer without steady-state allocations.
func NewLightmapRenderer(cx *core.Scope, dev *gpu.Device, camLayout *gpu.BindGroupLayout, opts LightmapRendererOptions) (*LightmapRenderer, error)NewLightmapRenderer compiles LightmapWGSL and creates the pipeline, fallback 1x1 white texture, default samplers, and dynamic per-draw uniform ring buffer on dev, owned by cx.
func (r *LightmapRenderer) BeginFrame()BeginFrame resets the per-frame dynamic uniform ring offset, releases any older uniform buffers retired when the ring grew in a previous frame, and drops cached texture bind groups whose textures or samplers have since been closed, so streaming or hot-reloading lightmaps does not grow the cache.
func (r *LightmapRenderer) Close() errorClose releases all GPU resources created by r. It is safe to call more than once.
func (r *LightmapRenderer) Draw(pass *gpu.RenderPass, cam *CameraBuffer, mesh *GPULightmapMesh, model math3d.Mat4, mat LightmapMaterial) errorDraw encodes the model transform and mat into a dynamic uniform slot, binds camera, per-draw uniforms, and albedo/lightmap textures on pass, and draws mesh. Multiple objects with different transforms, materials, or shared atlas UV sub-rectangles may be drawn within the same render pass.
func (r *LightmapRenderer) Pipeline() *gpu.PipelinePipeline returns the compiled lightmap gpu.Pipeline.
func (r *LightmapRenderer) Valid() boolValid reports whether r is open and its GPU resources belong to a live device.
type LightmapRendererOptions struct {
// ColorFormat overrides the color target format (defaults to dev.SurfaceFormat(), or [gpu.FormatRGBA8Unorm] if undefined).
ColorFormat gpu.TextureFormat
// DepthFormat overrides the depth target format when DisableDepth is false (defaults to [gpu.FormatDepth24Plus]).
DepthFormat gpu.TextureFormat
// DisableDepth creates the pipeline without a depth-stencil attachment.
DisableDepth bool
// DoubleSided disables back-face culling (uses [gpu.CullNone]).
DoubleSided bool
// Retained keeps internal GPU resources across device loss.
Retained bool
// InitialCapacity sets the initial per-frame dynamic uniform slot count (defaults to 64).
InitialCapacity int
// Label prefixes GPU resource debug labels.
Label string
}LightmapRendererOptions configures NewLightmapRenderer. The zero value enables depth testing (gpu.FormatDepth24Plus), back-face culling (gpu.CullBack with gpu.FrontCCW), and targets the device surface format.
type LightmapVertex struct {
Position [3]float32
Normal [3]float32
UV0 [2]float32
UV1 [2]float32
}LightmapVertex is one interleaved vertex for lightmapped 3D geometry carrying both primary (albedo) UV0 and secondary (baked lightmap) UV1 coordinates.
type LitPBRPipelineOptions struct {
// Label names the pipeline in GPU capture tools; empty picks render3d.lit_pbr, lit_pbr_fog, lit_pbr_ibl, lit_pbr_shadow, lit_pbr_spot_shadow or lit_pbr_point_shadow with a .linear suffix for LinearOutput.
Label string
// ColorFormat sets the color attachment format; [gpu.FormatUndefined] defaults to dev.SurfaceFormat(). Use [HDRTarget.Format] when drawing into an [HDRTarget].
ColorFormat gpu.TextureFormat
// DepthFormat enables depth testing and writes when not [gpu.FormatUndefined].
DepthFormat gpu.TextureFormat
// FogLayout, when set, compiles [LitPBRFogWGSL] with this layout ([GPUFogBuffer.Layout]) at [FogGroup], as [NewLitPBRFogPipeline] does.
FogLayout *gpu.BindGroupLayout
// IBLLayout, when set, compiles [LitPBRIBLWGSL] with this layout ([GPUIBLBuffer.Layout]) at [IBLGroup], as [NewLitPBRIBLPipeline] does. Fog and IBL share bind group 3, so setting both is an error.
IBLLayout *gpu.BindGroupLayout
// SkinLayout, when set, compiles [LitPBRSkinnedWGSL] with this layout ([GPUSkinPalette.Layout]) at [LitPBRSkinGroup] and takes [SkinnedVertexLayout] vertices, so a [GPUSkinnedMesh] is drawn with scene lights. The vertex stage skins each vertex with the palette and then applies the per-draw model and normal matrices: use an identity model with [SkinJointMatrices] (world-space joints), or the mesh node's world matrix with mesh-local joints such as anim3d's Player.SkinMatricesForNode. Fog, IBL and skinning all use bind group 3, so SkinLayout cannot be combined with FogLayout or IBLLayout.
SkinLayout *gpu.BindGroupLayout
// ShadowLayout, when set, compiles [LitPBRShadowWGSL] with this layout ([DirectionalShadowMap.Layout]) at [ShadowGroup], as [NewLitPBRShadowPipeline] does, so the first directional light is attenuated by the shadow map. The shadow uses bind group 3 like fog, IBL and skinning, so ShadowLayout cannot be combined with FogLayout, IBLLayout or SkinLayout.
ShadowLayout *gpu.BindGroupLayout
// SpotShadowLayout, when set, compiles [LitPBRSpotShadowWGSL] with this layout ([SpotShadowMap.Layout]) at [LocalShadowGroup], as [NewLitPBRSpotShadowPipeline] does, so the first spot light of the [LightRig] is attenuated by the spot shadow map. It uses bind group 3 like the directional shadow, fog, IBL and skinning, so it cannot be combined with any of them.
SpotShadowLayout *gpu.BindGroupLayout
// PointShadowLayout, when set, compiles [LitPBRPointShadowWGSL] with this layout ([PointShadowMap.Layout]) at [LocalShadowGroup], as [NewLitPBRPointShadowPipeline] does, so the first point light of the [LightRig] is attenuated by the point shadow atlas. It uses bind group 3 like the directional shadow, fog, IBL and skinning, so it cannot be combined with any of them.
PointShadowLayout *gpu.BindGroupLayout
// CSMLayout, when set, compiles [LitPBRCSMWGSL] with this layout ([CascadedShadowMap.Layout]) at [CSMGroup], as [NewLitPBRCSMPipeline] does, so the first directional light of the [LightRig] is attenuated by the cascaded shadow map. It uses bind group 3 like the single directional shadow, spot and point shadows, fog, IBL and skinning, so it cannot be combined with any of them.
CSMLayout *gpu.BindGroupLayout
// VertexColors selects [ColoredVertexLayout] (stride 48 bytes, @location(3) linear RGBA color for glTF COLOR_0) and multiplies pbr_draw.base_color (both RGB and alpha) by the linear vertex color before shading (and before IBL evaluation when IBLLayout is set), so a [GPUColoredMesh] can be drawn with scene lights. Cannot be combined with SkinLayout because [SkinnedVertexLayout] has no vertex color attribute.
VertexColors bool
// LinearOutput skips the final linear-to-sRGB encoding and its clamp to [0, 1] and writes the lit linear radiance ([ShadePoint], plus [EvaluateIBL] or [Fog.Apply] when enabled), for drawing into an [HDRTarget] that a [ToneMapPass] then resolves to the display.
LinearOutput bool
}LitPBRPipelineOptions configures NewLitPBRPipelineWithOptions.
type LocalShadowFilter uint8LocalShadowFilter selects how a local shadow map samples its depth texture.
const (
// LocalShadowFilterHard performs a single nearest-neighbor depth comparison tap.
LocalShadowFilterHard LocalShadowFilter = iota
// LocalShadowFilterPCF3x3 performs a 3x3 percentage-closer filter using linear comparison taps clamped inside the shadow map or cube face tile.
LocalShadowFilterPCF3x3
)func (f LocalShadowFilter) String() stringString returns the canonical filter name.
type MSAATarget struct {
// contains filtered or unexported fields
}MSAATarget manages an offscreen 3D color (and optional depth) render target with automatic MSAA resolve and resize support (#249).
When created with SampleCount > 1 on a device supporting Features.MSAA4x, the color attachment is multisampled and MSAATarget.ColorAttachment binds the single-sampled resolve texture as ResolveTarget (with StoreDiscard on the transient multisample buffer). When SampleCount clamps to 1, ColorAttachment targets the single-sampled color texture directly with StoreStore. In both cases, MSAATarget.OutputTexture returns the single-sampled texture ready for sampling in subsequent passes (such as FXAAPass or tone mapping) or CPU readback.
func NewMSAATarget(cx *core.Scope, dev *gpu.Device, desc MSAATargetDesc) (*MSAATarget, error)NewMSAATarget allocates an MSAATarget on dev scoped to cx. It clamps desc.SampleCount via ClampSampleCount so callers do not need separate error-handling paths for devices without MSAA4x.
func (t *MSAATarget) Close() errorClose releases the underlying GPU textures immediately instead of waiting for scope disposal. It is safe to call more than once or on a nil target.
func (t *MSAATarget) ColorAttachment(clearColor core.Color) (gpu.ColorAttachment, error)ColorAttachment returns a gpu.ColorAttachment configured to clear the target to clearColor and, when multisampled, automatically resolve into the single-sampled resolve texture at pass end (discarding the transient multisampled backing store). For a single-sampled target it stores directly into the color texture.
It returns an error when the target is nil, closed, or its device is lost, instead of an attachment with a nil Texture, which NSGo would draw into the view's swapchain.
func (t *MSAATarget) ColorFormat() gpu.TextureFormatColorFormat returns the resolved color attachment format.
func (t *MSAATarget) ColorTexture() *gpu.TextureColorTexture returns the primary color attachment texture (multisampled when SampleCount > 1), or nil if closed.
func (t *MSAATarget) DepthFormat() gpu.TextureFormatDepthFormat returns the configured depth/stencil format (FormatUndefined if none).
func (t *MSAATarget) DepthStencilAttachment(clearDepth float32) *gpu.DepthStencilAttachmentDepthStencilAttachment returns a gpu.DepthStencilAttachment clearing the target's depth buffer to clearDepth (and its stencil to 0 when the depth format has a stencil aspect), or nil when no depth format was configured or the target is closed. The depth and stencil are discarded at the end of the pass unless MSAATargetDesc.KeepDepth is set.
func (t *MSAATarget) DepthTexture() *gpu.TextureDepthTexture returns the depth/stencil texture, or nil when none was configured or the target is closed. Its contents survive a pass only when MSAATargetDesc.KeepDepth is set.
func (t *MSAATarget) Height() uint32Height returns the target's height in physical pixels.
func (t *MSAATarget) OutputTexture() *gpu.TextureOutputTexture returns the single-sampled color texture holding the resolved render output: Resolve when multisampled, Color when single-sampled, or nil if the target is nil or closed.
func (t *MSAATarget) RenderPassDesc(clearColor core.Color, clearDepth float32) (gpu.RenderPassDesc, error)RenderPassDesc builds a gpu.RenderPassDesc targeting t with MSAATarget.ColorAttachment and (if present) MSAATarget.DepthStencilAttachment. Like ColorAttachment, it returns an error for a nil, closed, or lost target.
func (t *MSAATarget) RenderTarget() *gpu.RenderTargetRenderTarget returns the underlying *gpu.RenderTarget, or nil if closed.
func (t *MSAATarget) Resize(width, height uint32) errorResize reallocates the underlying textures to width x height. If the target is already valid at that exact size and its sample count, clamped against the current device, is unchanged, Resize is a zero-allocation no-op. If allocation fails, the existing textures remain intact and the error is returned.
func (t *MSAATarget) ResolveTexture() *gpu.TextureResolveTexture returns the single-sampled resolve texture, or nil when the target is single-sampled or closed.
func (t *MSAATarget) Retained() boolRetained reports whether the target's textures were created with automatic recreation across device loss enabled.
func (t *MSAATarget) SampleCount() intSampleCount returns the effective (clamped) MSAA sample count (1 or 4), or 0 for a nil target.
func (t *MSAATarget) SetDevice(dev *gpu.Device)SetDevice updates the device used by future MSAATarget.Resize calls after NSGo restores a lost device onto a new *gpu.Device for a retained target.
The sample count is clamped against the new device on the next Resize, which reallocates the textures even at the same size when the clamped count changes (for example 4x on a device without Features.MSAA4x becomes 1x, and a target created at 1x on such a device becomes 4x on one that has it). Compare MSAATarget.SampleCount before and after, and rebuild pipelines created with the old count.
func (t *MSAATarget) Valid() boolValid reports whether the target's underlying GPU textures are open and belong to a live device.
func (t *MSAATarget) Width() uint32Width returns the target's width in physical pixels.
type MSAATargetDesc struct {
// Label names the underlying GPU textures in capture tools.
Label string
// Width and Height are the initial dimensions in physical pixels (both > 0).
Width uint32
Height uint32
// ColorFormat is the color attachment format. FormatUndefined defaults to dev.SurfaceFormat(), or FormatRGBA8Unorm if that is undefined.
ColorFormat gpu.TextureFormat
// DepthFormat is an optional depth/stencil format (e.g. FormatDepth24Plus); FormatUndefined disables the depth attachment.
DepthFormat gpu.TextureFormat
// SampleCount is the requested MSAA sample count (e.g. AAMSAA4x.SampleCount()). It is clamped to a device-supported count via [ClampSampleCount].
SampleCount int
// KeepDepth stores the depth (and stencil) attachment at the end of each pass so later passes can read [MSAATarget.DepthTexture]. By default the depth buffer is transient: it is cleared at the start of the pass and discarded at the end. A kept depth texture of a 4x target is multisampled.
KeepDepth bool
// Retained opts the color, resolve, and depth textures into automatic recreation by NSGo after a device loss.
Retained bool
}MSAATargetDesc configures NewMSAATarget.
type Material struct {
BaseColorFactor [4]float32
BaseColorTexture *GPUTexture
BaseColorSampler *GPUSampler
MetallicFactor float32
RoughnessFactor float32
MetallicRoughnessTexture *GPUTexture
MetallicRoughnessSampler *GPUSampler
NormalTexture *GPUTexture
NormalSampler *GPUSampler
NormalScale float32
OcclusionTexture *GPUTexture
OcclusionSampler *GPUSampler
OcclusionStrength float32
EmissiveFactor [3]float32
EmissiveTexture *GPUTexture
EmissiveSampler *GPUSampler
ClearcoatFactor float32
ClearcoatRoughnessFactor float32
ClearcoatTexture *GPUTexture
ClearcoatSampler *GPUSampler
ClearcoatRoughnessTexture *GPUTexture
ClearcoatRoughnessSampler *GPUSampler
ClearcoatNormalTexture *GPUTexture
ClearcoatNormalSampler *GPUSampler
ClearcoatNormalScale float32
TransmissionFactor float32
TransmissionTexture *GPUTexture
TransmissionSampler *GPUSampler
IOR float32
AlphaMode AlphaMode
AlphaCutoff float32
DoubleSided bool
}Material describes a glTF 2.0 metallic-roughness PBR surface ready to bind on a gpu.Device through NewGPUMaterial or evaluate on the CPU through EvaluateMaterial.
Start from DefaultMaterial for glTF 2.0 specification defaults (white base color, metallic 1, roughness 1, normal scale 1, occlusion strength 1, alpha cutoff 0.5). Any omitted texture or sampler falls back to the 1x1 neutral defaults in MaterialDefaults so every material shares one bind group layout (MaterialGroup) with zero pipeline permutations.
Texture channel conventions match glTF 2.0:
- BaseColorTexture: sRGB RGBA8 color + linear alpha, multiplied by BaseColorFactor (linear RGBA).
- MetallicRoughnessTexture: linear RGBA8 where G = roughness and B = metallic, multiplied by RoughnessFactor and MetallicFactor.
- NormalTexture: linear RGBA8 tangent-space normal map (+X right/+U, +Y up/-V, +Z outward), with XY scaled by NormalScale (a negative scale flips both, as glTF 2.0 allows).
- OcclusionTexture: linear R (or RGBA8) ambient occlusion factor blended by OcclusionStrength.
- EmissiveTexture: sRGB RGBA8 self-emission multiplied by EmissiveFactor (linear RGB).
func DefaultMaterial() MaterialDefaultMaterial returns a Material populated with glTF 2.0 default factors: linear white base color [1, 1, 1, 1], metallic 1.0, roughness 1.0, normal scale 1.0, occlusion strength 1.0, emissive [0, 0, 0], clearcoat normal scale 1.0, IOR 1.5, AlphaOpaque, and alpha cutoff 0.5.
func (m Material) AppendUniformData(dst []byte) []byteAppendUniformData appends m's 64-byte little-endian uniform block to dst without allocating when dst has at least MaterialUniformSize bytes of spare capacity.
func (m Material) EffectiveIOR() float32EffectiveIOR returns m.IOR, defaulting to DefaultMaterialIOR (1.5) when m.IOR is zero.
func (m Material) ExtendedUniforms() ExtendedMaterialUniformsExtendedUniforms packs m's scalar parameters and texture-presence flags (including KHR_materials_clearcoat, KHR_materials_transmission, and IOR) into ExtendedMaterialUniforms.
func (m Material) Uniforms() MaterialUniformsUniforms packs m's scalar parameters and texture-presence flags into MaterialUniforms.
func (m Material) UsesExtensions() boolUsesExtensions reports whether m sets any KHR_materials_clearcoat, KHR_materials_transmission, or non-default IOR parameters that require GPUExtendedMaterial / NewExtendedMaterialPipeline.
func (m Material) Validate() errorValidate checks that every numeric factor is finite and within its valid glTF 2.0 range, that AlphaMode is recognized, and that every non-nil GPU texture or sampler handle is currently GPUTexture.Valid / GPUSampler.Valid. Every error wraps ErrInvalidMaterial.
type MaterialDefaults struct {
// contains filtered or unexported fields
}MaterialDefaults owns the shared 1x1 fallback textures, default linear-repeat sampler, and MaterialGroup bind group layouts used by NewGPUMaterial and NewGPUUnlitMaterial whenever a material omits optional maps or samplers. Create one per gpu.Device and share it across all materials on that device.
func NewMaterialDefaults(cx *core.Scope, dev *gpu.Device, opts MaterialDefaultsOptions) (*MaterialDefaults, error)NewMaterialDefaults allocates the shared MaterialGroup layouts (metallic-roughness and unlit), default linear-repeat sampler, and four 1x1 fallback textures on dev, owned by cx:
- WhiteSRGB: (255, 255, 255, 255) RGBA8 sRGB for missing base color maps.
- WhiteLinear: (255, 255, 255, 255) RGBA8 unorm for missing metallic-roughness and occlusion maps.
- FlatNormal: (128, 128, 255, 255) RGBA8 unorm for missing tangent-space normal maps.
- Black: (0, 0, 0, 255) RGBA8 sRGB for missing emissive maps.
func (d *MaterialDefaults) Black() *GPUTextureBlack returns the 1x1 sRGB black fallback texture (0, 0, 0, 255).
func (d *MaterialDefaults) ByteSize() uint64ByteSize returns the total GPU memory held by the four 1x1 fallback textures.
func (d *MaterialDefaults) Close() errorClose releases the fallback textures, sampler, and bind group layouts now rather than waiting for scope disposal. Safe to call on nil or more than once.
func (d *MaterialDefaults) FlatNormal() *GPUTextureFlatNormal returns the 1x1 linear tangent-space flat normal fallback texture (128, 128, 255, 255).
func (d *MaterialDefaults) Layout() *gpu.BindGroupLayoutLayout returns the MaterialGroup bind group layout shared by every material created with d.
func (d *MaterialDefaults) Sampler() *GPUSamplerSampler returns the default linear-repeat sampler used when a material slot omits a sampler.
func (d *MaterialDefaults) UnlitLayout() *gpu.BindGroupLayoutUnlitLayout returns the MaterialGroup bind group layout shared by every GPUUnlitMaterial created with d, for NewUnlitPipeline.
MaterialDefaults.Valid does not cover it: NSGo restores a bind group layout after a device loss only when a restored bind group uses it, so this layout comes back only while a retained GPUUnlitMaterial exists (nsgo-dev/nsgo#2338). Check its Valid method before building an unlit pipeline after a restore.
func (d *MaterialDefaults) Valid() boolValid reports whether all fallback resources and the metallic-roughness bind group layout are open on a live device.
func (d *MaterialDefaults) WhiteLinear() *GPUTextureWhiteLinear returns the 1x1 linear white fallback texture (255, 255, 255, 255).
func (d *MaterialDefaults) WhiteSRGB() *GPUTextureWhiteSRGB returns the 1x1 sRGB white fallback texture (255, 255, 255, 255).
type MaterialDefaultsOptions struct {
// Label prefixes the debug labels of the fallback textures, sampler, and bind group layout.
Label string
// Retained keeps CPU shadow copies of the fallback textures and sampler so retained [GPUMaterial] instances recover automatically after a GPU device loss.
Retained bool
}MaterialDefaultsOptions configures NewMaterialDefaults.
type MaterialEvalInput struct {
Material Material
BaseColorSample [4]float32
HasBaseColorSample bool
VertexColor [4]float32 // linear RGBA vertex color (glTF COLOR_0); defaults to [1, 1, 1, 1] when HasVertexColor is false
HasVertexColor bool
MetallicSample float32 // glTF metallic-roughness texture B channel
RoughnessSample float32 // glTF metallic-roughness texture G channel
HasMetallicRoughnessSample bool
NormalSample [3]float32 // UNORM [0, 1] tangent-space normal sample
HasNormalSample bool
OcclusionSample float32 // glTF occlusion texture R channel
HasOcclusionSample bool
EmissiveSample [3]float32 // linear RGB emissive texture sample
HasEmissiveSample bool
ClearcoatSample float32 // glTF clearcoatTexture R channel
HasClearcoatSample bool
ClearcoatRoughnessSample float32 // glTF clearcoatRoughnessTexture G channel
HasClearcoatRoughnessSample bool
ClearcoatNormalSample [3]float32 // UNORM [0, 1] tangent-space clearcoat normal sample
HasClearcoatNormalSample bool
TransmissionSample float32 // glTF transmissionTexture R channel
HasTransmissionSample bool
BackgroundColor [3]float32 // linear RGB opaque scene background sampled behind a transmissive surface
Normal math3d.Vec3 // geometric world-space normal
Tangent math3d.Vec3 // optional world-space tangent (+U); derived from Normal when zero
Bitangent math3d.Vec3 // optional world-space bitangent (+Y normal map / -V); derived from Normal x Tangent when zero
ViewDir math3d.Vec3 // vector from surface toward camera
FrontFacing bool // true for front-facing fragments; flips Normal when false and Material.DoubleSided is true
Light MaterialLight // zero value uses [DefaultMaterialLight]
}MaterialEvalInput provides per-fragment inputs to EvaluateMaterial, the pure-Go CPU reference evaluator matching MaterialWGSL.
type MaterialEvalResult struct {
Linear math3d.Vec4 // linear RGBA radiance before tone mapping and sRGB encoding
SRGB math3d.Vec4 // Reinhard tone-mapped and sRGB-encoded RGBA matching [MaterialWGSL]
Normal math3d.Vec3 // final world-space shading normal after normal mapping
Metallic float32 // effective clamped metallic in [0, 1]
Roughness float32 // effective clamped roughness in [0.045, 1]
Discarded bool // true when AlphaMode == AlphaMask and effective alpha < AlphaCutoff
}MaterialEvalResult holds the CPU reference shading output produced by EvaluateMaterial.
func EvaluateMaterial(in MaterialEvalInput) MaterialEvalResultEvaluateMaterial evaluates the glTF 2.0 metallic-roughness Cook-Torrance GGX shading model on the CPU, matching MaterialWGSL (and MaterialColoredWGSL when MaterialEvalInput.HasVertexColor is set) so tests and tools can verify GPU renders against an exact pure-Go reference.
func EvaluateMaterialIBL(in MaterialEvalInput, sh IrradianceSH, prefilter *HDRCubemap, intensity float32) MaterialEvalResultEvaluateMaterialIBL evaluates the exact pure-Go CPU reference matching MaterialIBLWGSL (and MaterialIBLLinearWGSL via MaterialEvalResult.Linear): glTF 2.0 metallic-roughness texture factors, tangent-space normal perturbation, occlusion, emissive, and split-sum HDR image-based lighting via EvaluateIBLHDR.
type MaterialIBLPipelineOptions struct {
// Label names the pipeline in GPU capture tools.
Label string
// ColorFormat sets the color attachment format; [gpu.FormatUndefined] defaults to dev.SurfaceFormat(). Use [HDRTarget.Format] with LinearOutput: true when rendering into an [HDRTarget].
ColorFormat gpu.TextureFormat
// DepthFormat enables depth testing (and depth writes for opaque/alpha-mask modes) when non-zero.
DepthFormat gpu.TextureFormat
// AlphaMode selects blending and depth-write state: AlphaOpaque and AlphaMask write depth without color blending; AlphaBlend uses straight alpha blending ([gpu.BlendAlpha]) with depth writes disabled.
AlphaMode AlphaMode
// DoubleSided disables backface culling ([gpu.CullNone]); when false, back faces are culled ([gpu.CullBack]).
DoubleSided bool
// SampleCount sets the MSAA sample count (0 or 1 for non-MSAA, 4 for 4x MSAA).
SampleCount int
// LinearOutput compiles [MaterialIBLLinearWGSL] instead of [MaterialIBLWGSL], emitting unclamped linear HDR radiance for an [HDRTarget] resolved by [ToneMapPass].
LinearOutput bool
// Retained opts the pipeline into automatic recreation after a GPU device loss.
Retained bool
}MaterialIBLPipelineOptions configures NewMaterialIBLPipeline.
type MaterialLight struct {
Direction math3d.Vec3
Color math3d.Vec3
SkyColor math3d.Vec3
GroundColor math3d.Vec3
}MaterialLight defines the directional key light and hemisphere ambient environment shared by MaterialWGSL and EvaluateMaterial.
func DefaultMaterialLight() MaterialLightDefaultMaterialLight returns the directional key light and hemisphere ambient colors built into MaterialWGSL.
type MaterialPipelineOptions struct {
// Label names the pipeline in GPU capture tools.
Label string
// ColorFormat sets the color attachment format; [gpu.FormatUndefined] defaults to dev.SurfaceFormat().
ColorFormat gpu.TextureFormat
// DepthFormat enables depth testing (and depth writes for opaque/alpha-mask modes) when non-zero.
DepthFormat gpu.TextureFormat
// AlphaMode selects blending and depth-write state: AlphaOpaque and AlphaMask write depth without color blending; AlphaBlend uses straight alpha blending ([gpu.BlendAlpha]) with depth writes disabled.
AlphaMode AlphaMode
// DoubleSided disables backface culling ([gpu.CullNone]); when false, back faces are culled ([gpu.CullBack]).
DoubleSided bool
// FogLayout, when set, compiles [MaterialFogWGSL] instead of [MaterialWGSL] and lists this layout ([GPUFogBuffer.Layout]) at [MaterialFogGroup]; bind [GPUFogBuffer.BindGroup] there when drawing.
FogLayout *gpu.BindGroupLayout
// SkinLayout, when set, compiles [MaterialSkinnedWGSL] with this layout ([GPUSkinPalette.Layout]) at [MaterialSkinGroup] and takes [SkinnedVertexLayout] vertices, so a [GPUSkinnedMesh] is drawn with a textured [GPUMaterial]. Material shaders have no model matrix, so the palette must hold world-space joints: [SkinJointMatrices], or mesh-local joints uploaded with [GPUSkinPalette.UpdateWithTransform]. Fog and skinning both use bind group 2, so SkinLayout cannot be combined with FogLayout.
SkinLayout *gpu.BindGroupLayout
// VertexColors selects [ColoredVertexLayout] (stride 48 bytes, @location(3) linear RGBA color for glTF COLOR_0) and compiles [MaterialColoredWGSL] (or its fog / linear-output variant) so a [GPUColoredMesh] can be drawn with metallic-roughness materials. The fragment shader multiplies base_color (base_color_factor * base_sample) by the linear vertex color (RGB and alpha, per glTF 2.0 §3.7.2.1) before AlphaMask cutoff and PBR shading. Cannot be combined with SkinLayout because [SkinnedVertexLayout] has no vertex color attribute.
VertexColors bool
// LinearOutput skips the shader's built-in Reinhard tone mapping and gamma encoding and writes the unclamped linear radiance ([MaterialEvalResult].Linear), for drawing into an [HDRTarget] that a [ToneMapPass] then resolves to the display. Set ColorFormat to [HDRTarget.Format] with it.
LinearOutput bool
}MaterialPipelineOptions configures NewMaterialPipeline.
type MaterialUniforms struct {
BaseColorFactor [4]float32
EmissiveFactor [3]float32
NormalScale float32
MetallicFactor float32
RoughnessFactor float32
OcclusionStrength float32
AlphaCutoff float32
AlphaMode AlphaMode
DoubleSided bool
HasNormalMap bool
HasEmissiveMap bool
}MaterialUniforms holds the 64-byte uniform payload encoded for struct MaterialUniforms in MaterialBindingsWGSL.
func (u MaterialUniforms) AppendUniformData(dst []byte) []byteAppendUniformData appends u's 64-byte little-endian uniform block to dst and returns the extended slice. It allocates only when dst lacks capacity for MaterialUniformSize additional bytes.
func (u *MaterialUniforms) Encode(dst []byte) []byteEncode writes u into dst[:MaterialUniformSize] in the 16-byte-aligned little-endian layout declared by MaterialBindingsWGSL. It panics if len(dst) < MaterialUniformSize.
type MaterialUpload struct {
// Label names the uniform buffer and bind group in GPU capture tools.
Label string
// Retained keeps a CPU shadow copy of the uniform buffer so NSGo restores it (and its bind group, when the defaults and any bound textures/samplers are also retained) across a GPU device loss.
Retained bool
}MaterialUpload configures NewGPUMaterial.
type Mesh struct {
Positions []math3d.Vec3
Normals []math3d.Vec3
UVs []math3d.Vec2
Indices []uint32
}Mesh is indexed or non-indexed triangle-list geometry kept on the CPU, ready to upload to the GPU view's buffers with UploadMesh.
Positions is required. Normals and UVs are optional: each is either empty or holds one entry per position. Indices is optional: when empty, every three consecutive positions form a triangle; otherwise every three indices do, and each index must be less than len(Positions). Triangles are counter-clockwise when front-facing, matching glTF and math3d. A glTF triangle primitive maps directly: Positions, Normals, TexCoords0 and Indices of github.com/nsgo-dev/game/pkg/gltf.Primitive have these types.
func MeshFromTerrainMesh(tm world3d.TerrainMesh) MeshMeshFromTerrainMesh converts a CPU world3d.TerrainMesh into a Mesh ready for UploadMesh and rendering with GPUTerrainMaterial.
func SmoothOutlineNormals(m Mesh) (Mesh, error)SmoothOutlineNormals returns a copy of m whose normals are averaged across vertices at the same position, so that the inverted-hull outline of a hard-edged mesh such as a box or a low-poly prop stays closed at its corners instead of splitting apart. Two vertices share a position when every coordinate rounds to the same multiple of 1e-5; positions that differ by less than that but round apart are kept separate, so split vertices should carry identical positions, as exporters write them. Each triangle adds the normal of each of its corners weighted by the corner's angle: the vertex normal when m has normals, the face normal otherwise. Triangulation therefore does not change the result, and every face meeting at a position counts by the angle it spans there. Positions, UVs, and Indices are copied without mutating m. It returns an error wrapping ErrInvalidMesh when m fails Mesh.Validate or a coordinate's magnitude exceeds 1e12.
func (m Mesh) AppendIndexData(dst []byte) []byteAppendIndexData appends m's indices to dst at Mesh.IndexFormat width, little-endian and zero-padded to Mesh.IndexDataSize, and returns the extended slice. It appends nothing for a non-indexed mesh and allocates only when dst lacks capacity. It does not validate m: call Mesh.Validate first, because for a mesh that fails it the bytes written are unspecified (an out-of-range index is truncated to the index width, for example).
func (m Mesh) AppendVertexData(dst []byte) []byteAppendVertexData appends m's vertices to dst in the little-endian interleaved layout of MeshVertexLayout and returns the extended slice. Missing normals and UVs are written as zeros. It allocates only when dst lacks capacity for Mesh.VertexDataSize more bytes. It does not validate m: call Mesh.Validate first, because for a mesh that fails it the bytes written are unspecified (normals or UVs whose count does not match the positions, for example, are written as zeros).
func (m Mesh) Bounds() math3d.AABBBounds returns the axis-aligned box around m's positions, or math3d.AABBEmpty when m has none.
func (m Mesh) IndexDataSize() intIndexDataSize returns the byte length Mesh.AppendIndexData appends: the indices at Mesh.IndexFormat width, padded with zeros to a multiple of four bytes as WebGPU requires for buffer sizes. It is zero for a non-indexed mesh.
func (m Mesh) IndexFormat() gpu.IndexFormatIndexFormat returns the index width Mesh.AppendIndexData writes: gpu.IndexUint16 when every vertex fits below 0xFFFF (kept free because WebGL 2 always restarts primitives on it), otherwise gpu.IndexUint32.
func (m Mesh) Validate() errorValidate reports whether m can be uploaded: at least one triangle, normals and UVs that are empty or match the position count, finite attribute values, an index count (or, without indices, a vertex count) that is a multiple of three, and every index in range. Every error wraps ErrInvalidMesh.
func (m Mesh) VertexCount() intVertexCount returns the number of vertices, len(m.Positions).
func (m Mesh) VertexDataSize() intVertexDataSize returns the byte length Mesh.AppendVertexData appends.
type MeshUpload struct {
// Label names the buffers in GPU capture tools; the vertex buffer gets the suffix " vertices" and the index buffer " indices".
Label string
// Retained keeps a CPU copy of the buffers so NSGo recreates them after a device loss (see [gpu.BufferDesc].Retained). Leave it false when the game re-uploads its meshes from OnReady instead.
Retained bool
}MeshUpload configures UploadMesh.
type MetallicRoughnessMaterial = MaterialMetallicRoughnessMaterial is an explicit alias for Material naming the glTF 2.0 metallic-roughness workflow.
type MorphMesh struct {
Base Mesh
Targets []MorphTarget
Weights []float32
}MorphMesh pairs a base Mesh with zero or more MorphTarget displacement deltas and optional initial Weights, ready to upload with UploadMorphMesh.
Each target's Positions and Normals must be empty or match len(Base.Positions) with finite values. When Weights is non-empty, its length must match len(Targets) and every weight must be finite.
func (m MorphMesh) Validate() errorValidate reports whether m can be uploaded: a valid base Mesh, morph target delta slices that are empty or match the base vertex count with finite values, and initial weights that are either empty or match the target count with finite values. Every error wraps ErrInvalidMesh.
type MorphTarget struct {
Positions []math3d.Vec3
Normals []math3d.Vec3
}MorphTarget holds per-vertex displacement deltas for a single morph target. Positions and Normals are optional: each is either empty or holds one delta per base vertex. A github.com/nsgo-dev/game/pkg/gltf.MorphTarget maps directly to these fields.
type Occluder struct {
Vertices []math3d.Vec3
Indices []uint32
Bounds math3d.AABB
Transform math3d.Mat4
DoubleSided bool
// contains filtered or unexported fields
}Occluder holds static opaque triangle geometry rasterized into an OcclusionBuffer to cull hidden objects behind walls, floors, and buildings (#380).
func NewBoxOccluder(bounds math3d.AABB, transform math3d.Mat4) OccluderNewBoxOccluder builds a closed solid box Occluder from local-space bounds and a world transform. All six faces use outward CCW winding so back faces are skipped automatically.
func NewQuadOccluder(a, b, c, d math3d.Vec3, doubleSided bool) OccluderNewQuadOccluder builds a planar quad Occluder in world space from four CCW corners (a, b, c, d).
func OccluderFromMesh(vertices []math3d.Vec3, indices []uint32, transform math3d.Mat4) OccluderOccluderFromMesh derives a conservative Occluder directly from a static triangle mesh and its world transform. Degenerate or out-of-range triangles are discarded, non-indexed triangle soups (len(indices) == 0) are accepted, and coplanar shared edges are detected so flat walls rasterize without internal diagonal cracks while boundary and silhouette edges stay strictly inner-conservative.
type OcclusionBuffer struct {
// DepthNO selects OpenGL [-1, 1] NDC depth clipping (clip.Z >= -clip.W)
// when true. By default (false), WebGPU/Metal [0, 1] NDC depth
// (clip.Z >= 0) is used, matching [math3d.Perspective] and [Queue.FrustumNO].
DepthNO bool
// DepthBias is a small conservative depth margin added to Hi-Z max depth
// during [OcclusionBuffer.TestAABB] to guard against floating-point edge
// popping. Defaults to 1e-4 when <= 0.
DepthBias float32
// contains filtered or unexported fields
}OcclusionBuffer is a conservative CPU software depth buffer and max-Z hierarchical-Z (Hi-Z) pyramid for zero-false-negative volume occlusion culling (#380).
Typical per-frame usage (0 heap allocations in steady state):
occ.Clear() occ.Rasterize(viewProj, walls...) occ.BuildPyramid() plan := queue.BuildWithOcclusion(viewProj, camPos, items, occ)
func NewOcclusionBuffer(width, height int) *OcclusionBufferNewOcclusionBuffer allocates a reusable OcclusionBuffer of size width x height. Non-positive dimensions default to DefaultOcclusionWidth x DefaultOcclusionHeight (128x72).
func (b *OcclusionBuffer) BuildPyramid()BuildPyramid constructs the conservative max-Z hierarchical-Z (Hi-Z) mip pyramid from the rasterized depth buffer. Level 0 applies a separable 3x3 max erosion over the guard-banded depth buffer so partial pixel silhouettes and skewed quad corners never falsely occlude visible objects, and each coarser mip cell stores the maximum depth of its 2x2 children.
func (b *OcclusionBuffer) Clear()Clear resets the depth buffer to far (1.0) without allocating.
func (b *OcclusionBuffer) DepthAt(x, y int) float32DepthAt returns the conservative level-0 depth value at pixel (x, y), or 1.0 if out of range or if no geometry has been rasterized since [Clear].
func (b *OcclusionBuffer) Height() intHeight returns the vertical resolution of the occlusion buffer.
func (b *OcclusionBuffer) Levels() intLevels returns the number of mip levels in the Hi-Z pyramid.
func (b *OcclusionBuffer) Rasterize(viewProj math3d.Mat4, occluders ...Occluder)Rasterize projects, near-plane clips, and conservatively rasterizes one or more Occluder meshes into the depth buffer. Call OcclusionBuffer.BuildPyramid after rasterizing all occluders for the frame.
func (b *OcclusionBuffer) TestAABB(bounds math3d.AABB, viewProj math3d.Mat4) boolTestAABB reports whether bounds is potentially visible against the Hi-Z pyramid. It returns false ONLY when the projected AABB is strictly occluded behind the depth buffer (or completely outside the view frustum), guaranteeing zero false negatives (no popping).
If any corner of bounds crosses the near plane (camera inside or straddling the AABB), TestAABB always returns true.
func (b *OcclusionBuffer) Width() intWidth returns the horizontal resolution of the occlusion buffer.
type PBRDrawBuffer struct {
// contains filtered or unexported fields
}PBRDrawBuffer holds a PBRDrawUniform buffer and bind group bound at PBRDrawGroup for LitPBRWGSL.
func NewPBRDrawBuffer(cx *core.Scope, dev *gpu.Device, sharedLayout *gpu.BindGroupLayout, initial PBRDrawUniform, retained bool) (*PBRDrawBuffer, error)NewPBRDrawBuffer creates a per-draw PBR uniform buffer, bind group layout (or reuses sharedLayout if non-nil), and bind group on dev, scoped to cx.
func (b *PBRDrawBuffer) BindGroup() *gpu.BindGroupBindGroup returns the bind group to bind at PBRDrawGroup.
func (b *PBRDrawBuffer) Close() errorClose releases the draw buffer's bind group, uniform buffer, and owned bind group layout (if created without a shared layout). It is nil-safe and safe to call more than once.
func (b *PBRDrawBuffer) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout for PBRDrawGroup.
func (b *PBRDrawBuffer) Valid() boolValid reports whether the draw buffer and bind group are live.
func (b *PBRDrawBuffer) Write(dev *gpu.Device, u PBRDrawUniform)Write uploads u into the draw uniform buffer. Pass the current *gpu.Device or nil to reuse the stored one.
type PBRDrawUniform struct {
Model math3d.Mat4
NormalMatrix math3d.Mat4
BaseColor math3d.Vec4
PBRParams math3d.Vec4
Emissive math3d.Vec4
}PBRDrawUniform holds the per-draw world transform, normal matrix, and PBRMaterial matching LitPBRWGSL.
func NewPBRDrawUniform(model math3d.Mat4, mat PBRMaterial) PBRDrawUniformNewPBRDrawUniform constructs a PBRDrawUniform from an object-to-world model matrix and a PBRMaterial, deriving the normal matrix via math3d.NormalMatrix (falling back to identity if model is singular).
func (u *PBRDrawUniform) Encode(dst []byte) []byteEncode writes u into dst as the little-endian block LitPBRWGSL declares and returns dst[:PBRDrawUniformSize] without allocating. It panics if len(dst) < PBRDrawUniformSize.
type PBRLightmap struct {
// Model transforms vertices from object space to world space; the zero matrix defaults to identity.
Model math3d.Mat4
// Lightmap is the baked irradiance texture sampled at UV1*UVTransform.Scale + UVTransform.Offset. When nil, a 1x1 fallback texture is bound and indirect irradiance falls back to AmbientFallback (if non-zero or UseAmbientFallback is true) or the scene [LightRig]'s ambient light.
Lightmap *GPUTexture
// LightmapSampler is an optional sampler for Lightmap; nil defaults to linear clamp-to-edge.
LightmapSampler *GPUSampler
// Encoding specifies how Lightmap texels are decoded to linear irradiance.
Encoding LightmapEncoding
// Intensity scales decoded lightmap irradiance. Zero means zero (no baked light); [DefaultPBRLightmap] sets 1.
Intensity float32
// RGBMMaxRange sets the HDR peak scale for [LightmapRGBM]. Zero defaults to [DefaultRGBMMaxRange] (8.0).
RGBMMaxRange float32
// UVTransform maps UV1 into a shared baked lightmap atlas (uv1 * Scale + Offset). Zero Scale defaults to {1, 1}.
UVTransform UVTransform
// AmbientFallback overrides the scene [LightRig]'s ambient irradiance when Lightmap is nil (used whenever non-zero or UseAmbientFallback is true).
AmbientFallback [3]float32
// UseAmbientFallback forces AmbientFallback (even when zero) instead of the [LightRig]'s ambient when Lightmap is nil.
UseAmbientFallback bool
}PBRLightmap configures per-object transform, baked lightmap texture/sampler, encoding, intensity, RGBM range, shared-atlas UV transform, and fallback ambient irradiance for NewGPUPBRLightmap and GPUPBRLightmap.Update.
func DefaultPBRLightmap() PBRLightmapDefaultPBRLightmap returns a PBRLightmap with an identity model matrix, LightmapLinear encoding, unit intensity, default RGBM range, and identity atlas UV transform.
func (m PBRLightmap) EncodeUniform(dst []byte) []byteEncodeUniform writes m's PBRLightmapUniformSize-byte little-endian uniform block into dst, matching struct PBRLightmapUniform in PBRLightmapBindingsWGSL, and returns dst[:PBRLightmapUniformSize]. It panics if len(dst) < PBRLightmapUniformSize.
func (m PBRLightmap) Validate() errorValidate checks that every numeric field, encoding, UV transform, and non-nil GPU handle on m is valid. Every error wraps ErrInvalidLightmap.
type PBRLightmapEvalInput struct {
Material Material
BaseColorSample [4]float32
HasBaseColorSample bool
MetallicSample float32 // glTF metallic-roughness texture B channel
RoughnessSample float32 // glTF metallic-roughness texture G channel
HasMetallicRoughnessSample bool
NormalSample [3]float32 // UNORM [0, 1] tangent-space normal sample
HasNormalSample bool
OcclusionSample float32 // glTF occlusion texture R channel
HasOcclusionSample bool
EmissiveSample [3]float32 // linear RGB emissive texture sample
HasEmissiveSample bool
// Lightmap inputs. When HasLightmap is true, LightmapSample is decoded using Encoding, RGBMMaxRange, and Intensity and replaces Rig.Ambient.
HasLightmap bool
LightmapSample [4]float32
LightmapSRGB bool // true when the lightmap texture was uploaded as FormatRGBA8UnormSRGB (hardware already decoded sRGB)
Encoding LightmapEncoding
Intensity float32
RGBMMaxRange float32
AmbientFallback [3]float32
UseAmbientFallback bool
WorldPos math3d.Vec3
Normal math3d.Vec3 // geometric world-space normal
Tangent math3d.Vec3 // optional world-space tangent (+U); derived from Normal when zero
Bitangent math3d.Vec3 // optional world-space bitangent (+Y normal map / -V); derived from Normal x Tangent when zero
ViewDir math3d.Vec3 // vector from surface toward camera
FrontFacing bool // true for front-facing fragments; flips Normal when false and Material.DoubleSided is true
Rig LightRig
}PBRLightmapEvalInput provides per-fragment inputs to EvaluatePBRLightmap, the pure-Go CPU reference evaluator matching PBRLightmapWGSL.
type PBRLightmapEvalResult struct {
Linear math3d.Vec4 // unclamped linear RGBA radiance matching [PBRLightmapLinearWGSL]
SRGB math3d.Vec4 // IEC 61966-2-1 sRGB-encoded RGBA matching [PBRLightmapWGSL]
Indirect math3d.Vec3 // baked lightmap (or ambient fallback) diffuse contribution
Direct math3d.Vec3 // dynamic [LightRig] Cook-Torrance GGX direct contribution
Emissive math3d.Vec3 // emissive contribution
Normal math3d.Vec3 // final world-space shading normal after normal mapping
Metallic float32 // effective clamped metallic in [0, 1]
Roughness float32 // effective clamped roughness in [0.045, 1]
Discarded bool // true when AlphaMode == AlphaMask and effective alpha < AlphaCutoff
}PBRLightmapEvalResult holds the CPU reference shading output produced by EvaluatePBRLightmap.
func EvaluatePBRLightmap(in PBRLightmapEvalInput) PBRLightmapEvalResultEvaluatePBRLightmap evaluates the lightmapped glTF 2.0 metallic-roughness PBR shading model on the CPU, matching PBRLightmapWGSL and PBRLightmapLinearWGSL.
type PBRLightmapOptions struct {
// Label names the uniform buffer, bind group layout, and bind group in GPU capture tools.
Label string
// SharedLayout reuses an existing [PBRLightmapGroup] bind group layout (from [PBRLightmapBindGroupLayout], another [GPUPBRLightmap.Layout], or [GLTFPBRLightmapSet.Layout]) instead of creating one per object.
// FallbackTexture is an optional 1x1 linear texture bound when [PBRLightmap.Lightmap] is nil so callers sharing one fallback do not allocate a new 1x1 texture per instance.
FallbackTexture *GPUTexture
// FallbackSampler is an optional clamp-to-edge sampler bound when [PBRLightmap.LightmapSampler] is nil.
FallbackSampler *GPUSampler
// Retained keeps CPU shadow copies of the uniform buffer and any owned fallback texture/sampler so NSGo restores them across a GPU device loss.
Retained bool
}PBRLightmapOptions configures NewGPUPBRLightmap.
type PBRLightmapPipelineOptions struct {
// Label names the pipeline in GPU capture tools.
Label string
// ColorFormat sets the color attachment format; [gpu.FormatUndefined] defaults to dev.SurfaceFormat() (or [gpu.FormatRGBA8Unorm] if undefined).
ColorFormat gpu.TextureFormat
// DepthFormat enables depth testing (and depth writes for opaque and alpha-mask modes) when non-zero.
DepthFormat gpu.TextureFormat
// AlphaMode selects blending and depth-write state: [AlphaOpaque] and [AlphaMask] write depth without color blending; [AlphaBlend] uses straight alpha blending ([gpu.BlendAlpha]) with depth writes disabled.
AlphaMode AlphaMode
// DoubleSided disables back-face culling ([gpu.CullNone]); when false, back faces are culled ([gpu.CullBack]).
DoubleSided bool
// LinearOutput skips the shader's final linear_to_srgb encode and writes unclamped linear radiance, for drawing into an [HDRTarget] resolved by [ToneMapPass]. When ColorFormat is an sRGB format, linear output is selected automatically so the hardware does not encode twice.
LinearOutput bool
// Retained keeps the compiled pipeline across a GPU device loss.
Retained bool
}PBRLightmapPipelineOptions configures NewPBRLightmapPipeline.
type PBRMaterial struct {
// BaseColor is linear RGB albedo (dielectric diffuse reflectance or metallic F0 specular tint).
BaseColor math3d.Vec3
// Alpha is surface opacity in (0, 1]; zero defaults to 1 (opaque) in [NewPBRDrawUniform].
Alpha float32
// Metallic blends between dielectric (0) and conductor (1), clamped to [0, 1].
Metallic float32
// Roughness is perceptual roughness in [0, 1] (0 = smooth, 1 = fully rough). Internally clamped
// to >= 0.045 before squaring to alpha = roughness^2 to prevent GGX singularities.
Roughness float32
// Emissive is optional linear RGB self-emission added after direct and ambient lighting.
Emissive math3d.Vec3
// Clearcoat is the KHR_materials_clearcoat coating intensity in [0, 1] (0 disables clearcoat).
Clearcoat float32
// ClearcoatRoughness is the perceptual roughness of the clearcoat layer in [0, 1].
ClearcoatRoughness float32
// Transmission is the KHR_materials_transmission optical transmission factor in [0, 1] (0 disables transmission).
Transmission float32
// IOR is the dielectric index of refraction (>= 1.0); zero defaults to 1.5 (F0 = 0.04).
IOR float32
}PBRMaterial holds glTF 2.0 metallic-roughness surface parameters in linear RGB space.
func (m PBRMaterial) WithVertexColor(c math3d.Vec4) PBRMaterialWithVertexColor returns a copy of m with BaseColor multiplied by c.XYZ and Alpha multiplied by c.W (treating a zero Alpha on m as 1, matching NewPBRDrawUniform), so passing the result to EvaluatePBR, ShadePoint, ShadePointShadowed, ShadePointVisibility, or EvaluateIBL reproduces a LitPBRPipelineOptions.VertexColors fragment on the CPU.
type PixelBuffer struct {
Width int
Height int
Stride int
Format gpu.TextureFormat
Pixels []byte
}PixelBuffer holds uncompressed 2D pixel data on the CPU, ready to upload to a GPU view with UploadTexturePixels.
Width and Height must be positive. Format is one of gpu.FormatRGBA8Unorm, gpu.FormatRGBA8UnormSRGB, gpu.FormatRG8Unorm, gpu.FormatR8Unorm, or gpu.FormatUndefined (which selects RGBA8 linear or sRGB per TextureUpload.SRGB). Stride is the byte distance between consecutive rows; when zero, rows are assumed tightly packed (Width * BytesPerPixel).
func PixelBufferFromImage(img image.Image) (PixelBuffer, error)PixelBufferFromImage converts any image.Image (including sub-images with a non-zero Bounds().Min) into a tightly packed straight-alpha RGBA8 PixelBuffer. When img is already an *image.NRGBA, its channel bytes are copied verbatim even for pixels with zero alpha, preserving packed data maps. Every error wraps ErrInvalidTexture.
func (b PixelBuffer) BytesPerPixel() intBytesPerPixel returns the byte width of one pixel for b.Format, or zero for an unsupported format. gpu.FormatUndefined defaults to 4 (RGBA8).
func (b PixelBuffer) TightSize() intTightSize returns the byte length of tightly packed rows for b (Width * Height * BytesPerPixel), or zero when b has non-positive dimensions or an unsupported format.
func (b PixelBuffer) Validate() errorValidate reports whether b describes a valid uncompressed 2D pixel buffer: positive dimensions within uint32 range, a supported 8-bit format, a non-negative stride at least one row wide, and enough bytes in Pixels for every row. Every error wraps ErrInvalidTexture.
type PixelViewport struct {
X int32
Y int32
Width int32
Height int32
MinDepth float32
MaxDepth float32
}PixelViewport is a resolved, target-clamped pixel rectangle ready to apply to a gpu.RenderPass with PixelViewport.Apply.
func (p PixelViewport) Apply(pass *gpu.RenderPass)Apply sets both the rasterizer viewport and the matching pixel scissor rect on pass so draws stay strictly inside p with zero bleed across split seams.
func (p PixelViewport) Aspect() float32Aspect returns Width / Height, or zero when Width or Height is non-positive.
func (p PixelViewport) Bounds(pixelsPerPoint float32) core.BoundsBounds converts p from physical pixels to a core.Bounds in logical points for 2D overlay helpers such as DebugDraw.Flush, Gizmo.DrawGizmo, and BillboardRenderer.Draw, which draw into a *core.Drawing measured in points. pixelsPerPoint is the surface's content scale: its width in pixels (frame.Size) divided by the view's width in points. A non-positive or non-finite pixelsPerPoint is treated as 1.
type PointLight struct {
Position math3d.Vec3
Color math3d.Vec3
Intensity float32
Range float32
}PointLight is an omnidirectional punctual emitter at Position with inverse-square falloff and an optional glTF KHR_lights_punctual smooth cutoff Range.
Color is linear RGB tint (non-negative finite channels) and Intensity scales Color to produce linear radiant intensity. When Range > 0, attenuation is windowed by max(min(1 - (d/Range)^4, 1), 0)^2 / d^2 so contribution smoothly reaches zero at Range; when Range == 0, pure inverse-square falloff 1 / d^2 is used.
func (l PointLight) Validate() errorValidate reports whether l has a finite position, finite non-negative color channels, and finite non-negative intensity and range. Every error wraps ErrInvalidLight.
type PointShadowConfig struct {
// FaceResolution is the width and height of one cube face tile in texels. The 3x2 depth atlas has size (3 * FaceResolution) x (2 * FaceResolution). Zero defaults to 512.
FaceResolution uint32
// Near is the near plane distance of the six face projections. Zero defaults to [DefaultLocalShadowNear].
Near float32
// Far is the far plane distance used when the point light's Range is 0; a light with a Range uses that instead. Zero defaults to [DefaultLocalShadowFar].
Far float32
// DepthBias subtracts a constant NDC [0, 1] bias during depth comparison.
DepthBias float32
// NormalBias offsets the shaded world position along its surface normal before selecting the cube face and comparing depth.
NormalBias float32
// Filter selects hard single-tap or 3x3 PCF comparison sampling.
Filter LocalShadowFilter
// CullMode sets face culling for the shadow caster passes (default gpu.CullNone).
CullMode gpu.CullMode
// MaxCasters is the maximum number of [PointShadowMap.DrawCaster] calls per cube face pass, at most [MaxLocalShadowCasters]. Each face has its own slots, so faces can be recorded in any order or skipped. Zero defaults to [DefaultLocalShadowMaxCasters].
MaxCasters uint32
// Label names GPU resources in capture tools.
Label string
// Retained keeps resources across GPU device loss and restore.
Retained bool
}PointShadowConfig configures an omnidirectional 3x2 depth-atlas PointShadowMap.
func DefaultPointShadowConfig() PointShadowConfigDefaultPointShadowConfig returns a ready-to-use 512x512-per-face PCF 3x3 point shadow configuration.
func (c PointShadowConfig) AtlasSize() (width, height uint32)AtlasSize returns the width and height in texels of the 3x2 2D depth atlas.
func (c PointShadowConfig) Normalized() PointShadowConfigNormalized returns a copy of c with zero FaceResolution, Near, Far and MaxCasters filled with defaults.
func (c PointShadowConfig) Validate() errorValidate checks that c's resolution, planes, biases, filter, cull mode and caster count are valid. Every error wraps ErrInvalidLocalShadow.
type PointShadowMap struct {
// contains filtered or unexported fields
}PointShadowMap manages an omnidirectional shadow for the first point light of a LightRig: the six 90-degree cube faces packed into one 3x2 Depth32Float atlas, its caster pipeline and its sampling bind group.
Call PointShadowMap.Update with the rig's point light, record casters for each face to refresh between PointShadowMap.BeginFacePass and pass.End(), and bind PointShadowMap.BindGroup at LocalShadowGroup when drawing with NewLitPBRPointShadowPipeline.
func NewPointShadowMap(cx *core.Scope, dev *gpu.Device, cfg PointShadowConfig) (*PointShadowMap, error)NewPointShadowMap creates a 3x2 Depth32Float atlas point shadow map and its GPU resources scoped to cx. Invalid configuration, an atlas above the device's MaxTextureDimension2D, or a caster buffer above its MaxBufferSize returns an error wrapping ErrInvalidLocalShadow; device errors are returned as gpu.Error.
func (p *PointShadowMap) AtlasHeight() uint32AtlasHeight returns the full height of the 3x2 depth atlas (2 * FaceResolution).
func (p *PointShadowMap) AtlasWidth() uint32AtlasWidth returns the full width of the 3x2 depth atlas (3 * FaceResolution).
func (p *PointShadowMap) BeginFacePass(dev *gpu.Device, target ShadowPassTarget, face gpu.CubeFace) *gpu.RenderPassBeginFacePass begins a depth-only render pass on target (a *gpu.Encoder or *gpu.Frame) for cube face (0..5) of the 3x2 depth atlas, resets that face's caster slots, binds the depth pipeline, and locks viewport and scissor to the face's tile so geometry cannot bleed into neighboring faces.
Face 0 clears the whole atlas to 1.0 and faces 1..5 keep what is already there (gpu.LoadLoad). Refreshing only some faces in a frame (for example skipping faces whose casters did not move) therefore works as long as face 0 is either refreshed together with every other face or not refreshed at all. Each face has its own PointShadowMap.MaxCasters slots, so faces may be recorded in any order; record each face at most once per submission. It returns nil when p, dev or target is nil, p is invalid, or face is out of range.
func (p *PointShadowMap) BindGroup() *gpu.BindGroupBindGroup returns the bind group to set at LocalShadowGroup, or at the group passed to PointShadowWGSLForGroup, during the lit render pass.
func (p *PointShadowMap) ByteSize() uint64ByteSize returns the GPU memory held by the 3x2 depth atlas and uniform buffers.
func (p *PointShadowMap) Close() errorClose releases all GPU resources owned by p. It is safe to call on a nil receiver or more than once.
func (p *PointShadowMap) Config() PointShadowConfigConfig returns the normalized PointShadowConfig.
func (p *PointShadowMap) DepthTexture() *gpu.TextureDepthTexture returns the underlying Depth32Float 3x2 atlas gpu.Texture.
func (p *PointShadowMap) DrawCaster(pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) boolDrawCaster records a shadow caster draw for mesh transformed by model into the face pass most recently started by PointShadowMap.BeginFacePass. It returns false and draws nothing when an argument is invalid, PointShadowMap.Update has not been called yet, or PointShadowMap.MaxCasters casters were already drawn into this face.
func (p *PointShadowMap) FaceViewProj(face gpu.CubeFace) math3d.Mat4FaceViewProj returns the view-projection matrix of cube face (0..5) from the last PointShadowMap.Update. It returns identity for a nil receiver or an out-of-range face.
func (p *PointShadowMap) FaceViewport(face gpu.CubeFace) (x, y, width, height uint32)FaceViewport returns the pixel rectangle (x, y, width, height) inside the 3x2 depth atlas assigned to cube face (0..5).
func (p *PointShadowMap) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout for sampling this point shadow map (binding 0: PointShadow uniform, binding 1: texture_depth_2d, binding 2: sampler_comparison).
func (p *PointShadowMap) MaxCasters() uint32MaxCasters returns the number of PointShadowMap.DrawCaster calls one face pass accepts.
func (p *PointShadowMap) RenderTarget() *gpu.RenderTargetRenderTarget returns the underlying depth-only 3x2 atlas gpu.RenderTarget.
func (p *PointShadowMap) Sampler() *gpu.SamplerSampler returns the comparison gpu.Sampler bound in PointShadowMap.BindGroup.
func (p *PointShadowMap) Uniforms() PointShadowUniformUniforms returns the last point shadow uniform data written via PointShadowMap.Update.
func (p *PointShadowMap) Update(dev *gpu.Device, light PointLight) errorUpdate computes the six cube-face projections for the LightRig point light light (see NewPointShadowUniform) and writes the uniform buffer on dev without heap allocations.
func (p *PointShadowMap) Valid() boolValid reports whether all underlying GPU resources are open and live.
type PointShadowUniform struct {
Position math3d.Vec3
Near float32
Far float32
DepthBias float32
NormalBias float32
InvFaceResolution float32
// FilterMode is 0 for [LocalShadowFilterHard] and 1 for [LocalShadowFilterPCF3x3].
FilterMode float32
}PointShadowUniform is the packed uniform data matching the WGSL PointShadow block declared by PointShadowWGSL.
func NewPointShadowUniform(light PointLight, cfg PointShadowConfig) (PointShadowUniform, error)NewPointShadowUniform computes the shadow uniform data for the LightRig point light light under cfg. The far plane is light.Range, or cfg.Far when Range is 0. It returns an error wrapping ErrInvalidLight when light is invalid, and one wrapping ErrInvalidLocalShadow when cfg is invalid or the far plane is not beyond the near plane.
func (u *PointShadowUniform) Encode(dst []byte) []byteEncode writes u into dst in the little-endian layout declared by PointShadowWGSL and returns dst[:PointShadowUniformSize]. It allocates nothing and panics if len(dst) < PointShadowUniformSize.
func (u PointShadowUniform) FaceViewProj(face gpu.CubeFace) math3d.Mat4FaceViewProj returns the 90-degree [0, 1]-depth perspective view-projection matrix of cube face (0..5) that PointShadowMap renders with. Out-of-range faces clamp to gpu.CubeFacePosX.
type PostStack3D struct {
// contains filtered or unexported fields
}PostStack3D composes SSAO, Depth of Field, and Bloom over an offscreen 3D color+depth render target, routing enabled passes cleanly through ping-pong offscreen targets and writing the final result to the swapchain or a chosen destination texture.
Execution order is fixed to SSAO -> Depth of Field -> Bloom so ambient occlusion darkens crevices before bokeh blurring and highlights bloom after optical blur. All passes use portable WGSL compatible with both full and compute-free (WebGL 2 / OpenGL ES 3.0) NSGo GPU profiles.
func NewPostStack3D(cx *core.Scope, dev *gpu.Device, opts PostStack3DOptions) (*PostStack3D, error)NewPostStack3D creates a scope-owned composable 3D post-processing stack on dev.
func (s *PostStack3D) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) errorApply executes all enabled passes in order (SSAO -> Depth of Field -> Bloom) on caller-provided srcColor and depthTex textures, writing the final result into dstColor. A nil dstColor writes to the swapchain in OutputFormat; a texture must have the stack size and either ColorFormat or OutputFormat. srcColor and depthTex must have the stack size too, and dstColor cannot be one of them; a mismatch returns an error wrapping ErrInvalidPostProcess. If depthTex is nil, depth-dependent passes (SSAO and Depth of Field) are skipped; if no pass runs, srcColor is blitted to dstColor.
func (s *PostStack3D) ApplyScene(dev *gpu.Device, rec RenderPassRecorder, dstColor *gpu.Texture) errorApplyScene executes all enabled passes on PostStack3D.SceneTarget's color and depth attachments, writing the result into dstColor as PostStack3D.Apply does.
func (s *PostStack3D) BeginScenePass(rec RenderPassRecorder, clearColor core.Color) *gpu.RenderPassBeginScenePass begins a render pass targeting PostStack3D.SceneTarget, clearing color to clearColor and depth to 1.0 and storing both attachments for post-processing.
func (s *PostStack3D) Bloom() *BloomPassBloom returns the underlying BloomPass.
func (s *PostStack3D) Close() errorClose releases all GPU resources owned by s and its passes. It is safe to call on a nil receiver or more than once.
func (s *PostStack3D) ColorFormat() gpu.TextureFormatColorFormat returns the offscreen scene and intermediate color target format.
func (s *PostStack3D) DepthFormat() gpu.TextureFormatDepthFormat returns the offscreen scene depth target format.
func (s *PostStack3D) DepthOfField() *DepthOfFieldPassDepthOfField returns the underlying DepthOfFieldPass.
func (s *PostStack3D) Height() uint32Height returns the stack's offscreen target height in pixels.
func (s *PostStack3D) OutputFormat() gpu.TextureFormatOutputFormat returns the final destination format (swapchain or dstColor).
func (s *PostStack3D) Resize(dev *gpu.Device, width, height uint32) errorResize recreates the stack's scene, ping-pong, and per-pass offscreen targets.
func (s *PostStack3D) SSAO() *SSAOPassSSAO returns the underlying SSAOPass.
func (s *PostStack3D) SceneTarget() *gpu.RenderTargetSceneTarget returns the stack-managed offscreen 3D color+depth gpu.RenderTarget.
func (s *PostStack3D) SetBloom(enabled bool, cfg BloomConfig) errorSetBloom enables or disables Bloom and updates its configuration. A zero cfg keeps the current configuration, so SetBloom(false, BloomConfig{}) only turns the stage off.
func (s *PostStack3D) SetCamera(cam *scene3d.Camera) errorSetCamera refreshes the projection SSAO reconstructs view-space positions with and the clip planes Depth of Field linearizes depth with from cam's projection matrix, keeping every other setting. Call it whenever the camera's projection changes, such as after a resize changes its aspect ratio or a zoom changes its field of view.
func (s *PostStack3D) SetDepthOfField(enabled bool, cfg DepthOfFieldConfig) errorSetDepthOfField enables or disables Depth of Field and updates its configuration. A zero cfg keeps the current configuration, so SetDepthOfField(false, DepthOfFieldConfig{}) only turns the stage off.
func (s *PostStack3D) SetSSAO(enabled bool, cfg SSAOConfig) errorSetSSAO enables or disables SSAO and updates its configuration. A zero cfg keeps the current configuration, so SetSSAO(false, SSAOConfig{}) only turns the stage off.
func (s *PostStack3D) Valid() boolValid reports whether the stack and every internal pass and target are live.
func (s *PostStack3D) Width() uint32Width returns the stack's offscreen target width in pixels.
type PostStack3DOptions struct {
Label string
// Width and Height of the offscreen 3D scene and post-processing targets (must be > 0).
Width uint32
Height uint32
// ColorFormat is the scene and intermediate ping-pong color format: [gpu.FormatRGBA16Float] (the default, preserving HDR highlights for Bloom), [gpu.FormatRGBA8Unorm], [gpu.FormatRGBA8UnormSRGB], [gpu.FormatBGRA8Unorm] or [gpu.FormatBGRA8UnormSRGB]. Any other format returns an error wrapping [ErrInvalidPostProcess].
ColorFormat gpu.TextureFormat
// DepthFormat is the scene render target's depth format. Defaults to [gpu.FormatDepth32Float] when zero.
DepthFormat gpu.TextureFormat
// OutputFormat is the swapchain format the final stage writes when dstColor is nil. A non-nil dstColor may be in OutputFormat or ColorFormat. Defaults to dev.SurfaceFormat() (or [gpu.FormatRGBA8Unorm]) when zero.
OutputFormat gpu.TextureFormat
// Retained opts offscreen targets, buffers, and samplers into automatic recreation after device loss.
Retained bool
// EnableSSAO enables the SSAO pass (stage 1). When false and SSAO is zero, DefaultSSAOConfig is prepared for later enabling.
EnableSSAO bool
SSAO SSAOConfig
// EnableDoF enables the Depth of Field pass (stage 2).
EnableDoF bool
DoF DepthOfFieldConfig
// EnableBloom enables the Bloom pass (stage 3).
EnableBloom bool
Bloom BloomConfig
}PostStack3DOptions configures NewPostStack3D.
type PrefilterOptions struct {
// BaseSize is the resolution of mip level 0 (roughness = 0). Defaults to env.Size() when <= 0.
BaseSize int
// MipLevels is the number of roughness mip levels to generate, spanning roughness 0.0 (mip 0) through 1.0 (mip MipLevels-1). Defaults to min(MaxMipLevels(BaseSize, BaseSize), 5) when <= 0.
MipLevels int
// SampleCount is the number of Hammersley GGX importance samples per texel on roughness > 0 levels. Defaults to 64 when <= 0.
SampleCount int
}PrefilterOptions configures PrefilterEnvironment.
type ProbeBakeOptions struct {
// Size is the face edge length in texels (must be positive).
Size int
// Near and Far set the 90-degree cubemap face projection clip planes for [BakeReflectionProbeGPU]. Non-positive Near defaults to 0.05; Far <= Near defaults to Near + 100.
Near float32
Far float32
// ClearColor is the background clear color for each face pass in [BakeReflectionProbeGPU].
ClearColor core.Color
// SRGB marks the baked cubemap as sRGB-encoded: [BakeReflectionProbeGPU] renders into [gpu.FormatRGBA8UnormSRGB] targets and [UploadCubemap] uploads [gpu.FormatRGBA8UnormSRGB] so sampling decodes to linear light. When false, linear [gpu.FormatRGBA8Unorm] is used.
SRGB bool
// Prefilter configures GGX specular roughness mip prefiltering via [PrefilterEnvironment]. Zero fields use [PrefilterEnvironment]'s defaults unless SkipPrefilter is true.
Prefilter PrefilterOptions
// SkipPrefilter skips GGX prefiltering and uploads the captured mip-0 cubemap directly (with box mip generation controlled by Upload.GenerateMips).
SkipPrefilter bool
// Upload configures [UploadCubemap] for the final [GPUCubemap] (Label, Format, GenerateMips, Retained).
Upload CubemapUpload
}ProbeBakeOptions configures BakeReflectionProbe and BakeReflectionProbeGPU.
Reflection probe bakes are runtime-only data generated on load or on request rather than persisted in text scene files.
For BakeReflectionProbeGPU, each temporary offscreen face render target uses gpu.FormatRGBA8Unorm when SRGB is false or gpu.FormatRGBA8UnormSRGB when SRGB is true (unless Upload.Format explicitly selects one of those two formats), paired with gpu.FormatDepth24Plus for depth. Match the color format of any pipeline drawn inside renderFace (for example, gpu.FormatRGBA8Unorm for sRGB-encoding shaders such as LitPBRWGSL, or gpu.FormatRGBA8UnormSRGB for linear-output shaders).
type ProbeBlendResult struct {
Primary *ReflectionProbe
Secondary *ReflectionProbe
Weight0 float32
Weight1 float32
SkyWeight float32
}ProbeBlendResult holds up to two active local reflection probes selected for a world position together with normalized blend weights (Weight0 + Weight1 + SkyWeight == 1).
func (r ProbeBlendResult) EvaluateSpecular(worldPos, reflDir math3d.Vec3, roughness float32, skyPrefilter *Cubemap) [3]float32EvaluateSpecular evaluates the blended specular prefiltered environment color on the CPU at worldPos along reflDir for roughness in [0, 1], matching sample_probe_specular in ProbeIBLWGSL. Unbaked, dirty, disabled, or nil-cubemap probes and a nil skyPrefilter all contribute black (0, 0, 0), matching the GPU fallback cubemap identically.
type ProbeCounts [3]intProbeCounts is the [nx, ny, nz] probe lattice count serialized in flow style in baked light probe YAML files.
func (c ProbeCounts) MarshalYAML() (any, error)MarshalYAML encodes c in compact single-line flow style [nx, ny, nz].
type ProbeIBLBufferOptions struct {
// Label names the uniform buffer, fallback black cubemap, bind group layout, and bind group in GPU capture tools.
Label string
// Layout optionally reuses a shared [ProbeIBLBindGroupLayout] across multiple per-object [GPUProbeIBLBuffer] instances so they share one pipeline. When nil, the buffer creates and owns its own layout.
Layout *gpu.BindGroupLayout
// Retained keeps CPU shadow copies of the uniform buffer and black fallback cubemap so NSGo recreates them across a GPU device loss.
Retained bool
}ProbeIBLBufferOptions configures NewGPUProbeIBLBuffer.
type ProbeIBLPipelineOptions struct {
// Label names the pipeline in GPU capture tools; empty picks render3d.lit_pbr_probe_ibl (with .linear for LinearOutput).
Label string
// ColorFormat sets the color attachment format; [gpu.FormatUndefined] defaults to dev.SurfaceFormat().
ColorFormat gpu.TextureFormat
// DepthFormat enables depth testing and writes when not [gpu.FormatUndefined].
DepthFormat gpu.TextureFormat
// LinearOutput writes unclamped linear radiance without sRGB encoding for drawing into an [HDRTarget] resolved by [ToneMapPass].
LinearOutput bool
}ProbeIBLPipelineOptions configures NewLitPBRProbeIBLPipelineWithOptions.
type ProbeIBLUniform struct {
SH IrradianceSH
Probe0Pos math3d.Vec3
Probe0BoxMin math3d.Vec3
Probe0BoxMax math3d.Vec3
Probe0Weight float32
Probe0MaxLOD float32
Probe0BoxProjection bool
Probe1Pos math3d.Vec3
Probe1BoxMin math3d.Vec3
Probe1BoxMax math3d.Vec3
Probe1Weight float32
Probe1MaxLOD float32
Probe1BoxProjection bool
Intensity float32
SkyWeight float32
SkyMaxLOD float32
}ProbeIBLUniform holds the per-object diffuse L2 spherical harmonic irradiance and blended reflection-probe parameters bound by GPUProbeIBLBuffer at IBLGroup and read by ProbeIBLWGSL.
func NewProbeIBLUniform(sh IrradianceSH, blend ProbeBlendResult, sky *GPUCubemap, intensity float32) ProbeIBLUniformNewProbeIBLUniform builds a ProbeIBLUniform from interpolated light-probe irradiance sh, reflection probe blend result blend, optional sky prefiltered cubemap sky, and overall IBL intensity.
Unbaked, dirty, disabled, or invalid-GPUCubemap probes receive zero weight, and a nil or invalid sky receives zero SkyWeight and SkyMaxLOD, matching EvaluateProbeIBL identically.
func (u *ProbeIBLUniform) Encode(dst []byte) []byteEncode writes u into dst as the little-endian ProbeIBLUniformSize-byte block declared by ProbeIBLWGSL and returns dst[:ProbeIBLUniformSize] without allocating. It panics if len(dst) < ProbeIBLUniformSize.
func (u ProbeIBLUniform) Validate() errorValidate checks that every spherical harmonic coefficient, probe coordinate, weight, LOD, and intensity is finite and non-negative where required. Every error wraps ErrInvalidProbe.
type ProbeVec3 [3]float32ProbeVec3 is a 3-component float32 vector serialized in flow style as [x, y, z] in baked light probe YAML files.
func (v ProbeVec3) MarshalYAML() (any, error)MarshalYAML encodes v in compact single-line flow style [x, y, z], normalizing -0 to 0.
type Queue struct {
// LODHysteresis is the relative deadband [0, 0.5] used by [SelectLOD] when
// DrawItem.ID != 0 to prevent LOD popping near distance/screen thresholds.
LODHysteresis float32
// FrustumNO is kept for source compatibility and ignored: [Queue.Build]
// always extracts the [-1, 1] form, which is conservative for both depth
// conventions. A [0, 1] extraction of an OpenGL [-1, 1] matrix, such as
// [math3d.OrthoNO] or [math3d.PerspectiveNO], puts the near plane halfway
// into the view and culls visible geometry; the [-1, 1] form only admits
// a thin slab in front of a [0, 1] projection's near plane, which the
// depth test still discards.
FrustumNO bool
// DisableInstancing emits one InstanceBatch per opaque draw when true.
DisableInstancing bool
// Occluder is an optional software depth-buffer / Hi-Z occlusion buffer
// (#380). When non-nil, [Queue.Build] skips frustum-visible items whose
// WorldBounds fail [OcclusionBuffer.TestAABB] and records them in
// [RenderStats.Occluded].
Occluder *OcclusionBuffer
// TextureBytes and BufferBytes are optional resident GPU memory totals
// copied into RenderPlan.Stats for budget checking.
TextureBytes uint64
BufferBytes uint64
// contains filtered or unexported fields
}Queue performs frustum culling, LOD selection, opaque sorting, instanced batching, back-to-front transparency sorting, and statistics accumulation using reusable internal storage (0 allocs/op in steady state).
func (q *Queue) Build(viewProj math3d.Mat4, camPos math3d.Vec3, items []DrawItem) RenderPlanBuild culls items against the frustum of viewProj (and against Queue.Occluder when non-nil), selects active LODs, sorts opaque and transparent queues, builds instanced batches, and computes exact RenderStats.
func (q *Queue) BuildWithOcclusion(viewProj math3d.Mat4, camPos math3d.Vec3, items []DrawItem, occluder *OcclusionBuffer) RenderPlanBuildWithOcclusion performs the same culling, LOD selection, sorting, and batching pipeline as Queue.Build using the provided OcclusionBuffer (which may be nil to disable occlusion culling). Items that pass frustum culling but fail OcclusionBuffer.TestAABB are skipped and counted in both RenderStats.Occluded and RenderStats.CulledItems.
func (q *Queue) ResetLODHistory()ResetLODHistory clears cached per-ID LOD indices used for hysteresis.
type RawBufferUpload struct {
Label string
Usage gpu.BufferUsage // gpu.UsageCopyDst is always added
Data []byte
Retained bool
}RawBufferUpload describes a raw GPU buffer payload returned by the decode callback of Uploader.QueueRawBuffer.
type RawTextureUpload struct {
Desc gpu.TextureDesc // Usage defaults to TextureSampled | TextureCopyDst; TextureCopyDst is always added
Mips []TextureMipData
}RawTextureUpload describes a GPU texture and pre-encoded mip payloads returned by the decode callback of Uploader.QueueRawTexture.
type ReflectionProbe struct {
ID string
Position math3d.Vec3
BoxMin math3d.Vec3
BoxMax math3d.Vec3
BlendDistance float32 // inward fade width from the box boundary; 0 = sharp box boundary
Priority int // higher priority takes precedence when probes overlap
BoxProjection bool // apply parallax-corrected ray-AABB projection
Intensity float32 // reflection multiplier; 0 defaults to 1.0 (use Disabled to turn off)
Cubemap *Cubemap
Prefiltered *Cubemap
GPUCubemap *GPUCubemap
Dirty bool // needs re-bake on request; dirty probes are skipped during selection
Baked bool // cubemap has been baked or populated; unbaked probes are skipped during selection
Disabled bool // exclude probe from selection without removing it
}ReflectionProbe describes a local cubemap reflection volume with optional parallax-corrected box projection and smooth edge fade.
Reflection probe bakes (Cubemap, Prefiltered, and GPUCubemap) are runtime-only data generated on load or on request rather than persisted in text scene files. Call ReflectionProbe.Close when releasing a probe whose GPUCubemap is manually scoped; re-baking via BakeReflectionProbe or BakeReflectionProbeGPU automatically closes the previous GPUCubemap before replacing it.
func (p *ReflectionProbe) BoxVolume() float32BoxVolume returns the volume of p's influence AABB, or 0 for a nil, inverted, or non-finite box.
func (p *ReflectionProbe) Close() errorClose releases p's GPUCubemap if present and marks p unbaked. Safe to call on nil or more than once.
func (p *ReflectionProbe) EffectiveIntensity() float32EffectiveIntensity returns the reflection multiplier for p, treating a zero Intensity as 1.0 and returning 0 when p is nil, disabled, negative, or non-finite.
func (p *ReflectionProbe) Influence(worldPos math3d.Vec3) float32Influence returns the smooth influence weight in [0, 1] of p at worldPos. Points outside [BoxMin, BoxMax] or with non-finite coordinates return 0 (never NaN). Points farther than BlendDistance inside every face return 1; points within BlendDistance of a face fade with cubic smoothstep.
func (p *ReflectionProbe) Ready() boolReady reports whether p is enabled, baked, and clean (not Dirty).
func (p *ReflectionProbe) Validate() errorValidate checks that p's position, bounding box, blend distance, and intensity are finite and well-formed. Every error wraps ErrInvalidProbe.
type ReflectionProbeSet struct {
Probes []*ReflectionProbe
}ReflectionProbeSet manages a collection of local ReflectionProbe volumes and selects up to two overlapping ready probes to blend over the global sky environment.
func (s *ReflectionProbeSet) Add(probes ...*ReflectionProbe)Add appends probes to the set.
func (s *ReflectionProbeSet) Close() errorClose closes every probe's GPUCubemap in the set. Safe to call on nil or more than once.
func (s *ReflectionProbeSet) DirtyProbes() []*ReflectionProbeDirtyProbes returns every enabled probe currently marked Dirty or not yet Baked.
func (s *ReflectionProbeSet) SelectReflectionProbes(worldPos math3d.Vec3) ProbeBlendResultSelectReflectionProbes selects up to two active baked, non-dirty reflection probes affecting worldPos and computes smooth normalized blend weights (Weight0, Weight1, SkyWeight) summing to 1. Unbaked, dirty, and disabled probes are skipped so objects fall back smoothly to ready probes or the global sky.
type RenderPassRecorder interface {
BeginRenderPass(desc gpu.RenderPassDesc) *gpu.RenderPass
}RenderPassRecorder is satisfied by both *gpu.Encoder and *gpu.Frame, allowing DynamicResolutionTarget to drive standalone software renderers as well as live gpu.View frame callbacks.
type RenderPassStarter interface {
BeginRenderPass(desc gpu.RenderPassDesc) *gpu.RenderPass
}RenderPassStarter is satisfied by both *gpu.Encoder and *gpu.Frame, allowing CascadedShadowMap.BeginCascadePass to record depth passes both on a standalone gpu.SoftwareRenderer encoder and inside gpu.ViewProps.OnFrame.
type RenderPlan struct {
Opaque []ResolvedDraw
Batches []InstanceBatch
Transparent []ResolvedDraw
Stats RenderStats
}RenderPlan is the deterministic CPU draw plan produced by Queue.Build.
Its slices alias internal buffers owned by Queue to keep steady-state frame builds allocation-free; they remain valid until the next call to Queue.Build.
type RenderStats struct {
TotalItems int
CulledItems int
Occluded int
VisibleItems int
OpaqueDraws int
TransparentDraws int
InstancedBatches int
TotalDrawCalls int
Triangles uint64
Vertices uint64
MaterialSwitches int
PipelineSwitches int
TextureBytes uint64
BufferBytes uint64
}RenderStats captures per-frame culling, batching, state-switch, geometry, and GPU memory telemetry for a RenderPlan (#288).
func (s RenderStats) Add(other RenderStats) RenderStatsAdd combines s and other, useful when aggregating multiple render passes (for example shadow pass + main pass).
func (s RenderStats) Summary() stringSummary returns a concise human-readable diagnostic line for overlays or logs.
type RenderTexture struct {
// contains filtered or unexported fields
}RenderTexture is a scope-owned offscreen GPU render target whose color output is directly sampleable as a material texture via RenderTexture.GPUTexture and BindTexture.
Its underlying *gpu.RenderTarget belongs to the *core.Scope passed to NewRenderTexture and is released when that scope is disposed or earlier via RenderTexture.Close. Use it from the engine goroutine, like the gpu.Device it came from.
func NewRenderTexture(cx *core.Scope, dev *gpu.Device, desc RenderTextureDesc) (*RenderTexture, error)NewRenderTexture validates desc and allocates an offscreen RenderTexture on dev, scoped to cx (nil for headless tests closed explicitly). Invalid descriptors return an error wrapping ErrInvalidRenderTexture before creating any GPU resource; a nil or lost device returns gpu.ErrDeviceLost.
func (rt *RenderTexture) Aspect() float32Aspect returns Width / Height, or zero when either dimension is zero.
func (rt *RenderTexture) BeginFramePass(frame *gpu.Frame, clearColor core.Color) *gpu.RenderPassBeginFramePass begins a gpu.RenderPass on frame targeting rt, clearing color to clearColor and depth (when present) to 1. It returns nil if frame is nil or rt is not valid.
func (rt *RenderTexture) BeginPass(enc *gpu.Encoder, clearColor core.Color) *gpu.RenderPassBeginPass begins a gpu.RenderPass on enc targeting rt, clearing color to clearColor and depth (when present) to 1. It returns nil if enc is nil or rt is not valid.
func (rt *RenderTexture) ByteSize() uint64ByteSize returns the approximate GPU memory occupied by rt's attachments (color, MSAA resolve when present, and optional depth), for RenderStats and Budget accounting. It is zero for a nil receiver.
func (rt *RenderTexture) Close() errorClose releases rt's underlying GPU attachments immediately rather than waiting for its owning scope to dispose. It is safe to call on a nil receiver or more than once.
func (rt *RenderTexture) ColorFormat() gpu.TextureFormatColorFormat returns the resolved color attachment format, or gpu.FormatUndefined for a nil receiver.
func (rt *RenderTexture) ColorTexture() *gpu.TextureColorTexture returns the renderable color attachment *gpu.Texture, or nil for a nil receiver.
func (rt *RenderTexture) DepthFormat() gpu.TextureFormatDepthFormat returns the depth/stencil attachment format, or gpu.FormatUndefined if created without a depth attachment or for a nil receiver.
func (rt *RenderTexture) DepthTexture() *gpu.TextureDepthTexture returns the optional depth/stencil attachment *gpu.Texture, or nil when created without a depth format or for a nil receiver.
func (rt *RenderTexture) GPUTexture() *GPUTextureGPUTexture returns a *GPUTexture view of rt's sampleable color output so it can be passed directly to BindTexture or any material texture slot.
The returned handle is owned by rt; do not close it independently. After a RenderTexture.Resize that returns resized == true, re-fetch GPUTexture and recreate any bind groups built from the previous handle.
func (rt *RenderTexture) Generation() uint64Generation returns a monotonic counter starting at 1 that increments whenever RenderTexture.Resize replaces the underlying GPU textures, letting callers detect when cached BindTexture bind groups must be rebuilt.
func (rt *RenderTexture) Height() uint32Height returns the render texture height in pixels, or zero for a nil receiver.
func (rt *RenderTexture) PassDesc(label string, clearColor core.Color, clearDepth float32) gpu.RenderPassDescPassDesc builds a gpu.RenderPassDesc targeting rt's color (and optional resolve and depth/stencil) attachments, clearing color to clearColor and depth to clearDepth.
func (rt *RenderTexture) Resize(dev *gpu.Device, width, height uint32) (bool, error)Resize reallocates rt's offscreen attachments to width x height on dev, preserving format, sample count, label, retained flag, and owning scope.
When rt is already valid at width x height, Resize is a no-op and returns (false, nil). If allocation of the replacement target fails, the previous target remains intact. On success, the previous target is closed, Generation increments, and (true, nil) is returned so callers know to rebind any BindTexture bind groups referencing the prior texture.
func (rt *RenderTexture) SampleCount() intSampleCount returns the active MSAA sample count (1 or 4), or zero for a nil receiver.
func (rt *RenderTexture) Target() *gpu.RenderTargetTarget returns the underlying *gpu.RenderTarget, or nil for a nil receiver.
func (rt *RenderTexture) Texture() *gpu.TextureTexture returns the single-sampled *gpu.Texture suitable for shader sampling (the MSAA resolve texture when SampleCount > 1, otherwise the color texture), or nil for a nil receiver.
func (rt *RenderTexture) Valid() boolValid reports whether rt is open and its underlying GPU attachments belong to a live device.
func (rt *RenderTexture) Width() uint32Width returns the render texture width in pixels, or zero for a nil receiver.
type RenderTextureDesc struct {
// Label names the offscreen target's GPU attachments in capture tools.
Label string
// Width and Height are the texture dimensions in pixels; both must be positive.
Width uint32
Height uint32
// ColorFormat selects the color attachment format. Zero ([gpu.FormatUndefined]) defaults to [gpu.FormatRGBA8Unorm]. Depth/stencil formats are rejected.
ColorFormat gpu.TextureFormat
// DepthFormat optionally allocates a matching depth (or depth/stencil) attachment for 3D depth testing, such as [gpu.FormatDepth24Plus]. Leave zero ([gpu.FormatUndefined]) for a color-only render texture.
DepthFormat gpu.TextureFormat
// SampleCount sets MSAA sample count: 0 or 1 for single-sampled, or 4 for 4x MSAA with an automatic single-sampled resolve texture exposed via [RenderTexture.Texture] and [RenderTexture.GPUTexture].
SampleCount int
// Retained opts into automatic attachment recreation by NSGo after a GPU device loss so the RenderTexture and any [BindTexture] bind group built from [RenderTexture.GPUTexture] (with a retained sampler) stay valid.
Retained bool
}RenderTextureDesc configures an offscreen render-to-texture target created by NewRenderTexture (for mirrors, minimaps, portals, security cameras, or post-processing).
func (d RenderTextureDesc) Validate() errorValidate checks that d specifies positive dimensions, a valid color format, an optional depth/stencil format, and a supported MSAA sample count (0, 1, or 4). Every error wraps ErrInvalidRenderTexture.
type ResolvedDraw struct {
ID uint64
MeshID uint32
MaterialID uint32
PipelineID uint32
Blend BlendMode
LODIndex int // selected index into DrawItem.LODs, or -1 if LODs is empty
Transform math3d.Mat4
DistanceSq float32
// SortDepth is the center's clip-space depth after perspective divide:
// larger is farther. Ordering by it keeps transparent draws correct
// off-axis and under rotation, where Euclidean distance misorders (#546).
SortDepth float32
Triangles uint32
Vertices uint32
}ResolvedDraw is a visible draw item after frustum culling and LOD selection.
type SSAOConfig struct {
// Radius is the view-space sampling hemisphere radius in world units (> 0). Default: 0.6.
Radius float32
// Bias offsets depth comparisons in view-space units to suppress self-occlusion acne (>= 0). Default: 0.025.
Bias float32
// Intensity scales the occlusion darkening strength in [0, 4]. 0 leaves the scene unchanged. Default: 1.2.
Intensity float32
// Power raises ambient visibility (ao^Power) to tune crevice contrast (> 0). Default: 1.5.
Power float32
// SampleCount is the number of deterministic hemisphere kernel samples in [4, 16]. 0 defaults to 12.
SampleCount int
// BlurRadius is the depth-aware bilateral blur half-width in texels in [0, 4]. 0 disables blur.
BlurRadius int
// DepthThreshold is the view-space depth tolerance for bilateral blur edge preservation (> 0). Default: 0.2.
DepthThreshold float32
// Near and Far are fallback perspective clip planes used only when ProjMatrix is zero; the fallback projection also assumes a 60-degree vertical field of view and the pass's aspect ratio, so set ProjMatrix whenever the camera differs from that.
Near float32
Far float32
// ProjMatrix is the camera's [0, 1] NDC depth projection matrix (e.g. cam.ProjMatrix()). It is captured when the config is set, so refresh it with [SSAOPass.SetConfig] or [PostStack3D.SetCamera] whenever the projection changes, such as after a resize changes the camera's aspect ratio.
ProjMatrix math3d.Mat4
// InvProjMatrix optionally supplies ProjMatrix.Inverse(); when zero, it is computed from ProjMatrix.
InvProjMatrix math3d.Mat4
}SSAOConfig tunes screen-space ambient occlusion from a 3D depth buffer.
func DefaultSSAOConfig() SSAOConfigDefaultSSAOConfig returns balanced defaults for 3D SSAO.
func SSAOConfigFromCamera(cam *scene3d.Camera) SSAOConfigSSAOConfigFromCamera initializes an SSAOConfig using cam's projection matrix and the clip planes that matrix uses, combined with DefaultSSAOConfig quality settings.
func (c SSAOConfig) Validate() errorValidate checks that every field of c is finite and within its valid range. Every error wraps ErrInvalidPostProcess.
type SSAOPass struct {
// contains filtered or unexported fields
}SSAOPass computes screen-space ambient occlusion from a 3D depth texture, optionally filters it with a depth-aware bilateral blur, and multiplies the resulting occlusion factor into a scene color texture.
func NewSSAOPass(cx *core.Scope, dev *gpu.Device, opts SSAOPassOptions) (*SSAOPass, error)NewSSAOPass creates a scope-owned SSAOPass on dev.
func (p *SSAOPass) AOTexture() *gpu.TextureAOTexture returns the most recently computed ambient occlusion texture (blurred when BlurRadius > 0, raw otherwise).
func (p *SSAOPass) Apply(dev *gpu.Device, rec RenderPassRecorder, srcColor, depthTex, dstColor *gpu.Texture) errorApply computes SSAO from depthTex and multiplies it onto srcColor, writing to dstColor. A nil dstColor writes to the swapchain in OutputFormat, and a texture dstColor must be in ColorFormat or OutputFormat. Every texture must have the pass size and dstColor cannot also be an input; otherwise Apply returns an error wrapping ErrInvalidPostProcess.
func (p *SSAOPass) Close() errorClose releases all GPU resources owned by p. It is safe to call on a nil receiver or more than once.
func (p *SSAOPass) ComputeAO(dev *gpu.Device, rec RenderPassRecorder, depthTex *gpu.Texture) (*gpu.Texture, error)ComputeAO evaluates the SSAO hemisphere pass (and optional bilateral blur) from depthTex and returns the resulting AO texture for inspection or custom compositing.
func (p *SSAOPass) Config() SSAOConfigConfig returns the pass's current normalized SSAOConfig.
func (p *SSAOPass) Height() uint32Height returns the configured target height in pixels.
func (p *SSAOPass) Resize(dev *gpu.Device, width, height uint32) errorResize recreates the pass's offscreen AO targets for a new viewport size.
func (p *SSAOPass) SetConfig(cfg SSAOConfig) errorSetConfig validates and updates the SSAO parameters.
func (p *SSAOPass) Valid() boolValid reports whether the pass is open and its GPU resources are live.
func (p *SSAOPass) Width() uint32Width returns the configured target width in pixels.
type SSAOPassOptions struct {
Label string
Width uint32
Height uint32
ColorFormat gpu.TextureFormat // intermediate color format: RGBA16Float (the default), RGBA8Unorm, RGBA8UnormSRGB, BGRA8Unorm or BGRA8UnormSRGB
OutputFormat gpu.TextureFormat // destination format; defaults to dev.SurfaceFormat() or FormatRGBA8Unorm
Retained bool
Config SSAOConfig
}SSAOPassOptions configures NewSSAOPass.
type SamplerOptions struct {
Label string
MinFilter gpu.FilterMode
MagFilter gpu.FilterMode
MipmapFilter gpu.FilterMode
AddressU gpu.AddressMode
AddressV gpu.AddressMode
AddressW gpu.AddressMode
MinLOD float32
MaxLOD float32 // 0 defaults to 32 (unbounded)
MaxAnisotropy uint16 // 0 or 1 disables anisotropic filtering; >1 requires linear min, mag and mipmap filters (WebGPU rule)
Retained bool
}SamplerOptions configures texture filtering and coordinate wrapping for NewGPUSampler.
Its zero value uses nearest filtering and clamp-to-edge wrapping (matching gpu.SamplerDesc). Use SamplerLinearRepeat, SamplerLinearClamp, SamplerLinearMirror, SamplerNearestRepeat or SamplerNearestClamp for common presets.
func KTX2Sampler(data []byte, base SamplerOptions) (SamplerOptions, error)KTX2Sampler returns base with its filters set from the KTX2FilterKey of the KTX2 file in data: "nearest" sets the min, mag and mipmap filters to gpu.FilterNearest and turns anisotropic filtering off, which keeps pixel art sharp, and "linear" sets them to gpu.FilterLinear. A file without the key returns base unchanged. A file whose key/value data cannot be read, or whose filter is neither, returns an error wrapping ErrInvalidTexture.
func SamplerLinearClamp() SamplerOptionsSamplerLinearClamp returns trilinear filtering with clamp-to-edge wrapping, suited to non-repeating textures and UI/decals.
func SamplerLinearMirror() SamplerOptionsSamplerLinearMirror returns trilinear filtering with mirrored-repeat wrapping on U/V/W.
func SamplerLinearRepeat() SamplerOptionsSamplerLinearRepeat returns trilinear filtering with repeating U/V/W coordinates, suited to tiled 3D surfaces.
func SamplerNearestClamp() SamplerOptionsSamplerNearestClamp returns nearest-neighbor filtering with clamp-to-edge wrapping, suited to crisp pixel-art sprites and lookup tables.
func SamplerNearestRepeat() SamplerOptionsSamplerNearestRepeat returns nearest-neighbor filtering with repeating U/V/W coordinates, suited to tiled pixel-art surfaces.
func SamplerOptionsFromGLTF(s gltf.Sampler) (opts SamplerOptions, wantMipmaps bool, err error)SamplerOptionsFromGLTF converts a glTF 2.0 gltf.Sampler into SamplerOptions and reports whether the sampler uses mipmapped minification filtering.
Per the glTF 2.0 specification, omitted wrap modes (0) default to gpu.AddressRepeat, and omitted filter modes (0) default to linear filtering with linear mipmap filtering (wantMipmaps = true). Unknown filter or wrap constants return an error wrapping ErrInvalidSampler.
func (o SamplerOptions) Desc() gpu.SamplerDescDesc converts o into a gpu.SamplerDesc, applying defaults (MaxLOD 0 -> 32, MaxAnisotropy 0 -> 1).
func (o SamplerOptions) Validate() errorValidate checks that every filter mode, address mode, LOD bound and anisotropy setting is valid across all NSGo GPU backends (including WebGPU's requirement that MaxAnisotropy > 1 uses linear min, mag and mipmap filtering). Every error wraps ErrInvalidSampler.
type ShaderLanguage uint8ShaderLanguage identifies the source language of a CustomShaderDesc.
const (
// ShaderWGSL compiles WGSL vertex and fragment stages directly, with optional auto-generated @group(1) MaterialParams and texture bindings.
ShaderWGSL ShaderLanguage = iota
// ShaderKage translates a Kage surface shader (declared package-level var uniforms plus func Surface(...) vec4 or func Fragment(...) vec4) into portable WGSL targeting every NSGo GPU backend.
ShaderKage
)func (l ShaderLanguage) String() stringString returns the canonical lowercase name of l.
func (l ShaderLanguage) Valid() boolValid reports whether l is a recognized shader language.
type ShaderParamDesc struct {
Name string
Kind ShaderParamKind
Default any // optional; nil uses zero (or opaque white for ParamColor and 1x1 white fallback for ParamTexture)
Min *float64 // optional lower bound for numeric parameters (ParamFloat, ParamVec2..4, ParamInt)
Max *float64 // optional upper bound for numeric parameters (ParamFloat, ParamVec2..4, ParamInt)
}ShaderParamDesc declares one typed parameter of a CustomMaterial.
Uniform parameters are packed in declared order into a std140 uniform struct at @group(1) @binding(0). Each ParamTexture parameter allocates a consecutive (texture_2d<f32>, sampler) pair at @group(1) named <Name> and <Name>_sampler.
type ShaderParamKind uint8ShaderParamKind identifies the type of a declared custom material parameter.
const (
ParamFloat ShaderParamKind
ParamVec2
ParamVec3
ParamVec4
ParamColor
ParamInt
ParamBool
ParamTexture
)func (k ShaderParamKind) IsUniform() boolIsUniform reports whether k is stored in the std140 uniform buffer rather than bound as a separate texture/sampler pair.
func (k ShaderParamKind) String() stringString returns the canonical name of k.
func (k ShaderParamKind) UniformLayout() (align, size int)UniformLayout returns the WGSL/std140 alignment and byte size of k inside a uniform struct, or (0, 0) for non-uniform kinds such as ParamTexture. A ParamVec3 is 12 bytes, but ComputeUniformLayout refuses a 4-byte parameter right after one, so the 4 bytes that follow it stay padding on every backend.
func (k ShaderParamKind) Valid() boolValid reports whether k is a supported parameter kind.
func (k ShaderParamKind) WGSLType() stringWGSLType returns the portable WGSL type emitted for k in MaterialParams or texture bindings. ParamBool uses u32 (0 or 1) because WGSL uniform buffers forbid host-unshareable bool fields.
type ShadowDepthGrid struct {
Width int
Height int
Depths []float32
}ShadowDepthGrid is a CPU-readable row-major [0, 1] depth map (top-to-bottom, index y*Width + x) matching the layout returned by gpu.Device.ReadTexture on a gpu.FormatDepth32Float shadow map.
func ShadowDepthGridFromBytes(width, height int, raw []byte) (ShadowDepthGrid, error)ShadowDepthGridFromBytes decodes raw little-endian float32 depth readback bytes into a ShadowDepthGrid. Every error wraps ErrInvalidShadow.
type ShadowFilter uint8ShadowFilter selects the shadow-map sampling kernel.
const (
// ShadowFilterHard evaluates a single nearest-neighbor depth comparison tap (crisp texel-aligned shadow edges).
ShadowFilterHard ShadowFilter = iota
// ShadowFilterPCF3x3 averages a 3x3 grid of 9 percentage-closer comparison taps (using a linear comparison sampler for 2x2 hardware bilinear PCF per tap) for smooth penumbra transitions.
ShadowFilterPCF3x3
)func (f ShadowFilter) String() stringString returns a human-readable name for f.
type ShadowMapOptions struct {
// Label prefixes GPU resources in capture tools.
Label string
// Resolution is the shadow map width and height in texels (power of two in [MinShadowResolution, MaxShadowResolution]). Zero defaults to [DefaultShadowResolution] (1024).
Resolution uint32
// PCFKernel selects the initial filtering mode ([ShadowFilterHard] or [ShadowFilterPCF3x3]); it can also be switched dynamically per frame via [DirectionalShadowMap.WriteUniforms].
PCFKernel ShadowFilter
// DepthBias is the hardware rasterizer constant depth bias applied during the shadow depth pass.
DepthBias int32
// DepthBiasSlopeScale is the hardware rasterizer slope-scaled depth bias applied during the shadow depth pass.
DepthBiasSlopeScale float32
// CullMode selects face culling during the shadow depth pass (gpu.CullNone, gpu.CullBack, or gpu.CullFront).
CullMode gpu.CullMode
// MaxCasters is the maximum number of [DirectionalShadowMap.DrawCaster] calls per shadow pass. Zero defaults to [DefaultShadowMaxCasters] (256).
MaxCasters uint32
// Retained keeps the offscreen shadow render target, uniform buffers, samplers, bind groups, and depth pipeline alive across GPU device loss.
Retained bool
}ShadowMapOptions configures NewDirectionalShadowMap.
func DefaultShadowMapOptions() ShadowMapOptionsDefaultShadowMapOptions returns recommended options for NewDirectionalShadowMap: 1024x1024 depth map, 3x3 PCF filtering, hardware depth bias (2, 2.0), back-face culling, and 256 caster slots.
func (o ShadowMapOptions) Validate() errorValidate checks that every field of o is valid across all NSGo GPU backends. Every error wraps ErrInvalidShadow.
type ShadowPassTarget interface {
BeginRenderPass(desc gpu.RenderPassDesc) *gpu.RenderPass
}ShadowPassTarget is implemented by both *gpu.Encoder and *gpu.Frame, allowing DirectionalShadowMap.BeginShadowPass to record a shadow depth pass on either headless encoders or live gpu.View frames.
type ShadowUniforms struct {
// LightViewProj transforms world-space points into light clip space with [0, 1] depth.
LightViewProj math3d.Mat4
// LightDirection is the unit direction light rays travel (from the light toward the scene). Encoded into the WGSL uniform as to_light = -LightDirection so shaders compute dot(N, shadow.to_light.xyz) directly.
LightDirection math3d.Vec3
// Strength scales shadow darkness in [0, 1].
Strength float32
// DepthBias is the receiver clip-space depth bias.
DepthBias float32
// NormalBias is the world-space normal offset applied before projecting into light space.
NormalBias float32
// TexelSize is 1 / resolution in UV units, used for 3x3 PCF tap offsets.
TexelSize float32
// PCFKernel selects [ShadowFilterHard] or [ShadowFilterPCF3x3].
PCFKernel ShadowFilter
}ShadowUniforms is the per-frame directional shadow uniform block matching ShadowWGSL byte for byte (ShadowUniformSize = 96 bytes).
func (u ShadowUniforms) Encode(dst []byte) []byteEncode writes u into dst as the little-endian ShadowUniformSize-byte block declared by ShadowWGSL and returns dst[:ShadowUniformSize]. It panics if len(dst) is less than ShadowUniformSize.
type SkinPaletteOptions struct {
// Label names the uniform buffer, bind group layout, and bind group in GPU capture tools.
Label string
// Retained keeps a CPU shadow copy of the palette uniform buffer so NSGo restores it with the latest joint matrices after a device loss.
Retained bool
}SkinPaletteOptions configures NewGPUSkinPalette.
type SkinnedMesh struct {
Positions []math3d.Vec3
Normals []math3d.Vec3
UVs []math3d.Vec2
Joints [][4]uint16
Weights []math3d.Vec4
Indices []uint32
JointCount int
}SkinnedMesh is indexed or non-indexed triangle-list geometry with up to four joint influences per vertex, ready to upload with UploadSkinnedMesh.
Positions, Joints, and Weights are required and must have equal length. Normals and UVs are optional (empty or one entry per position). Indices is optional (empty for non-indexed triangle lists). JointCount optionally records the skin's joint count; when > 0, SkinnedMesh.Validate enforces that every joint index is strictly less than JointCount (and JointCount <= MaxSkinJoints). When JointCount == 0, every joint index must be strictly less than MaxSkinJoints.
func SkinnedMeshFromGLTF(prim gltf.Primitive, skin gltf.Skin) (SkinnedMesh, error)SkinnedMeshFromGLTF extracts and validates a SkinnedMesh from a glTF 2.0 triangle primitive and its associated skin, normalizing vertex weights so their four components sum to 1. Geometry errors wrap ErrInvalidMesh and skinning errors wrap ErrInvalidSkin.
func SkinnedMeshesFromGLTFNode(doc *gltf.Document, nodeIndex int) ([]SkinnedMesh, error)SkinnedMeshesFromGLTFNode extracts every triangle primitive of doc's skinned mesh node at nodeIndex against its referenced skin.
func (m SkinnedMesh) AppendIndexData(dst []byte) []byteAppendIndexData appends m's indices to dst at SkinnedMesh.IndexFormat width, little-endian and zero-padded to a 4-byte multiple, allocating only when dst lacks capacity.
func (m SkinnedMesh) AppendVertexData(dst []byte) []byteAppendVertexData appends m's skinned vertices to dst in the little-endian interleaved layout of SkinnedVertexLayout and returns the extended slice. Missing normals and UVs are written as zeros; joint weights are normalized via NormalizeSkinWeights so every vertex sums to 1. It allocates only when dst lacks capacity for SkinnedMesh.VertexDataSize more bytes. Call SkinnedMesh.Validate before encoding untrusted data.
func (m SkinnedMesh) Bounds() math3d.AABBBounds returns the axis-aligned box around the unskinned m.Positions in the mesh's own space, or math3d.AABBEmpty when m has none. It is not where the mesh is drawn: the skinned pipelines place vertices with the joint matrices, which move, rotate and animate them, so cull and frame a skinned mesh with SkinnedBounds instead.
func (m SkinnedMesh) IndexDataSize() intIndexDataSize returns the 4-byte-padded byte length SkinnedMesh.AppendIndexData appends, or zero for a non-indexed mesh.
func (m SkinnedMesh) IndexFormat() gpu.IndexFormatIndexFormat returns gpu.IndexUint16 when every vertex fits below 0xFFFF (avoiding WebGL 2's fixed primitive restart index), otherwise gpu.IndexUint32.
func (m SkinnedMesh) Indexed() boolIndexed reports whether m has an index list.
func (m SkinnedMesh) Validate() errorValidate checks both the triangle geometry (wrapping ErrInvalidMesh) and the skinning attributes (wrapping ErrInvalidSkin): matching Joints and Weights counts, JointCount in [0, MaxSkinJoints], finite non-negative weights, and every joint index strictly below JointCount (or MaxSkinJoints when JointCount == 0).
func (m SkinnedMesh) VertexCount() intVertexCount returns the number of vertices, len(m.Positions).
func (m SkinnedMesh) VertexDataSize() intVertexDataSize returns the byte length SkinnedMesh.AppendVertexData appends.
type SkinnedMeshPipelineOptions struct {
// Label names the render pipeline in GPU capture tools.
Label string
// ColorFormat overrides the color attachment format; when FormatUndefined, dev.SurfaceFormat() is used.
ColorFormat gpu.TextureFormat
// DepthFormat enables depth testing and depth writes when not FormatUndefined.
DepthFormat gpu.TextureFormat
// DoubleSided disables back-face culling when true; by default CCW front faces are kept and back faces are culled.
DoubleSided bool
// SampleCount sets the MSAA sample count (0 defaults to 1).
SampleCount int
// Retained keeps the pipeline descriptor so NSGo recreates it after device loss.
Retained bool
}SkinnedMeshPipelineOptions configures NewSkinnedMeshPipeline.
type SkyboxPipeline struct {
// contains filtered or unexported fields
}SkyboxPipeline renders any GPUCubemap as a fullscreen background skybox without a vertex buffer. Create it once in OnReady, bind a cubemap with SkyboxPipeline.BindCubemap, update the view each frame with SkyboxPipeline.WriteCamera or SkyboxPipeline.Write, and record the draw with SkyboxPipeline.Draw.
func NewSkyboxPipeline(cx *core.Scope, dev *gpu.Device, desc SkyboxPipelineDesc) (*SkyboxPipeline, error)NewSkyboxPipeline compiles SkyboxWGSL and creates the skybox render pipeline, bind group layout, and uniform buffer on dev, scoped to cx.
func (s *SkyboxPipeline) BindCubemap(cx *core.Scope, cube *GPUCubemap) (*gpu.BindGroup, error)BindCubemap creates a gpu.BindGroup pairing the pipeline's uniform buffer with cube's texture and sampler. When both the pipeline and cube were created with Retained: true, NSGo restores this bind group automatically after a device loss.
func (s *SkyboxPipeline) Close() errorClose releases the pipeline, layout, and uniform buffer. Safe to call more than once.
func (s *SkyboxPipeline) Draw(pass *gpu.RenderPass, group *gpu.BindGroup)Draw binds the skybox pipeline and cubemap bind group and issues the single fullscreen-triangle draw (3 vertices, no vertex buffer). It records nothing if either the pipeline or group is invalid.
func (s *SkyboxPipeline) Layout() *gpu.BindGroupLayoutLayout returns the skybox gpu.BindGroupLayout.
func (s *SkyboxPipeline) Pipeline() *gpu.PipelinePipeline returns the underlying gpu.Pipeline.
func (s *SkyboxPipeline) SetDevice(dev *gpu.Device)SetDevice updates the device handle used by SkyboxPipeline.Write and SkyboxPipeline.BindCubemap after a retained pipeline is restored on a new device in OnReady.
func (s *SkyboxPipeline) Valid() boolValid reports whether the pipeline, layout, and uniform buffer are open and belong to a live device.
func (s *SkyboxPipeline) Write(u SkyboxUniform)Write uploads u to the skybox uniform buffer. It encodes into storage the SkyboxPipeline owns, so the only copy made is the one gpu.Device.WriteBuffer takes of the bytes it queues.
func (s *SkyboxPipeline) WriteCamera(cam *scene3d.Camera)WriteCamera uploads cam's rotation and projection to the skybox uniform buffer with Exposure = 1 and LOD = 0.
type SkyboxPipelineDesc struct {
// Label names the GPU pipeline, uniform buffer, and layout in capture tools.
Label string
// ColorFormat is the render target color format; defaults to dev.SurfaceFormat() when [gpu.FormatUndefined].
ColorFormat gpu.TextureFormat
// DepthFormat is the depth attachment format (for example [gpu.FormatDepth24Plus]). Leave [gpu.FormatUndefined] for color-only passes. When set, the pipeline uses [gpu.CompareLessEqual] with DepthWrite disabled and [SkyboxWGSL] emits depth 1.0, so the skybox drawn after opaque geometry stays behind everything nearer than the far plane.
DepthFormat gpu.TextureFormat
// SampleCount is the MSAA sample count (0 or 1 for non-MSAA, 4 for 4x MSAA).
SampleCount int
// ToneMap compiles [SkyboxToneMapWGSL] instead of [SkyboxWGSL], applying Reinhard tone mapping and gamma 2.2 encoding after [SkyboxUniform].Exposure so an HDR [GPUCubemap] can draw directly to an LDR surface alongside [MaterialWGSL] or [MaterialIBLWGSL]. Leave false when rendering into an [HDRTarget] resolved by [ToneMapPass] or when drawing an already display-encoded LDR cubemap.
ToneMap bool
// Retained opts the pipeline and uniform buffer into automatic recreation after a GPU device loss.
Retained bool
}SkyboxPipelineDesc configures NewSkyboxPipeline.
type SkyboxUniform struct {
InvViewProj math3d.Mat4
Exposure float32
LOD float32
}SkyboxUniform is the per-frame data SkyboxWGSL reads: the inverse of Proj * ViewRotation (camera view with translation stripped) plus exposure and mip LOD.
func NewSkyboxUniform(cam *scene3d.Camera) SkyboxUniformNewSkyboxUniform builds a SkyboxUniform from cam's current rotation and projection with Exposure = 1 and LOD = 0. Camera translation is removed so the skybox stays infinitely far away as the viewer moves.
func NewSkyboxUniformFromMatrices(view, proj math3d.Mat4) SkyboxUniformNewSkyboxUniformFromMatrices builds a SkyboxUniform from raw view and projection matrices with translation stripped from view, Exposure = 1, and LOD = 0.
func (u *SkyboxUniform) Encode(dst []byte) []byteEncode writes u into dst as the little-endian SkyboxUniformSize-byte block declared by SkyboxWGSL and returns dst[:SkyboxUniformSize]. It panics if len(dst) < SkyboxUniformSize.
type SpotLight struct {
Position math3d.Vec3
Direction math3d.Vec3
Color math3d.Vec3
Intensity float32
Range float32
InnerConeAngle float32
OuterConeAngle float32
}SpotLight is a punctual cone-shaped emitter at Position shining along Direction, following glTF KHR_lights_punctual.
Direction is the world-space direction the cone points in (the light travels along it); it does not need to be unit length and is normalized when shaded or packed for the GPU. Color is linear RGB tint (non-negative finite channels) and Intensity scales Color to produce linear radiant intensity. Range windows the distance falloff exactly as it does for a PointLight (0 for pure inverse-square falloff). InnerConeAngle and OuterConeAngle are half-angles in radians from Direction with 0 <= InnerConeAngle < OuterConeAngle <= pi/2: surfaces inside the inner cone receive the full intensity, which then falls off smoothly to zero at the outer cone (see SpotConeAttenuation).
func (l SpotLight) Attenuation(worldPos math3d.Vec3) float32Attenuation returns the combined distance and cone attenuation l applies at worldPos: PointLightAttenuation with l.Range times SpotConeAttenuation. It is 0 for a degenerate direction or when worldPos coincides with the light, and multiplying it by Color * Intensity gives the incident radiance ShadePoint uses for l.
func (l SpotLight) ConeScaleOffset() (angleScale, angleOffset float32)ConeScaleOffset returns the angular attenuation terms glTF KHR_lights_punctual precomputes per light: angleScale = 1 / max(cos(InnerConeAngle) - cos(OuterConeAngle), 0.001) and angleOffset = -cos(OuterConeAngle) * angleScale. SpotConeAttenuation takes them, and the GPU light block stores them next to each spot light.
func (l SpotLight) Validate() errorValidate reports whether l has a finite position, a finite non-zero direction, finite non-negative color channels, intensity and range, and cone half-angles with 0 <= InnerConeAngle < OuterConeAngle <= pi/2, the bounds glTF KHR_lights_punctual sets. Every error wraps ErrInvalidLight.
type SpotShadowConfig struct {
// Resolution is the width and height of the square depth shadow map in texels. Zero defaults to 1024.
Resolution uint32
// Near is the near plane distance of the shadow projection. Zero defaults to [DefaultLocalShadowNear].
Near float32
// Far is the far plane distance used when the spot light's Range is 0; a light with a Range uses that instead. Zero defaults to [DefaultLocalShadowFar].
Far float32
// DepthBias subtracts a constant NDC [0, 1] bias during depth comparison to avoid shadow acne. [DefaultSpotShadowConfig] sets 0.0015; zero disables it.
DepthBias float32
// NormalBias offsets the shaded world position along its surface normal before projecting into light space.
NormalBias float32
// Filter selects hard single-tap or 3x3 PCF comparison sampling.
Filter LocalShadowFilter
// CullMode sets face culling for the shadow caster pass (default gpu.CullNone).
CullMode gpu.CullMode
// MaxCasters is the maximum number of [SpotShadowMap.DrawCaster] calls per shadow pass, at most [MaxLocalShadowCasters]. Zero defaults to [DefaultLocalShadowMaxCasters].
MaxCasters uint32
// Label names GPU resources in capture tools.
Label string
// Retained keeps resources across GPU device loss and restore.
Retained bool
}SpotShadowConfig configures a perspective 2D SpotShadowMap.
func DefaultSpotShadowConfig() SpotShadowConfigDefaultSpotShadowConfig returns a ready-to-use 1024x1024 PCF 3x3 spot shadow configuration.
func (c SpotShadowConfig) Normalized() SpotShadowConfigNormalized returns a copy of c with zero Resolution, Near, Far and MaxCasters filled with defaults.
func (c SpotShadowConfig) Validate() errorValidate checks that c's planes, biases, filter, cull mode and caster count are valid. Every error wraps ErrInvalidLocalShadow.
type SpotShadowMap struct {
// contains filtered or unexported fields
}SpotShadowMap manages a depth-only perspective 2D shadow map, its depth caster pipeline and its sampling bind group for the first spot light of a LightRig.
Create it once when the GPU device is ready (Retained: true survives device loss), call SpotShadowMap.Update with the rig's spot light, record casters between SpotShadowMap.BeginShadowPass and pass.End(), and bind SpotShadowMap.BindGroup at LocalShadowGroup when drawing with NewLitPBRSpotShadowPipeline. Its resources belong to the *core.Scope passed to NewSpotShadowMap.
func NewSpotShadowMap(cx *core.Scope, dev *gpu.Device, cfg SpotShadowConfig) (*SpotShadowMap, error)NewSpotShadowMap creates a depth-only perspective spot shadow map and its GPU resources scoped to cx. Invalid configuration, a resolution above the device's MaxTextureDimension2D, or a caster buffer above its MaxBufferSize returns an error wrapping ErrInvalidLocalShadow; device errors are returned as gpu.Error.
func (s *SpotShadowMap) BeginShadowPass(dev *gpu.Device, target ShadowPassTarget) *gpu.RenderPassBeginShadowPass resets the caster slot cursor, begins a depth-only render pass on target (a *gpu.Encoder or *gpu.Frame) clearing the spot shadow map to 1.0, sets the full viewport and scissor, and binds the depth pipeline. Record at most one shadow pass per submission. It returns nil when s, dev or target is nil or s is invalid, so check the result before drawing casters and calling End.
func (s *SpotShadowMap) BindGroup() *gpu.BindGroupBindGroup returns the bind group to set at LocalShadowGroup, or at the group passed to SpotShadowWGSLForGroup, during the lit render pass.
func (s *SpotShadowMap) ByteSize() uint64ByteSize returns the GPU memory held by the depth texture and uniform buffers.
func (s *SpotShadowMap) Close() errorClose releases all GPU resources owned by s. It is safe to call on a nil receiver or more than once.
func (s *SpotShadowMap) Config() SpotShadowConfigConfig returns the normalized SpotShadowConfig.
func (s *SpotShadowMap) DepthTexture() *gpu.TextureDepthTexture returns the underlying Depth32Float gpu.Texture.
func (s *SpotShadowMap) DrawCaster(pass *gpu.RenderPass, mesh *GPUMesh, model math3d.Mat4) boolDrawCaster records a shadow caster draw for mesh transformed by model inside the pass started by SpotShadowMap.BeginShadowPass. Each call uses its own 256-byte dynamic-offset uniform slot, so casters drawn in one pass never overwrite each other's transforms. It returns false and draws nothing when an argument is invalid, SpotShadowMap.Update has not been called yet, or SpotShadowMap.MaxCasters casters were already drawn in this pass.
func (s *SpotShadowMap) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout for sampling this spot shadow map (binding 0: SpotShadow uniform, binding 1: texture_depth_2d, binding 2: sampler_comparison).
func (s *SpotShadowMap) MaxCasters() uint32MaxCasters returns the number of SpotShadowMap.DrawCaster calls one shadow pass accepts.
func (s *SpotShadowMap) RenderTarget() *gpu.RenderTargetRenderTarget returns the underlying depth-only gpu.RenderTarget.
func (s *SpotShadowMap) Sampler() *gpu.SamplerSampler returns the comparison gpu.Sampler bound in SpotShadowMap.BindGroup.
func (s *SpotShadowMap) Uniforms() SpotShadowUniformUniforms returns the last spot shadow uniform data written via SpotShadowMap.Update.
func (s *SpotShadowMap) Update(dev *gpu.Device, light SpotLight) errorUpdate computes the shadow projection for the LightRig spot light light (see NewSpotShadowUniform) and writes the uniform buffer on dev without heap allocations.
func (s *SpotShadowMap) Valid() boolValid reports whether all underlying GPU resources are open and live.
type SpotShadowUniform struct {
// ViewProj is the spot light's [0, 1]-depth perspective view-projection matrix.
ViewProj math3d.Mat4
DepthBias float32
NormalBias float32
InvResolution float32
// FilterMode is 0 for [LocalShadowFilterHard] and 1 for [LocalShadowFilterPCF3x3].
FilterMode float32
}SpotShadowUniform is the packed uniform data matching the WGSL SpotShadow block declared by SpotShadowWGSL.
func NewSpotShadowUniform(light SpotLight, cfg SpotShadowConfig) (SpotShadowUniform, error)NewSpotShadowUniform computes the shadow uniform data for the LightRig spot light light under cfg. The projection's far plane is light.Range, or cfg.Far when Range is 0. It returns an error wrapping ErrInvalidLight when light is invalid, and one wrapping ErrInvalidLocalShadow when cfg is invalid, the cone is wider than MaxSpotShadowConeAngle, or the far plane is not beyond the near plane.
func (u *SpotShadowUniform) Encode(dst []byte) []byteEncode writes u into dst in the little-endian layout declared by SpotShadowWGSL and returns dst[:SpotShadowUniformSize]. It allocates nothing and panics if len(dst) < SpotShadowUniformSize.
type SurfaceDesc struct {
// Width and Height in pixels. In [ViewportRenderer.RenderFrame], leaving either non-positive fills both from frame.Size().
Width int
Height int
// HasDepth attaches the surface's depth buffer when true (set true when gpu.ViewProps.DepthFormat or gpu.NewSoftwareRenderer's depth format is set).
HasDepth bool
// ClearColor is the fallback clear color for the main surface when the first main-surface view has a zero ClearColor.
ClearColor core.Color
// ClearDepth is the fallback depth clear value for the main surface (0 defaults to 1).
ClearDepth float32
}SurfaceDesc describes the main on-screen render surface passed to ViewportRenderer.RenderEncoder or ViewportRenderer.RenderFrame.
type TerrainEvalInput struct {
Material TerrainMaterial
// Splat0 holds the RGBA weights from SplatMap0 (layers 0..3).
Splat0 [4]float32
// Splat1 holds the RGBA weights from SplatMap1 (layers 4..7).
Splat1 [4]float32
// Samples holds optional per-layer planar samples (indexed by layer index).
Samples []TerrainEvalLayerSample
// TriplanarX, TriplanarY, TriplanarZ hold optional per-layer samples along the X, Y, Z projection planes when Triplanar.Enabled is true.
TriplanarX []TerrainEvalLayerSample
TriplanarY []TerrainEvalLayerSample
TriplanarZ []TerrainEvalLayerSample
// WorldPos is the fragment world-space position.
WorldPos math3d.Vec3
// Normal is the geometric world-space normal.
Normal math3d.Vec3
// Tangent and Bitangent optionally supply the planar tangent frame; derived from Normal when zero.
Tangent math3d.Vec3
Bitangent math3d.Vec3
// ViewDir points from WorldPos toward the camera.
ViewDir math3d.Vec3
// Rig is the scene [LightRig].
Rig LightRig
// ShadowVisibility attenuates directional light 0 in [0, 1] (0 defaults to 1 unless UseShadowVisibility is true).
ShadowVisibility float32
UseShadowVisibility bool
}TerrainEvalInput provides per-fragment inputs to EvaluateTerrainMaterial, matching TerrainMaterialWGSL and TerrainMaterialShadowWGSL.
type TerrainEvalLayerSample struct {
// AlbedoLinear is the linear RGB base-color sample (defaults to [1, 1, 1] when HasAlbedo is false).
AlbedoLinear [3]float32
HasAlbedo bool
// MetallicSample is the metallic-roughness texture B channel (defaults to 1 when HasMetallicRoughness is false).
MetallicSample float32
// RoughnessSample is the metallic-roughness texture G channel (defaults to 1 when HasMetallicRoughness is false).
RoughnessSample float32
HasMetallicRoughness bool
// NormalSample is the UNORM [0, 1] tangent-space normal sample (defaults to [0.5, 0.5, 1] when HasNormal is false).
NormalSample [3]float32
HasNormal bool
// HeightSample is the normalized [0, 1] height-map sample (defaults to 0.5 when HasHeight is false).
HeightSample float32
HasHeight bool
}TerrainEvalLayerSample holds per-layer sampled texel values for the pure-Go CPU reference evaluator EvaluateTerrainMaterial.
type TerrainEvalResult struct {
Weights [MaxTerrainLayers]float32
TriplanarFactor float32
BaseColor math3d.Vec3
Normal math3d.Vec3
Metallic float32
Roughness float32
Linear math3d.Vec3
SRGB math3d.Vec3
}TerrainEvalResult holds the CPU reference output from EvaluateTerrainMaterial.
func EvaluateTerrainMaterial(in TerrainEvalInput) TerrainEvalResultEvaluateTerrainMaterial is the pure-Go CPU reference matching TerrainMaterialWGSL and TerrainMaterialShadowWGSL so tests can verify GPU renders against an exact analytical reference.
type TerrainLayer struct {
Name string
BaseColorFactor [3]float32
AlbedoImage image.Image
NormalImage image.Image
MetallicRoughnessImage image.Image
HeightImage image.Image
RoughnessFactor float32
MetallicFactor float32
NormalScale float32
UVScale math3d.Vec2
HeightBias float32
}TerrainLayer describes one PBR surface layer inside a TerrainMaterial.
Texture channel conventions match glTF 2.0 plus an optional grayscale height map:
- AlbedoImage: sRGB color texture multiplied by BaseColorFactor (defaults to solid white).
- NormalImage: linear tangent-space normal map (+X right/+U, +Y up/-V, +Z out; defaults to flat (128,128,255)).
- MetallicRoughnessImage: linear texture where G = roughness and B = metallic (defaults to white).
- HeightImage: linear grayscale height map used for height-based blending (defaults to 0.5).
func DefaultTerrainLayer(name string) TerrainLayerDefaultTerrainLayer returns a TerrainLayer initialized with natural dielectric outdoor terrain defaults: white linear tint, roughness 0.85, metallic 0, normal scale 1, UV scale (1, 1), and height bias 0.
type TerrainMaterial struct {
// Model transforms terrain vertices into world space; the zero matrix defaults to identity.
Model math3d.Mat4
// Layers defines 1 to 8 PBR terrain material layers in splat-channel order:
// layers 0..3 read SplatMap0 (R, G, B, A); layers 4..7 read SplatMap1 (R, G, B, A).
Layers []TerrainLayer
// SplatMap0 provides RGBA weights for layers 0..3. When nil, defaults to 1x1 (255, 0, 0, 0).
SplatMap0 image.Image
// SplatMap1 provides RGBA weights for layers 4..7. Required when len(Layers) > 4 unless nil defaults to 1x1 (0, 0, 0, 0).
SplatMap1 image.Image
// HeightBlendContrast controls height-based layer blending in [0, 1]: 0 uses
// linear splat blending; higher values produce sharper transitions driven by
// each layer's HeightImage and HeightBias.
HeightBlendContrast float32
// Triplanar configures slope-driven triplanar projection on steep terrain faces.
Triplanar TerrainTriplanar
// LayerTextureSize optionally sets the square texel width and height of the
// GPU 2D texture arrays backing the layer maps. When 0, the size is inferred
// from the first non-nil layer image (or 1 when all layers are solid colors).
// Any layer image with different dimensions is bilinearly resampled to match.
LayerTextureSize int
}TerrainMaterial describes a splat-map-driven multi-layer PBR terrain surface supporting up to 8 layers, optional height-based layer blending, and optional triplanar projection on steep slopes.
func TerrainMaterialFromDoc(fsys fs.FS, doc *world3d.TerrainDoc) (TerrainMaterial, error)TerrainMaterialFromDoc loads a TerrainMaterial from doc and fsys, decoding either packed RGBA splat maps (doc.SplatMaps) or per-layer grayscale weight maps (layers[i].WeightMap packed via world3d.PackLayerWeightMaps), optional material resource files (layers[i].Material), and per-layer PBR textures.
The returned material is validated and ready for NewGPUTerrainMaterial or EvaluateTerrainMaterial, blending layers identically to world3d.Heightmap.LayerAt.
func (m TerrainMaterial) AppendUniformData(dst []byte) []byteAppendUniformData appends m's 544-byte uniform block to dst without allocating when dst has sufficient spare capacity.
func (m TerrainMaterial) EncodeUniforms(dst []byte) []byteEncodeUniforms encodes m's uniform block into dst[:TerrainMaterialUniformSize] in the exact 16-byte-aligned layout declared by TerrainMaterialBindingsWGSL. It panics if len(dst) < TerrainMaterialUniformSize.
func (m TerrainMaterial) Validate() errorValidate checks that every field of m is finite and within valid ranges. Every error wraps ErrInvalidTerrainMaterial.
type TerrainMaterialUpload struct {
// Label prefixes GPU resource debug labels.
Label string
// Mipmaps generates CPU mip chains for the layer texture arrays.
Mipmaps bool
// Retained keeps CPU shadow copies of every GPU buffer, texture, sampler, and bind group so NSGo restores them across device loss.
Retained bool
}TerrainMaterialUpload configures NewGPUTerrainMaterial.
type TerrainPipelineOptions struct {
// Label names the pipeline in GPU capture tools.
Label string
// ColorFormat sets the color attachment format; [gpu.FormatUndefined] defaults to dev.SurfaceFormat().
ColorFormat gpu.TextureFormat
// DepthFormat enables depth testing and depth writes when non-zero.
DepthFormat gpu.TextureFormat
// DoubleSided disables back-face culling when true.
DoubleSided bool
// ShadowLayout, when set, compiles [TerrainMaterialShadowWGSL] with a [DirectionalShadowMap] at [ShadowGroup] (group 3).
ShadowLayout *gpu.BindGroupLayout
// CSMLayout, when set, compiles [TerrainMaterialCSMWGSL] with a [CascadedShadowMap] at [CSMGroup] (group 3).
CSMLayout *gpu.BindGroupLayout
// FogLayout, when set, compiles [TerrainMaterialFogWGSL] with a [GPUFogBuffer] at [FogGroup] (group 3).
FogLayout *gpu.BindGroupLayout
// LinearOutput skips sRGB encoding and writes linear radiance directly, for drawing into an [HDRTarget] resolved by [ToneMapPass].
LinearOutput bool
}TerrainPipelineOptions configures NewTerrainMaterialPipeline.
type TerrainTriplanar struct {
// Enabled activates triplanar projection when abs(world_normal.y) drops below SlopeThreshold.
Enabled bool
// SlopeThreshold is the world normal Y threshold in [0, 1] below which triplanar mapping blends in (0 defaults to 0.70, ~45°).
SlopeThreshold float32
// SlopeBlend is the transition width in [0, 1] over which planar UVs cross-fade into triplanar UVs (0 defaults to 0.15).
SlopeBlend float32
// Sharpness controls triplanar axis blend sharpness (> 0; 0 defaults to 4.0).
Sharpness float32
// Scale is the world-space repeat rate before per-layer UVScale (> 0; 0 defaults to 0.25).
Scale float32
}TerrainTriplanar configures slope-driven triplanar projection on steep terrain faces to eliminate UV stretching on cliffs.
func DefaultTerrainTriplanar() TerrainTriplanarDefaultTerrainTriplanar returns recommended triplanar projection settings for cliffs steeper than ~45°.
type TextureMipData struct {
MipLevel uint32
ArrayLayer uint32
Data []byte
BytesPerRow uint32 // 0 means tightly packed for the mip width and format
}TextureMipData is one mip level (and optional array layer / cubemap face) of texel or compressed block bytes for RawTextureUpload.
type TextureUpload struct {
// Label names the texture in GPU capture tools.
Label string
// SRGB stores RGBA8 channels in [gpu.FormatRGBA8UnormSRGB] so the GPU decodes RGB to linear light when sampling. Set it for color textures (base color / albedo, emissive); leave it false for data textures (normal, metallic-roughness, occlusion).
SRGB bool
// Mipmaps builds a CPU mipmap chain (box-filtered in linear light when SRGB is true) and uploads every level, so mipmapping works on every GPU backend including those without GPU mipmap generation.
Mipmaps bool
// MaxMipLevels caps the mipmap chain when Mipmaps is true; zero generates the full chain down to 1x1.
MaxMipLevels uint32
// Retained keeps a CPU copy of the texture and its uploaded mip levels so NSGo recreates them after a device loss (see [gpu.TextureDesc].Retained).
Retained bool
}TextureUpload configures UploadTexture and UploadTexturePixels.
type ToneMapOperator uint8ToneMapOperator selects the HDR-to-LDR tone mapping curve applied by ApplyToneMap and ToneMapPass (#250).
const (
// ToneMapNone applies exposure only and clamps linear RGB to [0, 1] with no highlight roll-off.
ToneMapNone ToneMapOperator = iota
// ToneMapReinhard applies per-channel Reinhard compression: c / (1 + c).
ToneMapReinhard
// ToneMapACES applies Krzysztof Narkowicz's fitted ACES filmic curve: (c*(2.51*c + 0.03)) / (c*(2.43*c + 0.59) + 0.14).
ToneMapACES
// ToneMapNeutral applies the Khronos PBR Neutral tone mapper, preserving mid-tone hues and smoothly desaturating bright highlights toward white.
ToneMapNeutral
// ToneMapAgX applies Troy Sobotka's AgX default look (inset matrix, log2 range mapping, 6th-order polynomial sigmoid, outset matrix, and display linearization), avoiding hue skew in bright saturated highlights.
ToneMapAgX
)func (op ToneMapOperator) String() stringString returns the lower-case name of op, or "unknown" for out-of-range values.
func (op ToneMapOperator) Valid() boolValid reports whether op is a known tone mapping operator.
type ToneMapOptions struct {
// Operator selects the tone mapping curve. The zero value is [ToneMapNone]; use [DefaultToneMapOptions] for the recommended [ToneMapACES] preset.
Operator ToneMapOperator
// Exposure is the linear exposure multiplier applied before tone mapping. Zero renders black, so a fade to black can interpolate it down to 0; negative, NaN and infinite values are treated as 1.0 (0 EV). Compute it from photographic stops with [ExposureFromEV], and start from [DefaultToneMapOptions] so the zero value of this field does not leave the image black.
Exposure float32
// Gamma selects the display transfer function when LinearOutput is false: zero (or non-positive / non-finite) applies the exact IEC 61966-2-1 linear-to-sRGB OETF; a positive finite value (for example 2.2) applies power-law encoding pow(c, 1/Gamma).
Gamma float32
// LinearOutput skips display OETF encoding and emits tone-mapped linear RGB in [0, 1]. [ToneMapPass] automatically enables linear output when its target format is sRGB (TargetFormat.IsSRGB()) so GPU hardware encodes linear-to-sRGB exactly once without double gamma.
LinearOutput bool
}ToneMapOptions configures exposure, tone mapping, and display gamma encoding for ApplyToneMap, AppendToneMapUniforms, and ToneMapPass (#250).
func DefaultToneMapOptions() ToneMapOptionsDefaultToneMapOptions returns the recommended HDR tone-mapping defaults: ToneMapACES, exposure 1.0 (0 EV), and exact sRGB encoding (Gamma 0).
func (o ToneMapOptions) Normalized() ToneMapOptionsNormalized returns a copy of o with invalid fields canonicalized identically for CPU and GPU evaluation: a negative, NaN or infinite Exposure becomes 1.0 (zero stays black), a non-positive or non-finite Gamma becomes 0 (exact sRGB), and unknown Operator values become ToneMapNone.
type ToneMapPass struct {
// contains filtered or unexported fields
}ToneMapPass draws a full-screen triangle that samples a linear HDR texture, applies exposure and a configurable ToneMapOperator, and encodes to sRGB or power-law gamma for display (#250).
A pass holds one uniform block, and NSGo applies gpu.Device.WriteBuffer ahead of the commands of the submission it belongs to, so every draw one ToneMapPass records into a submission uses the options of its last ToneMapPass.Draw. To tone-map several views with different options in one frame (split screen, a picture-in-picture camera, a photo-mode preview), create one ToneMapPass per view.
AppendToneMapUniforms encodes the options without allocating, and the pass reuses its bind group while the source texture stays the same; each draw still uploads the ToneMapUniformSize-byte block with WriteBuffer, which copies it. When created with Retained: true (along with a retained HDRTarget), the pass's GPU resources survive a device loss as ToneMapPassDesc.Retained describes.
func NewToneMapPass(cx *core.Scope, dev *gpu.Device, desc ToneMapPassDesc) (*ToneMapPass, error)NewToneMapPass compiles ToneMapWGSL (cached process-wide) and creates the uniform buffer, sampler, bind group layout, and render pipeline on dev scoped to cx (nil for manual closing in headless tests).
func (p *ToneMapPass) BindGroupFor(dev *gpu.Device, src *gpu.Texture) (*gpu.BindGroup, error)BindGroupFor returns a bind group pairing src with the pass's sampler and uniform buffer, caching it for steady-state reuse when src has not changed.
func (p *ToneMapPass) Close() errorClose releases the pass's GPU resources. It is safe to call on nil or more than once.
func (p *ToneMapPass) Draw(pass *gpu.RenderPass, dev *gpu.Device, src *gpu.Texture, opts ToneMapOptions) errorDraw uploads opts, binds src (reusing the cached bind group in steady state), and records the full-screen tone-mapping triangle into pass. The options apply to every draw of this pass in the same submission (see ToneMapPass).
func (p *ToneMapPass) DrawDynamicResolution(pass *gpu.RenderPass, dev *gpu.Device, src *DynamicResolutionTarget, opts ToneMapOptions) errorDrawDynamicResolution tone-maps the active scaled sub-viewport of a DynamicResolutionTarget (created with an HDR ColorFormat such as PreferredHDRFormat) over the whole of pass, upscaling it with the pass's sampler in the same draw. Call it after DynamicResolutionTarget.Begin3D's pass ends, in place of DynamicResolutionTarget.Upscale; the upscaler's sharpen filter is not applied. Like the upscaler, it clamps the sampled coordinates half a texel inside the scaled region so the target's unused texels never bleed in.
func (p *ToneMapPass) DrawTarget(pass *gpu.RenderPass, dev *gpu.Device, src *HDRTarget, opts ToneMapOptions) errorDrawTarget is ToneMapPass.Draw for an *HDRTarget, sampling src.ColorTexture().
func (p *ToneMapPass) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout at ToneMapGroup.
func (p *ToneMapPass) Pipeline() *gpu.PipelinePipeline returns the pass's tone-mapping render pipeline.
func (p *ToneMapPass) Sampler() *gpu.SamplerSampler returns the sampler bound for reading the HDR texture.
func (p *ToneMapPass) SetDevice(dev *gpu.Device)SetDevice updates the device reference used when a nil device is passed to ToneMapPass.Write, ToneMapPass.BindGroupFor, or ToneMapPass.Draw (for example from OnReady after a retained device restoration).
func (p *ToneMapPass) TargetFormat() gpu.TextureFormatTargetFormat returns the color format the pass renders into.
func (p *ToneMapPass) UniformBuffer() *gpu.BufferUniformBuffer returns the ToneMapUniformSize-byte uniform buffer.
func (p *ToneMapPass) Valid() boolValid reports whether the pass's GPU resources are open and live.
func (p *ToneMapPass) Write(dev *gpu.Device, opts ToneMapOptions)Write uploads opts to the pass's uniform buffer without allocating into the caller's heap (encodes into internal scratch storage). Pass dev (such as frame.Device()) after a device restore, or nil to use the pass's stored device.
type ToneMapPassDesc struct {
// Label names the pass's pipeline, sampler, uniform buffer, and bind group in GPU capture tools.
Label string
// TargetFormat is the color format of the render pass that [ToneMapPass] draws into. [gpu.FormatUndefined] defaults to dev.SurfaceFormat(). When TargetFormat.IsSRGB() is true, [ToneMapPass] automatically outputs linear tone-mapped RGB so the hardware sRGB target encodes linear-to-sRGB once without double gamma.
TargetFormat gpu.TextureFormat
// DepthFormat optionally matches a render pass with a depth attachment; depth testing and depth writes stay disabled.
DepthFormat gpu.TextureFormat
// NearestFilter selects [gpu.FilterNearest] instead of [gpu.FilterLinear] when sampling the HDR source texture.
NearestFilter bool
// Retained opts the uniform buffer, sampler, bind group layout and pipeline into automatic recreation after a GPU device loss. Bind groups have no retained form; the pass rebuilds its cached one on the next draw once the old one is no longer valid.
Retained bool
}ToneMapPassDesc configures NewToneMapPass.
type ToonDraw struct {
// Mesh is the main surface geometry drawn in the cel-shaded pass (and in the outline pass when OutlineMesh is nil).
Mesh *GPUMesh
// OutlineMesh is an optional mesh (for example built with [SmoothOutlineNormals]) drawn in the inverted-hull outline pass. When nil, Mesh is used.
OutlineMesh *GPUMesh
// Material supplies the cel-shading and outline parameters.
Material *GPUToonMaterial
// Transform is the object's world-space model matrix. A zero matrix is treated as [math3d.Mat4Identity].
Transform math3d.Mat4
}ToonDraw describes one cel-shaded object submitted to ToonRenderer.Draw.
type ToonEvalInput struct {
Normal math3d.Vec3
// ToLight points from the surface toward the key light, like [ToonSceneUniform.ToLight].
ToLight math3d.Vec3
ViewDir math3d.Vec3
LightColor math3d.Vec3
AmbientColor math3d.Vec3
// BaseSample is an optional linear RGBA sample from BaseColorTexture. Nil means opaque white {1, 1, 1, 1}.
BaseSample *[4]float32
// RampSample is an optional linear RGB sample from RampTexture. When non-nil, it replaces analytical band quantization.
RampSample *[3]float32
}ToonEvalInput supplies the surface normal, the directions toward the key light and the viewer, the light radiance, and optional texture samples for EvaluateToon.
type ToonLight struct {
Key DirectionalLight
Ambient AmbientLight
}ToonLight is the light a toon-shaded draw receives: one directional key light, whose N·L is quantized into bands, plus an ambient fill added to every band. Both use the same types and conventions as a LightRig: Key.Direction is the direction the light's rays travel, and an Intensity of 0 turns a light off.
func DefaultToonLight() ToonLightDefaultToonLight returns a white key light shining down from the upper front right with a dim cool ambient fill.
func ToonLightFromRig(rig LightRig) (ToonLight, error)ToonLightFromRig returns the toon light for a scene lit by rig: its first directional light as the key light and its ambient fill. Point lights and further directional lights are not used. It returns an error wrapping ErrInvalidLight when rig is invalid or has no directional light.
func (l ToonLight) Validate() errorValidate reports whether the key light has a finite non-zero direction and both lights have finite non-negative colors and intensities. Every error wraps ErrInvalidLight.
type ToonMaterial struct {
// BaseColorFactor is the linear RGBA base surface color multiplier, as in [Material]. Its alpha is written to the output alpha, which only a pipeline built with [NewToonPipeline] and a [ToonPipelineOptions.Blend] blends with: [ToonRenderer] draws opaque.
BaseColorFactor [4]float32
// BaseColorTexture is an optional 2D albedo texture multiplied with BaseColorFactor. When nil, [MaterialDefaults.WhiteSRGB] is bound.
BaseColorTexture *GPUTexture
// BaseColorSampler is the sampler for BaseColorTexture. When nil, [MaterialDefaults.Sampler] (linear repeat) is bound.
BaseColorSampler *GPUSampler
// ShadowColor is the linear RGB tint applied to the darkest diffuse band.
ShadowColor [3]float32
// Bands is the number of discrete diffuse cel-shading bands in [MinToonBands, MaxToonBands] (2..8). Zero defaults to [DefaultToonBands] (3). Ignored when RampTexture is set.
Bands int
// BandSmoothness controls transition softness between diffuse bands in [0, 0.5]. Zero produces crisp hard cel steps; small positive values anti-alias band boundaries.
BandSmoothness float32
// RampTexture is an optional 1D horizontal cel-ramp texture (height >= 1) sampled at u = clamp(N·L, 0, 1). When non-nil, its RGB value replaces analytical band quantization.
RampTexture *GPUTexture
// RampSampler is the sampler for RampTexture. When nil and RampTexture is set, the material creates a linear-clamp sampler so the ramp's ends do not wrap into each other.
RampSampler *GPUSampler
// SpecularColor is the linear RGB color of the stepped cel specular highlight. Zero disables specular highlights.
SpecularColor [3]float32
// SpecularPower is the Blinn-Phong shininess exponent. Zero defaults to [DefaultToonSpecularPower] (32).
SpecularPower float32
// SpecularThreshold is the step cutoff in [0, 1] applied to pow(N·H, SpecularPower).
SpecularThreshold float32
// SpecularSmoothness controls specular edge softness in [0, 0.5]. Zero gives a hard cel highlight edge.
SpecularSmoothness float32
// RimColor is the linear RGB color of the Fresnel rim highlight. Zero disables rim highlights.
RimColor [3]float32
// RimThreshold is the Fresnel cutoff in [0, 1] applied to (1 - N·V); higher values produce a thinner silhouette rim.
RimThreshold float32
// RimSmoothness controls rim edge softness in [0, 0.5]. Zero gives a crisp rim step.
RimSmoothness float32
// OutlineColor is the linear RGBA color of the inverted-hull outline pass. An alpha of 0 turns the outline off; other alpha values only blend in a pipeline built with [NewToonOutlinePipeline] and a [ToonPipelineOptions.Blend], since [ToonRenderer] draws opaque.
OutlineColor [4]float32
// OutlineWidth is the normal-extrusion distance of the inverted-hull outline pass: in world units, or with OutlineClipSpace in NDC y units, so the outline is OutlineWidth × viewport height / 2 pixels thick. Zero disables the outline pass.
OutlineWidth float32
// OutlineClipSpace extrudes outline vertices along their projected normal on screen instead of in world space, giving the same thickness in pixels at every distance and in every direction. It reads the aspect ratio from the camera's projection, which must match the viewport's.
OutlineClipSpace bool
}ToonMaterial defines cel/toon shading parameters: banded diffuse lighting (or a 1D ramp texture), hard stepped specular highlights, Fresnel rim lighting, and inverted-hull outline styling (#262).
func DefaultToonMaterial() ToonMaterialDefaultToonMaterial returns a ready-to-use cel-shaded material with 3 crisp bands, a cool shadow tint, subtle specular and rim highlights, and a dark silhouette outline.
func (m ToonMaterial) AppendUniformData(dst []byte) []byteAppendUniformData appends m's ToonUniformSize-byte little-endian uniform block matching ToonWGSL and ToonOutlineWGSL to dst and returns the extended slice. It allocates only when dst lacks capacity for ToonUniformSize more bytes.
func (m ToonMaterial) EffectiveBands() intEffectiveBands returns m.Bands, or DefaultToonBands when m.Bands is zero.
func (m ToonMaterial) EffectiveSpecularPower() float32EffectiveSpecularPower returns m.SpecularPower, or DefaultToonSpecularPower when m.SpecularPower is zero.
func (m ToonMaterial) HasOutline() boolHasOutline reports whether m draws an inverted-hull outline (positive width and non-zero outline alpha).
func (m ToonMaterial) Validate() errorValidate checks every scalar, color, band count, threshold, and optional GPU handle on m. Every error wraps ErrInvalidToonMaterial.
type ToonMaterialOptions struct {
// Label prefixes GPU resource labels in capture tools.
Label string
// Layout is an optional shared layout from [ToonMaterialBindingLayout] or [ToonRenderer.MaterialLayout]. When nil, the material creates and owns its own layout.
Layout *gpu.BindGroupLayout
// Retained keeps a CPU shadow copy of the uniform buffer (and of the ramp sampler the material creates) so NSGo restores them after a device loss. The [MaterialDefaults] and any caller-supplied textures and samplers must be retained too for the bind group to come back.
Retained bool
}ToonMaterialOptions configures NewGPUToonMaterial.
type ToonPipelineOptions struct {
// Label names the pipeline in GPU capture tools.
Label string
// CameraLayout is the @group(0) bind group layout (from [CameraBuffer.Layout]).
CameraLayout *gpu.BindGroupLayout
// MaterialLayout is the @group(1) bind group layout (from [ToonMaterialBindingLayout] or [GPUToonMaterial.Layout]).
MaterialLayout *gpu.BindGroupLayout
// SceneLayout is the @group(2) bind group layout (from [ToonSceneBindingLayout] or [ToonSceneDynamicBindingLayout]).
SceneLayout *gpu.BindGroupLayout
// ColorFormat is the color attachment format; zero defaults to dev.SurfaceFormat().
ColorFormat gpu.TextureFormat
// DepthFormat is the depth attachment format (e.g. [gpu.FormatDepth24Plus]), or [gpu.FormatUndefined] for no depth buffer.
DepthFormat gpu.TextureFormat
// DoubleSided disables back-face culling (uses [gpu.CullNone] instead of [gpu.CullBack]) on the main cel-shaded pass. Ignored by [NewToonOutlinePipeline], which always uses [gpu.CullFront].
DoubleSided bool
// Blend sets an optional color blend state on the main cel-shaded pass (nil means opaque).
Blend *gpu.BlendState
// Retained opts the pipeline into automatic recreation after a GPU device loss.
Retained bool
}ToonPipelineOptions configures NewToonPipeline and NewToonOutlinePipeline.
type ToonRenderer struct {
// contains filtered or unexported fields
}ToonRenderer manages both the inverted-hull outline pipeline and main cel-shaded pipeline together with a dynamic-offset per-draw scene uniform buffer, drawing outlines first and cel-shaded surfaces second in a single render pass (#262). Both pipelines draw opaque, with depth writes; for blended toon surfaces build pipelines with NewToonPipeline and NewToonOutlinePipeline and a ToonPipelineOptions.Blend.
func NewToonRenderer(cx *core.Scope, dev *gpu.Device, opts ToonRendererOptions) (*ToonRenderer, error)NewToonRenderer creates the shared material/scene layouts, both toon and outline pipelines, and the dynamic scene uniform buffer on dev, scoped to cx.
func (r *ToonRenderer) Begin()Begin starts a new frame: the next Draw reuses the scene uniform slots from the start of the buffer, and scene buffers that a Draw outgrew during the previous frame are released. Call it once per frame, after the previous frame's submission and before its first Draw, when submitting with gpu.Device.Submit directly. Inside a gpu.Frame (for example a gpu.View OnFrame callback) Draw rewinds on its own when gpu.Device.FrameIndex advances, so calling Begin there is optional.
func (r *ToonRenderer) Close() errorClose releases all GPU resources owned by r. It is safe to call on a nil receiver or more than once.
func (r *ToonRenderer) Draw(dev *gpu.Device, pass *gpu.RenderPass, camGroup *gpu.BindGroup, light ToonLight, draws ...ToonDraw) errorDraw writes per-draw transform/light uniforms and records the inverted-hull outline pass followed by the main cel-shaded pass into pass. Draws with invalid meshes or materials are skipped. Draw may run any number of times between two submissions, into one pass or several: each call writes its uniforms to slots no earlier call of the frame uses (see ToonRenderer.Begin). It returns a gpu.Error when r, dev, pass, or camGroup is nil, closed, or lost, an error wrapping ErrInvalidLight when light is invalid, and the error from growing the uniform buffer.
func (r *ToonRenderer) MaterialLayout() *gpu.BindGroupLayoutMaterialLayout returns the @group(ToonMaterialGroup) layout to pass in ToonMaterialOptions.Layout when creating GPUToonMaterial instances for this renderer.
func (r *ToonRenderer) NewMaterial(cx *core.Scope, dev *gpu.Device, defaults *MaterialDefaults, mat ToonMaterial, label string) (*GPUToonMaterial, error)NewMaterial is a convenience wrapper around NewGPUToonMaterial that binds mat to r's ToonRenderer.MaterialLayout and inherits r's Retained setting.
func (r *ToonRenderer) OutlinePipeline() *gpu.PipelineOutlinePipeline returns the inverted-hull outline pipeline.
func (r *ToonRenderer) ToonPipeline() *gpu.PipelineToonPipeline returns the main cel-shaded pipeline.
func (r *ToonRenderer) Valid() boolValid reports whether all GPU resources owned by r are open and belong to a live device.
type ToonRendererOptions struct {
// Label prefixes GPU resource labels in capture tools.
Label string
// CameraLayout is the @group(0) layout from [CameraBuffer.Layout] (required).
CameraLayout *gpu.BindGroupLayout
// ColorFormat is the color attachment format; zero defaults to dev.SurfaceFormat().
ColorFormat gpu.TextureFormat
// DepthFormat is the depth attachment format (e.g. [gpu.FormatDepth24Plus]), or [gpu.FormatUndefined] without depth.
DepthFormat gpu.TextureFormat
// DoubleSided disables back-face culling on the main cel-shaded pass.
DoubleSided bool
// InitialCapacity is the starting number of per-draw transform slots in the dynamic scene uniform buffer (defaults to 32). The buffer grows when the draws of one frame need more slots.
InitialCapacity int
// Retained opts owned pipelines, layouts, and uniform buffers into automatic restoration across GPU device loss.
Retained bool
}ToonRendererOptions configures NewToonRenderer.
type ToonSceneUniform struct {
Model math3d.Mat4
NormalMatrix math3d.Mat4
// ToLight is the unit vector from a surface toward the key light (the opposite of [DirectionalLight.Direction]).
ToLight math3d.Vec3
// LightColor is the key light's linear radiance (Color × Intensity).
LightColor math3d.Vec3
// AmbientColor is the ambient fill's linear radiance (Color × Intensity).
AmbientColor math3d.Vec3
}ToonSceneUniform holds the per-draw model matrix, inverse-transpose normal matrix, and key and ambient light packed for @group(2) in ToonWGSL and ToonOutlineWGSL.
func NewToonSceneUniform(model math3d.Mat4, light ToonLight) ToonSceneUniformNewToonSceneUniform builds a ToonSceneUniform from a world transform (zero value means identity) and a ToonLight.
func (u ToonSceneUniform) AppendUniformData(dst []byte) []byteAppendUniformData appends u's ToonSceneUniformSize-byte little-endian uniform block matching ToonWGSL and ToonOutlineWGSL to dst. It allocates only when dst lacks capacity for ToonSceneUniformSize more bytes.
type Trail struct {
// contains filtered or unexported fields
}Trail records a moving object's world positions and builds a camera-facing ribbon through them (#281).
Each point's ribbon edge runs along side = tangent × toCamera, so the strip's surface turns about its own centerline to face the viewer at every angle, like a 3D laser, sword swing or projectile streak.
func (t *Trail) AddPoint(p math3d.Vec3)AddPoint appends p as the newest point when it is at least MinDistance from the previous one. Non-finite points are ignored.
func (t *Trail) Bounds() math3d.AABBBounds returns a world-space AABB that contains the ribbon for any camera, or an empty box when fewer than 2 points are live.
func (t *Trail) Build(cam CameraBasis) []TrailVertexBuild returns the ribbon facing cam as a triangle strip: two vertices per point from tail to head, left edge first. It returns nil when fewer than 2 points are live. The slice aliases internal storage until the next Build.
func (t *Trail) Config() TrailConfigConfig returns a copy of the trail's configuration.
func (t *Trail) Draw(d *core.Drawing, cam CameraBasis, viewProj math3d.Mat4, viewport core.Bounds) intDraw builds the ribbon facing cam and fills it into d through viewProj and viewport, clipping each segment against the near plane. It returns the number of segments drawn.
func (t *Trail) DrawItem(template DrawItem) DrawItemDrawItem returns template with an identity Transform and WorldBounds, Triangles and Vertices taken from the trail, so it can be sorted by Queue.Build. A zero template Blend is replaced by BlendAlphaBlend.
func (t *Trail) EvaluateAt(u float32) (width float32, color core.Color)EvaluateAt returns the ribbon width and color at u in [0, 1], where 0 is the head and 1 the tail.
func (t *Trail) PointCount() intPointCount returns the number of live points.
func (t *Trail) Points() []TrailPointPoints returns the live points from oldest (index 0) to newest. The slice aliases internal storage until the next mutation.
func (t *Trail) SetConfig(cfg TrailConfig)SetConfig replaces the configuration, keeping live points and dropping the oldest ones beyond the new MaxPoints.
func (t *Trail) Update(dt time.Duration)Update ages every point by dt and removes the expired ones. Non-positive dt does nothing.
type TrailConfig struct {
// MaxPoints caps the number of recorded points; defaults to 64 when <= 0.
MaxPoints int
// Lifetime is how long each point lives before it expires; defaults to 500ms when <= 0.
Lifetime time.Duration
// MinDistance is the minimum world distance from the newest point before a new point is appended. Zero or negative records every distinct point; an exact duplicate refreshes the newest point's age.
MinDistance float32
// Width is the ribbon's base width in world units; defaults to 0.25 when <= 0.
Width float32
// WidthCurve scales Width along the trail from head (u=0, newest) to tail (u=1, oldest). Empty keeps 1.
WidthCurve particles.Curve
// ColorGradient evaluates color along the trail from head (u=0) to tail (u=1). When empty, Color is used.
ColorGradient particles.ColorCurve
// Color is the solid color used when ColorGradient is empty; zero means opaque white.
Color core.Color
}TrailConfig configures a 3D ribbon Trail (#281). It mirrors the MaxPoints, Lifetime, MinDistance, Width, WidthCurve, ColorGradient and Color options of particles.TrailConfig in world units and durations; it has no Texture, and Trail has no Attach, Detach or Follow, so feed it positions with Trail.AddPoint.
type TrailPoint struct {
// Pos is the recorded world-space position.
Pos math3d.Vec3
// Age is how long ago the point was recorded or last refreshed.
Age time.Duration
// Length is the distance along the trail from the oldest point.
Length float32
}TrailPoint is one recorded point of a Trail.
type TrailVertex struct {
// Pos is the vertex's world-space position.
Pos math3d.Vec3
// Normal is the ribbon's unit surface normal at this vertex, turned toward the camera.
Normal math3d.Vec3
// Color is the ribbon color evaluated at U.
Color core.Color
// U runs along the trail from 0 at the head (newest) to 1 at the tail (oldest); V is 0 on the left edge and 1 on the right.
U, V float32
}TrailVertex is one edge vertex of a built ribbon.
type TransmissionBackground struct {
// contains filtered or unexported fields
}TransmissionBackground owns the per-frame / per-pass bind group exposing the opaque scene color texture to transmissive materials without baking the background texture into each material's bind group.
In the shader, screen-space sample UVs are derived from frag_pos.xy / vec2<f32>(textureDimensions(transmission_bg_tex)), scaled and clamped by the 32-byte parameter uniform so standard resizes and DynamicResolutionTarget sub-viewports work seamlessly with one bind group update per frame or resize.
func NewTransmissionBackground(cx *core.Scope, dev *gpu.Device, opts TransmissionBackgroundOptions) (*TransmissionBackground, error)NewTransmissionBackground allocates the per-frame transmission background bind group layout, uniform buffer, linear clamp-to-edge sampler, 1x1 black fallback texture, and initial bind group on dev, owned by cx.
func (tb *TransmissionBackground) Bind(pass *gpu.RenderPass)Bind sets tb's bind group at TransmissionBackgroundGroup (group 3) on pass.
func (tb *TransmissionBackground) BindAt(pass *gpu.RenderPass, group uint32)BindAt sets tb's bind group at group on pass (use MaterialTransmissionBackgroundGroup = 2 when drawing with a default-light extended material pipeline without ExtendedMaterialPipelineOptions.LightLayout, or TransmissionBackgroundGroup = 3 when paired with GPULightBuffer).
func (tb *TransmissionBackground) BindGroup() *gpu.BindGroupBindGroup returns the current frame/pass bind group.
func (tb *TransmissionBackground) Close() errorClose releases all GPU resources owned by tb. Safe to call on nil or more than once.
func (tb *TransmissionBackground) Layout() *gpu.BindGroupLayoutLayout returns the bind group layout for ExtendedMaterialPipelineOptions.TransmissionLayout.
func (tb *TransmissionBackground) SetDynamicResolution(dev *gpu.Device, target *DynamicResolutionTarget, snapshot *gpu.Texture, viewportW, viewportH int, srgb bool) errorSetDynamicResolution configures tb to sample an opaque scene snapshot captured from target (or target.ColorTexture() when snapshot is nil) for a transmissive pass drawn either at target's active scaled viewport (viewportW == 0 || viewportH == 0) or at a custom viewport (such as native resolution).
func (tb *TransmissionBackground) SetTexture(dev *gpu.Device, tex *gpu.Texture, srgb bool) errorSetTexture binds the opaque scene color texture for the current frame/pass with full-texture UVs derived automatically from frag_pos.xy / vec2<f32>(textureDimensions(bg_tex)). Passing tex == nil binds the internal 1x1 black fallback. Only this single per-frame bind group is recreated when tex changes; no material bind groups are modified.
func (tb *TransmissionBackground) SetViewport(dev *gpu.Device, tex *gpu.Texture, viewportW, viewportH, activeW, activeH, texW, texH int, srgb bool) errorSetViewport binds tex and configures screen-to-background UV scaling and half-texel clamping for a transmissive pass rendering into (viewportW, viewportH) while sampling an opaque scene rendered into the top-left [0..activeW, 0..activeH] sub-rectangle of a (texW, texH) backing texture (such as a DynamicResolutionTarget).
func (tb *TransmissionBackground) Valid() boolValid reports whether tb's layout, uniform buffer, sampler, fallback texture, and bind group are live.
type TransmissionBackgroundOptions struct {
// Label prefixes debug labels on GPU objects. Defaults to "render3d.transmission_bg".
Label string
// Retained keeps CPU shadow copies of the uniform buffer, fallback texture, and sampler across GPU device loss.
Retained bool
// SRGB indicates that the bound opaque scene color texture holds sRGB-encoded values in a non-sRGB texture format (such as FormatRGBA8Unorm), so the shader decodes it to linear space before tinting. Leave false for linear HDR targets (FormatRGBA16Float) or hardware-decoded sRGB textures (FormatRGBA8UnormSRGB).
SRGB bool
}TransmissionBackgroundOptions configures NewTransmissionBackground.
type UVTransform struct {
Scale [2]float32
Offset [2]float32
}UVTransform applies an affine scale and offset (uv * Scale + Offset) to lightmap coordinates so multiple meshes can share regions of a single baked lightmap atlas.
func IdentityUVTransform() UVTransformIdentityUVTransform returns the identity UV transform (Scale {1, 1}, Offset {0, 0}).
func (t UVTransform) Apply(uv math3d.Vec2) math3d.Vec2Apply transforms uv by t.Normalized().
func (t UVTransform) Normalized() UVTransformNormalized returns t with a zero Scale ({0, 0}) replaced by {1, 1}.
func (t UVTransform) Validate() errorValidate checks that all scale and offset components are finite.
type UnlitMaterial struct {
// BaseColorFactor is the linear RGBA multiplier applied to the texture and vertex color, each component in [0, 1] as glTF 2.0 requires. Use [DefaultUnlitMaterial] for the glTF default [1, 1, 1, 1].
BaseColorFactor [4]float32
// BaseColorTexture is an optional base-color texture (typically uploaded with TextureUpload{SRGB: true}). When nil, [NewGPUUnlitMaterial] binds the shared [MaterialDefaults.WhiteSRGB] texture.
BaseColorTexture *GPUTexture
// BaseColorSampler is an optional sampler for BaseColorTexture. When nil, [NewGPUUnlitMaterial] binds the shared [MaterialDefaults.Sampler].
BaseColorSampler *GPUSampler
// AlphaMode selects opaque, alpha-masked cutout, or alpha-blended transparency.
AlphaMode AlphaMode
// AlphaCutoff is the discard threshold for [AlphaMask] (default 0.5). Fragments with combined alpha < AlphaCutoff are discarded.
AlphaCutoff float32
// DoubleSided disables back-face culling when building a pipeline for this material.
DoubleSided bool
// UseVertexColor enables multiplying the material color by the mesh's @location(3) linear RGBA vertex color (glTF COLOR_0).
UseVertexColor bool
}UnlitMaterial describes a glTF KHR_materials_unlit surface: flat color unaffected by scene lighting, computed in linear space as
baseColor = BaseColorFactor * baseColorTexture(uv) * vertexColor
where BaseColorTexture defaults to MaterialDefaults.WhiteSRGB when nil and vertexColor is COLOR_0 (or linear white (1, 1, 1, 1) when UseVertexColor is false or the mesh has no vertex colors).
func DefaultUnlitMaterial() UnlitMaterialDefaultUnlitMaterial returns the glTF 2.0 KHR_materials_unlit defaults: opaque white BaseColorFactor [1, 1, 1, 1], AlphaMode AlphaOpaque, AlphaCutoff 0.5, single-sided, and UseVertexColor enabled.
func UnlitMaterialFromGLTF(doc *gltf.Document, matIndex int, tex *GPUTexture, samp *GPUSampler) (UnlitMaterial, error)UnlitMaterialFromGLTF extracts an UnlitMaterial from doc.Materials[matIndex], verifying that the material enables KHR_materials_unlit (mat.Unlit == true). Optional pre-uploaded tex and samp are attached as BaseColorTexture and BaseColorSampler.
Returns an error wrapping ErrInvalidUnlitMaterial if doc is nil, matIndex is out of range, the material does not declare KHR_materials_unlit, or the resulting material fails validation.
func (m UnlitMaterial) BlendMode() BlendModeBlendMode returns the render3d.BlendMode corresponding to m.AlphaMode for Queue sorting.
func (m UnlitMaterial) Validate() errorValidate checks that m's uniform parameters and any attached GPU texture/sampler handles are valid. Every error wraps ErrInvalidUnlitMaterial.
type UnlitPipelineOptions struct {
// Label names the pipeline in GPU capture tools.
Label string
// ColorFormat sets the color attachment format; [gpu.FormatUndefined] defaults to dev.SurfaceFormat(). An sRGB format selects fs_linear so the hardware encodes once (see LinearOutput).
ColorFormat gpu.TextureFormat
// DepthFormat enables depth testing (and depth writes for opaque/alpha-mask modes) when non-zero.
DepthFormat gpu.TextureFormat
// DepthCompare overrides the depth comparison function when DepthFormat is set; zero defaults to [gpu.CompareLess].
DepthCompare gpu.CompareFunc
// AlphaMode selects blending and depth-write state: [AlphaOpaque] and [AlphaMask] write depth without color blending; [AlphaBlend] uses straight alpha blending ([gpu.BlendAlpha]) with depth writes disabled.
AlphaMode AlphaMode
// DoubleSided disables backface culling ([gpu.CullNone]); when false, back faces are culled ([gpu.CullBack], counter-clockwise front faces).
DoubleSided bool
// LinearOutput writes the linear color ([UnlitSample].Linear) through fs_linear instead of encoding it to sRGB in fs_main, for an [HDRTarget] that a [ToneMapPass] resolves. fs_linear is also chosen whenever ColorFormat is sRGB, because the hardware encodes on write there. [NewMaterialPipeline] does not switch on an sRGB ColorFormat, so give both pipelines a non-sRGB target when they draw into the same pass.
LinearOutput bool
// SampleCount is the MSAA sample count (0 or 1 disables multisampling).
SampleCount int
// Retained opts the pipeline into automatic recreation after device loss.
Retained bool
}UnlitPipelineOptions configures NewUnlitPipeline. Label, ColorFormat, DepthFormat, AlphaMode, DoubleSided and LinearOutput mean what they mean in MaterialPipelineOptions.
type UnlitSample struct {
// Linear holds the evaluated linear RGBA color (with alpha 1.0 for [AlphaOpaque] and surviving [AlphaMask] fragments).
Linear [4]float32
// SRGB holds the IEC 61966-2-1 sRGB-encoded RGB and linear alpha in [0, 1], matching [UnlitWGSL]'s fs_main output.
SRGB [4]float32
// Discarded is true when AlphaMode is [AlphaMask] and the combined alpha is strictly less than AlphaCutoff.
Discarded bool
}UnlitSample is the pure-Go CPU reference result produced by EvaluateUnlit, matching UnlitWGSL.
func EvaluateUnlit(mat UnlitMaterial, texLinear, vertexColor [4]float32) UnlitSampleEvaluateUnlit evaluates the exact glTF KHR_materials_unlit shading equation on the CPU:
base = mat.BaseColorFactor * texLinear * (mat.UseVertexColor ? vertexColor : [1,1,1,1])
applying AlphaMode (forcing alpha to 1.0 for opaque, discarding when alpha < AlphaCutoff for mask, or clamping alpha to [0, 1] for blend) and encoding linear RGB to sRGB via the IEC 61966-2-1 transfer curve.
Pass texLinear = [4]float32{1, 1, 1, 1} when no texture is bound (or decode an sRGB texel to linear RGB + linear alpha first), and vertexColor = [4]float32{1, 1, 1, 1} when COLOR_0 is omitted.
func (s UnlitSample) BlendOver(dst color.RGBA) color.RGBABlendOver composites s over an sRGB RGBA8 destination pixel using straight-alpha blending (gpu.BlendAlpha), matching AlphaBlend on a FormatRGBA8Unorm target. When s.Discarded is true, dst is returned unchanged.
func (s UnlitSample) RGBA8() color.RGBARGBA8 quantizes s.SRGB into an 8-bit color.RGBA matching an RGBA8Unorm framebuffer pixel (or zero when s.Discarded is true).
type UploadFrameStats struct {
// BytesUploaded is the exact number of bytes written to the GPU during this Step.
BytesUploaded int
// Completed is the number of uploads that finished and invoked onReady with a resource.
Completed int
// Failed is the number of uploads that failed during this Step.
Failed int
// Canceled is the number of uploads that were canceled during this Step.
Canceled int
// Pending is the number of unfinished uploads remaining after this Step.
Pending int
// InFlightDecodes is the number of decode callbacks currently running on worker goroutines.
InFlightDecodes int
// FrameDuration is the wall-clock time spent inside this Step call.
FrameDuration time.Duration
}UploadFrameStats summarizes the work performed by one Uploader.Step call.
type UploadHandle struct {
// contains filtered or unexported fields
}UploadHandle tracks one queued upload and allows inspecting its progress or canceling it from any goroutine.
func (h *UploadHandle) Cancel()Cancel requests cancellation of the upload. It is safe to call from any goroutine and safe to call more than once. Any partially created GPU resources are released on the next Uploader.Step (or Uploader.Close).
func (h *UploadHandle) Done() <-chan struct{}Done returns a channel that is closed when the upload reaches a terminal state (UploadReady, UploadFailed, or UploadCanceled).
func (h *UploadHandle) Err() errorErr returns the terminal error once the upload has failed or been canceled, or nil while in progress or after reaching UploadReady.
func (h *UploadHandle) Progress() (uploaded, total int64)Progress returns (uploaded, total) bytes for the GPU transfer stage. Both values are 0 while the asset is still queued or decoding.
func (h *UploadHandle) State() UploadStateState returns the current lifecycle state of the upload.
type UploadPriority intUploadPriority orders queued decodes and GPU uploads inside an Uploader. Higher priorities preempt lower ones; equal priorities preserve FIFO order.
const (
// PriorityLow is intended for background prefetching and distant assets.
PriorityLow UploadPriority = -1
// PriorityNormal is the default priority for standard asset streaming.
PriorityNormal UploadPriority = 0
// PriorityHigh is intended for immediately visible hero assets.
PriorityHigh UploadPriority = 1
)type UploadState uint8UploadState reports the lifecycle stage of an UploadHandle.
const (
// UploadQueued means the upload is waiting for a decode worker goroutine.
UploadQueued UploadState = iota
// UploadDecoding means a background worker is running the decode callback and preparing packed CPU staging bytes, or the decoded asset is waiting for the [Uploader.Step] that starts its upload.
UploadDecoding
// UploadUploading means the GPU resource is allocated and being streamed across frames by [Uploader.Step].
UploadUploading
// UploadReady means all bytes have been uploaded; onReady is called right after the state changes.
UploadReady
// UploadFailed means decoding, validation, or GPU upload failed.
UploadFailed
// UploadCanceled means the upload was canceled before completion.
UploadCanceled
)func (s UploadState) String() stringString returns a human-readable name for s.
type Uploader struct {
// contains filtered or unexported fields
}Uploader decodes meshes, textures, and raw buffers on background goroutines and streams them onto a gpu.Device during Uploader.Step without exceeding a configurable per-frame byte budget.
Call Uploader.Step once per frame from the engine goroutine (for example, inside gpu.ViewProps.OnFrame). All GPU resource creation, chunked writes, and onReady callbacks run on the goroutine calling Step, or on the one calling Uploader.Close, which must be the same. The Queue methods, UploadHandle methods, Uploader.SetBytesPerFrame, Uploader.SetChunkBytes, Uploader.Pending and Uploader.InFlightDecodes are safe to call from any goroutine.
func NewUploader(cx *core.Scope, dev *gpu.Device, opts UploaderOptions) *UploaderNewUploader creates a budgeted asynchronous GPU uploader bound to dev and scoped to cx. When cx is non-nil, disposing cx automatically closes the uploader and joins its worker goroutines. Pass cx == nil in headless tests and call Uploader.Close explicitly.
func (u *Uploader) BytesPerFrame() intBytesPerFrame returns the current per-frame GPU upload byte budget.
func (u *Uploader) ChunkBytes() intChunkBytes returns the maximum size of a single GPU write chunk.
func (u *Uploader) Close() errorClose cancels every unfinished upload, waits for the decode workers to exit, releases partially uploaded GPU resources, and calls the onReady of each unfinished upload with ErrUploaderClosed (or with the error it had already failed with). Resources already delivered stay owned by their scope or caller. Call Close on the goroutine that calls Uploader.Step, as it releases GPU resources and runs onReady callbacks; disposing the scope passed to NewUploader does. Close may be called more than once, and from an onReady callback.
func (u *Uploader) InFlightDecodes() intInFlightDecodes returns the number of decode callbacks currently executing on background worker goroutines.
func (u *Uploader) Pending() intPending returns the number of unfinished uploads (queued, decoding, or actively streaming).
func (u *Uploader) QueueMesh(ctx context.Context, priority UploadPriority, decode func(context.Context) (Mesh, error), onReady func(*GPUMesh, error), opts MeshUpload) *UploadHandleQueueMesh runs decode on a background worker, validates and packs the mesh there, and uploads its vertex and index buffers across Uploader.Step calls within the per-frame byte budget. opts are the same MeshUpload options UploadMesh takes, so a streamed mesh is the same GPUMesh a synchronous upload returns, and priority orders it against the other queued uploads.
onReady runs on the goroutine that calls Uploader.Step once every byte is uploaded, or with an error when decoding, validation or the upload fails or is canceled, or when Uploader.Close aborts it. Errors the call can report at once (a nil decode, a closed uploader, or a full queue under UploaderOptions.MaxPending) call onReady on the caller's goroutine before QueueMesh returns. onReady may be nil.
func (u *Uploader) QueueRawBuffer(ctx context.Context, priority UploadPriority, decode func(context.Context) (RawBufferUpload, error), onReady func(*gpu.Buffer, error)) *UploadHandleQueueRawBuffer runs decode on a background worker and streams the raw GPU buffer bytes it returns across Uploader.Step calls within the per-frame byte budget.
onReady is called as Uploader.QueueMesh describes.
func (u *Uploader) QueueRawTexture(ctx context.Context, priority UploadPriority, decode func(context.Context) (RawTextureUpload, error), onReady func(*gpu.Texture, error)) *UploadHandleQueueRawTexture runs decode on a background worker and streams the pre-encoded uncompressed or block-compressed mip levels, array layers or cube faces it returns across Uploader.Step calls within the per-frame byte budget.
onReady is called as Uploader.QueueMesh describes.
func (u *Uploader) QueueTexture(ctx context.Context, priority UploadPriority, decode func(context.Context) (image.Image, error), onReady func(*GPUTexture, error), opts TextureUpload) *UploadHandleQueueTexture runs decode on a background worker, converts the image there exactly as UploadTexture does (PixelBufferFromImage, so translucent images upload with straight alpha), builds the mip chain there when opts.Mipmaps is set (box-filtered in linear light for sRGB textures, as UploadTexturePixels does), and streams mip levels and row bands to the GPU across Uploader.Step calls within the per-frame byte budget. The GPUTexture it delivers holds the same texels a synchronous UploadTexture with the same opts would, so it works with BindTexture and GPUTexture.ByteSize.
onReady is called as Uploader.QueueMesh describes.
func (u *Uploader) QueueTexturePixels(ctx context.Context, priority UploadPriority, decode func(context.Context) (PixelBuffer, error), onReady func(*GPUTexture, error), opts TextureUpload) *UploadHandleQueueTexturePixels is Uploader.QueueTexture for raw PixelBuffer data, matching UploadTexturePixels: the buffer is validated, and RG8 or R8 data keeps its format. The decoded buffer's Pixels must not change until the handle is done.
onReady is called as Uploader.QueueMesh describes.
func (u *Uploader) SetBytesPerFrame(n int)SetBytesPerFrame adjusts the per-frame GPU upload byte budget at runtime. Values <= 0 restore DefaultUploadBytesPerFrame.
func (u *Uploader) SetChunkBytes(n int)SetChunkBytes adjusts the per-write chunk granularity at runtime. Values <= 0 restore DefaultUploadChunkBytes.
func (u *Uploader) Step() UploadFrameStatsStep advances GPU uploads on the engine goroutine without exceeding the configured per-frame byte budget. Call once per frame (for example inside gpu.ViewProps.OnFrame).
type UploaderOptions struct {
// BytesPerFrame caps how many bytes [Uploader.Step] writes to the GPU per call. Defaults to [DefaultUploadBytesPerFrame] (4 MiB) when <= 0. Adjustable at runtime via [Uploader.SetBytesPerFrame].
BytesPerFrame int
// ChunkBytes caps each individual buffer or texture write chunk so large assets split cleanly across frames. Defaults to [DefaultUploadChunkBytes] (256 KiB) when <= 0, and is clamped to BytesPerFrame during [Uploader.Step].
ChunkBytes int
// Workers is the number of background goroutines executing decode callbacks and CPU data packing. Defaults to min(runtime.GOMAXPROCS(0), 4) (at least 1) when <= 0.
Workers int
// MaxPending optionally limits the number of unfinished uploads (queued, decoding, and uploading). When > 0 and reached, Queue* fails immediately with [ErrUploadQueueFull].
MaxPending int
}UploaderOptions configures NewUploader. Zero values receive sensible defaults.
type ViewportContext struct {
// ViewIndex is the index of this view in the caller's original views slice.
ViewIndex int
// View is the CameraView being rendered.
View CameraView
// Camera is a per-view copy of View.Camera with Projection.Aspect matched to Viewport (unless View.PreserveAspect is true). View.Camera is never mutated.
Camera scene3d.Camera
// Uniform is the [CameraUniform] uploaded into CameraBindGroup for this view.
Uniform CameraUniform
// LayerMask is View.EffectiveLayerMask().
LayerMask uint32
// Viewport is the resolved, clamped pixel rectangle already applied to Pass via SetViewport and SetScissor.
Viewport PixelViewport
// CameraBindGroup is the per-view uniform bind group already bound at [CameraGroup] on Pass.
CameraBindGroup *gpu.BindGroup
// Pass is the active [gpu.RenderPass]. Do not call Pass.End(); the renderer ends passes automatically when switching targets or finishing the frame.
Pass *gpu.RenderPass
}ViewportContext carries the resolved camera, layer mask, pixel viewport, per-view camera bind group, and active gpu.RenderPass for one view rendered by ViewportRenderer.
type ViewportRect struct {
X float32
Y float32
Width float32
Height float32
MinDepth float32
MaxDepth float32
}ViewportRect describes a normalized sub-rectangle of a render target in [0, 1] top-left coordinates (matching NSGo's GPU viewport and scissor convention), together with its clip-depth range [MinDepth, MaxDepth].
The zero value (Width == 0 && Height == 0) represents the full target [0, 0, 1, 1] with depth range [0, 1]. A depth range of [0, 0] also means [0, 1], so a viewport cannot pin depth to exactly 0.
func FullViewport() ViewportRectFullViewport returns a ViewportRect covering the entire render target with depth range [0, 1].
func SplitScreenHorizontal(count int) []ViewportRectSplitScreenHorizontal arranges count viewports horizontally side by side across the X axis (alias of SplitScreenSideBySide).
func SplitScreenQuad() [4]ViewportRectSplitScreenQuad returns four quadrant ViewportRect tiles ordered top-left, top-right, bottom-left, bottom-right for 4-player split screen.
func SplitScreenSideBySide(count int) []ViewportRectSplitScreenSideBySide returns count equal-width full-height ViewportRect columns arranged left to right across the target (for example, 2-player side-by-side split screen). Returns nil if count <= 0.
func SplitScreenStacked(count int) []ViewportRectSplitScreenStacked returns count equal-height full-width ViewportRect rows arranged top to bottom down the target. Returns nil if count <= 0.
func SplitScreenVertical(count int) []ViewportRectSplitScreenVertical arranges count viewports vertically stacked down the Y axis (alias of SplitScreenStacked).
func ViewportFromPixels(x, y, width, height float32, targetWidth, targetHeight int) ViewportRectViewportFromPixels converts a pixel-space top-left rectangle into a normalized ViewportRect relative to a target of size targetWidth x targetHeight. Returns the zero ViewportRect if targetWidth or targetHeight is non-positive.
func (r ViewportRect) Aspect(targetWidth, targetHeight int) float32Aspect returns the resolved pixel aspect ratio (width / height) of r inside a target of size targetWidth x targetHeight, or zero if resolution fails.
func (r ViewportRect) Normalized() ViewportRectNormalized returns r with zero defaults filled in: an all-zero spatial rect becomes [0, 0, 1, 1] and a zero depth range becomes [0, 1].
func (r ViewportRect) Resolve(targetWidth, targetHeight int) (PixelViewport, bool)Resolve converts r into clamped pixel coordinates for a render target of size targetWidth x targetHeight. Both left/right and top/bottom edges are rounded independently so adjacent split-screen rects tile seamlessly with zero gaps and zero pixel overlap across seams. Returns (zero, false) if r is invalid, target dimensions are non-positive, or the resolved pixel area is empty.
func (r ViewportRect) Validate() errorValidate checks that r has finite coordinates within [0, 1], valid non-zero dimensions (or an all-zero full-target default), and a valid depth range 0 <= MinDepth <= MaxDepth <= 1. Every error wraps ErrInvalidViewport.
type ViewportRenderer struct {
// contains filtered or unexported fields
}ViewportRenderer orchestrates multi-camera frames combining offscreen render-to-texture passes (RenderTexture) and multiple viewports on the same target (such as side-by-side split screen or picture-in-picture overlays).
Each active view receives its own retained camera uniform buffer bound at CameraGroup so multiple cameras rendered within one gpu.Encoder or gpu.Frame never overwrite each other's uniform data before GPU execution. Adjacent views targeting the same surface share a single gpu.RenderPass unless a view requests CameraView.ResetDepth.
The uniform slots are reused by every call, so call ViewportRenderer.RenderFrame or ViewportRenderer.RenderEncoder at most once per submitted frame or command buffer: a second call on the same renderer before submission overwrites the first call's camera uniforms before the GPU runs its passes. Use a separate ViewportRenderer for each call that shares one submission.
func NewViewportRenderer(cx *core.Scope, dev *gpu.Device) (*ViewportRenderer, error)NewViewportRenderer creates a ViewportRenderer on dev scoped to cx, with a shared camera bind group layout matching CameraGroup and CameraWGSL. Pipelines rendering through the renderer list ViewportRenderer.CameraLayout at CameraGroup.
func NewViewportRendererWithLayout(cx *core.Scope, dev *gpu.Device, camLayout *gpu.BindGroupLayout) (*ViewportRenderer, error)NewViewportRendererWithLayout creates a ViewportRenderer that binds its per-view camera uniform buffers against an existing camera bind group layout (for example, CameraBuffer.Layout). Closing the renderer does not close camLayout.
func (r *ViewportRenderer) CameraLayout() *gpu.BindGroupLayoutCameraLayout returns the bind group layout pipelines list at CameraGroup when drawing through r, or nil for a nil receiver.
func (r *ViewportRenderer) Close() errorClose releases all GPU resources owned by r (its per-view uniform buffers, bind groups, and camera layout when created by NewViewportRenderer). Safe to call on a nil receiver or more than once.
func (r *ViewportRenderer) RenderEncoder(dev *gpu.Device, enc *gpu.Encoder, surface SurfaceDesc, views []CameraView, draw func(ViewportContext)) errorRenderEncoder renders all active views in execution order (offscreen RenderTexture views first, then main-surface viewports) into enc (for example on gpu.NewSoftwareRenderer). dev is the device enc was begun on: a device restored after a loss is a new *gpu.Device, and per-view camera bind groups created on any other device are dropped by the pass (nsgo-dev/nsgo#2345). The caller submits enc.Finish().
func (r *ViewportRenderer) RenderFrame(frame *gpu.Frame, surface SurfaceDesc, views []CameraView, draw func(ViewportContext)) errorRenderFrame renders all active views in execution order (offscreen RenderTexture views first, then main-surface viewports) into frame. When surface.Width or surface.Height is non-positive, both default to frame.Size(). It does not call frame.Submit(); the caller submits once all work is recorded.
func (r *ViewportRenderer) Valid() boolValid reports whether r is open and its camera bind group layout belongs to a live device.