Search code examples
iosshadermetalrealitykit

in RealityKit Custom Shader API, how do I create a texture sampler object in fragment shader?


I'm trying to create my own fragment shader in RealityKit, and looking up at the documentation I found this sample code :

#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();
    half3 color = (half3)tex.base_color().sample(textureSampler, 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);
}

This is a copy pasted sample code from Apple's documentation that doesn't work because there's no textureSampler object being created/initialized.

Anybody knows how I supposed to get it? or set a new one? Documentation seems to be sparse

Thanks


Solution

  • Creating a texture sampler in a RealityKit surface shader

    There is an example, along with useful comments, about creating such a texture sampler in the documentation for the baseColor property of CustomMaterial in RealityKit: CustomMaterial.baseColor

    You can also find an implementation of this in the sample code for Altering RealityKit Rendering with Shader Functions

    Here’s the code used in the sample to create a texture sampler:

    constexpr sampler textureSampler(coord::normalized,
                                     address::repeat,
                                     filter::linear,
                                     mip_filter::linear);