合并 dev2 的 ShaderBake 线(17 提交,2026-11-05/06)到 dev_chart
两条线从 a311c41 分叉:他那边是烘焙工具(编辑器窗口 + runtime 出图),
我这边是反射生成 UI 的字段配方。文件集只共用 Runtime/Core/XericRegistrationPaths.cs,
且他那侧只是新增 ToolBar 常量、两套根(工具栏 XericLibrary/Action Vessel、
右键 Xeric Library/Action Vessel)都保住了,所以合并无冲突。
This commit is contained in:
@@ -1,2 +1,4 @@
|
||||
.trae/
|
||||
.recode/
|
||||
# 本地离线编译校验脚本:写死了本机 Unity 安装路径,不进版本库
|
||||
.dbg/
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e07b0f08da31c98439dbdbe3da2f41c3
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 45db25770fc1d0b4b94396d3100c4167
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,21 @@
|
||||
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:x="UnityEditor.UIElements" xmlns:xer="XericUI.ShaderBake.Editor">
|
||||
<!--
|
||||
全局参数表的一行:勾选 + 名字 + 按类型只留一个输入控件。
|
||||
取控件一律在克隆出来的行内查(row.Q),不查全局。
|
||||
-->
|
||||
<ui:VisualElement name="global-row" class="prop-row global-row">
|
||||
<ui:Toggle name="global-enabled" class="global-enabled" />
|
||||
<ui:Label name="global-name" class="prop-label global-name" text="全局量" />
|
||||
<ui:VisualElement name="global-field" class="prop-field">
|
||||
<xer:FloatField name="global-float" class="prop-inline" />
|
||||
<ui:VisualElement name="global-vector" class="prop-vector">
|
||||
<xer:FloatField name="global-x" label="X" class="prop-vec-part" />
|
||||
<xer:FloatField name="global-y" label="Y" class="prop-vec-part" />
|
||||
<xer:FloatField name="global-z" label="Z" class="prop-vec-part" />
|
||||
<xer:FloatField name="global-w" label="W" class="prop-vec-part" />
|
||||
</ui:VisualElement>
|
||||
<x:ColorField name="global-color" class="prop-inline" />
|
||||
<x:ObjectField name="global-texture" class="prop-inline" />
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
</ui:UXML>
|
||||
@@ -0,0 +1,10 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cefd2e1ff10470d43a04e520e0636bbe
|
||||
ScriptedImporter:
|
||||
internalIDToNameTable: []
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0}
|
||||
@@ -0,0 +1,29 @@
|
||||
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:x="UnityEditor.UIElements" xmlns:xer="XericUI.ShaderBake.Editor">
|
||||
<!--
|
||||
材质属性表的一行模板:结构写在这里,控件种类摊开成兄弟节点,
|
||||
BakeShaderPropertyTable.cs 负责"留哪一个、其余收起来"。
|
||||
行里的 name 会在多行之间重复,所以取控件一律在克隆出来的行内查(row.Q),不查全局。
|
||||
样式跟着窗口根上的 BakeShaderWindow.uss 走,这里不重复挂样式表。
|
||||
-->
|
||||
<ui:VisualElement name="prop-row" class="prop-row">
|
||||
<ui:Label name="prop-label" class="prop-label" text="属性" />
|
||||
<ui:VisualElement name="prop-field" class="prop-field">
|
||||
<xer:FloatField name="prop-float" class="prop-inline" />
|
||||
<xer:IntegerField name="prop-int" class="prop-inline" />
|
||||
<ui:Toggle name="prop-toggle" class="prop-inline" />
|
||||
<ui:DropdownField name="prop-enum" class="prop-inline" />
|
||||
<x:ColorField name="prop-color" class="prop-inline" />
|
||||
<x:ObjectField name="prop-texture" class="prop-inline" />
|
||||
<ui:VisualElement name="prop-range" class="prop-range">
|
||||
<ui:Slider name="prop-slider" class="prop-slider" />
|
||||
<xer:FloatField name="prop-range-value" class="prop-range-value" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement name="prop-vector" class="prop-vector">
|
||||
<xer:FloatField name="prop-vec-x" label="X" class="prop-vec-part" />
|
||||
<xer:FloatField name="prop-vec-y" label="Y" class="prop-vec-part" />
|
||||
<xer:FloatField name="prop-vec-z" label="Z" class="prop-vec-part" />
|
||||
<xer:FloatField name="prop-vec-w" label="W" class="prop-vec-part" />
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
</ui:UXML>
|
||||
@@ -0,0 +1,10 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 029d91f86bf22cf47b96a8eb073d2029
|
||||
ScriptedImporter:
|
||||
internalIDToNameTable: []
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0}
|
||||
@@ -0,0 +1,336 @@
|
||||
/* ============================================================
|
||||
Bake Shader As Image 窗口样式。
|
||||
结构见 BakeShaderWindow.uxml,这里只放尺寸与配色;
|
||||
工具栏一族(Toolbar*)自带引擎配色与高度,不要再给它设背景。
|
||||
============================================================ */
|
||||
|
||||
.bake-root {
|
||||
flex-direction: column;
|
||||
flex-grow: 1;
|
||||
background-color: rgb(38, 38, 38);
|
||||
}
|
||||
|
||||
/* ── 顶部 / 底部工具栏 ── */
|
||||
.main-toolbar,
|
||||
.status-bar {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.toolbar-gap {
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.tool-narrow {
|
||||
min-width: 26px;
|
||||
width: 26px;
|
||||
}
|
||||
|
||||
.toolbar-emphasize {
|
||||
-unity-text-align: middle-center;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.status-message {
|
||||
font-size: 12px;
|
||||
-unity-text-align: middle-left;
|
||||
color: rgb(210, 210, 210);
|
||||
}
|
||||
|
||||
.status-readout {
|
||||
font-size: 11px;
|
||||
-unity-text-align: middle-right;
|
||||
color: rgb(160, 160, 160);
|
||||
margin-left: 6px;
|
||||
margin-right: 6px;
|
||||
}
|
||||
|
||||
/* ── 中部:左浏览图 + 右细节 ── */
|
||||
.main-row {
|
||||
flex-direction: row;
|
||||
flex-grow: 1;
|
||||
min-height: 120px;
|
||||
}
|
||||
|
||||
.preview-pane {
|
||||
flex-direction: column;
|
||||
flex-grow: 1;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.preview-viewport {
|
||||
flex-grow: 1;
|
||||
background-color: rgb(48, 48, 48);
|
||||
/* 浏览区是一块画布,不该有内边距把图挤到角上 */
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.preview-viewport > .unity-scroll-view__content-container {
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.preview-stage {
|
||||
flex-grow: 1;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 100%;
|
||||
}
|
||||
|
||||
.preview-frame {
|
||||
position: relative;
|
||||
margin: 12px;
|
||||
border-width: 1px;
|
||||
border-color: rgb(90, 90, 90);
|
||||
}
|
||||
|
||||
.preview-checker,
|
||||
.preview-image {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
/* 两张都按画面尺寸摆放,谁大谁小由代码算,样式不掺和 */
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.preview-checker {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.preview-readout {
|
||||
position: absolute;
|
||||
left: 8px;
|
||||
bottom: 8px;
|
||||
font-size: 11px;
|
||||
color: rgb(220, 220, 220);
|
||||
background-color: rgba(0, 0, 0, 0.45);
|
||||
padding: 1px 6px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.detail-split {
|
||||
width: 3px;
|
||||
flex-shrink: 0;
|
||||
background-color: rgb(60, 60, 60);
|
||||
}
|
||||
|
||||
.detail-split:hover {
|
||||
background-color: rgb(94, 142, 206);
|
||||
}
|
||||
|
||||
.detail-pane {
|
||||
width: 340px;
|
||||
min-width: 240px;
|
||||
flex-shrink: 0;
|
||||
background-color: rgb(42, 42, 42);
|
||||
border-left-width: 1px;
|
||||
border-left-color: rgb(60, 60, 60);
|
||||
}
|
||||
|
||||
/* 2021.2 之前叫 content-viewport,之后叫 content-container,两个都写上省得按版本失效 */
|
||||
.detail-pane > .unity-scroll-view__content-container,
|
||||
.detail-pane > .unity-scroll-view__content-viewport {
|
||||
width: 100%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.detail-content {
|
||||
width: 100%;
|
||||
flex-shrink: 0;
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
/* ── 分组 ── */
|
||||
.section {
|
||||
border-bottom-width: 1px;
|
||||
border-bottom-color: rgb(52, 52, 52);
|
||||
padding-top: 4px;
|
||||
padding-bottom: 6px;
|
||||
}
|
||||
|
||||
.section-head {
|
||||
font-size: 12px;
|
||||
margin-left: 6px;
|
||||
margin-bottom: 2px;
|
||||
color: rgb(225, 225, 225);
|
||||
}
|
||||
|
||||
.section-body {
|
||||
padding-left: 8px;
|
||||
padding-right: 8px;
|
||||
}
|
||||
|
||||
/* ── 控件排布 ── */
|
||||
.field-row {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.field-full {
|
||||
flex-grow: 1;
|
||||
flex-shrink: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* flex-basis: 0 是关键:默认 auto 会按内容宽度(标题 + 输入框)定基宽,
|
||||
* 一行两栏/三栏加起来必然超过侧栏宽度,输入框被挤到可视区外——表现就是"数值文本不显示"。
|
||||
*/
|
||||
.field-half {
|
||||
flex-grow: 1;
|
||||
flex-shrink: 1;
|
||||
flex-basis: 0;
|
||||
min-width: 0;
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
.field-third {
|
||||
flex-grow: 1;
|
||||
flex-shrink: 1;
|
||||
flex-basis: 0;
|
||||
min-width: 0;
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
.field-quarter {
|
||||
flex-grow: 1;
|
||||
flex-shrink: 1;
|
||||
flex-basis: 0;
|
||||
min-width: 0;
|
||||
margin-right: 3px;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
/* 2021.3 的字段标题默认吃 120px 左右,窄栏里会把输入区压没;侧栏内统一收窄 */
|
||||
.detail-content .unity-base-field__label,
|
||||
.detail-content .unity-text-field__label,
|
||||
.detail-content .unity-base-text-field__label {
|
||||
min-width: 30px;
|
||||
flex-shrink: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.detail-content .unity-base-field__input,
|
||||
.detail-content .unity-text-field__input,
|
||||
.detail-content .unity-base-text-field__input {
|
||||
flex-shrink: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ── 浏览图里的选中面片高亮 ── */
|
||||
.face-overlay {
|
||||
position: absolute;
|
||||
display: none;
|
||||
border-width: 1px;
|
||||
border-color: rgb(255, 196, 64);
|
||||
background-color: rgba(255, 196, 64, 0.14);
|
||||
}
|
||||
|
||||
.face-overlay-label {
|
||||
position: absolute;
|
||||
left: 2px;
|
||||
top: 2px;
|
||||
font-size: 10px;
|
||||
color: rgb(255, 224, 160);
|
||||
background-color: rgba(0, 0, 0, 0.55);
|
||||
padding: 0 4px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.field-toggle {
|
||||
font-size: 11px;
|
||||
margin-top: 2px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.field-note {
|
||||
font-size: 10px;
|
||||
color: rgb(150, 150, 150);
|
||||
margin-top: 6px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
/* ── 材质属性行 ── */
|
||||
.props-rows {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.prop-row {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
min-height: 18px;
|
||||
}
|
||||
|
||||
.prop-label {
|
||||
width: 108px;
|
||||
flex-shrink: 0;
|
||||
font-size: 11px;
|
||||
color: rgb(200, 200, 200);
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.prop-field {
|
||||
flex-grow: 1;
|
||||
flex-shrink: 1;
|
||||
min-width: 0;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.prop-inline {
|
||||
flex-grow: 1;
|
||||
flex-shrink: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.prop-range {
|
||||
flex-grow: 1;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.prop-slider {
|
||||
flex-grow: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.prop-range-value {
|
||||
width: 58px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.prop-vector {
|
||||
flex-grow: 1;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.prop-vec-part {
|
||||
flex-grow: 1;
|
||||
flex-shrink: 1;
|
||||
min-width: 0;
|
||||
margin-right: 2px;
|
||||
}
|
||||
|
||||
/* ── 全局参数行 ── */
|
||||
.global-enabled {
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
.global-name {
|
||||
width: 118px;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.prop-vec-part > .unity-label {
|
||||
min-width: 12px;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
/* 属性行里的数字框不要各自那套标题——标签已经在行首了 */
|
||||
.prop-inline > .unity-label,
|
||||
.prop-range-value > .unity-label {
|
||||
display: none;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0a8fca2612d22d0419ef90f4eb5b3624
|
||||
ScriptedImporter:
|
||||
internalIDToNameTable: []
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0}
|
||||
disableValidation: 0
|
||||
@@ -0,0 +1,239 @@
|
||||
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:x="UnityEditor.UIElements" xmlns:xer="XericUI.ShaderBake.Editor">
|
||||
<!--
|
||||
Xeric UI Action Vessel — Bake Shader As Image 面板结构。
|
||||
这一份只管"有哪些块、块里有哪些控件、叫什么名字",
|
||||
数值绑定与刷新逻辑全在 BakeShaderAsImageWindow.cs;样式见 BakeShaderWindow.uss。
|
||||
|
||||
命名约定:
|
||||
sec-* 可折叠分组(head 是那个勾,body 是内容容器)
|
||||
src-/out-/surf-/cam- 分组内控件,前缀即所属分组
|
||||
props-rows 材质属性表的容器(行由 BakeShaderPropertyRow.uxml 模板克隆)
|
||||
-->
|
||||
|
||||
<!-- 样式表由窗口代码加载(包在 Packages/ 还是 Assets/ 两条路径都要兼容),这里不重复引用 -->
|
||||
|
||||
<ui:VisualElement name="bake-root" class="bake-root">
|
||||
|
||||
<!-- ── 顶部工具栏:导出 / 渲染 / 预览缩放 / 重置 ── -->
|
||||
<x:Toolbar name="main-toolbar" class="main-toolbar">
|
||||
<x:ToolbarButton name="export-menu" text="导出 ▾" class="toolbar-emphasize" />
|
||||
<x:ToolbarButton name="render-now" text="重新渲染" />
|
||||
<x:ToolbarToggle name="auto-refresh" text="实时预览" />
|
||||
<x:ToolbarSpacer class="toolbar-gap" />
|
||||
<x:ToolbarButton name="zoom-out" text="-" class="tool-narrow" />
|
||||
<x:ToolbarButton name="zoom-fit" text="适应" />
|
||||
<x:ToolbarButton name="zoom-actual" text="1:1" />
|
||||
<x:ToolbarButton name="zoom-in" text="+" class="tool-narrow" />
|
||||
<x:ToolbarToggle name="show-checker" text="透明底" />
|
||||
<x:ToolbarSpacer class="toolbar-gap" />
|
||||
<x:ToolbarButton name="reset-settings" text="重置参数" />
|
||||
</x:Toolbar>
|
||||
|
||||
<!-- ── 中部:左边浏览图,右边细节列表 ── -->
|
||||
<ui:VisualElement name="main-row" class="main-row">
|
||||
|
||||
<ui:VisualElement name="preview-pane" class="preview-pane">
|
||||
<ui:ScrollView name="preview-viewport" class="preview-viewport" mode="Both">
|
||||
<ui:VisualElement name="preview-stage" class="preview-stage">
|
||||
<ui:VisualElement name="preview-frame" class="preview-frame">
|
||||
<ui:Image name="preview-checker" class="preview-checker" />
|
||||
<ui:Image name="preview-image" class="preview-image" />
|
||||
<!-- 选中面片的高亮:位置按百分比算,缩放时不用重排 -->
|
||||
<ui:VisualElement name="face-overlay" class="face-overlay">
|
||||
<ui:Label name="face-overlay-label" class="face-overlay-label" text="UV (0,0)" />
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
</ui:ScrollView>
|
||||
<!-- 读数浮在预览区左下角:缩放比与像素尺寸是看图时才关心的东西,不该占一行 -->
|
||||
<ui:Label name="preview-readout" class="preview-readout" text="-" />
|
||||
</ui:VisualElement>
|
||||
|
||||
<ui:VisualElement name="detail-split" class="detail-split" />
|
||||
|
||||
<ui:ScrollView name="detail-pane" class="detail-pane" mode="Vertical">
|
||||
<ui:VisualElement name="detail-content" class="detail-content">
|
||||
|
||||
<!-- 输入源 -->
|
||||
<ui:VisualElement name="sec-source" class="section">
|
||||
<ui:Toggle name="sec-source-head" label="输入源" value="true" class="section-head" />
|
||||
<ui:VisualElement name="sec-source-body" class="section-body">
|
||||
<x:ObjectField name="src-shader" label="Shader" class="field-full" />
|
||||
<x:ObjectField name="src-material" label="Material" class="field-full" />
|
||||
<ui:Label name="src-note" class="field-note" text="未指定" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<ui:Button name="src-apply" text="写回原材质" class="field-half" />
|
||||
<ui:Button name="src-revert" text="丢弃改动" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
|
||||
<!-- 输出目标 -->
|
||||
<ui:VisualElement name="sec-output" class="section">
|
||||
<ui:Toggle name="sec-output-head" label="输出" value="true" class="section-head" />
|
||||
<ui:VisualElement name="sec-output-body" class="section-body">
|
||||
<ui:VisualElement class="field-row">
|
||||
<ui:DropdownField name="out-preset" label="预设" class="field-half" />
|
||||
<ui:Button name="out-fit-aspect" text="匹配面片比例" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:IntegerField name="out-width" label="宽" class="field-half" />
|
||||
<xer:IntegerField name="out-height" label="高" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:IntegerField name="out-depth" label="深度" class="field-half" />
|
||||
<ui:DropdownField name="out-msaa" label="采样" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<xer:IntegerField name="out-pass" label="Pass 下标" class="field-full" />
|
||||
<x:ColorField name="out-clear" label="背景色" class="field-full" />
|
||||
<ui:Toggle name="out-hdr" label="HDR" class="field-toggle" />
|
||||
<ui:Toggle name="out-srgb" label="sRGB 存储" class="field-toggle" />
|
||||
<ui:Toggle name="out-flip" label="翻转 Y" class="field-toggle" />
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
|
||||
<!-- 面片 -->
|
||||
<ui:VisualElement name="sec-surface" class="section">
|
||||
<ui:Toggle name="sec-surface-head" label="面片" value="true" class="section-head" />
|
||||
<ui:VisualElement name="sec-surface-body" class="section-body">
|
||||
<xer:EnumField name="surf-kind" label="种类" class="field-full" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:FloatField name="surf-size-x" label="宽" class="field-half" />
|
||||
<xer:FloatField name="surf-size-y" label="高" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:IntegerField name="surf-seg-x" label="细分X" class="field-half" />
|
||||
<xer:IntegerField name="surf-seg-y" label="细分Y" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
|
||||
<ui:Label class="field-note" text="面片网格(一格一张 UV 区域,向左/下扩展编号递减)" />
|
||||
<ui:Label name="grid-info" class="field-note" text="1 × 1" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<ui:Button name="grid-left" text="←加列" class="field-quarter" />
|
||||
<ui:Button name="grid-right" text="加列→" class="field-quarter" />
|
||||
<ui:Button name="grid-down" text="↓加行" class="field-quarter" />
|
||||
<ui:Button name="grid-up" text="↑加行" class="field-quarter" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement class="field-row">
|
||||
<ui:Button name="grid-reset" text="恢复 1×1" class="field-half" />
|
||||
<ui:Button name="face-zero" text="选中面归零" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:Label name="face-info" class="field-note" text="在左侧浏览图里点选面片" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:IntegerField name="face-uv-x" label="UV X" class="field-half" />
|
||||
<xer:IntegerField name="face-uv-y" label="UV Y" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
|
||||
<ui:Label class="field-note" text="UV" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:FloatField name="surf-uv-off-x" label="偏移X" class="field-half" />
|
||||
<xer:FloatField name="surf-uv-off-y" label="偏移Y" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:FloatField name="surf-uv-tile-x" label="重复X" class="field-half" />
|
||||
<xer:FloatField name="surf-uv-tile-y" label="重复Y" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:Label class="field-note" text="面片变换" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:FloatField name="surf-pos-x" label="X" class="field-third" />
|
||||
<xer:FloatField name="surf-pos-y" label="Y" class="field-third" />
|
||||
<xer:FloatField name="surf-pos-z" label="Z" class="field-third" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:FloatField name="surf-rot-x" label="X" class="field-third" />
|
||||
<xer:FloatField name="surf-rot-y" label="Y" class="field-third" />
|
||||
<xer:FloatField name="surf-rot-z" label="Z" class="field-third" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:FloatField name="surf-scale-x" label="X" class="field-third" />
|
||||
<xer:FloatField name="surf-scale-y" label="Y" class="field-third" />
|
||||
<xer:FloatField name="surf-scale-z" label="Z" class="field-third" />
|
||||
</ui:VisualElement>
|
||||
<ui:Label class="field-note" text="外部网格" />
|
||||
<x:ObjectField name="surf-mesh" label="网格" class="field-full" />
|
||||
<xer:IntegerField name="surf-submesh" label="SubMesh" class="field-full" />
|
||||
<ui:Toggle name="surf-normalize" label="适配尺寸" class="field-toggle" />
|
||||
<ui:Toggle name="surf-uv-st" label="写 _MainTex_ST" class="field-toggle" />
|
||||
<ui:Toggle name="surf-double-sided" label="双面绘制" class="field-toggle" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<ui:Button name="surf-reset" text="面片归位" class="field-half" />
|
||||
<ui:Button name="surf-pick-scene" text="取选中物体" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:Button name="surf-import-model" text="导入模型文件…" class="field-full" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<ui:Button name="surf-rot-90" text="绕Z转90" class="field-third" />
|
||||
<ui:Button name="surf-flip-u" text="U镜像" class="field-third" />
|
||||
<ui:Button name="surf-flip-v" text="V镜像" class="field-third" />
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
|
||||
<!-- 离屏相机 -->
|
||||
<ui:VisualElement name="sec-camera" class="section">
|
||||
<ui:Toggle name="sec-camera-head" label="相机" value="true" class="section-head" />
|
||||
<ui:VisualElement name="sec-camera-body" class="section-body">
|
||||
<ui:Toggle name="cam-ortho" label="正交" class="field-toggle" />
|
||||
<xer:FloatField name="cam-ortho-size" label="正交半高" class="field-full" />
|
||||
<xer:FloatField name="cam-fov" label="视野角" class="field-full" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:FloatField name="cam-near" label="近" class="field-half" />
|
||||
<xer:FloatField name="cam-far" label="远" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:Label class="field-note" text="位置" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:FloatField name="cam-pos-x" label="X" class="field-third" />
|
||||
<xer:FloatField name="cam-pos-y" label="Y" class="field-third" />
|
||||
<xer:FloatField name="cam-pos-z" label="Z" class="field-third" />
|
||||
</ui:VisualElement>
|
||||
<ui:Label class="field-note" text="旋转(欧拉角)" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<xer:FloatField name="cam-rot-x" label="X" class="field-third" />
|
||||
<xer:FloatField name="cam-rot-y" label="Y" class="field-third" />
|
||||
<xer:FloatField name="cam-rot-z" label="Z" class="field-third" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement class="field-row">
|
||||
<ui:Button name="cam-fit" text="框住面片" class="field-half" />
|
||||
<ui:Button name="cam-selftest" text="管线自检" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:Label name="selftest-note" class="field-note"
|
||||
text="自检:用不依赖贴图与光照的内置纯色 shader 按同一套矩阵画一次,用来分清是渲染管线的问题还是被测 shader 本身的问题" />
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
|
||||
<!-- 全局参数:离屏渲染没有相机流程,光照/环境这类引擎全局量要自己补 -->
|
||||
<ui:VisualElement name="sec-globals" class="section">
|
||||
<ui:Toggle name="sec-globals-head" label="全局参数(光照 / 环境)" value="false" class="section-head" />
|
||||
<ui:VisualElement name="sec-globals-body" class="section-body">
|
||||
<ui:Label name="globals-note" class="field-note"
|
||||
text="引擎在相机流程里才写入的全局量(光照方向、环境光、反射探针)这里默认缺失;勾选的条目在渲染时注入,渲染完立即还原" />
|
||||
<ui:VisualElement class="field-row">
|
||||
<ui:Button name="globals-detect" text="扫描 Shader" class="field-half" />
|
||||
<ui:Button name="globals-presets" text="加入常用预设" class="field-half" />
|
||||
</ui:VisualElement>
|
||||
<ui:VisualElement name="globals-rows" class="props-rows" />
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
|
||||
<!-- 材质属性表:行来自 BakeShaderPropertyRow.uxml -->
|
||||
<ui:VisualElement name="sec-props" class="section">
|
||||
<ui:Toggle name="sec-props-head" label="材质属性" value="true" class="section-head" />
|
||||
<ui:VisualElement name="sec-props-body" class="section-body">
|
||||
<ui:VisualElement name="props-rows" class="props-rows" />
|
||||
<ui:Label name="props-note" class="field-note" text="未指定 shader" />
|
||||
</ui:VisualElement>
|
||||
</ui:VisualElement>
|
||||
|
||||
</ui:VisualElement>
|
||||
</ui:ScrollView>
|
||||
</ui:VisualElement>
|
||||
|
||||
<!-- ── 底部状态栏 ── -->
|
||||
<x:Toolbar name="status-bar" class="status-bar">
|
||||
<ui:Label name="status-message" class="status-message" text="未渲染" />
|
||||
<x:ToolbarSpacer class="toolbar-gap" />
|
||||
<ui:Label name="status-source" class="status-readout" text="-" />
|
||||
<ui:Label name="status-size" class="status-readout" text="-" />
|
||||
<ui:Label name="status-time" class="status-readout" text="-" />
|
||||
</x:Toolbar>
|
||||
</ui:VisualElement>
|
||||
</ui:UXML>
|
||||
@@ -0,0 +1,10 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f32f184a4b5088547a2011392c2669f2
|
||||
ScriptedImporter:
|
||||
internalIDToNameTable: []
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0}
|
||||
@@ -0,0 +1,297 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake.Editor
|
||||
{
|
||||
/// <summary>
|
||||
/// 导出:Unity 的图像类型(Texture2D / Sprite / RenderTexture)落成资产,
|
||||
/// 或按 Texture2D 自带的编码方法写成 PNG / JPG / TGA / EXR 文件。
|
||||
///
|
||||
/// <para><b>文件落在工程内和工程外走两条路</b>:落在 Assets 下面时必须触发导入并写导入设置
|
||||
/// (sRGB 与是否 Sprite),否则 Unity 会按默认值重新解释这张图——烘的时候是 sRGB、
|
||||
/// 进引擎变成线性,是最难查的那种"颜色不对"。</para>
|
||||
/// </summary>
|
||||
internal sealed class ShaderBakeExporter
|
||||
{
|
||||
private const string kPrefLastDir = "XericUI.ShaderBake.LastDir";
|
||||
|
||||
private readonly ShaderBakeRenderer m_Renderer;
|
||||
private readonly Action<string> m_Report;
|
||||
|
||||
public ShaderBakeExporter(ShaderBakeRenderer renderer, Action<string> report)
|
||||
{
|
||||
m_Renderer = renderer;
|
||||
m_Report = report;
|
||||
}
|
||||
|
||||
/// <summary> 把导出项灌进一个 GenericMenu(工具栏那颗按钮点开来的是它) </summary>
|
||||
public void BuildMenu(GenericMenu menu, string suggestedName)
|
||||
{
|
||||
string name = SanitizeName(suggestedName);
|
||||
|
||||
menu.AddItem(new GUIContent("PNG 文件…"), false, () => SaveFile(ShaderBakeImageFormat.Png, name));
|
||||
menu.AddItem(new GUIContent("JPG 文件…"), false, () => SaveFile(ShaderBakeImageFormat.Jpg, name));
|
||||
menu.AddItem(new GUIContent("TGA 文件…"), false, () => SaveFile(ShaderBakeImageFormat.Tga, name));
|
||||
menu.AddItem(new GUIContent("EXR 文件…"), false, () => SaveFile(ShaderBakeImageFormat.Exr, name));
|
||||
|
||||
menu.AddSeparator(string.Empty);
|
||||
menu.AddItem(new GUIContent("Texture2D 资产(.asset)…"), false, () => SaveTextureAsset(name));
|
||||
menu.AddItem(new GUIContent("Sprite 资产(png + 导入设置)…"), false, () => SaveSpriteAsset(name));
|
||||
menu.AddItem(new GUIContent("RenderTexture 资产(.asset)…"), false, () => SaveRenderTextureAsset(name));
|
||||
|
||||
menu.AddSeparator(string.Empty);
|
||||
menu.AddItem(new GUIContent("复制烘焙参数(JSON)"), false, CopySettingsJson);
|
||||
menu.AddItem(new GUIContent("用参数 JSON 替换…"), false, PasteSettingsJson);
|
||||
}
|
||||
|
||||
// ── 文件 ────────────────────────────────────────────────
|
||||
|
||||
public void SaveFile(ShaderBakeImageFormat format, string suggestedName)
|
||||
{
|
||||
Texture2D texture = m_Renderer.RenderToTexture2D(false);
|
||||
if (texture == null)
|
||||
{
|
||||
Fail(m_Renderer.lastError);
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] bytes;
|
||||
try
|
||||
{
|
||||
bytes = format.Encode(texture, m_Renderer.settings.output.clearColor);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ShaderBakeRenderer.ReleaseTempObject(texture, true);
|
||||
}
|
||||
if (bytes == null || bytes.Length == 0)
|
||||
{
|
||||
Fail(format + " 编码失败(这个纹理格式 Unity 的编码器不吃)");
|
||||
return;
|
||||
}
|
||||
|
||||
string path = EditorUtility.SaveFilePanel(
|
||||
"导出 " + format.GetExtension().ToUpperInvariant(), LastDir(), suggestedName, format.GetExtension());
|
||||
if (string.IsNullOrEmpty(path))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path));
|
||||
File.WriteAllBytes(path, bytes);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Fail("写入失败:" + e.Message);
|
||||
return;
|
||||
}
|
||||
|
||||
RememberDir(path);
|
||||
string assetPath = ToAssetPath(path);
|
||||
if (assetPath != null)
|
||||
{
|
||||
ImportAndConfigure(assetPath, false);
|
||||
Report("已导出 " + assetPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
Report("已导出 " + path);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 资产 ────────────────────────────────────────────────
|
||||
|
||||
public void SaveTextureAsset(string suggestedName)
|
||||
{
|
||||
Texture2D texture = m_Renderer.RenderToTexture2D(false);
|
||||
if (texture == null)
|
||||
{
|
||||
Fail(m_Renderer.lastError);
|
||||
return;
|
||||
}
|
||||
string path = EditorUtility.SaveFilePanelInProject("保存 Texture2D 资产", suggestedName, "asset",
|
||||
"这张图会作为可读的 Texture2D 存成 .asset(不走向器,随时可读回像素)");
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
ShaderBakeRenderer.ReleaseTempObject(texture, true);
|
||||
return;
|
||||
}
|
||||
|
||||
texture.name = Path.GetFileNameWithoutExtension(path);
|
||||
// CreateAsset 不吃 DontSave / hideFlags 非空的对象,落盘前必须摘掉
|
||||
texture.hideFlags = HideFlags.None;
|
||||
AssetDatabase.CreateAsset(texture, path);
|
||||
AssetDatabase.SaveAssets();
|
||||
RememberDir(path);
|
||||
Report("已保存 " + path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sprite 走"写 png + 设导入器"这条路,而不是把 Sprite 对象本身存成资产:
|
||||
/// Sprite.Create 出来的是一张纹理上的临时对象,直接 CreateAsset 会被当成非法资产。
|
||||
/// 让 Unity 自己按 Sprite 类型导入,拿到的 Sprite 才是别处也能用的正常资产。
|
||||
/// </summary>
|
||||
public void SaveSpriteAsset(string suggestedName)
|
||||
{
|
||||
string path = EditorUtility.SaveFilePanelInProject("保存 Sprite 资产", suggestedName, "png",
|
||||
"先写成 png,再把导入类型设为 Sprite(Single)");
|
||||
if (string.IsNullOrEmpty(path))
|
||||
return;
|
||||
|
||||
Texture2D texture = m_Renderer.RenderToTexture2D(false);
|
||||
if (texture == null)
|
||||
{
|
||||
Fail(m_Renderer.lastError);
|
||||
return;
|
||||
}
|
||||
byte[] bytes;
|
||||
try
|
||||
{
|
||||
bytes = ShaderBakeImageFormat.Png.Encode(texture, m_Renderer.settings.output.clearColor);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ShaderBakeRenderer.ReleaseTempObject(texture, true);
|
||||
}
|
||||
if (bytes == null)
|
||||
{
|
||||
Fail("PNG 编码失败");
|
||||
return;
|
||||
}
|
||||
|
||||
File.WriteAllBytes(path, bytes);
|
||||
ImportAndConfigure(path, true);
|
||||
RememberDir(path);
|
||||
Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(path);
|
||||
Report(sprite != null ? "已保存 Sprite " + path : "已写入 " + path + "(没拿到 Sprite,检查导入设置)");
|
||||
}
|
||||
|
||||
public void SaveRenderTextureAsset(string suggestedName)
|
||||
{
|
||||
string path = EditorUtility.SaveFilePanelInProject("保存 RenderTexture 资产", suggestedName, "asset",
|
||||
"RT 资产可以反复往里渲,也能被材质直接引用");
|
||||
if (string.IsNullOrEmpty(path))
|
||||
return;
|
||||
|
||||
// 存成资产要能被别处直接采样/读回,单采样即可;采样样式由烘焙设置里的 MSAA 只在预览时体现
|
||||
var rt = m_Renderer.settings.output.CreateRenderTexture(Path.GetFileNameWithoutExtension(path), 1);
|
||||
if (m_Renderer.Render(rt) == null)
|
||||
{
|
||||
Fail(m_Renderer.lastError);
|
||||
ShaderBakeRenderer.ReleaseTempObject(rt, true);
|
||||
return;
|
||||
}
|
||||
rt.hideFlags = HideFlags.None;
|
||||
AssetDatabase.CreateAsset(rt, path);
|
||||
AssetDatabase.SaveAssets();
|
||||
RememberDir(path);
|
||||
Report("已保存 " + path);
|
||||
}
|
||||
|
||||
// ── 参数搬运 ────────────────────────────────────────────
|
||||
|
||||
private void CopySettingsJson()
|
||||
{
|
||||
EditorGUIUtility.systemCopyBuffer = m_Renderer.settings.ToJson();
|
||||
Report("烘焙参数已复制到剪贴板");
|
||||
}
|
||||
|
||||
private void PasteSettingsJson()
|
||||
{
|
||||
string json = EditorGUIUtility.systemCopyBuffer;
|
||||
if (string.IsNullOrEmpty(json) || json.IndexOf("output", StringComparison.Ordinal) < 0)
|
||||
{
|
||||
Fail("剪贴板里不像是烘焙参数 JSON");
|
||||
return;
|
||||
}
|
||||
ShaderBakeSettings parsed = ShaderBakeSettings.FromJson(json);
|
||||
m_Renderer.settings.output = parsed.output;
|
||||
m_Renderer.settings.surface = parsed.surface;
|
||||
m_Renderer.settings.camera = parsed.camera;
|
||||
m_Renderer.settings.globals = parsed.globals;
|
||||
Report("烘焙参数已从剪贴板替换");
|
||||
Action apply = settingsReplaced;
|
||||
if (apply != null)
|
||||
apply.Invoke();
|
||||
}
|
||||
|
||||
/// <summary> 参数被外部整体换掉之后,窗口要把界面数值同步回来 </summary>
|
||||
public event Action settingsReplaced;
|
||||
|
||||
// ── 杂项 ────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 落在 Assets 下面时触发导入并设好类型。<paramref name="asSprite"/> 为真时按 Sprite 导入;
|
||||
/// 否则按普通贴图,并把 sRGB 跟烘焙设置对齐。
|
||||
/// </summary>
|
||||
private void ImportAndConfigure(string assetPath, bool asSprite)
|
||||
{
|
||||
AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
|
||||
var importer = AssetImporter.GetAtPath(assetPath) as TextureImporter;
|
||||
if (importer == null)
|
||||
return;
|
||||
|
||||
importer.textureType = asSprite ? TextureImporterType.Sprite : TextureImporterType.Default;
|
||||
if (asSprite)
|
||||
importer.spriteImportMode = SpriteImportMode.Single;
|
||||
importer.sRGBTexture = m_Renderer.settings.output.sRGB && !m_Renderer.settings.output.hdr;
|
||||
importer.mipmapEnabled = false;
|
||||
// 浮点位深交给导入器按源文件判断(EXR 源自己带格式),这里不去设 per-platform 压缩格式
|
||||
importer.SaveAndReimport();
|
||||
}
|
||||
|
||||
/// <summary> 工程内的绝对路径换成 Assets/... 相对路径;不在工程内返回 null </summary>
|
||||
private static string ToAssetPath(string absolutePath)
|
||||
{
|
||||
string normalized = absolutePath.Replace('\\', '/');
|
||||
string dataPath = Application.dataPath.Replace('\\', '/');
|
||||
if (!normalized.StartsWith(dataPath + "/", StringComparison.OrdinalIgnoreCase))
|
||||
return null;
|
||||
return "Assets" + normalized.Substring(dataPath.Length);
|
||||
}
|
||||
|
||||
/// <summary> 文件名直接拿去当路径用,分隔符和非法字符要先剔掉 </summary>
|
||||
private static string SanitizeName(string suggestedName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(suggestedName))
|
||||
return "BakedImage";
|
||||
foreach (char invalid in Path.GetInvalidFileNameChars())
|
||||
suggestedName = suggestedName.Replace(invalid, '_');
|
||||
return suggestedName.Replace('/', '_').Replace('\\', '_');
|
||||
}
|
||||
|
||||
private static string LastDir()
|
||||
{
|
||||
string dir = EditorPrefs.GetString(kPrefLastDir, string.Empty);
|
||||
return string.IsNullOrEmpty(dir) || !Directory.Exists(dir) ? Application.dataPath : dir;
|
||||
}
|
||||
|
||||
private static void RememberDir(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
string dir = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir))
|
||||
EditorPrefs.SetString(kPrefLastDir, dir);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// 记不住上次的目录不是错误,下次弹默认目录而已
|
||||
}
|
||||
}
|
||||
|
||||
private void Report(string message)
|
||||
{
|
||||
if (m_Report != null) m_Report(message);
|
||||
Debug.Log("[ShaderBake] " + message);
|
||||
}
|
||||
|
||||
private void Fail(string message)
|
||||
{
|
||||
if (m_Report != null) m_Report("导出失败:" + message);
|
||||
Debug.LogError("[ShaderBake] " + message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7469f2bb4d6701e45aeb7355cabff6b4
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,41 @@
|
||||
#if UNITY_2022_1_OR_NEWER
|
||||
using BaseFloatField = UnityEngine.UIElements.FloatField;
|
||||
using BaseIntegerField = UnityEngine.UIElements.IntegerField;
|
||||
using BaseEnumField = UnityEngine.UIElements.EnumField;
|
||||
#else
|
||||
using BaseFloatField = UnityEditor.UIElements.FloatField;
|
||||
using BaseIntegerField = UnityEditor.UIElements.IntegerField;
|
||||
using BaseEnumField = UnityEditor.UIElements.EnumField;
|
||||
#endif
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace XericUI.ShaderBake.Editor
|
||||
{
|
||||
/// <summary>
|
||||
/// 这三个数字/枚举输入框在 2021.3 与 2022.1 分属两个命名空间:
|
||||
/// 2021.3 在 <c>UnityEditor.UIElements</c>,2022.1 挪到了 <c>UnityEngine.UIElements</c>。
|
||||
///
|
||||
/// <para><b>为什么还要包一层</b>:UXML 的标签前缀只能指向一个固定命名空间,写
|
||||
/// <c>ui:FloatField</c> 在 2021.3 里会报 "has no registered factory method",写
|
||||
/// <c>x:FloatField</c> 又在 2022.1 里失效。包一个自己命名空间下的同名子类,
|
||||
/// 两份 UXML 就能共用同一个 <c>xer:FloatField</c> 标签,版本差异只留在 C# 的 using 别名里。</para>
|
||||
///
|
||||
/// <para>子类不做任何事,只负责把基类的 <c>UxmlTraits</c>(label/value 等)和工厂带过来。</para>
|
||||
/// </summary>
|
||||
public class FloatField : BaseFloatField
|
||||
{
|
||||
public new class UxmlFactory : UxmlFactory<FloatField, UxmlTraits> { }
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="FloatField"/>
|
||||
public class IntegerField : BaseIntegerField
|
||||
{
|
||||
public new class UxmlFactory : UxmlFactory<IntegerField, UxmlTraits> { }
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="FloatField"/>
|
||||
public class EnumField : BaseEnumField
|
||||
{
|
||||
public new class UxmlFactory : UxmlFactory<EnumField, UxmlTraits> { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f63a546664b3b5d41a2c6799f875dccb
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using XericUI.ShaderBake;
|
||||
|
||||
namespace XericUI.ShaderBake.Editor
|
||||
{
|
||||
/// <summary>
|
||||
/// 从 shader 源文件里找"不是材质属性、但会被 shader 读到"的全局量。
|
||||
///
|
||||
/// <para><b>为什么只能做到这个程度</b>:Unity 没有"列出 shader 实际引用了哪些 uniform"的 API,
|
||||
/// 编译器把 include 里的东西全展开了。这里做的是文本级扫描——只看 shader 文件里自己声明的
|
||||
/// uniform,够覆盖"手写一个 _GlobalTint 却没做成 property"这类常见情况;引擎内置量
|
||||
/// (光照方向、环境光、反射探针)靠"常用预设"补齐,不假装能自动枚举。</para>
|
||||
/// </summary>
|
||||
internal static class ShaderBakeGlobalScanner
|
||||
{
|
||||
private static readonly Regex kDeclaration = new Regex(
|
||||
@"(?m)^[ \t]*(?:uniform[ \t]+)?(float|float2|float3|float4|half|half2|half3|half4|fixed|fixed2|fixed3|fixed4|int|uint|color|sampler2D|sampler3D|samplerCUBE|sampler2DArray|Texture2D|Texture3D|TextureCube|Texture2DArray)[ \t]+([A-Za-z_][A-Za-z0-9_]*)[ \t]*(?:\[[^\]]*\])?[ \t]*;",
|
||||
RegexOptions.Compiled);
|
||||
|
||||
/// <summary> 扫描并把新发现的全局量加进参数表(默认关闭)。返回新增条数。 </summary>
|
||||
public static int Scan(Shader shader, ShaderBakeGlobalSettings settings, out string note)
|
||||
{
|
||||
if (shader == null)
|
||||
{
|
||||
note = "没有 shader";
|
||||
return 0;
|
||||
}
|
||||
string path = AssetDatabase.GetAssetPath(shader);
|
||||
if (string.IsNullOrEmpty(path) || !File.Exists(path))
|
||||
{
|
||||
note = "这个 shader 没有源文件(内置或运行时创建),只能手动加常用预设";
|
||||
return 0;
|
||||
}
|
||||
|
||||
string source;
|
||||
try
|
||||
{
|
||||
source = File.ReadAllText(path);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
note = "读 shader 源文件失败:" + e.Message;
|
||||
return 0;
|
||||
}
|
||||
|
||||
var properties = new HashSet<string>();
|
||||
for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
|
||||
properties.Add(ShaderUtil.GetPropertyName(shader, i));
|
||||
|
||||
int added = 0;
|
||||
foreach (Match match in kDeclaration.Matches(source))
|
||||
{
|
||||
string name = match.Groups[2].Value;
|
||||
if (properties.Contains(name) || name.StartsWith("unity_", System.StringComparison.Ordinal))
|
||||
continue;
|
||||
if (settings.entries != null && settings.entries.Exists(entry => entry != null && entry.name == name))
|
||||
continue;
|
||||
settings.Ensure(name, KindOf(match.Groups[1].Value));
|
||||
added++;
|
||||
}
|
||||
note = added > 0 ? "扫描到 " + added + " 个全局量(默认关闭)" : "没有扫到新的全局量";
|
||||
return added;
|
||||
}
|
||||
|
||||
private static ShaderBakeGlobalKind KindOf(string type)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case "float":
|
||||
case "half":
|
||||
case "fixed":
|
||||
case "int":
|
||||
case "uint":
|
||||
return ShaderBakeGlobalKind.Float;
|
||||
case "color":
|
||||
return ShaderBakeGlobalKind.Color;
|
||||
case "sampler2D":
|
||||
case "sampler3D":
|
||||
case "samplerCUBE":
|
||||
case "sampler2DArray":
|
||||
case "Texture2D":
|
||||
case "Texture3D":
|
||||
case "TextureCube":
|
||||
case "Texture2DArray":
|
||||
return ShaderBakeGlobalKind.Texture;
|
||||
default:
|
||||
return ShaderBakeGlobalKind.Vector;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: fefa29cac5af5424f9a8602a8159542f
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,250 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEditor.UIElements;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
using XericUI.ShaderBake;
|
||||
|
||||
namespace XericUI.ShaderBake.Editor
|
||||
{
|
||||
/// <summary>
|
||||
/// 右侧的"全局参数表":一行一条 <see cref="ShaderBakeGlobalEntry"/>,勾选才参与烘焙。
|
||||
/// 结构与材质属性表同构——模板在 BakeShaderGlobalRow.uxml,这里只决定点亮哪个控件。
|
||||
/// </summary>
|
||||
internal sealed class ShaderBakeGlobalTable
|
||||
{
|
||||
private sealed class Row
|
||||
{
|
||||
public VisualElement root;
|
||||
public Toggle enabled;
|
||||
public Label label;
|
||||
public FloatField floatValue;
|
||||
public VisualElement vectorGroup;
|
||||
public FloatField[] parts;
|
||||
public ColorField color;
|
||||
public ObjectField texture;
|
||||
public ShaderBakeGlobalEntry entry;
|
||||
public bool updating;
|
||||
}
|
||||
|
||||
private readonly VisualElement m_Container;
|
||||
private readonly VisualTreeAsset m_Template;
|
||||
private readonly List<Row> m_Rows = new List<Row>();
|
||||
|
||||
public event Action changed;
|
||||
|
||||
public int rowCount { get { return m_Rows.Count; } }
|
||||
|
||||
public ShaderBakeGlobalTable(VisualElement root, VisualTreeAsset template)
|
||||
{
|
||||
m_Container = root.Q<VisualElement>("globals-rows");
|
||||
m_Template = template;
|
||||
if (m_Container == null)
|
||||
throw new InvalidOperationException("BakeShaderWindow.uxml 缺少 globals-rows 容器");
|
||||
}
|
||||
|
||||
public void SetTarget(ShaderBakeGlobalSettings settings)
|
||||
{
|
||||
m_Settings = settings;
|
||||
Rebuild();
|
||||
}
|
||||
|
||||
private ShaderBakeGlobalSettings m_Settings;
|
||||
|
||||
public void Rebuild()
|
||||
{
|
||||
m_Rows.Clear();
|
||||
m_Container.Clear();
|
||||
if (m_Settings == null || m_Settings.entries == null || m_Template == null)
|
||||
return;
|
||||
|
||||
foreach (ShaderBakeGlobalEntry entry in m_Settings.entries)
|
||||
{
|
||||
if (entry == null || string.IsNullOrEmpty(entry.name))
|
||||
continue;
|
||||
Row row = CreateRow(entry);
|
||||
m_Rows.Add(row);
|
||||
m_Container.Add(row.root);
|
||||
}
|
||||
RefreshValues();
|
||||
}
|
||||
|
||||
/// <summary> 值被别处改过(粘贴参数、扫描新增)之后回写界面 </summary>
|
||||
public void RefreshValues()
|
||||
{
|
||||
foreach (Row row in m_Rows)
|
||||
{
|
||||
row.updating = true;
|
||||
try
|
||||
{
|
||||
row.enabled.SetValueWithoutNotify(row.entry.enabled);
|
||||
switch (row.entry.kind)
|
||||
{
|
||||
case ShaderBakeGlobalKind.Float:
|
||||
row.floatValue.SetValueWithoutNotify(row.entry.x);
|
||||
break;
|
||||
case ShaderBakeGlobalKind.Vector:
|
||||
row.parts[0].SetValueWithoutNotify(row.entry.x);
|
||||
row.parts[1].SetValueWithoutNotify(row.entry.y);
|
||||
row.parts[2].SetValueWithoutNotify(row.entry.z);
|
||||
row.parts[3].SetValueWithoutNotify(row.entry.w);
|
||||
break;
|
||||
case ShaderBakeGlobalKind.Color:
|
||||
row.color.SetValueWithoutNotify(row.entry.ToColor());
|
||||
break;
|
||||
case ShaderBakeGlobalKind.Texture:
|
||||
row.texture.SetValueWithoutNotify(row.entry.texture);
|
||||
break;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
row.updating = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Row CreateRow(ShaderBakeGlobalEntry entry)
|
||||
{
|
||||
VisualElement host = new VisualElement();
|
||||
m_Template.CloneTree(host);
|
||||
if (host.childCount == 0)
|
||||
return null;
|
||||
VisualElement root = host[0];
|
||||
root.RemoveFromHierarchy();
|
||||
|
||||
var row = new Row
|
||||
{
|
||||
root = root,
|
||||
enabled = root.Q<Toggle>("global-enabled"),
|
||||
label = root.Q<Label>("global-name"),
|
||||
floatValue = root.Q<FloatField>("global-float"),
|
||||
vectorGroup = root.Q<VisualElement>("global-vector"),
|
||||
color = root.Q<ColorField>("global-color"),
|
||||
texture = root.Q<ObjectField>("global-texture"),
|
||||
entry = entry
|
||||
};
|
||||
row.parts = new[]
|
||||
{
|
||||
root.Q<FloatField>("global-x"),
|
||||
root.Q<FloatField>("global-y"),
|
||||
root.Q<FloatField>("global-z"),
|
||||
root.Q<FloatField>("global-w")
|
||||
};
|
||||
|
||||
if (row.label != null)
|
||||
{
|
||||
row.label.text = entry.name;
|
||||
row.label.tooltip = entry.name + "\n" + DescribeKind(entry.kind);
|
||||
}
|
||||
|
||||
Hide(row.floatValue);
|
||||
Hide(row.vectorGroup);
|
||||
Hide(row.color);
|
||||
Hide(row.texture);
|
||||
switch (entry.kind)
|
||||
{
|
||||
case ShaderBakeGlobalKind.Float: Show(row.floatValue); break;
|
||||
case ShaderBakeGlobalKind.Vector: Show(row.vectorGroup); break;
|
||||
case ShaderBakeGlobalKind.Color: Show(row.color); break;
|
||||
case ShaderBakeGlobalKind.Texture: Show(row.texture); break;
|
||||
}
|
||||
|
||||
if (row.enabled != null)
|
||||
{
|
||||
row.enabled.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating) return;
|
||||
entry.enabled = evt.newValue;
|
||||
Notify();
|
||||
});
|
||||
}
|
||||
|
||||
if (row.floatValue != null)
|
||||
{
|
||||
row.floatValue.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating) return;
|
||||
entry.x = evt.newValue;
|
||||
Notify();
|
||||
});
|
||||
}
|
||||
|
||||
if (row.parts != null)
|
||||
{
|
||||
for (int i = 0; i < row.parts.Length; i++)
|
||||
{
|
||||
int component = i;
|
||||
FloatField field = row.parts[i];
|
||||
if (field == null) continue;
|
||||
field.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating) return;
|
||||
switch (component)
|
||||
{
|
||||
case 0: entry.x = evt.newValue; break;
|
||||
case 1: entry.y = evt.newValue; break;
|
||||
case 2: entry.z = evt.newValue; break;
|
||||
default: entry.w = evt.newValue; break;
|
||||
}
|
||||
Notify();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (row.color != null)
|
||||
{
|
||||
row.color.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating) return;
|
||||
entry.x = evt.newValue.r;
|
||||
entry.y = evt.newValue.g;
|
||||
entry.z = evt.newValue.b;
|
||||
entry.w = evt.newValue.a;
|
||||
Notify();
|
||||
});
|
||||
}
|
||||
|
||||
if (row.texture != null)
|
||||
{
|
||||
row.texture.objectType = typeof(Texture);
|
||||
row.texture.allowSceneObjects = false;
|
||||
row.texture.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating) return;
|
||||
entry.texture = evt.newValue as Texture;
|
||||
Notify();
|
||||
});
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
private static string DescribeKind(ShaderBakeGlobalKind kind)
|
||||
{
|
||||
switch (kind)
|
||||
{
|
||||
case ShaderBakeGlobalKind.Float: return "float";
|
||||
case ShaderBakeGlobalKind.Vector: return "float4";
|
||||
case ShaderBakeGlobalKind.Color: return "color";
|
||||
default: return "texture";
|
||||
}
|
||||
}
|
||||
|
||||
private void Notify()
|
||||
{
|
||||
Action handler = changed;
|
||||
if (handler != null)
|
||||
handler.Invoke();
|
||||
}
|
||||
|
||||
private static void Show(VisualElement element)
|
||||
{
|
||||
if (element != null) element.style.display = DisplayStyle.Flex;
|
||||
}
|
||||
|
||||
private static void Hide(VisualElement element)
|
||||
{
|
||||
if (element != null) element.style.display = DisplayStyle.None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e01a45cc073e2a54584fd03979143297
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,185 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake.Editor
|
||||
{
|
||||
/// <summary>
|
||||
/// 网格来源:从场景选中物体取网格,或把外部模型文件拉进工程再取网格。
|
||||
///
|
||||
/// <para><b>这里只搬网格,不搬层级</b>:烘焙是"一张网格 + 一个材质"离屏渲一次,
|
||||
/// 多层物体(带骨骼、带多个材质球)在这里会被拆成"挑一个网格"。
|
||||
/// 想要整棵树的效果请先把它们合到一个网格上,或者用 <c>SubMesh</c> 那一格逐层渲。</para>
|
||||
/// </summary>
|
||||
internal static class ShaderBakeModelSource
|
||||
{
|
||||
/// <summary> 外部模型文件的落点:不在工程里的文件必须先有个能导入的位置 </summary>
|
||||
private const string kImportFolder = "Assets/XericShaderBakeImports";
|
||||
|
||||
/// <summary> 选中物体(含未激活的子物体)里三角数最多的网格 </summary>
|
||||
public static Mesh PickFromSelection(out string note)
|
||||
{
|
||||
note = string.Empty;
|
||||
GameObject selected = Selection.activeGameObject;
|
||||
if (selected == null)
|
||||
{
|
||||
note = "场景里没选中物体";
|
||||
return null;
|
||||
}
|
||||
|
||||
Mesh best = null;
|
||||
int bestCount = 0;
|
||||
foreach (MeshFilter filter in selected.GetComponentsInChildren<MeshFilter>(true))
|
||||
{
|
||||
int count = CountTriangles(filter.sharedMesh);
|
||||
if (count > bestCount)
|
||||
{
|
||||
best = filter.sharedMesh;
|
||||
bestCount = count;
|
||||
}
|
||||
}
|
||||
foreach (SkinnedMeshRenderer skinned in selected.GetComponentsInChildren<SkinnedMeshRenderer>(true))
|
||||
{
|
||||
int count = CountTriangles(skinned.sharedMesh);
|
||||
if (count > bestCount)
|
||||
{
|
||||
best = skinned.sharedMesh;
|
||||
bestCount = count;
|
||||
}
|
||||
}
|
||||
|
||||
if (best == null)
|
||||
note = selected.name + " 及其子物体里没有网格";
|
||||
else
|
||||
note = "取自 " + selected.name + ":" + best.name + "(" + bestCount + " 三角)";
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 选一个模型文件导入并取网格。已经在工程里的文件不复制,只走一次导入。
|
||||
/// </summary>
|
||||
public static Mesh ImportFromFile(out string note)
|
||||
{
|
||||
note = string.Empty;
|
||||
string path = EditorUtility.OpenFilePanelWithFilters(
|
||||
"导入模型",
|
||||
Directory.Exists(kImportFolder) ? kImportFolder : Application.dataPath,
|
||||
new[] { "模型文件", "fbx,obj,dae,blend,3ds,ply,stl,glb,gltf", "所有文件", string.Empty });
|
||||
if (string.IsNullOrEmpty(path))
|
||||
{
|
||||
note = "已取消";
|
||||
return null;
|
||||
}
|
||||
|
||||
string assetPath = ToProjectPath(path);
|
||||
if (assetPath == null)
|
||||
{
|
||||
assetPath = CopyIntoProject(path);
|
||||
if (assetPath == null)
|
||||
{
|
||||
note = "复制到工程失败";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
|
||||
Mesh best = BiggestMeshAt(assetPath, out int triangleCount);
|
||||
if (best == null)
|
||||
note = assetPath + " 里没有可用的网格";
|
||||
else
|
||||
note = "已导入 " + assetPath + ":" + best.name + "(" + triangleCount + " 三角)";
|
||||
return best;
|
||||
}
|
||||
|
||||
private static int CountTriangles(Mesh mesh)
|
||||
{
|
||||
if (mesh == null)
|
||||
return 0;
|
||||
int total = 0;
|
||||
for (int i = 0; i < mesh.subMeshCount; i++)
|
||||
total += (int)mesh.GetIndexCount(i);
|
||||
return total / 3;
|
||||
}
|
||||
|
||||
/// <summary> 工程内的绝对路径换成 Assets/... 相对路径,不在工程内返回 null </summary>
|
||||
private static string ToProjectPath(string absolutePath)
|
||||
{
|
||||
string normalized = absolutePath.Replace('\\', '/');
|
||||
string dataPath = Application.dataPath.Replace('\\', '/');
|
||||
if (!normalized.StartsWith(dataPath + "/", StringComparison.OrdinalIgnoreCase))
|
||||
return null;
|
||||
return "Assets" + normalized.Substring(dataPath.Length);
|
||||
}
|
||||
|
||||
private static string CopyIntoProject(string absolutePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(kImportFolder))
|
||||
Directory.CreateDirectory(kImportFolder);
|
||||
string target = kImportFolder + "/" + Path.GetFileName(absolutePath);
|
||||
File.Copy(absolutePath, target, true);
|
||||
AssetDatabase.Refresh();
|
||||
return target;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogError("[ShaderBake] 复制模型失败:" + e.Message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模型里往往混着 LOD、碰撞体和皮肤网格,挑三角最多的那个通常就是用户想看的主体。
|
||||
/// </summary>
|
||||
private static Mesh BiggestMeshAt(string assetPath, out int triangleCount)
|
||||
{
|
||||
triangleCount = 0;
|
||||
Mesh best = null;
|
||||
var seen = new HashSet<Mesh>();
|
||||
|
||||
foreach (UnityEngine.Object obj in AssetDatabase.LoadAllAssetsAtPath(assetPath))
|
||||
{
|
||||
IEnumerable<Mesh> candidates = null;
|
||||
var filter = obj as MeshFilter;
|
||||
var skinned = obj as SkinnedMeshRenderer;
|
||||
var prefab = obj as GameObject;
|
||||
if (filter != null && filter.sharedMesh != null)
|
||||
candidates = new[] { filter.sharedMesh };
|
||||
else if (skinned != null && skinned.sharedMesh != null)
|
||||
candidates = new[] { skinned.sharedMesh };
|
||||
else if (prefab != null)
|
||||
candidates = CollectFromPrefab(prefab);
|
||||
|
||||
if (candidates == null)
|
||||
continue;
|
||||
foreach (Mesh mesh in candidates)
|
||||
{
|
||||
if (mesh == null || !seen.Add(mesh))
|
||||
continue;
|
||||
int count = CountTriangles(mesh);
|
||||
if (count > triangleCount)
|
||||
{
|
||||
best = mesh;
|
||||
triangleCount = count;
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static IEnumerable<Mesh> CollectFromPrefab(GameObject prefab)
|
||||
{
|
||||
var list = new List<Mesh>();
|
||||
foreach (MeshFilter filter in prefab.GetComponentsInChildren<MeshFilter>(true))
|
||||
if (filter.sharedMesh != null) list.Add(filter.sharedMesh);
|
||||
foreach (SkinnedMeshRenderer skinned in prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true))
|
||||
if (skinned.sharedMesh != null) list.Add(skinned.sharedMesh);
|
||||
Mesh mesh = prefab.GetComponent<Mesh>();
|
||||
if (mesh != null) list.Add(mesh);
|
||||
return list;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3f91410ca9c991149bea7ac159a5feb6
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,337 @@
|
||||
using System;
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace XericUI.ShaderBake.Editor
|
||||
{
|
||||
/// <summary>
|
||||
/// 左侧浏览图:把渲染结果按缩放摆进滚动区,负责缩放、拖拽平移与透明底棋盘。
|
||||
///
|
||||
/// <para><b>为什么要把 stage 的最小尺寸钉成视口尺寸</b>:ScrollView 在 mode=Both 下不会把内容撑到
|
||||
/// 视口大小,于是图小于视口时"居中"这条样式不成立,图会缩在左上角。这里显式把 min 尺寸设成视口尺寸,
|
||||
/// 让居中和"图大了才出滚动条"两件事同时成立。</para>
|
||||
/// </summary>
|
||||
internal sealed class ShaderBakePreviewPane
|
||||
{
|
||||
private readonly ScrollView m_Viewport;
|
||||
private readonly VisualElement m_Stage;
|
||||
private readonly VisualElement m_Frame;
|
||||
private readonly Image m_Checker;
|
||||
private readonly Image m_Image;
|
||||
private readonly Label m_Readout;
|
||||
private readonly VisualElement m_FaceOverlay;
|
||||
private readonly Label m_FaceOverlayLabel;
|
||||
|
||||
/// <summary> 在图上点了一下(不是拖拽)。参数是 0~1、左上为原点的坐标 </summary>
|
||||
public event Action<Vector2> faceClicked;
|
||||
|
||||
private Texture2D m_CheckerTexture;
|
||||
private int m_CheckerWidth;
|
||||
private int m_CheckerHeight;
|
||||
private bool m_CheckerVisible;
|
||||
private Vector2Int m_PixelSize = Vector2Int.zero;
|
||||
private float m_Zoom = 1f;
|
||||
private bool m_AutoFit = true;
|
||||
private bool m_Dragging;
|
||||
private bool m_PointerMoved;
|
||||
private Vector2 m_DragStart;
|
||||
private Vector2 m_ScrollStart;
|
||||
|
||||
/// <summary> 上一次渲染的不透明像素占比,-1 = 还没测过 </summary>
|
||||
private float m_CoverageRatio = -1f;
|
||||
private Color m_CoverageColor = Color.clear;
|
||||
|
||||
/// <summary> 当前缩放倍率(1 = 一个像素对应屏幕一个点) </summary>
|
||||
public float zoom { get { return m_Zoom; } }
|
||||
|
||||
/// <summary> 用户手动改过缩放后就不再自动适配,免得每次渲染都把他的视图抢回去 </summary>
|
||||
public bool autoFit { get { return m_AutoFit; } set { m_AutoFit = value; } }
|
||||
|
||||
public ShaderBakePreviewPane(VisualElement root)
|
||||
{
|
||||
m_Viewport = root.Q<ScrollView>("preview-viewport");
|
||||
m_Stage = root.Q<VisualElement>("preview-stage");
|
||||
m_Frame = root.Q<VisualElement>("preview-frame");
|
||||
m_Checker = root.Q<Image>("preview-checker");
|
||||
m_Image = root.Q<Image>("preview-image");
|
||||
m_Readout = root.Q<Label>("preview-readout");
|
||||
m_FaceOverlay = root.Q<VisualElement>("face-overlay");
|
||||
m_FaceOverlayLabel = root.Q<Label>("face-overlay-label");
|
||||
if (m_FaceOverlay != null)
|
||||
m_FaceOverlay.pickingMode = PickingMode.Ignore;
|
||||
|
||||
if (m_Viewport == null || m_Frame == null || m_Image == null)
|
||||
throw new InvalidOperationException("BakeShaderWindow.uxml 缺少预览区节点");
|
||||
|
||||
m_Viewport.RegisterCallback<GeometryChangedEvent>(OnViewportGeometry);
|
||||
m_Viewport.RegisterCallback<WheelEvent>(OnWheel);
|
||||
m_Viewport.RegisterCallback<PointerDownEvent>(OnPointerDown);
|
||||
m_Viewport.RegisterCallback<PointerMoveEvent>(OnPointerMove);
|
||||
m_Viewport.RegisterCallback<PointerUpEvent>(OnPointerUp);
|
||||
}
|
||||
|
||||
/// <summary> 挂上这次渲染的结果。传 null 表示"没有结果",只清读数。 </summary>
|
||||
public void SetResult(Texture content, Vector2Int pixelSize)
|
||||
{
|
||||
m_PixelSize = pixelSize;
|
||||
m_Image.style.backgroundImage = ToBackground(content);
|
||||
if (m_AutoFit)
|
||||
FitToView();
|
||||
ApplySize();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RenderTexture 与 Texture2D 走的是 Background 的两个不同入口——UI Toolkit 里 RT 不是
|
||||
/// "一张普通纹理",它要自己那条采样路径;传空则回到"没有背景"。
|
||||
/// </summary>
|
||||
private static StyleBackground ToBackground(Texture content)
|
||||
{
|
||||
if (content == null)
|
||||
return new StyleBackground(StyleKeyword.None);
|
||||
var rt = content as RenderTexture;
|
||||
if (rt != null)
|
||||
return new StyleBackground(Background.FromRenderTexture(rt));
|
||||
return new StyleBackground(Background.FromTexture2D(content as Texture2D));
|
||||
}
|
||||
|
||||
/// <summary> 透明底棋盘:只在需要看 alpha 时生成那张纹理 </summary>
|
||||
public void SetCheckerVisible(bool visible)
|
||||
{
|
||||
m_CheckerVisible = visible;
|
||||
if (m_Checker == null)
|
||||
return;
|
||||
m_Checker.style.display = visible ? DisplayStyle.Flex : DisplayStyle.None;
|
||||
if (visible)
|
||||
ApplySize();
|
||||
}
|
||||
|
||||
public void ZoomIn() { SetZoom(m_Zoom * 1.25f); }
|
||||
public void ZoomOut() { SetZoom(m_Zoom / 1.25f); }
|
||||
public void ActualSize() { m_AutoFit = false; SetZoom(1f); }
|
||||
public void FitToView()
|
||||
{
|
||||
m_AutoFit = true;
|
||||
Rect rect = m_Viewport.contentRect;
|
||||
if (m_PixelSize.x <= 0 || m_PixelSize.y <= 0 || rect.width < 8f || rect.height < 8f)
|
||||
return;
|
||||
// 留 24px 边距,否则图正好贴边看上去像被裁了一半
|
||||
float fit = Mathf.Min((rect.width - 24f) / m_PixelSize.x, (rect.height - 24f) / m_PixelSize.y);
|
||||
SetZoom(fit);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把选中面片的框贴到图上。范围是 0~1(左上为原点),用百分比定位,缩放/滚动都不用重算。
|
||||
/// </summary>
|
||||
public void SetFaceSelection(bool visible, Vector2 min, Vector2 max, string label)
|
||||
{
|
||||
if (m_FaceOverlay == null)
|
||||
return;
|
||||
if (!visible)
|
||||
{
|
||||
m_FaceOverlay.style.display = DisplayStyle.None;
|
||||
return;
|
||||
}
|
||||
m_FaceOverlay.style.display = DisplayStyle.Flex;
|
||||
m_FaceOverlay.style.left = Length.Percent(Mathf.Clamp01(min.x) * 100f);
|
||||
m_FaceOverlay.style.top = Length.Percent(Mathf.Clamp01(min.y) * 100f);
|
||||
m_FaceOverlay.style.width = Length.Percent(Mathf.Max(max.x - min.x, 0.002f) * 100f);
|
||||
m_FaceOverlay.style.height = Length.Percent(Mathf.Max(max.y - min.y, 0.002f) * 100f);
|
||||
if (m_FaceOverlayLabel != null)
|
||||
m_FaceOverlayLabel.text = label;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 报告这次结果里有多少像素不是全透明。看图时最先要确认的就是"到底画没画出来",
|
||||
/// 而棋盘格背景会让"没画"和"画了个透明的"看起来完全一样。
|
||||
/// </summary>
|
||||
public void SetCoverage(float opaqueRatio, Color averageColor)
|
||||
{
|
||||
m_CoverageRatio = opaqueRatio;
|
||||
m_CoverageColor = averageColor;
|
||||
UpdateReadout();
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
m_PixelSize = Vector2Int.zero;
|
||||
m_CoverageRatio = -1f;
|
||||
m_Image.style.backgroundImage = new StyleBackground(StyleKeyword.None);
|
||||
UpdateReadout();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (m_CheckerTexture != null)
|
||||
{
|
||||
UnityEngine.Object.DestroyImmediate(m_CheckerTexture);
|
||||
m_CheckerTexture = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetZoom(float value)
|
||||
{
|
||||
m_Zoom = Mathf.Clamp(value, 0.02f, 32f);
|
||||
ApplySize();
|
||||
}
|
||||
|
||||
private void ApplySize()
|
||||
{
|
||||
if (m_PixelSize.x <= 0 || m_PixelSize.y <= 0)
|
||||
{
|
||||
m_Frame.style.width = 0f;
|
||||
m_Frame.style.height = 0f;
|
||||
UpdateReadout();
|
||||
return;
|
||||
}
|
||||
int width = Mathf.Max(1, Mathf.RoundToInt(m_PixelSize.x * m_Zoom));
|
||||
int height = Mathf.Max(1, Mathf.RoundToInt(m_PixelSize.y * m_Zoom));
|
||||
m_Frame.style.width = width;
|
||||
m_Frame.style.height = height;
|
||||
if (m_CheckerVisible)
|
||||
EnsureChecker(width, height);
|
||||
UpdateReadout();
|
||||
}
|
||||
|
||||
private void UpdateReadout()
|
||||
{
|
||||
if (m_Readout == null)
|
||||
return;
|
||||
if (m_PixelSize.x <= 0)
|
||||
{
|
||||
m_Readout.text = "无结果";
|
||||
return;
|
||||
}
|
||||
m_Readout.text = m_PixelSize.x + " × " + m_PixelSize.y + " px " +
|
||||
(m_Zoom * 100f).ToString("0.#") + "%" + CoverageText();
|
||||
// 全透明是"这次什么都没画出来"的信号,值得比别的读数更抢眼一点
|
||||
m_Readout.style.color = new StyleColor(m_PixelSize.x > 0 && m_CoverageRatio <= 0.001f
|
||||
? new Color(0.98f, 0.51f, 0.41f)
|
||||
: new Color(0.86f, 0.86f, 0.86f));
|
||||
}
|
||||
|
||||
/// <summary> 覆盖率后缀;没测过就不占字数 </summary>
|
||||
private string CoverageText()
|
||||
{
|
||||
if (m_CoverageRatio < 0f)
|
||||
return string.Empty;
|
||||
if (m_CoverageRatio <= 0.001f)
|
||||
return " 全透明(没画出像素)";
|
||||
return " 不透明 " + Mathf.RoundToInt(m_CoverageRatio * 100f) + "%";
|
||||
}
|
||||
|
||||
private void OnViewportGeometry(GeometryChangedEvent evt)
|
||||
{
|
||||
// 视口变高变宽都要重钉,否则居中的参照物是上一次的大小
|
||||
if (m_Stage != null)
|
||||
{
|
||||
m_Stage.style.minWidth = Mathf.Max(evt.newRect.width, 1f);
|
||||
m_Stage.style.minHeight = Mathf.Max(evt.newRect.height, 1f);
|
||||
}
|
||||
if (m_AutoFit)
|
||||
FitToView();
|
||||
else
|
||||
ApplySize();
|
||||
}
|
||||
|
||||
private void OnWheel(WheelEvent evt)
|
||||
{
|
||||
if (m_PixelSize.x <= 0)
|
||||
return;
|
||||
// 滚轮在这块画布上的语义是缩放;平移交给拖拽,滚动条留给键盘和拖拽后的自动定位
|
||||
m_AutoFit = false;
|
||||
SetZoom(m_Zoom * (evt.delta.y > 0f ? 1.1f : 1f / 1.1f));
|
||||
evt.StopPropagation();
|
||||
}
|
||||
|
||||
private void OnPointerDown(PointerDownEvent evt)
|
||||
{
|
||||
if (m_PixelSize.x <= 0)
|
||||
return;
|
||||
m_Dragging = true;
|
||||
m_PointerMoved = false;
|
||||
m_DragStart = evt.position;
|
||||
m_ScrollStart = m_Viewport.scrollOffset;
|
||||
m_Viewport.CapturePointer(evt.pointerId);
|
||||
}
|
||||
|
||||
private void OnPointerMove(PointerMoveEvent evt)
|
||||
{
|
||||
// 指针已经被 capture,move 一定送到这里,不需要再判断是否还在视口内
|
||||
if (!m_Dragging)
|
||||
return;
|
||||
// 2022.1 的 position 是 Vector3,直接和 Vector2 相减会二义
|
||||
Vector2 delta = (Vector2)evt.position - m_DragStart;
|
||||
if (delta.sqrMagnitude > 16f)
|
||||
m_PointerMoved = true;
|
||||
m_Viewport.scrollOffset = m_ScrollStart - delta;
|
||||
}
|
||||
|
||||
private void OnPointerUp(PointerUpEvent evt)
|
||||
{
|
||||
m_Dragging = false;
|
||||
m_Viewport.ReleasePointer(evt.pointerId);
|
||||
if (m_PointerMoved || m_PixelSize.x <= 0 || faceClicked == null)
|
||||
return;
|
||||
|
||||
// 没拖动才算点选:拖动是平移视图,抬手时不该顺手换掉选中的面
|
||||
Rect bounds = m_Frame.worldBound;
|
||||
var position = new Vector2(evt.position.x, evt.position.y);
|
||||
if (bounds.width < 1f || bounds.height < 1f || !bounds.Contains(position))
|
||||
return;
|
||||
// 统一用"左上为原点"的 0~1 坐标,和 Renderer.TryPickFace 的约定一致
|
||||
faceClicked.Invoke(new Vector2(
|
||||
(position.x - bounds.x) / bounds.width,
|
||||
(position.y - bounds.y) / bounds.height));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成 8px 格子的棋盘纹理。
|
||||
///
|
||||
/// <para>2022.1 的 <c>ScaleMode</c> 还没有 <c>Tile</c>,靠铺贴做不到,所以干脆按面片当前的
|
||||
/// 显示尺寸生成一张等大纹理,元素直接拉伸也正好一格对一格。尺寸量化到 16 的整数倍:
|
||||
/// 连续缩放时大多数帧能命中缓存,且格子边界始终对齐。</para>
|
||||
/// </summary>
|
||||
private void EnsureChecker(int width, int height)
|
||||
{
|
||||
const int cell = 8;
|
||||
const int quantum = cell * 2;
|
||||
const int maxSide = 1024;
|
||||
|
||||
int w = Mathf.Clamp(Mathf.Max(width, quantum) / quantum * quantum, quantum, maxSide);
|
||||
int h = Mathf.Clamp(Mathf.Max(height, quantum) / quantum * quantum, quantum, maxSide);
|
||||
if (m_CheckerTexture != null && m_CheckerWidth == w && m_CheckerHeight == h)
|
||||
return;
|
||||
|
||||
UnityEngine.Object previous = m_CheckerTexture;
|
||||
var tex = new Texture2D(w, h, TextureFormat.RGBA32, false)
|
||||
{
|
||||
name = "ShaderBakeChecker",
|
||||
hideFlags = HideFlags.DontSave,
|
||||
filterMode = FilterMode.Point,
|
||||
wrapMode = TextureWrapMode.Clamp
|
||||
};
|
||||
|
||||
var light = new Color32(107, 107, 107, 255);
|
||||
var dark = new Color32(84, 84, 84, 255);
|
||||
var pixels = new Color32[w * h];
|
||||
for (int y = 0; y < h; y++)
|
||||
{
|
||||
int rowParity = (y / cell) & 1;
|
||||
int offset = y * w;
|
||||
for (int x = 0; x < w; x++)
|
||||
pixels[offset + x] = (((x / cell) & 1) == rowParity) ? light : dark;
|
||||
}
|
||||
tex.SetPixels32(pixels);
|
||||
tex.Apply();
|
||||
|
||||
m_CheckerTexture = tex;
|
||||
m_CheckerWidth = w;
|
||||
m_CheckerHeight = h;
|
||||
m_Checker.style.backgroundImage = new StyleBackground(tex);
|
||||
|
||||
if (previous != null)
|
||||
UnityEngine.Object.DestroyImmediate(previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0f3d8bd51b672da4ca67c58198d33d2b
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,607 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
using UnityEditor;
|
||||
using UnityEditor.UIElements;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace XericUI.ShaderBake.Editor
|
||||
{
|
||||
/// <summary>
|
||||
/// 右侧的"材质字段属性表":把 shader 声明的属性铺成一行行可编辑控件,改动直接写进那张
|
||||
/// (临时)材质并通知外部重画。
|
||||
///
|
||||
/// <para><b>行从模板克隆,不在代码里造控件</b>:结构在 BakeShaderPropertyRow.uxml,
|
||||
/// 这里只决定"这一行点亮哪个控件、其余收起来"。</para>
|
||||
///
|
||||
/// <para><b>2022.1 没有 GetPropertyDisplayName</b>,所以标签只能由属性名推(下划线去掉、
|
||||
/// 驼峰拆词),description 拿来当 tooltip 并用于识别 <c>[Toggle]</c> 与 <c>[Enum]</c> 两类属性。
|
||||
/// 这两个识别都是"猜形状",猜不中就退回普通数字框——功能不丢,只是少了个勾。</para>
|
||||
/// </summary>
|
||||
internal sealed class ShaderBakePropertyTable
|
||||
{
|
||||
/// <summary> 一行的所有控件;按类型只挂出一个 </summary>
|
||||
private sealed class Row
|
||||
{
|
||||
public VisualElement root;
|
||||
public Label label;
|
||||
public FloatField floatValue;
|
||||
public IntegerField intValue;
|
||||
public Toggle toggle;
|
||||
public DropdownField enumField;
|
||||
public ColorField colorField;
|
||||
public ObjectField textureField;
|
||||
public VisualElement rangeGroup;
|
||||
public Slider slider;
|
||||
public FloatField rangeValue;
|
||||
public VisualElement vectorGroup;
|
||||
public FloatField[] vectorParts;
|
||||
|
||||
public int propIndex;
|
||||
public string propName;
|
||||
public ShaderPropertyType propType;
|
||||
public string keyword;
|
||||
public float rangeMin;
|
||||
public float rangeMax;
|
||||
|
||||
/// <summary> 程序性赋值(RefreshValues)期间压掉回调,免得一次刷新触发一串重画 </summary>
|
||||
public bool updating;
|
||||
}
|
||||
|
||||
private readonly VisualElement m_Container;
|
||||
private readonly VisualTreeAsset m_Template;
|
||||
private readonly List<Row> m_Rows = new List<Row>();
|
||||
|
||||
private Shader m_Shader;
|
||||
private Material m_Material;
|
||||
|
||||
/// <summary> 任一属性被改动(外部据此重画) </summary>
|
||||
public event Action changed;
|
||||
|
||||
/// <summary> 行数(状态栏用来写"共 N 项属性") </summary>
|
||||
public int rowCount { get { return m_Rows.Count; } }
|
||||
|
||||
public ShaderBakePropertyTable(VisualElement root, VisualTreeAsset rowTemplate)
|
||||
{
|
||||
m_Container = root.Q<VisualElement>("props-rows");
|
||||
m_Template = rowTemplate;
|
||||
if (m_Container == null)
|
||||
throw new InvalidOperationException("BakeShaderWindow.uxml 缺少 props-rows 容器");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 换目标。shader 变了重建行,只有材质变了就重新取值——重建一次要克隆几十行,
|
||||
/// 不该在每次点导出的时候发生。
|
||||
/// </summary>
|
||||
public void SetTarget(Shader shader, Material material)
|
||||
{
|
||||
m_Material = material;
|
||||
if (shader != m_Shader)
|
||||
{
|
||||
m_Shader = shader;
|
||||
Rebuild();
|
||||
}
|
||||
else
|
||||
{
|
||||
RefreshValues();
|
||||
}
|
||||
}
|
||||
|
||||
public void Rebuild()
|
||||
{
|
||||
m_Rows.Clear();
|
||||
m_Container.Clear();
|
||||
if (m_Shader == null || m_Template == null)
|
||||
return;
|
||||
|
||||
int count = ShaderUtil.GetPropertyCount(m_Shader);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if (ShaderUtil.IsShaderPropertyHidden(m_Shader, i))
|
||||
continue;
|
||||
Row row = CreateRow(i);
|
||||
if (row != null)
|
||||
{
|
||||
m_Rows.Add(row);
|
||||
m_Container.Add(row.root);
|
||||
}
|
||||
}
|
||||
RefreshValues();
|
||||
}
|
||||
|
||||
/// <summary> 把材质当前的值读回界面(写回/丢弃改动、或外部改了材质之后用) </summary>
|
||||
public void RefreshValues()
|
||||
{
|
||||
foreach (Row row in m_Rows)
|
||||
{
|
||||
if (m_Material == null || !m_Material.HasProperty(row.propName))
|
||||
{
|
||||
row.root.style.display = DisplayStyle.None;
|
||||
continue;
|
||||
}
|
||||
row.root.style.display = DisplayStyle.Flex;
|
||||
row.updating = true;
|
||||
try
|
||||
{
|
||||
FillFromMaterial(row);
|
||||
}
|
||||
finally
|
||||
{
|
||||
row.updating = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
m_Rows.Clear();
|
||||
m_Container.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 修一处脚本造材质的老坑:贴图属性的 Tiling 为 0 时,shader 里的 <c>uv * _MainTex_ST</c>
|
||||
/// 会把四个顶点全乘成同一个点——整片只剩一个颜色,看上去就像"UV 没设置"。
|
||||
/// 只动这张临时副本,顺手把"没指定贴图"的数量数出来给界面当提示。
|
||||
/// </summary>
|
||||
public static string RepairTextureScale(Shader shader, Material material)
|
||||
{
|
||||
if (shader == null || material == null)
|
||||
return string.Empty;
|
||||
|
||||
int normalized = 0;
|
||||
int missing = 0;
|
||||
int count = ShaderUtil.GetPropertyCount(shader);
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
if ((ShaderPropertyType)(int)ShaderUtil.GetPropertyType(shader, i) != ShaderPropertyType.Texture)
|
||||
continue;
|
||||
string name = ShaderUtil.GetPropertyName(shader, i);
|
||||
if (material.GetTexture(name) == null)
|
||||
missing++;
|
||||
string scaleOffset = name + "_ST";
|
||||
if (!material.HasProperty(scaleOffset))
|
||||
continue;
|
||||
Vector4 st = material.GetVector(scaleOffset);
|
||||
if (st.x != 0f && st.y != 0f)
|
||||
continue;
|
||||
material.SetVector(scaleOffset, new Vector4(
|
||||
st.x == 0f ? 1f : st.x, st.y == 0f ? 1f : st.y, st.z, st.w));
|
||||
normalized++;
|
||||
}
|
||||
|
||||
var note = new System.Text.StringBuilder();
|
||||
if (normalized > 0)
|
||||
note.Append(normalized + " 项贴图 Tiling 为 0,已归一为 1");
|
||||
if (missing > 0)
|
||||
{
|
||||
if (note.Length > 0)
|
||||
note.Append(" · ");
|
||||
note.Append(missing + " 项贴图未指定(采样为空,渲出来会是透明)");
|
||||
}
|
||||
return note.ToString();
|
||||
}
|
||||
|
||||
// ── 建行 ────────────────────────────────────────────────
|
||||
|
||||
private Row CreateRow(int propIndex)
|
||||
{
|
||||
VisualElement host = new VisualElement();
|
||||
m_Template.CloneTree(host);
|
||||
if (host.childCount == 0)
|
||||
return null;
|
||||
VisualElement root = host[0];
|
||||
root.RemoveFromHierarchy();
|
||||
|
||||
Shader shader = m_Shader;
|
||||
string name = ShaderUtil.GetPropertyName(shader, propIndex);
|
||||
// 两个同名枚举分属编辑器与运行时命名空间,但取值顺序一致(Color..Int..Constants)
|
||||
var type = (ShaderPropertyType)(int)ShaderUtil.GetPropertyType(shader, propIndex);
|
||||
string description = ShaderUtil.GetPropertyDescription(shader, propIndex);
|
||||
|
||||
var row = new Row
|
||||
{
|
||||
root = root,
|
||||
label = root.Q<Label>("prop-label"),
|
||||
floatValue = root.Q<FloatField>("prop-float"),
|
||||
intValue = root.Q<IntegerField>("prop-int"),
|
||||
toggle = root.Q<Toggle>("prop-toggle"),
|
||||
enumField = root.Q<DropdownField>("prop-enum"),
|
||||
colorField = root.Q<ColorField>("prop-color"),
|
||||
textureField = root.Q<ObjectField>("prop-texture"),
|
||||
rangeGroup = root.Q<VisualElement>("prop-range"),
|
||||
slider = root.Q<Slider>("prop-slider"),
|
||||
rangeValue = root.Q<FloatField>("prop-range-value"),
|
||||
vectorGroup = root.Q<VisualElement>("prop-vector"),
|
||||
propIndex = propIndex,
|
||||
propName = name,
|
||||
propType = type,
|
||||
keyword = ReadKeyword(type, description)
|
||||
};
|
||||
row.vectorParts = new[]
|
||||
{
|
||||
root.Q<FloatField>("prop-vec-x"),
|
||||
root.Q<FloatField>("prop-vec-y"),
|
||||
root.Q<FloatField>("prop-vec-z"),
|
||||
root.Q<FloatField>("prop-vec-w")
|
||||
};
|
||||
|
||||
string displayName = ReadDisplayName(shader, propIndex, name);
|
||||
if (row.label != null)
|
||||
{
|
||||
row.label.text = displayName;
|
||||
row.label.tooltip = name + (string.IsNullOrEmpty(description) ? string.Empty : "\n" + description);
|
||||
}
|
||||
root.tooltip = row.label != null ? row.label.tooltip : name;
|
||||
|
||||
// 先把所有候选控件收起来,下面按类型只放一个出来
|
||||
HideAll(row);
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case ShaderPropertyType.Range:
|
||||
row.rangeMin = ShaderUtil.GetRangeLimits(shader, propIndex, 0);
|
||||
row.rangeMax = ShaderUtil.GetRangeLimits(shader, propIndex, 1);
|
||||
Show(row.rangeGroup);
|
||||
WireSlider(row);
|
||||
WireRangeValue(row);
|
||||
break;
|
||||
|
||||
case ShaderPropertyType.Float:
|
||||
if (row.keyword != null)
|
||||
{
|
||||
Show(row.toggle);
|
||||
WireToggle(row);
|
||||
}
|
||||
else
|
||||
{
|
||||
Show(row.floatValue);
|
||||
WireFloat(row);
|
||||
}
|
||||
break;
|
||||
|
||||
case ShaderPropertyType.Int:
|
||||
List<string> choices = ReadEnumChoices(description);
|
||||
if (choices != null)
|
||||
{
|
||||
Show(row.enumField);
|
||||
WireEnum(row, choices);
|
||||
}
|
||||
else if (row.keyword != null)
|
||||
{
|
||||
Show(row.toggle);
|
||||
WireToggle(row);
|
||||
}
|
||||
else
|
||||
{
|
||||
Show(row.intValue);
|
||||
WireInt(row);
|
||||
}
|
||||
break;
|
||||
|
||||
case ShaderPropertyType.Color:
|
||||
Show(row.colorField);
|
||||
if (row.colorField != null)
|
||||
{
|
||||
row.colorField.hdr = description != null && description.IndexOf("HDR", StringComparison.Ordinal) >= 0;
|
||||
row.colorField.showAlpha = true;
|
||||
}
|
||||
WireColor(row);
|
||||
break;
|
||||
|
||||
case ShaderPropertyType.Vector:
|
||||
Show(row.vectorGroup);
|
||||
WireVector(row);
|
||||
break;
|
||||
|
||||
case ShaderPropertyType.Texture:
|
||||
Show(row.textureField);
|
||||
if (row.textureField != null)
|
||||
{
|
||||
row.textureField.objectType = typeof(Texture);
|
||||
row.textureField.allowSceneObjects = false;
|
||||
// [NonModifiableTexture] 的图是 shader 写死的,给个能看的框但别让人以为改得动
|
||||
row.textureField.SetEnabled(!ShaderUtil.IsShaderPropertyNonModifiableTexureProperty(shader, propIndex));
|
||||
}
|
||||
WireTexture(row);
|
||||
break;
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
private static string ReadDisplayName(Shader shader, int propIndex, string propName)
|
||||
{
|
||||
#if UNITY_2022_2_OR_NEWER
|
||||
string displayName = ShaderUtil.GetPropertyDisplayName(shader, propIndex);
|
||||
if (!string.IsNullOrEmpty(displayName))
|
||||
return displayName;
|
||||
#endif
|
||||
return HumanizePropertyName(propName);
|
||||
}
|
||||
|
||||
/// <summary> <c>_BaseColor</c> → <c>Base Color</c>:下划线只是 shader 的命名习惯,不该出现在界面上 </summary>
|
||||
private static string HumanizePropertyName(string propName)
|
||||
{
|
||||
string text = propName.StartsWith("_", StringComparison.Ordinal) ? propName.Substring(1) : propName;
|
||||
var builder = new System.Text.StringBuilder(text.Length + 4);
|
||||
for (int i = 0; i < text.Length; i++)
|
||||
{
|
||||
char c = text[i];
|
||||
if (i > 0 && char.IsUpper(c) && !char.IsUpper(text[i - 1]) && builder.Length > 0)
|
||||
builder.Append(' ');
|
||||
builder.Append(c);
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 description 里认 <c>[Toggle(KEYWORD)]</c> / <c>[IntRange(KEYWORD)]</c> 的关键字。
|
||||
/// Unity 在这里给到的形状不止一种("<c>_MY_KEYWORD</c>"、"My Toggle (<c>_MY_KEYWORD</c>)"、
|
||||
/// "Toggle - <c>_MY_KEYWORD</c> on off"),所以规则是:挑一个下划线开头、或以
|
||||
/// <c>_ON</c> / <c>_OFF</c> 结尾的标识符。
|
||||
/// <para>故意不收全大写裸词(<c>SPECULAR</c> 这种散文会被误判成关键字,把数字属性变成勾);
|
||||
/// 代价是 <c>[Toggle(FOO)]</c> 这类不带下划线的写法认不出来,退回数字框——功能不丢,只是少了个勾。</para>
|
||||
/// </summary>
|
||||
private static string ReadKeyword(ShaderPropertyType type, string description)
|
||||
{
|
||||
if (string.IsNullOrEmpty(description))
|
||||
return null;
|
||||
if (type != ShaderPropertyType.Float && type != ShaderPropertyType.Int)
|
||||
return null;
|
||||
|
||||
MatchCollection matches = Regex.Matches(description, @"_?[A-Za-z][A-Za-z0-9_]*");
|
||||
foreach (Match match in matches)
|
||||
{
|
||||
string token = match.Value;
|
||||
if (token.Length < 2)
|
||||
continue;
|
||||
if (token.StartsWith("_", StringComparison.Ordinal))
|
||||
return token;
|
||||
if (token.EndsWith("_ON", StringComparison.Ordinal) || token.EndsWith("_OFF", StringComparison.Ordinal))
|
||||
return token;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary> <c>[Enum(A|B|C)]</c> 与 <c>[KeywordEnum]</c> 的取值表;不是枚举就返回 null </summary>
|
||||
private static List<string> ReadEnumChoices(string description)
|
||||
{
|
||||
if (string.IsNullOrEmpty(description))
|
||||
return null;
|
||||
char[] separators = description.IndexOf('|') >= 0 ? new[] { '|' } : new[] { ',' };
|
||||
if (description.IndexOf('|') < 0 && description.IndexOf(',') < 0)
|
||||
return null;
|
||||
|
||||
string[] parts = description.Split(separators);
|
||||
var choices = new List<string>(parts.Length);
|
||||
foreach (string part in parts)
|
||||
{
|
||||
string trimmed = part.Trim();
|
||||
if (trimmed.Length == 0)
|
||||
return null;
|
||||
choices.Add(trimmed);
|
||||
}
|
||||
// 只有一个分隔符的散文("1, 000"之类)不该被当成枚举
|
||||
return choices.Count >= 2 ? choices : null;
|
||||
}
|
||||
|
||||
// ── 取值 / 写值 ─────────────────────────────────────────
|
||||
|
||||
private void FillFromMaterial(Row row)
|
||||
{
|
||||
switch (row.propType)
|
||||
{
|
||||
case ShaderPropertyType.Range:
|
||||
float range = m_Material.GetFloat(row.propName);
|
||||
// shader 的范围声明可能写反(Range(1, 0)),滑块吃下反区间会直接画不出把手
|
||||
float min = Mathf.Min(row.rangeMin, row.rangeMax);
|
||||
float max = Mathf.Max(row.rangeMin, row.rangeMax);
|
||||
if (row.slider != null) { row.slider.lowValue = min; row.slider.highValue = max; }
|
||||
if (range < min || range > max)
|
||||
{
|
||||
// 值掉在区间外时把区间撑开,否则滑块会把值就地改掉——那是"我动了你的参数"
|
||||
if (row.slider != null) { row.slider.lowValue = Mathf.Min(min, range); row.slider.highValue = Mathf.Max(max, range); }
|
||||
}
|
||||
if (row.slider != null) row.slider.SetValueWithoutNotify(Mathf.Clamp(range, row.slider.lowValue, row.slider.highValue));
|
||||
if (row.rangeValue != null) row.rangeValue.SetValueWithoutNotify(range);
|
||||
break;
|
||||
|
||||
case ShaderPropertyType.Float:
|
||||
float value = m_Material.GetFloat(row.propName);
|
||||
if (row.toggle != null && row.keyword != null) row.toggle.SetValueWithoutNotify(!Mathf.Approximately(value, 0f));
|
||||
if (row.floatValue != null) row.floatValue.SetValueWithoutNotify(value);
|
||||
break;
|
||||
|
||||
case ShaderPropertyType.Int:
|
||||
int intValue = m_Material.GetInt(row.propName);
|
||||
if (row.toggle != null && row.keyword != null) row.toggle.SetValueWithoutNotify(intValue != 0);
|
||||
if (row.intValue != null) row.intValue.SetValueWithoutNotify(intValue);
|
||||
if (row.enumField != null)
|
||||
row.enumField.SetValueWithoutNotify(ChoiceLabelFor(intValue, row.enumField.choices));
|
||||
break;
|
||||
|
||||
case ShaderPropertyType.Color:
|
||||
if (row.colorField != null) row.colorField.SetValueWithoutNotify(m_Material.GetColor(row.propName));
|
||||
break;
|
||||
|
||||
case ShaderPropertyType.Vector:
|
||||
Vector4 v = m_Material.GetVector(row.propName);
|
||||
if (row.vectorParts != null)
|
||||
{
|
||||
row.vectorParts[0].SetValueWithoutNotify(v.x);
|
||||
row.vectorParts[1].SetValueWithoutNotify(v.y);
|
||||
row.vectorParts[2].SetValueWithoutNotify(v.z);
|
||||
row.vectorParts[3].SetValueWithoutNotify(v.w);
|
||||
}
|
||||
break;
|
||||
|
||||
case ShaderPropertyType.Texture:
|
||||
if (row.textureField != null) row.textureField.SetValueWithoutNotify(m_Material.GetTexture(row.propName));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void Write(Row row)
|
||||
{
|
||||
Action handler = changed;
|
||||
if (handler != null)
|
||||
handler.Invoke();
|
||||
}
|
||||
|
||||
private void WriteKeywordState(Row row, bool on)
|
||||
{
|
||||
if (row.keyword == null || m_Material == null)
|
||||
return;
|
||||
// Unity 的原生材质面板就是这么做的:值写 float,关键字另写一份,两者必须同步
|
||||
m_Material.SetFloat(row.propName, on ? 1f : 0f);
|
||||
if (on) m_Material.EnableKeyword(row.keyword);
|
||||
else m_Material.DisableKeyword(row.keyword);
|
||||
}
|
||||
|
||||
private void WireSlider(Row row)
|
||||
{
|
||||
if (row.slider == null) return;
|
||||
row.slider.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating || m_Material == null) return;
|
||||
m_Material.SetFloat(row.propName, evt.newValue);
|
||||
if (row.rangeValue != null) row.rangeValue.SetValueWithoutNotify(evt.newValue);
|
||||
Write(row);
|
||||
});
|
||||
}
|
||||
|
||||
private void WireRangeValue(Row row)
|
||||
{
|
||||
if (row.rangeValue == null) return;
|
||||
row.rangeValue.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating || m_Material == null) return;
|
||||
m_Material.SetFloat(row.propName, evt.newValue);
|
||||
if (row.slider != null)
|
||||
row.slider.SetValueWithoutNotify(Mathf.Clamp(evt.newValue, row.slider.lowValue, row.slider.highValue));
|
||||
Write(row);
|
||||
});
|
||||
}
|
||||
|
||||
private void WireFloat(Row row)
|
||||
{
|
||||
if (row.floatValue == null) return;
|
||||
row.floatValue.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating || m_Material == null) return;
|
||||
m_Material.SetFloat(row.propName, evt.newValue);
|
||||
Write(row);
|
||||
});
|
||||
}
|
||||
|
||||
private void WireInt(Row row)
|
||||
{
|
||||
if (row.intValue == null) return;
|
||||
row.intValue.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating || m_Material == null) return;
|
||||
m_Material.SetInt(row.propName, evt.newValue);
|
||||
Write(row);
|
||||
});
|
||||
}
|
||||
|
||||
private void WireToggle(Row row)
|
||||
{
|
||||
if (row.toggle == null) return;
|
||||
row.toggle.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating || m_Material == null) return;
|
||||
WriteKeywordState(row, evt.newValue);
|
||||
Write(row);
|
||||
});
|
||||
}
|
||||
|
||||
private void WireEnum(Row row, List<string> choices)
|
||||
{
|
||||
if (row.enumField == null) return;
|
||||
row.enumField.choices = choices;
|
||||
row.enumField.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating || m_Material == null) return;
|
||||
int index = choices.IndexOf(evt.newValue);
|
||||
m_Material.SetInt(row.propName, Mathf.Max(index, 0));
|
||||
Write(row);
|
||||
});
|
||||
}
|
||||
|
||||
private void WireColor(Row row)
|
||||
{
|
||||
if (row.colorField == null) return;
|
||||
row.colorField.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating || m_Material == null) return;
|
||||
m_Material.SetColor(row.propName, evt.newValue);
|
||||
Write(row);
|
||||
});
|
||||
}
|
||||
|
||||
private void WireVector(Row row)
|
||||
{
|
||||
for (int i = 0; i < row.vectorParts.Length; i++)
|
||||
{
|
||||
FloatField field = row.vectorParts[i];
|
||||
if (field == null) continue;
|
||||
int component = i;
|
||||
field.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating || m_Material == null) return;
|
||||
Vector4 v = m_Material.GetVector(row.propName);
|
||||
if (component == 0) v.x = evt.newValue;
|
||||
else if (component == 1) v.y = evt.newValue;
|
||||
else if (component == 2) v.z = evt.newValue;
|
||||
else v.w = evt.newValue;
|
||||
m_Material.SetVector(row.propName, v);
|
||||
Write(row);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void WireTexture(Row row)
|
||||
{
|
||||
if (row.textureField == null) return;
|
||||
row.textureField.RegisterValueChangedCallback(evt =>
|
||||
{
|
||||
if (row.updating || m_Material == null) return;
|
||||
m_Material.SetTexture(row.propName, evt.newValue as Texture);
|
||||
Write(row);
|
||||
});
|
||||
}
|
||||
|
||||
private static string ChoiceLabelFor(int value, List<string> choices)
|
||||
{
|
||||
if (choices == null || choices.Count == 0)
|
||||
return string.Empty;
|
||||
if (value < 0 || value >= choices.Count)
|
||||
return value.ToString();
|
||||
return choices[value];
|
||||
}
|
||||
|
||||
private static void HideAll(Row row)
|
||||
{
|
||||
Hide(row.floatValue);
|
||||
Hide(row.intValue);
|
||||
Hide(row.toggle);
|
||||
Hide(row.enumField);
|
||||
Hide(row.colorField);
|
||||
Hide(row.textureField);
|
||||
Hide(row.rangeGroup);
|
||||
Hide(row.vectorGroup);
|
||||
}
|
||||
|
||||
private static void Show(VisualElement element)
|
||||
{
|
||||
if (element != null) element.style.display = DisplayStyle.Flex;
|
||||
}
|
||||
|
||||
private static void Hide(VisualElement element)
|
||||
{
|
||||
if (element != null) element.style.display = DisplayStyle.None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ef4c99373e2d75e47b074bb6f18f86e1
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -72,6 +72,8 @@ namespace XericUI.Core
|
||||
public const string TableBar = MenuBarRoot + "/Table";
|
||||
/// <summary> 通用 UI 族的工具栏入口(场景变形手柄开关) </summary>
|
||||
public const string UIBar = MenuBarRoot + "/UI";
|
||||
/// <summary> 工具族(离线渲染 / 烘焙之类的一次性工具) </summary>
|
||||
public const string ToolBar = MenuBarRoot + "/Tool";
|
||||
|
||||
// ── Hierarchy 创建菜单 ────────────────────────────────────
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 522b7a3600dfdd04b869d20446c48dab
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,125 @@
|
||||
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 会把内部那张一起销毁,所以交出去的是按同一套参数另建的一张。
|
||||
// 这张要能被 Blit 写入,只能是单采样(采样已在 Render 里解析过了)。
|
||||
var effective = settings != null ? settings : ShaderBakeSettings.CreateDefault();
|
||||
var copy = effective.output.CreateRenderTexture("ShaderBakeResult", 1);
|
||||
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,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 198f9d8821b7c7345b4f336fb8bea669
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,124 @@
|
||||
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>
|
||||
/// 视口(世界 → 相机)矩阵。
|
||||
///
|
||||
/// <para><b>为什么要镜像 Z</b>:<see cref="Matrix4x4.Perspective"/> 与 <see cref="Matrix4x4.Ortho"/>
|
||||
/// 沿用 OpenGL 约定——相机朝 <b>-Z</b> 看;而 <c>TRS(...).inverse</c> 给出的是 Unity 自己的
|
||||
/// "朝 +Z 看"。两者直接拼起来,正前方的物体会得到负的裁剪 w(透视)或落在近远裁剪面之外(正交),
|
||||
/// 整块几何被裁光,表现就是"渲染成功但画面全透明"。</para>
|
||||
/// </summary>
|
||||
public Matrix4x4 viewMatrix
|
||||
{
|
||||
get
|
||||
{
|
||||
Matrix4x4 worldToLocal = Matrix4x4.TRS(position, Quaternion.Euler(eulerAngles), Vector3.one).inverse;
|
||||
return Matrix4x4.Scale(new Vector3(1f, 1f, -1f)) * worldToLocal;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 void Clamp()
|
||||
{
|
||||
orthographicSize = Mathf.Max(Mathf.Abs(orthographicSize), 0.0001f);
|
||||
fieldOfView = Mathf.Clamp(Mathf.Abs(fieldOfView), 1f, 179f);
|
||||
nearClipPlane = Mathf.Max(Mathf.Abs(nearClipPlane), 0.0001f);
|
||||
farClipPlane = Mathf.Max(Mathf.Abs(farClipPlane), nearClipPlane + 0.0001f);
|
||||
}
|
||||
|
||||
/// <summary> 摄像机指纹:变了不需要重建网格,只需要重画 </summary>
|
||||
public string GetCameraSignature()
|
||||
{
|
||||
return orthographic + "_" + orthographicSize + "_" + fieldOfView + "_" +
|
||||
nearClipPlane + "_" + farClipPlane + "_" + position + "_" + eulerAngles;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 65ae94c1813cc534f81fb2c5dc957a47
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,283 @@
|
||||
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 BuildFaces(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 BuildFaces(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>
|
||||
/// 按面片网格造一张平面:每个格子是一张完整的面片,UV 从自己格子的编号起算。
|
||||
/// <paramref name="segmentsX"/>/<paramref name="segmentsY"/> 是<b>单张面片内部</b>的细分,
|
||||
/// 给顶点着色器留梯度用;格子本身恒为一张。
|
||||
/// </summary>
|
||||
private static Mesh BuildFaces(ShaderBakeSurfaceSettings surface, int segmentsX, int segmentsY)
|
||||
{
|
||||
int columns = Mathf.Max(surface.gridColumns, 1);
|
||||
int rows = Mathf.Max(surface.gridRows, 1);
|
||||
segmentsX = Mathf.Max(segmentsX, 1);
|
||||
segmentsY = Mathf.Max(segmentsY, 1);
|
||||
|
||||
// size 是"每一格"的尺寸:加一格,整个平面就往那一侧长一格出去
|
||||
float faceWidth = surface.size.x;
|
||||
float faceHeight = surface.size.y;
|
||||
float halfWidth = faceWidth * columns * 0.5f;
|
||||
float halfHeight = faceHeight * rows * 0.5f;
|
||||
|
||||
int verticesPerFace = (segmentsX + 1) * (segmentsY + 1);
|
||||
int vertexCount = columns * rows * verticesPerFace;
|
||||
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 * segmentsX * segmentsY * (surface.doubleSided ? 12 : 6));
|
||||
|
||||
int stride = segmentsX + 1;
|
||||
for (int row = 0; row < rows; row++)
|
||||
for (int column = 0; column < columns; column++)
|
||||
{
|
||||
ShaderBakeFaceCell face = surface.GetFace(row * columns + column);
|
||||
float originX = -halfWidth + column * faceWidth;
|
||||
float originY = -halfHeight + row * faceHeight;
|
||||
int baseIndex = vertices.Count;
|
||||
|
||||
for (int y = 0; y <= segmentsY; y++)
|
||||
{
|
||||
float ty = (float)y / segmentsY;
|
||||
for (int x = 0; x <= segmentsX; x++)
|
||||
{
|
||||
float tx = (float)x / segmentsX;
|
||||
vertices.Add(new Vector3(originX + tx * faceWidth, originY + ty * faceHeight, 0f));
|
||||
normals.Add(Vector3.back); // 面朝 -Z,即默认相机(朝 +Z 看)看到的正面
|
||||
// 格子编号 + 面内 0~1,再统一套上全局的偏移/重复
|
||||
uvs.Add(RemapUv(new Vector2(face.uvX + tx, face.uvY + ty), surface));
|
||||
}
|
||||
}
|
||||
|
||||
for (int y = 0; y < segmentsY; y++)
|
||||
for (int x = 0; x < segmentsX; x++)
|
||||
{
|
||||
int bottomLeft = baseIndex + y * stride + x;
|
||||
int bottomRight = bottomLeft + 1;
|
||||
int topLeft = bottomLeft + stride;
|
||||
int topRight = topLeft + 1;
|
||||
// 与 Unity 内置 Quad 同向:从法线指的那一侧看是 xy 平面的逆时针。
|
||||
// 究竟哪一侧算正面由图形 API 决定,而这条链路的投影矩阵是自己拼的、没有相机帮忙统一,
|
||||
// 所以单靠一个固定绕序永远会在某个 API 上被 Cull Back 剔光——见 doubleSided。
|
||||
AddQuad(triangles, bottomLeft, bottomRight, topRight, topLeft, false);
|
||||
if (surface.doubleSided)
|
||||
AddQuad(triangles, bottomLeft, bottomRight, topRight, topLeft, true);
|
||||
}
|
||||
}
|
||||
|
||||
var mesh = NewMesh(vertexCount > 65000 ? "ShaderBakeFaces" : "ShaderBakeQuad");
|
||||
if (vertexCount > 65000)
|
||||
mesh.indexFormat = IndexFormat.UInt32;
|
||||
mesh.SetVertices(vertices);
|
||||
mesh.SetNormals(normals);
|
||||
mesh.SetUVs(0, uvs);
|
||||
mesh.SetTriangles(triangles, 0);
|
||||
Upload(mesh);
|
||||
return mesh;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一个格子的两个三角面。<paramref name="reverse"/> 为真时把绕序整个反过来:同一片几何
|
||||
/// 在"顺时针算正面"与"逆时针算正面"两种约定下各有一份是可见的,而另一份仍会被剔除,
|
||||
/// 所以不会画两遍、透明混合也不会被叠加两次。
|
||||
/// </summary>
|
||||
private static void AddQuad(List<int> triangles, int bottomLeft, int bottomRight, int topRight, int topLeft, bool reverse)
|
||||
{
|
||||
if (reverse)
|
||||
{
|
||||
triangles.Add(bottomLeft); triangles.Add(bottomRight); triangles.Add(topLeft);
|
||||
triangles.Add(bottomRight); triangles.Add(topRight); triangles.Add(topLeft);
|
||||
return;
|
||||
}
|
||||
triangles.Add(bottomLeft); triangles.Add(bottomRight); triangles.Add(topRight);
|
||||
triangles.Add(bottomLeft); triangles.Add(topRight); triangles.Add(topLeft);
|
||||
}
|
||||
|
||||
/// <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 BuildFaces(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++)
|
||||
{
|
||||
int[] tris = source.GetTriangles(i);
|
||||
if (surface.doubleSided)
|
||||
{
|
||||
// 反向补一份,理由同 AddQuad:正面对侧的约定由 API 决定,别让烘焙结果取决于显卡
|
||||
int complete = tris.Length / 3 * 3;
|
||||
var both = new int[tris.Length + complete];
|
||||
tris.CopyTo(both, 0);
|
||||
for (int t = 0; t < complete; t += 3)
|
||||
{
|
||||
both[tris.Length + t] = tris[t];
|
||||
both[tris.Length + t + 1] = tris[t + 2];
|
||||
both[tris.Length + t + 2] = tris[t + 1];
|
||||
}
|
||||
tris = both;
|
||||
}
|
||||
mesh.SetTriangles(tris, 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,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b86fe4466c4837f47bbe2e2bdc5454a1
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,158 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary> 能喂给 shader 的全局量类别,决定用哪个 SetGlobal 入口 </summary>
|
||||
public enum ShaderBakeGlobalKind
|
||||
{
|
||||
Float,
|
||||
Vector,
|
||||
Color,
|
||||
Texture
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一条全局参数。贴图引用标了 <see cref="NonSerializedAttribute"/>:JsonUtility 存不下来资产引用,
|
||||
/// 硬存一个实例 ID 反而会在换会话后变成半死的引用。
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeGlobalEntry
|
||||
{
|
||||
public string name;
|
||||
|
||||
public ShaderBakeGlobalKind kind;
|
||||
|
||||
[Tooltip("关掉就完全不动这个全局量,包括不捕获、不还原")]
|
||||
public bool enabled;
|
||||
|
||||
public float x;
|
||||
public float y;
|
||||
public float z;
|
||||
public float w;
|
||||
|
||||
[NonSerialized] public Texture texture;
|
||||
|
||||
public ShaderBakeGlobalEntry() { }
|
||||
|
||||
public ShaderBakeGlobalEntry(string name, ShaderBakeGlobalKind kind, bool enabled = false)
|
||||
{
|
||||
this.name = name;
|
||||
this.kind = kind;
|
||||
this.enabled = enabled;
|
||||
w = 1f;
|
||||
}
|
||||
|
||||
public Vector4 ToVector() { return new Vector4(x, y, z, w); }
|
||||
|
||||
public Color ToColor() { return new Color(x, y, z, w); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一组全局参数。烘焙走的是离屏命令缓冲,没有相机在渲染,"灯在哪、环境光是什么"这类由引擎
|
||||
/// 在相机流程里塞进去的全局量天然缺失——这里就是补那一块的口子。
|
||||
///
|
||||
/// <para><b>只改自己认识的那几条,并且画完就还原</b>:不还原等于把一次烘焙的临时值泄漏给整个编辑器。
|
||||
/// 还原是尽力而为:引擎每帧会重设的内置量(例如相机相关的矩阵)可能被覆盖回去。</para>
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeGlobalSettings
|
||||
{
|
||||
[Tooltip("要参与烘焙的全局参数。没勾选的行完全不参与")]
|
||||
public List<ShaderBakeGlobalEntry> entries = new List<ShaderBakeGlobalEntry>();
|
||||
|
||||
/// <summary>
|
||||
/// 把启用的条目写进全局,并返回一组还原动作(按相反顺序执行)。
|
||||
/// </summary>
|
||||
public List<Action> Apply()
|
||||
{
|
||||
var restores = new List<Action>();
|
||||
if (entries == null)
|
||||
return restores;
|
||||
|
||||
for (int i = 0; i < entries.Count; i++)
|
||||
{
|
||||
ShaderBakeGlobalEntry entry = entries[i];
|
||||
if (entry == null || !entry.enabled || string.IsNullOrEmpty(entry.name))
|
||||
continue;
|
||||
|
||||
string name = entry.name;
|
||||
switch (entry.kind)
|
||||
{
|
||||
case ShaderBakeGlobalKind.Float:
|
||||
{
|
||||
float previous = Shader.GetGlobalFloat(name);
|
||||
Shader.SetGlobalFloat(name, entry.x);
|
||||
restores.Add(() => Shader.SetGlobalFloat(name, previous));
|
||||
break;
|
||||
}
|
||||
case ShaderBakeGlobalKind.Vector:
|
||||
{
|
||||
Vector4 previous = Shader.GetGlobalVector(name);
|
||||
Shader.SetGlobalVector(name, entry.ToVector());
|
||||
restores.Add(() => Shader.SetGlobalVector(name, previous));
|
||||
break;
|
||||
}
|
||||
case ShaderBakeGlobalKind.Color:
|
||||
{
|
||||
Color previous = Shader.GetGlobalColor(name);
|
||||
Shader.SetGlobalColor(name, entry.ToColor());
|
||||
restores.Add(() => Shader.SetGlobalColor(name, previous));
|
||||
break;
|
||||
}
|
||||
case ShaderBakeGlobalKind.Texture:
|
||||
{
|
||||
Texture previous = Shader.GetGlobalTexture(name);
|
||||
Shader.SetGlobalTexture(name, entry.texture);
|
||||
restores.Add(() => Shader.SetGlobalTexture(name, previous));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return restores;
|
||||
}
|
||||
|
||||
/// <summary> 按名字找已有条目,没有就追加一条(扫描与预设都走这里,避免重复) </summary>
|
||||
public ShaderBakeGlobalEntry Ensure(string name, ShaderBakeGlobalKind kind)
|
||||
{
|
||||
if (entries == null)
|
||||
entries = new List<ShaderBakeGlobalEntry>();
|
||||
for (int i = 0; i < entries.Count; i++)
|
||||
{
|
||||
if (entries[i] != null && entries[i].name == name)
|
||||
return entries[i];
|
||||
}
|
||||
var entry = new ShaderBakeGlobalEntry(name, kind);
|
||||
entries.Add(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 常用光照/环境量。全部默认关闭:不同渲染管线对这些名字的语义不完全一样,
|
||||
/// 该不该开由用户决定,工具不替他改画面。
|
||||
/// </summary>
|
||||
public void AddEnvironmentPresets()
|
||||
{
|
||||
AddVector("_WorldSpaceLightPos0", 0.3f, 0.7f, -0.6f, 0f);
|
||||
AddColor("_LightColor0", 1f, 1f, 1f, 1f);
|
||||
AddColor("unity_AmbientSky", 0.21f, 0.23f, 0.25f, 1f);
|
||||
AddColor("unity_AmbientEquator", 0.11f, 0.12f, 0.13f, 1f);
|
||||
AddColor("unity_AmbientGround", 0.04f, 0.04f, 0.04f, 1f);
|
||||
AddVector("_Time", 0f, 0f, 0f, 0f);
|
||||
Ensure("unity_SpecCube0", ShaderBakeGlobalKind.Texture);
|
||||
}
|
||||
|
||||
private void AddVector(string name, float x, float y, float z, float w)
|
||||
{
|
||||
ShaderBakeGlobalEntry entry = Ensure(name, ShaderBakeGlobalKind.Vector);
|
||||
entry.x = x; entry.y = y; entry.z = z; entry.w = w;
|
||||
}
|
||||
|
||||
private void AddColor(string name, float x, float y, float z, float w)
|
||||
{
|
||||
ShaderBakeGlobalEntry entry = Ensure(name, ShaderBakeGlobalKind.Color);
|
||||
entry.x = x; entry.y = y; entry.z = z; entry.w = w;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 77fd56ea769f4804d9953825a78f5ad0
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,90 @@
|
||||
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
|
||||
{
|
||||
// 编辑器非播放状态下 Object.Destroy 会被拒绝并报错,统一走这条能分辨时机的回收
|
||||
ShaderBakeRenderer.ReleaseTempObject(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,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bdcb0938705cfd640a80e6a3f798c494
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -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,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3fe9d4e18fb587e49a4ba3ec6187f551
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,145 @@
|
||||
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(调用方负责销毁)。
|
||||
/// <paramref name="samples"/> 传负数表示按设置走;解析目标必须显式传 1——
|
||||
/// 往多采样目标上 Blit 是非法的,MSAA 那条路要靠"先画采样目标、再落地到单采样目标"。
|
||||
/// </summary>
|
||||
public RenderTexture CreateRenderTexture(string name = "ShaderBakeTarget", int samples = -1)
|
||||
{
|
||||
Clamp();
|
||||
int actualSamples = samples < 0 ? antiAliasing : SnapAntiAliasing(samples);
|
||||
if (hdr && actualSamples > 1)
|
||||
actualSamples = 1;
|
||||
var rt = new RenderTexture(width, height, depthBuffer, format, renderTextureColorSpace)
|
||||
{
|
||||
name = name,
|
||||
filterMode = filterMode,
|
||||
wrapMode = wrapMode,
|
||||
antiAliasing = actualSamples,
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
// 显式 Create:antiAliasing 只有在初始化之前赋值才生效,靠第一次使用时自动建就丢了
|
||||
rt.Create();
|
||||
return rt;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 03abdcca544f3a346ba5202158b34274
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,151 @@
|
||||
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, mipChain);
|
||||
return texture;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读进一张已存在的纹理(尺寸要和 source 一致;不一致 Unity 只会填左上角,剩下留黑)。
|
||||
/// 走 RenderTexture.active + ReadPixels,MSAA 目标已被调用方解析过,这里读到的是解析后的像素。
|
||||
/// </summary>
|
||||
public static void CopyInto(RenderTexture source, Texture2D destination, bool recalculateMipMaps = false)
|
||||
{
|
||||
RenderTexture previous = RenderTexture.active;
|
||||
try
|
||||
{
|
||||
RenderTexture.active = source;
|
||||
destination.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0, recalculateMipMaps);
|
||||
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>
|
||||
/// 结果统计:把目标降采样到 64×64 再读回,算出"有不透明像素的比例"和它们的平均颜色。
|
||||
///
|
||||
/// <para><b>为什么值得花这一次读回</b>:离屏烘焙最常见的两种失败——"什么都没画出来"(剔除、
|
||||
/// pass、相机框不住)与"画出来了但 alpha 是 0"(贴图没指定、混合模式吃掉颜色)——在预览里
|
||||
/// 长得一模一样,都是棋盘格。有一个数字就能把它们分开。</para>
|
||||
/// </summary>
|
||||
public static bool MeasureCoverage(RenderTexture source, out float opaqueRatio, out Color averageColor)
|
||||
{
|
||||
opaqueRatio = 0f;
|
||||
averageColor = Color.clear;
|
||||
if (source == null || !source.IsCreated())
|
||||
return false;
|
||||
|
||||
const int side = 64;
|
||||
RenderTexture previous = RenderTexture.active;
|
||||
RenderTexture small = RenderTexture.GetTemporary(side, side, 0,
|
||||
RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
|
||||
var probe = new Texture2D(side, side, TextureFormat.RGBA32, false, true)
|
||||
{
|
||||
hideFlags = HideFlags.DontSave
|
||||
};
|
||||
try
|
||||
{
|
||||
// 用 GetTemporary 而不是自己建:省掉一次显存分配,也躲开"目标正在被显示"的占用冲突
|
||||
Graphics.Blit(source, small);
|
||||
RenderTexture.active = small;
|
||||
probe.ReadPixels(new Rect(0, 0, side, side), 0, 0, false);
|
||||
probe.Apply(false);
|
||||
|
||||
Color32[] pixels = probe.GetPixels32();
|
||||
int opaque = 0;
|
||||
float r = 0f, g = 0f, b = 0f;
|
||||
for (int i = 0; i < pixels.Length; i++)
|
||||
{
|
||||
// 阈值 8/255:线性插值边缘那一圈极淡的像素不该算成"画出来了"
|
||||
if (pixels[i].a <= 8)
|
||||
continue;
|
||||
opaque++;
|
||||
r += pixels[i].r;
|
||||
g += pixels[i].g;
|
||||
b += pixels[i].b;
|
||||
}
|
||||
opaqueRatio = (float)opaque / pixels.Length;
|
||||
if (opaque > 0)
|
||||
averageColor = new Color(r / opaque / 255f, g / opaque / 255f, b / opaque / 255f, 1f);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
RenderTexture.active = previous;
|
||||
RenderTexture.ReleaseTemporary(small);
|
||||
ShaderBakeRenderer.ReleaseTempObject(probe);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 91e2060e655b6264585f07d092ad4908
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,433 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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;
|
||||
private MaterialPropertyBlock m_Block;
|
||||
|
||||
/// <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>
|
||||
/// 把浏览图上的一个点(0~1,左上为原点)打到面片网络上,返回命中的格子序号。
|
||||
/// 用的是与烘焙完全相同的投影,所以"看到的哪一格"和"点到的哪一格"是同一套坐标。
|
||||
/// </summary>
|
||||
public bool TryPickFace(Vector2 viewport01, out int faceIndex)
|
||||
{
|
||||
faceIndex = -1;
|
||||
Matrix4x4 viewProjection;
|
||||
if (!TryGetViewProjection(out viewProjection))
|
||||
return false;
|
||||
|
||||
ShaderBakeSurfaceSettings surface = settings.surface;
|
||||
float ndcX = viewport01.x * 2f - 1f;
|
||||
float ndcY = 1f - viewport01.y * 2f;
|
||||
Matrix4x4 inverse = viewProjection.inverse;
|
||||
Vector3 near = Unproject(inverse, new Vector3(ndcX, ndcY, -1f));
|
||||
Vector3 far = Unproject(inverse, new Vector3(ndcX, ndcY, 1f));
|
||||
Vector3 direction = far - near;
|
||||
|
||||
Matrix4x4 local = surface.localMatrix;
|
||||
Vector3 planePoint = local.MultiplyPoint3x4(Vector3.zero);
|
||||
Vector3 planeNormal = local.MultiplyVector(Vector3.forward).normalized;
|
||||
float denominator = Vector3.Dot(direction, planeNormal);
|
||||
if (Mathf.Abs(denominator) < 0.000001f)
|
||||
return false;
|
||||
float distance = Vector3.Dot(planePoint - near, planeNormal) / denominator;
|
||||
if (distance < 0f)
|
||||
return false;
|
||||
|
||||
int columns = Mathf.Max(surface.gridColumns, 1);
|
||||
int rows = Mathf.Max(surface.gridRows, 1);
|
||||
Vector3 localPoint = local.inverse.MultiplyPoint3x4(near + direction * distance);
|
||||
float totalWidth = surface.size.x * columns;
|
||||
float totalHeight = surface.size.y * rows;
|
||||
float u = (localPoint.x + totalWidth * 0.5f) / totalWidth;
|
||||
float v = (localPoint.y + totalHeight * 0.5f) / totalHeight;
|
||||
if (u < 0f || u > 1f || v < 0f || v > 1f)
|
||||
return false;
|
||||
int column = Mathf.Clamp(Mathf.FloorToInt(u * columns), 0, columns - 1);
|
||||
int row = Mathf.Clamp(Mathf.FloorToInt(v * rows), 0, rows - 1);
|
||||
faceIndex = row * columns + column;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 某一格在浏览图上的矩形范围(0~1,左上为原点),用来把选中高亮贴在图上。
|
||||
/// 透视或旋转时这是一个外接框,不是精确的四边形轮廓。
|
||||
/// </summary>
|
||||
public bool TryGetFaceViewportBounds(int faceIndex, out Vector2 min, out Vector2 max)
|
||||
{
|
||||
min = Vector2.zero;
|
||||
max = Vector2.zero;
|
||||
Matrix4x4 viewProjection;
|
||||
if (!TryGetViewProjection(out viewProjection))
|
||||
return false;
|
||||
|
||||
ShaderBakeSurfaceSettings surface = settings.surface;
|
||||
int columns = Mathf.Max(surface.gridColumns, 1);
|
||||
int rows = Mathf.Max(surface.gridRows, 1);
|
||||
if (faceIndex < 0 || faceIndex >= columns * rows)
|
||||
return false;
|
||||
|
||||
float faceWidth = surface.size.x;
|
||||
float faceHeight = surface.size.y;
|
||||
int column = faceIndex % columns;
|
||||
int row = faceIndex / columns;
|
||||
float x0 = -faceWidth * columns * 0.5f + column * faceWidth;
|
||||
float y0 = -faceHeight * rows * 0.5f + row * faceHeight;
|
||||
float x1 = x0 + faceWidth;
|
||||
float y1 = y0 + faceHeight;
|
||||
|
||||
Matrix4x4 local = surface.localMatrix;
|
||||
bool first = true;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
Vector3 corner = new Vector3((i & 1) == 0 ? x0 : x1, (i & 2) == 0 ? y0 : y1, 0f);
|
||||
Vector4 clip = viewProjection * local.MultiplyPoint3x4(corner);
|
||||
if (clip.w <= 0.0001f)
|
||||
return false;
|
||||
float u = (clip.x / clip.w + 1f) * 0.5f;
|
||||
float v = 1f - (clip.y / clip.w + 1f) * 0.5f;
|
||||
if (float.IsNaN(u) || float.IsNaN(v))
|
||||
return false;
|
||||
var point = new Vector2(Mathf.Clamp01(u), Mathf.Clamp01(v));
|
||||
if (first)
|
||||
{
|
||||
min = max = point;
|
||||
first = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
min = Vector2.Min(min, point);
|
||||
max = Vector2.Max(max, point);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryGetViewProjection(out Matrix4x4 viewProjection)
|
||||
{
|
||||
viewProjection = Matrix4x4.identity;
|
||||
if (settings == null || settings.surface == null)
|
||||
return false;
|
||||
// 外部网格不是平面,"点选格子"这件事对它没有意义
|
||||
if (settings.surface.kind == ShaderBakeSurfaceKind.Mesh && settings.surface.sourceMesh != null)
|
||||
return false;
|
||||
|
||||
Matrix4x4 projection = settings.camera.GetProjectionMatrix(settings.aspect);
|
||||
if (settings.output.flipY)
|
||||
projection = Matrix4x4.Scale(new Vector3(1f, -1f, 1f)) * projection;
|
||||
viewProjection = projection * settings.camera.viewMatrix;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Vector3 Unproject(Matrix4x4 inverse, Vector3 clip)
|
||||
{
|
||||
Vector4 point = inverse * new Vector4(clip.x, clip.y, clip.z, 1f);
|
||||
float w = Mathf.Abs(point.w) < 0.0000001f ? 0.0000001f : point.w;
|
||||
return new Vector3(point.x / w, point.y / w, point.z / w);
|
||||
}
|
||||
|
||||
/// <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);
|
||||
// 落地目标永远单采样:它要能被 ReadPixels 读、能被 Blit 写入、也直接拿去显示
|
||||
m_OwnedTarget = settings.output.CreateRenderTexture("ShaderBakeTarget", 1);
|
||||
m_TargetSignature = m_OwnedTarget != null ? signature : string.Empty;
|
||||
|
||||
if (settings.output.antiAliasing > 1 && m_OwnedTarget != null)
|
||||
m_MultiSampleSource = settings.output.CreateRenderTexture("ShaderBakeMultiSample", settings.output.antiAliasing);
|
||||
|
||||
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);
|
||||
// UV 已经烘进顶点了;只有用户显式要求时再补一份 _MainTex_ST 给依赖 ST 的 shader。
|
||||
// 走属性块而不是改材质,是为了不让这一笔写进材质副本、进而被"写回原材质"带走。
|
||||
MaterialPropertyBlock block = null;
|
||||
if (settings.surface.applyUvToMainTexST)
|
||||
{
|
||||
if (m_Block == null)
|
||||
m_Block = new MaterialPropertyBlock();
|
||||
m_Block.Clear();
|
||||
m_Block.SetVector("_MainTex_ST", new Vector4(
|
||||
settings.surface.uvTiling.x, settings.surface.uvTiling.y,
|
||||
settings.surface.uvOffset.x, settings.surface.uvOffset.y));
|
||||
block = m_Block;
|
||||
}
|
||||
|
||||
m_Buffer.DrawMesh(m_Geometry, settings.surface.localMatrix, material,
|
||||
Mathf.Max(settings.surface.meshSubMesh, 0), settings.output.shaderPass, block);
|
||||
|
||||
// 翻 Y 的投影是一次镜像,会把绕序反过来,背面剔除于是剔掉本该看见的正面。
|
||||
// 不动网格(外部模型的绕序不该被我们改),只在这一刻把剔除方向反过来。
|
||||
bool previousInvert = GL.invertCulling;
|
||||
GL.invertCulling = previousInvert != settings.output.flipY;
|
||||
List<Action> restoreGlobals = settings.globals != null ? settings.globals.Apply() : null;
|
||||
try
|
||||
{
|
||||
Graphics.ExecuteCommandBuffer(m_Buffer);
|
||||
}
|
||||
finally
|
||||
{
|
||||
GL.invertCulling = previousInvert;
|
||||
// 画完立刻还原:这些是编辑器全局状态,留一次烘焙的值下来会污染别处的渲染
|
||||
if (restoreGlobals != null)
|
||||
{
|
||||
for (int i = restoreGlobals.Count - 1; i >= 0; i--)
|
||||
restoreGlobals[i]();
|
||||
}
|
||||
}
|
||||
m_Buffer.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 回收一次性对象。运行时要走 <c>Destroy</c>(当帧不能立即销毁),编辑器里请传
|
||||
/// <paramref name="immediate"/> 让 <c>DestroyImmediate</c> 立刻放掉显存——导一批图时差别很大。
|
||||
/// </summary>
|
||||
public static void ReleaseTempObject(UnityEngine.Object obj)
|
||||
{
|
||||
ReleaseTempObject(obj, false);
|
||||
}
|
||||
|
||||
public 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)
|
||||
{
|
||||
// 只 Dispose:Dispose 内部已经 Release,再单独 Release 一次会二次释放,
|
||||
// 2021.3 上表现为关闭窗口时抛 _unity_self 为空的 ArgumentNullException
|
||||
try
|
||||
{
|
||||
m_Buffer.Dispose();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// 退出编辑器/域重载期间原生对象可能已被回收,这时再报错没有意义
|
||||
}
|
||||
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,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b3ca0c634575cad4bb7704b10761be85
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,69 @@
|
||||
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();
|
||||
|
||||
[Tooltip("渲染前注入的全局参数(光照方向、环境光、反射贴图等)")]
|
||||
public ShaderBakeGlobalSettings globals = new ShaderBakeGlobalSettings();
|
||||
|
||||
/// <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();
|
||||
camera.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,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6008bb008b33a724c949a88f401dcd58
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,234 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace XericUI.ShaderBake
|
||||
{
|
||||
/// <summary>
|
||||
/// 一个面片的 UV 区域编号:面片 (0,0) 用 UV [0,1],左边一格是 [-1,0],右边一格是 [1,2],以此类推。
|
||||
/// 网格里按行优先存放(第 0 行是 y 最小的一行)。
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ShaderBakeFaceCell
|
||||
{
|
||||
public int uvX;
|
||||
public int uvY;
|
||||
|
||||
public ShaderBakeFaceCell() { }
|
||||
|
||||
public ShaderBakeFaceCell(int x, int y)
|
||||
{
|
||||
uvX = x;
|
||||
uvY = y;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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("单张面片的尺寸(世界单位)。网格整体是它的 列数×行数 倍;外部网格只在 normalizeSize 打开时用它缩放")]
|
||||
public Vector2 size = Vector2.one;
|
||||
|
||||
[Tooltip("细分平面的行列段数。只有需要顶点插值的 shader 才要调大,四边形恒为 1x1")]
|
||||
public Vector2Int segments = Vector2Int.one;
|
||||
|
||||
[Tooltip("面片网格列数。每多一列就多一张 UV 区域,整体尺寸不变")]
|
||||
public int gridColumns = 1;
|
||||
|
||||
[Tooltip("面片网格行数")]
|
||||
public int gridRows = 1;
|
||||
|
||||
[Tooltip("每个面片对应的 UV 区域编号(行优先,第 0 行在下)。默认只有一格 (0,0)")]
|
||||
public List<ShaderBakeFaceCell> faces = new List<ShaderBakeFaceCell> { new ShaderBakeFaceCell(0, 0) };
|
||||
|
||||
[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>
|
||||
/// 双面绘制:正反两份绕序都写进网格。
|
||||
///
|
||||
/// <para><b>为什么要这么兜住</b>:这条链路没有相机,视图/投影矩阵是自己拼的(含一处 Z 镜像和
|
||||
/// 一个可选的 Y 镜像),"哪一侧算正面"于是成了我们自己的推导而不是引擎的保证;押错一次
|
||||
/// 就是整片被 Cull Back 剔掉,表现是"渲染成功、画面全透明"。两份绕序里同一时刻只有一份是
|
||||
/// 正面,所以透明混合不会被算两次。只有确定要复刻引擎的剔除行为时才关掉。</para>
|
||||
/// </summary>
|
||||
[Tooltip("双面绘制:正反两份绕序,避免押错正面约定导致整片被剔除")]
|
||||
public bool doubleSided = true;
|
||||
|
||||
/// <summary> 面片自己的局部变换矩阵(DrawMesh 用的那个 model 矩阵) </summary>
|
||||
public Matrix4x4 localMatrix
|
||||
{
|
||||
get { return Matrix4x4.TRS(position, Quaternion.Euler(eulerAngles), scale); }
|
||||
}
|
||||
|
||||
/// <summary> 面片网格单边上限:再多单张图已经容纳不下可辨认的细节了 </summary>
|
||||
public const int kMaxGrid = 16;
|
||||
|
||||
public int FaceCount { get { return gridColumns * gridRows; } }
|
||||
|
||||
public ShaderBakeFaceCell GetFace(int index)
|
||||
{
|
||||
EnsureFaces();
|
||||
return faces[Mathf.Clamp(index, 0, faces.Count - 1)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 让 faces 的数量与 gridColumns × gridRows 对齐。补出来的格子默认 (0,0),
|
||||
/// 真正的 UV 编号由 <see cref="AddColumn"/> / <see cref="AddRow"/> 按邻格推算。
|
||||
/// </summary>
|
||||
public void EnsureFaces()
|
||||
{
|
||||
gridColumns = Mathf.Clamp(gridColumns, 1, kMaxGrid);
|
||||
gridRows = Mathf.Clamp(gridRows, 1, kMaxGrid);
|
||||
if (faces == null)
|
||||
faces = new List<ShaderBakeFaceCell>();
|
||||
|
||||
int wanted = FaceCount;
|
||||
while (faces.Count < wanted)
|
||||
faces.Add(new ShaderBakeFaceCell(0, 0));
|
||||
if (faces.Count > wanted)
|
||||
faces.RemoveRange(wanted, faces.Count - wanted);
|
||||
for (int i = 0; i < faces.Count; i++)
|
||||
if (faces[i] == null)
|
||||
faces[i] = new ShaderBakeFaceCell(0, 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在左边/右边加一列。新列的 UV 编号取贴边那一列的编号往外挪一格——
|
||||
/// 这正是"左边加的面是 [-1,0]"这条规则的落点。
|
||||
/// </summary>
|
||||
public void AddColumn(bool right)
|
||||
{
|
||||
EnsureFaces();
|
||||
if (gridColumns >= kMaxGrid)
|
||||
return;
|
||||
|
||||
for (int row = gridRows - 1; row >= 0; row--)
|
||||
{
|
||||
int rowStart = row * gridColumns;
|
||||
int anchor = right ? rowStart + gridColumns - 1 : rowStart;
|
||||
ShaderBakeFaceCell source = faces[anchor];
|
||||
var cell = new ShaderBakeFaceCell(source.uvX + (right ? 1 : -1), source.uvY);
|
||||
faces.Insert(right ? anchor + 1 : rowStart, cell);
|
||||
}
|
||||
gridColumns++;
|
||||
}
|
||||
|
||||
/// <summary> 在上边/下边加一行,UV 编号同样从贴着的那一行往外推 </summary>
|
||||
public void AddRow(bool top)
|
||||
{
|
||||
EnsureFaces();
|
||||
if (gridRows >= kMaxGrid)
|
||||
return;
|
||||
|
||||
int offset = top ? faces.Count : 0;
|
||||
int anchorRow = top ? gridRows - 1 : 0;
|
||||
var added = new ShaderBakeFaceCell[gridColumns];
|
||||
for (int col = 0; col < gridColumns; col++)
|
||||
{
|
||||
ShaderBakeFaceCell source = faces[anchorRow * gridColumns + col];
|
||||
added[col] = new ShaderBakeFaceCell(source.uvX, source.uvY + (top ? 1 : -1));
|
||||
}
|
||||
faces.InsertRange(offset, added);
|
||||
gridRows++;
|
||||
}
|
||||
|
||||
/// <summary> 回到单片 (0,0) —— 网格加乱了时的退路 </summary>
|
||||
public void ResetGrid()
|
||||
{
|
||||
gridColumns = 1;
|
||||
gridRows = 1;
|
||||
faces = new List<ShaderBakeFaceCell> { new ShaderBakeFaceCell(0, 0) };
|
||||
}
|
||||
|
||||
/// <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);
|
||||
EnsureFaces();
|
||||
}
|
||||
|
||||
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";
|
||||
var builder = new System.Text.StringBuilder(64);
|
||||
// 老存档里没有 faces 这一项,直接读会踩空;这里只算指纹,不做补全
|
||||
int faceCount = faces != null ? faces.Count : 0;
|
||||
for (int i = 0; i < faceCount; i++)
|
||||
builder.Append(faces[i].uvX).Append(',').Append(faces[i].uvY).Append(';');
|
||||
return kind + "_" + size + "_" + segments + "_" + uvOffset + "_" + uvTiling +
|
||||
"_" + position + "_" + eulerAngles + "_" + scale + "_" + meshId + "_" + meshSubMesh +
|
||||
"_" + normalizeMeshSize + "_" + doubleSided + "_" + gridColumns + "x" + gridRows + "_" + builder;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5b43d17582f4b254096aae006b3a0f3d
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Reference in New Issue
Block a user