-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
83 lines (69 loc) · 1.65 KB
/
index.js
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var path = require('path')
var fs = require('fs')
var loaderUtils = require('loader-utils')
var chunks = {}
var chunkPath = ""
module.exports = function(source) {
this.cacheable && this.cacheable()
var uid = new Object()
uid.callback = this.async()
uid.finalString = source
uid.queue = 0
uid.done = false
var options = this.getOptions() || {}
if(options.glsl && options.glsl.chunkPath){
chunkPath = options.glsl.chunkPath
}
var r = /\$[\w-.]+/gi
var match = source.match( r )
if(match){
for (var i = 0; i < match.length; i++) {
chunks[match[i]] = ""
}
} else {
onChunksLoaded.call(uid)
}
var keys = []
for (var key in chunks){
keys.push(key)
}
keys.sort()
keys.reverse()
uid.queue+=keys.length
for(var i=0; i < keys.length; i++){
loadChunk.call(this, keys[i], uid )
}
}
function loadChunk(key, uid){
var name = key.substr(1, key.length-1)
var headerPath = path.resolve(chunkPath+"/"+name+".glsl");
this.dependency(headerPath)
fs.readFile(headerPath, "utf-8", function(err, content) {
uid.queue--
chunks[key]=content
if(err) {
chunks[key]=""
console.error("Can't open the shader chunk "+name+":\n"+err.toString())
}
if(uid.queue==0){
onChunksLoaded.call(uid)
}
})
}
function onChunksLoaded(){
if(this.done){ return }
this.done = true
var keys = []
for (var key in chunks){
keys.push(key)
}
keys.sort()
keys.reverse()
for(var i=0; i < keys.length; i++){
var key = keys[i]
var re = new RegExp("(\\"+key+")", "gi")
this.finalString = this.finalString.replace(re,chunks[key])
}
this.finalString = "module.exports = " + JSON.stringify(this.finalString)
this.callback(null, this.finalString)
}