我有一个在blender中创建的模型并导出到.obj文件。我编写了一个解析器来读取顶点纹理和法线的坐标。我已经将所有的协调划分为适用于程序的常量,以减小模式的大小,使其适合屏幕(这是一个临时措施)。除了不起作用的照明外,这个工作正常,当它应该着色时,我留下了一个黑色的3D物体。在网上研究之后,我想这可能是因为法线不是长度一般?如果这是真的,我怎样才能缩放我的坐标以使它们适合屏幕并使照明工作?
顶点着色器
//
// 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;
}
Fragment Shader:
// 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);
答案 0 :(得分:1)
如果您使用着色器,则可以在GLSL代码中对顶点和法线使用normalize()
运算。
您还可以查看obj2opengl script,它可以对模型进行缩放,居中和规范化,将OBJ文件转换为可以为iOS实现的头文件。我还将该脚本扩展到mtl2opengl以包含对MTL文件的支持,并使其更轻量级(也有Xcode示例)。