Compare commits

..

No commits in common. "6f7ec2e7ac40adc8206cc3a80a2f417235c27335" and "0c06dd7b83241f5fe05444c9ad4dd69ee2f36f97" have entirely different histories.

29 changed files with 103 additions and 193 deletions

View File

@ -26,9 +26,6 @@ module.exports = {
// Base config
extends: ['eslint:recommended'],
rules: {
'no-constant-condition': ['error', {checkLoops: false}],
},
overrides: [
// Tests
@ -84,7 +81,7 @@ module.exports = {
'assets/**/*.js',
],
rules: {
'no-undef': 0,
'no-undef': false,
},
}
],

View File

@ -1,9 +0,0 @@
import {createContext, useContext} from 'react';
const context = createContext();
export default context;
export function useEcs() {
return useContext(context);
}

View File

@ -7,3 +7,4 @@ export default context;
export function useMainEntity() {
return useContext(context);
}

View File

@ -1,6 +1,7 @@
import Arbitrary from '@/ecs/arbitrary.js';
import Base from '@/ecs/base.js';
import Schema from '@/ecs/schema.js';
import gather from '@/util/gather.js';
import gather from '@/engine/gather.js';
const specificationsAndOrDecorators = gather(
import.meta.glob('./*.js', {eager: true, import: 'default'}),
@ -16,7 +17,7 @@ for (const componentName in specificationsAndOrDecorators) {
if ('function' === typeof specificationOrDecorator) {
Components[componentName] = specificationOrDecorator(
class Decorated extends Arbitrary {
static componentName = componentName;
static name = componentName;
}
);
if (!Components[componentName]) {
@ -25,7 +26,7 @@ for (const componentName in specificationsAndOrDecorators) {
}
else {
Components[componentName] = class Component extends Arbitrary {
static componentName = componentName;
static name = componentName;
static schema = new Schema({
type: 'object',
properties: specificationOrDecorator,

View File

@ -2,60 +2,13 @@ import Schema from '@/ecs/schema.js';
export default function(Component) {
return class Inventory extends Component {
insertMany(entities) {
for (const [id, {slotChanged}] of entities) {
if (slotChanged) {
for (const slotIndex in slotChanged) {
this.get(id).slots[slotIndex] = {
...this.get(id).slots[slotIndex],
...slotChanged[slotIndex],
};
}
}
}
return super.insertMany(entities);
}
markChange(entityId, key, value) {
if ('slotChange' === key) {
const {index, change} = value;
return super.markChange(entityId, key, {[index]: change});
}
return super.markChange(entityId, key, value);
}
mergeDiff(original, update) {
if (update.slotChange) {
if (!original.slotChange) {
original.slotChange = {};
}
const merged = {};
for (const index in update.slotChange) {
merged[index] = {
...original.slotChange[index],
...update.slotChange[index],
};
}
return {slotChanged: merged};
}
return super.mergeDiff(original, update);
}
instanceFromSchema() {
const Instance = super.instanceFromSchema();
const Component = this;
Instance.prototype.item = function (slot) {
const {slots} = this;
const instance = this;
for (const index in slots) {
const item = slots[index];
if (slot === item.slotIndex) {
const proxy = new Proxy(item, {
set(target, property, value) {
target[property] = value;
const change = {[property]: value};
Component.markChange(instance.entity, 'slotChange', {index, change});
return true;
},
});
return proxy;
for (const {slotIndex, source} of this.slots) {
if (slot === slotIndex) {
return source;
}
}
};

View File

@ -1,54 +1,28 @@
import {RESOLUTION} from '@/constants.js'
import {System} from '@/ecs/index.js';
const [hx, hy] = [RESOLUTION.x / 2, RESOLUTION.y / 2];
export default class FollowCamera extends System {
static queries() {
return {
default: ['Camera', 'Position'],
};
}
reindex(entities) {
super.reindex(entities);
for (const id of entities) {
this.updateCamera(1, this.ecs.get(id));
this.updateCamera(this.ecs.get(id));
}
}
tick(elapsed) {
for (const [, , entityId] of this.select('default')) {
this.updateCamera(elapsed * 3, this.ecs.get(entityId));
tick() {
for (const entity of this.ecs.changed(['Position'])) {
this.updateCamera(entity);
}
}
updateCamera(portion, entity) {
updateCamera(entity) {
const {Camera, Position} = entity;
if (Camera && Position) {
const {AreaSize: {x, y}} = this.ecs.get(1);
const [px, py] = [
Math.max(hx, Math.min(Math.round(Position.x), x - hx)),
Math.max(hy, Math.min(Math.round(Position.y), y - hy)),
];
if (Camera.x === px && Camera.y === py) {
return;
}
if (Math.abs(Camera.x - px) < 0.1) {
Camera.x = px;
}
if (Math.abs(Camera.y - py) < 0.1) {
Camera.y = py;
}
const [dx, dy] = [
(px - Camera.x) * portion,
(py - Camera.y) * portion,
];
[Camera.x, Camera.y] = [
Camera.x + (Math.sign(dx) * Math.max(0.1, Math.abs(dx))),
Camera.y + (Math.sign(dy) * Math.max(0.1, Math.abs(dy))),
];
const [hx, hy] = [RESOLUTION.x / 2, RESOLUTION.y / 2];
Camera.x = Math.max(hx, Math.min(Position.x, x - hx));
Camera.y = Math.max(hy, Math.min(Position.y, y - hy));
}
}

View File

@ -1,3 +1,3 @@
import gather from '@/util/gather.js';
import gather from '@/engine/gather.js';
export default gather(import.meta.glob('./*.js', {eager: true, import: 'default'}));

View File

@ -83,7 +83,7 @@ export default class Base {
}
markChange(entityId, key, value) {
this.ecs.markChange(entityId, {[this.constructor.componentName]: {[key]: value}})
this.ecs.markChange(entityId, {[this.constructor.name]: {[key]: value}})
}
mergeDiff(original, update) {

View File

@ -75,6 +75,7 @@ export default class Ecs {
},
next: () => {
let result = it.next();
let satisfied = false;
while (!result.done) {
for (const componentName of criteria) {
if (!(componentName in result.value[1])) {

View File

@ -114,7 +114,7 @@ export default class Engine {
Inventory: {
slots: [
{
qty: 500,
qty: 10,
slotIndex: 0,
source: '/assets/potion',
}
@ -221,11 +221,10 @@ export default class Engine {
entity,
payload,
] of this.incomingActions) {
const {Controlled, Inventory, Ticking, Wielder} = entity;
const {Ecs, Controlled, id, Inventory, Position, Ticking, Wielder} = entity;
switch (payload.type) {
case 'changeSlot': {
Wielder.activeSlot = payload.value - 1;
break;
}
case 'moveUp':
case 'moveRight':
@ -237,11 +236,11 @@ export default class Engine {
case 'use': {
if (payload.value) {
const item = Inventory.item(Wielder.activeSlot);
this.server.readAsset(item.source + '/start.js')
this.server.readAsset(item + '/start.js')
.then((response) => response.text())
.then((code) => {
Ticking.addTickingPromise(
Script.tickingPromise(code, {item, wielder: entity}),
Script.tickingPromise(code, {console, wielder: entity}),
);
});
}

View File

@ -7,13 +7,17 @@ export default function gather(imports, options = {}) {
mapperForPath = (path) => path.replace(/\.\/(.*)\.js/, '$1'),
} = options;
const Gathered = {};
let id = 1;
for (const [path, Component] of Object.entries(imports).sort(([l], [r]) => l < r ? -1 : 1)) {
Gathered[
mapperForPath(path)
.split('-')
.map(capitalize)
.join('')
] = Component;
const key = mapperForPath(path)
.split('-')
.map(capitalize)
.join('');
if (Component.gathered) {
Component.gathered(id, key);
}
Gathered[key] = Gathered[id] = Component;
id += 1;
}
return Gathered;
}

18
app/engine/gather.test.js Normal file
View File

@ -0,0 +1,18 @@
import {expect, test} from 'vitest';
import gather from './gather.js';
test('gathers', async () => {
const Gathered = gather(
import.meta.glob('./test/*.js', {eager: true, import: 'default'}),
{mapperForPath: (path) => path.replace(/\.\/test\/(.*)\.js/, '$1')},
);
expect(Gathered.First.key)
.to.equal('First');
expect(Gathered[1].id)
.to.equal(1);
expect(Gathered.Second.key)
.to.equal('Second');
expect(Gathered[2].id)
.to.equal(2);
});

View File

@ -12,6 +12,5 @@ export default function usePacket(type, fn, dependencies) {
return () => {
client.removePacketListener(type, fn);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [client, ...dependencies]);
}

View File

@ -5,6 +5,9 @@ const encoder = new Encoder();
export default class Packet {
static id;
static type;
static decode(view) {
return decoder.decode(new DataView(view.buffer, view.byteOffset + 2, view.byteLength - 2));
}
@ -15,6 +18,11 @@ export default class Packet {
return new DataView(encoder.bytes.buffer, 0, encoder.pos);
}
static gathered(id, type) {
this.id = id;
this.type = type;
}
static pack(payload) {
return payload;
}

View File

@ -2,7 +2,7 @@ import {get, set} from 'idb-keyval';
import {encode} from '@/packets/index.js';
import Engine from '../../engine.js';
import Engine from '../../engine/engine.js';
import Server from './server.js';
class WorkerServer extends Server {
@ -51,10 +51,8 @@ onmessage = async (event) => {
postMessage(encode({type: 'ConnectionStatus', payload: 'connected'}));
})();
if (import.meta.hot) {
import.meta.hot.accept('../engine/engine.js', async () => {
await engine.disconnectPlayer(0, 0);
postMessage(encode({type: 'ConnectionStatus', payload: 'aborted'}));
close();
});
}
import.meta.hot.accept('../../engine/engine.js', async () => {
await engine.disconnectPlayer(0, 0);
postMessage(encode({type: 'ConnectionStatus', payload: 'aborted'}));
close();
});

View File

@ -1,22 +1,20 @@
import gather from '@/util/gather.js';
import gather from '@/engine/gather.js';
const Gathered = gather(import.meta.glob('./*.js', {eager: true, import: 'default'}));
const typeToId = new Map(Object.entries(Gathered).map(([type], id) => [type, id]));
const idToType = new Map(Object.entries(Gathered).map(([type], id) => [id, type]));
export function decode(packed) {
const view = ArrayBuffer.isView(packed) ? packed : new DataView(packed);
const type = idToType.get(view.getUint16(0, true));
const Packet = Gathered[type];
const id = view.getUint16(0, true);
const Packet = Gathered[id];
return {
type,
type: Packet.type,
payload: Packet.decode(view),
};
}
export function encode(packet) {
const encoded = Gathered[packet.type].encode(packet.payload);
encoded.setUint16(0, typeToId.get(packet.type), true);
const Packet = Gathered[packet.type];
const encoded = Packet.encode(packet.payload);
encoded.setUint16(0, Packet.id, true);
return encoded;
}

View File

@ -24,7 +24,7 @@ export default function Dom({children}) {
return () => {
window.removeEventListener('resize', onResize);
}
});
}, [ref.current]);
return (
<div className={styles.dom} ref={ref}>
{scale > 0 && (

View File

@ -2,8 +2,10 @@ import {Container} from '@pixi/react';
import {useState} from 'react';
import {RESOLUTION} from '@/constants.js';
import {useEcs} from '@/context/ecs.js';
import {useMainEntity} from '@/context/main-entity.js';
import Ecs from '@/ecs/ecs.js';
import Components from '@/ecs-components/index.js';
import Systems from '@/ecs-systems/index.js';
import usePacket from '@/hooks/use-packet.js';
import Entities from './entities.jsx';
@ -11,13 +13,14 @@ import TargetingGhost from './targeting-ghost.jsx';
import TileLayer from './tile-layer.jsx';
export default function EcsComponent() {
const [ecs] = useEcs();
const [ecs] = useState(new Ecs({Components, Systems}));
const [entities, setEntities] = useState({});
const [mainEntity] = useMainEntity();
usePacket('Tick', (payload) => {
if (0 === Object.keys(payload.ecs).length) {
return;
}
ecs.apply(payload.ecs);
const updatedEntities = {...entities};
for (const id in payload.ecs) {
if (false === payload.ecs[id]) {

View File

@ -7,7 +7,6 @@ import {createElement, useContext} from 'react';
import {RESOLUTION} from '@/constants.js';
import ClientContext from '@/context/client.js';
import EcsContext from '@/context/ecs.js';
import MainEntityContext from '@/context/main-entity.js';
import Ecs from './ecs.jsx';
@ -15,9 +14,7 @@ import styles from './pixi.module.css';
BaseTexture.defaultOptions.scaleMode = SCALE_MODES.NEAREST;
const Contexts = [ClientContext, EcsContext, MainEntityContext];
const ContextBridge = ({children, render}) => {
const ContextBridge = ({children, Contexts, render}) => {
const contexts = Contexts.map(useContext);
return render(
<>
@ -36,6 +33,7 @@ const ContextBridge = ({children, render}) => {
export const Stage = ({children, ...props}) => {
return (
<ContextBridge
Contexts={[ClientContext, MainEntityContext]}
render={(children) => <PixiStage {...props}>{children}</PixiStage>}
>
{children}

View File

@ -3,7 +3,6 @@ import {useContext, useEffect, useState} from 'react';
import addKeyListener from '@/add-key-listener.js';
import {RESOLUTION} from '@/constants.js';
import ClientContext from '@/context/client.js';
import {useEcs} from '@/context/ecs.js';
import {useMainEntity} from '@/context/main-entity.js';
import usePacket from '@/hooks/use-packet.js';
@ -19,7 +18,6 @@ export default function Ui({disconnected}) {
// Key input.
const client = useContext(ClientContext);
const [mainEntity, setMainEntity] = useMainEntity();
const [ecs] = useEcs();
const [showDisconnected, setShowDisconnected] = useState(false);
const [hotbarSlots, setHotbarSlots] = useState(Array(10).fill(0).map(() => {}));
const [activeSlot, setActiveSlot] = useState(0);
@ -138,38 +136,25 @@ export default function Ui({disconnected}) {
if (0 === Object.keys(payload.ecs).length) {
return;
}
ecs.apply(payload.ecs);
let localMainEntity = mainEntity;
for (const id in payload.ecs) {
const update = payload.ecs[id];
if (update?.MainEntity) {
if (payload.ecs[id]?.MainEntity) {
setMainEntity(localMainEntity = id);
}
if (localMainEntity === id) {
if (update.Inventory) {
if (payload.ecs[id].Inventory) {
const newHotbarSlots = [...hotbarSlots];
const {slots, slotChanged} = update.Inventory;
if (slotChanged) {
for (const slotIndex in slotChanged) {
payload.ecs[id].Inventory.slots
.forEach(({qty, slotIndex, source}) => {
newHotbarSlots[slotIndex] = {
...newHotbarSlots[slotIndex],
...slotChanged[slotIndex],
image: source + '/icon.png',
qty,
};
}
}
if (slots) {
slots
.forEach(({qty, slotIndex, source}) => {
newHotbarSlots[slotIndex] = {
image: source + '/icon.png',
qty,
};
});
}
});
setHotbarSlots(newHotbarSlots);
}
if (update.Wielder && 'activeSlot' in update.Wielder) {
setActiveSlot(update.Wielder.activeSlot);
if (payload.ecs[id].Wielder && 'activeSlot' in payload.ecs[id].Wielder) {
setActiveSlot(payload.ecs[id].Wielder.activeSlot);
}
}
}

View File

@ -3,11 +3,8 @@ import {useEffect, useState} from 'react';
import {useOutletContext, useParams} from 'react-router-dom';
import ClientContext from '@/context/client.js';
import EcsContext from '@/context/ecs.js';
import MainEntityContext from '@/context/main-entity.js';
import Ecs from '@/ecs/ecs.js';
import Components from '@/ecs-components/index.js';
import Systems from '@/ecs-systems/index.js';
import Ui from '@/react-components/ui.jsx';
import {juggleSession} from '@/session.server';
@ -20,7 +17,6 @@ export default function PlaySpecific() {
const Client = useOutletContext();
const [client, setClient] = useState();
const mainEntityTuple = useState();
const ecsTuple = useState(new Ecs({Components, Systems}));
const [disconnected, setDisconnected] = useState(false);
const params = useParams();
const [type, url] = params['*'].split('/');
@ -43,7 +39,7 @@ export default function PlaySpecific() {
if ('local' !== type) {
return;
}
async function onBeforeUnload() {
async function onBeforeUnload(event) {
client.disconnect();
function waitForSave() {
return new Promise((resolve) => setTimeout(resolve, 0));
@ -92,9 +88,7 @@ export default function PlaySpecific() {
return (
<ClientContext.Provider value={client}>
<MainEntityContext.Provider value={mainEntityTuple}>
<EcsContext.Provider value={ecsTuple}>
<Ui disconnected={disconnected} />
</EcsContext.Provider>
<Ui disconnected={disconnected} />
</MainEntityContext.Provider>
</ClientContext.Provider>
);

View File

@ -1,17 +0,0 @@
import {expect, test} from 'vitest';
import gather from './gather.js';
import First from './gather-test/first.js';
import Second from './gather-test/second.js';
test('gathers', async () => {
const Gathered = gather(
import.meta.glob('./gather-test/*.js', {eager: true, import: 'default'}),
{mapperForPath: (path) => path.replace(/\.\/gather-test\/(.*)\.js/, '$1')},
);
expect(Gathered.First)
.to.equal(First);
expect(Gathered.Second)
.to.equal(Second);
});

View File

@ -146,4 +146,4 @@ export default class Script {
);
}
}
};

View File

@ -4,7 +4,7 @@ import TickingPromise from './ticking-promise.js';
test('runs executor', async () => {
expect(
await new TickingPromise((resolve) => {
await new TickingPromise((resolve, reject) => {
resolve(32);
}),
)

View File

@ -6,7 +6,7 @@ import {WebSocketServer} from 'ws';
import Server from '@/net/server/server.js';
import {getSession} from '@/session.server.js';
import Engine from './engine.js';
import Engine from './engine/engine.js';
const wss = new WebSocketServer({
noServer: true,
@ -85,7 +85,7 @@ async function remakeServer(Engine) {
})();
if (import.meta.hot) {
import.meta.hot.accept('./engine.js', async ({default: Engine}) => {
import.meta.hot.accept('./engine/engine.js', async ({default: Engine}) => {
await remakeServer(Engine);
});
}

View File

@ -1,2 +1,7 @@
wielder.Health.health += 10
item.qty -= 1
wielder.Inventory.slots = [
{
...wielder.Inventory.slots[0],
qty: wielder.Inventory.slots[0].qty - 1,
}
]