diff --git a/README.md b/README.md index 64b0522..3a2c43a 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,6 @@ import { Vec3 } from "@bedrock-oss/bedrock-boost"; import { world } from "@minecraft/server"; world.beforeEvents.itemUse.subscribe((event) => { - event.source.applyImpulse(Vec3.from(event.source.getViewDirection()).setY(0).normalize().multiply(2)); }) @@ -79,6 +78,16 @@ Timings.begin("big operation 2"); Timings.end(); ``` +### ChatColor and ColorJSON classes + +```typescript +import { Logger } from "@bedrock-oss/bedrock-boost" + +const log = Logger.getLogger("main", "tag1", "tag2"); +log.info("Hello, Minecraft World!"); +``` +``` + ### Logger ```typescript diff --git a/docs/cache.md b/docs/cache.md new file mode 100644 index 0000000..4eda363 --- /dev/null +++ b/docs/cache.md @@ -0,0 +1,15 @@ +# Cache + +In Minecraft Bedrock Script API, native calls to the game engine are often costly and should be avoided when possible. For example, calling `world.getDimension()` in a loop will cause the script to get the dimension from the game engine for each iteration, which can be very slow. To avoid this, we can cache the dimension object. + +Currently, only the `Dimension` objects are cached, but more objects may be added in the future. + +## Usage + +The following example will get the dimension object for the overworld and cache it. If the dimension object is already cached, it will return the cached object. + +```typescript +import { getDimension } from "@bedrock-oss/bedrock-boost"; + +const dimension = getDimension("overworld"); +``` \ No newline at end of file diff --git a/docs/colorJson.md b/docs/colorJson.md new file mode 100644 index 0000000..22a0341 --- /dev/null +++ b/docs/colorJson.md @@ -0,0 +1,153 @@ +# ColorJSON + +## Overview + +The `ColorJSON` class is designed to transform various data types into a chat-friendly, colored JSON representation. It offers a range of customization options for the formatting and styling of JSON output. This documentation outlines how to use the `ColorJSON` class, including its properties and methods. + +### Key Features: + +- Color customization for different JSON elements. +- Inline threshold settings for compact JSON representation. +- Maximum depth control for object traversal. +- Class name inclusion in output. +- Ability to override methods for custom formatting. +- Cycle detection and handling. + +## Usage + +### Initialization + +```javascript +import ColorJSON from '@bedrock-oss/bedrock-boost'; +const jsonFormatter = new ColorJSON();// or use default instance `ColorJSON.DEFAULT` +``` + +### Basic JSON Stringification + +To convert a value to a colored JSON string: + +```javascript +const result = jsonFormatter.stringify(yourValue); +``` + +### Customization + +#### Tokens + +Customize JSON tokens like braces, brackets, comma, etc.: + +```javascript +jsonFormatter.OpenObject = '{'; +jsonFormatter.CloseObject = '}'; +// ...similarly for other tokens +``` + +#### Inline Threshold + +Set the inline threshold to control how short arrays and objects representation must be to be displayed inline: + +```javascript +jsonFormatter.InlineThreshold = 60; +``` +#### Maximum Depth + +Set the maximum depth to control how deep the object traversal must go: + +```javascript +jsonFormatter.MaxDepth = 5; // or 0 for unlimited +``` + + +#### Class Names + +Toggle inclusion of class names: + +```javascript +jsonFormatter.IncludeClassNames = true; // or false +``` + +#### Colors + +Customize colors for various elements: + +```javascript +jsonFormatter.OpenCloseObjectColor = ChatColor.YELLOW; +jsonFormatter.StringColor = ChatColor.DARK_GREEN; +// ...similarly for other color properties +``` + +### Customization through Method Overriding + +#### Overridable Methods + +The `ColorJSON` class contains several methods intended for overriding to customize the output. These methods handle the stringification of different data types and structural elements in JSON. + +- `stringifyString(value: string): string` +- `stringifyNumber(value: number): string` +- `stringifyBoolean(value: boolean): string` +- `stringifyFunction(value: function): string` +- `stringifyNull(): string` +- `stringifyUndefined(): string` +- `stringifyCycle(): string` +- `stringifyArray(value: any[]): string` +- `stringifyObject(value: object, className: string, entries: any[][], indentLevel: number): string` + +#### How to Override + +To override these methods, extend the `ColorJSON` class and redefine the methods as per your requirements. + +```javascript +class CustomColorJSON extends ColorJSON { + // Override methods here + stringifyString(value) { + // Custom implementation + } + + // ... other overrides +} +``` + +#### Example of Overriding + +```javascript +class MyColorJSON extends ColorJSON { + stringifyString(value) { + return `${this.StringColor}["${value}"]${ChatColor.RESET}`; + } + + stringifyNumber(value) { + return `${this.NumberColor}{${value}}${ChatColor.RESET}`; + } + // ... other method overrides +} +``` + +#### Using Customized Class + +```javascript +const jsonFormatter = new MyColorJSON(); +const result = jsonFormatter.stringify(yourValue); +``` + +### Cycle Detection and Handling + +The class automatically detects cycles within objects and arrays to prevent infinite loops. + +## Examples + +### Basic Example + +```javascript +const data = { name: "Alice", age: 30, active: true }; +const coloredJson = jsonFormatter.stringify(data); +world.sendMessage(coloredJson); +``` + +### Customized Example + +```javascript +jsonFormatter.StringColor = ChatColor.BLUE; +jsonFormatter.BooleanColor = ChatColor.RED; +const customColoredJson = jsonFormatter.stringify(data); +world.sendMessage(customColoredJson); +``` diff --git a/docs/logging.md b/docs/logging.md new file mode 100644 index 0000000..5749212 --- /dev/null +++ b/docs/logging.md @@ -0,0 +1,79 @@ +# Logging + +## Overview + +The logging system is designed to provide a flexible and efficient way to handle log messages in Minecraft Bedrock Script API. It leverages TypeScript to define log levels, color-coding, and message formatting, offering a customizable logging experience. + +## The `LogLevel` Class + +The `LogLevel` class is at the core of the logging system. It defines several log levels, each with a numerical level, name, and associated `ChatColor`. These levels include: + +- **All**: For logging all messages. +- **Trace**: Detailed information, useful for diagnosing problems. +- **Debug**: General debugging information. +- **Info**: General information about the script's operation. +- **Warn**: Warning messages about potential issues. +- **Error**: Error messages indicating problems that need attention. +- **Fatal**: Critical errors causing the script to abort. +- **Off**: Disables logging. + +## The `Logger` Class + +The `Logger` class is used for creating and managing loggers with specific names and tags. It provides methods for logging messages at different levels and configuring logging behavior. + +### Initialization + +The `init` method initializes the logging system, setting up commands and default settings. If not called, the system will initialize automatically when the first logger is created. + +### Configuration + +- **setLevel**: Sets the global logging level. By default, info and higher levels are enabled. +- **setFilter**: Sets a filter to control which loggers are active. By default, all loggers are active. +- **setFormatFunction**: Customizes how log messages are formatted. +- **setJsonFormatter**: Sets a JSON formatter for stringifying objects and arrays. By default, `ColorJSON.DEFAULT` is used. + +### Logging Methods + +Each log level has a corresponding method (`trace`, `debug`, `info`, `warn`, `error`, `fatal`) for logging messages. These methods internally use `log` and `logRaw` to process and display messages. + +## Usage + +To use the logging system, create a `Logger` instance with a specific name and tags. Then, use the appropriate logging methods (`info`, `warn`, `error`, etc.) to log messages. The system will handle formatting and display based on the configured settings. + +### Example + +```typescript +import { Logger } from "@bedrock-oss/bedrock-boost"; + +const logger = new Logger("myLogger", "myTag", "anotherTag"); + +logger.info("Hello, world!", { foo: "bar"}); +``` + +## Commands + +The logging system includes 2 commands to control the logging system: + +``` +scriptevent logger:level +scriptevent logger:filter +``` + +## Build Options + +When using esbuild, you can use `dropLabels` option with `LOGGING` label to remove all logging code from the final bundle. + +When using [gametests regolith filter](https://github.com/Bedrock-OSS/regolith-filters/tree/master/gametests), you can configure it like this: +```json +{ + "filter": "gametests", + "settings": { + "modules": [ + // ... + ], + "buildOptions": { + "dropLabels": ["LOGGING"] + } + } +} +``` \ No newline at end of file diff --git a/docs/profilingDummy.md b/docs/profilingDummy.md new file mode 100644 index 0000000..9892f03 --- /dev/null +++ b/docs/profilingDummy.md @@ -0,0 +1,15 @@ +# Profiling dummy + +Currently, when profiling a script, the profiler will group the time spent on waiting for the next tick into the last native call. This is not very useful, as it might make it seem like the last native call took a long time, when in reality it was just waiting for the next tick. + +To avoid this, we can use a dummy function and group the time spent on waiting for the next tick into that function. This will make the profiler more accurate. + +## Usage + +Make sure to make this call as late as possible in your script. This is in hopes, that the dummy will be called last in the tick, and therefore will group all the time spent on waiting for the next tick. + +```typescript +import { addIdleDummy } from "@bedrock-oss/bedrock-boost"; + +addIdleDummy(); +``` \ No newline at end of file diff --git a/docs/vec3.md b/docs/vec3.md new file mode 100644 index 0000000..20f2c2d --- /dev/null +++ b/docs/vec3.md @@ -0,0 +1,107 @@ +# Vec3 Class Documentation + +## Overview +`Vec3` is a versatile class designed for representing and manipulating 3-dimensional vectors in a Minecraft Bedrock Script API. This class offers a wide range of functionalities, including basic vector arithmetic, vector transformations, and utility functions for calculating properties like distance and angle between vectors. + +## Immutable + +`Vec3` instances are immutable, meaning that operations like `add` and `subtract` will return a new `Vec3` instance rather than modifying the original instance. This is to prevent unexpected behavior and side effects. + +> :warning: Setting the x, y, or z component of a vector directly will actually change the original vector. + +## Constructor +### `constructor(x, y, z)` +Constructs a `Vec3` object from various input types: +- **x**: Can be a `Vector3`, `Vec3`, `Direction`, an array of numbers `[x, y, z]`, or a single numeric value representing the x-coordinate. +- **y**: (Optional) The y-coordinate (required if x is a number). +- **z**: (Optional) The z-coordinate (required if x is a number). + +Directional vectors (Up, Down, North, South, East, West) are also supported. + +## Static Methods +### `static from(x, y, z)` +Creates a new `Vec3` instance from various inputs, similar to the constructor. + +### `static fromYawPitch(yaw, pitch)` +Creates a new direction vector from the given yaw and pitch values (in degrees). + +## Instance Methods +### `toVector()` +Converts the `Vec3` instance to the server's native `Vector` class if available, otherwise uses a polyfill. + +### `copy()` +Returns a new `Vec3` instance with the same x, y, z values. + +### `add(v)` +Adds another vector to the current vector and returns the result. + +### `subtract(v)` +Subtracts another vector from the current vector and returns the result. + +### `multiply(v)` +Multiplies the current vector by another vector or scalar and returns the result. + +### `divide(v)` +Divides the current vector by another vector or scalar and returns the result. + +### `normalize()` +Normalizes the vector to a length of 1. + +### `length()` +Returns the length (magnitude) of the vector. + +### `lengthSquared()` +Returns the squared length of the vector. + +### `cross(v)` +Computes the cross product with another vector and returns the result. + +### `distance(v)` +Calculates the distance to another vector. + +### `distanceSquared(v)` +Calculates the squared distance to another vector. + +### `lerp(v, t)` +Performs linear interpolation between the current vector and another vector. + +### `slerp(v, t)` +Performs spherical linear interpolation between the current vector and another vector. + +### `dot(v)` +Calculates the dot product with another vector. + +### `angleBetween(v)` +Calculates the angle (in radians) between the current vector and another vector. + +### `projectOnto(v)` +Projects the current vector onto another vector. + +### `reflect(normal)` +Reflects the vector against a given normal. + +### `setX(value)`, `setY(value)`, `setZ(value)` +Sets the x, y, or z component of the vector, respectively. + +### `distanceToLineSegment(start, end)` +Calculates the shortest distance from the vector to a line segment. + +### `equals(other)` +Checks if the current vector is equal to another vector. + +### `toString()` +Returns a string representation of the vector. + +## Usage Example +```javascript +import Vec3 from './Vec3'; + +// Creating a new Vec3 instance +let vector = Vec3.from(1, 2, 3); + +// Performing operations +let addedVector = vector.add(Vec3.from(1, 0, 0)); +let length = vector.length(); +``` + +This class is essential for vector manipulations in a Minecraft server, providing a comprehensive set of tools for handling 3D vector mathematics. \ No newline at end of file