31 Commits
Author SHA1 Message Date
ChaosMaker 931d248e4c dunut2 2026-10-15 20:52:38 +02:00
ChaosMaker b9922b3bdc Custom Input Module Working mostly accurately 2026-06-29 06:40:39 +02:00
ChaosMaker 4a1ddd0f98 Prototyped custom input module code 2026-06-26 19:34:44 +02:00
ChaosMaker 8cb42f07a2 WIP: Reworked input module for the terminal front-end 2026-06-23 06:05:58 +02:00
ChaosMaker 8682de7d17 HUUUGE dump of code, toast system in a svelte module, new reworked tailwing color palette, WIP cms, WIP API and probably much more that i forgot about. 2026-06-21 19:20:59 +02:00
ChaosMaker 50872d8951 a lot of work, but i'd guess mostly api in the works 2026-05-27 20:45:14 +02:00
ChaosMaker 68458be71f FileSystem pulls the file and pulls from localStorage cache to checksum both versions 2026-05-24 19:33:02 +02:00
ChaosMaker 65c776d1a2 more hash implementation 2026-05-19 20:41:29 +02:00
ChaosMaker 105bdc8c75 begining of MD5 implementation and some more work on the other code 2026-05-14 23:29:47 +02:00
ChaosMaker 619de5e1f8 WIP: new abstraction layer, file system now a singleton, shell should be too 2026-05-13 17:56:19 +02:00
ChaosMaker 106abd851a WIP: No idea what exactly i did over those past 2 days 2026-05-11 19:06:06 +02:00
ChaosMaker f50fc96416 Moar code that i didnt commit and push like a fucking moron - doing this remotely from orion 2026-05-02 19:50:47 +02:00
ChaosMaker 1f23f54ee4 shimeji class rewriten as the base for the rest, physis next 2026-04-03 06:46:00 +02:00
ChaosMaker 1c8aa9265c cleaner reimplementatinos of previous system ongoing, Need to rename the Physics code Physis and wrap it in a namespace 2026-04-03 06:11:12 +02:00
ChaosMaker a706962e1e web_g_engine factory method complete, should be capable of rendering 2026-04-02 17:15:28 +02:00
ChaosMaker 60313f5373 more rendering code, not much changes, beginning refactor of the rendering API 2026-04-02 06:31:30 +02:00
ChaosMaker 92418e7e4e new rendering code, still cant do shit, but its on webgl now so lessgooo gpu and vertices + shaders im coming for you 2026-04-01 18:11:17 +02:00
ChaosMaker 5c413f4e8b moooooore physics 2026-03-27 01:43:35 +01:00
ChaosMaker 2183dda2df 2dphysics unfiniished simple 1 object versioon in shimeji 2026-03-24 18:04:34 +01:00
ChaosMaker 2fa12e22d5 Shimeji with physics added !!!!! 2026-03-22 08:14:31 +01:00
ChaosMaker c3f1af6818 a bit of front-end work, changing users almost done on login, "drunk-code" no more (id hope), continuous processes and keybinds still not done. 2026-03-19 17:52:36 +01:00
ChaosMaker 18aeeb200f a lot of "drunk code", processes need rethinking, terminal initializes but commands dont go through to IO 2026-03-16 18:05:07 +01:00
ChaosMaker b40fa704c6 code stable. terminal initializes, database successfully connects, reads and writes. css on maintenance page needs tweaking. terminal still displays before initialization. 2026-03-08 09:52:49 +01:00
ChaosMaker 55787fe3c5 Update README.md 2026-03-07 04:35:03 +01:00
ChaosMaker 43589410e3 terminal initializes successfully, scuffed intro visuals, termianl still visible with the login form, user temporarily locked to gornodox only. all algorithms work for now, needs to check for bugs and merge to master befpre build. SIDE NOTE - *Make domain builds only from the* master *branch.* 2026-03-05 19:50:05 +01:00
ChaosMaker 9ac27f5fbd unsable code rework, doesnt run 2026-02-23 17:15:28 +01:00
ChaosMaker 1faab39849 more features, flags now mostly work, added support for -R flag in ls with a custom bash method for recursive tree traversal 2026-02-16 07:38:12 +01:00
ChaosMaker 0ad0e362d6 short format of ls command is done and working, could use a rewrite and cleanup but later, some flags implemented for the short format. 2026-02-15 20:06:52 +01:00
ChaosMaker 7fbf3593fb ls command now prints output in short format aswell (no flags support yet) 2026-02-13 07:34:42 +01:00
ChaosMaker 8830b130ad fixed small error 2026-02-12 10:24:59 +01:00
ChaosMaker aaecba5642 Added custom Posix class that holds the custom character weight table with a public GetCharWeight method to retrieve the weight from the table. Fixed spacing of the ls -l output and slowly working with the binary search in the ls.ts file 2026-02-12 10:24:46 +01:00
203 changed files with 12260 additions and 1165 deletions
+3
View File
@@ -0,0 +1,3 @@
# Drizzle
# Replace with your DB credentials!
DATABASE_URL="mysql://user:password@host:port/db-name"
+1
View File
@@ -7,3 +7,4 @@ bun.lockb
# Miscellaneous
/static/
/drizzle/
+48 -24
View File
@@ -1,38 +1,62 @@
# sv
Preview can be found here -> https://gornodox.dev
Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli).
Hello everyone that decided to visit my repo.
Today i present to you a 'Work In Progress', state of the art (not really) portfolio website.
## Creating a project
The main idea was that the "bash terminal" would serve as the main interface that the user would interact with...
If you're seeing this, you've probably already done this step. Congrats!
But then I thought to myself,
>*Wouldn't it be cool if it would actually work like a terminal?`*
```sh
# create a new project in the current directory
npx sv create
...and that's how we got here.
# create a new project in my-app
npx sv create my-app
```
>***Make note that not all features listed below may be implemented when you're seeing this.***
## Developing
The whole environment is a simulation of a linux environment, from every data structure to the way everything behaves. Theres a file system representation that gets generated from a live folder structure by [this](https://github.com/ChaosMakerMLG/FileSystemParser) project.
This gets parsed by my website into the object structure that the whole `Bash` algorithm can deal and interact with.
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
There are users, permissions, ownership, links (hard and symbolic)
File system supports file contents - they get cached into a file with a name, and the node stored on heap just has the name to the correct file cache.
```sh
npm run dev
Every command is treated like a process that can be exited
aswell as files being executable
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
All of this is purely data-driven and modular, so if you where to take my code and just implement an IO system that would interact with my algorithm, then it would work out of the box, which is REALLYYY COOOL in my opinion.
## Building
All the changes that the user makes will be stored on their browsers `localStorage` and read out on login
To create a production version of your app:
The website will still serve the purpose of being a portfolio but the actuall portfolio part will just be a process that is ran at initialization of the terminal, and it will display the info about me as a TUI ^w^
```sh
npm run build
```
It can of course be shutdown as mentioned above and thats how you get access to the shell ;)
You can preview the production build with `npm run preview`.
## This project uses and implements:
> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment.
- Tree traversal
- Binary search
- Quick sort
- And much mode weird stuff...
## Commands:
- return
- ls
- echo
- touch
- mkdir
- pwd
- cd
- exit
- cp
- mv
- rm
- cat
- less
- chown
- chmod
- reboot
- help
- whoami
- sudo
- su
- clear
> More will probably added with time :)
+11
View File
@@ -0,0 +1,11 @@
import { defineConfig } from 'drizzle-kit';
if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL is not set');
export default defineConfig({
schema: './src/lib/server/db/schema.ts',
dialect: 'mysql',
dbCredentials: { url: process.env.DATABASE_URL },
verbose: true,
strict: true
});
+1581 -305
View File
File diff suppressed because it is too large Load Diff
+14 -4
View File
@@ -1,7 +1,7 @@
{
"name": "svelte-portfolio",
"private": true,
"version": "0.0.1",
"version": "0.0.69",
"type": "module",
"scripts": {
"dev": "vite dev",
@@ -14,7 +14,11 @@
"lint": "prettier --check . && eslint .",
"test:e2e": "playwright test",
"test": "npm run test:e2e && npm run test:unit -- --run",
"test:unit": "vitest"
"test:unit": "vitest",
"db:push": "drizzle-kit push",
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"db:studio": "drizzle-kit studio"
},
"devDependencies": {
"@eslint/compat": "^1.4.0",
@@ -24,12 +28,15 @@
"@sveltejs/kit": "^2.43.2",
"@sveltejs/vite-plugin-svelte": "^6.2.0",
"@tailwindcss/vite": "^4.1.16",
"@types/node": "^22",
"@types/node": "^24",
"@vitest/browser": "^3.2.4",
"drizzle-kit": "^0.18.1",
"drizzle-orm": "^0.45.2",
"eslint": "^9.36.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.12.4",
"globals": "^16.4.0",
"mysql2": "^3.16.3",
"playwright": "^1.55.1",
"prettier": "^3.6.2",
"prettier-plugin-svelte": "^3.4.0",
@@ -44,6 +51,9 @@
"vitest-browser-svelte": "^1.1.0"
},
"dependencies": {
"@lucide/svelte": "^0.548.0"
"@lucide/svelte": "^0.548.0",
"animejs": "^4.5.0",
"gl-matrix": "^3.4.4",
"zod": "^4.3.6"
}
}
Executable → Regular
View File
Vendored Executable → Regular
+1
View File
@@ -8,6 +8,7 @@ declare global {
// interface PageState {}
// interface Platform {}
}
namespace TermOS {}
}
export {};
Executable → Regular
+12
View File
@@ -1,6 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<script>
// Immediately apply saved or system theme – no flash
(function () {
const saved = localStorage.getItem('theme');
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const theme =
saved === 'dark' || saved === 'light' ? saved : prefersDark ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', theme);
// Optional: prevent transition on load
document.documentElement.style.setProperty('--initial-load', 'true');
})();
</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
Executable → Regular
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 158 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 205 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 597 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 560 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 615 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 597 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 628 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 585 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 604 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 601 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 632 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 612 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 467 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 471 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 471 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 476 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 468 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 459 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 472 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 628 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 649 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 638 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 656 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 648 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 640 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 629 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 628 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 639 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 657 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 645 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 654 B

Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 668 B

After

Width:  |  Height:  |  Size: 668 B

Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 695 B

After

Width:  |  Height:  |  Size: 695 B

Executable → Regular
+2 -2
View File
@@ -33,7 +33,7 @@
},
"Interactible": false,
"Func": null,
"Parent": null
"Parent": 1
},
"2": {
"Inode": 2,
@@ -433,7 +433,7 @@
},
"13": {
"Inode": 13,
"Name": "kamil",
"Name": "gornodox",
"Type": 16384,
"Size": 4096,
"Children": [
Executable → Regular
View File
Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 620 B

After

Width:  |  Height:  |  Size: 620 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 506 B

After

Width:  |  Height:  |  Size: 506 B

Executable → Regular
View File
Executable → Regular
+2 -1
View File
@@ -1 +1,2 @@
// place files you want to import through the `$lib` alias in this folder.
+573
View File
@@ -0,0 +1,573 @@
import {
getWrapperManager,
MWIN_MANAGER,
resolveElement,
type MWinAPI,
type MWinNormalizedParams,
type MWinParams,
type MWinState,
type ResizeDirection
} from './mwin_util';
export function mwin_movable(node: HTMLElement, options: MWinParams) {
const controller = new MWinController(node, options);
const api: MWinAPI = {
state: controller.state,
minimize: () => controller.minimize(),
maximize: () => controller.maximize(),
close: () => controller.close()
};
options.onAPI?.(api);
return {
destroy: () => controller.destroy()
};
}
class MWinController {
#rafID: number | null = null;
#pendingApply = false;
#node: HTMLElement;
#wrapper: HTMLElement;
#opts: MWinNormalizedParams;
#savedTransition: string;
#savedStyles: string;
#wrapperObserver: ResizeObserver | null = null;
#wrapperWidth: number = 0;
#wrapperHeight: number = 0;
#wrapperLeft: number = 0;
#wrapperTop: number = 0;
#wrapperBorderLeft: number = 0;
#wrapperBorderTop: number = 0;
#dragOffsetX: number = 0;
#dragOffsetY: number = 0;
#resizeDirection: ResizeDirection = null;
#resizeStartRect = { x: 0, y: 0, width: 0, height: 0 };
#resizeStartPos = { x: 0, y: 0 };
#restoreRect: { x: number; y: number; width: number; height: number } | null = null;
state = $state<MWinState>({
x: 0,
y: 0,
width: 0,
height: 0,
minimized: false,
maximized: false,
moving: false,
resizing: false,
zIndex: 0
});
constructor(node: HTMLElement, options: MWinParams) {
this.#node = node;
const wrapper = resolveElement(options.wrapper, node);
if (!wrapper) throw new Error('[Movable] - Wrapper element not found!');
this.#wrapper = wrapper;
const wrapperStyle = getComputedStyle(this.#wrapper);
this.#wrapperBorderLeft = parseFloat(wrapperStyle.borderLeftWidth);
this.#wrapperBorderTop = parseFloat(wrapperStyle.borderTopWidth);
const resizableOpts = typeof options.resizable === 'object' ? options.resizable : {};
this.#opts = {
handle: resolveElement(options.handle, node),
initX: options.initX,
initY: options.initY,
initWidth: options.initWidth,
initHeight: options.initHeight,
baseZIndex: options.baseZIndex ?? 1,
resizeHandle: resolveElement(options.resizeHandle, node),
resizable: !!options.resizable,
threshold: resizableOpts.threshold ?? 8,
minWidth: resizableOpts.minWidth ?? 24, //MinWidth should be min-content
minHeight: resizableOpts.minHeight ?? 24, //MinHeight should be min-content
maxWidth: resizableOpts.maxWidth ?? Infinity,
maxHeight: resizableOpts.maxHeight ?? Infinity,
onClose: options.onClose,
onMinimize: options.onMinimize,
onMaximize: options.onMaximize
};
this.#savedStyles = this.#node.style.cssText;
this.#savedTransition = this.#node.style.transition;
this.#node.style.transition = 'none';
this.#node.style.willChange = 'transform';
this.#wrapper.style.position = 'relative';
this.#node.style.position = 'absolute';
const wRect = this.#wrapper.getBoundingClientRect();
const nRect = this.#node.getBoundingClientRect();
this.state.x = this.#opts.initX ?? nRect.left - wRect.left;
this.state.y = this.#opts.initY ?? nRect.top - wRect.top;
this.state.width = this.#opts.initWidth ?? nRect.width;
this.state.height = this.#opts.initHeight ?? nRect.height;
this.#node.style.left = '0';
this.#node.style.top = '0';
this.#node.classList.add('[Movable]');
const mgr = getWrapperManager(this.#wrapper);
mgr.refCount++;
if (!node.hasAttribute('tabindex')) {
node.setAttribute('tabindex', '0');
}
node.setAttribute('role', 'region');
node.setAttribute('aria-label', 'Movable window');
this.#cacheWrapperRect();
node.addEventListener('pointerdown', this.#onPointerDown);
node.addEventListener('pointermove', this.#updateCursor);
node.addEventListener('pointerleave', this.#resetCursor);
this.#clampAndApply();
this.#bringToFront();
this.#wrapperObserver = new ResizeObserver(() => {
this.#wrapperWidth = this.#wrapper.clientWidth;
this.#wrapperHeight = this.#wrapper.clientHeight;
this.#onWrapperResize();
});
this.#wrapperObserver.observe(this.#wrapper);
}
#cacheWrapperRect() {
const wrapperRect = this.#wrapper.getBoundingClientRect();
this.#wrapperLeft = wrapperRect.left + this.#wrapperBorderLeft;
this.#wrapperTop = wrapperRect.top + this.#wrapperBorderTop;
this.#wrapperWidth = this.#wrapper.clientWidth;
this.#wrapperHeight = this.#wrapper.clientHeight;
}
#bringToFront() {
const mgr = getWrapperManager(this.#wrapper);
mgr.zCounter++;
this.state.zIndex = this.#opts.baseZIndex + mgr.zCounter;
this.#node.style.zIndex = String(this.state.zIndex);
}
#clampAndApply() {
this.#clampRect();
this.#apply();
}
#clampRect() {
const bw = this.#wrapperWidth;
const bh = this.#wrapperHeight;
let w = Math.min(this.state.width, bw, this.#opts.maxWidth);
w = Math.max(w, this.#opts.minWidth, 0);
let h = Math.min(this.state.height, bh, this.#opts.maxHeight);
h = Math.max(h, this.#opts.minHeight, 0);
this.state.width = w;
this.state.height = h;
const maxX = Math.max(0, bw - w);
const maxY = Math.max(0, bh - h);
this.state.x = Math.min(Math.max(this.state.x, 0), maxX);
this.state.y = Math.min(Math.max(this.state.y, 0), maxY);
}
#apply() {
this.#node.style.transform = `translate(${this.state.x}px, ${this.state.y}px)`;
this.#node.style.setProperty('--x', this.state.x.toString());
this.#node.style.setProperty('--y', this.state.y.toString());
this.#node.style.setProperty('--w', this.state.width.toString());
this.#node.style.setProperty('--h', this.state.height.toString());
this.#node.style.width = this.state.width + 'px';
this.#node.style.height = this.state.height + 'px';
}
#getCornerDirection(e: PointerEvent): ResizeDirection {
if (!this.#opts.resizable) return null;
const t = this.#opts.threshold;
let dirY: string = '';
if (e.clientY - this.state.y < t) dirY = 'n';
else if (this.state.y + this.state.height - e.clientY < t) dirY = 's';
let dirX: string = '';
if (e.clientX - this.state.x < t) dirX = 'w';
else if (this.state.x + this.state.width - e.clientX < t) dirX = 'e';
if (dirY && dirX) {
return (dirY + dirX) as ResizeDirection;
}
return null;
}
#onPointerCancel = () => this.#onPointerUp();
#onPointerDown = (e: PointerEvent): void => {
if (this.#isInteractive(e.target as HTMLElement)) return;
if (this.state.minimized) return;
if (this.state.maximized) {
const target = e.target as HTMLElement;
const canDrag = this.#opts.handle?.contains(target) || !this.#opts.handle;
if (canDrag) this.#unmaximizeAtCursor(e);
return;
}
if (this.#opts.resizeHandle?.contains(e.target as HTMLElement)) {
this.#startResize(e, 'se');
return;
}
const dir = this.#getCornerDirection(e);
if (dir) {
this.#startResize(e, dir);
return;
}
if (this.#opts.handle?.contains(e.target as HTMLElement)) {
this.#startMove(e);
return;
}
if (!this.#opts.handle) {
this.#startMove(e);
}
};
#startMove(e: PointerEvent, skipOffset = false): void {
e.preventDefault();
this.#bringToFront();
this.state.moving = true;
this.#node.style.cursor = 'grabbing';
this.#cacheWrapperRect();
if (!skipOffset) {
const rect = this.#node.getBoundingClientRect();
this.#dragOffsetX = e.clientX - rect.left;
this.#dragOffsetY = e.clientY - rect.top;
}
this.#prepareInteraction();
}
#startResize(e: PointerEvent, direction: ResizeDirection): void {
e.preventDefault();
e.stopPropagation();
this.#bringToFront();
this.state.resizing = true;
this.#cacheWrapperRect();
this.#resizeDirection = direction;
this.#resizeStartRect = {
x: this.state.x,
y: this.state.y,
width: this.state.width,
height: this.state.height
};
this.#resizeStartPos = { x: e.clientX - this.#wrapperLeft, y: e.clientY - this.#wrapperTop };
this.#prepareInteraction();
}
#unmaximizeAtCursor(e: PointerEvent): void {
this.#cacheWrapperRect();
const cursorX = e.clientX - this.#wrapperLeft;
const cursorY = e.clientY - this.#wrapperTop;
const fracX = this.#wrapperWidth > 0 ? cursorX / this.#wrapperWidth : 0;
const fracY = this.#wrapperHeight > 0 ? cursorY / this.#wrapperHeight : 0;
if (this.#restoreRect) {
this.state.width = this.#restoreRect.width;
this.state.height = this.#restoreRect.height;
this.state.maximized = false;
this.#restoreRect = null;
} else {
// fallback: no saved rect, just keep current size
this.state.maximized = false;
}
// Position so the same relative point stays under the cursor
let newX = cursorX - fracX * this.state.width;
let newY = cursorY - fracY * this.state.height;
// Clamp inside the boundary
const maxX = Math.max(0, this.#wrapperWidth - this.state.width);
const maxY = Math.max(0, this.#wrapperHeight - this.state.height);
newX = Math.min(Math.max(newX, 0), maxX);
newY = Math.min(Math.max(newY, 0), maxY);
this.state.x = newX;
this.state.y = newY;
this.#scheduleApply();
this.#dragOffsetX = cursorX - newX;
this.#dragOffsetY = cursorY - newY;
this.#bringToFront();
this.state.moving = true;
this.#node.style.cursor = 'grabbing';
this.#prepareInteraction();
return;
}
#prepareInteraction(): void {
document.body.style.userSelect = 'none';
this.#node.style.transition = 'none';
this.#node.style.willChange = 'transform, width, height';
this.#node.style.touchAction = 'none';
window.addEventListener('pointermove', this.#onPointerMove, { passive: true });
window.addEventListener('pointerup', this.#onPointerUp, { passive: true });
window.addEventListener('pointercancel', this.#onPointerCancel, { passive: true });
}
#onPointerMove = (e: PointerEvent): void => {
this.#cacheWrapperRect();
const events = e.getCoalescedEvents?.() ?? [e];
for (const event of events) {
if (this.state.moving) {
this.#updateMove(event);
} else if (this.state.resizing) {
this.#updateResize(event);
}
}
this.#scheduleApply();
};
#scheduleApply(): void {
if (!this.#pendingApply) {
this.#pendingApply = true;
this.#rafID = requestAnimationFrame(() => {
if (!this.state.moving && !this.state.resizing) {
this.#node.style.willChange = 'auto';
}
this.#rafID = null;
this.#pendingApply = false;
this.#apply();
});
}
}
#updateMove(e: PointerEvent): void {
let newX = e.clientX - this.#wrapperLeft - this.#dragOffsetX;
let newY = e.clientY - this.#wrapperTop - this.#dragOffsetY;
newX = Math.max(0, Math.min(newX, this.#wrapperWidth - this.state.width));
newY = Math.max(0, Math.min(newY, this.#wrapperHeight - this.state.height));
this.state.x = newX;
this.state.y = newY;
}
#updateResize(e: PointerEvent): void {
const dir = this.#resizeDirection!;
const start = this.#resizeStartRect;
const dx = e.clientX - this.#wrapperLeft - this.#resizeStartPos.x;
const dy = e.clientY - this.#wrapperTop - this.#resizeStartPos.y;
const anchorLeft = dir.includes('e') ? start.x : start.x + start.width;
const anchorTop = dir.includes('s') ? start.y : start.y + start.height;
let movingX = anchorLeft;
let movingY = anchorTop;
if (dir.includes('e')) movingX = start.x + start.width + dx;
else movingX = start.x + dx;
if (dir.includes('s')) movingY = start.y + start.height + dy;
else movingY = start.y + dy;
const minWidth = this.#opts.minWidth;
const minHeight = this.#opts.minHeight;
const maxWidth = Math.min(this.#opts.maxWidth, this.#wrapperWidth);
const maxHeight = Math.min(this.#opts.maxHeight, this.#wrapperHeight);
if (dir.includes('e')) {
movingX = Math.max(anchorLeft + minWidth, Math.min(movingX, anchorLeft + maxWidth));
movingX = Math.min(movingX, this.#wrapperWidth);
} else {
movingX = Math.min(anchorLeft - minWidth, Math.max(movingX, anchorLeft - maxWidth));
movingX = Math.max(movingX, 0);
}
if (dir.includes('s')) {
movingY = Math.max(anchorTop + minHeight, Math.min(movingY, anchorTop + maxHeight));
movingY = Math.min(movingY, this.#wrapperHeight);
} else {
movingY = Math.min(anchorTop - minHeight, Math.max(movingY, anchorTop - maxHeight));
movingY = Math.max(movingY, 0);
}
const newX = Math.min(anchorLeft, movingX);
const newY = Math.min(anchorTop, movingY);
const newWidth = Math.abs(movingX - anchorLeft);
const newHeight = Math.abs(movingY - anchorTop);
this.state.x = newX;
this.state.y = newY;
this.state.width = newWidth;
this.state.height = newHeight;
}
#onPointerUp = (): void => {
if (this.#rafID !== null) {
cancelAnimationFrame(this.#rafID);
this.#rafID = null;
this.#pendingApply = false;
}
this.state.moving = false;
this.state.resizing = false;
this.#resizeDirection = null;
document.body.style.userSelect = '';
this.#node.style.transition = this.#savedTransition;
this.#node.style.willChange = 'auto';
this.#node.style.touchAction = '';
this.#node.style.cursor = 'auto';
window.removeEventListener('pointermove', this.#onPointerMove);
window.removeEventListener('pointerup', this.#onPointerUp);
window.removeEventListener('pointercancel', this.#onPointerCancel);
this.#apply();
};
#onWrapperResize(): void {
const style = getComputedStyle(this.#wrapper);
this.#wrapperBorderLeft = parseFloat(style.borderLeftWidth);
this.#wrapperBorderTop = parseFloat(style.borderTopWidth);
if (this.state.maximized) {
this.state.width = this.#wrapperWidth;
this.state.height = this.#wrapperHeight;
this.state.x = 0;
this.state.y = 0;
} else {
this.#clampRect();
}
this.#apply();
}
#updateCursor = (e: PointerEvent): void => {
if (this.state.moving || this.state.resizing) return;
const target = e.target as HTMLElement;
if (this.#isInteractive(target)) {
this.#resetCursor();
return;
}
if (this.#opts.resizeHandle?.contains(target)) {
this.#node.style.cursor = 'se-resize';
return;
}
const dir = this.#getCornerDirection(e);
if (dir) {
this.#node.style.cursor = dir === 'nw' || dir === 'se' ? 'nwse-resize' : 'nesw-resize';
return;
}
if (this.#opts.handle) {
if (this.#opts.handle.contains(target)) {
this.#node.style.cursor = 'grab';
} else {
this.#node.style.cursor = '';
}
} else {
this.#node.style.cursor = '';
}
};
#resetCursor = (): void => {
this.#node.style.cursor = '';
};
#isInteractive(target: HTMLElement): boolean {
const tag = target.tagName;
if (['INPUT', 'BUTTON', 'TEXTAREA', 'SELECT', 'A'].includes(tag)) return true;
if (target.isContentEditable) return true;
return !!target.closest('[role="button"], [role="textbox"]');
}
minimize(): void {
this.state.minimized = !this.state.minimized;
this.#opts.onMinimize?.();
}
maximize(): void {
if (this.state.maximized) {
if (this.#restoreRect) {
Object.assign(this.state, this.#restoreRect);
this.#restoreRect = null;
}
this.state.maximized = false;
} else {
this.#restoreRect = {
x: this.state.x,
y: this.state.y,
width: this.state.width,
height: this.state.height
};
this.state.x = 0;
this.state.y = 0;
this.state.width = this.#wrapperWidth;
this.state.height = this.#wrapperHeight;
this.state.maximized = true;
}
this.#apply();
}
close(): void {
this.#opts.onClose?.();
}
destroy(): void {
if (this.#rafID !== null) {
cancelAnimationFrame(this.#rafID);
}
this.#node.removeEventListener('pointerdown', this.#onPointerDown);
this.#node.removeEventListener('pointermove', this.#updateCursor);
this.#node.removeEventListener('pointerleave', this.#resetCursor);
//this.#node.removeEventListener('keydown', this.#onKeyDown);
window.removeEventListener('pointermove', this.#onPointerMove);
window.removeEventListener('pointerup', this.#onPointerUp);
window.removeEventListener('pointercancel', this.#onPointerCancel);
if (this.#wrapperObserver) {
this.#wrapperObserver.disconnect();
}
const mgr = getWrapperManager(this.#wrapper);
mgr.refCount--;
if (mgr.refCount === 0) {
delete (this.#wrapper as any)[MWIN_MANAGER];
}
document.body.style.userSelect = '';
this.#node.style.cssText = this.#savedStyles;
this.#node.style.transition = this.#savedTransition;
this.#node.style.willChange = 'auto';
this.#node.style.touchAction = '';
}
}
+96
View File
@@ -0,0 +1,96 @@
export interface MWinParams {
wrapper: HTMLElement | (() => HTMLElement) | string; // changed
handle?: HTMLElement | (() => HTMLElement) | string;
initX?: number;
initY?: number;
initWidth?: number;
initHeight?: number;
baseZIndex?: number;
resizable?: boolean | MWinResizeParams;
resizeHandle?: HTMLElement | (() => HTMLElement) | string;
onClose?: () => void;
onMinimize?: () => void;
onMaximize?: () => void;
onAPI?: (api: MWinAPI) => void;
}
export interface MWinNormalizedParams {
handle: HTMLElement | null;
initX?: number;
initY?: number;
initWidth?: number;
initHeight?: number;
baseZIndex: number;
resizeHandle: HTMLElement | null;
resizable: boolean;
threshold: number;
minWidth: number;
minHeight: number;
maxWidth: number;
maxHeight: number;
onClose?: () => void;
onMinimize?: () => void;
onMaximize?: () => void;
}
export interface MWinResizeParams {
threshold?: number;
minWidth?: number;
minHeight?: number;
maxWidth?: number;
maxHeight?: number;
}
export interface MWinState {
x: number;
y: number;
width: number;
height: number;
minimized: boolean;
maximized: boolean;
moving: boolean;
resizing: boolean;
zIndex: number;
}
export interface MWinAPI {
state: MWinState;
minimize: () => void;
maximize: () => void;
close: () => void;
}
export class WrapperManager {
zCounter: number = 0;
refCount: number = 0;
}
export type ResizeDirection = 'ne' | 'se' | 'sw' | 'nw' | null;
export const MWIN_MANAGER = Symbol('mwinlib');
export function getWrapperManager(wrapper: HTMLElement): WrapperManager {
let mgr = (wrapper as any)[MWIN_MANAGER] as WrapperManager | undefined;
if (!mgr) {
mgr = { zCounter: 0, refCount: 0 };
(wrapper as any)[MWIN_MANAGER] = mgr;
}
return mgr;
}
export function resolveElement(
input: HTMLElement | (() => HTMLElement) | string | undefined,
relativeTo: HTMLElement
): HTMLElement | null {
if (!input) return null;
if (input instanceof HTMLElement) return input;
if (typeof input === 'function') return input();
if (typeof input === 'string') {
return relativeTo.closest(input) as HTMLElement | null;
}
return null;
}
+19
View File
@@ -0,0 +1,19 @@
import { customType } from 'drizzle-orm/mysql-core';
export const mediumblob = customType<{
data: Buffer;
driverData: Buffer;
}>({
dataType() {
return 'MEDIUMBLOB';
}
});
export const longblob = customType<{
data: Buffer;
driverData: Buffer;
}>({
dataType() {
return 'LONGBLOB';
}
});
+5
View File
@@ -0,0 +1,5 @@
//if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set');
//const client = mysql.createPool(env.DATABASE_URL);
//export const db = drizzle(client, { schema, mode: 'default', logger: true });
+83
View File
@@ -0,0 +1,83 @@
import {
boolean,
char,
int,
longtext,
mysqlTable,
serial,
text,
timestamp,
tinyint,
varchar
} from 'drizzle-orm/mysql-core';
import { longblob, mediumblob } from './custom-types';
export const task = mysqlTable('task', {
id: serial('id').primaryKey(),
title: text('title').notNull(),
priority: int('priority').notNull().default(1)
});
export const config = mysqlTable('config', {
key: varchar('key', { length: 64 }).primaryKey(),
value: longtext('value').notNull()
});
export const projects = mysqlTable('projects', {
id: tinyint('id').notNull().primaryKey().autoincrement(),
name: text('name').notNull(),
data: longtext('data', {}).notNull(),
enabled: tinyint('enabled').notNull()
});
export const locales = mysqlTable('locales', {
code: char('code').notNull().unique(),
name: char('name').notNull(),
dictionary: longtext().notNull(),
flag: longtext('').notNull(),
enabled: tinyint('enabled').notNull()
});
export const groups = mysqlTable('groups', {
gid: int('gid').primaryKey().autoincrement(),
name: varchar('name', { length: 32 }).notNull().unique()
});
export const users = mysqlTable('users', {
uid: int('uid').primaryKey().autoincrement(),
username: varchar('username', { length: 32 }).notNull().unique(),
password: varchar('password', { length: 128 }).notNull(),
home: int('home').notNull(),
gid: int('gid')
.notNull()
.references(() => groups.gid),
accessible: boolean('accessible').notNull(),
face: mediumblob('face')
});
export const filesystem = mysqlTable(
'filesystem',
{
id: int('id').primaryKey().default(1),
data: longtext('data').notNull(),
checksum: varchar('checksum', { length: 32 }).notNull(),
updatedAt: timestamp('updated_at').defaultNow().onUpdateNow()
} /* ,
{
// Ensures only one row can exist
singleRow: check('single_row_check', `id = 1`)
} */
);
export const fileContents = mysqlTable('file_contents', {
guid: varchar('guid', { length: 36 }).primaryKey(),
data: longblob('data').notNull(),
mimeType: varchar('mime_type', { length: 127 }).default('text/plain'),
checksum: varchar('checksum', { length: 32 }).notNull()
});
export const allowList = mysqlTable('allow_list', {
ip: int('ip').notNull()
});
export type Config = typeof config.$inferSelect;
+382
View File
@@ -0,0 +1,382 @@
// this file is generated — do not edit it
/// <reference types="@sveltejs/kit" />
/**
* This module provides access to environment variables that are injected _statically_ into your bundle at build time and are limited to _private_ access.
*
* | | Runtime | Build time |
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
*
* Static environment variables are [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env` at build time and then statically injected into your bundle at build time, enabling optimisations like dead code elimination.
*
* **_Private_ access:**
*
* - This module cannot be imported into client-side code
* - This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured)
*
* For example, given the following build time environment:
*
* ```env
* ENVIRONMENT=production
* PUBLIC_BASE_URL=http://site.com
* ```
*
* With the default `publicPrefix` and `privatePrefix`:
*
* ```ts
* import { ENVIRONMENT, PUBLIC_BASE_URL } from '$env/static/private';
*
* console.log(ENVIRONMENT); // => "production"
* console.log(PUBLIC_BASE_URL); // => throws error during build
* ```
*
* The above values will be the same _even if_ different values for `ENVIRONMENT` or `PUBLIC_BASE_URL` are set at runtime, as they are statically replaced in your code with their build time values.
*/
declare module '$env/static/private' {
export const APP2UNIT_SLICES: string;
export const CHROME_DESKTOP: string;
export const CLUTTER_BACKEND: string;
export const DBUS_SESSION_BUS_ADDRESS: string;
export const DEBUGINFOD_URLS: string;
export const DESKTOP_SESSION: string;
export const DISPLAY: string;
export const EDITOR: string;
export const ELECTRON_NO_ATTACH_CONSOLE: string;
export const ELECTRON_OZONE_PLATFORM_HINT: string;
export const FC_FONTATIONS: string;
export const GDK_BACKEND: string;
export const HL_INITIAL_WORKSPACE_TOKEN: string;
export const HOME: string;
export const HYPRLAND_CMD: string;
export const HYPRLAND_INSTANCE_SIGNATURE: string;
export const INVOCATION_ID: string;
export const JOURNAL_STREAM: string;
export const LANG: string;
export const LC_ADDRESS: string;
export const LC_IDENTIFICATION: string;
export const LC_MEASUREMENT: string;
export const LC_MONETARY: string;
export const LC_NAME: string;
export const LC_NUMERIC: string;
export const LC_PAPER: string;
export const LC_TELEPHONE: string;
export const LC_TIME: string;
export const LOGNAME: string;
export const MAIL: string;
export const MANAGERPID: string;
export const MANAGERPIDFDID: string;
export const MEMORY_PRESSURE_WATCH: string;
export const MEMORY_PRESSURE_WRITE: string;
export const MOTD_SHOWN: string;
export const MOZ_ENABLE_WAYLAND: string;
export const NOTIFY_SOCKET: string;
export const NO_AT_BRIDGE: string;
export const PATH: string;
export const PWD: string;
export const QS_ICON_THEME: string;
export const QT_AUTO_SCREEN_SCALE_FACTOR: string;
export const QT_QPA_PLATFORM: string;
export const QT_QPA_PLATFORMTHEME: string;
export const QT_WAYLAND_DISABLE_WINDOWDECORATION: string;
export const SDL_VIDEODRIVER: string;
export const SHELL: string;
export const SHLVL: string;
export const SYSTEMD_EXEC_PID: string;
export const USER: string;
export const UWSM_FINALIZE_VARNAMES: string;
export const UWSM_WAIT_VARNAMES: string;
export const VIRTUAL_ENV_DISABLE_PROMPT: string;
export const VSCODE_CLI: string;
export const VSCODE_CODE_CACHE_PATH: string;
export const VSCODE_CRASH_REPORTER_PROCESS_TYPE: string;
export const VSCODE_CWD: string;
export const VSCODE_ESM_ENTRYPOINT: string;
export const VSCODE_HANDLES_UNCAUGHT_ERRORS: string;
export const VSCODE_IPC_HOOK: string;
export const VSCODE_NLS_CONFIG: string;
export const VSCODE_PID: string;
export const VSSCRIPT_PATH: string;
export const WAYLAND_DISPLAY: string;
export const XCURSOR_SIZE: string;
export const XCURSOR_THEME: string;
export const XDG_BACKEND: string;
export const XDG_CACHE_HOME: string;
export const XDG_CONFIG_DIRS: string;
export const XDG_CONFIG_HOME: string;
export const XDG_CURRENT_DESKTOP: string;
export const XDG_DATA_DIRS: string;
export const XDG_DATA_HOME: string;
export const XDG_MENU_PREFIX: string;
export const XDG_RUNTIME_DIR: string;
export const XDG_SEAT: string;
export const XDG_SEAT_PATH: string;
export const XDG_SESSION_CLASS: string;
export const XDG_SESSION_DESKTOP: string;
export const XDG_SESSION_ID: string;
export const XDG_SESSION_PATH: string;
export const XDG_SESSION_TYPE: string;
export const XDG_STATE_HOME: string;
export const XDG_VTNR: string;
export const _: string;
export const _JAVA_AWT_WM_NONREPARENTING: string;
export const ELECTRON_RUN_AS_NODE: string;
export const VSCODE_L10N_BUNDLE_LOCATION: string;
export const VITEST_VSCODE_LOG: string;
export const VITEST_VSCODE: string;
export const TEST: string;
export const VITEST_WS_ADDRESS: string;
export const VITEST: string;
export const NODE_ENV: string;
export const FORCE_COLOR: string;
export const PROD: string;
export const DEV: string;
export const BASE_URL: string;
export const MODE: string;
}
/**
* This module provides access to environment variables that are injected _statically_ into your bundle at build time and are _publicly_ accessible.
*
* | | Runtime | Build time |
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
*
* Static environment variables are [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env` at build time and then statically injected into your bundle at build time, enabling optimisations like dead code elimination.
*
* **_Public_ access:**
*
* - This module _can_ be imported into client-side code
* - **Only** variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`) are included
*
* For example, given the following build time environment:
*
* ```env
* ENVIRONMENT=production
* PUBLIC_BASE_URL=http://site.com
* ```
*
* With the default `publicPrefix` and `privatePrefix`:
*
* ```ts
* import { ENVIRONMENT, PUBLIC_BASE_URL } from '$env/static/public';
*
* console.log(ENVIRONMENT); // => throws error during build
* console.log(PUBLIC_BASE_URL); // => "http://site.com"
* ```
*
* The above values will be the same _even if_ different values for `ENVIRONMENT` or `PUBLIC_BASE_URL` are set at runtime, as they are statically replaced in your code with their build time values.
*/
declare module '$env/static/public' {
}
/**
* This module provides access to environment variables set _dynamically_ at runtime and that are limited to _private_ access.
*
* | | Runtime | Build time |
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
*
* Dynamic environment variables are defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](https://svelte.dev/docs/kit/cli)), this is equivalent to `process.env`.
*
* **_Private_ access:**
*
* - This module cannot be imported into client-side code
* - This module includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured)
*
* > [!NOTE] In `dev`, `$env/dynamic` includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter.
*
* > [!NOTE] To get correct types, environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed:
* >
* > ```env
* > MY_FEATURE_FLAG=
* > ```
* >
* > You can override `.env` values from the command line like so:
* >
* > ```sh
* > MY_FEATURE_FLAG="enabled" npm run dev
* > ```
*
* For example, given the following runtime environment:
*
* ```env
* ENVIRONMENT=production
* PUBLIC_BASE_URL=http://site.com
* ```
*
* With the default `publicPrefix` and `privatePrefix`:
*
* ```ts
* import { env } from '$env/dynamic/private';
*
* console.log(env.ENVIRONMENT); // => "production"
* console.log(env.PUBLIC_BASE_URL); // => undefined
* ```
*/
declare module '$env/dynamic/private' {
export const env: {
APP2UNIT_SLICES: string;
CHROME_DESKTOP: string;
CLUTTER_BACKEND: string;
DBUS_SESSION_BUS_ADDRESS: string;
DEBUGINFOD_URLS: string;
DESKTOP_SESSION: string;
DISPLAY: string;
EDITOR: string;
ELECTRON_NO_ATTACH_CONSOLE: string;
ELECTRON_OZONE_PLATFORM_HINT: string;
FC_FONTATIONS: string;
GDK_BACKEND: string;
HL_INITIAL_WORKSPACE_TOKEN: string;
HOME: string;
HYPRLAND_CMD: string;
HYPRLAND_INSTANCE_SIGNATURE: string;
INVOCATION_ID: string;
JOURNAL_STREAM: string;
LANG: string;
LC_ADDRESS: string;
LC_IDENTIFICATION: string;
LC_MEASUREMENT: string;
LC_MONETARY: string;
LC_NAME: string;
LC_NUMERIC: string;
LC_PAPER: string;
LC_TELEPHONE: string;
LC_TIME: string;
LOGNAME: string;
MAIL: string;
MANAGERPID: string;
MANAGERPIDFDID: string;
MEMORY_PRESSURE_WATCH: string;
MEMORY_PRESSURE_WRITE: string;
MOTD_SHOWN: string;
MOZ_ENABLE_WAYLAND: string;
NOTIFY_SOCKET: string;
NO_AT_BRIDGE: string;
PATH: string;
PWD: string;
QS_ICON_THEME: string;
QT_AUTO_SCREEN_SCALE_FACTOR: string;
QT_QPA_PLATFORM: string;
QT_QPA_PLATFORMTHEME: string;
QT_WAYLAND_DISABLE_WINDOWDECORATION: string;
SDL_VIDEODRIVER: string;
SHELL: string;
SHLVL: string;
SYSTEMD_EXEC_PID: string;
USER: string;
UWSM_FINALIZE_VARNAMES: string;
UWSM_WAIT_VARNAMES: string;
VIRTUAL_ENV_DISABLE_PROMPT: string;
VSCODE_CLI: string;
VSCODE_CODE_CACHE_PATH: string;
VSCODE_CRASH_REPORTER_PROCESS_TYPE: string;
VSCODE_CWD: string;
VSCODE_ESM_ENTRYPOINT: string;
VSCODE_HANDLES_UNCAUGHT_ERRORS: string;
VSCODE_IPC_HOOK: string;
VSCODE_NLS_CONFIG: string;
VSCODE_PID: string;
VSSCRIPT_PATH: string;
WAYLAND_DISPLAY: string;
XCURSOR_SIZE: string;
XCURSOR_THEME: string;
XDG_BACKEND: string;
XDG_CACHE_HOME: string;
XDG_CONFIG_DIRS: string;
XDG_CONFIG_HOME: string;
XDG_CURRENT_DESKTOP: string;
XDG_DATA_DIRS: string;
XDG_DATA_HOME: string;
XDG_MENU_PREFIX: string;
XDG_RUNTIME_DIR: string;
XDG_SEAT: string;
XDG_SEAT_PATH: string;
XDG_SESSION_CLASS: string;
XDG_SESSION_DESKTOP: string;
XDG_SESSION_ID: string;
XDG_SESSION_PATH: string;
XDG_SESSION_TYPE: string;
XDG_STATE_HOME: string;
XDG_VTNR: string;
_: string;
_JAVA_AWT_WM_NONREPARENTING: string;
ELECTRON_RUN_AS_NODE: string;
VSCODE_L10N_BUNDLE_LOCATION: string;
VITEST_VSCODE_LOG: string;
VITEST_VSCODE: string;
TEST: string;
VITEST_WS_ADDRESS: string;
VITEST: string;
NODE_ENV: string;
FORCE_COLOR: string;
PROD: string;
DEV: string;
BASE_URL: string;
MODE: string;
[key: `PUBLIC_${string}`]: undefined;
[key: `${string}`]: string | undefined;
}
}
/**
* This module provides access to environment variables set _dynamically_ at runtime and that are _publicly_ accessible.
*
* | | Runtime | Build time |
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
*
* Dynamic environment variables are defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](https://svelte.dev/docs/kit/cli)), this is equivalent to `process.env`.
*
* **_Public_ access:**
*
* - This module _can_ be imported into client-side code
* - **Only** variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`) are included
*
* > [!NOTE] In `dev`, `$env/dynamic` includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter.
*
* > [!NOTE] To get correct types, environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed:
* >
* > ```env
* > MY_FEATURE_FLAG=
* > ```
* >
* > You can override `.env` values from the command line like so:
* >
* > ```sh
* > MY_FEATURE_FLAG="enabled" npm run dev
* > ```
*
* For example, given the following runtime environment:
*
* ```env
* ENVIRONMENT=production
* PUBLIC_BASE_URL=http://example.com
* ```
*
* With the default `publicPrefix` and `privatePrefix`:
*
* ```ts
* import { env } from '$env/dynamic/public';
* console.log(env.ENVIRONMENT); // => undefined, not public
* console.log(env.PUBLIC_BASE_URL); // => "http://example.com"
* ```
*
* ```
*
* ```
*/
declare module '$env/dynamic/public' {
export const env: {
[key: `PUBLIC_${string}`]: string | undefined;
}
}
@@ -0,0 +1,28 @@
export { matchers } from './matchers.js';
export const nodes = [
() => import('./nodes/0'),
() => import('./nodes/1')
];
export const server_loads = [];
export const dictionary = {
};
export const hooks = {
handleError: (({ error }) => { console.error(error) }),
reroute: (() => {}),
transport: {}
};
export const decoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.decode]));
export const encoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.encode]));
export const hash = false;
export const decode = (type, value) => decoders[type](value);
export { default as root } from '../root.js';
@@ -0,0 +1 @@
export const matchers = {};
@@ -0,0 +1 @@
export { default as component } from "../../../../../../../node_modules/@sveltejs/kit/src/runtime/components/svelte-5/layout.svelte";
@@ -0,0 +1 @@
export { default as component } from "../../../../../../../node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte";
@@ -0,0 +1,52 @@
{
"compilerOptions": {
"paths": {
"$app/types": [
"./types/index.d.ts"
]
},
"rootDirs": [
"..",
"./types"
],
"verbatimModuleSyntax": true,
"isolatedModules": true,
"lib": [
"esnext",
"DOM",
"DOM.Iterable"
],
"moduleResolution": "bundler",
"module": "esnext",
"noEmit": true,
"target": "esnext",
"types": [
"node"
]
},
"include": [
"ambient.d.ts",
"non-ambient.d.ts",
"./types/**/$types.d.ts",
"../vite.config.js",
"../vite.config.ts",
"../src/**/*.js",
"../src/**/*.ts",
"../src/**/*.svelte",
"../test/**/*.js",
"../test/**/*.ts",
"../test/**/*.svelte",
"../tests/**/*.js",
"../tests/**/*.ts",
"../tests/**/*.svelte"
],
"exclude": [
"../node_modules/**",
"../src/service-worker.js",
"../src/service-worker/**/*.js",
"../src/service-worker.ts",
"../src/service-worker/**/*.ts",
"../src/service-worker.d.ts",
"../src/service-worker/**/*.d.ts"
]
}
+478
View File
@@ -0,0 +1,478 @@
<script lang="ts">
import { onMount } from 'svelte';
import {
CharacterRenderer,
INTERACTION,
ImageCache,
KeyboardInput,
NeedsSimulator,
Physics,
PointerController,
SoundPlayer,
StateClock,
collectStateUrls,
loadSoundPacks,
resolveStateName,
type BubblePack,
type ChatterConfig,
type InteractionConfig,
type StatePack
} from './';
import { CHATTER } from './chatter';
import { NEEDS, type ChatterHooks, type NeedDef } from './needs';
interface Props {
states: Record<string, StatePack>;
bubblePacks?: Record<string, BubblePack>;
needsConfig?: NeedDef[];
chatter?: ChatterConfig | null;
interactions?: InteractionConfig;
scale?: number;
maxSpeed?: number;
idleThreshold?: number;
runThreshold?: number;
acceleration?: number;
friction?: number;
startAt?: number;
floorHeight?: number;
floorColor?: string;
reflectionOpacity?: number;
reflectionFade?: number;
reflectionTint?: string;
wrapEdges?: boolean;
jumpVelocity?: number;
gravity?: number;
showShadow?: boolean;
bubbleAnchorX?: number;
bubbleAnchorY?: number;
muted?: boolean;
}
let {
states,
bubblePacks,
needsConfig = NEEDS,
chatter = CHATTER,
interactions = INTERACTION,
scale = 4,
maxSpeed = 280,
idleThreshold = 10,
runThreshold = 190,
acceleration = 1600,
friction = 2400,
startAt = 0.5,
floorHeight = 90,
floorColor = '#242830',
reflectionOpacity = 0.45,
reflectionFade = 0.9,
reflectionTint = 'rgba(120, 160, 200, 0.3)',
wrapEdges = true,
jumpVelocity = 620,
gravity = 2400,
showShadow = true,
bubbleAnchorX = 0,
bubbleAnchorY = 4,
muted = false
}: Props = $props();
/* ---------- DOM ---------- */
let canvas = $state<HTMLCanvasElement>();
let ctx: CanvasRenderingContext2D | null = null;
let dpr = 1;
let viewW = 0;
let viewH = 0;
/* ---------- Subsystems ---------- */
const cache = new ImageCache();
const physics = new Physics();
const clock = new StateClock();
const input = new KeyboardInput();
const needs = new NeedsSimulator();
const renderer = new CharacterRenderer();
const pointer = new PointerController(INTERACTION);
let soundPlayer: SoundPlayer | null = null;
let audioCtx: AudioContext | null = null;
let ready = false;
let placed = false;
let heldAnchorSet = false;
let loadError = $state<string | null>(null);
// Last drawn body size — used for pointer hit-testing on the next frame.
let lastBodyW = 0;
let lastBodyH = 0;
/* ---------- Asset loading ---------- */
const urlKey = $derived(
[
...collectStateUrls(states),
...Object.values(bubblePacks ?? {}).flatMap((p) => p.frames)
].join('\n')
);
$effect(() => {
const key = urlKey;
ready = false;
loadError = null;
if (!key) {
loadError = 'No state frames found. Check $lib/assets/character/states/.';
return;
}
let cancelled = false;
cache
.load(key.split('\n'))
.then(() => {
if (cancelled) return;
rebound();
ready = true;
})
.catch((err: Error) => {
if (cancelled) return;
loadError = err.message;
});
return () => {
cancelled = true;
};
});
/* ---------- Bounds ---------- */
function bounds() {
const { w } = cache.largestSize(collectStateUrls(states));
return { viewW, viewH, floorHeight, spriteW: w, scale };
}
function resize() {
if (!canvas || !ctx) return;
dpr = Math.min(window.devicePixelRatio || 1, 3);
const rect = canvas.getBoundingClientRect();
viewW = rect.width;
viewH = rect.height;
canvas.width = Math.max(1, Math.round(rect.width * dpr));
canvas.height = Math.max(1, Math.round(rect.height * dpr));
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.imageSmoothingEnabled = false;
if (!placed && viewW > 0) {
placed = true;
physics.place(viewW, startAt);
}
rebound();
}
function rebound() {
physics.rebound(
{ maxSpeed, acceleration, friction, jumpVelocity, gravity, wrapEdges },
bounds()
);
}
/* ---------- Audio ---------- */
const GESTURES = ['pointerdown', 'keydown', 'touchstart'] as const;
function unlockAudio() {
if (audioCtx) return;
try {
const Ctor = window.AudioContext ?? (window as any).webkitAudioContext;
if (!Ctor) return;
audioCtx = new Ctor();
void audioCtx.resume();
void loadSoundPacks(audioCtx).then((packs) => {
if (!audioCtx) return;
soundPlayer = new SoundPlayer(audioCtx, packs);
soundPlayer.setMuted(muted);
});
} catch (err) {
console.warn('[character] audio unavailable', err);
}
for (const g of GESTURES) window.removeEventListener(g, unlockAudio);
}
function installAudioUnlocker() {
for (const g of GESTURES) window.addEventListener(g, unlockAudio, { passive: true });
}
$effect(() => {
soundPlayer?.setMuted(muted);
});
function playSound(name: string, volume: number) {
soundPlayer?.play(name, volume);
}
/* ---------- State resolution ---------- */
function activeStateName(): string {
const needAction =
needs.active?.actionState && needs.active.elapsed >= needs.active.actionStart
? needs.active.actionState.name
: null;
return resolveStateName(
{
interaction: pointer.state,
grounded: physics.grounded,
speed: Math.abs(physics.vx),
needAction
},
{ idleThreshold, runThreshold },
states
);
}
function sideFor(pack: StatePack) {
return physics.facing === 'left' ? pack.left : pack.right;
}
function bodyFor(name: string): HTMLImageElement | null {
const pack = states[name];
if (!pack) return null;
const side = sideFor(pack);
if (!side.frames.length) return null;
const i = clock.frameIndex(pack, side);
return cache.get(side.frames[i]) ?? null;
}
/* ---------- Bubble ---------- */
function currentBubble(): { img: HTMLImageElement; index: number } | null {
if (pointer.state === 'held' || pointer.state === 'petted') return null;
const a = needs.active;
if (!a?.bubblePack || !a.bubblePack.frames.length) return null;
if (a.elapsed >= a.bubbleDuration) return null;
const index = Math.min(
Math.floor(a.elapsed * a.bubblePack.fps),
a.bubblePack.frames.length - 1
);
const img = cache.get(a.bubblePack.frames[index]);
return img ? { img, index } : null;
}
function currentCharsShown(): number {
const a = needs.active;
if (!a?.text || !chatter) return Infinity;
const speed = chatter.typeSpeed ?? 0;
if (speed <= 0) return Infinity;
const pack = a.bubblePack;
const textStart = pack ? (chatter.textFrame ?? 0) / pack.fps : 0;
const typingElapsed = a.elapsed - textStart;
if (typingElapsed <= 0) return 0;
return Math.min(a.text.length, Math.floor(typingElapsed * speed));
}
function buildChatterHooks(c: ChatterConfig): ChatterHooks {
return {
pack: c.pack,
interval: c.interval,
lines: c.lines,
typeSpeed: c.typeSpeed,
typeSound: c.typeSound,
typeSoundEvery: c.typeSoundEvery,
typeSoundVolume: c.typeSoundVolume,
bubbleDuration: (line: string, pack: BubblePack) => {
const animDur = pack.frames.length / pack.fps;
const textStart = (c.textFrame ?? 0) / pack.fps;
const speed = c.typeSpeed ?? 0;
const typing = speed > 0 ? line.length / speed : 0;
return Math.max(animDur, textStart + typing) + (c.holdLast ?? 1.6);
}
};
}
/* ---------- Loop ---------- */
let raf = 0;
let last = 0;
function loop(now: number) {
raf = requestAnimationFrame(loop);
const dt = last ? Math.min((now - last) / 1000, 1 / 20) : 0;
last = now;
if (!ready || !ctx) return;
const locked = needs.isLocked || pointer.state === 'held';
/* --- physics or held --- */
if (pointer.state === 'held') {
if (!heldAnchorSet) {
pointer.setGrabAnchor(physics.x, physics.y);
heldAnchorSet = true;
}
const anchor = pointer.getHeldPosition();
if (anchor) {
physics.x = anchor.x;
physics.y = Math.max(0, anchor.y);
physics.vx = 0;
physics.vy = 0;
physics.grounded = false;
physics.squash = 0;
}
} else {
heldAnchorSet = false;
physics.step(
dt,
{
direction: locked ? 0 : input.direction(),
jump: locked ? false : input.consumeJump()
},
{ maxSpeed, acceleration, friction, jumpVelocity, gravity, wrapEdges },
bounds()
);
}
/* --- falling → landing --- */
if (pointer.state === 'falling' && physics.grounded) {
pointer.setState('landing');
}
/* --- pointer bounds, then tick the pointer --- */
if (lastBodyW > 0) {
const gy = physics.groundY(bounds());
pointer.setBounds({
left: physics.x - lastBodyW / 2,
top: gy - physics.y - lastBodyH,
width: lastBodyW,
height: lastBodyH
});
}
pointer.update(dt);
/* --- resolve state and advance its clock --- */
const name = activeStateName();
const pack = states[name];
clock.update(dt, name, pack, Math.abs(physics.vx));
/* --- body image --- */
const body = bodyFor(name);
if (body) {
lastBodyW = body.naturalWidth * scale;
lastBodyH = body.naturalHeight * scale;
}
/* --- needs --- */
needs.step(dt, name, {
defs: needsConfig,
bubblePacks: bubblePacks ?? {},
states,
chatter: chatter ? buildChatterHooks(chatter) : null,
onSound: playSound
});
/* --- draw --- */
if (!body || !pack) return;
const side = sideFor(pack);
renderer.draw({
ctx,
viewW,
viewH,
groundY: physics.groundY(bounds()),
dpr,
body,
mirrored: side.mirrored,
x: physics.x,
y: physics.y,
squash: physics.squash,
bubble: currentBubble(),
bubbleText: needs.active?.text ?? null,
charsShown: currentCharsShown(),
bubbleTextFrame: chatter?.textFrame ?? 0,
scale,
showShadow,
reflectionOpacity,
reflectionFade,
reflectionTint,
bubbleAnchorX,
bubbleAnchorY,
chatter
});
}
onMount(() => {
if (!canvas) return;
ctx = canvas.getContext('2d');
if (!ctx) return;
pointer.onGrab = () => {
needs.active = null;
needs.queue.length = 0;
heldAnchorSet = false;
if (interactions.pickupSound) playSound(interactions.pickupSound, 1);
};
pointer.onRelease = () => {
const v = pointer.getThrowVelocity();
physics.vx = v.vx;
physics.vy = v.vy;
// If the throw is upward, lift the cat out of the grounded state.
if (physics.vy > 0) physics.grounded = false;
if (interactions.dropSound) playSound(interactions.dropSound, 0.8);
};
pointer.onLanding = () => {
if (interactions.landingSound) playSound(interactions.landingSound, 0.8);
};
pointer.onPetSound = () => {
if (interactions.purrSound) playSound(interactions.purrSound, interactions.purrVolume ?? 0.4);
};
resize();
const ro = new ResizeObserver(resize);
ro.observe(canvas);
input.attach(window);
pointer.attach(window);
installAudioUnlocker();
raf = requestAnimationFrame(loop);
return () => {
cancelAnimationFrame(raf);
ro.disconnect();
input.detach(window);
pointer.detach(window);
for (const g of GESTURES) window.removeEventListener(g, unlockAudio);
void audioCtx?.close();
};
});
</script>
<svelte:window />
<div class="layer">
<div class="floor" style:height="{floorHeight}px" style:background={floorColor}></div>
<canvas bind:this={canvas} aria-hidden="true"></canvas>
{#if loadError}
<p class="err">{loadError}</p>
{/if}
</div>
<style>
.layer {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 50;
}
.floor {
position: absolute;
left: 0;
right: 0;
bottom: 0;
background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.06), rgba(0, 0, 0, 0.15));
background-blend-mode: overlay;
}
canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
image-rendering: pixelated;
}
.err {
position: absolute;
bottom: 1rem;
left: 1rem;
margin: 0;
font:
12px/1.4 ui-monospace,
monospace;
color: #ff6b6b;
}
</style>
+75
View File
@@ -0,0 +1,75 @@
const files = import.meta.glob('$lib/assets/character/bubbles/**/*.png', {
eager: true,
query: '?url',
import: 'default'
}) as Record<string, string>;
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
const BUBBLE_RE = /\/bubbles\/([^/]+)\/[^/]+\.png$/i;
export interface BubblePack {
name: string;
frames: string[];
fps: number;
duration: number;
}
export interface BubblePackOptions {
fps?: number;
duration?: number;
}
export function loadBubblePacks(opts: BubblePackOptions = {}): Record<string, BubblePack> {
const { fps = 8, duration = 2.5 } = opts;
const groups = new Map<string, Array<[string, string]>>();
for (const [path, url] of Object.entries(files)) {
const m = BUBBLE_RE.exec(path);
if (!m) continue;
const name = m[1].toLowerCase();
if (!groups.has(name)) groups.set(name, []);
groups.get(name)!.push([path, url]);
}
const out: Record<string, BubblePack> = {};
for (const [name, entries] of groups) {
const frames = entries.sort(([a], [b]) => collator.compare(a, b)).map(([, url]) => url);
out[name] = { name, frames, fps, duration };
}
return out;
}
export class ImageCache {
private images = new Map<string, HTMLImageElement>();
async load(urls: string[]): Promise<void> {
const results = await Promise.all(
urls.map(
(url) =>
new Promise<[string, HTMLImageElement]>((resolve, reject) => {
const img = new Image();
img.onload = () => resolve([url, img]);
img.onerror = () => reject(new Error(`Could not load "${url}"`));
img.src = url;
})
)
);
this.images = new Map(results);
}
get(url: string): HTMLImageElement | undefined {
return this.images.get(url);
}
largestSize(urls: string[]): { w: number; h: number } {
let w = 0;
let h = 0;
for (const url of urls) {
const img = this.images.get(url);
if (!img) continue;
w = Math.max(w, img.naturalWidth);
h = Math.max(h, img.naturalHeight);
}
return { w, h };
}
}
+53
View File
@@ -0,0 +1,53 @@
export interface ChatterConfig {
pack: string;
interval: [number, number];
lines: string[];
fontFamily?: string;
fontSize?: number;
color?: string;
align?: 'center' | 'left';
padding?: { top?: number; right?: number; bottom?: number; left?: number };
/** Distance from bubble top to the top of the first line, in sprite px. */
textTop?: number;
lineHeight?: number;
/** Bubble frame index at which text appears. */
textFrame?: number;
/** Typewriter speed in characters per second. */
typeSpeed?: number;
/** Sound pack for typing clicks. */
typeSound?: string;
typeSoundEvery?: number;
typeSoundVolume?: number;
/** Seconds the last frame holds after typing completes. */
holdLast?: number;
}
export const CHATTER: ChatterConfig = {
pack: 'chatter',
interval: [12, 28],
lines: [
'mrrrp?',
'i could go for a nap',
'nice day for it',
'...',
'you again',
'meow',
'did you see that bird',
'my bowl is looking empty',
'i meant to do that',
'five more minutes'
],
fontFamily: "'Micro 5', sans-serif",
fontSize: 11,
color: '#1a1a1a',
align: 'center',
padding: { top: 8, right: 8, bottom: 8, left: 8 },
textTop: 8,
lineHeight: 1.2,
textFrame: 1,
typeSpeed: 24,
typeSound: 'type',
typeSoundEvery: 2,
typeSoundVolume: 0.3,
holdLast: 1.6
};
+43
View File
@@ -0,0 +1,43 @@
export type { Facing, PhysicsInput } from './types';
export { collectStateUrls, loadStates, resolveStateName, STATE_CONFIG, StateClock } from './states';
export type {
InteractionState,
ResolverConfig,
StateConfig,
StateConfigMap,
StateContext,
StatePack,
StateSide
} from './states';
export { ImageCache, loadBubblePacks } from './assets';
export type { BubblePack, BubblePackOptions } from './assets';
export { clamp, Physics } from './physics';
export type { PhysicsBounds, PhysicsConfig } from './physics';
export { KeyboardInput } from './input';
export { NEEDS, NeedsSimulator } from './needs';
export type {
ActiveEvent,
ChatterHooks,
FiredEvent,
NeedBand,
NeedDef,
NeedsConfig,
NeedSideEffect
} from './needs';
export { CHATTER } from './chatter';
export type { ChatterConfig } from './chatter';
export { CharacterRenderer } from './render';
export type { RenderInput } from './render';
export { loadSoundPacks, SoundPlayer } from './sounds';
export type { SoundPack } from './sounds';
export { INTERACTION, PointerController } from './interactions';
export type { InteractionConfig, PointerBounds } from './interactions';
+67
View File
@@ -0,0 +1,67 @@
const JUMP_KEYS = new Set([' ', 'w', 'arrowup']);
const MOVE_KEYS = new Set(['arrowleft', 'arrowright', 'a', 'd']);
export class KeyboardInput {
private held = new Set<string>();
private jumpQueued = false;
private listeners: Array<[string, EventListener]> = [];
attach(target: Window): void {
const down: EventListener = (e) => this.onKeyDown(e as KeyboardEvent);
const up: EventListener = (e) => this.onKeyUp(e as KeyboardEvent);
const blur: EventListener = () => this.clear();
target.addEventListener('keydown', down);
target.addEventListener('keyup', up);
target.addEventListener('blur', blur);
this.listeners = [
['keydown', down],
['keyup', up],
['blur', blur]
];
}
detach(target: Window): void {
for (const [type, fn] of this.listeners) target.removeEventListener(type, fn);
this.listeners = [];
}
direction(): -1 | 0 | 1 {
let d = 0;
if (this.held.has('arrowleft') || this.held.has('a')) d -= 1;
if (this.held.has('arrowright') || this.held.has('d')) d += 1;
return d as -1 | 0 | 1;
}
consumeJump(): boolean {
const j = this.jumpQueued;
this.jumpQueued = false;
return j;
}
clear(): void {
this.held.clear();
this.jumpQueued = false;
}
private onKeyDown(e: KeyboardEvent): void {
const k = e.key.toLowerCase();
if (JUMP_KEYS.has(k)) {
e.preventDefault();
if (!this.held.has(k)) this.jumpQueued = true;
this.held.add(k);
return;
}
if (MOVE_KEYS.has(k)) {
e.preventDefault();
this.held.add(k);
}
}
private onKeyUp(e: KeyboardEvent): void {
this.held.delete(e.key.toLowerCase());
}
}
+266
View File
@@ -0,0 +1,266 @@
import type { InteractionState } from './states';
export interface PointerBounds {
left: number;
top: number;
width: number;
height: number;
}
export interface InteractionConfig {
enabled?: boolean;
landingDuration?: number;
petDelay?: number;
petLinger?: number;
petSoundInterval?: number;
pickupSound?: string;
dropSound?: string;
landingSound?: string;
purrSound?: string;
purrVolume?: number;
/** Hard cap on throw speed, px/s. Prevents a fast flick launching the cat off-screen. */
maxThrowVelocity?: number;
/** Cursor-velocity smoothing, 0–1. Higher = twitchier throws, lower = smoother. */
throwSmoothing?: number;
}
export const INTERACTION: InteractionConfig = {
enabled: true,
landingDuration: 0.5,
petDelay: 0.25,
petLinger: 0.3,
petSoundInterval: 0.9,
pickupSound: 'pickup',
dropSound: 'drop',
landingSound: 'landing',
purrSound: 'purr',
purrVolume: 0.35,
maxThrowVelocity: 1200,
throwSmoothing: 0.35
};
function clamp(v: number, lo: number, hi: number): number {
return Math.min(Math.max(v, lo), hi);
}
function lerp(a: number, b: number, t: number): number {
return a + (b - a) * t;
}
export class PointerController {
cursorX = 0;
cursorY = 0;
state: InteractionState = 'free';
timeInState = 0;
onGrab?: () => void;
onRelease?: () => void;
onLanding?: () => void;
onPetStart?: () => void;
onPetSound?: () => void;
private cfg: Required<
Pick<
InteractionConfig,
| 'landingDuration'
| 'petDelay'
| 'petLinger'
| 'petSoundInterval'
| 'maxThrowVelocity'
| 'throwSmoothing'
>
> & { enabled: boolean };
private bounds: PointerBounds | null = null;
private grabAnchor: { x: number; y: number } | null = null;
private grabPointer = { x: 0, y: 0 };
private hoverTime = 0;
private lingerTime = 0;
private purrTimer = 0;
private listeners: Array<[string, EventListener]> = [];
// Cursor velocity tracking (screen coordinates, px/s).
private prevCursorX = 0;
private prevCursorY = 0;
private prevCursorSet = false;
private smoothVX = 0;
private smoothVY = 0;
constructor(cfg: InteractionConfig) {
this.cfg = {
enabled: cfg.enabled ?? true,
landingDuration: cfg.landingDuration ?? 0.5,
petDelay: cfg.petDelay ?? 0.25,
petLinger: cfg.petLinger ?? 0.3,
petSoundInterval: cfg.petSoundInterval ?? 0.9,
maxThrowVelocity: cfg.maxThrowVelocity ?? 1200,
throwSmoothing: clamp(cfg.throwSmoothing ?? 0.35, 0.05, 1)
};
}
attach(target: Window): void {
if (!this.cfg.enabled) return;
const down: EventListener = (e) => this.onPointerDown(e as PointerEvent);
const up: EventListener = () => this.onPointerUp();
const move: EventListener = (e) => this.onPointerMove(e as PointerEvent);
const leave: EventListener = () => this.onPointerLeave();
const pairs: Array<[string, EventListener]> = [
['pointerdown', down],
['pointerup', up],
['pointermove', move],
['pointerleave', leave]
];
for (const [type, fn] of pairs) target.addEventListener(type, fn);
this.listeners = pairs;
}
detach(target: Window): void {
for (const [type, fn] of this.listeners) target.removeEventListener(type, fn);
this.listeners = [];
}
setBounds(b: PointerBounds): void {
this.bounds = b;
}
setGrabAnchor(x: number, y: number): void {
this.grabAnchor = { x, y };
}
getHeldPosition(): { x: number; y: number } | null {
if (this.state !== 'held' || !this.grabAnchor) return null;
const dx = this.cursorX - this.grabPointer.x;
const dy = this.cursorY - this.grabPointer.y;
return { x: this.grabAnchor.x + dx, y: this.grabAnchor.y - dy };
}
/**
* Cursor velocity at the moment of release, converted to internal coordinates.
* `x` matches screen x; `y` is flipped because internal y grows upward.
*/
getThrowVelocity(): { vx: number; vy: number } {
const cap = this.cfg.maxThrowVelocity;
return {
vx: clamp(this.smoothVX, -cap, cap),
vy: clamp(-this.smoothVY, -cap, cap)
};
}
setState(s: InteractionState): void {
if (this.state === s) return;
this.state = s;
this.timeInState = 0;
if (s === 'held') this.onGrab?.();
if (s === 'falling') this.onRelease?.();
if (s === 'landing') this.onLanding?.();
if (s === 'petted') {
this.purrTimer = 0;
this.onPetStart?.();
}
}
update(dt: number): void {
this.timeInState += dt;
// Cursor velocity tracking. Only meaningful while held; otherwise decay
// to zero so a stale flick doesn't linger between grabs.
if (this.state === 'held' && this.prevCursorSet && dt > 0) {
const rawVX = (this.cursorX - this.prevCursorX) / dt;
const rawVY = (this.cursorY - this.prevCursorY) / dt;
const a = this.cfg.throwSmoothing;
this.smoothVX = lerp(this.smoothVX, rawVX, a);
this.smoothVY = lerp(this.smoothVY, rawVY, a);
} else if (this.state !== 'held') {
this.smoothVX = 0;
this.smoothVY = 0;
}
this.prevCursorX = this.cursorX;
this.prevCursorY = this.cursorY;
this.prevCursorSet = true;
if (this.state === 'landing' && this.timeInState >= this.cfg.landingDuration) {
this.setState('free');
}
if (this.state === 'free') {
if (this.hoveringHead()) {
this.hoverTime += dt;
if (this.hoverTime >= this.cfg.petDelay) {
this.hoverTime = 0;
this.setState('petted');
}
} else {
this.hoverTime = 0;
}
} else {
this.hoverTime = 0;
}
if (this.state === 'petted') {
if (this.hoveringHead()) {
this.lingerTime = 0;
} else {
this.lingerTime += dt;
if (this.lingerTime >= this.cfg.petLinger) {
this.lingerTime = 0;
this.setState('free');
}
}
this.purrTimer += dt;
if (this.purrTimer >= this.cfg.petSoundInterval) {
this.purrTimer = 0;
this.onPetSound?.();
}
}
}
private hoveringHead(): boolean {
const b = this.bounds;
if (!b) return false;
return (
this.cursorX >= b.left &&
this.cursorX <= b.left + b.width &&
this.cursorY >= b.top &&
this.cursorY <= b.top + b.height / 2
);
}
private hoveringBody(): boolean {
const b = this.bounds;
if (!b) return false;
return (
this.cursorX >= b.left &&
this.cursorX <= b.left + b.width &&
this.cursorY >= b.top &&
this.cursorY <= b.top + b.height
);
}
private onPointerDown(e: PointerEvent): void {
if (this.state !== 'free' && this.state !== 'petted') return;
this.cursorX = e.clientX;
this.cursorY = e.clientY;
if (!this.hoveringBody()) return;
e.preventDefault();
this.grabPointer = { x: this.cursorX, y: this.cursorY };
this.setState('held');
}
private onPointerUp(): void {
if (this.state === 'held') this.setState('falling');
}
private onPointerMove(e: PointerEvent): void {
this.cursorX = e.clientX;
this.cursorY = e.clientY;
}
private onPointerLeave(): void {
if (this.state === 'held') this.setState('falling');
}
}
+338
View File
@@ -0,0 +1,338 @@
import type { BubblePack } from './assets';
import type { StatePack } from './states';
export interface NeedBand {
at: number;
bubble: string;
action?: string;
sound?: string;
soundVolume?: number;
bubbleDuration?: number;
/** Seconds after the bubble disappears that the action begins. */
actionDelay?: number;
satisfyDuration?: number;
priority?: number;
}
export interface NeedSideEffect {
need: string;
perSecond: number;
}
export interface NeedDef {
id: string;
label: string;
riseRate: number;
max: number;
/** Multipliers on `riseRate` keyed by state name (idle, walk, run, jump, ...). */
activityMultipliers: Record<string, number>;
curve?: number;
bands: NeedBand[];
resetBelow: number;
priority: number;
satisfyDuration: number;
satisfyTo: number;
satisfySideEffects?: NeedSideEffect[];
/** Default bubbleDuration for this need's bands. */
bubbleDuration?: number;
/** Default actionDelay for this need's bands. */
actionDelay?: number;
}
export const NEEDS: NeedDef[] = [
{
id: 'thirst',
label: 'Thirst',
riseRate: 0.9,
max: 100,
activityMultipliers: { idle: 1, walk: 1.3, run: 2.0, jump: 1.6 },
curve: 0.5,
bands: [
{
at: 85,
bubble: 'thirst_urgent',
action: 'drink',
sound: 'thirst_urgent',
soundVolume: 0.6,
bubbleDuration: 1.6,
actionDelay: 0.4,
satisfyDuration: 4
},
{ at: 50, bubble: 'thirst_mild', bubbleDuration: 2 }
],
resetBelow: 15,
priority: 2,
satisfyDuration: 3,
satisfyTo: 0
},
{
id: 'boredom',
label: 'Boredom',
riseRate: 1.4,
max: 100,
activityMultipliers: { idle: 1.8, walk: 0.6, run: 0.3, jump: 0.5 },
curve: 0.3,
bands: [
{
at: 80,
bubble: 'bored_urgent',
action: 'play',
bubbleDuration: 1.6,
actionDelay: 0.4,
satisfyDuration: 5
},
{ at: 40, bubble: 'bored_mild', bubbleDuration: 2 }
],
resetBelow: 10,
priority: 1,
satisfyDuration: 4,
satisfyTo: 0
},
{
id: 'sleepiness',
label: 'Sleepiness',
riseRate: 0.6,
max: 100,
activityMultipliers: { idle: 1, walk: 1.2, run: 1.5, jump: 1.3 },
curve: 0.4,
bands: [
{
at: 90,
bubble: 'sleepy_urgent',
action: 'sleep',
bubbleDuration: 1.6,
actionDelay: 0.4,
satisfyDuration: 8
},
{ at: 60, bubble: 'sleepy_mild', bubbleDuration: 2 }
],
resetBelow: 5,
priority: 3,
satisfyDuration: 6,
satisfyTo: 0,
satisfySideEffects: [{ need: 'thirst', perSecond: 0.4 }]
}
];
export interface FiredEvent {
needId: string | null;
def: NeedDef | null;
band: NeedBand;
priority: number;
text?: string;
}
export interface ActiveEvent {
needId: string | null;
def: NeedDef | null;
bubblePack: BubblePack | null;
actionState: StatePack | null;
elapsed: number;
totalDuration: number;
satisfyTo: number;
text?: string;
soundPack?: string | null;
soundVolume?: number;
lastCharsShown: number;
bubbleDuration: number;
actionDelay: number;
satisfyDuration: number;
actionStart: number;
}
export interface ChatterHooks {
pack: string;
interval: [number, number];
lines: string[];
typeSpeed?: number;
typeSound?: string;
typeSoundEvery?: number;
typeSoundVolume?: number;
/** Total seconds the bubble stays up, computed by the caller. */
bubbleDuration: (line: string, pack: BubblePack) => number;
}
export interface NeedsConfig {
defs: NeedDef[];
bubblePacks: Record<string, BubblePack>;
states: Record<string, StatePack>;
chatter: ChatterHooks | null;
onSound: (name: string, volume: number) => void;
}
const MAX_QUEUE = 8;
export class NeedsSimulator {
values: Record<string, number> = {};
firedBands = new Set<string>();
queue: FiredEvent[] = [];
active: ActiveEvent | null = null;
chatterTimer = 0;
chatterTarget = -1;
private initialized = false;
get isLocked(): boolean {
return !!this.active?.actionState && this.active.elapsed >= this.active.actionStart;
}
step(dt: number, activity: string, cfg: NeedsConfig): void {
if (!cfg.defs.length) return;
if (!this.initialized) {
for (const d of cfg.defs) this.values[d.id] = 0;
this.initialized = true;
}
this.rise(dt, activity, cfg);
this.applySideEffects(dt, cfg);
this.checkBands(cfg);
this.maybeChatter(dt, cfg);
this.drainQueue(cfg);
this.advance(dt, cfg);
}
private rise(dt: number, activity: string, cfg: NeedsConfig): void {
for (const def of cfg.defs) {
if (this.active?.needId === def.id) continue;
const v = this.values[def.id] ?? 0;
const mult = def.activityMultipliers[activity] ?? 1;
const curve = def.curve ? Math.pow(1 + v / def.max, def.curve) : 1;
this.values[def.id] = Math.min(def.max, v + def.riseRate * mult * curve * dt);
}
}
private applySideEffects(dt: number, cfg: NeedsConfig): void {
const fx = this.active?.def?.satisfySideEffects;
if (!fx) return;
for (const e of fx) {
const other = cfg.defs.find((n) => n.id === e.need);
if (!other) continue;
const cur = this.values[other.id] ?? 0;
this.values[other.id] = Math.min(other.max, cur + e.perSecond * dt);
}
}
private checkBands(cfg: NeedsConfig): void {
for (const def of cfg.defs) {
const v = this.values[def.id] ?? 0;
for (const band of def.bands) {
const key = `${def.id}:${band.at}`;
if (v >= band.at && !this.firedBands.has(key)) {
this.firedBands.add(key);
if (this.queue.length < MAX_QUEUE) {
this.queue.push({
needId: def.id,
def,
band,
priority: band.priority ?? def.priority
});
}
} else if (v < def.resetBelow && this.firedBands.has(key)) {
this.firedBands.delete(key);
}
}
}
}
private maybeChatter(dt: number, cfg: NeedsConfig): void {
const c = cfg.chatter;
if (!c || !c.lines.length) return;
const pack = cfg.bubblePacks[c.pack];
if (!pack) return;
if (this.chatterTarget < 0) this.chatterTarget = randBetween(...c.interval);
if (this.active || this.queue.length > 0) return;
this.chatterTimer += dt;
if (this.chatterTimer < this.chatterTarget) return;
this.chatterTimer = 0;
this.chatterTarget = randBetween(...c.interval);
const line = c.lines[Math.floor(Math.random() * c.lines.length)];
this.queue.push({
needId: null,
def: null,
band: {
at: 0,
bubble: c.pack,
bubbleDuration: c.bubbleDuration(line, pack)
},
priority: -1000,
text: line
});
}
private drainQueue(cfg: NeedsConfig): void {
if (this.queue.length > 1) this.queue.sort((a, b) => b.priority - a.priority);
if (this.active || !this.queue.length) return;
const fired = this.queue.shift()!;
this.active = buildActiveEvent(fired, cfg);
if (this.active.soundPack) {
cfg.onSound(this.active.soundPack, this.active.soundVolume ?? 1);
}
}
private advance(dt: number, cfg: NeedsConfig): void {
const a = this.active;
if (!a) return;
a.elapsed += dt;
const c = cfg.chatter;
if (a.text && c?.typeSound && a.elapsed < a.bubbleDuration) {
const speed = c.typeSpeed ?? 0;
if (speed > 0) {
const charsShown = Math.min(a.text.length, Math.floor(a.elapsed * speed));
const every = Math.max(1, c.typeSoundEvery ?? 2);
const before = Math.floor(a.lastCharsShown / every);
const now = Math.floor(charsShown / every);
if (now > before) cfg.onSound(c.typeSound, c.typeSoundVolume ?? 0.3);
a.lastCharsShown = charsShown;
}
}
if (a.elapsed >= a.totalDuration) {
if (a.needId && a.def) this.values[a.needId] = a.satisfyTo;
this.active = null;
}
}
}
function buildActiveEvent(fired: FiredEvent, cfg: NeedsConfig): ActiveEvent {
const bubblePack = fired.band.bubble ? (cfg.bubblePacks[fired.band.bubble] ?? null) : null;
const actionState = fired.band.action ? (cfg.states[fired.band.action] ?? null) : null;
const bubbleDuration =
fired.band.bubbleDuration ?? fired.def?.bubbleDuration ?? bubblePack?.duration ?? 2.5;
const satisfyDuration = fired.band.satisfyDuration ?? fired.def?.satisfyDuration ?? 0;
const actionDelay = actionState ? (fired.band.actionDelay ?? fired.def?.actionDelay ?? 0.4) : 0;
const actionStart = bubbleDuration + actionDelay;
const totalDuration = actionState ? actionStart + satisfyDuration : bubbleDuration;
return {
needId: fired.needId,
def: fired.def,
bubblePack,
actionState,
elapsed: 0,
totalDuration,
satisfyTo: fired.def?.satisfyTo ?? 0,
text: fired.text,
soundPack: fired.band.sound ?? null,
soundVolume: fired.band.soundVolume ?? 1,
lastCharsShown: 0,
bubbleDuration,
actionDelay,
satisfyDuration,
actionStart
};
}
function randBetween(min: number, max: number): number {
return min + Math.random() * (max - min);
}
+102
View File
@@ -0,0 +1,102 @@
import type { Facing, PhysicsInput } from './types';
export interface PhysicsConfig {
maxSpeed: number;
acceleration: number;
friction: number;
jumpVelocity: number;
gravity: number;
wrapEdges: boolean;
}
export interface PhysicsBounds {
viewW: number;
viewH: number;
floorHeight: number;
spriteW: number;
scale: number;
}
export function clamp(v: number, lo: number, hi: number): number {
return Math.min(Math.max(v, lo), hi);
}
export class Physics {
x = 0;
vx = 0;
y = 0;
vy = 0;
grounded = true;
squash = 0;
facing: Facing = 'right';
place(viewW: number, fraction: number): void {
this.x = viewW * fraction;
}
step(dt: number, input: PhysicsInput, cfg: PhysicsConfig, bounds: PhysicsBounds): void {
/* --- horizontal --- */
if (input.direction !== 0) {
this.vx = clamp(
this.vx + input.direction * cfg.acceleration * dt,
-cfg.maxSpeed,
cfg.maxSpeed
);
this.facing = input.direction > 0 ? 'right' : 'left';
} else if (this.vx !== 0) {
// Air drag is much lighter than ground friction, so a thrown cat
// carries its momentum instead of stopping in a body length.
const f = this.grounded ? cfg.friction : cfg.friction * 0.15;
const drop = f * dt;
this.vx = Math.abs(this.vx) <= drop ? 0 : this.vx - Math.sign(this.vx) * drop;
}
const target = this.x + this.vx * dt;
const bounded = this.boundX(target, cfg, bounds);
if (!cfg.wrapEdges && bounded !== target) this.vx = 0;
this.x = bounded;
/* --- vertical --- */
if (input.jump && this.grounded) {
this.vy = cfg.jumpVelocity;
this.grounded = false;
}
if (!this.grounded) {
this.vy -= cfg.gravity * dt;
this.y += this.vy * dt;
if (this.y <= 0) {
const impact = -this.vy;
this.y = 0;
this.vy = 0;
this.grounded = true;
this.squash = clamp(impact / 900, 0, 1);
}
}
if (this.squash > 0) this.squash = Math.max(0, this.squash - dt * 5);
}
rebound(cfg: PhysicsConfig, bounds: PhysicsBounds): void {
this.x = this.boundX(this.x, cfg, bounds);
}
groundY(bounds: PhysicsBounds): number {
return bounds.viewH - bounds.floorHeight;
}
private boundX(value: number, cfg: PhysicsConfig, bounds: PhysicsBounds): number {
if (bounds.viewW <= 0) return value;
const half = (bounds.spriteW * bounds.scale) / 2;
if (cfg.wrapEdges) {
const wrapWidth = bounds.viewW + bounds.spriteW * bounds.scale;
return ((((value + half) % wrapWidth) + wrapWidth) % wrapWidth) - half;
}
const lo = half;
const hi = bounds.viewW - half;
if (hi <= lo) return bounds.viewW / 2;
return clamp(value, lo, hi);
}
}
+3
View File
@@ -0,0 +1,3 @@
export namespace Physis {
export class Engine {}
}
@@ -0,0 +1,24 @@
import Vector2 from '$lib/vector';
import Rigidbody2D from '../rigidbody/rigidbody2d';
export class AABB {
private size: Vector2 = new Vector2();
private halfSize: Vector2 = new Vector2();
private rigidbody: Rigidbody2D = new Rigidbody2D();
constructor(min?: Vector2, max?: Vector2) {
if (min !== undefined && max !== undefined) this.size = new Vector2(max).sub(min);
this.halfSize = new Vector2(this.size.mul(0.5));
}
public get getMin(): Vector2 {
return new Vector2(this.rigidbody.Position).sub(this.halfSize);
}
public get getMax(): Vector2 {
return new Vector2(this.rigidbody.Position).add(this.halfSize);
}
}
export default AABB;
@@ -0,0 +1,53 @@
import Vector2 from '$lib/vector';
import Rigidbody2D from '../rigidbody/rigidbody2d';
export class Box2D {
private size: Vector2 = new Vector2();
private halfSize: Vector2 = new Vector2();
private rigidbody: Rigidbody2D = new Rigidbody2D();
constructor();
constructor(min?: Vector2, max?: Vector2) {
if (min !== undefined && max !== undefined) this.size = new Vector2(max).sub(min);
this.halfSize = new Vector2(this.size.mul(0.5));
}
public get getMin(): Vector2 {
return new Vector2(this.rigidbody.Position).sub(this.halfSize);
}
public get getMax(): Vector2 {
return new Vector2(this.rigidbody.Position).add(this.halfSize);
}
public get getVectices(): Vector2[] {
const min: Vector2 = this.getMin;
const max: Vector2 = this.getMax;
const vertices: Vector2[] = [
new Vector2(min.x, min.y),
new Vector2(min.x, max.y),
new Vector2(max.x, min.y),
new Vector2(max.x, max.y)
];
if (this.rigidbody.Rotation != 0.0) {
for (const vert of vertices) {
//TODO Rotate Vert around this.rigidbody.getPosition by this.rigidbody.getRotation;
}
}
return vertices;
}
public get getRigidbody(): Rigidbody2D {
return this.rigidbody;
}
public get getHalfSize(): Vector2 {
return this.halfSize;
}
}
export default Box2D;
@@ -0,0 +1,17 @@
import type Vector2 from '$lib/vector';
import Rigidbody2D from '../rigidbody/rigidbody2d';
class Circle {
private radius: number = 1.0;
private rigidbody: Rigidbody2D = new Rigidbody2D();
public get Radius(): number {
return this.radius;
}
public get Center(): Vector2 {
return this.rigidbody.Position;
}
}
export default Circle;
@@ -0,0 +1,9 @@
import Vector2 from "$lib/vector";
class Collider2D {
protected offset: Vector2 = new Vector2();
//public abstract getInnertiaTensor(mass: number): number;
}
@@ -0,0 +1,22 @@
import type Vector2 from '$lib/vector';
class Ray2D {
private origin: Vector2;
private direction: Vector2;
constructor(origin: Vector2, direction: Vector2) {
this.origin = origin;
this.direction = direction;
this.direction.normalize();
}
public get Origin(): Vector2 {
return this.origin;
}
public get Direction(): Vector2 {
return this.direction;
}
}
export default Ray2D;
@@ -0,0 +1,26 @@
import Vector2 from '$lib/vector';
class RaycastResult {
private point: Vector2 = new Vector2();
private normal: Vector2 = new Vector2();
private t: number = -1;
private hit: boolean = false;
public init(point: Vector2, normal: Vector2, t: number, hit: boolean) {
this.point.set(point.x, point.y);
this.normal.set(normal.x, normal.y);
this.t = t;
this.hit = hit;
}
public static reset(result: RaycastResult) {
if (result != null) {
result.point.set(Vector2.zero.x, Vector2.zero.y);
result.normal.set(Vector2.zero.x, Vector2.zero.y);
result.t = -1;
result.hit = false;
}
}
}
export default RaycastResult;
@@ -0,0 +1,233 @@
import Line2D from '$lib/shimagic/renderer/line2d';
import Vector2 from '$lib/vector';
import VMath from '$lib/vmath';
import AABB from '../primitives/aabb';
import Box2D from '../primitives/box2d';
import Circle from '../primitives/circle';
import type Ray2D from '../primitives/ray2d';
import RaycastResult from '../primitives/raycast_result';
class IntersectionDetector2D {
public static pointOnLine(point: Vector2, line: Line2D): boolean {
let dy: number = line.getEnd().y - line.getStart().y;
let dx: number = line.getEnd().x - line.getStart().x;
let m: number = dy / dx;
let b = line.getEnd().y - m * line.getEnd().x;
//Check the line equation
return point.y == m * point.x + b;
}
public static pointInCircle(point: Vector2, circle: Circle) {
const circleCenter: Vector2 = circle.Center;
const centerToPoint: Vector2 = new Vector2(point).sub(circleCenter);
return centerToPoint.sqrLength <= circle.Radius * circle.Radius;
}
public static pointInAABB(point: Vector2, aabb: AABB): boolean {
let min: Vector2 = aabb.getMin;
let max: Vector2 = aabb.getMax;
return point.x <= max.x && point.x >= min.x && point.y >= min.y && point.y <= max.y;
}
public static pointInBox2D(point: Vector2, box: Box2D): boolean {
const pointLocal = new Vector2(point);
VMath.rotate(pointLocal, box.getRigidbody.Rotation, box.getRigidbody.Position);
let min: Vector2 = box.getMin;
let max: Vector2 = box.getMax;
return (
pointLocal.x <= max.x &&
pointLocal.x >= min.x &&
pointLocal.y >= min.y &&
pointLocal.y <= max.y
);
}
public static lineAndCircle(line: Line2D, circle: Circle): boolean {
if (this.pointInCircle(line.getStart(), circle) || this.pointInCircle(line.getEnd(), circle))
return true;
const ab: Vector2 = new Vector2(line.getEnd()).sub(line.getStart());
const circleCenter: Vector2 = circle.Center;
const centerToLineStart: Vector2 = new Vector2(circleCenter).sub(line.getStart());
const t: number = centerToLineStart.dot(ab) / ab.dot(ab);
if (t < 0.0 || t > 1.0) return false;
const closestPoint: Vector2 = new Vector2(line.getStart()).add(ab.mul(t));
return this.pointInCircle(closestPoint, circle);
}
public static lineAndAABB(line: Line2D, box: AABB): boolean {
if (this.pointInAABB(line.getStart(), box) || this.pointInAABB(line.getEnd(), box)) return true;
let uVec: Vector2 = new Vector2(line.getEnd()).sub(line.getStart());
uVec.normalize;
uVec.x = !uVec.equals(Vector2.zero) ? 1.0 / uVec.x : 0.0;
uVec.y = !uVec.equals(Vector2.zero) ? 1.0 / uVec.y : 0.0;
const min: Vector2 = box.getMin;
min.sub(line.getStart()).mul(uVec);
const max: Vector2 = box.getMax;
max.sub(line.getStart()).mul(uVec);
const tmin: number = Math.max(Math.min(min.x, max.x), Math.min(min.y, max.y));
const tmax: number = Math.min(Math.max(min.x, max.x), Math.max(min.y, max.y));
if (tmax < 0 || tmin > tmax) {
return false;
}
const t = tmin < 0 ? tmax : tmin;
return t > 0 && t * t < line.lengthSqr();
}
public static lineAndBox2D(line: Line2D, box: Box2D): boolean {
const rotation: number = box.getRigidbody.Rotation;
const center: Vector2 = box.getRigidbody.Position;
const localStart: Vector2 = new Vector2(line.getStart());
const localEnd: Vector2 = new Vector2(line.getEnd());
VMath.rotate(localStart, rotation, center);
VMath.rotate(localEnd, rotation, center);
const localLine: Line2D = new Line2D(localStart, localEnd);
const aabb: AABB = new AABB(box.getMin, box.getMax);
return this.lineAndAABB(localLine, aabb);
}
public static raycast(circle: Circle, ray: Ray2D, result: RaycastResult): boolean;
public static raycast(aabb: AABB, ray: Ray2D, result: RaycastResult): boolean;
public static raycast(box: Box2D, ray: Ray2D, result: RaycastResult): boolean;
public static raycast(
primitive: Circle | AABB | Box2D,
ray: Ray2D,
result: RaycastResult
): boolean {
if (primitive instanceof Circle) {
RaycastResult.reset(result);
const originToCircle: Vector2 = new Vector2(primitive.Center).sub(ray.Origin);
const radiusSqr: number = primitive.Radius * primitive.Radius;
const originToCircleSqr: number = originToCircle.sqrLength;
const a: number = originToCircle.dot(ray.Direction);
const bSqr: number = originToCircleSqr - a * a;
if (radiusSqr - bSqr < 0.0) return false;
const f: number = Math.sqrt(radiusSqr - bSqr);
let t: number = 0;
if (originToCircleSqr < radiusSqr) {
t = a + f;
} else {
t = a - f;
}
if (result != null) {
const point: Vector2 = new Vector2(ray.Origin).add(new Vector2(ray.Direction)).mul(t);
const normal: Vector2 = new Vector2(point).sub(primitive.Center);
normal.normalize();
result.init(point, normal, t, true);
}
return true;
} else if (primitive instanceof AABB) {
RaycastResult.reset(result);
let uVec: Vector2 = ray.Direction;
uVec.normalize;
uVec.x = !uVec.equals(Vector2.zero) ? 1.0 / uVec.x : 0.0;
uVec.y = !uVec.equals(Vector2.zero) ? 1.0 / uVec.y : 0.0;
const min: Vector2 = primitive.getMin;
min.sub(ray.Origin).mul(uVec);
const max: Vector2 = primitive.getMax;
max.sub(ray.Origin).mul(uVec);
const tmin: number = Math.max(Math.min(min.x, max.x), Math.min(min.y, max.y));
const tmax: number = Math.min(Math.max(min.x, max.x), Math.max(min.y, max.y));
if (tmax < 0 || tmin > tmax) {
return false;
}
const t = tmin < 0 ? tmax : tmin;
const hit: boolean = t > 0; //&& t * t < ray.Distance;
if (!hit) return false;
if (result != null) {
const point: Vector2 = new Vector2(ray.Origin).add(new Vector2(ray.Direction).mul(t));
const normal: Vector2 = new Vector2(ray.Origin).sub(point);
normal.normalize();
result.init(point, normal, t, true);
}
return true;
} else {
//TODO: Box2D implementation
RaycastResult.reset(result);
const halfSize: Vector2 = primitive.getHalfSize;
const xAxis: Vector2 = new Vector2(1, 0);
const yAxis: Vector2 = new Vector2(0, 1);
VMath.rotate(xAxis, primitive.getRigidbody.Rotation, Vector2.zero);
VMath.rotate(yAxis, primitive.getRigidbody.Rotation, Vector2.zero);
const p: Vector2 = new Vector2(primitive.getRigidbody.Position).sub(ray.Origin);
const f: Vector2 = new Vector2(xAxis.dot(ray.Direction), yAxis.dot(ray.Direction));
const e: Vector2 = new Vector2(xAxis.dot(p), yAxis.dot(p));
const tArr: number[] = [0, 0, 0, 0];
if (VMath.compare(f.x, 0)) {
if (-e.x - halfSize.x > 0 || -e.x + halfSize.x < 0) {
return false;
}
}
f.x = 0.00001;
tArr[0 * 2 + 0] = e.x + halfSize.x / f.x;
tArr[0 * 2 + 1] = e.x - halfSize.x / f.x;
if (VMath.compare(f.y, 0)) {
if (-e.y - halfSize.y > 0 || -e.y + halfSize.y < 0) {
return false;
}
}
f.y = 0.00001;
tArr[1 * 2 + 0] = e.y + halfSize.y / f.y;
tArr[1 * 2 + 1] = e.x - halfSize.x / f.x;
const tmin: number = Math.max(Math.min(tArr[0], tArr[1]), Math.min(tArr[2], tArr[3]));
const tmax: number = Math.min(Math.max(tArr[0], tArr[1]), Math.max(tArr[2], tArr[3]));
const t = tmin < 0 ? tmax : tmin;
const hit: boolean = t > 0; //&& t * t < ray.Distance;
if (!hit) return false;
if (result != null) {
const point: Vector2 = new Vector2(ray.Origin).add(new Vector2(ray.Direction).mul(t));
const normal: Vector2 = new Vector2(ray.Origin).sub(point);
normal.normalize();
result.init(point, normal, t, true);
}
return true;
}
public static circleAndLine()
}
}
@@ -0,0 +1,24 @@
import Vector2 from '$lib/vector';
class Rigidbody2D {
private position: Vector2 = new Vector2();
private rotation: number = 0.0;
public get Position(): Vector2 {
return this.position;
}
public set setPosition(position: Vector2) {
this.position = position;
}
public get Rotation(): number {
return this.rotation;
}
public set setRotation(rotation: number) {
this.rotation = rotation;
}
}
export default Rigidbody2D;
+228
View File
@@ -0,0 +1,228 @@
import type { ChatterConfig } from './chatter';
export interface RenderInput {
ctx: CanvasRenderingContext2D;
viewW: number;
viewH: number;
groundY: number;
dpr: number;
body: HTMLImageElement;
mirrored: boolean;
x: number;
y: number;
squash: number;
bubble: { img: HTMLImageElement; index: number } | null;
bubbleText: string | null;
charsShown: number;
bubbleTextFrame: number;
scale: number;
showShadow: boolean;
reflectionOpacity: number;
reflectionFade: number;
reflectionTint: string;
bubbleAnchorX: number;
bubbleAnchorY: number;
chatter: ChatterConfig | null;
}
export class CharacterRenderer {
private reflCanvas: HTMLCanvasElement | null = null;
private reflCtx: CanvasRenderingContext2D | null = null;
private reflW = 0;
private reflH = 0;
draw(input: RenderInput): void {
const { ctx, viewW, viewH } = input;
ctx.clearRect(0, 0, viewW, viewH);
const dw = input.body.naturalWidth * input.scale;
const dh = input.body.naturalHeight * input.scale;
const half = dw / 2;
if (input.x + half <= 0 || input.x - half >= viewW) return;
const leftX = Math.round(input.x - half);
const feetY = input.groundY - input.y;
const topY = feetY - dh;
this.drawShadow(input, half);
this.drawReflection(input, leftX, dw, dh);
this.drawBody(input, leftX, feetY, dw, dh, half);
this.drawBubble(input, topY);
}
private drawShadow(input: RenderInput, half: number): void {
if (!input.showShadow) return;
const { ctx, groundY, x, y } = input;
const t = Math.min(Math.max(y / 200, 0), 1);
const rx = half * 0.75 * (1 - t * 0.5);
const ry = Math.max(2, rx * 0.22);
ctx.save();
ctx.globalAlpha = 0.32 * (1 - t * 0.85);
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.ellipse(x, groundY, rx, ry, 0, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
private drawReflection(input: RenderInput, leftX: number, dw: number, dh: number): void {
const { y, reflectionOpacity, reflectionFade, reflectionTint, groundY, dpr } = input;
const heightFade = Math.max(0, 1 - y / (dh * 4));
const alpha = Math.min(Math.max(reflectionOpacity * heightFade, 0), 1);
if (alpha <= 0.01) return;
const rc = this.ensureRefl(dw, dh, dpr);
if (!rc) return;
const pw = this.reflW;
const ph = this.reflH;
rc.save();
rc.translate(input.mirrored ? pw : 0, ph);
rc.scale(input.mirrored ? -1 : 1, -1);
rc.drawImage(input.body, 0, 0, pw, ph);
rc.restore();
rc.globalCompositeOperation = 'source-atop';
rc.fillStyle = reflectionTint;
rc.fillRect(0, 0, pw, ph);
rc.globalCompositeOperation = 'destination-out';
const grad = rc.createLinearGradient(0, 0, 0, ph);
grad.addColorStop(0, 'rgba(0,0,0,0)');
grad.addColorStop(1, `rgba(0,0,0,${Math.min(Math.max(reflectionFade, 0), 1)})`);
rc.fillStyle = grad;
rc.fillRect(0, 0, pw, ph);
rc.globalCompositeOperation = 'source-over';
input.ctx.globalAlpha = alpha;
input.ctx.drawImage(this.reflCanvas!, leftX, Math.round(groundY + input.y), dw, dh);
input.ctx.globalAlpha = 1;
}
private drawBody(
input: RenderInput,
leftX: number,
feetY: number,
dw: number,
dh: number,
half: number
): void {
const { ctx, mirrored, squash, body } = input;
const sx = 1 + squash * 0.22;
const sy = 1 - squash * 0.22;
ctx.save();
ctx.translate(leftX + half, feetY);
ctx.scale(mirrored ? -sx : sx, sy);
ctx.drawImage(body, -half, -dh, dw, dh);
ctx.restore();
}
private drawBubble(input: RenderInput, topY: number): void {
const bf = input.bubble;
if (!bf) return;
const { ctx, scale, bubbleAnchorX, bubbleAnchorY, x, chatter } = input;
const bw = bf.img.naturalWidth * scale;
const bh = bf.img.naturalHeight * scale;
const ax = x + bubbleAnchorX * scale;
const ay = topY - bubbleAnchorY * scale;
const bx = Math.round(ax - bw / 2);
const by = Math.round(ay - bh);
ctx.drawImage(bf.img, bx, by, bw, bh);
if (!input.bubbleText || !chatter) return;
if (bf.index < input.bubbleTextFrame) return;
drawBubbleText(ctx, input.bubbleText, bx, by, bw, bh, scale, input.charsShown, chatter);
}
private ensureRefl(wCss: number, hCss: number, dpr: number): CanvasRenderingContext2D | null {
const pw = Math.max(1, Math.round(wCss * dpr));
const ph = Math.max(1, Math.round(hCss * dpr));
if (!this.reflCanvas) {
this.reflCanvas = document.createElement('canvas');
this.reflCtx = this.reflCanvas.getContext('2d');
}
if (!this.reflCtx) return null;
if (this.reflW !== pw || this.reflH !== ph) {
this.reflCanvas.width = pw;
this.reflCanvas.height = ph;
this.reflW = pw;
this.reflH = ph;
}
this.reflCtx.setTransform(1, 0, 0, 1, 0, 0);
this.reflCtx.globalCompositeOperation = 'source-over';
this.reflCtx.globalAlpha = 1;
this.reflCtx.clearRect(0, 0, pw, ph);
this.reflCtx.imageSmoothingEnabled = false;
return this.reflCtx;
}
}
function wrapText(c: CanvasRenderingContext2D, text: string, maxWidth: number): string[] {
const words = text.split(/\s+/).filter(Boolean);
const lines: string[] = [];
let line = '';
for (const word of words) {
const candidate = line ? `${line} ${word}` : word;
if (c.measureText(candidate).width <= maxWidth) line = candidate;
else {
if (line) lines.push(line);
line = word;
}
}
if (line) lines.push(line);
return lines;
}
function drawBubbleText(
c: CanvasRenderingContext2D,
text: string,
bx: number,
by: number,
bw: number,
bh: number,
scale: number,
charsShown: number,
chatter: ChatterConfig
): void {
const padLeft = (chatter.padding?.left ?? 8) * scale;
const padRight = (chatter.padding?.right ?? 8) * scale;
const padBottom = (chatter.padding?.bottom ?? 8) * scale;
const textTop = (chatter.textTop ?? chatter.padding?.top ?? 8) * scale;
const maxW = bw - padLeft - padRight;
const maxH = bh - textTop - padBottom;
if (maxW <= 0 || maxH <= 0) return;
const size = chatter.fontSize ?? 11;
const lineHeight = size * (chatter.lineHeight ?? 1.2);
c.save();
c.font = `${size}px ${chatter.fontFamily ?? 'monospace'}`;
c.textBaseline = 'top';
c.textAlign = chatter.align === 'left' ? 'left' : 'center';
c.fillStyle = chatter.color ?? '#1a1a1a';
const lines = wrapText(c, text, maxW);
const x = chatter.align === 'left' ? bx + padLeft : bx + bw / 2;
const y0 = by + textTop;
let cursor = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const visible = Math.max(0, Math.min(line.length, charsShown - cursor));
if (visible <= 0) break;
c.fillText(line.slice(0, visible), x, y0 + i * lineHeight);
cursor += line.length;
if (visible < line.length) break;
}
c.restore();
}
+25
View File
@@ -0,0 +1,25 @@
import Vector2 from '$lib/vector';
class Line2D {
private from: Vector2;
private to: Vector2;
constructor(from: Vector2, to: Vector2) {
this.from = from;
this.to = to;
}
public getStart(): Vector2 {
return this.from;
}
public getEnd(): Vector2 {
return this.to;
}
public lengthSqr(): number {
return new Vector2(this.to).sub(this.from).sqrLength;
}
}
export default Line2D;
+131
View File
@@ -0,0 +1,131 @@
import type Vector2 from '$lib/vector';
class Renderer {
private gl: WebGL2RenderingContext;
private posBuffer!: WebGLBuffer;
private program!: WebGLProgram;
private drawMode: DrawMode = DrawMode.TEX;
constructor(canvas: HTMLCanvasElement) {
let context = canvas.getContext('webgl2');
if (!context) throw new Error(`Failed to get webgl2 context from ${canvas}`);
this.gl = context;
}
public async init() {
try {
const vert: WebGLShader = await this.loadShader(
this.gl,
'src/lib/shimeji/renderer/shaders/vertex_shader.vert',
this.gl.VERTEX_SHADER
);
const frag: WebGLShader = await this.loadShader(
this.gl,
'src/lib/shimeji/renderer/shaders/fragment_shader.frag',
this.gl.FRAGMENT_SHADER
);
const program = this.gl.createProgram();
this.program = program;
this.gl.attachShader(program, vert);
this.gl.attachShader(program, frag);
this.gl.linkProgram(program);
if (!this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) {
console.error(this.gl.getProgramInfoLog(program));
this.gl.deleteProgram(program);
throw new Error(`Failed to link program to webgl2 context ${program}`);
}
const pos = this.gl.createBuffer();
this.posBuffer = pos;
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, pos);
this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
let resUniLoc = this.gl.getUniformLocation(program, 'u_resolution');
this.gl.clearColor(0, 0, 0, 0);
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
this.gl.useProgram(program);
this.gl.enableVertexAttribArray(0);
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, pos);
this.gl.vertexAttribPointer(0, 2, this.gl.FLOAT, false, 0, 0);
this.gl.uniform2f(resUniLoc, this.gl.canvas.width, this.gl.canvas.height);
} catch (error) {
console.log(error);
this.gl.VERTEX_SHADER;
}
}
private async loadShader(
gl: WebGL2RenderingContext,
path: string,
type: typeof gl.VERTEX_SHADER | typeof gl.FRAGMENT_SHADER
) {
const response = await fetch(path);
if (!response.ok) throw new Error(`failed to fetch the shader file ${response}`);
const data = await response.text();
const shader = gl.createShader(type);
if (!shader) throw new Error(`Failed to create the shader ${shader}`);
gl.shaderSource(shader, data);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error(gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
throw new Error(`Failed to compile the shader ${shader}`);
}
return shader;
}
public UpdateBounds(width: number, height: number): void {
this.gl.viewport(0, 0, width, height);
}
/**
* Set the draw mode to one of the enum values
* @param {DrawMode} mode
* @returns {void}
*/
public set SetDrawMode(mode: DrawMode) {}
public Draw(pos: Vector2, size: number): void {
//this.gl.clearColor(0, 0, 0, 0);
// this.gl.clear(this.gl.COLOR_BUFFER_BIT);
let x1 = pos.x - size;
let x2 = pos.x + size;
let y1 = pos.y + size;
let y2 = pos.y - size;
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.posBuffer);
this.gl.bufferData(
this.gl.ARRAY_BUFFER,
new Float32Array([x1, y1, x2, y1, x2, y2, x1, y1, x1, y2, x2, y2]),
this.gl.DYNAMIC_DRAW
);
var primitiveType = this.gl.TRIANGLES;
var offset = 0;
var count = 6;
this.gl.drawArrays(primitiveType, offset, count);
}
}
enum DrawMode {
TEX = 0,
WIRE = 1,
VERT = 2
}
export default Renderer;
@@ -0,0 +1,10 @@
#version 300 es
precision mediump float;
out vec4 color;
in vec4 v_color;
void main() {
color = vec4(1.0, 1.0, 1.0, 1.0);
}
@@ -0,0 +1,16 @@
#version 300 es
layout ( location = 0 ) in vec2 a_position;
uniform vec2 u_resolution;
out vec4 v_color;
void main() {
vec2 zeroToOne = a_position / u_resolution;
vec2 zeroToTwo = zeroToOne * 2.0;
vec2 clipSpace = zeroToTwo - 1.0;
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
//gl_Position = vec4(a_position, 0, 1);
gl_PointSize = 5.0;
v_color = vec4(a_position.xy, 0.0, 1.0);
}
+174
View File
@@ -0,0 +1,174 @@
import type Vector2 from '$lib/vector';
export namespace WebG {
export class Engine {
private _GL: WebGL2RenderingContext;
private _Program!: WebGLProgram;
private _Shaders: Array<WebGLShader> = Array<WebGLShader>();
private _DrawMode: EngineDrawMode = EngineDrawMode.TEXTURE;
private _PosBuffer!: WebGLBuffer;
constructor(gl: WebGL2RenderingContext) {
this._GL = gl;
}
/**
* Factory method: Loads all shaders compiles and links them
* @async
* @public
* @param config - Engine configuration
* @returns Promise<Engine> that resolver when the engine is done initializing\
*/
public static async Initialize(config: EngineConfig) {
const GL = config.canvas.getContext('webgl2');
if (!GL) throw new Error('WebGL2 not supported!');
const shaderSources: ShaderSrc[] = [];
try {
const [vertSource, fragSource] = await Promise.all([
fetch(config.vertexShaderUrl).then((r) => r.text()),
fetch(config.fragmentShaderUrl).then((r) => r.text())
]);
shaderSources.push(
{ type: GL.VERTEX_SHADER, src: vertSource, url: config.vertexShaderUrl },
{ type: GL.FRAGMENT_SHADER, src: fragSource, url: config.fragmentShaderUrl }
);
} catch (error) {
throw new Error(`${error} Filed to fetch the shaders`);
}
const ENGINE = new Engine(GL);
ENGINE._Program = GL.createProgram();
if (!ENGINE._Program) throw new Error(`Failed to create a new program ${ENGINE._Program}`);
for (const { type, src, url } of shaderSources) {
const shader = ENGINE.compileShader(type, src, url);
ENGINE._Shaders.push(shader);
GL.attachShader(ENGINE._Program, shader);
}
ENGINE._GL.linkProgram(ENGINE._Program);
if (!GL.getProgramParameter(ENGINE._Program, GL.LINK_STATUS))
throw new Error(
`Failed to link program ${ENGINE._Program} - Logs: ${GL.getProgramInfoLog(ENGINE._Program)}`
);
const pos = GL.createBuffer();
ENGINE._PosBuffer = pos;
ENGINE._GL.bindBuffer(ENGINE._GL.ARRAY_BUFFER, pos);
GL.enableVertexAttribArray(0);
GL.bindBuffer(GL.ARRAY_BUFFER, pos);
GL.vertexAttribPointer(0, 2, GL.FLOAT, false, 0, 0);
GL.clearColor(0, 0, 0, 0);
GL.clear(GL.COLOR_BUFFER_BIT);
GL.viewport(0, 0, GL.canvas.width, GL.canvas.height);
GL.useProgram(ENGINE._Program);
let resUniLoc = GL.getUniformLocation(ENGINE._Program, 'u_resolution');
GL.uniform2f(resUniLoc, GL.canvas.width, GL.canvas.height);
return ENGINE;
}
/**
* Compile a single shader from source
* @param type - WebGL Shader type (e.g., gl.VERTEX_SHADER)
* @param src - Source code in GLSL
* @param url - Source url - used for debbugging (optional)
* @returns - Compiled {WebGLShader}
* @private
*/
private compileShader(type: number, src: string, url?: string) {
const shader = this._GL.createShader(type);
if (!shader) throw new Error(`Failed to create a new shader of type ${type}`);
this._GL.shaderSource(shader, src);
this._GL.compileShader(shader);
if (!this._GL.getShaderParameter(shader, this._GL.COMPILE_STATUS)) {
this._GL.deleteShader(shader);
throw new Error(
`Failed to compile shader from source ${src} located at ${url || 'unknown'} - Logs: ${this._GL.getShaderInfoLog(shader)}`
);
}
return shader;
}
public get GL(): WebGL2RenderingContext {
return this._GL;
}
public get Program(): WebGLProgram {
return this._Program;
}
public setDrawMode(mode: EngineDrawMode) {
this._DrawMode = mode;
}
public draw(args: DrawCallArgs) {
const positions: Array<number> = [];
for (const v of args.vertices) {
positions.push(v.x, v.y);
}
this._GL.bindBuffer(this._GL.ARRAY_BUFFER, this._PosBuffer);
this._GL.bufferData(this._GL.ARRAY_BUFFER, new Float32Array(positions), this._GL.STATIC_DRAW);
this._GL.drawArrays(this._DrawMode, 0, args.vertices.length);
}
public destroy() {
for (const shader of this._Shaders) {
this._GL.detachShader(this._Program, shader);
this._GL.deleteShader(shader);
}
this._GL.deleteBuffer(this._PosBuffer);
this._GL.deleteProgram(this._Program);
}
}
/**
* Enum for setting the draw mode of the engine
* @enum {0} - Texture, the default form of rendering, either a texture or a color
*/
export enum EngineDrawMode {
TEXTURE = 5, //WebGL2RenderingContext.TRIANGLE_STRIP
WIREFRAME = 2, //WebGL2RenderingContext.LINES
VERTEX = 0 //WebGL2RenderingContext.POINTS
}
export interface DrawCallArgs {
vertices: Array<Vector2>;
}
interface ShaderSrc {
type: number;
src: string;
url: string;
}
/**
* {Engine} class factory method dependency that passes all the nesesary data for engine initialization
* @param canvas - A {HTMLCanvasElement}
* @param vertexShaderUrl - A string url to the primary vertex shader file
* @param fragmentShaderUrl - A string utl to the primary fragment shader file
* @param attributes - Shader attributes passed into and mapped to the program
* @param uniforms - Shader uniforms passed into and mapped to the program
*/
export interface EngineConfig {
canvas: HTMLCanvasElement;
vertexShaderUrl: string;
fragmentShaderUrl: string;
attributes?: Record<string, number>;
uniforms?: Record<string, number>;
}
}
+97
View File
@@ -0,0 +1,97 @@
const SOUND_RE = /\/sounds\/([^/]+)\/[^/]+\.(wav|mp3|ogg)$/i;
const files = import.meta.glob('$lib/assets/character/sounds/**/*.{wav,mp3,ogg}', {
eager: true,
query: '?url',
import: 'default'
}) as Record<string, string>;
export interface SoundPack {
name: string;
buffers: AudioBuffer[];
}
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
function soundPackUrls(): Record<string, string[]> {
const groups: Record<string, [string, string][]> = {};
for (const [path, url] of Object.entries(files)) {
const m = SOUND_RE.exec(path);
if (!m) continue;
const name = m[1].toLowerCase();
(groups[name] ??= []).push([path, url]);
}
const out: Record<string, string[]> = {};
for (const [name, entries] of Object.entries(groups)) {
out[name] = entries.sort(([a], [b]) => collator.compare(a, b)).map(([, url]) => url);
}
return out;
}
export async function loadSoundPacks(ctx: AudioContext): Promise<Record<string, SoundPack>> {
const urls = soundPackUrls();
const out: Record<string, SoundPack> = {};
await Promise.all(
Object.entries(urls).map(async ([name, list]) => {
const buffers: AudioBuffer[] = [];
for (const url of list) {
try {
const res = await fetch(url);
const raw = await res.arrayBuffer();
buffers.push(await ctx.decodeAudioData(raw));
} catch (err) {
console.warn(`[sound] failed to load "${url}"`, err);
}
}
if (buffers.length) out[name] = { name, buffers };
})
);
return out;
}
export class SoundPlayer {
private cursor: Record<string, number> = {};
private muted = false;
constructor(
private ctx: AudioContext,
private packs: Record<string, SoundPack>
) {}
has(name: string): boolean {
return !!this.packs[name];
}
setMuted(muted: boolean) {
this.muted = muted;
}
isMuted(): boolean {
return this.muted;
}
play(name: string, volume = 1): void {
if (this.muted) return;
const pack = this.packs[name];
if (!pack || !pack.buffers.length) return;
if (this.ctx.state === 'suspended') void this.ctx.resume();
const i = (this.cursor[name] ?? 0) % pack.buffers.length;
this.cursor[name] = i + 1;
const src = this.ctx.createBufferSource();
src.buffer = pack.buffers[i];
const gain = this.ctx.createGain();
gain.gain.value = Math.max(0, Math.min(1, volume));
src.connect(gain).connect(this.ctx.destination);
src.start();
}
}
+211
View File
@@ -0,0 +1,211 @@
import type { Facing } from './types';
export type { Facing };
const files = import.meta.glob('$lib/assets/character/states/**/*.png', {
eager: true,
query: '?url',
import: 'default'
}) as Record<string, string>;
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
/** Matches states/<name>/<file>.png OR states/<name>/<side>/<file>.png */
const STATE_RE = /\/states\/([^/]+)\/(?:(left|right)\/)?[^/]+\.png$/i;
export interface StateSide {
frames: string[];
/** True if these frames must be drawn flipped. */
mirrored: boolean;
}
export interface StatePack {
name: string;
fps: number;
left: StateSide;
right: StateSide;
/** Reference speed in px/s. When set, playback scales with |vx| / speed. */
speed?: number;
/** If true, loops. If false, holds on the last frame after one pass. */
loop: boolean;
}
export interface StateConfig {
fps?: number;
speed?: number;
loop?: boolean;
}
export type StateConfigMap = Record<string, StateConfig>;
export const STATE_CONFIG: StateConfigMap = {
idle: { fps: 6 },
walk: { fps: 8, speed: 120 },
run: { fps: 12, speed: 280 },
jump: { fps: 8, loop: false },
held: { fps: 8 },
falling: { fps: 8 },
landing: { fps: 8, loop: false },
love: { fps: 8 },
drink: { fps: 8, loop: false },
play: { fps: 8, loop: false },
sleep: { fps: 8, loop: false }
};
export function loadStates(config: StateConfigMap = {}): Record<string, StatePack> {
const merged: StateConfigMap = { ...STATE_CONFIG, ...config };
const grouped = new Map<
string,
{
left: Array<[string, string]>;
right: Array<[string, string]>;
flat: Array<[string, string]>;
}
>();
for (const [path, url] of Object.entries(files)) {
const m = STATE_RE.exec(path);
if (!m) continue;
const name = m[1].toLowerCase();
const side = m[2]?.toLowerCase();
let bucket = grouped.get(name);
if (!bucket) {
bucket = { left: [], right: [], flat: [] };
grouped.set(name, bucket);
}
if (side === 'left') bucket.left.push([path, url]);
else if (side === 'right') bucket.right.push([path, url]);
else bucket.flat.push([path, url]);
}
const out: Record<string, StatePack> = {};
for (const [name, buckets] of grouped) {
const sortUrls = (arr: Array<[string, string]>) =>
arr.sort(([a], [b]) => collator.compare(a, b)).map(([, url]) => url);
const leftUrls = sortUrls(buckets.left);
const rightUrls = sortUrls(buckets.right);
const flatUrls = sortUrls(buckets.flat);
const cfg = merged[name] ?? {};
let left: StateSide;
let right: StateSide;
if (leftUrls.length || rightUrls.length) {
if (leftUrls.length && rightUrls.length) {
left = { frames: leftUrls, mirrored: false };
right = { frames: rightUrls, mirrored: false };
} else if (leftUrls.length) {
left = { frames: leftUrls, mirrored: false };
right = { frames: leftUrls, mirrored: true };
} else {
right = { frames: rightUrls, mirrored: false };
left = { frames: rightUrls, mirrored: true };
}
} else if (flatUrls.length) {
left = { frames: flatUrls, mirrored: true };
right = { frames: flatUrls, mirrored: false };
} else {
continue;
}
out[name] = {
name,
fps: cfg.fps ?? 8,
left,
right,
speed: cfg.speed,
loop: cfg.loop ?? true
};
}
return out;
}
export function collectStateUrls(packs: Record<string, StatePack>): string[] {
const out = new Set<string>();
for (const pack of Object.values(packs)) {
for (const url of pack.left.frames) out.add(url);
for (const url of pack.right.frames) out.add(url);
}
return [...out];
}
/* ------------------------------------------------------------------ */
/* State resolution */
/* ------------------------------------------------------------------ */
export type InteractionState = 'free' | 'held' | 'falling' | 'landing' | 'petted';
export interface StateContext {
interaction: InteractionState;
grounded: boolean;
speed: number;
/** Active need-action state name (e.g. 'drink'), or null. */
needAction: string | null;
}
export interface ResolverConfig {
idleThreshold: number;
runThreshold: number;
}
/** Interaction-state → state-pack-name overrides, in priority order. */
const INTERACTION_MAP: Array<[InteractionState, string]> = [
['held', 'held'],
['falling', 'falling'],
['landing', 'landing'],
['petted', 'love']
];
export function resolveStateName(
ctx: StateContext,
cfg: ResolverConfig,
packs: Record<string, StatePack>
): string {
for (const [interactionState, packName] of INTERACTION_MAP) {
if (ctx.interaction === interactionState && packs[packName]) return packName;
}
if (ctx.needAction && packs[ctx.needAction]) return ctx.needAction;
if (!ctx.grounded && packs.jump) return 'jump';
if (ctx.speed >= cfg.runThreshold && packs.run) return 'run';
if (ctx.speed >= cfg.idleThreshold && packs.walk) return 'walk';
return 'idle';
}
/* ------------------------------------------------------------------ */
/* Animation clock */
/* ------------------------------------------------------------------ */
export class StateClock {
private lastName = '';
private elapsed = 0;
update(dt: number, name: string, pack: StatePack | undefined, speed: number): void {
if (name !== this.lastName) {
this.lastName = name;
this.elapsed = 0;
return;
}
if (!pack) return;
const rate = pack.speed && pack.speed > 0 ? Math.min(Math.max(speed / pack.speed, 0.25), 3) : 1;
this.elapsed += dt * rate;
}
get time(): number {
return this.elapsed;
}
frameIndex(pack: StatePack, side: StateSide): number {
const count = side.frames.length;
if (!count) return 0;
const raw = Math.floor(this.elapsed * pack.fps);
return pack.loop ? raw % count : Math.min(raw, count - 1);
}
}
+36
View File
@@ -0,0 +1,36 @@
export type Facing = 'left' | 'right';
export type AnimName = 'idle' | 'walk' | 'run' | 'jump';
export interface Clip {
frames: string[];
fps: number;
speed?: number;
}
export interface FacingClips {
mirrored: boolean;
idle: Clip;
walk: Clip;
run?: Clip;
jump?: Clip;
}
export type CharacterSprites = Record<Facing, FacingClips>;
export interface BubblePack {
name: string;
frames: string[];
fps: number;
duration: number;
}
export interface ActionPack {
name: string;
frames: string[];
fps: number;
}
export interface PhysicsInput {
direction: -1 | 0 | 1;
jump: boolean;
}
Executable → Regular
+110 -58
View File
@@ -1,68 +1,80 @@
import { COMMANDS, GROUP, PASSWD, type CommandArgs, type ICommand, type Result } from './static';
import { VirtualFS } from './fs';
import { Terminal, type PrintData } from '../terminal/terminal';
import { Stack } from '../stack';
import { Terminal, type PrintData } from '../terminal/terminal';
import {
COMMANDS,
type CommandArgs,
type CommandResultData,
type ICommand
} from './commandRegistry';
import { GROUP, type Group } from './etc/groupData';
import { PASSWD, type User } from './etc/userData';
import { VirtualFS, type TreeNode } from './fs';
import type { KeybindInhibitor } from './keybindInhibitor';
import { ExitCode } from './metadata';
import { Process } from './process';
export type Permission = {
r: boolean;
w: boolean;
x: boolean;
};
export type BashInitArgs = {
stdio?: Terminal;
user: User;
fs: any;
};
export type TimeStamps = {
modified: Date;
changed: Date;
accessed: Date;
};
// TODO: Finish this
// TODO: Change into a type instead of an enum for performance (low priority)
export enum ExitCode {
SUCCESS = 0,
ERROR = 1
export enum Signal {
SIGINT,
SIGKILL
}
export type User = {
username: string;
passwd: string; //HASHED PASSWORD //TODO: Make a formated type
readonly uid: number; // Normal user 1000+ System user 1-999 root - 0 //TODO: Make a formated type
readonly gid: number; // Primary group | 'Users' 1000 - Others - 1000+ root - 0 //TODO: Make a formated type
home: string; //TODO: Make a formated type
history: string[];
cwd?: number; //TODO: Make a formated type
pwd?: number; //TODO: Make a formated type
export type BashInitArgs = {
io?: Terminal;
fs: Map<number, TreeNode>;
user: { username: string; password: string };
};
export type Group = {
groupname: string;
gid: number; // Primary group 'Users' 1000 - Others - 1000+ root - 0
members: number[]; //TODO: Make a formated type UID
export type Result = {
exitCode: ExitCode;
path: number; //the inode of the place that the command was executed in
resultData?: CommandResultData;
};
export class Bash {
private vfs: VirtualFS;
private _passwd: User[];
private _instances: Stack<User>;
private _group: Group[];
private _terminal!: Terminal;
private user: User;
private readonly vfs: VirtualFS;
private readonly _passwd: User[];
private readonly _group: Group[];
private readonly _terminal!: Terminal;
private readonly _commands: Record<string, ICommand>;
private _userInstances: Stack<User>;
private user: User;
private _process?: Process;
constructor(args: BashInitArgs) {
this.user = args.user;
this._commands = COMMANDS;
this._passwd = PASSWD;
this._group = GROUP;
this._terminal = args.stdio!;
this._instances = new Stack<User>();
this._userInstances = new Stack<User>();
this._terminal = args.io!;
this.vfs = new VirtualFS({ fs: args.fs, user: args.user });
const loginResult = this.userLogin(args.user.username, args.user.password);
if (loginResult == ExitCode.ERROR)
this._terminal.throwExeption(
`Failed to initialize bash instance - access denied for user ${args.user.username}`,
ExitCode.ERROR
);
this.user = this._userInstances.peek()!;
this.vfs = new VirtualFS({ fs: args.fs, user: this.user });
}
private _initNewUserSession(user: User): User {
if (!this._passwd.includes(user))
this._terminal.throwExeption(
`user not found under the name ${user.username}`,
ExitCode.ERROR
);
this._userInstances.push(user);
return user;
}
private async _initNewProcess(command: ICommand, args: CommandArgs) {
this._process = new Process(this, this.user.uid, 'TEMP PROCESS NAME', command, args);
//this._terminal.isProcessActive = true;
}
private _appendNewResult(inode: number, output: any, cmd: string) {
@@ -71,7 +83,7 @@ export class Bash {
output: output,
cmd: cmd
};
console.log(data);
console.log(this.vfs.formatPath(this.vfs.getPathByInode(inode)), 'TEST TEST !@#');
this._terminal.PrintOutput(data);
}
@@ -85,6 +97,10 @@ export class Bash {
}
}
clearTerminal(): void {
this._terminal.clearTerminal();
}
getCwd(): number {
return this.vfs.cwd;
}
@@ -101,6 +117,19 @@ export class Bash {
return this.vfs;
}
getProcess(): Process | ExitCode.ERROR {
if (this._process) {
return this._process;
}
return ExitCode.ERROR;
}
getProcessKeybindInhibitor(): KeybindInhibitor | null {
if (this._process) {
return this._process.getKeybindInhibitor();
} else return null;
}
getTerminalWidth(): number {
return this._terminal.getTerminalWidth();
}
@@ -110,25 +139,38 @@ export class Bash {
}
hasSudoPerms(uid: number): boolean {
return this._group[1].members.includes(uid);
return this._group[0].members.includes(uid);
}
executeCommand(commandName: string, args: CommandArgs): void {
async executeCommand(commandName: string, args: CommandArgs): Promise<Result> {
let result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd() };
const command = this._commands[commandName];
const command: ICommand = this._commands[commandName];
if (!command) this.throwError(result);
if (command.root) {
if (this.hasSudoPerms(this.user.uid)) {
let out: Result = command.method.call(this, args);
await this._initNewProcess(command, args);
if (!this._process) throw new Error('failed to init new process');
const out: Result = await this._process.getResult();
this._appendNewResult(this.getCwd(), out, this.user.history[0]);
}
this.throwError(result);
}
let out: Result = command.method.call(this, args);
await this._initNewProcess(command, args);
if (!this._process) throw new Error('failed to init new process');
const out: Result = await this._process.getResult();
console.log(out);
this._appendNewResult(out.path, out.data?.data, this.user.history[0]);
this._appendNewResult(out.path, out.resultData?.data, this.user.history[0]);
return out;
}
static testMethod() {
//
}
throwError(result: Result): void {
@@ -140,14 +182,24 @@ export class Bash {
}
userLogout() {
this._instances.pop();
if (this._instances.size() === 0) {
this._userInstances.pop();
if (this._userInstances.size() === 0) {
//TODO: Implement system logout
} else {
//this.changeUser(this._instances.peek()!);
}
}
userLogin(username: string, passwd: string): ExitCode {
const user: User | undefined = this._passwd.find((user) => user.username === username);
if (user && user.passwd === passwd) {
this._initNewUserSession(user);
return ExitCode.SUCCESS;
}
return ExitCode.ERROR;
}
formatBytes(bytes: number, dPoint?: number, pow: 1024 | 1000 = 1024): string {
if (!+bytes) return '0';
+10 -58
View File
@@ -1,9 +1,13 @@
import { Bash, ExitCode, type Group, type User } from './bash';
import { ls } from './commands/ls';
import type { KeyBind } from '../terminal/keybindRegistry';
import type { Bash, Result } from './bash';
import { cd } from './commands/cd';
import { clear } from './commands/clear';
import { ls } from './commands/ls';
import { testProcess } from './commands/testAsync';
export type ICommand = {
method: (this: Bash, args: CommandArgs) => Result;
keybinds?: Map<KeyBind, () => any>;
flags: string[];
help: string;
root: boolean;
@@ -14,69 +18,17 @@ export type CommandArgs = {
args: string[];
};
export type resultData = {
export type CommandResultData = {
cmd: string; //the string that contains the shorthand for the command that was executed - used in a switch statement in parseResult
data: any; //the data that the commmand may have returned like TreeNodes[] from ls
args?: CommandArgs;
};
export type Result = {
exitCode: ExitCode;
path: number; //the inode of the place that the command was executed in
data?: resultData;
};
export const GROUP: Group[] = [
{
groupname: 'sudo',
gid: 69,
members: [0, 1001]
},
{
groupname: 'users',
gid: 984,
members: [1001, 1002]
}
] as const;
export const PASSWD: User[] = [
{
username: 'root',
passwd: '123',
uid: 0,
gid: 0,
home: '/',
history: [] //TODO: Delete this and declare a new history array when logging the user in.
},
{
username: 'admin',
passwd: '456',
uid: 1000,
gid: 1000,
home: '/home/admin',
history: [] //TODO: Delete this and declare a new history array when logging the user in.
},
{
username: 'user',
passwd: '789',
uid: 1001,
gid: 1000,
home: '/home/user',
history: [] //TODO: Delete this and declare a new history array when logging the user in.
},
{
username: 'kamil',
passwd: '000',
uid: 1002,
gid: 1000,
home: '/home/kamil',
history: [] //TODO: Delete this and declare a new history array when logging the user in.
}
];
export const COMMANDS = {
cd,
ls
ls,
clear,
testProcess
} as const satisfies Record<string, ICommand>;
/* //export const commands {
+4 -2
View File
@@ -1,6 +1,7 @@
import { ExitCode, type Bash } from '../bash';
import type { Bash, Result } from '../bash';
import type { CommandArgs, ICommand } from '../commandRegistry';
import { Type, type TreeNode } from '../fs';
import type { CommandArgs, ICommand, Result } from '../static';
import { ExitCode } from '../metadata';
export const cmd_cd = function (this: Bash, args: CommandArgs): Result {
let result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd() };
@@ -21,6 +22,7 @@ export const cmd_cd = function (this: Bash, args: CommandArgs): Result {
if (args.args[0] === '-') {
[this.getFs().cwd, this.getFs().pwd] = [this.getFs().pwd, this.getFs().cwd];
result.exitCode = ExitCode.SUCCESS;
return result;
}
+17
View File
@@ -0,0 +1,17 @@
import { type Bash, type Result } from "../bash";
import type { CommandArgs, ICommand } from "../commandRegistry";
import { ExitCode } from "../metadata";
export const cmd_clear = function(this: Bash, args: CommandArgs): Result {
let result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd() };
this.clearTerminal();
result.exitCode = ExitCode.SUCCESS;
return result;
}
export const clear: ICommand = {
method: cmd_clear,
flags: [] as string[],
help: 'PATH TO HELP.md',
root: false
};
+129 -105
View File
@@ -1,7 +1,8 @@
import { Bash, ExitCode, type Permission, type TimeStamps } from '../bash';
import { Type, type NodePerms, type TreeNode } from '../fs';
import type { Bash, Result } from '../bash';
import type { CommandArgs, CommandResultData, ICommand } from '../commandRegistry';
import { Type, VirtualFS, type NodePerms, type TreeNode } from '../fs';
import { ExitCode, type Permission } from '../metadata';
import { Sort, SortNodeBy } from '../sort';
import type { CommandArgs, ICommand, Result, resultData } from '../static';
type LsEntry = {
inode: number | null;
@@ -18,7 +19,7 @@ const LsEntryUtils = {
return Object.entries(entry)
.filter(([_, value]) => value !== '')
.map(([_, value]) => value)
.join(' ');
.join(' ').trimStart();
}
};
@@ -38,8 +39,9 @@ const months: readonly string[] = [
];
export const cmd_ls = function (this: Bash, args: CommandArgs): Result {
const resultData: resultData = { cmd: 'ls', data: null, args: args };
const result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd(), data: resultData };
const Fs = this.getFs();
const resultData: CommandResultData = { cmd: 'ls', data: null, args: args };
const result: Result = { exitCode: ExitCode.ERROR, path: this.getCwd(), resultData: resultData };
const nodes: TreeNode[] = [];
//Check if any args contain the long flags with value and are valid flags inside the ls const
@@ -55,10 +57,10 @@ export const cmd_ls = function (this: Bash, args: CommandArgs): Result {
this.throwError(result); //No such flag/s
}
if (args.args.length === 0) nodes.push(this.getFs().getNodeByINode(this.getFs().cwd));
if (args.args.length === 0) nodes.push(Fs.getNodeByINode(Fs.cwd));
for (let i = 0; i < args.args.length; i++) {
const node = this.getFs().resolvePath(args.args[i]);
const node = Fs.resolvePath(args.args[i]);
if (node === null) this.throwError(result); //no such path (i think this will never occur as backed methods have error cases implemented - which is wrong)
nodes.push(node);
@@ -70,22 +72,24 @@ export const cmd_ls = function (this: Bash, args: CommandArgs): Result {
};
function result_ls(this: Bash, data: any, args: CommandArgs): HTMLElement {
const dummysonoerror: HTMLElement = document.createElement('div');
const Fs: VirtualFS = this.getFs();
const flagInfo = checkFlags(args.flags);
const nodes: TreeNode[] = data;
let nodeIndex: number = 0;
const f_a: boolean = flagInfo.has('a') || flagInfo.has('all');
const f_A: boolean = flagInfo.has('A') || flagInfo.has('almost-all');
const f_G: boolean = flagInfo.has('G') || flagInfo.has('no-group');
//const f_G: boolean = flagInfo.has('G') || flagInfo.has('no-group');
const f_h: boolean = flagInfo.has('h') || flagInfo.has('human-readable');
const f_r: boolean = flagInfo.has('r') || flagInfo.has('reverse');
const f_Q: boolean = flagInfo.has('Q') || flagInfo.has('quote-name');
const f_n: boolean = flagInfo.has('n') || flagInfo.has('numeric-uid-gid');
const f_N: boolean = flagInfo.has('N') || flagInfo.has('literal');
const f_L: boolean = flagInfo.has('L') || flagInfo.has('dereference');
const f_R: boolean = flagInfo.has('R') || flagInfo.has('recursive');
//const f_Q: boolean = flagInfo.has('Q') || flagInfo.has('quote-name');
//const f_n: boolean = flagInfo.has('n') || flagInfo.has('numeric-uid-gid');
//const f_N: boolean = flagInfo.has('N') || flagInfo.has('literal');
//const f_L: boolean = flagInfo.has('L') || flagInfo.has('dereference');
const f_i: boolean = flagInfo.has('i') || flagInfo.has('inode');
const f_help: boolean = flagInfo.has('help');
//const f_help: boolean = flagInfo.has('help');
const f_si: boolean = flagInfo.has('si');
const f_X: boolean = flagInfo.has('X');
const f_S: boolean = flagInfo.has('S');
@@ -96,153 +100,171 @@ function result_ls(this: Bash, data: any, args: CommandArgs): HTMLElement {
const f_g: boolean = flagInfo.has('g');
const f_o: boolean = flagInfo.has('o');
let shouldShift: boolean = false
const valuedArgs = args.flags.filter((flag: string) =>
flag.includes('=') && ls.flags.includes(flag.split('=')[0]));
if (f_l || f_g || f_o) {
const w: HTMLElement = document.createElement('div');
if(f_R) {
const treeWalkResult: TreeNode[] = [];
const treeWalkCallback = (node: TreeNode) => { treeWalkResult.push(node); }
for(const node of nodes) {
treeWalkResult.push(node);
Fs.recursiveTraversalPre(node, treeWalkCallback);
}
nodes.length = 0;
nodes.push(...treeWalkResult.filter((node) => node.type != Type.File));
}
for (const node of nodes) {
const elem: HTMLElement = document.createElement('div');
const children: TreeNode[] = node.children.map((child) => this.getFs().getNodeByINode(child));
const rows: string[] = [];
const childrenMap: TreeNode[] = node.children.map((child) => Fs.getNodeByINode(child));
const children: TreeNode[] = (f_a || f_A)
? childrenMap
: childrenMap.filter((child) => !child.name.startsWith('.'));
const timeArg = valuedArgs.find((flag) => flag.startsWith('time'));
const shouldNamesShift: boolean = children.some((child) => child.name.match(/\s/) !== null);
let timestamp: SortNodeBy.ATIME | SortNodeBy.CTIME | SortNodeBy.MTIME = SortNodeBy.MTIME;
if(f_a && !f_A) {
const current: TreeNode = node;
current.name = '.';
const parent: TreeNode = Fs.getNodeByINode(node.parent);
parent.name = '..';
children.unshift(current, parent);
}
if(timeArg) {
let value: string = timeArg.split('=')[1];
if (value && isValidNodeTimestamp(value)) {
timestamp = value;
console.log(timestamp);
}
if (value && isValidNodeTimestamp(value)) timestamp = value;
}
if (!f_U && !f_f) {
const sortArg = valuedArgs.find((flag) => flag.startsWith('sort'));
let sortBy: SortNodeBy = SortNodeBy.NAME;
if(f_t) sortBy = timestamp;
if(f_S) sortBy = SortNodeBy.SIZE;
if(f_X) sortBy = SortNodeBy.EXTENSION;
if(sortArg) {
let value = sortArg.split('=')[1];
if(value && isValidNodeSortMethod(value)) {
sortBy = value;
console.log(sortBy, 'sortBy');
}
if(value && isValidNodeSortMethod(value)) sortBy = value;
}
Sort.nodeArraySort.call(this, children, f_r, sortBy);
}
const sizes = children.map((child) => child.size);
const maxSizeWidth = Math.max(...sizes.map((size) => size));
if (f_l || f_g || f_o) {
const rows: string[] = [];
const maxSizeWidth = Math.max(
...children.map((child) => child.size.toString().length));
for (const child of children) {
if (child.name.startsWith('.') && !(f_a || f_A)) continue;
const cols: LsEntry = {
const entry: LsEntry = {
inode: null,
perms: formatPermission(child),
children: formatChildren(child),
owners: formatOwners.call(this, child, flagInfo),
size: formatSize.call(this, f_h, child, maxSizeWidth, f_si),
modt: formatModtime(child, timestamp),
name: formatName(child, flagInfo, shouldShift)
name: formatName(child, flagInfo, shouldNamesShift)
};
if (f_i) cols.inode = child.inode;
if (f_i) entry.inode = child.inode;
rows.push(LsEntryUtils.toString(cols));
}
if (f_a && !f_A) {
const current: LsEntry = {
inode: null,
perms: formatPermission(node),
children: formatChildren(node),
owners: formatOwners.call(this, node, flagInfo),
size: formatSize.call(this, f_h, node, maxSizeWidth, f_si),
modt: formatModtime(node, timestamp),
name: '.'
};
let parent: LsEntry = {
...current,
name: '..'
};
if (node.parent) {
const parentNode: TreeNode = this.getFs().getNodeByINode(node.parent);
parent = {
inode: null,
perms: formatPermission(parentNode),
children: formatChildren(parentNode),
owners: formatOwners.call(this, parentNode, flagInfo),
size: formatSize.call(this, f_h, parentNode, maxSizeWidth, f_si),
modt: formatModtime(parentNode, timestamp),
name: '..'
};
}
if (f_i) {
current.inode = node.inode;
parent.inode = node.parent ? node.parent : node.inode;
}
if (f_r) {
rows.push(LsEntryUtils.toString(parent), LsEntryUtils.toString(current));
} else {
rows.unshift(LsEntryUtils.toString(current), LsEntryUtils.toString(parent));
}
rows.push(LsEntryUtils.toString(entry));
}
//TODO: Calculate the total size of contents in the node
rows.unshift('total ' + node.children.length.toString());
if (nodes.length > 1) {
const nodePath: string =
node.name === '/' ? '/:' : `${this.getFs().getPathByInode(node.inode).slice(1)}:`;
rows.unshift(nodePath);
rows.push('\n');
}
for(const row of rows) {
const name: string = row[row.length - 1];
if(!name.startsWith('"') || !name.startsWith("'"))
name.padStart(1, ' ');
else continue;
const nodePath: HTMLElement = document.createElement('p');
nodePath.innerText = `${Fs.getPathByInode(node.inode)}:`;
w.appendChild(nodePath);
if(nodeIndex +1 < nodes.length) elem.style.marginBottom = `${this.getTerminalFontSize() * 2}px`;
}
for (let i = 0; i < rows.length; i++) {
const p: HTMLElement = document.createElement('p');
p.innerText = rows[i];
elem.appendChild(p);
}
w.appendChild(elem);
}
return w;
else {
const maxWidth: number = Math.ceil((this.getTerminalWidth() / this.getTerminalFontSize()) * 0.8);
let columns: string[][] = [];
let colWidths: number[];
let lowBound: number = 1;
let highBound: number = children.length;
while(lowBound + 1 < highBound) {
const c = lowBound + (highBound - lowBound) / 2;
columns = [];
colWidths = [];
let fileIndex = 0;
for(let i = 0; i < c; i++) {
if(fileIndex >= children.length) break;
columns[i] = [];
for(let j = 0; j < Math.ceil(children.length / c); j++) {
if(fileIndex >= children.length) break;
columns[i].push(children[fileIndex].name);
fileIndex++;
}
colWidths.push(Math.max(...columns[i].map((name) => name.length)));
}
const calcWidth: number = colWidths.reduce((prev, curr) => prev + curr) + ((c-1) * 2);
if(calcWidth < maxWidth) lowBound = c + 1;
else if(calcWidth > maxWidth) highBound = c -1
}
return dummysonoerror; //TEMP SO NO ERROR CUZ RETURNS HTMLElement EVERY TIME, DELETE LATER
}
const wrapper: HTMLElement = document.createElement('div');
function checkMaxColumns(this: Bash, files: TreeNode[]) {
const paddingWidth: number = 2;
const maxWidth: number = (this.getTerminalWidth() / this.getTerminalFontSize()) * 0.8;
wrapper.style.display = 'flex';
wrapper.style.columnGap = `${this.getTerminalFontSize() * 2}px`;
wrapper.style.marginBottom = `${this.getTerminalFontSize() * 2}px`;
let fileIndex = 0;
//Upper bound set to max width / min column width - 1 character + padding
let lowBound: number = 1;
let highBound: number = Math.floor(maxWidth / (1 + paddingWidth));
for(let i = 0; i < lowBound; i++) {
if(fileIndex >= children.length) break;
const col: HTMLElement = document.createElement('div');
for(let j = 0; j < Math.ceil(children.length / lowBound); j++) {
if(fileIndex >= children.length) break;
const entry: HTMLElement = document.createElement('p');
entry.innerText = formatName(children[fileIndex], flagInfo, shouldNamesShift);
col.appendChild(entry);
fileIndex++;
}
wrapper.appendChild(col);
}
if (nodes.length > 1) {
const nodePath: HTMLElement = document.createElement('p');
nodePath.innerText = `${Fs.getPathByInode(node.inode)}`;
w.appendChild(nodePath);
}
w.appendChild(wrapper);
}
nodeIndex++;
}
return w;
}
function isValidNodeSortMethod(value: string): value is SortNodeBy {
@@ -256,8 +278,8 @@ function isValidNodeTimestamp(value: string): value is SortNodeBy.ATIME | SortNo
function parsePerms(perms: NodePerms): string {
const parts: string[] = [];
//for each key (key representing key name and p representing the key contents) of entries in perms as types keyof NodePerms and Permission
for (const [key, p] of Object.entries(perms) as [keyof NodePerms, Permission][]) {
const perms: string = `${p.r ? 'r' : '-'}${p.w ? 'w' : '-'}${p.x ? 'x' : '-'}`;
for (const [, permission] of Object.entries(perms) as [keyof NodePerms, Permission][]) {
const perms: string = `${permission.r ? 'r' : '-'}${permission.w ? 'w' : '-'}${permission.x ? 'x' : '-'}`;
parts.push(perms);
}
return parts.join('');
@@ -336,14 +358,14 @@ function formatModtime(node: TreeNode, sortBy: SortNodeBy.ATIME | SortNodeBy.CTI
}
function formatName(node: TreeNode, flag: any, shouldShift: boolean) {
let name: string;
let name: string = node.name;
const char: string = flag.has('Q') ? '"' : "'";
if (/\s/.test(node.name)) {
name = `${char}${node.name}${char}`
shouldShift = true;
name = `${char}${name}${char}`
} else {
name = `${node.name}`;
//Shift non quoted names 1 char right to align if any names in group have a quote
name = `${shouldShift ? ' ' : ''}${node.name}`;
}
return flag.has('p') && node.type === Type.Directory ? `${name}/` : name;
@@ -373,6 +395,7 @@ export const ls: ICommand = {
't',
'S',
'r',
'R',
'Q',
'p',
'o',
@@ -389,6 +412,7 @@ export const ls: ICommand = {
'no-group',
'human-readable',
'reverse',
'recursive',
'quote-name',
'indicator-style',
'literal',
-13
View File
@@ -1,13 +0,0 @@
import type { ICommand } from "../static"
import { cmd_ls } from "./ls"
type LsEntry
export class ls {
public const ls: ICommand = {
method: ls.cmd_ls
}
}

Some files were not shown because too many files have changed in this diff Show More