Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
871c5bed86 | ||
|
|
c7d1610648 | ||
|
|
afd663b6af |
@@ -9,7 +9,6 @@
|
|||||||
"version": "0.0.69",
|
"version": "0.0.69",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@lucide/svelte": "^0.548.0",
|
"@lucide/svelte": "^0.548.0",
|
||||||
"animejs": "^4.5.0",
|
|
||||||
"gl-matrix": "^3.4.4",
|
"gl-matrix": "^3.4.4",
|
||||||
"zod": "^4.3.6"
|
"zod": "^4.3.6"
|
||||||
},
|
},
|
||||||
@@ -2190,28 +2189,6 @@
|
|||||||
"url": "https://github.com/sponsors/epoberezkin"
|
"url": "https://github.com/sponsors/epoberezkin"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/animejs": {
|
|
||||||
"version": "4.5.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/animejs/-/animejs-4.5.0.tgz",
|
|
||||||
"integrity": "sha512-NQimYX+lz8WaXonGS9zVVoviCIAjONeJayxacUditaivYLqyXgGjFKjuyl0aUUhFKm5MriX9ty1TGovNzoJQWA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"funding": {
|
|
||||||
"type": "github",
|
|
||||||
"url": "https://github.com/sponsors/juliangarnier"
|
|
||||||
},
|
|
||||||
"peerDependencies": {
|
|
||||||
"@types/three": ">=0.150.0",
|
|
||||||
"three": ">=0.150.0"
|
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"@types/three": {
|
|
||||||
"optional": true
|
|
||||||
},
|
|
||||||
"three": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/ansi-regex": {
|
"node_modules/ansi-regex": {
|
||||||
"version": "5.0.1",
|
"version": "5.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite dev",
|
"dev": "vite dev",
|
||||||
|
"dev-host": "vite dev --host",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"prepare": "svelte-kit sync || echo ''",
|
"prepare": "svelte-kit sync || echo ''",
|
||||||
@@ -52,7 +53,6 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@lucide/svelte": "^0.548.0",
|
"@lucide/svelte": "^0.548.0",
|
||||||
"animejs": "^4.5.0",
|
|
||||||
"gl-matrix": "^3.4.4",
|
"gl-matrix": "^3.4.4",
|
||||||
"zod": "^4.3.6"
|
"zod": "^4.3.6"
|
||||||
}
|
}
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 158 B |
|
Before Width: | Height: | Size: 158 B |
|
Before Width: | Height: | Size: 158 B |
|
Before Width: | Height: | Size: 205 B |
|
Before Width: | Height: | Size: 597 B |
|
Before Width: | Height: | Size: 560 B |
|
Before Width: | Height: | Size: 615 B |
|
Before Width: | Height: | Size: 597 B |
|
Before Width: | Height: | Size: 628 B |
|
Before Width: | Height: | Size: 585 B |
|
Before Width: | Height: | Size: 604 B |
|
Before Width: | Height: | Size: 601 B |
|
Before Width: | Height: | Size: 632 B |
|
Before Width: | Height: | Size: 612 B |
|
Before Width: | Height: | Size: 467 B |
|
Before Width: | Height: | Size: 471 B |
|
Before Width: | Height: | Size: 471 B |
|
Before Width: | Height: | Size: 476 B |
|
Before Width: | Height: | Size: 468 B |
|
Before Width: | Height: | Size: 459 B |
|
Before Width: | Height: | Size: 472 B |
|
Before Width: | Height: | Size: 628 B |
|
Before Width: | Height: | Size: 649 B |
|
Before Width: | Height: | Size: 638 B |
|
Before Width: | Height: | Size: 656 B |
|
Before Width: | Height: | Size: 648 B |
|
Before Width: | Height: | Size: 640 B |
|
Before Width: | Height: | Size: 629 B |
|
Before Width: | Height: | Size: 628 B |
|
Before Width: | Height: | Size: 639 B |
|
Before Width: | Height: | Size: 657 B |
|
Before Width: | Height: | Size: 645 B |
|
Before Width: | Height: | Size: 654 B |
@@ -110,7 +110,6 @@ class MWinController {
|
|||||||
|
|
||||||
this.#node.style.left = '0';
|
this.#node.style.left = '0';
|
||||||
this.#node.style.top = '0';
|
this.#node.style.top = '0';
|
||||||
this.#node.classList.add('[Movable]');
|
|
||||||
|
|
||||||
const mgr = getWrapperManager(this.#wrapper);
|
const mgr = getWrapperManager(this.#wrapper);
|
||||||
mgr.refCount++;
|
mgr.refCount++;
|
||||||
@@ -182,10 +181,6 @@ class MWinController {
|
|||||||
|
|
||||||
#apply() {
|
#apply() {
|
||||||
this.#node.style.transform = `translate(${this.state.x}px, ${this.state.y}px)`;
|
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.width = this.state.width + 'px';
|
||||||
this.#node.style.height = this.state.height + 'px';
|
this.#node.style.height = this.state.height + 'px';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
//if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set');
|
import { drizzle } from 'drizzle-orm/mysql2';
|
||||||
|
import mysql from 'mysql2/promise';
|
||||||
|
import * as schema from './schema';
|
||||||
|
import { env } from '$env/dynamic/private';
|
||||||
|
|
||||||
//const client = mysql.createPool(env.DATABASE_URL);
|
if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set');
|
||||||
|
|
||||||
//export const db = drizzle(client, { schema, mode: 'default', logger: true });
|
const client = mysql.createPool(env.DATABASE_URL);
|
||||||
|
|
||||||
|
export const db = drizzle(client, { schema, mode: 'default', logger: true });
|
||||||
|
|||||||
@@ -1,382 +0,0 @@
|
|||||||
|
|
||||||
// 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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
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';
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export const matchers = {};
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export { default as component } from "../../../../../../../node_modules/@sveltejs/kit/src/runtime/components/svelte-5/layout.svelte";
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export { default as component } from "../../../../../../../node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte";
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
{
|
|
||||||
"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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,478 +0,0 @@
|
|||||||
<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>
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
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 };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
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
|
|
||||||
};
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
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';
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,266 +0,0 @@
|
|||||||
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');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,338 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,228 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { WebG } from './renderer/web_g_engine';
|
||||||
|
|
||||||
|
export namespace Shimagic {
|
||||||
|
export class Shimeji {
|
||||||
|
private WebGEngine: WebG.Engine;
|
||||||
|
//private PhysisEngine: Physis.Engine;
|
||||||
|
private size!: number;
|
||||||
|
|
||||||
|
private AnimID: number | null = null;
|
||||||
|
private pDeltaT: number = 0;
|
||||||
|
|
||||||
|
constructor(webgengine: WebG.Engine /* physis: Physis.Engine */) {
|
||||||
|
this.WebGEngine = webgengine;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Factory method: Initializes all sub-systems like WebG & Physis aswell as initializes the Shimeji and starts its animation
|
||||||
|
* @async
|
||||||
|
* @public
|
||||||
|
* @param {ShimejiConfig} config - Shimeji configuration
|
||||||
|
* @returns {Promise<Shimeji>} that resolves when the Shimeji is done initializing
|
||||||
|
*/
|
||||||
|
public static async Initialize(config: ShimejiConfig): Promise<Shimeji> {
|
||||||
|
const webg = await WebG.Engine.Initialize(config.webG);
|
||||||
|
//const physis = await Physis.Engine.Initialize(config.physis);
|
||||||
|
|
||||||
|
const shimeji = new Shimeji(webg);
|
||||||
|
shimeji.size = config.size;
|
||||||
|
|
||||||
|
const AFrame = (delta: number) => {
|
||||||
|
shimeji.pDeltaT = delta;
|
||||||
|
shimeji.AnimID = requestAnimationFrame(shimeji._anim);
|
||||||
|
};
|
||||||
|
|
||||||
|
shimeji.AnimID = requestAnimationFrame(AFrame);
|
||||||
|
|
||||||
|
return shimeji;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _anim(delta: number) {
|
||||||
|
let dt = (delta - this.pDeltaT) / 1000;
|
||||||
|
dt = Math.min(dt, 0.05 /* * this.Physis.TIMESCALE */);
|
||||||
|
this.pDeltaT = delta;
|
||||||
|
|
||||||
|
this.UpdatePhysics(dt);
|
||||||
|
this.UpdateFrame(dt);
|
||||||
|
|
||||||
|
this.AnimID = requestAnimationFrame(this._anim);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A function called automatically every "frame" where the code for calculating the next physics frame of the Shimeji is placed
|
||||||
|
* @param delta - Automatically passed in deltaT value;
|
||||||
|
*/
|
||||||
|
private UpdatePhysics(delta: number): void {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A function called automatically every "frame" where the code for drawing the next frame of the Shimeji is placed
|
||||||
|
* @param delta - Automatically passed in deltaT value;
|
||||||
|
*/
|
||||||
|
private UpdateFrame(delta: number): void {}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ShimejiConfig {
|
||||||
|
sprite: string; //temp soultion to
|
||||||
|
size: number;
|
||||||
|
webG: WebG.EngineConfig;
|
||||||
|
//physis: Physis.EngineConfig;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,211 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
@@ -1,191 +0,0 @@
|
|||||||
// $lib/stores/petals.ts
|
|
||||||
|
|
||||||
function mulberry32(seed: number): () => number {
|
|
||||||
let a = seed >>> 0;
|
|
||||||
return () => {
|
|
||||||
a = (a + 0x6d2b79f5) | 0;
|
|
||||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
|
||||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
||||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function accelPosition(u: number, k: number): number {
|
|
||||||
if (k < 0.01) return u * u;
|
|
||||||
if (k > 50) return u;
|
|
||||||
const denom = k - 1 + Math.exp(-k);
|
|
||||||
return (k * u - 1 + Math.exp(-k * u)) / denom;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PetalsOptions {
|
|
||||||
duration?: number;
|
|
||||||
fallAccel?: number;
|
|
||||||
fallDistance?: number;
|
|
||||||
leadIn?: number;
|
|
||||||
swayAmp?: number;
|
|
||||||
swayCycles?: number;
|
|
||||||
windX?: number;
|
|
||||||
spin?: number;
|
|
||||||
maxKeyframes?: number;
|
|
||||||
seed?: number;
|
|
||||||
hideOriginals?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type PetalsCleanup = () => void;
|
|
||||||
|
|
||||||
let callCounter = 0;
|
|
||||||
|
|
||||||
function viewportBottom(): number {
|
|
||||||
const vv = window.visualViewport;
|
|
||||||
if (vv) return vv.height + vv.offsetTop;
|
|
||||||
return Math.max(document.documentElement.clientHeight, window.innerHeight);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function petals(
|
|
||||||
node: HTMLElement,
|
|
||||||
{
|
|
||||||
duration = 15000,
|
|
||||||
fallAccel = 4,
|
|
||||||
fallDistance,
|
|
||||||
leadIn = 0.18,
|
|
||||||
swayAmp = 22,
|
|
||||||
swayCycles = 2.0,
|
|
||||||
windX = 60,
|
|
||||||
spin = 300,
|
|
||||||
maxKeyframes = 90,
|
|
||||||
seed,
|
|
||||||
hideOriginals = true
|
|
||||||
}: PetalsOptions = {}
|
|
||||||
): PetalsCleanup {
|
|
||||||
const chars = Array.from(node.querySelectorAll<HTMLElement>('.char')).filter(
|
|
||||||
(el) => el.textContent?.trim() !== ''
|
|
||||||
);
|
|
||||||
|
|
||||||
if (chars.length === 0) return () => {};
|
|
||||||
|
|
||||||
const effectiveSeed = seed ?? Date.now() ^ (callCounter++ * 0x9e3779b9);
|
|
||||||
|
|
||||||
const rect = node.getBoundingClientRect();
|
|
||||||
const vb = viewportBottom();
|
|
||||||
|
|
||||||
// ── Clone + fixed overlay ────────────────────────────────────────────
|
|
||||||
const clone = node.cloneNode(true) as HTMLElement;
|
|
||||||
clone.removeAttribute('id');
|
|
||||||
clone.querySelectorAll<HTMLElement>('[id]').forEach((n) => n.removeAttribute('id'));
|
|
||||||
|
|
||||||
clone.querySelectorAll<HTMLElement>('.prompt, .cursor').forEach((n) => {
|
|
||||||
n.style.visibility = 'hidden';
|
|
||||||
});
|
|
||||||
|
|
||||||
clone.style.cssText = `
|
|
||||||
position: fixed;
|
|
||||||
top: ${rect.top}px;
|
|
||||||
left: ${rect.left}px;
|
|
||||||
margin: 0;
|
|
||||||
overflow: visible;
|
|
||||||
pointer-events: none;
|
|
||||||
z-index: 9999;
|
|
||||||
contain: layout style;
|
|
||||||
`;
|
|
||||||
|
|
||||||
const origFont = getComputedStyle(node);
|
|
||||||
clone.style.fontSize = origFont.fontSize;
|
|
||||||
clone.style.fontFamily = origFont.fontFamily;
|
|
||||||
clone.style.fontWeight = origFont.fontWeight;
|
|
||||||
clone.style.fontStyle = origFont.fontStyle;
|
|
||||||
clone.style.fontVariant = origFont.fontVariant;
|
|
||||||
clone.style.fontStretch = origFont.fontStretch;
|
|
||||||
clone.style.lineHeight = origFont.lineHeight;
|
|
||||||
clone.style.letterSpacing = origFont.letterSpacing;
|
|
||||||
clone.style.wordSpacing = origFont.wordSpacing;
|
|
||||||
clone.style.color = 'var(--color-text-primary)';
|
|
||||||
clone.style.transition = 'var(--transition-standard)';
|
|
||||||
|
|
||||||
document.body.appendChild(clone);
|
|
||||||
|
|
||||||
if (hideOriginals) {
|
|
||||||
chars.forEach((el) => {
|
|
||||||
el.style.visibility = 'hidden';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloneChars = Array.from(clone.querySelectorAll<HTMLElement>('.char'));
|
|
||||||
const petalRects: DOMRect[] = [];
|
|
||||||
for (let i = 0; i < cloneChars.length; i++) {
|
|
||||||
petalRects.push(cloneChars[i].getBoundingClientRect());
|
|
||||||
}
|
|
||||||
|
|
||||||
const anims: Animation[] = [];
|
|
||||||
|
|
||||||
cloneChars.forEach((el, i) => {
|
|
||||||
const rand = mulberry32(effectiveSeed + i * 100003);
|
|
||||||
|
|
||||||
const charDuration = duration * (1.85 + rand() * 1.43);
|
|
||||||
const charAccel = fallAccel * (0.9 + rand() * 0.2);
|
|
||||||
const charSwayCycles = swayCycles * (0.7 + rand() * 0.7);
|
|
||||||
const charLeadIn = leadIn * (0.85 + rand() * 0.3);
|
|
||||||
|
|
||||||
const phase = rand() * Math.PI * 2;
|
|
||||||
const dir: 1 | -1 = rand() < 0.5 ? -1 : 1;
|
|
||||||
const amp = swayAmp * (0.5 + rand() * 0.9);
|
|
||||||
const spinTotal = spin * (0.7 + rand() * 0.6) * dir;
|
|
||||||
const charWindX = windX * (0.5 + rand() * 1.0);
|
|
||||||
|
|
||||||
let charFall: number;
|
|
||||||
if (fallDistance != null) {
|
|
||||||
charFall = fallDistance * (0.95 + rand() * 0.15);
|
|
||||||
} else {
|
|
||||||
const petalRect = petalRects[i];
|
|
||||||
const neededFall = vb - petalRect.top + petalRect.height + 40;
|
|
||||||
charFall = neededFall * (1 + rand() * 0.35);
|
|
||||||
}
|
|
||||||
|
|
||||||
const N = Math.min(maxKeyframes, Math.max(40, Math.round(charDuration / 200)));
|
|
||||||
const frames: Keyframe[] = [];
|
|
||||||
|
|
||||||
for (let k = 0; k <= N; k++) {
|
|
||||||
const t = k / N;
|
|
||||||
const y = charFall * accelPosition(t, charAccel);
|
|
||||||
|
|
||||||
const lead = Math.min(1, t / charLeadIn);
|
|
||||||
const leadSmooth = lead * lead * (3 - 2 * lead);
|
|
||||||
|
|
||||||
const sway = amp * leadSmooth * Math.sin(2 * Math.PI * charSwayCycles * t + phase);
|
|
||||||
const wind = charWindX * t;
|
|
||||||
const x = sway + wind;
|
|
||||||
|
|
||||||
const r = spinTotal * t;
|
|
||||||
|
|
||||||
frames.push({
|
|
||||||
transform: `translate(${x.toFixed(2)}px, ${y.toFixed(2)}px) rotate(${r.toFixed(2)}deg)`,
|
|
||||||
offset: t
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
anims.push(
|
|
||||||
el.animate(frames, {
|
|
||||||
duration: charDuration,
|
|
||||||
delay: 0,
|
|
||||||
easing: 'linear',
|
|
||||||
fill: 'forwards'
|
|
||||||
})
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
let cleaned = false;
|
|
||||||
const doCleanup = (): void => {
|
|
||||||
if (cleaned) return;
|
|
||||||
cleaned = true;
|
|
||||||
for (const a of anims) a.cancel();
|
|
||||||
clone.remove();
|
|
||||||
if (hideOriginals) {
|
|
||||||
chars.forEach((el) => {
|
|
||||||
el.style.visibility = '';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
void Promise.allSettled(anims.map((a) => a.finished)).then(doCleanup);
|
|
||||||
|
|
||||||
return doCleanup;
|
|
||||||
}
|
|
||||||
@@ -1,370 +1,336 @@
|
|||||||
|
import Vector2 from "../vector";
|
||||||
|
|
||||||
export class Shimeji {
|
export class Shimeji {
|
||||||
private element: HTMLElement;
|
private element: HTMLElement;
|
||||||
|
private canvas: HTMLCanvasElement;
|
||||||
// Position and velocity
|
private rect: DOMRect;
|
||||||
private x: number = 0;
|
|
||||||
private y: number = 0;
|
private pos: Vector2 = Vector2.zero;
|
||||||
private velocityX: number = 0;
|
private vel: Vector2 = Vector2.zero;
|
||||||
private velocityY: number = 0;
|
|
||||||
|
private angle: number = 0; // radians
|
||||||
// Mouse tracking
|
private angularVelocity: number = 0; // rad/s
|
||||||
private mouseX: number = 0;
|
private inertia: number; // kg·m²
|
||||||
private mouseY: number = 0;
|
private localGrip: Vector2 = Vector2.zero; // offset from center (body‑fixed)
|
||||||
private mouseAccelX: number = 0;
|
|
||||||
private mouseAccelY: number = 0;
|
private mousePos: Vector2 = Vector2.zero;
|
||||||
|
|
||||||
// Throw detection - track mouse movement history
|
private pivot: Vector2 = Vector2.zero;
|
||||||
private mouseHistory: Array<{ x: number; y: number; time: number }> = [];
|
|
||||||
private readonly HISTORY_LENGTH: number = 5;
|
private isBeingDragged: boolean = false;
|
||||||
|
|
||||||
private isBeingDragged: boolean = false;
|
private rafId: number | null = null;
|
||||||
|
private prevDeltaTime: number = 0;
|
||||||
private rafId: number | null = null;
|
|
||||||
|
|
||||||
// Physics parameters
|
private readonly RESTITUTION: number = 0.6;
|
||||||
private readonly STIFFNESS: number = 0.85;
|
private readonly STIFFNESS: number = 500;
|
||||||
private readonly DAMPING: number = 0.6;
|
private readonly DAMPING: number = 1;
|
||||||
private readonly MASS: number = 1.0;
|
private readonly MASS: number = 10.0;
|
||||||
|
private readonly FRICTION: number = 0.9;
|
||||||
// Gravity (pixels per frame squared)
|
private readonly GRAVITY: number = 10;
|
||||||
private gravity: number = 10;
|
|
||||||
|
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
|
||||||
// Bounce coefficients (energy retention - lower = less bounce)
|
|
||||||
private readonly WALL_BOUNCE: number = 0.5; // Walls lose 50% energy
|
constructor(element: HTMLElement, canvas: HTMLCanvasElement) {
|
||||||
private readonly FLOOR_BOUNCE: number = 0.6; // Floor loses 40% energy (realistic)
|
this.element = element;
|
||||||
private readonly CEILING_BOUNCE: number = 0.4; // Ceiling loses 60% energy
|
this.canvas= canvas;
|
||||||
|
this.rect = element.getBoundingClientRect();
|
||||||
// Minimum velocity to continue bouncing
|
|
||||||
private readonly MIN_BOUNCE_VELOCITY: number = 2;
|
this.bounds = {
|
||||||
|
minX: 0,
|
||||||
// Boundaries
|
minY: 0,
|
||||||
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
|
maxX: window.innerWidth,
|
||||||
|
maxY: window.innerHeight
|
||||||
// Optional forces
|
};
|
||||||
private wind: number = 0;
|
|
||||||
private friction: number = 0.98;
|
this.inertia = (1 / 12) *
|
||||||
|
this.MASS * (this.rect.width * this.rect.width + this.rect.height * this.rect.height);
|
||||||
// Track if on ground for additional effects
|
|
||||||
private wasOnGround: boolean = false;
|
this.pos.set(window.innerWidth / 2, window.innerHeight/ 2);
|
||||||
private bounceCount: number = 0;
|
|
||||||
|
this.updateBounds();
|
||||||
constructor(element: HTMLElement) {
|
window.addEventListener('resize', () => this.updateBounds());
|
||||||
this.element = element;
|
|
||||||
|
console.log(this.element.getBoundingClientRect());
|
||||||
// Initialize bounds (will update on resize)
|
|
||||||
this.bounds = {
|
this.setupDragEvents();
|
||||||
minX: 0,
|
}
|
||||||
minY: 0,
|
|
||||||
maxX: window.innerWidth,
|
private updateBounds(): void {
|
||||||
maxY: window.innerHeight
|
this.bounds = {
|
||||||
};
|
minX: 0,
|
||||||
|
minY: 0,
|
||||||
// Start with element at center
|
maxX: window.innerWidth,
|
||||||
this.x = window.innerWidth / 2;
|
maxY: window.innerHeight
|
||||||
this.y = window.innerHeight / 2;
|
};
|
||||||
|
|
||||||
this.updateBounds();
|
this.canvas.width = window.innerWidth;
|
||||||
window.addEventListener('resize', () => this.updateBounds());
|
this.canvas.height = window.innerHeight;
|
||||||
|
}
|
||||||
this.setupDragEvents();
|
|
||||||
}
|
start(): void {
|
||||||
|
if (this.rafId !== null) return;
|
||||||
private updateBounds(): void {
|
|
||||||
this.bounds = {
|
const firstFrame = (delta: number) => {
|
||||||
minX: 0,
|
this.prevDeltaTime = delta;
|
||||||
minY: 0,
|
this.rafId = requestAnimationFrame(animate);
|
||||||
maxX: window.innerWidth,
|
}
|
||||||
maxY: window.innerHeight
|
|
||||||
};
|
const animate = (delta: number) => {
|
||||||
}
|
const dt: number = Math.min(delta - this.prevDeltaTime, 0.05);
|
||||||
|
this.prevDeltaTime = delta;
|
||||||
start(): void {
|
|
||||||
if (this.rafId !== null) return;
|
this.updatePhysics(dt);
|
||||||
|
this.applyBoundaries();
|
||||||
const animate = () => {
|
this.render();
|
||||||
this.updatePhysics();
|
this.rafId = requestAnimationFrame(animate);
|
||||||
this.applyBoundaries();
|
};
|
||||||
this.render();
|
|
||||||
this.rafId = requestAnimationFrame(animate);
|
this.rafId = requestAnimationFrame(firstFrame);
|
||||||
};
|
}
|
||||||
|
|
||||||
this.rafId = requestAnimationFrame(animate);
|
stop(): void {
|
||||||
}
|
if (this.rafId !== null) {
|
||||||
|
cancelAnimationFrame(this.rafId);
|
||||||
stop(): void {
|
this.rafId = null;
|
||||||
if (this.rafId !== null) {
|
}
|
||||||
cancelAnimationFrame(this.rafId);
|
}
|
||||||
this.rafId = null;
|
|
||||||
}
|
private getCornerWorld(lx: number, ly: number): Vector2 {
|
||||||
}
|
// lx, ly are in local coordinates (relative to center, with rotation)
|
||||||
|
const cos = Math.cos(this.angle);
|
||||||
private setupDragEvents(): void {
|
const sin = Math.sin(this.angle);
|
||||||
this.element.addEventListener('mousedown', (e) => {
|
return new Vector2(
|
||||||
e.preventDefault();
|
this.pos.x + (lx * cos - ly * sin),
|
||||||
this.isBeingDragged = true;
|
this.pos.y + (lx * sin + ly * cos)
|
||||||
this.element.style.cursor = 'grabbing';
|
);
|
||||||
|
}
|
||||||
// Clear mouse history on new drag
|
|
||||||
this.mouseHistory = [];
|
private setupDragEvents(): void {
|
||||||
});
|
this.element.addEventListener('mousedown', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
// Track mouse movement globally for better throw detection
|
this.isBeingDragged = true;
|
||||||
document.addEventListener('mousemove', (e) => {
|
this.element.style.cursor = 'grabbing';
|
||||||
if (this.isBeingDragged) {
|
|
||||||
this.mouseX = e.pageX;
|
const parent = this.element.parentElement;
|
||||||
this.mouseY = e.pageY;
|
if(parent) parent.style.cursor = 'grabbing';
|
||||||
this.mouseAccelX = e.movementX;
|
|
||||||
this.mouseAccelY = e.movementY;
|
const clickWorld = new Vector2(e.pageX, e.pageY);
|
||||||
|
const center = this.pos;
|
||||||
// Store mouse position history for throw calculation
|
const offset = clickWorld.sub(center)
|
||||||
this.mouseHistory.push({
|
const cos = Math.cos(-this.angle);
|
||||||
x: e.pageX,
|
const sin = Math.sin(-this.angle);
|
||||||
y: e.pageY,
|
|
||||||
time: Date.now()
|
this.localGrip = new Vector2(
|
||||||
});
|
offset.x * cos - offset.y * sin,
|
||||||
|
offset.x * sin + offset.y * cos
|
||||||
// Keep only recent history
|
);
|
||||||
if (this.mouseHistory.length > this.HISTORY_LENGTH) {
|
|
||||||
this.mouseHistory.shift();
|
this.pivot.x = e.offsetX - this.rect.width / 2;
|
||||||
}
|
this.pivot.y = e.offsetY - this.rect.height / 2;
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
this.element.addEventListener('mouseup', (e) => {
|
document.addEventListener('mousemove', (e) => {
|
||||||
if (this.isBeingDragged) {
|
this.mousePos.x = e.pageX;
|
||||||
this.isBeingDragged = false;
|
this.mousePos.y = e.pageY;
|
||||||
this.element.style.cursor = 'grab';
|
});
|
||||||
|
|
||||||
// Calculate throw velocity based on mouse movement speed
|
document.addEventListener('mouseup', (e) => {
|
||||||
this.applyThrowVelocity();
|
if(this.isBeingDragged) {
|
||||||
|
this.isBeingDragged = false;
|
||||||
// Reset mouse history
|
this.element.style.cursor = 'grab';
|
||||||
this.mouseHistory = [];
|
|
||||||
}
|
const parent = this.element.parentElement;
|
||||||
});
|
if(parent) parent.style.cursor = 'auto';
|
||||||
|
|
||||||
this.element.addEventListener('dragstart', (e) => {
|
this.pivot = Vector2.zero;
|
||||||
e.preventDefault();
|
}
|
||||||
});
|
|
||||||
}
|
this.canvas.getContext('2d')!.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||||
|
});
|
||||||
private applyThrowVelocity(): void {
|
|
||||||
if (this.mouseHistory.length < 2) return;
|
this.element.addEventListener('dragstart', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
// Get oldest and newest mouse positions
|
});
|
||||||
const oldest = this.mouseHistory[0];
|
}
|
||||||
const newest = this.mouseHistory[this.mouseHistory.length - 1];
|
|
||||||
|
private updatePhysics(dt: number): void {
|
||||||
// Calculate time delta in seconds
|
|
||||||
const timeDelta = (newest.time - oldest.time) / 1000;
|
const cos = Math.cos(this.angle);
|
||||||
if (timeDelta === 0) return;
|
const sin = Math.sin(this.angle);
|
||||||
|
const gripWorld = new Vector2(
|
||||||
// Calculate velocity in pixels per second
|
this.pos.x + (this.localGrip.x * cos - this.localGrip.y * sin),
|
||||||
let throwVelX = (newest.x - oldest.x) / timeDelta;
|
this.pos.y + (this.localGrip.x * sin + this.localGrip.y * cos)
|
||||||
let throwVelY = (newest.y - oldest.y) / timeDelta;
|
);
|
||||||
|
|
||||||
// Cap maximum throw velocity to prevent ridiculous speeds
|
if (this.isBeingDragged) {
|
||||||
const MAX_THROW_SPEED = 50;
|
const direction: Vector2 = this.mousePos.sub(gripWorld);
|
||||||
throwVelX = Math.min(Math.max(throwVelX, -MAX_THROW_SPEED), MAX_THROW_SPEED);
|
|
||||||
throwVelY = Math.min(Math.max(throwVelY, -MAX_THROW_SPEED), MAX_THROW_SPEED);
|
const force: Vector2 = direction.mul(this.STIFFNESS);
|
||||||
|
|
||||||
// Apply throw velocity (divide by ~60 to convert from per-second to per-frame)
|
const acceleration: Vector2 = force.div(this.MASS).deadZone(0.001);
|
||||||
this.velocityX += throwVelX / 60;
|
|
||||||
this.velocityY += throwVelY / 60;
|
acceleration.mulEq(dt);
|
||||||
|
|
||||||
// Add a little extra oomph based on acceleration
|
this.vel.addEq(acceleration);
|
||||||
if (Math.abs(this.mouseAccelX) > 5) {
|
this.vel.mulEq(0.8);
|
||||||
this.velocityX += this.mouseAccelX / 30;
|
|
||||||
}
|
const r = gripWorld.sub(this.pos);
|
||||||
if (Math.abs(this.mouseAccelY) > 5) {
|
const torque = r.cross(force);
|
||||||
this.velocityY += this.mouseAccelY / 30;
|
this.angularVelocity += (torque / this.inertia) * dt;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
this.vel.y += this.GRAVITY;
|
||||||
private updatePhysics(): void {
|
this.vel.mulEq(this.DAMPING);
|
||||||
// Apply spring force toward mouse when dragging
|
|
||||||
if (this.isBeingDragged) {
|
if (this.pos.y + this.rect.width >= this.bounds.maxY) {
|
||||||
const dx = this.mouseX - this.x;
|
this.vel.x *= this.FRICTION;
|
||||||
const dy = this.mouseY - this.y;
|
}
|
||||||
|
|
||||||
const forceX = dx * this.STIFFNESS;
|
const outVel = this.vel.mul(dt);
|
||||||
const forceY = dy * this.STIFFNESS;
|
this.pos.addEq(outVel);
|
||||||
|
|
||||||
// Apply force to acceleration (F = ma)
|
this.angle += this.angularVelocity * dt;
|
||||||
const accelerationX = (forceX + this.mouseAccelX) / this.MASS;
|
this.angle %= 2 * Math.PI;
|
||||||
const accelerationY = (forceY + this.mouseAccelY) / this.MASS;
|
}
|
||||||
|
|
||||||
// Update velocity with acceleration
|
private applyBoundaries(): void {
|
||||||
this.velocityX += accelerationX;
|
const w = this.rect.width / 2;
|
||||||
this.velocityY += accelerationY;
|
const h = this.rect.height / 2;
|
||||||
}
|
|
||||||
|
// List of corners in local coordinates (four combinations)
|
||||||
// Apply gravity (always present, but stronger when not dragging)
|
const corners = [
|
||||||
if (!this.isBeingDragged) {
|
{ lx: w, ly: h }, // top‑right
|
||||||
this.velocityY += this.gravity;
|
{ lx: w, ly: -h }, // bottom‑right
|
||||||
} else {
|
{ lx: -w, ly: h }, // top‑left
|
||||||
// Slight gravity even when dragging for realism
|
{ lx: -w, ly: -h } // bottom‑left
|
||||||
this.velocityY += this.gravity * 0.3;
|
];
|
||||||
}
|
|
||||||
|
// Check each wall
|
||||||
// Apply wind (optional horizontal force)
|
// Left wall (x = leftBound)
|
||||||
if (this.y > 10) this.velocityX += this.wind;
|
const leftBound = w;
|
||||||
|
for (const corner of corners) {
|
||||||
// Apply damping (air resistance)
|
const world = this.getCornerWorld(corner.lx, corner.ly);
|
||||||
this.velocityX *= this.DAMPING;
|
if (world.x < leftBound) {
|
||||||
this.velocityY *= this.DAMPING;
|
// Penetration depth (distance from wall to corner)
|
||||||
|
const penetration = leftBound - world.x;
|
||||||
// Update position with velocity
|
// Normal points to the right (+x)
|
||||||
this.x += this.velocityX;
|
const normal = new Vector2(1, 0);
|
||||||
this.y += this.velocityY;
|
// Contact point is the wall at corner's y (or clamp to avoid escaping)
|
||||||
}
|
const contactY = Math.min(Math.max(world.y, this.bounds.minY + h), this.bounds.maxY - h);
|
||||||
|
const contactPoint = new Vector2(leftBound, contactY);
|
||||||
private getElementHeight(): number {
|
this.resolveCollision(normal, contactPoint);
|
||||||
return this.element.offsetHeight;
|
// Reposition to avoid continuous penetration
|
||||||
}
|
this.pos.x = leftBound - w;
|
||||||
|
return; // after one correction, stop checking further walls to avoid multiple impulses
|
||||||
private getElementWidth(): number {
|
}
|
||||||
return this.element.offsetWidth;
|
}
|
||||||
}
|
|
||||||
|
// Right wall (x = rightBound)
|
||||||
private applyBoundaries(): void {
|
const rightBound = this.bounds.maxX - w;
|
||||||
const elementWidth = this.getElementWidth();
|
for (const corner of corners) {
|
||||||
const elementHeight = this.getElementHeight();
|
const world = this.getCornerWorld(corner.lx, corner.ly);
|
||||||
|
if (world.x > rightBound) {
|
||||||
// X-axis boundaries with realistic bounce
|
const penetration = world.x - rightBound;
|
||||||
const leftBound = elementWidth / 2;
|
const normal = new Vector2(-1, 0);
|
||||||
const rightBound = this.bounds.maxX - elementWidth / 2;
|
const contactY = Math.min(Math.max(world.y, this.bounds.minY + h), this.bounds.maxY - h);
|
||||||
|
const contactPoint = new Vector2(rightBound, contactY);
|
||||||
if (this.x < leftBound) {
|
this.resolveCollision(normal, contactPoint);
|
||||||
this.x = leftBound;
|
this.pos.x = rightBound + w;
|
||||||
// Bounce with energy loss
|
return;
|
||||||
this.velocityX = -Math.abs(this.velocityX) * this.WALL_BOUNCE;
|
}
|
||||||
|
}
|
||||||
// Stop if bounce is too small
|
|
||||||
if (Math.abs(this.velocityX) < this.MIN_BOUNCE_VELOCITY) {
|
// Top wall (y = topBound)
|
||||||
this.velocityX = 0;
|
const topBound = h;
|
||||||
}
|
for (const corner of corners) {
|
||||||
} else if (this.x > rightBound) {
|
const world = this.getCornerWorld(corner.lx, corner.ly);
|
||||||
this.x = rightBound;
|
if (world.y < topBound) {
|
||||||
this.velocityX = -Math.abs(this.velocityX) * this.WALL_BOUNCE;
|
const penetration = topBound - world.y;
|
||||||
|
const normal = new Vector2(0, 1);
|
||||||
if (Math.abs(this.velocityX) < this.MIN_BOUNCE_VELOCITY) {
|
const contactX = Math.min(Math.max(world.x, leftBound), rightBound);
|
||||||
this.velocityX = 0;
|
const contactPoint = new Vector2(contactX, topBound);
|
||||||
}
|
this.resolveCollision(normal, contactPoint);
|
||||||
}
|
this.pos.y = topBound - h;
|
||||||
|
return;
|
||||||
// Y-axis boundaries with realistic bounce
|
}
|
||||||
const topBound = elementHeight / 2;
|
}
|
||||||
const bottomBound = this.bounds.maxY - elementHeight / 2;
|
|
||||||
|
// Bottom wall (y = bottomBound)
|
||||||
// Ceiling collision
|
const bottomBound = this.bounds.maxY - h;
|
||||||
if (this.y < topBound) {
|
for (const corner of corners) {
|
||||||
this.y = topBound;
|
const world = this.getCornerWorld(corner.lx, corner.ly);
|
||||||
this.velocityY = -this.velocityY * this.CEILING_BOUNCE;
|
if (world.y > bottomBound) {
|
||||||
|
const penetration = world.y - bottomBound;
|
||||||
// Stop tiny bouncing on ceiling
|
const normal = new Vector2(0, -1);
|
||||||
if (Math.abs(this.velocityY) < this.MIN_BOUNCE_VELOCITY) {
|
const contactX = Math.min(Math.max(world.x, leftBound), rightBound);
|
||||||
this.velocityY = 0;
|
const contactPoint = new Vector2(contactX, bottomBound);
|
||||||
}
|
this.resolveCollision(normal, contactPoint);
|
||||||
}
|
this.pos.y = bottomBound + h;
|
||||||
// Floor collision
|
return;
|
||||||
else if (this.y > bottomBound) {
|
}
|
||||||
this.y = bottomBound;
|
}
|
||||||
|
}
|
||||||
const impactSpeed = Math.abs(this.velocityY);
|
|
||||||
|
private resolveCollision(normal: Vector2, contactPoint: Vector2): void {
|
||||||
// Only bounce if impact speed is significant
|
// Vector from center to contact point
|
||||||
if (impactSpeed > this.MIN_BOUNCE_VELOCITY) {
|
const r = contactPoint.sub(this.pos);
|
||||||
// Apply floor bounce with energy loss
|
|
||||||
this.velocityY = -this.velocityY * this.FLOOR_BOUNCE;
|
// Velocity of the contact point
|
||||||
|
const v_rel = this.vel.clone();
|
||||||
// Bounce gets smaller each time naturally due to energy loss
|
// Add tangential component from angular velocity: ω × r
|
||||||
this.bounceCount++;
|
v_rel.x -= this.angularVelocity * r.y;
|
||||||
|
v_rel.y += this.angularVelocity * r.x;
|
||||||
// Apply ground friction on bounce
|
|
||||||
this.velocityX *= this.groundFriction;
|
// Relative velocity along normal
|
||||||
|
const vn = v_rel.dot(normal);
|
||||||
// Optional: Visual feedback for bounce
|
if (vn > 0) return; // Already separating
|
||||||
// console.log(`Bounce ${this.bounceCount}: impact speed ${impactSpeed.toFixed(2)}, new velocity ${this.velocityY.toFixed(2)}`);
|
|
||||||
} else {
|
// Impulse numerator
|
||||||
// Stop bouncing when energy is too low
|
const numerator = -(1 + this.RESTITUTION) * vn;
|
||||||
this.velocityY = 0;
|
|
||||||
this.wasOnGround = true;
|
// Denominator: 1/m + (r × n)^2 / I
|
||||||
}
|
const r_cross_n = r.cross(normal);
|
||||||
} else {
|
const denominator = 1 / this.MASS + (r_cross_n * r_cross_n) / this.inertia;
|
||||||
this.wasOnGround = false;
|
|
||||||
// Reset bounce count when in air
|
const j = numerator / denominator;
|
||||||
if (!this.isBeingDragged && this.velocityY !== 0) {
|
const impulse = normal.mul(j);
|
||||||
this.bounceCount = 0;
|
|
||||||
}
|
// Apply impulse
|
||||||
}
|
this.vel.addEq(impulse.div(this.MASS));
|
||||||
}
|
this.angularVelocity += r.cross(impulse) / this.inertia;
|
||||||
|
}
|
||||||
private get groundFriction(): number {
|
|
||||||
// More friction when moving fast
|
private drawRay(pos1: {x: number, y: number}, pos2: {x: number, y: number}) {
|
||||||
const speed = Math.abs(this.velocityX);
|
const ctx = this.canvas.getContext("2d")!;
|
||||||
if (speed > 10) return this.friction * 0.9;
|
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||||
if (speed > 5) return this.friction * 0.95;
|
ctx.strokeStyle = "white";
|
||||||
return this.friction;
|
ctx.lineWidth = 0.1
|
||||||
}
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(pos1.x, pos1.y);
|
||||||
private render(): void {
|
ctx.lineTo(pos2.x, pos2.y);
|
||||||
this.element.style.transform = `translate(${this.x}px, ${this.y}px) translateY(-50%)`;
|
ctx.stroke();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Public methods to control physics
|
private render(): void {
|
||||||
setGravity(value: number): void {
|
this.element.style.transform = `translate(${this.pos.x}px, ${this.pos.y}px) rotate(${this.angle * 180 / Math.PI}deg)`;
|
||||||
this.gravity = value;
|
|
||||||
}
|
/* if(this.isBeingDragged) {
|
||||||
|
this.drawRay(
|
||||||
setWind(value: number): void {
|
{x: this.mousePos.x, y: this.mousePos.y},
|
||||||
this.wind = value;
|
{x: this.pos.x + this.pivot.x, y: this.pos.y + this.pivot.y}
|
||||||
}
|
)
|
||||||
|
} */
|
||||||
setPhysics(stiffness: number, damping: number, mass: number = 1.0): void {
|
}
|
||||||
(this as any).STIFFNESS = stiffness;
|
|
||||||
(this as any).DAMPING = damping;
|
addImpulse(x: number, y: number): void {
|
||||||
(this as any).MASS = mass;
|
this.vel.x += x;
|
||||||
}
|
this.vel.y += y;
|
||||||
|
}
|
||||||
setFriction(value: number): void {
|
|
||||||
this.friction = value;
|
moveTo(pos: number) {
|
||||||
}
|
|
||||||
|
}
|
||||||
// Configure bounce properties
|
|
||||||
setBounceProperties(wall: number, floor: number, ceiling: number = 0.4): void {
|
|
||||||
(this as any).WALL_BOUNCE = Math.min(Math.max(wall, 0), 1);
|
|
||||||
(this as any).FLOOR_BOUNCE = Math.min(Math.max(floor, 0), 1);
|
|
||||||
(this as any).CEILING_BOUNCE = Math.min(Math.max(ceiling, 0), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add impulse (like a jump)
|
|
||||||
addImpulse(x: number, y: number): void {
|
|
||||||
this.velocityX += x;
|
|
||||||
this.velocityY += y;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reset position
|
|
||||||
resetPosition(x?: number, y?: number): void {
|
|
||||||
this.x = x ?? this.bounds.maxX / 2;
|
|
||||||
this.y = y ?? this.bounds.maxY / 2;
|
|
||||||
this.velocityX = 0;
|
|
||||||
this.velocityY = 0;
|
|
||||||
this.isBeingDragged = false;
|
|
||||||
this.bounceCount = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
getState() {
|
|
||||||
return {
|
|
||||||
x: this.x,
|
|
||||||
y: this.y,
|
|
||||||
velocityX: this.velocityX,
|
|
||||||
velocityY: this.velocityY,
|
|
||||||
mouseX: this.mouseX,
|
|
||||||
mouseY: this.mouseY,
|
|
||||||
isBeingDragged: this.isBeingDragged,
|
|
||||||
isOnGround: this.wasOnGround,
|
|
||||||
bounceCount: this.bounceCount
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
export class KeybindListener {
|
||||||
|
#abortController: AbortController;
|
||||||
|
#eventStack: KeyboardEvent[] = [];
|
||||||
|
#bindTable: Map<Keybind, KeybindOptions> = new Map();
|
||||||
|
|
||||||
|
constructor(elem: HTMLElement) {
|
||||||
|
this.#abortController = new AbortController();
|
||||||
|
|
||||||
|
elem.addEventListener('keydown', (e) => this.#captureEvent(e), {
|
||||||
|
signal: this.#abortController.signal,
|
||||||
|
passive: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#captureEvent(e: KeyboardEvent) {
|
||||||
|
if (e.altKey || e.shiftKey || e.ctrlKey) {
|
||||||
|
this.#eventStack.push(e);
|
||||||
|
}
|
||||||
|
this.#processEvent(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
#processEvent(e: KeyboardEvent) {
|
||||||
|
const keybind: Keybind = {
|
||||||
|
key: e.key,
|
||||||
|
modifiers: this.#pushModifiers()
|
||||||
|
};
|
||||||
|
|
||||||
|
const value = this.#bindTable.get(keybind);
|
||||||
|
if (!value) return;
|
||||||
|
|
||||||
|
value?.function?.(e);
|
||||||
|
console.log(`[keybind-listener] - executed a function under a keybind: ${keybind}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
#pushModifiers(): Modifier[] {
|
||||||
|
const mods: Modifier[] = [];
|
||||||
|
|
||||||
|
for (const event of this.#eventStack) {
|
||||||
|
mods.push(event.key as Modifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
return mods;
|
||||||
|
}
|
||||||
|
|
||||||
|
registerKeybinds(keybinds: { keybind: Keybind; options: KeybindOptions }[]): void {
|
||||||
|
for (const value of keybinds) {
|
||||||
|
this.#bindTable.set(value.keybind, {
|
||||||
|
function: value.options.function,
|
||||||
|
no_inhibit: value.options.no_inhibit ?? false
|
||||||
|
});
|
||||||
|
console.log(`[keybind-listener] - keybind registered under the key: ${value.keybind}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Keybind = {
|
||||||
|
key: string;
|
||||||
|
modifiers?: Modifier[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type KeybindOptions = {
|
||||||
|
function: (e: KeyboardEvent) => void;
|
||||||
|
no_inhibit?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Modifier = 'Control' | 'Alt' | 'Shift';
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import type { Keybind, KeybindOptions } from "../terminal/keybind_listenter";
|
||||||
|
|
||||||
|
export const SHELL_KEYBINDS: { keybind: Keybind; options: KeybindOptions }[] = [
|
||||||
|
{
|
||||||
|
keybind: {
|
||||||
|
key: 'c',
|
||||||
|
modifiers: ['Control']
|
||||||
|
}
|
||||||
|
options: {
|
||||||
|
function
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import Renderer from '$lib/shimagic/renderer/rendererr';
|
||||||
|
import { WebG } from '$lib/shimagic/renderer/web_g_enginee';
|
||||||
|
import { Shimagic } from '$lib/stores/shimeji';
|
||||||
|
import Vector2 from '$lib/vector';
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
|
||||||
|
const drag: number = 3;
|
||||||
|
const speed: number = 2;
|
||||||
|
|
||||||
|
let shimeji: Shimagic.Shimeji;
|
||||||
|
let renderer: Renderer;
|
||||||
|
let sprite: HTMLElement;
|
||||||
|
let canvas: HTMLCanvasElement;
|
||||||
|
let shown: boolean = $state(false);
|
||||||
|
|
||||||
|
function genRandomPos(min: number, max: number): number {
|
||||||
|
const out = Math.random() * (max - min) + min;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchShader(path: string): Promise<string> {
|
||||||
|
const response = await fetch(path);
|
||||||
|
if (!response.ok) throw new Error(`failed to fetch the shader file ${response}`);
|
||||||
|
return await response.text();
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(async () => {
|
||||||
|
canvas.width = window.innerWidth;
|
||||||
|
canvas.height = window.innerHeight;
|
||||||
|
|
||||||
|
//const vert = await fetchShader('src/lib/shimeji/renderer/shaders/vertex_shader.vert');
|
||||||
|
//const frag = await fetchShader('src/lib/shimeji/renderer/shaders/fragment_shader.frag');
|
||||||
|
|
||||||
|
const engineConfig: WebG.EngineConfig = {
|
||||||
|
canvas: canvas,
|
||||||
|
vertexShaderUrl: 'src/lib/shimeji/renderer/shaders/vertex_shader.vert',
|
||||||
|
fragmentShaderUrl: 'src/lib/shimeji/renderer/shaders/fragment_shader.frag',
|
||||||
|
attributes: {
|
||||||
|
aPosition: 0,
|
||||||
|
aColor: 1
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const engine = await WebG.Engine.Initialize(engineConfig);
|
||||||
|
|
||||||
|
const drawArgs: WebG.DrawCallArgs = {
|
||||||
|
vertices: [
|
||||||
|
new Vector2(200, 200),
|
||||||
|
new Vector2(700, 700),
|
||||||
|
new Vector2(700, 200),
|
||||||
|
new Vector2(200, 200),
|
||||||
|
new Vector2(200, 700),
|
||||||
|
new Vector2(700, 700)
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
engine.setDrawMode(WebG.EngineDrawMode.TEXTURE);
|
||||||
|
engine.draw(drawArgs);
|
||||||
|
|
||||||
|
/* shimeji = new Shimeji(40, canvas, renderer);
|
||||||
|
shimeji.start();
|
||||||
|
|
||||||
|
shown = true;
|
||||||
|
|
||||||
|
document.addEventListener('keydown', (e) => {
|
||||||
|
if (e.key === 'a') {
|
||||||
|
shimeji.addImpulse(-500, -100);
|
||||||
|
}
|
||||||
|
if (e.key === 'd') {
|
||||||
|
shimeji.addImpulse(500, -100);
|
||||||
|
}
|
||||||
|
if (e.key === 'space') {
|
||||||
|
shimeji.moveTo(genRandomPos(200, window.innerWidth - 200));
|
||||||
|
}
|
||||||
|
}); */
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class=" absolute z-20 size-full overflow-clip">
|
||||||
|
<canvas
|
||||||
|
bind:this={canvas}
|
||||||
|
style=" stroke-width: 5px;"
|
||||||
|
class=" absolute z-2 size-full stroke-red-500"
|
||||||
|
></canvas>
|
||||||
|
<!-- <div
|
||||||
|
bind:this={sprite}
|
||||||
|
class=" absolute z-30 size-20 origin-center -translate-1/2 cursor-grab bg-amber-400 opacity-15 will-change-transform transform-flat"
|
||||||
|
></div> -->
|
||||||
|
</div>
|
||||||
@@ -47,11 +47,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
let cwd: string = $state('');
|
let cwd: string = $state('');
|
||||||
const hostname = 'termos'; //TODO: Change this to pull from config on db
|
const hostname = 'terminal'; //TODO: Change this to pull from config on db
|
||||||
//let isProcessActive = $state(false);
|
//let isProcessActive = $state(false);
|
||||||
|
|
||||||
let mwin: MWinAPI;
|
let mwin: MWinAPI;
|
||||||
let inputValue = $state('Lorem ipsum dolor sit amet consectetur adipisicing elit.');
|
let inputValue = $state('');
|
||||||
let inputComponent: any;
|
let inputComponent: any;
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -60,30 +60,35 @@
|
|||||||
class=" relative flex h-screen w-full flex-col items-center justify-center"
|
class=" relative flex h-screen w-full flex-col items-center justify-center"
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
class="absolute flex size-full h-256 w-420 flex-col rounded-md shadow-subtle transition-discrete will-change-auto"
|
class="absolute flex size-full h-256 w-512 flex-col rounded-md shadow-subtle transition-discrete will-change-auto"
|
||||||
id="terminal"
|
|
||||||
use:mwin_movable={{
|
use:mwin_movable={{
|
||||||
wrapper: '#terminal-wrapper',
|
wrapper: '#terminal-wrapper',
|
||||||
handle: '#terminal-bar',
|
handle: '#terminal-bar',
|
||||||
baseZIndex: 10,
|
baseZIndex: 10,
|
||||||
resizable: { threshold: 10, minWidth: 500, minHeight: 300 },
|
resizable: { threshold: 24, minWidth: 500, minHeight: 300 },
|
||||||
onClose: () => {
|
|
||||||
mwin.state.height = 0;
|
|
||||||
},
|
|
||||||
onAPI: (api) => (mwin = api)
|
onAPI: (api) => (mwin = api)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
id="terminal-bar"
|
id="terminal-bar"
|
||||||
class=" flex h-9 w-full flex-row items-center rounded-t-md bg-surface-2 text-center font-terminal text-sm font-bold text-primary select-none light:bg-surface-3"
|
class=" flex h-9 w-full flex-row items-center rounded-t-md bg-surface-2 text-center font-terminal text-sm font-bold text-primary select-none"
|
||||||
>
|
>
|
||||||
<div class="dots-wrapper mx-3 flex h-full flex-row items-center justify-center gap-3">
|
<div class="dots-wrapper mx-3 flex h-full flex-row items-center justify-center gap-3">
|
||||||
<button class="size-[11px] cursor-pointer rounded-full p-0" title=""></button>
|
<button class="size-3 cursor-pointer rounded-full p-0" title="" onclick={() => mwin.close()}
|
||||||
<button class="size-[11px] cursor-pointer rounded-full p-0" title=""></button>
|
></button>
|
||||||
<button class="size-[11px] cursor-pointer rounded-full p-0" title=""></button>
|
<button
|
||||||
|
class="size-3 cursor-pointer rounded-full p-0"
|
||||||
|
title=""
|
||||||
|
onclick={() => mwin.maximize()}
|
||||||
|
></button>
|
||||||
|
<button
|
||||||
|
class="size-3 cursor-pointer rounded-full p-0"
|
||||||
|
title=""
|
||||||
|
onclick={() => mwin.minimize()}
|
||||||
|
></button>
|
||||||
</div>
|
</div>
|
||||||
<div class=" mr-2 flex grow items-center text-center text-sm">
|
<div class=" mr-2 flex grow text-sm">
|
||||||
<span class="leading-none">{username}@{hostname} {cwd}</span>
|
<p>{username}@{hostname} {cwd}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
@@ -101,30 +106,44 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
|
* {
|
||||||
|
transition: var(--transition-standard);
|
||||||
|
}
|
||||||
|
@keyframes fadeIn {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
}
|
||||||
.dots-wrapper {
|
.dots-wrapper {
|
||||||
& > button {
|
& > button {
|
||||||
transition: all 0.05s ease;
|
|
||||||
border: none;
|
border: none;
|
||||||
|
&:hover {
|
||||||
|
transform: translateY(-0.1rem);
|
||||||
|
}
|
||||||
&:active {
|
&:active {
|
||||||
transform: translateY(1px);
|
transform: translate(0);
|
||||||
}
|
}
|
||||||
&:nth-child(1) {
|
&:nth-child(1) {
|
||||||
background-color: rgb(220, 65, 65);
|
background-color: rgb(255, 0, 0);
|
||||||
&:active {
|
&:active {
|
||||||
background-color: rgb(200, 45, 45);
|
background-color: rgb(255, 100, 100);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
&:nth-child(2) {
|
&:nth-child(2) {
|
||||||
background-color: rgb(255, 165, 0);
|
background-color: rgb(255, 165, 0);
|
||||||
&:active {
|
&:active {
|
||||||
background-color: rgb(220, 145, 0);
|
background-color: rgb(255, 215, 50);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
&:nth-child(3) {
|
&:nth-child(3) {
|
||||||
background-color: rgb(55, 170, 60);
|
background-color: rgb(50, 205, 50);
|
||||||
&:active {
|
&:active {
|
||||||
background-color: rgb(35, 150, 40);
|
background-color: rgb(100, 255, 100);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
<div
|
<div
|
||||||
transition:fly={{ x: 20, y: 0, duration: 300 }}
|
transition:fly={{ x: 20, y: 0, duration: 300 }}
|
||||||
id={`toast-${toast.id.toString()}`}
|
id={`toast-${toast.id.toString()}`}
|
||||||
class="w-md overflow-hidden rounded-md bg-bg-lighter-dark"
|
class="w-md overflow-hidden rounded-md bg-surface-2"
|
||||||
onclick={() => toast.onClick?.(toast)}
|
onclick={() => toast.onClick?.(toast)}
|
||||||
role="button"
|
role="button"
|
||||||
tabindex={toast.onClick ? 0 : undefined}
|
tabindex={toast.onClick ? 0 : undefined}
|
||||||
@@ -30,18 +30,18 @@
|
|||||||
<div class="flex items-center justify-start">
|
<div class="flex items-center justify-start">
|
||||||
<div class="mx-4 my-8">
|
<div class="mx-4 my-8">
|
||||||
{#if toast.type === 'info'}
|
{#if toast.type === 'info'}
|
||||||
<Info class=" text-info-dark"></Info>
|
<Info class=" text-info"></Info>
|
||||||
{:else if toast.type === 'error'}
|
{:else if toast.type === 'error'}
|
||||||
<CircleX class="text-danger-dark"></CircleX>
|
<CircleX class="text-error"></CircleX>
|
||||||
{:else if toast.type === 'warn'}
|
{:else if toast.type === 'warn'}
|
||||||
<TriangleAlert class="text-warning-dark"></TriangleAlert>
|
<TriangleAlert class="text-warning"></TriangleAlert>
|
||||||
{:else}
|
{:else}
|
||||||
<CircleCheckBig class="text-success-dark"></CircleCheckBig>
|
<CircleCheckBig class="text-success"></CircleCheckBig>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
<div class="my-2 mr-auto mb-auto ml-2 flex flex-col items-start justify-start select-none">
|
<div class="my-2 mr-auto mb-auto ml-2 flex flex-col items-start justify-start select-none">
|
||||||
<h5 class=" text- text-md font-bold text-text-dark">{toast.title}</h5>
|
<h5 class=" text- text-md text-text-dark font-bold">{toast.title}</h5>
|
||||||
<p class=" text-md mb-2 overflow-x-hidden overflow-y-scroll text-text-muted-dark">
|
<p class=" text-md mb-2 overflow-x-hidden overflow-y-scroll text-muted">
|
||||||
{toast.message}
|
{toast.message}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -56,16 +56,13 @@
|
|||||||
<X
|
<X
|
||||||
stroke-width={3}
|
stroke-width={3}
|
||||||
size={18}
|
size={18}
|
||||||
class=" transition-all duration-200 hover:text-text-muted-dark active:scale-90"
|
class=" transition-all duration-200 hover:text-muted active:scale-90"
|
||||||
></X>
|
></X>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{#if !toast.hideProgress && toast.tween}
|
{#if !toast.hideProgress && toast.tween}
|
||||||
<div
|
<div style:padding-right={`${toast.tween.current}%`} class=" h-[2px] w-0 bg-primary"></div>
|
||||||
style:padding-right={`${toast.tween.current}%`}
|
|
||||||
class=" h-[2px] w-0 bg-primary-hover-dark"
|
|
||||||
></div>
|
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
{/each}
|
{/each}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { petals, type PetalsCleanup } from '$lib/stores/petals';
|
import { KeybindListener } from '$lib/termos/terminal/keybind_listenter';
|
||||||
|
import { SHELL_KEYBINDS } from '$lib/termos/util/shell_keybinds';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
|
|
||||||
let {
|
let {
|
||||||
@@ -14,39 +15,13 @@
|
|||||||
oninput?: (value: string) => void;
|
oninput?: (value: string) => void;
|
||||||
} = $props();
|
} = $props();
|
||||||
|
|
||||||
let container: HTMLElement;
|
let container: HTMLElement | undefined;
|
||||||
let cursorPos: number = $state(value.length);
|
let cursorPos: number = $derived(value.length);
|
||||||
let anchorPos: number | null = $state(null);
|
let text: string = $state('');
|
||||||
let isDragging: boolean = $state(false);
|
|
||||||
let focused: boolean = $state(false);
|
let focused: boolean = $state(false);
|
||||||
let blinkPaused: boolean = $state(false);
|
let blinkPaused: boolean = $state(false);
|
||||||
let blinkTimer: ReturnType<typeof setTimeout> | null = null;
|
let blinkTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
let cleanup: PetalsCleanup | null = null;
|
|
||||||
|
|
||||||
let sel = $derived.by(() => {
|
|
||||||
if (anchorPos === null || anchorPos === cursorPos) {
|
|
||||||
return { active: false, start: -1, end: -1 };
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
active: true,
|
|
||||||
start: Math.min(anchorPos, cursorPos),
|
|
||||||
end: Math.max(anchorPos, cursorPos)
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
function isSelected(i: number): boolean {
|
|
||||||
return sel.active && i >= sel.start && i < sel.end;
|
|
||||||
}
|
|
||||||
|
|
||||||
function gust(): void {
|
|
||||||
if (!container) return;
|
|
||||||
petals(container, { duration: 4000, swayAmp: 26, hideOriginals: false });
|
|
||||||
value = '';
|
|
||||||
cursorPos = 0;
|
|
||||||
anchorPos = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (autofocus && container) {
|
if (autofocus && container) {
|
||||||
container.focus();
|
container.focus();
|
||||||
@@ -62,32 +37,6 @@
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
$effect(() => {
|
|
||||||
if (cursorPos > value.length) cursorPos = value.length;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Global mousemove / mouseup during drag.
|
|
||||||
$effect(() => {
|
|
||||||
if (!isDragging) return;
|
|
||||||
|
|
||||||
const onMove = (e: MouseEvent) => {
|
|
||||||
const idx = charIndexFromEvent(e);
|
|
||||||
if (idx === null) return;
|
|
||||||
cursorPos = idx;
|
|
||||||
pauseBlink();
|
|
||||||
};
|
|
||||||
const onUp = () => {
|
|
||||||
isDragging = false;
|
|
||||||
};
|
|
||||||
|
|
||||||
window.addEventListener('mousemove', onMove);
|
|
||||||
window.addEventListener('mouseup', onUp);
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('mousemove', onMove);
|
|
||||||
window.removeEventListener('mouseup', onUp);
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
export function focusInput(): void {
|
export function focusInput(): void {
|
||||||
container?.focus();
|
container?.focus();
|
||||||
}
|
}
|
||||||
@@ -102,11 +51,14 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleFocus() {
|
function handleFocus() {
|
||||||
|
console.log('focused');
|
||||||
focused = true;
|
focused = true;
|
||||||
blinkPaused = false;
|
blinkPaused = false; // start blinking immediately
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleBlur() {
|
function handleBlur() {
|
||||||
|
console.log('blured');
|
||||||
|
|
||||||
focused = false;
|
focused = false;
|
||||||
if (blinkTimer) {
|
if (blinkTimer) {
|
||||||
clearTimeout(blinkTimer);
|
clearTimeout(blinkTimer);
|
||||||
@@ -115,161 +67,48 @@
|
|||||||
blinkPaused = true;
|
blinkPaused = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function charIndexFromEvent(e: MouseEvent): number | null {
|
function insertChar(char: string) {
|
||||||
const el = (e.target as HTMLElement | null)?.closest?.(
|
text = text.slice(0, cursorPos) + char + text.slice(cursorPos);
|
||||||
'[data-char-index]'
|
cursorPos += char.length;
|
||||||
) as HTMLElement | null;
|
|
||||||
if (!el) return null;
|
|
||||||
const raw = el.getAttribute('data-char-index');
|
|
||||||
return raw === null ? null : Number(raw);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getSelectedText(): string {
|
|
||||||
if (!sel.active) return '';
|
|
||||||
return value.slice(sel.start, sel.end);
|
|
||||||
}
|
|
||||||
|
|
||||||
function deleteSelection(): void {
|
|
||||||
if (!sel.active) return;
|
|
||||||
value = value.slice(0, sel.start) + value.slice(sel.end);
|
|
||||||
cursorPos = sel.start;
|
|
||||||
anchorPos = null;
|
|
||||||
oninput(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function insertChar(char: string): void {
|
|
||||||
if (sel.active) {
|
|
||||||
value = value.slice(0, sel.start) + char + value.slice(sel.end);
|
|
||||||
cursorPos = sel.start + char.length;
|
|
||||||
anchorPos = null;
|
|
||||||
} else {
|
|
||||||
value = value.slice(0, cursorPos) + char + value.slice(cursorPos);
|
|
||||||
cursorPos += char.length;
|
|
||||||
}
|
|
||||||
oninput(value);
|
|
||||||
pauseBlink();
|
pauseBlink();
|
||||||
}
|
}
|
||||||
|
|
||||||
function deleteCharBefore() {
|
function deleteCharBefore() {
|
||||||
if (sel.active) {
|
|
||||||
deleteSelection();
|
|
||||||
pauseBlink();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (cursorPos > 0) {
|
if (cursorPos > 0) {
|
||||||
value = value.slice(0, cursorPos - 1) + value.slice(cursorPos);
|
text = text.slice(0, cursorPos - 1) + text.slice(cursorPos);
|
||||||
oninput(value);
|
|
||||||
cursorPos--;
|
cursorPos--;
|
||||||
pauseBlink();
|
pauseBlink();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function deleteCharAfter() {
|
function deleteCharAfter() {
|
||||||
if (sel.active) {
|
if (cursorPos < text.length) {
|
||||||
deleteSelection();
|
text = text.slice(0, cursorPos) + text.slice(cursorPos + 1);
|
||||||
pauseBlink();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (cursorPos < value.length) {
|
|
||||||
value = value.slice(0, cursorPos) + value.slice(cursorPos + 1);
|
|
||||||
oninput(value);
|
|
||||||
pauseBlink();
|
pauseBlink();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function moveCursor(delta: number, extend: boolean) {
|
function moveCursor(delta: number) {
|
||||||
const newPos = cursorPos + delta;
|
const newPos = cursorPos + delta;
|
||||||
if (newPos < 0 || newPos > value.length) return;
|
if (newPos >= 0 && newPos <= text.length) {
|
||||||
if (extend) {
|
cursorPos = newPos;
|
||||||
if (anchorPos === null) anchorPos = cursorPos;
|
pauseBlink();
|
||||||
} else {
|
|
||||||
anchorPos = null;
|
|
||||||
}
|
}
|
||||||
cursorPos = newPos;
|
|
||||||
pauseBlink();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function moveTo(pos: number, extend: boolean) {
|
function handleKeydown(e: KeyboardEvent) {
|
||||||
if (extend) {
|
console.log(e.key);
|
||||||
if (anchorPos === null) anchorPos = cursorPos;
|
|
||||||
} else {
|
|
||||||
anchorPos = null;
|
|
||||||
}
|
|
||||||
cursorPos = pos;
|
|
||||||
pauseBlink();
|
|
||||||
}
|
|
||||||
|
|
||||||
function prevWordBoundary(pos: number): number {
|
if (e.ctrlKey) {
|
||||||
let i = pos;
|
|
||||||
while (i > 0 && !/\s/.test(value[i - 1])) i--;
|
|
||||||
while (i > 0 && /\s/.test(value[i - 1])) i--;
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
|
|
||||||
function nextWordBoundary(pos: number): number {
|
|
||||||
let i = pos;
|
|
||||||
while (i < value.length && !/\s/.test(value[i])) i++;
|
|
||||||
while (i < value.length && /\s/.test(value[i])) i++;
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
|
|
||||||
function handleMouseDown(e: MouseEvent): void {
|
|
||||||
e.preventDefault();
|
|
||||||
const idx = charIndexFromEvent(e);
|
|
||||||
const clickPos = idx ?? value.length;
|
|
||||||
|
|
||||||
if (e.shiftKey) {
|
|
||||||
if (anchorPos === null) anchorPos = cursorPos;
|
|
||||||
cursorPos = clickPos;
|
|
||||||
} else {
|
|
||||||
anchorPos = clickPos;
|
|
||||||
cursorPos = clickPos;
|
|
||||||
}
|
|
||||||
isDragging = true;
|
|
||||||
pauseBlink();
|
|
||||||
}
|
|
||||||
|
|
||||||
function handlePaste(e: ClipboardEvent): void {
|
|
||||||
e.preventDefault();
|
|
||||||
const text = e.clipboardData?.getData('text/plain') ?? '';
|
|
||||||
if (text) insertChar(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
function copySelection(): void {
|
|
||||||
if (!sel.active) return;
|
|
||||||
void navigator.clipboard.writeText(getSelectedText());
|
|
||||||
}
|
|
||||||
|
|
||||||
function cutSelection(): void {
|
|
||||||
if (!sel.active) return;
|
|
||||||
void navigator.clipboard.writeText(getSelectedText());
|
|
||||||
deleteSelection();
|
|
||||||
pauseBlink();
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleKeydown(e: KeyboardEvent) {
|
|
||||||
if (e.ctrlKey || e.metaKey) {
|
|
||||||
if (e.key === 'a' || e.key === 'A') {
|
if (e.key === 'a' || e.key === 'A') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
anchorPos = 0;
|
cursorPos = 0;
|
||||||
cursorPos = value.length;
|
|
||||||
pauseBlink();
|
pauseBlink();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (e.key === 'c' || e.key === 'C') {
|
|
||||||
e.preventDefault();
|
|
||||||
copySelection();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (e.key === 'x' || e.key === 'X') {
|
|
||||||
e.preventDefault();
|
|
||||||
cutSelection();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (e.key === 'e' || e.key === 'E') {
|
if (e.key === 'e' || e.key === 'E') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
anchorPos = null;
|
cursorPos = text.length;
|
||||||
cursorPos = value.length;
|
|
||||||
pauseBlink();
|
pauseBlink();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -278,50 +117,46 @@
|
|||||||
deleteCharAfter();
|
deleteCharAfter();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (e.key === 'Home') {
|
|
||||||
e.preventDefault();
|
|
||||||
moveTo(0, e.shiftKey);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (e.key === 'End') {
|
|
||||||
e.preventDefault();
|
|
||||||
moveTo(value.length, e.shiftKey);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (e.key === 'ArrowLeft') {
|
if (e.key === 'ArrowLeft') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
moveTo(prevWordBoundary(cursorPos), e.shiftKey);
|
cursorPos = 0;
|
||||||
|
pauseBlink();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (e.key === 'ArrowRight') {
|
if (e.key === 'ArrowRight') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
moveTo(nextWordBoundary(cursorPos), e.shiftKey);
|
cursorPos = text.length;
|
||||||
|
pauseBlink();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// ignore other Ctrl combos
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Arrow keys
|
// Arrow keys
|
||||||
if (e.key === 'ArrowLeft') {
|
if (e.key === 'ArrowLeft') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
moveCursor(-1, e.shiftKey);
|
moveCursor(-1);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (e.key === 'ArrowRight') {
|
if (e.key === 'ArrowRight') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
moveCursor(1, e.shiftKey);
|
moveCursor(1);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Home / End
|
// Home / End
|
||||||
if (e.key === 'Home') {
|
if (e.key === 'Home') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
moveTo(0, e.shiftKey);
|
cursorPos = 0;
|
||||||
|
pauseBlink();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (e.key === 'End') {
|
if (e.key === 'End') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
moveTo(value.length, e.shiftKey);
|
cursorPos = text.length;
|
||||||
|
pauseBlink();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,21 +172,21 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Printable characters
|
// Printable characters (length === 1 and no modifier)
|
||||||
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
insertChar(e.key);
|
insertChar(e.key);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (e.key === 'Enter') {
|
// Everything else (Enter, Tab, etc.) is ignored.EEE
|
||||||
e.preventDefault();
|
|
||||||
gust();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
|
const keybindListener = new KeybindListener(container!);
|
||||||
|
|
||||||
|
keybindListener.registerKeybinds(SHELL_KEYBINDS);
|
||||||
|
|
||||||
if (autofocus && container) {
|
if (autofocus && container) {
|
||||||
container.focus();
|
container.focus();
|
||||||
}
|
}
|
||||||
@@ -360,7 +195,7 @@
|
|||||||
|
|
||||||
<div
|
<div
|
||||||
id="terminal-input"
|
id="terminal-input"
|
||||||
class="relative inline-block font-terminal whitespace-nowrap outline-none select-none"
|
class=" relative inline-block font-terminal whitespace-nowrap outline-none select-none"
|
||||||
bind:this={container}
|
bind:this={container}
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
role="textbox"
|
role="textbox"
|
||||||
@@ -368,49 +203,22 @@
|
|||||||
onblur={handleBlur}
|
onblur={handleBlur}
|
||||||
onfocus={handleFocus}
|
onfocus={handleFocus}
|
||||||
onkeydown={handleKeydown}
|
onkeydown={handleKeydown}
|
||||||
onpaste={handlePaste}
|
|
||||||
onmousedown={handleMouseDown}
|
|
||||||
style="--cursor-index: {cursorPos};"
|
style="--cursor-index: {cursorPos};"
|
||||||
>
|
>
|
||||||
<span class="prompt inline-block w-[1ch] text-center">$</span>
|
<span class="prompt inline-block w-[1ch] text-center">$</span>
|
||||||
<span class="inline cursor-text" aria-hidden="true">
|
<span class="inline cursor-text" aria-hidden="true">
|
||||||
{#each value.split('') as char, i}
|
{#each text.split('') as char}
|
||||||
<span
|
<span class="inline-block w-[1ch] text-center">{char}</span>
|
||||||
class="char inline-block w-[1ch] text-center whitespace-pre"
|
|
||||||
class:selected={isSelected(i)}
|
|
||||||
data-char-index={i}>{char}</span
|
|
||||||
>
|
|
||||||
{/each}
|
{/each}
|
||||||
</span>
|
</span>
|
||||||
<div
|
<div
|
||||||
id="curs"
|
|
||||||
class="cursor absolute bottom-[0.2rem] h-px w-[1ch] bg-text-primary"
|
class="cursor absolute bottom-[0.2rem] h-px w-[1ch] bg-text-primary"
|
||||||
class:animate-cursor-blink={!blinkPaused && !sel.active}
|
class:animate-cursor-blink={!blinkPaused}
|
||||||
></div>
|
></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.cursor {
|
.cursor {
|
||||||
left: calc(var(--cursor-index) * 1ch + 8.5px + 1ch);
|
left: calc(var(--cursor-index) * 1ch + 8.5px + 1ch);
|
||||||
transition: all 0.1s ease;
|
|
||||||
}
|
|
||||||
.char {
|
|
||||||
transition: all linear 0.1s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.char.selected {
|
|
||||||
transition: none;
|
|
||||||
background-color: var(--color-highlight);
|
|
||||||
border-radius: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.char.selected + .char.selected {
|
|
||||||
border-top-left-radius: 0;
|
|
||||||
border-bottom-left-radius: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.char.selected:has(+ .char.selected) {
|
|
||||||
border-top-right-radius: 0;
|
|
||||||
border-bottom-right-radius: 0;
|
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
/* import { db } from '$lib/server/db';
|
import { db } from '$lib/server/db';
|
||||||
import { config } from '$lib/server/db/schema';
|
import { config } from '$lib/server/db/schema';
|
||||||
import { PASSWD } from '$lib/stores/bash/etc/userData';
|
import { PASSWD } from '$lib/stores/bash/etc/userData';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
@@ -36,4 +36,3 @@ export const load: PageServerLoad = async () => {
|
|||||||
throw error(500, 'Database query failed');
|
throw error(500, 'Database query failed');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
*/
|
|
||||||
|
|||||||
@@ -1,19 +1,12 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import Login from '../modules/Login.svelte';
|
||||||
import Maintenence from '../modules/Maintenence.svelte';
|
import Maintenence from '../modules/Maintenence.svelte';
|
||||||
import Settings from '../modules/Settings.svelte';
|
import Settings from '../modules/Settings.svelte';
|
||||||
import Terminal from '../modules/Terminal.svelte';
|
import Terminal from '../modules/Terminal.svelte';
|
||||||
|
|
||||||
import { loadBubblePacks, loadStates } from '$lib/shimagic';
|
|
||||||
import { CHATTER } from '$lib/shimagic/chatter';
|
|
||||||
import { NEEDS } from '$lib/shimagic/needs';
|
|
||||||
import Shimeji from '$lib/shimagic/Shimeji.svelte';
|
|
||||||
|
|
||||||
const states = loadStates();
|
|
||||||
const bubblePacks = loadBubblePacks({ fps: 8, duration: 2.5 });
|
|
||||||
|
|
||||||
let { form, data } = $props();
|
let { form, data } = $props();
|
||||||
|
|
||||||
const MAINTENANCE = false;
|
const MAINTENANCE = $derived(Boolean(data.config[0]));
|
||||||
let username = $state('');
|
let username = $state('');
|
||||||
|
|
||||||
function welcomeSequence() {
|
function welcomeSequence() {
|
||||||
@@ -41,7 +34,7 @@
|
|||||||
<Maintenence />
|
<Maintenence />
|
||||||
{:else}
|
{:else}
|
||||||
<Settings></Settings>
|
<Settings></Settings>
|
||||||
<!-- <div
|
<div
|
||||||
bind:this={bound}
|
bind:this={bound}
|
||||||
id="main"
|
id="main"
|
||||||
class="relative flex h-screen w-full items-center justify-center p-24"
|
class="relative flex h-screen w-full items-center justify-center p-24"
|
||||||
@@ -53,11 +46,9 @@
|
|||||||
<Login init={initializer} {form} />
|
<Login init={initializer} {form} />
|
||||||
</div>
|
</div>
|
||||||
<div id="wrapper2" class=" {form?.success ? 'intro' : ''}">
|
<div id="wrapper2" class=" {form?.success ? 'intro' : ''}">
|
||||||
|
<Terminal {username} {bound}></Terminal>
|
||||||
</div>
|
</div>
|
||||||
</div> -->
|
</div>
|
||||||
<Terminal username="gornodox"></Terminal>
|
|
||||||
<Shimeji {states} {bubblePacks} needsConfig={NEEDS} chatter={CHATTER} scale={4} />
|
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<script>
|
||||||
|
import Terminal from '../../modules/Terminal.svelte';
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<Terminal username="test"></Terminal>
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Space+Mono:ital,wght@0,400;0,700;1,400;1,700&display=swap');
|
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Space+Mono:ital,wght@0,400;0,700;1,400;1,700&display=swap');
|
||||||
@import url('https://fonts.googleapis.com/css2?family=Micro+5&family=Press+Start+2P&display=swap');
|
|
||||||
@import 'tailwindcss';
|
@import 'tailwindcss';
|
||||||
@import './animations.css';
|
@import './animations.css';
|
||||||
@custom-variant light (&:where(.light, .light *));
|
@custom-variant light (&:where(.light, .light *));
|
||||||
@@ -291,10 +290,6 @@
|
|||||||
--lang-cs: oklch(0.55 0.27927 141.446);
|
--lang-cs: oklch(0.55 0.27927 141.446);
|
||||||
--lang-cpp: oklch(0.6 0.15576 6.88);
|
--lang-cpp: oklch(0.6 0.15576 6.88);
|
||||||
|
|
||||||
* {
|
|
||||||
transition: var(--transition-standard);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|
||||||
#underline-bg
|
#underline-bg
|
||||||
|
|||||||