当前位置:网站首页>OpenGL drawing simple triangles
OpenGL drawing simple triangles
2022-07-24 10:07:00 【Deciduous ex】
OpenGL Draw simple triangles
I was busy a while ago , I went to study something else , I just remembered recently , About OpenGL The practical application of has not been written , Make it up now .
Get ready
Whatever stay Android Environmental use OpenGL, First you need a GLSurfaceView example . The next step is roughly divided into two steps :
Set up OpenGL Version number , Usually use 2.0 Best compatibility , The specific version is different from Baidu .
glSurfaceView.setEGLContextClientVersion(2);Set up
Renderer.- seeing the name of a thing one thinks of its function Renderer For the renderer , Its essence is an interface , There are three methods, namely
onSurfaceCreated、onSurfaceChangedandonDrawFrame. be-all OpenGL The relevant operations of rendering and display need to be carried out in these methods , That is, the main body of the whole rendering process . - Rendering is divided into two modes according to the refresh logic , adopt
glSurfaceView.setRenderMode()Set up , NamelyRENDERMODE_WHEN_DIRTYandRENDERMODE_CONTINUOUSLY. The former is a reminder refresh , The latter is constantly refreshed , It's easy to understand , Simply speaking OpenGL Rendering is done by constantly calling onDrawFrame Method to refresh , When it comes toRENDERMODE_WHEN_DIRTYMode requires manual invocationglSurfaceView.requestRender()The next refresh will be performed when , And the other one will constantly refresh automatically . Considering performance , Usually choose the first refresh method .
- seeing the name of a thing one thinks of its function Renderer For the renderer , Its essence is an interface , There are three methods, namely
draw
Here, according to Renderer Three methods of interface , Divide the drawing into three steps .
onSurfaceCreated
The method will be in OpenGL Called after preparation , Will only be called once , Therefore, the parameters required for drawing need to be initialized here . take OpenGL The rendering of is compared to painting ,onSurfaceCreated Prepare paper for painting , Next, you need to trace the image at a fixed point , Then prepare the color of the painting .
Fixed point stroke
Any figure is made of
The verticesConnected by , stay OpenGL It's the same in China , First, you need to determine the position of the vertex , Because its coordinate axis is Cartesian coordinate and extremum by 1, Therefore, the floating-point typefloatFor storage .float triangleVertex[] = { 0f, 0.5f, 0.0f, // top -0.5f, -0.25f, 0.0f, // bottom left 0.5f, -0.25f, 0.0f // bottom right };After the coordinates are determined , In order to be able to transmit to OpenGL Use , It needs to be installed and replaced with something recognizable at the bottom Buffer object .
// To apply for space Because a float Occupy 4 Bytes ByteBuffer bb = ByteBuffer.allocateDirect(triangleVertex.length * 4); // Convert data types recognized by local memory bb.order(ByteOrder.nativeOrder()); // Convert coordinate data to FloatBuffer, To pass in to OpenGL mVertexBuffer = bb.asFloatBuffer(); mVertexBuffer.put(triangleVertex); mVertexBuffer.position(0);Prepare paint
When the outline has been determined , The next step is to color and fill it , We're going to introduce
Shaders. Those who don't understand the colorimeter can go to see it OpenGL Or read my previous blog posts . Shaders are divided intoVertex shaderandChip shader, After writing the Shader Language, create and get the corresponding shader handle .public static int uLoadShader(int shaderType, String source) { // Distribute Shader Handle int shader = GLES20.glCreateShader(shaderType); if (0 != shader) { // by Shader Binding source code GLES20.glShaderSource(shader, source); // compile GLES20.glCompileShader(shader); int[] compiled = new int[1]; // get Shader The compilation of GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0); if (compiled[0] == 0) { glError(1, "Could not compile shader:" + shaderType); glError(1, "GLES20 Error:" + GLES20.glGetShaderInfoLog(shader)); GLES20.glDeleteShader(shader); shader = 0; } } return shader; } // establish Shader int vertexShader = uLoadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode); int fragmentShader = uLoadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);Finally, create an empty
Programobject , And set the shader to the object .// Create an empty Program mProgram = GLES20.glCreateProgram(); // Set shader to program GLES20.glAttachShader(mProgram, vertexShader); GLES20.glAttachShader(mProgram, fragmentShader); // Connect to the program GLES20.glLinkProgram(mProgram);
onSurfaceChanged
This method is relatively simple , It will be called when the screen size changes , It is usually used to update and set the display size .
public void onSurfaceChanged(GL10 gl10, int width, int height) {
// Set view size
GLES20.glViewport(0, 0, width, height);
}onDrawFrame
similar View Of onDraw Method , The specific drawing is carried out here . Because this method is responsible for refreshing the dynamic graph , So the first step is usually to Clear the screen , Erase the last painting , And then use onSurfaceCreated Prepare parameters for specific painting .
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
// Add the program to OpenGLES2.0 Environmental Science
GLES20.glUseProgram(mProgram);
// Get the vPosition Member handle
int mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
// Get the vColor Handle to member
int mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
// Enable handle to triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle);
// Prepare coordinate data of triangle
GLES20.glVertexAttribPointer(mPositionHandle, COORS_PER_VERTEX,
GLES20.GL_FLOAT, false,
vertexStride, mVertexBuffer);
// Set the color of the triangle
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
// Draw triangle
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);
// Prohibit handles to vertex arrays
GLES20.glDisableVertexAttribArray(mPositionHandle);I have written the notes in great detail , Some people here may not understand that since shaders are already pigments , Then why is there a step to set paint in the code . That's because shaders are actually similar C Programming language , It also has its own constants and variables , The color set here is actually a color variable defined in our Shader Language . If you are interested, you can read what I wrote GLSL Related articles . Here are the specific shader languages :
private String vertexShaderCode =
"attribute vec4 vPosition;" +
"void main() {" +
" gl_Position = vPosition;" +
"}";
private String fragmentShaderCode =
"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
" gl_FragColor = vColor;" +
"}";private String vertexShaderCode =
"attribute vec4 vPosition;" +
"void main() {" +
" gl_Position = vPosition;" +
"}";
private String fragmentShaderCode =
"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
" gl_FragColor = vColor;" +
"}";Conclusion
The above is the specific process of drawing a simple graph , All of them are analyzed and elaborated according to my personal experience , If there is something wrong, please give me some advice .
边栏推荐
- Synchronized scope "concurrent programming"
- [STM32 learning] (15) STM32 realizes DHT11 temperature and humidity acquisition and display
- MySQL status view qps/tps/ cache hit rate view
- Color recognition of regions of interest in pictures and videos based on OpenCV
- 757. Set the intersection size to at least 2: greedy application question
- [STM32 learning] (5) press the key to control the flow light (interrupt Implementation)
- PHP Basics - PHP types
- 程序的编译与链接
- Dr. water 3
- Use of jstack "JVM common commands"
猜你喜欢
![[STM32 learning] (4) press the key to control the flow light](/img/2a/b26860e2c65c0790a60ac207bf52ec.png)
[STM32 learning] (4) press the key to control the flow light

程序的编译与链接

给你的网站加一个爱发电角标

Spark Learning: compile spark source code in win10

Analysis of Kube proxy IPVS mode
![[robot learning] mechanism kinematics analysis and MATLAB simulation (3D model +word report +matlab program)](/img/dd/d29a5be7306580ad388ba6487d230f.png)
[robot learning] mechanism kinematics analysis and MATLAB simulation (3D model +word report +matlab program)

What did zoneawareloadbalancer of ribbon and its parent class do?

Spark Learning: a form of association in a distributed environment?

What's the difference between testing / developing programmers' professionalism and salted fish? They don't want to be excellent coders?
![[STM32 learning] (6) use of serial port 1 (usart1)](/img/b1/430d3501a99e46958c066f7fd7eee9.png)
[STM32 learning] (6) use of serial port 1 (usart1)
随机推荐
【LeeCode】获取2个字符串的最长公共子串
2022: I feel like sleeping for the first time during the day
Redis configuration serialization
07 Jason module
缓冲区的概念真的理解么?带你揭开缓冲区的面纱~
note: expected ‘void * (***)(void ***)’ but argument is of type ‘void (*)(void *)’
Reading makes people improve my list
高精尖中心论文入选国际顶会ACL 2022,进一步拓展长安链隐私计算能力
Raspberry Pie: /bin/sh: 1: bison: not found
2022, enterprise informatization construction based on Unified Process Platform refers to thubierv0.1
[STM32 learning] (17) STM32 realizes LCD12864 display serial implementation
Selnium checks three conditions when it cannot locate an element
JS 84*148=b6a8 how many decimal places can you make both sides equal
给你的网站加一个爱发电角标
JS, the return statement used in the for loop should be placed in the function to terminate the loop, similar to the invalid return problem in break & foreach
Installation UMI tutorial (error reporting and solutions)
Application of for loop
AttributeError: module ‘sipbuild. api‘ has no attribute ‘prepare_ metadata_ for_ build_ wheel‘
Compilation and linking of programs
Where is the bitbucket clone address