Microsoft MVP성태의 닷넷 이야기
Graphics: 8. Unity Shader - Texture의 UV 좌표에 대응하는 Pixel 좌표 [링크 복사], [링크+제목 복사]
조회: 17373
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 13개 있습니다.)
Graphics: 2. Unity로 실습하는 Shader
; https://www.sysnet.pe.kr/2/0/11607

Graphics: 3. Unity로 실습하는 Shader (1) - 컬러 반전 및 상하/좌우 뒤집기
; https://www.sysnet.pe.kr/2/0/11608

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

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

Graphics: 6. Unity로 실습하는 Shader (4) - 퐁 셰이딩(phong shading)
; https://www.sysnet.pe.kr/2/0/11611

Graphics: 7. Unity로 실습하는 Shader (5) - Flat Shading
; https://www.sysnet.pe.kr/2/0/11613

Graphics: 8. Unity Shader - Texture의 UV 좌표에 대응하는 Pixel 좌표
; https://www.sysnet.pe.kr/2/0/11614

Graphics: 9. Unity Shader - 전역 변수의 초기화
; https://www.sysnet.pe.kr/2/0/11616

Graphics: 10. Unity로 실습하는 Shader (6) - Mosaic Shading
; https://www.sysnet.pe.kr/2/0/11619

Graphics: 11. Unity로 실습하는 Shader (7) - Blur (평균값, 가우스, 중간값) 필터
; https://www.sysnet.pe.kr/2/0/11620

Graphics: 12. Unity로 실습하는 Shader (8) - 다중 패스(Multi-Pass Shader)
; https://www.sysnet.pe.kr/2/0/11628

Graphics: 13. Unity로 실습하는 Shader (9) - 투명 배경이 있는 텍스처 입히기
; https://www.sysnet.pe.kr/2/0/11631

Graphics: 19. Unity로 실습하는 Shader (10) - 빌보드 구현
; https://www.sysnet.pe.kr/2/0/11641




Unity Shader - Texture의 UV 좌표에 대응하는 Pixel 좌표

간단하게 예를 들어서, 0 ~ 1 사이로 정규화되어 있는 UV 좌표계에서 0.1에 해당하는 texture의 pixel(x,y) 위치를 알고 싶다는 것입니다. 이것은 UV 좌표계의 의미를 알면 유추해 낼 수 있습니다.

가령, 가로 1024 * 세로 768 이미지의 texture를 (0,0) ~ (1,1) UV 좌표로 매핑한 경우 다음과 같은 의미를 갖게 됩니다.

u    pixel
0 -> 0
1 -> 1024

v    pixel
0 -> 0
1 -> 768

따라서, 다음과 같은 비율로 알아낼 수 있습니다.

u:x = 1:1024
v:y = 1:768

만약 그중에 (0.1, 0.7) uv 좌표 값을 가지고 있다면 이것을 pixel 위치로 환산하면 다음과 같이 계산할 수 있습니다.

0.1:x = 1:1024
x = 1024 * 0.1 = 102.4
   = width of texture * u

0.7:y = 1:768
y = 768 * 0.7 = 537.6
   = height of texture * v

uv(0.1, 0.7) == xy(102.4, 537.6) ≈ (102, 538)


실제로 그런지 Unity에서 지구본을 texture로 사용했던 예제를 보겠습니다.

Unity로 실습하는 Shader
; https://www.sysnet.pe.kr/2/0/11607

Shader "My/basicShader"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Pass
        {
            CGPROGRAM
    #pragma vertex vert
    #pragma fragment frag

    #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert(appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;

            fixed4 frag(v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                return col;
            }
            ENDCG
        }
    }
}

그러니까, 위의 tex2D 함수는 2048 * 1024 크기의 지구 이미지를 texture로 사용했을 때, uv 좌표에 해당하는 texture의 컬러를 구해주고 있는 것입니다.

fixed4 frag(v2f i) : SV_Target
{
    fixed4 col = tex2D(_MainTex, i.uv);
    return col;
}

만약, 현재의 i.uv가 가리키고 있는 좌표보다 u 값으로 +10 pixel에 해당하는 컬러 값을 사용하고 싶다면 다음과 같이 하면 됩니다.

fixed4 frag(v2f i) : SV_Target
{
    float uPerX = 1.0 / 2048; // 1 / width
    float vPerY = 1.0 / 1024; // 1 / height

    float uOffset = 10 * uPerX;
    float vOffset = 0 * vPerY;

    float2 nextUVOffset = float2(uOffset, vOffset);
    fixed4 col = tex2D(_MainTex, i.uv + nextUVOffset);

    return col;
}

저렇게 하면, 지구본이 +10 픽셀만큼 회전한 것처럼 보입니다. 또는, u 값으로 +2048 pixel을 준다면 어떻게 될까요?

float uOffset = 2048 * xPerU;

결국 제자리로 오기 때문에 화면에는 아무런 변화가 없습니다.




그런데, shader 코드에 2048, 1024이라고 하드 코딩을 하는 것이 좀 그렇군요. ^^ 이것을 없애려면 Properties 영역으로 옮겨 변수 처리를 하면 됩니다. 물론 그래도 되지만, Unity에서는 "_TexelSize"라는 접미사를 붙이면 해당 텍스처의 width, height를 담고 있는 값을 알아서 전달해 줍니다.

예를 들어, 위의 코드에서는 텍스처 변수 명이 "_MainTex"였으므로 다음과 같이 선언해 주면 됩니다.

float2 _MainTex_TexelSize;

그리고 그 변수의 값은 각각 다음과 같이 설정이 됩니다.

Accessing shader properties in Cg/HLSL
; https://docs.unity3d.com/Manual/SL-PropertiesInPrograms.html

x contains 1.0/width
y contains 1.0/height
z contains width
w contains height

결국 이를 반영하면 다음과 같이 하드 코딩 없이 작성할 수 있습니다.

fixed4 frag(v2f i) : SV_Target
{
    float uPerX = _MainTex_TexelSize.x;
    float vPerY = _MainTex_TexelSize.y;

    float uOffset = 10 * uPerX; // x축으로 +10 pixel 위치
    float vOffset = 10 * vPerY; // y축으로 +10 pixel 위치

    float2 nextUVOffset = float2(uOffset, vOffset);
    fixed4 col = tex2D(_MainTex, i.uv + nextUVOffset);

    return col;
}

float2 UVtoXY(float2 uv, float2 texelSize)
{
    return float2(uv.x / texelSize.x, uv.y / texelSize.y);
}

float2 XYtoUV(float2 pos, float2 texelSize)
{
    return float2(pos.x * texelSize.x, pos.y * texelSize.y);
}




다음의 링크를 보면,

D3D이용 2D출력시 마법의 숫자 -0.5 에 대하여  
; http://blog.daum.net/gamza-net/16

실수 보정을 하는데 아마 이 때문인지 다음의 답글을 보면,

How to get precise pixel values form a Texture2D using uv coordinates.
; https://answers.unity.com/questions/1106031/how-to-get-precise-pixel-values-for-a-texture2d-us.html

(0.5를 빼지 않고) 더하는 것이 나옵니다.

u = x / width + 0.5 / width;
v = y / height + 0.5 / height;

pixel shader에서 저 작업이 필요한지는... 혹시 아시는 분은 덧글 부탁드립니다. ^^




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







[최초 등록일: ]
[최종 수정일: 7/21/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)
13606정성태4/24/202465닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024322닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024338오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024565닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024795닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024837닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024846닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024862닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024884닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024864닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241049닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241050닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241068닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241079닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241217C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241193닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241078Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241150닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241262닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241168오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241328Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241112Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241060개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241195Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241454Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...