Documentation

Overview

Package mtl provides access to Apple's Metal API (https://developer.apple.com/documentation/metal).

Package mtl requires macOS version 10.13 or newer.

This package is in very early stages of development. The API will change when opportunities for improvement are discovered; it is not yet frozen. Less than 20% of the Metal API surface is implemented. Current functionality is sufficient to render very basic geometry.

Example (ListDevices)

Code:

package main

import (
	"encoding/json"
	"fmt"
	"github.com/hajimehoshi/ebiten/internal/graphicsdriver/metal/mtl"
	"log"
	"os"
)

func main() {
	device, err := mtl.CreateSystemDefaultDevice()
	if err != nil {
		log.Fatalln(err)
	}
	printJSON("preferred system default Metal device = ", device)

	fmt.Println("device supports the macOS GPU family 1, version 1 feature set:", device.SupportsFeatureSet(mtl.MacOSGPUFamily1V1))
	fmt.Println("device supports the macOS GPU family 1, version 2 feature set:", device.SupportsFeatureSet(mtl.MacOSGPUFamily1V2))
	fmt.Println("device supports the macOS read-write texture, tier 2 feature set:", device.SupportsFeatureSet(mtl.MacOSReadWriteTextureTier2))
	fmt.Println("device supports the macOS GPU family 1, version 3 feature set:", device.SupportsFeatureSet(mtl.MacOSGPUFamily1V3))
	fmt.Println("device supports the macOS GPU family 1, version 4 feature set:", device.SupportsFeatureSet(mtl.MacOSGPUFamily1V4))
	fmt.Println("device supports the macOS GPU family 2, version 1 feature set:", device.SupportsFeatureSet(mtl.MacOSGPUFamily2V1))

	// Sample output:
	// all Metal devices in the system = [
	// 	{
	// 		"Headless": false,
	// 		"LowPower": true,
	// 		"Removable": false,
	// 		"RegistryID": 4294968287,
	// 		"Name": "Intel Iris Pro Graphics"
	// 	},
	// 	{
	// 		"Headless": false,
	// 		"LowPower": false,
	// 		"Removable": false,
	// 		"RegistryID": 4294968322,
	// 		"Name": "AMD Radeon R9 M370X"
	// 	}
	// ]
	// preferred system default Metal device = {
	// 	"Headless": false,
	// 	"LowPower": false,
	// 	"Removable": false,
	// 	"RegistryID": 4294968322,
	// 	"Name": "AMD Radeon R9 M370X"
	// }
	// device supports the macOS GPU family 1, version 1 feature set: true
	// device supports the macOS GPU family 1, version 2 feature set: true
	// device supports the macOS read-write texture, tier 2 feature set: true
	// device supports the macOS GPU family 1, version 3 feature set: true
	// device supports the macOS GPU family 1, version 4 feature set: true
	// device supports the macOS GPU family 2, version 1 feature set: true
}

// printJSON prints label, then v as JSON encoded with indent to stdout. It panics on any error.
// It's meant to be used by examples to print the output.
func printJSON(label string, v interface{}) {
	fmt.Print(label)
	w := json.NewEncoder(os.Stdout)
	w.SetIndent("", "\t")
	err := w.Encode(v)
	if err != nil {
		panic(err)
	}
}
Example (RenderTriangle)

Code:

package main

import (
	"fmt"
	"github.com/hajimehoshi/ebiten/internal/graphicsdriver/metal/mtl"
	"golang.org/x/image/math/f32"
	"image"
	"image/color"
	"log"
	"unsafe"
)

func main() {
	device, err := mtl.CreateSystemDefaultDevice()
	if err != nil {
		log.Fatalln(err)
	}

	// Create a render pipeline state.
	const source = `#include <metal_stdlib>

using namespace metal;

struct Vertex {
	float4 position [[position]];
	float4 color;
};

vertex Vertex VertexShader(
	uint vertexID [[vertex_id]],
	device Vertex * vertices [[buffer(0)]]
) {
	return vertices[vertexID];
}

fragment float4 FragmentShader(Vertex in [[stage_in]]) {
	return in.color;
}
`
	lib, err := device.MakeLibrary(source, mtl.CompileOptions{})
	if err != nil {
		log.Fatalln(err)
	}
	vs, err := lib.MakeFunction("VertexShader")
	if err != nil {
		log.Fatalln(err)
	}
	fs, err := lib.MakeFunction("FragmentShader")
	if err != nil {
		log.Fatalln(err)
	}
	var rpld mtl.RenderPipelineDescriptor
	rpld.VertexFunction = vs
	rpld.FragmentFunction = fs
	rpld.ColorAttachments[0].PixelFormat = mtl.PixelFormatRGBA8UNorm
	rps, err := device.MakeRenderPipelineState(rpld)
	if err != nil {
		log.Fatalln(err)
	}

	// Create a vertex buffer.
	type Vertex struct {
		Position f32.Vec4
		Color    f32.Vec4
	}
	vertexData := [...]Vertex{
		{f32.Vec4{+0.00, +0.75, 0, 1}, f32.Vec4{1, 1, 1, 1}},
		{f32.Vec4{-0.75, -0.75, 0, 1}, f32.Vec4{1, 1, 1, 1}},
		{f32.Vec4{+0.75, -0.75, 0, 1}, f32.Vec4{0, 0, 0, 1}},
	}
	vertexBuffer := device.MakeBufferWithBytes(unsafe.Pointer(&vertexData[0]), unsafe.Sizeof(vertexData), mtl.ResourceStorageModeManaged)

	// Create an output texture to render into.
	td := mtl.TextureDescriptor{
		TextureType: mtl.TextureType2D,
		PixelFormat: mtl.PixelFormatRGBA8UNorm,
		Width:       80,
		Height:      20,
		StorageMode: mtl.StorageModeManaged,
	}
	texture := device.MakeTexture(td)

	cq := device.MakeCommandQueue()
	cb := cq.MakeCommandBuffer()

	// Encode all render commands.
	var rpd mtl.RenderPassDescriptor
	rpd.ColorAttachments[0].LoadAction = mtl.LoadActionClear
	rpd.ColorAttachments[0].StoreAction = mtl.StoreActionStore
	rpd.ColorAttachments[0].ClearColor = mtl.ClearColor{Red: 0, Green: 0, Blue: 0, Alpha: 1}
	rpd.ColorAttachments[0].Texture = texture
	rce := cb.MakeRenderCommandEncoder(rpd)
	rce.SetRenderPipelineState(rps)
	rce.SetVertexBuffer(vertexBuffer, 0, 0)
	rce.DrawPrimitives(mtl.PrimitiveTypeTriangle, 0, 3)
	rce.EndEncoding()

	// Encode all blit commands.
	bce := cb.MakeBlitCommandEncoder()
	bce.Synchronize(texture)
	bce.EndEncoding()

	cb.Commit()
	cb.WaitUntilCompleted()

	// Read pixels from output texture into an image.
	img := image.NewNRGBA(image.Rect(0, 0, texture.Width(), texture.Height()))
	bytesPerRow := 4 * texture.Width()
	region := mtl.RegionMake2D(0, 0, texture.Width(), texture.Height())
	texture.GetBytes(&img.Pix[0], uintptr(bytesPerRow), region, 0)

	// Output image to stdout as grayscale ASCII art.
	levels := []struct {
		MinY  uint8
		Shade string
	}{{220, " "}, {170, "░"}, {85, "▒"}, {35, "▓"}, {0, "█"}}
	for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
		for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
			c := color.GrayModel.Convert(img.At(x, y)).(color.Gray)
			for _, l := range levels {
				if c.Y >= l.MinY {
					fmt.Print(l.Shade)
					break
				}
			}
		}
		fmt.Println()
	}

}
████████████████████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████████████████████
██████████████████████████████████████    ██████████████████████████████████████
████████████████████████████████████        ████████████████████████████████████
██████████████████████████████████        ░░░░██████████████████████████████████
████████████████████████████████        ░░░░░░░░████████████████████████████████
██████████████████████████████        ░░░░░░░░░░░░██████████████████████████████
████████████████████████████        ░░░░░░░░░░░░▒▒▒▒████████████████████████████
██████████████████████████        ░░░░░░░░░░░░▒▒▒▒▒▒▒▒██████████████████████████
████████████████████████        ░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒████████████████████████
██████████████████████        ░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██████████████████████
████████████████████        ░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████████████████████
██████████████████        ░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓██████████████████
████████████████        ░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓████████████████
██████████████        ░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓██████████████
████████████        ░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓████████████████
████████████████████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████████████████████
████████████████████████████████████████████████████████████████████████████████

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BlendFactor

type BlendFactor uint8
const (
	BlendFactorZero                     BlendFactor = 0
	BlendFactorOne                      BlendFactor = 1
	BlendFactorSourceColor              BlendFactor = 2
	BlendFactorOneMinusSourceColor      BlendFactor = 3
	BlendFactorSourceAlpha              BlendFactor = 4
	BlendFactorOneMinusSourceAlpha      BlendFactor = 5
	BlendFactorDestinationColor         BlendFactor = 6
	BlendFactorOneMinusDestinationColor BlendFactor = 7
	BlendFactorDestinationAlpha         BlendFactor = 8
	BlendFactorOneMinusDestinationAlpha BlendFactor = 9
	BlendFactorSourceAlphaSaturated     BlendFactor = 10
	BlendFactorBlendColor               BlendFactor = 11
	BlendFactorOneMinusBlendColor       BlendFactor = 12
	BlendFactorBlendAlpha               BlendFactor = 13
	BlendFactorOneMinusBlendAlpha       BlendFactor = 14
	BlendFactorSource1Color             BlendFactor = 15
	BlendFactorOneMinusSource1Color     BlendFactor = 16
	BlendFactorSource1Alpha             BlendFactor = 17
	BlendFactorOneMinusSource1Alpha     BlendFactor = 18
)

type BlitCommandEncoder

type BlitCommandEncoder struct {
	CommandEncoder
}

BlitCommandEncoder is an encoder that specifies resource copy and resource synchronization commands.

Reference: https://developer.apple.com/documentation/metal/mtlblitcommandencoder.

func (BlitCommandEncoder) CopyFromTexture

func (bce BlitCommandEncoder) CopyFromTexture(sourceTexture Texture, sourceSlice int, sourceLevel int, sourceOrigin Origin, sourceSize Size, destinationTexture Texture, destinationSlice int, destinationLevel int, destinationOrigin Origin)

func (BlitCommandEncoder) Synchronize

func (bce BlitCommandEncoder) Synchronize(resource Resource)

Synchronize flushes any copy of the specified resource from its corresponding Device caches and, if needed, invalidates any CPU caches.

Reference: https://developer.apple.com/documentation/metal/mtlblitcommandencoder/1400775-synchronize.

func (BlitCommandEncoder) SynchronizeTexture

func (bce BlitCommandEncoder) SynchronizeTexture(texture Texture, slice int, level int)

type Buffer

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

Buffer is a memory allocation for storing unformatted data that is accessible to the GPU.

Reference: https://developer.apple.com/documentation/metal/mtlbuffer.

func (Buffer) CopyToContents

func (b Buffer) CopyToContents(data unsafe.Pointer, lengthInBytes uintptr)

func (Buffer) Native

func (b Buffer) Native() unsafe.Pointer

func (Buffer) Release

func (b Buffer) Release()

func (Buffer) Retain

func (b Buffer) Retain()

type CPUCacheMode

type CPUCacheMode uint8

CPUCacheMode is the CPU cache mode that defines the CPU mapping of a resource.

Reference: https://developer.apple.com/documentation/metal/mtlcpucachemode.

const (
	// CPUCacheModeDefaultCache is the default CPU cache mode for the resource.
	// Guarantees that read and write operations are executed in the expected order.
	CPUCacheModeDefaultCache CPUCacheMode = 0

	// CPUCacheModeWriteCombined is a write-combined CPU cache mode for the resource.
	// Optimized for resources that the CPU will write into, but never read.
	CPUCacheModeWriteCombined CPUCacheMode = 1
)

type ClearColor

type ClearColor struct {
	Red, Green, Blue, Alpha float64
}

ClearColor is an RGBA value used for a color pixel.

Reference: https://developer.apple.com/documentation/metal/mtlclearcolor.

type CommandBuffer

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

CommandBuffer is a container that stores encoded commands that are committed to and executed by the GPU.

Reference: https://developer.apple.com/documentation/metal/mtlcommandbuffer.

func (CommandBuffer) Commit

func (cb CommandBuffer) Commit()

Commit commits this command buffer for execution as soon as possible.

Reference: https://developer.apple.com/documentation/metal/mtlcommandbuffer/1443003-commit.

func (CommandBuffer) MakeBlitCommandEncoder

func (cb CommandBuffer) MakeBlitCommandEncoder() BlitCommandEncoder

MakeBlitCommandEncoder creates an encoder object that can encode memory operation (blit) commands into this command buffer.

Reference: https://developer.apple.com/documentation/metal/mtlcommandbuffer/1443001-makeblitcommandencoder.

func (CommandBuffer) MakeRenderCommandEncoder

func (cb CommandBuffer) MakeRenderCommandEncoder(rpd RenderPassDescriptor) RenderCommandEncoder

MakeRenderCommandEncoder creates an encoder object that can encode graphics rendering commands into this command buffer.

Reference: https://developer.apple.com/documentation/metal/mtlcommandbuffer/1442999-makerendercommandencoder.

func (CommandBuffer) PresentDrawable

func (cb CommandBuffer) PresentDrawable(d Drawable)

PresentDrawable registers a drawable presentation to occur as soon as possible.

Reference: https://developer.apple.com/documentation/metal/mtlcommandbuffer/1443029-presentdrawable.

func (CommandBuffer) WaitUntilCompleted

func (cb CommandBuffer) WaitUntilCompleted()

WaitUntilCompleted waits for the execution of this command buffer to complete.

Reference: https://developer.apple.com/documentation/metal/mtlcommandbuffer/1443039-waituntilcompleted.

type CommandEncoder

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

CommandEncoder is an encoder that writes sequential GPU commands into a command buffer.

Reference: https://developer.apple.com/documentation/metal/mtlcommandencoder.

func (CommandEncoder) EndEncoding

func (ce CommandEncoder) EndEncoding()

EndEncoding declares that all command generation from this encoder is completed.

Reference: https://developer.apple.com/documentation/metal/mtlcommandencoder/1458038-endencoding.

type CommandQueue

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

CommandQueue is a queue that organizes the order in which command buffers are executed by the GPU.

Reference: https://developer.apple.com/documentation/metal/mtlcommandqueue.

func (CommandQueue) MakeCommandBuffer

func (cq CommandQueue) MakeCommandBuffer() CommandBuffer

MakeCommandBuffer creates a command buffer.

Reference: https://developer.apple.com/documentation/metal/mtlcommandqueue/1508686-makecommandbuffer.

func (CommandQueue) Release

func (c CommandQueue) Release()

type CompileOptions

type CompileOptions struct {
}

CompileOptions specifies optional compilation settings for the graphics or compute functions within a library.

Reference: https://developer.apple.com/documentation/metal/mtlcompileoptions.

type Device

type Device struct {

	// Headless indicates whether a device is configured as headless.
	Headless bool

	// LowPower indicates whether a device is low-power.
	LowPower bool

	// Name is the name of the device.
	Name string
	// contains filtered or unexported fields
}

Device is abstract representation of the GPU that serves as the primary interface for a Metal app.

Reference: https://developer.apple.com/documentation/metal/mtldevice.

func CreateSystemDefaultDevice

func CreateSystemDefaultDevice() (Device, error)

CreateSystemDefaultDevice returns the preferred system default Metal device.

Reference: https://developer.apple.com/documentation/metal/1433401-mtlcreatesystemdefaultdevice.

func (Device) Device

func (d Device) Device() unsafe.Pointer

Device returns the underlying id<MTLDevice> pointer.

func (Device) MakeBufferWithBytes

func (d Device) MakeBufferWithBytes(bytes unsafe.Pointer, length uintptr, opt ResourceOptions) Buffer

MakeBufferWithBytes allocates a new buffer of a given length and initializes its contents by copying existing data into it.

Reference: https://developer.apple.com/documentation/metal/mtldevice/1433429-makebuffer.

func (Device) MakeBufferWithLength

func (d Device) MakeBufferWithLength(length uintptr, opt ResourceOptions) Buffer

MakeBufferWithLength allocates a new zero-filled buffer of a given length.

Reference: https://developer.apple.com/documentation/metal/mtldevice/1433375-newbufferwithlength

func (Device) MakeCommandQueue

func (d Device) MakeCommandQueue() CommandQueue

MakeCommandQueue creates a serial command submission queue.

Reference: https://developer.apple.com/documentation/metal/mtldevice/1433388-makecommandqueue.

func (Device) MakeLibrary

func (d Device) MakeLibrary(source string, opt CompileOptions) (Library, error)

MakeLibrary creates a new library that contains the functions stored in the specified source string.

Reference: https://developer.apple.com/documentation/metal/mtldevice/1433431-makelibrary.

func (Device) MakeRenderPipelineState

func (d Device) MakeRenderPipelineState(rpd RenderPipelineDescriptor) (RenderPipelineState, error)

MakeRenderPipelineState creates a render pipeline state object.

Reference: https://developer.apple.com/documentation/metal/mtldevice/1433369-makerenderpipelinestate.

func (Device) MakeTexture

func (d Device) MakeTexture(td TextureDescriptor) Texture

MakeTexture creates a texture object with privately owned storage that contains texture state.

Reference: https://developer.apple.com/documentation/metal/mtldevice/1433425-maketexture.

func (Device) SupportsFeatureSet

func (d Device) SupportsFeatureSet(fs FeatureSet) bool

SupportsFeatureSet reports whether device d supports feature set fs.

Reference: https://developer.apple.com/documentation/metal/mtldevice/1433418-supportsfeatureset.

type Drawable

type Drawable interface {
	// Drawable returns the underlying id<MTLDrawable> pointer.
	Drawable() unsafe.Pointer
}

Drawable is a displayable resource that can be rendered or written to.

Reference: https://developer.apple.com/documentation/metal/mtldrawable.

type FeatureSet

type FeatureSet uint16

FeatureSet defines a specific platform, hardware, and software configuration.

Reference: https://developer.apple.com/documentation/metal/mtlfeatureset.

const (
	MacOSGPUFamily1V1          FeatureSet = 10000 // The GPU family 1, version 1 feature set for macOS.
	MacOSGPUFamily1V2          FeatureSet = 10001 // The GPU family 1, version 2 feature set for macOS.
	MacOSReadWriteTextureTier2 FeatureSet = 10002 // The read-write texture, tier 2 feature set for macOS.
	MacOSGPUFamily1V3          FeatureSet = 10003 // The GPU family 1, version 3 feature set for macOS.
	MacOSGPUFamily1V4          FeatureSet = 10004 // The GPU family 1, version 4 feature set for macOS.
	MacOSGPUFamily2V1          FeatureSet = 10005 // The GPU family 2, version 1 feature set for macOS.
)

The device feature sets that define specific platform, hardware, and software configurations.

const (
	FeatureSet_iOS_GPUFamily1_v1           FeatureSet = 0
	FeatureSet_iOS_GPUFamily1_v2           FeatureSet = 2
	FeatureSet_iOS_GPUFamily1_v3           FeatureSet = 5
	FeatureSet_iOS_GPUFamily1_v4           FeatureSet = 8
	FeatureSet_iOS_GPUFamily1_v5           FeatureSet = 12
	FeatureSet_iOS_GPUFamily2_v1           FeatureSet = 1
	FeatureSet_iOS_GPUFamily2_v2           FeatureSet = 3
	FeatureSet_iOS_GPUFamily2_v3           FeatureSet = 6
	FeatureSet_iOS_GPUFamily2_v4           FeatureSet = 9
	FeatureSet_iOS_GPUFamily2_v5           FeatureSet = 13
	FeatureSet_iOS_GPUFamily3_v1           FeatureSet = 4
	FeatureSet_iOS_GPUFamily3_v2           FeatureSet = 7
	FeatureSet_iOS_GPUFamily3_v3           FeatureSet = 10
	FeatureSet_iOS_GPUFamily3_v4           FeatureSet = 14
	FeatureSet_iOS_GPUFamily4_v1           FeatureSet = 11
	FeatureSet_iOS_GPUFamily4_v2           FeatureSet = 15
	FeatureSet_iOS_GPUFamily5_v1           FeatureSet = 16
	FeatureSet_tvOS_GPUFamily1_v1          FeatureSet = 30000
	FeatureSet_tvOS_GPUFamily1_v2          FeatureSet = 30001
	FeatureSet_tvOS_GPUFamily1_v3          FeatureSet = 30002
	FeatureSet_tvOS_GPUFamily1_v4          FeatureSet = 30004
	FeatureSet_tvOS_GPUFamily2_v1          FeatureSet = 30003
	FeatureSet_tvOS_GPUFamily2_v2          FeatureSet = 30005
	FeatureSet_macOS_GPUFamily1_v1         FeatureSet = 10000
	FeatureSet_macOS_GPUFamily1_v2         FeatureSet = 10001
	FeatureSet_macOS_GPUFamily1_v3         FeatureSet = 10003
	FeatureSet_macOS_GPUFamily1_v4         FeatureSet = 10004
	FeatureSet_macOS_GPUFamily2_v1         FeatureSet = 10005
	FeatureSet_macOS_ReadWriteTextureTier2 FeatureSet = 10002
)

type Function

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

Function represents a programmable graphics or compute function executed by the GPU.

Reference: https://developer.apple.com/documentation/metal/mtlfunction.

func (Function) Release

func (f Function) Release()

type IndexType

type IndexType uint8

IndexType is the index type for an index buffer that references vertices of geometric primitives.

Reference: https://developer.apple.com/documentation/metal/mtlstoragemode

const (
	// IndexTypeUInt16 is a 16-bit unsigned integer used as a primitive index.
	IndexTypeUInt16 IndexType = 0

	// IndexTypeUInt32 is a 32-bit unsigned integer used as a primitive index.
	IndexTypeUInt32 IndexType = 1
)

type Library

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

Library is a collection of compiled graphics or compute functions.

Reference: https://developer.apple.com/documentation/metal/mtllibrary.

func (Library) MakeFunction

func (l Library) MakeFunction(name string) (Function, error)

MakeFunction returns a pre-compiled, non-specialized function.

Reference: https://developer.apple.com/documentation/metal/mtllibrary/1515524-makefunction.

type LoadAction

type LoadAction uint8

LoadAction defines actions performed at the start of a rendering pass for a render command encoder.

Reference: https://developer.apple.com/documentation/metal/mtlloadaction.

const (
	LoadActionDontCare LoadAction = 0
	LoadActionLoad     LoadAction = 1
	LoadActionClear    LoadAction = 2
)

Actions performed at the start of a rendering pass for a render command encoder.

type Origin

type Origin struct{ X, Y, Z int }

Origin represents the location of a pixel in an image or texture relative to the upper-left corner, whose coordinates are (0, 0).

Reference: https://developer.apple.com/documentation/metal/mtlorigin.

type PixelFormat

type PixelFormat uint16

PixelFormat defines data formats that describe the organization and characteristics of individual pixels in a texture.

Reference: https://developer.apple.com/documentation/metal/mtlpixelformat.

const (
	PixelFormatRGBA8UNorm     PixelFormat = 70 // Ordinary format with four 8-bit normalized unsigned integer components in RGBA order.
	PixelFormatRGBA8UNormSRGB PixelFormat = 71 // Ordinary format with four 8-bit normalized unsigned integer components in RGBA order with conversion between sRGB and linear space.
	PixelFormatBGRA8UNorm     PixelFormat = 80 // Ordinary format with four 8-bit normalized unsigned integer components in BGRA order.
	PixelFormatBGRA8UNormSRGB PixelFormat = 81 // Ordinary format with four 8-bit normalized unsigned integer components in BGRA order with conversion between sRGB and linear space.
)

The data formats that describe the organization and characteristics of individual pixels in a texture.

type PrimitiveType

type PrimitiveType uint8

PrimitiveType defines geometric primitive types for drawing commands.

Reference: https://developer.apple.com/documentation/metal/mtlprimitivetype.

const (
	PrimitiveTypePoint         PrimitiveType = 0
	PrimitiveTypeLine          PrimitiveType = 1
	PrimitiveTypeLineStrip     PrimitiveType = 2
	PrimitiveTypeTriangle      PrimitiveType = 3
	PrimitiveTypeTriangleStrip PrimitiveType = 4
)

Geometric primitive types for drawing commands.

type Region

type Region struct {
	Origin Origin // The location of the upper-left corner of the block.
	Size   Size   // The size of the block.
}

Region is a rectangular block of pixels in an image or texture, defined by its upper-left corner and its size.

Reference: https://developer.apple.com/documentation/metal/mtlregion.

func RegionMake2D

func RegionMake2D(x, y, width, height int) Region

RegionMake2D returns a 2D, rectangular region for image or texture data.

Reference: https://developer.apple.com/documentation/metal/1515675-mtlregionmake2d.

type RenderCommandEncoder

type RenderCommandEncoder struct {
	CommandEncoder
}

RenderCommandEncoder is an encoder that specifies graphics-rendering commands and executes graphics functions.

Reference: https://developer.apple.com/documentation/metal/mtlrendercommandencoder.

func (RenderCommandEncoder) DrawIndexedPrimitives

func (rce RenderCommandEncoder) DrawIndexedPrimitives(typ PrimitiveType, indexCount int, indexType IndexType, indexBuffer Buffer, indexBufferOffset int)

DrawIndexedPrimitives encodes a command to render one instance of primitives using an index list specified in a buffer.

Reference: https://developer.apple.com/documentation/metal/mtlrendercommandencoder/1515542-drawindexedprimitives

func (RenderCommandEncoder) DrawPrimitives

func (rce RenderCommandEncoder) DrawPrimitives(typ PrimitiveType, vertexStart, vertexCount int)

DrawPrimitives renders one instance of primitives using vertex data in contiguous array elements.

Reference: https://developer.apple.com/documentation/metal/mtlrendercommandencoder/1516326-drawprimitives.

func (RenderCommandEncoder) Release

func (rce RenderCommandEncoder) Release()

func (RenderCommandEncoder) SetBlendColor

func (rce RenderCommandEncoder) SetBlendColor(red, green, blue, alpha float32)

func (RenderCommandEncoder) SetFragmentBytes

func (rce RenderCommandEncoder) SetFragmentBytes(bytes unsafe.Pointer, length uintptr, index int)

func (RenderCommandEncoder) SetFragmentTexture

func (rce RenderCommandEncoder) SetFragmentTexture(texture Texture, index int)

SetFragmentTexture sets a texture for the fragment function at an index in the texture argument table.

Reference: https://developer.apple.com/documentation/metal/mtlrendercommandencoder/1515390-setfragmenttexture

func (RenderCommandEncoder) SetRenderPipelineState

func (rce RenderCommandEncoder) SetRenderPipelineState(rps RenderPipelineState)

SetRenderPipelineState sets the current render pipeline state object.

Reference: https://developer.apple.com/documentation/metal/mtlrendercommandencoder/1515811-setrenderpipelinestate.

func (RenderCommandEncoder) SetVertexBuffer

func (rce RenderCommandEncoder) SetVertexBuffer(buf Buffer, offset, index int)

SetVertexBuffer sets a buffer for the vertex shader function at an index in the buffer argument table with an offset that specifies the start of the data.

Reference: https://developer.apple.com/documentation/metal/mtlrendercommandencoder/1515829-setvertexbuffer.

func (RenderCommandEncoder) SetVertexBytes

func (rce RenderCommandEncoder) SetVertexBytes(bytes unsafe.Pointer, length uintptr, index int)

SetVertexBytes sets a block of data for the vertex function.

Reference: https://developer.apple.com/documentation/metal/mtlrendercommandencoder/1515846-setvertexbytes.

func (RenderCommandEncoder) SetViewport

func (rce RenderCommandEncoder) SetViewport(viewport Viewport)

type RenderPassAttachmentDescriptor

type RenderPassAttachmentDescriptor struct {
	LoadAction  LoadAction
	StoreAction StoreAction
	Texture     Texture
}

RenderPassAttachmentDescriptor describes a render target that serves as the output destination for pixels generated by a render pass.

Reference: https://developer.apple.com/documentation/metal/mtlrenderpassattachmentdescriptor.

type RenderPassColorAttachmentDescriptor

type RenderPassColorAttachmentDescriptor struct {
	RenderPassAttachmentDescriptor
	ClearColor ClearColor
}

RenderPassColorAttachmentDescriptor describes a color render target that serves as the output destination for color pixels generated by a render pass.

Reference: https://developer.apple.com/documentation/metal/mtlrenderpasscolorattachmentdescriptor.

type RenderPassDescriptor

type RenderPassDescriptor struct {
	// ColorAttachments is array of state information for attachments that store color data.
	ColorAttachments [1]RenderPassColorAttachmentDescriptor
}

RenderPassDescriptor describes a group of render targets that serve as the output destination for pixels generated by a render pass.

Reference: https://developer.apple.com/documentation/metal/mtlrenderpassdescriptor.

type RenderPipelineColorAttachmentDescriptor

type RenderPipelineColorAttachmentDescriptor struct {
	// PixelFormat is the pixel format of the color attachment's texture.
	PixelFormat PixelFormat

	BlendingEnabled bool

	DestinationAlphaBlendFactor BlendFactor
	DestinationRGBBlendFactor   BlendFactor
	SourceAlphaBlendFactor      BlendFactor
	SourceRGBBlendFactor        BlendFactor
}

RenderPipelineColorAttachmentDescriptor describes a color render target that specifies the color configuration and color operations associated with a render pipeline.

Reference: https://developer.apple.com/documentation/metal/mtlrenderpipelinecolorattachmentdescriptor.

type RenderPipelineDescriptor

type RenderPipelineDescriptor struct {
	// VertexFunction is a programmable function that processes individual vertices in a rendering pass.
	VertexFunction Function

	// FragmentFunction is a programmable function that processes individual fragments in a rendering pass.
	FragmentFunction Function

	// ColorAttachments is an array of attachments that store color data.
	ColorAttachments [1]RenderPipelineColorAttachmentDescriptor
}

RenderPipelineDescriptor configures new RenderPipelineState objects.

Reference: https://developer.apple.com/documentation/metal/mtlrenderpipelinedescriptor.

type RenderPipelineState

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

RenderPipelineState contains the graphics functions and configuration state used in a render pass.

Reference: https://developer.apple.com/documentation/metal/mtlrenderpipelinestate.

func (RenderPipelineState) Release

func (r RenderPipelineState) Release()

type Resource

type Resource interface {
	// contains filtered or unexported methods
}

Resource represents a memory allocation for storing specialized data that is accessible to the GPU.

Reference: https://developer.apple.com/documentation/metal/mtlresource.

type ResourceOptions

type ResourceOptions uint16

ResourceOptions defines optional arguments used to create and influence behavior of buffer and texture objects.

Reference: https://developer.apple.com/documentation/metal/mtlresourceoptions.

const (
	// ResourceCPUCacheModeDefaultCache is the default CPU cache mode for the resource.
	// Guarantees that read and write operations are executed in the expected order.
	ResourceCPUCacheModeDefaultCache ResourceOptions = ResourceOptions(CPUCacheModeDefaultCache) << resourceCPUCacheModeShift

	// ResourceCPUCacheModeWriteCombined is a write-combined CPU cache mode for the resource.
	// Optimized for resources that the CPU will write into, but never read.
	ResourceCPUCacheModeWriteCombined ResourceOptions = ResourceOptions(CPUCacheModeWriteCombined) << resourceCPUCacheModeShift

	// ResourceStorageModeShared indicates that the resource is stored in system memory
	// accessible to both the CPU and the GPU.
	ResourceStorageModeShared ResourceOptions = ResourceOptions(StorageModeShared) << resourceStorageModeShift

	// ResourceStorageModeManaged indicates that the resource exists as a synchronized
	// memory pair with one copy stored in system memory accessible to the CPU
	// and another copy stored in video memory accessible to the GPU.
	ResourceStorageModeManaged ResourceOptions = ResourceOptions(StorageModeManaged) << resourceStorageModeShift

	// ResourceStorageModePrivate indicates that the resource is stored in memory
	// only accessible to the GPU. In iOS and tvOS, the resource is stored
	// in system memory. In macOS, the resource is stored in video memory.
	ResourceStorageModePrivate ResourceOptions = ResourceOptions(StorageModePrivate) << resourceStorageModeShift

	// ResourceStorageModeMemoryless indicates that the resource is stored in on-tile memory,
	// without CPU or GPU memory backing. The contents of the on-tile memory are undefined
	// and do not persist; the only way to populate the resource is to render into it.
	// Memoryless resources are limited to temporary render targets (i.e., Textures configured
	// with a TextureDescriptor and used with a RenderPassAttachmentDescriptor).
	ResourceStorageModeMemoryless ResourceOptions = ResourceOptions(StorageModeMemoryless) << resourceStorageModeShift

	// ResourceHazardTrackingModeUntracked indicates that the command encoder dependencies
	// for this resource are tracked manually with Fence objects. This value is always set
	// for resources sub-allocated from a Heap object and may optionally be specified for
	// non-heap resources.
	ResourceHazardTrackingModeUntracked ResourceOptions = 1 << resourceHazardTrackingModeShift
)

type Size

type Size struct{ Width, Height, Depth int }

Size represents the set of dimensions that declare the size of an object, such as an image, texture, threadgroup, or grid.

Reference: https://developer.apple.com/documentation/metal/mtlsize.

type StorageMode

type StorageMode uint8

StorageMode defines defines the memory location and access permissions of a resource.

Reference: https://developer.apple.com/documentation/metal/mtlstoragemode.

const (
	// StorageModeShared indicates that the resource is stored in system memory
	// accessible to both the CPU and the GPU.
	StorageModeShared StorageMode = 0

	// StorageModeManaged indicates that the resource exists as a synchronized
	// memory pair with one copy stored in system memory accessible to the CPU
	// and another copy stored in video memory accessible to the GPU.
	StorageModeManaged StorageMode = 1

	// StorageModePrivate indicates that the resource is stored in memory
	// only accessible to the GPU. In iOS and tvOS, the resource is stored in
	// system memory. In macOS, the resource is stored in video memory.
	StorageModePrivate StorageMode = 2

	// StorageModeMemoryless indicates that the resource is stored in on-tile memory,
	// without CPU or GPU memory backing. The contents of the on-tile memory are undefined
	// and do not persist; the only way to populate the resource is to render into it.
	// Memoryless resources are limited to temporary render targets (i.e., Textures configured
	// with a TextureDescriptor and used with a RenderPassAttachmentDescriptor).
	StorageModeMemoryless StorageMode = 3
)

type StoreAction

type StoreAction uint8

StoreAction defines actions performed at the end of a rendering pass for a render command encoder.

Reference: https://developer.apple.com/documentation/metal/mtlstoreaction.

const (
	StoreActionDontCare                   StoreAction = 0
	StoreActionStore                      StoreAction = 1
	StoreActionMultisampleResolve         StoreAction = 2
	StoreActionStoreAndMultisampleResolve StoreAction = 3
	StoreActionUnknown                    StoreAction = 4
	StoreActionCustomSampleDepthStore     StoreAction = 5
)

Actions performed at the end of a rendering pass for a render command encoder.

type Texture

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

Texture is a memory allocation for storing formatted image data that is accessible to the GPU.

Reference: https://developer.apple.com/documentation/metal/mtltexture.

func NewTexture

func NewTexture(texture unsafe.Pointer) Texture

NewTexture returns a Texture that wraps an existing id<MTLTexture> pointer.

func (Texture) GetBytes

func (t Texture) GetBytes(pixelBytes *byte, bytesPerRow uintptr, region Region, level int)

GetBytes copies a block of pixels from the storage allocation of texture slice zero into system memory at a specified address.

Reference: https://developer.apple.com/documentation/metal/mtltexture/1515751-getbytes.

func (Texture) Height

func (t Texture) Height() int

Height is the height of the texture image for the base level mipmap, in pixels.

Reference: https://developer.apple.com/documentation/metal/mtltexture/1515938-height

func (Texture) Release

func (t Texture) Release()

func (Texture) ReplaceRegion

func (t Texture) ReplaceRegion(region Region, level int, pixelBytes unsafe.Pointer, bytesPerRow int)

ReplaceRegion copies a block of pixels from the caller's pointer into the storage allocation for slice 0 of a texture.

Reference: https://developer.apple.com/documentation/metal/mtltexture/1515464-replaceregion

func (Texture) Width

func (t Texture) Width() int

Width is the width of the texture image for the base level mipmap, in pixels.

Reference: https://developer.apple.com/documentation/metal/mtltexture/1515339-width

type TextureDescriptor

type TextureDescriptor struct {
	TextureType TextureType
	PixelFormat PixelFormat
	Width       int
	Height      int
	StorageMode StorageMode
	Usage       TextureUsage
}

TextureDescriptor configures new Texture objects.

Reference: https://developer.apple.com/documentation/metal/mtltexturedescriptor.

type TextureType

type TextureType uint16

TextureType defines The dimension of each image, including whether multiple images are arranged into an array or a cube.

Reference: https://developer.apple.com/documentation/metal/mtltexturetype

const (
	TextureType2D TextureType = 2
)

type TextureUsage

type TextureUsage uint8
const (
	TextureUsageUnknown         TextureUsage = 0x0000
	TextureUsageShaderRead      TextureUsage = 0x0001
	TextureUsageShaderWrite     TextureUsage = 0x0002
	TextureUsageRenderTarget    TextureUsage = 0x0004
	TextureUsagePixelFormatView TextureUsage = 0x0008
)

type Viewport

type Viewport struct {
	OriginX float64
	OriginY float64
	Width   float64
	Height  float64
	ZNear   float64
	ZFar    float64
}

Source Files