ios - 写入 MTLTexture 会导致致命错误
问题描述
给定一个MTLTexture
,定义如下。
// Create device.
id<MTLDevice> dev = MTLCreateDefaultSystemDevice();
// Size of texture.
const unsigned int W = 640;
const unsigned int H = 480;
// Define texture.
MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init];
desc.pixelFormat = MTLPixelFormatBGRA8Unorm;
desc.width = W;
desc.height = H;
// Create texture.
id<MTLTexture> tex = [device newTextureWithDescriptor:desc];
据我了解,此时我应该拥有desc
在设备上分配dev
并通过tex
.
现在,给定另一个纹理tex2
(已知已分配和可访问)和定义如下的 Metal 计算内核。
kernel void foo(texture2d<float, access::read> in [[texture(0)]],
texture2d<float, access::write> out [[texture(1)]],
uint2 pix [[thread_position_in_grid]]) {
// Out of bounds check.
if (pix.x >= out.get_width() || pix.y >= out.get_height()) {
return;
}
// Do some processing on the input texture.
// ... All fine up to here.
// Write out a pixel to the output buffer.
const float4 p = abc; // abc is computed above.
out.write(p, pix);
}
据我了解,当像素p
被写入时out
, 的值p
将被转换为符合 的像素格式tex
,在这种情况下MTLPixelFormatBGRA8Unorm
。
但是,当按如下方式启动内核时,p
写入的行out
(上面定义为tex
)会触发严重错误(SIGABRT
)。
// Create a Metal library.
id<MTLLibrary> lib = [dev newDefaultLibrary];
// Load the kernel.
id<MTLFunction> kernel = [lib newFunctionWithName:@"foo"];
// Create a pipeline state.
id<MTLComputePipelineState> pipelineState = [dev newComputePipelineStateWithFunction:kernel error:NULL];
// Create a command queue.
id<MTLCommandQueue> cmdQueue = [dev newCommandQueue];
// Create command buffer.
id<MTLCommandBuffer> cmdBuff = [cmdQueue commandBuffer];
// Create compute encoder.
id<MTLComputeCommandEncoder> enc = [cmdBuff computeCommandEncoder];
// Set the pipeline state.
[enc setComputePipelineState:pipelineState];
// Set the input textures (tex2 is read only in the kernel, as above).
[enc setTexture:tex2 atIndex:0];
[enc setTexture:tex atIndex:1];
// 2D launch configuration.
const MTLSize groupDim = MTLSizeMake(16, 16, 1);
const MTLSize gridDim = MTLSizeMake((int)ceil((float)(W / (float)groupDim.width)),
(int)ceil((float)(H / (float)groupDim.height)),
1);
// Launch kernel.
[enc dispatchThreadgroups:gridDim threadsPerThreadgroup:groupDim];
[enc endEncoding];
[enc commit];
[cmdBuff waitUntilCompleted];
我的问题是,在上述情况下,我对如何分配 MTLTexture
正确的理解?或者,上面的示例是否仅在我需要单独分配的某些纹理周围定义一个包装器?
解决方案
上述纹理分配和计算内核启动是正确的。在进一步挖掘文档后,丢失的部分usage
是MTLTextureDescriptor
. 在文档中,说明了以下内容。
此属性的默认值为 MTLTextureUsageShaderRead。
因此,在问题中给出的示例中,需要以下附加属性分配MTLTextureDescriptor
。
desc.usage = MTLTextureUsageShaderWrite;
推荐阅读
- r - 在 R 中的 Shiny 上绘制密度图;得到“错误:数学函数的非数字参数”
- c# - 在 Hangfire.Core v1.7.18 中编辑 Strings.resx 文件时出现编译错误
- javascript - 如何让每个用户的网站“独一无二”?
- function - Dataweave 2.0:如何将其他块数据分配给变量
- javascript - 几秒钟后通知开/关
- java - Hibernate 支持 Union 吗?
- javascript - if/else 事件监听器的选择器问题
- java - 我的一门课完成后没有返回主课。我如何让它返回?
- rust - Rust 中的“项目”是什么?
- ruby-on-rails - 如何在我的 I18n 语言环境中添加 CSS 样式?