La référence API provient des commentaires de documentation Go du code source et est rédigée en anglais.
package scenemodel
import "github.com/nsgo-dev/game/pkg/scenemodel"Vue d’ensemble
Package scenemodel gives the objects of a scene file their 3D look: the built-in primitive an object names in mesh, or the glTF 2.0 model it names in model, optionally narrowed to one node (modelNode) or one mesh (modelMesh), with the material file it names in material replacing the model's materials (sceneformat.ObjectDoc). So a 3D level can be written as a scene file, as a 2D one is, instead of being assembled in Go.
Build builds a scene into a scene3d node tree, as sceneformat.BuildNodes3D does, loads each model through a ModelResolver, as sceneformat.Build loads materials through a MaterialResolver, and attaches each object's geometry and materials to its node as a Drawable, with the node's LocalBounds set from the geometry. Assets is a ModelResolver, MaterialResolver and ImageResolver over a project's files. Built.AppendDrawItems lists the parts as render3d.DrawItem values for render3d.Queue, and Renderer uploads them to a gpu.Device and draws them lit by a render3d.LightRig and textured with their base color.
assets := scenemodel.NewAssets(os.DirFS(projectRoot))
built, err := scenemodel.Build(doc, scene.Root(), assets)
...
r, err := scenemodel.NewRenderer(cx, dev, built, scenemodel.RendererOptions{})
...
// Each frame:
r.Prepare(cam, lights)
pass := frame.BeginRenderPass(gpu.RenderPassDesc{})
r.Draw(pass)
pass.End()
game check reports a model file that is missing or does not load, and a modelNode or modelMesh the model does not have, with the scene file and line; game mv, game index and the editor's MoveFile rewrite the scenes that name a model when it moves (package refs).
Index
- Constantes
- Variables
- func BakeLightProbeGrid(b *Built, grid *LightProbeGrid, opts ProbeBakeOptions) (*render3d.LightProbeGrid, error)
- func BakeReflectionProbe(b *Built, probe *ReflectionProbe, opts ProbeBakeOptions) (*render3d.HDRCubemap, error)
- func DefaultLODScreenRatio(level, count int) float32
- func DrawItemID(di, pi int) uint64
- func DrawPipeline(m Material) uint32
- func FindMesh(doc *gltf.Document, name string) int
- func FindNode(doc *gltf.Document, name string) int
- func PrimitiveMesh(name string) (render3d.Mesh, error)
- type Assets
- func NewAssets(fsys fs.FS) *Assets
- func (a *Assets) GridMap(path string) (*world3d.GridMapDoc, error)
- func (a *Assets) HDR(path string) (*render3d.HDRImage, error)
- func (a *Assets) Image(path string) (image.Image, error)
- func (a *Assets) ImportSettings(modelPath string) (*importsettings.File, error)
- func (a *Assets) Library() *resource.Library
- func (a *Assets) LightProbeGrid(path string) (*render3d.LightProbeGrid, error)
- func (a *Assets) Material(path string) (*resource.Material, error)
- func (a *Assets) Model(path string) (*gltf.Document, error)
- type Built
- func Build(doc *sceneformat.SceneDoc, parent *scene3d.Node, models ModelResolver) (*Built, error)
- func (b *Built) ActiveCamera(aspect float32) (*scene3d.Camera, bool)
- func (b *Built) ActiveCameraObject() (*Camera, bool)
- func (b *Built) AppendDrawItems(dst []render3d.DrawItem) []render3d.DrawItem
- func (b *Built) AppendOccluders(dst []render3d.Occluder) []render3d.Occluder
- func (b *Built) HasBakedProbes() bool
- func (b *Built) HasSceneLighting() bool
- func (b *Built) LightRig() render3d.LightRig
- func (b *Built) Part(id uint64) (*Drawable, *Part, bool)
- func (b *Built) RasterizeOccluders(buf *render3d.OcclusionBuffer, viewProj math3d.Mat4) int
- func (b *Built) SampleLightProbes(worldPos math3d.Vec3) (render3d.IrradianceSH, bool)
- func (b *Built) ShadowLights() (dir *render3d.DirectionalLight, point *render3d.PointLight, spot *render3d.SpotLight)
- func (b *Built) WorldBounds() (math3d.AABB, bool)
- type Camera
- type Drawable
- type Environment
- type GridMapResolver
- type HDRResolver
- type ImageResolver
- type ImportSettingsResolver
- type Light
- type LightProbeGrid
- type LightProbeGridResolver
- type Material
- type ModelResolver
- type Occluder
- type Part
- type PartLOD
- type ProbeBakeOptions
- type ReflectionProbe
- type Renderer
- func NewRenderer(cx *core.Scope, dev *gpu.Device, b *Built, opts RendererOptions) (*Renderer, error)
- func (r *Renderer) ClearColor(fallback core.Color) core.Color
- func (r *Renderer) Close() error
- func (r *Renderer) Draw(pass *gpu.RenderPass)
- func (r *Renderer) DrawSky(pass *gpu.RenderPass)
- func (r *Renderer) HasSky() bool
- func (r *Renderer) Plan() render3d.RenderPlan
- func (r *Renderer) Prepare(cam *scene3d.Camera, lights render3d.LightRig) (render3d.RenderStats, error)
- func (r *Renderer) PrepareScene(cam *scene3d.Camera) (render3d.RenderStats, error)
- func (r *Renderer) RecordShadows(target render3d.ShadowPassTarget)
- func (r *Renderer) SetShading(s Shading) error
- func (r *Renderer) Shading() Shading
- type RendererOptions
- type Shading
- type Texture
Constantes
const AttachmentKey = "scenemodel.drawable"AttachmentKey is the scene3d.Node attachment under which Build stores the *Drawable of each node that draws geometry, so code that holds a node, such as an editor's picking, can find what it draws with scene3d.AttachmentAs.
const BaseColorGroup = render3d.PBRDrawGroup + 1BaseColorGroup is the bind group of the base color texture and sampler in ShaderWGSL, after render3d's camera (render3d.CameraGroup), scene lights and environment (render3d.LightGroup) and per-draw uniform (render3d.PBRDrawGroup).
Variables
var ShaderWGSL = buildShaderPreludeWGSL() + litFragmentBodyWGSL + ` let display = scene_tonemap_srgb(fogged, scene_env.params.x, scene_env.params.y);
var alpha = 1.0;
if (pbr_draw.emissive.w > 0.5) {
alpha = base.a;
}
return vec4<f32>(display, alpha);
}
`ShaderWGSL is the shader module Renderer draws with in ShadingLit: render3d metallic-roughness PBR lighting with directional/point/spot lights, optional directional/point/spot shadows, per-object reflection probes and light probe SH irradiance (falling back to scene sky IBL), distance and height fog, exposure, tone mapping, and a base color texture.
Fonctions
func BakeLightProbeGrid(b *Built, grid *LightProbeGrid, opts ProbeBakeOptions) (*render3d.LightProbeGrid, error)BakeLightProbeGrid renders b's 3D scene from every lattice point of grid into a small linear HDR cubemap using render3d on an offscreen software GPU renderer and integrates each probe's cosine-convolved L2 spherical harmonic irradiance coefficients.
func BakeReflectionProbe(b *Built, probe *ReflectionProbe, opts ProbeBakeOptions) (*render3d.HDRCubemap, error)BakeReflectionProbe renders b's 3D scene from probe's world position into all six faces of a linear HDR cubemap using render3d on an offscreen software GPU renderer, disabling existing baked probe contributions so rebaking captures direct lighting, shadows, sky, and emissives.
func DefaultLODScreenRatio(level, count int) float32DefaultLODScreenRatio returns the default MinScreenRatio threshold for level (0-indexed from finest to coarsest) in an LOD chain of count levels. The coarsest level (level >= count-1) always returns 0 (unbounded fallback).
func DrawItemID(di, pi int) uint64DrawItemID returns the render3d.DrawItem ID AppendDrawItems gives part pi of drawable di.
func DrawPipeline(m Material) uint32DrawPipeline returns the render3d.DrawItem PipelineID of a part drawn with m: 0 for a single-sided opaque or cutout surface, 1 for a double-sided one, 2 for a single-sided blended surface and 3 for a double-sided one. Renderer draws each with its own pipeline.
func FindMesh(doc *gltf.Document, name string) intFindMesh returns the index of the first mesh of doc named name, or -1 when none is, as sceneformat.ObjectDoc.ModelMesh looks it up.
func FindNode(doc *gltf.Document, name string) intFindNode returns the index of the first node of doc named name, or -1 when none is, as sceneformat.ObjectDoc.ModelNode looks it up.
func PrimitiveMesh(name string) (render3d.Mesh, error)PrimitiveMesh returns the geometry of the built-in primitive name, one of sceneformat.MeshPrimitives, in the object's space: indexed triangles wound counter-clockwise from outside, with unit normals and UVs from 0 to 1. Every call returns new slices.
The shapes are sized like Godot's default meshes so that an object's scale reads as meters: a box 1 on each side, a sphere 1 across, a plane 1 by 1 in the XZ plane facing +Y, a cylinder 1 across and 1 tall, and a capsule 1 across and 2 tall, each centered on the origin with its round axis along Y.
Types
type Assets struct {
// contains filtered or unexported fields
}Assets loads models, grid maps, material files, images, model import sidecars, Radiance HDR panoramas/cubemaps and baked light probe grids from a project's files, such as os.DirFS(projectRoot) or an embed.FS, and keeps each one it loaded, so it serves Build as a ModelResolver, a GridMapResolver, a sceneformat.MaterialResolver, an ImageResolver, an ImportSettingsResolver, an HDRResolver and a LightProbeGridResolver. Models load with gltf.LoadFS, so a .gltf file's separate buffers and images are read from beside it; grid maps parse with world3d.ParseGridMapWith; material files load through a resource.Library, which shares one value per path; images decode as PNG or JPEG; sidecars load through importsettings.Parse; HDR skies and reflection probes decode with render3d.DecodeHDR; light probe grids load with render3d.LoadLightProbeGridFS.
Its methods are safe to call from any goroutine.
func NewAssets(fsys fs.FS) *AssetsNewAssets returns Assets that read from fsys, rooted at the project root.
func (a *Assets) GridMap(path string) (*world3d.GridMapDoc, error)GridMap loads and parses the YAML grid map at path (*.gridmap.yaml or *.gridmap.yml) on first use and returns the same document after that.
func (a *Assets) HDR(path string) (*render3d.HDRImage, error)HDR decodes the Radiance .hdr panorama at path on first use and returns the same image after that.
func (a *Assets) Image(path string) (image.Image, error)Image decodes the PNG or JPEG image at path on first use and returns the same image after that.
func (a *Assets) ImportSettings(modelPath string) (*importsettings.File, error)ImportSettings reads and parses the *.import.yaml sidecar beside modelPath on first use and caches the result, returning (nil, nil) when no sidecar file exists.
func (a *Assets) Library() *resource.LibraryLibrary returns the resource.Library that Material loads from, so a game can reload edited material files into it (resource.Library.Reload).
func (a *Assets) LightProbeGrid(path string) (*render3d.LightProbeGrid, error)LightProbeGrid parses the baked light probe grid YAML file at path on first use and returns the same grid after that.
func (a *Assets) Material(path string) (*resource.Material, error)Material loads the material file at path through the Assets' resource.Library. It lets Assets serve as a sceneformat.MaterialResolver.
func (a *Assets) Model(path string) (*gltf.Document, error)Model loads the glTF model at path, a .gltf or .glb file, on first use and returns the same document after that.
type Built struct {
// Nodes3D holds the layer and object nodes, as sceneformat.BuildNodes3D builds them.
sceneformat.Nodes3D
// Drawables are the nodes that draw geometry, depth first in document order: an object's node, then the nodes made for its model's nodes or grid map instances, then its child objects.
Drawables []*Drawable
// GridMaps maps each object ID that named ObjectDoc.GridMap to its constructed runtime *world3d.GridMap, for collision queries, raycasting, or custom instancing.
GridMaps map[string]*world3d.GridMap
// Occluders are the occluders built from scene objects that set ObjectDoc.Occluder, in document order.
Occluders []Occluder
// LODHysteresis is the largest non-zero lodHysteresis declared by any model import sidecar in the built scene, or 0 when none sets one.
LODHysteresis float32
// Lights are the scene's 3D light objects in depth-first document order, linked to their scene3d nodes.
Lights []*Light
// Cameras are the scene's 3D camera objects in depth-first document order, linked to their scene3d nodes.
Cameras []*Camera
// ReflectionProbes are the scene's 3D reflection probe objects in depth-first document order, linked to their scene3d nodes and any loaded baked cubemaps.
ReflectionProbes []*ReflectionProbe
// LightProbeGrids are the scene's 3D light probe grid objects in depth-first document order, linked to their scene3d nodes and any loaded baked SH irradiance grids.
LightProbeGrids []*LightProbeGrid
// Environment holds the resolved sky, ambient/IBL lighting, fog, tone mapping and exposure from SceneDoc.Environment.
Environment Environment
// Meshes and Materials count the distinct MeshID and MaterialID values the parts use.
Meshes, Materials int
}Built is a scene's 3D node tree with the geometry, lights, cameras and environment each scene declares, from Build.
func Build(doc *sceneformat.SceneDoc, parent *scene3d.Node, models ModelResolver) (*Built, error)Build builds doc's layers and objects into a 3D node tree under parent, as sceneformat.BuildNodes3D does, and gives every object that names a look its geometry and material:
- ObjectDoc.Mesh, a built-in primitive (PrimitiveMesh), drawn on the object's node with the object's material, or with a white, non-metallic, fully rough surface when it names none;
- ObjectDoc.Model, a glTF model loaded through models: with ModelMesh, that mesh drawn on the object's node; with ModelNode, that node's mesh drawn on the object's node and each of its descendants as a child node with its own transform; and with neither, a child node for each root node of the model's default scene (or of its first scene, or every parentless node when it has none) and their descendants. The model's materials are used unless the object names a material file, which replaces them all.
- ObjectDoc.GridMap, a 3D grid map loaded through a GridMapResolver and its glTF mesh library through models, instanced with world3d.GridMap.BuildInstances as child nodes of the object's node sharing the tile meshes and materials, with the built *world3d.GridMap recorded in Built.GridMaps.
A node Build makes for a glTF node is named after it, and is added after the object's child objects. Every node that draws gets its geometry's bounds as its LocalBounds and its *Drawable as the attachment AttachmentKey. A model draws in its bind pose with its meshes' default morph weights applied; skins, cameras, lights, animations and vertex colors are not used, nor are points and lines. A primitive without normals draws flat-shaded, and the base color texture's UV set and KHR_texture_transform are applied to the UVs.
models may be nil when no object names a model or grid map. It must implement sceneformat.MaterialResolver when an object names a material file, ImageResolver when such a file names a texture, and GridMapResolver when an object names a grid map; Assets does all four. A material file is read when Build runs: build again to see it edited.
Build returns an error and leaves parent unchanged when doc is invalid or still instances or inherits other scene files (pass it through sceneformat.Resolve first), when parent is nil, or when a model, node, mesh, grid map, material or image cannot be loaded or found.
func (b *Built) ActiveCamera(aspect float32) (*scene3d.Camera, bool)ActiveCamera builds a *scene3d.Camera from the scene's active 3D camera object (ActiveCameraObject) for the given aspect ratio (width / height).
func (b *Built) ActiveCameraObject() (*Camera, bool)ActiveCameraObject returns the scene's active visible, enabled 3D camera object: the one marked Current, or the first visible, enabled 3D camera in document order when none is marked.
func (b *Built) AppendDrawItems(dst []render3d.DrawItem) []render3d.DrawItemAppendDrawItems appends a render3d.DrawItem for every part of every drawable whose node is visible and enabled, in Drawables order, and returns the extended slice for render3d.Queue.Build. An item's ID holds the drawable's index in Drawables in its high 32 bits and the part's index in its low 32 bits (DrawItemID); its PipelineID is DrawPipeline of the part's material; its Transform is the node's world matrix and WorldBounds the part's bounds under it.
func (b *Built) AppendOccluders(dst []render3d.Occluder) []render3d.OccluderAppendOccluders appends a render3d.Occluder for every visible, enabled occluder in b.Occluders at its node's current world transform and returns the extended slice.
func (b *Built) HasBakedProbes() boolHasBakedProbes reports whether b contains at least one reflection probe with a baked cubemap or light probe grid with baked irradiance data.
func (b *Built) HasSceneLighting() boolHasSceneLighting reports whether the built scene declares any 3D lights, an environment section, or baked reflection/light probes.
func (b *Built) LightRig() render3d.LightRigLightRig evaluates every visible, enabled light node in b at its current world transform and returns a render3d.LightRig combining b.Environment.Ambient with the scene's directional, point and spot lights. Within each category, shadow-casting lights come first so slot 0 matches render3d's shadow sampling slots.
func (b *Built) Part(id uint64) (*Drawable, *Part, bool)Part returns the drawable and part a render3d.DrawItem ID from AppendDrawItems names, and false when it names none.
func (b *Built) RasterizeOccluders(buf *render3d.OcclusionBuffer, viewProj math3d.Mat4) intRasterizeOccluders clears buf, rasterizes every visible, enabled occluder in b for viewProj, builds the Hi-Z pyramid when at least one occluder was rasterized, and returns the number of occluders rasterized.
func (b *Built) SampleLightProbes(worldPos math3d.Vec3) (render3d.IrradianceSH, bool)SampleLightProbes evaluates the scene's visible, enabled, baked light probe grids at worldPos and returns the trilinearly interpolated L2 spherical harmonic irradiance scaled by the chosen grid's intensity. When multiple baked grids contain worldPos, the smallest-volume grid wins (ties break in document order); when worldPos is outside every grid, the nearest grid is sampled (clamped to its boundary). Returns (zero, false) when no visible baked light probe grid exists.
func (b *Built) ShadowLights() (dir *render3d.DirectionalLight, point *render3d.PointLight, spot *render3d.SpotLight)ShadowLights returns the first visible shadow-casting directional, point and spot lights in b, matching slot 0 of each LightRig slice.
func (b *Built) WorldBounds() (math3d.AABB, bool)WorldBounds returns the union of the world-space AABBs of every visible, enabled drawable in b, or false when b has none.
type Camera struct {
// Node is the scene3d node placing and orienting the camera.
Node *scene3d.Node
// Object is the ID of the scene object the camera belongs to.
Object string
// Doc is a copy of the source camera definition.
Doc sceneformat.Camera3DDoc
}Camera is a 3D camera built from a scene object (sceneformat.ObjectDoc.Camera), attached to its scene3d.Node so moving or rotating the node updates the camera's viewpoint.
func (c *Camera) SceneCamera(aspect float32) *scene3d.CameraSceneCamera constructs a *scene3d.Camera from c's current node world transform and projection settings for the given viewport aspect ratio (width / height).
type Drawable struct {
// Node is the scene3d node the parts are drawn at; its LocalBounds hold the parts' bounds.
Node *scene3d.Node
// Object is the ID of the scene object the drawable belongs to.
Object string
// Parts are what the node draws, in the order the model lists them.
Parts []Part
}Drawable is a node that draws geometry: an object's node, or a node Build made for a node of the object's model.
type Environment struct {
// Present reports whether the scene declared an environment section.
Present bool
// Doc is a copy of SceneDoc.Environment when Present is true.
Doc sceneformat.EnvironmentDoc
// Ambient is the linear ambient fill light.
Ambient render3d.AmbientLight
// SkyKind is the resolved sky kind, or empty when Doc.Sky is nil.
SkyKind sceneformat.SkyKind
// SkyColor is the linear RGB color of a SkyColor sky.
SkyColor math3d.Vec3
// SkyClearColor is the display-space tone-mapped clear color for SkyColor.
SkyClearColor core.Color
// SkyCubemap is the linear HDR cubemap for SkyGradient or SkyHDR skies, or nil.
SkyCubemap *render3d.HDRCubemap
// IBLIrradiance is the L2 spherical-harmonic diffuse irradiance when IBLIntensity > 0.
IBLIrradiance render3d.IrradianceSH
// IBLPrefilter is the GGX prefiltered specular cubemap when IBLIntensity > 0.
IBLPrefilter *render3d.HDRCubemap
// IBLIntensity is the effective IBL multiplier (>= 0).
IBLIntensity float32
// Fog is the resolved render3d.Fog configuration.
Fog render3d.Fog
// HasFog reports whether distance or height fog is active.
HasFog bool
// ToneMap holds the tone mapping operator and exposure.
ToneMap render3d.ToneMapOptions
}Environment is the resolved 3D environment built from sceneformat.SceneDoc.Environment, ready to drive render3d's sky, ambient fill, image-based lighting, fog, tone mapping and exposure.
type GridMapResolver interface {
GridMap(path string) (*world3d.GridMapDoc, error)
}GridMapResolver loads the 3D grid map files objects name in sceneformat.ObjectDoc.GridMap. path is the slash-separated path from the project root that the scene file writes, such as "levels/dungeon.gridmap.yaml".
type HDRResolver interface {
HDR(path string) (*render3d.HDRImage, error)
}HDRResolver loads the Radiance .hdr image at path, a slash-separated path from the project root, for an HDR sky (sceneformat.SkyDoc.HDR) or a baked reflection probe cubemap (sceneformat.ReflectionProbeDoc.Cubemap).
type ImageResolver interface {
Image(path string) (image.Image, error)
}ImageResolver loads the image at path, a slash-separated path from the project root, for the texture of a material file (resource.Material.Texture).
type ImportSettingsResolver interface {
ImportSettings(modelPath string) (*importsettings.File, error)
}ImportSettingsResolver loads the *.import.yaml sidecar of the model at modelPath, a slash-separated path from the project root such as "models/tree.glb". It returns (nil, nil) when the model has no sidecar file.
type Light struct {
// Node is the scene3d node placing and aiming the light.
Node *scene3d.Node
// Object is the ID of the scene object the light belongs to.
Object string
// Doc is a copy of the source light definition.
Doc sceneformat.LightDoc
}Light is a 3D light built from a scene object (sceneformat.ObjectDoc.Light), attached to its scene3d.Node so moving or rotating the node updates the light's world position and direction (-Z in local space).
type LightProbeGrid struct {
// Node is the scene3d node placing the light probe grid.
Node *scene3d.Node
// Object is the ID of the scene object the light probe grid belongs to.
Object string
// Doc is a copy of the source light probe grid definition.
Doc sceneformat.LightProbeGridDoc
// Grid is the loaded baked *render3d.LightProbeGrid when Doc.Data is set, or nil when unbaked.
Grid *render3d.LightProbeGrid
}LightProbeGrid is a 3D light probe grid built from a scene object (sceneformat.ObjectDoc.LightProbeGrid), linked to its scene3d.Node and holding any baked L2 spherical harmonic irradiance grid loaded from Doc.Data.
func (g *LightProbeGrid) WorldBounds() math3d.AABBWorldBounds returns the world-space axis-aligned volume covering g's light probes.
type LightProbeGridResolver interface {
LightProbeGrid(path string) (*render3d.LightProbeGrid, error)
}LightProbeGridResolver loads the baked light probe grid YAML file at path, a slash-separated path from the project root, for a scene object's light probe grid (sceneformat.LightProbeGridDoc.Data).
type Material struct {
// BaseColor is the linear RGBA base color, multiplied by BaseColorTexture's texels.
BaseColor math3d.Vec4
// Metallic and Roughness are the metalness and perceptual roughness, from 0 to 1.
Metallic, Roughness float32
// Emissive is the linear RGB light the surface gives off, its glTF emissive strength included.
Emissive math3d.Vec3
// BaseColorTexture is the sRGB base color image, or nil for none.
BaseColorTexture *Texture
// AlphaMode says how the base color's alpha is used: ignored, a cutout at AlphaCutoff, or blended over what is behind.
AlphaMode render3d.AlphaMode
// AlphaCutoff is the alpha below which a render3d.AlphaMask surface is discarded.
AlphaCutoff float32
// DoubleSided draws the back faces too, lit from the side the viewer sees.
DoubleSided bool
}Material is the surface a Part draws with, in glTF 2.0's metallic-roughness terms.
func MaterialFromFile(rm *resource.Material) MaterialMaterialFromFile converts a material file into a Material without its texture: the base color and emissive CSS colors converted from sRGB to linear light, the base color's alpha times the opacity, render3d.AlphaBlend when that alpha is below 1, the metalness, roughness and double-sidedness as written. Its 2D blend mode does not apply in 3D, and a 3D surface is always lit, so Unlit is not used either.
type ModelResolver interface {
Model(path string) (*gltf.Document, error)
}ModelResolver loads the glTF models objects name in sceneformat.ObjectDoc.Model, as sceneformat.MaterialResolver loads their material files. path is the slash-separated path from the project root that the scene file writes, such as "models/crate.glb". A resolver that returns the same document for the same path lets every object that names it share its decoded textures.
The ModelResolver given to Build may also implement sceneformat.MaterialResolver, to resolve the material files objects name in ObjectDoc.Material, ImageResolver, to load the textures those material files name, GridMapResolver, to load the 3D grid maps objects name in ObjectDoc.GridMap, ImportSettingsResolver, to read a model's *.import.yaml sidecar for LOD definitions, and HDRResolver, to load Radiance .hdr sky panoramas named in EnvironmentDoc.Sky.HDR. Assets implements all six.
type Occluder struct {
// Node is the scene3d node the occluder follows.
Node *scene3d.Node
// Object is the ID of the scene object that declared the occluder.
Object string
// Mode is sceneformat.OccluderModel or sceneformat.OccluderBox.
Mode sceneformat.OccluderMode
// LocalBounds is the occluder's bounding box in Node's local space.
LocalBounds math3d.AABB
// DoubleSided reports whether both front and back faces occlude.
DoubleSided bool
// contains filtered or unexported fields
}Occluder is one occluder attached to a Built 3D scene (Built.Occluders), produced for any scene object that sets sceneformat.ObjectDoc.Occluder.
func (o Occluder) RenderOccluder() render3d.OccluderRenderOccluder returns a render3d.Occluder positioned at o.Node's current world matrix without copying vertex or index slices.
type Part struct {
// Mesh is the triangle geometry in the space of the node that draws it.
Mesh render3d.Mesh
// MeshID identifies Mesh among the meshes of one Built, from 0 up: parts that draw the same glTF primitive or primitive shape share it, as render3d.DrawItem.MeshID expects.
MeshID uint32
// Material is the surface Mesh draws with.
Material Material
// MaterialID identifies Material among the materials of one Built, from 0 up, shared by the parts that use the same glTF material or material file.
MaterialID uint32
// LODs are the detail levels for this part, ordered from finest (index 0, matching Mesh and MeshID) to coarsest. Empty when the part has only one detail level.
LODs []PartLOD
// contains filtered or unexported fields
}Part is one piece of geometry a node draws with one material.
type PartLOD struct {
// Mesh is the triangle geometry in the space of the node that draws it.
Mesh render3d.Mesh
// MeshID identifies Mesh among the meshes of one Built, matching render3d.LODLevel.MeshID.
MeshID uint32
// MinScreenRatio is the minimum viewport-height fraction in [0, 1] at which this level is drawn (render3d.LODLevel.MinScreenRatio).
MinScreenRatio float32
// MaxDistance is the optional maximum camera distance in world units at which this level is drawn (render3d.LODLevel.MaxDistance).
MaxDistance float32
// Triangles and Vertices are the geometry counts of Mesh.
Triangles uint32
Vertices uint32
}PartLOD is one level of detail of a Part, ordered from finest (index 0) to coarsest.
type ProbeBakeOptions struct {
// Size overrides the cubemap face resolution in texels; non-positive uses the probe's
// Resolution for reflection probes (default 64) or 16 for light probe grids.
Size int
// Near and Far set the 90-degree cubemap face clip planes; non-positive Near defaults to 0.05,
// and Far <= Near defaults to Near + 200.
Near float32
Far float32
// FallbackLights supplies the direct light rig used when the built scene has no 3D lights
// and no environment section. When nil, Built.LightRig() is always used.
FallbackLights *render3d.LightRig
// FallbackClearColor sets the background clear color when the scene has no solid or cubemap sky.
FallbackClearColor core.Color
}ProbeBakeOptions configures BakeReflectionProbe and BakeLightProbeGrid.
type ReflectionProbe struct {
// Node is the scene3d node placing the reflection probe.
Node *scene3d.Node
// Object is the ID of the scene object the reflection probe belongs to.
Object string
// Doc is a copy of the source reflection probe definition.
Doc sceneformat.ReflectionProbeDoc
// Cubemap is the loaded base-mip linear HDR cubemap when Doc.Cubemap is set, or nil when unbaked.
Cubemap *render3d.HDRCubemap
// Prefiltered is the GGX roughness-prefiltered HDR cubemap built from Cubemap, or nil when unbaked.
Prefiltered *render3d.HDRCubemap
}ReflectionProbe is a 3D reflection probe built from a scene object (sceneformat.ObjectDoc.ReflectionProbe), linked to its scene3d.Node and holding any baked cubemap and GGX prefiltered specular mip chain loaded from Doc.Cubemap.
func (p *ReflectionProbe) RuntimeProbe(gpuCube *render3d.GPUCubemap) *render3d.ReflectionProbeRuntimeProbe builds a *render3d.ReflectionProbe reflecting p's current node transform, visibility, and baked state, optionally attaching gpuCube for GPU shading.
func (p *ReflectionProbe) WorldBounds() (pos, boxMin, boxMax math3d.Vec3)WorldBounds returns the probe's capture origin and world-space axis-aligned influence box [boxMin, boxMax].
type Renderer struct {
// contains filtered or unexported fields
}Renderer draws a Built scene's drawables, lights, shadows, reflection probes, light probe grids and environment on a gpu.Device, culled and ordered by a render3d.Queue (frustum culling, software occlusion culling when Built has occluders, LOD selection with hysteresis, opaque surfaces front to back by pipeline, material and mesh, blended ones back to front). Each frame, call PrepareScene (or Prepare with custom lights), call RecordShadows before the main render pass when any light casts shadows, and call DrawSky and Draw inside the render pass. Its GPU resources belong to the scope given to NewRenderer, or are released by Close. Use it from the engine goroutine, like the device.
func NewRenderer(cx *core.Scope, dev *gpu.Device, b *Built, opts RendererOptions) (*Renderer, error)NewRenderer uploads every mesh, texture, material, sky cubemap, IBL prefilter and shadow map of b to dev, scoped to cx, and creates the buffers and pipelines that draw them. b's drawables are fixed from here on; their nodes may move, hide and show.
func (r *Renderer) ClearColor(fallback core.Color) core.ColorClearColor returns the scene environment's tone-mapped solid sky color when SkyKind is SkyColor, or fallback otherwise.
func (r *Renderer) Close() errorClose releases every GPU resource of r now instead of when its scope is disposed. It is safe to call on nil and more than once; after it, Prepare returns an error and Draw records nothing.
func (r *Renderer) Draw(pass *gpu.RenderPass)Draw records the parts Prepare planned into pass: the opaque and cutout ones first, then the blended ones back to front. pass must have a color attachment of RendererOptions.ColorFormat and a depth attachment of its DepthFormat. It records nothing once the renderer is closed.
func (r *Renderer) DrawSky(pass *gpu.RenderPass)DrawSky draws the scene's gradient or HDR skybox cubemap into pass using the scene's exposure and tone mapping operator. Call it before Draw inside the render pass; it does nothing when the scene has no cubemap sky.
func (r *Renderer) HasSky() boolHasSky reports whether the built scene has a gradient or HDR skybox cubemap that DrawSky draws.
func (r *Renderer) Plan() render3d.RenderPlanPlan returns the render3d.RenderPlan from the most recent Prepare call, allowing callers to inspect selected LOD indices and culling statistics.
func (r *Renderer) Prepare(cam *scene3d.Camera, lights render3d.LightRig) (render3d.RenderStats, error)Prepare writes cam and lights to their buffers and each visible part's world transform to its draw buffer, and plans the frame with the renderer's render3d.Queue: frustum culling and draw order. Call it once a frame before the render pass that Draw records into. It returns the plan's statistics, and an error when lights fails render3d's validation or the renderer is closed.
func (r *Renderer) PrepareScene(cam *scene3d.Camera) (render3d.RenderStats, error)PrepareScene prepares the frame using the built scene's own 3D lights (Built.LightRig), shadow-casting lights (Built.ShadowLights) and environment (sky, IBL, fog, tone mapping, exposure). Call RecordShadows before the main render pass when any light casts shadows, then DrawSky and Draw inside the pass.
func (r *Renderer) RecordShadows(target render3d.ShadowPassTarget)RecordShadows records the depth shadow passes for any active shadow-casting lights prepared by PrepareScene into target (a *gpu.Frame or *gpu.Encoder). Call it before BeginRenderPass for the main scene pass. It does nothing when no shadows are active or in ShadingUnlit.
func (r *Renderer) SetShading(s Shading) errorSetShading makes Draw shade the parts with s from the next frame on. The first change to ShadingUnlit creates its pipelines, under the scope given to NewRenderer, and returns an error when they cannot be created, leaving the shading as it was; so does an unknown Shading or a closed renderer.
func (r *Renderer) Shading() ShadingShading returns how Draw shades the parts (SetShading).
type RendererOptions struct {
// Label prefixes the debug labels of the GPU resources; empty is "scenemodel".
Label string
// ColorFormat is the color attachment's format; gpu.FormatUndefined is the device's surface format.
ColorFormat gpu.TextureFormat
// DepthFormat is the depth attachment's format, which every pass the renderer draws in must have; gpu.FormatUndefined is gpu.FormatDepth24Plus.
DepthFormat gpu.TextureFormat
// Retained keeps CPU copies of the buffers and textures so NSGo recreates them after a device loss (gpu.BufferDesc.Retained).
Retained bool
// DisableOcclusion disables CPU software occlusion culling even when Built holds occluders.
DisableOcclusion bool
// OcclusionWidth and OcclusionHeight configure the software render3d.OcclusionBuffer resolution; non-positive values use render3d's defaults (128x72).
OcclusionWidth, OcclusionHeight int
// LODHysteresis overrides the relative deadband [0, 0.5] used by render3d.Queue for LOD selection; 0 uses Built.LODHysteresis.
LODHysteresis float32
// LinearOutput compiles linear HDR shaders (no tone mapping or sRGB encode) for rendering into a floating-point target such as FormatRGBA16Float when baking reflection or light probes.
LinearOutput bool
// DisableProbes excludes baked local reflection probes and light probe grids from shading (still keeping direct lights, shadows, sky and emissives), used when baking or rebaking probes.
DisableProbes bool
}RendererOptions configures NewRenderer.
type Shading uint8Shading says how Renderer shades the parts it draws (Renderer.SetShading).
const (
// ShadingLit lights every part with the render3d.LightRig given to Prepare (or built.LightRig via PrepareScene), plus the scene's environment. It is a Renderer's shading until SetShading changes it.
ShadingLit Shading = iota
// ShadingUnlit draws every part at its textured base color plus its emissive color and ignores the lights, as an editor's unlit view shows a scene.
ShadingUnlit
)func (s Shading) String() stringString returns "lit" or "unlit", or "Shading(n)" for any other value.
type Texture struct {
// Name says where the image came from, such as "models/crate.glb image 0" or "textures/stone.png", for debug labels.
Name string
// Image is the decoded image, whose color is sRGB.
Image image.Image
// Sampler is how the image is filtered and wrapped: the glTF texture's sampler, or linear filtering with repeat wrapping for a material file's texture.
Sampler render3d.SamplerOptions
// Mipmaps reports whether the sampler filters between mip levels, so the image needs a mip chain.
Mipmaps bool
}Texture is a decoded image a Material samples. Build returns one *Texture per image and sampler, which every material that uses them shares, so a renderer uploads each once.