所以,我正在尝试用 3d 纹理渲染一个立方体。纹理包含 3 片 3 种不同的颜色,红绿蓝。每个切片由具有相同颜色的 4 个像素组成。工作正常。https://imgur.com/a/a5oXi
private func makeTexture() {
let width = 2
let height = 2
let depth = 3
let byteSize = 4
let bytesPerRow = byteSize * width
let bytesPerImage = bytesPerRow * height
let blue: UInt32 = 0x000000FF
let green: UInt32 = 0xFF00FF00
let red: UInt32 = 0x00FF0000
let textureDescriptor = MTLTextureDescriptor()
textureDescriptor.pixelFormat = .bgra8Unorm
textureDescriptor.width = width
textureDescriptor.height = height
textureDescriptor.depth = depth
textureDescriptor.textureType = .type3D
let image = UnsafeMutableRawPointer.allocate(bytes: width*height*depth*byteSize, alignedTo: 1)
image.storeBytes(of: red, toByteOffset: 0, as: UInt32.self)
image.storeBytes(of: red, toByteOffset: 4, as: UInt32.self)
image.storeBytes(of: red, toByteOffset: 8, as: UInt32.self)
image.storeBytes(of: red, toByteOffset: 12, as: UInt32.self)
image.storeBytes(of: green, toByteOffset: 16, as: UInt32.self)
image.storeBytes(of: green, toByteOffset: 20, as: UInt32.self)
image.storeBytes(of: green, toByteOffset: 24, as: UInt32.self)
image.storeBytes(of: green, toByteOffset: 28, as: UInt32.self)
image.storeBytes(of: blue, toByteOffset: 32, as: UInt32.self)
image.storeBytes(of: blue, toByteOffset: 36, as: UInt32.self)
image.storeBytes(of: blue, toByteOffset: 40, as: UInt32.self)
image.storeBytes(of: blue, toByteOffset: 44, as: UInt32.self)
texture = device?.makeTexture(descriptor: textureDescriptor)
let region = MTLRegionMake3D(0, 0, 0, width, height, depth)
texture?.replace(region: region,
mipmapLevel: 0,
slice: 0,
withBytes: image,
bytesPerRow: bytesPerRow,
bytesPerImage: bytesPerImage)
}
片段着色器代码:
struct VertexOut{
float4 position [[position]];
float3 textureCoordinate;
};
fragment half4 basic_fragment(VertexOut in [[stage_in]],
texture3d<half> colorTexture [[ texture(0) ]]) {
constexpr sampler textureSampler (mag_filter::nearest,
min_filter::nearest);
// Sample the texture to obtain a color
const half4 colorSample = colorTexture.sample(textureSampler, in.textureCoordinate);
// We return the color of the texture
return colorSample;
}
然后我想让红色和蓝色切片透明,所以我设置 alphas 等于 0
let blue: UInt32 = 0x000000FF
let green: UInt32 = 0xFF00FF00
let red: UInt32 = 0x00FF0000
片段着色器现在包含
const half4 colorSample = colorTexture.sample(textureSampler, in.textureCoordinate);
if (colorSample.a <= 0)
discard_fragment();
并希望看到绿色的切口,但我只看到绿色边缘https://imgur.com/a/yGQdQ。
立方体内部没有任何东西,我什至看不到后边缘,因为 cullMode 设置为 .front。
我可以绘制并查看对象内的纹理,以便我可以看到它的内部吗?到目前为止我还没有找到方法。不是当我将纹理类型设置为 3d 时,它应该计算 3D 对象的每个像素的颜色吗?不只是边缘?也许可以,但不显示?