feat(ShaderBake): runtime 侧把 shader 渲成 RT/Texture2D/Sprite/文件字节
离屏渲染走 CommandBuffer + 自建视图投影矩阵,不往场景塞相机和 GameObject, 代价是 API 相关的 Y 翻转要露成一个开关(output.flipY);灯光/雾/阴影不参与, 所以光照类 shader 会渲成无灯效果,这一点写在注释里而不是假装支持。 外部网格一律复制到新网格再改 UV:直接改 MeshFilter.sharedMesh 等于改了项目资产。
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 一次性调用的门面:给"我就是要把这个 shader 烘成一张图/一个文件"的运行时代码用。
|
||||
/// 需要在帧之间反复改参数重画(比如编辑器预览)请直接用 <see cref="ShaderBakeRenderer"/>,
|
||||
/// 它会把目标纹理和网格留着复用。
|
||||
/// </summary>
|
||||
public static class ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 渲进一张新建的 RenderTexture。<b>返回的纹理由调用方销毁</b>(用
|
||||
/// <see cref="ShaderBakeRenderer.ReleaseTempObject"/> 就行)。失败返回 null,原因写在 lastError。
|
||||
/// </summary>
|
||||
public static RenderTexture BakeToRenderTexture(Material material, ShaderBakeSettings settings, out string lastError)
|
||||
{
|
||||
lastError = null;
|
||||
using (var renderer = CreateRenderer(material, settings, out lastError))
|
||||
{
|
||||
if (renderer == null)
|
||||
return null;
|
||||
RenderTexture rt = renderer.Render();
|
||||
lastError = renderer.lastError;
|
||||
if (rt == null)
|
||||
return null;
|
||||
|
||||
// renderer.Dispose 会把内部那张一起销毁,所以交出去的是按同一套参数另建的一张
|
||||
var effective = settings != null ? settings : ShaderBakeSettings.CreateDefault();
|
||||
var copy = effective.output.CreateRenderTexture("ShaderBakeResult");
|
||||
Graphics.Blit(rt, copy);
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 渲成可读 Texture2D。调用方负责销毁。 </summary>
|
||||
public static Texture2D BakeToTexture2D(Material material, ShaderBakeSettings settings, bool generateMips = false)
|
||||
{
|
||||
string lastError;
|
||||
using (var renderer = CreateRenderer(material, settings, out lastError))
|
||||
{
|
||||
if (renderer == null)
|
||||
{
|
||||
Debug.LogError("[ShaderBake] " + lastError);
|
||||
return null;
|
||||
}
|
||||
return renderer.RenderToTexture2D(generateMips);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 渲成 Sprite(连同它持有的纹理一起交给调用方)。 </summary>
|
||||
public static Sprite BakeToSprite(Material material, ShaderBakeSettings settings, float pixelsPerUnit = 100f)
|
||||
{
|
||||
string lastError;
|
||||
using (var renderer = CreateRenderer(material, settings, out lastError))
|
||||
{
|
||||
if (renderer == null)
|
||||
{
|
||||
Debug.LogError("[ShaderBake] " + lastError);
|
||||
return null;
|
||||
}
|
||||
return renderer.RenderToSprite(pixelsPerUnit);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 渲成图片文件字节(PNG / JPG / TGA / EXR)。
|
||||
/// <paramref name="settings"/> 为 null 时用默认 512×512 那套。
|
||||
/// </summary>
|
||||
public static byte[] BakeToBytes(Material material, ShaderBakeImageFormat format, ShaderBakeSettings settings = null)
|
||||
{
|
||||
string lastError;
|
||||
using (var renderer = CreateRenderer(material, settings, out lastError))
|
||||
{
|
||||
if (renderer == null)
|
||||
{
|
||||
Debug.LogError("[ShaderBake] " + lastError);
|
||||
return null;
|
||||
}
|
||||
Texture2D keep;
|
||||
byte[] bytes = renderer.RenderToBytes(format, out keep);
|
||||
if (keep != null)
|
||||
ShaderBakeRenderer.ReleaseTempObject(keep);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 从 Shader 直接烘一份(内部建临时材质并在用完后销毁) </summary>
|
||||
public static byte[] BakeToBytes(Shader shader, ShaderBakeImageFormat format, ShaderBakeSettings settings = null)
|
||||
{
|
||||
if (shader == null)
|
||||
{
|
||||
Debug.LogError("[ShaderBake] shader 为空");
|
||||
return null;
|
||||
}
|
||||
var temp = new Material(shader) { hideFlags = HideFlags.DontSave };
|
||||
try
|
||||
{
|
||||
return BakeToBytes(temp, format, settings);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ShaderBakeRenderer.ReleaseTempObject(temp);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 把参数与材质装进一个新渲染器;材质为空时返回 null 并写好 lastError </summary>
|
||||
public static ShaderBakeRenderer CreateRenderer(Material material, ShaderBakeSettings settings, out string lastError)
|
||||
{
|
||||
if (material == null)
|
||||
{
|
||||
lastError = "没有材质";
|
||||
return null;
|
||||
}
|
||||
lastError = string.Empty;
|
||||
return new ShaderBakeRenderer
|
||||
{
|
||||
material = material,
|
||||
settings = settings != null ? settings : ShaderBakeSettings.CreateDefault()
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 离屏"摄像机"参数。这里没有真的 Camera——投影与视口矩阵是自己算出来塞进 CommandBuffer 的,
|
||||
/// 好处是不往场景里塞任何临时物体,坏处是 API 相关的 Y 翻转要自己管(见 output.flipY)。
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeCameraSettings
|
||||
{
|
||||
[Tooltip("正交(默认):面片不会因为透视而变形,适合贴图类 shader")]
|
||||
public bool orthographic = true;
|
||||
|
||||
[Tooltip("正交半高(世界单位):实际能看到的竖向范围是它的两倍")]
|
||||
public float orthographicSize = 0.6f;
|
||||
|
||||
[Tooltip("透视相机的竖向视野角(度),正交时忽略")]
|
||||
public float fieldOfView = 60f;
|
||||
|
||||
[Tooltip("近裁剪面")]
|
||||
public float nearClipPlane = 0.01f;
|
||||
|
||||
[Tooltip("远裁剪面")]
|
||||
public float farClipPlane = 100f;
|
||||
|
||||
[Tooltip("相机位置:正交时只有朝向影响画面,位置决定远近")]
|
||||
public Vector3 position = new Vector3(0f, 0f, -10f);
|
||||
|
||||
[Tooltip("相机旋转(欧拉角,度):默认朝 +Z 看,即看着放在原点、面朝 -Z 的面片")]
|
||||
public Vector3 eulerAngles;
|
||||
|
||||
/// <summary> 视口(世界 → 相机)矩阵 </summary>
|
||||
public Matrix4x4 viewMatrix
|
||||
{
|
||||
get { return Matrix4x4.TRS(position, Quaternion.Euler(eulerAngles), Vector3.one).inverse; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 投影矩阵。正交时宽高按 aspect 分配(半宽 = 半高 × aspect),与 Unity 相机一致。
|
||||
/// </summary>
|
||||
public Matrix4x4 GetProjectionMatrix(float aspect)
|
||||
{
|
||||
if (aspect <= 0f) aspect = 1f;
|
||||
if (orthographic)
|
||||
{
|
||||
float halfHeight = Mathf.Max(orthographicSize, 0.0001f);
|
||||
float halfWidth = halfHeight * aspect;
|
||||
return Matrix4x4.Ortho(-halfWidth, halfWidth, -halfHeight, halfHeight,
|
||||
Mathf.Max(nearClipPlane, 0.0001f), Mathf.Max(farClipPlane, nearClipPlane + 0.0001f));
|
||||
}
|
||||
return Matrix4x4.Perspective(Mathf.Clamp(fieldOfView, 1f, 179f), aspect,
|
||||
Mathf.Max(nearClipPlane, 0.0001f), Mathf.Max(farClipPlane, nearClipPlane + 0.0001f));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把包围盒框进画面:正交改半高,透视改距离;同时把远近裁剪面推到包围盒外侧,
|
||||
/// 免得贴脸的大面片被近裁剪面削掉一块。
|
||||
/// </summary>
|
||||
public void FrameBounds(Bounds bounds, float aspect, float padding = 1.15f)
|
||||
{
|
||||
Vector3 extents = bounds.extents;
|
||||
float radius = extents.magnitude;
|
||||
if (radius < 0.0001f) radius = 0.0001f;
|
||||
if (aspect <= 0f) aspect = 1f;
|
||||
|
||||
if (orthographic)
|
||||
{
|
||||
// 横向不够宽时以横向为准:半高 = 半宽 / aspect
|
||||
float halfFromHeight = extents.y;
|
||||
float halfFromWidth = extents.x / aspect;
|
||||
orthographicSize = Mathf.Max(halfFromHeight, halfFromWidth) * Mathf.Max(padding, 1f);
|
||||
}
|
||||
else
|
||||
{
|
||||
float halfFov = Mathf.Clamp(fieldOfView, 1f, 179f) * 0.5f * Mathf.Deg2Rad;
|
||||
float verticalFit = extents.y;
|
||||
float horizontalFit = extents.x / aspect;
|
||||
float neededHalfHeight = Mathf.Max(verticalFit, horizontalFit) * Mathf.Max(padding, 1f);
|
||||
float distance = radius + neededHalfHeight / Mathf.Max(Mathf.Tan(halfFov), 0.0001f);
|
||||
|
||||
// 沿当前朝向平移,不改朝向——转着找角度是用户的事,这里只负责"离远一点"
|
||||
Vector3 dir = Quaternion.Euler(eulerAngles) * Vector3.forward;
|
||||
position = bounds.center - dir * Mathf.Max(distance, radius + 0.0001f);
|
||||
}
|
||||
|
||||
float distanceFromCamera = Vector3.Distance(position, bounds.center);
|
||||
nearClipPlane = Mathf.Max(0.0001f, distanceFromCamera - radius * 3f);
|
||||
farClipPlane = distanceFromCamera + radius * 3f;
|
||||
}
|
||||
|
||||
/// <summary> 摄像机指纹:变了不需要重建网格,只需要重画 </summary>
|
||||
public string GetCameraSignature()
|
||||
{
|
||||
return orthographic + "_" + orthographicSize + "_" + fieldOfView + "_" +
|
||||
nearClipPlane + "_" + farClipPlane + "_" + position + "_" + eulerAngles;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 按 <see cref="ShaderBakeSurfaceSettings"/> 造出这次烘焙要画的那张网格。
|
||||
///
|
||||
/// <para><b>外部网格一定要复制</b>:UV 偏移/重复是写进顶点数据的,直接改
|
||||
/// <c>MeshFilter.sharedMesh</c> 等于改了项目里的资产。这里把顶点搬到一张新网格上,
|
||||
/// 蒙皮信息不带过来(烘焙用不到,带过来反而要把骨骼矩阵一起搬)。</para>
|
||||
/// </summary>
|
||||
public static class ShaderBakeGeometryBuilder
|
||||
{
|
||||
/// <summary> 造一张新网格(调用方负责销毁)。kind 为外部网格但没有指定网格时退回单片四边形。 </summary>
|
||||
public static Mesh Build(ShaderBakeSurfaceSettings surface)
|
||||
{
|
||||
if (surface == null)
|
||||
return null;
|
||||
surface.Clamp();
|
||||
|
||||
switch (surface.kind)
|
||||
{
|
||||
case ShaderBakeSurfaceKind.Plane:
|
||||
return BuildGrid(surface, Mathf.Max(surface.segments.x, 1), Mathf.Max(surface.segments.y, 1));
|
||||
case ShaderBakeSurfaceKind.Mesh when surface.sourceMesh != null:
|
||||
return BuildFromMesh(surface);
|
||||
default:
|
||||
return BuildGrid(surface, 1, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 世界空间的包围盒:网格局部包围盒乘面片变换。给"框住面片"用,所以要在外面算,
|
||||
/// 免得网格和变换的耦合漏进几何构建里。
|
||||
/// </summary>
|
||||
public static Bounds GetWorldBounds(Mesh mesh, Matrix4x4 matrix)
|
||||
{
|
||||
if (mesh == null)
|
||||
return new Bounds(Vector3.zero, Vector3.one);
|
||||
if (matrix.isIdentity)
|
||||
return mesh.bounds;
|
||||
|
||||
Bounds b = mesh.bounds;
|
||||
Vector3 min = b.min, max = b.max;
|
||||
Vector3 worldMin = matrix.MultiplyPoint(min);
|
||||
Vector3 worldMax = worldMin;
|
||||
|
||||
// 旋转过之后轴对齐盒子的八个角才是新盒子的候选极值,只转两个角会得到一个歪掉的框
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
Vector3 corner = matrix.MultiplyPoint(new Vector3(
|
||||
(i & 1) == 0 ? min.x : max.x,
|
||||
(i & 2) == 0 ? min.y : max.y,
|
||||
(i & 4) == 0 ? min.z : max.z));
|
||||
worldMin = Vector3.Min(worldMin, corner);
|
||||
worldMax = Vector3.Max(worldMax, corner);
|
||||
}
|
||||
|
||||
var bounds = new Bounds();
|
||||
bounds.SetMinMax(worldMin, worldMax);
|
||||
return bounds;
|
||||
}
|
||||
|
||||
/// <summary> 网格在自身变换之后、相机之前的最大分量跨度,用于决定要不要走 uint32 索引 </summary>
|
||||
private static Mesh BuildGrid(ShaderBakeSurfaceSettings surface, int columns, int rows)
|
||||
{
|
||||
float halfWidth = surface.size.x * 0.5f;
|
||||
float halfHeight = surface.size.y * 0.5f;
|
||||
|
||||
int vertexCount = (columns + 1) * (rows + 1);
|
||||
var vertices = new List<Vector3>(vertexCount);
|
||||
var normals = new List<Vector3>(vertexCount);
|
||||
var uvs = new List<Vector2>(vertexCount);
|
||||
var triangles = new List<int>(columns * rows * 6);
|
||||
|
||||
for (int y = 0; y <= rows; y++)
|
||||
{
|
||||
float ty = rows == 0 ? 0f : (float)y / rows;
|
||||
for (int x = 0; x <= columns; x++)
|
||||
{
|
||||
float tx = columns == 0 ? 0f : (float)x / columns;
|
||||
vertices.Add(new Vector3(
|
||||
Mathf.Lerp(-halfWidth, halfWidth, tx),
|
||||
Mathf.Lerp(-halfHeight, halfHeight, ty),
|
||||
0f));
|
||||
normals.Add(Vector3.back); // 面朝 -Z,即默认相机(朝 +Z 看)看到的正面
|
||||
uvs.Add(RemapUv(new Vector2(tx, ty), surface));
|
||||
}
|
||||
}
|
||||
|
||||
int stride = columns + 1;
|
||||
for (int y = 0; y < rows; y++)
|
||||
for (int x = 0; x < columns; x++)
|
||||
{
|
||||
int bottomLeft = y * stride + x;
|
||||
int bottomRight = bottomLeft + 1;
|
||||
int topLeft = bottomLeft + stride;
|
||||
int topRight = topLeft + 1;
|
||||
// 绕序按"从 -Z 往 +Z 看是顺时针"排;翻转投影时靠 output.flipY 修,不靠这里换绕序
|
||||
triangles.Add(bottomLeft);
|
||||
triangles.Add(bottomRight);
|
||||
triangles.Add(topLeft);
|
||||
triangles.Add(bottomRight);
|
||||
triangles.Add(topRight);
|
||||
triangles.Add(topLeft);
|
||||
}
|
||||
|
||||
var mesh = NewMesh("ShaderBakeQuad");
|
||||
mesh.SetVertices(vertices);
|
||||
mesh.SetNormals(normals);
|
||||
mesh.SetUVs(0, uvs);
|
||||
mesh.SetTriangles(triangles, 0);
|
||||
Upload(mesh);
|
||||
return mesh;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 复制外部网格的第 0 套 UV(没有就按位置做平面投影),再套上偏移/重复。
|
||||
/// </summary>
|
||||
private static Mesh BuildFromMesh(ShaderBakeSurfaceSettings surface)
|
||||
{
|
||||
Mesh source = surface.sourceMesh;
|
||||
int subMesh = Mathf.Min(surface.meshSubMesh, Mathf.Max(source.subMeshCount - 1, 0));
|
||||
|
||||
var vertices = new List<Vector3>();
|
||||
source.GetVertices(vertices);
|
||||
if (vertices.Count == 0)
|
||||
{
|
||||
Debug.LogWarning("[ShaderBake] 外部网格没有顶点数据(可能是只读网格),退回单片四边形");
|
||||
return BuildGrid(surface, 1, 1);
|
||||
}
|
||||
|
||||
var normals = new List<Vector3>();
|
||||
if (source.HasVertexAttribute(VertexAttribute.Normal))
|
||||
source.GetNormals(normals);
|
||||
|
||||
var tangents = new List<Vector4>();
|
||||
if (source.HasVertexAttribute(VertexAttribute.Tangent))
|
||||
source.GetTangents(tangents);
|
||||
|
||||
var uvs = new List<Vector2>();
|
||||
if (source.HasVertexAttribute(VertexAttribute.TexCoord0))
|
||||
source.GetUVs(0, uvs);
|
||||
if (uvs.Count != vertices.Count)
|
||||
uvs = BuildPlanarUv(vertices);
|
||||
|
||||
// UV 是"面片的贴图坐标",不该被模型的尺寸归一化影响,所以先 remap 再缩放顶点
|
||||
for (int i = 0; i < uvs.Count; i++)
|
||||
uvs[i] = RemapUv(uvs[i], surface);
|
||||
|
||||
var mesh = NewMesh("ShaderBakeMesh");
|
||||
if (vertices.Count > 65000)
|
||||
mesh.indexFormat = IndexFormat.UInt32;
|
||||
|
||||
Bounds srcBounds = source.bounds;
|
||||
Vector3 normalizeScale = surface.normalizeMeshSize ? FitScale(srcBounds.size, surface.size) : Vector3.one;
|
||||
|
||||
for (int i = 0; i < vertices.Count; i++)
|
||||
vertices[i] = Vector3.Scale(vertices[i] - srcBounds.center, normalizeScale);
|
||||
|
||||
mesh.SetVertices(vertices);
|
||||
if (normals.Count == vertices.Count) mesh.SetNormals(normals); else mesh.RecalculateNormals();
|
||||
if (tangents.Count == vertices.Count) mesh.SetTangents(tangents);
|
||||
mesh.SetUVs(0, uvs);
|
||||
|
||||
// 只搬到选中的那一层:后面的层不该跟着画出来,但 subMesh 之前的层要一起画(多层模型常有共用材质球的分层)
|
||||
int layerCount = subMesh + 1;
|
||||
mesh.subMeshCount = layerCount;
|
||||
for (int i = 0; i < layerCount; i++)
|
||||
mesh.SetTriangles(source.GetTriangles(i), i);
|
||||
|
||||
Upload(mesh);
|
||||
mesh.RecalculateBounds();
|
||||
return mesh;
|
||||
}
|
||||
|
||||
/// <summary> 把源尺寸装进目标尺寸:x/y 各自贴合,z 跟 x/y 的平均倍率走以免模型被压扁成纸片 </summary>
|
||||
private static Vector3 FitScale(Vector3 sourceSize, Vector2 targetSize)
|
||||
{
|
||||
float sx = sourceSize.x > 0.0001f ? targetSize.x / sourceSize.x : 1f;
|
||||
float sy = sourceSize.y > 0.0001f ? targetSize.y / sourceSize.y : 1f;
|
||||
float sz = sourceSize.z > 0.0001f ? (sx + sy) * 0.5f : 1f;
|
||||
return new Vector3(sx, sy, sz);
|
||||
}
|
||||
|
||||
/// <summary> 网格没带 UV 时的兜底:拿 x/y 位置做一次平面投影,至少贴图有坐标可用 </summary>
|
||||
private static List<Vector2> BuildPlanarUv(List<Vector3> vertices)
|
||||
{
|
||||
var min = new Vector3(float.MaxValue, float.MaxValue, 0f);
|
||||
var max = new Vector3(float.MinValue, float.MinValue, 0f);
|
||||
foreach (Vector3 v in vertices)
|
||||
{
|
||||
min = Vector3.Min(min, v);
|
||||
max = Vector3.Max(max, v);
|
||||
}
|
||||
|
||||
float rangeX = Mathf.Max(max.x - min.x, 0.0001f);
|
||||
float rangeY = Mathf.Max(max.y - min.y, 0.0001f);
|
||||
|
||||
var uvs = new List<Vector2>(vertices.Count);
|
||||
foreach (Vector3 v in vertices)
|
||||
uvs.Add(new Vector2((v.x - min.x) / rangeX, (v.y - min.y) / rangeY));
|
||||
return uvs;
|
||||
}
|
||||
|
||||
private static Vector2 RemapUv(Vector2 uv, ShaderBakeSurfaceSettings surface)
|
||||
{
|
||||
return Vector2.Scale(uv, surface.uvTiling) + surface.uvOffset;
|
||||
}
|
||||
|
||||
private static Mesh NewMesh(string name)
|
||||
{
|
||||
return new Mesh
|
||||
{
|
||||
name = name,
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary> 上传为只读以外的可变网格(false):重建时还要读回顶点,别让 Unity 把它锁掉 </summary>
|
||||
private static void Upload(Mesh mesh)
|
||||
{
|
||||
mesh.UploadMeshData(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 可导出的图片文件编码。全部走 Unity 自己的 <c>ImageConversion</c> 扩展方法,不引第三方编码器。
|
||||
/// </summary>
|
||||
public enum ShaderBakeImageFormat
|
||||
{
|
||||
/// <summary> PNG:带 alpha,无损 </summary>
|
||||
Png,
|
||||
|
||||
/// <summary> JPG:无 alpha,导出前会把透明压到背景色上 </summary>
|
||||
Jpg,
|
||||
|
||||
/// <summary> TGA:无压缩、带 alpha,Photoshop / 老管线常用 </summary>
|
||||
Tga,
|
||||
|
||||
/// <summary> EXR:浮点 HDR,配 output.hdr 用 </summary>
|
||||
Exr
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 编码分派。注意这几个函数都要求纹理是可读的、且是非压缩格式——
|
||||
/// 所以入口只接 <see cref="ShaderBakeReadback"/> 造出来的 RGBA32 / RGBAFloat,别把导入的资源塞进来。
|
||||
/// </summary>
|
||||
public static class ShaderBakeImageFormatExtensions
|
||||
{
|
||||
public static string GetExtension(this ShaderBakeImageFormat format)
|
||||
{
|
||||
switch (format)
|
||||
{
|
||||
case ShaderBakeImageFormat.Jpg: return "jpg";
|
||||
case ShaderBakeImageFormat.Tga: return "tga";
|
||||
case ShaderBakeImageFormat.Exr: return "exr";
|
||||
default: return "png";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 这个格式能不能存 alpha </summary>
|
||||
public static bool SupportsAlpha(this ShaderBakeImageFormat format)
|
||||
{
|
||||
return format != ShaderBakeImageFormat.Jpg;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 编码成文件字节。<paramref name="flattenBackground"/> 只给 JPG 用:它没有 alpha 通道,
|
||||
/// 直接把 RGBA 交上去会得到一圈发黑的边,所以先按这个颜色把透明压平(顺带把浮点截到 0~1)。
|
||||
/// </summary>
|
||||
public static byte[] Encode(this ShaderBakeImageFormat format, Texture2D texture, Color flattenBackground)
|
||||
{
|
||||
if (texture == null)
|
||||
throw new ArgumentNullException(nameof(texture));
|
||||
|
||||
if (format == ShaderBakeImageFormat.Jpg)
|
||||
{
|
||||
var flattened = ShaderBakeReadback.FlattenOntoBackground(texture, flattenBackground);
|
||||
try
|
||||
{
|
||||
return flattened.EncodeToJPG();
|
||||
}
|
||||
finally
|
||||
{
|
||||
UnityEngine.Object.Destroy(flattened);
|
||||
}
|
||||
}
|
||||
|
||||
switch (format)
|
||||
{
|
||||
case ShaderBakeImageFormat.Tga:
|
||||
return texture.EncodeToTGA();
|
||||
case ShaderBakeImageFormat.Exr:
|
||||
return texture.EncodeToEXR(Texture2D.EXRFlags.None);
|
||||
default:
|
||||
return texture.EncodeToPNG();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EXR 要求浮点纹理才能存下超过 1 的分量;非 HDR 的源用 RGBA32 烘,导 EXR 时格式仍合法但值域被截断,
|
||||
/// 这里给个提示而不是报错。
|
||||
/// </summary>
|
||||
public static bool NeedsFloatSource(this ShaderBakeImageFormat format)
|
||||
{
|
||||
return format == ShaderBakeImageFormat.Exr;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 把"用户给的 Shader 或 Material"归一成一张可渲染的材质,并管好这张材质的生死。
|
||||
///
|
||||
/// <para><b>为什么 Shader 入口要自己造材质</b>:渲染路径只认材质,而 Shader 资产本身不能被修改
|
||||
/// (属性默认值存在 Shader 里、不在任何实例上)。造一张临时材质是唯一能就地调参数的路子,
|
||||
/// 代价是它不属于任何资产——所以用完必须还,见 <see cref="Dispose"/>。</para>
|
||||
///
|
||||
/// <para><b>Material 入口不动原资产</b>:直接编辑传进来的材质资产等于改了项目里的文件,
|
||||
/// 用户点一下颜色滑块就写脏了一个 .mat。这里也造一份副本,改坏了指望不了别人替你记。</para>
|
||||
/// </summary>
|
||||
public sealed class ShaderBakeMaterialSource : IDisposable
|
||||
{
|
||||
/// <summary> 渲染实际用的材质(可能是临时造的副本) </summary>
|
||||
public Material material { get; private set; }
|
||||
|
||||
/// <summary> 这份材质是不是自己造的,决定 Dispose 时要不要销毁它 </summary>
|
||||
public bool ownsMaterial { get; private set; }
|
||||
|
||||
/// <summary> 用户给的 Shader 入口,用于界面显示与材质属性列表 </summary>
|
||||
public Shader sourceShader { get; private set; }
|
||||
|
||||
/// <summary> 用户给的 Material 入口,副本的参数就按它初始化 </summary>
|
||||
public Material sourceMaterial { get; private set; }
|
||||
|
||||
/// <summary> 当前生效的 shader(两个入口最终都落到它上面) </summary>
|
||||
public Shader shader
|
||||
{
|
||||
get
|
||||
{
|
||||
if (sourceShader != null) return sourceShader;
|
||||
return material != null ? material.shader : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 给界面看的来源说明:Shader 入口写"临时材质",Material 入口写"副本" </summary>
|
||||
public string description
|
||||
{
|
||||
get
|
||||
{
|
||||
if (sourceShader != null) return sourceShader.name + "(临时材质)";
|
||||
if (material != null) return material.name + "(副本)";
|
||||
return "未指定";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> Shader 入口:建一张临时材质。传 null 表示清空。 </summary>
|
||||
public void Assign(Shader shader)
|
||||
{
|
||||
ReleaseOwned();
|
||||
sourceShader = shader;
|
||||
sourceMaterial = null;
|
||||
if (shader == null)
|
||||
{
|
||||
material = null;
|
||||
return;
|
||||
}
|
||||
material = new Material(shader)
|
||||
{
|
||||
name = shader.name + " (Bake)",
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
ownsMaterial = true;
|
||||
}
|
||||
|
||||
/// <summary> Material 入口:复制一张临时材质,参数与来源一致。传 null 表示清空。 </summary>
|
||||
public void Assign(Material source)
|
||||
{
|
||||
ReleaseOwned();
|
||||
sourceShader = null;
|
||||
sourceMaterial = source;
|
||||
if (source == null)
|
||||
{
|
||||
material = null;
|
||||
return;
|
||||
}
|
||||
material = new Material(source)
|
||||
{
|
||||
name = source.name + " (Bake)",
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
ownsMaterial = true;
|
||||
}
|
||||
|
||||
/// <summary> 把副本当前的参数写回来源材质(用户显式按"应用"才走这里) </summary>
|
||||
public bool ApplyToSource()
|
||||
{
|
||||
if (material == null || sourceMaterial == null)
|
||||
return false;
|
||||
// CopyPropertiesFromMaterial 只搬它认得的属性,材质整体替换反而会把 hideFlags 带过来
|
||||
sourceMaterial.CopyPropertiesFromMaterial(material);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary> 丢弃副本上的改动,回到来源材质的参数 </summary>
|
||||
public bool RevertToSource()
|
||||
{
|
||||
if (sourceMaterial == null)
|
||||
return false;
|
||||
Assign(sourceMaterial);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary> 换 shader 名/属性列表之后要把副本丢干净 </summary>
|
||||
public void Clear()
|
||||
{
|
||||
ReleaseOwned();
|
||||
sourceShader = null;
|
||||
sourceMaterial = null;
|
||||
material = null;
|
||||
ownsMaterial = false;
|
||||
}
|
||||
|
||||
private void ReleaseOwned(bool immediate)
|
||||
{
|
||||
if (ownsMaterial && material != null)
|
||||
ShaderBakeRenderer.ReleaseTempObject(material, immediate);
|
||||
material = null;
|
||||
ownsMaterial = false;
|
||||
}
|
||||
|
||||
private void ReleaseOwned()
|
||||
{
|
||||
ReleaseOwned(false);
|
||||
}
|
||||
|
||||
/// <summary> 编辑器里退出窗口时按 immediate 释放,显存当场就还回去了 </summary>
|
||||
public void Dispose(bool immediate)
|
||||
{
|
||||
ReleaseOwned(immediate);
|
||||
sourceShader = null;
|
||||
sourceMaterial = null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 输出目标设置:决定"烘出来那张 RenderTexture 长什么样"。
|
||||
///
|
||||
/// <para><b>为什么 flipY 要摊开给用户</b>:这里走的是 CommandBuffer + 自建投影矩阵的离屏渲染,
|
||||
/// 没有相机帮你做 API 相关的 Y 翻转,于是同一段代码在 D3D 与 OpenGL/Metal 上读回来的像素是上下相反的。
|
||||
/// 与其替用户猜一个方向,不如把开关留在界面上(规范:一次调用不出结果时先怀疑方向,再怀疑内容)。</para>
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeOutputSettings
|
||||
{
|
||||
/// <summary> 边长下限 </summary>
|
||||
public const int kMinDimension = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 边长上限:4096² 的 RGBA32 读回是 64MB 内存,ARGBFloat 是 256MB。
|
||||
/// 再往上就不是"烘焙一张图"而是"烘一张图集"了,交给调用方自己决定要不要冒险。
|
||||
/// </summary>
|
||||
public const int kMaxDimension = 4096;
|
||||
|
||||
[Tooltip("导出图片的宽(像素)")]
|
||||
public int width = 512;
|
||||
|
||||
[Tooltip("导出图片的高(像素)")]
|
||||
public int height = 512;
|
||||
|
||||
[Tooltip("HDR:目标改用 ARGBFloat。开这项时请配 EXR 导出,PNG/JPG 存不下超过 1 的分量")]
|
||||
public bool hdr;
|
||||
|
||||
[Tooltip("多重采样,只能是 1 / 2 / 4 / 8;渲染完会自动解析回普通纹理再读回")]
|
||||
public int antiAliasing = 1;
|
||||
|
||||
[Tooltip("深度位数。只渲一张面片填 0 就够,渲模型(有多层遮挡)要留 24")]
|
||||
public int depthBuffer = 24;
|
||||
|
||||
[Tooltip("目标按 sRGB 存储。关掉=线性,通常配 HDR + EXR 自己走色彩管理")]
|
||||
public bool sRGB = true;
|
||||
|
||||
[Tooltip("背景色。alpha 留 0 才能导出带透明通道的图;导 JPG 时这个颜色会被压进图里")]
|
||||
public Color clearColor = new Color(0f, 0f, 0f, 0f);
|
||||
|
||||
[Tooltip("翻转投影 Y:画面上下颠倒时打开(不同图形 API 的读回方向不一样)")]
|
||||
public bool flipY;
|
||||
|
||||
[Tooltip("subShader 的 pass 下标,-1=所有 pass 叠加渲染")]
|
||||
public int shaderPass = -1;
|
||||
|
||||
[Tooltip("目标纹理的过滤方式")]
|
||||
public FilterMode filterMode = FilterMode.Bilinear;
|
||||
|
||||
[Tooltip("目标纹理的寻址方式")]
|
||||
public TextureWrapMode wrapMode = TextureWrapMode.Clamp;
|
||||
|
||||
/// <summary> 目标的 RenderTexture 格式 </summary>
|
||||
public RenderTextureFormat format
|
||||
{
|
||||
get { return hdr ? RenderTextureFormat.ARGBFloat : RenderTextureFormat.ARGB32; }
|
||||
}
|
||||
|
||||
/// <summary> 目标的色彩存储方式(HDR 只能线性) </summary>
|
||||
public RenderTextureReadWrite renderTextureColorSpace
|
||||
{
|
||||
get { return hdr || !sRGB ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB; }
|
||||
}
|
||||
|
||||
/// <summary> 读回成 Texture2D 时用的像素格式 </summary>
|
||||
public TextureFormat textureFormat
|
||||
{
|
||||
get { return hdr ? TextureFormat.RGBAFloat : TextureFormat.RGBA32; }
|
||||
}
|
||||
|
||||
/// <summary> 读回来的 Texture2D 是否按线性解释 </summary>
|
||||
public bool isLinearTexture
|
||||
{
|
||||
get { return hdr || !sRGB; }
|
||||
}
|
||||
|
||||
/// <summary> 目标纹理的有效宽高(读回、贴图、算尺寸都走这个,别各自再算一遍) </summary>
|
||||
public Vector2Int size
|
||||
{
|
||||
get { return new Vector2Int(width, height); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把用户敲进来的数值收进合法区间。非法值不报错、只归位——界面上每改一次都走这里,
|
||||
/// 报错会把输入框变成打字障碍。
|
||||
/// </summary>
|
||||
public void Clamp()
|
||||
{
|
||||
width = Mathf.Clamp(width, kMinDimension, kMaxDimension);
|
||||
height = Mathf.Clamp(height, kMinDimension, kMaxDimension);
|
||||
depthBuffer = Mathf.Clamp(depthBuffer, 0, 32);
|
||||
// HDR 浮点目标基本没有平台支持 MSAA,硬开着只会得到一张黑图
|
||||
if (hdr)
|
||||
antiAliasing = 1;
|
||||
else
|
||||
antiAliasing = SnapAntiAliasing(antiAliasing);
|
||||
}
|
||||
|
||||
/// <summary> 距离最近的一个合法采样倍数(1/2/4/8) </summary>
|
||||
public static int SnapAntiAliasing(int requested)
|
||||
{
|
||||
if (requested <= 1) return 1;
|
||||
if (requested <= 2) return 2;
|
||||
if (requested <= 4) return 4;
|
||||
return 8;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 目标设置指纹:变了就要重建 RenderTexture。尺寸、格式、采样、深度都会换掉显存布局。
|
||||
/// </summary>
|
||||
public string GetTargetSignature()
|
||||
{
|
||||
return width + "x" + height + "_" + (hdr ? "f" : "l") + "_" + antiAliasing + "_" + depthBuffer + "_" + (sRGB ? "s" : "l");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按当前设置造一张未被使用过的 RenderTexture(调用方负责销毁)。
|
||||
/// </summary>
|
||||
public RenderTexture CreateRenderTexture(string name = "ShaderBakeTarget")
|
||||
{
|
||||
Clamp();
|
||||
var rt = new RenderTexture(width, height, depthBuffer, format, renderTextureColorSpace)
|
||||
{
|
||||
name = name,
|
||||
filterMode = filterMode,
|
||||
wrapMode = wrapMode,
|
||||
antiAliasing = antiAliasing,
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
// 显式 Create:antiAliasing 只有在初始化之前赋值才生效,靠第一次使用时自动建就丢了
|
||||
rt.Create();
|
||||
return rt;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// RenderTexture → 可读 Texture2D,以及透明压平。
|
||||
///
|
||||
/// <para><b>为什么用 ReadPixels 而不是 AsyncGPUReadback</b>:后者要等帧,回调里的数据这一轮就拿不到,
|
||||
/// 而"点导出→拿到文件"这条链要的是同步返回。烘焙一张图本来就是离线动作, stall 一帧无所谓。</para>
|
||||
/// </summary>
|
||||
public static class ShaderBakeReadback
|
||||
{
|
||||
/// <summary>
|
||||
/// 把目标读回成可读纹理。<paramref name="linear"/> 决定纹理按线性还是 sRGB 解释,
|
||||
/// 必须和生成它的那张 RenderTexture 一致,否则同一张图在编辑器和文件里会差一层 gamma。
|
||||
/// </summary>
|
||||
public static Texture2D ToTexture2D(RenderTexture source, TextureFormat format, bool linear, bool mipChain = false)
|
||||
{
|
||||
if (source == null)
|
||||
throw new ArgumentNullException(nameof(source));
|
||||
|
||||
var texture = new Texture2D(source.width, source.height, format, mipChain, linear)
|
||||
{
|
||||
name = source.name,
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
CopyInto(source, texture);
|
||||
return texture;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读进一张已存在的纹理(尺寸要和 source 一致;不一致 Unity 只会填左上角,剩下留黑)。
|
||||
/// 走 RenderTexture.active + ReadPixels,MSAA 目标已被调用方解析过,这里读到的是解析后的像素。
|
||||
/// </summary>
|
||||
public static void CopyInto(RenderTexture source, Texture2D destination)
|
||||
{
|
||||
RenderTexture previous = RenderTexture.active;
|
||||
try
|
||||
{
|
||||
RenderTexture.active = source;
|
||||
destination.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0, false);
|
||||
destination.Apply(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
RenderTexture.active = previous;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把浮点/带 alpha 的纹理压成 RGB24:透明部分按 <paramref name="background"/> 混合,
|
||||
/// 分量截到 0~1。JPG 没有 alpha 通道,直接用原图编码会得到一圈发黑的边。
|
||||
/// </summary>
|
||||
public static Texture2D FlattenOntoBackground(Texture2D source, Color background)
|
||||
{
|
||||
int width = source.width;
|
||||
int height = source.height;
|
||||
var flattened = new Texture2D(width, height, TextureFormat.RGB24, false, false)
|
||||
{
|
||||
name = source.name,
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
|
||||
Color[] pixels = source.GetPixels();
|
||||
for (int i = 0; i < pixels.Length; i++)
|
||||
{
|
||||
Color p = pixels[i];
|
||||
float a = Mathf.Clamp01(p.a);
|
||||
pixels[i] = new Color(
|
||||
Mathf.Lerp(background.r, p.r, a),
|
||||
Mathf.Lerp(background.g, p.g, a),
|
||||
Mathf.Lerp(background.b, p.b, a),
|
||||
1f);
|
||||
}
|
||||
flattened.SetPixels(pixels);
|
||||
flattened.Apply(false);
|
||||
return flattened;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把一张纹理/RT 画成 Sprite。注意 Sprite 不拥有纹理:纹理销毁了 Sprite 就空了,
|
||||
/// 所以调用方要么留着纹理,要么连纹理一起作为资产存下来。
|
||||
/// </summary>
|
||||
public static Sprite ToSprite(Texture2D texture, Vector2 pivot, float pixelsPerUnit, string name = null)
|
||||
{
|
||||
if (texture == null)
|
||||
throw new ArgumentNullException(nameof(texture));
|
||||
var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), pivot, pixelsPerUnit);
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
sprite.name = name;
|
||||
return sprite;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 把材质渲染成图的执行者。<b>运行时与编辑器都能用</b>:全程不碰 UnityEditor,
|
||||
/// 不往场景里放相机或 GameObject——离屏渲染靠 CommandBuffer 自带视图/投影矩阵。
|
||||
///
|
||||
/// <para><b>用法</b>:<c>using (var r = new ShaderBakeRenderer(mat)) { var tex = r.RenderToTexture2D(); ... }</c>,
|
||||
/// 或者常驻一个实例反复改 <see cref="settings"/> 再 <see cref="Render"/>(预览就是这条路)。</para>
|
||||
///
|
||||
/// <para><b>已知的渲染环境限制</b>:没有真实相机,于是灯光、雾、环境光、阴影都不参与——
|
||||
/// Unlit 类 shader 效果一致,Surface/光照类 shader 会渲成"无灯"。要带光照请改用场景相机截帧,
|
||||
/// 那是另一条路,这里不假装支持。</para>
|
||||
/// </summary>
|
||||
public sealed class ShaderBakeRenderer : IDisposable
|
||||
{
|
||||
/// <summary> 怎么渲。外部可以直接改这个对象里的字段,改完调用 Render 就会跟着生效。 </summary>
|
||||
public ShaderBakeSettings settings = ShaderBakeSettings.CreateDefault();
|
||||
|
||||
/// <summary> 渲什么。允许为 null(此时 Render 返回 null 并留一条 lastError)。 </summary>
|
||||
public Material material;
|
||||
|
||||
/// <summary> 最近一次失败的原因;成功时清空。给界面状态栏用,不让用户去 Console 里找。 </summary>
|
||||
public string lastError = string.Empty;
|
||||
|
||||
private Mesh m_Geometry;
|
||||
private string m_GeometrySignature = string.Empty;
|
||||
private RenderTexture m_OwnedTarget;
|
||||
private string m_TargetSignature = string.Empty;
|
||||
private RenderTexture m_MultiSampleSource;
|
||||
private CommandBuffer m_Buffer;
|
||||
|
||||
/// <summary> 当前这次烘焙用的网格(只读用途,外部别销毁) </summary>
|
||||
public Mesh geometry { get { return m_Geometry; } }
|
||||
|
||||
/// <summary> 上一次渲染留下的目标(可能为 null)。预览直接拿它显示,省一次重建。 </summary>
|
||||
public RenderTexture target { get { return m_OwnedTarget; } }
|
||||
|
||||
/// <summary> 面片在世界空间的包围盒(相机框位用) </summary>
|
||||
public Bounds geometryBounds
|
||||
{
|
||||
get { return ShaderBakeGeometryBuilder.GetWorldBounds(m_Geometry, settings.surface.localMatrix); }
|
||||
}
|
||||
|
||||
/// <summary> 参数变了但还没重画:界面用它决定状态栏写"待刷新"还是"已渲染" </summary>
|
||||
public bool isDirty
|
||||
{
|
||||
get { return m_TargetSignature != settings.output.GetTargetSignature() || m_GeometrySignature != settings.surface.GetGeometrySignature(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 渲一次。<paramref name="target"/> 为空时用内部缓存的目标(尺寸变了自动重建),
|
||||
/// 非空时渲进调用方那张(要求宽高与 settings.output 一致,否则 Unity 只会画一部分)。
|
||||
/// 返回真正写入了结果的那张 RT,可能是传入的那张,也可能是内部那张。
|
||||
/// </summary>
|
||||
public RenderTexture Render(RenderTexture target = null)
|
||||
{
|
||||
lastError = string.Empty;
|
||||
|
||||
if (material == null)
|
||||
{
|
||||
lastError = "没有材质:先给一个 Shader 或 Material";
|
||||
return null;
|
||||
}
|
||||
if (material.shader == null)
|
||||
{
|
||||
lastError = "材质上的 shader 丢了";
|
||||
return null;
|
||||
}
|
||||
|
||||
settings.ClampAll();
|
||||
EnsureGeometry();
|
||||
if (m_Geometry == null)
|
||||
{
|
||||
lastError = "几何构建失败";
|
||||
return null;
|
||||
}
|
||||
|
||||
RenderTexture dest = target ?? EnsureOwnedTarget();
|
||||
if (dest == null)
|
||||
{
|
||||
lastError = "目标纹理创建失败(尺寸或格式超出显卡限制)";
|
||||
return null;
|
||||
}
|
||||
|
||||
// MSAA 目标不能直接被 ReadPixels 读到解析后的像素,所以先画进采样目标,再 Blit 回普通目标
|
||||
bool needResolve = settings.output.antiAliasing > 1 && target == null && m_MultiSampleSource != null;
|
||||
RenderTexture drawn = needResolve ? m_MultiSampleSource : dest;
|
||||
|
||||
DrawInto(drawn);
|
||||
|
||||
if (needResolve)
|
||||
Graphics.Blit(m_MultiSampleSource, dest);
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/// <summary> 渲成可读 Texture2D(调用方负责销毁)。导出文件与存资产都从这里出发。 </summary>
|
||||
public Texture2D RenderToTexture2D(bool generateMips = false)
|
||||
{
|
||||
RenderTexture rt = Render();
|
||||
if (rt == null)
|
||||
return null;
|
||||
var texture = ShaderBakeReadback.ToTexture2D(rt, settings.output.textureFormat, settings.output.isLinearTexture, generateMips);
|
||||
texture.name = material != null ? material.name : "ShaderBakeResult";
|
||||
return texture;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 渲成 Sprite。返回的 Sprite 持有那张纹理,<b>别去销毁 sprite.texture</b>;
|
||||
/// 默认轴心在正中、100 像素=1 单位,和 Unity 新建 Sprite 的默认值一致。
|
||||
/// </summary>
|
||||
public Sprite RenderToSprite(float pixelsPerUnit = 100f, float pivotX = 0.5f, float pivotY = 0.5f)
|
||||
{
|
||||
Texture2D texture = RenderToTexture2D(false);
|
||||
if (texture == null)
|
||||
return null;
|
||||
return ShaderBakeReadback.ToSprite(texture, new Vector2(pivotX, pivotY), Mathf.Max(pixelsPerUnit, 0.01f), texture.name);
|
||||
}
|
||||
|
||||
/// <summary> 渲成图片文件的字节。textureToKeep 非空时把中间纹理交出去由调用方销毁,否则就地销毁。 </summary>
|
||||
public byte[] RenderToBytes(ShaderBakeImageFormat format, out Texture2D textureToKeep)
|
||||
{
|
||||
textureToKeep = null;
|
||||
Texture2D texture = RenderToTexture2D(false);
|
||||
if (texture == null)
|
||||
return null;
|
||||
if (format.NeedsFloatSource() && !settings.output.hdr)
|
||||
Debug.LogWarning("[ShaderBake] EXR 建议配 HDR 输出,否则值域被截到 0~1");
|
||||
|
||||
byte[] bytes = format.Encode(texture, settings.output.clearColor);
|
||||
textureToKeep = texture;
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary> 渲成图片文件的字节(中间纹理自动回收) </summary>
|
||||
public byte[] RenderToBytes(ShaderBakeImageFormat format, bool destroyTexture = true)
|
||||
{
|
||||
Texture2D texture;
|
||||
byte[] bytes = RenderToBytes(format, out texture);
|
||||
if (destroyTexture && texture != null)
|
||||
ReleaseTempObject(texture);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// <summary> 把相机挪到刚好框住面片。改了尺寸/位置之后按一下就回到"看得见"的状态。 </summary>
|
||||
public void FitCameraToGeometry()
|
||||
{
|
||||
EnsureGeometry();
|
||||
if (m_Geometry == null)
|
||||
return;
|
||||
settings.camera.FrameBounds(geometryBounds, settings.aspect);
|
||||
}
|
||||
|
||||
/// <summary> 网格与相机指纹都记下来,界面据此判断要不要重建 </summary>
|
||||
public string stateSignature
|
||||
{
|
||||
get { return settings.output.GetTargetSignature() + "|" + settings.surface.GetGeometrySignature() + "|" + settings.camera.GetCameraSignature(); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只重建网格(面片参数变了)。渲染路径本来就会在签名不符时重建,这里给界面留个显式入口。
|
||||
/// </summary>
|
||||
public void InvalidateGeometry()
|
||||
{
|
||||
m_GeometrySignature = string.Empty;
|
||||
}
|
||||
|
||||
private void EnsureGeometry()
|
||||
{
|
||||
string signature = settings.surface.GetGeometrySignature();
|
||||
if (m_Geometry != null && signature == m_GeometrySignature)
|
||||
return;
|
||||
|
||||
ReleaseTempObject(m_Geometry);
|
||||
m_Geometry = ShaderBakeGeometryBuilder.Build(settings.surface);
|
||||
m_GeometrySignature = signature;
|
||||
}
|
||||
|
||||
private RenderTexture EnsureOwnedTarget()
|
||||
{
|
||||
string signature = settings.output.GetTargetSignature();
|
||||
if (m_OwnedTarget != null && signature == m_TargetSignature)
|
||||
return m_OwnedTarget;
|
||||
|
||||
ReleaseTempObject(m_OwnedTarget);
|
||||
ReleaseTempObject(m_MultiSampleSource);
|
||||
m_OwnedTarget = settings.output.CreateRenderTexture("ShaderBakeTarget");
|
||||
m_TargetSignature = m_OwnedTarget != null ? signature : string.Empty;
|
||||
|
||||
if (settings.output.antiAliasing > 1 && m_OwnedTarget != null)
|
||||
m_MultiSampleSource = settings.output.CreateRenderTexture("ShaderBakeMultiSample");
|
||||
|
||||
return m_OwnedTarget;
|
||||
}
|
||||
|
||||
private void DrawInto(RenderTexture rt)
|
||||
{
|
||||
if (m_Buffer == null)
|
||||
{
|
||||
m_Buffer = new CommandBuffer { name = "XericUI.ShaderBake" };
|
||||
}
|
||||
|
||||
Matrix4x4 projection = settings.camera.GetProjectionMatrix(settings.aspect);
|
||||
if (settings.output.flipY)
|
||||
projection = Matrix4x4.Scale(new Vector3(1f, -1f, 1f)) * projection;
|
||||
|
||||
m_Buffer.Clear();
|
||||
m_Buffer.SetRenderTarget(rt, 0, CubemapFace.Unknown, 0);
|
||||
m_Buffer.ClearRenderTarget(true, true, settings.output.clearColor, 1f);
|
||||
m_Buffer.SetViewProjectionMatrices(settings.camera.viewMatrix, projection);
|
||||
m_Buffer.DrawMesh(m_Geometry, settings.surface.localMatrix, material,
|
||||
Mathf.Max(settings.surface.meshSubMesh, 0), settings.output.shaderPass);
|
||||
Graphics.ExecuteCommandBuffer(m_Buffer);
|
||||
m_Buffer.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 回收一次性对象。运行时要走 <c>Destroy</c>(当帧不能立即销毁),编辑器里请传
|
||||
/// <paramref name="immediate"/> 让 <c>DestroyImmediate</c> 立刻放掉显存——导一批图时差别很大。
|
||||
/// </summary>
|
||||
public static void ReleaseTempObject(UnityEngine.Object obj)
|
||||
{
|
||||
ReleaseTempObject(obj, false);
|
||||
}
|
||||
|
||||
internal static void ReleaseTempObject(UnityEngine.Object obj, bool immediate)
|
||||
{
|
||||
if (obj == null)
|
||||
return;
|
||||
#if UNITY_EDITOR
|
||||
if (immediate || !Application.isPlaying)
|
||||
UnityEngine.Object.DestroyImmediate(obj);
|
||||
else
|
||||
UnityEngine.Object.Destroy(obj);
|
||||
#else
|
||||
UnityEngine.Object.Destroy(obj);
|
||||
#endif
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
|
||||
/// <summary> 编辑器里关窗口时传 immediate,显存和网格内存当场还回去 </summary>
|
||||
public void Dispose(bool immediate)
|
||||
{
|
||||
if (m_Buffer != null)
|
||||
{
|
||||
m_Buffer.Release();
|
||||
m_Buffer.Dispose();
|
||||
m_Buffer = null;
|
||||
}
|
||||
ReleaseTempObject(m_MultiSampleSource, immediate);
|
||||
ReleaseTempObject(m_OwnedTarget, immediate);
|
||||
ReleaseTempObject(m_Geometry, immediate);
|
||||
m_MultiSampleSource = null;
|
||||
m_OwnedTarget = null;
|
||||
m_Geometry = null;
|
||||
m_TargetSignature = string.Empty;
|
||||
m_GeometrySignature = string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 一次烘焙所需的全部参数:输出 / 面片 / 离屏相机三组。
|
||||
/// 材质不进这里——材质是"内容",会换、会被就地编辑,而这一份是"怎么渲",可以存下来复用。
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeSettings
|
||||
{
|
||||
[Tooltip("输出目标")]
|
||||
public ShaderBakeOutputSettings output = new ShaderBakeOutputSettings();
|
||||
|
||||
[Tooltip("被渲染的面片")]
|
||||
public ShaderBakeSurfaceSettings surface = new ShaderBakeSurfaceSettings();
|
||||
|
||||
[Tooltip("离屏相机")]
|
||||
public ShaderBakeCameraSettings camera = new ShaderBakeCameraSettings();
|
||||
|
||||
/// <summary> 画面宽高比 </summary>
|
||||
public float aspect
|
||||
{
|
||||
get
|
||||
{
|
||||
if (output.height <= 0 || output.width <= 0) return 1f;
|
||||
return (float)output.width / output.height;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary> 三组参数各自归位 </summary>
|
||||
public void ClampAll()
|
||||
{
|
||||
output.Clamp();
|
||||
surface.Clamp();
|
||||
}
|
||||
|
||||
/// <summary> 复制一份(编辑器窗口拿它当工作副本,改坏了不至于污染存下来的那份) </summary>
|
||||
public ShaderBakeSettings Clone()
|
||||
{
|
||||
return FromJson(ToJson());
|
||||
}
|
||||
|
||||
/// <summary> JsonUtility 只吃 [Serializable] 的类,这里三组都满足;Mesh / 材质引用序列化成实例ID,读回来时由界面重新指派 </summary>
|
||||
public string ToJson()
|
||||
{
|
||||
return JsonUtility.ToJson(this);
|
||||
}
|
||||
|
||||
public static ShaderBakeSettings FromJson(string json)
|
||||
{
|
||||
if (string.IsNullOrEmpty(json)) return CreateDefault();
|
||||
var s = new ShaderBakeSettings();
|
||||
JsonUtility.FromJsonOverwrite(json, s);
|
||||
s.ClampAll();
|
||||
return s;
|
||||
}
|
||||
|
||||
public static ShaderBakeSettings CreateDefault()
|
||||
{
|
||||
return new ShaderBakeSettings();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary> 被烘焙的几何面片是哪一种 </summary>
|
||||
public enum ShaderBakeSurfaceKind
|
||||
{
|
||||
/// <summary>单片四边形:两个三角面,UV 从 uvOffset 起、按 uvTiling 铺 </summary>
|
||||
Quad,
|
||||
|
||||
/// <summary>细分平面:顶点数量由 segments 决定,给"在顶点着色器里挪顶点"的 shader 留出梯度 </summary>
|
||||
Plane,
|
||||
|
||||
/// <summary>外部网格:模型(导入的或场景里挑的),UV 沿用网格自己的第 0 套再乘偏移缩放 </summary>
|
||||
Mesh
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 面片设置:形状、UV 变换与面片自身的变换("面片编辑"就是这一组数值)。
|
||||
///
|
||||
/// <para><b>UV 变换落在网格上而不是材质上</b>:这样 shader 里怎么写 <c>uv</c> 就怎么收到结果,
|
||||
/// 不会被 <c>_MainTex_ST</c> 之类的第二层缩放重复一遍。需要走 ST 的那类 shader 用
|
||||
/// <see cref="applyUvToMainTexST"/> 单独开。</para>
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeSurfaceSettings
|
||||
{
|
||||
/// <summary> 细分上限:单边 512 段=26 万顶点,再多就是把手抖拖进卡顿 </summary>
|
||||
public const int kMaxSegments = 512;
|
||||
|
||||
[Tooltip("面片种类:单片四边形 / 细分平面 / 外部网格")]
|
||||
public ShaderBakeSurfaceKind kind = ShaderBakeSurfaceKind.Quad;
|
||||
|
||||
[Tooltip("面片尺寸(世界单位)。四边形与细分平面用它的 x/y;外部网格只在 normalizeSize 打开时用它缩放")]
|
||||
public Vector2 size = Vector2.one;
|
||||
|
||||
[Tooltip("细分平面的行列段数。只有需要顶点插值的 shader 才要调大,四边形恒为 1x1")]
|
||||
public Vector2Int segments = Vector2Int.one;
|
||||
|
||||
[Tooltip("UV 起点偏移:把贴图的哪一块挪到面片左下角")]
|
||||
public Vector2 uvOffset;
|
||||
|
||||
[Tooltip("UV 重复次数(缩放):x/y 各铺几遍")]
|
||||
public Vector2 uvTiling = Vector2.one;
|
||||
|
||||
[Tooltip("外部网格(kind = 外部网格 时生效)")]
|
||||
public Mesh sourceMesh;
|
||||
|
||||
[Tooltip("外部网格用第几个 subMesh")]
|
||||
public int meshSubMesh;
|
||||
|
||||
[Tooltip("把外部网格归一化到 size 指定的尺寸(关掉就按模型原始米数渲,可能只占画面一角)")]
|
||||
public bool normalizeMeshSize = true;
|
||||
|
||||
[Tooltip("面片位置偏移")]
|
||||
public Vector3 position;
|
||||
|
||||
[Tooltip("面片旋转(欧拉角,度)")]
|
||||
public Vector3 eulerAngles;
|
||||
|
||||
[Tooltip("面片额外缩放(与 size 相乘,外部网格用它做整体缩放)")]
|
||||
public Vector3 scale = Vector3.one;
|
||||
|
||||
[Tooltip("把 UV 偏移/重复同时写进 _MainTex_ST:给 Standard / Unlit 那类靠 ST 做缩放的 shader 用")]
|
||||
public bool applyUvToMainTexST;
|
||||
|
||||
/// <summary> 面片自己的局部变换矩阵(DrawMesh 用的那个 model 矩阵) </summary>
|
||||
public Matrix4x4 localMatrix
|
||||
{
|
||||
get { return Matrix4x4.TRS(position, Quaternion.Euler(eulerAngles), scale); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 收拢非法数值。段数与 subMesh 都可能被敲成负数或超出网格实际层数,这里一次归位。
|
||||
/// </summary>
|
||||
public void Clamp()
|
||||
{
|
||||
size = new Vector2(
|
||||
Mathf.Max(size.x, 0.0001f),
|
||||
Mathf.Max(size.y, 0.0001f));
|
||||
segments = new Vector2Int(
|
||||
Mathf.Clamp(segments.x, 1, kMaxSegments),
|
||||
Mathf.Clamp(segments.y, 1, kMaxSegments));
|
||||
scale = new Vector3(
|
||||
FixZero(scale.x),
|
||||
FixZero(scale.y),
|
||||
FixZero(scale.z));
|
||||
if (uvTiling.x == 0f) uvTiling.x = 1f;
|
||||
if (uvTiling.y == 0f) uvTiling.y = 1f;
|
||||
meshSubMesh = Mathf.Max(meshSubMesh, 0);
|
||||
}
|
||||
|
||||
private static float FixZero(float v)
|
||||
{
|
||||
return Mathf.Abs(v) < 0.0001f ? 1f : v;
|
||||
}
|
||||
|
||||
/// <summary> 几何指纹:变了就要重建网格 </summary>
|
||||
public string GetGeometrySignature()
|
||||
{
|
||||
var meshId = sourceMesh != null ? sourceMesh.GetInstanceID().ToString() : "none";
|
||||
return kind + "_" + size + "_" + segments + "_" + uvOffset + "_" + uvTiling +
|
||||
"_" + position + "_" + eulerAngles + "_" + scale + "_" + meshId + "_" + meshSubMesh +
|
||||
"_" + normalizeMeshSize;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user