import { GameObject, GameObjectBase, GameObjectBaseType, GameObjectData, GameResource, AnimationSchema, FramesData, FrameValue, EasePathValue, } from '@gedit/render-engine'; import { PixiGameScene } from '../../common'; import TweenOne, { ITimelineCallBack, Tween, Plugins } from 'tween-one'; import { AudioGameObject } from './audio'; import { setByKey } from '@gedit/utils/lib/common/objects'; import { EditorGradientPlugin, FillArrayPlugin, LineArrayPlugin, LineDashArrayPlugin, GeditPathMotionPlugin, EditPathMorphArrayPlugin, colorToValue, PathChild, } from '@gedit/canvas-draw'; import { coverData } from '@gedit/utils'; // Ticker.fps(30); // @ts-ignore window.TweenOne = TweenOne; Plugins.push(GeditPathMotionPlugin); Plugins.push(EditorGradientPlugin); Plugins.push(FillArrayPlugin); Plugins.push(LineArrayPlugin); Plugins.push(LineDashArrayPlugin); Plugins.push(EditPathMorphArrayPlugin); const animArrayKeys: { [key: string]: string } = { 'style.color': 'FillArray', 'style.line': 'LineArray', 'style.lineDash': 'LineDashArray', 'path.paths': 'PathMorphArray', }; const animKeys = [ 'EditorGradient', 'FillArray', 'LineArray', 'LineDashArray', 'PathMorphArray', ]; /* const keysObject: any = { 'position.x': 'x', 'position.y': 'y', 'scale.x': 'scaleX', 'scale.y': 'scaleY', 'origin.x': 'originX', 'origin.y': 'originY', }; */ export interface AnimationGameObjectData extends Required { [GameObjectBaseType.ANIMATION]: AnimationSchema; } export interface TimelineCallBack extends Omit { regionTotalTime: number; regionStartTime?: number; regionEndTime?: number; } export interface AnimPathChild extends PathChild { ease?: EasePathValue; } export class AnimationGameObject extends GameObjectBase< AnimationGameObjectData, PixiGameScene > { static type = GameObjectBaseType.ANIMATION; public anim: any; private $onTimelineChange: (e: TimelineCallBack) => void; get onTimelineChange(): (e: TimelineCallBack) => void { return this.$onTimelineChange; } set onTimelineChange(cb: (e: TimelineCallBack) => void) { this.$onTimelineChange = cb; } create(resource: GameResource, children?: GameObject[]): void { super.create.apply(this, arguments); } /** * 场景创建完成后触发自动播放, 避免播放动画节点丢失 */ onSceneCreated(): void { if (!this.scene.config.isIDE) { const data = this.data[GameObjectBaseType.ANIMATION]; if (data.auto) { this.init(data); } } } getGameObjectById(id: string): GameObject | undefined { const store = this.api?.gameObjectStore; if (store) { return store.get(id); } return this.scene.getGameObjectById(id); } init(config?: AnimationSchema): void { const { frames = [] } = config || {}; const data = this.data[GameObjectBaseType.ANIMATION]; if (frames.length) { let nodes: GameObject[] = []; const anim = frames.filter( c => !c.canvasHide && !(c instanceof AudioGameObject) && c.frame?.value?.length ); const onTimelineChangeCallBack = ( node: GameObject, e: ITimelineCallBack ) => { nodes.push(node); if (nodes.length <= anim.length - 1) { return; } const cbNodes = [...nodes]; const { vars, moment, ...common } = e; const regionTotalTime = (data?.regionEndTime || data.totalTime || 0) - (data?.regionStartTime || 0); const newCallBack: TimelineCallBack = { ...common, targets: cbNodes, moment: moment > regionTotalTime ? regionTotalTime : moment, regionTotalTime, regionStartTime: data.regionStartTime, regionEndTime: data.regionEndTime, }; this.$onTimelineChange?.(newCallBack); nodes = []; }; this.anim = frames .filter(c => !c.canvasHide) .map(item => { const node = this.getGameObjectById(item.id); if (!node) { return; } const { frame, displayType } = item; const { componentTime } = frame || {}; if (componentTime) { switch (displayType) { case 'audio': return this.createAudioItem(item, node, config); default: break; } console.warn('没有当前组件'); return; } /* if (!frame.value?.length) { return; } */ return this.createTweenItem( item, node, config, onTimelineChangeCallBack ); }) .filter(c => c); } } protected createTweenItem( item: FramesData, node: GameObject, config?: AnimationSchema, onTimelineChangeCallBack?: (node: GameObject, e: ITimelineCallBack) => void ): Tween { const { frame, pathMotion } = item; const { startTime: cStartTime, totalTime: cTotalTime } = frame || {}; // const renderObject = node?.getRendererObject!(); const { totalTime, regionStartTime = 0, regionEndTime = 0, auto, yoyo, repeat, } = config || {}; const value = (frame.value || []).filter((v: any) => !!v.key) as FrameValue; const animObj: any = {}; const positionValues = value.filter(c => c.key.match(/^position/)); const isPathMotion = !!positionValues.length && positionValues.some(c => 'bezierSV' in c || 'bezierEV' in c); value .slice() .reverse() .forEach((c: any) => { if (c.key.match(/color|fill|stroke/gi) && colorToValue(c.value)) { animObj.EditorGradient = { value: c.value, key: c.key }; } else if (animArrayKeys[c.key]) { animObj[animArrayKeys[c.key]] = { value: c.value, key: c.key }; } else { animObj[c.key] = c.value; } }); const timeObj: { [key: string]: any[] } = {}; (isPathMotion ? value.filter(c => !c.key.match(/^position/)) : value ).forEach((c: any) => { timeObj[c.time] = timeObj[c.time] || []; timeObj[c.time].push(c); }); const timeKeys = Object.keys(timeObj); let animate: any = [ { appearTo: 0, duration: totalTime }, // 时间轴的总时间 ]; // console.log(frame.value); timeKeys.forEach((c, i) => { const tObj = timeObj[c]; tObj.forEach((d: any) => { const a: { [key: string]: any } = {}; const prevObjArr = value.filter((e: any) => e.key === d.key); const prevArr = prevObjArr.filter((e: any) => e.time < d.time); const preObj = prevArr[prevArr.length - 1]; if (d.key.match(/color|fill|stroke/gi) && colorToValue(d.value)) { a.EditorGradient = { value: d.value, key: d.key }; if (preObj) { a.startAt = { EditorGradient: { value: preObj.value, key: preObj.key }, }; } } else if (animArrayKeys[d.key]) { a[animArrayKeys[d.key]] = { value: d.value, key: d.key }; if (preObj) { a.startAt = { [animArrayKeys[d.key]]: { value: preObj.value, ke: preObj.key }, }; } } else { a[d.key] = d.value; if (preObj) { a.startAt = { [d.key]: preObj.value }; } } const sTime = preObj ? preObj.time : d.time; a.duration = parseFloat(c) - sTime; a.appearTo = sTime; if (preObj && preObj.ease) { a.ease = preObj.ease.value === 'custom' ? preObj.ease.path : preObj.ease.value; } else { a.ease = 'linear'; } animate.push(a); }); }); if (isPathMotion) { const paths: AnimPathChild[] = []; positionValues.forEach(c => { const keys = c.key.split('.'); const key = keys[1] as 'x' | 'y'; const inPaths = paths.find(p => p.id === c.time); const path: AnimPathChild = inPaths || ({ id: c.time, } as AnimPathChild); path[key] = c.value || 0; path.ease = c.ease; if ('pathFuncType' in c) { path.type = c.pathFuncType; } if ('bezierSV' in c) { path[`${key}1`] = c.bezierSV; } if ('bezierEV' in c) { path[`${key}2`] = c.bezierEV; } if (!inPaths) { paths.push(path); } }); for (let i = 1; i <= paths.length; i++) { const pre = paths[i - 1]; const current = paths[i]; if (!current || !pre) { continue; } const time = (current.id as number) - (pre.id as number); const sTime = pre.id as number; const a: any = {}; a.duration = time; a.appearTo = sTime; if (pre && pre.ease) { a.ease = pre.ease.value === 'custom' ? pre.ease.path : pre.ease.value; } else { a.ease = 'linear'; } a.GeditPathMotion = { value: [pre, current], rotate: pathMotion.rotation, }; a.startAt = { x: pre.x, y: pre.y, }; animate.push(a); } } animate = animate.filter((c: any) => !c.duration && !c.appearTo ? false : c ); animate.unshift({ ...animObj, duration: 0, appearTo: 0 }); let data = node!.data; const tween = TweenOne(animObj, { animation: animate, repeat, yoyo, paused: !auto, regionStartTime, regionEndTime, onChangeTimeline: (e: any) => { const moment = e.moment - (regionEndTime - regionStartTime) * e.repeat + regionStartTime; if (typeof e.vars === 'object') { Object.keys(e.vars!).forEach((key: any) => { if (animKeys.includes(key)) { data = setByKey( data, e.vars![key].key, e.vars![key].value, true, true ); return; } data = setByKey(data, key, e.vars![key], true, true); }); node!.update(data); } if (e.mode === 'onTimelineComplete') { node?.setVisible(undefined); } // TODO 事件监听后续再加 /* if (config?.onChangeTimeline) { config?.onChangeTimeline(e); } */ const visible = moment >= cStartTime && moment <= cTotalTime + cStartTime; node?.setVisible(visible); onTimelineChangeCallBack?.(node, e); }, }); // @ts-ignore tween.__itemId = item.id; return tween as Tween; } protected createAudioItem( item: any, node?: GameObject, config?: AnimationSchema ): AudioGameObject { const { frame = {} } = item; const { startTime, componentTime } = frame; const audioNode = node as AudioGameObject; const delay = (componentTime.startTime + startTime) / 1000; const id = `render_${this.id}`; audioNode.markerDelay[id] = delay; if (delay >= 0) { audioNode.createMarker({ tag: { start: componentTime.startTime / 1000, duration: Math.min( (config?.totalTime || 0) - componentTime.startTime - startTime, componentTime.totalTime ) / 1000, }, param: audioNode.data.audio, markerName: id, }); if (config?.auto) { audioNode.play({ delay, sprite: id }); } } return audioNode; } play(): void { if (!this.anim) { this.init(this.data[GameObjectBaseType.ANIMATION]); } this.anim.forEach((item: any) => { if (item instanceof AudioGameObject) { const id = `render_${this.id}`; item.play({ delay: item.markerDelay[id], sprite: id }); return; } item.paused = false; }); } pause(): void { if (!this.anim) { return; } this.anim.forEach((item: any) => { if (item instanceof AudioGameObject) { item.pause(); return; } item.paused = true; }); } reverse(): void { if (!this.anim) { return; } this.anim.forEach((item: any) => { if (item instanceof AudioGameObject) { console.log('auto not support reverse.'); return; } item.reverse = true; }); return; } goto(moment: number, paused?: boolean): void { if (!this.anim) { return; } this.anim.forEach((item: any) => { if (item instanceof AudioGameObject) { // console.log('auto not support goto.'); return; } item.goto(moment, paused); }); } replay(): void { this.goto(0, true); this.play(); } dispose(): void { if (this.anim) { this.anim.forEach((item: any) => { if (item instanceof AudioGameObject) { item.dispose(); return; } item.kill(); }); } super.dispose(); } updateAnimVisible(id: string, visible: boolean): void { const node = this.getGameObjectById(id); // console.log(id, node, visible); node?.setVisible(visible); } setVisible(): void {} setDepth(): void {} update(data: AnimationGameObjectData): void { super.update(data); if (this.scene.config.isIDE) { const frames = data[GameObjectBaseType.ANIMATION].frames; frames.forEach((frame: FramesData) => { const item = this.scene.getGameObjectById(frame.id); if (item) { const animData = {}; let d = item.data; if ( !( frame.frame.current && d.useAnimationId && this.id.match(d.useAnimationId) ) ) { return; } Object.keys(frame.frame.current).forEach(c => { setByKey(animData, c, frame.frame.current[c]); }); d = coverData(d, animData); item?.update(d); } }); } } }