RealityKit自定义片段着色器中如何创建/获取纹理采样器对象?
解决RealityKit自定义表面着色器中textureSampler未初始化的问题
苹果官方文档的这段示例代码确实遗漏了纹理采样器的获取逻辑——你不需要手动创建或初始化textureSampler,RealityKit会为材质中的纹理自动绑定对应的采样器,直接通过surface_parameters的samplers()接口即可获取。
修改后的完整代码如下:
#include <metal_stdlib> #include <RealityKit/RealityKit.h> using namespace metal; [[visible]] void mySurfaceShader(realitykit::surface_parameters params) { // Retrieve the base color tint from the entity's material. half3 baseColorTint = (half3)params.material_constants().base_color_tint(); // Retrieve the entity's texture coordinates. float2 uv = params.geometry().uv0(); // Flip the texture coordinates y-axis. This is only needed for entities // loaded from USDZ or .reality files. uv.y = 1.0 - uv.y; // Sample a value from the material's base color texture based on the // flipped UV coordinates. auto tex = params.textures(); auto sampler = params.samplers().base_color(); // 获取与base_color纹理绑定的采样器 half3 color = (half3)tex.base_color().sample(sampler, uv).rgb; // Multiply the tint by the sampled value from the texture, and // assign the result to the shader's base color property. color *= baseColorTint; params.surface().set_base_color(color); }
核心修改点是新增了auto sampler = params.samplers().base_color();这一行,通过params.samplers()获取材质中与基础颜色纹理配对的采样器,直接用于纹理采样即可。RealityKit会根据你在Swift/Obj-C代码中配置的材质采样参数(比如过滤模式、寻址模式)自动初始化这个采样器,无需手动配置。
内容的提问来源于stack exchange,提问作者foolinaroundz
相关产品推荐
相关产品推荐

