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