Коммит 4c55a427 создал по автору TraumatiXXX's avatar TraumatiXXX
Просмотр файлов

Merge branch 'feature/146' into develop

владельцы b608529e 817a40f0
<template>
<div id="loading-screen" style="
position: absolute;
width: 100%;
height: 100%;
background: white;
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
">
<img src="images/logo_233x233.png" alt="Loading..." id="loading-logo" />
</div>
<div id="phaser-container"></div>
</template>
<script lang="ts">
import 'phaser';
// import 'phaser3-rex-plugins/templates/ui/ui-plugin';
// import 'phaser3-rex-plugins/templates/ui/ui-components';
import CreateMoreScrollablePanels from '../../kanbans/CreateScrollablePanel';
import { useKanvasoStore } from '../../../stores/kanvaso';
import { mapActions, mapState } from 'pinia';
// import PreloadScene from './PreloadScene';
// import BootScene from './BootScene';
import { KanvasojKanvaso, TreeNode } from '../../../types/stores/kanvaso';
import CreateToolbar from '../../toolbar/CreateToolbar';
import { watch, computed } from 'vue';
import { Router } from 'vue-router';
import UIPlugin from 'phaser3-rex-plugins/templates/ui/ui-plugin';
declare const window: {
router: Router;
} & Window;
class EndlessCanvas extends Phaser.Scene {
rexUI: UIPlugin;
registry: Phaser.Data.DataManager;
toolbarWidth: number;
store: any;
router: Router;
objectFields: string[];
constructor() {
super({
key: 'endless-canvas',
});
this.store = useKanvasoStore();
this.router = window.router;
this.objectFields = [
'name',
'isPublished',
'isDeleted',
'description',
'id',
'type',
'typeId',
'parentUuid',
'hasParent',
];
this.toolbarWidth = 50;
}
preload() {
this.load.scenePlugin(
'rexuiplugin',
'rexuiplugin.min.js',
'rexUI',
'rexUI',
);
this.load.image('icon', 'phaser/stretching_icon.png');
this.load.image('logo', 'phaser/logo_202x200.png');
//заполняем registry объектами холста
this.store.getMap.forEach((element) => {
this.registry.set(element.uuid, element);
});
//организуем слежение за getMap и в случае его изменения выясняем что изменилось и обновляем данные в registry
const map = computed(() => this.store.getMap);
watch(map, (newData, oldData) => {
newData.forEach((element) => {
const uuid = element.uuid;
const oldElement = oldData.filter((el) => el.uuid === uuid)[0];
this.objectFields.forEach((field) => {
if (oldElement && element && element[field] !== oldElement[field]) {
this.registry.set(uuid, element);
}
});
});
//TODO: На данный момент таким образом можем реализовать только обновление существующих объектов. В случае добавления и удаления нужно дорабатывать метод или применять другие подходы. Например полный рестарт сцены (это очень нехорошо :))
// Добавляем обработку добавления новых элементов
newData.forEach((element) => {
if (!oldData.some((el) => el.uuid === element.uuid)) {
this.registry.set(element.uuid, element);
}
});
// Добавляем обработку удаления элементов
oldData.forEach((element) => {
if (!newData.some((el) => el.uuid === element.uuid)) {
this.registry.remove(element.uuid);
}
});
//Как обновлять реестр понятно. Не совсем понятно пока как убирать добавлять внутриигровые объекты
});
}
create(): void {
const scene = this;
//@ts-ignore
const toolbar = CreateToolbar(scene, scene.router);
// const back = this.add
// .text(0, 0, '<<', {
// fontSize: '24px',
// backgroundColor: '#000',
// color: '#fff',
// })
// .setDepth(20);
// back.setInteractive();
// back.on('pointerdown', () => {
// this.router.push('/projects');
// });
scene.cameras.main.setBackgroundColor('#abcdef');
// Скрываем экран загрузки здесь, потому что на этом этапе preload уже завершен
document.getElementById('loading-screen').style.display = 'none';
let parent = scene.sys.game.canvas.parentElement;
let parentWidth = parent.offsetWidth;
let parentHeight = parent.offsetHeight;
const numberOfPanels = scene.store.getTree.length;
let panelWidth = parentWidth - scene.toolbarWidth;
let panelHeight = parentHeight / numberOfPanels;
let topPanelsArr = CreateMoreScrollablePanels(
//@ts-ignore
scene,
scene.store.getTree,
scene.registry,
{ h: panelHeight, w: panelWidth },
);
for (let i = 0; i < topPanelsArr.length; i++) {
topPanelsArr[i]
.setPosition(
parentWidth / 2 + scene.toolbarWidth / 2,
panelHeight / 2 + i * panelHeight,
)
.layout();
}
// .drawBounds(this.add.graphics(), 0xff0000)}
scene.registry.events.on(
'changedata',
(parent, key, data, previousData) => { },
);
}
}
const config: Phaser.Types.Core.GameConfig = {
type: Phaser.AUTO,
parent: 'phaser-container',
width: window.innerWidth,
height: window.innerHeight,
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
},
scene: EndlessCanvas,
plugins: {
// scene: [
// {
// key: 'rexUI',
// plugin: RexPlugins,
// mapping: 'rexUI',
// },
// // ...
// ],
},
};
export default {
name: 'EndlessCanvas',
data() {
return {
wsSubscribe: null,
game: null,
};
},
computed: {
...mapState(useKanvasoStore, {
project: 'getKanvaso',
}),
currentProject() {
return this.project ? this.project[0]?.node : null;
},
projectUuid() {
return this.$route?.params?.uuid || '';
},
},
methods: {
...mapActions(useKanvasoStore, [
'onGetKanvasoFull',
'onEditKanvasoObjekto',
'onEditKanvaso',
'onEditKanvasoLigilo',
'onGetKanvasoObjekto',
'onKanvasoSubscribe',
]),
resizeHandler() {
const container = document.getElementById('phaser-container');
container.style.width = window.innerWidth + 'px';
container.style.height = window.innerHeight + 'px';
const canvas = container.querySelector('canvas');
canvas.style.width = window.innerWidth + 'px';
canvas.style.height = window.innerHeight + 'px';
//FIXME: Ещё можно способом ниже изменять напрямую размеры холста, но это не даёт нужного результата. Размер меняется, но по краям появляются чёрные полосы :(
// //@ts-ignore
// canvas.attributes.width.value = window.innerWidth;
// //@ts-ignore
// canvas.attributes.height.value = window.innerHeight;
// console.log(
this.game.scale.resize(window.innerWidth, window.innerHeight);
// );
},
},
async mounted() {
interface KanvasojKanvasoResult {
data?: {
kanvasojKanvaso?: KanvasojKanvaso;
};
}
document.getElementsByTagName('body')[0].style.overflow = 'hidden';
await this.onGetKanvasoFull({ uuid: this.projectUuid })
.then((result: KanvasojKanvasoResult) => {
if (!result.data.kanvasojKanvaso.edges.length) {
throw new Error(result.toString());
}
this.onKanvasoSubscribe({
kanvasoj: [this.currentProject.objId],
}).then((data: any) => {
this.wsSubscribe = data;
});
})
.catch((err: any) => {
console.log('error get kanvaso full :>> ', err);
this.$router.replace({ name: 'projects' });
});
await this.onGetKanvasoObjekto({ kanvaso_Uuid: this.projectUuid });
window.addEventListener('resize', this.resizeHandler);
window.router = this.$router;
this.game = new Phaser.Game(config);
// window.addEventListener('resize', function (event) {
// console.log('resize');
// game.scale.resize(
// window.innerWidth < 600 ? window.innerWidth : window.innerWidth - 205,
// window.innerWidth < 600
// ? window.innerHeight - 51
// : window.innerHeight - 10,
// );
// });
// setInterval(() => {
// game.scale.resize(
// window.innerWidth < 600 ? window.innerWidth : window.innerWidth - 205,
// window.innerWidth < 600
// ? window.innerHeight - 51
// : window.innerHeight - 10,
// );
// }, 100);
},
beforeUnmount() {
this.wsSubscribe.unsubscribe();
document.getElementsByTagName('body')[0].style.overflow = 'auto';
this.game.destroy();
delete window.router;
},
};
</script>
<style>
#phaser-container>canvas {
margin-top: 0 !important;
}
</style>
...@@ -113,6 +113,7 @@ const routes: RouteRecordRaw[] = [ ...@@ -113,6 +113,7 @@ const routes: RouteRecordRaw[] = [
}, },
{ {
path: '/develop', path: '/develop',
component: () => import('layouts/CanvasLayout.vue'),
children: [ children: [
{ {
path: 'testspace-i', path: 'testspace-i',
...@@ -129,10 +130,10 @@ const routes: RouteRecordRaw[] = [ ...@@ -129,10 +130,10 @@ const routes: RouteRecordRaw[] = [
}, },
}, },
{ {
path: 'endless3', path: 'testspace-o',
name: 'endless3', name: 'testspace-o',
meta: { title: 'Endless3' }, meta: { title: 'Test Space Objects' },
component: () => import('../apps/develop/EndlessPage3.vue'), component: () => import('../apps/develop/objects/TestSpaceObjects.vue'),
beforeEnter: (to, from) => { beforeEnter: (to, from) => {
const store = useCurrentUserStore(); const store = useCurrentUserStore();
// if (!store.getUserId) { // if (!store.getUserId) {
......
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать