@playcanvas/web-components 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/pwc.js CHANGED
@@ -2928,214 +2928,1391 @@
2928
2928
  return asset;
2929
2929
  };
2930
2930
 
2931
+ /**
2932
+ * Formats one line of the printable hierarchy: the node's name, an `[index]` marker when the
2933
+ * name is shared by several nodes in the model, the attached component types, and the material
2934
+ * names of a render component.
2935
+ *
2936
+ * @param node - The node to format.
2937
+ * @param counts - The number of nodes bearing each name.
2938
+ * @returns The formatted line.
2939
+ */
2940
+ const formatNode = (node, counts) => {
2941
+ const index = (counts.get(node.name) ?? 0) > 1 ? ` [${node.index}]` : '';
2942
+ const components = node.components.length > 0 ? ` (${node.components.join(', ')})` : '';
2943
+ // Braces rather than brackets: `[N]` already means a match index on this line
2944
+ const materials = node.materials.length > 0 ? ` {${node.materials.map((slot) => slot.name ?? 'null').join(', ')}}` : '';
2945
+ return `${node.name}${index}${components}${materials}`;
2946
+ };
2947
+ /**
2948
+ * Formats the printable form of a hierarchy subtree.
2949
+ *
2950
+ * @param root - The subtree root.
2951
+ * @param counts - The number of nodes bearing each name.
2952
+ * @returns The tree, one line per node.
2953
+ */
2954
+ const formatHierarchy = (root, counts) => {
2955
+ const lines = [formatNode(root, counts)];
2956
+ const walk = (node, prefix) => {
2957
+ node.children.forEach((child, i) => {
2958
+ const last = i === node.children.length - 1;
2959
+ lines.push(`${prefix}${last ? '└─ ' : '├─ '}${formatNode(child, counts)}`);
2960
+ walk(child, `${prefix}${last ? ' ' : '│ '}`);
2961
+ });
2962
+ };
2963
+ walk(root, '');
2964
+ return lines.join('\n');
2965
+ };
2966
+ /**
2967
+ * The ModelElement interface provides properties and methods for manipulating
2968
+ * {@link https://developer.playcanvas.com/user-manual/web-components/tags/pc-model/ | `<pc-model>`} elements.
2969
+ * The ModelElement interface also inherits the properties and methods of the
2970
+ * {@link HTMLElement} interface.
2971
+ *
2972
+ * The element becomes ready once its container asset has loaded and the instantiated hierarchy has
2973
+ * been added to the scene — `entity` is non-null by then. A failed load also settles readiness,
2974
+ * with `entity` remaining `null`: readiness means the load settled, not that it succeeded — listen
2975
+ * for `error`, or check `entity`, to tell the outcomes apart. Changing `asset` re-arms readiness
2976
+ * and instantiates anew, so a `ready()` obtained after the change resolves against the new
2977
+ * hierarchy. A `pc-model` outside a `pc-app`, or referencing an unknown asset id, warns and never
2978
+ * becomes ready.
2979
+ *
2980
+ * @fires {Event} load - Fired each time a container asset finishes instantiating, including
2981
+ * re-instantiation after `asset` changes. Does not bubble — listen on this element, or use a
2982
+ * capture-phase listener on an ancestor.
2983
+ * @fires {ErrorEvent} error - Fired when the container asset fails to load, with the engine's
2984
+ * error in `message`. Does not bubble. The element still becomes ready — readiness means the load
2985
+ * settled, not that it succeeded.
2986
+ */
2987
+ class ModelElement extends AsyncElement {
2988
+ _asset = '';
2989
+ _entity = null;
2990
+ /**
2991
+ * Incremented on every new load and on disconnect, and captured by a load when it starts. A
2992
+ * load that resumes from an await or a load callback abandons itself if the value has moved
2993
+ * on, so a superseded load can neither instantiate a second entity nor parent one that has
2994
+ * since been destroyed.
2995
+ */
2996
+ _loadGeneration = 0;
2997
+ /**
2998
+ * The pending asset subscriptions of the current load, if it is waiting for its asset. Held
2999
+ * so that whatever supersedes the load can detach the handlers from the asset, rather than
3000
+ * leave them registered until the asset settles (or forever, if it never does).
3001
+ */
3002
+ _loadHandle = null;
3003
+ _errorHandle = null;
3004
+ /**
3005
+ * The root entity of the instantiated model. `null` until the container asset has loaded
3006
+ * and been instantiated, and again once the element has been removed from the document.
3007
+ * @returns The model's root entity, or `null`.
3008
+ */
3009
+ get entity() {
3010
+ return this._entity;
3011
+ }
3012
+ /**
3013
+ * Returns a snapshot of the instantiated node tree, or `null` while there is none (the
3014
+ * container asset has not loaded, or the element has left the document). One call grounds a
3015
+ * session — a browser console, a test, an agent — in the vocabulary `pc-node` binding
3016
+ * resolves against: the instantiated names ({@link HierarchyNode.name}), paths, match
3017
+ * indices, attached component types and the material assignments of render components
3018
+ * ({@link HierarchyNode.materials}). `String(...)` of the result, or of any node in it,
3019
+ * is the printable form.
3020
+ *
3021
+ * The snapshot is plain data, computed afresh each call: it does not follow later changes
3022
+ * to the hierarchy, and mutating it changes nothing.
3023
+ *
3024
+ * @returns The root of the instantiated node tree, or `null`.
3025
+ */
3026
+ hierarchy() {
3027
+ const root = this._entity;
3028
+ if (!root) {
3029
+ return null;
3030
+ }
3031
+ // Ordinals are assigned in the traversal resolution searches — pre-order depth-first
3032
+ // from the model root, the root itself included — so each node's index is exactly what
3033
+ // a pc-node's index attribute selects. Once the walk completes, the map holds the total
3034
+ // count per name, which is what the printable form reads to annotate only shared names.
3035
+ const ordinals = new Map();
3036
+ const describe = (entity, pathBelowRoot) => {
3037
+ const index = ordinals.get(entity.name) ?? 0;
3038
+ ordinals.set(entity.name, index + 1);
3039
+ const node = {
3040
+ name: entity.name,
3041
+ // The root has no path below itself; its own name stands in, as it does for
3042
+ // the path a pc-node bound to the root reports.
3043
+ path: pathBelowRoot || entity.name,
3044
+ index,
3045
+ // A plain GraphNode grafted into the hierarchy has no component storage
3046
+ components: Object.keys(entity.c ?? {}).sort(),
3047
+ materials: (entity.render?.meshInstances ?? []).map((meshInstance, slot) => ({
3048
+ index: slot,
3049
+ name: meshInstance.material?.name ?? null
3050
+ })),
3051
+ children: entity.children.map((child) => describe(child, pathBelowRoot ? `${pathBelowRoot}/${child.name}` : child.name))
3052
+ };
3053
+ // Non-enumerable, keeping the snapshot plain data under JSON.stringify, spreads and
3054
+ // key enumeration. Deferred to call time, by which the ordinal map holds its totals.
3055
+ Object.defineProperty(node, 'toString', {
3056
+ enumerable: false,
3057
+ value: () => formatHierarchy(node, ordinals)
3058
+ });
3059
+ return node;
3060
+ };
3061
+ return describe(root, '');
3062
+ }
3063
+ connectedCallback() {
3064
+ // A model outside an application is inert and never becomes ready, so awaiting it hangs.
3065
+ // Warn rather than fail silently, naming the parent it requires, as every other misplaced
3066
+ // element does.
3067
+ if (!this.closestApp) {
3068
+ const label = this._asset ? ` '${this._asset}'` : '';
3069
+ console.warn(`pc-model${label} must be a descendant of pc-app - model not created`);
3070
+ return;
3071
+ }
3072
+ this._loadModel();
3073
+ }
3074
+ disconnectedCallback() {
3075
+ this._loadGeneration++;
3076
+ this._detachLoadHandlers();
3077
+ this._unloadModel();
3078
+ this._resetReady();
3079
+ }
3080
+ _detachLoadHandlers() {
3081
+ this._loadHandle?.off();
3082
+ this._loadHandle = null;
3083
+ this._errorHandle?.off();
3084
+ this._errorHandle = null;
3085
+ }
3086
+ /**
3087
+ * Resolves readiness and dispatches the `load` event. Called once the instantiated hierarchy
3088
+ * has been parented — readiness means "in the scene graph", matching `pc-entity`, so a ready
3089
+ * model's entity always has world transforms.
3090
+ */
3091
+ _announceLoad() {
3092
+ this._onReady();
3093
+ this.dispatchEvent(new Event('load'));
3094
+ }
3095
+ _instantiate(container) {
3096
+ const generation = this._loadGeneration;
3097
+ const entity = container.instantiateRenderEntity();
3098
+ this._entity = entity;
3099
+ // The parent's readiness re-arms when it is torn down, so these can resume in a later
3100
+ // connection cycle. The entity is captured above and the generation re-checked, so a
3101
+ // stale resume cannot parent an entity a newer cycle has already destroyed.
3102
+ const parentEntityElement = this.closestEntity;
3103
+ if (parentEntityElement) {
3104
+ parentEntityElement.ready().then(() => {
3105
+ if (generation !== this._loadGeneration) {
3106
+ return;
3107
+ }
3108
+ parentEntityElement.entity.addChild(entity);
3109
+ this._announceLoad();
3110
+ });
3111
+ }
3112
+ else {
3113
+ const appElement = this.closestApp;
3114
+ if (appElement) {
3115
+ appElement.ready().then(() => {
3116
+ if (generation !== this._loadGeneration) {
3117
+ return;
3118
+ }
3119
+ appElement.app.root.addChild(entity);
3120
+ this._announceLoad();
3121
+ });
3122
+ }
3123
+ }
3124
+ }
3125
+ async _loadModel() {
3126
+ this._unloadModel();
3127
+ // Supersede any load already in flight - only the newest load may instantiate
3128
+ const generation = ++this._loadGeneration;
3129
+ this._detachLoadHandlers();
3130
+ // Re-arm readiness so a waiter obtained after an asset change resolves against the new
3131
+ // hierarchy. A no-op on first connection, where readiness is still pending.
3132
+ this._resetReady();
3133
+ const appElement = this.closestApp;
3134
+ if (!appElement) {
3135
+ // Outside pc-app; connectedCallback already warned. Reached through the asset setter.
3136
+ return;
3137
+ }
3138
+ await appElement.ready();
3139
+ // The element may have been removed, or another load started, while we waited
3140
+ if (generation !== this._loadGeneration) {
3141
+ return;
3142
+ }
3143
+ const asset = useAsset(this._asset);
3144
+ if (!asset) {
3145
+ // An empty id is a legitimate transient (the asset may be assigned later); a
3146
+ // non-empty one that resolves to nothing is a dead end - say so rather than staying
3147
+ // silently pending.
3148
+ if (this._asset) {
3149
+ console.warn(`pc-model could not find asset '${this._asset}' - model not created`);
3150
+ }
3151
+ return;
3152
+ }
3153
+ if (asset.loaded) {
3154
+ this._instantiate(asset.resource);
3155
+ }
3156
+ else {
3157
+ // The generation is re-checked even though a superseded handler is detached: the
3158
+ // detach relies on how the engine's event emitter treats removal, while the check
3159
+ // holds on its own. Whichever of load/error fires first detaches the other.
3160
+ this._loadHandle = asset.once('load', () => {
3161
+ this._detachLoadHandlers();
3162
+ if (generation !== this._loadGeneration) {
3163
+ return;
3164
+ }
3165
+ this._instantiate(asset.resource);
3166
+ });
3167
+ this._errorHandle = asset.once('error', (err) => {
3168
+ this._detachLoadHandlers();
3169
+ if (generation !== this._loadGeneration) {
3170
+ return;
3171
+ }
3172
+ // A failed load settles readiness with a null entity, mirroring pc-asset:
3173
+ // readiness means the load settled, not that it succeeded.
3174
+ this.dispatchEvent(new ErrorEvent('error', {
3175
+ message: err instanceof Error ? err.message : String(err)
3176
+ }));
3177
+ this._onReady();
3178
+ });
3179
+ }
3180
+ }
3181
+ _unloadModel() {
3182
+ this._entity?.destroy();
3183
+ this._entity = null;
3184
+ }
3185
+ /**
3186
+ * Sets the id of the `pc-asset` to use for the model.
3187
+ * @param value - The asset ID.
3188
+ */
3189
+ set asset(value) {
3190
+ this._asset = value;
3191
+ if (this.isConnected) {
3192
+ this._loadModel();
3193
+ }
3194
+ }
3195
+ /**
3196
+ * Gets the id of the `pc-asset` to use for the model.
3197
+ * @returns The asset ID.
3198
+ */
3199
+ get asset() {
3200
+ return this._asset;
3201
+ }
3202
+ static get observedAttributes() {
3203
+ return ['asset'];
3204
+ }
3205
+ attributeChangedCallback(name, _oldValue, newValue) {
3206
+ switch (name) {
3207
+ case 'asset':
3208
+ this.asset = newValue ?? '';
3209
+ break;
3210
+ }
3211
+ }
3212
+ }
3213
+ customElements.define('pc-model', ModelElement);
3214
+
2931
3215
  /**
2932
3216
  * Represents a component in the PlayCanvas engine.
2933
3217
  *
2934
3218
  * @category Components
2935
3219
  */
2936
- class ComponentElement extends AsyncElement {
2937
- _componentName;
2938
- _enabled = true;
2939
- _component = null;
2940
- _appElement = null;
3220
+ class ComponentElement extends AsyncElement {
3221
+ _componentName;
3222
+ _enabled = true;
3223
+ _component = null;
3224
+ _appElement = null;
3225
+ /**
3226
+ * The element hosting this component, held so the host's readiness cycles can be observed
3227
+ * even after `closestEntity` would no longer resolve (during teardown).
3228
+ */
3229
+ _hostElement = null;
3230
+ /**
3231
+ * The listener re-applying this component when the host's readiness cycles. Held for
3232
+ * removal on disconnect.
3233
+ */
3234
+ _hostReadyListener = null;
3235
+ /**
3236
+ * Incremented on every connect and disconnect. connectedCallback captures the value on entry
3237
+ * and abandons itself wherever it resumes from an await if the value has moved on — so a
3238
+ * callback whose element was removed cannot act on a torn-down tree, and one whose element
3239
+ * was removed and re-inserted (which runs a callback of its own) cannot add the component a
3240
+ * second time.
3241
+ */
3242
+ _connectionGeneration = 0;
3243
+ /**
3244
+ * Creates a new ComponentElement instance.
3245
+ *
3246
+ * @param componentName - The name of the component.
3247
+ * @ignore
3248
+ */
3249
+ constructor(componentName) {
3250
+ super();
3251
+ this._componentName = componentName;
3252
+ }
3253
+ /**
3254
+ * Returns the data the component is created with. Overridden by subclasses to supply the
3255
+ * initial values of their cached properties.
3256
+ *
3257
+ * @returns The initial component data.
3258
+ */
3259
+ getInitialComponentData() {
3260
+ return {};
3261
+ }
3262
+ /**
3263
+ * Creates the component on the host's current entity, removing it first from a previous
3264
+ * entity that is still alive (a retargeted `<pc-node>` moves its decorations with it). When
3265
+ * the entity already has a component of this type — a glTF node arriving with its authored
3266
+ * `render` component, say — warns and leaves `component` null. The element-level warning is
3267
+ * load-bearing: the engine's own duplicate-addComponent warning is Debug-stripped from
3268
+ * production builds, which would otherwise leave a silent null.
3269
+ */
3270
+ _applyComponent() {
3271
+ const entity = this._hostElement?.entity ?? null;
3272
+ if (this._component && this._component.entity === entity) {
3273
+ return;
3274
+ }
3275
+ // A retarget leaves the previous component on a still-live entity - remove it so the
3276
+ // decoration follows the element, or vanishes with a dissolved binding. A destroyed
3277
+ // entity took its components with it.
3278
+ const previous = this._component;
3279
+ if (previous?.entity && previous.entity.c[this._componentName] === previous) {
3280
+ previous.entity.removeComponent(this._componentName);
3281
+ }
3282
+ this._component = null;
3283
+ if (!entity) {
3284
+ return;
3285
+ }
3286
+ if (entity.c[this._componentName]) {
3287
+ const label = this.id ? ` '${this.id}'` : '';
3288
+ console.warn(`${this.tagName.toLowerCase()}${label} - '${entity.name}' already has a '${this._componentName}' component - component not added`);
3289
+ return;
3290
+ }
3291
+ this._component = entity.addComponent(this._componentName, this.getInitialComponentData());
3292
+ }
3293
+ async _addComponent() {
3294
+ const generation = this._connectionGeneration;
3295
+ const entityElement = this.closestEntity;
3296
+ if (!entityElement) {
3297
+ // A component can only exist on an entity, so an element placed outside one is inert.
3298
+ // It still becomes ready (with a null `component`), so warn rather than fail silently
3299
+ const label = this.id ? ` '${this.id}'` : '';
3300
+ console.warn(`${this.tagName.toLowerCase()}${label} must be a descendant of pc-entity - component not added`);
3301
+ return;
3302
+ }
3303
+ await entityElement.ready();
3304
+ // The element may have been removed, or removed and re-inserted, while the entity became
3305
+ // ready — the component belongs to the connection that owns the current generation.
3306
+ if (generation !== this._connectionGeneration) {
3307
+ return;
3308
+ }
3309
+ this._hostElement = entityElement;
3310
+ this._applyComponent();
3311
+ // Re-apply when the host's readiness cycles without this element disconnecting: a
3312
+ // `<pc-node>` rebinding after its model reloads or retargets, or a re-created entity.
3313
+ // The 'ready' event bubbles, so events from descendants pass through this host - only
3314
+ // the host's own cycles count. Readiness is cycled here too, so decorations one level
3315
+ // down re-apply the same way.
3316
+ this._hostReadyListener = (event) => {
3317
+ if (event.target !== this._hostElement) {
3318
+ return;
3319
+ }
3320
+ if (generation !== this._connectionGeneration) {
3321
+ return;
3322
+ }
3323
+ this._hostCycled();
3324
+ };
3325
+ entityElement.addEventListener('ready', this._hostReadyListener);
3326
+ }
3327
+ /**
3328
+ * Re-evaluates this component against the host's current entity: applied to a new entity,
3329
+ * moved from a still-live old one, or removed when the host no longer fronts an entity at
3330
+ * all. Readiness follows - it cycles with a re-application and stays unresolved while the
3331
+ * host is unbound. Called by the host-ready listener, and directly by a `<pc-node>`
3332
+ * dissolving its binding: the one transition that fires no ready event to ride.
3333
+ *
3334
+ * @internal
3335
+ */
3336
+ _hostCycled() {
3337
+ this._resetReady();
3338
+ this._applyComponent();
3339
+ if (this._hostElement?.entity) {
3340
+ this.initComponent();
3341
+ this._onReady();
3342
+ }
3343
+ }
3344
+ /**
3345
+ * Configures the newly added component. Overridden by subclasses whose setup goes beyond
3346
+ * the initial data — child-element handling, asset resolution and the like.
3347
+ */
3348
+ initComponent() {
3349
+ // optional hook
3350
+ }
3351
+ async connectedCallback() {
3352
+ const generation = ++this._connectionGeneration;
3353
+ this._appElement = this.closestApp ?? null;
3354
+ await this._appElement?.ready();
3355
+ // The element may have been removed, or removed and re-inserted, while the application
3356
+ // became ready. A re-insertion runs a connectedCallback of its own, so a stale resume
3357
+ // must not add the component alongside it.
3358
+ if (generation !== this._connectionGeneration) {
3359
+ return;
3360
+ }
3361
+ await this._addComponent();
3362
+ if (generation !== this._connectionGeneration) {
3363
+ return;
3364
+ }
3365
+ this.initComponent();
3366
+ this._onReady();
3367
+ }
3368
+ disconnectedCallback() {
3369
+ // Invalidate any connectedCallback still suspended on an await
3370
+ this._connectionGeneration++;
3371
+ if (this._hostElement && this._hostReadyListener) {
3372
+ this._hostElement.removeEventListener('ready', this._hostReadyListener);
3373
+ }
3374
+ this._hostElement = null;
3375
+ this._hostReadyListener = null;
3376
+ // Remove the component when the element is disconnected. Skip this when the owning
3377
+ // application has already been destroyed — removing a <pc-app> disconnects it before
3378
+ // its children, taking the component systems with it.
3379
+ if (this._appElement?.app && this._component?.entity) {
3380
+ this._component.entity.removeComponent(this._componentName);
3381
+ }
3382
+ this._component = null;
3383
+ this._appElement = null;
3384
+ this._resetReady();
3385
+ }
3386
+ /**
3387
+ * The PlayCanvas component instance. `null` until the element is ready, and also for an
3388
+ * element that is not a descendant of a `<pc-entity>` — await {@link whenReady} or the
3389
+ * element's `ready()` promise before accessing it.
3390
+ * @returns The component instance, or `null`.
3391
+ */
3392
+ get component() {
3393
+ return this._component;
3394
+ }
3395
+ /**
3396
+ * Sets the enabled state of the component.
3397
+ * @param value - The enabled state of the component.
3398
+ */
3399
+ set enabled(value) {
3400
+ this._enabled = value;
3401
+ if (this.component) {
3402
+ this.component.enabled = value;
3403
+ }
3404
+ }
3405
+ /**
3406
+ * Gets the enabled state of the component.
3407
+ * @returns The enabled state of the component.
3408
+ */
3409
+ get enabled() {
3410
+ return this._enabled;
3411
+ }
3412
+ static get observedAttributes() {
3413
+ return ['enabled'];
3414
+ }
3415
+ attributeChangedCallback(name, _oldValue, newValue) {
3416
+ switch (name) {
3417
+ case 'enabled':
3418
+ this.enabled = parseBool(newValue, true);
3419
+ break;
3420
+ }
3421
+ }
3422
+ }
3423
+
3424
+ /**
3425
+ * The AnimComponentElement interface provides properties and methods for manipulating
3426
+ * {@link https://developer.playcanvas.com/user-manual/web-components/tags/pc-anim/ | `<pc-anim>`} elements.
3427
+ * The AnimComponentElement interface also inherits the properties and methods of the
3428
+ * {@link HTMLElement} interface.
3429
+ *
3430
+ * The element drives animation clips over the host entity's hierarchy. Clips come from
3431
+ * `<pc-anim-clip>` children — or, when the element is a direct child of a `<pc-model>` and
3432
+ * declares no clips, every animation of that model's container asset is assigned, named by track
3433
+ * name, in container order. The first clip plays automatically (opt out with `activate="false"`);
3434
+ * switch clips declaratively through the `clip` attribute, or imperatively through {@link play}
3435
+ * and {@link transition}. Tracks bind to scene nodes by name, so any hierarchy whose node names
3436
+ * match a clip's curves can be animated — a model's skeleton is simply the common case.
3437
+ *
3438
+ * The engine reports no clip completion: a non-looping clip holds its last pose silently. Poll
3439
+ * the underlying {@link AnimComponent} (via {@link component}) for playback state beyond what
3440
+ * this element exposes.
3441
+ *
3442
+ * @category Components
3443
+ */
3444
+ class AnimComponentElement extends ComponentElement {
3445
+ /**
3446
+ * Whether playback starts automatically once a clip is assigned.
3447
+ */
3448
+ _activate = true;
3449
+ /**
3450
+ * The clip elements whose states are currently assigned, by clip name. The single writer of
3451
+ * a state: a later clip child re-using an adopted name is rejected as a duplicate.
3452
+ */
3453
+ _assignedClips = new Map();
3454
+ /**
3455
+ * Whether the current clip set was auto-assigned from the enclosing model rather than
3456
+ * declared by clip children.
3457
+ */
3458
+ _autoAssigned = false;
3459
+ /**
3460
+ * The name of the active clip.
3461
+ */
3462
+ _clip = '';
3463
+ /**
3464
+ * The element the model-readiness listener is attached to, held so disconnection can detach
3465
+ * it after `closestEntity` no longer resolves.
3466
+ */
3467
+ _modelListenerTarget = null;
3468
+ /**
3469
+ * Incremented whenever the clip source changes, and captured by an auto-assign pass on
3470
+ * entry — a pass resuming from an await abandons itself if the value has moved on, so a
3471
+ * superseded pass cannot assign clips alongside declared children or a newer pass.
3472
+ */
3473
+ _sourceGeneration = 0;
3474
+ /**
3475
+ * The playback speed multiplier applied across all clips.
3476
+ */
3477
+ _speed = 1;
3478
+ /**
3479
+ * The cross-fade duration of declarative clip switches, in seconds.
3480
+ */
3481
+ _transitionTime = 0;
3482
+ /**
3483
+ * The unknown clip name already warned about, so a repeated selection of the same missing
3484
+ * name complains once.
3485
+ */
3486
+ _warnedClip = null;
3487
+ /**
3488
+ * Rebinds when a model under the host announces readiness. The engine resolves each curve
3489
+ * once, at the first tick after assignment, and never retries — and its mesh-instance
3490
+ * broadcast fires before an instantiated hierarchy is parented, so a model that loads after
3491
+ * the clips were assigned would otherwise stay silently unbound. A re-instantiation of the
3492
+ * implicit clip source (the parent `<pc-model>`) means a new container, so the clip set
3493
+ * refreshes instead — unless every clip declares its own asset, where a rebind suffices.
3494
+ */
3495
+ _onModelReady = (event) => {
3496
+ if (!(event.target instanceof ModelElement) || !this.component) {
3497
+ return;
3498
+ }
3499
+ if (event.target === this.parentElement) {
3500
+ const implicit = this._autoAssigned ||
3501
+ [...this._assignedClips.values()].some(clip => !clip.asset);
3502
+ if (implicit) {
3503
+ this._refreshClips();
3504
+ return;
3505
+ }
3506
+ }
3507
+ this.component.rebind();
3508
+ };
3509
+ /** @ignore */
3510
+ constructor() {
3511
+ super('anim');
3512
+ }
3513
+ getInitialComponentData() {
3514
+ // The engine assigns creation data in key order and `activate` gates playback, so it
3515
+ // must precede any future key that builds layers (e.g. a state graph)
3516
+ return {
3517
+ activate: this._activate,
3518
+ speed: this._speed
3519
+ };
3520
+ }
3521
+ initComponent() {
3522
+ if (!this.component) {
3523
+ return;
3524
+ }
3525
+ // A host readiness cycle can re-run this. An identical re-add is deduped by the DOM;
3526
+ // the explicit swap handles the listener target changing across connections.
3527
+ const host = this.closestEntity;
3528
+ if (host && host !== this._modelListenerTarget) {
3529
+ this._modelListenerTarget?.removeEventListener('ready', this._onModelReady);
3530
+ host.addEventListener('ready', this._onModelReady);
3531
+ this._modelListenerTarget = host;
3532
+ }
3533
+ this._applyClips();
3534
+ }
3535
+ disconnectedCallback() {
3536
+ this._modelListenerTarget?.removeEventListener('ready', this._onModelReady);
3537
+ this._modelListenerTarget = null;
3538
+ // Invalidate any auto-assign still awaiting its model, and drop the adoption
3539
+ // bookkeeping so a reconnection starts clean
3540
+ this._sourceGeneration++;
3541
+ this._assignedClips.clear();
3542
+ this._autoAssigned = false;
3543
+ super.disconnectedCallback();
3544
+ }
3545
+ /**
3546
+ * The clip children in DOM order. Read afresh each pass — the DOM is the single source of
3547
+ * truth for the declared clip set.
3548
+ */
3549
+ _clipElements() {
3550
+ return Array.from(this.querySelectorAll(':scope > pc-anim-clip'));
3551
+ }
3552
+ /**
3553
+ * Assigns a clip's state. Until the clip's real track resolves, the engine's own placeholder
3554
+ * track stands in — it keeps the layer playable, so `activate` can start playback and the
3555
+ * declared `clip` selection can apply before any asset has loaded.
3556
+ */
3557
+ _assignClip(clip) {
3558
+ this.component.assignAnimation(clip.name, clip._track ?? playcanvas.AnimTrack.EMPTY, undefined, clip.speed, clip.loop);
3559
+ }
3560
+ /**
3561
+ * Validates a clip child and, when valid, assigns its state and starts its track resolution.
3562
+ *
3563
+ * @param clip - The clip element.
3564
+ * @returns Whether the clip was adopted.
3565
+ */
3566
+ _adoptClip(clip) {
3567
+ const name = clip.name;
3568
+ if (!name) {
3569
+ clip._markInvalid('pc-anim-clip must have a name - clip not assigned');
3570
+ return false;
3571
+ }
3572
+ if (name.indexOf('.') !== -1) {
3573
+ clip._markInvalid(`pc-anim-clip '${name}' - '.' in a clip name is reserved for blend tree paths - clip not assigned`);
3574
+ return false;
3575
+ }
3576
+ if (this._assignedClips.has(name)) {
3577
+ clip._markInvalid(`pc-anim-clip '${name}' - an earlier clip already uses this name - clip not assigned`);
3578
+ return false;
3579
+ }
3580
+ this._assignedClips.set(name, clip);
3581
+ this._assignClip(clip);
3582
+ clip._resolveTrack(this);
3583
+ return true;
3584
+ }
3585
+ /**
3586
+ * Assigns the current clip set: the declared clip children when there are any, otherwise the
3587
+ * enclosing model's clips. Runs against a fresh component after a host cycle, so the
3588
+ * adoption bookkeeping rebuilds from scratch.
3589
+ */
3590
+ _applyClips(restore) {
3591
+ if (!this.component) {
3592
+ return;
3593
+ }
3594
+ this._sourceGeneration++;
3595
+ this._assignedClips.clear();
3596
+ this._autoAssigned = false;
3597
+ const clips = this._clipElements();
3598
+ if (clips.length === 0) {
3599
+ this._kickAutoAssign(restore);
3600
+ return;
3601
+ }
3602
+ for (const clip of clips) {
3603
+ this._adoptClip(clip);
3604
+ }
3605
+ this._applySelection(restore);
3606
+ }
3607
+ /**
3608
+ * Assigns every clip of the enclosing model's container, named by track name, in container
3609
+ * order. Names the engine cannot host — dotted (reserved for blend tree paths) or already
3610
+ * taken — are skipped with a warning naming each.
3611
+ */
3612
+ async _kickAutoAssign(restore) {
3613
+ const generation = this._sourceGeneration;
3614
+ const model = this.parentElement;
3615
+ if (!(model instanceof ModelElement)) {
3616
+ // Not inside a model: an empty component, driven through the JS API
3617
+ return;
3618
+ }
3619
+ await model.ready();
3620
+ // The source may have changed while the model loaded - a declared clip child appearing
3621
+ // flips the element over to declared mode, and wins
3622
+ const component = this.component;
3623
+ if (generation !== this._sourceGeneration || !component || this._clipElements().length > 0) {
3624
+ return;
3625
+ }
3626
+ const container = AssetElement.get(model.asset)?.resource;
3627
+ if (!container) {
3628
+ // The load failed; the model already reported it
3629
+ return;
3630
+ }
3631
+ const label = this.id ? ` '${this.id}'` : '';
3632
+ if (container.animations.length === 0) {
3633
+ console.warn(`pc-anim${label} - model '${model.asset}' has no animations`);
3634
+ return;
3635
+ }
3636
+ const seen = new Set();
3637
+ for (const animationAsset of container.animations) {
3638
+ const track = animationAsset.resource;
3639
+ if (!(track instanceof playcanvas.AnimTrack)) {
3640
+ continue;
3641
+ }
3642
+ if (track.name.indexOf('.') !== -1) {
3643
+ console.warn(`pc-anim${label} - track '${track.name}' - '.' in a clip name is reserved for blend tree paths - track skipped`);
3644
+ continue;
3645
+ }
3646
+ if (seen.has(track.name)) {
3647
+ console.warn(`pc-anim${label} - duplicate track name '${track.name}' - track skipped`);
3648
+ continue;
3649
+ }
3650
+ seen.add(track.name);
3651
+ component.assignAnimation(track.name, track);
3652
+ }
3653
+ this._autoAssigned = seen.size > 0;
3654
+ this._applySelection(restore);
3655
+ }
3656
+ /**
3657
+ * Applies the active-clip selection: the declared `clip` when it names an assigned state,
3658
+ * else a captured pre-rebuild state when it survived, else the engine's default (the first
3659
+ * assigned clip). A restore also reinstates the playhead and both playing flags exactly as
3660
+ * captured — the reassignment that preceded it set both to the `activate` outcome, which is
3661
+ * not necessarily the state the rebuild interrupted.
3662
+ */
3663
+ _applySelection(restore) {
3664
+ const component = this.component;
3665
+ const layer = component ? component.baseLayer : null;
3666
+ if (!component || !layer) {
3667
+ return;
3668
+ }
3669
+ if (this._clip && !layer.states.includes(this._clip)) {
3670
+ this._warnUnknownClip(this._clip);
3671
+ }
3672
+ let target = null;
3673
+ if (this._clip && layer.states.includes(this._clip)) {
3674
+ target = this._clip;
3675
+ }
3676
+ else if (restore && layer.states.includes(restore.state)) {
3677
+ target = restore.state;
3678
+ }
3679
+ if (target && layer.activeState !== target) {
3680
+ layer.play(target);
3681
+ }
3682
+ if (restore) {
3683
+ if (target === restore.state) {
3684
+ layer.activeStateCurrentTime = restore.time;
3685
+ }
3686
+ layer.playing = restore.layerPlaying;
3687
+ component.playing = restore.playing;
3688
+ }
3689
+ }
3690
+ _warnUnknownClip(name) {
3691
+ if (this._warnedClip === name) {
3692
+ return;
3693
+ }
3694
+ this._warnedClip = name;
3695
+ const label = this.id ? ` '${this.id}'` : '';
3696
+ console.warn(`pc-anim${label} has no clip named '${name}' - selection unchanged`);
3697
+ }
3698
+ /**
3699
+ * Rebuilds the clip set from the DOM, restoring the active clip and playhead when they
3700
+ * survive the rebuild. The engine cannot remove a state from a loaded graph (unassigning
3701
+ * only empties the state's tracks), so removals, renames and source changes drop the whole
3702
+ * graph and reassign.
3703
+ *
3704
+ * @internal
3705
+ */
3706
+ _refreshClips() {
3707
+ const component = this.component;
3708
+ if (!component) {
3709
+ return;
3710
+ }
3711
+ const layer = component.baseLayer;
3712
+ const restore = layer ? {
3713
+ state: layer.activeState,
3714
+ time: layer.activeStateCurrentTime,
3715
+ playing: component.playing,
3716
+ layerPlaying: layer.playing
3717
+ } : undefined;
3718
+ component.removeStateGraph();
3719
+ this._applyClips(restore);
3720
+ }
3721
+ /**
3722
+ * Adopts a clip child announced by its connectedCallback. The initComponent sweep adopts
3723
+ * children already present, so this is a no-op for those; it serves clips appended later,
3724
+ * and flips an auto-assigned element over to its declared children — declared clips win.
3725
+ *
3726
+ * @param clip - The clip element.
3727
+ * @internal
3728
+ */
3729
+ _registerClip(clip) {
3730
+ if (!this.component) {
3731
+ return;
3732
+ }
3733
+ if (this._autoAssigned) {
3734
+ this._refreshClips();
3735
+ return;
3736
+ }
3737
+ if (this._assignedClips.get(clip.name) === clip) {
3738
+ return;
3739
+ }
3740
+ // A clip child appearing supersedes an auto-assign still awaiting its model
3741
+ this._sourceGeneration++;
3742
+ if (this._adoptClip(clip)) {
3743
+ this._applySelection();
3744
+ }
3745
+ }
3746
+ /**
3747
+ * Releases a disconnected clip child. Rebuilds the set — a state cannot be removed from a
3748
+ * live graph — and the removal of the last child inside a `<pc-model>` flips the element
3749
+ * back to auto-assigning the model's clips.
3750
+ *
3751
+ * @param clip - The clip element.
3752
+ * @internal
3753
+ */
3754
+ _unregisterClip(clip) {
3755
+ if (!this.component) {
3756
+ // The whole subtree is coming down (parents disconnect first) - nothing to rebuild
3757
+ return;
3758
+ }
3759
+ if (this._assignedClips.get(clip.name) !== clip) {
3760
+ // The clip never held a state (invalid or duplicate name)
3761
+ return;
3762
+ }
3763
+ this._refreshClips();
3764
+ }
3765
+ /**
3766
+ * Swaps a clip's resolved track in for the placeholder (or for its previous track after an
3767
+ * asset change). A swap of the active clip restarts it: the engine preserves the playhead
3768
+ * through a track replacement, which would land mid-way into unrelated animation.
3769
+ *
3770
+ * @param clip - The clip element.
3771
+ * @returns Whether the clip still owns its state — the resolution may have been superseded
3772
+ * by a rebuild that dropped it.
3773
+ * @internal
3774
+ */
3775
+ _onClipResolved(clip) {
3776
+ const component = this.component;
3777
+ if (!component || this._assignedClips.get(clip.name) !== clip) {
3778
+ return false;
3779
+ }
3780
+ this._assignClip(clip);
3781
+ const layer = component.baseLayer;
3782
+ if (layer && layer.activeState === clip.name) {
3783
+ layer.play(clip.name);
3784
+ }
3785
+ return true;
3786
+ }
3787
+ /**
3788
+ * Applies a clip's changed speed or loop. The engine bakes both into the playback state it
3789
+ * creates on state entry, so a live change re-enters the state and restores the playhead.
3790
+ *
3791
+ * @param clip - The clip element.
3792
+ * @internal
3793
+ */
3794
+ _onClipParamsChanged(clip) {
3795
+ const component = this.component;
3796
+ if (!component || this._assignedClips.get(clip.name) !== clip) {
3797
+ return;
3798
+ }
3799
+ this._assignClip(clip);
3800
+ const layer = component.baseLayer;
3801
+ if (layer && layer.activeState === clip.name) {
3802
+ const time = layer.activeStateCurrentTime;
3803
+ layer.play(clip.name);
3804
+ layer.activeStateCurrentTime = time;
3805
+ }
3806
+ }
3807
+ /**
3808
+ * Resumes playback, optionally switching to a named clip first (a hard cut). A name that
3809
+ * matches no clip leaves the selection unchanged.
3810
+ *
3811
+ * @param name - The name of the clip to play. Resumes the current clip when omitted.
3812
+ */
3813
+ play(name) {
3814
+ const component = this.component;
3815
+ const layer = component ? component.baseLayer : null;
3816
+ if (!component || !layer) {
3817
+ return;
3818
+ }
3819
+ // layer.play sets the layer controller's playing flag; the component's is the system
3820
+ // gate. Setting both is what makes this a resume regardless of how playback stopped.
3821
+ if (name !== undefined) {
3822
+ if (!layer.states.includes(name)) {
3823
+ return;
3824
+ }
3825
+ layer.play(name);
3826
+ }
3827
+ else {
3828
+ layer.play();
3829
+ }
3830
+ component.playing = true;
3831
+ }
3832
+ /**
3833
+ * Pauses playback, preserving the playhead — {@link play} resumes from where it stopped.
3834
+ */
3835
+ pause() {
3836
+ if (!this.component) {
3837
+ return;
3838
+ }
3839
+ // Only the component flag - the single gate the system tick reads - is cleared. The
3840
+ // layer controller's flag is left as-is so a pause is exactly reversible, whether
3841
+ // resumed through play() (which sets both) or through the component API directly.
3842
+ this.component.playing = false;
3843
+ }
3844
+ /**
3845
+ * Cross-fades to a named clip and ensures playback is running. A name that matches no clip
3846
+ * leaves the selection unchanged.
3847
+ *
3848
+ * @param name - The name of the clip to fade to.
3849
+ * @param time - The fade duration in seconds. Defaults to the `transition-time` attribute.
3850
+ */
3851
+ transition(name, time) {
3852
+ const component = this.component;
3853
+ const layer = component ? component.baseLayer : null;
3854
+ if (!component || !layer || !layer.states.includes(name)) {
3855
+ return;
3856
+ }
3857
+ layer.transition(name, Math.max(0, time ?? this._transitionTime));
3858
+ layer.playing = true;
3859
+ component.playing = true;
3860
+ }
3861
+ /**
3862
+ * Gets the underlying PlayCanvas anim component.
3863
+ * @returns The anim component.
3864
+ */
3865
+ get component() {
3866
+ return super.component;
3867
+ }
3868
+ /**
3869
+ * Gets the names of the assigned clips.
3870
+ * @returns The clip names, in assignment order.
3871
+ */
3872
+ get clips() {
3873
+ const layer = this.component ? this.component.baseLayer : null;
3874
+ return layer ? layer.states.filter(state => !playcanvas.ANIM_CONTROL_STATES.includes(state)) : [];
3875
+ }
3876
+ /**
3877
+ * Sets whether playback starts automatically once a clip is assigned. Defaults to `true`.
3878
+ * Applies when clips are assigned — it does not stop a clip that is already playing.
3879
+ * @param value - Whether playback starts automatically.
3880
+ */
3881
+ set activate(value) {
3882
+ this._activate = value;
3883
+ if (this.component) {
3884
+ this.component.activate = value;
3885
+ }
3886
+ }
3887
+ /**
3888
+ * Gets whether playback starts automatically once a clip is assigned.
3889
+ * @returns Whether playback starts automatically.
3890
+ */
3891
+ get activate() {
3892
+ return this._activate;
3893
+ }
3894
+ /**
3895
+ * Sets the name of the active clip. Changing it switches playback, cross-fading over
3896
+ * `transition-time` seconds (a hard cut at 0). An empty value leaves the current clip
3897
+ * playing; a name that matches no clip warns and leaves the selection unchanged.
3898
+ * @param value - The name of the active clip.
3899
+ */
3900
+ set clip(value) {
3901
+ this._clip = value;
3902
+ const component = this.component;
3903
+ const layer = component ? component.baseLayer : null;
3904
+ if (!component || !layer || !value) {
3905
+ return;
3906
+ }
3907
+ if (!layer.states.includes(value)) {
3908
+ this._warnUnknownClip(value);
3909
+ return;
3910
+ }
3911
+ if (layer.activeState === value) {
3912
+ return;
3913
+ }
3914
+ if (this._transitionTime > 0) {
3915
+ this.transition(value);
3916
+ }
3917
+ else {
3918
+ this.play(value);
3919
+ }
3920
+ }
3921
+ /**
3922
+ * Gets the name of the active clip.
3923
+ * @returns The name of the active clip.
3924
+ */
3925
+ get clip() {
3926
+ return this._clip;
3927
+ }
3928
+ /**
3929
+ * Sets the playback speed multiplier applied across all clips, where 0 freezes playback.
3930
+ * Defaults to 1.
3931
+ * @param value - The playback speed multiplier.
3932
+ */
3933
+ set speed(value) {
3934
+ this._speed = value;
3935
+ if (this.component) {
3936
+ this.component.speed = value;
3937
+ }
3938
+ }
3939
+ /**
3940
+ * Gets the playback speed multiplier applied across all clips.
3941
+ * @returns The playback speed multiplier.
3942
+ */
3943
+ get speed() {
3944
+ return this._speed;
3945
+ }
3946
+ /**
3947
+ * Sets the cross-fade duration of clip switches made through the `clip` attribute, in
3948
+ * seconds. Defaults to 0 (a hard cut).
3949
+ * @param value - The cross-fade duration in seconds.
3950
+ */
3951
+ set transitionTime(value) {
3952
+ this._transitionTime = value;
3953
+ }
3954
+ /**
3955
+ * Gets the cross-fade duration of clip switches made through the `clip` attribute.
3956
+ * @returns The cross-fade duration in seconds.
3957
+ */
3958
+ get transitionTime() {
3959
+ return this._transitionTime;
3960
+ }
3961
+ static get observedAttributes() {
3962
+ return [...super.observedAttributes, 'activate', 'clip', 'speed', 'transition-time'];
3963
+ }
3964
+ attributeChangedCallback(name, _oldValue, newValue) {
3965
+ super.attributeChangedCallback(name, _oldValue, newValue);
3966
+ switch (name) {
3967
+ case 'activate':
3968
+ this.activate = parseBool(newValue, true);
3969
+ break;
3970
+ case 'clip':
3971
+ this.clip = newValue ?? '';
3972
+ break;
3973
+ case 'speed':
3974
+ this.speed = parseNumber(newValue, 1, name);
3975
+ break;
3976
+ case 'transition-time':
3977
+ this.transitionTime = parseNumber(newValue, 0, name);
3978
+ break;
3979
+ }
3980
+ }
3981
+ }
3982
+ customElements.define('pc-anim', AnimComponentElement);
3983
+
3984
+ /**
3985
+ * The AnimClipElement interface provides properties and methods for manipulating
3986
+ * {@link https://developer.playcanvas.com/user-manual/web-components/tags/pc-anim-clip/ | `<pc-anim-clip>`}
3987
+ * elements. The AnimClipElement interface also inherits the properties and methods of the
3988
+ * {@link HTMLElement} interface.
3989
+ *
3990
+ * A clip declares one named animation on its parent `<pc-anim>`. `name` is both the clip's name
3991
+ * and the track looked up in the clip's source: an explicit `asset` (a `container`, an
3992
+ * `animation` `.glb`, or an `animclip` JSON), or, without one, the container of the `<pc-model>`
3993
+ * enclosing the parent `<pc-anim>`. A source holding a single track supplies it whatever it is
3994
+ * named; in a multi-track source the track named `name` is chosen, falling back to the first
3995
+ * with a warning. The element becomes ready once its resolved track is assigned.
3996
+ *
3997
+ * @category Components
3998
+ */
3999
+ class AnimClipElement extends AsyncElement {
2941
4000
  /**
2942
- * The element hosting this component, held so the host's readiness cycles can be observed
2943
- * even after `closestEntity` would no longer resolve (during teardown).
4001
+ * The `<pc-anim>` this clip was adopted by, captured when the parent adopts the clip and on
4002
+ * connection.
4003
+ *
4004
+ * `disconnectedCallback` cannot rediscover it: by the time the element is disconnected its
4005
+ * `parentElement` is already `null`, so a lookup would both fail to find the component and
4006
+ * emit a misleading "must be a direct child" warning for what is an ordinary removal.
2944
4007
  */
2945
- _hostElement = null;
4008
+ _animElement = null;
4009
+ _asset = '';
2946
4010
  /**
2947
- * The listener re-applying this component when the host's readiness cycles. Held for
2948
- * removal on disconnect.
4011
+ * Incremented on every connect and disconnect, and captured by connectedCallback on entry —
4012
+ * a resume from an await abandons itself if the value has moved on, so a stale callback can
4013
+ * neither act on a torn-down tree nor register its clip alongside a re-inserted element's
4014
+ * own callback.
2949
4015
  */
2950
- _hostReadyListener = null;
4016
+ _connectionGeneration = 0;
4017
+ _errorHandle = null;
2951
4018
  /**
2952
- * Incremented on every connect and disconnect. connectedCallback captures the value on entry
2953
- * and abandons itself wherever it resumes from an await if the value has moved on — so a
2954
- * callback whose element was removed cannot act on a torn-down tree, and one whose element
2955
- * was removed and re-inserted (which runs a callback of its own) cannot add the component a
2956
- * second time.
4019
+ * Incremented on every track resolution and on disconnect, and captured by a resolution when
4020
+ * it starts. A resolution that resumes from an await or an asset callback abandons itself if
4021
+ * the value has moved on, so a superseded resolution cannot hand a stale track to the parent.
2957
4022
  */
2958
- _connectionGeneration = 0;
4023
+ _loadGeneration = 0;
2959
4024
  /**
2960
- * Creates a new ComponentElement instance.
4025
+ * The pending asset subscriptions of the current resolution, if it is waiting for its asset.
4026
+ * Held so that whatever supersedes the resolution can detach the handlers from the asset,
4027
+ * rather than leave them registered until the asset settles (or forever, if it never does).
4028
+ */
4029
+ _loadHandle = null;
4030
+ _loop = true;
4031
+ _name = '';
4032
+ _speed = 1;
4033
+ /**
4034
+ * The source complaint already made — the asset id it was made for, or `''` for the
4035
+ * no-asset-no-model case — so re-resolutions (host cycles, model reloads) do not repeat it.
4036
+ */
4037
+ _warnedSource = null;
4038
+ /**
4039
+ * Whether the owning `<pc-anim>` already rejected this clip's name — its sweeps re-run on
4040
+ * host cycles and must not repeat the complaint.
4041
+ */
4042
+ _warnedInvalid = false;
4043
+ /**
4044
+ * The clip's resolved track. `null` until resolution completes, during which the owning
4045
+ * `<pc-anim>` assigns the engine's placeholder track in its stead.
2961
4046
  *
2962
- * @param componentName - The name of the component.
2963
- * @ignore
4047
+ * @internal
2964
4048
  */
2965
- constructor(componentName) {
2966
- super();
2967
- this._componentName = componentName;
4049
+ _track = null;
4050
+ async connectedCallback() {
4051
+ const generation = ++this._connectionGeneration;
4052
+ const animElement = this.animElement;
4053
+ await animElement?.ready();
4054
+ // The element may have been removed (perhaps re-inserted, which runs a callback of its
4055
+ // own), or its parent torn down, while we were waiting. A <pc-app> disconnects before
4056
+ // its children, so by the time we resume the component can already be gone - see the
4057
+ // matching guard in disconnectedCallback below.
4058
+ const component = animElement ? animElement.component : null;
4059
+ if (generation !== this._connectionGeneration || !animElement || !component) {
4060
+ return;
4061
+ }
4062
+ this._animElement = animElement;
4063
+ animElement._registerClip(this);
4064
+ }
4065
+ disconnectedCallback() {
4066
+ // Invalidate any connectedCallback or track resolution still suspended on an await
4067
+ this._connectionGeneration++;
4068
+ this._loadGeneration++;
4069
+ this._detachLoadHandlers();
4070
+ // Uses the cached parent rather than a fresh lookup, since parentElement is already null
4071
+ // by now. The component itself is null if the whole <pc-app> is being torn down —
4072
+ // parents disconnect first and have already removed the component.
4073
+ this._animElement?._unregisterClip(this);
4074
+ this._animElement = null;
4075
+ this._track = null;
4076
+ this._resetReady();
4077
+ }
4078
+ get animElement() {
4079
+ const animElement = this.parentElement;
4080
+ if (!(animElement instanceof AnimComponentElement)) {
4081
+ const label = this._name ? ` '${this._name}'` : '';
4082
+ console.warn(`pc-anim-clip${label} must be a direct child of a pc-anim element`);
4083
+ return null;
4084
+ }
4085
+ return animElement;
4086
+ }
4087
+ _detachLoadHandlers() {
4088
+ this._loadHandle?.off();
4089
+ this._loadHandle = null;
4090
+ this._errorHandle?.off();
4091
+ this._errorHandle = null;
2968
4092
  }
2969
4093
  /**
2970
- * Returns the data the component is created with. Overridden by subclasses to supply the
2971
- * initial values of their cached properties.
4094
+ * Reports a name-validation failure from the owning `<pc-anim>`, once per name value.
2972
4095
  *
2973
- * @returns The initial component data.
4096
+ * @param message - The complaint.
4097
+ * @internal
2974
4098
  */
2975
- getInitialComponentData() {
2976
- return {};
4099
+ _markInvalid(message) {
4100
+ if (this._warnedInvalid) {
4101
+ return;
4102
+ }
4103
+ this._warnedInvalid = true;
4104
+ console.warn(message);
2977
4105
  }
2978
4106
  /**
2979
- * Creates the component on the host's current entity, removing it first from a previous
2980
- * entity that is still alive (a retargeted `<pc-node>` moves its decorations with it). When
2981
- * the entity already has a component of this type a glTF node arriving with its authored
2982
- * `render` component, say — warns and leaves `component` null. The element-level warning is
2983
- * load-bearing: the engine's own duplicate-addComponent warning is Debug-stripped from
2984
- * production builds, which would otherwise leave a silent null.
4107
+ * Resolves the clip's track from its source and hands it to the owning `<pc-anim>`. Called
4108
+ * by the parent whenever the clip is (re)adopted, and again when the source changes; a newer
4109
+ * resolution supersedes one still in flight. The element becomes ready once the resolved
4110
+ * track is assigned.
4111
+ *
4112
+ * @param animElement - The owning `<pc-anim>`.
4113
+ * @internal
2985
4114
  */
2986
- _applyComponent() {
2987
- const entity = this._hostElement?.entity ?? null;
2988
- if (this._component && this._component.entity === entity) {
4115
+ async _resolveTrack(animElement) {
4116
+ this._animElement = animElement;
4117
+ const generation = ++this._loadGeneration;
4118
+ this._detachLoadHandlers();
4119
+ if (this._asset) {
4120
+ const asset = useAsset(this._asset);
4121
+ if (!asset) {
4122
+ this._warnSource(`pc-anim-clip '${this._name}' could not find asset '${this._asset}' - clip not assigned`);
4123
+ return;
4124
+ }
4125
+ if (asset.loaded) {
4126
+ this._extractTrack(asset, `asset '${this._asset}'`);
4127
+ return;
4128
+ }
4129
+ // Whichever of load/error fires first detaches the other. The generation is
4130
+ // re-checked even though a superseded handler is detached: the detach relies on how
4131
+ // the engine's event emitter treats removal, while the check holds on its own.
4132
+ this._loadHandle = asset.once('load', () => {
4133
+ this._detachLoadHandlers();
4134
+ if (generation !== this._loadGeneration) {
4135
+ return;
4136
+ }
4137
+ this._extractTrack(asset, `asset '${this._asset}'`);
4138
+ });
4139
+ this._errorHandle = asset.once('error', () => {
4140
+ this._detachLoadHandlers();
4141
+ if (generation !== this._loadGeneration) {
4142
+ return;
4143
+ }
4144
+ this._warnSource(`pc-anim-clip '${this._name}' - asset '${this._asset}' failed to load - clip not assigned`);
4145
+ });
2989
4146
  return;
2990
4147
  }
2991
- // A retarget leaves the previous component on a still-live entity - remove it so the
2992
- // decoration follows the element, or vanishes with a dissolved binding. A destroyed
2993
- // entity took its components with it.
2994
- const previous = this._component;
2995
- if (previous?.entity && previous.entity.c[this._componentName] === previous) {
2996
- previous.entity.removeComponent(this._componentName);
4148
+ const model = animElement.parentElement;
4149
+ if (!(model instanceof ModelElement)) {
4150
+ this._warnSource(`pc-anim-clip '${this._name}' has no asset and no enclosing pc-model - clip not assigned`);
4151
+ return;
2997
4152
  }
2998
- this._component = null;
2999
- if (!entity) {
4153
+ await model.ready();
4154
+ if (generation !== this._loadGeneration) {
3000
4155
  return;
3001
4156
  }
3002
- if (entity.c[this._componentName]) {
3003
- const label = this.id ? ` '${this.id}'` : '';
3004
- console.warn(`${this.tagName.toLowerCase()}${label} - '${entity.name}' already has a '${this._componentName}' component - component not added`);
4157
+ const asset = AssetElement.get(model.asset);
4158
+ if (!asset?.resource) {
4159
+ // The model's load failed; it already reported the error
3005
4160
  return;
3006
4161
  }
3007
- this._component = entity.addComponent(this._componentName, this.getInitialComponentData());
4162
+ this._extractTrack(asset, `model '${model.asset}'`);
3008
4163
  }
3009
- async _addComponent() {
3010
- const generation = this._connectionGeneration;
3011
- const entityElement = this.closestEntity;
3012
- if (!entityElement) {
3013
- // A component can only exist on an entity, so an element placed outside one is inert.
3014
- // It still becomes ready (with a null `component`), so warn rather than fail silently
3015
- const label = this.id ? ` '${this.id}'` : '';
3016
- console.warn(`${this.tagName.toLowerCase()}${label} must be a descendant of pc-entity - component not added`);
4164
+ /**
4165
+ * Complains about the clip's source, once per source value — resolutions re-run on host
4166
+ * cycles and model reloads, and must not repeat the complaint.
4167
+ */
4168
+ _warnSource(message) {
4169
+ if (this._warnedSource === this._asset) {
3017
4170
  return;
3018
4171
  }
3019
- await entityElement.ready();
3020
- // The element may have been removed, or removed and re-inserted, while the entity became
3021
- // ready — the component belongs to the connection that owns the current generation.
3022
- if (generation !== this._connectionGeneration) {
4172
+ this._warnedSource = this._asset;
4173
+ console.warn(message);
4174
+ }
4175
+ /**
4176
+ * Picks the clip's track out of a loaded source asset: the track named `name`, or a lone
4177
+ * track whatever it is named, or the first of several with a warning.
4178
+ *
4179
+ * @param asset - The loaded source asset.
4180
+ * @param source - How warnings name the source.
4181
+ */
4182
+ _extractTrack(asset, source) {
4183
+ const label = `pc-anim-clip '${this._name}'`;
4184
+ // Widened: the engine registers an 'animclip' handler but omits the type from the
4185
+ // Asset.type union
4186
+ const type = asset.type;
4187
+ let candidates;
4188
+ switch (type) {
4189
+ case 'container':
4190
+ candidates = asset.resource.animations.map((animationAsset) => animationAsset.resource);
4191
+ break;
4192
+ case 'animation':
4193
+ candidates = asset.resources;
4194
+ break;
4195
+ case 'animclip':
4196
+ candidates = [asset.resource];
4197
+ break;
4198
+ default:
4199
+ this._warnSource(`${label} - ${source} has type '${asset.type}', expected 'container', 'animation' or 'animclip' - clip not assigned`);
4200
+ return;
4201
+ }
4202
+ // A JSON 'animation' asset parses to the engine's legacy Animation class, which the anim
4203
+ // system rejects - only real AnimTracks qualify
4204
+ const tracks = candidates.filter((candidate) => candidate instanceof playcanvas.AnimTrack);
4205
+ if (tracks.length === 0) {
4206
+ this._warnSource(`${label} - ${source} contains no usable animation track - clip not assigned`);
3023
4207
  return;
3024
4208
  }
3025
- this._hostElement = entityElement;
3026
- this._applyComponent();
3027
- // Re-apply when the host's readiness cycles without this element disconnecting: a
3028
- // `<pc-node>` rebinding after its model reloads or retargets, or a re-created entity.
3029
- // The 'ready' event bubbles, so events from descendants pass through this host - only
3030
- // the host's own cycles count. Readiness is cycled here too, so decorations one level
3031
- // down re-apply the same way.
3032
- this._hostReadyListener = (event) => {
3033
- if (event.target !== this._hostElement) {
3034
- return;
3035
- }
3036
- if (generation !== this._connectionGeneration) {
3037
- return;
4209
+ let track = tracks.find((candidate) => candidate.name === this._name);
4210
+ if (!track) {
4211
+ track = tracks[0];
4212
+ if (tracks.length > 1) {
4213
+ console.warn(`${label} - no track named '${this._name}' in ${source} - using '${track.name}' (available: ${tracks.map((candidate) => candidate.name).join(', ')})`);
3038
4214
  }
3039
- this._hostCycled();
3040
- };
3041
- entityElement.addEventListener('ready', this._hostReadyListener);
4215
+ }
4216
+ this._track = track;
4217
+ if (this._animElement?._onClipResolved(this)) {
4218
+ this._onReady();
4219
+ }
3042
4220
  }
3043
4221
  /**
3044
- * Re-evaluates this component against the host's current entity: applied to a new entity,
3045
- * moved from a still-live old one, or removed when the host no longer fronts an entity at
3046
- * all. Readiness follows - it cycles with a re-application and stays unresolved while the
3047
- * host is unbound. Called by the host-ready listener, and directly by a `<pc-node>`
3048
- * dissolving its binding: the one transition that fires no ready event to ride.
3049
- *
3050
- * @internal
4222
+ * Sets the id of the `pc-asset` supplying the clip's track: a `container`, an `animation`
4223
+ * `.glb`, or an `animclip` JSON. When empty, the track comes from the container of the
4224
+ * `<pc-model>` enclosing the parent `<pc-anim>`.
4225
+ * @param value - The asset id.
3051
4226
  */
3052
- _hostCycled() {
3053
- this._resetReady();
3054
- this._applyComponent();
3055
- if (this._hostElement?.entity) {
3056
- this.initComponent();
3057
- this._onReady();
4227
+ set asset(value) {
4228
+ this._asset = value;
4229
+ this._warnedSource = null;
4230
+ if (this._animElement) {
4231
+ this._resetReady();
4232
+ this._track = null;
4233
+ this._resolveTrack(this._animElement);
3058
4234
  }
3059
4235
  }
3060
4236
  /**
3061
- * Configures the newly added component. Overridden by subclasses whose setup goes beyond
3062
- * the initial data — child-element handling, asset resolution and the like.
4237
+ * Gets the id of the `pc-asset` supplying the clip's track.
4238
+ * @returns The asset id.
4239
+ */
4240
+ get asset() {
4241
+ return this._asset;
4242
+ }
4243
+ /**
4244
+ * Sets whether the clip loops. A non-looping clip holds its last pose when it ends — the
4245
+ * engine reports no completion. Defaults to `true`.
4246
+ * @param value - Whether the clip loops.
3063
4247
  */
3064
- initComponent() {
3065
- // optional hook
4248
+ set loop(value) {
4249
+ this._loop = value;
4250
+ this._animElement?._onClipParamsChanged(this);
3066
4251
  }
3067
- async connectedCallback() {
3068
- const generation = ++this._connectionGeneration;
3069
- this._appElement = this.closestApp ?? null;
3070
- await this._appElement?.ready();
3071
- // The element may have been removed, or removed and re-inserted, while the application
3072
- // became ready. A re-insertion runs a connectedCallback of its own, so a stale resume
3073
- // must not add the component alongside it.
3074
- if (generation !== this._connectionGeneration) {
3075
- return;
3076
- }
3077
- await this._addComponent();
3078
- if (generation !== this._connectionGeneration) {
3079
- return;
3080
- }
3081
- this.initComponent();
3082
- this._onReady();
4252
+ /**
4253
+ * Gets whether the clip loops.
4254
+ * @returns Whether the clip loops.
4255
+ */
4256
+ get loop() {
4257
+ return this._loop;
3083
4258
  }
3084
- disconnectedCallback() {
3085
- // Invalidate any connectedCallback still suspended on an await
3086
- this._connectionGeneration++;
3087
- if (this._hostElement && this._hostReadyListener) {
3088
- this._hostElement.removeEventListener('ready', this._hostReadyListener);
3089
- }
3090
- this._hostElement = null;
3091
- this._hostReadyListener = null;
3092
- // Remove the component when the element is disconnected. Skip this when the owning
3093
- // application has already been destroyed — removing a <pc-app> disconnects it before
3094
- // its children, taking the component systems with it.
3095
- if (this._appElement?.app && this._component?.entity) {
3096
- this._component.entity.removeComponent(this._componentName);
4259
+ /**
4260
+ * Sets the name of the clip: the name it is played by, and the track looked up in the
4261
+ * clip's source. Names must be unique within a `<pc-anim>` and must not contain `.`.
4262
+ * @param value - The clip name.
4263
+ */
4264
+ set name(value) {
4265
+ this._name = value;
4266
+ this._warnedInvalid = false;
4267
+ if (this._animElement) {
4268
+ this._resetReady();
4269
+ this._animElement._refreshClips();
3097
4270
  }
3098
- this._component = null;
3099
- this._appElement = null;
3100
- this._resetReady();
3101
4271
  }
3102
4272
  /**
3103
- * The PlayCanvas component instance. `null` until the element is ready, and also for an
3104
- * element that is not a descendant of a `<pc-entity>` — await {@link whenReady} or the
3105
- * element's `ready()` promise before accessing it.
3106
- * @returns The component instance, or `null`.
4273
+ * Gets the name of the clip.
4274
+ * @returns The clip name.
3107
4275
  */
3108
- get component() {
3109
- return this._component;
4276
+ get name() {
4277
+ return this._name;
3110
4278
  }
3111
4279
  /**
3112
- * Sets the enabled state of the component.
3113
- * @param value - The enabled state of the component.
4280
+ * Sets the playback speed of the clip, where negative values play it backwards. Applies
4281
+ * immediately, preserving the playhead. Defaults to 1.
4282
+ * @param value - The playback speed.
3114
4283
  */
3115
- set enabled(value) {
3116
- this._enabled = value;
3117
- if (this.component) {
3118
- this.component.enabled = value;
3119
- }
4284
+ set speed(value) {
4285
+ this._speed = value;
4286
+ this._animElement?._onClipParamsChanged(this);
3120
4287
  }
3121
4288
  /**
3122
- * Gets the enabled state of the component.
3123
- * @returns The enabled state of the component.
4289
+ * Gets the playback speed of the clip.
4290
+ * @returns The playback speed.
3124
4291
  */
3125
- get enabled() {
3126
- return this._enabled;
4292
+ get speed() {
4293
+ return this._speed;
3127
4294
  }
3128
4295
  static get observedAttributes() {
3129
- return ['enabled'];
4296
+ return ['asset', 'loop', 'name', 'speed'];
3130
4297
  }
3131
4298
  attributeChangedCallback(name, _oldValue, newValue) {
3132
4299
  switch (name) {
3133
- case 'enabled':
3134
- this.enabled = parseBool(newValue, true);
4300
+ case 'asset':
4301
+ this.asset = newValue ?? '';
4302
+ break;
4303
+ case 'loop':
4304
+ this.loop = parseBool(newValue, true);
4305
+ break;
4306
+ case 'name':
4307
+ this.name = newValue ?? '';
4308
+ break;
4309
+ case 'speed':
4310
+ this.speed = parseNumber(newValue, 1, name);
3135
4311
  break;
3136
4312
  }
3137
4313
  }
3138
4314
  }
4315
+ customElements.define('pc-anim-clip', AnimClipElement);
3139
4316
 
3140
4317
  /**
3141
4318
  * The ListenerComponentElement interface provides properties and methods for manipulating
@@ -11249,574 +12426,284 @@
11249
12426
  * Gets the overlap flag of the sound slot.
11250
12427
  * @returns The overlap flag.
11251
12428
  */
11252
- get overlap() {
11253
- return this._overlap;
11254
- }
11255
- /**
11256
- * Sets the pitch of the sound slot.
11257
- * @param value - The pitch.
11258
- */
11259
- set pitch(value) {
11260
- this._pitch = value;
11261
- if (this.soundSlot) {
11262
- this.soundSlot.pitch = value;
11263
- }
11264
- }
11265
- /**
11266
- * Gets the pitch of the sound slot.
11267
- * @returns The pitch.
11268
- */
11269
- get pitch() {
11270
- return this._pitch;
11271
- }
11272
- /**
11273
- * Sets the start time of the sound slot.
11274
- * @param value - The start time.
11275
- */
11276
- set startTime(value) {
11277
- this._startTime = value;
11278
- if (this.soundSlot) {
11279
- this.soundSlot.startTime = value;
11280
- }
11281
- }
11282
- /**
11283
- * Gets the start time of the sound slot.
11284
- * @returns The start time.
11285
- */
11286
- get startTime() {
11287
- return this._startTime;
11288
- }
11289
- /**
11290
- * Sets the volume of the sound slot.
11291
- * @param value - The volume.
11292
- */
11293
- set volume(value) {
11294
- this._volume = value;
11295
- if (this.soundSlot) {
11296
- this.soundSlot.volume = value;
11297
- }
11298
- }
11299
- /**
11300
- * Gets the volume of the sound slot.
11301
- * @returns The volume.
11302
- */
11303
- get volume() {
11304
- return this._volume;
11305
- }
11306
- static get observedAttributes() {
11307
- return ['asset', 'auto-play', 'duration', 'loop', 'name', 'overlap', 'pitch', 'start-time', 'volume'];
11308
- }
11309
- attributeChangedCallback(name, _oldValue, newValue) {
11310
- switch (name) {
11311
- case 'asset':
11312
- this.asset = newValue ?? '';
11313
- break;
11314
- case 'auto-play':
11315
- this.autoPlay = parseBool(newValue, false);
11316
- break;
11317
- case 'duration':
11318
- this.duration = parseNumber(newValue, null, name);
11319
- break;
11320
- case 'loop':
11321
- this.loop = parseBool(newValue, false);
11322
- break;
11323
- case 'name':
11324
- this.name = newValue ?? '';
11325
- break;
11326
- case 'overlap':
11327
- this.overlap = parseBool(newValue, false);
11328
- break;
11329
- case 'pitch':
11330
- this.pitch = parseNumber(newValue, 1, name);
11331
- break;
11332
- case 'start-time':
11333
- this.startTime = parseNumber(newValue, 0, name);
11334
- break;
11335
- case 'volume':
11336
- this.volume = parseNumber(newValue, 1, name);
11337
- break;
11338
- }
11339
- }
11340
- }
11341
- customElements.define('pc-sound', SoundSlotElement);
11342
-
11343
- /**
11344
- * The GSplatComponentElement interface provides properties and methods for manipulating
11345
- * {@link https://developer.playcanvas.com/user-manual/web-components/tags/pc-gsplat/ | `<pc-gsplat>`} elements.
11346
- * The GSplatComponentElement interface also inherits the properties and methods of the
11347
- * {@link HTMLElement} interface.
11348
- *
11349
- * @category Components
11350
- */
11351
- class GSplatComponentElement extends ComponentElement {
11352
- _asset = '';
11353
- _castShadows = false;
11354
- _lodBaseDistance = 5;
11355
- _lodMultiplier = 3;
11356
- _lodRangeMin = 0;
11357
- _lodRangeMax = 99;
11358
- /** @ignore */
11359
- constructor() {
11360
- super('gsplat');
11361
- }
11362
- getInitialComponentData() {
11363
- return {
11364
- asset: useAsset(this._asset),
11365
- castShadows: this._castShadows,
11366
- lodBaseDistance: this._lodBaseDistance,
11367
- lodMultiplier: this._lodMultiplier,
11368
- lodRangeMin: this._lodRangeMin,
11369
- lodRangeMax: this._lodRangeMax
11370
- };
11371
- }
11372
- /**
11373
- * Gets the underlying PlayCanvas gsplat component.
11374
- * @returns The gsplat component.
11375
- */
11376
- get component() {
11377
- return super.component;
11378
- }
11379
- /**
11380
- * Sets id of the `pc-asset` to use for the splat.
11381
- * @param value - The asset ID.
11382
- */
11383
- set asset(value) {
11384
- this._asset = value;
11385
- const asset = useAsset(value);
11386
- if (this.component && asset) {
11387
- this.component.asset = asset;
11388
- }
11389
- }
11390
- /**
11391
- * Gets the id of the `pc-asset` to use for the splat.
11392
- * @returns The asset ID.
11393
- */
11394
- get asset() {
11395
- return this._asset;
11396
- }
11397
- /**
11398
- * Sets whether the splat casts shadows.
11399
- * @param value - Whether the splat casts shadows.
11400
- */
11401
- set castShadows(value) {
11402
- this._castShadows = value;
11403
- if (this.component) {
11404
- this.component.castShadows = value;
11405
- }
11406
- }
11407
- /**
11408
- * Gets whether the splat casts shadows.
11409
- * @returns Whether the splat casts shadows.
11410
- */
11411
- get castShadows() {
11412
- return this._castShadows;
11413
- }
11414
- /**
11415
- * Sets the base distance for the first LOD transition (LOD 0 to LOD 1). Splats closer than
11416
- * this distance use the highest quality LOD. Each subsequent LOD level transitions at a
11417
- * progressively larger distance, controlled by {@link lodMultiplier}. Clamped to a minimum of
11418
- * 0.1. Defaults to 5. Only affects assets that contain LOD levels (e.g. `.lod-meta.json`).
11419
- * @param value - The LOD base distance.
11420
- */
11421
- set lodBaseDistance(value) {
11422
- this._lodBaseDistance = value;
11423
- if (this.component) {
11424
- this.component.lodBaseDistance = value;
11425
- }
11426
- }
11427
- /**
11428
- * Gets the base distance for the first LOD transition.
11429
- * @returns The LOD base distance.
11430
- */
11431
- get lodBaseDistance() {
11432
- return this._lodBaseDistance;
12429
+ get overlap() {
12430
+ return this._overlap;
11433
12431
  }
11434
12432
  /**
11435
- * Sets the multiplier between successive LOD distance thresholds. Each LOD level transitions
11436
- * at this factor times the previous level's distance, creating a geometric progression. Lower
11437
- * values keep higher quality at distance; higher values switch to coarser LODs sooner. Clamped
11438
- * to a minimum of 1.2. Defaults to 3. Only affects assets that contain LOD levels (e.g.
11439
- * `.lod-meta.json`).
11440
- * @param value - The LOD multiplier.
12433
+ * Sets the pitch of the sound slot.
12434
+ * @param value - The pitch.
11441
12435
  */
11442
- set lodMultiplier(value) {
11443
- this._lodMultiplier = value;
11444
- if (this.component) {
11445
- this.component.lodMultiplier = value;
12436
+ set pitch(value) {
12437
+ this._pitch = value;
12438
+ if (this.soundSlot) {
12439
+ this.soundSlot.pitch = value;
11446
12440
  }
11447
12441
  }
11448
12442
  /**
11449
- * Gets the multiplier between successive LOD distance thresholds.
11450
- * @returns The LOD multiplier.
12443
+ * Gets the pitch of the sound slot.
12444
+ * @returns The pitch.
11451
12445
  */
11452
- get lodMultiplier() {
11453
- return this._lodMultiplier;
12446
+ get pitch() {
12447
+ return this._pitch;
11454
12448
  }
11455
12449
  /**
11456
- * Sets the minimum allowed LOD index (inclusive). The LOD selected by distance is clamped so it
11457
- * never goes finer (lower index) than this value. Raising it avoids downloading the highest
11458
- * quality (largest) LOD files. Defaults to 0. Only affects assets that contain LOD levels (e.g.
11459
- * `.lod-meta.json`).
11460
- * @param value - The minimum LOD index.
12450
+ * Sets the start time of the sound slot.
12451
+ * @param value - The start time.
11461
12452
  */
11462
- set lodRangeMin(value) {
11463
- this._lodRangeMin = value;
11464
- if (this.component) {
11465
- this.component.lodRangeMin = value;
12453
+ set startTime(value) {
12454
+ this._startTime = value;
12455
+ if (this.soundSlot) {
12456
+ this.soundSlot.startTime = value;
11466
12457
  }
11467
12458
  }
11468
12459
  /**
11469
- * Gets the minimum allowed LOD index.
11470
- * @returns The minimum LOD index.
12460
+ * Gets the start time of the sound slot.
12461
+ * @returns The start time.
11471
12462
  */
11472
- get lodRangeMin() {
11473
- return this._lodRangeMin;
12463
+ get startTime() {
12464
+ return this._startTime;
11474
12465
  }
11475
12466
  /**
11476
- * Sets the maximum allowed LOD index (inclusive). The LOD selected by distance is clamped so it
11477
- * never goes coarser (higher index) than this value. The default of 99 effectively means "no
11478
- * cap". Defaults to 99. Only affects assets that contain LOD levels (e.g. `.lod-meta.json`).
11479
- * @param value - The maximum LOD index.
12467
+ * Sets the volume of the sound slot.
12468
+ * @param value - The volume.
11480
12469
  */
11481
- set lodRangeMax(value) {
11482
- this._lodRangeMax = value;
11483
- if (this.component) {
11484
- this.component.lodRangeMax = value;
12470
+ set volume(value) {
12471
+ this._volume = value;
12472
+ if (this.soundSlot) {
12473
+ this.soundSlot.volume = value;
11485
12474
  }
11486
12475
  }
11487
12476
  /**
11488
- * Gets the maximum allowed LOD index.
11489
- * @returns The maximum LOD index.
12477
+ * Gets the volume of the sound slot.
12478
+ * @returns The volume.
11490
12479
  */
11491
- get lodRangeMax() {
11492
- return this._lodRangeMax;
12480
+ get volume() {
12481
+ return this._volume;
11493
12482
  }
11494
12483
  static get observedAttributes() {
11495
- return [
11496
- ...super.observedAttributes,
11497
- 'asset',
11498
- 'cast-shadows',
11499
- 'lod-base-distance',
11500
- 'lod-multiplier',
11501
- 'lod-range-min',
11502
- 'lod-range-max'
11503
- ];
12484
+ return ['asset', 'auto-play', 'duration', 'loop', 'name', 'overlap', 'pitch', 'start-time', 'volume'];
11504
12485
  }
11505
12486
  attributeChangedCallback(name, _oldValue, newValue) {
11506
- super.attributeChangedCallback(name, _oldValue, newValue);
11507
12487
  switch (name) {
11508
12488
  case 'asset':
11509
12489
  this.asset = newValue ?? '';
11510
12490
  break;
11511
- case 'cast-shadows':
11512
- this.castShadows = parseBool(newValue, false);
12491
+ case 'auto-play':
12492
+ this.autoPlay = parseBool(newValue, false);
11513
12493
  break;
11514
- case 'lod-base-distance':
11515
- this.lodBaseDistance = parseNumber(newValue, 5, name);
12494
+ case 'duration':
12495
+ this.duration = parseNumber(newValue, null, name);
11516
12496
  break;
11517
- case 'lod-multiplier':
11518
- this.lodMultiplier = parseNumber(newValue, 3, name);
12497
+ case 'loop':
12498
+ this.loop = parseBool(newValue, false);
11519
12499
  break;
11520
- case 'lod-range-min':
11521
- this.lodRangeMin = parseNumber(newValue, 0, name);
12500
+ case 'name':
12501
+ this.name = newValue ?? '';
11522
12502
  break;
11523
- case 'lod-range-max':
11524
- this.lodRangeMax = parseNumber(newValue, 99, name);
12503
+ case 'overlap':
12504
+ this.overlap = parseBool(newValue, false);
12505
+ break;
12506
+ case 'pitch':
12507
+ this.pitch = parseNumber(newValue, 1, name);
12508
+ break;
12509
+ case 'start-time':
12510
+ this.startTime = parseNumber(newValue, 0, name);
12511
+ break;
12512
+ case 'volume':
12513
+ this.volume = parseNumber(newValue, 1, name);
11525
12514
  break;
11526
12515
  }
11527
12516
  }
11528
12517
  }
11529
- customElements.define('pc-gsplat', GSplatComponentElement);
12518
+ customElements.define('pc-sound', SoundSlotElement);
11530
12519
 
11531
12520
  /**
11532
- * Formats one line of the printable hierarchy: the node's name, an `[index]` marker when the
11533
- * name is shared by several nodes in the model, the attached component types, and the material
11534
- * names of a render component.
11535
- *
11536
- * @param node - The node to format.
11537
- * @param counts - The number of nodes bearing each name.
11538
- * @returns The formatted line.
11539
- */
11540
- const formatNode = (node, counts) => {
11541
- const index = (counts.get(node.name) ?? 0) > 1 ? ` [${node.index}]` : '';
11542
- const components = node.components.length > 0 ? ` (${node.components.join(', ')})` : '';
11543
- // Braces rather than brackets: `[N]` already means a match index on this line
11544
- const materials = node.materials.length > 0 ? ` {${node.materials.map((slot) => slot.name ?? 'null').join(', ')}}` : '';
11545
- return `${node.name}${index}${components}${materials}`;
11546
- };
11547
- /**
11548
- * Formats the printable form of a hierarchy subtree.
11549
- *
11550
- * @param root - The subtree root.
11551
- * @param counts - The number of nodes bearing each name.
11552
- * @returns The tree, one line per node.
11553
- */
11554
- const formatHierarchy = (root, counts) => {
11555
- const lines = [formatNode(root, counts)];
11556
- const walk = (node, prefix) => {
11557
- node.children.forEach((child, i) => {
11558
- const last = i === node.children.length - 1;
11559
- lines.push(`${prefix}${last ? '└─ ' : '├─ '}${formatNode(child, counts)}`);
11560
- walk(child, `${prefix}${last ? ' ' : '│ '}`);
11561
- });
11562
- };
11563
- walk(root, '');
11564
- return lines.join('\n');
11565
- };
11566
- /**
11567
- * The ModelElement interface provides properties and methods for manipulating
11568
- * {@link https://developer.playcanvas.com/user-manual/web-components/tags/pc-model/ | `<pc-model>`} elements.
11569
- * The ModelElement interface also inherits the properties and methods of the
12521
+ * The GSplatComponentElement interface provides properties and methods for manipulating
12522
+ * {@link https://developer.playcanvas.com/user-manual/web-components/tags/pc-gsplat/ | `<pc-gsplat>`} elements.
12523
+ * The GSplatComponentElement interface also inherits the properties and methods of the
11570
12524
  * {@link HTMLElement} interface.
11571
12525
  *
11572
- * The element becomes ready once its container asset has loaded and the instantiated hierarchy has
11573
- * been added to the scene — `entity` is non-null by then. A failed load also settles readiness,
11574
- * with `entity` remaining `null`: readiness means the load settled, not that it succeeded — listen
11575
- * for `error`, or check `entity`, to tell the outcomes apart. Changing `asset` re-arms readiness
11576
- * and instantiates anew, so a `ready()` obtained after the change resolves against the new
11577
- * hierarchy. A `pc-model` outside a `pc-app`, or referencing an unknown asset id, warns and never
11578
- * becomes ready.
11579
- *
11580
- * @fires {Event} load - Fired each time a container asset finishes instantiating, including
11581
- * re-instantiation after `asset` changes. Does not bubble — listen on this element, or use a
11582
- * capture-phase listener on an ancestor.
11583
- * @fires {ErrorEvent} error - Fired when the container asset fails to load, with the engine's
11584
- * error in `message`. Does not bubble. The element still becomes ready — readiness means the load
11585
- * settled, not that it succeeded.
12526
+ * @category Components
11586
12527
  */
11587
- class ModelElement extends AsyncElement {
12528
+ class GSplatComponentElement extends ComponentElement {
11588
12529
  _asset = '';
11589
- _entity = null;
11590
- /**
11591
- * Incremented on every new load and on disconnect, and captured by a load when it starts. A
11592
- * load that resumes from an await or a load callback abandons itself if the value has moved
11593
- * on, so a superseded load can neither instantiate a second entity nor parent one that has
11594
- * since been destroyed.
11595
- */
11596
- _loadGeneration = 0;
11597
- /**
11598
- * The pending asset subscriptions of the current load, if it is waiting for its asset. Held
11599
- * so that whatever supersedes the load can detach the handlers from the asset, rather than
11600
- * leave them registered until the asset settles (or forever, if it never does).
11601
- */
11602
- _loadHandle = null;
11603
- _errorHandle = null;
11604
- /**
11605
- * The root entity of the instantiated model. `null` until the container asset has loaded
11606
- * and been instantiated, and again once the element has been removed from the document.
11607
- * @returns The model's root entity, or `null`.
11608
- */
11609
- get entity() {
11610
- return this._entity;
12530
+ _castShadows = false;
12531
+ _lodBaseDistance = 5;
12532
+ _lodMultiplier = 3;
12533
+ _lodRangeMin = 0;
12534
+ _lodRangeMax = 99;
12535
+ /** @ignore */
12536
+ constructor() {
12537
+ super('gsplat');
11611
12538
  }
11612
- /**
11613
- * Returns a snapshot of the instantiated node tree, or `null` while there is none (the
11614
- * container asset has not loaded, or the element has left the document). One call grounds a
11615
- * session — a browser console, a test, an agent — in the vocabulary `pc-node` binding
11616
- * resolves against: the instantiated names ({@link HierarchyNode.name}), paths, match
11617
- * indices, attached component types and the material assignments of render components
11618
- * ({@link HierarchyNode.materials}). `String(...)` of the result, or of any node in it,
11619
- * is the printable form.
11620
- *
11621
- * The snapshot is plain data, computed afresh each call: it does not follow later changes
11622
- * to the hierarchy, and mutating it changes nothing.
11623
- *
11624
- * @returns The root of the instantiated node tree, or `null`.
11625
- */
11626
- hierarchy() {
11627
- const root = this._entity;
11628
- if (!root) {
11629
- return null;
11630
- }
11631
- // Ordinals are assigned in the traversal resolution searches — pre-order depth-first
11632
- // from the model root, the root itself included — so each node's index is exactly what
11633
- // a pc-node's index attribute selects. Once the walk completes, the map holds the total
11634
- // count per name, which is what the printable form reads to annotate only shared names.
11635
- const ordinals = new Map();
11636
- const describe = (entity, pathBelowRoot) => {
11637
- const index = ordinals.get(entity.name) ?? 0;
11638
- ordinals.set(entity.name, index + 1);
11639
- const node = {
11640
- name: entity.name,
11641
- // The root has no path below itself; its own name stands in, as it does for
11642
- // the path a pc-node bound to the root reports.
11643
- path: pathBelowRoot || entity.name,
11644
- index,
11645
- // A plain GraphNode grafted into the hierarchy has no component storage
11646
- components: Object.keys(entity.c ?? {}).sort(),
11647
- materials: (entity.render?.meshInstances ?? []).map((meshInstance, slot) => ({
11648
- index: slot,
11649
- name: meshInstance.material?.name ?? null
11650
- })),
11651
- children: entity.children.map((child) => describe(child, pathBelowRoot ? `${pathBelowRoot}/${child.name}` : child.name))
11652
- };
11653
- // Non-enumerable, keeping the snapshot plain data under JSON.stringify, spreads and
11654
- // key enumeration. Deferred to call time, by which the ordinal map holds its totals.
11655
- Object.defineProperty(node, 'toString', {
11656
- enumerable: false,
11657
- value: () => formatHierarchy(node, ordinals)
11658
- });
11659
- return node;
12539
+ getInitialComponentData() {
12540
+ return {
12541
+ asset: useAsset(this._asset),
12542
+ castShadows: this._castShadows,
12543
+ lodBaseDistance: this._lodBaseDistance,
12544
+ lodMultiplier: this._lodMultiplier,
12545
+ lodRangeMin: this._lodRangeMin,
12546
+ lodRangeMax: this._lodRangeMax
11660
12547
  };
11661
- return describe(root, '');
11662
12548
  }
11663
- connectedCallback() {
11664
- // A model outside an application is inert and never becomes ready, so awaiting it hangs.
11665
- // Warn rather than fail silently, naming the parent it requires, as every other misplaced
11666
- // element does.
11667
- if (!this.closestApp) {
11668
- const label = this._asset ? ` '${this._asset}'` : '';
11669
- console.warn(`pc-model${label} must be a descendant of pc-app - model not created`);
11670
- return;
12549
+ /**
12550
+ * Gets the underlying PlayCanvas gsplat component.
12551
+ * @returns The gsplat component.
12552
+ */
12553
+ get component() {
12554
+ return super.component;
12555
+ }
12556
+ /**
12557
+ * Sets id of the `pc-asset` to use for the splat.
12558
+ * @param value - The asset ID.
12559
+ */
12560
+ set asset(value) {
12561
+ this._asset = value;
12562
+ const asset = useAsset(value);
12563
+ if (this.component && asset) {
12564
+ this.component.asset = asset;
11671
12565
  }
11672
- this._loadModel();
11673
12566
  }
11674
- disconnectedCallback() {
11675
- this._loadGeneration++;
11676
- this._detachLoadHandlers();
11677
- this._unloadModel();
11678
- this._resetReady();
12567
+ /**
12568
+ * Gets the id of the `pc-asset` to use for the splat.
12569
+ * @returns The asset ID.
12570
+ */
12571
+ get asset() {
12572
+ return this._asset;
11679
12573
  }
11680
- _detachLoadHandlers() {
11681
- this._loadHandle?.off();
11682
- this._loadHandle = null;
11683
- this._errorHandle?.off();
11684
- this._errorHandle = null;
12574
+ /**
12575
+ * Sets whether the splat casts shadows.
12576
+ * @param value - Whether the splat casts shadows.
12577
+ */
12578
+ set castShadows(value) {
12579
+ this._castShadows = value;
12580
+ if (this.component) {
12581
+ this.component.castShadows = value;
12582
+ }
11685
12583
  }
11686
12584
  /**
11687
- * Resolves readiness and dispatches the `load` event. Called once the instantiated hierarchy
11688
- * has been parented — readiness means "in the scene graph", matching `pc-entity`, so a ready
11689
- * model's entity always has world transforms.
12585
+ * Gets whether the splat casts shadows.
12586
+ * @returns Whether the splat casts shadows.
11690
12587
  */
11691
- _announceLoad() {
11692
- this._onReady();
11693
- this.dispatchEvent(new Event('load'));
12588
+ get castShadows() {
12589
+ return this._castShadows;
11694
12590
  }
11695
- _instantiate(container) {
11696
- const generation = this._loadGeneration;
11697
- const entity = container.instantiateRenderEntity();
11698
- this._entity = entity;
11699
- // @ts-ignore
11700
- if (container.animations.length > 0) {
11701
- entity.addComponent('anim');
11702
- // @ts-ignore
11703
- entity.anim.assignAnimation('animation', container.animations[0].resource);
11704
- }
11705
- // The parent's readiness re-arms when it is torn down, so these can resume in a later
11706
- // connection cycle. The entity is captured above and the generation re-checked, so a
11707
- // stale resume cannot parent an entity a newer cycle has already destroyed.
11708
- const parentEntityElement = this.closestEntity;
11709
- if (parentEntityElement) {
11710
- parentEntityElement.ready().then(() => {
11711
- if (generation !== this._loadGeneration) {
11712
- return;
11713
- }
11714
- parentEntityElement.entity.addChild(entity);
11715
- this._announceLoad();
11716
- });
11717
- }
11718
- else {
11719
- const appElement = this.closestApp;
11720
- if (appElement) {
11721
- appElement.ready().then(() => {
11722
- if (generation !== this._loadGeneration) {
11723
- return;
11724
- }
11725
- appElement.app.root.addChild(entity);
11726
- this._announceLoad();
11727
- });
11728
- }
12591
+ /**
12592
+ * Sets the base distance for the first LOD transition (LOD 0 to LOD 1). Splats closer than
12593
+ * this distance use the highest quality LOD. Each subsequent LOD level transitions at a
12594
+ * progressively larger distance, controlled by {@link lodMultiplier}. Clamped to a minimum of
12595
+ * 0.1. Defaults to 5. Only affects assets that contain LOD levels (e.g. `.lod-meta.json`).
12596
+ * @param value - The LOD base distance.
12597
+ */
12598
+ set lodBaseDistance(value) {
12599
+ this._lodBaseDistance = value;
12600
+ if (this.component) {
12601
+ this.component.lodBaseDistance = value;
11729
12602
  }
11730
12603
  }
11731
- async _loadModel() {
11732
- this._unloadModel();
11733
- // Supersede any load already in flight - only the newest load may instantiate
11734
- const generation = ++this._loadGeneration;
11735
- this._detachLoadHandlers();
11736
- // Re-arm readiness so a waiter obtained after an asset change resolves against the new
11737
- // hierarchy. A no-op on first connection, where readiness is still pending.
11738
- this._resetReady();
11739
- const appElement = this.closestApp;
11740
- if (!appElement) {
11741
- // Outside pc-app; connectedCallback already warned. Reached through the asset setter.
11742
- return;
11743
- }
11744
- await appElement.ready();
11745
- // The element may have been removed, or another load started, while we waited
11746
- if (generation !== this._loadGeneration) {
11747
- return;
11748
- }
11749
- const asset = useAsset(this._asset);
11750
- if (!asset) {
11751
- // An empty id is a legitimate transient (the asset may be assigned later); a
11752
- // non-empty one that resolves to nothing is a dead end - say so rather than staying
11753
- // silently pending.
11754
- if (this._asset) {
11755
- console.warn(`pc-model could not find asset '${this._asset}' - model not created`);
11756
- }
11757
- return;
11758
- }
11759
- if (asset.loaded) {
11760
- this._instantiate(asset.resource);
12604
+ /**
12605
+ * Gets the base distance for the first LOD transition.
12606
+ * @returns The LOD base distance.
12607
+ */
12608
+ get lodBaseDistance() {
12609
+ return this._lodBaseDistance;
12610
+ }
12611
+ /**
12612
+ * Sets the multiplier between successive LOD distance thresholds. Each LOD level transitions
12613
+ * at this factor times the previous level's distance, creating a geometric progression. Lower
12614
+ * values keep higher quality at distance; higher values switch to coarser LODs sooner. Clamped
12615
+ * to a minimum of 1.2. Defaults to 3. Only affects assets that contain LOD levels (e.g.
12616
+ * `.lod-meta.json`).
12617
+ * @param value - The LOD multiplier.
12618
+ */
12619
+ set lodMultiplier(value) {
12620
+ this._lodMultiplier = value;
12621
+ if (this.component) {
12622
+ this.component.lodMultiplier = value;
11761
12623
  }
11762
- else {
11763
- // The generation is re-checked even though a superseded handler is detached: the
11764
- // detach relies on how the engine's event emitter treats removal, while the check
11765
- // holds on its own. Whichever of load/error fires first detaches the other.
11766
- this._loadHandle = asset.once('load', () => {
11767
- this._detachLoadHandlers();
11768
- if (generation !== this._loadGeneration) {
11769
- return;
11770
- }
11771
- this._instantiate(asset.resource);
11772
- });
11773
- this._errorHandle = asset.once('error', (err) => {
11774
- this._detachLoadHandlers();
11775
- if (generation !== this._loadGeneration) {
11776
- return;
11777
- }
11778
- // A failed load settles readiness with a null entity, mirroring pc-asset:
11779
- // readiness means the load settled, not that it succeeded.
11780
- this.dispatchEvent(new ErrorEvent('error', {
11781
- message: err instanceof Error ? err.message : String(err)
11782
- }));
11783
- this._onReady();
11784
- });
12624
+ }
12625
+ /**
12626
+ * Gets the multiplier between successive LOD distance thresholds.
12627
+ * @returns The LOD multiplier.
12628
+ */
12629
+ get lodMultiplier() {
12630
+ return this._lodMultiplier;
12631
+ }
12632
+ /**
12633
+ * Sets the minimum allowed LOD index (inclusive). The LOD selected by distance is clamped so it
12634
+ * never goes finer (lower index) than this value. Raising it avoids downloading the highest
12635
+ * quality (largest) LOD files. Defaults to 0. Only affects assets that contain LOD levels (e.g.
12636
+ * `.lod-meta.json`).
12637
+ * @param value - The minimum LOD index.
12638
+ */
12639
+ set lodRangeMin(value) {
12640
+ this._lodRangeMin = value;
12641
+ if (this.component) {
12642
+ this.component.lodRangeMin = value;
11785
12643
  }
11786
12644
  }
11787
- _unloadModel() {
11788
- this._entity?.destroy();
11789
- this._entity = null;
12645
+ /**
12646
+ * Gets the minimum allowed LOD index.
12647
+ * @returns The minimum LOD index.
12648
+ */
12649
+ get lodRangeMin() {
12650
+ return this._lodRangeMin;
11790
12651
  }
11791
12652
  /**
11792
- * Sets the id of the `pc-asset` to use for the model.
11793
- * @param value - The asset ID.
12653
+ * Sets the maximum allowed LOD index (inclusive). The LOD selected by distance is clamped so it
12654
+ * never goes coarser (higher index) than this value. The default of 99 effectively means "no
12655
+ * cap". Defaults to 99. Only affects assets that contain LOD levels (e.g. `.lod-meta.json`).
12656
+ * @param value - The maximum LOD index.
11794
12657
  */
11795
- set asset(value) {
11796
- this._asset = value;
11797
- if (this.isConnected) {
11798
- this._loadModel();
12658
+ set lodRangeMax(value) {
12659
+ this._lodRangeMax = value;
12660
+ if (this.component) {
12661
+ this.component.lodRangeMax = value;
11799
12662
  }
11800
12663
  }
11801
12664
  /**
11802
- * Gets the id of the `pc-asset` to use for the model.
11803
- * @returns The asset ID.
12665
+ * Gets the maximum allowed LOD index.
12666
+ * @returns The maximum LOD index.
11804
12667
  */
11805
- get asset() {
11806
- return this._asset;
12668
+ get lodRangeMax() {
12669
+ return this._lodRangeMax;
11807
12670
  }
11808
12671
  static get observedAttributes() {
11809
- return ['asset'];
12672
+ return [
12673
+ ...super.observedAttributes,
12674
+ 'asset',
12675
+ 'cast-shadows',
12676
+ 'lod-base-distance',
12677
+ 'lod-multiplier',
12678
+ 'lod-range-min',
12679
+ 'lod-range-max'
12680
+ ];
11810
12681
  }
11811
12682
  attributeChangedCallback(name, _oldValue, newValue) {
12683
+ super.attributeChangedCallback(name, _oldValue, newValue);
11812
12684
  switch (name) {
11813
12685
  case 'asset':
11814
12686
  this.asset = newValue ?? '';
11815
12687
  break;
12688
+ case 'cast-shadows':
12689
+ this.castShadows = parseBool(newValue, false);
12690
+ break;
12691
+ case 'lod-base-distance':
12692
+ this.lodBaseDistance = parseNumber(newValue, 5, name);
12693
+ break;
12694
+ case 'lod-multiplier':
12695
+ this.lodMultiplier = parseNumber(newValue, 3, name);
12696
+ break;
12697
+ case 'lod-range-min':
12698
+ this.lodRangeMin = parseNumber(newValue, 0, name);
12699
+ break;
12700
+ case 'lod-range-max':
12701
+ this.lodRangeMax = parseNumber(newValue, 99, name);
12702
+ break;
11816
12703
  }
11817
12704
  }
11818
12705
  }
11819
- customElements.define('pc-model', ModelElement);
12706
+ customElements.define('pc-gsplat', GSplatComponentElement);
11820
12707
 
11821
12708
  /**
11822
12709
  * Parses one mapping into its valid rules, warning for each entry that is not one: an unknown
@@ -13181,6 +14068,8 @@
13181
14068
  }
13182
14069
  customElements.define('pc-sky', SkyElement);
13183
14070
 
14071
+ exports.AnimClipElement = AnimClipElement;
14072
+ exports.AnimComponentElement = AnimComponentElement;
13184
14073
  exports.AppElement = AppElement;
13185
14074
  exports.AssetElement = AssetElement;
13186
14075
  exports.AsyncElement = AsyncElement;