import { IonContent, ReactComponentOrElement } from '@ionic/react'; import react, { ReactComponentElement, useEffect, useRef, useState, } from 'react'; import './Map.css'; import MouseHandler from './MouseHandler'; import SlippyBoard from './SlippyBoard'; import Tile from './Tile'; import fakeTile from './FakeTile.svg'; interface MapProperties { height: number; width: number; } const Map: react.FC = (props: MapProperties) => { const nbTiles = Math.ceil((Math.max(props.width, props.height) * 2) / 256) + 2; const boardSize = nbTiles * 256; const [shift, setShift] = useState({ x: -boardSize / 2, y: -boardSize / 2 }); const [zoom, setZoom] = useState(1); const addShift = (deltaShift: { x: number; y: number }) => { setShift({ x: shift.x + deltaShift.x, y: shift.y + deltaShift.y }); }; const addZoom = (zoomFactor: number, center: { x: number; y: number }) => { addShift({ x: (shift.x - center.x) * (zoomFactor - 1), y: (shift.y - center.y) * (zoomFactor - 1), }); setZoom(zoom * zoomFactor); }; console.log(`Rendering Map, zoom:${zoom}, shift:${JSON.stringify(shift)}`); var initialTiledLayer: any[][] = []; for (let row = 0; row < nbTiles; row++) { let tileRow = []; for (let col = 0; col < nbTiles; col++) { tileRow.push(); } initialTiledLayer.push(tileRow); } const [tiledLayer, setTiledLayer] = useState(initialTiledLayer); useEffect(() => { const firstVisibleTiles = { x: Math.max(Math.floor(-shift.x / 256 / zoom), 0), y: Math.max(Math.floor(-shift.y / 256 / zoom), 0), }; const lastVisibleTiles = { x: Math.min( Math.ceil(firstVisibleTiles.x + props.width / 256 / zoom), nbTiles - 1 ), y: Math.min( Math.ceil(firstVisibleTiles.y + props.height / 256 / zoom), nbTiles - 1 ), }; console.log( `Adding new tiles if needed for ${JSON.stringify( firstVisibleTiles )}/${JSON.stringify(lastVisibleTiles)}.` ); const newTiledLayer: any[][] = []; for (let row = 0; row < nbTiles; row++) { let tileRow = []; for (let col = 0; col < nbTiles; col++) { const key = `${row}/${col}`; if ( tiledLayer[row][col].type === 'g' && row >= firstVisibleTiles.y && row <= lastVisibleTiles.y && col >= firstVisibleTiles.x && col <= lastVisibleTiles.x ) { console.log(`Adding tile ${row}/${col}`); tileRow.push( ); } else { // tileRow.push(); tileRow.push(tiledLayer[row][col]); } } newTiledLayer.push(tileRow); } setTiledLayer(newTiledLayer); }, [shift, zoom, nbTiles]); // console.log(`tiledLayer: ${JSON.stringify(tiledLayer)}`); return (
), }, { key: 'tiles', content: tiledLayer }, { key: 'circle', content: }, ]} />
); }; export default Map;