Skip to content

Commit

Permalink
Merge pull request #68 from jslauthor/fix-infinite-regex
Browse files Browse the repository at this point in the history
Fix infinite regex recursion when parsing heavily nested shaders
  • Loading branch information
FarazzShaikh authored Nov 21, 2024
2 parents 7b32ca1 + 7c22f8d commit e5812b0
Showing 1 changed file with 29 additions and 9 deletions.
38 changes: 29 additions & 9 deletions package/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,15 +158,35 @@ export default class CustomShaderMaterial<

// Prepare the main body and beforeMain
if (newShader) {
const mainBodyRegex =
/void\s+main\s*\(\s*\)[^{]*{((?:[^{}]+|{(?:[^{}]+|{(?:[^{}]+|{(?:[^{}]+|{[^{}]*})*})*})*})*})/gm;
const mainBodyMatches = newShader.matchAll(mainBodyRegex);
mainBody = mainBodyMatches.next().value?.[1];
if (mainBody) mainBody = mainBody.slice(0, -1);

const mainDefRegex = /void\s+main\s*\(\s*\)\s*{/gm;
const mainIndex = newShader.search(mainDefRegex);
beforeMain = newShader.slice(0, mainIndex);
// Simpler approach to extract main function body
const mainStartIndex = newShader.search(/void\s+main\s*\(\s*\)\s*{/);
if (mainStartIndex !== -1) {
// Get everything before main function
beforeMain = newShader.slice(0, mainStartIndex);

// Find the matching closing brace using brace counting
let braceCount = 0;
let mainEndIndex = -1;

for (let i = mainStartIndex; i < newShader.length; i++) {
if (newShader[i] === "{") braceCount++;
if (newShader[i] === "}") {
braceCount--;
if (braceCount === 0) {
mainEndIndex = i;
break;
}
}
}

if (mainEndIndex !== -1) {
// Extract main body without the outer braces
const fullMain = newShader.slice(mainStartIndex, mainEndIndex + 1);
mainBody = fullMain.slice(fullMain.indexOf("{") + 1, -1);
}
} else {
beforeMain = newShader;
}
}

// Set csm_UnlitFac if csm_FragColor is used to preserve
Expand Down

0 comments on commit e5812b0

Please sign in to comment.