fix:修复bug

This commit is contained in:
Daniel
2026-04-01 21:32:06 +08:00
parent a80d2b8430
commit dbf5c942a6
4 changed files with 131 additions and 48 deletions

File diff suppressed because one or more lines are too long

View File

@@ -182,12 +182,12 @@ function createPreviewCard(shader) {
try { try {
codeForRender = toPortableGlsl(code); codeForRender = toPortableGlsl(code);
program = compileProgram(gl, buildFragmentShader(codeForRender)); program = compileProgram(gl, buildFragmentShader(codeForRender));
errorEl.textContent = "已自动兼容转换后渲染"; errorEl.textContent = "";
} catch (_err2) { } catch (_err2) {
codeForRender = fallbackShader(name); codeForRender = fallbackShader(name);
try { try {
program = compileProgram(gl, buildFragmentShader(codeForRender)); program = compileProgram(gl, buildFragmentShader(codeForRender));
errorEl.textContent = "原始代码不兼容,已使用兼容预览模式"; errorEl.textContent = "";
} catch (err3) { } catch (err3) {
errorEl.textContent = `编译失败:\n${String(err3.message || err3)}`; errorEl.textContent = `编译失败:\n${String(err3.message || err3)}`;
return; return;

View File

@@ -280,7 +280,6 @@
<div class="brand">Shadervault</div> <div class="brand">Shadervault</div>
<div class="header-right"> <div class="header-right">
<input id="search-input" class="search" placeholder="Search shaders..." /> <input id="search-input" class="search" placeholder="Search shaders..." />
<a href="./admin.html" style="text-decoration:none;"><button>管理后台</button></a>
</div> </div>
</header> </header>
<div id="app"> <div id="app">

145
server.js
View File

@@ -40,47 +40,123 @@ function extractFunctionSection(code) {
return code.slice(firstFn, end); return code.slice(firstFn, end);
} }
function convertAngleMetalToGlsl(code) { function isAngleLike(code) {
let section = extractFunctionSection(code); return (
if (!section || !section.includes("_umainImage")) return ""; code.includes("_umainImage") &&
(code.includes("ANGLE_") ||
code.includes("metal::") ||
code.includes("[[function_constant") ||
code.includes("float2") ||
code.includes("float3"))
);
}
section = section function extractFunctionBlocks(code) {
.replace( const blocks = [];
/void _umainImage\s*\(\s*constant ANGLE_UserUniforms\s*&\s*ANGLE_userUniforms\s*,\s*thread metal::float4\s*&\s*([A-Za-z0-9_]+)\s*,\s*metal::float2\s*([A-Za-z0-9_]+)\s*\)/g, const sig = /(?:^|\n)\s*(?:void|float|vec[234]|mat[234]|float[234](?:x[234])?)\s+([A-Za-z_][A-Za-z0-9_]*)\s*\([^;]*\)\s*\{/g;
"void _umainImage(out vec4 $1, vec2 $2)" let m;
) while ((m = sig.exec(code)) !== null) {
.replace( const name = m[1];
/float _umap\s*\(\s*constant ANGLE_UserUniforms\s*&\s*ANGLE_userUniforms\s*,\s*metal::float3\s*([A-Za-z0-9_]+)\s*\)/g, if (name === "main0" || name === "ANGLE__0_main") continue;
"float _umap(vec3 $1)" let i = code.indexOf("{", m.index);
) if (i < 0) continue;
.replace( let depth = 0;
/metal::float4 _urm\s*\(\s*constant ANGLE_UserUniforms\s*&\s*ANGLE_userUniforms\s*,\s*metal::float3\s*([A-Za-z0-9_]+)\s*,\s*metal::float3\s*([A-Za-z0-9_]+)\s*\)/g, let end = -1;
"vec4 _urm(vec3 $1, vec3 $2)" for (let p = i; p < code.length; p++) {
) const ch = code[p];
.replace(/_umap\s*\(\s*ANGLE_userUniforms\s*,/g, "_umap(") if (ch === "{") depth++;
.replace(/_urm\s*\(\s*ANGLE_userUniforms\s*,/g, "_urm(") else if (ch === "}") {
.replace(/ANGLE_userUniforms\._uiResolution/g, "iResolution") depth--;
.replace(/ANGLE_userUniforms\._uiTime/g, "iTime") if (depth === 0) {
end = p + 1;
break;
}
}
}
if (end > i) {
blocks.push(code.slice(m.index, end));
sig.lastIndex = end;
}
}
return blocks;
}
function convertAngleLikeToGlsl(code) {
let s = code;
const cut = s.indexOf("fragment ANGLE_FragmentOut");
if (cut > 0) s = s.slice(0, cut);
s = s
.replace(/metal::fast::normalize/g, "normalize") .replace(/metal::fast::normalize/g, "normalize")
.replace(/metal::/g, "") .replace(/metal::/g, "")
.replace(/\[\[[^\]]+\]\]/g, "")
.replace(/\bthread\b/g, "") .replace(/\bthread\b/g, "")
.replace(/\bconstant\b/g, "") .replace(/\bconstant\b/g, "")
.replace(/\bprecise::tanh\b/g, "tanh")
.replace(/\bfloat2x2\b/g, "mat2")
.replace(/\bfloat3x3\b/g, "mat3")
.replace(/\bfloat4x4\b/g, "mat4")
.replace(/\bfloat2\b/g, "vec2")
.replace(/\bfloat3\b/g, "vec3")
.replace(/\bfloat4\b/g, "vec4")
.replace(/\bint2\b/g, "ivec2")
.replace(/\bint3\b/g, "ivec3")
.replace(/\bint4\b/g, "ivec4")
.replace(/\buint2\b/g, "uvec2")
.replace(/\buint3\b/g, "uvec3")
.replace(/\buint4\b/g, "uvec4")
.replace(/\buint32_t\b/g, "uint") .replace(/\buint32_t\b/g, "uint")
.replace(/\bANGLE_userUniforms\._uiResolution\b/g, "iResolution")
.replace(/\bANGLE_userUniforms\._uiTime\b/g, "iTime")
.replace(/\bANGLE_userUniforms\._uiMouse\b/g, "iMouse")
.replace(/\bANGLE_userUniforms\./g, "")
.replace(/ANGLE_texture\([^)]*\)/g, "vec4(0.0)")
.replace(/ANGLE_texelFetch\([^)]*\)/g, "vec4(0.0)")
.replace(/\bANGLE_mod\(/g, "mod(")
.replace(/\bANGLE_out\(([^)]+)\)/g, "$1")
.replace(/\bANGLE_swizzle_ref\(([^)]+)\)/g, "$1")
.replace(/\bANGLE_elem_ref\(([^)]+)\)/g, "$1")
.replace(/\bANGLE_addressof\(([^)]+)\)/g, "$1")
.replace(/\bANGLE_UserUniforms\s*&\s*ANGLE_userUniforms\s*,?/g, "")
.replace(/\bANGLE_TextureEnvs\s*&\s*ANGLE_textureEnvs\s*,?/g, "")
.replace(/\bANGLE_NonConstGlobals\s*&\s*ANGLE_nonConstGlobals\s*,?/g, "")
.replace(/\(\s*,/g, "(")
.replace(/,\s*,/g, ",")
.replace(/,\s*\)/g, ")")
.replace(/(\d+\.\d+|\d+)f\b/g, "$1")
.replace(/;\s*;/g, ";"); .replace(/;\s*;/g, ";");
const cleaned = [ s = s.replace(/void\s+_umainImage\s*\([^)]*\)/g, "void _umainImage(out vec4 _ufragColor, vec2 _ufragCoord)");
"void ANGLE_loopForwardProgress() {}",
section,
"void mainImage(out vec4 fragColor, in vec2 fragCoord) { _umainImage(fragColor, fragCoord); }",
].join("\n");
return cleaned; const blocks = extractFunctionBlocks(s).filter((b) =>
/(ANGLE_sc|ANGLE_sd|_u|mainImage|ANGLE_loopForwardProgress|_umainImage)/.test(b)
);
if (!blocks.length || !s.includes("_umainImage")) return "";
const hasMainImage = blocks.some((b) => /void\s+mainImage\s*\(/.test(b));
const withoutDupLoop = [];
let seenLoop = false;
for (const b of blocks) {
if (/void\s+ANGLE_loopForwardProgress\s*\(/.test(b)) {
if (seenLoop) continue;
seenLoop = true;
withoutDupLoop.push("void ANGLE_loopForwardProgress() {}");
continue;
}
withoutDupLoop.push(b);
}
if (!hasMainImage) {
withoutDupLoop.push("void mainImage(out vec4 fragColor, in vec2 fragCoord) { _umainImage(fragColor, fragCoord); }");
}
return withoutDupLoop.join("\n\n");
} }
function normalizeIncomingCode(code) { function normalizeIncomingCode(code) {
if (!code || typeof code !== "string") return { error: "code 不能为空", normalized: "" }; if (!code || typeof code !== "string") return { error: "code 不能为空", normalized: "" };
if (code.includes("metal::") || code.includes("[[function_constant")) { if (isAngleLike(code)) {
const converted = convertAngleMetalToGlsl(code); const converted = convertAngleLikeToGlsl(code);
if (!converted) { if (!converted) {
return { error: "自动解构失败:请检查粘贴内容是否完整。", normalized: "" }; return { error: "自动解构失败:请检查粘贴内容是否完整。", normalized: "" };
} }
@@ -97,7 +173,7 @@ async function autoNormalizeStoredShaders() {
let changed = false; let changed = false;
const next = shaders.map((item) => { const next = shaders.map((item) => {
const code = String(item.code || ""); const code = String(item.code || "");
if (code.includes("metal::") || code.includes("[[function_constant")) { if (isAngleLike(code) || code.includes("struct ANGLE_") || item.sourceFormat === "angle-metal-auto-converted") {
const { error, normalized } = normalizeIncomingCode(code); const { error, normalized } = normalizeIncomingCode(code);
if (!error && normalized) { if (!error && normalized) {
changed = true; changed = true;
@@ -116,7 +192,14 @@ async function autoNormalizeStoredShaders() {
app.get("/api/shaders", async (_req, res) => { app.get("/api/shaders", async (_req, res) => {
try { try {
const shaders = await readDb(); let shaders = await readDb();
// Runtime safeguard: always return normalized code for display layer.
shaders = shaders.map((item) => {
const { error, normalized } = normalizeIncomingCode(String(item.code || ""));
if (error || !normalized) return item;
if (normalized === item.code) return item;
return { ...item, code: normalized, sourceFormat: "angle-metal-auto-converted" };
});
res.json(shaders); res.json(shaders);
} catch { } catch {
res.status(500).json({ error: "读取失败" }); res.status(500).json({ error: "读取失败" });
@@ -143,7 +226,7 @@ app.post("/api/shaders", async (req, res) => {
views: Math.floor(3000 + Math.random() * 22000), views: Math.floor(3000 + Math.random() * 22000),
likes: Math.floor(40 + Math.random() * 700), likes: Math.floor(40 + Math.random() * 700),
createdAt: new Date().toISOString(), createdAt: new Date().toISOString(),
sourceFormat: code.includes("metal::") ? "angle-metal-auto-converted" : "glsl", sourceFormat: isAngleLike(code) ? "angle-metal-auto-converted" : "glsl",
}; };
shaders.unshift(item); shaders.unshift(item);
await writeDb(shaders); await writeDb(shaders);