| 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843 |
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
|
/**
* Helpers for creating a common 3d application.
* @namespace clay.application
*/
// TODO createCompositor, ambientCubemap, ambientSH.
// TODO mobile. scroll events.
// TODO Dispose test. geoCache test.
// TODO fitModel, normal generation.
import Renderer from './Renderer';
import Scene from './Scene';
import Timeline from './animation/Timeline';
import CubeGeo from './geometry/Cube';
import SphereGeo from './geometry/Sphere';
import PlaneGeo from './geometry/Plane';
import CylinderGeo from './geometry/Cylinder';
import ConeGeo from './geometry/Cone';
import Texture2D from './Texture2D';
import Texture from './Texture';
import shaderLibrary from './shader/library';
import Mesh from './Mesh';
import Material from './Material';
import PerspectiveCamera from './camera/Perspective';
import OrthographicCamera from './camera/Orthographic';
import Vector3 from './math/Vector3';
import GLTFLoader from './loader/GLTF';
import Node from './Node';
import DirectionalLight from './light/Directional';
import PointLight from './light/Point';
import SpotLight from './light/Spot';
import AmbientLight from './light/Ambient';
import AmbientCubemapLight from './light/AmbientCubemap';
import AmbientSHLight from './light/AmbientSH';
import ShadowMapPass from './prePass/ShadowMap';
import RayPicking from './picking/RayPicking';
import LRUCache from './core/LRU';
import util from './core/util';
import colorUtil from './core/color';
var parseColor = colorUtil.parseToFloat;
import './shader/builtin';
/**
* @typedef {string|HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} ImageLike
*/
/**
* @typedef {string|Array.<number>} Color
*/
/**
* @constructor
* @alias clay.application.App3D
* @param {HTMLDomElement|string} dom Container dom element or a selector string that can be used in `querySelector`
* @param {Object} appNS
* @param {Function} init Initialization callback that will be called when initing app.
* @param {Function} loop Loop callback that will be called each frame.
* @param {number} [width] Container width.
* @param {number} [height] Container height.
* @param {number} [devicePixelRatio]
* @param {Object} [graphic] Graphic configuration including shadow, postEffect
* @param {boolean} [graphic.shadow=false] If enable shadow
* @param {boolean} [event=false] If enable mouse/touch event. It will slow down the system if geometries are complex.
*/
function App3D(dom, appNS) {
appNS = appNS || {};
appNS.graphic = appNS.graphic || {};
if (typeof dom === 'string') {
dom = document.querySelector(dom);
}
if (!dom) { throw new Error('Invalid dom'); }
var isDomCanvas = dom.nodeName.toUpperCase() === 'CANVAS';
var rendererOpts = {};
isDomCanvas && (rendererOpts.canvas = dom);
appNS.devicePixelRatio && (rendererOpts.devicePixelRatio = appNS.devicePixelRatio);
var gRenderer = new Renderer(rendererOpts);
var gWidth = appNS.width || dom.clientWidth;
var gHeight = appNS.height || dom.clientHeight;
var gScene = new Scene();
var gTimeline = new Timeline();
var gShadowPass = appNS.graphic.shadow && new ShadowMapPass();
var gRayPicking = appNS.event && new RayPicking({
scene: gScene,
renderer: gRenderer
});
!isDomCanvas && dom.appendChild(gRenderer.canvas);
gRenderer.resize(gWidth, gHeight);
var gFrameTime = 0;
var gElapsedTime = 0;
gTimeline.start();
Object.defineProperties(this, {
/**
* Container dom element
* @name clay.application.App3D#container
* @type {HTMLDomElement}
*/
container: { get: function () { return dom; } },
/**
* @name clay.application.App3D#renderer
* @type {clay.Renderer}
*/
renderer: { get: function () { return gRenderer; }},
/**
* @name clay.application.App3D#scene
* @type {clay.Renderer}
*/
scene: { get: function () { return gScene; }},
/**
* @name clay.application.App3D#timeline
* @type {clay.Renderer}
*/
timeline: { get: function () { return gTimeline; }},
/**
* Time elapsed since last frame. Can be used in loop to calculate the movement.
* @name clay.application.App3D#frameTime
* @type {number}
*/
frameTime: { get: function () { return gFrameTime; }},
/**
* Time elapsed since application created.
* @name clay.application.App3D#elapsedTime
* @type {number}
*/
elapsedTime: { get: function () { return gElapsedTime; }}
});
/**
* Resize the application. Will use the container clientWidth/clientHeight if width/height in parameters are not given.
* @method
* @memberOf {clay.application.App3D}
* @param {number} [width]
* @param {number} [height]
*/
this.resize = function (width, height) {
gWidth = width || appNS.width || dom.clientWidth;
gHeight = height || dom.height || dom.clientHeight;
gRenderer.resize(gWidth, gHeight);
};
/**
* Dispose the application
* @method
*/
this.dispose = function () {
if (appNS.dispose) {
appNS.dispose(this);
}
gTimeline.stop();
gRenderer.disposeScene(gScene);
dom.innerHTML = '';
['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove'].forEach(function (eveType) {
this[makeHandlerName(eveType)] && dom.removeEventListener(makeHandlerName(eveType));
});
};
gRayPicking && this._initMouseEvents(gRayPicking);
this._geoCache = new LRUCache(20);
// Do init the application.
appNS.init && appNS.init(this);
// Use the inited camera.
gRayPicking && (gRayPicking.camera = gScene.getMainCamera());
var gTexturesList = {};
var gGeometriesList = {};
if (appNS.loop) {
gTimeline.on('frame', function (frameTime) {
gFrameTime = frameTime;
gElapsedTime += frameTime;
appNS.loop(this);
gScene.update();
gRayPicking && (gRayPicking.camera = gScene.getMainCamera());
// Render shadow pass
gShadowPass && gShadowPass.render(gRenderer, gScene, null, true);
this._doRender(gRenderer, gScene, true);
// Mark all resources unused;
markUsed(gTexturesList);
markUsed(gGeometriesList);
// Collect resources used in this frame.
var newTexturesList = [];
var newGeometriesList = [];
collectResources(gScene, newTexturesList, newGeometriesList);
// Dispose those unsed resources.
checkAndDispose(gRenderer, gTexturesList);
checkAndDispose(gRenderer, gGeometriesList);
gTexturesList = newTexturesList;
gGeometriesList = newGeometriesList;
}, this);
}
else {
console.warn('Miss loop method.');
}
}
function isImageLikeElement(val) {
return val instanceof Image
|| val instanceof HTMLCanvasElement
|| val instanceof HTMLVideoElement;
}
function makeHandlerName(eveType) {
return '_' + eveType + 'Handler';
}
function packageEvent(eventType, pickResult, offsetX, offsetY) {
var event = util.clone(pickResult);
event.type = eventType;
event.offsetX = offsetX;
event.offsetY = offsetY;
return event;
}
function bubblingEvent(target, event) {
while (target && !event.cancelBubble) {
target.trigger(event.type, event);
target = target.getParent();
}
}
App3D.prototype._initMouseEvents = function (rayPicking) {
var dom = this.container;
var oldTarget = null;
['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove'].forEach(function (eveType) {
dom.addEventListener(eveType, this[makeHandlerName(eveType)] = function (e) {
var box = dom.getBoundingClientRect();
var offsetX = e.clientX - box.left;
var offsetY = e.clientY - box.top;
var pickResult = rayPicking.pick(offsetX, offsetY);
if (pickResult) {
// Just ignore silent element.
if (pickResult.target.silent) {
return;
}
if (eveType === 'mousemove') {
var targetChanged = pickResult.target !== oldTarget;
if (targetChanged) {
oldTarget && bubblingEvent(oldTarget, packageEvent('mouseout', {
target: oldTarget
}, offsetX, offsetY));
}
bubblingEvent(pickResult.target, packageEvent('mousemove', pickResult, offsetX, offsetY));
if (targetChanged) {
bubblingEvent(pickResult.target, packageEvent('mouseover', pickResult, offsetX, offsetY));
}
}
else {
bubblingEvent(pickResult.target, packageEvent(eveType, pickResult, offsetX, offsetY));
}
oldTarget = pickResult.target;
}
else if (oldTarget) {
bubblingEvent(oldTarget, packageEvent('mouseout', {
target: oldTarget
}, offsetX, offsetY));
oldTarget = null;
}
});
}, this);
};
App3D.prototype._doRender = function (renderer, scene) {
var camera = scene.getMainCamera();
camera.aspect = renderer.getViewportAspect();
renderer.render(scene);
};
function markUsed(resourceList) {
for (var i = 0; i < resourceList.length; i++) {
resourceList[i].__used__ = 0;
}
}
function checkAndDispose(renderer, resourceList) {
for (var i = 0; i < resourceList.length; i++) {
if (!resourceList[i].__used__) {
resourceList[i].dispose(renderer);
}
}
}
function updateUsed(resource, list) {
list.push(resource);
resource.__used__ = resource.__used__ || 0;
resource.__used__++;
}
function collectResources(scene, textureResourceList, geometryResourceList) {
function trackQueue(queue) {
for (var i = 0; i < queue.length; i++) {
var renderable = queue[i];
var geometry = renderable.geometry;
var material = renderable.material;
updateUsed(geometry, geometryResourceList);
for (var name in material.uniforms) {
var val = material.uniforms[name].value;
if (val instanceof Texture) {
updateUsed(val, textureResourceList);
}
else if (val instanceof Array) {
for (var k = 0; k < val.length; k++) {
if (val[k] instanceof Texture) {
updateUsed(val[k], textureResourceList);
}
}
}
}
}
}
trackQueue(scene.opaqueList);
trackQueue(scene.transparentList);
for (var k = 0; k < scene.lights.length; k++) {
// Track AmbientCubemap
if (scene.lights[k].cubemap) {
updateUsed(scene.lights[k].cubemap, textureResourceList);
}
}
}
/**
* Load a texture from image or string.
* @param {ImageLike} img
* @param {Object} [opts] Texture options.
* @param {boolean} [opts.flipY=true] If flipY. See {@link clay.Texture.flipY}
* @param {number} [opts.anisotropic] Anisotropic filtering. See {@link clay.Texture.anisotropic}
* @param {number} [opts.wrapS=clay.Texture.REPEAT] See {@link clay.Texture.wrapS}
* @param {number} [opts.wrapT=clay.Texture.REPEAT] See {@link clay.Texture.wrapT}
* @param {number} [opts.minFilter=clay.Texture.LINEAR_MIPMAP_LINEAR] See {@link clay.Texture.minFilter}
* @param {number} [opts.magFilter=clay.Texture.LINEAR] See {@link clay.Texture.magFilter}
* @return {Promise}
* @example
* app.loadTexture('diffuseMap.jpg')
* .then(function (texture) {
* material.set('diffuseMap', texture);
* });
*/
App3D.prototype.loadTexture = function (urlOrImg, opts) {
var self = this;
// TODO Promise ?
return new Promise(function (resolve, reject) {
var texture = self.loadTextureSync(urlOrImg, opts);
if (!texture.isRenderable()) {
texture.success(function () {
resolve(texture);
});
texture.error(function () {
reject();
});
}
else {
resolve(texture);
}
});
};
/**
* Create a texture from image or string synchronously. Texture can be use directly and don't have to wait for it's loaded.
* @param {ImageLike} img
* @param {Object} [opts] Texture options.
* @param {boolean} [opts.flipY=true] If flipY. See {@link clay.Texture.flipY}
* @param {number} [opts.anisotropic] Anisotropic filtering. See {@link clay.Texture.anisotropic}
* @param {number} [opts.wrapS=clay.Texture.REPEAT] See {@link clay.Texture.wrapS}
* @param {number} [opts.wrapT=clay.Texture.REPEAT] See {@link clay.Texture.wrapT}
* @param {number} [opts.minFilter=clay.Texture.LINEAR_MIPMAP_LINEAR] See {@link clay.Texture.minFilter}
* @param {number} [opts.magFilter=clay.Texture.LINEAR] See {@link clay.Texture.magFilter}
* @return {Promise}
* @example
* var texture = app.loadTexture('diffuseMap.jpg', {
* anisotropic: 8,
* flipY: false
* });
* material.set('diffuseMap', texture);
*/
App3D.prototype.loadTextureSync = function (urlOrImg, opts) {
var texture = new Texture2D(opts);
if (typeof urlOrImg === 'string') {
texture.load(urlOrImg);
}
else if (isImageLikeElement(urlOrImg)) {
texture.image = urlOrImg;
texture.dynamic = urlOrImg instanceof HTMLVideoElement;
}
return texture;
};
/**
* Create a material.
* @param {Object} materialConfig. materialConfig contains `shader`, `transparent` and uniforms that used in corresponding uniforms.
* Uniforms can be `color`, `alpha` `diffuseMap` etc.
* @param {string} [shader='clay.standardMR'] Default to be standard shader with metalness and roughness workflow.
* @param {boolean} [transparent=false] If material is transparent.
* @return {clay.Material}
*/
App3D.prototype.createMaterial = function (matConfig) {
matConfig = matConfig || {};
matConfig.shader = matConfig.shader || 'clay.standardMR';
var material = new Material({
shader: shaderLibrary.get(matConfig.shader)
});
function makeTextureSetter(key) {
return function (texture) {
material.setUniform(key, texture);
};
}
for (var key in matConfig) {
if (material.uniforms[key]) {
var val = matConfig[key];
if (material.uniforms[key].type === 't' || isImageLikeElement(val)) {
// Try to load a texture.
this.loadTexture(val).then(makeTextureSetter(key));
}
else {
material.setUniform(key, val);
}
}
}
if (matConfig.transparent) {
matConfig.depthMask = false;
matConfig.transparent = true;
}
return material;
};
/**
* Create a cube mesh and add it to the scene or the given parent node.
* @method
* @param {Array.<number>|number} [subdivision=1] Subdivision of cube.
* Can be a number to represent both width, height and depth dimensions. Or an array to represent them respectively.
* @param {Object|clay.Material} [material]
* @param {clay.Node} [parentNode] Parent node to append. Default to be scene.
* @return {clay.Mesh}
* @example
* // Create a white cube.
* app.createCube()
*/
App3D.prototype.createCube = function (subdiv, material, parentNode) {
if (subdiv == null) {
subdiv = 1;
}
if (typeof subdiv === 'number') {
subdiv = [subdiv, subdiv, subdiv];
}
var geoKey = 'cube-' + subdiv.join('-');
var cube = this._geoCache.get(geoKey);
if (!cube) {
cube = new CubeGeo({
widthSegments: subdiv[0],
heightSegments: subdiv[1],
depthSegments: subdiv[2]
});
this._geoCache.put(geoKey, cube);
}
return this.createMesh(cube, material, parentNode);
};
/**
* Create a cube mesh that camera is inside the cube.
* @method
* @param {Array.<number>|number} [subdivision=1] Subdivision of cube.
* Can be a number to represent both width, height and depth dimensions. Or an array to represent them respectively.
* @param {Object|clay.Material} [material]
* @param {clay.Node} [parentNode] Parent node to append. Default to be scene.
* @return {clay.Mesh}
* @example
* // Create a white cube inside.
* app.createCubeInside()
*/
App3D.prototype.createCubeInside = function (subdiv, material, parentNode) {
if (subdiv == null) {
subdiv = 1;
}
if (typeof subdiv === 'number') {
subdiv = [subdiv, subdiv, subdiv];
}
var geoKey = 'cubeInside-' + subdiv.join('-');
var cube = this._geoCache.get(geoKey);
if (!cube) {
cube = new CubeGeo({
inside: true,
widthSegments: subdiv[0],
heightSegments: subdiv[1],
depthSegments: subdiv[2]
});
this._geoCache.put(geoKey, cube);
}
return this.createMesh(cube, material, parentNode);
};
/**
* Create a sphere mesh and add it to the scene or the given parent node.
* @method
* @param {number} [subdivision=20] Subdivision of sphere.
* @param {Object|clay.Material} [material]
* @param {clay.Node} [parentNode] Parent node to append. Default to be scene.
* @return {clay.Mesh}
* @example
* // Create a semi-transparent sphere.
* app.createSphere(20, {
* color: [0, 0, 1],
* transparent: true,
* alpha: 0.5
* })
*/
App3D.prototype.createSphere = function (subdivision, material, parentNode) {
if (subdivision == null) {
subdivision = 20;
}
var geoKey = 'sphere-' + subdivision;
var sphere = this._geoCache.get(geoKey);
if (!sphere) {
sphere = new SphereGeo({
widthSegments: subdivision * 2,
heightSegments: subdivision
});
this._geoCache.put(geoKey, sphere);
}
return this.createMesh(sphere, material, parentNode);
};
/**
* Create a plane mesh and add it to the scene or the given parent node.
* @method
* @param {Array.<number>|number} [subdivision=1] Subdivision of plane.
* Can be a number to represent both width and height dimensions. Or an array to represent them respectively.
* @param {Object|clay.Material} [material]
* @param {clay.Node} [parentNode] Parent node to append. Default to be scene.
* @return {clay.Mesh}
* @example
* // Create a red color plane.
* app.createPlane(1, {
* color: [1, 0, 0]
* })
*/
App3D.prototype.createPlane = function (subdiv, material, parentNode) {
if (subdiv == null) {
subdiv = 1;
}
if (typeof subdiv === 'number') {
subdiv = [subdiv, subdiv];
}
var geoKey = 'plane-' + subdiv.join('-');
var planeGeo = this._geoCache.get(geoKey);
if (!planeGeo) {
planeGeo = new PlaneGeo({
widthSegments: subdiv[0],
heightSegments: subdiv[1]
});
this._geoCache.put(geoKey, planeGeo);
}
return this.createMesh(planeGeo, material, parentNode);
};
/**
* Create a general mesh with given geometry instance and material config.
* @param {*} geometry
*/
App3D.prototype.createMesh = function (geometry, mat, parentNode) {
var mesh = new Mesh({
geometry: geometry,
material: mat instanceof Material ? mat : this.createMaterial(mat)
});
parentNode = parentNode || this.scene;
parentNode.add(mesh);
return mesh;
};
/**
* Create a perspective or orthographic camera and add it to the scene.
* @param {Array.<number>|clay.math.Vector3} position
* @param {Array.<number>|clay.math.Vector3} target
* @param {string} [type="perspective"] Can be 'perspective' or 'orthographic'(in short 'ortho')
* @return {clay.camera.Perspective}
*/
App3D.prototype.createCamera = function (position, target, type) {
var CameraCtor;
if (type === 'ortho' || type === 'orthographic') {
CameraCtor = OrthographicCamera;
}
else {
if (type && type !== 'perspective') {
console.error('Unkown camera type ' + type + '. Use default perspective camera');
}
CameraCtor = PerspectiveCamera;
}
var camera = new CameraCtor();
if (position instanceof Vector3) {
camera.position.copy(position);
}
else if (position instanceof Array) {
camera.position.setArray(position);
}
if (target instanceof Array) {
target = new Vector3(target[0], target[1], target[2]);
}
if (target instanceof Vector3) {
camera.lookAt(target);
}
this.scene.add(camera);
return camera;
};
/**
* Create a directional light and add it to the scene.
* @param {Array.<number>|clay.math.Vector3} dir A Vector3 or array to represent the direction.
* @param {Color} [color='#fff'] Color of directional light, default to be white.
* @param {number} [intensity] Intensity of directional light, default to be 1.
*
* @example
* app.createDirectionalLight([-1, -1, -1], '#fff', 2);
*/
App3D.prototype.createDirectionalLight = function (dir, color, intensity) {
var light = new DirectionalLight();
if (dir instanceof Vector3) {
dir = dir.array;
}
light.position.setArray(dir).negate();
light.lookAt(Vector3.ZERO);
if (typeof color === 'string') {
color = parseColor(color);
}
color != null && (light.color = color);
intensity != null && (light.intensity = intensity);
this.scene.add(light);
return light;
};
/**
* Create a spot light and add it to the scene.
* @param {Array.<number>|clay.math.Vector3} position Position of the spot light.
* @param {Array.<number>|clay.math.Vector3} [target] Target position where spot light points to.
* @param {number} [range=20] Falloff range of spot light. Default to be 20.
* @param {Color} [color='#fff'] Color of spot light, default to be white.
* @param {number} [intensity=1] Intensity of spot light, default to be 1.
* @param {number} [umbraAngle=30] Umbra angle of spot light. Default to be 30 degree from the middle line.
* @param {number} [penumbraAngle=45] Penumbra angle of spot light. Default to be 45 degree from the middle line.
*
* @example
* app.createSpotLight([5, 5, 5], [0, 0, 0], 20, #900);
*/
App3D.prototype.createSpotLight = function (position, target, range, color, intensity, umbraAngle, penumbraAngle) {
var light = new SpotLight();
light.position.setArray(position instanceof Vector3 ? position.array : position);
if (target instanceof Array) {
target = new Vector3(target[0], target[1], target[2]);
}
if (target instanceof Vector3) {
light.lookAt(target);
}
if (typeof color === 'string') {
color = parseColor(color);
}
range != null && (light.range = range);
color != null && (light.color = color);
intensity != null && (light.intensity = intensity);
umbraAngle != null && (light.umbraAngle = umbraAngle);
penumbraAngle != null && (light.penumbraAngle = penumbraAngle);
this.scene.add(light);
return light;
};
/**
* Create a point light.
* @param {Array.<number>|clay.math.Vector3} position Position of point light..
* @param {number} [range=100] Falloff range of point light.
* @param {Color} [color='#fff'] Color of point light.
* @param {number} [intensity=1] Intensity of point light.
*/
App3D.prototype.createPointLight = function (position, range, color, intensity) {
var light = new PointLight();
light.position.setArray(position instanceof Vector3 ? position.array : position);
if (typeof color === 'string') {
color = parseColor(color);
}
range != null && (light.range = range);
color != null && (light.color = color);
intensity != null && (light.intensity = intensity);
this.scene.add(light);
return light;
};
/**
* Create a ambient light.
* @param {Color} [color='#fff'] Color of ambient light.
* @param {number} [intensity=1] Intensity of ambient light.
*/
App3D.prototype.createAmbientLight = function (color, intensity) {
var light = new AmbientLight();
if (typeof color === 'string') {
color = parseColor(color);
}
color != null && (light.color = color);
intensity != null && (light.intensity = intensity);
this.scene.add(light);
return light;
};
/**
* Load a [glTF](https://github.com/KhronosGroup/glTF) format model.
* You can convert FBX/DAE/OBJ format models to [glTF](https://github.com/KhronosGroup/glTF) with [fbx2gltf](https://github.com/pissang/claygl#fbx-to-gltf20-converter) python script,
* or simply using the [Clay Viewer](https://github.com/pissang/clay-viewer) client application.
* @param {string} url
* @param {Object} opts
* @param {string} [opts.shader='lambert'] 'basic'|'lambert'|'standard'
* @param {boolean} [opts.waitTextureLoaded=false] If add to scene util textures are all loaded.
* @param {boolean} [opts.autoPlayAnimation=true] If autoplay the animation of model.
* @param {boolean} [opts.upAxis='y'] Change model to y up if upAxis is 'z'
* @param {boolean} [opts.textureFlipY=false]
* @param {string} [opts.textureRootPath] Root path of texture. Default to be relative with glTF file.
* @return {Promise}
*/
App3D.prototype.loadModel = function (url, opts) {
if (typeof url !== 'string') {
throw new Error('Invalid URL.');
}
opts = opts || {};
if (opts.autoPlayAnimation == null) {
opts.autoPlayAnimation = true;
}
var shaderName = opts.shader || 'standard';
var loaderOpts = {
rootNode: new Node(),
shaderName: 'clay.' + shaderName,
textureRootPath: opts.textureRootPath,
crossOrigin: 'Anonymous',
textureFlipY: opts.textureFlipY
};
var loader = new GLTFLoader(loaderOpts);
var scene = this.scene;
var timeline = this.timeline;
return new Promise(function (resolve, reject) {
function afterLoad(result) {
scene.add(result.rootNode);
if (opts.autoPlayAnimation) {
result.clips.forEach(function (clip) {
timeline.addClip(clip);
});
}
resolve(result);
}
loader.success(function (result) {
if (!opts.waitTextureLoaded) {
afterLoad(result);
}
else {
Promise.all(result.textures.map(function (texture) {
if (texture.isRenderable()) {
return Promise.resolve(texture);
}
return new Promise(function (resolve) {
texture.success(resolve);
texture.error(resolve);
});
})).then(function () {
afterLoad(result);
}).catch(function () {
afterLoad(result);
});
}
});
loader.error(function () {
reject();
});
loader.load(url);
});
};
export default {
App3D: App3D,
/**
* Create a 3D application that will manage the app initialization and loop.
* @name clay.application.create
* @param {HTMLDomElement|string} dom Container dom element or a selector string that can be used in `querySelector`
* @param {Object} appNS
* @param {Function} init Initialization callback that will be called when initing app.
* @param {Function} loop Loop callback that will be called each frame.
* @param {number} [width] Container width.
* @param {number} [height] Container height.
* @param {number} [devicePixelRatio]
* @return {clay.application.App3D}
*
* @example
* clay.application.create('#app', {
* init: function (app) {
* app.createCube();
* var camera = app.createCamera();
* camera.position.set(0, 0, 2);
* },
* loop: function () { // noop }
* })
*/
create: function (dom, appNS) {
return new App3D(dom, appNS);
}
}; |