Microsoft MVP성태의 닷넷 이야기
Graphics: 27. .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리 [링크 복사], [링크+제목 복사]
조회: 19403
글쓴 사람
정성태 (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 (1) - OpenGL.Net 라이브러리

제가 ^^ 게임 프로그래머는 아니지만, 좋은 OpenGL 강좌가 있길래 따라 해 봤습니다.

TheThinMatrix/OpenGL-Tutorial-1
; https://github.com/TheThinMatrix/OpenGL-Tutorial-1

OpenGL 3D Game Tutorial 1: The Display
; https://www.youtube.com/watch?v=VS8wlS9hF8E

위의 강좌는 Java로 하고 있지만 1편의 개발 환경 구성을 제외하고는 대부분 닷넷에서도 그대로 따라 할 수 있습니다. (아니, 그럴 것 같습니다. ^^) 닷넷으로 하는 경우, 저 강좌의 1편은 자바 특화 환경이라 굳이 볼 필요가 없습니다. 닷넷은, 닷넷에 맞게 구성해야 하는데 우선 C# 프로젝트에서 NuGet을 이용해 다음의 패키지를 설치합니다.

OpenGL.Net
; https://github.com/luca-piccioni/OpenGL.Net

이 글에서는 Windows Forms 응용 프로그램으로 호스팅할 것이므로, 다음의 3개 정도만 추가하면 됩니다.

Install-Package OpenGL.Net
Install-Package OpenGL.Net.Math
Install-Package OpenGL.Net.WinForms

그런 다음, MainForm에 "Toolbox"에 있는 OpenGL.Net.WinForms의 "GlControl"을 얹어 놓습니다.

opengl_tutorial_1_0.png

해당 GlControl의 속성 창을 이용해 다음의 4가지 이벤트를 구독하고,

  • ContextCreated
  • ContextDestroying
  • ContextUpdate
  • Render

"Animation" 속성 값을 "true"로 변경합니다

다시 말해, InitializeComponent (또는 그냥 MainForm의 생성자) 등의 메서드 안에 다음과 같은 코드가 추가되어 있으면 됩니다.

private void InitializeComponent()
{
    this.glControl = new OpenGL.GlControl();
    this.SuspendLayout();
    // 
    // glControl
    // 
    this.glControl.Animation = true;
    this.glControl.AnimationTimer = false;
    this.glControl.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
    this.glControl.ColorBits = ((uint)(24u));
    this.glControl.DepthBits = ((uint)(0u));
    this.glControl.Dock = System.Windows.Forms.DockStyle.Fill;
    this.glControl.Location = new System.Drawing.Point(0, 0);
    this.glControl.MultisampleBits = ((uint)(0u));
    this.glControl.Name = "glControl";
    this.glControl.Size = new System.Drawing.Size(581, 270);
    this.glControl.StencilBits = ((uint)(0u));
    this.glControl.TabIndex = 0;
    this.glControl.ContextCreated += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glControl_ContextCreated);
    this.glControl.ContextDestroying += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glControl_ContextDestroying);
    this.glControl.ContextUpdate += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glControl_ContextUpdate);
    this.glControl.Render += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glControl_Render);
    // 
    // MainForm
    // 
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(581, 270);
    this.Controls.Add(this.glControl);
    this.Name = "MainForm";
    this.Text = "MainForm";
    this.ResumeLayout(false);
}

이하 나머지는, 일단은 기본 프로젝트 구성이 목적이니 그냥 기본에 속한 이벤트 핸들러 코드만 작성하겠습니다.

Gl.DebugProc _debugProc;

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

    if (Gl.CurrentExtensions != null && Gl.CurrentExtensions.DebugOutput_ARB)
    {
        Gl.DebugMessageCallback(_debugProc, null);
        Gl.DebugMessageControl(Gl.DebugSource.DontCare, Gl.DebugType.DontCare, Gl.DebugSeverity.DontCare, 0, null, true);
    }

    if (Gl.CurrentVersion != null && Gl.CurrentVersion.Api == KhronosVersion.ApiGl && glControl.MultisampleBits > 0)
    {
        Gl.Enable(EnableCap.Multisample);
    }
}

private void GLDebugMessageCallbackProc(Gl.DebugSource source, Gl.DebugType type, uint id, Gl.DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
{
    string strMessage;

    unsafe
    {
        strMessage = Encoding.ASCII.GetString((byte*)message.ToPointer(), length);
    }

    Debug.WriteLine($"{source}, {type}, {severity}: {strMessage}");
}

private void glControl_ContextUpdate(object sender, GlControlEventArgs e)
{
}

private void glControl_ContextDestroying(object sender, GlControlEventArgs e)
{
}

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

위의 변경 사항들은 원래의 OpenGL.NET 예제에 있는 것을 보고 베낀 것입니다. ^^ 좀 더 자세한 예제가 궁금하다면 다음을 참고하시고.

OpenGL.Net/Samples/HelloTriangle/
; https://github.com/luca-piccioni/OpenGL.Net/tree/master/Samples/HelloTriangle




위의 구조에 "OpenGL 3D Game Tutorial 1: The Display" 강좌의 DisplayManager 타입을,

// DisplayManager.cs

using OpenGL;
using System;

namespace GameApp
{
    public class DisplayManager
    {
        public void createDisplay()
        {
        }

        public void updateDisplay()
        {
        }

        public void closeDisplay()
        {
        }
    }
}

굳이 끼워 맞추자면 각각 ContextCreated, ContextUpdate, Render 이벤트 핸들러에서 다음과 같이 호출하는 식으로 작성할 수 있습니다.

using Khronos;
using OpenGL;
using System;
using System.Diagnostics;
using System.Text;

namespace GameApp
{
    public class DisplayManager
    {
        GlControl _glControl;
        Gl.DebugProc _debugProc;

        public void createDisplay(GlControl glControl)
        {
            _debugProc = GLDebugMessageCallbackProc;
            _glControl = glControl;

            if (Gl.CurrentExtensions != null && Gl.CurrentExtensions.DebugOutput_ARB)
            {
                Gl.DebugMessageCallback(_debugProc, null);
                Gl.DebugMessageControl(Gl.DebugSource.DontCare, Gl.DebugType.DontCare, Gl.DebugSeverity.DontCare, 0, null, true);
            }

            if (Gl.CurrentVersion != null && Gl.CurrentVersion.Api == KhronosVersion.ApiGl && glControl.MultisampleBits > 0)
            {
                Gl.Enable(EnableCap.Multisample);
            }
        }

        private void GLDebugMessageCallbackProc(Gl.DebugSource source, Gl.DebugType type, uint id, Gl.DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
        {
            string strMessage;

            unsafe
            {
                strMessage = Encoding.ASCII.GetString((byte*)message.ToPointer(), length);
            }

            Debug.WriteLine($"{source}, {type}, {severity}: {strMessage}");
        }

        public unsafe void updateDisplay()
        {
        }

        public void closeDisplay()
        {
        }
    }
}

GlControl _glControl;

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

private void glControl_ContextDestroying(object sender, GlControlEventArgs e)
{
    _displayManager.closeDisplay();
}

private void glControl_Render(object sender, OpenGL.GlControlEventArgs e)
{
    // ...[생략]...

    _displayManager.updateDisplay();
}

그래도 이렇게만 하고 실행하면 너무 심심하니, Render 메서드에 다음과 같은 정도의 내용만 추가해 보겠습니다. (게임 개발자가 아니라서 ^^ 더 멋있는 예제를 추가할 수가 없군요.)

Random _random = new Random(Environment.TickCount);

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

    int w = 200;
    int h = 200;
    uint* n = stackalloc uint[w * h * 3];

    {
        Gl.ClearColor(0.0f, 0.0f, 1.0f, 1.0f);
        Gl.Clear(ClearBufferMask.ColorBufferBit);

        for (int i = 0; i < (w * h * 3); i++)
        {
            *(n + i) = (uint)_random.Next(255) * 255u * 255u * 255u;
        }

        IntPtr ptr = new IntPtr(n);
        Gl.DrawPixels(w, h, PixelFormat.Bgr, PixelType.UnsignedInt, ptr);
    }

    _displayManager.updateDisplay();
}

이렇게 하고 실행하면 좌측 하단에 지글(?)거리는 화면을 볼 수 있습니다.

opengl_tutorial_1_1.png

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

그나저나... DirectX뿐만 아니라, OpenGL이 의외로 닷넷에서도 매끄럽게 잘 연동이 되어 놀랐습니다. ^^




참고로 MainForm 생성 시 1st-chance 예외로 꼭 System.InvalidOperationException이 발생합니다.

System.InvalidOperationException
  HResult=0x80131509
  Message=unable to load library at libbcm_host.so
  Source=OpenGL.Net
  StackTrace:
   at Khronos.GetProcAddressWindows.GetLibraryHandle(String libraryPath) in C:\OpenGL.Net\Khronos.Net\GetProcAddressOS.cs:line 304

Inner Exception 1:
Win32Exception: The specified module could not be found

무시하고 지나가면 되는데, System.InvalidOperationException 예외가 1st-chance 발생 시 멈추도록 설정되어 있다면 Visual Studio로 디버깅 시 무조건 한번 걸리게 되므로 "Debug" / "Exceptions..." 메뉴를 이용해 "thrown"으로 설정된 것을 해제해야 합니다.




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







[최초 등록일: ]
[최종 수정일: 11/21/2020]

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

비밀번호

댓글 작성자
 



2021-03-26 09시06분
dotnet/Silk.NET - high-speed .NET multimedia, graphics, and compute; providing bindings to popular low-level APIs such as OpenGL, OpenCL, OpenAL, OpenXR, GLFW, SDL, Vulkan, Assimp, and DirectX.
; https://github.com/dotnet/Silk.NET
정성태
2022-07-22 09시14분
STRIDE - Open-source C# Game Engine
; https://www.stride3d.net/

On .NET Live - Taking .NET game development in Stride
; https://www.youtube.com/watch?v=J6g5y8m26zs&ab_channel=dotNET

Graph3D: A Windows.Forms Render Control in C#
; https://www.codeproject.com/Articles/5293980/Graph3D-A-Windows-Forms-Render-Control-in-Csharp
정성태
2023-06-27 08시43분
ComputeSharp 2.0 - DirextX 12 및 D2D1으로 GPU에서 C#을 쉽게 실행
; https://forum.dotnetdev.kr/t/computesharp-2-0-dirextx-12-d2d1-gpu-c/7498
정성태

... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13097정성태7/12/20225460오류 유형: 817. Golang - binary.Read: invalid type int32
13096정성태7/8/20228223.NET Framework: 2030. C# 11 - UTF-8 문자열 리터럴
13095정성태7/7/20226305Windows: 208. AD 도메인에 참여하지 않은 컴퓨터에서 Kerberos 인증을 사용하는 방법
13094정성태7/6/20226001오류 유형: 816. Golang - "short write" 오류 원인
13093정성태7/5/20226932.NET Framework: 2029. C# - HttpWebRequest로 localhost 접속 시 2초 이상 지연
13092정성태7/3/20227866.NET Framework: 2028. C# - HttpWebRequest의 POST 동작 방식파일 다운로드1
13091정성태7/3/20226687.NET Framework: 2027. C# - IPv4, IPv6를 모두 지원하는 서버 소켓 생성 방법
13090정성태6/29/20225816오류 유형: 815. PyPI에 업로드한 패키지가 반영이 안 되는 경우
13089정성태6/28/20226301개발 환경 구성: 646. HOSTS 파일 변경 시 Edge 브라우저에 반영하는 방법
13088정성태6/27/20225424개발 환경 구성: 645. "Developer Command Prompt for VS 2022" 명령행 환경의 폰트를 바꾸는 방법
13087정성태6/23/20228378스크립트: 41. 파이썬 - FastAPI / uvicorn 호스팅 환경에서 asyncio 사용하는 방법 [1]
13086정성태6/22/20227795.NET Framework: 2026. C# 11 - 문자열 보간 개선 2가지파일 다운로드1
13085정성태6/22/20227860.NET Framework: 2025. C# 11 - 원시 문자열 리터럴(raw string literals)파일 다운로드1
13084정성태6/21/20226472개발 환경 구성: 644. Windows - 파이썬 2.7을 msi 설치 없이 구성하는 방법
13083정성태6/20/20227056.NET Framework: 2024. .NET 7에 도입된 GC의 메모리 해제에 대한 segment와 region의 차이점 [2]
13082정성태6/19/20226116.NET Framework: 2023. C# - Process의 I/O 사용량을 보여주는 GetProcessIoCounters Win32 API파일 다운로드1
13081정성태6/17/20226196.NET Framework: 2022. C# - .NET 7 Preview 5 신규 기능 - System.IO.Stream ReadExactly / ReadAtLeast파일 다운로드1
13080정성태6/17/20226806개발 환경 구성: 643. Visual Studio 2022 17.2 버전에서 C# 11 또는 .NET 7.0 preview 적용
13079정성태6/17/20224554오류 유형: 814. 파이썬 - Error: The file/path provided (...) does not appear to exist
13078정성태6/16/20226582.NET Framework: 2021. WPF - UI Thread와 Render Thread파일 다운로드1
13077정성태6/15/20226905스크립트: 40. 파이썬 - PostgreSQL 환경 구성
13075정성태6/15/20225860Linux: 50. Linux - apt와 apt-get의 차이 [2]
13074정성태6/13/20226161.NET Framework: 2020. C# - NTFS 파일에 사용자 정의 속성값 추가하는 방법파일 다운로드1
13073정성태6/12/20226356Windows: 207. Windows Server 2022에 도입된 WSL 2
13072정성태6/10/20226667Linux: 49. Linux - ls 명령어로 출력되는 디렉터리 색상 변경 방법
13071정성태6/9/20227247스크립트: 39. Python에서 cx_Oracle 환경 구성
... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...