From 53bad4b29aea9da02728c5ba096fc2994e8475cf Mon Sep 17 00:00:00 2001 From: Learn OpenGL ES Date: Thu, 10 May 2012 17:19:33 -0400 Subject: [PATCH] Fix normal code -- use a cross product. --- .../android/lesson8/ErrorHandler.java | 1 - .../android/lesson8/LessonEightRenderer.java | 25 +++++++++++++------ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/android/AndroidOpenGLESLessons/src/com/learnopengles/android/lesson8/ErrorHandler.java b/android/AndroidOpenGLESLessons/src/com/learnopengles/android/lesson8/ErrorHandler.java index 9a4c45b..a03d89c 100644 --- a/android/AndroidOpenGLESLessons/src/com/learnopengles/android/lesson8/ErrorHandler.java +++ b/android/AndroidOpenGLESLessons/src/com/learnopengles/android/lesson8/ErrorHandler.java @@ -1,6 +1,5 @@ package com.learnopengles.android.lesson8; - interface ErrorHandler { enum ErrorType { BUFFER_CREATION_ERROR diff --git a/android/AndroidOpenGLESLessons/src/com/learnopengles/android/lesson8/LessonEightRenderer.java b/android/AndroidOpenGLESLessons/src/com/learnopengles/android/lesson8/LessonEightRenderer.java index fd9a895..0e9f6e3 100644 --- a/android/AndroidOpenGLESLessons/src/com/learnopengles/android/lesson8/LessonEightRenderer.java +++ b/android/AndroidOpenGLESLessons/src/com/learnopengles/android/lesson8/LessonEightRenderer.java @@ -309,13 +309,24 @@ class HeightMap { // Cheap normal using a derivative of the function. // The slope for X will be 2X, for Y will be 2Y. - final float xNormal = (-2 * xPosition) / 10f; - final float yNormal = (-2 * yPosition) / 10f; - final float length = Matrix.length(xNormal, yNormal, 1f); - - heightMapVertexData[offset++] = xNormal / length; - heightMapVertexData[offset++] = yNormal / length; - heightMapVertexData[offset++] = 1f / length; + // Divide by 10 since the position's Z is also divided by 10. + final float xSlope = (2 * xPosition) / 10f; + final float ySlope = (2 * yPosition) / 10f; + + // Calculate the normal using the cross product of the slope. + final float[] planeVectorX = {1f, 0f, xSlope}; + final float[] planeVectorY = {0f, 1f, ySlope}; + final float[] normalVector = { + (planeVectorX[1] * planeVectorY[2]) - (planeVectorX[2] * planeVectorY[1]), + (planeVectorX[2] * planeVectorY[0]) - (planeVectorX[0] * planeVectorY[2]), + (planeVectorX[0] * planeVectorY[1]) - (planeVectorX[1] * planeVectorY[0])}; + + // Normalize the normal + final float length = Matrix.length(normalVector[0], normalVector[1], normalVector[2]); + + heightMapVertexData[offset++] = normalVector[0] / length; + heightMapVertexData[offset++] = normalVector[1] / length; + heightMapVertexData[offset++] = normalVector[2] / length; // Add some fancy colors. heightMapVertexData[offset++] = xRatio;