axiom-metal-migration-diag
Use when ANY Metal porting issue occurs - black screen, rendering artifacts, shader errors, wrong colors, performance regressions, GPU crashes
Install
mkdir -p .claude/skills/axiom-metal-migration-diag && curl -L -o skill.zip "https://mcp.directory/api/skills/download/6505" && unzip -o skill.zip -d .claude/skills/axiom-metal-migration-diag && rm skill.zipInstalls to .claude/skills/axiom-metal-migration-diag
About this skill
Metal Migration Diagnostics
Systematic diagnosis for common Metal porting issues.
When to Use This Diagnostic Skill
Use this skill when:
- Screen is black after porting to Metal
- Shaders fail to compile in Metal
- Colors or coordinates are wrong
- Performance is worse than the original
- Rendering artifacts appear
- App crashes during GPU work
Mandatory First Step: Enable Metal Validation
Time cost: 30 seconds setup vs hours of blind debugging
Before ANY debugging, enable Metal validation:
Xcode → Edit Scheme → Run → Diagnostics
✓ Metal API Validation
✓ Metal Shader Validation
✓ GPU Frame Capture (Metal)
Most Metal bugs produce clear validation errors. If you're debugging without validation enabled, stop and enable it first.
Symptom 1: Black Screen
Decision Tree
Black screen after porting
│
├─ Are there Metal validation errors in console?
│ └─ YES → Fix validation errors first (see below)
│
├─ Is the render pass descriptor valid?
│ ├─ Check: view.currentRenderPassDescriptor != nil
│ ├─ Check: drawable = view.currentDrawable != nil
│ └─ FIX: Ensure MTKView.device is set, view is on screen
│
├─ Is the pipeline state created?
│ ├─ Check: makeRenderPipelineState doesn't throw
│ └─ FIX: Check shader function names match library
│
├─ Are draw calls being issued?
│ ├─ Add: encoder.label = "Main Pass" for frame capture
│ └─ DEBUG: GPU Frame Capture → verify draw calls appear
│
├─ Are resources bound?
│ ├─ Check: setVertexBuffer, setFragmentTexture called
│ └─ FIX: Metal requires explicit binding every frame
│
├─ Is the vertex data correct?
│ ├─ DEBUG: GPU Frame Capture → inspect vertex buffer
│ └─ FIX: Check buffer offsets, vertex count
│
├─ Are coordinates in Metal's range?
│ ├─ Metal NDC: X [-1,1], Y [-1,1], Z [0,1]
│ ├─ OpenGL NDC: X [-1,1], Y [-1,1], Z [-1,1]
│ └─ FIX: Adjust projection matrix or vertex shader
│
└─ Is clear color set?
├─ Default clear color is (0,0,0,0) — transparent black
└─ FIX: Set view.clearColor or renderPassDescriptor.colorAttachments[0].clearColor
Common Fixes
Missing Drawable:
// BAD: Drawing before view is ready
override func viewDidLoad() {
draw() // metalView.currentDrawable is nil
}
// GOOD: Wait for delegate callback
func draw(in view: MTKView) {
guard let drawable = view.currentDrawable else { return }
// Safe to draw
}
Wrong Function Names:
// BAD: Function name doesn't match .metal file
descriptor.vertexFunction = library.makeFunction(name: "vertexMain")
// .metal file has: vertex VertexOut vertexShader(...)
// GOOD: Names must match exactly
descriptor.vertexFunction = library.makeFunction(name: "vertexShader")
Missing Resource Binding:
// BAD: Assumed state persists like OpenGL
encoder.setRenderPipelineState(pso)
encoder.drawPrimitives(...) // No buffers bound!
// GOOD: Bind everything explicitly
encoder.setRenderPipelineState(pso)
encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
encoder.setVertexBytes(&uniforms, length: uniformsSize, index: 1)
encoder.setFragmentTexture(texture, index: 0)
encoder.drawPrimitives(...)
Time cost: GPU Frame Capture diagnosis: 5-10 min. Guessing without tools: 1-4 hours.
Symptom 2: Shader Compilation Errors
Decision Tree
Shader fails to compile
│
├─ "Use of undeclared identifier"
│ ├─ Check: #include <metal_stdlib>
│ ├─ Check: using namespace metal;
│ └─ FIX: Standard functions need metal_stdlib
│
├─ "No matching function for call to 'texture'"
│ └─ GLSL texture() → MSL tex.sample(sampler, uv)
│ FIX: Texture sampling is a method, needs sampler
│
├─ "Invalid type 'vec4'"
│ └─ GLSL vec4 → MSL float4
│ FIX: See type mapping table in metal-migration-ref
│
├─ "No matching constructor"
│ ├─ GLSL: vec4(vec3, float) works
│ ├─ MSL: float4(float3, float) works
│ └─ Check: Argument types match exactly
│
├─ "Attribute index out of range"
│ ├─ Check: [[attribute(N)]] matches vertex descriptor
│ └─ FIX: vertexDescriptor.attributes[N] must be configured
│
├─ "Buffer binding index out of range"
│ ├─ Check: [[buffer(N)]] where N < 31
│ └─ FIX: Metal has max 31 buffer bindings per stage
│
└─ "Cannot convert value of type"
├─ MSL is stricter than GLSL about implicit conversions
└─ FIX: Add explicit casts: float(intValue), int(floatValue)
Common Conversions
// GLSL
vec4 color = texture(sampler2D, uv);
// MSL — texture and sampler are separate
float4 color = tex.sample(samp, uv);
// GLSL — mod() for floats
float x = mod(y, z);
// MSL — fmod() for floats
float x = fmod(y, z);
// GLSL — atan(y, x)
float angle = atan(y, x);
// MSL — atan2(y, x)
float angle = atan2(y, x);
// GLSL — inversesqrt
float invSqrt = inversesqrt(x);
// MSL — rsqrt
float invSqrt = rsqrt(x);
Time cost: With conversion table: 2-5 min per shader. Without: 15-30 min per shader.
Symptom 3: Wrong Colors or Coordinates
Decision Tree
Rendering looks wrong
│
├─ Image is upside down
│ ├─ Cause: Metal Y-axis is opposite OpenGL
│ ├─ FIX (vertex shader): pos.y = -pos.y
│ ├─ FIX (texture load): MTKTextureLoader .origin: .bottomLeft
│ └─ FIX (UV): uv.y = 1.0 - uv.y in fragment shader
│
├─ Image is mirrored
│ ├─ Cause: Winding order or cull mode wrong
│ ├─ FIX: encoder.setFrontFacing(.counterClockwise)
│ └─ FIX: encoder.setCullMode(.back) or .none to test
│
├─ Colors are swapped (red/blue)
│ ├─ Cause: Pixel format mismatch
│ ├─ Check: .bgra8Unorm vs .rgba8Unorm
│ └─ FIX: Match texture pixel format to data format
│
├─ Colors are washed out / too bright
│ ├─ Cause: sRGB vs linear color space
│ ├─ Check: Using .bgra8Unorm_srgb for sRGB textures?
│ └─ FIX: Use _srgb format variants for gamma-correct rendering
│
├─ Depth fighting / z-fighting
│ ├─ Cause: NDC Z range difference
│ ├─ OpenGL: Z in [-1, 1]
│ ├─ Metal: Z in [0, 1]
│ └─ FIX: Adjust projection matrix for Metal's Z range
│
├─ Objects clipped incorrectly
│ ├─ Cause: Near/far plane or viewport
│ ├─ Check: Viewport size matches drawable size
│ └─ FIX: encoder.setViewport(MTLViewport(...))
│
└─ Transparency wrong
├─ Cause: Blend state not configured
├─ FIX: pipelineDescriptor.colorAttachments[0].isBlendingEnabled = true
└─ FIX: Set sourceRGBBlendFactor, destinationRGBBlendFactor
Coordinate System Fix
// Fix projection matrix for Metal's Z range [0, 1]
func metalPerspectiveProjection(fovY: Float, aspect: Float, near: Float, far: Float) -> simd_float4x4 {
let yScale = 1.0 / tan(fovY * 0.5)
let xScale = yScale / aspect
let zRange = far - near
return simd_float4x4(rows: [
SIMD4<Float>(xScale, 0, 0, 0),
SIMD4<Float>(0, yScale, 0, 0),
SIMD4<Float>(0, 0, far / zRange, 1), // Metal: [0, 1]
SIMD4<Float>(0, 0, -near * far / zRange, 0)
])
}
Time cost: With GPU Frame Capture texture inspection: 5-10 min. Without: 1-2 hours.
Symptom 4: Performance Regression
Decision Tree
Performance worse than OpenGL
│
├─ Enabling validation?
│ └─ Validation adds ~30% overhead
│ FIX: Disable for release builds, keep for debug
│
├─ Creating resources every frame?
│ ├─ BAD: device.makeBuffer() in draw()
│ └─ FIX: Create buffers once, reuse with triple buffering
│
├─ Creating pipeline state every frame?
│ ├─ BAD: makeRenderPipelineState() in draw()
│ └─ FIX: Create PSO once at init, store as property
│
├─ Too many draw calls?
│ ├─ DEBUG: GPU Frame Capture → count draw calls
│ └─ FIX: Batch geometry, use instancing, indirect draws
│
├─ GPU-CPU sync stalls?
│ ├─ DEBUG: Metal System Trace → look for stalls
│ ├─ Cause: waitUntilCompleted() blocks CPU
│ └─ FIX: Triple buffering with semaphore
│
├─ Inefficient buffer updates?
│ ├─ BAD: Recreating buffer to update
│ └─ FIX: buffer.contents().copyMemory() for dynamic data
│
├─ Wrong storage mode?
│ ├─ .shared: Good for small dynamic data
│ ├─ .private: Good for static GPU-only data
│ └─ FIX: Use .private for geometry that doesn't change
│
└─ Missing Metal-specific optimizations?
├─ Argument buffers reduce binding overhead
├─ Indirect draws reduce CPU work
└─ See WWDC sessions on Metal optimization
Triple Buffering Pattern
class TripleBufferedRenderer {
static let maxInflightFrames = 3
let inflightSemaphore = DispatchSemaphore(value: maxInflightFrames)
var uniformBuffers: [MTLBuffer] = []
var currentBufferIndex = 0
init(device: MTLDevice) {
for _ in 0..<Self.maxInflightFrames {
let buffer = device.makeBuffer(length: uniformsSize, options: .storageModeShared)!
uniformBuffers.append(buffer)
}
}
func draw(in view: MTKView) {
// Wait for a buffer to be available
inflightSemaphore.wait()
let buffer = uniformBuffers[currentBufferIndex]
// Safe to write — GPU is done with this buffer
memcpy(buffer.contents(), &uniforms, uniformsSize)
let commandBuffer = commandQueue.makeCommandBuffer()!
// Signal when GPU is done
commandBuffer.addCompletedHandler { [weak self] _ in
self?.inflightSemaphore.signal()
}
// ... encode and commit
currentBufferIndex = (currentBufferIndex + 1) % Self.maxInflightFrames
}
}
Time cost: Metal System Trace diagnosis: 15-30 min. Guessing: hours.
Symptom 5: Crashes During GPU Work
Decision Tree
App crashes during rendering
│
├─ EXC_BAD_ACCESS in Metal framework
│ ├─ Cause: Accessing released resource
│ ├─ Check: Buffer/texture retained during GPU use
│ └─ FIX: Keep strong references until command buffer completes
│
├─ "Execution of the command buffer was aborted"
│ ├─ Cause: GPU timeout (>10 sec on iOS)
│ ├─ Check: Infinite loop in shader?
│ └─ FIX: Add early exit conditions, reduce work
│
├─ "-[MTLDebugRenderCommandEncoder validateDrawCall
---
*Content truncated.*
More by CharlesWiltgen
View all skills by CharlesWiltgen →You might also like
flutter-development
aj-geddes
Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.
drawio-diagrams-enhanced
jgtolentino
Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.
ui-ux-pro-max
nextlevelbuilder
"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."
godot
bfollington
This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.
nano-banana-pro
garg-aayush
Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.
fastapi-templates
wshobson
Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.
Related MCP Servers
Browse all serversExtend your developer tools with GitHub MCP Server for advanced automation, supporting GitHub Student and student packag
RSS Feed Parser is a powerful rss feed generator and rss link generator with RSSHub integration, perfect for creating cu
Access and interact with Jira and Linear tickets directly in conversations—no context switching to Jira ticketing softwa
Enhance your workflow with platform-specific notification sounds on Android. Get alert sounds & custom tones, including
Use Claude Code, Gemini CLI, Codex CLI, or any MCP client with any AI model. Acts as a multi-model proxy supporting Open
Access Confluence pages and Jira in the cloud with Atlassian API. Integrate effortlessly using the REST API for Jira.
Stay ahead of the MCP ecosystem
Get weekly updates on new skills and servers.