refactor web

This commit is contained in:
bridge
2025-11-20 22:16:27 +08:00
parent cdc3322ff0
commit 10d571e6bb
17 changed files with 947 additions and 155 deletions

View File

@@ -0,0 +1,74 @@
<script setup lang="ts">
import { useGameStore } from '../../stores/game'
import { useTextures } from './composables/useTextures'
import { computed } from 'vue'
import { Graphics } from 'pixi.js'
const store = useGameStore()
const { textures } = useTextures()
const TILE_SIZE = 64
function getTexture(avatar: any) {
const key = `${(avatar.gender || 'male').toLowerCase()}_${avatar.pic_id || 1}`
return textures.value[key]
}
function getScale(avatar: any) {
const tex = getTexture(avatar)
if (!tex) return 1
return (TILE_SIZE * 1.8) / Math.max(tex.width, tex.height)
}
// Fallback graphics draw function
const drawFallback = (g: Graphics, avatar: any) => {
g.clear()
g.circle(0, 0, TILE_SIZE * 0.6)
g.fill({ color: avatar.gender === 'female' ? 0xffaaaa : 0xaaaaff })
g.stroke({ width: 2, color: 0x000000 })
}
const nameStyle = {
fontFamily: '"Microsoft YaHei", sans-serif',
fontSize: 24,
fill: 0xffffff,
stroke: { color: 0x000000, width: 4 },
align: 'center'
}
</script>
<template>
<container sortable-children>
<container
v-for="avatar in store.avatarList"
:key="avatar.id"
:x="avatar.x * TILE_SIZE + TILE_SIZE / 2"
:y="avatar.y * TILE_SIZE + TILE_SIZE / 2"
:z-index="avatar.y"
>
<!-- Avatar Sprite -->
<sprite
v-if="getTexture(avatar)"
:texture="getTexture(avatar)"
:anchor-x="0.5"
:anchor-y="0.8"
:scale="getScale(avatar)"
/>
<!-- Fallback Graphics -->
<graphics
v-else
@render="g => drawFallback(g, avatar)"
/>
<!-- Name Tag -->
<text
:text="avatar.name"
:style="nameStyle"
:anchor-x="0.5"
:anchor-y="1"
:y="-TILE_SIZE * 0.8"
/>
</container>
</container>
</template>

View File

@@ -0,0 +1,63 @@
<script setup lang="ts">
import { Application } from 'vue3-pixi'
import { ref, onMounted } from 'vue'
import { useElementSize } from '@vueuse/core'
import Viewport from './Viewport.vue'
import MapLayer from './MapLayer.vue'
import EntityLayer from './EntityLayer.vue'
import { useTextures } from './composables/useTextures'
const container = ref<HTMLElement>()
const { width, height } = useElementSize(container)
const { loadTextures, isLoaded } = useTextures()
const mapSize = ref({ width: 2000, height: 2000 })
function onMapLoaded(size: { width: number, height: number }) {
mapSize.value = size
}
const devicePixelRatio = window.devicePixelRatio || 1
onMounted(() => {
loadTextures()
})
</script>
<template>
<div ref="container" class="game-canvas-container">
<!--
antialias: false (像素风必须关闭)
resolution: devicePixelRatio (保证清晰度)
background-color: 0x000000
-->
<Application
v-if="width > 0 && height > 0"
:width="width"
:height="height"
:background-color="0x000000"
:antialias="false"
:resolution="devicePixelRatio"
>
<Viewport
v-if="isLoaded"
:screen-width="width"
:screen-height="height"
:world-width="mapSize.width"
:world-height="mapSize.height"
>
<MapLayer @mapLoaded="onMapLoaded" />
<EntityLayer />
</Viewport>
</Application>
</div>
</template>
<style scoped>
.game-canvas-container {
width: 100%;
height: 100%;
overflow: hidden;
background: #000;
}
</style>

View File

@@ -0,0 +1,103 @@
<script setup lang="ts">
import { ref, onMounted, watch, inject } from 'vue'
import { Container, Sprite } from 'pixi.js'
import { useTextures } from './composables/useTextures'
const mapContainer = ref<Container>()
const { textures, isLoaded } = useTextures()
const TILE_SIZE = 64
const regions = ref<any[]>([])
const emit = defineEmits(['mapLoaded'])
async function initMap() {
if (!mapContainer.value || !isLoaded.value) return
try {
const res = await fetch('/api/map')
const data = await res.json()
const mapData = data.data
regions.value = data.regions || []
if (!mapData) return
// Imperative Tile Rendering
mapContainer.value.removeChildren()
const rows = mapData.length
const cols = mapData[0].length
console.log(`Rendering Map: ${cols}x${rows}`)
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
const type = mapData[y][x]
const tex = textures.value[type] || textures.value['PLAIN']
if (tex) {
const s = new Sprite(tex)
s.x = x * TILE_SIZE
s.y = y * TILE_SIZE
s.width = TILE_SIZE
s.height = TILE_SIZE
// Optimization: Static tiles don't need interactivity
s.eventMode = 'none'
mapContainer.value.addChild(s)
}
}
}
// Emit world size
emit('mapLoaded', {
width: cols * TILE_SIZE,
height: rows * TILE_SIZE
})
} catch (e) {
console.error("Map load error", e)
}
}
watch(isLoaded, (val) => {
if (val) initMap()
})
onMounted(() => {
if (isLoaded.value) initMap()
})
function getRegionStyle(type: string) {
const base = {
fontFamily: '"Microsoft YaHei", sans-serif',
fontSize: type === 'sect' ? 48 : 64,
fill: type === 'sect' ? 0xffcc00 : (type === 'city' ? 0xccffcc : 0xffffff),
stroke: { color: 0x000000, width: 8, join: 'round' },
align: 'center',
dropShadow: {
color: '#000000',
blur: 4,
angle: Math.PI / 6,
distance: 4,
alpha: 0.8
}
}
return base
}
</script>
<template>
<container ref="mapContainer">
<!-- Regions (Labels) -->
<text
v-for="r in regions"
:key="r.name"
:text="r.name"
:x="r.x * TILE_SIZE + TILE_SIZE / 2"
:y="r.y * TILE_SIZE + TILE_SIZE / 2"
:anchor="0.5"
:style="getRegionStyle(r.type)"
:z-index="100"
/>
</container>
</template>

View File

@@ -0,0 +1,90 @@
<script setup lang="ts">
import { Viewport as PixiViewport } from 'pixi-viewport'
import { useApplication } from 'vue3-pixi'
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { Container } from 'pixi.js'
const props = defineProps<{
screenWidth: number
screenHeight: number
worldWidth: number
worldHeight: number
}>()
const app = useApplication()
const containerRef = ref<Container>()
let viewport: PixiViewport | null = null
onMounted(async () => {
await nextTick()
if (!containerRef.value || !app.value) return
viewport = new PixiViewport({
screenWidth: props.screenWidth,
screenHeight: props.screenHeight,
worldWidth: props.worldWidth,
worldHeight: props.worldHeight,
events: app.value.renderer.events
})
viewport
.drag()
.pinch()
.wheel()
.decelerate({ friction: 0.9 })
// Initial Fit
fitMap()
const container = containerRef.value
if (container.parent) container.parent.removeChild(container)
app.value.stage.addChild(viewport)
viewport.addChild(container)
;(window as any).__viewport = viewport
})
function fitMap() {
if (!viewport) return
const { worldWidth, worldHeight } = props
// Don't fit if world is default small
if (worldWidth < 100) return
viewport.resize(props.screenWidth, props.screenHeight, worldWidth, worldHeight)
viewport.fit(true, worldWidth, worldHeight)
const fitScale = Math.min(props.screenWidth / worldWidth, props.screenHeight / worldHeight)
// Allow zooming out a bit more than fit
viewport.clampZoom({ minScale: fitScale * 0.8, maxScale: 4.0 })
// If current zoom is weird, reset
if (viewport.scaled < fitScale) viewport.setZoom(fitScale)
}
watch(() => [props.screenWidth, props.screenHeight], ([w, h]) => {
if (viewport) {
viewport.resize(w, h, props.worldWidth, props.worldHeight)
// Optional: Refit on significant resize or just clamp?
// clampZoom updates automatically if minScale is not dynamic?
// No, we set minScale manually. We should re-clamp.
const fitScale = Math.min(w / props.worldWidth, h / props.worldHeight)
viewport.clampZoom({ minScale: fitScale * 0.8, maxScale: 4.0 })
}
})
watch(() => [props.worldWidth, props.worldHeight], () => {
fitMap()
})
onUnmounted(() => {
if (viewport) {
viewport.destroy({ children: false })
}
})
</script>
<template>
<container ref="containerRef">
<slot />
</container>
</template>

View File

@@ -0,0 +1,64 @@
import { ref } from 'vue'
import { Assets, Texture } from 'pixi.js'
// 全局纹理缓存,避免重复加载
const textures = ref<Record<string, Texture>>({})
const isLoaded = ref(false)
export function useTextures() {
const loadTextures = async () => {
if (isLoaded.value) return
const manifest: Record<string, string> = {
'PLAIN': '/assets/tiles/plain.png',
'WATER': '/assets/tiles/water.png',
'SEA': '/assets/tiles/sea.png',
'MOUNTAIN': '/assets/tiles/mountain.png',
'FOREST': '/assets/tiles/forest.png',
'CITY': '/assets/tiles/city.png',
'DESERT': '/assets/tiles/desert.png',
'RAINFOREST': '/assets/tiles/rainforest.png',
'GLACIER': '/assets/tiles/glacier.png',
'SNOW_MOUNTAIN': '/assets/tiles/snow_mountain.png',
'VOLCANO': '/assets/tiles/volcano.png',
'GRASSLAND': '/assets/tiles/grassland.png',
'SWAMP': '/assets/tiles/swamp.png',
'CAVE': '/assets/tiles/cave.png',
'RUINS': '/assets/tiles/ruins.png',
'FARM': '/assets/tiles/farm.png'
}
// 加载地图纹理
for (const [key, url] of Object.entries(manifest)) {
try {
textures.value[key] = await Assets.load(url)
} catch (e) {
console.error(`Failed to load texture: ${url}`, e)
}
}
// 加载角色立绘 (1-16)
for (let i = 1; i <= 16; i++) {
const maleUrl = `/assets/males/${i}.png`
const femaleUrl = `/assets/females/${i}.png`
try {
textures.value[`male_${i}`] = await Assets.load(maleUrl)
} catch (e) { /* ignore */ }
try {
textures.value[`female_${i}`] = await Assets.load(femaleUrl)
} catch (e) { /* ignore */ }
}
isLoaded.value = true
console.log('Textures loaded')
}
return {
textures,
isLoaded,
loadTextures
}
}