Core Engine
Relevant source files
The following files were used as context for generating this wiki page:
The Core Engine is the foundational module of the @nextorders/avatar package, responsible for the generation of SVG avatars. It provides a flexible and extensible framework that separates the generic logic of SVG creation and manipulation from the specific artistic details of an avatar style. The engine takes an avatar style definition (such as open-peeps) and a set of user-defined options, then orchestrates the entire process from random number generation to applying transformations and backgrounds, ultimately producing a complete SVG avatar.
This engine is not typically used directly but is consumed by higher-level functions like the main createAvatar function, which prepares a simplified set of options before passing them to the core. The core's main function, createAvatar (aliased as createBaseAvatar in the main package), is the central point of this process.
Sources: packages/avatar/src/core/index.ts, packages/avatar/src/index.ts:18
Core Functionality: createAvatar
The primary function of the core engine is createAvatar, located in packages/avatar/src/core/index.ts. This function orchestrates the entire avatar generation pipeline. It is a generic function designed to work with any compliant avatar style.
The process can be summarized in the following steps:
- Option Merging: Combines default style options with user-provided options.
- PRNG Initialization: Creates a pseudo-random number generator (PRNG) instance using the provided
seed. - Style Creation: Invokes the
createmethod of the providedstyleobject, passing the PRNG and merged options. This returns the basic SVG body and attributes for the avatar. - Background Generation: Determines the background type, colors, and rotation based on options and the PRNG.
- SVG Transformation: Applies a series of SVG transformations to the avatar body, such as scaling, flipping, rotating, and translating.
- Final Assembly: Adds the background and any clipping masks (for rounded corners) to the SVG body, constructs the final
<svg>tag with all its attributes, and wraps the body. - Result Packaging: Returns a
Resultobject containing the final SVG string and methods to access it in different formats (toString,toJson,toDataUri).
Sources: packages/avatar/src/core/index.ts:8-86
Avatar Generation Flow
The following diagram illustrates the high-level data flow within the core createAvatar function.
This diagram shows the sequential process of generating an avatar, from initial options to the final result object.
Sources: packages/avatar/src/core/index.ts:8-71
Architecture and Data Flow
The engine's architecture is designed around the Style interface, which allows for different avatar designs (like open-peeps) to be plugged into the same generation logic.
Key Components and Interfaces
The core engine relies on a few key data structures to manage the generation process.
| Component | Description | Source File |
|---|---|---|
Style<O> | An object that defines an avatar style. It must contain a create method and can optionally provide a schema for its options. | packages/avatar/src/core/index.ts:8 |
StyleCreate<O> | The signature for the create method on a Style. It receives the prng and options and must return a StyleCreateResult. | packages/avatar/src/core/index.ts:12 |
StyleCreateResult | The object returned by a style's create method. It contains the base SVG body as a string and a dictionary of SVG attributes. | packages/avatar/src/core/index.ts:12 |
Result | The final object returned by the core createAvatar function. It provides methods to get the avatar as a string, JSON object, or Data URI. | packages/avatar/src/core/index.ts:9-86 |
svgUtils | A collection of utility functions for programmatically manipulating the SVG string (e.g., adding backgrounds, transforms). | packages/avatar/src/core/utils/svg.ts |
openPeeps | An example implementation of the Style interface. It defines how to assemble an avatar from various components like face, hair, and accessories. | packages/avatar/src/open-peeps/index.ts |
Interaction Diagram
This sequence diagram shows how the main createAvatar function interacts with the core engine (createBaseAvatar), the openPeeps style, and the SVG utilities to generate an avatar.
This diagram illustrates the flow of control from the initial public function call through the core engine and its dependencies.
Sources: packages/avatar/src/index.ts:16-18, packages/avatar/src/core/index.ts:8-86
SVG Manipulation Utilities
The core engine uses a set of helper functions found in packages/avatar/src/core/utils/svg.ts to apply transformations and other effects to the base SVG generated by the style. These functions work by wrapping the SVG body in <g> (group) elements with transform attributes or by prepending definitions like backgrounds and masks.
| Function | Description |
|---|---|
addBackground | Prepends a <rect> element to the SVG body to act as a background. It supports solid, gradientLinear, and randomGradientLinear. |
addScale | Wraps the SVG body in a <g> tag with a scale transform to resize the avatar around its center. |
addTranslate | Wraps the SVG body in a <g> tag with a translate transform to move the avatar horizontally or vertically. |
addRotate | Wraps the SVG body in a <g> tag with a rotate transform to rotate the avatar around its center. |
addFlip | Wraps the SVG body in a <g> tag with a scale(-1 1) transform to flip the avatar horizontally. |
addViewboxMask | Adds a <mask> to the SVG to clip the final output, typically used for creating rounded corners (radius). |
createAttrString | Converts the attributes object into a valid string for inclusion in the opening <svg> tag, ensuring proper XML escaping. |
Sources: packages/avatar/src/core/utils/svg.ts
Configuration and Options
The engine is configured through an options object. These options are divided into two categories: core options handled by the engine itself, and style-specific options passed to the style's create method.
Core Options
These options are processed by the core createAvatar function to apply generic effects.
| Option | Type | Description | Source |
|---|---|---|---|
seed | string | The seed for the pseudo-random number generator. Required. | packages/avatar/src/core/index.ts:11 |
size | number | The width and height of the final SVG in pixels. | packages/avatar/src/core/index.ts:28-31 |
scale | number | A percentage to scale the avatar (e.g., 80 for 80%). Default is 100. | packages/avatar/src/core/index.ts:33-35 |
flip | boolean | If true, flips the avatar horizontally. | packages/avatar/src/core/index.ts:37-39 |
rotate | number | The degree of rotation to apply to the avatar. | packages/avatar/src/core/index.ts:41-43 |
translateX, translateY | number | A percentage to move the avatar along the X or Y axis. | packages/avatar/src/core/index.ts:45-53 |
backgroundType | array of string | A list of background types to choose from (e.g., solid, gradientLinear). | packages/avatar/src/core/index.ts:14 |
backgroundColor | array of string | A list of hex color codes for the background. | packages/avatar/src/core/index.ts:18 |
backgroundRotation | array of number | A range of degrees for gradient rotation. | packages/avatar/src/core/index.ts:20-26 |
radius | number | A percentage to create rounded corners (e.g., 50 for a circle). | packages/avatar/src/core/index.ts:64-66 |
Style-Specific Options (open-peeps)
These options are defined by the open-peeps style and are used within its create method to select different avatar components. A full list is available in the style's schema.
| Option | Type | Description |
|---|---|---|
accessories | string[] | A list of possible accessories like glasses or eyepatch. |
accessoriesProbability | number | The probability (0-100) that an accessory will be applied. |
face | string[] | A list of possible face types, like smile, calm, or rage. |
facialHair | string[] | A list of possible facial hair styles. |
facialHairProbability | number | The probability (0-100) that facial hair will be applied. |
head | string[] | A list of possible head/hair styles. |
skinColor | string[] | A list of possible hex color codes for the skin. |
clothingColor | string[] | A list of possible hex color codes for the clothing. |
Sources: packages/avatar/src/open-peeps/schema.ts
Return Value
The core createAvatar function returns a Result object, which provides multiple ways to consume the generated avatar.
// Simplified Result interface
interface Result {
// Returns the full SVG as a string.
toString: () => string;
// Returns the SVG and additional metadata as a JSON object.
toJson: () => {
svg: string;
extra: Record<string, any>;
};
// Returns a Data URI for use in `<img>` tags or CSS.
toDataUri: () => string;
}
The toJson() method is particularly useful as it provides not only the SVG but also the specific choices made during generation (e.g., which components were picked, what colors were used).
Sources: packages/avatar/src/core/index.ts:72-86
Conclusion
The Core Engine of the @nextorders/avatar package is a well-structured and powerful system for SVG avatar generation. By abstracting the style from the generation logic, it allows for easy creation of new avatar styles while reusing the robust core functionality for transformations, background processing, and output formatting. Its reliance on a seeded PRNG ensures that avatar generation is deterministic, which is a key feature for producing consistent avatars for the same identifier.