Merge remote-tracking branch 'origin/feature/#215-dexie-caching-implementation' into feature/character-profile

# Conflicts:
#	src/screens/Game.vue
This commit is contained in:
2024-10-25 22:20:34 +02:00
26 changed files with 673 additions and 723 deletions

View File

@ -15,6 +15,7 @@ import GmPanel from '@/components/gameMaster/GmPanel.vue'
import Login from '@/screens/Login.vue'
import Characters from '@/screens/Characters.vue'
import Game from '@/screens/Game.vue'
// import Loading from '@/screens/Loading.vue'
import ZoneEditor from '@/screens/ZoneEditor.vue'
import { computed } from 'vue'
@ -22,16 +23,11 @@ const gameStore = useGameStore()
const zoneEditorStore = useZoneEditorStore()
const currentScreen = computed(() => {
// if (!gameStore.isAssetsLoaded) return Loading
if (!gameStore.connection) return Login
if (!gameStore.token) return Login
if (!gameStore.character) return Characters
if (zoneEditorStore.active) return ZoneEditor
return Game
})
// Disable right click
addEventListener('contextmenu', (event) => event.preventDefault())
// Disable pinch zoom
addEventListener('gesturestart', (event) => event.preventDefault())
</script>

View File

@ -118,7 +118,6 @@ function saveObject() {
return
}
console.log(objectTags.value)
gameStore.connection?.emit(
'gm:object:update',
{

View File

@ -8,7 +8,7 @@ import { useScene } from 'phavuer'
import { useGameStore } from '@/stores/gameStore'
import { useZoneEditorStore } from '@/stores/zoneEditorStore'
import { onBeforeMount, onBeforeUnmount } from 'vue'
import { createTileArray, getTile, placeTile, setAllTiles } from '@/composables/zoneComposable'
import { createTileArray, getTile, placeTile, setLayerTiles } from '@/composables/zoneComposable'
import Controls from '@/components/utilities/Controls.vue'
const emit = defineEmits(['tilemap:create'])
@ -117,7 +117,7 @@ function paint(pointer: Phaser.Input.Pointer) {
if (!pointer.isDown) return
// Set new tileArray with selected tile
setAllTiles(zoneTilemap, tiles, createTileArray(zoneTilemap.width, zoneTilemap.height, zoneEditorStore.selectedTile.id))
setLayerTiles(zoneTilemap, tiles, createTileArray(zoneTilemap.width, zoneTilemap.height, zoneEditorStore.selectedTile.id))
// Adjust zoneEditorStore.zone.tiles
zoneEditorStore.zone.tiles = createTileArray(zoneTilemap.width, zoneTilemap.height, zoneEditorStore.selectedTile.id)
@ -127,7 +127,7 @@ onBeforeMount(() => {
if (!zoneEditorStore.zone?.tiles) {
return
}
setAllTiles(zoneTilemap, tiles, zoneEditorStore.zone.tiles)
setLayerTiles(zoneTilemap, tiles, zoneEditorStore.zone.tiles)
scene.input.on(Phaser.Input.Events.POINTER_MOVE, pencil)
scene.input.on(Phaser.Input.Events.POINTER_MOVE, eraser)

View File

@ -14,11 +14,9 @@
</template>
<script setup lang="ts">
import { onBeforeMount, onUnmounted, ref } from 'vue'
import { useScene } from 'phavuer'
import { onUnmounted, ref } from 'vue'
import { useGameStore } from '@/stores/gameStore'
import { useZoneEditorStore } from '@/stores/zoneEditorStore'
import { loadAssets } from '@/composables/zoneComposable'
import { type Zone } from '@/types'
// Components
@ -32,7 +30,6 @@ import Tiles from '@/components/gameMaster/zoneEditor/Tiles.vue'
import Objects from '@/components/gameMaster/zoneEditor/Objects.vue'
import EventTiles from '@/components/gameMaster/zoneEditor/EventTiles.vue'
const scene = useScene()
const gameStore = useGameStore()
const zoneEditorStore = useZoneEditorStore()
@ -62,11 +59,6 @@ function save() {
})
}
onBeforeMount(async () => {
await gameStore.fetchAllZoneAssets()
await loadAssets(scene)
})
onUnmounted(() => {
zoneEditorStore.reset()
})

View File

@ -1,118 +1,118 @@
<template>
<div class="relative" v-if="gameStore.uiSettings.isCharacterProfileOpen" :style="modalStyle">
<img src="/assets/ui-elements/profile-ui-box-outer.svg" class="absolute w-full h-full" />
<img src="/assets/ui-elements/profile-ui-box-inner.svg" class="absolute left-2 bottom-2 w-[calc(100%_-_16px)] h-[calc(100%_-_40px)]" />
<div @mousedown="startDrag" class="cursor-move px-5 py-2.5 flex justify-between items-center relative">
<span class="text-xs text-white font-thin">Character Profile [Alt+C]</span>
<button @click="gameStore.uiSettings.isCharacterProfileOpen = false" class="w-3.5 h-3.5 m-0 p-0 relative hover:rotate-180 transition-transform duration-300 ease-in-out">
<img alt="close" draggable="false" src="/assets/icons/close-button-white.svg" class="w-full h-full" />
</button>
</div>
<div class="py-4 px-6 flex flex-col gap-7 relative z-10">
<div class="flex flex-col gap-2.5">
<div class="flex justify-between">
<div>
<p class="text-sm m-0 font-bold text-white tracking-wide">{{ gameStore.character?.name }}</p>
<span class="text-xs">{{ gameStore.character?.experience }} / 18.600XP</span>
</div>
<a class="hover:cursor-pointer bg-[url('/assets/ui-elements/ui-border-4-corners-small.svg')] bg-no-repeat block w-8 h-8 relative mx-[3px]">
<img class="hover:drop-shadow-default w-3.5 h-3.5 m-[9px] object-contain" draggable="false" src="/assets/icons/plus-green-icon.svg" />
</a>
</div>
<div class="flex justify-between">
<div class="flex flex-col gap-0.5">
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<span class="absolute w-full top-1/2 -translate-y-1/2 text-[6px] text-center">CROWN</span>
</div>
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<span class="absolute w-full top-1/2 -translate-y-1/2 text-[6px] text-center">R-HAND</span>
</div>
<div class="flex gap-0.5 items-end">
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<span class="absolute w-full top-1/2 -translate-y-1/2 text-[6px] text-center">L-HAND</span>
</div>
<div class="w-6 h-6 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<span class="absolute w-full top-1/2 -translate-y-1/2 text-[6px] text-center">RING</span>
</div>
</div>
</div>
<img src="/assets/placeholders/inventory_player.png" class="w-8 h-auto"/>
<div class="flex flex-col items-end gap-0.5">
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<img class="absolute w-6 h-6 left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" src="/assets/icons/profile/helmet.svg">
</div>
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<img class="absolute w-6 h-6 left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" src="/assets/icons/profile/chestplate.svg">
</div>
<div class="flex gap-0.5 items-end">
<div class="w-6 h-6 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<img class="absolute w-4 h-4 left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" src="/assets/icons/profile/boots.svg">
</div>
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<img class="absolute w-6 h-6 left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" src="/assets/icons/profile/legs.svg">
</div>
</div>
</div>
</div>
<div class="flex justify-between">
<div class="flex flex-col">
<div class="w-[105px] h-px mb-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
<div class="flex gap-11">
<p class="m-0 text-xs text-white tracking-wide">Health</p>
<span class="m-0 text-xs text-white tracking-wide">+ 15</span>
</div>
<div class="w-[105px] h-px my-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
<div class="flex gap-11">
<p class="m-0 text-xs text-white tracking-wide">Health</p>
<span class="m-0 text-xs text-white tracking-wide">+ 15</span>
</div>
<div class="w-[105px] h-px mt-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
</div>
<div class="flex flex-col">
<div class="w-[105px] h-px mb-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
<div class="flex gap-11">
<p class="m-0 text-xs text-white tracking-wide">Health</p>
<span class="m-0 text-xs text-white tracking-wide">+ 15</span>
</div>
<div class="w-[105px] h-px my-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
<div class="flex gap-11">
<p class="m-0 text-xs text-white tracking-wide">Health</p>
<span class="m-0 text-xs text-white tracking-wide">+ 15</span>
</div>
<div class="w-[105px] h-px mt-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
</div>
</div>
</div>
<div class="grid grid-rows-4 grid-cols-6 gap-0.5">
<div v-for="n in 24" class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600"></div>
</div>
</div>
<div class="relative" v-if="gameStore.uiSettings.isCharacterProfileOpen" :style="modalStyle">
<img src="/assets/ui-elements/profile-ui-box-outer.svg" class="absolute w-full h-full" />
<img src="/assets/ui-elements/profile-ui-box-inner.svg" class="absolute left-2 bottom-2 w-[calc(100%_-_16px)] h-[calc(100%_-_40px)]" />
<div @mousedown="startDrag" class="cursor-move px-5 py-2.5 flex justify-between items-center relative">
<span class="text-xs text-white font-thin">Character Profile [Alt+C]</span>
<button @click="gameStore.uiSettings.isCharacterProfileOpen = false" class="w-3.5 h-3.5 m-0 p-0 relative hover:rotate-180 transition-transform duration-300 ease-in-out">
<img alt="close" draggable="false" src="/assets/icons/close-button-white.svg" class="w-full h-full" />
</button>
</div>
<div class="py-4 px-6 flex flex-col gap-7 relative z-10">
<div class="flex flex-col gap-2.5">
<div class="flex justify-between">
<div>
<p class="text-sm m-0 font-bold text-white tracking-wide">{{ gameStore.character?.name }}</p>
<span class="text-xs">{{ gameStore.character?.experience }} / 18.600XP</span>
</div>
<a class="hover:cursor-pointer bg-[url('/assets/ui-elements/ui-border-4-corners-small.svg')] bg-no-repeat block w-8 h-8 relative mx-[3px]">
<img class="hover:drop-shadow-default w-3.5 h-3.5 m-[9px] object-contain" draggable="false" src="/assets/icons/plus-green-icon.svg" />
</a>
</div>
<div class="flex justify-between">
<div class="flex flex-col gap-0.5">
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<span class="absolute w-full top-1/2 -translate-y-1/2 text-[6px] text-center">CROWN</span>
</div>
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<span class="absolute w-full top-1/2 -translate-y-1/2 text-[6px] text-center">R-HAND</span>
</div>
<div class="flex gap-0.5 items-end">
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<span class="absolute w-full top-1/2 -translate-y-1/2 text-[6px] text-center">L-HAND</span>
</div>
<div class="w-6 h-6 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<span class="absolute w-full top-1/2 -translate-y-1/2 text-[6px] text-center">RING</span>
</div>
</div>
</div>
<img src="/assets/placeholders/inventory_player.png" class="w-8 h-auto" />
<div class="flex flex-col items-end gap-0.5">
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<img class="absolute w-6 h-6 left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" src="/assets/icons/profile/helmet.svg" />
</div>
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<img class="absolute w-6 h-6 left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" src="/assets/icons/profile/chestplate.svg" />
</div>
<div class="flex gap-0.5 items-end">
<div class="w-6 h-6 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<img class="absolute w-4 h-4 left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" src="/assets/icons/profile/boots.svg" />
</div>
<div class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600">
<img class="absolute w-6 h-6 left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2" src="/assets/icons/profile/legs.svg" />
</div>
</div>
</div>
</div>
<div class="flex justify-between">
<div class="flex flex-col">
<div class="w-[105px] h-px mb-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
<div class="flex gap-11">
<p class="m-0 text-xs text-white tracking-wide">Health</p>
<span class="m-0 text-xs text-white tracking-wide">+ 15</span>
</div>
<div class="w-[105px] h-px my-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
<div class="flex gap-11">
<p class="m-0 text-xs text-white tracking-wide">Health</p>
<span class="m-0 text-xs text-white tracking-wide">+ 15</span>
</div>
<div class="w-[105px] h-px mt-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
</div>
<div class="flex flex-col">
<div class="w-[105px] h-px mb-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
<div class="flex gap-11">
<p class="m-0 text-xs text-white tracking-wide">Health</p>
<span class="m-0 text-xs text-white tracking-wide">+ 15</span>
</div>
<div class="w-[105px] h-px my-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
<div class="flex gap-11">
<p class="m-0 text-xs text-white tracking-wide">Health</p>
<span class="m-0 text-xs text-white tracking-wide">+ 15</span>
</div>
<div class="w-[105px] h-px mt-[3px] flex justify-between">
<div class="w-px h-full bg-gray-300"></div>
<div class="w-[101px] h-full bg-gray-300"></div>
<div class="w-px h-full bg-gray-300"></div>
</div>
</div>
</div>
</div>
<div class="grid grid-rows-4 grid-cols-6 gap-0.5">
<div v-for="n in 24" class="w-9 h-9 border border-solid border-gray-500 rounded-sm bg-gray relative hover:bg-gray-600"></div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
@ -176,8 +176,6 @@ function initializePosition() {
width.value = Math.min(modalWidth, window.innerWidth)
height.value = Math.min(modalHeight, window.innerHeight)
if (modalPositionX !== 0 && modalPositionY !== 0) {
console.log(modalPositionX)
console.log(modalPositionY)
x.value = modalPositionX
y.value = modalPositionY
} else {
@ -224,14 +222,21 @@ watch(
}
)
function keyPress(event: KeyboardEvent) {
if (event.altKey && event.key === 'c') {
gameStore.toggleCharacterProfile()
}
}
onMounted(() => {
window.addEventListener('mousemove', drag)
window.addEventListener('mouseup', stopDrag)
addEventListener('keydown', keyPress)
addEventListener('mousemove', drag)
addEventListener('mouseup', stopDrag)
initializePosition()
})
onUnmounted(() => {
window.removeEventListener('mousemove', drag)
window.removeEventListener('mouseup', stopDrag)
removeEventListener('mousemove', drag)
removeEventListener('mouseup', stopDrag)
})
</script>
</script>

View File

@ -161,8 +161,6 @@ function initializePosition() {
width.value = Math.min(props.modalWidth, window.innerWidth)
height.value = Math.min(props.modalHeight, window.innerHeight)
if (props.modalPositionX !== 0 && props.modalPositionY !== 0) {
console.log(props.modalPositionX)
console.log(props.modalPositionY)
x.value = props.modalPositionX
y.value = props.modalPositionY
} else {

View File

@ -1,5 +1,5 @@
<template>
<Modal v-for="notification in gameStore.getNotifications" :key="notification.id" :isModalOpen="true" @modal:close="closeNotification(notification.id)">
<Modal v-for="notification in gameStore.notifications" :key="notification.id" :isModalOpen="true" @modal:close="closeNotification(notification.id)">
<template #modalHeader v-if="notification.title">
<h3 class="m-0 font-medium shrink-0 text-white">{{ notification.title }}</h3>
</template>

View File

@ -1,28 +0,0 @@
<template>
<Image v-for="object in zoneStore.zone?.zoneObjects" v-bind="getImageProps(object)" />
</template>
<script setup lang="ts">
import { calculateIsometricDepth, tileToWorldX, tileToWorldY } from '@/composables/zoneComposable'
import { Image, Text } from 'phavuer'
import { useZoneStore } from '@/stores/zoneStore'
import type { ZoneObject } from '@/types'
const zoneStore = useZoneStore()
const props = defineProps<{
tilemap: Phaser.Tilemaps.Tilemap
}>()
const getImageProps = (object: ZoneObject) => {
return {
depth: calculateIsometricDepth(object.positionX, object.positionY, object.object.frameWidth, object.object.frameHeight),
x: tileToWorldX(props.tilemap as any, object.positionX, object.positionY),
y: tileToWorldY(props.tilemap as any, object.positionX, object.positionY),
flipX: object.isRotated,
texture: object.object.id,
originY: Number(object.object.originX),
originX: Number(object.object.originY)
}
}
</script>

View File

@ -1,23 +1,20 @@
<template>
<Tiles :key="zoneStore.zone?.id ?? 0" @tilemap:create="tileMap = $event" />
<Objects v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />
<ZoneTiles :key="zoneStore.zone?.id ?? 0" @tilemap:create="tileMap = $event" />
<ZoneObjects v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />
<Characters v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />
</template>
<script setup lang="ts">
import { useScene } from 'phavuer'
import { useGameStore } from '@/stores/gameStore'
import { useZoneStore } from '@/stores/zoneStore'
import { onBeforeMount, onBeforeUnmount, ref } from 'vue'
import { onBeforeUnmount, ref, onBeforeMount } from 'vue'
import type { Character as CharacterT, Zone as ZoneT, ExtendedCharacter as ExtendedCharacterT } from '@/types'
import Tiles from '@/components/zone/Tiles.vue'
import Objects from '@/components/zone/Objects.vue'
import ZoneTiles from '@/components/zone/ZoneTiles.vue'
import ZoneObjects from '@/components/zone/ZoneObjects.vue'
import Characters from '@/components/zone/Characters.vue'
import { loadAssets } from '@/composables/zoneComposable'
const gameStore = useGameStore()
const zoneStore = useZoneStore()
const scene = useScene()
const tileMap = ref(null as Phaser.Tilemaps.Tilemap | null)
@ -28,13 +25,6 @@ type zoneLoadData = {
// Event listeners
gameStore.connection!.on('zone:character:teleport', async (data: zoneLoadData) => {
/**
* This is the cause of the bug
*/
// Fetch assets for new zone
await gameStore.fetchZoneAssets(data.zone.id)
await loadAssets(scene)
/**
* @TODO : Update character via global event server-side, remove this and listen for it somewhere not here
*/
@ -61,12 +51,8 @@ gameStore.connection!.on('character:move', (data: ExtendedCharacterT) => {
zoneStore.updateCharacter(data)
})
onBeforeMount(() => {
gameStore.connection!.emit('zone:character:join', async (response: zoneLoadData) => {
// Fetch assets for new zone
await gameStore.fetchZoneAssets(response.zone.id)
await loadAssets(scene)
onBeforeMount(async () => {
gameStore!.connection!.emit('zone:character:join', async (response: zoneLoadData) => {
// Set zone and characters
zoneStore.setZone(response.zone)
zoneStore.setCharacters(response.characters)

View File

@ -0,0 +1,14 @@
<template>
<ZoneObject v-for="zoneObject in zoneStore.zone?.zoneObjects" :tilemap="tilemap" :zoneObject />
</template>
<script setup lang="ts">
import { useZoneStore } from '@/stores/zoneStore'
import ZoneObject from '@/components/zone/partials/ZoneObject.vue'
const zoneStore = useZoneStore()
defineProps<{
tilemap: Phaser.Tilemaps.Tilemap
}>()
</script>

View File

@ -7,14 +7,13 @@ import config from '@/config'
import { useScene } from 'phavuer'
import { useZoneStore } from '@/stores/zoneStore'
import { onBeforeMount, onBeforeUnmount } from 'vue'
import { placeTile, setAllTiles } from '@/composables/zoneComposable'
import { setLayerTiles } from '@/composables/zoneComposable'
import Controls from '@/components/utilities/Controls.vue'
const emit = defineEmits(['tilemap:create'])
const zoneStore = useZoneStore()
const scene = useScene()
const zoneTilemap = createTilemap()
const tiles = createTileLayer()
@ -54,7 +53,7 @@ onBeforeMount(() => {
if (!zoneStore.zone?.tiles) {
return
}
setAllTiles(zoneTilemap, tiles, zoneStore.zone.tiles)
setLayerTiles(zoneTilemap, tiles, zoneStore.zone.tiles)
})
onBeforeUnmount(() => {

View File

@ -0,0 +1,63 @@
<template>
<Image v-if="isTextureLoaded" v-bind="imageProps" />
</template>
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Image, useScene } from 'phavuer'
import { calculateIsometricDepth, tileToWorldX, tileToWorldY } from '@/composables/zoneComposable'
import { useAssetManager } from '@/utilities/assetManager'
import type { ZoneObject } from '@/types'
const props = defineProps<{
tilemap: Phaser.Tilemaps.Tilemap
zoneObject: ZoneObject
}>()
const scene = useScene()
const assetManager = useAssetManager
const isTextureLoaded = ref(false)
const imageProps = computed(() => ({
depth: calculateIsometricDepth(props.zoneObject.positionX, props.zoneObject.positionY, props.zoneObject.object.frameWidth, props.zoneObject.object.frameHeight),
x: tileToWorldX(props.tilemap, props.zoneObject.positionX, props.zoneObject.positionY),
y: tileToWorldY(props.tilemap, props.zoneObject.positionX, props.zoneObject.positionY),
flipX: props.zoneObject.isRotated,
texture: props.zoneObject.object.id,
originY: Number(props.zoneObject.object.originX),
originX: Number(props.zoneObject.object.originY)
}))
const loadTexture = async () => {
const textureId = props.zoneObject.object.id
// Check if the texture is already loaded in Phaser
if (scene.textures.exists(textureId)) {
isTextureLoaded.value = true
return
}
let assetData = await assetManager.getAsset(textureId)
if (!assetData) {
await assetManager.downloadAsset(textureId, `/assets/objects/${textureId}.png`, 'objects', props.zoneObject.object.updatedAt)
assetData = await assetManager.getAsset(textureId)
}
if (assetData) {
return new Promise<void>((resolve) => {
scene.textures.addBase64(textureId, assetData.data)
scene.textures.once(`addtexture-${textureId}`, () => {
isTextureLoaded.value = true
resolve()
})
})
}
}
onMounted(() => {
loadTexture().catch((error) => {
console.error('Error loading texture:', error)
})
})
</script>

View File

View File

@ -3,7 +3,6 @@ import Tilemap = Phaser.Tilemaps.Tilemap
import TilemapLayer = Phaser.Tilemaps.TilemapLayer
import Tileset = Phaser.Tilemaps.Tileset
import Tile = Phaser.Tilemaps.Tile
import { useGameStore } from '@/stores/gameStore'
export function getTile(layer: TilemapLayer | Tilemap, x: number, y: number): Tile | undefined {
const tile = layer.getTileAtWorldXY(x, y)
@ -51,11 +50,7 @@ export function placeTile(zone: Tilemap, layer: TilemapLayer, x: number, y: numb
layer.putTileAt(tileImg.firstgid, x, y)
}
export function deleteTile(layer: TilemapLayer, x: number, y: number) {
layer.removeTileAt(x, y)
}
export function setAllTiles(zone: Tilemap, layer: TilemapLayer, tiles: string[][]) {
export function setLayerTiles(zone: Tilemap, layer: TilemapLayer, tiles: string[][]) {
tiles.forEach((row: string[], y: number) => {
row.forEach((tile: string, x: number) => {
placeTile(zone, layer, x, y, tile)
@ -72,43 +67,5 @@ export const calculateIsometricDepth = (x: number, y: number, width: number = 0,
if (isCharacter) {
return baseDepth // @TODO: Fix collision, this is a hack
}
// For objects, use their back bottom corner
return baseDepth + (width + height) / (2 * config.tile_size.x)
}
export const sortByIsometricDepth = <T extends { positionX: number; positionY: number }>(items: T[]) => {
return [...items].sort((a, b) => {
return calculateIsometricDepth(a.positionX, a.positionY, 0, 0) - calculateIsometricDepth(b.positionX, b.positionY, 0, 0)
})
}
export const clearAssets = (scene: Phaser.Scene) => {
scene.load.destroy()
}
export const loadAssets = (scene: Phaser.Scene): Promise<void> => {
return new Promise((resolve) => {
const gameStore = useGameStore()
let addedLoad = false
gameStore.assets.forEach((asset) => {
if (scene.load.textureManager.exists(asset.key)) return
addedLoad = true
if (asset.group === 'sprite_animations') {
scene.load.spritesheet(asset.key, config.server_endpoint + asset.url, { frameWidth: asset.frameWidth ?? 0, frameHeight: asset.frameHeight ?? 0 })
} else {
scene.load.image(asset.key, config.server_endpoint + asset.url)
}
})
if (addedLoad) {
scene.load.start()
scene.load.on(Phaser.Loader.Events.COMPLETE, () => {
resolve()
})
} else {
resolve()
}
})
}

View File

@ -114,13 +114,7 @@ gameStore.connection?.on('character:list', (data: any) => {
})
onMounted(async () => {
/**
* Fetch sprite assets from the server
* This is done here because phaser needs it in createScene in Game.vue.
*/
await gameStore.fetchSpriteAssets()
// wait 0.5 sec
// wait 0.75 sec
setTimeout(() => {
gameStore.connection?.emit('character:list')
isLoading.value = false

View File

@ -2,18 +2,16 @@
<div class="flex justify-center items-center h-dvh relative">
<Game :config="gameConfig" @create="createGame">
<Scene name="main" @preload="preloadScene" @create="createScene">
<div v-if="isLoaded">
<Menu />
<Hud />
<Hotkeys />
<Minimap />
<Zone />
<Chat />
<ExpBar />
<Menu />
<Hud />
<Hotkeys />
<Minimap />
<Zone />
<Chat />
<ExpBar />
<CharacterProfile />
<Effects />
</div>
<CharacterProfile />
<Effects />
</Scene>
</Game>
</div>
@ -22,7 +20,6 @@
<script setup lang="ts">
import config from '@/config'
import 'phaser'
import { ref, onBeforeUnmount, onMounted } from 'vue'
import { Game, Scene } from 'phavuer'
import { useGameStore } from '@/stores/gameStore'
import Menu from '@/components/gui/Menu.vue'
@ -33,18 +30,28 @@ import Hotkeys from '@/components/gui/Hotkeys.vue'
import Chat from '@/components/gui/Chat.vue'
import CharacterProfile from '@/components/gui/CharacterProfile.vue'
import Effects from '@/components/Effects.vue'
import { loadAssets } from '@/composables/zoneComposable'
import Minimap from '@/components/gui/Minimap.vue'
import AwaitLoaderPlugin from 'phaser3-rex-plugins/plugins/awaitloader-plugin'
import { useAssetManager } from '@/utilities/assetManager'
const gameStore = useGameStore()
const isLoaded = ref(false)
const assetManager = useAssetManager
const gameConfig = {
name: config.name,
width: window.innerWidth,
height: window.innerHeight,
type: Phaser.AUTO, // AUTO, CANVAS, WEBGL, HEADLESS
resolution: 5
resolution: 5,
plugins: {
global: [
{
key: 'rexAwaitLoader',
plugin: AwaitLoaderPlugin,
start: true
}
]
}
}
const createGame = (game: Phaser.Game) => {
@ -65,84 +72,47 @@ const createGame = (game: Phaser.Game) => {
}
}
const preloadScene = async (scene: Phaser.Scene) => {
isLoaded.value = false
/**
* Create loading bar
*/
const width = scene.cameras.main.width
const height = scene.cameras.main.height
const progressBox = scene.add.graphics()
const progressBar = scene.add.graphics()
progressBox.fillStyle(0x222222, 0.8)
progressBox.fillRect(width / 2 - 180, height / 2, 320, 50)
const loadingText = scene.make.text({
x: width / 2,
y: height / 2 - 50,
text: 'Loading...',
style: {
font: '20px monospace',
fill: '#ffffff'
}
})
loadingText.setOrigin(0.5, 0.5)
scene.load.on(Phaser.Loader.Events.PROGRESS, function (value: any) {
progressBar.clear()
progressBar.fillStyle(0x368f8b, 1)
progressBar.fillRect(width / 2 - 180 + 10, height / 2 + 10, 300 * value, 30)
})
scene.load.on(Phaser.Loader.Events.COMPLETE, function () {
progressBar.destroy()
progressBox.destroy()
loadingText.destroy()
isLoaded.value = true
})
function preloadScene(scene: Phaser.Scene) {
/**
* Load the base assets into the Phaser scene
*/
scene.load.image('blank_tile', '/assets/zone/blank_tile.png')
scene.load.image('waypoint', '/assets/waypoint.png')
/**
* Load the assets into the Phaser scene
*/
await loadAssets(scene)
scene.load.rexAwait(async function (successCallback) {
await assetManager.getAssetsByGroup('tiles').then((assets) => {
assets.forEach((asset) => {
if (scene.load.textureManager.exists(asset.key)) return
scene.textures.addBase64(asset.key, asset.data)
})
})
// Load objects
await assetManager.getAssetsByGroup('objects').then((assets) => {
assets.forEach((asset) => {
if (scene.load.textureManager.exists(asset.key)) return
scene.textures.addBase64(asset.key, asset.data)
})
})
successCallback()
})
}
const createScene = async (scene: Phaser.Scene) => {
function createScene(scene: Phaser.Scene) {
/**
* Create sprite animations
* This is done here because phaser forces us to
*/
gameStore.assets.forEach((asset) => {
if (asset.group !== 'sprite_animations') return
scene.anims.create({
key: asset.key,
frameRate: 7,
frames: scene.anims.generateFrameNumbers(asset.key, { start: 0, end: asset.frameCount! - 1 }),
repeat: -1
assetManager.getAssetsByGroup('sprite_animations').then((assets) => {
assets.forEach((asset) => {
scene.anims.create({
key: asset.key,
frameRate: 7,
frames: scene.anims.generateFrameNumbers(asset.key, { start: 0, end: asset.frameCount! - 1 }),
repeat: -1
})
})
})
}
function keyPress(event: KeyboardEvent) {
if (event.altKey && event.key === 'c') {
gameStore.toggleCharacterProfile()
}
}
onMounted(() => {
window.addEventListener('keydown', keyPress)
})
onBeforeUnmount(() => {
isLoaded.value = false
})
</script>

74
src/screens/Loading.vue Normal file
View File

@ -0,0 +1,74 @@
<template>
<div class="flex flex-col justify-center items-center h-dvh relative">
<div v-if="!isLoaded" class="w-20 h-20 rounded-full border-4 border-solid border-gray-300 border-t-transparent animate-spin"></div>
<button v-else @click="continueBtnClick" class="w-20 h-20 rounded-full bg-gray-500 flex items-center justify-center hover:bg-gray-600 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</button>
<div v-if="!isLoaded" class="text-center mt-6">
<h1 class="text-2xl font-bold">Loading...</h1>
<p class="text-gray-400">Please wait while we load the assets.</p>
</div>
</div>
</template>
<script setup lang="ts" async>
import { onMounted, ref } from 'vue'
import config from '@/config'
import type { AssetT as ServerAsset } from '@/types'
import { useAssetManager } from '@/utilities/assetManager'
import { useGameStore } from '@/stores/gameStore'
/**
* This component downloads all assets from the server and
* stores them in the asset manager.
*/
const gameStore = useGameStore()
const assetManager = useAssetManager
const isLoaded = ref(false)
async function getAssets() {
return fetch(config.server_endpoint + '/assets/')
.then((response) => {
if (!response.ok) throw new Error('Failed to fetch assets')
console.log(response)
return response.json()
})
.catch((error) => {
console.error('Error fetching assets:', error)
return false
})
}
async function loadAssetsIntoAssetManager(assets: ServerAsset[]): Promise<void> {
for (const asset of assets) {
// Check if the asset is already loaded
const existingAsset = await assetManager.getAsset(asset.key)
// Check if the asset needs to be updated
if (!existingAsset || new Date(asset.updatedAt) > new Date(existingAsset.updatedAt)) {
// Check if the asset is already loaded, if so, delete it
if (existingAsset) {
await assetManager.deleteAsset(asset.key)
}
// Add the asset to the asset manager
await assetManager.downloadAsset(asset.key, asset.url, asset.group, asset.updatedAt, asset.frameCount, asset.frameWidth, asset.frameHeight)
}
}
}
function continueBtnClick() {
gameStore.isAssetsLoaded = true
}
onMounted(async () => {
const assets = await getAssets()
if (assets) {
await loadAssetsIntoAssetManager(assets)
isLoaded.value = true
}
})
</script>

View File

@ -16,7 +16,6 @@ import { Game, Scene } from 'phavuer'
import { useGameStore } from '@/stores/gameStore'
import { useZoneEditorStore } from '@/stores/zoneEditorStore'
import ZoneEditor from '@/components/gameMaster/zoneEditor/ZoneEditor.vue'
import { loadAssets } from '@/composables/zoneComposable'
const gameStore = useGameStore()
const zoneEditorStore = useZoneEditorStore()
@ -93,11 +92,6 @@ const preloadScene = async (scene: Phaser.Scene) => {
scene.load.image('TELEPORT', '/assets/zone/tp_tile.png')
scene.load.image('blank_tile', '/assets/zone/blank_tile.png')
scene.load.image('waypoint', '/assets/waypoint.png')
/**
* Load the assets into the Phaser scene
*/
await loadAssets(scene)
}
const createScene = async (scene: Phaser.Scene) => {

View File

@ -1,9 +1,8 @@
import axios from 'axios'
import config from '@/config'
import { useGameStore } from '@/stores/gameStore'
import { useCookies } from '@vueuse/integrations/useCookies'
export async function register(username: string, password: string, gameStore = useGameStore()) {
export async function register(username: string, password: string) {
try {
const response = await axios.post(`${config.server_endpoint}/register`, { username, password })
useCookies().set('token', response.data.token as string)
@ -13,13 +12,13 @@ export async function register(username: string, password: string, gameStore = u
}
}
export async function login(username: string, password: string, gameStore = useGameStore()) {
export async function login(username: string, password: string) {
try {
const response = await axios.post(`${config.server_endpoint}/login`, { username, password })
useCookies().set('token', response.data.token as string, {
// for whole domain
// @TODO : #190
domain: window.location.hostname.split('.').slice(-2).join('.')
// domain: window.location.hostname.split('.').slice(-2).join('.')
})
return { success: true, token: response.data.token }
} catch (error: any) {

View File

@ -7,9 +7,9 @@ import { useCookies } from '@vueuse/integrations/useCookies'
export const useGameStore = defineStore('game', {
state: () => {
return {
loginMessage: null as string | null,
notifications: [] as Notification[],
assets: [] as Asset[],
isAssetsLoaded: false,
loadedAssets: [] as string[],
token: '' as string | null,
connection: null as Socket | null,
user: null as User | null,
@ -31,12 +31,6 @@ export const useGameStore = defineStore('game', {
}
}
},
getters: {
getNotifications: (state: any) => state.notifications,
getAssetByKey: (state) => {
return (key: string) => state.assets.find((asset) => asset.key === key)
}
},
actions: {
addNotification(notification: Notification) {
if (!notification.id) {
@ -47,54 +41,6 @@ export const useGameStore = defineStore('game', {
removeNotification(id: string) {
this.notifications = this.notifications.filter((notification: Notification) => notification.id !== id)
},
setAssets(assets: Asset[]) {
this.assets = assets
},
addAsset(asset: Asset) {
this.assets.push(asset)
},
addAssets(assets: Asset[]) {
this.assets = this.assets.concat(assets)
},
async fetchSpriteAssets() {
return fetch(config.server_endpoint + '/assets/sprites')
.then((response) => response.json())
.then((assets) => {
// Only add the sprites that are not already in the store
this.addAssets(assets.filter((asset: Asset) => !this.getAssetByKey(asset.key)))
return true
})
.catch((error) => {
console.error('Error fetching assets:', error)
return false
})
},
async fetchZoneAssets(zoneId: number) {
return fetch(config.server_endpoint + '/assets/zone/' + zoneId)
.then((response) => response.json())
.then((assets) => {
// Only add the zones that are not already in the store
this.addAssets(assets.filter((asset: Asset) => !this.getAssetByKey(asset.key)))
return true
})
.catch((error) => {
console.error('Error fetching assets:', error)
return false
})
},
async fetchAllZoneAssets() {
return fetch(config.server_endpoint + '/assets/zone')
.then((response) => response.json())
.then((assets) => {
// Only add the zones that are not already in the store
this.addAssets(assets.filter((asset: Asset) => !this.getAssetByKey(asset.key)))
return true
})
.catch((error) => {
console.error('Error fetching assets:', error)
return false
})
},
setToken(token: string) {
this.token = token
},
@ -152,15 +98,15 @@ export const useGameStore = defineStore('game', {
})
},
disconnectSocket() {
if (this.connection) this.connection.disconnect()
this.connection?.disconnect()
useCookies().remove('token', {
// for whole domain
// @TODO : #190
domain: window.location.hostname.split('.').slice(-2).join('.')
// domain: window.location.hostname.split('.').slice(-2).join('.')
})
this.assets = []
this.isAssetsLoaded = false
this.connection = null
this.token = null
this.user = null

View File

@ -4,10 +4,11 @@ export type Notification = {
message?: string
}
export type Asset = {
export type AssetT = {
key: string
url: string
group: 'tiles' | 'objects' | 'sprites' | 'sprite_animations' | 'sound' | 'music' | 'ui' | 'font' | 'other'
updatedAt: Date
frameCount?: number
frameWidth?: number
frameHeight?: number

View File

@ -0,0 +1,72 @@
import config from '@/config'
import Dexie from 'dexie'
class AssetManager extends Dexie {
assets!: Dexie.Table<
{
key: string
data: Blob
group: string
updatedAt: Date
frameCount?: number
frameWidth?: number
frameHeight?: number
},
string
>
constructor() {
super('Assets')
this.version(1).stores({
assets: 'key, group'
})
}
async downloadAsset(key: string, url: string, group: string, updatedAt: Date, frameCount?: number, frameWidth?: number, frameHeight?: number) {
try {
const response = await fetch(config.server_endpoint + url)
const blob = await response.blob()
await this.assets.put({ key, data: blob, group, updatedAt, frameCount, frameWidth, frameHeight })
} catch (error) {
console.error(`Failed to add asset ${key}:`, error)
}
}
async getAsset(key: string) {
try {
const asset = await this.assets.get(key)
if (asset) {
return {
...asset,
data: URL.createObjectURL(asset.data)
}
}
} catch (error) {
console.error(`Failed to retrieve asset ${key}:`, error)
}
return null
}
async getAssetsByGroup(group: string) {
try {
const assets = await this.assets.where('group').equals(group).toArray()
return assets.map((asset) => ({
...asset,
data: URL.createObjectURL(asset.data)
}))
} catch (error) {
console.error(`Failed to retrieve assets for group ${group}:`, error)
return []
}
}
async deleteAsset(key: string) {
try {
await this.assets.delete(key)
} catch (error) {
console.error(`Failed to delete asset ${key}:`, error)
}
}
}
export const useAssetManager = new AssetManager()