620 lines
18 KiB
JavaScript
620 lines
18 KiB
JavaScript
import {useCallback, useEffect, useRef, useState} from 'react';
|
|
|
|
import {useClient, usePacket} from '@/react/context/client.js';
|
|
import {useDebug} from '@/react/context/debug.js';
|
|
import {useEcs, useEcsTick} from '@/react/context/ecs.js';
|
|
import {useMainEntity} from '@/react/context/main-entity.js';
|
|
import {RESOLUTION} from '@/util/constants.js';
|
|
import EventEmitter from '@/util/event-emitter.js';
|
|
|
|
import addKeyListener from './add-key-listener.js';
|
|
import ClientEcs from './client-ecs.js';
|
|
import Disconnected from './dom/disconnected.jsx';
|
|
import Chat from './dom/chat/chat.jsx';
|
|
import Bag from './dom/bag.jsx';
|
|
import Dom from './dom/dom.jsx';
|
|
import Entities from './dom/entities.jsx';
|
|
import External from './dom/external.jsx';
|
|
import HotBar from './dom/hotbar.jsx';
|
|
import Pixi from './pixi/pixi.jsx';
|
|
import Devtools from './devtools.jsx';
|
|
import styles from './ui.module.css';
|
|
|
|
const KEY_MAP = {
|
|
keyDown: 1,
|
|
keyUp: 0,
|
|
};
|
|
|
|
function emptySlots() {
|
|
return Array(50).fill(undefined);
|
|
}
|
|
|
|
const devEventsChannel = new EventEmitter();
|
|
|
|
function Ui({disconnected}) {
|
|
// Key input.
|
|
const client = useClient();
|
|
const chatInputRef = useRef();
|
|
const gameRef = useRef();
|
|
const [mainEntity, setMainEntity] = useMainEntity();
|
|
const [debug, setDebug] = useDebug();
|
|
const [ecs, setEcs] = useEcs();
|
|
const [showDisconnected, setShowDisconnected] = useState(false);
|
|
const [bufferSlot, setBufferSlot] = useState();
|
|
const [devtoolsIsOpen, setDevtoolsIsOpen] = useState(false);
|
|
const ratio = (RESOLUTION.x * (devtoolsIsOpen ? 2 : 1)) / RESOLUTION.y;
|
|
const [camera, setCamera] = useState({x: 0, y: 0});
|
|
const [inventorySlots, setInventorySlots] = useState(emptySlots());
|
|
const [activeSlot, setActiveSlot] = useState(0);
|
|
const [scale, setScale] = useState(2);
|
|
const [Components, setComponents] = useState();
|
|
const [Systems, setSystems] = useState();
|
|
const [monopolizers, setMonopolizers] = useState([]);
|
|
const [message, setMessage] = useState('');
|
|
const [chatIsOpen, setChatIsOpen] = useState(false);
|
|
const [chatHistory, setChatHistory] = useState([]);
|
|
const [chatHistoryCaret, setChatHistoryCaret] = useState(-1);
|
|
const [chatMessages, setChatMessages] = useState({});
|
|
const [pendingMessage, setPendingMessage] = useState('');
|
|
const [hotbarIsHidden, setHotbarIsHidden] = useState(true);
|
|
const [hotbarHideHandle, setHotbarHideHandle] = useState();
|
|
const [isInventoryOpen, setIsInventoryOpen] = useState(false);
|
|
const [externalInventory, setExternalInventory] = useState();
|
|
const [externalInventorySlots, setExternalInventorySlots] = useState();
|
|
const [particleWorker, setParticleWorker] = useState();
|
|
const refreshEcs = useCallback(() => {
|
|
class ClientEcsPerf extends ClientEcs {
|
|
markChange() {}
|
|
}
|
|
setEcs(new ClientEcsPerf({Components, Systems}));
|
|
}, [Components, Systems, setEcs]);
|
|
useEffect(() => {
|
|
async function setEcsStuff() {
|
|
const {default: Components} = await import('@/ecs/components/index.js');
|
|
const {default: Systems} = await import('@/ecs/systems/index.js');
|
|
setComponents(Components);
|
|
setSystems(Systems);
|
|
}
|
|
setEcsStuff();
|
|
}, []);
|
|
useEffect(() => {
|
|
refreshEcs();
|
|
}, [refreshEcs]);
|
|
useEffect(() => {
|
|
let handle;
|
|
if (disconnected) {
|
|
handle = setTimeout(() => {
|
|
setShowDisconnected(true);
|
|
}, 1000);
|
|
}
|
|
else {
|
|
setShowDisconnected(false)
|
|
}
|
|
return () => {
|
|
clearTimeout(handle);
|
|
};
|
|
}, [disconnected]);
|
|
useEffect(() => {
|
|
return addKeyListener(document.body, ({type, payload}) => {
|
|
if (chatInputRef.current) {
|
|
chatInputRef.current.focus();
|
|
}
|
|
if (chatIsOpen) {
|
|
return;
|
|
}
|
|
let actionPayload;
|
|
switch (payload) {
|
|
case 'w': {
|
|
actionPayload = {type: 'moveUp', value: KEY_MAP[type]};
|
|
break;
|
|
}
|
|
case 'a': {
|
|
actionPayload = {type: 'moveLeft', value: KEY_MAP[type]};
|
|
break;
|
|
}
|
|
case 's': {
|
|
actionPayload = {type: 'moveDown', value: KEY_MAP[type]};
|
|
break;
|
|
}
|
|
case 'd': {
|
|
actionPayload = {type: 'moveRight', value: KEY_MAP[type]};
|
|
break;
|
|
}
|
|
}
|
|
if (actionPayload) {
|
|
client.send({
|
|
type: 'Action',
|
|
payload: actionPayload,
|
|
});
|
|
}
|
|
});
|
|
}, [
|
|
chatIsOpen,
|
|
client,
|
|
]);
|
|
const keepHotbarOpen = useCallback(() => {
|
|
if (!isInventoryOpen) {
|
|
setHotbarIsHidden(false);
|
|
if (hotbarHideHandle) {
|
|
clearTimeout(hotbarHideHandle);
|
|
}
|
|
setHotbarHideHandle(setTimeout(() => {
|
|
setHotbarIsHidden(true);
|
|
}, 4000));
|
|
}
|
|
}, [hotbarHideHandle, isInventoryOpen]);
|
|
useEffect(() => {
|
|
return addKeyListener(document.body, ({event, type, payload}) => {
|
|
if ('Escape' === payload && 'keyDown' === type && chatIsOpen) {
|
|
setChatIsOpen(false);
|
|
return;
|
|
}
|
|
if (chatInputRef.current) {
|
|
chatInputRef.current.focus();
|
|
}
|
|
if (chatIsOpen) {
|
|
return;
|
|
}
|
|
let actionPayload;
|
|
switch (payload) {
|
|
case '-':
|
|
if ('keyDown' === type) {
|
|
setScale((scale) => scale > 1 ? scale - 1 : 1);
|
|
}
|
|
break;
|
|
case '=':
|
|
case '+':
|
|
if ('keyDown' === type) {
|
|
setScale((scale) => scale < 4 ? Math.floor(scale + 1) : 4);
|
|
}
|
|
break;
|
|
case 'F3': {
|
|
if (event) {
|
|
event.preventDefault();
|
|
}
|
|
if ('keyDown' === type) {
|
|
setDebug(!debug);
|
|
}
|
|
break;
|
|
}
|
|
case 'F4': {
|
|
if (event) {
|
|
event.preventDefault();
|
|
}
|
|
if ('keyDown' === type) {
|
|
setDevtoolsIsOpen(!devtoolsIsOpen);
|
|
}
|
|
break;
|
|
}
|
|
case '`': {
|
|
if (event) {
|
|
event.preventDefault();
|
|
}
|
|
if ('keyDown' === type) {
|
|
if (isInventoryOpen) {
|
|
setHotbarIsHidden(true);
|
|
}
|
|
else {
|
|
setHotbarIsHidden(false);
|
|
if (hotbarHideHandle) {
|
|
clearTimeout(hotbarHideHandle);
|
|
}
|
|
}
|
|
setIsInventoryOpen(!isInventoryOpen);
|
|
}
|
|
break
|
|
}
|
|
case 'Enter': {
|
|
if ('keyDown' === type) {
|
|
setChatIsOpen(true);
|
|
}
|
|
break
|
|
}
|
|
case 'e': {
|
|
if (KEY_MAP[type]) {
|
|
if (monopolizers.length > 0) {
|
|
monopolizers[0].trigger();
|
|
break;
|
|
}
|
|
}
|
|
actionPayload = {type: 'interact', value: KEY_MAP[type]};
|
|
break;
|
|
}
|
|
case '1': {
|
|
if ('keyDown' === type) {
|
|
keepHotbarOpen();
|
|
actionPayload = {type: 'changeSlot', value: 1};
|
|
}
|
|
break;
|
|
}
|
|
case '2': {
|
|
if ('keyDown' === type) {
|
|
keepHotbarOpen();
|
|
actionPayload = {type: 'changeSlot', value: 2};
|
|
}
|
|
break;
|
|
}
|
|
case '3': {
|
|
if ('keyDown' === type) {
|
|
keepHotbarOpen();
|
|
actionPayload = {type: 'changeSlot', value: 3};
|
|
}
|
|
break;
|
|
}
|
|
case '4': {
|
|
if ('keyDown' === type) {
|
|
keepHotbarOpen();
|
|
actionPayload = {type: 'changeSlot', value: 4};
|
|
}
|
|
break;
|
|
}
|
|
case '5': {
|
|
if ('keyDown' === type) {
|
|
keepHotbarOpen();
|
|
actionPayload = {type: 'changeSlot', value: 5};
|
|
}
|
|
break;
|
|
}
|
|
case '6': {
|
|
if ('keyDown' === type) {
|
|
keepHotbarOpen();
|
|
actionPayload = {type: 'changeSlot', value: 6};
|
|
}
|
|
break;
|
|
}
|
|
case '7': {
|
|
if ('keyDown' === type) {
|
|
keepHotbarOpen();
|
|
actionPayload = {type: 'changeSlot', value: 7};
|
|
}
|
|
break;
|
|
}
|
|
case '8': {
|
|
if ('keyDown' === type) {
|
|
keepHotbarOpen();
|
|
actionPayload = {type: 'changeSlot', value: 8};
|
|
}
|
|
break;
|
|
}
|
|
case '9': {
|
|
if ('keyDown' === type) {
|
|
keepHotbarOpen();
|
|
actionPayload = {type: 'changeSlot', value: 9};
|
|
}
|
|
break;
|
|
}
|
|
case '0': {
|
|
if ('keyDown' === type) {
|
|
keepHotbarOpen();
|
|
actionPayload = {type: 'changeSlot', value: 10};
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
if (actionPayload) {
|
|
client.send({
|
|
type: 'Action',
|
|
payload: actionPayload,
|
|
});
|
|
}
|
|
});
|
|
}, [
|
|
chatIsOpen,
|
|
client,
|
|
debug,
|
|
devtoolsIsOpen,
|
|
hotbarHideHandle,
|
|
isInventoryOpen,
|
|
keepHotbarOpen,
|
|
monopolizers,
|
|
setDebug,
|
|
setScale,
|
|
]);
|
|
usePacket('EcsChange', async () => {
|
|
refreshEcs();
|
|
setMainEntity(undefined);
|
|
setMonopolizers([]);
|
|
}, [refreshEcs, setMainEntity, setMonopolizers]);
|
|
usePacket('Tick', async (payload, client) => {
|
|
if (0 === Object.keys(payload.ecs).length) {
|
|
return;
|
|
}
|
|
await ecs.apply(payload.ecs);
|
|
client.emitter.invoke(':Ecs', payload.ecs);
|
|
}, [ecs]);
|
|
useEcsTick((payload) => {
|
|
if (!('1' in payload) || particleWorker) {
|
|
return
|
|
}
|
|
const localParticleWorker = new Worker(
|
|
new URL('./particle-worker.js', import.meta.url),
|
|
{type: 'module'},
|
|
);
|
|
localParticleWorker.postMessage(ecs.get(1).toJSON());
|
|
setParticleWorker((particleWorker) => {
|
|
if (particleWorker) {
|
|
particleWorker.terminate();
|
|
}
|
|
return localParticleWorker;
|
|
});
|
|
}, [particleWorker]);
|
|
useEcsTick((payload) => {
|
|
let localMainEntity = mainEntity;
|
|
for (const id in payload) {
|
|
const entity = ecs.get(id);
|
|
const update = payload[id];
|
|
if (!update) {
|
|
continue;
|
|
}
|
|
if (update.Direction && entity.Collider) {
|
|
entity.Collider.updateAabbs();
|
|
}
|
|
if (update.Sound?.play) {
|
|
for (const sound of update.Sound.play) {
|
|
(new Audio(sound)).play();
|
|
}
|
|
}
|
|
if (update.MainEntity) {
|
|
setMainEntity(localMainEntity = id);
|
|
}
|
|
if (update.Inventory) {
|
|
if (localMainEntity === id) {
|
|
setBufferSlot(entity.Inventory.item(0));
|
|
const newInventorySlots = emptySlots();
|
|
for (let i = 1; i < 41; ++i) {
|
|
newInventorySlots[i - 1] = entity.Inventory.item(i);
|
|
}
|
|
setInventorySlots(newInventorySlots);
|
|
}
|
|
else if (update.Inventory.slots) {
|
|
const newInventorySlots = Array(30).fill(undefined);
|
|
for (let i = 0; i < 30; ++i) {
|
|
newInventorySlots[i] = entity.Inventory.item(i);
|
|
}
|
|
setExternalInventory(entity.id)
|
|
setExternalInventorySlots(newInventorySlots);
|
|
setIsInventoryOpen(true);
|
|
setHotbarIsHidden(false);
|
|
if (hotbarHideHandle) {
|
|
clearTimeout(hotbarHideHandle);
|
|
}
|
|
}
|
|
else if (update.Inventory.closed) {
|
|
setExternalInventory();
|
|
setExternalInventorySlots();
|
|
}
|
|
}
|
|
if (localMainEntity === id) {
|
|
if (update.Wielder && 'activeSlot' in update.Wielder) {
|
|
setActiveSlot(update.Wielder.activeSlot);
|
|
}
|
|
}
|
|
}
|
|
if (localMainEntity) {
|
|
const mainEntityEntity = ecs.get(localMainEntity);
|
|
const x = Math.round((mainEntityEntity.Camera.x * scale) - RESOLUTION.x / 2);
|
|
const y = Math.round((mainEntityEntity.Camera.y * scale) - RESOLUTION.y / 2);
|
|
if (x !== camera.x || y !== camera.y) {
|
|
setCamera({x, y});
|
|
}
|
|
}
|
|
}, [camera, ecs, hotbarHideHandle, mainEntity, scale]);
|
|
useEffect(() => {
|
|
function onContextMenu(event) {
|
|
event.preventDefault();
|
|
}
|
|
document.body.addEventListener('contextmenu', onContextMenu);
|
|
return () => {
|
|
document.body.removeEventListener('contextmenu', onContextMenu);
|
|
};
|
|
}, []);
|
|
const computePosition = useCallback(({clientX, clientY}) => {
|
|
if (!gameRef.current || !mainEntity) {
|
|
return;
|
|
}
|
|
const {top, left, width} = gameRef.current.getBoundingClientRect();
|
|
const master = ecs.get(1);
|
|
if (!master) {
|
|
return;
|
|
}
|
|
const {Camera} = ecs.get(mainEntity);
|
|
const size = width / RESOLUTION.x;
|
|
const camera = {
|
|
x: ((Camera.x * scale) - (RESOLUTION.x / 2)),
|
|
y: ((Camera.y * scale) - (RESOLUTION.y / 2)),
|
|
}
|
|
return {
|
|
x: (((clientX - left) / size) + camera.x) / scale,
|
|
y: (((clientY - top) / size) + camera.y) / scale,
|
|
};
|
|
}, [
|
|
ecs,
|
|
mainEntity,
|
|
scale,
|
|
]);
|
|
return (
|
|
<div
|
|
className={styles.ui}
|
|
>
|
|
<style>
|
|
{`
|
|
@media (max-aspect-ratio: ${ratio}) { .${styles.game} { width: 100%; } }
|
|
@media (min-aspect-ratio: ${ratio}) { .${styles.game} { height: 100%; } }
|
|
.${styles.game} {
|
|
cursor: ${
|
|
bufferSlot
|
|
? `url('${bufferSlot.icon}'), auto !important`
|
|
: 'auto'
|
|
};
|
|
}
|
|
`}
|
|
</style>
|
|
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */ }
|
|
<div
|
|
className={[styles.game, devtoolsIsOpen && styles.devtoolsIsOpen].filter(Boolean).join(' ')}
|
|
onMouseDown={(event) => {
|
|
if (chatIsOpen) {
|
|
event.preventDefault();
|
|
return;
|
|
}
|
|
const where = computePosition(event);
|
|
switch (event.button) {
|
|
case 0:
|
|
if (devtoolsIsOpen) {
|
|
devEventsChannel.invoke(
|
|
'click',
|
|
where,
|
|
);
|
|
}
|
|
else {
|
|
client.send({
|
|
type: 'Action',
|
|
payload: {type: 'use', value: [1, where]},
|
|
});
|
|
}
|
|
break;
|
|
case 2:
|
|
if (monopolizers.length > 0) {
|
|
monopolizers[0].trigger();
|
|
break;
|
|
}
|
|
client.send({
|
|
type: 'Action',
|
|
payload: {type: 'interact', value: 1},
|
|
});
|
|
break;
|
|
}
|
|
}}
|
|
onMouseUp={(event) => {
|
|
if (chatIsOpen) {
|
|
event.preventDefault();
|
|
return;
|
|
}
|
|
const where = computePosition(event);
|
|
switch (event.button) {
|
|
case 0:
|
|
client.send({
|
|
type: 'Action',
|
|
payload: {type: 'use', value: [0, where]},
|
|
});
|
|
break;
|
|
case 2:
|
|
client.send({
|
|
type: 'Action',
|
|
payload: {type: 'interact', value: 0},
|
|
});
|
|
break;
|
|
}
|
|
event.preventDefault();
|
|
}}
|
|
onWheel={(event) => {
|
|
if (chatIsOpen) {
|
|
event.preventDefault();
|
|
return;
|
|
}
|
|
if (!isInventoryOpen) {
|
|
setHotbarIsHidden(false);
|
|
if (hotbarHideHandle) {
|
|
clearTimeout(hotbarHideHandle);
|
|
}
|
|
setHotbarHideHandle(setTimeout(() => {
|
|
setHotbarIsHidden(true);
|
|
}, 4000));
|
|
}
|
|
if (event.deltaY > 0) {
|
|
client.send({
|
|
type: 'Action',
|
|
payload: {type: 'changeSlot', value: 1 + ((activeSlot + 1) % 10)},
|
|
});
|
|
}
|
|
else {
|
|
client.send({
|
|
type: 'Action',
|
|
payload: {type: 'changeSlot', value: 1 + ((activeSlot + 9) % 10)},
|
|
});
|
|
}
|
|
}}
|
|
ref={gameRef}
|
|
>
|
|
<Pixi
|
|
camera={camera}
|
|
monopolizers={monopolizers}
|
|
particleWorker={particleWorker}
|
|
scale={scale}
|
|
/>
|
|
<Dom>
|
|
<HotBar
|
|
active={activeSlot}
|
|
hotbarIsHidden={hotbarIsHidden}
|
|
onActivate={(i) => {
|
|
keepHotbarOpen();
|
|
client.send({
|
|
type: 'Action',
|
|
payload: {type: 'swapSlots', value: [0, mainEntity, i + 1]},
|
|
});
|
|
}}
|
|
slots={inventorySlots.slice(0, 10)}
|
|
/>
|
|
<Bag
|
|
isInventoryOpen={isInventoryOpen}
|
|
onActivate={(i) => {
|
|
client.send({
|
|
type: 'Action',
|
|
payload: {type: 'swapSlots', value: [0, mainEntity, i + 11]},
|
|
});
|
|
}}
|
|
slots={inventorySlots.slice(10, 20)}
|
|
/>
|
|
{externalInventory && (
|
|
<External
|
|
isInventoryOpen={isInventoryOpen}
|
|
onActivate={(i) => {
|
|
client.send({
|
|
type: 'Action',
|
|
payload: {type: 'swapSlots', value: [0, externalInventory, i]},
|
|
});
|
|
}}
|
|
slots={externalInventorySlots}
|
|
/>
|
|
)}
|
|
<Entities
|
|
camera={camera}
|
|
scale={scale}
|
|
setChatMessages={setChatMessages}
|
|
setMonopolizers={setMonopolizers}
|
|
/>
|
|
{chatIsOpen && (
|
|
<Chat
|
|
chatHistory={chatHistory}
|
|
chatHistoryCaret={chatHistoryCaret}
|
|
chatInputRef={chatInputRef}
|
|
chatMessages={chatMessages}
|
|
message={message}
|
|
pendingMessage={pendingMessage}
|
|
setChatHistory={setChatHistory}
|
|
setChatHistoryCaret={setChatHistoryCaret}
|
|
setMessage={setMessage}
|
|
setPendingMessage={setPendingMessage}
|
|
onClose={() => {
|
|
setChatIsOpen(false);
|
|
}}
|
|
/>
|
|
)}
|
|
{showDisconnected && (
|
|
<Disconnected />
|
|
)}
|
|
</Dom>
|
|
</div>
|
|
{devtoolsIsOpen && (
|
|
<div className={[styles.devtools, devtoolsIsOpen && styles.devtoolsIsOpen].filter(Boolean).join(' ')}>
|
|
<Devtools
|
|
eventsChannel={devEventsChannel}
|
|
/>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default Ui;
|