성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>.NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리</h1> <p> 제가 ^^ 게임 프로그래머는 아니지만, 좋은 OpenGL 강좌가 있길래 따라 해 봤습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > TheThinMatrix/OpenGL-Tutorial-1 ; <a target='tab' href='https://github.com/TheThinMatrix/OpenGL-Tutorial-1'>https://github.com/TheThinMatrix/OpenGL-Tutorial-1</a> OpenGL 3D Game Tutorial 1: The Display ; <a target='tab' href='https://www.youtube.com/watch?v=VS8wlS9hF8E'>https://www.youtube.com/watch?v=VS8wlS9hF8E</a> </pre> <br /> 위의 강좌는 Java로 하고 있지만 1편의 개발 환경 구성을 제외하고는 대부분 닷넷에서도 그대로 따라 할 수 있습니다. (아니, 그럴 것 같습니다. ^^) 닷넷으로 하는 경우, 저 강좌의 1편은 자바 특화 환경이라 굳이 볼 필요가 없습니다. 닷넷은, 닷넷에 맞게 구성해야 하는데 우선 C# 프로젝트에서 NuGet을 이용해 다음의 패키지를 설치합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > OpenGL.Net ; <a target='tab' href='https://github.com/luca-piccioni/OpenGL.Net'>https://github.com/luca-piccioni/OpenGL.Net</a> </pre> <br /> 이 글에서는 Windows Forms 응용 프로그램으로 호스팅할 것이므로, 다음의 3개 정도만 추가하면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Install-Package OpenGL.Net Install-Package OpenGL.Net.Math Install-Package OpenGL.Net.WinForms </pre> <br /> 그런 다음, MainForm에 "Toolbox"에 있는 OpenGL.Net.WinForms의 "GlControl"을 얹어 놓습니다.<br /> <br /> <img alt='opengl_tutorial_1_0.png' src='/SysWebRes/bbs/opengl_tutorial_1_0.png' /><br /> <br /> 해당 GlControl의 속성 창을 이용해 다음의 4가지 이벤트를 구독하고,<br /> <br /> <ul> <li>ContextCreated</li> <li>ContextDestroying</li> <li>ContextUpdate</li> <li>Render</li> </ul> <br /> "Animation" 속성 값을 "true"로 변경합니다<br /> <br /> 다시 말해, InitializeComponent (또는 그냥 MainForm의 생성자) 등의 메서드 안에 다음과 같은 코드가 추가되어 있으면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > private void InitializeComponent() { this.glControl = new OpenGL.GlControl(); this.SuspendLayout(); // // glControl // <span style='color: blue; font-weight: bold'>this.glControl.Animation = true;</span> 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; <span style='color: blue; font-weight: bold'>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);</span> // // 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); } </pre> <br /> 이하 나머지는, 일단은 기본 프로젝트 구성이 목적이니 그냥 기본에 속한 이벤트 핸들러 코드만 작성하겠습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Gl.DebugProc _debugProc; private void <span style='color: blue; font-weight: bold'>glControl_ContextCreated</span>(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 <span style='color: blue; font-weight: bold'>glControl_ContextUpdate</span>(object sender, GlControlEventArgs e) { } private void <span style='color: blue; font-weight: bold'>glControl_ContextDestroying</span>(object sender, GlControlEventArgs e) { } private void <span style='color: blue; font-weight: bold'>glControl_Render</span>(object sender, OpenGL.GlControlEventArgs e) { Control senderControl = (Control)sender; Gl.Viewport(0, 0, senderControl.ClientSize.Width, senderControl.ClientSize.Height); } </pre> <br /> 위의 변경 사항들은 원래의 OpenGL.NET 예제에 있는 것을 보고 베낀 것입니다. ^^ 좀 더 자세한 예제가 궁금하다면 다음을 참고하시고.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > OpenGL.Net/Samples/HelloTriangle/ ; <a target='tab' href='https://github.com/luca-piccioni/OpenGL.Net/tree/master/Samples/HelloTriangle'>https://github.com/luca-piccioni/OpenGL.Net/tree/master/Samples/HelloTriangle</a> </pre> <br /> <hr style='width: 50%' /><br /> <br /> 위의 구조에 "<a target='tab' href='https://www.youtube.com/watch?v=VS8wlS9hF8E'>OpenGL 3D Game Tutorial 1: The Display</a>" 강좌의 DisplayManager 타입을,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // DisplayManager.cs using OpenGL; using System; namespace GameApp { public class DisplayManager { public void createDisplay() { } public void updateDisplay() { } public void closeDisplay() { } } } </pre> <br /> 굳이 끼워 맞추자면 각각 ContextCreated, ContextUpdate, Render 이벤트 핸들러에서 다음과 같이 호출하는 식으로 작성할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 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() { } } } </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 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(); } </pre> <br /> 그래도 이렇게만 하고 실행하면 너무 심심하니, Render 메서드에 다음과 같은 정도의 내용만 추가해 보겠습니다. (게임 개발자가 아니라서 ^^ 더 멋있는 예제를 추가할 수가 없군요.)<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > <span style='color: blue; font-weight: bold'>Random _random = new Random(Environment.TickCount);</span> private unsafe void glControl_Render(object sender, OpenGL.GlControlEventArgs e) { Control senderControl = (Control)sender; Gl.Viewport(0, 0, senderControl.ClientSize.Width, senderControl.ClientSize.Height); <span style='color: blue; font-weight: bold'>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); }</span> _displayManager.updateDisplay(); } </pre> <br /> 이렇게 하고 실행하면 좌측 하단에 지글(?)거리는 화면을 볼 수 있습니다.<br /> <br /> <img alt='opengl_tutorial_1_1.png' src='/SysWebRes/bbs/opengl_tutorial_1_1.png' /><br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1395&boardid=331301885'>첨부 파일은 이 글의 예제 프로젝트</a>를 포함합니다.)<br /> <br /> 그나저나... DirectX뿐만 아니라, OpenGL이 의외로 닷넷에서도 매끄럽게 잘 연동이 되어 놀랐습니다. ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 참고로 MainForm 생성 시 <a target='tab' href='http://www.sysnet.pe.kr/2/0/510'>1st-chance 예외</a>로 꼭 System.InvalidOperationException이 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 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 </pre> <br /> 무시하고 지나가면 되는데, System.InvalidOperationException 예외가 1st-chance 발생 시 멈추도록 설정되어 있다면 Visual Studio로 디버깅 시 무조건 한번 걸리게 되므로 <a target='tab' href='http://www.sysnet.pe.kr/2/0/510'>"Debug" / "Exceptions..." 메뉴를 이용해 "thrown"으로 설정된 것을 해제</a>해야 합니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
8398
(왼쪽의 숫자를 입력해야 합니다.)