Microsoft MVP성태의 닷넷 이야기
Graphics: 31. .NET으로 구현하는 OpenGL (6) - Texturing [링크 복사], [링크+제목 복사]
조회: 13306
글쓴 사람
정성태 (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 (6) - Texturing

아래의 글에 이어,

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

6회 강좌는,

OpenGL 3D Game Tutorial 6: Texturing
; https://youtu.be/SPt-aogu72A

3D 객체에 texture를 입히는 방법에 대해 설명하고 있습니다. OpenGL에서 texture는 이미지의 색상 데이터를 구하는 것에서 시작하는데, 아쉽게도 OpenGL 자체는 이미지 파일들에 대한 로드 방법을 제공하지 않습니다. 즉, 그 부분은 우리가 직접 구현해야 하는 것입니다. 가령, 그나마 가장 간단한 유형인 BMP 파일의 경우 아래의 글에 설명하는 데로,

Tutorial 5 : A Textured Cube
; http://www.opengl-tutorial.org/kr/beginners-tutorials/tutorial-5-a-textured-cube/

직접 이미지의 데이터를 로드해서 glGenTextures, glBindTexture, glTexImage2D 등의 함수를 이용해 사용할 수 있습니다. 그런데, 사실 저건 C/C++의 상황에서 그런 것이고 닷넷이라면 Bitmap 타입이 알아서 대표적인 이미지들에 대한 데이터 처리를 해주므로,

OpenGL C# (OpenTK) Load and Draw Image functions not working
; https://stackoverflow.com/questions/11645368/opengl-c-sharp-opentk-load-and-draw-image-functions-not-working

그나마 간단하게 OpenGL 리소스로 바인딩할 수 있습니다. 혹은, 다양한 이미지 파일을 OpenGL 용으로 바인딩해주는 라이브러리를 가져다 쓰는 것도 가능합니다. soil이 그런 용도로 사용할 수 있는 오픈 소스인데요,

soil 1.16.0 - Simple OpenGL Image Library 
; https://www.nuget.org/packages/soil/
; http://www.lonesock.net/soil.html

NuGet에서도 제공하긴 하지만 아쉽게도 해당 라이브러리는 C/C++ 용으로 닷넷에서는 사용할 수 없습니다. 대신... ^^ 제가 저 라이브러리를 .NET 용으로 래핑했으므로,

SOIL(Simple OpenGL Image Library) - Native DLL 및 .NET DLL 제공
; https://www.sysnet.pe.kr/2/0/11768
; https://www.nuget.org/packages/SoilDotnet

저걸 가져다 쓰시면 됩니다.

Install-Package SoilDotnet

자, 그럼 지난 5회 강좌의 소스 코드에 texture를 입히는 과정을 진행해 보겠습니다.




우선, 3D 객체의 정보를 담고 있는 Model에 texture 매핑 정보를 담을 UV 좌표 데이터를 연결해야 합니다.

// MainForm.cs

float[] _textureCoords =
{
    0,0, // V0
    0,1, // V1
    1,1, // V2
    1,0, // V3
};

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

    // ...[생략]...

    // 3D 객체에 _textureCoords UV 좌표 데이터를 추가
    _model = _loader.loadToVAO(_vertices, _textureCoords, _indices);

    // ...[생략]...
}

loadToVAO에서는 당연히 _textureCoords 데이터를 GPU 메모리에 올리고, VAO의 슬롯 하나에 UV 데이터를 바인딩합니다.

// Loader.cs

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

    bindIndicesBuffer(indices);
    storeDataInAttributeList(0, 3, positions); // Position 데이터를 VAO의 0번 슬롯에 할당
    storeDataInAttributeList(1, 2, textures);  // textures UV 매핑 데이터를 VAO의 1번 슬롯에 할당
    unbindVAO();

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

unsafe void storeDataInAttributeList(uint attributeNumber, int coordinateSize, 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, coordinateSize, VertexAttribType.Float, false, 0, IntPtr.Zero);

    Gl.BindBuffer(BufferTarget.ArrayBuffer, 0);
}

texture UV 매핑 데이터를 Model에 넣었으니 이제 해당 texture를 로드해야 합니다. 이를 위해 Texture 처리를 Loader 타입에 제공하고,

// Loader.cs

List _textures = new List();

public void CleanUp()
{
    Gl.DeleteVertexArrays(_vaos.ToArray());
    Gl.DeleteBuffers(_vbos.ToArray());
    Gl.DeleteTextures(_textures.ToArray());
}

public uint loadTexture(string fileName)
{
    string filePath = $".\\res\\{fileName}.png";

    uint tex2d_id = Soil.NET.WrapSOIL.load_OGL_texture(filePath, Soil.NET.WrapSOIL.SOIL_LOAD.AUTO, Soil.NET.WrapSOIL.SOIL_NEW.ID,
        Soil.NET.WrapSOIL.SOIL_FLAG.MIPMAPS | Soil.NET.WrapSOIL.SOIL_FLAG.NTSC_SAFE_RGB | Soil.NET.WrapSOIL.SOIL_FLAG.COMPRESS_TO_DXT);

    _textures.Add(tex2d_id);
    return tex2d_id;
}

Model에 입힐 Texture 자원의 바인딩 핸들을 보관할 ModelTexture 타입과,

// ModelTexture.cs

namespace GameApp
{
    public class ModelTexture
    {
        uint _textureID;
        public uint ID
        {
            get { return _textureID; }
        }

        public ModelTexture(uint id)
        {
            this._textureID = id;
        }
    }
}

Texture가 지정된 Model을 나타내는 TextureModel 타입을 만듭니다. (작명이 다소 혼란스럽지만 원 강좌의 내용을 그대로 따라 했습니다.)

// TextureModel.cs

namespace GameApp.Model
{
    public class TextureModel
    {
        RawModel _rawModel;
        public RawModel RawModel
        {
            get { return _rawModel; }
        }

        ModelTexture _texture;
        public ModelTexture Texture
        {
            get { return _texture; }
        }

        public TextureModel(RawModel model, ModelTexture texture)
        {
            this._rawModel = model;
            this._texture = texture;
        }
    }
}

이제 이것들을 통합해서 초기화하면 데이터는 모두 마련이 됩니다.

// MainForm.cs

ModelTexture _texture;
TextureModel _textureModel;

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

    // SOIL.NET 초기화
    bool result = Soil.NET.WrapSOIL.Initialize();
    if (result == false)
    {
        MessageBox.Show("SOIL: Not initialized: " + Soil.NET.WrapSOIL.GetSoilLastError());
        return;
    }

    _loader = new Loader();
    _renderer = new Renderer();
    _model = _loader.loadToVAO(_vertices, _textureCoords, _indices);
    _texture = new ModelTexture(_loader.loadTexture("image"));
    _textureModel = new TextureModel(_model, _texture);
    _shader = new StaticShader();
}

(잊지 말고 /res 폴더에 256x256 크기의 image.png 파일을 넣어둡니다.)




나머지는 이제 렌더링과 관련된 변경을 해야 합니다. Texture가 지정된 Model이 되었으므로 이제 Renderer 타입에서는 _textureModel을 렌더링할 수 있어야 합니다.

// MainForm.cs

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(_textureModel);
    _shader.Stop();

    _displayManager.updateDisplay();
}

따라서 Renderer의 Redner 메서드도 다음과 같이 바뀌게 됩니다.

public void Render(TextureModel textureModel)
{
    RawModel model = textureModel.RawModel;
    Gl.BindVertexArray(model.VaoID);
    Gl.EnableVertexAttribArray(0);
    Gl.EnableVertexAttribArray(1); // UV 매핑 데이터 Slot 활성

    Gl.ActiveTexture(TextureUnit.Texture0);
    Gl.BindTexture(TextureTarget.Texture2d, textureModel.Texture.ID);
    Gl.DrawElements(PrimitiveType.Triangles, model.VertexCount, DrawElementsType.UnsignedInt, IntPtr.Zero);

    Gl.DisableVertexAttribArray(0);
    Gl.DisableVertexAttribArray(1); // UV 매핑 데이터 Slot 비활성
    Gl.BindVertexArray(0);
}

끝입니다. 이렇게 변경하고 실행하면 다음과 같은 화면을 볼 수 있습니다.

opengl_tutorial_6_1.png

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




참고로 이번에도 역시, bindAttribute의 코드는 없애도 실행에는 아무런 지장이 없습니다.

// StaticShader.cs

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");
        // base.bindAttribute(1, "_textureCoords");
    }
}





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







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

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...
NoWriterDateCnt.TitleFile(s)
13272정성태2/27/20234216오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
13271정성태2/25/20234149오류 유형: 849. Sql Server Configuration Manager가 시작 메뉴에 없는 경우
13270정성태2/24/20233758.NET Framework: 2098. dotnet build에 /p 옵션을 적용 시 유의점
13269정성태2/23/20234295스크립트: 46. 파이썬 - uvicorn의 콘솔 출력을 UDP로 전송
13268정성태2/22/20234849개발 환경 구성: 667. WSL 2 내부에서 열고 있는 UDP 서버를 호스트 측에서 접속하는 방법
13267정성태2/21/20234774.NET Framework: 2097. C# - 비동기 소켓 사용 시 메모리 해제가 finalizer 단계에서 발생하는 사례파일 다운로드1
13266정성태2/20/20234376오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
13265정성태2/18/20234287.NET Framework: 2096. .NET Core/5+ - PublishSingleFile 유형에 대한 runtimeconfig.json 설정
13264정성태2/17/20235785스크립트: 45. 파이썬 - uvicorn 사용자 정의 Logger 작성
13263정성태2/16/20233918개발 환경 구성: 666. 최신 버전의 ilasm.exe/ildasm.exe 사용하는 방법
13262정성태2/15/20235006디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
13261정성태2/15/20234299Windows: 224. Visual Studio - 영문 폰트가 Fullwidth Latin Character로 바뀌는 문제
13260정성태2/14/20234083오류 유형: 847. ilasm.exe 컴파일 오류 - error : syntax error at token '-' in ... -inf
13259정성태2/14/20234209.NET Framework: 2095. C# - .NET5부터 도입된 CollectionsMarshal
13258정성태2/13/20234107오류 유형: 846. .NET Framework 4.8 Developer Pack 설치 실패 - 0x81f40001
13257정성태2/13/20234204.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [1]파일 다운로드1
13256정성태2/10/20235056개발 환경 구성: 665. WSL 2의 네트워크 통신 방법 - 두 번째 이야기
13255정성태2/10/20234350오류 유형: 845. gihub - windows2022 이미지에서 .NET Framework 4.5.2 미만의 프로젝트에 대한 빌드 오류
13254정성태2/10/20234262Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리
13253정성태2/9/20235040Windows: 222. C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법파일 다운로드1
13252정성태2/9/20233852오류 유형: 844. ssh로 명령어 수행 시 멈춤 현상
13251정성태2/8/20234318스크립트: 44. 파이썬의 3가지 스레드 ID
13250정성태2/8/20236114오류 유형: 843. System.InvalidOperationException - Unable to configure HTTPS endpoint
13249정성태2/7/20234927오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/20234048오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20234962VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...