Coordinate Systems Graphics Programming 321190 2014 년봄학기 3/14/2014 박경신 2D Cartesian Coordinate Systems 3D Cartesian Coordinate Systems Cartesian Coordination Systems -x +y y-axis x-axis +x Two axes: x-axis and y-axis, two straight lines perpendicular to each other, both pass through origin and extends infinitely in two opposite directions 원점 (Origin) 은좌표계의중심에위치하고있고값은 (0, 0) 이다. y z z y x 왼손좌표계 (Left-handed coordinate system) 는 x+ 는오른쪽, y+ 는위쪽, z+ 는화면안쪽. 오른손좌표계 (Right- handed coordinate system) 는 x+ 는왼쪽, y+ 는위쪽, z+ 는화면안쪽. -y x
Screen Coordinate System 3D Coordinate Systems (0, 0) +y y-axis x-axis +x Screen coordinate system은원점 (Origin) 이화면의좌측상단에위치하고값은 (0, 0) 이다. x+ 오른쪽. y+ 아래쪽. 1 unit = 1pixel z y x OpenGL 은오른손좌표계 (Righthanded coordinate system) x+ 오른쪽. y+ 위쪽. z+ 화면밖으로나오는방향. OpenGL Camera OpenGL에서는카메라가물체의공간 (drawing coordinates) 의원점 (origin) 에위치하며 z- 방향으로향하고있다. 관측공간을지정하지않는다면, 디폴트로 2x2x22 2 입방체의 viewing volume을사용한다. (1, 1, 1) Orthographic Viewing 직교투영 (Orthographic parallel projection) Ortho(left, right, bottom, top, znear, zfar); 기본직교투영에서는점들은 z-축을향해 z=0 평면에투영 z=0 (-1, -1, -1)
Perspective Viewing 원근투영 (Perspective projection) Frustum(left, right, bottom, top, znear, zfar); Perspective(fovy, aspect, znear, zfar); - 상하좌우값을설정하는대신 y 방향의시선각도 (FOV) 와종횡비 ( 가까운쪽클리핑평면의너비를높이로나눈값 ) 를사용 Viewport Functions 뷰포트 (Viewport) 윈도우내부에설정한공간. 그리기가뷰포트내부로제한됨. glviewport(x, y, width, height) 윈도우를처음생성할때전체윈도우에해당하는픽셀영역을뷰포트로설정 ; 이보다작은영역을뷰포트로설정할때는 glviewport() 사용. 일반적으로윈도우전체를뷰포트로사용. GLUT Reshape function이있을경우, glviewport() 가반드시포함되어야함. Transformations and Viewing OpenGL에서 projection matrix (transformation) 를사용하여 projection을수행함 Transformation 함수는좌표계변환을위해사용하였음 그러나 OpenGL 3.0 이전 transformation 함수들은 deprecated ( 더이상사용하지않길권고함 ) 3 가지선택 Application code GLSL functions GLM (OpenGL Mathematics) vector, matrix Conventional OpenGL Rendering Pipeline OpenGL에서지원하는옵션과상태변수를검사해서적용여부를판단하므로저사양 HW에서는비효율적 Modified Phong Illumination Model만지원하는고정된조명계산 Gouraud Shading만지원하는고정된음영처리 정점색을계산한후정점색을보간하여픽셀색을결정 Mach Band가나타나거나픽셀값이잘못계산될수있음 Viewer
Extending OpenGL 그래픽하드웨어의발전에따라복잡한그래픽기법을적용하기위한기능의지원필요 OpenGL은새로운버전에추가된기능을확장기능으로지원 이전버전의 API를수정하지않음으로써이전버전과의호환성유지 함수나매크로상수이름에확장기능을식별할수있도록접미어를붙여명명 _ARB, _EXT, _NV, _ATI 등등 프로그래머블하드웨어를지원하기위한 API를확장기능으로제공 고정파이프라인을이용하는대신사용자가작성한코드대로음영처리를할수있는프로그래머블파이프라인의이용이가능 Programmable Pipeline Vertex Shader, Fragment Shader를작성하여다양한렌더링기법을적용가능 OpenGL Shader 기본 Shaders Vertex shader Fragment shader Vertex Shader Applications Moving vertices Morphing Wave motion Fractals Lighting More realistic models Cartoon shaders
Fragment Shader Applications Per-fragment lighting calculations Fragment Shader Applications Texture mapping per vertex lighting per fragment lighting Smooth shading Environment mapping Bump mapping Simple Vertex Shader Execution Model Input from application in vec4 vposition; void main(void) Must link to variable in application Vertex data Shader Program { GPU gl_position = vposition; Built-in variable Application Program Vertex Shader Primitive Assembly gldrawarrays Vertex
Simple Fragment Program void main(void) { gl_fragcolor = vec4(1.0, 0.0, 0.0, 1.0); Execution Model Shader Program Application Rasterizer Fragment Shader Frame Buffer Fragment Fragment Color GLSL Data Types C types: int, float, bool Vectors: 벡터 float vec2, vec3, vec4 또한 int (ivec) 와 boolean (bvec) Matrices: mat2, mat3, mat4 행렬 열 (columns) 우선으로구성 일반적인참조방식은 m[row][column] Texture Sampler: 텍스쳐접근이가능한샘플러타입 sampler1d, sampler2d, sampler3d, samplercube sampler1dshadow, sampler2dshadow C++ style constructors vec3 a = vec3(1.0, 2.0, 3.0) vec2 b = vec2(a) GLSL Pointers GLSL에는 pointer 개념이없음 C 언어의구조체 (struct) 을이용해서함수로복사해서사용가능 Matrices나 Vectors 는기본형 (basic types) 으로 GLSL 함수에파라메터입력이나반환형출력으로사용가능 mat3 3f func(mat3 a)
GLSL Qualifiers 변수평가자 (Variable Qualifiers) const 상수 attribute 전역변수이며, 정점마다바뀔수있고, OpenGL 프로그램에서 Vertex Shader로값을변경함. 이평가자는 Vertex Shader에서만사용됨. 쉐이더에서는읽기전용. Built-in vertex attribute: gl_position User-defined vertex attribute: in vec3 velocity uniform 전역변수이며, Primitive마다바뀔수있고, OpenGL 프로그램에서쉐이더로값을변경함. 이평가자는 Vertex Shader 와 Fragment Shader 모두에서사용가능. 쉐이더에서이변수는상수. varying Vertex Shader에서 Fragment Shader로전달되는변수. Vertex Shader 에서는쓰기가허용되지만, Fragment Shader에서는읽기전용. 최신버전에서는 Vertex Shader에서 out으로쓰고, Fragment Shader 에서 in 으로사용 User-defined varying variable: out vec4 color; Example: Vertex Shader const vec4 red = vec4(1.0, 0.0, 0.0, 1.0); out vec3 color_out; void main(void) { gl_position = vposition; color_out = red; Required Fragment Shader in vec3 color_out; void main(void) { gl_fragcolor = color_out; // in latest version use form // out vec4 fragcolor; // fragcolor = color_out; GLSL Operators and Functions 일반적인 C 함수 Trigonometric Arithmetic Normalize, reflect, length Overloading of vector and matrix types mat4 a; vec4 b, c, d; c = b*a; ;// a column vector stored as a 1d array d = a*b; // a row vector stored as a 1d array
GLSL Constructor 생성자 (Constructor) 변수의초기화는 C++ 생성자방식을이용 vec3 n = vec3(0.0, 1.0, 0.0); 생성자는초기화외에식에서도사용가능 greencolor = mycolor + vec3(0.0, 1.0, 0.0); 벡터에하나의스칼라값을지정하면벡터의모든요소에할당 ivec4 whitecolor = ivec4(255); 스칼라와벡터, 행렬을생성자내에서혼합해사용할수있고, 여분의요소가있는경우버려짐 vec4 v = vec4(x, vec2(y, z), w); 행렬은열우선으로구성되고, 단일스칼라값을지정하는경우대각행렬이됨 ( 대각이외의요소는 0으로채워짐 ) mat2 m = mat2(1.0, 0.0, 0.0, 1.0); mat2 m = mat2(1.0); 형변환은생성자를통해서만가능 float j = 4.7; int i = int(j); GLSL Swizzling and Selection [] 또는 (.) operator를사용하여벡터및행렬요소에접근 x, y, z, w r, g, b, a s, t, p, q vec3 a = vec3(0.0, 0.0, 1.0); a[2], a.b, a.z, a.p는모두다같음 mat3 m = mat3(1.0); float element21 = m[2][1]; // 0.0 mat3 m = mat3(1.0); vec3 column1 = m[0]; // (1, 0, 0) 요소선택자를이용하여재배치및복제가능 vec3 myzyx = szyx; s.zyx; 요소선택자를사용하여벡터일부요소만수정가능 vec4 a; a.yz = vec2(1.0, 2.0); GLSL Passing Values 함수의반환형으로배열을제외한모든타입이사용가능 함수의인자로는배열및구조체를포함한모든타입이사용가능 Call by value로만호출되므로다음한정자를사용하여함수내의인자값이변경될수있는여부를지정할수있음 in (default) const in out inout (deprecated) OpenGL Geometry 가상의공간을구성하는각물체를표현하는데있어가장기본이되는요소 실시간그래픽스에서는주로가장단순한형태의표현방법인 linear primitives i i 를사용 Point, vertex Line segments Polygon Polyhedron
OpenGL Geometry Primitives GL_POINTS GL_LINES GL_LINE_STRIP GL_LINE_LOOP GL_TRIANGLES GL_TRIANGLE_STRIP GL_TRIANGLE_FAN OpenGL Attributes 각기하학적기본요소 (geometry primitive) 는속성을갖고있다. 속성은기본요소가화면상에나타날수있는방법을제어한다. Color Line thickness Line styles Polygon patterns 선의두께나스타일 다각형표시방법 OpenGL Attributes OpenGL Color Model RGB (Red Green Blue) or RGBA(Red Green Blue Alpha) RGB 색이따로분리돼서 framebuffer 에저장되어있음. Color Triangle const float vertexcolor[] = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 10f 1.0f, 0.0f, 00f 1.0f, 10f 0.0f, 00f 00f 0.0f, 1.0f, 10f 1.0f 10f ; const float vertexpositions[] = { -0.75f, -0.75f, 0.0f, 1.0f, 0.75f, -0.75f, 0.0f, 1.0f, 0.75f, 0.75f, 0.0f, 1.0f ; void SetData() t { glgenvertexarrays(1, &vao); // vao glbindvertexarray(vao); glgenbuffers(2, &vbo[0]); // vbo glbindbuffer(gl_array_buffer, vbo[0]); // vertex position glbufferdata(gl_array_buffer, 12*sizeof(GLfloat), vertexpositions, GL_STATIC_DRAW); glvertexattribpointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0); glenablevertexattribarray(0); glbindbuffer(gl_array_buffer, vbo[1]); // vertex color glbufferdata(gl_array_buffer, 12*sizeof(GLfloat), vertexcolor, GL_STATIC_DRAW); glvertexattribpointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0); glenablevertexattribarray(1); glbindvertexarray(0);