2

For lighting I need the normal vectors in the fragment shader. The tutorials I read ask me to provide the normal data alongside with the vertices of a model. But aren't the normals already given by the faces specified by the vertices?

For calculating the normals I need all the three vertices of a triangle. But as far as I know we can only access a single vertex in each pass of the vertex shader.

How can I compute the normal vectors for each pixel based on the vertex data? I want to apply normal maps after that but that comes later and is not really related to this question.

danijar
  • 32,406
  • 45
  • 166
  • 297

1 Answers1

2

But aren't the normals already given by the faces specified by the vertices?

Yes, and no. Technically you could determine the normal per face, but usually the artist who designs a 3D model in a modeller wants to fine tune the normals to tweak lighting calculations.

normal vectors for each pixel based on the vertex data?

Just pass the normals as a varying variable (varying or out keyword, depending on the GLSL version) to the fragment shader. The normal vector will be interpolated barycentrically. You can then normalize it to unit length in the fragment shader.

datenwolf
  • 159,371
  • 13
  • 185
  • 298
  • The first part of your answer is clear, I want to fine tune the normals with normal maps later. But how can I calculate the normal in the vertex shader if there is only one (the current) vertex given but not all three triangle corners? – danijar Jan 04 '13 at 00:35
  • @sharethis: You don't compute normals in the vertex shader. It would be inefficient to redo this for each frame rendered. You calculate the normals once when loading the model, and normally you don't even compute them in the renderer. Normally the 3D model is saved completely with normals. – datenwolf Jan 04 '13 at 00:40
  • @sharethis: I explained in detail how to compute a mesh's vertex normal in http://stackoverflow.com/a/6661242/524368 – datenwolf Jan 04 '13 at 00:42
  • Just an addition for the correct answer: You can not calculate the vertex normal in a vertex shader, but if you can use a geometry shader before the vertex shader it is technically possible to calculate vertex normals on the fly. See [this thread](http://stackoverflow.com/questions/19346019/calculate-normals-geometry-shader). – Bim Feb 20 '15 at 15:21