Introduction to Computer Graphics

규규·2024년 5월 2일

그래픽스

목록 보기
1/3

Introduction to Computer Graphics

1. Introduction

1.1 Painting and Drawing

  • Image 는 pixel 로 구성 됨. RGB 가 있고 grayscale 이 있음.
  • pixel 의 color 값은 frame buffer 라는 large block of memory 에 저장 됨. Screen 의 color 값 변경은 frame buffer 값 변경으로 이루어 짐.
  • raster graphics : computer screen 의 basic model. pixel RGB 의 값을 electron beam 으로 조절
  • vector graphics : basic (primitive) geometric object 로 이미지를 표현. geometric shape 는 attributes 를 가짐 (thickness, color). vector graphics 를 사용하면 raster 대비 필요한 information (memory) 가 매우 적어 짐.
  • painting program : image 는 grid of pixel 로 나타 남. Adobe Photoshop. Gimp.
  • drawing program : image 를 geometric shape 로 만듬. layer 개념 활용. Adobe Illustrator. Inkscape.
  • file format
    • raster : GIF,PNG,JPEG,WebP, natural coordinate system 활용
    • vector : SVG (Scalable Vector Graphics) - scalable 하기 때문에 web browser 에 매우 적절. real number coordinates 활용.

1.2 Elements of 3D Graphics

  • 3D graphics 에서는 대부분 vector graphics 를 활용.
  • geometric modeling
  • image 를 list of geometric objects 로 표현
  • object 는 attributes 를 가짐
  • geometry
    • world coordinates 를 가짐
    • hierarchical modeling : geomtric primitives 의 조합으로 만듦
    • geometric transform : scaling, rotation, translation
  • appearance
    • geometric object 에 attributes 를 assign
    • material 이라는 용어를 사용
      • intrinsic visual appperance
      • ex : texture :
    • object 가 보이는 environment 에 따라, actual apperance 가 달라짐 (ex: lighting)
  • image
    • rasterization : 3D graphics 를 2D image 로 변경 (viewing, projection)

1.3 Hardware and Software

OpenGL

  • 1992 년에 Silicon Graphics 에 의해 개발.
  • 대부분의 graphics hardware 에서 OpenGL 을 지원 (desktop, mobile device)
  • WebGL : Web browser 에서 사용되기 위한 OpenGL 버전. OpenGL ES (embedded system) 에 기반 함. Web 에서 대부분의 3D graphics 에 사용
  • CPU 에서 GPU API 에 해당되는 set of commands 를 보냄. OpenGL 은 graphics API 의 한 예. 대부분의 GPU 는 OPenGL 을 지원 (OpenGL command 를 이해)하고, 최소한 OpenGL command 를 GPU 가 이해하는 command 로 번역 가능.
  • graphics API 에는 Vulkan (OpenGL 과 동일 개발 그룹), Metal, Direct3D, WebGPU 가 있음. 이런 API 들은 더 빠르고 효율적이나 더 복잡하고 low-level 이고 쓰기 어려움.
  • OpenGL 은 client/server 시스템으로 설계됨. GPU 가 server, CPU 가 client 에 해당. 그런데 CPU-GPU channel 의 communication time 이 bottleneck 이 되기 때문에 data 를 GPU 메모리에 저장하는 방식을 사용.
  • OpenGL 의 발전
    • OpenGL 은 triangle 과 같은 primitive 를 drawing 함. 그 의미는 각각의 vertice 의 coordinate, attribute 를 계산한다는 뜻임.
    • OpenGL 1.0 은 vertice 를 각각 command 로 계산.
    • OpenGL 1.1 은 여러 vertices 를 array 로 1개 command 로 계산
    • OpenGL 1.5 는 VBO (Vertex Buffer Object) 를 써서, set of vertices 의 coordinates, attributes 를 GPU 의 block of memory 에 저장. (CPU 와의 retransmit X)
    • OpenGL 1.1 은 texture object 를 써서 data reload 를 없앰.
    • OpenGL 2.0 에서는 User 가 직접 graphic feature 를 사용 할 수 있도록 programmable 한 sharders 를 제공 (GLSL(OpenGL Shading Lanuage) programming language 사용)(rendering pipeline 의 몇 개 stage 에서 실행 됨)
      • vertex shaders : each vertex 마다 실행 됨. vertex coordinates(geometric transform), color(attributes, global lighting environment) 등을 계산
      • fragment(pixel) shaders : each pixel 마다 실행 됨. pixel 의 color 등을 계산.
    • 2023년 기준 최신 OpenGL 버전은 4.6 (2017년 개발로 마지막)

2. Two-Dimensonal Graphics

2.1 Pixels, Coordinates, and Colors

2.1.1 Pixel Coordinates

  • digital image 는 pixel 은 row, column coordinate 를 사용.
  • 대부분의 graphics system 은 좌,상단 / 일부 (OpenGL 포함) 은 좌,하단
  • aliasing : discre 한 pixel 에 image 를 표현하다보니 계단과 같이 이미지가 보이는 현상. (jagged)
  • antialiasing : pixel 이 partially covered 되면 background color 와 mix 해서 aliasing 을 줄이는 방법.
  • 요즘 display 는 resolution, PPI (pixels per inch) 가 좋아서 (100 이상) 개별 pixel 은 구분이 안감.
  • 대부분의 graphical system 에서 pixel 은 물리적인 size 를 의미하는게 아니라, 각 device 마다의 적절한 거리를 나타냄 (desktop 에서 1pixel 은 1/100 inch, mobile 은 1/160 inch)
  • vector graphics 는 pixel 에 의한 문제가 rasterization 할 때 빼고는 없음.

2.1.2 Real-number Coordinate Systems

  • API 가 제공하는 subroutine 을 통해 pixel coordinates, real number coordinates 을 쉽게 변환 가능.
  • 그때 그때 상황에 맞게 유용한 coordinate system 을 사용.

2.1.3 Aspect Ratio

  • ratio of width to its height

2.1.4 Color Models

  • RGB color model : RGB intensity 로 color 를 표현
  • light 는 다양한 wavelength 의 wave 로 구성 됨. Three basic (primitive) color 의 조합으로 인식 할 수 있는 대부분의 color 를 표현 가능.
  • color gamut : device 에서 display 가능한 set of colors
  • HSV, HSL
    • Hue :0 ~ 360 degrees
    • Saturation : 0 ~ 1. 0 은 shade of gray. 1은 pure color
    • Value, Lightness : 얼마나 밝은지. 0 ~ 1.
    • alpha : transparency

2.2 Shapes

2.2.1 Basic Shapes

  • API 마다 basic shapes 이 다름. (ex : lines, rectangels, ovals)
  • Lines
    • Line 이 있을 때 어떤 Pixel 에 color 를 부여 할 지 Bresenham's algorithm 이 있음.
    • Line 에는 cap, pattern, join 과 같은 attribute 가 있음
  • rectangle
    • 2개 점의 좌표로 rectangle 표현 가능.
    • rounded corner 와 같은 variation 있음
  • oval(ellipse)
    • center point, radius 가짐
    • oval 이 basic shape 이 아니라면, discre 한 line 여러개로도 표현 가능. (타원의 방정식 수식 활용)

2.2.2 Stroke and Fil

  • shape 를 visible 하는 2개 방법 : stroke,fill
  • stroke : 경계를 선으로 긋는 것
  • Fill : closed surface 라면 그냥 Fill
  • shape 이 intersect 한다면 winding number 활용. winding number 란 positive direction 으로 몇 번 감싸졌는지.

2.2.3 Polygons, Curves, and Paths

  • 모든 shape 을 basic shape 으로 할 수 없으니 polygon 을 활용. polygon 은 line segments 로 이루어짐.
  • regular polygon : 길이,각도가 모두 동일
  • convex polygon : polygon 내부에 어떤 2점을 잇든, 그 이은 선이 polygon 내부에 있는 경우.
  • polygon 을 그리는 방법 :
    • line sgements 를 가진 path 를 활용.
    • path 에는 create,move,lineto,closepath 등 command 를 가짐
    • path 는 line 뿐만 아니라 curve 도 될 수 있음. (Bezier curve:2차/3차 다항식 등) Bezier curve 는 control points 로 곡선 형태 조절 가능.

2.3 Transforms

2.3.1 Viewing and Modeling

  • Viewport : image 가 display 될 pixel 로 이루어지고 natural pixel coordinates 를 활용하는 rectangle. Window 에서 Viewport 로 coordinate transform 이루어짐. (보통 T 로 표현)
  • world coordinates : 각각 다른 실수 좌표계로 정의된 geometric objects 이 모여 "scence", "world" 를 만드는 좌표계
  • world coordinate system 을 사용하면 scene 를 describing 하는게 자연스럽고, viewport coordinate 에서 작업하는 것 보다 쉽기 때문임. object 를 define 하는데 사용하는 좌표계를 object coordinates 라 함. object 를 scene 에 옮기기 위해서는 object coordinates 에서 scene 에 활용하는 world coordinate system 으로 옮겨야 하고, 이걸 modeling transformation 이라 함. (좌표계가 3개가 있는 것??)
  • affine transform : T(x,y) = (ax+by+e,cx+dy+f) 꼴의 좌표 변환

2.3.2 Translation

  • 좌표를 수평, 수직으로 특정 값 만큼 이동.

2.3.3 Rotation

  • x1 = cos(r) x - sin(r) y (*r = radian)
  • y1 = sin(r) x + cos(r) y

2.3.4 Combining Transformations

2.3.5 Scaling

  • 모든 affine transform 은 translations, rotations about the origin, scalings about the origin 의 조합으로 생성 가능.
  • Euclidean transform : 거리와 각도를 유지하는 transform. rigid motion 을 나타냄.

2.3.6 Shear

  • x1 = x + b * y
  • y1 = y

2.3.7 Window-to-Viewport

  • 이미지가 표시되기전 마지막 transformation 은 window-to-viewport transformation

2.3.8 Matrices and Vectors

  • transform 은 matrices 로 표현 가능. 변환이 수행되는 점은 vectors 로 표현 가능.
  • linear transformation :
  • Rotation, Scaling 은 linear transformation. 여러 command 를 한 개의 matrix 로 표현 가능.
  • Translation 은 not lienar transformation. 그런데 2D 좌표에서 1개의 값을 더 사용하여 3x3 matrix 를 사용하면, translation 도 행렬 곱셈으로 표현 할 수 있음
  • 모든 transformation 은 1개의 행렬로 표현 가능하니, computer 는 "current matrix","current transformation" 만 추적하면 됨.

2.4 Hierarchical Modeling

2.4.1 Building Complex Objects

  • 일반적으로 object 의 중심이 coordinates 의 origin (0,0) 에서 시작해서 scaling->rotation->translation 을 통해 scene 에 배치 됨. (scaling, rotatino 은 reference point 를 고정하기 때문에 먼저 실행)
  • 작은 object 들은 각각 coordinate system, modeling transformation 을 통해서 main object(complex object) 를 구성 함.
  • complex object 전체에 modeling transformation 적용 할 수도 있음.
  • 서브루틴에 의해 객체가 그려지면, 프로그램은 서브루틴 호출 전에 current transformation 을 한번 저장하고, 서브루틴이 return 되면, 저장된 transformation 이 복원 됨.

2.4.2 Scence Graphs

  • scene graph : tree like structure. root 는 entire scene, children 은 top-level objects in the scene.

2.4.3 The Transform Stack

  • Transform stack : 객체를 그리기 전에 current transform 을 stack 에 push 하고, 그리고 나서 transform 을 pop. (?)
  • 일부 graphics API 는 transform stack 을 제공. OpenGL 은 glPushMatrix(), glPopMatrix() 를 stack of transformation matrices 로 사용.

2.5 Java Graphics2D

  • Swing : java standard distribution 에 포함된 graphical user interface
  • JavaFX : graphics API
  • ...

2.6 HTML Canvas Graphics

  • 대부분의 modern web browser 는 web page 에 image 생성을 위한 2D graphics API 를 지원. JavaScript 로 구현되어 있음.
  • ...

2.7 SVG:A Scene Description Language

  • SVG (Scalable Vector Graphics)
    • scence description lanauage : programming language 가 scence 을 절차적으로 생성하는것과 달리, SVG 는 "선언적으로" content list(shape, attriute, geometric transform) 를 지정함.
    • XML language
  • ...

3. OpenGL 1.1: Geometry

3.1 Shapes and Colors in OpenGL 1.1

  • OpenGL default 좌표계에서는 x,y,z range 를 -1 ~ 1로 사용.
  • OpenGL 은 다양한 언어로 구현 가능하나, API specification 은 C 로 가정하고 구현.

3.1.1 OpenGL Primitives

  • OpenGL 은 point,line,triangle 과 같은 몇 개의 basic shape(primitive) 만 drawing 가능. curve, curve shape drawing 은 불가능 하고 approximation 만 가능.
  • primitive 는 vertices 로 정의 됨. vertex 는 x,y,z 좌표로 이루어진 점.
    glVertex2f(<x>,<y>) 에서 2 는 paramter 개수, f는 data type 을 의미.
  • OpenGL 에는 10 종류의 primitive 가 존재. (3개는 최신버전 기준 삭제 됨)
  • simplest primitive 는 GL_POINTS. single point 를 rendering.
  • line segment primitive : GL_LINES,GL_LINE_STRIP,GL_LINE_LOOP
    • GL_LINES : disconnected line segment 를 drawing. 2개의 vertices 를 지정.
    • GL_LINES : connected line segment 를 drawing. 2개의 vertices 를 지정.
    • GL_LINE_LOOP : connected line segment 를 drawing. 2개의 vertices 를 지정. final vertex 로 돌아감. (closed)
  • triangle primitive : GL_TRIANGLES,GL_TRIANGLE_STRIP,GL_TRIANGLE_FAN
  • quadrilateral primitive (현재는 삭제) : GL_QUADS,GL_QUAD_STRIP,GL_POLYGON

3.1.2 OpenGL Color

  • OpenGL color 지정을 위한 다양한 함수가 존재. glColor* 이름을 가짐.
  • transparency 설정 가능
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  • glColor3f(<r,g,b>), glColor4f(<r,g,b,a>)

3.1.3 glColor and glVertex with Arrays

  • array 로 color, vertex 를 한번에 지정 가능. glColor3fv,glVertex2iv,etc.

3.1.4 The Depth Test

  • hidden surface problem : 3D 에서 어떤 object 가 다른 object 뒤에 있으면 안 보이도록 처리해야 함.
  • painter's algorithm : 뒤에 있는 object 부터 앞에 있는 object 까지 순서대로 drawing 하면 자연스럽게 뒤에 object 는 안 보임. 2D 에서는 일반적으로 행해지나, 3D 에서는 구현이 어려움. 따라서 OpenGL 에서는 painter's algorithm 대신 depth test 를 사용.
  • depth test
    • depth 는 viewer 부터 object 까지의 거리를 의미. depth 가 작은 object 가 depth 가 큰 object 를 가림.
    • OpenGL 은 pixel 마다 depth value 를 가짐. 추가 메모리를 써서 depth value 를 저장하는 depth buffer 구성. Drawing 할 때 depth buffer 를 참고해서 pixel 이 visible 한 지 안한지 판단. depth value 는 z좌표를 활용하고 -1 ~ 1 range 를 가짐. default 로 depth test 는 turn off 되있으므로, glEnable(GL_DEPTH_TEST) 호출이 반드시 필요. depth value 는 numerical precision 한계를 가지고 있기 때문에, 여러 object 가 같은 값을 가지는 한계가 발생 할 수도 있음.

3.2 3D Coordinates and Transforms

3.2.1 3D Coordinates

  • modeling : construct a scene in 3D
  • OpenGL 에서 일반적인 eye coordinate 는 z축이 화면에 수직, viewer 쪽의 방향이 (+). x/y 는 나머지는 right-handed cooridnate system. (world coordinateseye coordinate 는 다를 수 있음.)
  • objects 는 각각 object coordinates 를 가지고 modeling transforms 를 통해 world, complex objects 에 배치 됨.

3.2.2 Basic 3D Transforms

  • 3D 에서 Rotation 은 회전축 (axis of rotation) 을 가짐.
  • glRotate(r,ax,ay,az) r 은 회적 각도, ax/ay/ax 은 회전축 지정

3.2.3 Hierarchical Modeling

  • stack of transforms 를 활용

3.3 Projection and Viewing

3.3.1 Many Coordinate Systems

  • object coordinates : 실제 object 를 그리는데 사용하는 좌표
  • modeling transformation : 전체 scene 에서 size,orientation,position 을 조절.
  • world coordinates : complete scene 을 구성하는 coordinates. (modeling transformation maps from object coordinates to world coordinates)
  • eye coordinates : viewer 의 좌표계. viewer 는 origin(0,0,0) 에 있으며, 음의 z축 방향을 보고 있음 (모니터 방향)
  • viewing transformation : world coordinates 에서 eye coordinates로의 변환.
  • modelview transformation : modeling, viewing transform 을 1개의 transform 으로 조합. OpenGL 내부에서는 world coordinates 를 전혀 사용하지 않고, modelview transformation을 사용해서 object coordinateseye coordinates 로 바로 이동.
  • viewport : viewer 는 전체 3D world 를 다 볼 수 있고, viewport 라는 일부 부분만 봄.
  • view volume : 실제로 rendering 되는 volume of space.
  • drawing 을 위해서 view volumecube 에 mapping 하는 coordinate transform 을 적용.
  • cube : 중점이 origin 에 있고, x/y/z 좌표가 -1 ~ 1 까지 존재. cube 의 좌표계를 clip coordinates 라고 함.
  • projection transformation : eye coordinates 에서 clip coordinatesprojection transformation 라고 함.
  • device coordinates : 실제 physical display 에서 그림이 그려지는 2D coordinate system. 일반적으로 device coordinates 의 단위는 pixel. drawing region 은 rectangle of pixels 이고, 이 rectangle 이 viewport.
  • viewport transformation : clip coordinatesviewport 로 fit.
  • TODO : 이미지 캡처 떠서 붙이기

3.3.2 The Viewport Transformation

  • x,y clip coordinates 를 display device coordinates 로 변환. glViewport(x,y,width,height) 함수를 활용.
  • OpenGL 은 java 용 JOGL 이나 C 용 GLUT library 를 사용해서 화면에 drawing.

3.3.3 The Projection Transformation

  • 다른 transform 과 마찬가지로 matrix 로 표현 됨.
  • OpenGL 은 modelview transformation 과 별도로 projection matrix 를 tracking 함. glRotatef 와 같은 함수는 두 matrix 모두에 적용 될 수 있으므로, 어느 matrix 에 적용 할 지 알기 위해 matrix mode 라는 state property 를 활용. matrix mode 의 값은 GL_PROJECTION, GL_MODELVIEW.
  • view volume 은 무한한 3D world 에서 일부만 해당되며, view volumeviewing transformationproject 의 조합으로 결정 됨.
  • view transform 은 viewr 가 어디에 위치해 있고, 어느 방향으로 보는지는 정하지만, 얼만큼 보는지는 정하지 않음. projection transform 이 정함. view 안의 모양과 범위를 정함. 카메라가 실제 세상을 보고 있다고 생각하면, view transform 은 카메라의 위치와 방향을 의미하고, projection transform 은 카메라로 실제로 볼 수 있는 Box 의 모양과 크기를 결정한다고 보면 됨.
  • projection 에는 perspective projectionorthographic projection이 있음.
    • perspective projection
      • viewer 가 보는 화면 (pyramid 형태) 를 window 에 투영 시키는 방법. 단, near,far 2개의 값의 거리안의 truncated pyramid(frustum)만 보이게 함.
      • glFrustum(xmin,xmax,ymin,ymax,near,far) 함수로 set-up
    • orthographic projection
      • z 좌표를 삭제하고 3D 를 2D 로 투영. 원근감이 없음. near,far 사용
      • glOrtho(xmin,xmax,ymin,ymax,Near,Far);
    • TODO : 이미지 캡처하기

3.3.4 The Modelview Transformation

  • modeling,viewing 은 개념적으로는 다르지만, matrix 처리 관점에서는 동일.
  • ex : glRotatef(90,0,1,0); 명령은 object y축 기준 90도 회전하는 것과, viewer 를 -90도 회전하는 것으로 모두 동일하게 표현 가능.
  • TODO..

3.3.5 A Camera Abstraction

  • ...

3.4 Polygonal Meshes and glDrawArrays

  • OpenGL 은 points,lines,polygons 만 rendering 가능.
  • polyhedron,polygonal meshpolygon 으로 이루어져 있고, curved surface,spherepolygon 으로 approximation 가능.
  • Set of polygon 을 represent 하는 data structure 정의.

3.4.1 Indexed Face Sets

  • Polygonal mesh 를 표현하는 주요 방법 : IFS(Indexed face sets)
  • polygon 의 앞면은 vertex 를 오른손으로 시계방향으로 돌릴 때 엄지 방향.
  • IFS 에서는 모든 vertex 의 좌표를 가짐.
Vertex #0.  (2, -1, 2)
Vertex #1.  (2, -1, -2)
Vertex #2.  (2, 1, -2)
Vertex #3.  (2, 1, 2)
Vertex #4.  (1.5, 1.5, 0)
Vertex #5.  (-1.5, 1.5, 0)
Vertex #6.  (-2, -1, 2)
Vertex #7.  (-2, 1, 2)
Vertex #8.  (-2, 1, -2)
Vertex #9.  (-2, -1, -2)
  • polygonal face 를 describe 하기 위해 vertex list 를 나열
Face #0:  (0, 1, 2, 3)
Face #1:  (3, 2, 4)
Face #2:  (7, 3, 4, 5)
Face #3:  (2, 8, 5, 4)
Face #4:  (5, 8, 7)
Face #5:  (0, 3, 7, 6)
Face #6:  (0, 6, 9, 1)
Face #7:  (2, 1, 9, 8)
Face #8:  (6, 7, 8, 9)
  • Front face 는 polyhedron 의 바깥쪽 면을 의미하고 (Back face 는 반대), vertex 를 시계 반대 방향으로 나열하는게 OpenGL 규칙.
  • Vertex, face data 는 2d array 로 표현 가능. 추가로 faceColor(R,G,B) 도 face data 순서에 맞게 2d array 로 표현 가능.
  • IFS 의 장점
    • IFS 에서는 Face 의 vertex 를 index(integer) 로 표현하기 때문에, vertex 의 coordinates 를 정의하는 횟수가 줄어서 memory space 이득이 있음.
    • 구조의 변형이 일어날 때 vertex 의 좌표만 변경해 주면 됨.
  • facevertex 를 따로 drawing 하고 싶을 때, depth 가 같은 문제가 존재하므로, polygon offset 을 활용해서 depth 를 살짝 다르게 함.

3.4.2 glDrawArrays and glDrawElements

  • 위의 내용은 OpenGL 1.0 의 기능. OpenGL 1.1 에서는 primitive 를 draw 하는데 너무 많은 funciton 이 호출 된다는 것 (glVertex2d,glColor3fv,glBegin/glEnd)
  • OpenGL 1.1 에서는 glDrawArrays, glDrawElements 를 활용 (WebGL 에서도 사용)
  • glDrawArrays
    • primitive 를 drawing 하는데 필요한 모든 것 (vertex coordinates, colors, vertex attributes, etc.) 를 1개의 array 로 표현.
    • array 가 만들어지면 glDrawArrays 함수 호출 1번으로 draw
    • vertex coordinates 를 single 1d array 로 저장. array 는 int,float,double 을 사용 할 수 있으며, 좌표는 2/3/4 개 사용 가능
    • glVertexPointer
      • glVertexPointer 를 통해서 vertex array meta 정보를 넘겨 줌.
      • void glVertexPointer(int size, int type, int stride, void* array)
      • glEnableClientState(GL_VERTEX_ARRAY); 가 호출 되어야 사용 가능.
      • ex :
      float coords[8] = { -0.5,-0.5, 0.5,-0.5, 0.5,0.5, -0.5,0.5 };
      			glVertexPointer( 2, GL_FLOAT, 0, coords );
    • glDrawArrays
      • glDrawArrays 를 사용해서 최종적으로 drawing
      • void glDrawArrays(int primitiveType,int firstVertex,int vertexCount)
        • primitiveType : primitive type (ex:GL_QUADS)
        • firstVertext : primitive 를 drawing 하는데 사용되는 first vertex 숫자
        • vertextCount : 사용되는 vertices 숫자.
        • ex : glDrawArrays( GL_TRIANGLE_FAN, 0, 4 );
    • glColorPoint
      • vetices 의 Color 를 나타내는 array
      • void glColorPointer(int size, int type, int stride, void* array)
      • glEnableClientState(GL_COLOR_ARRAY); 호출 필요
    • Ex:
float coords[6] = { -0.9,-0.9,  0.9,-0.9,  0,0.7 }; // two coords per vertex.
float colors[9] = { 1,0,0,  0,1,0,  1,0,0 };  // three RGB values per vertex.

glVertexPointer( 2, GL_FLOAT, 0, coords );  // Set data type and location.
glColorPointer( 3, GL_FLOAT, 0, colors );

glEnableClientState( GL_VERTEX_ARRAY );  // Enable use of arrays.
glEnableClientState( GL_COLOR_ARRAY );

glDrawArrays( GL_TRIANGLES, 0, 3 ); // Use 3 vertices, starting with vertex 0.
  • glDrawElements
    • glDrawArrays 와 유사하지만, IFS format 에 사용되도록 설계.
    • void glDrawElements( int primitiveType, vertexCount, dataType, void *array)
    • Ex:
float vertexCoords[24] = {  // Coordinates for the vertices of a cube.
           1,1,1,   1,1,-1,   1,-1,-1,   1,-1,1,
          -1,1,1,  -1,1,-1,  -1,-1,-1,  -1,-1,1  };
          
float vertexColors[24] = {  // An RGB color value for each vertex
           1,1,1,   1,0,0,   1,1,0,   0,1,0,
           0,0,1,   1,0,1,   0,0,0,   0,1,1  };
          
int elementArray[24] = {  // Vertex numbers for the six faces.
          0,1,2,3, 0,3,7,4, 0,4,5,1,
          6,2,1,5, 6,5,4,7, 6,7,3,2  };
          
glVertexPointer( 3, GL_FLOAT, 0, vertexCoords );
glColorPointer( 3, GL_FLOAT, 0, vertexColors );

glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_COLOR_ARRAY );

glDrawElements( GL_QUADS, 24, GL_UNSIGNED_INT, elementArray );

3.4.3 Data Buffers in Java

  • ...

3.4.4 Display Lists and VBOs

  • 지금까지는 같은 object 를 여러번 drawing 할 경우, command 와 data 를 GPU 로 매번 transmit 하는 비효율이 존재 했음. 해결을 위해 GPU 에 information 을 저장하는 display listsVBO (Vertex Buffer Objects) 기술이 존재.
  • Displa lists
    • OpenGL 1.0 에 존재했고, modern OpenGL API 에는 사라짐
    • 동일한 명령을 여러번 사용 할 때, 명령을 GPU 에 저장
    • ...
  • VBO
    • VBO 는 data 를 저장
    • array 를 VBO 에 create,delete 하는 OpenGL command 가 존재. glDrawArrays(),glDrawElements() 를 VBO 에서 사용 가능

3.5 Some Linear Algebra

3.5.2 Matrices and Transformations

  • Rotation, Scaling 은 linear transformation. Translation 은 not linear transformation.
  • affine transformation
    • Linear transformation 후에 translation
    • transformation 이후에 parallel 관계가 유지 되는 경우.
    • 컴퓨터 그래픽스에서는 차원을 한개 더 사용하는 trick 으로 affine transformation 을 vector 와 matrix 의 곱으로 표현 될 수 있도록 함. (linear transformation 으로 바꿈).
    • 4x4 matrix 와 (x,y,z,1) 사용함으로써 translation term 을 표현
  • Transformation function 에 대한되는 Matrix
    • TODO : 이미지 캡처
    • translate,scale,rotation
    • glMultMatrixf(T) 함수를 사용하여 임의의 변환 행렬을 사용하는 것도 가능.

3.5.3 Homogeneous Coordinates

  • Perspective projection 은 object 가 viewer 와 거리가 멀 경우, 움직임이 작아짐. 항상 parallel 관계를 유지하는 affine transformation 에 해당 안 됨.
  • homogeneous coordinates
    • 놀랍게도, 4D vector 를 사용해서 perspective projection 을 표현 가능. (x,y,z,w) 를 (x/w,y/w,z/w) 를 표현하는데 사용하면 됨. w 가 0 일 경우에는, 무한히 떨어진 point 를 의미.
    • OpenGL 내부적으로 모든 3D point 와 vector 를 homogeneous coordinates 로 표현.

4. OpenGL 1.1: Light and Material

4.1 Introduction to Lighting

  • OpenGL 은 default 로 lighting calculation 을 안 함. glEnable(GL_LIGHTING) 호출 필요.
  • material : The properties of a surface that determine how it interacts light

4.1.1 Light and Material

  • specular reflection
    • 정반사
    • specular highlights : surface 가 모두 illuminated 되어도, 반사된 빛이 viewer 에게 도착한 경로의 surface 만, 빛이 보이는 효과.
    • shininess : specular highlights 의 size 와 sharpness 를 결정하는 material property
    • TODO : 이미지 삽입
  • Diffuse reflection
    • 난반사
  • 빛이 surface 에 닿으면 일부는 흡수, 일부는 정반사, 일부는 난반사. 반사량은 파장에 따라 달라지고, material 의 color 에 따라 파장에 따른 반사량도 달라짐. diffuse colordiffuse reflection 의 양을 결정, specular colorspecular reflection 의 양을 결정, OpenGL 은 ambient color 도 존재하여 ambient light(주변광) 의 반사량을 결정. emission color 는 빛이 있을 때 조금 더 brighter 한 특성.
  • ...

4.1.2 Light Properties

  • point light : 모든 방향으로 빛을 내보냄.
  • directional light : 같은 방향으로 빛을 내보냄. (빛이 parallel)(태양)
  • ligth 는 ambient color, diffuse color, specular color 를 가지며, intensity or energy 를 의미. 각각의 material 과 얼만큼 세기로 작용하는지를 의미.

4.1.3 Normal Vectors

  • 빛이 표면에 닿는 각도에 따라 시각적 효과 달라지고, 법선 벡터(unit normal vector)를 알아야 각도 계산 가능. (법선 벡터는 polygon 의 앞면 방향) Vertices of a primitive 에 있는 normal vector 를 lighting 계산에 활용. Vertex 마다 normal vector 를 할당.
  • Flat shading : surface 가 face 처럼 보이게 함. 법선 벡터가 Face 에 대해서 수직.
  • Smooth shading : surface 가 smooth 하게 보이게 함. 법선 벡터가 vertex 를 지나는 curved surface 에 대해서 수직.
  • TODO : 이미지 캡처

4.1.4 The OpenGL 1.1 Lighting Equation

  • lighting calculation 은 한 point 에 대해서 color (rgb) 를 계산하는 것.

  • OpenGL 1.1 에서는 vertices of a primitive 에서만 calculation 수행. vertex 에서 꼐산이 완료되면, primitive 의 interior point 는 interpolation.

  • a(alpha) 계산은 단순함. rgb 계산은 복잡함.

  • red color of vertex : r=mer+garmar+I0,r+I0,r+I0,r+...r = me_{r} + ga_{r}*ma_{r} + I_{0,r} + I_{0,r} + I_{0,r} + ...

    • Ambient color of material : (mar,mag,mab)(ma_{r},ma_{g},ma_{b})
    • Diffuse color of material : (mdr,mdg,mdb)(md_{r},md_{g},md_{b})
    • Specular color of material : (msr,msg,msb)(ms_{r},ms_{g},ms_{b})
    • Emission color of material : (mer,meg,meb)(me_{r},me_{g},me_{b})
    • Global ambient intensity : (gar,gag,gab)(ga_{r},ga_{g},ga_{b})
    • I0,rI_{0,r} : light number 0 에 의한 red color 기여분
  • 빛의 color 기여분 계산

    • lr=larmar+f(ldrmdr(LN)+lsrmsrmax(0,VR)mh)l_{r} = la_{r} * ma_{r} + f * (ld_{r}*md_{r}*(L \cdot N) + ls_{r}*ms_{r}*max(0,V \cdot R)^{mh})
    • Ambient color of light : (lar,lag,lab)(la_{r},la_{g},la_{b})
    • Diffuse color of light : (ldr,ldg,ldb)(ld_{r},ld_{g},ld_{b})
    • Specular color of light : (lsr,lsg,lmsb)(ls_{r},ls_{g},lms_{b})
    • Value of the shininess property of material : mhmh
    • ff : 0 - surface 가 빛의 반대쪽을 향함 / 1 - surface 가 빛을 향함.
    • ambient term 은 빛이 surface 를 향하든 아니든 존재 함.
    • diffuse term 은 빛의 diffsue 세기 material 의 diffuse 반사율 LN 의 내적 (각도가 곱해지는 이유는, 각도가 클 수록 빛의 에너지가 넓은 면적에 닿기 때문)
    • specular term 은 Viewer 와 정반사 각도가 좁을수록 커짐. shiness(mhmh) 값이 클 수록 작고,sharp 한 specular highlight 가 생김.
    • TODO : 빛 입사 이미지 캡처
  • 이 외에도 빛의 거리에 의한 효과, spotlight, shadw 효과 등이 더 존재함.

4.2 Light and Material in OpenGL 1.1

4.2.1 Working with Material

  • material properties 는 vertext 속성. polygon 에서는 앞면, 뒷면 재질을 따로 가짐.
  • ambient, diffuse, specular, emission color
  • void glMaterialfv(int side, int property, float* valueArray)
  • Ex:
float[] gold = { 0.24725F, 0.1995F, 0.0745F, 1.0F,      /* ambient */
                 0.75164F, 0.60648F, 0.22648F, 1.0F,    /* diffuse */
                 0.628281F, 0.555802F, 0.366065F, 1.0F, /* specular */
                 50.0F                                  /* shininess */
    };
    
gl.glMaterialfv( GL2.GL_FRONT_AND_BACK, GL2.GL_AMBIENT, gold, 0 );
gl.glMaterialfv( GL2.GL_FRONT_AND_BACK, GL2.GL_DIFFUSE, gold, 4 );
gl.glMaterialfv( GL2.GL_FRONT_AND_BACK, GL2.GL_SPECULAR, gold, 8 );
gl.glMaterialf( GL2.GL_FRONT_AND_BACK, GL2.GL_SHININESS, gold[12] );

4.2.2 Defining Normal Vectors

  • normal vector 는 vertex 의 attribute.
  • ...

4.2.3 Working with Lights

  • 광원을 Gl_LIGHT0 과 같이 선언 할 수 있으며 directional ligth,point light 종류가 있고, 각 광원은 diffuse,specular,ambient intensity 가질 수 있음.
  • void glLightfv(int light, int property, float* valueArray);
  • GL_POSITION property로 좌표 설정.
  • 위치 설정은 다소 어려움. 기본 3가지 방법이 있음
    • modelview transformation 전에 설정. ...
    • viewing transformation 후에 설정. ...
    • modeligh transformation 이후 위치 설정. ...

4.2.4 Global Lighting Properties

  • 개별 광원 외에도 몇 개의 global 광원 property 가 3개 있음.
  • global ambient light : GL_LIGHT_MODEL_AMBIENT
  • GL_LIGHT_MODEL_TWO_SIDE : 양면의 조명을 키는데 사용
  • GL_LIGTH_MODEL_LOVAL_VIEWER

4.3 Image Textures

  • Texture : Surface 에 pattern 을 부여. 단일 primitive 내에서 pixel to pixel 간 변형.
  • Image textures : Texture 중 한 종류.
  • OpenGL 에서는 Texture image width, height 는 2 의 제곱 꼴.
  • Image texture 의 기본 동작은 pixel 의 RGBA color 값에 image color RGBA 값을 곱하는 것.

4.3.1 Texture Coordinates

  • Texture 가 surface 에 적용 될 때, surface 의 각 점은 texture 의 점과 Mapping 되어야 함. 이를 위해 object 는 texture coordinates 가 필요. OpenGL 에서는 primitive 의 각각 vertex 마다 texture coordinates 가 지정 됨. primitive 내부 점은 vertex 에서의 interpolation 으로 결정 됨.
  • Texture image 는 자체 2D coordinate system 과 함께 제공 됨. s 는 수평 좌표, t 는 수직 좌표, 좌표는 좌하단부터 (0,0) 으로 시작해서 0 ~ 1 범위의 실수 값. (0 ~ 1 밖의 값도 여전히 텍스트 좌표로 유효하긴 함) Texture 좌표는 픽셀 개수와는 상관 없음.
  • textured primitive 를 위해서는 각 vertex 마다 (s,t) 좌표가 필요. texture coordinatevertexattribute
  • TODO : 이미지 캡처
  • Ex:
glNormal3d(0,0,1);       // This normal works for all three vertices.
glBegin(GL_TRIANGLES);
glTexCoord2d(0.3,0.1);   // Texture coords for vertex (0,0)
glVertex2d(0,0);
glTexCoord2d(0.45,0.6);  // Texture coords for vertex (0,1)
glVertex2d(0,1);
glTexCoord2d(0.25,0.7);  // Texture coords for vertex (1,0)
glVertex2d(1,0);
glEnd();
  • 적절한 texture coordinates 지정은 다소 어려우므로, 쉬운 방법은 그냥 전체 좌표 (0,0), (1,1) 으로 지정해 버리는 것.

4.3.2 MipMaps and Filtering

  • minification filter : texture 에서의 2개 이상의 pixel 이 surface 에서의 1개 의 pixel 을 덮을 때.
  • magnification filter : texture 에서의 1개의 pixel 이 surface 에서의 2개 이상의 pixel 을 덮을 때.
  • texels : texture 의 pixel 을 칭 함. texture pixel, texture element.
  • nearest texel filtering : 가장 가까운 texel 의 color 활용, 결과가 좋지는 않음.
  • linear filtering : 여러 texel color 의 average 값을 활용. surface area 가 texture 대비 많이 작을 때는 비효율 적.
  • mipmaps : texture 이미지의 size 를 줄여서 활용. minification filtering 에만 활용. surface 의 크기와 가장 유사한 mipmap 을 선택 한 후, linear filtering 수행.

4.3.3 Texture Target and Texture Parameters

  • texture 는 2D 뿐만 아니라 1D,3D 도 사용 가능.
  • Texture 가 surface 에 적용되는 세부 옵션 조절 :
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);

4.3.4 Texture Transformation

  • texture 는 1,2,3D 모두 가능하므로 좌표계를 homogeneous coordinates 로 활용. 좌표계는 (s,t,r,q) 로 표현 됨.
  • texture coordinatesvertex coordinates 오 다르지 않으므로, transformation 이 같은 방식으로 이루어짐. modelview, projection transformation 에 따라서 texture transformation 이 행해 짐. 3개 변환의 각각의 값은 matrix 로 저장 됨.
  • texture matrix 는 scaling,rotation,translation 및 조합으로 나타내 짐.

4.3.5 Loading a Texture from Memory

  • image data load 함수 : glTexImage2D(target, mipmapLevel, internalFormat, width, height, border, format, dataType, pixels);

4.3.6 Texture from Color Buffer

  • OpenGL 의 color buffer 를 사용해서 자체적으로 texture drawing 가능.

4.3.7 Texture Objects

  • 위의 내용은 OpenGL 1.0 의 기능. OpenGL 1.1 에서는 더 효율적이기 위해 texture objects 를 도입.
  • texture objects 는 동일 프로그램에서 여러 텍스처 이미지로 작업 할 때 사용. GPU 에 여러 texture data 를 미리 저장해 놓을 수 있음.

4.3.8 Loading Textures in C

  • ...

4.4 Lights, Camera, Action

  • Rendering a scene 은 scene graph 를 탐색하면서 object 를 rendering 하는 과정.
  • scene graph 를 디자인 할 때는 고려 사항이 많음. 예를 들어, transform 이 object node 의 property 여야 하는지, transform 을 나타내는 별도의 node 가 있어야 하는지 등등.
  • 근본적인 선택은 shape of the graph 임. scene graph 는 directed acyclic graph(dag) 일 수 있음. (node 가 여러 parent 를 가질 수 있는 자료구조, 1개의 parent 를 가지는 tree 와는 다름)

4.4.1 Attribute Stack

  • glPushMatrix, glPopmatrix 는 transform stack 을 조작하는데 활용 됨.
  • scene graph 탐색 중에 transfrom 이 포함된 node 를 만나면, transform 적용 전에 glPushMatrix 가 호출되고, 해당 node 와 하위 항목들이 rendering 된 후에, glPopMatrix 가 호출되어 이전의 modelview transformation 을 복구 함.
  • color, material 과 같은 attribute 에도 동일 방법이 적용 됨. glPushAttrib, glPopAttrib 함수를 활용해서 attribute stack 을 유지.
  • ...

4.4.2 Moving Camera

  • 다른 object 처럼 world 를 움직 일 수 있는 viewer 를 구현한다 해보자.
  • 그럼 viewer 를 moving camera 라고 생각한다면, camera 에 변형을 적용 할 수도 있고, camera 의 위치, 방향, 크기(시야각) 에 따라 rendering 할 내용이 결정 됨. (viewing transformation 을 결정)
  • camera 에 modeling transformation 에 적용하는건, scence 전체에 viewing transformation 을 하는 것과 같고, viewing transformation 은 camera 의 modeling transformation 을 하는 것의 역과 같음.
  • scene graphcamera object node 를 포함시키면 도움 됨 (?)
  • scene graph 가 탐색 될 때, 어떤 node 든 path 에 따라 적용된 모든 transform 의 합인 modeling transformation 이 적용 됨. 그런데 만약 node 가 camera node 라면 modeling transformation 을 적용하는게 아니라 그 inverse 를 viewing transform 으로 적용 해야 함. inverse 를 위해서 path 를 거꾸로 따라감.
  • TODO : 이미지 캡쳐
  • 위 내용을 쉽게 구현하기 위해 tree 구조에서 patent pointer 를 활용.
  • 위 내용을 염두해두고 camera 에서 scene 을 rendering 하는 algorithm 을 정리하면
    1. glLoadIdentity() 를 호출해서 modelview transform 가 identity 가 되게 함.
    2. camera node 에서 parent pinter 를 따라서 root of tree 까지 감.
    3. 각 node 에서 modeling transformation 의 inverse 를 적용.
    4. root 에 도달하면 camera 에 해당하는 viewing transformation 이 설립(?)
    5. 이제 scene graph 를 탐색하면서 scene 을 rendering (camera node 는 무시)

4.4.3 Moving Light

  • Light 를 object 로 고려하는 것도 도움이 됨. Light 를 lamp 로 생각하면 geometric, modeling transformation 가 다 적용 가능함. scene graph 의 node 로 표현 가능.
  • Light 는 modelview transformation 의 영향을 받음.
  • 그런데 Light 를 node 로 간주하면, Light node 에 가기 전에 순회하는 node 는 light 에 대한 설정이 불가능 함. 따라서 light 를 set up 하기 위한 scene graph 를 첫번째로 순회하고, 두번째로 geometry 를 그리기 위해서 순회를 한번 더 하는 방법을 활용.
profile
복습용 저장소

0개의 댓글