mirror of
https://github.com/unanmed/HumanBreak.git
synced 2026-11-25 10:36:32 +08:00
refactor: src 除入口外全部移入 monorepo
This commit is contained in:
1 parent
cca10a429c
commit
0679bbb1a5
103 files changed
+340
-252
No files matched your search
+4
-2
@@ -1,10 +1,12 @@
|
||||
import { createApp } from 'vue';
|
||||
import './game/index';
|
||||
import App from './App.vue';
|
||||
import './styles.less';
|
||||
import 'ant-design-vue/dist/antd.dark.css';
|
||||
import { createGame } from '@user/entry-client';
|
||||
|
||||
createApp(App).mount('#root');
|
||||
|
||||
// 创建游戏实例
|
||||
createGame();
|
||||
|
||||
main.init('play');
|
||||
main.listen();
|
||||
@@ -1,165 +0,0 @@
|
||||
import { KeyCode } from '@motajs/client-base';
|
||||
import { Hotkey, HotkeyData } from '@motajs/system-action';
|
||||
import type { HeroMover, IMoveController } from '@user/data-state';
|
||||
import { Ticker } from 'mutate-animate';
|
||||
import { mainScope } from '@motajs/legacy-ui';
|
||||
|
||||
type MoveKey = Record<Dir, HotkeyData>;
|
||||
type MoveKeyConfig = Record<Dir, string>;
|
||||
|
||||
export class HeroKeyMover {
|
||||
/** 当前按下的键 */
|
||||
private pressedKey: Set<Dir> = new Set();
|
||||
/** 当前的移动方向 */
|
||||
private moveDir: Dir = 'down';
|
||||
/** 当前是否正在使用按键移动 */
|
||||
private moving: boolean = false;
|
||||
/** 当前移动的控制器 */
|
||||
private controller?: IMoveController;
|
||||
|
||||
/** 按键接续ticker */
|
||||
private ticker = new Ticker();
|
||||
|
||||
/** 当前移动实例绑定的热键 */
|
||||
hotkey: Hotkey;
|
||||
/** 当前热键的移动按键信息 */
|
||||
hotkeyData: MoveKey;
|
||||
/** 移动实例 */
|
||||
mover: HeroMover;
|
||||
/** 移动可触发的作用域 */
|
||||
scope: symbol = mainScope;
|
||||
|
||||
constructor(hotkey: Hotkey, mover: HeroMover, config?: MoveKeyConfig) {
|
||||
this.hotkey = hotkey;
|
||||
this.mover = mover;
|
||||
hotkey.on('press', this.onPressKey);
|
||||
hotkey.on('release', this.onReleaseKey);
|
||||
|
||||
const data = hotkey.data;
|
||||
|
||||
this.hotkeyData = {
|
||||
left: data[config?.left ?? 'moveLeft'],
|
||||
right: data[config?.right ?? 'moveRight'],
|
||||
up: data[config?.up ?? 'moveUp'],
|
||||
down: data[config?.down ?? 'moveDown']
|
||||
};
|
||||
|
||||
this.ticker.add(() => {
|
||||
if (!this.moving) {
|
||||
if (this.pressedKey.size > 0) {
|
||||
const dir = [...this.pressedKey].at(-1);
|
||||
if (!dir) return;
|
||||
this.moveDir = dir;
|
||||
this.tryStartMove();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private onPressKey = (code: KeyCode) => {
|
||||
if (core.isReplaying() || !core.isPlaying()) return;
|
||||
core.waitHeroToStop();
|
||||
if (code === this.hotkeyData.left.key) this.press('left');
|
||||
else if (code === this.hotkeyData.right.key) this.press('right');
|
||||
else if (code === this.hotkeyData.up.key) this.press('up');
|
||||
else if (code === this.hotkeyData.down.key) this.press('down');
|
||||
};
|
||||
|
||||
private onReleaseKey = (code: KeyCode) => {
|
||||
if (code === this.hotkeyData.left.key) this.release('left');
|
||||
else if (code === this.hotkeyData.right.key) this.release('right');
|
||||
else if (code === this.hotkeyData.up.key) this.release('up');
|
||||
else if (code === this.hotkeyData.down.key) this.release('down');
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置按键触发作用域
|
||||
*/
|
||||
setScope(scope: symbol) {
|
||||
this.scope = scope;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按下某个方向键
|
||||
* @param dir 移动方向
|
||||
*/
|
||||
press(dir: Dir) {
|
||||
if (this.hotkey.scope !== this.scope || core.status.lockControl) return;
|
||||
this.pressedKey.add(dir);
|
||||
this.moveDir = dir;
|
||||
if (!this.moving) {
|
||||
this.tryStartMove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 松开方向键
|
||||
* @param dir 移动方向
|
||||
*/
|
||||
release(dir: Dir) {
|
||||
this.pressedKey.delete(dir);
|
||||
if (this.pressedKey.size > 0) {
|
||||
this.moveDir = [...this.pressedKey][0];
|
||||
} else {
|
||||
this.endMove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试开始移动
|
||||
* @returns 是否成功开始移动
|
||||
*/
|
||||
tryStartMove() {
|
||||
if (this.moving || core.status.lockControl) return false;
|
||||
|
||||
this.mover.oneStep(this.moveDir);
|
||||
const controller = this.mover.startMove(false, false, false, true);
|
||||
if (!controller) return;
|
||||
|
||||
this.controller = controller;
|
||||
controller.onEnd.then(() => {
|
||||
this.moving = false;
|
||||
this.controller = void 0;
|
||||
this.mover.off('stepEnd', this.onStepEnd);
|
||||
});
|
||||
this.moving = true;
|
||||
|
||||
this.mover.on('stepEnd', this.onStepEnd);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止本次按键移动
|
||||
*/
|
||||
endMove() {
|
||||
this.controller?.stop();
|
||||
}
|
||||
|
||||
private onStepEnd = () => {
|
||||
const con = this.controller;
|
||||
if (!con) return;
|
||||
if (core.status.lockControl) {
|
||||
con.stop();
|
||||
return;
|
||||
}
|
||||
if (!this.moving) {
|
||||
con.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.pressedKey.size > 0) {
|
||||
if (con.queue.length === 0) {
|
||||
con.push({ type: 'dir', value: this.moveDir });
|
||||
}
|
||||
} else {
|
||||
con.stop();
|
||||
}
|
||||
};
|
||||
|
||||
destroy() {
|
||||
this.hotkey.off('press', this.onPressKey);
|
||||
this.hotkey.off('release', this.onReleaseKey);
|
||||
this.mover.off('stepEnd', this.onStepEnd);
|
||||
this.ticker.destroy();
|
||||
}
|
||||
}
|
||||
@@ -1,268 +0,0 @@
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { audioPlayer, AudioPlayer, AudioRoute, AudioStatus } from './player';
|
||||
import { guessTypeByExt, isAudioSupport } from './support';
|
||||
import { logger } from '@motajs/common';
|
||||
import { StreamLoader } from '../loader';
|
||||
import { linear, sleep, Transition } from 'mutate-animate';
|
||||
import { VolumeEffect } from './effect';
|
||||
|
||||
interface BgmVolume {
|
||||
effect: VolumeEffect;
|
||||
transition: Transition;
|
||||
}
|
||||
|
||||
interface BgmControllerEvent {
|
||||
play: [];
|
||||
pause: [];
|
||||
resume: [];
|
||||
stop: [];
|
||||
}
|
||||
|
||||
export class BgmController<
|
||||
T extends string = BgmIds
|
||||
> extends EventEmitter<BgmControllerEvent> {
|
||||
/** bgm音频名称的前缀 */
|
||||
prefix: string = 'bgms.';
|
||||
/** 每个 bgm 的音量控制器 */
|
||||
readonly gain: Map<T, BgmVolume> = new Map();
|
||||
|
||||
/** 正在播放的 bgm */
|
||||
playingBgm?: T;
|
||||
/** 是否正在播放 */
|
||||
playing: boolean = false;
|
||||
|
||||
/** 是否已经启用 */
|
||||
enabled: boolean = true;
|
||||
/** 主音量控制器 */
|
||||
private readonly mainGain: VolumeEffect;
|
||||
/** 是否屏蔽所有的音乐切换 */
|
||||
private blocking: boolean = false;
|
||||
/** 渐变时长 */
|
||||
private transitionTime: number = 2000;
|
||||
|
||||
constructor(public readonly player: AudioPlayer) {
|
||||
super();
|
||||
this.mainGain = player.createVolumeEffect();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置音频渐变时长
|
||||
* @param time 渐变时长
|
||||
*/
|
||||
setTransitionTime(time: number) {
|
||||
this.transitionTime = time;
|
||||
for (const [, value] of this.gain) {
|
||||
value.transition.time(time);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 屏蔽音乐切换
|
||||
*/
|
||||
blockChange() {
|
||||
this.blocking = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消屏蔽音乐切换
|
||||
*/
|
||||
unblockChange() {
|
||||
this.blocking = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置总音量大小
|
||||
* @param volume 音量大小
|
||||
*/
|
||||
setVolume(volume: number) {
|
||||
this.mainGain.setVolume(volume);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取总音量大小
|
||||
*/
|
||||
getVolume() {
|
||||
return this.mainGain.getVolume();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置是否启用
|
||||
* @param enabled 是否启用
|
||||
*/
|
||||
setEnabled(enabled: boolean) {
|
||||
if (enabled) this.resume();
|
||||
else this.stop();
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 bgm 音频名称的前缀
|
||||
*/
|
||||
setPrefix(prefix: string) {
|
||||
this.prefix = prefix;
|
||||
}
|
||||
|
||||
private getId(name: T) {
|
||||
return `${this.prefix}${name}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 bgm 名称获取其 AudioRoute 实例
|
||||
* @param id 音频名称
|
||||
*/
|
||||
get(id: T) {
|
||||
return this.player.getRoute(this.getId(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一个 bgm
|
||||
* @param id 要添加的 bgm 的名称
|
||||
* @param url 指定 bgm 的加载地址
|
||||
*/
|
||||
addBgm(id: T, url: string = `project/bgms/${id}`) {
|
||||
const type = guessTypeByExt(id);
|
||||
if (!type) {
|
||||
logger.warn(50, id.split('.').slice(0, -1).join('.'));
|
||||
return;
|
||||
}
|
||||
const gain = this.player.createVolumeEffect();
|
||||
if (isAudioSupport(type)) {
|
||||
const source = audioPlayer.createElementSource();
|
||||
source.setSource(url);
|
||||
source.setLoop(true);
|
||||
const route = new AudioRoute(source, audioPlayer);
|
||||
route.addEffect([gain, this.mainGain]);
|
||||
audioPlayer.addRoute(this.getId(id), route);
|
||||
this.setTransition(id, route, gain);
|
||||
} else {
|
||||
const source = audioPlayer.createStreamSource();
|
||||
const stream = new StreamLoader(url);
|
||||
stream.pipe(source);
|
||||
source.setLoop(true);
|
||||
const route = new AudioRoute(source, audioPlayer);
|
||||
route.addEffect([gain, this.mainGain]);
|
||||
audioPlayer.addRoute(this.getId(id), route);
|
||||
this.setTransition(id, route, gain);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除一个 bgm
|
||||
* @param id 要移除的 bgm 的名称
|
||||
*/
|
||||
removeBgm(id: T) {
|
||||
this.player.removeRoute(this.getId(id));
|
||||
const gain = this.gain.get(id);
|
||||
gain?.transition.ticker.destroy();
|
||||
this.gain.delete(id);
|
||||
}
|
||||
|
||||
private setTransition(id: T, route: AudioRoute, gain: VolumeEffect) {
|
||||
const transition = new Transition();
|
||||
transition
|
||||
.time(this.transitionTime)
|
||||
.mode(linear())
|
||||
.transition('volume', 0);
|
||||
|
||||
const tick = () => {
|
||||
gain.setVolume(transition.value.volume);
|
||||
};
|
||||
|
||||
/**
|
||||
* @param expect 在结束时应该是正在播放还是停止
|
||||
*/
|
||||
const setTick = async (expect: AudioStatus) => {
|
||||
transition.ticker.remove(tick);
|
||||
transition.ticker.add(tick);
|
||||
const identifier = route.stopIdentifier;
|
||||
await sleep(this.transitionTime + 500);
|
||||
if (
|
||||
route.status === expect &&
|
||||
identifier === route.stopIdentifier
|
||||
) {
|
||||
transition.ticker.remove(tick);
|
||||
if (route.status === AudioStatus.Playing) {
|
||||
gain.setVolume(1);
|
||||
} else {
|
||||
gain.setVolume(0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
route.onStart(async () => {
|
||||
transition.transition('volume', 1);
|
||||
setTick(AudioStatus.Playing);
|
||||
});
|
||||
route.onEnd(() => {
|
||||
transition.transition('volume', 0);
|
||||
setTick(AudioStatus.Paused);
|
||||
});
|
||||
route.setEndTime(this.transitionTime);
|
||||
|
||||
this.gain.set(id, { effect: gain, transition });
|
||||
}
|
||||
|
||||
/**
|
||||
* 播放一个 bgm
|
||||
* @param id 要播放的 bgm 名称
|
||||
*/
|
||||
play(id: T, when?: number) {
|
||||
if (this.blocking) return;
|
||||
if (id !== this.playingBgm && this.playingBgm) {
|
||||
this.player.pause(this.getId(this.playingBgm));
|
||||
}
|
||||
this.playingBgm = id;
|
||||
if (!this.enabled) return;
|
||||
this.player.play(this.getId(id), when);
|
||||
this.playing = true;
|
||||
this.emit('play');
|
||||
}
|
||||
|
||||
/**
|
||||
* 继续当前的 bgm
|
||||
*/
|
||||
resume() {
|
||||
if (this.blocking || !this.enabled || this.playing) return;
|
||||
if (this.playingBgm) {
|
||||
this.player.resume(this.getId(this.playingBgm));
|
||||
}
|
||||
this.playing = true;
|
||||
this.emit('resume');
|
||||
}
|
||||
|
||||
/**
|
||||
* 暂停当前的 bgm
|
||||
*/
|
||||
pause() {
|
||||
if (this.blocking || !this.enabled) return;
|
||||
if (this.playingBgm) {
|
||||
this.player.pause(this.getId(this.playingBgm));
|
||||
}
|
||||
this.playing = false;
|
||||
this.emit('pause');
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止当前的 bgm
|
||||
*/
|
||||
stop() {
|
||||
if (this.blocking || !this.enabled) return;
|
||||
if (this.playingBgm) {
|
||||
this.player.stop(this.getId(this.playingBgm));
|
||||
}
|
||||
this.playing = false;
|
||||
this.emit('stop');
|
||||
}
|
||||
}
|
||||
|
||||
export const bgmController = new BgmController<BgmIds>(audioPlayer);
|
||||
|
||||
export function loadAllBgm() {
|
||||
const loading = Mota.require('var', 'loading');
|
||||
loading.once('coreInit', () => {
|
||||
const data = data_a1e2fb4a_e986_4524_b0da_9b7ba7c0874d;
|
||||
for (const bgm of data.main.bgms) {
|
||||
bgmController.addBgm(bgm);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
import { logger } from '@motajs/common';
|
||||
import { OggVorbisDecoderWebWorker } from '@wasm-audio-decoders/ogg-vorbis';
|
||||
import { OggOpusDecoderWebWorker } from 'ogg-opus-decoder';
|
||||
import { AudioType, isAudioSupport } from './support';
|
||||
import type { AudioPlayer } from './player';
|
||||
|
||||
const fileSignatures: [AudioType, number[]][] = [
|
||||
[AudioType.Mp3, [0x49, 0x44, 0x33]],
|
||||
[AudioType.Ogg, [0x4f, 0x67, 0x67, 0x53]],
|
||||
[AudioType.Wav, [0x52, 0x49, 0x46, 0x46]],
|
||||
[AudioType.Flac, [0x66, 0x4c, 0x61, 0x43]],
|
||||
[AudioType.Aac, [0xff, 0xf1]],
|
||||
[AudioType.Aac, [0xff, 0xf9]]
|
||||
];
|
||||
const oggHeaders: [AudioType, number[]][] = [
|
||||
[AudioType.Opus, [0x4f, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64]]
|
||||
];
|
||||
|
||||
export function checkAudioType(data: Uint8Array) {
|
||||
let audioType: AudioType | '' = '';
|
||||
// 检查头文件获取音频类型,仅检查前256个字节
|
||||
const toCheck = data.slice(0, 256);
|
||||
for (const [type, value] of fileSignatures) {
|
||||
if (value.every((v, i) => toCheck[i] === v)) {
|
||||
audioType = type;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (audioType === AudioType.Ogg) {
|
||||
// 如果是ogg的话,进一步判断是不是opus
|
||||
for (const [key, value] of oggHeaders) {
|
||||
const has = toCheck.some((_, i) => {
|
||||
return value.every((v, ii) => toCheck[i + ii] === v);
|
||||
});
|
||||
if (has) {
|
||||
audioType = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return audioType;
|
||||
}
|
||||
|
||||
export interface IAudioDecodeError {
|
||||
/** 错误信息 */
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface IAudioDecodeData {
|
||||
/** 每个声道的音频信息 */
|
||||
channelData: Float32Array[];
|
||||
/** 已经被解码的 PCM 采样数 */
|
||||
samplesDecoded: number;
|
||||
/** 音频采样率 */
|
||||
sampleRate: number;
|
||||
/** 解码错误信息 */
|
||||
errors: IAudioDecodeError[];
|
||||
}
|
||||
|
||||
export abstract class AudioDecoder {
|
||||
static readonly decoderMap: Map<AudioType, new () => AudioDecoder> =
|
||||
new Map();
|
||||
|
||||
/**
|
||||
* 注册一个解码器
|
||||
* @param type 要注册的解码器允许解码的类型
|
||||
* @param decoder 解码器对象
|
||||
*/
|
||||
static registerDecoder(type: AudioType, decoder: new () => AudioDecoder) {
|
||||
if (this.decoderMap.has(type)) {
|
||||
logger.warn(47, type);
|
||||
return;
|
||||
}
|
||||
this.decoderMap.set(type, decoder);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解码音频数据
|
||||
* @param data 音频文件数据
|
||||
* @param player AudioPlayer实例
|
||||
*/
|
||||
static async decodeAudioData(data: Uint8Array, player: AudioPlayer) {
|
||||
// 检查头文件获取音频类型,仅检查前256个字节
|
||||
const toCheck = data.slice(0, 256);
|
||||
const type = checkAudioType(data);
|
||||
if (type === '') {
|
||||
logger.error(
|
||||
25,
|
||||
[...toCheck]
|
||||
.map(v => v.toString(16).padStart(2, '0'))
|
||||
.join(' ')
|
||||
.toUpperCase()
|
||||
);
|
||||
return null;
|
||||
}
|
||||
if (isAudioSupport(type)) {
|
||||
if (data.buffer instanceof ArrayBuffer) {
|
||||
return player.ac.decodeAudioData(data.buffer);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
const Decoder = this.decoderMap.get(type);
|
||||
if (!Decoder) {
|
||||
return null;
|
||||
} else {
|
||||
const decoder = new Decoder();
|
||||
await decoder.create();
|
||||
const decodedData = await decoder.decode(data);
|
||||
if (!decodedData) return null;
|
||||
const buffer = player.ac.createBuffer(
|
||||
decodedData.channelData.length,
|
||||
decodedData.channelData[0].length,
|
||||
decodedData.sampleRate
|
||||
);
|
||||
decodedData.channelData.forEach((v, i) => {
|
||||
buffer.copyToChannel(v, i);
|
||||
});
|
||||
decoder.destroy();
|
||||
return buffer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建音频解码器
|
||||
*/
|
||||
abstract create(): Promise<void>;
|
||||
|
||||
/**
|
||||
* 摧毁这个解码器
|
||||
*/
|
||||
abstract destroy(): void;
|
||||
|
||||
/**
|
||||
* 解码流数据
|
||||
* @param data 流数据
|
||||
*/
|
||||
abstract decode(data: Uint8Array): Promise<IAudioDecodeData | undefined>;
|
||||
|
||||
/**
|
||||
* 解码整个文件
|
||||
* @param data 文件数据
|
||||
*/
|
||||
abstract decodeAll(data: Uint8Array): Promise<IAudioDecodeData | undefined>;
|
||||
|
||||
/**
|
||||
* 当音频解码完成后,会调用此函数,需要返回之前还未解析或未返回的音频数据。调用后,该解码器将不会被再次使用
|
||||
*/
|
||||
abstract flush(): Promise<IAudioDecodeData | undefined>;
|
||||
}
|
||||
|
||||
export class VorbisDecoder implements AudioDecoder {
|
||||
decoder?: OggVorbisDecoderWebWorker;
|
||||
|
||||
async create(): Promise<void> {
|
||||
this.decoder = new OggVorbisDecoderWebWorker();
|
||||
await this.decoder.ready;
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.decoder?.free();
|
||||
}
|
||||
|
||||
async decode(data: Uint8Array): Promise<IAudioDecodeData | undefined> {
|
||||
return this.decoder?.decode(data);
|
||||
}
|
||||
|
||||
async decodeAll(data: Uint8Array): Promise<IAudioDecodeData | undefined> {
|
||||
return this.decoder?.decodeFile(data);
|
||||
}
|
||||
|
||||
async flush(): Promise<IAudioDecodeData | undefined> {
|
||||
return this.decoder?.flush();
|
||||
}
|
||||
}
|
||||
|
||||
export class OpusDecoder implements AudioDecoder {
|
||||
decoder?: OggOpusDecoderWebWorker;
|
||||
|
||||
async create(): Promise<void> {
|
||||
this.decoder = new OggOpusDecoderWebWorker();
|
||||
await this.decoder.ready;
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.decoder?.free();
|
||||
}
|
||||
|
||||
async decode(data: Uint8Array): Promise<IAudioDecodeData | undefined> {
|
||||
return this.decoder?.decode(data);
|
||||
}
|
||||
|
||||
async decodeAll(data: Uint8Array): Promise<IAudioDecodeData | undefined> {
|
||||
return this.decoder?.decodeFile(data);
|
||||
}
|
||||
|
||||
async flush(): Promise<IAudioDecodeData | undefined> {
|
||||
return await this.decoder?.flush();
|
||||
}
|
||||
}
|
||||
@@ -1,288 +0,0 @@
|
||||
import { isNil } from 'lodash-es';
|
||||
import { sleep } from 'mutate-animate';
|
||||
|
||||
export interface IAudioInput {
|
||||
/** 输入节点 */
|
||||
input: AudioNode;
|
||||
}
|
||||
|
||||
export interface IAudioOutput {
|
||||
/** 输出节点 */
|
||||
output: AudioNode;
|
||||
}
|
||||
|
||||
export abstract class AudioEffect implements IAudioInput, IAudioOutput {
|
||||
/** 输出节点 */
|
||||
abstract output: AudioNode;
|
||||
/** 输入节点 */
|
||||
abstract input: AudioNode;
|
||||
|
||||
constructor(public readonly ac: AudioContext) {}
|
||||
|
||||
/**
|
||||
* 当音频播放结束时触发,可以用于节点结束后处理
|
||||
*/
|
||||
abstract end(): void;
|
||||
|
||||
/**
|
||||
* 当音频开始播放时触发,可以用于节点初始化
|
||||
*/
|
||||
abstract start(): void;
|
||||
|
||||
/**
|
||||
* 连接至其他效果器
|
||||
* @param target 目标输入
|
||||
* @param output 当前效果器输出通道
|
||||
* @param input 目标效果器的输入通道
|
||||
*/
|
||||
connect(target: IAudioInput, output?: number, input?: number) {
|
||||
this.output.connect(target.input, output, input);
|
||||
}
|
||||
|
||||
/**
|
||||
* 与其他效果器取消连接
|
||||
* @param target 目标输入
|
||||
* @param output 当前效果器输出通道
|
||||
* @param input 目标效果器的输入通道
|
||||
*/
|
||||
disconnect(target?: IAudioInput, output?: number, input?: number) {
|
||||
if (!target) {
|
||||
if (!isNil(output)) {
|
||||
this.output.disconnect(output);
|
||||
} else {
|
||||
this.output.disconnect();
|
||||
}
|
||||
} else {
|
||||
if (!isNil(output)) {
|
||||
if (!isNil(input)) {
|
||||
this.output.disconnect(target.input, output, input);
|
||||
} else {
|
||||
this.output.disconnect(target.input, output);
|
||||
}
|
||||
} else {
|
||||
this.output.disconnect(target.input);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class StereoEffect extends AudioEffect {
|
||||
output: PannerNode;
|
||||
input: PannerNode;
|
||||
|
||||
constructor(ac: AudioContext) {
|
||||
super(ac);
|
||||
const panner = ac.createPanner();
|
||||
this.input = panner;
|
||||
this.output = panner;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置音频朝向,x正方形水平向右,y正方形垂直于地面向上,z正方向垂直屏幕远离用户
|
||||
* @param x 朝向x坐标
|
||||
* @param y 朝向y坐标
|
||||
* @param z 朝向z坐标
|
||||
*/
|
||||
setOrientation(x: number, y: number, z: number) {
|
||||
this.output.orientationX.value = x;
|
||||
this.output.orientationY.value = y;
|
||||
this.output.orientationZ.value = z;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置音频位置,x正方形水平向右,y正方形垂直于地面向上,z正方向垂直屏幕远离用户
|
||||
* @param x 位置x坐标
|
||||
* @param y 位置y坐标
|
||||
* @param z 位置z坐标
|
||||
*/
|
||||
setPosition(x: number, y: number, z: number) {
|
||||
this.output.positionX.value = x;
|
||||
this.output.positionY.value = y;
|
||||
this.output.positionZ.value = z;
|
||||
}
|
||||
|
||||
end(): void {}
|
||||
|
||||
start(): void {}
|
||||
}
|
||||
|
||||
export class VolumeEffect extends AudioEffect {
|
||||
output: GainNode;
|
||||
input: GainNode;
|
||||
|
||||
constructor(ac: AudioContext) {
|
||||
super(ac);
|
||||
const gain = ac.createGain();
|
||||
this.input = gain;
|
||||
this.output = gain;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置音量大小
|
||||
* @param volume 音量大小
|
||||
*/
|
||||
setVolume(volume: number) {
|
||||
this.output.gain.value = volume;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取音量大小
|
||||
*/
|
||||
getVolume(): number {
|
||||
return this.output.gain.value;
|
||||
}
|
||||
|
||||
end(): void {}
|
||||
|
||||
start(): void {}
|
||||
}
|
||||
|
||||
export class ChannelVolumeEffect extends AudioEffect {
|
||||
output: ChannelMergerNode;
|
||||
input: ChannelSplitterNode;
|
||||
|
||||
/** 所有的音量控制节点 */
|
||||
private readonly gain: GainNode[] = [];
|
||||
|
||||
constructor(ac: AudioContext) {
|
||||
super(ac);
|
||||
const splitter = ac.createChannelSplitter();
|
||||
const merger = ac.createChannelMerger();
|
||||
this.output = merger;
|
||||
this.input = splitter;
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const gain = ac.createGain();
|
||||
splitter.connect(gain, i);
|
||||
gain.connect(merger, 0, i);
|
||||
this.gain.push(gain);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置某个声道的音量大小
|
||||
* @param channel 要设置的声道,可填0-5
|
||||
* @param volume 这个声道的音量大小
|
||||
*/
|
||||
setVolume(channel: number, volume: number) {
|
||||
if (!this.gain[channel]) return;
|
||||
this.gain[channel].gain.value = volume;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取某个声道的音量大小,可填0-5
|
||||
* @param channel 要获取的声道
|
||||
*/
|
||||
getVolume(channel: number): number {
|
||||
if (!this.gain[channel]) return 0;
|
||||
return this.gain[channel].gain.value;
|
||||
}
|
||||
|
||||
end(): void {}
|
||||
|
||||
start(): void {}
|
||||
}
|
||||
|
||||
export class DelayEffect extends AudioEffect {
|
||||
output: DelayNode;
|
||||
input: DelayNode;
|
||||
|
||||
constructor(ac: AudioContext) {
|
||||
super(ac);
|
||||
const delay = ac.createDelay();
|
||||
this.input = delay;
|
||||
this.output = delay;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置延迟时长
|
||||
* @param delay 延迟时长,单位秒
|
||||
*/
|
||||
setDelay(delay: number) {
|
||||
this.output.delayTime.value = delay;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取延迟时长
|
||||
*/
|
||||
getDelay() {
|
||||
return this.output.delayTime.value;
|
||||
}
|
||||
|
||||
end(): void {}
|
||||
|
||||
start(): void {}
|
||||
}
|
||||
|
||||
export class EchoEffect extends AudioEffect {
|
||||
output: GainNode;
|
||||
input: GainNode;
|
||||
|
||||
/** 延迟节点 */
|
||||
private readonly delay: DelayNode;
|
||||
/** 反馈增益节点 */
|
||||
private readonly gainNode: GainNode;
|
||||
/** 当前增益 */
|
||||
private gain: number = 0.5;
|
||||
/** 是否正在播放 */
|
||||
private playing: boolean = false;
|
||||
|
||||
constructor(ac: AudioContext) {
|
||||
super(ac);
|
||||
const delay = ac.createDelay();
|
||||
const gain = ac.createGain();
|
||||
gain.gain.value = 0.5;
|
||||
delay.delayTime.value = 0.05;
|
||||
delay.connect(gain);
|
||||
gain.connect(delay);
|
||||
this.delay = delay;
|
||||
this.gainNode = gain;
|
||||
this.input = gain;
|
||||
this.output = gain;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置回声反馈增益大小
|
||||
* @param gain 增益大小,范围 0-1,大于等于1的视为0.5,小于0的视为0
|
||||
*/
|
||||
setFeedbackGain(gain: number) {
|
||||
const resolved = gain >= 1 ? 0.5 : gain < 0 ? 0 : gain;
|
||||
this.gain = resolved;
|
||||
if (this.playing) this.gainNode.gain.value = resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置回声间隔时长
|
||||
* @param delay 回声时长,范围 0.01-Infinity,小于0.01的视为0.01
|
||||
*/
|
||||
setEchoDelay(delay: number) {
|
||||
const resolved = delay < 0.01 ? 0.01 : delay;
|
||||
this.delay.delayTime.value = resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取反馈节点增益
|
||||
*/
|
||||
getFeedbackGain() {
|
||||
return this.gain;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取回声间隔时长
|
||||
*/
|
||||
getEchoDelay() {
|
||||
return this.delay.delayTime.value;
|
||||
}
|
||||
|
||||
end(): void {
|
||||
this.playing = false;
|
||||
const echoTime = Math.ceil(Math.log(0.001) / Math.log(this.gain)) + 10;
|
||||
sleep(this.delay.delayTime.value * echoTime).then(() => {
|
||||
if (!this.playing) this.gainNode.gain.value = 0;
|
||||
});
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.playing = true;
|
||||
this.gainNode.gain.value = this.gain;
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { loadAllBgm } from './bgm';
|
||||
import { OpusDecoder, VorbisDecoder } from './decoder';
|
||||
import { AudioType } from './support';
|
||||
import { AudioDecoder } from './decoder';
|
||||
|
||||
loadAllBgm();
|
||||
AudioDecoder.registerDecoder(AudioType.Ogg, VorbisDecoder);
|
||||
AudioDecoder.registerDecoder(AudioType.Opus, OpusDecoder);
|
||||
|
||||
export * from './support';
|
||||
export * from './effect';
|
||||
export * from './player';
|
||||
export * from './source';
|
||||
export * from './bgm';
|
||||
export * from './decoder';
|
||||
export * from './sound';
|
||||
@@ -1,595 +0,0 @@
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import {
|
||||
AudioBufferSource,
|
||||
AudioElementSource,
|
||||
AudioSource,
|
||||
AudioStreamSource
|
||||
} from './source';
|
||||
import {
|
||||
AudioEffect,
|
||||
ChannelVolumeEffect,
|
||||
DelayEffect,
|
||||
EchoEffect,
|
||||
IAudioOutput,
|
||||
StereoEffect,
|
||||
VolumeEffect
|
||||
} from './effect';
|
||||
import { isNil } from 'lodash-es';
|
||||
import { logger } from '@motajs/common';
|
||||
import { sleep } from 'mutate-animate';
|
||||
import { AudioDecoder } from './decoder';
|
||||
|
||||
interface AudioPlayerEvent {}
|
||||
|
||||
export class AudioPlayer extends EventEmitter<AudioPlayerEvent> {
|
||||
/** 音频播放上下文 */
|
||||
readonly ac: AudioContext;
|
||||
|
||||
/** 所有的音频播放路由 */
|
||||
readonly audioRoutes: Map<string, AudioRoute> = new Map();
|
||||
/** 音量节点 */
|
||||
readonly gain: GainNode;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.ac = new AudioContext();
|
||||
this.gain = this.ac.createGain();
|
||||
this.gain.connect(this.ac.destination);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解码音频数据
|
||||
* @param data 音频数据
|
||||
*/
|
||||
decodeAudioData(data: Uint8Array) {
|
||||
return AudioDecoder.decodeAudioData(data, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置音量
|
||||
* @param volume 音量
|
||||
*/
|
||||
setVolume(volume: number) {
|
||||
this.gain.gain.value = volume;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取音量
|
||||
*/
|
||||
getVolume() {
|
||||
return this.gain.gain.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个音频源
|
||||
* @param Source 音频源类
|
||||
*/
|
||||
createSource<T extends AudioSource>(
|
||||
Source: new (ac: AudioContext) => T
|
||||
): T {
|
||||
return new Source(this.ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个兼容流式音频源,可以与流式加载相结合,主要用于处理 opus ogg 不兼容的情况
|
||||
*/
|
||||
createStreamSource() {
|
||||
return new AudioStreamSource(this.ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个通过 audio 元素播放的音频源
|
||||
*/
|
||||
createElementSource() {
|
||||
return new AudioElementSource(this.ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个通过 AudioBuffer 播放的音频源
|
||||
*/
|
||||
createBufferSource() {
|
||||
return new AudioBufferSource(this.ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取音频目的地
|
||||
*/
|
||||
getDestination() {
|
||||
return this.gain;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个音频效果器
|
||||
* @param Effect 效果器类
|
||||
*/
|
||||
createEffect<T extends AudioEffect>(
|
||||
Effect: new (ac: AudioContext) => T
|
||||
): T {
|
||||
return new Effect(this.ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个修改音量的效果器
|
||||
* ```txt
|
||||
* |----------|
|
||||
* Input ----> | GainNode | ----> Output
|
||||
* |----------|
|
||||
* ```
|
||||
*/
|
||||
createVolumeEffect() {
|
||||
return new VolumeEffect(this.ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个立体声效果器
|
||||
* ```txt
|
||||
* |------------|
|
||||
* Input ----> | PannerNode | ----> Output
|
||||
* |------------|
|
||||
* ```
|
||||
*/
|
||||
createStereoEffect() {
|
||||
return new StereoEffect(this.ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个修改单个声道音量的效果器
|
||||
* ```txt
|
||||
* |----------|
|
||||
* -> | GainNode | \
|
||||
* |--------------| / |----------| -> |------------|
|
||||
* Input ----> | SplitterNode | ...... | MergerNode | ----> Output
|
||||
* |--------------| \ |----------| -> |------------|
|
||||
* -> | GainNode | /
|
||||
* |----------|
|
||||
* ```
|
||||
*/
|
||||
createChannelVolumeEffect() {
|
||||
return new ChannelVolumeEffect(this.ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个延迟效果器
|
||||
* |-----------|
|
||||
* Input ----> | DelayNode | ----> Output
|
||||
* |-----------|
|
||||
*/
|
||||
createDelay() {
|
||||
return new DelayEffect(this.ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个回声效果器
|
||||
* ```txt
|
||||
* |----------|
|
||||
* Input ----> | GainNode | ----> Output
|
||||
* ^ |----------| |
|
||||
* | |
|
||||
* | |------------| ↓
|
||||
* |-- | Delay Node | <--
|
||||
* |------------|
|
||||
* ```
|
||||
*/
|
||||
createEchoEffect() {
|
||||
return new EchoEffect(this.ac);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个音频播放路由
|
||||
* @param source 音频源
|
||||
*/
|
||||
createRoute(source: AudioSource) {
|
||||
return new AudioRoute(source, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一个音频播放路由,可以直接被播放
|
||||
* @param id 这个音频播放路由的名称
|
||||
* @param route 音频播放路由对象
|
||||
*/
|
||||
addRoute(id: string, route: AudioRoute) {
|
||||
if (this.audioRoutes.has(id)) {
|
||||
logger.warn(45, id);
|
||||
}
|
||||
this.audioRoutes.set(id, route);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据名称获取音频播放路由对象
|
||||
* @param id 音频播放路由的名称
|
||||
*/
|
||||
getRoute(id: string) {
|
||||
return this.audioRoutes.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除一个音频播放路由
|
||||
* @param id 要移除的播放路由的名称
|
||||
*/
|
||||
removeRoute(id: string) {
|
||||
this.audioRoutes.delete(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 播放音频
|
||||
* @param id 音频名称
|
||||
* @param when 从音频的哪个位置开始播放,单位秒
|
||||
*/
|
||||
play(id: string, when: number = 0) {
|
||||
const route = this.getRoute(id);
|
||||
if (!route) {
|
||||
logger.warn(53, 'play', id);
|
||||
return;
|
||||
}
|
||||
route.play(when);
|
||||
}
|
||||
|
||||
/**
|
||||
* 暂停音频播放
|
||||
* @param id 音频名称
|
||||
* @returns 当音乐真正停止时兑现
|
||||
*/
|
||||
pause(id: string) {
|
||||
const route = this.getRoute(id);
|
||||
if (!route) {
|
||||
logger.warn(53, 'pause', id);
|
||||
return;
|
||||
}
|
||||
return route.pause();
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止音频播放
|
||||
* @param id 音频名称
|
||||
* @returns 当音乐真正停止时兑现
|
||||
*/
|
||||
stop(id: string) {
|
||||
const route = this.getRoute(id);
|
||||
if (!route) {
|
||||
logger.warn(53, 'stop', id);
|
||||
return;
|
||||
}
|
||||
return route.stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* 继续音频播放
|
||||
* @param id 音频名称
|
||||
*/
|
||||
resume(id: string) {
|
||||
const route = this.getRoute(id);
|
||||
if (!route) {
|
||||
logger.warn(53, 'play', id);
|
||||
return;
|
||||
}
|
||||
route.resume();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置听者位置,x正方向水平向右,y正方向垂直于地面向上,z正方向垂直屏幕远离用户
|
||||
* @param x 位置x坐标
|
||||
* @param y 位置y坐标
|
||||
* @param z 位置z坐标
|
||||
*/
|
||||
setListenerPosition(x: number, y: number, z: number) {
|
||||
const listener = this.ac.listener;
|
||||
listener.positionX.value = x;
|
||||
listener.positionY.value = y;
|
||||
listener.positionZ.value = z;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置听者朝向,x正方向水平向右,y正方向垂直于地面向上,z正方向垂直屏幕远离用户
|
||||
* @param x 朝向x坐标
|
||||
* @param y 朝向y坐标
|
||||
* @param z 朝向z坐标
|
||||
*/
|
||||
setListenerOrientation(x: number, y: number, z: number) {
|
||||
const listener = this.ac.listener;
|
||||
listener.forwardX.value = x;
|
||||
listener.forwardY.value = y;
|
||||
listener.forwardZ.value = z;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置听者头顶朝向,x正方向水平向右,y正方向垂直于地面向上,z正方向垂直屏幕远离用户
|
||||
* @param x 头顶朝向x坐标
|
||||
* @param y 头顶朝向y坐标
|
||||
* @param z 头顶朝向z坐标
|
||||
*/
|
||||
setListenerUp(x: number, y: number, z: number) {
|
||||
const listener = this.ac.listener;
|
||||
listener.upX.value = x;
|
||||
listener.upY.value = y;
|
||||
listener.upZ.value = z;
|
||||
}
|
||||
}
|
||||
|
||||
export const enum AudioStatus {
|
||||
Playing,
|
||||
Pausing,
|
||||
Paused,
|
||||
Stoping,
|
||||
Stoped
|
||||
}
|
||||
|
||||
type AudioStartHook = (route: AudioRoute) => void;
|
||||
type AudioEndHook = (time: number, route: AudioRoute) => void;
|
||||
|
||||
interface AudioRouteEvent {
|
||||
updateEffect: [];
|
||||
play: [];
|
||||
stop: [];
|
||||
pause: [];
|
||||
resume: [];
|
||||
}
|
||||
|
||||
export class AudioRoute
|
||||
extends EventEmitter<AudioRouteEvent>
|
||||
implements IAudioOutput
|
||||
{
|
||||
output: AudioNode;
|
||||
|
||||
/** 效果器路由图 */
|
||||
readonly effectRoute: AudioEffect[] = [];
|
||||
|
||||
/** 结束时长,当音频暂停或停止时,会经过这么长时间之后才真正终止播放,期间可以做音频淡入淡出等效果 */
|
||||
endTime: number = 0;
|
||||
|
||||
/** 当前播放状态 */
|
||||
status: AudioStatus = AudioStatus.Stoped;
|
||||
/** 暂停时刻 */
|
||||
private pauseTime: number = 0;
|
||||
/** 暂停时播放了多长时间 */
|
||||
private pauseCurrentTime: number = 0;
|
||||
|
||||
/** 音频时长,单位秒 */
|
||||
get duration() {
|
||||
return this.source.duration;
|
||||
}
|
||||
/** 当前播放了多长时间,单位秒 */
|
||||
get currentTime() {
|
||||
if (this.status === AudioStatus.Paused) {
|
||||
return this.pauseCurrentTime;
|
||||
} else {
|
||||
return this.source.currentTime;
|
||||
}
|
||||
}
|
||||
set currentTime(time: number) {
|
||||
this.source.stop();
|
||||
this.source.play(time);
|
||||
}
|
||||
|
||||
private shouldStop: boolean = false;
|
||||
/**
|
||||
* 每次暂停或停止时自增,用于判断当前正在处理的情况。
|
||||
* 假如暂停后很快播放,然后很快暂停,那么需要根据这个来判断实际是否应该执行暂停后操作
|
||||
*/
|
||||
stopIdentifier: number = 0;
|
||||
|
||||
private audioStartHook?: AudioStartHook;
|
||||
private audioEndHook?: AudioEndHook;
|
||||
|
||||
constructor(
|
||||
public readonly source: AudioSource,
|
||||
public readonly player: AudioPlayer
|
||||
) {
|
||||
super();
|
||||
this.output = source.output;
|
||||
source.on('end', () => {
|
||||
if (this.status === AudioStatus.Playing) {
|
||||
this.status = AudioStatus.Stoped;
|
||||
}
|
||||
});
|
||||
source.on('play', () => {
|
||||
if (this.status !== AudioStatus.Playing) {
|
||||
this.status = AudioStatus.Playing;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置结束时间,暂停或停止时,会经过这么长时间才终止音频的播放,这期间可以做一下音频淡出的效果。
|
||||
* @param time 暂停或停止时,经过多长时间之后才会结束音频的播放
|
||||
*/
|
||||
setEndTime(time: number) {
|
||||
this.endTime = time;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当音频播放时执行的函数,可以用于音频淡入效果
|
||||
* @param fn 音频开始播放时执行的函数
|
||||
*/
|
||||
onStart(fn?: AudioStartHook) {
|
||||
this.audioStartHook = fn;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当音频暂停或停止时执行的函数,可以用于音频淡出效果
|
||||
* @param fn 音频在暂停或停止时执行的函数,不填时表示取消这个钩子。
|
||||
* 包含两个参数,第一个参数是结束时长,第二个参数是当前音频播放路由对象
|
||||
*/
|
||||
onEnd(fn?: AudioEndHook) {
|
||||
this.audioEndHook = fn;
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始播放这个音频
|
||||
* @param when 从音频的什么时候开始播放,单位秒
|
||||
*/
|
||||
async play(when: number = 0) {
|
||||
if (this.status === AudioStatus.Playing) return;
|
||||
this.link();
|
||||
await this.player.ac.resume();
|
||||
if (this.effectRoute.length > 0) {
|
||||
const first = this.effectRoute[0];
|
||||
this.source.connect(first);
|
||||
const last = this.effectRoute.at(-1)!;
|
||||
last.connect({ input: this.player.getDestination() });
|
||||
} else {
|
||||
this.source.connect({ input: this.player.getDestination() });
|
||||
}
|
||||
this.source.play(when);
|
||||
this.status = AudioStatus.Playing;
|
||||
this.pauseTime = 0;
|
||||
this.audioStartHook?.(this);
|
||||
this.startAllEffect();
|
||||
this.emit('play');
|
||||
}
|
||||
|
||||
/**
|
||||
* 暂停音频播放
|
||||
*/
|
||||
async pause() {
|
||||
if (this.status !== AudioStatus.Playing) return;
|
||||
this.status = AudioStatus.Pausing;
|
||||
this.stopIdentifier++;
|
||||
const identifier = this.stopIdentifier;
|
||||
if (this.audioEndHook) {
|
||||
this.audioEndHook(this.endTime, this);
|
||||
await sleep(this.endTime);
|
||||
}
|
||||
if (
|
||||
this.status !== AudioStatus.Pausing ||
|
||||
this.stopIdentifier !== identifier
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.pauseCurrentTime = this.source.currentTime;
|
||||
const time = this.source.stop();
|
||||
this.pauseTime = time;
|
||||
if (this.shouldStop) {
|
||||
this.status = AudioStatus.Stoped;
|
||||
this.endAllEffect();
|
||||
this.emit('stop');
|
||||
this.shouldStop = false;
|
||||
} else {
|
||||
this.status = AudioStatus.Paused;
|
||||
this.endAllEffect();
|
||||
this.emit('pause');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 继续音频播放
|
||||
*/
|
||||
resume() {
|
||||
if (this.status === AudioStatus.Playing) return;
|
||||
if (
|
||||
this.status === AudioStatus.Pausing ||
|
||||
this.status === AudioStatus.Stoping
|
||||
) {
|
||||
this.audioStartHook?.(this);
|
||||
this.emit('resume');
|
||||
return;
|
||||
}
|
||||
if (this.status === AudioStatus.Paused) {
|
||||
this.play(this.pauseTime);
|
||||
} else {
|
||||
this.play(0);
|
||||
}
|
||||
this.status = AudioStatus.Playing;
|
||||
this.pauseTime = 0;
|
||||
this.audioStartHook?.(this);
|
||||
this.startAllEffect();
|
||||
this.emit('resume');
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止音频播放
|
||||
*/
|
||||
async stop() {
|
||||
if (this.status !== AudioStatus.Playing) {
|
||||
if (this.status === AudioStatus.Pausing) {
|
||||
this.shouldStop = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.status = AudioStatus.Stoping;
|
||||
this.stopIdentifier++;
|
||||
const identifier = this.stopIdentifier;
|
||||
if (this.audioEndHook) {
|
||||
this.audioEndHook(this.endTime, this);
|
||||
await sleep(this.endTime);
|
||||
}
|
||||
if (
|
||||
this.status !== AudioStatus.Stoping ||
|
||||
this.stopIdentifier !== identifier
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.source.stop();
|
||||
this.status = AudioStatus.Stoped;
|
||||
this.pauseTime = 0;
|
||||
this.endAllEffect();
|
||||
this.emit('stop');
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加效果器
|
||||
* @param effect 要添加的效果,可以是数组,表示一次添加多个
|
||||
* @param index 从哪个位置开始添加,如果大于数组长度,那么加到末尾,如果小于0,那么将会从后面往前数。默认添加到末尾
|
||||
*/
|
||||
addEffect(effect: AudioEffect | AudioEffect[], index?: number) {
|
||||
if (isNil(index)) {
|
||||
if (effect instanceof Array) {
|
||||
this.effectRoute.push(...effect);
|
||||
} else {
|
||||
this.effectRoute.push(effect);
|
||||
}
|
||||
} else {
|
||||
if (effect instanceof Array) {
|
||||
this.effectRoute.splice(index, 0, ...effect);
|
||||
} else {
|
||||
this.effectRoute.splice(index, 0, effect);
|
||||
}
|
||||
}
|
||||
this.setOutput();
|
||||
if (this.source.playing) this.link();
|
||||
this.emit('updateEffect');
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除一个效果器
|
||||
* @param effect 要移除的效果
|
||||
*/
|
||||
removeEffect(effect: AudioEffect) {
|
||||
const index = this.effectRoute.indexOf(effect);
|
||||
if (index === -1) return;
|
||||
this.effectRoute.splice(index, 1);
|
||||
effect.disconnect();
|
||||
this.setOutput();
|
||||
if (this.source.playing) this.link();
|
||||
this.emit('updateEffect');
|
||||
}
|
||||
|
||||
private setOutput() {
|
||||
const effect = this.effectRoute.at(-1);
|
||||
if (!effect) this.output = this.source.output;
|
||||
else this.output = effect.output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接音频路由图
|
||||
*/
|
||||
private link() {
|
||||
this.effectRoute.forEach(v => v.disconnect());
|
||||
this.effectRoute.forEach((v, i) => {
|
||||
const next = this.effectRoute[i + 1];
|
||||
if (next) {
|
||||
v.connect(next);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private startAllEffect() {
|
||||
this.effectRoute.forEach(v => v.start());
|
||||
}
|
||||
|
||||
private endAllEffect() {
|
||||
this.effectRoute.forEach(v => v.end());
|
||||
}
|
||||
}
|
||||
|
||||
export const audioPlayer = new AudioPlayer();
|
||||
// window.audioPlayer = audioPlayer;
|
||||
@@ -1,132 +0,0 @@
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { audioPlayer, AudioPlayer } from './player';
|
||||
import { logger } from '@motajs/common';
|
||||
import { VolumeEffect } from './effect';
|
||||
|
||||
type LocationArray = [number, number, number];
|
||||
|
||||
interface SoundPlayerEvent {}
|
||||
|
||||
export class SoundPlayer<
|
||||
T extends string = SoundIds
|
||||
> extends EventEmitter<SoundPlayerEvent> {
|
||||
/** 每个音效的唯一标识符 */
|
||||
private num: number = 0;
|
||||
|
||||
/** 每个音效的数据 */
|
||||
readonly buffer: Map<T, AudioBuffer> = new Map();
|
||||
/** 所有正在播放的音乐 */
|
||||
readonly playing: Set<number> = new Set();
|
||||
/** 音量节点 */
|
||||
readonly gain: VolumeEffect;
|
||||
|
||||
/** 是否已经启用 */
|
||||
enabled: boolean = true;
|
||||
|
||||
constructor(public readonly player: AudioPlayer) {
|
||||
super();
|
||||
this.gain = player.createVolumeEffect();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置是否启用音效
|
||||
* @param enabled 是否启用音效
|
||||
*/
|
||||
setEnabled(enabled: boolean) {
|
||||
if (!enabled) this.stopAllSounds();
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置音量大小
|
||||
* @param volume 音量大小
|
||||
*/
|
||||
setVolume(volume: number) {
|
||||
this.gain.setVolume(volume);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取音量大小
|
||||
*/
|
||||
getVolume() {
|
||||
return this.gain.getVolume();
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一个音效
|
||||
* @param id 音效名称
|
||||
* @param data 音效的Uint8Array数据
|
||||
*/
|
||||
async add(id: T, data: Uint8Array) {
|
||||
const buffer = await this.player.decodeAudioData(data);
|
||||
if (!buffer) {
|
||||
logger.warn(51, id);
|
||||
return;
|
||||
}
|
||||
this.buffer.set(id, buffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* 播放一个音效
|
||||
* @param id 音效名称
|
||||
* @param position 音频位置,[0, 0, 0]表示正中心,x轴指向水平向右,y轴指向水平向上,z轴指向竖直向上
|
||||
* @param orientation 音频朝向,[0, 1, 0]表示朝向前方
|
||||
*/
|
||||
play(
|
||||
id: T,
|
||||
position: LocationArray = [0, 0, 0],
|
||||
orientation: LocationArray = [1, 0, 0]
|
||||
) {
|
||||
if (!this.enabled) return -1;
|
||||
const buffer = this.buffer.get(id);
|
||||
if (!buffer) {
|
||||
logger.warn(52, id);
|
||||
return -1;
|
||||
}
|
||||
const soundNum = this.num++;
|
||||
const source = this.player.createBufferSource();
|
||||
source.setBuffer(buffer);
|
||||
const route = this.player.createRoute(source);
|
||||
const stereo = this.player.createStereoEffect();
|
||||
stereo.setPosition(position[0], position[1], position[2]);
|
||||
stereo.setOrientation(orientation[0], orientation[1], orientation[2]);
|
||||
route.addEffect([stereo, this.gain]);
|
||||
this.player.addRoute(`sounds.${soundNum}`, route);
|
||||
route.play();
|
||||
source.output.addEventListener('ended', () => {
|
||||
this.playing.delete(soundNum);
|
||||
});
|
||||
this.playing.add(soundNum);
|
||||
return soundNum;
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止一个音效
|
||||
* @param num 音效的唯一 id
|
||||
*/
|
||||
stop(num: number) {
|
||||
const id = `sounds.${num}`;
|
||||
const route = this.player.getRoute(id);
|
||||
if (route) {
|
||||
route.stop();
|
||||
this.player.removeRoute(id);
|
||||
this.playing.delete(num);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止播放所有音效
|
||||
*/
|
||||
stopAllSounds() {
|
||||
this.playing.forEach(v => {
|
||||
const id = `sounds.${v}`;
|
||||
const route = this.player.getRoute(id);
|
||||
if (route) {
|
||||
route.stop();
|
||||
this.player.removeRoute(id);
|
||||
}
|
||||
});
|
||||
this.playing.clear();
|
||||
}
|
||||
}
|
||||
export const soundPlayer = new SoundPlayer<SoundIds>(audioPlayer);
|
||||
@@ -1,562 +0,0 @@
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { IStreamController, IStreamReader } from '../loader';
|
||||
import { IAudioInput, IAudioOutput } from './effect';
|
||||
import { logger } from '@motajs/common';
|
||||
import { AudioType } from './support';
|
||||
import CodecParser, { CodecFrame, MimeType, OggPage } from 'codec-parser';
|
||||
import { isNil } from 'lodash-es';
|
||||
import { IAudioDecodeData, AudioDecoder, checkAudioType } from './decoder';
|
||||
|
||||
interface AudioSourceEvent {
|
||||
play: [];
|
||||
end: [];
|
||||
}
|
||||
|
||||
export abstract class AudioSource
|
||||
extends EventEmitter<AudioSourceEvent>
|
||||
implements IAudioOutput
|
||||
{
|
||||
/** 音频源的输出节点 */
|
||||
abstract readonly output: AudioNode;
|
||||
|
||||
/** 是否正在播放 */
|
||||
playing: boolean = false;
|
||||
|
||||
/** 获取音频时长 */
|
||||
abstract get duration(): number;
|
||||
/** 获取当前音频播放了多长时间 */
|
||||
abstract get currentTime(): number;
|
||||
|
||||
constructor(public readonly ac: AudioContext) {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始播放这个音频源
|
||||
*/
|
||||
abstract play(when?: number): void;
|
||||
|
||||
/**
|
||||
* 停止播放这个音频源
|
||||
* @returns 音频暂停的时刻
|
||||
*/
|
||||
abstract stop(): number;
|
||||
|
||||
/**
|
||||
* 连接到音频路由图上,每次调用播放的时候都会执行一次
|
||||
* @param target 连接至的目标
|
||||
*/
|
||||
abstract connect(target: IAudioInput): void;
|
||||
|
||||
/**
|
||||
* 设置是否循环播放
|
||||
* @param loop 是否循环
|
||||
*/
|
||||
abstract setLoop(loop: boolean): void;
|
||||
}
|
||||
|
||||
const mimeTypeMap: Record<AudioType, MimeType> = {
|
||||
[AudioType.Aac]: 'audio/aac',
|
||||
[AudioType.Flac]: 'audio/flac',
|
||||
[AudioType.Mp3]: 'audio/mpeg',
|
||||
[AudioType.Ogg]: 'application/ogg',
|
||||
[AudioType.Opus]: 'application/ogg',
|
||||
[AudioType.Wav]: 'application/ogg'
|
||||
};
|
||||
|
||||
function isOggPage(data: any): data is OggPage {
|
||||
return !isNil(data.isFirstPage);
|
||||
}
|
||||
|
||||
export class AudioStreamSource extends AudioSource implements IStreamReader {
|
||||
output: AudioBufferSourceNode;
|
||||
|
||||
/** 音频数据 */
|
||||
buffer?: AudioBuffer;
|
||||
|
||||
/** 是否已经完全加载完毕 */
|
||||
loaded: boolean = false;
|
||||
/** 已经缓冲了多长时间,如果缓冲完那么跟歌曲时长一致 */
|
||||
buffered: number = 0;
|
||||
/** 已经缓冲的采样点数量 */
|
||||
bufferedSamples: number = 0;
|
||||
/** 歌曲时长,加载完毕之前保持为 0 */
|
||||
duration: number = 0;
|
||||
/** 当前已经播放了多长时间 */
|
||||
get currentTime(): number {
|
||||
return this.ac.currentTime - this.lastStartTime + this.lastStartWhen;
|
||||
}
|
||||
/** 在流传输阶段,至少缓冲多长时间的音频之后才开始播放,单位秒 */
|
||||
bufferPlayDuration: number = 1;
|
||||
/** 音频的采样率,未成功解析出之前保持为 0 */
|
||||
sampleRate: number = 0;
|
||||
|
||||
private controller?: IStreamController;
|
||||
private loop: boolean = false;
|
||||
|
||||
private target?: IAudioInput;
|
||||
|
||||
/** 上一次播放是从何时开始的 */
|
||||
private lastStartWhen: number = 0;
|
||||
/** 开始播放时刻 */
|
||||
private lastStartTime: number = 0;
|
||||
/** 上一次播放的缓存长度 */
|
||||
private lastBufferSamples: number = 0;
|
||||
|
||||
/** 是否已经获取到头文件 */
|
||||
private headerRecieved: boolean = false;
|
||||
/** 音频类型 */
|
||||
private audioType: AudioType | '' = '';
|
||||
/** 音频解码器 */
|
||||
private decoder?: AudioDecoder;
|
||||
/** 音频解析器 */
|
||||
private parser?: CodecParser;
|
||||
/** 每多长时间组成一个缓存 Float32Array */
|
||||
private bufferChunkSize = 10;
|
||||
/** 缓存音频数据,每 bufferChunkSize 秒钟组成一个 Float32Array,用于流式解码 */
|
||||
private audioData: Float32Array[][] = [];
|
||||
|
||||
private errored: boolean = false;
|
||||
|
||||
constructor(context: AudioContext) {
|
||||
super(context);
|
||||
this.output = context.createBufferSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置每个缓存数据的大小,默认为10秒钟一个缓存数据
|
||||
* @param size 每个缓存数据的时长,单位秒
|
||||
*/
|
||||
setChunkSize(size: number) {
|
||||
if (this.controller?.loading || this.loaded) return;
|
||||
this.bufferChunkSize = size;
|
||||
}
|
||||
|
||||
piped(controller: IStreamController): void {
|
||||
this.controller = controller;
|
||||
}
|
||||
|
||||
async pump(data: Uint8Array | undefined, done: boolean): Promise<void> {
|
||||
if (!data || this.errored) return;
|
||||
if (!this.headerRecieved) {
|
||||
// 检查头文件获取音频类型,仅检查前256个字节
|
||||
const toCheck = data.slice(0, 256);
|
||||
this.audioType = checkAudioType(data);
|
||||
if (!this.audioType) {
|
||||
logger.error(
|
||||
25,
|
||||
[...toCheck]
|
||||
.map(v => v.toString().padStart(2, '0'))
|
||||
.join(' ')
|
||||
.toUpperCase()
|
||||
);
|
||||
return;
|
||||
}
|
||||
// 创建解码器
|
||||
const Decoder = AudioDecoder.decoderMap.get(this.audioType);
|
||||
if (!Decoder) {
|
||||
this.errored = true;
|
||||
logger.error(24, this.audioType);
|
||||
return Promise.reject(
|
||||
`Cannot decode stream source type of '${this.audioType}', since there is no registered decoder for that type.`
|
||||
);
|
||||
}
|
||||
this.decoder = new Decoder();
|
||||
// 创建数据解析器
|
||||
const mime = mimeTypeMap[this.audioType];
|
||||
const parser = new CodecParser(mime);
|
||||
this.parser = parser;
|
||||
await this.decoder.create();
|
||||
this.headerRecieved = true;
|
||||
}
|
||||
|
||||
const decoder = this.decoder;
|
||||
const parser = this.parser;
|
||||
if (!decoder || !parser) {
|
||||
this.errored = true;
|
||||
return Promise.reject(
|
||||
'No parser or decoder attached in this AudioStreamSource'
|
||||
);
|
||||
}
|
||||
|
||||
await this.decodeData(data, decoder, parser);
|
||||
if (done) await this.decodeFlushData(decoder, parser);
|
||||
this.checkBufferedPlay();
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查采样率,如果还未解析出采样率,那么将设置采样率,如果当前采样率与之前不同,那么发出警告
|
||||
*/
|
||||
private checkSampleRate(info: (OggPage | CodecFrame)[]) {
|
||||
for (const one of info) {
|
||||
const frame = isOggPage(one) ? one.codecFrames[0] : one;
|
||||
if (frame) {
|
||||
const rate = frame.header.sampleRate;
|
||||
if (this.sampleRate === 0) {
|
||||
this.sampleRate = rate;
|
||||
break;
|
||||
} else {
|
||||
if (rate !== this.sampleRate) {
|
||||
logger.warn(48);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析音频数据
|
||||
*/
|
||||
private async decodeData(
|
||||
data: Uint8Array,
|
||||
decoder: AudioDecoder,
|
||||
parser: CodecParser
|
||||
) {
|
||||
// 解析音频数据
|
||||
const audioData = await decoder.decode(data);
|
||||
if (!audioData) return;
|
||||
// @ts-expect-error 库类型声明错误
|
||||
const audioInfo = [...parser.parseChunk(data)] as (
|
||||
| OggPage
|
||||
| CodecFrame
|
||||
)[];
|
||||
|
||||
// 检查采样率
|
||||
this.checkSampleRate(audioInfo);
|
||||
// 追加音频数据
|
||||
this.appendDecodedData(audioData, audioInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解码剩余数据
|
||||
*/
|
||||
private async decodeFlushData(decoder: AudioDecoder, parser: CodecParser) {
|
||||
const audioData = await decoder.flush();
|
||||
if (!audioData) return;
|
||||
// @ts-expect-error 库类型声明错误
|
||||
const audioInfo = [...parser.flush()] as (OggPage | CodecFrame)[];
|
||||
|
||||
this.checkSampleRate(audioInfo);
|
||||
this.appendDecodedData(audioData, audioInfo);
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加音频数据
|
||||
*/
|
||||
private appendDecodedData(
|
||||
data: IAudioDecodeData,
|
||||
info: (CodecFrame | OggPage)[]
|
||||
) {
|
||||
const channels = data.channelData.length;
|
||||
if (channels === 0) return;
|
||||
if (this.audioData.length !== channels) {
|
||||
this.audioData = [];
|
||||
for (let i = 0; i < channels; i++) {
|
||||
this.audioData.push([]);
|
||||
}
|
||||
}
|
||||
// 计算出应该放在哪
|
||||
const chunk = this.sampleRate * this.bufferChunkSize;
|
||||
const sampled = this.bufferedSamples;
|
||||
const pushIndex = Math.floor(sampled / chunk);
|
||||
const bufferIndex = sampled % chunk;
|
||||
const dataLength = data.channelData[0].length;
|
||||
let buffered = 0;
|
||||
let nowIndex = pushIndex;
|
||||
let toBuffer = bufferIndex;
|
||||
while (buffered < dataLength) {
|
||||
const rest = toBuffer !== 0 ? chunk - bufferIndex : chunk;
|
||||
|
||||
for (let i = 0; i < channels; i++) {
|
||||
const audioData = this.audioData[i];
|
||||
if (!audioData[nowIndex]) {
|
||||
audioData.push(new Float32Array(chunk));
|
||||
}
|
||||
const toPush = data.channelData[i].slice(
|
||||
buffered,
|
||||
buffered + rest
|
||||
);
|
||||
|
||||
audioData[nowIndex].set(toPush, toBuffer);
|
||||
}
|
||||
buffered += rest;
|
||||
nowIndex++;
|
||||
toBuffer = 0;
|
||||
}
|
||||
|
||||
this.buffered +=
|
||||
info.reduce((prev, curr) => prev + curr.duration, 0) / 1000;
|
||||
this.bufferedSamples += info.reduce(
|
||||
(prev, curr) => prev + curr.samples,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查已缓冲内容,并在未开始播放时播放
|
||||
*/
|
||||
private checkBufferedPlay() {
|
||||
if (this.playing || this.sampleRate === 0) return;
|
||||
const played = this.lastBufferSamples / this.sampleRate;
|
||||
const dt = this.buffered - played;
|
||||
if (this.loaded) {
|
||||
this.playAudio(played);
|
||||
return;
|
||||
}
|
||||
if (dt < this.bufferPlayDuration) return;
|
||||
this.lastBufferSamples = this.bufferedSamples;
|
||||
// 需要播放
|
||||
this.mergeBuffers();
|
||||
if (!this.buffer) return;
|
||||
if (this.playing) this.output.stop();
|
||||
this.createSourceNode(this.buffer);
|
||||
this.output.loop = false;
|
||||
this.output.start(0, played);
|
||||
this.lastStartTime = this.ac.currentTime;
|
||||
this.playing = true;
|
||||
this.output.addEventListener('ended', () => {
|
||||
this.playing = false;
|
||||
this.checkBufferedPlay();
|
||||
});
|
||||
}
|
||||
|
||||
private mergeBuffers() {
|
||||
const buffer = this.ac.createBuffer(
|
||||
this.audioData.length,
|
||||
this.bufferedSamples,
|
||||
this.sampleRate
|
||||
);
|
||||
const chunk = this.sampleRate * this.bufferChunkSize;
|
||||
const bufferedChunks = Math.floor(this.bufferedSamples / chunk);
|
||||
const restLength = this.bufferedSamples % chunk;
|
||||
for (let i = 0; i < this.audioData.length; i++) {
|
||||
const audio = this.audioData[i];
|
||||
const data = new Float32Array(this.bufferedSamples);
|
||||
for (let j = 0; j < bufferedChunks; j++) {
|
||||
data.set(audio[j], chunk * j);
|
||||
}
|
||||
if (restLength !== 0) {
|
||||
data.set(
|
||||
audio[bufferedChunks].slice(0, restLength),
|
||||
chunk * bufferedChunks
|
||||
);
|
||||
}
|
||||
|
||||
buffer.copyToChannel(data, i, 0);
|
||||
}
|
||||
this.buffer = buffer;
|
||||
}
|
||||
|
||||
async start() {
|
||||
delete this.buffer;
|
||||
this.headerRecieved = false;
|
||||
this.audioType = '';
|
||||
this.errored = false;
|
||||
this.buffered = 0;
|
||||
this.sampleRate = 0;
|
||||
this.bufferedSamples = 0;
|
||||
this.duration = 0;
|
||||
this.loaded = false;
|
||||
if (this.playing) this.output.stop();
|
||||
this.playing = false;
|
||||
this.lastStartTime = this.ac.currentTime;
|
||||
}
|
||||
|
||||
end(done: boolean, reason?: string): void {
|
||||
if (done && this.buffer) {
|
||||
this.loaded = true;
|
||||
delete this.controller;
|
||||
this.mergeBuffers();
|
||||
this.duration = this.buffered;
|
||||
this.audioData = [];
|
||||
this.decoder?.destroy();
|
||||
delete this.decoder;
|
||||
delete this.parser;
|
||||
} else {
|
||||
logger.warn(44, reason ?? '');
|
||||
}
|
||||
}
|
||||
|
||||
private playAudio(when?: number) {
|
||||
if (!this.buffer) return;
|
||||
this.lastStartTime = this.ac.currentTime;
|
||||
if (this.playing) this.output.stop();
|
||||
this.emit('play');
|
||||
this.createSourceNode(this.buffer);
|
||||
this.output.start(0, when);
|
||||
this.playing = true;
|
||||
this.output.addEventListener('ended', () => {
|
||||
this.playing = false;
|
||||
this.emit('end');
|
||||
if (this.loop && !this.output.loop) this.play(0);
|
||||
});
|
||||
}
|
||||
|
||||
play(when?: number): void {
|
||||
if (this.playing || this.errored) return;
|
||||
if (this.loaded && this.buffer) {
|
||||
this.playing = true;
|
||||
this.playAudio(when);
|
||||
} else {
|
||||
this.controller?.start();
|
||||
}
|
||||
}
|
||||
|
||||
private createSourceNode(buffer: AudioBuffer) {
|
||||
if (!this.target) return;
|
||||
const node = this.ac.createBufferSource();
|
||||
node.buffer = buffer;
|
||||
if (this.playing) this.output.stop();
|
||||
this.playing = false;
|
||||
this.output = node;
|
||||
node.connect(this.target.input);
|
||||
node.loop = this.loop;
|
||||
}
|
||||
|
||||
stop(): number {
|
||||
if (this.playing) this.output.stop();
|
||||
this.playing = false;
|
||||
return this.ac.currentTime - this.lastStartTime;
|
||||
}
|
||||
|
||||
connect(target: IAudioInput): void {
|
||||
this.target = target;
|
||||
}
|
||||
|
||||
setLoop(loop: boolean): void {
|
||||
this.loop = loop;
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioElementSource extends AudioSource {
|
||||
output: MediaElementAudioSourceNode;
|
||||
|
||||
/** audio 元素 */
|
||||
readonly audio: HTMLAudioElement;
|
||||
|
||||
get duration(): number {
|
||||
return this.audio.duration;
|
||||
}
|
||||
get currentTime(): number {
|
||||
return this.audio.currentTime;
|
||||
}
|
||||
|
||||
constructor(context: AudioContext) {
|
||||
super(context);
|
||||
const audio = new Audio();
|
||||
audio.preload = 'none';
|
||||
this.output = context.createMediaElementSource(audio);
|
||||
this.audio = audio;
|
||||
audio.addEventListener('play', () => {
|
||||
this.playing = true;
|
||||
this.emit('play');
|
||||
});
|
||||
audio.addEventListener('ended', () => {
|
||||
this.playing = false;
|
||||
this.emit('end');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置音频源的路径
|
||||
* @param url 音频路径
|
||||
*/
|
||||
setSource(url: string) {
|
||||
this.audio.src = url;
|
||||
}
|
||||
|
||||
play(when: number = 0): void {
|
||||
if (this.playing) return;
|
||||
this.audio.currentTime = when;
|
||||
this.audio.play();
|
||||
}
|
||||
|
||||
stop(): number {
|
||||
this.audio.pause();
|
||||
this.playing = false;
|
||||
this.emit('end');
|
||||
return this.audio.currentTime;
|
||||
}
|
||||
|
||||
connect(target: IAudioInput): void {
|
||||
this.output.connect(target.input);
|
||||
}
|
||||
|
||||
setLoop(loop: boolean): void {
|
||||
this.audio.loop = loop;
|
||||
}
|
||||
}
|
||||
|
||||
export class AudioBufferSource extends AudioSource {
|
||||
output: AudioBufferSourceNode;
|
||||
|
||||
/** 音频数据 */
|
||||
buffer?: AudioBuffer;
|
||||
/** 是否循环 */
|
||||
private loop: boolean = false;
|
||||
|
||||
duration: number = 0;
|
||||
get currentTime(): number {
|
||||
return this.ac.currentTime - this.lastStartTime + this.lastStartWhen;
|
||||
}
|
||||
|
||||
/** 上一次播放是从何时开始的 */
|
||||
private lastStartWhen: number = 0;
|
||||
/** 播放开始时刻 */
|
||||
private lastStartTime: number = 0;
|
||||
private target?: IAudioInput;
|
||||
|
||||
constructor(context: AudioContext) {
|
||||
super(context);
|
||||
this.output = context.createBufferSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置音频源数据
|
||||
* @param buffer 音频源,可以是未解析的 ArrayBuffer,也可以是已解析的 AudioBuffer
|
||||
*/
|
||||
async setBuffer(buffer: ArrayBuffer | AudioBuffer) {
|
||||
if (buffer instanceof ArrayBuffer) {
|
||||
this.buffer = await this.ac.decodeAudioData(buffer);
|
||||
} else {
|
||||
this.buffer = buffer;
|
||||
}
|
||||
this.duration = this.buffer.duration;
|
||||
}
|
||||
|
||||
play(when?: number): void {
|
||||
if (this.playing || !this.buffer) return;
|
||||
this.playing = true;
|
||||
this.lastStartTime = this.ac.currentTime;
|
||||
this.emit('play');
|
||||
this.createSourceNode(this.buffer);
|
||||
this.output.start(0, when);
|
||||
this.output.addEventListener('ended', () => {
|
||||
this.playing = false;
|
||||
this.emit('end');
|
||||
if (this.loop && !this.output.loop) this.play(0);
|
||||
});
|
||||
}
|
||||
|
||||
private createSourceNode(buffer: AudioBuffer) {
|
||||
if (!this.target) return;
|
||||
const node = this.ac.createBufferSource();
|
||||
node.buffer = buffer;
|
||||
this.output = node;
|
||||
node.connect(this.target.input);
|
||||
node.loop = this.loop;
|
||||
}
|
||||
|
||||
stop(): number {
|
||||
this.output.stop();
|
||||
return this.ac.currentTime - this.lastStartTime;
|
||||
}
|
||||
|
||||
connect(target: IAudioInput): void {
|
||||
this.target = target;
|
||||
}
|
||||
|
||||
setLoop(loop: boolean): void {
|
||||
this.loop = loop;
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
const audio = new Audio();
|
||||
|
||||
const supportMap = new Map<string, boolean>();
|
||||
|
||||
export const enum AudioType {
|
||||
Mp3 = 'audio/mpeg',
|
||||
Wav = 'audio/wav; codecs="1"',
|
||||
Flac = 'audio/flac',
|
||||
Opus = 'audio/ogg; codecs="opus"',
|
||||
Ogg = 'audio/ogg; codecs="vorbis"',
|
||||
Aac = 'audio/aac'
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查一种音频类型是否能被播放
|
||||
* @param type 音频类型
|
||||
*/
|
||||
export function isAudioSupport(type: AudioType): boolean {
|
||||
if (supportMap.has(type)) return supportMap.get(type)!;
|
||||
else {
|
||||
const support = audio.canPlayType(type);
|
||||
const canPlay = support === 'maybe' || support === 'probably';
|
||||
supportMap.set(type, canPlay);
|
||||
return canPlay;
|
||||
}
|
||||
}
|
||||
|
||||
const typeMap = new Map<string, AudioType>([
|
||||
['ogg', AudioType.Ogg],
|
||||
['mp3', AudioType.Mp3],
|
||||
['wav', AudioType.Wav],
|
||||
['flac', AudioType.Flac],
|
||||
['opus', AudioType.Opus],
|
||||
['aac', AudioType.Aac]
|
||||
]);
|
||||
|
||||
/**
|
||||
* 根据文件名拓展猜测其类型
|
||||
* @param file 文件名
|
||||
*/
|
||||
export function guessTypeByExt(file: string): AudioType | '' {
|
||||
const ext = /\.[a-zA-Z\d]+$/.exec(file);
|
||||
if (!ext?.[0]) return '';
|
||||
const type = ext[0].slice(1);
|
||||
return typeMap.get(type.toLocaleLowerCase()) ?? '';
|
||||
}
|
||||
|
||||
isAudioSupport(AudioType.Ogg);
|
||||
isAudioSupport(AudioType.Mp3);
|
||||
isAudioSupport(AudioType.Wav);
|
||||
isAudioSupport(AudioType.Flac);
|
||||
isAudioSupport(AudioType.Opus);
|
||||
isAudioSupport(AudioType.Aac);
|
||||
|
||||
console.log(supportMap);
|
||||
@@ -1,70 +0,0 @@
|
||||
import { Patch, PatchClass } from '@motajs/legacy-common';
|
||||
import { audioPlayer, bgmController, soundPlayer } from '../audio';
|
||||
import { mainSetting } from '@motajs/legacy-ui';
|
||||
import { sleep } from 'mutate-animate';
|
||||
import { isNil } from 'lodash-es';
|
||||
|
||||
// todo: 添加弃用警告 logger.warn(56)
|
||||
|
||||
export function patchAudio() {
|
||||
const patch = new Patch(PatchClass.Control);
|
||||
|
||||
const play = (bgm: BgmIds, when?: number) => {
|
||||
bgmController.play(bgm, when);
|
||||
};
|
||||
const pause = () => {
|
||||
bgmController.pause();
|
||||
};
|
||||
|
||||
patch.add('playBgm', function (bgm, startTime) {
|
||||
play(bgm, startTime);
|
||||
});
|
||||
patch.add('pauseBgm', function () {
|
||||
pause();
|
||||
});
|
||||
patch.add('resumeBgm', function () {
|
||||
bgmController.resume();
|
||||
});
|
||||
patch.add('checkBgm', function () {
|
||||
if (bgmController.playing) return;
|
||||
if (mainSetting.getValue('audio.bgmEnabled')) {
|
||||
if (bgmController.playingBgm) {
|
||||
bgmController.play(bgmController.playingBgm);
|
||||
} else {
|
||||
play(main.startBgm, 0);
|
||||
}
|
||||
} else {
|
||||
pause();
|
||||
}
|
||||
});
|
||||
patch.add('triggerBgm', function () {
|
||||
if (bgmController.playing) bgmController.pause();
|
||||
else bgmController.resume();
|
||||
});
|
||||
|
||||
patch.add(
|
||||
'playSound',
|
||||
function (sound, _pitch, callback, position, orientation) {
|
||||
const name = core.getMappedName(sound) as SoundIds;
|
||||
const num = soundPlayer.play(name, position, orientation);
|
||||
const route = audioPlayer.getRoute(`sounds.${num}`);
|
||||
if (!route) {
|
||||
callback?.();
|
||||
return -1;
|
||||
} else {
|
||||
sleep(route.duration).then(() => callback?.());
|
||||
return num;
|
||||
}
|
||||
}
|
||||
);
|
||||
patch.add('stopSound', function (id) {
|
||||
if (isNil(id)) {
|
||||
soundPlayer.stopAllSounds();
|
||||
} else {
|
||||
soundPlayer.stop(id);
|
||||
}
|
||||
});
|
||||
patch.add('getPlayingSounds', function () {
|
||||
return [...soundPlayer.playing];
|
||||
});
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { Patch } from '@motajs/legacy-common';
|
||||
import { patchAudio } from './audio';
|
||||
import { patchWeather } from './weather';
|
||||
import { patchUI } from './ui';
|
||||
|
||||
export function patchAll() {
|
||||
patchAudio();
|
||||
patchWeather();
|
||||
patchUI();
|
||||
const loading = Mota.require('var', 'loading');
|
||||
loading.once('coreInit', () => {
|
||||
Patch.patchAll();
|
||||
});
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import { Patch, PatchClass } from '@motajs/legacy-common';
|
||||
import { TipStore } from '../render/components/tip';
|
||||
|
||||
export function patchUI() {
|
||||
const patch = new Patch(PatchClass.UI);
|
||||
|
||||
patch.add('drawTip', function (text, id) {
|
||||
const tip = TipStore.get('main-tip');
|
||||
tip?.drawTip(text, id);
|
||||
});
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { Patch, PatchClass } from '@motajs/legacy-common';
|
||||
import { WeatherController } from '../weather';
|
||||
import { isNil } from 'lodash-es';
|
||||
|
||||
// todo: 添加弃用警告 logger.warn(56)
|
||||
|
||||
export function patchWeather() {
|
||||
const patch = new Patch(PatchClass.Control);
|
||||
let nowWeather: string = '';
|
||||
let nowLevel: number = 0;
|
||||
|
||||
patch.add('setWeather', (type, level) => {
|
||||
const weather = WeatherController.get('main');
|
||||
if (!weather) return;
|
||||
if (type === nowWeather && level === nowLevel) return;
|
||||
weather.clearWeather();
|
||||
if (!isNil(type)) {
|
||||
weather.activate(type, level);
|
||||
nowWeather = type;
|
||||
nowLevel = level ?? 5;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { patchAll } from './fallback';
|
||||
|
||||
patchAll();
|
||||
|
||||
export * from './weather';
|
||||
export * from './audio';
|
||||
export * from './loader';
|
||||
export * from './fallback';
|
||||
export * from './render';
|
||||
@@ -1 +0,0 @@
|
||||
export * from './stream';
|
||||
@@ -1,128 +0,0 @@
|
||||
import { logger } from '@motajs/common';
|
||||
import EventEmitter from 'eventemitter3';
|
||||
|
||||
export interface IStreamController<T = void> {
|
||||
readonly loading: boolean;
|
||||
|
||||
/**
|
||||
* 开始流传输
|
||||
*/
|
||||
start(): Promise<T>;
|
||||
|
||||
/**
|
||||
* 主动终止流传输
|
||||
* @param reason 终止原因
|
||||
*/
|
||||
cancel(reason?: string): void;
|
||||
}
|
||||
|
||||
export interface IStreamReader<T = any> {
|
||||
/**
|
||||
* 接受字节流流传输的数据
|
||||
* @param data 传入的字节流数据,只包含本分块的内容
|
||||
* @param done 是否传输完成
|
||||
*/
|
||||
pump(
|
||||
data: Uint8Array | undefined,
|
||||
done: boolean,
|
||||
response: Response
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* 当前对象被传递给加载流时执行的函数
|
||||
* @param controller 传输流控制对象
|
||||
*/
|
||||
piped(controller: IStreamController<T>): void;
|
||||
|
||||
/**
|
||||
* 开始流传输
|
||||
* @param stream 传输流对象
|
||||
* @param controller 传输流控制对象
|
||||
*/
|
||||
start(
|
||||
stream: ReadableStream,
|
||||
controller: IStreamController<T>,
|
||||
response: Response
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* 结束流传输
|
||||
* @param done 是否传输完成,如果为 false 的话,说明可能是由于出现错误导致的终止
|
||||
* @param reason 如果没有传输完成,那么表示失败的原因
|
||||
*/
|
||||
end(done: boolean, reason?: string): void;
|
||||
}
|
||||
|
||||
interface StreamLoaderEvent {
|
||||
data: [data: Uint8Array | undefined, done: boolean];
|
||||
}
|
||||
|
||||
export class StreamLoader
|
||||
extends EventEmitter<StreamLoaderEvent>
|
||||
implements IStreamController<void>
|
||||
{
|
||||
/** 传输目标 */
|
||||
private target: Set<IStreamReader> = new Set();
|
||||
/** 读取流对象 */
|
||||
private stream?: ReadableStream;
|
||||
|
||||
loading: boolean = false;
|
||||
|
||||
constructor(public readonly url: string) {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* 将加载流传递给字节流读取对象
|
||||
* @param reader 字节流读取对象
|
||||
*/
|
||||
pipe(reader: IStreamReader) {
|
||||
if (this.loading) {
|
||||
logger.warn(46);
|
||||
return;
|
||||
}
|
||||
this.target.add(reader);
|
||||
reader.piped(this);
|
||||
return this;
|
||||
}
|
||||
|
||||
async start() {
|
||||
if (this.loading) return;
|
||||
this.loading = true;
|
||||
const response = await window.fetch(this.url);
|
||||
const stream = response.body;
|
||||
if (!stream) {
|
||||
logger.error(23);
|
||||
return;
|
||||
}
|
||||
// 获取读取器
|
||||
this.stream = stream;
|
||||
const reader = response.body?.getReader();
|
||||
const targets = [...this.target];
|
||||
await Promise.all(targets.map(v => v.start(stream, this, response)));
|
||||
if (reader && reader.read) {
|
||||
// 开始流传输
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
await Promise.all(
|
||||
targets.map(v => v.pump(value, done, response))
|
||||
);
|
||||
if (done) break;
|
||||
}
|
||||
} else {
|
||||
// 如果不支持流传输
|
||||
const buffer = await response.arrayBuffer();
|
||||
const data = new Uint8Array(buffer);
|
||||
await Promise.all(targets.map(v => v.pump(data, true, response)));
|
||||
}
|
||||
this.loading = false;
|
||||
targets.forEach(v => v.end(true));
|
||||
}
|
||||
|
||||
cancel(reason?: string) {
|
||||
if (!this.stream) return;
|
||||
this.stream.cancel(reason);
|
||||
this.loading = false;
|
||||
this.target.forEach(v => v.end(false, reason));
|
||||
}
|
||||
}
|
||||
@@ -1,637 +0,0 @@
|
||||
import { DefaultProps, ElementLocator, Font, useKey } from '@motajs/render';
|
||||
import { computed, defineComponent, reactive, ref } from 'vue';
|
||||
import { Background, Selection } from './misc';
|
||||
import { TextContent, TextContentExpose, TextContentProps } from './textbox';
|
||||
import { SetupComponentOptions } from './types';
|
||||
import { TextAlign } from './textboxTyper';
|
||||
import { Page, PageExpose } from './page';
|
||||
import { GameUI, IUIMountable } from '@motajs/system-ui';
|
||||
|
||||
export interface ConfirmBoxProps extends DefaultProps, TextContentProps {
|
||||
text: string;
|
||||
width: number;
|
||||
loc: ElementLocator;
|
||||
selFont?: Font;
|
||||
selFill?: CanvasStyle;
|
||||
pad?: number;
|
||||
yesText?: string;
|
||||
noText?: string;
|
||||
winskin?: ImageIds;
|
||||
defaultYes?: boolean;
|
||||
color?: CanvasStyle;
|
||||
border?: CanvasStyle;
|
||||
}
|
||||
|
||||
export type ConfirmBoxEmits = {
|
||||
yes: () => void;
|
||||
no: () => void;
|
||||
};
|
||||
|
||||
const confirmBoxProps = {
|
||||
props: [
|
||||
'text',
|
||||
'width',
|
||||
'loc',
|
||||
'selFont',
|
||||
'selFill',
|
||||
'pad',
|
||||
'yesText',
|
||||
'noText',
|
||||
'winskin',
|
||||
'defaultYes',
|
||||
'color',
|
||||
'border'
|
||||
],
|
||||
emits: ['no', 'yes']
|
||||
} satisfies SetupComponentOptions<
|
||||
ConfirmBoxProps,
|
||||
ConfirmBoxEmits,
|
||||
keyof ConfirmBoxEmits
|
||||
>;
|
||||
|
||||
/**
|
||||
* 确认框组件,与 2.x 的 drawConfirm 类似,可以键盘操作,单次调用参考 {@link getConfirm}。
|
||||
* 参数参考 {@link ConfirmBoxProps},事件参考 {@link ConfirmBoxEmits},用例如下:
|
||||
* ```tsx
|
||||
* const onYes = () => console.log('yes');
|
||||
* const onNo = () => console.log('no');
|
||||
*
|
||||
* <ConfirmBox
|
||||
* text="是否要返回标题界面"
|
||||
* width={240}
|
||||
* // 确认框会自动计算宽度和高度,因此不需要手动指定,即使手动指定也无效
|
||||
* loc={[240, 240, void 0, void 0, 0.5, 0.5]}
|
||||
* // 使用 winskin 图片作为背景
|
||||
* winskin="winskin.png"
|
||||
* // 使用颜色作为背景和边框,如果设置了 winskin,那么此参数无效
|
||||
* color="#333"
|
||||
* border="gold"
|
||||
* // 设置选项的字体
|
||||
* selFont={new Font('Verdana', 16)}
|
||||
* // 设置选项的文本颜色
|
||||
* selFill="#d48"
|
||||
* // 完全继承 TextContent 的参数,因此可以填写 font 参数指定文本字体
|
||||
* font={new Font('arial')}
|
||||
* onYes={onYes}
|
||||
* onNo={onNo}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export const ConfirmBox = defineComponent<
|
||||
ConfirmBoxProps,
|
||||
ConfirmBoxEmits,
|
||||
keyof ConfirmBoxEmits
|
||||
>((props, { emit, attrs }) => {
|
||||
const content = ref<TextContentExpose>();
|
||||
const height = ref(200);
|
||||
const selected = ref(props.defaultYes ? true : false);
|
||||
const yesSize = ref<[number, number]>([0, 0]);
|
||||
const noSize = ref<[number, number]>([0, 0]);
|
||||
|
||||
const loc = computed<ElementLocator>(() => {
|
||||
const [x = 0, y = 0, , , ax = 0, ay = 0] = props.loc;
|
||||
return [x, y, props.width, height.value, ax, ay];
|
||||
});
|
||||
const yesText = computed(() => props.yesText ?? '确认');
|
||||
const noText = computed(() => props.noText ?? '取消');
|
||||
const pad = computed(() => props.pad ?? 32);
|
||||
const yesLoc = computed<ElementLocator>(() => {
|
||||
const y = height.value - pad.value;
|
||||
return [props.width / 3, y, void 0, void 0, 0.5, 1];
|
||||
});
|
||||
const noLoc = computed<ElementLocator>(() => {
|
||||
const y = height.value - pad.value;
|
||||
return [(props.width / 3) * 2, y, void 0, void 0, 0.5, 1];
|
||||
});
|
||||
const contentLoc = computed<ElementLocator>(() => {
|
||||
const width = props.width - pad.value * 2;
|
||||
return [props.width / 2, pad.value, width, 0, 0.5, 0];
|
||||
});
|
||||
const selectLoc = computed<ElementLocator>(() => {
|
||||
if (selected.value) {
|
||||
const [x = 0, y = 0] = yesLoc.value;
|
||||
const [width, height] = yesSize.value;
|
||||
return [x, y + 4, width + 8, height + 8, 0.5, 1];
|
||||
} else {
|
||||
const [x = 0, y = 0] = noLoc.value;
|
||||
const [width, height] = noSize.value;
|
||||
return [x, y + 4, width + 8, height + 8, 0.5, 1];
|
||||
}
|
||||
});
|
||||
|
||||
const onUpdateHeight = (textHeight: number) => {
|
||||
height.value = textHeight + pad.value * 4;
|
||||
};
|
||||
|
||||
const setYes = (_: string, width: number, height: number) => {
|
||||
yesSize.value = [width, height];
|
||||
};
|
||||
|
||||
const setNo = (_: string, width: number, height: number) => {
|
||||
noSize.value = [width, height];
|
||||
};
|
||||
|
||||
const [key] = useKey();
|
||||
key.realize('confirm', () => {
|
||||
if (selected.value) emit('yes');
|
||||
else emit('no');
|
||||
});
|
||||
key.realize('moveLeft', () => void (selected.value = true));
|
||||
key.realize('moveRight', () => void (selected.value = false));
|
||||
|
||||
return () => (
|
||||
<container loc={loc.value}>
|
||||
<Background
|
||||
loc={[0, 0, props.width, height.value]}
|
||||
winskin={props.winskin}
|
||||
color={props.color}
|
||||
border={props.border}
|
||||
zIndex={0}
|
||||
/>
|
||||
<TextContent
|
||||
{...attrs}
|
||||
ref={content}
|
||||
loc={contentLoc.value}
|
||||
text={props.text}
|
||||
width={props.width - pad.value * 2}
|
||||
zIndex={5}
|
||||
textAlign={TextAlign.Center}
|
||||
autoHeight
|
||||
onUpdateHeight={onUpdateHeight}
|
||||
/>
|
||||
<Selection
|
||||
loc={selectLoc.value}
|
||||
winskin={props.winskin}
|
||||
border={props.border}
|
||||
noevent
|
||||
zIndex={10}
|
||||
/>
|
||||
<text
|
||||
loc={yesLoc.value}
|
||||
text={yesText.value}
|
||||
fillStyle={props.selFill}
|
||||
font={props.selFont}
|
||||
cursor="pointer"
|
||||
zIndex={15}
|
||||
onClick={() => emit('yes')}
|
||||
onEnter={() => (selected.value = true)}
|
||||
onSetText={setYes}
|
||||
/>
|
||||
<text
|
||||
loc={noLoc.value}
|
||||
text={noText.value}
|
||||
fillStyle={props.selFill}
|
||||
font={props.selFont}
|
||||
cursor="pointer"
|
||||
zIndex={15}
|
||||
onClick={() => emit('no')}
|
||||
onEnter={() => (selected.value = false)}
|
||||
onSetText={setNo}
|
||||
/>
|
||||
</container>
|
||||
);
|
||||
}, confirmBoxProps);
|
||||
|
||||
export type ChoiceKey = string | number | symbol;
|
||||
export type ChoiceItem = [key: ChoiceKey, text: string];
|
||||
|
||||
export interface ChoicesProps extends DefaultProps, TextContentProps {
|
||||
choices: ChoiceItem[];
|
||||
loc: ElementLocator;
|
||||
width: number;
|
||||
maxHeight?: number;
|
||||
text?: string;
|
||||
title?: string;
|
||||
winskin?: ImageIds;
|
||||
color?: CanvasStyle;
|
||||
border?: CanvasStyle;
|
||||
selFont?: Font;
|
||||
selFill?: CanvasStyle;
|
||||
titleFont?: Font;
|
||||
titleFill?: CanvasStyle;
|
||||
pad?: number;
|
||||
interval?: number;
|
||||
}
|
||||
|
||||
export type ChoicesEmits = {
|
||||
choose: (key: ChoiceKey) => void;
|
||||
};
|
||||
|
||||
const choicesProps = {
|
||||
props: [
|
||||
'choices',
|
||||
'loc',
|
||||
'width',
|
||||
'maxHeight',
|
||||
'text',
|
||||
'title',
|
||||
'winskin',
|
||||
'color',
|
||||
'border',
|
||||
'selFont',
|
||||
'selFill',
|
||||
'titleFont',
|
||||
'titleFill',
|
||||
'pad',
|
||||
'interval'
|
||||
],
|
||||
emits: ['choose']
|
||||
} satisfies SetupComponentOptions<
|
||||
ChoicesProps,
|
||||
ChoicesEmits,
|
||||
keyof ChoicesEmits
|
||||
>;
|
||||
|
||||
/**
|
||||
* 选项框组件,用于在多个选项中选择一个,例如样板的系统设置就由它实现。单次调用参考 {@link getChoice}。
|
||||
* 参数参考 {@link ChoicesProps},事件参考 {@link ChoicesEmits}。用例如下:
|
||||
* ```tsx
|
||||
* <Choices
|
||||
* // 选项数组,每一项是一个二元素数组,第一项表示这个选项的 id,在选中时会以此作为参数传递给事件
|
||||
* // 第二项表示这一项的内容,即展示给玩家看的内容
|
||||
* choices={[[0, '选项1'], [100, '选项2']]}
|
||||
* // 选项框会自动计算宽度和高度,因此不需要手动指定,即使手动指定也无效
|
||||
* loc={[240, 240, void 0, void 0, 0.5, 0.5]}
|
||||
* text="请选择一项"
|
||||
* title="选项"
|
||||
* // 使用 winskin 图片作为背景
|
||||
* winskin="winskin.png"
|
||||
* // 使用颜色作为背景和边框,如果设置了 winskin,那么此参数无效
|
||||
* color="#333"
|
||||
* border="gold"
|
||||
* // 调整每两个选项之间的间隔
|
||||
* interval={12}
|
||||
* // 设置选项的字体
|
||||
* selFont={new Font('Verdana', 16)}
|
||||
* // 设置选项的文本颜色
|
||||
* selFill="#d48"
|
||||
* // 设置标题的字体
|
||||
* titleFont={new Font('Verdana', 16)}
|
||||
* // 设置标题的文本颜色
|
||||
* selFill="gold"
|
||||
* // 完全继承 TextContent 的参数,因此可以填写 font 参数指定文本字体
|
||||
* font={new Font('arial')}
|
||||
* // 当选择某一项时触发
|
||||
* onChoice={(choice) => console.log(choice)}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export const Choices = defineComponent<
|
||||
ChoicesProps,
|
||||
ChoicesEmits,
|
||||
keyof ChoicesEmits
|
||||
>((props, { emit, attrs }) => {
|
||||
const titleHeight = ref(0);
|
||||
const contentHeight = ref(0);
|
||||
const selected = ref(0);
|
||||
const pageCom = ref<PageExpose>();
|
||||
const choiceSize = reactive<[number, number][]>([]);
|
||||
|
||||
const selFont = computed(() => props.selFont ?? new Font());
|
||||
const maxHeight = computed(() => props.maxHeight ?? 360);
|
||||
const pad = computed(() => props.pad ?? 28);
|
||||
const choiceInterval = computed(() => props.interval ?? 16);
|
||||
const hasText = computed(() => !!props.text);
|
||||
const hasTitle = computed(() => !!props.title);
|
||||
const contentWidth = computed(() => props.width - pad.value * 2);
|
||||
const choiceHeight = computed(
|
||||
() => selFont.value.size + 8 + choiceInterval.value
|
||||
);
|
||||
const contentY = computed(() => {
|
||||
if (hasTitle.value) {
|
||||
return pad.value * 2 + titleHeight.value;
|
||||
} else {
|
||||
return pad.value;
|
||||
}
|
||||
});
|
||||
const choicesY = computed(() => {
|
||||
const padding = pad.value;
|
||||
const text = hasText.value;
|
||||
let y = padding;
|
||||
if (hasTitle.value) {
|
||||
y += titleHeight.value;
|
||||
if (text) {
|
||||
y += padding / 2;
|
||||
} else {
|
||||
y += padding;
|
||||
}
|
||||
}
|
||||
if (text) {
|
||||
y += contentHeight.value;
|
||||
y += padding / 2;
|
||||
}
|
||||
return y;
|
||||
});
|
||||
const choicesMaxHeight = computed(
|
||||
() =>
|
||||
maxHeight.value -
|
||||
choicesY.value -
|
||||
pad.value * 2 -
|
||||
selFont.value.size -
|
||||
8
|
||||
);
|
||||
const choiceCountPerPage = computed(() =>
|
||||
Math.max(Math.floor(choicesMaxHeight.value / choiceHeight.value), 1)
|
||||
);
|
||||
const pages = computed(() =>
|
||||
Math.ceil(props.choices.length / choiceCountPerPage.value)
|
||||
);
|
||||
const choicesHeight = computed(() => {
|
||||
const padBottom = pages.value > 1 ? pad.value + selFont.value.size : 0;
|
||||
if (props.choices.length > choiceCountPerPage.value) {
|
||||
return choiceCountPerPage.value * choiceHeight.value + padBottom;
|
||||
} else {
|
||||
return props.choices.length * choiceHeight.value + padBottom;
|
||||
}
|
||||
});
|
||||
const boxHeight = computed(() => {
|
||||
if (props.choices.length > choiceCountPerPage.value) {
|
||||
return (
|
||||
choicesHeight.value +
|
||||
choicesY.value +
|
||||
// 不乘2是因为 choiceY 已经算上了顶部填充
|
||||
pad.value
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
choicesHeight.value +
|
||||
choicesY.value +
|
||||
// 不乘2是因为 choiceY 已经算上了顶部填充
|
||||
pad.value
|
||||
);
|
||||
}
|
||||
});
|
||||
const boxLoc = computed<ElementLocator>(() => {
|
||||
const [x = 0, y = 0, , , ax = 0, ay = 0] = props.loc;
|
||||
return [x, y, props.width, boxHeight.value, ax, ay];
|
||||
});
|
||||
const titleLoc = computed<ElementLocator>(() => {
|
||||
return [props.width / 2, pad.value, void 0, void 0, 0.5, 0];
|
||||
});
|
||||
const contentLoc = computed<ElementLocator>(() => {
|
||||
return [
|
||||
props.width / 2,
|
||||
contentY.value,
|
||||
contentWidth.value,
|
||||
void 0,
|
||||
0.5,
|
||||
0
|
||||
];
|
||||
});
|
||||
const choiceLoc = computed<ElementLocator>(() => {
|
||||
return [
|
||||
props.width / 2,
|
||||
choicesY.value,
|
||||
contentWidth.value,
|
||||
choicesHeight.value,
|
||||
0.5,
|
||||
0
|
||||
];
|
||||
});
|
||||
const selectionLoc = computed<ElementLocator>(() => {
|
||||
const [width = 200, height = 200] = choiceSize[selected.value] ?? [];
|
||||
return [
|
||||
props.width / 2 - pad.value,
|
||||
(selected.value + 0.5) * choiceHeight.value,
|
||||
width + 8,
|
||||
height + 8,
|
||||
0.5,
|
||||
0.5
|
||||
];
|
||||
});
|
||||
|
||||
const getPageContent = (page: number) => {
|
||||
const count = choiceCountPerPage.value;
|
||||
return props.choices.slice(page * count, (page + 1) * count);
|
||||
};
|
||||
|
||||
const getChoiceLoc = (index: number): ElementLocator => {
|
||||
return [
|
||||
props.width / 2 - pad.value,
|
||||
choiceHeight.value * (index + 0.5),
|
||||
void 0,
|
||||
void 0,
|
||||
0.5,
|
||||
0.5
|
||||
];
|
||||
};
|
||||
|
||||
const updateContentHeight = (height: number) => {
|
||||
contentHeight.value = height;
|
||||
};
|
||||
|
||||
const updateTitleHeight = (_0: string, _1: number, height: number) => {
|
||||
titleHeight.value = height;
|
||||
};
|
||||
|
||||
const updateChoiceSize = (index: number, width: number, height: number) => {
|
||||
choiceSize[index] = [width, height];
|
||||
};
|
||||
|
||||
const onPageChange = () => {
|
||||
selected.value = 0;
|
||||
};
|
||||
|
||||
const [key] = useKey();
|
||||
key.realize('moveUp', () => {
|
||||
if (selected.value === 0) {
|
||||
if (pageCom.value?.now() !== 0) {
|
||||
pageCom.value?.movePage(-1);
|
||||
selected.value = choiceCountPerPage.value - 1;
|
||||
}
|
||||
} else {
|
||||
selected.value--;
|
||||
}
|
||||
});
|
||||
key.realize('moveDown', () => {
|
||||
if (selected.value === choiceCountPerPage.value - 1) {
|
||||
pageCom.value?.movePage(1);
|
||||
selected.value = 0;
|
||||
} else {
|
||||
const page = pageCom.value?.now() ?? 1;
|
||||
const index = page * choiceCountPerPage.value + selected.value;
|
||||
if (index < props.choices.length - 1) {
|
||||
selected.value++;
|
||||
}
|
||||
}
|
||||
});
|
||||
key.realize('moveLeft', () => pageCom.value?.movePage(-1));
|
||||
key.realize('moveRight', () => pageCom.value?.movePage(1));
|
||||
key.realize('confirm', () => {
|
||||
const page = pageCom.value?.now() ?? 1;
|
||||
const index = page * choiceCountPerPage.value + selected.value;
|
||||
emit('choose', props.choices[index][0]);
|
||||
});
|
||||
|
||||
return () => (
|
||||
<container loc={boxLoc.value}>
|
||||
<Background
|
||||
loc={[0, 0, props.width, boxHeight.value]}
|
||||
winskin={props.winskin}
|
||||
color={props.color}
|
||||
border={props.border}
|
||||
/>
|
||||
{hasTitle.value && (
|
||||
<text
|
||||
loc={titleLoc.value}
|
||||
text={props.title}
|
||||
font={props.titleFont ?? new Font(void 0, 18)}
|
||||
fillStyle={props.titleFill ?? 'gold'}
|
||||
zIndex={5}
|
||||
onSetText={updateTitleHeight}
|
||||
/>
|
||||
)}
|
||||
{hasText.value && (
|
||||
<TextContent
|
||||
{...attrs}
|
||||
text={props.text}
|
||||
loc={contentLoc.value}
|
||||
width={contentWidth.value}
|
||||
zIndex={5}
|
||||
autoHeight
|
||||
onUpdateHeight={updateContentHeight}
|
||||
/>
|
||||
)}
|
||||
<Page
|
||||
ref={pageCom}
|
||||
loc={choiceLoc.value}
|
||||
pages={pages.value}
|
||||
font={props.selFont}
|
||||
hideIfSingle
|
||||
onPageChange={onPageChange}
|
||||
>
|
||||
{(page: number) => [
|
||||
<Selection
|
||||
loc={selectionLoc.value}
|
||||
winskin={props.winskin}
|
||||
color={props.color}
|
||||
border={props.border}
|
||||
/>,
|
||||
...getPageContent(page).map((v, i) => {
|
||||
return (
|
||||
<text
|
||||
text={v[1]}
|
||||
loc={getChoiceLoc(i)}
|
||||
font={props.selFont}
|
||||
cursor="pointer"
|
||||
zIndex={5}
|
||||
onClick={() => emit('choose', v[0])}
|
||||
onSetText={(_, width, height) =>
|
||||
updateChoiceSize(i, width, height)
|
||||
}
|
||||
onEnter={() => (selected.value = i)}
|
||||
/>
|
||||
);
|
||||
})
|
||||
]}
|
||||
</Page>
|
||||
</container>
|
||||
);
|
||||
}, choicesProps);
|
||||
|
||||
/**
|
||||
* 弹出一个确认框,然后将确认结果返回,例如给玩家弹出一个确认框,并获取玩家是否确认:
|
||||
* ```ts
|
||||
* const confirm = await getConfirm(
|
||||
* // 在哪个 UI 控制器上打开,对于一般 UI 组件来说,直接填写 props.controller 即可
|
||||
* props.controller,
|
||||
* // 确认内容
|
||||
* '确认要 xxx 吗?',
|
||||
* // 确认框的位置,宽度由下一个参数指定,高度参数由组件内部计算得出,指定无效
|
||||
* [240, 240, void 0, void 0, 0.5, 0.5],
|
||||
* // 宽度设为 240
|
||||
* 240,
|
||||
* // 可以给选择框传入其他的 props,例如指定字体,此项可选
|
||||
* { font: new Font('Verdana', 20) }
|
||||
* );
|
||||
* // 之后,就可以直接判断 confirm 来执行不同的操作了
|
||||
* if (confirm) { ... }
|
||||
* ```
|
||||
* @param controller UI 控制器
|
||||
* @param text 确认文本内容
|
||||
* @param loc 确认框的位置
|
||||
* @param width 确认框的宽度
|
||||
* @param props 额外的 props,参考 {@link ConfirmBoxProps}
|
||||
*/
|
||||
export function getConfirm(
|
||||
controller: IUIMountable,
|
||||
text: string,
|
||||
loc: ElementLocator,
|
||||
width: number,
|
||||
props?: Partial<ConfirmBoxProps>
|
||||
) {
|
||||
return new Promise<boolean>(res => {
|
||||
const instance = controller.open(
|
||||
ConfirmBoxUI,
|
||||
{
|
||||
...(props ?? {}),
|
||||
loc,
|
||||
text,
|
||||
width,
|
||||
onYes: () => {
|
||||
controller.close(instance);
|
||||
res(true);
|
||||
},
|
||||
onNo: () => {
|
||||
controller.close(instance);
|
||||
res(false);
|
||||
}
|
||||
},
|
||||
true
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 弹出一个选择框,然后将选择结果返回,例如给玩家弹出一个选择框,并获取玩家选择了哪个:
|
||||
* ```ts
|
||||
* const choice = await getChoice(
|
||||
* // 在哪个 UI 控制器上打开,对于一般 UI 组件来说,直接填写 props.controller 即可
|
||||
* props.controller,
|
||||
* // 选项内容,参考 Choices 的注释
|
||||
* [[0, '选项1'], [1, '选项2'], [2, '选项3']],
|
||||
* // 选择框的位置,宽度由下一个参数指定,高度参数由组件内部计算得出,指定无效
|
||||
* [240, 240, void 0, void 0, 0.5, 0.5],
|
||||
* // 宽度设为 240
|
||||
* 240,
|
||||
* // 可以给选择框传入其他的 props,例如指定标题,此项可选
|
||||
* { title: '选项标题' }
|
||||
* );
|
||||
* // 之后,就可以直接判断 choice 来执行不同的操作了
|
||||
* if (choice === 0) { ... }
|
||||
* ```
|
||||
* @param controller UI 控制器
|
||||
* @param choices 选择框的选项
|
||||
* @param loc 选择框的位置
|
||||
* @param width 选择框的宽度
|
||||
* @param props 额外的 props,参考 {@link ChoicesProps}
|
||||
*/
|
||||
export function getChoice<T extends ChoiceKey = ChoiceKey>(
|
||||
controller: IUIMountable,
|
||||
choices: ChoiceItem[],
|
||||
loc: ElementLocator,
|
||||
width: number,
|
||||
props?: Partial<ChoicesProps>
|
||||
) {
|
||||
return new Promise<T>(res => {
|
||||
const instance = controller.open(
|
||||
ChoicesUI,
|
||||
{
|
||||
...(props ?? {}),
|
||||
choices,
|
||||
loc,
|
||||
width,
|
||||
onChoose: key => {
|
||||
controller.close(instance);
|
||||
res(key as T);
|
||||
}
|
||||
},
|
||||
true
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** @see {@link ConfirmBox} */
|
||||
export const ConfirmBoxUI = new GameUI('confirm-box', ConfirmBox);
|
||||
/** @see {@link Choices} */
|
||||
export const ChoicesUI = new GameUI('choices', Choices);
|
||||
@@ -1,503 +0,0 @@
|
||||
import { DefaultProps, ElementLocator, GraphicPropsBase } from '@motajs/render';
|
||||
import { computed, defineComponent, onMounted, Ref, ref, watch } from 'vue';
|
||||
import { SetupComponentOptions } from './types';
|
||||
|
||||
export interface IconsProps extends DefaultProps<GraphicPropsBase> {
|
||||
loc: ElementLocator;
|
||||
}
|
||||
|
||||
const iconsProps = {
|
||||
props: ['loc']
|
||||
} satisfies SetupComponentOptions<IconsProps>;
|
||||
|
||||
type PathGenerator = (width: number, height: number) => Path2D;
|
||||
/**
|
||||
* @param ox 横向偏移坐标
|
||||
* @param oy 纵向偏移坐标
|
||||
* @param width 路径宽度
|
||||
* @param height 路径高度
|
||||
*/
|
||||
type PathFn = (ox: number, oy: number, width: number, height: number) => Path2D;
|
||||
|
||||
function adjustPath(
|
||||
aspect: number,
|
||||
ref: Ref<Path2D | undefined>,
|
||||
fn: PathFn
|
||||
): PathGenerator {
|
||||
let beforeWidth = 200;
|
||||
let beforeHeight = 200;
|
||||
let path: Path2D | undefined;
|
||||
return (width, height) => {
|
||||
if (width === beforeWidth && height === beforeHeight && path) {
|
||||
return path;
|
||||
}
|
||||
beforeWidth = width;
|
||||
beforeHeight = height;
|
||||
const eleAspect = width / height;
|
||||
let ox = 0;
|
||||
let oy = 0;
|
||||
let dw = 0;
|
||||
let dh = 0;
|
||||
if (aspect >= eleAspect) {
|
||||
ox = 0;
|
||||
dw = width;
|
||||
dh = width / aspect;
|
||||
oy = (height - dh) / 2;
|
||||
} else {
|
||||
oy = 0;
|
||||
dh = height;
|
||||
dw = height * aspect;
|
||||
ox = (width - dw) / 2;
|
||||
}
|
||||
path = fn(ox, oy, dw, dh);
|
||||
ref.value = path;
|
||||
return path;
|
||||
};
|
||||
}
|
||||
|
||||
export const RollbackIcon = defineComponent<IconsProps>(props => {
|
||||
const path = ref<Path2D>();
|
||||
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
|
||||
const path = new Path2D();
|
||||
const arc = width / 10;
|
||||
const arrow = width / 10;
|
||||
const left = ox + width / 10;
|
||||
const top = oy + height / 5;
|
||||
const right = ox + width - width / 10;
|
||||
const bottom = oy + height - height / 5;
|
||||
const end = left + width / 4;
|
||||
path.moveTo(left, bottom);
|
||||
path.lineTo(right - arc, bottom);
|
||||
path.arcTo(right, bottom, right, bottom - arc, arc);
|
||||
path.lineTo(right, top + arc);
|
||||
path.arcTo(right, top, right - arc, top, arc);
|
||||
path.lineTo(end, top);
|
||||
path.moveTo(end + arrow, top - arrow);
|
||||
path.lineTo(end, top);
|
||||
path.lineTo(end + arrow, top + arrow);
|
||||
path.moveTo(left, top);
|
||||
return path;
|
||||
});
|
||||
|
||||
watch(props, () => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<g-path
|
||||
loc={props.loc}
|
||||
path={path.value}
|
||||
stroke
|
||||
lineJoin="round"
|
||||
lineCap="round"
|
||||
></g-path>
|
||||
);
|
||||
};
|
||||
}, iconsProps);
|
||||
|
||||
export const RetweetIcon = defineComponent<IconsProps>(props => {
|
||||
const path = ref<Path2D>();
|
||||
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
|
||||
const path = new Path2D();
|
||||
const arc = width / 10;
|
||||
const arrow = width / 10;
|
||||
const left = ox + width / 10;
|
||||
const top = oy + height / 5;
|
||||
const right = ox + width - width / 10;
|
||||
const bottom = oy + height - height / 5;
|
||||
const end = left + width / 2;
|
||||
path.moveTo(end, bottom);
|
||||
path.lineTo(left + arc, bottom);
|
||||
path.arcTo(left, bottom, left, bottom - arc, arc);
|
||||
path.lineTo(left, top + arc);
|
||||
path.arcTo(left, top, left + arc, top, arc);
|
||||
path.lineTo(right, top);
|
||||
path.moveTo(right - arrow, top - arrow);
|
||||
path.lineTo(right, top);
|
||||
path.lineTo(right - arrow, top + arrow);
|
||||
path.moveTo(left, top);
|
||||
return path;
|
||||
});
|
||||
|
||||
watch(props, () => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<g-path
|
||||
loc={props.loc}
|
||||
path={path.value}
|
||||
stroke
|
||||
lineJoin="round"
|
||||
lineCap="round"
|
||||
></g-path>
|
||||
);
|
||||
};
|
||||
}, iconsProps);
|
||||
|
||||
export const ViewMapIcon = defineComponent<IconsProps>(props => {
|
||||
const path = ref<Path2D>();
|
||||
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
|
||||
const path = new Path2D();
|
||||
const left = ox + width / 5;
|
||||
const top = oy + height / 5;
|
||||
const right = ox + width - width / 5;
|
||||
const bottom = oy + height - height / 5;
|
||||
const cx = ox + width / 2;
|
||||
const cy = oy + height / 2;
|
||||
path.rect(left, top, right - left, bottom - top);
|
||||
path.moveTo(cx, top);
|
||||
path.lineTo(cx, bottom);
|
||||
path.moveTo(left, cy);
|
||||
path.lineTo(right, cy);
|
||||
|
||||
return path;
|
||||
});
|
||||
|
||||
watch(props, () => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<g-path
|
||||
loc={props.loc}
|
||||
path={path.value}
|
||||
stroke
|
||||
lineJoin="round"
|
||||
lineCap="round"
|
||||
></g-path>
|
||||
);
|
||||
};
|
||||
}, iconsProps);
|
||||
|
||||
export const DanmakuIcon = defineComponent<IconsProps>(props => {
|
||||
const path = ref<Path2D>();
|
||||
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
|
||||
const path = new Path2D();
|
||||
const left = ox + width / 5;
|
||||
const bottom = oy + height - height / 5;
|
||||
const cx = ox + width / 2;
|
||||
const cy = oy + height / 2;
|
||||
const rx = width / 3;
|
||||
const ry = height / 4;
|
||||
const start = (Math.PI * 16) / 18;
|
||||
const end = (Math.PI * 12) / 18;
|
||||
path.ellipse(cx, cy, rx, ry, 0, start, end);
|
||||
path.lineTo(left - width / 24, bottom - height / 36);
|
||||
path.closePath();
|
||||
return path;
|
||||
});
|
||||
|
||||
watch(props, () => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<g-path
|
||||
loc={props.loc}
|
||||
path={path.value}
|
||||
stroke
|
||||
lineJoin="round"
|
||||
lineCap="round"
|
||||
></g-path>
|
||||
);
|
||||
};
|
||||
}, iconsProps);
|
||||
|
||||
export const ReplayIcon = defineComponent<IconsProps>(props => {
|
||||
const path = ref<Path2D>();
|
||||
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
|
||||
const path = new Path2D();
|
||||
const arc = width / 10;
|
||||
const left = ox + width / 5;
|
||||
const top = oy + height / 5;
|
||||
const right = ox + width - width / 5;
|
||||
const bottom = oy + height - height / 5;
|
||||
const cy = oy + height / 2;
|
||||
path.moveTo(right, cy - height / 8);
|
||||
path.lineTo(right, top + arc);
|
||||
path.arcTo(right, top, right - arc, top, arc);
|
||||
path.lineTo(left + arc, top);
|
||||
path.arcTo(left, top, left, top + arc, arc);
|
||||
path.lineTo(left, cy);
|
||||
path.moveTo(left + arc, cy - arc);
|
||||
path.lineTo(left, cy);
|
||||
path.lineTo(left - arc, cy - arc);
|
||||
path.moveTo(left, cy + height / 8);
|
||||
path.lineTo(left, bottom - arc);
|
||||
path.arcTo(left, bottom, left + arc, bottom, arc);
|
||||
path.lineTo(right - arc, bottom);
|
||||
path.arcTo(right, bottom, right, bottom - arc, arc);
|
||||
path.lineTo(right, cy);
|
||||
path.moveTo(right - arc, cy + arc);
|
||||
path.lineTo(right, cy);
|
||||
path.lineTo(right + arc, cy + arc);
|
||||
return path;
|
||||
});
|
||||
|
||||
watch(props, () => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<g-path
|
||||
loc={props.loc}
|
||||
path={path.value}
|
||||
stroke
|
||||
lineJoin="round"
|
||||
lineCap="round"
|
||||
></g-path>
|
||||
);
|
||||
};
|
||||
}, iconsProps);
|
||||
|
||||
export const NumpadIcon = defineComponent<IconsProps>(props => {
|
||||
const path = ref<Path2D>();
|
||||
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
|
||||
const path = new Path2D();
|
||||
const left = ox + width / 5;
|
||||
const top = oy + height / 5;
|
||||
const right = ox + width - width / 5;
|
||||
const bottom = oy + height - height / 5;
|
||||
const cx = ox + width / 2;
|
||||
const cy = oy + height / 2;
|
||||
path.rect(left, top, right - left, bottom - top);
|
||||
const path2 = new Path2D();
|
||||
path2.ellipse(cx, cy, width / 9, height / 6, 0, 0, Math.PI * 2);
|
||||
path.addPath(path2);
|
||||
return path;
|
||||
});
|
||||
|
||||
watch(props, () => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<g-path
|
||||
loc={props.loc}
|
||||
path={path.value}
|
||||
stroke
|
||||
lineJoin="round"
|
||||
lineCap="round"
|
||||
></g-path>
|
||||
);
|
||||
};
|
||||
}, iconsProps);
|
||||
|
||||
export const PlayIcon = defineComponent<IconsProps>(props => {
|
||||
const path = ref<Path2D>();
|
||||
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
|
||||
const path = new Path2D();
|
||||
const left = ox + width / 5;
|
||||
const top = oy + height / 5;
|
||||
const right = ox + width - width / 5;
|
||||
const bottom = oy + height - height / 5;
|
||||
path.moveTo(left, top);
|
||||
path.lineTo(right, oy + height / 2);
|
||||
path.lineTo(left, bottom);
|
||||
path.closePath();
|
||||
return path;
|
||||
});
|
||||
|
||||
watch(props, () => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<g-path
|
||||
loc={props.loc}
|
||||
path={path.value}
|
||||
fill
|
||||
stroke
|
||||
lineJoin="round"
|
||||
lineCap="round"
|
||||
></g-path>
|
||||
);
|
||||
};
|
||||
}, iconsProps);
|
||||
|
||||
export const PauseIcon = defineComponent<IconsProps>(props => {
|
||||
const path = ref<Path2D>();
|
||||
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
|
||||
const path = new Path2D();
|
||||
const cx = ox + width / 2;
|
||||
const top = oy + height / 5;
|
||||
const bottom = oy + height - height / 5;
|
||||
path.moveTo(cx - width / 5, top);
|
||||
path.lineTo(cx - width / 5, bottom);
|
||||
path.moveTo(cx + width / 5, top);
|
||||
path.lineTo(cx + width / 5, bottom);
|
||||
return path;
|
||||
});
|
||||
|
||||
watch(props, () => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<g-path
|
||||
loc={props.loc}
|
||||
path={path.value}
|
||||
stroke
|
||||
lineJoin="round"
|
||||
lineCap="round"
|
||||
></g-path>
|
||||
);
|
||||
};
|
||||
}, iconsProps);
|
||||
|
||||
export const DoubleArrow = defineComponent<IconsProps>(props => {
|
||||
const path = ref<Path2D>();
|
||||
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
|
||||
const path = new Path2D();
|
||||
const path2 = new Path2D();
|
||||
const left = ox + width / 5;
|
||||
const top = oy + height / 5;
|
||||
const right = ox + width - width / 5;
|
||||
const bottom = oy + height - height / 5;
|
||||
const cx = ox + width / 2;
|
||||
const cy = oy + height / 2;
|
||||
path.moveTo(left, top + height / 12);
|
||||
path.lineTo(cx + width / 8, cy);
|
||||
path.lineTo(left, bottom - height / 12);
|
||||
path.closePath();
|
||||
path2.moveTo(cx, top + height / 12);
|
||||
path2.lineTo(right, cy);
|
||||
path2.lineTo(cx, bottom - height / 12);
|
||||
path2.closePath();
|
||||
path.addPath(path2);
|
||||
return path;
|
||||
});
|
||||
|
||||
watch(props, () => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<g-path
|
||||
loc={props.loc}
|
||||
path={path.value}
|
||||
stroke
|
||||
fill
|
||||
lineJoin="round"
|
||||
lineCap="round"
|
||||
></g-path>
|
||||
);
|
||||
};
|
||||
}, iconsProps);
|
||||
|
||||
export const StepForward = defineComponent<IconsProps>(props => {
|
||||
const path = ref<Path2D>();
|
||||
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const generatePath = adjustPath(1, path, (ox, oy, width, height) => {
|
||||
const path = new Path2D();
|
||||
const path2 = new Path2D();
|
||||
const left = ox + width / 5;
|
||||
const top = oy + height / 5;
|
||||
const right = ox + width - width / 5;
|
||||
const bottom = oy + height - height / 5;
|
||||
path.moveTo(left, top);
|
||||
path.lineTo(right, oy + height / 2);
|
||||
path.lineTo(left, bottom);
|
||||
path.closePath();
|
||||
path2.moveTo(right, top);
|
||||
path2.lineTo(right, bottom);
|
||||
path.addPath(path2);
|
||||
return path;
|
||||
});
|
||||
|
||||
watch(props, () => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
generatePath(width.value, height.value);
|
||||
});
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<g-path
|
||||
loc={props.loc}
|
||||
path={path.value}
|
||||
stroke
|
||||
fill
|
||||
lineJoin="round"
|
||||
lineCap="round"
|
||||
></g-path>
|
||||
);
|
||||
};
|
||||
}, iconsProps);
|
||||
@@ -1,9 +0,0 @@
|
||||
export * from './choices';
|
||||
export * from './icons';
|
||||
export * from './misc';
|
||||
export * from './page';
|
||||
export * from './scroll';
|
||||
export * from './textbox';
|
||||
export * from './textboxTyper';
|
||||
export * from './tip';
|
||||
export * from './types';
|
||||
@@ -1,583 +0,0 @@
|
||||
import {
|
||||
DefaultProps,
|
||||
ElementLocator,
|
||||
onTick,
|
||||
PathProps,
|
||||
Sprite
|
||||
} from '@motajs/render';
|
||||
import { computed, defineComponent, ref, SetupContext, watch } from 'vue';
|
||||
import { SetupComponentOptions } from './types';
|
||||
import { MotaOffscreenCanvas2D } from '@motajs/render';
|
||||
import { TextboxProps, TextContent, TextContentProps } from './textbox';
|
||||
import { Scroll, ScrollExpose, ScrollProps } from './scroll';
|
||||
import { transitioned } from '../use';
|
||||
import { hyper } from 'mutate-animate';
|
||||
import { logger } from '@motajs/common';
|
||||
import { GameUI, IUIMountable } from '@motajs/system-ui';
|
||||
|
||||
interface ProgressProps extends DefaultProps {
|
||||
/** 进度条的位置 */
|
||||
loc: ElementLocator;
|
||||
/** 进度条的进度,1表示完成,0表示未完成 */
|
||||
progress: number;
|
||||
/** 已完成部分的样式,默认为绿色(green) */
|
||||
success?: CanvasStyle;
|
||||
/** 未完成部分的样式,默认为灰色(gray) */
|
||||
background?: CanvasStyle;
|
||||
/** 线宽度 */
|
||||
lineWidth?: number;
|
||||
}
|
||||
|
||||
const progressProps = {
|
||||
props: ['loc', 'progress', 'success', 'background']
|
||||
} satisfies SetupComponentOptions<ProgressProps>;
|
||||
|
||||
/**
|
||||
* 进度条组件,参数参考 {@link ProgressProps},用例如下:
|
||||
* ```tsx
|
||||
* // 定义进度
|
||||
* const progress = ref(0);
|
||||
*
|
||||
* // 显示进度条
|
||||
* <Progress loc={[12, 12, 120, 8]} progress={progress.value} />
|
||||
* ```
|
||||
*/
|
||||
export const Progress = defineComponent<ProgressProps>(props => {
|
||||
const element = ref<Sprite>();
|
||||
|
||||
const render = (canvas: MotaOffscreenCanvas2D) => {
|
||||
const { ctx } = canvas;
|
||||
const width = props.loc[2] ?? 200;
|
||||
const height = props.loc[3] ?? 200;
|
||||
ctx.lineCap = 'round';
|
||||
const lineWidth = props.lineWidth ?? 2;
|
||||
ctx.lineWidth = lineWidth;
|
||||
ctx.strokeStyle = props.background ?? 'gray';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(lineWidth, height / 2);
|
||||
ctx.lineTo(width - lineWidth, height / 2);
|
||||
ctx.stroke();
|
||||
if (!isNaN(props.progress)) {
|
||||
ctx.strokeStyle = props.success ?? 'green';
|
||||
const p = lineWidth + (width - lineWidth * 2) * props.progress;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(lineWidth, height / 2);
|
||||
ctx.lineTo(p, height / 2);
|
||||
ctx.stroke();
|
||||
}
|
||||
};
|
||||
|
||||
watch(props, () => {
|
||||
element.value?.update();
|
||||
});
|
||||
|
||||
return () => {
|
||||
return <sprite ref={element} loc={props.loc} render={render}></sprite>;
|
||||
};
|
||||
}, progressProps);
|
||||
|
||||
export interface ArrowProps extends PathProps {
|
||||
/** 箭头的起始和终点坐标,前两个是起始坐标,后两个是终点坐标 */
|
||||
arrow: [number, number, number, number];
|
||||
/** 箭头的头部大小 */
|
||||
head?: number;
|
||||
/** 箭头的颜色 */
|
||||
color?: CanvasStyle;
|
||||
}
|
||||
|
||||
const arrowProps = {
|
||||
props: ['arrow', 'head', 'color']
|
||||
} satisfies SetupComponentOptions<ArrowProps>;
|
||||
|
||||
/**
|
||||
* 箭头组件,显示一个箭头,参数参考 {@link ArrowProps},用例如下:
|
||||
* ```tsx
|
||||
* // 从 (12, 12) 到 (48, 48) 的箭头
|
||||
* <Arrow arrow={[12, 12, 48, 48]} />
|
||||
* ```
|
||||
*/
|
||||
export const Arrow = defineComponent<ArrowProps>(props => {
|
||||
const loc = computed<ElementLocator>(() => {
|
||||
const [x1, y1, x2, y2] = props.arrow;
|
||||
const left = Math.min(x1, x2);
|
||||
const right = Math.max(x1, x2);
|
||||
const top = Math.min(y1, y2);
|
||||
const bottom = Math.max(y1, y2);
|
||||
return [left, top, right - left, bottom - top];
|
||||
});
|
||||
const path = computed(() => {
|
||||
const path = new Path2D();
|
||||
const head = props.head ?? 8;
|
||||
const [x = 0, y = 0] = loc.value;
|
||||
const [x1, y1, x2, y2] = props.arrow;
|
||||
path.moveTo(x1 - x, y1 - y);
|
||||
path.lineTo(x2 - x, y2 - y);
|
||||
const angle = Math.atan2(y2 - y1, x2 - x1);
|
||||
path.moveTo(
|
||||
x2 - head * Math.cos(angle - Math.PI / 6),
|
||||
y2 - head * Math.sin(angle - Math.PI / 6)
|
||||
);
|
||||
path.lineTo(x2 - x, y2 - y);
|
||||
path.lineTo(
|
||||
x2 - head * Math.cos(angle + Math.PI / 6),
|
||||
y2 - head * Math.sin(angle + Math.PI / 6)
|
||||
);
|
||||
return path;
|
||||
});
|
||||
|
||||
return () => (
|
||||
<g-path
|
||||
loc={loc.value}
|
||||
path={path.value}
|
||||
stroke
|
||||
strokeStyle={props.color}
|
||||
lineCap="round"
|
||||
lineJoin="round"
|
||||
/>
|
||||
);
|
||||
}, arrowProps);
|
||||
|
||||
export interface ScrollTextProps extends TextboxProps, ScrollProps {
|
||||
/** 自动滚动的速度,每秒多少像素 */
|
||||
speed: number;
|
||||
/** 文字的最大宽度 */
|
||||
width: number;
|
||||
/** 自动滚动组件的定位 */
|
||||
loc: ElementLocator;
|
||||
/** 文字滚动入元素之前要先滚动多少像素,默认16像素 */
|
||||
pad?: number;
|
||||
}
|
||||
|
||||
export type ScrollTextEmits = {
|
||||
/**
|
||||
* 当滚动完毕时触发
|
||||
*/
|
||||
scrollEnd: () => void;
|
||||
};
|
||||
|
||||
export interface ScrollTextExpose {
|
||||
/**
|
||||
* 暂停滚动
|
||||
*/
|
||||
pause(): void;
|
||||
|
||||
/**
|
||||
* 继续滚动
|
||||
*/
|
||||
resume(): void;
|
||||
|
||||
/**
|
||||
* 设置滚动速度
|
||||
*/
|
||||
setSpeed(speed: number): void;
|
||||
|
||||
/**
|
||||
* 立刻重新滚动
|
||||
*/
|
||||
rescroll(): void;
|
||||
}
|
||||
|
||||
const scrollProps = {
|
||||
props: ['speed', 'loc', 'pad', 'width'],
|
||||
emits: ['scrollEnd']
|
||||
} satisfies SetupComponentOptions<
|
||||
ScrollTextProps,
|
||||
ScrollTextEmits,
|
||||
keyof ScrollTextEmits
|
||||
>;
|
||||
|
||||
/**
|
||||
* 滚动文字,可以用于展示长剧情或者 staff 表,参数参考 {@link ScrollTextProps},
|
||||
* 事件参考 {@link ScrollTextEmits},函数接口参考 {@link ScrollTextExpose},用例如下:
|
||||
* ```tsx
|
||||
* // 用于接受函数接口
|
||||
* const scroll = ref<ScrollTextExpose>();
|
||||
* // 显示的文字
|
||||
* const text = '滚动文字'.repeat(100);
|
||||
*
|
||||
* onMounted(() => {
|
||||
* // 设置为每秒滚动 100 像素
|
||||
* scroll.value?.setSpeed(100);
|
||||
* // 暂停滚动
|
||||
* scroll.value?.pause();
|
||||
* });
|
||||
*
|
||||
* // 显示滚动文字,每秒滚动 50 像素
|
||||
* <ScrollText ref={scroll} text={text} speed={50} loc={[0, 0, 180, 100]} width={180} />
|
||||
* ```
|
||||
*/
|
||||
export const ScrollText = defineComponent<
|
||||
ScrollTextProps,
|
||||
ScrollTextEmits,
|
||||
keyof ScrollTextEmits
|
||||
>((props, { emit, expose, attrs }) => {
|
||||
const scroll = ref<ScrollExpose>();
|
||||
const speed = ref(props.speed);
|
||||
|
||||
const eleHeight = computed(() => props.loc[3] ?? props.width);
|
||||
const pad = computed(() => props.pad ?? 16);
|
||||
|
||||
let lastFixedTime = Date.now();
|
||||
let lastFixedPos = 0;
|
||||
let paused = false;
|
||||
let nowScroll = 0;
|
||||
|
||||
onTick(() => {
|
||||
if (paused || !scroll.value) return;
|
||||
const now = Date.now();
|
||||
const dt = now - lastFixedTime;
|
||||
nowScroll = (dt / 1000) * speed.value + lastFixedPos;
|
||||
scroll.value.scrollTo(nowScroll, 0);
|
||||
if (nowScroll >= scroll.value.getScrollLength()) {
|
||||
emit('scrollEnd');
|
||||
paused = true;
|
||||
}
|
||||
});
|
||||
|
||||
const pause = () => {
|
||||
paused = true;
|
||||
};
|
||||
|
||||
const resume = () => {
|
||||
paused = false;
|
||||
lastFixedPos = nowScroll;
|
||||
lastFixedTime = Date.now();
|
||||
};
|
||||
|
||||
const setSpeed = (value: number) => {
|
||||
lastFixedPos = nowScroll;
|
||||
lastFixedTime = Date.now();
|
||||
speed.value = value;
|
||||
};
|
||||
|
||||
const rescroll = () => {
|
||||
nowScroll = 0;
|
||||
lastFixedTime = Date.now();
|
||||
lastFixedPos = 0;
|
||||
};
|
||||
|
||||
expose<ScrollTextExpose>({ pause, resume, setSpeed, rescroll });
|
||||
|
||||
return () => (
|
||||
<Scroll
|
||||
ref={scroll}
|
||||
loc={props.loc}
|
||||
padEnd={eleHeight.value + pad.value}
|
||||
noscroll
|
||||
>
|
||||
<TextContent
|
||||
{...attrs}
|
||||
width={props.width - 16}
|
||||
loc={[8, eleHeight.value + pad.value]}
|
||||
autoHeight
|
||||
/>
|
||||
</Scroll>
|
||||
);
|
||||
}, scrollProps);
|
||||
|
||||
export interface SelectionProps extends DefaultProps {
|
||||
loc: ElementLocator;
|
||||
color?: CanvasStyle;
|
||||
border?: CanvasStyle;
|
||||
winskin?: ImageIds;
|
||||
/** 选择图标的不透明度范围 */
|
||||
alphaRange?: [number, number];
|
||||
}
|
||||
|
||||
const selectionProps = {
|
||||
props: ['loc', 'color', 'border', 'winskin', 'alphaRange']
|
||||
} satisfies SetupComponentOptions<SelectionProps>;
|
||||
|
||||
/**
|
||||
* 显示一个选择光标,与 2.x 的 drawUIEventSelector 效果一致,参数参考 {@link SelectionProps},用例如下:
|
||||
* ```tsx
|
||||
* // 使用 winskin.png 作为选择光标,光标动画的不透明度范围是 [0.3, 0.8]
|
||||
* <Selection loc={[24, 24, 80, 16]} winskin="winskin.png" alphaRange={[0.3, 0.8]} />
|
||||
* // 使用指定的填充和边框颜色作为选择光标
|
||||
* <Selection loc={[24, 24, 80, 16]} color="#ddd" border="gold" />
|
||||
* ```
|
||||
*/
|
||||
export const Selection = defineComponent<SelectionProps>(props => {
|
||||
const minAlpha = computed(() => props.alphaRange?.[0] ?? 0.25);
|
||||
const maxAlpha = computed(() => props.alphaRange?.[1] ?? 0.55);
|
||||
const alpha = transitioned(minAlpha.value, 2000, hyper('sin', 'in-out'))!;
|
||||
|
||||
const isWinskin = computed(() => !!props.winskin);
|
||||
const winskinImage = computed(() =>
|
||||
isWinskin.value ? core.material.images.images[props.winskin!] : null
|
||||
);
|
||||
const fixedLoc = computed<ElementLocator>(() => {
|
||||
const [x = 0, y = 0, width = 200, height = 200] = props.loc;
|
||||
return [x + 1, y + 1, width - 2, height - 2];
|
||||
});
|
||||
|
||||
const renderWinskin = (canvas: MotaOffscreenCanvas2D) => {
|
||||
const ctx = canvas.ctx;
|
||||
const image = winskinImage.value;
|
||||
if (!image) return;
|
||||
const [, , width = 200, height = 200] = props.loc;
|
||||
// 背景
|
||||
ctx.drawImage(image, 130, 66, 28, 28, 2, 2, width - 4, height - 4);
|
||||
// 四个角
|
||||
ctx.drawImage(image, 128, 64, 2, 2, 0, 0, 2, 2);
|
||||
ctx.drawImage(image, 158, 64, 2, 2, width - 2, 0, 2, 2);
|
||||
ctx.drawImage(image, 128, 94, 2, 2, 0, height - 2, 2, 2);
|
||||
ctx.drawImage(image, 158, 94, 2, 2, width - 2, height - 2, 2, 2);
|
||||
// 四条边
|
||||
ctx.drawImage(image, 130, 64, 28, 2, 2, 0, width - 4, 2);
|
||||
ctx.drawImage(image, 130, 94, 28, 2, 2, height - 2, width - 4, 2);
|
||||
ctx.drawImage(image, 128, 66, 2, 28, 0, 2, 2, height - 4);
|
||||
ctx.drawImage(image, 158, 66, 2, 28, width - 2, 2, 2, height - 4);
|
||||
};
|
||||
|
||||
onTick(() => {
|
||||
if (alpha.value === maxAlpha.value) {
|
||||
alpha.set(minAlpha.value);
|
||||
}
|
||||
if (alpha.value === minAlpha.value) {
|
||||
alpha.set(maxAlpha.value);
|
||||
}
|
||||
});
|
||||
|
||||
return () =>
|
||||
isWinskin.value ? (
|
||||
<sprite
|
||||
loc={props.loc}
|
||||
render={renderWinskin}
|
||||
alpha={alpha.ref.value}
|
||||
noanti
|
||||
/>
|
||||
) : (
|
||||
<g-rectr
|
||||
loc={fixedLoc.value}
|
||||
circle={[4]}
|
||||
alpha={alpha.ref.value}
|
||||
fill
|
||||
stroke
|
||||
fillStyle={props.color}
|
||||
strokeStyle={props.border}
|
||||
lineWidth={1}
|
||||
/>
|
||||
);
|
||||
}, selectionProps);
|
||||
|
||||
export interface BackgroundProps extends DefaultProps {
|
||||
loc: ElementLocator;
|
||||
winskin?: ImageIds;
|
||||
color?: CanvasStyle;
|
||||
border?: CanvasStyle;
|
||||
}
|
||||
|
||||
const backgroundProps = {
|
||||
props: ['loc', 'winskin', 'color', 'border']
|
||||
} satisfies SetupComponentOptions<BackgroundProps>;
|
||||
|
||||
/**
|
||||
* 背景组件,与 Selection 类似,不过绘制的是背景,而不是选择光标,参数参考 {@link BackgroundProps},用例如下:
|
||||
* ```tsx
|
||||
* // 使用 winskin2.png 作为背景
|
||||
* <Background loc={[8, 8, 160, 160]} winskin="winskin2.png" />
|
||||
* // 使用指定填充和边框颜色作为背景
|
||||
* <Background loc={[8, 8, 160, 160]} color="#333" border="gold" />
|
||||
* ```
|
||||
*/
|
||||
export const Background = defineComponent<BackgroundProps>(props => {
|
||||
const isWinskin = computed(() => !!props.winskin);
|
||||
const fixedLoc = computed<ElementLocator>(() => {
|
||||
const [x = 0, y = 0, width = 200, height = 200] = props.loc;
|
||||
return [x + 2, y + 2, width - 4, height - 4];
|
||||
});
|
||||
|
||||
return () =>
|
||||
isWinskin.value ? (
|
||||
<winskin image={props.winskin!} loc={props.loc} noanti />
|
||||
) : (
|
||||
<g-rectr
|
||||
loc={fixedLoc.value}
|
||||
fillStyle={props.color}
|
||||
strokeStyle={props.border}
|
||||
fill
|
||||
stroke
|
||||
lineWidth={2}
|
||||
circle={[4]}
|
||||
/>
|
||||
);
|
||||
}, backgroundProps);
|
||||
|
||||
export interface WaitBoxProps<T>
|
||||
extends Partial<BackgroundProps>,
|
||||
Partial<TextContentProps> {
|
||||
loc: ElementLocator;
|
||||
width: number;
|
||||
promise?: Promise<T>;
|
||||
text?: string;
|
||||
pad?: number;
|
||||
}
|
||||
|
||||
export type WaitBoxEmits<T> = {
|
||||
resolve: (data: T) => void;
|
||||
};
|
||||
|
||||
export interface WaitBoxExpose<T> {
|
||||
/**
|
||||
* 手动将此组件兑现,注意调用时如果传入的 Promise 还没有兑现,
|
||||
* 当 Promise 兑现后将不会再次触发 resolve 事件,即 resolve 事件只会被触发一次
|
||||
* @param data 兑现值
|
||||
*/
|
||||
resolve(data: T): void;
|
||||
}
|
||||
|
||||
const waitBoxProps = {
|
||||
props: ['promise', 'loc', 'winskin', 'color', 'border'],
|
||||
emits: ['resolve']
|
||||
} satisfies SetupComponentOptions<
|
||||
WaitBoxProps<unknown>,
|
||||
WaitBoxEmits<unknown>,
|
||||
keyof WaitBoxEmits<unknown>
|
||||
>;
|
||||
|
||||
/**
|
||||
* 等待框,可以等待某个异步操作 (Promise),操作完毕后触发兑现事件,单次调用参考 {@link waitbox}。
|
||||
* 参数参考 {@link WaitBoxProps},事件参考 {@link WaitBoxEmits},函数接口参考 {@link WaitBoxExpose}。用例如下:
|
||||
* ```tsx
|
||||
* // 创建一个等待 1000ms 的 Promise,兑现值是等待完毕时的当前时间刻
|
||||
* const promise = new Promise(res => window.setTimeout(() => res(Date.now()), 1000));
|
||||
*
|
||||
* <WaitBox
|
||||
* // 传入要等待的 Promise
|
||||
* promise={promise}
|
||||
* // 等待框的位置,宽度由 width 参数指定,高度由内部计算得来,不需要手动指定,即使手动指定也无效
|
||||
* loc={[240, 240, void 0, void 0, 0.5, 0.5]}
|
||||
* // 等待框的宽度
|
||||
* width={240}
|
||||
* // 完全继承 Background 的参数,因此可以直接指定背景样式
|
||||
* winskin="winskin2.png"
|
||||
* // 完全继承 TextContent 的参数,因此可以直接指定字体
|
||||
* font={new Font('Verdana', 28)}
|
||||
* />
|
||||
* ```
|
||||
*/
|
||||
export const WaitBox = defineComponent<
|
||||
WaitBoxProps<unknown>,
|
||||
WaitBoxEmits<unknown>,
|
||||
keyof WaitBoxEmits<unknown>
|
||||
>(
|
||||
<T,>(
|
||||
props: WaitBoxProps<T>,
|
||||
{ emit, expose, attrs }: SetupContext<WaitBoxEmits<T>>
|
||||
) => {
|
||||
const contentHeight = ref(200);
|
||||
|
||||
const text = computed(() => props.text ?? '请等待 ...');
|
||||
const pad = computed(() => props.pad ?? 24);
|
||||
const containerLoc = computed<ElementLocator>(() => {
|
||||
const [x = 0, y = 0, , , ax = 0, ay = 0] = props.loc;
|
||||
return [x, y, props.width, contentHeight.value, ax, ay];
|
||||
});
|
||||
const backLoc = computed<ElementLocator>(() => {
|
||||
return [1, 1, props.width - 2, contentHeight.value - 2];
|
||||
});
|
||||
const contentLoc = computed<ElementLocator>(() => {
|
||||
return [
|
||||
pad.value,
|
||||
pad.value,
|
||||
props.width - pad.value * 2,
|
||||
contentHeight.value - pad.value * 2
|
||||
];
|
||||
});
|
||||
|
||||
let resolved: boolean = false;
|
||||
|
||||
props.promise?.then(
|
||||
value => {
|
||||
resolve(value);
|
||||
},
|
||||
reason => {
|
||||
logger.warn(63, reason);
|
||||
}
|
||||
);
|
||||
|
||||
const resolve = (data: T) => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
emit('resolve', data);
|
||||
};
|
||||
|
||||
const onContentHeight = (height: number) => {
|
||||
contentHeight.value = height + pad.value * 2;
|
||||
};
|
||||
|
||||
expose<WaitBoxExpose<T>>({ resolve });
|
||||
|
||||
return () => (
|
||||
<container loc={containerLoc.value}>
|
||||
<Background
|
||||
loc={backLoc.value}
|
||||
zIndex={0}
|
||||
winskin={props.winskin}
|
||||
color={props.color}
|
||||
border={props.border}
|
||||
/>
|
||||
<TextContent
|
||||
{...attrs}
|
||||
autoHeight
|
||||
text={text.value}
|
||||
loc={contentLoc.value}
|
||||
width={props.width - pad.value * 2}
|
||||
zIndex={5}
|
||||
onUpdateHeight={onContentHeight}
|
||||
/>
|
||||
</container>
|
||||
);
|
||||
},
|
||||
waitBoxProps
|
||||
);
|
||||
|
||||
/**
|
||||
* 打开一个等待框,等待传入的 Promise 兑现后,关闭等待框,并将兑现值返回。
|
||||
* 示例,等待 1000ms:
|
||||
* ```ts
|
||||
* // 创建一个等待 1000ms 的 Promise,兑现值是等待完毕时的当前时间刻
|
||||
* const promise = new Promise(res => window.setTimeout(() => res(Date.now()), 1000));
|
||||
* const value = await waitbox(
|
||||
* // 在哪个 UI 控制器上打开,对于一般 UI 组件来说,直接填写 props.controller 即可
|
||||
* props.controller,
|
||||
* // 确认框的位置,宽度由下一个参数指定,高度参数由组件内部计算得出,指定无效
|
||||
* [240, 240, void 0, void 0, 0.5, 0.5],
|
||||
* // 确认框的宽度
|
||||
* 240,
|
||||
* // 要等待的 Promise
|
||||
* promise,
|
||||
* // 额外的 props,例如填写等待文本,此项可选,参考 WaitBoxProps
|
||||
* { text: '请等待 1000ms' }
|
||||
* );
|
||||
* console.log(value); // 输出时间刻
|
||||
* ```
|
||||
* @param controller UI 控制器
|
||||
* @param loc 等待框的位置
|
||||
* @param width 等待框的宽度
|
||||
* @param promise 要等待的 Promise
|
||||
* @param props 额外的 props,参考 {@link WaitBoxProps}
|
||||
*/
|
||||
export function waitbox<T>(
|
||||
controller: IUIMountable,
|
||||
loc: ElementLocator,
|
||||
width: number,
|
||||
promise: Promise<T>,
|
||||
props?: Partial<WaitBoxProps<T>>
|
||||
): Promise<T> {
|
||||
return new Promise<T>(res => {
|
||||
const instance = controller.open(WaitBoxUI, {
|
||||
...(props ?? {}),
|
||||
loc,
|
||||
width,
|
||||
promise,
|
||||
onResolve: data => {
|
||||
controller.close(instance);
|
||||
res(data as T);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export const WaitBoxUI = new GameUI('wait-box', WaitBox);
|
||||
@@ -1,320 +0,0 @@
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
nextTick,
|
||||
onMounted,
|
||||
ref,
|
||||
SlotsType,
|
||||
VNode,
|
||||
watch
|
||||
} from 'vue';
|
||||
import { SetupComponentOptions } from './types';
|
||||
import { clamp } from 'lodash-es';
|
||||
import { DefaultProps, ElementLocator, Font } from '@motajs/render';
|
||||
|
||||
/** 圆角矩形页码距离容器的边框大小,与 pageSize 相乘 */
|
||||
const RECT_PAD = 0.1;
|
||||
|
||||
export interface PageProps extends DefaultProps {
|
||||
/** 共有多少页 */
|
||||
pages: number;
|
||||
/** 页码组件的定位 */
|
||||
loc: ElementLocator;
|
||||
/** 页码的字体 */
|
||||
font?: Font;
|
||||
/** 只有一页的时候,是否隐藏页码 */
|
||||
hideIfSingle?: boolean;
|
||||
}
|
||||
|
||||
export type PageEmits = {
|
||||
pageChange: (page: number) => void;
|
||||
};
|
||||
|
||||
export interface PageExpose {
|
||||
/**
|
||||
* 切换页码
|
||||
* @param page 要切换至的页码数,1 表示第一页
|
||||
*/
|
||||
changePage(page: number): void;
|
||||
|
||||
/**
|
||||
* 切换到传入的页码数加上当前页码数的页码
|
||||
* @param delta 页码数增量
|
||||
*/
|
||||
movePage(delta: number): void;
|
||||
|
||||
/**
|
||||
* 获取当前在第几页
|
||||
*/
|
||||
now(): number;
|
||||
}
|
||||
|
||||
type PageSlots = SlotsType<{
|
||||
default: (page: number) => VNode | VNode[];
|
||||
}>;
|
||||
|
||||
const pageProps = {
|
||||
props: ['pages', 'loc', 'font', 'hideIfSingle'],
|
||||
emits: ['pageChange']
|
||||
} satisfies SetupComponentOptions<
|
||||
PageProps,
|
||||
PageEmits,
|
||||
keyof PageEmits,
|
||||
PageSlots
|
||||
>;
|
||||
|
||||
/**
|
||||
* 分页组件,用于多页切换,例如存档界面等。参数参考 {@link PageProps},函数接口参考 {@link PageExpose}
|
||||
*
|
||||
* ---
|
||||
*
|
||||
* 用例如下,是一个在每页显示文字的用例,其中 page 表示页码索引,第一页就是 0,第二页就是 1,以此类推:
|
||||
* ```tsx
|
||||
* <Page maxPage={5}>
|
||||
* {
|
||||
* (page: number) => {
|
||||
* return items[page].map(v => <text text={v.text} />)
|
||||
* }
|
||||
* }
|
||||
* </Page>
|
||||
* ```
|
||||
*/
|
||||
export const Page = defineComponent<
|
||||
PageProps,
|
||||
PageEmits,
|
||||
keyof PageEmits,
|
||||
PageSlots
|
||||
>((props, { slots, expose, emit }) => {
|
||||
const nowPage = ref(0);
|
||||
|
||||
// 五个元素的位置
|
||||
const leftLoc = ref<ElementLocator>([]);
|
||||
const leftPageLoc = ref<ElementLocator>([]);
|
||||
const nowPageLoc = ref<ElementLocator>([]);
|
||||
const rightPageLoc = ref<ElementLocator>([]);
|
||||
const rightLoc = ref<ElementLocator>([]);
|
||||
/** 内容的位置 */
|
||||
const contentLoc = ref<ElementLocator>([]);
|
||||
/** 页码容器的位置 */
|
||||
const pageLoc = ref<ElementLocator>([]);
|
||||
/** 页码的矩形框的位置 */
|
||||
const rectLoc = ref<ElementLocator>([0, 0, 0, 0]);
|
||||
/** 页面文字的位置 */
|
||||
const textLoc = ref<ElementLocator>([0, 0, 0, 0]);
|
||||
|
||||
// 两个监听的参数
|
||||
const leftArrow = ref<Path2D>();
|
||||
const rightArrow = ref<Path2D>();
|
||||
|
||||
const hide = computed(() => props.hideIfSingle && props.pages === 1);
|
||||
const font = computed(() => props.font ?? new Font());
|
||||
const isFirst = computed(() => nowPage.value === 0);
|
||||
const isLast = computed(() => nowPage.value === props.pages - 1);
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const round = computed(() => font.value.size / 4);
|
||||
const nowPageFont = computed(() => Font.clone(font.value, { weight: 700 }));
|
||||
|
||||
// 左右箭头的颜色
|
||||
const leftColor = computed(() => (isFirst.value ? '#666' : '#ddd'));
|
||||
const rightColor = computed(() => (isLast.value ? '#666' : '#ddd'));
|
||||
|
||||
let updating = false;
|
||||
const updatePagePos = () => {
|
||||
if (updating) return;
|
||||
updating = true;
|
||||
nextTick(() => {
|
||||
updating = false;
|
||||
});
|
||||
const pageH = hide.value ? 0 : font.value.size + 8;
|
||||
contentLoc.value = [0, 0, width.value, height.value - pageH];
|
||||
pageLoc.value = [0, height.value - pageH, width.value, pageH];
|
||||
const center = width.value / 2;
|
||||
const size = font.value.size * 1.5;
|
||||
nowPageLoc.value = [center, 0, size, size, 0.5, 0];
|
||||
leftPageLoc.value = [center - size * 1.5, 0, size, size, 0.5, 0];
|
||||
leftLoc.value = [center - size * 3, 0, size, size, 0.5, 0];
|
||||
rightPageLoc.value = [center + size * 1.5, 0, size, size, 0.5, 0];
|
||||
rightLoc.value = [center + size * 3, 0, size, size, 0.5, 0];
|
||||
};
|
||||
|
||||
const updateArrowPath = () => {
|
||||
const rectSize = font.value.size * 1.5;
|
||||
const size = font.value.size;
|
||||
const pad = rectSize - size;
|
||||
const left = new Path2D();
|
||||
left.moveTo(size, pad);
|
||||
left.lineTo(pad, rectSize / 2);
|
||||
left.lineTo(size, rectSize - pad);
|
||||
const right = new Path2D();
|
||||
right.moveTo(pad, pad);
|
||||
right.lineTo(size, rectSize / 2);
|
||||
right.lineTo(pad, rectSize - pad);
|
||||
leftArrow.value = left;
|
||||
rightArrow.value = right;
|
||||
};
|
||||
|
||||
const updateRectAndText = () => {
|
||||
const size = font.value.size * 1.5;
|
||||
const pad = RECT_PAD * size;
|
||||
rectLoc.value = [pad, pad, size - pad * 2, size - pad * 2];
|
||||
textLoc.value = [size / 2, size / 2, void 0, void 0, 0.5, 0.5];
|
||||
};
|
||||
|
||||
watch(font, () => {
|
||||
updatePagePos();
|
||||
updateArrowPath();
|
||||
updateRectAndText();
|
||||
});
|
||||
watch(
|
||||
() => props.loc,
|
||||
() => {
|
||||
updatePagePos();
|
||||
updateRectAndText();
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* 切换页码
|
||||
*/
|
||||
const changePage = (page: number) => {
|
||||
const target = clamp(page, 0, props.pages - 1);
|
||||
if (nowPage.value !== target) {
|
||||
nowPage.value = target;
|
||||
emit('pageChange', target);
|
||||
}
|
||||
};
|
||||
|
||||
const movePage = (delta: number) => {
|
||||
changePage(nowPage.value + delta);
|
||||
};
|
||||
|
||||
const now = () => nowPage.value;
|
||||
|
||||
const lastPage = () => {
|
||||
changePage(nowPage.value - 1);
|
||||
};
|
||||
|
||||
const nextPage = () => {
|
||||
changePage(nowPage.value + 1);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
updatePagePos();
|
||||
updateArrowPath();
|
||||
updateRectAndText();
|
||||
});
|
||||
|
||||
expose<PageExpose>({ changePage, movePage, now });
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<container loc={props.loc}>
|
||||
<container loc={contentLoc.value}>
|
||||
{slots.default?.(nowPage.value)}
|
||||
</container>
|
||||
<container loc={pageLoc.value} hidden={hide.value}>
|
||||
<container
|
||||
key={1}
|
||||
loc={leftLoc.value}
|
||||
onClick={lastPage}
|
||||
cursor="pointer"
|
||||
>
|
||||
<g-rectr
|
||||
loc={rectLoc.value}
|
||||
circle={[round.value]}
|
||||
strokeStyle={leftColor.value}
|
||||
lineWidth={1}
|
||||
stroke
|
||||
></g-rectr>
|
||||
<g-path
|
||||
path={leftArrow.value}
|
||||
stroke
|
||||
strokeStyle={leftColor.value}
|
||||
lineWidth={1}
|
||||
></g-path>
|
||||
</container>
|
||||
{!isFirst.value && (
|
||||
<container
|
||||
key={2}
|
||||
loc={leftPageLoc.value}
|
||||
onClick={lastPage}
|
||||
cursor="pointer"
|
||||
>
|
||||
<g-rectr
|
||||
loc={rectLoc.value}
|
||||
circle={[round.value]}
|
||||
strokeStyle="#ddd"
|
||||
lineWidth={1}
|
||||
stroke
|
||||
></g-rectr>
|
||||
<text
|
||||
loc={textLoc.value}
|
||||
text={nowPage.value.toString()}
|
||||
font={font.value}
|
||||
></text>
|
||||
</container>
|
||||
)}
|
||||
<container loc={nowPageLoc.value} key={3}>
|
||||
<g-rectr
|
||||
loc={rectLoc.value}
|
||||
circle={[round.value]}
|
||||
strokeStyle="#ddd"
|
||||
fillStyle="#ddd"
|
||||
lineWidth={1}
|
||||
fill
|
||||
stroke
|
||||
></g-rectr>
|
||||
<text
|
||||
loc={textLoc.value}
|
||||
text={(nowPage.value + 1).toString()}
|
||||
fillStyle="#222"
|
||||
font={nowPageFont.value}
|
||||
></text>
|
||||
</container>
|
||||
{!isLast.value && (
|
||||
<container
|
||||
key={4}
|
||||
loc={rightPageLoc.value}
|
||||
onClick={nextPage}
|
||||
cursor="pointer"
|
||||
>
|
||||
<g-rectr
|
||||
loc={rectLoc.value}
|
||||
circle={[round.value]}
|
||||
strokeStyle="#ddd"
|
||||
lineWidth={1}
|
||||
stroke
|
||||
></g-rectr>
|
||||
<text
|
||||
loc={textLoc.value}
|
||||
text={(nowPage.value + 2).toString()}
|
||||
font={font.value}
|
||||
></text>
|
||||
</container>
|
||||
)}
|
||||
<container
|
||||
key={5}
|
||||
loc={rightLoc.value}
|
||||
onClick={nextPage}
|
||||
cursor="pointer"
|
||||
>
|
||||
<g-rectr
|
||||
loc={rectLoc.value}
|
||||
circle={[round.value]}
|
||||
strokeStyle={rightColor.value}
|
||||
lineWidth={1}
|
||||
stroke
|
||||
></g-rectr>
|
||||
<g-path
|
||||
path={rightArrow.value}
|
||||
stroke
|
||||
strokeStyle={rightColor.value}
|
||||
lineWidth={1}
|
||||
></g-path>
|
||||
</container>
|
||||
</container>
|
||||
</container>
|
||||
);
|
||||
};
|
||||
}, pageProps);
|
||||
@@ -1,556 +0,0 @@
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
nextTick,
|
||||
onMounted,
|
||||
onUnmounted,
|
||||
onUpdated,
|
||||
ref,
|
||||
SlotsType,
|
||||
VNode,
|
||||
watch
|
||||
} from 'vue';
|
||||
import { SetupComponentOptions } from './types';
|
||||
import {
|
||||
Container,
|
||||
DefaultProps,
|
||||
ElementLocator,
|
||||
RenderItem,
|
||||
Sprite,
|
||||
Transform,
|
||||
MotaOffscreenCanvas2D,
|
||||
IActionEvent,
|
||||
IWheelEvent,
|
||||
MouseType
|
||||
} from '@motajs/render';
|
||||
import { hyper, linear, Transition } from 'mutate-animate';
|
||||
import { clamp } from 'lodash-es';
|
||||
import { transitioned } from '../use';
|
||||
|
||||
export const enum ScrollDirection {
|
||||
Horizontal,
|
||||
Vertical
|
||||
}
|
||||
|
||||
export interface ScrollExpose {
|
||||
/**
|
||||
* 控制滚动条滚动至目标位置
|
||||
* @param y 滚动至的目标位置
|
||||
* @param time 滚动的动画时长,默认为无动画
|
||||
*/
|
||||
scrollTo(y: number, time?: number): void;
|
||||
|
||||
/**
|
||||
* 获取这个滚动条组件最多可以滚动多长
|
||||
*/
|
||||
getScrollLength(): number;
|
||||
}
|
||||
|
||||
export interface ScrollProps extends DefaultProps {
|
||||
loc: ElementLocator;
|
||||
hor?: boolean;
|
||||
noscroll?: boolean;
|
||||
/**
|
||||
* 滚动到最下方(最右方)时的填充大小,如果默认的高度计算方式有误,
|
||||
* 那么可以调整此参数来修复错误
|
||||
*/
|
||||
padEnd?: number;
|
||||
}
|
||||
|
||||
type ScrollSlots = SlotsType<{
|
||||
default: () => VNode | VNode[];
|
||||
}>;
|
||||
|
||||
const scrollProps = {
|
||||
props: ['hor', 'noscroll', 'loc', 'padEnd']
|
||||
} satisfies SetupComponentOptions<ScrollProps, {}, string, ScrollSlots>;
|
||||
|
||||
/** 滚动条图示的最短长度 */
|
||||
const SCROLL_MIN_LENGTH = 20;
|
||||
/** 滚动条图示的宽度 */
|
||||
const SCROLL_WIDTH = 10;
|
||||
/** 滚动条的颜色 */
|
||||
const SCROLL_COLOR = '255,255,255';
|
||||
|
||||
/**
|
||||
* 滚动条组件,具有虚拟滚动功能,即在画面外的不渲染。参数参考 {@link ScrollProps},暴露接口参考 {@link ScrollExpose}
|
||||
*
|
||||
* ---
|
||||
*
|
||||
* 使用时,建议使用平铺式布局,即包含很多子元素,而不要用一个 container 将所有内容包裹,
|
||||
* 每个子元素的高度(宽度)不建议过大,以更好地通过虚拟滚动优化
|
||||
*
|
||||
* **推荐写法**:
|
||||
* ```tsx
|
||||
* <Scroll>
|
||||
* <item />
|
||||
* <item />
|
||||
* ...其他元素
|
||||
* <item />
|
||||
* <item />
|
||||
* </Scroll>
|
||||
* ```
|
||||
* **不推荐**使用这种写法:
|
||||
* ```tsx
|
||||
* <Scroll>
|
||||
* <container>
|
||||
* <item />
|
||||
* </container>
|
||||
* <Scroll>
|
||||
* ```
|
||||
*/
|
||||
export const Scroll = defineComponent<ScrollProps, {}, string, ScrollSlots>(
|
||||
(props, { slots, expose }) => {
|
||||
/** 滚动条的定位 */
|
||||
const sp = ref<ElementLocator>([0, 0, 1, 1]);
|
||||
|
||||
const listenedChild: Set<RenderItem> = new Set();
|
||||
const areaMap: Map<RenderItem, [number, number]> = new Map();
|
||||
const content = ref<Container>();
|
||||
const scroll = ref<Sprite>();
|
||||
|
||||
const scrollAlpha = transitioned(0.5, 100, linear())!;
|
||||
|
||||
const width = computed(() => props.loc[2] ?? 200);
|
||||
const height = computed(() => props.loc[3] ?? 200);
|
||||
const direction = computed(() =>
|
||||
props.hor ? ScrollDirection.Horizontal : ScrollDirection.Vertical
|
||||
);
|
||||
const scrollColor = computed(
|
||||
() => `rgba(${SCROLL_COLOR},${scrollAlpha.ref.value ?? 0.5})`
|
||||
);
|
||||
const padEnd = computed(() => props.padEnd ?? 0);
|
||||
|
||||
watch(scrollColor, () => {
|
||||
scroll.value?.update();
|
||||
});
|
||||
|
||||
/** 滚动内容的当前位置 */
|
||||
let contentPos = 0;
|
||||
/** 滚动条的当前位置 */
|
||||
let scrollPos = 0;
|
||||
/** 滚动内容的目标位置 */
|
||||
let contentTarget = 0;
|
||||
/** 滚动条的目标位置 */
|
||||
let scrollTarget = 0;
|
||||
/** 滚动内容的长度 */
|
||||
let maxLength = 0;
|
||||
/** 滚动条的长度 */
|
||||
let scrollLength = SCROLL_MIN_LENGTH;
|
||||
|
||||
const transition = new Transition();
|
||||
transition.value.scroll = 0;
|
||||
transition.value.showScroll = 0;
|
||||
transition.mode(hyper('sin', 'out')).absolute();
|
||||
|
||||
//#region 滚动操作
|
||||
|
||||
transition.ticker.add(() => {
|
||||
if (scrollPos !== scrollTarget) {
|
||||
scrollPos = transition.value.scroll;
|
||||
content.value?.update();
|
||||
}
|
||||
if (contentPos !== contentTarget) {
|
||||
contentPos = transition.value.showScroll;
|
||||
checkAllItem();
|
||||
content.value?.update();
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 滚动到目标值
|
||||
* @param time 动画时长
|
||||
*/
|
||||
const scrollTo = (y: number, time: number = 0) => {
|
||||
if (maxLength < height.value) return;
|
||||
const max = maxLength - height.value;
|
||||
const target = clamp(y, 0, max);
|
||||
contentTarget = target;
|
||||
if (direction.value === ScrollDirection.Horizontal) {
|
||||
scrollTarget =
|
||||
(width.value - scrollLength) * (contentTarget / max);
|
||||
} else {
|
||||
scrollTarget =
|
||||
(height.value - scrollLength) * (contentTarget / max);
|
||||
}
|
||||
if (isNaN(scrollTarget)) scrollTarget = 0;
|
||||
transition.time(time).transition('scroll', scrollTarget);
|
||||
transition.time(time).transition('showScroll', target);
|
||||
};
|
||||
|
||||
/**
|
||||
* 计算一个元素会在画面上显示的区域
|
||||
*/
|
||||
const getArea = (item: RenderItem, rect: DOMRectReadOnly) => {
|
||||
if (direction.value === ScrollDirection.Horizontal) {
|
||||
areaMap.set(item, [rect.left - width.value, rect.right]);
|
||||
} else {
|
||||
areaMap.set(item, [rect.top - height.value, rect.bottom]);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 检查一个元素是否需要显示,不需要则隐藏
|
||||
*/
|
||||
const checkItem = (item: RenderItem) => {
|
||||
const area = areaMap.get(item);
|
||||
if (!area) {
|
||||
item.show();
|
||||
return;
|
||||
}
|
||||
const [min, max] = area;
|
||||
if (contentPos > min - 10 && contentPos < max + 10) {
|
||||
item.show();
|
||||
} else {
|
||||
item.hide();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 对所有元素执行显示检查
|
||||
*/
|
||||
const checkAllItem = () => {
|
||||
content.value?.children.forEach(v => checkItem(v));
|
||||
};
|
||||
|
||||
/**
|
||||
* 当一个元素的矩阵发生变换时执行,检查其显示区域
|
||||
*/
|
||||
const onTransform = (item: RenderItem) => {
|
||||
const rect = item.getBoundingRect();
|
||||
const pad = props.padEnd ?? 0;
|
||||
if (item.parent === content.value) {
|
||||
if (direction.value === ScrollDirection.Horizontal) {
|
||||
if (rect.right > maxLength - pad) {
|
||||
maxLength = rect.right + pad;
|
||||
updatePosition();
|
||||
}
|
||||
} else {
|
||||
if (rect.bottom > maxLength - pad) {
|
||||
maxLength = rect.bottom + pad;
|
||||
updatePosition();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
item.off('transform', onTransform);
|
||||
listenedChild.delete(item);
|
||||
}
|
||||
getArea(item, rect);
|
||||
checkItem(item);
|
||||
scroll.value?.update();
|
||||
content.value?.update();
|
||||
};
|
||||
|
||||
/**
|
||||
* 更新滚动条位置
|
||||
*/
|
||||
const updatePosition = () => {
|
||||
if (direction.value === ScrollDirection.Horizontal) {
|
||||
scrollLength = clamp(
|
||||
(height.value / maxLength) * width.value,
|
||||
SCROLL_MIN_LENGTH,
|
||||
width.value
|
||||
);
|
||||
const h = props.noscroll
|
||||
? height.value
|
||||
: height.value - SCROLL_WIDTH;
|
||||
sp.value = [0, h, width.value, SCROLL_WIDTH];
|
||||
} else {
|
||||
scrollLength = clamp(
|
||||
(height.value / maxLength) * height.value,
|
||||
SCROLL_MIN_LENGTH,
|
||||
height.value
|
||||
);
|
||||
const w = props.noscroll
|
||||
? width.value
|
||||
: width.value - SCROLL_WIDTH;
|
||||
sp.value = [w, 0, SCROLL_WIDTH, height.value];
|
||||
}
|
||||
};
|
||||
|
||||
let updating = false;
|
||||
const updateScroll = () => {
|
||||
if (!content.value || updating) return;
|
||||
updating = true;
|
||||
nextTick(() => {
|
||||
updating = false;
|
||||
});
|
||||
let max = 0;
|
||||
listenedChild.forEach(v => v.off('transform', onTransform));
|
||||
listenedChild.clear();
|
||||
areaMap.clear();
|
||||
content.value.children.forEach(v => {
|
||||
if (v.isComment) return;
|
||||
const rect = v.getBoundingRect();
|
||||
if (direction.value === ScrollDirection.Horizontal) {
|
||||
if (rect.right > max) {
|
||||
max = rect.right;
|
||||
}
|
||||
} else {
|
||||
if (rect.bottom > max) {
|
||||
max = rect.bottom;
|
||||
}
|
||||
}
|
||||
getArea(v, rect);
|
||||
if (!listenedChild.has(v)) {
|
||||
v.on('transform', onTransform);
|
||||
listenedChild.add(v);
|
||||
}
|
||||
checkItem(v);
|
||||
});
|
||||
maxLength = Math.max(max + padEnd.value, 10);
|
||||
updatePosition();
|
||||
scroll.value?.update();
|
||||
};
|
||||
|
||||
watch(() => props.loc, updateScroll);
|
||||
onUpdated(updateScroll);
|
||||
onMounted(updateScroll);
|
||||
onUnmounted(() => {
|
||||
listenedChild.forEach(v => v.off('transform', onTransform));
|
||||
});
|
||||
|
||||
//#endregion
|
||||
|
||||
//#region 渲染滚动
|
||||
|
||||
const drawScroll = (canvas: MotaOffscreenCanvas2D) => {
|
||||
if (props.noscroll) return;
|
||||
const ctx = canvas.ctx;
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineWidth = 3;
|
||||
ctx.strokeStyle = scrollColor.value;
|
||||
ctx.beginPath();
|
||||
const scroll = transition.value.scroll;
|
||||
if (direction.value === ScrollDirection.Horizontal) {
|
||||
ctx.moveTo(scroll + 5, 5);
|
||||
ctx.lineTo(scroll + scrollLength - 5, 5);
|
||||
} else {
|
||||
ctx.moveTo(5, scroll + 5);
|
||||
ctx.lineTo(5, scroll + scrollLength - 5);
|
||||
}
|
||||
ctx.stroke();
|
||||
};
|
||||
|
||||
const renderContent = (
|
||||
canvas: MotaOffscreenCanvas2D,
|
||||
children: RenderItem[],
|
||||
transform: Transform
|
||||
) => {
|
||||
const ctx = canvas.ctx;
|
||||
ctx.save();
|
||||
if (direction.value === ScrollDirection.Horizontal) {
|
||||
ctx.translate(-contentPos, 0);
|
||||
} else {
|
||||
ctx.translate(0, -contentPos);
|
||||
}
|
||||
children.forEach(v => {
|
||||
if (v.hidden) return;
|
||||
v.renderContent(canvas, transform);
|
||||
});
|
||||
ctx.restore();
|
||||
};
|
||||
|
||||
//#endregion
|
||||
|
||||
//#region 事件监听
|
||||
|
||||
const wheelScroll = (delta: number, max: number) => {
|
||||
const sign = Math.sign(delta);
|
||||
const dx = Math.abs(delta);
|
||||
const movement = Math.min(max, dx) * sign;
|
||||
scrollTo(contentTarget + movement, dx > 10 ? 300 : 0);
|
||||
};
|
||||
|
||||
const wheel = (ev: IWheelEvent) => {
|
||||
if (direction.value === ScrollDirection.Horizontal) {
|
||||
if (ev.wheelX !== 0) {
|
||||
wheelScroll(ev.wheelX, width.value / 5);
|
||||
} else if (ev.wheelY !== 0) {
|
||||
wheelScroll(ev.wheelY, width.value / 5);
|
||||
}
|
||||
} else {
|
||||
wheelScroll(ev.wheelY, height.value / 5);
|
||||
}
|
||||
};
|
||||
|
||||
const getPos = (ev: IActionEvent, absolute: boolean = false) => {
|
||||
if (absolute) {
|
||||
if (direction.value === ScrollDirection.Horizontal) {
|
||||
return ev.absoluteX;
|
||||
} else {
|
||||
return ev.absoluteY;
|
||||
}
|
||||
} else {
|
||||
if (direction.value === ScrollDirection.Horizontal) {
|
||||
return ev.offsetX;
|
||||
} else {
|
||||
return ev.offsetY;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let identifier = -2;
|
||||
let downPos = 0;
|
||||
/** 拖动内容时,内容原本所在的位置 */
|
||||
let contentBefore = 0;
|
||||
|
||||
const down = (ev: IActionEvent) => {
|
||||
identifier = ev.identifier;
|
||||
downPos = getPos(ev, true);
|
||||
contentBefore = contentTarget;
|
||||
};
|
||||
|
||||
const move = (ev: IActionEvent) => {
|
||||
if (ev.identifier !== identifier) return;
|
||||
let pos = 0;
|
||||
if (ev.touch) {
|
||||
pos = getPos(ev);
|
||||
} else {
|
||||
if (ev.buttons & MouseType.Left) {
|
||||
pos = getPos(ev);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const movement = pos - downPos;
|
||||
scrollTo(contentBefore - movement, 0);
|
||||
};
|
||||
|
||||
/** 最初滚动条在哪 */
|
||||
let scrollBefore = 0;
|
||||
/** 本次拖动滚动条的操作标识符 */
|
||||
let scrollIdentifier = -2;
|
||||
/** 点击滚动条时,点击位置在平行于滚动条方向的位置 */
|
||||
let scrollDownPos = 0;
|
||||
/** 是否是点击了滚动条区域中滚动条之外的地方,这样视为类滚轮操作 */
|
||||
let scrollMutate = false;
|
||||
/** 点击滚动条时,点击位置垂直于滚动条方向的位置 */
|
||||
let scrollPin = 0;
|
||||
|
||||
/**
|
||||
* 获取点击滚动条时,垂直于滚动条方向的位置
|
||||
*/
|
||||
const getScrollPin = (ev: IActionEvent) => {
|
||||
if (direction.value === ScrollDirection.Horizontal) {
|
||||
return ev.absoluteY;
|
||||
} else {
|
||||
return ev.absoluteX;
|
||||
}
|
||||
};
|
||||
|
||||
const downScroll = (ev: IActionEvent) => {
|
||||
scrollBefore = contentTarget;
|
||||
scrollIdentifier = ev.identifier;
|
||||
const pos = getPos(ev, true);
|
||||
// 计算点击在了滚动条的哪个位置
|
||||
const offsetPos = getPos(ev);
|
||||
const sEnd = scrollPos + scrollLength;
|
||||
if (offsetPos >= scrollPos && offsetPos <= sEnd) {
|
||||
scrollDownPos = pos - scrollPos;
|
||||
scrollMutate = false;
|
||||
scrollPin = getScrollPin(ev);
|
||||
} else {
|
||||
scrollMutate = true;
|
||||
}
|
||||
scrollAlpha.set(0.9);
|
||||
};
|
||||
|
||||
const moveScroll = (ev: IActionEvent) => {
|
||||
if (ev.identifier !== scrollIdentifier || scrollMutate) return;
|
||||
const pos = getPos(ev, true);
|
||||
const scrollPos = pos - scrollDownPos;
|
||||
let deltaPin = 0;
|
||||
let threshold = 0;
|
||||
if (ev.touch) {
|
||||
const pin = getScrollPin(ev);
|
||||
deltaPin = Math.abs(pin - scrollPin);
|
||||
threshold = 200;
|
||||
} else {
|
||||
const pin = getScrollPin(ev);
|
||||
deltaPin = Math.abs(pin - scrollPin);
|
||||
threshold = 100;
|
||||
}
|
||||
if (deltaPin > threshold) {
|
||||
scrollTo(scrollBefore, 0);
|
||||
} else {
|
||||
const pos = (scrollPos / height.value) * maxLength;
|
||||
scrollTo(pos, 0);
|
||||
}
|
||||
};
|
||||
|
||||
const upScroll = (ev: IActionEvent) => {
|
||||
scrollAlpha.set(0.7);
|
||||
if (!scrollMutate) return;
|
||||
const pos = getPos(ev);
|
||||
if (pos < scrollPos) {
|
||||
scrollTo(contentTarget - 50, 300);
|
||||
} else {
|
||||
scrollTo(contentTarget + 50, 300);
|
||||
}
|
||||
};
|
||||
|
||||
const enter = () => {
|
||||
scrollAlpha.set(0.7);
|
||||
};
|
||||
|
||||
const leave = () => {
|
||||
scrollAlpha.set(0.5);
|
||||
};
|
||||
|
||||
//#endregion
|
||||
|
||||
onMounted(() => {
|
||||
scroll.value?.root?.on('move', move);
|
||||
scroll.value?.root?.on('move', moveScroll);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
scroll.value?.root?.off('move', move);
|
||||
scroll.value?.root?.off('move', moveScroll);
|
||||
transition.ticker.destroy();
|
||||
});
|
||||
|
||||
//#region expose 函数
|
||||
|
||||
const getScrollLength = () => {
|
||||
return maxLength - height.value;
|
||||
};
|
||||
|
||||
expose<ScrollExpose>({
|
||||
scrollTo,
|
||||
getScrollLength
|
||||
});
|
||||
|
||||
//#endregion
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<container loc={props.loc} onWheel={wheel}>
|
||||
<container-custom
|
||||
loc={[0, 0, props.loc[2], props.loc[3]]}
|
||||
ref={content}
|
||||
onDown={down}
|
||||
render={renderContent}
|
||||
zIndex={0}
|
||||
>
|
||||
{slots.default?.()}
|
||||
</container-custom>
|
||||
<sprite
|
||||
nocache
|
||||
hidden={props.noscroll}
|
||||
loc={sp.value}
|
||||
ref={scroll}
|
||||
render={drawScroll}
|
||||
onDown={downScroll}
|
||||
onUp={upScroll}
|
||||
zIndex={10}
|
||||
onEnter={enter}
|
||||
onLeave={leave}
|
||||
></sprite>
|
||||
</container>
|
||||
);
|
||||
};
|
||||
},
|
||||
scrollProps
|
||||
);
|
||||
@@ -1,593 +0,0 @@
|
||||
import {
|
||||
ElementLocator,
|
||||
Font,
|
||||
Sprite,
|
||||
DefaultProps,
|
||||
Text,
|
||||
MotaOffscreenCanvas2D
|
||||
} from '@motajs/render';
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
nextTick,
|
||||
onMounted,
|
||||
onUnmounted,
|
||||
ref,
|
||||
shallowReactive,
|
||||
shallowRef,
|
||||
SlotsType,
|
||||
VNode,
|
||||
watch
|
||||
} from 'vue';
|
||||
import { logger } from '@motajs/common';
|
||||
import { isNil } from 'lodash-es';
|
||||
import { SetupComponentOptions } from './types';
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import {
|
||||
ITextContentConfig,
|
||||
TextContentTyper,
|
||||
TyperRenderable,
|
||||
TextContentType,
|
||||
WordBreak,
|
||||
TextAlign
|
||||
} from './textboxTyper';
|
||||
|
||||
export interface TextContentProps
|
||||
extends DefaultProps,
|
||||
Partial<ITextContentConfig> {
|
||||
/** 显示的文字 */
|
||||
text?: string;
|
||||
/** 是否填充 */
|
||||
fill?: boolean;
|
||||
/** 是否描边 */
|
||||
stroke?: boolean;
|
||||
/** 是否自适应高度 */
|
||||
autoHeight?: boolean;
|
||||
/** 文字的最大宽度 */
|
||||
width: number;
|
||||
}
|
||||
|
||||
export type TextContentEmits = {
|
||||
typeEnd: () => void;
|
||||
typeStart: () => void;
|
||||
updateHeight: (height: number) => void;
|
||||
};
|
||||
|
||||
export interface TextContentExpose {
|
||||
/**
|
||||
* 重新开始打字
|
||||
*/
|
||||
retype(): void;
|
||||
|
||||
/**
|
||||
* 立刻显示所有文字
|
||||
*/
|
||||
showAll(): void;
|
||||
|
||||
/**
|
||||
* 获取这段 TextContent 的总高度
|
||||
*/
|
||||
getHeight(): number;
|
||||
}
|
||||
|
||||
const textContentOptions = {
|
||||
props: [
|
||||
'breakChars',
|
||||
'font',
|
||||
'ignoreLineEnd',
|
||||
'ignoreLineStart',
|
||||
'interval',
|
||||
'keepLast',
|
||||
'lineHeight',
|
||||
'text',
|
||||
'textAlign',
|
||||
'wordBreak',
|
||||
'fill',
|
||||
'fillStyle',
|
||||
'strokeStyle',
|
||||
'strokeWidth',
|
||||
'stroke',
|
||||
'loc',
|
||||
'width',
|
||||
'autoHeight'
|
||||
],
|
||||
emits: ['typeEnd', 'typeStart', 'updateHeight']
|
||||
} satisfies SetupComponentOptions<
|
||||
TextContentProps,
|
||||
TextContentEmits,
|
||||
keyof TextContentEmits
|
||||
>;
|
||||
|
||||
export const TextContent = defineComponent<
|
||||
TextContentProps,
|
||||
TextContentEmits,
|
||||
keyof TextContentEmits
|
||||
>((props, { emit, expose }) => {
|
||||
const loc = ref<ElementLocator>(
|
||||
(props.loc?.slice() as ElementLocator) ?? []
|
||||
);
|
||||
|
||||
if (props.width < 0) {
|
||||
logger.warn(41, String(props.width));
|
||||
}
|
||||
|
||||
const typer = new TextContentTyper(props);
|
||||
let renderable: TyperRenderable[] = [];
|
||||
let needUpdate = false;
|
||||
|
||||
const retype = () => {
|
||||
if (needUpdate) return;
|
||||
needUpdate = true;
|
||||
if (!spriteElement.value) {
|
||||
needUpdate = false;
|
||||
}
|
||||
renderable = [];
|
||||
|
||||
spriteElement.value?.requestBeforeFrame(() => {
|
||||
typer.setConfig(props);
|
||||
typer.setText(props.text ?? '');
|
||||
typer.type();
|
||||
needUpdate = false;
|
||||
updateLoc();
|
||||
});
|
||||
};
|
||||
|
||||
const showAll = () => {
|
||||
typer.typeAll();
|
||||
};
|
||||
|
||||
watch(props, () => {
|
||||
typer.setConfig(props);
|
||||
retype();
|
||||
});
|
||||
|
||||
const getHeight = () => {
|
||||
return typer.getHeight();
|
||||
};
|
||||
|
||||
const updateLoc = () => {
|
||||
const height = getHeight();
|
||||
if (props.autoHeight) {
|
||||
const [x = 0, y = 0, width = 200, , ax = 0, ay = 0] = loc.value;
|
||||
loc.value = [x, y, width, height, ax, ay];
|
||||
}
|
||||
emit('updateHeight', height);
|
||||
};
|
||||
|
||||
expose<TextContentExpose>({ retype, showAll, getHeight });
|
||||
|
||||
const spriteElement = shallowRef<Sprite>();
|
||||
const renderContent = (canvas: MotaOffscreenCanvas2D) => {
|
||||
const ctx = canvas.ctx;
|
||||
ctx.textBaseline = 'top';
|
||||
renderable.forEach(v => {
|
||||
switch (v.type) {
|
||||
case TextContentType.Text: {
|
||||
if (v.text.length === 0) return;
|
||||
ctx.fillStyle = v.fillStyle;
|
||||
ctx.strokeStyle = v.strokeStyle;
|
||||
ctx.font = v.font;
|
||||
const text = v.text.slice(0, v.pointer);
|
||||
|
||||
if (props.fill ?? true) {
|
||||
ctx.fillText(text, v.x, v.y);
|
||||
}
|
||||
if (props.stroke) {
|
||||
ctx.strokeText(text, v.x, v.y);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case TextContentType.Icon: {
|
||||
const { renderable: r, x: dx, y: dy, width, height } = v;
|
||||
const render = r.render;
|
||||
const [x, y, w, h] = render[0];
|
||||
const icon = r.autotile ? r.image[0] : r.image;
|
||||
ctx.drawImage(icon, x, y, w, h, dx, dy, width, height);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const renderFunc = (data: TyperRenderable[]) => {
|
||||
renderable = data;
|
||||
spriteElement.value?.update();
|
||||
};
|
||||
|
||||
typer.setRender(renderFunc);
|
||||
typer.on('typeStart', () => {
|
||||
emit('typeStart');
|
||||
});
|
||||
typer.on('typeEnd', () => {
|
||||
emit('typeEnd');
|
||||
});
|
||||
|
||||
onMounted(retype);
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<sprite
|
||||
loc={loc.value}
|
||||
ref={spriteElement}
|
||||
render={renderContent}
|
||||
></sprite>
|
||||
);
|
||||
};
|
||||
}, textContentOptions);
|
||||
|
||||
export interface TextboxProps extends TextContentProps, DefaultProps {
|
||||
/** 背景颜色 */
|
||||
backColor?: CanvasStyle;
|
||||
/** 背景 winskin */
|
||||
winskin?: ImageIds;
|
||||
/** 边框与文字间的距离,默认为8 */
|
||||
padding?: number;
|
||||
/** 标题 */
|
||||
title?: string;
|
||||
/** 标题字体 */
|
||||
titleFont?: Font;
|
||||
/** 标题填充样式 */
|
||||
titleFill?: CanvasStyle;
|
||||
/** 标题描边样式 */
|
||||
titleStroke?: CanvasStyle;
|
||||
/** 标题文字与边框间的距离,默认为4 */
|
||||
titlePadding?: number;
|
||||
/** 最大宽度 */
|
||||
width: number;
|
||||
}
|
||||
|
||||
export interface TextboxExpose {
|
||||
/**
|
||||
* 显示这个文本框
|
||||
*/
|
||||
show(): void;
|
||||
|
||||
/**
|
||||
* 隐藏这个文本框
|
||||
*/
|
||||
hide(): void;
|
||||
|
||||
/**
|
||||
* 重新开始打字
|
||||
*/
|
||||
retype(): void;
|
||||
|
||||
/**
|
||||
* 立刻显示所有文字
|
||||
*/
|
||||
showAll(): void;
|
||||
}
|
||||
|
||||
type TextboxEmits = TextContentEmits;
|
||||
type TextboxSlots = SlotsType<{
|
||||
default: (data: TextboxProps) => VNode[];
|
||||
title: (data: TextboxProps) => VNode[];
|
||||
}>;
|
||||
|
||||
const textboxOptions = {
|
||||
props: (textContentOptions.props as (keyof TextboxProps)[]).concat([
|
||||
'backColor',
|
||||
'winskin',
|
||||
'padding',
|
||||
'titleFill',
|
||||
'titleStroke',
|
||||
'titleFont',
|
||||
'titlePadding',
|
||||
'id',
|
||||
'hidden',
|
||||
'title'
|
||||
]),
|
||||
emits: textContentOptions.emits
|
||||
} satisfies SetupComponentOptions<TextboxProps, {}, string, TextboxSlots>;
|
||||
|
||||
let id = 0;
|
||||
function getNextTextboxId() {
|
||||
return `@default-textbox-${id++}`;
|
||||
}
|
||||
|
||||
export const Textbox = defineComponent<
|
||||
TextboxProps,
|
||||
TextboxEmits,
|
||||
keyof TextboxEmits,
|
||||
TextboxSlots
|
||||
>((props, { slots, expose }) => {
|
||||
const contentData = shallowReactive<TextContentProps>({ width: 200 });
|
||||
const data = shallowReactive<TextboxProps>({ width: 200 });
|
||||
|
||||
const setContentData = () => {
|
||||
contentData.breakChars = props.breakChars ?? '';
|
||||
contentData.font = props.font ?? new Font();
|
||||
contentData.ignoreLineEnd = props.ignoreLineEnd ?? '';
|
||||
contentData.ignoreLineStart = props.ignoreLineStart ?? '';
|
||||
contentData.interval = props.interval ?? 0;
|
||||
contentData.keepLast = props.keepLast ?? false;
|
||||
contentData.lineHeight = props.lineHeight ?? 0;
|
||||
contentData.text = props.text ?? '';
|
||||
contentData.textAlign = props.textAlign ?? TextAlign.Left;
|
||||
contentData.wordBreak = props.wordBreak ?? WordBreak.Space;
|
||||
contentData.fill = props.fill ?? true;
|
||||
contentData.stroke = props.stroke ?? false;
|
||||
contentData.fillStyle = props.fillStyle ?? '#fff';
|
||||
contentData.strokeStyle = props.strokeStyle ?? '#000';
|
||||
contentData.strokeWidth = props.strokeWidth ?? 2;
|
||||
contentData.loc = props.loc;
|
||||
contentData.width = props.width;
|
||||
};
|
||||
|
||||
const setTextboxData = () => {
|
||||
data.backColor = props.backColor ?? '#222';
|
||||
data.winskin = props.winskin;
|
||||
data.padding = props.padding ?? 8;
|
||||
data.titleFill = props.titleFill ?? 'gold';
|
||||
data.titleStroke = props.titleStroke ?? 'transparent';
|
||||
data.titleFont = props.titleFont ?? new Font('Verdana', 18);
|
||||
data.titlePadding = props.titlePadding ?? 8;
|
||||
data.width = props.width ?? props.loc?.[2] ?? 200;
|
||||
data.height = props.height ?? props.loc?.[3] ?? 200;
|
||||
data.title = props.title ?? '';
|
||||
};
|
||||
|
||||
setContentData();
|
||||
setTextboxData();
|
||||
|
||||
watch(props, () => {
|
||||
const needUpdateTitle = data.title !== props.title;
|
||||
setTextboxData();
|
||||
if (needUpdateTitle) {
|
||||
onSetText();
|
||||
}
|
||||
});
|
||||
|
||||
const titleElement = ref<Text>();
|
||||
const content = ref<TextContentExpose>();
|
||||
const hidden = ref(props.hidden);
|
||||
/** 标题宽度 */
|
||||
const tw = ref(data.titlePadding! * 2);
|
||||
/** 标题高度 */
|
||||
const th = ref(data.titlePadding! * 2);
|
||||
const contentY = computed(() => {
|
||||
const height = th.value;
|
||||
return data.title ? height : 0;
|
||||
});
|
||||
const backHeight = computed(() => data.height! - contentY.value);
|
||||
const contentWidth = computed(() => data.width! - data.padding! * 2);
|
||||
const contentHeight = computed(
|
||||
() => data.height! - data.padding! * 2 - contentY.value
|
||||
);
|
||||
|
||||
const onSetText = () => {
|
||||
nextTick(() => {
|
||||
titleElement.value?.requestBeforeFrame(() => {
|
||||
if (titleElement.value) {
|
||||
const { width, height } = titleElement.value;
|
||||
tw.value = width + data.padding! * 2;
|
||||
th.value = height + data.padding! * 2;
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// ----- store
|
||||
|
||||
/** 结束打字机 */
|
||||
const storeEmits: TextboxStoreEmits = {
|
||||
endType() {
|
||||
content.value?.showAll();
|
||||
},
|
||||
hide() {
|
||||
hidden.value = true;
|
||||
},
|
||||
show() {
|
||||
hidden.value = false;
|
||||
},
|
||||
update(value) {
|
||||
if (data.title !== value.title) {
|
||||
data.title = value.title;
|
||||
onSetText();
|
||||
}
|
||||
},
|
||||
setText(text) {
|
||||
if (contentData.text === text) {
|
||||
content.value?.retype();
|
||||
} else {
|
||||
contentData.text = text;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const store = TextboxStore.use(
|
||||
props.id ?? getNextTextboxId(),
|
||||
contentData,
|
||||
storeEmits
|
||||
);
|
||||
|
||||
const onTypeStart = () => {
|
||||
store.emitTypeStart();
|
||||
};
|
||||
|
||||
const onTypeEnd = () => {
|
||||
store.emitTypeEnd();
|
||||
};
|
||||
|
||||
expose<TextboxExpose>({
|
||||
show() {
|
||||
hidden.value = false;
|
||||
},
|
||||
hide() {
|
||||
hidden.value = true;
|
||||
},
|
||||
retype() {
|
||||
content.value?.retype();
|
||||
},
|
||||
showAll() {
|
||||
content.value?.showAll();
|
||||
}
|
||||
});
|
||||
|
||||
return () => (
|
||||
<container
|
||||
id={props.id}
|
||||
hidden={hidden.value}
|
||||
alpha={data.alpha}
|
||||
loc={props.loc}
|
||||
>
|
||||
{data.title && (
|
||||
<container zIndex={10} loc={[0, 0, tw.value, th.value]}>
|
||||
{slots.title ? (
|
||||
slots.title(data)
|
||||
) : props.winskin ? (
|
||||
<winskin
|
||||
image={props.winskin}
|
||||
loc={[0, 0, tw.value, th.value]}
|
||||
></winskin>
|
||||
) : (
|
||||
<g-rect loc={[0, 0, tw.value, th.value]}></g-rect>
|
||||
)}
|
||||
<text
|
||||
ref={titleElement}
|
||||
text={data.title}
|
||||
loc={[data.titlePadding, data.titlePadding]}
|
||||
fillStyle={data.titleFill}
|
||||
strokeStyle={data.titleStroke}
|
||||
font={data.titleFont}
|
||||
></text>
|
||||
</container>
|
||||
)}
|
||||
{slots.default ? (
|
||||
slots.default(data)
|
||||
) : props.winskin ? (
|
||||
<winskin
|
||||
image={props.winskin}
|
||||
loc={[0, contentY.value, data.width!, backHeight.value]}
|
||||
></winskin>
|
||||
) : (
|
||||
<g-rect
|
||||
loc={[0, contentY.value, data.width!, backHeight.value]}
|
||||
fill
|
||||
fillStyle={data.backColor}
|
||||
></g-rect>
|
||||
)}
|
||||
<TextContent
|
||||
{...contentData}
|
||||
ref={content}
|
||||
x={data.padding!}
|
||||
y={contentY.value + data.padding!}
|
||||
width={contentWidth.value}
|
||||
height={contentHeight.value}
|
||||
onTypeEnd={onTypeEnd}
|
||||
onTypeStart={onTypeStart}
|
||||
></TextContent>
|
||||
</container>
|
||||
);
|
||||
}, textboxOptions);
|
||||
|
||||
interface TextboxStoreEmits {
|
||||
endType: () => void;
|
||||
hide: () => void;
|
||||
show: () => void;
|
||||
update: (value: TextboxProps) => void;
|
||||
setText: (text: string) => void;
|
||||
}
|
||||
|
||||
interface TextboxStoreEvent {
|
||||
update: [value: TextboxProps];
|
||||
show: [];
|
||||
hide: [];
|
||||
typeStart: [];
|
||||
typeEnd: [];
|
||||
}
|
||||
|
||||
export class TextboxStore extends EventEmitter<TextboxStoreEvent> {
|
||||
static list: Map<string, TextboxStore> = new Map();
|
||||
|
||||
typing: boolean = false;
|
||||
|
||||
private constructor(
|
||||
private readonly data: TextboxProps,
|
||||
private readonly emits: TextboxStoreEmits
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始打字,由组件调用,而非组件外调用
|
||||
*/
|
||||
emitTypeStart() {
|
||||
this.typing = true;
|
||||
this.emit('typeStart');
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束打字,由组件调用,而非组件外调用
|
||||
*/
|
||||
emitTypeEnd() {
|
||||
this.typing = false;
|
||||
this.emit('typeEnd');
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束打字机的打字
|
||||
*/
|
||||
endType() {
|
||||
this.emits.endType();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改渲染数据
|
||||
*/
|
||||
modify(data: Partial<TextboxProps>) {
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
// @ts-expect-error 无法推导
|
||||
if (!isNil(value)) this.data[key] = value;
|
||||
}
|
||||
this.emits.update(this.data);
|
||||
this.emit('update', this.data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置显示的文本
|
||||
* @param text 要显示的文本
|
||||
*/
|
||||
setText(text: string) {
|
||||
this.emits.setText(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示文本框
|
||||
*/
|
||||
show() {
|
||||
this.emits.show();
|
||||
}
|
||||
|
||||
/**
|
||||
* 隐藏文本框
|
||||
*/
|
||||
hide() {
|
||||
this.emits.hide();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文本框
|
||||
* @param id 文本框id
|
||||
*/
|
||||
static get(id: string): TextboxStore | undefined {
|
||||
return this.list.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在当前作用域下生成文本框控制器
|
||||
* @param id 文本框id
|
||||
* @param props 文本框渲染数据
|
||||
*/
|
||||
static use(id: string, props: TextboxProps, emits: TextboxStoreEmits) {
|
||||
const store = new TextboxStore(props, emits);
|
||||
if (this.list.has(id)) {
|
||||
logger.warn(42, id);
|
||||
}
|
||||
this.list.set(id, store);
|
||||
onUnmounted(() => {
|
||||
this.list.delete(id);
|
||||
});
|
||||
return store;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,169 +0,0 @@
|
||||
import { DefaultProps, ElementLocator, Font, texture } from '@motajs/render';
|
||||
import { logger } from '@motajs/common';
|
||||
import { computed, defineComponent, onUnmounted, ref } from 'vue';
|
||||
import { SetupComponentOptions } from './types';
|
||||
import { transitioned } from '../use';
|
||||
import { hyper } from 'mutate-animate';
|
||||
import { debounce } from 'lodash-es';
|
||||
|
||||
export interface TipProps extends DefaultProps {
|
||||
loc: ElementLocator;
|
||||
pad?: [number, number];
|
||||
corner?: number;
|
||||
id?: string;
|
||||
}
|
||||
|
||||
export interface TipExpose {
|
||||
/**
|
||||
* 显示提示文本
|
||||
* @param text 提示文字
|
||||
* @param icon 显示的图标,不填则不显示
|
||||
*/
|
||||
drawTip(text: string, icon?: AllIds | AllNumbers): void;
|
||||
}
|
||||
|
||||
const tipProps = {
|
||||
props: ['loc', 'pad', 'corner', 'id']
|
||||
} satisfies SetupComponentOptions<TipProps>;
|
||||
|
||||
let id = 0;
|
||||
function getNextTipId() {
|
||||
return `@default-tip-${id++}`;
|
||||
}
|
||||
|
||||
export const Tip = defineComponent<TipProps>((props, { expose }) => {
|
||||
const iconNum = ref<AllNumbers>(0);
|
||||
const text = ref<string>('');
|
||||
const textWidth = ref(0);
|
||||
|
||||
const font = new Font('normal');
|
||||
|
||||
const alpha = transitioned(0, 500, hyper('sin', 'in-out'))!;
|
||||
const pad = computed(() => props.pad ?? [4, 4]);
|
||||
const locHeight = computed(() => props.loc[3] ?? 200);
|
||||
const hidden = computed(() => alpha.ref.value === 0);
|
||||
const showIcon = computed(() => iconNum.value !== 0);
|
||||
const iconSize = computed<[number, number]>(() => {
|
||||
const renderable = texture.getRenderable(iconNum.value);
|
||||
if (!renderable) return [1, 1];
|
||||
const [, , width, height] = renderable.render[0];
|
||||
return [width, height];
|
||||
});
|
||||
const iconLoc = computed<ElementLocator>(() => {
|
||||
const [width, height] = iconSize.value;
|
||||
const aspect = width / height;
|
||||
const realHeight = locHeight.value - pad.value[1] * 2;
|
||||
const realWidth = realHeight * aspect;
|
||||
return [pad.value[0], pad.value[1], realWidth, realHeight];
|
||||
});
|
||||
const textLoc = computed<ElementLocator>(() => {
|
||||
if (showIcon.value) {
|
||||
const [, , width] = iconLoc.value;
|
||||
const x = width! + pad.value[0] + pad.value[1];
|
||||
return [x, locHeight.value / 2, void 0, void 0, 0, 0.5];
|
||||
} else {
|
||||
return [pad.value[0], locHeight.value / 2, void 0, void 0, 0, 0.5];
|
||||
}
|
||||
});
|
||||
const containerLoc = computed<ElementLocator>(() => {
|
||||
const [x = 0, y = 0, , height = 200] = props.loc;
|
||||
const iconWidth = iconLoc.value[2] ?? 32;
|
||||
if (showIcon.value) {
|
||||
const width =
|
||||
textWidth.value + iconWidth + pad.value[0] * 2 + pad.value[1];
|
||||
return [x, y, width, height];
|
||||
} else {
|
||||
const width = textWidth.value + pad.value[0] * 2;
|
||||
return [x, y, width, height];
|
||||
}
|
||||
});
|
||||
const rectLoc = computed<ElementLocator>(() => {
|
||||
const [, , width = 200, height = 200] = containerLoc.value;
|
||||
return [1, 1, width - 2, height - 2];
|
||||
});
|
||||
|
||||
const hide = debounce(() => {
|
||||
alpha.set(0);
|
||||
}, 3000);
|
||||
|
||||
const drawTip = (tipText: string, iconId: AllIds | AllNumbers = 0) => {
|
||||
if (typeof iconId === 'string') {
|
||||
const num = texture.idNumberMap[iconId];
|
||||
iconNum.value = num;
|
||||
} else {
|
||||
iconNum.value = iconId;
|
||||
}
|
||||
text.value = core.replaceText(tipText);
|
||||
alpha.set(0, 0);
|
||||
alpha.set(1);
|
||||
hide();
|
||||
};
|
||||
|
||||
const onSetText = (_: string, width: number) => {
|
||||
textWidth.value = width;
|
||||
};
|
||||
|
||||
const ex: TipExpose = { drawTip };
|
||||
|
||||
TipStore.use(props.id ?? getNextTipId(), ex);
|
||||
|
||||
expose<TipExpose>(ex);
|
||||
|
||||
return () => (
|
||||
<container
|
||||
loc={containerLoc.value}
|
||||
alpha={alpha.ref.value}
|
||||
hidden={hidden.value}
|
||||
noevent
|
||||
>
|
||||
<g-rectr
|
||||
loc={rectLoc.value}
|
||||
circle={[props.corner ?? 4]}
|
||||
fill
|
||||
fillStyle="rgba(40,40,40,0.8)"
|
||||
/>
|
||||
<icon
|
||||
hidden={!showIcon.value}
|
||||
icon={iconNum.value}
|
||||
loc={iconLoc.value}
|
||||
/>
|
||||
<text
|
||||
loc={textLoc.value}
|
||||
text={text.value}
|
||||
onSetText={onSetText}
|
||||
font={font}
|
||||
/>
|
||||
</container>
|
||||
);
|
||||
}, tipProps);
|
||||
|
||||
export class TipStore {
|
||||
static list: Map<string, TipStore> = new Map();
|
||||
|
||||
private constructor(private readonly data: TipExpose) {}
|
||||
|
||||
/**
|
||||
* 显示提示文本
|
||||
* @param text 提示文字
|
||||
* @param icon 显示的图标,不填则不显示
|
||||
*/
|
||||
drawTip(text: string, icon: AllIds | AllNumbers = 0) {
|
||||
this.data.drawTip(text, icon);
|
||||
}
|
||||
|
||||
static get(id: string) {
|
||||
return TipStore.list.get(id);
|
||||
}
|
||||
|
||||
static use(id: string, data: TipExpose) {
|
||||
const store = new TipStore(data);
|
||||
if (this.list.has(id)) {
|
||||
logger.warn(60, id);
|
||||
}
|
||||
this.list.set(id, store);
|
||||
onUnmounted(() => {
|
||||
this.list.delete(id);
|
||||
});
|
||||
return store;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { ComponentOptions, EmitsOptions, SlotsType } from 'vue';
|
||||
|
||||
export type SetupComponentOptions<
|
||||
Props extends Record<string, any>,
|
||||
E extends EmitsOptions = {},
|
||||
EE extends string = string,
|
||||
S extends SlotsType = {}
|
||||
> = Pick<ComponentOptions, 'name' | 'inheritAttrs'> & {
|
||||
props?: (keyof Props)[];
|
||||
emits?: E | EE[];
|
||||
slots?: S;
|
||||
};
|
||||
@@ -1,43 +0,0 @@
|
||||
import { MotaRenderer, createApp } from '@motajs/render';
|
||||
import { defineComponent } from 'vue';
|
||||
import { UIController } from '@motajs/system-ui';
|
||||
import { mainSceneUI } from './ui/main';
|
||||
import { MAIN_HEIGHT, MAIN_WIDTH } from './shared';
|
||||
import { TextboxStore } from './components';
|
||||
|
||||
export function create() {
|
||||
const main = new MotaRenderer();
|
||||
main.size(MAIN_WIDTH, MAIN_HEIGHT);
|
||||
|
||||
const App = defineComponent(_props => {
|
||||
const ui = new UIController('root-ui');
|
||||
ui.open(mainSceneUI, {});
|
||||
|
||||
return () => (
|
||||
<container width={MAIN_WIDTH} height={MAIN_HEIGHT}>
|
||||
{ui.render()}
|
||||
</container>
|
||||
);
|
||||
});
|
||||
|
||||
main.hide();
|
||||
createApp(App).mount(main);
|
||||
|
||||
Mota.require('var', 'hook').on('reset', () => {
|
||||
main.show();
|
||||
});
|
||||
|
||||
Mota.require('var', 'hook').on('restart', () => {
|
||||
main.hide();
|
||||
});
|
||||
|
||||
console.log(main);
|
||||
}
|
||||
|
||||
Mota.register('module', 'MainUI', {
|
||||
TextboxStore
|
||||
});
|
||||
|
||||
export * from './components';
|
||||
export * from './ui';
|
||||
export * from './use';
|
||||
@@ -1,10 +0,0 @@
|
||||
export const STATUS_BAR_WIDTH = 180;
|
||||
export const STATUS_BAR_HEIGHT = 480;
|
||||
|
||||
export const ENABLE_RIGHT_STATUS_BAR = true;
|
||||
|
||||
export const MAP_WIDTH = 480;
|
||||
export const MAP_HEIGHT = 480;
|
||||
|
||||
export const MAIN_WIDTH = 480 + 180 * 2;
|
||||
export const MAIN_HEIGHT = 480;
|
||||
@@ -1,2 +0,0 @@
|
||||
export * from './main';
|
||||
export * from './statusBar';
|
||||
@@ -1,238 +0,0 @@
|
||||
import { LayerShadowExtends } from '@/core/fx/shadow';
|
||||
import {
|
||||
ILayerGroupRenderExtends,
|
||||
FloorDamageExtends,
|
||||
LayerGroupAnimate,
|
||||
FloorViewport,
|
||||
ILayerRenderExtends,
|
||||
HeroRenderer,
|
||||
LayerDoorAnimate,
|
||||
Props,
|
||||
LayerGroup,
|
||||
Font
|
||||
} from '@motajs/render';
|
||||
import { WeatherController } from '@/module/weather';
|
||||
import { FloorChange } from '@/plugin/fallback';
|
||||
import { LayerGroupFilter } from '@/plugin/fx/gameCanvas';
|
||||
import { LayerGroupHalo } from '@/plugin/fx/halo';
|
||||
import { FloorItemDetail } from '@/plugin/fx/itemDetail';
|
||||
import { PopText } from '@/plugin/fx/pop';
|
||||
import { LayerGroupPortal } from '@/plugin/fx/portal';
|
||||
import { defineComponent, onMounted, reactive, ref } from 'vue';
|
||||
import { Textbox, Tip } from '../components';
|
||||
import { GameUI, UIController } from '@motajs/system-ui';
|
||||
import {
|
||||
MAIN_HEIGHT,
|
||||
MAIN_WIDTH,
|
||||
STATUS_BAR_HEIGHT,
|
||||
STATUS_BAR_WIDTH
|
||||
} from '../shared';
|
||||
import {
|
||||
ILeftHeroStatus,
|
||||
IRightHeroStatus,
|
||||
LeftStatusBar,
|
||||
RightStatusBar
|
||||
} from './statusBar';
|
||||
import { onLoaded } from '../use';
|
||||
import { ReplayingStatus } from './toolbar';
|
||||
|
||||
const MainScene = defineComponent(() => {
|
||||
const layerGroupExtends: ILayerGroupRenderExtends[] = [
|
||||
new FloorDamageExtends(),
|
||||
new FloorItemDetail(),
|
||||
new LayerGroupFilter(),
|
||||
new LayerGroupPortal(),
|
||||
new LayerGroupHalo(),
|
||||
new LayerGroupAnimate(),
|
||||
new FloorViewport()
|
||||
];
|
||||
const eventExtends: ILayerRenderExtends[] = [
|
||||
new HeroRenderer(),
|
||||
new LayerDoorAnimate(),
|
||||
new LayerShadowExtends()
|
||||
];
|
||||
const mapDrawProps: Props<'container'> = {
|
||||
width: core._PX_,
|
||||
height: core._PY_
|
||||
};
|
||||
const mainTextboxProps: Props<typeof Textbox> = {
|
||||
text: '',
|
||||
hidden: true,
|
||||
loc: [0, 330, 480, 150],
|
||||
zIndex: 30,
|
||||
fillStyle: '#fff',
|
||||
titleFill: 'gold',
|
||||
font: new Font('normal'),
|
||||
titleFont: new Font('normal', 20, 'px', 700),
|
||||
winskin: 'winskin2.png',
|
||||
interval: 100,
|
||||
lineHeight: 4,
|
||||
width: 480
|
||||
};
|
||||
|
||||
const map = ref<LayerGroup>();
|
||||
const hideStatus = ref(false);
|
||||
const weather = new WeatherController('main');
|
||||
|
||||
onMounted(() => {
|
||||
weather.bind(map.value);
|
||||
});
|
||||
|
||||
const leftStatus: ILeftHeroStatus = reactive({
|
||||
hp: 0,
|
||||
atk: 0,
|
||||
def: 0,
|
||||
mdef: 0,
|
||||
money: 0,
|
||||
exp: 0,
|
||||
yellowKey: 0,
|
||||
blueKey: 0,
|
||||
redKey: 0,
|
||||
floor: 'MT0',
|
||||
lv: '',
|
||||
regen: 0,
|
||||
exAtk: 0,
|
||||
magicDef: 0
|
||||
});
|
||||
const replayStatus: ReplayingStatus = reactive({
|
||||
playing: false,
|
||||
speed: 1,
|
||||
played: 0,
|
||||
total: 0
|
||||
});
|
||||
const rightStatus: IRightHeroStatus = reactive({
|
||||
autoSkill: false,
|
||||
skillName: '',
|
||||
skillDesc: '',
|
||||
jumpCount: 0,
|
||||
springCount: 0,
|
||||
floor: 'MT0',
|
||||
replaying: false,
|
||||
replayStatus,
|
||||
night: 0
|
||||
});
|
||||
|
||||
const { getHeroStatusOn } = Mota.requireAll('fn');
|
||||
|
||||
const updateStatus = () => {
|
||||
if (!core.status || !core.status.hero || !core.status.floorId) return;
|
||||
hideStatus.value = core.getFlag('hideStatusBar', false);
|
||||
|
||||
const hero = core.status.hero;
|
||||
const floor = core.status.floorId;
|
||||
leftStatus.atk = getHeroStatusOn('atk');
|
||||
leftStatus.hp = getHeroStatusOn('hp');
|
||||
leftStatus.def = getHeroStatusOn('def');
|
||||
leftStatus.mdef = getHeroStatusOn('mdef');
|
||||
leftStatus.money = getHeroStatusOn('money');
|
||||
leftStatus.exp = core.getNextLvUpNeed() ?? 0;
|
||||
leftStatus.yellowKey = core.itemCount('yellowKey');
|
||||
leftStatus.blueKey = core.itemCount('blueKey');
|
||||
leftStatus.redKey = core.itemCount('redKey');
|
||||
leftStatus.floor = core.status.floorId;
|
||||
leftStatus.lv = core.getLvName(hero.lv);
|
||||
leftStatus.regen = getHeroStatusOn('hpmax');
|
||||
leftStatus.exAtk = getHeroStatusOn('mana');
|
||||
leftStatus.magicDef = getHeroStatusOn('magicDef');
|
||||
|
||||
const { HeroSkill, NightSpecial } = Mota.require('module', 'Mechanism');
|
||||
rightStatus.autoSkill = HeroSkill.getAutoSkill();
|
||||
rightStatus.skillName = HeroSkill.getSkillName();
|
||||
rightStatus.skillDesc = HeroSkill.getSkillDesc();
|
||||
rightStatus.night = NightSpecial.getNight(floor);
|
||||
rightStatus.floor = floor;
|
||||
rightStatus.replaying = core.isReplaying();
|
||||
const { pausing, speed, toReplay, totalList } = core.status.replay;
|
||||
replayStatus.playing = !pausing;
|
||||
replayStatus.speed = speed;
|
||||
replayStatus.played = totalList.length - toReplay.length;
|
||||
replayStatus.total = totalList.length;
|
||||
if (HeroSkill.learnedSkill(HeroSkill.Jump)) {
|
||||
if (Mota.Plugin.require('skill_g').jumpIgnoreFloor.has(floor)) {
|
||||
rightStatus.jumpCount = -2;
|
||||
} else {
|
||||
rightStatus.jumpCount = 3 - (flags[`jump_${floor}`] ?? 0);
|
||||
}
|
||||
} else {
|
||||
rightStatus.jumpCount = -1;
|
||||
}
|
||||
if (core.hasFlag('spring')) {
|
||||
rightStatus.springCount = 50 - (flags.springCount ?? 0);
|
||||
} else {
|
||||
rightStatus.springCount = -1;
|
||||
}
|
||||
};
|
||||
|
||||
const loaded = ref(false);
|
||||
onLoaded(() => {
|
||||
loaded.value = true;
|
||||
});
|
||||
|
||||
Mota.require('var', 'hook').on('statusBarUpdate', updateStatus);
|
||||
|
||||
return () => (
|
||||
<container id="main-scene" width={MAIN_WIDTH} height={MAIN_HEIGHT}>
|
||||
{loaded.value && (
|
||||
<LeftStatusBar
|
||||
loc={[0, 0, STATUS_BAR_WIDTH, STATUS_BAR_HEIGHT]}
|
||||
status={leftStatus}
|
||||
hidden={hideStatus.value}
|
||||
></LeftStatusBar>
|
||||
)}
|
||||
<g-line line={[180, 0, 180, 480]} lineWidth={1} />
|
||||
<container id="map-draw" {...mapDrawProps} x={180} zIndex={10}>
|
||||
<layer-group id="layer-main" ex={layerGroupExtends} ref={map}>
|
||||
<layer layer="bg" zIndex={10}></layer>
|
||||
<layer layer="bg2" zIndex={20}></layer>
|
||||
<layer layer="event" zIndex={30} ex={eventExtends}></layer>
|
||||
<layer layer="fg" zIndex={40}></layer>
|
||||
<layer layer="fg2" zIndex={50}></layer>
|
||||
<PopText id="pop-main" zIndex={80}></PopText>
|
||||
</layer-group>
|
||||
<Textbox id="main-textbox" {...mainTextboxProps}></Textbox>
|
||||
<FloorChange id="floor-change" zIndex={50}></FloorChange>
|
||||
<Tip
|
||||
id="main-tip"
|
||||
zIndex={80}
|
||||
loc={[8, 8, 200, 32]}
|
||||
pad={[12, 6]}
|
||||
corner={16}
|
||||
/>
|
||||
</container>
|
||||
<g-line line={[180 + 480, 0, 180 + 480, 480]} lineWidth={1} />
|
||||
{loaded.value && (
|
||||
<RightStatusBar
|
||||
loc={[480 + 180, 0, STATUS_BAR_WIDTH, STATUS_BAR_HEIGHT]}
|
||||
status={rightStatus}
|
||||
hidden={hideStatus.value}
|
||||
></RightStatusBar>
|
||||
)}
|
||||
<container
|
||||
loc={[0, 0, MAIN_WIDTH, MAIN_HEIGHT]}
|
||||
hidden={mainUIController.showBack.value}
|
||||
>
|
||||
{mainUIController.render()}
|
||||
</container>
|
||||
<g-rect
|
||||
loc={[0, 0, MAIN_WIDTH, MAIN_HEIGHT]}
|
||||
hidden={hideStatus.value}
|
||||
zIndex={100}
|
||||
stroke
|
||||
noevent
|
||||
></g-rect>
|
||||
<g-line
|
||||
line={[180, 0, 480 + 180, 0]}
|
||||
hidden={!hideStatus.value}
|
||||
zIndex={100}
|
||||
/>
|
||||
<g-line
|
||||
line={[180, 480, 480 + 180, 480]}
|
||||
hidden={!hideStatus.value}
|
||||
zIndex={100}
|
||||
/>
|
||||
</container>
|
||||
);
|
||||
});
|
||||
|
||||
export const mainSceneUI = new GameUI('main-scene', MainScene);
|
||||
export const mainUIController = new UIController('main-ui');
|
||||
@@ -1,579 +0,0 @@
|
||||
import { ElementLocator } from '@motajs/render';
|
||||
import { GameUI, UIComponentProps } from '@motajs/system-ui';
|
||||
import { defineComponent } from 'vue';
|
||||
import {
|
||||
ChoiceItem,
|
||||
ChoiceKey,
|
||||
Choices,
|
||||
ChoicesProps,
|
||||
getConfirm,
|
||||
SetupComponentOptions,
|
||||
waitbox
|
||||
} from '../components';
|
||||
import { mainUi } from '@motajs/legacy-ui';
|
||||
import { gameKey } from '@motajs/system-action';
|
||||
import { generateKeyboardEvent } from '@motajs/system-action';
|
||||
import { getVitualKeyOnce } from '@motajs/legacy-ui';
|
||||
import { getAllSavesData, getSaveData } from '@/module/utils';
|
||||
|
||||
export interface SettingsProps extends Partial<ChoicesProps>, UIComponentProps {
|
||||
loc: ElementLocator;
|
||||
}
|
||||
|
||||
const settingsProps = {
|
||||
props: ['loc', 'controller', 'instance']
|
||||
} satisfies SetupComponentOptions<SettingsProps>;
|
||||
|
||||
const enum MainChoice {
|
||||
SystemSetting,
|
||||
VirtualKey,
|
||||
ViewMap,
|
||||
/** @see {@link ReplaySettings} */
|
||||
Replay,
|
||||
/** @see {@link SyncSave} */
|
||||
SyncSave,
|
||||
/** @see {@link GameInfo} */
|
||||
GameInfo,
|
||||
Restart,
|
||||
Back
|
||||
}
|
||||
|
||||
export const MainSettings = defineComponent<SettingsProps>(props => {
|
||||
const choices: ChoiceItem[] = [
|
||||
[MainChoice.SystemSetting, '系统设置'],
|
||||
[MainChoice.VirtualKey, '虚拟键盘'],
|
||||
[MainChoice.ViewMap, '浏览地图'],
|
||||
[MainChoice.Replay, '录像回放'],
|
||||
[MainChoice.SyncSave, '同步存档'],
|
||||
[MainChoice.GameInfo, '游戏信息'],
|
||||
[MainChoice.Restart, '返回标题'],
|
||||
[MainChoice.Back, '返回游戏']
|
||||
];
|
||||
|
||||
const choose = (key: ChoiceKey) => {
|
||||
switch (key) {
|
||||
case MainChoice.SystemSetting: {
|
||||
mainUi.open('settings');
|
||||
break;
|
||||
}
|
||||
case MainChoice.VirtualKey: {
|
||||
getVitualKeyOnce().then(value => {
|
||||
gameKey.emitKey(
|
||||
value.key,
|
||||
value.assist,
|
||||
'up',
|
||||
generateKeyboardEvent(value.key, value.assist)
|
||||
);
|
||||
});
|
||||
break;
|
||||
}
|
||||
case MainChoice.ViewMap: {
|
||||
// todo
|
||||
break;
|
||||
}
|
||||
case MainChoice.Replay: {
|
||||
props.controller.open(ReplaySettingsUI, { loc: props.loc });
|
||||
break;
|
||||
}
|
||||
case MainChoice.SyncSave: {
|
||||
props.controller.open(SyncSaveUI, { loc: props.loc });
|
||||
break;
|
||||
}
|
||||
case MainChoice.GameInfo: {
|
||||
props.controller.open(GameInfoUI, { loc: props.loc });
|
||||
break;
|
||||
}
|
||||
case MainChoice.Restart: {
|
||||
props.controller.closeAll();
|
||||
core.restart();
|
||||
break;
|
||||
}
|
||||
case MainChoice.Back: {
|
||||
props.controller.close(props.instance);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return () => (
|
||||
<Choices
|
||||
loc={props.loc}
|
||||
choices={choices}
|
||||
width={240}
|
||||
onChoose={choose}
|
||||
/>
|
||||
);
|
||||
}, settingsProps);
|
||||
|
||||
const enum ReplayChoice {
|
||||
Start,
|
||||
StartFromSave,
|
||||
ResumeReplay,
|
||||
ReplayRest,
|
||||
ChooseReplay,
|
||||
Download,
|
||||
Back
|
||||
}
|
||||
|
||||
export const ReplaySettings = defineComponent<SettingsProps>(props => {
|
||||
const choice: ChoiceItem[] = [
|
||||
[ReplayChoice.Start, '从头回放录像'],
|
||||
[ReplayChoice.StartFromSave, '从存档开始回放'],
|
||||
[ReplayChoice.ResumeReplay, '接续播放剩余录像'],
|
||||
[ReplayChoice.ReplayRest, '播放存档剩余录像'],
|
||||
[ReplayChoice.ChooseReplay, '选择录像文件'],
|
||||
[ReplayChoice.Download, '下载当前录像'],
|
||||
[ReplayChoice.Back, '返回游戏']
|
||||
];
|
||||
|
||||
const choose = (key: ChoiceKey) => {
|
||||
switch (key) {
|
||||
case ReplayChoice.Start: {
|
||||
props.controller.closeAll();
|
||||
core.ui.closePanel();
|
||||
const route = core.status.route.slice();
|
||||
const seed = core.getFlag<number>('__seed__');
|
||||
core.startGame(core.status.hard, seed, route);
|
||||
break;
|
||||
}
|
||||
case ReplayChoice.StartFromSave: {
|
||||
// todo
|
||||
break;
|
||||
}
|
||||
case ReplayChoice.ResumeReplay: {
|
||||
// todo
|
||||
break;
|
||||
}
|
||||
case ReplayChoice.ReplayRest: {
|
||||
// todo
|
||||
break;
|
||||
}
|
||||
case ReplayChoice.ChooseReplay: {
|
||||
props.controller.closeAll();
|
||||
core.chooseReplayFile();
|
||||
break;
|
||||
}
|
||||
case ReplayChoice.Download: {
|
||||
core.download(
|
||||
core.firstData.name + '_' + core.formatDate2() + '.h5route',
|
||||
// @ts-expect-error 暂时无法推导
|
||||
LZString.compressToBase64(
|
||||
JSON.stringify({
|
||||
name: core.firstData.name,
|
||||
hard: core.status.hard,
|
||||
seed: core.getFlag('__seed__'),
|
||||
route: core.encodeRoute(core.status.route)
|
||||
})
|
||||
)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case ReplayChoice.Back: {
|
||||
props.controller.close(props.instance);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return () => (
|
||||
<Choices
|
||||
loc={props.loc}
|
||||
choices={choice}
|
||||
width={240}
|
||||
onChoose={choose}
|
||||
/>
|
||||
);
|
||||
}, settingsProps);
|
||||
|
||||
const enum GameInfoChoice {
|
||||
Statistics,
|
||||
Project,
|
||||
Tower,
|
||||
Help,
|
||||
Download,
|
||||
Back
|
||||
}
|
||||
|
||||
export const GameInfo = defineComponent<SettingsProps>(props => {
|
||||
const choices: ChoiceItem[] = [
|
||||
[GameInfoChoice.Statistics, '数据统计'],
|
||||
[GameInfoChoice.Project, '查看工程'],
|
||||
[GameInfoChoice.Tower, '游戏主页'],
|
||||
[GameInfoChoice.Help, '操作帮助'],
|
||||
[GameInfoChoice.Download, '下载离线版本'],
|
||||
[GameInfoChoice.Back, '返回主菜单']
|
||||
];
|
||||
|
||||
const choose = async (key: ChoiceKey) => {
|
||||
switch (key) {
|
||||
case GameInfoChoice.Statistics: {
|
||||
// todo
|
||||
break;
|
||||
}
|
||||
case GameInfoChoice.Project: {
|
||||
if (core.platform.isPC) window.open('editor.html', '_blank');
|
||||
else {
|
||||
const confirm = await getConfirm(
|
||||
props.controller,
|
||||
'即将离开本游戏,跳转至工程页面,确认跳转?',
|
||||
props.loc,
|
||||
240
|
||||
);
|
||||
if (confirm) {
|
||||
window.location.href = 'editor-mobile.html';
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case GameInfoChoice.Tower: {
|
||||
const name = core.firstData.name;
|
||||
const href = `/tower/?name=${name}`;
|
||||
if (core.platform.isPC) {
|
||||
window.open(href, '_blank');
|
||||
} else {
|
||||
const confirm = await getConfirm(
|
||||
props.controller,
|
||||
'即将离开本游戏,跳转至评论页面,确认跳转?',
|
||||
props.loc,
|
||||
240
|
||||
);
|
||||
if (confirm) {
|
||||
window.location.href = href;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case GameInfoChoice.Download: {
|
||||
const name = core.firstData.name;
|
||||
const href = `/games/${name}/${name}.zip`;
|
||||
if (core.platform.isPC) window.open(href);
|
||||
else window.location.href = href;
|
||||
break;
|
||||
}
|
||||
case GameInfoChoice.Help: {
|
||||
// todo
|
||||
break;
|
||||
}
|
||||
case GameInfoChoice.Back: {
|
||||
props.controller.close(props.instance);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return () => (
|
||||
<Choices
|
||||
loc={props.loc}
|
||||
choices={choices}
|
||||
width={240}
|
||||
onChoose={choose}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
const enum SyncSaveChoice {
|
||||
// ----- 主菜单
|
||||
ToServer,
|
||||
FromServer,
|
||||
ToLocal,
|
||||
FromLocal,
|
||||
ClearLocal,
|
||||
Back,
|
||||
// ----- 子菜单
|
||||
AllSaves,
|
||||
NowSave
|
||||
}
|
||||
|
||||
export const SyncSave = defineComponent<SettingsProps>(props => {
|
||||
const choices: ChoiceItem[] = [
|
||||
[SyncSaveChoice.ToServer, '同步存档至服务器'],
|
||||
[SyncSaveChoice.FromServer, '从服务器加载存档'],
|
||||
[SyncSaveChoice.ToLocal, '存档至本地文件'],
|
||||
[SyncSaveChoice.FromLocal, '存本地文件读档'],
|
||||
[SyncSaveChoice.ClearLocal, '清空本地存档'],
|
||||
[SyncSaveChoice.Back, '返回上一级']
|
||||
];
|
||||
|
||||
const choose = (key: ChoiceKey) => {
|
||||
switch (key) {
|
||||
case SyncSaveChoice.ToServer: {
|
||||
props.controller.open(SyncSaveSelectUI, { loc: props.loc });
|
||||
break;
|
||||
}
|
||||
case SyncSaveChoice.FromServer: {
|
||||
// todo
|
||||
break;
|
||||
}
|
||||
case SyncSaveChoice.ToLocal: {
|
||||
props.controller.open(DownloadSaveSelectUI, { loc: props.loc });
|
||||
break;
|
||||
}
|
||||
case SyncSaveChoice.FromLocal: {
|
||||
// todo
|
||||
break;
|
||||
}
|
||||
case SyncSaveChoice.ClearLocal: {
|
||||
props.controller.open(ClearSaveSelectUI, { loc: props.loc });
|
||||
break;
|
||||
}
|
||||
case SyncSaveChoice.Back: {
|
||||
props.controller.close(props.instance);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return () => (
|
||||
<Choices
|
||||
loc={props.loc}
|
||||
width={240}
|
||||
choices={choices}
|
||||
onChoose={choose}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
export const SyncSaveSelect = defineComponent<SettingsProps>(props => {
|
||||
const choices: ChoiceItem[] = [
|
||||
[SyncSaveChoice.AllSaves, '同步全部存档'],
|
||||
[SyncSaveChoice.NowSave, '同步当前存档'],
|
||||
[SyncSaveChoice.Back, '返回上一级']
|
||||
];
|
||||
|
||||
const choose = async (key: ChoiceKey) => {
|
||||
switch (key) {
|
||||
case SyncSaveChoice.AllSaves: {
|
||||
core.playSound('confirm.opus');
|
||||
const confirm = await getConfirm(
|
||||
props.controller,
|
||||
'你确定要同步全部存档么?这可能在存档较多的时候比较慢。',
|
||||
props.loc,
|
||||
240
|
||||
);
|
||||
if (confirm) {
|
||||
core.syncSave('all');
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SyncSaveChoice.NowSave: {
|
||||
core.playSound('confirm.opus');
|
||||
const confirm = await getConfirm(
|
||||
props.controller,
|
||||
'确定要同步当前存档吗?',
|
||||
props.loc,
|
||||
240
|
||||
);
|
||||
if (confirm) {
|
||||
core.syncSave();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SyncSaveChoice.Back: {
|
||||
props.controller.close(props.instance);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return () => (
|
||||
<Choices
|
||||
loc={props.loc}
|
||||
width={240}
|
||||
choices={choices}
|
||||
onChoose={choose}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
export const DownloadSaveSelect = defineComponent<SettingsProps>(props => {
|
||||
const choices: ChoiceItem[] = [
|
||||
[SyncSaveChoice.AllSaves, '下载全部存档'],
|
||||
[SyncSaveChoice.NowSave, '下载当前存档'],
|
||||
[SyncSaveChoice.Back, '返回上一级']
|
||||
];
|
||||
|
||||
const choose = async (key: ChoiceKey) => {
|
||||
switch (key) {
|
||||
case SyncSaveChoice.AllSaves: {
|
||||
const confirm = await getConfirm(
|
||||
props.controller,
|
||||
'确认要下载所有存档吗?',
|
||||
props.loc,
|
||||
240
|
||||
);
|
||||
if (confirm) {
|
||||
const data = await waitbox(
|
||||
props.controller,
|
||||
props.loc,
|
||||
240,
|
||||
getAllSavesData(),
|
||||
{ text: '请等待处理完毕' }
|
||||
);
|
||||
core.download(
|
||||
`${core.firstData.name}_${core.formatDate2(new Date())}.h5save`,
|
||||
data
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SyncSaveChoice.NowSave: {
|
||||
const confirm = await getConfirm(
|
||||
props.controller,
|
||||
'确认要下载当前存档吗?',
|
||||
props.loc,
|
||||
240
|
||||
);
|
||||
if (confirm) {
|
||||
const data = await getSaveData(core.saves.saveIndex);
|
||||
core.download(
|
||||
`${core.firstData.name}_${core.formatDate2(new Date())}.h5save`,
|
||||
data
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SyncSaveChoice.Back: {
|
||||
props.controller.close(props.instance);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return () => (
|
||||
<Choices
|
||||
loc={props.loc}
|
||||
width={240}
|
||||
choices={choices}
|
||||
onChoose={choose}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
export const ClearSaveSelect = defineComponent<SettingsProps>(props => {
|
||||
const choices: ChoiceItem[] = [
|
||||
[SyncSaveChoice.AllSaves, '清空全部塔存档'],
|
||||
[SyncSaveChoice.NowSave, '清空当前塔存档'],
|
||||
[SyncSaveChoice.Back, '返回上一级']
|
||||
];
|
||||
|
||||
const choose = async (key: ChoiceKey) => {
|
||||
switch (key) {
|
||||
case SyncSaveChoice.AllSaves: {
|
||||
const confirm = await getConfirm(
|
||||
props.controller,
|
||||
'你确定要清除【全部游戏】的所有本地存档?此行为不可逆!!!',
|
||||
props.loc,
|
||||
240
|
||||
);
|
||||
if (confirm) {
|
||||
await waitbox(
|
||||
props.controller,
|
||||
props.loc,
|
||||
240,
|
||||
new Promise<void>(res => {
|
||||
core.clearLocalForage(() => {
|
||||
core.saves.ids = {};
|
||||
core.saves.autosave.data = null;
|
||||
core.saves.autosave.updated = false;
|
||||
core.saves.autosave.now = 0;
|
||||
// @ts-expect-error 沙比样板
|
||||
core.saves.cache = {};
|
||||
core.saves.saveIndex = 1;
|
||||
core.saves.favorite = [];
|
||||
core.saves.favoriteName = {};
|
||||
// @ts-expect-error 沙比样板
|
||||
core.control._updateFavoriteSaves();
|
||||
core.removeLocalStorage('saveIndex');
|
||||
res();
|
||||
});
|
||||
}),
|
||||
{ text: '正在情况,请稍后...' }
|
||||
);
|
||||
await getConfirm(
|
||||
props.controller,
|
||||
'所有塔的存档已经全部清空',
|
||||
props.loc,
|
||||
240
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SyncSaveChoice.NowSave: {
|
||||
const confirm = await getConfirm(
|
||||
props.controller,
|
||||
'你确定要清除【当前游戏】的所有本地存档?此行为不可逆!!!',
|
||||
props.loc,
|
||||
240
|
||||
);
|
||||
if (confirm) {
|
||||
await waitbox(
|
||||
props.controller,
|
||||
props.loc,
|
||||
240,
|
||||
new Promise<void>(res => {
|
||||
Object.keys(core.saves.ids).forEach(function (v) {
|
||||
core.removeLocalForage('save' + v);
|
||||
});
|
||||
core.removeLocalForage('autoSave', () => {
|
||||
core.saves.ids = {};
|
||||
core.saves.autosave.data = null;
|
||||
core.saves.autosave.updated = false;
|
||||
core.saves.autosave.now = 0;
|
||||
core.ui.closePanel();
|
||||
core.saves.saveIndex = 1;
|
||||
core.saves.favorite = [];
|
||||
core.saves.favoriteName = {};
|
||||
// @ts-expect-error 沙比样板
|
||||
core.control._updateFavoriteSaves();
|
||||
core.removeLocalStorage('saveIndex');
|
||||
res();
|
||||
});
|
||||
}),
|
||||
{ text: '正在情况,请稍后...' }
|
||||
);
|
||||
await getConfirm(
|
||||
props.controller,
|
||||
'当前塔的存档已被清空',
|
||||
props.loc,
|
||||
240
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case SyncSaveChoice.Back: {
|
||||
props.controller.close(props.instance);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return () => (
|
||||
<Choices
|
||||
loc={props.loc}
|
||||
width={240}
|
||||
choices={choices}
|
||||
onChoose={choose}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
/** @see {@link MainSettings} */
|
||||
export const MainSettingsUI = new GameUI('main-settings', MainSettings);
|
||||
/** @see {@link ReplaySettings} */
|
||||
export const ReplaySettingsUI = new GameUI('replay-settings', ReplaySettings);
|
||||
/** @see {@link GameInfo} */
|
||||
export const GameInfoUI = new GameUI('game-info', GameInfo);
|
||||
/** @see {@link SyncSave} */
|
||||
export const SyncSaveUI = new GameUI('sync-save', SyncSave);
|
||||
/** @see {@link SyncSaveSelect} */
|
||||
export const SyncSaveSelectUI = new GameUI('sync-save-select', SyncSaveSelect);
|
||||
/** @see {@link DownloadSaveSelect} */
|
||||
export const DownloadSaveSelectUI = new GameUI(
|
||||
'download-save-select',
|
||||
DownloadSaveSelect
|
||||
);
|
||||
/** @see {@link ClearSaveSelect} */
|
||||
export const ClearSaveSelectUI = new GameUI(
|
||||
'clear-save-select',
|
||||
ClearSaveSelect
|
||||
);
|
||||
@@ -1,419 +0,0 @@
|
||||
import { GameUI, UIComponentProps } from '@motajs/system-ui';
|
||||
import { computed, defineComponent, ref, watch } from 'vue';
|
||||
import { SetupComponentOptions, TextContent } from '../components';
|
||||
import {
|
||||
DefaultProps,
|
||||
ElementLocator,
|
||||
Sprite,
|
||||
Font,
|
||||
MotaOffscreenCanvas2D
|
||||
} from '@motajs/render';
|
||||
import { transitionedColor } from '../use';
|
||||
import { linear } from 'mutate-animate';
|
||||
import { Scroll } from '../components/scroll';
|
||||
import { getArea, MinimapDrawer } from '@motajs/legacy-ui';
|
||||
import {
|
||||
NumpadToolbar,
|
||||
PlayingToolbar,
|
||||
ReplayingStatus,
|
||||
ReplayingToolbar
|
||||
} from './toolbar';
|
||||
|
||||
export interface ILeftHeroStatus {
|
||||
hp: number;
|
||||
atk: number;
|
||||
def: number;
|
||||
mdef: number;
|
||||
money: number;
|
||||
exp: number;
|
||||
yellowKey: number;
|
||||
blueKey: number;
|
||||
redKey: number;
|
||||
floor: FloorIds;
|
||||
lv: string;
|
||||
/** 生命回复 */
|
||||
regen: number;
|
||||
/** 额外攻击 */
|
||||
exAtk: number;
|
||||
/** 魔法防御 */
|
||||
magicDef: number;
|
||||
}
|
||||
|
||||
interface StatusBarProps<T> extends DefaultProps, UIComponentProps {
|
||||
loc: ElementLocator;
|
||||
status: T;
|
||||
hidden: boolean;
|
||||
}
|
||||
|
||||
const statusBarProps = {
|
||||
props: ['loc', 'status', 'hidden']
|
||||
} satisfies SetupComponentOptions<StatusBarProps<unknown>>;
|
||||
|
||||
export const LeftStatusBar = defineComponent<StatusBarProps<ILeftHeroStatus>>(
|
||||
p => {
|
||||
const hpIcon = core.material.images.images['hp.png'];
|
||||
const atkIcon = core.material.images.images['atk.png'];
|
||||
const defIcon = core.material.images.images['def.png'];
|
||||
const mdefIcon = core.material.images.images['IQ.png'];
|
||||
const moneyIcon = core.material.images.images['money.png'];
|
||||
const expIcon = core.material.images.images['exp.png'];
|
||||
|
||||
const s = p.status;
|
||||
const f = core.formatBigNumber;
|
||||
|
||||
const floorName = computed(() => core.floors[s.floor]?.title ?? '');
|
||||
|
||||
const key = (num: number) => {
|
||||
return num.toString().padStart(2, '0');
|
||||
};
|
||||
|
||||
const font1 = new Font('normal', 18);
|
||||
const font2 = new Font('normal', 18, 'px', 700);
|
||||
const font3 = new Font('normal', 14, 'px', 700);
|
||||
|
||||
const iconLoc = (n: number): ElementLocator => {
|
||||
return [16, 76 + 44 * n, 32, 32];
|
||||
};
|
||||
|
||||
const textLoc = (n: number): ElementLocator => {
|
||||
return [60, 92 + 44 * n, void 0, void 0, 0, 0.5];
|
||||
};
|
||||
|
||||
const central = (y: number): ElementLocator => {
|
||||
const width = p.loc[2] ?? 200;
|
||||
return [width / 2, y, void 0, void 0, 0.5, 0.5];
|
||||
};
|
||||
|
||||
const right = (y: number): ElementLocator => {
|
||||
const width = p.loc[2] ?? 200;
|
||||
return [width - 16, y, void 0, void 0, 1, 0.5];
|
||||
};
|
||||
|
||||
const keyCount = 3;
|
||||
const keyY = 92 + 44 * 6;
|
||||
const keyLoc = (n: number): ElementLocator => {
|
||||
const width = p.loc[2] ?? 200;
|
||||
const per = width / (keyCount + 1);
|
||||
return [per * (n + 1), keyY, void 0, void 0, 0.5, 0.5];
|
||||
};
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<container loc={p.loc} hidden={p.hidden}>
|
||||
<text
|
||||
text={floorName.value}
|
||||
loc={central(24)}
|
||||
font={font1}
|
||||
cursor="pointer"
|
||||
></text>
|
||||
<text text={s.lv} loc={central(54)} font={font1}></text>
|
||||
<image image={hpIcon} loc={iconLoc(0)}></image>
|
||||
<text text={f(s.hp)} loc={textLoc(0)} font={font1}></text>
|
||||
<text
|
||||
text={`+${f(s.regen)}/t`}
|
||||
loc={right(110)}
|
||||
font={font3}
|
||||
fillStyle="#a7ffa7"
|
||||
></text>
|
||||
<image image={atkIcon} loc={iconLoc(1)}></image>
|
||||
<text text={f(s.atk)} loc={textLoc(1)} font={font1}></text>
|
||||
<text
|
||||
text={`+${f(s.exAtk)}`}
|
||||
loc={right(154)}
|
||||
font={font3}
|
||||
fillStyle="#ffd3d3"
|
||||
></text>
|
||||
<image image={defIcon} loc={iconLoc(2)}></image>
|
||||
<text text={f(s.def)} loc={textLoc(2)} font={font1}></text>
|
||||
{s.magicDef > 0 && (
|
||||
<text
|
||||
text={`+${f(s.magicDef)}`}
|
||||
loc={right(198)}
|
||||
font={font3}
|
||||
fillStyle="#b0bdff"
|
||||
></text>
|
||||
)}
|
||||
<image image={mdefIcon} loc={iconLoc(3)}></image>
|
||||
<text text={f(s.mdef)} loc={textLoc(3)} font={font1}></text>
|
||||
<image image={moneyIcon} loc={iconLoc(4)}></image>
|
||||
<text text={f(s.money)} loc={textLoc(4)} font={font1} />
|
||||
<image image={expIcon} loc={iconLoc(5)}></image>
|
||||
<text text={f(s.exp)} loc={textLoc(5)} font={font1}></text>
|
||||
<text
|
||||
text={key(s.yellowKey)}
|
||||
loc={keyLoc(0)}
|
||||
font={font2}
|
||||
fillStyle="#fca"
|
||||
></text>
|
||||
<text
|
||||
text={key(s.blueKey)}
|
||||
loc={keyLoc(1)}
|
||||
font={font2}
|
||||
fillStyle="#aad"
|
||||
></text>
|
||||
<text
|
||||
text={key(s.redKey)}
|
||||
loc={keyLoc(2)}
|
||||
font={font2}
|
||||
fillStyle="#f88"
|
||||
></text>
|
||||
<text
|
||||
text="技能树"
|
||||
loc={central(396)}
|
||||
font={font1}
|
||||
cursor="pointer"
|
||||
></text>
|
||||
<text
|
||||
text="查看技能"
|
||||
loc={central(428)}
|
||||
font={font1}
|
||||
cursor="pointer"
|
||||
></text>
|
||||
</container>
|
||||
);
|
||||
};
|
||||
},
|
||||
statusBarProps
|
||||
);
|
||||
|
||||
interface RightStatusBarMisc {
|
||||
name: string;
|
||||
value: string;
|
||||
nameColor: string;
|
||||
valueColor: string;
|
||||
}
|
||||
|
||||
export interface IRightHeroStatus {
|
||||
/** 自动切换技能 */
|
||||
autoSkill: boolean;
|
||||
/** 当前开启的技能 */
|
||||
skillName: string;
|
||||
/** 技能描述 */
|
||||
skillDesc: string;
|
||||
/** 跳跃剩余次数,-1 表示未开启,-2表示当前楼层不能跳 */
|
||||
jumpCount: number;
|
||||
/** 治愈之泉剩余次数,-1 表示未开启 */
|
||||
springCount: number;
|
||||
/** 当前楼层 */
|
||||
floor: FloorIds;
|
||||
/** 是否正在录像播放 */
|
||||
replaying: boolean;
|
||||
/** 录像播放状态 */
|
||||
replayStatus: ReplayingStatus;
|
||||
/** 极昼永夜 */
|
||||
night: number;
|
||||
}
|
||||
|
||||
export const RightStatusBar = defineComponent<StatusBarProps<IRightHeroStatus>>(
|
||||
p => {
|
||||
const font1 = new Font('normal', 18);
|
||||
const font2 = new Font('normal', 16);
|
||||
|
||||
const minimap = ref<Sprite>();
|
||||
const inNumpad = ref(false);
|
||||
|
||||
const onNumpad = () => {
|
||||
inNumpad.value = !inNumpad.value;
|
||||
};
|
||||
|
||||
const s = p.status;
|
||||
const skill = computed(() =>
|
||||
s.autoSkill ? '已开启自动切换' : s.skillName
|
||||
);
|
||||
const skillDesc = computed(() =>
|
||||
s.autoSkill ? '自动切换技能时,会自动选择最优技能' : s.skillDesc
|
||||
);
|
||||
|
||||
const skillColor = transitionedColor('#284', 200, linear())!;
|
||||
|
||||
watch(
|
||||
() => s.autoSkill,
|
||||
value => {
|
||||
skillColor.set(value ? '#284' : '#824');
|
||||
}
|
||||
);
|
||||
|
||||
const miscData = computed<RightStatusBarMisc[]>(() => {
|
||||
const data: RightStatusBarMisc[] = [];
|
||||
if (s.jumpCount !== -1) {
|
||||
const text =
|
||||
s.jumpCount === -2 ? '不可跳跃' : s.jumpCount.toString();
|
||||
data.push({
|
||||
name: '跳跃剩余',
|
||||
nameColor: '#fff',
|
||||
value: text,
|
||||
valueColor: '#fff'
|
||||
});
|
||||
}
|
||||
if (s.springCount >= 0) {
|
||||
data.push({
|
||||
name: '治愈之泉',
|
||||
nameColor: '#a7ffa7',
|
||||
value: s.springCount.toString(),
|
||||
valueColor: '#a7ffa7'
|
||||
});
|
||||
}
|
||||
if (s.night !== 0) {
|
||||
const text = s.night.toString();
|
||||
data.push({
|
||||
name: '极昼永夜',
|
||||
nameColor: '#a3f8ff',
|
||||
value: s.night > 0 ? '+' + text : text,
|
||||
valueColor: s.night > 0 ? '#a7ffa7' : '#ffa7a7'
|
||||
});
|
||||
}
|
||||
return data;
|
||||
});
|
||||
|
||||
const central = (y: number): ElementLocator => {
|
||||
const width = p.loc[2] ?? 200;
|
||||
return [width / 2, y, void 0, void 0, 0.5, 0.5];
|
||||
};
|
||||
|
||||
const middle = (x: number, y: number): ElementLocator => {
|
||||
return [x, y, void 0, void 0, 0, 0.5];
|
||||
};
|
||||
|
||||
const changeAutoSkill = () => {
|
||||
const { HeroSkill } = Mota.require('module', 'Mechanism');
|
||||
const auto = !s.autoSkill;
|
||||
HeroSkill.setAutoSkill(auto);
|
||||
core.status.route.push(`set:autoSkill:${auto}`);
|
||||
core.updateStatusBar();
|
||||
};
|
||||
|
||||
const area = getArea();
|
||||
const minimapDrawer = new MinimapDrawer(
|
||||
document.createElement('canvas')
|
||||
);
|
||||
minimapDrawer.noBorder = true;
|
||||
minimapDrawer.scale = 4;
|
||||
minimapDrawer.showInfo = true;
|
||||
let linked = false;
|
||||
const drawMinimap = (canvas: MotaOffscreenCanvas2D) => {
|
||||
const ctx = canvas.ctx;
|
||||
ctx.save();
|
||||
ctx.scale(
|
||||
1 / core.domStyle.scale / devicePixelRatio,
|
||||
1 / core.domStyle.scale / devicePixelRatio
|
||||
);
|
||||
if (!linked) {
|
||||
minimapDrawer.link(canvas.canvas);
|
||||
linked = true;
|
||||
}
|
||||
if (minimapDrawer.nowFloor !== s.floor) {
|
||||
minimapDrawer.drawedThumbnail = {};
|
||||
} else {
|
||||
minimapDrawer.drawToTarget();
|
||||
ctx.restore();
|
||||
return;
|
||||
}
|
||||
minimapDrawer.nowFloor = s.floor;
|
||||
minimapDrawer.nowArea =
|
||||
Object.keys(area).find(v =>
|
||||
area[v].includes(core.status.floorId)
|
||||
) ?? '';
|
||||
minimapDrawer.locateMap(minimapDrawer.nowFloor);
|
||||
minimapDrawer.drawMap();
|
||||
ctx.restore();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => s.floor,
|
||||
() => {
|
||||
minimap.value?.update();
|
||||
}
|
||||
);
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<container loc={p.loc} hidden={p.hidden}>
|
||||
<g-rectr
|
||||
loc={[10, 10, 160, 24]}
|
||||
circle={[6]}
|
||||
fillStyle={skillColor.ref.value}
|
||||
onClick={changeAutoSkill}
|
||||
cursor="pointer"
|
||||
></g-rectr>
|
||||
<text
|
||||
loc={central(22)}
|
||||
text={skill.value}
|
||||
font={font1}
|
||||
onClick={changeAutoSkill}
|
||||
cursor="pointer"
|
||||
/>
|
||||
<TextContent
|
||||
loc={[10, 42, 160, 60]}
|
||||
text={skillDesc.value}
|
||||
font={new Font('normal', 14)}
|
||||
width={160}
|
||||
lineHeight={4}
|
||||
></TextContent>
|
||||
<g-line
|
||||
line={[0, 107, 180, 107]}
|
||||
strokeStyle="#888"
|
||||
lineWidth={1}
|
||||
zIndex={-20}
|
||||
></g-line>
|
||||
<Scroll loc={[0, 107, 180, 100]}>
|
||||
{miscData.value
|
||||
.map((v, i) => {
|
||||
return [
|
||||
<text
|
||||
text={v.name}
|
||||
loc={middle(10, 16 + i * 22)}
|
||||
fillStyle={v.nameColor}
|
||||
font={font2}
|
||||
></text>,
|
||||
<text
|
||||
text={v.value}
|
||||
loc={middle(100, 16 + i * 22)}
|
||||
fillStyle={v.valueColor}
|
||||
font={font2}
|
||||
></text>
|
||||
];
|
||||
})
|
||||
.flat()}
|
||||
</Scroll>
|
||||
<g-line
|
||||
line={[0, 207, 180, 207]}
|
||||
strokeStyle="#888"
|
||||
lineWidth={1}
|
||||
zIndex={-20}
|
||||
></g-line>
|
||||
<sprite
|
||||
ref={minimap}
|
||||
loc={[10, 207, 160, 160]}
|
||||
render={drawMinimap}
|
||||
></sprite>
|
||||
<g-line
|
||||
line={[0, 367, 180, 367]}
|
||||
strokeStyle="#888"
|
||||
lineWidth={1}
|
||||
zIndex={-20}
|
||||
></g-line>
|
||||
{inNumpad.value ? (
|
||||
<NumpadToolbar
|
||||
loc={[0, 367, 180, 113]}
|
||||
onNumpad={onNumpad}
|
||||
/>
|
||||
) : s.replaying ? (
|
||||
<ReplayingToolbar
|
||||
loc={[0, 367, 180, 113]}
|
||||
status={s.replayStatus}
|
||||
/>
|
||||
) : (
|
||||
<PlayingToolbar
|
||||
loc={[0, 367, 180, 113]}
|
||||
onNumpad={onNumpad}
|
||||
/>
|
||||
)}
|
||||
</container>
|
||||
);
|
||||
};
|
||||
},
|
||||
statusBarProps
|
||||
);
|
||||
|
||||
export const leftStatusBarUI = new GameUI('left-status-bar', LeftStatusBar);
|
||||
export const rightStatusBarUI = new GameUI('right-status-bar', RightStatusBar);
|
||||
@@ -1,364 +0,0 @@
|
||||
import { DefaultProps, ElementLocator, Font } from '@motajs/render';
|
||||
import { computed, defineComponent, ref } from 'vue';
|
||||
import { SetupComponentOptions } from '../components';
|
||||
import {
|
||||
DanmakuIcon,
|
||||
DoubleArrow,
|
||||
NumpadIcon,
|
||||
PauseIcon,
|
||||
PlayIcon,
|
||||
ReplayIcon,
|
||||
RetweetIcon,
|
||||
RollbackIcon,
|
||||
StepForward,
|
||||
ViewMapIcon
|
||||
} from '../components/icons';
|
||||
import {
|
||||
generateBinary,
|
||||
getVitualKeyOnce,
|
||||
openDanmakuPoster
|
||||
} from '@motajs/legacy-ui';
|
||||
import { gameKey } from '@motajs/system-action';
|
||||
import { generateKeyboardEvent } from '@motajs/system-action';
|
||||
import { transitioned } from '../use';
|
||||
import { linear } from 'mutate-animate';
|
||||
import { KeyCode } from '@motajs/client-base';
|
||||
import { Progress } from '../components/misc';
|
||||
|
||||
interface ToolbarProps extends DefaultProps {
|
||||
loc?: ElementLocator;
|
||||
}
|
||||
|
||||
type ToolbarEmits = {
|
||||
numpad: () => void;
|
||||
};
|
||||
|
||||
const toolbarProps = {
|
||||
props: ['loc'],
|
||||
emits: ['numpad']
|
||||
} satisfies SetupComponentOptions<
|
||||
ToolbarProps,
|
||||
ToolbarEmits,
|
||||
keyof ToolbarEmits
|
||||
>;
|
||||
|
||||
const im = (col: number, row: number): ElementLocator => {
|
||||
return [5 + 34 * col, 5 + 36 * row, 32, 32];
|
||||
};
|
||||
|
||||
const ic = (col: number, row: number): ElementLocator => {
|
||||
return [7 + 34 * col, 7 + 36 * row, 28, 28];
|
||||
};
|
||||
|
||||
const ic2 = (col: number, row: number): ElementLocator => {
|
||||
return [9 + 34 * col, 9 + 36 * row, 24, 24];
|
||||
};
|
||||
|
||||
const middle = (col: number, row: number): ElementLocator => {
|
||||
return [21 + 34 * col, 21 + 36 * row, void 0, void 0, 0.5, 0.5];
|
||||
};
|
||||
|
||||
const middle2 = (
|
||||
col: number,
|
||||
row: number,
|
||||
width: number,
|
||||
height: number
|
||||
): ElementLocator => {
|
||||
return [21 + 34 * col, 21 + 36 * row, width, height, 0.5, 0.5];
|
||||
};
|
||||
|
||||
export const PlayingToolbar = defineComponent<
|
||||
ToolbarProps,
|
||||
ToolbarEmits,
|
||||
keyof ToolbarEmits
|
||||
>((props, { emit }) => {
|
||||
const bookIcon = core.statusBar.icons.book;
|
||||
const flyIcon = core.statusBar.icons.fly;
|
||||
const toolIcon = core.statusBar.icons.toolbox;
|
||||
const equipIcon = core.statusBar.icons.equipbox;
|
||||
const keyIcon = core.statusBar.icons.keyboard;
|
||||
const shopIcon = core.statusBar.icons.shop;
|
||||
const saveIcon = core.statusBar.icons.save;
|
||||
const loadIcon = core.statusBar.icons.load;
|
||||
const setIcon = core.statusBar.icons.settings;
|
||||
|
||||
const iconFont = new Font('Verdana', 12);
|
||||
|
||||
const book = () => core.openBook(true);
|
||||
const tool = () => core.openEquipbox(true);
|
||||
const fly = () => core.useFly(true);
|
||||
const save = () => core.save(true);
|
||||
const load = () => core.load(true);
|
||||
const equip = () => core.openEquipbox(true);
|
||||
const shop = () => core.openQuickShop(true);
|
||||
const key = () => {
|
||||
getVitualKeyOnce().then(value => {
|
||||
gameKey.emitKey(
|
||||
value.key,
|
||||
value.assist,
|
||||
'up',
|
||||
generateKeyboardEvent(value.key, value.assist)
|
||||
);
|
||||
});
|
||||
};
|
||||
const undo = () => core.doSL('autoSave', 'load');
|
||||
const redo = () => core.doSL('autoSave', 'reload');
|
||||
const numpad = () => emit('numpad');
|
||||
const view = () => {
|
||||
if (core.isPlaying() && !core.isMoving() && !core.status.lockControl) {
|
||||
core.ui._drawViewMaps();
|
||||
}
|
||||
};
|
||||
const danmaku = () => requestAnimationFrame(openDanmakuPoster);
|
||||
const replay = () => core.ui._drawReplay();
|
||||
const settings = () => core.openSettings(true);
|
||||
|
||||
return () => (
|
||||
<container loc={props.loc} cursor="pointer">
|
||||
<image image={bookIcon} loc={im(0, 0)} noanti onClick={book} />
|
||||
<image image={toolIcon} loc={im(1, 0)} noanti onClick={tool} />
|
||||
<image image={flyIcon} loc={im(2, 0)} noanti onClick={fly} />
|
||||
<image image={saveIcon} loc={im(3, 0)} noanti onClick={save} />
|
||||
<image image={loadIcon} loc={im(4, 0)} noanti onClick={load} />
|
||||
<image image={equipIcon} loc={im(0, 1)} noanti onClick={equip} />
|
||||
<image image={shopIcon} loc={im(1, 1)} noanti onClick={shop} />
|
||||
<image image={keyIcon} loc={im(2, 1)} noanti onClick={key} />
|
||||
<RollbackIcon loc={ic(3, 1)} strokeStyle="#eee" onClick={undo} />
|
||||
<RetweetIcon loc={ic(4, 1)} strokeStyle="#eee" onClick={redo} />
|
||||
<NumpadIcon loc={ic(0, 2)} strokeStyle="#eee" onClick={numpad} />
|
||||
<ViewMapIcon loc={ic(1, 2)} strokeStyle="#eee" onClick={view} />
|
||||
<DanmakuIcon loc={ic(2, 2)} strokeStyle="#eee" onClick={danmaku} />
|
||||
<ReplayIcon loc={ic(3, 2)} strokeStyle="#eee" onClick={replay} />
|
||||
<text text="R" loc={middle(3, 2)} font={iconFont} noevent />
|
||||
<image image={setIcon} loc={im(4, 2)} noanti onClick={settings} />
|
||||
</container>
|
||||
);
|
||||
}, toolbarProps);
|
||||
|
||||
export interface ReplayingStatus {
|
||||
/** 是否正在播放 */
|
||||
playing: boolean;
|
||||
/** 录像播放速度 */
|
||||
speed: number;
|
||||
/** 已播放的长度 */
|
||||
played: number;
|
||||
/** 总长度 */
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface ReplayingProps extends ToolbarProps {
|
||||
/** 录像播放状态 */
|
||||
status: ReplayingStatus;
|
||||
}
|
||||
|
||||
const replayingProps = {
|
||||
props: ['status', 'loc']
|
||||
} satisfies SetupComponentOptions<ReplayingProps>;
|
||||
|
||||
export const ReplayingToolbar = defineComponent<ReplayingProps>(props => {
|
||||
const status = props.status;
|
||||
|
||||
const bookIcon = core.statusBar.icons.book;
|
||||
const saveIcon = core.statusBar.icons.save;
|
||||
const font1 = new Font('normal', 16);
|
||||
const font2 = new Font('Verdana', 12);
|
||||
|
||||
const speedText = computed(() => `${status.speed}速`);
|
||||
const progress = computed(() => status.played / status.total);
|
||||
const progressText1 = computed(() => `${status.played}/${status.total}`);
|
||||
const progressText2 = computed(
|
||||
() => `${(progress.value * 100).toFixed(2)}%`
|
||||
);
|
||||
|
||||
const play = () => core.resumeReplay();
|
||||
const pause = () => core.pauseReplay();
|
||||
const stop = () => core.stopReplay(true);
|
||||
const speedDown = () => core.speedDownReplay();
|
||||
const speedUp = () => core.speedUpReplay();
|
||||
const book = () => core.openBook(true);
|
||||
const save = () => core.save(true);
|
||||
const view = () => {
|
||||
if (core.isPlaying() && !core.isMoving() && !core.status.lockControl) {
|
||||
core.ui._drawViewMaps();
|
||||
}
|
||||
};
|
||||
const rewind = () => core.rewindReplay();
|
||||
const step = () => core.stepReplay();
|
||||
|
||||
return () => {
|
||||
return (
|
||||
<container loc={props.loc} cursor="pointer">
|
||||
{status.playing ? (
|
||||
<PauseIcon loc={ic(0, 0)} onClick={pause} />
|
||||
) : (
|
||||
<PlayIcon loc={ic(0, 0)} onClick={play} />
|
||||
)}
|
||||
<g-rectr loc={[47, 13, 16, 16]} circle={[2]} onClick={stop} />
|
||||
<DoubleArrow
|
||||
loc={middle2(2, 0, 28, 28)}
|
||||
scale={[-1, 1]}
|
||||
onClick={speedDown}
|
||||
/>
|
||||
<text text={speedText.value} loc={middle(3, 0)} font={font1} />
|
||||
<DoubleArrow loc={ic(4, 0)} onClick={speedUp} />
|
||||
<image image={bookIcon} loc={im(0, 1)} noanti onClick={book} />
|
||||
<image image={saveIcon} loc={im(1, 1)} noanti onClick={save} />
|
||||
<ViewMapIcon loc={ic(2, 1)} onClick={view} />
|
||||
<StepForward
|
||||
loc={middle2(3, 1, 28, 28)}
|
||||
scale={[-1, 1]}
|
||||
onClick={rewind}
|
||||
/>
|
||||
<StepForward loc={ic(4, 1)} onClick={step} />
|
||||
<text
|
||||
text={progressText1.value}
|
||||
loc={[12, 98, void 0, void 0, 0, 1]}
|
||||
font={font2}
|
||||
/>
|
||||
<text
|
||||
text={progressText2.value}
|
||||
loc={[168, 98, void 0, void 0, 1, 1]}
|
||||
font={font2}
|
||||
/>
|
||||
<Progress
|
||||
loc={[12, 101, 156, 4]}
|
||||
progress={progress.value}
|
||||
success="lightgreen"
|
||||
/>
|
||||
</container>
|
||||
);
|
||||
};
|
||||
}, replayingProps);
|
||||
|
||||
export const NumpadToolbar = defineComponent<
|
||||
ToolbarProps,
|
||||
ToolbarEmits,
|
||||
keyof ToolbarEmits
|
||||
>((props, { emit }) => {
|
||||
const numpad = () => emit('numpad');
|
||||
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
|
||||
|
||||
const ctrlEnabled = ref(false);
|
||||
const shiftEnabled = ref(false);
|
||||
const altEnabled = ref(false);
|
||||
|
||||
const ctrlAlpha = transitioned(0, 100, linear())!;
|
||||
const shiftAlpha = transitioned(0, 100, linear())!;
|
||||
const altAlpha = transitioned(0, 100, linear())!;
|
||||
|
||||
const ctrlColor = computed(
|
||||
() => `rgba(221,221,221,${ctrlAlpha.ref.value})`
|
||||
);
|
||||
const ctrlTextColor = computed(() => {
|
||||
const rgb = Math.floor(255 - ctrlAlpha.ref.value * 255);
|
||||
return `rgba(${rgb},${rgb},${rgb},1)`;
|
||||
});
|
||||
|
||||
const shiftColor = computed(
|
||||
() => `rgba(221,221,221,${shiftAlpha.ref.value})`
|
||||
);
|
||||
const shiftTextColor = computed(() => {
|
||||
const rgb = Math.floor(255 - shiftAlpha.ref.value * 255);
|
||||
return `rgba(${rgb},${rgb},${rgb},1)`;
|
||||
});
|
||||
|
||||
const altColor = computed(() => `rgba(221,221,221,${altAlpha.ref.value})`);
|
||||
const altTextColor = computed(() => {
|
||||
const rgb = Math.floor(255 - altAlpha.ref.value * 255);
|
||||
return `rgba(${rgb},${rgb},${rgb},1)`;
|
||||
});
|
||||
|
||||
const clickCtrl = () => {
|
||||
ctrlEnabled.value = !ctrlEnabled.value;
|
||||
ctrlAlpha.set(ctrlEnabled.value ? 1 : 0);
|
||||
};
|
||||
|
||||
const clickShift = () => {
|
||||
shiftEnabled.value = !shiftEnabled.value;
|
||||
shiftAlpha.set(shiftEnabled.value ? 1 : 0);
|
||||
};
|
||||
|
||||
const clickAlt = () => {
|
||||
altEnabled.value = !altEnabled.value;
|
||||
altAlpha.set(altEnabled.value ? 1 : 0);
|
||||
};
|
||||
|
||||
const clickNum = (num: number) => {
|
||||
const bin = generateBinary([
|
||||
ctrlEnabled.value,
|
||||
shiftEnabled.value,
|
||||
altEnabled.value
|
||||
]);
|
||||
const code = (KeyCode.Digit0 + num) as KeyCode;
|
||||
gameKey.emitKey(code, bin, 'up', generateKeyboardEvent(code, bin));
|
||||
};
|
||||
|
||||
return () => (
|
||||
<container loc={props.loc} cursor="pointer">
|
||||
<container loc={[0, 0, 180, 81]}>
|
||||
{nums
|
||||
.map((v, i) => {
|
||||
const col = i % 5;
|
||||
const row = Math.floor(i / 5);
|
||||
return [
|
||||
<g-rectr
|
||||
loc={ic2(col, row)}
|
||||
circle={[4]}
|
||||
stroke
|
||||
onClick={() => clickNum(v)}
|
||||
/>,
|
||||
<text
|
||||
text={v.toString()}
|
||||
loc={middle(col, row)}
|
||||
noevent
|
||||
/>
|
||||
];
|
||||
})
|
||||
.flat()}
|
||||
</container>
|
||||
<g-rectr
|
||||
loc={[41, 81, 36, 24]}
|
||||
circle={[4]}
|
||||
stroke
|
||||
fill
|
||||
fillStyle={ctrlColor.value}
|
||||
onClick={clickCtrl}
|
||||
></g-rectr>
|
||||
<text
|
||||
text="Ctrl"
|
||||
loc={[59, 93, void 0, void 0, 0.5, 0.5]}
|
||||
fillStyle={ctrlTextColor.value}
|
||||
noevent
|
||||
/>
|
||||
<g-rectr
|
||||
loc={[86, 81, 44, 24]}
|
||||
circle={[4]}
|
||||
stroke
|
||||
fill
|
||||
fillStyle={shiftColor.value}
|
||||
onClick={clickShift}
|
||||
></g-rectr>
|
||||
<text
|
||||
text="Shift"
|
||||
loc={[108, 93, void 0, void 0, 0.5, 0.5]}
|
||||
fillStyle={shiftTextColor.value}
|
||||
noevent
|
||||
/>
|
||||
<g-rectr
|
||||
loc={[139, 81, 30, 24]}
|
||||
circle={[4]}
|
||||
stroke
|
||||
fill
|
||||
fillStyle={altColor.value}
|
||||
onClick={clickAlt}
|
||||
></g-rectr>
|
||||
<text
|
||||
text="Alt"
|
||||
loc={[154, 93, void 0, void 0, 0.5, 0.5]}
|
||||
fillStyle={altTextColor.value}
|
||||
noevent
|
||||
/>
|
||||
<NumpadIcon loc={ic(0, 2)} strokeStyle="gold" onClick={numpad} />
|
||||
</container>
|
||||
);
|
||||
}, toolbarProps);
|
||||
@@ -1,293 +0,0 @@
|
||||
import { TimingFn, Transition } from 'mutate-animate';
|
||||
import {
|
||||
ComponentInternalInstance,
|
||||
getCurrentInstance,
|
||||
onMounted,
|
||||
onUnmounted,
|
||||
ref,
|
||||
Ref
|
||||
} from 'vue';
|
||||
|
||||
export const enum Orientation {
|
||||
/** 横屏 */
|
||||
Landscape,
|
||||
/** 竖屏 */
|
||||
Portrait
|
||||
}
|
||||
|
||||
export type OrientationHook = (
|
||||
orientation: Orientation,
|
||||
width: number,
|
||||
height: number
|
||||
) => void;
|
||||
|
||||
let nowOrientation = Orientation.Landscape;
|
||||
const orientationHooks = new Set<OrientationHook>();
|
||||
|
||||
function checkOrientation() {
|
||||
const before = nowOrientation;
|
||||
// 只要宽度大于高度,那么就视为横屏
|
||||
if (window.innerWidth >= window.innerHeight) {
|
||||
nowOrientation = Orientation.Landscape;
|
||||
} else {
|
||||
nowOrientation = Orientation.Portrait;
|
||||
}
|
||||
if (nowOrientation === before) return;
|
||||
|
||||
orientationHooks.forEach(v => {
|
||||
v(nowOrientation, window.innerWidth, window.innerHeight);
|
||||
});
|
||||
}
|
||||
window.addEventListener('resize', checkOrientation);
|
||||
|
||||
/**
|
||||
* 当屏幕方向改变时执行函数
|
||||
* @param hook 当屏幕方向改变时执行的函数
|
||||
*/
|
||||
export function onOrientationChange(hook: OrientationHook) {
|
||||
onMounted(() => {
|
||||
orientationHooks.add(hook);
|
||||
hook(nowOrientation, window.innerWidth, window.innerHeight);
|
||||
});
|
||||
onUnmounted(() => {
|
||||
orientationHooks.delete(hook);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 当游戏加载完成时执行函数,如果调用此函数时游戏已经加载,那么会立刻调用传入的钩子函数
|
||||
* @param hook 当游戏加载完成时执行的函数
|
||||
*/
|
||||
export function onLoaded(hook: () => void) {
|
||||
const loading = Mota.require('var', 'loading');
|
||||
if (!loading.loaded) {
|
||||
loading.once('loaded', hook);
|
||||
} else {
|
||||
hook();
|
||||
}
|
||||
}
|
||||
|
||||
export interface ITransitionedController<T> {
|
||||
readonly ref: Ref<T>;
|
||||
readonly value: T;
|
||||
set(value: T, time?: number): void;
|
||||
}
|
||||
|
||||
class RenderTransition implements ITransitionedController<number> {
|
||||
private static key: number = 0;
|
||||
|
||||
private readonly key: string = `$${RenderTransition.key++}`;
|
||||
|
||||
public readonly ref: Ref<number>;
|
||||
|
||||
set value(v: number) {
|
||||
this.transition.transition(this.key, v);
|
||||
}
|
||||
get value() {
|
||||
return this.transition.value[this.key];
|
||||
}
|
||||
|
||||
constructor(
|
||||
value: number,
|
||||
public readonly transition: Transition,
|
||||
public readonly time: number,
|
||||
public readonly curve: TimingFn
|
||||
) {
|
||||
this.ref = ref(value);
|
||||
transition.value[this.key] = value;
|
||||
transition.ticker.add(() => {
|
||||
this.ref.value = transition.value[this.key];
|
||||
});
|
||||
}
|
||||
|
||||
set(value: number, time: number = this.time): void {
|
||||
this.transition.time(time).mode(this.curve).transition(this.key, value);
|
||||
}
|
||||
}
|
||||
|
||||
type ColorRGBA = [number, number, number, number];
|
||||
|
||||
class RenderColorTransition implements ITransitionedController<string> {
|
||||
private static key: number = 0;
|
||||
|
||||
private readonly keyR: string = `$colorR${RenderColorTransition.key++}`;
|
||||
private readonly keyG: string = `$colorG${RenderColorTransition.key++}`;
|
||||
private readonly keyB: string = `$colorB${RenderColorTransition.key++}`;
|
||||
private readonly keyA: string = `$colorA${RenderColorTransition.key++}`;
|
||||
|
||||
public readonly ref: Ref<string>;
|
||||
|
||||
set value(v: string) {
|
||||
this.set(v);
|
||||
}
|
||||
get value() {
|
||||
return this.encodeColor();
|
||||
}
|
||||
|
||||
constructor(
|
||||
value: string,
|
||||
public readonly transition: Transition,
|
||||
public readonly time: number,
|
||||
public readonly curve: TimingFn
|
||||
) {
|
||||
this.ref = ref(value);
|
||||
const [r, g, b, a] = this.decodeColor(value);
|
||||
transition.value[this.keyR] = r;
|
||||
transition.value[this.keyG] = g;
|
||||
transition.value[this.keyB] = b;
|
||||
transition.value[this.keyA] = a;
|
||||
transition.ticker.add(() => {
|
||||
this.ref.value = this.encodeColor();
|
||||
});
|
||||
}
|
||||
|
||||
set(value: string, time: number = this.time): void {
|
||||
this.transitionColor(this.decodeColor(value), time);
|
||||
}
|
||||
|
||||
private transitionColor([r, g, b, a]: ColorRGBA, time: number) {
|
||||
this.transition
|
||||
.mode(this.curve)
|
||||
.time(time)
|
||||
.transition(this.keyR, r)
|
||||
.transition(this.keyG, g)
|
||||
.transition(this.keyB, b)
|
||||
.transition(this.keyA, a);
|
||||
}
|
||||
|
||||
private decodeColor(color: string): ColorRGBA {
|
||||
if (color.startsWith('#')) {
|
||||
return this.decodeHash(color);
|
||||
} else if (color.startsWith('rgba')) {
|
||||
return this.decodeRGBA(color);
|
||||
} else if (color.startsWith('rgb')) {
|
||||
return this.decodeRGB(color);
|
||||
}
|
||||
return [0, 0, 0, 1];
|
||||
}
|
||||
|
||||
private decodeHash(color: string): ColorRGBA {
|
||||
switch (color.length) {
|
||||
case 4:
|
||||
return [
|
||||
Number(`0x${color.slice(1, 2).repeat(2)}`),
|
||||
Number(`0x${color.slice(2, 3).repeat(2)}`),
|
||||
Number(`0x${color.slice(3, 4).repeat(2)}`),
|
||||
1
|
||||
];
|
||||
case 5:
|
||||
return [
|
||||
Number(`0x${color.slice(1, 2).repeat(2)}`),
|
||||
Number(`0x${color.slice(2, 3).repeat(2)}`),
|
||||
Number(`0x${color.slice(3, 4).repeat(2)}`),
|
||||
Number(`0x${color.slice(4, 5).repeat(2)}`)
|
||||
];
|
||||
case 7:
|
||||
return [
|
||||
Number(`0x${color.slice(1, 3)}`),
|
||||
Number(`0x${color.slice(3, 5)}`),
|
||||
Number(`0x${color.slice(5, 7)}`),
|
||||
1
|
||||
];
|
||||
case 9:
|
||||
return [
|
||||
Number(`0x${color.slice(1, 3)}`),
|
||||
Number(`0x${color.slice(3, 5)}`),
|
||||
Number(`0x${color.slice(5, 7)}`),
|
||||
Number(`0x${color.slice(7, 9)}`)
|
||||
];
|
||||
}
|
||||
return [0, 0, 0, 0];
|
||||
}
|
||||
|
||||
private decodeRGBA(color: string): ColorRGBA {
|
||||
const data = color.slice(color.indexOf('(') + 1, color.indexOf(')'));
|
||||
const [r, g, b, a] = data.split(',');
|
||||
return [Number(r), Number(g), Number(b), Number(a)];
|
||||
}
|
||||
|
||||
private decodeRGB(color: string): ColorRGBA {
|
||||
const data = color.slice(color.indexOf('(') + 1, color.indexOf(')'));
|
||||
const [r, g, b] = data.split(',');
|
||||
return [Number(r), Number(g), Number(b), 1];
|
||||
}
|
||||
|
||||
private encodeColor() {
|
||||
const r = this.transition.value[this.keyR];
|
||||
const g = this.transition.value[this.keyG];
|
||||
const b = this.transition.value[this.keyB];
|
||||
const a = this.transition.value[this.keyA];
|
||||
return `rgba(${r},${g},${b},${a})`;
|
||||
}
|
||||
}
|
||||
|
||||
const transitionMap = new Map<ComponentInternalInstance, Transition>();
|
||||
|
||||
function checkTransition() {
|
||||
const instance = getCurrentInstance();
|
||||
if (!instance) return null;
|
||||
if (instance.isUnmounted) {
|
||||
const tran = transitionMap.get(instance);
|
||||
tran?.ticker.destroy();
|
||||
transitionMap.delete(instance);
|
||||
return null;
|
||||
}
|
||||
if (!transitionMap.has(instance)) {
|
||||
const tran = new Transition();
|
||||
transitionMap.set(instance, tran);
|
||||
onUnmounted(() => {
|
||||
transitionMap.delete(instance);
|
||||
tran.ticker.destroy();
|
||||
});
|
||||
}
|
||||
const tran = transitionMap.get(instance);
|
||||
if (!tran) return null;
|
||||
return tran;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个渐变数值,当数值发生变化时会缓慢变化值目标值而非突变,只可以用于组件内,不可用于组件外
|
||||
* ```tsx
|
||||
* const value = transitioned(10, 300, linear()); // 创建渐变,初始值为 10,渐变时长 300ms,线性变化
|
||||
* value.set(100); // 渐变至 100
|
||||
*
|
||||
* // 直接在元素上使用
|
||||
* <text text={value.ref.value} />
|
||||
* ```
|
||||
* @param value 初始值
|
||||
* @param time 渐变时长
|
||||
* @param curve 渐变的速率曲线
|
||||
*/
|
||||
export function transitioned(
|
||||
value: number,
|
||||
time: number,
|
||||
curve: TimingFn
|
||||
): ITransitionedController<number> | null {
|
||||
const tran = checkTransition();
|
||||
if (!tran) return null;
|
||||
return new RenderTransition(value, tran, time, curve);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个渐变颜色,当颜色发生变化时会缓慢变化值目标值而非突变,自动判断颜色字符串类型,只可用于组件内,不可用于组件外
|
||||
* ```tsx
|
||||
* // 创建渐变,初始值为 '#fff'(白色),渐变时长 300ms,线性变化
|
||||
* const color = transitionedColor('#fff', 300, linear());
|
||||
* color.set('rgba(129, 30, 40, 0.7)'); // 渐变至这个颜色
|
||||
*
|
||||
* // 直接在元素上使用
|
||||
* <text text='文本' fillStyle={color.ref.value} />
|
||||
* ```
|
||||
* @param color 颜色的初始值
|
||||
* @param time 渐变时长
|
||||
* @param curve 渐变的速率曲线
|
||||
*/
|
||||
export function transitionedColor(
|
||||
color: string,
|
||||
time: number,
|
||||
curve: TimingFn
|
||||
): ITransitionedController<string> | null {
|
||||
const tran = checkTransition();
|
||||
if (!tran) return null;
|
||||
return new RenderColorTransition(color, tran, time, curve);
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export * from './saves';
|
||||
@@ -1,35 +0,0 @@
|
||||
export function getAllSavesData() {
|
||||
return new Promise<string>(res => {
|
||||
core.getAllSaves(saves => {
|
||||
if (!saves) {
|
||||
res('');
|
||||
return;
|
||||
}
|
||||
const content = {
|
||||
name: core.firstData.name,
|
||||
version: core.firstData.version,
|
||||
data: saves
|
||||
};
|
||||
// @ts-expect-error 暂时无法推导
|
||||
res(LZString.compressToBase64(JSON.stringify(content)));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function getSaveData(index: number) {
|
||||
return new Promise<string>(res => {
|
||||
core.getSave(index, data => {
|
||||
if (!data) {
|
||||
res('');
|
||||
return;
|
||||
}
|
||||
const content = {
|
||||
name: core.firstData.name,
|
||||
version: core.firstData.version,
|
||||
data: data
|
||||
};
|
||||
// @ts-expect-error 暂时无法推导
|
||||
res(LZString.compressToBase64(JSON.stringify(content)));
|
||||
});
|
||||
});
|
||||
}
|
||||
Whitespace-only changes.
@@ -1,11 +0,0 @@
|
||||
import { RainWeather } from './rain';
|
||||
import { SnowWeather } from './snow';
|
||||
import { SunWeather } from './sun';
|
||||
import { WeatherController } from './weather';
|
||||
|
||||
WeatherController.register('rain', RainWeather);
|
||||
WeatherController.register('sun', SunWeather);
|
||||
WeatherController.register('snow', SnowWeather);
|
||||
|
||||
export * from './weather';
|
||||
export * from './rain';
|
||||
@@ -1,212 +0,0 @@
|
||||
import {
|
||||
Shader,
|
||||
ShaderProgram,
|
||||
MotaRenderer,
|
||||
Container,
|
||||
IShaderUniform,
|
||||
UniformType
|
||||
} from '@motajs/render';
|
||||
import { IWeather } from './weather';
|
||||
|
||||
const rainVs = /* glsl */ `
|
||||
in vec2 a_rainVertex;
|
||||
in vec2 a_offset; // 雨滴的中心位置
|
||||
in vec4 a_data; // x: 雨滴宽度; y: 雨滴长度; z: 雨滴旋转角度,0表示向下,逆时针为正;
|
||||
// w: 属于哪一种雨,需要两种雨反复循环,一种无法实现循环,0表示第一种,1表示第二种
|
||||
|
||||
uniform float u_progress; // 下雨进度,从最上落到最下是0.5个进度,以保证不会出现奇怪的问题
|
||||
|
||||
out vec2 v_center;
|
||||
out vec2 v_data; // 雨滴宽度与高度
|
||||
out vec2 v_pos;
|
||||
|
||||
mat2 createScaleMatrix(float x, float y) {
|
||||
return mat2(
|
||||
x, 0,
|
||||
0, y
|
||||
);
|
||||
}
|
||||
|
||||
vec2 getOffsetByProgress(vec2 offset) {
|
||||
if (a_data.w == 0.0) {
|
||||
if (u_progress < 0.5) {
|
||||
return offset * u_progress * 2.0;
|
||||
} else {
|
||||
return offset * (u_progress - 1.0) * 2.0;
|
||||
}
|
||||
} else {
|
||||
return offset * u_progress * 2.0;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
float cosTheta = cos(a_data.z);
|
||||
float sinTheta = sin(a_data.z);
|
||||
mat2 rotate = mat2(
|
||||
cosTheta, -sinTheta,
|
||||
sinTheta, cosTheta
|
||||
);
|
||||
vec2 offset = getOffsetByProgress(vec2(-sinTheta * 2.0, -cosTheta * 2.0));
|
||||
mat2 scale = createScaleMatrix(a_data.x, a_data.y);
|
||||
vec2 off = a_offset + offset;
|
||||
vec2 pos = rotate * scale * a_rainVertex + off;
|
||||
v_center = off;
|
||||
v_pos = pos;
|
||||
gl_Position = vec4(pos, 0.0, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
const rainFs = /* glsl */ `
|
||||
in vec2 v_center;
|
||||
in vec2 v_data; // 雨滴的宽度与长度
|
||||
in vec2 v_pos;
|
||||
|
||||
uniform vec4 u_color; // 雨滴的颜色
|
||||
|
||||
out vec4 outColor;
|
||||
|
||||
float random(vec2 uv) {
|
||||
return fract(sin(dot(uv, vec2(12.9898, 78.233))) * 43758.5453);
|
||||
}
|
||||
|
||||
void main() {
|
||||
float ran = random(v_pos);
|
||||
vec2 pos = vec2(v_pos.x + ran * 0.01, v_pos.y);
|
||||
vec2 texPos = (pos + 1.0) / 2.0;
|
||||
texPos.y = 1.0 - texPos.y;
|
||||
vec4 tex = texture(u_sampler, texPos);
|
||||
outColor = mix(u_color, tex, 0.9);
|
||||
}
|
||||
`;
|
||||
|
||||
/** 雨滴顶点坐标 */
|
||||
const vertex = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);
|
||||
|
||||
export class RainWeather implements IWeather {
|
||||
readonly shader: RainShader;
|
||||
readonly program: ShaderProgram;
|
||||
|
||||
private progress: IShaderUniform<UniformType.Uniform1f> | null = null;
|
||||
|
||||
constructor(readonly level: number = 5) {
|
||||
const shader = new RainShader();
|
||||
const gl = shader.gl;
|
||||
shader.size(480, 480);
|
||||
shader.setHD(true);
|
||||
shader.setZIndex(100);
|
||||
const program = shader.createProgram(ShaderProgram);
|
||||
program.fs(rainFs);
|
||||
program.vs(rainVs);
|
||||
program.requestCompile();
|
||||
const pos = program.defineAttribArray('a_rainVertex');
|
||||
program.defineAttribArray('a_offset');
|
||||
program.defineAttribArray('a_data');
|
||||
program.defineUniform('u_progress', shader.UNIFORM_1f);
|
||||
program.defineUniform('u_color', shader.UNIFORM_4f);
|
||||
program.mode(shader.DRAW_ARRAYS_INSTANCED);
|
||||
shader.useProgram(program);
|
||||
|
||||
if (pos) {
|
||||
pos.buffer(vertex, gl.STATIC_DRAW);
|
||||
pos.pointer(2, gl.FLOAT, false, 0, 0);
|
||||
pos.enable();
|
||||
}
|
||||
this.shader = shader;
|
||||
this.program = program;
|
||||
}
|
||||
|
||||
activate(): void {
|
||||
const render = MotaRenderer.get('render-main');
|
||||
const draw = render?.getElementById('map-draw') as Container;
|
||||
if (!draw) return;
|
||||
const shader = this.shader;
|
||||
shader.append(draw);
|
||||
|
||||
const gl = shader.gl;
|
||||
const program = this.program;
|
||||
program.paramArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, 100 * this.level);
|
||||
|
||||
this.progress = program.getUniform<UniformType.Uniform1f>('u_progress');
|
||||
shader.useProgram(program);
|
||||
shader.generateRainPath(
|
||||
this.level * 100,
|
||||
(((Math.random() - 0.5) * Math.PI) / 30) * this.level,
|
||||
(Math.PI / 180) * (12 - this.level),
|
||||
program
|
||||
);
|
||||
}
|
||||
|
||||
frame(): void {
|
||||
this.shader.update(this.shader);
|
||||
const time = 5000 - 400 * this.level;
|
||||
const progress = (Date.now() % time) / time;
|
||||
|
||||
this.shader.useProgram(this.program);
|
||||
this.progress?.set(progress);
|
||||
}
|
||||
|
||||
deactivate(): void {
|
||||
const render = MotaRenderer.get('render-main');
|
||||
const draw = render?.getElementById('map-draw') as Container;
|
||||
const layer = draw.children;
|
||||
if (!layer || !draw) return;
|
||||
const shader = this.shader;
|
||||
draw.appendChild(...layer);
|
||||
shader.remove();
|
||||
}
|
||||
}
|
||||
|
||||
class RainShader extends Shader {
|
||||
/**
|
||||
* 生成雨滴
|
||||
* @param num 雨滴数量
|
||||
*/
|
||||
generateRainPath(
|
||||
num: number,
|
||||
angle: number,
|
||||
deviation: number,
|
||||
program: ShaderProgram
|
||||
) {
|
||||
const aOffset = program.getAttribArray('a_offset');
|
||||
const aData = program.getAttribArray('a_data');
|
||||
const color = program.getUniform<UniformType.Uniform4f>('u_color');
|
||||
const gl = this.gl;
|
||||
if (!aOffset || !aData) return;
|
||||
|
||||
const tan = Math.tan(angle);
|
||||
|
||||
const offset = new Float32Array(num * 2);
|
||||
const data = new Float32Array(num * 4);
|
||||
const half = num / 2;
|
||||
for (let i = 0; i < half; i++) {
|
||||
const ox = Math.random() * 3 - 1.5;
|
||||
const oy = Math.random() * 2 - 1;
|
||||
const rad = angle + (Math.random() - 0.5) * Math.PI * deviation;
|
||||
const length = Math.random() * 0.05 + 0.03;
|
||||
const width = Math.random() * 0.002 + 0.002;
|
||||
offset.set([ox, oy], i * 2);
|
||||
data.set([width, length, rad, 0], i * 4);
|
||||
}
|
||||
for (let i = half; i < num; i++) {
|
||||
const ox = Math.random() * 3 - 1.5 + tan * 2;
|
||||
const oy = Math.random() * 2 + 1;
|
||||
const rad = angle + (Math.random() - 0.5) * Math.PI * deviation;
|
||||
const length = Math.random() * 0.1 + 0.05;
|
||||
const width = Math.random() * 0.002 + 0.002;
|
||||
offset.set([ox, oy], i * 2);
|
||||
data.set([width, length, rad, 1], i * 4);
|
||||
}
|
||||
|
||||
aOffset.buffer(offset, gl.STATIC_DRAW);
|
||||
aData.buffer(data, gl.STATIC_DRAW);
|
||||
aOffset.pointer(2, gl.FLOAT, false, 0, 0);
|
||||
aOffset.divisor(1);
|
||||
aOffset.enable();
|
||||
aData.pointer(4, gl.FLOAT, false, 0, 0);
|
||||
aData.divisor(1);
|
||||
aData.enable();
|
||||
|
||||
program.paramArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, num);
|
||||
color?.set(1, 1, 1, 0.1);
|
||||
}
|
||||
}
|
||||
@@ -1,250 +0,0 @@
|
||||
import {
|
||||
Shader,
|
||||
ShaderProgram,
|
||||
MotaRenderer,
|
||||
Container,
|
||||
GL2Program,
|
||||
IShaderUniform,
|
||||
UniformType,
|
||||
Transform,
|
||||
MotaOffscreenCanvas2D
|
||||
} from '@motajs/render';
|
||||
import { IWeather } from './weather';
|
||||
|
||||
const snowVs = /* glsl */ `
|
||||
in vec2 a_snowVertex;
|
||||
in vec2 a_offset; // 雨滴的中心位置
|
||||
in vec4 a_data; // x: 雨滴宽度; y: 雨滴长度; z: 雨滴旋转角度,0表示向下,逆时针为正;
|
||||
// w: 属于哪一种雨,需要两种雨反复循环,一种无法实现循环,0表示第一种,1表示第二种
|
||||
|
||||
uniform float u_progress; // 下雨进度,从最上落到最下是0.5个进度,以保证不会出现奇怪的问题
|
||||
|
||||
out vec2 v_center;
|
||||
out vec2 v_data; // 雨滴宽度与高度
|
||||
out vec2 v_pos;
|
||||
|
||||
mat2 createScaleMatrix(float x, float y) {
|
||||
return mat2(
|
||||
x, 0,
|
||||
0, y
|
||||
);
|
||||
}
|
||||
|
||||
vec2 getOffsetByProgress(vec2 offset) {
|
||||
if (a_data.w == 0.0) {
|
||||
if (u_progress < 0.5) {
|
||||
return offset * u_progress * 2.0;
|
||||
} else {
|
||||
return offset * (u_progress - 1.0) * 2.0;
|
||||
}
|
||||
} else {
|
||||
return offset * u_progress * 2.0;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
float cosTheta = cos(a_data.z);
|
||||
float sinTheta = sin(a_data.z);
|
||||
mat2 rotate = mat2(
|
||||
cosTheta, -sinTheta,
|
||||
sinTheta, cosTheta
|
||||
);
|
||||
vec2 offset = getOffsetByProgress(vec2(-sinTheta * 2.0, -cosTheta * 2.0));
|
||||
mat2 scale = createScaleMatrix(a_data.x, a_data.y);
|
||||
vec2 off = a_offset + offset;
|
||||
|
||||
// const int segments = 32; // 圆的分段数
|
||||
// float angleIncrement = 2.0 * 3.14159265359 / float(segments);
|
||||
// vec2 a_roundVertex[segments];
|
||||
// for (int i = 0; i < segments; i++) {
|
||||
// float angle = float(i) * angleIncrement;
|
||||
// a_roundVertex[i] = vec2(cos(angle), sin(angle)); // 生成单位圆的顶点
|
||||
// }
|
||||
|
||||
// vec2 pos = rotate * scale * a_roundVertex + off;
|
||||
vec2 pos = rotate * scale * a_snowVertex + off;
|
||||
v_center = off;
|
||||
v_pos = pos;
|
||||
gl_Position = vec4(pos, 0.0, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
const snowFs = /* glsl */ `
|
||||
in vec2 v_center;
|
||||
in vec2 v_data; // 雨滴的宽度与长度
|
||||
in vec2 v_pos;
|
||||
|
||||
uniform vec4 u_color; // 雨滴的颜色
|
||||
|
||||
out vec4 outColor;
|
||||
|
||||
float random(vec2 uv) {
|
||||
return fract(sin(dot(uv, vec2(12.9898, 78.233))) * 43758.5453);
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
float distanceFromCenter = length(v_pos - v_center);
|
||||
if (distanceFromCenter < 0.05) {
|
||||
outColor = u_color; // 雪花颜色
|
||||
} else {
|
||||
// outColor = vec4(0.0, 0.0, 0.0, 0.2);
|
||||
discard; // 不绘制超出圆的部分
|
||||
}
|
||||
|
||||
// float ran = random(v_pos);
|
||||
// vec2 pos = vec2(v_pos.x + ran * 0.01, v_pos.y);
|
||||
// vec2 texPos = (pos + 1.0) / 2.0;
|
||||
// texPos.y = 1.0 - texPos.y;
|
||||
// vec4 tex = texture(u_sampler, texPos);
|
||||
// // outColor = mix(u_color, tex, 0.9);
|
||||
// outColor = u_color;
|
||||
}
|
||||
`;
|
||||
|
||||
/** 雨滴顶点坐标 */
|
||||
const vertex = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);
|
||||
|
||||
Mota.require('var', 'loading').once('coreInit', () => {
|
||||
const shader = new SnowShader();
|
||||
const gl = shader.gl;
|
||||
shader.size(480, 480);
|
||||
shader.setHD(true);
|
||||
SnowWeather.shader = shader;
|
||||
const program = shader.createProgram(ShaderProgram);
|
||||
program.fs(snowFs);
|
||||
program.vs(snowVs);
|
||||
program.requestCompile();
|
||||
const pos = program.defineAttribArray('a_snowVertex');
|
||||
program.defineAttribArray('a_offset');
|
||||
program.defineAttribArray('a_data');
|
||||
program.defineUniform('u_progress', shader.UNIFORM_1f);
|
||||
program.defineUniform('u_color', shader.UNIFORM_4f);
|
||||
program.mode(shader.DRAW_ARRAYS_INSTANCED);
|
||||
SnowShader.snowProgram = program;
|
||||
shader.useProgram(program);
|
||||
|
||||
if (pos) {
|
||||
pos.buffer(vertex, gl.STATIC_DRAW);
|
||||
pos.pointer(2, gl.FLOAT, false, 0, 0);
|
||||
pos.enable();
|
||||
}
|
||||
});
|
||||
|
||||
export class SnowWeather implements IWeather {
|
||||
static id: string = 'snow';
|
||||
|
||||
static shader: SnowShader;
|
||||
|
||||
private progress: IShaderUniform<UniformType.Uniform1f> | null = null;
|
||||
|
||||
constructor(readonly level: number = 5) {}
|
||||
|
||||
activate(): void {
|
||||
const render = MotaRenderer.get('render-main');
|
||||
const draw = render?.getElementById('map-draw') as Container;
|
||||
if (!draw) return;
|
||||
const shader = SnowWeather.shader;
|
||||
shader.append(draw);
|
||||
|
||||
const gl = shader.gl;
|
||||
const program = SnowShader.snowProgram;
|
||||
program.paramArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, 100 * this.level);
|
||||
|
||||
this.progress = program.getUniform<UniformType.Uniform1f>('u_progress');
|
||||
shader.generateSnowPath(
|
||||
this.level * 100,
|
||||
(((Math.random() - 0.5) * Math.PI) / 30) * this.level,
|
||||
(Math.PI / 180) * (12 - this.level)
|
||||
);
|
||||
}
|
||||
|
||||
frame(): void {
|
||||
SnowWeather.shader.update(SnowWeather.shader);
|
||||
const time = 5000 - 400 * this.level;
|
||||
const progress = (Date.now() % time) / time;
|
||||
|
||||
SnowWeather.shader.useProgram(SnowShader.snowProgram);
|
||||
this.progress?.set(progress);
|
||||
}
|
||||
|
||||
deactivate(): void {
|
||||
const render = MotaRenderer.get('render-main');
|
||||
const layer = render?.getElementById('layer-main');
|
||||
const draw = render?.getElementById('map-draw') as Container;
|
||||
if (!layer || !draw) return;
|
||||
const shader = SnowWeather.shader;
|
||||
layer.append(draw);
|
||||
shader.remove();
|
||||
}
|
||||
}
|
||||
|
||||
class SnowShader extends Shader {
|
||||
static snowProgram: ShaderProgram;
|
||||
static backProgram: ShaderProgram;
|
||||
|
||||
/**
|
||||
* 生成雨滴
|
||||
* @param num 雨滴数量
|
||||
*/
|
||||
generateSnowPath(num: number, angle: number, deviation: number) {
|
||||
const program = SnowShader.snowProgram;
|
||||
SnowWeather.shader.useProgram(program);
|
||||
const aOffset = program.getAttribArray('a_offset');
|
||||
const aData = program.getAttribArray('a_data');
|
||||
const color = program.getUniform<UniformType.Uniform4f>('u_color');
|
||||
const gl = this.gl;
|
||||
if (!aOffset || !aData) return;
|
||||
|
||||
const tan = Math.tan(angle);
|
||||
|
||||
const offset = new Float32Array(num * 2);
|
||||
const data = new Float32Array(num * 4);
|
||||
const half = num / 2;
|
||||
for (let i = 0; i < half; i++) {
|
||||
const ox = Math.random() * 3 - 1.5;
|
||||
const oy = Math.random() * 2 - 1;
|
||||
const rad = angle + (Math.random() - 0.5) * Math.PI * deviation;
|
||||
const length = Math.random() * 0.05 + 0.03;
|
||||
const width = Math.random() * 0.05 + 0.03;
|
||||
offset.set([ox, oy], i * 2);
|
||||
data.set([width, length, rad, 0], i * 4);
|
||||
}
|
||||
for (let i = half; i < num; i++) {
|
||||
const ox = Math.random() * 3 - 1.5 + tan * 2;
|
||||
const oy = Math.random() * 2 + 1;
|
||||
const rad = angle + (Math.random() - 0.5) * Math.PI * deviation;
|
||||
const length = Math.random() * 0.1 + 0.05;
|
||||
const width = Math.random() * 0.1 + 0.05;
|
||||
offset.set([ox, oy], i * 2);
|
||||
data.set([width, length, rad, 1], i * 4);
|
||||
}
|
||||
|
||||
aOffset.buffer(offset, gl.STATIC_DRAW);
|
||||
aData.buffer(data, gl.STATIC_DRAW);
|
||||
aOffset.pointer(2, gl.FLOAT, false, 0, 0);
|
||||
aOffset.divisor(1);
|
||||
aOffset.enable();
|
||||
aData.pointer(4, gl.FLOAT, false, 0, 0);
|
||||
aData.divisor(1);
|
||||
aData.enable();
|
||||
|
||||
program.paramArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, num);
|
||||
color?.set(1, 1, 1, 0.1);
|
||||
}
|
||||
|
||||
protected preDraw(
|
||||
canvas: MotaOffscreenCanvas2D,
|
||||
transform: Transform,
|
||||
gl: WebGL2RenderingContext,
|
||||
program: GL2Program
|
||||
): boolean {
|
||||
const snow = SnowShader.snowProgram;
|
||||
const snowParam = snow.getDrawParams(this.DRAW_ARRAYS_INSTANCED);
|
||||
if (!snowParam) return false;
|
||||
this.useProgram(snow);
|
||||
if (!snow.ready()) return false;
|
||||
this.draw(gl, snow);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
import { IWeather } from './weather';
|
||||
|
||||
export class SunWeather implements IWeather {
|
||||
static id: string = 'sun';
|
||||
|
||||
activate(): void {}
|
||||
|
||||
frame(): void {}
|
||||
|
||||
deactivate(): void {}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
import { logger } from '@motajs/common';
|
||||
import { RenderItem } from '@motajs/render';
|
||||
import { Ticker } from 'mutate-animate';
|
||||
|
||||
export interface IWeather {
|
||||
/**
|
||||
* 初始化天气,当天气被添加时会被立刻调用
|
||||
*/
|
||||
activate(item: RenderItem): void;
|
||||
|
||||
/**
|
||||
* 每帧执行的函数
|
||||
*/
|
||||
frame(): void;
|
||||
|
||||
/**
|
||||
* 摧毁这个天气,当天气被删除时会执行
|
||||
*/
|
||||
deactivate(item: RenderItem): void;
|
||||
}
|
||||
|
||||
type Weather = new (level?: number) => IWeather;
|
||||
|
||||
export class WeatherController {
|
||||
static list: Map<string, Weather> = new Map();
|
||||
static map: Map<string, WeatherController> = new Map();
|
||||
|
||||
/** 当前的所有天气 */
|
||||
active: Set<IWeather> = new Set();
|
||||
ticker: Ticker = new Ticker();
|
||||
|
||||
private binded?: RenderItem;
|
||||
|
||||
constructor(public readonly id: string) {
|
||||
WeatherController.map.set(id, this);
|
||||
}
|
||||
|
||||
private tick = () => {
|
||||
this.active.forEach(v => {
|
||||
v.frame();
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 清空所有天气
|
||||
*/
|
||||
clearWeather() {
|
||||
if (this.binded) {
|
||||
this.active.forEach(v => {
|
||||
v.deactivate(this.binded!);
|
||||
});
|
||||
}
|
||||
this.active.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个天气
|
||||
* @param weather 要获取的天气
|
||||
*/
|
||||
getWeather<T extends IWeather = IWeather>(weather: Weather): T | null {
|
||||
return ([...this.active].find(v => v instanceof weather) as T) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一个天气,如果天气不存在则抛出警告。注意虽然原则上不允许天气重复。
|
||||
* @param id 天气的id
|
||||
* @param level 天气的等级
|
||||
* @returns 天气实例,可以操作天气的效果,也可以用来删除
|
||||
*/
|
||||
activate(id: string, level?: number) {
|
||||
const Weather = WeatherController.list.get(id);
|
||||
if (!Weather) {
|
||||
logger.warn(25, id);
|
||||
return;
|
||||
}
|
||||
const weather = new Weather(level);
|
||||
this.active.add(weather);
|
||||
if (this.binded) {
|
||||
weather.activate(this.binded);
|
||||
}
|
||||
if (!this.ticker.funcs.has(this.tick)) {
|
||||
this.ticker.add(this.tick);
|
||||
}
|
||||
return weather;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除一个天气
|
||||
* @param weather 要删除的天气
|
||||
*/
|
||||
deactivate(weather: IWeather) {
|
||||
this.active.delete(weather);
|
||||
if (this.active.size === 0) {
|
||||
this.ticker.remove(this.tick);
|
||||
}
|
||||
if (this.binded) {
|
||||
weather.deactivate(this.binded);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将这个天气控制器绑定至一个渲染元素上
|
||||
* @param item 要绑定的元素,不填表示取消绑定
|
||||
*/
|
||||
bind(item?: RenderItem) {
|
||||
if (this.binded) {
|
||||
this.active.forEach(v => v.deactivate(this.binded!));
|
||||
}
|
||||
this.binded = item;
|
||||
if (item) {
|
||||
this.active.forEach(v => v.activate(item));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 摧毁这个天气控制器
|
||||
*/
|
||||
destroy() {
|
||||
WeatherController.map.delete(this.id);
|
||||
}
|
||||
|
||||
static get(id: string) {
|
||||
return this.map.get(id);
|
||||
}
|
||||
|
||||
static register(id: string, weather: Weather) {
|
||||
this.list.set(id, weather);
|
||||
}
|
||||
}
|
||||
+2
-17
@@ -1,21 +1,6 @@
|
||||
{
|
||||
"name": "@motajs/user",
|
||||
"name": "@user/main",
|
||||
"dependencies": {
|
||||
"@motajs/client": "workspace:*",
|
||||
"@motajs/client-base": "workspace:*",
|
||||
"@motajs/common": "workspace:*",
|
||||
"@motajs/render": "workspace:*",
|
||||
"@motajs/render-core": "workspace:*",
|
||||
"@motajs/render-elements": "workspace:*",
|
||||
"@motajs/render-style": "workspace:*",
|
||||
"@motajs/render-vue": "workspace:*",
|
||||
"@motajs/system": "workspace:*",
|
||||
"@motajs/system-ui": "workspace:*",
|
||||
"@motajs/system-action": "workspace:*",
|
||||
"@motajs/legacy-common": "workspace:*",
|
||||
"@motajs/legacy-client": "workspace:*",
|
||||
"@motajs/legacy-data": "workspace:*",
|
||||
"@motajs/legacy-ui": "workspace:*",
|
||||
"@motajs/legacy-system": "workspace:*"
|
||||
"@user/entry-client": "workspace:*"
|
||||
}
|
||||
}
|
||||
@@ -1,435 +0,0 @@
|
||||
import {
|
||||
MotaOffscreenCanvas2D,
|
||||
RenderItem,
|
||||
RenderItemPosition,
|
||||
Transform
|
||||
} from '@motajs/render';
|
||||
import { IStateDamageable } from '@/game/state/interface';
|
||||
import EventEmitter from 'eventemitter3';
|
||||
import { Ticker } from 'mutate-animate';
|
||||
|
||||
interface BarrageBossEvent {
|
||||
end: [];
|
||||
start: [];
|
||||
}
|
||||
|
||||
export abstract class BarrageBoss extends EventEmitter<BarrageBossEvent> {
|
||||
ticker: Ticker = new Ticker();
|
||||
/** 这个boss的所有弹幕 */
|
||||
projectiles: Set<Projectile> = new Set();
|
||||
|
||||
/** 开始时刻 */
|
||||
private startTime: number = 0;
|
||||
|
||||
/** 当前帧数 */
|
||||
frame: number = 0;
|
||||
/** 上一帧的时刻 */
|
||||
lastTime: number = 0;
|
||||
|
||||
/** 这个boss战的主渲染元素,所有弹幕都会在此之上渲染 */
|
||||
abstract readonly main: BossSprite;
|
||||
/** 这个boss战中勇士的碰撞箱 */
|
||||
abstract readonly hitbox: Hitbox.HitboxType;
|
||||
/** 勇士的状态 */
|
||||
abstract readonly state: IStateDamageable;
|
||||
|
||||
/**
|
||||
* boss的ai,战斗开始后,每帧执行一次
|
||||
* @param time 从战斗开始算起至现在经过了多长时间
|
||||
* @param frame 从战斗开始算起至现在经过了多少帧,即当前是第几帧
|
||||
* @param dt 本帧距上一帧多长时间,即上一帧持续了多长时间
|
||||
*/
|
||||
abstract ai(time: number, frame: number, dt: number): void;
|
||||
|
||||
private tick = () => {
|
||||
const now = Date.now();
|
||||
const dt = now - this.lastTime;
|
||||
this.ai(now - this.startTime, this.frame, dt);
|
||||
this.frame++;
|
||||
this.projectiles.forEach(v => {
|
||||
const time = now - v.startTime;
|
||||
v.time = time;
|
||||
v.ai(this, time, v.frame, dt);
|
||||
v.frame++;
|
||||
if (time > 60_000) {
|
||||
this.destroyProjectile(v);
|
||||
}
|
||||
if (v.isIntersect(this.hitbox)) {
|
||||
v.doDamage(this.state);
|
||||
}
|
||||
});
|
||||
this.lastTime = now;
|
||||
};
|
||||
|
||||
/**
|
||||
* 开始这个弹幕战
|
||||
*/
|
||||
start() {
|
||||
if (this.ticker.funcs.has(this.tick)) {
|
||||
this.ticker.remove(this.tick);
|
||||
}
|
||||
this.startTime = Date.now();
|
||||
this.frame = 0;
|
||||
this.ticker.add(this.tick);
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束这个弹幕战
|
||||
*/
|
||||
end() {
|
||||
if (this.ticker.funcs.has(this.tick)) {
|
||||
this.ticker.remove(this.tick);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 摧毁传入的弹幕
|
||||
*/
|
||||
destroyProjectile(projectile: Projectile) {
|
||||
this.projectiles.delete(projectile);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用于创建一个弹幕的工厂函数
|
||||
* @param Proj 弹幕类
|
||||
* @param x 弹幕的横坐标
|
||||
* @param y 弹幕的纵坐标
|
||||
*/
|
||||
createProjectile<T extends Projectile>(
|
||||
Proj: new (boss: this) => T,
|
||||
x: number,
|
||||
y: number
|
||||
): T {
|
||||
const projectile = new Proj(this);
|
||||
projectile.setPosition(x, y);
|
||||
return projectile;
|
||||
}
|
||||
}
|
||||
|
||||
export class BossSprite<
|
||||
T extends BarrageBoss = BarrageBoss
|
||||
> extends RenderItem {
|
||||
/** 这个sprite所属的boss */
|
||||
readonly boss: T;
|
||||
|
||||
constructor(type: RenderItemPosition, boss: T) {
|
||||
super(type, false);
|
||||
this.boss = boss;
|
||||
}
|
||||
|
||||
/**
|
||||
* override 此方法来实现自定义渲染,默认会调用 {@link renderProjectiles} 方法。
|
||||
* 关于本方法,参考 {@link RenderItem.render}
|
||||
* @param canvas 渲染至的目标画布
|
||||
* @param transform 当前画布相对于父元素的变换矩阵
|
||||
*/
|
||||
protected render(
|
||||
canvas: MotaOffscreenCanvas2D,
|
||||
transform: Transform
|
||||
): void {
|
||||
this.renderProjectiles(canvas, transform);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染所有弹幕
|
||||
* @param canvas 渲染至的画布
|
||||
* @param transform 渲染时的变换矩阵
|
||||
*/
|
||||
protected renderProjectiles(
|
||||
canvas: MotaOffscreenCanvas2D,
|
||||
transform: Transform
|
||||
) {
|
||||
this.boss.projectiles.forEach(v => {
|
||||
v.render(canvas, transform);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class Projectile<T extends BarrageBoss = BarrageBoss> {
|
||||
/** 这个弹幕从属的boss */
|
||||
boss: T;
|
||||
/** 这个弹幕的伤害 */
|
||||
abstract damage: number;
|
||||
|
||||
private _x: number = 0;
|
||||
get x(): number {
|
||||
return this._x;
|
||||
}
|
||||
set x(v: number) {
|
||||
this._x = v;
|
||||
this.updateHitbox(v, this._y);
|
||||
}
|
||||
|
||||
private _y: number = 0;
|
||||
get y(): number {
|
||||
return this._y;
|
||||
}
|
||||
set y(v: number) {
|
||||
this._y = v;
|
||||
this.updateHitbox(this._x, v);
|
||||
}
|
||||
|
||||
/** 弹幕的生成时刻 */
|
||||
startTime: number = Date.now();
|
||||
/** 弹幕当前帧数 */
|
||||
frame: number = 0;
|
||||
/** 当前弹幕持续时长 */
|
||||
time: number = 0;
|
||||
|
||||
/** 这个弹幕的碰撞箱 */
|
||||
abstract hitbox: Hitbox.HitboxType;
|
||||
|
||||
constructor(boss: T) {
|
||||
this.boss = boss;
|
||||
boss.projectiles.add(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一个碰撞箱是否与本弹幕的碰撞箱有交叉。
|
||||
* 此判断应该具有对称性,如果用A检测B发生碰撞,那么用B检测A也应该发生碰撞。
|
||||
* @param hitbox 要检测的碰撞箱
|
||||
*/
|
||||
abstract isIntersect(hitbox: Hitbox.HitboxType): boolean;
|
||||
|
||||
/**
|
||||
* 当弹幕的横纵坐标改变时,更新碰撞箱
|
||||
* @param x 弹幕的横坐标
|
||||
* @param y 弹幕的纵坐标
|
||||
*/
|
||||
abstract updateHitbox(x: number, y: number): void;
|
||||
|
||||
/**
|
||||
* 对一个目标造成伤害
|
||||
* @param target 伤害目标
|
||||
* @returns 是否成功对目标造成伤害
|
||||
*/
|
||||
abstract doDamage(target: IStateDamageable): boolean;
|
||||
|
||||
/**
|
||||
* 设置这个弹幕的位置
|
||||
*/
|
||||
setPosition(x: number, y: number) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.updateHitbox(x, y);
|
||||
}
|
||||
|
||||
/**
|
||||
* 这个弹幕的ai,每帧执行一次,直至被销毁,在1分钟后会强制被摧毁
|
||||
* @param boss 从属的boss
|
||||
* @param time 从弹幕生成开始算起至现在经过了多长时间
|
||||
* @param frame 从弹幕生成开始算起至现在经过了多少帧,即当前是第几帧
|
||||
* @param dt 本帧距上一帧多长时间,即上一帧持续了多长时间
|
||||
*/
|
||||
abstract ai(boss: T, time: number, frame: number, dt: number): void;
|
||||
|
||||
/**
|
||||
* 这个弹幕的渲染函数,原则上一个boss的弹幕应该全部画在同一层,而且渲染前画布不进行矩阵变换
|
||||
* @param canvas 渲染至的画布
|
||||
* @param transform 渲染时的变换矩阵
|
||||
*/
|
||||
abstract render(canvas: MotaOffscreenCanvas2D, transform: Transform): void;
|
||||
|
||||
/**
|
||||
* 摧毁这个弹幕
|
||||
*/
|
||||
destroy() {
|
||||
this.boss.destroyProjectile(this);
|
||||
}
|
||||
}
|
||||
|
||||
export namespace Hitbox {
|
||||
export type HitboxType = Line | Rect | Circle;
|
||||
|
||||
export class Line {
|
||||
constructor(
|
||||
public x1: number,
|
||||
public y1: number,
|
||||
public x2: number,
|
||||
public y2: number
|
||||
) {}
|
||||
|
||||
setPoint1(x: number, y: number) {
|
||||
this.x1 = x;
|
||||
this.y1 = y;
|
||||
}
|
||||
|
||||
setPoint2(x: number, y: number) {
|
||||
this.x2 = x;
|
||||
this.y2 = y;
|
||||
}
|
||||
}
|
||||
|
||||
export class Circle {
|
||||
constructor(
|
||||
public x: number,
|
||||
public y: number,
|
||||
public radius: number
|
||||
) {}
|
||||
|
||||
setRadius(radius: number) {
|
||||
this.radius = radius;
|
||||
}
|
||||
|
||||
setCenter(x: number, y: number) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
}
|
||||
|
||||
export class Rect {
|
||||
constructor(
|
||||
public x: number,
|
||||
public y: number,
|
||||
public w: number,
|
||||
public h: number
|
||||
) {}
|
||||
|
||||
setPosition(x: number, y: number) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
setSize(w: number, h: number) {
|
||||
this.w = w;
|
||||
this.h = h;
|
||||
}
|
||||
}
|
||||
|
||||
function cross(
|
||||
x1: number,
|
||||
y1: number,
|
||||
x2: number,
|
||||
y2: number,
|
||||
x3: number,
|
||||
y3: number
|
||||
): number {
|
||||
const dx1 = x2 - x1;
|
||||
const dy1 = y2 - y1;
|
||||
const dx2 = x3 - x1;
|
||||
const dy2 = y3 - y1;
|
||||
return dx1 * dy2 - dx2 * dy1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查两条线段是否有交叉
|
||||
*/
|
||||
export function checkLineLine(line1: Line, line2: Line) {
|
||||
const { x1, y1, x2, y2 } = line1;
|
||||
const { x1: x3, y1: y3, x2: x4, y2: y4 } = line2;
|
||||
|
||||
if (
|
||||
Math.max(x1, x2) < Math.min(x3, x4) ||
|
||||
Math.min(x1, x2) > Math.max(x3, x4) ||
|
||||
Math.max(y1, y2) < Math.min(y3, y4) ||
|
||||
Math.min(y1, y2) > Math.max(y3, y4)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const d1 = cross(x1, y1, x2, y2, x3, y3);
|
||||
const d2 = cross(x1, y1, x2, y2, x4, y4);
|
||||
const d3 = cross(x3, y3, x4, y4, x1, y1);
|
||||
const d4 = cross(x3, y3, x4, y4, x2, y2);
|
||||
|
||||
return d1 * d2 < 0 && d3 * d4 < 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查线段和圆是否有交叉
|
||||
*/
|
||||
export function checkLineCircle(line: Line, circle: Circle) {
|
||||
const { x1, y1, x2, y2 } = line;
|
||||
const { x: cx, y: cy, radius: r } = circle;
|
||||
const minX = Math.min(x1, x2);
|
||||
const maxX = Math.max(x1, x2);
|
||||
const minY = Math.min(y1, y2);
|
||||
const maxY = Math.max(y1, y2);
|
||||
|
||||
// 检查圆心是否在扩展后的矩形范围之外
|
||||
if (cx + r < minX || cx - r > maxX || cy + r < minY || cy - r > maxY) {
|
||||
return false; // 完全不相交
|
||||
}
|
||||
|
||||
// 计算线段的方向向量
|
||||
const dx = x2 - x1;
|
||||
const dy = y2 - y1;
|
||||
|
||||
// A, B, C 对应二次方程的系数
|
||||
const a = dx * dx + dy * dy;
|
||||
const b = 2 * (dx * (x1 - cx) + dy * (y1 - cy));
|
||||
const c = (x1 - cx) * (x1 - cx) + (y1 - cy) * (y1 - cy) - r * r;
|
||||
|
||||
// 计算判别式 Δ
|
||||
const discriminant = b ** 2 - 4 * a * c;
|
||||
|
||||
// 如果判别式小于0,则没有交点
|
||||
if (discriminant < 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 计算t的解(参数化线段的参数)
|
||||
const sqrtDiscriminant = Math.sqrt(discriminant);
|
||||
const t1 = (-b - sqrtDiscriminant) / (2 * a);
|
||||
const t2 = (-b + sqrtDiscriminant) / (2 * a);
|
||||
|
||||
// 检查 t1 和 t2 是否在 [0, 1] 之间
|
||||
if ((t1 >= 0 && t1 <= 1) || (t2 >= 0 && t2 <= 1)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 否则没有交点在线段上
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查线段与矩形是否有交叉
|
||||
*/
|
||||
export function checkLineRect(line: Line, rect: Rect) {
|
||||
const { x, y, w, h } = rect;
|
||||
return (
|
||||
checkLineLine(line, new Line(x, y, x + w, y + h)) ||
|
||||
checkLineLine(line, new Line(x + w, y, x, y + h))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查两个圆是否有交叉
|
||||
*/
|
||||
export function checkCircleCircle(circle1: Circle, circle2: Circle) {
|
||||
const dx = circle1.x - circle2.x;
|
||||
const dy = circle1.y - circle2.y;
|
||||
const dis = dx ** 2 + dy ** 2;
|
||||
return dis <= (circle1.radius + circle2.radius) ** 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查圆与矩形是否有交叉
|
||||
*/
|
||||
export function checkCircleRect(circle: Circle, rect: Rect) {
|
||||
const { x: cx, y: cy, radius: r } = circle;
|
||||
const { x, y, w, h } = rect;
|
||||
|
||||
if (cx > x && cx < x + w && cy > y && cy < y + h) return true;
|
||||
|
||||
// 找到圆心到矩形的最近点
|
||||
const closestX = Math.max(x, Math.min(cx, x + w));
|
||||
const closestY = Math.max(y, Math.min(cy, y + h));
|
||||
|
||||
return Math.hypot(closestX - cx, closestY - cy) <= r;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查两个矩形是否有交叉
|
||||
*/
|
||||
export function checkRectRect(rect1: Rect, rect2: Rect) {
|
||||
const { x: x1, y: y1, w: w1, h: h1 } = rect1;
|
||||
const { x: x3, y: y3, w: w2, h: h2 } = rect2;
|
||||
const x2 = x1 + w1;
|
||||
const y2 = y1 + h1;
|
||||
const x4 = x3 + w2;
|
||||
const y4 = y3 + h2;
|
||||
|
||||
return x2 >= x3 && x4 >= x1 && y2 >= y3 && y4 >= y1;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import { BarrageBoss } from './barrage';
|
||||
import { TowerBoss } from './towerBoss';
|
||||
|
||||
let boss: BarrageBoss | null;
|
||||
|
||||
export function startTowerBoss() {
|
||||
boss = new TowerBoss();
|
||||
boss.start();
|
||||
boss.once('end', () => {
|
||||
boss = null;
|
||||
});
|
||||
}
|
||||
|
||||
export function getBoss<T extends BarrageBoss>(): T | null {
|
||||
return boss as T;
|
||||
}
|
||||
|
||||
Mota.require('var', 'hook').on('reset', () => {
|
||||
if (boss) {
|
||||
boss.end();
|
||||
}
|
||||
});
|
||||
@@ -1,130 +0,0 @@
|
||||
import { IStateDamageable } from '@/game/state/interface';
|
||||
import { BarrageBoss, BossSprite, Hitbox } from './barrage';
|
||||
import {
|
||||
Container,
|
||||
LayerGroup,
|
||||
MotaRenderer,
|
||||
RenderItem,
|
||||
Shader,
|
||||
Transform,
|
||||
MotaOffscreenCanvas2D
|
||||
} from '@motajs/render';
|
||||
import { Pop } from '../fx/pop';
|
||||
import { SplittableBall } from './palaceBossProjectile';
|
||||
import { PointEffect } from '../fx/pointShader';
|
||||
|
||||
Mota.require('var', 'loading').once('coreInit', () => {
|
||||
const shader = new Shader();
|
||||
shader.size(480, 480);
|
||||
shader.setHD(true);
|
||||
shader.setZIndex(120);
|
||||
PalaceBoss.shader = shader;
|
||||
PalaceBoss.effect.create(shader, 40);
|
||||
});
|
||||
|
||||
const enum BossStage {
|
||||
Prologue,
|
||||
|
||||
Stage1,
|
||||
Stage2,
|
||||
Stage3,
|
||||
Stage4,
|
||||
|
||||
End
|
||||
}
|
||||
|
||||
export class PalaceBoss extends BarrageBoss {
|
||||
static effect: PointEffect = new PointEffect();
|
||||
static shader: Shader;
|
||||
|
||||
main: BossSprite<BarrageBoss>;
|
||||
hitbox: Hitbox.Circle;
|
||||
state: IStateDamageable;
|
||||
|
||||
private stage: BossStage = BossStage.Prologue;
|
||||
|
||||
/** 用于展示傅里叶频谱的背景元素 */
|
||||
private back: SonicBack;
|
||||
/** 楼层渲染元素 */
|
||||
private group: LayerGroup;
|
||||
/** 楼层渲染容器 */
|
||||
private mapDraw: Container;
|
||||
/** 伤害弹出 */
|
||||
pop: Pop;
|
||||
|
||||
private heroHp: number = 0;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
const render = MotaRenderer.get('render-main')!;
|
||||
this.group = render.getElementById('layer-main') as LayerGroup;
|
||||
this.mapDraw = render.getElementById('map-draw') as Container;
|
||||
this.pop = render.getElementById('pop-main') as Pop;
|
||||
|
||||
this.state = core.status.hero;
|
||||
this.main = new BossEffect('static', this);
|
||||
this.back = new SonicBack('static');
|
||||
const { x, y } = core.status.hero.loc;
|
||||
const cell = 32;
|
||||
this.hitbox = new Hitbox.Circle(x + cell / 2, y + cell / 2, cell / 3);
|
||||
}
|
||||
|
||||
override start(): void {
|
||||
super.start();
|
||||
|
||||
PalaceBoss.shader.append(this.mapDraw);
|
||||
this.main.append(this.group);
|
||||
|
||||
// const event = this.group.getLayer('event');
|
||||
// const hero = event?.getExtends('floor-hero') as HeroRenderer;
|
||||
// hero?.on('moveTick', this.moveTick);
|
||||
|
||||
SplittableBall.init({});
|
||||
this.heroHp = core.status.hero.hp;
|
||||
}
|
||||
|
||||
override end(): void {
|
||||
super.end();
|
||||
|
||||
PalaceBoss.shader.remove();
|
||||
this.main.remove();
|
||||
this.back.remove();
|
||||
this.main.destroy();
|
||||
this.back.destroy();
|
||||
|
||||
// const event = this.group.getLayer('event');
|
||||
// const hero = event?.getExtends('floor-hero') as HeroRenderer;
|
||||
// hero?.off('moveTick', this.moveTick);
|
||||
|
||||
SplittableBall.end();
|
||||
|
||||
PalaceBoss.effect.end();
|
||||
core.status.hero.hp = this.heroHp;
|
||||
|
||||
Mota.Plugin.require('replay_g').clip('choices:0');
|
||||
}
|
||||
|
||||
ai(time: number, frame: number): void {}
|
||||
}
|
||||
|
||||
class BossEffect extends BossSprite<PalaceBoss> {
|
||||
protected preDraw(
|
||||
canvas: MotaOffscreenCanvas2D,
|
||||
transform: Transform
|
||||
): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
protected postDraw(
|
||||
canvas: MotaOffscreenCanvas2D,
|
||||
transform: Transform
|
||||
): void {}
|
||||
}
|
||||
|
||||
class SonicBack extends RenderItem {
|
||||
protected render(
|
||||
canvas: MotaOffscreenCanvas2D,
|
||||
transform: Transform
|
||||
): void {}
|
||||
}
|
||||
@@ -1,270 +0,0 @@
|
||||
import { Transform, MotaOffscreenCanvas2D } from '@motajs/render';
|
||||
import { IStateDamageable } from '@/game/state/interface';
|
||||
import { Hitbox, Projectile } from './barrage';
|
||||
import type { PalaceBoss } from './palaceBoss';
|
||||
import { clamp } from '@motajs/legacy-ui';
|
||||
|
||||
function popDamage(damage: number, boss: PalaceBoss, color: string) {
|
||||
const { x, y } = core.status.hero.loc;
|
||||
boss.pop.addPop(
|
||||
(-damage).toString(),
|
||||
1000,
|
||||
x * 32 + 16,
|
||||
y * 32 + 16,
|
||||
color
|
||||
);
|
||||
}
|
||||
|
||||
export interface ISplitData {
|
||||
split: boolean;
|
||||
/** 分裂时刻,以弹幕被创建时刻为基准 */
|
||||
time: number;
|
||||
/** 分裂起始角度,以该弹幕朝向方向为 0 */
|
||||
startAngle: number;
|
||||
/** 分裂终止角度,以该弹幕朝向方向为 0 */
|
||||
endAngle: number;
|
||||
/** 每秒加速度 */
|
||||
acc: number;
|
||||
/** 初始速度 */
|
||||
startVel: number;
|
||||
/** 终止速度 */
|
||||
endVel: number;
|
||||
/** 持续时长 */
|
||||
lastTime: number;
|
||||
/** 分裂数量 */
|
||||
count: number;
|
||||
/** 这个弹幕分裂产生的弹幕的分裂信息,不填则表示产生的弹幕不会分裂 */
|
||||
data?: ISplitData;
|
||||
}
|
||||
|
||||
export class SplittableBall extends Projectile<PalaceBoss> {
|
||||
damage: number = 10000;
|
||||
hitbox: Hitbox.Circle = new Hitbox.Circle(0, 0, 8);
|
||||
|
||||
static ball: Map<string, MotaOffscreenCanvas2D> = new Map();
|
||||
|
||||
private damaged: boolean = false;
|
||||
private splitData?: ISplitData;
|
||||
private last: number = 60_000;
|
||||
|
||||
/** 角度,水平向右为 0,顺时针旋转一圈为 Math.PI * 2 */
|
||||
private angle: number = 0;
|
||||
/** 每秒加速度 */
|
||||
private acc: number = 0;
|
||||
/** 初始速度,每秒多少像素 */
|
||||
private startVel: number = 0;
|
||||
/** 终止速度 */
|
||||
private endVel: number = 0;
|
||||
/** 弹幕颜色 */
|
||||
private color?: string;
|
||||
|
||||
private startVelX: number = 0;
|
||||
private startVelY: number = 0;
|
||||
private endVelX: number = 0;
|
||||
private endVelY: number = 0;
|
||||
private vx: number = 0;
|
||||
private vy: number = 0;
|
||||
// 加速度
|
||||
private ax: number = 0;
|
||||
private ay: number = 0;
|
||||
|
||||
/** 是否已经分裂过 */
|
||||
private splitted: boolean = false;
|
||||
|
||||
static init(colors: Record<string, string[]>) {
|
||||
this.ball.clear();
|
||||
for (const [key, color] of Object.entries(colors)) {
|
||||
const canvas = new MotaOffscreenCanvas2D();
|
||||
canvas.size(32, 32);
|
||||
canvas.withGameScale(true);
|
||||
canvas.setHD(true);
|
||||
const ctx = canvas.ctx;
|
||||
const gradient = ctx.createRadialGradient(16, 16, 8, 16, 16, 16);
|
||||
const step = 1 / (color.length - 1);
|
||||
for (let i = 0; i < color.length; i++) {
|
||||
gradient.addColorStop(i * step, color[i]);
|
||||
}
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.arc(16, 16, 16, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
canvas.freeze();
|
||||
this.ball.set(key, canvas);
|
||||
}
|
||||
}
|
||||
|
||||
static end() {
|
||||
this.ball.forEach(v => {
|
||||
v.clear();
|
||||
v.delete();
|
||||
});
|
||||
this.ball.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置持续时长
|
||||
* @param time 持续时长
|
||||
*/
|
||||
setLastTime(time: number) {
|
||||
this.last = time;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置这个弹幕的分裂数据
|
||||
* @param data 分裂数据,不填表示该弹幕不会分裂
|
||||
*/
|
||||
setSplitData(data?: ISplitData) {
|
||||
this.splitData = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算速度分量信息
|
||||
*/
|
||||
private calVel() {
|
||||
const sin = Math.sin(this.angle);
|
||||
const cos = Math.cos(this.angle);
|
||||
const vel = Math.hypot(this.vx, this.vy);
|
||||
|
||||
this.startVelX = this.startVel * cos;
|
||||
this.startVelY = this.startVel * sin;
|
||||
this.endVelX = this.endVel * cos;
|
||||
this.endVelY = this.endVel * sin;
|
||||
this.ax = this.acc * cos;
|
||||
this.ay = this.acc * sin;
|
||||
this.vx = vel * cos;
|
||||
this.vy = vel * sin;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置弹幕速度朝向
|
||||
* @param angle 朝向
|
||||
*/
|
||||
setAngle(angle: number) {
|
||||
this.angle = angle;
|
||||
this.calVel();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置速度
|
||||
* @param start 起始速度
|
||||
* @param end 终止速度
|
||||
*/
|
||||
setVel(start: number, end: number) {
|
||||
this.startVel = start;
|
||||
this.endVel = end;
|
||||
this.calVel();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置加速度
|
||||
* @param acc 加速度,每秒加速多少像素
|
||||
*/
|
||||
setAcc(acc: number) {
|
||||
this.acc = acc;
|
||||
this.calVel();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置弹幕的颜色
|
||||
* @param color 颜色
|
||||
*/
|
||||
setColor(color: string) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
isIntersect(hitbox: Hitbox.HitboxType): boolean {
|
||||
if (hitbox instanceof Hitbox.Circle) {
|
||||
return Hitbox.checkCircleCircle(hitbox, this.hitbox);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
updateHitbox(x: number, y: number): void {
|
||||
this.hitbox.setCenter(x, y);
|
||||
}
|
||||
|
||||
doDamage(target: IStateDamageable): boolean {
|
||||
if (this.damaged) return false;
|
||||
target.hp -= this.damage;
|
||||
this.damaged = true;
|
||||
core.drawHeroAnimate('hand');
|
||||
popDamage(this.damage, this.boss, '#ff8180');
|
||||
return true;
|
||||
}
|
||||
|
||||
private split(boss: PalaceBoss) {
|
||||
if (!this.splitData?.split) return;
|
||||
if (this.splitted) return;
|
||||
this.splitted = true;
|
||||
const {
|
||||
startAngle,
|
||||
endAngle,
|
||||
startVel,
|
||||
endVel,
|
||||
acc,
|
||||
lastTime,
|
||||
count,
|
||||
data
|
||||
} = this.splitData;
|
||||
|
||||
const sa = this.angle + startAngle;
|
||||
const ea = this.angle + endAngle;
|
||||
const step = (ea - sa - 1) / count;
|
||||
const { x, y } = this.hitbox;
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const proj = boss.createProjectile(SplittableBall, x, y);
|
||||
proj.setAngle(sa + step * i);
|
||||
proj.setAcc(acc);
|
||||
proj.setVel(startVel, endVel);
|
||||
proj.setLastTime(lastTime);
|
||||
proj.setSplitData(data);
|
||||
}
|
||||
}
|
||||
|
||||
ai(boss: PalaceBoss, time: number, _frame: number, dt: number): void {
|
||||
if (this.splitData?.split) {
|
||||
if (time > this.splitData.time) {
|
||||
this.split(boss);
|
||||
}
|
||||
}
|
||||
if (time > this.last) {
|
||||
this.destroy();
|
||||
return;
|
||||
}
|
||||
const p = dt / 1000;
|
||||
this.vx += this.ax * p;
|
||||
this.vy += this.ay * p;
|
||||
|
||||
const sx = Math.sign(this.vx);
|
||||
const sy = Math.sign(this.vy);
|
||||
const cx = clamp(
|
||||
Math.abs(this.vx),
|
||||
Math.abs(this.startVelX),
|
||||
Math.abs(this.endVelX)
|
||||
);
|
||||
const cy = clamp(
|
||||
Math.abs(this.vy),
|
||||
Math.abs(this.startVelY),
|
||||
Math.abs(this.endVelY)
|
||||
);
|
||||
this.vx = cx * sx;
|
||||
this.vy = cy * sy;
|
||||
|
||||
const { x, y } = this.hitbox;
|
||||
this.setPosition(x + this.vx * p, y + this.vy * p);
|
||||
}
|
||||
|
||||
render(canvas: MotaOffscreenCanvas2D, _transform: Transform): void {
|
||||
if (!this.color) return;
|
||||
const texture = SplittableBall.ball.get(this.color);
|
||||
if (!texture) return;
|
||||
const ctx = canvas.ctx;
|
||||
ctx.drawImage(texture.canvas, this.x - 16, this.y - 16, 32, 32);
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.split(this.boss);
|
||||
super.destroy();
|
||||
}
|
||||
}
|
||||
@@ -1,846 +0,0 @@
|
||||
import {
|
||||
Shader,
|
||||
MotaRenderer,
|
||||
LayerGroup,
|
||||
RenderItem,
|
||||
MotaOffscreenCanvas2D,
|
||||
Container,
|
||||
HeroRenderer
|
||||
} from '@motajs/render';
|
||||
import { PointEffect } from '../fx/pointShader';
|
||||
import { BarrageBoss, BossSprite, Hitbox } from './barrage';
|
||||
import { Animation, hyper, power, sleep, Transition } from 'mutate-animate';
|
||||
import {
|
||||
ArrowProjectile,
|
||||
AttackProjectile,
|
||||
BoomProjectile,
|
||||
ChainProjectile,
|
||||
IceProjectile,
|
||||
PortalProjectile,
|
||||
ProjectileDirection,
|
||||
ThunderBallProjectile,
|
||||
ThunderProjectile
|
||||
} from './towerBossProjectile';
|
||||
import { IStateDamageable } from '@/game/state/interface';
|
||||
import { Pop } from '../fx/pop';
|
||||
import { WeatherController } from '@/module';
|
||||
|
||||
Mota.require('var', 'loading').once('coreInit', () => {
|
||||
const shader = new Shader();
|
||||
shader.size(480, 480);
|
||||
shader.setHD(true);
|
||||
shader.setZIndex(120);
|
||||
TowerBoss.shader = shader;
|
||||
TowerBoss.effect.create(shader, 40);
|
||||
});
|
||||
|
||||
const enum TowerBossStage {
|
||||
/** 开场白阶段 */
|
||||
Prologue,
|
||||
|
||||
Stage1,
|
||||
Dialogue1,
|
||||
Stage2,
|
||||
Dialogue2,
|
||||
Stage3,
|
||||
Stage4,
|
||||
Stage5,
|
||||
|
||||
End
|
||||
}
|
||||
|
||||
const enum HealthBarStatus {
|
||||
Start,
|
||||
Running,
|
||||
End
|
||||
}
|
||||
|
||||
export class TowerBoss extends BarrageBoss {
|
||||
static effect: PointEffect = new PointEffect();
|
||||
static shader: Shader;
|
||||
|
||||
/** boss战阶段 */
|
||||
stage: TowerBossStage = TowerBossStage.Prologue;
|
||||
/** 当前boss血量 */
|
||||
hp: number = 10000;
|
||||
/** 当前时刻 */
|
||||
time: number = 0;
|
||||
|
||||
readonly hitbox: Hitbox.Rect;
|
||||
readonly state: IStateDamageable;
|
||||
readonly main: BossSprite;
|
||||
|
||||
/** 血条显示元素 */
|
||||
private healthBar: HealthBar;
|
||||
/** 对话文字显示元素 */
|
||||
private word: Word;
|
||||
/** 楼层渲染元素 */
|
||||
private group: LayerGroup;
|
||||
/** 楼层渲染容器 */
|
||||
private mapDraw: Container;
|
||||
/** 伤害弹出 */
|
||||
pop: Pop;
|
||||
|
||||
/** 每个阶段的进度,具体定义参考 ai 函数开头 */
|
||||
private stageProgress: number = 0;
|
||||
/** 当前阶段的开始时刻 */
|
||||
private stageStartTime: number = 0;
|
||||
/** 每一阶段的攻击boss次数 */
|
||||
private attackTime: number = 0;
|
||||
/** 攻击boss的红圈间隔时长 */
|
||||
private attackInterval: number = 7000;
|
||||
|
||||
/** 使用技能1 智慧之矢 的次数 */
|
||||
private skill1Time: number = 0;
|
||||
/** 使用技能2 随机传送 的次数 */
|
||||
private skill2Time: number = 0;
|
||||
/** 使用技能3 冰锥 的次数 */
|
||||
private skill3Time: number = 0;
|
||||
/** 技能1的释放间隔 */
|
||||
private skill1Interval: number = 10000;
|
||||
/** 技能2的释放间隔 */
|
||||
private skill2Interval: number = 7000;
|
||||
/** 技能3的释放间隔 */
|
||||
private skill3Interval: number = 13000;
|
||||
|
||||
/** 使用技能4 随机闪电 的次数 */
|
||||
private skill4Time: number = 0;
|
||||
/** 使用技能5 球形闪电 的次数 */
|
||||
private skill5Time: number = 0;
|
||||
/** 技能4的释放间隔 */
|
||||
private skill4Interval: number = 4000;
|
||||
/** 技能5的释放间隔 */
|
||||
private skill5Interval: number = 12000;
|
||||
|
||||
/** 使用技能6 炸弹 的次数 */
|
||||
private skill6Time: number = 0;
|
||||
/** 使用技能7 连锁闪电 的次数 */
|
||||
private skill7Time: number = 0;
|
||||
/** 技能6的释放间隔 */
|
||||
private skill6Interval: number = 500;
|
||||
/** 技能7的释放间隔 */
|
||||
private skill7Interval: number = 10000;
|
||||
|
||||
private heroHp: number = 0;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.healthBar = new HealthBar('absolute');
|
||||
this.word = new Word('absolute');
|
||||
this.main = new BossSprite('absolute', this);
|
||||
const render = MotaRenderer.get('render-main')!;
|
||||
this.group = render.getElementById('layer-main') as LayerGroup;
|
||||
this.mapDraw = render.getElementById('map-draw') as Container;
|
||||
this.pop = render.getElementById('pop-main') as Pop;
|
||||
|
||||
this.healthBar.init();
|
||||
this.word.init();
|
||||
this.main.size(480, 480);
|
||||
this.main.setHD(true);
|
||||
this.main.setZIndex(80);
|
||||
|
||||
TowerBoss.effect.setTransform(this.group.camera);
|
||||
|
||||
const { x, y } = core.status.hero.loc;
|
||||
const cell = 32;
|
||||
this.hitbox = new Hitbox.Rect(x * cell + 2, y * cell + 2, 28, 28);
|
||||
this.state = core.status.hero;
|
||||
}
|
||||
|
||||
private moveTick = (x: number, y: number) => {
|
||||
this.hitbox.setPosition(x * 32 + 2, y * 32 + 2);
|
||||
};
|
||||
|
||||
override start() {
|
||||
super.start();
|
||||
|
||||
TowerBoss.shader.append(this.mapDraw);
|
||||
this.healthBar.append(this.group);
|
||||
this.word.append(this.group);
|
||||
this.main.append(this.group);
|
||||
|
||||
const event = this.group.getLayer('event');
|
||||
const hero = event?.getExtends('floor-hero') as HeroRenderer;
|
||||
hero?.on('moveTick', this.moveTick);
|
||||
|
||||
ArrowProjectile.init();
|
||||
PortalProjectile.init();
|
||||
ThunderProjectile.init();
|
||||
ThunderBallProjectile.init();
|
||||
AttackProjectile.init();
|
||||
|
||||
TowerBoss.effect.start();
|
||||
TowerBoss.effect.use();
|
||||
|
||||
this.heroHp = core.status.hero.hp;
|
||||
}
|
||||
|
||||
override end() {
|
||||
super.end();
|
||||
TowerBoss.shader.remove();
|
||||
this.healthBar.remove();
|
||||
this.word.remove();
|
||||
this.main.remove();
|
||||
this.main.destroy();
|
||||
this.healthBar.destroy();
|
||||
|
||||
const event = this.group.getLayer('event');
|
||||
const hero = event?.getExtends('floor-hero') as HeroRenderer;
|
||||
hero?.off('moveTick', this.moveTick);
|
||||
|
||||
ArrowProjectile.end();
|
||||
PortalProjectile.end();
|
||||
ThunderProjectile.end();
|
||||
ThunderBallProjectile.end();
|
||||
AttackProjectile.end();
|
||||
|
||||
TowerBoss.effect.end();
|
||||
core.status.hero.hp = this.heroHp;
|
||||
|
||||
Mota.Plugin.require('replay_g').clip('choices:0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 用于全局检测,例如受伤、攻击boss等
|
||||
*/
|
||||
check(_time: number) {
|
||||
this.checkLose();
|
||||
}
|
||||
|
||||
private checkLose() {
|
||||
if (core.status.hero.hp < 0) {
|
||||
core.lose();
|
||||
core.updateStatusBar();
|
||||
this.end();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 攻击boss
|
||||
* @param damage 造成的伤害
|
||||
*/
|
||||
attackBoss(damage: number) {
|
||||
this.hp -= damage;
|
||||
if (this.hp < 0) this.hp = 0;
|
||||
this.healthBar.set(this.hp);
|
||||
// 先用drawAnimate凑活一下,等下个版本提供更好的 api
|
||||
if (this.stage === TowerBossStage.Stage3) {
|
||||
core.drawAnimate('hand', 7, 2);
|
||||
this.pop.addPop((-damage).toString(), 1000, 240, 80, '#dafc1d');
|
||||
} else if (this.stage === TowerBossStage.Stage4) {
|
||||
core.drawAnimate('hand', 7, 3);
|
||||
this.pop.addPop((-damage).toString(), 1000, 240, 112, '#dafc1d');
|
||||
} else if (this.stage === TowerBossStage.Stage5) {
|
||||
core.drawAnimate('hand', 7, 4);
|
||||
this.pop.addPop((-damage).toString(), 1000, 240, 144, '#dafc1d');
|
||||
} else {
|
||||
core.drawAnimate('hand', 7, 1);
|
||||
this.pop.addPop((-damage).toString(), 1000, 240, 172, '#dafc1d');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加攻击boss的圆圈
|
||||
* @param last 持续时长
|
||||
* @param damage 造成的伤害
|
||||
*/
|
||||
addAttackCircle(_: number, n: number) {
|
||||
const s = 13 - n * 2;
|
||||
const nx = Math.floor(Math.random() * s + n + 1);
|
||||
const ny = Math.floor(Math.random() * s + n + 1);
|
||||
const proj = this.createProjectile(AttackProjectile, nx * 32, ny * 32);
|
||||
proj.damage = 250 + Math.floor(Math.random() * 500);
|
||||
}
|
||||
|
||||
ai(time: number, frame: number): void {
|
||||
this.time = time;
|
||||
const fixedTime = time - this.stageStartTime;
|
||||
this.main.update();
|
||||
this.check(time);
|
||||
TowerBoss.effect.requestUpdate();
|
||||
switch (this.stage) {
|
||||
case TowerBossStage.Prologue:
|
||||
this.aiPrologue(fixedTime, frame);
|
||||
break;
|
||||
case TowerBossStage.Stage1:
|
||||
this.aiStage1(fixedTime, frame);
|
||||
break;
|
||||
case TowerBossStage.Dialogue1:
|
||||
this.aiDialogue1(fixedTime, frame);
|
||||
break;
|
||||
case TowerBossStage.Stage2:
|
||||
this.aiStage2(fixedTime, frame);
|
||||
break;
|
||||
case TowerBossStage.Dialogue2:
|
||||
this.aiDialogue2(fixedTime, frame);
|
||||
break;
|
||||
case TowerBossStage.Stage3:
|
||||
this.aiStage3(fixedTime, frame);
|
||||
break;
|
||||
case TowerBossStage.Stage4:
|
||||
this.aiStage4(fixedTime, frame);
|
||||
break;
|
||||
case TowerBossStage.Stage5:
|
||||
this.aiStage5(fixedTime, frame);
|
||||
break;
|
||||
case TowerBossStage.End:
|
||||
this.aiEnd(fixedTime, frame);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换boss阶段
|
||||
* @param stage 切换至的阶段
|
||||
* @param time 在当前阶段经过的时间
|
||||
*/
|
||||
private changeStage(stage: TowerBossStage, time: number) {
|
||||
this.stage = stage;
|
||||
this.stageStartTime += time;
|
||||
this.stageProgress = 0;
|
||||
}
|
||||
|
||||
private aiPrologue(time: number, _frame: number) {
|
||||
// stageProgress:
|
||||
// 0: 开始; 1: 开始血条动画
|
||||
|
||||
if (this.stageProgress === 0) {
|
||||
this.healthBar.showStart();
|
||||
this.stageProgress = 1;
|
||||
}
|
||||
|
||||
if (time > 1500) {
|
||||
this.changeStage(TowerBossStage.Stage1, time);
|
||||
this.attackTime = 2;
|
||||
this.skill1Time = 1;
|
||||
this.skill2Time = 1;
|
||||
this.skill3Time = 1;
|
||||
core.playBgm('towerBoss.opus');
|
||||
}
|
||||
}
|
||||
|
||||
async releaseSkill1() {
|
||||
const locs = new Set<number>();
|
||||
const count = Math.ceil(Math.random() * 8) + 4;
|
||||
let i = 0;
|
||||
while (i < count) {
|
||||
const dir = Math.floor(Math.random() * 2);
|
||||
const pos = Math.floor(Math.random() * 13);
|
||||
const loc = pos + dir * 13;
|
||||
if (locs.has(loc)) continue;
|
||||
i++;
|
||||
locs.add(loc);
|
||||
const proj = this.createProjectile(ArrowProjectile, 0, 0);
|
||||
proj.setData(dir);
|
||||
if (dir === ProjectileDirection.Horizontal) {
|
||||
proj.setPosition(480 - 32, pos * 32 + 32);
|
||||
} else {
|
||||
proj.setPosition(pos * 32 + 32, 480 - 32);
|
||||
}
|
||||
await sleep(200);
|
||||
}
|
||||
}
|
||||
|
||||
releaseSkill2() {
|
||||
const x = Math.floor(Math.random() * 11 + 2);
|
||||
const y = Math.floor(Math.random() * 11 + 2);
|
||||
const proj = this.createProjectile(PortalProjectile, 0, 0);
|
||||
proj.setTarget(x, y);
|
||||
proj.createEffect(TowerBoss.effect);
|
||||
}
|
||||
|
||||
async releaseSkill3() {
|
||||
const count = Math.floor(Math.random() * 100);
|
||||
const used = new Set<number>();
|
||||
for (let i = 0; i < count; i++) {
|
||||
const x = Math.floor(Math.random() * 13 + 1);
|
||||
const y = Math.floor(Math.random() * 13 + 1);
|
||||
const index = x + y * 13;
|
||||
if (used.has(index)) continue;
|
||||
used.add(index);
|
||||
const proj = this.createProjectile(IceProjectile, x * 32, y * 32);
|
||||
proj.setPos(x, y);
|
||||
await sleep(20);
|
||||
}
|
||||
}
|
||||
|
||||
private aiStage1(time: number, _frame: number) {
|
||||
// stageProgress:
|
||||
// 0: 开始; 1,2,3,4: 对应对话
|
||||
|
||||
const skill1Release = this.skill1Time * this.skill1Interval;
|
||||
const skill2Release = this.skill2Time * this.skill2Interval;
|
||||
const skill3Release = this.skill3Time * this.skill3Interval;
|
||||
const attack = this.attackTime * this.attackInterval;
|
||||
|
||||
if (time > skill1Release) {
|
||||
this.releaseSkill1();
|
||||
this.skill1Time++;
|
||||
}
|
||||
if (time > skill2Release) {
|
||||
this.releaseSkill2();
|
||||
this.skill2Time++;
|
||||
}
|
||||
if (time > skill3Release) {
|
||||
this.releaseSkill3();
|
||||
this.skill3Time++;
|
||||
}
|
||||
if (time > attack) {
|
||||
this.addAttackCircle(500, 0);
|
||||
this.attackTime++;
|
||||
}
|
||||
|
||||
if (this.hp <= 7000) {
|
||||
this.changeStage(TowerBossStage.Dialogue1, time);
|
||||
this.attackTime = 1;
|
||||
}
|
||||
}
|
||||
|
||||
private aiDialogue1(time: number, _frame: number) {
|
||||
this.changeStage(TowerBossStage.Stage2, time);
|
||||
this.attackTime = 3;
|
||||
this.skill4Time = 5;
|
||||
this.skill5Time = 3;
|
||||
core.playBgm('towerBoss2.opus');
|
||||
const weather = WeatherController.get('main');
|
||||
weather?.activate('rain', 6);
|
||||
}
|
||||
|
||||
releaseSkill4() {
|
||||
const x = Math.floor(Math.random() * 11 + 2);
|
||||
const y = Math.floor(Math.random() * 11 + 2);
|
||||
const power = Math.floor(Math.random() * 6 + 1);
|
||||
const proj = this.createProjectile(ThunderProjectile, 0, 0);
|
||||
proj.setData(x, y, power);
|
||||
proj.createEffect(TowerBoss.effect);
|
||||
}
|
||||
|
||||
async releaseSkill5() {
|
||||
const count = Math.floor(Math.random() * 12 + 6);
|
||||
const used = new Set<number>();
|
||||
let i = 0;
|
||||
while (i < count) {
|
||||
const x = Math.floor(Math.random() * 13 + 1);
|
||||
const y = Math.floor(Math.random() * 13 + 1);
|
||||
const index = x + y * 13;
|
||||
if (used.has(index)) continue;
|
||||
i++;
|
||||
used.add(index);
|
||||
const px = x * 32 + 16;
|
||||
const py = y * 32 + 16;
|
||||
const proj1 = this.createProjectile(ThunderBallProjectile, 0, 0);
|
||||
const proj2 = this.createProjectile(ThunderBallProjectile, 0, 0);
|
||||
const proj3 = this.createProjectile(ThunderBallProjectile, 0, 0);
|
||||
const proj4 = this.createProjectile(ThunderBallProjectile, 0, 0);
|
||||
proj1.setData(ProjectileDirection.BottomToTop, x, y);
|
||||
proj2.setData(ProjectileDirection.LeftToRight, x, y);
|
||||
proj3.setData(ProjectileDirection.RightToLeft, x, y);
|
||||
proj4.setData(ProjectileDirection.TopToBottom, x, y);
|
||||
proj1.setPosition(px, py);
|
||||
proj2.setPosition(px, py);
|
||||
proj3.setPosition(px, py);
|
||||
proj4.setPosition(px, py);
|
||||
await sleep(200);
|
||||
}
|
||||
}
|
||||
|
||||
private aiStage2(time: number, _frame: number) {
|
||||
const skill4Release = this.skill4Time * this.skill4Interval;
|
||||
const skill5Release = this.skill5Time * this.skill5Interval;
|
||||
const attack = this.attackTime * this.attackInterval;
|
||||
|
||||
if (time > skill4Release) {
|
||||
this.releaseSkill4();
|
||||
this.skill4Time++;
|
||||
}
|
||||
if (time > skill5Release) {
|
||||
this.releaseSkill5();
|
||||
this.skill5Time++;
|
||||
}
|
||||
if (time > attack) {
|
||||
this.addAttackCircle(500, 0);
|
||||
this.attackTime++;
|
||||
}
|
||||
|
||||
if (this.hp <= 3500) {
|
||||
this.changeStage(TowerBossStage.Dialogue2, time);
|
||||
this.attackTime = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 压缩地形,将地形向内压缩一格
|
||||
*/
|
||||
terrainClose(n: number) {
|
||||
for (let nx = n - 1; nx < 15 - n + 1; nx++) {
|
||||
core.removeBlock(nx, n - 1);
|
||||
core.removeBlock(nx, 15 - n);
|
||||
core.setBgFgBlock('bg', 0, nx, n - 1);
|
||||
core.setBgFgBlock('bg', 0, nx, 15 - n);
|
||||
}
|
||||
for (let ny = n; ny < 15 - n; ny++) {
|
||||
core.removeBlock(n - 1, ny);
|
||||
core.removeBlock(15 - n, ny);
|
||||
core.setBgFgBlock('bg', 0, n - 1, ny);
|
||||
core.setBgFgBlock('bg', 0, 15 - n, ny);
|
||||
}
|
||||
for (let nx = n; nx < 15 - n; nx++) {
|
||||
core.setBlock(527, nx, n);
|
||||
core.setBlock(527, nx, 15 - n - 1);
|
||||
}
|
||||
for (let ny = n + 1; ny < 15 - n - 1; ny++) {
|
||||
core.setBlock(527, n, ny);
|
||||
core.setBlock(527, 15 - n - 1, ny);
|
||||
}
|
||||
core.stopAutomaticRoute();
|
||||
core.setHeroLoc('x', 7);
|
||||
core.setHeroLoc('y', 7);
|
||||
core.setHeroLoc('direction', 'up');
|
||||
core.setBlock(557, 7, n + 1);
|
||||
}
|
||||
|
||||
private aiDialogue2(time: number, _frame: number) {
|
||||
this.changeStage(TowerBossStage.Stage3, time);
|
||||
this.attackTime = 3;
|
||||
this.terrainClose(1);
|
||||
this.skill6Time = 30;
|
||||
this.skill7Time = 2;
|
||||
core.playBgm('towerBoss3.opus');
|
||||
}
|
||||
|
||||
releaseSkill6(n: number, last: number) {
|
||||
const s = 15 - n * 2;
|
||||
const x = Math.floor(Math.random() * s + n);
|
||||
const y = Math.floor(Math.random() * s + n);
|
||||
const proj = this.createProjectile(BoomProjectile, 0, 0);
|
||||
proj.setData(x, y, last);
|
||||
}
|
||||
|
||||
async releaseSkill7(n: number) {
|
||||
const count = Math.floor(Math.random() * 6 + 3);
|
||||
const nodes: LocArr[] = [];
|
||||
let lastX = -1;
|
||||
let lastY = -1;
|
||||
const s = 15 - n * 2;
|
||||
const used = new Set<number>();
|
||||
let i = 0;
|
||||
while (i < count) {
|
||||
const x = Math.floor(Math.random() * s + n);
|
||||
const y = Math.floor(Math.random() * s + n);
|
||||
const index = x + y * s;
|
||||
if (used.has(index)) continue;
|
||||
i++;
|
||||
used.add(index);
|
||||
nodes.push([x, y]);
|
||||
if (lastX !== -1 && lastY !== -1) {
|
||||
const proj = this.createProjectile(ChainProjectile, 0, 0);
|
||||
proj.hitbox.setPoint1(lastX * 32 + 16, lastY * 32 + 16);
|
||||
proj.hitbox.setPoint2(x * 32 + 16, y * 32 + 16);
|
||||
}
|
||||
lastX = x;
|
||||
lastY = y;
|
||||
}
|
||||
}
|
||||
|
||||
private aiStage3(time: number, _frame: number) {
|
||||
const skill6Release = this.skill6Time * this.skill6Interval;
|
||||
const skill7Release = this.skill7Time * this.skill7Interval;
|
||||
const attack = this.attackTime * this.attackInterval;
|
||||
|
||||
if (time > skill6Release) {
|
||||
this.releaseSkill6(2, 500);
|
||||
this.skill6Time++;
|
||||
}
|
||||
if (time > skill7Release) {
|
||||
this.releaseSkill7(2);
|
||||
this.skill7Time++;
|
||||
}
|
||||
if (time > attack) {
|
||||
this.addAttackCircle(500, 1);
|
||||
this.attackTime++;
|
||||
}
|
||||
|
||||
if (this.hp <= 2000) {
|
||||
this.changeStage(TowerBossStage.Stage4, time);
|
||||
this.terrainClose(2);
|
||||
this.attackTime = 1;
|
||||
this.skill6Time = 12;
|
||||
this.skill6Interval = 400;
|
||||
this.skill7Time = 1;
|
||||
}
|
||||
}
|
||||
|
||||
private aiStage4(time: number, _frame: number) {
|
||||
const skill6Release = this.skill6Time * this.skill6Interval;
|
||||
const skill7Release = this.skill7Time * this.skill7Interval;
|
||||
const attack = this.attackTime * this.attackInterval;
|
||||
|
||||
if (time > skill6Release) {
|
||||
this.releaseSkill6(3, 500);
|
||||
this.skill6Time++;
|
||||
}
|
||||
if (time > skill7Release) {
|
||||
this.releaseSkill7(3);
|
||||
this.skill7Time++;
|
||||
}
|
||||
if (time > attack) {
|
||||
this.addAttackCircle(500, 2);
|
||||
this.attackTime++;
|
||||
}
|
||||
|
||||
if (this.hp <= 1000) {
|
||||
this.changeStage(TowerBossStage.Stage5, time);
|
||||
this.terrainClose(3);
|
||||
this.attackTime = 1;
|
||||
this.skill6Time = 17;
|
||||
this.skill6Interval = 300;
|
||||
this.skill7Time = 1;
|
||||
}
|
||||
}
|
||||
|
||||
private aiStage5(time: number, _frame: number) {
|
||||
const skill6Release = this.skill6Time * this.skill6Interval;
|
||||
const skill7Release = this.skill7Time * this.skill7Interval;
|
||||
const attack = this.attackTime * this.attackInterval;
|
||||
|
||||
if (time > skill6Release) {
|
||||
this.releaseSkill6(4, 500);
|
||||
this.skill6Time++;
|
||||
}
|
||||
if (time > skill7Release) {
|
||||
this.releaseSkill7(4);
|
||||
this.skill7Time++;
|
||||
}
|
||||
if (time > attack) {
|
||||
this.addAttackCircle(500, 3);
|
||||
this.attackTime++;
|
||||
}
|
||||
|
||||
if (this.hp <= 0) {
|
||||
this.changeStage(TowerBossStage.End, time);
|
||||
}
|
||||
}
|
||||
|
||||
private aiEnd(_time: number, _frame: number) {
|
||||
this.end();
|
||||
core.insertAction([
|
||||
{ type: 'openDoor', loc: [13, 6], floorId: 'MT19' },
|
||||
{ type: 'setValue', name: 'flag:boss1', value: 'true' },
|
||||
{ type: 'changeFloor', floorId: 'MT20', loc: [7, 9] },
|
||||
{ type: 'forbidSave' },
|
||||
{ type: 'showStatusBar' }
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
interface TextRenderable {
|
||||
x: number;
|
||||
y: number;
|
||||
blur: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
class Word extends RenderItem {
|
||||
private ani: Animation = new Animation();
|
||||
|
||||
/** 当前正在显示的文字 */
|
||||
private showing: string = '';
|
||||
/** 文字显示时间间隔 */
|
||||
private showInterval: number = 100;
|
||||
/** 文字显示的虚化时长 */
|
||||
private showBlurTime: number = 200;
|
||||
/** 显示开始时刻 */
|
||||
private showStartTime: number = 0;
|
||||
|
||||
/** 最大虚化程度 */
|
||||
private readonly MAX_BLUR = 5;
|
||||
|
||||
/**
|
||||
* 初始化
|
||||
*/
|
||||
init() {
|
||||
this.size(480, 24);
|
||||
this.setHD(true);
|
||||
this.setZIndex(95);
|
||||
}
|
||||
|
||||
/**
|
||||
* 降下背景
|
||||
*/
|
||||
curtainDown() {
|
||||
this.delegateTicker(() => {
|
||||
this.pos(this.ani.x, this.ani.y);
|
||||
}, 700);
|
||||
this.ani.time(600).mode(hyper('sin', 'out')).absolute().move(0, 24);
|
||||
return sleep(700);
|
||||
}
|
||||
|
||||
/**
|
||||
* 升起背景
|
||||
*/
|
||||
curtainUp() {
|
||||
this.delegateTicker(() => {
|
||||
this.pos(this.ani.x, this.ani.y);
|
||||
}, 700);
|
||||
this.ani.time(600).mode(hyper('sin', 'out')).absolute().move(0, 0);
|
||||
return sleep(700);
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示文字,会将之前的文字取消显示
|
||||
* @param text 要显示的文字
|
||||
*/
|
||||
showText(text: string) {
|
||||
this.showStartTime = Date.now();
|
||||
this.showing = text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置文字显示的参数
|
||||
* @param interval 文字显示时间间隔
|
||||
* @param blurTime 文字显示虚化时长
|
||||
*/
|
||||
setParam(interval: number, blurTime: number) {
|
||||
this.showInterval = interval;
|
||||
this.showBlurTime = blurTime;
|
||||
}
|
||||
|
||||
private getTextRenerable() {
|
||||
const dt = Date.now() - this.showStartTime;
|
||||
const res: TextRenderable[] = [];
|
||||
|
||||
[...this.showing].forEach((v, i) => {
|
||||
const showStartTime = i * this.showInterval;
|
||||
const blurRatio = (dt - showStartTime) / this.showBlurTime;
|
||||
let blur = blurRatio * this.MAX_BLUR;
|
||||
if (blur < 0) blur = 0;
|
||||
else if (blur > this.MAX_BLUR) blur = this.MAX_BLUR;
|
||||
|
||||
const obj: TextRenderable = {
|
||||
blur,
|
||||
x: i * 18,
|
||||
y: 12,
|
||||
text: v
|
||||
};
|
||||
res.push(obj);
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
protected render(canvas: MotaOffscreenCanvas2D): void {
|
||||
const data = this.getTextRenerable();
|
||||
const ctx = canvas.ctx;
|
||||
ctx.font = '18px "normal"';
|
||||
ctx.textAlign = 'left';
|
||||
ctx.textBaseline = 'middle';
|
||||
|
||||
for (const { blur, x, y, text } of data) {
|
||||
if (blur !== 0) {
|
||||
ctx.filter = `blur(${blur}px)`;
|
||||
} else {
|
||||
ctx.filter = 'none';
|
||||
}
|
||||
ctx.fillText(text, x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class HealthBar extends RenderItem {
|
||||
private trans: Transition = new Transition();
|
||||
/** 当前血条状态 */
|
||||
private status: HealthBarStatus = HealthBarStatus.Start;
|
||||
|
||||
/**
|
||||
* 初始化
|
||||
*/
|
||||
init() {
|
||||
this.trans.time(2000).absolute().mode(power(3, 'out'));
|
||||
this.trans.value.hp = 0;
|
||||
this.trans.value.x = 0;
|
||||
this.trans.value.y = -16;
|
||||
|
||||
this.size(480, 16);
|
||||
this.setHD(true);
|
||||
this.setZIndex(100);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置剩余血量
|
||||
*/
|
||||
set(value: number) {
|
||||
this.trans.time(2000).mode(power(3, 'out')).transition('hp', value);
|
||||
this.delegateTicker(() => {
|
||||
this.update();
|
||||
}, 2500);
|
||||
}
|
||||
|
||||
/**
|
||||
* 展示开始动画
|
||||
*/
|
||||
async showStart() {
|
||||
if (this.status !== HealthBarStatus.Start) return;
|
||||
this.delegateTicker(() => {
|
||||
this.update();
|
||||
}, 2500);
|
||||
this.trans
|
||||
.time(600)
|
||||
.mode(hyper('sin', 'out'))
|
||||
.absolute()
|
||||
.transition('y', 0);
|
||||
this.trans.time(2000).mode(power(3, 'out')).transition('hp', 10000);
|
||||
await sleep(1700);
|
||||
this.status = HealthBarStatus.Running;
|
||||
}
|
||||
|
||||
/**
|
||||
* 展示结束动画
|
||||
*/
|
||||
async showEnd() {
|
||||
if (this.status !== HealthBarStatus.Running) return;
|
||||
this.delegateTicker(() => {
|
||||
this.update();
|
||||
}, 2500);
|
||||
this.trans
|
||||
.time(600)
|
||||
.mode(hyper('sin', 'in'))
|
||||
.absolute()
|
||||
.transition('y', -16);
|
||||
await sleep(700);
|
||||
this.status = HealthBarStatus.End;
|
||||
}
|
||||
|
||||
protected render(canvas: MotaOffscreenCanvas2D): void {
|
||||
const ctx = canvas.ctx;
|
||||
|
||||
const hp = this.trans.value.hp;
|
||||
const ratio = hp / 10000;
|
||||
const r = Math.min(255 * 2 - ratio * 2 * 255, 255);
|
||||
const g = Math.min(ratio * 2 * 255, 255);
|
||||
|
||||
ctx.save();
|
||||
ctx.translate(this.trans.value.x, this.trans.value.y);
|
||||
ctx.fillStyle = '#bbb';
|
||||
ctx.fillRect(2, 2, 480 - 4, 16 - 4);
|
||||
|
||||
const color = `rgb(${Math.floor(r)},${Math.floor(g)},0)`;
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillRect(2, 2, (480 - 4) * ratio, 16 - 4);
|
||||
|
||||
ctx.font = '12px "normal"';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.textAlign = 'right';
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.strokeStyle = '#000';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeText(`${Math.floor(hp)} / 10000`, 472, 8);
|
||||
ctx.fillText(`${Math.floor(hp)} / 10000`, 472, 8);
|
||||
|
||||
ctx.lineWidth = 4;
|
||||
ctx.strokeStyle = '#fff';
|
||||
ctx.shadowBlur = 4;
|
||||
ctx.shadowColor = '#000';
|
||||
ctx.strokeRect(0, 0, 480, 16);
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
@@ -1,994 +0,0 @@
|
||||
import { hyper, power, TimingFn } from 'mutate-animate';
|
||||
import { Hitbox, Projectile } from './barrage';
|
||||
import { MotaOffscreenCanvas2D, Transform } from '@motajs/render';
|
||||
import type { TowerBoss } from './towerBoss';
|
||||
import { IStateDamageable } from '@/game/state/interface';
|
||||
import { PointEffect, PointEffectType } from '../fx/pointShader';
|
||||
import { isNil } from 'lodash-es';
|
||||
|
||||
export const enum ProjectileDirection {
|
||||
Vertical,
|
||||
Horizontal,
|
||||
|
||||
LeftToRight,
|
||||
RightToLeft,
|
||||
TopToBottom,
|
||||
BottomToTop
|
||||
}
|
||||
|
||||
function popDamage(damage: number, boss: TowerBoss, color: string) {
|
||||
const { x, y } = core.status.hero.loc;
|
||||
boss.pop.addPop(
|
||||
(-damage).toString(),
|
||||
1000,
|
||||
x * 32 + 16,
|
||||
y * 32 + 16,
|
||||
color
|
||||
);
|
||||
}
|
||||
|
||||
export class AttackProjectile extends Projectile<TowerBoss> {
|
||||
static easeIn?: TimingFn;
|
||||
static easeOut?: TimingFn;
|
||||
|
||||
damage: number = 500;
|
||||
hitbox: Hitbox.Rect = new Hitbox.Rect(0, 0, 32, 32);
|
||||
|
||||
static init() {
|
||||
this.easeIn = hyper('sin', 'out');
|
||||
this.easeOut = hyper('sin', 'in');
|
||||
}
|
||||
|
||||
static end() {
|
||||
this.easeIn = void 0;
|
||||
this.easeOut = void 0;
|
||||
}
|
||||
|
||||
isIntersect(hitbox: Hitbox.HitboxType): boolean {
|
||||
if (hitbox instanceof Hitbox.Rect) {
|
||||
return Hitbox.checkRectRect(this.hitbox, hitbox);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
updateHitbox(x: number, y: number): void {
|
||||
this.hitbox.setPosition(x, y);
|
||||
}
|
||||
|
||||
doDamage(target: IStateDamageable): boolean {
|
||||
this.boss.attackBoss(this.damage);
|
||||
this.destroy();
|
||||
return true;
|
||||
}
|
||||
|
||||
ai(boss: TowerBoss, time: number, frame: number): void {
|
||||
if (time > 4000) {
|
||||
this.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
render(canvas: MotaOffscreenCanvas2D, transform: Transform): void {
|
||||
const progress = this.time / 4000;
|
||||
let alpha = 1;
|
||||
let offset = 0;
|
||||
if (progress < 0.1) {
|
||||
alpha = progress * 10;
|
||||
offset = 24 * AttackProjectile.easeIn!(10 * (0.1 - progress));
|
||||
} else if (progress > 0.9) {
|
||||
alpha = 10 * (1 - progress);
|
||||
offset = 24 * AttackProjectile.easeOut!(10 * (progress - 0.9));
|
||||
} else {
|
||||
alpha = 1;
|
||||
offset = 0;
|
||||
}
|
||||
const ctx = canvas.ctx;
|
||||
ctx.save();
|
||||
ctx.strokeStyle = '#ffe229';
|
||||
ctx.fillStyle = '#ffe229';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.globalAlpha = alpha;
|
||||
ctx.beginPath();
|
||||
const o = offset + 16;
|
||||
const cx = this.x + 16;
|
||||
const cy = this.y + 16;
|
||||
ctx.arc(cx, cy, 2, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, o, 0, Math.PI * 2);
|
||||
ctx.moveTo(cx + o, cy);
|
||||
ctx.lineTo(cx + o + 16, cy);
|
||||
ctx.moveTo(cx, cy + o);
|
||||
ctx.lineTo(cx, cy + o + 16);
|
||||
ctx.moveTo(cx - o, cy);
|
||||
ctx.lineTo(cx - o - 16, cy);
|
||||
ctx.moveTo(cx, cy - o);
|
||||
ctx.lineTo(cx, cy - o - 16);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
|
||||
export class ArrowProjectile extends Projectile<TowerBoss> {
|
||||
static easing?: TimingFn;
|
||||
static dangerEasing?: TimingFn;
|
||||
|
||||
static horizontal: MotaOffscreenCanvas2D | null = null;
|
||||
static vertical: MotaOffscreenCanvas2D | null = null;
|
||||
|
||||
hitbox: Hitbox.Rect = new Hitbox.Rect(0, 0, 102, 32);
|
||||
damage: number = 1000;
|
||||
|
||||
/** 弹幕的方向 */
|
||||
direction: ProjectileDirection = ProjectileDirection.Horizontal;
|
||||
|
||||
private damaged: boolean = false;
|
||||
private sounded: boolean = false;
|
||||
|
||||
/**
|
||||
* boss战开始时初始化
|
||||
*/
|
||||
static init() {
|
||||
this.easing = power(2, 'in');
|
||||
this.dangerEasing = power(3, 'out');
|
||||
this.horizontal = new MotaOffscreenCanvas2D();
|
||||
this.vertical = new MotaOffscreenCanvas2D();
|
||||
const hor = this.horizontal;
|
||||
hor.size(480, 32);
|
||||
hor.setHD(true);
|
||||
hor.withGameScale(true);
|
||||
const ctxHor = hor.ctx;
|
||||
ctxHor.fillStyle = '#f00';
|
||||
ctxHor.globalAlpha = 0.6;
|
||||
for (let i = 0; i < 15; i++) {
|
||||
ctxHor.fillRect(i * 32 + 2, 2, 28, 28);
|
||||
}
|
||||
const ver = this.vertical;
|
||||
ver.size(32, 480);
|
||||
ver.setHD(true);
|
||||
ver.withGameScale(true);
|
||||
const ctxVer = ver.ctx;
|
||||
ctxVer.fillStyle = '#f00';
|
||||
ctxVer.globalAlpha = 0.6;
|
||||
for (let i = 0; i < 15; i++) {
|
||||
ctxVer.fillRect(2, i * 32 + 2, 28, 28);
|
||||
}
|
||||
hor.freeze();
|
||||
ver.freeze();
|
||||
}
|
||||
|
||||
/**
|
||||
* boss战结束后清理
|
||||
*/
|
||||
static end() {
|
||||
this.easing = void 0;
|
||||
this.dangerEasing = void 0;
|
||||
this.horizontal?.clear();
|
||||
this.horizontal?.delete();
|
||||
this.horizontal = null;
|
||||
this.vertical?.clear();
|
||||
this.vertical?.delete();
|
||||
this.vertical = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置弹幕的数据
|
||||
* @param direction 弹幕的方向
|
||||
*/
|
||||
setData(direction: ProjectileDirection) {
|
||||
this.direction = direction;
|
||||
if (direction === ProjectileDirection.Horizontal) {
|
||||
this.hitbox.setSize(102, 32);
|
||||
} else {
|
||||
this.hitbox.setSize(32, 102);
|
||||
}
|
||||
}
|
||||
|
||||
isIntersect(hitbox: Hitbox.HitboxType): boolean {
|
||||
if (hitbox instanceof Hitbox.Rect) {
|
||||
return Hitbox.checkRectRect(hitbox, this.hitbox);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
updateHitbox(x: number, y: number): void {
|
||||
this.hitbox.setPosition(x, y);
|
||||
}
|
||||
|
||||
doDamage(target: IStateDamageable): boolean {
|
||||
if (this.damaged) return false;
|
||||
target.hp -= this.damage;
|
||||
this.damaged = true;
|
||||
core.drawHeroAnimate('hand');
|
||||
popDamage(this.damage, this.boss, '#ff8180');
|
||||
return true;
|
||||
}
|
||||
|
||||
ai(boss: TowerBoss, time: number, frame: number): void {
|
||||
if (time > 3000) {
|
||||
if (!this.sounded) {
|
||||
core.playSound('arrow.opus');
|
||||
this.sounded = true;
|
||||
}
|
||||
const progress = (time - 3000) / 2000;
|
||||
const res = ArrowProjectile.easing!(progress);
|
||||
const dx = res * 640;
|
||||
const x = 480 - 32 - dx;
|
||||
if (this.direction === ProjectileDirection.Horizontal) {
|
||||
this.setPosition(x, this.y);
|
||||
} else {
|
||||
this.setPosition(this.x, x);
|
||||
}
|
||||
} else if (time > 5000) {
|
||||
this.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
render(canvas: MotaOffscreenCanvas2D, transform: Transform): void {
|
||||
const ctx = canvas.ctx;
|
||||
ctx.globalAlpha = 1;
|
||||
const ratio = devicePixelRatio * core.domStyle.scale;
|
||||
const cell = 32 * ratio;
|
||||
ctx.save();
|
||||
|
||||
if (this.time < 3000) {
|
||||
let begin = 1;
|
||||
if (this.time < 2000) {
|
||||
begin = ArrowProjectile.dangerEasing!(this.time / 2000);
|
||||
}
|
||||
const len = begin * 13 * 32;
|
||||
const fl = len * ratio;
|
||||
const x1 = 480 - 32 - len;
|
||||
const fx1 = x1 * ratio;
|
||||
|
||||
if (this.direction === ProjectileDirection.Horizontal) {
|
||||
const canvas = ArrowProjectile.horizontal!.canvas;
|
||||
ctx.drawImage(canvas, fx1, 0, fl, cell, x1, this.y, len, 32);
|
||||
} else {
|
||||
const canvas = ArrowProjectile.vertical!.canvas;
|
||||
ctx.drawImage(canvas, 0, fx1, cell, fl, this.x, x1, 32, len);
|
||||
}
|
||||
} else {
|
||||
if (this.direction === ProjectileDirection.Horizontal) {
|
||||
const len = Math.max(this.x - 32, 0);
|
||||
const fl = len * ratio;
|
||||
const canvas = ArrowProjectile.horizontal!.canvas;
|
||||
ctx.drawImage(canvas, cell, 0, fl, cell, 32, this.y, len, 32);
|
||||
} else {
|
||||
const len = Math.max(this.y - 32, 0);
|
||||
const fl = len * ratio;
|
||||
const canvas = ArrowProjectile.vertical!.canvas;
|
||||
ctx.drawImage(canvas, 0, cell, cell, fl, this.x, 32, 32, len);
|
||||
}
|
||||
}
|
||||
const img = core.material.images.images['arrow.png'];
|
||||
if (this.direction === ProjectileDirection.Vertical) {
|
||||
ctx.translate(this.x + 32, this.y);
|
||||
ctx.rotate(Math.PI / 2);
|
||||
ctx.drawImage(img, 0, 0, 102, 32);
|
||||
} else {
|
||||
ctx.drawImage(img, this.x, this.y, 102, 32);
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
|
||||
export class PortalProjectile extends Projectile<TowerBoss> {
|
||||
static easing?: TimingFn;
|
||||
|
||||
damage: number = 0;
|
||||
hitbox: Hitbox.Circle = new Hitbox.Circle(0, 0, 0);
|
||||
|
||||
/** 传送目标位置 */
|
||||
private tx: number = 0;
|
||||
/** 传送目标位置 */
|
||||
private ty: number = 0;
|
||||
/** 是否已经传送过 */
|
||||
private transfered: boolean = false;
|
||||
|
||||
private effect?: PointEffect;
|
||||
private effectId1?: number;
|
||||
private effectId2?: number;
|
||||
|
||||
static init() {
|
||||
this.easing = hyper('sin', 'out');
|
||||
}
|
||||
|
||||
static end() {
|
||||
this.easing = void 0;
|
||||
}
|
||||
|
||||
createEffect(effect: PointEffect) {
|
||||
this.effect = effect;
|
||||
const id1 = effect.addEffect(
|
||||
PointEffectType.CircleWarpTangetial,
|
||||
Date.now(),
|
||||
4000,
|
||||
[this.tx * 32 + 16, this.ty * 32 + 16, 0, 32]
|
||||
);
|
||||
const id2 = effect.addEffect(
|
||||
PointEffectType.CircleContrast,
|
||||
Date.now(),
|
||||
4000,
|
||||
[this.tx * 32 + 16, this.ty * 32 + 16, 32, 24]
|
||||
);
|
||||
this.effectId1 = id1;
|
||||
this.effectId2 = id2;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置传送目标位置
|
||||
*/
|
||||
setTarget(x: number, y: number) {
|
||||
this.tx = x;
|
||||
this.ty = y;
|
||||
}
|
||||
|
||||
isIntersect(hitbox: Hitbox.HitboxType): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
updateHitbox(x: number, y: number): void {
|
||||
this.hitbox.setCenter(x, y);
|
||||
}
|
||||
|
||||
doDamage(target: IStateDamageable): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
ai(boss: TowerBoss, time: number, frame: number): void {
|
||||
if (!this.transfered && time > 2000) {
|
||||
this.transfered = true;
|
||||
core.setHeroLoc('x', this.tx);
|
||||
core.setHeroLoc('y', this.ty);
|
||||
}
|
||||
|
||||
if (time > 4000) {
|
||||
this.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
render(canvas: MotaOffscreenCanvas2D, transform: Transform): void {
|
||||
const effect = this.effect;
|
||||
const id1 = this.effectId1;
|
||||
const id2 = this.effectId2;
|
||||
if (!effect || isNil(id1) || isNil(id2)) return;
|
||||
const time = this.time;
|
||||
const max = Math.PI * 2;
|
||||
if (time < 2000) {
|
||||
const progress = PortalProjectile.easing!(time / 2000);
|
||||
const ratio = Math.min(progress * 3, 1);
|
||||
effect.setEffect(id1, void 0, [0, max * progress, 0, 0]);
|
||||
effect.setEffect(id2, void 0, [ratio, 0, 0, 0]);
|
||||
} else {
|
||||
const progress = PortalProjectile.easing!((time - 2000) / 2000);
|
||||
const ratio = Math.min((1 - progress) * 3, 1);
|
||||
effect.setEffect(id1, void 0, [max * progress, max, 0, 0]);
|
||||
effect.setEffect(id2, void 0, [ratio, 0, 0, 0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class IceProjectile extends Projectile<TowerBoss> {
|
||||
damage: number = 5000;
|
||||
hitbox: Hitbox.Rect = new Hitbox.Rect(0, 0, 32, 32);
|
||||
|
||||
private damaged: boolean = false;
|
||||
/** 是否已经播放冰冻动画 */
|
||||
private animated: boolean = false;
|
||||
/** 是否已经转换成滑冰图块 */
|
||||
private converted: boolean = false;
|
||||
|
||||
private bx: number = 0;
|
||||
private by: number = 0;
|
||||
|
||||
/**
|
||||
* 设置这个寒冰弹幕的攻击位置
|
||||
*/
|
||||
setPos(x: number, y: number) {
|
||||
this.bx = x;
|
||||
this.by = y;
|
||||
this.updateHitbox(x * 32, y * 32);
|
||||
}
|
||||
|
||||
isIntersect(hitbox: Hitbox.HitboxType): boolean {
|
||||
if (this.damaged) return false;
|
||||
if (this.time < 2000) return false;
|
||||
if (hitbox instanceof Hitbox.Rect) {
|
||||
return Hitbox.checkRectRect(hitbox, this.hitbox);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
updateHitbox(x: number, y: number): void {
|
||||
this.hitbox.setPosition(x, y);
|
||||
}
|
||||
|
||||
doDamage(target: IStateDamageable): boolean {
|
||||
if (!this.damaged) return false;
|
||||
target.hp -= this.damage;
|
||||
this.damaged = true;
|
||||
popDamage(this.damage, this.boss, '#6bf8ff');
|
||||
return true;
|
||||
}
|
||||
|
||||
ai(boss: TowerBoss, time: number, frame: number): void {
|
||||
if (!this.converted && time > 2000) {
|
||||
this.converted = true;
|
||||
core.setBgFgBlock('bg', 167, this.bx, this.by);
|
||||
}
|
||||
if (time > 4000) {
|
||||
core.setBgFgBlock('bg', 526, this.bx, this.by);
|
||||
this.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
render(canvas: MotaOffscreenCanvas2D, transform: Transform): void {
|
||||
const ctx = canvas.ctx;
|
||||
if (this.time < 2000) {
|
||||
ctx.fillStyle = 'rgb(150,150,255)';
|
||||
ctx.globalAlpha = 0.6;
|
||||
ctx.fillRect(this.x + 2, this.y + 2, 28, 28);
|
||||
} else {
|
||||
if (!this.animated) {
|
||||
this.animated = true;
|
||||
core.drawAnimate('ice', this.bx, this.by);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class ThunderProjectile extends Projectile<TowerBoss> {
|
||||
/** 闪电缓存画布 */
|
||||
static cache: MotaOffscreenCanvas2D | null = null;
|
||||
|
||||
damage: number = 0;
|
||||
hitbox: Hitbox.Rect = new Hitbox.Rect(0, 0, 96, 96);
|
||||
|
||||
private bx: number = 0;
|
||||
private by: number = 0;
|
||||
/** 闪电的强度 */
|
||||
private power: number = 0;
|
||||
private damaged: boolean = false;
|
||||
private cached: boolean = false;
|
||||
private sounded: boolean = false;
|
||||
|
||||
private effect?: PointEffect;
|
||||
private effectId1?: number;
|
||||
private effectId2?: number;
|
||||
|
||||
static init() {
|
||||
this.cache = new MotaOffscreenCanvas2D();
|
||||
this.cache.setHD(true);
|
||||
this.cache.withGameScale(true);
|
||||
this.cache.size(480, 480);
|
||||
}
|
||||
|
||||
static end() {
|
||||
this.cache?.clear();
|
||||
this.cache?.delete();
|
||||
this.cache = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建着色器特效
|
||||
*/
|
||||
createEffect(effect: PointEffect) {
|
||||
this.effect = effect;
|
||||
this.effectId1 = effect.addEffect(
|
||||
PointEffectType.CircleBrightness,
|
||||
Date.now() + 1000,
|
||||
600,
|
||||
[this.bx * 32 + 16, this.by * 32 + 16, 128, 32],
|
||||
[1, 0, 0, 0]
|
||||
);
|
||||
this.effectId2 = effect.addEffect(
|
||||
PointEffectType.CircleWarp,
|
||||
Date.now() + 1000,
|
||||
600,
|
||||
[this.bx * 32 + 16, this.by * 32 + 16, 240 + this.power * 32, 32],
|
||||
[0.1, 6, 0.8, 0],
|
||||
[0, Math.PI, 0, 0]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置闪电的信息
|
||||
*/
|
||||
setData(x: number, y: number, power: number) {
|
||||
this.bx = x;
|
||||
this.by = y;
|
||||
this.power = power;
|
||||
this.damage = power * 3000;
|
||||
this.updateHitbox(x * 32 - 32, y * 32 - 32);
|
||||
}
|
||||
|
||||
isIntersect(hitbox: Hitbox.HitboxType): boolean {
|
||||
if (this.damaged) return false;
|
||||
if (this.time < 1000) return false;
|
||||
if (hitbox instanceof Hitbox.Rect) {
|
||||
return Hitbox.checkRectRect(hitbox, this.hitbox);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
updateHitbox(x: number, y: number): void {
|
||||
this.hitbox.setPosition(x, y);
|
||||
}
|
||||
|
||||
doDamage(target: IStateDamageable): boolean {
|
||||
if (this.damaged) return false;
|
||||
this.damaged = true;
|
||||
target.hp -= this.damage;
|
||||
popDamage(this.damage, this.boss, '#cfe6fc');
|
||||
return true;
|
||||
}
|
||||
|
||||
ai(boss: TowerBoss, time: number, frame: number): void {
|
||||
if (time > 500) {
|
||||
if (!this.sounded) {
|
||||
core.playSound('thunder.opus');
|
||||
this.sounded = true;
|
||||
}
|
||||
}
|
||||
if (time > 2000) {
|
||||
this.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
render(canvas: MotaOffscreenCanvas2D, transform: Transform): void {
|
||||
const ctx = canvas.ctx;
|
||||
if (this.time < 1000) {
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.globalAlpha = 0.6;
|
||||
for (let dx = -1; dx < 2; dx++) {
|
||||
for (let dy = -1; dy < 2; dy++) {
|
||||
const x = (this.bx + dx) * 32 + 2;
|
||||
const y = (this.by + dy) * 32 + 2;
|
||||
ctx.fillRect(x, y, 28, 28);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!this.cached) this.cacheThunder();
|
||||
if (!ThunderProjectile.cache) return;
|
||||
const progress = (this.time - 1000) / 1000;
|
||||
const effect = this.effect;
|
||||
const id = this.effectId1;
|
||||
if (!effect || isNil(id)) return;
|
||||
if (progress < 0.6) {
|
||||
const x = this.bx * 32 + 16;
|
||||
const y = this.by * 32 + 16;
|
||||
effect.setEffect(
|
||||
id,
|
||||
[x, y, 32 + progress * 256, 32],
|
||||
[(0.6 - progress) / 0.6, 0, 0, 0]
|
||||
);
|
||||
}
|
||||
if (progress < 0.5) {
|
||||
ctx.globalAlpha = 1;
|
||||
} else {
|
||||
ctx.globalAlpha = 1 - (progress - 0.5) * 2;
|
||||
}
|
||||
ctx.drawImage(ThunderProjectile.cache.canvas, 0, 0, 480, 480);
|
||||
}
|
||||
}
|
||||
|
||||
private cacheThunder() {
|
||||
const cache = ThunderProjectile.cache;
|
||||
if (!cache) return;
|
||||
this.cached = true;
|
||||
cache.clear();
|
||||
const ctx = cache.ctx;
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < this.power; i++) {
|
||||
let x = this.bx * 32 + 16;
|
||||
let y = this.by * 32 + 16;
|
||||
ctx.moveTo(x, y);
|
||||
while (y > 0) {
|
||||
x += Math.floor(Math.random() * 30 - 15);
|
||||
y -= Math.floor(Math.random() * 80);
|
||||
ctx.lineTo(x, y);
|
||||
}
|
||||
}
|
||||
ctx.shadowBlur = 5;
|
||||
ctx.shadowColor = '#62c8f4';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.globalAlpha = 0.6;
|
||||
ctx.strokeStyle = '#fff';
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
export class ThunderBallProjectile extends Projectile<TowerBoss> {
|
||||
static dangerEasing?: TimingFn;
|
||||
|
||||
static horizontal: MotaOffscreenCanvas2D | null = null;
|
||||
static vertical: MotaOffscreenCanvas2D | null = null;
|
||||
|
||||
damage: number = 3000;
|
||||
hitbox: Hitbox.Rect = new Hitbox.Rect(0, 0, 16, 16);
|
||||
|
||||
private direction: ProjectileDirection = ProjectileDirection.BottomToTop;
|
||||
private cx: number = 0;
|
||||
private cy: number = 0;
|
||||
private damaged: boolean = false;
|
||||
private sounded: boolean = false;
|
||||
|
||||
/**
|
||||
* boss战开始时初始化
|
||||
*/
|
||||
static init() {
|
||||
this.dangerEasing = power(3, 'out');
|
||||
this.horizontal = new MotaOffscreenCanvas2D();
|
||||
this.vertical = new MotaOffscreenCanvas2D();
|
||||
const hor = this.horizontal;
|
||||
hor.size(480, 32);
|
||||
hor.setHD(true);
|
||||
hor.withGameScale(true);
|
||||
const ctxHor = hor.ctx;
|
||||
ctxHor.fillStyle = '#fff';
|
||||
ctxHor.globalAlpha = 0.6;
|
||||
for (let i = 0; i < 15; i++) {
|
||||
ctxHor.fillRect(i * 32 + 2, 2, 28, 28);
|
||||
}
|
||||
const ver = this.vertical;
|
||||
ver.size(32, 480);
|
||||
ver.setHD(true);
|
||||
ver.withGameScale(true);
|
||||
const ctxVer = ver.ctx;
|
||||
ctxVer.fillStyle = '#fff';
|
||||
ctxVer.globalAlpha = 0.6;
|
||||
for (let i = 0; i < 15; i++) {
|
||||
ctxVer.fillRect(2, i * 32 + 2, 28, 28);
|
||||
}
|
||||
hor.freeze();
|
||||
ver.freeze();
|
||||
}
|
||||
|
||||
/**
|
||||
* boss战结束后清理
|
||||
*/
|
||||
static end() {
|
||||
this.dangerEasing = void 0;
|
||||
this.horizontal?.clear();
|
||||
this.horizontal?.delete();
|
||||
this.horizontal = null;
|
||||
this.vertical?.clear();
|
||||
this.vertical?.delete();
|
||||
this.vertical = null;
|
||||
}
|
||||
|
||||
setData(direction: ProjectileDirection, cx: number, cy: number) {
|
||||
this.cx = cx;
|
||||
this.cy = cy;
|
||||
this.direction = direction;
|
||||
this.setPosition(cx * 32 + 16, cy * 32 + 16);
|
||||
}
|
||||
|
||||
isIntersect(hitbox: Hitbox.HitboxType): boolean {
|
||||
if (this.damaged) return false;
|
||||
if (this.time < 3000) return false;
|
||||
if (hitbox instanceof Hitbox.Rect) {
|
||||
return Hitbox.checkRectRect(this.hitbox, hitbox);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
updateHitbox(x: number, y: number): void {
|
||||
this.hitbox.setPosition(x, y);
|
||||
}
|
||||
|
||||
doDamage(target: IStateDamageable): boolean {
|
||||
if (this.damaged) return false;
|
||||
this.damaged = true;
|
||||
target.hp -= this.damage;
|
||||
core.playSound('electron.opus');
|
||||
popDamage(this.damage, this.boss, '#cfe6fc');
|
||||
return true;
|
||||
}
|
||||
|
||||
ai(boss: TowerBoss, time: number, frame: number): void {
|
||||
if (time > 3000) {
|
||||
if (!this.sounded) {
|
||||
core.playSound('electron.opus');
|
||||
this.sounded = true;
|
||||
}
|
||||
const dt = time - 3000;
|
||||
const dis = dt * 0.2;
|
||||
const cx = this.cx * 32 + 16;
|
||||
const cy = this.cy * 32 + 16;
|
||||
|
||||
switch (this.direction) {
|
||||
case ProjectileDirection.BottomToTop:
|
||||
this.setPosition(cx, cy - dis);
|
||||
break;
|
||||
case ProjectileDirection.LeftToRight:
|
||||
this.setPosition(cx + dis, cy);
|
||||
break;
|
||||
case ProjectileDirection.RightToLeft:
|
||||
this.setPosition(cx - dis, cy);
|
||||
break;
|
||||
case ProjectileDirection.TopToBottom:
|
||||
this.setPosition(cx, cy + dis);
|
||||
break;
|
||||
}
|
||||
|
||||
if (this.x < -16 || this.x > 496 || this.y < -16 || this.y > 496) {
|
||||
this.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
render(canvas: MotaOffscreenCanvas2D, transform: Transform): void {
|
||||
const ctx = canvas.ctx;
|
||||
const cx = this.cx * 32 + 16;
|
||||
const cy = this.cy * 32 + 16;
|
||||
let left = 0;
|
||||
let right = 0;
|
||||
let top = 0;
|
||||
let bottom = 0;
|
||||
if (this.time < 3000) {
|
||||
let begin = 1;
|
||||
if (this.time < 2000) {
|
||||
begin = ArrowProjectile.dangerEasing!(this.time / 2000);
|
||||
}
|
||||
|
||||
switch (this.direction) {
|
||||
case ProjectileDirection.BottomToTop: {
|
||||
const height = (cy - 48) * begin;
|
||||
left = cx - 16;
|
||||
right = cx + 16;
|
||||
bottom = cy + 16;
|
||||
top = cy - height - 16;
|
||||
break;
|
||||
}
|
||||
case ProjectileDirection.LeftToRight: {
|
||||
const width = (432 - cx) * begin;
|
||||
left = cx - 16;
|
||||
right = cx + 16 + width;
|
||||
bottom = cy + 16;
|
||||
top = cy - 16;
|
||||
break;
|
||||
}
|
||||
case ProjectileDirection.RightToLeft: {
|
||||
const width = (cx - 48) * begin;
|
||||
left = cx - width - 16;
|
||||
right = cx + 16;
|
||||
bottom = cy + 16;
|
||||
top = cy - 16;
|
||||
break;
|
||||
}
|
||||
case ProjectileDirection.TopToBottom: {
|
||||
const height = (432 - cy) * begin;
|
||||
left = cx - 16;
|
||||
right = cx + 16;
|
||||
bottom = cy + 16 + height;
|
||||
top = cy + 16;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
switch (this.direction) {
|
||||
case ProjectileDirection.BottomToTop: {
|
||||
left = cx - 16;
|
||||
right = cx + 16;
|
||||
bottom = this.y;
|
||||
top = 32;
|
||||
break;
|
||||
}
|
||||
case ProjectileDirection.LeftToRight: {
|
||||
left = this.x;
|
||||
right = 448;
|
||||
bottom = cy + 16;
|
||||
top = cy - 16;
|
||||
break;
|
||||
}
|
||||
case ProjectileDirection.RightToLeft: {
|
||||
left = 32;
|
||||
right = this.x;
|
||||
bottom = cy + 16;
|
||||
top = cy - 16;
|
||||
break;
|
||||
}
|
||||
case ProjectileDirection.TopToBottom: {
|
||||
left = cx - 16;
|
||||
right = cx + 16;
|
||||
bottom = 448;
|
||||
top = this.y;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const ratio = devicePixelRatio * core.domStyle.scale;
|
||||
const w = right - left;
|
||||
const h = bottom - top;
|
||||
const fw = w * ratio;
|
||||
const fh = h * ratio;
|
||||
const fl = left * ratio;
|
||||
const ft = top * ratio;
|
||||
const cell = 32 * ratio;
|
||||
const hor = ThunderBallProjectile.horizontal!.canvas;
|
||||
const ver = ThunderBallProjectile.vertical!.canvas;
|
||||
ctx.save();
|
||||
if (this.time > 1000 && this.time < 3000) {
|
||||
ctx.globalAlpha = (3000 - this.time) / 2000;
|
||||
} else {
|
||||
ctx.globalAlpha = 1;
|
||||
}
|
||||
if (w > 0 && h > 0 && this.time < 3000) {
|
||||
switch (this.direction) {
|
||||
case ProjectileDirection.BottomToTop:
|
||||
case ProjectileDirection.TopToBottom: {
|
||||
ctx.drawImage(ver, 0, ft, cell, fh, left, top, w, h);
|
||||
break;
|
||||
}
|
||||
case ProjectileDirection.LeftToRight:
|
||||
case ProjectileDirection.RightToLeft: {
|
||||
ctx.drawImage(hor, fl, 0, fw, cell, left, top, w, h);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.shadowBlur = 8;
|
||||
ctx.shadowColor = '#62c8f4';
|
||||
ctx.globalAlpha = 0.9;
|
||||
ctx.beginPath();
|
||||
const radius = 7 + Math.floor(Math.random() * 2);
|
||||
ctx.arc(this.x, this.y, radius, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
|
||||
export class BoomProjectile extends Projectile<TowerBoss> {
|
||||
damage: number = 3000;
|
||||
hitbox: Hitbox.Rect = new Hitbox.Rect(0, 0, 32, 32);
|
||||
|
||||
private bx: number = 0;
|
||||
private by: number = 0;
|
||||
private last: number = 500;
|
||||
|
||||
private damaged: boolean = false;
|
||||
private animated: boolean = false;
|
||||
|
||||
setData(x: number, y: number, last: number) {
|
||||
this.bx = x;
|
||||
this.by = y;
|
||||
this.last = last;
|
||||
this.setPosition(x * 32, y * 32);
|
||||
}
|
||||
|
||||
isIntersect(hitbox: Hitbox.HitboxType): boolean {
|
||||
if (this.time < this.last + 1000) return false;
|
||||
if (this.damaged) return false;
|
||||
if (hitbox instanceof Hitbox.Rect) {
|
||||
return Hitbox.checkRectRect(this.hitbox, hitbox);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
updateHitbox(x: number, y: number): void {
|
||||
this.hitbox.setPosition(x, y);
|
||||
}
|
||||
|
||||
doDamage(target: IStateDamageable): boolean {
|
||||
if (this.damaged) return false;
|
||||
target.hp -= this.damage;
|
||||
this.damaged = true;
|
||||
popDamage(this.damage, this.boss, '#e08aff');
|
||||
return true;
|
||||
}
|
||||
|
||||
ai(boss: TowerBoss, time: number, frame: number): void {
|
||||
if (!this.animated && time > this.last + 1000) {
|
||||
this.animated = true;
|
||||
core.drawAnimate('explosion1', this.bx, this.by);
|
||||
}
|
||||
if (time > this.last + 1100) {
|
||||
this.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
render(canvas: MotaOffscreenCanvas2D, transform: Transform): void {
|
||||
const ctx = canvas.ctx;
|
||||
const end = this.last + 1000;
|
||||
const r = 12;
|
||||
const mr = 27;
|
||||
ctx.save();
|
||||
if (this.time < end) {
|
||||
const angle = this.time / 500;
|
||||
const sin = Math.sin(angle);
|
||||
const cos = Math.cos(angle);
|
||||
ctx.fillStyle = 'rgb(255,50,50)';
|
||||
ctx.strokeStyle = 'rgb(255,50,50)';
|
||||
ctx.lineWidth = 1.5;
|
||||
ctx.globalAlpha = 0.8;
|
||||
const cx = this.x + 16;
|
||||
const cy = this.y + 16;
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, r, 0, Math.PI * 2);
|
||||
ctx.moveTo(cx + r * cos, cy + r * sin);
|
||||
ctx.lineTo(cx + mr * cos, cy + mr * sin);
|
||||
ctx.moveTo(cx - r * cos, cy - r * sin);
|
||||
ctx.lineTo(cx - mr * cos, cy - mr * sin);
|
||||
ctx.stroke();
|
||||
ctx.beginPath();
|
||||
ctx.arc(cx, cy, 2, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
if (this.time > end - 500) {
|
||||
const dt = this.time - end + 500;
|
||||
const pos = this.y - (1 - dt / 500) * 480;
|
||||
const img = core.material.images.images['boom.png'];
|
||||
ctx.drawImage(img, this.x, pos - 80, 36, 80);
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
|
||||
export class ChainProjectile extends Projectile<TowerBoss> {
|
||||
damage: number = 4000;
|
||||
hitbox: Hitbox.Line = new Hitbox.Line(0, 0, 0, 0);
|
||||
|
||||
private damaged: boolean = false;
|
||||
|
||||
isIntersect(hitbox: Hitbox.HitboxType): boolean {
|
||||
if (this.time < 1000) return false;
|
||||
if (this.damaged) return false;
|
||||
if (hitbox instanceof Hitbox.Rect) {
|
||||
return Hitbox.checkLineRect(this.hitbox, hitbox);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
updateHitbox(x: number, y: number): void {
|
||||
this.hitbox.setPoint1(x, y);
|
||||
}
|
||||
|
||||
doDamage(target: IStateDamageable): boolean {
|
||||
if (this.damaged) return false;
|
||||
target.hp -= this.damage;
|
||||
this.damaged = true;
|
||||
core.playSound('electron.opus');
|
||||
popDamage(this.damage, this.boss, '#8affd6');
|
||||
return true;
|
||||
}
|
||||
|
||||
ai(boss: TowerBoss, time: number, frame: number): void {
|
||||
if (time > 2000) {
|
||||
this.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
render(canvas: MotaOffscreenCanvas2D, transform: Transform): void {
|
||||
const ctx = canvas.ctx;
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(this.hitbox.x1, this.hitbox.y1);
|
||||
ctx.lineTo(this.hitbox.x2, this.hitbox.y2);
|
||||
|
||||
const progress = (this.time - 1000) / 1000;
|
||||
|
||||
if (this.time < 1000) {
|
||||
ctx.globalAlpha = 0.6;
|
||||
ctx.strokeStyle = 'rgb(220,100,255)';
|
||||
ctx.stroke();
|
||||
} else {
|
||||
ctx.lineWidth = 2;
|
||||
ctx.strokeStyle = '#fff';
|
||||
ctx.shadowBlur = 12;
|
||||
ctx.shadowColor = '#62c8f4';
|
||||
ctx.globalAlpha = 1 - progress;
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
@@ -1,353 +0,0 @@
|
||||
import { MotaOffscreenCanvas2D } from '@motajs/render';
|
||||
import {
|
||||
CameraAnimation,
|
||||
Container,
|
||||
LayerGroup,
|
||||
MotaRenderer,
|
||||
Shader,
|
||||
Sprite,
|
||||
disableViewport,
|
||||
enableViewport
|
||||
} from '@motajs/render';
|
||||
import type { HeroMover, MoveStep } from '@/game/state/move';
|
||||
import EventEmitter from 'eventemitter3';
|
||||
|
||||
export interface IChaseController {
|
||||
/** 本次追逐战实例 */
|
||||
readonly chase: Chase;
|
||||
|
||||
/**
|
||||
* 开始这个追逐战
|
||||
* @param fromSave 是否是从存档开始
|
||||
*/
|
||||
start(fromSave: boolean): void;
|
||||
|
||||
/**
|
||||
* 结束这个追逐战
|
||||
* @param success 是否逃脱成功
|
||||
*/
|
||||
end(success: boolean): void;
|
||||
|
||||
/**
|
||||
* 初始化这次追逐战的音频
|
||||
* @param fromSave 是否从存档开始
|
||||
*/
|
||||
initAudio(fromSave: boolean): void;
|
||||
}
|
||||
|
||||
export interface ChaseData {
|
||||
path: Partial<Record<FloorIds, LocArr[]>>;
|
||||
camera: Partial<Record<FloorIds, CameraAnimation>>;
|
||||
}
|
||||
|
||||
interface TimeListener {
|
||||
fn: (emitTime: number) => void;
|
||||
time: number;
|
||||
}
|
||||
|
||||
interface LocListener {
|
||||
fn: (x: number, y: number) => void;
|
||||
floorId: FloorIds;
|
||||
once: boolean;
|
||||
}
|
||||
|
||||
interface ChaseEvent {
|
||||
changeFloor: [floor: FloorIds];
|
||||
end: [success: boolean];
|
||||
start: [];
|
||||
step: [x: number, y: number];
|
||||
frame: [totalTime: number, floorTime: number];
|
||||
}
|
||||
|
||||
export class Chase extends EventEmitter<ChaseEvent> {
|
||||
static shader: Shader;
|
||||
|
||||
/** 本次追逐战的数据 */
|
||||
private readonly data: ChaseData;
|
||||
|
||||
/** 是否显示路线 */
|
||||
private showPath: boolean = false;
|
||||
/** 每层的路线显示 */
|
||||
private pathMap: Map<FloorIds, MotaOffscreenCanvas2D> = new Map();
|
||||
/** 当前的摄像机动画 */
|
||||
private nowCamera?: CameraAnimation;
|
||||
/** 当前楼层 */
|
||||
private nowFloor?: FloorIds;
|
||||
|
||||
/** 开始时刻 */
|
||||
startTime: number = 0;
|
||||
/** 进入当前楼层的时刻 */
|
||||
nowFloorTime: number = 0;
|
||||
/** 是否正在进行追逐战 */
|
||||
started: boolean = false;
|
||||
|
||||
/** 路径显示的sprite */
|
||||
private pathSprite?: Sprite;
|
||||
/** 当前 LayerGroup 渲染元素 */
|
||||
private layer: LayerGroup;
|
||||
/** 委托ticker的id */
|
||||
private delegation: number = -1;
|
||||
|
||||
/** 时间监听器 */
|
||||
private onTimeListener: TimeListener[] = [];
|
||||
/** 楼层时间监听器 */
|
||||
private onFloorTimeListener: Partial<Record<FloorIds, TimeListener[]>> = {};
|
||||
/** 勇士位置监听器 */
|
||||
private onHeroLocListener: Map<number, Set<LocListener>> = new Map();
|
||||
|
||||
/** 勇士移动实例 */
|
||||
private heroMove: HeroMover;
|
||||
|
||||
constructor(data: ChaseData, showPath: boolean = false) {
|
||||
super();
|
||||
|
||||
this.data = data;
|
||||
this.showPath = showPath;
|
||||
|
||||
const render = MotaRenderer.get('render-main')!;
|
||||
const layer = render.getElementById('layer-main')! as LayerGroup;
|
||||
this.layer = layer;
|
||||
|
||||
const mover = Mota.require('module', 'State').heroMoveCollection.mover;
|
||||
this.heroMove = mover;
|
||||
|
||||
mover.on('stepEnd', this.onStepEnd);
|
||||
}
|
||||
|
||||
private onStepEnd = (step: MoveStep) => {
|
||||
if (step.type === 'speed') return;
|
||||
const { x, y } = core.status.hero.loc;
|
||||
this.emitHeroLoc(x, y);
|
||||
this.emit('step', x, y);
|
||||
};
|
||||
|
||||
private emitHeroLoc(x: number, y: number) {
|
||||
if (!this.nowFloor) return;
|
||||
const floor = core.status.maps[this.nowFloor];
|
||||
const width = floor.width;
|
||||
const index = x + y * width;
|
||||
const list = this.onHeroLocListener.get(index);
|
||||
if (!list) return;
|
||||
const toDelete = new Set<LocListener>();
|
||||
list.forEach(v => {
|
||||
if (v.floorId === this.nowFloor) {
|
||||
v.fn(x, y);
|
||||
if (v.once) toDelete.add(v);
|
||||
}
|
||||
});
|
||||
toDelete.forEach(v => list.delete(v));
|
||||
}
|
||||
|
||||
private emitTime() {
|
||||
const now = Date.now();
|
||||
const nTime = now - this.startTime;
|
||||
const fTime = now - this.nowFloorTime;
|
||||
|
||||
this.emit('frame', nTime, fTime);
|
||||
|
||||
while (true) {
|
||||
const time = this.onTimeListener[0];
|
||||
if (!time) break;
|
||||
if (time.time <= nTime) {
|
||||
time.fn(nTime);
|
||||
this.onTimeListener.shift();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.nowFloor) return;
|
||||
const floor = this.onFloorTimeListener[this.nowFloor];
|
||||
if (!floor) return;
|
||||
|
||||
while (true) {
|
||||
const time = floor[0];
|
||||
if (!time) break;
|
||||
if (time.time <= fTime) {
|
||||
time.fn(nTime);
|
||||
floor.shift();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private tick = () => {
|
||||
if (!this.started) return;
|
||||
const floor = core.status.floorId;
|
||||
if (floor !== this.nowFloor) {
|
||||
this.changeFloor(floor);
|
||||
}
|
||||
this.emitTime();
|
||||
};
|
||||
|
||||
private readyPath() {
|
||||
for (const [key, nodes] of Object.entries(this.data.path)) {
|
||||
if (nodes.length === 0) return;
|
||||
const floor = key as FloorIds;
|
||||
const canvas = new MotaOffscreenCanvas2D();
|
||||
const ctx = canvas.ctx;
|
||||
const cell = 32;
|
||||
const half = cell / 2;
|
||||
const { width, height } = core.status.maps[floor];
|
||||
canvas.setHD(true);
|
||||
canvas.size(width * cell, height * cell);
|
||||
const [fx, fy] = nodes.shift()!;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(fx * cell + half, fy * cell + half);
|
||||
nodes.forEach(([x, y]) => {
|
||||
ctx.lineTo(x * cell + half, y * cell + half);
|
||||
});
|
||||
ctx.strokeStyle = '#0ff';
|
||||
ctx.globalAlpha = 0.6;
|
||||
ctx.stroke();
|
||||
this.pathMap.set(floor, canvas);
|
||||
}
|
||||
this.pathSprite = new Sprite('static', false, true);
|
||||
this.pathSprite.size(480, 480);
|
||||
this.pathSprite.pos(0, 0);
|
||||
this.pathSprite.setZIndex(120);
|
||||
this.pathSprite.setAntiAliasing(false);
|
||||
this.layer.appendChild(this.pathSprite);
|
||||
this.pathSprite.setRenderFn(canvas => {
|
||||
const ctx = canvas.ctx;
|
||||
const path = this.pathMap.get(core.status.floorId);
|
||||
if (!path) return;
|
||||
ctx.drawImage(path.canvas, 0, 0, path.width, path.height);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 当到达某个时间时触发函数
|
||||
* @param time 触发时刻
|
||||
* @param fn 触发时执行的函数,函数的参数表示实际触发时间
|
||||
*/
|
||||
onTime(time: number, fn: (emitTime: number) => void) {
|
||||
this.onTimeListener.push({ time, fn });
|
||||
if (this.started) {
|
||||
this.onTimeListener.sort((a, b) => a.time - b.time);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当在某个楼层中到达某个时间时触发函数
|
||||
* @param floor 触发楼层
|
||||
* @param time 从进入该楼层开始计算的触发时刻
|
||||
* @param fn 触发时执行的函数
|
||||
*/
|
||||
onFloorTime(floor: FloorIds, time: number, fn: (emitTime: number) => void) {
|
||||
this.onFloorTimeListener[floor] ??= [];
|
||||
const list = this.onFloorTimeListener[floor];
|
||||
list.push({ time, fn });
|
||||
if (this.started) {
|
||||
list.sort((a, b) => a.time - b.time);
|
||||
}
|
||||
}
|
||||
|
||||
private ensureLocListener(index: number) {
|
||||
const listener = this.onHeroLocListener.get(index);
|
||||
if (listener) return listener;
|
||||
else {
|
||||
const set = new Set<LocListener>();
|
||||
this.onHeroLocListener.set(index, set);
|
||||
return set;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当勇士走到某一层的某一格时执行函数
|
||||
* @param x 触发横坐标
|
||||
* @param y 触发纵坐标
|
||||
* @param floor 触发楼层
|
||||
* @param fn 触发函数
|
||||
* @param once 是否只执行一次
|
||||
*/
|
||||
onLoc(
|
||||
x: number,
|
||||
y: number,
|
||||
floor: FloorIds,
|
||||
fn: (x: number, y: number) => void,
|
||||
once: boolean = false
|
||||
) {
|
||||
const map = core.status.maps[floor];
|
||||
const { width } = map;
|
||||
const index = x + y * width;
|
||||
const set = this.ensureLocListener(index);
|
||||
set.add({ floorId: floor, fn, once });
|
||||
}
|
||||
|
||||
/**
|
||||
* 当勇士走到某一层的某一格时执行函数,且只执行一次
|
||||
* @param x 触发横坐标
|
||||
* @param y 触发纵坐标
|
||||
* @param floor 触发楼层
|
||||
* @param fn 触发函数
|
||||
*/
|
||||
onceLoc(
|
||||
x: number,
|
||||
y: number,
|
||||
floor: FloorIds,
|
||||
fn: (x: number, y: number) => void
|
||||
) {
|
||||
this.onLoc(x, y, floor, fn, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换楼层
|
||||
* @param floor 目标楼层
|
||||
*/
|
||||
changeFloor(floor: FloorIds) {
|
||||
if (floor === this.nowFloor) return;
|
||||
this.nowFloor = floor;
|
||||
if (this.nowCamera) {
|
||||
this.nowCamera.destroy();
|
||||
}
|
||||
const camera = this.data.camera[floor];
|
||||
if (camera) {
|
||||
camera.start();
|
||||
this.nowCamera = camera;
|
||||
}
|
||||
this.nowFloorTime = Date.now();
|
||||
this.emit('changeFloor', floor);
|
||||
}
|
||||
|
||||
start() {
|
||||
disableViewport();
|
||||
if (this.showPath) this.readyPath();
|
||||
this.changeFloor(core.status.floorId);
|
||||
this.startTime = Date.now();
|
||||
this.delegation = this.layer.delegateTicker(this.tick);
|
||||
this.started = true;
|
||||
for (const floorTime of Object.values(this.onFloorTimeListener)) {
|
||||
floorTime.sort((a, b) => a.time - b.time);
|
||||
}
|
||||
this.onTimeListener.sort((a, b) => a.time - b.time);
|
||||
const render = MotaRenderer.get('render-main')!;
|
||||
const mapDraw = render.getElementById('map-draw') as Container;
|
||||
Chase.shader.append(mapDraw);
|
||||
this.emit('start');
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束这次追逐战
|
||||
* @param success 是否成功逃脱
|
||||
*/
|
||||
end(success: boolean) {
|
||||
enableViewport();
|
||||
this.layer.removeTicker(this.delegation);
|
||||
this.pathSprite?.destroy();
|
||||
this.heroMove.off('stepEnd', this.onStepEnd);
|
||||
Chase.shader.remove();
|
||||
this.emit('end', success);
|
||||
this.removeAllListeners();
|
||||
this.pathMap.forEach(v => v.delete());
|
||||
this.pathMap.clear();
|
||||
}
|
||||
}
|
||||
|
||||
Mota.require('var', 'loading').once('coreInit', () => {
|
||||
const shader = new Shader();
|
||||
Chase.shader = shader;
|
||||
shader.size(480, 480);
|
||||
shader.setHD(true);
|
||||
});
|
||||
@@ -1,723 +0,0 @@
|
||||
import { Animation, hyper, linear, power, sleep } from 'mutate-animate';
|
||||
import { Chase, ChaseData, IChaseController } from './chase';
|
||||
import { completeAchievement } from '@motajs/legacy-ui';
|
||||
import {
|
||||
Camera,
|
||||
CameraAnimation,
|
||||
ICameraScale,
|
||||
LayerGroup,
|
||||
MotaRenderer,
|
||||
Sprite
|
||||
} from '@motajs/render';
|
||||
import { PointEffect, PointEffectType } from '../fx/pointShader';
|
||||
import { bgmController } from '@/module';
|
||||
|
||||
const path: Partial<Record<FloorIds, LocArr[]>> = {
|
||||
MT16: [
|
||||
[23, 23],
|
||||
[0, 23]
|
||||
],
|
||||
MT15: [
|
||||
[63, 4],
|
||||
[61, 4],
|
||||
[61, 5],
|
||||
[58, 5],
|
||||
[58, 8],
|
||||
[54, 8],
|
||||
[54, 11],
|
||||
[51, 11],
|
||||
[51, 8],
|
||||
[45, 8],
|
||||
[45, 4],
|
||||
[47, 4],
|
||||
[47, 6],
|
||||
[51, 6],
|
||||
[51, 5],
|
||||
[52, 5],
|
||||
[52, 3],
|
||||
[50, 3],
|
||||
[50, 5],
|
||||
[48, 5],
|
||||
[48, 3],
|
||||
[35, 3],
|
||||
[35, 5],
|
||||
[31, 5],
|
||||
[31, 7],
|
||||
[34, 7],
|
||||
[34, 9],
|
||||
[31, 9],
|
||||
[31, 11],
|
||||
[12, 11],
|
||||
[12, 8],
|
||||
[1, 8],
|
||||
[1, 7],
|
||||
[0, 7]
|
||||
],
|
||||
MT14: [
|
||||
[127, 7],
|
||||
[126, 7],
|
||||
[126, 8],
|
||||
[124, 8],
|
||||
[124, 7],
|
||||
[115.2, 7],
|
||||
[115.2, 9.2],
|
||||
[110.2, 9.2],
|
||||
[110.2, 11],
|
||||
[109.8, 11],
|
||||
[109.8, 8.8],
|
||||
[111.8, 8.8],
|
||||
[111.8, 7],
|
||||
[104, 7],
|
||||
[104, 3],
|
||||
[100, 3],
|
||||
[100, 4],
|
||||
[98, 4],
|
||||
[98, 3],
|
||||
[96, 3],
|
||||
[96, 6],
|
||||
[95, 6],
|
||||
[95, 7],
|
||||
[88, 7],
|
||||
[88, 6],
|
||||
[85, 6],
|
||||
[85, 8],
|
||||
[83, 8],
|
||||
[83, 9],
|
||||
[81, 9],
|
||||
[81, 11],
|
||||
[72, 11],
|
||||
[72, 5],
|
||||
[68, 5],
|
||||
[68, 8],
|
||||
[67, 8],
|
||||
[67, 10],
|
||||
[65, 10],
|
||||
[65, 11],
|
||||
[62, 11],
|
||||
[62, 9],
|
||||
[60, 9],
|
||||
[60, 11],
|
||||
[57, 11],
|
||||
[57, 9],
|
||||
[54, 9]
|
||||
]
|
||||
};
|
||||
|
||||
let back: Sprite | undefined;
|
||||
let contrastId: number = 0;
|
||||
const effect = new PointEffect();
|
||||
|
||||
Mota.require('var', 'loading').once('loaded', () => {
|
||||
effect.create(Chase.shader, 40);
|
||||
});
|
||||
|
||||
/**
|
||||
* 初始化并开始这个追逐战
|
||||
*/
|
||||
export function initChase(): IChaseController {
|
||||
const ani = new Animation();
|
||||
|
||||
const render = MotaRenderer.get('render-main')!;
|
||||
const layer = render.getElementById('layer-main')! as LayerGroup;
|
||||
|
||||
const camera = new Camera(layer);
|
||||
camera.clearOperation();
|
||||
camera.transform = layer.camera;
|
||||
camera.disable();
|
||||
const animation16 = new CameraAnimation(camera);
|
||||
const animation15 = new CameraAnimation(camera);
|
||||
const animation14 = new CameraAnimation(camera);
|
||||
effect.setTransform(layer.camera);
|
||||
|
||||
const data: ChaseData = {
|
||||
path,
|
||||
camera: {
|
||||
MT16: animation16,
|
||||
MT15: animation15,
|
||||
MT14: animation14
|
||||
}
|
||||
};
|
||||
|
||||
const chase = new Chase(data, flags.chaseHard === 0);
|
||||
|
||||
// 旋转在前,平移在后
|
||||
const translate1 = camera.addTranslate();
|
||||
const scale = camera.addScale();
|
||||
const rotate = camera.addRotate();
|
||||
const translate2 = camera.addTranslate();
|
||||
const translate = camera.addTranslate();
|
||||
|
||||
translate1.x = -7 * 32;
|
||||
translate1.y = -7 * 32;
|
||||
translate2.x = 7 * 32;
|
||||
translate2.y = 7 * 32;
|
||||
|
||||
translate.x = 10 * 32;
|
||||
translate.y = 10 * 32;
|
||||
|
||||
const inOut = hyper('sin', 'in-out');
|
||||
// MT16 摄像机动画
|
||||
animation16.translate(translate, 10, 10, 1, 0, linear());
|
||||
animation16.translate(translate, 0, 10, 1600, 0, hyper('sin', 'in'));
|
||||
// MT15 摄像机动画
|
||||
animation15.rotate(rotate, -Math.PI / 30, 4000, 0, inOut);
|
||||
animation15.rotate(rotate, 0, 3000, 5000, inOut);
|
||||
animation15.rotate(rotate, -Math.PI / 40, 1800, 11000, inOut);
|
||||
animation15.rotate(rotate, 0, 2000, 13000, inOut);
|
||||
animation15.translate(translate, 49, 0, 1, 0, linear());
|
||||
animation15.translate(translate, 45, 0, 2324, 0, hyper('sin', 'in'));
|
||||
animation15.translate(translate, 40, 0, 1992, 2324, hyper('sin', 'out'));
|
||||
animation15.translate(translate, 41, 0, 498, 5312, hyper('sin', 'in-out'));
|
||||
animation15.translate(translate, 37, 0, 1660, 5810, hyper('sin', 'in'));
|
||||
animation15.translate(translate, 29, 0, 830, 7470, hyper('sin', 'out'));
|
||||
animation15.translate(translate, 25, 0, 996, 11454, hyper('sin', 'in'));
|
||||
animation15.translate(translate, 12, 0, 996, 12450, linear());
|
||||
animation15.translate(translate, 0, 0, 1470, 13446, hyper('sin', 'out'));
|
||||
// MT14 摄像机动画
|
||||
animation14.rotate(rotate, -Math.PI / 70, 1000, 0, inOut);
|
||||
animation14.rotate(rotate, 0, 4000, 2000, inOut);
|
||||
animation14.translate(translate, 113, 0, 1, 0, hyper('sin', 'in'));
|
||||
animation14.translate(translate, 109, 0, 1328, 0, hyper('sin', 'in'));
|
||||
animation14.translate(translate, 104, 0, 332, 1328, hyper('sin', 'out'));
|
||||
animation14.translate(translate, 92, 0, 2822, 5478, hyper('sin', 'in'));
|
||||
animation14.translate(translate, 84, 0, 1992, 8300, linear());
|
||||
animation14.translate(translate, 74, 0, 2988, 10292, linear());
|
||||
animation14.translate(translate, 65, 0, 2988, 13280, linear());
|
||||
animation14.translate(translate, 58, 0, 1992, 16268, linear());
|
||||
animation14.translate(translate, 47, 0, 3320, 18260, linear());
|
||||
animation14.translate(translate, 36, 0, 3320, 21580, linear());
|
||||
animation14.translate(translate, 0, 0, 9960, 24900, linear());
|
||||
|
||||
chase.on('end', success => {
|
||||
camera.transform.reset();
|
||||
camera.transform.translate(
|
||||
-translate.x * 32 - 7 * 32,
|
||||
-translate.y * 32 - 7 * 32
|
||||
);
|
||||
animation16.destroy();
|
||||
animation15.destroy();
|
||||
animation14.destroy();
|
||||
camera.destroy();
|
||||
back?.destroy();
|
||||
back = void 0;
|
||||
core.removeFlag('onChase');
|
||||
core.removeFlag('chaseId');
|
||||
|
||||
if (success) {
|
||||
completeAchievement('challenge', 0);
|
||||
}
|
||||
});
|
||||
|
||||
judgeFail1(chase, ani, camera);
|
||||
drawBack(chase, ani);
|
||||
para1(chase, ani);
|
||||
para2(chase, ani);
|
||||
para3(chase, ani);
|
||||
processScale(chase, ani, scale, camera);
|
||||
|
||||
Mota.Plugin.require('chase_g').chaseInit1();
|
||||
|
||||
chase.on('end', () => {
|
||||
effect.end();
|
||||
camera.destroy();
|
||||
});
|
||||
|
||||
chase.on('frame', () => {
|
||||
effect.requestUpdate();
|
||||
});
|
||||
|
||||
chase.on('changeFloor', () => {
|
||||
effect.clearEffect();
|
||||
});
|
||||
|
||||
const controller: IChaseController = {
|
||||
chase,
|
||||
start(fromSave) {
|
||||
core.setFlag('onChase', true);
|
||||
core.setFlag('chaseId', 1);
|
||||
chase.start();
|
||||
camera.enable();
|
||||
wolfMove(chase);
|
||||
effect.use();
|
||||
effect.start();
|
||||
if (fromSave) {
|
||||
initFromSave(chase);
|
||||
core.autosave();
|
||||
}
|
||||
},
|
||||
end(success) {
|
||||
chase.end(success);
|
||||
},
|
||||
initAudio(fromSave) {
|
||||
if (fromSave) initFromSave(chase);
|
||||
else initAudio(chase);
|
||||
}
|
||||
};
|
||||
return controller;
|
||||
}
|
||||
|
||||
function initAudio(chase: Chase) {
|
||||
playAudio(0, chase);
|
||||
}
|
||||
|
||||
function initFromSave(chase: Chase) {
|
||||
playAudio(43.5, chase);
|
||||
}
|
||||
|
||||
function playAudio(from: number, chase: Chase) {
|
||||
const playing = bgmController.playingBgm;
|
||||
bgmController.play('escape.opus', from);
|
||||
bgmController.blockChange();
|
||||
chase.on('end', () => {
|
||||
bgmController.unblockChange();
|
||||
if (playing) bgmController.play(playing);
|
||||
});
|
||||
}
|
||||
|
||||
function processScale(
|
||||
chase: Chase,
|
||||
ani: Animation,
|
||||
scale: ICameraScale,
|
||||
camera: Camera
|
||||
) {
|
||||
chase.onceLoc(35, 3, 'MT15', () => {
|
||||
camera.applyScaleAnimation(scale, ani, 2200);
|
||||
ani.mode(linear()).time(1).scale(1.2);
|
||||
sleep(150).then(() => {
|
||||
ani.mode(hyper('sin', 'out')).time(2000).scale(1);
|
||||
});
|
||||
});
|
||||
chase.onFloorTime('MT14', 100, () => {
|
||||
camera.applyScaleAnimation(scale, ani, 30000);
|
||||
ani.mode(hyper('sin', 'in-out')).time(3000).scale(0.8);
|
||||
});
|
||||
chase.onceLoc(57, 10, 'MT14', () => {
|
||||
ani.mode(power(6, 'in')).time(200).scale(1.1);
|
||||
sleep(200).then(() => {
|
||||
ani.mode(hyper('sin', 'in-out')).time(3000).scale(1);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function wolfMove(chase: Chase) {
|
||||
core.moveBlock(23, 17, Array(6).fill('down'), 80);
|
||||
await sleep(550);
|
||||
core.setBlock(508, 23, 23);
|
||||
}
|
||||
|
||||
function judgeFail1(chase: Chase, ani: Animation, camera: Camera) {
|
||||
chase.on('frame', () => {
|
||||
const now = Date.now();
|
||||
const time = now - chase.nowFloorTime;
|
||||
if (time < 500) return;
|
||||
if (core.status.hero.loc.x > -camera.transform.x / 32 + 22) {
|
||||
chase.end(false);
|
||||
if (ani.value.rect !== void 0) {
|
||||
ani.time(750).apply('rect', 0);
|
||||
}
|
||||
core.lose('逃跑失败');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function drawBack(chase: Chase, ani: Animation) {
|
||||
chase.onFloorTime('MT15', 0, () => {
|
||||
ani.register('rect', 0);
|
||||
ani.mode(hyper('sin', 'out')).time(1500).absolute().apply('rect', 64);
|
||||
|
||||
const render = MotaRenderer.get('render-main')!;
|
||||
const layer = render.getElementById('layer-main')! as LayerGroup;
|
||||
back = new Sprite('absolute', false);
|
||||
back.setZIndex(100);
|
||||
back.size(480, 480);
|
||||
back.pos(0, 0);
|
||||
back.append(layer);
|
||||
back.setRenderFn(canvas => {
|
||||
const ctx = canvas.ctx;
|
||||
ctx.fillStyle = '#000';
|
||||
ctx.fillRect(0, 0, 480, ani.value.rect);
|
||||
ctx.fillRect(0, 480, 480, -ani.value.rect);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function addCommonWarp(x: number, y: number) {
|
||||
effect.addEffect(
|
||||
PointEffectType.CircleWarp,
|
||||
Date.now(),
|
||||
500,
|
||||
[x * 32 + 16, y * 32 + 16, 48, 32],
|
||||
[1 / 10, 6, 0.8, 0],
|
||||
[0, -Math.PI, 0, 0]
|
||||
);
|
||||
}
|
||||
|
||||
function addMediumWarp(x: number, y: number) {
|
||||
effect.addEffect(
|
||||
PointEffectType.CircleWarp,
|
||||
Date.now(),
|
||||
5000,
|
||||
[x * 32 + 16, y * 32 + 16, 480, 64],
|
||||
[1 / 40, 1, 0.5, 0],
|
||||
[0, Math.PI * 2, 0, 0]
|
||||
);
|
||||
}
|
||||
|
||||
function addLargeWarp(x: number, y: number) {
|
||||
effect.addEffect(
|
||||
PointEffectType.CircleWarp,
|
||||
Date.now(),
|
||||
10000,
|
||||
[x * 32 + 16, y * 32 + 16, 1080, 96],
|
||||
[1 / 25, 1, 0.5, 0],
|
||||
[0, Math.PI * 2, 0, 0]
|
||||
);
|
||||
}
|
||||
|
||||
function addCommonContrast(x: number, y: number, ani: Animation, chase: Chase) {
|
||||
const id = contrastId++;
|
||||
const name = 'contrast' + id;
|
||||
ani.register(name, 1);
|
||||
sleep(500).then(() => {
|
||||
ani.mode(linear()).absolute().time(1500).apply(name, 0);
|
||||
});
|
||||
const fx = effect.addEffect(
|
||||
PointEffectType.CircleContrast,
|
||||
Date.now(),
|
||||
2000,
|
||||
[x * 32 + 16, y * 32 + 16, 48, 8],
|
||||
[1, 0, 0, 0]
|
||||
);
|
||||
const fn = () => {
|
||||
effect.setEffect(fx, void 0, [ani.value[name], 0, 0, 0]);
|
||||
};
|
||||
chase.on('frame', fn);
|
||||
sleep(2000).then(() => {
|
||||
chase.off('frame', fn);
|
||||
});
|
||||
}
|
||||
|
||||
function addMediumContrast(x: number, y: number, ani: Animation, chase: Chase) {
|
||||
const id = contrastId++;
|
||||
const name = 'contrast' + id;
|
||||
ani.register(name, 1);
|
||||
sleep(1500).then(() => {
|
||||
ani.mode(linear()).absolute().time(5000).apply(name, 0);
|
||||
});
|
||||
const fx = effect.addEffect(
|
||||
PointEffectType.CircleContrast,
|
||||
Date.now(),
|
||||
7500,
|
||||
[x * 32 + 16, y * 32 + 16, 144, 32],
|
||||
[1, 0, 0, 0]
|
||||
);
|
||||
const fn = () => {
|
||||
effect.setEffect(
|
||||
fx,
|
||||
[x * 32 + 16, y * 32 + 16, 144 + (1 - ani.value[name]) * 240, 32],
|
||||
[ani.value[name], 0, 0, 0]
|
||||
);
|
||||
};
|
||||
chase.on('frame', fn);
|
||||
sleep(7500).then(() => {
|
||||
chase.off('frame', fn);
|
||||
});
|
||||
}
|
||||
|
||||
function addLargeContrast(x: number, y: number, ani: Animation, chase: Chase) {
|
||||
const id = contrastId++;
|
||||
const name = 'contrast' + id;
|
||||
ani.register(name, 1);
|
||||
sleep(500).then(() => {
|
||||
ani.mode(linear()).absolute().time(9500).apply(name, 0);
|
||||
});
|
||||
const fx = effect.addEffect(
|
||||
PointEffectType.CircleContrast,
|
||||
Date.now(),
|
||||
7500,
|
||||
[x * 32 + 16, y * 32 + 16, 324, 240],
|
||||
[1, 0, 0, 0]
|
||||
);
|
||||
const fn = () => {
|
||||
effect.setEffect(
|
||||
fx,
|
||||
[x * 32 + 16, y * 32 + 16, 324 + (1 - ani.value[name]) * 720, 240],
|
||||
[ani.value[name], 0, 0, 0]
|
||||
);
|
||||
};
|
||||
chase.on('frame', fn);
|
||||
sleep(10000).then(() => {
|
||||
chase.off('frame', fn);
|
||||
});
|
||||
}
|
||||
|
||||
function explode1(x: number, y: number, ani: Animation, chase: Chase) {
|
||||
core.setBlock(336, x, y);
|
||||
core.drawAnimate('explosion1', x, y);
|
||||
addCommonWarp(x, y);
|
||||
addCommonContrast(x, y, ani, chase);
|
||||
}
|
||||
|
||||
function para1(chase: Chase, ani: Animation) {
|
||||
chase.onFloorTime('MT15', 830, () => {
|
||||
for (let tx = 53; tx < 58; tx++) {
|
||||
for (let ty = 3; ty < 8; ty++) {
|
||||
core.setBlock(336, tx, ty);
|
||||
}
|
||||
}
|
||||
core.drawAnimate('explosion3', 55, 5);
|
||||
addMediumWarp(55, 5);
|
||||
addMediumContrast(55, 5, ani, chase);
|
||||
});
|
||||
chase.onFloorTime('MT15', 1080, () => {
|
||||
explode1(58, 9, ani, chase);
|
||||
explode1(59, 9, ani, chase);
|
||||
});
|
||||
chase.onFloorTime('MT15', 1190, () => {
|
||||
explode1(53, 8, ani, chase);
|
||||
explode1(52, 8, ani, chase);
|
||||
});
|
||||
chase.onFloorTime('MT15', 1580, () => {
|
||||
explode1(51, 7, ani, chase);
|
||||
});
|
||||
chase.onFloorTime('MT15', 1830, () => {
|
||||
explode1(47, 7, ani, chase);
|
||||
explode1(49, 9, ani, chase);
|
||||
});
|
||||
}
|
||||
|
||||
function para2(chase: Chase, ani: Animation) {
|
||||
let emitted32x9 = false;
|
||||
chase.onceLoc(45, 8, 'MT15', () => {
|
||||
explode1(45, 9, ani, chase);
|
||||
});
|
||||
chase.onceLoc(45, 6, 'MT15', () => {
|
||||
explode1(44, 6, ani, chase);
|
||||
});
|
||||
chase.onceLoc(45, 4, 'MT15', () => {
|
||||
explode1(44, 4, ani, chase);
|
||||
core.drawAnimate('explosion1', 48, 6);
|
||||
core.removeBlock(48, 6);
|
||||
addCommonWarp(48, 6);
|
||||
addCommonContrast(48, 6, ani, chase);
|
||||
});
|
||||
chase.onceLoc(41, 3, 'MT15', () => {
|
||||
explode1(41, 4, ani, chase);
|
||||
explode1(32, 6, ani, chase);
|
||||
});
|
||||
chase.onceLoc(35, 3, 'MT15', () => {
|
||||
core.drawAnimate('explosion3', 37, 7);
|
||||
addMediumWarp(37, 7);
|
||||
addMediumContrast(37, 7, ani, chase);
|
||||
for (let tx = 36; tx < 42; tx++) {
|
||||
for (let ty = 4; ty < 11; ty++) {
|
||||
core.setBlock(336, tx, ty);
|
||||
}
|
||||
}
|
||||
});
|
||||
chase.onceLoc(31, 5, 'MT15', () => {
|
||||
core.removeBlock(34, 8);
|
||||
core.removeBlock(33, 8);
|
||||
core.drawAnimate('explosion1', 34, 8);
|
||||
core.drawAnimate('explosion1', 33, 8);
|
||||
addCommonWarp(34, 8);
|
||||
addCommonWarp(33, 8);
|
||||
addCommonContrast(34, 8, ani, chase);
|
||||
addCommonContrast(33, 8, ani, chase);
|
||||
});
|
||||
chase.onceLoc(33, 7, 'MT15', () => {
|
||||
explode1(32, 9, ani, chase);
|
||||
});
|
||||
chase.onceLoc(33, 9, 'MT15', () => {
|
||||
if (emitted32x9) return;
|
||||
emitted32x9 = true;
|
||||
core.removeBlock(32, 9);
|
||||
core.drawAnimate('explosion1', 32, 9);
|
||||
addCommonWarp(32, 9);
|
||||
addCommonContrast(32, 9, ani, chase);
|
||||
});
|
||||
chase.onceLoc(34, 9, 'MT15', () => {
|
||||
if (emitted32x9) return;
|
||||
emitted32x9 = true;
|
||||
core.removeBlock(32, 9);
|
||||
core.drawAnimate('explosion1', 32, 9);
|
||||
addCommonWarp(32, 9);
|
||||
addCommonContrast(32, 9, ani, chase);
|
||||
});
|
||||
chase.onceLoc(35, 9, 'MT15', () => {
|
||||
if (emitted32x9) return;
|
||||
emitted32x9 = true;
|
||||
core.removeBlock(32, 9);
|
||||
core.drawAnimate('explosion1', 32, 9);
|
||||
addCommonWarp(32, 9);
|
||||
});
|
||||
for (let x = 19; x < 31; x++) {
|
||||
const xx = x;
|
||||
chase.onceLoc(xx, 11, 'MT15', () => {
|
||||
core.setBlock(336, xx + 1, 11);
|
||||
core.drawAnimate('explosion1', xx + 1, 11);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function para3(chase: Chase, ani: Animation) {
|
||||
chase.onceLoc(126, 7, 'MT14', () => {
|
||||
explode1(126, 6, ani, chase);
|
||||
explode1(124, 6, ani, chase);
|
||||
explode1(124, 9, ani, chase);
|
||||
explode1(126, 9, ani, chase);
|
||||
});
|
||||
chase.onceLoc(123, 7, 'MT14', () => {
|
||||
core.setBlock(508, 127, 7);
|
||||
core.jumpBlock(127, 7, 112, 7, 500, true);
|
||||
setTimeout(() => {
|
||||
core.setBlock(509, 112, 7);
|
||||
}, 520);
|
||||
core.drawHeroAnimate('amazed');
|
||||
explode1(121, 6, ani, chase);
|
||||
explode1(122, 6, ani, chase);
|
||||
explode1(120, 8, ani, chase);
|
||||
explode1(121, 8, ani, chase);
|
||||
explode1(122, 8, ani, chase);
|
||||
});
|
||||
let emitted110x10 = false;
|
||||
let emitted112x8 = false;
|
||||
chase.onceLoc(110, 10, 'MT14', () => {
|
||||
explode1(109, 11, ani, chase);
|
||||
core.removeBlock(112, 8);
|
||||
core.drawAnimate('explosion1', 112, 8);
|
||||
addCommonWarp(112, 8);
|
||||
addCommonContrast(112, 8, ani, chase);
|
||||
core.insertAction([
|
||||
{ type: 'moveHero', time: 400, steps: ['backward:1'] }
|
||||
]);
|
||||
emitted110x10 = true;
|
||||
});
|
||||
chase.onLoc(112, 8, 'MT14', () => {
|
||||
if (!emitted110x10 || emitted112x8) return;
|
||||
core.jumpBlock(112, 7, 110, 4, 500, true);
|
||||
core.drawHeroAnimate('amazed');
|
||||
setTimeout(() => {
|
||||
core.setBlock(506, 110, 4);
|
||||
}, 540);
|
||||
emitted112x8 = true;
|
||||
});
|
||||
chase.onceLoc(118, 7, 'MT14', () => {
|
||||
explode1(117, 6, ani, chase);
|
||||
explode1(116, 6, ani, chase);
|
||||
explode1(115, 6, ani, chase);
|
||||
explode1(114, 6, ani, chase);
|
||||
explode1(117, 8, ani, chase);
|
||||
explode1(116, 8, ani, chase);
|
||||
});
|
||||
chase.onceLoc(112, 7, 'MT14', () => {
|
||||
explode1(112, 8, ani, chase);
|
||||
explode1(113, 7, ani, chase);
|
||||
});
|
||||
chase.onceLoc(115, 7, 'MT14', () => {
|
||||
for (let tx = 111; tx <= 115; tx++) {
|
||||
explode1(tx, 10, ani, chase);
|
||||
}
|
||||
explode1(112, 8, ani, chase);
|
||||
});
|
||||
chase.onceLoc(110, 7, 'MT14', () => {
|
||||
core.jumpBlock(97, 4, 120, -3, 2000);
|
||||
for (let tx = 109; tx <= 120; tx++) {
|
||||
for (let ty = 3; ty <= 11; ty++) {
|
||||
if (ty == 7) continue;
|
||||
core.setBlock(336, tx, ty);
|
||||
}
|
||||
}
|
||||
core.drawAnimate('explosion2', 119, 7);
|
||||
addLargeWarp(119, 7);
|
||||
addLargeContrast(119, 7, ani, chase);
|
||||
core.removeBlock(105, 7);
|
||||
core.drawAnimate('explosion1', 105, 7);
|
||||
addCommonWarp(105, 7);
|
||||
addCommonContrast(105, 7, ani, chase);
|
||||
});
|
||||
chase.onceLoc(97, 3, 'MT14', () => {
|
||||
explode1(95, 3, ani, chase);
|
||||
explode1(93, 6, ani, chase);
|
||||
});
|
||||
chase.onceLoc(88, 6, 'MT14', () => {
|
||||
explode1(87, 4, ani, chase);
|
||||
explode1(88, 5, ani, chase);
|
||||
});
|
||||
chase.onceLoc(86, 6, 'MT14', () => {
|
||||
explode1(84, 6, ani, chase);
|
||||
explode1(85, 5, ani, chase);
|
||||
explode1(86, 8, ani, chase);
|
||||
});
|
||||
chase.onceLoc(81, 9, 'MT14', () => {
|
||||
explode1(81, 8, ani, chase);
|
||||
explode1(82, 11, ani, chase);
|
||||
});
|
||||
chase.onceLoc(72, 11, 'MT14', () => {
|
||||
explode1(73, 8, ani, chase);
|
||||
explode1(72, 4, ani, chase);
|
||||
});
|
||||
chase.onceLoc(72, 7, 'MT14', () => {
|
||||
for (let tx = 74; tx < 86; tx++) {
|
||||
for (let ty = 3; ty < 12; ty++) {
|
||||
core.setBlock(336, tx, ty);
|
||||
}
|
||||
}
|
||||
core.drawAnimate('explosion2', 79, 7);
|
||||
addLargeWarp(79, 7);
|
||||
addLargeContrast(79, 7, ani, chase);
|
||||
});
|
||||
chase.onceLoc(68, 5, 'MT14', () => {
|
||||
explode1(68, 4, ani, chase);
|
||||
explode1(67, 6, ani, chase);
|
||||
});
|
||||
chase.onceLoc(67, 10, 'MT14', () => {
|
||||
for (let tx = 65; tx <= 72; tx++) {
|
||||
for (let ty = 3; ty <= 9; ty++) {
|
||||
core.setBlock(336, tx, ty);
|
||||
}
|
||||
}
|
||||
core.setBlock(336, 72, 10);
|
||||
core.setBlock(336, 72, 11);
|
||||
core.drawAnimate('explosion3', 69, 5);
|
||||
addMediumWarp(69, 5);
|
||||
addMediumContrast(69, 5, ani, chase);
|
||||
});
|
||||
chase.onceLoc(64, 11, 'MT14', () => {
|
||||
explode1(63, 9, ani, chase);
|
||||
explode1(60, 8, ani, chase);
|
||||
explode1(56, 11, ani, chase);
|
||||
});
|
||||
chase.onceLoc(57, 9, 'MT14', () => {
|
||||
for (let tx = 58; tx <= 64; tx++) {
|
||||
for (let ty = 3; ty <= 11; ty++) {
|
||||
core.setBlock(336, tx, ty);
|
||||
}
|
||||
}
|
||||
core.drawAnimate('explosion2', 61, 7);
|
||||
addLargeWarp(61, 7);
|
||||
addLargeContrast(61, 7, ani, chase);
|
||||
});
|
||||
const exploded: Set<number> = new Set();
|
||||
chase.on('step', (x, y) => {
|
||||
if (core.status.floorId !== 'MT14') return;
|
||||
if (exploded.has(x)) return;
|
||||
if (x > 20 && x < 49) {
|
||||
for (let ty = 3; ty <= 11; ty++) {
|
||||
core.setBlock(336, x + 4, ty);
|
||||
core.drawAnimate('explosion1', x + 4, ty);
|
||||
}
|
||||
exploded.add(x);
|
||||
}
|
||||
});
|
||||
chase.onceLoc(21, 7, 'MT14', async () => {
|
||||
flags.finishChase1 = true;
|
||||
Mota.Plugin.require('replay_g').clip('choices:0');
|
||||
core.showStatusBar();
|
||||
ani.time(750).apply('rect', 0);
|
||||
chase.end(true);
|
||||
await sleep(750);
|
||||
ani.ticker.destroy();
|
||||
core.deleteCanvas('chaseBack');
|
||||
});
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { IChaseController } from './chase';
|
||||
import { initChase as init1 } from './chase1';
|
||||
|
||||
let nowChase: IChaseController | undefined;
|
||||
|
||||
const chaseIndexes: Record<number, () => IChaseController> = {
|
||||
0: init1
|
||||
};
|
||||
|
||||
export function getNow() {
|
||||
return nowChase;
|
||||
}
|
||||
|
||||
export function initChase(index: number) {
|
||||
nowChase?.end(false);
|
||||
const controller = chaseIndexes[index]();
|
||||
nowChase = controller;
|
||||
controller.chase.on('end', () => {
|
||||
nowChase = void 0;
|
||||
});
|
||||
return nowChase;
|
||||
}
|
||||
|
||||
export function start(fromSave: boolean) {
|
||||
nowChase?.start(fromSave);
|
||||
}
|
||||
|
||||
export function end(success: boolean) {
|
||||
nowChase?.end(success);
|
||||
}
|
||||
|
||||
export function initAudio(fromSave: boolean) {
|
||||
nowChase?.initAudio(fromSave);
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
import {
|
||||
wrapInstancedComponent,
|
||||
MotaOffscreenCanvas2D,
|
||||
RenderItem,
|
||||
RenderItemPosition,
|
||||
Transform
|
||||
} from '@motajs/render';
|
||||
|
||||
// 渲染端的向后兼容用,会充当两个版本间过渡的作用
|
||||
class Change extends RenderItem {
|
||||
private tips: string[] = [];
|
||||
/** 当前小贴士 */
|
||||
private usingTip: string = '';
|
||||
/** 透明度 */
|
||||
private backAlpha: number = 0;
|
||||
private title: string = '';
|
||||
|
||||
constructor(type: RenderItemPosition) {
|
||||
super(type, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置楼传过程中的小贴士
|
||||
*/
|
||||
setTips(tip: string[]) {
|
||||
this.tips = tip;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置标题
|
||||
*/
|
||||
setTitle(title: string) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示楼层切换的从透明变黑的动画
|
||||
* @param time 动画时长
|
||||
*/
|
||||
showChange(time: number) {
|
||||
const length = this.tips.length;
|
||||
const tip = this.tips[Math.floor(Math.random() * length)] ?? '';
|
||||
this.usingTip = tip;
|
||||
|
||||
return new Promise<void>(res => {
|
||||
const start = Date.now();
|
||||
const id = this.delegateTicker(
|
||||
() => {
|
||||
const dt = Date.now() - start;
|
||||
const progress = dt / time;
|
||||
if (progress > 1) {
|
||||
this.backAlpha = 1;
|
||||
this.removeTicker(id);
|
||||
} else {
|
||||
this.backAlpha = progress;
|
||||
}
|
||||
this.update();
|
||||
},
|
||||
10000,
|
||||
res
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示楼层切换从黑到透明的动画
|
||||
* @param time 动画时长
|
||||
*/
|
||||
async hideChange(time: number) {
|
||||
return new Promise<void>(res => {
|
||||
const start = Date.now();
|
||||
const id = this.delegateTicker(
|
||||
() => {
|
||||
const dt = Date.now() - start;
|
||||
const progress = dt / time;
|
||||
if (progress > 1) {
|
||||
this.removeTicker(id);
|
||||
this.backAlpha = 0;
|
||||
} else {
|
||||
this.backAlpha = 1 - progress;
|
||||
}
|
||||
this.update();
|
||||
},
|
||||
10000,
|
||||
res
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
protected render(
|
||||
canvas: MotaOffscreenCanvas2D,
|
||||
_transform: Transform
|
||||
): void {
|
||||
if (this.backAlpha === 0) return;
|
||||
const ctx = canvas.ctx;
|
||||
ctx.globalAlpha = this.backAlpha;
|
||||
ctx.fillStyle = '#000';
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.font = '32px "normal"';
|
||||
ctx.fillText(this.title, canvas.width / 2, canvas.height * 0.4);
|
||||
ctx.font = '16px "normal"';
|
||||
if (this.usingTip.length > 0) {
|
||||
ctx.fillText(
|
||||
'小贴士:' + this.usingTip,
|
||||
canvas.width / 2,
|
||||
canvas.height * 0.75
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const FloorChange = wrapInstancedComponent(() => new Change('static'));
|
||||
@@ -1,225 +0,0 @@
|
||||
import { Animation, linear, sleep } from 'mutate-animate';
|
||||
import { has } from '@motajs/legacy-ui';
|
||||
|
||||
// todo: 移植到渲染树
|
||||
|
||||
interface SplittedImage {
|
||||
canvas: HTMLCanvasElement;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
interface FraggingImage extends SplittedImage {
|
||||
/** 横坐标增量 */
|
||||
deltaX: number;
|
||||
/** 纵坐标增量 */
|
||||
deltaY: number;
|
||||
endRad: number;
|
||||
}
|
||||
|
||||
/** 最大移动距离,最终位置距离中心的距离变成原来的几倍 */
|
||||
const MAX_MOVE_LENGTH = 1.15;
|
||||
/** 移动距离波动,在最大移动距离的基础上加上多少倍距离的波动距离 */
|
||||
const MOVE_FLUSH = 0.7;
|
||||
/** 最大旋转角,单位是弧度 */
|
||||
const MAX_ROTATE = 0.5;
|
||||
/** 碎裂动画的速率曲线函数 */
|
||||
const FRAG_TIMING = linear();
|
||||
|
||||
export function init() {
|
||||
return;
|
||||
Mota.rewrite(core.events, 'afterBattle', 'add', (_, enemy, x, y) => {
|
||||
// 打怪特效
|
||||
const setting = Mota.require('var', 'mainSetting');
|
||||
if (setting.getValue('fx.frag') && has(x) && has(y)) {
|
||||
const frame = core.status.globalAnimateStatus % 2;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 32;
|
||||
canvas.height = 32;
|
||||
core.drawIcon(canvas, enemy.id, 0, 0, 32, 32, frame);
|
||||
const manager = applyFragWith(canvas);
|
||||
const frag = manager.canvas;
|
||||
frag.style.imageRendering = 'pixelated';
|
||||
frag.style.width = `${frag.width * core.domStyle.scale}px`;
|
||||
frag.style.height = `${frag.height * core.domStyle.scale}px`;
|
||||
const left =
|
||||
(x * 32 + 16 - frag.width / 2 - core.bigmap.offsetX) *
|
||||
core.domStyle.scale;
|
||||
const top =
|
||||
(y * 32 + 16 - frag.height / 2 - core.bigmap.offsetY) *
|
||||
core.domStyle.scale;
|
||||
frag.style.left = `${left}px`;
|
||||
frag.style.top = `${top}px`;
|
||||
frag.style.zIndex = '45';
|
||||
frag.style.position = 'absolute';
|
||||
frag.style.filter = 'sepia(20%)brightness(120%)';
|
||||
core.dom.gameDraw.appendChild(frag);
|
||||
manager.onEnd.then(() => {
|
||||
frag.remove();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function applyFragWith(
|
||||
canvas: HTMLCanvasElement,
|
||||
length: number = 4,
|
||||
time: number = 1000,
|
||||
config: any = {} // todo: 类型标注
|
||||
) {
|
||||
// 先切分图片
|
||||
const imgs = splitCanvas(canvas, length);
|
||||
const cx = canvas.width / 2;
|
||||
const cy = canvas.height / 2;
|
||||
|
||||
let maxX = 0;
|
||||
let maxY = 0;
|
||||
const toMove: FraggingImage[] = imgs.map(v => {
|
||||
const centerX = v.x + v.canvas.width / 2;
|
||||
const centerY = v.y + v.canvas.height / 2;
|
||||
const onX = centerX === cx;
|
||||
const onY = centerY === cy;
|
||||
const mml = config.maxMoveLength ?? MAX_MOVE_LENGTH;
|
||||
const mf = config.moveFlush ?? MOVE_FLUSH;
|
||||
const rate = mml - 1 + Math.random() ** 3 * mf;
|
||||
let endX = onY ? 0 : (centerX - cx) * rate;
|
||||
let endY = onX ? 0 : (centerY - cy) * rate;
|
||||
const mx = Math.abs(endX + centerX) + Math.abs(v.canvas.width);
|
||||
const my = Math.abs(endY + centerY) + Math.abs(v.canvas.height);
|
||||
if (mx > maxX) maxX = mx;
|
||||
if (my > maxY) maxY = my;
|
||||
const r = config.maxRotate ?? MAX_ROTATE;
|
||||
const endRad = Math.random() * r * 2 - r;
|
||||
|
||||
return {
|
||||
deltaX: endX,
|
||||
deltaY: endY,
|
||||
endRad,
|
||||
x: centerX,
|
||||
y: centerY,
|
||||
canvas: v.canvas
|
||||
};
|
||||
});
|
||||
|
||||
// 再执行动画
|
||||
const frag = document.createElement('canvas');
|
||||
const ctx = frag.getContext('2d')!;
|
||||
const ani = new Animation();
|
||||
ani.register('rate', 0);
|
||||
const ft = config.fragTiming ?? FRAG_TIMING;
|
||||
ani.absolute().time(time).mode(ft).apply('rate', 1);
|
||||
frag.width = maxX * 2;
|
||||
frag.height = maxY * 2;
|
||||
ctx.save();
|
||||
const dw = maxX - canvas.width / 2;
|
||||
const dh = maxY - canvas.height / 2;
|
||||
|
||||
const fragFn = () => {
|
||||
const rate = ani.value.rate;
|
||||
const opacity = 1 - rate;
|
||||
ctx.globalAlpha = opacity;
|
||||
ctx.clearRect(0, 0, frag.width, frag.height);
|
||||
toMove.forEach(v => {
|
||||
ctx.save();
|
||||
const nx = v.deltaX * rate;
|
||||
const ny = v.deltaY * rate;
|
||||
const rotate = v.endRad * rate;
|
||||
|
||||
ctx.translate(nx + v.x + dw, ny + v.y + dh);
|
||||
ctx.rotate(rotate);
|
||||
ctx.drawImage(
|
||||
v.canvas,
|
||||
nx - v.canvas.width / 2,
|
||||
ny - v.canvas.height / 2
|
||||
);
|
||||
ctx.restore();
|
||||
});
|
||||
};
|
||||
const onEnd = () => {};
|
||||
ani.ticker.add(fragFn);
|
||||
|
||||
return makeFragManager(frag, ani, time, onEnd);
|
||||
}
|
||||
|
||||
function makeFragManager(
|
||||
canvas: HTMLCanvasElement,
|
||||
ani: Animation,
|
||||
time: number,
|
||||
onEnd: () => void
|
||||
) {
|
||||
const promise = sleep(time + 50);
|
||||
|
||||
return {
|
||||
animation: ani,
|
||||
onEnd: promise.then(() => {
|
||||
ani.ticker.destroy();
|
||||
onEnd();
|
||||
}),
|
||||
canvas
|
||||
};
|
||||
}
|
||||
|
||||
export function withImage(
|
||||
image: CanvasImageSource,
|
||||
sx: number,
|
||||
sy: number,
|
||||
sw: number,
|
||||
sh: number
|
||||
): SplittedImage {
|
||||
const canvas = document.createElement('canvas');
|
||||
const ctx = canvas.getContext('2d')!;
|
||||
canvas.width = sw;
|
||||
canvas.height = sh;
|
||||
ctx.drawImage(image, sx, sy, sw, sh, 0, 0, sw, sh);
|
||||
return { canvas, x: sx, y: sy };
|
||||
}
|
||||
|
||||
/**
|
||||
* 切分画布
|
||||
* @param canvas 要被切分的画布
|
||||
* @param l 切分小块的边长
|
||||
*/
|
||||
function splitCanvas(canvas: HTMLCanvasElement, l: number): SplittedImage[] {
|
||||
if (canvas.width / l < 2 || canvas.height / l < 2) {
|
||||
console.warn('切分画布要求切分边长大于等于画布长宽的一半!');
|
||||
return [];
|
||||
}
|
||||
const w = canvas.width;
|
||||
const h = canvas.height;
|
||||
const numX = Math.floor(w / l);
|
||||
const numY = Math.floor(h / l);
|
||||
const rw = (w - numX * l) / 2;
|
||||
const rh = (h - numY * l) / 2;
|
||||
|
||||
const res: SplittedImage[] = [];
|
||||
|
||||
if (rw > 0) {
|
||||
if (rh > 0) {
|
||||
res.push(
|
||||
withImage(canvas, 0, 0, rw, rh),
|
||||
withImage(canvas, 0, canvas.height - rh, rw, rh),
|
||||
withImage(canvas, canvas.width - rw, 0, rw, rh),
|
||||
withImage(canvas, canvas.width - rw, canvas.height - rh, rw, rh)
|
||||
);
|
||||
}
|
||||
for (const x of [0, canvas.width - rw]) {
|
||||
for (let ny = 0; ny < numY; ny++) {
|
||||
res.push(withImage(canvas, x, rh + l * ny, rw, l));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rh > 0) {
|
||||
for (const y of [0, canvas.height - rh]) {
|
||||
for (let nx = 0; nx < numX; nx++) {
|
||||
res.push(withImage(canvas, rw + l * nx, y, l, rh));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let nx = 0; nx < numX; nx++) {
|
||||
for (let ny = 0; ny < numY; ny++) {
|
||||
res.push(withImage(canvas, rw + l * nx, rh + l * ny, l, l));
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { logger } from '@motajs/common';
|
||||
import {
|
||||
LayerGroupFloorBinder,
|
||||
ILayerGroupRenderExtends,
|
||||
LayerGroup
|
||||
} from '@motajs/render';
|
||||
|
||||
const filterMap: [FloorIds[], string][] = [];
|
||||
|
||||
function getCanvasFilterByFloorId(floorId: FloorIds = core.status.floorId) {
|
||||
return filterMap.find(v => v[0].includes(floorId))?.[1] ?? '';
|
||||
}
|
||||
|
||||
Mota.require('var', 'loading').once('coreInit', () => {
|
||||
filterMap.push(
|
||||
[['MT50', 'MT60', 'MT61'], 'contrast(120%)'], // 童心佬的滤镜(
|
||||
[
|
||||
core.floorIds.slice(61, 70).concat(core.floorIds.slice(72, 107)),
|
||||
'contrast(120%)'
|
||||
] // 童心佬的滤镜(
|
||||
);
|
||||
});
|
||||
|
||||
export class LayerGroupFilter implements ILayerGroupRenderExtends {
|
||||
id: string = 'filter';
|
||||
|
||||
group!: LayerGroup;
|
||||
binder!: LayerGroupFloorBinder;
|
||||
|
||||
setFilter(floorId: FloorIds) {
|
||||
const filter = getCanvasFilterByFloorId(floorId);
|
||||
this.group.setFilter(filter);
|
||||
// console.log(filter);
|
||||
}
|
||||
|
||||
private onFloorChange = (floor: FloorIds) => {
|
||||
this.setFilter(floor);
|
||||
};
|
||||
|
||||
private listen() {
|
||||
this.binder.on('floorChange', this.onFloorChange);
|
||||
}
|
||||
|
||||
awake(group: LayerGroup): void {
|
||||
this.group = group;
|
||||
const ex = group.getExtends('floor-binder');
|
||||
if (ex instanceof LayerGroupFloorBinder) {
|
||||
this.binder = ex;
|
||||
this.listen();
|
||||
} else {
|
||||
logger.error(1201);
|
||||
group.removeExtends('floor-damage');
|
||||
}
|
||||
}
|
||||
|
||||
onDestroy(group: LayerGroup): void {
|
||||
this.binder?.off('floorChange', this.onFloorChange);
|
||||
}
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
import { logger } from '@motajs/common';
|
||||
import { MotaOffscreenCanvas2D } from '@motajs/render';
|
||||
import { mainSetting } from '@motajs/legacy-ui';
|
||||
import {
|
||||
LayerGroupFloorBinder,
|
||||
ILayerGroupRenderExtends,
|
||||
LayerGroup,
|
||||
Sprite,
|
||||
Transform
|
||||
} from '@motajs/render';
|
||||
|
||||
const gameListener = Mota.require('var', 'gameListener');
|
||||
|
||||
export class LayerGroupHalo implements ILayerGroupRenderExtends {
|
||||
id: string = 'halo';
|
||||
|
||||
group!: LayerGroup;
|
||||
binder!: LayerGroupFloorBinder;
|
||||
halo!: Halo;
|
||||
|
||||
static sprites: Set<Halo> = new Set();
|
||||
|
||||
awake(group: LayerGroup): void {
|
||||
this.group = group;
|
||||
const ex = group.getExtends('floor-binder');
|
||||
if (ex instanceof LayerGroupFloorBinder) {
|
||||
this.binder = ex;
|
||||
this.halo = new Halo();
|
||||
this.halo.setHD(true);
|
||||
this.halo.size(group.width, group.height);
|
||||
this.halo.setZIndex(75);
|
||||
this.halo.binder = ex;
|
||||
group.appendChild(this.halo);
|
||||
LayerGroupHalo.sprites.add(this.halo);
|
||||
} else {
|
||||
logger.error(1401);
|
||||
group.removeExtends('halo');
|
||||
}
|
||||
}
|
||||
|
||||
onDestroy(group: LayerGroup): void {
|
||||
this.halo?.destroy();
|
||||
LayerGroupHalo.sprites.delete(this.halo);
|
||||
}
|
||||
}
|
||||
|
||||
const haloColor: Record<number, string[]> = {
|
||||
21: ['cyan'],
|
||||
25: ['purple'],
|
||||
26: ['blue'],
|
||||
27: ['red'],
|
||||
31: ['#3CFF49'],
|
||||
29: ['#51E9FF'],
|
||||
32: ['#fff966']
|
||||
};
|
||||
|
||||
class Halo extends Sprite {
|
||||
/** 单元格大小 */
|
||||
cellSize: number = 32;
|
||||
/** 当前楼层,用于获取有哪些光环 */
|
||||
binder!: LayerGroupFloorBinder;
|
||||
|
||||
constructor() {
|
||||
super('static', true);
|
||||
|
||||
this.setRenderFn((canvas, transform) => {
|
||||
this.drawHalo(canvas, transform);
|
||||
});
|
||||
}
|
||||
|
||||
drawHalo(canvas: MotaOffscreenCanvas2D, transform: Transform) {
|
||||
if (!mainSetting.getValue('screen.halo', true)) return;
|
||||
const floorId = this.binder.getFloor();
|
||||
if (!floorId) return;
|
||||
const col = core.status.maps[floorId].enemy;
|
||||
if (!col) return;
|
||||
const [dx, dy] = col.translation;
|
||||
const list = col.haloList.concat(
|
||||
Object.keys(flags[`melt_${floorId}`] ?? {}).map(v => {
|
||||
const [x, y] = v.split(',').map(v => parseInt(v));
|
||||
return {
|
||||
type: 'square',
|
||||
data: {
|
||||
x: x + dx,
|
||||
y: y + dy,
|
||||
d: 3
|
||||
},
|
||||
special: 25
|
||||
};
|
||||
})
|
||||
);
|
||||
const { ctx } = canvas;
|
||||
const cell = this.cellSize;
|
||||
ctx.lineWidth = 1;
|
||||
for (const halo of list) {
|
||||
if (halo.type === 'square') {
|
||||
const { x, y, d } = halo.data;
|
||||
let [color, border] = haloColor[halo.special];
|
||||
let alpha = 0.1;
|
||||
let borderAlpha = 0.6;
|
||||
const { mouseX, mouseY } = gameListener;
|
||||
if (mouseX === halo.from?.x && mouseY === halo.from?.y) {
|
||||
alpha = 0.3;
|
||||
borderAlpha = 0.8;
|
||||
color = '#ff0';
|
||||
border = '#ff0';
|
||||
}
|
||||
const r = Math.floor(d / 2);
|
||||
const left = x - r;
|
||||
const top = y - r;
|
||||
ctx.fillStyle = color;
|
||||
ctx.strokeStyle = border ?? color;
|
||||
ctx.globalAlpha = alpha;
|
||||
ctx.fillRect(left * cell, top * cell, d * cell, d * cell);
|
||||
ctx.globalAlpha = borderAlpha;
|
||||
ctx.strokeRect(left * cell, top * cell, d * cell, d * cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateHalo(block: Block) {
|
||||
if (block.event.cls === 'enemys' || block.event.cls === 'enemy48') {
|
||||
LayerGroupHalo.sprites.forEach(v => {
|
||||
const floor = v.binder.getFloor();
|
||||
if (floor === core.status.floorId) {
|
||||
v.update();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Mota.require('var', 'hook').on('enemyExtract', col => {
|
||||
LayerGroupHalo.sprites.forEach(v => {
|
||||
const floor = v.binder.getFloor();
|
||||
if (col.floorId === floor) {
|
||||
v.update();
|
||||
}
|
||||
});
|
||||
});
|
||||
gameListener.on('hoverBlock', updateHalo);
|
||||
gameListener.on('leaveBlock', updateHalo);
|
||||
@@ -1,269 +0,0 @@
|
||||
import { logger } from '@motajs/common';
|
||||
import { mainSetting } from '@motajs/legacy-ui';
|
||||
import {
|
||||
Damage,
|
||||
DamageRenderable,
|
||||
FloorDamageExtends,
|
||||
LayerGroupFloorBinder,
|
||||
ILayerGroupRenderExtends,
|
||||
LayerGroup
|
||||
} from '@motajs/render';
|
||||
|
||||
interface ItemDetailData {
|
||||
x: number;
|
||||
y: number;
|
||||
diff: Record<string | symbol, number | undefined>;
|
||||
}
|
||||
|
||||
interface ItemData {
|
||||
id: AllIdsOf<'items'>;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
const ItemState = Mota.require('module', 'State').ItemState;
|
||||
Mota.require('var', 'hook').on('setBlock', (x, y, floorId, block) => {
|
||||
FloorItemDetail.listened.forEach(v => {
|
||||
v.setBlock(block, x, y);
|
||||
});
|
||||
});
|
||||
|
||||
export class FloorItemDetail implements ILayerGroupRenderExtends {
|
||||
id: string = 'item-detail';
|
||||
|
||||
group!: LayerGroup;
|
||||
floorBinder!: LayerGroupFloorBinder;
|
||||
damage!: FloorDamageExtends;
|
||||
sprite!: Damage;
|
||||
|
||||
/** 每个分块中包含的物品信息 */
|
||||
blockData: Map<number, Map<number, ItemData>> = new Map();
|
||||
|
||||
/** 需要更新的分块 */
|
||||
private dirtyBlock: Set<number> = new Set();
|
||||
/** 道具详细信息 */
|
||||
private detailData: Map<number, Map<number, ItemDetailData>> = new Map();
|
||||
|
||||
static detailColor: Record<string, CanvasStyle> = {
|
||||
atk: '#FF7A7A',
|
||||
atkper: '#FF7A7A',
|
||||
def: '#00E6F1',
|
||||
defper: '#00E6F1',
|
||||
mdef: '#6EFF83',
|
||||
mdefper: '#6EFF83',
|
||||
hp: '#A4FF00',
|
||||
hpmax: '#F9FF00',
|
||||
hpmaxper: '#F9FF00',
|
||||
mana: '#c66',
|
||||
manaper: '#c66'
|
||||
};
|
||||
|
||||
static listened: Set<FloorItemDetail> = new Set();
|
||||
|
||||
private onBeforeDamageRender = (block: number) => {
|
||||
if (!mainSetting.getValue('screen.itemDetail')) return;
|
||||
if (this.dirtyBlock.has(block)) {
|
||||
this.sprite.block.clearCache(block, 1);
|
||||
}
|
||||
this.render(block);
|
||||
};
|
||||
|
||||
private onUpdateMapSize = (width: number, height: number) => {
|
||||
this.updateMapSize(width, height);
|
||||
};
|
||||
|
||||
private onUpdate = () => {
|
||||
this.updateItems();
|
||||
};
|
||||
|
||||
private onUpdateBlocks = (blocks: Set<number>) => {
|
||||
blocks.forEach(v => {
|
||||
this.dirtyBlock.add(v);
|
||||
});
|
||||
};
|
||||
|
||||
private listen() {
|
||||
this.sprite.on('dirtyUpdate', this.onBeforeDamageRender);
|
||||
this.sprite.on('setMapSize', this.onUpdateMapSize);
|
||||
this.sprite.on('updateBlocks', this.onUpdateBlocks);
|
||||
this.damage.on('update', this.onUpdate);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新地图大小
|
||||
*/
|
||||
updateMapSize(width: number, height: number) {
|
||||
this.blockData.clear();
|
||||
|
||||
// 预留blockData
|
||||
this.sprite.block.size(width, height);
|
||||
const data = this.sprite.block.blockData;
|
||||
const num = data.width * data.height;
|
||||
for (let i = 0; i <= num; i++) {
|
||||
this.blockData.set(i, new Map());
|
||||
this.detailData.set(i, new Map());
|
||||
this.dirtyBlock.add(i);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新全地图的物品,并进行分块存储
|
||||
*/
|
||||
updateItems() {
|
||||
const floor = this.floorBinder.getFloor();
|
||||
if (!floor) return;
|
||||
core.extractBlocks(floor);
|
||||
|
||||
core.status.maps[floor].blocks.forEach(v => {
|
||||
if (v.event.cls !== 'items' || v.disable) return;
|
||||
const id = v.event.id as AllIdsOf<'items'>;
|
||||
const item = core.material.items[id];
|
||||
if (item.cls === 'constants' || item.cls === 'tools') return;
|
||||
const x = v.x;
|
||||
const y = v.y;
|
||||
const block = this.sprite.block.getIndexByLoc(x, y);
|
||||
const index = x + y * this.sprite.mapWidth;
|
||||
const blockData = this.blockData.get(block);
|
||||
blockData?.set(index, { x, y, id });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置图块
|
||||
* @param block 图块数字
|
||||
* @param x 横坐标
|
||||
* @param y 纵坐标
|
||||
*/
|
||||
setBlock(block: AllNumbers, x: number, y: number) {
|
||||
const map = maps_90f36752_8815_4be8_b32b_d7fad1d0542e;
|
||||
const index = this.sprite.block.getIndexByLoc(x, y);
|
||||
const itemIndex = x + y * this.sprite.mapWidth;
|
||||
const blockData = this.blockData.get(index);
|
||||
this.dirtyBlock.add(index);
|
||||
if (block === 0) {
|
||||
blockData?.delete(itemIndex);
|
||||
return;
|
||||
}
|
||||
const cls = map[block].cls;
|
||||
if (cls !== 'items') {
|
||||
blockData?.delete(itemIndex);
|
||||
return;
|
||||
}
|
||||
const id = map[block].id;
|
||||
blockData?.set(itemIndex, { x, y, id });
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算指定分块中的物品信息
|
||||
* @param block 要计算的分块
|
||||
*/
|
||||
calAllItems(block: Set<number>) {
|
||||
if (!core.status.thisMap) return;
|
||||
if (this.dirtyBlock.size === 0 || block.size === 0) return;
|
||||
let diff: Record<string | symbol, number | undefined> = {};
|
||||
const before = core.status.hero;
|
||||
const hero = structuredClone(core.status.hero);
|
||||
const handler: ProxyHandler<any> = {
|
||||
set(target, key, v) {
|
||||
diff[key] = v - (target[key] || 0);
|
||||
if (!diff[key]) diff[key] = void 0;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
core.status.hero = new Proxy(hero, handler);
|
||||
|
||||
core.setFlag('__statistics__', true);
|
||||
block.forEach(v => {
|
||||
if (!this.dirtyBlock.has(v)) return;
|
||||
const data = this.blockData.get(v);
|
||||
const detail = this.detailData.get(v);
|
||||
detail?.clear();
|
||||
if (!data) return;
|
||||
data.forEach(v => {
|
||||
const { id, x, y } = v;
|
||||
const index = x + y * this.sprite.mapWidth;
|
||||
diff = {};
|
||||
|
||||
const item = core.material.items[id];
|
||||
if (item.cls === 'equips') {
|
||||
// 装备也显示
|
||||
const diff: Record<string, any> = {
|
||||
...(item.equip.value ?? {})
|
||||
};
|
||||
const per = item.equip.percentage ?? {};
|
||||
for (const name of Object.keys(per)) {
|
||||
const n = name as SelectKey<HeroStatus, number>;
|
||||
diff[name + 'per'] = per[n].toString() + '%';
|
||||
}
|
||||
detail?.set(index, { x, y, diff });
|
||||
return;
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
ItemState.item(id)?.itemEffectFn();
|
||||
detail?.set(index, { x, y, diff });
|
||||
});
|
||||
});
|
||||
core.status.hero = before;
|
||||
window.hero = before;
|
||||
window.flags = before.flags;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算并渲染指定格子里面的物品
|
||||
* @param block 需要渲染的格子
|
||||
*/
|
||||
render(block: number) {
|
||||
if (this.dirtyBlock.has(block)) {
|
||||
this.calAllItems(new Set([block]));
|
||||
}
|
||||
const data = this.detailData;
|
||||
this.dirtyBlock.delete(block);
|
||||
const info = data.get(block);
|
||||
if (!info) return;
|
||||
info.forEach(({ x, y, diff }) => {
|
||||
let n = 0;
|
||||
for (const [key, value] of Object.entries(diff)) {
|
||||
if (!value) continue;
|
||||
const color = FloorItemDetail.detailColor[key] ?? '#fff';
|
||||
const text = core.formatBigNumber(value, 4);
|
||||
const renderable: DamageRenderable = {
|
||||
x: x * this.sprite.cellSize + 2,
|
||||
y: y * this.sprite.cellSize + 31 - n * 10,
|
||||
text,
|
||||
color,
|
||||
align: 'left',
|
||||
baseline: 'alphabetic'
|
||||
};
|
||||
this.sprite.renderable.get(block)?.add(renderable);
|
||||
n++;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
awake(group: LayerGroup): void {
|
||||
this.group = group;
|
||||
|
||||
const binder = group.getExtends('floor-binder');
|
||||
const damage = group.getExtends('floor-damage');
|
||||
if (
|
||||
binder instanceof LayerGroupFloorBinder &&
|
||||
damage instanceof FloorDamageExtends
|
||||
) {
|
||||
this.floorBinder = binder;
|
||||
this.damage = damage;
|
||||
this.sprite = damage.sprite;
|
||||
this.listen();
|
||||
FloorItemDetail.listened.add(this);
|
||||
} else {
|
||||
logger.warn(1001);
|
||||
group.removeExtends('item-detail');
|
||||
}
|
||||
}
|
||||
|
||||
onDestroy(group: LayerGroup): void {
|
||||
this.sprite.off('beforeDamageRender', this.onBeforeDamageRender);
|
||||
this.sprite.off('setMapSize', this.onUpdateMapSize);
|
||||
FloorItemDetail.listened.delete(this);
|
||||
}
|
||||
}
|
||||
@@ -1,651 +0,0 @@
|
||||
import { logger } from '@motajs/common';
|
||||
import { UniformType, Shader, ShaderProgram, Transform } from '@motajs/render';
|
||||
|
||||
export const enum PointEffectType {
|
||||
/**
|
||||
* 无特效,在此之后的所有特效将会被截断,因此不要在空特效之后添加特效,也不要手动添加空特效
|
||||
*/
|
||||
None,
|
||||
/**
|
||||
* 反色特效,可与任意特效叠加\
|
||||
* 参数分别为:\
|
||||
* `data1: x, y, radius, decay` | 横坐标,纵坐标,半径,衰减开始半径\
|
||||
* `data2: ratio, _, _, _` | 反色强度,空,空,空
|
||||
*/
|
||||
CircleInvert,
|
||||
/**
|
||||
* 灰度特效,可与任意特效叠加\
|
||||
* 参数分别为:\
|
||||
* `data1: x, y, radius, decay` | 横坐标,纵坐标,半径,衰减开始半径\
|
||||
* `data2: ratio, _, _, _` | 黑白强度,空,空,空
|
||||
*/
|
||||
CircleGray,
|
||||
/**
|
||||
* 对比度特效,可与任意特效叠加\
|
||||
* 参数分别为:\
|
||||
* `data1: x, y, radius, decay` | 横坐标,纵坐标,半径,衰减开始半径\
|
||||
* `data2: ratio, _, _, _` | 对比度强度(0表示不变,-1表示灰色,1表示2倍对比度),空,空,空
|
||||
*/
|
||||
CircleContrast,
|
||||
/**
|
||||
* 饱和度特效,可与任意特效叠加\
|
||||
* 参数分别为:\
|
||||
* `data1: x, y, radius, decay` | 横坐标,纵坐标,半径,衰减开始半径\
|
||||
* `data2: ratio, _, _, _` | 对比度强度(0表示不变,-1表示灰色,1表示2倍饱和度),空,空,空
|
||||
*/
|
||||
CircleSaturate,
|
||||
/**
|
||||
* 饱和度特效,可与任意特效叠加\
|
||||
* 参数分别为:\
|
||||
* `data1: x, y, radius, decay` | 横坐标,纵坐标,半径,衰减开始半径\
|
||||
* `data2: angle, _, _, _` | 旋转角度(0表示旋转0度,1表示旋转360度),空,空,空
|
||||
*/
|
||||
CircleHue,
|
||||
/**
|
||||
* 圆形扭曲特效\
|
||||
* 参数分别为:\
|
||||
* `data1: x, y, maxRaius, waveRadius` | 中心横坐标,中心纵坐标,波纹最大传播距离,波纹环的半径\
|
||||
* `data2: amplitude, attenuation, linear, tangential` \
|
||||
*   * `amplitude`: 震动幅度(1表示幅度为1个屏幕,受摄像机缩放影响)\
|
||||
*   * `attenuation`: 衰减比例,即衰减速度\
|
||||
*   * `linear`: 开始线性衰减时间(为确保波纹最终归于平静,在衰减时,会首先平方反比衰减,
|
||||
* 然后到此值时转为线性衰减。此参数范围0-1,0.5表示从一半时间处开始线性衰减)\
|
||||
*   * `tangential`: 切向扭曲比例(1表示与振动幅度一致)\
|
||||
* `data3: startPhase, endPhase, _, _` | 起始位置相位(靠近波纹中心的位置),终止位置相位(远离波纹中心位置),空,空,
|
||||
* 其中相位一个周期为2 * PI,填 Math.PI * 2 则表示相位从一个周期处开始
|
||||
*/
|
||||
CircleWarp,
|
||||
/**
|
||||
* 圆形切向扭曲特效\
|
||||
* 参数分别为:\
|
||||
* `data1: x, y, minRadius, maxRadius` | 中心横坐标,中心纵坐标,扭曲环内圈半径,扭曲环外圈半径
|
||||
* (1表示扭曲了相位角的程度,例如Math.PI的相位,幅度为1,表示旋转整整一圈)\
|
||||
* `data2: startPhase, endPhase, _, _` 起始位置相位(靠近波纹中心的位置),终止位置相位(远离波纹中心的位置),空,空
|
||||
*/
|
||||
CircleWarpTangetial,
|
||||
/**
|
||||
* 圆形亮度特效,可与任何特效叠加\
|
||||
* 参数分别为:\
|
||||
* `data1: x, y, radius, decay` | 中心横坐标,中心纵坐标,半径,衰减开始半径\
|
||||
* `data2: ratio, _, _, _` | 亮度(0表示不变,1表示2倍亮度),空,空,空
|
||||
*/
|
||||
CircleBrightness
|
||||
}
|
||||
|
||||
type EffectData = [x0: number, x1: number, x2: number, x3: number];
|
||||
|
||||
const warpEffect = new Set<PointEffectType>();
|
||||
warpEffect
|
||||
.add(PointEffectType.CircleWarp)
|
||||
.add(PointEffectType.CircleWarpTangetial);
|
||||
|
||||
export class PointEffect {
|
||||
/** 着色器程序 */
|
||||
private program?: ShaderProgram;
|
||||
/** 着色器渲染元素 */
|
||||
private shader?: Shader;
|
||||
|
||||
/** 是否开始计时器 */
|
||||
private started: boolean = false;
|
||||
/** 计时器委托id */
|
||||
private delegation: number = -1;
|
||||
/** 特效id计数器,用于修改对应特效的数据 */
|
||||
private effectId: number = 0;
|
||||
/** 特效id到特效索引的映射 */
|
||||
private idIndexMap: Map<number, number> = new Map();
|
||||
/** 变换矩阵 */
|
||||
private transform?: Transform;
|
||||
|
||||
/** 特效最大数量 */
|
||||
private effectCount: number = 0;
|
||||
/** 特效数据 */
|
||||
private dataList: Float32Array = new Float32Array();
|
||||
/** 经过矩阵变换操作后的特效数据 */
|
||||
private transformed: Float32Array = new Float32Array();
|
||||
/** 当前的数据指针,也就是下一次添加特效应该添加至哪 */
|
||||
private dataPointer: number = 0;
|
||||
/** 是否需要更新数据 */
|
||||
private needUpdateData: boolean = false;
|
||||
/** 需要在之后添加的特效 */
|
||||
private toAdd: Set<number[]> = new Set();
|
||||
/** 每个特效的开始时间 */
|
||||
private startTime: Map<number, number> = new Map();
|
||||
/**
|
||||
* 为着色器创建程序
|
||||
* @param shader 着色器渲染元素
|
||||
* @param itemCount 最大效果数量
|
||||
*/
|
||||
create(shader: Shader, itemCount: number) {
|
||||
if (this.program || this.shader || this.started) return;
|
||||
const program = shader.createProgram(ShaderProgram);
|
||||
program.fs(generateFragment(itemCount));
|
||||
program.requestCompile();
|
||||
|
||||
// 声明变量
|
||||
program.defineUniform('u_count', shader.UNIFORM_1i);
|
||||
program.defineUniform('u_screen', shader.UNIFORM_2f);
|
||||
program.defineUniformBlock(
|
||||
'EffectInfo',
|
||||
itemCount * 16,
|
||||
shader.gl.DYNAMIC_DRAW,
|
||||
0
|
||||
);
|
||||
|
||||
this.program = program;
|
||||
this.shader = shader;
|
||||
this.effectCount = itemCount;
|
||||
this.dataList = new Float32Array(itemCount * 16);
|
||||
this.transformed = new Float32Array(itemCount * 16);
|
||||
this.transform = shader.transform;
|
||||
|
||||
return program;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在下一帧更新特效数据
|
||||
*/
|
||||
requestUpdate() {
|
||||
if (this.dataList[0] !== PointEffectType.None) {
|
||||
this.needUpdateData = true;
|
||||
}
|
||||
if (this.shader) this.shader.update(this.shader);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置本特效实例的变换矩阵,变换矩阵可以在设置特效位置时自动进行变换,配合摄像机视角
|
||||
* @param tranform 变换矩阵
|
||||
*/
|
||||
setTransform(tranform: Transform) {
|
||||
this.transform = tranform;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一个特效,如果特效还未开始,那么会在其开始时添加特效,注意特效数据必须填四位,不足者补0
|
||||
* @param type 特效类型
|
||||
* @param startTime 特效开始时间
|
||||
* @param time 特效持续时间
|
||||
* @param data1 第一组自定义数据,可选
|
||||
* @param data2 第二组自定义数据,可选
|
||||
* @param data3 第三组自定义数据,可选
|
||||
* @returns 这个特效的唯一id,可用于设置特效
|
||||
*/
|
||||
addEffect(
|
||||
type: PointEffectType,
|
||||
startTime: number,
|
||||
time: number,
|
||||
data1: EffectData = [0, 0, 0, 0],
|
||||
data2: EffectData = [0, 0, 0, 0],
|
||||
data3: EffectData = [0, 0, 0, 0]
|
||||
) {
|
||||
if (type === PointEffectType.None) return -1;
|
||||
const now = Date.now();
|
||||
// 如果已经结束,那么什么都不干
|
||||
if (now > time + startTime) return -1;
|
||||
// 填充 0 是因为 std140 布局中,每个数据都会占据 16 的倍数个字节
|
||||
// 不过第二项填充一个整数,是为了能够对每个特效进行标识,从而能够对某个特效进行修改
|
||||
const id = this.effectId++;
|
||||
// 第三项为特效的进度
|
||||
const data = [type, id, 0, time, ...data1, ...data2, ...data3];
|
||||
this.startTime.set(id, startTime);
|
||||
|
||||
if (now >= startTime) {
|
||||
this.addEffectToList(data);
|
||||
} else {
|
||||
// 如果还没开始,那么添加至预备队列
|
||||
this.toAdd.add(data);
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 立刻删除一个特效
|
||||
* @param id 要删除的特效的id
|
||||
*/
|
||||
deleteEffect(id: number) {
|
||||
this.removeEffect(this.findIndexById(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有特性
|
||||
*/
|
||||
clearEffect() {
|
||||
this.dataList.fill(0);
|
||||
this.dataPointer = 0;
|
||||
this.needUpdateData = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置一个特效的数据,注意特效数据必须填四位,不足者补0
|
||||
* @param id 特效id
|
||||
* @param data1 第一组自定义数据,可选
|
||||
* @param data2 第二组自定义数据,可选
|
||||
* @param data3 第三组自定义数据,可选
|
||||
*/
|
||||
setEffect(
|
||||
id: number,
|
||||
data1?: EffectData,
|
||||
data2?: EffectData,
|
||||
data3?: EffectData
|
||||
) {
|
||||
const index = this.findIndexById(id);
|
||||
if (index >= this.dataPointer || index === -1) return;
|
||||
const list = this.dataList;
|
||||
if (data1) {
|
||||
list.set(data1, index * 16 + 4);
|
||||
}
|
||||
if (data2) {
|
||||
list.set(data2, index * 16 + 8);
|
||||
}
|
||||
if (data3) {
|
||||
list.set(data3, index * 16 + 12);
|
||||
}
|
||||
this.needUpdateData = true;
|
||||
}
|
||||
|
||||
private findIndexById(id: number) {
|
||||
const map = this.idIndexMap.get(id);
|
||||
if (map !== void 0) return map;
|
||||
let index = -1;
|
||||
const list = this.dataList;
|
||||
for (let i = 0; i < this.effectCount; i++) {
|
||||
const realIndex = i * 16 + 1;
|
||||
if (list[realIndex] === id) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (index !== -1) {
|
||||
this.idIndexMap.set(id, index);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
private addEffectToList(data: number[]) {
|
||||
if (this.dataPointer >= this.effectCount) {
|
||||
logger.warn(1101);
|
||||
return;
|
||||
}
|
||||
const type = data[0];
|
||||
const list = this.dataList;
|
||||
if (warpEffect.has(type)) {
|
||||
list.copyWithin(16, 0);
|
||||
list.set(data, 0);
|
||||
this.dataPointer++;
|
||||
this.idIndexMap.clear();
|
||||
} else {
|
||||
const id = data[1];
|
||||
list.set(data, this.dataPointer * 16);
|
||||
this.idIndexMap.set(id, this.dataPointer);
|
||||
this.dataPointer++;
|
||||
}
|
||||
|
||||
this.needUpdateData = true;
|
||||
}
|
||||
|
||||
private removeEffect(index: number) {
|
||||
if (index >= this.effectCount) return;
|
||||
if (this.dataPointer === 0) return;
|
||||
const list = this.dataList;
|
||||
const id = list[index * 16 + 1];
|
||||
this.startTime.delete(id);
|
||||
list.copyWithin(index * 16, index * 16 + 16);
|
||||
list.fill(0, -16, -1);
|
||||
this.dataPointer--;
|
||||
this.needUpdateData = true;
|
||||
this.idIndexMap.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用这个特效作为着色器程序
|
||||
*/
|
||||
use() {
|
||||
if (!this.shader || !this.program) return;
|
||||
this.shader.useProgram(this.program);
|
||||
const uCount =
|
||||
this.program.getUniform<UniformType.Uniform1f>('u_count');
|
||||
uCount?.set(this.effectCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始计时器
|
||||
*/
|
||||
start() {
|
||||
if (!this.shader || !this.program) return;
|
||||
this.started = true;
|
||||
const block = this.program.getUniformBlock('EffectInfo')!;
|
||||
const screen =
|
||||
this.program.getUniform<UniformType.Uniform2f>('u_screen');
|
||||
const { width, height } = this.shader;
|
||||
const scale = core.domStyle.scale * devicePixelRatio;
|
||||
screen?.set(width * scale, height * scale);
|
||||
|
||||
// 不知道性能怎么样,只能试试看了
|
||||
this.delegation = this.shader.delegateTicker(() => {
|
||||
if (!this.started) {
|
||||
this.shader?.removeTicker(this.delegation);
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
const toDelete = new Set<number[]>();
|
||||
this.toAdd.forEach(v => {
|
||||
const id = v[1];
|
||||
const startTime = this.startTime.get(id);
|
||||
if (!startTime) return;
|
||||
const time = v[3];
|
||||
if (now > startTime + time) {
|
||||
toDelete.add(v);
|
||||
} else if (now >= startTime) {
|
||||
this.addEffectToList(v);
|
||||
toDelete.add(v);
|
||||
}
|
||||
});
|
||||
toDelete.forEach(v => this.toAdd.delete(v));
|
||||
|
||||
const toRemove: number[] = [];
|
||||
const list = this.dataList;
|
||||
|
||||
// 倒序以保证删除时不会影响到其他删除
|
||||
for (let i = this.effectCount - 1; i >= 0; i--) {
|
||||
const type = list[i * 16];
|
||||
if (type === PointEffectType.None) continue;
|
||||
const id = list[i * 16 + 1];
|
||||
const start = this.startTime.get(id);
|
||||
if (!start) {
|
||||
toRemove.push(i);
|
||||
continue;
|
||||
}
|
||||
const time = list[i * 16 + 3];
|
||||
const progress = (now - start) / time;
|
||||
if (progress > 1) toRemove.push(i);
|
||||
list[i * 16 + 2] = progress;
|
||||
}
|
||||
toRemove.forEach(v => {
|
||||
this.removeEffect(v);
|
||||
});
|
||||
|
||||
if (this.needUpdateData) {
|
||||
const list = this.dataList;
|
||||
const transformed = this.transformed;
|
||||
transformed.set(list);
|
||||
this.transformData();
|
||||
block.set(transformed);
|
||||
this.needUpdateData = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 结束计时器
|
||||
*/
|
||||
end() {
|
||||
if (!this.started || !this.shader || !this.program) return;
|
||||
this.shader.removeTicker(this.delegation);
|
||||
this.started = false;
|
||||
this.dataList.fill(0);
|
||||
this.dataPointer = 0;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.end();
|
||||
if (this.shader && this.program) {
|
||||
this.shader.deleteProgram(this.program);
|
||||
}
|
||||
}
|
||||
|
||||
private transformData() {
|
||||
const transform = this.transform;
|
||||
if (!transform) return;
|
||||
const count = this.effectCount;
|
||||
const list = this.dataList;
|
||||
const transformed = this.transformed;
|
||||
let ratio = core.domStyle.scale;
|
||||
if (this.shader?.highResolution) ratio *= devicePixelRatio;
|
||||
const scale = transform.scaleX * ratio;
|
||||
const scaleTransform = new Transform();
|
||||
scaleTransform.scale(ratio, ratio);
|
||||
const scaled = scaleTransform.multiply(transform);
|
||||
const fixedHeight = core._PY_ * ratio;
|
||||
|
||||
const transformXY = (index: number) => {
|
||||
const x = list[index + 4];
|
||||
const y = list[index + 5];
|
||||
const [tx, ty] = Transform.transformed(scaled, x, y);
|
||||
transformed[index + 4] = tx;
|
||||
transformed[index + 5] = fixedHeight - ty;
|
||||
};
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const index = i * 16;
|
||||
const type = list[index];
|
||||
|
||||
switch (type) {
|
||||
case PointEffectType.CircleGray:
|
||||
case PointEffectType.CircleInvert:
|
||||
case PointEffectType.CircleContrast:
|
||||
case PointEffectType.CircleSaturate:
|
||||
case PointEffectType.CircleHue:
|
||||
case PointEffectType.CircleBrightness:
|
||||
case PointEffectType.CircleWarpTangetial: {
|
||||
transformXY(index);
|
||||
transformed[index + 6] *= scale;
|
||||
transformed[index + 7] *= scale;
|
||||
break;
|
||||
}
|
||||
case PointEffectType.CircleWarp: {
|
||||
transformXY(index);
|
||||
transformed[index + 6] *= scale;
|
||||
transformed[index + 7] *= scale;
|
||||
transformed[index + 8] *= scale;
|
||||
break;
|
||||
}
|
||||
case PointEffectType.None: {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function generateFragment(itemCount: number) {
|
||||
return /* glsl */ `
|
||||
uniform int u_count;
|
||||
uniform vec2 u_screen; // 画布长宽
|
||||
|
||||
out vec4 outColor;
|
||||
|
||||
struct Effect {
|
||||
vec2 type; // 效果类型
|
||||
vec2 time; // 开始时间,持续时长
|
||||
vec4 info1; // 第一组信息,表示自定义参数
|
||||
vec4 info2; // 第二组信息,表示自定义参数
|
||||
vec4 info3; // 第三组信息,表示自定义参数
|
||||
};
|
||||
|
||||
layout (std140) uniform EffectInfo {
|
||||
Effect effects[${itemCount}];
|
||||
};
|
||||
|
||||
// Helper function: RGB to HSL conversion
|
||||
vec3 rgb2hsl(vec3 color) {
|
||||
float maxC = max(max(color.r, color.g), color.b);
|
||||
float minC = min(min(color.r, color.g), color.b);
|
||||
float delta = maxC - minC;
|
||||
|
||||
float h = 0.0;
|
||||
float s = 0.0;
|
||||
float l = (maxC + minC) * 0.5;
|
||||
|
||||
if (delta != 0.0) {
|
||||
s = (l < 0.5) ? delta / (maxC + minC) : delta / (2.0 - maxC - minC);
|
||||
|
||||
if (maxC == color.r) {
|
||||
h = (color.g - color.b) / delta + (color.g < color.b ? 6.0 : 0.0);
|
||||
} else if (maxC == color.g) {
|
||||
h = (color.b - color.r) / delta + 2.0;
|
||||
} else {
|
||||
h = (color.r - color.g) / delta + 4.0;
|
||||
}
|
||||
h /= 6.0;
|
||||
}
|
||||
|
||||
return vec3(h, s, l);
|
||||
}
|
||||
|
||||
// Helper function: Hue to RGB conversion
|
||||
float hue2rgb(float p, float q, float t) {
|
||||
if (t < 0.0) t += 1.0;
|
||||
if (t > 1.0) t -= 1.0;
|
||||
if (t < 1.0 / 6.0) return p + (q - p) * 6.0 * t;
|
||||
if (t < 1.0 / 2.0) return q;
|
||||
if (t < 2.0 / 3.0) return p + (q - p) * (2.0 / 3.0 - t) * 6.0;
|
||||
return p;
|
||||
}
|
||||
|
||||
// Helper function: HSL to RGB conversion
|
||||
vec3 hsl2rgb(vec3 hsl) {
|
||||
float h = hsl.x;
|
||||
float s = hsl.y;
|
||||
float l = hsl.z;
|
||||
|
||||
float r, g, b;
|
||||
|
||||
if (s == 0.0) {
|
||||
r = g = b = l; // Achromatic (gray)
|
||||
} else {
|
||||
float q = (l < 0.5) ? (l * (1.0 + s)) : (l + s - l * s);
|
||||
float p = 2.0 * l - q;
|
||||
|
||||
r = hue2rgb(p, q, h + 1.0 / 3.0);
|
||||
g = hue2rgb(p, q, h);
|
||||
b = hue2rgb(p, q, h - 1.0 / 3.0);
|
||||
}
|
||||
|
||||
return vec3(r, g, b);
|
||||
}
|
||||
|
||||
// x: 横坐标 y: 纵坐标 z: 半径 w: 衰减开始半径
|
||||
// 计算圆形效果的衰减程度
|
||||
float calCircleDecay(vec4 data) {
|
||||
float dis = distance(data.xy, gl_FragCoord.xy);
|
||||
if (dis <= data.w) return 1.0;
|
||||
if (dis >= data.z) return 0.0;
|
||||
if (data.z <= data.w) return 1.0;
|
||||
return 1.0 - (dis - data.w) / (data.z - data.w);
|
||||
}
|
||||
|
||||
// data1: x, y, maxRadius, waveRadius
|
||||
// data2: amplitude, attenuation, linear, _
|
||||
// 计算波纹扭曲的衰减程度,从 x = 1 的平方反比函数开始,衰减至 x = 1 + attenuation,然后线性衰减
|
||||
float calWarpDecay(float progress, vec4 data1, vec4 data2) {
|
||||
if (progress >= data2.z) {
|
||||
float end = 1.0 / pow(1.0 + data2.y, 2.0);
|
||||
return end - end * (progress - data2.z) / (1.0 - data2.z);
|
||||
} else {
|
||||
return 1.0 / pow(1.0 + (progress / data2.z) * data2.y, 2.0);
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec2 coord = v_texCoord;
|
||||
vec4 color = texture(u_sampler, v_texCoord);
|
||||
for (int i = 0; i < u_count; i++) {
|
||||
Effect effect = effects[i];
|
||||
int effectType = int(effect.type.x);
|
||||
vec2 timeInfo = effect.time;
|
||||
vec4 data1 = effect.info1;
|
||||
vec4 data2 = effect.info2;
|
||||
vec4 data3 = effect.info3;
|
||||
if (effectType == ${PointEffectType.None}) break;
|
||||
float progress = timeInfo.x;
|
||||
|
||||
// 下面开始实施对应的着色器特效
|
||||
|
||||
// 反色,data1: x y radius decay;data2: ratio _ _ _
|
||||
if (effectType == ${PointEffectType.CircleInvert}) {
|
||||
float ratio = data2.x * calCircleDecay(data1);
|
||||
if (ratio > 0.0) {
|
||||
vec3 delta = (1.0 - 2.0 * color.rgb) * ratio;
|
||||
color.rgb = clamp(color.rgb + delta, 0.0, 1.0);
|
||||
}
|
||||
}
|
||||
// 灰度,data1: x y radius decay;data2: ratio _ _ _
|
||||
else if (effectType == ${PointEffectType.CircleGray}) {
|
||||
float ratio = data2.x * calCircleDecay(data1);
|
||||
if (ratio > 0.0) {
|
||||
float gray = dot(color.rgb, vec3(0.2126, 0.7125, 0.0722));
|
||||
vec3 grayed = color.rgb - gray;
|
||||
color = vec4(color.rgb - grayed * ratio, 1.0);
|
||||
}
|
||||
}
|
||||
// 亮度,data1: x y radius decay;data2: ratio _ _ _
|
||||
else if (effectType == ${PointEffectType.CircleBrightness}) {
|
||||
float ratio = data2.x * calCircleDecay(data1) + 1.0;
|
||||
if (ratio > 0.0) {
|
||||
color.rgb *= ratio;
|
||||
}
|
||||
}
|
||||
// 对比度,data1: x y radius decay;data2: ratio _ _ _
|
||||
else if (effectType == ${PointEffectType.CircleContrast}) {
|
||||
float ratio = data2.x * calCircleDecay(data1) + 1.0;
|
||||
if (ratio > 0.0) {
|
||||
color.rgb = mix(vec3(0.5), color.rgb, ratio);
|
||||
}
|
||||
}
|
||||
// 饱和度,data1: x y radius decay;data2: ratio _ _ _
|
||||
else if (effectType == ${PointEffectType.CircleSaturate}) {
|
||||
float ratio = data2.x * calCircleDecay(data1) + 1.0;
|
||||
if (ratio > 0.0) {
|
||||
float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));
|
||||
color.rgb = mix(vec3(gray), color.rgb, ratio);
|
||||
}
|
||||
}
|
||||
// 色相旋转,data1: x y radius decay;data2: angle _ _ _
|
||||
else if (effectType == ${PointEffectType.CircleHue}) {
|
||||
float ratio = data2.x * calCircleDecay(data1);
|
||||
if (ratio > 0.0) {
|
||||
vec3 hsl = rgb2hsl(color.rgb);
|
||||
hsl.x = mod(hsl.x + data2.x * ratio, 1.0);
|
||||
color.rgb = hsl2rgb(hsl);
|
||||
}
|
||||
}
|
||||
// 扭曲,data1: x, y, maxRadius, waveRadius; data2: amplitude, attenuation, linear, _
|
||||
// data3: startPhase, endPhase, _, _
|
||||
else if (effectType == ${PointEffectType.CircleWarp}) {
|
||||
float dis = distance(data1.xy, gl_FragCoord.xy);
|
||||
// 当前半径
|
||||
float radius = progress * data1.z;
|
||||
if (dis > radius + data1.w || dis < radius - data1.w) continue;
|
||||
float ratio = data2.x * calWarpDecay(progress, data1, data2);
|
||||
float halfRadius = data1.w / 2.0;
|
||||
if (ratio > 0.0 && abs(dis - radius) <= halfRadius) {
|
||||
// 计算当前相位
|
||||
float x = ((dis - radius) / data1.w + 0.5) * (data3.y - data3.x) + data3.x;
|
||||
float wave = sin(x) * ratio;
|
||||
float xRatio = (gl_FragCoord.x - data1.x) / dis;
|
||||
float yRatio = (gl_FragCoord.y - data1.y) / dis;
|
||||
coord.x += wave * xRatio + wave * yRatio * data2.w;
|
||||
coord.y += wave * yRatio + wave * xRatio * data2.w;
|
||||
color = texture(u_sampler, coord);
|
||||
}
|
||||
}
|
||||
// 切向扭曲,data1: x, y, minRadius, maxRadius; data2: startPhase, endPhase, _, _
|
||||
else if (effectType == ${PointEffectType.CircleWarpTangetial}) {
|
||||
float dis = distance(data1.xy, gl_FragCoord.xy);
|
||||
float ratio = (dis - data1.z) / (data1.w - data1.z);
|
||||
if (ratio <= 1.0 && ratio > 0.0) {
|
||||
float phase = ratio * (data2.y - data2.x) + data2.x;
|
||||
float waveSin = sin(phase);
|
||||
float waveCos = cos(phase);
|
||||
// 相对坐标
|
||||
vec2 relCoord = gl_FragCoord.xy - data1.xy;
|
||||
coord.x = (data1.x + relCoord.x * waveCos - relCoord.y * waveSin) / u_screen.x;
|
||||
coord.y = 1.0 - (data1.y + relCoord.x * waveSin + relCoord.y * waveCos) / u_screen.y;
|
||||
color = texture(u_sampler, coord);
|
||||
}
|
||||
}
|
||||
}
|
||||
outColor = color;
|
||||
}
|
||||
`;
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
import {
|
||||
wrapInstancedComponent,
|
||||
RenderItem,
|
||||
RenderItemPosition,
|
||||
Transform,
|
||||
MotaOffscreenCanvas2D
|
||||
} from '@motajs/render';
|
||||
|
||||
import { TimingFn } from 'mutate-animate';
|
||||
|
||||
interface PopData {
|
||||
cx: number;
|
||||
cy: number;
|
||||
path: TimingFn<2>;
|
||||
text: string;
|
||||
time: number;
|
||||
start: number;
|
||||
color: CanvasStyle;
|
||||
}
|
||||
|
||||
function parabola(input: number): [number, number] {
|
||||
const x = input * 100;
|
||||
return [x, x ** 2 / 20 - 3 * x];
|
||||
}
|
||||
|
||||
export class Pop extends RenderItem {
|
||||
private popList: Set<PopData> = new Set();
|
||||
|
||||
private delegation: number = 0;
|
||||
|
||||
constructor(type: RenderItemPosition) {
|
||||
super(type, false);
|
||||
this.delegation = this.delegateTicker(() => {
|
||||
if (this.popList.size > 0) this.update();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一个弹出文字
|
||||
* @param text 要显示的文字
|
||||
* @param time 持续时长
|
||||
* @param cx 中心点,也就是从哪弹出的
|
||||
* @param cy 中心点,也就是从哪弹出的
|
||||
* @param path 自定义路径,不填表示默认的抛物线路径
|
||||
*/
|
||||
addPop(
|
||||
text: string,
|
||||
time: number,
|
||||
cx: number,
|
||||
cy: number,
|
||||
color: CanvasStyle,
|
||||
path?: TimingFn<2>
|
||||
) {
|
||||
this.popList.add({
|
||||
text,
|
||||
time,
|
||||
cx,
|
||||
cy,
|
||||
color,
|
||||
path: path ?? parabola,
|
||||
start: Date.now()
|
||||
});
|
||||
this.update();
|
||||
}
|
||||
|
||||
protected render(
|
||||
canvas: MotaOffscreenCanvas2D,
|
||||
_transform: Transform
|
||||
): void {
|
||||
const ctx = canvas.ctx;
|
||||
const toDelete = new Set<PopData>();
|
||||
const now = Date.now();
|
||||
ctx.strokeStyle = '#000';
|
||||
ctx.font = '22px Verdana';
|
||||
ctx.lineWidth = 3;
|
||||
this.popList.forEach(v => {
|
||||
const { cx, cy, path, text, color, time, start } = v;
|
||||
const dt = now - start;
|
||||
const progress = dt / time;
|
||||
if (progress >= 1) {
|
||||
toDelete.add(v);
|
||||
return;
|
||||
}
|
||||
const [x, y] = path(progress);
|
||||
const dx = cx + x;
|
||||
const dy = cy + y;
|
||||
ctx.globalAlpha = Math.min(1, 2 - progress * 2);
|
||||
ctx.fillStyle = color;
|
||||
ctx.strokeText(text, dx, dy);
|
||||
ctx.fillText(text, dx, dy);
|
||||
});
|
||||
toDelete.forEach(v => {
|
||||
this.popList.delete(v);
|
||||
});
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
super.destroy();
|
||||
this.removeTicker(this.delegation);
|
||||
}
|
||||
}
|
||||
|
||||
export const PopText = wrapInstancedComponent(() => new Pop('static'));
|
||||
@@ -1,296 +0,0 @@
|
||||
import { logger } from '@motajs/common';
|
||||
import { MotaOffscreenCanvas2D } from '@motajs/render';
|
||||
import { mainSetting, MotaSettingItem } from '@motajs/legacy-ui';
|
||||
import {
|
||||
LayerGroupFloorBinder,
|
||||
ILayerGroupRenderExtends,
|
||||
LayerGroup,
|
||||
Sprite
|
||||
} from '@motajs/render';
|
||||
import type { BluePalace } from '@/game/mechanism/misc';
|
||||
|
||||
/** 最大粒子数 */
|
||||
const MAX_PARTICLES = 10;
|
||||
/** 粒子持续时长 */
|
||||
const PARTICLE_LAST = 2000;
|
||||
/** 粒子产生间隔 */
|
||||
const PARTICLE_INTERVAL = PARTICLE_LAST / MAX_PARTICLES;
|
||||
|
||||
export class LayerGroupPortal implements ILayerGroupRenderExtends {
|
||||
id: string = 'portal';
|
||||
|
||||
group!: LayerGroup;
|
||||
binder!: LayerGroupFloorBinder;
|
||||
portal!: Portal;
|
||||
|
||||
private onFloorChange = (floor: FloorIds) => {
|
||||
const data = Mota.require('module', 'Mechanism').BluePalace.portals;
|
||||
this.portal.cellSize = this.group.cellSize;
|
||||
this.portal.setData(data[floor] ?? []);
|
||||
};
|
||||
|
||||
private listen() {
|
||||
this.binder.on('floorChange', this.onFloorChange);
|
||||
}
|
||||
|
||||
awake(group: LayerGroup): void {
|
||||
this.group = group;
|
||||
const ex = group.getExtends('floor-binder');
|
||||
if (ex instanceof LayerGroupFloorBinder) {
|
||||
this.binder = ex;
|
||||
this.portal = new Portal();
|
||||
this.portal.setHD(true);
|
||||
this.portal.size(group.width, group.height);
|
||||
group.appendChild(this.portal);
|
||||
this.listen();
|
||||
} else {
|
||||
logger.error(1301);
|
||||
group.removeExtends('portal');
|
||||
}
|
||||
}
|
||||
|
||||
onDestroy(group: LayerGroup): void {
|
||||
this.binder.off('floorChange', this.onFloorChange);
|
||||
}
|
||||
}
|
||||
|
||||
interface DrawingPortal {
|
||||
color: string;
|
||||
x: number;
|
||||
y: number;
|
||||
particles: Set<PortalParticle>;
|
||||
/** v表示竖向,h表示横向 */
|
||||
type: 'v' | 'h';
|
||||
/** 上一次新增粒子的时间 */
|
||||
lastParticle: number;
|
||||
}
|
||||
|
||||
interface PortalParticle {
|
||||
fx: number;
|
||||
fy: number;
|
||||
totalTime: number;
|
||||
time: number;
|
||||
tx: number;
|
||||
ty: number;
|
||||
r: number;
|
||||
}
|
||||
|
||||
export class Portal extends Sprite {
|
||||
static colors: string[] = ['#0f0', '#ff0', '#0ff', '#fff', '#f0f'];
|
||||
|
||||
cellSize: number = 32;
|
||||
/** 当前的渲染数据 */
|
||||
private renderData: BluePalace.Portal[] = [];
|
||||
/** 渲染内容 */
|
||||
private renderable: Set<DrawingPortal> = new Set();
|
||||
|
||||
/** 粒子开关设置 */
|
||||
private particleSetting: MotaSettingItem;
|
||||
/** 上一帧时刻 */
|
||||
private lastTime: number = 0;
|
||||
|
||||
private delegation: number;
|
||||
|
||||
constructor() {
|
||||
super('static', false, true);
|
||||
|
||||
this.particleSetting = mainSetting.getSetting('fx.portalParticle')!;
|
||||
|
||||
this.delegation = this.delegateTicker(() => {
|
||||
if (this.particleSetting.value && this.renderable.size > 0) {
|
||||
this.update(this);
|
||||
}
|
||||
});
|
||||
|
||||
this.setZIndex(35);
|
||||
|
||||
this.setRenderFn((canvas, transform) => {
|
||||
this.renderPortal(canvas);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置渲染内容
|
||||
*/
|
||||
setData(data: BluePalace.Portal[]) {
|
||||
this.renderData = data;
|
||||
this.generateRenderable();
|
||||
this.update(this);
|
||||
}
|
||||
|
||||
private generateRenderable() {
|
||||
this.renderable.clear();
|
||||
if (this.renderData.length === 0) return;
|
||||
const colorLength = Portal.colors.length;
|
||||
const cell = this.cellSize;
|
||||
this.renderData.forEach((v, i) => {
|
||||
const c = Portal.colors[i % colorLength];
|
||||
const { fx, fy, tx, ty, dir, toDir } = v;
|
||||
|
||||
let x1 = fx * cell;
|
||||
let y1 = fy * cell;
|
||||
let x2 = tx * cell;
|
||||
let y2 = ty * cell;
|
||||
|
||||
if (dir === 'down') y1 += cell;
|
||||
else if (dir === 'right') x1 += cell;
|
||||
|
||||
if (toDir === 'down') y2 += cell;
|
||||
else if (toDir === 'right') x2 += cell;
|
||||
|
||||
this.renderable.add({
|
||||
x: x1,
|
||||
y: y1,
|
||||
type: dir === 'left' || dir === 'right' ? 'v' : 'h',
|
||||
color: c,
|
||||
particles: new Set(),
|
||||
lastParticle: Date.now()
|
||||
});
|
||||
|
||||
this.renderable.add({
|
||||
x: x2,
|
||||
y: y2,
|
||||
type: toDir === 'left' || toDir === 'right' ? 'v' : 'h',
|
||||
color: c,
|
||||
particles: new Set(),
|
||||
lastParticle: Date.now()
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private renderPortal(canvas: MotaOffscreenCanvas2D) {
|
||||
if (this.renderable.size === 0) return;
|
||||
const { ctx } = canvas;
|
||||
|
||||
const p = this.particleSetting.value;
|
||||
ctx.lineCap = 'round';
|
||||
ctx.lineWidth = 3;
|
||||
ctx.shadowOffsetX = 0;
|
||||
ctx.shadowOffsetY = 0;
|
||||
if (p) {
|
||||
ctx.shadowBlur = 8;
|
||||
} else {
|
||||
ctx.shadowBlur = 0;
|
||||
}
|
||||
|
||||
const time = Date.now();
|
||||
const dt = time - this.lastTime;
|
||||
this.lastTime = time;
|
||||
this.renderable.forEach(v => {
|
||||
const { color, x, y, type, lastParticle, particles } = v;
|
||||
|
||||
ctx.strokeStyle = color;
|
||||
ctx.fillStyle = color;
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.shadowColor = color;
|
||||
if (type === 'v') {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, y - 14);
|
||||
ctx.lineTo(x, y + 30);
|
||||
ctx.stroke();
|
||||
} else {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + 2, y);
|
||||
ctx.lineTo(x + 30, y);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
if (!p) return;
|
||||
|
||||
const needDelete = new Set<PortalParticle>();
|
||||
particles.forEach(v => {
|
||||
const { fx, fy, tx, ty, time: t, totalTime, r } = v;
|
||||
const progress = t / totalTime;
|
||||
const nx = (tx - fx) * progress + fx;
|
||||
const ny = (ty - fy) * progress + fy;
|
||||
v.time += dt;
|
||||
|
||||
if (progress > 1) {
|
||||
needDelete.add(v);
|
||||
return;
|
||||
} else if (progress > 0.75) {
|
||||
ctx.globalAlpha = (1 - progress) * 4;
|
||||
} else if (progress < 0.25) {
|
||||
ctx.globalAlpha = progress * 4;
|
||||
} else {
|
||||
ctx.globalAlpha = 1;
|
||||
}
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.arc(nx, ny, r, 0, Math.PI * 2);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
});
|
||||
needDelete.forEach(v => {
|
||||
particles.delete(v);
|
||||
});
|
||||
if (
|
||||
time - lastParticle >= PARTICLE_INTERVAL &&
|
||||
particles.size < MAX_PARTICLES
|
||||
) {
|
||||
// 添加新粒子
|
||||
const direction = Math.random();
|
||||
const k = Math.random() / 2 - 0.3;
|
||||
const verticle = Math.floor(Math.random() * 8 + 8);
|
||||
const r = Math.random() * 2;
|
||||
v.lastParticle = time;
|
||||
if (direction > 0.5) {
|
||||
// 左边 | 上边
|
||||
if (type === 'h') {
|
||||
const fx = Math.floor(Math.random() * 24 + x + 4);
|
||||
particles.add({
|
||||
fx: fx,
|
||||
fy: y - 1,
|
||||
tx: verticle * k + fx + 4,
|
||||
ty: -verticle + y - 1,
|
||||
r: r,
|
||||
time: 0,
|
||||
totalTime: PARTICLE_LAST
|
||||
});
|
||||
} else {
|
||||
const fy = Math.floor(Math.random() * 44 + y - 14);
|
||||
particles.add({
|
||||
fy: fy,
|
||||
fx: x - 1,
|
||||
ty: verticle * k + fy + 4,
|
||||
tx: -verticle + x - 1,
|
||||
r: r,
|
||||
time: 0,
|
||||
totalTime: PARTICLE_LAST
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// 右边 | 下边
|
||||
if (type === 'h') {
|
||||
const fx = Math.floor(Math.random() * 24 + x + 4);
|
||||
particles.add({
|
||||
fx: fx,
|
||||
fy: y + 1,
|
||||
tx: verticle * k + fx + 4,
|
||||
ty: verticle + y - 1,
|
||||
r: r,
|
||||
time: 0,
|
||||
totalTime: PARTICLE_LAST
|
||||
});
|
||||
} else {
|
||||
const fy = Math.floor(Math.random() * 44 + y - 14);
|
||||
particles.add({
|
||||
fy: fy,
|
||||
fx: x + 1,
|
||||
ty: verticle * k + fy + 4,
|
||||
tx: verticle + x + 1,
|
||||
r: r,
|
||||
time: 0,
|
||||
totalTime: PARTICLE_LAST
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
super.destroy();
|
||||
this.removeTicker(this.delegation);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
export function chaseInit1() {
|
||||
const ids: FloorIds[] = ['MT13', 'MT14', 'MT15'];
|
||||
const toRemove: [number, number, FloorIds][] = [];
|
||||
ids.forEach(v => {
|
||||
core.status.maps[v].cannotMoveDirectly = true;
|
||||
core.extractBlocks(v);
|
||||
core.status.maps[v].blocks.forEach(vv => {
|
||||
if (
|
||||
['animates', 'items'].includes(vv.event.cls) &&
|
||||
!vv.event.id.endsWith('Portal')
|
||||
) {
|
||||
toRemove.push([vv.x, vv.y, v]);
|
||||
}
|
||||
});
|
||||
});
|
||||
toRemove.forEach(v => {
|
||||
core.removeBlock(...v);
|
||||
});
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
///<reference path="../../../../src/types/core.d.ts" />
|
||||
export {};
|
||||
|
||||
/* @__PURE__ */ (function () {
|
||||
if (main.mode !== 'play' || main.replayChecking) return;
|
||||
|
||||
/**
|
||||
* 热重载css
|
||||
* @param {string} data
|
||||
*/
|
||||
function reloadCss(data) {
|
||||
const css = document.getElementById('mota-css');
|
||||
css.remove();
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.type = 'text/css';
|
||||
link.href = data;
|
||||
link.id = 'mota-css';
|
||||
document.head.appendChild(link);
|
||||
console.log(`Css hot reload: ${data}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 热重载楼层
|
||||
* @param {string} data
|
||||
*/
|
||||
async function reloadFloor(data) {
|
||||
// 如果被砍层了直接忽略
|
||||
if (
|
||||
core.status.maps &&
|
||||
(core.status.maps[data].deleted ||
|
||||
core.status.maps[data].forceDelete)
|
||||
)
|
||||
return;
|
||||
// 首先重新加载main.floors对应的楼层
|
||||
await import(
|
||||
/* @vite-ignore */ `/forceTem/project/floors/${data}.js?v=${Date.now()}`
|
||||
);
|
||||
// 然后写入core.floors并解析
|
||||
core.floors[data] = main.floors[data];
|
||||
const floor = core.loadFloor(data);
|
||||
if (core.isPlaying()) {
|
||||
core.status.maps[data] = floor;
|
||||
delete core.status.mapBlockObjs[data];
|
||||
core.extractBlocks(data);
|
||||
if (data === core.status.floorId) {
|
||||
core.status.thisMap = core.status.maps[data];
|
||||
let weather = core.getFlag('__weather__', null);
|
||||
if (!weather && core.status.thisMap.weather)
|
||||
weather = core.status.thisMap.weather;
|
||||
if (weather) core.setWeather(weather[0], weather[1]);
|
||||
else core.setWeather();
|
||||
}
|
||||
core.status.maps[data].enemy?.extract();
|
||||
core.status.maps[data].enemy?.calRealAttribute();
|
||||
core.updateStatusBar(true, true);
|
||||
}
|
||||
Mota.require('module', 'Shadow').Shadow.update(true);
|
||||
const Binder = Mota.require('module', 'Render').LayerGroupFloorBinder;
|
||||
Binder.activedBinder.forEach(v => {
|
||||
if (v.getFloor() === core.status.floorId) {
|
||||
v.updateBindData();
|
||||
}
|
||||
});
|
||||
console.log(`Floor hot reload: ${data}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 属性热重载,包括全塔属性等
|
||||
* @param {string} data
|
||||
*/
|
||||
async function reloadData(data) {
|
||||
const script = document.createElement('script');
|
||||
script.src = `/forceTem/project/${data}.js?v=${Date.now()}`;
|
||||
document.body.appendChild(script);
|
||||
await new Promise(res => {
|
||||
script.onload = () => res('success');
|
||||
});
|
||||
|
||||
let after;
|
||||
if (data === 'data') after = data_a1e2fb4a_e986_4524_b0da_9b7ba7c0874d;
|
||||
if (data === 'enemys')
|
||||
after = enemys_fcae963b_31c9_42b4_b48c_bb48d09f3f80;
|
||||
if (data === 'icons')
|
||||
after = icons_4665ee12_3a1f_44a4_bea3_0fccba634dc1;
|
||||
if (data === 'items')
|
||||
after = items_296f5d02_12fd_4166_a7c1_b5e830c9ee3a;
|
||||
if (data === 'maps') after = maps_90f36752_8815_4be8_b32b_d7fad1d0542e;
|
||||
if (data === 'events')
|
||||
after = events_c12a15a8_c380_4b28_8144_256cba95f760;
|
||||
|
||||
if (data === 'enemys') {
|
||||
core.enemys.enemys = after;
|
||||
for (var enemyId in after) {
|
||||
core.enemys.enemys[enemyId].id = enemyId;
|
||||
}
|
||||
core.material.enemys = core.getEnemys();
|
||||
} else if (data === 'icons') {
|
||||
core.icons.icons = after;
|
||||
core.material.icons = core.getIcons();
|
||||
} else if (data === 'items') {
|
||||
core.items.items = after;
|
||||
for (var itemId in after) {
|
||||
core.items.items[itemId].id = itemId;
|
||||
}
|
||||
core.material.items = core.getItems();
|
||||
} else if (data === 'maps') {
|
||||
core.maps.blocksInfo = after;
|
||||
core.status.mapBlockObjs = {};
|
||||
core.status.number2block = {};
|
||||
Object.values(core.status.maps).forEach(v => delete v.blocks);
|
||||
core.extractBlocks();
|
||||
core.setWeather(
|
||||
core.animateFrame.weather.type,
|
||||
core.animateFrame.weather.level
|
||||
);
|
||||
core.drawMap();
|
||||
} else if (data === 'events') {
|
||||
core.events.commonEvent = after.commonEvent;
|
||||
} else if (data === 'data') {
|
||||
location.reload();
|
||||
}
|
||||
core.updateStatusBar(true, true);
|
||||
console.log(`Data hot reload: ${data}`);
|
||||
}
|
||||
|
||||
const ws = new WebSocket('ws://127.0.0.1:3000');
|
||||
ws.addEventListener('open', () => {
|
||||
console.log(`Web socket connect successfully`);
|
||||
});
|
||||
ws.addEventListener('message', e => {
|
||||
const data = JSON.parse(e.data);
|
||||
if (data.type === 'reload') location.reload();
|
||||
if (data.type === 'floorHotReload') reloadFloor(data.floor);
|
||||
if (data.type === 'dataHotReload') reloadData(data.data);
|
||||
if (data.type === 'cssHotReload') reloadCss(data.path);
|
||||
});
|
||||
})();
|
||||
@@ -1,152 +0,0 @@
|
||||
import { has, ofDir } from '@/plugin/game/utils';
|
||||
|
||||
export function init() {
|
||||
// 伤害弹出
|
||||
// 复写阻激夹域检测
|
||||
control.prototype.checkBlock = function (forceMockery: boolean = false) {
|
||||
const x = core.getHeroLoc('x'),
|
||||
y = core.getHeroLoc('y'),
|
||||
loc = x + ',' + y;
|
||||
const info = core.status.thisMap.enemy.mapDamage[loc];
|
||||
const damage = info?.damage;
|
||||
if (damage) {
|
||||
if (!main.replayChecking) {
|
||||
Mota.Plugin.require('pop_r').addPop(
|
||||
(x - core.bigmap.offsetX / 32) * 32 + 12,
|
||||
(y - core.bigmap.offsetY / 32) * 32 + 20,
|
||||
(-damage).toString()
|
||||
);
|
||||
}
|
||||
core.status.hero.hp -= damage;
|
||||
const type = [...info.type];
|
||||
const text = type.join(',') || '伤害';
|
||||
core.drawTip('受到' + text + damage + '点');
|
||||
core.drawHeroAnimate('zone');
|
||||
this._checkBlock_disableQuickShop();
|
||||
core.status.hero.statistics.extraDamage += damage;
|
||||
if (core.status.hero.hp <= 0) {
|
||||
core.status.hero.hp = 0;
|
||||
core.updateStatusBar();
|
||||
core.events.lose();
|
||||
return;
|
||||
} else {
|
||||
core.updateStatusBar();
|
||||
}
|
||||
}
|
||||
checkMockery(loc, forceMockery);
|
||||
checkHunt(loc);
|
||||
};
|
||||
}
|
||||
|
||||
function checkMockery(loc: string, force: boolean = false) {
|
||||
if (core.status.lockControl && !force) return;
|
||||
const mockery = core.status.thisMap.enemy.mapDamage[loc]?.mockery;
|
||||
if (mockery) {
|
||||
mockery.sort((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]));
|
||||
const action = [];
|
||||
const [tx, ty] = mockery[0];
|
||||
let { x, y } = core.status.hero.loc;
|
||||
const dir = x > tx ? 'left' : x < tx ? 'right' : y > ty ? 'up' : 'down';
|
||||
const { x: dx, y: dy } = core.utils.scan[dir];
|
||||
|
||||
action.push({ type: 'forbidSave', forbid: true });
|
||||
action.push({ type: 'changePos', direction: dir });
|
||||
const blocks = core.getMapBlocksObj();
|
||||
while (1) {
|
||||
x += dx;
|
||||
y += dy;
|
||||
const block = blocks[`${x},${y}`];
|
||||
if (block) {
|
||||
if (
|
||||
[
|
||||
'animates',
|
||||
'autotile',
|
||||
'tileset',
|
||||
'npcs',
|
||||
'npc48',
|
||||
'terrains'
|
||||
].includes(block.event.cls) &&
|
||||
block.event.noPass
|
||||
) {
|
||||
action.push(
|
||||
{
|
||||
type: 'hide',
|
||||
loc: [[x, y]],
|
||||
remove: true,
|
||||
time: 0
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: `function() { core.removeGlobalAnimate(${x}, ${y}) }`
|
||||
},
|
||||
{
|
||||
type: 'animate',
|
||||
name: 'hand',
|
||||
loc: [x, y],
|
||||
async: true
|
||||
}
|
||||
);
|
||||
}
|
||||
if (block.event.cls.startsWith('enemy')) {
|
||||
action.push({ type: 'moveAction' });
|
||||
}
|
||||
}
|
||||
action.push({ type: 'moveAction' });
|
||||
if (x === tx && y === ty) break;
|
||||
}
|
||||
action.push({
|
||||
type: 'function',
|
||||
function: `function() { core.checkBlock(true); }`
|
||||
});
|
||||
action.push({ type: 'stopAsync' });
|
||||
action.push({ type: 'forbidSave' });
|
||||
core.insertAction(action);
|
||||
}
|
||||
}
|
||||
|
||||
function checkHunt(loc: string) {
|
||||
const hunt = core.status.thisMap.enemy.mapDamage[loc]?.hunt;
|
||||
if (!hunt) return;
|
||||
const { x: hx, y: hy } = core.status.hero.loc;
|
||||
|
||||
const action: any = [];
|
||||
hunt.sort((a, b) => {
|
||||
return a[0] === b[0] ? a[1] - b[1] : a[0] - b[0];
|
||||
});
|
||||
|
||||
for (const [x, y, dir] of hunt) {
|
||||
const [tx, ty] = ofDir(x, y, dir);
|
||||
if (core.getBlock(tx, ty)) continue;
|
||||
action.push(
|
||||
{
|
||||
type: 'move',
|
||||
loc: [x, y],
|
||||
time: 100,
|
||||
keep: true,
|
||||
steps: [`${dir}:1`]
|
||||
},
|
||||
{
|
||||
type: 'update'
|
||||
}
|
||||
);
|
||||
|
||||
if (has(hy) && x === hx) {
|
||||
if (Math.abs(y - hy) <= 2) {
|
||||
action.push({
|
||||
type: 'battle',
|
||||
loc: [tx, ty]
|
||||
});
|
||||
}
|
||||
}
|
||||
if (has(hx) && y === hy) {
|
||||
if (Math.abs(x - hx) <= 2) {
|
||||
action.push({
|
||||
type: 'battle',
|
||||
loc: [tx, ty]
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
core.insertAction(action);
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
// todo: 优化,直接调用 floor.enemy.list 进行计算
|
||||
|
||||
/**
|
||||
* 检查漏怪
|
||||
*/
|
||||
export function checkRemainEnemy(floorIds: FloorIds[]) {
|
||||
const enemy: Partial<Record<FloorIds, { loc: LocArr; id: EnemyIds }[]>> =
|
||||
{};
|
||||
floorIds.forEach(v => {
|
||||
core.extractBlocks(v);
|
||||
const blocks = core.status.maps[v].blocks;
|
||||
blocks.forEach(block => {
|
||||
if (!block.event.cls.startsWith('enemy') || block.disable) return;
|
||||
const id: EnemyIds = block.event.id as EnemyIds;
|
||||
enemy[v] ??= [];
|
||||
const info = enemy[v]!;
|
||||
info.push({ loc: [block.x, block.y], id });
|
||||
});
|
||||
});
|
||||
return enemy;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取剩余怪物字符串
|
||||
*/
|
||||
export function getRemainEnemyString(floorIds: FloorIds[]) {
|
||||
const enemy = checkRemainEnemy(floorIds);
|
||||
const str = [];
|
||||
let now = [];
|
||||
for (const floor in enemy) {
|
||||
const all: { loc: LocArr; id: EnemyIds }[] = enemy[floor as FloorIds]!;
|
||||
const remain: Partial<Record<EnemyIds, number>> = {};
|
||||
all.forEach(v => {
|
||||
const id = v.id;
|
||||
remain[id] ??= 0;
|
||||
remain[id]!++;
|
||||
});
|
||||
const title = core.status.maps[floor as FloorIds].title;
|
||||
for (const id in remain) {
|
||||
const name = core.material.enemys[id as EnemyIds].name;
|
||||
now.push(`${title}(${floor}): ${name} * ${remain[id as EnemyIds]}`);
|
||||
if (now.length === 10) {
|
||||
str.push(now.join('\n'));
|
||||
now = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (now.length > 0) {
|
||||
str.push(now.join('\n'));
|
||||
str[0] = `当前剩余怪物:\n${str[0]}`;
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
@@ -1,684 +0,0 @@
|
||||
import type {
|
||||
RenderAdapter,
|
||||
LayerDoorAnimate,
|
||||
LayerGroupAnimate,
|
||||
LayerFloorBinder,
|
||||
HeroRenderer,
|
||||
Layer,
|
||||
LayerGroup,
|
||||
FloorViewport
|
||||
} from '@motajs/render';
|
||||
import type { TimingFn } from 'mutate-animate';
|
||||
import { BlockMover, heroMoveCollection, MoveStep } from '@/game/state/move';
|
||||
|
||||
// 向后兼容用,会充当两个版本间过渡的作用
|
||||
|
||||
interface Adapters {
|
||||
'hero-adapter'?: RenderAdapter<HeroRenderer>;
|
||||
'door-animate'?: RenderAdapter<LayerDoorAnimate>;
|
||||
animate?: RenderAdapter<LayerGroupAnimate>;
|
||||
layer?: RenderAdapter<Layer>;
|
||||
viewport?: RenderAdapter<FloorViewport>;
|
||||
}
|
||||
|
||||
const adapters: Adapters = {};
|
||||
|
||||
export function init() {
|
||||
const hook = Mota.require('var', 'hook');
|
||||
const loading = Mota.require('var', 'loading');
|
||||
let fallbackIds: number = 1e8;
|
||||
|
||||
if (!main.replayChecking && main.mode === 'play') {
|
||||
const Adapter = Mota.require('module', 'Render').RenderAdapter;
|
||||
const hero = Adapter.get<HeroRenderer>('hero-adapter');
|
||||
const doorAnimate = Adapter.get<LayerDoorAnimate>('door-animate');
|
||||
const animate = Adapter.get<LayerGroupAnimate>('animate');
|
||||
const layer = Adapter.get<Layer>('layer');
|
||||
const viewport = Adapter.get<FloorViewport>('viewport');
|
||||
|
||||
adapters['hero-adapter'] = hero;
|
||||
adapters['door-animate'] = doorAnimate;
|
||||
adapters['animate'] = animate;
|
||||
adapters['layer'] = layer;
|
||||
adapters['viewport'] = viewport;
|
||||
}
|
||||
|
||||
const { mover: heroMover } = heroMoveCollection;
|
||||
|
||||
// ----- 工具函数
|
||||
|
||||
/**
|
||||
* 根据事件中给出的移动数组解析出全部的移动步骤
|
||||
*/
|
||||
function getMoveSteps(steps: string[]) {
|
||||
const moveSteps: string[] = [];
|
||||
steps.forEach(v => {
|
||||
const [type, number] = v.split(':');
|
||||
if (!number) moveSteps.push(type);
|
||||
else {
|
||||
if (type === 'speed') moveSteps.push(v);
|
||||
else {
|
||||
moveSteps.push(...Array(Number(number)).fill(type));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return moveSteps;
|
||||
}
|
||||
|
||||
function setHeroDirection(dir: Dir) {
|
||||
heroMover.setFaceDir(dir);
|
||||
heroMover.setMoveDir(dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成跳跃函数
|
||||
*/
|
||||
function generateJumpFn(dx: number, dy: number): TimingFn<3> {
|
||||
const distance = Math.hypot(dx, dy);
|
||||
const peak = 3 + distance;
|
||||
|
||||
return (progress: number) => {
|
||||
const x = dx * progress;
|
||||
const y = progress * dy + (progress ** 2 - progress) * peak;
|
||||
|
||||
return [x, y, Math.ceil(y)];
|
||||
};
|
||||
}
|
||||
|
||||
Mota.r(() => {
|
||||
// ----- 引入
|
||||
const Camera = Mota.require('module', 'Render').Camera;
|
||||
const Renderer = Mota.require('module', 'Render').MotaRenderer;
|
||||
const Animation = Mota.require('module', 'Animation');
|
||||
|
||||
// ----- 勇士移动相关
|
||||
control.prototype.moveAction = async function (callback?: () => void) {
|
||||
heroMover.clearMoveQueue();
|
||||
heroMover.oneStep('forward');
|
||||
const lock = core.status.lockControl;
|
||||
const controller = heroMover.startMove(false, true, lock);
|
||||
controller?.onEnd.then(() => {
|
||||
callback?.();
|
||||
});
|
||||
heroMover.once('stepEnd', () => {
|
||||
controller?.stop();
|
||||
});
|
||||
};
|
||||
|
||||
control.prototype._moveAction_moving = function (
|
||||
callback?: () => void
|
||||
) {};
|
||||
|
||||
events.prototype._action_moveAction = function (
|
||||
data: any,
|
||||
x: number,
|
||||
y: number,
|
||||
prefix: any
|
||||
) {
|
||||
if (core.canMoveHero()) {
|
||||
var nx = core.nextX(),
|
||||
ny = core.nextY();
|
||||
// 检查noPass决定是撞击还是移动
|
||||
if (core.noPass(nx, ny)) {
|
||||
core.insertAction([{ type: 'trigger', loc: [nx, ny] }]);
|
||||
} else {
|
||||
// 先移动一格,然后尝试触发事件
|
||||
core.insertAction([
|
||||
{
|
||||
type: 'function',
|
||||
function:
|
||||
'function() { core.moveAction(core.doAction); }',
|
||||
async: true
|
||||
},
|
||||
{ type: '_label' }
|
||||
]);
|
||||
}
|
||||
}
|
||||
core.doAction();
|
||||
};
|
||||
|
||||
events.prototype.eventMoveHero = async function (
|
||||
steps: string[],
|
||||
time: number = 500,
|
||||
callback?: () => void
|
||||
) {
|
||||
if (heroMover.moving) return;
|
||||
const moveSteps = getMoveSteps(steps);
|
||||
|
||||
const resolved = moveSteps.map<MoveStep>(v => {
|
||||
if (v.startsWith('speed')) {
|
||||
return { type: 'speed', value: Number(v.slice(6)) };
|
||||
} else {
|
||||
return { type: 'dir', value: v as Move2 };
|
||||
}
|
||||
});
|
||||
const start: MoveStep = { type: 'speed', value: time };
|
||||
|
||||
heroMover.insertMove(...[start, ...resolved]);
|
||||
const controller = heroMover.startMove(true, true, true, false);
|
||||
if (!controller) {
|
||||
callback?.();
|
||||
return;
|
||||
}
|
||||
controller.onEnd.then(() => {
|
||||
callback?.();
|
||||
});
|
||||
|
||||
const animate = fallbackIds++;
|
||||
|
||||
core.animateFrame.lastAsyncId = animate;
|
||||
core.animateFrame.asyncId[animate] = controller.stop;
|
||||
};
|
||||
|
||||
control.prototype.setHeroLoc = function (
|
||||
name: 'x' | 'y' | 'direction',
|
||||
value: number | Dir,
|
||||
noGather?: boolean
|
||||
) {
|
||||
if (!core.status.hero) return;
|
||||
// @ts-ignore
|
||||
core.status.hero.loc[name] = value;
|
||||
if ((name === 'x' || name === 'y') && !noGather) {
|
||||
this.gatherFollowers();
|
||||
}
|
||||
if (name === 'direction') {
|
||||
adapters['hero-adapter']?.sync('turn', value);
|
||||
adapters['hero-adapter']?.sync('setAnimateDir', value);
|
||||
setHeroDirection(value as Dir);
|
||||
} else if (name === 'x') {
|
||||
// 为了防止逆天样板出问题
|
||||
core.bigmap.posX = value as number;
|
||||
adapters['hero-adapter']?.sync('setHeroLoc', value);
|
||||
} else {
|
||||
// 为了防止逆天样板出问题
|
||||
core.bigmap.posY = value as number;
|
||||
adapters['hero-adapter']?.sync('setHeroLoc', void 0, value);
|
||||
}
|
||||
};
|
||||
|
||||
////// 停止勇士的一切行动,等待勇士行动结束后,再执行callback //////
|
||||
control.prototype.waitHeroToStop = function (callback?: () => void) {
|
||||
core.stopAutomaticRoute();
|
||||
core.clearContinueAutomaticRoute();
|
||||
heroMover.controller?.stop();
|
||||
if (callback) {
|
||||
core.status.replay.animate = true;
|
||||
core.lockControl();
|
||||
core.status.automaticRoute.moveDirectly = false;
|
||||
setTimeout(
|
||||
function () {
|
||||
core.status.replay.animate = false;
|
||||
callback();
|
||||
},
|
||||
core.status.replay.speed === 24 ? 1 : 30
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
control.prototype.moveHero = async function (
|
||||
direction?: Dir,
|
||||
callback?: () => void,
|
||||
noRoute: boolean = false
|
||||
) {
|
||||
if (heroMover.moving) return;
|
||||
heroMover.clearMoveQueue();
|
||||
heroMover.oneStep(direction ?? 'forward');
|
||||
const lock = core.status.lockControl;
|
||||
const controller = heroMover.startMove(false, noRoute, lock);
|
||||
controller?.onEnd.then(() => {
|
||||
callback?.();
|
||||
});
|
||||
heroMover.once('stepEnd', () => {
|
||||
controller?.stop();
|
||||
});
|
||||
};
|
||||
|
||||
events.prototype.setHeroIcon = function (name: ImageIds) {
|
||||
const img = core.material.images.images[name];
|
||||
if (!img) return;
|
||||
core.status.hero.image = name;
|
||||
adapters['hero-adapter']?.sync('setImage', img);
|
||||
};
|
||||
|
||||
control.prototype.isMoving = function () {
|
||||
return heroMover.moving;
|
||||
};
|
||||
|
||||
////// 设置自动寻路路线 //////
|
||||
control.prototype.setAutomaticRoute = function (
|
||||
destX: number,
|
||||
destY: number,
|
||||
stepPostfix: DiredLoc[]
|
||||
) {
|
||||
if (heroMover.moving) return;
|
||||
if (!core.status.played || core.status.lockControl) return;
|
||||
if (this._setAutomaticRoute_isMoving(destX, destY)) return;
|
||||
if (this._setAutomaticRoute_isTurning(destX, destY, stepPostfix))
|
||||
return;
|
||||
if (
|
||||
this._setAutomaticRoute_clickMoveDirectly(
|
||||
destX,
|
||||
destY,
|
||||
stepPostfix
|
||||
)
|
||||
)
|
||||
return;
|
||||
// 找寻自动寻路路线
|
||||
const moveStep = core.automaticRoute(destX, destY);
|
||||
if (
|
||||
moveStep.length == 0 &&
|
||||
(destX != core.status.hero.loc.x ||
|
||||
destY != core.status.hero.loc.y ||
|
||||
stepPostfix.length == 0)
|
||||
)
|
||||
return;
|
||||
moveStep.push(...stepPostfix);
|
||||
core.status.automaticRoute.destX = destX;
|
||||
core.status.automaticRoute.destY = destY;
|
||||
this._setAutomaticRoute_drawRoute(moveStep);
|
||||
this._setAutomaticRoute_setAutoSteps(moveStep);
|
||||
|
||||
// ???
|
||||
core.setAutoHeroMove();
|
||||
|
||||
// 执行移动
|
||||
const steps: MoveStep[] = moveStep.map(v => {
|
||||
return { type: 'dir', value: v.direction };
|
||||
});
|
||||
heroMover.clearMoveQueue();
|
||||
heroMover.insertMove(...steps);
|
||||
heroMover.startMove();
|
||||
};
|
||||
|
||||
// ----- 开关门
|
||||
events.prototype.openDoor = function (
|
||||
x: number,
|
||||
y: number,
|
||||
needKey: boolean,
|
||||
callback?: () => void
|
||||
) {
|
||||
var block = core.getBlock(x, y);
|
||||
core.saveAndStopAutomaticRoute();
|
||||
if (!this._openDoor_check(block, x, y, needKey)) {
|
||||
var locked = core.status.lockControl;
|
||||
core.waitHeroToStop(function () {
|
||||
if (!locked) core.unlockControl();
|
||||
if (callback) callback();
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (core.status.replay.speed === 24) {
|
||||
core.status.replay.animate = true;
|
||||
core.removeBlock(x, y);
|
||||
setTimeout(function () {
|
||||
core.status.replay.animate = false;
|
||||
Mota.require('var', 'hook').emit(
|
||||
'afterOpenDoor',
|
||||
block.event.id as AllIdsOf<'animates'>,
|
||||
x,
|
||||
y
|
||||
);
|
||||
if (callback) callback();
|
||||
}, 1); // +1是为了录像检测系统
|
||||
} else {
|
||||
const locked = core.status.lockControl;
|
||||
core.lockControl();
|
||||
core.status.replay.animate = true;
|
||||
core.removeBlock(x, y);
|
||||
|
||||
const cb = () => {
|
||||
core.maps._removeBlockFromMap(core.status.floorId, block);
|
||||
if (!locked) core.unlockControl();
|
||||
core.status.replay.animate = false;
|
||||
hook.emit(
|
||||
'afterOpenDoor',
|
||||
block.event.id as AllIdsOf<'animates'>,
|
||||
x,
|
||||
y
|
||||
);
|
||||
callback?.();
|
||||
};
|
||||
|
||||
adapters['door-animate']?.all('openDoor', block).then(cb);
|
||||
|
||||
const animate = fallbackIds++;
|
||||
core.animateFrame.lastAsyncId = animate;
|
||||
core.animateFrame.asyncId[animate] = cb;
|
||||
// this._openDoor_animate(block, x, y, callback);
|
||||
}
|
||||
};
|
||||
|
||||
events.prototype.closeDoor = function (
|
||||
x: number,
|
||||
y: number,
|
||||
id: AllIds,
|
||||
callback?: () => void
|
||||
) {
|
||||
id = id || '';
|
||||
if (
|
||||
// @ts-ignore
|
||||
(core.material.icons.animates[id] == null &&
|
||||
// @ts-ignore
|
||||
core.material.icons.npc48[id] == null) ||
|
||||
core.getBlock(x, y) != null
|
||||
) {
|
||||
if (callback) callback();
|
||||
return;
|
||||
}
|
||||
var block = core.getBlockById(id);
|
||||
var doorInfo = (block.event || {}).doorInfo;
|
||||
if (!doorInfo) {
|
||||
if (callback) callback();
|
||||
return;
|
||||
}
|
||||
|
||||
core.playSound(doorInfo.closeSound);
|
||||
|
||||
const locked = core.status.lockControl;
|
||||
core.lockControl();
|
||||
core.status.replay.animate = true;
|
||||
const cb = function () {
|
||||
if (!locked) core.unlockControl();
|
||||
core.status.replay.animate = false;
|
||||
core.setBlock(id, x, y);
|
||||
core.showBlock(x, y);
|
||||
callback?.();
|
||||
};
|
||||
|
||||
if (core.status.replay.speed === 24) {
|
||||
cb();
|
||||
} else {
|
||||
adapters['door-animate']?.all('closeDoor', block).then(() => {
|
||||
cb();
|
||||
});
|
||||
|
||||
const animate = fallbackIds++;
|
||||
core.animateFrame.lastAsyncId = animate;
|
||||
core.animateFrame.asyncId[animate] = cb;
|
||||
this._openDoor_animate(block, x, y, callback);
|
||||
}
|
||||
};
|
||||
|
||||
// ----- animate & hero animate
|
||||
////// 绘制动画 //////
|
||||
maps.prototype.drawAnimate = function (
|
||||
name: AnimationIds,
|
||||
x: number,
|
||||
y: number,
|
||||
alignWindow?: boolean,
|
||||
callback?: () => void
|
||||
) {
|
||||
// @ts-ignore
|
||||
name = core.getMappedName(name);
|
||||
|
||||
// 正在播放录像:不显示动画
|
||||
if (
|
||||
core.isReplaying() ||
|
||||
!core.material.animates[name] ||
|
||||
x == null ||
|
||||
y == null
|
||||
) {
|
||||
if (callback) callback();
|
||||
return -1;
|
||||
}
|
||||
|
||||
adapters.animate
|
||||
?.all(
|
||||
'drawAnimate',
|
||||
name,
|
||||
x * 32 + 16,
|
||||
y * 32 + 16,
|
||||
alignWindow ?? false
|
||||
)
|
||||
.then(() => {
|
||||
callback?.();
|
||||
});
|
||||
};
|
||||
|
||||
maps.prototype.drawHeroAnimate = function (
|
||||
name: AnimationIds,
|
||||
callback?: () => void
|
||||
) {
|
||||
// @ts-ignore
|
||||
name = core.getMappedName(name);
|
||||
|
||||
// 正在播放录像或动画不存在:不显示动画
|
||||
if (core.isReplaying() || !core.material.animates[name]) {
|
||||
if (callback) callback();
|
||||
return -1;
|
||||
}
|
||||
|
||||
adapters.animate?.global('drawHeroAnimate', name).then(() => {
|
||||
callback?.();
|
||||
});
|
||||
};
|
||||
|
||||
// 移动跳跃图块 & 跳跃勇士
|
||||
maps.prototype.moveBlock = async function (
|
||||
x: number,
|
||||
y: number,
|
||||
steps: string[],
|
||||
time: number = 500,
|
||||
keep: boolean = false,
|
||||
callback?: () => void
|
||||
) {
|
||||
if (!steps || steps.length === 0) {
|
||||
callback?.();
|
||||
return;
|
||||
}
|
||||
const block = core.getBlock(x, y);
|
||||
if (!block) {
|
||||
callback?.();
|
||||
return;
|
||||
}
|
||||
const mover = new BlockMover(x, y, core.status.floorId, 'event');
|
||||
const moveSteps = getMoveSteps(steps);
|
||||
const resolved = moveSteps.map<MoveStep>(v => {
|
||||
if (v.startsWith('speed')) {
|
||||
return { type: 'speed', value: Number(v.slice(6)) };
|
||||
} else {
|
||||
return { type: 'dir', value: v as Move2 };
|
||||
}
|
||||
});
|
||||
const start: MoveStep = { type: 'speed', value: time };
|
||||
mover.insertMove(...[start, ...resolved]);
|
||||
const controller = mover.startMove();
|
||||
|
||||
if (controller) {
|
||||
await controller.onEnd;
|
||||
}
|
||||
|
||||
if (!keep) {
|
||||
core.removeBlock(mover.x, mover.y);
|
||||
}
|
||||
callback?.();
|
||||
};
|
||||
|
||||
////// 显示跳跃某块的动画,达到{"type":"jump"}的效果 //////
|
||||
maps.prototype.jumpBlock = async function (
|
||||
sx: number,
|
||||
sy: number,
|
||||
ex: number,
|
||||
ey: number,
|
||||
time: number = 500,
|
||||
keep: boolean = false,
|
||||
callback?: () => void
|
||||
) {
|
||||
const block = core.getBlock(sx, sy);
|
||||
if (!block) {
|
||||
callback?.();
|
||||
return;
|
||||
}
|
||||
time /= core.status.replay.speed;
|
||||
if (core.status.replay.speed === 24) time = 1;
|
||||
const dx = ex - sx;
|
||||
const dy = ey - sy;
|
||||
|
||||
const fn = generateJumpFn(dx, dy);
|
||||
|
||||
const list = adapters.layer?.items ?? [];
|
||||
const items = [...list].filter(v => {
|
||||
if (v.layer !== 'event') return false;
|
||||
const ex = v.getExtends('floor-binder') as LayerFloorBinder;
|
||||
if (!ex) return false;
|
||||
return ex.getFloor() === core.status.floorId;
|
||||
});
|
||||
const width = core.status.thisMap.width;
|
||||
const index = sx + sy * width;
|
||||
|
||||
const promise = Promise.all(
|
||||
items.map(v => {
|
||||
return v.moveAs(index, ex, ey, fn, time, keep);
|
||||
})
|
||||
);
|
||||
|
||||
core.updateStatusBar();
|
||||
core.removeBlock(sx, sy);
|
||||
await promise;
|
||||
if (keep) {
|
||||
core.setBlock(block.id, ex, ey);
|
||||
}
|
||||
core.updateStatusBar();
|
||||
|
||||
callback?.();
|
||||
};
|
||||
|
||||
events.prototype.jumpHero = async function (
|
||||
ex: number,
|
||||
ey: number,
|
||||
time: number = 500,
|
||||
callback?: () => void
|
||||
) {
|
||||
if (heroMover.moving) return;
|
||||
|
||||
const sx = core.getHeroLoc('x');
|
||||
const sy = core.getHeroLoc('y');
|
||||
adapters.viewport?.all('mutateTo', ex, ey, time);
|
||||
|
||||
const locked = core.status.lockControl;
|
||||
core.lockControl();
|
||||
const list = adapters['hero-adapter']?.items ?? [];
|
||||
const items = [...list];
|
||||
|
||||
time /= core.status.replay.speed;
|
||||
if (core.status.replay.speed === 24) time = 1;
|
||||
const fn = generateJumpFn(ex - sx, ey - sy);
|
||||
await Promise.all(
|
||||
items.map(v => {
|
||||
if (!v.renderable) return Promise.reject();
|
||||
return v.layer.moveRenderable(
|
||||
v.renderable,
|
||||
sx,
|
||||
sy,
|
||||
fn,
|
||||
time
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
if (!locked) core.unlockControl();
|
||||
core.setHeroLoc('x', ex);
|
||||
core.setHeroLoc('y', ey);
|
||||
callback?.();
|
||||
};
|
||||
|
||||
// ----- 视角处理
|
||||
|
||||
////// 瞬间移动 //////
|
||||
control.prototype.moveDirectly = function (
|
||||
destX: number,
|
||||
destY: number,
|
||||
ignoreSteps: number
|
||||
) {
|
||||
const data = this.controldata;
|
||||
const success = data.moveDirectly(destX, destY, ignoreSteps);
|
||||
if (success) adapters.viewport?.all('mutateTo', destX, destY);
|
||||
return success;
|
||||
};
|
||||
|
||||
control.prototype.moveViewport = function (
|
||||
x: number,
|
||||
y: number,
|
||||
_moveMode: EaseMode,
|
||||
time: number = 1,
|
||||
callback?: () => void
|
||||
) {
|
||||
const main = Renderer.get('render-main');
|
||||
const layer = main?.getElementById('layer-main') as LayerGroup;
|
||||
if (!layer) return;
|
||||
const camera = Camera.for(layer);
|
||||
camera.clearOperation();
|
||||
const translate = camera.addTranslate();
|
||||
|
||||
const animateTime = time / Math.max(core.status.replay.speed, 1);
|
||||
const animate = new Animation.Animation();
|
||||
animate
|
||||
.absolute()
|
||||
.time(1)
|
||||
.mode(Animation.linear())
|
||||
.move(core.bigmap.offsetX, core.bigmap.offsetY);
|
||||
animate.time(animateTime).move(x * 32, y * 32);
|
||||
|
||||
camera.applyTranslateAnimation(
|
||||
translate,
|
||||
animate,
|
||||
animateTime + 50
|
||||
);
|
||||
camera.transform = layer.camera;
|
||||
|
||||
const end = () => {
|
||||
core.bigmap.offsetX = x * 32;
|
||||
core.bigmap.offsetY = y * 32;
|
||||
camera.destroy();
|
||||
callback?.();
|
||||
};
|
||||
|
||||
const timeout = window.setTimeout(end, animateTime + 50);
|
||||
|
||||
const id = fallbackIds++;
|
||||
core.animateFrame.lastAsyncId = id;
|
||||
core.animateFrame.asyncId[id] = () => {
|
||||
end();
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
loading.once('loaded', () => {
|
||||
for (const animate of Object.values(core.material.animates)) {
|
||||
animate.se ??= {};
|
||||
if (typeof animate.se === 'string') {
|
||||
animate.se = { 1: animate.se };
|
||||
}
|
||||
animate.pitch ??= {};
|
||||
}
|
||||
});
|
||||
|
||||
const moveAction = new Set<string>(['up', 'down', 'left', 'right']);
|
||||
// 复写录像的移动
|
||||
core.registerReplayAction('move', action => {
|
||||
if (moveAction.has(action)) {
|
||||
if (!heroMover.moving) {
|
||||
heroMover.startMove();
|
||||
}
|
||||
if (!heroMover.controller) {
|
||||
return false;
|
||||
}
|
||||
heroMover.controller.push({
|
||||
type: 'dir',
|
||||
value: action as Dir
|
||||
});
|
||||
|
||||
heroMover.controller.onEnd.then(() => {
|
||||
core.replay();
|
||||
});
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
// return { readyMove, endMove, move };
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
// @ts-nocheck
|
||||
|
||||
// 创建新图层
|
||||
function createCanvas(name, zIndex) {
|
||||
if (!name) return;
|
||||
var canvas = document.createElement('canvas');
|
||||
canvas.id = name;
|
||||
canvas.className = 'gameCanvas no-anti-aliasing';
|
||||
// 编辑器模式下设置zIndex会导致加入的图层覆盖优先级过高
|
||||
if (main.mode != 'editor') canvas.style.zIndex = zIndex || 0;
|
||||
// 将图层插入进游戏内容
|
||||
document.getElementById('gameDraw').appendChild(canvas);
|
||||
var ctx = canvas.getContext('2d');
|
||||
core.canvas[name] = ctx;
|
||||
|
||||
return canvas;
|
||||
}
|
||||
|
||||
export function init() {
|
||||
// 大地图适配
|
||||
|
||||
core.initStatus.bg2maps = {};
|
||||
core.initStatus.fg2maps = {};
|
||||
|
||||
if (main.mode == 'editor') {
|
||||
var bg2Canvas = createCanvas('bg2', 20);
|
||||
var fg2Canvas = createCanvas('fg2', 63);
|
||||
core.bigmap.canvas = [
|
||||
'bg2',
|
||||
'fg2',
|
||||
'bg',
|
||||
'event',
|
||||
'event2',
|
||||
'fg',
|
||||
'damage'
|
||||
];
|
||||
/*插入编辑器的图层 不做此步新增图层无法在编辑器显示*/
|
||||
// 编辑器图层覆盖优先级 eui > efg > fg(前景层) > event2(48*32图块的事件层) > event(事件层) > bg(背景层)
|
||||
// 背景层2(bg2) 插入事件层(event)之前(即bg与event之间)
|
||||
document
|
||||
.getElementById('mapEdit')
|
||||
.insertBefore(bg2Canvas, document.getElementById('event'));
|
||||
// 前景层2(fg2) 插入编辑器前景(efg)之前(即fg之后)
|
||||
document
|
||||
.getElementById('mapEdit')
|
||||
.insertBefore(fg2Canvas, document.getElementById('ebm'));
|
||||
// 原本有三个图层 从4开始添加
|
||||
var num = 4;
|
||||
// 新增图层存入editor.dom中
|
||||
editor.dom.bg2c = core.canvas.bg2.canvas;
|
||||
editor.dom.bg2Ctx = core.canvas.bg2;
|
||||
editor.dom.fg2c = core.canvas.fg2.canvas;
|
||||
editor.dom.fg2Ctx = core.canvas.fg2;
|
||||
editor.dom.maps.push('bg2map', 'fg2map');
|
||||
editor.dom.canvas.push('bg2', 'fg2');
|
||||
|
||||
// 创建编辑器上的按钮
|
||||
var createCanvasBtn = name => {
|
||||
// 电脑端创建按钮
|
||||
var input = document.createElement('input');
|
||||
// layerMod4/layerMod5
|
||||
var id = 'layerMod' + num++;
|
||||
// bg2map/fg2map
|
||||
var value = name + 'map';
|
||||
input.type = 'radio';
|
||||
input.name = 'layerMod';
|
||||
input.id = id;
|
||||
input.value = value;
|
||||
editor.dom[id] = input;
|
||||
input.onchange = () => {
|
||||
editor.uifunctions.setLayerMod(value);
|
||||
};
|
||||
return input;
|
||||
};
|
||||
|
||||
var createCanvasBtn_mobile = name => {
|
||||
// 手机端往选择列表中添加子选项
|
||||
var input = document.createElement('option');
|
||||
var id = 'layerMod' + num++;
|
||||
var value = name + 'map';
|
||||
input.name = 'layerMod';
|
||||
input.value = value;
|
||||
editor.dom[id] = input;
|
||||
return input;
|
||||
};
|
||||
if (!editor.isMobile) {
|
||||
var input = createCanvasBtn('bg2');
|
||||
var input2 = createCanvasBtn('fg2');
|
||||
// 获取事件层及其父节点
|
||||
var child = document.getElementById('layerMod'),
|
||||
parent = child.parentNode;
|
||||
// 背景层2插入事件层前
|
||||
parent.insertBefore(input, child);
|
||||
// 不能直接更改背景层2的innerText 所以创建文本节点
|
||||
var txt = document.createTextNode('背2');
|
||||
// 插入事件层前(即新插入的背景层2前)
|
||||
parent.insertBefore(txt, child);
|
||||
// 向最后插入前景层2(即插入前景层后)
|
||||
parent.appendChild(input2);
|
||||
var txt2 = document.createTextNode('前2');
|
||||
parent.appendChild(txt2);
|
||||
} else {
|
||||
var input = createCanvasBtn_mobile('bg2');
|
||||
var input2 = createCanvasBtn_mobile('fg2');
|
||||
// 手机端因为是选项 所以可以直接改innerText
|
||||
input.innerText = '背景2';
|
||||
input2.innerText = '前景2';
|
||||
var parent = document.getElementById('layerMod');
|
||||
parent.insertBefore(input, parent.children[1]);
|
||||
parent.appendChild(input2);
|
||||
}
|
||||
}
|
||||
|
||||
maps.prototype._loadFloor_doNotCopy = function () {
|
||||
return [
|
||||
'firstArrive',
|
||||
'eachArrive',
|
||||
'blocks',
|
||||
'parallelDo',
|
||||
'map',
|
||||
'bgmap',
|
||||
'fgmap',
|
||||
'bg2map',
|
||||
'fg2map',
|
||||
'events',
|
||||
'changeFloor',
|
||||
'afterBattle',
|
||||
'afterGetItem',
|
||||
'afterOpenDoor',
|
||||
'cannotMove',
|
||||
'enemy'
|
||||
];
|
||||
};
|
||||
////// 绘制背景和前景层 //////
|
||||
maps.prototype._drawBg_draw = function (
|
||||
floorId,
|
||||
toDrawCtx,
|
||||
cacheCtx,
|
||||
config
|
||||
) {
|
||||
config.ctx = cacheCtx;
|
||||
core.maps._drawBg_drawBackground(floorId, config);
|
||||
// ------ 调整这两行的顺序来控制是先绘制贴图还是先绘制背景图块;后绘制的覆盖先绘制的。
|
||||
core.maps._drawFloorImages(
|
||||
floorId,
|
||||
config.ctx,
|
||||
'bg',
|
||||
null,
|
||||
null,
|
||||
config.onMap
|
||||
);
|
||||
core.maps._drawBgFgMap(floorId, 'bg', config);
|
||||
if (config.onMap) {
|
||||
core.drawImage(
|
||||
toDrawCtx,
|
||||
cacheCtx.canvas,
|
||||
core.bigmap.v2 ? -32 : 0,
|
||||
core.bigmap.v2 ? -32 : 0
|
||||
);
|
||||
core.clearMap('bg2');
|
||||
core.clearMap(cacheCtx);
|
||||
}
|
||||
core.maps._drawBgFgMap(floorId, 'bg2', config);
|
||||
if (config.onMap)
|
||||
core.drawImage(
|
||||
'bg2',
|
||||
cacheCtx.canvas,
|
||||
core.bigmap.v2 ? -32 : 0,
|
||||
core.bigmap.v2 ? -32 : 0
|
||||
);
|
||||
config.ctx = toDrawCtx;
|
||||
};
|
||||
maps.prototype._drawFg_draw = function (
|
||||
floorId,
|
||||
toDrawCtx,
|
||||
cacheCtx,
|
||||
config
|
||||
) {
|
||||
config.ctx = cacheCtx;
|
||||
// ------ 调整这两行的顺序来控制是先绘制贴图还是先绘制前景图块;后绘制的覆盖先绘制的。
|
||||
core.maps._drawFloorImages(
|
||||
floorId,
|
||||
config.ctx,
|
||||
'fg',
|
||||
null,
|
||||
null,
|
||||
config.onMap
|
||||
);
|
||||
core.maps._drawBgFgMap(floorId, 'fg', config);
|
||||
if (config.onMap) {
|
||||
core.drawImage(
|
||||
toDrawCtx,
|
||||
cacheCtx.canvas,
|
||||
core.bigmap.v2 ? -32 : 0,
|
||||
core.bigmap.v2 ? -32 : 0
|
||||
);
|
||||
core.clearMap('fg2');
|
||||
core.clearMap(cacheCtx);
|
||||
}
|
||||
core.maps._drawBgFgMap(floorId, 'fg2', config);
|
||||
if (config.onMap)
|
||||
core.drawImage(
|
||||
'fg2',
|
||||
cacheCtx.canvas,
|
||||
core.bigmap.v2 ? -32 : 0,
|
||||
core.bigmap.v2 ? -32 : 0
|
||||
);
|
||||
config.ctx = toDrawCtx;
|
||||
};
|
||||
////// 移动判定 //////
|
||||
maps.prototype._generateMovableArray_arrays = function (floorId) {
|
||||
return {
|
||||
bgArray: this.getBgMapArray(floorId),
|
||||
fgArray: this.getFgMapArray(floorId),
|
||||
eventArray: this.getMapArray(floorId),
|
||||
bg2Array: this._getBgFgMapArray('bg2', floorId),
|
||||
fg2Array: this._getBgFgMapArray('fg2', floorId)
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
import { EnemyCollection, ensureFloorDamage } from '@/game/enemy/damage';
|
||||
import { formatDamage } from '../utils';
|
||||
|
||||
export function init() {
|
||||
core.control.updateDamage = function (
|
||||
floorId = core.status.floorId,
|
||||
ctx,
|
||||
thumbnail: boolean = false
|
||||
) {
|
||||
if (!floorId || core.status.gameOver || main.mode !== 'play') return;
|
||||
const onMap = ctx == null;
|
||||
const floor = core.status.maps[floorId];
|
||||
|
||||
// 没有怪物手册
|
||||
// if (!core.hasItem('book')) return;
|
||||
core.status.damage.posX = core.bigmap.posX;
|
||||
core.status.damage.posY = core.bigmap.posY;
|
||||
if (!onMap) {
|
||||
const width = core.floors[floorId].width,
|
||||
height = core.floors[floorId].height;
|
||||
// 地图过大的缩略图不绘制显伤
|
||||
if (width * height > core.bigmap.threshold) return;
|
||||
}
|
||||
// 计算伤害
|
||||
ensureFloorDamage(floorId);
|
||||
|
||||
floor.enemy.extract();
|
||||
floor.enemy.calRealAttribute();
|
||||
floor.enemy.calMapDamage();
|
||||
floor.enemy.emit('calculated');
|
||||
core.status.damage.data = [];
|
||||
|
||||
// floor.enemy.render(true);
|
||||
|
||||
// getItemDetail(floorId, onMap); // 宝石血瓶详细信息
|
||||
if (thumbnail) {
|
||||
renderThumbnailDamage(floor.enemy);
|
||||
this.drawDamage(ctx, floorId);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function renderThumbnailDamage(col: EnemyCollection) {
|
||||
core.status.damage.data = [];
|
||||
core.status.damage.extraData = [];
|
||||
core.status.damage.dir = [];
|
||||
|
||||
// 怪物伤害
|
||||
col.list.forEach(v => {
|
||||
const { damage } = v.calDamage();
|
||||
|
||||
// 伤害全部相等,绘制在怪物本身所在位置
|
||||
const { damage: dam, color } = formatDamage(damage);
|
||||
const critical = v.calCritical(1)[0];
|
||||
core.status.damage.data.push({
|
||||
text: dam,
|
||||
px: 32 * v.x! + 1,
|
||||
py: 32 * (v.y! + 1) - 1,
|
||||
color: color
|
||||
});
|
||||
const setting = Mota.require('var', 'mainSetting');
|
||||
const criGem = setting.getValue('screen.criticalGem', false);
|
||||
const n = critical?.atkDelta ?? Infinity;
|
||||
const ratio = core.status.maps[col.floorId].ratio;
|
||||
const cri = criGem ? Math.ceil(n / ratio) : n;
|
||||
|
||||
core.status.damage.data.push({
|
||||
text: isFinite(cri) ? cri.toString() : '?',
|
||||
px: 32 * v.x! + 1,
|
||||
py: 32 * (v.y! + 1) - 11,
|
||||
color: '#fff'
|
||||
});
|
||||
});
|
||||
|
||||
// 地图伤害
|
||||
const floor = core.status.maps[col.floorId];
|
||||
const width = floor.width;
|
||||
const height = floor.height;
|
||||
const objs = core.getMapBlocksObj(col.floorId);
|
||||
|
||||
const startX = 0;
|
||||
const endX = width;
|
||||
const startY = 0;
|
||||
const endY = height;
|
||||
|
||||
for (let x = startX; x < endX; x++) {
|
||||
for (let y = startY; y < endY; y++) {
|
||||
const id = `${x},${y}` as LocString;
|
||||
const dam = col.mapDamage[id];
|
||||
if (!dam || objs[id]?.event.noPass) continue;
|
||||
|
||||
// 地图伤害
|
||||
if (dam.damage !== 0) {
|
||||
const damage = core.formatBigNumber(dam.damage, true);
|
||||
const color = dam.damage < 0 ? '#6eff6a' : '#fa3';
|
||||
core.status.damage.extraData.push({
|
||||
text: damage,
|
||||
px: 32 * x + 16,
|
||||
py: 32 * y + 16,
|
||||
color,
|
||||
alpha: 1
|
||||
});
|
||||
}
|
||||
|
||||
// 电摇嘲讽
|
||||
if (dam.mockery) {
|
||||
dam.mockery.sort((a, b) =>
|
||||
a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]
|
||||
);
|
||||
const [tx, ty] = dam.mockery[0];
|
||||
const dir = x > tx ? '←' : x < tx ? '→' : y > ty ? '↑' : '↓';
|
||||
core.status.damage.extraData.push({
|
||||
text: '嘲' + dir,
|
||||
px: 32 * x + 16,
|
||||
py: 32 * (y + 1) - 14,
|
||||
color: '#fd4',
|
||||
alpha: 1
|
||||
});
|
||||
}
|
||||
|
||||
// 追猎
|
||||
if (dam.hunt) {
|
||||
core.status.damage.extraData.push({
|
||||
text: '猎',
|
||||
px: 32 * x + 16,
|
||||
py: 32 * (y + 1) - 14,
|
||||
color: '#fd4',
|
||||
alpha: 1
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import { hook } from '@/game/game';
|
||||
|
||||
export {};
|
||||
|
||||
const potionItems: AllIdsOf<'items'>[] = [
|
||||
'redPotion',
|
||||
'bluePotion',
|
||||
'yellowPotion',
|
||||
'greenPotion',
|
||||
'I482',
|
||||
'I484',
|
||||
'I487',
|
||||
'I491'
|
||||
];
|
||||
|
||||
hook.on('afterGetItem', (itemId, x, y, isGentleClick) => {
|
||||
// 获得一个道具后触发的事件
|
||||
// itemId:获得的道具ID;x和y是该道具所在的坐标
|
||||
// isGentleClick:是否是轻按触发的
|
||||
if (potionItems.includes(itemId)) core.playSound('回血');
|
||||
else core.playSound('获得道具');
|
||||
|
||||
const todo: any[] = [];
|
||||
// 检查该点的获得道具后事件。
|
||||
if (core.status.floorId == null) return;
|
||||
const event = core.floors[core.status.floorId].afterGetItem[`${x},${y}`];
|
||||
if (
|
||||
event &&
|
||||
(event instanceof Array ||
|
||||
!isGentleClick ||
|
||||
!event.disableOnGentleClick)
|
||||
) {
|
||||
core.unshift(todo, event as any[]);
|
||||
}
|
||||
if (core.hasFlag('spring')) {
|
||||
if (!core.hasFlag('springCount')) core.setFlag('springCount', 0);
|
||||
if (potionItems.includes(itemId)) {
|
||||
core.addFlag('springCount', 1);
|
||||
}
|
||||
if (core.getFlag<number>('springCount', 0) === 50) {
|
||||
core.setFlag('springCount', 0);
|
||||
core.status.hero.hpmax += core.getNakedStatus('hpmax') * 0.1;
|
||||
}
|
||||
core.updateStatusBar();
|
||||
}
|
||||
|
||||
if (todo.length > 0) core.insertAction(todo, x, y);
|
||||
});
|
||||
|
||||
hook.on('afterOpenDoor', (doorId, x, y) => {
|
||||
// 开一个门后触发的事件
|
||||
|
||||
const todo: any[] = [];
|
||||
// 检查该点的获得开门后事件。
|
||||
if (core.status.floorId == null) return;
|
||||
const event = core.floors[core.status.floorId].afterOpenDoor[`${x},${y}`];
|
||||
if (event) core.unshift(todo, event as any[]);
|
||||
|
||||
if (todo.length > 0) core.insertAction(todo, x, y);
|
||||
|
||||
if (core.status.event.id == null) core.continueAutomaticRoute();
|
||||
else core.clearContinueAutomaticRoute();
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
/* @__PURE__ */ import './dev/hotReload'; // 仅开发会用到
|
||||
import * as fiveLayer from './fiveLayer';
|
||||
import * as itemDetail from './fx/itemDetail';
|
||||
import * as replay from './replay';
|
||||
import * as ui from './ui';
|
||||
import * as removeMap from './removeMap';
|
||||
import * as shop from './shop';
|
||||
import * as skill from './skill';
|
||||
import * as skillTree from './skillTree';
|
||||
import * as utils from './utils';
|
||||
import * as chase from './chase';
|
||||
import * as remainEnemy from './enemy/remainEnemy';
|
||||
import * as checkBlock from './enemy/checkblock';
|
||||
import * as fallback from './fallback';
|
||||
import './hook';
|
||||
|
||||
Mota.Plugin.register('utils_g', utils);
|
||||
Mota.Plugin.register('shop_g', shop);
|
||||
Mota.Plugin.register('replay_g', replay, replay.init);
|
||||
Mota.Plugin.register('skillTree_g', skillTree);
|
||||
Mota.Plugin.register('removeMap_g', removeMap);
|
||||
Mota.Plugin.register('chase_g', chase);
|
||||
Mota.Plugin.register('skill_g', skill);
|
||||
Mota.Plugin.register('fiveLayer_g', fiveLayer, fiveLayer.init);
|
||||
Mota.Plugin.register('itemDetail_g', itemDetail, itemDetail.init);
|
||||
// Mota.Plugin.register('study_g', study);
|
||||
Mota.Plugin.register('remainEnemy_g', remainEnemy);
|
||||
Mota.Plugin.register('checkBlock_g', checkBlock, checkBlock.init);
|
||||
// todo: 这几个不应该放到插件
|
||||
Mota.Plugin.register('ui_g', ui, ui.init);
|
||||
// 用于暂时向后兼容的插件,若干个版本后会删除
|
||||
Mota.Plugin.register('fallback_g', fallback, fallback.init);
|
||||
|
||||
// export {
|
||||
// halo,
|
||||
// hero,
|
||||
// loopMap,
|
||||
// remainEnemy,
|
||||
// removeMap,
|
||||
// shop,
|
||||
// skill,
|
||||
// skillTree,
|
||||
// study,
|
||||
// towerBoss,
|
||||
// utils,
|
||||
// chase,
|
||||
// damage,
|
||||
// battle,
|
||||
// special
|
||||
// };
|
||||
@@ -1,111 +0,0 @@
|
||||
export function removeMaps(
|
||||
fromId: FloorIds,
|
||||
toId: FloorIds,
|
||||
force: boolean = false
|
||||
) {
|
||||
toId = toId || fromId;
|
||||
var fromIndex = core.floorIds.indexOf(fromId),
|
||||
toIndex = core.floorIds.indexOf(toId);
|
||||
if (toIndex < 0) toIndex = core.floorIds.length - 1;
|
||||
// @ts-ignore
|
||||
flags.__visited__ ??= {};
|
||||
flags.__removed__ ??= [];
|
||||
flags.__disabled__ ??= {};
|
||||
// @ts-ignore
|
||||
flags.__leaveLoc__ ??= {};
|
||||
flags.__forceDelete__ ??= {};
|
||||
let deleted = false;
|
||||
for (var i = fromIndex; i <= toIndex; ++i) {
|
||||
var floorId = core.floorIds[i];
|
||||
if (core.status.maps[floorId].deleted) continue;
|
||||
delete flags.__visited__[floorId];
|
||||
flags.__removed__.push(floorId);
|
||||
delete flags.__disabled__[floorId];
|
||||
delete flags.__leaveLoc__[floorId];
|
||||
(core.status.autoEvents || []).forEach(event => {
|
||||
if (event.floorId == floorId && event.currentFloor) {
|
||||
core.autoEventExecuting(event.symbol, false);
|
||||
core.autoEventExecuted(event.symbol, false);
|
||||
}
|
||||
});
|
||||
core.status.maps[floorId].deleted = true;
|
||||
core.status.maps[floorId].canFlyTo = false;
|
||||
core.status.maps[floorId].canFlyFrom = false;
|
||||
core.status.maps[floorId].cannotViewMap = true;
|
||||
if (force) {
|
||||
core.status.maps[floorId].forceDelete = true;
|
||||
flags.__forceDelete__[floorId] = true;
|
||||
}
|
||||
deleteFlags(floorId);
|
||||
deleted = true;
|
||||
}
|
||||
if (deleted && !main.replayChecking) {
|
||||
Mota.Plugin.require('fly_r').splitArea();
|
||||
}
|
||||
}
|
||||
|
||||
export function deleteFlags(floorId: FloorIds) {
|
||||
delete flags[`jump_${floorId}`];
|
||||
delete flags[`inte_${floorId}`];
|
||||
delete flags[`loop_${floorId}`];
|
||||
delete flags[`melt_${floorId}`];
|
||||
delete flags[`night_${floorId}`];
|
||||
}
|
||||
|
||||
// 恢复楼层
|
||||
// core.plugin.removeMap.resumeMaps("MT1", "MT300") 恢复MT1~MT300之间的全部层
|
||||
// core.plugin.removeMap.resumeMaps("MT10") 只恢复MT10层
|
||||
export function resumeMaps(fromId: FloorIds, toId: FloorIds) {
|
||||
toId = toId || fromId;
|
||||
var fromIndex = core.floorIds.indexOf(fromId),
|
||||
toIndex = core.floorIds.indexOf(toId);
|
||||
if (toIndex < 0) toIndex = core.floorIds.length - 1;
|
||||
flags.__removed__ = flags.__removed__ || [];
|
||||
for (var i = fromIndex; i <= toIndex; ++i) {
|
||||
var floorId = core.floorIds[i];
|
||||
if (!core.status.maps[floorId].deleted) continue;
|
||||
if (
|
||||
core.status.maps[floorId].forceDelete ||
|
||||
flags.__forceDelete__[floorId]
|
||||
)
|
||||
continue;
|
||||
// @ts-ignore
|
||||
flags.__removed__ = flags.__removed__.filter(f => {
|
||||
return f != floorId;
|
||||
});
|
||||
// @ts-ignore
|
||||
core.status.maps[floorId] = core.loadFloor(floorId);
|
||||
}
|
||||
}
|
||||
|
||||
// 分区砍层相关
|
||||
var inAnyPartition = (floorId: FloorIds) => {
|
||||
var inPartition = false;
|
||||
(core.floorPartitions || []).forEach(floor => {
|
||||
var fromIndex = core.floorIds.indexOf(floor[0]);
|
||||
var toIndex = core.floorIds.indexOf(floor[1]!);
|
||||
var index = core.floorIds.indexOf(floorId);
|
||||
if (fromIndex < 0 || index < 0) return;
|
||||
if (toIndex < 0) toIndex = core.floorIds.length - 1;
|
||||
if (index >= fromIndex && index <= toIndex) inPartition = true;
|
||||
});
|
||||
return inPartition;
|
||||
};
|
||||
|
||||
// 分区砍层
|
||||
export function autoRemoveMaps(floorId: FloorIds) {
|
||||
if (main.mode != 'play' || !inAnyPartition(floorId)) return;
|
||||
// 根据分区信息自动砍层与恢复
|
||||
(core.floorPartitions || []).forEach(floor => {
|
||||
var fromIndex = core.floorIds.indexOf(floor[0]);
|
||||
var toIndex = core.floorIds.indexOf(floor[1]!);
|
||||
var index = core.floorIds.indexOf(floorId);
|
||||
if (fromIndex < 0 || index < 0) return;
|
||||
if (toIndex < 0) toIndex = core.floorIds.length - 1;
|
||||
if (index >= fromIndex && index <= toIndex) {
|
||||
resumeMaps(core.floorIds[fromIndex], core.floorIds[toIndex]);
|
||||
} else {
|
||||
removeMaps(core.floorIds[fromIndex], core.floorIds[toIndex]);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
import { HeroSkill } from '@/game/mechanism/misc';
|
||||
import { getSkillFromIndex, upgradeSkill } from './skillTree';
|
||||
import { canOpenShop } from './shop';
|
||||
|
||||
const replayableSettings = ['autoSkill'];
|
||||
|
||||
let cliping = false;
|
||||
let startIndex = 0;
|
||||
|
||||
export function readyClip() {
|
||||
cliping = true;
|
||||
return (startIndex = core.status.route.length - 1);
|
||||
}
|
||||
|
||||
export function clip(...replace: string[]) {
|
||||
if (!cliping) return;
|
||||
cliping = false;
|
||||
|
||||
core.status.route.splice(startIndex);
|
||||
core.status.route.push(...replace);
|
||||
}
|
||||
|
||||
export function init() {
|
||||
function tipAndWait(content: string, time: number) {
|
||||
const speed = core.status.replay.speed;
|
||||
if (main.replayChecking || speed === 24) return Promise.resolve();
|
||||
const { tip } = Mota.Plugin.require('utils_r');
|
||||
tip('info', '录像播放操作:' + content);
|
||||
return new Promise<void>(res => {
|
||||
setTimeout(res, time / speed);
|
||||
});
|
||||
}
|
||||
|
||||
// 注册修改设置的录像操作
|
||||
const settingNameMap: Record<string, string> = {
|
||||
autoSkill: '自动切换技能'
|
||||
};
|
||||
core.registerReplayAction('settings', name => {
|
||||
if (!name.startsWith('set:')) return false;
|
||||
const [, setting, value] = name.split(':');
|
||||
const v = eval(value);
|
||||
if (typeof v !== 'boolean') return false;
|
||||
if (!replayableSettings.includes(setting)) return false;
|
||||
switch (setting) {
|
||||
case 'autoSkill':
|
||||
HeroSkill.setAutoSkill(v);
|
||||
break;
|
||||
}
|
||||
const settingName = settingNameMap[setting];
|
||||
core.status.route.push(name);
|
||||
if (settingName) {
|
||||
tipAndWait(`切换设置:${settingName}`, 1000).then(() => {
|
||||
core.replay();
|
||||
});
|
||||
} else {
|
||||
core.replay();
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
core.registerReplayAction('upgradeSkill', name => {
|
||||
if (!name.startsWith('skill:')) return false;
|
||||
const skill = parseInt(name.slice(6));
|
||||
upgradeSkill(skill);
|
||||
const s = getSkillFromIndex(skill);
|
||||
const skillName = s?.title;
|
||||
core.status.route.push(name);
|
||||
tipAndWait(`升级技能:${skillName}`, 1000).then(() => {
|
||||
core.replay();
|
||||
});
|
||||
return true;
|
||||
});
|
||||
|
||||
// 商店
|
||||
let shopOpened = false;
|
||||
let openedShopId = '';
|
||||
|
||||
Mota.require('var', 'hook').on('reset', () => {
|
||||
shopOpened = false;
|
||||
openedShopId = '';
|
||||
});
|
||||
|
||||
core.registerReplayAction('openShop', name => {
|
||||
if (!name.startsWith('openShop:')) return false;
|
||||
const id = name.slice(9);
|
||||
if (!canOpenShop(id)) return false;
|
||||
if (shopOpened && openedShopId === id) return true;
|
||||
openedShopId = name.slice(9);
|
||||
shopOpened = true;
|
||||
core.status.route.push(name);
|
||||
core.replay();
|
||||
return true;
|
||||
});
|
||||
|
||||
core.registerReplayAction('buy', name => {
|
||||
if (!name.startsWith('buy:') && !name.startsWith('sell:')) return false;
|
||||
if (!shopOpened) return false;
|
||||
if (!openedShopId) return false;
|
||||
const [type, id, n] = name.split(':');
|
||||
const num = parseInt(n);
|
||||
const shop = core.status.shops[openedShopId] as ItemShopEvent;
|
||||
const item = shop.choices.find(v => v.id === id);
|
||||
if (!item) return false;
|
||||
flags.itemShop ??= {};
|
||||
flags.itemShop[openedShopId] ??= {};
|
||||
flags.itemShop[openedShopId][id] ??= 0;
|
||||
if ((num as number) > item.number - flags.itemShop[openedShopId][id]) {
|
||||
return false;
|
||||
}
|
||||
let cost = 0;
|
||||
if (type === 'buy') {
|
||||
cost = parseInt(item.money) * (num as number);
|
||||
} else {
|
||||
cost = -item.sell * (num as number);
|
||||
}
|
||||
if (cost > core.status.hero.money) return false;
|
||||
core.status.hero.money -= cost;
|
||||
flags.itemShop[openedShopId][id] += type === 'buy' ? num : -num;
|
||||
core.addItem(
|
||||
id as AllIdsOf<'items'>,
|
||||
(type === 'buy' ? num : -num) as number
|
||||
);
|
||||
const { name: itemName } = core.material.items[id as AllIdsOf<'items'>];
|
||||
core.status.route.push(name);
|
||||
tipAndWait(`购买物品:${itemName}`, 1000).then(() => {
|
||||
core.replay();
|
||||
});
|
||||
return true;
|
||||
});
|
||||
|
||||
core.registerReplayAction('closeShop', name => {
|
||||
if (name !== 'closeShop') return false;
|
||||
shopOpened = false;
|
||||
openedShopId = '';
|
||||
core.status.route.push(name);
|
||||
core.replay();
|
||||
return true;
|
||||
});
|
||||
|
||||
const skillNameMap: Record<string, string> = {
|
||||
Blade: '断灭之刃',
|
||||
Shield: '铸剑为盾'
|
||||
};
|
||||
function skillAction(skill: string) {
|
||||
let toEmit = skill;
|
||||
|
||||
// 兼容性处理
|
||||
if (skill === '1') {
|
||||
toEmit = 'Blade';
|
||||
} else if (skill === '2') {
|
||||
toEmit = 'Jump';
|
||||
} else if (skill === '3') {
|
||||
toEmit = 'Shield';
|
||||
}
|
||||
|
||||
if (toEmit === 'Jump') {
|
||||
if (
|
||||
!flags.onChase &&
|
||||
!core.status.floorId.startsWith('tower') &&
|
||||
HeroSkill.learnedSkill(HeroSkill.Jump)
|
||||
) {
|
||||
const success = Mota.Plugin.require('skill_g').jumpSkill();
|
||||
core.status.route.push(`useSkill:${toEmit}`);
|
||||
if (!success) core.replay();
|
||||
return true;
|
||||
} else {
|
||||
if (core.hasItem('pickaxe')) {
|
||||
core.useItem('pickaxe');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (HeroSkill.getAutoSkill()) {
|
||||
core.replay();
|
||||
core.updateStatusBar();
|
||||
return true;
|
||||
}
|
||||
let num = HeroSkill.Skill.None;
|
||||
switch (toEmit) {
|
||||
case 'Blade':
|
||||
num = HeroSkill.Blade;
|
||||
break;
|
||||
case 'Shield':
|
||||
num = HeroSkill.Shield;
|
||||
break;
|
||||
}
|
||||
HeroSkill.toggleSkill(num);
|
||||
}
|
||||
core.updateStatusBar();
|
||||
const name = skillNameMap[toEmit];
|
||||
core.status.route.push(`useSkill:${toEmit}`);
|
||||
if (name) {
|
||||
tipAndWait(`切换技能:${name}`, 1000).then(() => {
|
||||
core.replay();
|
||||
});
|
||||
} else {
|
||||
core.replay();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
core.registerReplayAction('useSkill', name => {
|
||||
if (!name.startsWith('useSkill:')) return false;
|
||||
const [, skill] = name.split(':');
|
||||
return skillAction(skill);
|
||||
});
|
||||
|
||||
// 兼容旧版
|
||||
core.registerReplayAction('key', name => {
|
||||
if (!name.startsWith('key:')) return false;
|
||||
const key = parseInt(name.slice(4));
|
||||
|
||||
if (key === 49) {
|
||||
return skillAction('1');
|
||||
} else if (key === 50) {
|
||||
return skillAction('2');
|
||||
} else if (key === 51) {
|
||||
return skillAction('3');
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
core.registerReplayAction('fly', action => {
|
||||
if (!action.startsWith('fly:')) return false;
|
||||
const floorId = action.slice(4) as FloorIds;
|
||||
if (
|
||||
!core.canUseItem('fly') ||
|
||||
(core.flags.flyNearStair && !core.nearStair())
|
||||
)
|
||||
return false;
|
||||
tipAndWait(`飞往:${floorId}`, 1000).then(() => {
|
||||
if (!core.flyTo(floorId, core.replay)) {
|
||||
core.control._replay_error(action);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
export function openShop(shopId: string, noRoute: boolean) {
|
||||
const shop = core.status.shops[shopId] as ItemShopEvent;
|
||||
// Step 1: 检查能否打开此商店
|
||||
if (!canOpenShop(shopId)) {
|
||||
core.drawTip('该商店尚未开启');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Step 3: 检查道具商店 or 公共事件
|
||||
if (shop.item) {
|
||||
Mota.r(() => {
|
||||
if (!core.isReplaying()) {
|
||||
Mota.require('var', 'mainUi').open('shop', {
|
||||
shopId: shopId
|
||||
});
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// 是否访问过某个快捷商店
|
||||
export function isShopVisited(id: string) {
|
||||
flags.__shops__ ??= {};
|
||||
var shops = core.getFlag<any>('__shops__');
|
||||
if (!shops[id]) shops[id] = {};
|
||||
return shops[id].visited;
|
||||
}
|
||||
|
||||
/// 当前应当显示的快捷商店列表
|
||||
export function listShopIds() {
|
||||
return Object.keys(core.status.shops).filter(id => {
|
||||
// @ts-ignore
|
||||
return isShopVisited(id) || !core.status.shops[id].mustEnable;
|
||||
});
|
||||
}
|
||||
|
||||
/// 是否能够打开某个商店
|
||||
export function canOpenShop(id: string) {
|
||||
if (isShopVisited(id)) return true;
|
||||
var shop = core.status.shops[id];
|
||||
// @ts-ignore
|
||||
if (shop.item || shop.commonEvent || shop.mustEnable) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// 启用或禁用某个快捷商店
|
||||
export function setShopVisited(id: string, visited: boolean) {
|
||||
if (!core.hasFlag('__shops__')) core.setFlag('__shops__', {});
|
||||
var shops = core.getFlag<any>('__shops__');
|
||||
if (!shops[id]) shops[id] = {};
|
||||
if (visited) shops[id].visited = true;
|
||||
else delete shops[id].visited;
|
||||
}
|
||||
|
||||
/// 能否使用快捷商店
|
||||
export function canUseQuickShop() {
|
||||
// 如果返回一个字符串,表示不能,字符串为不能使用的提示
|
||||
// 返回null代表可以使用
|
||||
|
||||
// 检查当前楼层的canUseQuickShop选项是否为false
|
||||
if (core.status.thisMap.canUseQuickShop === false)
|
||||
return '当前楼层不能使用快捷商店。';
|
||||
return null;
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
// @ts-nocheck
|
||||
|
||||
import { HeroSkill } from '@/game/mechanism/misc';
|
||||
|
||||
// 所有的主动技能效果
|
||||
var ignoreInJump = {
|
||||
event: ['X20007', 'X20001', 'X20006', 'X20014', 'X20010', 'X20007'],
|
||||
bg: [
|
||||
'X20037',
|
||||
'X20038',
|
||||
'X20039',
|
||||
'X20045',
|
||||
'X20047',
|
||||
'X20053',
|
||||
'X20054',
|
||||
'X20055',
|
||||
'X20067',
|
||||
'X20068',
|
||||
'X20075',
|
||||
'X20076'
|
||||
]
|
||||
};
|
||||
|
||||
export const jumpIgnoreFloor: Set<FloorIds> = new Set([
|
||||
'MT31',
|
||||
'snowTown',
|
||||
'MT36',
|
||||
'MT37',
|
||||
'MT38',
|
||||
'MT39',
|
||||
'MT40',
|
||||
'MT42',
|
||||
'MT43',
|
||||
'MT44',
|
||||
'MT45',
|
||||
'MT46',
|
||||
'MT47',
|
||||
'MT48',
|
||||
'MT49',
|
||||
'MT50',
|
||||
'MT57',
|
||||
'MT59',
|
||||
'MT60',
|
||||
'MT61',
|
||||
'MT71',
|
||||
'MT72',
|
||||
'MT73',
|
||||
'MT74',
|
||||
'MT75',
|
||||
'MT84',
|
||||
'MT93'
|
||||
]);
|
||||
// 跳跃
|
||||
export function jumpSkill(callback?: () => void) {
|
||||
if (core.status.floorId.startsWith('tower')) {
|
||||
callback?.();
|
||||
core.drawTip('当前无法使用该技能');
|
||||
return false;
|
||||
}
|
||||
if (jumpIgnoreFloor.has(core.status.floorId) || flags.onChase) {
|
||||
callback?.();
|
||||
core.drawTip('当前楼层无法使用该技能');
|
||||
return false;
|
||||
}
|
||||
if (!HeroSkill.learnedSkill(HeroSkill.Jump)) {
|
||||
callback?.();
|
||||
return false;
|
||||
}
|
||||
if (!flags['jump_' + core.status.floorId])
|
||||
flags['jump_' + core.status.floorId] = 0;
|
||||
if (core.status.floorId == 'MT14') {
|
||||
const loc = core.status.hero.loc;
|
||||
if (loc.x === 77 && loc.y === 5) {
|
||||
flags.MT14Jump = true;
|
||||
}
|
||||
if (flags.jump_MT14 === 2 && !flags.MT14Jump) {
|
||||
callback?.();
|
||||
core.drawTip('该地图还有一个必跳的地方,你还没有跳');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (flags['jump_' + core.status.floorId] >= 3) {
|
||||
callback?.();
|
||||
core.drawTip('当前地图使用次数已用完');
|
||||
return false;
|
||||
}
|
||||
var direction = core.status.hero.loc.direction;
|
||||
var loc = core.status.hero.loc;
|
||||
var checkLoc = {};
|
||||
switch (direction) {
|
||||
case 'up':
|
||||
checkLoc.x = loc.x;
|
||||
checkLoc.y = loc.y - 1;
|
||||
break;
|
||||
case 'right':
|
||||
checkLoc.x = loc.x + 1;
|
||||
checkLoc.y = loc.y;
|
||||
break;
|
||||
case 'down':
|
||||
checkLoc.x = loc.x;
|
||||
checkLoc.y = loc.y + 1;
|
||||
break;
|
||||
case 'left':
|
||||
checkLoc.x = loc.x - 1;
|
||||
checkLoc.y = loc.y;
|
||||
break;
|
||||
}
|
||||
// 前方是否可通行 或 是怪物
|
||||
var cls = core.getBlockCls(checkLoc.x, checkLoc.y);
|
||||
var noPass = core.noPass(checkLoc.x, checkLoc.y);
|
||||
var id = core.getBlockId(checkLoc.x, checkLoc.y) || '';
|
||||
var bgId =
|
||||
core.getBlockByNumber(core.getBgNumber(checkLoc.x, checkLoc.y)).event
|
||||
.id || '';
|
||||
// 可以通行
|
||||
if (
|
||||
!noPass ||
|
||||
cls == 'items' ||
|
||||
(id.startsWith('X') && !ignoreInJump.event.includes(id)) ||
|
||||
(bgId.startsWith('X') && !ignoreInJump.bg.includes(bgId))
|
||||
) {
|
||||
callback?.();
|
||||
core.drawTip('当前无法使用技能');
|
||||
return false;
|
||||
}
|
||||
// debugger;
|
||||
// 不是怪物且不可以通行
|
||||
if (noPass && !(cls == 'enemys' || cls == 'enemy48')) {
|
||||
var toLoc = checkNoPass(direction, checkLoc.x, checkLoc.y, true);
|
||||
if (!toLoc) {
|
||||
callback?.();
|
||||
return false;
|
||||
}
|
||||
core.autosave();
|
||||
if (flags.chapter <= 1) core.status.hero.hp -= 200 * flags.hard;
|
||||
core.updateStatusBar();
|
||||
flags['jump_' + core.status.floorId]++;
|
||||
if (core.status.hero.hp <= 0) {
|
||||
core.status.hero.hp = 0;
|
||||
core.updateStatusBar();
|
||||
core.events.lose('你跳死了');
|
||||
callback?.();
|
||||
return false;
|
||||
}
|
||||
core.playSound('015-Jump01.opus');
|
||||
core.insertAction(
|
||||
[{ type: 'jumpHero', loc: [toLoc.x, toLoc.y], time: 500 }],
|
||||
void 0,
|
||||
void 0,
|
||||
callback
|
||||
);
|
||||
return true;
|
||||
}
|
||||
// 是怪物
|
||||
if (cls == 'enemys' || cls == 'enemy48') {
|
||||
var firstNoPass = checkNoPass(direction, checkLoc.x, checkLoc.y, false);
|
||||
if (!firstNoPass) {
|
||||
callback?.();
|
||||
return false;
|
||||
}
|
||||
core.autosave();
|
||||
if (flags.chapter <= 1) core.status.hero.hp -= 200 * flags.hard;
|
||||
core.updateStatusBar();
|
||||
flags['jump_' + core.status.floorId]++;
|
||||
if (core.status.hero.hp <= 0) {
|
||||
core.status.hero.hp = 0;
|
||||
core.updateStatusBar();
|
||||
core.events.lose('你跳死了');
|
||||
callback?.();
|
||||
return false;
|
||||
}
|
||||
core.playSound('015-Jump01.opus');
|
||||
core.insertAction(
|
||||
[
|
||||
{
|
||||
type: 'jump',
|
||||
from: [checkLoc.x, checkLoc.y],
|
||||
to: [firstNoPass.x, firstNoPass.y],
|
||||
time: 500,
|
||||
keep: true
|
||||
}
|
||||
],
|
||||
void 0,
|
||||
void 0,
|
||||
callback
|
||||
);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
// 检查一条线上的不可通过
|
||||
function checkNoPass(direction, x, y, startNo) {
|
||||
if (!startNo) startNo = false;
|
||||
switch (direction) {
|
||||
case 'up':
|
||||
y--;
|
||||
break;
|
||||
case 'right':
|
||||
x++;
|
||||
break;
|
||||
case 'down':
|
||||
y++;
|
||||
break;
|
||||
case 'left':
|
||||
x--;
|
||||
break;
|
||||
}
|
||||
if (
|
||||
x > core.status.thisMap.width - 1 ||
|
||||
y > core.status.thisMap.height - 1 ||
|
||||
x < 0 ||
|
||||
y < 0
|
||||
) {
|
||||
return core.drawTip('当前无法使用技能');
|
||||
}
|
||||
var id = core.getBlockId(x, y) || '';
|
||||
if (core.getBgNumber(x, y))
|
||||
var bgId =
|
||||
core.getBlockByNumber(core.getBgNumber(x, y)).event.id || '';
|
||||
else var bgId = '';
|
||||
if (
|
||||
core.noPass(x, y) ||
|
||||
core.getBlockCls(x, y) == 'items' ||
|
||||
(id.startsWith('X') && !ignoreInJump.event.includes(id)) ||
|
||||
(bgId.startsWith('X') && !ignoreInJump.bg.includes(bgId)) ||
|
||||
core.getBlockCls(x, y) == 'animates'
|
||||
)
|
||||
return checkNoPass(direction, x, y, true);
|
||||
if (!startNo) return checkNoPass(direction, x, y, false);
|
||||
return { x: x, y: y };
|
||||
}
|
||||
}
|
||||
@@ -1,316 +0,0 @@
|
||||
import { HeroSkill } from '@/game/mechanism/misc';
|
||||
|
||||
let levels: number[] = [];
|
||||
|
||||
export type Chapter = 'chapter1' | 'chapter2';
|
||||
|
||||
export interface Skill {
|
||||
index: number;
|
||||
title: string;
|
||||
desc: string[];
|
||||
consume: (level: number) => number;
|
||||
front: [skill: number, level: number][];
|
||||
loc: LocArr;
|
||||
max: number;
|
||||
effect: (level: number) => string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {Record<Chapter, Skill[]>}
|
||||
*/
|
||||
export const skills: Record<Chapter, Skill[]> = {
|
||||
chapter1: [
|
||||
{
|
||||
index: 0,
|
||||
title: '力量',
|
||||
desc: ['力量就是根本!可以通过智慧增加力量,每级增加2点攻击。'],
|
||||
consume: level => 10 * level + 10,
|
||||
front: [],
|
||||
loc: [1, 2],
|
||||
max: 10,
|
||||
effect: level => [`攻击 + ${level * 2}`]
|
||||
},
|
||||
{
|
||||
index: 1,
|
||||
title: '致命一击',
|
||||
desc: ['爆发出全部力量攻击敌人,每级增加5点额外攻击。'],
|
||||
consume: level => 30 * level + 30,
|
||||
front: [[0, 5]],
|
||||
loc: [2, 1],
|
||||
max: 10,
|
||||
effect: level => [`额外攻击 + ${level * 5}`]
|
||||
},
|
||||
{
|
||||
index: 2,
|
||||
title: '断灭之刃',
|
||||
desc: [
|
||||
'<span style="color: gold">主动技能,快捷键1</span>,',
|
||||
'开启后会在战斗时会额外增加一定量的攻击,但同时减少一定量的防御。'
|
||||
],
|
||||
consume: level => 200 * level + 400,
|
||||
front: [[1, 5]],
|
||||
loc: [4, 1],
|
||||
max: 5,
|
||||
effect: level => [`增加${level * 10}%攻击,减少${level * 10}%防御`]
|
||||
},
|
||||
{
|
||||
index: 3,
|
||||
title: '坚韧',
|
||||
desc: ['由智慧转化出坚韧!每级增加2点防御'],
|
||||
consume: level => 10 * level + 10,
|
||||
front: [],
|
||||
loc: [1, 4],
|
||||
max: 10,
|
||||
effect: level => [`防御 + ${level * 2}`]
|
||||
},
|
||||
{
|
||||
index: 4,
|
||||
title: '回春',
|
||||
desc: ['让智慧化为治愈之泉水!每级增加1点生命回复'],
|
||||
consume: level => 20 * level + 20,
|
||||
front: [[3, 5]],
|
||||
loc: [2, 5],
|
||||
max: 25,
|
||||
effect: level => [`生命回复 + ${level}`]
|
||||
},
|
||||
{
|
||||
index: 5,
|
||||
title: '治愈之泉',
|
||||
desc: [
|
||||
'让生命变得更多一些吧!每吃50瓶血瓶就增加当前生命回复10%的生命回复'
|
||||
],
|
||||
consume: () => 1500,
|
||||
front: [[4, 25]],
|
||||
loc: [4, 5],
|
||||
max: 1,
|
||||
effect: () => [`50瓶血10%生命回复`]
|
||||
},
|
||||
{
|
||||
index: 6,
|
||||
title: '坚固之盾',
|
||||
desc: ['让护甲更加坚硬一些吧!每级增加10点防御'],
|
||||
consume: level => 50 + level * 50,
|
||||
front: [[3, 5]],
|
||||
loc: [2, 3],
|
||||
max: 10,
|
||||
effect: level => [`防御 + ${level * 10}`]
|
||||
},
|
||||
{
|
||||
index: 7,
|
||||
title: '无上之盾',
|
||||
desc: [
|
||||
'<span style="color: #dd4">第一章终极技能</span>,战斗时智慧的 1/10 会充当等量护盾。'
|
||||
],
|
||||
consume: () => 2500,
|
||||
front: [
|
||||
[6, 10],
|
||||
[5, 1],
|
||||
[2, 2]
|
||||
],
|
||||
loc: [5, 3],
|
||||
max: 1,
|
||||
effect: () => [`战斗时智慧会充当护盾`]
|
||||
}
|
||||
],
|
||||
chapter2: [
|
||||
{
|
||||
index: 8,
|
||||
title: '锋利',
|
||||
desc: ['让剑变得更加锋利!每级使攻击增加1%(buff式增加)'],
|
||||
consume: level => (level > 5 ? 50 * level ** 2 : 250 * level + 250),
|
||||
front: [],
|
||||
loc: [1, 2],
|
||||
max: 15,
|
||||
effect: level => [`攻击增加${level}%`]
|
||||
},
|
||||
{
|
||||
index: 9,
|
||||
title: '坚硬',
|
||||
desc: ['让盾牌变得更加坚固!每级使防御增加1%(buff式增加)'],
|
||||
consume: level => (level > 5 ? 50 * level ** 2 : 250 * level + 250),
|
||||
front: [],
|
||||
loc: [1, 4],
|
||||
max: 15,
|
||||
effect: level => [`防御增加${level}%`]
|
||||
},
|
||||
{
|
||||
index: 10,
|
||||
title: '铸剑为盾',
|
||||
desc: [
|
||||
'<span style="color: gold">主动技能,快捷键3</span>,',
|
||||
'减少一定的攻击,增加一定的防御'
|
||||
],
|
||||
consume: level => 1000 * level ** 2 + 1000,
|
||||
front: [[9, 5]],
|
||||
loc: [2, 5],
|
||||
max: 5,
|
||||
effect: level => [
|
||||
`增加${level * 10}%的防御,减少${level * 10}%的攻击`
|
||||
]
|
||||
},
|
||||
{
|
||||
index: 11,
|
||||
title: '魔法盾',
|
||||
desc: ['为主角提供魔法防御,每级增加100点魔法防御'],
|
||||
consume: level => 5000 * level + 5000,
|
||||
front: [
|
||||
[8, 10],
|
||||
[12, 10]
|
||||
],
|
||||
loc: [4, 1],
|
||||
max: 10,
|
||||
effect: level => [`魔法防御 + ${level * 100}`]
|
||||
},
|
||||
{
|
||||
index: 12,
|
||||
title: '聪慧',
|
||||
desc: ['使主角变得更加聪明,每级使绿宝石增加的智慧点上升5%'],
|
||||
consume: level =>
|
||||
level > 5 ? 100 * level ** 2 : 250 * level + 1250,
|
||||
front: [
|
||||
[8, 10],
|
||||
[9, 10]
|
||||
],
|
||||
loc: [3, 3],
|
||||
max: 20,
|
||||
effect: level => [`增加${level * 5}%绿宝石效果`]
|
||||
},
|
||||
{
|
||||
index: 13,
|
||||
title: '治愈',
|
||||
desc: ['使主角能够更好地回复生命,每级使血瓶的加血量增加2%'],
|
||||
consume: level =>
|
||||
level > 5 ? 100 * level ** 2 : 250 * level + 1250,
|
||||
front: [[10, 3]],
|
||||
loc: [4, 5],
|
||||
max: 10,
|
||||
effect: level => [`增加${level * 2}%的血瓶回血量`]
|
||||
},
|
||||
{
|
||||
index: 14,
|
||||
title: '胜利之号',
|
||||
desc: [
|
||||
'<span style="color: #dd4">第二章终极技能</span>,',
|
||||
'勇士攻防增加10%(buff式增加)'
|
||||
],
|
||||
consume: () => 25000,
|
||||
front: [
|
||||
[13, 10],
|
||||
[12, 10],
|
||||
[11, 3]
|
||||
],
|
||||
loc: [5, 3],
|
||||
max: 1,
|
||||
effect: () => [`攻防增加10%`]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
export function resetSkillLevel() {
|
||||
levels = [];
|
||||
}
|
||||
|
||||
export function getSkillFromIndex(index: number) {
|
||||
for (const [, skill] of Object.entries(skills)) {
|
||||
const s = skill.find(v => v.index === index);
|
||||
if (s) return s;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取技能等级
|
||||
*/
|
||||
export function getSkillLevel(skill: number) {
|
||||
levels[skill] ??= 0;
|
||||
return levels[skill];
|
||||
}
|
||||
|
||||
export function getSkillConsume(skill: number) {
|
||||
const s = getSkillFromIndex(skill);
|
||||
if (!s) return 0;
|
||||
return s.consume(getSkillLevel(skill));
|
||||
}
|
||||
|
||||
export function openTree() {
|
||||
if (main.replayChecking) return;
|
||||
Mota.require('var', 'mainUi').open('skillTree');
|
||||
}
|
||||
|
||||
/**
|
||||
* 能否升级某个技能
|
||||
*/
|
||||
export function canUpgrade(skill: number) {
|
||||
const consume = getSkillConsume(skill);
|
||||
if (consume > core.status.hero.mdef) return false;
|
||||
const level = getSkillLevel(skill);
|
||||
const s = getSkillFromIndex(skill);
|
||||
if (level === s?.max) return false;
|
||||
const front = s?.front ?? [];
|
||||
for (const [skill, level] of front) {
|
||||
if (getSkillLevel(skill) < level) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 实际升级效果
|
||||
* @param {number} skill
|
||||
*/
|
||||
export function upgradeSkill(skill: number) {
|
||||
if (!canUpgrade(skill)) return false;
|
||||
switch (skill) {
|
||||
case 0: // 力量 +2攻击
|
||||
core.status.hero.atk += 2;
|
||||
break;
|
||||
case 1: // 致命一击 +5额外攻击
|
||||
core.status.hero.mana += 5;
|
||||
break;
|
||||
case 2: // 断灭之刃
|
||||
HeroSkill.learnSkill(HeroSkill.Blade);
|
||||
break;
|
||||
case 3: // 坚韧 +2防御
|
||||
core.status.hero.def += 2;
|
||||
break;
|
||||
case 4: // 回春 +1回复
|
||||
core.status.hero.hpmax += 1;
|
||||
break;
|
||||
case 5: // 治愈之泉
|
||||
core.setFlag('spring', true);
|
||||
break;
|
||||
case 6: // 坚固之盾 +10防御
|
||||
core.status.hero.def += 10;
|
||||
break;
|
||||
case 7: // 无上之盾
|
||||
core.setFlag('superSheild', true);
|
||||
break;
|
||||
case 8: // 锋利 +1%攻击
|
||||
core.addBuff('atk', 0.01);
|
||||
break;
|
||||
case 9: // 锋利 +1%防御
|
||||
core.addBuff('def', 0.01);
|
||||
break;
|
||||
case 10: // 铸剑为盾
|
||||
HeroSkill.learnSkill(HeroSkill.Shield);
|
||||
break;
|
||||
case 11: // 魔法盾
|
||||
core.status.hero.magicDef += 100;
|
||||
break;
|
||||
case 14:
|
||||
core.addBuff('atk', 0.1);
|
||||
core.addBuff('def', 0.1);
|
||||
break;
|
||||
}
|
||||
const consume = getSkillConsume(skill);
|
||||
core.status.hero.mdef -= consume;
|
||||
levels[skill]++;
|
||||
core.updateStatusBar();
|
||||
return true;
|
||||
}
|
||||
|
||||
export function saveSkillTree() {
|
||||
return levels.slice();
|
||||
}
|
||||
|
||||
export function loadSkillTree(data: number[]) {
|
||||
levels = data ?? [];
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
// @ts-nocheck
|
||||
|
||||
export function init() {
|
||||
if (main.mode === 'editor') return;
|
||||
const { mainUi, fixedUi, mainSetting } = Mota.requireAll('var');
|
||||
|
||||
ui.prototype.drawBook = function () {
|
||||
if (!core.isReplaying()) return mainUi.open('book');
|
||||
};
|
||||
|
||||
ui.prototype._drawToolbox = function () {
|
||||
if (!core.isReplaying()) return mainUi.open('toolbox');
|
||||
};
|
||||
|
||||
ui.prototype._drawEquipbox = function () {
|
||||
if (!core.isReplaying()) return mainUi.open('equipbox');
|
||||
};
|
||||
|
||||
ui.prototype.drawFly = function () {
|
||||
if (!core.isReplaying()) return mainUi.open('fly');
|
||||
};
|
||||
|
||||
control.prototype.updateStatusBar_update = function () {
|
||||
core.control.updateNextFrame = false;
|
||||
if (!core.isPlaying() || core.hasFlag('__statistics__')) return;
|
||||
core.control.controldata.updateStatusBar();
|
||||
if (!core.control.noAutoEvents) core.checkAutoEvents();
|
||||
core.control._updateStatusBar_setToolboxIcon();
|
||||
core.control.noAutoEvents = true;
|
||||
Mota.require('var', 'hook').emit('statusBarUpdate');
|
||||
};
|
||||
|
||||
control.prototype.showStatusBar = function () {
|
||||
if (main.mode == 'editor') return;
|
||||
core.removeFlag('hideStatusBar');
|
||||
if (mainSetting.getValue('ui.tips')) {
|
||||
if (!fixedUi.hasName('tips')) {
|
||||
fixedUi.open('tips');
|
||||
}
|
||||
}
|
||||
core.updateStatusBar();
|
||||
};
|
||||
|
||||
control.prototype.hideStatusBar = function (showToolbox) {
|
||||
if (main.mode == 'editor') return;
|
||||
|
||||
// 如果原本就是隐藏的,则先显示
|
||||
if (!core.domStyle.showStatusBar) this.showStatusBar();
|
||||
if (core.isReplaying()) showToolbox = true;
|
||||
fixedUi.closeByName('tips');
|
||||
|
||||
core.setFlag('hideStatusBar', true);
|
||||
core.setFlag('showToolbox', showToolbox || null);
|
||||
core.updateStatusBar();
|
||||
};
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
/**
|
||||
* 滑动数组
|
||||
* @param arr
|
||||
* @param delta
|
||||
*/
|
||||
export function slide<T>(arr: T[], delta: number): T[] {
|
||||
if (delta === 0) return arr;
|
||||
delta %= arr.length;
|
||||
if (delta > 0) {
|
||||
arr.unshift(...arr.splice(arr.length - delta, delta));
|
||||
return arr;
|
||||
}
|
||||
if (delta < 0) {
|
||||
arr.push(...arr.splice(0, -delta));
|
||||
return arr;
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
const backDirMap: Record<Dir2, Dir2> = {
|
||||
up: 'down',
|
||||
down: 'up',
|
||||
left: 'right',
|
||||
right: 'left',
|
||||
leftup: 'rightdown',
|
||||
rightup: 'leftdown',
|
||||
leftdown: 'rightup',
|
||||
rightdown: 'leftup'
|
||||
};
|
||||
|
||||
export function backDir(dir: Dir): Dir;
|
||||
export function backDir(dir: Dir2): Dir2;
|
||||
export function backDir(dir: Dir2): Dir2 {
|
||||
return backDirMap[dir];
|
||||
}
|
||||
|
||||
export function has<T>(v: T): v is NonNullable<T> {
|
||||
return v !== null && v !== void 0;
|
||||
}
|
||||
|
||||
export function maxGameScale(n: number = 0) {
|
||||
const index = core.domStyle.availableScale.indexOf(core.domStyle.scale);
|
||||
core.control.setDisplayScale(
|
||||
core.domStyle.availableScale.length - 1 - index - n
|
||||
);
|
||||
if (!core.isPlaying() && core.flags.enableHDCanvas) {
|
||||
// @ts-ignore
|
||||
core.domStyle.ratio = Math.max(
|
||||
window.devicePixelRatio || 1,
|
||||
core.domStyle.scale
|
||||
);
|
||||
core.resize();
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureArray<T>(arr: T): T extends any[] ? T : T[] {
|
||||
// @ts-ignore
|
||||
return arr instanceof Array ? arr : [arr];
|
||||
}
|
||||
|
||||
export function ofDir(x: number, y: number, dir: Dir2): LocArr {
|
||||
const { x: dx, y: dy } = core.utils.scan2[dir];
|
||||
return [x + dx, y + dy];
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算曼哈顿距离
|
||||
*/
|
||||
export function manhattan(x1: number, y1: number, x2: number, y2: number) {
|
||||
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查一个点是否在当前超大地图 v2 优化范围内
|
||||
*/
|
||||
export function checkV2(x?: number, y?: number) {
|
||||
return (
|
||||
has(x) &&
|
||||
has(y) &&
|
||||
!(
|
||||
core.bigmap.v2 &&
|
||||
(x < core.bigmap.posX - core.bigmap.extend ||
|
||||
x > core.bigmap.posX + core._WIDTH_ + core.bigmap.extend ||
|
||||
y < core.bigmap.posY - core.bigmap.extend ||
|
||||
y > core.bigmap.posY + core._HEIGHT_ + core.bigmap.extend)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function formatDamage(damage: number): DamageString {
|
||||
let dam = '';
|
||||
let color = '';
|
||||
if (!Number.isFinite(damage)) {
|
||||
dam = '???';
|
||||
color = '#f22';
|
||||
} else {
|
||||
dam = core.formatBigNumber(damage, true);
|
||||
if (damage <= 0) color = '#1f1';
|
||||
else if (damage < core.status.hero.hp / 3) color = '#fff';
|
||||
else if (damage < (core.status.hero.hp * 2) / 3) color = '#ff0';
|
||||
else if (damage < core.status.hero.hp) color = '#f93';
|
||||
else color = '#f22';
|
||||
}
|
||||
|
||||
return { damage: dam, color: color as Color };
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一个数组的数值是否全部相等
|
||||
* @param arr 要判断的数组
|
||||
*/
|
||||
export function equal(arr: number[]): boolean;
|
||||
/**
|
||||
* 判断一个数组的元素的某个属性的数值是否全部相等
|
||||
* @param arr 要判断的数组
|
||||
* @param key 要判断的属性名
|
||||
*/
|
||||
export function equal<T>(arr: T[], key: keyof T): boolean;
|
||||
export function equal(arr: any, key?: any) {
|
||||
if (has(key)) {
|
||||
for (let i = 1; i < arr.length; i++) {
|
||||
if (arr[i][key] !== arr[0][key]) return false;
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
for (let i = 1; i < arr.length; i++) {
|
||||
if (arr[i] !== arr[0]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个数组的数值的最大值和最小值
|
||||
* @param arr 要获得的数组
|
||||
*/
|
||||
export function boundary(arr: number[]): [number, number];
|
||||
/**
|
||||
* 获得一个数组的元素的某个属性的数值的最大值和最小值
|
||||
* @param arr 要获得的数组
|
||||
* @param key 要获得的属性名
|
||||
*/
|
||||
export function boundary<T>(arr: T[], key: keyof T): [number, number];
|
||||
export function boundary(arr: any, key?: any) {
|
||||
if (has(key)) {
|
||||
let min = arr[0][key];
|
||||
let max = arr[0][key];
|
||||
for (let i = 1; i < arr.length; i++) {
|
||||
const ele = arr[i][key];
|
||||
if (ele < min) min = ele;
|
||||
if (ele > max) max = ele;
|
||||
}
|
||||
return [min, max];
|
||||
} else {
|
||||
let min = arr[0];
|
||||
let max = arr[0];
|
||||
for (let i = 1; i < arr.length; i++) {
|
||||
const ele = arr[i];
|
||||
if (ele < min) min = ele;
|
||||
if (ele > max) max = ele;
|
||||
}
|
||||
return [min, max];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取两个坐标的相对方向
|
||||
* @param from 初始坐标
|
||||
* @param to 指向坐标
|
||||
*/
|
||||
export function findDir(from: Loc, to: Loc): Dir2 | 'none' {
|
||||
const dx = to.x - from.x;
|
||||
const dy = to.y - from.y;
|
||||
return (
|
||||
(Object.entries(core.utils.scan2).find(v => {
|
||||
v[1].x === dx && v[1].y === dy;
|
||||
})?.[0] as Dir2) ?? 'none'
|
||||
);
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import * as chase from './chase';
|
||||
import * as gameCanvas from './fx/gameCanvas';
|
||||
import * as boss from './boss';
|
||||
import './loopMap';
|
||||
|
||||
Mota.Plugin.register('chase_r', chase);
|
||||
Mota.Plugin.register('gameCanvas_r', gameCanvas);
|
||||
Mota.Plugin.register('chase_r', chase);
|
||||
Mota.Plugin.register('boss_r', boss);
|
||||
Mota.Plugin.register('utils_r', utils);
|
||||
@@ -1,105 +0,0 @@
|
||||
import {
|
||||
Container,
|
||||
FloorDamageExtends,
|
||||
LayerGroupFloorBinder,
|
||||
FloorLayer,
|
||||
LayerGroup,
|
||||
FloorViewport,
|
||||
MotaRenderer
|
||||
} from '@motajs/render';
|
||||
import { FloorItemDetail } from '@/plugin/fx/itemDetail';
|
||||
|
||||
const loopMaps = Mota.require('module', 'Mechanism').MiscData.loopMaps;
|
||||
|
||||
let loopLayer: LayerGroup;
|
||||
let show: boolean = false;
|
||||
/** 循环式地图中,更新视角的委托ticker */
|
||||
let delegation: number = -1;
|
||||
|
||||
const hook = Mota.require('var', 'hook');
|
||||
hook.on('changingFloor', (floorId, heroLoc) => {
|
||||
enableLoopMapElement(floorId);
|
||||
});
|
||||
|
||||
function createLayer() {
|
||||
const group = new LayerGroup();
|
||||
['bg', 'bg2', 'event', 'fg', 'fg2'].forEach(v => {
|
||||
group.addLayer(v as FloorLayer);
|
||||
});
|
||||
|
||||
const damage = new FloorDamageExtends();
|
||||
const detail = new FloorItemDetail();
|
||||
group.id = 'layer-loop';
|
||||
group.extends(damage);
|
||||
group.extends(detail);
|
||||
|
||||
loopLayer = group;
|
||||
group.setZIndex(20);
|
||||
}
|
||||
|
||||
function enableLoopMapElement(floorId: FloorIds) {
|
||||
if (!loopMaps.has(floorId)) {
|
||||
disableLoopMapElement();
|
||||
return;
|
||||
}
|
||||
if (!loopLayer) createLayer();
|
||||
const render = MotaRenderer.get('render-main');
|
||||
const draw = render?.getElementById('map-draw') as Container;
|
||||
const group = render?.getElementById('layer-main') as LayerGroup;
|
||||
if (!draw || !group) return;
|
||||
const ex = loopLayer.getExtends('floor-binder') as LayerGroupFloorBinder;
|
||||
const viewport = group.getExtends('viewport') as FloorViewport;
|
||||
if (!ex || !viewport) return;
|
||||
ex.bindFloor(floorId);
|
||||
|
||||
draw.appendChild(loopLayer);
|
||||
show = true;
|
||||
|
||||
const floor = core.status.maps[floorId];
|
||||
viewport.setAutoBound(false);
|
||||
const transform = group.camera;
|
||||
const width = floor.width;
|
||||
const testPos = width * loopLayer.cellSize;
|
||||
|
||||
loopLayer.removeTicker(delegation);
|
||||
delegation = loopLayer.delegateTicker(() => {
|
||||
const [x1] = transform.transformed(0, 0);
|
||||
const camera = loopLayer.camera;
|
||||
if (x1 > 0) {
|
||||
// 这个是计算循环地图应该显示在哪
|
||||
const [, y2] = transform.transformed(x1 - testPos, 0);
|
||||
camera.reset();
|
||||
camera.translate(core._PX_ - testPos, y2);
|
||||
loopLayer.pos(transform.x - core._PX_, 0);
|
||||
loopLayer.show();
|
||||
loopLayer.update(loopLayer);
|
||||
} else {
|
||||
const [x2, y2] = transform.transformed(testPos, 0);
|
||||
if (x2 < core._PX_) {
|
||||
// 这个不用做其他运算,可以直接显示
|
||||
camera.reset();
|
||||
camera.translate(0, y2);
|
||||
loopLayer.pos(x2, 0);
|
||||
loopLayer.show();
|
||||
loopLayer.update(loopLayer);
|
||||
} else {
|
||||
loopLayer.hide();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function disableLoopMapElement() {
|
||||
if (!show) return;
|
||||
show = false;
|
||||
loopLayer.remove();
|
||||
|
||||
const render = MotaRenderer.get('render-main');
|
||||
const group = render?.getElementById('layer-main') as LayerGroup;
|
||||
if (!group) return;
|
||||
const viewport = group.getExtends('viewport') as FloorViewport;
|
||||
if (!viewport) return;
|
||||
|
||||
viewport.setAutoBound(true);
|
||||
loopLayer.removeTicker(delegation);
|
||||
}
|
||||
Reference in new issue
Block a user