axiom-metal-migration-ref について
OpenGLやDirectXの描画コードをMetalへ移植する開発者向けのリファレンススキルです。シェーダー変換、API対応表、ビューやパイプラインの設定、ストレージモードと同期を扱います。
主な機能
- 01GLSL・HLSLからMSLへの対応表
- 02OpenGLとMetal APIの対応表
- 03MTKViewとCAMetalLayerの設定
- 04描画パイプラインとストレージモード
- 05Metal Shader Converterの手順
活用シーン
- 01GLSLシェーダーのMSLへの移植
- 02HLSLシェーダーのMSLへの変換
- 03OpenGL呼び出しに対応するMetal APIの確認
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ charleswiltgen/ axiom --skill axiom-metal-migration-refインストール後、Claude Code で/axiom-metal-migration-refを入力して読み込まれたか確認します。
詳細
Metal 移行リファレンス
OpenGL/DirectX のコードを Metal に変換するための完全なリファレンスです。
このリファレンスを使用する場面
次の場合にこのリファレンスを使用してください:
- GLSL シェーダーを Metal Shading Language(MSL)に変換する
- HLSL シェーダーを MSL に変換する
- Metal における GL/D3D API の相当機能を調べる
- MTKView または CAMetalLayer を設定する
- レンダーパイプラインを構築する
- DirectX 向けに Metal Shader Converter を使用する
パート 1:GLSL から MSL への変換
型の対応
| GLSL | MSL | 備考 |
|---|---|---|
void | void | |
bool | bool | |
int | int | 32 ビット符号付き |
uint | uint | 32 ビット符号なし |
float | float | 32 ビット |
double | N/A | float を使用します(MSL に 64 ビット浮動小数点型はありません) |
vec2 | float2 | |
vec3 | float3 | |
vec4 | float4 | |
ivec2 | int2 | |
ivec3 | int3 | |
ivec4 | int4 | |
uvec2 | uint2 | |
uvec3 | uint3 | |
uvec4 | uint4 | |
bvec2 | bool2 | |
bvec3 | bool3 | |
bvec4 | bool4 | |
mat2 | float2x2 | |
mat3 | float3x3 | |
mat4 | float4x4 | |
mat2x3 | float2x3 | 列 x 行 |
mat3x4 | float3x4 | |
sampler2D | texture2d<float> + sampler | MSL では分離されています |
sampler3D | texture3d<float> + sampler | |
samplerCube | texturecube<float> + sampler | |
sampler2DArray | texture2d_array<float> + sampler | |
sampler2DShadow | depth2d<float> + sampler |
組み込み変数の対応
| GLSL | MSL | ステージ |
|---|---|---|
gl_Position | [[position]] を返す | 頂点 |
gl_PointSize | [[point_size]] を返す | 頂点 |
gl_VertexID | [[vertex_id]] パラメーター | 頂点 |
gl_InstanceID | [[instance_id]] パラメーター | 頂点 |
gl_FragCoord | [[position]] パラメーター | フラグメント |
gl_FrontFacing | [[front_facing]] パラメーター | フラグメント |
gl_PointCoord | [[point_coord]] パラメーター | フラグメント |
gl_FragDepth | [[depth(any)]] を返す | フラグメント |
gl_SampleID | [[sample_id]] パラメーター | フラグメント |
gl_SamplePosition | [[sample_position]] パラメーター | フラグメント |
関数の対応
| GLSL | MSL | 備考 |
|---|---|---|
texture(sampler, uv) | tex.sample(sampler, uv) | テクスチャのメソッド |
textureLod(sampler, uv, lod) | tex.sample(sampler, uv, level(lod)) | |
textureGrad(sampler, uv, ddx, ddy) | tex.sample(sampler, uv, gradient2d(ddx, ddy)) | |
texelFetch(sampler, coord, lod) | tex.read(coord, lod) | 整数座標 |
textureSize(sampler, lod) | tex.get_width(lod)、tex.get_height(lod) | 別々に呼び出します |
dFdx(v) | dfdx(v) | |
dFdy(v) | dfdy(v) | |
fwidth(v) | fwidth(v) | 同じ |
mix(a, b, t) | mix(a, b, t) | 同じ |
clamp(v, lo, hi) | clamp(v, lo, hi) | 同じ |
smoothstep(e0, e1, x) | smoothstep(e0, e1, x) | 同じ |
step(edge, x) | step(edge, x) | 同じ |
mod(x, y) | fmod(x, y) | 名前が異なります |
fract(x) | fract(x) | 同じ |
inversesqrt(x) | rsqrt(x) | 名前が異なります |
atan(y, x) | atan2(y, x) | 名前が異なります |
シェーダー構造の変換
GLSL 頂点シェーダー:
#version 300 es
precision highp float;
layout(location = 0) in vec3 aPosition;
layout(location = 1) in vec2 aTexCoord;
uniform mat4 uModelViewProjection;
out vec2 vTexCoord;
void main() {
gl_Position = uModelViewProjection * vec4(aPosition, 1.0);
vTexCoord = aTexCoord;
}
MSL 頂点シェーダー:
#include <metal_stdlib>
using namespace metal;
struct VertexIn {
float3 position [[attribute(0)]];
float2 texCoord [[attribute(1)]];
};
struct VertexOut {
float4 position [[position]];
float2 texCoord;
};
struct Uniforms {
float4x4 modelViewProjection;
};
vertex VertexOut vertexShader(
VertexIn in [[stage_in]],
constant Uniforms& uniforms [[buffer(1)]]
) {
VertexOut out;
out.position = uniforms.modelViewProjection * float4(in.position, 1.0);
out.texCoord = in.texCoord;
return out;
}
GLSL フラグメントシェーダー:
#version 300 es
precision highp float;
in vec2 vTexCoord;
uniform sampler2D uTexture;
out vec4 fragColor;
void main() {
fragColor = texture(uTexture, vTexCoord);
}
MSL フラグメントシェーダー:
fragment float4 fragmentShader(
VertexOut in [[stage_in]],
texture2d<float> tex [[texture(0)]],
sampler samp [[sampler(0)]]
) {
return tex.sample(samp, in.texCoord);
}
精度修飾子
GLSL の精度修飾子に直接対応する MSL の機能はありません。MSL では明示的な型を使用します。
| GLSL | MSL の相当型 |
|---|---|
lowp float | half(16 ビット) |
mediump float | half(16 ビット) |
highp float | float(32 ビット) |
lowp int | short(16 ビット) |
mediump int | short(16 ビット) |
highp int | int(32 ビット) |
バッファーのアラインメント(重要)
GLSL/C での想定:
vec3:12 バイト、アラインメントは任意vec4:16 バイト
MSL での要件:
float3:ストレージは 12 バイト、16 バイト境界にアラインメントfloat4:ストレージは 16 バイト、16 バイト境界にアラインメント
解決策:CPU と GPU で共有する構造体には、Swift の simd 型を使用します。
import simd
struct Uniforms {
var modelViewProjection: simd_float4x4 // Correct alignment
var cameraPosition: simd_float3 // 16-byte aligned
var padding: Float = 0 // Explicit padding if needed
}
または、MSL のパック型を使用します(低速です)。
struct VertexPacked {
packed_float3 position; // 12 bytes, no padding
packed_float2 texCoord; // 8 bytes
};
パート 2:HLSL から MSL への変換
型マッピング
| HLSL | MSL | 注記 |
|---|---|---|
float | float | |
float2 | float2 | |
float3 | float3 | |
float4 | float4 | |
half | half | |
int | int | |
uint | uint | |
bool | bool | |
float2x2 | float2x2 | |
float3x3 | float3x3 | |
float4x4 | float4x4 | |
Texture2D | texture2d<float> | |
Texture3D | texture3d<float> | |
TextureCube | texturecube<float> | |
SamplerState | sampler | |
RWTexture2D | texture2d<float, access::read_write> | |
RWBuffer | device float* [[buffer(n)]] | |
StructuredBuffer | constant T* [[buffer(n)]] | |
RWStructuredBuffer | device T* [[buffer(n)]] |
セマンティクスマッピング
| HLSL セマンティクス | MSL 属性 |
|---|---|
SV_Position | [[position]] |
SV_Target0 | 戻り値 / [[color(0)]] |
SV_Target1 | [[color(1)]] |
SV_Depth | [[depth(any)]] |
SV_VertexID | [[vertex_id]] |
SV_InstanceID | [[instance_id]] |
SV_IsFrontFace | [[front_facing]] |
SV_SampleIndex | [[sample_id]] |
SV_PrimitiveID | [[primitive_id]] |
SV_DispatchThreadID | [[thread_position_in_grid]] |
SV_GroupThreadID | [[thread_position_in_threadgroup]] |
SV_GroupID | [[threadgroup_position_in_grid]] |
SV_GroupIndex | [[thread_index_in_threadgroup]] |
関数マッピング
| HLSL | MSL | 注記 |
|---|---|---|
tex.Sample(samp, uv) | tex.sample(samp, uv) | 小文字 |
tex.SampleLevel(samp, uv, lod) | tex.sample(samp, uv, level(lod)) | |
tex.SampleGrad(samp, uv, ddx, ddy) | tex.sample(samp, uv, gradient2d(ddx, ddy)) | |
tex.Load(coord) | tex.read(coord.xy, coord.z) | coord を分割 |
mul(a, b) | a * b | 演算子 |
saturate(x) | saturate(x) | 同じ |
lerp(a, b, t) | mix(a, b, t) | 名前が異なる |
frac(x) | fract(x) | 名前が異なる |
ddx(v) | dfdx(v) | 名前が異なる |
ddy(v) | dfdy(v) | 名前が異なる |
clip(x) | if (x < 0) discard_fragment() | 手動 |
discard | discard_fragment() | 関数呼び出し |
Metal Shader Converter(DirectX → Metal)
DXIL(コンパイル済み HLSL)を Metal ライブラリに変換する Apple の公式ツールです。
要件:
- Xcode 15 以降を搭載した macOS 13 以降
- または VS 2019 以降を搭載した Windows 10 以降
- 対象デバイス:Argument Buffers Tier 2(macOS 14 以降、iOS 17 以降)
ワークフロー:
# Step 1: Compile HLSL to DXIL using DXC
dxc -T vs_6_0 -E MainVS -Fo vertex.dxil shader.hlsl
dxc -T ps_6_0 -E MainPS -Fo fragment.dxil shader.hlsl
# Step 2: Convert DXIL to Metal library
metal-shaderconverter vertex.dxil -o vertex.metallib
metal-shaderconverter fragment.dxil -o fragment.metallib
# Step 3: Load in Swift
let vertexLib = try device.makeLibrary(URL: vertexURL)
let fragmentLib = try device.makeLibrary(URL: fragmentURL)
主なオプション:
| オプション | 用途 |
|---|---|
-o <file> | 出力 metallib のパス |
--minimum-gpu-family | 対象 GPU ファミリー |
--minimum-os-build-version | 最小 OS バージョン |
--vertex-stage-in | 頂点フェッチ関数を分離 |
-dualSourceBlending | デュアルソースブレンディングを有効化 |
対応するシェーダーモデル:SM 6.0~6.6(6.6 の機能には制限があります)
パート 3:OpenGL API から Metal API への移行
ビュー/コンテキストの設定
| OpenGL | Metal |
|---|---|
NSOpenGLView | MTKView |
GLKView | MTKView |
EAGLContext | MTLDevice + MTLCommandQueue |
CGLContextObj | MTLDevice |
リソースの作成
| OpenGL | Metal |
|---|---|
glGenBuffers + glBufferData | device.makeBuffer(bytes:length:options:) |
glGenTextures + glTexImage2D | device.makeTexture(descriptor:) + texture.replace(region:...) |
glGenFramebuffers | MTLRenderPassDescriptor |
glGenVertexArrays | MTLVertexDescriptor |
glCreateShader + glCompileShader | ビルド時コンパイル → MTLLibrary |
glCreateProgram + glLinkProgram | MTLRenderPipelineDescriptor → MTLRenderPipelineState |
状態管理
| OpenGL | Metal |
|---|---|
glEnable(GL_DEPTH_TEST) | MTLDepthStencilDescriptor → MTLDepthStencilState |
glDepthFunc(GL_LESS) | descriptor.depthCompareFunction = .less |
glEnable(GL_BLEND) | pipelineDescriptor.colorAttachments[0].isBlendingEnabled = true |
glBlendFunc | sourceRGBBlendFactor, destinationRGBBlendFactor |
glCullFace | encoder.setCullMode(.back) |
glFrontFace | encoder.setFrontFacing(.counterClockwise) |
glViewport | encoder.setViewport(MTLViewport(...)) |
glScissor | encoder.setScissorRect(MTLScissorRect(...)) |
描画コマンド
| OpenGL | Metal |
|---|---|
glDrawArrays(mode, first, count) | encoder.drawPrimitives(type:vertexStart:vertexCount:) |
glDrawElements(mode, count, type, indices) | encoder.drawIndexedPrimitives(type:indexCount:indexType:indexBuffer:indexBufferOffset:) |
glDrawArraysInstanced | encoder.drawPrimitives(type:vertexStart:vertexCount:instanceCount:) |
glDrawElementsInstanced | encoder.drawIndexedPrimitives(...instanceCount:) |
プリミティブ型
| OpenGL | Metal |
|---|---|
GL_POINTS | .point |
GL_LINES | .line |
GL_LINE_STRIP | .lineStrip |
GL_TRIANGLES | .triangle |
GL_TRIANGLE_STRIP | .triangleStrip |
GL_TRIANGLE_FAN | 該当なし(三角形に分解) |
パート 4:セットアップの完全な例
MTKView のセットアップ(推奨)
import MetalKit
class GameViewController: UIViewController {
var metalView: MTKView!
var renderer: Renderer!
override func viewDidLoad() {
super.viewDidLoad()
// Create Metal view
guard let device = MTLCreateSystemDefaultDevice() else {
fatalError("Metal not supported")
}
metalView = MTKView(frame: view.bounds, device: device)
metalView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
metalView.colorPixelFormat = .bgra8Unorm
metalView.depthStencilPixelFormat = .depth32Float
metalView.clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
metalView.preferredFramesPerSecond = 60
view.addSubview(metalView)
// Create renderer
renderer = Renderer(metalView: metalView)
metalView.delegate = renderer
}
}
class Renderer: NSObject, MTKViewDelegate {
let device: MTLDevice
let commandQueue: MTLCommandQueue
var pipelineState: MTLRenderPipelineState!
var depthState: MTLDepthStencilState!
var vertexBuffer: MTLBuffer!
init(metalView: MTKView) {
device = metalView.device!
commandQueue = device.makeCommandQueue()!
super.init()
buildPipeline(metalView: metalView)
buildDepthStencil()
buildBuffers()
}
private func buildPipeline(metalView: MTKView) {
let library = device.makeDefaultLibrary()!
let descriptor = MTLRenderPipelineDescriptor()
descriptor.vertexFunction = library.makeFunction(name: "vertexShader")
descriptor.fragmentFunction = library.makeFunction(name: "fragmentShader")
descriptor.colorAttachments[0].pixelFormat = metalView.colorPixelFormat
descriptor.depthAttachmentPixelFormat = metalView.depthStencilPixelFormat
// Vertex descriptor (matches shader's VertexIn struct)
let vertexDescriptor = MTLVertexDescriptor()
vertexDescriptor.attributes[0].format = .float3
vertexDescriptor.attributes[0].offset = 0
vertexDescriptor.attributes[0].bufferIndex = 0
vertexDescriptor.attributes[1].format = .float2
vertexDescriptor.attributes[1].offset = MemoryLayout<SIMD3<Float>>.stride
vertexDescriptor.attributes[1].bufferIndex = 0
vertexDescriptor.layouts[0].stride = MemoryLayout<Vertex>.stride
descriptor.vertexDescriptor = vertexDescriptor
pipelineState = try! device.makeRenderPipelineState(descriptor: descriptor)
}
private func buildDepthStencil() {
let descriptor = MTLDepthStencilDescriptor()
descriptor.depthCompareFunction = .less
descriptor.isDepthWriteEnabled = true
depthState = device.makeDepthStencilState(descriptor: descriptor)
}
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
// Handle resize
}
func draw(in view: MTKView) {
guard let drawable = view.currentDrawable,
let descriptor = view.currentRenderPassDescriptor,
let commandBuffer = commandQueue.makeCommandBuffer(),
let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: descriptor) else {
return
}
encoder.setRenderPipelineState(pipelineState)
encoder.setDepthStencilState(depthState)
encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: vertexCount)
encoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()
}
}
CAMetalLayer のセットアップ(カスタム制御)
import Metal
import QuartzCore
class MetalLayerView: UIView {
var metalLayer: CAMetalLayer!
var device: MTLDevice!
var commandQueue: MTLCommandQueue!
var displayLink: CADisplayLink?
override class var layerClass: AnyClass { CAMetalLayer.self }
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
device = MTLCreateSystemDefaultDevice()!
commandQueue = device.makeCommandQueue()!
metalLayer = layer as? CAMetalLayer
metalLayer.device = device
metalLayer.pixelFormat = .bgra8Unorm
metalLayer.framebufferOnly = true
displayLink = CADisplayLink(target: self, selector: #selector(render))
displayLink?.add(to: .main, forMode: .common)
}
override func layoutSubviews() {
super.layoutSubviews()
metalLayer.drawableSize = CGSize(
width: bounds.width * contentScaleFactor,
height: bounds.height * contentScaleFactor
)
}
@objc func render() {
guard let drawable = metalLayer.nextDrawable(),
let commandBuffer = commandQueue.makeCommandBuffer() else {
return
}
let descriptor = MTLRenderPassDescriptor()
descriptor.colorAttachments[0].texture = drawable.texture
descriptor.colorAttachments[0].loadAction = .clear
descriptor.colorAttachments[0].storeAction = .store
descriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 1)
guard let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: descriptor) else {
return
}
// Draw commands here
encoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()
}
}
コンピュートシェーダーのセットアップ
class ComputeProcessor {
let device: MTLDevice
let commandQueue: MTLCommandQueue
var computePipeline: MTLComputePipelineState!
init() {
device = MTLCreateSystemDefaultDevice()!
commandQueue = device.makeCommandQueue()!
let library = device.makeDefaultLibrary()!
let function = library.makeFunction(name: "computeKernel")!
computePipeline = try! device.makeComputePipelineState(function: function)
}
func process(input: MTLBuffer, output: MTLBuffer, count: Int) {
let commandBuffer = commandQueue.makeCommandBuffer()!
let encoder = commandBuffer.makeComputeCommandEncoder()!
encoder.setComputePipelineState(computePipeline)
encoder.setBuffer(input, offset: 0, index: 0)
encoder.setBuffer(output, offset: 0, index: 1)
let threadGroupSize = MTLSize(width: 256, height: 1, depth: 1)
let threadGroups = MTLSize(
width: (count + 255) / 256,
height: 1,
depth: 1
)
encoder.dispatchThreadgroups(threadGroups, threadsPerThreadgroup: threadGroupSize)
encoder.endEncoding()
commandBuffer.commit()
commandBuffer.waitUntilCompleted()
}
}
// Compute shader
kernel void computeKernel(
device float* input [[buffer(0)]],
device float* output [[buffer(1)]],
uint id [[thread_position_in_grid]]
) {
output[id] = input[id] * 2.0;
}
パート 5:ストレージモードと同期
バッファーのストレージモード
| モード | CPU アクセス | GPU アクセス | 用途 |
|---|---|---|---|
.shared | 読み取り/書き込み | 読み取り/書き込み | 小さな動的データ、ユニフォーム |
.private | なし | 読み取り/書き込み | 静的アセット、レンダーターゲット |
.managed (macOS) | 読み取り/書き込み | 読み取り/書き込み | 部分更新を行う大容量バッファー |
// Shared: CPU and GPU both access (iOS typical)
let uniformBuffer = device.makeBuffer(length: size, options: .storageModeShared)
// Private: GPU only (best for static geometry)
let vertexBuffer = device.makeBuffer(bytes: vertices, length: size, options: .storageModePrivate)
// Managed: Explicit sync (macOS)
#if os(macOS)
let buffer = device.makeBuffer(length: size, options: .storageModeManaged)
// After CPU write:
buffer.didModifyRange(0..<size)
#endif
テクスチャのストレージモード
let descriptor = MTLTextureDescriptor.texture2DDescriptor(
pixelFormat: .rgba8Unorm,
width: 1024,
height: 1024,
mipmapped: true
)
// For static textures (loaded once)
descriptor.storageMode = .private
descriptor.usage = [.shaderRead]
// For render targets
descriptor.storageMode = .private
descriptor.usage = [.renderTarget, .shaderRead]
// For CPU-readable (screenshots, readback)
descriptor.storageMode = .shared // iOS
descriptor.storageMode = .managed // macOS
descriptor.usage = [.shaderRead, .shaderWrite]
リソース
WWDC:2016-00602, 2018-00604, 2019-00611
ドキュメント:/metal/migrating-opengl-code-to-metal, /metal/shader-converter, /metalkit/mtkview
スキル:axiom-metal-migration, axiom-metal-migration-diag
最終更新日:2025-12-29 プラットフォーム:iOS 12+, macOS 10.14+, tvOS 12+ ステータス:シェーダー変換と API マッピングの完全なリファレンス