summaryrefslogtreecommitdiffstats
path: root/Scripts/GrassGridBlit.shader
blob: f4dc872b727e2ac685b6be4fbb244b4f6ed5d501 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
Shader "yum_food/GrassGridBlit"
{
    Properties
    {
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        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;
            };

            // Grid parameters
            float3 _PlayerGridPos;    // Player's grid cell position (x, y, z)
            int3 _GridCount;          // Number of instances along each axis
            int3 _GridHalf;           // Half dimensions for centering around player
            int2 _TexDimensions;      // Texture width and height

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

            float4 frag (v2f i) : SV_Target
            {
                // Convert UV to pixel coordinates
                int2 pixelCoord = int2(i.uv.x * _TexDimensions.x, i.uv.y * _TexDimensions.y);

                // Convert pixel coordinate to instance index
                int instanceID = pixelCoord.x + pixelCoord.y * _TexDimensions.x;

                // Calculate total valid instances
                int totalInstances = _GridCount.x * _GridCount.y * _GridCount.z;

                // If this pixel is beyond valid instances, output invalid marker
                if (instanceID >= totalInstances) {
                    return float4(0, 0, 0, -1);  // Alpha = -1 marks invalid
                }

                // Convert instance index to local grid coordinates (0 to GridCount-1)
                int localX = instanceID % _GridCount.x;
                int localY = (instanceID / _GridCount.x) % _GridCount.y;
                int localZ = instanceID / (_GridCount.x * _GridCount.y);

                // Convert to world grid coordinates centered around player
                int worldX = _PlayerGridPos.x - _GridHalf.x + localX;
                int worldY = _PlayerGridPos.y - _GridHalf.y + localY;
                int worldZ = _PlayerGridPos.z - _GridHalf.z + localZ;

                // Store world grid coordinates in RGB channels, alpha = 0 marks valid
                return float4(worldX, worldY, worldZ, 0);
            }
            ENDCG
        }
    }
}