### Install and Build Project Dependencies
Source: https://github.com/hyperscapeai/hyperscape/blob/main/README.md
Installs all project dependencies and builds all packages. This is a standard starting point for any project setup.
```bash
npm install
npm run build
```
--------------------------------
### Clone and Run Hyperscape Quick Start
Source: https://github.com/hyperscapeai/hyperscape/blob/main/README.md
A concise guide to getting Hyperscape up and running, from cloning the repository to starting the game and interacting with it.
```bash
git clone [repository-url]
cd hyperscape
npm install
npm run build
npm start
# Open browser to http://localhost:4444
```
--------------------------------
### Install and Run Hyperscape RPG Engine
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/README.md
Instructions for cloning the repository, installing dependencies using Bun, copying environment variables, and starting the development server for the Hyperscape RPG Engine.
```bash
# Clone the repository
git clone https://github.com/hyperscape/hyperscape
cd hyperscape/packages/hyperscape
# Install dependencies
bun install
# Copy environment variables
cp .env.example .env
# Start the development server
bun run dev
```
--------------------------------
### Install and Start Hyperscape RPG
Source: https://github.com/hyperscapeai/hyperscape/blob/main/README.md
This command sequence outlines the basic steps to install project dependencies, build the necessary packages, and start the Hyperscape RPG server. It assumes the user has Node.js and npm installed.
```bash
# Quick start - get playing in 3 steps:
npm install
npm run build
npm start
```
```bash
# Install dependencies
npm install
# Build all packages
npm run build
# Start the RPG server
npm start
```
--------------------------------
### Create and Develop ElizaOS Plugin
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/plugin-hyperscape/README.md
Commands to create a new ElizaOS plugin, navigate to its directory, and start the development server with hot-reloading.
```bash
# Create a new plugin (automatically adds "plugin-" prefix)
elizaos create -t plugin solana
# This creates: plugin-solana
# Dependencies are automatically installed and built
# Navigate to the plugin directory
cd plugin-solana
# Start development immediately
elizaos dev
```
--------------------------------
### ElizaOS Plugin Development Commands
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/plugin-hyperscape/README.md
CLI commands for starting ElizaOS plugins in development mode, with or without hot-reloading, and for running tests.
```bash
# Start development with hot-reloading (recommended)
elizaos dev
# OR start without hot-reloading
elizaos start
# Note: When using 'start', you need to rebuild after changes:
# bun run build
# Test the plugin
elizaos test
```
--------------------------------
### ElizaOS Plugin End-to-End Test Example
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/plugin-hyperscape/README.md
An example of an End-to-End test for an ElizaOS plugin, demonstrating how to simulate user interaction and verify agent responses within a real runtime environment.
```typescript
// E2E test example (__tests__/e2e/starter-plugin.ts)
export const StarterPluginTestSuite: TestSuite = {
name: 'plugin_starter_test_suite',
description: 'E2E tests for the starter plugin',
tests: [
{
name: 'hello_world_action_test',
fn: async (runtime) => {
// Simulate user asking agent to say hello
const testMessage = {
content: { text: 'Can you say hello?' }
};
// Execute action and capture response
const response = await helloWorldAction.handler(runtime, testMessage, ...);
// Verify agent responds with "hello world"
if (!response.text.includes('hello world')) {
throw new Error('Expected "hello world" in response');
}
},
},
],
};
```
--------------------------------
### ElizaOS Plugin Publishing Commands
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/plugin-hyperscape/README.md
Commands for authenticating with npm, testing the plugin before publishing, and initiating the initial publish process.
```bash
# npm Authentication
npm login
# Test your plugin meets all requirements
elizaos publish --test
# Publish to npm + GitHub + registry (recommended)
elizaos publish
```
--------------------------------
### API State Query Examples (Bash)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/README.md
Retrieve game state information through the REST API. Examples include fetching all available queries, specific player statistics, or general world information.
```bash
# Get all available state queries
GET /api/state
# Get player stats
GET /api/state/player-stats?playerId=123
# Get world info
GET /api/state/world-info
```
--------------------------------
### Start ElizaOS with Hyperscape Plugin (Bash)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/README.md
Initiate the ElizaOS environment with the Hyperscape plugin integrated, enabling AI agent functionality within the RPG. This involves navigating to the plugin directory and running the start command.
```bash
# Start ElizaOS with Hyperscape plugin
cd packages/plugin-hyperscape
elizaos start
```
--------------------------------
### Start Game Server
Source: https://github.com/hyperscapeai/hyperscape/blob/main/README.md
Starts the main RPG game server. This command is used for playing the game or running it in a production-like environment.
```bash
npm start
```
--------------------------------
### Project Setup and Variable Checks in CMake
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/physx/snippets/compiler/cmake/CMakeLists.txt
This snippet demonstrates the initial setup for a CMake project, including setting the minimum required version, defining the project name and languages, and performing essential checks for required environment variables like PHYSX_ROOT_DIR. It ensures that the build environment is correctly configured before proceeding.
```cmake
cmake_minimum_required(VERSION 3.16)
project(Snippets C CXX)
# This is required to be defined by external callers!
IF(NOT DEFINED PHYSX_ROOT_DIR)
MESSAGE(FATAL_ERROR "PHYSX_ROOT_DIR variable wasn't set.")
ENDIF()
IF(NOT EXISTS ${PHYSX_ROOT_DIR})
MESSAGE(FATAL_ERROR "PHYSX_ROOT_DIR variable was invalid.")
ENDIF()
INCLUDE(NvidiaBuildOptions)
```
--------------------------------
### Vitest Unit and Integration Tests for ElizaOS Plugin
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/plugin-hyperscape/README.md
Examples of writing unit and integration tests for an ElizaOS plugin using Vitest, covering plugin metadata and component interactions.
```typescript
// Unit test example (__tests__/plugin.test.ts)
describe('Plugin Configuration', () => {
it('should have correct plugin metadata', () => {
expect(starterPlugin.name).toBe('plugin-hyperscape');
});
});
// Integration test example (__tests__/integration.test.ts)
describe('Integration: HelloWorld Action with StarterService', () => {
it('should handle HelloWorld action with StarterService', async () => {
// Test interactions between components
});
});
```
--------------------------------
### Install physx-js-webidl via npm
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/README.md
Install the physx-js-webidl library using npm for easy integration into your project. This command fetches the latest stable version from the npm registry.
```bash
npm i physx-js-webidl
```
--------------------------------
### Database Setup and Reset Commands (Bash)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/README.md
Initialize the game's SQLite database or reset the world state. The `db:init` command sets up the database, while `db:reset` purges all player data and resets the world.
```bash
# Initialize database
bun run db:init
# Reset world state (WARNING: Deletes all player data)
bun run db:reset
```
--------------------------------
### CMake Project Setup and Options
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/physx/source/compiler/cmake/CMakeLists.txt
Initializes the CMake project for PhysX and defines core build options such as scalar math, static library generation, and PDB export. These options control fundamental aspects of the build process.
```cmake
cmake_minimum_required(VERSION 3.16)
project(PhysX C CXX)
CMAKE_POLICY(SET CMP0057 NEW) # Enable IN_LIST
OPTION(PX_SCALAR_MATH "Disable SIMD math" OFF)
OPTION(PX_GENERATE_STATIC_LIBRARIES "Generate static libraries" OFF)
OPTION(PX_EXPORT_LOWLEVEL_PDB "Export low level pdb's" OFF)
```
--------------------------------
### Interactive Component Example (JavaScript)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/CONTRIBUTING.md
An example of an interactive component for Hyperscape worlds written in JavaScript. It demonstrates basic component setup, state management using useEffect, and event handling for interactions.
```javascript
/**
* Interactive component for Hyperscape worlds
* @param {Object} props - Component properties
* @param {Vector3} props.position - Initial position
* @param {Function} props.onInteract - Interaction callback
*/
export default function InteractiveComponent(props) {
const { position, onInteract } = props
useEffect(() => {
// Setup component
return () => {
// Cleanup
}
}, [])
return (
{/* Component content */}
)
}
```
--------------------------------
### Project Setup and Platform Configuration
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/physx/source/compiler/cmakegpu/CMakeLists.txt
Initializes the CMake project, sets the minimum version, and defines project languages. It includes logic to configure SDK paths for Windows development if environment variables are set, enabling specific include and library directories.
```cmake
cmake_minimum_required(VERSION 3.16)
# PROJECT(CUDA) will enable building CUDA files ( .cu )
PROJECT(PhysX C CXX CUDA)
IF(DEFINED ENV{PM_winsdk_PATH} AND NOT "$ENV{PM_winsdk_PATH}" STREQUAL "" AND DEFINED ENV{PM_msvc_PATH} AND NOT "$ENV{PM_msvc_PATH}" STREQUAL "")
SET(CMAKE_VS_SDK_INCLUDE_DIRECTORIES "$ENV{PM_winsdk_PATH}/include/ucrt;$ENV{PM_winsdk_PATH}/include/um;$ENV{PM_winsdk_PATH}/include/shared")
SET(CMAKE_VS_SDK_LIBRARY_DIRECTORIES "$ENV{PM_winsdk_PATH}/lib/ucrt/x64;$ENV{PM_winsdk_PATH}/lib/um/x64;$ENV{VCToolsInstallDir}/lib/x64;$ENV{VCToolsInstallDir}/atlmfc/lib/x64")
ENDIF()
```
--------------------------------
### Local Development and Testing Workflow with ElizaOS
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/plugin-hyperscape/README.md
This snippet demonstrates the standard workflow for developing and testing plugins using ElizaOS. It includes commands for local testing with hot-reloading and running various test suites (component, E2E).
```bash
# Edit your plugin code
elizaos dev # Test locally with hot-reload
# Run all tests
elizaos test
# Run specific test types if needed
elizaos test component # Component tests only
elizaos test e2e # E2E tests only
```
--------------------------------
### Three.js Core Setup and GLTF/VRM Loading
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/plugin-hyperscape/src/public/puppeteer/index.html
This snippet sets up the essential Three.js scene, camera, and renderer. It also configures GLTFLoader with the VRMLoaderPlugin for handling VRM files and exposes various Three.js components and loaders globally for easier access within the project.
```javascript
import * as THREE from 'three'
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
import { RGBELoader } from 'three/addons/loaders/RGBELoader.js'
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js'
import { VRMLoaderPlugin } from '@pixiv/three-vrm'
import * as SkeletonUtils from 'three/addons/utils/SkeletonUtils.js'
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(
70,
innerWidth / innerHeight,
0.1,
10000
)
const renderer = new THREE.WebGLRenderer({ alpha: true })
renderer.setSize(innerWidth, innerHeight)
document.body.appendChild(renderer.domElement)
/* --- GLTF / VRM loader ------------------------------------------------ */
const VRMLoader = new GLTFLoader()
VRMLoader.register(parser => new VRMLoaderPlugin(parser))
window.scene = scene
window.camera = camera
window.renderer = renderer
window.THREE = THREE
window.GLTFLoader = GLTFLoader
window.VRMLoader = VRMLoader
window.ObjectLoader = THREE.ObjectLoader
window.MaterialLoader = THREE.MaterialLoader
window.TextureLoader = new THREE.TextureLoader()
window.GLTFExporter = GLTFExporter
window.RGBELoader = RGBELoader
window.SkeletonUtils = SkeletonUtils
```
--------------------------------
### Alternative Publishing Options with ElizaOS CLI
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/plugin-hyperscape/README.md
This snippet details alternative publishing methods using the ElizaOS command-line interface. These options allow for selective publishing to npm only, skipping registry submissions, or performing a dry run without actual publishing.
```bash
# Publish to npm only (skip GitHub and registry)
elizaos publish --npm
# Publish but skip registry submission
elizaos publish --skip-registry
# Generate registry files locally without publishing
elizaos publish --dry-run
```
--------------------------------
### ElizaOS Plugin Testing Commands
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/plugin-hyperscape/README.md
Commands to execute different types of tests for ElizaOS plugins, including component, end-to-end, and all tests.
```bash
# Run component tests
elizaos test component
# Run end-to-end tests
elizaos test e2e
# Running All Tests
elizaos test
```
--------------------------------
### Version Management and Publishing with npm and Git
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/plugin-hyperscape/README.md
This snippet covers the standard process for managing project versions using npm and publishing to npm and GitHub. It includes commands for incrementing patch, minor, and major versions, publishing to npm, and pushing changes and tags to GitHub.
```bash
# Patch version (bug fixes): 1.0.0 → 1.0.1
npm version patch
# Minor version (new features): 1.0.1 → 1.1.0
npm version minor
# Major version (breaking changes): 1.1.0 → 2.0.0
npm version major
npm publish
git push origin main
git push --tags # Push version tags
```
--------------------------------
### API Action Execution Examples (Bash)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/README.md
Execute actions within the game via the REST API. This includes retrieving a player's available actions and performing specific actions like attacking.
```bash
# Get available actions for player
GET /api/actions/available?playerId=123
# Execute action
POST /api/actions/attack
{
"targetId": "goblin-456",
"playerId": "123"
}
```
--------------------------------
### CMake Project Setup and Configuration
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/physx/pvdruntime/compiler/cmake/CMakeLists.txt
Sets the minimum CMake version, defines the project name and languages, and configures build settings for different configurations (debug, checked, profile, release). It also enforces the definition of PHYSX_ROOT_DIR and includes NvidiaBuildOptions.
```cmake
cmake_minimum_required(VERSION 3.16)
project(PVDRuntime C CXX)
set(PVDRuntimeBuilt 1 CACHE INTERNAL "PVDRuntimeBuilt")
# This is required to be defined by external callers!
IF(NOT DEFINED PHYSX_ROOT_DIR)
MESSAGE(FATAL_ERROR "PHYSX_ROOT_DIR variable wasn't set.")
ENDIF()
IF(NOT EXISTS ${PHYSX_ROOT_DIR})
MESSAGE(FATAL_ERROR "PHYSX_ROOT_DIR variable was invalid.")
ENDIF()
INCLUDE(NvidiaBuildOptions)
IF(CMAKE_CONFIGURATION_TYPES)
SET(CMAKE_CONFIGURATION_TYPES debug checked profile release)
SET(CMAKE_CONFIGURATION_TYPES "${CMAKE_CONFIGURATION_TYPES}" CACHE STRING
"Reset config to what we need"
FORCE)
# Need to define these at least once.
SET(CMAKE_EXE_LINKER_FLAGS_CHECKED "")
SET(CMAKE_EXE_LINKER_FLAGS_PROFILE "")
SET(CMAKE_SHARED_LINKER_FLAGS_CHECKED "")
SET(CMAKE_SHARED_LINKER_FLAGS_PROFILE "")
# Build PDBs for all configurations
SET(CMAKE_EXE_LINKER_FLAGS "/DEBUG")
SET(CMAKE_SHARED_LINKER_FLAGS "/DEBUG")
ENDIF()
SET(PROJECT_CMAKE_FILES_DIR compiler/cmake)
SET(PLATFORM_CMAKELISTS ${PHYSX_ROOT_DIR}/pvdruntime/${PROJECT_CMAKE_FILES_DIR}/${TARGET_BUILD_PLATFORM}/CMakeLists.txt)
IF(NOT EXISTS ${PLATFORM_CMAKELISTS})
MESSAGE(FATAL_ERROR "Unable to find platform CMakeLists.txt for ${TARGET_BUILD_PLATFORM} at ${PLATFORM_CMAKELISTS}")
ENDIF()
# Include the platform specific CMakeLists
INCLUDE(${PHYSX_ROOT_DIR}/pvdruntime/${PROJECT_CMAKE_FILES_DIR}/${TARGET_BUILD_PLATFORM}/CMakeLists.txt)
# Set folder Server to all Server projects
SET_PROPERTY(TARGET PVDRuntime PROPERTY FOLDER "PVDRuntime")
INSTALL(
TARGETS PVDRuntime
EXPORT PhysXSDK
DESTINATION $<$:${PX_ROOT_LIB_DIR}/debug>$<$:${PX_ROOT_LIB_DIR}/release>$<$:${PX_ROOT_LIB_DIR}/checked>$<$:${PX_ROOT_LIB_DIR}/profile>
)
```
--------------------------------
### Run Development Server
Source: https://github.com/hyperscapeai/hyperscape/blob/main/README.md
Starts the development server with hot-reloading for both the client and server. The client runs on http://localhost:3333 with Vite HMR, and the server runs on ws://localhost:4444/ws, with automatic rebuilds on TypeScript changes.
```bash
npm run dev
```
```bash
bun run dev
```
--------------------------------
### Build and Run Docker Container for Hyperscape
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/DOCKER.md
This snippet demonstrates how to build a Docker image for the Hyperscape project and run it as a detached container. It includes volume mounts for source code, world data, and the environment file, along with essential environment variables for configuration. Ensure Docker is installed and accessible.
```bash
docker build -t hyperscapedemo . && docker run -d -p 4444:4444 \
-v "$(pwd)/src:/app/src" \
-v "$(pwd)/world:/app/world" \
-v "$(pwd)/.env:/app/.env" \
-e DOMAIN=demo.hyperscape.host \
-e PORT=4444 \
-e ASSETS_DIR=/world/assets \
-e PUBLIC_WS_URL=https://demo.hyperscape.host/ws \
-e PUBLIC_API_URL=https://demo.hyperscape.host/api \
-e PUBLIC_ASSETS_URL=https://demo.hyperscape.host/assets \
hyperscapedemo
```
--------------------------------
### Run Test Validation Commands (Bash)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/README.md
Perform test validation to verify the installation and system integrity. Commands include a quick health check and a full system integration test.
```bash
# Quick health check
bun run test:health
# Full system validation
bun run test:rpg:integration
```
--------------------------------
### Clone Hyperscape Repository (Bash)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/CONTRIBUTING.md
This command clones the Hyperscape AI project repository from GitHub to your local machine, allowing you to start working on the codebase.
```bash
git clone https://github.com/hyperscape-xyz/hyperscape.git
```
--------------------------------
### Agent Configuration Schema in package.json
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/plugin-hyperscape/README.md
This snippet shows the structure of the `agentConfig` section within the `package.json` file. It defines plugin type and parameters, including API keys, with their respective types and descriptions. This configuration is crucial for defining plugin requirements.
```json
"agentConfig": {
"pluginType": "elizaos:plugin:1.0.0",
"pluginParameters": {
"API_KEY": {
"type": "string",
"description": "API key for the service"
}
}
}
```
--------------------------------
### Hyperscape Firemaking and Cooking with TypeScript
Source: https://context7.com/hyperscapeai/hyperscape/llms.txt
Demonstrates how to use the Processing System in Hyperscape to light fires with logs and cook food. It shows event emissions for starting processes and event listeners for success, failure, and expiration. Requires basic inventory items and proximity to a fire for cooking.
```typescript
import { ProcessingSystem } from '@hyperscape/hyperscape';
import { EventType } from '@hyperscape/hyperscape';
const processingSystem = world.getSystem('rpg-processing');
// Light fire with logs (requires tinderbox in inventory)
world.emit(EventType.PROCESSING_START, {
playerId: 'player-123',
processingType: 'firemaking',
inputItemId: 'logs_oak',
inputSlot: 10,
position: { x: 5, y: 0, z: 5 } // Ground position
});
// Fire placed in world as entity
world.on(EventType.PROCESSING_FIREMAKING_SUCCESS, (data) => {
console.log(`Lit fire with ${data.logType}, gained ${data.xpGained} Firemaking XP`);
console.log(`Fire entity ID: ${data.fireId}`);
console.log(`Fire duration: ${data.duration}ms`);
});
// Cook food on fire (requires raw food in inventory)
world.emit(EventType.PROCESSING_START, {
playerId: 'player-123',
processingType: 'cooking',
inputItemId: 'raw_shrimp',
inputSlot: 12,
fireId: 'fire-001' // Must be standing near fire
});
// Cooking can succeed or burn food
world.on(EventType.PROCESSING_COOKING_SUCCESS, (data) => {
console.log(`Cooked ${data.outputItemId}, gained ${data.xpGained} Cooking XP`);
console.log(`Output quantity: ${data.outputQuantity}`);
// Cooked food added to inventory
});
world.on(EventType.PROCESSING_COOKING_FAILED, (data) => {
console.log(`Burnt ${data.inputItemId}!`);
console.log(`Gained ${data.xpGained} Cooking XP (reduced)`);
// Burnt food added to inventory (less healing)
});
// Listen for general processing events
world.on(EventType.PROCESSING_FAILED, (data) => {
console.log(`Processing failed: ${data.reason}`); // 'missing_tool', 'invalid_location', 'level_too_low'
});
// Fire burns out after duration
world.on(EventType.PROCESSING_FIRE_EXPIRED, (data) => {
console.log(`Fire ${data.fireId} burned out`);
// Fire entity removed from world
});
```
--------------------------------
### Create and Manage Game Worlds in Hyperscape (TypeScript)
Source: https://context7.com/hyperscapeai/hyperscape/llms.txt
This snippet demonstrates how to create and manage server-side and client-side world instances in Hyperscape using TypeScript. It covers starting worlds, accessing registered systems, emitting events, registering custom systems, and updating the world loop. Dependencies include '@hyperscape/hyperscape'.
```typescript
import { createServerWorld, createClientWorld } from '@hyperscape/hyperscape';
// Server-side world creation
const serverWorld = await createServerWorld();
await serverWorld.start();
console.log(`Server world started with ID: ${serverWorld.id}`);
// Client-side world creation
const clientWorld = createClientWorld();
await clientWorld.start();
console.log(`Client world started`);
// Access world systems
const combatSystem = serverWorld.getSystem('rpg-combat');
const inventorySystem = serverWorld.getSystem('rpg-inventory');
const playerSystem = serverWorld.getSystem('rpg-player');
// Emit events to systems
serverWorld.emit('COMBAT_ATTACK_REQUEST', {
playerId: 'player123',
targetId: 'mob456',
attackType: 'MELEE'
});
// Register custom systems
serverWorld.register('custom-system', CustomSystemClass);
// Update loop (called automatically by runtime)
serverWorld.update(deltaTime);
```
--------------------------------
### Run Flow Editor on Linux
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/flow/README.md
Launches the NVIDIA Flow editor on Linux in either release or debug mode. The executable path depends on the build configuration.
```text
To run Flow editor: _build/linux-x86_64/release/nvfloweditor (release), _build/linux-x86_64/debug/nvfloweditor (debug)
```
--------------------------------
### Run Flow Editor on Windows
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/flow/README.md
Launches the NVIDIA Flow editor on Windows in either release or debug mode. The executable path depends on the build configuration.
```text
To run Flow editor: _build\windows-x86_64\release\nvfloweditor.exe (release), _build\windows-x86_64\debug\nvfloweditor.exe (debug)
```
--------------------------------
### Build NVIDIA Flow SDK on Windows
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/flow/README.md
Builds the NVIDIA Flow SDK using a batch script on Windows. Requires Visual Studio 2017 or later. This command navigates to the 'flow' directory and executes the build script.
```bat
cd flow
.\build.bat
```
--------------------------------
### Build physx-js-webidl using Docker
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/README.md
Build the physx-js-webidl library using Docker Compose for a consistent build environment. This method simplifies dependency management and ensures reproducible builds.
```bash
# Build the image
docker compose up
# Build Release
docker compose run --rm builder ./make.sh
# Build Debug
docker compose run --rm builder ./make.sh debug
# Build Profile
docker compose run --rm builder ./make.sh profile
# Build All Versions
docker compose run --rm builder ./make.sh all
```
--------------------------------
### Package-Specific Build and Test Commands
Source: https://github.com/hyperscapeai/hyperscape/blob/main/README.md
Allows building or testing individual packages within the monorepo. Use the --workspace flag to target specific packages.
```bash
npm run build --workspace=packages/hyperscape
```
```bash
npm run test --workspace=packages/rpg
```
```bash
npm run dev --workspace=packages/generation
```
--------------------------------
### Build physx-js-webidl from source
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/README.md
Build the physx-js-webidl library from source using the provided shell script. This process requires the Emscripten SDK and generates release, debug, or profile versions of the binaries and TypeScript definitions.
```bash
# Clone this repo
git clone https://github.com/fabmax/physx-js-webidl
# Enter that directory
cd physx-js-webidl
# Download submodule containing the PhysX code
git submodule update --init
# Build (generates project files, TypeScript definitions, and compiles)
./make.sh # Build release version (default)
./make.sh release # Build release version
./make.sh debug # Build debug version with assertions
./make.sh profile # Build profile version with profiling
./make.sh all # Build all versions
```
--------------------------------
### Build NVIDIA Flow SDK on Linux
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/flow/README.md
Builds the NVIDIA Flow SDK using a shell script on Linux. Requires GMake. This command navigates to the 'flow' directory and executes the build script.
```sh
cd flow
./build.sh
```
--------------------------------
### Run Hyperscape RPG Engine Tests
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/README.md
Command to execute the unified test suite for the Hyperscape RPG Engine, which validates all game systems through browser automation and visual verification.
```bash
# Run all tests (headless mode)
bun run test
```
--------------------------------
### Set Environment Variables for Production Deployment (Bash)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/README.md
Configure essential environment variables for production deployment, including database connection strings and asset URLs. Required variables are DATABASE_URL and WORLD_PATH, with optional variables for CDN and LiveKit integration.
```bash
# Required
DATABASE_URL=sqlite:./world/db.sqlite
WORLD_PATH=./world
# Optional
PUBLIC_ASSETS_URL=https://your-cdn.com/assets/
LIVEKIT_API_KEY=your-livekit-key
LIVEKIT_API_SECRET=your-livekit-secret
```
--------------------------------
### Define Build Options and Library Types with CMake
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/physx/source/compiler/cmake/jni-windows/CMakeLists.txt
This snippet defines project-wide build options such as copying external DLLs and enabling NVTX profiling. It also configures the definition for static library builds, controlled by the PX_GENERATE_STATIC_LIBRARIES option.
```cmake
OPTION(PX_COPY_EXTERNAL_DLL "Copy external dlls into SDK bin directory" OFF)
OPTION(PX_USE_NVTX "Enabled NVTX profiling" OFF)
# cache lib type defs
IF(PX_GENERATE_STATIC_LIBRARIES)
SET(PHYSX_LIBTYPE_DEFS "PX_PHYSX_STATIC_LIB;" CACHE INTERNAL "PhysX lib type defs")
ENDIF()
```
--------------------------------
### Run Tests with Different Options (Bash)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/README.md
Execute tests with options for visible browser debugging, detailed logging, or filtering by test category (RPG, framework, integration, gameplay).
```bash
# Run with visible browser (for debugging)
bun run test:headed
# Run with detailed logging
bun run test:verbose
# Run only RPG-specific tests
bun run test:rpg
# Run only framework/engine tests
bun run test:framework
# Run only integration tests
bun run test:integration
# Run only gameplay scenario tests
bun run test:gameplay
```
--------------------------------
### Manage Equipment: Equip, Unequip, and View Player Gear (TypeScript)
Source: https://context7.com/hyperscapeai/hyperscape/llms.txt
Demonstrates how to manage player equipment using the EquipmentSystem. This includes equipping and unequipping items, auto-detecting equipment slots, viewing equipped items, and accessing combat bonuses. It also shows how to listen for events related to equipment changes and requirement failures.
```typescript
import { EquipmentSystem } from '@hyperscape/hyperscape';
import { EventType } from '@hyperscape/hyperscape';
const equipmentSystem = world.getSystem('rpg-equipment');
// Equip item from inventory
world.emit(EventType.EQUIPMENT_EQUIP, {
playerId: 'player-123',
slot: 5, // Inventory slot
equipmentSlot: 'weapon' // 'weapon', 'shield', 'helmet', 'body', 'legs', 'gloves', 'boots', 'cape', 'amulet', 'ring'
});
// Auto-equip (detects slot from item type)
world.emit(EventType.EQUIPMENT_EQUIP, {
playerId: 'player-123',
slot: 5,
equipmentSlot: null // Auto-detect
});
// Unequip item to inventory
world.emit(EventType.EQUIPMENT_UNEQUIP, {
playerId: 'player-123',
equipmentSlot: 'weapon'
});
// Get equipped items
const player = world.entities.get('player-123');
const stats = player.components.get('stats');
const equipped = stats.equipment;
console.log(`Weapon: ${equipped.weapon?.name || 'None'}`);
console.log(`Body: ${equipped.body?.name || 'None'}`);
console.log(`Helmet: ${equipped.helmet?.name || 'None'}`);
// Get combat bonuses from equipment
const bonuses = stats.combatBonuses;
console.log(`Attack bonus: ${bonuses.attack}`);
console.log(`Strength bonus: ${bonuses.strength}`);
console.log(`Defense bonus: ${bonuses.defense}`);
console.log(`Ranged bonus: ${bonuses.ranged}`);
// Listen for equipment changes
world.on(EventType.EQUIPMENT_EQUIPPED, (data) => {
console.log(`${data.playerId} equipped ${data.itemId} in ${data.equipmentSlot}`);
console.log(`New bonuses: Attack +${data.newBonuses.attack}, Defense +${data.newBonuses.defense}`);
});
world.on(EventType.EQUIPMENT_UNEQUIPPED, (data) => {
console.log(`${data.playerId} unequipped ${data.itemId} from ${data.equipmentSlot}`);
});
world.on(EventType.EQUIPMENT_REQUIREMENT_FAILED, (data) => {
console.log(`Cannot equip ${data.itemId}: requires level ${data.required}, have ${data.current}`);
});
```
--------------------------------
### CMake Build Configuration for Hyperscape
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/physx/snippets/compiler/cmake/linux/CMakeLists.txt
This snippet demonstrates CMake configuration for the Hyperscape project. It checks for essential PhysX definitions and sets compiler and linker flags. It's crucial for ensuring the project builds correctly with the specified PhysX settings.
```cmake
IF(NOT DEFINED PHYSX_LINUX_COMPILE_DEFS)
MESSAGE(FATAL ERROR "Snippets uses the PhysX compile defs, and they're not defined when they need to be.")
ENDIF()
IF (NOT DEFINED PHYSX_CXX_FLAGS)
MESSAGE(FATAL ERROR "Snippets uses the PhysX CXX flags, and they're not defined when they need to be.")
ENDIF()
# Get the CXX Flags from the Cached variables set by the PhysX CMakeLists
SET(CMAKE_CXX_FLAGS "${PHYSX_CXX_FLAGS}")
SET(CMAKE_CXX_FLAGS_DEBUG "${PHYSX_CXX_FLAGS_DEBUG}")
SET(CMAKE_CXX_FLAGS_CHECKED "${PHYSX_CXX_FLAGS_CHECKED}")
SET(CMAKE_CXX_FLAGS_PROFILE "${PHYSX_CXX_FLAGS_PROFILE}")
SET(CMAKE_CXX_FLAGS_RELEASE "${PHYSX_CXX_FLAGS_RELEASE}")
# Build PDBs for all configurations
SET(CMAKE_SHARED_LINKER_FLAGS "/DEBUG")
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath='$ORIGIN'")
# Include all of the projects
SET(PLATFORM_SNIPPETS_LIST LoadCollection)
SET(SNIPPET_RENDER_ENABLED 1)
```
--------------------------------
### Clean and Reinstall Project
Source: https://github.com/hyperscapeai/hyperscape/blob/main/README.md
Removes build artifacts, distribution files, and node_modules, then reinstalls dependencies and rebuilds the project. This is a common fix for build errors after updates.
```bash
rm -rf packages/*/build packages/*/dist node_modules
npm install
npm run build
```
--------------------------------
### CMake Build Configuration and Flags
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/physx/source/compiler/cmake/CMakeLists.txt
Configures CMake for specific build configurations (debug, checked, profile, release) and sets linker flags. It ensures PDB files are generated for all configurations and manages response file usage to overcome command-line limitations.
```cmake
IF(CMAKE_CONFIGURATION_TYPES)
SET(CMAKE_CONFIGURATION_TYPES debug checked profile release)
SET(CMAKE_CONFIGURATION_TYPES "${CMAKE_CONFIGURATION_TYPES}" CACHE STRING
"Reset config to what we need"
FORCE)
SET(CMAKE_SHARED_LINKER_FLAGS_CHECKED "")
SET(CMAKE_SHARED_LINKER_FLAGS_PROFILE "")
# Build PDBs for all configurations
SET(CMAKE_SHARED_LINKER_FLAGS "/DEBUG")
ENDIF()
# Prevent failure due to command line limitations
IF(USE_RESPONSE_FILES)
SET(CMAKE_C_USE_RESPONSE_FILE_FOR_OBJECTS 1)
SET(CMAKE_C_USE_RESPONSE_FILE_FOR_INCLUDES 1)
SET(CMAKE_C_USE_RESPONSE_FILE_FOR_LIBRARIES 1)
SET(CMAKE_CXX_USE_RESPONSE_FILE_FOR_OBJECTS 1)
SET(CMAKE_CXX_USE_RESPONSE_FILE_FOR_INCLUDES 1)
SET(CMAKE_CXX_USE_RESPONSE_FILE_FOR_LIBRARIES 1)
ENDIF()
IF($ENV{PHYSX_AUTOBUILD})
IF($ENV{PHYSX_AUTOBUILD} STREQUAL "1")
SET(PHYSX_AUTOBUILD "PHYSX_AUTOBUILD")
ENDIF()
ENDIF()
```
--------------------------------
### Gather Resources: Woodcutting and Fishing Actions (TypeScript)
Source: https://context7.com/hyperscapeai/hyperscape/llms.txt
Illustrates how to interact with the ResourceSystem for gathering activities like woodcutting and fishing. This code shows how to initiate gathering, monitor progress, handle successful gathers (including XP gains), manage failures, cancel operations, and react to resource depletion and respawning.
```typescript
import { ResourceSystem } from '@hyperscape/hyperscape';
import { EventType } from '@hyperscape/hyperscape';
const resourceSystem = world.getSystem('rpg-resource');
// Start woodcutting
world.emit(EventType.RESOURCE_GATHER_START, {
playerId: 'player-123',
resourceId: 'tree-oak-001',
resourceType: 'tree'
});
// Gathering progresses automatically based on:
// - Player woodcutting level
// - Axe tier (bronze/steel/mithril)
// - Tree tier
// - Success rate calculation
// Listen for gathering progress
world.on(EventType.RESOURCE_GATHER_PROGRESS, (data) => {
console.log(`Gathering progress: ${data.progress}%`);
console.log(`Time remaining: ${data.timeRemaining}ms`);
});
// Listen for successful gather
world.on(EventType.RESOURCE_GATHERED, (data) => {
console.log(`Gathered ${data.quantity}x ${data.itemId} from ${data.resourceId}`);
console.log(`Gained ${data.xpGained} ${data.skill} XP`);
// Item automatically added to inventory
});
// Listen for gathering failure
world.on(EventType.RESOURCE_GATHER_FAILED, (data) => {
console.log(`Gathering failed: ${data.reason}`); // 'no_tool', 'level_too_low', 'inventory_full'
});
// Stop gathering (cancel)
world.emit(EventType.RESOURCE_GATHER_STOP, {
playerId: 'player-123'
});
// Start fishing
world.emit(EventType.RESOURCE_GATHER_START, {
playerId: 'player-123',
resourceId: 'fishing-spot-001',
resourceType: 'fishing_spot'
});
// Resource depletes after multiple gathers
world.on(EventType.RESOURCE_DEPLETED, (data) => {
console.log(`Resource ${data.resourceId} depleted, respawning in ${data.respawnTime}ms`);
});
```
--------------------------------
### Run All Project Tests
Source: https://github.com/hyperscapeai/hyperscape/blob/main/README.md
Executes all automated tests for the Hyperscape project using npm. This command initiates the visual testing system, which relies on Playwright for browser automation and pixel analysis to ensure game functionality and visual consistency.
```bash
npm test
```
--------------------------------
### PhysX Client Loading and Test Functions (JavaScript)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/src/client/public/test-physx-client.html
This snippet defines utility functions for logging messages and updating the status display, along with the main asynchronous function `testPhysXLoading` that orchestrates the PhysX client tests. It handles module imports, PhysX object creation, and verification of PhysX and THREE.js integration. It depends on an external PhysX module and potentially the THREE.js library.
```javascript
const logsDiv = document.getElementById('logs');
const statusDiv = document.getElementById('status');
function log(message, type = 'info') {
const logEntry = document.createElement('div');
logEntry.className = `log ${type}`;
logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
logsDiv.appendChild(logEntry);
console.log(message);
}
function updateStatus(message, state) {
statusDiv.textContent = `Status: ${message}`;
statusDiv.className = state;
}
async function testPhysXLoading() {
try {
log('Starting PhysX client test...');
updateStatus('Loading PhysX...', 'loading');
// Test 1: Load PhysX module directly
log('Test 1: Loading PhysX module...');
const startTime = performance.now();
// Import PhysXManager
const { loadPhysX, waitForPhysX, getPhysX, isPhysXReady } = await import('./build/index.js');
// Check initial state
log(`Initial PhysX ready state: ${isPhysXReady()}`);
// Load PhysX
const physxInfo = await waitForPhysX('ClientTest', 15000);
const loadTime = performance.now() - startTime;
log(`PhysX loaded in ${loadTime.toFixed(2)}ms`, 'success');
log(`PhysX version: ${physxInfo.version}`, 'success');
// Test 2: Verify PHYSX global
const PHYSX = getPhysX();
if (!PHYSX) {
throw new Error('PHYSX global not available after loading');
}
log('PHYSX global is available', 'success');
// Test 3: Create basic physics objects
log('Test 3: Creating physics objects...');
// Create a transform
const transform = new PHYSX.PxTransform(PHYSX.PxIDENTITYEnum.PxIdentity);
log('Created PxTransform', 'success');
// Create geometry
const boxGeometry = new PHYSX.PxBoxGeometry(1, 1, 1);
log('Created PxBoxGeometry', 'success');
// Create material
if (physxInfo.physics) {
const material = physxInfo.physics.createMaterial(0.5, 0.5, 0.6);
log('Created PxMaterial', 'success');
// Create a rigid body
const rigidBody = physxInfo.physics.createRigidDynamic(transform);
log('Created PxRigidDynamic', 'success');
// Test 4: Verify pose operations
const pose = rigidBody.getGlobalPose();
if (pose && pose.p && pose.q) {
log(`Rigid body position: (${pose.p.x}, ${pose.p.y}, ${pose.p.z})`, 'success');
log(`Rigid body quaternion: (${pose.q.x}, ${pose.q.y}, ${pose.q.z}, ${pose.q.w})`, 'success');
} else {
log('Warning: Pose structure not as expected', 'warn');
}
}
// Test 5: Test idempotency
log('Test 5: Testing idempotent loading...');
const secondLoadStart = performance.now();
await loadPhysX();
const secondLoadTime = performance.now() - secondLoadStart;
log(`Second load completed in ${secondLoadTime.toFixed(2)}ms (should be instant)`, 'success');
// Test 6: Verify THREE.js extensions
if (window.THREE) {
log('THREE.js is available', 'success');
// Check if physics extensions were applied
const testVec = new THREE.Vector3(1, 2, 3);
if (typeof testVec.toPxVec3 === 'function') {
log('THREE.js physics extensions are applied', 'success');
} else {
log('THREE.js physics extensions not found (non-critical)', 'warn');
}
}
updateStatus('All tests passed!', 'loaded');
log('✅ PhysX client loading test completed successfully!', 'success');
} catch (error) {
updateStatus('Test failed', 'failed');
log(`❌ Error: ${error.message}`, 'error');
console.error(error);
}
}
// Add THREE.js for testing
window.THREE = {
Vector3: class Vector3 {
constructor(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
},
Quaternion: class Quaternion {
constructor(x, y, z, w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
}
};
// Start test
testPhysXLoading();
```
--------------------------------
### Run Legacy Test Commands (Bash)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/README.md
Execute individual legacy test suites for specific debugging purposes, including RPG comprehensive, system integration, framework validation, and gameplay scenarios.
```bash
# Legacy test commands (for specific debugging)
bun run test:legacy:rpg # RPG comprehensive tests
bun run test:legacy:integration # System integration tests
bun run test:legacy:hyperscape # Framework validation tests
bun run test:legacy:gameplay # Gameplay scenario tests
```
--------------------------------
### World System API
Source: https://context7.com/hyperscapeai/hyperscape/llms.txt
APIs for creating and managing game world instances, including server-side and client-side world creation, accessing systems, emitting events, and registering custom systems.
```APIDOC
## World System - Create and Manage Game World
### Description
Create server-side or client-side world instances with core systems registered automatically.
### Method
- `createServerWorld()`: Creates a server-side world instance.
- `createClientWorld()`: Creates a client-side world instance.
- `world.start()`: Starts the world instance.
- `world.getSystem(systemName)`: Retrieves a specific system from the world.
- `world.emit(eventName, eventData)`: Emits an event to the world's systems.
- `world.register(systemName, SystemClass)`: Registers a custom system.
- `world.update(deltaTime)`: Updates the world's systems.
### Endpoint
N/A (This is a library API, not a network endpoint)
### Parameters
None for world creation functions.
### Request Body
None
### Request Example
```typescript
import { createServerWorld } from '@hyperscape/hyperscape';
import { createClientWorld } from '@hyperscape/hyperscape';
// Server-side world creation
const serverWorld = await createServerWorld();
await serverWorld.start();
console.log(`Server world started with ID: ${serverWorld.id}`);
// Client-side world creation
const clientWorld = createClientWorld();
await clientWorld.start();
console.log(`Client world started`);
// Access world systems
const combatSystem = serverWorld.getSystem('rpg-combat');
const inventorySystem = serverWorld.getSystem('rpg-inventory');
const playerSystem = serverWorld.getSystem('rpg-player');
// Emit events to systems
serverWorld.emit('COMBAT_ATTACK_REQUEST', {
playerId: 'player123',
targetId: 'mob456',
attackType: 'MELEE'
});
// Register custom systems
serverWorld.register('custom-system', CustomSystemClass);
// Update loop (called automatically by runtime)
serverWorld.update(deltaTime);
```
### Response
#### Success Response (200)
- `world`: The created world instance object.
- `world.id`: (string) Unique identifier for the server world.
#### Response Example
```json
{
"world": { ... world instance object ... },
"world.id": "some-server-world-id"
}
```
```
--------------------------------
### Run Project Tests (Bash)
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/hyperscape/CONTRIBUTING.md
Executes the test suite for the project using npm. Ensure all tests pass before committing your changes to maintain code quality.
```bash
npm run test
```
--------------------------------
### Configure Compiler Warnings for GCC
Source: https://github.com/hyperscapeai/hyperscape/blob/main/packages/physx-js-webidl/PhysX/physx/source/compiler/cmake/linux/CMakeLists.txt
This snippet defines a set of compiler warning flags for GCC. It includes general warnings and specific exclusions to manage the warning level without failing the build. The flags are intended to catch common C++ programming errors.
```cmake
SET(GCC_WARNINGS "-Wall -Werror \
-Wno-address \
-Wno-aligned-new \
-Wno-array-bounds \
-Wno-class-memaccess \
-Wno-conversion-null \
-Wno-format \
-Wno-format-overflow \
-Wno-invalid-offsetof \
-Wno-misleading-indentation \
-Wno-mismatched-new-delete \
-Wno-nonnull \
-Wno-nonnull-compare \
-Wno-pragmas \
-Wno-restrict \
-Wno-stringop-overflow \
-Wno-stringop-overread \
-Wno-subobject-linkage \
-Wno-template-id-cdtor \
-Wno-uninitialized \
-Wno-unused-but-set-variable \
-Wno-unused-function \
-Wno-unused-result \
-Wno-unknown-pragmas \
-Wno-use-after-free \
")
```