我正在学习this tutorial并获得此metal
代码,并稍微改动以使用鼠标来控制相机的位置:
struct Ray {
float3 origin;
float3 direction;
Ray(float3 o, float3 d) {
origin = o;
direction = d;
}
};
struct Sphere {
float3 center;
float radius;
Sphere(float3 c, float r) {
center = c;
radius = r;
}
};
float distToSphere(Ray ray, Sphere s) {
return length(ray.origin - s.center) - s.radius;
}
float distToScene(Ray r) {
Sphere s = Sphere(float3(1.), 0.5);
Ray repeatRay = r;
repeatRay.origin = fmod(r.origin, 2.);
return distToSphere(repeatRay, s);
}
kernel void compute(texture2d<float, access::write> output [[texture(0)]],
constant float &mouseX [[buffer(1)]],
constant float &mouseY [[buffer(2)]],
uint2 gid [[thread_position_in_grid]]) {
int width = output.get_width();
int height = output.get_height();
float2 uv = float2(gid) / float2(width, height);
uv = uv * 2.0 - 1.0;
float3 camPos = float3(1000+mouseX*-0.05, 1000-mouseY*0.05, 1);
Ray ray = Ray(camPos, normalize(float3(uv.x,uv.y, 1.)));
float3 col = float3(0.);
for (int i=0.; i<100.; i++) {
float dist = distToScene(ray);
if (dist < 0.001) {
col = float3(1.);
break;
}
ray.origin += ray.direction * dist;
}
float3 posRelativeToCamera = ray.origin - camPos;
output.write(float4(col * abs((posRelativeToCamera) / 10.0), 1.), gid);
}
一切正常。现在,我想用鼠标旋转相机而不是位置。我从shadertoy.com做了一些研究,并将setCamera()
代码转换为metal
:
float3x3 setCamera( float3 origin, float3 target, float rotation) {
float3 forward = normalize(target - origin);
float3 orientation = float3(sin(rotation), cos(rotation), 0.0);
float3 left = normalize(cross(forward, orientation));
float3 up = normalize(cross(left, forward));
return float3x3(left, up, forward);
}
但是,我不知道如何注入我的代码以使其工作。
我该如何使其发挥作用?