Modify part of asset classes (#3229)

* Modify part of asset classes

* Update import

* Update

* mesh-loader

* Update the import statement of JsonAsset as default import

* Rename files

* Remove old asset and asset-mng

* Copyrights

* Fix some bugs

* Fix imports of vmath classes; Fix errors of decorator property's ts comment notation;Adjust the order of member declarations for better IDE intelligense
This commit is contained in:
Leslie Leigh
2018-09-13 10:30:07 +08:00
committed by pandamicro
parent 1dab0a28ad
commit 968a67260c
27 changed files with 2044 additions and 976 deletions
+44 -3
View File
@@ -1,5 +1,40 @@
import { vec3, quat, clamp } from '../vmath';
import Asset from './asset';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const {ccclass} = _decorator;
import Asset from "../../assets/CCAsset";
import vec3 from "../../core/vmath/vec3";
import quat from "../../core/vmath/quat";
import { clamp } from "../../core/vmath/utils";
/**
* @typedef {import("../framework/skeleton").SkeletonMask} SkeletonMask
* @typedef {import("../framework/skeleton").default} Skeleton
* @typedef {import("../../scene-graph/CCNode").default} Joint
*/
let tmpvec3 = vec3.create(0, 0, 0);
let tmpquat = quat.create();
@@ -25,7 +60,8 @@ function _binaryIndexOf(array, key) {
return lo;
}
export default class AnimationClip extends Asset {
@ccclass
export class AnimationClip extends Asset {
constructor() {
super();
@@ -47,6 +83,11 @@ export default class AnimationClip extends Asset {
return this._length;
}
/**
*
* @param {Skeleton} skeleton
* @param {number} t
*/
sample(skeleton, t) {
clamp(t, 0, this._length);
-217
View File
@@ -1,217 +0,0 @@
import { EventEmitter } from '../event-sys';
import resl from '../misc/resl';
import utils from '../misc/utils';
function _createTable() {
let obj = Object.create(null);
obj.__tmp__ = undefined;
delete obj.__tmp__;
return obj;
}
function _wrapCallback(localID, callback) {
return function (err, asset) {
if (err) {
if (callback) {
callback(err);
}
return;
}
if (callback) {
// if we are requesting subAsset, go get it.
if (localID) {
asset = asset.subAsset(localID);
if (!asset) {
callback(new Error(`subasset ${localID} not found.`));
return;
}
}
callback(null, asset);
}
};
}
class AssetTask extends EventEmitter {
constructor() {
super();
}
run(assetMng, uuid, info) {
assetMng.loadUrls(info.type, info.urls, (err, asset) => {
// remove loadings
delete assetMng._loadings[uuid];
// emit error
if (err) {
this.emit('loaded', err);
return;
}
// emit loaded
asset._uuid = uuid;
asset._loaded = true;
assetMng.add(uuid, asset);
this.emit('loaded', null, asset);
});
}
}
export default class AssetMng {
constructor(app) {
this._app = app;
this._loaders = _createTable(); // asset type to loader
this._assetInfos = _createTable(); // uuid to asset-infos
this._assets = _createTable(); // uuid to asset
this._loadings = _createTable(); // uuid to loading tasks
this._levelInfos = _createTable(); // sceneName to scene file
}
registerLoader(type, loader) {
this._loaders[type] = loader;
}
registerAsset(uuid, info) {
if (this._assetInfos[uuid]) {
console.warn(`asset ${uuid} already registerred.`);
return;
}
this._assetInfos[uuid] = info;
}
registerLevel(name, file) {
if (this._levelInfos[name]) {
console.warn(`level ${name} is already registerred.`);
return;
}
this._levelInfos[name] = file;
}
loadLevel(name, callback) {
if (!this._levelInfos[name]) {
console.error(`Cannot load scene ${name}`);
callback && callback(new Error('loadFail'), null);
} else {
let app = this._app;
resl({
manifest: {
sceneJson: {
type: 'text',
parser: JSON.parse,
src: this._levelInfos[name]
}
},
onDone(data) {
utils.parseLevel(
app,
data.sceneJson,
(err, level) => {
callback && callback(err, level);
}
);
},
onError(err) {
callback && callback(err, null);
}
});
}
}
add(uuid, asset) {
if (this._assets[uuid]) {
console.warn(`Failed to add asset ${uuid}, already exists.`);
return;
}
this._assets[uuid] = asset;
}
get(uuid) {
// if this is a sub-asset
let subIdx = uuid.indexOf('@');
if (subIdx === -1) {
return this._assets[uuid];
}
let localID = uuid.substring(0, subIdx);
uuid = uuid.substring(subIdx + 1);
let asset = this._assets[uuid];
if (asset && localID) {
return asset.subAsset(localID);
}
return null;
}
load(uuid, callback) {
// if this is a sub-asset
let subIdx = uuid.indexOf('@');
let localID;
if (subIdx !== -1) {
localID = uuid.substring(0, subIdx);
uuid = uuid.substring(subIdx + 1);
}
// check if asset loaded
let asset = this._assets[uuid];
if (asset) {
// if we already loaded
if (callback) {
// if we are requesting subAsset, go get it.
if (localID) {
asset = asset.subAsset(localID);
if (!asset) {
callback(new Error(`subasset ${localID} not found.`));
return;
}
}
callback(null, asset);
}
return;
}
// if this is a loading task
let task = this._loadings[uuid];
let taskCallback = _wrapCallback(localID, callback);
if (task) {
task.once('loaded', taskCallback);
return;
}
// check if we have asset-info for loading asset
let info = this._assetInfos[uuid];
if (!info) {
if (callback) {
callback(new Error(`asset info ${uuid} not found, please add it first.`));
}
return;
}
// create new task
task = new AssetTask(this);
this._loadings[uuid] = task;
task.once('loaded', _wrapCallback(localID, callback));
task.run(this, uuid, info);
}
loadUrls(type, urls, callback) {
let loader = this._loaders[type];
if (!loader) {
if (callback) {
callback(new Error(`can not find loader for asset type ${type}, please register it first.`));
}
return;
}
loader(this._app, urls, callback);
}
}
-39
View File
@@ -1,39 +0,0 @@
let _internal_id = -1;
export default class Asset {
constructor() {
++_internal_id;
this._uuid = `internal-${_internal_id}`;
this._name = '';
this._loaded = false;
// TODO
// this._caches = {}; // downloaded caches (for reload)
}
get uuid() {
return this._uuid;
}
get name() {
return this._name;
}
/**
* Overwrite this if you have sub-assets
*/
subAsset(/*localID*/) {
return null;
}
unload() {
this._loaded = false;
}
reload() {
}
clone() {
}
}
+87 -37
View File
@@ -1,68 +1,118 @@
import Asset from './asset';
import { EventEmitter } from '../event-sys';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
import Asset from "../../assets/CCAsset";
import { EventTarget } from "../../core/event/index";
const { ccclass, mixins } = _decorator;
/**
* Enums indicating the load mode of an audio clip
* @property {number} WEB_AUDIO load through Web Audio API interface
* @property {number} DOM_AUDIO load through an audio DOM element
* @typedef {number} PlayingState
* @enum {number}
*/
const enums = {
UNKNOWN_AUDIO: -1,
WEB_AUDIO: 0,
DOM_AUDIO: 1,
WX_GAME_AUDIO: 2,
export const PlayingState = {
INITIALIZING: 0,
PLAYING: 1,
STOPPED: 2,
};
/**
* The base class for audio clip asset
* Enums indicating the load mode of an audio clip
* @typedef {number} AudioSourceType
* @enum {number}
*/
export default class AudioClip extends Asset {
export const AudioSourceType = {
UNKNOWN_AUDIO: -1,
/**
* Create an empty asset
* load through Web Audio API interface
*/
constructor() {
super();
this.__initEventEmitter();
this._audio = null;
this._state = AudioClip.INITIALIZING;
this._duration = 0;
/**
* Current load mode
* @type {number}
*/
this.loadMode = AudioClip.UNKNOWN_AUDIO;
}
WEB_AUDIO: 0,
/**
* load through an audio DOM element
*/
DOM_AUDIO: 1,
WX_GAME_AUDIO: 2,
};
/**
* @typedef {AudioBuffer|HTMLAudioElement} AudioSource
*/
/**
* The base class for audio clip asset.
* @mixes {EventTarget}
*/
@ccclass
@mixins(EventTarget)
export class AudioClip extends Asset {
/**
* @type {AudioSource}
*/
_audio = null;
/**
* @type {number}
*/
_duration = 0;
/**
* @type { PlayingState }
*/
_state = PlayingState.INITIALIZING;
/**
* @type { AudioSourceType }
*/
loadMode = AudioSourceType.UNKNOWN_AUDIO;
/**
* Set the actual audio clip asset
* @param {AudioBuffer|HTMLAudioElement} clip
* @param {Obeject} info
* @param {AudioSource} clip
* @param {Object} info
*/
setNativeAsset(clip, info) {
this._audio = clip;
this._duration = info ? info.length : 0;
if (clip) {
this._loaded = true;
this._state = AudioClip.STOPPED;
super.loaded = true;
this._state = PlayingState.STOPPED;
} else {
this._loaded = false;
this._state = AudioClip.INITIALIZING;
super.loaded = false;
this._state = PlayingState.INITIALIZING;
this.duration = 0;
}
}
/**
* Get current state of the clip
* @return {number}
* @return {PlayingState}
*/
getState() {
return this._state;
}
}
Object.assign(AudioClip, enums);
EventEmitter.mixin(AudioClip);
}
+86
View File
@@ -0,0 +1,86 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const {ccclass} = _decorator;
import Font from "./font";
import vec2 from "../../core/vmath/vec2";
import Texture2D from "./texture-2d";
/**
* @typedef {{char: string, x: number, y: number, width: number, height: number, xoffset: number, yoffset: number, xadvance: number, uvs: vec2[]}} BitmapFontGlyph
*/
@ccclass
export class BitmapFont extends Font {
/**
* @type {Texture2D}
*/
_texture = null;
/**
* @type {string}
*/
_face = "";
/**
* @type {BitmapFontGlyph}
*/
_defaultGlyph = {
char: "",
x: 0,
y: 0,
width: 16,
height: 16,
xoffset: 0,
yoffset: 0,
xadvance: 16,
uvs: [
vec2.create(0, 0),
vec2.create(0, 0),
vec2.create(0, 0),
vec2.create(0, 0)
],
};
constructor() {
super();
super._type = "bitmap";
}
/**
* @return {Texture2D}
*/
get texture() {
return this._texture;
}
/**
* @return {string}
*/
get face() {
return this._face;
}
}
-37
View File
@@ -1,37 +0,0 @@
import Font from './font';
import { vec2 } from '../vmath';
export default class BMFont extends Font {
constructor() {
super();
this._texture = null;
this._face = '';
this._defaultGlyph = {
char: ' ',
x: 0,
y: 0,
width: 16,
height: 16,
xoffset: 0,
yoffset: 0,
xadvance: 16,
uvs: [
vec2.create(0, 0),
vec2.create(0, 0),
vec2.create(0, 0),
vec2.create(0, 0)
],
};
this._type = 'bitmap';
}
get texture() {
return this._texture;
}
get face() {
return this._face;
}
}
+159 -112
View File
@@ -1,128 +1,175 @@
import AudioClip from './audio-clip';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
export default class DOMAudioClip extends AudioClip {
constructor() {
super();
this.loadMode = AudioClip.DOM_AUDIO;
this._volume = 1;
this._loop = false;
this._currentTimer = 0;
this._oneShoting = false;
http://www.cocos.com
this._post_play = () => {
this._state = AudioClip.PLAYING;
this.emit('started');
};
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
this._on_gesture = () => {
let promise = this._audio.play();
if (!promise) {
console.warn('no promise returned from HTMLMediaElement.play()');
return;
}
promise.then(() => {
if (this._alreadyDelayed) this._post_play();
else { this._audio.pause(); this._audio.currentTime = 0; }
window.removeEventListener('touchend', this._on_gesture);
document.removeEventListener('mouseup', this._on_gesture);
});
};
}
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
setNativeAsset(clip, info) {
super.setNativeAsset(clip, info);
clip.volume = this._volume;
clip.loop = this._loop;
// callback on audio ended
clip.addEventListener('ended', () => {
if (this._oneShoting) return;
this._state = AudioClip.STOPPED;
this._audio.currentTime = 0;
this.emit('ended');
});
/* play & stop immediately after receiving a gesture so that
we can freely invoke play() outside event listeners later */
window.addEventListener('touchend', this._on_gesture);
document.addEventListener('mouseup', this._on_gesture);
}
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const { ccclass } = _decorator;
import { AudioClip, AudioSourceType, PlayingState } from "./audio-clip";
play() {
if (!this._audio || this._state === AudioClip.PLAYING) return;
let promise = this._audio.play();
if (!promise) {
console.warn('no promise returned from HTMLMediaElement.play()');
return;
@ccclass
export class DOMAudioClip extends AudioClip {
/**
* @type {number}
*/
_volume = 1;
/**
* @type {boolean}
*/
_loop = false;
/**
* @type {number}
*/
_currentTimer = 0;
/**
* @type {boolean}
*/
_oneShoting = false;
constructor() {
super();
this.loadMode = AudioSourceType.DOM_AUDIO;
this._post_play = () => {
this._state = AudioSourceType.PLAYING;
// @ts-ignore
this.emit('started');
};
this._on_gesture = () => {
let promise = this._audio.play();
if (!promise) {
console.warn('no promise returned from HTMLMediaElement.play()');
return;
}
promise.then(() => {
if (this._alreadyDelayed) this._post_play();
else { this._audio.pause(); this._audio.currentTime = 0; }
window.removeEventListener('touchend', this._on_gesture);
document.removeEventListener('mouseup', this._on_gesture);
});
};
}
promise.then(this._post_play).catch(() => { this._alreadyDelayed = true; });
}
pause() {
if (this._state !== AudioClip.PLAYING) return;
this._audio.pause();
this._state = AudioClip.STOPPED;
this._oneShoting = false;
}
setNativeAsset(clip, info) {
super.setNativeAsset(clip, info);
clip.volume = this._volume;
clip.loop = this._loop;
// callback on audio ended
clip.addEventListener('ended', () => {
if (this._oneShoting) return;
this._state = PlayingState.STOPPED;
this._audio.currentTime = 0;
// @ts-ignore
this.emit('ended');
});
/* play & stop immediately after receiving a gesture so that
we can freely invoke play() outside event listeners later */
window.addEventListener('touchend', this._on_gesture);
document.addEventListener('mouseup', this._on_gesture);
}
stop() {
this._audio.currentTime = 0;
if (this._state !== AudioClip.PLAYING) return;
this._audio.pause();
this._state = AudioClip.STOPPED;
this._oneShoting = false;
}
play() {
if (!this._audio || this._state === PlayingState.PLAYING) return;
let promise = this._audio.play();
if (!promise) {
console.warn('no promise returned from HTMLMediaElement.play()');
return;
}
promise.then(this._post_play).catch(() => { this._alreadyDelayed = true; });
}
playOneShot(volume = 1) {
/* HTMLMediaElement doesn't support multiple playback at the
same time so here we fall back to re-start style approach */
if (!this._audio) return;
this._audio.currentTime = 0;
this._audio.volume = volume;
if (this._oneShoting) return;
this._audio.loop = false;
this._oneShoting = true;
this._audio.play().then(() => {
this._audio.addEventListener('ended', () => {
this._audio.currentTime = 0;
this._audio.volume = this._volume;
this._audio.loop = this._loop;
pause() {
if (this._state !== PlayingState.PLAYING) return;
this._audio.pause();
this._state = PlayingState.STOPPED;
this._oneShoting = false;
}, { once: true });
}).catch(() => { this._oneShoting = false; });
}
}
setCurrentTime(val) {
if (!this._audio) return;
this._audio.currentTime = val;
}
stop() {
this._audio.currentTime = 0;
if (this._state !== PlayingState.PLAYING) return;
this._audio.pause();
this._state = PlayingState.STOPPED;
this._oneShoting = false;
}
getCurrentTime() {
return this._audio ? this._audio.currentTime : 0;
}
playOneShot(volume = 1) {
/* HTMLMediaElement doesn't support multiple playback at the
same time so here we fall back to re-start style approach */
if (!this._audio) return;
this._audio.currentTime = 0;
this._audio.volume = volume;
if (this._oneShoting) return;
this._audio.loop = false;
this._oneShoting = true;
this._audio.play().then(() => {
this._audio.addEventListener('ended', () => {
this._audio.currentTime = 0;
this._audio.volume = this._volume;
this._audio.loop = this._loop;
this._oneShoting = false;
}, { once: true });
}).catch(() => { this._oneShoting = false; });
}
getDuration() {
if (!this._audio) return this._duration;
// ios wechat browser doesn't have duration
return isNaN(this._audio.duration) ? this._duration : this._audio.duration;
}
setCurrentTime(val) {
if (!this._audio) return;
this._audio.currentTime = val;
}
setVolume(val) {
this._volume = val;
/* note this won't work for ios devices, for there
is just no way to set HTMLMediaElement's volume */
if (this._audio) this._audio.volume = val;
}
getCurrentTime() {
return this._audio ? this._audio.currentTime : 0;
}
getVolume() {
if (this._audio) return this._audio.volume;
return this._volume;
}
getDuration() {
if (!this._audio) return this._duration;
// ios wechat browser doesn't have duration
return isNaN(this._audio.duration) ? this._duration : this._audio.duration;
}
setLoop(val) {
this._loop = val;
if (this._audio) this._audio.loop = val;
}
getLoop() {
return this._loop;
}
}
setVolume(val) {
this._volume = val;
/* note this won't work for ios devices, for there
is just no way to set HTMLMediaElement's volume */
if (this._audio) this._audio.volume = val;
}
getVolume() {
if (this._audio) return this._audio.volume;
return this._volume;
}
setLoop(val) {
this._loop = val;
if (this._audio) this._audio.loop = val;
}
getLoop() {
return this._loop;
}
}
+111 -44
View File
@@ -1,55 +1,122 @@
import Asset from './asset';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const {ccclass, property} = _decorator;
import Technique from "../../renderer/core/technique";
import Asset from "../../assets/CCAsset";
@ccclass
export default class Effect extends Asset {
constructor() {
super();
/**
* @type {Technique[]}
*/
@property([Technique])
_techniques = [];
// effect disc
this._techniques = [];
this._properties = {};
this._defines = [];
this._dependencies = [];
}
/**
* @type {Object}
*/
@property(Object)
_properties = {};
set techniques(val) {
this._techniques = val;
}
/**
* @type {Definition[]}
*/
@property([Object])
_defines = [];
get techniques() {
return this._techniques;
}
/**
* @type {Dependency[]}
*/
@property([Object])
_dependencies = [];
set properties(val) {
this._properties = val;
}
/**
* @typedef {{name: string, value: boolean|number|string}} Definition
* @typedef {{define: string, extension: string}} Dependency
*/
get properties() {
return this._properties;
}
set defines(val) {
this._defines = val;
}
get defines() {
return this._defines;
}
set dependencies(val) {
this._dependencies = val;
}
get dependencies() {
return this._dependencies;
}
unload() {
if (!this._loaded) {
return;
/**
* @param {Technique[]} val
*/
set techniques(val) {
this._techniques = val;
}
// TODO: what should we do here ???
/**
* @return {Technique[]}
*/
get techniques() {
return this._techniques;
}
super.unload();
}
/**
* @param {Object} val
*/
set properties(val) {
this._properties = val;
}
/**
* @return {Object}
*/
get properties() {
return this._properties;
}
/**
* @param {Definition[]} val
*/
set defines(val) {
this._defines = val;
}
/**
* @return {Definition[]}}
*/
get defines() {
return this._defines;
}
/**
* @param {Dependency[]} val
*/
set dependencies(val) {
this._dependencies = val;
}
/**
* @return {Dependency[]}
*/
get dependencies() {
return this._dependencies;
}
destroy() {
// TODO: what should we do here ???
return super.destroy();
}
}
+79 -20
View File
@@ -1,28 +1,87 @@
import Asset from './asset';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const {ccclass} = _decorator;
import Asset from "../../assets/CCAsset";
/**
* @typedef {import("../../core/vmath/index").vec2} vec2
* @typedef {"unknow" | "bitmap" | "opentype"} FontType
* @typedef {{char: string, x: number, y: number, width: number, height: number, xoffset: number, yoffset: number, xadvance: number, uvs: vec2[]}} BitmapFontGlyph
* @typedef {{id: number, x: number, y: number, width: number, height: number, xoffset: number, yoffset: number, xadvance: number, uvs: vec2[]}} OpentypeFontGlyph
* @typedef {BitmapFontGlyph | OpentypeFontGlyph} Glyph
*/
@ccclass
export default class Font extends Asset {
constructor() {
super();
/** Font size.
* @type {number}
*/
_size = 32;
this._size = 32; // font size
this._type = 'unknow'; // font type: bitmap or opentype
// bitmap font glyph: {char, x, y, width, height, xoffset, yoffset, xadvance}
// opentype font glyph: {id, x, y, width, height, xoffset, yoffset, xadvance}
this._glyphs = {};
this._lineHeight = 32;
this._useKerning = false;
}
/** Font type.
* @type {FontType}
*/
_type = "unknow";
get size() {
return this._size;
}
/**
* Line height.
* @type {number}
*/
_lineHeight = 32;
get lineHeight() {
return this._lineHeight;
}
/**
*
* @type {boolean}
*/
_useKerning = false;
get type() {
return this._type;
}
/**
* @type {Glyph[]}
*/
_glyphs = [];
/**
* @return {number}
*/
get size() {
return this._size;
}
/**
* @return {number}
*/
get lineHeight() {
return this._lineHeight;
}
/**
* @return {FontType}
*/
get type() {
return this._type;
}
}
-55
View File
@@ -1,55 +0,0 @@
import Asset from './asset';
// TODO:
// import gltfUtils from '../loaders/utils/gltf-utils';
// import ModelComponent from '../framework/model-component';
// import SkinningModelComponent from '../framework/skinning-model-component';
export default class Gltf extends Asset {
constructor() {
super();
this._nodes = null; // [gltfNode, ...]
this._meshes = null; // [Mesh, ...]
this._joints = null; // Joints
}
subAsset(localID) {
let id = parseInt(localID.substring(1));
if (localID[0] === 'm') {
return this._meshes[id];
}
if (localID === 'joints') {
return this._joints;
}
return null;
}
// TODO:
// instantiate(app) {
// let entities = gltfUtils.createEntities(this._app, this._nodes);
// for (let i = 0; i < this._nodes.length; ++i) {
// let gltfNode = this._nodes[i];
// if (gltfNode.mesh) {
// let mesh = this._meshes[gltfNode.mesh];
// let ctor = ModelComponent;
// if (mesh.skinning) {
// ctor = SkinningModelComponent;
// }
// let comp = new ctor();
// comp._app = app;
// comp._entity = entities[i];
// comp.mesh = mesh;
// // invoke onInit
// if (comp.onInit) {
// comp.onInit();
// }
// }
// }
// }
}
+73 -16
View File
@@ -1,20 +1,58 @@
import Asset from './asset';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const { ccclass, property } = _decorator;
import Asset from "../../assets/CCAsset";
import Texture from './texture';
import renderer from '../renderer';
import { vec2, vec3, vec4, color3, color4 } from '../vmath';
import { vec2, vec3, vec4, color3, color4 } from '../../core/vmath/index';
import Effect from "./effect";
function _objArrayClone(val) {
return val.map(obj => Object.assign({}, obj));
}
@ccclass
export default class Material extends Asset {
constructor() {
super();
/**
* @type {Effect}
*/
@property(Effect)
_effect = null;
this._props = {};
this._effectInst = null; // renderer.effect
this._effect = null; // effect asset
}
/**
* @type {Object}
*/
@property
_props = {};
/**
* @type {renderer.effect}
*/
_effecInst = null;
_updateEffectInst() {
let techNum = this._effect.techniques.length;
@@ -26,7 +64,7 @@ export default class Material extends Asset {
for (let k = 0; k < tech.params.length; ++k) {
let param = tech.params[k];
switch(param.type) {
switch (param.type) {
case renderer.PARAM_FLOAT:
props[param.name] = param.value;
break;
@@ -92,9 +130,16 @@ export default class Material extends Asset {
}
}
/**
* @return {Effect}
*/
get effect() {
return this._effect;
}
/**
* @param {Effect} val
*/
set effect(val) {
if (this._effect !== val) {
this._effect = val;
@@ -102,10 +147,17 @@ export default class Material extends Asset {
}
}
/**
* @return {renderer.effect}
*/
get effectInst() {
return this._effectInst;
}
/**
*
* @param {Material} mat
*/
copy(mat) {
if (this._effect !== mat._effect) {
this._effect = mat._effect;
@@ -119,6 +171,11 @@ export default class Material extends Asset {
}
}
/**
*
* @param {string} name
* @param {*} val
*/
setProperty(name, val) {
this._props[name] = val;
@@ -129,17 +186,17 @@ export default class Material extends Asset {
}
}
/**
*
* @param {string} name
* @param {*} val
*/
define(name, val) {
this._effectInst.define(name, val);
}
unload() {
if (!this._loaded) {
return;
}
destroy() {
// TODO: what should we do here ???
super.unload();
super.destroy();
}
}
+152 -41
View File
@@ -1,56 +1,167 @@
import Asset from './asset';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const { ccclass, property } = _decorator;
import { GLTFAsset } from "../../assets/CCGLTFAsset";
import Asset from "../../assets/CCAsset";
import { default as GLTFUtils } from "./utils/gltf-utils";
/** @typedef {import("../../core/vmath/index").vec3} vec3 */
@ccclass
export default class Mesh extends Asset {
constructor() {
super();
/**
* @type {GLTFAsset}
*/
@property(GLTFAsset)
_gltfAsset;
this._subMeshes = null; // [renderer.InputAssemblers]
this._skinning = null; // {jointIndices, bindposes}
/**
* @type {number}
*/
@property(Number)
_gltfIndex = -1;
this._minPos = null; // vec3
this._maxPos = null; // vec3
}
/**
* @type {renderer.InputAssemblers}
*/
_subMeshes = null;
unload() {
if (!this._loaded) {
return;
/**
* @type {{jointIndices, bindposes}}
*/
_skinning = null;
/**
* @type {vec3}
*/
_minPos = null;
/**
* @type {vec3}
*/
_maxPos = null;
/**
* !#en
* Gets the native data of this mesh.
* @return {GLTFAsset | Null} The native data, or null if this is an empty mesh.
*/
getNativeAsset() {
return this._gltfAsset;
}
// destroy vertex buffer
this._subMeshes[0]._vertexBuffer.destroy();
// destroy index buffers
for (let i = 0; i < this._subMeshes.length; ++i) {
let mesh = this._subMeshes[i];
mesh._indexBuffer.destroy();
/**
* !#en
* Gets the index into the native data of this mesh.
* @return {number} The index into the native data.
*/
getNativeAssetIndex() {
return this._gltfIndex;
}
this._subMeshes = null;
/**
* !#en
* Sets the native data of this mesh.
* @param {GLTFAsset} gltfAsset The GLTF asset.
* @param {number} gltfIndex An index to the GLTF meshes.
*/
setNative(gltfAsset, gltfIndex) {
this._gltfAsset = gltfAsset;
this._gltfIndex = gltfIndex;
this._update();
}
super.unload();
}
/**
* !#en
* Destory this mesh and immediately release its video memory.
*/
destroy() {
if (this._subMeshes !== null) {
// Destroy vertex buffer
this._subMeshes[0]._vertexBuffer.destroy();
// Destroy index buffers
for (let i = 0; i < this._subMeshes.length; ++i) {
this._subMeshes[i]._indexBuffer.destroy();
}
this._subMeshes = null;
}
get skinning() {
return this._skinning;
}
return super.destroy();
}
get subMeshCount() {
return this._subMeshes.length;
}
/**
* !#en
* Submeshes count of this mesh.
* @property {number}
*/
get subMeshCount() {
return this._subMeshes.length;
}
getSubMesh(idx) {
return this._subMeshes[idx];
}
/**
* !#en
* Gets the specified submesh.
* @param {number} index Index of the specified submesh.
*/
getSubMesh(index) {
return this._subMeshes[index];
}
// TODO
// updateData () {
// // store the data
// if (this._persist) {
// if (this._data) {
// this._data.set(data, offset);
// } else {
// this._data = data;
// }
// }
// }
/**
* !#en
* Gets the skinning data associated with this mesh.
*/
get skinning() {
return this._skinning;
}
// TODO
// updateData () {
// // store the data
// if (this._persist) {
// if (this._data) {
// this._data.set(data, offset);
// } else {
// this._data = data;
// }
// }
// }
_update(app) {
if (!this._gltfAsset) {
return;
}
const result = GLTFUtils.createMesh(app, this._gltfAsset, this._gltfIndex);
if (!result) {
return;
}
this.name = result.name;
this._subMeshes = result.subMeshes;
this._minPos = result.minPos;
this._maxPos = result.maxPos;
this._skinning = result.skinning;
}
}
+272
View File
@@ -0,0 +1,272 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const {ccclass} = _decorator;
import Font from "./font";
import vec2 from "../../core/vmath/vec2";
import ShelfPack from "./utils/shelf-pack";
import Texture2D from "./texture-2d";
/**
* @typedef {{id: number, x: number, y: number, width: number, height: number, xoffset: number, yoffset: number, xadvance: number, uvs: vec2[]}} OpentypeFontGlyph
*/
@ccclass
export default class OpentypeFont extends Font {
/**
* opentype.Font
* @type {any}
*/
_font = null;
/**
* @type {number}
*/
_padding = 2;
/**
* @type {number}
*/
_fontScale = 1;
/**
* @type {Object}
*/
_textCache = {};
/**
* @type {ShelfPack}
*/
_packer;
/**
* @type {HTMLCanvasElement}
*/
_packCanvas;
/**
* @type {Texture2D}
*/
_fontAtlas;
/**
* @type {OpentypeFontGlyph}
*/
_defaultGlyph = {
id: 32, // space charCode
x: 0,
y: 0,
width: 16,
height: 16,
xoffset: 0,
yoffset: 0,
xadvance: 16,
uvs: [
vec2.create(0, 0),
vec2.create(0, 0),
vec2.create(0, 0),
vec2.create(0, 0)
],
};
constructor(device, width = 1024, height = 1024) {
super();
super._type = "opentype";
// this._face = null; // TODO:
this._packer = new ShelfPack(width, height); // TODO: auto resize
this._packCanvas = document.createElement('canvas');
this._packCanvas.width = width;
this._packCanvas.height = height;
this._fontAtlas = new Texture2D(device, width, height);
this._fontAtlas.mipmap = false;
this._fontAtlas.premultiplyAlpha = true;
}
/**
* Sets the opentype font.
* @param {any} val Opentype font to set.
*/
set font(val) {
this._font = val;
this._fontScale = this._size / this._font.unitsPerEm;
}
/**
* Gets the opentype font.
* @return {any} The opentype font.
*/
get font() {
return this._font;
}
/**
* Gets the generated texture.
* @return {Texture2D}
*/
get texture() {
return this._fontAtlas;
}
/**
* Sets the size.
* @param {number} val Size to set.
*/
set size(val) {
if (this._size !== val) {
this._size = val;
// when font size changed, we need to clear font atlas.
this.clear();
}
}
/**
* Sets the line height.
* @param {number} val Line height to set.
*/
set lineHeight(val) {
if (this._lineHeight !== val) {
this._lineHeight = val;
this.clear();
}
}
addText(text) {
if (this._textCache[text] === undefined) {
this._textCache[text] = text;
this._addTextToFontAtlas(text);
}
}
removeText(text) {
if (this._textCache[text] === undefined) {
console.warn(`can not remove text: '${text}' from font. not exists.`);
} else {
this._removeTextFromFontAtlas(text);
delete this._textCache[text];
}
}
clear() {
this._packer.clear();
let ctx = this._packCanvas.getContext('2d');
ctx.clearRect(0, 0, this._packCanvas.width, this._packCanvas.height);
this._fontAtlas.setImages([this._packCanvas]);
this._fontAtlas.commit();
}
_addTextToFontAtlas(text) {
let ctx = this._packCanvas.getContext('2d');
let fontAtlasDirty = false;
for (let i = 0; i < text.length; ++i) {
let char = text[i];
let charCode = text.charCodeAt(i);
// get opentype glyph
let otGlyph = this._font.charToGlyph(char);
if (otGlyph.path.getBoundingBox === undefined) { // opentype's bug ? some glyph such as space do not have getBoundingBox func.
continue;
}
let bbox = otGlyph.getBoundingBox();
let glyph = {
id: charCode,
x: 0,
y: 0,
width: 0,
height: 0,
xoffset: 0,
yoffset: 0,
xadvance: 0,
uvs: []
};
glyph.width = (bbox.x2 - bbox.x1) * this._fontScale;
glyph.height = (bbox.y2 - bbox.y1) * this._fontScale;
if (this._glyphs[charCode] !== undefined) {
this._packer.packOne(glyph.width, glyph.height, glyph.id); // increment refcount
} else {
fontAtlasDirty = true;
glyph.xadvance = otGlyph.advanceWidth * this._fontScale;
this._glyphs[charCode] = glyph;
let bin = this._packer.packOne(glyph.width + this._padding, glyph.height + this._padding, glyph.id); // pack a new one
if (bin !== null) {
glyph.xoffset = bbox.x1 * this._fontScale;
glyph.yoffset = this._size - bbox.y2 * this._fontScale + this._font.descender * this._fontScale;
// compute uvs
let u0 = (bin.x + this._padding / 2) / this._packCanvas.width;
let u1 = (bin.x + this._padding / 2 + glyph.width) / this._packCanvas.width;
let v0 = 1.0 - (bin.y + this._padding / 2 + glyph.height) / this._packCanvas.height;
let v1 = 1.0 - (bin.y + this._padding / 2) / this._packCanvas.height;
glyph.uvs = [
vec2.create(u0, v0),
vec2.create(u1, v0),
vec2.create(u0, v1),
vec2.create(u1, v1)
];
let path = otGlyph.getPath(bin.x - bbox.x1 * this._fontScale + this._padding / 2, bin.y + bbox.y2 * this._fontScale + this._padding / 2, this._size, { xScale: this._fontScale, yScale: this._fontScale });
path.fill = '#FFFFFF';
path.draw(ctx);
} else {
console.error('font glyph pack failed. font atlas size is not enough.');
}
}
}
if (fontAtlasDirty) {
// update font atlas
this._fontAtlas.setImages([this._packCanvas]);
this._fontAtlas.commit();
}
}
_removeTextFromFontAtlas(text) {
let ctx = this._packCanvas.getContext('2d');
let fontAtlasDirty = false;
for (let i = 0; i < text.length; ++i) {
let charCode = text.charCodeAt(i);
if (this._glyphs[charCode] !== undefined) {
let bin = this._packer.getBin(charCode);
let refCount = this._packer.unref(bin);
if (refCount === 0) {
delete this._glyphs[charCode];
ctx.clearRect(bin.x, bin.y, bin.w, bin.h);
fontAtlasDirty = true;
}
} else {
console.warn('try to remove a no exist glyph.');
}
}
if (fontAtlasDirty) {
// update font atlas
this._fontAtlas.setImages([this._packCanvas]);
this._fontAtlas.commit();
}
}
}
-181
View File
@@ -1,181 +0,0 @@
import Font from './font';
import Texture2D from '../assets/texture-2d';
import ShelfPack from './utils/shelf-pack';
import { vec2 } from '../vmath';
export default class OpenTypeFont extends Font {
constructor(device, width = 1024, height = 1024) {
super();
this._font = null; // opentype.Font
this._padding = 2;
this._fontScale = 1;
this._textCache = {};
// this._face = null; // TODO:
this._packer = new ShelfPack(width, height); // TODO: auto resize
this._packCanvas = document.createElement('canvas');
this._packCanvas.width = width;
this._packCanvas.height = height;
this._fontAtlas = new Texture2D(device, width, height);
this._fontAtlas.mipmap = false;
this._fontAtlas.premultiplyAlpha = true;
this._defaultGlyph = {
id: 32, // space charCode
x: 0,
y: 0,
width: 16,
height: 16,
xoffset: 0,
yoffset: 0,
xadvance: 16,
uvs: [
vec2.create(0, 0),
vec2.create(0, 0),
vec2.create(0, 0),
vec2.create(0, 0)
],
};
this._type = 'opentype';
}
set font(val) {
this._font = val;
this._fontScale = this._size / this._font.unitsPerEm;
}
get font() {
return this._font;
}
get texture() {
return this._fontAtlas;
}
set size(val) {
if (this._size !== val) {
this._size = val;
// when font size changed, we need to clear font atlas.
this.clear();
}
}
set lineHeight(val) {
if (this._lineHeight !== val) {
this._lineHeight = val;
this.clear();
}
}
addText(text) {
if (this._textCache[text] === undefined) {
this._textCache[text] = text;
this._addTextToFontAtlas(text);
}
}
removeText(text) {
if (this._textCache[text] === undefined) {
console.warn(`can not remove text: '${text}' from font. not exists.`);
} else {
this._removeTextFromFontAtlas(text);
delete this._textCache[text];
}
}
clear() {
this._packer.clear();
let ctx = this._packCanvas.getContext('2d');
ctx.clearRect(0, 0, this._packCanvas.width, this._packCanvas.height);
this._fontAtlas.setImages([this._packCanvas]);
this._fontAtlas.commit();
}
_addTextToFontAtlas(text) {
let ctx = this._packCanvas.getContext('2d');
let fontAtlasDirty = false;
for (let i = 0; i < text.length; ++i) {
let char = text[i];
let charCode = text.charCodeAt(i);
// get opentype glyph
let otGlyph = this._font.charToGlyph(char);
if (otGlyph.path.getBoundingBox === undefined) { // opentype's bug ? some glyph such as space do not have getBoundingBox func.
continue;
}
let bbox = otGlyph.getBoundingBox();
let glyph = {
id: charCode,
x: 0,
y: 0,
width: 0,
height: 0,
xoffset: 0,
yoffset: 0,
xadvance: 0,
};
glyph.width = (bbox.x2 - bbox.x1) * this._fontScale;
glyph.height = (bbox.y2 - bbox.y1) * this._fontScale;
if (this._glyphs[charCode] !== undefined) {
this._packer.packOne(glyph.width, glyph.height, glyph.id); // increment refcount
} else {
fontAtlasDirty = true;
glyph.xadvance = otGlyph.advanceWidth * this._fontScale;
this._glyphs[charCode] = glyph;
let bin = this._packer.packOne(glyph.width + this._padding, glyph.height + this._padding, glyph.id); // pack a new one
if (bin !== null) {
glyph.xoffset = bbox.x1 * this._fontScale;
glyph.yoffset = this._size - bbox.y2 * this._fontScale + this._font.descender * this._fontScale;
// compute uvs
let u0 = (bin.x + this._padding / 2) / this._packCanvas.width;
let u1 = (bin.x + this._padding / 2 + glyph.width) / this._packCanvas.width;
let v0 = 1.0 - (bin.y + this._padding / 2 + glyph.height) / this._packCanvas.height;
let v1 = 1.0 - (bin.y + this._padding / 2) / this._packCanvas.height;
glyph.uvs = [
vec2.create(u0, v0),
vec2.create(u1, v0),
vec2.create(u0, v1),
vec2.create(u1, v1)
];
let path = otGlyph.getPath(bin.x - bbox.x1 * this._fontScale + this._padding / 2, bin.y + bbox.y2 * this._fontScale + this._padding / 2, this._size, {xScale: this._fontScale, yScale: this._fontScale});
path.fill = '#FFFFFF';
path.draw(ctx);
} else {
console.error('font glyph pack failed. font atlas size is not enough.');
}
}
}
if (fontAtlasDirty) {
// update font atlas
this._fontAtlas.setImages([this._packCanvas]);
this._fontAtlas.commit();
}
}
_removeTextFromFontAtlas(text) {
let ctx = this._packCanvas.getContext('2d');
let fontAtlasDirty = false;
for (let i = 0; i < text.length; ++i) {
let charCode = text.charCodeAt(i);
if (this._glyphs[charCode] !== undefined) {
let bin = this._packer.getBin(charCode);
let refCount = this._packer.unref(bin);
if (refCount === 0) {
delete this._glyphs[charCode];
ctx.clearRect(bin.x, bin.y, bin.w, bin.h);
fontAtlasDirty = true;
}
} else {
console.warn('try to remove a no exist glyph.');
}
}
if (fontAtlasDirty) {
// update font atlas
this._fontAtlas.setImages([this._packCanvas]);
this._fontAtlas.commit();
}
}
}
+30 -2
View File
@@ -1,11 +1,39 @@
import Asset from './asset';
import { vec3, mat4 } from '../vmath';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const { ccclass } = _decorator;
import Asset from "../../assets/CCAsset";
import { vec3, mat4 } from '../../core/vmath/index';
let _t_tmp = vec3.create(0, 0, 0);
let _s_tmp = vec3.create(0, 0, 0);
let _mat4_tmp = mat4.create();
let _textureMatrix = mat4.create();
@ccclass
export default class Sprite extends Asset {
constructor() {
super();
+29 -1
View File
@@ -1,4 +1,31 @@
import Texture from './texture';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const { ccclass } = _decorator;
import { Texture } from './texture';
import gfx from '../gfx';
import { gfxFilters, gfxWraps, gfxTextureFmts } from '../misc/mappings';
@@ -51,6 +78,7 @@ function _allocData(texture) {
return null;
}
@ccclass
export default class Texture2D extends Texture {
constructor(device, width = 2, height = 2, fmt = 'rgba8') {
super(device);
+31 -2
View File
@@ -1,4 +1,32 @@
import Texture from './texture';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const { ccclass } = _decorator;
import { Texture } from './texture';
import gfx from '../gfx';
import { gfxFilters, gfxWraps, gfxTextureFmts } from '../misc/mappings';
@@ -30,7 +58,8 @@ function _updateOpts(out, texture) {
out.mipFilter = gfxFilters[texture._mipFilter];
}
export default class TextureCube extends Texture {
@ccclass
export class TextureCube extends Texture {
constructor(device, width = 2, height = 2, fmt = 'rgba8') {
super(device);
+39 -18
View File
@@ -1,32 +1,53 @@
import Texture2D from './texture-2d';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const { ccclass, property } = _decorator;
import Texture2D from './texture-2d';
import Sprite from "./sprite";
@ccclass
export default class TextureSprite extends Texture2D {
/**
* @type {Sprite[]}
*/
@property([Sprite])
_sprites = [];
constructor(device) {
super(device);
this._sprites = {};
}
get sprites() {
return this._sprites;
}
unload() {
if (!this._loaded) {
return;
}
// unload all sprites
destroy() {
for (let name in this._sprites) {
this._sprites[name].unload();
this._sprites[name].destroy();
}
super.unload();
}
subAsset(localID) {
let sprite = this._sprites[localID];
return sprite || null;
super.destroy();
}
}
+30 -2
View File
@@ -1,6 +1,34 @@
import Asset from './asset';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
export default class Texture extends Asset {
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const { ccclass } = _decorator;
import Asset from "../../assets/CCAsset";
@ccclass
export class Texture extends Asset {
constructor(device) {
super();
+442
View File
@@ -0,0 +1,442 @@
/* @flow */
import gfx from '../../gfx';
import renderer from '../../renderer';
import { vec3, quat, mat4 } from '../../vmath';
import { Node } from '../../scene-graph';
import AnimationClip from '../../assets/animation-clip';
import Joints from '../../assets/joints';
const _type2size = {
SCALAR: 1,
VEC2: 2,
VEC3: 3,
VEC4: 4,
MAT2: 4,
MAT3: 9,
MAT4: 16,
};
const _compType2Array = {
5120: Int8Array,
5121: Uint8Array,
5122: Int16Array,
5123: Uint16Array,
5124: Int32Array,
5125: Uint32Array,
5126: Float32Array,
};
/**
* @param {object} gltf
* @param {ArrayBuffer} bin
* @param {number} accessorID
*/
function createArray(gltf, bin, accessorID) {
let acc = gltf.accessors[accessorID];
let bufView = gltf.bufferViews[acc.bufferView];
let num = _type2size[acc.type];
let typedArray = _compType2Array[acc.componentType];
let result = new typedArray(bin, bufView.byteOffset + acc.byteOffset, acc.count * num);
return result;
}
/**
* @param {Array} gltfNodes
*/
function createNodes(gltfNodes) {
let nodes = new Array(gltfNodes.length);
for (let i = 0; i < gltfNodes.length; ++i) {
let gltfNode = gltfNodes[i];
let node = new Node(gltfNode.name);
if (gltfNode.translation) {
node.setLocalPos(
gltfNode.translation[0],
gltfNode.translation[1],
gltfNode.translation[2]
);
}
if (gltfNode.rotation) {
node.setLocalRot(
gltfNode.rotation[0],
gltfNode.rotation[1],
gltfNode.rotation[2],
gltfNode.rotation[3]
);
}
if (gltfNode.scale) {
node.setLocalScale(
gltfNode.scale[0],
gltfNode.scale[1],
gltfNode.scale[2]
);
}
nodes[i] = node;
}
for (let i = 0; i < gltfNodes.length; ++i) {
let gltfNode = gltfNodes[i];
let node = nodes[i];
if (gltfNode.children) {
for (let j = 0; j < gltfNode.children.length; ++j) {
let index = gltfNode.children[j];
node.append(nodes[index]);
}
}
}
return nodes;
}
/**
* @param {App} app
* @param {Array} gltfNodes
*/
function createEntities(app, gltfNodes) {
let nodes = new Array(gltfNodes.length);
for (let i = 0; i < gltfNodes.length; ++i) {
let gltfNode = gltfNodes[i];
let node = app.createEntity(gltfNode.name);
if (gltfNode.translation) {
node.setLocalPos(
gltfNode.translation[0],
gltfNode.translation[1],
gltfNode.translation[2]
);
}
if (gltfNode.rotation) {
node.setLocalRot(
gltfNode.rotation[0],
gltfNode.rotation[1],
gltfNode.rotation[2],
gltfNode.rotation[3]
);
}
if (gltfNode.scale) {
node.setLocalScale(
gltfNode.scale[0],
gltfNode.scale[1],
gltfNode.scale[2]
);
}
nodes[i] = node;
}
for (let i = 0; i < gltfNodes.length; ++i) {
let gltfNode = gltfNodes[i];
let node = nodes[i];
if (gltfNode.children) {
for (let j = 0; j < gltfNode.children.length; ++j) {
let index = gltfNode.children[j];
node.append(nodes[index]);
}
}
}
return nodes;
}
/**
* @param {App} app
* @param {GLTFAsset} gltfAsset
* @param {number} index
* @return {{ name: string, subMeshes: any[], minPos: vec3, maxPos: vec3, skinning: any }}
*/
function createMesh(app, gltfAsset, index) {
/** @type {import("../../../../types/glTF/glTF").GlTf} */
const gltf = gltfAsset._description;
if (index >= gltf.meshes.length) {
return null;
}
const gltfMesh = gltf.meshes[index];
const bin = gltfAsset.buffers[0].data;
const accessors = gltf.accessors;
const attributes = gltfMesh.primitives[0].attributes;
let vbView = null;
// create mesh-asset
const name = gltfMesh.name;
const subMeshes = new Array(gltfMesh.primitives.length);
let minPos = null;
let maxPos = null;
// create vertex-format
let vfmt = [];
let vcount = 0;
if (attributes.POSITION !== undefined) {
let acc = accessors[attributes.POSITION];
vfmt.push({ name: gfx.ATTR_POSITION, type: acc.componentType, num: _type2size[acc.type] });
vcount = acc.count;
vbView = gltf.bufferViews[acc.bufferView];
minPos = vec3.create(acc.min[0], acc.min[1], acc.min[2]);
maxPos = vec3.create(acc.max[0], acc.max[1], acc.max[2]);
}
if (attributes.NORMAL !== undefined) {
let acc = accessors[attributes.NORMAL];
vfmt.push({ name: gfx.ATTR_NORMAL, type: acc.componentType, num: _type2size[acc.type] });
}
if (attributes.TANGENT !== undefined) {
let acc = accessors[attributes.TANGENT];
vfmt.push({ name: gfx.ATTR_TANGENT, type: acc.componentType, num: _type2size[acc.type] });
}
if (attributes.COLOR_0 !== undefined) {
let acc = accessors[attributes.COLOR_0];
vfmt.push({ name: gfx.ATTR_COLOR0, type: acc.componentType, num: _type2size[acc.type] });
}
if (attributes.TEXCOORD_0 !== undefined) {
let acc = accessors[attributes.TEXCOORD_0];
vfmt.push({ name: gfx.ATTR_UV0, type: acc.componentType, num: _type2size[acc.type] });
}
if (attributes.TEXCOORD_1 !== undefined) {
let acc = accessors[attributes.TEXCOORD_1];
vfmt.push({ name: gfx.ATTR_UV1, type: acc.componentType, num: _type2size[acc.type] });
}
if (attributes.TEXCOORD_2 !== undefined) {
let acc = accessors[attributes.TEXCOORD_2];
vfmt.push({ name: gfx.ATTR_UV2, type: acc.componentType, num: _type2size[acc.type] });
}
if (attributes.TEXCOORD_3 !== undefined) {
let acc = accessors[attributes.TEXCOORD_3];
vfmt.push({ name: gfx.ATTR_UV3, type: acc.componentType, num: _type2size[acc.type] });
}
if (attributes.JOINTS_0 !== undefined) {
let acc = accessors[attributes.JOINTS_0];
vfmt.push({ name: gfx.ATTR_JOINTS, type: acc.componentType, num: _type2size[acc.type] });
}
if (attributes.WEIGHTS_0 !== undefined) {
let acc = accessors[attributes.WEIGHTS_0];
vfmt.push({ name: gfx.ATTR_WEIGHTS, type: acc.componentType, num: _type2size[acc.type] });
}
// create vertex-buffer
let vbData = new Uint8Array(bin, vbView.byteOffset, vbView.byteLength);
let vb = new gfx.VertexBuffer(
app.device,
new gfx.VertexFormat(vfmt),
gfx.USAGE_STATIC,
vbData,
vcount
);
// create index-buffer
for (let i = 0; i < gltfMesh.primitives.length; ++i) {
let primitive = gltfMesh.primitives[i];
let ib = null;
if (primitive.indices !== undefined) {
let ibAcc = accessors[primitive.indices];
let ibView = gltf.bufferViews[ibAcc.bufferView];
let ibData = new Uint8Array(bin, ibView.byteOffset, ibView.byteLength);
ib = new gfx.IndexBuffer(
app.device,
ibAcc.componentType,
gfx.USAGE_STATIC,
ibData,
ibAcc.count
);
}
subMeshes[i] = new renderer.InputAssembler(vb, ib);
}
// create skinning if we found
let skinning = null;
if (gltf.skins) {
for (let i = 0; i < gltf.skins.length; ++i) {
if (gltf.skins[i].name === gltfMesh.name) {
skinning = createSkinning(gltf, bin, i);
}
}
}
return { name, subMeshes, minPos, maxPos, skinning};
}
/**
* @param {Object} gltf
* @param {ArrayBuffer} bin
* @param {number} index
*/
function createSkinning(gltf, bin, index) {
if (index >= gltf.skins.length) {
return null;
}
let gltfSkin = gltf.skins[index];
// extract bindposes mat4 data
let accessor = gltf.accessors[gltfSkin.inverseBindMatrices];
let bufView = gltf.bufferViews[accessor.bufferView];
let data = new Float32Array(bin, bufView.byteOffset + accessor.byteOffset, accessor.count * 16);
let bindposes = new Array(accessor.count);
for (let i = 0; i < accessor.count; ++i) {
bindposes[i] = mat4.create(
data[16 * i + 0], data[16 * i + 1], data[16 * i + 2], data[16 * i + 3],
data[16 * i + 4], data[16 * i + 5], data[16 * i + 6], data[16 * i + 7],
data[16 * i + 8], data[16 * i + 9], data[16 * i + 10], data[16 * i + 11],
data[16 * i + 12], data[16 * i + 13], data[16 * i + 14], data[16 * i + 15]
);
}
return {
jointIndices: gltfSkin.joints,
bindposes,
};
}
/**
* @param {Object} gltf
* @param {ArrayBuffer} bin
* @param {number} index
*/
function createAnimationClip(gltf, bin, index) {
if (index >= gltf.animations.length) {
return null;
}
let gltfAnimation = gltf.animations[index];
let framesList = [];
let maxLength = -1;
for (let i = 0; i < gltfAnimation.channels.length; ++i) {
let gltfChannel = gltfAnimation.channels[i];
let inputAcc = gltf.accessors[gltfChannel.input];
// find frames by input name
let frames;
for (let j = 0; j < framesList.length; ++j) {
if (framesList[j].name === inputAcc.name) {
frames = framesList[j];
break;
}
}
// if not found, create one
if (!frames) {
let inArray = createArray(gltf, bin, gltfChannel.input);
let inputs = new Array(inArray.length);
for (let i = 0; i < inArray.length; ++i) {
let t = inArray[i];
inputs[i] = t;
if (maxLength < t) {
maxLength = t;
}
}
frames = {
name: inputAcc.name,
times: inputs,
joints: [],
};
framesList.push(frames);
}
// find output frames by node id
let jointFrames;
for (let j = 0; j < frames.joints.length; ++j) {
if (frames.joints[j].id === gltfChannel.node) {
jointFrames = frames.joints[j];
break;
}
}
// if not found, create one
if (!jointFrames) {
jointFrames = {
id: gltfChannel.node
};
frames.joints.push(jointFrames);
}
let outArray = createArray(gltf, bin, gltfChannel.output);
if (gltfChannel.path === 'translation') {
let cnt = outArray.length / 3;
jointFrames.translations = new Array(cnt);
for (let i = 0; i < cnt; ++i) {
jointFrames.translations[i] = vec3.create(
outArray[3 * i + 0],
outArray[3 * i + 1],
outArray[3 * i + 2]
);
}
} else if (gltfChannel.path === 'rotation') {
let cnt = outArray.length / 4;
jointFrames.rotations = new Array(cnt);
for (let i = 0; i < cnt; ++i) {
jointFrames.rotations[i] = quat.create(
outArray[4 * i + 0],
outArray[4 * i + 1],
outArray[4 * i + 2],
outArray[4 * i + 3]
);
}
} else if (gltfChannel.path === 'scale') {
let cnt = outArray.length / 3;
jointFrames.scales = new Array(cnt);
for (let i = 0; i < cnt; ++i) {
jointFrames.scales[i] = vec3.create(
outArray[3 * i + 0],
outArray[3 * i + 1],
outArray[3 * i + 2]
);
}
}
}
let animClip = new AnimationClip();
animClip._name = gltfAnimation.name;
animClip._framesList = framesList;
animClip._length = maxLength;
return animClip;
}
/**
* @param {object} gltf
*/
function createJoints(gltf) {
let joints = new Joints();
joints._name = gltf.joints[0].name;
joints._nodes = gltf.joints;
return joints;
}
export default {
createArray,
createNodes,
createEntities,
createMesh,
createSkinning,
createAnimationClip,
createJoints,
};
+178 -122
View File
@@ -1,137 +1,193 @@
import AudioClip from './audio-clip';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const { ccclass } = _decorator;
import { AudioClip, AudioSourceType, PlayingState } from "./audio-clip";
@ccclass
export default class WebAudioClip extends AudioClip {
constructor(context, app) {
super();
this.loadMode = AudioClip.WEB_AUDIO;
this._currentTimer = 0;
this._startTime = 0;
this._offset = 0;
this._loop = false;
this._volume = 1;
/**
* @type {number}
*/
_startTime;
this._app = app;
this._context = context;
this._sourceNode = this._context.createBufferSource();
this._gainNode = this._context.createGain();
this._gainNode.connect(this._context.destination);
/**
* @type {number}
*/
_offset;
this._on_ended = () => {
this._offset = 0;
this._startTime = this._context.currentTime;
if (this._sourceNode.loop) return;
this.emit('ended');
this._state = AudioClip.STOPPED;
};
/**
* @type {number}
*/
_volume;
this._do_play = () => {
this._sourceNode = this._context.createBufferSource();
this._sourceNode.buffer = this._audio;
this._sourceNode.loop = this._loop;
this._sourceNode.connect(this._gainNode);
this._sourceNode.start(0, this._offset);
this._state = AudioClip.PLAYING;
this._startTime = this._context.currentTime;
// delay eval here to yield uniform behavior with other platforms
this._app.once('tick', () => { this.emit('started'); });
/* still not supported by all platforms *
this._sourceNode.onended = this._on_ended;
/* doing it manually for now */
clearInterval(this._currentTimer);
this._currentTimer = setInterval(() => {
this._on_ended();
clearInterval(this._currentTimer);
if (this._sourceNode.loop) {
this._currentTimer = setInterval(this._on_ended, this._audio.duration * 1000);
}
}, (this._audio.duration - this._offset) * 1000);
};
/**
* @type {boolean}
*/
_loop;
this._on_gesture = () => {
this._context.resume().then(() => {
if (this._alreadyDelayed) this._do_play();
window.removeEventListener('touchend', this._on_gesture);
document.removeEventListener('mouseup', this._on_gesture);
});
};
}
/**
* @type {WindowTimers}
*/
_currentTimer;
constructor(context, app) {
super();
setNativeAsset(clip, info) {
super.setNativeAsset(clip, info);
if (this._context.state === 'running') return;
window.addEventListener('touchend', this._on_gesture);
document.addEventListener('mouseup', this._on_gesture);
}
this.loadMode = AudioSourceType.WEB_AUDIO;
this._currentTimer = 0;
this._startTime = 0;
this._offset = 0;
this._loop = false;
this._volume = 1;
play() {
if (!this._audio || this._state === AudioClip.PLAYING) return;
if (this._context.state === 'running') {
this._do_play();
} else this._alreadyDelayed = true;
}
this._app = app;
this._context = context;
this._sourceNode = this._context.createBufferSource();
this._gainNode = this._context.createGain();
this._gainNode.connect(this._context.destination);
pause() {
if (this._state !== AudioClip.PLAYING) return;
this._sourceNode.stop();
this._offset += this._context.currentTime - this._startTime;
this._state = AudioClip.STOPPED;
clearInterval(this._currentTimer);
}
this._on_ended = () => {
this._offset = 0;
this._startTime = this._context.currentTime;
if (this._sourceNode.loop) return;
// @ts-ignore
this.emit('ended');
this._state = PlayingState.STOPPED;
};
stop() {
this._offset = 0;
if (this._state !== AudioClip.PLAYING) return;
this._sourceNode.stop();
this._state = AudioClip.STOPPED;
clearInterval(this._currentTimer);
}
this._do_play = () => {
this._sourceNode = this._context.createBufferSource();
this._sourceNode.buffer = this._audio;
this._sourceNode.loop = this._loop;
this._sourceNode.connect(this._gainNode);
this._sourceNode.start(0, this._offset);
this._state = PlayingState.PLAYING;
this._startTime = this._context.currentTime;
// delay eval here to yield uniform behavior with other platforms
// @ts-ignore
this._app.once('tick', () => { this.emit('started'); });
/* still not supported by all platforms *
this._sourceNode.onended = this._on_ended;
/* doing it manually for now */
clearInterval(this._currentTimer);
this._currentTimer = setInterval(() => {
this._on_ended();
clearInterval(this._currentTimer);
if (this._sourceNode.loop) {
this._currentTimer = setInterval(this._on_ended, this._audio.duration * 1000);
}
}, (this._audio.duration - this._offset) * 1000);
};
playOneShot(volume = 1) {
if (!this._audio) return;
let gainNode = this._context.createGain();
gainNode.connect(this._context.destination);
gainNode.gain.value = volume;
let sourceNode = this._context.createBufferSource();
sourceNode.buffer = this._audio;
sourceNode.loop = false;
sourceNode.connect(gainNode);
sourceNode.start();
}
setCurrentTime(val) {
this._offset = val;
if (this._state !== AudioClip.PLAYING) return;
this._sourceNode.stop(); this._do_play();
}
getCurrentTime() {
if (this._state !== AudioClip.PLAYING) return this._offset;
return this._context.currentTime - this._startTime + this._offset;
}
getDuration() {
return this._audio ? this._audio.duration : 0;
}
setVolume(val) {
this._volume = val;
if (this._gainNode.gain.setTargetAtTime) {
this._gainNode.gain.setTargetAtTime(val, this._context.currentTime, 0.01);
} else {
this._gainNode.gain.value = val;
this._on_gesture = () => {
this._context.resume().then(() => {
if (this._alreadyDelayed) this._do_play();
window.removeEventListener('touchend', this._on_gesture);
document.removeEventListener('mouseup', this._on_gesture);
});
};
}
}
getVolume() {
return this._volume;
}
setNativeAsset(clip, info) {
super.setNativeAsset(clip, info);
if (this._context.state === 'running') return;
window.addEventListener('touchend', this._on_gesture);
document.addEventListener('mouseup', this._on_gesture);
}
setLoop(val) {
this._loop = val;
this._sourceNode.loop = val;
}
play() {
if (!this._audio || this._state === PlayingState.PLAYING) return;
if (this._context.state === 'running') {
this._do_play();
} else this._alreadyDelayed = true;
}
getLoop() {
return this._loop;
}
}
pause() {
if (this._state !== PlayingState.PLAYING) return;
this._sourceNode.stop();
this._offset += this._context.currentTime - this._startTime;
this._state = PlayingState.STOPPED;
clearInterval(this._currentTimer);
}
stop() {
this._offset = 0;
if (this._state !== PlayingState.PLAYING) return;
this._sourceNode.stop();
this._state = PlayingState.STOPPED;
clearInterval(this._currentTimer);
}
playOneShot(volume = 1) {
if (!this._audio) return;
let gainNode = this._context.createGain();
gainNode.connect(this._context.destination);
gainNode.gain.value = volume;
let sourceNode = this._context.createBufferSource();
sourceNode.buffer = this._audio;
sourceNode.loop = false;
sourceNode.connect(gainNode);
sourceNode.start();
}
setCurrentTime(val) {
this._offset = val;
if (this._state !== PlayingState.PLAYING) return;
this._sourceNode.stop(); this._do_play();
}
getCurrentTime() {
if (this._state !== PlayingState.PLAYING) return this._offset;
return this._context.currentTime - this._startTime + this._offset;
}
getDuration() {
return this._audio ? this._audio.duration : 0;
}
setVolume(val) {
this._volume = val;
if (this._gainNode.gain.setTargetAtTime) {
this._gainNode.gain.setTargetAtTime(val, this._context.currentTime, 0.01);
} else {
this._gainNode.gain.value = val;
}
}
getVolume() {
return this._volume;
}
setLoop(val) {
this._loop = val;
this._sourceNode.loop = val;
}
getLoop() {
return this._loop;
}
}
+39 -9
View File
@@ -1,12 +1,40 @@
import AudioClip from './audio-clip';
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
const { ccclass } = _decorator;
import { AudioClip, AudioSourceType, PlayingState } from './audio-clip';
/**
* WeChat audio to port. https://developers.weixin.qq.com/minigame/dev/document/media/audio/InnerAudioContext.html
*/
@ccclass
export default class WxGameAudioClip extends AudioClip {
constructor() {
super();
this.loadMode = AudioClip.WX_GAME_AUDIO;
this.loadMode = AudioSourceType.WX_GAME_AUDIO;
this._volume = 1;
this._loop = false;
this._oneShoting = false;
@@ -28,25 +56,27 @@ export default class WxGameAudioClip extends AudioClip {
_initEventsListener() {
this._audio.onPlay(() => {
this._state = AudioClip.PLAYING;
this._state = PlayingState.PLAYING;
this._currentTime = this._audio.currentTime;
// @ts-ignore
this.emit('started');
});
this._audio.onPause(() => {
this._state = AudioClip.STOPPED;
this._state = PlayingState.STOPPED;
this._oneShoting = false;
});
this._audio.onStop(() => {
this._state = AudioClip.STOPPED;
this._state = PlayingState.STOPPED;
this._oneShoting = false;
this._currentTime = 0;
});
this._audio.onEnded(() => {
this._state = AudioClip.STOPPED;
this._state = PlayingState.STOPPED;
this._currentTime = 0;
// @ts-ignore
this.emit('ended');
if (this._oneShoting) {
this._audio.volume = this._volume;
@@ -57,7 +87,7 @@ export default class WxGameAudioClip extends AudioClip {
}
play() {
if (!this._audio || this._state === AudioClip.PLAYING) {
if (!this._audio || this._state === PlayingState.PLAYING) {
return;
}
@@ -65,7 +95,7 @@ export default class WxGameAudioClip extends AudioClip {
}
pause() {
if (this._state !== AudioClip.PLAYING) {
if (this._state !== PlayingState.PLAYING) {
return;
}
@@ -73,7 +103,7 @@ export default class WxGameAudioClip extends AudioClip {
}
stop() {
if (this._state === AudioClip.STOPPED) {
if (this._state === PlayingState.STOPPED) {
return;
}
+12
View File
@@ -1,5 +1,8 @@
import { utils } from '../scene-graph';
import { vec3, quat, mat4 } from '../vmath';
/**
* @typedef {import("../../scene-graph/CCNode").default} Joint
*/
let _v3_tmp = vec3.create();
let _qt_tmp = quat.create();
@@ -12,8 +15,17 @@ export default class Skeleton {
}
setRoot(root) {
/**
* @type {Joint}
*/
this._root = root;
/**
* @type {Joint[]}
*/
this._joints = utils.flat(this._root);
/**
* @type {mat4[]}
*/
this._matrices = new Array(this._joints.length);
for (let i = 0; i < this._joints.length; ++i) {
+52
View File
@@ -0,0 +1,52 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
//@ts-check
import { _decorator } from "../core/data/index";
const {ccclass, property} = _decorator;
/**
* !#en
* Class for buffer asset.
*
* !#zh
* Buffer 资源类。<br>
*
* @class BufferAsset
* @extends Asset
*/
@ccclass
export class BufferAsset extends cc.Asset {
/**
* @type {ArrayBuffer}
*/
get data() {
return this._data;
}
/**
* @type {ArrayBuffer}
*/
_data = null;
}
+78
View File
@@ -0,0 +1,78 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
//@ts-check
import { _decorator } from "../core/data/index";
const { ccclass, property } = _decorator;
import JsonAsset from "./CCJsonAsset";
import { BufferAsset } from "./CCBufferAsset";
import Asset from "./CCAsset";
/**
* !#en
* Class for GLTF file.
*
* !#zh
* GLTF 资源类。<br>
*
* @class GLTFAsset
* @extends Asset
*/
@ccclass
export class GLTFAsset extends Asset {
/**
* @type {JsonAsset}
*/
@property(JsonAsset)
_description;
/**
* @type {BufferAsset[]}
*/
@property([BufferAsset])
_buffers = [];
/**
* Sets the underlying GlTf file asset.
* @param {JsonAsset} value
*/
set description(value) {
this._description = value;
}
/**
* Gets the underlying GlTf file asset.
* @return {JsonAsset} description
*/
get description() {
return this._description;
}
/**
* The buffers this GLTF Asset associated.
*/
get buffers() {
return this._buffers;
}
}
+1 -1
View File
@@ -46,7 +46,7 @@ export default class JsonAsset extends Asset {
/**
* @property {Object} json - The loaded JSON object.
*/
@property
@property()
json = null;
}
+20 -17
View File
@@ -308,23 +308,26 @@ var ccclass = checkCtorArgument(function (ctor, name) {
* 定义 [CCClass](/docs/creator/scripting/class/) 所用的属性。
*
* @method property
* @param {Object} [options] - an object with some property attributes
* @param {Any} [options.type]
* @param {Boolean|Function} [options.visible]
* @param {String} [options.displayName]
* @param {String} [options.tooltip]
* @param {Boolean} [options.multiline]
* @param {Boolean} [options.readonly]
* @param {Number} [options.min]
* @param {Number} [options.max]
* @param {Number} [options.step]
* @param {Number[]} [options.range]
* @param {Boolean} [options.slide]
* @param {Boolean} [options.serializable]
* @param {Boolean} [options.editorOnly]
* @param {Boolean} [options.override]
* @param {Boolean} [options.animatable]
* @param {String} [options.formerlySerializedAs]
* @param {Object | Function} [ctorProtoOrOptions] - an object with some property attributes
* @param {Any} [ctorProtoOrOptions.type]
* @param {Boolean|Function} [ctorProtoOrOptions.visible]
* @param {String} [ctorProtoOrOptions.displayName]
* @param {String} [ctorProtoOrOptions.tooltip]
* @param {Boolean} [ctorProtoOrOptions.multiline]
* @param {Boolean} [ctorProtoOrOptions.readonly]
* @param {Number} [ctorProtoOrOptions.min]
* @param {Number} [ctorProtoOrOptions.max]
* @param {Number} [ctorProtoOrOptions.step]
* @param {Number[]} [ctorProtoOrOptions.range]
* @param {Boolean} [ctorProtoOrOptions.slide]
* @param {Boolean} [ctorProtoOrOptions.serializable]
* @param {Boolean} [ctorProtoOrOptions.editorOnly]
* @param {Boolean} [ctorProtoOrOptions.override]
* @param {Boolean} [ctorProtoOrOptions.animatable]
* @param {String} [ctorProtoOrOptions.formerlySerializedAs]
* @param {*} [propName]
* @param {*} [desc]
* @return {*}
* @example
* const {ccclass, property} = cc._decorator;
*