SceneKit shader not working

2019-09-10 20:50发布

问题:

I'm trying to work with shaders in SceneKit on iOS 8. Here is my code:

let sphere = SCNSphere(radius: 6)
    sphere.segmentCount = 100
    sphere.firstMaterial?.diffuse.contents = UIImage(named: "noise.png")
    sphere.firstMaterial?.diffuse.wrapS = SCNWrapMode.Repeat
    sphere.firstMaterial?.diffuse.wrapT = SCNWrapMode.Repeat
    sphere.firstMaterial?.reflective.contents = UIImage(named: "envmap3")
    sphere.firstMaterial?.fresnelExponent = 1.3

    let sphereNode = SCNNode(geometry: sphere)
    sphereNode.position = SCNVector3(x: 0, y: 0, z: -20)

    let surfaceModifier = NSString(contentsOfFile: NSBundle.mainBundle().pathForResource("carPaint", ofType: "shader")!, encoding: NSUTF8StringEncoding, error: nil)
    sphere.firstMaterial?.shaderModifiers = [SCNShaderModifierEntryPointSurface: surfaceModifier!]

    scene.rootNode.addChildNode(sphereNode)

The code is from the WWDC 2013 SceneKit Demo and I translated it into Swift

This here is the corresponding shader code from the carPaint.shader file of that demo:

float flakeSize = 0.2;
float flakeIntensity = 0.7;

vec3 paintColor0 = vec3(0.9, 0.4, 0.3);
vec3 paintColor1 = vec3(0.9, 0.75, 0.2);
vec3 flakeColor = vec3(flakeIntensity, flakeIntensity, flakeIntensity);

vec3 rnd =  texture2D(u_diffuseTexture, _surface.diffuseTexcoord * vec2(1.0 / flakeSize)).rgb;
rnd = normalize(2 * rnd - 1.0);

vec3 nrm1 = normalize(0.05 * rnd + 0.95 * _surface.normal);
vec3 nrm2 = normalize(0.3 * rnd + 0.4 * _surface.normal);

float fresnel1 = clamp(dot(nrm1, _surface.view), 0.0, 1.0);
float fresnel2 = clamp(dot(nrm2, _surface.view), 0.0, 1.0);

vec3 col = mix(paintColor0, paintColor1, fresnel1);
col += pow(fresnel2, 106.0) * flakeColor;

_surface.normal = nrm1;
_surface.diffuse = vec4(col, 1.0);
_surface.emission = (_surface.reflective * _surface.reflective) * 2.0;
_surface.reflective = vec4(0.0);

And this here is the console output: http://pastebin.com/JAbJSrxg

The app does not crash but the shader is not working and the sphere color is set to pink.

So my question is, how can I get this to work? I think I'm doing it right but obviously I'm doing it not right.

Thanks

回答1:

The console log you posted says there's an error on this line of the shader:

rnd = normalize(2 * rnd - 1.0);

GLSL ES 1.0, which is used by OpenGL ES 2.0, which is what SceneKit uses on iOS, doesn't support integer types. So it's complaining about the literal 2 on that line. You can fix this by making it a floating point literal 2.0.

If this shader source is unchanged from the sample code project you pulled it from, you might want to report a bug. That shader code works on desktop OpenGL, but it ought to be written so that it works on iOS too.