Microsoft MVP성태의 닷넷 이야기
Graphics: 27. .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리 [링크 복사], [링크+제목 복사]
조회: 19390
글쓴 사람
정성태 (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)
12945정성태1/28/20226263오류 유형: 791. SQL 서버 로그인 시 localhost는 되고, 127.0.0.1로는 안 되는 문제
12944정성태1/28/20228626.NET Framework: 1143. C# - Entity Framework Core 6 개요
12943정성태1/27/20227538.NET Framework: 1142. .NET 5+로 포팅 시 플랫폼 호환성 경고 메시지(SYSLIB0006, SYSLIB0011, CA1416)파일 다운로드1
12942정성태1/27/20227808.NET Framework: 1141. XmlSerializer와 Dictionary 타입파일 다운로드1
12941정성태1/26/20229215오류 유형: 790. AKS/k8s - pod 상태가 Pending으로 지속되는 경우
12940정성태1/26/20226636오류 유형: 789. AKS에서 hpa에 따른 autoscale 기능이 동작하지 않는다면?
12939정성태1/25/20227312.NET Framework: 1140. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 MP3 오디오 파일 인코딩/디코딩하는 예제파일 다운로드1
12938정성태1/24/20229583개발 환경 구성: 633. Docker Desktop + k8s 환경에서 local 이미지를 사용하는 방법
12937정성태1/24/20227420.NET Framework: 1139. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 오디오(mp2) 인코딩하는 예제(encode_audio.c) [2]파일 다운로드1
12936정성태1/22/20227381.NET Framework: 1138. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 멀티미디어 파일의 메타데이터를 보여주는 예제(metadata.c)파일 다운로드1
12935정성태1/22/20227555.NET Framework: 1137. ffmpeg의 파일 해시 예제(ffhash.c)를 C#으로 포팅파일 다운로드1
12934정성태1/22/20227110오류 유형: 788. Warning C6262 Function uses '65564' bytes of stack: exceeds /analyze:stacksize '16384'. Consider moving some data to heap. [2]
12933정성태1/21/20227665.NET Framework: 1136. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 MP2 오디오 파일 디코딩 예제(decode_audio.c)파일 다운로드1
12932정성태1/20/20228114.NET Framework: 1135. C# - ffmpeg(FFmpeg.AutoGen)로 하드웨어 가속기를 이용한 비디오 디코딩 예제(hw_decode.c) [2]파일 다운로드1
12931정성태1/20/20226283개발 환경 구성: 632. ASP.NET Core 프로젝트를 AKS/k8s에 올리는 과정
12930정성태1/19/20226883개발 환경 구성: 631. AKS/k8s의 Volume에 파일 복사하는 방법
12929정성태1/19/20226668개발 환경 구성: 630. AKS/k8s의 Pod에 Volume 연결하는 방법
12928정성태1/18/20226815개발 환경 구성: 629. AKS/Kubernetes에서 호스팅 중인 pod에 shell(/bin/bash)로 진입하는 방법
12927정성태1/18/20226553개발 환경 구성: 628. AKS 환경에 응용 프로그램 배포 방법
12926정성태1/17/20227032오류 유형: 787. AKS - pod 배포 시 ErrImagePull/ImagePullBackOff 오류
12925정성태1/17/20227151개발 환경 구성: 627. AKS의 준비 단계 - ACR(Azure Container Registry)에 docker 이미지 배포
12924정성태1/15/20228616.NET Framework: 1134. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) [2]파일 다운로드1
12923정성태1/15/20227585개발 환경 구성: 626. ffmpeg.exe를 사용해 비디오 파일을 MPEG1 포맷으로 변경하는 방법
12922정성태1/14/20226634개발 환경 구성: 625. AKS - Azure Kubernetes Service 생성 및 SLO/SLA 변경 방법
12921정성태1/14/20225625개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/20226394오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
... 16  17  18  19  20  21  22  23  24  25  26  [27]  28  29  30  ...