Microsoft MVP성태의 닷넷 이야기
Graphics: 30. .NET으로 구현하는 OpenGL (4), (5) - Shader [링크 복사], [링크+제목 복사],
조회: 18935
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 8개 있습니다.)
Graphics: 27. .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리
; https://www.sysnet.pe.kr/2/0/11770

Graphics: 28. .NET으로 구현하는 OpenGL (2) - VAO, VBO
; https://www.sysnet.pe.kr/2/0/11772

Graphics: 29. .NET으로 구현하는 OpenGL (3) - Index Buffer
; https://www.sysnet.pe.kr/2/0/11773

Graphics: 30. .NET으로 구현하는 OpenGL (4), (5) - Shader
; https://www.sysnet.pe.kr/2/0/11774

Graphics: 31. .NET으로 구현하는 OpenGL (6) - Texturing
; https://www.sysnet.pe.kr/2/0/11775

Graphics: 32. .NET으로 구현하는 OpenGL (7), (8) - Matrices and Uniform Variables, Model, View & Projection Matrices
; https://www.sysnet.pe.kr/2/0/11784

Graphics: 33. .NET으로 구현하는 OpenGL (9), (10) - OBJ File Format, Loading 3D Models
; https://www.sysnet.pe.kr/2/0/11787

Graphics: 34. .NET으로 구현하는 OpenGL (11) - Per-Pixel Lighting
; https://www.sysnet.pe.kr/2/0/11792




.NET으로 구현하는 OpenGL (4), (5) - Shader

아래의 글에 이어,

.NET으로 구현하는 OpenGL (3) - Index Buffer
; https://www.sysnet.pe.kr/2/0/11773

4회 강좌는,

OpenGL 3D Game Tutorial 4: Introduction to Shaders
; https://www.youtube.com/watch?v=AyNZG_mqGVE

Shader에 대한 설명을 할 뿐, 딱히 코드의 변경은 없습니다. Shader를 도입한 코드의 변경은 5회 강좌에서 설명합니다.

OpenGL 3D Game Tutorial 5: Coloring using Shaders
; https://youtu.be/4w7lNF8dnYw

소스 코드
; https://www.dropbox.com/sh/qtfhwru70y9sg8b/AAAweVar09wgu9DmmSO8yAf8a?dl=0

Shader를 도입하기 위해, 우선 (ShaderProgram 클래스를 상속한) StaticShader 인스턴스 생성 및 해제 코드와 Shader를 적용할 Model의 렌더링 시 전/후처리를 합니다.

// MainForm.cs

StaticShader _shader;

private void glControl_ContextCreated(object sender, OpenGL.GlControlEventArgs e)
{
    GlControl glControl = (GlControl)sender;
    _displayManager.createDisplay(glControl);

    _loader = new Loader();
    _renderer = new Renderer();
    _shader = new StaticShader();
    _model = _loader.loadToVAO(_vertices, _indices);
}

private void glControl_ContextDestroying(object sender, GlControlEventArgs e)
{
    _loader.CleanUp();
    _shader.CleanUp();
}

private void glControl_Render(object sender, OpenGL.GlControlEventArgs e)
{
    Control senderControl = (Control)sender;
    Gl.Viewport(0, 0, senderControl.ClientSize.Width, senderControl.ClientSize.Height);

    _renderer.Prepare();
    _shader.Start();
    _renderer.Render(_model);
    _shader.Stop();

    _displayManager.updateDisplay();
}

자, 그럼 StaticShader에는 무슨 일을 하느냐? 하면 GLSL 문법의 vertex shader와 fragment shader 파일을,

#version 400 core

in vec3 _position;

out vec3 _colour;

void main(void)
{
    gl_Position  = vec4(_position, 1.0);
    _colour = vec3(_position.x + 0.5, 1.0, _position.y + 0.5);
}

#version 400 core

in vec3 _colour;

out vec4 _out_Color;

void main(void)
{
    _out_Color = vec4(_colour, 1.0);
}

로드해서 런타임 시에 컴파일해 보관하고 있어야 합니다. (아래의 코드는 정형화된 코드 절차이므로 거의 그대로 재사용할 수 있습니다.)

using OpenGL;
using System;
using System.Collections.Generic;
using System.IO;

namespace GameApp
{
    public abstract class ShaderProgram
    {
        uint _programID;
        uint _vertexShaderID;
        uint _fragmentShaderID;

        public ShaderProgram(string vertexFile, string fragmentFile)
        {
            _vertexShaderID = loadShader(vertexFile, ShaderType.VertexShader);
            _fragmentShaderID = loadShader(fragmentFile, ShaderType.FragmentShader);

            _programID = Gl.CreateProgram();
            Gl.AttachShader(_programID, _vertexShaderID);
            Gl.AttachShader(_programID, _fragmentShaderID);

            bindAttributes();

            Gl.LinkProgram(_programID);
            Gl.ValidateProgram(_programID);
        }

        protected abstract void bindAttributes();

        public void Start()
        {
            Gl.UseProgram(_programID);
        }

        public void Stop()
        {
            Gl.UseProgram(0);
        }

        public void CleanUp()
        {
            Stop();
            Gl.DetachShader(_programID, _vertexShaderID);
            Gl.DetachShader(_programID, _fragmentShaderID);
            Gl.DeleteShader(_vertexShaderID);
            Gl.DeleteShader(_fragmentShaderID);
            Gl.DeleteProgram(_programID);
        }

        protected void bindAttribute(uint attribute, string variableName)
        {
            Gl.BindAttribLocation(_programID, attribute, variableName);
        }

        static uint loadShader(string file, ShaderType type)
        {
            string[] codeText = ReadShaderCode(file);
            uint shaderID = Gl.CreateShader(type);

            Gl.ShaderSource(shaderID, codeText);
            Gl.CompileShader(shaderID);

            int compileResult = Gl.FALSE;
            Gl.GetShader(shaderID, ShaderParameterName.CompileStatus, out compileResult);

            if (compileResult == Gl.FALSE)
            {
                throw new InvalidDataException(OpenGLExtension.GetShaderInfoLog(shaderID));
            }

            return shaderID;
        }

        private static string[] ReadShaderCode(string file)
        {
            // ...[생략: 파일 텍스트 로드]... 
        }
    }
}

ShaderProgram 타입에서 bindAttributes 메서드를 abstract로 해놓았으니, 당연히 ShaderProgram 타입을 상속받은 타입을 정의해야 하고 그것이 MainForm.cs에서 사용한 StaticShader입니다.

namespace GameApp
{
    public class StaticShader : ShaderProgram
    {
        const string VERTEX_FILE = "./shaders/vertexShader.txt";
        const string FRAGMENT_FILE = "./shaders/fragmentShader.txt";

        public StaticShader() : base(VERTEX_FILE, FRAGMENT_FILE)
        {
        }

        protected override void bindAttributes()
        {
            base.bindAttribute(0, "position");
        }
    }
}

바인딩은 0번 위치에 "position"이라는 이름으로 하고 있습니다. 이것은 vertexShader의 소스 코드를 보면 이해할 수 있습니다.

#version 400 core

in vec3 _position;

out vec3 _colour;

void main(void)
{
    gl_Position  = vec4(_position, 1.0);
    _colour = vec3(_position.x + 0.5, 1.0, _position.y + 0.5);
}

위의 소스 코드에 보면 "_position" 이름이 나오는데 원래 저 변수는 다음과 같이 선언한 것을 줄인 것입니다.

layout(location = 0) in vec3 _position;

다시 말해, 이름은 달라도 되지만 location으로 바인딩한 숫자는 틀리면 안 됩니다. 그렇긴 해도 이름 역시 맞춰주는 것이 일관성을 위해 좋을 것입니다. 만약 이름을 기준으로 location 위치를 동적으로 구하고 싶다면 다음과 같은 식으로 Gl.GetAttribLocation 메서드를 이용할 수 있습니다.

protected void bindAttribute(...)
{
    uint id = (uint)Gl.GetAttribLocation(_programID, "_position"); // vertex shader 코드의 변수 중 "_position"에 대한 location 값을 반환
    Gl.BindAttribLocation(_programID, id, "_position");
}




그런데, 사실 Gl.BindAttribLocation 메서드에서는 이름과 ID만을 바인딩할 뿐 값이 없습니다. 실질적인 값은, VBO가 로드된 VAO의 슬롯 번호를 통해서 전달하기 때문입니다.

public RawModel loadToVAO(float [] positions, int[] indices)
{
    uint vaoID = createVAO();

    bindIndicesBuffer(indices);
    storeDataInAttributeList(0, positions);

    unbindVAO();

    return new RawModel(vaoID, positions.Length);
}

unsafe void storeDataInAttributeList(uint attributeNumber, float [] data)
{
    uint vboID = Gl.GenBuffer();
    vbos.Add(vboID);
    Gl.BindBuffer(BufferTarget.ArrayBuffer, vboID);

    Gl.BufferData(BufferTarget.ArrayBuffer, (uint)(data.Length * sizeof(float)), data, BufferUsage.StaticDraw);

    Gl.VertexAttribPointer(attributeNumber, 3, VertexAttribType.Float, false, 0, IntPtr.Zero);
    Gl.BindBuffer(BufferTarget.ArrayBuffer, 0);
}

Gl.VertexAttribPointer의 호출로 Vertex 위치를 가리키는 VBO 데이터가 attributeNumber (== 0)에 해당하는 슬롯으로 지정되었기 때문에 Shader의 Gl.GetAttribLocation에서 이 값과 연결된 것입니다. 그런데 솔직히 Gl.BindAttribLocation이 왜 필요한지 잘 모르겠습니다. 어차피 Gl.VertexAttribPointer에 의해 0번으로 지정되었는데, 그 값을 shader 처리 클래스에서 Gl.BindAttribLocation을 이용해 슬롯 번호를 다른 것으로 할당하는 것이 크게 의미가 없어 보이기 때문입니다. (혹시, 나중에 POSITION 관련 값들이 다중으로 전달될 때 이를 명시하기 위한 걸로 사용되는 걸까요?)

암튼, 실제로 현재 예제에서는 ShaderProgram 타입의 bindAttribute를 주석 처리해도 shader가 잘 동작합니다.

protected void bindAttribute(uint attribute, string variableName)
{
    // Gl.BindAttribLocation(_programID, attribute, variableName);
}

다음은 이번 글의 예제가 동작했을 때 보이는 화면입니다.

opengl_tutorial_5_1.png

(첨부 파일은 이 글의 예제 프로젝트를 포함합니다.)




문서에 보면 아래의 예제에서,

#version 400 core

/* layout(location = 0) */ in vec3 position;

out vec3 colour;

void main(void)
{
    gl_Position  = vec4(position, 1.0);
    colour = vec3(position.x + 0.5, 1.0, position.y + 0.5);
}

VertexAttribPointer에 전달한 attributeNumber 슬롯 번호는 위의 shader에 할당한 location의 값과 맞춰주기만 하면 된다고 합니다. 그런데 실제로 테스트해 보면 현재 단계에서는 오직 양쪽 모두 0번으로 설정했을 때만 정상적으로 그려지는 것을 확인할 수 있습니다. 만약 VertexAttribPointer의 값이 크고 shader 측의 location 값이 낮다면 비정상 종료하고, 그 반대의 경우라면 (당연히) 데이터가 안 들어왔을 테니 vertex shader의 출력이 비어 있게 됩니다.

아마도, VAO에 더 많은 VBO를 슬롯에 할당한 경우에는 번호를 맞춰주는 식으로 동작을 할 것 같습니다.

참고로, VAO에 무작정 많은 VBO 슬롯을 할당할 수 있는 것은 아닙니다. 이것은 버전마다 틀린데 근래의 GPU에서는 대부분 16개를 지원한다고 합니다. 이 슬롯의 최대 개수를 코드로 얻고 싶다면 다음과 같은 메서드를 만들 수 있습니다.

int GetMaxVertexAttribs()
{
    ulong[] values = new ulong[1];
    Gl.GetIntegerNV(Gl.MAX_VERTEX_ATTRIBS, values);

    return (int)values[0];
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 11/13/2018]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11383정성태12/4/201723396디버깅 기술: 110. 비동기 코드 실행 중 예외로 인한 ASP.NET 프로세스 비정상 종료 현상 [1]
11382정성태12/4/201721932오류 유형: 436. System.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired 예외 발생 시 "[Pre-Login] initialization=48; handshake=1944;" 값의 의미
11381정성태11/30/201718422.NET Framework: 702. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법(두 번째 이야기)파일 다운로드1
11380정성태11/30/201718450디버깅 기술: 109. windbg - (x64에서의 인자 값 추적을 이용한) Thread.Abort 시 대상이 되는 스레드를 식별하는 방법
11379정성태11/30/201719136오류 유형: 435. System.Web.HttpException - Session state has created a session id, but cannot save it because the response was already flushed by the application.
11378정성태11/29/201720618.NET Framework: 701. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법 [1]파일 다운로드1
11377정성태11/29/201719881.NET Framework: 700. CommonOpenFileDialog 사용 시 사용자가 선택한 파일 목록을 구하는 방법 [3]파일 다운로드1
11376정성태11/28/201724272VS.NET IDE: 123. Visual Studio 편집기의 \r\n (crlf) 개행을 \n으로 폴더 단위로 설정하는 방법
11375정성태11/28/201719067오류 유형: 434. Visual Studio로 ASP.NET 디버깅 중 System.Web.HttpException - Could not load type 오류
11374정성태11/27/201724166사물인터넷: 14. 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정 [1]
11373정성태11/27/201723153오류 유형: 433. Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
11372정성태11/25/201726131사물인터넷: 13. 윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법 [4]
11371정성태11/25/201719817오류 유형: 432. Hyper-V 가상 스위치 생성 시 Failed to connect Ethernet switch port 0x80070002 오류 발생
11370정성태11/25/201719822오류 유형: 431. Hyper-V의 Virtual Switch 생성 시 "External network" 목록에 특정 네트워크 어댑터 항목이 없는 경우
11369정성태11/25/201721787사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠) [1]
11368정성태11/25/201727421.NET Framework: 699. UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제 [2]파일 다운로드1
11367정성태11/25/201727487개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201719135오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
11365정성태11/25/201721379오류 유형: 429. 이벤트 로그 - User Policy could not be updated successfully
11364정성태11/24/201723331사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표) [2]
11363정성태11/23/201723355사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
11362정성태11/22/201719744오류 유형: 428. 윈도우 업데이트 KB4048953 - 0x800705b4 [2]
11361정성태11/22/201722547오류 유형: 427. 이벤트 로그 - Filter Manager failed to attach to volume '\Device\HarddiskVolume??' 0xC03A001C
11360정성태11/22/201722394오류 유형: 426. 이벤트 로그 - The kernel power manager has initiated a shutdown transition.
11359정성태11/16/201721902오류 유형: 425. 윈도우 10 Version 1709 (OS Build 16299.64) 업그레이드 시 발생한 문제 2가지
11358정성태11/15/201726693사물인터넷: 9. Visual Studio 2017에서 Raspberry Pi C++ 응용 프로그램 제작 [1]
... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...