-
Notifications
You must be signed in to change notification settings - Fork 0
/
testOfObj.js
430 lines (395 loc) · 13.8 KB
/
testOfObj.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
const startTime = Number(new Date());
const WIDTH = 1200;
const HEIGHT = 1200;
const { JSDOM } = require("jsdom");
const dom = new JSDOM('<!doctype html><html><head></head><body></body></html>', {
resources: 'usable'
});
const window = dom.window;
const document = window.document;
const canvas = document.createElement('canvas');
const fs = require('fs');
const THREE = require('three');
const OBJLoader = require('./src/common/loaders/OBJLoader_node');
const MTLLoader = require('./src/common/loaders/MTLLoader_node');
const PNG = require('pngjs').PNG;
const gl = require('gl')(WIDTH, HEIGHT, {
preserveDrawingBuffer: true,
antialias: true,
});
const png = new PNG({ width: WIDTH, height: HEIGHT });
global.document = document;
global.window = window;
const lightIntensity = {
aroundPoint: 0.2,
ambient: 1,
autoPoint: 4,
}
const paramsCache = {
gl,
canvas,
png,
WIDTH,
HEIGHT,
// 合成图片输出地址
outPath: './src/common/img/output/out-zb.png',
// 相机视角
copyPosition: new THREE.Vector3(-9, 27, 40),
copyLookAt: new THREE.Vector3(0, 0, 0),
modelPath: './src/static/models/zb2.obj',
mtlPath: './src/static/models/zb2.mtl',
colorMapPath: './src/static/imgs/map_green.png',
normalMapPath: './src/static/imgs/map_normal.png',
backUrls: [
'HDR_r.jpg', 'HDR_l.jpg',
'HDR_u.jpg', 'HDR_d.jpg',
'HDR_f.jpg', 'HDR_b.jpg'
],
autoPointIntensity: lightIntensity.autoPoint,
lights: [
{
type: 'AmbientLight',
color: '#fff',
intensity: lightIntensity.ambient,
},
{
type: 'PointLight',
color: '#fff',
intensity: lightIntensity.aroundPoint,
position: [0, 200, 0]
},
{
type: 'PointLight',
color: '#fff',
intensity: lightIntensity.aroundPoint,
position: [0, -200, 0]
},
{
type: 'PointLight',
color: '#fff',
intensity: lightIntensity.aroundPoint,
position: [200, 0, 0]
},
{
type: 'PointLight',
color: '#fff',
intensity: lightIntensity.aroundPoint,
position: [-200, 0, 0]
},
{
type: 'PointLight',
color: '#fff',
intensity: lightIntensity.aroundPoint,
position: [0, 0, 200]
},
{
type: 'PointLight',
color: '#fff',
intensity: lightIntensity.aroundPoint,
position: [0, 0, -200]
},
],
}
/**
* 服务端测试脚本
*/
class renderObject {
constructor(options) {
this.defaultOpt = {}
this.options = {}
Object.assign(this.options, this.defaultOptions, options)
this.componentCache = {
renderer: null,
scene: null,
camera: null,
model: null,
colorMap: null,
normalMap: null,
envMap: null,
autoPointLight: null,
}
}
/**
* 开始绘制
*/
draw() {
// 同步任务
this.initRenderer()
this.initScene()
this.initCamera()
this.initLights()
// 异步任务
Promise.all([
this.loadColorMap(),
this.loadNormalMap(),
this.loadModel(),
]).then(
() => {
this.initModel()
}
)
}
/**
* 渲染器构建
*/
initRenderer() {
const { options, componentCache } = this
const { canvas, gl } = options
componentCache.renderer = new THREE.WebGLRenderer({
canvas: canvas,
preserveDrawingBuffer: true,
context: gl,
});
}
/**
* 场景构建
*/
initScene() {
const { componentCache } = this
componentCache.scene = new THREE.Scene();
}
/**
* 相机构建
*/
initCamera() {
const { options: { WIDTH, HEIGHT, copyPosition, copyLookAt }, componentCache } = this
const camera = new THREE.PerspectiveCamera(45, WIDTH / HEIGHT, 0.1, 10000);
camera.position.copy(copyPosition);
camera.lookAt(copyLookAt);
camera.updateMatrixWorld()
componentCache.scene.add(camera)
componentCache.camera = camera
}
/**
* 灯光构建
*/
initLights() {
const {
componentCache: { scene, camera },
options: { lights, autoPointIntensity }
} = this
//增加一个相机位置的点光源
const autoPointLight = new THREE.PointLight( '#fff', autoPointIntensity )
autoPointLight.position.copy(camera.position)
scene.add(autoPointLight)
lights.forEach(ele => {
let light = null
switch(ele.type) {
case 'PointLight':
light = new THREE.PointLight( ele.color, ele.intensity )
light.position.set(ele.position[0], ele.position[1], ele.position[2])
break;
case 'RectAreaLight':
light = new THREE.DirectionalLight( ele.color, ele.intensity, ele.width, ele.height )
light.position.set(ele.position[0], ele.position[1], ele.position[2])
light.lookAt(ele.lookAt[0], ele.lookAt[1], ele.lookAt[2])
break;
case 'AmbientLight':
light = new THREE.AmbientLight( ele.color, ele.intensity )
break;
}
scene.add(light)
});
}
/**
* 加载模型和材质
*/
async loadModel() {
const {
options: { modelPath, mtlPath },
componentCache,
} = this
const manager = new THREE.LoadingManager();
const mtlLoaderCache = new MTLLoader( manager )
const OBJLoaderCache = new OBJLoader( manager )
const materials = await mtlLoaderCache.load( mtlPath )
materials.preload();
OBJLoaderCache.setMaterials( materials )
componentCache.model = await OBJLoaderCache.load( modelPath )
}
/**
* 加载颜色纹理
*/
async loadColorMap(...arg){
const { options, componentCache, _loadTexture } = this
try {
const texture = await _loadTexture(options.colorMapPath, ...arg);
texture.magFilter = THREE.LinearFilter
texture.minFilter = THREE.LinearMipMapLinearFilter
// texture.repeat.set( 5, 5 );
componentCache.colorMap = texture;
}
catch (err) {
console.log('加载颜色纹理失败:', err);
}
}
/**
* 加载法线纹理
*/
async loadNormalMap(...arg){
const { options, componentCache, _loadTexture } = this
try {
const texture = await _loadTexture(options.normalMapPath, ...arg);
texture.magFilter = THREE.LinearFilter
texture.minFilter = THREE.LinearMipMapLinearFilter
// texture.repeat.set( 5, 5 );
componentCache.normalMap = texture;
}
catch (err) {
console.log('加载颜色纹理失败:', err);
}
}
/**
* 纹理加载器
* @param {String} path 图片地址
* @param {Number} width 纹理宽度,默认为1024
* @param {Number} height 纹理高度,默认为1024
*/
_loadTexture(path, format = THREE.RGBAFormat) {
// return new Promise((resolve, reject) => {
// fs.readFile(path, (err, data) => {
// if (err) {
// reject(err)
// }
// const texture = new THREE.DataTexture(data, width, height, format);
// texture.generateMipmaps = true;
// texture.flipY = true;
// texture.unpackAlignment = 4;
// texture.needsUpdate = true;
// texture.wrapS = texture.wrapT = THREE.RepeatWrapping
// console.log(`load texture: ${path}`)
// resolve(texture)
// })
// })
return new Promise((resolve, reject) => {
const pngCache = new PNG();
fs.createReadStream(path)
.pipe(pngCache)
.on('parsed', () => {
const { width, height, data } = pngCache
const texture = new THREE.DataTexture(data, width, height, format);
texture.generateMipmaps = true;
texture.flipY = true;
texture.unpackAlignment = 4;
texture.needsUpdate = true;
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
console.log(`loaded texture: ${path}`)
resolve(texture)
})
.on('error', (error) => {
reject(error)
})
})
}
/**
* 组装模型
*/
initModel() {
const {
componentCache: { model, colorMap, cubeTexture, normalMap, renderer, camera, scene },
options: {
WIDTH,
HEIGHT,
}
} = this
model.traverse((child) => {
if (child instanceof THREE.Mesh) {
switch(child.name) {
case '发光球':
// child.material.emissiveMap = HDRMap;
child.material.emissive = new THREE.Color('#fff');
child.material.envMap = cubeTexture;
break;
case '金属球':
// child.material.emissive = new THREE.Color('rgba(189, 148, 68, 1)');
child.material.envMap = cubeTexture
// 高度程度, 默认30
// child.material.shininess = 15
// 粗糙度,
// child.material.roughness = 1
break;
case '布料':
// 颜色贴图和漫反射,纯色背景通过mtl解析生成
child.material.map = colorMap
// child.material.color = new THREE.Color('#eee')
// 粗糙度
child.material.roughness = 0.95
// 非金属程度
child.material.metalness = 1
// 使用蒙皮效果
child.material.skinning = true
// 把环境贴图加进去
// child.material.envMap = cubeTexture
// child.material.envMapIntensity = 0.05
// 法线贴图
child.material.normalMap = normalMap;
child.material.normalScale = new THREE.Vector2(0.2, 0.2);
// 将发光颜色设置成自身颜色,自身来着mtl的Kd
// child.material.emissive = child.material.color
// 将发光贴图设置为颜色贴图
// child.material.emissiveMap = textureMap
// 环境贴图和颜色贴图的混合方式设定, 设置为mix模式
// child.material.combine = THREE.MixOperation
// 高光贴图属性, 只针对Phong材质
// child.material.specular = new THREE.Color('#000')
// 高光程度, 默认30, (暂时不影响渲染效果)
// child.material.shininess = 3
// child.material.reflectivity = 0.9
// child.material.refractionRatio = 0.8
break;
default :
child.material.map = colorMap
}
// child.material.side = THREE.DoubleSide;
}
})
console.log('start render')
// Let's create a render target object where we'll be rendering
const rtTexture = new THREE.WebGLRenderTarget(
WIDTH, HEIGHT, {
minFilter: THREE.LinearFilter,
magFilter: THREE.NearestFilter,
format: THREE.RGBAFormat
})
scene.add( model );
renderer.setRenderTarget(rtTexture);
renderer.render(scene, camera);
this.exportImg()
}
/**
* 导出图片
*/
exportImg(){
const {
componentCache: { renderer, },
options: { WIDTH, HEIGHT, outPath, gl, png, }
} = this
const newGl = renderer.getContext()
const pixels = new Uint8Array(4 * WIDTH * HEIGHT)
newGl.readPixels(0, 0, WIDTH, HEIGHT, gl.RGBA, gl.UNSIGNED_BYTE, pixels)
for(let j = 0; j < HEIGHT; j++){
for(let i = 0; i < WIDTH; i++){
const k = j * WIDTH + i
const r = pixels[4*k]
const g = pixels[4*k + 1]
const b = pixels[4*k + 2]
const a = pixels[4*k + 3]
const m = (HEIGHT - j + 1) * WIDTH + i
png.data[4*m] = r
png.data[4*m + 1] = g
png.data[4*m + 2] = b
png.data[4*m + 3] = a
}
}
const stream = fs.createWriteStream(outPath)
png.pack().pipe(stream)
stream.on('close', () => {
const endTime = Number(new Date());
console.log(`mage written: ${ outPath }`)
console.log(`The process execute: ${endTime - startTime}ms`)
}
)
}
}
const renderInit = new renderObject(paramsCache)
renderInit.draw()