1
+ //In Unity3D editor, add 3D Object/Quad to Main Camera, then bind material with shader to the quad. Set quad position at (x=0 ; y=0; z=0.4;). Apply fly script to the camera. Play.
2
+ Shader "Chess with sky"
3
+ {
4
+ Properties
5
+ {
6
+ field( "Field size" ,Float )= 0.2
7
+ }
8
+ Subshader
9
+ {
10
+ Pass
11
+ {
12
+ CGPROGRAM
13
+ #pragma vertex vertex_shader
14
+ #pragma fragment pixel_shader
15
+ #pragma target 3.0
16
+
17
+ float field;
18
+ struct custom_type
19
+ {
20
+ float4 screen_vertex : SV_POSITION ;
21
+ float3 world_vertex : TEXCOORD1 ;
22
+ };
23
+
24
+ float plane (float3 p)
25
+ {
26
+ return p.y;
27
+ }
28
+
29
+ float3 chess (float2 uv)
30
+ {
31
+ float d = field;
32
+ float x = fmod ( floor (uv.x*d), 2.0 );
33
+ float y = fmod ( floor (uv.y*d), 2.0 );
34
+ return ( ( abs (x)==0.0 && abs (y)==0.0 ) || ( abs (x)==1.0 && abs (y)==1.0 ) ) ? float3 (1.0 ,1.0 ,1.0 ): float3 (0.0 ,0.0 ,0.0 );
35
+ }
36
+
37
+ float3 sky (float3 p)
38
+ {
39
+ p.y = max (p.y,0.0 );
40
+ return float3 (pow (1.0 -p.y,2.0 ), 1.0 -p.y, 0.6 +(1.0 -p.y)*0.4 );
41
+ }
42
+
43
+ float3 set_texture ( float3 pos, float3 nor )
44
+ {
45
+ float3 w = nor*nor;
46
+ return (w.x*chess (pos.yz ) + w.y*chess (pos.zx)+ w.z*chess (pos.xy)) / (w.x+w.y+w.z);
47
+ }
48
+
49
+ float3 lighting (float3 p)
50
+ {
51
+ float3 x = float3 (0.01 ,0.00 ,0.00 );
52
+ float3 y = float3 (0.00 ,0.01 ,0.00 );
53
+ float3 z = float3 (0.00 ,0.00 ,0.01 );
54
+ float3 AmbientLight = float3 (0.1 ,0.1 ,0.1 );
55
+ float3 LightDirection = normalize (float3 (4.0 ,10.0 ,-10.0 ));
56
+ float3 LightColor = float3 (1.0 ,1.0 ,1.0 );
57
+ float3 NormalDirection = normalize (float3 (
58
+ plane (p+x) - plane (p-x),
59
+ plane (p+y) - plane (p-y),
60
+ plane (p+z) - plane (p-z) ));
61
+ return (max (dot (LightDirection, NormalDirection),0.0 ) * LightColor + AmbientLight)*set_texture (p,NormalDirection);
62
+ }
63
+
64
+ float4 raymarch (float3 ro, float3 rd)
65
+ {
66
+ for (int i=0 ; i<128 ; i++)
67
+ {
68
+ float t = plane (ro);
69
+ if (t < 0.001 ) return float4 (lighting (ro),1.0 ); else ro+=t*rd;
70
+ }
71
+ return float4 (lighting (ro),1.0 );
72
+ }
73
+
74
+ custom_type vertex_shader (float4 vertex : POSITION )
75
+ {
76
+ custom_type vs;
77
+ vs.screen_vertex = mul (UNITY_MATRIX_MVP , vertex);
78
+ vs.world_vertex = mul (_Object2World , vertex);
79
+ return vs;
80
+ }
81
+
82
+ float4 pixel_shader (custom_type ps ) : SV_TARGET
83
+ {
84
+ float3 worldPosition = ps.world_vertex;
85
+ float3 viewDirection = normalize (ps.world_vertex - _WorldSpaceCameraPos );
86
+ float3 color = lerp (sky (viewDirection), raymarch (worldPosition,viewDirection).xyz, pow (smoothstep (0.0 ,-0.55 ,viewDirection.y),0.5 ) );
87
+ return float4 (color,1.0 );
88
+ }
89
+
90
+ ENDCG
91
+ }
92
+ }
93
+ }
0 commit comments