Get it on Google Play


Wm뮤 :: '분류 전체보기' 카테고리의 글 목록 (71 Page)

블로그 이미지
가끔 그림그리거나 3D모델링하거나
취미로 로봇만드는
전자과 게임프로그래머 (퇴사함)
2022.3.22f1 주로 사용
모카쨩
@Ahzkwid

Recent Comment

Archive


2020. 11. 12. 21:49 공학기술

 

 

보라색 출사각: 결과 약49도

 

빨간색 출사각 : 결과 약 45.6도

 

 

 

직접 프리즘으로 계측한 결과임 

'공학기술' 카테고리의 다른 글

전동킥보드 구매요령  (0) 2020.11.18
기계부품 자료 모음  (0) 2020.11.10
절전모드 해제 방지  (0) 2020.10.31
posted by 모카쨩
2020. 11. 12. 13:43 아두이노

rc522는 RFID모듈이다 2020년 기준 국내 1000~2000가격에 구할수 있다

 

 

NFC랑 RFID랑 다른것 같다. 뭔차인진 몰겄고 걍 작동만 되면 된다

 

 

 

 

다음 표를 보면서 핀을 넣는다

주의할점은 IRQ는 사용 안함이고 핀순서가 뒤죽박죽이기 때문에 기판에 인쇄된 글자를 보면서 해야한다

 

 

 

결과

 

 

 

카드의 값을 읽어올때는 DumpInfo예제를 쓴다

 

결과

 

 

PCD_Authenticate() failed: Error in communication. 에러는 일반적으로 암호화된 블록을 키없이 읽으려고 할때 발생한다.

읽기 키 기본값은 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF이고 키를 변경하면 키를 가진사람외에는 읽기 방지 할 수있다.

 

 

보통은 이걸 바꾼다

MFRC522::MIFARE_Key key;

void setup() {
    for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
    }
    }

 

 

A MIFARE PICC responded with NAK.

은 쓰기방지가 걸려있는거다. 다른 섹터, 혹은 블록을 참조해야한다고했는데 알고보니 트레일러가 잘못된거였다

 

 

 

 

함수모음

    //카드접촉검사
    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;

    //카드읽기가 정상인지 검사
    if ( ! mfrc522.PICC_ReadCardSerial())
        return;

 

 

데이터블록은 blockAddr/4*4+3이여야 한다

혹은 blockAddr-(blockAddr%4)+3

즉 1이면 3, 4이면7, 5여도 7 

    byte sector         = 1;
    byte sector2         = 0;
    
    byte blockAddr      = 1;
    byte dataBlock[]    = {
        0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
        0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
        0x09, 0x0a, 0xff, 0x0b, //  9, 10, 255, 11,
        0x0c, 0x0d, 0x0e, 0x0f  // 12, 13, 14, 15
    };
    byte trailerBlock   = blockAddr/4*4+3;

 

데이터시트

www.nxp.com/docs/en/data-sheet/MF1S50YYX_V1.pdf

 

0번섹터 0번블록은 UID등등의 값이 들어가있고 Manufacture Block이라고 한다

503번RFID는

0~3바이트는 NUID

500번RFID는

0~5바이트는 UID

 

각 섹터별 3번블록은 섹터정보가 있는지 함부로 값을쓰면 개박살난다

 

 

 

 


  byte sectorTrailerBuffer[16]={0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x07,0x80,0x69,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};

block=1;

      byte sectorTrailerIndex = block/4*4+3;
      
      
      //해당 블록에 액세스
      
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, sectorTrailerIndex, &key, &(mfrc522.uid));
      if (status == MFRC522::STATUS_OK) 
      {
        Serial.println(F("PCD_Authenticate() success: "));
      }
      else 
      {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      
      
      
  
  if(block==sectorTrailerIndex)
      {
      if(useAkey)
      {
//A값
[0 0 1]
  mfrc522.MIFARE_SetAccessBits(&sectorTrailerBuffer[6], 0, 0, 0, 1); 
      }
      else
      {
//B값
[0 1 1]
  mfrc522.MIFARE_SetAccessBits(&sectorTrailerBuffer[6], 3, 3, 3, 3); 
      }
      
  
        status = mfrc522.MIFARE_Write(block, sectorTrailerBuffer, 16);
      }
      else
      {
        status = mfrc522.MIFARE_Write(block, buffer, 16);
      }
      
  
    
    if (status == MFRC522::STATUS_OK) 
    {
      Serial.println(F("MIFARE_Write() success: "));
    }
    else 
    {
      Serial.print(F("MIFARE_Write() failed: "));
      Serial.println(mfrc522.GetStatusCodeName(status));
      return;
    }
  
  
  
  

'아두이노' 카테고리의 다른 글

byte to hex  (0) 2021.02.23
블루투스 테스트용 앱들  (0) 2020.08.01
블루투스 셋업용 코드  (0) 2020.07.31
posted by 모카쨩
2020. 11. 11. 20:19 Unity

 

 

 

UnityWebRequestMultimedia.GetAudioClip을 사용시 빌드플랫폼이 윈도우로 설정되어있으면 발생함

안드로이드나 애플로 돌리자

'Unity' 카테고리의 다른 글

Resource ID out of range in GetResource  (0) 2020.11.16
투명 렌더텍스처  (0) 2020.11.10
유니티 아틀라스 이미지 깨질때  (0) 2020.11.09
posted by 모카쨩
2020. 11. 10. 18:52 Unity

 

 

 

 

'Unity' 카테고리의 다른 글

Streaming of 'mpeg' on this platform is not supported  (0) 2020.11.11
유니티 아틀라스 이미지 깨질때  (0) 2020.11.09
이벤트 트리거  (0) 2020.10.29
posted by 모카쨩
2020. 11. 10. 15:57 공학기술

 

스트리퍼 볼트

 

 

 

무릎보조기

 

 

 

 

 

 

 

스프링 

굵기 2.5파이 : 양손으로 세게 눌러야 들어간다. 킥보드 서스펜션용으로써도 될것같다

 

 

 

 

타포린

방수포라고도 하며 흔히 천막에 쓰는 그 천을 말한다

 

 

 

덕트호스

후렉시블호스, 플렉시블호스라고도 하며 고깃집에 있는 그것

 

 

 

 

 

EVA폼

의상 제작에 사용

페파쿠라를 쓰면 된단다

https://gall.dcinside.com/board/view/?id=hit&no=17147 

 

 

플라베니아, 단프라 시트

플라스틱판중에서 튼튼함에 비해 가장 가볍고 가장 저렴하다

다만 쉽게 찌그러지기에 조심해서 써야함

 

 

 

 

 

포맥스

폼보드는 쉽게 부서지고 햇빛받으면 가루 날리는 단점이 있는 반면에

얘는 밀도가 매우 높아서 그럴일이 없다

사실상 경량화된 PVC판

커터칼로 자르려면 2T정도가 적절하고 3T부터는 톱같은걸 써야 겨우 잘린다

몰론 튼튼한건 3T부터 튼튼하다. 그런데 2T도 꽤 쓸만함

 

 

 

철지

고무자석에 붙일때 쓰는거

그냥 자석이 달라붙는 철판 정도로 보면 된다

자기장 차단용으로 쓸수 있긴한데 그럴일이 별로 없긴하다

 

 

 

 

종이디스플레이

https://gall.dcinside.com/board/view/?id=hit&no=17176 

 

 

 

 

 

 

 

'공학기술' 카테고리의 다른 글

굴절각  (0) 2020.11.12
절전모드 해제 방지  (0) 2020.10.31
mpu6050  (0) 2020.10.28
posted by 모카쨩
2020. 11. 9. 11:14 Unity

'Unity' 카테고리의 다른 글

투명 렌더텍스처  (0) 2020.11.10
이벤트 트리거  (0) 2020.10.29
유니티 내비게이션 navigation  (0) 2020.10.25
posted by 모카쨩
2020. 11. 4. 22:09 Unity/shader

 

 

거의 내 부스 상품을 만들기 위해서 만든 코드들이다

https://ahzkwid.booth.pm/

몇개는 개인작 하다가 만든정도

 

자주 쓰는 간단한 코드들만 적어놨다

 

 

 

두 값이 다른지 검사

if(!all(vec1 - vec2))
//위아래동일(all은 -1도 true로 반환하기 때문)
//(vec1 != vec2)
if(length(vec1 - vec2)<0.01) //가끔씩 미세한 변화로 인해 인식 안될때 사용

if(!((vec1.x==vec2.x)&&(vec1.y==vec2.y)&&(vec1.z==vec2.z)))

 

에미션

color.rgb = lerp(color.rgb,1 , _EmitionColor.rgb);

 

 

 

uv가 0~1을 벗어났는지 검사

v1

더보기
if (!all(uv.xy==saturate(uv.xy)))
{
    col.a = 0;
}

 

v2

col.a*=all(uv==saturate(uv));

 

 

 

벡터 검사

 

 

 

 

 

 

흘러가는 쉐이더 (흐르는)

Shader "Unlit/Backgrond"

{

Properties

{

_MainTex("Texture", 2D) = "white" {}

_Speed("Speed", Float) = 1

}

SubShader

{

Tags { "RenderType"="Opaque" }

LOD 100


Pass

{

CGPROGRAM

#pragma vertex vert

#pragma fragment frag

// make fog work

#pragma multi_compile_fog


#include "UnityCG.cginc"


struct appdata

{

float4 vertex : POSITION;

float2 uv : TEXCOORD0;

};


struct v2f

{

float2 uv : TEXCOORD0;

UNITY_FOG_COORDS(1)

float4 vertex : SV_POSITION;

};


sampler2D _MainTex;

float4 _MainTex_ST;

float _Speed;


v2f vert (appdata v)

{

v2f o;

o.vertex = UnityObjectToClipPos(v.vertex);

o.uv = TRANSFORM_TEX(v.uv, _MainTex);

UNITY_TRANSFER_FOG(o,o.vertex);

return o;

}


fixed4 frag (v2f i) : SV_Target

{

// sample the texture


i.uv.x = (i.uv.x + _Time.y* _Speed) % 1;
i.uv.y = (i.uv.y + _Time.y* _Speed) % 1;
if (i.uv.x < 0)
{
    i.uv.x += 1;
}
if (i.uv.y < 0)
{
    i.uv.y += 1;
}

fixed4 col = tex2D(_MainTex, i.uv);

// apply fog

UNITY_APPLY_FOG(i.fogCoord, col);

return col;

}

ENDCG

}

}

}

 

 

 

 

 

 

 

 

 

 

define

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #define _Board 0
            #define _Black 1
            #define _White 2

 

 

 

쉐이더에서 화면상의 좌표를 가져올때

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

uv에 담겨있음

 

 

 

이렇게 주면 스크린색상은 이렇게 나온다

col.r = i.grab_uv.x;
col.b = i.grab_uv.y;
col.g = 0;

 

 

		SubShader
		{
			GrabPass {"_GrabTexture" }
			Pass
			{
				sampler2D _GrabTexture;
				fixed4 frag(v2f i) : SV_Target
				{
					fixed4 colGrab = tex2D(_GrabTexture, i.uv.xy);
                }
            }
        }

그랩텍스처

모바일에선 프레임이 확떨어지니 주의

A31기준으로 60->50으로 떨어졌다

 

 

 

쉐이더 내부함수 공유

Shader "Unlit/DualPassUnlitShader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    CGINCLUDE
    #include "UnityCG.cginc"

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

    struct v2f
    {
        float2 uv : TEXCOORD0;
        UNITY_FOG_COORDS(1)
        float4 vertex : SV_POSITION;
    };

    sampler2D _MainTex;
    float4 _MainTex_ST;

    v2f vert(appdata v)
    {
        v2f o;
        o.vertex = UnityObjectToClipPos(v.vertex);
        o.uv = TRANSFORM_TEX(v.uv, _MainTex);
        return o;
    }
    fixed4 frag(v2f i) : SV_Target
    {
        // sample the texture
        fixed4 col = tex2D(_MainTex, i.uv);
        return col;
    }
    fixed4 frag2(v2f i) : SV_Target
    {
        // sample the texture
        fixed4 col = tex2D(_MainTex, i.uv);
        return col;
    }
    ENDCG
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            ENDCG
        }
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag2
            ENDCG
        }
    }
}

 

 

 

 

그림자생성코드 (vert frag용)

이 pass는 독립적이여야 한다(기존코드와 분리되어야 함)

Pass
{
	Tags {"LightMode" = "ShadowCaster"}

	CGPROGRAM
	#pragma vertex vert
	#pragma fragment frag
	#pragma multi_compile_shadowcaster
	#include "UnityCG.cginc"

	struct v2f {
		V2F_SHADOW_CASTER;
	};

	v2f vert(appdata_base v)
	{
		v2f o;
		TRANSFER_SHADOW_CASTER_NORMALOFFSET(o)
		return o;
	}

	float4 frag(v2f i) : SV_Target
	{
		SHADOW_CASTER_FRAGMENT(i)
	}
	ENDCG
}

 

근데 위에거 안 들어가도 그림자 생기는 잣갓은 경우가 있음

FallBack 들어가서 그렇다.

역으로 응용하면 쉐도우 캐스터 안 쓰고도 그림자 뽑아내는데 쓸수도

FallBack "Diffuse"

 

 

 

 

그림자생성코드 (serf용)

addshadow는 필수이고

target 3.0은 필수라고는 하는데 테스트는 안해봄

#pragma target 3.0
#pragma surface surf Standard addshadow fullforwardshadows

 

 

 

 

 

Blend연산 기본

보통 SubShader의 Tags아래에 들어간다

Blend SrcAlpha OneMinusSrcAlpha // Traditional transparency
Blend One OneMinusSrcAlpha // Premultiplied transparency
Blend One One // Additive
Blend OneMinusDstColor One // Soft Additive
Blend DstColor Zero // Multiplicative
Blend DstColor SrcColor // 2x Multiplicative

 

 

 

스프라이트 쉐이더, UI에도 사용함

Shader "UI/SpriteSample"
{
    Properties
    {
        [PerRendererData] _MainTex("Texture", 2D) = "white" {}
        _StencilComp("Stencil Comparison", Float) = 8
        _Stencil("Stencil ID", Float) = 0
        _StencilOp("Stencil Operation", Float) = 0
        _StencilWriteMask("Stencil Write Mask", Float) = 255
        _StencilReadMask("Stencil Read Mask", Float) = 255
        _ColorMask("Color Mask", Float) = 15
    }
    SubShader
    {
        Tags
        {
            "Queue" = "Transparent"
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
            "PreviewType" = "Plane"
            "CanUseSpriteAtlas" = "True"
        }
        LOD 100

        Cull Off
        Lighting Off
        ZWrite Off
//ZTest[unity_GUIZTestMode]
        Blend One OneMinusSrcAlpha
        
        
		Stencil
		{
			Ref[_Stencil]
			Comp[_StencilComp]
			Pass[_StencilOp]
			ReadMask[_StencilReadMask]
			WriteMask[_StencilWriteMask]
		}
		ColorMask[_ColorMask]
        
        
        
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            // make fog work
            #pragma multi_compile_fog

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
                fixed4 color : COLOR;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.color = v.color;
                UNITY_TRANSFER_FOG(o,o.vertex);
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                // sample the texture
                fixed4 col = tex2D(_MainTex, i.uv);
                col.rgb *= col.a * i.color.a;
                col.rgb *= i.color.rgb * i.color.a;
                /*
                위 두줄 잘 안되면 이거 사용
                col.a *= i.color.a;
                col.rgb *= col.a;
                */
                // apply fog
                //UNITY_APPLY_FOG(i.fogCoord, col);
                return col;
            }
            ENDCG
        }
    }
}

 

 

 

컬링모드

	Properties {
		[KeywordEnum(None,Front,Back)] _CullingMode ("Culling Mode", Float) = 2
	}

    SubShader {
		Cull [_CullingMode]
    }

 

 

항상 보이는 UI

Shader "ahzkwid/UI/AhzkwidUISimple" {
    Properties{
        _MainTex("MainTex", 2D) = "white" {}
        _Color("Main Color", Color) = (1,1,1,0)
        [KeywordEnum(None,Front,Back)] _CullingMode("Culling Mode", Float) = 2
    }
        SubShader{
            Tags {
            "RenderType" = "Opaque"
            "Queue" = "Geometry+3000"
            }

            Cull[_CullingMode]
            ZWrite off
            ZTest Always
            blend srcalpha oneminussrcalpha
            
            Pass{
                SetTexture[_MainTex]
                {
                    ConstantColor[_Color]
                    //Combine texture
                	Combine texture* primary DOUBLE, texture* constant
                }

            }

        }
}

 

컷아웃버전

Shader "ahzkwid/UI/AhzkwidCutOut" {
    Properties{
        _MainTex("MainTex", 2D) = "white" {}
        _Color("Main Color", Color) = (1,1,1,0)
        _Cutoff("Cutout offset", Range(0, 1)) = 0.5
        [KeywordEnum(None,Front,Back)] _CullingMode("Culling Mode", Float) = 2
        [KeywordEnum(Opaque,CutOut,TransParent)] _RenderingMode("Rendering Mode", Float) = 2
    }
        SubShader{
            Tags {
            "RenderType" = "Opaque"
            "Queue" = "Geometry+3000"
            }

Tags { "Queue" = "AlphaTest" "RenderType" = "TransparentCutout" "IgnoreProjector" = "True" } //이거가 있어야 스텐실이 적용되더라
            Cull[_CullingMode]
            ZWrite off
            ZTest Always
            blend srcalpha oneminussrcalpha
            
            Pass{
                AlphaTest Greater [_Cutoff]
                SetTexture[_MainTex]
                {
                    ConstantColor[_Color]
                    //Combine texture
                	Combine texture* constant
                }

            }

        }
}

 

컷아웃 UI (ugui)

Shader "ahzkwid/UI/AhzkwidUICutOut" {
    Properties{
        [PerRendererData] _MainTex("Texture", 2D) = "white" {}
        _StencilComp("Stencil Comparison", Float) = 8
        _Stencil("Stencil ID", Float) = 0
        _StencilOp("Stencil Operation", Float) = 0
        _StencilWriteMask("Stencil Write Mask", Float) = 255
        _StencilReadMask("Stencil Read Mask", Float) = 255
        _ColorMask("Color Mask", Float) = 15
        
        _Cutoff("Cutout offset", Range(0, 1)) = 0.5
        [KeywordEnum(None,Front,Back)] _CullingMode("Culling Mode", Float) = 2
        [KeywordEnum(Opaque,CutOut,TransParent)] _RenderingMode("Rendering Mode", Float) = 2
    }
        SubShader{
        
                    Stencil
                    {
                        Ref[_Stencil]
                        Comp[_StencilComp]
                        Pass[_StencilOp]
                        ReadMask[_StencilReadMask]
                        WriteMask[_StencilWriteMask]
                    }
                    ColorMask[_ColorMask]
        
            Tags
            {
                "PreviewType" = "Plane"
                "CanUseSpriteAtlas" = "True"
            }

Tags { "Queue" = "AlphaTest" "RenderType" = "TransparentCutout" "IgnoreProjector" = "True" } //이거가 있어야 스텐실이 적용되더라
            Cull[_CullingMode]
            ZWrite off
            ZTest Always
            blend srcalpha oneminussrcalpha
            
            Pass{
                AlphaTest Greater [_Cutoff]
                SetTexture[_MainTex]
                {
                	Combine texture* constant
                }

            }

        }
}

 

vert frag를 컷아웃버전으로 만들땐 아래를 추가한다

Tags { "Queue" = "AlphaTest" "RenderType" = "TransparentCutout" "IgnoreProjector" = "True" }
AlphaToMask On

 

 

 

다기능버전

Shader "ahzkwid/UI/AhzkwidUI" {
    Properties{
        _MainTex("MainTex", 2D) = "white" {}
        _Color("Main Color", Color) = (1,1,1,0)
        _Cutoff("Cutout offset", Range(0, 1)) = 0.5
        [KeywordEnum(None,Front,Back)] _CullingMode("Culling Mode", Float) = 2
        [KeywordEnum(Opaque,CutOut,TransParent)] _RenderingMode("Rendering Mode", Float) = 2
    }
    SubShader{
        Tags {
        "RenderType" = "Opaque"
        "Queue" = "Geometry+3000"
        }

        Cull[_CullingMode]
        ZWrite off
        ZTest Always
        blend srcalpha oneminussrcalpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                fixed4 color : COLOR;
                UNITY_FOG_COORDS(1)
                float4 vertex : SV_POSITION;
            };

            fixed4 _TintColor;
            float4 _Color;
            float _Cutoff;
            float _RenderingMode;
            sampler2D _MainTex;
            float4 _MainTex_ST;

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

            fixed4 frag(v2f i) : SV_Target
            {
                // sample the texture
                fixed4 col = tex2D(_MainTex, i.uv);
                col.rgb *= _Color.rgb * i.color.rgb * _Color.a * i.color.a;
                col.a *= _Color.a * i.color.a;
                if (_RenderingMode == 0)
                {
                    col.a = 1;
                }
                if (_RenderingMode == 1)
                {
                    if (col.a >= _Cutoff)
                    {
                        col.a = 1;
                    }
                    else
                    {
                        col.a = 0;
                    }

                }
                return col;
            }
            ENDCG
        }
        }
}

 

 

 

 

 

//서피스쉐이더

테셀레이션 샘플

 Shader "Tessellation Sample" {
        Properties {
            _Tess ("Tessellation", Range(1,32)) = 4
            _MainTex ("Base (RGB)", 2D) = "white" {}
            _DispTex ("Disp Texture", 2D) = "gray" {}
            _NormalMap ("Normalmap", 2D) = "bump" {}
            _Displacement ("Displacement", Range(0, 1.0)) = 0.3
            _Color ("Color", color) = (1,1,1,0)
            _SpecColor ("Spec color", color) = (0.5,0.5,0.5,0.5)
        }
        SubShader {
            Tags { "RenderType"="Opaque" }
            LOD 200
            
            CGPROGRAM
            #pragma surface surf Standard addshadow fullforwardshadows tessellate:tessFixed
            #pragma target 5.0

            float _Tess;

            float4 tessFixed()
            {
                return _Tess;
            }


            struct Input {
                float2 uv_MainTex;
            };

            sampler2D _MainTex;
            fixed4 _Color;

            void surf (Input IN, inout SurfaceOutputStandard o) {
                half4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
                o.Albedo = c.rgb;
            }
            ENDCG
        }
    }

 

 

 

텍스처 1픽셀 이동값과 텍스처 사이즈 

sampler2D _MainTex;
float4 _MainTex_TexelSize;

_MainTex_TexelSize.x = 1/width //따라서 1픽셀 가로

_MainTex_TexelSize.y = 1/height //따라서 1픽셀 세로

_MainTex_TexelSize.z = width 

_MainTex_TexelSize.w = height 

 

 

 

 

 

 

 

 

 

RGB2HSV

이거 만들었을때가 쉐이더 뉴비일때라 코드가 좀 지저분하다

23년에 코드에 문제있는거 발견하고 재수정함


float3  rgb2hsv ( float3 c )
{
    c=saturate(c);
    float3 HSV={0,1,1};
    float _min = c.r;
    float _med = c.g;
    float _max = c.b;
    float _t = 0;
    if(_min>_med)
    {
        _t=_min;
        _min=_med;
        _med=_t;
    }
    if(_min>_max)
    {
        _t=_min;
        _min=_max;
        _max=_t;
    }
    if(_med>_max)
    {
        _t=_med;
        _med=_max;
        _max=_t;
    }

    HSV.b=_max;

    float Delta  = _max - _min;
    if(_max>0)
    {
        HSV.g = Delta/_max;
    }

    if(Delta>0)
    {
        if  ( _max == c.r ) 
        {
            HSV.r = (c.g-c.b)/Delta;
        }
        else if ( _max == c.g ) 
        {
            HSV.r = 2.0 + (c.b-c.r)/Delta;
        }
        else
        {
            HSV.r = 4.0 + (c.r-c.g)/Delta;
        }
        if (HSV.r < 0)
        {
            HSV.r += 6.0;
        }
    }
    HSV.r /= 6.0;

    return HSV;
}

 

 

VR에서 화면분할할때

fixed4 frag (v2f i) : SV_Target
{	
	#if UNITY_SINGLE_PASS_STEREO
		i.uv.x/=2;
		if(unity_StereoEyeIndex>0)
		{
			i.uv.x+=0.5;
		}
	#endif

 

 

흘러가는 쉐이더

i.uv.x = (i.uv.x + _Time.y* _Speed) % 1;
i.uv.y = (i.uv.y + _Time.y* _Speed) % 1;
fixed4 col = tex2D(_MainTex, i.uv);

 

아웃라인

        half4 color = tex2D(_MainTex, IN.texcoord);


        float outlineColAlphaMax = 0;
        for (float x = -_OutLineWidth; x < _OutLineWidth; x += _MainTex_TexelSize.x)
        {
            for (float y = -_OutLineWidth; y < _OutLineWidth; y += _MainTex_TexelSize.y)
            {
                if (x*x+y*y < _OutLineWidth * _OutLineWidth)
                {
                    half4 colTarget = tex2D(_MainTex, IN.texcoord + float2(x, y));

                    float colAlpha = max(0,colTarget.a - color.a);
                    outlineColAlphaMax = max(colAlpha, outlineColAlphaMax);
                }
            }
        }
        color.rgb = _OutLineColor;
        color.a = outlineColAlphaMax;

 

 

디스토션 테스트

옛날에 짠거라 uv 포지션 다시 잡아줘야 하는데 언젠가 할듯

Shader "Ahzkwid/Distortion"
{
	Properties
	{
		[KeywordEnum(Default,Overlay)] _RenderMode("Render Mode", Float) = 0
		_MainTex("UI Texture", 2D) = "normal" {}
		[KeywordEnum(Off,Front,Back)] _CullingMode("Cull Mode", Float) = 0
		_Strength("Strength", range(0,1)) = 1.0
	}
		SubShader
		{
			Tags {
			"RenderType" = "TransparentCutout"
			"Queue" = "Transparent+2000"}
			AlphaToMask On
			ZWrite off
			LOD 100
			Cull[_CullingMode]
			GrabPass {"_GrabTexture" }
			Pass
			{
				blend srcalpha oneminussrcalpha
				CGPROGRAM
				#pragma vertex vert
				#pragma fragment frag
				#pragma multi_compile_fog
				#pragma target 4.0
				#pragma shader_feature PP_ON
				#pragma shader_feature LR_ON

				#include "UnityCG.cginc"
				sampler2D _GrabTexture;


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

				struct v2f
				{
					float2 uv : TEXCOORD0;
					UNITY_FOG_COORDS(1)
					float4 vertex : SV_POSITION;
					float4 distance : TEXCOORD2;
					float4 grab_uv : TEXCOORD3;
				};

				sampler2D _MainTex;
				float4 _MainTex_ST;
				float _Strength;
				float _RenderMode;

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

					//o.distance.x = o.vertex.w;
					o.uv = TRANSFORM_TEX(v.uv, _MainTex);
					//o.uv = o.vertex;
					//o.grab_uv = ComputeGrabScreenPos(o.vertex);
					{
						//수동계산
						o.grab_uv = o.vertex;
						//o.grab_uv.xy /= o.vertex.w;
						//o.grab_uv.x = (o.grab_uv.x + 1) / 2;
						//o.grab_uv.y = 1 - (o.grab_uv.y + 1) / 2;
					}
					/*
					if (_RenderMode > 0)
					{
						o.uv = float4(TRANSFORM_TEX(v.uv, _MainTex),1,1);
						o.vertex.xy = o.uv;
						o.vertex.xy -= 0.5;
						o.vertex.xy *= 2;
						o.vertex.y = -o.vertex.y;
						o.vertex.zw = 1;
					}
					*/
					#if UNITY_SINGLE_PASS_STEREO
					 o.grabUv.x /= 2;

					if (unity_StereoEyeIndex > 0)
					{
						o.grabUv.x += 0.5;
					}
					#endif



					UNITY_TRANSFER_FOG(o,o.vertex);
					return o;
				}

				fixed4 frag(v2f i) : SV_Target
				{
					fixed4 colMain = tex2D(_MainTex, i.uv.xy);
					float2 grabUv = i.grab_uv.xy;

					if (_RenderMode > 0)
					{
					}
					else
					{
						//수동계산
						grabUv.xy /= i.vertex.w;
						grabUv.x = (grabUv.x + 1) / 2;
						grabUv.y = 1 - (grabUv.y + 1) / 2;
					}



					float3 offset;
					//offset.rg = 0.5;
					offset.rg = 128.0/255.0;
					offset.b = 1;




					grabUv.x += (colMain.r- offset.r) * _Strength;
					grabUv.y += (colMain.g - offset.g) * _Strength;

					//grabUv.y += 0.1;

					fixed4 colGrab = tex2D(_GrabTexture, grabUv.xy);



					fixed4 col = colGrab;



					UNITY_APPLY_FOG(i.fogCoord, colMain);



					return col;
				}
				ENDCG
			}
		}
}

 

 

 

 

 

 

 

 

 

쉐이더용 LenPos

int2 LenPos(int _angle, int _len)
{

    int2 _pos = int2(0,0);
    switch (_angle)
    {
        case 0:
            _pos.x = _len;
            _pos.y = 0;
            break;
        case 45:
            _pos.x = _len;
            _pos.y = _len;
            break;
        case 90:
            _pos.x = 0;
            _pos.y = _len;
            break;
        case 135:
            _pos.x = -_len;
            _pos.y = +_len;
            break;
        case 180:
            _pos.x = -_len;
            _pos.y = 0;
            break;
        case 225:
            _pos.x = -_len;
            _pos.y = -_len;
            break;
        case 270:
            _pos.x = 0;
            _pos.y = -_len;
            break;
        case 315:
            _pos.x = _len;
            _pos.y = -_len;
            break;
    }
    return _pos;
}

 

 

스크린 사이즈

_ScreenParams.x //width
_ScreenParams.y //height

 

 

각도계산

float2 center = 0.5;
float2 pos = i.uv.xy-center;
float2 dir  =((atan2(pos.x,-pos.y)*2/3.14)/4+0.75)%1;

 

 

 

UI(UGUI)의 color가져오기

존나 자주 쓰는데 맨날 까먹음

그래서 그냥 얘만 따로 적어놨다

struct appdata
{
    fixed4 color : COLOR;
};

struct v2f
{
    fixed4 color : COLOR;
};

v2f vert (appdata v)
{
    v2f o;
    o.color = v.color;
    return o;
}

fixed4 frag (v2f i) : SV_Target
{
    return i.color.rgb;
}

 

UI(UGUI)쉐이더의 필수항목

SubShader
{
    ZWrite Off //없으면 자글자글하게 나온다
}

 

 

 

 

'Unity > shader' 카테고리의 다른 글

유니티 쉐이더 인스펙터  (0) 2021.02.21
스텐실  (0) 2021.01.20
Material Button GameStage Gray doesn't have _Stencil property  (0) 2020.06.29
posted by 모카쨩
2020. 10. 31. 18:40 공학기술

'공학기술' 카테고리의 다른 글

기계부품 자료 모음  (0) 2020.11.10
mpu6050  (0) 2020.10.28
발진기  (0) 2020.10.28
posted by 모카쨩

저사양 유저용 블로그 진입