본문 바로가기

실시간 운영체제

[실시간 운영체제] Computer Graphics (Draw circle)

 

Open GL의 기본적인 코드는

https://developer.android.com/develop/ui/views/graphics/opengl

위 사이트에 공개된 코드를 사용하였다.

 


MainActivity.java

package com.example.draw_circle;

import androidx.appcompat.app.AppCompatActivity;

import android.opengl.GLSurfaceView;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private GLSurfaceView gLView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Create a GLSurfaceView instance and set it
        // as the ContentView for this Activity.
        gLView = new MyGLSurfaceView(this);
        setContentView(gLView);
    }
}

 

 

MyGLSurfaceView.java

package com.example.draw_circle;

import android.content.Context;
import android.opengl.GLSurfaceView;

class MyGLSurfaceView extends GLSurfaceView {

    private final MyGLRenderer renderer;

    public MyGLSurfaceView(Context context){
        super(context);

        // Create an OpenGL ES 2.0 context
        setEGLContextClientVersion(2);

        renderer = new MyGLRenderer();

        // Set the Renderer for drawing on the GLSurfaceView
        setRenderer(renderer);
    }
}

 

 

MyGLRenderer.java

package com.example.draw_circle;


import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;

public class MyGLRenderer implements GLSurfaceView.Renderer {

    // vPMatrix is an abbreviation for "Model View Projection Matrix"
    private final float[] vPMatrix = new float[16];
    private final float[] projectionMatrix = new float[16];
    private final float[] viewMatrix = new float[16];

    private circle mCircle;

    public void onSurfaceCreated(GL10 unused, EGLConfig config) {
        // Set the background frame color
        GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

        mCircle = new circle();
    }

    public void onDrawFrame(GL10 unused) {
        // Redraw background color
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

        // Set the camera position (View matrix)
        Matrix.setLookAtM(viewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

        // Calculate the projection and view transformation
        Matrix.multiplyMM(vPMatrix, 0, projectionMatrix, 0, viewMatrix, 0);

        mCircle.draw(vPMatrix);
    }

    public void onSurfaceChanged(GL10 unused, int width, int height) {
        GLES20.glViewport(0, 0, width, height);

        float ratio = (float) width / height;

        // this projection matrix is applied to object coordinates
        // in the onDrawFrame() method
        Matrix.frustumM(projectionMatrix, 0, ratio, -ratio, -1, 1, 3, 7);

    }

    public static int loadShader(int type, String shaderCode){

        // 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 compile it
        GLES20.glShaderSource(shader, shaderCode);
        GLES20.glCompileShader(shader);

        return shader;
    }
}

 

 

circle.java

package com.example.draw_circle;


import android.opengl.GLES20;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

public class circle {

    private final String vertexShaderCode =
            // This matrix member variable provides a hook to manipulate
            // the coordinates of the objects that use this vertex shader
            "uniform mat4 uMVPMatrix;" +
                    "attribute vec4 vPosition;" +
                    "void main() {" +
                    // the matrix must be included as a modifier of gl_Position
                    // Note that the uMVPMatrix factor *must be first* in order
                    // for the matrix multiplication product to be correct.
                    "  gl_Position = uMVPMatrix * vPosition;" +
                    "}";

    // Use to access and set the view transformation
    private int vPMatrixHandle;

    private FloatBuffer vertexBuffer;

    private final int mProgram;

    private int positionHandle;
    private int colorHandle;

    private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex

    // number of coordinates per vertex in this array
    static final int COORDS_PER_VERTEX = 3;

    private static final int vertexCount=100;

    static float circle_coordinate[] = new float[vertexCount*COORDS_PER_VERTEX]; //원을 그리기 위해 이 부분을 바꿔준다

    // Set color with red, green, blue and alpha (opacity) values
    float color[] = { 0.63671875f, 0.76953125f, 0.22265625f, 1.0f };

    float color_red[] = { 1.0f, 0f, 0f, 1.0f };

    public circle() {

        //set vertexes for circle
        float R = 0.3f; //반지름
        float r=0.3f; // 타원으로 하고싶을때 x축의 반지름 값 바꿔주면 됨

        float circle_center_x = 0.0f; //원의 중심점 바꿀 수 있게 해줌
        float circle_center_y = 0.0f;

        circle_coordinate[0] = circle_center_x; //v0 : x=0 원의 중심점(0,0,0)
        circle_coordinate[1] = circle_center_y; //v0 : y=0
        circle_coordinate[2] = 0.0f; //v0 : z=0

        //make a loop to compute circle vertexes
        float d_angle = (float)Math.PI/24;

        int index = 3;

        //돌아가면서 삼각형의 좌표를 계속 생성해줌
        for (float angle = 0.0f;angle<=2*Math.PI+d_angle;angle=angle+d_angle){ //축 안바꾸고 그냥 일직선

        //for (float angle = (float)Math.PI/4;angle<=5*Math.PI/4+d_angle;angle=angle+d_angle){ //원의 축을 바꿔주는거

            circle_coordinate[index] = circle_center_x+r*(float)Math.cos(angle); //x=R*cos(angle) 타원일떄
            //circle_coordinate[index] = circle_center_x+R*(float)Math.cos(angle);
            circle_coordinate[index+1] = circle_center_y+R*(float)Math.sin(angle); //x=R*cos(angle)
            circle_coordinate[index+2] = 0.0f; //x=R*cos(angle)

            index = index+3;
        }

        // initialize vertex byte buffer for shape coordinates
        ByteBuffer bb = ByteBuffer.allocateDirect(
                // (number of coordinate values * 4 bytes per float)
                circle_coordinate.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
        vertexBuffer.put(circle_coordinate);
        // set the buffer to read the first coordinate
        vertexBuffer.position(0);



        int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER,
                vertexShaderCode);
        int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER,
                fragmentShaderCode);

        // 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);
    }

    public void draw(float[] mvpMatrix) {

        // get handle to shape's transformation matrix
        vPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");

        // Pass the projection and view transformation to the shader
        GLES20.glUniformMatrix4fv(vPMatrixHandle, 1, false, mvpMatrix, 0);

        // Add program to OpenGL ES environment
        GLES20.glUseProgram(mProgram);

        // get handle to vertex shader's vPosition member
        positionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");

        // Enable a handle to the circle vertices
        GLES20.glEnableVertexAttribArray(positionHandle);



        // Prepare the circle coordinate data
        GLES20.glVertexAttribPointer(positionHandle, COORDS_PER_VERTEX,
                GLES20.GL_FLOAT, false,
                vertexStride, vertexBuffer);

        // get handle to fragment shader's vColor member
        colorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");

        // Set color for drawing the circle
        GLES20.glUniform4fv(colorHandle, 1, color_red, 0);

        // Draw the triangle
        //GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3); //처음 3개의 점만 이어 삼각형 하나 만듬
        //GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, 4); //0,1,2 / 0,2,3 두개의 삼각형이 만들어짐

        //50이면 원
        //26이면 반원
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, 50);


        // Disable vertex array
        GLES20.glDisableVertexAttribArray(positionHandle);
    }

    private final String fragmentShaderCode =
            "precision mediump float;" +
                    "uniform vec4 vColor;" +
                    "void main() {" +
                    "  gl_FragColor = vColor;" +
                    "}";
}

 

 

이와 같은 그림처럼 원을 그리기 위해서는 p0, p1, p2 3개의 점으로 이루어진 아주 작은 삼각형을 무수히 만들어야한다.

 

for (float angle = 0.0f;angle<=2*Math.PI+d_angle;angle=angle+d_angle){ //축 안바꾸고 그냥 일직선

//for (float angle = (float)Math.PI/4;angle<=5*Math.PI/4+d_angle;angle=angle+d_angle){ //원의 축을 바꿔주는거

    circle_coordinate[index] = circle_center_x+r*(float)Math.cos(angle); //x=R*cos(angle) 타원일떄
    //circle_coordinate[index] = circle_center_x+R*(float)Math.cos(angle);
    circle_coordinate[index+1] = circle_center_y+R*(float)Math.sin(angle); //x=R*cos(angle)
    circle_coordinate[index+2] = 0.0f; //x=R*cos(angle)

    index = index+3;
}

위와 같이 일정 각도를 회전하며 좌표를 생성하는 코드를 작성하였다. 

 

또한 축 변경도 가능하다.

 

//50이면 원
//26이면 반원
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, 50);

무수히 생성된 50개의 좌표를 이용하게 되면 원

26개의 좌표를 이용하면 반원이 그려지는 것을 확인할 수 있다.

 

//set vertexes for circle
float R = 0.3f; //반지름
float r=0.3f; // 타원으로 하고싶을때 x축의 반지름 값 바꿔주면 됨

r의 값을 조절해 타원 또한 그릴 수 있다.