From facb277db0faef9c79ffc20c32b7d801aa3dad34 Mon Sep 17 00:00:00 2001 From: Jeffrey Alan Scudder Date: Tue, 19 Dec 2023 18:37:26 -0500 Subject: [PATCH] abstract `field` into `world` to prep for other areas --- package.json | 5 +- session-server/package-lock.json | 50 +- session-server/package.json | 2 +- session-server/session.mjs | 28 +- system/package.json | 2 +- .../public/aesthetic.computer/disks/field.mjs | 624 +----------------- system/public/aesthetic.computer/lib/disk.mjs | 34 +- .../aesthetic.computer/systems/world.mjs | 615 +++++++++++++++++ 8 files changed, 714 insertions(+), 646 deletions(-) create mode 100644 system/public/aesthetic.computer/systems/world.mjs diff --git a/package.json b/package.json index a3fb856dcb..d99703ef5a 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "ext": "cd vscode-extension; npm run reload;", "ext:publish": "cd vscode-extension; npm run publish;", "code": "cd system; npm run codespaces-dev", - "stripe": "cd system; npm run stripe-dev", + "stripe": "cd system; npm run stripe-dev-sotce", "edge": "vercel dev", "edge.old": "concurrently --raw \"vercel dev\" \"http-server edge-stream -p 9000 --cors -c-1 -i --P http://localhost:3000 -S --cert ssl-dev/localhost.pem --key ssl-dev/localhost-key.pem\"", "code:debug": "cd system; npm run codespaces-dev-debug", @@ -22,6 +22,9 @@ "server:socket": "cd socket-server; npm run server", "assets:sync:down": "aws s3 sync s3://assets-aesthetic-computer system/public/assets --endpoint-url https://sfo3.digitaloceanspaces.com", "assets:sync:up": "aws s3 sync system/public/assets s3://assets-aesthetic-computer --endpoint-url https://sfo3.digitaloceanspaces.com --exclude '*.DS_Store' --acl public-read", + "session:reset": "f() { cd session-server; npx jamsocket backend terminate $1 };f", + "session:alive": "cd session-server; npx jamsocket backend list", + "session:publish": "cd session-server; npm run build; npm run deploy", "server:session": "cd session-server; npm run dev", "server:session:build": "cd session-server; npm run build:jamsocket", "server:session:deploy": "cd session-server; npm run deploy", diff --git a/session-server/package-lock.json b/session-server/package-lock.json index 980dd6300c..a668efefa7 100644 --- a/session-server/package-lock.json +++ b/session-server/package-lock.json @@ -14,7 +14,7 @@ "fastify": "^4.19.2", "firebase-admin": "^12.0.0", "ip": "^1.1.8", - "jamsocket": "^0.7.2", + "jamsocket": "^0.7.3", "redis": "^4.6.7", "ws": "^8.13.0" }, @@ -23,9 +23,9 @@ } }, "node_modules/@babel/runtime": { - "version": "7.23.4", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.4.tgz", - "integrity": "sha512-2Yv65nlWnWlSpe3fXEyX5i7fx5kIKo4Qbcj+hMO0odwaneFjfXw5fdum+4yL20O0QiaHpia0cYQ9xpNMqrBwHg==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.6.tgz", + "integrity": "sha512-zHd0eUrf5GZoOWVCXp6koAKQTfZV07eit6bGPmJgnZdnSAvvZee6zniW2XMF7Cmc4ISOOnPy3QaSiIJGJkVEDQ==", "dependencies": { "regenerator-runtime": "^0.14.0" }, @@ -1065,9 +1065,9 @@ } }, "node_modules/cli-spinners": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.1.tgz", - "integrity": "sha512-jHgecW0pxkonBJdrKsqxgRX9AcG+u/5k0Q7WPDfi8AogLAdwxEkyYYNWwZ5GvVFoFx2uiY1eNcSK00fh+1+FyQ==", + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", "engines": { "node": ">=6" }, @@ -2128,9 +2128,9 @@ } }, "node_modules/jamsocket": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/jamsocket/-/jamsocket-0.7.2.tgz", - "integrity": "sha512-B2Qe+Yvh2lxoJijgzARn5snBZ9qmA4CUARr6kW56T/B0nZukPU+cdYt/PQp9ZOhZVpNWHUmeIJuwixYfZoLwzg==", + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/jamsocket/-/jamsocket-0.7.3.tgz", + "integrity": "sha512-gNId2oltxRJA1Me8MLDnc1yyfOEdqH/J8iP67mR5EB3lF9mDBs//tDgA0/n2pVO8q1beolTFBOiTU4cZVGxLDw==", "dependencies": { "@oclif/core": "1.9.0", "@oclif/plugin-help": "5.1.12", @@ -3536,9 +3536,9 @@ } }, "node_modules/regenerator-runtime": { - "version": "0.14.0", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.0.tgz", - "integrity": "sha512-srw17NI0TUWHuGa5CFGGmhfNIeja30WMBfbslPNhf6JrqQlLN5gcrvig1oqPxiVaXb0oW0XRKtH6Nngs5lKCIA==" + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz", + "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==" }, "node_modules/require-directory": { "version": "2.1.1", @@ -4236,9 +4236,9 @@ }, "dependencies": { "@babel/runtime": { - "version": "7.23.4", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.4.tgz", - "integrity": "sha512-2Yv65nlWnWlSpe3fXEyX5i7fx5kIKo4Qbcj+hMO0odwaneFjfXw5fdum+4yL20O0QiaHpia0cYQ9xpNMqrBwHg==", + "version": "7.23.6", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.23.6.tgz", + "integrity": "sha512-zHd0eUrf5GZoOWVCXp6koAKQTfZV07eit6bGPmJgnZdnSAvvZee6zniW2XMF7Cmc4ISOOnPy3QaSiIJGJkVEDQ==", "requires": { "regenerator-runtime": "^0.14.0" } @@ -5077,9 +5077,9 @@ } }, "cli-spinners": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.1.tgz", - "integrity": "sha512-jHgecW0pxkonBJdrKsqxgRX9AcG+u/5k0Q7WPDfi8AogLAdwxEkyYYNWwZ5GvVFoFx2uiY1eNcSK00fh+1+FyQ==" + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==" }, "cli-width": { "version": "3.0.0", @@ -5856,9 +5856,9 @@ } }, "jamsocket": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/jamsocket/-/jamsocket-0.7.2.tgz", - "integrity": "sha512-B2Qe+Yvh2lxoJijgzARn5snBZ9qmA4CUARr6kW56T/B0nZukPU+cdYt/PQp9ZOhZVpNWHUmeIJuwixYfZoLwzg==", + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/jamsocket/-/jamsocket-0.7.3.tgz", + "integrity": "sha512-gNId2oltxRJA1Me8MLDnc1yyfOEdqH/J8iP67mR5EB3lF9mDBs//tDgA0/n2pVO8q1beolTFBOiTU4cZVGxLDw==", "requires": { "@oclif/core": "1.9.0", "@oclif/plugin-help": "5.1.12", @@ -6878,9 +6878,9 @@ } }, "regenerator-runtime": { - "version": "0.14.0", - "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.0.tgz", - "integrity": "sha512-srw17NI0TUWHuGa5CFGGmhfNIeja30WMBfbslPNhf6JrqQlLN5gcrvig1oqPxiVaXb0oW0XRKtH6Nngs5lKCIA==" + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz", + "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==" }, "require-directory": { "version": "2.1.1", diff --git a/session-server/package.json b/session-server/package.json index cb212bc30b..962ee46b39 100644 --- a/session-server/package.json +++ b/session-server/package.json @@ -24,7 +24,7 @@ "fastify": "^4.19.2", "firebase-admin": "^12.0.0", "ip": "^1.1.8", - "jamsocket": "^0.7.2", + "jamsocket": "^0.7.3", "redis": "^4.6.7", "ws": "^8.13.0" }, diff --git a/session-server/session.mjs b/session-server/session.mjs index aa65fedf50..5b73293680 100644 --- a/session-server/session.mjs +++ b/session-server/session.mjs @@ -64,6 +64,24 @@ if (dev) { fastify = Fastify({ logger: true }); // Still log in production. No reason not to? } +// Insert `cors` headers as needed. 23.12.19.16.31 +// TODO: Is this even necessary? +fastify.options("*", async (req, reply) => { + const allowedOrigins = [ + "https://aesthetic.local:8888", + "https://aesthetic.computer", + ]; + + const origin = req.headers.origin; + console.log("✈ïļ Preflight origin:", origin); + // Check if the incoming origin is allowed + if (allowedOrigins.includes(origin)) { + reply.header("Access-Control-Allow-Origin", origin); + } + reply.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); + reply.send(); +}); + const server = fastify.server; const info = { @@ -297,14 +315,16 @@ wss.on("connection", (ws, req) => { if (!codeChannels[codeChannel]) codeChannels[codeChannel] = new Set(); codeChannels[codeChannel].add(id); } else { - // `world:field` - if (msg.type.startsWith("world:field")) { - const label = (msg.label = msg.type.split(":").pop()); + // Filter for `world:${piece}:${label}` type messages. + if (msg.type.startsWith("world:")) { + const parsed = msg.type.split(":"); + const piece = parsed[1]; + const label = parsed.pop(); // TODO: Store client position on disconnect, based on their handle. if (label === "join") { - ws.send(pack("world:field:list", worldClients, id)); + ws.send(pack(`world:${piece}:list`, worldClients, id)); // ^ Send existing list to everyone but this user. worldClients[msg.id] = { ...msg.content }; // Add user client list. others(JSON.stringify(msg)); // Alert everyone else about the join. diff --git a/system/package.json b/system/package.json index 62ef4dc134..17aa372fb5 100644 --- a/system/package.json +++ b/system/package.json @@ -10,7 +10,7 @@ "test": "NODE_OPTIONS='--experimental-vm-modules --es-module-specifier-resolution=node' jest", "codespaces-dev": "kill-port 8880 8888 8889 8080 8000 8111 3333 3000 3001; netlify dev", "stripe-dev-print": "stripe listen --forward-to https://localhost:8888/api/print", - "stripe-dev": "stripe listen --forward-to https://localhost:8888/api/ticket/sotce", + "stripe-dev-sotce": "stripe listen --forward-to https://localhost:8888/api/ticket/sotce", "spaces-dev-netlify": "http-server public -p 8111 --cors -c-1 -i -s", "codespaces-dev-debug": "kill-port 8889 8888 8080 8000 8111 3333; netlify dev --debug", "codespaces-dev-public": "kill-port 8080 8888 8889 8000 8111 3333; netlify dev --live", diff --git a/system/public/aesthetic.computer/disks/field.mjs b/system/public/aesthetic.computer/disks/field.mjs index bb04e1b526..4757d50374 100644 --- a/system/public/aesthetic.computer/disks/field.mjs +++ b/system/public/aesthetic.computer/disks/field.mjs @@ -5,8 +5,10 @@ #endregion */ /* #region 🏁 TODO - - [🍊] Move common functionality to a `world.mjs` library file. - - [] Store something persistent on the server... + - [x] Move common functionality to a `world.mjs` library file. + - [-] Move all functions over succesfully. + - [] Localize world geometry to this file. + - [] Store something persistent on the server? + Later + Done - [x] Slow camera following. @@ -48,622 +50,22 @@ - [x] `Enter` button appears and disappears at weird times. #endregion */ -// 🧒 -class Kid { - handle; - net; - pos = { x: 0, y: 0 }; - netPos; - size = 16; - leash = { x: 0, y: 0, len: 0, max: 12, deadzone: 8 }; - face = "meh"; - color = "white"; - #keys = { U: false, D: false, L: false, R: false }; - message; - #messageDuration; - #messageProgress = 0; - - constructor(handle = "?", pos = this.pos, face, net = false) { - this.handle = handle; - console.log("🧒 From:", this.handle, face); - - this.pos = pos; - if (net) this.netPos = { ...pos }; - - this.face = face || this.face; - this.net = net; // Is it from the network? - } - - // Show a message above the kid's head for `time` frames. - write(text, time = 320) { - this.message = text; - this.#messageDuration = time; - this.#messageProgress = 0; // Reset message progress. - } - - // Change the mood (face) of the kid. - mood(face) { - this.face = face; - } - - // Change the color of the kid. - tint(c) { - this.color = c; - } - - // Render the kid. - paint({ ink, pan, text, typeface }) { - const leash = this.leash; - pan(this.pos.x, this.pos.y); - ink(this.color).circle(0, 0, this.size); // Head - - // Face - // Eyes - ink(this.color).point(-6, -6); - ink(this.color).point(6, -6); - // Mouth - if (this.face === "smile") { - ink(this.color).line(0, 6, -6, 3); - ink(this.color).line(0, 6, 6, 3); - } else if (this.face === "frown") { - ink(this.color).line(0, 3, -6, 8); - ink(this.color).line(0, 3, 6, 8); - } else if (this.face === "meh") { - ink(this.color).line(-6, 6, 6, 6); - } - - ink(leash.len > leash.deadzone ? this.color : [this.color, 128]).line( - 0, - 0, - leash.x, - leash.y, - ); - if (this.message) { - const blockWidth = typeface.glyphs["0"].resolution[0]; - const tb = text.box( - this.message, - undefined, - this.message.length * blockWidth, - ); - ink(this.color).write(this.message, { - x: -tb.box.width / 2, - y: -this.size - 12, - }); - } - } - - // Control the kid. - act({ event: e, num }) { - const k = this.#keys; - const leash = this.leash; - if (e.is("keyboard:down:w") || e.is("keyboard:down:arrowup")) k.U = true; - if (e.is("keyboard:down:s") || e.is("keyboard:down:arrowdown")) k.D = true; - if (e.is("keyboard:down:a") || e.is("keyboard:down:arrowleft")) k.L = true; - if (e.is("keyboard:down:d") || e.is("keyboard:down:arrowright")) k.R = true; - if (e.is("keyboard:up:w") || e.is("keyboard:up:arrowup")) k.U = false; - if (e.is("keyboard:up:s") || e.is("keyboard:up:arrowdown")) k.D = false; - if (e.is("keyboard:up:a") || e.is("keyboard:up:arrowleft")) k.L = false; - if (e.is("keyboard:up:d") || e.is("keyboard:up:arrowright")) k.R = false; - - if (e.is("touch:1")) leash.start = { x: e.x, y: e.y }; - - if (e.is("draw:1") && leash.start) { - leash.x = e.x - leash.start.x; - leash.y = e.y - leash.start.y; - this.#snapLeash(num); - } - - if (e.is("lift:1")) leash.start = null; - } - - // Simulate the kid's movement and time messages. - sim({ num }, net) { - // 🗞 Network Prediction - if (this.net && this.netPos) { - const p2 = num.p2; - const STEP_SIZE = 1; - const direction = p2.norm(p2.sub(this.netPos, this.pos)); - const distance = p2.len(p2.sub(this.netPos, this.pos)); - if (distance < STEP_SIZE) { - this.pos = this.netPos; // Set position to target. - } else { - this.pos = p2.inc(this.pos, p2.scl(direction, STEP_SIZE)); - } - return; // No need to compute movements, locally. - } - - // Local simulation. - - // ðŸ—Ļïļ Message - if (this.message) { - if (this.#messageProgress < this.#messageDuration) { - this.#messageProgress += 1; - } else { - this.message = null; - this.#messageProgress = 0; - net?.({ clear: true }); - } - } - - // 🏃 Movement - const k = this.#keys, - leash = this.leash, - pos = this.pos; - - if (k.U) leash.y -= 1; - if (k.D) leash.y += 1; - if (k.L) leash.x -= 1; - if (k.R) leash.x += 1; - - this.#snapLeash(num); - - if (!leash.start) { - leash.y *= 0.97; - leash.x *= 0.97; - } - - const newPos = { ...pos }; - if (leash.len > leash.deadzone) { - newPos.x = num.lerp(pos.x, pos.x + leash.x, 0.075); - newPos.y = num.lerp(pos.y, pos.y + leash.y, 0.075); - } else if (leash.len > 1) { - newPos.x = num.lerp(pos.x, pos.x + leash.x, 0.025); - newPos.y = num.lerp(pos.y, pos.y + leash.y, 0.025); - } - - // Run the net callback whenever the position changes. - if (newPos.x !== pos.x || newPos.y !== pos.y) net?.({ pos }); - - pos.x = newPos.x; - pos.y = newPos.y; - - if (pos.x < 0) pos.x = 0; - if (pos.x > world.size.width) pos.x = world.size.width; - if (pos.y < 0) pos.y = 0; - if (pos.y > world.size.height) pos.y = world.size.height; - } - - // Limit the kid's movement leash. - #snapLeash(num) { - const leash = this.leash; - leash.len = num.p2.len(leash); - if (leash.len > leash.max) { - const scale = leash.max / leash.len; - leash.x *= scale; - leash.y *= scale; - } - } - - // Kill all controls. - off() { - const k = this.#keys; - k.U = k.D = k.L = k.R = false; - this.leash.start = null; - } - - // Return the screen position of this kid, given a camera and world, - screenPos(cam, world) { - return { x: cam.x + this.pos.x, y: cam.y + this.pos.y }; - } -} - -// 🌎 -class World { - size = {}; - constructor(width = 192, height = 192) { - this.size.width = width; - this.size.height = height; - } - - paint({ ink }) { - ink("green").box(0, 0, this.size.width, this.size.height); - } -} - -// ðŸŽĨ -class Cam { - x = 0; - y = 0; - dolly = { x: 0, y: 0 }; - - constructor(x, y, dolly) { - this.x = x; - this.y = y; - this.dolly = { ...dolly }; - } -} - -let me, world, cam, input, inputBtn, server; -const scenery = { - grasses: [ - { x: 190, y: 170 }, - { x: 276, y: 286 }, - { x: 128, y: 128 }, - { x: 400, y: 400 }, - { x: 500, y: 512 }, - ], -}; -const kids = {}; - -const { keys, values } = Object; - // ðŸĨū Boot -async function boot({ - api, - help, - wipe, - handle, - screen, - ui, - send, - net: { socket }, - sound, - store, -}) { - // âœĻ Initialization & Interface +async function boot({ wipe }) { wipe(0); - world = new World(512, 512); - const pos = (await store.retrieve("field:pos")) || { - x: undefined, - y: undefined, - }; - - me = new Kid( - handle(), - { x: pos.x || world.size.width / 2, y: pos.y || world.size.height / 2 }, - help.choose("meh", "smile", "frown"), - ); - - cam = new Cam( - screen.width / 2 - me.pos.x, - screen.height / 2 - me.pos.y, - me.pos, - ); - - const scheme = { - dark: { - fg: 255, - bg: [0, 100], - block: 255, - blockHi: 0, - line: 255, - }, - }; - - input = new ui.TextInput( - api, - "...", - async (text) => { - if ( - input.text === "smile" || - input.text === "frown" || - input.text === "sad" || - input.text === "meh" - ) { - if (input.text === "sad") input.text = "frown"; - me.mood(input.text); - server.send("world:field:mood", me.face); // Send to server. - } else if ( - input.text === "red" || - input.text === "yellow" || - input.text === "orange" || - input.text === "black" || - input.text === "brown" || - input.text === "purple" || - input.text === "pink" || - input.text === "blue" || - input.text === "lime" || - input.text === "white" - ) { - me.tint(input.text); - server.send("world:field:tint", me.color); // Send to server. - } else { - me.write(input.text); // Display message on 🧒. - server.send("world:field:write", me.message); // Send to server. - } - - // Clear text, hide cursor block, and close keyboard. - input.text = ""; - input.showBlink = false; - input.mute = true; - send({ type: "keyboard:close" }); - }, - { - // autolock: false, - // wrap, - scheme, - // copied, - // activated, - // didReset: () => { - // messageComplete = true; - // }, - // gutterMax, - // lineSpacing, - hideGutter: true, - closeOnEmptyEnter: true, - }, - ); - - inputBtn = new ui.Button(); - - send({ type: "keyboard:soft-lock" }); - - // ðŸ§Ķ Socket Networking - server = socket((id, type, content) => { - if (type === "left") { - console.log("ïļâœŒïļ Goodbye:", id); - delete kids[id]; - return; - } - - if (type === "joined") { - console.log("ïļðŸ‘‹ Hello:", id); - return; - } - - if (type.startsWith("connected")) { - if (me.handle === "?") me.handle = `nub${id}`; - server.send("world:field:join", { - handle: me.handle, - pos: me.pos, - face: me.face, - }); - console.log("ðŸŠī Welcome:", me.handle, `(${id})`); - return; - } - - // TODO: How can this be oriented around storing a server list. - if (type === "world:field:list") { - // console.log("🗞ïļ Listing all field clients..."); - keys(content).forEach((key) => { - if (!kids[key]) { - const data = content[key]; - console.log("🧒 Joined:", data.handle || id, data); - kids[key] = new Kid( - data.handle || `nub${id}`, - data.pos, - data.face, - true, - ); - } - }); - return; - } - - if (type === "world:field:join") { - if (!kids[id]) { - kids[id] = new Kid( - content.handle || `nub${id}`, - content.pos, - content.face, - true, - ); - - // Send a join message back? - // server.send("world:field:join", { - // handle: me.handle, - // pos: me.pos, - // face: me.face, - // }); - } - } - - // TODO: Stop receiving own messages? - // if (server.id !== id) { - if (type === "world:field:tint") { - const kid = kids[id]; - if (kid) kid.tint(content); - } - - if (type === "world:field:mood") { - const kid = kids[id]; - if (kid) kid.mood(content); - } - - if (type === "world:field:write") { - const kid = kids[id]; - if (kid) { - kid.write(content); - sound.synth({ - type: "sine", - tone: 950, - attack: 0.1, - decay: 0.96, - volume: 0.65, - duration: 0.015, - }); - } - } - - if (type === "world:field:write:clear") { - const kid = kids[id]; - if (kid) kid.write(null); - } - - if (type === "world:field:move") { - const kid = kids[id]; - if (kid) kid.netPos = content.pos; - } - // } - }); } // ðŸŽĻ Paint -function paint({ api, wipe, layer, ink, pan, unpan, pen, screen, leaving }) { - wipe(0); // 🖞ïļ Backdrop - - layer(0); - // 🌎 + 🧒 World & Players - pan(cam.x, cam.y); - world.paint(api); - - scenery.grasses.forEach((grass) => { - ink("lime") - .line(grass.x, grass.y, grass.x, grass.y - 10) - .line(grass.x, grass.y, grass.x - 5, grass.y - 6) - .line(grass.x, grass.y, grass.x + 5, grass.y - 6); - }); - - // layer(1); - - inputBtn.paint((btn) => { - ink("white", btn.down && btn.over ? 128 : 64).circle( - me.pos.x, - me.pos.y, - btn.box.w / 2, - true, - ); - }); - - me.paint(api); - - unpan(); - - keys(kids).forEach((key) => { - pan(cam.x, cam.y); - const kid = kids[key]; - kid.paint(api); - unpan(); - }); - - // TODO: Make this a generic module for printing user lists? 23.12.04.15.47 - [me, ...values(kids)].forEach((kid, i) => { - const row = i * 12; - ink("black").write(kid.handle, { x: 7, y: 21 + 1 + row }); - ink("cyan").write(kid.handle, { x: 6, y: 21 + row }); - }); - - // ðŸ’ŧ Screen UI - const l = me.leash; - if (l.start) { - if (pen) ink(0, 255, 0, 90).line(l.start.x, l.start.y, pen.x, pen.y); - ink(l.len > l.deadzone ? "yellow" : "red").line( - l.start.x, - l.start.y, - l.start.x + me.leash.x, - l.start.y + me.leash.y, - ); - } - - if (input.canType && !leaving()) { - input.paint(api, false, { - x: 0, - y: 18, - width: screen.width, - height: screen.height - 18, - }); - } - - // layer(0); - // pan(cam.x, cam.y); - // unpan(); +// ðŸ˜ą TODO: This should just paint the world... +function paint({ wipe }) { + wipe("olive"); // 🖞ïļ Backdrop } // 🎊 Act -function act({ event: e, api, send, jump, hud, piece, screen }) { - if (e.is("reframed")) { - cam.x = screen.width / 2 - dolly.x; - cam.y = screen.height / 2 - dolly.y; - } - - if (!input.canType) { - me.act(api); - - function open() { - me.off(); - // send({ type: "keyboard:open" }); // Keyboard will open automatically - // because of the unlocking logic. - } - - inputBtn.act(e, { - down: () => { - send({ type: "keyboard:soft-unlock" }); - }, - push: () => { - open(); - send({ type: "keyboard:soft-lock" }); - }, - cancel: () => { - send({ type: "keyboard:soft-lock" }); - }, - rollout: () => { - send({ type: "keyboard:soft-lock" }); - }, - rollover: () => { - if (inputBtn.down) send({ type: "keyboard:soft-unlock" }); - }, - }); - - if ( - (!input.canType && e.is("keyboard:down:enter")) || - e.is("keyboard:down:escape") || - e.is("keyboard:down:`") - ) { - send({ type: "keyboard:open" }); - open(); - } - - // if (e.is("keyboard:down:escape")) jump("prompt"); - - // Backspace back to `prompt`. - if (e.is("keyboard:down:backspace")) { - jump(`prompt~${hud.currentLabel.text || piece}`)(() => { - send({ type: "keyboard:open" }); - }); - } - } - - if ( - input.canType && - (e.is("keyboard:down:`") || - e.is("keyboard:down:escape") || - (input.text.trim().length === 0 && - e.is("keyboard:down:enter") && - !e.shift)) - ) { - send({ type: "keyboard:close" }); - } - - if (input.canType && e.is("lift") && !input.shifting && !input.paste.down) { - send({ type: "keyboard:close" }); - } - - if ( - e.is("keyboard:open") || - e.is("keyboard:close") || - (input.canType && !e.is("keyboard:down:escape")) - ) { - // if (e.is("keyboard:close")) input.text = ""; - input.act(api); - } -} +function act() {} // ðŸ§Ū Sim -function sim({ api, geo, simCount, screen, num }) { - me.sim(api, function net(kid) { - if (simCount % 4n === 0n) { - // Send position updates at a rate of 30hz (120 / 4). - if (kid.pos) server.send("world:field:move", kid); - } - if (kid.clear) server.send("world:field:write:clear", kid); - }); // 🧒 Movement - - cam.dolly.x = num.lerp(cam.dolly.x, me.pos.x, 0.05); - cam.dolly.y = num.lerp(cam.dolly.y, me.pos.y, 0.05); - - cam.x = screen.width / 2 - cam.dolly.x; - cam.y = screen.height / 2 - cam.dolly.y; - - keys(kids).forEach((key) => kids[key].sim(api)); // Networked kids. - input.sim(api); // 💎 Chat - - const btnPos = me.screenPos(cam, world); // Button to activate prompt. - inputBtn.box = new geo.Box( - btnPos.x - me.size, - btnPos.y - me.size, - me.size * 2, - ); -} +function sim() {} // ðŸĨ Beat // function beat() { @@ -671,11 +73,7 @@ function sim({ api, geo, simCount, screen, num }) { // } // 👋 Leave -function leave({ store }) { - // Persist current position. - store["field:pos"] = me.pos; - store.persist("field:pos"); -} +function leave() {} // 📰 Meta function meta() { diff --git a/system/public/aesthetic.computer/lib/disk.mjs b/system/public/aesthetic.computer/lib/disk.mjs index 93d79e26a5..54c99b53b7 100644 --- a/system/public/aesthetic.computer/lib/disk.mjs +++ b/system/public/aesthetic.computer/lib/disk.mjs @@ -19,6 +19,7 @@ const { round, sin, random, max, floor } = Math; const { keys } = Object; import { nopaint_boot, nopaint_act, nopaint_is } from "../systems/nopaint.mjs"; import * as prompt from "../systems/prompt-system.mjs"; +import * as world from "../systems/world.mjs"; import { headers } from "./headers.mjs"; import { logs } from "./logs.mjs"; import { soundWhitelist } from "./sound/sound-whitelist.mjs"; @@ -2481,7 +2482,7 @@ async function load( // Start the socket server // TODO: Before we load the disk, in case of needing to reload remotely on failure? 23.01.27.12.48 let receiver; // Handles incoming messages from the socket. - const forceProd = false; // For testing prod socket servers in development. + const forceProd = true; // For testing prod socket servers in development. // TOOD: Hoist this to an environment variable? // Requests a session-backend and connects via websockets. @@ -3003,6 +3004,37 @@ async function load( }; system = "prompt"; + } else if (module.system?.startsWith("world")) { + boot = async ($) => { + await world.world_boot($); + await module.boot?.($); + }; + + sim = ($) => { + world.world_sim($); + module.sim?.($); + }; + + paint = ($) => { + // Paint behind the world first. + let noPaint = module.paint?.($); + noPaint = noPaint || world.world_paint($); + return noPaint; + }; + + beat = module.beat || defaults.beat; + + act = ($) => { + world.world_act($); + module.act?.($); + }; + + leave = ($) => { + world.world_leave($); + module.leave?.($); + }; + + system = "world"; } else { boot = module.boot || defaults.boot; sim = module.sim || defaults.sim; diff --git a/system/public/aesthetic.computer/systems/world.mjs b/system/public/aesthetic.computer/systems/world.mjs new file mode 100644 index 0000000000..f0ad1995ca --- /dev/null +++ b/system/public/aesthetic.computer/systems/world.mjs @@ -0,0 +1,615 @@ +// World (System), 23.12.18.22.48 +// This module contains all of the world system functionality. +// Worlds are multi-user, interconnected rooms. + +let me, world, cam, input, inputBtn, server; + +const scenery = { + grasses: [ + { x: 190, y: 170 }, + { x: 276, y: 286 }, + { x: 128, y: 128 }, + { x: 400, y: 400 }, + { x: 500, y: 512 }, + ], +}; +const kids = {}; + +const { keys, values } = Object; + +async function world_boot({ + api, + help, + handle, + screen, + ui, + send, + net: { socket }, + sound, + store, + piece, +}) { + // âœĻ Initialization & Interface + world = new World(512, 512); + const pos = (await store.retrieve(`${piece}:pos`)) || { + x: undefined, + y: undefined, + }; + + me = new Kid( + handle(), + { x: pos.x || world.size.width / 2, y: pos.y || world.size.height / 2 }, + help.choose("meh", "smile", "frown"), + ); + + cam = new Cam( + screen.width / 2 - me.pos.x, + screen.height / 2 - me.pos.y, + me.pos, + ); + + const scheme = { + dark: { + fg: 255, + bg: [0, 100], + block: 255, + blockHi: 0, + line: 255, + }, + }; + + input = new ui.TextInput( + api, + "...", + async (text) => { + if ( + input.text === "smile" || + input.text === "frown" || + input.text === "sad" || + input.text === "meh" + ) { + if (input.text === "sad") input.text = "frown"; + me.mood(input.text); + server.send(`world:${piece}:mood`, me.face); // Send to server. + } else if ( + input.text === "red" || + input.text === "yellow" || + input.text === "orange" || + input.text === "black" || + input.text === "brown" || + input.text === "purple" || + input.text === "pink" || + input.text === "blue" || + input.text === "lime" || + input.text === "white" + ) { + me.tint(input.text); + server.send(`world:${piece}:tint`, me.color); // Send to server. + } else { + me.write(input.text); // Display message on 🧒. + server.send(`world:${piece}:write`, me.message); // Send to server. + } + + // Clear text, hide cursor block, and close keyboard. + input.text = ""; + input.showBlink = false; + input.mute = true; + send({ type: "keyboard:close" }); + }, + { + // autolock: false, + // wrap, + scheme, + // copied, + // activated, + // didReset: () => { + // messageComplete = true; + // }, + // gutterMax, + // lineSpacing, + hideGutter: true, + closeOnEmptyEnter: true, + }, + ); + + inputBtn = new ui.Button(); + + send({ type: "keyboard:soft-lock" }); + + // ðŸ§Ķ Socket Networking + server = socket((id, type, content) => { + if (type === "left") { + console.log("ïļâœŒïļ Goodbye:", id); + delete kids[id]; + return; + } + + if (type === "joined") { + console.log("ïļðŸ‘‹ Hello:", id); + return; + } + + if (type.startsWith("connected")) { + if (me.handle === "?") me.handle = `nub${id}`; + server.send(`world:${piece}:join`, { + handle: me.handle, + pos: me.pos, + face: me.face, + }); + console.log("ðŸŠī Welcome:", me.handle, `(${id})`); + return; + } + + // TODO: How can this be oriented around storing a server list. + if (type === `world:${piece}:list`) { + // console.log("🗞ïļ Listing all field clients..."); + keys(content).forEach((key) => { + if (!kids[key]) { + const data = content[key]; + console.log("🧒 Joined:", data.handle || id, data); + kids[key] = new Kid( + data.handle || `nub${id}`, + data.pos, + data.face, + true, + ); + } + }); + return; + } + + if (type === `world:${piece}:join`) { + if (!kids[id]) { + kids[id] = new Kid( + content.handle || `nub${id}`, + content.pos, + content.face, + true, + ); + } + } + + // TODO: Stop receiving own messages? + // if (server.id !== id) { + if (type === `world:${piece}:tint`) { + const kid = kids[id]; + if (kid) kid.tint(content); + } + + if (type === `world:${piece}:mood`) { + const kid = kids[id]; + if (kid) kid.mood(content); + } + + if (type === `world:${piece}:write`) { + const kid = kids[id]; + if (kid) { + kid.write(content); + sound.synth({ + type: "sine", + tone: 950, + attack: 0.1, + decay: 0.96, + volume: 0.65, + duration: 0.015, + }); + } + } + + if (type === `world:${piece}:write:clear`) { + const kid = kids[id]; + if (kid) kid.write(null); + } + + if (type === `world:${piece}:move`) { + const kid = kids[id]; + if (kid) kid.netPos = content.pos; + } + // } + }); +} + +function world_paint({ + api, + wipe, + layer, + ink, + pan, + unpan, + pen, + screen, + leaving, +}) { + // 🌎 + 🧒 World & Players + pan(cam.x, cam.y); + + world.paint(api); + + // Scenery. + scenery.grasses.forEach((grass) => { + ink("lime") + .line(grass.x, grass.y, grass.x, grass.y - 10) + .line(grass.x, grass.y, grass.x - 5, grass.y - 6) + .line(grass.x, grass.y, grass.x + 5, grass.y - 6); + }); + + inputBtn.paint((btn) => { + ink("white", btn.down && btn.over ? 128 : 64).circle( + me.pos.x, + me.pos.y, + btn.box.w / 2, + true, + ); + }); + + me.paint(api); + + unpan(); + + // Other kids. + keys(kids).forEach((key) => { + pan(cam.x, cam.y); + const kid = kids[key]; + kid.paint(api); + unpan(); + }); + + // TODO: Make this a generic module for printing user lists? 23.12.04.15.47 + [me, ...values(kids)].forEach((kid, i) => { + const row = i * 12; + ink("black").write(kid.handle, { x: 7, y: 21 + 1 + row }); + ink("cyan").write(kid.handle, { x: 6, y: 21 + row }); + }); + + // ðŸ’ŧ Screen UI + const l = me.leash; + if (l.start) { + if (pen) ink(0, 255, 0, 90).line(l.start.x, l.start.y, pen.x, pen.y); + ink(l.len > l.deadzone ? "yellow" : "red").line( + l.start.x, + l.start.y, + l.start.x + me.leash.x, + l.start.y + me.leash.y, + ); + } + + if (input.canType && !leaving()) { + input.paint(api, false, { + x: 0, + y: 18, + width: screen.width, + height: screen.height - 18, + }); + } +} + +function world_act({ event: e, api, send, jump, hud, piece, screen }) { + if (e.is("reframed")) { + cam.x = screen.width / 2 - dolly.x; + cam.y = screen.height / 2 - dolly.y; + } + + if (!input.canType) { + me.act(api); + + inputBtn.act(e, { + down: () => { + send({ type: "keyboard:soft-unlock" }); + }, + push: () => { + me.off(); + send({ type: "keyboard:soft-lock" }); + }, + cancel: () => { + send({ type: "keyboard:soft-lock" }); + }, + rollout: () => { + send({ type: "keyboard:soft-lock" }); + }, + rollover: () => { + if (inputBtn.down) send({ type: "keyboard:soft-unlock" }); + }, + }); + + if ( + !input.canType && + e.is("keyboard:down:enter") // || + // e.is("keyboard:down:escape") || + // e.is("keyboard:down:`") + ) { + send({ type: "keyboard:open" }); + me.off(); + } + + if (e.is("keyboard:down:escape") || e.is("keyboard:down:`")) jump("prompt"); + + // Backspace back to `prompt`. + if (e.is("keyboard:down:backspace")) { + jump(`prompt~${hud.currentLabel.text || piece}`)(() => { + send({ type: "keyboard:open" }); + }); + } + } + + if ( + input.canType && + (e.is("keyboard:down:`") || + e.is("keyboard:down:escape") || + (input.text.trim().length === 0 && + e.is("keyboard:down:enter") && + !e.shift)) + ) { + send({ type: "keyboard:close" }); + } + + if (input.canType && e.is("lift") && !input.shifting && !input.paste.down) { + send({ type: "keyboard:close" }); + } + + if ( + e.is("keyboard:open") || + e.is("keyboard:close") || + (input.canType && !e.is("keyboard:down:escape")) + ) { + // if (e.is("keyboard:close")) input.text = ""; + input.act(api); + } +} + +function world_sim({ api, geo, simCount, screen, num }) { + me.sim(api, function net(kid) { + if (simCount % 4n === 0n) { + // Send position updates at a rate of 30hz (120 / 4). + if (kid.pos) server.send("world:field:move", kid); + } + if (kid.clear) server.send("world:field:write:clear", kid); + }); // 🧒 Movement + + cam.dolly.x = num.lerp(cam.dolly.x, me.pos.x, 0.05); + cam.dolly.y = num.lerp(cam.dolly.y, me.pos.y, 0.05); + + cam.x = screen.width / 2 - cam.dolly.x; + cam.y = screen.height / 2 - cam.dolly.y; + + keys(kids).forEach((key) => kids[key].sim(api)); // Networked kids. + input.sim(api); // 💎 Chat + + const btnPos = me.screenPos(cam, world); // Button to activate prompt. + inputBtn.box = new geo.Box( + btnPos.x - me.size, + btnPos.y - me.size, + me.size * 2, + ); +} + +function world_leave({ store, piece }) { + store[`world:${piece}:pos`] = me.pos; // Persist current position. + store.persist(`world:${piece}:pos`); +} + +export { world_boot, world_paint, world_sim, world_act, world_leave }; + +// 🧒 +class Kid { + handle; + net; + pos = { x: 0, y: 0 }; + netPos; + size = 16; + leash = { x: 0, y: 0, len: 0, max: 12, deadzone: 8 }; + face = "meh"; + color = "white"; + #keys = { U: false, D: false, L: false, R: false }; + message; + #messageDuration; + #messageProgress = 0; + + constructor(handle = "?", pos = this.pos, face, net = false) { + this.handle = handle; + console.log("🧒 From:", this.handle, face); + + this.pos = pos; + if (net) this.netPos = { ...pos }; + + this.face = face || this.face; + this.net = net; // Is it from the network? + } + + // Show a message above the kid's head for `time` frames. + write(text, time = 320) { + this.message = text; + this.#messageDuration = time; + this.#messageProgress = 0; // Reset message progress. + } + + // Change the mood (face) of the kid. + mood(face) { + this.face = face; + } + + // Change the color of the kid. + tint(c) { + this.color = c; + } + + // Render the kid. + paint({ ink, pan, text, typeface }) { + const leash = this.leash; + pan(this.pos.x, this.pos.y); + ink(this.color).circle(0, 0, this.size); // Head + + // Face + // Eyes + ink(this.color).point(-6, -6); + ink(this.color).point(6, -6); + // Mouth + if (this.face === "smile") { + ink(this.color).line(0, 6, -6, 3); + ink(this.color).line(0, 6, 6, 3); + } else if (this.face === "frown") { + ink(this.color).line(0, 3, -6, 8); + ink(this.color).line(0, 3, 6, 8); + } else if (this.face === "meh") { + ink(this.color).line(-6, 6, 6, 6); + } + + ink(leash.len > leash.deadzone ? this.color : [this.color, 128]).line( + 0, + 0, + leash.x, + leash.y, + ); + if (this.message) { + const blockWidth = typeface.glyphs["0"].resolution[0]; + const tb = text.box( + this.message, + undefined, + this.message.length * blockWidth, + ); + ink(this.color).write(this.message, { + x: -tb.box.width / 2, + y: -this.size - 12, + }); + } + } + + // Control the kid. + act({ event: e, num }) { + const k = this.#keys; + const leash = this.leash; + if (e.is("keyboard:down:w") || e.is("keyboard:down:arrowup")) k.U = true; + if (e.is("keyboard:down:s") || e.is("keyboard:down:arrowdown")) k.D = true; + if (e.is("keyboard:down:a") || e.is("keyboard:down:arrowleft")) k.L = true; + if (e.is("keyboard:down:d") || e.is("keyboard:down:arrowright")) k.R = true; + if (e.is("keyboard:up:w") || e.is("keyboard:up:arrowup")) k.U = false; + if (e.is("keyboard:up:s") || e.is("keyboard:up:arrowdown")) k.D = false; + if (e.is("keyboard:up:a") || e.is("keyboard:up:arrowleft")) k.L = false; + if (e.is("keyboard:up:d") || e.is("keyboard:up:arrowright")) k.R = false; + + if (e.is("touch:1")) leash.start = { x: e.x, y: e.y }; + + if (e.is("draw:1") && leash.start) { + leash.x = e.x - leash.start.x; + leash.y = e.y - leash.start.y; + this.#snapLeash(num); + } + + if (e.is("lift:1")) leash.start = null; + } + + // Simulate the kid's movement and time messages. + sim({ num }, net) { + // 🗞 Network Prediction + if (this.net && this.netPos) { + const p2 = num.p2; + const STEP_SIZE = 1; + const direction = p2.norm(p2.sub(this.netPos, this.pos)); + const distance = p2.len(p2.sub(this.netPos, this.pos)); + if (distance < STEP_SIZE) { + this.pos = this.netPos; // Set position to target. + } else { + this.pos = p2.inc(this.pos, p2.scl(direction, STEP_SIZE)); + } + return; // No need to compute movements, locally. + } + + // Local simulation. + + // ðŸ—Ļïļ Message + if (this.message) { + if (this.#messageProgress < this.#messageDuration) { + this.#messageProgress += 1; + } else { + this.message = null; + this.#messageProgress = 0; + net?.({ clear: true }); + } + } + + // 🏃 Movement + const k = this.#keys, + leash = this.leash, + pos = this.pos; + + if (k.U) leash.y -= 1; + if (k.D) leash.y += 1; + if (k.L) leash.x -= 1; + if (k.R) leash.x += 1; + + this.#snapLeash(num); + + if (!leash.start) { + leash.y *= 0.97; + leash.x *= 0.97; + } + + const newPos = { ...pos }; + if (leash.len > leash.deadzone) { + newPos.x = num.lerp(pos.x, pos.x + leash.x, 0.075); + newPos.y = num.lerp(pos.y, pos.y + leash.y, 0.075); + } else if (leash.len > 1) { + newPos.x = num.lerp(pos.x, pos.x + leash.x, 0.025); + newPos.y = num.lerp(pos.y, pos.y + leash.y, 0.025); + } + + // Run the net callback whenever the position changes. + if (newPos.x !== pos.x || newPos.y !== pos.y) net?.({ pos }); + + pos.x = newPos.x; + pos.y = newPos.y; + + if (pos.x < 0) pos.x = 0; + if (pos.x > world.size.width) pos.x = world.size.width; + if (pos.y < 0) pos.y = 0; + if (pos.y > world.size.height) pos.y = world.size.height; + } + + // Limit the kid's movement leash. + #snapLeash(num) { + const leash = this.leash; + leash.len = num.p2.len(leash); + if (leash.len > leash.max) { + const scale = leash.max / leash.len; + leash.x *= scale; + leash.y *= scale; + } + } + + // Kill all controls. + off() { + const k = this.#keys; + k.U = k.D = k.L = k.R = false; + this.leash.start = null; + } + + // Return the screen position of this kid, given a camera and world, + screenPos(cam, world) { + return { x: cam.x + this.pos.x, y: cam.y + this.pos.y }; + } +} + +// 🌎 +class World { + size = {}; + constructor(width = 192, height = 192) { + this.size.width = width; + this.size.height = height; + } + + paint({ ink }) { + ink("green").box(0, 0, this.size.width, this.size.height); + } +} + +// ðŸŽĨ +class Cam { + x = 0; + y = 0; + dolly = { x: 0, y: 0 }; + + constructor(x, y, dolly) { + this.x = x; + this.y = y; + this.dolly = { ...dolly }; + } +} -- knotmirror 0.0.1