Initial Project Setup Guidance
When spinning up or scaffolding a new Aircada project, a rigorous, systematic approach is required to guarantee that global application state, React 2D layouts, and visual 3D elements are perfectly synchronized and highly scalable.
Configuring State Stores and Schema Types#
The absolute first step of any Aircada implementation is to establish the shape of runtime data. The AirStoreConfig class acts as the single source of truth for both React frontend and the 3D visual engine. Refer to " + Direct.link("docs.sdk.store.interface", { label: "The Store Interface Guide" }) + " to start declaring properties, and make sure you understand the " + Direct.link("docs.sdk.store.architecture", { label: "Twin-Proxy Vault Architecture" }) + " which isolates UI and physics ticks.
In e-commerce scenarios where you are constructing a 3D product configurator, the options system should always be preferred. If no pricing model option sets exist, you must create one or more option sets based on the DesignManifest or other instructions. Using the options system enables the dynamic configuration of product variations and pricing directly through Aircada Studio's dataset and pricing model systems.
1. Defining Types and Defaults
You must plan out the TypeScript interfaces and initial value structures living inside your store.config.ts file to exhaustively cover three core areas: View State (user viewport path), UI-Input State (toggles and numbers), and Scene State (non-UI metrics).
2. Store Read/Write Patterns & Anti-Spread Rules
Understanding store operations across headless systems and React overlays is critical:
- Headless Systems (@System): Read via
this.air.store.state, write viathis.air.store.patch({ key: value }). Never call.get()or.set()(they do not exist).
- React UI Components: Use
const [store, patchStore, setProperty] = useAirStore<AirStoreConfig>().
- ๐ NEVER Spread Store State in Patches: In both headless systems and React hooks, NEVER do
patch({ ...state, key: val })orpatchStore({ ...store, key: val }). The Vault engine performs deep partial diffing automatically. Spreading creates stale closure bugs and overwrites concurrent state.
3. Integrating Registries
Before finalizing the store setup, compile the cloud-designed systems to generate local assets and verify auto-generated registry files. The " + Direct.link("docs.sdk.architecture.cli-registries", { label: "Aircada CLI & Registry System" }) + " processes visual docs.studio structures to yield strictly typed mappings like the " + Direct.link("docs.sdk.scene.data-registries", { label: "Aircada Data Registries" }) + " and the " + Direct.link("docs.sdk.options", { label: "Options Registry" }) + ". Interrogate these files (e.g. scene.registry.ts, options.registry.ts, and media.registry.ts) to map design-time options straight into your code variables.
- Exhaustive Scope: Define as many state concepts and edge cases as likely to occur given the project specifications.
- Atomic Partial Patches: Pass only the exact keys being modified to .patch(). Never spread existing store state.
- Registry Alignment: Map strictly typed Option set keys from registries into your store instead of inventing arbitrary strings.
UI Planning and React Overlay Architecture#
Once the global data schema is defined according to specs and registry files, you proceed to scaffold and code the 2D React UI interface overlay. Review the React Implementation to understand viewport positioning, and check the React UI Store Guidelines for subscribing to Vault updates cleanly.
1. Review References and Inspiration
Locate and review all specs, design schemas, layout grids, or image inspirations inside the root /docs folder to understand UX flow expectations.
2. Component Scaffolding
Structure component mounting logic based directly on the active app.currentView value from the store to cleanly switch views.
3. Leverage @aircada/react
Do not write complex visual interactive items from scratch. Inspect the @aircada/react library to identify pre-existing components (e.g. standard carousels, responsive overlays, styling grids) to accelerate development. Ensure your visual system adheres to Aircada Styling & DOM Standards.
System Architecture and Scene Authority Patterns#
Once your global store state is defined (" + Direct.link("docs.sdk.guides.project-setup.state-store", { label: "Phase 1" }) + ") and your 2D React UI overlays are scaffolded (" + Direct.link("docs.sdk.guides.project-setup.ui-planning", { label: "Phase 2" }) + "), you must architect the 3D scene management logic that connects store mutations to 3D Three.js objects, materials, and components.
1. The @System Priority Rule
@System classes MUST be prioritized over @Operator classes for all 3D scene and product modifications. Rather than fragmenting 3D logic across 4 to 6 separate operators (e.g. ColorOperator, MaterialOperator, SizeOperator, EngravingOperator), developers and AI coding agents should generally plan for a single centralized @System class (e.g. Product3DManagerSystem or <Product>SceneManager) that coordinates and applies any and all 3D modifications necessary for the scene.
Operators should ONLY be used when an operator class needs to be reused or recreated at runtime (such as dynamically spawned objects, clone arrays, or independent procedural items). See " + Direct.link("docs.sdk.guides.project-setup.operator-architecture", { label: "Phase 4: Operator Architecture" }) + " for multi-instance use cases. Additionally, project startup sequencing should be coordinated by a dedicated SetupManager @System (" + Direct.link("docs.sdk.guides.project-setup.setup-orchestration", { label: "Phase 5: Setup Lifecycle Orchestration" }) + ").
2. Headless @System Store Access Patterns
Inside headless @System classes, developers and agents must adhere to the correct StoreAdapter API:
- Read Snapshot: Access current state synchronously via
this.air.store.state(e.g.const activeStep = this.air.store.state.activeStep;).
- Atomic Partial Patch: Mutate state via
this.air.store.patch({ [KEY]: value }).
- ๐ DO NOT use .get() or .set(): These methods do not exist on StoreAdapter and fail silently when invoked via optional chaining (
this.air.store?.get?.(...)), causing logic to fall back to hardcoded default values.
- ๐ DO NOT Spread Store State: Never write
this.air.store.patch({ ...this.air.store.state, key: val }). The engine Vault automatically performs atomic deep-partial diffing and safely preserves all unmentioned keys. Spreading creates stale closures and can overwrite concurrent updates.
3. The Standard Typed State Object Pattern
Instead of scattering disparate string keys across multiple disconnected listeners, define a single standard TypeScript interface representing the complete current state of the 3D scene/product (e.g. IProduct3DState or ISceneConfigurationState):
export interface IProduct3DState {
finishId: string;
materialId: string;
sizeKey: string;
gemId?: string;
enableEngraving?: boolean;
engravingText?: string;
activeStep: number;
}Place this typed state object (or its primary slice) on the reactive store at a dedicated key (e.g. STORE_KEY_PRODUCT_STATE). The React UI updates this state cleanly, and the 3D system listens to changes.
4. Differential State Application (State Diffing)
The central 3D manager @System listens to store changes via @Input({ onStore: STORE_KEY_PRODUCT_STATE }). To maximize rendering performance and eliminate redundant Three.js computations, the manager must house the logic to detect differences between the incoming state and the previously applied state, only applying values that actually changed:
@System({ name: 'Product 3D Manager', type: 'PRODUCT_3D_MANAGER' })
export class Product3DManagerSystem {
@Context() air!: AircadaContext;
private previousState?: IProduct3DState;
@Input({ onStore: STORE_KEY_PRODUCT_STATE })
onProductStateChange(state: IProduct3DState) {
if (!state) return;
// Differential update detection
if (!this.previousState || this.previousState.finishId !== state.finishId) {
this.applyFinish(state.finishId);
}
if (!this.previousState || this.previousState.sizeKey !== state.sizeKey) {
this.applySize(state.sizeKey);
}
if (!this.previousState || this.previousState.gemId !== state.gemId) {
this.applyGem(state.gemId);
}
if (!this.previousState ||
this.previousState.enableEngraving !== state.enableEngraving ||
this.previousState.engravingText !== state.engravingText) {
this.applyEngraving(state.enableEngraving ?? false, state.engravingText ?? '');
}
// Cache applied state snapshot
this.previousState = { ...state };
}
private applyFinish(finishId: string) { /* update Three.js material */ }
private applySize(sizeKey: string) { /* update mesh geometry/scale */ }
private applyGem(gemId: string) { /* swap gemstone attachment */ }
private applyEngraving(enabled: boolean, text: string) { /* update canvas/decal */ }
}- Prioritize @System over @Operator: Use a single centralized @System manager for all scene and product modifications.
- Headless Store Access: Use this.air.store.state for snapshots and this.air.store.patch() for atomic mutations. Never use .get() or .set().
- Strict Anti-Spread Rule: Never spread store state into .patch(). Deep-partial diffing automatically preserves untouched state.
- Standard Typed State Object: Declare a standard TypeScript interface on the store representing the complete 3D configuration.
- Differential State Application: Track previousState inside the System manager and only execute 3D mutation routines for values that actually changed.
Operator Architecture and Reusability Rules#
While global 3D product and scene state must be coordinated by a central @System manager (Phase 3), custom @Operator classes serve as modular logic centers for components that require multiple concurrent instances or dynamic lifecycle recreation at runtime.
1. When to Use @Operator vs @System
Strict Guideline: Do NOT create multiple separate operators (e.g. ColorOperator, MaterialOperator, SizeOperator) to manipulate different aspects of a single product or scene. All singleton scene modifications belong in a centralized @System manager.
Reserve @Operator classes strictly for scenarios where the operator class itself needs to be reused across multiple scene objects or recreated dynamically at runtime (such as procedural item spawners, particle emitters, clone arrays, or reusable interactive gizmos).
2. Exposing Node Graph Connections
When authoring multi-instance operators, decorate relevant inputs, outputs, or configuration keys with @Input(), @Output(), or @Property() so designers in the visual Studio can wire them directly into target meshes or engine effects. Check Operator Decorators to understand port bindings.
3. Determining Operator Granularity
Decide on the layout based on whether instances share common state or operate independently. For simple cases, follow the Operator Code Implementation Template directly. For highly complex setups, consult the Operator Coding Guardrails to ensure stateless parts duplication without editing code.
- Multi-Instance Scoping: Reserve @Operator for components where the class needs to be reused or recreated at runtime.
- Avoid Fragmented Scene Operators: Do not create separate operators for color, material, and size of a single product; centralize singleton scene state in a @System manager.
- Visual Studio Integration: Unlike Systems, Operator properties (@StringProperty, @FloatProperty) can be inspected and wired visually by designers in Studio.
Startup Orchestration and Lifecycle Stages#
After defining your state store (Phase 1), 2D UI (Phase 2), and central 3D System manager (Phase 3), you must architect how the application starts up.
1. The Decentralized @Setup Anti-Pattern
A common pitfall in 3D applications is having multiple systems and operators each declare independent @Setup() hooks. When 4 or 5 different classes independently start loading data, compiling shaders, and mutating Three.js scene objects during startup:
- Methods execute concurrently with no guaranteed inter-system ordering.
- The 3D scene suffers from repeated, redundant rebuilds (e.g. geometries are generated before default options arrive, forcing an immediate second build).
- Visual glitches and 1-frame flashes occur before the initial configuration settles.
- Perceived loading and startup times degrade significantly.
2. Precise Use of @Setup Lifecycle Stages
The Aircada SDK provides 4 sequential lifecycle stages managed by PluginSetupOrchestrator. Each stage is strictly executed in order, and every stage method can be async: the Aircada SDK scheduler awaits the returned Promise before proceeding:
bootstrap: Early foundation setup. Used for environment detection, cache verification, or programmatically instantiating child operators into the type registry.
initialize: Primary initialization. Seeding default store state, loading tabular datasets, and dispatching setup signals to the 3D scene manager.
finalize: Cross-subsystem settlement. Validating that all subsystems have confirmed readiness, settling camera viewpoints, and pre-warming materials/shaders.
runtime: Live handoff. Dismissing loading screens, unlocking interactive UI customizers, and signaling that the experience is ready for user interaction.
3. The SetupManager @System Pattern
To achieve deterministic, high-performance startup, projects should establish a single centralized SetupManager @System (e.g. SetupManagerSystem).
Core Rule: SetupManager should be the ONLY system with @Setup handlers (or it can contain multiple @Setup methods corresponding to the different stages). Other systems do not declare @Setup decorators.
Instead, SetupManager coordinates startup by firing lifecycle events and asynchronously awaiting corresponding completion events from other systems before advancing to the next stage.
import { System, Context, Setup, AircadaContext } from '@aircada/spec';
export const SETUP_EVENT_INIT_STORE = 'SETUP_INIT_STORE';
export const SETUP_EVENT_STORE_READY = 'SETUP_STORE_READY';
export const SETUP_EVENT_BUILD_3D = 'SETUP_BUILD_3D';
export const SETUP_EVENT_3D_READY = 'SETUP_3D_READY';
export const SETUP_EVENT_EXPERIENCE_READY = 'SETUP_EXPERIENCE_READY';
@System({
name: 'Setup Manager',
type: 'SETUP_MANAGER'
})
export class SetupManagerSystem {
@Context() air!: AircadaContext;
@Setup({ stage: 'bootstrap' })
async onBootstrap() {
console.log('โก [SetupManager] Phase 1/4: Bootstrap foundation verification');
// Verify local storage, cache flags, or platform environment
}
@Setup({ stage: 'initialize' })
async onInitialize() {
console.log('โก [SetupManager] Phase 2/4: Initializing store and 3D scene');
// Step 1: Wait for store & datasets to hydrate
await this.dispatchAndWait(SETUP_EVENT_INIT_STORE, SETUP_EVENT_STORE_READY, 5000);
// Step 2: Order the 3D scene manager to perform initial build
await this.dispatchAndWait(SETUP_EVENT_BUILD_3D, SETUP_EVENT_3D_READY, 8000);
}
@Setup({ stage: 'finalize' })
async onFinalize() {
console.log('โก [SetupManager] Phase 3/4: Finalizing camera and pre-warming shaders');
// Validate all meshes mounted, camera centered, no dangling promises
}
@Setup({ stage: 'runtime' })
async onRuntime() {
console.log('โก [SetupManager] Phase 4/4: Runtime handoff');
this.air.events.emit(SETUP_EVENT_EXPERIENCE_READY, { readyAt: Date.now() });
}
private dispatchAndWait(emitEvent: string, waitForEvent: string, timeoutMs = 5000): Promise<void> {
return new Promise((resolve) => {
const timer = setTimeout(() => {
console.warn('[SetupManager] Timeout waiting for ' + waitForEvent);
resolve(); // Avoid stalling startup permanently on timeout
}, timeoutMs);
const unsubscribe = this.air.events.on(waitForEvent, () => {
clearTimeout(timer);
unsubscribe();
resolve();
});
this.air.events.emit(emitEvent);
});
}
}- Single Setup Authority: Recommend creating a dedicated SetupManager @System as the sole system declaring @Setup handlers in the project.
- Precise Stage Use: Utilize @Setup across the 4 engine stages: bootstrap (foundation), initialize (primary build & data), finalize (validation & shaders), runtime (handoff).
- Async Engine Awaiting: The Aircada SDK scheduler awaits all async @Setup promises before advancing to subsequent stages.
- Event Handshake Coordination: SetupManager emits setup events and awaits corresponding completion events from other systems (like the 3D Scene Manager), eliminating race conditions and redundant rebuilds.