render

package
v1.5.4 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2026 License: 0BSD Imports: 8 Imported by: 0

Documentation

Overview

Package render provides optimized software asterization routines using edge function rasterization. Uses incremental updates to avoid recomputing barycentric coordinates per pixel.

Index

Constants

View Source
const (
	FrustumLeft = iota
	FrustumRight
	FrustumBottom
	FrustumTop
	FrustumNear
	FrustumFar
)

FrustumPlane indices for clarity.

Variables

This section is empty.

Functions

func RGB

func RGB(r, g, b uint8) color.RGBA

RGB creates a color from RGB values.

func RGBA

func RGBA(r, g, b, a uint8) color.RGBA

RGBA creates a color from RGBA values.

Types

type AABB

type AABB struct {
	Min math3d.Vec3
	Max math3d.Vec3
}

AABB represents an axis-aligned bounding box.

func NewAABB

func NewAABB(minV, maxV math3d.Vec3) AABB

NewAABB creates an AABB from min and max points.

func TransformAABB

func TransformAABB(box AABB, m math3d.Mat4) AABB

TransformAABB transforms an AABB by a matrix and returns the new bounds. This is a convenience function wrapping AABB.Transform.

func (AABB) Center

func (b AABB) Center() math3d.Vec3

Center returns the center of the AABB.

func (AABB) ContainsPoint

func (b AABB) ContainsPoint(p math3d.Vec3) bool

ContainsPoint returns true if the point is inside the AABB.

func (AABB) Extents

func (b AABB) Extents() math3d.Vec3

Extents is an alias for HalfSize.

func (AABB) HalfSize

func (b AABB) HalfSize() math3d.Vec3

HalfSize returns half the dimensions (extents from center).

func (AABB) Size

func (b AABB) Size() math3d.Vec3

Size returns the dimensions of the AABB.

func (AABB) Transform

func (b AABB) Transform(m math3d.Mat4) AABB

Transform returns an AABB that bounds the original AABB after transformation. This computes a new AABB that contains all 8 transformed corners.

type BoundedMeshRenderer

type BoundedMeshRenderer interface {
	MeshRenderer
	GetBounds() (minV, maxV math3d.Vec3)
}

BoundedMeshRenderer extends MeshRenderer with bounding box support for frustum culling.

type Camera

type Camera struct {
	// Position in world space
	Position math3d.Vec3
	// Orientation (Euler angles in radians)
	Pitch float64 // Rotation around X axis (look up/down)
	Yaw   float64 // Rotation around Y axis (look left/right)
	Roll  float64 // Rotation around Z axis (tilt)
	// Projection parameters
	FOV         float64 // Vertical field of view in radians
	AspectRatio float64 // Width / Height
	Near        float64 // Near clipping plane
	Far         float64 // Far clipping plane
	// contains filtered or unexported fields
}

Camera represents a 3D camera with position and orientation.

func NewCamera

func NewCamera() *Camera

NewCamera creates a new camera with default settings.

func (*Camera) Forward

func (c *Camera) Forward() math3d.Vec3

Forward returns the forward direction vector.

func (*Camera) GetFrustum

func (c *Camera) GetFrustum() Frustum

GetFrustum returns the current view frustum from the camera.

func (*Camera) LookAt

func (c *Camera) LookAt(target math3d.Vec3)

LookAt makes the camera look at a target point.

func (*Camera) MoveForward

func (c *Camera) MoveForward(distance float64)

MoveForward moves the camera forward (or backward if negative).

func (*Camera) MoveRight

func (c *Camera) MoveRight(distance float64)

MoveRight moves the camera right (or left if negative).

func (*Camera) MoveUp

func (c *Camera) MoveUp(distance float64)

MoveUp moves the camera up (or down if negative).

func (*Camera) ProjectionMatrix

func (c *Camera) ProjectionMatrix() math3d.Mat4

ProjectionMatrix returns the projection matrix.

func (*Camera) Right

func (c *Camera) Right() math3d.Vec3

Right returns the right direction vector.

func (*Camera) Rotate

func (c *Camera) Rotate(deltaPitch, deltaYaw, deltaRoll float64)

Rotate rotates the camera by the given angles (in radians).

func (*Camera) SetAspectRatio

func (c *Camera) SetAspectRatio(aspect float64)

SetAspectRatio sets the aspect ratio.

func (*Camera) SetClipPlanes

func (c *Camera) SetClipPlanes(near, far float64)

SetClipPlanes sets the near and far clipping planes.

func (*Camera) SetFOV

func (c *Camera) SetFOV(fov float64)

SetFOV sets the field of view (in radians).

func (*Camera) SetPosition

func (c *Camera) SetPosition(pos math3d.Vec3)

SetPosition sets the camera position.

func (*Camera) SetRotation

func (c *Camera) SetRotation(pitch, yaw, roll float64)

SetRotation sets the camera rotation (pitch, yaw, roll in radians).

func (*Camera) Up

func (c *Camera) Up() math3d.Vec3

Up returns the up direction vector.

func (*Camera) ViewMatrix

func (c *Camera) ViewMatrix() math3d.Mat4

ViewMatrix returns the view matrix.

func (*Camera) ViewProjectionMatrix

func (c *Camera) ViewProjectionMatrix() math3d.Mat4

ViewProjectionMatrix returns the combined view-projection matrix.

func (*Camera) WorldToScreen

func (c *Camera) WorldToScreen(worldPos math3d.Vec3, screenWidth, screenHeight int) (x, y, depth float64, visible bool)

WorldToScreen transforms a world point to screen coordinates. Returns (screenX, screenY, depth, visible).

type Color

type Color = color.RGBA

Color is an alias for color.RGBA for convenience.

func ModulateColor

func ModulateColor(a, b Color) Color

ModulateColor modulates one color by another (texture * vertex color).

func MultiplyColor

func MultiplyColor(c Color, intensity float64) Color

MultiplyColor multiplies a color by a scalar (for lighting).

type CullingStats

type CullingStats struct {
	MeshesTested int // Total meshes tested for culling
	MeshesCulled int // Meshes culled (not rendered)
	MeshesDrawn  int // Meshes that passed culling
}

CullingStats tracks frustum culling performance.

type FilterMode

type FilterMode int

FilterMode determines how texture sampling is performed.

const (
	FilterNearest  FilterMode = iota // Nearest-neighbor (pixelated)
	FilterBilinear                   // Bilinear interpolation (smooth)
)

type Framebuffer

type Framebuffer struct {
	Width  int          // Width in "pixels" (same as terminal columns)
	Height int          // Height in "pixels" (2x terminal rows due to half-blocks)
	Pixels []color.RGBA // Row-major pixel data
	BG     color.RGBA   // Background color for transparent pixels
}

Framebuffer is a 2D array of pixels that can be rendered to the terminal. We use double vertical resolution by using half-block characters (▀▄).

func NewFramebuffer

func NewFramebuffer(width, height int) *Framebuffer

NewFramebuffer creates a new framebuffer with the given dimensions. Height should be 2x the desired terminal rows for half-block rendering.

func (*Framebuffer) Clear

func (fb *Framebuffer) Clear()

Clear fills the framebuffer with a solid color.

func (*Framebuffer) DrawLine

func (fb *Framebuffer) DrawLine(x0, y0, x1, y1 int, c color.RGBA)

DrawLine draws a line from (x0, y0) to (x1, y1) using Bresenham's algorithm.

func (*Framebuffer) DrawRect

func (fb *Framebuffer) DrawRect(x, y, w, h int, c color.RGBA)

DrawRect draws a filled rectangle.

func (*Framebuffer) DrawRectOutline

func (fb *Framebuffer) DrawRectOutline(x, y, w, h int, c color.RGBA)

DrawRectOutline draws a rectangle outline.

func (*Framebuffer) GetPixel

func (fb *Framebuffer) GetPixel(x, y int) color.RGBA

GetPixel returns the color at (x, y). Returns transparent black if out of bounds.

func (*Framebuffer) Resize

func (fb *Framebuffer) Resize(width, height int)

Resize changes the size of the framebuffer, reallocating pixel data.

func (*Framebuffer) SavePNG

func (fb *Framebuffer) SavePNG(path string) error

SavePNG saves the framebuffer as a PNG file.

func (*Framebuffer) SetPixel

func (fb *Framebuffer) SetPixel(x, y int, c color.RGBA)

SetPixel sets a pixel at (x, y) to the given color. Bounds checking is performed.

func (*Framebuffer) ToImage

func (fb *Framebuffer) ToImage() *image.RGBA

ToImage converts the framebuffer to a standard Go image.RGBA.

type Frustum

type Frustum struct {
	Planes [6]Plane
}

Frustum represents the 6 planes of a view frustum. Planes are ordered: Left, Right, Bottom, Top, Near, Far. Each plane's normal points inward (toward the center of the frustum).

func ExtractFrustum

func ExtractFrustum(m math3d.Mat4) Frustum

ExtractFrustum is an alias for NewFrustumFromMatrix for API consistency.

func NewFrustumFromMatrix

func NewFrustumFromMatrix(m math3d.Mat4) Frustum

NewFrustumFromMatrix extracts frustum planes from a view-projection matrix. Uses the Gribb/Hartmann method for extracting planes from the combined matrix. The resulting planes have normals pointing inward.

func (Frustum) ContainsAABB

func (f Frustum) ContainsAABB(box AABB) bool

ContainsAABB tests if the AABB is completely inside the frustum. Returns true only if all 8 corners are inside all 6 planes.

func (Frustum) ContainsPoint

func (f Frustum) ContainsPoint(p math3d.Vec3) bool

ContainsPoint tests if a point is inside the frustum.

func (Frustum) IntersectAABB

func (f Frustum) IntersectAABB(box AABB) bool

IntersectAABB tests if the AABB intersects or is inside the frustum. Returns true if any part of the AABB is visible. Uses the "positive vertex" optimization for faster rejection.

func (Frustum) IntersectsFrustum

func (f Frustum) IntersectsFrustum(box AABB) bool

IntersectsFrustum is an alias for IntersectAABB for API consistency.

func (Frustum) IntersectsSphere

func (f Frustum) IntersectsSphere(center math3d.Vec3, radius float64) bool

IntersectsSphere tests if a sphere intersects the frustum. center is the sphere center, radius is the sphere radius.

type MeshRenderer

type MeshRenderer interface {
	VertexCount() int
	TriangleCount() int
	GetVertex(i int) (pos, normal math3d.Vec3, uv math3d.Vec2)
	GetFace(i int) [3]int
}

MeshRenderer is imported from models to avoid circular deps. This interface allows drawing meshes without importing the models package.

type Plane

type Plane struct {
	Normal math3d.Vec3
	D      float64
}

Plane represents a plane in 3D space using the equation: Ax + By + Cz + D = 0 where (A, B, C) is the normal and D is the distance from origin.

func (*Plane) DistanceToPoint

func (p *Plane) DistanceToPoint(point math3d.Vec3) float64

DistanceToPoint returns the signed distance from the plane to a point. Positive = in front (same side as normal), negative = behind.

func (*Plane) Normalize

func (p *Plane) Normalize()

Normalize normalizes the plane equation so the normal has unit length.

func (*Plane) SignedDistance

func (p *Plane) SignedDistance(point math3d.Vec3) float64

SignedDistance is an alias for DistanceToPoint.

type Rasterizer

type Rasterizer struct {
	CullingStats           CullingStats // Statistics for debugging/benchmarking
	DisableBackfaceCulling bool         // If true, render both sides of triangles
	// contains filtered or unexported fields
}

Rasterizer handles software triangle rasterization.

func NewRasterizer

func NewRasterizer(camera *Camera, fb *Framebuffer) *Rasterizer

NewRasterizer creates a new rasterizer.

func (*Rasterizer) ClearDepth

func (r *Rasterizer) ClearDepth()

ClearDepth clears the Z-buffer (call before each frame).

func (*Rasterizer) DrawCube

func (r *Rasterizer) DrawCube(center math3d.Vec3, size float64, color Color, lightDir math3d.Vec3)

DrawCube draws a solid cube with lighting.

func (*Rasterizer) DrawMesh

func (r *Rasterizer) DrawMesh(mesh MeshRenderer, transform math3d.Mat4, color Color, lightDir math3d.Vec3)

DrawMesh renders a mesh with the given transform and color. Automatically performs frustum culling if the mesh provides bounds.

func (*Rasterizer) DrawMeshCulled

func (r *Rasterizer) DrawMeshCulled(
	mesh MeshRenderer,
	transform math3d.Mat4,
	localBounds AABB,
	color Color,
	lightDir math3d.Vec3,
) bool

DrawMeshCulled renders a mesh with frustum culling. Returns true if the mesh was drawn, false if it was culled.

func (*Rasterizer) DrawMeshGouraud

func (r *Rasterizer) DrawMeshGouraud(mesh MeshRenderer, transform math3d.Mat4, color Color, lightDir math3d.Vec3)

DrawMeshGouraud renders a mesh with Gouraud shading (per-vertex lighting). This produces smoother shading than flat shading by interpolating lighting across triangles. Automatically performs frustum culling if the mesh provides bounds.

func (*Rasterizer) DrawMeshGouraudCulled

func (r *Rasterizer) DrawMeshGouraudCulled(
	mesh MeshRenderer,
	transform math3d.Mat4,
	localBounds AABB,
	color Color,
	lightDir math3d.Vec3,
) bool

DrawMeshGouraudCulled renders a mesh with Gouraud shading, with frustum culling. localBounds should be the mesh's local-space bounding box (e.g., mesh.BoundsMin/Max). Returns true if the mesh was drawn, false if it was culled.

func (*Rasterizer) DrawMeshGouraudOpt

func (r *Rasterizer) DrawMeshGouraudOpt(mesh MeshRenderer, transform math3d.Mat4, color Color, lightDir math3d.Vec3)

DrawMeshGouraudOpt renders a mesh with optimized Gouraud shading.

func (*Rasterizer) DrawMeshTextured

func (r *Rasterizer) DrawMeshTextured(mesh MeshRenderer, transform math3d.Mat4, tex *Texture, lightDir math3d.Vec3)

DrawMeshTextured renders a mesh with texture mapping. Automatically performs frustum culling if the mesh provides bounds.

func (*Rasterizer) DrawMeshTexturedCulled

func (r *Rasterizer) DrawMeshTexturedCulled(
	mesh MeshRenderer,
	transform math3d.Mat4,
	localBounds AABB,
	tex *Texture,
	lightDir math3d.Vec3,
) bool

DrawMeshTexturedCulled renders a textured mesh with frustum culling. Returns true if the mesh was drawn, false if it was culled.

func (*Rasterizer) DrawMeshTexturedGouraud

func (r *Rasterizer) DrawMeshTexturedGouraud(mesh MeshRenderer, transform math3d.Mat4, tex *Texture, lightDir math3d.Vec3)

DrawMeshTexturedGouraud renders a mesh with texture mapping and Gouraud shading. Combines perspective-correct texture mapping with smooth per-vertex lighting. Automatically performs frustum culling if the mesh provides bounds.

func (*Rasterizer) DrawMeshTexturedGouraudCulled

func (r *Rasterizer) DrawMeshTexturedGouraudCulled(
	mesh MeshRenderer,
	transform math3d.Mat4,
	localBounds AABB,
	tex *Texture,
	lightDir math3d.Vec3,
) bool

DrawMeshTexturedGouraudCulled renders a textured mesh with Gouraud shading, with frustum culling. localBounds should be the mesh's local-space bounding box (e.g., mesh.BoundsMin/Max). Returns true if the mesh was drawn, false if it was culled.

func (*Rasterizer) DrawMeshTexturedOpt

func (r *Rasterizer) DrawMeshTexturedOpt(mesh MeshRenderer, transform math3d.Mat4, tex *Texture, lightDir math3d.Vec3)

DrawMeshTexturedOpt renders a textured mesh with optimized rasterization.

func (*Rasterizer) DrawMeshWireframe

func (r *Rasterizer) DrawMeshWireframe(mesh MeshRenderer, transform math3d.Mat4, color Color)

DrawMeshWireframe renders a mesh as wireframe. Automatically performs frustum culling if the mesh provides bounds.

func (*Rasterizer) DrawQuad

func (r *Rasterizer) DrawQuad(v0, v1, v2, v3 math3d.Vec3, color Color)

DrawQuad draws a quad as two triangles.

func (*Rasterizer) DrawTexturedCube

func (r *Rasterizer) DrawTexturedCube(transform math3d.Mat4, size float64, tex *Texture, lightDir math3d.Vec3)

DrawTexturedCube draws a cube with texture mapping.

func (*Rasterizer) DrawTransformedCube

func (r *Rasterizer) DrawTransformedCube(transform math3d.Mat4, size float64, color Color, lightDir math3d.Vec3)

DrawTransformedCube draws a cube with a transformation matrix.

func (*Rasterizer) DrawTransformedCubeGouraud

func (r *Rasterizer) DrawTransformedCubeGouraud(transform math3d.Mat4, size float64, color Color, lightDir math3d.Vec3)

DrawTransformedCubeGouraud draws a cube with Gouraud shading (smooth corners). Uses per-vertex normals averaged at corners for smoother lighting transitions.

func (*Rasterizer) DrawTriangle

func (r *Rasterizer) DrawTriangle(tri Triangle)

DrawTriangle rasterizes a single triangle.

func (*Rasterizer) DrawTriangleFlat

func (r *Rasterizer) DrawTriangleFlat(v0, v1, v2 math3d.Vec3, color Color)

DrawTriangleFlat draws a triangle with flat shading (single color).

func (*Rasterizer) DrawTriangleGouraud

func (r *Rasterizer) DrawTriangleGouraud(tri Triangle, lightDir math3d.Vec3)

DrawTriangleGouraud rasterizes a triangle with Gouraud shading (per-vertex lighting). Lighting is calculated at each vertex and interpolated across the triangle.

func (*Rasterizer) DrawTriangleGouraudOpt

func (r *Rasterizer) DrawTriangleGouraudOpt(tri Triangle, lightDir math3d.Vec3)

DrawTriangleGouraudOpt is an optimized version using edge functions with incremental updates.

func (*Rasterizer) DrawTriangleLit

func (r *Rasterizer) DrawTriangleLit(v0, v1, v2 math3d.Vec3, baseColor Color, lightDir math3d.Vec3)

DrawTriangleLit draws a triangle with simple directional lighting.

func (*Rasterizer) DrawTriangleTextured

func (r *Rasterizer) DrawTriangleTextured(tri Triangle, tex *Texture, lightDir math3d.Vec3)

DrawTriangleTextured rasterizes a textured triangle with perspective-correct UV interpolation.

func (*Rasterizer) DrawTriangleTexturedGouraud

func (r *Rasterizer) DrawTriangleTexturedGouraud(tri Triangle, tex *Texture, lightDir math3d.Vec3)

DrawTriangleTexturedGouraud rasterizes a textured triangle with Gouraud shading. Per-vertex lighting is calculated and interpolated, then modulated with texture.

func (*Rasterizer) DrawTriangleTexturedOpt

func (r *Rasterizer) DrawTriangleTexturedOpt(tri Triangle, tex *Texture, lightDir math3d.Vec3)

DrawTriangleTexturedOpt is an optimized textured triangle rasterizer with Gouraud shading.

func (*Rasterizer) GetFrustum

func (r *Rasterizer) GetFrustum() Frustum

GetFrustum returns the current frustum (updating if needed).

func (*Rasterizer) Height

func (r *Rasterizer) Height() int

Height returns the framebuffer height.

func (*Rasterizer) InvalidateFrustum

func (r *Rasterizer) InvalidateFrustum()

InvalidateFrustum marks the frustum as needing recalculation. Call this when the camera moves or rotates.

func (*Rasterizer) IsVisible

func (r *Rasterizer) IsVisible(worldBounds AABB) bool

IsVisible tests if a world-space AABB is visible in the frustum.

func (*Rasterizer) IsVisibleTransformed

func (r *Rasterizer) IsVisibleTransformed(localBounds AABB, transform math3d.Mat4) bool

IsVisibleTransformed tests if a local-space AABB is visible after transformation.

func (*Rasterizer) ResetCullingStats

func (r *Rasterizer) ResetCullingStats()

ResetCullingStats resets the culling statistics (call once per frame).

func (*Rasterizer) Resize

func (r *Rasterizer) Resize()

Resize resizes the rasterizer's buffer to match the framebuffer.

func (*Rasterizer) UpdateFrustum

func (r *Rasterizer) UpdateFrustum()

UpdateFrustum recalculates the frustum planes from the camera.

func (*Rasterizer) Width

func (r *Rasterizer) Width() int

Width returns the framebuffer width.

type Texture

type Texture struct {
	Width      int
	Height     int
	Pixels     []Color    // Row-major pixel data
	WrapU      WrapMode   // Horizontal wrap mode
	WrapV      WrapMode   // Vertical wrap mode
	FilterMode FilterMode // Sampling filter mode
}

Texture holds a 2D image for texture mapping.

func LoadTexture

func LoadTexture(path string) (*Texture, error)

LoadTexture loads a texture from an image file.

func NewCheckerTexture

func NewCheckerTexture(width, height, checkSize int, c1, c2 Color) *Texture

NewCheckerTexture creates a procedural checkerboard texture.

func NewGradientTexture

func NewGradientTexture(width, height int, left, right Color) *Texture

NewGradientTexture creates a horizontal gradient texture.

func NewTexture

func NewTexture(width, height int) *Texture

NewTexture creates an empty texture with the given dimensions.

func TextureFromImage

func TextureFromImage(img image.Image) *Texture

TextureFromImage creates a texture from an image.Image.

func (*Texture) GetPixel

func (t *Texture) GetPixel(x, y int) Color

GetPixel returns the pixel at (x, y) with bounds checking.

func (*Texture) Sample

func (t *Texture) Sample(u, v float64) Color

Sample samples the texture at UV coordinates (0-1 range).

func (*Texture) SetPixel

func (t *Texture) SetPixel(x, y int, c Color)

SetPixel sets a pixel in the texture.

type Triangle

type Triangle struct {
	V [3]Vertex
}

Triangle represents a triangle to be rasterized.

type Vertex

type Vertex struct {
	Position math3d.Vec3 // World position
	Normal   math3d.Vec3 // Normal vector (for lighting)
	UV       math3d.Vec2 // Texture coordinates
	Color    Color       // Vertex color
}

Vertex represents a vertex with all attributes needed for rasterization.

type Wireframe

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

Wireframe renders 3D wireframe objects.

func NewWireframe

func NewWireframe(camera *Camera, fb *Framebuffer) *Wireframe

NewWireframe creates a new wireframe renderer.

func (*Wireframe) DrawAxes

func (w *Wireframe) DrawAxes(length float64)

DrawAxes draws the coordinate axes at the origin.

func (*Wireframe) DrawCube

func (w *Wireframe) DrawCube(center math3d.Vec3, size float64, color Color)

DrawCube draws a wireframe cube.

func (*Wireframe) DrawGrid

func (w *Wireframe) DrawGrid(size, step float64, color Color)

DrawGrid draws a grid on the XZ plane at y=0.

func (*Wireframe) DrawLine3D

func (w *Wireframe) DrawLine3D(p1, p2 math3d.Vec3, color Color)

DrawLine3D draws a line in 3D space.

func (*Wireframe) DrawPoint

func (w *Wireframe) DrawPoint(pos math3d.Vec3, size float64, color Color)

DrawPoint draws a point as a small cross.

func (*Wireframe) DrawTransformedCube

func (w *Wireframe) DrawTransformedCube(transform math3d.Mat4, size float64, color Color)

DrawTransformedCube draws a wireframe cube with a transformation matrix.

type WrapMode

type WrapMode int

WrapMode determines how texture coordinates outside [0,1] are handled.

const (
	WrapRepeat WrapMode = iota // Tile the texture
	WrapClamp                  // Clamp to edge
)

Jump to

Keyboard shortcuts

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