### Example: Constant Velocity Motor Setup Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/constraints.md Provides a complete example of configuring a constraint axis to operate as a constant velocity motor. This includes setting the motor type, the desired velocity target, and the maximum force the motor can exert. ```javascript // Constant velocity motor havok.HP_Constraint_SetAxisMotorType(constraintId, havok.ConstraintAxis.ANGULAR_Z, havok.ConstraintMotorType.VELOCITY); havok.HP_Constraint_SetAxisMotorVelocityTarget(constraintId, havok.ConstraintAxis.ANGULAR_Z, Math.PI); // π rad/s havok.HP_Constraint_SetAxisMotorMaxForce(constraintId, havok.ConstraintAxis.ANGULAR_Z, 100.0); ``` -------------------------------- ### Full Body Setup Example Source: https://github.com/babylonjs/havok/blob/main/_autodocs/configuration.md Demonstrates the complete process of creating a physics body, setting its shape, motion type, mass properties, damping, gravity, initial position, and finally adding it to the physics world. ```javascript const [result, bodyId] = havok.HP_Body_Create(); // Set shape const [shapeResult, shapeId] = havok.HP_Shape_CreateSphere([0, 0, 0], 1.0); havok.HP_Body_SetShape(bodyId, shapeId); // Set motion type havok.HP_Body_SetMotionType(bodyId, havok.MotionType.DYNAMIC); // Set mass properties const [massResult, massProps] = havok.HP_Shape_BuildMassProperties(shapeId); havok.HP_Body_SetMassProperties(bodyId, massProps); // Configure physics havok.HP_Body_SetLinearDamping(bodyId, 0.05); havok.HP_Body_SetAngularDamping(bodyId, 0.1); havok.HP_Body_SetGravityFactor(bodyId, 1.0); // Set initial position havok.HP_Body_SetPosition(bodyId, [0, 5, 0]); // Add to world havok.HP_World_AddBody(worldId, bodyId, false); ``` -------------------------------- ### Start Demo Project Source: https://github.com/babylonjs/havok/blob/main/packages/demo/README.md Execute this command in the main repository directory to start the demo project. This command targets the specific demo package. ```bash npm start -w @babylonjs/havok-demo ``` -------------------------------- ### Install Dependencies Source: https://github.com/babylonjs/havok/blob/main/packages/demo/README.md Run this command in the main repository directory to install all project dependencies. ```bash npm install ``` -------------------------------- ### Example: Find Contact Points Between Shapes Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/queries.md This example demonstrates how to perform a shape proximity query and then iterate through the results to find contact points and distances between shapes. It includes setup for shapes and collectors, executing the query, and processing the results. ```javascript const [testShapeResult, testShapeId] = havok.HP_Shape_CreateSphere([0, 0, 0], 1.0); const [collectorResult, collectorId] = havok.HP_QueryCollector_Create(10); const proximityQuery = [ testShapeId, // Shape to query [0, 5, 0], // Position [0, 0, 0, 1], // Rotation 100, // Max distance false, // Ignore triggers [0n] ]; havok.HP_World_ShapeProximityWithCollector(worldId, collectorId, proximityQuery); const [numResult, numHits] = havok.HP_QueryCollector_GetNumHits(collectorId); for (let i = 0; i < numHits; i++) { const [hitResult, result] = havok.HP_QueryCollector_GetShapeProximityResult(collectorId, i); const distance = result[0]; const pointInInputShape = result[1][3]; // Position in query shape space const pointInWorld = result[2][3]; // Position in world space if (distance < 0) { console.log(`Penetration: ${-distance}m`); } else { console.log(`Gap: ${distance}m`); } } havok.HP_Shape_Release(testShapeId); havok.HP_QueryCollector_Release(collectorId); ``` -------------------------------- ### Create Physics Scene with Havok Source: https://github.com/babylonjs/havok/blob/main/_autodocs/configuration.md Initializes Havok Physics, creates a physics world, and adds a static ground and a dynamic sphere. This is a complete setup example. ```javascript async function createPhysicsScene() { // Initialize Havok const havok = await HavokPhysics(); // Create world const [worldResult, worldId] = havok.HP_World_Create(); havok.HP_World_SetGravity(worldId, [0, -9.81, 0]); havok.HP_World_SetIdealStepTime(worldId, 1/60); havok.HP_World_SetSpeedLimit(worldId, 100, Math.PI * 10); // Create ground const [groundShapeResult, groundShapeId] = havok.HP_Shape_CreateBox( [0, 0, 0], [0, 0, 0, 1], [10, 0.5, 10] ); havok.HP_Shape_SetMaterial(groundShapeId, [0.5, 0.5, 0.0, havok.MaterialCombine.GEOMETRIC_MEAN, havok.MaterialCombine.GEOMETRIC_MEAN]); const [groundBodyResult, groundBodyId] = havok.HP_Body_Create(); havok.HP_Body_SetShape(groundBodyId, groundShapeId); havok.HP_Body_SetMotionType(groundBodyId, havok.MotionType.STATIC); havok.HP_Body_SetPosition(groundBodyId, [0, 0, 0]); havok.HP_World_AddBody(worldId, groundBodyId, true); // Create dynamic sphere const [sphereShapeResult, sphereShapeId] = havok.HP_Shape_CreateSphere([0, 0, 0], 1.0); havok.HP_Shape_SetDensity(sphereShapeId, 1000); havok.HP_Shape_SetMaterial(sphereShapeId, [0.3, 0.2, 0.8, havok.MaterialCombine.GEOMETRIC_MEAN, havok.MaterialCombine.GEOMETRIC_MEAN]); const [sphereBodyResult, sphereBodyId] = havok.HP_Body_Create(); havok.HP_Body_SetShape(sphereBodyId, sphereShapeId); havok.HP_Body_SetMotionType(sphereBodyId, havok.MotionType.DYNAMIC); const [massResult, massProps] = havok.HP_Shape_BuildMassProperties(sphereShapeId); havok.HP_Body_SetMassProperties(sphereBodyId, massProps); havok.HP_Body_SetLinearDamping(sphereBodyId, 0.05); havok.HP_Body_SetAngularDamping(sphereBodyId, 0.1); havok.HP_Body_SetPosition(sphereBodyId, [0, 5, 0]); havok.HP_World_AddBody(worldId, sphereBodyId, false); return { havok, worldId }; } ``` -------------------------------- ### Minimal Havok Physics Example Source: https://github.com/babylonjs/havok/blob/main/_autodocs/INDEX.md A basic example showing the initialization of Havok Physics, creation of a world, a sphere shape, a dynamic body, setting its properties, adding it to the world, and stepping the simulation. ```APIDOC ## Minimal Example ### Description This example demonstrates the basic setup and usage of Havok Physics, including world creation, object manipulation, and simulation stepping. ### Code ```javascript import HavokPhysics from "@babylonjs/havok"; // Initialize const havok = await HavokPhysics(); // Create world const [worldRes, worldId] = havok.HP_World_Create(); havok.HP_World_SetGravity(worldId, [0, -9.81, 0]); // Create sphere const [shapeRes, shapeId] = havok.HP_Shape_CreateSphere([0, 0, 0], 1.0); // Create body const [bodyRes, bodyId] = havok.HP_Body_Create(); havok.HP_Body_SetShape(bodyId, shapeId); havok.HP_Body_SetMotionType(bodyId, havok.MotionType.DYNAMIC); // Set mass const [massRes, massProps] = havok.HP_Shape_BuildMassProperties(shapeId); havok.HP_Body_SetMassProperties(bodyId, massProps); // Add to world havok.HP_World_AddBody(worldId, bodyId, false); // Step simulation havok.HP_World_Step(worldId, 1/60); // Query position const [posRes, pos] = havok.HP_Body_GetPosition(bodyId); ``` ``` -------------------------------- ### Initialize Havok Physics Source: https://github.com/babylonjs/havok/blob/main/_autodocs/INDEX.md Demonstrates how to import and initialize the HavokPhysics factory function to get access to the physics engine bindings. ```APIDOC ## Initialize Havok Physics ### Description Import and initialize the HavokPhysics factory function to obtain the physics engine bindings. ### Method ```javascript await HavokPhysics() ``` ### Returns - `Promise`: A promise that resolves with the Havok physics engine instance. ``` -------------------------------- ### Hinge Joint Configuration Example Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/constraints.md Configures a hinge joint by locking all linear axes and two angular axes, while freeing the remaining angular axis for rotation. This is a common setup for doors or limbs. ```javascript // Lock all translation havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.LINEAR_X, havok.ConstraintAxisLimitMode.LOCKED); havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.LINEAR_Y, havok.ConstraintAxisLimitMode.LOCKED); havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.LINEAR_Z, havok.ConstraintAxisLimitMode.LOCKED); // Lock 2 angular axes havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.ANGULAR_X, havok.ConstraintAxisLimitMode.LOCKED); havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.ANGULAR_Y, havok.ConstraintAxisLimitMode.LOCKED); // Free hinge axis havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.ANGULAR_Z, havok.ConstraintAxisLimitMode.FREE); ``` -------------------------------- ### Start Debug Recording - JavaScript Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/worlds-and-simulation.md Begins performance counter recording for physics objects. This functionality is only available in development builds of Havok. ```javascript HP_Debug_StartRecordingStats(world: HP_WorldId): Result ``` -------------------------------- ### Example: Linear and Angular Max Force Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/constraints.md Illustrates setting the maximum force for both linear and angular motors. The first example shows setting a maximum force of 1000 Newtons for a linear axis, while the second sets a maximum torque of 100 Newton-meters for an angular axis. ```javascript // Motor can apply up to 1000 N of force havok.HP_Constraint_SetAxisMotorMaxForce(constraintId, havok.ConstraintAxis.LINEAR_X, 1000.0); // Motor can apply up to 100 N·m of torque havok.HP_Constraint_SetAxisMotorMaxForce(constraintId, havok.ConstraintAxis.ANGULAR_Z, 100.0); ``` -------------------------------- ### Integrate Havok Physics with Babylon.js Scene Source: https://github.com/babylonjs/havok/blob/main/_autodocs/INDEX.md Example showing how to enable Havok Physics for a Babylon.js scene using the HavokPlugin. This requires importing both HavokPhysics and the HavokPlugin. ```javascript import HavokPhysics from "@babylonjs/havok"; import { HavokPlugin } from "@babylonjs/core/Physics/v2/Plugins/havokPlugin"; const havok = await HavokPhysics(); const plugin = new HavokPlugin(undefined, havok); scene.enablePhysics(new Vector3(0, -9.81, 0), plugin); // Use scene.physicsEnabled() to check ``` -------------------------------- ### Configure Hinge Joint Constraint Source: https://github.com/babylonjs/havok/blob/main/_autodocs/configuration.md Example of creating and configuring a hinge joint. It attaches bodies, sets pivot points and axes, and defines rotational limits. ```javascript const [result, constraintId] = havok.HP_Constraint_Create(); // Attach to bodies havok.HP_Constraint_SetParentBody(constraintId, bodyA); havok.HP_Constraint_SetChildBody(constraintId, bodyB); // Position hinge in parent space havok.HP_Constraint_SetAnchorInParent( constraintId, [0, 0, 0], // pivot [1, 0, 0], // axisX [0, 1, 0] // axisY (Z is computed) ); // Position hinge in child space havok.HP_Constraint_SetAnchorInChild( constraintId, [0, 0, 0], [1, 0, 0], [0, 1, 0] ); // Hinge rotation (lock X and Y, free Z) havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.LINEAR_X, havok.ConstraintAxisLimitMode.LOCKED); havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.LINEAR_Y, havok.ConstraintAxisLimitMode.LOCKED); havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.LINEAR_Z, havok.ConstraintAxisLimitMode.LOCKED); havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.ANGULAR_X, havok.ConstraintAxisLimitMode.LOCKED); havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.ANGULAR_Y, havok.ConstraintAxisLimitMode.LOCKED); havok.HP_Constraint_SetAxisMode(constraintId, havok.ConstraintAxis.ANGULAR_Z, havok.ConstraintAxisLimitMode.FREE); havok.HP_Constraint_SetEnabled(constraintId, 1); ``` -------------------------------- ### Tunnel Detection for Character Movement Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/queries.md This example demonstrates how to use shape casting to detect obstacles in the path of a character, calculating the allowable movement distance before a collision. ```javascript const [sweepShapeResult, sweepShapeId] = havok.HP_Shape_CreateCapsule([0, 0, 0], [0, 2, 0], 0.5); const [collectorResult, collectorId] = havok.HP_QueryCollector_Create(10); // Sweep character ahead to detect obstacles const characterPos = [0, 1, 0]; const moveDirection = [0, 0, 10]; // Move 10m forward const castQuery = [ sweepShapeId, // Character shape [0, 0, 0, 1], // Rotation characterPos, // Start position [characterPos[0] + moveDirection[0], characterPos[1] + moveDirection[1], characterPos[2] + moveDirection[2]], // End position false, // Ignore triggers [0n] ]; havok.HP_World_ShapeCastWithCollector(worldId, collectorId, castQuery); const [numResult, numHits] = havok.HP_QueryCollector_GetNumHits(collectorId); if (numHits > 0) { const [hitResult, result] = havok.HP_QueryCollector_GetShapeCastResult(collectorId, 0); const fraction = result[0]; const allowableDistance = fraction * 10; // How far character can move console.log(`Can move ${allowableDistance}m before collision`); // Move character to collision point const safePos = [ characterPos[0] + moveDirection[0] * fraction * 0.99, // Slight buffer characterPos[1] + moveDirection[1] * fraction * 0.99, characterPos[2] + moveDirection[2] * fraction * 0.99 ]; console.log(`Safe position: ${safePos}`); } havok.HP_Shape_Release(sweepShapeId); havok.HP_QueryCollector_Release(collectorId); ``` -------------------------------- ### Get Physics Statistics - JavaScript Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/worlds-and-simulation.md Retrieves current memory allocation statistics for all physics objects. Use this to monitor memory usage. ```javascript const [result, stats] = havok.HP_GetStatistics(); console.log(`Bodies: ${stats[0]}, Shapes: ${stats[1]}, Constraints: ${stats[2]}`); ``` -------------------------------- ### Handle Trigger Events Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/worlds-and-simulation.md Iterate through all trigger events from the last simulation step. Use HP_World_GetTriggerEvents to get the first event and HP_World_GetNextTriggerEvent to retrieve subsequent events. ```javascript let [eventResult, eventId] = havok.HP_World_GetTriggerEvents(worldId); while (eventId !== 0) { const [asTriggerResult, trigger] = havok.HP_Event_AsTrigger(eventId); if (trigger[0] === havok.EventType.TRIGGER_ENTERED) { console.log("Body entered trigger"); } // Next event [eventId] = havok.HP_World_GetNextTriggerEvent(worldId, eventId); } ``` -------------------------------- ### Vehicle Collision Prediction Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/queries.md This example shows how to predict potential collisions for a vehicle by performing a shape cast over a look-ahead time, identifying imminent collisions. ```javascript const [vehicleShapeResult, vehicleShapeId] = havok.HP_Shape_CreateBox( [0, 0, 0], [0, 0, 0, 1], [1, 0.5, 2] ); const [collectorResult, collectorId] = havok.HP_QueryCollector_Create(50); const vehiclePos = [0, 1, 0]; const velocity = [20, 0, 0]; // 20 m/s const lookAheadTime = 1.0; // 1 second look-ahead const castQuery = [ vehicleShapeId, [0, 0, 0, 1], vehiclePos, [vehiclePos[0] + velocity[0] * lookAheadTime, vehiclePos[1] + velocity[1] * lookAheadTime, vehiclePos[2] + velocity[2] * lookAheadTime], false, [0n] ]; havok.HP_World_ShapeCastWithCollector(worldId, collectorId, castQuery); const [numResult, numHits] = havok.HP_QueryCollector_GetNumHits(collectorId); for (let i = 0; i < numHits; i++) { const [hitResult, result] = havok.HP_QueryCollector_GetShapeCastResult(collectorId, i); const fraction = result[0]; const distanceToCollision = fraction * (velocity[0] * lookAheadTime); const timeToCollision = (fraction * lookAheadTime); if (timeToCollision < 0.1) { // Collision within 100ms console.log("Imminent collision! Apply brakes!"); } } ``` -------------------------------- ### Handle Collision Events Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/worlds-and-simulation.md Iterate through all collision events from the last simulation step. Use HP_World_GetCollisionEvents to get the first event and HP_World_GetNextCollisionEvent to retrieve subsequent events. ```javascript let [eventResult, eventId] = havok.HP_World_GetCollisionEvents(worldId); while (eventId !== 0) { const [asCollisionResult, collision] = havok.HP_Event_AsCollision(eventId); console.log(`Collision with impulse: ${collision[3]}`); // Next event [eventId] = havok.HP_World_GetNextCollisionEvent(worldId, eventId); } ``` -------------------------------- ### Lock All Linear Axes Example Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/constraints.md Locks all three linear axes of a constraint, preventing any translation. This is often a starting point for many joint types. ```javascript // Lock all linear axes for (let axis = 0; axis < 3; axis++) { havok.HP_Constraint_SetAxisMode( constraintId, axis, havok.ConstraintAxisLimitMode.LOCKED ); } // Free all angular axes for (let axis = 3; axis < 6; axis++) { havok.HP_Constraint_SetAxisMode( constraintId, axis, havok.ConstraintAxisLimitMode.FREE ); } ``` -------------------------------- ### Initialize and Use Havok Physics Source: https://github.com/babylonjs/havok/blob/main/_autodocs/INDEX.md Minimal example demonstrating how to initialize Havok Physics, create a world, a sphere shape, a dynamic body, and step the simulation. Ensure the Havok WASM module is available. ```javascript import HavokPhysics from "@babylonjs/havok"; // Initialize const havok = await HavokPhysics(); // Create world const [worldRes, worldId] = havok.HP_World_Create(); havok.HP_World_SetGravity(worldId, [0, -9.81, 0]); // Create sphere const [shapeRes, shapeId] = havok.HP_Shape_CreateSphere([0, 0, 0], 1.0); // Create body const [bodyRes, bodyId] = havok.HP_Body_Create(); havok.HP_Body_SetShape(bodyId, shapeId); havok.HP_Body_SetMotionType(bodyId, havok.MotionType.DYNAMIC); // Set mass const [massRes, massProps] = havok.HP_Shape_BuildMassProperties(shapeId); havok.HP_Body_SetMassProperties(bodyId, massProps); // Add to world havok.HP_World_AddBody(worldId, bodyId, false); // Step simulation havok.HP_World_Step(worldId, 1/60); // Query position const [posRes, pos] = havok.HP_Body_GetPosition(bodyId); ``` -------------------------------- ### Dynamic Object Setup in Havok Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/index.md Illustrates the process of setting up a dynamic physics object, including creating a shape, body, setting properties like density and motion type, and adding it to the world. This pattern is essential for simulating dynamic entities. ```javascript const [shapeRes, shapeId] = havok.HP_Shape_CreateSphere([0, 0, 0], 1.0); havok.HP_Shape_SetDensity(shapeId, 1000); const [bodyRes, bodyId] = havok.HP_Body_Create(); havok.HP_Body_SetShape(bodyId, shapeId); havok.HP_Body_SetMotionType(bodyId, havok.MotionType.DYNAMIC); const [massRes, massProps] = havok.HP_Shape_BuildMassProperties(shapeId); havok.HP_Body_SetMassProperties(bodyId, massProps); havok.HP_Body_SetLinearDamping(bodyId, 0.05); havok.HP_Body_SetAngularDamping(bodyId, 0.1); havok.HP_World_AddBody(worldId, bodyId, false); ``` -------------------------------- ### Initialize and Use Havok Physics Engine Source: https://github.com/babylonjs/havok/blob/main/_autodocs/00_START_HERE.md This snippet demonstrates the basic initialization of the Havok Physics engine, setting up a world with gravity, creating a sphere shape and body, setting its mass and motion type, adding it to the world, and stepping the simulation. ```javascript import HavokPhysics from "@babylonjs/havok"; // Initialize const havok = await HavokPhysics(); // Create world with gravity const [worldRes, worldId] = havok.HP_World_Create(); havok.HP_World_SetGravity(worldId, [0, -9.81, 0]); // Create a sphere const [shapeRes, shapeId] = havok.HP_Shape_CreateSphere([0, 0, 0], 1.0); // Create a body const [bodyRes, bodyId] = havok.HP_Body_Create(); havok.HP_Body_SetShape(bodyId, shapeId); havok.HP_Body_SetMotionType(bodyId, havok.MotionType.DYNAMIC); // Set mass const [massRes, massProps] = havok.HP_Shape_BuildMassProperties(shapeId); havok.HP_Body_SetMassProperties(bodyId, massProps); // Add to world havok.HP_World_AddBody(worldId, bodyId, false); // Step simulation havok.HP_World_Step(worldId, 1/60); ``` -------------------------------- ### Basic Havok Initialization Source: https://github.com/babylonjs/havok/blob/main/_autodocs/configuration.md A robust way to initialize Havok Physics, including error handling for the asynchronous loading and initialization process. ```javascript async function initializePhysics() { try { const havok = await HavokPhysics(); console.log("Havok initialized successfully"); return havok; } catch (error) { console.error("Failed to initialize Havok:", error); return null; } } const havok = await initializePhysics(); ``` -------------------------------- ### HP_Shape_GetType Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/shapes.md Gets the type of shape (COLLIDER or CONTAINER). ```APIDOC ## HP_Shape_GetType ### Description Gets the type of shape (COLLIDER or CONTAINER). ### Method ```javascript HP_Shape_GetType(shape: HP_ShapeId): [Result, ShapeType] ``` ### Parameters * **shape** (HP_ShapeId) - Required - Shape to query ### Returns * **[Result, ShapeType]** - Result and shape type ### Example ```javascript const [result, type] = havok.HP_Shape_GetType(shapeId); if (type === havok.ShapeType.CONTAINER) { console.log("This is a container shape"); } ``` ``` -------------------------------- ### HP_Constraint_GetAxisMode Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/constraints.md Gets the limit mode for a specified axis of a constraint. ```APIDOC ## HP_Constraint_GetAxisMode ### Description Gets the limit mode for a specified axis of a constraint. ### Method ```javascript HP_Constraint_GetAxisMode(constraint: HP_ConstraintId, axis: ConstraintAxis): [Result, ConstraintAxisLimitMode] ``` ### Parameters #### Path Parameters - **constraint** (HP_ConstraintId) - Required - Constraint to configure - **axis** (ConstraintAxis) - Required - Axis to query ### Returns - **[Result, ConstraintAxisLimitMode]** ``` -------------------------------- ### Get Shape Density Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/shapes.md Retrieves the density value of a shape. ```javascript HP_Shape_GetDensity(shapeId: HP_ShapeId): [Result, number] ``` -------------------------------- ### Import Havok Physics Source: https://github.com/babylonjs/havok/blob/main/packages/havok/README.md Import the HavokPhysics module into your project. This is the first step to using the library. ```javascript import HavokPhysics from "@babylonjs/havok"; ``` -------------------------------- ### Get Body Position Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/bodies.md Retrieves the current world-space position of a body. ```javascript HP_Body_GetPosition(bodyId: HP_BodyId): [Result, Vector3] ``` -------------------------------- ### Havok Physics Quick Reference Source: https://github.com/babylonjs/havok/blob/main/_autodocs/READING_ORDER.md This cheat sheet provides essential code snippets for setting up and interacting with Havok Physics, including world creation, gravity configuration, body and shape creation, adding bodies to the world, stepping the simulation, and retrieving body positions. ```javascript const havok = await HavokPhysics(); const [res, worldId] = havok.HP_World_Create(); havok.HP_World_SetGravity(worldId, [0, -9.81, 0]); ``` ```javascript const [shapeRes, shapeId] = havok.HP_Shape_CreateSphere([0,0,0], 1); const [bodyRes, bodyId] = havok.HP_Body_Create(); havok.HP_Body_SetShape(bodyId, shapeId); havok.HP_Body_SetMotionType(bodyId, havok.MotionType.DYNAMIC); ``` ```javascript havok.HP_World_AddBody(worldId, bodyId, false); ``` ```javascript havok.HP_World_Step(worldId, 1/60); ``` ```javascript const [res, pos] = havok.HP_Body_GetPosition(bodyId); ``` -------------------------------- ### HP_Shape_GetBoundingBox Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/shapes.md Gets axis-aligned bounding box for a shape at a given transform. ```APIDOC ## HP_Shape_GetBoundingBox ### Description Gets axis-aligned bounding box for a shape at a given transform. ### Method ```javascript HP_Shape_GetBoundingBox(shape: HP_ShapeId, worldFromShape: QTransform): [Result, Aabb] ``` ### Parameters #### Path Parameters * **shape** (HP_ShapeId) - Required - Shape to query * **worldFromShape** (QTransform) - Required - [translation, rotation] of shape in world space ### Returns * **[Result, Aabb]** - Result and [[minX, minY, minZ], [maxX, maxY, maxZ]] ### Example ```javascript const transform = [[0, 1, 0], [0, 0, 0, 1]]; // At height 1, no rotation const [result, aabb] = havok.HP_Shape_GetBoundingBox(shapeId, transform); console.log(`Min: ${aabb[0]}, Max: ${aabb[1]}`); ``` ``` -------------------------------- ### Integrate Physics Stepping into Game Loop Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/worlds-and-simulation.md This example demonstrates how to integrate the HP_World_Step function into a game loop for continuous physics simulation. It handles accumulating delta time and stepping the physics world at a fixed rate. ```javascript const havok = await HavokPhysics(); const [result, worldId] = havok.HP_World_Create(); havok.HP_World_SetGravity(worldId, [0, -9.81, 0]); // Main game loop const timeStep = 1/60; // 60 Hz let lastTime = Date.now() / 1000; function gameLoop() { const now = Date.now() / 1000; const deltaTime = now - lastTime; lastTime = now; // Step physics (may step multiple times for large deltas) let accumulator = 0; accumulator += deltaTime; while (accumulator >= timeStep) { const stepResult = havok.HP_World_Step(worldId, timeStep); if (stepResult !== havok.Result.RESULT_OK) { console.error("Physics step failed"); } accumulator -= timeStep; } // Render scene updateGraphics(); requestAnimationFrame(gameLoop); } gameLoop(); ``` -------------------------------- ### Initialize Havok Physics Source: https://github.com/babylonjs/havok/blob/main/_autodocs/README.md Import and initialize the Havok physics engine. This is the default export and returns a promise that resolves to the physics interface. ```javascript import HavokPhysics from "@babylonjs/havok"; const havokInterface = await HavokPhysics(); ``` -------------------------------- ### Get Shape Type Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/shapes.md Retrieves the type of a shape (COLLIDER or CONTAINER). ```typescript HP_Shape_GetType(shape: HP_ShapeId): [Result, ShapeType] ``` ```javascript const [result, type] = havok.HP_Shape_GetType(shapeId); if (type === havok.ShapeType.CONTAINER) { console.log("This is a container shape"); } ``` -------------------------------- ### Get Body Orientation Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/bodies.md Retrieves the current world-space rotation of a body as a quaternion. ```javascript HP_Body_GetOrientation(bodyId: HP_BodyId): [Result, Quaternion] ``` -------------------------------- ### Get Angular Velocity of a Body Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/bodies.md Retrieves the current angular velocity of a specified body. ```javascript HP_Body_GetAngularVelocity(bodyId: HP_BodyId): [Result, Vector3] ``` -------------------------------- ### Initialization Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/index.md Before using any physics functions, initialize the Havok module. The returned object extends Emscripten's EmscriptenModule interface. ```APIDOC ## Initialization Before using any physics functions, initialize the Havok module: ```javascript import HavokPhysics from "@babylonjs/havok"; const havok = await HavokPhysics(); // Now access functions and enumerations via havok object const [result, shapeId] = havok.HP_Shape_CreateSphere([0, 0, 0], 1.0); ``` The returned object is of type `HavokPhysicsWithBindings` and extends Emscripten's `EmscriptenModule` interface. ``` -------------------------------- ### Get Body Motion Type Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/bodies.md Retrieves the current motion type of a specified body. ```javascript HP_Body_GetMotionType(bodyId: HP_BodyId): [Result, MotionType] ``` -------------------------------- ### Initialize HavokPhysics Factory Function Source: https://github.com/babylonjs/havok/blob/main/_autodocs/configuration.md Use this async factory function to load and initialize the WebAssembly module for Havok Physics. It returns a singleton interface with all physics functions. ```javascript import HavokPhysics from "@babylonjs/havok"; const havokInterface = await HavokPhysics(); ``` -------------------------------- ### Initialize Havok Physics Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/index.md Import and initialize the Havok physics module before accessing its functions. The initialization returns a HavokPhysicsWithBindings object. ```javascript import HavokPhysics from "@babylonjs/havok"; const havok = await HavokPhysics(); // Now access functions and enumerations via havok object const [result, shapeId] = havok.HP_Shape_CreateSphere([0, 0, 0], 1.0); ``` -------------------------------- ### Get Shape Material Properties Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/shapes.md Retrieves the material properties (friction, restitution) of a shape. ```javascript HP_Shape_GetMaterial(shapeId: HP_ShapeId): [Result, PhysicsMaterial] ``` -------------------------------- ### Example: Motorized Hinge Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/constraints.md Demonstrates setting up a hinge constraint to spin at a constant angular velocity. This involves setting the motor type to VELOCITY, defining the target velocity, and specifying the maximum force the motor can apply. ```javascript // Motor to spin hinge at constant velocity havok.HP_Constraint_SetAxisMotorType( hingeConstraintId, havok.ConstraintAxis.ANGULAR_Z, havok.ConstraintMotorType.VELOCITY ); havok.HP_Constraint_SetAxisMotorVelocityTarget( hingeConstraintId, havok.ConstraintAxis.ANGULAR_Z, Math.PI // 180° per second ); havok.HP_Constraint_SetAxisMotorMaxForce( hingeConstraintId, havok.ConstraintAxis.ANGULAR_Z, 100.0 ); ``` -------------------------------- ### Get Shape Collision Filter Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/shapes.md Retrieves the collision filter properties for a given shape. ```javascript HP_Shape_GetFilterInfo(shapeId: HP_ShapeId): [Result, FilterInfo] ``` -------------------------------- ### Get Body Transform (Position and Rotation) Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/bodies.md Retrieves the current world-space position and rotation of a body. ```javascript const [result, transform] = havok.HP_Body_GetQTransform(bodyId); console.log(`Position: ${transform[0]}`); console.log(`Rotation: ${transform[1]}`); ``` -------------------------------- ### Project File Structure Source: https://github.com/babylonjs/havok/blob/main/_autodocs/INDEX.md This code block illustrates the directory and file organization for the Babylon.js Havok physics integration project. ```tree /workspace/home/output/ ├── INDEX.md # This file ├── README.md # Project overview ├── types.md # Type definitions ├── errors.md # Error codes and handling ├── configuration.md # Setup and configuration └── api-reference/ ├── index.md # Navigation guide ├── shapes.md # Shape API (32 functions) ├── bodies.md # Body API (36 functions) ├── worlds-and-simulation.md # World API (28 functions) ├── constraints.md # Constraint API (39 functions) └── queries.md # Query Collector API (8 functions) ``` -------------------------------- ### Retrieve First-Hit Raycast Result Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/queries.md Demonstrates how to perform a raycast and retrieve the first hit result. Ensure the collector is created with sufficient capacity and released afterward. ```javascript const [collectorResult, collectorId] = havok.HP_QueryCollector_Create(1); const rayQuery = [ [0, 5, 0], // Ray start [0, 5, 100], // Ray end [0xFFFFFFFF, 0xFFFFFFFF], // Hit all false, // Ignore triggers [0n] // No body to ignore ]; havok.HP_World_CastRayWithCollector(worldId, collectorId, rayQuery); const [numResult, numHits] = havok.HP_QueryCollector_GetNumHits(collectorId); if (numHits > 0) { const [hitResult, hit] = havok.HP_QueryCollector_GetCastRayResult(collectorId, 0); const fraction = hit[0]; // 0.0-1.0 along ray const contact = hit[1]; // ContactPoint // Compute actual world position const rayStart = [0, 5, 0]; const rayEnd = [0, 5, 100]; const hitPos = [ rayStart[0] + (rayEnd[0] - rayStart[0]) * fraction, rayStart[1] + (rayEnd[1] - rayStart[1]) * fraction, rayStart[2] + (rayEnd[2] - rayStart[2]) * fraction ]; console.log(`Ray hit at position: ${hitPos}`); console.log(`Hit body: ${contact[0]}, Shape: ${contact[1]}`); console.log(`Normal: ${contact[4]}`); } havok.HP_QueryCollector_Release(collectorId); ``` -------------------------------- ### Get Damping of Constraint Axis Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/constraints.md Retrieves the damping coefficient of a spring-damper system configured on a constraint axis. ```javascript HP_Constraint_GetAxisDamping(constraint: HP_ConstraintId, axis: ConstraintAxis): [Result, number] ``` -------------------------------- ### Get Stiffness of Constraint Axis Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/constraints.md Retrieves the stiffness value of a spring-damper system configured on a constraint axis. ```javascript HP_Constraint_GetAxisStiffness(constraint: HP_ConstraintId, axis: ConstraintAxis): [Result, number] ``` -------------------------------- ### Get Friction for Constraint Axis Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/constraints.md Retrieves the current friction coefficient set for a specific constraint axis. ```javascript HP_Constraint_GetAxisFriction(constraint: HP_ConstraintId, axis: ConstraintAxis): [Result, number] ``` -------------------------------- ### Initialize Havok Physics Engine Source: https://github.com/babylonjs/havok/blob/main/packages/havok/README.md Initialize the Havok physics engine. This function returns a promise, so it should be called within an async function or handled with .then(). ```javascript const havokInterface = await HavokPhysics(); ``` -------------------------------- ### Get Child Body of Havok Constraint Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/constraints.md Retrieves the child body ID associated with a given constraint. ```javascript havok.HP_Constraint_GetChildBody(constraintId); ``` -------------------------------- ### Enable Havok Physics in Babylon.js Source: https://github.com/babylonjs/havok/blob/main/_autodocs/configuration.md Integrate Havok Physics into a Babylon.js scene by creating a HavokPlugin instance and enabling physics for the scene. Ensure HavokPhysics is awaited before creating the plugin. ```javascript import HavokPhysics from "@babylonjs/havok"; import { HavokPlugin } from "@babylonjs/core/Physics/v2/Plugins/havokPlugin"; async function enablePhysics(scene) { const havokInterface = await HavokPhysics(); const hk = new HavokPlugin(undefined, havokInterface); scene.enablePhysics(new Vector3(0, -9.81, 0), hk); return hk; } ``` -------------------------------- ### Retrieve All-Hits Raycast Results Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/queries.md Demonstrates how to perform a raycast and iterate through all hit results. Ensure the collector is created with a sufficient capacity to hold all potential hits. ```javascript const [collectorResult, collectorId] = havok.HP_QueryCollector_Create(100); // Same ray query but with larger capacity havok.HP_World_CastRayWithCollector(worldId, collectorId, rayQuery); const [numResult, numHits] = havok.HP_QueryCollector_GetNumHits(collectorId); for (let i = 0; i < numHits; i++) { const [hitResult, hit] = havok.HP_QueryCollector_GetCastRayResult(collectorId, i); console.log(`Hit ${i}: fraction=${hit[0]}, distance=${hit[0] * rayLength}`); } ``` -------------------------------- ### Get Parent Body of Havok Constraint Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/constraints.md Retrieves the parent body ID associated with a given constraint. ```javascript havok.HP_Constraint_GetParentBody(constraintId); ``` -------------------------------- ### Get Gravity Factor of a Body Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/bodies.md Retrieves the current gravity scaling factor applied to a specific body. ```javascript HP_Body_GetGravityFactor(bodyId: HP_BodyId): [Result, number] ``` -------------------------------- ### Create a Havok Physics World Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/worlds-and-simulation.md Creates a new physics world with default settings. Gravity can be configured after creation. ```javascript const [result, worldId] = havok.HP_World_Create(); if (result !== havok.Result.RESULT_OK) { throw new Error("Failed to create world"); } // Configure world havok.HP_World_SetGravity(worldId, [0, -9.81, 0]); ``` -------------------------------- ### Babylon.js Havok Project File Structure Source: https://github.com/babylonjs/havok/blob/main/_autodocs/SUMMARY.md This snippet shows the directory structure of the Babylon.js Havok project, illustrating the location of key documentation and API reference files. ```tree output/ ├── SUMMARY.md ← This file ├── INDEX.md ← Master index and navigation ├── README.md ← Project overview ├── types.md ← All type definitions ├── errors.md ← Error codes and handling ├── configuration.md ← Setup guide └── api-reference/ ├── index.md ← API navigation ├── shapes.md ← Shape functions ├── bodies.md ← Body functions ├── worlds-and-simulation.md ← World + query functions ├── constraints.md ← Constraint functions └── queries.md ← Query collector functions ``` -------------------------------- ### Get Shape from Havok Body Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/bodies.md HP_Body_GetShape retrieves the ID of the shape currently assigned to a specified body. ```javascript havok.HP_Body_GetShape(bodyId) ``` -------------------------------- ### Find Nearest Object with Point Proximity Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/queries.md Demonstrates how to perform a point proximity query and retrieve the closest object. This involves creating a collector, executing the query, and then fetching the first result. ```javascript const [collectorResult, collectorId] = havok.HP_QueryCollector_Create(1); const proximityQuery = [ [0, 2, 0], // Query point 50, // Max 50m away [0xFFFFFFFF, 0xFFFFFFFF], // Hit all false, // Ignore triggers [0n] // No body to ignore ]; havok.HP_World_PointProximityWithCollector(worldId, collectorId, proximityQuery); const [numResult, numHits] = havok.HP_QueryCollector_GetNumHits(collectorId); if (numHits > 0) { const [hitResult, result] = havok.HP_QueryCollector_GetPointProximityResult(collectorId, 0); const distance = result[0]; const contact = result[1]; console.log(`Nearest surface is ${distance}m away`); console.log(`Closest point: ${contact[3]}`); console.log(`Normal: ${contact[4]}`); } ``` -------------------------------- ### HP_World_GetCollisionEvents Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/worlds-and-simulation.md Retrieves the first collision event from the most recent simulation step. Use this to start iterating through all collision events. ```APIDOC ## HP_World_GetCollisionEvents ### Description Gets the first collision event from the last simulation step. ### Method ```javascript HP_World_GetCollisionEvents(world: HP_WorldId): [Result, number] ``` ### Returns `[Result, eventId]` — Event ID or 0 if no events ### Behavior Returns the first collision event. Use `HP_World_GetNextCollisionEvent()` to iterate through subsequent events. ### Example ```javascript let [eventResult, eventId] = havok.HP_World_GetCollisionEvents(worldId); while (eventId !== 0) { const [asCollisionResult, collision] = havok.HP_Event_AsCollision(eventId); console.log(`Collision with impulse: ${collision[3]}`); // Next event [eventId] = havok.HP_World_GetNextCollisionEvent(worldId, eventId); } ``` ``` -------------------------------- ### Set Shape Material Properties Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/shapes.md Sets the material properties, such as friction and restitution, for a shape. See configuration.md for material examples. ```javascript HP_Shape_SetMaterial(shapeId: HP_ShapeId, material: PhysicsMaterial): Result ``` -------------------------------- ### Get Body Activation State Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/bodies.md Retrieves the current activation state of a body, indicating whether it is currently active or inactive. ```javascript HP_Body_GetActivationState(bodyId: HP_BodyId): [Result, ActivationState] ``` -------------------------------- ### Object Lifetime Management in Havok Source: https://github.com/babylonjs/havok/blob/main/_autodocs/api-reference/index.md Demonstrates the standard lifecycle for managing physics objects in Havok, from creation to release. Ensure objects are released in the reverse order of their creation to prevent dangling references. ```javascript const [createResult, objectId] = havok.HP_Object_Create(); havok.HP_Object_SetProperty(objectId, value); havok.HP_World_AddObject(worldId, objectId); havok.HP_World_RemoveObject(worldId, objectId); const releaseResult = havok.HP_Object_Release(objectId); ```