silphius/app/react-components/ecs.jsx

90 lines
2.3 KiB
JavaScript

import {Container} from '@pixi/react';
import {useEffect, useState} from 'react';
import {RESOLUTION} from '@/constants.js';
import {useEcs, useEcsTick} from '@/context/ecs.js';
import {useMainEntity} from '@/context/main-entity.js';
import Entities from './entities.jsx';
import TargetingGhost from './targeting-ghost.jsx';
import TargetingGrid from './targeting-grid.jsx';
import TileLayer from './tile-layer.jsx';
export default function EcsComponent() {
const [ecs] = useEcs();
const [entities, setEntities] = useState({});
const [activeTool, setActiveTool] = useState(false);
const [mainEntity] = useMainEntity();
useEffect(() => {
if (mainEntity) {
ecs.get(mainEntity)
.Wielder.activeItem()
.then(({tool} = {}) => {
setActiveTool(tool);
});
}
}, [ecs, mainEntity]);
useEcsTick((payload) => {
if (
mainEntity
&& payload[mainEntity]
&& (payload[mainEntity].Inventory || payload[mainEntity].Wielder)
) {
ecs.get(mainEntity)
.Wielder.activeItem()
.then(({tool} = {}) => {
setActiveTool(tool);
});
}
const updatedEntities = {...entities};
for (const id in payload) {
const update = payload[id];
if (false === update) {
delete updatedEntities[id];
}
else {
updatedEntities[id] = ecs.get(id);
if (update.Emitter?.emit) {
updatedEntities[id].Emitter.emitting = {
...updatedEntities[id].Emitter.emitting,
...update.Emitter.emit,
};
}
}
}
setEntities(updatedEntities);
}, [ecs, entities, mainEntity]);
if (!mainEntity) {
return false;
}
const entity = ecs.get(mainEntity);
const {Camera} = entity;
const {TileLayers: {layers: [layer]}} = ecs.get(1);
const [cx, cy] = [
Math.round(Camera.x - RESOLUTION.x / 2),
Math.round(Camera.y - RESOLUTION.y / 2),
];
return (
<Container
x={-cx}
y={-cy}
>
<TileLayer tileLayer={layer} />
{activeTool && (
<TargetingGrid
entity={entity}
tileLayer={layer}
/>
)}
<Entities entities={entities} />
{activeTool && (
<TargetingGhost
entity={entity}
projection={activeTool.projection}
tileLayer={layer}
/>
)}
</Container>
)
}