我在搅拌机中创建了一个模型并导出到 .obj 文件。我编写了一个解析器,它读取顶点纹理和法线的坐标。我一直将所有坐标除以适用于程序的常数,以减小模式的大小,使其适合屏幕(这是一个临时措施)。这工作正常,除了照明不起作用,当它应该着色时,我留下了一个黑色的 3D 对象。在网上研究之后,我认为这可能是因为法线不是长度为 1?如果这是真的,我如何缩放我的坐标以使其适合屏幕并让照明正常工作?
顶点着色器
//
// Created by Jake Cunningham on 13/10/2012.
// Copyright (c) 2012 Jake Cunningham. All rights reserved.
//
attribute vec4 position;
attribute vec3 normal;
varying lowp vec4 colorVarying;
uniform mat4 modelViewProjectionMatrix;
uniform mat3 normalMatrix;
attribute vec2 TextCo;
varying vec2 textCoOut;
void main()
{
vec3 eyeNormal = normalize(normalMatrix * normal);
vec3 lightPosition = vec3(0.0, 0.0, 1.0);
vec4 diffuseColor = vec4(0.4, 0.4, 1.0, 1.0);
float nDotVP = max(0.0, dot(eyeNormal, normalize(lightPosition)));
colorVarying = diffuseColor * nDotVP;
gl_Position = modelViewProjectionMatrix * position;
textCoOut = TextCo;
}
片段着色器:
// Created by Jake Cunningham on 13/10/2012.
// Copyright (c) 2012 Jake Cunningham. All rights reserved.
//
varying lowp vec4 colorVarying;
varying lowp vec2 textCoOut;
uniform sampler2D texture;
void main()
{
gl_FragColor = colorVarying * texture2D(texture, textCoOut);
}
来自视图控制器的代码。
glEnable(GL_DEPTH_TEST);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glGenVertexArraysOES(1, &_vertexArray);
glBindVertexArrayOES(_vertexArray);
glGenBuffers(1, &_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, loader.currentCountOfVerticies * sizeof(GLfloat) * 3, arrayOfVerticies, GL_STATIC_DRAW);
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 12, BUFFER_OFFSET(0));
glGenVertexArraysOES(1, &_normalArray);
glBindVertexArrayOES(_normalArray);
glGenBuffers(1, &_normalBuffer);
glBindBuffer(GL_ARRAY_BUFFER, _normalBuffer);
glBufferData(GLKVertexAttribNormal, loader.currentCountOfNormals * sizeof(GLfloat) * 3,loader.arrayOfNormals , GL_STATIC_DRAW);
glEnableVertexAttribArray(GLKVertexAttribNormal);
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 12, BUFFER_OFFSET(0));
glGenVertexArraysOES(1, &_textureArray);
glBindVertexArrayOES(_textureArray);
glGenBuffers(1, &_textureBuffer);
glBindBuffer(GL_ARRAY_BUFFER, _textureBuffer);
glBufferData(GL_ARRAY_BUFFER, loader.currentCountOfTextureCoordinates * sizeof(GLfloat) * 2, loader.arrayOftextureCoOrdinates, GL_STATIC_DRAW);
glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 8, BUFFER_OFFSET(0));
glBindVertexArrayOES(0);