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

아래의 글에 이어,

.NET으로 구현하는 OpenGL (9), (10)
; https://www.sysnet.pe.kr/2/0/11787

11회 강좌는,

OpenGL 3D Game Tutorial 11: Per-Pixel Lighting
; https://youtu.be/bcxX0R8nnDs

확산광(Diffuse lighting)에 대한 조명 연산을 다룹니다. (예제를 위한 리소스 파일(dragon.obj)을 다운로드합니다.)

그다음은 코드 변경인데요, 우선 조명 객체를 정의하고,

// Light.cs

namespace GameApp.Entities
{
    public class Light
    {
        Vertex3f _position;
        public Vertex3f Position
        {
            get { return _position; }
            set { _position = value; }
        }

        Vertex3f _colour;
        public Vertex3f Colour
        {
            get { return _colour; }
            set { _colour = value; }
        }

        public Light(Vertex3f position, Vertex3f colour)
        {
            this._position = position;
            this._colour = colour;
        }
    }
}

vertex shader로 광원의 위치를 알려준 후,

#version 400 core

/* layout(location = 0) */ in vec3 _position;
/* layout(location = 1) */ in vec2 _textureCoords;
/* layout(location = 2) */ in vec3 _normal;

out vec2 _pass_textureCoords;

uniform mat4 _transformationMatrix;
uniform mat4 _projectionMatrix;
uniform mat4 _viewMatrix;
uniform vec3 _lightPosition;

void main(void)
{
    gl_Position  = _projectionMatrix * _viewMatrix * _transformationMatrix * vec4(_position, 1.0);
    _pass_textureCoords = _textureCoords;
}

fragment shader로는 광원의 색을 알려줍니다.

#version 400 core

in vec2 _pass_textureCoords;

out vec4 out_Color;

uniform sampler2D textureSampler;
uniform vec3 _lightColour;

void main(void)
{
    out_Color = texture(textureSampler, _pass_textureCoords);
}

그렇다면 당연히 shader 코드에 변수 전달을 위해 StaticShader 타입을 변경해야 합니다.

// StaticShader.cs

public class StaticShader : ShaderProgram
{
    // ...[생략]...

    int _loc_lightPosition;
    int _loc_lightColour;

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

    protected override void getAllUniformLocations()
    {
        _loc_transformationMatrix  = base.getUniformLocation("_transformationMatrix");
        _loc_projectionMatrix = base.getUniformLocation("_projectionMatrix");
        _loc_viewMatrix = base.getUniformLocation("_viewMatrix");

        _loc_lightPosition = base.getUniformLocation("_lightPosition");
        _loc_lightColour = base.getUniformLocation("_lightColour");
    }

    public void loadLight(Light light)
    {
        base.loadVector(_loc_lightPosition, light.Position);
        base.loadVector(_loc_lightColour, light.Colour);
    }

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

이제 지난 강좌에서 obj 파일로부터 로드만 하고 사용하지 않은 normalsArray를 사용할 차례입니다. 법선 정보는 모델에 포함되므로 shader에 변수로 전달하는 것이 아닌, VAO를 통해서 전달한다고 합니다. 따라서 loadToVAO 코드가 법선 정보를 담도록 확장하게 됩니다.

// Loader.cs

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

    bindIndicesBuffer(indices);
    storeDataInAttributeList(0, 3, positions);
    storeDataInAttributeList(1, 2, textures);
    storeDataInAttributeList(2, 3, normals);
    unbindVAO();

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

물론 모델 로드 시에 법선 벡터를 함께 로드하도록 코드도 바꾸고,

// OBJLoader.cs

public static RawModel loadObjModel2(string fileName, Loader loader)
{
    string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "res", fileName + ".obj");

    AssimpContext importer = new AssimpContext();
    importer.SetConfig(new NormalSmoothingAngleConfig(66.0f));
    Scene scene = importer.ImportFile(filePath, PostProcessPreset.TargetRealTimeQuality | PostProcessSteps.FlipWindingOrder);

    if (scene == null || scene.HasMeshes == false)
    {
        return null;
    }

    float[] verticesArray = VerticesFromMesh(scene.Meshes[0]);
    float[] textureArray = TextureFromMesh(scene.Meshes[0]);
    int[] indicesArray = IndicesFromMesh(scene.Meshes[0]);
    float[] normalsArray = NormalsFromMesh(scene.Meshes[0]);

    return loader.loadToVAO(verticesArray, textureArray, normalsArray, indicesArray);
}

렌더링 시 EnableVertexAttribArray를 조정해 줍니다.

// Renderer.cs

public void Render(Entity entity, StaticShader shader)
{
    TextureModel model = entity.Model;
    RawModel rawModel = model.RawModel;

    Gl.BindVertexArray(rawModel.VaoID);
    Gl.EnableVertexAttribArray(0);
    Gl.EnableVertexAttribArray(1);
    Gl.EnableVertexAttribArray(2);

    Matrix4x4 transformationMatrix = Maths.createTransformationMatrix(entity.Position, entity.RotX, entity.RotY, entity.RotZ, entity.Scale);
    shader.loadTransformationMatrix(transformationMatrix);

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

    Gl.DisableVertexAttribArray(0);
    Gl.DisableVertexAttribArray(1);
    Gl.DisableVertexAttribArray(2);
    Gl.BindVertexArray(0);
}

자, 이제 shader 코드에서 전달받은 광원의 위치와 색상을 반영하면 됩니다.

#version 400 core

/* layout(location = 0) */ in vec3 _position;
/* layout(location = 1) */ in vec2 _textureCoords;
/* layout(location = 2) */ in vec3 _normal;

out vec2 _pass_textureCoords;
out vec3 _surfaceNormal;
out vec3 _toLightVector;

uniform mat4 _transformationMatrix;
uniform mat4 _projectionMatrix;
uniform mat4 _viewMatrix;
uniform vec3 _lightPosition;

void main(void)
{
    vec4 worldPosition = _transformationMatrix * vec4(_position, 1.0);
    gl_Position  = _projectionMatrix * _viewMatrix * worldPosition;
    _pass_textureCoords = _textureCoords;

    _surfaceNormal = (_transformationMatrix * vec4(_normal, 0.0)).xyz;
    _toLightVector = _lightPosition - worldPosition.xyz;
}

#version 400 core

in vec2 _pass_textureCoords;
in vec3 _surfaceNormal;
in vec3 _toLightVector;

out vec4 out_Color;

uniform sampler2D textureSampler;
uniform vec3 _lightColour;

void main(void)
{
    vec3 unitNormal = normalize(_surfaceNormal);
    vec3 unitLightVector = normalize(_toLightVector);

    float nDotl = dot(unitNormal, unitLightVector);
    float brightness = max(nDotl, 0.0);
    vec3 diffuse = brightness * _lightColour;

    out_Color = vec4(diffuse, 1.0) * texture(textureSampler, _pass_textureCoords);
}

사실 위의 코드 자체는 지난 글에서 다룬 것과 크게 다르지 않습니다.

Unity로 실습하는 Shader (2) - 고로 셰이딩(gouraud shading) + 퐁 모델(Phong model)
; https://www.sysnet.pe.kr/2/0/11609

마지막으로, 위의 모든 변화를 MainForm.cs에 적용하는 것으로 완성하면 됩니다.

// MainForm.cs

Camera _camera;
Entity _entity;
Light _light;

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

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

    _loader = new Loader();

    _model = OBJLoader.loadObjModel2("dragon", _loader);
    _staticModel = new TextureModel(_model, new ModelTexture(_loader.loadTexture("white"))); // white.png 파일은 그냥 흰색 바탕의 2의 배수 크기를 가진 이미지이면 됩니다.

    _staticModel = new TextureModel(_model, _texture);
    _shader = new StaticShader();
    _renderer = new Renderer(_shader, glControl.ClientSize.Width, glControl.ClientSize.Height);

    _camera = new Camera();
    _entity = new Entity(_staticModel, new Vertex3f(0, -4, -10), 0, 0, 0, 1);
    _light = new Light(new Vertex3f(0, 0, -20), new Vertex3f(1, 1, 1));
}

private void glControl_Render(object sender, OpenGL.GlControlEventArgs e)
{
    _renderer.Prepare();

    _shader.Start();
    {
        _shader.loadLight(_light);
        _shader.loadViewMatrix(_camera);
        _renderer.Render(_entity, _shader);
    }
    _shader.Stop();

    _displayManager.updateDisplay();
}




그런데, shader의 빛을 반영하는 코드를 빼고 그냥 모델과 텍스처만 로드하는 정도로만 코드를 변경해도 다음과 같이 Wireframe 식으로 나옵니다.
opengl_tutorial_11_1.png

강좌의 설명 글을 보면, white.png 텍스처 파일이 2의 n 승 크기인지 확인하라고 합니다. 그래도 그런 현상이 발생한다면 다음의 코드를 넣어보라고 하는데,

int value = (int)TextureMagFilter.Linear;
Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureMagFilter, ref value);
Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureMinFilter, ref value);

value = Gl.REPEAT;
Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureWrapS, ref value);
Gl.TexParameteri(TextureTarget.Texture2d, TextureParameterName.TextureWrapT, ref value);

조금 나아지긴 했지만 여전히 아래와 같이 완벽하게 제거되지 않은 모습으로 나옵니다.

opengl_tutorial_11_2.png

어쩔 수 없습니다. 어쨌든 이대로 진행해서 빛을 반영하는 코드를 다시 넣어 보면 이젠 다음과 같이 나옵니다.

opengl_tutorial_11_3.png

너무 어둡군요. ^^ 보정으로 다음과 같이 0.3 정도 더하면 좀 더 밝아지지만,

out_Color = (vec4(diffuse, 1.0) + 0.3) * texture(textureSampler, _pass_textureCoords);

아래와 같이 그다지 멋이 없게 음영 처리가 됩니다.

opengl_tutorial_11_4.png

아마도 모델의 크기가 커서 조명 위치가 용의 안쪽으로 들어간 듯한데요, 그냥 하늘에서 태양을 비춘다고 여기며 Light의 좌표를 y-축으로 올리고 나면,

opengl_tutorial_11_5.png

이제서야 좀 근사하게 음영 처리가 되었습니다. ^^ (그래도 화면을 키워보면 처음의 wireframe 선이 두드러지게 보입니다. 혹시 해결 방법을 아시는 분은 덧글 부탁드립니다. ^^)

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




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







[최초 등록일: ]
[최종 수정일: 12/11/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)
13551정성태2/12/20242016닷넷: 2213. ASP.NET/Core 웹 응용 프로그램 - 2차 스레드의 예외로 인한 비정상 종료
13550정성태2/11/20242107Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
13549정성태2/3/20242477개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
13548정성태2/1/20242308개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242056개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241896Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241828닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241846오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241824Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241876오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241921VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242051Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242145개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242213닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242268닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242372닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242206닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242038닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242233닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242141닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242024닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242010닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241894닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242032Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20241959오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242048닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...