我已经按照WWDC2014上关于如何使用Metal API的讲座进行了演讲,他们正在创建" Hello world"应用程序与一个简单的三角我希望在绿色背景上看到一个红色三角形。一切都很好,但三角形本身并不存在,我无法弄清楚原因。请帮忙!
这些线是金属着色器:
struct Vertex
{
float3 position;
};
struct VertexOut
{
float4 position [[position]];
float4 color;
};
vertex VertexOut myVertexShader(
device Vertex* vertexArray [[ buffer(0) ]],
unsigned int vid [[ vertex_id ]])
{
VertexOut out;
float3 pos = vertexArray[vid].position;
out.position = float4(pos[0], pos[1], pos[2], 0.0);
out.color = float4(1.0, 0.0, 0.0, 1.0);
return out;
}
fragment float4 myFragmentShader(VertexOut interpolated [[ stage_in ]])
{
return interpolated.color;
}
这些是观点:
@implementation MyView
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if(self)
{
_device = MTLCreateSystemDefaultDevice();
}
NSLog(@"MyView::initWithCoder called");
return self;
}
+(id)layerClass
{
return [CAMetalLayer class];
}
@end
这些是视图控制器:
static const float zcoord = 0.f;
static const float vertexArrayData[] =
{
-0.3, -0.5, zcoord,
0.3, -0.5, zcoord,
0.f, 0.2, zcoord
};
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
MyView* view = (MyView*) self.view;
id<MTLCommandQueue> queue = [view.device newCommandQueue];
id<MTLBuffer> vertexArray = [view.device newBufferWithBytes:vertexArrayData
length:sizeof(vertexArrayData)
options:0];
MTLRenderPipelineDescriptor* desc = [MTLRenderPipelineDescriptor new];
id<MTLLibrary> lib = [view.device newDefaultLibrary];
desc.vertexFunction = [lib newFunctionWithName:@"myVertexShader"];
desc.fragmentFunction = [lib newFunctionWithName:@"myFragmentShader"];
desc.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
id<MTLRenderPipelineState> renderPipeline = [view.device newRenderPipelineStateWithDescriptor:desc error:nil];
id<MTLCommandBuffer> commandBuffer = [queue commandBuffer];
id<CAMetalDrawable> drawable = [(CAMetalLayer*)view.layer nextDrawable];
MTLRenderPassDescriptor* renderDesc = [MTLRenderPassDescriptor new];
renderDesc.colorAttachments[0].texture = drawable.texture;
renderDesc.colorAttachments[0].loadAction = MTLLoadActionClear;
renderDesc.colorAttachments[0].clearColor = MTLClearColorMake(0.0, 1.0, 0.0, 1.0);
id<MTLRenderCommandEncoder> render = [commandBuffer renderCommandEncoderWithDescriptor:renderDesc];
[render setRenderPipelineState:renderPipeline];
[render setVertexBuffer:vertexArray offset:0 atIndex:0];
[render drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
[render endEncoding];
[commandBuffer presentDrawable:drawable];
[commandBuffer commit];
}
答案 0 :(得分:2)
我知道了,费尔拉斯。
问题出在这一行:
out.position = float4(pos[0], pos[1], pos[2], 0.0);
float4 的最后一个组件不应为零。 1.0 的帮助。
此致