35
OpenGL ES App 1 – Triangles and Transformation

OpenGL ES App 1 – Triangles and Transformation

  • Upload
    deron

  • View
    30

  • Download
    0

Embed Size (px)

DESCRIPTION

OpenGL ES App 1 – Triangles and Transformation. Goal. Learn some important functions and process in OpenGL ES Draw some triangles on the screen Do some transformation on each triangle in each frame so that the triangles will MOVE!!. Initialize and specify the view. - PowerPoint PPT Presentation

Citation preview

OpenGL ES

OpenGL ES App 1 Triangles and TransformationGoalLearn some important functions and process in OpenGL ESDraw some triangles on the screenDo some transformation on each triangle in each frame so that the triangles will MOVE!!Initialize and specify the viewonCreate: each time you run the program, this function must execute first/** Hold a reference to our GLSurfaceView */private GLSurfaceView mGLSurfaceView;

mGLSurfaceView = new GLSurfaceView(this);

GLSurfaceView manages OpenGL surfaces for us and draws it into the Android view system.Call constructor.Initialize and specify the viewCheck if system supports OpenGL ES 2.0final ActivityManager activityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();

After the above code, the OpenGL ES configuration information is in configurationInfo.reqGlEsVersionInitialize and specify the viewCheck if system supports OpenGL ES 2.0 final boolean supportsEs2 = true; //configurationInfo.reqGlEsVersion >= 0x20000;If you want to run the code in Android Emulator, you must let the code like above ( that is, let the check passes ), or the emulation would fails !!!Initialize and specify the viewIf it supports, set the context and the renderer.if (supportsEs2){// Request an OpenGL ES 2.0 compatible context.mGLSurfaceView.setEGLContextClientVersion(2);// Set the renderermGLSurfaceView.setRenderer(new LessonOneRenderer());}Initialize and specify the viewSome activity functions that can be definedprotected void onResume()//resume the saved dataprotected void onPause()//execute in idle mode, it will save the dataOpenGL ES Activity Life CycleActivity startsonCreate()onStart()onResume()Activity Is runningonRestart()onStop()Activitycomes to the foregroundActivitycomes to the foregroundUse navigatesback to the ActivityOther applicationsneed memoryShut downActivity onPause()Activityis invisibleNew Activityis startedProcess is killedonDestroy()The RendererLets start with triangles.

/** Store our model data in a float buffer. */private final FloatBuffer mTriangle1Vertices;private final FloatBuffer mTriangle2Vertices;private final FloatBuffer mTriangle3Vertices;In OpenGL ES 2.0, the vertices become a data that store in the buffer first, so declare the buffers for the triangles.The RendererIn constructor MyLessonOneRender()final float[] triangle1VerticesData = {// X, Y, Z,// R, G, B, A-0.5f, -0.25f, 0.0f,1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.25f, 0.0f,0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.559016994f, 0.0f,0.0f, 1.0f, 0.0f, 1.0f};Initialize the position and color of the vertices

GeometryPosition / vertex normals / vertex colors / texture coordinatesTopologyPrimitiveLines / triangles / surfaces / Geometry DataThe RendererIn constructor MyLessonOneRender()mTriangle1Vertices = ByteBuffer.allocateDirect(triangle1VerticesData.length * mBytesPerFloat) .order(ByteOrder.nativeOrder()).asFloatBuffer();mTriangle1Vertices.put(triangle1VerticesData).position(0);

We need to copy the data in another buffer which will be passed to OpenGL ES API.

We must convert our data into a FloatBuffer so that we can use it to hold floating-point data.The RendererSecond, the matrices for projecting the objects onto the view space.Three Matrices Model Matrix MView Matrix VProjection Matrix PPutting them together: P V M (model vertices)eyeView frustum13Model Matrix

Model MatrixThe object has its orientation. When you put the object in the scene.Model Matrix represents the transformation from object space to world space.Set Model Matrix in OpenGL ESCan use the Matrix helper class to help usMatrix.setIdentityM(mModelMatrix, 0);

Matrix.translateM(mModelMatrix, 0, 1.0f, 0.0f, 0.0f);Matrix.rotateM(mModelMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f);

long time = SystemClock.uptimeMillis() % 10000L; //system timefloat angleInDegrees = (360.0f / 10000.0f) * ((int) time); //varies based on time

Initialize the model matrixPerform simple rotationPerform simple translationView MatrixObject SpaceXZWorld SpaceZXCameraXZXZZXXZXZView SpaceApply model matrixApply view matrixView MatrixThe camera also has its spaceThe view matrix represent the transforms from world space to camera space.Set View Matrix in OpenGL ESprivate float[] mViewMatrix = new float[16];public void onSurfaceCreated(GL10 glUnused, EGLConfig config){Matrix.setLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);

Set View Matrix in OpenGL ESeyeX, eyeY, eyeZ: eye positionlookX, lookY, lookZ: look vectorupX, upY, upZ: up vector

Projection MatrixXZXZView SpaceXZXZProjection SpaceFar clipping planeNearclipping planeZ-axis direction: camera view direction22Camera3D ModelsLightsProjection PlaneBoardA 3D SceneProjection MatrixThe projection matrix specifies near and far view distance, angle of the view of the camera and the screen resolution proportion.Projection MatrixSet Projection Matrix in OpenGL ESMatrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);Combine the above matrix togetherprivate float[] mMVPMatrix = new float[16];//MVPMatrix = Model * View * Projection//( * means matrix multiplication)

The shadersIn openGL ES 2.0, you can define your own vertex shader and fragment shader!!!Vertex ShaderModify/create/ignore attributes of vertex, such as position, color, normal, texture coordinatesFragment(Pixel) ShaderPer-pixel lighting, allowing complex shading equation to be evaluated per pixel.The shadersShader coding process in OpenGL ESEdit the shadersLoad the shadersLink the shaders into a program

Simple vertex shaderfinal String vertexShader ="uniform mat4 u_MVPMatrix;\n

+ "attribute vec4 a_Position;\n+ "attribute vec4 a_Color;\n+ "varying vec4 v_Color;\n"+ "void main() \n"+ "{\n"+ " v_Color = a_Color; \n

+ " gl_Position = u_MVPMatrix\n"+ " * a_Position; \n"+ "} \n";The combined model/view/projection matrix.The final color that will be passed to fragment shader.Pass the color. Shader will help us do triangle interpolation.Multiply the vertex by the matrix to get the final point(gl_Position).Simple fragment shaderfinal String fragmentShader ="precision mediump float; \n+ "varying vec4 v_Color; \n"+ "void main() \n+ "{ \n"+ " gl_FragColor = v_Color; \n

+ "} \n";Pass the color through the pipeline.ShadersLoad the shadersint vertexShaderHandle = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);// Pass in the shader source.GLES20.glShaderSource(vertexShaderHandle, vertexShader);// Compile the shader.GLES20.glCompileShader(vertexShaderHandle);// Get the compilation status.final int[] compileStatus = new int[1];GLES20.glGetShaderiv(vertexShaderHandle, GLES20.GL_COMPILE_STATUS, compileStatus, 0);

ShadersLoad the shaders// If the compilation failed, delete the shader.if (compileStatus[0] == 0){GLES20.glDeleteShader(vertexShaderHandle);vertexShaderHandle = 0;}Similarly, we can load the fragment shaders.

ShadersLink the shaders into a programBefore we can use our vertex and fragment shader, we need to bind them together into a program.The process of link the shadersCreate a new program objectIf that succeeded, we then attach our shadersBind the attributes in the shader codeLink the programShadersLink the shaders into a programint programHandle = GLES20.glCreateProgram();// Bind the vertex shader to the program. GLES20.glAttachShader(programHandle, vertexShaderHandle);// Bind the fragment shader to the program. GLES20.glAttachShader(programHandle, fragmentShaderHandle);// Bind attributes GLES20.glBindAttribLocation(programHandle, 0, "a_Position"); GLES20.glBindAttribLocation(programHandle, 1, "a_Color");// Link the two shaders together into a program. GLES20.glLinkProgram(programHandle);ShadersAfter linking, we canPass data into the programmMVPMatrixHandle = GLES20.glGetUniformLocation(programHandle, "u_MVPMatrix");mPositionHandle = GLES20.glGetAttribLocation(programHandle, "a_Position");mColorHandle = GLES20.glGetAttribLocation(programHandle, "a_Color");Tell OpenGL to use this program for rendering.GLES20.glUseProgram(programHandle);Display triangle(s)In the example, we define drawTriangle function to handle the drawing part.The process of drawTriangle Pass in the position informationPass in the color informationPass in the final matrix to the vertex shader using GLES20.glUniformMatrix4fv().Converts the points into a triangle and draws it on the screen using GLES20.glDrawArrays().Display triangle(s)Can you draw a program to display more triangles?

ReferenceLearn OpenGL ES http://www.learnopengles.com/OpenGL Transformation http://www.songho.ca/opengl/gl_transform.htmlWorld, View and Projection Matrix Unveiled http://robertokoci.com/world-view-projection-matrix-unveiled/