silphius/app/react/components/pixi/sprite.jsx

91 lines
2.3 KiB
React
Raw Normal View History

2024-06-12 14:31:12 -05:00
import {Sprite as PixiSprite} from '@pixi/react';
2024-07-18 04:18:06 -05:00
import {useEffect, useState} from 'react';
2024-06-14 12:05:02 -05:00
2024-07-20 04:32:33 -05:00
import {useAsset} from '@/react/context/assets.js';
2024-06-12 14:31:12 -05:00
2024-07-19 01:27:47 -05:00
import {deferredLighting} from './lights.js';
2024-07-18 04:18:06 -05:00
function textureFromAsset(asset, animation, frame) {
2024-06-12 14:31:12 -05:00
if (!asset) {
2024-07-18 04:18:06 -05:00
return undefined;
2024-06-12 14:31:12 -05:00
}
let texture;
2024-07-02 12:00:12 -05:00
if (asset.data.animations) {
2024-07-25 10:48:22 -05:00
if (!animation) {
return undefined;
}
2024-07-18 04:18:06 -05:00
texture = asset.animations[animation][frame];
2024-06-12 14:31:12 -05:00
}
else {
2024-07-02 12:00:12 -05:00
texture = asset.textures[''];
2024-06-12 14:31:12 -05:00
}
2024-07-18 04:18:06 -05:00
return texture;
}
export default function Sprite({entity, ...rest}) {
const [mounted, setMounted] = useState();
const [normals, setNormals] = useState();
const [normalsMounted, setNormalsMounted] = useState();
2024-07-25 10:48:22 -05:00
const {alpha, anchor, animation, frame, scale, rotates, rotation, source} = entity.Sprite;
2024-07-18 04:18:06 -05:00
const asset = useAsset(source);
const normalsAsset = useAsset(normals);
useEffect(() => {
if (!asset) {
return;
}
const {normals} = asset.data.meta;
if (normals) {
const {pathname} = new URL(
source.split('/').slice(0, -1).concat(normals).join('/'),
'http://example.org',
);
setNormals(pathname);
}
}, [asset, source]);
const texture = textureFromAsset(
asset,
animation,
frame,
);
const normalsTexture = textureFromAsset(
normalsAsset,
animation,
frame,
);
if (mounted) {
2024-07-19 01:27:47 -05:00
mounted.parentGroup = deferredLighting.diffuseGroup;
2024-07-18 04:18:06 -05:00
}
if (normalsMounted) {
2024-07-19 01:27:47 -05:00
normalsMounted.parentGroup = deferredLighting.normalGroup;
2024-07-18 04:18:06 -05:00
}
2024-06-12 14:31:12 -05:00
return (
2024-07-18 04:18:06 -05:00
<>
{texture && (
<PixiSprite
2024-07-25 10:48:22 -05:00
alpha={alpha}
2024-07-18 04:18:06 -05:00
anchor={anchor}
ref={setMounted}
2024-07-25 10:48:22 -05:00
{...(rotates ? {rotation: entity.Direction.direction + rotation} : {})}
2024-07-18 04:18:06 -05:00
scale={scale}
texture={texture}
x={Math.round(entity.Position.x)}
y={Math.round(entity.Position.y)}
{...rest}
/>
)}
{normalsTexture && (
<PixiSprite
2024-07-25 10:48:22 -05:00
alpha={alpha}
2024-07-18 04:18:06 -05:00
anchor={anchor}
ref={setNormalsMounted}
2024-07-25 10:48:22 -05:00
{...(rotates ? {rotation: entity.Direction.direction + rotation} : {})}
2024-07-18 04:18:06 -05:00
scale={scale}
texture={normalsTexture}
x={Math.round(entity.Position.x)}
y={Math.round(entity.Position.y)}
{...rest}
/>
)}
</>
2024-06-12 14:31:12 -05:00
);
}