diff --git a/cocos/3d/assets/audio/clip.ts b/cocos/3d/assets/audio/clip.ts new file mode 100644 index 0000000000..8687fc8743 --- /dev/null +++ b/cocos/3d/assets/audio/clip.ts @@ -0,0 +1,100 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +import { Asset } from '../../../assets/asset'; +import { ccclass, property } from '../../../core/data/class-decorator'; +import { EventTargetFactory } from '../../../core/event/event-target-factory'; +import { AudioPlayer, PlayingState } from './player'; +import { AudioPlayerDOM } from './player-dom'; +import { AudioPlayerWeb } from './player-web'; + +export const AudioType = { + UNKNOWN_AUDIO: -1, + WEB_AUDIO: 0, + DOM_AUDIO: 1, + WX_GAME_AUDIO: 2, +}; + +@ccclass('cc.AudioClip') +export class AudioClip extends EventTargetFactory(Asset) { + + public set _nativeAsset (clip: any) { + this._audio = clip; + if (clip) { + let ctor: any; + if (clip instanceof AudioBuffer) { + ctor = AudioPlayerWeb; + this._loadMode = AudioType.WEB_AUDIO; + } else { + ctor = AudioPlayerDOM; + this._loadMode = AudioType.DOM_AUDIO; + } + this._player = new ctor({ clip, duration: this._duration, eventTarget: this }); + this.loaded = true; + this.emit('load'); + } else { + this._player = null; + this._loadMode = AudioType.UNKNOWN_AUDIO; + this._duration = 0; + this.loaded = false; + } + } + + public get _nativeAsset () { + return this._audio; + } + + get loadMode () { + return this._loadMode; + } + + get state () { + return this._player ? this._player.getState() : PlayingState.INITIALIZING; + } + + public static PlayingState = PlayingState; + public static AudioType = AudioType; + @property // we serialize this because it's unavailable at runtime on some platforms + protected _duration = 0; + @property(AudioType) + protected _loadMode = AudioType.UNKNOWN_AUDIO; + + private _audio: any = null; + private _player: AudioPlayer | null = null; + + public play () { if (this._player) { this._player.play(); } } + public pause () { if (this._player) { this._player.pause(); } } + public stop () { if (this._player) { this._player.stop(); } } + public playOneShot (volume: number) { if (this._player) { this._player.playOneShot(volume); } } + public setCurrentTime (val: number) { if (this._player) { this._player.setCurrentTime(val); } } + public getCurrentTime () { if (this._player) { return this._player.getCurrentTime(); } return 0; } + public getDuration () { if (this._player) { return this._player.getDuration(); } return this._duration; } + public setVolume (val: number) { if (this._player) { this._player.setVolume(val); } } + public getVolume () { if (this._player) { return this._player.getVolume(); } return 1; } + public setLoop (val: boolean) { if (this._player) { this._player.setLoop(val); } } + public getLoop () { if (this._player) { return this._player.getLoop(); } return false; } +} + +cc.AudioClip = AudioClip; diff --git a/cocos/3d/assets/dom-audio-clip.ts b/cocos/3d/assets/audio/player-dom.ts similarity index 87% rename from cocos/3d/assets/dom-audio-clip.ts rename to cocos/3d/assets/audio/player-dom.ts index 3f5c7402f0..65ccee6869 100644 --- a/cocos/3d/assets/dom-audio-clip.ts +++ b/cocos/3d/assets/audio/player-dom.ts @@ -23,29 +23,26 @@ THE SOFTWARE. ****************************************************************************/ -import { ccclass } from '../../core/data/class-decorator'; -import { AudioClip, AudioSourceType, IAudioInfo, PlayingState } from './audio-clip'; +import { AudioPlayer, IAudioInfo, PlayingState } from './player'; -@ccclass('cc.DOMAudioClip') -export class DOMAudioClip extends AudioClip { +export class AudioPlayerDOM extends AudioPlayer { protected _volume = 1; protected _loop = false; protected _currentTimer = 0; protected _oneShoting = false; - protected _audio: HTMLAudioElement | null = null; + protected _audio: HTMLAudioElement; private _post_play: () => void; private _on_gesture: () => void; private _alreadyDelayed = false; - constructor () { - super(); - - this._loadMode = AudioSourceType.DOM_AUDIO; + constructor (info: IAudioInfo) { + super(info); + this._audio = info.clip; this._post_play = () => { this._state = PlayingState.PLAYING; - this.emit('started'); + this._eventTarget.emit('started'); }; this._on_gesture = () => { @@ -62,19 +59,15 @@ export class DOMAudioClip extends AudioClip { document.removeEventListener('mouseup', this._on_gesture); }); }; - } - public setNativeAsset (clip: HTMLAudioElement) { - super._nativeAsset = clip; - clip.volume = this._volume; - clip.loop = this._loop; + this._audio.volume = this._volume; + this._audio.loop = this._loop; // callback on audio ended - clip.addEventListener('ended', () => { + this._audio.addEventListener('ended', () => { if (this._oneShoting) { return; } this._state = PlayingState.STOPPED; - clip.currentTime = 0; - // @ts-ignore - this.emit('ended'); + this._audio!.currentTime = 0; + this._eventTarget.emit('ended'); }); /* play & stop immediately after receiving a gesture so that we can freely invoke play() outside event listeners later */ @@ -164,5 +157,3 @@ export class DOMAudioClip extends AudioClip { return this._loop; } } - -cc.DOMAudioClip = DOMAudioClip; diff --git a/cocos/3d/assets/web-audio-clip.ts b/cocos/3d/assets/audio/player-web.ts similarity index 91% rename from cocos/3d/assets/web-audio-clip.ts rename to cocos/3d/assets/audio/player-web.ts index 865a0ee2e4..8fe28e89f7 100644 --- a/cocos/3d/assets/web-audio-clip.ts +++ b/cocos/3d/assets/audio/player-web.ts @@ -23,11 +23,12 @@ THE SOFTWARE. ****************************************************************************/ -import { ccclass } from '../../core/data/class-decorator'; -import { AudioClip, AudioSourceType, IAudioInfo, PlayingState } from './audio-clip'; +import sys from '../../../core/platform/CCSys'; +import { AudioPlayer, IAudioInfo, PlayingState } from './player'; -@ccclass('cc.WebAudioClip') -export default class WebAudioClip extends AudioClip { +const audioSupport = sys.__audioSupport; + +export class AudioPlayerWeb extends AudioPlayer { protected _startTime = 0; protected _offset = 0; protected _volume = 1; @@ -43,12 +44,11 @@ export default class WebAudioClip extends AudioClip { private _on_gesture: () => void; private _alreadyDelayed = false; - constructor (context: AudioContext) { - super(); + constructor (info: IAudioInfo) { + super(info); + this._audio = info.clip; - this._loadMode = AudioSourceType.WEB_AUDIO; - - this._context = context; + this._context = audioSupport.context; this._sourceNode = this._context.createBufferSource(); this._gainNode = this._context.createGain(); this._gainNode.connect(this._context.destination); @@ -57,8 +57,7 @@ export default class WebAudioClip extends AudioClip { this._offset = 0; this._startTime = this._context.currentTime; if (this._sourceNode.loop) { return; } - // @ts-ignore - this.emit('ended'); + this._eventTarget.emit('ended'); this._state = PlayingState.STOPPED; }; @@ -71,7 +70,7 @@ export default class WebAudioClip extends AudioClip { this._state = PlayingState.PLAYING; this._startTime = this._context.currentTime; // delay eval here to yield uniform behavior with other platforms - cc.director.once(cc.Director.EVENT_AFTER_UPDATE, () => { this.emit('started'); }); + cc.director.once(cc.Director.EVENT_AFTER_UPDATE, () => { this._eventTarget.emit('started'); }); /* still not supported by all platforms * this._sourceNode.onended = this._on_ended; /* doing it manually for now */ @@ -92,10 +91,7 @@ export default class WebAudioClip extends AudioClip { document.removeEventListener('mouseup', this._on_gesture); }); }; - } - public set _nativeAsset (clip: AudioBuffer) { - super._nativeAsset = clip; if (this._context.state === 'running') { return; } window.addEventListener('touchend', this._on_gesture); document.addEventListener('mouseup', this._on_gesture); @@ -173,5 +169,3 @@ export default class WebAudioClip extends AudioClip { return this._loop; } } - -cc.WebAudioClip = WebAudioClip; diff --git a/cocos/3d/assets/wx-game-audio-clip.js b/cocos/3d/assets/audio/player-wx.js similarity index 96% rename from cocos/3d/assets/wx-game-audio-clip.js rename to cocos/3d/assets/audio/player-wx.js index 534495dfe0..b461d8bca7 100644 --- a/cocos/3d/assets/wx-game-audio-clip.js +++ b/cocos/3d/assets/audio/player-wx.js @@ -25,7 +25,7 @@ // @ts-check import { _decorator } from "../../core/data/index"; const { ccclass } = _decorator; -import { AudioClip, AudioSourceType, PlayingState } from './audio-clip'; +import { AudioClip, AudioType, PlayingState } from './audio-clip'; /** * WeChat audio to port. https://developers.weixin.qq.com/minigame/dev/document/media/audio/InnerAudioContext.html @@ -34,7 +34,7 @@ import { AudioClip, AudioSourceType, PlayingState } from './audio-clip'; export default class WxGameAudioClip extends AudioClip { constructor() { super(); - this.loadMode = AudioSourceType.WX_GAME_AUDIO; + this.loadMode = AudioType.WX_GAME_AUDIO; this._volume = 1; this._loop = false; this._oneShoting = false; @@ -153,4 +153,4 @@ export default class WxGameAudioClip extends AudioClip { } } -cc.WxGameAudioClip = WxGameAudioClip; \ No newline at end of file +cc.WxGameAudioClip = WxGameAudioClip; diff --git a/cocos/3d/assets/audio-clip.ts b/cocos/3d/assets/audio/player.ts similarity index 53% rename from cocos/3d/assets/audio-clip.ts rename to cocos/3d/assets/audio/player.ts index 59ec525c31..9e232091eb 100644 --- a/cocos/3d/assets/audio-clip.ts +++ b/cocos/3d/assets/audio/player.ts @@ -23,64 +23,38 @@ THE SOFTWARE. ****************************************************************************/ -import { Asset } from '../../assets/asset'; -import { ccclass, property } from '../../core/data/class-decorator'; -import { EventTargetFactory } from '../../core/event/event-target-factory'; - export const PlayingState = { INITIALIZING: 0, PLAYING: 1, STOPPED: 2, }; -export const AudioSourceType = { - UNKNOWN_AUDIO: -1, - /** - * load through Web Audio API interface - */ - WEB_AUDIO: 0, - /** - * load through an audio DOM element - */ - DOM_AUDIO: 1, - - WX_GAME_AUDIO: 2, -}; - -@ccclass('cc.AudioClip') -export class AudioClip extends EventTargetFactory(Asset) { - protected _audio: any = null; - protected _state = PlayingState.INITIALIZING; - - @property // we serialize this because it's unavailable at runtime on some platforms - protected _duration = 0; - - @property(AudioSourceType) - protected _loadMode = AudioSourceType.UNKNOWN_AUDIO; - - public set _nativeAsset (clip: any) { - this._audio = clip; - if (clip) { - this.loaded = true; - this.emit('load'); - this._state = PlayingState.STOPPED; - } else { - this.loaded = false; - this._state = PlayingState.INITIALIZING; - this._duration = 0; - } - } - public get _nativeAsset () { - return this._audio; - } - - get loadMode () { - return this._loadMode; - } - - get state () { - return this._state; - } +export interface IAudioInfo { + clip: any; + duration: number; + eventTarget: any; } -cc.AudioClip = AudioClip; +export abstract class AudioPlayer { + protected _state = PlayingState.STOPPED; + protected _duration = 0; + protected _eventTarget: any; + + constructor (info: IAudioInfo) { + this._duration = info.duration; + this._eventTarget = info.eventTarget; + } + + public abstract play (): void; + public abstract pause (): void; + public abstract stop (): void; + public abstract playOneShot (volume: number): void; + public abstract setCurrentTime (val: number): void; + public abstract getCurrentTime (): number; + public abstract getDuration (): number; + public abstract setVolume (val: number): void; + public abstract getVolume (): number; + public abstract setLoop (val: boolean): void; + public abstract getLoop (): boolean; + public getState () { return this._state; } +} diff --git a/cocos/3d/assets/index.js b/cocos/3d/assets/index.js index 4cc366051f..1b4749241e 100644 --- a/cocos/3d/assets/index.js +++ b/cocos/3d/assets/index.js @@ -24,8 +24,7 @@ ****************************************************************************/ export { default as AnimationClip } from "./animation-clip"; -export { AudioClip } from "./audio-clip"; -export { DOMAudioClip } from "./dom-audio-clip"; +export { AudioClip } from "./audio/clip"; export { BitmapFont } from "./bitmap-font"; export { EffectAsset } from "./effect-asset"; export { Material } from "./material"; @@ -33,7 +32,5 @@ export { Mesh } from "./mesh"; export { default as OpentypeFont } from "./opentype-font"; export { default as Skeleton } from "./skeleton"; export { default as Sprite } from "./sprite"; -export { default as WebAudioClip } from "./web-audio-clip"; -export { default as WxGameAudioClip } from "./wx-game-audio-clip"; export { PhysicsMaterial } from './physics/material'; diff --git a/cocos/3d/framework/animation-component.ts b/cocos/3d/framework/animation-component.ts index aa7f1dbc02..9cd59cd4f3 100644 --- a/cocos/3d/framework/animation-component.ts +++ b/cocos/3d/framework/animation-component.ts @@ -267,7 +267,7 @@ class AnimationCtrl { @executionOrder(99) @executeInEditMode @menu('Components/AnimationComponent') -export default class AnimationComponent extends Component { +export class AnimationComponent extends Component { @property({ type: [AnimationClip] }) public _clips: AnimationClip[] = []; diff --git a/cocos/3d/framework/audio-source-component.ts b/cocos/3d/framework/audio-source-component.ts new file mode 100644 index 0000000000..cd2de55111 --- /dev/null +++ b/cocos/3d/framework/audio-source-component.ts @@ -0,0 +1,190 @@ +/**************************************************************************** + 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. + ****************************************************************************/ +import { Component } from '../../components/component'; +import { ccclass, property } from '../../core/data/class-decorator'; +import { AudioClip } from '../assets/audio/clip'; + +/** + * A representation of a single audio source, + * contains basic functionalities like play, pause and stop. + */ +@ccclass('cc.AudioSourceComponent') +export class AudioSourceComponent extends Component { + @property(AudioClip) + protected _clip: AudioClip | null = null; + @property + protected _loop = false; + @property + protected _playOnAwake = true; + @property + protected _volume = 1; + + private _cachedCurrentTime = 0; + + /** + * The default AudioClip to play + */ + @property({ type: AudioClip }) + set clip (val) { + this._clip = val; + this._syncStates(); + } + get clip () { + return this._clip; + } + + /** + * Is the audio clip looping? + */ + @property({ type: Boolean }) + set loop (val) { + this._loop = val; + if (this._clip) { this._clip.setLoop(val); } + } + get loop () { + return this._loop; + } + + /** + * Is the autoplay enabled? + * Note that for the most time now the autoplay will only starts + * after a user gesture is received, according to the latest autoplay policy: + * https://www.chromium.org/audio-video/autoplay + */ + @property({ type: Boolean }) + set playOnAwake (val) { + this._playOnAwake = val; + } + get playOnAwake () { + return this._playOnAwake; + } + + /** + * The volume of this audio source (0.0 to 1.0). + */ + @property({ type: Number }) + set volume (val) { + if (this._clip) { + this._clip.setVolume(val); + // on some platform volume control may not be available + this._volume = this._clip.getVolume(); + } else { + this._volume = val; + } + } + get volume () { + return this._volume; + } + + public onLoad () { + this._syncStates(); + } + + /** + * Plays the clip + */ + public play () { + if (!this._clip) { return; } + if (this.playing) { this.currentTime = 0; } + else { this._clip.play(); } + } + + /** + * Pause the clip + */ + public pause () { + if (!this._clip) { return; } + this._clip.pause(); + } + + /** + * Stop the clip + */ + public stop () { + if (!this._clip) { return; } + this._clip.stop(); + } + + /** + * Plays an AudioClip, and scales volume by volumeScale. + * @param clip - the clip being played + * @param volumeScale - the scale of the volume (0-1). + */ + public playOneShot (clip: AudioClip, volumeScale = 1) { + clip.playOneShot(this._volume * volumeScale); + } + + protected _syncStates () { + if (!this._clip) { return; } + this._clip.setCurrentTime(this._cachedCurrentTime); + this._clip.setLoop(this._loop); + this.volume = this._volume; + if (this._playOnAwake) { this.play(); } + } + + /** + * set current playback time, in seconds + * @param num the playback time you want to jump to + */ + set currentTime (num: number) { + this._cachedCurrentTime = num; + if (!this._clip) { return; } + this._clip.setCurrentTime(this._cachedCurrentTime); + } + + /** + * get the current playback time, in seconds + * @returns time current playback time + */ + get currentTime () { + if (!this._clip) { return this._cachedCurrentTime; } + return this._clip.getCurrentTime(); + } + + /** + * get the audio duration, in seconds + * @returns audio duration + */ + get duration () { + if (!this._clip) { return 0; } + return this._clip.getDuration(); + } + + /** + * get current audio state + * @returns current audio state + */ + get state () { + if (!this._clip) { return AudioClip.PlayingState.INITIALIZING; } + return this._clip.state; + } + + /** + * is the audio currently playing? + */ + get playing () { + return this.state === AudioClip.PlayingState.PLAYING; + } +} diff --git a/cocos/3d/framework/index.ts b/cocos/3d/framework/index.ts index 41e013a3b4..8d22c0c3fd 100644 --- a/cocos/3d/framework/index.ts +++ b/cocos/3d/framework/index.ts @@ -24,38 +24,42 @@ THE SOFTWARE. ****************************************************************************/ -import AnimationComponent from './animation-component'; +import { AnimationComponent } from './animation-component'; +import { AudioSourceComponent } from './audio-source-component'; import { CameraComponent } from './camera-component'; -import LightComponent from './light-component'; +import { LightComponent } from './light-component'; import { ModelComponent } from './model-component'; +import { ParticleSystemComponent } from './particle/particle-system-component'; import { BoxColliderComponent, SphereColliderComponent } from './physics/collider-component'; import { RigidBodyComponent } from './physics/rigid-body-component'; -import SkinningModelComponent from './skinning-model-component'; -import SkyboxComponent from './skybox-component'; +import { SkinningModelComponent } from './skinning-model-component'; +import { SkyboxComponent } from './skybox-component'; export * from './physics'; -import ParticleSystemComponent from './particle/particle-system-component'; export { - CameraComponent, AnimationComponent, + AudioSourceComponent, + CameraComponent, LightComponent, ModelComponent, SkinningModelComponent, SkyboxComponent, + BoxColliderComponent, - SphereColliderComponent, - RigidBodyComponent, ParticleSystemComponent, + RigidBodyComponent, + SphereColliderComponent, }; -cc.CameraComponent = CameraComponent; cc.AnimationComponent = AnimationComponent; +cc.AudioSourceComponent = AudioSourceComponent; +cc.CameraComponent = CameraComponent; cc.LightComponent = LightComponent; cc.ModelComponent = ModelComponent; cc.SkinningModelComponent = SkinningModelComponent; cc.SkyboxComponent = SkyboxComponent; -cc.RigidBodyComponent = RigidBodyComponent; cc.BoxColliderComponent = BoxColliderComponent; -cc.SphereColliderComponent = SphereColliderComponent; cc.ParticleSystemComponent = ParticleSystemComponent; +cc.RigidBodyComponent = RigidBodyComponent; +cc.SphereColliderComponent = SphereColliderComponent; diff --git a/cocos/3d/framework/light-component.ts b/cocos/3d/framework/light-component.ts index 79089a0d94..81ace6dc80 100644 --- a/cocos/3d/framework/light-component.ts +++ b/cocos/3d/framework/light-component.ts @@ -115,7 +115,7 @@ const LightShadowType = Enum({ @ccclass('cc.LightComponent') @menu('Components/LightComponent') @executeInEditMode -export default class LightComponent extends Component { +export class LightComponent extends Component { public static Type = Type; public static ShadowType = LightShadowType; diff --git a/cocos/3d/framework/particle/particle-system-component.ts b/cocos/3d/framework/particle/particle-system-component.ts index 90bc516f6a..17f008e87e 100644 --- a/cocos/3d/framework/particle/particle-system-component.ts +++ b/cocos/3d/framework/particle/particle-system-component.ts @@ -27,7 +27,7 @@ const _world_mat = mat4.create(); @requireComponent(ParticleSystemRenderer) @executionOrder(99) @executeInEditMode -export default class ParticleSystemComponent extends Component { +export class ParticleSystemComponent extends Component { @property public capacity = 2000; diff --git a/cocos/3d/framework/skinning-model-component.ts b/cocos/3d/framework/skinning-model-component.ts index 50d5a12183..8fdf4ee432 100644 --- a/cocos/3d/framework/skinning-model-component.ts +++ b/cocos/3d/framework/skinning-model-component.ts @@ -45,7 +45,7 @@ type SkinningTarget = Map; @executionOrder(100) @executeInEditMode @menu('Components/SkinningModelComponent') -export default class SkinningModelComponent extends ModelComponent { +export class SkinningModelComponent extends ModelComponent { /** * !#en The bone nodes diff --git a/cocos/3d/framework/skybox-component.ts b/cocos/3d/framework/skybox-component.ts index a94c958794..c99dedecf1 100644 --- a/cocos/3d/framework/skybox-component.ts +++ b/cocos/3d/framework/skybox-component.ts @@ -44,7 +44,7 @@ import { box } from '../primitive'; @ccclass('cc.SkyboxComponent') @menu('Components/SkyboxComponent') @executeInEditMode -export default class SkyboxComponent extends Component { +export class SkyboxComponent extends Component { @property({ type: TextureCube, diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts index 2df4d22f2b..310a6d38af 100644 --- a/cocos/3d/ui/components/canvas-component.ts +++ b/cocos/3d/ui/components/canvas-component.ts @@ -27,10 +27,9 @@ import { CameraComponent } from '../../../3d/framework/camera-component'; import { Component } from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator'; -import { Color, Rect, Size, Vec3 } from '../../../core/value-types'; +import { Size, Vec3 } from '../../../core/value-types'; import { GFXClearFlag } from '../../../gfx/define'; import { Camera } from '../../../renderer/scene/camera'; -import { Node } from '../../../scene-graph/node'; const _tempPos = new Vec3(); const _worldPos = new Vec3(); @@ -169,7 +168,7 @@ export class CanvasComponent extends Component { } public __preload () { - const cameraNode = new Node('UICamera'); + const cameraNode = new cc.Node('UICamera'); cameraNode.setPosition(0, 0, 1000); if (!CC_EDITOR) { this._camera = cc.director.root.ui.renderScene.createCamera({ @@ -189,7 +188,6 @@ export class CanvasComponent extends Component { this._camera!.resize(device.width, device.height); } - cc.director.root.ui.addScreen(this); // if (CC_DEV) { diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/3d/ui/components/ui-transfrom-component.ts index ed77c6a045..90449e4ce4 100644 --- a/cocos/3d/ui/components/ui-transfrom-component.ts +++ b/cocos/3d/ui/components/ui-transfrom-component.ts @@ -3,8 +3,6 @@ import { ccclass, executeInEditMode, executionOrder, menu, property } from '../. import { Mat4, Rect, Size, Vec2, Vec3 } from '../../../core/value-types'; import * as math from '../../../core/vmath/index'; import { EventType } from '../../../scene-graph/node-event-enum'; -import { MaskComponent } from './mask-component'; -import { UIRenderComponent } from './ui-render-component'; const _vec2a = new Vec2(); const _vec2b = new Vec2(); @@ -201,7 +199,7 @@ export class UITransformComponent extends Component { const cameraPt = _vec2a; const testPt = _vec2b; - const renderComp = this.node.getComponent(UIRenderComponent); + const renderComp = this.node.getComponent(cc.UIRenderComponent) as any; if (!renderComp) { return false; } diff --git a/cocos/3d/ui/components/widget-component.ts b/cocos/3d/ui/components/widget-component.ts index ee0d61bfe2..4766c7d747 100644 --- a/cocos/3d/ui/components/widget-component.ts +++ b/cocos/3d/ui/components/widget-component.ts @@ -24,7 +24,6 @@ THE SOFTWARE. ****************************************************************************/ -import { widgetManager } from './widget-manager'; import { Component} from '../../../components/component'; import { ccclass, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../../core/data/class-decorator'; import { Node } from '../../../scene-graph/index'; @@ -115,7 +114,7 @@ export class WidgetComponent extends Component { this._target = value; if (CC_EDITOR /*&& !cc.engine._isPlaying*/ && this.node.parent) { // adjust the offsets to keep the size and position unchanged after target chagned - widgetManager.updateOffsetsToStayPut(this); + cc._widgetManager.updateOffsetsToStayPut(this); } } @@ -562,7 +561,7 @@ export class WidgetComponent extends Component { * cc.log(widget.node.y); // changed */ public updateAlignment () { - widgetManager.updateAlignment(this.node); + cc._widgetManager.updateAlignment(this.node); } protected onLoad () { @@ -579,11 +578,11 @@ export class WidgetComponent extends Component { } protected onEnable () { - widgetManager.add(this); + cc._widgetManager.add(this); } protected onDisable () { - widgetManager.remove(this); + cc._widgetManager.remove(this); } private _setAlign (flag: AlignFlags, isAlign: boolean) { @@ -619,7 +618,7 @@ export class WidgetComponent extends Component { if (CC_EDITOR && !cc.engine._isPlaying && this.node.parent) { // adjust the offsets to keep the size and position unchanged after alignment chagned - widgetManager.updateOffsetsToStayPut(this, flag); + cc._widgetManager.updateOffsetsToStayPut(this, flag); } } else { if (isHorizontal) { diff --git a/cocos/audio/CCAudio.js b/cocos/audio/CCAudio.js deleted file mode 100644 index 568120454c..0000000000 --- a/cocos/audio/CCAudio.js +++ /dev/null @@ -1,505 +0,0 @@ -/**************************************************************************** - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - 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. - ****************************************************************************/ - -const EventTarget = require('../core/event/event-target'); -const sys = require('../core/platform/CCSys'); -const LoadMode = require('../core/assets/CCAudioClip').LoadMode; - -let touchBinded = false; -let touchPlayList = [ - //{ instance: Audio, offset: 0, audio: audio } -]; - -let Audio = function (src) { - EventTarget.call(this); - - this._src = src; - this._element = null; - this.id = 0; - - this._volume = 1; - this._loop = false; - this._nextTime = 0; // playback position to set - - this._state = Audio.State.INITIALZING; - - this._onended = function () { - this.emit('ended'); - }.bind(this); -}; - -cc.js.extend(Audio, EventTarget); - -/** - * !#en Audio state. - * !#zh 声音播放状态 - * @enum audioEngine.AudioState - * @memberof cc - */ -// TODO - At present, the state is mixed with two states of users and systems, and it is best to split into two types. A "loading" should also be added to the system state. -Audio.State = { - /** - * @property {Number} ERROR - */ - ERROR : -1, - /** - * @property {Number} INITIALZING - */ - INITIALZING: 0, - /** - * @property {Number} PLAYING - */ - PLAYING: 1, - /** - * @property {Number} PAUSED - */ - PAUSED: 2, - /** - * @property {Number} STOPPED - */ - STOPPED: 3, -}; - -(function (proto) { - - proto._bindEnded = function (callback) { - callback = callback || this._onended; - let elem = this._element; - if (this._src && (elem instanceof HTMLAudioElement)) { - elem.addEventListener('ended', callback); - } else { - elem.onended = callback; - } - }; - - proto._unbindEnded = function () { - let elem = this._element; - if (elem instanceof HTMLAudioElement) { - elem.removeEventListener('ended', this._onended); - } else if (elem) { - elem.onended = null; - } - }; - - // proto.mount = function (elem) { - // if (CC_DEBUG) { - // cc.warn('Audio.mount(value) is deprecated. Please use Audio._onLoaded().'); - // } - // }; - - proto._onLoaded = function () { - let elem = this._src._nativeAsset; - if (elem instanceof HTMLAudioElement) { - // Reuse dom audio element - if (!this._element) { - this._element = document.createElement('audio'); - } - this._element.src = elem.src; - } - else { - this._element = new WebAudioElement(elem, this); - } - - this.setVolume(this._volume); - this.setLoop(this._loop); - if (this._nextTime !== 0) { - this.setCurrentTime(this._nextTime); - } - if (this._state === Audio.State.PLAYING) { - this.play(); - } - else { - this._state = Audio.State.INITIALZING; - } - }; - - proto.play = function () { - // marked as playing so it will playOnLoad - this._state = Audio.State.PLAYING; - - if (!this._element) { - return; - } - - this._bindEnded(); - this._element.play(); - - if (!CC_QQPLAY && !CC_WECHATGAME) { - if (this._src && this._src.loadMode === LoadMode.DOM_AUDIO && - this._element.paused) { - touchPlayList.push({ instance: this, offset: 0, audio: this._element }); - } - - if (touchBinded) return; - touchBinded = true; - - // Listen to the touchstart body event and play the audio when necessary. - cc.game.canvas.addEventListener('touchstart', function () { - let item; - while (item = touchPlayList.pop()) { - item.audio.play(item.offset); - } - }); - } - }; - - proto.destroy = function () { - if (CC_WECHATGAME) { - this._element && this._element.destroy(); - } - this._element = null; - }; - - proto.pause = function () { - if (!this._element || this._state !== Audio.State.PLAYING) return; - this._unbindEnded(); - this._element.pause(); - this._state = Audio.State.PAUSED; - }; - - proto.resume = function () { - if (!this._element || this._state !== Audio.State.PAUSED) return; - this._bindEnded(); - this._element.play(); - this._state = Audio.State.PLAYING; - }; - - proto.stop = function () { - if (!this._element) return; - this._element.pause(); - try { - this._element.currentTime = 0; - } catch (error) {} - // remove touchPlayList - for (let i = 0; i < touchPlayList.length; i++) { - if (touchPlayList[i].instance === this) { - touchPlayList.splice(i, 1); - break; - } - } - this._unbindEnded(); - this.emit('stop'); - this._state = Audio.State.STOPPED; - }; - - proto.setLoop = function (loop) { - this._loop = loop; - if (this._element) { - this._element.loop = loop; - } - }; - proto.getLoop = function () { - return this._loop; - }; - - proto.setVolume = function (num) { - this._volume = num; - if (this._element) { - this._element.volume = num; - } - }; - proto.getVolume = function () { - return this._volume; - }; - - proto.setCurrentTime = function (num) { - if (this._element) { - this._nextTime = 0; - } - else { - this._nextTime = num; - return; - } - - this._unbindEnded(); - if (!(CC_QQPLAY || CC_WECHATGAME)) { - this._bindEnded(function () { - this._bindEnded(); - }.bind(this)); - } - try { - this._element.currentTime = num; - } - catch (err) { - let _element = this._element; - if (_element.addEventListener) { - let func = function () { - _element.removeEventListener('loadedmetadata', func); - _element.currentTime = num; - }; - _element.addEventListener('loadedmetadata', func); - } - } - }; - proto.getCurrentTime = function () { - return this._element ? this._element.currentTime : 0; - }; - - proto.getDuration = function () { - return this._element ? this._element.duration : 0; - }; - - proto.getState = function () { - if (!CC_WECHATGAME) { - let elem = this._element; - if (elem && Audio.State.PLAYING === this._state && elem.paused) { - this._state = Audio.State.PAUSED; - } - } - return this._state; - }; - - proto.__defineGetter__('src', function () { - return this._src; - }); - proto.__defineSetter__('src', function (clip) { - this._unbindEnded(); - if (clip) { - this._src = clip; - if (clip.loaded) { - this._onLoaded(); - } - else { - let self = this; - clip.once('load', function () { - if (clip === self._src) { - self._onLoaded(); - } - }); - cc.loader.load({ - url: clip.nativeUrl, - // For audio, we should skip loader otherwise it will load a new audioClip. - skips: ['Loader'], - }, - function (err, audioNativeAsset) { - if (err) { - cc.error(err); - return; - } - if (!clip.loaded) { - clip._nativeAsset = audioNativeAsset; - } - }); - } - } - else { - this._src = null; - if (this._element instanceof HTMLAudioElement) { - this._element.src = ''; - } - else { - this._element = null; - } - this._state = Audio.State.INITIALZING; - } - return clip; - }); - - proto.__defineGetter__('paused', function () { - return this._element ? this._element.paused : true; - }); - - // setFinishCallback - -})(Audio.prototype); - -// Encapsulated WebAudio interface -let WebAudioElement = function (buffer, audio) { - this._audio = audio; - this._context = sys.__audioSupport.context; - this._buffer = buffer; - - this._gainObj = this._context['createGain'](); - this._volume = 1; - // https://www.chromestatus.com/features/5287995770929152 - if (this._gainObj['gain'].setTargetAtTime) { - this._gainObj['gain'].setTargetAtTime(this._volume, this._context.currentTime, 0.01); - } else { - this._gainObj['gain'].value = 1; - } - this._gainObj['connect'](this._context['destination']); - - this._loop = false; - // The time stamp on the audio time axis when the recording begins to play. - this._startTime = -1; - // Record the currently playing 'Source' - this._currentSource = null; - // Record the time has been played - this.playedLength = 0; - - this._currextTimer = null; - - this._endCallback = function () { - if (this.onended) { - this.onended(this); - } - }.bind(this); -}; - -(function (proto) { - proto.play = function (offset) { - // If repeat play, you need to stop before an audio - if (this._currentSource && !this.paused) { - this._currentSource.onended = null; - this._currentSource.stop(0); - this.playedLength = 0; - } - - let audio = this._context["createBufferSource"](); - audio.buffer = this._buffer; - audio["connect"](this._gainObj); - audio.loop = this._loop; - - this._startTime = this._context.currentTime; - offset = offset || this.playedLength; - if (offset) { - this._startTime -= offset; - } - let duration = this._buffer.duration; - - let startTime = offset; - let endTime; - if (this._loop) { - if (audio.start) - audio.start(0, startTime); - else if (audio["notoGrainOn"]) - audio["noteGrainOn"](0, startTime); - else - audio["noteOn"](0, startTime); - } else { - endTime = duration - offset; - if (audio.start) - audio.start(0, startTime, endTime); - else if (audio["notoGrainOn"]) - audio["noteGrainOn"](0, startTime, endTime); - else - audio["noteOn"](0, startTime, endTime); - } - - this._currentSource = audio; - - audio.onended = this._endCallback; - - // If the current audio context time stamp is 0 and audio context state is suspended - // There may be a need to touch events before you can actually start playing audio - if ((!audio.context.state || audio.context.state === "suspended") && this._context.currentTime === 0) { - let self = this; - clearTimeout(this._currextTimer); - this._currextTimer = setTimeout(function () { - if (!(CC_QQPLAY || CC_WECHATGAME) && self._context.currentTime === 0) { - touchPlayList.push({ - instance: self._audio, - offset: offset, - audio: self - }); - } - }, 10); - } - }; - - proto.pause = function () { - clearTimeout(this._currextTimer); - if (this.paused) return; - // Record the time the current has been played - this.playedLength = this._context.currentTime - this._startTime; - // If more than the duration of the audio, Need to take the remainder - this.playedLength %= this._buffer.duration; - let audio = this._currentSource; - this._currentSource = null; - this._startTime = -1; - if (audio) - audio.stop(0); - }; - - proto.__defineGetter__('paused', function () { - // If the current audio is a loop, paused is false - if (this._currentSource && this._currentSource.loop) - return false; - - // startTime default is -1 - if (this._startTime === -1) - return true; - - // Current time - Start playing time > Audio duration - return this._context.currentTime - this._startTime > this._buffer.duration; - }); - - proto.__defineGetter__('loop', function () { return this._loop; }); - proto.__defineSetter__('loop', function (bool) { - if (this._currentSource) - this._currentSource.loop = bool; - - return this._loop = bool; - }); - - proto.__defineGetter__('volume', function () { - return this._volume; - }); - proto.__defineSetter__('volume', function (num) { - this._volume = num; - if (this._gainObj['gain'].setTargetAtTime) { - this._gainObj['gain'].setTargetAtTime(this._volume, this._context.currentTime, 0.01); - } else { - this._volume['gain'].value = num; - } - if (sys.os === sys.OS_IOS && !this.paused && this._currentSource) { - // IOS must be stop webAudio - this._currentSource.onended = null; - this.pause(); - this.play(); - } - return num; - }); - - proto.__defineGetter__('currentTime', function () { - if (this.paused) { - return this.playedLength; - } - // Record the time the current has been played - this.playedLength = this._context.currentTime - this._startTime; - // If more than the duration of the audio, Need to take the remainder - this.playedLength %= this._buffer.duration; - return this.playedLength; - }); - proto.__defineSetter__('currentTime', function (num) { - if (!this.paused) { - this.pause(); - this.playedLength = num; - this.play(); - } else { - this.playedLength = num; - } - return num; - }); - - proto.__defineGetter__('duration', function () { - return this._buffer.duration; - }); - -})(WebAudioElement.prototype); - -module.exports = cc.Audio = Audio; diff --git a/cocos/audio/CCAudioClip.js b/cocos/audio/CCAudioClip.js deleted file mode 100644 index 5bbbca5fbf..0000000000 --- a/cocos/audio/CCAudioClip.js +++ /dev/null @@ -1,115 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - 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. - ****************************************************************************/ - -const Asset = require('./CCAsset'); -const EventTarget = require('../event/event-target'); - -var LoadMode = cc.Enum({ - WEB_AUDIO: 0, - DOM_AUDIO: 1, -}); - -/** - * !#en Class for audio data handling. - * !#zh 音频资源类。 - * @class AudioClip - * @extends Asset - * @uses EventTarget - */ -var AudioClip = cc.Class({ - name: 'cc.AudioClip', - extends: Asset, - mixins: [EventTarget], - - ctor () { - this.loaded = false; - - // the web audio buffer or