struct Material
{
float3 ambientColor;
float3 diffuseColor;
float3 specularColor;
float specularPower;
};
//结构体的声明和初始化(常量)
constant Material material = {
.ambientColor = { 0.9, 0.1, 0 },
.diffuseColor = { 0.9, 0.1, 0 },
.specularColor = { 1, 1, 1 },
.specularPower = 100
};
//变量属性
struct Vertex
{
float4 position [[attribute(0)]];
float3 normal [[attribute(1)]];
};
#include
typedef struct
{
simd::float4x4 modelViewProjectionMatrix;
simd::float4x4 modelViewMatrix;
simd::float3x3 normalMatrix;
} Uniforms;
使用SIMD库
vertex VS(Vertex vert [[stage_in]],
constant Uniforms &uniforms [[buffer(1)]])
{
ProjectedVertex outVert;
outVert.position = uniforms.modelViewProjectionMatrix * vert.position;
outVert.eye = -(uniforms.modelViewMatrix * vert.position).xyz;
outVert.normal = uniforms.normalMatrix * vert.normal;
return outVert;
}
fragment float4 PS(ProjectedVertex vert [[stage_in]], constant Uniforms &uniforms [[buffer(0)]])
{
float3 ambientTerm = light.ambientColor * material.ambientColor;
float3 normal = normalize(vert.normal);
float diffuseIntensity = saturate(dot(normal, light.direction));
float3 diffuseTerm = light.diffuseColor * material.diffuseColor * diffuseIntensity;
//Blin-Phong Shading
float3 specularTerm(0);
if (diffuseIntensity > 0)
{
float3 eyeDirection = normalize(vert.eye);
float3 halfway = normalize(light.direction + eyeDirection);
float specular = pow(saturate(dot(normal, halfway)), material.specularPower);
specularTerm = light.specularColor * material.specularColor * specular;
}
return float4(ambientTerm + diffuseTerm + specularTerm, 1);
}
texture2d tex [[ texture(QUAD_IMAGE_TEXTURE) ]];
constexpr sampler s_quad(filter::linear);
half4 image_color = tex.sample(s_quad, in.uv);
本文版权DsoTsin所有,转载文章请注明出处!