-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathglr.js
133 lines (127 loc) · 2.87 KB
/
glr.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
const schemas = {
"scene": {
"nodes": ["node"]
},
"node": {
"camera": "",
"children": ["node"],
"skin": "",
"mesh": ""
},
"skin": {
"inverseBindMatrices": "accessor",
"skeleton": "node",
"joints": ["node"]
},
"mesh": {
"primitives": [{
"attributes": {
"*": "accessor"
},
"indices": "accessor",
"material": "",
"targets": {
"*": "accessor"
}
}]
},
"accessor": {
"bufferView": ""
},
"material": {
"pbrMetallicRoughness": {
"baseColorTexture": {
"index": "texture"
},
"metallicRoughnessTexture": {
"index": "texture"
}
},
"emissiveTexture": {
"index": "texture"
}
},
"bufferView": {
"buffer": ""
},
"texture": {
"sampler": "",
"source": "image"
},
"image": {
"bufferView": ""
},
"animation": {
"channels": [{
"sampler": ""
}],
"samplers": [{
"input": "accessor",
"output": "accessor"
}]
}
}
function plural(word) {
if (word === 'mesh') return word + 'es'
return word + 's'
}
function push_unique(arr, elt) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === elt) return i
}
return arr.push(elt) - 1
}
function glr2gltf(contents) {
let model = JSON.parse(contents)
let named = model.named
delete model.named
function lift(obj, type) {
if (typeof type === 'string' || type instanceof String) {
const types = plural(type)
if (!model.hasOwnProperty(types)) model[types] = []
if (obj.hasOwnProperty('children')) {
if (obj.children.length == 0) {
delete obj.children
} else if (obj.children.length == 1) {
let child = obj.children[0]
delete obj.children
obj = Object.assign(child, obj)
}
}
if (schemas.hasOwnProperty(type)) lift(obj, schemas[type])
if (type === 'node') {
return model[types].push(JSON.stringify(obj)) - 1
}
return push_unique(model[types], JSON.stringify(obj))
} else if (Array.isArray(type)) {
for (let i = 0; i < obj.length; i++) {
obj[i] = lift(obj[i], type[0])
}
return obj
} else {
for (key in obj) {
if (type.hasOwnProperty(key)) {
let childType = type[key]
if (childType === '') childType = key
obj[key] = lift(obj[key], childType)
} else if (type.hasOwnProperty('*')) {
let childType = type['*']
obj[key] = lift(obj[key], childType)
}
}
return obj
}
}
model.scene = lift(model.scene, 'scene')
for (key in model) {
if (Array.isArray(model[key])) {
model[key] = model[key].map(s => {
let obj = JSON.parse(s)
if (named[obj.name]) obj = Object.assign(obj, named[obj.name])
return obj
})
}
}
return model
}
exports.glr2gltf = glr2gltf