Skip to content

Commit aab66e4

Browse files
Procedural cubes with Vertex Shader
1 parent ade970c commit aab66e4

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

Diff for: DrawCubes.cs

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using UnityEngine;
2+
3+
public class DrawCubes : MonoBehaviour
4+
{
5+
public Shader shader;
6+
protected Material material;
7+
8+
void Start()
9+
{
10+
material = new Material(shader);
11+
}
12+
13+
void OnRenderObject()
14+
{
15+
material.SetPass(0);
16+
Graphics.DrawProcedural(MeshTopology.Triangles, 36 * 100000, 1);
17+
}
18+
}

Diff for: DrawCubes.shader

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
Shader "Draw Cubes"
2+
{
3+
Subshader
4+
{
5+
Tags { "RenderType" = "Transparent" "Queue" = "Transparent" }
6+
Pass
7+
{
8+
Cull Off
9+
ZWrite Off
10+
Blend SrcAlpha OneMinusSrcAlpha
11+
CGPROGRAM
12+
#pragma vertex VSMain
13+
#pragma fragment PSMain
14+
#pragma target 5.0
15+
16+
float3 hash(uint p)
17+
{
18+
p = 1103515245U*((p >> 1U)^(p));
19+
uint h32 = 1103515245U*((p)^(p>>3U));
20+
uint n = h32^(h32 >> 16);
21+
uint3 rz = uint3(n, n*16807U, n*48271U);
22+
return float3((rz >> 1) & uint3(0x7fffffffU,0x7fffffffU,0x7fffffffU))/float(0x7fffffff);
23+
}
24+
25+
void GenerateCube (inout uint id, inout float3 normal, inout float3 position, inout float instance)
26+
{
27+
float PI = 3.14159265;
28+
float q = floor((id-36.0*floor(id/36.0))/6.0);
29+
float s = q-3.0*floor(q/3.0);
30+
float inv = -2.0*step(2.5,q)+1.0;
31+
float f = id-6.0*floor(id/6.0);
32+
float t = f-floor(f/3.0);
33+
float a = (t-6.0*floor(t/6.0))*PI*0.5+PI*0.25;
34+
float3 p = float3(cos(a),0.707106781,sin(a))*inv;
35+
float x = (s-2.0*floor(s/2.0))*PI*0.5;
36+
float4x4 mat = float4x4(1,0,0,0,0,cos(x),sin(x),0,0,-sin(x),cos(x),0,0,0,0,1);
37+
float z = step(2.0,s)*PI*0.5;
38+
mat = mul(mat,float4x4(cos(z),-sin(z),0,0,sin(z),cos(z),0,0,0,0,1,0,0,0,0,1));
39+
position = (mul(float4(p,1.0),mat)).xyz;
40+
normal = (mul(float4(float3(0,1,0)*inv,0),mat)).xyz;
41+
instance = floor(id/36.0);
42+
}
43+
44+
float4 VSMain (uint id:SV_VertexID, out float3 normal:TEXCOORD0, out float3 position:TEXCOORD1, out float instance:TEXCOORD2) : SV_POSITION
45+
{
46+
GenerateCube (id, normal, position, instance);
47+
float3 random = hash(uint(instance))*256;
48+
position.xz += random.xz;
49+
position.y += (sin(_Time.g+random.y)*0.5+0.5)*256;
50+
return UnityObjectToClipPos(float4(position,1.0));
51+
}
52+
53+
float4 PSMain (float4 vertex:SV_POSITION, float3 normal:TEXCOORD0, float3 position:TEXCOORD1, float instance:TEXCOORD2) : SV_Target
54+
{
55+
float3 uv = position/256.0;
56+
return float4(lerp(float3(1,1,1),float3(0,0,1),uv.y),pow(uv.y,4.0));
57+
}
58+
ENDCG
59+
}
60+
61+
}
62+
}

0 commit comments

Comments
 (0)