Compare commits
99 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
216ada5568 | ||
|
|
449e25e0f3 | ||
|
|
3cbb95831c | ||
|
|
146baf1d23 | ||
|
|
e7cc716590 | ||
|
|
3aa2d549d1 | ||
|
|
901012064a | ||
|
|
bf2336a172 | ||
|
|
708a112449 | ||
|
|
ff2ee3d6db | ||
|
|
6bc04830d3 | ||
|
|
589bb365bd | ||
|
|
0b8a43eb91 | ||
|
|
bb3087dc37 | ||
|
|
92f56570d9 | ||
|
|
938da0d4dc | ||
|
|
3d94859151 | ||
|
|
a85b1873dd | ||
|
|
446ad080e1 | ||
|
|
ead61e648a | ||
|
|
600fbfd3b7 | ||
|
|
f3031d6cd0 | ||
|
|
7152ae093e | ||
|
|
2bd93ff9e0 | ||
|
|
f68e45f898 | ||
|
|
7eca07c7d1 | ||
|
|
ee4ec2fc39 | ||
|
|
b93a5a3ac0 | ||
|
|
de63e0e52d | ||
|
|
daef2fd2f2 | ||
|
|
6705ce8980 | ||
|
|
f443816355 | ||
|
|
c8c08d5fbe | ||
|
|
b8328657df | ||
|
|
8d235ddf12 | ||
|
|
05f284e3fa | ||
|
|
566baa250c | ||
|
|
19a8bd41a9 | ||
|
|
58cad839b6 | ||
|
|
34035ae6ac | ||
|
|
3a4547fb80 | ||
|
|
86b21bb6dd | ||
|
|
8cf114cbb4 | ||
|
|
f9100da8a2 | ||
|
|
f9c1a3e71a | ||
|
|
73594c8599 | ||
|
|
239f35389e | ||
|
|
95d3296dd9 | ||
|
|
c566f90d16 | ||
|
|
9410af3a69 | ||
|
|
8627fc52ef | ||
|
|
813cc8dbbc | ||
|
|
d90d81d7ff | ||
|
|
b1f62cc58c | ||
|
|
38da997069 | ||
|
|
88d5f6455b | ||
|
|
eb3a41be69 | ||
|
|
1332af93ab | ||
|
|
93adf50498 | ||
|
|
291fd9ead0 | ||
|
|
e86138ec00 | ||
|
|
c431f117e9 | ||
|
|
847a3ef314 | ||
|
|
bab09fed6d | ||
|
|
d56c983e01 | ||
|
|
69df7302d5 | ||
|
|
01f7e715a4 | ||
|
|
e71a823848 | ||
|
|
a8865594ca | ||
|
|
23d764c534 | ||
|
|
c7aee73dcb | ||
|
|
925d1fc437 | ||
|
|
a6dbedb3cd | ||
|
|
74a6b9bfe6 | ||
|
|
40126060fb | ||
|
|
6032c034bc | ||
|
|
6b4062eee6 | ||
|
|
0ea21e86eb | ||
|
|
30c5da879b | ||
|
|
1a76081fec | ||
|
|
045c4b49ef | ||
|
|
af0996f6ab | ||
|
|
6c390aeae3 | ||
|
|
e9519484cc | ||
|
|
b7da920f31 | ||
|
|
35647a5c5b | ||
|
|
8ea8f7fec7 | ||
|
|
5254b84704 | ||
|
|
f728a217c9 | ||
|
|
c27817b73a | ||
|
|
7ea79c8ced | ||
|
|
fb10c63882 | ||
|
|
96ef8ccba3 | ||
|
|
6148f18340 | ||
|
|
867a18e788 | ||
|
|
387c4364b5 | ||
|
|
60dce4a08f | ||
|
|
d2325c20bd | ||
|
|
29295607df |
306
.github/workflows/build.yml
vendored
@@ -1,13 +1,15 @@
|
||||
name: Build
|
||||
name: Build and Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "*" ]
|
||||
tags: [ "v*" ]
|
||||
pull_request:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# LINUX BUILD
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
build-linux:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
@@ -15,44 +17,16 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Check Out Code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Cache SDL3 (Linux)
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
sdl3
|
||||
sdl3-build
|
||||
key: sdl3-linux-${{ hashFiles('sdl3/CMakeLists.txt') }}
|
||||
|
||||
- name: Build SDL3 (Linux)
|
||||
run: |
|
||||
if [ ! -d "sdl3/.git" ]; then
|
||||
echo "Cloning SDL3 repository..."
|
||||
git clone --depth 1 --branch main https://github.com/libsdl-org/SDL.git sdl3
|
||||
else
|
||||
echo "SDL3 source is already present (possibly from cache)."
|
||||
fi
|
||||
|
||||
mkdir -p sdl3-build
|
||||
cd sdl3-build
|
||||
cmake ../sdl3 -GNinja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX="${PWD}/installed_sdl3" \
|
||||
-DSDL_SHARED=ON \
|
||||
-DSDL_STATIC=OFF
|
||||
ninja
|
||||
ninja install
|
||||
uses: actions/checkout@v4
|
||||
with: { fetch-depth: 0 }
|
||||
|
||||
- name: Build Prosperon (Linux)
|
||||
run: |
|
||||
export PKG_CONFIG_PATH="${PWD}/sdl3-build/installed_sdl3/lib/pkgconfig:$PKG_CONFIG_PATH"
|
||||
meson setup build -Dbuildtype=release -Db_lto=true -Db_ndebug=true
|
||||
meson setup build -Dbuildtype=release -Db_lto=true -Db_lto_mode=thin -Db_ndebug=true
|
||||
meson compile -C build
|
||||
|
||||
- name: Test Prosperon (Linux)
|
||||
env:
|
||||
TRACY_NO_INVARIANT_CHECK: 1
|
||||
env: { TRACY_NO_INVARIANT_CHECK: 1 }
|
||||
run: |
|
||||
meson test --print-errorlogs -C build
|
||||
|
||||
@@ -63,102 +37,117 @@ jobs:
|
||||
name: testlog-linux
|
||||
path: build/meson-logs/testlog.txt
|
||||
|
||||
- name: Create artifact folder (Linux)
|
||||
if: ${{ github.event_name == 'release' && github.event.action == 'published' }}
|
||||
run: |
|
||||
mkdir _pack
|
||||
cp build/prosperon _pack/
|
||||
cp sdl3-build/installed_sdl3/lib/libSDL3.so _pack/
|
||||
|
||||
- name: Upload Artifact (Linux)
|
||||
if: ${{ github.event_name == 'release' && github.event.action == 'published' }}
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: prosperon-artifacts-linux
|
||||
path: _pack
|
||||
path: build/prosperon
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# WINDOWS BUILD (MSYS2 / CLANG64)
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
build-windows:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: gitea.pockle.world/john/prosperon/linux:latest
|
||||
runs-on: win-native
|
||||
strategy:
|
||||
matrix: { msystem: [ CLANG64 ] }
|
||||
|
||||
steps:
|
||||
- name: Check Out Code
|
||||
uses: actions/checkout@v3
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Cache SDL3 (Windows cross)
|
||||
uses: actions/cache@v3
|
||||
- name: Setup MSYS2
|
||||
uses: msys2/setup-msys2@v2
|
||||
with:
|
||||
path: |
|
||||
sdl3-win
|
||||
sdl3-build-win
|
||||
key: sdl3-win-${{ hashFiles('sdl3-win/CMakeLists.txt') }}
|
||||
msystem: ${{ matrix.msystem }}
|
||||
update: true
|
||||
cache: true
|
||||
install: |
|
||||
git zip gzip tar base-devel
|
||||
pacboy: |
|
||||
meson
|
||||
cmake
|
||||
toolchain
|
||||
|
||||
- name: Build SDL3 (Windows cross)
|
||||
- name: Build Prosperon (Windows)
|
||||
shell: msys2 {0}
|
||||
run: |
|
||||
if [ ! -d "sdl3-win/.git" ]; then
|
||||
echo "Cloning SDL3 for Windows cross..."
|
||||
git clone --depth 1 --branch main https://github.com/libsdl-org/SDL.git sdl3-win
|
||||
else
|
||||
echo "SDL3-win source already present (possibly from cache)."
|
||||
fi
|
||||
|
||||
mkdir -p sdl3-build-win
|
||||
cd sdl3-build-win
|
||||
cmake ../sdl3-win -GNinja \
|
||||
-DCMAKE_SYSTEM_NAME=Windows \
|
||||
-DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc \
|
||||
-DCMAKE_CXX_COMPILER=x86_64-w64-mingw32-g++ \
|
||||
-DCMAKE_RC_COMPILER=x86_64-w64-mingw32-windres \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX="${PWD}/installed_sdl3_win" \
|
||||
-DSDL_SHARED=ON \
|
||||
-DSDL_STATIC=OFF
|
||||
ninja
|
||||
ninja install
|
||||
|
||||
- name: Configure PKG_CONFIG_PATH (Windows cross)
|
||||
run: |
|
||||
echo "PKG_CONFIG_PATH=${GITHUB_WORKSPACE}/sdl3-build-win/installed_sdl3_win/lib/pkgconfig:$PKG_CONFIG_PATH" >> $GITHUB_ENV
|
||||
|
||||
- name: Build Prosperon (Windows cross)
|
||||
run: |
|
||||
meson setup build -Dbuildtype=release -Db_lto=true -Db_ndebug=true --cross-file mingw32.cross
|
||||
meson setup build -Dbuildtype=release -Db_lto=true -Db_lto_mode=thin -Db_ndebug=true -Dtracy:only_localhost=true -Dtracy:no_broadcast=true
|
||||
meson compile -C build
|
||||
|
||||
- name: Test Prosperon
|
||||
|
||||
- name: Test Prosperon (Windows)
|
||||
shell: msys2 {0}
|
||||
env:
|
||||
TRACY_NO_INVARIANT_CHECK: 1
|
||||
run: |
|
||||
meson test --print-errorlogs -C build
|
||||
|
||||
- name: Upload Test Log
|
||||
|
||||
- name: Upload Test Log (Windows)
|
||||
if: ${{ always() }}
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: testlog-linux
|
||||
name: testlog-windows
|
||||
path: build/meson-logs/testlog.txt
|
||||
|
||||
- name: Create package folder
|
||||
run: |
|
||||
mkdir _pack
|
||||
cp build/prosperon.exe _pack/
|
||||
cp sdl3-build-win/installed_sdl3_win/bin/SDL3.dll _pack/
|
||||
|
||||
- name: Upload Artifact (Windows cross)
|
||||
if: ${{ github.event_name == 'release' && github.event.action == 'published' }}
|
||||
- name: Upload Artifact (Windows)
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: prosperon-artifacts-windows
|
||||
path: _pack
|
||||
path: build/prosperon.exe
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# MACOS BUILD
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
build-macos:
|
||||
runs-on: macos-latest
|
||||
|
||||
steps:
|
||||
- name: Check Out Code
|
||||
uses: actions/checkout@v4
|
||||
with: { fetch-depth: 0 }
|
||||
|
||||
- name: Build Prosperon (macOS)
|
||||
run: |
|
||||
meson setup build -Dbuildtype=release -Db_lto=true -Db_lto_mode=thin -Db_ndebug=true
|
||||
meson compile -C build
|
||||
|
||||
- name: Test Prosperon (macOS)
|
||||
run: |
|
||||
meson test --print-errorlogs -C build
|
||||
|
||||
- name: Upload Test Log (macOS)
|
||||
if: ${{ always() }}
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: testlog-macos
|
||||
path: build/meson-logs/testlog.txt
|
||||
|
||||
- name: Upload Artifact (macOS)
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: prosperon-artifacts-macos
|
||||
path: build/prosperon
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# PACKAGE CROSS-PLATFORM DIST
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
package-dist:
|
||||
if: ${{ github.event_name == 'release' && github.event.action == 'published' }}
|
||||
needs: [build-linux, build-windows]
|
||||
needs: [ build-linux, build-windows, build-macos ]
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Check Out Code
|
||||
uses: actions/checkout@v3
|
||||
with: { fetch-depth: 0 }
|
||||
|
||||
- name: Get Latest Tag
|
||||
id: get_tag
|
||||
run: |
|
||||
TAG=$(git describe --tags --abbrev=0)
|
||||
echo "tag=$TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Download Linux Artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
@@ -172,24 +161,115 @@ jobs:
|
||||
name: prosperon-artifacts-windows
|
||||
path: windows_artifacts
|
||||
|
||||
- name: Create the Dist Folder
|
||||
- name: Download macOS Artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: prosperon-artifacts-macos
|
||||
path: mac_artifacts
|
||||
|
||||
- name: Create Dist Folder
|
||||
run: |
|
||||
mkdir dist
|
||||
|
||||
cp README.md dist/
|
||||
cp license.txt dist/
|
||||
cp -r examples dist/
|
||||
|
||||
# Make subdirectories for each platform
|
||||
mkdir dist/linux
|
||||
mkdir dist/win
|
||||
|
||||
# Copy artifacts in
|
||||
cp linux_artifacts/* dist/linux/
|
||||
mkdir -p dist/linux dist/win dist/mac
|
||||
cp README.md dist/
|
||||
cp license.txt dist/
|
||||
cp -r examples dist/
|
||||
cp linux_artifacts/* dist/linux/
|
||||
cp windows_artifacts/* dist/win/
|
||||
cp mac_artifacts/* dist/mac/
|
||||
|
||||
- name: Package Final Dist
|
||||
run: |
|
||||
TAG=${{ steps.get_tag.outputs.tag }}
|
||||
zip -r "prosperon-${TAG}.zip" dist
|
||||
echo "Created prosperon-${TAG}.zip"
|
||||
|
||||
- name: Upload Final Dist
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: prosperon
|
||||
name: "prosperon-${{ steps.get_tag.outputs.tag }}"
|
||||
path: "prosperon-${{ steps.get_tag.outputs.tag }}.zip"
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# DEPLOY TO ITCH.IO (single ZIP containing all OSes)
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
deploy-itch:
|
||||
needs: [ package-dist ]
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Check Out Code
|
||||
uses: actions/checkout@v3
|
||||
with: { fetch-depth: 0 }
|
||||
|
||||
- name: Get Latest Tag
|
||||
id: get_tag
|
||||
run: |
|
||||
TAG=$(git describe --tags --abbrev=0)
|
||||
echo "tag=$TAG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Download Final Distribution
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: "prosperon-${{ steps.get_tag.outputs.tag }}"
|
||||
path: dist
|
||||
|
||||
- name: Set up Butler
|
||||
uses: jdno/setup-butler@v1
|
||||
|
||||
- name: Push to itch.io
|
||||
run: |
|
||||
butler push "dist/prosperon-${{ steps.get_tag.outputs.tag }}.zip" \
|
||||
${{ secrets.ITCHIO_USERNAME }}/prosperon:universal \
|
||||
--userversion ${{ steps.get_tag.outputs.tag }}
|
||||
env:
|
||||
BUTLER_API_KEY: ${{ secrets.ITCHIO_API_KEY }}
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# DEPLOY TO SELF-HOSTED GITEA
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
deploy-gitea:
|
||||
needs: [ package-dist ]
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Check Out Code
|
||||
uses: actions/checkout@v3
|
||||
with: { fetch-depth: 0 }
|
||||
|
||||
- name: Get Latest Tag & Commit Message
|
||||
id: get_tag
|
||||
run: |
|
||||
TAG=$(git describe --tags --abbrev=0)
|
||||
COMMIT_MSG=$(git log -1 --pretty=%B "$TAG")
|
||||
echo "tag=$TAG" >> $GITHUB_OUTPUT
|
||||
echo "commit_msg=$COMMIT_MSG" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Download Final Distribution
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: "prosperon-${{ steps.get_tag.outputs.tag }}"
|
||||
path: dist
|
||||
|
||||
- name: Create / Update Gitea Release
|
||||
run: |
|
||||
TAG=${{ steps.get_tag.outputs.tag }}
|
||||
ZIP=dist/prosperon-${TAG}.zip
|
||||
BODY=$(echo "${{ steps.get_tag.outputs.commit_msg }}" | jq -R -s '.')
|
||||
RELEASE=$(curl -s -H "Authorization: token ${{ secrets.TOKEN_GITEA }}" \
|
||||
"https://gitea.pockle.world/api/v1/repos/john/prosperon/releases/tags/$TAG" | jq -r '.id')
|
||||
|
||||
if [ "$RELEASE" = "null" ] || [ -z "$RELEASE" ]; then
|
||||
RELEASE=$(curl -X POST \
|
||||
-H "Authorization: token ${{ secrets.TOKEN_GITEA }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"$TAG\",\"target_commitish\":\"${{ github.sha }}\",\"name\":\"$TAG\",\"body\":$BODY,\"draft\":false,\"prerelease\":false}" \
|
||||
"https://gitea.pockle.world/api/v1/repos/john/prosperon/releases" | jq -r '.id')
|
||||
fi
|
||||
|
||||
curl -X POST \
|
||||
-H "Authorization: token ${{ secrets.TOKEN_GITEA }}" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @"$ZIP" \
|
||||
"https://gitea.pockle.world/api/v1/repos/john/prosperon/releases/$RELEASE/assets?name=prosperon-${TAG}.zip"
|
||||
env:
|
||||
TOKEN_GITEA: ${{ secrets.TOKEN_GITEA }}
|
||||
|
||||
64
.github/workflows/macbuild.yml
vendored
@@ -1,64 +0,0 @@
|
||||
name: Build
|
||||
|
||||
jobs:
|
||||
# ===============================================================
|
||||
# MACOS BUILD (Using Homebrew SDL3)
|
||||
# ===============================================================
|
||||
build-macos:
|
||||
runs-on: macos-latest
|
||||
continue-on-error: true
|
||||
steps:
|
||||
# 1) Check out code
|
||||
- name: Check Out Code
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# 2) Install dependencies (SDL3 via Homebrew) + ccache
|
||||
- name: Install Dependencies (macOS)
|
||||
run: |
|
||||
brew update
|
||||
brew install sdl3 meson ninja cmake ccache
|
||||
|
||||
# 3) Configure ccache
|
||||
- name: Configure ccache
|
||||
run: |
|
||||
echo "CMAKE_C_COMPILER_LAUNCHER=ccache" >> $GITHUB_ENV
|
||||
echo "CMAKE_CXX_COMPILER_LAUNCHER=ccache" >> $GITHUB_ENV
|
||||
|
||||
# 4) Cache ccache
|
||||
- name: Cache ccache
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/Library/Caches/ccache
|
||||
key: ccache-macos-${{ hashFiles('**/*.c', '**/*.cpp', '**/*.h', '**/CMakeLists.txt', '**/meson.build') }}
|
||||
restore-keys: |
|
||||
ccache-macos-
|
||||
|
||||
# 5) Build Prosperon (macOS) linking against Homebrew's SDL3
|
||||
- name: Build Prosperon (macOS)
|
||||
run: |
|
||||
# Ensure pkg-config can find Homebrew's SDL3 .pc files
|
||||
export PKG_CONFIG_PATH="$(brew --prefix sdl3)/lib/pkgconfig:$PKG_CONFIG_PATH"
|
||||
meson setup build_macos -Dbuildtype=release -Db_lto=true -Db_ndebug=true
|
||||
meson compile -C build_macos
|
||||
|
||||
# 6) Copy SDL3 .dylib from Homebrew for packaging
|
||||
- name: Copy SDL3 library for packaging
|
||||
run: |
|
||||
SDL3_PREFIX=$(brew --prefix sdl3)
|
||||
mkdir -p sdl3-macos
|
||||
# Copy all versions of the SDL3 dynamic library
|
||||
cp -a "${SDL3_PREFIX}/lib/libSDL3*.dylib" sdl3-macos/ || echo "No .dylib found, ignoring"
|
||||
|
||||
# 7) Create minimal artifact folder (macOS)
|
||||
- name: Create artifact folder (macOS)
|
||||
run: |
|
||||
mkdir _pack
|
||||
cp build_macos/prosperon _pack/
|
||||
cp sdl3-macos/libSDL3*.dylib _pack/ || echo "No .dylib found, ignoring"
|
||||
|
||||
# 8) Upload artifact (macOS)
|
||||
- name: Upload Artifact (macOS)
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: prosperon-artifacts-macos
|
||||
path: _pack
|
||||
1
.gitignore
vendored
@@ -29,3 +29,4 @@ game.zip
|
||||
icon.ico
|
||||
steam/
|
||||
subprojects/*/
|
||||
build_dbg/
|
||||
27
AGENTS.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# AGENTS.md
|
||||
|
||||
## Project Overview
|
||||
This is a game engine developed using a QuickJS fork as its scripting language. It is an actor based system, based on Douglas Crockford's Misty. It is a Meson compiled project with a number of dependencies.
|
||||
|
||||
## File Structure
|
||||
- `source/`: Contains the C source code
|
||||
- `scripts/`: Contains script code that is loaded on executable start, and modules
|
||||
- `shaders/`: Contains shaders that ship with the engine (for shader based backends)
|
||||
- `benchmarks/`: Benchmark programs for testing speed
|
||||
- `tests/`: Unit tests
|
||||
- `examples/`: Contains full game examples
|
||||
|
||||
## Coding Practices
|
||||
- Use K&R style C
|
||||
- Use as little whitespace as possible
|
||||
- Javascript style prefers objects and prototypical inheritence over ES6 classes, liberal use of closures, and var everywhere
|
||||
|
||||
## Instructions
|
||||
- When generating code, adhere to the coding practices outlined above.
|
||||
- When adding new features, ensure they align with the project's goals.
|
||||
- When fixing bugs, review the code carefully before making changes.
|
||||
- When writing unit tests, cover all important scenarios.
|
||||
|
||||
## Compiling, running, and testing
|
||||
- To compile the code, run "make", which generates a prosperon executable in build_dbg/, and copy it into the root folder
|
||||
- Run a test by giving it as its command: so ./prosperon tests/overling.js would run the test overling.js, ./prosperon tests/nota.js runs the nota benchmark
|
||||
371
CLAUDE.md
Normal file
@@ -0,0 +1,371 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Build Commands
|
||||
|
||||
### Build variants
|
||||
- `make debug` - Build debug version (uses meson debug configuration)
|
||||
- `make fast` - Build optimized version
|
||||
- `make release` - Build release version with LTO and optimizations
|
||||
- `make small` - Build minimal size version
|
||||
- `make web` - Build for web/emscripten platform
|
||||
- `make crosswin` - Cross-compile for Windows using mingw32
|
||||
|
||||
### Testing
|
||||
- `meson test -C build_dbg` - Run all tests in debug build
|
||||
- `meson test -C build_<variant>` - Run tests in specific build variant
|
||||
- `./build_dbg/prosperon tests/<testname>.js` - Run specific test
|
||||
- Available tests: `spawn_actor`, `empty`, `nota`, `wota`, `portalspawner`, `overling`, `send`, `delay`
|
||||
|
||||
### Common development commands
|
||||
- `meson setup build_<variant>` - Configure build directory
|
||||
- `meson compile -C build_<variant>` - Compile in build directory
|
||||
- `./build_dbg/prosperon examples/<example>` - Run example from build directory
|
||||
- Copy prosperon to game directory and run: `cp build_dbg/prosperon <game-dir>/ && cd <game-dir> && ./prosperon`
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
Prosperon is an actor-based game engine inspired by Douglas Crockford's Misty system. Key architectural principles:
|
||||
|
||||
### Actor Model
|
||||
- Each actor runs on its own thread
|
||||
- Communication only through message passing (no shared JavaScript objects)
|
||||
- Hierarchical actor system with spawning/killing
|
||||
- Actor lifecycle: awake, update, draw, garbage collection
|
||||
|
||||
### JavaScript Style Guide
|
||||
- Use `use()` function for imports (Misty-style, not ES6 import/export)
|
||||
- Prefer closures and javascript objects and prototypes over ES6 style classes
|
||||
- Follow existing JavaScript patterns in the codebase
|
||||
- Functions as first-class citizens
|
||||
- Do not use const or let; only var
|
||||
|
||||
### Core Systems
|
||||
1. **Actor System** (scripts/core/engine.js)
|
||||
- Message passing via `$_.send()`, `$_.receive()`
|
||||
- Actor spawning/management
|
||||
- Register-based component system (update, draw, gui, etc.)
|
||||
|
||||
2. **Module System**
|
||||
- `use()` function for loading modules
|
||||
- Module paths: `scripts/modules/`, `scripts/modules/ext/`
|
||||
- Custom QuickJS build with embedded C modules
|
||||
|
||||
3. **Build System**
|
||||
- Meson build configuration (Makefile is convenience wrapper)
|
||||
- Multiple platform targets (Windows, macOS, Linux, Web)
|
||||
- Custom QuickJS build in `subprojects/`
|
||||
- Uses SDL3 for cross-platform support
|
||||
|
||||
### Engine Entry Points
|
||||
- `source/prosperon.c` - Main C entry point
|
||||
- `scripts/core/engine.js` - JavaScript engine initialization for system
|
||||
- `scripts/core/base.js` has modifications to this Javascript runtime (for example, additions to the base Array, String, etc)
|
||||
|
||||
### Subprojects
|
||||
- C code has many subprojects, who's source and sometimes documentation can be found in subprojects. subprojects/quickjs/doc has documentation for quickjs
|
||||
|
||||
### Resource System
|
||||
- Scripts are bundled into `core.zip` during build
|
||||
- Runtime module loading via PhysFS
|
||||
- Resource paths checked in order: `/`, `scripts/modules/`, `scripts/modules/ext/`
|
||||
|
||||
### Notable Dependencies
|
||||
- QuickJS (custom build) - JavaScript runtime
|
||||
- SDL3 - Platform abstraction
|
||||
- Chipmunk2D - Physics
|
||||
- ENet - Networking
|
||||
- Soloud - Audio
|
||||
- Tracy - Profiling (when enabled)
|
||||
|
||||
## Development Tips
|
||||
|
||||
### Running Games
|
||||
```bash
|
||||
# Build first
|
||||
make debug
|
||||
|
||||
# Run example from build directory
|
||||
./build_dbg/prosperon examples/chess
|
||||
|
||||
# Or copy to game directory
|
||||
cp build_dbg/prosperon examples/chess/
|
||||
cd examples/chess
|
||||
./prosperon
|
||||
```
|
||||
|
||||
### Documentation
|
||||
- Documentation is found in docs
|
||||
- Documentation for the JS modules loaded with 'use' is docs/api/modules
|
||||
- .md files directly in docs gives a high level overview
|
||||
- docs/dull is what this specific Javascript system is (including alterations from quickjs/es6)
|
||||
|
||||
### Shader Development
|
||||
- Shaders are in `shaders/` directory as HLSL
|
||||
- Compile script: `shaders/compile.sh`
|
||||
- Outputs to platform-specific formats: `dxil/`, `msl/`, `spv/`
|
||||
|
||||
### Example Games
|
||||
Located in `examples/` directory:
|
||||
- `chess` - Chess implementation (has its own Makefile)
|
||||
- `pong` - Classic pong game
|
||||
- `snake` - Snake game
|
||||
- `tetris` - Tetris clone
|
||||
- `bunnymark` - Performance test
|
||||
|
||||
### Testing
|
||||
```bash
|
||||
# Run all tests
|
||||
meson test -C build_dbg
|
||||
|
||||
# Run specific test
|
||||
./build_dbg/prosperon tests/spawn_actor.js
|
||||
```
|
||||
|
||||
### Debugging
|
||||
- Use debug build: `make debug`
|
||||
- Tracy profiler support when enabled
|
||||
- Console logging available via `console.log()`, `console.error()`, etc.
|
||||
- Log files written to `.prosperon/log.txt`
|
||||
|
||||
# Project Structure Notes
|
||||
|
||||
## Core JavaScript Modules
|
||||
|
||||
- JavaScript modules are defined using the MISTUSE macro in jsffi.c
|
||||
- The `js_os_funcs`, `js_io_funcs`, etc. arrays define the available functions for each module
|
||||
- New functions are added with MIST_FUNC_DEF(module, function, args_count)
|
||||
|
||||
## File I/O
|
||||
|
||||
- `io.slurp(path)` - Reads a file as text
|
||||
- `io.slurpbytes(path)` - Reads a file as an ArrayBuffer
|
||||
- `io.slurpwrite(path, data)` - Writes data (string or ArrayBuffer) to a file
|
||||
- `io.exists(path)` - Checks if a file exists
|
||||
|
||||
## Script Loading
|
||||
|
||||
- The `use(path)` function in engine.js loads JavaScript modules
|
||||
- Script loading happens in prosperon.c and the engine.js script
|
||||
- jsffi.c contains the C hooks for the QuickJS JavaScript engine
|
||||
- Added functionality for bytecode compilation and loading:
|
||||
- `os.compile_bytecode(source, filename)` - Compiles JS to bytecode, returns ArrayBuffer
|
||||
- `os.eval_bytecode(bytecode)` - Evaluates bytecode from an ArrayBuffer
|
||||
- `compile(scriptPath)` - Compiles a JS file to a .jso bytecode file
|
||||
- Modified `use()` to check for .jso files before loading .js files
|
||||
|
||||
## QuickJS Bytecode API
|
||||
|
||||
- `JS_Eval` with JS_EVAL_FLAG_COMPILE_ONLY - Compiles without executing
|
||||
- `JS_WriteObject` with JS_WRITE_OBJ_BYTECODE - Serializes to bytecode
|
||||
- `JS_ReadObject` with JS_READ_OBJ_BYTECODE - Deserializes and loads bytecode
|
||||
- Bytecode files use .jso extension alongside .js files
|
||||
|
||||
## Available JavaScript APIs
|
||||
|
||||
### Core APIs
|
||||
- `actor` - Base prototype for all actor objects
|
||||
- `$_` - Special global for actor messaging
|
||||
- `prosperon` - Global engine interface
|
||||
- `console` - Logging and debugging interface
|
||||
|
||||
### Framework APIs
|
||||
- `moth` - Higher-level game framework that simplifies Prosperon usage
|
||||
- Handles window creation, game loop, and event dispatching
|
||||
- Provides simple configuration via config.js
|
||||
- Auto-initializes systems like rendering and input
|
||||
- Manages camera, resolution, and FPS automatically
|
||||
|
||||
### Rendering
|
||||
- `draw2d` - 2D drawing primitives
|
||||
- `render` - Low-level rendering operations
|
||||
- `graphics` - Higher-level graphics utilities
|
||||
- `camera` - Camera controls and transformations
|
||||
- `sprite` - Sprite rendering and management
|
||||
|
||||
### Physics and Math
|
||||
- `math` - Mathematical utilities
|
||||
- `geometry` - Geometric calculations and shapes
|
||||
- `transform` - Object transformations
|
||||
|
||||
### Input and Events
|
||||
- `input` - Mouse, keyboard, and touch handling
|
||||
- `event` - Event management system
|
||||
|
||||
### Networking
|
||||
- `enet` - Networking through ENet library
|
||||
- `http` - HTTP client capabilities
|
||||
|
||||
### Audio
|
||||
- `sound` - Audio playback using SoLoud
|
||||
|
||||
### Utility Modules
|
||||
- `time` - Time management and delays
|
||||
- `io` - File I/O operations
|
||||
- `json` - JSON parsing and serialization
|
||||
- `util` - General utilities
|
||||
- `color` - Color manipulation
|
||||
- `miniz` - Compression utilities
|
||||
- `nota` - Structured data format
|
||||
- `wota` - Serialization format
|
||||
- `qr` - QR code generation/reading
|
||||
- `tween` - Animation tweening
|
||||
- `spline` - Spline calculations
|
||||
- `imgui` - Immediate mode GUI
|
||||
|
||||
## Game Development Patterns
|
||||
|
||||
### Project Structure
|
||||
- Game config is typically in `config.js`
|
||||
- Main entry point is `main.js`
|
||||
- Resource loading through `resources.js`
|
||||
|
||||
### Actor Pattern Usage
|
||||
- Create actors with `actor.spawn(script, config)`
|
||||
- Manage actor hierarchy with overlings and underlings
|
||||
- Schedule actor tasks with `delay()` method
|
||||
- Clean up with `kill()` and `garbage()`
|
||||
|
||||
### Game Loop Registration
|
||||
- Register functions like `update`, `draw`, `gui`, etc.
|
||||
- Set function.layer property to control execution order
|
||||
- Use `Register` system to manage callbacks
|
||||
|
||||
### Program vs Module Pattern
|
||||
- Programs are actor scripts that don't return values, they execute top-to-bottom
|
||||
- Modules are files that return single values (usually objects) that get frozen
|
||||
- Programs can spawn other programs as underlings
|
||||
- Programs have lifecycle hooks: awake, update, draw, garbage, etc.
|
||||
|
||||
## Technical Capabilities
|
||||
|
||||
### Graphics Pipeline
|
||||
- Supports multiple render backends (Direct3D, Metal, Vulkan via SDL3)
|
||||
- Custom shader system with cross-platform compilation
|
||||
- Sprite batching for efficient 2D rendering
|
||||
- Camera systems for both 2D and 3D
|
||||
|
||||
### Asset Support
|
||||
- Images: PNG, JPG, QOI, etc.
|
||||
- Audio: Various formats through SoLoud
|
||||
- Models: Basic 3D model support
|
||||
- Custom formats: Aseprite animations, etc.
|
||||
|
||||
### Developer Tools
|
||||
- Built-in documentation system with `prosperon.DOC`
|
||||
- Tracy profiler integration for performance monitoring
|
||||
- Imgui debugging tools
|
||||
- Console logging with various severity levels
|
||||
|
||||
## Misty Networking Patterns
|
||||
|
||||
Prosperon implements the Misty actor networking model. Understanding these patterns is critical for building distributed applications.
|
||||
|
||||
### Portal Reply Pattern
|
||||
Portals must reply with an actor object, not application data:
|
||||
```javascript
|
||||
// CORRECT: Portal replies with actor
|
||||
$_.portal(e => {
|
||||
$_.send(e, $_); // Reply with server actor
|
||||
}, 5678);
|
||||
|
||||
// WRONG: Portal sends application data
|
||||
$_.portal(e => {
|
||||
$_.send(e, {type: 'game_start'}); // This breaks the pattern
|
||||
}, 5678);
|
||||
```
|
||||
|
||||
### Two-Phase Connection Protocol
|
||||
Proper Misty networking follows a two-phase pattern:
|
||||
|
||||
**Phase 1: Actor Connection**
|
||||
- Client contacts portal using `$_.contact()`
|
||||
- Portal replies with an actor object
|
||||
- This establishes the communication channel
|
||||
|
||||
**Phase 2: Application Communication**
|
||||
- Client sends application messages to the received actor
|
||||
- Normal bidirectional messaging begins
|
||||
- Application logic handles game/service initialization
|
||||
|
||||
### Message Header Management
|
||||
Messages contain `__HEADER__` information that can cause issues:
|
||||
|
||||
```javascript
|
||||
// CORRECT: Extract clean actor reference
|
||||
$_.receiver(e => {
|
||||
if (e.type === 'join_game') {
|
||||
var opponent = e.__HEADER__.replycc; // Clean actor reference
|
||||
$_.send(opponent, {type: 'game_start'});
|
||||
}
|
||||
});
|
||||
|
||||
// WRONG: Using message object directly
|
||||
$_.receiver(e => {
|
||||
opponent = e; // Contains return headers that pollute future sends
|
||||
});
|
||||
```
|
||||
|
||||
### Return ID Lifecycle
|
||||
- Each reply callback gets a unique return ID
|
||||
- Return IDs are consumed once and then deleted
|
||||
- Reusing message objects with return headers causes "Could not find return function" errors
|
||||
- Always create clean actor references for ongoing communication
|
||||
|
||||
### Actor Object Transparency
|
||||
Actor objects must be completely opaque black boxes that work identically regardless of transport:
|
||||
|
||||
```javascript
|
||||
// Actor objects work transparently for:
|
||||
// - Same-process communication (fastest - uses mailbox)
|
||||
// - Inter-process communication (uses mailbox)
|
||||
// - Network communication (uses ENet)
|
||||
|
||||
// The actor shouldn't know or care about the transport mechanism
|
||||
$_.send(opponent, {type: 'move', from: [0,0], to: [1,1]});
|
||||
```
|
||||
|
||||
**Key Implementation Details:**
|
||||
- `actor_send()` in `scripts/core/engine.js` handles routing based on available actor data
|
||||
- Actor objects sent in message data automatically get address/port populated when received over network
|
||||
- Three communication pathways: `os.mailbox_exist()` check → mailbox send → network send
|
||||
- Actor objects must contain all necessary routing information for transparent messaging
|
||||
|
||||
### Common Networking Bugs
|
||||
1. **Portal sending application data**: Portal should only establish actor connections
|
||||
2. **Return ID collision**: Reusing messages with return headers for multiple sends
|
||||
3. **Mixed phases**: Trying to do application logic during connection establishment
|
||||
4. **Header pollution**: Using received message objects as actor references
|
||||
5. **Missing actor address info**: Actor objects in message data need network address population (fixed in engine.js:746-766)
|
||||
|
||||
### Example: Correct Chess Networking
|
||||
```javascript
|
||||
// Server: Portal setup
|
||||
$_.portal(e => {
|
||||
$_.send(e, $_); // Just reply with actor
|
||||
}, 5678);
|
||||
|
||||
// Client: Two-phase connection
|
||||
$_.contact((actor, reason) => {
|
||||
if (actor) {
|
||||
opponent = actor;
|
||||
$_.send(opponent, {type: 'join_game'}); // Phase 2: app messaging
|
||||
}
|
||||
}, {address: "localhost", port: 5678});
|
||||
|
||||
// Server: Handle application messages
|
||||
$_.receiver(e => {
|
||||
if (e.type === 'join_game') {
|
||||
opponent = e.__HEADER__.replycc;
|
||||
$_.send(opponent, {type: 'game_start', your_color: 'black'});
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Memory Management
|
||||
|
||||
- When working with a conversational AI system like Claude, it's important to maintain a clean and focused memory
|
||||
- Regularly review and update memories to ensure they remain relevant and helpful
|
||||
- Delete or modify memories that are no longer accurate or useful
|
||||
- Prioritize information that can genuinely assist in future interactions
|
||||
4
Makefile
@@ -1,5 +1,5 @@
|
||||
debug: FORCE
|
||||
meson setup build_dbg -Dbuildtype=debugoptimized
|
||||
meson setup build_dbg -Dbuildtype=debug
|
||||
meson compile -C build_dbg
|
||||
|
||||
fast: FORCE
|
||||
@@ -7,7 +7,7 @@ fast: FORCE
|
||||
meson compile -C build_fast
|
||||
|
||||
release: FORCE
|
||||
meson setup -Dbuildtype=release -Db_lto=true -Db_ndebug=true build_release
|
||||
meson setup -Dbuildtype=release -Db_lto=true -Db_lto_mode=thin -Db_ndebug=true build_release
|
||||
meson compile -C build_release
|
||||
|
||||
sanitize: FORCE
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
Thank you for using Prosperon!
|
||||
|
||||
Provided are prosperon builds for all available platforms, including SDL3 for each respective one. SDL3 must be present in the same folder as prosperon to run!
|
||||
Provided are prosperon builds for all available platforms. Simply run prosperon for your platform in a game folder to play!
|
||||
|
||||
To get started, take a dive into the provided example games in the examples folder. Just copy the prosperon executable for your platform, along with its SDL3 library, into any provided example folder, then run it!
|
||||
|
||||
NOTE: For MacOS, SDL3 must first be installed with homebrew. After installing homebrew, run `brew install sdl3`. This will be fixed in a future release!
|
||||
To get started, take a dive into the provided example games in the examples folder. You can either copy the prosperon executable into an example directory and run it there, or run `prosperon path/to/example` from the project root.
|
||||
|
||||
You can take a look through the docs folder for the prosperon manual to learn all about it. The manual is available on the web at [docs.prosperon.dev](https://docs.prosperon.dev).
|
||||
|
||||
76
benchmarks/nota.js
Normal file
@@ -0,0 +1,76 @@
|
||||
var nota = use('nota')
|
||||
var os = use('os')
|
||||
var io = use('io')
|
||||
|
||||
var ll = io.slurp('benchmarks/nota.json')
|
||||
|
||||
var newarr = []
|
||||
var accstr = ""
|
||||
for (var i = 0; i < 10000; i++) {
|
||||
accstr += i;
|
||||
newarr.push(i.toString())
|
||||
}
|
||||
// Arrays to store timing results
|
||||
var jsonDecodeTimes = [];
|
||||
var jsonEncodeTimes = [];
|
||||
var notaEncodeTimes = [];
|
||||
var notaDecodeTimes = [];
|
||||
var notaSizes = [];
|
||||
|
||||
// Run 100 tests
|
||||
for (let i = 0; i < 100; i++) {
|
||||
// JSON Decode test
|
||||
let start = os.now();
|
||||
var jll = json.decode(ll);
|
||||
jsonDecodeTimes.push((os.now() - start) * 1000);
|
||||
|
||||
// JSON Encode test
|
||||
start = os.now();
|
||||
let jsonStr = JSON.stringify(jll);
|
||||
jsonEncodeTimes.push((os.now() - start) * 1000);
|
||||
|
||||
// NOTA Encode test
|
||||
start = os.now();
|
||||
var nll = nota.encode(jll);
|
||||
notaEncodeTimes.push((os.now() - start) * 1000);
|
||||
|
||||
// NOTA Decode test
|
||||
start = os.now();
|
||||
var oll = nota.decode(nll);
|
||||
notaDecodeTimes.push((os.now() - start) * 1000);
|
||||
}
|
||||
|
||||
// Calculate statistics
|
||||
function getStats(arr) {
|
||||
const avg = arr.reduce((a, b) => a + b) / arr.length;
|
||||
const min = Math.min(...arr);
|
||||
const max = Math.max(...arr);
|
||||
return { avg, min, max };
|
||||
}
|
||||
|
||||
// Pretty print results
|
||||
console.log("\n=== Performance Test Results (100 iterations) ===");
|
||||
console.log("\nJSON Decoding (ms):");
|
||||
const jsonDecStats = getStats(jsonDecodeTimes);
|
||||
console.log(`Average: ${jsonDecStats.avg.toFixed(2)} ms`);
|
||||
console.log(`Min: ${jsonDecStats.min.toFixed(2)} ms`);
|
||||
console.log(`Max: ${jsonDecStats.max.toFixed(2)} ms`);
|
||||
|
||||
console.log("\nJSON Encoding (ms):");
|
||||
const jsonEncStats = getStats(jsonEncodeTimes);
|
||||
console.log(`Average: ${jsonEncStats.avg.toFixed(2)} ms`);
|
||||
console.log(`Min: ${jsonEncStats.min.toFixed(2)} ms`);
|
||||
console.log(`Max: ${jsonEncStats.max.toFixed(2)} ms`);
|
||||
|
||||
console.log("\nNOTA Encoding (ms):");
|
||||
const notaEncStats = getStats(notaEncodeTimes);
|
||||
console.log(`Average: ${notaEncStats.avg.toFixed(2)} ms`);
|
||||
console.log(`Min: ${notaEncStats.min.toFixed(2)} ms`);
|
||||
console.log(`Max: ${notaEncStats.max.toFixed(2)} ms`);
|
||||
|
||||
console.log("\nNOTA Decoding (ms):");
|
||||
const notaDecStats = getStats(notaDecodeTimes);
|
||||
console.log(`Average: ${notaDecStats.avg.toFixed(2)} ms`);
|
||||
console.log(`Min: ${notaDecStats.min.toFixed(2)} ms`);
|
||||
console.log(`Max: ${notaDecStats.max.toFixed(2)} ms`);
|
||||
|
||||
2132
benchmarks/nota.json
Normal file
106
benchmarks/wota.js
Normal file
@@ -0,0 +1,106 @@
|
||||
//
|
||||
// wota_benchmark.js
|
||||
//
|
||||
// Usage in QuickJS:
|
||||
// qjs wota_benchmark.js
|
||||
//
|
||||
// Prerequisite:
|
||||
var wota = use('wota');
|
||||
var os = use('os');
|
||||
// or otherwise ensure `wota` and `os` are available.
|
||||
// Make sure wota_benchmark.js is loaded after wota.js or combined with it.
|
||||
//
|
||||
|
||||
// Helper to run a function repeatedly and measure total time in seconds.
|
||||
// Returns elapsed time in seconds.
|
||||
function measureTime(fn, iterations) {
|
||||
let t1 = os.now();
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
fn();
|
||||
}
|
||||
let t2 = os.now();
|
||||
return t2 - t1;
|
||||
}
|
||||
|
||||
// We'll define a function that does `encode -> decode` for a given value:
|
||||
function roundTripWota(value) {
|
||||
let encoded = wota.encode(value);
|
||||
let decoded = wota.decode(encoded);
|
||||
// Not doing a deep compare here, just measuring performance.
|
||||
// (We trust the test suite to verify correctness.)
|
||||
}
|
||||
|
||||
// A small suite of data we want to benchmark. Each entry includes:
|
||||
// name: label for printing
|
||||
// data: the test value(s) to encode/decode
|
||||
// iterations: how many times to loop
|
||||
//
|
||||
// You can tweak these as you like for heavier or lighter tests.
|
||||
const benchmarks = [
|
||||
{
|
||||
name: "Small Integers",
|
||||
data: [0, 42, -1, 2023],
|
||||
iterations: 100000
|
||||
},
|
||||
{
|
||||
name: "Strings (short, emoji)",
|
||||
data: ["Hello, Wota!", "short", "Emoji: \u{1f600}\u{1f64f}"],
|
||||
iterations: 100000
|
||||
},
|
||||
{
|
||||
name: "Small Objects",
|
||||
data: [
|
||||
{ a:1, b:2.2, c:"3", d:false },
|
||||
{ x:42, y:null, z:"test" }
|
||||
],
|
||||
iterations: 50000
|
||||
},
|
||||
{
|
||||
name: "Nested Arrays",
|
||||
data: [ [ [ [1,2], [3,4] ] ], [[[]]], [1, [2, [3, [4]]]] ],
|
||||
iterations: 50000
|
||||
},
|
||||
{
|
||||
name: "Large Array (1k numbers)",
|
||||
// A thousand random numbers
|
||||
data: [ Array.from({length:1000}, (_, i) => i * 0.5) ],
|
||||
iterations: 1000
|
||||
},
|
||||
{
|
||||
name: "Large Binary Blob (256KB)",
|
||||
// A 256KB ArrayBuffer
|
||||
data: [ new Uint8Array(256 * 1024).buffer ],
|
||||
iterations: 200
|
||||
}
|
||||
];
|
||||
|
||||
// Print a header
|
||||
console.log("Wota Encode/Decode Benchmark");
|
||||
console.log("============================\n");
|
||||
|
||||
// We'll run each benchmark scenario in turn.
|
||||
for (let bench of benchmarks) {
|
||||
// We'll measure how long it takes to do 'iterations' *for each test value*
|
||||
// in bench.data. The total loop count is `bench.iterations * bench.data.length`.
|
||||
// Then we compute an overall encode+decode throughput (ops/s).
|
||||
let totalIterations = bench.iterations * bench.data.length;
|
||||
|
||||
// We'll define a function that does a roundTrip for *each* data item in bench.data
|
||||
// to measure in one loop iteration. Then we multiply by bench.iterations.
|
||||
function runAllData() {
|
||||
for (let val of bench.data) {
|
||||
roundTripWota(val);
|
||||
}
|
||||
}
|
||||
|
||||
let elapsedSec = measureTime(runAllData, bench.iterations);
|
||||
let opsPerSec = (totalIterations / elapsedSec).toFixed(1);
|
||||
|
||||
console.log(`${bench.name}:`);
|
||||
console.log(` Iterations: ${bench.iterations} × ${bench.data.length} data items = ${totalIterations}`);
|
||||
console.log(` Elapsed: ${elapsedSec.toFixed(3)} s`);
|
||||
console.log(` Throughput: ${opsPerSec} encode+decode ops/sec\n`);
|
||||
}
|
||||
|
||||
// All done
|
||||
console.log("Benchmark completed.\n");
|
||||
182
benchmarks/wota_nota_json.js
Normal file
@@ -0,0 +1,182 @@
|
||||
//
|
||||
// benchmark_wota_nota_json.js
|
||||
//
|
||||
// Usage in QuickJS:
|
||||
// qjs benchmark_wota_nota_json.js
|
||||
//
|
||||
// Ensure wota, nota, json, and os are all available, e.g.:
|
||||
var wota = use('wota');
|
||||
var nota = use('nota');
|
||||
var json = use('json');
|
||||
var os = use('os');
|
||||
//
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// 1. Setup "libraries" array to easily switch among Wota, Nota, and JSON
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
const libraries = [
|
||||
{
|
||||
name: "Wota",
|
||||
encode: wota.encode,
|
||||
decode: wota.decode,
|
||||
// Wota produces an ArrayBuffer. We'll count `buffer.byteLength` as size.
|
||||
getSize(encoded) {
|
||||
return encoded.byteLength;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "Nota",
|
||||
encode: nota.encode,
|
||||
decode: nota.decode,
|
||||
// Nota also produces an ArrayBuffer:
|
||||
getSize(encoded) {
|
||||
return encoded.byteLength;
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "JSON",
|
||||
encode: json.encode,
|
||||
decode: json.decode,
|
||||
// JSON produces a JS string. We'll measure its UTF-16 code unit length
|
||||
// as a rough "size". Alternatively, you could convert to UTF-8 for
|
||||
// a more accurate byte size. Here we just use `string.length`.
|
||||
getSize(encodedStr) {
|
||||
return encodedStr.length;
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// 2. Test data sets (similar to wota benchmarks).
|
||||
// Each scenario has { name, data, iterations }
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
const benchmarks = [
|
||||
{
|
||||
name: "Small Integers",
|
||||
data: [0, 42, -1, 2023],
|
||||
iterations: 100000
|
||||
},
|
||||
{
|
||||
name: "Floating point",
|
||||
data: [0.1, 1e-50, 3.14159265359],
|
||||
iterations: 100000
|
||||
},
|
||||
{
|
||||
name: "Strings (short, emoji)",
|
||||
data: ["Hello, Wota!", "short", "Emoji: \u{1f600}\u{1f64f}"],
|
||||
iterations: 100000
|
||||
},
|
||||
{
|
||||
name: "Small Objects",
|
||||
data: [
|
||||
{ a:1, b:2.2, c:"3", d:false },
|
||||
{ x:42, y:null, z:"test" }
|
||||
],
|
||||
iterations: 50000
|
||||
},
|
||||
{
|
||||
name: "Nested Arrays",
|
||||
data: [ [ [ [1,2], [3,4] ] ], [[[]]], [1, [2, [3, [4]]]] ],
|
||||
iterations: 50000
|
||||
},
|
||||
{
|
||||
name: "Large Array (1k integers)",
|
||||
data: [ Array.from({length:1000}, (_, i) => i) ],
|
||||
iterations: 1000
|
||||
},
|
||||
{
|
||||
name: "Large Binary Blob (256KB)",
|
||||
data: [ new Uint8Array(256 * 1024).buffer ],
|
||||
iterations: 200
|
||||
}
|
||||
];
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// 3. Utility: measureTime(fn) => how long fn() takes in seconds.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
function measureTime(fn) {
|
||||
let start = os.now();
|
||||
fn();
|
||||
let end = os.now();
|
||||
return (end - start); // in seconds
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// 4. For each library, we run each benchmark scenario and measure:
|
||||
// - Encoding time (seconds)
|
||||
// - Decoding time (seconds)
|
||||
// - Total encoded size (bytes or code units for JSON)
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
function runBenchmarkForLibrary(lib, bench) {
|
||||
// We'll encode and decode each item in `bench.data`.
|
||||
// We do 'bench.iterations' times. Then sum up total time.
|
||||
|
||||
// Pre-store the encoded results for all items so we can measure decode time
|
||||
// in a separate pass. Also measure total size once.
|
||||
let encodedList = [];
|
||||
let totalSize = 0;
|
||||
|
||||
// 1) Measure ENCODING
|
||||
let encodeTime = measureTime(() => {
|
||||
for (let i = 0; i < bench.iterations; i++) {
|
||||
// For each data item, encode it
|
||||
for (let d of bench.data) {
|
||||
let e = lib.encode(d);
|
||||
// store only in the very first iteration, so we can decode them later
|
||||
// but do not store them every iteration or we blow up memory.
|
||||
if (i === 0) {
|
||||
encodedList.push(e);
|
||||
totalSize += lib.getSize(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 2) Measure DECODING
|
||||
let decodeTime = measureTime(() => {
|
||||
for (let i = 0; i < bench.iterations; i++) {
|
||||
// decode everything we stored during the first iteration
|
||||
for (let e of encodedList) {
|
||||
let decoded = lib.decode(e);
|
||||
// not verifying correctness here, just measuring speed
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { encodeTime, decodeTime, totalSize };
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// 5. Main driver: run across all benchmarks, for each library.
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
console.log("Benchmark: Wota vs Nota vs JSON");
|
||||
console.log("================================\n");
|
||||
|
||||
for (let bench of benchmarks) {
|
||||
console.log(`SCENARIO: ${bench.name}`);
|
||||
console.log(` Data length: ${bench.data.length} | Iterations: ${bench.iterations}\n`);
|
||||
|
||||
for (let lib of libraries) {
|
||||
let { encodeTime, decodeTime, totalSize } = runBenchmarkForLibrary(lib, bench);
|
||||
|
||||
// We'll compute total operations = bench.iterations * bench.data.length
|
||||
let totalOps = bench.iterations * bench.data.length;
|
||||
let encOpsPerSec = (totalOps / encodeTime).toFixed(1);
|
||||
let decOpsPerSec = (totalOps / decodeTime).toFixed(1);
|
||||
|
||||
console.log(` ${lib.name}:`);
|
||||
console.log(` Encode time: ${encodeTime.toFixed(3)}s => ${encOpsPerSec} encodes/sec`);
|
||||
console.log(` Decode time: ${decodeTime.toFixed(3)}s => ${decOpsPerSec} decodes/sec`);
|
||||
console.log(` Total size: ${totalSize} bytes (or code units for JSON)`);
|
||||
console.log("");
|
||||
}
|
||||
console.log("---------------------------------------------------------\n");
|
||||
}
|
||||
|
||||
console.log("Benchmark complete.\n");
|
||||
46
docs/api/modules/camera.md
Normal file
@@ -0,0 +1,46 @@
|
||||
# camera
|
||||
|
||||
### list() <sub>function</sub>
|
||||
|
||||
Return an array of available camera device IDs.
|
||||
|
||||
|
||||
|
||||
**Returns**: An array of camera IDs, or undefined if no cameras are available.
|
||||
|
||||
|
||||
### open(id) <sub>function</sub>
|
||||
|
||||
Open a camera device with the given ID.
|
||||
|
||||
|
||||
|
||||
**id**: The camera ID to open.
|
||||
|
||||
|
||||
**Returns**: A camera object on success, or throws an error if the camera cannot be opened.
|
||||
|
||||
|
||||
### name(id) <sub>function</sub>
|
||||
|
||||
Return the name of the camera with the given ID.
|
||||
|
||||
|
||||
|
||||
**id**: The camera ID to query.
|
||||
|
||||
|
||||
**Returns**: A string with the camera's name, or throws an error if the name cannot be retrieved.
|
||||
|
||||
|
||||
### position(id) <sub>function</sub>
|
||||
|
||||
Return the physical position of the camera with the given ID.
|
||||
|
||||
|
||||
|
||||
**id**: The camera ID to query.
|
||||
|
||||
|
||||
**Returns**: A string indicating the camera position ("unknown", "front", or "back").
|
||||
|
||||
76
docs/api/modules/debug.md
Normal file
@@ -0,0 +1,76 @@
|
||||
# debug
|
||||
|
||||
### stack_depth() <sub>function</sub>
|
||||
|
||||
Return the current stack depth.
|
||||
|
||||
|
||||
|
||||
**Returns**: A number representing the stack depth.
|
||||
|
||||
|
||||
### build_backtrace() <sub>function</sub>
|
||||
|
||||
Build and return a backtrace of the current call stack.
|
||||
|
||||
|
||||
|
||||
**Returns**: An object representing the call stack backtrace.
|
||||
|
||||
|
||||
### closure_vars(fn) <sub>function</sub>
|
||||
|
||||
Return the closure variables for a given function.
|
||||
|
||||
|
||||
|
||||
**fn**: The function object to inspect.
|
||||
|
||||
|
||||
**Returns**: An object containing the closure variables.
|
||||
|
||||
|
||||
### local_vars(depth) <sub>function</sub>
|
||||
|
||||
Return the local variables for a specific stack frame.
|
||||
|
||||
|
||||
|
||||
**depth**: The stack frame depth to inspect.
|
||||
|
||||
|
||||
**Returns**: An object containing the local variables at the specified depth.
|
||||
|
||||
|
||||
### fn_info(fn) <sub>function</sub>
|
||||
|
||||
Return metadata about a given function.
|
||||
|
||||
|
||||
|
||||
**fn**: The function object to inspect.
|
||||
|
||||
|
||||
**Returns**: An object with metadata about the function.
|
||||
|
||||
|
||||
### backtrace_fns() <sub>function</sub>
|
||||
|
||||
Return an array of functions in the current backtrace.
|
||||
|
||||
|
||||
|
||||
**Returns**: An array of function objects from the call stack.
|
||||
|
||||
|
||||
### dump_obj(obj) <sub>function</sub>
|
||||
|
||||
Return a string representation of a given object.
|
||||
|
||||
|
||||
|
||||
**obj**: The object to dump.
|
||||
|
||||
|
||||
**Returns**: A string describing the object's contents.
|
||||
|
||||
39
docs/api/modules/dmon.md
Normal file
@@ -0,0 +1,39 @@
|
||||
# dmon
|
||||
|
||||
### watch() <sub>function</sub>
|
||||
|
||||
Start watching the root directory, recursively.
|
||||
|
||||
This function begins monitoring the specified directory and its subdirectories recursively for events such as file creation, deletion, modification, or movement. Events are queued and can be retrieved by calling poll.
|
||||
|
||||
:throws: An error if dmon is already watching.
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### unwatch() <sub>function</sub>
|
||||
|
||||
Stop watching the currently monitored directory.
|
||||
|
||||
This function halts filesystem monitoring for the directory previously set by watch. It clears the watch state, allowing a new watch to be started.
|
||||
|
||||
:throws: An error if no directory is currently being watched.
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### poll(callback) <sub>function</sub>
|
||||
|
||||
Retrieve and process queued filesystem events.
|
||||
|
||||
This function dequeues all pending filesystem events and invokes the provided callback for each one. The callback receives an event object with properties: 'action' (string: "create", "delete", "modify", or "move"), 'root' (string: watched directory), 'file' (string: affected file path), and 'old' (string: previous file path for move events, empty if not applicable).
|
||||
|
||||
|
||||
|
||||
**callback**: A function to call for each event, receiving an event object as its argument.
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
45
docs/api/modules/enet.md
Normal file
@@ -0,0 +1,45 @@
|
||||
# enet
|
||||
|
||||
### initialize() <sub>function</sub>
|
||||
|
||||
|
||||
Initialize the ENet library. Must be called before using any ENet functionality.
|
||||
Throws an error if initialization fails.
|
||||
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### deinitialize() <sub>function</sub>
|
||||
|
||||
|
||||
Deinitialize the ENet library, cleaning up all resources. Call this when you no longer
|
||||
need any ENet functionality.
|
||||
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### create_host(address) <sub>function</sub>
|
||||
|
||||
|
||||
Create an ENet host for either a client-like unbound host or a server bound to a specific
|
||||
address and port:
|
||||
|
||||
- If no argument is provided, creates an unbound "client-like" host with default settings
|
||||
(maximum 32 peers, 2 channels, unlimited bandwidth).
|
||||
- If you pass an "ip:port" string (e.g. "127.0.0.1:7777"), it creates a server bound to
|
||||
that address. The server supports up to 32 peers, 2 channels, and unlimited bandwidth.
|
||||
|
||||
Throws an error if host creation fails for any reason.
|
||||
|
||||
omit to create an unbound client-like host.
|
||||
|
||||
|
||||
**address**: (optional) A string in 'ip:port' format to bind the host (server), or
|
||||
|
||||
|
||||
**Returns**: An ENetHost object.
|
||||
|
||||
@@ -66,23 +66,3 @@ and booleans for pressed buttons (left, middle, right, x1, x2).
|
||||
|
||||
**Returns**: Object { x, y, left, middle, right, x1, x2 }
|
||||
|
||||
|
||||
### mouse <sub>object</sub>
|
||||
|
||||
### keyboard <sub>object</sub>
|
||||
|
||||
### print_pawn_kbm(pawn) <sub>function</sub>
|
||||
|
||||
### procdown() <sub>function</sub>
|
||||
|
||||
### print_md_kbm(pawn) <sub>function</sub>
|
||||
|
||||
### has_bind(pawn, bind) <sub>function</sub>
|
||||
|
||||
### action <sub>object</sub>
|
||||
|
||||
### tabcomplete(val, list) <sub>function</sub>
|
||||
|
||||
### do_uncontrol(pawn) <sub>function</sub>
|
||||
|
||||
### player <sub>object</sub>
|
||||
|
||||
@@ -174,12 +174,17 @@ Return the application's base directory (where the executable is located).
|
||||
**Returns**: A string with the base directory path.
|
||||
|
||||
|
||||
### userdir() <sub>function</sub>
|
||||
### prefdir(org, app) <sub>function</sub>
|
||||
|
||||
Return the user's directory, often used for saving data.
|
||||
Get the user-and-app-specific path where files can be written.
|
||||
|
||||
|
||||
|
||||
**org**: The name of your organization.
|
||||
|
||||
**app**: The name of your application.
|
||||
|
||||
|
||||
**Returns**: A string with the user's directory path.
|
||||
|
||||
|
||||
|
||||
30
docs/api/modules/nota.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# nota
|
||||
|
||||
### encode(value) <sub>function</sub>
|
||||
|
||||
Convert a JavaScript value into a NOTA-encoded ArrayBuffer.
|
||||
|
||||
This function serializes JavaScript values (such as numbers, strings, booleans, arrays, objects, or ArrayBuffers) into the NOTA binary format. The resulting ArrayBuffer can be stored or transmitted and later decoded back into a JavaScript value.
|
||||
|
||||
:throws: An error if no argument is provided.
|
||||
|
||||
|
||||
**value**: The JavaScript value to encode (e.g., number, string, boolean, array, object, or ArrayBuffer).
|
||||
|
||||
|
||||
**Returns**: An ArrayBuffer containing the NOTA-encoded data.
|
||||
|
||||
|
||||
### decode(buffer) <sub>function</sub>
|
||||
|
||||
Decode a NOTA-encoded ArrayBuffer into a JavaScript value.
|
||||
|
||||
This function deserializes a NOTA-formatted ArrayBuffer into its corresponding JavaScript representation, such as a number, string, boolean, array, object, or ArrayBuffer. If the input is invalid or empty, it returns undefined.
|
||||
|
||||
|
||||
|
||||
**buffer**: An ArrayBuffer containing NOTA-encoded data to decode.
|
||||
|
||||
|
||||
**Returns**: The decoded JavaScript value (e.g., number, string, boolean, array, object, or ArrayBuffer), or undefined if no argument is provided.
|
||||
|
||||
@@ -33,71 +33,3 @@
|
||||
### imgui(...args) <sub>function</sub>
|
||||
|
||||
### app(...args) <sub>function</sub>
|
||||
|
||||
### date <sub>string</sub>
|
||||
|
||||
### camera <sub>object</sub>
|
||||
|
||||
### debug <sub>boolean</sub>
|
||||
|
||||
### semver <sub>object</sub>
|
||||
|
||||
### title <sub>string</sub>
|
||||
|
||||
### width <sub>number</sub>
|
||||
|
||||
### height <sub>number</sub>
|
||||
|
||||
### size <sub>object</sub>
|
||||
|
||||
### icon <sub>object</sub>
|
||||
|
||||
### high_dpi <sub>number</sub>
|
||||
|
||||
### alpha <sub>number</sub>
|
||||
|
||||
### fullscreen <sub>number</sub>
|
||||
|
||||
### sample_count <sub>number</sub>
|
||||
|
||||
### enable_clipboard <sub>boolean</sub>
|
||||
|
||||
### enable_dragndrop <sub>boolean</sub>
|
||||
|
||||
### max_dropped_files <sub>number</sub>
|
||||
|
||||
### swap_interval <sub>number</sub>
|
||||
|
||||
### name <sub>string</sub>
|
||||
|
||||
### identifier <sub>string</sub>
|
||||
|
||||
### creator <sub>string</sub>
|
||||
|
||||
### copyright <sub>string</sub>
|
||||
|
||||
### type <sub>string</sub>
|
||||
|
||||
### url <sub>string</sub>
|
||||
|
||||
### postvals <sub>object</sub>
|
||||
|
||||
### hudcam <sub>object</sub>
|
||||
|
||||
### appcam <sub>object</sub>
|
||||
|
||||
### screencolor <sub>object</sub>
|
||||
|
||||
### window <sub>object</sub>
|
||||
|
||||
An application window, created via prosperon.engine_start or SDL calls. Freed on GC.
|
||||
|
||||
|
||||
### font <sub>object</sub>
|
||||
|
||||
### gpu <sub>object</sub>
|
||||
|
||||
A handle for low-level GPU operations via SDL GPU. Freed on GC.
|
||||
|
||||
|
||||
### exit() <sub>function</sub>
|
||||
|
||||
66
docs/api/types/enet_host.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# enet_host
|
||||
|
||||
### service(callback, timeout) <sub>function</sub>
|
||||
|
||||
|
||||
Poll for and process any available network events (connect, receive, disconnect, or none)
|
||||
from this host, calling the provided callback for each event. This function loops until
|
||||
no more events are available in the current timeframe.
|
||||
|
||||
Event object properties:
|
||||
- type: String, one of "connect", "receive", "disconnect", or "none".
|
||||
- peer: (present if type = "connect") The ENetPeer object for the new connection.
|
||||
- channelID: (present if type = "receive") The channel on which the data was received.
|
||||
- data: (present if type = "receive") The received data as a *plain JavaScript object*.
|
||||
If the JSON parse fails or the data isn't an object, a JavaScript error is thrown.
|
||||
|
||||
object as its single argument.
|
||||
|
||||
|
||||
**callback**: A function called once for each available event, receiving an event
|
||||
|
||||
**timeout**: (optional) Timeout in milliseconds. Defaults to 0 (non-blocking).
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### connect(host, port) <sub>function</sub>
|
||||
|
||||
|
||||
Initiate a connection from this host to a remote server. Throws an error if the
|
||||
connection cannot be started.
|
||||
|
||||
|
||||
|
||||
**host**: The hostname or IP address of the remote server (e.g. "example.com" or "127.0.0.1").
|
||||
|
||||
**port**: The port number to connect to.
|
||||
|
||||
|
||||
**Returns**: An ENetPeer object representing the connection.
|
||||
|
||||
|
||||
### flush() <sub>function</sub>
|
||||
|
||||
|
||||
Flush all pending outgoing packets for this host immediately.
|
||||
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### broadcast(data) <sub>function</sub>
|
||||
|
||||
|
||||
Broadcast a JavaScript object to all connected peers on channel 0. The object is
|
||||
serialized to JSON, and the packet is sent reliably. Throws an error if serialization fails.
|
||||
|
||||
|
||||
|
||||
**data**: A JavaScript object to broadcast to all peers.
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
102
docs/api/types/enet_peer.md
Normal file
@@ -0,0 +1,102 @@
|
||||
# enet_peer
|
||||
|
||||
### send(data) <sub>function</sub>
|
||||
|
||||
|
||||
Send a JavaScript object to this peer on channel 0. The object is serialized to JSON and
|
||||
sent reliably. Throws an error if serialization fails.
|
||||
|
||||
|
||||
|
||||
**data**: A JavaScript object to send.
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### disconnect() <sub>function</sub>
|
||||
|
||||
|
||||
Request a graceful disconnection from this peer. The connection will close after
|
||||
pending data is sent.
|
||||
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### disconnect_now() <sub>function</sub>
|
||||
|
||||
|
||||
Immediately terminate the connection to this peer, discarding any pending data.
|
||||
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### disconnect_later() <sub>function</sub>
|
||||
|
||||
|
||||
Request a disconnection from this peer after all queued packets are sent.
|
||||
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### reset() <sub>function</sub>
|
||||
|
||||
|
||||
Reset this peer's connection, immediately dropping it and clearing its internal state.
|
||||
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### ping() <sub>function</sub>
|
||||
|
||||
|
||||
Send a ping request to this peer to measure latency.
|
||||
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### throttle_configure(interval, acceleration, deceleration) <sub>function</sub>
|
||||
|
||||
|
||||
Configure the throttling behavior for this peer, controlling how ENet adjusts its sending
|
||||
rate based on packet loss or congestion.
|
||||
|
||||
|
||||
|
||||
**interval**: The interval (ms) between throttle adjustments.
|
||||
|
||||
**acceleration**: The factor to increase sending speed when conditions improve.
|
||||
|
||||
**deceleration**: The factor to decrease sending speed when conditions worsen.
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### timeout(timeout_limit, timeout_min, timeout_max) <sub>function</sub>
|
||||
|
||||
|
||||
Set timeout parameters for this peer, determining how long ENet waits before considering
|
||||
the connection lost.
|
||||
|
||||
|
||||
|
||||
**timeout_limit**: The total time (ms) before the peer is disconnected.
|
||||
|
||||
**timeout_min**: The minimum timeout (ms) used for each timeout attempt.
|
||||
|
||||
**timeout_max**: The maximum timeout (ms) used for each timeout attempt.
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
661
docs/dull/Array.md
Normal file
@@ -0,0 +1,661 @@
|
||||
# Array
|
||||
|
||||
### length <sub>number</sub>
|
||||
|
||||
### at(index) <sub>function</sub>
|
||||
|
||||
Return the item at index 'index', supporting negative indices to count from
|
||||
the end. If 'index' is out of range, returns undefined.
|
||||
|
||||
|
||||
|
||||
**index**: The index of the element to return (can be negative).
|
||||
|
||||
|
||||
**Returns**: The element at the given index, or undefined.
|
||||
|
||||
|
||||
### with(index, value) <sub>function</sub>
|
||||
|
||||
Return a shallow copy of the array, but with the element at 'index' replaced
|
||||
by 'value'. If 'index' is negative, it counts from the end. Throws if out of range.
|
||||
|
||||
|
||||
|
||||
**index**: The zero-based index (can be negative) to replace.
|
||||
|
||||
**value**: The new value for the specified position.
|
||||
|
||||
|
||||
**Returns**: A new array with the updated element.
|
||||
|
||||
|
||||
### concat(items) <sub>function</sub>
|
||||
|
||||
Return a new array that is the result of concatenating this array with
|
||||
any additional arrays or values provided.
|
||||
|
||||
|
||||
|
||||
**items**: One or more arrays or values to concatenate.
|
||||
|
||||
|
||||
**Returns**: A new array with the items appended.
|
||||
|
||||
|
||||
### every(callback, thisArg) <sub>function</sub>
|
||||
|
||||
Return true if the provided callback function returns a truthy value for
|
||||
every element in the array; otherwise false.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(element, index, array) => boolean.
|
||||
|
||||
**thisArg**: Optional. A value to use as 'this' within the callback.
|
||||
|
||||
|
||||
**Returns**: True if all elements pass the test, otherwise false.
|
||||
|
||||
|
||||
### some(callback, thisArg) <sub>function</sub>
|
||||
|
||||
Return true if the provided callback function returns a truthy value for at
|
||||
least one element in the array; otherwise false.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(element, index, array) => boolean.
|
||||
|
||||
**thisArg**: Optional. A value to use as 'this' within the callback.
|
||||
|
||||
|
||||
**Returns**: True if at least one element passes the test, otherwise false.
|
||||
|
||||
|
||||
### forEach(callback, thisArg) <sub>function</sub>
|
||||
|
||||
Call the provided callback function once for each element in the array.
|
||||
Does not produce a return value.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(element, index, array).
|
||||
|
||||
**thisArg**: Optional. A value to use as 'this' within the callback.
|
||||
|
||||
|
||||
**Returns**: None
|
||||
|
||||
|
||||
### map(callback, thisArg) <sub>function</sub>
|
||||
|
||||
Create a new array with the results of calling a provided callback function
|
||||
on every element in this array.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(element, index, array) => newElement.
|
||||
|
||||
**thisArg**: Optional. A value to use as 'this' within the callback.
|
||||
|
||||
|
||||
**Returns**: A new array of transformed elements.
|
||||
|
||||
|
||||
### filter(callback, thisArg) <sub>function</sub>
|
||||
|
||||
Create a new array containing all elements for which the provided callback
|
||||
function returns a truthy value.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(element, index, array) => boolean.
|
||||
|
||||
**thisArg**: Optional. A value to use as 'this' within the callback.
|
||||
|
||||
|
||||
**Returns**: A new array of elements that passed the test.
|
||||
|
||||
|
||||
### reduce(callback, initialValue) <sub>function</sub>
|
||||
|
||||
Apply a callback function against an accumulator and each element in the
|
||||
array (from left to right) to reduce it to a single value.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(accumulator, element, index, array) => newAccumulator.
|
||||
|
||||
**initialValue**: Optional. The initial value for the accumulator.
|
||||
|
||||
|
||||
**Returns**: The single resulting value.
|
||||
|
||||
|
||||
### reduceRight(callback, initialValue) <sub>function</sub>
|
||||
|
||||
Similar to reduce(), except it processes elements from right to left.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(accumulator, element, index, array) => newAccumulator.
|
||||
|
||||
**initialValue**: Optional. The initial value for the accumulator.
|
||||
|
||||
|
||||
**Returns**: The single resulting value.
|
||||
|
||||
|
||||
### fill(value, start, end) <sub>function</sub>
|
||||
|
||||
Fill the array with a static value from 'start' index up to (but not including)
|
||||
'end' index. Modifies the original array.
|
||||
|
||||
|
||||
|
||||
**value**: The value to fill.
|
||||
|
||||
**start**: The starting index (default 0).
|
||||
|
||||
**end**: The ending index (default array.length).
|
||||
|
||||
|
||||
**Returns**: The modified array (with filled values).
|
||||
|
||||
|
||||
### find(callback, thisArg) <sub>function</sub>
|
||||
|
||||
Return the first element in the array that satisfies the provided callback
|
||||
function. If none is found, return undefined.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(element, index, array) => boolean.
|
||||
|
||||
**thisArg**: Optional. A value to use as 'this' within the callback.
|
||||
|
||||
|
||||
**Returns**: The first matching element, or undefined if not found.
|
||||
|
||||
|
||||
### findIndex(callback, thisArg) <sub>function</sub>
|
||||
|
||||
Return the index of the first element in the array that satisfies the
|
||||
provided callback function. If none is found, return -1.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(element, index, array) => boolean.
|
||||
|
||||
**thisArg**: Optional. A value to use as 'this' within the callback.
|
||||
|
||||
|
||||
**Returns**: The index of the first matching element, or -1 if not found.
|
||||
|
||||
|
||||
### findLast(callback, thisArg) <sub>function</sub>
|
||||
|
||||
Return the last element in the array that satisfies the provided callback
|
||||
function, searching from right to left. If none is found, return undefined.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(element, index, array) => boolean.
|
||||
|
||||
**thisArg**: Optional. A value to use as 'this' within the callback.
|
||||
|
||||
|
||||
**Returns**: The last matching element, or undefined if not found.
|
||||
|
||||
|
||||
### findLastIndex(callback, thisArg) <sub>function</sub>
|
||||
|
||||
Return the index of the last element in the array that satisfies the
|
||||
provided callback function, searching from right to left. If none is found,
|
||||
return -1.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(element, index, array) => boolean.
|
||||
|
||||
**thisArg**: Optional. A value to use as 'this' within the callback.
|
||||
|
||||
|
||||
**Returns**: The index of the last matching element, or -1 if not found.
|
||||
|
||||
|
||||
### indexOf(searchElement, fromIndex) <sub>function</sub>
|
||||
|
||||
Return the first index at which a given element can be found. If not present,
|
||||
return -1.
|
||||
|
||||
|
||||
|
||||
**searchElement**: The item to locate in the array.
|
||||
|
||||
**fromIndex**: The index at which to start searching (default 0).
|
||||
|
||||
|
||||
**Returns**: The index of the found element, or -1 if not found.
|
||||
|
||||
|
||||
### lastIndexOf(searchElement, fromIndex) <sub>function</sub>
|
||||
|
||||
Return the last index at which a given element can be found, or -1 if not
|
||||
present. Searches backward from 'fromIndex'.
|
||||
|
||||
|
||||
|
||||
**searchElement**: The item to locate in the array.
|
||||
|
||||
**fromIndex**: The index at which to start searching backward (default array.length - 1).
|
||||
|
||||
|
||||
**Returns**: The last index of the found element, or -1 if not found.
|
||||
|
||||
|
||||
### includes(searchElement, fromIndex) <sub>function</sub>
|
||||
|
||||
Return a boolean indicating whether the array contains the given element,
|
||||
comparing elements using the SameValueZero algorithm.
|
||||
|
||||
|
||||
|
||||
**searchElement**: The value to search for.
|
||||
|
||||
**fromIndex**: The position in the array to start searching (default 0).
|
||||
|
||||
|
||||
**Returns**: True if the element is found, otherwise false.
|
||||
|
||||
|
||||
### join(separator) <sub>function</sub>
|
||||
|
||||
Join all elements of the array into a string, separated by 'separator'.
|
||||
|
||||
|
||||
|
||||
**separator**: The delimiter string to separate elements (default ',').
|
||||
|
||||
|
||||
**Returns**: A string of array elements joined by the separator.
|
||||
|
||||
|
||||
### toString() <sub>function</sub>
|
||||
|
||||
Return a string representing the elements of the array, separated by commas.
|
||||
Overrides Object.prototype.toString.
|
||||
|
||||
|
||||
|
||||
**Returns**: A comma-separated string of array elements.
|
||||
|
||||
|
||||
### toLocaleString() <sub>function</sub>
|
||||
|
||||
Return a localized string representing the array and its elements, calling
|
||||
each element's toLocaleString if available.
|
||||
|
||||
|
||||
|
||||
**Returns**: A locale-sensitive, comma-separated string of array elements.
|
||||
|
||||
|
||||
### pop() <sub>function</sub>
|
||||
|
||||
Remove the last element from the array and return it. This changes the length
|
||||
of the array.
|
||||
|
||||
|
||||
|
||||
**Returns**: The removed element, or undefined if the array is empty.
|
||||
|
||||
|
||||
### push(items) <sub>function</sub>
|
||||
|
||||
Append one or more elements to the end of the array and return the new length
|
||||
of the array.
|
||||
|
||||
|
||||
|
||||
**items**: One or more items to append.
|
||||
|
||||
|
||||
**Returns**: The new length of the array.
|
||||
|
||||
|
||||
### shift() <sub>function</sub>
|
||||
|
||||
Remove the first element from the array and return it. This changes the length
|
||||
of the array.
|
||||
|
||||
|
||||
|
||||
**Returns**: The removed element, or undefined if the array is empty.
|
||||
|
||||
|
||||
### unshift(items) <sub>function</sub>
|
||||
|
||||
Insert one or more elements at the start of the array and return the new
|
||||
length of the array.
|
||||
|
||||
|
||||
|
||||
**items**: One or more elements to insert at the start.
|
||||
|
||||
|
||||
**Returns**: The new length of the array.
|
||||
|
||||
|
||||
### reverse() <sub>function</sub>
|
||||
|
||||
Reverse the elements of the array in place and return the modified array.
|
||||
|
||||
|
||||
|
||||
**Returns**: The reversed array.
|
||||
|
||||
|
||||
### toReversed() <sub>function</sub>
|
||||
|
||||
Return a shallow copy of the array in reverse order, without modifying the original array.
|
||||
|
||||
|
||||
|
||||
**Returns**: A new reversed array.
|
||||
|
||||
|
||||
### sort(compareFunction) <sub>function</sub>
|
||||
|
||||
Sort the array in place, returning it. By default, sorts elements as strings in ascending order. An optional compareFunction may be used for custom sorting.
|
||||
|
||||
|
||||
|
||||
**compareFunction**: A function(a, b) => number, defining sort order.
|
||||
|
||||
|
||||
**Returns**: The sorted array.
|
||||
|
||||
|
||||
### toSorted(compareFunction) <sub>function</sub>
|
||||
|
||||
Return a shallow copy of the array, sorted according to the optional compare
|
||||
function, without modifying the original array.
|
||||
|
||||
|
||||
|
||||
**compareFunction**: A function(a, b) => number, defining sort order.
|
||||
|
||||
|
||||
**Returns**: A new sorted array.
|
||||
|
||||
|
||||
### slice(start, end) <sub>function</sub>
|
||||
|
||||
Return a shallow copy of a portion of the array into a new array object, selected from 'start' to 'end' (end not included).
|
||||
|
||||
|
||||
|
||||
**start**: The beginning index (0-based). Negative values count from the end.
|
||||
|
||||
**end**: The end index (exclusive). Negative values count from the end.
|
||||
|
||||
|
||||
**Returns**: A new array containing the extracted elements.
|
||||
|
||||
|
||||
### splice(start, deleteCount, items) <sub>function</sub>
|
||||
|
||||
Change the contents of the array by removing or replacing existing elements and/or adding new elements in place. Returns an array of removed elements.
|
||||
|
||||
|
||||
|
||||
**start**: The index at which to start changing the array.
|
||||
|
||||
**deleteCount**: Number of elements to remove.
|
||||
|
||||
**items**: Elements to add in place of the removed elements.
|
||||
|
||||
|
||||
**Returns**: An array containing the removed elements (if any).
|
||||
|
||||
|
||||
### toSpliced(start, deleteCount, items) <sub>function</sub>
|
||||
|
||||
Return a shallow copy of the array, with a splice-like operation applied at 'start' removing 'deleteCount' elements and adding 'items'. Does not mutate the original array.
|
||||
|
||||
|
||||
|
||||
**start**: The index at which to start the splice operation.
|
||||
|
||||
**deleteCount**: Number of elements to remove.
|
||||
|
||||
**items**: Elements to add in place of the removed elements.
|
||||
|
||||
|
||||
**Returns**: A new array with the splice applied.
|
||||
|
||||
|
||||
### copyWithin(target, start, end) <sub>function</sub>
|
||||
|
||||
Copy a sequence of array elements within the array, overwriting existing values. This operation is performed in place and returns the modified array.
|
||||
|
||||
|
||||
|
||||
**target**: The index at which to copy the sequence to.
|
||||
|
||||
**start**: The beginning index of the sequence to copy.
|
||||
|
||||
**end**: The end index (exclusive) of the sequence to copy (default array.length).
|
||||
|
||||
|
||||
**Returns**: The modified array.
|
||||
|
||||
|
||||
### flatMap(callback, thisArg) <sub>function</sub>
|
||||
|
||||
Return a new array formed by applying a callback function to each element and then flattening the result by one level.
|
||||
|
||||
|
||||
|
||||
**callback**: A function(element, index, array) => array or value.
|
||||
|
||||
**thisArg**: Optional. A value to use as 'this' within the callback.
|
||||
|
||||
|
||||
**Returns**: A new array with the flattened results.
|
||||
|
||||
|
||||
### flat(depth) <sub>function</sub>
|
||||
|
||||
Return a new array with all sub-array elements concatenated into it recursively up to the specified depth.
|
||||
|
||||
|
||||
|
||||
**depth**: The maximum depth to flatten (default 1).
|
||||
|
||||
|
||||
**Returns**: A new flattened array.
|
||||
|
||||
|
||||
### values() <sub>function</sub>
|
||||
|
||||
Return a new Array Iterator object that contains the values for each index in the array.
|
||||
|
||||
|
||||
|
||||
**Returns**: An iterator over the array's elements.
|
||||
|
||||
|
||||
### keys() <sub>function</sub>
|
||||
|
||||
Return a new Array Iterator object that contains the keys (indexes) for each index in the array.
|
||||
|
||||
|
||||
|
||||
**Returns**: An iterator over the array's indices.
|
||||
|
||||
|
||||
### entries() <sub>function</sub>
|
||||
|
||||
Return a new Array Iterator object that contains key/value pairs for each index in the array. Each entry is [index, value].
|
||||
|
||||
|
||||
|
||||
**Returns**: An iterator over [index, value] pairs.
|
||||
|
||||
|
||||
### add(other) <sub>function</sub>
|
||||
|
||||
Non-standard. Add corresponding elements of the current array and 'other' element-wise, returning a new array. Behavior depends on data types.
|
||||
|
||||
|
||||
|
||||
**other**: Another array or scalar to add to each element.
|
||||
|
||||
|
||||
**Returns**: A new array with element-wise sum results.
|
||||
|
||||
|
||||
### sub(other) <sub>function</sub>
|
||||
|
||||
Non-standard. Subtract corresponding elements of 'other' from the current array element-wise, returning a new array. Behavior depends on data types.
|
||||
|
||||
|
||||
|
||||
**other**: Another array or scalar to subtract from each element.
|
||||
|
||||
|
||||
**Returns**: A new array with element-wise difference results.
|
||||
|
||||
|
||||
### div(other) <sub>function</sub>
|
||||
|
||||
Non-standard. Divide each element of the current array by the corresponding element of 'other' (or a scalar) element-wise, returning a new array. Behavior depends on data types.
|
||||
|
||||
|
||||
|
||||
**other**: Another array or scalar for the division.
|
||||
|
||||
|
||||
**Returns**: A new array with element-wise division results.
|
||||
|
||||
|
||||
### scale() <sub>function</sub>
|
||||
|
||||
### lerp() <sub>function</sub>
|
||||
|
||||
### x <sub>accessor</sub>
|
||||
|
||||
### y <sub>accessor</sub>
|
||||
|
||||
### xy <sub>accessor</sub>
|
||||
|
||||
### r <sub>accessor</sub>
|
||||
|
||||
### g <sub>accessor</sub>
|
||||
|
||||
### b <sub>accessor</sub>
|
||||
|
||||
### a <sub>accessor</sub>
|
||||
|
||||
### rgb <sub>accessor</sub>
|
||||
|
||||
### rgba <sub>accessor</sub>
|
||||
|
||||
### filter!(fn) <sub>function</sub>
|
||||
|
||||
Perform an in-place filter of this array using the provided callback 'fn'.
|
||||
Any element for which 'fn' returns a falsy value is removed. The array is modified
|
||||
and then returned.
|
||||
|
||||
|
||||
|
||||
**fn**: A callback function(element, index, array) => boolean.
|
||||
|
||||
|
||||
**Returns**: The filtered (modified) array.
|
||||
|
||||
|
||||
### delete(item) <sub>function</sub>
|
||||
|
||||
Remove the first occurrence of 'item' from the array, if it exists.
|
||||
Returns undefined.
|
||||
|
||||
|
||||
|
||||
**item**: The item to remove.
|
||||
|
||||
|
||||
**Returns**: undefined
|
||||
|
||||
|
||||
### copy() <sub>function</sub>
|
||||
|
||||
Return a deep copy of this array by applying 'deep_copy' to each element.
|
||||
The resulting array is entirely new.
|
||||
|
||||
|
||||
|
||||
**Returns**: A new array that is a deep copy of the original.
|
||||
|
||||
|
||||
### equal(b) <sub>function</sub>
|
||||
|
||||
Check if this array and array 'b' have the same elements in the same order.
|
||||
If they are of different lengths, return false. Otherwise compare them via JSON.
|
||||
|
||||
|
||||
|
||||
**b**: Another array to compare against.
|
||||
|
||||
|
||||
**Returns**: True if they match, false otherwise.
|
||||
|
||||
|
||||
### last() <sub>function</sub>
|
||||
|
||||
Return the last element of this array. If the array is empty, returns undefined.
|
||||
|
||||
|
||||
|
||||
**Returns**: The last element of the array, or undefined if empty.
|
||||
|
||||
|
||||
### wrapped(x) <sub>function</sub>
|
||||
|
||||
Return a copy of the array with the first 'x' elements appended to the end.
|
||||
Does not modify the original array.
|
||||
|
||||
|
||||
|
||||
**x**: The number of leading elements to re-append.
|
||||
|
||||
|
||||
**Returns**: A new array with the leading elements wrapped to the end.
|
||||
|
||||
|
||||
### wrap_idx(x) <sub>function</sub>
|
||||
|
||||
Wrap the integer 'x' around this array's length, ensuring the resulting index
|
||||
lies within [0, this.length - 1].
|
||||
|
||||
|
||||
|
||||
**x**: The index to wrap.
|
||||
|
||||
|
||||
**Returns**: A wrapped index within this array's bounds.
|
||||
|
||||
|
||||
### mirrored(x) <sub>function</sub>
|
||||
|
||||
Return a new array that appends a reversed copy (excluding the last element)
|
||||
of itself to the end. For example, [1,2,3] -> [1,2,3,2,1]. If the array has length
|
||||
<= 1, a copy of it is returned directly.
|
||||
|
||||
|
||||
|
||||
**Returns**: A new "mirrored" array.
|
||||
|
||||
@@ -3,9 +3,20 @@ c = 'emcc'
|
||||
cpp = 'em++'
|
||||
ar = 'emar'
|
||||
strip = 'emstrip'
|
||||
pkg-config = 'pkg-config'
|
||||
exe_wrapper = 'node'
|
||||
|
||||
[host_machine]
|
||||
system = 'emscripten'
|
||||
cpu_family = 'wasm64'
|
||||
cpu = 'wasm64'
|
||||
endian = 'little'
|
||||
cpu_family = 'wasm32'
|
||||
cpu = 'wasm32'
|
||||
endian = 'little'
|
||||
|
||||
[built-in options]
|
||||
pkg_config_path = '$EMSDK/upstream/emscripten/cache/sysroot/lib/pkgconfig'
|
||||
cmake_prefix_path = '$EMSDK/upstream/emscripten/cache/sysroot'
|
||||
|
||||
[properties]
|
||||
needs_exe_wrapper = true
|
||||
cmake_system_name = 'Emscripten'
|
||||
sys_root = '@env:EMSDK@/upstream/emscripten/cache/sysroot'
|
||||
|
||||
3
examples/chess/Makefile
Normal file
@@ -0,0 +1,3 @@
|
||||
def:
|
||||
cd _prosperon && make && cp build_dbg/prosperon ..
|
||||
./prosperon
|
||||
BIN
examples/chess/black_bishop.png
Normal file
|
After Width: | Height: | Size: 390 B |
BIN
examples/chess/black_king.png
Normal file
|
After Width: | Height: | Size: 438 B |
BIN
examples/chess/black_knight.png
Normal file
|
After Width: | Height: | Size: 398 B |
BIN
examples/chess/black_pawn.png
Normal file
|
After Width: | Height: | Size: 337 B |
BIN
examples/chess/black_queen.png
Normal file
|
After Width: | Height: | Size: 390 B |
BIN
examples/chess/black_rook.png
Normal file
|
After Width: | Height: | Size: 379 B |
9
examples/chess/config.js
Normal file
@@ -0,0 +1,9 @@
|
||||
// Chess game configuration for Moth framework
|
||||
return {
|
||||
title: "Chess",
|
||||
resolution: { width: 480, height: 480 },
|
||||
internal_resolution: { width: 480, height: 480 },
|
||||
fps: 60,
|
||||
clearColor: [22/255, 120/255, 194/255, 1],
|
||||
mode: 'stretch' // No letterboxing for chess
|
||||
};
|
||||
57
examples/chess/grid.js
Normal file
@@ -0,0 +1,57 @@
|
||||
var CELLS = Symbol()
|
||||
|
||||
var key = function key(x,y) { return `${x},${y}` }
|
||||
|
||||
function grid(w, h)
|
||||
{
|
||||
this[CELLS] = new Map()
|
||||
this.width = w;
|
||||
this.height = h;
|
||||
}
|
||||
|
||||
grid.prototype = {
|
||||
cell(x,y) {
|
||||
var k = key(x,y)
|
||||
if (!this[CELLS].has(k)) this[CELLS].set(k,[])
|
||||
return this[CELLS].get(k)
|
||||
},
|
||||
|
||||
add(entity, pos) {
|
||||
this.cell(pos.x, pos.y).push(entity);
|
||||
entity.coord = pos.slice();
|
||||
},
|
||||
|
||||
remove(entity, pos) {
|
||||
var c = this.cell(pos.x, pos.y);
|
||||
c.splice(c.indexOf(entity), 1);
|
||||
},
|
||||
|
||||
at(pos) {
|
||||
return this.cell(pos.x, pos.y);
|
||||
},
|
||||
|
||||
inBounds(pos) {
|
||||
return pos.x >= 0 && pos.x < this.width && pos.y >= 0 && pos.y < this.height;
|
||||
},
|
||||
|
||||
each(fn) {
|
||||
for (var [k, list] of this[CELLS])
|
||||
for (var p of list) fn(p, p.coord);
|
||||
},
|
||||
|
||||
toString() {
|
||||
var out = `grid [${this.width}x${this.height}]
|
||||
`
|
||||
for (var y = 0; y < this.height; y++) {
|
||||
for (var x = 0; x < this.width; x++) {
|
||||
var cell = this.at([x,y]);
|
||||
out += cell.length
|
||||
}
|
||||
if (y !== this.height - 1) out += "\n"
|
||||
}
|
||||
|
||||
return out
|
||||
},
|
||||
}
|
||||
|
||||
return grid
|
||||
422
examples/chess/main.js
Normal file
@@ -0,0 +1,422 @@
|
||||
/* main.js – runs the demo with your prototype-based grid */
|
||||
|
||||
var moth = use('moth')
|
||||
var json = use('json')
|
||||
|
||||
var res = 160
|
||||
var internal_res = 480
|
||||
|
||||
moth.initialize({ width:res, height:res, resolution_x:internal_res, resolution_y:internal_res, mode:'letterbox' });
|
||||
|
||||
var os = use('os');
|
||||
var draw2d = use('draw2d');
|
||||
var gfx = use('graphics');
|
||||
|
||||
/*──── import our pieces + systems ───────────────────────────────────*/
|
||||
var Grid = use('grid'); // your new ctor
|
||||
var MovementSystem = use('movement').MovementSystem;
|
||||
var startingPos = use('pieces').startingPosition;
|
||||
var rules = use('rules');
|
||||
|
||||
/*──── build board ───────────────────────────────────────────────────*/
|
||||
var grid = new Grid(8, 8);
|
||||
grid.width = 8; // (the ctor didn't store them)
|
||||
grid.height = 8;
|
||||
|
||||
var mover = new MovementSystem(grid, rules);
|
||||
startingPos(grid);
|
||||
|
||||
/*──── networking and game state ─────────────────────────────────────*/
|
||||
var gameState = 'waiting'; // 'waiting', 'searching', 'server_waiting', 'connected'
|
||||
var isServer = false;
|
||||
var opponent = null;
|
||||
var myColor = null; // 'white' or 'black'
|
||||
var isMyTurn = false;
|
||||
|
||||
function updateTitle() {
|
||||
var title = "Misty Chess - ";
|
||||
|
||||
switch(gameState) {
|
||||
case 'waiting':
|
||||
title += "Press S to start server or J to join";
|
||||
break;
|
||||
case 'searching':
|
||||
title += "Searching for server...";
|
||||
break;
|
||||
case 'server_waiting':
|
||||
title += "Waiting for player to join...";
|
||||
break;
|
||||
case 'connected':
|
||||
if (myColor) {
|
||||
title += (mover.turn === myColor ? "Your turn (" + myColor + ")" : "Opponent's turn (" + mover.turn + ")");
|
||||
} else {
|
||||
title += mover.turn + " turn";
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
prosperon.window.title = title
|
||||
}
|
||||
|
||||
// Initialize title
|
||||
updateTitle();
|
||||
|
||||
/*──── mouse → click-to-move ─────────────────────────────────────────*/
|
||||
var selectPos = null;
|
||||
var hoverPos = null;
|
||||
var holdingPiece = false;
|
||||
|
||||
var opponentMousePos = null;
|
||||
var opponentHoldingPiece = false;
|
||||
var opponentSelectPos = null;
|
||||
|
||||
prosperon.on('mouse_button_down', function(e) {
|
||||
if (e.which !== 0) return;
|
||||
|
||||
// Don't allow piece selection unless we have an opponent
|
||||
if (gameState !== 'connected' || !opponent) return;
|
||||
|
||||
var mx = e.mouse.x;
|
||||
var my = e.mouse.y;
|
||||
|
||||
var c = [Math.floor(mx / 60), Math.floor(my / 60)];
|
||||
if (!grid.inBounds(c)) return;
|
||||
|
||||
var cell = grid.at(c);
|
||||
if (cell.length && cell[0].colour === mover.turn) {
|
||||
selectPos = c;
|
||||
holdingPiece = true;
|
||||
// Send pickup notification to opponent
|
||||
if (opponent) {
|
||||
$_.send(opponent, {
|
||||
type: 'piece_pickup',
|
||||
pos: c
|
||||
});
|
||||
}
|
||||
} else {
|
||||
selectPos = null;
|
||||
}
|
||||
})
|
||||
|
||||
prosperon.on('mouse_button_up', function(e) {
|
||||
if (e.which !== 0 || !holdingPiece || !selectPos) return;
|
||||
|
||||
// Don't allow moves unless we have an opponent and it's our turn
|
||||
if (gameState !== 'connected' || !opponent || !isMyTurn) {
|
||||
holdingPiece = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var mx = e.mouse.x;
|
||||
var my = e.mouse.y;
|
||||
|
||||
var c = [Math.floor(mx / 60), Math.floor(my / 60)];
|
||||
if (!grid.inBounds(c)) {
|
||||
holdingPiece = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (mover.tryMove(grid.at(selectPos)[0], c)) {
|
||||
console.log("Made move from", selectPos, "to", c);
|
||||
// Send move to opponent
|
||||
console.log("Sending move to opponent:", opponent);
|
||||
$_.send(opponent, {
|
||||
type: 'move',
|
||||
from: selectPos,
|
||||
to: c
|
||||
});
|
||||
isMyTurn = false; // It's now opponent's turn
|
||||
console.log("Move sent, now opponent's turn");
|
||||
selectPos = null;
|
||||
updateTitle();
|
||||
}
|
||||
|
||||
holdingPiece = false;
|
||||
|
||||
// Send piece drop notification to opponent
|
||||
if (opponent) {
|
||||
$_.send(opponent, {
|
||||
type: 'piece_drop'
|
||||
});
|
||||
}
|
||||
})
|
||||
|
||||
prosperon.on('mouse_motion', function(e) {
|
||||
var mx = e.pos.x;
|
||||
var my = e.pos.y;
|
||||
|
||||
var c = [Math.floor(mx / 60), Math.floor(my / 60)];
|
||||
if (!grid.inBounds(c)) {
|
||||
hoverPos = null;
|
||||
return;
|
||||
}
|
||||
|
||||
hoverPos = c;
|
||||
|
||||
// Send mouse position to opponent in real-time
|
||||
if (opponent && gameState === 'connected') {
|
||||
$_.send(opponent, {
|
||||
type: 'mouse_move',
|
||||
pos: c,
|
||||
holding: holdingPiece,
|
||||
selectPos: selectPos
|
||||
});
|
||||
}
|
||||
})
|
||||
|
||||
/*──── drawing helpers ───────────────────────────────────────────────*/
|
||||
/* ── constants ─────────────────────────────────────────────────── */
|
||||
var S = 60; // square size in px
|
||||
var light = [0.93,0.93,0.93,1];
|
||||
var dark = [0.25,0.25,0.25,1];
|
||||
var allowedColor = [1.0, 0.84, 0.0, 1.0]; // Gold for allowed moves
|
||||
var myMouseColor = [0.0, 1.0, 0.0, 1.0]; // Green for my mouse
|
||||
var opponentMouseColor = [1.0, 0.0, 0.0, 1.0]; // Red for opponent mouse
|
||||
|
||||
/* ── draw one 8×8 chess board ──────────────────────────────────── */
|
||||
function drawBoard() {
|
||||
for (var y = 0; y < 8; ++y)
|
||||
for (var x = 0; x < 8; ++x) {
|
||||
var isMyHover = hoverPos && hoverPos[0] === x && hoverPos[1] === y;
|
||||
var isOpponentHover = opponentMousePos && opponentMousePos[0] === x && opponentMousePos[1] === y;
|
||||
var isValidMove = selectPos && holdingPiece && isValidMoveForTurn(selectPos, [x, y]);
|
||||
|
||||
var color = ((x+y)&1) ? dark : light;
|
||||
|
||||
if (isValidMove) {
|
||||
color = allowedColor; // Gold for allowed moves
|
||||
} else if (isMyHover && !isOpponentHover) {
|
||||
color = myMouseColor; // Green for my mouse
|
||||
} else if (isOpponentHover) {
|
||||
color = opponentMouseColor; // Red for opponent mouse
|
||||
}
|
||||
|
||||
draw2d.rectangle(
|
||||
{ x: x*S, y: y*S, width: S, height: S },
|
||||
{ thickness: 0, color: color }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function isValidMoveForTurn(from, to) {
|
||||
if (!grid.inBounds(to)) return false;
|
||||
|
||||
var piece = grid.at(from)[0];
|
||||
if (!piece) return false;
|
||||
|
||||
// Check if the destination has a piece of the same color
|
||||
var destCell = grid.at(to);
|
||||
if (destCell.length && destCell[0].colour === piece.colour) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return rules.canMove(piece, from, to, grid);
|
||||
}
|
||||
|
||||
/* ── draw every live piece ─────────────────────────────────────── */
|
||||
function drawPieces() {
|
||||
grid.each(function (piece) {
|
||||
if (piece.captured) return;
|
||||
|
||||
// Skip drawing the piece being held (by me or opponent)
|
||||
if (holdingPiece && selectPos &&
|
||||
piece.coord[0] === selectPos[0] &&
|
||||
piece.coord[1] === selectPos[1]) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip drawing the piece being held by opponent
|
||||
if (opponentHoldingPiece && opponentSelectPos &&
|
||||
piece.coord[0] === opponentSelectPos[0] &&
|
||||
piece.coord[1] === opponentSelectPos[1]) {
|
||||
return;
|
||||
}
|
||||
|
||||
var r = { x: piece.coord[0]*S, y: piece.coord[1]*S,
|
||||
width:S, height:S };
|
||||
|
||||
draw2d.image(piece.sprite, r, 0, [0,0], [0,0], {mode:"nearest"});
|
||||
});
|
||||
|
||||
// Draw the held piece at the mouse position if we're holding one
|
||||
if (holdingPiece && selectPos && hoverPos) {
|
||||
var piece = grid.at(selectPos)[0];
|
||||
if (piece) {
|
||||
var r = { x: hoverPos[0]*S, y: hoverPos[1]*S,
|
||||
width:S, height:S };
|
||||
|
||||
draw2d.image(piece.sprite, r, 0, [0,0], [0,0], {mode:"nearest"});
|
||||
}
|
||||
}
|
||||
|
||||
// Draw opponent's held piece if they're dragging one
|
||||
if (opponentHoldingPiece && opponentSelectPos && opponentMousePos) {
|
||||
var opponentPiece = grid.at(opponentSelectPos)[0];
|
||||
if (opponentPiece) {
|
||||
var r = { x: opponentMousePos[0]*S, y: opponentMousePos[1]*S,
|
||||
width:S, height:S };
|
||||
|
||||
// Draw with slight transparency to show it's the opponent's piece
|
||||
draw2d.image(opponentPiece.sprite, r, 0, [0,0], [0,0], {mode:"nearest", color: [1, 1, 1, 0.7]});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
prosperon.on('draw', function() {
|
||||
drawBoard()
|
||||
drawPieces()
|
||||
})
|
||||
|
||||
prosperon.on('key_down', function(e) {
|
||||
// S key - start server
|
||||
if (e.scancode === 22 && gameState === 'waiting') { // S key
|
||||
startServer();
|
||||
}
|
||||
// J key - join server
|
||||
else if (e.scancode === 13 && gameState === 'waiting') { // J key
|
||||
joinServer();
|
||||
}
|
||||
})
|
||||
|
||||
function startServer() {
|
||||
gameState = 'server_waiting';
|
||||
isServer = true;
|
||||
myColor = 'white';
|
||||
isMyTurn = true;
|
||||
updateTitle();
|
||||
|
||||
console.log("Starting server with actor:", json.encode($_));
|
||||
|
||||
$_.portal(e => {
|
||||
console.log("Portal received contact message:", json.encode(e));
|
||||
|
||||
// The proper Misty pattern: Portal should only reply with an actor reference
|
||||
// Use a clean actor object, not application data
|
||||
$_.send(e, { id: $_.id }); // Send a clean actor reference
|
||||
|
||||
console.log("Portal replied with server actor reference");
|
||||
}, 5678);
|
||||
}
|
||||
|
||||
function joinServer() {
|
||||
gameState = 'searching';
|
||||
updateTitle();
|
||||
|
||||
console.log("Client attempting to join server with client actor:", json.encode($_));
|
||||
|
||||
function contact_fn(actor, reason) {
|
||||
console.log("Contact callback received:", actor ? "SUCCESS" : "FAILED", reason);
|
||||
|
||||
if (actor) {
|
||||
// Ensure we have a clean actor reference with just the id
|
||||
if (typeof actor === 'object' && actor.id) {
|
||||
// Store server actor reference for ongoing communication
|
||||
opponent = { id: actor.id }; // Clean actor reference
|
||||
console.log("Connection established with server actor:", json.encode(opponent));
|
||||
|
||||
// Now that we have the server actor reference, send application message
|
||||
// This follows the two-phase Misty pattern:
|
||||
// 1. First establish actor connection (done with contact)
|
||||
// 2. Then send application messages
|
||||
console.log("Sending greet message to server");
|
||||
$_.send(opponent, {
|
||||
type: 'greet',
|
||||
client_actor: { id: $_.id } // Send clean actor reference
|
||||
});
|
||||
|
||||
// Update game state now that we're connected
|
||||
gameState = 'connected';
|
||||
updateTitle();
|
||||
} else {
|
||||
console.log("Received invalid actor reference:", json.encode(actor));
|
||||
gameState = 'waiting';
|
||||
updateTitle();
|
||||
}
|
||||
} else {
|
||||
console.log(`Failed to connect: ${json.encode(reason)}`);
|
||||
gameState = 'waiting';
|
||||
updateTitle();
|
||||
}
|
||||
}
|
||||
|
||||
// Initial contact phase - get actor reference only
|
||||
$_.contact(contact_fn, {
|
||||
address: "localhost",
|
||||
port: 5678
|
||||
});
|
||||
}
|
||||
|
||||
var os = use('os')
|
||||
|
||||
// Set up IO actor subscription
|
||||
var ioguy = { id: os.ioactor() };
|
||||
|
||||
$_.send(ioguy, {
|
||||
type: "subscribe",
|
||||
actor: $_
|
||||
});
|
||||
|
||||
$_.receiver(e => {
|
||||
if (e.type === 'game_start' || e.type === 'move' || e.type === 'greet')
|
||||
console.log("Receiver got message:", e.type, e);
|
||||
if (e.type === 'quit') os.exit()
|
||||
|
||||
if (e.type === 'greet') {
|
||||
console.log("Server received greet from client");
|
||||
// Store the client's actor object for ongoing communication
|
||||
if (e.client_actor && e.client_actor.id) {
|
||||
opponent = { id: e.client_actor.id }; // Clean actor reference
|
||||
console.log("Stored client actor:", json.encode(opponent));
|
||||
gameState = 'connected';
|
||||
updateTitle();
|
||||
|
||||
// Send game_start to the client
|
||||
console.log("Sending game_start to client");
|
||||
$_.send(opponent, {
|
||||
type: 'game_start',
|
||||
your_color: 'black'
|
||||
});
|
||||
console.log("game_start message sent to client");
|
||||
} else {
|
||||
console.log("Invalid client actor in greet message:", json.encode(e));
|
||||
}
|
||||
}
|
||||
else if (e.type === 'game_start') {
|
||||
console.log("Game starting, I am:", e.your_color);
|
||||
myColor = e.your_color;
|
||||
isMyTurn = (myColor === 'white');
|
||||
gameState = 'connected';
|
||||
updateTitle();
|
||||
} else if (e.type === 'move') {
|
||||
console.log("Received move from opponent:", e.from, "to", e.to);
|
||||
// Apply opponent's move
|
||||
var fromCell = grid.at(e.from);
|
||||
if (fromCell.length) {
|
||||
var piece = fromCell[0];
|
||||
if (mover.tryMove(piece, e.to)) {
|
||||
isMyTurn = true; // It's now our turn
|
||||
updateTitle();
|
||||
console.log("Applied opponent move, now my turn");
|
||||
} else {
|
||||
console.log("Failed to apply opponent move");
|
||||
}
|
||||
} else {
|
||||
console.log("No piece found at from position");
|
||||
}
|
||||
} else if (e.type === 'mouse_move') {
|
||||
// Update opponent's mouse position
|
||||
opponentMousePos = e.pos;
|
||||
opponentHoldingPiece = e.holding;
|
||||
opponentSelectPos = e.selectPos;
|
||||
} else if (e.type === 'piece_pickup') {
|
||||
// Opponent picked up a piece
|
||||
opponentSelectPos = e.pos;
|
||||
opponentHoldingPiece = true;
|
||||
} else if (e.type === 'piece_drop') {
|
||||
// Opponent dropped their piece
|
||||
opponentHoldingPiece = false;
|
||||
opponentSelectPos = null;
|
||||
}
|
||||
|
||||
prosperon.dispatch(e.type, e)
|
||||
})
|
||||
32
examples/chess/movement.js
Normal file
@@ -0,0 +1,32 @@
|
||||
var MovementSystem = function(grid, rules) {
|
||||
this.grid = grid;
|
||||
this.rules = rules || {}; // expects { canMove: fn }
|
||||
this.turn = 'white';
|
||||
}
|
||||
|
||||
MovementSystem.prototype.tryMove = function (piece, to) {
|
||||
if (piece.colour !== this.turn) return false;
|
||||
|
||||
// normalise ‘to’ into our hybrid coord
|
||||
var dest = [to.x !== undefined ? to.x : to[0],
|
||||
to.y !== undefined ? to.y : to[1]];
|
||||
|
||||
if (!this.grid.inBounds(dest)) return false;
|
||||
if (!this.rules.canMove(piece, piece.coord, dest, this.grid)) return false;
|
||||
|
||||
var victims = this.grid.at(dest);
|
||||
if (victims.length && victims[0].colour === piece.colour) return false;
|
||||
if (victims.length) victims[0].captured = true;
|
||||
|
||||
this.grid.remove(piece, piece.coord);
|
||||
this.grid.add (piece, dest);
|
||||
|
||||
// grid.add() re-creates coord; re-add .x/.y fields:
|
||||
piece.coord.x = dest.x;
|
||||
piece.coord.y = dest.y;
|
||||
|
||||
this.turn = (this.turn === 'white') ? 'black' : 'white';
|
||||
return true;
|
||||
};
|
||||
|
||||
return { MovementSystem: MovementSystem };
|
||||
29
examples/chess/pieces.js
Normal file
@@ -0,0 +1,29 @@
|
||||
/* pieces.js – simple data holders + starting layout */
|
||||
function Piece(kind, colour) {
|
||||
this.kind = kind; // "pawn" etc.
|
||||
this.colour = colour; // "white"/"black"
|
||||
this.sprite = colour + '_' + kind; // for draw2d.image
|
||||
this.captured = false;
|
||||
this.coord = [0,0];
|
||||
}
|
||||
Piece.prototype.toString = function () {
|
||||
return this.colour.charAt(0) + this.kind.charAt(0).toUpperCase();
|
||||
};
|
||||
|
||||
function startingPosition(grid) {
|
||||
var W = 'white', B = 'black', x;
|
||||
|
||||
// pawns
|
||||
for (x = 0; x < 8; x++) {
|
||||
grid.add(new Piece('pawn', W), [x, 6]);
|
||||
grid.add(new Piece('pawn', B), [x, 1]);
|
||||
}
|
||||
// major pieces
|
||||
var back = ['rook','knight','bishop','queen','king','bishop','knight','rook'];
|
||||
for (x = 0; x < 8; x++) {
|
||||
grid.add(new Piece(back[x], W), [x, 7]);
|
||||
grid.add(new Piece(back[x], B), [x, 0]);
|
||||
}
|
||||
}
|
||||
|
||||
return { Piece, startingPosition };
|
||||
BIN
examples/chess/prosperon
Executable file
45
examples/chess/rules.js
Normal file
@@ -0,0 +1,45 @@
|
||||
/* helper – robust coord access */
|
||||
function cx(c) { return (c.x !== undefined) ? c.x : c[0]; }
|
||||
function cy(c) { return (c.y !== undefined) ? c.y : c[1]; }
|
||||
|
||||
/* simple move-shape checks */
|
||||
var deltas = {
|
||||
pawn: function (pc, dx, dy, grid, to) {
|
||||
var dir = (pc.colour === 'white') ? -1 : 1;
|
||||
var base = (pc.colour === 'white') ? 6 : 1;
|
||||
var one = (dy === dir && dx === 0 && grid.at(to).length === 0);
|
||||
var two = (dy === 2 * dir && dx === 0 && cy(pc.coord) === base &&
|
||||
grid.at({ x: cx(pc.coord), y: cy(pc.coord)+dir }).length === 0 &&
|
||||
grid.at(to).length === 0);
|
||||
var cap = (dy === dir && Math.abs(dx) === 1 && grid.at(to).length);
|
||||
return one || two || cap;
|
||||
},
|
||||
rook : function (pc, dx, dy) { return (dx === 0 || dy === 0); },
|
||||
bishop: function (pc, dx, dy) { return Math.abs(dx) === Math.abs(dy); },
|
||||
queen : function (pc, dx, dy) { return (dx === 0 || dy === 0 || Math.abs(dx) === Math.abs(dy)); },
|
||||
knight: function (pc, dx, dy) { return (Math.abs(dx) === 1 && Math.abs(dy) === 2) ||
|
||||
(Math.abs(dx) === 2 && Math.abs(dy) === 1); },
|
||||
king : function (pc, dx, dy) { return Math.max(Math.abs(dx), Math.abs(dy)) === 1; }
|
||||
};
|
||||
|
||||
function clearLine(from, to, grid) {
|
||||
var dx = Math.sign(cx(to) - cx(from));
|
||||
var dy = Math.sign(cy(to) - cy(from));
|
||||
var x = cx(from) + dx, y = cy(from) + dy;
|
||||
while (x !== cx(to) || y !== cy(to)) {
|
||||
if (grid.at({ x: x, y: y }).length) return false;
|
||||
x += dx; y += dy;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function canMove(piece, from, to, grid) {
|
||||
var dx = cx(to) - cx(from);
|
||||
var dy = cy(to) - cy(from);
|
||||
var f = deltas[piece.kind];
|
||||
if (!f || !f(piece, dx, dy, grid, to)) return false;
|
||||
if (piece.kind === 'knight') return true;
|
||||
return clearLine(from, to, grid);
|
||||
}
|
||||
|
||||
return { canMove };
|
||||
BIN
examples/chess/white_bishop.png
Normal file
|
After Width: | Height: | Size: 376 B |
BIN
examples/chess/white_king.png
Normal file
|
After Width: | Height: | Size: 403 B |
BIN
examples/chess/white_knight.png
Normal file
|
After Width: | Height: | Size: 381 B |
BIN
examples/chess/white_pawn.png
Normal file
|
After Width: | Height: | Size: 313 B |
BIN
examples/chess/white_queen.png
Normal file
|
After Width: | Height: | Size: 378 B |
BIN
examples/chess/white_rook.png
Normal file
|
After Width: | Height: | Size: 378 B |
258
meson.build
@@ -1,13 +1,14 @@
|
||||
project('prosperon', ['c', 'cpp'], default_options : [ 'cpp_std=c++11'])
|
||||
project('prosperon', ['c', 'cpp'],
|
||||
version: '0.9.3',
|
||||
meson_version: '>=1.4',
|
||||
default_options : [ 'cpp_std=c++11'])
|
||||
|
||||
libtype = get_option('default_library')
|
||||
libtype = get_option('default_library')
|
||||
|
||||
link = []
|
||||
src = []
|
||||
|
||||
if not get_option('editor')
|
||||
add_project_arguments('-DNEDITOR', language:'c')
|
||||
endif
|
||||
add_project_arguments('-pedantic', language: ['c'])
|
||||
|
||||
git_tag_cmd = run_command('git', 'describe', '--tags', '--abbrev=0', check: false)
|
||||
prosperon_version = 'unknown'
|
||||
@@ -31,21 +32,51 @@ add_project_arguments(
|
||||
add_project_arguments('-Wno-incompatible-pointer-types', language: 'c')
|
||||
add_project_arguments('-Wno-narrowing', language: 'cpp')
|
||||
add_project_arguments('-Wno-missing-braces', language:'c')
|
||||
add_project_arguments('-Wl,--disable-new-dtags', language:'cpp')
|
||||
add_project_arguments('-Wl,--disable-new-dtags', language:'c')
|
||||
add_project_arguments('-Wno-strict-prototypes', language:'c')
|
||||
add_project_arguments('-Wno-unused-command-line-argument', language: 'c')
|
||||
add_project_arguments('-Wno-unused-command-line-argument', language: 'cpp')
|
||||
|
||||
deps = []
|
||||
|
||||
if host_machine.system() == 'darwin'
|
||||
add_project_arguments('-x', 'objective-c', language: 'c')
|
||||
fworks = ['foundation', 'metal', 'audiotoolbox', 'metalkit', 'avfoundation', 'quartzcore', 'cocoa']
|
||||
fworks = [
|
||||
'foundation',
|
||||
'metal',
|
||||
'audiotoolbox',
|
||||
'metalkit',
|
||||
'avfoundation',
|
||||
'quartzcore',
|
||||
'cocoa',
|
||||
'coreaudio',
|
||||
'coremedia',
|
||||
'gamecontroller',
|
||||
'forcefeedback',
|
||||
'iokit',
|
||||
'corefoundation',
|
||||
'corehaptics',
|
||||
'carbon',
|
||||
'uniformtypeidentifiers'
|
||||
]
|
||||
foreach fkit : fworks
|
||||
deps += dependency('appleframeworks', modules: fkit)
|
||||
endforeach
|
||||
endif
|
||||
|
||||
cmake = import('cmake')
|
||||
|
||||
sdl3_opts = cmake.subproject_options()
|
||||
sdl3_opts.add_cmake_defines({
|
||||
'SDL_STATIC': 'ON',
|
||||
'SDL_SHARED': 'OFF',
|
||||
'SDL_TEST': 'OFF',
|
||||
'CMAKE_BUILD_TYPE': 'Release',
|
||||
'SDL_THREADS': 'ON',
|
||||
'SDL_PIPEWIRE': 'ON',
|
||||
'SDL_PULSEAUDIO': 'ON',
|
||||
})
|
||||
|
||||
cc = meson.get_compiler('c')
|
||||
deps += dependency('sdl3', required:true)
|
||||
|
||||
if host_machine.system() == 'darwin'
|
||||
deps += dependency('appleframeworks', modules: 'accelerate')
|
||||
@@ -56,72 +87,162 @@ endif
|
||||
if host_machine.system() == 'linux'
|
||||
deps += cc.find_library('asound', required:true)
|
||||
deps += [dependency('x11'), dependency('xi'), dependency('xcursor'), dependency('egl'), dependency('gl')]
|
||||
# link += '-fuse-ld=mold' # use mold, which is very fast, for debug builds
|
||||
endif
|
||||
|
||||
if host_machine.system() == 'windows'
|
||||
deps += cc.find_library('d3d11')
|
||||
# these are for tracy
|
||||
deps += cc.find_library('ws2_32', required:true)
|
||||
deps += cc.find_library('dbghelp')
|
||||
#end
|
||||
link += '-static' # Required to pack in mingw dlls on cross compilation
|
||||
deps += cc.find_library('winmm')
|
||||
deps += cc.find_library('setupapi')
|
||||
deps += cc.find_library('imm32')
|
||||
deps += cc.find_library('version')
|
||||
deps += cc.find_library('cfgmgr32')
|
||||
deps += cc.find_library('bcrypt')
|
||||
sdl3_opts.add_cmake_defines({'HAVE_ISINF': '1'}) # Hack for MSYS2
|
||||
sdl3_opts.add_cmake_defines({'HAVE_ISNAN': '1'})
|
||||
link += '-static'
|
||||
endif
|
||||
|
||||
if host_machine.system() == 'emscripten'
|
||||
link += '-sUSE_WEBGPU'
|
||||
# Use the pre-installed copy
|
||||
deps += dependency('sdl3',
|
||||
static : true,
|
||||
method : 'pkg-config', # or 'cmake' if you prefer
|
||||
required : true)
|
||||
else
|
||||
sdl3_proj = cmake.subproject('sdl3', options : sdl3_opts)
|
||||
deps += sdl3_proj.dependency('SDL3-static')
|
||||
endif
|
||||
|
||||
tracy_opts = ['fibers=true', 'on_demand=true']
|
||||
|
||||
quickjs_opts = []
|
||||
|
||||
src += 'qjs_tracy.c'
|
||||
add_project_arguments('-DTRACY_ENABLE', language:['c','cpp'])
|
||||
deps += dependency('tracy', static:true, default_options:tracy_opts)
|
||||
|
||||
quickjs_opts += 'default_library=static'
|
||||
|
||||
deps += dependency('quickjs', static:true, default_options:quickjs_opts)
|
||||
|
||||
storefront = get_option('storefront')
|
||||
if storefront == 'steam'
|
||||
deps += dependency('qjs-steam',static:false)
|
||||
endif
|
||||
|
||||
deps += dependency('qjs-layout',static:true)
|
||||
deps += dependency('qjs-nota',static:true)
|
||||
deps += dependency('qjs-miniz',static:true)
|
||||
deps += dependency('qjs-soloud',static:true)
|
||||
deps += dependency('qjs-layout', static:true)
|
||||
deps += dependency('qjs-miniz', static:true)
|
||||
deps += dependency('physfs', static:true)
|
||||
|
||||
#deps += dependency('opencv4')
|
||||
#deps += cc.find_library('opencv')
|
||||
|
||||
deps += dependency('threads')
|
||||
deps += dependency('chipmunk', static:true)
|
||||
|
||||
deps += dependency('chipmunk')
|
||||
if host_machine.system() != 'emscripten'
|
||||
deps += dependency('enet', static:true)
|
||||
src += 'qjs_enet.c'
|
||||
|
||||
if get_option('chipmunk')
|
||||
# deps += dependency('qjs-chipmunk', static:false)
|
||||
src += 'qjs_tracy.c'
|
||||
tracy_opts = ['fibers=true', 'on_demand=true']
|
||||
add_project_arguments('-DTRACY_ENABLE', language:['c','cpp'])
|
||||
deps += dependency('tracy', static:true, default_options:tracy_opts)
|
||||
|
||||
src += 'qjs_dmon.c'
|
||||
endif
|
||||
|
||||
if get_option('enet')
|
||||
#deps += dependency('qjs-enet', static:false)
|
||||
endif
|
||||
deps += dependency('soloud', static:true)
|
||||
deps += dependency('libqrencode', static:true)
|
||||
|
||||
link_args = link
|
||||
sources = []
|
||||
src += ['anim.c', 'config.c', 'datastream.c','font.c','gameobject.c','HandmadeMath.c','jsffi.c','model.c','render.c','script.c','simplex.c','spline.c', 'timer.c', 'transform.c','prosperon.c', 'wildmatch.c', 'sprite.c', 'quadtree.c', 'aabb.c', 'rtree.c']
|
||||
src += [
|
||||
'anim.c', 'config.c', 'datastream.c','font.c','HandmadeMath.c','jsffi.c','model.c',
|
||||
'render.c','simplex.c','spline.c', 'transform.c','prosperon.c', 'wildmatch.c',
|
||||
'sprite.c', 'rtree.c', 'qjs_nota.c', 'qjs_soloud.c',
|
||||
'qjs_qr.c', 'qjs_wota.c', 'monocypher.c', 'qjs_blob.c', 'qjs_crypto.c', 'qjs_time.c', 'qjs_http.c'
|
||||
]
|
||||
# quirc src
|
||||
src += [
|
||||
'thirdparty/quirc/quirc.c', 'thirdparty/quirc/decode.c',
|
||||
'thirdparty/quirc/identify.c', 'thirdparty/quirc/version_db.c'
|
||||
]
|
||||
|
||||
imsrc = ['GraphEditor.cpp','ImCurveEdit.cpp','ImGradient.cpp','imgui_draw.cpp','imgui_tables.cpp','imgui_widgets.cpp','imgui.cpp','ImGuizmo.cpp','imnodes.cpp','implot_items.cpp','implot.cpp', 'imgui_impl_sdlrenderer3.cpp', 'imgui_impl_sdl3.cpp', 'imgui_impl_sdlgpu3.cpp']
|
||||
curl_opts = [
|
||||
'http=enabled',
|
||||
'ssl=enabled',
|
||||
'openssl=enabled',
|
||||
'schannel=disabled',
|
||||
'secure-transport=disabled',
|
||||
'dict=disabled',
|
||||
'file=disabled',
|
||||
'ftp=disabled',
|
||||
'gopher=disabled',
|
||||
'imap=disabled',
|
||||
'ldap=disabled',
|
||||
'ldaps=disabled',
|
||||
'mqtt=disabled',
|
||||
'pop3=disabled',
|
||||
'rtmp=disabled',
|
||||
'rtsp=disabled',
|
||||
'smb=disabled',
|
||||
'smtp=disabled',
|
||||
'telnet=disabled',
|
||||
'tftp=disabled',
|
||||
'alt-svc=disabled',
|
||||
'asynchdns=disabled',
|
||||
'aws=disabled',
|
||||
'basic-auth=disabled',
|
||||
'bearer-auth=disabled',
|
||||
'bindlocal=disabled',
|
||||
'brotli=disabled',
|
||||
'cookies=disabled',
|
||||
'digest-auth=disabled',
|
||||
'doh=disabled',
|
||||
'form-api=disabled',
|
||||
'getoptions=disabled',
|
||||
'gsasl=disabled',
|
||||
'gss-api=disabled',
|
||||
'headers-api=disabled',
|
||||
'hsts=disabled',
|
||||
'http2=disabled',
|
||||
'idn=disabled',
|
||||
'kerberos-auth=disabled',
|
||||
'libcurl-option=disabled',
|
||||
'libz=disabled',
|
||||
'mime=disabled',
|
||||
'negotiate-auth=disabled',
|
||||
'netrc=disabled',
|
||||
'ntlm=disabled',
|
||||
'parsedate=disabled',
|
||||
'progress-meter=disabled',
|
||||
'proxy=disabled',
|
||||
'psl=disabled',
|
||||
'sha512_256=disabled',
|
||||
'shuffle-dns=disabled',
|
||||
'socketpair=disabled',
|
||||
'tls-srp=disabled',
|
||||
'unixsockets=disabled',
|
||||
'verbose-strings=disabled',
|
||||
'zstd=disabled',
|
||||
'debug=disabled',
|
||||
'curldebug=false',
|
||||
'libuv=disabled',
|
||||
'tests=disabled',
|
||||
'unittests=disabled',
|
||||
'default_library=static'
|
||||
]
|
||||
|
||||
curl_proj = subproject('curl', default_options: curl_opts)
|
||||
deps += dependency('libcurl')
|
||||
deps += dependency('zlib', static: true)
|
||||
deps += dependency('openssl', static:true)
|
||||
|
||||
imsrc = [
|
||||
'GraphEditor.cpp','ImCurveEdit.cpp','ImGradient.cpp','imgui_draw.cpp',
|
||||
'imgui_tables.cpp','imgui_widgets.cpp','imgui.cpp','ImGuizmo.cpp','imnodes.cpp',
|
||||
'implot_items.cpp','implot.cpp','imgui_impl_sdlrenderer3.cpp','imgui_impl_sdl3.cpp',
|
||||
'imgui_impl_sdlgpu3.cpp'
|
||||
]
|
||||
|
||||
srceng = 'source'
|
||||
tp = srceng / 'thirdparty'
|
||||
|
||||
includes = [srceng,tp / 'cgltf',tp / 'imgui',tp / 'par',tp / 'stb',tp,tp / 'pl_mpeg/include']
|
||||
includes = [
|
||||
srceng, tp / 'cgltf', tp / 'imgui', tp / 'par', tp / 'stb',
|
||||
tp, tp / 'pl_mpeg/include', tp / 'quirc'
|
||||
]
|
||||
|
||||
foreach file : src
|
||||
full_path = join_paths('source', file)
|
||||
sources += files(full_path)
|
||||
full_path = join_paths('source', file)
|
||||
sources += files(full_path)
|
||||
endforeach
|
||||
|
||||
if get_option('editor')
|
||||
@@ -129,8 +250,6 @@ if get_option('editor')
|
||||
foreach imgui : imsrc
|
||||
sources += tp / 'imgui' / imgui
|
||||
endforeach
|
||||
# sub_dmon = subproject('qjs-dmon')
|
||||
# dmon_dep = sub_dmon.get_variable('qjs_dmon_dep')
|
||||
endif
|
||||
|
||||
includers = []
|
||||
@@ -144,7 +263,7 @@ foreach folder: zip_folders
|
||||
zip_paths += meson.project_source_root() / folder
|
||||
endforeach
|
||||
|
||||
# Now use the hash file as a dependency so that any change in the files causes a rebuild.
|
||||
# Produce core.zip
|
||||
core = custom_target('core.zip',
|
||||
output : 'core.zip',
|
||||
command : ['sh', '-c',
|
||||
@@ -152,7 +271,7 @@ core = custom_target('core.zip',
|
||||
' && echo "Rebuilding core.zip" && rm -f ' + meson.current_build_dir() + '/core.zip && ' +
|
||||
'zip -r ' + meson.current_build_dir() + '/core.zip scripts fonts icons shaders'
|
||||
],
|
||||
build_always: true,
|
||||
build_always_stale: true,
|
||||
build_by_default: true
|
||||
)
|
||||
|
||||
@@ -164,6 +283,26 @@ prosperon_raw = executable('prosperon_raw', sources,
|
||||
install:false
|
||||
)
|
||||
|
||||
strip_enabled = ['release', 'minsize'].contains(get_option('buildtype'))
|
||||
|
||||
if strip_enabled
|
||||
prosperon_raw_stripped = custom_target('prosperon_raw_stripped',
|
||||
input: prosperon_raw,
|
||||
output: 'prosperon_raw_stripped',
|
||||
command: [
|
||||
'sh', '-c',
|
||||
'strip "$1" && cp "$1" "$2"',
|
||||
'stripper',
|
||||
'@INPUT@',
|
||||
'@OUTPUT@'
|
||||
],
|
||||
build_by_default: true
|
||||
)
|
||||
exe_for_concat = prosperon_raw_stripped
|
||||
else
|
||||
exe_for_concat = prosperon_raw
|
||||
endif
|
||||
|
||||
if host_machine.system() == 'windows'
|
||||
exe_ext = '.exe'
|
||||
else
|
||||
@@ -172,7 +311,7 @@ endif
|
||||
|
||||
prosperon = custom_target('prosperon',
|
||||
output: 'prosperon' + exe_ext,
|
||||
input: [prosperon_raw, core],
|
||||
input: [exe_for_concat, core],
|
||||
command: [
|
||||
'sh', '-c',
|
||||
'cat "$1" "$2" > "$3" && chmod +x "$3" >/dev/null 2>&1',
|
||||
@@ -181,12 +320,12 @@ prosperon = custom_target('prosperon',
|
||||
'@INPUT1@',
|
||||
'@OUTPUT@'
|
||||
],
|
||||
build_always: true,
|
||||
build_always_stale: true,
|
||||
build_by_default: true
|
||||
)
|
||||
|
||||
prosperon_dep = declare_dependency(
|
||||
link_with:prosperon
|
||||
link_with: prosperon
|
||||
)
|
||||
|
||||
copy_tests = custom_target(
|
||||
@@ -194,19 +333,24 @@ copy_tests = custom_target(
|
||||
output: 'tests',
|
||||
command: [
|
||||
'cp', '-rf',
|
||||
join_paths(meson.source_root(), 'tests'),
|
||||
meson.build_root()
|
||||
join_paths(meson.project_source_root(), 'tests'),
|
||||
meson.project_build_root()
|
||||
],
|
||||
build_always: true,
|
||||
build_always_stale: true,
|
||||
build_by_default: true
|
||||
)
|
||||
|
||||
tests = [
|
||||
'spawn_actor',
|
||||
'empty'
|
||||
'empty',
|
||||
'nota',
|
||||
'wota',
|
||||
'portalspawner',
|
||||
'overling',
|
||||
'send',
|
||||
'delay'
|
||||
]
|
||||
|
||||
foreach file : tests
|
||||
test(file, prosperon_raw, args:['tests/' + file + '.js'], depends:copy_tests)
|
||||
endforeach
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
site_name: Prosperon Documentation
|
||||
edit_uri: edit/master/doc/docs
|
||||
|
||||
plugins:
|
||||
- search
|
||||
- awesome-pages
|
||||
- mike
|
||||
|
||||
extra_css:
|
||||
- style.css
|
||||
@@ -32,6 +32,9 @@ extra:
|
||||
analytics:
|
||||
provider: google
|
||||
property: G-85ECSFGCBV
|
||||
version:
|
||||
default: latest
|
||||
provider: mike
|
||||
|
||||
markdown_extensions:
|
||||
- admonition
|
||||
|
||||
@@ -625,13 +625,6 @@ debug or serialization. Implementation details may vary.
|
||||
:return: A quoted version of the string.
|
||||
`;
|
||||
|
||||
(String.prototype.localeCompare)[prosperon.DOC] = `Return a number indicating whether this string is less than, equal to, or
|
||||
greater than 'compareString' in sort order, according to the current locale.
|
||||
|
||||
:param compareString: The string to compare against.
|
||||
:return: A negative number if less, 0 if the same, or a positive number if greater.
|
||||
`;
|
||||
|
||||
(String.prototype.toLowerCase)[prosperon.DOC] = `Return a new string with all alphabetic characters converted to lowercase.
|
||||
|
||||
:return: The lowercase version of this string.
|
||||
|
||||
1129
scripts/core/doc.js
Normal file
165
scripts/core/io.js
Normal file
@@ -0,0 +1,165 @@
|
||||
$_.unneeded(_ => {
|
||||
}, Infinity)
|
||||
|
||||
var subscribers = []
|
||||
|
||||
var windows = []
|
||||
var renderers = []
|
||||
|
||||
var os = use('os')
|
||||
|
||||
$_.receiver(e => {
|
||||
if (e.type === "subscribe") {
|
||||
if (!e.actor) throw Error('Got a subscribe message with no actor.');
|
||||
console.log('subscribing: ' + json.encode(e.actor))
|
||||
subscribers.push(e.actor)
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.type === "window") {
|
||||
var window = windows[e.id]
|
||||
|
||||
switch (e.fn) {
|
||||
case "create":
|
||||
window = os.engine_start(e.config)
|
||||
windows[e.id] = window
|
||||
break;
|
||||
|
||||
case "fullscreen":
|
||||
window.fullscreen()
|
||||
break;
|
||||
|
||||
case "make_renderer":
|
||||
var renderer = window.make_renderer(e.config || {})
|
||||
renderers[e.renderer_id] = renderer
|
||||
break;
|
||||
|
||||
case "keyboard_shown":
|
||||
return window.keyboard_shown()
|
||||
|
||||
case "theme":
|
||||
return window.theme()
|
||||
|
||||
case "safe_area":
|
||||
return window.safe_area()
|
||||
|
||||
case "bordered":
|
||||
window.bordered(e.value)
|
||||
break;
|
||||
|
||||
case "set_icon":
|
||||
window.set_icon(e.icon)
|
||||
break;
|
||||
|
||||
case "set_title":
|
||||
window.title = e.title
|
||||
break;
|
||||
|
||||
case "get_title":
|
||||
return window.title
|
||||
|
||||
case "set_size":
|
||||
window.size = e.size
|
||||
break;
|
||||
|
||||
case "get_size":
|
||||
return window.size
|
||||
|
||||
case "mouse_grab":
|
||||
window.mouse_grab(e.value)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (e.type === "render") {
|
||||
var renderer = renderers[e.id]
|
||||
|
||||
switch (e.fn) {
|
||||
case "draw_color":
|
||||
renderer.draw_color(e.color)
|
||||
break;
|
||||
|
||||
case "present":
|
||||
renderer.present()
|
||||
break;
|
||||
|
||||
case "clear":
|
||||
renderer.clear()
|
||||
break;
|
||||
|
||||
case "line":
|
||||
renderer.line(e.config)
|
||||
break;
|
||||
|
||||
case "point":
|
||||
renderer.point(e.config)
|
||||
break;
|
||||
|
||||
case "texture":
|
||||
renderer.texture(e.texture, e.src_rect, e.dst_rect, e.angle, e.center)
|
||||
break;
|
||||
|
||||
case "rects":
|
||||
renderer.rects(e.rects)
|
||||
break;
|
||||
|
||||
case "geometry":
|
||||
renderer.geometry(e.vertices, e.indices)
|
||||
break;
|
||||
|
||||
case "geometry2":
|
||||
renderer.geometry2(e.vertices, e.indices)
|
||||
break;
|
||||
|
||||
case "sprite":
|
||||
renderer.sprite(e.config)
|
||||
break;
|
||||
|
||||
case "load_texture":
|
||||
renderer.load_texture(e.path)
|
||||
break;
|
||||
|
||||
case "get_image":
|
||||
renderer.get_image(e.config)
|
||||
break;
|
||||
|
||||
case "scale":
|
||||
renderer.scale(e.scale)
|
||||
break;
|
||||
|
||||
case "logical_size":
|
||||
renderer.logical_size(e.size)
|
||||
break;
|
||||
|
||||
case "viewport":
|
||||
renderer.viewport(e.viewport)
|
||||
break;
|
||||
|
||||
case "clip":
|
||||
renderer.clip(e.rect)
|
||||
break;
|
||||
|
||||
case "vsync":
|
||||
renderer.vsync(e.enable)
|
||||
break;
|
||||
|
||||
case "coords":
|
||||
renderer.coords(e.config)
|
||||
break;
|
||||
|
||||
case "camera":
|
||||
renderer.camera(e.cam, e.layer)
|
||||
break;
|
||||
|
||||
case "screen2world":
|
||||
return renderer.screen2world(e.point)
|
||||
|
||||
case "target":
|
||||
renderer.target(e.target)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (var a of subscribers)
|
||||
$_.send(a, e);
|
||||
});
|
||||
26
scripts/modules/camera.js
Normal file
@@ -0,0 +1,26 @@
|
||||
var camera = this
|
||||
|
||||
camera.list[prosperon.DOC] = `Return an array of available camera device IDs.
|
||||
|
||||
:return: An array of camera IDs, or undefined if no cameras are available.
|
||||
`
|
||||
|
||||
camera.open[prosperon.DOC] = `Open a camera device with the given ID.
|
||||
|
||||
:param id: The camera ID to open.
|
||||
:return: A camera object on success, or throws an error if the camera cannot be opened.
|
||||
`
|
||||
|
||||
camera.name[prosperon.DOC] = `Return the name of the camera with the given ID.
|
||||
|
||||
:param id: The camera ID to query.
|
||||
:return: A string with the camera's name, or throws an error if the name cannot be retrieved.
|
||||
`
|
||||
|
||||
camera.position[prosperon.DOC] = `Return the physical position of the camera with the given ID.
|
||||
|
||||
:param id: The camera ID to query.
|
||||
:return: A string indicating the camera position ("unknown", "front", or "back").
|
||||
`
|
||||
|
||||
return this;
|
||||
@@ -1,7 +1,6 @@
|
||||
var io = use('io')
|
||||
var util = use('util')
|
||||
|
||||
|
||||
var dumpfolder = ".prosperon";
|
||||
|
||||
io.mkdir(dumpfolder)
|
||||
@@ -27,71 +26,52 @@ Cmdline.register_order = function (order, fn, doc, usage = "") {
|
||||
Cmdline.register_order(
|
||||
"makedoc",
|
||||
function() {
|
||||
var doc = use('doc')
|
||||
var doc = use('doc')
|
||||
|
||||
var gs = ['console', 'prosperon', 'actor', 'use']
|
||||
var gs = ['console', 'prosperon', 'actor', 'use']
|
||||
|
||||
Object.getOwnPropertyDescriptor(prosperon.c_types.transform, 'pos')[prosperon.DOC] = 'TEST DOC'
|
||||
for (var g of gs)
|
||||
io.slurpwrite(`.src/docs/api/${g}.md`, doc.writeDocFile(globalThis[g], g))
|
||||
|
||||
console.log(Object.getOwnPropertyDescriptor(prosperon.c_types.transform,'pos')[prosperon.DOC])
|
||||
var coredocs = io.enumerate("scripts/modules", 0)
|
||||
coredocs = coredocs.filter(x => io.match("**/*.js", x)).map(x => x.name())
|
||||
|
||||
for (var g of gs)
|
||||
io.slurpwrite(`.src/docs/api/${g}.md`, doc.writeDocFile(globalThis[g], g))
|
||||
var APIPATH = '.src/docs/api/modules/'
|
||||
|
||||
var coredocs = io.enumerate("scripts/modules", 0)
|
||||
coredocs = coredocs.filter(x => io.match("**/*.js", x)).map(x => x.name())
|
||||
for (var m of coredocs) {
|
||||
var u = use(m)
|
||||
var path = `${APIPATH}${m}.md`
|
||||
io.slurpwrite(path, doc.writeDocFile(u, m))
|
||||
}
|
||||
|
||||
var TYPEPATH = '.src/docs/api/types/'
|
||||
for (var c in prosperon.c_types)
|
||||
io.slurpwrite(`${TYPEPATH}${c}.md`, doc.writeDocFile(prosperon.c_types[c], c))
|
||||
|
||||
var TYPEPATH = '.src/docs/api/types/'
|
||||
for (var c in prosperon.c_types) {
|
||||
io.slurpwrite(`${TYPEPATH}${c}.md`, doc.writeDocFile(prosperon.c_types[c], c))
|
||||
}
|
||||
var DULLPATH = '.src/docs/dull/'
|
||||
var mixins = ['Object', 'String', 'Array', 'Map', 'WeakMap', 'Symbol','Set', 'WeakSet', 'ArrayBuffer', 'Function']
|
||||
for (var m of mixins) {
|
||||
var path = `${DULLPATH}${m}.md`
|
||||
io.slurpwrite(path, doc.writeDocFile(globalThis[m].prototype, m))
|
||||
}
|
||||
|
||||
var APIPATH = '.src/docs/api/modules/'
|
||||
|
||||
for (var m of coredocs) {
|
||||
var u = use(m)
|
||||
var path = `${APIPATH}${m}.md`
|
||||
io.slurpwrite(path, doc.writeDocFile(u, m))
|
||||
}
|
||||
|
||||
var DULLPATH = '.src/docs/dull/'
|
||||
var mixins = ['Object', 'String', 'Array', 'Map', 'WeakMap', 'Symbol','Set', 'WeakSet', 'ArrayBuffer', 'Function']
|
||||
for (var m of mixins) {
|
||||
var path = `${DULLPATH}${m}.md`
|
||||
io.slurpwrite(path, doc.writeDocFile(globalThis[m].prototype, m))
|
||||
}
|
||||
|
||||
var dullgpath = '.src/docs/dull/globals/'
|
||||
var globals = ['Object', 'String', 'Array', 'Symbol', 'Number', 'Error','Function', 'Math']
|
||||
for (var m of globals) {
|
||||
var path = `${dullgpath}${m}.md`
|
||||
io.slurpwrite(path, doc.writeDocFile(globalThis[m], m))
|
||||
}
|
||||
var dullgpath = '.src/docs/dull/globals/'
|
||||
var globals = ['Object', 'String', 'Array', 'Symbol', 'Number', 'Error','Function', 'Math']
|
||||
for (var m of globals) {
|
||||
var path = `${dullgpath}${m}.md`
|
||||
io.slurpwrite(path, doc.writeDocFile(globalThis[m], m))
|
||||
}
|
||||
"Make documentation."
|
||||
})
|
||||
|
||||
function spawn_root(script)
|
||||
{
|
||||
return actor.spawn(script, {}, function(underling, msg) {
|
||||
if (msg.message !== "created") return;
|
||||
Object.defineProperty(underling, 'then', {
|
||||
configurable:false,
|
||||
writable:false,
|
||||
value:function() {
|
||||
os.exit(0);
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
Cmdline.register_order(
|
||||
"play",
|
||||
function (argv) {
|
||||
var app
|
||||
if (io.exists("main.js"))
|
||||
app = spawn_root("main.js")
|
||||
app = actor.spawn("main.js")
|
||||
else
|
||||
app = spawn_root("nogame.js")
|
||||
app = actor.spawn("nogame.js")
|
||||
|
||||
// rm actor so it can't be tampered
|
||||
globalThis.actor = undefined
|
||||
@@ -141,28 +121,6 @@ Cmdline.register_order(
|
||||
"OBJECT ?FILE?",
|
||||
);
|
||||
|
||||
Cmdline.register_order(
|
||||
"run",
|
||||
function (script) {
|
||||
var s = os.now()
|
||||
script = script.join(" ");
|
||||
if (!script) {
|
||||
console.print("Need something to run.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
spawn_root(script)
|
||||
} catch(e) {
|
||||
console.error(e);
|
||||
os.exit(1);
|
||||
}
|
||||
},
|
||||
"Run a given script. SCRIPT can be the script itself, or a file containing the script",
|
||||
"SCRIPT",
|
||||
);
|
||||
|
||||
Cmdline.orders.script = Cmdline.orders.run;
|
||||
|
||||
Cmdline.print_order = function (fn) {
|
||||
if (typeof fn === "string") fn = Cmdline.orders[fn];
|
||||
|
||||
@@ -171,6 +129,50 @@ Cmdline.print_order = function (fn) {
|
||||
console.print(fn.doc + "\n");
|
||||
};
|
||||
|
||||
function parse_args(argv)
|
||||
{
|
||||
var args = {};
|
||||
for (var i = 0; i < argv.length; i++) {
|
||||
if (argv[i].startsWith("--")) {
|
||||
var key = argv[i].slice(2);
|
||||
if (i + 1 < argv.length && !argv[i + 1].startsWith("--")) {
|
||||
args[key] = argv[i + 1];
|
||||
i++; // Skip the value
|
||||
} else {
|
||||
args[key] = true; // Flag without value
|
||||
}
|
||||
}
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function unparse_args(args) {
|
||||
var argv = [];
|
||||
for (var key in args) {
|
||||
if (args.hasOwnProperty(key)) {
|
||||
argv.push("--" + key); // Add the flag with "--" prefix
|
||||
if (args[key] !== true) {
|
||||
argv.push(args[key]); // Add the value if it's not a boolean true flag
|
||||
}
|
||||
}
|
||||
}
|
||||
return argv;
|
||||
}
|
||||
|
||||
Cmdline.register_order(
|
||||
"spawn",
|
||||
function(argv) {
|
||||
prosperon.args = parse_args(argv)
|
||||
if (!prosperon.args.cwd) prosperon.args.cwd = '.'
|
||||
io.mount(prosperon.args.cwd)
|
||||
|
||||
if (!prosperon.args.program)
|
||||
os.exit()
|
||||
},
|
||||
"Spawn a new prosperon actor.",
|
||||
"TOPIC"
|
||||
);
|
||||
|
||||
Cmdline.register_order(
|
||||
"help",
|
||||
function (order) {
|
||||
@@ -199,21 +201,43 @@ Cmdline.register_order(
|
||||
Cmdline.register_order(
|
||||
"version",
|
||||
function () {
|
||||
console.print(`Prosperon version ${prosperon.version} [${prosperon.revision}]`);
|
||||
console.print(`Prosperon version ${prosperon.version} [${prosperon.revision}]` + "\n");
|
||||
},
|
||||
"Display Prosperon info.",
|
||||
);
|
||||
|
||||
function cmd_args(cmds) {
|
||||
cmds.shift()
|
||||
if (cmds.length === 0) cmds[0] = "play";
|
||||
else if (!Cmdline.orders[cmds[0]]) {
|
||||
// assume it's a script
|
||||
cmds[1] = cmds[0]
|
||||
cmds[0] = "run"
|
||||
// Remove the leading 'prosperon'
|
||||
cmds.shift();
|
||||
|
||||
// If there are no arguments left, assume we want to spawn main.js
|
||||
if (!cmds[0]) {
|
||||
// => effectively do: prosperon spawn --program main.js
|
||||
cmds.unshift("main.js");
|
||||
cmds.unshift("--program");
|
||||
cmds.unshift("spawn");
|
||||
} else if (!Cmdline.orders[cmds[0]]) {
|
||||
// If the first token isn't a recognized command, treat it as either
|
||||
// a directory containing main.js, or a script to run directly.
|
||||
var arg0 = cmds.shift();
|
||||
if (io.is_directory(arg0)) {
|
||||
var script = cmds[0] ? cmds.shift() : "main.js";
|
||||
cmds.unshift(script);
|
||||
cmds.unshift("--program");
|
||||
cmds.unshift(arg0);
|
||||
cmds.unshift("--cwd");
|
||||
} else {
|
||||
cmds.unshift(arg0);
|
||||
cmds.unshift("--program");
|
||||
}
|
||||
cmds.unshift("spawn");
|
||||
}
|
||||
|
||||
Cmdline.orders[cmds[0]](cmds.slice(1));
|
||||
}
|
||||
|
||||
return cmd_args;
|
||||
return {
|
||||
process: cmd_args,
|
||||
encode: parse_args,
|
||||
decode: unparse_args,
|
||||
}
|
||||
|
||||
42
scripts/modules/debug.js
Normal file
@@ -0,0 +1,42 @@
|
||||
var debug = this
|
||||
|
||||
debug.stack_depth[prosperon.DOC] = `Return the current stack depth.
|
||||
|
||||
:return: A number representing the stack depth.
|
||||
`
|
||||
|
||||
debug.build_backtrace[prosperon.DOC] = `Build and return a backtrace of the current call stack.
|
||||
|
||||
:return: An object representing the call stack backtrace.
|
||||
`
|
||||
|
||||
debug.closure_vars[prosperon.DOC] = `Return the closure variables for a given function.
|
||||
|
||||
:param fn: The function object to inspect.
|
||||
:return: An object containing the closure variables.
|
||||
`
|
||||
|
||||
debug.local_vars[prosperon.DOC] = `Return the local variables for a specific stack frame.
|
||||
|
||||
:param depth: The stack frame depth to inspect.
|
||||
:return: An object containing the local variables at the specified depth.
|
||||
`
|
||||
|
||||
debug.fn_info[prosperon.DOC] = `Return metadata about a given function.
|
||||
|
||||
:param fn: The function object to inspect.
|
||||
:return: An object with metadata about the function.
|
||||
`
|
||||
|
||||
debug.backtrace_fns[prosperon.DOC] = `Return an array of functions in the current backtrace.
|
||||
|
||||
:return: An array of function objects from the call stack.
|
||||
`
|
||||
|
||||
debug.dump_obj[prosperon.DOC] = `Return a string representation of a given object.
|
||||
|
||||
:param obj: The object to dump.
|
||||
:return: A string describing the object's contents.
|
||||
`
|
||||
|
||||
return this
|
||||
35
scripts/modules/device.js
Normal file
@@ -0,0 +1,35 @@
|
||||
// helpful render devices. width and height in pixels; diagonal in inches.
|
||||
return {
|
||||
pc: { width: 1920, height: 1080 },
|
||||
macbook_m2: { width: 2560, height: 1664, diagonal: 13.6 },
|
||||
ds_top: { width: 400, height: 240, diagonal: 3.53 },
|
||||
ds_bottom: { width: 320, height: 240, diagonal: 3.02 },
|
||||
playdate: { width: 400, height: 240, diagonal: 2.7 },
|
||||
switch: { width: 1280, height: 720, diagonal: 6.2 },
|
||||
switch_lite: { width: 1280, height: 720, diagonal: 5.5 },
|
||||
switch_oled: { width: 1280, height: 720, diagonal: 7 },
|
||||
dsi: { width: 256, height: 192, diagonal: 3.268 },
|
||||
ds: { width: 256, height: 192, diagonal: 3 },
|
||||
dsixl: { width: 256, height: 192, diagonal: 4.2 },
|
||||
ipad_air_m2: { width: 2360, height: 1640, diagonal: 11.97 },
|
||||
iphone_se: { width: 1334, height: 750, diagonal: 4.7 },
|
||||
iphone_12_pro: { width: 2532, height: 1170, diagonal: 6.06 },
|
||||
iphone_15: { width: 2556, height: 1179, diagonal: 6.1 },
|
||||
gba: { width: 240, height: 160, diagonal: 2.9 },
|
||||
gameboy: { width: 160, height: 144, diagonal: 2.48 },
|
||||
gbc: { width: 160, height: 144, diagonal: 2.28 },
|
||||
steamdeck: { width: 1280, height: 800, diagonal: 7 },
|
||||
vita: { width: 960, height: 544, diagonal: 5 },
|
||||
psp: { width: 480, height: 272, diagonal: 4.3 },
|
||||
imac_m3: { width: 4480, height: 2520, diagonal: 23.5 },
|
||||
macbook_pro_m3: { width: 3024, height: 1964, diagonal: 14.2 },
|
||||
ps1: { width: 320, height: 240, diagonal: 5 },
|
||||
ps2: { width: 640, height: 480 },
|
||||
snes: { width: 256, height: 224 },
|
||||
gamecube: { width: 640, height: 480 },
|
||||
n64: { width: 320, height: 240 },
|
||||
c64: { width: 320, height: 200 },
|
||||
macintosh: { width: 512, height: 342 },
|
||||
gamegear: { width: 160, height: 144, diagonal: 3.2 }
|
||||
};
|
||||
|
||||
27
scripts/modules/dmon.js
Normal file
@@ -0,0 +1,27 @@
|
||||
var dmon = this
|
||||
|
||||
dmon.watch[prosperon.DOC] = `Start watching the root directory, recursively.
|
||||
|
||||
This function begins monitoring the specified directory and its subdirectories recursively for events such as file creation, deletion, modification, or movement. Events are queued and can be retrieved by calling poll.
|
||||
|
||||
:return: None
|
||||
:throws: An error if dmon is already watching.
|
||||
`
|
||||
|
||||
dmon.unwatch[prosperon.DOC] = `Stop watching the currently monitored directory.
|
||||
|
||||
This function halts filesystem monitoring for the directory previously set by watch. It clears the watch state, allowing a new watch to be started.
|
||||
|
||||
:return: None
|
||||
:throws: An error if no directory is currently being watched.
|
||||
`
|
||||
|
||||
dmon.poll[prosperon.DOC] = `Retrieve and process queued filesystem events.
|
||||
|
||||
This function dequeues all pending filesystem events and invokes the provided callback for each one. The callback receives an event object with properties: 'action' (string: "create", "delete", "modify", or "move"), 'root' (string: watched directory), 'file' (string: affected file path), and 'old' (string: previous file path for move events, empty if not applicable).
|
||||
|
||||
:param callback: A function to call for each event, receiving an event object as its argument.
|
||||
:return: None
|
||||
`
|
||||
|
||||
return dmon
|
||||
@@ -3,122 +3,374 @@ var graphics = use('graphics')
|
||||
var math = use('math')
|
||||
var util = use('util')
|
||||
var os = use('os')
|
||||
var geometry = use('geometry')
|
||||
|
||||
var draw = {}
|
||||
draw[prosperon.DOC] = `
|
||||
A collection of 2D drawing functions that operate in screen space. Provides primitives
|
||||
for lines, rectangles, text, sprite drawing, etc.
|
||||
for lines, rectangles, text, sprite drawing, etc. Immediate mode.
|
||||
`
|
||||
|
||||
var whiteimage = {}
|
||||
whiteimage.surface = graphics.make_surface([1,1])
|
||||
whiteimage.surface.rect({x:0,y:0,width:1,height:1}, [1,1,1,1])
|
||||
whiteimage.texture = prosperon.gpu.load_texture(whiteimage.surface)
|
||||
/*var whiteimage = {}
|
||||
whiteimage = graphics.make_surface([1,1])
|
||||
whiteimage.rect({x:0,y:0,width:1,height:1}, [1,1,1,1])
|
||||
render.load_texture(whiteimage)
|
||||
*/
|
||||
|
||||
draw.point = function (pos, size, color = Color.blue) {
|
||||
render._main.point(pos, color)
|
||||
}
|
||||
if (render.point)
|
||||
draw.point = function(pos,size,opt = {color:Color.white}, pipeline) {
|
||||
render.settings(opt)
|
||||
render.pipeline(pipeline)
|
||||
render.point([pos])
|
||||
}
|
||||
else
|
||||
draw.point = function() { throw new Error('Backend cannot draw points.') }
|
||||
draw.point[prosperon.DOC] = `
|
||||
:param pos: A 2D position ([x, y]) where the point should be drawn.
|
||||
:param size: The size of the point (not currently affecting rendering).
|
||||
:param color: The color of the point, defaults to Color.blue.
|
||||
:param size: The size of the point.
|
||||
:param color: The color of the point, defaults to white.
|
||||
:return: None
|
||||
`
|
||||
|
||||
draw.line = function render_line(points, color = Color.white, thickness = 1, pipeline) {
|
||||
var mesh = graphics.make_line_prim(points, thickness, 0, 0, color)
|
||||
render.queue({
|
||||
type: 'geometry',
|
||||
mesh,
|
||||
pipeline,
|
||||
first_index: 0,
|
||||
num_indices: mesh.num_indices
|
||||
})
|
||||
/* ------------------------------------------------------------------------
|
||||
* helper – is (dx,dy) inside the desired wedge?
|
||||
* -------------------------------------------------------------------- */
|
||||
function within_wedge(dx, dy, start, end, full_circle)
|
||||
{
|
||||
if (full_circle) return true
|
||||
|
||||
var ang = Math.atan2(dy, dx) // [-π,π]
|
||||
if (ang < 0) ang += Math.PI * 2
|
||||
var t = ang / (Math.PI * 2) // turn ∈ [0,1)
|
||||
|
||||
if (start <= end) return t >= start && t <= end
|
||||
return t >= start || t <= end // wrap-around arc
|
||||
}
|
||||
draw.line[prosperon.DOC] = `
|
||||
:param points: An array of 2D positions representing the line vertices.
|
||||
:param color: The color of the line, default Color.white.
|
||||
:param thickness: The line thickness, default 1.
|
||||
:param pipeline: (Optional) A pipeline or rendering state object.
|
||||
:return: None
|
||||
`
|
||||
|
||||
draw.cross = function render_cross(pos, size, color = Color.red, thickness = 1, pipe) {
|
||||
/* ------------------------------------------------------------------------
|
||||
* software ellipse – outline / ring / fill via inner_radius
|
||||
* -------------------------------------------------------------------- */
|
||||
function software_ellipse(pos, radii, opt)
|
||||
{
|
||||
var rx = radii[0], ry = radii[1]
|
||||
if (rx <= 0 || ry <= 0) return
|
||||
|
||||
var cx = pos[0], cy = pos[1]
|
||||
var raw_start = opt.start
|
||||
var raw_end = opt.end
|
||||
var full_circle = Math.abs(raw_end - raw_start) >= 1 - 1e-9
|
||||
var start = (raw_start % 1 + 1) % 1
|
||||
var end = (raw_end % 1 + 1) % 1
|
||||
var thickness = Math.max(1, opt.thickness|0)
|
||||
|
||||
/* inner ellipse radii (may be zero or negative → treat as no hole) */
|
||||
var rx_i = rx - thickness,
|
||||
ry_i = ry - thickness
|
||||
var hole = (rx_i > 0 && ry_i > 0)
|
||||
|
||||
/* fast one-pixel outline ? --------------------------------------- */
|
||||
if (!hole && thickness === 1) {
|
||||
/* (same midpoint algorithm as before, filtered by wedge) --------*/
|
||||
var rx_sq = rx * rx, ry_sq = ry * ry
|
||||
var two_rx_sq = rx_sq << 1, two_ry_sq = ry_sq << 1
|
||||
var x = 0, y = ry, px = 0, py = two_rx_sq * y
|
||||
var p = ry_sq - rx_sq * ry + 0.25 * rx_sq
|
||||
|
||||
function plot_pts(x, y) {
|
||||
var pts = [
|
||||
[cx + x, cy + y], [cx - x, cy + y],
|
||||
[cx + x, cy - y], [cx - x, cy - y]
|
||||
].filter(pt => within_wedge(pt[0]-cx, pt[1]-cy, start, end, full_circle))
|
||||
if (pts.length) render.point(pts)
|
||||
}
|
||||
|
||||
while (px < py) {
|
||||
plot_pts(x, y)
|
||||
++x; px += two_ry_sq
|
||||
if (p < 0) p += ry_sq + px
|
||||
else { --y; py -= two_rx_sq; p += ry_sq + px - py }
|
||||
}
|
||||
p = ry_sq*(x+.5)*(x+.5) + rx_sq*(y-1)*(y-1) - rx_sq*ry_sq
|
||||
while (y >= 0) {
|
||||
plot_pts(x, y)
|
||||
--y; py -= two_rx_sq
|
||||
if (p > 0) p += rx_sq - py
|
||||
else { ++x; px += two_ry_sq; p += rx_sq - py + px }
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------
|
||||
* FILL or RING (thickness ≥ 2 OR hole == false -> full fill)
|
||||
* ---------------------------------------------------------------- */
|
||||
var strips = []
|
||||
var rx_sq = rx * rx, ry_sq = ry * ry
|
||||
var rx_i_sq = rx_i * rx_i, ry_i_sq = ry_i * ry_i
|
||||
|
||||
for (var dy = -ry; dy <= ry; ++dy) {
|
||||
var yy = dy * dy
|
||||
var x_out = Math.floor(rx * Math.sqrt(1 - yy / ry_sq))
|
||||
var y_screen = cy + dy
|
||||
|
||||
/* optional inner span */
|
||||
var x_in = hole ? Math.floor(rx_i * Math.sqrt(1 - yy / ry_i_sq)) : -1
|
||||
|
||||
var run_start = null
|
||||
for (var dx = -x_out; dx <= x_out; ++dx) {
|
||||
if (hole && Math.abs(dx) <= x_in) { run_start = null; continue }
|
||||
if (!within_wedge(dx, dy, start, end, full_circle)) { run_start = null; continue }
|
||||
|
||||
if (run_start === null) run_start = cx + dx
|
||||
|
||||
var last = (dx === x_out)
|
||||
var next_in_ring =
|
||||
!last &&
|
||||
!(hole && Math.abs(dx+1) <= x_in) &&
|
||||
within_wedge(dx+1, dy, start, end, full_circle)
|
||||
|
||||
if (last || !next_in_ring) {
|
||||
strips.push({
|
||||
x: run_start,
|
||||
y: y_screen,
|
||||
width: (cx + dx) - run_start + 1,
|
||||
height: 1
|
||||
})
|
||||
run_start = null
|
||||
}
|
||||
}
|
||||
}
|
||||
if (strips.length) render.rects(strips)
|
||||
}
|
||||
|
||||
var ellipse_def = {
|
||||
color: Color.white,
|
||||
start: 0,
|
||||
end: 1,
|
||||
mode: 'fill',
|
||||
thickness: 1,
|
||||
}
|
||||
|
||||
if (render.ellipse)
|
||||
draw.ellipse = function(pos, radii, def, pipeline) {
|
||||
}
|
||||
else
|
||||
draw.ellipse = function(pos, radii, def, pipeline) {
|
||||
var opt = def ? {...ellipse_def, ...def} : ellipse_def
|
||||
render.settings(opt)
|
||||
render.pipeline(pipeline)
|
||||
if (opt.thickness <= 0) opt.thickness = Math.max(radii[0], radii[1])
|
||||
software_ellipse(pos, radii, opt)
|
||||
}
|
||||
|
||||
var line_def = {
|
||||
color: Color.white,
|
||||
thickness: 1,
|
||||
cap:"butt",
|
||||
}
|
||||
|
||||
draw.line = function(points, def, pipeline)
|
||||
{
|
||||
var opt
|
||||
if (def)
|
||||
opt = {...line_def, ...def}
|
||||
else
|
||||
opt = line_def
|
||||
|
||||
render.settings(opt)
|
||||
render.pipeline(pipeline)
|
||||
render.line(points)
|
||||
}
|
||||
|
||||
draw.cross = function render_cross(pos, size, def, pipe) {
|
||||
var a = [pos.add([0, size]), pos.add([0, -size])]
|
||||
var b = [pos.add([size, 0]), pos.add([-size, 0])]
|
||||
draw.line(a, color, thickness)
|
||||
draw.line(b, color, thickness)
|
||||
draw.line(a, def, pipe)
|
||||
draw.line(b, def,pipe)
|
||||
}
|
||||
draw.cross[prosperon.DOC] = `
|
||||
:param pos: The center of the cross as a 2D position ([x, y]).
|
||||
:param size: Half the size of each cross arm.
|
||||
:param color: The color of the cross, default Color.red.
|
||||
:param thickness: The thickness of each line, default 1.
|
||||
:param pipe: (Optional) A pipeline or rendering state object.
|
||||
:return: None
|
||||
`
|
||||
|
||||
draw.arrow = function render_arrow(start, end, color = Color.red, wingspan = 4, wingangle = 10, pipe) {
|
||||
draw.arrow = function render_arrow(start, end, wingspan = 4, wingangle = 10, def, pipe) {
|
||||
var dir = math.norm(end.sub(start))
|
||||
var wing1 = [math.rotate(dir, wingangle).scale(wingspan).add(end), end]
|
||||
var wing2 = [math.rotate(dir, -wingangle).scale(wingspan).add(end), end]
|
||||
render.line([start, end], color)
|
||||
render.line(wing1, color)
|
||||
render.line(wing2, color)
|
||||
draw.line([start, end], def, pipe)
|
||||
draw.line(wing1, def, pipe)
|
||||
draw.line(wing2, def, pipe)
|
||||
}
|
||||
draw.arrow[prosperon.DOC] = `
|
||||
:param start: The start position of the arrow ([x, y]).
|
||||
:param end: The end (tip) position of the arrow ([x, y]).
|
||||
:param color: The color, default Color.red.
|
||||
:param wingspan: The length of each arrowhead 'wing', default 4.
|
||||
:param wingangle: Wing rotation in degrees, default 10.
|
||||
:param pipe: (Optional) A pipeline or rendering state object.
|
||||
:return: None
|
||||
`
|
||||
|
||||
draw.rectangle = function render_rectangle(rect, color = Color.white, pipeline) {
|
||||
var T = os.make_transform()
|
||||
T.rect(rect)
|
||||
render.queue({
|
||||
type: 'sprite',
|
||||
transform: T,
|
||||
color,
|
||||
pipeline,
|
||||
image: whiteimage
|
||||
})
|
||||
/* ------------------------------------------------------------------------
|
||||
* helper – plain rectangle outline of arbitrary thickness (radius=0)
|
||||
* -------------------------------------------------------------------- */
|
||||
function software_outline_rect(rect, thickness)
|
||||
{
|
||||
if (thickness <= 0) {
|
||||
render.rectangle(rect);
|
||||
return;
|
||||
}
|
||||
|
||||
/* stroke swallows the whole thing → fill instead */
|
||||
if ((thickness << 1) >= rect.width ||
|
||||
(thickness << 1) >= rect.height) {
|
||||
render.rectangle(rect) // filled
|
||||
return
|
||||
}
|
||||
|
||||
const x0 = rect.x,
|
||||
y0 = rect.y,
|
||||
x1 = rect.x + rect.width,
|
||||
y1 = rect.y + rect.height
|
||||
|
||||
render.rects([
|
||||
{ x:x0, y:y0, width:rect.width, height:thickness }, // top
|
||||
{ x:x0, y:y1-thickness, width:rect.width, height:thickness }, // bottom
|
||||
{ x:x0, y:y0+thickness, width:thickness,
|
||||
height:rect.height - (thickness<<1) }, // left
|
||||
{ x:x1-thickness, y:y0+thickness, width:thickness,
|
||||
height:rect.height - (thickness<<1) } // right
|
||||
])
|
||||
}
|
||||
draw.rectangle[prosperon.DOC] = `
|
||||
:param rect: A rectangle object with {x, y, width, height}.
|
||||
:param color: The fill color, default Color.white.
|
||||
:param pipeline: (Optional) A pipeline or rendering state object.
|
||||
:return: None
|
||||
`
|
||||
|
||||
var tile_def = {repeat_x:true, repeat_y:true}
|
||||
/* ------------------------------------------------------------------------
|
||||
* ROUNDED rectangle outline (was software_round_rect)
|
||||
* -------------------------------------------------------------------- */
|
||||
function software_round_rect(rect, radius, thickness = 1)
|
||||
{
|
||||
if (thickness <= 0) {
|
||||
software_fill_round_rect(rect, radius)
|
||||
return
|
||||
}
|
||||
|
||||
draw.tile = function(image, rect, color = Color.white, tile = tile_def, pipeline) {
|
||||
if (!image) throw Error('Need an image to render.')
|
||||
if (typeof image === "string")
|
||||
image = graphics.texture(image)
|
||||
var mesh = render._main.tile(image.texture, {x:0,y:0,width:image.texture.width,height:image.texture.height}, rect, tile)
|
||||
render.queue({
|
||||
type:'geometry',
|
||||
mesh,
|
||||
image,
|
||||
pipeline,
|
||||
first_index:0,
|
||||
num_indices:mesh.num_indices
|
||||
})
|
||||
radius = Math.min(radius, rect.width >> 1, rect.height >> 1)
|
||||
|
||||
/* stroke covers whole rect → fall back to fill ------------------- */
|
||||
if ((thickness << 1) >= rect.width ||
|
||||
(thickness << 1) >= rect.height ||
|
||||
thickness >= radius) {
|
||||
software_fill_round_rect(rect, radius)
|
||||
return
|
||||
}
|
||||
|
||||
const x0 = rect.x,
|
||||
y0 = rect.y,
|
||||
x1 = rect.x + rect.width - 1, // inclusive
|
||||
y1 = rect.y + rect.height - 1
|
||||
|
||||
const cx_l = x0 + radius, cx_r = x1 - radius
|
||||
const cy_t = y0 + radius, cy_b = y1 - radius
|
||||
const r_out = radius
|
||||
const r_in = radius - thickness
|
||||
|
||||
/* straight bands (top/bottom/left/right) ------------------------- */
|
||||
render.rects([
|
||||
{ x:x0 + radius, y:y0, width:rect.width - (radius << 1),
|
||||
height:thickness }, // top
|
||||
{ x:x0 + radius, y:y1 - thickness + 1,
|
||||
width:rect.width - (radius << 1), height:thickness }, // bottom
|
||||
{ x:x0, y:y0 + radius, width:thickness,
|
||||
height:rect.height - (radius << 1) }, // left
|
||||
{ x:x1 - thickness + 1, y:y0 + radius, width:thickness,
|
||||
height:rect.height - (radius << 1) } // right
|
||||
])
|
||||
|
||||
/* corner arcs ---------------------------------------------------- */
|
||||
const strips = []
|
||||
|
||||
for (let dy = 0; dy < radius; ++dy) {
|
||||
const dy_sq = dy * dy
|
||||
const dx_out = Math.floor(Math.sqrt(r_out * r_out - dy_sq))
|
||||
const dx_in = (r_in > 0 && dy < r_in)
|
||||
? Math.floor(Math.sqrt(r_in * r_in - dy_sq))
|
||||
: -1 // no inner rim
|
||||
const w = dx_out - dx_in // strip width
|
||||
if (w <= 0) continue
|
||||
|
||||
/* top */
|
||||
strips.push(
|
||||
{ x:cx_l - dx_out, y:cy_t - dy, width:w, height:1 }, // NW
|
||||
{ x:cx_r + dx_in + 1, y:cy_t - dy, width:w, height:1 } // NE
|
||||
)
|
||||
|
||||
/* bottom */
|
||||
strips.push(
|
||||
{ x:cx_l - dx_out, y:cy_b + dy, width:w, height:1 }, // SW
|
||||
{ x:cx_r + dx_in + 1, y:cy_b + dy, width:w, height:1 } // SE
|
||||
)
|
||||
}
|
||||
|
||||
render.rects(strips)
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------
|
||||
* filled rounded rect (unchanged)
|
||||
* -------------------------------------------------------------------- */
|
||||
function software_fill_round_rect(rect, radius)
|
||||
{
|
||||
radius = Math.min(radius, rect.width >> 1, rect.height >> 1)
|
||||
|
||||
const x0 = rect.x,
|
||||
y0 = rect.y,
|
||||
x1 = rect.x + rect.width - 1,
|
||||
y1 = rect.y + rect.height - 1
|
||||
|
||||
/* main column */
|
||||
render.rects([
|
||||
{ x:x0 + radius, y:y0, width:rect.width - (radius << 1),
|
||||
height:rect.height }
|
||||
])
|
||||
|
||||
/* side columns */
|
||||
render.rects([
|
||||
{ x:x0, y:y0 + radius, width:radius,
|
||||
height:rect.height - (radius << 1) },
|
||||
{ x:x1 - radius + 1, y:y0 + radius, width:radius,
|
||||
height:rect.height - (radius << 1) }
|
||||
])
|
||||
|
||||
/* corner caps */
|
||||
const cx_l = x0 + radius, cx_r = x1 - radius
|
||||
const cy_t = y0 + radius, cy_b = y1 - radius
|
||||
const caps = []
|
||||
|
||||
for (let dy = 0; dy < radius; ++dy) {
|
||||
const dx = Math.floor(Math.sqrt(radius * radius - dy * dy))
|
||||
const w = (dx << 1) + 1
|
||||
|
||||
caps.push(
|
||||
{ x:cx_l - dx, y:cy_t - dy, width:w, height:1 },
|
||||
{ x:cx_r - dx, y:cy_t - dy, width:w, height:1 },
|
||||
{ x:cx_l - dx, y:cy_b + dy, width:w, height:1 },
|
||||
{ x:cx_r - dx, y:cy_b + dy, width:w, height:1 }
|
||||
)
|
||||
}
|
||||
|
||||
render.rects(caps)
|
||||
}
|
||||
|
||||
var rect_def = {
|
||||
thickness:1,
|
||||
color: Color.white,
|
||||
radius: 0
|
||||
}
|
||||
draw.rectangle = function render_rectangle(rect, def, pipeline) {
|
||||
var opt = def ? {...rect_def, ...def} : rect_def
|
||||
render.settings(opt)
|
||||
render.pipeline(pipeline)
|
||||
|
||||
var t = opt.thickness|0
|
||||
|
||||
if (t <= 0) {
|
||||
if (opt.radius)
|
||||
software_fill_round_rect(rect, opt.radius)
|
||||
else
|
||||
render.rectangle(rect)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (opt.radius)
|
||||
software_round_rect(rect, opt.radius, t)
|
||||
else
|
||||
software_outline_rect(rect,t)
|
||||
}
|
||||
draw.tile[prosperon.DOC] = `
|
||||
:param image: An image object or string path to a texture.
|
||||
:param rect: A rectangle specifying draw location/size ({x, y, width, height}).
|
||||
:param color: The color tint, default Color.white.
|
||||
:param tile: A tiling definition ({repeat_x, repeat_y}), default tile_def.
|
||||
:param pipeline: (Optional) A pipeline or rendering state object.
|
||||
:return: None
|
||||
:raises Error: If no image is provided.
|
||||
`
|
||||
|
||||
var slice9_info = {
|
||||
tile_top:true,
|
||||
@@ -126,28 +378,21 @@ var slice9_info = {
|
||||
tile_left:true,
|
||||
tile_right:true,
|
||||
tile_center_x:true,
|
||||
tile_center_right:true
|
||||
tile_center_right:true,
|
||||
color: Color.white,
|
||||
}
|
||||
|
||||
draw.slice9 = function slice9(image, rect = [0,0], slice = 0, color = Color.white, info = slice9_info, pipeline) {
|
||||
draw.slice9 = function slice9(image, rect = [0,0], slice = 0, info = slice9_info, pipeline) {
|
||||
if (!image) throw Error('Need an image to render.')
|
||||
if (typeof image === "string")
|
||||
image = graphics.texture(image)
|
||||
var mesh = render._main.slice9(image.texture, rect, util.normalizeSpacing(slice), info)
|
||||
render.queue({
|
||||
type: 'geometry',
|
||||
mesh,
|
||||
image,
|
||||
pipeline,
|
||||
first_index:0,
|
||||
num_indices:mesh.num_indices
|
||||
})
|
||||
|
||||
render.slice9(image, rect, slice, slice9_info, pipeline);
|
||||
}
|
||||
draw.slice9[prosperon.DOC] = `
|
||||
:param image: An image object or string path to a texture.
|
||||
:param rect: A rectangle specifying draw location/size, default [0, 0].
|
||||
:param slice: The pixel inset or spacing for the 9-slice (number or object).
|
||||
:param color: The color tint, default Color.white.
|
||||
:param info: A slice9 info object controlling tiling of edges/corners.
|
||||
:param pipeline: (Optional) A pipeline or rendering state object.
|
||||
:return: None
|
||||
@@ -155,33 +400,24 @@ draw.slice9[prosperon.DOC] = `
|
||||
`
|
||||
|
||||
var std_sprite_cmd = {type:'sprite', color:[1,1,1,1]}
|
||||
var image_info = {
|
||||
tile_x: false,
|
||||
tile_y: false,
|
||||
flip_x: false,
|
||||
flip_y: false,
|
||||
color: Color.white,
|
||||
}
|
||||
|
||||
draw.image = function image(image, rect = [0,0], rotation = 0, color, pipeline) {
|
||||
draw.image = function image(image, rect = [0,0], rotation = 0, anchor = [0,0], shear = [0,0], info, pipeline) {
|
||||
if (!image) throw Error('Need an image to render.')
|
||||
if (typeof image === "string")
|
||||
image = graphics.texture(image)
|
||||
rect.width ??= image.texture.width
|
||||
rect.height ??= image.texture.height
|
||||
var cmd = Object.create(std_sprite_cmd)
|
||||
cmd.image = image
|
||||
cmd.rect = rect
|
||||
if (pipeline) cmd.pipeline = pipeline
|
||||
if (color) cmd.color = color
|
||||
render.queue(cmd)
|
||||
var sprite = graphics.make_sprite()
|
||||
sprite.set_image(image)
|
||||
sprite.set_rect(rect)
|
||||
return sprite
|
||||
info ??= image_info;
|
||||
render.settings(info)
|
||||
render.image(image, rect, rotation, anchor, shear, info)
|
||||
}
|
||||
draw.image[prosperon.DOC] = `
|
||||
:param image: An image object or string path to a texture.
|
||||
:param rect: A rectangle specifying draw location/size, default [0,0]; width/height default to image size.
|
||||
:param rotation: Rotation in degrees (not currently used).
|
||||
:param color: The color tint, default none.
|
||||
:param pipeline: (Optional) A pipeline or rendering state object.
|
||||
:return: A sprite object that was created for this draw call.
|
||||
:raises Error: If no image is provided.
|
||||
`
|
||||
|
||||
draw.images = function images(image, rects, config) {
|
||||
if (!image) throw Error('Need an image to render.')
|
||||
@@ -210,29 +446,40 @@ draw.images[prosperon.DOC] = `
|
||||
:raises Error: If no image is provided.
|
||||
`
|
||||
|
||||
draw.sprites = function(sprites, sort = 0, pipeline) {
|
||||
var cmds = graphics.make_sprite_queue(sprites, prosperon.camera, pipeline, sort)
|
||||
for (var i = 0; i < cmds.length; i++)
|
||||
render.queue(cmds[i])
|
||||
}
|
||||
draw.sprites[prosperon.DOC] = `
|
||||
:param sprites: An array of sprite objects to draw.
|
||||
:param sort: Sorting mode or order, default 0.
|
||||
:param pipeline: (Optional) A pipeline or rendering state object.
|
||||
:return: None
|
||||
`
|
||||
function software_circle(pos, radius)
|
||||
{
|
||||
if (radius <= 0) return // nothing to draw
|
||||
|
||||
draw.circle = function render_circle(pos, radius, color, inner_radius = 1, pipeline) {
|
||||
render.rectangle({x:pos.x, y:pos.y, width:radius*2,height:radius*2}, color, circle_pipeline)
|
||||
var cx = pos[0], cy = pos[1]
|
||||
var x = 0, y = radius
|
||||
var d = 3 - (radius << 1) // decision parameter
|
||||
|
||||
while (x <= y) {
|
||||
draw.point([
|
||||
[cx + x, cy + y], [cx - x, cy + y],
|
||||
[cx + x, cy - y], [cx - x, cy - y],
|
||||
[cx + y, cy + x], [cx - y, cy + x],
|
||||
[cx + y, cy - x], [cx - y, cy - x]
|
||||
])
|
||||
|
||||
if (d < 0) d += (x << 2) + 6
|
||||
else {
|
||||
d += ((x - y) << 2) + 10
|
||||
y--
|
||||
}
|
||||
x++
|
||||
}
|
||||
}
|
||||
|
||||
var circle_def = {
|
||||
inner_radius:1, // percentage: 1 means filled circle
|
||||
color: Color.white,
|
||||
start:0,
|
||||
end: 1,
|
||||
}
|
||||
draw.circle = function render_circle(pos, radius, def, pipeline) {
|
||||
draw.ellipse(pos, [radius,radius], def, pipeline)
|
||||
}
|
||||
draw.circle[prosperon.DOC] = `
|
||||
:param pos: Center of the circle ([x, y]).
|
||||
:param radius: The circle radius.
|
||||
:param color: The fill color of the circle, default none.
|
||||
:param inner_radius: (Unused) Possibly ring thickness, default 1.
|
||||
:param pipeline: (Optional) A pipeline or rendering state object.
|
||||
:return: None
|
||||
`
|
||||
|
||||
var sysfont = graphics.get_font('fonts/c64.ttf', 8)
|
||||
|
||||
|
||||
@@ -1,36 +1,33 @@
|
||||
// loop.js
|
||||
var render = use('render') // The refactored file above
|
||||
/*
|
||||
the "dull" game engine
|
||||
|
||||
This sets up a lot of different modules to be used altogether
|
||||
*/
|
||||
|
||||
var render = use('render')
|
||||
var layout = use('clay')
|
||||
var input = use('input')
|
||||
var emitter = use('emitter')
|
||||
var os = use('os')
|
||||
var event = use('event')
|
||||
var imgui = use('imgui')
|
||||
|
||||
var tracy = use('tracy')
|
||||
|
||||
var waittime = 1/240
|
||||
var last_frame_time = 0
|
||||
var frame_t = 0
|
||||
var fpses = []
|
||||
var timescale = 1
|
||||
|
||||
last_frame_time = os.now()
|
||||
|
||||
function step() {
|
||||
var now = os.now()
|
||||
var dt = now - last_frame_time
|
||||
if (dt < waittime) os.sleep(waittime - dt)
|
||||
last_frame_time = os.now()
|
||||
last_frame_time = now
|
||||
|
||||
dt = last_frame_time - frame_t
|
||||
frame_t = last_frame_time
|
||||
|
||||
event.engine_input(e => prosperon.dispatch(e.type, e))
|
||||
// event.engine_input(e => prosperon.dispatch(e.type, e))
|
||||
layout.newframe()
|
||||
|
||||
prosperon.appupdate(dt)
|
||||
input.procdown()
|
||||
emitter.update(dt * timescale)
|
||||
os.update_timers(dt * timescale)
|
||||
prosperon.update(dt * timescale)
|
||||
|
||||
render.setup_draw()
|
||||
@@ -39,12 +36,18 @@ function step() {
|
||||
if (imgui) imgui.prosperon_menu();
|
||||
|
||||
// Now do the GPU present (calls gpupresent in render.js)
|
||||
render._main.present()
|
||||
render.present()
|
||||
|
||||
tracy.end_frame()
|
||||
}
|
||||
|
||||
function start()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
// Return or export them so you can call from a main script
|
||||
return {
|
||||
start,
|
||||
step
|
||||
}
|
||||
151
scripts/modules/enet.js
Normal file
@@ -0,0 +1,151 @@
|
||||
// enet.js doc (updated)
|
||||
var enet = this;
|
||||
|
||||
//------------------------------------------------
|
||||
// Top-level ENet functions
|
||||
//------------------------------------------------
|
||||
|
||||
enet.initialize[prosperon.DOC] = `
|
||||
Initialize the ENet library. Must be called before using any ENet functionality.
|
||||
Throws an error if initialization fails.
|
||||
|
||||
:return: None
|
||||
`;
|
||||
|
||||
enet.deinitialize[prosperon.DOC] = `
|
||||
Deinitialize the ENet library, cleaning up all resources. Call this when you no longer
|
||||
need any ENet functionality.
|
||||
|
||||
:return: None
|
||||
`;
|
||||
|
||||
enet.create_host[prosperon.DOC] = `
|
||||
Create an ENet host for either a client-like unbound host or a server bound to a specific
|
||||
address and port:
|
||||
|
||||
- If no argument is provided, creates an unbound "client-like" host with default settings
|
||||
(maximum 32 peers, 2 channels, unlimited bandwidth).
|
||||
- If you pass an "ip:port" string (e.g. "127.0.0.1:7777"), it creates a server bound to
|
||||
that address. The server supports up to 32 peers, 2 channels, and unlimited bandwidth.
|
||||
|
||||
Throws an error if host creation fails for any reason.
|
||||
|
||||
:param address: (optional) A string in 'ip:port' format to bind the host (server), or
|
||||
omit to create an unbound client-like host.
|
||||
:return: An ENetHost object.
|
||||
`;
|
||||
|
||||
//------------------------------------------------
|
||||
// ENetHost methods
|
||||
//------------------------------------------------
|
||||
|
||||
var enet_host = prosperon.c_types.enet_host;
|
||||
|
||||
enet_host.service[prosperon.DOC] = `
|
||||
Poll for and process any available network events (connect, receive, disconnect, or none)
|
||||
from this host, calling the provided callback for each event. This function loops until
|
||||
no more events are available in the current timeframe.
|
||||
|
||||
Event object properties:
|
||||
- type: String, one of "connect", "receive", "disconnect", or "none".
|
||||
- peer: (present if type = "connect") The ENetPeer object for the new connection.
|
||||
- channelID: (present if type = "receive") The channel on which the data was received.
|
||||
- data: (present if type = "receive") The received data as a *plain JavaScript object*.
|
||||
If the JSON parse fails or the data isn't an object, a JavaScript error is thrown.
|
||||
|
||||
:param callback: A function called once for each available event, receiving an event
|
||||
object as its single argument.
|
||||
:param timeout: (optional) Timeout in milliseconds. Defaults to 0 (non-blocking).
|
||||
:return: None
|
||||
`;
|
||||
|
||||
enet_host.connect[prosperon.DOC] = `
|
||||
Initiate a connection from this host to a remote server. Throws an error if the
|
||||
connection cannot be started.
|
||||
|
||||
:param host: The hostname or IP address of the remote server (e.g. "example.com" or "127.0.0.1").
|
||||
:param port: The port number to connect to.
|
||||
:return: An ENetPeer object representing the connection.
|
||||
`;
|
||||
|
||||
enet_host.flush[prosperon.DOC] = `
|
||||
Flush all pending outgoing packets for this host immediately.
|
||||
|
||||
:return: None
|
||||
`;
|
||||
|
||||
enet_host.broadcast[prosperon.DOC] = `
|
||||
Broadcast a JavaScript object to all connected peers on channel 0. The object is
|
||||
serialized to JSON, and the packet is sent reliably. Throws an error if serialization fails.
|
||||
|
||||
:param data: A JavaScript object to broadcast to all peers.
|
||||
:return: None
|
||||
`;
|
||||
|
||||
//------------------------------------------------
|
||||
// ENetPeer methods
|
||||
//------------------------------------------------
|
||||
|
||||
var enet_peer = prosperon.c_types.enet_peer;
|
||||
|
||||
enet_peer.send[prosperon.DOC] = `
|
||||
Send a JavaScript object to this peer on channel 0. The object is serialized to JSON and
|
||||
sent reliably. Throws an error if serialization fails.
|
||||
|
||||
:param data: A JavaScript object to send.
|
||||
:return: None
|
||||
`;
|
||||
|
||||
enet_peer.disconnect[prosperon.DOC] = `
|
||||
Request a graceful disconnection from this peer. The connection will close after
|
||||
pending data is sent.
|
||||
|
||||
:return: None
|
||||
`;
|
||||
|
||||
enet_peer.disconnect_now[prosperon.DOC] = `
|
||||
Immediately terminate the connection to this peer, discarding any pending data.
|
||||
|
||||
:return: None
|
||||
`;
|
||||
|
||||
enet_peer.disconnect_later[prosperon.DOC] = `
|
||||
Request a disconnection from this peer after all queued packets are sent.
|
||||
|
||||
:return: None
|
||||
`;
|
||||
|
||||
enet_peer.reset[prosperon.DOC] = `
|
||||
Reset this peer's connection, immediately dropping it and clearing its internal state.
|
||||
|
||||
:return: None
|
||||
`;
|
||||
|
||||
enet_peer.ping[prosperon.DOC] = `
|
||||
Send a ping request to this peer to measure latency.
|
||||
|
||||
:return: None
|
||||
`;
|
||||
|
||||
enet_peer.throttle_configure[prosperon.DOC] = `
|
||||
Configure the throttling behavior for this peer, controlling how ENet adjusts its sending
|
||||
rate based on packet loss or congestion.
|
||||
|
||||
:param interval: The interval (ms) between throttle adjustments.
|
||||
:param acceleration: The factor to increase sending speed when conditions improve.
|
||||
:param deceleration: The factor to decrease sending speed when conditions worsen.
|
||||
:return: None
|
||||
`;
|
||||
|
||||
enet_peer.timeout[prosperon.DOC] = `
|
||||
Set timeout parameters for this peer, determining how long ENet waits before considering
|
||||
the connection lost.
|
||||
|
||||
:param timeout_limit: The total time (ms) before the peer is disconnected.
|
||||
:param timeout_min: The minimum timeout (ms) used for each timeout attempt.
|
||||
:param timeout_max: The maximum timeout (ms) used for each timeout attempt.
|
||||
:return: None
|
||||
`;
|
||||
|
||||
// Return the enet object.
|
||||
return enet;
|
||||
@@ -1,7 +1,6 @@
|
||||
var Color = use('color')
|
||||
var os = use('os')
|
||||
var graphics = use('graphics')
|
||||
//var render = use('render')
|
||||
|
||||
var ex = {}
|
||||
|
||||
@@ -111,7 +110,7 @@ ex.draw = function()
|
||||
/* var diff = graphics.texture(this.diffuse)
|
||||
if (!diff) throw new Error("emitter does not have a proper diffuse texture")
|
||||
|
||||
var mesh = render._main.make_sprite_mesh(this.particles)
|
||||
var mesh = graphics.make_sprite_mesh(this.particles)
|
||||
if (mesh.num_indices === 0) return
|
||||
render.queue({
|
||||
type:'geometry',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
var ret = {
|
||||
return {
|
||||
get pos() {
|
||||
if (!this.transform) return
|
||||
return this.transform.pos;
|
||||
@@ -29,5 +29,3 @@ var ret = {
|
||||
this.scale = this.scale.map((x, i) => x * vec[i]);
|
||||
},
|
||||
}
|
||||
|
||||
return ret
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
var graphics = this
|
||||
|
||||
graphics[prosperon.DOC] = `
|
||||
Provides functionality for loading and managing images, fonts, textures, and sprite meshes.
|
||||
Includes both JavaScript and C-implemented routines for creating geometry buffers, performing
|
||||
@@ -7,49 +8,149 @@ rectangle packing, etc.
|
||||
|
||||
var io = use('io')
|
||||
var res = use('resources')
|
||||
var render = use('render')
|
||||
|
||||
var GPU = Symbol()
|
||||
var CPU = Symbol()
|
||||
var LASTUSE = Symbol()
|
||||
|
||||
var cache = new Map()
|
||||
|
||||
// When creating an image, do an Object.create(graphics.Image)
|
||||
graphics.Image = {
|
||||
get gpu() {
|
||||
this[LASTUSE] = os.now();
|
||||
if (!this[GPU]) {
|
||||
this[GPU] = render.load_texture(this[CPU]);
|
||||
decorate_rect_px(this);
|
||||
}
|
||||
|
||||
return this[GPU]
|
||||
},
|
||||
|
||||
get texture() { return this.gpu },
|
||||
|
||||
get cpu() {
|
||||
this[LASTUSE] = os.now();
|
||||
if (!this[CPU]) this[CPU] = render.read_texture(this[GPU])
|
||||
return this[CPU]
|
||||
},
|
||||
|
||||
get surface() { return this.cpu },
|
||||
|
||||
get width() {
|
||||
return this[GPU].width
|
||||
},
|
||||
|
||||
get height() {
|
||||
return this[GPU].height
|
||||
},
|
||||
|
||||
unload_gpu() {
|
||||
this[GPU] = undefined
|
||||
},
|
||||
|
||||
unload_cpu() {
|
||||
this[CPU] = undefined
|
||||
},
|
||||
}
|
||||
|
||||
function calc_image_size(img) {
|
||||
if (!img.texture || !img.rect) return
|
||||
return [img.texture.width * img.rect.width, img.texture.height * img.rect.height]
|
||||
}
|
||||
|
||||
/**
|
||||
Internally loads image data from disk and prepares a GPU texture. Used by graphics.texture().
|
||||
Not intended for direct user calls.
|
||||
*/
|
||||
function create_image(path) {
|
||||
var data = io.slurpbytes(path)
|
||||
var newimg
|
||||
switch (path.ext()) {
|
||||
case 'gif':
|
||||
newimg = graphics.make_gif(data)
|
||||
if (newimg.surface)
|
||||
newimg.texture = prosperon.gpu.load_texture(newimg.surface)
|
||||
else
|
||||
for (var frame of newimg.frames)
|
||||
frame.texture = prosperon.gpu.load_texture(frame.surface)
|
||||
break
|
||||
case 'ase':
|
||||
case 'aseprite':
|
||||
newimg = graphics.make_aseprite(data)
|
||||
if (newimg.surface)
|
||||
newimg.texture = prosperon.gpu.load_texture(newimg.surface)
|
||||
else {
|
||||
for (var anim in newimg) {
|
||||
var a = newimg[anim]
|
||||
for (var frame of a.frames)
|
||||
frame.texture = prosperon.gpu.load_texture(frame.surface)
|
||||
}
|
||||
}
|
||||
break
|
||||
default:
|
||||
newimg = {
|
||||
surface: graphics.make_texture(data)
|
||||
}
|
||||
newimg.texture = prosperon.gpu.load_texture(newimg.surface)
|
||||
break
|
||||
function decorate_rect_px(img) {
|
||||
// needs a GPU texture to measure
|
||||
if (!img || !img.texture) return
|
||||
|
||||
// default UV rect is the whole image if none supplied
|
||||
img.rect ??= {x:0, y:0, width:1, height:1} // [u0,v0,uw,vh] in 0-1
|
||||
|
||||
// store pixel-space version: [x, y, w, h] in texels
|
||||
img.rect_px = {
|
||||
x:Math.round(img.rect.x * img.texture.width),
|
||||
y:Math.round(img.rect.y * img.texture.height),
|
||||
width:Math.round(img.rect.width * img.texture.width),
|
||||
height:Math.round(img.rect.height * img.texture.height)
|
||||
}
|
||||
}
|
||||
|
||||
function make_handle(obj)
|
||||
{
|
||||
var image = Object.create(graphics.Image);
|
||||
|
||||
if (obj.surface) {
|
||||
im
|
||||
}
|
||||
return Object.assign(Object.create(graphics.Image), {
|
||||
rect:{x:0,y:0,width:1,height:1},
|
||||
[CPU]:obj,
|
||||
[GPU]:undefined,
|
||||
[LASTUSE]:os.now()
|
||||
})
|
||||
}
|
||||
|
||||
function wrapSurface(surf, maybeRect){
|
||||
const h = make_handle(surf);
|
||||
if(maybeRect) h.rect = maybeRect; /* honour frame sub-rect */
|
||||
return h;
|
||||
}
|
||||
function wrapFrames(arr){ /* [{surface,time,rect}, …] → [{image,time}] */
|
||||
return arr.map(f => ({
|
||||
image : wrapSurface(f.surface || f), /* accept bare surface too */
|
||||
time: f.time,
|
||||
rect: f.rect /* keep for reference */
|
||||
}));
|
||||
}
|
||||
function makeAnim(frames, loop=true){
|
||||
return { frames, loop }
|
||||
}
|
||||
|
||||
function decode_image(bytes, ext)
|
||||
{
|
||||
switch(ext) {
|
||||
case 'gif': return graphics.make_gif(bytes)
|
||||
case 'ase':
|
||||
case 'aseprite': return graphics.make_aseprite(bytes)
|
||||
default: return {surface:graphics.make_texture(bytes)}
|
||||
}
|
||||
}
|
||||
|
||||
function create_image(path){
|
||||
try{
|
||||
const bytes = io.slurpbytes(path);
|
||||
let raw = decode_image(bytes, path.ext());
|
||||
|
||||
/* ── Case A: static image ─────────────────────────────────── */
|
||||
if(raw.surface)
|
||||
return make_handle(raw.surface);
|
||||
|
||||
/* ── Case B: GIF helpers returned array [surf, …] ─────────── */
|
||||
if(Array.isArray(raw))
|
||||
return makeAnim( wrapFrames(raw), true );
|
||||
|
||||
/* ── Case C: GIF helpers returned {frames,loop} ───────────── */
|
||||
if(raw.frames && Array.isArray(raw.frames))
|
||||
return makeAnim( wrapFrames(raw.frames), !!raw.loop );
|
||||
|
||||
/* ── Case D: ASE helpers returned { animName:{frames,loop}, … } ── */
|
||||
const anims = {};
|
||||
for(const [name, anim] of Object.entries(raw)){
|
||||
if(anim && Array.isArray(anim.frames))
|
||||
anims[name] = makeAnim( wrapFrames(anim.frames), !!anim.loop );
|
||||
else if(anim && anim.surface) /* ase with flat surface */
|
||||
anims[name] = makeAnim(
|
||||
[{image:make_handle(anim.surface),time:0}], true );
|
||||
}
|
||||
if(Object.keys(anims).length) return anims;
|
||||
|
||||
throw new Error('Unsupported image structure from decoder');
|
||||
|
||||
}catch(e){
|
||||
console.error(`Error loading image ${path}: ${e.message}`);
|
||||
throw e;
|
||||
}
|
||||
return newimg
|
||||
}
|
||||
|
||||
var image = {}
|
||||
@@ -82,15 +183,49 @@ graphics.is_image[prosperon.DOC] = `
|
||||
:return: True if 'obj' has a .texture and a .rect property, indicating it's an image object.
|
||||
`
|
||||
|
||||
graphics.texture = function texture(path) {
|
||||
if (typeof path !== 'string') {
|
||||
return path // fallback if already an image object
|
||||
throw new Error('need a string for graphics.texture')
|
||||
graphics.texture_from_data = function(data)
|
||||
{
|
||||
if (!(data instanceof ArrayBuffer)) return undefined
|
||||
|
||||
var img = {
|
||||
surface: graphics.make_texture(data)
|
||||
}
|
||||
var parts = path.split(':')
|
||||
var ipath = res.find_image(parts[0])
|
||||
graphics.texture.cache[ipath] ??= create_image(ipath)
|
||||
return graphics.texture.cache[ipath]
|
||||
render.load_texture(img)
|
||||
decorate_rect_px(img)
|
||||
|
||||
return img
|
||||
}
|
||||
|
||||
graphics.from_surface = function(id, surf)
|
||||
{
|
||||
return make_handle(surf)
|
||||
var img = { surface: surf }
|
||||
}
|
||||
|
||||
graphics.from = function(id, data)
|
||||
{
|
||||
if (typeof id !== 'string')
|
||||
throw new Error('Expected a string ID')
|
||||
|
||||
if (data instanceof ArrayBuffer)
|
||||
return graphics.texture_from_data(data)
|
||||
}
|
||||
|
||||
graphics.texture = function texture(path) {
|
||||
if (path.__proto__ === graphics.Image) return path
|
||||
|
||||
if (typeof path !== 'string')
|
||||
throw new Error('need a string for graphics.texture')
|
||||
|
||||
var id = path.split(':')[0]
|
||||
if (cache.has(id)) return cache.get(id)
|
||||
|
||||
var ipath = res.find_image(id)
|
||||
if (!ipath) throw new Error(`unknown image ${id}`)
|
||||
|
||||
var image = create_image(ipath)
|
||||
cache.set(id, image)
|
||||
return image
|
||||
}
|
||||
graphics.texture[prosperon.DOC] = `
|
||||
:param path: A string path to an image file or an already-loaded image object.
|
||||
@@ -170,9 +305,12 @@ graphics.get_font = function get_font(path, size) {
|
||||
if (fontcache[fontstr]) return fontcache[fontstr]
|
||||
|
||||
var data = io.slurpbytes(fullpath)
|
||||
fontcache[fontstr] = graphics.make_font(data, size)
|
||||
fontcache[fontstr].texture = prosperon.gpu.load_texture(fontcache[fontstr].surface)
|
||||
return fontcache[fontstr]
|
||||
var font = graphics.make_font(data,size)
|
||||
font.texture = render.load_texture(font.surface)
|
||||
|
||||
fontcache[fontstr] = font
|
||||
|
||||
return font
|
||||
}
|
||||
graphics.get_font[prosperon.DOC] = `
|
||||
:param path: A string path to a font file, optionally with ".size" appended.
|
||||
@@ -265,13 +403,6 @@ graphics.cull_sprites[prosperon.DOC] = `
|
||||
Filter an array of sprites to only those visible in the provided camera’s view.
|
||||
`
|
||||
|
||||
graphics.rects_to_sprites[prosperon.DOC] = `
|
||||
:param rects: An array of rect coords or objects.
|
||||
:param image: An image object (with .texture).
|
||||
:return: An array of sprite objects referencing the 'image' and each rect for UV or position.
|
||||
Convert an array of rect coords into sprite objects referencing a single image.
|
||||
`
|
||||
|
||||
graphics.make_surface[prosperon.DOC] = `
|
||||
:param dimensions: The size object {width, height}, or an array [w,h].
|
||||
:return: A blank RGBA surface with the given dimensions, typically for software rendering or icons.
|
||||
|
||||
26
scripts/modules/http.js
Normal file
@@ -0,0 +1,26 @@
|
||||
var http = this
|
||||
|
||||
http.fetch[prosperon.DOC] = `Initiate an asynchronous HTTP GET request.
|
||||
|
||||
This function enqueues an HTTP GET request for the specified URL. It supports both buffered responses (full response collected in memory) and streaming data (processed as it arrives). The request is executed asynchronously, and its completion or streaming data is handled via callbacks provided in the options. Use 'poll' to process the results.
|
||||
|
||||
:param url: A string representing the URL to fetch.
|
||||
:param options: Either a callback function or an object with optional properties:
|
||||
- 'callback': A function invoked upon request completion, receiving an object with 'data' (string or null) and 'error' (string or null) properties.
|
||||
- 'on_data': A function invoked for each chunk of streaming data, receiving a string chunk as its argument. If supplied, 'callback.data' will be null.
|
||||
:return: undefined
|
||||
:throws:
|
||||
- An error if the URL is not a string or is invalid.
|
||||
- An error if the options argument is neither a function nor an object.
|
||||
- An error if memory allocation or CURL initialization fails.
|
||||
`
|
||||
|
||||
http.poll[prosperon.DOC] = `Process pending HTTP requests and invoke callbacks.
|
||||
|
||||
This function checks for I/O activity on all enqueued HTTP requests and processes any that have completed or received data. For completed requests, it invokes the 'callback' function (if provided) with the result. For streaming requests, it invokes the 'data' function (if provided) as data arrives. This function must be called repeatedly to drive the asynchronous request system.
|
||||
|
||||
:return: undefined
|
||||
:throws: An error if CURL multi-handle processing fails.
|
||||
`
|
||||
|
||||
return http
|
||||
@@ -2,6 +2,15 @@ var imgui = this;
|
||||
|
||||
var debug = {}
|
||||
|
||||
var imdebug = function imdebug() {
|
||||
imtoggle("Physics", debug, "draw_phys");
|
||||
imtoggle("Bouning boxes", debug, "draw_bb");
|
||||
imtoggle("Names", debug, "draw_names");
|
||||
imtoggle("Sprite nums", debug, "sprite_nums");
|
||||
imtoggle("Debug overlay", debug, "show");
|
||||
imtoggle("Show ur names", debug, "urnames");
|
||||
};
|
||||
|
||||
function imtoggle(name, obj, field) {
|
||||
var changed = false;
|
||||
var old = obj[field];
|
||||
@@ -10,9 +19,14 @@ function imtoggle(name, obj, field) {
|
||||
return false;
|
||||
};
|
||||
|
||||
var render_menu = true;
|
||||
|
||||
imgui.render_menu = function(render) { render_menu = render; }
|
||||
|
||||
imgui.prosperon_menu = function prosperon_menu() {
|
||||
imgui.newframe();
|
||||
|
||||
|
||||
if (render_menu) {
|
||||
if (debug.console)
|
||||
debug.console = imgui.window("console", _ => {
|
||||
imgui.text(console.transcript);
|
||||
@@ -42,13 +56,13 @@ imgui.prosperon_menu = function prosperon_menu() {
|
||||
imtoggle("Console [f9]", debug, "console");
|
||||
});
|
||||
|
||||
imgui.sokol_gfx();
|
||||
// imgui.sokol_gfx();
|
||||
|
||||
imgui.menu("Graphics", _ => {
|
||||
imtoggle("Draw sprites", render, "draw_sprites");
|
||||
imtoggle("Draw particles", render, "draw_particles");
|
||||
imtoggle("Draw HUD", render, "draw_hud");
|
||||
imtoggle("Draw GUI", render, "draw_gui");
|
||||
// imtoggle("Draw sprites", render, "draw_sprites");
|
||||
// imtoggle("Draw particles", render, "draw_particles");
|
||||
// imtoggle("Draw HUD", render, "draw_hud");
|
||||
// imtoggle("Draw GUI", render, "draw_gui");
|
||||
|
||||
imgui.menu("Window", _ => {
|
||||
prosperon.fullscreen = imgui.checkbox("fullscreen", prosperon.fullscreen);
|
||||
@@ -81,9 +95,8 @@ imgui.prosperon_menu = function prosperon_menu() {
|
||||
}
|
||||
});
|
||||
*/
|
||||
// prosperon.imgui();
|
||||
|
||||
imgui.endframe(render._main);
|
||||
}
|
||||
prosperon.imgui();
|
||||
};
|
||||
|
||||
imgui.windowpos[prosperon.DOC] = `Return the position of the current ImGui window as an ImVec2.
|
||||
@@ -309,16 +322,6 @@ imgui.barplot[prosperon.DOC] = `Plot a bar chart in the current ImPlot.
|
||||
:return: None
|
||||
`;
|
||||
|
||||
imgui.pieplot[prosperon.DOC] = `Plot a pie chart in the current ImPlot.
|
||||
|
||||
:param labels: An array of label strings for each slice.
|
||||
:param values: An array of numeric values corresponding to each slice.
|
||||
:param x: The x position of the pie’s center.
|
||||
:param y: The y position of the pie’s center.
|
||||
:param radius: The radius of the pie chart.
|
||||
:return: None
|
||||
`;
|
||||
|
||||
imgui.textplot[prosperon.DOC] = `Render text at the specified coordinates in plot space.
|
||||
|
||||
:param text: The string to render.
|
||||
@@ -725,4 +728,4 @@ imgui.init[prosperon.DOC] = `Initialize ImGui with SDL and SDL_gpu, creating the
|
||||
:return: None
|
||||
`;
|
||||
|
||||
return false
|
||||
return this
|
||||
|
||||
@@ -103,8 +103,10 @@ io.basedir[prosperon.DOC] = `Return the application's base directory (where the
|
||||
:return: A string with the base directory path.
|
||||
`
|
||||
|
||||
io.userdir[prosperon.DOC] = `Return the user's directory, often used for saving data.
|
||||
io.prefdir[prosperon.DOC] = `Get the user-and-app-specific path where files can be written.
|
||||
|
||||
:param org: The name of your organization.
|
||||
:param app: The name of your application.
|
||||
:return: A string with the user's directory path.
|
||||
`
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ Provides functions for introspecting and configuring the QuickJS runtime engine.
|
||||
Includes debug info, memory usage, GC controls, code evaluation, etc.
|
||||
`
|
||||
|
||||
js.rt_info[prosperon.DOC] = "Return internal QuickJS runtime info, such as object counts."
|
||||
|
||||
js.dump_shapes[prosperon.DOC] = `
|
||||
:return: A debug string describing the internal shape hierarchy used by QuickJS.
|
||||
Use this for internal debugging of object shapes.
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
var json = {}
|
||||
|
||||
json.encode = function(val,space,replacer,whitelist)
|
||||
json.encode = function encode(val,replacer,space = 1,whitelist)
|
||||
{
|
||||
return JSON.stringify(val, replacer, space ? 1 : 0)
|
||||
return JSON.stringify(val, replacer, space)
|
||||
}
|
||||
|
||||
json.encode[prosperon.DOC] = `Produce a JSON text from a Javascript object. If a record value, at any level, contains a json() method, it will be called, and the value it returns (usually a simpler record) will be JSONified.
|
||||
@@ -11,7 +11,7 @@ If the record does not have a json() method, and if whitelist is a record, then
|
||||
|
||||
If the space input is true, then line breaks and extra whitespace will be included in the text.`
|
||||
|
||||
json.decode = function(text,reviver)
|
||||
json.decode = function decode(text,reviver)
|
||||
{
|
||||
return JSON.parse(text,reviver)
|
||||
}
|
||||
|
||||
106
scripts/modules/lcdsprite.js
Normal file
@@ -0,0 +1,106 @@
|
||||
var sprite = {}
|
||||
|
||||
var graphics = use('graphics')
|
||||
var render = use('render')
|
||||
var draw2d = use('draw2d')
|
||||
|
||||
var SPRITE = Symbol() /* raw C sprite */
|
||||
var POS = Symbol() /* cached JS copies of simple data */
|
||||
var ROT = Symbol()
|
||||
var SCALE = Symbol()
|
||||
var SKEW = Symbol()
|
||||
var CENTER = Symbol()
|
||||
var COLOR = Symbol()
|
||||
var IMAGE = Symbol()
|
||||
|
||||
var ursprite = {
|
||||
get pos() { return this[POS] },
|
||||
set pos(v) {
|
||||
this[POS] = v
|
||||
this[SPRITE].pos = v
|
||||
},
|
||||
|
||||
get center() { return this[CENTER] },
|
||||
set center(v){
|
||||
this[CENTER] = v
|
||||
this[SPRITE].center = v
|
||||
},
|
||||
|
||||
get rotation() { return this[ROT] },
|
||||
set rotation(t){
|
||||
this[ROT] = t
|
||||
this[SPRITE].rotation = t * 2*Math.PI /* C expects radians */
|
||||
this[SPRITE].set_affine()
|
||||
},
|
||||
|
||||
get scale() { return this[SCALE] },
|
||||
set scale(v){
|
||||
this[SCALE] = v
|
||||
this[SPRITE].scale = v
|
||||
this[SPRITE].set_affine()
|
||||
},
|
||||
|
||||
get skew() { return this[SKEW] },
|
||||
set skew(v){
|
||||
this[SKEW] = v
|
||||
this[SPRITE].skew = v
|
||||
this[SPRITE].set_affine()
|
||||
},
|
||||
|
||||
get layer() { return this[SPRITE].layer },
|
||||
set layer(n){ this[SPRITE].layer = n },
|
||||
|
||||
get color() { return this[COLOR] },
|
||||
set color(v){
|
||||
this[COLOR] = v
|
||||
this[SPRITE].color = v
|
||||
},
|
||||
|
||||
move(mv) { this[SPRITE].move(mv) },
|
||||
moveto(p){
|
||||
this.pos = p
|
||||
},
|
||||
|
||||
get image() { return this[IMAGE] },
|
||||
set image(img) {
|
||||
this[IMAGE] = img
|
||||
this[SPRITE].set_image(img)
|
||||
}
|
||||
}
|
||||
|
||||
var _sprites = []
|
||||
|
||||
var def_sprite = Object.freeze({
|
||||
pos: [0,0],
|
||||
rotation: 0,
|
||||
scale: [1,1],
|
||||
center: [0,0],
|
||||
color: [1,1,1,1],
|
||||
skew: [0,0],
|
||||
layer: 0,
|
||||
})
|
||||
|
||||
sprite.create = function(image, info) {
|
||||
info.__proto__ = def_sprite
|
||||
var sp = Object.create(ursprite)
|
||||
sp[SPRITE] = graphics.make_sprite(info)
|
||||
sp.image = graphics.texture(image)
|
||||
|
||||
_sprites.push(sp)
|
||||
return sp
|
||||
}
|
||||
|
||||
sprite.forEach = fn => { for (let s of _sprites) fn(s) }
|
||||
sprite.values = () => _sprites.slice()
|
||||
sprite.geometry= () => graphics.make_sprite_mesh(_sprites)
|
||||
|
||||
var raws = []
|
||||
sprite.queue = function() {
|
||||
if (raws.length != _sprites.length)
|
||||
raws.length = _sprites.length
|
||||
|
||||
for (var i = 0; i < _sprites.length; i++) raws[i] = _sprites[i]
|
||||
return graphics.make_sprite_queue(_sprites.map(x => x[SPRITE]))
|
||||
}
|
||||
|
||||
return sprite
|
||||
101
scripts/modules/moth.js
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Moth Game Framework
|
||||
* Higher-level game development framework built on top of Prosperon
|
||||
*/
|
||||
|
||||
var os = use('os');
|
||||
var io = use('io');
|
||||
var render = use('render');
|
||||
var actor = use('actor');
|
||||
var gameConfig = {};
|
||||
var gameDir = "";
|
||||
|
||||
// Framework initialization
|
||||
function initialize() {
|
||||
var configPath = `config.js`;
|
||||
if (io.exists(configPath))
|
||||
gameConfig = use(configPath);
|
||||
|
||||
// Set up default config values
|
||||
gameConfig.resolution = gameConfig.resolution || { width: 640, height: 480 };
|
||||
gameConfig.internal_resolution = gameConfig.internal_resolution || gameConfig.resolution;
|
||||
gameConfig.title = gameConfig.title || "Moth Game";
|
||||
gameConfig.fps = gameConfig.fps || 60;
|
||||
gameConfig.clearColor = gameConfig.clearColor || [0, 0, 0, 1];
|
||||
|
||||
// Initialize render system
|
||||
render.initialize({
|
||||
width: gameConfig.resolution.width,
|
||||
height: gameConfig.resolution.height,
|
||||
resolution_x: gameConfig.internal_resolution.width,
|
||||
resolution_y: gameConfig.internal_resolution.height,
|
||||
mode: gameConfig.mode || 'letterbox'
|
||||
});
|
||||
|
||||
// Set up default camera
|
||||
gameConfig.camera = gameConfig.camera || {
|
||||
size: [gameConfig.internal_resolution.width, gameConfig.internal_resolution.height],
|
||||
transform: os.make_transform(),
|
||||
fov: 50,
|
||||
near_z: 0,
|
||||
far_z: 1000,
|
||||
surface: undefined,
|
||||
viewport: {x: 0, y: 0, width: 1, height: 1},
|
||||
ortho: true,
|
||||
anchor: [0, 0]
|
||||
};
|
||||
|
||||
// Set window title
|
||||
prosperon.window.title = gameConfig.title;
|
||||
|
||||
startGameLoop();
|
||||
}
|
||||
|
||||
// Main game loop
|
||||
function startGameLoop() {
|
||||
var last = os.now();
|
||||
var fpsTimer = 0;
|
||||
var fpsCount = 0;
|
||||
var targetFrameTime = 1 / gameConfig.fps;
|
||||
|
||||
function loop() {
|
||||
var now = os.now();
|
||||
var dt = now - last;
|
||||
last = now;
|
||||
|
||||
// Dispatch update event
|
||||
prosperon.dispatch('update', dt);
|
||||
|
||||
// Clear and set up rendering
|
||||
render.clear(gameConfig.clearColor);
|
||||
render.camera(gameConfig.camera);
|
||||
|
||||
// Dispatch draw event
|
||||
prosperon.dispatch('draw');
|
||||
|
||||
// Present the frame
|
||||
render.present();
|
||||
|
||||
// FPS counter
|
||||
fpsTimer += dt;
|
||||
fpsCount++;
|
||||
if (fpsTimer >= 0.5) {
|
||||
// Only update if the title wasn't changed by the game
|
||||
if (prosperon.window.title === gameConfig.title) {
|
||||
prosperon.window.title = `${gameConfig.title} - FPS ${(fpsCount / fpsTimer).toFixed(1)}`;
|
||||
}
|
||||
fpsTimer = fpsCount = 0;
|
||||
}
|
||||
|
||||
// Schedule next frame
|
||||
$_.delay(loop, Math.max(0, targetFrameTime - (os.now() - now)));
|
||||
}
|
||||
|
||||
loop();
|
||||
}
|
||||
|
||||
// Public API
|
||||
return {
|
||||
initialize: initialize,
|
||||
config: gameConfig
|
||||
};
|
||||
40
scripts/modules/nota.js
Normal file
@@ -0,0 +1,40 @@
|
||||
var nota = this
|
||||
|
||||
var json = use('json')
|
||||
|
||||
var encode = nota.encode
|
||||
|
||||
function nota_tostring()
|
||||
{
|
||||
return json.encode(nota.decode(this))
|
||||
}
|
||||
|
||||
var nota_obj = {
|
||||
toString: nota_tostring
|
||||
}
|
||||
|
||||
nota.encode = function(obj, replacer)
|
||||
{
|
||||
var result = encode(obj,replacer)
|
||||
result.toString = nota_tostring
|
||||
return result
|
||||
}
|
||||
|
||||
nota.encode[prosperon.DOC] = `Convert a JavaScript value into a NOTA-encoded ArrayBuffer.
|
||||
|
||||
This function serializes JavaScript values (such as numbers, strings, booleans, arrays, objects, or ArrayBuffers) into the NOTA binary format. The resulting ArrayBuffer can be stored or transmitted and later decoded back into a JavaScript value.
|
||||
|
||||
:param value: The JavaScript value to encode (e.g., number, string, boolean, array, object, or ArrayBuffer).
|
||||
:return: An ArrayBuffer containing the NOTA-encoded data.
|
||||
:throws: An error if no argument is provided.
|
||||
`
|
||||
|
||||
nota.decode[prosperon.DOC] = `Decode a NOTA-encoded ArrayBuffer into a JavaScript value.
|
||||
|
||||
This function deserializes a NOTA-formatted ArrayBuffer into its corresponding JavaScript representation, such as a number, string, boolean, array, object, or ArrayBuffer. If the input is invalid or empty, it returns undefined.
|
||||
|
||||
:param buffer: An ArrayBuffer containing NOTA-encoded data to decode.
|
||||
:return: The decoded JavaScript value (e.g., number, string, boolean, array, object, or ArrayBuffer), or undefined if no argument is provided.
|
||||
`
|
||||
|
||||
return nota
|
||||
@@ -15,9 +15,6 @@ os.exit[prosperon.DOC] = "Exit the application with the specified exit code."
|
||||
os.now[prosperon.DOC] = "Return current time (in seconds as a float) with high resolution."
|
||||
os.openurl[prosperon.DOC] = "Open the provided URL in the default web browser, if possible."
|
||||
|
||||
os.make_timer[prosperon.DOC] = "Create a new timer object that will call a specified function after a certain delay."
|
||||
os.update_timers[prosperon.DOC] = "Advance all timers by the provided time delta (in seconds)."
|
||||
|
||||
os.sleep[prosperon.DOC] = "Block execution for the specified number of seconds."
|
||||
os.battery_pct[prosperon.DOC] = "Return the battery level (percentage) or negative if unknown."
|
||||
os.battery_voltage[prosperon.DOC] = "Return the current battery voltage in volts, if available."
|
||||
@@ -25,10 +22,9 @@ os.battery_seconds[prosperon.DOC] = "Return the estimated remaining battery time
|
||||
os.power_state[prosperon.DOC] = "Return a string describing power status: 'on battery', 'charging', 'charged', etc."
|
||||
|
||||
os.on[prosperon.DOC] = "Register a global callback for certain engine-wide or system-level events."
|
||||
os.rt_info[prosperon.DOC] = "Return internal QuickJS runtime info, such as object counts."
|
||||
os.rusage[prosperon.DOC] = "Return resource usage stats for this process, if the platform supports it."
|
||||
os.mallinfo[prosperon.DOC] = "Return detailed memory allocation info (arena size, free blocks, etc.) on some platforms."
|
||||
os.env[prosperon.DOC] = "Fetch the value of a given environment variable, or undefined if it doesn't exist."
|
||||
os.system[prosperon.DOC] = "Execute a shell command using the system() call. Returns the command's exit code."
|
||||
|
||||
return os
|
||||
return os
|
||||
|
||||
584
scripts/modules/parseq.js
Normal file
@@ -0,0 +1,584 @@
|
||||
// parseq.js
|
||||
// Douglas Crockford
|
||||
// 2020-11-09
|
||||
|
||||
// Better living thru eventuality!
|
||||
|
||||
// You can access the parseq object in your module by importing it.
|
||||
// import parseq from "./parseq.js";
|
||||
|
||||
/*jslint node */
|
||||
|
||||
/*property
|
||||
concat, create, evidence, fallback, forEach, freeze, isArray, isSafeInteger,
|
||||
keys, length, min, parallel, parallel_object, pop, push, race, sequence,
|
||||
some
|
||||
*/
|
||||
|
||||
function make_reason(factory_name, excuse, evidence) {
|
||||
|
||||
// Make a reason object. These are used for exceptions and cancellations.
|
||||
// They are made from Error objects.
|
||||
|
||||
const reason = new Error("parseq." + factory_name + (
|
||||
excuse === undefined
|
||||
? ""
|
||||
: ": " + excuse
|
||||
));
|
||||
reason.evidence = evidence;
|
||||
return reason;
|
||||
}
|
||||
|
||||
function get_array_length(array, factory_name) {
|
||||
if (Array.isArray(array)) {
|
||||
return array.length;
|
||||
}
|
||||
if (array === undefined) {
|
||||
return 0;
|
||||
}
|
||||
throw make_reason(factory_name, "Not an array.", array);
|
||||
}
|
||||
|
||||
function check_callback(callback, factory_name) {
|
||||
if (typeof callback !== "function" || callback.length !== 2) {
|
||||
throw make_reason(factory_name, "Not a callback function.", callback);
|
||||
}
|
||||
}
|
||||
|
||||
function check_requestors(requestor_array, factory_name) {
|
||||
|
||||
// A requestor array contains only requestors. A requestor is a function that
|
||||
// takes wun or two arguments: 'callback' and optionally 'initial_value'.
|
||||
|
||||
if (requestor_array.some(function (requestor) {
|
||||
return (
|
||||
typeof requestor !== "function"
|
||||
|| requestor.length < 1
|
||||
|| requestor.length > 2
|
||||
);
|
||||
})) {
|
||||
throw make_reason(
|
||||
factory_name,
|
||||
"Bad requestors array.",
|
||||
requestor_array
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function run(
|
||||
factory_name,
|
||||
requestor_array,
|
||||
initial_value,
|
||||
action,
|
||||
timeout,
|
||||
time_limit,
|
||||
throttle = 0
|
||||
) {
|
||||
|
||||
// The 'run' function does the work that is common to all of the Parseq
|
||||
// factories. It takes the name of the factory, an array of requestors, an
|
||||
// initial value, an action callback, a timeout callback, a time limit in
|
||||
// milliseconds, and a throttle.
|
||||
|
||||
// If all goes well, we call all of the requestor functions in the array. Each
|
||||
// of them might return a cancel function that is kept in the 'cancel_array'.
|
||||
|
||||
let cancel_array = new Array(requestor_array.length);
|
||||
let next_number = 0;
|
||||
let timer_id;
|
||||
|
||||
// We need 'cancel' and 'start_requestor' functions.
|
||||
|
||||
function cancel(reason = make_reason(factory_name, "Cancel.")) {
|
||||
|
||||
// Stop all unfinished business. This can be called when a requestor fails.
|
||||
// It can also be called when a requestor succeeds, such as 'race' stopping
|
||||
// its losers, or 'parallel' stopping the unfinished optionals.
|
||||
|
||||
// If a timer is running, stop it.
|
||||
|
||||
if (timer_id !== undefined) {
|
||||
clearTimeout(timer_id);
|
||||
timer_id = undefined;
|
||||
}
|
||||
|
||||
// If anything is still going, cancel it.
|
||||
|
||||
if (cancel_array !== undefined) {
|
||||
cancel_array.forEach(function (cancel) {
|
||||
try {
|
||||
if (typeof cancel === "function") {
|
||||
return cancel(reason);
|
||||
}
|
||||
} catch (ignore) {}
|
||||
});
|
||||
cancel_array = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function start_requestor(value) {
|
||||
|
||||
// The 'start_requestor' function is not recursive, exactly. It does not
|
||||
// directly call itself, but it does return a function that might call
|
||||
// 'start_requestor'.
|
||||
|
||||
// Start the execution of a requestor, if there are any still waiting.
|
||||
|
||||
if (
|
||||
cancel_array !== undefined
|
||||
&& next_number < requestor_array.length
|
||||
) {
|
||||
|
||||
// Each requestor has a number.
|
||||
|
||||
let number = next_number;
|
||||
next_number += 1;
|
||||
|
||||
// Call the next requestor, passing in a callback function,
|
||||
// saving the cancel function that the requestor might return.
|
||||
|
||||
const requestor = requestor_array[number];
|
||||
try {
|
||||
cancel_array[number] = requestor(
|
||||
function start_requestor_callback(value, reason) {
|
||||
|
||||
// This callback function is called by the 'requestor' when it is done.
|
||||
// If we are no longer running, then this call is ignored.
|
||||
// For example, it might be a result that is sent back after the time
|
||||
// limit has expired. This callback function can only be called wunce.
|
||||
|
||||
if (
|
||||
cancel_array !== undefined
|
||||
&& number !== undefined
|
||||
) {
|
||||
|
||||
// We no longer need the cancel associated with this requestor.
|
||||
|
||||
cancel_array[number] = undefined;
|
||||
|
||||
// Call the 'action' function to let the requestor know what happened.
|
||||
|
||||
action(value, reason, number);
|
||||
|
||||
// Clear 'number' so this callback can not be used again.
|
||||
|
||||
number = undefined;
|
||||
|
||||
// If there are any requestors that are still waiting to start, then
|
||||
// start the next wun. If the next requestor is in a sequence, then it
|
||||
// gets the most recent 'value'. The others get the 'initial_value'.
|
||||
|
||||
setTimeout(start_requestor, 0, (
|
||||
factory_name === "sequence"
|
||||
? value
|
||||
: initial_value
|
||||
));
|
||||
}
|
||||
},
|
||||
value
|
||||
);
|
||||
|
||||
// Requestors are required to report their failure thru the callback.
|
||||
// They are not allowed to throw exceptions. If we happen to catch wun,
|
||||
// it is treated as a failure.
|
||||
|
||||
} catch (exception) {
|
||||
action(undefined, exception, number);
|
||||
number = undefined;
|
||||
start_requestor(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// With the 'cancel' and the 'start_requestor' functions in hand,
|
||||
// we can now get to work.
|
||||
|
||||
// If a timeout was requested, start the timer.
|
||||
|
||||
if (time_limit !== undefined) {
|
||||
if (typeof time_limit === "number" && time_limit >= 0) {
|
||||
if (time_limit > 0) {
|
||||
timer_id = setTimeout(timeout, time_limit);
|
||||
}
|
||||
} else {
|
||||
throw make_reason(factory_name, "Bad time limit.", time_limit);
|
||||
}
|
||||
}
|
||||
|
||||
// If we are doing 'race' or 'parallel', we want to start all of the requestors
|
||||
// at wunce. However, if there is a 'throttle' in place then we start as many
|
||||
// as the 'throttle' allows, and then as each requestor finishes, another is
|
||||
// started.
|
||||
|
||||
// The 'sequence' and 'fallback' factories set 'throttle' to 1 because they
|
||||
// process wun at a time and always start another requestor when the
|
||||
// previous requestor finishes.
|
||||
|
||||
if (!Number.isSafeInteger(throttle) || throttle < 0) {
|
||||
throw make_reason(factory_name, "Bad throttle.", throttle);
|
||||
}
|
||||
let repeat = Math.min(throttle || Infinity, requestor_array.length);
|
||||
while (repeat > 0) {
|
||||
setTimeout(start_requestor, 0, initial_value);
|
||||
repeat -= 1;
|
||||
}
|
||||
|
||||
// We return 'cancel' which allows the requestor to cancel this work.
|
||||
|
||||
return cancel;
|
||||
}
|
||||
|
||||
// The factories ///////////////////////////////////////////////////////////////
|
||||
|
||||
function parallel(
|
||||
required_array,
|
||||
optional_array,
|
||||
time_limit,
|
||||
time_option,
|
||||
throttle,
|
||||
factory_name = "parallel"
|
||||
) {
|
||||
|
||||
// The parallel factory is the most complex of these factories. It can take
|
||||
// a second array of requestors that get a more forgiving failure policy.
|
||||
// It returns a requestor that produces an array of values.
|
||||
|
||||
let requestor_array;
|
||||
|
||||
// There are four cases because 'required_array' and 'optional_array'
|
||||
// can both be empty.
|
||||
|
||||
let number_of_required = get_array_length(required_array, factory_name);
|
||||
if (number_of_required === 0) {
|
||||
if (get_array_length(optional_array, factory_name) === 0) {
|
||||
|
||||
// If both are empty, then 'requestor_array' is empty.
|
||||
|
||||
requestor_array = [];
|
||||
} else {
|
||||
|
||||
// If there is only 'optional_array', then it is the 'requestor_array'.
|
||||
|
||||
requestor_array = optional_array;
|
||||
time_option = true;
|
||||
}
|
||||
} else {
|
||||
|
||||
// If there is only 'required_array', then it is the 'requestor_array'.
|
||||
|
||||
if (get_array_length(optional_array, factory_name) === 0) {
|
||||
requestor_array = required_array;
|
||||
time_option = undefined;
|
||||
|
||||
// If both arrays are provided, we concatenate them together.
|
||||
|
||||
} else {
|
||||
requestor_array = required_array.concat(optional_array);
|
||||
if (time_option !== undefined && typeof time_option !== "boolean") {
|
||||
throw make_reason(
|
||||
factory_name,
|
||||
"Bad time_option.",
|
||||
time_option
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We check the array and return the requestor.
|
||||
|
||||
check_requestors(requestor_array, factory_name);
|
||||
return function parallel_requestor(callback, initial_value) {
|
||||
check_callback(callback, factory_name);
|
||||
let number_of_pending = requestor_array.length;
|
||||
let number_of_pending_required = number_of_required;
|
||||
let results = [];
|
||||
if (number_of_pending === 0) {
|
||||
callback(
|
||||
factory_name === "sequence"
|
||||
? initial_value
|
||||
: results
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// 'run' gets it started.
|
||||
|
||||
let cancel = run(
|
||||
factory_name,
|
||||
requestor_array,
|
||||
initial_value,
|
||||
function parallel_action(value, reason, number) {
|
||||
|
||||
// The action function gets the result of each requestor in the array.
|
||||
// 'parallel' wants to return an array of all of the values it sees.
|
||||
|
||||
results[number] = value;
|
||||
number_of_pending -= 1;
|
||||
|
||||
// If the requestor was wun of the requireds, make sure it was successful.
|
||||
// If it failed, then the parallel operation fails. If an optionals requestor
|
||||
// fails, we can still continue.
|
||||
|
||||
if (number < number_of_required) {
|
||||
number_of_pending_required -= 1;
|
||||
if (value === undefined) {
|
||||
cancel(reason);
|
||||
callback(undefined, reason);
|
||||
callback = undefined;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// If all have been processed, or if the requireds have all succeeded
|
||||
// and we do not have a 'time_option', then we are done.
|
||||
|
||||
if (
|
||||
number_of_pending < 1
|
||||
|| (
|
||||
time_option === undefined
|
||||
&& number_of_pending_required < 1
|
||||
)
|
||||
) {
|
||||
cancel(make_reason(factory_name, "Optional."));
|
||||
callback(
|
||||
factory_name === "sequence"
|
||||
? results.pop()
|
||||
: results
|
||||
);
|
||||
callback = undefined;
|
||||
}
|
||||
},
|
||||
function parallel_timeout() {
|
||||
|
||||
// When the timer fires, work stops unless we were under the 'false'
|
||||
// time option. The 'false' time option puts no time limits on the
|
||||
// requireds, allowing the optionals to run until the requireds finish
|
||||
// or the time expires, whichever happens last.
|
||||
|
||||
const reason = make_reason(
|
||||
factory_name,
|
||||
"Timeout.",
|
||||
time_limit
|
||||
);
|
||||
if (time_option === false) {
|
||||
time_option = undefined;
|
||||
if (number_of_pending_required < 1) {
|
||||
cancel(reason);
|
||||
callback(results);
|
||||
}
|
||||
} else {
|
||||
|
||||
// Time has expired. If all of the requireds were successful,
|
||||
// then the parallel operation is successful.
|
||||
|
||||
cancel(reason);
|
||||
if (number_of_pending_required < 1) {
|
||||
callback(results);
|
||||
} else {
|
||||
callback(undefined, reason);
|
||||
}
|
||||
callback = undefined;
|
||||
}
|
||||
},
|
||||
time_limit,
|
||||
throttle
|
||||
);
|
||||
return cancel;
|
||||
};
|
||||
}
|
||||
|
||||
function parallel_object(
|
||||
required_object,
|
||||
optional_object,
|
||||
time_limit,
|
||||
time_option,
|
||||
throttle
|
||||
) {
|
||||
|
||||
// 'parallel_object' is similar to 'parallel' except that it takes and
|
||||
// produces objects of requestors instead of arrays of requestors. This
|
||||
// factory converts the objects to arrays, and the requestor it returns
|
||||
// turns them back again. It lets 'parallel' do most of the work.
|
||||
|
||||
const names = [];
|
||||
let required_array = [];
|
||||
let optional_array = [];
|
||||
|
||||
// Extract the names and requestors from 'required_object'.
|
||||
// We only collect functions with an arity of 1 or 2.
|
||||
|
||||
if (required_object) {
|
||||
if (typeof required_object !== "object") {
|
||||
throw make_reason(
|
||||
"parallel_object",
|
||||
"Type mismatch.",
|
||||
required_object
|
||||
);
|
||||
}
|
||||
Object.keys(required_object).forEach(function (name) {
|
||||
let requestor = required_object[name];
|
||||
if (
|
||||
typeof requestor === "function"
|
||||
&& (requestor.length === 1 || requestor.length === 2)
|
||||
) {
|
||||
names.push(name);
|
||||
required_array.push(requestor);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Extract the names and requestors from 'optional_object'.
|
||||
// Look for duplicate keys.
|
||||
|
||||
if (optional_object) {
|
||||
if (typeof optional_object !== "object") {
|
||||
throw make_reason(
|
||||
"parallel_object",
|
||||
"Type mismatch.",
|
||||
optional_object
|
||||
);
|
||||
}
|
||||
Object.keys(optional_object).forEach(function (name) {
|
||||
let requestor = optional_object[name];
|
||||
if (
|
||||
typeof requestor === "function"
|
||||
&& (requestor.length === 1 || requestor.length === 2)
|
||||
) {
|
||||
if (required_object && required_object[name] !== undefined) {
|
||||
throw make_reason(
|
||||
"parallel_object",
|
||||
"Duplicate name.",
|
||||
name
|
||||
);
|
||||
}
|
||||
names.push(name);
|
||||
optional_array.push(requestor);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Call 'parallel' to get a requestor.
|
||||
|
||||
const parallel_requestor = parallel(
|
||||
required_array,
|
||||
optional_array,
|
||||
time_limit,
|
||||
time_option,
|
||||
throttle,
|
||||
"parallel_object"
|
||||
);
|
||||
|
||||
// Return the parallel object requestor.
|
||||
|
||||
return function parallel_object_requestor(callback, initial_value) {
|
||||
|
||||
// When our requestor is called, we return the result of our parallel requestor.
|
||||
|
||||
return parallel_requestor(
|
||||
|
||||
// We pass our callback to the parallel requestor,
|
||||
// converting its value into an object.
|
||||
|
||||
function parallel_object_callback(value, reason) {
|
||||
if (value === undefined) {
|
||||
return callback(undefined, reason);
|
||||
}
|
||||
const object = Object.create(null);
|
||||
names.forEach(function (name, index) {
|
||||
object[name] = value[index];
|
||||
});
|
||||
return callback(object);
|
||||
},
|
||||
initial_value
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
function race(requestor_array, time_limit, throttle) {
|
||||
|
||||
// The 'race' factory returns a requestor that starts all of the
|
||||
// requestors in 'requestor_array' at wunce. The first success wins.
|
||||
|
||||
const factory_name = (
|
||||
throttle === 1
|
||||
? "fallback"
|
||||
: "race"
|
||||
);
|
||||
|
||||
if (get_array_length(requestor_array, factory_name) === 0) {
|
||||
throw make_reason(factory_name, "No requestors.");
|
||||
}
|
||||
check_requestors(requestor_array, factory_name);
|
||||
return function race_requestor(callback, initial_value) {
|
||||
check_callback(callback, factory_name);
|
||||
let number_of_pending = requestor_array.length;
|
||||
let cancel = run(
|
||||
factory_name,
|
||||
requestor_array,
|
||||
initial_value,
|
||||
function race_action(value, reason, number) {
|
||||
number_of_pending -= 1;
|
||||
if (value !== undefined) {
|
||||
|
||||
// We have a winner. Cancel the losers and pass the value to the 'callback'.
|
||||
|
||||
cancel(make_reason(factory_name, "Loser.", number));
|
||||
callback(value);
|
||||
callback = undefined;
|
||||
} else if (number_of_pending < 1) {
|
||||
|
||||
// There was no winner. Signal a failure.
|
||||
|
||||
cancel(reason);
|
||||
callback(undefined, reason);
|
||||
callback = undefined;
|
||||
}
|
||||
},
|
||||
function race_timeout() {
|
||||
let reason = make_reason(
|
||||
factory_name,
|
||||
"Timeout.",
|
||||
time_limit
|
||||
);
|
||||
cancel(reason);
|
||||
callback(undefined, reason);
|
||||
callback = undefined;
|
||||
},
|
||||
time_limit,
|
||||
throttle
|
||||
);
|
||||
return cancel;
|
||||
};
|
||||
}
|
||||
|
||||
function fallback(requestor_array, time_limit) {
|
||||
|
||||
// The 'fallback' factory returns a requestor that tries each requestor
|
||||
// in 'requestor_array', wun at a time, until it finds a successful wun.
|
||||
|
||||
return race(requestor_array, time_limit, 1);
|
||||
}
|
||||
|
||||
function sequence(requestor_array, time_limit) {
|
||||
|
||||
// A sequence runs each requestor in order, passing results to the next,
|
||||
// as long as they are all successful. A sequence is a throttled parallel.
|
||||
|
||||
return parallel(
|
||||
requestor_array,
|
||||
undefined,
|
||||
time_limit,
|
||||
undefined,
|
||||
1,
|
||||
"sequence"
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
return {
|
||||
fallback,
|
||||
parallel,
|
||||
parallel_object,
|
||||
race,
|
||||
sequence
|
||||
}
|
||||
@@ -1,856 +1 @@
|
||||
var render = {}
|
||||
|
||||
var io = use('io')
|
||||
var os = use('os')
|
||||
var controller = use('controller')
|
||||
var tracy = use('tracy')
|
||||
var graphics = use('graphics')
|
||||
|
||||
var default_conf = {
|
||||
title:`Prosperon [${prosperon.version}-${prosperon.revision}]`,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
icon: graphics.make_texture(io.slurpbytes('icons/moon.gif')),
|
||||
high_dpi:0,
|
||||
alpha:1,
|
||||
fullscreen:0,
|
||||
sample_count:1,
|
||||
enable_clipboard:true,
|
||||
enable_dragndrop: true,
|
||||
max_dropped_files: 1,
|
||||
swap_interval: 1,
|
||||
name: "Prosperon",
|
||||
version:prosperon.version + "-" + prosperon.revision,
|
||||
identifier: "world.pockle.prosperon",
|
||||
creator: "Pockle World LLC",
|
||||
copyright: "Copyright Pockle World 2025",
|
||||
type: "application",
|
||||
url: "https://github.com/johnbrethauer/prosperon"
|
||||
}
|
||||
|
||||
var config = use('config.js')
|
||||
config.__proto__ = default_conf
|
||||
|
||||
prosperon.camera = use('camera').make()
|
||||
prosperon.camera.size = [config.width,config.height]
|
||||
|
||||
var base_pipeline = {
|
||||
vertex: "sprite.vert",
|
||||
fragment: "sprite.frag",
|
||||
primitive: "triangle", // point, line, linestrip, triangle, trianglestrip
|
||||
fill: true, // false for lines
|
||||
depth: {
|
||||
compare: "greater_equal", // never/less/equal/less_equal/greater/not_equal/greater_equal/always
|
||||
test: false,
|
||||
write: false,
|
||||
bias: 0,
|
||||
bias_slope_scale: 0,
|
||||
bias_clamp: 0
|
||||
},
|
||||
stencil: {
|
||||
enabled: true,
|
||||
front: {
|
||||
compare: "equal", // never/less/equal/less_equal/greater/neq/greq/always
|
||||
fail: "keep", // keep/zero/replace/incr_clamp/decr_clamp/invert/incr_wrap/decr_wrap
|
||||
depth_fail: "keep",
|
||||
pass: "keep"
|
||||
},
|
||||
back: {
|
||||
compare: "equal", // never/less/equal/less_equal/greater/neq/greq/always
|
||||
fail: "keep", // keep/zero/replace/incr_clamp/decr_clamp/invert/incr_wrap/decr_wrap
|
||||
depth_fail: "keep",
|
||||
pass: "keep"
|
||||
},
|
||||
test: true,
|
||||
compare_mask: 0,
|
||||
write_mask: 0
|
||||
},
|
||||
blend: {
|
||||
enabled: false,
|
||||
src_rgb: "zero", // zero/one/src_color/one_minus_src_color/dst_color/one_minus_dst_color/src_alpha/one_minus_src_alpha/dst_alpha/one_minus_dst_alpha/constant_color/one_minus_constant_color/src_alpha_saturate
|
||||
dst_rgb: "zero",
|
||||
op_rgb: "add", // add/sub/rev_sub/min/max
|
||||
src_alpha: "one",
|
||||
dst_alpha: "zero",
|
||||
op_alpha: "add"
|
||||
},
|
||||
cull: "none", // none/front/back
|
||||
face: "cw", // cw/ccw
|
||||
alpha_to_coverage: false,
|
||||
multisample: {
|
||||
count: 1, // number of multisamples
|
||||
mask: 0xFFFFFFFF,
|
||||
domask: false
|
||||
},
|
||||
label: "scripted pipeline",
|
||||
target: {}
|
||||
}
|
||||
|
||||
var sprite_pipeline = Object.create(base_pipeline);
|
||||
sprite_pipeline.blend = {
|
||||
enabled:true,
|
||||
src_rgb: "src_alpha", // zero/one/src_color/one_minus_src_color/dst_color/one_minus_dst_color/src_alpha/one_minus_src_alpha/dst_alpha/one_minus_dst_alpha/constant_color/one_minus_constant_color/src_alpha_saturate
|
||||
dst_rgb: "one_minus_src_alpha",
|
||||
op_rgb: "add", // add/sub/rev_sub/min/max
|
||||
src_alpha: "one",
|
||||
dst_alpha: "zero",
|
||||
op_alpha: "add"
|
||||
};
|
||||
|
||||
sprite_pipeline.target = {
|
||||
color_targets: [{
|
||||
format:"rgba8",
|
||||
blend:sprite_pipeline.blend
|
||||
}],
|
||||
depth: "d32 float s8"
|
||||
};
|
||||
|
||||
|
||||
var appy = {};
|
||||
appy.inputs = {};
|
||||
if (os.platform() === "macos") {
|
||||
appy.inputs["S-q"] = os.exit;
|
||||
}
|
||||
|
||||
appy.inputs["M-f4"] = os.exit;
|
||||
|
||||
controller.player[0].control(appy);
|
||||
|
||||
|
||||
|
||||
|
||||
prosperon.window = prosperon.engine_start(config);
|
||||
|
||||
var driver = "vulkan"
|
||||
switch(os.platform()) {
|
||||
case "Linux":
|
||||
driver = "vulkan"
|
||||
break
|
||||
case "Windows":
|
||||
// driver = "direct3d12"
|
||||
driver = "vulkan"
|
||||
break
|
||||
case "macOS":
|
||||
driver = "metal"
|
||||
break
|
||||
}
|
||||
|
||||
render._main = prosperon.window.make_gpu(false,driver)
|
||||
prosperon.gpu = render._main
|
||||
render._main.window = prosperon.window
|
||||
render._main.claim_window(prosperon.window)
|
||||
render._main.set_swapchain('sdr', 'vsync')
|
||||
|
||||
var unit_transform = os.make_transform();
|
||||
|
||||
var cur = {};
|
||||
cur.images = [];
|
||||
cur.samplers = [];
|
||||
|
||||
var tbuffer;
|
||||
function full_upload(buffers) {
|
||||
var cmds = render._main.acquire_cmd_buffer();
|
||||
tbuffer = render._main.upload(cmds, buffers, tbuffer);
|
||||
cmds.submit();
|
||||
}
|
||||
|
||||
full_upload[prosperon.DOC] = `Acquire a command buffer and upload the provided data buffers to the GPU, then submit.
|
||||
|
||||
:param buffers: An array of data buffers to be uploaded.
|
||||
:return: None
|
||||
`
|
||||
|
||||
function bind_pipeline(pass, pipeline) {
|
||||
make_pipeline(pipeline)
|
||||
pass.bind_pipeline(pipeline.gpu)
|
||||
pass.pipeline = pipeline;
|
||||
}
|
||||
|
||||
bind_pipeline[prosperon.DOC] = `Ensure the specified pipeline is created on the GPU and bind it to the given render pass.
|
||||
|
||||
:param pass: The current render pass to bind the pipeline to.
|
||||
:param pipeline: The pipeline object containing shader and state info.
|
||||
:return: None
|
||||
`
|
||||
|
||||
var main_pass;
|
||||
|
||||
var cornflower = [62/255,96/255,113/255,1];
|
||||
|
||||
function get_pipeline_ubo_slot(pipeline, name) {
|
||||
if (!pipeline.vertex.reflection.ubos) return;
|
||||
for (var i = 0; i < pipeline.vertex.reflection.ubos.length; i++) {
|
||||
var ubo = pipeline.vertex.reflection.ubos[i];
|
||||
if (ubo.name.endsWith(name))
|
||||
return i;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
get_pipeline_ubo_slot[prosperon.DOC] = `Return the index of a uniform buffer block within the pipeline's vertex reflection data by name suffix.
|
||||
|
||||
:param pipeline: The pipeline whose vertex reflection is inspected.
|
||||
:param name: A string suffix to match against the uniform buffer block name.
|
||||
:return: The integer index of the matching UBO, or undefined if not found.
|
||||
`
|
||||
|
||||
function transpose4x4(val) {
|
||||
var out = [];
|
||||
out[0] = val[0]; out[1] = val[4]; out[2] = val[8]; out[3] = val[12];
|
||||
out[4] = val[1]; out[5] = val[5]; out[6] = val[9]; out[7] = val[13];
|
||||
out[8] = val[2]; out[9] = val[6]; out[10] = val[10];out[11] = val[14];
|
||||
out[12] = val[3];out[13] = val[7];out[14] = val[11];out[15] = val[15];
|
||||
return out;
|
||||
}
|
||||
|
||||
transpose4x4[prosperon.DOC] = `Return a new 4x4 matrix array that is the transpose of the passed matrix.
|
||||
|
||||
:param val: An array of length 16 representing a 4x4 matrix in row-major format.
|
||||
:return: A new array of length 16 representing the transposed matrix.
|
||||
`
|
||||
|
||||
function ubo_obj_to_array(pipeline, name, obj) {
|
||||
var ubo;
|
||||
for (var i = 0; i < pipeline.vertex.reflection.ubos.length; i++) {
|
||||
ubo = pipeline.vertex.reflection.ubos[i];
|
||||
if (ubo.name.endsWith(name)) break;
|
||||
}
|
||||
var type = pipeline.vertex.reflection.types[ubo.type];
|
||||
var len = 0;
|
||||
for (var mem of type.members)
|
||||
len += type_to_byte_count(mem.type);
|
||||
|
||||
var buf = new ArrayBuffer(len);
|
||||
var view = new DataView(buf);
|
||||
|
||||
for (var mem of type.members) {
|
||||
var val = obj[mem.name];
|
||||
if (!val) throw new Error (`Could not find ${mem.name} on supplied object`);
|
||||
|
||||
if (mem.name === 'model')
|
||||
val = transpose4x4(val.array());
|
||||
|
||||
for (var i = 0; i < val.length; i++)
|
||||
view.setFloat32(mem.offset + i*4, val[i],true);
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
ubo_obj_to_array[prosperon.DOC] = `Construct an ArrayBuffer containing UBO data from the provided object, matching the pipeline's reflection info.
|
||||
|
||||
:param pipeline: The pipeline whose vertex reflection is read for UBO structure.
|
||||
:param name: The name suffix that identifies the target UBO in the reflection data.
|
||||
:param obj: An object whose properties match the UBO members.
|
||||
:return: An ArrayBuffer containing packed UBO data.
|
||||
`
|
||||
|
||||
function type_to_byte_count(type) {
|
||||
switch (type) {
|
||||
case 'float': return 4;
|
||||
case 'vec2': return 8;
|
||||
case 'vec3': return 12;
|
||||
case 'vec4': return 16;
|
||||
case 'mat4': return 64;
|
||||
default: throw new Error("Unknown or unsupported float-based type: " + type);
|
||||
}
|
||||
}
|
||||
|
||||
type_to_byte_count[prosperon.DOC] = `Return the byte size for known float-based types.
|
||||
|
||||
:param type: A string type identifier (e.g., 'float', 'vec2', 'vec3', 'vec4', 'mat4').
|
||||
:return: Integer number of bytes.
|
||||
`
|
||||
|
||||
var sprite_model_ubo = {
|
||||
model: unit_transform,
|
||||
color: [1,1,1,1]
|
||||
};
|
||||
|
||||
var shader_cache = {};
|
||||
var shader_times = {};
|
||||
|
||||
function make_pipeline(pipeline) {
|
||||
if (pipeline.hasOwnProperty("gpu")) return; // this pipeline has already been made
|
||||
|
||||
if (typeof pipeline.vertex === 'string')
|
||||
pipeline.vertex = make_shader(pipeline.vertex);
|
||||
if (typeof pipeline.fragment === 'string')
|
||||
pipeline.fragment = make_shader(pipeline.fragment)
|
||||
|
||||
// 1) Reflection data for vertex shader
|
||||
var refl = pipeline.vertex.reflection
|
||||
if (!refl || !refl.inputs || !Array.isArray(refl.inputs)) {
|
||||
pipeline.gpu = render._main.make_pipeline(pipeline);
|
||||
return;
|
||||
}
|
||||
|
||||
var inputs = refl.inputs
|
||||
var buffer_descriptions = []
|
||||
var attributes = []
|
||||
|
||||
// 2) Build buffer + attribute for each reflection input
|
||||
for (var i = 0; i < inputs.length; i++) {
|
||||
var inp = inputs[i]
|
||||
var typeStr = inp.type
|
||||
var nameStr = (inp.name || "").toUpperCase()
|
||||
var pitch = 4
|
||||
var fmt = "float1"
|
||||
|
||||
if (typeStr == "vec2") {
|
||||
pitch = 8
|
||||
fmt = "float2"
|
||||
} else if (typeStr == "vec3") {
|
||||
pitch = 12
|
||||
fmt = "float3"
|
||||
} else if (typeStr == "vec4") {
|
||||
if (nameStr.indexOf("COLOR") >= 0) {
|
||||
pitch = 16
|
||||
fmt = "color"
|
||||
} else {
|
||||
pitch = 16
|
||||
fmt = "float4"
|
||||
}
|
||||
}
|
||||
|
||||
buffer_descriptions.push({
|
||||
slot: i,
|
||||
pitch: pitch,
|
||||
input_rate: "vertex",
|
||||
instance_step_rate: 0,
|
||||
name:inp.name.split(".").pop()
|
||||
})
|
||||
|
||||
attributes.push({
|
||||
location: inp.location,
|
||||
buffer_slot: i,
|
||||
format: fmt,
|
||||
offset: 0
|
||||
})
|
||||
}
|
||||
|
||||
pipeline.vertex_buffer_descriptions = buffer_descriptions
|
||||
pipeline.vertex_attributes = attributes
|
||||
|
||||
pipeline.gpu = render._main.make_pipeline(pipeline);
|
||||
}
|
||||
|
||||
make_pipeline[prosperon.DOC] = `Create and store a GPU pipeline object if it has not already been created.
|
||||
|
||||
:param pipeline: An object describing the pipeline state, shaders, and reflection data.
|
||||
:return: None
|
||||
`
|
||||
|
||||
var shader_type;
|
||||
|
||||
function make_shader(sh_file) {
|
||||
var file = `shaders/${shader_type}/${sh_file}.${shader_type}`
|
||||
if (shader_cache[file]) return shader_cache[file]
|
||||
var refl = json.decode(io.slurp(`shaders/reflection/${sh_file}.json`))
|
||||
|
||||
var shader = {
|
||||
code: io.slurpbytes(file),
|
||||
format: shader_type,
|
||||
stage: sh_file.endsWith("vert") ? "vertex" : "fragment",
|
||||
num_samplers: refl.separate_samplers ? refl.separate_samplers.length : 0,
|
||||
num_textures: 0,
|
||||
num_storage_buffers: refl.separate_storage_buffers ? refl.separate_storage_buffers.length : 0,
|
||||
num_uniform_buffers: refl.ubos ? refl.ubos.length : 0,
|
||||
entrypoint: shader_type === "msl" ? "main0" : "main"
|
||||
}
|
||||
console.log(`making shader ${sh_file} of format ${shader_type}`)
|
||||
|
||||
shader.gpu = render._main.make_shader(shader)
|
||||
shader.reflection = refl;
|
||||
shader_cache[file] = shader
|
||||
shader.file = sh_file
|
||||
return shader
|
||||
}
|
||||
|
||||
make_shader[prosperon.DOC] = `Load and compile a shader from disk, caching the result. Reflective metadata is also loaded.
|
||||
|
||||
:param sh_file: The base filename (without extension) of the shader to compile.
|
||||
:return: A shader object with GPU and reflection data attached.
|
||||
`
|
||||
|
||||
// helpful render devices. width and height in pixels; diagonal in inches.
|
||||
render.device = {
|
||||
pc: { width: 1920, height: 1080 },
|
||||
macbook_m2: { width: 2560, height: 1664, diagonal: 13.6 },
|
||||
ds_top: { width: 400, height: 240, diagonal: 3.53 },
|
||||
ds_bottom: { width: 320, height: 240, diagonal: 3.02 },
|
||||
playdate: { width: 400, height: 240, diagonal: 2.7 },
|
||||
switch: { width: 1280, height: 720, diagonal: 6.2 },
|
||||
switch_lite: { width: 1280, height: 720, diagonal: 5.5 },
|
||||
switch_oled: { width: 1280, height: 720, diagonal: 7 },
|
||||
dsi: { width: 256, height: 192, diagonal: 3.268 },
|
||||
ds: { width: 256, height: 192, diagonal: 3 },
|
||||
dsixl: { width: 256, height: 192, diagonal: 4.2 },
|
||||
ipad_air_m2: { width: 2360, height: 1640, diagonal: 11.97 },
|
||||
iphone_se: { width: 1334, height: 750, diagonal: 4.7 },
|
||||
iphone_12_pro: { width: 2532, height: 1170, diagonal: 6.06 },
|
||||
iphone_15: { width: 2556, height: 1179, diagonal: 6.1 },
|
||||
gba: { width: 240, height: 160, diagonal: 2.9 },
|
||||
gameboy: { width: 160, height: 144, diagonal: 2.48 },
|
||||
gbc: { width: 160, height: 144, diagonal: 2.28 },
|
||||
steamdeck: { width: 1280, height: 800, diagonal: 7 },
|
||||
vita: { width: 960, height: 544, diagonal: 5 },
|
||||
psp: { width: 480, height: 272, diagonal: 4.3 },
|
||||
imac_m3: { width: 4480, height: 2520, diagonal: 23.5 },
|
||||
macbook_pro_m3: { width: 3024, height: 1964, diagonal: 14.2 },
|
||||
ps1: { width: 320, height: 240, diagonal: 5 },
|
||||
ps2: { width: 640, height: 480 },
|
||||
snes: { width: 256, height: 224 },
|
||||
gamecube: { width: 640, height: 480 },
|
||||
n64: { width: 320, height: 240 },
|
||||
c64: { width: 320, height: 200 },
|
||||
macintosh: { width: 512, height: 342 },
|
||||
gamegear: { width: 160, height: 144, diagonal: 3.2 }
|
||||
};
|
||||
|
||||
render.device.doc = `Device resolutions given as [x,y,inches diagonal].`;
|
||||
|
||||
var render_queue = [];
|
||||
var hud_queue = [];
|
||||
|
||||
var current_queue = render_queue;
|
||||
|
||||
var std_sampler = {
|
||||
min_filter: "nearest",
|
||||
mag_filter: "nearest",
|
||||
mipmap: "linear",
|
||||
u: "repeat",
|
||||
v: "repeat",
|
||||
w: "repeat",
|
||||
mip_bias: 0,
|
||||
max_anisotropy: 0,
|
||||
compare_op: "none",
|
||||
min_lod: 0,
|
||||
max_lod: 0,
|
||||
anisotropy: false,
|
||||
compare: false
|
||||
};
|
||||
|
||||
function upload_model(model) {
|
||||
var bufs = [];
|
||||
for (var i in model) {
|
||||
if (typeof model[i] !== 'object') continue;
|
||||
bufs.push(model[i]);
|
||||
}
|
||||
render._main.upload(this, bufs);
|
||||
}
|
||||
|
||||
upload_model[prosperon.DOC] = `Upload all buffer-like properties of the given model to the GPU.
|
||||
|
||||
:param model: An object whose buffer properties are to be uploaded.
|
||||
:return: None
|
||||
`
|
||||
|
||||
function bind_model(pass, pipeline, model) {
|
||||
var buffers = pipeline.vertex_buffer_descriptions;
|
||||
var bufs = [];
|
||||
if (buffers)
|
||||
for (var b of buffers) {
|
||||
if (b.name in model) bufs.push(model[b.name])
|
||||
else throw Error (`could not find buffer ${b.name} on model`);
|
||||
}
|
||||
pass.bind_buffers(0,bufs);
|
||||
pass.bind_index_buffer(model.indices);
|
||||
}
|
||||
|
||||
bind_model[prosperon.DOC] = `Bind the model's vertex and index buffers for the given pipeline and render pass.
|
||||
|
||||
:param pass: The current render pass.
|
||||
:param pipeline: The pipeline object with vertex buffer descriptions.
|
||||
:param model: The model object containing matching buffers and an index buffer.
|
||||
:return: None
|
||||
`
|
||||
|
||||
function bind_mat(pass, pipeline, mat) {
|
||||
var imgs = [];
|
||||
var refl = pipeline.fragment.reflection;
|
||||
if (refl.separate_images) {
|
||||
for (var i of refl.separate_images) {
|
||||
if (i.name in mat) {
|
||||
var tex = mat[i.name];
|
||||
imgs.push({texture:tex.texture, sampler:tex.sampler});
|
||||
} else
|
||||
throw Error (`could not find all necessary images: ${i.name}`)
|
||||
}
|
||||
pass.bind_samplers(false, 0,imgs);
|
||||
}
|
||||
}
|
||||
|
||||
bind_mat[prosperon.DOC] = `Bind the material images and samplers needed by the pipeline's fragment shader.
|
||||
|
||||
:param pass: The current render pass.
|
||||
:param pipeline: The pipeline whose fragment shader reflection indicates required textures.
|
||||
:param mat: An object mapping the required image names to {texture, sampler}.
|
||||
:return: None
|
||||
`
|
||||
|
||||
function group_sprites_by_texture(sprites, mesh) {
|
||||
if (sprites.length === 0) return;
|
||||
for (var i = 0; i < sprites.length; i++) {
|
||||
sprites[i].mesh = mesh;
|
||||
sprites[i].first_index = i*6;
|
||||
sprites[i].num_indices = 6;
|
||||
}
|
||||
return;
|
||||
// The code below is an alternate approach to grouping by image. Currently not in use.
|
||||
/*
|
||||
var groups = [];
|
||||
var group = {image:sprites[0].image, first_index:0};
|
||||
var count = 1;
|
||||
for (var i = 1; i < sprites.length; i++) {
|
||||
if (sprites[i].image === group.image) {
|
||||
count++;
|
||||
continue;
|
||||
}
|
||||
group.num_indices = count*6;
|
||||
var newgroup = {image:sprites[i].image, first_index:group.first_index+group.num_indices};
|
||||
group = newgroup;
|
||||
groups.push(group);
|
||||
count=1;
|
||||
}
|
||||
group.num_indices = count*6;
|
||||
return groups;
|
||||
*/
|
||||
}
|
||||
|
||||
group_sprites_by_texture[prosperon.DOC] = `Assign each sprite to the provided mesh, generating index data as needed.
|
||||
|
||||
:param sprites: An array of sprite objects.
|
||||
:param mesh: A mesh object (pos, color, uv, indices, etc.) to link to each sprite.
|
||||
:return: None
|
||||
`
|
||||
|
||||
var main_color = {
|
||||
type:"2d",
|
||||
format: "rgba8",
|
||||
layers: 1,
|
||||
mip_levels: 1,
|
||||
samples: 0,
|
||||
sampler:true,
|
||||
color_target:true
|
||||
};
|
||||
|
||||
var main_depth = {
|
||||
type: "2d",
|
||||
format: "d32 float s8",
|
||||
layers:1,
|
||||
mip_levels:1,
|
||||
samples:0,
|
||||
sampler:true,
|
||||
depth_target:true
|
||||
};
|
||||
|
||||
function render_camera(cmds, camera) {
|
||||
var pass;
|
||||
delete camera.target // TODO: HORRIBLE
|
||||
if (!camera.target) {
|
||||
main_color.width = main_depth.width = camera.size.x;
|
||||
main_color.height = main_depth.height = camera.size.y;
|
||||
camera.target = {
|
||||
color_targets: [{
|
||||
texture: render._main.texture(main_color),
|
||||
mip_level:0,
|
||||
layer: 0,
|
||||
load:"clear",
|
||||
store:"store",
|
||||
clear: cornflower
|
||||
}],
|
||||
depth_stencil: {
|
||||
texture: render._main.texture(main_depth),
|
||||
clear:1,
|
||||
load:"dont_care",
|
||||
store:"dont_care",
|
||||
stencil_load:"dont_care",
|
||||
stencil_store:"dont_care",
|
||||
stencil_clear:0
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var buffers = [];
|
||||
buffers = buffers.concat(graphics.queue_sprite_mesh(render_queue));
|
||||
var unique_meshes = [...new Set(render_queue.map(x => x.mesh))];
|
||||
for (var q of unique_meshes)
|
||||
buffers = buffers.concat([q.pos, q.color, q.uv, q.indices]);
|
||||
|
||||
buffers = buffers.concat(graphics.queue_sprite_mesh(hud_queue));
|
||||
for (var q of hud_queue)
|
||||
if (q.type === 'geometry') buffers = buffers.concat([q.mesh.pos, q.mesh.color, q.mesh.uv, q.mesh.indices]);
|
||||
|
||||
full_upload(buffers)
|
||||
|
||||
var pass = cmds.render_pass(camera.target);
|
||||
|
||||
var pipeline = sprite_pipeline;
|
||||
bind_pipeline(pass,pipeline);
|
||||
|
||||
var camslot = get_pipeline_ubo_slot(pipeline, 'TransformBuffer');
|
||||
if (typeof camslot !== 'undefined')
|
||||
cmds.camera(camera, camslot);
|
||||
|
||||
modelslot = get_pipeline_ubo_slot(pipeline, "model");
|
||||
if (typeof modelslot !== 'undefined') {
|
||||
var ubo = ubo_obj_to_array(pipeline, 'model', sprite_model_ubo);
|
||||
cmds.push_vertex_uniform_data(modelslot, ubo);
|
||||
}
|
||||
|
||||
var mesh;
|
||||
var img;
|
||||
var modelslot;
|
||||
|
||||
cmds.push_debug_group("draw")
|
||||
for (var group of render_queue) {
|
||||
if (mesh != group.mesh) {
|
||||
mesh = group.mesh;
|
||||
bind_model(pass,pipeline,mesh);
|
||||
}
|
||||
|
||||
if (group.image && img != group.image) {
|
||||
img = group.image;
|
||||
img.sampler = std_sampler;
|
||||
bind_mat(pass,pipeline,{diffuse:img});
|
||||
}
|
||||
|
||||
pass.draw_indexed(group.num_indices, 1, group.first_index, 0, 0);
|
||||
}
|
||||
cmds.pop_debug_group()
|
||||
|
||||
cmds.push_debug_group("hud")
|
||||
var camslot = get_pipeline_ubo_slot(pipeline, 'TransformBuffer');
|
||||
if (typeof camslot !== 'undefined')
|
||||
cmds.hud(camera.size, camslot);
|
||||
|
||||
for (var group of hud_queue) {
|
||||
if (mesh != group.mesh) {
|
||||
mesh = group.mesh;
|
||||
bind_model(pass,pipeline,mesh);
|
||||
}
|
||||
|
||||
if (group.image && img != group.image) {
|
||||
img = group.image;
|
||||
img.sampler = std_sampler;
|
||||
bind_mat(pass,pipeline,{diffuse:img});
|
||||
}
|
||||
|
||||
pass.draw_indexed(group.num_indices, 1, group.first_index, 0, 0);
|
||||
}
|
||||
cmds.pop_debug_group();
|
||||
|
||||
pass?.end();
|
||||
|
||||
render_queue = [];
|
||||
hud_queue = [];
|
||||
}
|
||||
|
||||
render_camera[prosperon.DOC] = `Render a scene using the provided camera, drawing both render queue and HUD queue items.
|
||||
|
||||
:param cmds: A command buffer obtained from the GPU context.
|
||||
:param camera: The camera object (with size, optional target, etc.).
|
||||
:return: None
|
||||
`
|
||||
|
||||
var imgui = use('imgui')
|
||||
if (imgui) imgui.init(render._main, prosperon.window);
|
||||
|
||||
var swaps = [];
|
||||
function gpupresent() {
|
||||
os.clean_transforms();
|
||||
var cmds = render._main.acquire_cmd_buffer();
|
||||
render_camera(cmds, prosperon.camera);
|
||||
var swapchain_tex = cmds.acquire_swapchain();
|
||||
if (!swapchain_tex)
|
||||
cmds.cancel();
|
||||
else {
|
||||
var torect = prosperon.camera.draw_rect(prosperon.window.size);
|
||||
torect.texture = swapchain_tex;
|
||||
if (swapchain_tex) {
|
||||
cmds.blit({
|
||||
src: prosperon.camera.target.color_targets[0].texture,
|
||||
dst: torect,
|
||||
filter:"nearest",
|
||||
load: "clear"
|
||||
});
|
||||
|
||||
if (imgui) {
|
||||
cmds.push_debug_group("imgui")
|
||||
imgui.prepend(cmds);
|
||||
var pass = cmds.render_pass({
|
||||
color_targets:[{texture:swapchain_tex}]});
|
||||
imgui.endframe(cmds,pass);
|
||||
pass.end();
|
||||
cmds.pop_debug_group()
|
||||
}
|
||||
}
|
||||
cmds.submit()
|
||||
}
|
||||
}
|
||||
|
||||
gpupresent[prosperon.DOC] = `Perform the per-frame rendering and present the final swapchain image, including imgui pass if available.
|
||||
|
||||
:return: None
|
||||
`
|
||||
|
||||
var stencil_write = {
|
||||
compare: "always",
|
||||
fail_op: "replace",
|
||||
depth_fail_op: "replace",
|
||||
pass_op: "replace"
|
||||
};
|
||||
|
||||
var stencil_writer = function stencil_writer(ref) {
|
||||
var pipe = Object.create(base_pipeline);
|
||||
Object.assign(pipe, {
|
||||
stencil: {
|
||||
enabled: true,
|
||||
front: stencil_write,
|
||||
back: stencil_write,
|
||||
write:true,
|
||||
read:true,
|
||||
ref:ref
|
||||
},
|
||||
write_mask: colormask.none
|
||||
});
|
||||
return pipe;
|
||||
}.hashify();
|
||||
|
||||
render.stencil_writer = stencil_writer;
|
||||
|
||||
// objects by default draw where the stencil buffer is 0
|
||||
render.fillmask = function fillmask(ref) {
|
||||
var pipe = stencil_writer(ref);
|
||||
render.use_shader('screenfill.cg', pipe);
|
||||
render.draw(shape.quad);
|
||||
}
|
||||
|
||||
render.fillmask[prosperon.DOC] = `Draw a fullscreen shape using a 'screenfill' shader to populate the stencil buffer with a given reference.
|
||||
|
||||
:param ref: The stencil reference value to write.
|
||||
:return: None
|
||||
`
|
||||
|
||||
var stencil_invert = {
|
||||
compare: "always",
|
||||
fail_op: "invert",
|
||||
depth_fail_op: "invert",
|
||||
pass_op: "invert"
|
||||
};
|
||||
|
||||
render.mask = function mask(image, pos, scale, rotation = 0, ref = 1) {
|
||||
if (typeof image === 'string')
|
||||
image = graphics.texture(image);
|
||||
|
||||
var tex = image.texture;
|
||||
if (scale) scale = scale.div([tex.width,tex.height]);
|
||||
else scale = [1,1,1]
|
||||
|
||||
var pipe = stencil_writer(ref);
|
||||
render.use_shader('sprite.cg', pipe);
|
||||
var t = os.make_transform();
|
||||
t.trs(pos, undefined, scale);
|
||||
set_model(t);
|
||||
render.use_mat({
|
||||
diffuse:image.texture,
|
||||
rect: image.rect,
|
||||
shade: Color.white
|
||||
});
|
||||
render.draw(shape.quad);
|
||||
}
|
||||
|
||||
render.mask[prosperon.DOC] = `Draw an image to the stencil buffer, marking its area with a specified reference value.
|
||||
|
||||
:param image: A texture or string path (which is converted to a texture).
|
||||
:param pos: The translation (x, y) for the image placement.
|
||||
:param scale: Optional scaling applied to the texture.
|
||||
:param rotation: Optional rotation in radians (unused by default).
|
||||
:param ref: The stencil reference value to write.
|
||||
:return: None
|
||||
`
|
||||
|
||||
render.viewport = function(rect) {
|
||||
render._main.viewport(rect);
|
||||
}
|
||||
|
||||
render.viewport[prosperon.DOC] = `Set the GPU viewport to the specified rectangle.
|
||||
|
||||
:param rect: A rectangle [x, y, width, height].
|
||||
:return: None
|
||||
`
|
||||
|
||||
render.scissor = function(rect) {
|
||||
render.viewport(rect)
|
||||
}
|
||||
|
||||
render.scissor[prosperon.DOC] = `Set the GPU scissor region to the specified rectangle (alias of render.viewport).
|
||||
|
||||
:param rect: A rectangle [x, y, width, height].
|
||||
:return: None
|
||||
`
|
||||
|
||||
var imdebug = function imdebug() {
|
||||
imtoggle("Physics", debug, "draw_phys");
|
||||
imtoggle("Bouning boxes", debug, "draw_bb");
|
||||
imtoggle("Names", debug, "draw_names");
|
||||
imtoggle("Sprite nums", debug, "sprite_nums");
|
||||
imtoggle("Debug overlay", debug, "show");
|
||||
imtoggle("Show ur names", debug, "urnames");
|
||||
};
|
||||
|
||||
var observed_tex = undefined;
|
||||
|
||||
var debug = {}
|
||||
debug.console = false
|
||||
|
||||
// Some initialization
|
||||
shader_type = render._main.shader_format()[0];
|
||||
|
||||
std_sampler = render._main.make_sampler({
|
||||
min_filter: "nearest",
|
||||
mag_filter: "nearest",
|
||||
mipmap_mode: "nearest",
|
||||
address_mode_u: "repeat",
|
||||
address_mode_v: "repeat",
|
||||
address_mode_w: "repeat"
|
||||
});
|
||||
|
||||
render._main.present = gpupresent;
|
||||
|
||||
if (tracy) tracy.gpu_init()
|
||||
|
||||
render.queue = function(cmd) {
|
||||
if (Array.isArray(cmd))
|
||||
for (var i of cmd) current_queue.push(i)
|
||||
else
|
||||
current_queue.push(cmd)
|
||||
}
|
||||
|
||||
render.queue[prosperon.DOC] = `Enqueue one or more draw commands. These commands are batched until render_camera is called.
|
||||
|
||||
:param cmd: Either a single command object or an array of command objects.
|
||||
:return: None
|
||||
`
|
||||
|
||||
render.setup_draw = function() {
|
||||
current_queue = render_queue;
|
||||
prosperon.draw();
|
||||
}
|
||||
|
||||
render.setup_draw[prosperon.DOC] = `Switch the current queue to the primary scene render queue, then invoke 'prosperon.draw' if defined.
|
||||
|
||||
:return: None
|
||||
`
|
||||
|
||||
render.setup_hud = function() {
|
||||
current_queue = hud_queue;
|
||||
prosperon.hud();
|
||||
}
|
||||
|
||||
render.setup_hud[prosperon.DOC] = `Switch the current queue to the HUD render queue, then invoke 'prosperon.hud' if defined.
|
||||
|
||||
:return: None
|
||||
`
|
||||
|
||||
return render
|
||||
return use('sdl_render')
|
||||
|
||||
@@ -41,9 +41,9 @@ function isRecognizedExtension(ext) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Attempt to find file with or without extension from the current PATH
|
||||
// (From the original resources.js, unchanged except for code style)
|
||||
function find_in_path(filename, exts = []) {
|
||||
if (typeof filename !== 'string') return undefined
|
||||
|
||||
if (filename.includes('.')) {
|
||||
for (var dir of prosperon.PATH) {
|
||||
var candidate = dir + filename
|
||||
@@ -53,10 +53,15 @@ function find_in_path(filename, exts = []) {
|
||||
}
|
||||
|
||||
for (var dir of prosperon.PATH) {
|
||||
var candidate = dir + filename
|
||||
if (io.exists(candidate) && !io.is_directory(candidate)) return candidate
|
||||
for (var ext of exts) {
|
||||
candidate = dir + filename + '.' + ext
|
||||
// Only check extensions if exts is provided and not empty
|
||||
if (exts.length > 0) {
|
||||
for (var ext of exts) {
|
||||
var candidate = dir + filename + '.' + ext
|
||||
if (io.exists(candidate) && !io.is_directory(candidate)) return candidate
|
||||
}
|
||||
} else {
|
||||
// Fallback to extensionless file only if no extensions are specified
|
||||
var candidate = dir + filename
|
||||
if (io.exists(candidate) && !io.is_directory(candidate)) return candidate
|
||||
}
|
||||
}
|
||||
|
||||
791
scripts/modules/sdl_gpu.js
Normal file
@@ -0,0 +1,791 @@
|
||||
var render = {}
|
||||
|
||||
var io = use('io')
|
||||
var os = use('os')
|
||||
var controller = use('controller')
|
||||
var tracy = use('tracy')
|
||||
var graphics = use('graphics')
|
||||
var imgui = use('imgui')
|
||||
|
||||
var base_pipeline = {
|
||||
vertex: "sprite.vert",
|
||||
fragment: "sprite.frag",
|
||||
primitive: "triangle", // point, line, linestrip, triangle, trianglestrip
|
||||
fill: true, // false for lines
|
||||
depth: {
|
||||
compare: "greater_equal", // never/less/equal/less_equal/greater/not_equal/greater_equal/always
|
||||
test: false,
|
||||
write: false,
|
||||
bias: 0,
|
||||
bias_slope_scale: 0,
|
||||
bias_clamp: 0
|
||||
},
|
||||
stencil: {
|
||||
enabled: true,
|
||||
front: {
|
||||
compare: "equal", // never/less/equal/less_equal/greater/neq/greq/always
|
||||
fail: "keep", // keep/zero/replace/incr_clamp/decr_clamp/invert/incr_wrap/decr_wrap
|
||||
depth_fail: "keep",
|
||||
pass: "keep"
|
||||
},
|
||||
back: {
|
||||
compare: "equal", // never/less/equal/less_equal/greater/neq/greq/always
|
||||
fail: "keep", // keep/zero/replace/incr_clamp/decr_clamp/invert/incr_wrap/decr_wrap
|
||||
depth_fail: "keep",
|
||||
pass: "keep"
|
||||
},
|
||||
test: true,
|
||||
compare_mask: 0,
|
||||
write_mask: 0
|
||||
},
|
||||
blend: {
|
||||
enabled: false,
|
||||
src_rgb: "zero", // zero/one/src_color/one_minus_src_color/dst_color/one_minus_dst_color/src_alpha/one_minus_src_alpha/dst_alpha/one_minus_dst_alpha/constant_color/one_minus_constant_color/src_alpha_saturate
|
||||
dst_rgb: "zero",
|
||||
op_rgb: "add", // add/sub/rev_sub/min/max
|
||||
src_alpha: "one",
|
||||
dst_alpha: "zero",
|
||||
op_alpha: "add"
|
||||
},
|
||||
cull: "none", // none/front/back
|
||||
face: "cw", // cw/ccw
|
||||
alpha_to_coverage: false,
|
||||
multisample: {
|
||||
count: 1, // number of multisamples
|
||||
mask: 0xFFFFFFFF,
|
||||
domask: false
|
||||
},
|
||||
label: "scripted pipeline",
|
||||
target: {}
|
||||
}
|
||||
|
||||
var sprite_pipeline = Object.create(base_pipeline);
|
||||
sprite_pipeline.blend = {
|
||||
enabled:true,
|
||||
src_rgb: "src_alpha", // zero/one/src_color/one_minus_src_color/dst_color/one_minus_dst_color/src_alpha/one_minus_src_alpha/dst_alpha/one_minus_dst_alpha/constant_color/one_minus_constant_color/src_alpha_saturate
|
||||
dst_rgb: "one_minus_src_alpha",
|
||||
op_rgb: "add", // add/sub/rev_sub/min/max
|
||||
src_alpha: "one",
|
||||
dst_alpha: "zero",
|
||||
op_alpha: "add"
|
||||
};
|
||||
|
||||
var context;
|
||||
|
||||
sprite_pipeline.target = {
|
||||
color_targets: [{
|
||||
format:"rgba8",
|
||||
blend:sprite_pipeline.blend
|
||||
}],
|
||||
depth: "d32 float s8"
|
||||
};
|
||||
|
||||
var driver = "vulkan"
|
||||
switch(os.platform()) {
|
||||
case "Linux":
|
||||
driver = "vulkan"
|
||||
break
|
||||
case "Windows":
|
||||
// driver = "direct3d12"
|
||||
driver = "vulkan"
|
||||
break
|
||||
case "macOS":
|
||||
driver = "metal"
|
||||
break
|
||||
}
|
||||
|
||||
var unit_transform = os.make_transform();
|
||||
|
||||
var cur = {};
|
||||
cur.images = [];
|
||||
cur.samplers = [];
|
||||
|
||||
var tbuffer;
|
||||
function full_upload(buffers) {
|
||||
var cmds = context.acquire_cmd_buffer();
|
||||
tbuffer = context.upload(cmds, buffers, tbuffer);
|
||||
cmds.submit();
|
||||
}
|
||||
|
||||
full_upload[prosperon.DOC] = `Acquire a command buffer and upload the provided data buffers to the GPU, then submit.
|
||||
|
||||
:param buffers: An array of data buffers to be uploaded.
|
||||
:return: None
|
||||
`
|
||||
|
||||
function bind_pipeline(pass, pipeline) {
|
||||
make_pipeline(pipeline)
|
||||
pass.bind_pipeline(pipeline.gpu)
|
||||
pass.pipeline = pipeline;
|
||||
}
|
||||
|
||||
bind_pipeline[prosperon.DOC] = `Ensure the specified pipeline is created on the GPU and bind it to the given render pass.
|
||||
|
||||
:param pass: The current render pass to bind the pipeline to.
|
||||
:param pipeline: The pipeline object containing shader and state info.
|
||||
:return: None
|
||||
`
|
||||
|
||||
var main_pass;
|
||||
|
||||
var cornflower = [62/255,96/255,113/255,1];
|
||||
|
||||
function get_pipeline_ubo_slot(pipeline, name) {
|
||||
if (!pipeline.vertex.reflection.ubos) return;
|
||||
for (var i = 0; i < pipeline.vertex.reflection.ubos.length; i++) {
|
||||
var ubo = pipeline.vertex.reflection.ubos[i];
|
||||
if (ubo.name.endsWith(name))
|
||||
return i;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
get_pipeline_ubo_slot[prosperon.DOC] = `Return the index of a uniform buffer block within the pipeline's vertex reflection data by name suffix.
|
||||
|
||||
:param pipeline: The pipeline whose vertex reflection is inspected.
|
||||
:param name: A string suffix to match against the uniform buffer block name.
|
||||
:return: The integer index of the matching UBO, or undefined if not found.
|
||||
`
|
||||
|
||||
function transpose4x4(val) {
|
||||
var out = [];
|
||||
out[0] = val[0]; out[1] = val[4]; out[2] = val[8]; out[3] = val[12];
|
||||
out[4] = val[1]; out[5] = val[5]; out[6] = val[9]; out[7] = val[13];
|
||||
out[8] = val[2]; out[9] = val[6]; out[10] = val[10];out[11] = val[14];
|
||||
out[12] = val[3];out[13] = val[7];out[14] = val[11];out[15] = val[15];
|
||||
return out;
|
||||
}
|
||||
|
||||
transpose4x4[prosperon.DOC] = `Return a new 4x4 matrix array that is the transpose of the passed matrix.
|
||||
|
||||
:param val: An array of length 16 representing a 4x4 matrix in row-major format.
|
||||
:return: A new array of length 16 representing the transposed matrix.
|
||||
`
|
||||
|
||||
function ubo_obj_to_array(pipeline, name, obj) {
|
||||
var ubo;
|
||||
for (var i = 0; i < pipeline.vertex.reflection.ubos.length; i++) {
|
||||
ubo = pipeline.vertex.reflection.ubos[i];
|
||||
if (ubo.name.endsWith(name)) break;
|
||||
}
|
||||
var type = pipeline.vertex.reflection.types[ubo.type];
|
||||
var len = 0;
|
||||
for (var mem of type.members)
|
||||
len += type_to_byte_count(mem.type);
|
||||
|
||||
var buf = new ArrayBuffer(len);
|
||||
var view = new DataView(buf);
|
||||
|
||||
for (var mem of type.members) {
|
||||
var val = obj[mem.name];
|
||||
if (!val) throw new Error (`Could not find ${mem.name} on supplied object`);
|
||||
|
||||
if (mem.name === 'model')
|
||||
val = transpose4x4(val.array());
|
||||
|
||||
for (var i = 0; i < val.length; i++)
|
||||
view.setFloat32(mem.offset + i*4, val[i],true);
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
ubo_obj_to_array[prosperon.DOC] = `Construct an ArrayBuffer containing UBO data from the provided object, matching the pipeline's reflection info.
|
||||
|
||||
:param pipeline: The pipeline whose vertex reflection is read for UBO structure.
|
||||
:param name: The name suffix that identifies the target UBO in the reflection data.
|
||||
:param obj: An object whose properties match the UBO members.
|
||||
:return: An ArrayBuffer containing packed UBO data.
|
||||
`
|
||||
|
||||
function type_to_byte_count(type) {
|
||||
switch (type) {
|
||||
case 'float': return 4;
|
||||
case 'vec2': return 8;
|
||||
case 'vec3': return 12;
|
||||
case 'vec4': return 16;
|
||||
case 'mat4': return 64;
|
||||
default: throw new Error("Unknown or unsupported float-based type: " + type);
|
||||
}
|
||||
}
|
||||
|
||||
type_to_byte_count[prosperon.DOC] = `Return the byte size for known float-based types.
|
||||
|
||||
:param type: A string type identifier (e.g., 'float', 'vec2', 'vec3', 'vec4', 'mat4').
|
||||
:return: Integer number of bytes.
|
||||
`
|
||||
|
||||
var sprite_model_ubo = {
|
||||
model: unit_transform,
|
||||
color: [1,1,1,1]
|
||||
};
|
||||
|
||||
var shader_cache = {};
|
||||
var shader_times = {};
|
||||
|
||||
function make_pipeline(pipeline) {
|
||||
if (pipeline.hasOwnProperty("gpu")) return; // this pipeline has already been made
|
||||
|
||||
if (typeof pipeline.vertex === 'string')
|
||||
pipeline.vertex = make_shader(pipeline.vertex);
|
||||
if (typeof pipeline.fragment === 'string')
|
||||
pipeline.fragment = make_shader(pipeline.fragment)
|
||||
|
||||
// 1) Reflection data for vertex shader
|
||||
var refl = pipeline.vertex.reflection
|
||||
if (!refl || !refl.inputs || !Array.isArray(refl.inputs)) {
|
||||
pipeline.gpu = context.make_pipeline(pipeline);
|
||||
return;
|
||||
}
|
||||
|
||||
var inputs = refl.inputs
|
||||
var buffer_descriptions = []
|
||||
var attributes = []
|
||||
|
||||
// 2) Build buffer + attribute for each reflection input
|
||||
for (var i = 0; i < inputs.length; i++) {
|
||||
var inp = inputs[i]
|
||||
var typeStr = inp.type
|
||||
var nameStr = (inp.name || "").toUpperCase()
|
||||
var pitch = 4
|
||||
var fmt = "float1"
|
||||
|
||||
if (typeStr == "vec2") {
|
||||
pitch = 8
|
||||
fmt = "float2"
|
||||
} else if (typeStr == "vec3") {
|
||||
pitch = 12
|
||||
fmt = "float3"
|
||||
} else if (typeStr == "vec4") {
|
||||
if (nameStr.indexOf("COLOR") >= 0) {
|
||||
pitch = 16
|
||||
fmt = "color"
|
||||
} else {
|
||||
pitch = 16
|
||||
fmt = "float4"
|
||||
}
|
||||
}
|
||||
|
||||
buffer_descriptions.push({
|
||||
slot: i,
|
||||
pitch: pitch,
|
||||
input_rate: "vertex",
|
||||
instance_step_rate: 0,
|
||||
name:inp.name.split(".").pop()
|
||||
})
|
||||
|
||||
attributes.push({
|
||||
location: inp.location,
|
||||
buffer_slot: i,
|
||||
format: fmt,
|
||||
offset: 0
|
||||
})
|
||||
}
|
||||
|
||||
pipeline.vertex_buffer_descriptions = buffer_descriptions
|
||||
pipeline.vertex_attributes = attributes
|
||||
|
||||
pipeline.gpu = context.make_pipeline(pipeline);
|
||||
}
|
||||
|
||||
make_pipeline[prosperon.DOC] = `Create and store a GPU pipeline object if it has not already been created.
|
||||
|
||||
:param pipeline: An object describing the pipeline state, shaders, and reflection data.
|
||||
:return: None
|
||||
`
|
||||
|
||||
var shader_type;
|
||||
|
||||
function make_shader(sh_file) {
|
||||
var file = `shaders/${shader_type}/${sh_file}.${shader_type}`
|
||||
if (shader_cache[file]) return shader_cache[file]
|
||||
var refl = json.decode(io.slurp(`shaders/reflection/${sh_file}.json`))
|
||||
|
||||
var shader = {
|
||||
code: io.slurpbytes(file),
|
||||
format: shader_type,
|
||||
stage: sh_file.endsWith("vert") ? "vertex" : "fragment",
|
||||
num_samplers: refl.separate_samplers ? refl.separate_samplers.length : 0,
|
||||
num_textures: 0,
|
||||
num_storage_buffers: refl.separate_storage_buffers ? refl.separate_storage_buffers.length : 0,
|
||||
num_uniform_buffers: refl.ubos ? refl.ubos.length : 0,
|
||||
entrypoint: shader_type === "msl" ? "main0" : "main"
|
||||
}
|
||||
|
||||
shader.gpu = context.make_shader(shader)
|
||||
shader.reflection = refl;
|
||||
shader_cache[file] = shader
|
||||
shader.file = sh_file
|
||||
return shader
|
||||
}
|
||||
|
||||
make_shader[prosperon.DOC] = `Load and compile a shader from disk, caching the result. Reflective metadata is also loaded.
|
||||
|
||||
:param sh_file: The base filename (without extension) of the shader to compile.
|
||||
:return: A shader object with GPU and reflection data attached.
|
||||
`
|
||||
|
||||
var render_queue = [];
|
||||
var hud_queue = [];
|
||||
|
||||
var current_queue = render_queue;
|
||||
|
||||
var std_sampler = {
|
||||
min_filter: "nearest",
|
||||
mag_filter: "nearest",
|
||||
mipmap: "linear",
|
||||
u: "repeat",
|
||||
v: "repeat",
|
||||
w: "repeat",
|
||||
mip_bias: 0,
|
||||
max_anisotropy: 0,
|
||||
compare_op: "none",
|
||||
min_lod: 0,
|
||||
max_lod: 0,
|
||||
anisotropy: false,
|
||||
compare: false
|
||||
};
|
||||
|
||||
function upload_model(model) {
|
||||
var bufs = [];
|
||||
for (var i in model) {
|
||||
if (typeof model[i] !== 'object') continue;
|
||||
bufs.push(model[i]);
|
||||
}
|
||||
context.upload(this, bufs);
|
||||
}
|
||||
|
||||
upload_model[prosperon.DOC] = `Upload all buffer-like properties of the given model to the GPU.
|
||||
|
||||
:param model: An object whose buffer properties are to be uploaded.
|
||||
:return: None
|
||||
`
|
||||
|
||||
function bind_model(pass, pipeline, model) {
|
||||
var buffers = pipeline.vertex_buffer_descriptions;
|
||||
var bufs = [];
|
||||
if (buffers)
|
||||
for (var b of buffers) {
|
||||
if (b.name in model) bufs.push(model[b.name])
|
||||
else throw Error (`could not find buffer ${b.name} on model`);
|
||||
}
|
||||
pass.bind_buffers(0,bufs);
|
||||
pass.bind_index_buffer(model.indices);
|
||||
}
|
||||
|
||||
bind_model[prosperon.DOC] = `Bind the model's vertex and index buffers for the given pipeline and render pass.
|
||||
|
||||
:param pass: The current render pass.
|
||||
:param pipeline: The pipeline object with vertex buffer descriptions.
|
||||
:param model: The model object containing matching buffers and an index buffer.
|
||||
:return: None
|
||||
`
|
||||
|
||||
function bind_mat(pass, pipeline, mat) {
|
||||
var imgs = [];
|
||||
var refl = pipeline.fragment.reflection;
|
||||
if (refl.separate_images) {
|
||||
for (var i of refl.separate_images) {
|
||||
if (i.name in mat) {
|
||||
var tex = mat[i.name];
|
||||
imgs.push({texture:tex.texture, sampler:tex.sampler});
|
||||
} else
|
||||
throw Error (`could not find all necessary images: ${i.name}`)
|
||||
}
|
||||
pass.bind_samplers(false, 0,imgs);
|
||||
}
|
||||
}
|
||||
|
||||
bind_mat[prosperon.DOC] = `Bind the material images and samplers needed by the pipeline's fragment shader.
|
||||
|
||||
:param pass: The current render pass.
|
||||
:param pipeline: The pipeline whose fragment shader reflection indicates required textures.
|
||||
:param mat: An object mapping the required image names to {texture, sampler}.
|
||||
:return: None
|
||||
`
|
||||
|
||||
function group_sprites_by_texture(sprites, mesh) {
|
||||
if (sprites.length === 0) return;
|
||||
for (var i = 0; i < sprites.length; i++) {
|
||||
sprites[i].mesh = mesh;
|
||||
sprites[i].first_index = i*6;
|
||||
sprites[i].num_indices = 6;
|
||||
}
|
||||
return;
|
||||
// The code below is an alternate approach to grouping by image. Currently not in use.
|
||||
/*
|
||||
var groups = [];
|
||||
var group = {image:sprites[0].image, first_index:0};
|
||||
var count = 1;
|
||||
for (var i = 1; i < sprites.length; i++) {
|
||||
if (sprites[i].image === group.image) {
|
||||
count++;
|
||||
continue;
|
||||
}
|
||||
group.num_indices = count*6;
|
||||
var newgroup = {image:sprites[i].image, first_index:group.first_index+group.num_indices};
|
||||
group = newgroup;
|
||||
groups.push(group);
|
||||
count=1;
|
||||
}
|
||||
group.num_indices = count*6;
|
||||
return groups;
|
||||
*/
|
||||
}
|
||||
|
||||
group_sprites_by_texture[prosperon.DOC] = `Assign each sprite to the provided mesh, generating index data as needed.
|
||||
|
||||
:param sprites: An array of sprite objects.
|
||||
:param mesh: A mesh object (pos, color, uv, indices, etc.) to link to each sprite.
|
||||
:return: None
|
||||
`
|
||||
|
||||
var main_color = {
|
||||
type:"2d",
|
||||
format: "rgba8",
|
||||
layers: 1,
|
||||
mip_levels: 1,
|
||||
samples: 0,
|
||||
sampler:true,
|
||||
color_target:true
|
||||
};
|
||||
|
||||
var main_depth = {
|
||||
type: "2d",
|
||||
format: "d32 float s8",
|
||||
layers:1,
|
||||
mip_levels:1,
|
||||
samples:0,
|
||||
sampler:true,
|
||||
depth_target:true
|
||||
};
|
||||
|
||||
function render_camera(cmds, camera) {
|
||||
var pass;
|
||||
delete camera.target // TODO: HORRIBLE
|
||||
if (!camera.target) {
|
||||
main_color.width = main_depth.width = camera.size.x;
|
||||
main_color.height = main_depth.height = camera.size.y;
|
||||
camera.target = {
|
||||
color_targets: [{
|
||||
texture: context.texture(main_color),
|
||||
mip_level:0,
|
||||
layer: 0,
|
||||
load:"clear",
|
||||
store:"store",
|
||||
clear: cornflower
|
||||
}],
|
||||
depth_stencil: {
|
||||
texture: context.texture(main_depth),
|
||||
clear:1,
|
||||
load:"dont_care",
|
||||
store:"dont_care",
|
||||
stencil_load:"dont_care",
|
||||
stencil_store:"dont_care",
|
||||
stencil_clear:0
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
var buffers = [];
|
||||
buffers = buffers.concat(graphics.queue_sprite_mesh(render_queue));
|
||||
var unique_meshes = [...new Set(render_queue.map(x => x.mesh))];
|
||||
for (var q of unique_meshes)
|
||||
buffers = buffers.concat([q.pos, q.color, q.uv, q.indices]);
|
||||
|
||||
buffers = buffers.concat(graphics.queue_sprite_mesh(hud_queue));
|
||||
for (var q of hud_queue)
|
||||
if (q.type === 'geometry') buffers = buffers.concat([q.mesh.pos, q.mesh.color, q.mesh.uv, q.mesh.indices]);
|
||||
|
||||
full_upload(buffers)
|
||||
|
||||
var pass = cmds.render_pass(camera.target);
|
||||
|
||||
var pipeline = sprite_pipeline;
|
||||
bind_pipeline(pass,pipeline);
|
||||
|
||||
var camslot = get_pipeline_ubo_slot(pipeline, 'TransformBuffer');
|
||||
if (typeof camslot !== 'undefined')
|
||||
cmds.camera(camera, camslot);
|
||||
|
||||
modelslot = get_pipeline_ubo_slot(pipeline, "model");
|
||||
if (typeof modelslot !== 'undefined') {
|
||||
var ubo = ubo_obj_to_array(pipeline, 'model', sprite_model_ubo);
|
||||
cmds.push_vertex_uniform_data(modelslot, ubo);
|
||||
}
|
||||
|
||||
var mesh;
|
||||
var img;
|
||||
var modelslot;
|
||||
|
||||
cmds.push_debug_group("draw")
|
||||
for (var group of render_queue) {
|
||||
if (mesh != group.mesh) {
|
||||
mesh = group.mesh;
|
||||
bind_model(pass,pipeline,mesh);
|
||||
}
|
||||
|
||||
if (group.image && img != group.image) {
|
||||
img = group.image;
|
||||
img.sampler = std_sampler;
|
||||
bind_mat(pass,pipeline,{diffuse:img});
|
||||
}
|
||||
|
||||
pass.draw_indexed(group.num_indices, 1, group.first_index, 0, 0);
|
||||
}
|
||||
cmds.pop_debug_group()
|
||||
|
||||
cmds.push_debug_group("hud")
|
||||
var camslot = get_pipeline_ubo_slot(pipeline, 'TransformBuffer');
|
||||
if (typeof camslot !== 'undefined')
|
||||
cmds.hud(camera.size, camslot);
|
||||
|
||||
for (var group of hud_queue) {
|
||||
if (mesh != group.mesh) {
|
||||
mesh = group.mesh;
|
||||
bind_model(pass,pipeline,mesh);
|
||||
}
|
||||
|
||||
if (group.image && img != group.image) {
|
||||
img = group.image;
|
||||
img.sampler = std_sampler;
|
||||
bind_mat(pass,pipeline,{diffuse:img});
|
||||
}
|
||||
|
||||
pass.draw_indexed(group.num_indices, 1, group.first_index, 0, 0);
|
||||
}
|
||||
cmds.pop_debug_group();
|
||||
|
||||
pass?.end();
|
||||
|
||||
render_queue = [];
|
||||
hud_queue = [];
|
||||
}
|
||||
|
||||
render_camera[prosperon.DOC] = `Render a scene using the provided camera, drawing both render queue and HUD queue items.
|
||||
|
||||
:param cmds: A command buffer obtained from the GPU context.
|
||||
:param camera: The camera object (with size, optional target, etc.).
|
||||
:return: None
|
||||
`
|
||||
|
||||
var swaps = [];
|
||||
render.present = function() {
|
||||
os.clean_transforms();
|
||||
var cmds = context.acquire_cmd_buffer();
|
||||
render_camera(cmds, prosperon.camera);
|
||||
var swapchain_tex = cmds.acquire_swapchain();
|
||||
if (!swapchain_tex)
|
||||
cmds.cancel();
|
||||
else {
|
||||
var torect = prosperon.camera.draw_rect(prosperon.window.size);
|
||||
torect.texture = swapchain_tex;
|
||||
if (swapchain_tex) {
|
||||
cmds.blit({
|
||||
src: prosperon.camera.target.color_targets[0].texture,
|
||||
dst: torect,
|
||||
filter:"nearest",
|
||||
load: "clear"
|
||||
});
|
||||
|
||||
if (imgui) { // draws any imgui commands present
|
||||
cmds.push_debug_group("imgui")
|
||||
imgui.prepend(cmds);
|
||||
var pass = cmds.render_pass({
|
||||
color_targets:[{texture:swapchain_tex}]});
|
||||
imgui.endframe(cmds,pass);
|
||||
pass.end();
|
||||
cmds.pop_debug_group()
|
||||
}
|
||||
}
|
||||
cmds.submit()
|
||||
}
|
||||
}
|
||||
|
||||
render.present[prosperon.DOC] = `Perform the per-frame rendering and present the final swapchain image, including imgui pass if available.
|
||||
|
||||
:return: None
|
||||
`
|
||||
|
||||
var stencil_write = {
|
||||
compare: "always",
|
||||
fail_op: "replace",
|
||||
depth_fail_op: "replace",
|
||||
pass_op: "replace"
|
||||
};
|
||||
|
||||
function stencil_writer(ref) {
|
||||
var pipe = Object.create(base_pipeline);
|
||||
Object.assign(pipe, {
|
||||
stencil: {
|
||||
enabled: true,
|
||||
front: stencil_write,
|
||||
back: stencil_write,
|
||||
write:true,
|
||||
read:true,
|
||||
ref:ref
|
||||
},
|
||||
write_mask: colormask.none
|
||||
});
|
||||
return pipe;
|
||||
}.hashify();
|
||||
|
||||
// objects by default draw where the stencil buffer is 0
|
||||
function fillmask(ref) {
|
||||
var pipe = stencil_writer(ref);
|
||||
render.use_shader('screenfill.cg', pipe);
|
||||
render.draw(shape.quad);
|
||||
}
|
||||
|
||||
render.fillmask[prosperon.DOC] = `Draw a fullscreen shape using a 'screenfill' shader to populate the stencil buffer with a given reference.
|
||||
|
||||
:param ref: The stencil reference value to write.
|
||||
:return: None
|
||||
`
|
||||
|
||||
var stencil_invert = {
|
||||
compare: "always",
|
||||
fail_op: "invert",
|
||||
depth_fail_op: "invert",
|
||||
pass_op: "invert"
|
||||
};
|
||||
|
||||
function mask(image, pos, scale, rotation = 0, ref = 1) {
|
||||
if (typeof image === 'string')
|
||||
image = graphics.texture(image);
|
||||
|
||||
var tex = image.texture;
|
||||
if (scale) scale = scale.div([tex.width,tex.height]);
|
||||
else scale = [1,1,1]
|
||||
|
||||
var pipe = stencil_writer(ref);
|
||||
render.use_shader('sprite.cg', pipe);
|
||||
var t = os.make_transform();
|
||||
t.trs(pos, undefined, scale);
|
||||
set_model(t);
|
||||
render.use_mat({
|
||||
diffuse:image.texture,
|
||||
rect: image.rect,
|
||||
shade: Color.white
|
||||
});
|
||||
render.draw(shape.quad);
|
||||
}
|
||||
|
||||
render.mask[prosperon.DOC] = `Draw an image to the stencil buffer, marking its area with a specified reference value.
|
||||
|
||||
:param image: A texture or string path (which is converted to a texture).
|
||||
:param pos: The translation (x, y) for the image placement.
|
||||
:param scale: Optional scaling applied to the texture.
|
||||
:param rotation: Optional rotation in radians (unused by default).
|
||||
:param ref: The stencil reference value to write.
|
||||
:return: None
|
||||
`
|
||||
|
||||
render.viewport = function(rect) {
|
||||
context.viewport(rect);
|
||||
}
|
||||
|
||||
render.viewport[prosperon.DOC] = `Set the GPU viewport to the specified rectangle.
|
||||
|
||||
:param rect: A rectangle [x, y, width, height].
|
||||
:return: None
|
||||
`
|
||||
|
||||
render.scissor = function(rect) {
|
||||
render.viewport(rect)
|
||||
}
|
||||
|
||||
render.scissor[prosperon.DOC] = `Set the GPU scissor region to the specified rectangle (alias of render.viewport).
|
||||
|
||||
:param rect: A rectangle [x, y, width, height].
|
||||
:return: None
|
||||
`
|
||||
|
||||
var std_sampler
|
||||
|
||||
if (tracy) tracy.gpu_init()
|
||||
|
||||
render.queue = function(cmd) {
|
||||
if (Array.isArray(cmd))
|
||||
for (var i of cmd) current_queue.push(i)
|
||||
else
|
||||
current_queue.push(cmd)
|
||||
}
|
||||
|
||||
render.queue[prosperon.DOC] = `Enqueue one or more draw commands. These commands are batched until render_camera is called.
|
||||
|
||||
:param cmd: Either a single command object or an array of command objects.
|
||||
:return: None
|
||||
`
|
||||
|
||||
render.setup_draw = function() {
|
||||
current_queue = render_queue;
|
||||
prosperon.draw();
|
||||
}
|
||||
|
||||
render.setup_draw[prosperon.DOC] = `Switch the current queue to the primary scene render queue, then invoke 'prosperon.draw' if defined.
|
||||
|
||||
:return: None
|
||||
`
|
||||
|
||||
render.setup_hud = function() {
|
||||
current_queue = hud_queue;
|
||||
prosperon.hud();
|
||||
}
|
||||
|
||||
render.setup_hud[prosperon.DOC] = `Switch the current queue to the HUD render queue, then invoke 'prosperon.hud' if defined.
|
||||
|
||||
:return: None
|
||||
`
|
||||
|
||||
render.initialize = function(config)
|
||||
{
|
||||
var default_conf = {
|
||||
title:`Prosperon [${prosperon.version}-${prosperon.revision}]`,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
icon: graphics.make_texture(io.slurpbytes('icons/moon.gif')),
|
||||
high_dpi:0,
|
||||
alpha:1,
|
||||
fullscreen:0,
|
||||
sample_count:1,
|
||||
enable_clipboard:true,
|
||||
enable_dragndrop: true,
|
||||
max_dropped_files: 1,
|
||||
swap_interval: 1,
|
||||
name: "Prosperon",
|
||||
version:prosperon.version + "-" + prosperon.revision,
|
||||
identifier: "world.pockle.prosperon",
|
||||
creator: "Pockle World LLC",
|
||||
copyright: "Copyright Pockle World 2025",
|
||||
type: "game",
|
||||
url: "https://prosperon.dev"
|
||||
}
|
||||
|
||||
config.__proto__ = default_conf
|
||||
|
||||
prosperon.camera = use('ext/camera').make()
|
||||
prosperon.camera.size = [config.width,config.height]
|
||||
|
||||
prosperon.window = prosperon.engine_start(config)
|
||||
|
||||
context = prosperon.window.make_gpu(false,driver)
|
||||
context.window = prosperon.window
|
||||
context.claim_window(prosperon.window)
|
||||
context.set_swapchain('sdr', 'vsync')
|
||||
|
||||
if (imgui) imgui.init(context, prosperon.window)
|
||||
|
||||
shader_type = context.shader_format()[0];
|
||||
|
||||
std_sampler = context.make_sampler({
|
||||
min_filter: "nearest",
|
||||
mag_filter: "nearest",
|
||||
mipmap_mode: "nearest",
|
||||
address_mode_u: "repeat",
|
||||
address_mode_v: "repeat",
|
||||
address_mode_w: "repeat"
|
||||
});
|
||||
}
|
||||
|
||||
return render
|
||||
|
||||
122
scripts/modules/sdl_render.js
Normal file
@@ -0,0 +1,122 @@
|
||||
var render = {}
|
||||
|
||||
var context
|
||||
|
||||
var util = use('util')
|
||||
|
||||
render.initialize = function(config)
|
||||
{
|
||||
var default_conf = {
|
||||
title:`Prosperon [${prosperon.version}-${prosperon.revision}]`,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
// icon: graphics.make_texture(io.slurpbytes('icons/moon.gif')),
|
||||
high_dpi:0,
|
||||
alpha:1,
|
||||
fullscreen:0,
|
||||
sample_count:1,
|
||||
enable_clipboard:true,
|
||||
enable_dragndrop: true,
|
||||
max_dropped_files: 1,
|
||||
swap_interval: 1,
|
||||
name: "Prosperon",
|
||||
version:prosperon.version + "-" + prosperon.revision,
|
||||
identifier: "world.pockle.prosperon",
|
||||
creator: "Pockle World LLC",
|
||||
copyright: "Copyright Pockle World 2025",
|
||||
type: "game",
|
||||
url: "https://prosperon.dev"
|
||||
}
|
||||
|
||||
prosperon.window = prosperon.engine_start({width:500,height:500})
|
||||
context = prosperon.window.make_renderer("vulkan")
|
||||
}
|
||||
|
||||
render.sprite = function(sprite)
|
||||
{
|
||||
context.sprite(sprite)
|
||||
}
|
||||
|
||||
// img here is the engine surface
|
||||
render.load_texture = function(surface)
|
||||
{
|
||||
return context.load_texture(surface)
|
||||
}
|
||||
|
||||
var current_color = Color.white
|
||||
|
||||
render.image = function(image, rect, rotation, anchor, shear, info)
|
||||
{
|
||||
// rect.width = image.rect_px.width;
|
||||
// rect.height = image.rect_px.height;
|
||||
context.texture(image.texture, image.rect_px, rect, rotation, anchor);
|
||||
}
|
||||
|
||||
render.clip = function(rect)
|
||||
{
|
||||
context.clip(rect)
|
||||
}
|
||||
|
||||
render.line = function(points)
|
||||
{
|
||||
context.line(points)
|
||||
}
|
||||
|
||||
render.point = function(pos)
|
||||
{
|
||||
context.point(pos)
|
||||
}
|
||||
|
||||
render.rectangle = function(rect)
|
||||
{
|
||||
context.rects([rect])
|
||||
}
|
||||
|
||||
render.rects = function(rects)
|
||||
{
|
||||
context.rects(rects)
|
||||
}
|
||||
|
||||
render.pipeline = function(pipe)
|
||||
{
|
||||
// any changes here
|
||||
}
|
||||
|
||||
render.settings = function(set)
|
||||
{
|
||||
if (!set.color) return
|
||||
context.draw_color(set.color)
|
||||
}
|
||||
|
||||
render.geometry = function(image, mesh, pipeline)
|
||||
{
|
||||
context.geometry(image, mesh)
|
||||
}
|
||||
|
||||
render.slice9 = function(image, rect, slice, info, pipeline)
|
||||
{
|
||||
context.slice9(image.texture, image.rect_px, util.normalizeSpacing(slice), rect);
|
||||
}
|
||||
|
||||
render.get_image = function(rect)
|
||||
{
|
||||
return context.get_image(rect)
|
||||
}
|
||||
|
||||
render.clear = function(color)
|
||||
{
|
||||
if (color) context.draw_color(color)
|
||||
context.clear()
|
||||
}
|
||||
|
||||
render.present = function()
|
||||
{
|
||||
context.present()
|
||||
}
|
||||
|
||||
render.camera = function(cam)
|
||||
{
|
||||
context.camera(cam);
|
||||
}
|
||||
|
||||
return render
|
||||
@@ -16,6 +16,7 @@ audio.pcm = function pcm(file)
|
||||
file = res.find_sound(file);
|
||||
if (!file) throw new Error(`Could not findfile ${file}`);
|
||||
if (pcms[file]) return pcms[file];
|
||||
var bytes = io.slurpbytes(file)
|
||||
var newpcm = soloud.load_wav_mem(io.slurpbytes(file));
|
||||
pcms[file] = newpcm;
|
||||
return newpcm;
|
||||
@@ -73,4 +74,33 @@ audio.music = function music(file, fade = 0.5) {
|
||||
};
|
||||
audio.music[doc.sym] = `Play the given music file, with an optional cross fade. The song will loop. When this is invoked again, the previous music is replaced.`
|
||||
|
||||
var ss = use('sdl_audio')
|
||||
|
||||
var feeder = ss.open_stream("playback")
|
||||
|
||||
feeder.set_format({format:"f32", channels:2,samplerate:44100})
|
||||
|
||||
feeder.resume()
|
||||
|
||||
var FRAMES = 1024
|
||||
var CHANNELS = 2
|
||||
var BYTES_PER_F = 4
|
||||
var SAMPLES = FRAMES * CHANNELS
|
||||
var CHUNK_BYTES = FRAMES * CHANNELS * BYTES_PER_F
|
||||
|
||||
var mixview = new Float32Array(FRAMES*CHANNELS)
|
||||
var mixbuf = mixview.buffer
|
||||
|
||||
function pump()
|
||||
{
|
||||
if (feeder.queued() < CHUNK_BYTES*3) {
|
||||
var mm = soloud.mix(FRAMES)
|
||||
feeder.put(mm)
|
||||
}
|
||||
|
||||
$_.delay(pump, 1/240)
|
||||
}
|
||||
|
||||
pump()
|
||||
|
||||
return audio;
|
||||
|
||||
@@ -42,16 +42,16 @@ time.strparse = {
|
||||
s: "second",
|
||||
};
|
||||
|
||||
time.isleap = function(year) {
|
||||
time.isleap = function isleap(year) {
|
||||
return this.yearsize(year) === 366;
|
||||
};
|
||||
|
||||
time.yearsize = function(y) {
|
||||
time.yearsize = function yearsize(y) {
|
||||
if (y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0)) return 366;
|
||||
return 365;
|
||||
};
|
||||
|
||||
time.timecode = function(t, fps = 24) {
|
||||
time.timecode = function timecode(t, fps = 24) {
|
||||
var s = Math.trunc(t);
|
||||
t -= s;
|
||||
return `${s}:${Math.trunc(fps * s)}`;
|
||||
@@ -60,7 +60,7 @@ time.timecode = function(t, fps = 24) {
|
||||
time.monthdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
time.zones = { "-12": "IDLW" };
|
||||
|
||||
time.record = function(num, zone = this.computer_zone()) {
|
||||
time.record = function record(num, zone = this.computer_zone()) {
|
||||
if (typeof num === "object") {
|
||||
return num;
|
||||
} else if (typeof num === "number") {
|
||||
@@ -113,7 +113,7 @@ time.record = function(num, zone = this.computer_zone()) {
|
||||
}
|
||||
};
|
||||
|
||||
time.number = function(rec) {
|
||||
time.number = function number(rec) {
|
||||
if (typeof rec === "number") {
|
||||
return rec;
|
||||
} else if (typeof rec === "object") {
|
||||
@@ -153,7 +153,7 @@ time.number = function(rec) {
|
||||
|
||||
time.fmt = "vB mB d h:nn:ss TZz a y c";
|
||||
|
||||
time.text = function(num, fmt = this.fmt, zone) {
|
||||
time.text = function text(num, fmt = this.fmt, zone) {
|
||||
var rec = (typeof num === "number") ? time.record(num, zone) : num;
|
||||
zone = rec.zone;
|
||||
if (fmt.match("a")) {
|
||||
@@ -187,7 +187,7 @@ time.text = function(num, fmt = this.fmt, zone) {
|
||||
fmt = fmt.replaceAll("h", rec.hour);
|
||||
fmt = fmt.replaceAll("nn", rec.minute.toString().padStart(2, "0"));
|
||||
fmt = fmt.replaceAll("n", rec.minute);
|
||||
fmt = fmt.replaceAll("ss", rec.second.toString().padStart(2, "0"));
|
||||
fmt = fmt.replaceAll("ss", rec.second.toFixed(2).padStart(2, "0"));
|
||||
fmt = fmt.replaceAll("s", rec.second);
|
||||
fmt = fmt.replaceAll("z", zone >= 0 ? "+" + zone : zone);
|
||||
fmt = fmt.replaceAll(/mm[^bB]/g, rec.month + 1);
|
||||
|
||||
43
scripts/modules/wota.js
Normal file
@@ -0,0 +1,43 @@
|
||||
// wota
|
||||
var wota = this
|
||||
|
||||
var json = use('json')
|
||||
|
||||
var encode = wota.encode
|
||||
|
||||
function wota_tostring()
|
||||
{
|
||||
return json.encode(wota.decode(this))
|
||||
}
|
||||
|
||||
var wota_obj = {
|
||||
toString: wota_tostring
|
||||
}
|
||||
|
||||
wota.encode = function(obj, replacer)
|
||||
{
|
||||
var result = encode(obj, replacer)
|
||||
result.toString = wota_tostring
|
||||
return result
|
||||
}
|
||||
|
||||
wota.encode[prosperon.DOC] = `Convert a JavaScript value into a WOTA-encoded ArrayBuffer.
|
||||
|
||||
This function serializes JavaScript values (such as numbers, strings, booleans, arrays, objects, or ArrayBuffers) into the WOTA binary format. The resulting ArrayBuffer can be stored or transmitted and later decoded back into a JavaScript value.
|
||||
|
||||
:param value: The JavaScript value to encode (e.g., number, string, boolean, array, object, or ArrayBuffer).
|
||||
:param replacer: An optional function that alters the encoding behavior for specific values.
|
||||
:return: An ArrayBuffer containing the WOTA-encoded data.
|
||||
:throws: An error if no argument is provided or if a cyclic object is encountered.
|
||||
`
|
||||
|
||||
wota.decode[prosperon.DOC] = `Decode a WOTA-encoded ArrayBuffer into a JavaScript value.
|
||||
|
||||
This function deserializes a WOTA-formatted ArrayBuffer into its corresponding JavaScript representation, such as a number, string, boolean, array, object, or ArrayBuffer. If the input is invalid or empty, it returns undefined.
|
||||
|
||||
:param buffer: An ArrayBuffer containing WOTA-encoded data to decode.
|
||||
:param reviver: An optional function that transforms the decoded values.
|
||||
:return: The decoded JavaScript value (e.g., number, string, boolean, array, object, or ArrayBuffer), or undefined if no argument is provided.
|
||||
`
|
||||
|
||||
return wota
|
||||
@@ -1,34 +0,0 @@
|
||||
#include <stdlib.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "aabb.h"
|
||||
|
||||
aabb*
|
||||
aabb_new(float x, float y, float hW, float hH) {
|
||||
aabb* a = malloc(sizeof(aabb));
|
||||
a->center.x = x;
|
||||
a->center.y = y;
|
||||
a->dims.w = hW;
|
||||
a->dims.h = hH;
|
||||
return a;
|
||||
}
|
||||
|
||||
void
|
||||
aabb_free(aabb *a) {
|
||||
free(a);
|
||||
}
|
||||
|
||||
int
|
||||
aabb_contains(aabb *a, float x, float y) {
|
||||
return (x >= a->center.x-a->dims.w &&
|
||||
x <= a->center.x+a->dims.w) &&
|
||||
(y >= a->center.y-a->dims.h &&
|
||||
y <= a->center.y+a->dims.h);
|
||||
}
|
||||
|
||||
int
|
||||
aabb_intersects(aabb *a, aabb *b) {
|
||||
return (abs(a->center.x - b->center.x) < (a->dims.w + b->dims.w)) &&
|
||||
(abs(a->center.y - b->center.y) < (a->dims.h + b->dims.h));
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
/*
|
||||
aabb.h
|
||||
2014 JSK (kutani@projectkutani.com)
|
||||
|
||||
Simple (2D) axis-aligned bounding box implementation. Part of the Panic
|
||||
Panic project.
|
||||
|
||||
Released to the public domain. See LICENSE for details.
|
||||
*/
|
||||
#ifndef _AABB_H
|
||||
#define _AABB_H
|
||||
|
||||
/** \brief axis-aligned bounding box
|
||||
|
||||
Simple struct of four floats, divided into two sub-structs.
|
||||
|
||||
center {x, y} - The center point of the bounding box
|
||||
dims {w, h} - The half-width and half-height of the box
|
||||
*/
|
||||
typedef struct aabb {
|
||||
struct {
|
||||
float x;
|
||||
float y;
|
||||
} center;
|
||||
struct {
|
||||
float w;
|
||||
float h;
|
||||
} dims;
|
||||
} aabb;
|
||||
|
||||
/// Malloc's a new aabb struct
|
||||
/*!
|
||||
Mallocs a new aabb struct and sets center and dims to the passed
|
||||
x, y, hW, and hH values.
|
||||
*/
|
||||
aabb* aabb_new(float x, float y, float hW, float hH);
|
||||
|
||||
|
||||
/// Frees the passed aabb.
|
||||
void aabb_free(aabb *a);
|
||||
|
||||
/// Checks if the point x,y lies within the passed aabb
|
||||
int aabb_contains(aabb *a, float x, float y);
|
||||
|
||||
/// Checks if the two passed aabb's intersect
|
||||
int aabb_intersects(aabb *a, aabb *b);
|
||||
|
||||
#endif
|
||||
@@ -16,7 +16,10 @@ void animation_run(struct animation *anim, float now)
|
||||
|
||||
HMM_Vec4 sample_cubicspline(sampler *sampler, float t, int prev, int next)
|
||||
{
|
||||
return (HMM_Vec4)HMM_SLerp(HMM_QV4(sampler->data[prev]), t, HMM_QV4(sampler->data[next]));
|
||||
HMM_Vec4 ret;
|
||||
HMM_Quat qv = HMM_SLerp(HMM_QV4(sampler->data[prev]), t, HMM_QV4(sampler->data[next]));
|
||||
memcpy(ret.e, qv.e, sizeof(ret.e));
|
||||
return ret;
|
||||
}
|
||||
|
||||
HMM_Vec4 sample_sampler(sampler *sampler, float time)
|
||||
@@ -37,6 +40,9 @@ HMM_Vec4 sample_sampler(sampler *sampler, float time)
|
||||
float td = sampler->times[next_time]-sampler->times[previous_time];
|
||||
float t = (time - sampler->times[previous_time])/td;
|
||||
|
||||
HMM_Vec4 ret;
|
||||
HMM_Quat qv;
|
||||
|
||||
switch(sampler->type) {
|
||||
case LINEAR:
|
||||
return HMM_LerpV4(sampler->data[previous_time],time,sampler->data[next_time]);
|
||||
@@ -48,7 +54,9 @@ HMM_Vec4 sample_sampler(sampler *sampler, float time)
|
||||
return sample_cubicspline(sampler,t, previous_time, next_time);
|
||||
break;
|
||||
case SLERP:
|
||||
return (HMM_Vec4)HMM_SLerp(sampler->data[previous_time].quat, time, sampler->data[next_time].quat);
|
||||
qv = HMM_SLerp(sampler->data[previous_time].quat, time, sampler->data[next_time].quat);
|
||||
memcpy(ret.e,qv.e,sizeof(ret.e));
|
||||
return ret;
|
||||
break;
|
||||
}
|
||||
return sample_cubicspline(sampler,t, previous_time, next_time);
|
||||
|
||||
@@ -24,11 +24,12 @@
|
||||
#define STBI_NO_STDIO
|
||||
#include "stb_image.h"
|
||||
|
||||
#define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_BOX
|
||||
|
||||
#define STB_IMAGE_RESIZE_IMPLEMENTATION
|
||||
#include "stb_image_resize2.h"
|
||||
|
||||
#define STB_IMAGE_WRITE_IMPLEMENTATION
|
||||
#define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_BOX
|
||||
#include "stb_image_write.h"
|
||||
|
||||
#define PL_MPEG_IMPLEMENTATION
|
||||
|
||||
@@ -306,24 +306,7 @@ struct ase_t
|
||||
void* mem_ctx;
|
||||
};
|
||||
|
||||
#define ASEPRITE_ERROR_MAX 256
|
||||
static char aseprite_error[ASEPRITE_ERROR_MAX] = {0};
|
||||
|
||||
static const char *aseprite_GetError() {
|
||||
return aseprite_error;
|
||||
}
|
||||
|
||||
static void aseprite_clear_error() {
|
||||
aseprite_error[0] = 0;
|
||||
}
|
||||
|
||||
static void aseprite_set_error(const char *msg) {
|
||||
if (msg) {
|
||||
strncpy(aseprite_error, msg, ASEPRITE_ERROR_MAX-1);
|
||||
aseprite_error[ASEPRITE_ERROR_MAX-1] = 0;
|
||||
} else
|
||||
aseprite_error[0] = 0;
|
||||
}
|
||||
const char *aseprite_GetError(void);
|
||||
|
||||
#endif // CUTE_ASEPRITE_H
|
||||
|
||||
@@ -331,6 +314,24 @@ static void aseprite_set_error(const char *msg) {
|
||||
#ifndef CUTE_ASEPRITE_IMPLEMENTATION_ONCE
|
||||
#define CUTE_ASEPRITE_IMPLEMENTATION_ONCE
|
||||
|
||||
#define ASEPRITE_ERROR_MAX 256
|
||||
char aseprite_error[ASEPRITE_ERROR_MAX] = {0};
|
||||
|
||||
const char *aseprite_GetError(void) {
|
||||
return aseprite_error;
|
||||
}
|
||||
|
||||
void aseprite_clear_error(void) {
|
||||
aseprite_error[0] = 0;
|
||||
}
|
||||
|
||||
void aseprite_set_error(const char *msg) {
|
||||
if (msg) {
|
||||
strncpy(aseprite_error, msg, ASEPRITE_ERROR_MAX-1);
|
||||
aseprite_error[ASEPRITE_ERROR_MAX-1] = 0;
|
||||
} else
|
||||
aseprite_error[0] = 0;
|
||||
}
|
||||
|
||||
#ifndef _CRT_SECURE_NO_WARNINGS
|
||||
#define _CRT_SECURE_NO_WARNINGS
|
||||
@@ -725,7 +726,6 @@ static int s_inflate(const void* in, int in_bytes, void* out, int out_bytes, voi
|
||||
s->out_end = s->out + out_bytes;
|
||||
s->begin = (char*)out;
|
||||
|
||||
int count = 0;
|
||||
uint32_t bfinal;
|
||||
do
|
||||
{
|
||||
@@ -739,8 +739,6 @@ static int s_inflate(const void* in, int in_bytes, void* out, int out_bytes, voi
|
||||
case 2: s_dynamic(s); CUTE_ASEPRITE_CALL(s_block(s)); break;
|
||||
case 3: CUTE_ASEPRITE_CHECK(0, "Detected unknown block type within input stream.");
|
||||
}
|
||||
|
||||
++count;
|
||||
}
|
||||
while (!bfinal);
|
||||
|
||||
|
||||
@@ -15,11 +15,6 @@ void datastream_free(JSRuntime *rt,datastream *ds)
|
||||
free(ds);
|
||||
}
|
||||
|
||||
static void render_audio(plm_t *mpeg, plm_samples_t *samples, struct datastream *ds) {
|
||||
// for (int i = 0; i < samples->count * CHANNELS; i++)
|
||||
// ringpush(ds->ring, samples->interleaved[i]);
|
||||
}
|
||||
|
||||
struct datastream *ds_openvideo(void *raw, size_t rawlen)
|
||||
{
|
||||
struct datastream *ds = malloc(sizeof(*ds));
|
||||
|
||||
1744
source/dmon.h
Normal file
@@ -21,31 +21,6 @@ void font_free(JSRuntime *rt, font *f)
|
||||
free(f);
|
||||
}
|
||||
|
||||
struct sFont *MakeSDFFont(const char *fontfile, int height)
|
||||
{
|
||||
int packsize = 1024;
|
||||
struct sFont *newfont = calloc(1, sizeof(struct sFont));
|
||||
newfont->height = height;
|
||||
|
||||
char fontpath[256];
|
||||
snprintf(fontpath, 256, "fonts/%s", fontfile);
|
||||
|
||||
// unsigned char *ttf_buffer = slurp_file(fontpath, NULL);
|
||||
unsigned char *bitmap = malloc(packsize * packsize);
|
||||
|
||||
stbtt_fontinfo fontinfo;
|
||||
// if (!stbtt_InitFont(&fontinfo, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer, 0))) {
|
||||
// YughError("Failed to make font %s", fontfile);
|
||||
// }
|
||||
|
||||
for (int i = 32; i < 95; i++) {
|
||||
int w, h, xoff, yoff;
|
||||
// unsigned char *stbtt_GetGlyphSDF(&fontinfo, height, i, 1, 0, 1, &w, &h, &xoff, &yoff);
|
||||
}
|
||||
|
||||
return newfont;
|
||||
}
|
||||
|
||||
struct sFont *MakeFont(void *ttf_buffer, size_t len, int height) {
|
||||
if (!ttf_buffer)
|
||||
return NULL;
|
||||
@@ -111,29 +86,6 @@ struct sFont *MakeFont(void *ttf_buffer, size_t len, int height) {
|
||||
return newfont;
|
||||
}
|
||||
|
||||
int text_flush() {
|
||||
/* if (arrlen(text_buffer) == 0) return 0;
|
||||
|
||||
sg_range verts;
|
||||
verts.ptr = text_buffer;
|
||||
verts.size = sizeof(struct text_vert) * arrlen(text_buffer);
|
||||
if (sg_query_buffer_will_overflow(*buf, verts.size)) {
|
||||
sg_destroy_buffer(*buf);
|
||||
*buf = sg_make_buffer(&(sg_buffer_desc){
|
||||
.size = verts.size,
|
||||
.type = SG_BUFFERTYPE_STORAGEBUFFER,
|
||||
.usage = SG_USAGE_STREAM,
|
||||
.label = "text buffer"
|
||||
});
|
||||
}
|
||||
|
||||
sg_append_buffer(*buf, &verts);
|
||||
int n = arrlen(text_buffer);
|
||||
arrsetlen(text_buffer, 0);
|
||||
return n;
|
||||
*/
|
||||
}
|
||||
|
||||
void sdrawCharacter(struct text_vert **buffer, stbtt_packedchar c, HMM_Vec2 cursor, float scale, struct rgba color) {
|
||||
struct text_vert vert;
|
||||
|
||||
@@ -185,7 +137,7 @@ const char *esc_color(const char *c, struct rgba *color, struct rgba defc)
|
||||
{
|
||||
struct rgba d;
|
||||
if (!color) color = &d;
|
||||
if (*c != '\e') return c;
|
||||
if (*c != '\033') return c;
|
||||
c++;
|
||||
if (*c != '[') return c;
|
||||
c++;
|
||||
@@ -235,7 +187,7 @@ HMM_Vec2 measure_text(const char *text, font *f, float size, float letterSpacing
|
||||
continue;
|
||||
}
|
||||
|
||||
float charWidth = f->Characters[*c].advance + letterSpacing;
|
||||
float charWidth = f->Characters[(unsigned char)*c].advance + letterSpacing;
|
||||
|
||||
// Handle wrapping
|
||||
if (wrap > 0 && lineWidth + charWidth > wrap) {
|
||||
@@ -283,15 +235,13 @@ HMM_Vec2 measure_text(const char *text, font *f, float size, float letterSpacing
|
||||
}
|
||||
/* pos given in screen coordinates */
|
||||
struct text_vert *renderText(const char *text, HMM_Vec2 pos, font *f, float scale, colorf color, float wrap) {
|
||||
int wrapAtWord = 1;
|
||||
text_vert *buffer = NULL;
|
||||
int len = strlen(text);
|
||||
|
||||
HMM_Vec2 cursor = pos;
|
||||
float lineHeight = f->ascent - f->descent;
|
||||
float lineWidth = 0;
|
||||
|
||||
for (char *c = text; *c != 0; c++) {
|
||||
for (const char *c = text; *c != 0; c++) {
|
||||
if (*c == '\n') {
|
||||
cursor.x = pos.x;
|
||||
cursor.y -= lineHeight + f->linegap;
|
||||
@@ -299,7 +249,7 @@ struct text_vert *renderText(const char *text, HMM_Vec2 pos, font *f, float scal
|
||||
continue;
|
||||
}
|
||||
|
||||
struct character chara = f->Characters[*c];
|
||||
struct character chara = f->Characters[(unsigned char)*c];
|
||||
|
||||
if (wrap > 0 && lineWidth + chara.advance > wrap) {
|
||||
cursor.x = pos.x;
|
||||
|
||||
@@ -60,7 +60,4 @@ struct sFont *MakeFont(void *data, size_t len, int height);
|
||||
struct text_vert *renderText(const char *text, HMM_Vec2 pos, font *f, float scale, colorf color, float wrap);
|
||||
HMM_Vec2 measure_text(const char *text, font *f, float scale, float letterSpacing, float wrap);
|
||||
|
||||
// Flushes all letters from renderText calls into the provided buffer
|
||||
int text_flush();
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
#include "gameobject.h"
|
||||
|
||||
#include "math.h"
|
||||
#include <chipmunk/chipmunk.h>
|
||||
|
||||
#include "stb_ds.h"
|
||||
|
||||
static void velocityFn(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
|
||||
{
|
||||
/* gameobject *go = body2go(body);
|
||||
gameobject_apply(go);
|
||||
cpVect pos = cpBodyGetPosition(body);
|
||||
HMM_Vec2 g = warp_force((HMM_Vec3){pos.x, pos.y, 0}, go->warp_mask).xy;
|
||||
if (!go) {
|
||||
cpBodyUpdateVelocity(body,g.cp,damping,dt);
|
||||
return;
|
||||
}
|
||||
|
||||
// cpFloat d = isfinite(go->damping) ? go->damping : damping;
|
||||
cpFloat d = damping;
|
||||
|
||||
cpBodyUpdateVelocity(body,g.cp,d,dt*go->timescale);
|
||||
|
||||
if (isfinite(go->maxvelocity))
|
||||
cpBodySetVelocity(body, cpvclamp(cpBodyGetVelocity(body), go->maxvelocity));
|
||||
|
||||
if (isfinite(go->maxangularvelocity)) {
|
||||
float av = cpBodyGetAngularVelocity(body);
|
||||
if (fabs(av) > go->maxangularvelocity)
|
||||
cpBodySetAngularVelocity(body, copysignf(go->maxangularvelocity, av));
|
||||
}
|
||||
*/
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
#ifndef GAMEOBJECT_H
|
||||
#define GAMEOBJECT_H
|
||||
|
||||
#define dag_rm(p,c) do{\
|
||||
for (int i = arrlen(p->children)-1; i--; i >=0) {\
|
||||
if (p->children[i] == c) { \
|
||||
arrdelswap(p->children,i);\
|
||||
c->parent=NULL;\
|
||||
break;\
|
||||
}}}while(0)
|
||||
|
||||
#define dag_set(p,c) do{\
|
||||
arrpush(p->children,c);\
|
||||
if(c->parent) dag_rm(c->parent,c);\
|
||||
c->parent=p;\
|
||||
}while(0)
|
||||
|
||||
#define dag_clip(p) do{\
|
||||
if (p->parent)\
|
||||
dag_rm(p->parent,p);\
|
||||
}while(0)
|
||||
|
||||
struct gameobject {
|
||||
float damping;
|
||||
float timescale;
|
||||
float maxvelocity;
|
||||
float maxangularvelocity;
|
||||
unsigned int layer;
|
||||
unsigned int warp_mask;
|
||||
};
|
||||
|
||||
/*
|
||||
Friction uses coulomb model. When shapes collide, their friction is multiplied. Some example values:
|
||||
Steel on steel: 0.0005
|
||||
Wood on steel: 0.0012
|
||||
Wood on wood: 0.0015
|
||||
=> steel = 0.025
|
||||
=> wood = 0.04
|
||||
=> hardrubber = 0.31
|
||||
=> concrete = 0.05
|
||||
=> rubber = 0.5
|
||||
Hardrubber on steel: 0.0077
|
||||
Hardrubber on concrete: 0.015
|
||||
Rubber on concrete: 0.025
|
||||
*/
|
||||
|
||||
typedef struct gameobject gameobject;
|
||||
|
||||
#endif
|
||||
2839
source/jsffi.c
@@ -1,7 +1,8 @@
|
||||
#ifndef FFI_H
|
||||
#define FFI_H
|
||||
|
||||
#include <quickjs.h>
|
||||
void ffi_load(JSContext *js, int argc, char **argv);
|
||||
void ffi_load(JSContext *js);
|
||||
int js_print_exception(JSContext *js, JSValue v);
|
||||
|
||||
#endif
|
||||
|
||||
123
source/kim.h
Executable file
@@ -0,0 +1,123 @@
|
||||
#ifndef KIM_H
|
||||
#define KIM_H
|
||||
|
||||
// write number of runes from a kim stream int a utf8 stream
|
||||
void utf8_to_kim(const char **utf, char **kim, long long *runeout);
|
||||
|
||||
// write number of runes from a kim stream int a utf8 stream
|
||||
void kim_to_utf8(char **kim, char **utf, int runes);
|
||||
|
||||
// Return the number of runes in a utf8 string
|
||||
int utf8_count(const char *utf8);
|
||||
|
||||
#ifdef KIM_IMPLEMENTATION
|
||||
|
||||
#define KIM_CONT 0x80
|
||||
#define KIM_DATA 0x7f
|
||||
#define CONTINUE(CHAR) (CHAR>>7)
|
||||
|
||||
int decode_utf8(char **s);
|
||||
void encode_utf8(char **s, int code);
|
||||
static void encode_kim(char **s, int code);
|
||||
int decode_kim(char **s);
|
||||
|
||||
static inline int utf8_bytes(char c)
|
||||
{
|
||||
int bytes = __builtin_clz(~(c));
|
||||
if (!bytes) return 1;
|
||||
return bytes-24;
|
||||
}
|
||||
|
||||
int utf8_count(const char *utf8)
|
||||
{
|
||||
int count = 0;
|
||||
|
||||
while(*utf8) {
|
||||
count++;
|
||||
utf8 += utf8_bytes(*utf8);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
// decode and advance s, returning the character rune
|
||||
int decode_utf8(char **s) {
|
||||
int k = **s ? __builtin_clz(~(**s << 24)) : 0; // Count # of leading 1 bits.
|
||||
int mask = (1 << (8 - k)) - 1; // All 1's with k leading 0's.
|
||||
int value = **s & mask;
|
||||
for (++(*s), --k; k > 0 && **s; --k, ++(*s)) { // Note that k = #total bytes, or 0.
|
||||
value <<= 6;
|
||||
value += (**s & 0x3F);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// Write and advance s with rune in utf-8
|
||||
void encode_utf8(char **s, int rune) {
|
||||
char val[4];
|
||||
int lead_byte_max = 0x7F;
|
||||
int val_index = 0;
|
||||
while (rune > lead_byte_max) {
|
||||
val[val_index++] = (rune & 0x3F) | 0x80;
|
||||
rune >>= 6;
|
||||
lead_byte_max >>= (val_index == 1 ? 2 : 1);
|
||||
}
|
||||
val[val_index++] = (rune & lead_byte_max) | (~lead_byte_max << 1);
|
||||
while (val_index--) {
|
||||
**s = val[val_index];
|
||||
(*s)++;
|
||||
}
|
||||
}
|
||||
|
||||
// write and advance s with rune in kim
|
||||
static inline void encode_kim(char **s, int rune)
|
||||
{
|
||||
if (rune < KIM_CONT) {
|
||||
**s = 0 | (KIM_DATA & rune);
|
||||
(*s)++;
|
||||
return;
|
||||
}
|
||||
|
||||
int bits = ((32 - __builtin_clz(rune) + 6) / 7) * 7;
|
||||
|
||||
while (bits > 7) {
|
||||
bits -= 7;
|
||||
**s = KIM_CONT | (KIM_DATA & (rune >> bits));
|
||||
(*s)++;
|
||||
}
|
||||
**s = KIM_DATA & rune;
|
||||
(*s)++;
|
||||
}
|
||||
|
||||
// decode and advance s, returning the character rune
|
||||
int decode_kim(char **s)
|
||||
{
|
||||
int rune = **s & KIM_DATA;
|
||||
while (CONTINUE(**s)) {
|
||||
rune <<= 7;
|
||||
(*s)++;
|
||||
rune |= **s & KIM_DATA;
|
||||
}
|
||||
(*s)++;
|
||||
return rune;
|
||||
}
|
||||
|
||||
void utf8_to_kim(const char **utf, char **kim, long long *runeout)
|
||||
{
|
||||
const char * str = *utf;
|
||||
long long runes = 0;
|
||||
while (*str) {
|
||||
runes++;
|
||||
encode_kim(kim, decode_utf8(&str));
|
||||
}
|
||||
if (runeout) *runeout = runes;
|
||||
}
|
||||
|
||||
void kim_to_utf8(char **kim, char **utf, int runes)
|
||||
{
|
||||
for (int i = 0; i < runes; i++)
|
||||
encode_utf8(utf, decode_kim(kim));
|
||||
}
|
||||
|
||||
#endif
|
||||
#endif
|
||||
@@ -1,7 +1,6 @@
|
||||
#include "model.h"
|
||||
|
||||
#include "stb_ds.h"
|
||||
#include "gameobject.h"
|
||||
|
||||
#include "render.h"
|
||||
|
||||
@@ -18,59 +17,19 @@
|
||||
|
||||
#include "jsffi.h"
|
||||
|
||||
unsigned short pack_short_tex(float c) { return c * USHRT_MAX; }
|
||||
|
||||
SDL_GPUBuffer *texcoord_floats(float *f, int n)
|
||||
{
|
||||
unsigned short packed[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
float v = f[i];
|
||||
if (v < 0) v = 0;
|
||||
if (v > 1) v = 1;
|
||||
packed[i] = pack_short_tex(v);
|
||||
}
|
||||
|
||||
/* return sg_make_buffer(&(sg_buffer_desc){
|
||||
.data = SG_RANGE(packed),
|
||||
.label = "tex coord vert buffer",
|
||||
});*/
|
||||
return NULL;
|
||||
}
|
||||
|
||||
SDL_GPUBuffer *par_idx_buffer(uint32_t *p, int v)
|
||||
{
|
||||
uint16_t idx[v];
|
||||
for (int i = 0; i < v; i++) idx[i] = p[i];
|
||||
|
||||
/* return sg_make_buffer(&(sg_buffer_desc){
|
||||
.data = SG_RANGE(idx),
|
||||
.type = SG_BUFFERTYPE_INDEXBUFFER
|
||||
});*/
|
||||
return NULL;
|
||||
}
|
||||
|
||||
SDL_GPUBuffer *float_buffer(float *f, int v)
|
||||
{
|
||||
return NULL;
|
||||
/* return sg_make_buffer(&(sg_buffer_desc){
|
||||
.data = (sg_range){
|
||||
.ptr = f,
|
||||
.size = sizeof(*f)*v
|
||||
}
|
||||
});*/
|
||||
}
|
||||
|
||||
SDL_GPUBuffer *index_buffer(float *f, int verts)
|
||||
{
|
||||
return NULL;
|
||||
/* uint16_t idxs[verts];
|
||||
for (int i = 0; i < verts; i++)
|
||||
idxs[i] = f[i];
|
||||
|
||||
return sg_make_buffer(&(sg_buffer_desc){
|
||||
.data = SG_RANGE(idxs),
|
||||
.type = SG_BUFFERTYPE_INDEXBUFFER,
|
||||
});*/
|
||||
}
|
||||
|
||||
uint32_t pack_int10_n2(float *norm)
|
||||
@@ -87,71 +46,21 @@ uint32_t pack_int10_n2(float *norm)
|
||||
SDL_GPUBuffer *normal_floats(float *f, int n)
|
||||
{
|
||||
return float_buffer(f, n);
|
||||
/* uint32_t packed_norms[n/3];
|
||||
for (int v = 0, i = 0; v < n/3; v++, i+= 3)
|
||||
packed_norms[v] = pack_int10_n2(f+i);
|
||||
|
||||
return sg_make_buffer(&(sg_buffer_desc){
|
||||
.data = SG_RANGE(packed_norms),
|
||||
.label = "normal vert buffer",
|
||||
});*/
|
||||
}
|
||||
|
||||
SDL_GPUBuffer *ubyten_buffer(float *f, int v)
|
||||
{
|
||||
return NULL;
|
||||
/* unsigned char b[v];
|
||||
for (int i = 0; i < (v); i++)
|
||||
b[i] = f[i]*255;
|
||||
|
||||
return sg_make_buffer(&(sg_buffer_desc){.data=SG_RANGE(b)});*/
|
||||
}
|
||||
|
||||
SDL_GPUBuffer *ubyte_buffer(float *f, int v)
|
||||
{
|
||||
return NULL;
|
||||
/* unsigned char b[v];
|
||||
for (int i = 0; i < (v); i++)
|
||||
b[i] = f[i];
|
||||
|
||||
return sg_make_buffer(&(sg_buffer_desc){.data=SG_RANGE(b)});
|
||||
*/
|
||||
}
|
||||
|
||||
SDL_GPUBuffer *accessor2buffer(cgltf_accessor *a, int type)
|
||||
{
|
||||
return NULL;
|
||||
/* int n = cgltf_accessor_unpack_floats(a, NULL, 0);
|
||||
float vs[n];
|
||||
cgltf_accessor_unpack_floats(a, vs, n);
|
||||
|
||||
switch(type) {
|
||||
case MAT_POS:
|
||||
return sg_make_buffer(&(sg_buffer_desc){
|
||||
.data.ptr = vs,
|
||||
.data.size = sizeof(float)*n
|
||||
});
|
||||
case MAT_NORM:
|
||||
return normal_floats(vs,n);
|
||||
case MAT_TAN:
|
||||
return normal_floats(vs,n); // TODO: MAKE A TANGENT READER
|
||||
case MAT_COLOR:
|
||||
return ubyten_buffer(vs,n);
|
||||
case MAT_WEIGHT:
|
||||
return ubyten_buffer(vs,n);
|
||||
case MAT_BONE:
|
||||
return ubyte_buffer(vs,n);
|
||||
case MAT_UV:
|
||||
return texcoord_floats(vs,n);
|
||||
case MAT_INDEX:
|
||||
return index_buffer(vs,n);
|
||||
}
|
||||
|
||||
return sg_make_buffer(&(sg_buffer_desc) {
|
||||
.data.size = 4,
|
||||
.usage = SG_USAGE_STREAM
|
||||
});
|
||||
*/
|
||||
}
|
||||
|
||||
void packFloats(float *src, float *dest, int srcLength) {
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
|
||||
#include "HandmadeMath.h"
|
||||
#include "transform.h"
|
||||
#include "gameobject.h"
|
||||
#include "anim.h"
|
||||
#include "cgltf.h"
|
||||
|
||||
|
||||
2956
source/monocypher.c
Normal file
321
source/monocypher.h
Normal file
@@ -0,0 +1,321 @@
|
||||
// Monocypher version __git__
|
||||
//
|
||||
// This file is dual-licensed. Choose whichever licence you want from
|
||||
// the two licences listed below.
|
||||
//
|
||||
// The first licence is a regular 2-clause BSD licence. The second licence
|
||||
// is the CC-0 from Creative Commons. It is intended to release Monocypher
|
||||
// to the public domain. The BSD licence serves as a fallback option.
|
||||
//
|
||||
// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0
|
||||
//
|
||||
// ------------------------------------------------------------------------
|
||||
//
|
||||
// Copyright (c) 2017-2019, Loup Vaillant
|
||||
// All rights reserved.
|
||||
//
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// 1. Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
//
|
||||
// 2. Redistributions in binary form must reproduce the above copyright
|
||||
// notice, this list of conditions and the following disclaimer in the
|
||||
// documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
// ------------------------------------------------------------------------
|
||||
//
|
||||
// Written in 2017-2019 by Loup Vaillant
|
||||
//
|
||||
// To the extent possible under law, the author(s) have dedicated all copyright
|
||||
// and related neighboring rights to this software to the public domain
|
||||
// worldwide. This software is distributed without any warranty.
|
||||
//
|
||||
// You should have received a copy of the CC0 Public Domain Dedication along
|
||||
// with this software. If not, see
|
||||
// <https://creativecommons.org/publicdomain/zero/1.0/>
|
||||
|
||||
#ifndef MONOCYPHER_H
|
||||
#define MONOCYPHER_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef MONOCYPHER_CPP_NAMESPACE
|
||||
namespace MONOCYPHER_CPP_NAMESPACE {
|
||||
#elif defined(__cplusplus)
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// Constant time comparisons
|
||||
// -------------------------
|
||||
|
||||
// Return 0 if a and b are equal, -1 otherwise
|
||||
int crypto_verify16(const uint8_t a[16], const uint8_t b[16]);
|
||||
int crypto_verify32(const uint8_t a[32], const uint8_t b[32]);
|
||||
int crypto_verify64(const uint8_t a[64], const uint8_t b[64]);
|
||||
|
||||
|
||||
// Erase sensitive data
|
||||
// --------------------
|
||||
void crypto_wipe(void *secret, size_t size);
|
||||
|
||||
|
||||
// Authenticated encryption
|
||||
// ------------------------
|
||||
void crypto_aead_lock(uint8_t *cipher_text,
|
||||
uint8_t mac [16],
|
||||
const uint8_t key [32],
|
||||
const uint8_t nonce[24],
|
||||
const uint8_t *ad, size_t ad_size,
|
||||
const uint8_t *plain_text, size_t text_size);
|
||||
int crypto_aead_unlock(uint8_t *plain_text,
|
||||
const uint8_t mac [16],
|
||||
const uint8_t key [32],
|
||||
const uint8_t nonce[24],
|
||||
const uint8_t *ad, size_t ad_size,
|
||||
const uint8_t *cipher_text, size_t text_size);
|
||||
|
||||
// Authenticated stream
|
||||
// --------------------
|
||||
typedef struct {
|
||||
uint64_t counter;
|
||||
uint8_t key[32];
|
||||
uint8_t nonce[8];
|
||||
} crypto_aead_ctx;
|
||||
|
||||
void crypto_aead_init_x(crypto_aead_ctx *ctx,
|
||||
const uint8_t key[32], const uint8_t nonce[24]);
|
||||
void crypto_aead_init_djb(crypto_aead_ctx *ctx,
|
||||
const uint8_t key[32], const uint8_t nonce[8]);
|
||||
void crypto_aead_init_ietf(crypto_aead_ctx *ctx,
|
||||
const uint8_t key[32], const uint8_t nonce[12]);
|
||||
|
||||
void crypto_aead_write(crypto_aead_ctx *ctx,
|
||||
uint8_t *cipher_text,
|
||||
uint8_t mac[16],
|
||||
const uint8_t *ad , size_t ad_size,
|
||||
const uint8_t *plain_text, size_t text_size);
|
||||
int crypto_aead_read(crypto_aead_ctx *ctx,
|
||||
uint8_t *plain_text,
|
||||
const uint8_t mac[16],
|
||||
const uint8_t *ad , size_t ad_size,
|
||||
const uint8_t *cipher_text, size_t text_size);
|
||||
|
||||
|
||||
// General purpose hash (BLAKE2b)
|
||||
// ------------------------------
|
||||
|
||||
// Direct interface
|
||||
void crypto_blake2b(uint8_t *hash, size_t hash_size,
|
||||
const uint8_t *message, size_t message_size);
|
||||
|
||||
void crypto_blake2b_keyed(uint8_t *hash, size_t hash_size,
|
||||
const uint8_t *key, size_t key_size,
|
||||
const uint8_t *message, size_t message_size);
|
||||
|
||||
// Incremental interface
|
||||
typedef struct {
|
||||
// Do not rely on the size or contents of this type,
|
||||
// for they may change without notice.
|
||||
uint64_t hash[8];
|
||||
uint64_t input_offset[2];
|
||||
uint64_t input[16];
|
||||
size_t input_idx;
|
||||
size_t hash_size;
|
||||
} crypto_blake2b_ctx;
|
||||
|
||||
void crypto_blake2b_init(crypto_blake2b_ctx *ctx, size_t hash_size);
|
||||
void crypto_blake2b_keyed_init(crypto_blake2b_ctx *ctx, size_t hash_size,
|
||||
const uint8_t *key, size_t key_size);
|
||||
void crypto_blake2b_update(crypto_blake2b_ctx *ctx,
|
||||
const uint8_t *message, size_t message_size);
|
||||
void crypto_blake2b_final(crypto_blake2b_ctx *ctx, uint8_t *hash);
|
||||
|
||||
|
||||
// Password key derivation (Argon2)
|
||||
// --------------------------------
|
||||
#define CRYPTO_ARGON2_D 0
|
||||
#define CRYPTO_ARGON2_I 1
|
||||
#define CRYPTO_ARGON2_ID 2
|
||||
|
||||
typedef struct {
|
||||
uint32_t algorithm; // Argon2d, Argon2i, Argon2id
|
||||
uint32_t nb_blocks; // memory hardness, >= 8 * nb_lanes
|
||||
uint32_t nb_passes; // CPU hardness, >= 1 (>= 3 recommended for Argon2i)
|
||||
uint32_t nb_lanes; // parallelism level (single threaded anyway)
|
||||
} crypto_argon2_config;
|
||||
|
||||
typedef struct {
|
||||
const uint8_t *pass;
|
||||
const uint8_t *salt;
|
||||
uint32_t pass_size;
|
||||
uint32_t salt_size; // 16 bytes recommended
|
||||
} crypto_argon2_inputs;
|
||||
|
||||
typedef struct {
|
||||
const uint8_t *key; // may be NULL if no key
|
||||
const uint8_t *ad; // may be NULL if no additional data
|
||||
uint32_t key_size; // 0 if no key (32 bytes recommended otherwise)
|
||||
uint32_t ad_size; // 0 if no additional data
|
||||
} crypto_argon2_extras;
|
||||
|
||||
extern const crypto_argon2_extras crypto_argon2_no_extras;
|
||||
|
||||
void crypto_argon2(uint8_t *hash, uint32_t hash_size, void *work_area,
|
||||
crypto_argon2_config config,
|
||||
crypto_argon2_inputs inputs,
|
||||
crypto_argon2_extras extras);
|
||||
|
||||
|
||||
// Key exchange (X-25519)
|
||||
// ----------------------
|
||||
|
||||
// Shared secrets are not quite random.
|
||||
// Hash them to derive an actual shared key.
|
||||
void crypto_x25519_public_key(uint8_t public_key[32],
|
||||
const uint8_t secret_key[32]);
|
||||
void crypto_x25519(uint8_t raw_shared_secret[32],
|
||||
const uint8_t your_secret_key [32],
|
||||
const uint8_t their_public_key [32]);
|
||||
|
||||
// Conversion to EdDSA
|
||||
void crypto_x25519_to_eddsa(uint8_t eddsa[32], const uint8_t x25519[32]);
|
||||
|
||||
// scalar "division"
|
||||
// Used for OPRF. Be aware that exponential blinding is less secure
|
||||
// than Diffie-Hellman key exchange.
|
||||
void crypto_x25519_inverse(uint8_t blind_salt [32],
|
||||
const uint8_t private_key[32],
|
||||
const uint8_t curve_point[32]);
|
||||
|
||||
// "Dirty" versions of x25519_public_key().
|
||||
// Use with crypto_elligator_rev().
|
||||
// Leaks 3 bits of the private key.
|
||||
void crypto_x25519_dirty_small(uint8_t pk[32], const uint8_t sk[32]);
|
||||
void crypto_x25519_dirty_fast (uint8_t pk[32], const uint8_t sk[32]);
|
||||
|
||||
|
||||
// Signatures
|
||||
// ----------
|
||||
|
||||
// EdDSA with curve25519 + BLAKE2b
|
||||
void crypto_eddsa_key_pair(uint8_t secret_key[64],
|
||||
uint8_t public_key[32],
|
||||
uint8_t seed[32]);
|
||||
void crypto_eddsa_sign(uint8_t signature [64],
|
||||
const uint8_t secret_key[64],
|
||||
const uint8_t *message, size_t message_size);
|
||||
int crypto_eddsa_check(const uint8_t signature [64],
|
||||
const uint8_t public_key[32],
|
||||
const uint8_t *message, size_t message_size);
|
||||
|
||||
// Conversion to X25519
|
||||
void crypto_eddsa_to_x25519(uint8_t x25519[32], const uint8_t eddsa[32]);
|
||||
|
||||
// EdDSA building blocks
|
||||
void crypto_eddsa_trim_scalar(uint8_t out[32], const uint8_t in[32]);
|
||||
void crypto_eddsa_reduce(uint8_t reduced[32], const uint8_t expanded[64]);
|
||||
void crypto_eddsa_mul_add(uint8_t r[32],
|
||||
const uint8_t a[32],
|
||||
const uint8_t b[32],
|
||||
const uint8_t c[32]);
|
||||
void crypto_eddsa_scalarbase(uint8_t point[32], const uint8_t scalar[32]);
|
||||
int crypto_eddsa_check_equation(const uint8_t signature[64],
|
||||
const uint8_t public_key[32],
|
||||
const uint8_t h_ram[32]);
|
||||
|
||||
|
||||
// Chacha20
|
||||
// --------
|
||||
|
||||
// Specialised hash.
|
||||
// Used to hash X25519 shared secrets.
|
||||
void crypto_chacha20_h(uint8_t out[32],
|
||||
const uint8_t key[32],
|
||||
const uint8_t in [16]);
|
||||
|
||||
// Unauthenticated stream cipher.
|
||||
// Don't forget to add authentication.
|
||||
uint64_t crypto_chacha20_djb(uint8_t *cipher_text,
|
||||
const uint8_t *plain_text,
|
||||
size_t text_size,
|
||||
const uint8_t key[32],
|
||||
const uint8_t nonce[8],
|
||||
uint64_t ctr);
|
||||
uint32_t crypto_chacha20_ietf(uint8_t *cipher_text,
|
||||
const uint8_t *plain_text,
|
||||
size_t text_size,
|
||||
const uint8_t key[32],
|
||||
const uint8_t nonce[12],
|
||||
uint32_t ctr);
|
||||
uint64_t crypto_chacha20_x(uint8_t *cipher_text,
|
||||
const uint8_t *plain_text,
|
||||
size_t text_size,
|
||||
const uint8_t key[32],
|
||||
const uint8_t nonce[24],
|
||||
uint64_t ctr);
|
||||
|
||||
|
||||
// Poly 1305
|
||||
// ---------
|
||||
|
||||
// This is a *one time* authenticator.
|
||||
// Disclosing the mac reveals the key.
|
||||
// See crypto_lock() on how to use it properly.
|
||||
|
||||
// Direct interface
|
||||
void crypto_poly1305(uint8_t mac[16],
|
||||
const uint8_t *message, size_t message_size,
|
||||
const uint8_t key[32]);
|
||||
|
||||
// Incremental interface
|
||||
typedef struct {
|
||||
// Do not rely on the size or contents of this type,
|
||||
// for they may change without notice.
|
||||
uint8_t c[16]; // chunk of the message
|
||||
size_t c_idx; // How many bytes are there in the chunk.
|
||||
uint32_t r [4]; // constant multiplier (from the secret key)
|
||||
uint32_t pad[4]; // random number added at the end (from the secret key)
|
||||
uint32_t h [5]; // accumulated hash
|
||||
} crypto_poly1305_ctx;
|
||||
|
||||
void crypto_poly1305_init (crypto_poly1305_ctx *ctx, const uint8_t key[32]);
|
||||
void crypto_poly1305_update(crypto_poly1305_ctx *ctx,
|
||||
const uint8_t *message, size_t message_size);
|
||||
void crypto_poly1305_final (crypto_poly1305_ctx *ctx, uint8_t mac[16]);
|
||||
|
||||
|
||||
// Elligator 2
|
||||
// -----------
|
||||
|
||||
// Elligator mappings proper
|
||||
void crypto_elligator_map(uint8_t curve [32], const uint8_t hidden[32]);
|
||||
int crypto_elligator_rev(uint8_t hidden[32], const uint8_t curve [32],
|
||||
uint8_t tweak);
|
||||
|
||||
// Easy to use key pair generation
|
||||
void crypto_elligator_key_pair(uint8_t hidden[32], uint8_t secret_key[32],
|
||||
uint8_t seed[32]);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // MONOCYPHER_H
|
||||
632
source/nota.h
Executable file
@@ -0,0 +1,632 @@
|
||||
#ifndef NOTA_H
|
||||
#define NOTA_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* Nota type nibble values */
|
||||
#define NOTA_BLOB 0x00
|
||||
#define NOTA_TEXT 0x10
|
||||
#define NOTA_ARR 0x20
|
||||
#define NOTA_REC 0x30
|
||||
#define NOTA_FLOAT 0x40
|
||||
#define NOTA_INT 0x60
|
||||
#define NOTA_SYM 0x70
|
||||
|
||||
#define NOTA_NULL 0x00
|
||||
#define NOTA_FALSE 0x02
|
||||
#define NOTA_TRUE 0x03
|
||||
#define NOTA_INF 0x03
|
||||
#define NOTA_PRIVATE 0x08
|
||||
#define NOTA_SYSTEM 0x09
|
||||
|
||||
/* Some internal constants/macros (used in varint logic, etc.) */
|
||||
#define NOTA_CONT 0x80
|
||||
#define NOTA_DATA 0x7f
|
||||
#define NOTA_INT_DATA 0x07
|
||||
#define NOTA_INT_SIGN(CHAR) (CHAR & (1<<3))
|
||||
#define NOTA_SIG_SIGN(CHAR) (CHAR & (1<<3))
|
||||
#define NOTA_EXP_SIGN(CHAR) (CHAR & (1<<4))
|
||||
#define NOTA_TYPE 0x70
|
||||
#define NOTA_HEAD_DATA 0x0f
|
||||
#define CONTINUE(CHAR) (CHAR>>7)
|
||||
#define UTF8_DATA 0x3f
|
||||
|
||||
/* A helper to get the high-level Nota type nibble from a byte */
|
||||
static inline int nota_type(const char *nota) { return (*nota) & 0x70; }
|
||||
|
||||
char *nota_read_blob(long long *len, char **blob, char *nota);
|
||||
char *nota_read_text(char **text, char *nota);
|
||||
char *nota_read_array(long long *len, char *nota);
|
||||
char *nota_read_record(long long *len, char *nota);
|
||||
char *nota_read_float(double *d, char *nota);
|
||||
char *nota_read_int(long long *n, char *nota);
|
||||
char *nota_read_sym(int *sym, char *nota);
|
||||
|
||||
typedef struct NotaBuffer {
|
||||
char *data;
|
||||
size_t size; /* number of bytes used */
|
||||
size_t capacity; /* allocated size of data */
|
||||
} NotaBuffer;
|
||||
|
||||
/* Initialize a NotaBuffer with a given initial capacity. */
|
||||
void nota_buffer_init(NotaBuffer *nb, size_t initial_capacity);
|
||||
|
||||
/* Free the buffer's internal memory. (Does NOT free nb itself.) */
|
||||
void nota_buffer_free(NotaBuffer *nb);
|
||||
|
||||
void nota_write_blob (NotaBuffer *nb, unsigned long long nbits, const char *data);
|
||||
void nota_write_text (NotaBuffer *nb, const char *s);
|
||||
void nota_write_array (NotaBuffer *nb, unsigned long long count);
|
||||
void nota_write_record(NotaBuffer *nb, unsigned long long count);
|
||||
void nota_write_number(NotaBuffer *nb, double n);
|
||||
void nota_write_sym (NotaBuffer *nb, int sym);
|
||||
|
||||
#ifdef NOTA_IMPLEMENTATION
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <math.h>
|
||||
#include <limits.h>
|
||||
|
||||
#include "kim.h"
|
||||
|
||||
/* -------------------------------------------------------
|
||||
HELPER: skip a varint
|
||||
------------------------------------------------------- */
|
||||
static inline char *nota_skip(char *nota)
|
||||
{
|
||||
while (CONTINUE(*nota)) {
|
||||
nota++;
|
||||
}
|
||||
return nota + 1;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------
|
||||
HELPER: read a varint
|
||||
------------------------------------------------------- */
|
||||
char *nota_read_num(long long *n, char *nota)
|
||||
{
|
||||
if (!n) {
|
||||
return nota_skip(nota);
|
||||
}
|
||||
unsigned char b = (unsigned char)*nota;
|
||||
long long result = b & NOTA_HEAD_DATA;
|
||||
nota++;
|
||||
|
||||
while (b & NOTA_CONT) {
|
||||
b = (unsigned char)*nota++;
|
||||
result = (result << 7) | (b & NOTA_DATA);
|
||||
}
|
||||
|
||||
*n = result;
|
||||
return nota;
|
||||
}
|
||||
|
||||
/* Count how many bits of varint we need to encode n,
|
||||
with sb “special bits” in the first byte. */
|
||||
static inline int nota_bits(long long n, int sb)
|
||||
{
|
||||
if (n == 0) return sb;
|
||||
int bits = (sizeof(n)*CHAR_BIT) - __builtin_clzll(n);
|
||||
bits -= sb;
|
||||
int needed = ((bits + 6) / 7)*7 + sb;
|
||||
return needed;
|
||||
}
|
||||
|
||||
/* Write a varint into *nota, with sb bits in the first char (which is already set). */
|
||||
static inline char *nota_continue_num(long long n, char *nota, int sb)
|
||||
{
|
||||
int bits = nota_bits(n, sb);
|
||||
bits -= sb;
|
||||
|
||||
if (bits > 0)
|
||||
nota[0] |= NOTA_CONT;
|
||||
else
|
||||
nota[0] &= ~NOTA_CONT;
|
||||
|
||||
int shex = (~0) << sb;
|
||||
nota[0] &= shex; /* clear sb bits */
|
||||
nota[0] |= (~shex) & ((unsigned long long)n >> bits);
|
||||
|
||||
int i = 1;
|
||||
while (bits > 0) {
|
||||
bits -= 7;
|
||||
int head = (bits == 0) ? 0 : NOTA_CONT;
|
||||
nota[i] = head | (NOTA_DATA & (n >> bits));
|
||||
i++;
|
||||
}
|
||||
|
||||
return ¬a[i];
|
||||
}
|
||||
|
||||
char *nota_read_blob(long long *len, char **blob, char *nota)
|
||||
{
|
||||
if (!len) return nota;
|
||||
nota = nota_read_num(len, nota);
|
||||
int bytes = (int)floor((*len + 7) / 8.0);
|
||||
*len = bytes;
|
||||
*blob = (char *)malloc(bytes);
|
||||
memcpy(*blob, nota, bytes);
|
||||
return nota + bytes;
|
||||
}
|
||||
|
||||
char *nota_read_text(char **text, char *nota)
|
||||
{
|
||||
long long chars;
|
||||
nota = nota_read_num(&chars, nota);
|
||||
|
||||
char utf[chars*4 + 1]; /* enough for wide chars + null */
|
||||
char *pp = utf;
|
||||
kim_to_utf8(¬a, &pp, chars);
|
||||
*pp = 0;
|
||||
*text = strdup(utf);
|
||||
return nota;
|
||||
}
|
||||
|
||||
char *nota_read_array(long long *len, char *nota)
|
||||
{
|
||||
if (!len) return nota;
|
||||
return nota_read_num(len, nota);
|
||||
}
|
||||
|
||||
char *nota_read_record(long long *len, char *nota)
|
||||
{
|
||||
if (!len) return nota;
|
||||
return nota_read_num(len, nota);
|
||||
}
|
||||
|
||||
char *nota_read_float(double *d, char *nota)
|
||||
{
|
||||
if (!d) {
|
||||
return nota_skip(nota);
|
||||
}
|
||||
|
||||
int neg = NOTA_SIG_SIGN(*nota);
|
||||
int esign = NOTA_EXP_SIGN(*nota);
|
||||
|
||||
long long e = (*nota) & NOTA_INT_DATA;
|
||||
while (CONTINUE(*nota)) {
|
||||
nota++;
|
||||
e = (e << 7) | ((*nota) & NOTA_DATA);
|
||||
}
|
||||
nota++;
|
||||
|
||||
long long sig = (*nota) & NOTA_DATA;
|
||||
while (CONTINUE(*nota)) {
|
||||
nota++;
|
||||
sig = (sig << 7) | ((*nota) & NOTA_DATA);
|
||||
}
|
||||
nota++;
|
||||
|
||||
if (neg) sig = -sig;
|
||||
if (esign) e = -e;
|
||||
|
||||
*d = (double)sig * pow(10.0, (double)e);
|
||||
return nota;
|
||||
}
|
||||
|
||||
char *nota_read_int(long long *n, char *nota)
|
||||
{
|
||||
if (!n) return nota_skip(nota);
|
||||
|
||||
*n = 0;
|
||||
char *c = nota;
|
||||
*n |= (*c) & NOTA_INT_DATA;
|
||||
while (CONTINUE(*(c++))) {
|
||||
*n = (*n << 7) | (*c & NOTA_DATA);
|
||||
}
|
||||
|
||||
/* if sign bit is set in the first byte, negative. */
|
||||
if (NOTA_INT_SIGN(*nota)) *n = -*n;
|
||||
|
||||
return c;
|
||||
}
|
||||
|
||||
char *nota_read_sym(int *sym, char *nota)
|
||||
{
|
||||
if (sym) *sym = ((*nota) & 0x0f);
|
||||
return nota + 1;
|
||||
}
|
||||
|
||||
static void nota_buffer_grow(NotaBuffer *nb, size_t min_add)
|
||||
{
|
||||
size_t needed = nb->size + min_add;
|
||||
if (needed <= nb->capacity) return;
|
||||
|
||||
size_t new_cap = (nb->capacity == 0 ? 64 : nb->capacity * 2);
|
||||
while (new_cap < needed) {
|
||||
new_cap *= 2;
|
||||
}
|
||||
char *new_data = (char *)realloc(nb->data, new_cap);
|
||||
if (!new_data) {
|
||||
fprintf(stderr, "realloc failed in nota_buffer_grow\n");
|
||||
abort();
|
||||
}
|
||||
nb->data = new_data;
|
||||
nb->capacity = new_cap;
|
||||
}
|
||||
|
||||
void nota_buffer_init(NotaBuffer *nb, size_t initial_capacity)
|
||||
{
|
||||
nb->data = NULL;
|
||||
nb->size = 0;
|
||||
nb->capacity = 0;
|
||||
if (initial_capacity > 0) {
|
||||
nb->data = (char *)malloc(initial_capacity);
|
||||
if (!nb->data) {
|
||||
fprintf(stderr, "malloc failed in nota_buffer_init\n");
|
||||
abort();
|
||||
}
|
||||
nb->capacity = initial_capacity;
|
||||
}
|
||||
}
|
||||
|
||||
void nota_buffer_free(NotaBuffer *nb)
|
||||
{
|
||||
if (nb->data) free(nb->data);
|
||||
nb->data = NULL;
|
||||
nb->size = 0;
|
||||
nb->capacity = 0;
|
||||
}
|
||||
|
||||
/* Allocate 'len' bytes in the buffer and return a pointer to them. */
|
||||
static char *nota_buffer_alloc(NotaBuffer *nb, size_t len)
|
||||
{
|
||||
nota_buffer_grow(nb, len);
|
||||
char *p = nb->data + nb->size;
|
||||
nb->size += len;
|
||||
return p;
|
||||
}
|
||||
|
||||
static void nota_write_int_buf(NotaBuffer *nb, long long n);
|
||||
static void nota_write_float_buf(NotaBuffer *nb, double d);
|
||||
|
||||
static void nota_write_int_or_float_buf(NotaBuffer *nb, double n)
|
||||
{
|
||||
if (n < (double)INT64_MIN || n > (double)INT64_MAX) {
|
||||
nota_write_float_buf(nb, n);
|
||||
return;
|
||||
}
|
||||
|
||||
double ip;
|
||||
double frac = modf(n, &ip);
|
||||
if (fabs(frac) < 1e-14)
|
||||
nota_write_int_buf(nb, (long long)ip);
|
||||
else
|
||||
nota_write_float_buf(nb, n);
|
||||
}
|
||||
|
||||
void nota_write_sym(NotaBuffer *nb, int sym)
|
||||
{
|
||||
char *p = nota_buffer_alloc(nb, 1);
|
||||
*p = NOTA_SYM | (sym & 0x0f);
|
||||
}
|
||||
|
||||
void nota_write_blob(NotaBuffer *nb, unsigned long long nbits, const char *data)
|
||||
{
|
||||
unsigned long long bytes_len = (nbits + 7ULL) >> 3;
|
||||
|
||||
char *p = nota_buffer_alloc(nb, 1 + 10 + bytes_len);
|
||||
p[0] = NOTA_BLOB;
|
||||
char *end = nota_continue_num(nbits, p, 4);
|
||||
|
||||
size_t varint_used = (size_t)(end - p - 1);
|
||||
|
||||
memcpy(end, data, (size_t)bytes_len);
|
||||
size_t total_used = 1 + varint_used + bytes_len;
|
||||
size_t allocated = 1 + 10 + bytes_len;
|
||||
|
||||
nb->size -= (allocated - total_used);
|
||||
}
|
||||
|
||||
void nota_write_text(NotaBuffer *nb, const char *s)
|
||||
{
|
||||
long long runes = utf8_count(s);
|
||||
|
||||
size_t max_kim = (size_t)(runes * 5);
|
||||
char *p = nota_buffer_alloc(nb, 1 + 10 + max_kim);
|
||||
|
||||
p[0] = NOTA_TEXT;
|
||||
char *end = nota_continue_num(runes, p, 4);
|
||||
|
||||
char *kim_out = end;
|
||||
const char *utf_in = s;
|
||||
while (*utf_in) {
|
||||
int codepoint = decode_utf8((char **)&utf_in);
|
||||
encode_kim(&kim_out, codepoint);
|
||||
}
|
||||
|
||||
size_t used = (size_t)(kim_out - p);
|
||||
size_t allocated = 1 + 10 + max_kim;
|
||||
|
||||
nb->size -= (allocated - used);
|
||||
}
|
||||
|
||||
void nota_write_array(NotaBuffer *nb, unsigned long long count)
|
||||
{
|
||||
char *p = nota_buffer_alloc(nb, 10);
|
||||
p[0] = NOTA_ARR;
|
||||
char *end = nota_continue_num(count, p, 4);
|
||||
size_t used = (size_t)(end - p);
|
||||
nb->size -= (10 - used);
|
||||
}
|
||||
|
||||
void nota_write_record(NotaBuffer *nb, unsigned long long count)
|
||||
{
|
||||
char *p = nota_buffer_alloc(nb, 10);
|
||||
p[0] = NOTA_REC;
|
||||
char *end = nota_continue_num(count, p, 4);
|
||||
size_t used = (size_t)(end - p);
|
||||
nb->size -= (10 - used);
|
||||
}
|
||||
|
||||
void nota_write_number_str(NotaBuffer *nb, const char *str)
|
||||
{
|
||||
/* -------------------------------------------
|
||||
1) Parse sign
|
||||
------------------------------------------- */
|
||||
int negative = 0;
|
||||
if (*str == '+') {
|
||||
str++;
|
||||
}
|
||||
else if (*str == '-') {
|
||||
negative = 1;
|
||||
str++;
|
||||
}
|
||||
|
||||
/* -------------------------------------------
|
||||
2) Parse integer part
|
||||
------------------------------------------- */
|
||||
long long coefficient = 0;
|
||||
int got_digits = 0;
|
||||
|
||||
while (*str >= '0' && *str <= '9') {
|
||||
got_digits = 1;
|
||||
int d = (*str - '0');
|
||||
str++;
|
||||
|
||||
// Basic overflow check (very naive):
|
||||
if (coefficient <= (LLONG_MAX - d) / 10) {
|
||||
coefficient = coefficient * 10 + d;
|
||||
} else {
|
||||
// If you want to handle overflow by switching to float, do that here.
|
||||
// For simplicity, let's just keep wrapping. In production, be careful!
|
||||
coefficient = coefficient * 10 + d;
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------
|
||||
3) Check for decimal part
|
||||
------------------------------------------- */
|
||||
int has_decimal_point = 0;
|
||||
int fraction_digits = 0;
|
||||
|
||||
if (*str == '.') {
|
||||
has_decimal_point = 1;
|
||||
str++;
|
||||
while (*str >= '0' && *str <= '9') {
|
||||
got_digits = 1;
|
||||
int d = (*str - '0');
|
||||
str++;
|
||||
fraction_digits++;
|
||||
if (coefficient <= (LLONG_MAX - d) / 10) {
|
||||
coefficient = coefficient * 10 + d;
|
||||
} else {
|
||||
// Same naive overflow comment
|
||||
coefficient = coefficient * 10 + d;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------
|
||||
4) Check for exponent part
|
||||
------------------------------------------- */
|
||||
int exponent_negative = 0;
|
||||
long long exponent_val = 0;
|
||||
|
||||
if (*str == 'e' || *str == 'E') {
|
||||
str++;
|
||||
if (*str == '+') {
|
||||
str++;
|
||||
}
|
||||
else if (*str == '-') {
|
||||
exponent_negative = 1;
|
||||
str++;
|
||||
}
|
||||
while (*str >= '0' && *str <= '9') {
|
||||
int d = (*str - '0');
|
||||
str++;
|
||||
if (exponent_val <= (LLONG_MAX - d) / 10) {
|
||||
exponent_val = exponent_val * 10 + d;
|
||||
} else {
|
||||
// Again, naive overflow handling
|
||||
exponent_val = exponent_val * 10 + d;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------
|
||||
5) If there were no valid digits at all,
|
||||
store 0 and return. (simple fallback)
|
||||
------------------------------------------- */
|
||||
if (!got_digits) {
|
||||
nota_write_int_buf(nb, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
/* -------------------------------------------
|
||||
6) Combine fraction digits into exponent
|
||||
final_exponent = exponent_val - fraction_digits
|
||||
(apply exponent sign if any)
|
||||
------------------------------------------- */
|
||||
if (exponent_negative) {
|
||||
exponent_val = -exponent_val;
|
||||
}
|
||||
long long final_exponent = exponent_val - fraction_digits;
|
||||
|
||||
/* -------------------------------------------
|
||||
7) Decide if we are storing an integer
|
||||
or a float in Nota format.
|
||||
-------------------------------------------
|
||||
Rule used here:
|
||||
- If there's no decimal point AND final_exponent == 0,
|
||||
=> integer
|
||||
- If we do have a decimal point, but fraction_digits == 0
|
||||
and exponent_val == 0, then the user typed something
|
||||
like "123." or "100.0". That is effectively an integer,
|
||||
so store it as an integer if you want a purely numeric approach.
|
||||
- Otherwise store as float.
|
||||
------------------------------------------- */
|
||||
|
||||
// If "no decimal" => definitely integer:
|
||||
// or decimal present but fraction_digits=0 & exponent_val=0 => integer
|
||||
int treat_as_integer = 0;
|
||||
if (!has_decimal_point && final_exponent == 0) {
|
||||
treat_as_integer = 1;
|
||||
}
|
||||
else if (has_decimal_point && fraction_digits == 0 && exponent_val == 0) {
|
||||
// Means "123." or "123.0"
|
||||
treat_as_integer = 1;
|
||||
}
|
||||
|
||||
if (treat_as_integer) {
|
||||
// If negative => flip the sign in the stored value
|
||||
if (negative) {
|
||||
coefficient = -coefficient;
|
||||
}
|
||||
// Write the integer in Nota format (varint with sign bit)
|
||||
nota_write_int_buf(nb, coefficient);
|
||||
return;
|
||||
}
|
||||
|
||||
/* -------------------------------------------
|
||||
8) Write as float in Nota format
|
||||
We do basically the same approach as
|
||||
nota_write_float_buf does:
|
||||
- NOTA_FLOAT nibble
|
||||
- sign bit if negative
|
||||
- exponent sign bit if final_exponent < 0
|
||||
- varint of |final_exponent|
|
||||
- varint of |coefficient|
|
||||
------------------------------------------- */
|
||||
{
|
||||
char *p = nota_buffer_alloc(nb, 21); // Up to ~21 bytes worst-case
|
||||
p[0] = NOTA_FLOAT;
|
||||
if (negative) {
|
||||
p[0] |= (1 << 3); // Mantissa sign bit
|
||||
}
|
||||
if (final_exponent < 0) {
|
||||
p[0] |= (1 << 4); // Exponent sign bit
|
||||
final_exponent = -final_exponent;
|
||||
}
|
||||
// Write exponent as varint (with 3 bits used in the first byte)
|
||||
char *c = nota_continue_num(final_exponent, p, 3);
|
||||
// Write the absolute coefficient (7 bits used in the first byte)
|
||||
char *end = nota_continue_num(coefficient, c, 7);
|
||||
|
||||
// Adjust the buffer size to the actual used length
|
||||
size_t used = (size_t)(end - p);
|
||||
nb->size -= (21 - used);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void nota_write_number(NotaBuffer *nb, double n)
|
||||
{
|
||||
nota_write_int_or_float_buf(nb, n);
|
||||
}
|
||||
|
||||
/* Write an integer in varint form (with sign bit) */
|
||||
static void nota_write_int_buf(NotaBuffer *nb, long long n)
|
||||
{
|
||||
/* up to ~10 bytes for varint */
|
||||
char *p = nota_buffer_alloc(nb, 10);
|
||||
char sign = 0;
|
||||
if (n < 0) {
|
||||
sign = 0x08; /* sign bit in the nibble */
|
||||
n = -n;
|
||||
}
|
||||
p[0] = NOTA_INT | sign;
|
||||
char *end = nota_continue_num(n, p, 3);
|
||||
size_t used = (size_t)(end - p);
|
||||
nb->size -= (10 - used);
|
||||
}
|
||||
|
||||
static void extract_mantissa_coefficient(double num, long *coefficient, long *exponent)
|
||||
{
|
||||
if (num == 0.0) {
|
||||
*coefficient = 0;
|
||||
*exponent = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
/* Round to 12 decimal places to avoid floating artifacts. */
|
||||
double rounded = floor(fabs(num) * 1e12 + 0.5) / 1e12;
|
||||
if (num < 0) {
|
||||
rounded = -rounded;
|
||||
}
|
||||
|
||||
char buf[64];
|
||||
snprintf(buf, sizeof(buf), "%.14g", rounded);
|
||||
|
||||
char *exp_pos = strpbrk(buf, "eE");
|
||||
long exp_from_sci = 0;
|
||||
if (exp_pos) {
|
||||
exp_from_sci = atol(exp_pos + 1);
|
||||
*exp_pos = '\0';
|
||||
}
|
||||
|
||||
char *dec_point = strchr(buf, '.');
|
||||
int digits_after_decimal = 0;
|
||||
if (dec_point) {
|
||||
digits_after_decimal = (int)strlen(dec_point + 1);
|
||||
memmove(dec_point, dec_point + 1, strlen(dec_point));
|
||||
}
|
||||
|
||||
long long coeff_ll = atoll(buf);
|
||||
*coefficient = (long)coeff_ll;
|
||||
*exponent = exp_from_sci - digits_after_decimal;
|
||||
}
|
||||
|
||||
static void nota_write_float_buf(NotaBuffer *nb, double d)
|
||||
{
|
||||
if (d == 0.0) {
|
||||
nota_write_int_buf(nb, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
long coef, exp;
|
||||
extract_mantissa_coefficient(d, &coef, &exp);
|
||||
|
||||
if (coef == 0) {
|
||||
nota_write_int_buf(nb, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
int neg = (d < 0.0);
|
||||
if (exp == 0) {
|
||||
nota_write_int_buf(nb, neg ? -coef : coef);
|
||||
return;
|
||||
}
|
||||
|
||||
char *p = nota_buffer_alloc(nb, 21);
|
||||
|
||||
p[0] = NOTA_FLOAT;
|
||||
if (neg) p[0] |= (1 << 3);
|
||||
if (exp < 0) {
|
||||
p[0] |= (1 << 4);
|
||||
exp = -exp;
|
||||
}
|
||||
|
||||
char *c = nota_continue_num(exp, p, 3);
|
||||
char *end = nota_continue_num(labs(coef), c, 7);
|
||||
|
||||
size_t used = (size_t)(end - p);
|
||||
nb->size -= (21 - used);
|
||||
}
|
||||
|
||||
#endif /* NOTA_IMPLEMENTATION */
|
||||
|
||||
#endif /* NOTA_H */
|
||||
1476
source/prosperon.c
91
source/prosperon.h
Normal file
@@ -0,0 +1,91 @@
|
||||
#ifndef PROSPERON_H
|
||||
#define PROSPERON_H
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include "quickjs.h"
|
||||
|
||||
#define STATE_VECTOR_LENGTH 624
|
||||
#define STATE_VECTOR_M 397
|
||||
|
||||
#define ACTOR_IDLE 0
|
||||
#define ACTOR_READY 1
|
||||
#define ACTOR_RUNNING 2
|
||||
#define ACTOR_EXHAUSTED 3
|
||||
#define ACTOR_RECLAIMING 4
|
||||
#define ACTOR_SLOW 5
|
||||
|
||||
typedef JSValue (*MODULEFN)(JSContext *js);
|
||||
|
||||
typedef struct tagMTRand {
|
||||
uint32_t mt[STATE_VECTOR_LENGTH];
|
||||
int32_t index;
|
||||
} MTRand;
|
||||
|
||||
typedef struct {
|
||||
const char *name;
|
||||
MODULEFN fn;
|
||||
} ModuleEntry;
|
||||
|
||||
typedef struct {
|
||||
int argc;
|
||||
char **argv;
|
||||
} cmdargs;
|
||||
|
||||
typedef struct prosperon_rt {
|
||||
cmdargs cmd;
|
||||
JSContext *context;
|
||||
JSValue cycle_fn;
|
||||
JSValue idx_buffer;
|
||||
JSValue on_exception;
|
||||
JSValue message_handle;
|
||||
JSValue unneeded;
|
||||
|
||||
ModuleEntry *module_registry;
|
||||
JSValue *js_swapchains;
|
||||
|
||||
/* Protects JSContext usage */
|
||||
SDL_Mutex *mutex;
|
||||
|
||||
SDL_Mutex *turn;
|
||||
|
||||
char *id;
|
||||
MTRand mrand;
|
||||
double unneeded_secs;
|
||||
int idx_count;
|
||||
|
||||
/* The “mailbox” for incoming messages + a dedicated lock for it: */
|
||||
void **messages;
|
||||
JSValue *events;
|
||||
SDL_Mutex *msg_mutex; /* For messages queue only */
|
||||
|
||||
/* CHANGED FOR EVENTS: a separate lock for the actor->events queue */
|
||||
struct { Uint32 key; JSValue value; } *timers;
|
||||
|
||||
int state;
|
||||
Uint32 ar;
|
||||
int need_stop;
|
||||
int main_thread_only;
|
||||
} prosperon_rt;
|
||||
|
||||
extern SDL_ThreadID main_thread;
|
||||
extern SDL_TLSID prosperon_id;
|
||||
|
||||
prosperon_rt *create_actor(int argc, char **argv);
|
||||
const char *register_actor(const char *id, prosperon_rt *actor, int mainthread);
|
||||
void actor_free(prosperon_rt *actor);
|
||||
const char *send_message(const char *id, void *msg);
|
||||
Uint32 actor_timer_cb(prosperon_rt *actor, SDL_TimerID id, Uint32 interval);
|
||||
JSValue js_actor_delay(JSContext *js, JSValue self, int argc, JSValue *argv);
|
||||
JSValue js_actor_removetimer(JSContext *js, JSValue self, int argc, JSValue *argv);
|
||||
void script_startup(prosperon_rt *rt);
|
||||
void script_evalf(JSContext *js, const char *format, ...);
|
||||
JSValue script_eval(JSContext *js, const char *file, const char *script);
|
||||
int uncaught_exception(JSContext *js, JSValue v);
|
||||
int actor_exists(const char *id);
|
||||
void set_actor_state(prosperon_rt *actor);
|
||||
|
||||
int prosperon_mount_core(void);
|
||||
|
||||
JSValue js_os_ioactor(JSContext *js, JSValue self, int argc, JSValue *argv);
|
||||
|
||||
#endif
|
||||
460
source/qjs_blob.c
Normal file
@@ -0,0 +1,460 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "quickjs.h"
|
||||
#include "qjs_blob.h"
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// A simple blob structure that can be in two states:
|
||||
// - antestone (mutable): writing is allowed
|
||||
// - stone (immutable): reading is allowed
|
||||
//
|
||||
// The blob is stored as an array of bits in memory, but for simplicity here,
|
||||
// we store them in a dynamic byte array with a bit_length and capacity in bits.
|
||||
//
|
||||
// This is a minimal demonstration. Real usage might require more sophisticated
|
||||
// memory or bit manipulation for performance.
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
typedef struct {
|
||||
// The actual buffer holding the bits (in multiples of 8 bits).
|
||||
uint8_t *data;
|
||||
|
||||
// The total number of bits currently in use (the "length" of the blob).
|
||||
size_t bit_length;
|
||||
|
||||
// The total capacity in bits that 'data' can currently hold without realloc.
|
||||
size_t bit_capacity;
|
||||
|
||||
// 0 = antestone (mutable)
|
||||
// 1 = stone (immutable)
|
||||
int is_stone;
|
||||
} JSBlobData;
|
||||
|
||||
// Forward declaration of class ID and methods
|
||||
static JSClassID js_blob_class_id;
|
||||
|
||||
// Helper to ensure capacity for writing
|
||||
// new_bits is additional bits to be appended
|
||||
static int js_blob_ensure_capacity(JSContext *ctx, JSBlobData *bd, size_t new_bits) {
|
||||
size_t need_bits = bd->bit_length + new_bits;
|
||||
if (need_bits <= bd->bit_capacity) return 0;
|
||||
|
||||
// Increase capacity (in multiples of bytes).
|
||||
// We can pick a growth strategy. For demonstration, double it:
|
||||
size_t new_capacity = bd->bit_capacity == 0 ? 64 : bd->bit_capacity * 2;
|
||||
while (new_capacity < need_bits) new_capacity *= 2;
|
||||
|
||||
// Round up new_capacity to a multiple of 8 bits
|
||||
if (new_capacity % 8) {
|
||||
new_capacity += 8 - (new_capacity % 8);
|
||||
}
|
||||
|
||||
size_t new_size_bytes = new_capacity / 8;
|
||||
uint8_t *new_ptr = realloc(bd->data, new_size_bytes);
|
||||
if (!new_ptr) {
|
||||
return -1; // out of memory
|
||||
}
|
||||
// zero-fill the new area (only beyond the old capacity)
|
||||
size_t old_size_bytes = bd->bit_capacity / 8;
|
||||
if (new_size_bytes > old_size_bytes) {
|
||||
memset(new_ptr + old_size_bytes, 0, new_size_bytes - old_size_bytes);
|
||||
}
|
||||
bd->data = new_ptr;
|
||||
bd->bit_capacity = new_capacity;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Finalizer for JSBlobData
|
||||
static void js_blob_finalizer(JSRuntime *rt, JSValue val) {
|
||||
JSBlobData *bd = JS_GetOpaque(val, js_blob_class_id);
|
||||
if (bd) {
|
||||
free(bd->data);
|
||||
bd->data = NULL;
|
||||
bd->bit_length = 0;
|
||||
bd->bit_capacity = 0;
|
||||
bd->is_stone = 0;
|
||||
free(bd);
|
||||
}
|
||||
}
|
||||
|
||||
// Mark function: not used here, as we have no child JS objects in JSBlobData
|
||||
static void js_blob_mark(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func) {
|
||||
// No child JS references to mark
|
||||
}
|
||||
|
||||
// A helper to create a new JSBlobData object, returning a JSValue wrapping it.
|
||||
static JSValue js_blob_wrap(JSContext *ctx, JSBlobData *bd) {
|
||||
JSValue obj = JS_NewObjectClass(ctx, js_blob_class_id);
|
||||
if (JS_IsException(obj)) {
|
||||
free(bd->data);
|
||||
free(bd);
|
||||
return obj;
|
||||
}
|
||||
JS_SetOpaque(obj, bd);
|
||||
return obj;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Helpers for reading/writing bits
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
// Write one bit (0 or 1) at the end of the blob
|
||||
static int js_blob_write_bit_internal(JSContext *ctx, JSBlobData *bd, int bit_val) {
|
||||
if (bd->is_stone) {
|
||||
// Trying to write to an immutable blob -> throw
|
||||
return -1;
|
||||
}
|
||||
if (js_blob_ensure_capacity(ctx, bd, 1) < 0) {
|
||||
return -1;
|
||||
}
|
||||
// index in bits
|
||||
size_t bit_index = bd->bit_length;
|
||||
size_t byte_index = bit_index >> 3;
|
||||
size_t offset_in_byte = bit_index & 7;
|
||||
|
||||
// set or clear bit
|
||||
if (bit_val)
|
||||
bd->data[byte_index] |= (1 << offset_in_byte);
|
||||
else
|
||||
bd->data[byte_index] &= ~(1 << offset_in_byte);
|
||||
|
||||
bd->bit_length++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Read one bit from a stone blob at position 'pos'
|
||||
static int js_blob_read_bit_internal(JSBlobData *bd, size_t pos, int *out_bit) {
|
||||
if (!bd->is_stone) {
|
||||
// It's not stone -> reading might be out of the specification
|
||||
// but we can allow or return error. Here we just return error.
|
||||
return -1;
|
||||
}
|
||||
if (pos >= bd->bit_length) {
|
||||
return -1; // out of range
|
||||
}
|
||||
size_t byte_index = pos >> 3;
|
||||
size_t offset_in_byte = pos & 7;
|
||||
*out_bit = (bd->data[byte_index] & (1 << offset_in_byte)) ? 1 : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Turn a blob into the "stone" state. This discards any extra capacity.
|
||||
static void js_blob_make_stone(JSBlobData *bd) {
|
||||
bd->is_stone = 1;
|
||||
// Optionally shrink the buffer to exactly bit_length in size
|
||||
if (bd->bit_capacity > bd->bit_length) {
|
||||
size_t size_in_bytes = (bd->bit_length + 7) >> 3; // round up to full bytes
|
||||
uint8_t *new_ptr = NULL;
|
||||
if (size_in_bytes) {
|
||||
new_ptr = realloc(bd->data, size_in_bytes);
|
||||
if (new_ptr) {
|
||||
bd->data = new_ptr;
|
||||
}
|
||||
} else {
|
||||
// zero length
|
||||
free(bd->data);
|
||||
bd->data = NULL;
|
||||
}
|
||||
bd->bit_capacity = bd->bit_length; // capacity in bits now matches length
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// JS Functions (blob.make, blob.write_bit, blob.read_logical, etc.)
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
// blob.make(...)
|
||||
static JSValue js_blob_make(JSContext *ctx, JSValueConst this_val,
|
||||
int argc, JSValueConst *argv) {
|
||||
// We'll implement a few typical signatures:
|
||||
// blob.make()
|
||||
// blob.make(capacity)
|
||||
// blob.make(length, logical_value)
|
||||
// blob.make(blob, from, to) (makes a copy)
|
||||
//
|
||||
// This is a simplified approach. The spec mentions random, partial copy, etc.
|
||||
// We'll handle just these forms enough to demonstrate the concept.
|
||||
|
||||
JSBlobData *bd = calloc(1, sizeof(*bd));
|
||||
if (!bd) return JS_ThrowOutOfMemory(ctx);
|
||||
|
||||
// default
|
||||
bd->data = NULL;
|
||||
bd->bit_length = 0;
|
||||
bd->bit_capacity = 0;
|
||||
bd->is_stone = 0; // initially antestone
|
||||
|
||||
// blob.make()
|
||||
if (argc == 0) {
|
||||
// empty antestone blob
|
||||
}
|
||||
// blob.make(capacity)
|
||||
else if (argc == 1 && JS_IsNumber(argv[0])) {
|
||||
int64_t capacity_bits;
|
||||
if (JS_ToInt64(ctx, &capacity_bits, argv[0]) < 0) {
|
||||
free(bd);
|
||||
return JS_EXCEPTION;
|
||||
}
|
||||
if (capacity_bits < 0) capacity_bits = 0;
|
||||
bd->bit_capacity = (size_t)capacity_bits;
|
||||
if (bd->bit_capacity % 8) {
|
||||
bd->bit_capacity += 8 - (bd->bit_capacity % 8);
|
||||
}
|
||||
if (bd->bit_capacity) {
|
||||
size_t bytes = bd->bit_capacity / 8;
|
||||
bd->data = calloc(bytes, 1);
|
||||
if (!bd->data) {
|
||||
free(bd);
|
||||
return JS_ThrowOutOfMemory(ctx);
|
||||
}
|
||||
}
|
||||
}
|
||||
// blob.make(length, logical)
|
||||
else if (argc == 2 && JS_IsNumber(argv[0]) && JS_IsBool(argv[1])) {
|
||||
int64_t length_bits;
|
||||
if (JS_ToInt64(ctx, &length_bits, argv[0]) < 0) {
|
||||
free(bd);
|
||||
return JS_EXCEPTION;
|
||||
}
|
||||
if (length_bits < 0) length_bits = 0;
|
||||
int is_one = JS_ToBool(ctx, argv[1]);
|
||||
bd->bit_length = (size_t)length_bits;
|
||||
bd->bit_capacity = bd->bit_length;
|
||||
if (bd->bit_capacity % 8) {
|
||||
bd->bit_capacity += 8 - (bd->bit_capacity % 8);
|
||||
}
|
||||
size_t bytes = bd->bit_capacity / 8;
|
||||
if (bytes) {
|
||||
bd->data = malloc(bytes);
|
||||
if (!bd->data) {
|
||||
free(bd);
|
||||
return JS_ThrowOutOfMemory(ctx);
|
||||
}
|
||||
memset(bd->data, is_one ? 0xff : 0x00, bytes);
|
||||
// if length_bits isn't a multiple of 8, we need to clear the unused bits
|
||||
size_t used_bits_in_last_byte = (size_t)length_bits & 7;
|
||||
if (used_bits_in_last_byte && is_one) {
|
||||
// clear top bits in the last byte
|
||||
uint8_t mask = (1 << used_bits_in_last_byte) - 1;
|
||||
bd->data[bytes - 1] &= mask;
|
||||
}
|
||||
}
|
||||
}
|
||||
// blob.make(blob, from, to)
|
||||
else if (argc >= 1 && JS_IsObject(argv[0])) {
|
||||
// we try copying from another blob if it's of the same class
|
||||
JSBlobData *src = JS_GetOpaque(argv[0], js_blob_class_id);
|
||||
if (!src) {
|
||||
free(bd);
|
||||
return JS_ThrowTypeError(ctx, "blob.make: argument 1 not a blob");
|
||||
}
|
||||
int64_t from = 0, to = (int64_t)src->bit_length;
|
||||
if (argc >= 2 && JS_IsNumber(argv[1])) {
|
||||
JS_ToInt64(ctx, &from, argv[1]);
|
||||
if (from < 0) from = 0;
|
||||
}
|
||||
if (argc >= 3 && JS_IsNumber(argv[2])) {
|
||||
JS_ToInt64(ctx, &to, argv[2]);
|
||||
if (to < from) to = from;
|
||||
if (to > (int64_t)src->bit_length) to = (int64_t)src->bit_length;
|
||||
}
|
||||
size_t copy_len = (size_t)(to - from);
|
||||
bd->bit_length = copy_len;
|
||||
bd->bit_capacity = copy_len;
|
||||
if (bd->bit_capacity % 8) {
|
||||
bd->bit_capacity += 8 - (bd->bit_capacity % 8);
|
||||
}
|
||||
size_t bytes = bd->bit_capacity / 8;
|
||||
if (bytes) {
|
||||
bd->data = calloc(bytes, 1);
|
||||
if (!bd->data) {
|
||||
free(bd);
|
||||
return JS_ThrowOutOfMemory(ctx);
|
||||
}
|
||||
}
|
||||
// Now copy the bits.
|
||||
// For simplicity, let's do a naive bit copy one by one:
|
||||
for (size_t i = 0; i < copy_len; i++) {
|
||||
size_t src_bit_index = from + i;
|
||||
size_t src_byte = src_bit_index >> 3;
|
||||
size_t src_off = src_bit_index & 7;
|
||||
int bit_val = (src->data[src_byte] >> src_off) & 1;
|
||||
size_t dst_byte = i >> 3;
|
||||
size_t dst_off = i & 7;
|
||||
if (bit_val) {
|
||||
bd->data[dst_byte] |= (1 << dst_off);
|
||||
} else {
|
||||
bd->data[dst_byte] &= ~(1 << dst_off);
|
||||
}
|
||||
}
|
||||
}
|
||||
// else fail
|
||||
else {
|
||||
free(bd);
|
||||
return JS_ThrowTypeError(ctx, "blob.make: invalid arguments");
|
||||
}
|
||||
|
||||
return js_blob_wrap(ctx, bd);
|
||||
}
|
||||
|
||||
// blob.write_bit(blob, logical)
|
||||
static JSValue js_blob_write_bit(JSContext *ctx, JSValueConst this_val,
|
||||
int argc, JSValueConst *argv) {
|
||||
if (argc < 2) {
|
||||
return JS_ThrowTypeError(ctx, "blob.write_bit(blob, logical) requires 2 arguments");
|
||||
}
|
||||
JSBlobData *bd = JS_GetOpaque(argv[0], js_blob_class_id);
|
||||
if (!bd) {
|
||||
return JS_ThrowTypeError(ctx, "blob.write_bit: argument 1 not a blob");
|
||||
}
|
||||
int bit_val = JS_ToBool(ctx, argv[1]); // interpret any truthy as 1, else 0
|
||||
if (js_blob_write_bit_internal(ctx, bd, bit_val) < 0) {
|
||||
return JS_ThrowTypeError(ctx, "blob.write_bit: cannot write (maybe stone or OOM)");
|
||||
}
|
||||
return JS_UNDEFINED;
|
||||
}
|
||||
|
||||
// blob.read_logical(blob, from)
|
||||
static JSValue js_blob_read_logical(JSContext *ctx, JSValueConst this_val,
|
||||
int argc, JSValueConst *argv) {
|
||||
if (argc < 2) {
|
||||
return JS_ThrowTypeError(ctx, "blob.read_logical(blob, from) requires 2 arguments");
|
||||
}
|
||||
JSBlobData *bd = JS_GetOpaque(argv[0], js_blob_class_id);
|
||||
if (!bd) {
|
||||
return JS_ThrowTypeError(ctx, "blob.read_logical: argument 1 not a blob");
|
||||
}
|
||||
int64_t pos;
|
||||
if (JS_ToInt64(ctx, &pos, argv[1]) < 0) {
|
||||
return JS_EXCEPTION;
|
||||
}
|
||||
if (pos < 0) {
|
||||
return JS_NULL; // out of range
|
||||
}
|
||||
int bit_val;
|
||||
if (js_blob_read_bit_internal(bd, (size_t)pos, &bit_val) < 0) {
|
||||
return JS_NULL; // error or out of range
|
||||
}
|
||||
return JS_NewBool(ctx, bit_val);
|
||||
}
|
||||
|
||||
// blob.stone(blob)
|
||||
static JSValue js_blob_stone(JSContext *ctx, JSValueConst this_val,
|
||||
int argc, JSValueConst *argv) {
|
||||
if (argc < 1) {
|
||||
return JS_ThrowTypeError(ctx, "blob.stone(blob) requires 1 argument");
|
||||
}
|
||||
JSBlobData *bd = JS_GetOpaque(argv[0], js_blob_class_id);
|
||||
if (!bd) {
|
||||
return JS_ThrowTypeError(ctx, "blob.stone: argument not a blob");
|
||||
}
|
||||
if (!bd->is_stone) {
|
||||
js_blob_make_stone(bd);
|
||||
}
|
||||
return JS_UNDEFINED;
|
||||
}
|
||||
|
||||
// blob.length(blob)
|
||||
// Return number of bits in the blob
|
||||
static JSValue js_blob_length(JSContext *ctx, JSValueConst this_val,
|
||||
int argc, JSValueConst *argv) {
|
||||
if (argc < 1) {
|
||||
return JS_ThrowTypeError(ctx, "blob.length(blob) requires 1 argument");
|
||||
}
|
||||
JSBlobData *bd = JS_GetOpaque(argv[0], js_blob_class_id);
|
||||
if (!bd) {
|
||||
return JS_ThrowTypeError(ctx, "blob.length: argument not a blob");
|
||||
}
|
||||
return JS_NewInt64(ctx, bd->bit_length);
|
||||
}
|
||||
|
||||
// blob.blob?(value)
|
||||
// Return true if the value is a blob object
|
||||
static JSValue js_blob_is_blob(JSContext *ctx, JSValueConst this_val,
|
||||
int argc, JSValueConst *argv) {
|
||||
if (argc < 1) return JS_FALSE;
|
||||
JSBlobData *bd = JS_GetOpaque(argv[0], js_blob_class_id);
|
||||
return JS_NewBool(ctx, bd != NULL);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Exports list
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
static const JSCFunctionListEntry js_blob_funcs[] = {
|
||||
// The "make" function.
|
||||
JS_CFUNC_DEF("make", 3, js_blob_make),
|
||||
// Some example read/write routines
|
||||
JS_CFUNC_DEF("write_bit", 2, js_blob_write_bit),
|
||||
JS_CFUNC_DEF("read_logical", 2, js_blob_read_logical),
|
||||
// Convert blob from antestone -> stone
|
||||
JS_CFUNC_DEF("stone", 1, js_blob_stone),
|
||||
// Return the length in bits
|
||||
JS_CFUNC_DEF("length", 1, js_blob_length),
|
||||
// Check if a value is a blob
|
||||
JS_CFUNC_DEF("isblob", 1, js_blob_is_blob),
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Class definition for the 'blob' objects
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
static JSClassDef js_blob_class = {
|
||||
"BlobClass",
|
||||
.finalizer = js_blob_finalizer,
|
||||
.gc_mark = js_blob_mark,
|
||||
};
|
||||
|
||||
// Module init function
|
||||
static int js_blob_init(JSContext *ctx, JSModuleDef *m) {
|
||||
// Register the class if not already done
|
||||
if (JS_IsRegisteredClass(ctx, js_blob_class_id) == 0) {
|
||||
JS_NewClassID(&js_blob_class_id);
|
||||
JS_NewClass(JS_GetRuntime(ctx), js_blob_class_id, &js_blob_class);
|
||||
}
|
||||
|
||||
// Create a prototype object
|
||||
JSValue proto = JS_NewObject(ctx);
|
||||
JS_SetClassProto(ctx, js_blob_class_id, proto);
|
||||
|
||||
// Export our functions as named exports
|
||||
JS_SetModuleExportList(ctx, m, js_blob_funcs, sizeof(js_blob_funcs) / sizeof(js_blob_funcs[0]));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The module entry point
|
||||
#ifdef JS_SHARED_LIBRARY
|
||||
#define JS_INIT_MODULE js_init_module
|
||||
#else
|
||||
#define JS_INIT_MODULE js_init_module_blob
|
||||
#endif
|
||||
|
||||
JSModuleDef *JS_INIT_MODULE(JSContext *ctx, const char *module_name) {
|
||||
JSModuleDef *m = JS_NewCModule(ctx, module_name, js_blob_init);
|
||||
if (!m) return NULL;
|
||||
JS_AddModuleExportList(ctx, m, js_blob_funcs, sizeof(js_blob_funcs) / sizeof(js_blob_funcs[0]));
|
||||
return m;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// js_blob_use(ctx) for easy embedding: returns an object with the blob functions
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
JSValue js_blob_use(JSContext *ctx) {
|
||||
// Ensure class is registered
|
||||
if (JS_IsRegisteredClass(ctx, js_blob_class_id) == 0) {
|
||||
JS_NewClassID(&js_blob_class_id);
|
||||
JS_NewClass(JS_GetRuntime(ctx), js_blob_class_id, &js_blob_class);
|
||||
|
||||
// Create a prototype object
|
||||
JSValue proto = JS_NewObject(ctx);
|
||||
JS_SetClassProto(ctx, js_blob_class_id, proto);
|
||||
}
|
||||
|
||||
// Create a plain object (the "exports") and add the funcs
|
||||
JSValue obj = JS_NewObject(ctx);
|
||||
JS_SetPropertyFunctionList(ctx, obj, js_blob_funcs,
|
||||
sizeof(js_blob_funcs) / sizeof(js_blob_funcs[0]));
|
||||
return obj;
|
||||
}
|
||||