scene3d

package
v0.1.18 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Scene3D(实验性)

Author: HyperparameterSI

纯 Go、可选的三维视口,导入路径: github.com/HyperparameterSI/golet/backend/plugins/scene3d。 不依赖浏览器、前端代码、cgo 或第三方引擎运行时。

当前是软件光栅器,不是已完成的 GPU 游戏引擎。 Golet 的 GPU 合成器负责 显示最终图像;三角形变换、裁剪、光照和深度测试在 CPU 上执行。 没有“比其他引擎快 10~100 倍”的对比证据。

已实现

  • 右手坐标系,透视摄像机,仿射模型变换,索引网格和共享几何实例。
  • 六个视锥平面的三角形裁剪、包围盒视锥剔除、背面剔除和逐像素深度测试。
  • 不透明纯色材质、双面/无光照模式、环境光和方向光(平面 Lambert 着色)。
  • 有文件大小/顶点数/三角形数限制的 OBJ 加载;只接受已三角化的面。
  • scene3d.View 参与原生 UI 的布局、裁剪、输入和图像合成,可与 Forma 混排。
  • 可选动画回调,遵循减少动态效果偏好;默认无持续动画或后台计时器。
  • 稳定尺寸下复用颜色、深度、顶点工作缓冲和 UI 位图;静态帧复用。
  • 可替换 Renderer(当前接口输出 CPU 图像),可查询实际工作计数和缓冲容量。

运行示例

Studio 已集成「插件 → Scene3D · 三维视口」:运行 pnpm dev,打开该项即可体验 四种场景、参数调节和可复制的 Go 使用示例。其界面跟随 Studio 原生主题设置。

在仓库根目录:

go run ./backend/examples/scene3d
go run ./backend/examples/scene3d backend/examples/scene3d/assets/pyramid.obj
# 可选:加载自己的已三角化 OBJ;不会自动缩放或居中模型。
go run ./backend/examples/scene3d /path/to/model.obj

示例提供 Forma 按钮:环绕摄像机、旋转模型、播放/暂停、切换明暗主题。 点击三维视口获得键盘焦点,左右方向键环绕。仅模型与背景颜色跟随示例设置; 材质不会被组件主题隐式改写。默认窗口沿用 HiddenInset 和原生交通灯。

接入

场景、网格和摄像机只创建一次,在应用状态中保存;不要在每帧创建网格。

// Author: HyperparameterSI
mesh := scene3d.Cube()
scene := &scene3d.Scene{
    Background: color.RGBA{18, 24, 38, 255},
    Ambient: .2,
    Lights: []scene3d.DirectionalLight{
        {Direction: scene3d.Vec3{X: 2, Y: 4, Z: 3}, Intensity: .8},
    },
    Instances: []scene3d.Instance{{
        Mesh: mesh,
        Material: scene3d.Material{Color: color.RGBA{100, 160, 240, 255}},
    }},
}
camera := scene3d.DefaultCamera()
var revision uint64

// 在 ui.View 的构建函数中,与 forma.Button 等组件放在同一布局中:
scene3d.View(c, scene3d.ViewOptions{
    Scene: scene, Camera: camera, Revision: revision,
    MaxDimension: 960,
    OnFrame: func(stats scene3d.Stats, err error) {
        if err != nil { log.Printf("scene3d: render failed: %v", err) }
    },
}).Fill()

修改实例、材质、灯光或背景后必须增加 Revision,通过正常的窗口更新流程 重绘。摄像机与尺寸自动参与缓存键。Animate func(time.Time) 在可见绘制帧中 更新场景并触发重绘,不需要手动增加 Revision;使用传入时间进行固定步长或 有界增量更新。暂停时将 Animate 设为 nil。示例演示了变换动画,不包含骨骼动画。

Scene 是调用者拥有的数据,渲染期间不能并发修改。View、位图与动画回调 在 UI 线程运行;后台加载完成后通过 Window.Update 交付场景。独立软件渲染可在 工作 goroutine 上进行,但每个工作线程要有自己的 Target,交付图像时要保证 其生命周期,不能同时改写正在显示的像素。

资源与扩展边界

鼠标摄像机控制

OrbitControls 是可复用的 Y-up 环绕控制器,不产生后台动画。 左键拖动控制水平与俯仰角(限制在极点以内),Shift+左键或中键平移观察中心, 滚轮/捏合控制距离。支持自定义旋转/缩放速度与最小/最大观察距离。 在窗口状态中保留一个控制器,并在构建视口时接入:

// Author: HyperparameterSI
// controls、camera、height 都保存在窗口状态中。
scene3d.View(c, scene3d.ViewOptions{
    Scene: world, Camera: camera, Revision: revision,
    OnInput: func(ev ui.InputEvent) bool {
        return controls.Handle(&camera, ev, height)
    },
}).Fill().DrawOver(func(_ *ui.Painter, r ui.Rect) { height = r.H })

控制器类型为 scene3d.OrbitControls,height 为 float32,使用显示高度而非渲染 像素,因此切换分辨率不改变平移灵敏度。Golet 将捕获后的移动、松开事件发送到 视口,即使指针已拖出视口;失焦也会发送松开。移除视口、切换页签或重置摄像机 时调用 controls.Cancel() 清除拖动状态。Studio 的使用示例页包含完整接入片段。

缓冲与渲染器
  • NewMesh 复制输入并保持几何不可变;多个 Instance 可共享 Mesh。
  • 每个像素需要 4 字节 RGBA 和 4 字节深度。640×360 两个缓冲合计约 1.76 MiB。
  • MaxPixels 限制单目标为 4,194,304 像素(颜色+深度 32 MiB)。变换顶点另计。
  • Scale 默认为每 DIP 一个渲染像素,不会自动按 Retina 放大。MaxDimension 默认 1024、上限 2048,等比例限制分辨率;这是质量/资源的显式权衡。
  • Stats.BufferBytes 不包含模型、Go 对象头、UI/GPU 纹理或驱动内存。
  • Renderer 可替换图像生成算法;NewRenderer 每次挂载仅调用一次,更换需重挂载。 它不是原生 GPU 纹理/命令队列接口。
  • 直接使用 Software.Render 时,Target.Image 为借用数据,下次 Render 会覆盖; Target.Release 释放 CPU 引用。视口移除后其状态随 UI 生命周期回收。

尚未实现:原生 GPU 三维管线、GPU 实例化、纹理采样、PBR、透明排序、阴影、 抗锯齿、glTF/GLB、骨骼动画、物理、编辑器。OBJ 的 UV、法线和材质声明被忽略, 不打开 MTL 或纹理文件;不支持的几何记录和非三角面明确报错。

验证与性能

CGO_ENABLED=0 go test ./backend/plugins/scene3d ./backend/examples/scene3d
CGO_ENABLED=0 go test ./backend/plugins/scene3d -run '^$' -bench BenchmarkSoftware -benchmem -count=3

2026-10-28,Apple M5 / macOS arm64 / Go 1.27.1,三次中位数:

软件光栅器,640×360 每帧时间 预热后分配
1 个共享网格实例(立方体) 0.181 ms 0 B / 0 次
100 个共享网格实例(立方体) 0.369 ms 0 B / 0 次

场景由基准源码固定,包含视锥剔除,并非所有三角形都覆盖屏幕。 只测 Render;不含 OBJ 加载、UI 构建、纹理上传、呈现或真实游戏逻辑。 不能换算成游戏 FPS,也不能据此声称超过其他引擎。GUI 交互由 ui.Tester 检查, 并不等于已经完成各平台真实显卡验证。

原始结果见 基准输出。 研究来源和 GPU 阶段设计见 设计记录。

Documentation

Overview

Package scene3d supplies an opt-in 3D viewport for Golet native UI. The initial renderer is a pure-Go software rasterizer, not a native GPU engine. It supports indexed meshes, six-plane clipping, depth testing, opaque flat materials and directional lighting. No frontend is required.

Index

Constants

View Source
const MaxPixels = 4 * 1024 * 1024

MaxPixels bounds color/depth buffer allocation (32 MiB combined). A viewport can render at lower resolution than its display rectangle.

Variables

This section is empty.

Functions

func View

func View(c *ui.Context, o ViewOptions) ui.Element

View creates a normal UI element containing a 3D image. It participates in layout, clipping, overlays and input with Forma in the same native window. Call only while building a ui.View, and mutate scenes on that UI thread. The renderer is CPU-based; the resulting image uses Golet's usual compositor.

Types

type Camera

type Camera struct {
	Position, Target, Up Vec3
	FOVY, Near, Far      float32
}

Camera is a perspective camera. FOVY is vertical radians; Near must be positive and Far greater than Near. Defaults are explicit via DefaultCamera.

func DefaultCamera

func DefaultCamera() Camera

type DirectionalLight

type DirectionalLight struct {
	Direction Vec3
	Intensity float32
}

DirectionalLight.Direction points FROM the surface TOWARD the light. Intensity is nonnegative. Lighting is flat Lambert plus Scene.Ambient.

type Instance

type Instance struct {
	Mesh      *Mesh
	Transform Mat4
	Material  Material
}

Instance references shared geometry with a per-instance affine transform.

type Mat4

type Mat4 [16]float32

Mat4 is a column-major matrix acting on column vectors. Use Identity for objects without a transform; Instance's zero matrix also means identity.

func Identity

func Identity() Mat4

func RotationY

func RotationY(radians float32) Mat4

RotationY turns by radians about the up axis.

func Scaling

func Scaling(v Vec3) Mat4

func Translation

func Translation(v Vec3) Mat4

func (Mat4) Mul

func (a Mat4) Mul(b Mat4) Mat4

Mul returns a*b: b is applied first.

type Material

type Material struct {
	Color              color.RGBA
	Unlit, DoubleSided bool
}

Material is opaque flat shading. Alpha must be 255; blending is not yet supported. Unlit bypasses lighting; DoubleSided disables back-face culling.

type Mesh

type Mesh struct {
	// contains filtered or unexported fields
}

Mesh owns immutable geometry, shared by any number of instances. NewMesh copies its input. CCW triangles face outwards.

func Cube

func Cube() *Mesh

Cube returns a unit cube centered on the origin. Retain and share it.

func LoadOBJ

func LoadOBJ(r io.Reader, limits OBJLimits) (*Mesh, error)

LoadOBJ loads triangulated Wavefront OBJ positions and faces. Positive and relative negative indices and v/vt/vn syntax are accepted. UVs, normals and materials are not imported: the initial renderer uses flat solid materials. Polygons must be triangulated by the exporter. No external files are opened.

func NewMesh

func NewMesh(vertices []Vec3, indices []uint32) (*Mesh, error)

NewMesh validates and copies indexed triangles. Degenerate triangles are legal and skipped during rendering. Vertices must be finite.

func (*Mesh) Geometry

func (m *Mesh) Geometry() ([]Vec3, []uint32)

Geometry returns independent copies for exporters or alternate renderers.

func (*Mesh) TriangleCount

func (m *Mesh) TriangleCount() int

func (*Mesh) VertexCount

func (m *Mesh) VertexCount() int

type OBJLimits

type OBJLimits struct {
	Bytes               int64
	Vertices, Triangles int
}

OBJLimits bounds untrusted input. Zero fields select defaults: 16 MiB, 250,000 vertices and 500,000 triangles. Lines are limited to 64 KiB.

type OrbitControls

type OrbitControls struct {
	// RotationSpeed is radians per DIP, default .006.
	RotationSpeed float32
	// ZoomSpeed is the exponential wheel factor per DIP, default .002.
	ZoomSpeed float32
	// Distance bounds default to max(.25, Near*2) and Far*.9 respectively.
	MinDistance, MaxDistance float32
	// contains filtered or unexported fields
}

OrbitControls provides event-driven, Y-up camera navigation. Keep one per viewport on its UI thread. Left drag orbits, Shift+left or middle drag pans, wheel and touchpad pinch dolly. It never schedules animation or allocates resources. Camera.Target is the orbit pivot and moves together with panning.

func (*OrbitControls) Cancel

func (o *OrbitControls) Cancel()

Cancel releases drag state when removing a viewport or resetting its camera. Golet also delivers pointer-up when a captured window loses focus.

func (*OrbitControls) Handle

func (o *OrbitControls) Handle(camera *Camera, ev ui.InputEvent, viewportHeight float32) bool

Handle consumes navigation events and updates camera. viewportHeight is the displayed height in DIPs, used to make panning independent of render scale. Forward events from ViewOptions.OnInput; Golet captures accepted drags and delivers moves/releases outside the viewport. Other inputs return false.

func (*OrbitControls) Rotate

func (o *OrbitControls) Rotate(camera *Camera, yaw, pitch float32) bool

Rotate changes yaw and pitch in radians while retaining target and distance. Pitch stops just short of the poles, preventing camera flips. Returns false for an invalid camera or non-finite deltas. Navigation assumes world Y is up.

type Renderer

type Renderer interface {
	Render(*Target, Request) (Stats, error)
}

Renderer allows alternative CPU/image-producing renderers without changing scene ownership or the viewport. Direct GPU texture sharing is not yet part of this interface and requires a future compositor integration.

type Request

type Request struct {
	Scene         *Scene
	Camera        Camera
	Width, Height int
}

Request describes one immutable frame. Scene and its slices must not change until Render returns. Width and Height are render pixels, not window DIPs.

type Scene

type Scene struct {
	Instances  []Instance
	Lights     []DirectionalLight
	Ambient    float32
	Background color.RGBA
}

Scene is a caller-owned snapshot. Do not mutate while rendering. The caller controls animation, simulation and scheduling; there is no background loop.

type Software

type Software struct{}

Software is a stateless, flat-shaded reference renderer. Different targets may be rendered concurrently. It uses no worker pool or global resources.

func (Software) Render

func (Software) Render(t *Target, r Request) (Stats, error)

Render validates before allocating and reuses buffers at a stable size. Meshes are shared, invisible instance bounds are rejected before transforming vertices, and depth is tested before writing a pixel.

type Stats

type Stats struct {
	Instances, CulledInstances, Triangles, RasterizedTriangles, ShadedPixels int
	BufferBytes                                                              int
}

Stats counts actual work; it does not measure GPU time or promise FPS.

type Target

type Target struct {
	Image *image.RGBA
	// contains filtered or unexported fields
}

Target holds reusable CPU buffers. Use one per viewport/rendering goroutine. Image is borrowed until the next Render; copy it to retain a frame.

func (*Target) BufferBytes

func (t *Target) BufferBytes() int

BufferBytes reports retained color, depth and transformed-vertex capacity, excluding immutable meshes, Go headers and the UI compositor's GPU texture.

func (*Target) Release

func (t *Target) Release()

Release drops CPU buffers; the UI compositor owns its uploaded texture.

type Vec3

type Vec3 struct{ X, Y, Z float32 }

Vec3 is a point or direction in a right-handed world; Y points up.

func (Vec3) Add

func (a Vec3) Add(b Vec3) Vec3

func (Vec3) Cross

func (a Vec3) Cross(b Vec3) Vec3

func (Vec3) Dot

func (a Vec3) Dot(b Vec3) float32

func (Vec3) Scale

func (a Vec3) Scale(s float32) Vec3

func (Vec3) Sub

func (a Vec3) Sub(b Vec3) Vec3

func (Vec3) Unit

func (a Vec3) Unit() Vec3

Unit returns zero for a zero-length vector.

type ViewOptions

type ViewOptions struct {
	Scene    *Scene
	Camera   Camera
	Revision uint64
	// Scale is render pixels per DIP (default 1, maximum 2). MaxDimension
	// caps either side (default 1024, maximum 2048), preserving aspect ratio.
	Scale        float32
	MaxDimension int
	// NewRenderer is called once per mounted view. nil uses Software.
	NewRenderer func() Renderer
	OnInput     func(ui.InputEvent) bool
	// Animate updates scene transforms before each visible frame. nil leaves
	// the viewport event-driven. Reduced-motion preferences suppress it.
	// It runs on the UI thread; use the supplied clock, not wall-clock timers.
	Animate func(time.Time)
	// OnFrame runs after a render attempt on the UI thread. It must not
	// reenter rendering. Errors are explicit; failed frames are not displayed.
	// After an error, change Revision or another frame input to retry.
	OnFrame func(Stats, error)
}

ViewOptions control rendering and integration with Forma or other native UI. Revision must change when Scene or mesh instance/material/light data changes. Camera and resolution changes are detected automatically. No timer is started. Use a stable UI Key when showing/reordering several viewports.

Jump to

Keyboard shortcuts

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