ambientOcclusion
The ambient light exposure for a material.
Declaration
var ambientOcclusion: CustomMaterial.AmbientOcclusion { get set }Discussion
Ambient occlusion (AO) represents the entity’s exposure to ambient light. Specify ambient occlusion using a UV-mapped image called an ambient occlusion map. In an AO map, black pixels represent parts of the model that receive no ambient light because of a crevice, dent, or recessed area, or another part of the entity blocking ambient light from reaching it. White pixels represent flat portions of the model that receive full ambient light. You generate ambient occlusion maps using a 3D software package.
The following code loads an ambient occlusion map and adds it to the custom material:
if let aoResource = try? TextureResource.load(named:"entity_ao") {
let aoMap = MaterialParameters.Texture(aoResource)
material.emissiveColor = .init(texture: aoMap)
}In a custom material, RealityKit doesn’t automatically use the value you set on this property to render your entity. The ambient occlusion texture is available in the material’s shader functions, but RealityKit only renders ambient occlusion if the material’s lightingModel is CustomMaterial.LightingModel.lit or CustomMaterial.LightingModel.clearcoat and its surface shader calls params.surface().set_ambient_occlusion().
The following Metal code shows how to sample the ambient occlusion texture to set the AO value in a surface shader function:
// Retrieve the entity's texture coordinates.
float2 uv = params.geometry().uv0();
// Entities loaded from USDZ or .reality files have texture coordinates
// with a flipped y-axis. This adjusts for that.
uv.y = 1.0 - uv.y;
// Sample the ambient occlusion texture and use it to set the
// ambient occlusion value to use during rendering.
auto tex = params.textures();
half metallic = tex.ambient_occlusion().sample(textureSampler, uv).r;
params.surface().set_ambient_occlusion(metallic);