4. Noise
23. #pragmas
这里由于不同的编译环境显卡不一样,所以加入这一条指令:
#pragma exclude_renderers d3d11
24. What’s all that noise?
- A greate way to add naturalism to a shader
- In the real world noise is everywhere.
- What is noise?
- Making something appear less than perfect.
- It can be used for so many things.s
25. Using noise to create a fire shader
25.1 uv
25.1.1 投影映射:将3D空间坐标转换成2D
- Projector:比如地球仪,将矩形地图纹理均匀贴到球表面的投影函数成为sphere形式;还有cubic,plane etc.
- UV Mapping:用于将 3 维模型中的每个顶点与 2 维纹理坐标一一对应。通常是将 uv 坐标保存在顶点信息中,在三角形内使用时,通过插值的方式得到每个片元具体的 uv 坐标,再从纹理中采样获得对应的值
25.1.2 变换函数
将 uv 坐标经过处理变换后,根据实际的纹理尺寸,转化为纹理空间坐标
-
坐标范围的处理:此时得到的有可能是 [0.25,0.3] 这种在 [0,1] 范围内的值,但也有可能超出了 [0,1] 范围,那么需要对范围外的值进行处理。可以选择Repeat, Mirror, Clamp etc.
-
坐标的自由转换:比如旋转平移缩放,uv就像一个窗口,如果你需要纹理往右移,则你需要把窗口向左移,用u – 0.5 而不是 u + 0.5
-
转到纹理空间:用uv坐标再分别乘以纹理实际的宽高。比如 uv 坐标为 [0.25,0.3],纹理的宽高为 [256,256],那么相乘可得到 [64,76.8]。
由此可以得到,要想让纹理向上跑,那么窗口就要下移,uv上面需要减。
25.1.3 纹理采样
依据纹理空间坐标,对纹理进行采样,要处理放大和缩小两个情况。
- 放大:比如我们只有 40x40 的纹理,却要贴到 256x256 大小的画布上去,这就是一个上采样的过程。使用最邻近采样,双线性采样,三次卷积采样。
- 缩小:将高分辨率的纹理贴到低分辨率的画布。mipmapping, SAT, 各项异性过滤。
25.2 Make a Shader transparent
-
Set the Queue Tag to Transparent
-
Set the blendering:
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
25.3 Summary
- A simple noise function
- Move the noise in the y direction over time
- Layer multiple passes of the noise function
- Add an alpha layer to crop the result
26. Using noise to create wood and marble
This has been converted into CGinclude file by Lex-DRL.
26.1 Using custom include files
- Copy the file to Unity’s CGIncludes folder
- Win:Program Files folder.
Unity/Editor/Data/CGIncludes
- Mac:In the folder
Applications > Unity > Hub > Editor > UnityVersion > Unity use Show Package Contents to expose the CGIncludes folder > CGIncludes
- Win:Program Files folder.
26.2 Create wood and marble
#include "noiseSimplex.cginc"
float4 frag (v2f i) : COLOR
{
float3 pos = i.position.xyz * 2;//3d model
float n = snoise(pos);
float ring = frac(_NoiseScale*n);
ring *= _Contrast *(1.0 - ring);
float delta = pow(ring,_RingScale) + n;
fixed3 color = lerp(_DarkColor, _PaleColor, delta);
return fixed4( color, 1.0 );
}
26.3 Test
- Who is credited with being the first to use noise in shaders ?
- Ken Perlin
- We can layer up noise by adjusting the position value and summing the values.