Lecture Series on Android Programming Lecturer: Prof.Luqun Li Teaching Assistants: Fengyou Sun, Haijun Yang, Ting.

Slides:



Advertisements
Similar presentations
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Advertisements

Android basics. About Android Linux based operating system Open source Designed for handheld devices Developed by Android Inc. Google (2005) Open Handset.
Applets Graphical Java programs Run inside web browser Platform-neutral Easy deployment--loads when needed Secure.
Graphics Pipeline.
CS 4363/6353 BASIC RENDERING. THE GRAPHICS PIPELINE OVERVIEW Vertex Processing Coordinate transformations Compute color for each vertex Clipping and Primitive.
Animation and Input CSCI Day Six. Animation Basic Steps to Draw Something: var vertices = [ … ]; var BufferId = gl.CreateBuffer(); gl.bindBuffer.
Building Apps with Graphics & Animation. Displaying Bitmaps Efficiently Loading Large Bitmaps Efficiently Caching Bitmaps Managing Bitmap Memory Displaying.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
CS378 - Mobile Computing 3D Graphics.
 The success of GL lead to OpenGL (1992), a platform-independent API that was  Easy to use  Close enough to the hardware to get excellent performance.
MAT 594CM S2010Fundamentals of Spatial ComputingAngus Forbes Overview Today: - Make sure everyone is set up with an OpenGL environment - OpenGL basics:
Cosc 5/4730 OpenGL ES An introduction. OpenGL ES GL was first developed by SGI as a priority graphics language – OpenGL was developed initially by SGI.
GLSL I May 28, 2007 (Adapted from Ed Angel’s lecture slides)
GLSL I Ed Angel Professor of Computer Science, Electrical and Computer Engineering, and Media Arts Director, Arts Technology Center University of New Mexico.
Mohan Sridharan Based on slides created by Edward Angel GLSL I 1 CS4395: Computer Graphics.
Computer Science – Game DesignUC Santa Cruz Adapted from Jim Whitehead’s slides Shaders Feb 18, 2011 Creative Commons Attribution 3.0 (Except copyrighted.
Michael Robertson Yuta Takayama. WebGL is OpenGL on a web browser. OpenGL is a low-level 3D graphics API Basically, WebGL is a 3D graphics API that generates.
Programming Concepts. Derive a new class from Activity of the framework Prepare the data beforehand, e.g., vertices, colours, normal vectors, texture.
Geometric Objects and Transformations. Coordinate systems rial.html.
Programming with OpenGL Part 2: Complete Programs Ed Angel Professor of Emeritus of Computer Science University of New Mexico.
Programming with OpenGL Part 2: Complete Programs Ed Angel Professor of Emeritus of Computer Science University of New Mexico.
CS 418: Interactive Computer Graphics Introduction to WebGL: HelloTriangle.html Eric Shaffer.
OpenGL Shading Language (Advanced Computer Graphics) Ernest Tatum.
WebGL: in-browser 3D graphics Nick Whitelegg Maritme and Technology Faculty Southampton Solent University.
CS 4363/6353 TEXTURE MAPPING PART II. WHAT WE KNOW We can open image files for reading We can load them into texture buffers We can link that texture.
tiled Map Case Study: Rendering with JPanel © Allan C. Milne v
Introduction to XNA Graphics Programming Asst. Prof. Rujchai Ung-arunyawee COE, KKU.
1 Graphics CSCI 343, Fall 2015 Lecture 4 More on WebGL.
به نام خدا تنظیم کننده : فرانه حدادی استاد : مهندس زمانیان تابستان 92.
Lecture 6: 3D graphics Concepts 1  Principles of Interactive Graphics  CMSCD2012  Dr David England, Room 718,  ex 2271 
GRAPHICS PIPELINE & SHADERS SET09115 Intro to Graphics Programming.
Control flow for interactive applications CSE 3541 Matt Boggus.
1 Introduction to Computer Graphics with WebGL Ed Angel Professor Emeritus of Computer Science Founding Director, Arts, Research, Technology and Science.
CSE 381 – Advanced Game Programming GLSL. Rendering Revisited.
1 Graphics CSCI 343, Fall 2015 Lecture 6 Viewing, Animation, User Interface.
OpenGL-ES 3.0 And Beyond Boston Photo credit :Johnson Cameraface OpenGL Basics.
1 Graphics CSCI 343, Fall 2015 Lecture 5 Color in WebGL.
1 OGRE Programming Intermediate Tutorial: Volume Selection.
Week 3 Lecture 4: Part 2: GLSL I Based on Interactive Computer Graphics (Angel) - Chapter 9.
CS378 - Mobile Computing 3D Graphics.
A UGMENTED F UTURE OF M OBILE R EALITY Oleg Novosad Mobile / Web / Game Engineer.
 Learn how you can use the shader through OpenGL ES  Add texture on object and make the object have a different look!!
 Learn some important functions and process in OpenGL ES  Draw some triangles on the screen  Do some transformation on each triangle in each frame.
What are shaders? In the field of computer graphics, a shader is a computer program that runs on the graphics processing unit(GPU) and is used to do shading.
OpenGL Shading Language
3D Objects in WebGL Loading 3D model files. Announcement Midterm exam on 12/2 –No Internet connection. –Example code and exam questions will be on USB.
Programming with OpenGL Part 3: Shaders Ed Angel Professor of Emeritus of Computer Science University of New Mexico 1 E. Angel and D. Shreiner: Interactive.
GLSL I.  Fixed vs. Programmable  HW fixed function pipeline ▪ Faster ▪ Limited  New programmable hardware ▪ Many effects become possible. ▪ Global.
Advanced Texture Mapping Bump Mapping & Environment Mapping (Reflection)
Mobile & Casual Gaming OpenGL ES Intro. /red/chapter03.html.
Computer Science – Game DesignUC Santa Cruz Tile Engine.
COMP 175 | COMPUTER GRAPHICS Remco Chang1/XX13 – GLSL Lecture 13: OpenGL Shading Language (GLSL) COMP 175: Computer Graphics April 12, 2016.
Pushin’ Geo to the GPU As well as colors, normals, and other vertex data Made by Jeff Chastine, Modified by Chao Mei Jeff Chastine.
Google VR (gvr) CardBoard and DayDream With OpenGL
Shaders, part 2 alexandri zavodny.
The Basics: HTML5, Drawing, and Source Code Organization
Introduction to Computer Graphics with WebGL
GLSL I Ed Angel Professor of Computer Science, Electrical and Computer Engineering, and Media Arts Director, Arts Technology Center University of New Mexico.
Introduction to Computer Graphics with WebGL
Day 05 Shader Basics.
Programming 3D Graphics
Chapter VI OpenGL ES and Shader
Lecture 13 Clipping & Scan Conversion
Programming with OpenGL Part 3: Shaders
Mickaël Sereno Shaders Mickaël Sereno 25/04/2019 Mickaël Sereno -
CIS 441/541: Introduction to Computer Graphics Lecture 15: shaders
CS 480/680 Computer Graphics GLSL Overview.
Language Definitions Chap. 3 of Orange Book.
Introduction to Computer Graphics with WebGL
CS 480/680 Fall 2011 Dr. Frederick C Harris, Jr. Computer Graphics
Presentation transcript:

Lecture Series on Android Programming Lecturer: Prof.Luqun Li Teaching Assistants: Fengyou Sun, Haijun Yang, Ting Sun Chapter 10 Programming 3D Graphics with OpenGL

Shanghai Normal University 2 Contents 2 2 Defining Shapes 3 3 Drawing Shapes 4 4 Applying Projection and Camera Views 5 5 Adding Motion 1 1 Building an OpenGL ES Environment 6 6 Responding to Touch Events

Shanghai Normal University 3 Building an OpenGL ES Environment Implement a GLSurfaceView and a GLS urfaceView.Renderer GLSurfaceView is a view container fo r graphics drawn with OpenGL GLSurfaceView.Renderer controls wh at is drawn within that view GLSurfaceView is for a full-screen or near-full scre en graphics view TextureView is used to incorporate OpenGL ES gra phics in a small portion of their layouts

Shanghai Normal University 4 Declare in the Manifest To use the OpenGL ES 2.0 API : If your application uses texture com pression :

Shanghai Normal University 5 Create an Activity Android applications that use Open GL ES have activities just like any o ther application that has a user inte rface. A minimal implementation of an acti vity that uses a GLSurfaceView

Shanghai Normal University 6 Create an Activity public class OpenGLES20 extends Activity { private GLSurfaceView public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create a GLSurfaceView instance and set it // as the ContentView for this Activity. mGLView = new MyGLSurfaceView(this); setContentView(mGLView); }

Shanghai Normal University 7 Build a GLSurfaceView Object A GLSurfaceView is a specialized v iew where you can draw OpenGL ES graphics. The actual drawing of objects is con trolled in the GLSurfaceView.Ren derer that you set on this view.

Shanghai Normal University 8 Build a GLSurfaceView Object class MyGLSurfaceView extends GL SurfaceView { public MyGLSurfaceView(Context co ntext){ super(context); // Set the Renderer for drawing on the // GLSurfaceView setRenderer(new MyRenderer()); }

Shanghai Normal University 9 Build a GLSurfaceView Object // Create an OpenGL ES 2.0 context setEGLContextClientVersion(2); // Render the view only when there is a //change in the drawing data setRenderMode(GLSurfaceView.REN DERMODE_WHEN_DIRTY);

Shanghai Normal University 10 Build a Renderer Class Three methods in a renderer called by th e Android system : onSurfaceCreated() - Called once to se t up the view's OpenGL ES environment. onDrawFrame() - Called for each redra w of the view. onSurfaceChanged() - Called if the geo metry of the view changes, for example when the device's screen orientation cha nges.

Shanghai Normal University 11 Build a Renderer Class public class MyGL20Renderer implements GLSurfaceView. Renderer { public void onSurfaceCreated(GL10 unused, EGLConfig co nfig) { // Set the background frame color GLES20.glClearColor(0.5f, 0.5f, 0.5f, 1.0f); } public void onDrawFrame(GL10 unused) { // Redraw background color GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); } public void onSurfaceChanged(GL10 unused, int width, int height) { GLES20.glViewport(0, 0, width, height); }

Shanghai Normal University 12 Contents 2 2 Defining Shapes 3 3 Drawing Shapes 4 4 Applying Projection and Camera Views 5 5 Adding Motion 1 1 Building an OpenGL ES Environment 6 6 Responding to Touch Events

Shanghai Normal University 13 OpenGL coordinate system OpenGL assumes a square, uniform coordinate system and, by default, happily draws those coordinates ont o your typically non-square screen a s if it is perfectly square. To solve this problem, you can appl y OpenGL projection modes and ca mera views to transform coordinate s so your graphic objects have the c orrect proportions on any display.

Shanghai Normal University 14 OpenGL coordinate system Default OpenGL coordinate system (left) mapped to a typical Android d evice screen (right)

Shanghai Normal University 15 Define a Triangle OpenGL ES allows you to define dra wn objects using coordinates in thre e-dimensional space. So, before you can draw a triangle, you must defin e its coordinates. Define a vertex array of floating point numbe rs for the coordinates Write these coordinates into a ByteBuffer

Shanghai Normal University 16 Define a Triangle class Triangle { private FloatBuffer vertexBuffer; // number of c oordinates per vertex in this array static final int COORDS_PER_VERTEX = 3; static float triangleCoords[] = { // in counterclockwise order: 0.0f, f, 0.0f, // top -0.5f, f, 0.0f, // bottom left 0.5f, f, 0.0f // bottom right }; // Set color with red, green, blue and alpha // (opacity) values float color[] = { f, f, f, 1.0f };

Shanghai Normal University 17 Define a Triangle public Triangle() { // initialize vertex byte buffer for shape coordinates ByteBuffer bb = ByteBuffer.allocateDirect( // (number of coordinate values * 4 bytes per float) triangleCoords.length * 4); // use the device hardware's native byte order bb.order(ByteOrder.nativeOrder()); // create a floating point buffer from the ByteBuffer vertexBuffer = bb.asFloatBuffer(); // add the coordinates to the FloatBuffer vertex Buffer.put(triangleCoords); // set the buffer to read the first coordinate vertexBuffer.position(0); }

Shanghai Normal University 18 Define a Square Define the vertices in a counterclock wise order for both triangles that re present this shape, and put the valu es in a ByteBuffer. Use a drawing list to avoid defining the two coordinates shared by each triangle twice

Shanghai Normal University 19 Define a Square class Square { private FloatBuffer vertexBuffer; private ShortBuffer drawListBuffer; //number of coordinates per vertex in this array static final int COORDS_PER_VERTEX = 3; static float squareCoords[] = { -0.5f, 0.5f, 0.0f, // top left -0.5f, -0.5f, 0.0f, // bottom left 0.5f, -0.5f, 0.0f, // bottom right 0.5f, 0.5f, 0.0f }; // top right private short drawOrder[] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices

Shanghai Normal University 20 Define a Square public Square() { // initialize vertex byte buffer for shape coordinates ByteBuffer bb = ByteBuffer.allocateDirect( // (# of coordinate values * 4 bytes per float) squareCoords.length * 4); bb.order(ByteOrder.nativeOrder()); vertexBuffer = bb.asFloatBuffer(); vertexBuffer.put(squareCoords); vertexBuffer.position(0); // initialize byte buffer for the draw list ByteBuffer dlb = ByteBuffer.allocateDirect( // (# of coordinate values * 2 bytes per short) drawOrder.length * 2); dlb.order(ByteOrder.nativeOrder()); drawListBuffer = dlb.asShortBuffer(); drawListBuffer.put(drawOrder); drawListBuffer.position(0); }

Shanghai Normal University 21 Contents 2 2 Defining Shapes 3 3 Drawing Shapes 4 4 Applying Projection and Camera Views 5 5 Adding Motion 1 1 Building an OpenGL ES Environment 6 6 Responding to Touch Events

Shanghai Normal University 22 Initialize Shapes Initialize and load the shapes in the onSurfa ceCreated() public void onSurfaceCreated(GL10 unused, EGLConfig config) {... // initialize a triangle mTriangle = new Triangle(); // initialize a square mSquare = new Square(); }

Shanghai Normal University 23 Draw a Shape You must define the following: Vertex Shader - OpenGL ES graphics code f or rendering the vertices of a shape. Fragment Shader - OpenGL ES code for ren dering the face of a shape with colors or text ures. Program - An OpenGL ES object that contai ns the shaders you want to use for drawing one or more shapes.

Shanghai Normal University 24 Draw a Shape Define basic shaders private final String vertexShaderCode = "attribute vec4 vPosition;" + "void main() {" + " gl_Position = vPosition;" + "}"; private final String fragmentShaderCode = "precision mediump float;" + "uniform vec4 vColor;" + "void main() {" + " gl_FragColor = vColor;" + "}";

Shanghai Normal University 25 Draw a Shape Compile OpenGL Shading Language (GLSL) code public static int loadShader(int type, String shad erCode){ // create a vertex shader type //(GLES20.GL_VERTEX_SHADER) // or a fragment shader type //(GLES20.GL_FRAGMENT_SHADER) int shader = GLES20.glCreateShader(type); // add the source code to the shader and compil e it GLES20.glShaderSource(shader, shaderCode); GLES20.glCompileShader(shader); return shader; }

Shanghai Normal University 26 Draw a Shape In order to draw your shape, you must compile the shader code, add them to a OpenGL ES program object and then link the program.

Shanghai Normal University 27 Draw a Shape public Triangle() {... int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSh aderCode); int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fra gmentShaderCode); // create empty OpenGL ES Program mProgram = GLES20.glCreateProgram(); // add the vertex shader to program GLES20.glAttachShader(mProgram, vertexShader); // add the fragment shader to program GLES20.glAttachShader(mProgram, fragmentShader); // creates OpenGL ES program executables GLES20.glLinkProgram(mProgram); }

Shanghai Normal University 28 Draw a Shape Drawing shapes with OpenGL ES re quires that you specify several para meters to tell the rendering pipeline what you want to draw and how to draw it. Since drawing options can vary by s hape, it's a good idea to have your shape classes contain their own dra wing logic.

Shanghai Normal University 29 Draw a Shape public void draw() { // Add program to OpenGL ES environment GLES20.glUseProgram(mProgram); // get handle to vertex shader's vPosition memb er mPositionHandle = GLES20.glGetAttribLocation (mProgram, "vPosition"); // Enable a handle to the triangle vertices GLES20.glEnableVertexAttribArray(mPositionHa ndle); // Prepare the triangle coordinate data GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, fals e, vertexStride, vertexBuffer);

Shanghai Normal University 30 Draw a Shape // get handle to fragment shader's vColor mem ber mColorHandle = GLES20.glGetUniformLocation (mProgram, "vColor"); // Set color for drawing the triangle GLES20.glUniform4fv(mColorHandle, 1, color, 0); // Draw the triangle GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount); // Disable vertex array GLES20.glDisableVertexAttribArray(mPositionHa ndle); }

Shanghai Normal University 31 Draw a Shape Call draw() from within your rende rer’s onDrawFrame() method

Shanghai Normal University 32 Contents 2 2 Defining Shapes 3 3 Drawing Shapes 4 4 Applying Projection and Camera Views 5 5 Adding Motion 1 1 Building an OpenGL ES Environment 6 6 Responding to Touch Events

Shanghai Normal University 33 Applying Projection and Camera Views Projection - This transformation adj usts the coordinates of drawn objec ts based on the width and height of the GLSurfaceView where they ar e displayed. Camera View - This transformation adjusts the coordinates of drawn ob jects based on a virtual camera posi tion.

Shanghai Normal University 34 Define a public void onSurfaceChanged(GL10 unu sed, int width, int height) { GLES20.glViewport(0, 0, width, height); float ratio = (float) width / height; // this projection matrix is applied to obj ect coordinates // in the onDrawFrame() method Matrix.frustumM(mProjMatrix, 0, -ratio, r atio, -1, 1, 3, 7); }

Shanghai Normal University 35 Define a Camera public void onDrawFrame(GL10 unused) {... // Set the camera position (View matrix) Matrix.setLookAtM(mVMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f); // Calculate the projection and view transformat ion Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0); // Draw shape mTriangle.draw(mMVPMatrix); }

Shanghai Normal University 36 Apply Projection and Camera public void draw(float[] mvpMatrix) { // pass in the calculated transformation matrix... // get handle to shape's transformation matrix mMVPMatrixHandle = GLES20.glGetUniformLoca tion(mProgram, "uMVPMatrix"); // Apply the projection and view transformation GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0); // Draw the triangle GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);... }

Shanghai Normal University 37 Triangle Transformed Triangle drawn with a projection an d camera view applied.

Shanghai Normal University 38 Contents 2 2 Defining Shapes 3 3 Drawing Shapes 4 4 Applying Projection and Camera Views 5 5 Adding Motion 1 1 Building an OpenGL ES Environment 6 6 Responding to Touch Events

Shanghai Normal University 39 Adding Motion OpenGL ES provides additional capa bilities for moving and transforming drawn objects in three dimensions o r in other unique ways to create co mpelling user experiences.

Shanghai Normal University 40 Rotate a Shape private float[] mRotationMatrix = new float[16]; public void onDrawFrame(GL10 gl) {... // Create a rotation transformation for the triangle long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0 f); // Combine the rotation matrix with the projection and ca mera view Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, m MVPMatrix, 0); // Draw triangle mTriangle.draw(mMVPMatrix); }

Shanghai Normal University 41 Enable Continuous Rendering public MyGLSurfaceView(Context context) {... // Render the view only when there is a c hange in the drawing data //setRenderMode(GLSurfaceView.RENDE RMODE_WHEN_DIRTY); // comment out for auto-rotation } Unless you have objects changing without any user interaction, it’s usually a good idea have this flag tur ned on.

Shanghai Normal University 42 Contents 2 2 Defining Shapes 3 3 Drawing Shapes 4 4 Applying Projection and Camera Views 5 5 Adding Motion 1 1 Building an OpenGL ES Environment 6 6 Responding to Touch Events

Shanghai Normal University 43 Responding to Touch Events The key to making your OpenGL ES application touch interactive is expa nding your implementation of GLSu rfaceView to override the onTouc hEvent() to listen for touch events.

Shanghai Normal University 44 Setup a Touch public boolean onTouchEvent(MotionEvent e) { // MotionEvent reports input details from the to uch screen // and other input controls. In this case, you are only // interested in events where the touch position changed. float x = e.getX(); float y = e.getY(); switch (e.getAction()) { case MotionEvent.ACTION_MOVE: float dx = x - mPreviousX; float dy = y - mPreviousY;

Shanghai Normal University 45 Setup a Touch Listener // reverse direction of rotation above the mid-line if (y > getHeight() / 2) { dx = dx * -1 ; } // reverse direction of rotation to left of the mid-line if (x < getWidth() / 2) { dy = dy * -1 ; } mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACT OR; // = 180.0f / 320 requestRender(); } mPreviousX = x; mPreviousY = y; return true; }

Shanghai Normal University 46 Set Render Mode public MyGLSurfaceView(Context co ntext) {... // Render the view only when there is a change in the drawing data setRenderMode(GLSurfaceView. RENDERMODE_WHEN_DIRTY); }

Shanghai Normal University 47 Expose the Rotation Angle Add a public member and declare th is public variable as volatile public class MyGLRenderer impl ements GLSurfaceView.Rendere r {... public volatile float mAngle;

Shanghai Normal University 48 Apply Rotation public void onDrawFrame(GL10 gl) {... // Create a rotation for the triangle // long time = SystemClock.uptimeMillis() % 4000L; // float angle = 0.090f * ((int) time); Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f); // Combine the rotation matrix with the projection and ca mera view Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, m MVPMatrix, 0); // Draw triangle mTriangle.draw(mMVPMatrix); }

Shanghai Normal University 49 Responding to Touch Events Triangle being rotated with touch in put

Shanghai Normal University 50 Summary This class walks you through the basics o f developing applications that use OpenG L, including setup, drawing objects, movi ng drawn elements and responding to to uch input. The example code in this class uses the OpenGL ES 2.0 APIs, which is the recom mended API version to use with current Android devices. For more information ab out versions of OpenGL ES, see the Open GL developer guide.