-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathloadShader.js
More file actions
44 lines (38 loc) · 1.02 KB
/
loadShader.js
File metadata and controls
44 lines (38 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const loadShader = async (path) => {
let shaderCode
try {
const response = await fetch(path)
if (!response.ok) throw new Error(`Failed to fetch ${path}`)
shaderCode = await response.text()
shaderCode = await processIncludes(shaderCode)
return shaderCode
} catch (error) {
console.error(error)
throw error
}
}
const processIncludes = async (shaderCode) => {
const includeRegex = /#include "(.+)"/g
const includePaths = []
let match
while ((match = includeRegex.exec(shaderCode)) !== null) {
includePaths.push(match[1])
}
const includes = await Promise.all(
includePaths.map(async (path) => {
try {
const response = await fetch(path)
if (!response.ok) throw new Error(`Failed to fetch ${path}`)
return await response.text()
} catch (error) {
console.error(`Failed to load included file: ${path}`)
throw error
}
})
)
includePaths.forEach((path, index) => {
shaderCode = shaderCode.replace(`#include "${path}"`, includes[index])
})
return shaderCode
}
export default loadShader