silphius/app/react/components/pixi/water.jsx
2024-07-28 18:51:52 -05:00

60 lines
1.5 KiB
JavaScript

import {Container, Graphics} from '@pixi/react';
import {forwardRef, memo, useCallback, useEffect, useRef, useState} from 'react';
import {deferredLighting} from './lights.js';
const WaterTile = forwardRef(function WaterTile({height, width}, ref) {
const draw = useCallback((g) => {
g.clear();
g.beginFill(0x000000);
g.drawRect(
0,
0,
width,
height
);
}, [height, width]);
return <Graphics alpha={0} draw={draw} ref={ref} />
});
function Water({tileLayer, water}) {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
const waterTile = useRef();
const waterTiles = [];
if (mounted) {
for (const tileIndex in water) {
const tileIndexNumber = parseInt(tileIndex);
const tx = tileIndexNumber % tileLayer.area.x;
const ty = (tileIndexNumber - tx) / tileLayer.area.x;
waterTiles.push(
<Graphics
x={tx * tileLayer.tileSize.x}
y={ty * tileLayer.tileSize.y}
alpha={Math.floor(water[tileIndex]) / (256 * 2)}
key={tileIndex}
geometry={waterTile.current}
/>
);
}
}
return (
<Container ref={(element) => {
if (element) {
element.parentGroup = deferredLighting.diffuseGroup;
}
}}>
<WaterTile
height={tileLayer.tileSize.y}
ref={waterTile}
width={tileLayer.tileSize.x}
/>
{waterTiles}
</Container>
);
}
export default memo(Water);