Opengl basic learning topic (2) vertices, straight lines, and polygon

Source: Internet
Author: User

Opengl basic learning topic (2) vertices, straight lines, and polygon

Digress

As learning grows, I feel more and more confused. In the previous blog, we recommend that you use a simplec framework based on VS2015 to learn opengl.

Some problems.

1. The Release version is not considered in the VS Debug mode.

2. In this version, some Macros in the basic header files of chead and c are poorly designed, such

//4.0 console prints error message
#ifndef CERR
#define CERR (fmt, ...) \
fprintf (stderr, fmt, ## __ VA_ARGS __), putchar ('\ n')
# endif / *! CERR * /

//4.1 console prints error message and exits
#ifndef ERR_EXIT
#define ERR_EXIT (fmt, ...) \
CERR (fmt, ## __ VA_ARGS__), exit (EXIT_FAILURE)
# endif / *! ERR * /

What's more reasonable is that

// Error print macro
# Define CERR_EXIT (fmt ,...)\
Fprintf (stderr, "[% s: % d]", _ FILE __, _ LINE _), fprintf (stderr, fmt, ##__ VA_ARGS __), fputs ("\ r \ n", stderr)

The secondary macro here needs to be re-designed

3. The original SC _log module, a simple logging system, is applicable to the multi-thread mode of a single user. With the increase of projects, multiple users need to be supported. Reconstruction is required to enable the log record capability of massive users.

4. You need to add a Session module for multiple users.

5. Some internal modules need to be reconstructed, and the linked list structure should be replaced by the tree structure to increase the search rate.

We recommend that you learn about opengl and use simplec framework. We recommend that you do a good job in the next version. I am working too much overtime. I really don't want ......

Certificate --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Share a sad story of a programmer

One night, after dinner, two programmers met someone they shouldn't have met,

Comfort each other.

I am surprised to write code. Haha

Certificate --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Question

This course is about drawing simple ry. before actually drawing, let's get familiar with some concepts.

I. Points, straight lines, and polygon
We know the concepts of straight lines and polygon in Mathematics (specifically, ry), but these concepts are different in computers.
A mathematical point has only a position and no size. However, in a computer, no matter how accurate the computation is, it cannot represent an infinitely small point. On the other hand, no matter how accurate a graphic output device (such as a display) is, it cannot output an infinitely small point. In general, the points in OpenGL will be drawn into a single pixel (you can search for the pixel concept ~), Although it may be small enough, it is not infinitely small. On the same pixel, OpenGL can draw many coordinates with only slightly different points, but the specific color of the pixel will depend on OpenGL implementation. Of course, excessive attention to the details is the tip of the horn. We don't have to spend too much time studying "how to draw multiple points to the same pixel ".
Similarly, a mathematical straight line has no width, but an OpenGL straight line has width. At the same time, OpenGL's straight lines must be limited in length, rather than infinite in mathematics. It can be considered that OpenGL's "Straight Line" concept is close to the mathematical "line segment", which can be determined by two endpoints.
A polygon is a closed area formed by the combination of multiple line segments at the beginning and end. OpenGL specifies that a polygon must be a "Convex Polygon" (defined as: The line segments determined by any two points in the polygon are within the polygon, and thus can be derived, convex Polygon cannot be hollow ). A polygon can be determined by its edge endpoint (vertex. (Note: If the polygon used is not a convex polygon, the final output result is undefined-OpenGL relaxed the check for efficiency, which may lead to display errors. To avoid this error, use a triangle as much as possible, because all triangles are convex polygon)

As you can imagine, points, straight lines, and polygon can be combined into various geometric shapes. Even you can regard an arc as a link between many short straight line segments, which are short enough to have a length smaller than the width of one pixel. In this way, the arc and circle can also be expressed. Through a small polygon located on different planes, we can also form a "surface ".

Ii. Specify vertex in OpenGL
From the above discussion, we can know that "points" are the foundation of everything.
How to specify a vertex? OpenGL provides a series of functions. They all start with glVertex, followed by a number and 1 ~ 2 letters. For example:
GlVertex2d
GlVertex2f
GlVertex3f
GlVertex3fv
And so on.
A number indicates the number of parameters. 2 indicates two parameters. 3 indicates three parameters. 4 indicates four parameters ~).
Letters indicate the parameter type, and s indicates a 16-digit integer (OpenGL defines this type as GLshort ),
I Represents a 32-bit integer (OpenGL defines this type as GLint and GLsizei ),
F indicates a 32-bit floating point number (OpenGL defines this type as GLfloat and GLclampf ),
D indicates a 64-bit floating point number (OpenGL defines this type as GLdouble and GLclampd ).
V indicates that several parameters passed will use pointers. See the example below.
These functions have the same function except for the type and number of parameters. For example, the functions of the following five code segments are equivalent:
(1) glVertex2i (1, 3 );
(2) glVertex2f (1.0f, 3.0f );
(3) glVertex3f (1.0f, 3.0f, 0.0f );
(4) glVertex4f (1.0f, 3.0f, 0.0f, 1.0f );
(5) GLfloat VertexArr3 [] = {1.0f, 3.0f, 0.0f };
GlVertex3fv (VertexArr3 );
In the future, we will use glVertex * to represent this series of functions.
Note: many functions of OpenGL adopt this form. Adding parameter description marks to the same prefix will help you learn more.

Here, we can extend it here. In the current compiler, it is recommended that 5.f be equivalent to 5.0f. we recommend that you do not use these skills. For example, sometimes you may think that the C99/C11 style is good,

Sometimes I think the C89 style is the safest.

Example:

//C89
int hoge;
int piyo;

hoge = 16;
piyo = 1;
printf("hoge = %d, piyo = %d\n",hoge,piyo);


//C99 / C11

int hoge = 13;
printf("hoge = %d.\n",hoge);
int piyo = 5;
printf("heoo piyo is %d.\n",piyo);

Continue to the topic

3. start plotting
Assuming that I have already specified several vertices, how does OpenGL know what I want to do with these vertices? Is it drawn one by one or connected to a line? Or a polygon? Or what else?
To solve this problem, OpenGL requires that the command to specify the vertex must be included after the glBegin function and before the glEnd function (otherwise, the specified vertex will be ignored ). GlBegin is used to specify how to use these points.
For example, I write:
GlBegin (GL_POINTS );
GlVertex2f (0.0f, 0.0f );
GlVertex2f (0.5f, 0.0f );
GlEnd ();
The two points will be painted separately. If you replace GL_POINTS with GL_LINES, the two points will be considered as the two endpoints of a straight line, and OpenGL will draw a straight line.
We can also specify more vertices and draw more complex images.
In addition to GL_POINTS and GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLES, GL_TRIANGLE_STRIP, and GL_TRIANGLE_FAN.

The above two functions are summarized as follows:

Function prototype:
Void glBegin (GLenum mode );
Void glEnd (void );
Parameter description:
Mode: Type of the created element. It can be the following value
GL_POINTS: processes each vertex as a vertex. vertex n defines vertex n and draws N vertices in total.
GL_LINES: each vertex is used as an independent line segment. n lines are defined between the 2n-1 and 2n vertices, and N/2 lines are drawn in total.
GL_LINE_STRIP: Draw a group of line segments connected from the first vertex to the last vertex. The n and n + 1 vertices define the line segment n, and draw n-1 lines in total.
GL_LINE_LOOP: draws a group of line segments connected from the first vertex to the last vertex, and then connects the last vertex to the first vertex, the n and n + 1 vertices define the line n and draw n lines in total.
GL_TRIANGLES: each vertex is used as an independent triangle. The 3n-2, 3n-1, and 3n vertices define the nth triangle. n/3 triangles are drawn in total.
GL_TRIANGLE_STRIP: draws a group of connected triangles. n triangles are defined for odd n, vertex n, n + 1, and n + 2. For even n, vertex n + 1, n, and n + 2 define the nth triangle, drawing a total of N-2 triangles
GL_TRIANGLE_FAN: draws a group of connected triangles, which are determined by the first vertex and the vertex given after it. vertex 1, n + 1, and n + 2 define the n triangles, draw a total of N-2 triangles
GL_QUADS: draws a group of independent quadrilateral composed of four vertices. Vertex 4n-3, 4n-2, 4n-1, and 4n define the nth quadrilateral. Draw N/4 quadrilateral in total
GL_QUAD_STRIP: Draw a group of connected quadrilateral. Each quadrilateral is determined by a pair of vertices and a pair of vertices given afterwards. Vertex 2n-1, 2n, 2n + 2, and 2n + 1 Define the nth quadrilateral. n/2-1 Quadrilateral is drawn in total.
GL_POLYGON: draws a convex polygon. Vertices 1 to n define this polygon.

I am not going to make a big article on glBegin various methods. You can try to change the glBegin method and vertex position to generate interesting patterns.
Program code:

void display (void)
{
      glClear (GL_COLOR_BUFFER_BIT);
      glBegin (/ * Fill in the pattern you want * /);
         / * Use glVertex * functions here * /
         / * Specify your desired vertex position * /
      glEnd ();
      glFlush ();
}


Change this code to what you like and use it to replace the myDisplay function in the first lesson. Compile the code and run it.

Here are three examples:

First draw a circle, the idea is hitting, according to the Round parameter equation (r * cos t, r * sin t), t belongs to [0, 2 * Pi]

The Code is as follows:

#include <glut.h>
#define _USE_MATH_DEFINES // Enable the default constant macro in math.h
#include <math.h>

// Draw the number of vertices of the circle
#define _INT_N (20)
/ *
* Draw a circle here
* /
static void display (void)
{
     int i;
     GLdouble r = 0.5;

     glClear (GL_COLOR_BUFFER_BIT);

     glBegin (GL_POLYGON);
     for (i = 0; i <_INT_N; ++ i) {
         double p = 2 * M_PI * i / _INT_N;
         glVertex2d (r * cos (p), r * sin (p)); // connect the dots
     }
     glEnd ();

     glFlush ();
}

int main (int argc, char * argv [])
{
     glutInit (& argc, argv);

     // glut is initialized to rgb color mode, single buffer
     glutInitDisplayMode (GLUT_RGB | GLUT_SINGLE);

     // glut form creation
     glutInitWindowSize (500, 500);
     glutInitWindowPosition (123,456);
     glutCreateWindow ("Test the drawing of the circle here");

// Set the drawing function
     glutDisplayFunc (display);

     // glut form main loop
     glutMainLoop ();

     return 0;
}

I tried the above Code and basically understood it. Here I will talk about some nonsense, So that you need to set up the environment. After the environment is complete, the learning is completed by 1/3.

The Learning programming technology is summarized as follows:

Frontline operations => setting up the environment hello world + learning basic api + project => you can enter the combat mode.

Offline command => Design Philosophy + strength in solving pressure and emergency problems => leader

 

The second example is to draw a star

The instance diagram is as follows:


To draw this star, you need to calculate the location of each point on your own and require Junior High School ry knowledge. The Code is as follows:

#include <glut.h>
#define _USE_MATH_DEFINES // Enable the default constant macro in math.h
#include <math.h>

// Draw the number of vertices of the circle
#define _INT_N (20)

// Convert the angle value into radians
#define TO_F_PII (d) \
    (d * (float) M_PI / 180)

/ *
* Draw a pentagram here
* /
static void display (void)
{
    // 5x = 360 => x = 72 degrees, x / 2 = 36 degrees
    GLfloat a = 0.5f; // The default scale is half the current screen opengl coordinate system with the center of the screen as (0,0)
    // Calculate the ordinate from top to bottom as a, a * cos (72 degrees), -a * cos (36 degrees)
    // The calculated abscissa from left to right is -a * sin (72 degrees), -a * sin (36 degrees), 0, a * sin (36 degrees), a * sin (72 degrees)

    // A, B, C, D, E coordinates are as follows, you need to calculate the trigonometric function yourself
    GLfloat pii72 = TO_F_PII (72.f);
    GLfloat pii36 = TO_F_PII (36.f);
    GLfloat
        pointA [2] = {-a * sinf (pii72), a * cosf (pii72)},
        pointB [2] = {0.f, a},
        pointC [2] = {a * sinf (pii72), a * cosf (pii72)},
        pointD [2] = {a * sinf (pii36), -a * cosf (pii36)},
        pointE [2] = {-a * sinf (pii36), -a * cosf (pii36)};


    glClear (GL_COLOR_BUFFER_BIT);


    // Draw from A-> C-> E-> B-> D-> A in order
    glBegin (GL_LINE_LOOP);

    glVertex2fv (pointA);
    glVertex2fv (pointC);
    glVertex2fv (pointE);
    glVertex2fv (pointB);
    glVertex2fv (pointD);

    glEnd ();

    glFlush ();
}

Wuxing is still sacred, but it is polluted. Love your family and thank them for giving me life and everything.

The following is the last example to plot f (x) = sinx. This example is the simplest. A slight modification is made to extend the coordinate system. For details, refer to the following code.

#define _USE_MATH_DEFINES // Enable the default constant macro in math.h
#include <math.h>

// Draw trigonometric functions
static void display (void)
{
     GLfloat fz = 10.f, p;

     glClear (GL_COLOR_BUFFER_BIT);

     // Draw the coordinate system first
     glBegin (GL_LINES);
     glVertex2f (-1.f, 0.f);
     glVertex2f (1.f, 0.f);
     glVertex2f (0.f, 1.f);
     glVertex2f (0.f, -1.f);
     glEnd ();

     // Draw trigonometric functions
     glBegin (GL_LINE_STRIP);
     for (p = -fz; p <fz; p + = 0.01f)
         glVertex2f (p / fz, sinf (p) / fz);
     glEnd ();

     glFlush ();
} 

The second section about opengl basic learning is basically completed. The above example is very simple, but you need to think about it yourself. Here are some additional questions. Are there any readers curious about the above static learning.

This is to add multiple main files to a project and use the display naming function. because the static modified functions are only valid in the current file, the compilation of functions with the same name will not fail.

I still have a lot of knowledge about the static and extern keywords.

 

Finally, before writing a blog post, I really don't want to think about it ~ I read the hydrology and wrote it later, so I knew it was so difficult. I also successfully entered the pen and water industry. I would like to pay tribute to my colleagues who wrote blog posts.

I have done, written, and thought before I can know that some things are expensive and hard to be difficult.

(If you have any questions, please make a brick at any time and change it immediately)

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.