refactor(04-11): 渲染端结构性移植——通用渲染资产下沉 @user/client-base(D-58..D-68)

- MOVE:39 个文件由 client-modules/src/render/ 移入 client-base/src/{components,elements,map,layout}/,删除原件
- D-58:新建 client-base/src/shared/(10 常量纯摘取)+ 被移 map 文件 shared 说明符改指 4 处
- D-63:client-base/src/index.ts 新增 5 条桶导出;14 个实现层消费者改指 @user/client-base
- D-66:client-base/package.json 新增 5 条 workspace:* 依赖 + 根 pnpm i(lockfile importer 同步)
- D-59 / D-60 / D-68:10 处架构耦合以带原因 // @ts-expect-error 暂记,不反向引用、不解耦
- D-62:命名一律不变;D-64 ?raw 不处理;D-65 legacy 一律不管
This commit is contained in:
AncTe committed 2026-09-24 17:14:43 +08:00
1 parent bfc69b20b5
commit 0b93426d47
60 files changed
+355 -22

No files matched your search

@@ -1,797 +0,0 @@
import { ElementLocator, Font } from '@motajs/render';
import { computed, defineComponent, reactive, ref } from 'vue';
import { Background, Selection } from './misc';
import { TextContent, TextContentProps } from './textbox';
import { TextAlign } from './textboxTyper';
import { Page, PageExpose } from './page';
import { GameUI, IUIMountable, SetupComponentOptions } from '@motajs/system';
import { useKey } from '../use';
import { sleep } from 'mutate-animate';
import { DefaultProps } from '@motajs/render-vue';
export interface ConfirmBoxProps extends DefaultProps, TextContentProps {
/** 确认框的提示文本内容 */
text: string;
/** 确认框对话框的宽度 */
width: number;
/** 确认框对话框的位置 */
loc: ElementLocator;
/** 确认/取消按钮的字体样式 */
selFont?: Font;
/** 确认/取消按钮的文本颜色 */
selFill?: CanvasStyle;
/** 对话框内部所有元素的内边距 */
pad?: number;
/** 确认按钮的显示文本,默认为"确认" */
yesText?: string;
/** 取消按钮的显示文本,默认为"取消" */
noText?: string;
/** 窗口皮肤图片ID,用于对话框背景绘制 */
winskin?: ImageIds;
/** 是否默认选中确认按钮 */
defaultYes?: boolean;
/** 对话框背景颜色,当未设置 winskin 时生效 */
color?: CanvasStyle;
/** 对话框边框颜色,当未设置 winskin 时生效 */
border?: CanvasStyle;
/** 按键作用域,如果需要同作用域按键,那么需要传入 */
scope?: symbol;
}
export type ConfirmBoxEmits = {
yes: () => void;
no: () => void;
};
const confirmBoxProps = {
props: [
'text',
'width',
'loc',
'selFont',
'selFill',
'pad',
'yesText',
'noText',
'winskin',
'defaultYes',
'color',
'border',
'scope'
],
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 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 ?? 24);
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 = (width: number, height: number) => {
yesSize.value = [width, height];
};
const setNo = (width: number, height: number) => {
noSize.value = [width, height];
};
const [key] = useKey(false, props.scope);
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 ?? '#333'}
border={props.border}
zIndex={0}
/>
<TextContent
{...attrs}
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)}
onResize={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)}
onResize={setNo}
/>
</container>
);
}, confirmBoxProps);
export type ChoiceKey = string | number;
export type ChoiceItem<T extends ChoiceKey = ChoiceKey> = [
key: T,
text: string
];
export interface ChoicesProps extends DefaultProps, TextContentProps {
/** 选项数组 */
choices: ChoiceItem[];
/** 选择框对话框的位置 */
loc: ElementLocator;
/** 选择框对话框的宽度 */
width: number;
/** 选择框的最大高度,超过时将分页显示 */
maxHeight?: number;
/** 选择框的提示文本内容 */
text?: string;
/** 选择框的标题文本 */
title?: string;
/** 窗口皮肤图片ID,用于对话框背景绘制 */
winskin?: ImageIds;
/** 对话框背景颜色,当未设置 winskin 时生效 */
color?: CanvasStyle;
/** 对话框边框颜色,当未设置 winskin 时生效 */
border?: CanvasStyle;
/** 选项文本的字体样式 */
selFont?: Font;
/** 选项文本的颜色 */
selFill?: CanvasStyle;
/** 标题文本的字体样式 */
titleFont?: Font;
/** 标题文本的颜色 */
titleFill?: CanvasStyle;
/** 对话框内部所有元素的内边距 */
pad?: number;
/** 选项之间的垂直间隔 */
interval?: number;
/** 默认选中的选项索引 */
selected?: number;
/** 按键作用域,如果需要同作用域按键,那么需要传入,例如系统设置 UI */
scope?: symbol;
}
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',
'selected',
'scope'
],
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(props.selected ?? 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 = (_: 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(false, props.scope);
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', () => {
const page = pageCom.value?.now() ?? 0;
if (selected.value === choiceCountPerPage.value - 1) {
if (page < pages.value - 1) {
pageCom.value?.movePage(1);
selected.value = 0;
}
} else {
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() ?? 0;
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 ?? '#333'}
border={props.border}
/>
<text
hidden={!hasTitle.value}
loc={titleLoc.value}
text={props.title}
font={props.titleFont ?? new Font(void 0, 18)}
fillStyle={props.titleFill ?? 'gold'}
zIndex={5}
onResize={updateTitleHeight}
/>
<TextContent
{...attrs}
hidden={!hasText.value}
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}
fillStyle={props.selFill}
onClick={() => emit('choose', v[0])}
onResize={(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<T>[],
loc: ElementLocator,
width: number,
props?: Partial<ChoicesProps>
): Promise<T> {
return new Promise<T>(res => {
const instance = controller.open(
ChoicesUI,
{
...(props ?? {}),
choices,
loc,
width,
onChoose: key => {
controller.close(instance);
res(key as T);
}
},
true
);
});
}
function getChoiceRoute(defaults: number) {
const route = core.status.replay.toReplay[0];
if (!route.startsWith('choices:')) {
return defaults;
} else {
return Number(route.slice(8));
}
}
/**
* 弹出一个确认框,然后将确认结果返回,与 getConfirm 不同的是内置录像支持,如果这个选择框需要进录像,
* 需要使用此方法。例如给玩家弹出一个确认框,并获取玩家是否确认:
* ```ts
* const confirm = await routedConfirm(
* // 在哪个 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 async function routedConfirm(
controller: IUIMountable,
text: string,
loc: ElementLocator,
width: number,
props?: Partial<ConfirmBoxProps>
) {
if (core.isReplaying()) {
const confirm = getChoiceRoute(1) === 0;
const timeout = core.control.__replay_getTimeout();
core.status.route.push(`choices:${confirm ? 0 : 1}`);
core.status.replay.toReplay.shift();
if (timeout === 0) return confirm;
const instance = controller.open(ConfirmBoxUI, {
...(props ?? {}),
text,
loc,
width,
defaultYes: confirm
});
await sleep(core.control.__replay_getTimeout());
controller.close(instance);
return confirm;
} else {
const confirm = await getConfirm(controller, text, loc, width, props);
core.status.route.push(`choices:${confirm ? 0 : 1}`);
return confirm;
}
}
/**
* 弹出一个选择框,然后将选择结果返回,与 getChoice 不同的是内置录像支持,如果这个选择框需要进录像,
* 需要使用此方法。例如给玩家弹出一个选择框,并获取玩家选择了哪个:
* ```ts
* const choice = await routedChoice(
* // 在哪个 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 async function routedChoices<T extends ChoiceKey>(
controller: IUIMountable,
choices: ChoiceItem<T>[],
loc: ElementLocator,
width: number,
props?: Partial<ChoicesProps>
): Promise<T> {
if (core.isReplaying()) {
const selected = getChoiceRoute(0);
const timeout = core.control.__replay_getTimeout();
core.status.route.push(`choices:${selected}`);
core.status.replay.toReplay.shift();
if (timeout === 0) return choices[selected][0];
const instance = controller.open(ChoicesUI, {
...(props ?? {}),
choices,
loc,
width,
selected
});
await sleep(core.control.__replay_getTimeout());
controller.close(instance);
return choices[selected][0];
} else {
const choice = await getChoice(controller, choices, loc, width, props);
const index = choices.findIndex(v => v[0] === choice);
core.status.route.push(`choices:${index}`);
return choice;
}
}
/** @see {@link ConfirmBox} */
export const ConfirmBoxUI = new GameUI('confirm-box', ConfirmBox);
/** @see {@link Choices} */
export const ChoicesUI = new GameUI('choices', Choices);
@@ -1,233 +0,0 @@
import { DefaultProps } from '@motajs/render-vue';
import { SetupComponentOptions } from '@motajs/system';
import { clamp, isNil } from 'lodash-es';
import { computed, defineComponent, onMounted, ref, watch } from 'vue';
import { Scroll, ScrollExpose } from './scroll';
import { MotaOffscreenCanvas2D, Font } from '@motajs/render';
import {
HALF_STATUS_WIDTH,
STATUS_BAR_HEIGHT,
STATUS_BAR_WIDTH
} from '../../shared';
const SCROLL_HEIGHT = STATUS_BAR_HEIGHT - 280;
const HALF_HEIGHT = SCROLL_HEIGHT / 2;
export interface FloorSelectorProps extends DefaultProps {
floors: FloorIds[];
now?: number;
}
export type FloorSelectorEmits = {
/**
* 点击关闭按钮时触发
*/
close: () => void;
/**
* 当选中的楼层改变时触发
* @param floor 楼层索引
* @param floorId 楼层 id
*/
update: (floor: number, floorId: FloorIds) => void;
'update:now': (value: number) => void;
};
const floorSelectorProps = {
props: ['floors', 'now'],
emits: ['close', 'update', 'update:now']
} satisfies SetupComponentOptions<
FloorSelectorProps,
FloorSelectorEmits,
keyof FloorSelectorEmits
>;
export const FloorSelector = defineComponent<
FloorSelectorProps,
FloorSelectorEmits,
keyof FloorSelectorEmits
>((props, { emit }) => {
const listFont = new Font(Font.defaultFamily, 12);
/** 当前选中楼层,不反向 */
const now = ref(props.now ?? 0);
/** 当前鼠标选中楼层,反向 */
const selList = ref(0);
const scrollRef = ref<ScrollExpose>();
const floors = computed(() => props.floors.toReversed());
const floorId = computed(() => props.floors[now.value]);
const floorName = computed(() => core.floors[floorId.value].title);
watch(
() => props.now,
value => {
if (!isNil(value)) {
changeTo(value);
}
}
);
let gradient: CanvasGradient | null = null;
const getGradient = (ctx: CanvasRenderingContext2D) => {
if (gradient) return gradient;
gradient = ctx.createLinearGradient(0, 0, 0, SCROLL_HEIGHT);
gradient.addColorStop(0, 'rgba(255,255,255,0)');
gradient.addColorStop(0.2, 'rgba(255,255,255,1)');
gradient.addColorStop(0.8, 'rgba(255,255,255,1)');
gradient.addColorStop(1, 'rgba(255,255,255,0)');
return gradient;
};
const renderMask = (canvas: MotaOffscreenCanvas2D) => {
const { ctx } = canvas;
const gradient = getGradient(ctx);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 144, 200);
};
const changeTo = (index: number, time: number = 500) => {
// 取反是为了符合 2.x 的操作习惯
const res = clamp(index, 0, floors.value.length - 1);
const reversed = floors.value.length - res - 1;
now.value = res;
selList.value = reversed;
const y = reversed * 24;
scrollRef.value?.scrollTo(y, time);
emit('update', now.value, floorId.value);
emit('update:now', now.value);
};
const changeFloor = (delta: number) => {
changeTo(now.value + delta);
};
const enterList = (index: number) => {
selList.value = index;
};
const close = () => {
emit('close');
};
onMounted(() => {
changeTo(now.value, 0);
});
return () => (
<container>
<text
text={floorName.value}
loc={[HALF_STATUS_WIDTH, 24]}
anc={[0.5, 0.5]}
/>
<g-line line={[48, 40, STATUS_BAR_WIDTH - 48, 40]} lineWidth={1} />
<g-line
line={[
48,
STATUS_BAR_HEIGHT - 40,
STATUS_BAR_WIDTH - 48,
STATUS_BAR_HEIGHT - 40
]}
lineWidth={1}
/>
<text
text="退出"
loc={[90, STATUS_BAR_HEIGHT - 24]}
anc={[0.5, 0.5]}
cursor="pointer"
onClick={close}
/>
<text
text="「 上移十层 」"
loc={[90, 70]}
anc={[0.5, 0.5]}
cursor="pointer"
onClick={() => changeFloor(10)}
/>
<text
text="「 上移一层 」"
loc={[90, 110]}
anc={[0.5, 0.5]}
cursor="pointer"
onClick={() => changeFloor(1)}
/>
<text
text="「 下移一层 」"
loc={[90, STATUS_BAR_HEIGHT - 110]}
anc={[0.5, 0.5]}
cursor="pointer"
onClick={() => changeFloor(-1)}
/>
<text
text="「 下移十层 」"
loc={[90, STATUS_BAR_HEIGHT - 70]}
anc={[0.5, 0.5]}
cursor="pointer"
onClick={() => changeFloor(-10)}
/>
<container loc={[0, 140, 144, SCROLL_HEIGHT]}>
<Scroll
ref={scrollRef}
loc={[0, 0, 144, SCROLL_HEIGHT]}
noscroll
zIndex={10}
padEnd={HALF_HEIGHT - 12}
>
{floors.value.map((v, i, a) => {
const floor = core.floors[v];
const reversed = a.length - i - 1;
const nowFloor = a.length - now.value - 1;
const highlight = nowFloor === i || selList.value === i;
const color = highlight ? '#fff' : '#aaa';
const fill = highlight ? '#fff' : '#000';
return (
<container
nocache
loc={[0, i * 24 + HALF_HEIGHT - 12, 144, 24]}
key={v}
>
<text
cursor="pointer"
text={floor.title}
loc={[114, 12]}
anc={[1, 0.5]}
font={listFont}
fillStyle={color}
onEnter={() => enterList(i)}
onLeave={() => enterList(nowFloor)}
onClick={() => changeTo(reversed)}
/>
<g-circle
stroke
fill
lineWidth={1}
circle={[130, 12, 3]}
strokeStyle={color}
fillStyle={nowFloor === i ? fill : '#000'}
/>
</container>
);
})}
</Scroll>
<g-line
line={[130, 0, 130, SCROLL_HEIGHT]}
zIndex={5}
lineWidth={1}
strokeStyle="#aaa"
/>
<custom
zIndex={20}
loc={[0, 0, 144, SCROLL_HEIGHT]}
nocache
noevent
render={renderMask}
composite="destination-in"
/>
</container>
</container>
);
}, floorSelectorProps);
@@ -1,450 +0,0 @@
import { ElementLocator } from '@motajs/render';
import { DefaultProps, GraphicPropsBase } from '@motajs/render-vue';
import { SetupComponentOptions } from '@motajs/system';
import {
computed,
defineComponent,
DefineSetupFnComponent,
onMounted,
Ref,
shallowRef,
watch
} from 'vue';
export interface IconsProps extends DefaultProps<GraphicPropsBase> {
loc: ElementLocator;
}
const iconsProps = {
props: ['loc']
} satisfies SetupComponentOptions<IconsProps>;
type IconLoc = [
x: number,
y: number,
w: number,
h: number,
cx: number,
cy: number
];
type IconPad = [left: number, right: number, top: number, bottom: number];
type PathGenerator = (width: number, height: number) => Path2D;
type PadFn = (divisor: number) => IconPad;
/**
* @param loc 图标位置信息
* @param pad 计算图标外围填充
*/
type PathFn = (loc: IconLoc, pad: PadFn) => Path2D;
/**
* 适配填充
* @param x 左上角横坐标
* @param y 左上角纵坐标
* @param width 矩形宽度
* @param height 矩形高度
* @param divisor 填充除数,例如左边缘会变成 `x + width / divisor`
*/
function pad(
x: number,
y: number,
width: number,
height: number,
divisor: number
): IconPad {
return [
x + width / divisor, // left
x + width - width / divisor, // right
y + height / divisor, // top
y + height - height / divisor // bottom
];
}
/**
* 适配图标路径生成
* @param aspect 宽高比
* @param ref 路径响应式对象
* @param fn 路径定义函数
*/
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;
}
const cx = ox + dw / 2;
const cy = oy + dh / 2;
path = fn([ox, oy, dw, dh, cx, cy], divisor =>
pad(ox, oy, dw, dh, divisor)
);
ref.value = path;
return path;
};
}
/**
* 定义一个描边图标
* @param aspect 图标的宽高比
* @param pathDef 图标的路径定义函数
* @param props 图标组件定义的参数配置
*/
export function defineIcon<T extends IconsProps>(
aspect: number,
pathDef: PathFn,
props: SetupComponentOptions<T> = iconsProps
): DefineSetupFnComponent<T> {
return defineComponent<T>(props => {
const path = shallowRef<Path2D>();
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const generatePath = adjustPath(aspect, path, pathDef);
watch(props, () => {
generatePath(width.value, height.value);
});
onMounted(() => {
generatePath(width.value, height.value);
});
return () => (
<g-path
loc={props.loc}
path={path.value}
stroke
lineJoin="round"
lineCap="round"
></g-path>
);
}, props);
}
export const RollbackIcon = defineIcon(1, loc => {
const path = new Path2D();
const [ox, oy, width, height] = loc;
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;
});
export const RetweetIcon = defineIcon(1, loc => {
const path = new Path2D();
const [ox, oy, width, height] = loc;
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;
});
export const ViewMapIcon = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, , , , cx, cy] = loc;
const [left, right, top, bottom] = pad(5);
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;
});
export const DanmakuIcon = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, , width, height, cx, cy] = loc;
const [left, , , bottom] = pad(5);
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;
});
export const ReplayIcon = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, , width, height, , cy] = loc;
const [left, right, top, bottom] = pad(5);
const arc = width / 10;
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;
});
export const NumpadIcon = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, , width, height, cx, cy] = loc;
const [left, right, top, bottom] = pad(5);
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;
});
export const PlayIcon = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, oy, , height] = loc;
const [left, right, top, bottom] = pad(5);
path.moveTo(left, top);
path.lineTo(right, oy + height / 2);
path.lineTo(left, bottom);
path.closePath();
return path;
});
export const PauseIcon = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, , width, , cx] = loc;
const [, , top, bottom] = pad(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;
});
export const DoubleArrow = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const path2 = new Path2D();
const [, , , height, cx, cy] = loc;
const [left, right, top, bottom] = pad(5);
path.moveTo(left, top + height / 12);
path.lineTo(cx, 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;
});
export const StepForward = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const path2 = new Path2D();
const [, oy, , height] = loc;
const [left, right, top, bottom] = pad(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;
});
export const SoundVolume = defineIcon(1, loc => {
const path = new Path2D();
const [ox, oy, width, height, cx, cy] = loc;
const left = ox + width / 8;
const top = oy + height / 5;
const bottom = oy + height - height / 5;
path.moveTo(left, height / 2 - height / 10);
path.lineTo(left, height / 2 + height / 10);
path.lineTo(left + width / 6, height / 2 + height / 10);
path.lineTo(width / 2, bottom);
path.lineTo(width / 2, top);
path.lineTo(left + width / 6, height / 2 - height / 10);
path.closePath();
const start = -Math.PI / 4;
const end = Math.PI / 4;
path.moveTo(
width / 2 + (Math.SQRT1_2 * width) / 6,
height / 2 - (Math.SQRT1_2 * width) / 6
);
path.arc(cx, cy, width / 6, start, end);
path.moveTo(
width / 2 + (Math.SQRT1_2 * width) / 3,
height / 2 - (Math.SQRT1_2 * width) / 3
);
path.arc(cx, cy, width / 3, start, end);
return path;
});
export const Fullscreen = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, , width, height] = loc;
const [left, right, top, bottom] = pad(4);
// 左上
path.moveTo(left + width / 6, top + height / 6);
path.lineTo(left, top);
path.moveTo(left, top + height / 8);
path.lineTo(left, top);
path.lineTo(left + width / 8, top);
// 右上
path.moveTo(right - width / 6, top + height / 6);
path.lineTo(right, top);
path.moveTo(right, top + height / 8);
path.lineTo(right, top);
path.lineTo(right - width / 8, top);
// 左下
path.moveTo(left + width / 6, bottom - height / 6);
path.lineTo(left, bottom);
path.moveTo(left, bottom - height / 8);
path.lineTo(left, bottom);
path.lineTo(left + width / 8, bottom);
// 右下
path.moveTo(right - width / 6, bottom - height / 6);
path.lineTo(right, bottom);
path.moveTo(right, bottom - height / 8);
path.lineTo(right, bottom);
path.lineTo(right - width / 8, bottom);
return path;
});
export const ExitFullscreen = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, , width, height] = loc;
const [left, right, top, bottom] = pad(4);
// 左上
path.moveTo(left + width / 6, top + height / 6);
path.lineTo(left, top);
path.moveTo(left + width / 24, top + height / 6);
path.lineTo(left + width / 6, top + height / 6);
path.lineTo(left + width / 6, top + height / 24);
// 右上
path.moveTo(right - width / 6, top + height / 6);
path.lineTo(right, top);
path.moveTo(right - width / 24, top + height / 6);
path.lineTo(right - width / 6, top + height / 6);
path.lineTo(right - width / 6, top + height / 24);
// 左下
path.moveTo(left + width / 6, bottom - height / 6);
path.lineTo(left, bottom);
path.moveTo(left + width / 24, bottom - height / 6);
path.lineTo(left + width / 6, bottom - height / 6);
path.lineTo(left + width / 6, bottom - height / 24);
// 右下
path.moveTo(right - width / 6, bottom - height / 6);
path.lineTo(right, bottom);
path.moveTo(right - width / 24, bottom - height / 6);
path.lineTo(right - width / 6, bottom - height / 6);
path.lineTo(right - width / 6, bottom - height / 24);
return path;
});
export const ArrowLeftTailless = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, , width] = loc;
const [left, right, top, bottom] = pad(4);
path.moveTo(right, top);
path.lineTo(left + width / 4, (top + right) / 2);
path.lineTo(right, bottom);
return path;
});
export const ArrowRightTailless = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, , width] = loc;
const [left, right, top, bottom] = pad(4);
path.moveTo(left, top);
path.lineTo(right - width / 4, (top + right) / 2);
path.lineTo(left, bottom);
return path;
});
export const ArrowUpTailless = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, , , height] = loc;
const [left, right, top, bottom] = pad(4);
path.moveTo(left, bottom);
path.lineTo((left + right) / 2, top + height / 4);
path.lineTo(right, bottom);
return path;
});
export const ArrowDownTailless = defineIcon(1, (loc, pad) => {
const path = new Path2D();
const [, , , height] = loc;
const [left, right, top, bottom] = pad(4);
path.moveTo(left, top);
path.lineTo((left + right) / 2, bottom - height / 4);
path.lineTo(right, top);
return path;
});
@@ -1,12 +0,0 @@
export * from './choices';
export * from './floorSelect';
export * from './icons';
export * from './input';
export * from './list';
export * from './misc';
export * from './page';
export * from './scroll';
export * from './textbox';
export * from './textboxTyper';
export * from './thumbnail';
export * from './tip';
@@ -1,601 +0,0 @@
import { DefaultProps } from '@motajs/render-vue';
import { computed, defineComponent, onUnmounted, ref, watch } from 'vue';
import { TextContent, TextContentProps } from './textbox';
import {
Container,
ElementLocator,
MotaRenderer,
Transform,
Font,
RectRCircleParams,
IRenderItem,
IRenderTreeRoot
} from '@motajs/render';
import { transitionedColor, useKey } from '../use';
import { linear } from 'mutate-animate';
import { Background, Selection } from './misc';
import { GameUI, IUIMountable, SetupComponentOptions } from '@motajs/system';
import { KeyCode } from '@motajs/client-base';
export interface InputProps extends DefaultProps, Partial<TextContentProps> {
/** 输入框的提示内容 */
placeholder?: string;
/** 输入框的值 */
value?: string;
/** 是否是多行输入,多行输入时,允许换行 */
multiline?: boolean;
/** 边框颜色 */
border?: string;
/** 边框圆角 */
circle?: RectRCircleParams;
/** 边框宽度 */
borderWidth?: number;
/** 内边距 */
pad?: number;
}
export type InputEmits = {
/**
* 当输入框的值被确认时触发,例如失焦时
* @param value 输入框的值
*/
change: (value: string) => void;
/**
* 当输入框的值发生改变时触发,例如输入了一个字符,或者删除了一个字母
* @param value 输入框的值
*/
input: (value: string) => void;
'update:value': (value: string) => void;
};
const inputProps = {
props: [
'loc',
'placeholder',
'value',
'multiline',
'border',
'circle',
'borderWidth',
'pad'
],
emits: ['change', 'input', 'update:value']
} satisfies SetupComponentOptions<InputProps, InputEmits, keyof InputEmits>;
/**
* 输入组件,点击后允许编辑。参数参考 {@link InputProps},事件参考 {@link InputEmits}。
* 完全继承 TextContent 组件的参数,用于控制输入内容的显示方式。用法示例:
* ```tsx
* const inputValue = ref('');
* <Input
* placeholder="提示词"
* // 双向数据绑定,当输入内容改变时,inputValue 会同时改变
* v-model={inputValue.value}
* // 设置为多行模式
* multiline
* // 边框颜色
* border="#eee"
* // 圆角参数,与 g-rectr 参数一致
* circle={[4]}
* // 边框宽度
* borderWidth={3}
* // 内边距
* pad={8}
* />
* ```
*/
export const Input = defineComponent<InputProps, InputEmits, keyof InputEmits>(
(props, { attrs, emit }) => {
let ele: HTMLInputElement | HTMLTextAreaElement | null = null;
const value = ref(props.value ?? '');
const root = ref<Container>();
const width = computed(() => props.loc?.[2] ?? 200);
const height = computed(() => props.loc?.[3] ?? 200);
const showText = computed(() => value.value || props.placeholder || '');
const padding = computed(() => props.pad ?? 4);
const textLoc = computed<ElementLocator>(() => [
padding.value,
padding.value,
width.value - padding.value * 2,
height.value - padding.value * 2
]);
const rectLoc = computed<ElementLocator>(() => {
const b = props.borderWidth ?? 1;
return [b, b, width.value - b * 2, height.value - b * 2];
});
const borderColor = transitionedColor(
props.border ?? '#ddd',
200,
linear()
)!;
const listenInput = () => {
if (!ele) return;
ele.addEventListener('input', () => {
if (ele) {
updateInput(ele.value);
}
});
ele.addEventListener('change', () => {
if (ele) {
updateValue(ele.value);
}
});
ele.addEventListener('blur', () => {
if (ele) {
updateInput(ele.value);
}
ele?.remove();
});
};
const createInput = (mul: boolean) => {
if (mul) {
ele = document.createElement('textarea');
} else {
ele = document.createElement('input');
}
// See file://./../../../../../src/styles.less
ele.classList.add('motajs-input-element');
listenInput();
};
const updateValue = (newValue: string) => {
value.value = newValue;
emit('update:value', newValue);
emit('change', newValue);
};
const updateInput = (newValue: string) => {
value.value = newValue;
emit('update:value', newValue);
emit('input', newValue);
};
const click = () => {
if (!ele) createInput(props.multiline ?? false);
if (!ele) return;
// 计算当前绝对位置
const chain: IRenderItem[] = [];
let now: IRenderItem | null = root.value ?? null;
let renderer: IRenderTreeRoot | null = null;
if (!now) return;
while (now) {
chain.unshift(now);
if (now?.isRoot) {
renderer = now as MotaRenderer;
}
now = now.parent;
}
const canvas = renderer?.getCanvas();
if (!canvas) return;
const w = width.value;
const h = height.value;
const border = props.borderWidth ?? 1;
const inputWidth = w - border * 2;
const inputHeight = h - border * 2;
// 应用根画布偏移
const box = canvas.getBoundingClientRect();
let trans = new Transform();
trans.translate(box.x, box.y);
trans.scale(renderer?.getScale() ?? 1);
for (const item of chain) {
const { anchorX, anchorY, width, height } = item;
trans.translate(-anchorX * width, -anchorY * height);
trans = trans.multiply(item.transform);
}
trans.translate(border, border);
// 构建CSS transform的matrix字符串
const [a, b, , c, d, , e, f] = trans.mat;
const str = `matrix(${a},${b},${c},${d},${e},${f})`;
const font = props.font ?? Font.defaults();
ele.style.transform = str;
ele.style.width = `${inputWidth}px`;
ele.style.height = `${inputHeight}px`;
ele.style.font = font.string();
ele.style.color = String(props.fillStyle ?? 'white');
ele.style.zIndex = '100';
document.body.appendChild(ele);
ele.focus();
};
const enter = () => {
borderColor.set('#0ff');
};
const leave = () => {
borderColor.set(props.border ?? '#ddd');
};
const [key] = useKey();
key.realize('confirm', (_, code) => {
if (code === KeyCode.Enter) {
// 特判回车键
ele?.blur();
}
});
watch(
() => props.value,
newValue => {
value.value = newValue ?? '';
}
);
watch(
() => props.multiline,
value => {
createInput(value ?? false);
},
{
immediate: true
}
);
onUnmounted(() => {
ele?.remove();
});
return () => (
<container
loc={props.loc}
ref={root}
cursor="text"
onClick={click}
onEnter={enter}
onLeave={leave}
>
<g-rectr
loc={rectLoc.value}
circle={props.circle}
lineWidth={props.borderWidth ?? 1}
fill
stroke
fillStyle="#111"
strokeStyle={borderColor.ref.value}
zIndex={0}
/>
<TextContent
{...attrs}
noevent
loc={textLoc.value}
width={width.value - padding.value * 2}
text={showText.value}
fillStyle="white"
alpha={value.value.length === 0 ? 0.6 : 1}
zIndex={10}
/>
</container>
);
},
inputProps
);
export interface InputBoxProps extends TextContentProps {
/** 输入框对话框的位置 */
loc: ElementLocator;
/** 传递给内部 Input 组件的配置参数,用于自定义输入行为 */
input?: InputProps;
/** 窗口皮肤图片ID,用于对话框背景绘制 */
winskin?: ImageIds;
/** 对话框背景颜色,当未设置 winskin 时生效 */
color?: CanvasStyle;
/** 对话框边框颜色,当未设置 winskin 时生效 */
border?: CanvasStyle;
/** 对话框内部所有元素的内边距 */
pad?: number;
/** 内部输入框区域的高度 */
inputHeight?: number;
/** 对话框顶部的提示文本 */
text?: string;
/** 确认按钮的显示文本,默认为"确认" */
yesText?: string;
/** 取消按钮的显示文本,默认为"取消" */
noText?: string;
/** 确认/取消按钮的字体样式 */
selFont?: Font;
/** 确认/取消按钮的文本颜色 */
selFill?: CanvasStyle;
}
export type InputBoxEmits = {
/**
* 当确认输入框的内容时触发
* @param value 输入框的内容
*/
confirm: (value: string) => void;
/**
* 当取消时触发
* @param value 输入框的内容
*/
cancel: (value: string) => void;
} & InputEmits;
const inputBoxProps = {
props: [
'loc',
'input',
'winskin',
'color',
'border',
'pad',
'inputHeight',
'text',
'yesText',
'noText',
'selFont',
'selFill',
'width'
],
emits: ['confirm', 'cancel', 'change', 'input', 'update:value']
} satisfies SetupComponentOptions<
InputBoxProps,
InputBoxEmits,
keyof InputBoxEmits
>;
/**
* 输入框组件,与 2.x 的 myconfirm 类似,单次调用参考 {@link getInput}。用法与 `ConfirmBox` 类似。
* 参数参考 {@link InputBoxProps},事件参考 {@link InputBoxEmits},用例如下:
* ```tsx
* const onConfirm = (value: string) => console.log(value);
*
* <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')}
* onConfirm={onYes}
* // 可以使用 input 参数调整输入组件
* input={{
* // 例如在输入组件中添加占位符(未输入任何东西时显示此内容)
* placeholder: '在这里输入你的文本'
* }}
* />
* ```
*/
export const InputBox = defineComponent<
InputBoxProps,
InputBoxEmits,
keyof InputBoxEmits
>((props, { attrs, emit }) => {
const contentHeight = ref(0);
const value = ref('');
const selected = ref(false);
const yesSize = ref<[number, number]>([0, 0]);
const noSize = ref<[number, number]>([0, 0]);
const height = ref(200);
const yesText = computed(() => props.yesText ?? '确认');
const noText = computed(() => props.noText ?? '取消');
const text = computed(() => props.text ?? '请输入内容:');
const padding = computed(() => props.pad ?? 8);
const inputHeight = computed(() => props.inputHeight ?? 24);
const inputLoc = computed<ElementLocator>(() => [
padding.value,
padding.value * 2 + contentHeight.value,
props.width - padding.value * 2,
inputHeight.value
]);
const yesLoc = computed<ElementLocator>(() => {
const y = height.value - padding.value;
return [props.width / 3, y, void 0, void 0, 0.5, 1];
});
const noLoc = computed<ElementLocator>(() => {
const y = height.value - padding.value;
return [(props.width / 3) * 2, y, void 0, void 0, 0.5, 1];
});
const selectionLoc = 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 boxLoc = computed<ElementLocator>(() => {
const [x = 0, y = 0, , , ax = 0, ay = 0] = props.loc;
return [x, y, props.width, height.value, ax, ay];
});
const updateHeight = (h: number) => {
contentHeight.value = h;
const [, yh] = yesSize.value;
const [, nh] = noSize.value;
const buttonHeight = Math.max(yh, nh);
height.value = h + inputHeight.value + padding.value * 4 + buttonHeight;
};
const change = (value: string) => {
emit('change', value);
};
const input = (value: string) => {
emit('update:value', value);
emit('input', value);
};
const setYes = (width: number, height: number) => {
yesSize.value = [width, height];
};
const setNo = (width: number, height: number) => {
noSize.value = [width, height];
};
const confirm = () => {
emit('confirm', value.value);
};
const cancel = () => {
emit('cancel', value.value);
};
return () => (
<container loc={boxLoc.value}>
<Background
loc={[0, 0, props.width, height.value]}
winskin={props.winskin}
color={props.color ?? '#333'}
border={props.border}
zIndex={0}
/>
<TextContent
{...attrs}
loc={[padding.value, padding.value]}
text={text.value}
width={props.width - padding.value * 2}
zIndex={5}
onUpdateHeight={updateHeight}
autoHeight
/>
<Input
{...(props.input ?? {})}
loc={inputLoc.value}
v-model={value.value}
zIndex={10}
circle={[4]}
onChange={change}
onInput={input}
/>
<Selection
loc={selectionLoc.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={confirm}
onEnter={() => (selected.value = true)}
onResize={setYes}
/>
<text
loc={noLoc.value}
text={noText.value}
fillStyle={props.selFill}
font={props.selFont}
cursor="pointer"
zIndex={15}
onClick={cancel}
onEnter={() => (selected.value = false)}
onResize={setNo}
/>
</container>
);
}, inputBoxProps);
/**
* 弹出一个输入框,然后将结果返回:
* ```ts
* const value = await getInput(
* // 在哪个 UI 控制器上打开,对于一般 UI 组件来说,直接填写 props.controller 即可
* props.controller,
* // 提示内容
* '请输入文本:',
* // 输入框的位置,宽度由下一个参数指定,高度参数由组件内部计算得出,指定无效
* [240, 240, void 0, void 0, 0.5, 0.5],
* // 宽度设为 240
* 240,
* // 可以给选择框传入其他的 props,例如指定字体,此项可选
* { font: new Font('Verdana', 20) }
* );
* // 之后,就可以根据 value 来执行不同的操作了
* console.log(value); // 输出用户输入的内容
* ```
* @param controller UI 控制器
* @param text 确认文本内容
* @param loc 确认框的位置
* @param width 确认框的宽度
* @param props 额外的 props,参考 {@link ConfirmBoxProps}
*/
export function getInput(
controller: IUIMountable,
text: string,
loc: ElementLocator,
width: number,
props?: InputBoxProps
) {
return new Promise<string>(res => {
const instance = controller.open(
InputBoxUI,
{
...(props ?? {}),
text,
loc,
width,
onConfirm: value => {
controller.close(instance);
res(value);
},
onCancel: () => {
controller.close(instance);
res('');
}
},
true
);
});
}
/**
* 与 `getInput` 类似,不过会将结果转为数字。用法参考 {@link getInput}
* @param controller UI 控制器
* @param text 确认文本内容
* @param loc 确认框的位置
* @param width 确认框的宽度
* @param props 额外的 props,参考 {@link ConfirmBoxProps}
*/
export async function getInputNumber(
controller: IUIMountable,
text: string,
loc: ElementLocator,
width: number,
props?: InputBoxProps
) {
const value = await getInput(controller, text, loc, width, props);
return parseFloat(value);
}
export async function routedInput() {
// todo
}
export async function routedInputNumber() {
// todo
}
export const InputBoxUI = new GameUI('input-box', InputBox);
@@ -1,220 +0,0 @@
import { DefaultProps } from '@motajs/render-vue';
import { computed, defineComponent, ref, SlotsType, VNode } from 'vue';
import { Selection } from './misc';
import { ElementLocator, Font } from '@motajs/render';
import { SetupComponentOptions } from '@motajs/system';
import { Scroll } from './scroll';
export interface ListProps extends DefaultProps {
/** 列表内容,第一项表示 id,第二项表示显示的内容 */
list: [string, string][];
/** 当前选中的项 */
selected: string;
/** 定位 */
loc: ElementLocator;
/** 每行的高度,默认 18 */
lineHeight?: number;
/** 字体 */
font?: Font;
/** 使用 winskin 作为光标 */
winskin?: ImageIds;
/** 使用指定样式作为光标背景 */
color?: CanvasStyle;
/** 使用指定样式作为光标边框 */
border?: CanvasStyle;
/** 选择图标的不透明度范围 */
alphaRange?: [number, number];
}
export type ListEmits = {
/**
* 当用户选中某一项时触发
* @param key 选中的项的 id
*/
update: (key: string) => void;
'update:selected': (value: string) => void;
};
const listProps = {
props: [
'list',
'selected',
'loc',
'lineHeight',
'font',
'winskin',
'color',
'border',
'alphaRange'
],
emits: ['update', 'update:selected']
} satisfies SetupComponentOptions<ListProps, ListEmits, keyof ListEmits>;
export const List = defineComponent<ListProps, ListEmits, keyof ListEmits>(
(props, { emit }) => {
const selected = ref(props.list[0][0]);
const lineHeight = computed(() => props.lineHeight ?? 18);
const select = (value: string) => {
selected.value = value;
emit('update', value);
emit('update:selected', value);
};
return () => (
<Scroll loc={props.loc}>
{props.list.map((v, i) => {
const [key, value] = v;
const loc: ElementLocator = [
0,
lineHeight.value * i,
props.loc[2] ?? 200,
lineHeight.value
];
const selectionLoc: ElementLocator = [
0,
0,
(props.loc[2] ?? 200) - 10,
lineHeight.value
];
const textLoc: ElementLocator = [
10,
lineHeight.value / 2,
void 0,
void 0,
0,
0.5
];
return (
<container loc={loc} onClick={() => select(key)}>
{selected.value === key && (
<Selection
loc={selectionLoc}
color={props.color}
border={props.border}
winskin={props.winskin}
alphaRange={props.alphaRange}
/>
)}
<text
loc={textLoc}
text={value}
font={props.font}
/>
</container>
);
})}
</Scroll>
);
},
listProps
);
export interface ListPageProps extends ListProps {
/** 组件定位 */
loc: ElementLocator;
/** 列表所占比例 */
basis?: number;
/** 列表是否排列在右侧 */
right?: boolean;
/** 是否显示关闭按钮 */
close?: boolean;
/** 关闭按钮的位置,相对于组件定位 */
closeLoc?: ElementLocator;
}
export type ListPageEmits = {
close: () => void;
} & ListEmits;
export type ListPageSlots = SlotsType<{
default: (key: string) => VNode | VNode[];
[x: string]: (key: string) => VNode | VNode[];
}>;
const listPageProps = {
props: [
'basis',
'right',
'list',
'selected',
'loc',
'lineHeight',
'font',
'winskin',
'color',
'border',
'alphaRange',
'close',
'closeLoc'
],
emits: ['update', 'update:selected', 'close']
} satisfies SetupComponentOptions<
ListPageProps,
ListPageEmits,
keyof ListPageEmits,
ListPageSlots
>;
export const ListPage = defineComponent<
ListPageProps,
ListPageEmits,
keyof ListPageEmits,
ListPageSlots
>((props, { emit, slots }) => {
const selected = ref(props.selected);
const basis = computed(() => props.basis ?? 0.3);
const width = computed(() => props.loc[2] ?? 200);
const height = computed(() => props.loc[3] ?? 200);
const listLoc = computed<ElementLocator>(() => {
const listWidth = width.value * basis.value;
if (props.right) {
return [width.value - listWidth, 0, listWidth, height.value];
} else {
return [0, 0, listWidth, height.value];
}
});
const contentLoc = computed<ElementLocator>(() => {
const contentWidth = width.value * (1 - basis.value);
if (props.right) {
return [0, 0, contentWidth, height.value];
} else {
return [width.value - contentWidth, 0, contentWidth, height.value];
}
});
const update = (key: string) => {
emit('update', key);
emit('update:selected', key);
};
const close = () => emit('close');
return () => (
<container loc={props.loc}>
<List
{...props}
loc={listLoc.value}
list={props.list}
v-model:selected={selected.value}
onUpdate={update}
></List>
<container loc={contentLoc.value}>
{slots[selected.value]?.(selected.value) ??
slots.default?.(selected.value)}
</container>
{props.close && (
<text
loc={props.closeLoc}
text="关闭"
cursor="pointer"
font={props.font}
onClick={close}
></text>
)}
</container>
);
}, listPageProps);
@@ -1,590 +0,0 @@
import {
ElementLocator,
CustomRenderItem,
MotaOffscreenCanvas2D
} from '@motajs/render';
import { DefaultProps, PathProps } from '@motajs/render-vue';
import { computed, defineComponent, ref, SetupContext, watch } from 'vue';
import { TextContent, TextContentProps } from './textbox';
import { Scroll, ScrollExpose, ScrollProps } from './scroll';
import { transitioned } from '../use';
import { logger } from '@motajs/common';
import { GameUI, IUIMountable, SetupComponentOptions } from '@motajs/system';
import { clamp } from 'lodash-es';
import { using } from '../renderer';
import { cosh, CurveMode } from '@motajs/animate';
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<CustomRenderItem>();
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();
const progress = clamp(props.progress, 0, 1);
if (!isNaN(progress)) {
ctx.strokeStyle = props.success ?? 'green';
const p = lineWidth + (width - lineWidth * 2) * progress;
ctx.beginPath();
ctx.moveTo(lineWidth, height / 2);
ctx.lineTo(p, height / 2);
ctx.stroke();
}
};
watch(props, () => {
element.value?.update();
});
return () => {
return <custom ref={element} loc={props.loc} render={render}></custom>;
};
}, 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 TextContentProps, 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;
using.onExcitedFunc(() => {
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;
}
lastFixedTime = now;
});
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,
cosh(2, CurveMode.EaseInOut)
)!;
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, ax, ay] = props.loc;
return [x + 1, y + 1, width - 2, height - 2, ax, ay];
});
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);
};
using.onExcitedFunc(() => {
if (alpha.value === maxAlpha.value) {
alpha.set(minAlpha.value);
}
if (alpha.value === minAlpha.value) {
alpha.set(maxAlpha.value);
}
});
return () =>
isWinskin.value ? (
<custom
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 imageName={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', 'width'],
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)}
* // 当传入的 Promise 兑现时触发此事件,注意此事件只可能触发一次,触发后便不会再次触发
* onResolve={(time) => console.log(time)}
* />
* ```
*/
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);
export const BackgroundUI = new GameUI('background', Background);
@@ -1,353 +0,0 @@
import {
computed,
defineComponent,
nextTick,
onMounted,
ref,
SlotsType,
VNode,
watch
} from 'vue';
import { clamp, isNil } from 'lodash-es';
import { ElementLocator, Font } from '@motajs/render';
import { SetupComponentOptions } from '@motajs/system';
import { DefaultProps } from '@motajs/render-vue';
/** 圆角矩形页码距离容器的边框大小,与 pageSize 相乘 */
const RECT_PAD = 0.1;
export interface PageProps extends DefaultProps {
/** 共有多少页 */
pages: number;
/** 页码组件的定位 */
loc: ElementLocator;
/** 当前页码 */
page?: number;
/** 页码的字体 */
font?: Font;
/** 只有一页的时候,是否隐藏页码 */
hideIfSingle?: boolean;
}
export type PageEmits = {
pageChange: (page: number) => void;
'update:page': (page: number) => void;
};
export interface PageExpose {
/**
* 切换页码
* @param page 要切换至的页码数,0 表示第一页
*/
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', 'page', 'font', 'hideIfSingle'],
emits: ['pageChange', 'update:page']
} 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(props.page ?? 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 interval = computed(() => {
const size = font.value.size * 1.5;
const max = size * 9;
if (width.value > max) {
return size;
} else {
return (width.value - size * 5) / 4;
}
});
// 左右箭头的颜色
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;
const int = size + interval.value;
nowPageLoc.value = [center, 0, size, size, 0.5, 0];
leftPageLoc.value = [center - int, 0, size, size, 0.5, 0];
leftLoc.value = [center - int * 2, 0, size, size, 0.5, 0];
rightPageLoc.value = [center + int, 0, size, size, 0.5, 0];
rightLoc.value = [center + int * 2, 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();
}
);
watch(
() => props.page,
page => {
if (!isNil(page)) {
const target = clamp(page, 0, props.pages - 1);
if (nowPage.value !== target) {
nowPage.value = target;
emit('pageChange', target);
}
}
}
);
/**
* 切换页码
*/
const changePage = (page: number) => {
const target = clamp(page, 0, props.pages - 1);
if (nowPage.value !== target) {
nowPage.value = target;
emit('pageChange', target);
emit('update:page', 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} nocache>
<container
key={1}
loc={leftLoc.value}
onClick={lastPage}
cursor="pointer"
nocache
>
<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"
nocache
>
<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} nocache>
<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"
nocache
>
<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"
nocache
>
<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,582 +0,0 @@
import {
computed,
defineComponent,
nextTick,
onMounted,
onUnmounted,
onUpdated,
ref,
SlotsType,
VNode,
watch
} from 'vue';
import {
Container,
ElementLocator,
CustomRenderItem,
Transform,
MotaOffscreenCanvas2D,
IActionEvent,
IWheelEvent,
MouseType,
EventProgress,
ActionEventMap,
ActionType,
CustomContainerPropagateOrigin,
IRenderItem,
ICustomContainer
} from '@motajs/render';
import { hyper, linear, Transition } from 'mutate-animate';
import { clamp } from 'lodash-es';
import { transitioned } from '../use';
import { SetupComponentOptions } from '@motajs/system';
import { DefaultProps } from '@motajs/render-vue';
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<IRenderItem> = new Set();
const areaMap: Map<IRenderItem, [number, number]> = new Map();
const content = ref<Container>();
const scroll = ref<CustomRenderItem>();
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: IRenderItem, 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: IRenderItem) => {
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: IRenderItem) => {
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: IRenderItem[],
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 事件监听
// todo: 滑动操作时的滚动惯性
const customPropagate = <T extends ActionType>(
type: T,
progress: EventProgress,
event: ActionEventMap[T],
_: ICustomContainer,
origin: CustomContainerPropagateOrigin
) => {
if (progress === EventProgress.Capture) {
if (direction.value === ScrollDirection.Horizontal) {
event.offsetX += contentPos;
} else {
event.offsetY += contentPos;
}
}
origin(type, progress, event);
};
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}
propagate={customPropagate}
zIndex={0}
>
{slots.default?.()}
</container-custom>
<custom
nocache
hidden={props.noscroll}
loc={sp.value}
ref={scroll}
render={drawScroll}
onDown={downScroll}
onUp={upScroll}
zIndex={10}
onEnter={enter}
onLeave={leave}
></custom>
</container>
);
};
},
scrollProps
);
@@ -1,673 +0,0 @@
import {
ElementLocator,
Font,
CustomRenderItem,
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 EventEmitter from 'eventemitter3';
import {
ITextContentConfig,
TextContentTyper,
TyperRenderable,
TextContentType,
WordBreak,
TextAlign
} from './textboxTyper';
import { SetupComponentOptions } from '@motajs/system';
import { texture } from '../elements';
import { DefaultProps } from '@motajs/render-vue';
// todo: TextContent 应该改成渲染元素?
//#region TextContent
export interface TextContentProps
extends DefaultProps, Partial<ITextContentConfig> {
/** 显示的文字 */
text?: string;
/** 是否填充 */
fill?: boolean;
/** 是否描边 */
stroke?: boolean;
/** 是否自适应高度,即组件内部计算 height 的值,而非指定,可与滚动条结合 */
autoHeight?: boolean;
/** 文字的最大宽度 */
width: number;
}
export type TextContentEmits = {
/**
* 当打字机结束时触发
*/
typeEnd: () => void;
/**
* 当打字机开始打字时触发
*/
typeStart: () => void;
/**
* 当文字发生变动,组件内部重新计算文字高度时触发
* @param height 更新后的高度
*/
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 = shallowRef<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 || props.hidden) return;
needUpdate = true;
if (!spriteElement.value) {
needUpdate = false;
}
renderable = [];
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 = props.width, , 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<CustomRenderItem>();
const renderContent = (canvas: MotaOffscreenCanvas2D) => {
const ctx = canvas.ctx;
ctx.textBaseline = 'top';
ctx.lineWidth = props.strokeWidth ?? 2;
ctx.lineJoin = 'round';
for (const data of renderable) {
if (data.cut) break;
switch (data.type) {
case TextContentType.Text: {
if (data.text.length === 0) continue;
ctx.fillStyle = data.fillStyle;
ctx.strokeStyle = data.strokeStyle;
ctx.font = data.font;
const text = data.text.slice(0, data.pointer);
if (props.stroke) {
ctx.strokeText(text, data.x, data.y);
}
if (props.fill ?? true) {
ctx.fillText(text, data.x, data.y);
}
break;
}
case TextContentType.Icon: {
const { renderable: r, x: dx, y: dy, width, height } = data;
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 (
<custom
loc={loc.value}
ref={spriteElement}
render={renderContent}
></custom>
);
};
}, textContentOptions);
//#region Textbox
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;
/** 图标 */
icon?: AllIdsWithNone;
/** 最大宽度 */
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, emit }) => {
const data = shallowReactive<TextboxProps>({ width: 200 });
const setTextboxData = () => {
// Textbox
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 ?? '';
data.icon = props.icon;
// TextContent
data.breakChars = props.breakChars ?? '';
data.font = props.font ?? new Font();
data.ignoreLineEnd = props.ignoreLineEnd ?? '';
data.ignoreLineStart = props.ignoreLineStart ?? '';
data.interval = props.interval ?? 0;
data.keepLast = props.keepLast ?? false;
data.lineHeight = props.lineHeight ?? 0;
data.text = props.text ?? '';
data.textAlign = props.textAlign ?? TextAlign.Left;
data.wordBreak = props.wordBreak ?? WordBreak.Space;
data.fill = props.fill ?? true;
data.stroke = props.stroke ?? false;
data.fillStyle = props.fillStyle ?? '#fff';
data.strokeStyle = props.strokeStyle ?? '#000';
data.strokeWidth = props.strokeWidth ?? 2;
data.loc = props.loc;
data.width = props.width;
};
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 contentX = computed(() => {
if (hasIcon.value) {
return data.padding! + 40;
} else {
return data.padding!;
}
});
const contentY = computed(() => {
const height = th.value;
return data.title ? height : 0;
});
const backHeight = computed(() => data.height! - contentY.value);
const contentWidth = computed(() => {
if (hasIcon.value) {
return data.width! - data.padding! * 2 - 40;
} else {
return data.width! - data.padding! * 2;
}
});
const contentHeight = computed(
() => data.height! - data.padding! * 2 - contentY.value
);
const iconLoc = computed<ElementLocator>(() => {
const y = contentY.value;
const pad = data.padding!;
const icon = data.icon;
if (isNil(icon) || icon === 'none') {
return [];
} else {
const num = texture.idNumberMap[icon];
const renderable = texture.getRenderable(num);
if (!renderable) return [];
const [, , w, h] = renderable.render[0];
return [pad, pad + y, w, h];
}
});
const hasIcon = computed(() => {
return !isNil(data.icon) && data.icon !== 'none';
});
const onSetText = () => {
nextTick(() => {
titleElement.value?.requestBeforeFrame(() => {
if (titleElement.value) {
const { width, height } = titleElement.value;
tw.value = width + data.titlePadding! * 2;
th.value = height + data.titlePadding! * 2;
}
});
});
};
//#region store
let lastTitle = data.title;
/** 结束打字机 */
const storeEmits: TextboxStoreEmits = {
endType() {
content.value?.showAll();
},
hide() {
hidden.value = true;
},
show() {
hidden.value = false;
},
update(value) {
if (value.title !== lastTitle) {
onSetText();
lastTitle = value.title;
}
},
setText(text) {
if (data.text === text) {
content.value?.retype();
} else {
data.text = text;
}
}
};
const store = TextboxStore.use(
props.id ?? getNextTextboxId(),
data,
storeEmits
);
const onTypeStart = () => {
store.emitTypeStart();
emit('typeStart');
};
const onTypeEnd = () => {
store.emitTypeEnd();
emit('typeEnd');
};
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={data.loc}
>
{data.title && (
<container zIndex={10} loc={[0, 0, tw.value, th.value]}>
{slots.title ? (
slots.title(data)
) : props.winskin ? (
<winskin
imageName={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}
strokeWidth={2}
></text>
</container>
)}
{slots.default ? (
slots.default(data)
) : props.winskin ? (
<winskin
imageName={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>
)}
{hasIcon.value && (
<icon icon={data.icon as AllIds} loc={iconLoc.value} animate />
)}
{hasIcon.value && (
<g-rect
loc={iconLoc.value}
strokeStyle="gold"
fillStyle="#222"
lineWidth={2}
fill
stroke
/>
)}
<TextContent
{...data}
ref={content}
x={contentX.value}
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(
public 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,84 +0,0 @@
import {
ElementLocator,
MotaOffscreenCanvas2D,
CustomRenderItem
} from '@motajs/render';
import { CustomProps } from '@motajs/render-vue';
import { defineComponent, ref, watch } from 'vue';
import { SetupComponentOptions } from '@motajs/system';
export interface ThumbnailProps extends CustomProps {
/** 缩略图的位置 */
loc: ElementLocator;
/** 楼层 ID */
floorId: FloorIds;
/** 缩略图填充样式 */
padStyle?: CanvasStyle;
/** 楼层信息 */
map?: Block[];
/** 角色信息 */
hero?: HeroStatus;
// configs
damage?: boolean;
all?: boolean;
noHD?: boolean;
/** 缩略图的比例,1 表示与实际地图大小一致 */
size?: number;
}
const thumbnailProps = {
props: [
'loc',
'padStyle',
'floorId',
'map',
'hero',
'damage',
'all',
'noHD',
'size'
]
} satisfies SetupComponentOptions<ThumbnailProps>;
export const Thumbnail = defineComponent<ThumbnailProps>(props => {
const spriteRef = ref<CustomRenderItem>();
const update = () => {
spriteRef.value?.update();
};
const drawThumbnail = (canvas: MotaOffscreenCanvas2D) => {
if (props.hidden) return;
const ctx = canvas.ctx;
const hero = props.hero;
const options: Partial<DrawThumbnailConfig> = {
damage: props.damage,
ctx: ctx,
x: 0,
y: 0,
size: props.size ?? 1,
all: props.all,
noHD: props.noHD,
v2: true,
inFlyMap: false
};
if (hero) {
options.heroLoc = hero.loc;
options.heroIcon = hero.image;
options.flags = hero.flags;
options.centerX = hero.loc.x;
options.centerY = hero.loc.y;
}
ctx.save();
ctx.fillStyle = props.padStyle ?? 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
core.drawThumbnail(props.floorId, props.map, options);
ctx.restore();
};
watch(props, update);
return () => (
<custom noanti ref={spriteRef} loc={props.loc} render={drawThumbnail} />
);
}, thumbnailProps);
@@ -1,176 +0,0 @@
import { ElementLocator, Font } from '@motajs/render';
import { logger } from '@motajs/common';
import { computed, defineComponent, onUnmounted, ref } from 'vue';
import { transitioned } from '../use';
import { hyper } from 'mutate-animate';
import { debounce } from 'lodash-es';
import { texture } from '../elements';
import { SetupComponentOptions } from '@motajs/system';
import { DefaultProps } from '@motajs/render-vue';
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 {
// 样板竟然会传 null 进来,然后报错
iconNum.value = iconId ?? 0;
}
text.value = core.replaceText(tipText);
alpha.set(0, 0);
alpha.set(1);
hide();
};
const onSetText = (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(0,0,0,0.8)"
/>
<icon
hidden={!showIcon.value}
icon={iconNum.value}
loc={iconLoc.value}
/>
<text
loc={textLoc.value}
text={text.value}
onResize={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,504 +0,0 @@
import { logger } from '@motajs/common';
import { MotaOffscreenCanvas2D, SizedCanvasImageSource } from '@motajs/render';
// 经过测试(https://www.measurethat.net/Benchmarks/Show/30741/1/drawimage-img-vs-canvas-vs-bitmap-cropping-fix-loading)
// 得出结论,ImageBitmap和Canvas的绘制性能不如Image,于是直接画Image就行,所以缓存基本上就是存Image
type ImageMapKeys = Exclude<Cls, 'tileset' | 'autotile'>;
type ImageMap = Record<ImageMapKeys, ImageBitmap>;
const i = (img: ImageMapKeys) => {
return core.material.images[img];
};
const imageMap: Partial<ImageMap> = {};
interface AutotileCache {
parent?: Set<AllNumbersOf<'autotile'>>;
frame: number;
cache: Record<string, HTMLCanvasElement>;
}
type AutotileCaches = Record<AllNumbersOf<'autotile'>, AutotileCache>;
interface TextureRequire {
tileset: Record<string, ImageBitmap>;
material: Record<ImageMapKeys, ImageBitmap>;
autotile: AutotileCaches;
images: Record<ImageIds, ImageBitmap>;
}
interface RenderableDataBase {
/** 图块的总帧数 */
frame: number;
/** 对应图块属性的动画帧数,-1表示没有设定,0表示第一帧 */
animate: number;
render: [x: number, y: number, width: number, height: number][];
}
export interface RenderableData extends RenderableDataBase {
image: SizedCanvasImageSource;
autotile: false;
}
export interface AutotileRenderable extends RenderableDataBase {
image: Record<string, SizedCanvasImageSource>;
autotile: true;
}
class TextureCache {
tileset!: Record<string, ImageBitmap>;
material: Record<ImageMapKeys, ImageBitmap>;
autotile!: AutotileCaches;
images!: Record<ImageIds, ImageBitmap>;
idNumberMap!: IdToNumber;
/** 渲染信息 */
renderable: Map<number, RenderableData | AutotileRenderable> = new Map();
/** 自动元件额外连接信息,用于对非自身图块进行连接 */
autoConn: Map<number, Set<number>> = new Map();
/** 行走图朝向绑定 */
characterDirection: Record<Dir2, number> = {
down: 0,
left: 1,
right: 2,
up: 3,
leftup: 1,
leftdown: 1,
rightup: 2,
rightdown: 2
};
/** 行走图转向顺序 */
characterTurn: Dir[] = ['up', 'right', 'down', 'left'];
characterTurn2: Dir2[] = ['leftup', 'rightup', 'rightdown', 'leftdown'];
constructor() {
this.material = imageMap as Record<ImageMapKeys, ImageBitmap>;
}
init() {
const map = maps_90f36752_8815_4be8_b32b_d7fad1d0542e;
// @ts-expect-error 无法推导
this.idNumberMap = {};
for (const [key, { id }] of Object.entries(map)) {
// @ts-expect-error 无法推导
this.idNumberMap[id] = parseInt(key) as AllNumbers;
}
this.tileset = core.material.images.tilesets;
this.autotile = splitAutotiles(this.idNumberMap);
this.images = core.material.images.images;
this.calRenderable();
this.calAutotileConnections();
}
/**
* 获取纹理
* @param type 纹理类型
* @param key 纹理名称
*/
require<T extends keyof TextureRequire, K extends keyof TextureRequire[T]>(
type: T,
key: K
): TextureRequire[T][K] {
return this[type][key];
}
/**
* 计算每个图块的可渲染信息
*/
private calRenderable() {
const map = maps_90f36752_8815_4be8_b32b_d7fad1d0542e;
for (const key of Object.keys(map)) {
this.calRenderableByNum(parseInt(key));
}
}
/**
* 根据图块数字计算出它的渲染信息
* @param num 图块数字
*/
calRenderableByNum(
num: number
): RenderableData | AutotileRenderable | null {
const map = maps_90f36752_8815_4be8_b32b_d7fad1d0542e;
const icons = icons_4665ee12_3a1f_44a4_bea3_0fccba634dc1;
/** 特判空图块与空气墙 */
if (num === 0 || num === 17) return null;
// 额外素材
if (num >= 10000) {
const offset = core.getTilesetOffset(num);
if (!offset) return null;
const { image, x, y } = offset;
const data: RenderableData = {
image: this.tileset[image],
frame: 1,
render: [[x * 32, y * 32, 32, 32]],
animate: 0,
autotile: false
};
this.renderable.set(num, data);
return data;
}
const data = map[num as Exclude<AllNumbers, 0>];
// 地狱般的分支if
if (data) {
const { cls, id, animate } = data;
// enemy48和npc48都应该视为大怪物
if (cls === 'enemy48' || cls === 'npc48') {
const img = core.material.images[cls];
if (!img) return null;
// @ts-expect-error 无法推导
const line = icons[cls][id];
const w = 32;
const h = 48;
const y = h * line;
const data: RenderableData = {
image: img,
frame: 4,
render: [
[0, y, w, h],
[w, y, w, h],
[w * 2, y, w, h],
[w * 3, y, w, h]
],
animate: (animate ?? 0) - 1,
autotile: false
};
this.renderable.set(num, data);
return data;
}
// 自动元件
if (cls === 'autotile') {
if (!this.autotile) return null;
const auto = this.autotile[num as AllNumbersOf<'autotile'>];
const cell = 32;
const render: [number, number, number, number][] = [];
if (auto.frame >= 1) {
render.push([0, 0, cell, cell]);
}
if (auto.frame >= 3) {
render.push(
[cell, 0, cell, cell],
[cell * 2, 0, cell, cell]
);
}
if (auto.frame >= 4) {
render.push([cell * 3, 0, cell, cell]);
}
const data: AutotileRenderable = {
image: auto.cache,
frame: auto.frame,
render,
autotile: true,
animate: (animate ?? 0) - 1
};
this.renderable.set(num, data);
return data;
} else {
const image =
core.material.images[
cls as Exclude<Cls, 'tileset' | 'autotile'>
];
if (!image) return null;
const frame = core.getAnimateFrames(cls);
const cell = 32;
// @ts-expect-error 无法推导
const offset = (icons[cls][id] as number) * cell;
const render: [number, number, number, number][] = [
[0, offset, cell, cell]
];
if (frame === 2) {
render.push([cell, offset, cell, cell]);
}
if (frame === 4) {
render.push(
[cell, offset, cell, cell],
[cell * 2, offset, cell, cell],
[cell * 3, offset, cell, cell]
);
}
const data: RenderableData = {
image,
frame: frame,
render,
autotile: false,
animate: (animate ?? 0) - 1
};
this.renderable.set(num, data);
return data;
}
} else {
logger.warn(11, num.toString());
return null;
}
}
/**
* 获取一个图块的渲染信息,自动元件会特别标明autotile属性
* @param num 图块数字
*/
getRenderable(num: number) {
return this.renderable.get(num) ?? this.calRenderableByNum(num);
}
/**
* 计算自动元件的额外连接
*/
private calAutotileConnections() {
const icons = icons_4665ee12_3a1f_44a4_bea3_0fccba634dc1;
const maps = maps_90f36752_8815_4be8_b32b_d7fad1d0542e;
Object.keys(icons.autotile).forEach(v => {
const num = this.idNumberMap[v as AllIdsOf<'autotile'>];
const data = maps[num];
const { autotileConnection } = data;
if (!autotileConnection) return;
const list = new Set<AllNumbers>();
autotileConnection.forEach(v => {
if (typeof v === 'number') {
list.add(v);
} else {
list.add(this.idNumberMap[v]);
}
});
this.autoConn.set(num, list);
});
}
/**
* 获取自动元件的额外连接情况
* @param num 自动元件的图块数字
*/
getAutotileConnections(num: number) {
return this.autoConn.get(num);
}
}
export const texture = new TextureCache();
// 3x4 与 2x3 的自动元件信息
// 将自动元件按 16x16 切分后,数组分别表示 左上 右上 右下 左下 所在图块位置
const bigAutotile: Record<number, [number, number, number, number]> = {};
const smallAutotile: Record<number, [number, number, number, number]> = {};
function getAutotileIndices() {
// 应当从 0 - 255 进行枚举
// 二进制从高位到低位依次是 左上 上 右上 右 右下 下 左下 左
// 有兴趣可以研究下这个算法
const get = (
target: Record<number, [number, number, number, number]>,
mode: 1 | 2
) => {
const h = mode === 1 ? 4 : 2;
const v = mode === 1 ? 24 : 8;
const luo = mode === 1 ? 12 : 8; // leftup origin
const ruo = mode === 1 ? 17 : 11; // rightup origin
const ldo = mode === 1 ? 42 : 20; // leftdown origin
const rdo = mode === 1 ? 47 : 23; // rightdown origin
const luc = mode === 1 ? 4 : 2; // leftup corner
const ruc = mode === 1 ? 5 : 3; // rightup corner
const rdc = mode === 1 ? 11 : 7; // rightdown corner
const ldc = mode === 1 ? 10 : 6; // leftdown corner
for (let i = 0; i <= 0b11111111; i++) {
let lu = luo; // leftup
let ru = ruo; // rightup
let ld = ldo; // leftdown
let rd = rdo; // rightdown
// 先看四个方向,最后看斜角方向
if (i & 0b00000001) {
lu += h;
ld += h;
if (i & 0b00010000) {
ru += h / 2;
rd += h / 2;
}
}
if (i & 0b00000100) {
ld -= v;
rd -= v;
if (i & 0b01000000) {
lu -= v / 2;
ru -= v / 2;
}
}
if (i & 0b00010000) {
ru -= h;
rd -= h;
if (i & 0b00000001) {
lu -= h / 2;
ld -= h / 2;
}
}
if (i & 0b01000000) {
lu += v;
ru += v;
if (i & 0b00000100) {
ld += v / 2;
rd += v / 2;
}
}
// 斜角
if ((i & 0b11000001) === 0b01000001) {
lu = luc;
}
if ((i & 0b01110000) === 0b01010000) {
ru = ruc;
}
if ((i & 0b00011100) === 0b00010100) {
rd = rdc;
}
if ((i & 0b00000111) === 0b00000101) {
ld = ldc;
}
target[i] = [lu, ru, rd, ld];
}
};
get(bigAutotile, 1);
get(smallAutotile, 2);
}
getAutotileIndices();
function getRepeatMap() {
// 实际上3x4与2x3的重复映射是一致的,因此只需要计算一个就行了
// 这里使用2x3的进行计算
const calculated: Record<string, number> = {};
const repeatMap: Record<number, number> = {};
for (const [num, [lu, ru, rd, ld]] of Object.entries(smallAutotile)) {
const n = lu + ru * 24 + rd * 24 ** 2 + ld * 24 ** 3;
calculated[num] = n;
for (const [num2, n2] of Object.entries(calculated)) {
if (n2 === n) {
repeatMap[Number(num)] = Number(num2);
break;
}
}
}
return repeatMap;
}
function splitAutotiles(map: IdToNumber): AutotileCaches {
const cache: Partial<AutotileCaches> = {};
/** 重复映射,由于自动元件只有48种,其余的208种是重复的,因此需要获取重复映射 */
const repeatMap: Record<number, number> = getRepeatMap();
/** 每个自动元件左上角32*32的内容,用于判断父子关系 */
const masterMap: Partial<Record<AllNumbersOf<'autotile'>, string>> = {};
for (const [key, img] of Object.entries(core.material.images.autotile)) {
const auto = map[key as AllIdsOf<'autotile'>];
// 判断自动元件类型
let mode: 1 | 2 = 1;
let frame = 1;
if (img.width === 384) {
frame = 4;
} else if (img.width === 192) {
mode = 2;
frame = 3;
} else if (img.width === 64) {
mode = 2;
}
cache[auto] = {
frame,
cache: {}
};
// 父子关系,截取本图块的左上角存入map
const master = new MotaOffscreenCanvas2D();
master.setHD(false);
master.setAntiAliasing(false);
master.size(32, 32);
master.ctx.drawImage(img, 0, 0, 32, 32, 0, 0, 32, 32);
masterMap[auto] = master.canvas.toDataURL('image/png');
// 自动图块的绘制信息
for (let i = 0; i <= 0b11111111; i++) {
const re = repeatMap[i];
if (re) {
const cached = cache[auto]!.cache[re];
if (cached) {
cache[auto]!.cache[i] = cached;
continue;
}
}
const data = (mode === 1 ? bigAutotile : smallAutotile)[i];
const row = mode === 1 ? 6 : 4;
const info: [number, number][] = data.map(v => [
(v % row) * 16,
Math.floor(v / row) * 16
]);
const canvas = new MotaOffscreenCanvas2D();
canvas.setHD(false);
canvas.setAntiAliasing(false);
canvas.size(32 * frame, 32);
const ctx = canvas.ctx;
for (let i = 0; i < frame; i++) {
const dx = 32 * i;
const sx1 = info[0][0] + (i * row * 32) / 2;
const sx2 = info[1][0] + (i * row * 32) / 2;
const sx3 = info[2][0] + (i * row * 32) / 2;
const sx4 = info[3][0] + (i * row * 32) / 2;
const sy1 = info[0][1];
const sy2 = info[1][1];
const sy3 = info[2][1];
const sy4 = info[3][1];
ctx.drawImage(img, sx1, sy1, 16, 16, dx, 0, 16, 16);
ctx.drawImage(img, sx2, sy2, 16, 16, dx + 16, 0, 16, 16);
ctx.drawImage(img, sx3, sy3, 16, 16, dx + 16, 16, 16, 16);
ctx.drawImage(img, sx4, sy4, 16, 16, dx, 16, 16, 16);
}
cache[auto]!.cache[i] = canvas.canvas;
}
}
const judge = new MotaOffscreenCanvas2D();
judge.setHD(false);
judge.setAntiAliasing(false);
judge.size(32, 32);
// 进行父子关系判断
for (const [key, img] of Object.entries(core.material.images.autotile)) {
const auto = map[key as AllIdsOf<'autotile'>];
// 只针对3*4的图块进行,截取第一行中间的,然后判断
judge.clear();
judge.ctx.drawImage(img, 32, 0, 32, 32, 0, 0, 32, 32);
const data = judge.canvas.toDataURL('image/png');
for (const [key, data2] of Object.entries(masterMap)) {
const auto2 = map[key as AllIdsOf<'autotile'>];
if (data === data2) {
cache[auto]!.parent ??= new Set();
cache[auto]!.parent!.add(auto2);
}
}
}
return cache as AutotileCaches;
}
export function createCache() {
const { loading } = Mota.require('@user/data-base');
loading.once('loaded', () => {
[
'enemys',
'enemy48',
'npcs',
'npc48',
'terrains',
'items',
'animates'
].forEach(v => (imageMap[v as ImageMapKeys] = i(v as ImageMapKeys)));
texture.init();
});
}
@@ -1,47 +0,0 @@
import { logger } from '@motajs/common';
import { MapRenderItem } from '../map';
import { mainRenderer, tagManager } from '../renderer';
import { createCache } from './cache';
import { Icon, Winskin } from './misc';
export function createElements() {
createCache();
// ----- 注册标签
mainRenderer.registerElement('icon', Icon);
mainRenderer.registerElement('winskin', Winskin);
mainRenderer.registerElement('map-render', MapRenderItem);
tagManager.registerTag(
'icon',
tagManager.createStandardElement(false, Icon)
);
tagManager.registerTag(
'winskin',
tagManager.createStandardElement(false, Winskin)
);
tagManager.registerTag('map-render', props => {
if (!props) {
logger.error(42, 'layerState');
throw new Error(`Lack of map-render property.`);
}
const { layerState, renderer, extension } = props;
if (!layerState) {
logger.error(42, 'layerState');
throw new Error(`Lack of map-render property.`);
}
if (!renderer) {
logger.error(42, 'renderer');
throw new Error(`Lack of map-render property.`);
}
if (!extension) {
logger.error(42, 'extension');
throw new Error(`Lack of map-render property.`);
}
return new MapRenderItem(layerState, renderer, extension);
});
}
export * from './cache';
export * from './misc';
export * from './props';
@@ -1,267 +0,0 @@
import { logger } from '@motajs/common';
import {
RenderItem,
MotaOffscreenCanvas2D,
Transform,
SizedCanvasImageSource
} from '@motajs/render';
import { isNil } from 'lodash-es';
import { RenderableData, AutotileRenderable, texture } from './cache';
import { IExcitable } from '@motajs/animate';
import { IMotaIcon, IMotaWinskin } from './types';
export class Icon extends RenderItem implements IMotaIcon, IExcitable<number> {
/** 图标id */
icon: AllNumbers = 0;
/** 渲染动画的第几帧 */
frame: number = 0;
/** 是否启用动画 */
animate: boolean = false;
/** 当前动画速度 */
frameSpeed: number = 300;
/** 当前帧率 */
nowFrame: number = 0;
/** 图标的渲染信息 */
private renderable?: RenderableData | AutotileRenderable;
private pendingIcon?: AllNumbers;
/** 委托激励对象 id,用于图标的动画展示 */
private delegation: number = -1;
constructor(cache: boolean = false) {
super(cache);
this.setAntiAliasing(false);
this.setHD(false);
}
excited(payload: number): void {
if (!this.renderable) return;
const frame = Math.floor(payload / 300);
if (frame === this.nowFrame) return;
this.nowFrame = frame;
this.update();
}
protected render(
canvas: MotaOffscreenCanvas2D,
_transform: Transform
): void {
const ctx = canvas.ctx;
const renderable = this.renderable;
if (!renderable) return;
const [x, y, w, h] = renderable.render[0];
const cw = this.width;
const ch = this.height;
const frame = this.animate
? this.nowFrame % renderable.frame
: this.frame;
if (!this.animate) {
if (renderable.autotile) {
ctx.drawImage(renderable.image[0], x, y, w, h, 0, 0, cw, ch);
} else {
ctx.drawImage(renderable.image, x, y, w, h, 0, 0, cw, ch);
}
} else {
const [x1, y1, w1, h1] = renderable.render[frame];
if (renderable.autotile) {
const img = renderable.image[0];
ctx.drawImage(img, x1, y1, w1, h1, 0, 0, cw, ch);
} else {
ctx.drawImage(renderable.image, x1, y1, w1, h1, 0, 0, cw, ch);
}
}
}
/**
* 设置图标
* @param id 图标id
*/
setIcon(id: AllIdsWithNone | AllNumbers) {
if (id === 0 || id === 'none') {
this.renderable = void 0;
return;
}
const num = typeof id === 'number' ? id : texture.idNumberMap[id];
const { loading } = Mota.require('@user/data-base');
if (loading.loaded) {
this.setIconRenderable(num);
} else {
if (isNil(this.pendingIcon)) {
loading.once('loaded', () => {
this.setIconRenderable(this.pendingIcon ?? 0);
delete this.pendingIcon;
});
}
this.pendingIcon = num;
}
}
setFrameSpeed(speed: number): void {
this.frameSpeed = speed;
this.update();
}
setFrame(frame: number): void {
if (frame < 0) {
this.setAnimateStatus(true);
return;
}
this.frame = frame;
this.update();
}
setAnimateStatus(animate: boolean): void {
this.animate = animate;
if (!animate) this.removeExcitable(this.delegation);
else this.delegation = this.delegateExcitable(this);
this.update();
}
private setIconRenderable(num: AllNumbers) {
const renderable = texture.getRenderable(num);
if (!renderable) {
logger.warn(43, num.toString());
return;
} else {
this.icon = num;
this.renderable = renderable;
this.frame = renderable.frame;
}
this.update();
}
destroy(): void {
super.destroy();
}
protected handleProps(
key: string,
_prevValue: any,
nextValue: any
): boolean {
switch (key) {
case 'icon':
this.setIcon(nextValue);
return true;
case 'animate':
if (!this.assertType(nextValue, 'boolean', key)) return false;
this.setAnimateStatus(nextValue);
return true;
case 'frame':
if (!this.assertType(nextValue, 'number', key)) return false;
this.setFrame(nextValue);
return true;
case 'speed':
if (!this.assertType(nextValue, 'number', key)) return false;
this.setFrameSpeed(nextValue);
return true;
}
return false;
}
}
export class Winskin extends RenderItem implements IMotaWinskin {
image: SizedCanvasImageSource | null = null;
/** 边框宽度,32表示原始宽度 */
borderSize: number = 32;
/** 图片名称 */
imageName: string = '';
private pendingImage?: ImageIds;
constructor(enableCache: boolean = false) {
super(enableCache);
this.setAntiAliasing(false);
}
protected render(canvas: MotaOffscreenCanvas2D): void {
const img = this.image;
if (!img) return;
const ctx = canvas.ctx;
const w = this.width;
const h = this.height;
const pad = this.borderSize / 2;
// 背景
ctx.drawImage(img, 0, 0, 128, 128, 2, 2, w - 4, h - 4);
// 上下左右边框
ctx.save();
ctx.drawImage(img, 144, 0, 32, 16, pad, 0, w - pad * 2, pad);
ctx.drawImage(img, 144, 48, 32, 16, pad, h - pad, w - pad * 2, pad);
ctx.drawImage(img, 128, 16, 16, 32, 0, pad, pad, h - pad * 2);
ctx.drawImage(img, 176, 16, 16, 32, w - pad, pad, pad, h - pad * 2);
// 四个角的边框
ctx.drawImage(img, 128, 0, 16, 16, 0, 0, pad, pad);
ctx.drawImage(img, 176, 0, 16, 16, w - pad, 0, pad, pad);
ctx.drawImage(img, 128, 48, 16, 16, 0, h - pad, pad, pad);
ctx.drawImage(img, 176, 48, 16, 16, w - pad, h - pad, pad, pad);
}
/**
* 设置winskin图片
* @param image winskin图片
*/
setImage(image: SizedCanvasImageSource) {
this.image = image;
this.imageName = '';
this.update();
}
/**
* 通过图片名称设置winskin
* @param name 图片名称
*/
setImageByName(name: ImageIds) {
const { loading } = Mota.require('@user/data-base');
if (loading.loaded) {
const image = core.material.images.images[name];
this.setImage(image);
} else {
if (isNil(this.pendingImage)) {
loading.once('loaded', () => {
const id = this.pendingImage;
if (!id) return;
const image = core.material.images.images[id];
this.setImage(image);
delete this.pendingImage;
});
}
this.pendingImage = name;
}
this.imageName = name;
}
/**
* 设置边框大小
* @param size 边框大小
*/
setBorderSize(size: number) {
this.borderSize = size;
this.update();
}
protected handleProps(
key: string,
_prevValue: any,
nextValue: any
): boolean {
switch (key) {
case 'image':
this.setImage(nextValue);
return true;
case 'imageName':
if (!this.assertType(nextValue, 'string', key)) return false;
this.setImageByName(nextValue);
return true;
case 'borderSize':
if (!this.assertType(nextValue, 'number', key)) return false;
this.setBorderSize(nextValue);
return true;
}
return false;
}
}
@@ -1,40 +0,0 @@
import { BaseProps, TagDefine } from '@motajs/render-vue';
import { ERenderItemEvent, SizedCanvasImageSource } from '@motajs/render';
import { IGameMap } from '@user/data-base';
import { IMapExtensionManager, IMapRenderer } from '../map';
export interface IconProps extends BaseProps {
/** 图标 id 或数字 */
icon: AllNumbers | AllIds;
/** 显示图标的第几帧 */
frame?: number;
/** 是否开启动画,开启后 frame 参数无效 */
animate?: boolean;
/** 动画速度 */
speed?: number;
}
export interface WinskinProps extends BaseProps {
/** 直接设置 winskin 图片 */
image?: SizedCanvasImageSource;
/** 根据图片名称设置 winskin 图片 */
imageName?: string;
/** 边框大小 */
borderSize?: number;
}
export interface MapRenderProps extends BaseProps {
layerState: IGameMap;
renderer: IMapRenderer;
extension: IMapExtensionManager;
}
declare module 'vue/jsx-runtime' {
namespace JSX {
export interface IntrinsicElements {
icon: TagDefine<IconProps, ERenderItemEvent>;
winskin: TagDefine<WinskinProps, ERenderItemEvent>;
'map-render': TagDefine<MapRenderProps, ERenderItemEvent>;
}
}
}
@@ -1,65 +0,0 @@
import { IRenderItem, SizedCanvasImageSource } from '@motajs/render';
export interface IMotaIcon extends IRenderItem {
/** 图标id */
readonly icon: AllNumbers;
/** 渲染动画的第几帧 */
readonly frame: number;
/** 是否启用动画 */
readonly animate: boolean;
/** 当前动画帧数,如果没有启用动画则为 -1 */
readonly nowFrame: number;
/** 当前图标的动画速度,每多长时间切换至下一帧,单位毫秒 */
readonly frameSpeed: number;
/**
* 设置图标
* @param id 图标id
*/
setIcon(id: AllIdsWithNone | AllNumbers): void;
/**
* 设置当前图标的帧动画速度,单位毫秒
* @param speed 帧动画速度
*/
setFrameSpeed(speed: number): void;
/**
* 设置当前图标是否启用帧动画
* @param animate 是否启用帧动画
*/
setAnimateStatus(animate: boolean): void;
/**
* 设置图标显示第几帧,如果传入负数视为启用帧动画
* @param frame 显示图标的第几帧
*/
setFrame(frame: number): void;
}
export interface IMotaWinskin extends IRenderItem {
/** winskin 图片源 */
readonly image: SizedCanvasImageSource | null;
/** 边框尺寸 */
readonly borderSize: number;
/** winskin 图片名称,如果不是使用名称设置的图片的话,此值为空字符串 */
readonly imageName: string;
/**
* 设置winskin图片
* @param image winskin图片
*/
setImage(image: SizedCanvasImageSource): void;
/**
* 通过图片名称设置winskin
* @param name 图片名称
*/
setImageByName(name: ImageIds): void;
/**
* 设置边框大小
* @param size 边框大小
*/
setBorderSize(size: number): void;
}
@@ -2,7 +2,7 @@ import { Font } from '@motajs/render';
import { defineComponent } from 'vue';
import { DEFAULT_FONT, MAIN_HEIGHT, MAIN_WIDTH } from '../shared';
import { hook } from '@user/data-base';
import { createElements } from './elements';
import { createElements } from '@user/client-base';
import { mainRenderer } from './renderer';
import { createUI } from './ui';
import { createAction } from './action';
@@ -42,8 +42,8 @@ export function createRender() {
Font.setDefaults(DEFAULT_FONT);
}
export * from './components';
export * from './elements';
export * from '@user/client-base';
export * from '@user/client-base';
export * from './fx';
export * from './ui';
export * from './utils';
@@ -1,352 +0,0 @@
import { clamp } from 'lodash-es';
import {
IBlockData,
IBlockIndex,
IBlockInfo,
IBlockSplitter,
IBlockSplitterConfig
} from './types';
import { ISearchable8Dir } from '@motajs/common';
export class BlockSplitter<T> implements IBlockSplitter<T> {
blockWidth: number = 0;
blockHeight: number = 0;
dataWidth: number = 0;
dataHeight: number = 0;
width: number = 1;
height: number = 1;
/** 分块映射 */
readonly blockMap: Map<number, IBlockData<T>> = new Map();
/** 数据宽度配置 */
private splitDataWidth: number = 0;
/** 数据高度配置 */
private splitDataHeight: number = 0;
/** 单个分块的宽度配置 */
private splitBlockWidth: number = 0;
/** 单个分块的高度配置 */
private splitBlockHeight: number = 0;
/**
* 检查坐标范围
* @param x 分块横坐标
* @param y 分块纵坐标
*/
private checkLocRange(x: number, y: number) {
return x >= 0 && y >= 0 && x < this.width && y < this.height;
}
getBlockByLoc(x: number, y: number): IBlockData<T> | null {
if (!this.checkLocRange(x, y)) return null;
const index = y * this.width + x;
return this.blockMap.get(index) ?? null;
}
getBlockByIndex(index: number): IBlockData<T> | null {
return this.blockMap.get(index) ?? null;
}
setBlockByLoc(data: T, x: number, y: number): IBlockData<T> | null {
if (!this.checkLocRange(x, y)) return null;
const index = y * this.width + x;
const block = this.blockMap.get(index);
if (!block) return null;
block.data = data;
return block;
}
setBlockByIndex(data: T, index: number): IBlockData<T> | null {
const block = this.blockMap.get(index);
if (!block) return null;
block.data = data;
return block;
}
*iterateBlockByLoc(x: number, y: number): Generator<IBlockIndex, void> {
if (!this.checkLocRange(x, y)) return;
const index = y * this.width + x;
yield* this.iterateBlockByIndex(index);
}
*iterateBlockByIndex(index: number): Generator<IBlockIndex, void> {
const block = this.blockMap.get(index);
if (!block) return;
const startX = block.x * this.blockWidth;
const startY = block.y * this.blockHeight;
const endX = startX + block.width;
const endY = startY + block.height;
for (let ny = startY; ny < endY; ny++) {
for (let nx = startX; nx < endX; nx++) {
const index: IBlockIndex = {
x: nx,
y: ny,
dataX: nx * this.blockWidth,
dataY: ny * this.blockHeight,
index: ny * this.dataWidth + nx
};
yield index;
}
}
}
*iterateBlockByIndices(
indices: Iterable<number>
): Generator<IBlockIndex, void> {
for (const index of indices) {
yield* this.iterateBlockByIndex(index);
}
}
iterateBlocks(): Iterable<IBlockData<T>> {
return this.blockMap.values();
}
*iterateBlocksOfDataArea(
x: number,
y: number,
width: number,
height: number
): Generator<IBlockData<T>> {
const r = this.width - 1;
const b = this.height - 1;
const rx = x + width;
const by = y + height;
const left = clamp(Math.floor(x / this.blockWidth), 0, r);
const top = clamp(Math.floor(y / this.blockHeight), 0, b);
const right = clamp(Math.floor(rx / this.blockWidth), 0, r);
const bottom = clamp(Math.floor(by / this.blockHeight), 0, b);
for (let ny = left; ny <= right; ny++) {
for (let nx = top; nx <= bottom; nx++) {
const index = ny * this.width + nx;
const block = this.blockMap.get(index);
if (!block) continue;
yield block;
}
}
}
getIndexByLoc(x: number, y: number): number {
if (!this.checkLocRange(x, y)) return -1;
return y * this.width + x;
}
getLocByIndex(index: number): Loc | null {
if (index >= this.width * this.height) return null;
return {
x: index % this.width,
y: Math.floor(index / this.width)
};
}
getIndicesByLocList(list: Iterable<Loc>): Iterable<number> {
const res: number[] = [];
for (const { x, y } of list) {
res.push(this.getIndexByLoc(x, y));
}
return res;
}
getLocListByIndices(list: Iterable<number>): Iterable<Loc | null> {
const res: (Loc | null)[] = [];
for (const index of list) {
res.push(this.getLocByIndex(index));
}
return res;
}
getBlockByDataLoc(x: number, y: number): IBlockData<T> | null {
const bx = Math.floor(x / this.blockWidth);
const by = Math.floor(y / this.blockHeight);
if (!this.checkLocRange(bx, by)) return null;
const index = by * this.width + bx;
return this.blockMap.get(index) ?? null;
}
getBlockByDataIndex(index: number): IBlockData<T> | null {
const x = index % this.dataWidth;
const y = Math.floor(index / this.dataWidth);
return this.getBlockByDataLoc(x, y);
}
getIndicesByDataLocList(list: Iterable<Loc>): Set<number> {
const res = new Set<number>();
for (const { x, y } of list) {
const bx = Math.floor(x / this.blockWidth);
const by = Math.floor(y / this.blockHeight);
if (!this.checkLocRange(bx, by)) continue;
res.add(bx + by * this.width);
}
return res;
}
getIndicesByDataIndices(list: Iterable<number>): Set<number> {
const res = new Set<number>();
for (const index of list) {
const x = index % this.dataWidth;
const y = Math.floor(index / this.dataWidth);
const bx = Math.floor(x / this.blockWidth);
const by = Math.floor(y / this.blockHeight);
if (!this.checkLocRange(bx, by)) continue;
res.add(bx + by * this.width);
}
return res;
}
getBlocksByDataLocList(list: Iterable<Loc>): Set<IBlockData<T>> {
const res = new Set<IBlockData<T>>();
for (const { x, y } of list) {
const bx = Math.floor(x / this.blockWidth);
const by = Math.floor(y / this.blockHeight);
if (!this.checkLocRange(bx, by)) continue;
const index = bx + by * this.width;
const data = this.blockMap.get(index);
if (data) res.add(data);
}
return res;
}
getBlocksByDataIndices(list: Iterable<number>): Set<IBlockData<T>> {
const res = new Set<IBlockData<T>>();
for (const index of list) {
const x = index % this.dataWidth;
const y = Math.floor(index / this.dataWidth);
const bx = Math.floor(x / this.blockWidth);
const by = Math.floor(y / this.blockHeight);
if (!this.checkLocRange(bx, by)) continue;
const blockIndex = bx + by * this.width;
const data = this.blockMap.get(blockIndex);
if (data) res.add(data);
}
return res;
}
configSplitter(config: IBlockSplitterConfig): void {
this.splitDataWidth = config.dataWidth;
this.splitDataHeight = config.dataHeight;
this.splitBlockWidth = config.blockWidth;
this.splitBlockHeight = config.blockHeight;
}
private mapBlock(
x: number,
y: number,
realWidth: number,
width: number,
height: number,
fn: (block: IBlockInfo) => T
) {
const index = y * realWidth + x;
const block: IBlockInfo = {
index,
x,
y,
dataX: x * this.blockWidth,
dataY: y * this.blockHeight,
width,
height
};
const data = fn(block);
const blockData = new SplittedBlockData(this, block, data);
this.blockMap.set(index, blockData);
}
splitBlocks(mapFn: (block: IBlockInfo) => T): void {
this.blockMap.clear();
this.blockWidth = this.splitBlockWidth;
this.blockHeight = this.splitBlockHeight;
this.dataWidth = this.splitDataWidth;
this.dataHeight = this.splitDataHeight;
const restX = this.splitDataWidth % this.splitBlockWidth;
const restY = this.splitDataHeight % this.splitBlockHeight;
const width = Math.floor(this.splitDataWidth / this.splitBlockWidth);
const height = Math.floor(this.splitDataHeight / this.splitBlockHeight);
const hasXRest = restX > 0;
const hasYRest = restY > 0;
const realWidth = hasXRest ? width + 1 : width;
const bw = this.blockWidth;
const bh = this.blockHeight;
this.width = realWidth;
this.height = hasYRest ? height + 1 : height;
for (let ny = 0; ny < height; ny++) {
for (let nx = 0; nx < width; nx++) {
this.mapBlock(nx, ny, realWidth, bw, bh, mapFn);
}
}
if (hasXRest) {
for (let ny = 0; ny < height; ny++) {
this.mapBlock(width, ny, realWidth, restX, bh, mapFn);
}
}
if (hasYRest) {
for (let nx = 0; nx < width; nx++) {
this.mapBlock(nx, height, realWidth, bw, restY, mapFn);
}
}
if (hasXRest && hasYRest) {
this.mapBlock(width, height, realWidth, restX, restY, mapFn);
}
}
}
class SplittedBlockData<T> implements IBlockData<T>, ISearchable8Dir {
width: number;
height: number;
x: number;
y: number;
dataX: number;
dataY: number;
index: number;
data: T;
constructor(
readonly splitter: BlockSplitter<T>,
info: IBlockInfo,
data: T
) {
this.width = info.width;
this.height = info.height;
this.x = info.x;
this.y = info.y;
this.dataX = info.dataX;
this.dataY = info.dataY;
this.index = info.index;
this.data = data;
}
left(): IBlockData<T> | null {
return this.splitter.getBlockByLoc(this.x - 1, this.y);
}
right(): IBlockData<T> | null {
return this.splitter.getBlockByLoc(this.x + 1, this.y);
}
up(): IBlockData<T> | null {
return this.splitter.getBlockByLoc(this.x, this.y - 1);
}
down(): IBlockData<T> | null {
return this.splitter.getBlockByLoc(this.x, this.y + 1);
}
leftUp(): IBlockData<T> | null {
return this.splitter.getBlockByLoc(this.x - 1, this.y - 1);
}
leftDown(): IBlockData<T> | null {
return this.splitter.getBlockByLoc(this.x - 1, this.y + 1);
}
rightUp(): IBlockData<T> | null {
return this.splitter.getBlockByLoc(this.x + 1, this.y - 1);
}
rightDown(): IBlockData<T> | null {
return this.splitter.getBlockByLoc(this.x + 1, this.y + 1);
}
next(): IBlockData<T> | null {
return this.splitter.getBlockByIndex(this.index + 1);
}
}
@@ -1,2 +0,0 @@
/** 单个图块的实例化数据数量 */
export const INSTANCED_COUNT = 4 + 4 + 4 + 4;
@@ -1,109 +0,0 @@
import { MotaOffscreenCanvas2D, RenderItem } from '@motajs/render';
import { IGameMap } from '@user/data-base';
import { IMapRenderer } from './types';
import { ElementNamespace, ComponentInternalInstance } from 'vue';
import { CELL_HEIGHT, CELL_WIDTH, MAP_HEIGHT, MAP_WIDTH } from '../../shared';
import { IMapExtensionManager } from './extension';
export class MapRenderItem extends RenderItem {
/**
* @param layerState 地图状态对象
* @param renderer 地图渲染器对象
*/
constructor(
readonly layerState: IGameMap,
readonly renderer: IMapRenderer,
readonly exManager: IMapExtensionManager
) {
super(false);
renderer.setLayerState(layerState);
renderer.setCellSize(CELL_WIDTH, CELL_HEIGHT);
renderer.setRenderSize(MAP_WIDTH, MAP_HEIGHT);
// 元素被销毁时会自动删除所有的激励对象,所以不需要担心会内存泄漏
this.delegateExcitable(time => {
this.renderer.tick(time);
if (this.renderer.needUpdate()) {
this.update();
}
const text = exManager.textRenderer;
if (text) {
if (text.needResize) {
this.resizeTextRenderer(this.width, this.height);
}
if (text.needUpdate()) {
this.update();
}
}
});
}
private resizeTextRenderer(width: number, height: number) {
const ex = this.exManager.textRenderer;
if (!ex) return;
const ratio = this.highResolution ? devicePixelRatio : 1;
const scale = ratio * this.scale;
const w = width * scale;
const h = height * scale;
ex.resize(
w,
h,
w / this.renderer.renderWidth,
h / this.renderer.renderHeight
);
}
private sizeGL(width: number, height: number) {
const ratio = this.highResolution ? devicePixelRatio : 1;
const scale = ratio * this.scale;
const w = width * scale;
const h = height * scale;
this.renderer.setCanvasSize(w, h);
this.renderer.setViewport(0, 0, w, h);
if (this.exManager.textRenderer) {
this.exManager.textRenderer.resize(
w,
h,
w / this.renderer.renderWidth,
h / this.renderer.renderHeight
);
}
}
onResize(scale: number): void {
super.onResize(scale);
this.sizeGL(this.width, this.height);
}
size(width: number, height: number): void {
super.size(width, height);
this.sizeGL(width, height);
}
protected render(canvas: MotaOffscreenCanvas2D): void {
this.renderer.clear(true, true);
const map = this.renderer.render();
canvas.ctx.drawImage(map.canvas, 0, 0, canvas.width, canvas.height);
if (this.exManager.textRenderer) {
const text = this.exManager.textRenderer.render(map);
canvas.ctx.drawImage(text, 0, 0, canvas.width, canvas.height);
}
}
patchProp(
key: string,
prevValue: any,
nextValue: any,
namespace?: ElementNamespace,
parentComponent?: ComponentInternalInstance | null
): void {
switch (key) {
case 'layerState': {
this.renderer.setLayerState(nextValue);
break;
}
}
super.patchProp(key, prevValue, nextValue, namespace, parentComponent);
}
}
@@ -1,73 +0,0 @@
import {
IMapLayer,
IMapLayerHookController,
IMapLayerHooks
} from '@user/data-base';
import { IMapDoorRenderer } from './types';
import { IMapRenderer } from '../types';
import { sleep } from 'mutate-animate';
import { DOOR_ANIMATE_INTERVAL } from '../../../shared';
export class MapDoorRenderer implements IMapDoorRenderer {
/** 钩子控制器 */
readonly controller: IMapLayerHookController;
/** 动画间隔 */
private interval: number = DOOR_ANIMATE_INTERVAL;
constructor(
readonly renderer: IMapRenderer,
readonly layer: IMapLayer
) {
this.controller = layer.addHook(new MapDoorHook(this));
this.controller.load();
}
setAnimateInterval(interval: number): void {
this.interval = interval;
}
async openDoor(x: number, y: number): Promise<void> {
const status = this.renderer.getBlockStatus(this.layer, x, y);
if (!status) return;
const array = this.layer.getMapRef().array;
const index = y * this.layer.width + x;
const num = array[index];
const data = this.renderer.manager.getTile(num);
if (!data) return;
const frames = data.frames;
for (let i = 0; i < frames; i++) {
status.useSpecifiedFrame(i);
await sleep(this.interval);
}
}
async closeDoor(num: number, x: number, y: number): Promise<void> {
const data = this.renderer.manager.getTile(num);
if (!data) return;
const moving = this.renderer.addMovingBlock(this.layer, num, x, y);
const frames = data.frames;
for (let i = frames - 1; i >= 0; i--) {
moving.useSpecifiedFrame(i);
await sleep(this.interval);
}
moving.destroy();
}
destroy(): void {
this.controller.unload();
}
}
class MapDoorHook implements Partial<IMapLayerHooks> {
constructor(readonly renderer: MapDoorRenderer) {}
onOpenDoor(x: number, y: number): Promise<void> {
return this.renderer.openDoor(x, y);
}
onCloseDoor(num: number, x: number, y: number): Promise<void> {
return this.renderer.closeDoor(num, x, y);
}
}
@@ -1,560 +0,0 @@
import {
FaceDirection,
FaceGroup,
IFaceManager,
IObjectMover,
IObjectMoverHooks,
ObjectAnimDirection,
ObjectMoveStep,
ObjectMoveType,
TileType
} from '@user/data-common';
import { IHeroLocation, IHeroLocationHooks, IMapLayer } from '@user/data-base';
import { IMapRenderer, IMapRendererTicker, IMovingBlock } from '../types';
import { isNil } from 'lodash-es';
import { IFaceHandler, IHookController, logger } from '@motajs/common';
import { IMaterialFramedData } from '@user/client-base';
import { ITexture, ITextureSplitter, TextureRowSplitter } from '@motajs/render';
import { IMapHeroRenderer } from './types';
import { ExcitationCurve2D } from '@motajs/animate';
import { state } from '@user/data-state';
/** 默认的移动时长 */
const DEFAULT_TIME = 100;
interface IHeroRenderEntity {
/** 移动图块对象 */
readonly block: IMovingBlock;
/** 标识符,用于判定跟随者 */
readonly identifier: string;
/** 目标横坐标,移动时有效 */
targetX: number;
/** 目标纵坐标,移动时有效 */
targetY: number;
/** 当前的移动朝向 */
direction: FaceDirection;
/** 下一个跟随者的移动方向 */
nextDirection: FaceDirection;
/** 当前是否正在移动 */
moving: boolean;
/** 当前是否正在动画,移动跟动画要分开,有的操作比如跳跃就是在移动中但是没动画 */
animating: boolean;
/** 帧动画间隔 */
animateInterval: number;
/** 当一次动画时刻 */
lastAnimateTime: number;
/** 当前的动画帧数 */
animateFrame: number;
/** 移动的 `Promise`,移动完成时兑现,如果停止,则一直是兑现状态 */
promise: Promise<void>;
/** 勇士移动的动画方向 */
animateDirection: ObjectAnimDirection;
}
export class MapHeroRenderer implements IMapHeroRenderer {
private static readonly splitter: ITextureSplitter<number> =
new TextureRowSplitter();
/** 勇士位置钩子 */
readonly locationController: IHookController<IHeroLocationHooks>;
/** 勇士移动钩子 */
readonly moverController: IHookController<IObjectMoverHooks<IHeroLocation>>;
/** 派生自 `faceManager` 的贴图四向朝向处理器 */
readonly dir4: IFaceHandler<FaceDirection>;
/** 勇士每个朝向的贴图对象 */
readonly textureMap: Map<FaceDirection, IMaterialFramedData> = new Map();
/** 勇士渲染实体,与 `entities[0]` 同引用 */
readonly heroEntity: IHeroRenderEntity;
/**
* 渲染实体,索引 0 表示勇士,后续索引依次表示跟随的跟随者。
* 整体是一个状态机,而且下一个跟随者只与上一个跟随者有关,下一个跟随者移动的方向就是上一个跟随者上一步移动后指向的方向。
*/
readonly entities: IHeroRenderEntity[] = [];
/** 每帧执行的帧动画对象 */
readonly ticker: IMapRendererTicker;
constructor(
readonly renderer: IMapRenderer,
readonly layer: IMapLayer,
readonly hero: IHeroLocation,
readonly faceManager: IFaceManager
) {
this.dir4 = faceManager.get<FaceDirection>(FaceGroup.Dir4)!;
this.locationController = hero.addHook(new MapHeroLocationHook(this));
this.locationController.load();
this.moverController = hero.mover.addHook(new MapHeroMoverHook(this));
this.moverController.load();
const moving = this.addHeroMoving(renderer, layer, hero);
const heroEntity: IHeroRenderEntity = {
block: moving,
identifier: '',
targetX: hero.x,
targetY: hero.y,
direction: hero.getCurrentFaceDirection(),
nextDirection: FaceDirection.Unknown,
moving: false,
animating: false,
animateInterval: 0,
lastAnimateTime: 0,
animateFrame: 0,
promise: Promise.resolve(),
animateDirection: ObjectAnimDirection.Forward
};
this.heroEntity = heroEntity;
this.entities.push(heroEntity);
this.ticker = renderer.requestTicker(time => this.tick(time));
}
/**
* 添加勇士对应的移动图块
* @param renderer 渲染器
* @param layer 图块所属图层
* @param hero 勇士状态对象
*/
private addHeroMoving(
renderer: IMapRenderer,
layer: IMapLayer,
hero: IHeroLocation
) {
// @ts-expect-error 需要重构(贴图别名来源属 D-18,待用户先改数据端后处理)
const imageAlias = hero.image;
if (isNil(imageAlias)) {
logger.warn(88);
return renderer.addMovingBlock(layer, 0, hero.x, hero.y);
}
const image = this.renderer.manager.getImageByAlias(imageAlias);
if (!image) {
logger.warn(89, imageAlias);
return renderer.addMovingBlock(layer, 0, hero.x, hero.y);
}
this.updateHeroTexture(image);
const tex = this.textureMap.get(
this.dir4.degrade(hero.getCurrentFaceDirection())
);
if (!tex) {
return renderer.addMovingBlock(layer, 0, hero.x, hero.y);
}
const block = renderer.addMovingBlock(layer, tex, hero.x, hero.y);
block.useSpecifiedFrame(0);
return block;
}
/**
* 更新勇士贴图
* @param image 勇士使用的贴图,包含四个方向
*/
private updateHeroTexture(image: ITexture) {
const textures = [
...image.split(MapHeroRenderer.splitter, image.height / 4)
];
if (textures.length !== 4) {
logger.warn(90, hero.image);
return;
}
const faceList = [
FaceDirection.Down,
FaceDirection.Left,
FaceDirection.Right,
FaceDirection.Up
];
faceList.forEach((v, i) => {
const dirImage = textures[i];
const data: IMaterialFramedData = {
offset: dirImage.width / 4,
texture: dirImage,
tileType: TileType.Unknown,
frames: 4,
defaultFrame: 0
};
this.textureMap.set(v, data);
});
}
private tick(time: number) {
this.entities.forEach(v => {
if (v.animating) {
const dt = time - v.lastAnimateTime;
if (dt > v.animateInterval) {
if (v.animateDirection === ObjectAnimDirection.Forward) {
v.animateFrame++;
} else {
v.animateFrame--;
if (v.animateFrame < 0) {
// 小于 0,则加上帧数的整数倍,就写个 10000 倍吧
v.animateFrame += v.block.texture.frames * 10000;
}
}
v.lastAnimateTime = time;
v.block.useSpecifiedFrame(v.animateFrame);
}
} else {
if (v.animateFrame !== 0) {
v.animateFrame = 0;
v.block.useSpecifiedFrame(0);
}
}
});
}
setImage(image: ITexture): void {
this.updateHeroTexture(image);
const tex = this.textureMap.get(
this.dir4.degrade(this.hero.getCurrentFaceDirection())
);
if (!tex) return;
this.heroEntity.block.setTexture(tex);
}
setAlpha(alpha: number): void {
this.heroEntity.block.setAlpha(alpha);
}
setPosition(x: number, y: number): void {
this.entities.forEach(v => {
v.block.setPos(x, y);
v.nextDirection = FaceDirection.Unknown;
});
}
/**
* 移动指定渲染实体,不会影响其他渲染实体。多次调用时会按顺序依次移动
* @param entity 渲染实体
* @param direction 移动方向
* @param time 移动时长
*/
private moveEntity(
entity: IHeroRenderEntity,
direction: FaceDirection,
time: number
) {
const { x: dx, y: dy } =
this.hero.mover.faceHandler.movement(direction);
if (dx === 0 && dy === 0) return;
const block = entity.block;
const tx = block.x + dx;
const ty = block.y + dy;
const nextTile = state.roleFace.getFaceOf(block.tile, direction);
const nextTex = this.renderer.manager.getTile(
nextTile?.identifier ?? block.tile
);
entity.animateInterval = time;
entity.promise = entity.promise.then(async () => {
entity.moving = true;
entity.animating = true;
entity.direction = direction;
if (nextTex) block.setTexture(nextTex);
await block.lineTo(tx, ty, time);
entity.nextDirection = entity.direction;
});
}
/**
* 生成跳跃曲线
* @param dx 横向偏移量
* @param dy 纵向偏移量
*/
private generateJumpFn(dx: number, dy: number): ExcitationCurve2D {
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];
};
}
/**
* 将指定渲染实体跳跃至目标点,多次调用时会按顺序依次执行,可以与 `moveEntity` 混用
* @param entity 渲染实体
* @param x 目标横坐标
* @param y 目标纵坐标
* @param time 跳跃时长
*/
private jumpEntity(
entity: IHeroRenderEntity,
x: number,
y: number,
time: number
) {
const block = entity.block;
entity.promise = entity.promise.then(async () => {
const dx = block.x - x;
const dy = block.y - y;
const fn = this.generateJumpFn(dx, dy);
entity.moving = true;
entity.animating = false;
entity.animateFrame = 0;
await block.moveRelative(fn, time);
});
}
startMove(): void {
this.heroEntity.moving = true;
this.heroEntity.animating = true;
this.heroEntity.lastAnimateTime = this.ticker.timestamp;
}
private endEntityMoving(entity: IHeroRenderEntity) {
entity.moving = false;
entity.animating = false;
entity.animateFrame = 0;
entity.block.useSpecifiedFrame(0);
}
async waitMoveEnd(): Promise<void> {
await Promise.all(this.entities.map(v => v.promise));
this.entities.forEach(v => this.endEntityMoving(v));
}
stopMove(): void {
this.entities.forEach(v => {
v.block.endMoving();
this.endEntityMoving(v);
});
}
async move(direction: FaceDirection, time: number): Promise<void> {
this.moveEntity(this.heroEntity, direction, time);
for (let i = 1; i < this.entities.length; i++) {
const last = this.entities[i - 1];
this.moveEntity(this.entities[i], last.nextDirection, time);
}
await Promise.all(this.entities.map(v => v.promise));
}
async jumpTo(
x: number,
y: number,
time: number,
waitFollower: boolean
): Promise<void> {
// 首先要把所有的跟随者移动到勇士所在位置
for (let i = 1; i < this.entities.length; i++) {
// 对于每一个跟随者,需要向前遍历每一个跟随者,然后朝向移动,这样就可以聚集在一起了
const now = this.entities[i];
for (let j = i - 1; j >= 0; j--) {
const last = this.entities[j];
this.moveEntity(now, last.nextDirection, DEFAULT_TIME);
}
}
this.entities.forEach(v => {
this.jumpEntity(v, x, y, time);
});
if (waitFollower) {
await Promise.all(this.entities.map(v => v.promise));
} else {
return this.heroEntity.promise;
}
}
addFollower(image: number, id: string): void {
const last = this.entities[this.entities.length - 1];
if (last.moving) {
logger.warn(92);
return;
}
const degraded = this.dir4.degrade(last.nextDirection);
const nowFace =
degraded === FaceDirection.Unknown ? FaceDirection.Down : degraded;
const faced = state.roleFace.getFaceOf(image, nowFace);
const tex = this.renderer.manager.getTile(faced?.face ?? image);
if (!tex) {
logger.warn(91, image.toString());
return;
}
const handler = this.hero.mover.faceHandler;
const { x: dxn, y: dyn } = handler.movement(last.nextDirection);
const { x: dx, y: dy } = handler.movement(last.direction);
const x = last.block.x - dxn;
const y = last.block.y - dyn;
const moving = this.renderer.addMovingBlock(this.layer, tex, x, y);
const entity: IHeroRenderEntity = {
block: moving,
identifier: id,
targetX: last.targetX - dx,
targetY: last.targetY - dy,
direction: nowFace,
nextDirection: FaceDirection.Unknown,
moving: false,
animating: false,
animateInterval: 0,
lastAnimateTime: 0,
animateFrame: 0,
promise: Promise.resolve(),
animateDirection: ObjectAnimDirection.Forward
};
moving.useSpecifiedFrame(0);
this.entities.push(entity);
}
async removeFollower(follower: string, animate: boolean): Promise<void> {
const index = this.entities.findIndex(v => v.identifier === follower);
if (index === -1) return;
if (this.entities[index].moving) {
logger.warn(93);
return;
}
if (index === this.entities.length - 1) {
this.entities[index].block.destroy();
this.entities.splice(index, 1);
return;
}
// 展示动画
if (animate) {
for (let i = index + 1; i < this.entities.length; i++) {
const last = this.entities[i - 1];
const moving = this.entities[i];
this.moveEntity(moving, last.nextDirection, DEFAULT_TIME);
}
this.entities[index].block.destroy();
this.entities.splice(index, 1);
await Promise.all(this.entities.map(v => v.promise));
return;
}
// 不展示动画
for (let i = index + 1; i < this.entities.length; i++) {
const last = this.entities[i - 1];
const moving = this.entities[i];
moving.block.setPos(last.block.x, last.block.y);
const nextFace = state.roleFace.getFaceOf(
moving.block.tile,
last.nextDirection
);
if (!nextFace) continue;
const tile = this.renderer.manager.getTile(nextFace.identifier);
if (!tile) continue;
moving.block.setTexture(tile);
moving.direction = last.nextDirection;
moving.nextDirection = moving.direction;
}
this.entities[index].block.destroy();
this.entities.splice(index, 1);
}
removeAllFollowers(): void {
for (let i = 1; i < this.entities.length; i++) {
this.entities[i].block.destroy();
}
this.entities.length = 1;
}
setFollowerAlpha(identifier: string, alpha: number): void {
const follower = this.entities.find(v => v.identifier === identifier);
if (!follower) return;
follower.block.setAlpha(alpha);
}
setHeroAnimateDirection(direction: ObjectAnimDirection): void {
this.heroEntity.animateDirection = direction;
}
turn(direction?: FaceDirection): void {
const next = isNil(direction)
? this.dir4.next(this.heroEntity.direction)
: direction;
const tex = this.textureMap.get(next);
if (tex) {
this.heroEntity.block.setTexture(tex);
this.heroEntity.direction = next;
}
}
destroy() {
this.locationController.unload();
this.moverController.unload();
}
}
class MapHeroLocationHook implements Partial<IHeroLocationHooks> {
constructor(readonly hero: MapHeroRenderer) {}
onSetImage(image: ImageIds): void {
const texture = this.hero.renderer.manager.getImageByAlias(image);
if (!texture) {
logger.warn(89, hero.image);
return;
}
this.hero.setImage(texture);
}
onSetPos(x: number, y: number): void {
this.hero.setPosition(x, y);
}
onSetAlpha(alpha: number): void {
this.hero.setAlpha(alpha);
}
onAddFollower(follower: number, identifier: string): void {
this.hero.addFollower(follower, identifier);
}
onRemoveFollower(identifier: string, animate: boolean): void {
this.hero.removeFollower(identifier, animate);
}
onRemoveAllFollowers(): void {
this.hero.removeAllFollowers();
}
onSetFollowerAlpha(identifier: string, alpha: number): void {
this.hero.setFollowerAlpha(identifier, alpha);
}
}
class MapHeroMoverHook implements Partial<IObjectMoverHooks<IHeroLocation>> {
constructor(readonly hero: MapHeroRenderer) {}
async onMoveStart(): Promise<void> {
this.hero.startMove();
}
async onMoveEnd(): Promise<void> {
await this.hero.waitMoveEnd();
}
async onStepEnd(
_code: number,
step: Readonly<ObjectMoveStep>,
tile: IHeroLocation,
mover: IObjectMover<IHeroLocation>
): Promise<void> {
this.hero.setHeroAnimateDirection(mover.currAnimDir);
switch (step.type) {
case ObjectMoveType.Dir:
return this.hero.move(step.move, mover.currentSpeed);
case ObjectMoveType.DirFace:
this.hero.turn(step.face);
return this.hero.move(step.move, mover.currentSpeed);
case ObjectMoveType.Special:
return this.hero.move(mover.moveDirection, mover.currentSpeed);
case ObjectMoveType.Face:
this.hero.turn(step.value);
break;
case ObjectMoveType.Teleport:
this.hero.setPosition(tile.x, tile.y);
break;
case ObjectMoveType.Jump:
return this.hero.jumpTo(
tile.x,
tile.y,
mover.currentSpeed,
false
);
case ObjectMoveType.AnimDir:
this.hero.setHeroAnimateDirection(step.dir);
break;
case ObjectMoveType.Speed:
break;
}
}
onSetFaceDir(dir: FaceDirection): void {
this.hero.turn(dir);
}
}
@@ -1,3 +0,0 @@
export * from './hero';
export * from './manager';
export * from './types';
@@ -1,92 +0,0 @@
import { IFaceManager } from '@user/data-common';
import { IHeroLocation, IMapLayer } from '@user/data-base';
import {
IMapDoorRenderer,
IMapExtensionManager,
IMapHeroRenderer
} from './types';
import { IMapRenderer } from '../types';
import { MapHeroRenderer } from './hero';
import { logger } from '@motajs/common';
import { MapDoorRenderer } from './door';
import { OnMapTextRenderer } from './text';
import { IOnMapTextRenderer } from './types';
export class MapExtensionManager implements IMapExtensionManager {
/** 勇士状态至勇士渲染器的映射 */
readonly heroMap: Map<IHeroLocation, IMapHeroRenderer> = new Map();
/** 地图图层到门渲染器的映射 */
readonly doorMap: Map<IMapLayer, IMapDoorRenderer> = new Map();
/** 单例的文字渲染拓展(独立图层) */
textRenderer: IOnMapTextRenderer | null = null;
constructor(readonly renderer: IMapRenderer) {}
addHero(
state: IHeroLocation,
layer: IMapLayer,
faceManager: IFaceManager
): IMapHeroRenderer | null {
if (this.heroMap.has(state)) {
logger.error(45, 'hero renderer');
return null;
}
const heroRenderer = new MapHeroRenderer(
this.renderer,
layer,
state,
faceManager
);
this.heroMap.set(state, heroRenderer);
return heroRenderer;
}
removeHero(state: IHeroLocation): void {
const renderer = this.heroMap.get(state);
if (!renderer) return;
renderer.destroy();
this.heroMap.delete(state);
}
addDoor(layer: IMapLayer): IMapDoorRenderer | null {
if (this.doorMap.has(layer)) {
logger.error(45, 'door renderer');
return null;
}
const doorRenderer = new MapDoorRenderer(this.renderer, layer);
this.doorMap.set(layer, doorRenderer);
return doorRenderer;
}
addText(): IOnMapTextRenderer | null {
if (this.textRenderer) {
logger.error(45, 'on-map text renderer');
return null;
}
const r = new OnMapTextRenderer(this.renderer);
this.textRenderer = r;
return r;
}
removeText(): void {
if (!this.textRenderer) return;
this.textRenderer.destroy();
this.textRenderer = null;
}
removeDoor(layer: IMapLayer): void {
const renderer = this.doorMap.get(layer);
if (!renderer) return;
renderer.destroy();
this.doorMap.delete(layer);
}
destroy(): void {
this.heroMap.forEach(v => void v.destroy());
this.doorMap.forEach(v => void v.destroy());
this.heroMap.clear();
this.doorMap.clear();
this.textRenderer?.destroy();
this.textRenderer = null;
}
}
@@ -1,280 +0,0 @@
import { logger } from '@motajs/common';
import {
IBlockData,
IBlockSplitter,
IMapRenderer,
IMapRenderResult,
IMapVertexBlock
} from '../types';
import { IMapTextArea, IMapTextRenderable, IOnMapTextRenderer } from './types';
import { ITransformUpdatable, Transform } from '@motajs/render';
export class OnMapTextRenderer
implements IOnMapTextRenderer, ITransformUpdatable<Transform>
{
/** 画布元素 */
readonly canvas: HTMLCanvasElement;
/** 画布 Canvas2D 上下文 */
readonly ctx: CanvasRenderingContext2D;
needResize: boolean = true;
/** 分块上附着文本区域的标识符 */
private readonly attachSymbol: symbol = Symbol('onMapTextAreas');
/** 是否有内容发生变化,需要更新 */
private dirty: boolean = false;
/** 分块对象 */
private readonly block: IBlockSplitter<IMapVertexBlock>;
/** 变换矩阵 */
private readonly transform: Transform;
constructor(readonly renderer: IMapRenderer) {
this.canvas = document.createElement('canvas');
this.ctx = this.canvas.getContext('2d')!;
this.block = renderer.vertex.block;
this.transform = renderer.transform;
this.ctx.lineWidth = 2;
this.transform.bind(this);
}
updateTransform() {
this.dirty = true;
}
/**
* 标记为需要更新
*/
markDirty(): void {
this.dirty = true;
}
resize(
width: number,
height: number,
scaleX: number,
scaleY: number
): void {
this.canvas.width = width;
this.canvas.height = height;
this.ctx.setTransform(1, 0, 0, 1, 0, 0);
this.ctx.translate(width / 2, height / 2);
this.ctx.scale(1, -1);
this.ctx.scale(scaleX, scaleY);
this.dirty = true;
this.needResize = false;
}
getBlockByLoc(x: number, y: number): Readonly<IMapTextArea> | null {
const index = y * this.renderer.mapWidth + x;
// 首先尝试使用分块系统获取对应分块并从分块附着数据读取
const blockData = this.block.getBlockByDataIndex(index);
if (blockData) {
const map = blockData.data.getAttachedData<
Map<number, MapTextArea>
>(this.attachSymbol);
if (map) return map.get(index) ?? null;
}
return null;
}
getBlockByIndex(index: number): Readonly<IMapTextArea> | null {
const blockData = this.block.getBlockByDataIndex(index);
if (blockData) {
const map = blockData.data.getAttachedData<
Map<number, MapTextArea>
>(this.attachSymbol);
if (map) return map.get(index) || null;
}
return null;
}
render(data: IMapRenderResult): HTMLCanvasElement {
if (!this.dirty) return this.canvas;
const ctx = this.ctx;
const { renderWidth, renderHeight } = this.renderer;
// clear
ctx.clearRect(
-renderWidth / 2,
-renderHeight / 2,
renderWidth,
renderHeight
);
ctx.save();
// apply transform matrix
const [a, b, , c, d, , e, f] = this.transform.mat;
ctx.transform(
a,
b,
c,
d,
(e * renderWidth) / 2,
(f * renderHeight) / 2
);
// 由于 WebGL 坐标系与 Canvas2D 坐标系不一样,所以还需要变换一下
ctx.scale(1, -1);
// draw text in each block
for (const blk of data.area.blockList) {
const map = blk.data.getAttachedData<Map<number, MapTextArea>>(
this.attachSymbol
);
if (!map) continue;
for (const area of map.values()) {
const baseX = area.mapX * this.renderer.cellWidth;
const baseY = area.mapY * this.renderer.cellHeight;
for (const renderable of area.getRenderables()) {
const x = baseX + (renderable.px ?? 0) - renderWidth / 2;
const y = renderHeight / 2 - (baseY + (renderable.py ?? 0));
ctx.font = renderable.font.string();
ctx.textAlign = renderable.textAlign ?? 'left';
ctx.textBaseline = renderable.textBaseline ?? 'top';
if (renderable.stroke) {
ctx.strokeStyle = renderable.strokeStyle ?? 'black';
ctx.strokeText(renderable.text, x, -y);
}
if (renderable.fill) {
ctx.fillStyle = renderable.fillStyle ?? 'white';
ctx.fillText(renderable.text, x, -y);
}
}
}
}
this.dirty = false;
ctx.restore();
return this.canvas;
}
/**
* 获取分块所附着的文字数据
* @param blockData 分块数据
*/
private getAttachedMap(
blockData: IBlockData<IMapVertexBlock>
): Map<number, MapTextArea> {
const map = blockData.data.getAttachedData<Map<number, MapTextArea>>(
this.attachSymbol
);
if (map) return map;
else {
const map = new Map();
blockData.data.attach(this.attachSymbol, map);
return map;
}
}
requireBlockArea(x: number, y: number): Readonly<IMapTextArea> | null {
const index = y * this.renderer.mapWidth + x;
// try to find corresponding block by data index
const blockData = this.block.getBlockByDataIndex(index);
if (blockData) {
const map = this.getAttachedMap(blockData);
const exist = map.get(index);
if (exist) return exist;
const area = new MapTextArea(this, x, y);
map.set(index, area);
this.markDirty();
return area;
} else {
logger.error(47);
return null;
}
}
needUpdate(): boolean {
return this.dirty;
}
clear(): void {
// 清理所有附着在分块上的文本区域
for (const b of this.block.iterateBlocks()) {
const blk = b.data;
const map = blk.getAttachedData<Map<number, MapTextArea>>(
this.attachSymbol
);
if (map) {
for (const area of map.values()) area.clear();
blk.deleteAttachedData(this.attachSymbol);
}
}
this.dirty = true;
}
destroy(): void {
this.transform.unbind(this);
this.clear();
// the canvas and context references are left intact; consumers may
// discard the renderer instance to allow GC. We don't detach the
// canvas from any DOM since ownership is external.
}
}
class MapTextArea implements IMapTextArea {
readonly index: number;
// maintain both a set for quick membership checks and a map for index lookup
private renderableSet: Set<IMapTextRenderable> = new Set();
private renderableMap: Map<number, IMapTextRenderable> = new Map();
private reverseMap: Map<IMapTextRenderable, number> = new Map();
private nextRenderableIndex: number = 1;
/**
* 获取本区域的所有可渲染对象,用于绘制阶段
*/
getRenderables(): Iterable<IMapTextRenderable> {
return this.renderableSet;
}
constructor(
readonly renderer: OnMapTextRenderer,
public readonly mapX: number,
public readonly mapY: number
) {
this.index = mapY * renderer.renderer.mapWidth + mapX;
}
addTextRenderable(renderable: IMapTextRenderable): number {
const idx = this.nextRenderableIndex++;
this.renderableSet.add(renderable);
this.renderableMap.set(idx, renderable);
this.reverseMap.set(renderable, idx);
this.renderer.markDirty();
return idx;
}
removeTextRenderable(renderable: IMapTextRenderable): void {
const idx = this.reverseMap.get(renderable);
if (idx !== void 0) {
this.renderableSet.delete(renderable);
this.renderableMap.delete(idx);
this.reverseMap.delete(renderable);
this.renderer.markDirty();
}
}
removeTextRenderableByIndex(index: number): void {
const obj = this.renderableMap.get(index);
if (obj !== void 0) {
this.renderableMap.delete(index);
this.renderableSet.delete(obj);
this.reverseMap.delete(obj);
this.renderer.markDirty();
}
}
clear(): void {
if (this.renderableSet.size > 0) {
this.renderableSet.clear();
this.renderableMap.clear();
this.reverseMap.clear();
this.renderer.markDirty();
}
}
}
@@ -1,247 +0,0 @@
import { ITexture, Font } from '@motajs/render';
import { IFaceManager } from '@user/data-common';
import { IHeroLocation, IMapLayer } from '@user/data-base';
import { IMapRenderResult } from '../types';
export interface IMapExtensionManager {
/** 勇士状态至勇士渲染器的映射 */
readonly heroMap: Map<IHeroLocation, IMapHeroRenderer>;
/** 地图图层到门渲染器的映射 */
readonly doorMap: Map<IMapLayer, IMapDoorRenderer>;
/** 单例的文字渲染拓展(独立图层) */
readonly textRenderer: IOnMapTextRenderer | null;
/**
* 添加勇士渲染拓展
* @param state 勇士状态
* @param layer 勇士所在图层
*/
addHero(
state: IHeroLocation,
layer: IMapLayer,
faceManager: IFaceManager
): IMapHeroRenderer | null;
/**
* 移除勇士渲染拓展
* @param state 勇士状态
*/
removeHero(state: IHeroLocation): void;
/**
* 添加开门动画拓展
*/
addDoor(layer: IMapLayer): IMapDoorRenderer | null;
/**
* 移除开门动画拓展
*/
removeDoor(layer: IMapLayer): void;
/**
* 添加文字渲染拓展
*/
addText(): IOnMapTextRenderer | null;
/**
* 移除文字渲染拓展
*/
removeText(): void;
/**
* 摧毁这个拓展管理对象,释放相关资源
*/
destroy(): void;
}
export interface IMapHeroRenderer {
/**
* 设置勇士图片
* @param image 勇士使用的图片
*/
setImage(image: ITexture): void;
/**
* 添加跟随者
* @param image 跟随者图块数字
* @param id 跟随者的 id,用于删除操作
*/
addFollower(image: number, id: string): void;
/**
* 取消跟随者
* @param follower 跟随者的 id
* @param animate 填 `true` 的话,如果删除了中间的跟随者,后续跟随者会使用移动动画移动到下一格,否则瞬移至下一格
*/
removeFollower(follower: string, animate: boolean): Promise<void>;
/**
* 移除所有跟随者
*/
removeAllFollowers(): void;
/**
* 设置勇士不透明度
* @param alpha 不透明度
*/
setAlpha(alpha: number): void;
/**
* 设置跟随者的不透明度
* @param identifier 跟随者标识符
* @param alpha 跟随者不透明度
*/
setFollowerAlpha(identifier: string, alpha: number): void;
/**
* 摧毁这个勇士渲染拓展,释放相关资源
*/
destroy(): void;
}
export interface IMapDoorRenderer {
/**
* 开启指定位置的门,播放开门动画
* @param x 门横坐标
* @param y 门纵坐标
*/
openDoor(x: number, y: number): Promise<void>;
/**
* 在指定位置执行关门动画
* @param num 门图块数字
* @param x 门横坐标
* @param y 门纵坐标
*/
closeDoor(num: number, x: number, y: number): Promise<void>;
/**
* 设置开关门动画两帧之间的间隔
* @param interval 开门动画间隔
*/
setAnimateInterval(interval: number): void;
/**
* 摧毁这个门动画拓展,释放相关资源
*/
destroy(): void;
}
export interface IMapTextRenderable {
/** 文本内容 */
readonly text: string;
/** 文本字体 */
readonly font: Font;
/** 是否填充 */
readonly fill?: boolean;
/** 是否描边 */
readonly stroke?: boolean;
/** 文本填充样式 */
readonly fillStyle?: CanvasStyle;
/** 文本描边样式 */
readonly strokeStyle?: CanvasStyle;
/** 文本横坐标,注意 {@link IMapTextArea.addTextRenderable} 的相对关系 */
readonly px?: number;
/** 文本纵坐标,注意 {@link IMapTextArea.addTextRenderable} 的相对关系 */
readonly py?: number;
/** 文本横向对齐方式 */
readonly textAlign?: CanvasTextAlign;
/** 文本纵向对齐方式 */
readonly textBaseline?: CanvasTextBaseline;
}
export interface IMapTextRequested {
/**
* 申请更新指定的图块
* @param blocks 需要更新数据的图块列表
*/
requestBlocks(blocks: IMapTextArea[]): void;
}
export interface IMapTextArea {
/** 图块在地图上的索引 */
readonly index: number;
/** 图块横坐标 */
readonly mapX: number;
/** 图块纵坐标 */
readonly mapY: number;
/**
* 添加文字可渲染对象。可渲染对象的坐标相对于图块,而非地图。
* @param renderable 可渲染对象
* @returns 添加的可渲染对象的唯一索引标识符
*/
addTextRenderable(renderable: IMapTextRenderable): number;
/**
* 移除指定的文字可渲染对象
* @param renderable 可渲染对象
*/
removeTextRenderable(renderable: IMapTextRenderable): void;
/**
* 根据可渲染对象的索引标识符移除文字的可渲染对象
* @param index 可渲染对象对应的索引标识符
*/
removeTextRenderableByIndex(index: number): void;
/**
* 清除本图块的所有文字可渲染对象
*/
clear(): void;
}
export interface IOnMapTextRenderer {
/** 是否需要修改画布大小 */
readonly needResize: boolean;
/**
* 修改画布的缩放比例,传入的参数包含 `devicePixelRatio` 以及渲染器自身缩放比例
* @param width 画布宽度
* @param height 画布高度
* @param scaleX 画布横向比例
* @param scaleY 画布纵向比例
*/
resize(width: number, height: number, scaleX: number, scaleY: number): void;
/**
* 渲染地图文字,返回的画布就是文字画到的画布
*/
render(data: IMapRenderResult): HTMLCanvasElement;
/**
* 申请指定图块坐标的文字管理对象,如果该点已被申请,则会使用已申请的对象
* @param x 图块横坐标
* @param y 图块纵坐标
* @returns 申请的文字管理对象,如果申请的坐标不在地图上,则会返回 `null`
*/
requireBlockArea(x: number, y: number): Readonly<IMapTextArea> | null;
/**
* 根据图块坐标获取已申请的文字管理对象,如果未申请则返回 `null`
* @param x 图块横坐标
* @param y 图块纵坐标
*/
getBlockByLoc(x: number, y: number): Readonly<IMapTextArea> | null;
/**
* 根据索引获取已申请的文字管理对象,如果未申请则返回 `null`
* @param index 管理对象索引
*/
getBlockByIndex(index: number): Readonly<IMapTextArea> | null;
/**
* 判断是否需要更新
*/
needUpdate(): boolean;
/**
* 清空所有文字内容
*/
clear(): void;
/**
* 摧毁这个文字渲染对象,释放相关资源
*/
destroy(): void;
}
@@ -1,11 +0,0 @@
export * from './extension';
export * from './block';
export * from './constant';
export * from './element';
export * from './moving';
export * from './renderer';
export * from './status';
export * from './types';
export * from './vertex';
export * from './viewport';
@@ -1,268 +0,0 @@
import { linear, TimingFn } from 'mutate-animate';
import { IMapRenderer, IMapVertexGenerator, IMovingBlock } from './types';
import { IMaterialFramedData, ITextureManager } from '@user/client-base';
import { logger } from '@motajs/common';
import { IMapLayer } from '@user/data-base';
import { DynamicBlockStatus } from './status';
export interface IMovingRenderer {
/** 素材管理器 */
readonly manager: ITextureManager;
/** 顶点数组生成器 */
readonly vertex: IMapVertexGenerator;
/**
* 获得当前时间戳
*/
getTimestamp(): number;
/**
* 删除指定的移动图块对象
* @param block 移动图块对象
*/
deleteMoving(block: IMovingBlock): void;
}
export class MovingBlock extends DynamicBlockStatus implements IMovingBlock {
readonly tile: number;
readonly renderer: IMovingRenderer;
readonly layer: IMapLayer;
texture: IMaterialFramedData;
index: number;
x: number = 0;
y: number = 0;
/** 当前动画开始的时刻 */
private startTime: number = 0;
/** 是否是直线动画 */
private line: boolean = false;
/** 是否是相对模式 */
private relative: boolean = false;
/** 目标横坐标 */
private targetX: number = 0;
/** 目标纵坐标 */
private targetY: number = 0;
/** 直线移动的横坐标增量 */
private dx: number = 0;
/** 直线移动的纵坐标增量 */
private dy: number = 0;
/** 动画时长 */
private time: number = 0;
/** 速率曲线 */
private timing: TimingFn = () => 0;
/** 移动轨迹曲线 */
private curve: TimingFn<2> = () => [0, 0];
/** 动画开始时横坐标 */
private startX: number = 0;
/** 动画开始时纵坐标 */
private startY: number = 0;
/** 当前动画是否已经结束 */
private end: boolean = true;
/** 是否通过 `setPos` 设置了位置 */
private posUpdated: boolean = false;
/** 兑现函数 */
private promiseFunc: () => void = () => {};
constructor(
renderer: IMovingRenderer & IMapRenderer,
index: number,
layer: IMapLayer,
block: number | IMaterialFramedData
) {
super(layer, renderer.vertex, index);
this.renderer = renderer;
this.index = index;
this.layer = layer;
if (typeof block === 'number') {
this.texture = renderer.manager.getTile(block)!;
this.tile = block;
} else {
if (!renderer.manager.assetContainsTexture(block.texture)) {
logger.error(34);
}
if (renderer.getOffsetIndex(block.offset) === -1) {
logger.error(41);
}
this.texture = block;
this.tile = -1;
}
}
setPos(x: number, y: number): void {
if (!this.end) return;
this.x = x;
this.y = y;
this.posUpdated = true;
}
setTexture(texture: IMaterialFramedData): void {
if (texture === this.texture) return;
this.texture = texture;
this.renderer.vertex.updateMoving(this, true);
}
lineTo(
x: number,
y: number,
time: number,
timing?: TimingFn
): Promise<this> {
if (!this.end) return Promise.resolve(this);
this.startX = this.x;
this.startY = this.y;
this.targetX = x;
this.targetY = y;
this.dx = x - this.x;
this.dy = y - this.y;
this.time = time;
this.relative = false;
this.startTime = this.renderer.getTimestamp();
if (time === 0) {
this.x = x;
this.y = y;
this.end = true;
return Promise.resolve(this);
}
this.end = false;
this.timing = timing ?? linear();
this.line = true;
return new Promise(res => {
this.promiseFunc = () => res(this);
});
}
moveAs(curve: TimingFn<2>, time: number, timing?: TimingFn): Promise<this> {
if (!this.end) return Promise.resolve(this);
this.time = time;
this.line = false;
this.relative = false;
this.startX = this.x;
this.startY = this.y;
this.startTime = this.renderer.getTimestamp();
if (time === 0) {
const [tx, ty] = curve(1);
this.x = tx;
this.y = ty;
this.end = true;
return Promise.resolve(this);
}
this.end = false;
this.timing = timing ?? linear();
this.curve = curve;
return new Promise(res => {
this.promiseFunc = () => res(this);
});
}
moveRelative(
curve: TimingFn<2>,
time: number,
timing?: TimingFn
): Promise<this> {
if (!this.end) return Promise.resolve(this);
this.time = time;
this.line = false;
this.relative = true;
this.startX = this.x;
this.startY = this.y;
this.startTime = this.renderer.getTimestamp();
if (time === 0) {
const [tx, ty] = curve(1);
this.x = tx + this.startX;
this.y = ty + this.startY;
this.end = true;
return Promise.resolve(this);
}
this.end = false;
this.timing = timing ?? linear();
this.curve = curve;
return new Promise(res => {
this.promiseFunc = () => res(this);
});
}
stepMoving(timestamp: number): boolean {
if (this.end) {
if (this.posUpdated) {
this.posUpdated = false;
return true;
}
return false;
}
const dt = timestamp - this.startTime;
if (this.line) {
if (dt > this.time) {
this.x = this.targetX;
this.y = this.targetY;
this.end = true;
this.promiseFunc();
return true;
} else {
const timeProgress = dt / this.time;
const progress = this.timing(timeProgress);
this.x = this.startX + progress * this.dx;
this.y = this.startY + progress * this.dy;
}
} else {
if (dt > this.time) {
const [tx, ty] = this.curve(1);
if (this.relative) {
this.x = tx + this.startX;
this.y = ty + this.startY;
} else {
this.x = tx;
this.y = ty;
}
this.end = true;
this.promiseFunc();
return true;
} else {
const timeProgress = dt / this.time;
const progress = this.timing(timeProgress);
const [tx, ty] = this.curve(progress);
if (this.relative) {
this.x = tx + this.startX;
this.y = ty + this.startY;
} else {
this.x = tx;
this.y = ty;
}
}
}
return true;
}
endMoving(): void {
this.end = true;
if (this.line) {
this.x = this.targetX;
this.y = this.targetY;
} else {
const [x, y] = this.curve(1);
if (this.relative) {
this.x = x + this.startX;
this.y = y + this.startY;
} else {
this.x = x;
this.y = y;
}
}
this.promiseFunc();
this.posUpdated = true;
}
useDefaultFrame(): void {
if (!this.renderer.manager.getTile(this.tile)) return;
const defaultFrame = this.renderer.manager.getDefaultFrame(this.tile);
this.useSpecifiedFrame(defaultFrame);
}
destroy(): void {
this.renderer.deleteMoving(this);
}
}
File diff suppressed because it is too large. Load diff
@@ -1,12 +0,0 @@
#version 300 es
precision highp float;
precision highp sampler2DArray;
in vec3 v_texCoord;
out vec4 outColor;
uniform sampler2DArray u_sampler;
void main() {
outColor = texture(u_sampler, v_texCoord);
}
@@ -1,16 +0,0 @@
#version 300 es
precision highp float;
layout(location = 0) in vec2 a_position;
layout(location = 1) in vec2 a_texCoord;
out vec3 v_texCoord;
uniform float u_nowFrame;
uniform mat3 u_transform;
void main() {
vec3 transformed = u_transform * vec3(a_position, 1.0);
v_texCoord = vec3(a_texCoord, u_nowFrame);
gl_Position = vec4(transformed.xy, 0.95, 1.0);
}
@@ -1,17 +0,0 @@
#version 300 es
precision highp float;
precision highp sampler2DArray;
in vec4 v_texCoord;
out vec4 outColor;
uniform sampler2DArray u_sampler;
void main() {
vec4 texColor = texture(u_sampler, v_texCoord.xyz);
float alpha = texColor.a * v_texCoord.a;
// todo: 透明像素应该如何解决??
if (alpha < 0.1) discard;
outColor = vec4(texColor.rgb, alpha);
}
@@ -1,36 +0,0 @@
#version 300 es
precision highp float;
precision mediump int;
// 顶点坐标
layout(location = 0) in vec4 a_position;
// 实例化数据
// 图块坐标
layout(location = 1) in vec4 a_tilePos;
// 贴图坐标
layout(location = 2) in vec4 a_texCoord;
// x: 纵深,y: 不透明度
layout(location = 3) in vec4 a_tileData;
// x: 当前帧数,负数表示使用 u_nowFrame,y: 最大帧数,z: 偏移池索引,w: 纹理数组索引
layout(location = 4) in vec4 a_texData;
// x,y,z: 纹理坐标,w: 不透明度
out vec4 v_texCoord;
uniform float u_offsetPool[$1];
uniform float u_nowFrame;
uniform mat3 u_transform;
void main() {
// 坐标
vec2 pos = a_position.xy * a_tilePos.zw + a_tilePos.xy;
vec2 texCoord = a_position.zw * a_texCoord.zw + a_texCoord.xy;
// 偏移量
float offset = mod(a_texData.x < 0.0 ? u_nowFrame : a_texData.x, a_texData.y);
int offsetIndex = int(a_texData.z);
// 贴图偏移
texCoord.x += u_offsetPool[offsetIndex] * offset;
v_texCoord = vec4(texCoord.xy, a_texData.w, a_tileData.y);
vec3 transformed = u_transform * vec3(pos.xy, 1.0);
gl_Position = vec4(transformed.xy, a_tileData.x, 1.0);
}
@@ -1,70 +0,0 @@
import { IMapLayer } from '@user/data-base';
import { IBlockStatus, IMapVertexStatus } from './types';
export class StaticBlockStatus implements IBlockStatus {
/**
* @param layer 图层对象
* @param vertex 顶点数组生成器对象
* @param x 图块横坐标
* @param y 图块纵坐标
*/
constructor(
readonly layer: IMapLayer,
readonly vertex: IMapVertexStatus,
readonly x: number,
readonly y: number
) {}
setAlpha(alpha: number): void {
this.vertex.setStaticAlpha(this.layer, alpha, this.x, this.y);
}
getAlpha(): number {
return this.vertex.getStaticAlpha(this.layer, this.x, this.y);
}
useGlobalFrame(): void {
this.vertex.setStaticFrame(this.layer, this.x, this.y, -1);
}
useSpecifiedFrame(frame: number): void {
this.vertex.setStaticFrame(this.layer, this.x, this.y, frame);
}
getFrame(): number {
return this.vertex.getStaticFrame(this.layer, this.x, this.y);
}
}
export class DynamicBlockStatus implements IBlockStatus {
/**
* @param layer 图层对象
* @param vertex 顶点数组生成器对象
* @param index 图块索引
*/
constructor(
readonly layer: IMapLayer,
readonly vertex: IMapVertexStatus,
readonly index: number
) {}
setAlpha(alpha: number): void {
this.vertex.setDynamicAlpha(this.index, alpha);
}
getAlpha(): number {
return this.vertex.getDynamicAlpha(this.index);
}
useGlobalFrame(): void {
this.vertex.setDynamicFrame(this.index, -1);
}
useSpecifiedFrame(frame: number): void {
this.vertex.setDynamicFrame(this.index, frame);
}
getFrame(): number {
return this.vertex.getDynamicFrame(this.index);
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,138 +0,0 @@
import { Transform } from '@motajs/render';
import {
IBlockData,
IMapRenderArea,
IMapRenderData,
IMapRenderer,
IMapVertexBlock,
IMapVertexGenerator,
IMapViewportController
} from './types';
import { clamp } from 'lodash-es';
export class MapViewport implements IMapViewportController {
transform: Transform = new Transform();
/** 顶点生成器 */
readonly vertex: IMapVertexGenerator;
constructor(readonly renderer: IMapRenderer) {
this.vertex = renderer.vertex;
}
private pushBlock(
list: IMapRenderArea[],
start: IBlockData<IMapVertexBlock>,
end: IBlockData<IMapVertexBlock>
) {
const startIndex = start.data.startIndex;
const endIndex = end.data.endIndex;
list.push({
startIndex,
endIndex,
count: endIndex - startIndex
});
}
private checkDynamic(
list: IMapRenderArea[],
dynamicStart: number,
dynamicCount: number
) {
const last = list[list.length - 1];
if (!last || last.endIndex < dynamicStart) {
list.push({
startIndex: dynamicStart,
endIndex: dynamicStart + dynamicCount,
count: dynamicCount
});
} else {
last.endIndex = dynamicStart + dynamicCount;
last.count += dynamicCount;
}
}
getRenderArea(): IMapRenderData {
const { cellWidth, cellHeight, renderWidth, renderHeight } =
this.renderer;
const { blockWidth, blockHeight, width, height } = this.vertex.block;
// 其实只需要算左上角和右下角就行了
const [left, top] = this.transform.untransformed(-1, -1);
const [right, bottom] = this.transform.untransformed(1, 1);
const cl = (left * renderWidth) / cellWidth;
const ct = (top * renderHeight) / cellHeight;
const cr = (right * renderWidth) / cellWidth;
const cb = (bottom * renderHeight) / cellHeight;
const blockLeft = clamp(Math.floor(cl / blockWidth), 0, width - 1);
const blockRight = clamp(Math.floor(cr / blockWidth), 0, width - 1);
const blockTop = clamp(Math.floor(ct / blockHeight), 0, height - 1);
const blockBottom = clamp(Math.floor(cb / blockHeight), 0, height - 1);
const renderArea: IMapRenderArea[] = [];
const updateArea: IMapRenderArea[] = [];
const blockList: IBlockData<IMapVertexBlock>[] = [];
// 内层横向外层纵向的话,索引在换行之前都是连续的,方便整合
for (let ny = blockTop; ny <= blockBottom; ny++) {
for (let nx = blockLeft; nx <= blockRight; nx++) {
const block = this.vertex.block.getBlockByLoc(nx, ny)!;
blockList.push(block);
}
}
if (blockList.length > 0) {
if (blockList.length === 1) {
const block = blockList[0];
if (block.data.renderDirty) {
this.pushBlock(updateArea, block, block);
}
this.pushBlock(renderArea, block, block);
} else {
// 更新区域
let updateStart: IBlockData<IMapVertexBlock> = blockList[0];
let updateEnd: IBlockData<IMapVertexBlock> = blockList[0];
let renderStart: IBlockData<IMapVertexBlock> = blockList[0];
let renderEnd: IBlockData<IMapVertexBlock> = blockList[0];
for (let i = 1; i < blockList.length; i++) {
const block = blockList[i];
const { renderDirty } = block.data;
// 连续则合并
// 渲染区域
if (block.index === renderEnd.index + 1) {
renderEnd = block;
} else {
this.pushBlock(renderArea, renderStart, renderEnd);
renderStart = block;
renderEnd = block;
}
// 缓冲区更新区域
if (renderDirty && block.index === updateEnd.index + 1) {
updateEnd = block;
} else {
this.pushBlock(updateArea, updateStart, updateEnd);
updateStart = block;
updateEnd = block;
}
}
this.pushBlock(updateArea, updateStart, updateEnd);
this.pushBlock(renderArea, renderStart, renderEnd);
}
}
const dynamicStart = this.vertex.dynamicStart;
const dynamicCount = this.vertex.dynamicCount;
this.checkDynamic(renderArea, dynamicStart, dynamicCount);
if (this.vertex.dynamicRenderDirty) {
this.checkDynamic(updateArea, dynamicStart, dynamicCount);
}
return {
render: renderArea,
dirty: updateArea,
blockList: blockList
};
}
bindTransform(transform: Transform): void {
this.transform = transform;
}
}
@@ -6,7 +6,7 @@ import {
} from '@motajs/render';
// import { WeatherController } from '../weather';
import { defineComponent, onUnmounted, reactive, ref } from 'vue';
import { Textbox, TextboxProps, Tip } from '../components';
import { Textbox, TextboxProps, Tip } from '@user/client-base';
import { GameUI } from '@motajs/system';
import {
ENABLE_RIGHT_STATUS_BAR,
@@ -13,7 +13,7 @@ import {
onMounted,
shallowReactive
} from 'vue';
import { getConfirm, Page, PageExpose, Thumbnail } from '../components';
import { getConfirm, Page, PageExpose, Thumbnail } from '@user/client-base';
import { useKey } from '../use';
import {
HALF_HEIGHT,
@@ -13,12 +13,12 @@ import {
ChoicesProps,
getConfirm,
waitbox
} from '../components';
} from '@user/client-base';
import { mainUi } from '@motajs/legacy-ui';
import { gameKey, generateKeyboardEvent } from '@motajs/system';
import { getVitualKeyOnce } from '@motajs/legacy-ui';
import { getAllSavesData, getSaveData, syncFromServer } from '../utils';
import { getInput } from '../components';
import { getInput } from '@user/client-base';
import { openStatistics } from './statistics';
import { saveWithExist } from './save';
import { compressToBase64 } from 'lz-string';
@@ -5,7 +5,7 @@ import {
UIComponentProps
} from '@motajs/system';
import { defineComponent } from 'vue';
import { waitbox, ListPage, TextContent } from '../components';
import { waitbox, ListPage, TextContent } from '@user/client-base';
import { DefaultProps } from '@motajs/render-vue';
// @ts-expect-error 需要重构
import { ItemState } from '@user/data-state';
@@ -1,6 +1,6 @@
import { GameUI, SetupComponentOptions } from '@motajs/system';
import { computed, ComputedRef, defineComponent, shallowReactive } from 'vue';
import { TextContent } from '../components';
import { TextContent } from '@user/client-base';
import { ElementLocator, Font, ITexture } from '@motajs/render';
import { MixedToolbar, ReplayingStatus } from './toolbar';
import { openViewMap } from './viewmap';
@@ -28,7 +28,7 @@ import {
transitionedColor,
useKey
} from '../use';
import { ExitFullscreen, Fullscreen, SoundVolume } from '../components';
import { ExitFullscreen, Fullscreen, SoundVolume } from '@user/client-base';
import { mainSetting, triggerFullscreen } from '@motajs/legacy-ui';
import { saveLoad } from './save';
import { MainSceneUI } from './main';
@@ -10,13 +10,13 @@ import {
RollbackIcon,
StepForward,
ViewMapIcon
} from '../components/icons';
} from '@user/client-base';
import { getVitualKeyOnce } from '@motajs/legacy-ui';
import { gameKey, generateKeyboardEvent } from '@motajs/system';
import { transitioned } from '../use';
import { linear } from 'mutate-animate';
import { KeyCode } from '@motajs/client-base';
import { Progress } from '../components/misc';
import { Progress } from '@user/client-base';
import { generateBinary } from '@motajs/legacy-common';
import { SetupComponentOptions } from '@motajs/system';
import { saveSave, saveLoad } from './save';
@@ -23,10 +23,10 @@ import {
shallowRef,
watch
} from 'vue';
import { FloorSelector } from '../components';
import { FloorSelector } from '@user/client-base';
import { clamp, mean } from 'lodash-es';
import { StatisticsDataOneFloor } from './statistics';
import { Tip, TipExpose } from '../components';
import { Tip, TipExpose } from '@user/client-base';
import { useKey } from '../use';
import {
ENABLE_RIGHT_STATUS_BAR,
@@ -1,3 +1,4 @@
// @ts-expect-error layout.ts 已按 D-58..D-68 移植到 @user/client-base,本桶按 D-60 暂以标注记录断链
export * from './layout';
export * from './saves';
export * from './use';
@@ -1,86 +0,0 @@
import { ElementLocator } from '@motajs/render';
export interface IGridLayoutData {
/** 有多少列 */
readonly cols: number;
/** 有多少行 */
readonly rows: number;
/** 去除余留部分后的宽度 */
readonly width: number;
/** 去除预留部分后的高度 */
readonly height: number;
/** 元素总数量 */
readonly count: number;
/** 每个元素的定位,按照从左到右,从左上下的顺序排列,包含所有六个元素 */
readonly locs: readonly ElementLocator[];
}
/**
* 网格布局
* @param width 总宽度
* @param height 总高度
* @param itemWidth 每个元素的宽度
* @param itemHeight 每个元素的高度
* @param intervalX 元素的横向间隔
* @param intervalY 元素的纵向间隔,不填时等于横向间隔
* @returns 网格布局信息
*/
export function adjustGrid(
width: number,
height: number,
itemWidth: number,
itemHeight: number,
intervalX: number,
intervalY: number = intervalX
): IGridLayoutData {
const cols = Math.floor((width + intervalX) / (itemWidth + intervalX));
const rows = Math.floor((height + intervalY) / (itemHeight + intervalY));
const rawWidth = (itemWidth + intervalX) * cols - intervalX;
const rawHeight = (itemHeight + intervalY) * rows - intervalY;
const locs: ElementLocator[] = [];
for (let y = 0; y < rows; y++) {
const iy = (intervalY + itemHeight) * y;
for (let x = 0; x < cols; x++) {
const ix = (intervalX + itemWidth) * x;
locs.push([ix, iy, itemWidth, itemHeight, 0, 0]);
}
}
return {
cols,
rows,
count: cols * rows,
width: rawWidth,
height: rawHeight,
locs
};
}
/**
* 适配为覆盖模式,类似于 `object-fit: cover`
* @param itemWidth 元素宽度
* @param itemHeight 元素高度
* @param targetWidth 目标宽度
* @param targetHeight 目标高度
* @returns 适配为覆盖模式后元素的宽高
*/
export function adjustCover(
itemWidth: number,
itemHeight: number,
targetWidth: number,
targetHeight: number
): Readonly<LocArr> {
const aspect = itemWidth / itemHeight;
const canvasAspect = targetWidth / targetHeight;
if (canvasAspect > aspect) {
const width = targetWidth;
const height = width / aspect;
return [width, height];
} else {
const height = targetHeight;
const width = height * aspect;
return [width, height];
}
}
@@ -1,4 +1,5 @@
import { compressToBase64, decompressFromBase64 } from 'lz-string';
// @ts-expect-error components 已按 D-58..D-68 移植到 @user/client-base,本文件按 D-60 暂以标注记录断链
import { getConfirm, waitbox } from '../components';
import { IUIMountable } from '@motajs/system';
import { SyncSaveFromServerResponse } from '@motajs/client-base';