支持spine4.3

This commit is contained in:
tianmo committed 2026-09-02 13:53:12 +08:00
1 parent 63e4f61631
commit 0656684a92
206 files changed
+100597 -1320

No files matched your search

+831
View File
@@ -0,0 +1,831 @@
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated April 5, 2025. Replaces all prior versions.
*
* Copyright (c) 2013-2025, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
import { AnimationState, AnimationStateData, AtlasAttachmentLoader, ClippingAttachment, Color, MeshAttachment, Physics, RegionAttachment, Skeleton, SkeletonBinary, SkeletonClipping, SkeletonData, SkeletonJson, SkeletonPhysicsMovement, Skin, Utils, Vector2, } from "@spine-particle/spine-core-4.3";
import { Assets } from "@pixi/assets";
import { Point, Ticker } from "@pixi/core";
import { Bounds, Container } from "@pixi/display";
import { Graphics } from "@pixi/graphics";
import { DarkSlotMesh } from "./DarkSlotMesh.js";
import { SlotMesh } from "./SlotMesh.js";
import "@pixi/events";
;
/** A bounds provider that provides a fixed size given by the user. */
export class AABBRectangleBoundsProvider {
x;
y;
width;
height;
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
calculateBounds() {
return { x: this.x, y: this.y, width: this.width, height: this.height };
}
}
/** A bounds provider that calculates the bounding box from the setup pose. */
export class SetupPoseBoundsProvider {
clipping;
/**
* @param clipping If true, clipping attachments are used to compute the bounds. False, by default.
*/
constructor(clipping = false) {
this.clipping = clipping;
}
calculateBounds(gameObject) {
if (!gameObject.skeleton)
return { x: 0, y: 0, width: 0, height: 0 };
// Make a copy of animation state and skeleton as this might be called while
// the skeleton in the GameObject has already been heavily modified. We can not
// reconstruct that state.
const skeleton = new Skeleton(gameObject.skeleton.data);
skeleton.setupPose();
skeleton.updateWorldTransform(Physics.update);
const bounds = skeleton.getBoundsRect(this.clipping ? new SkeletonClipping() : undefined);
return bounds.width === Number.NEGATIVE_INFINITY
? { x: 0, y: 0, width: 0, height: 0 }
: bounds;
}
}
/** A bounds provider that calculates the bounding box by taking the maximumg bounding box for a combination of skins and specific animation. */
export class SkinsAndAnimationBoundsProvider {
animation;
skins;
timeStep;
clipping;
/**
* @param animation The animation to use for calculating the bounds. If null, the setup pose is used.
* @param skins The skins to use for calculating the bounds. If empty, the default skin is used.
* @param timeStep The time step to use for calculating the bounds. A smaller time step means more precision, but slower calculation.
* @param clipping If true, clipping attachments are used to compute the bounds. False, by default.
*/
constructor(animation, skins = [], timeStep = 0.05, clipping = false) {
this.animation = animation;
this.skins = skins;
this.timeStep = timeStep;
this.clipping = clipping;
}
calculateBounds(gameObject) {
if (!gameObject.skeleton || !gameObject.state)
return { x: 0, y: 0, width: 0, height: 0 };
// Make a copy of animation state and skeleton as this might be called while
// the skeleton in the GameObject has already been heavily modified. We can not
// reconstruct that state.
const animationState = new AnimationState(gameObject.state.data);
const skeleton = new Skeleton(gameObject.skeleton.data);
const clipper = this.clipping ? new SkeletonClipping() : undefined;
const data = skeleton.data;
if (this.skins.length > 0) {
const customSkin = new Skin("custom-skin");
for (const skinName of this.skins) {
const skin = data.findSkin(skinName);
if (skin == null)
continue;
customSkin.addSkin(skin);
}
skeleton.setSkin(customSkin);
}
skeleton.setupPose();
const animation = this.animation != null ? data.findAnimation(this.animation) : null;
if (animation == null) {
skeleton.updateWorldTransform(Physics.update);
const bounds = skeleton.getBoundsRect(clipper);
return bounds.width === Number.NEGATIVE_INFINITY
? { x: 0, y: 0, width: 0, height: 0 }
: bounds;
}
else {
let minX = Number.POSITIVE_INFINITY, minY = Number.POSITIVE_INFINITY, maxX = Number.NEGATIVE_INFINITY, maxY = Number.NEGATIVE_INFINITY;
animationState.clearTracks();
animationState.setAnimation(0, animation, false);
const steps = Math.max(animation.duration / this.timeStep, 1.0);
for (let i = 0; i < steps; i++) {
const delta = i > 0 ? this.timeStep : 0;
animationState.update(delta);
animationState.apply(skeleton);
skeleton.update(delta);
skeleton.updateWorldTransform(Physics.update);
const bounds = skeleton.getBoundsRect(clipper);
minX = Math.min(minX, bounds.x);
minY = Math.min(minY, bounds.y);
maxX = Math.max(maxX, bounds.x + bounds.width);
maxY = Math.max(maxY, bounds.y + bounds.height);
}
const bounds = {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY,
};
return bounds.width === Number.NEGATIVE_INFINITY
? { x: 0, y: 0, width: 0, height: 0 }
: bounds;
}
}
}
/**
* The class to instantiate a {@link Spine} game object in Pixi.
* Create and customize the default configuration using the static method {@link Spine.createOptions},
* then pass it to the constructor.
*/
export class Spine extends Container {
/** The skeleton for this Spine game object. */
skeleton;
/** The animation state for this Spine game object. */
state;
/** Tracks this Pixi container's world movement and applies it to skeleton physics constraints. */
skeletonPhysics;
darkTint = false;
hasNeverUpdated = true;
_debug = undefined;
get debug() {
return this._debug;
}
/** Pass a {@link SpineDebugRenderer} or create your own {@link ISpineDebugRenderer} to render bones, meshes, ...
* @example spineGO.debug = new SpineDebugRenderer();
*/
set debug(value) {
if (this._debug) {
this._debug.unregisterSpine(this);
}
if (value) {
value.registerSpine(this);
}
this._debug = value;
}
slotMeshFactory = () => new SlotMesh();
beforeUpdateWorldTransforms = () => { };
afterUpdateWorldTransforms = () => { };
_autoUpdate = false;
_ticker = Ticker.shared;
get autoUpdate() {
return this._autoUpdate;
}
/** When `true`, the Spine AnimationState and the Skeleton will be automatically updated using the {@link ticker}. */
set autoUpdate(value) {
if (value && !this._autoUpdate) {
this._ticker.add(this.internalUpdate, this);
}
else if (!value && this._autoUpdate) {
this._ticker.remove(this.internalUpdate, this);
}
this._autoUpdate = value;
}
/** The ticker to use when {@link autoUpdate} is `true`. Defaults to {@link Ticker.shared}. */
get ticker() {
return this._ticker;
}
/** Sets the ticker to use when {@link autoUpdate} is `true`. If `autoUpdate` is already `true`, the update callback will be moved from the old ticker to the new one. */
set ticker(value) {
value = value ?? Ticker.shared;
if (this._ticker === value)
return;
if (this._autoUpdate) {
this._ticker.remove(this.internalUpdate, this);
value.add(this.internalUpdate, this);
}
this._ticker = value;
}
meshesCache = new Map();
static vectorAux = new Vector2();
static clipper = new SkeletonClipping();
static QUAD_TRIANGLES = [0, 1, 2, 2, 3, 0];
static VERTEX_SIZE = 2 + 2 + 4;
static DARK_VERTEX_SIZE = 2 + 2 + 4 + 4;
lightColor = new Color();
darkColor = new Color();
clippingVertAux = new Float32Array(6);
_boundsProvider;
/** The bounds provider to use. If undefined the bounds will be dynamic, calculated when requested and based on the current frame. */
get boundsProvider() {
return this._boundsProvider;
}
set boundsProvider(value) {
this._boundsProvider = value;
if (value) {
this._boundsSpineID = -1;
this._boundsSpineDirty = true;
this.interactiveChildren = false;
}
else {
this.interactiveChildren = true;
this.hitArea = null;
}
if (!this.hasNeverUpdated) {
this.calculateBounds();
}
}
_boundsPoint = new Point();
_boundsSpineID = -1;
_boundsSpineDirty = true;
constructor(options) {
super();
if (options instanceof SkeletonData)
options = { skeletonData: options };
else if ("skeleton" in options)
options = new.target.createOptions(options);
const { autoUpdate = true, boundsProvider, darkTint, skeletonData, ticker } = options;
this.skeleton = new Skeleton(skeletonData);
this.skeletonPhysics = new SkeletonPhysicsMovement(this.skeleton, {
readTransform: (out, readRotation) => this.readPhysicsTransform(out, readRotation),
worldToSkeleton: point => this.pixiWorldCoordinatesToSkeleton(point),
});
this.state = new AnimationState(new AnimationStateData(skeletonData));
if (ticker)
this._ticker = ticker;
this.autoUpdate = autoUpdate;
this.boundsProvider = boundsProvider;
// dark tint can be enabled by options, otherwise is enable if at least one slot has tint black
this.darkTint = darkTint === undefined
? this.skeleton.slots.some(slot => !!slot.data.setupPose.darkColor)
: darkTint;
if (this.darkTint)
this.slotMeshFactory = () => new DarkSlotMesh();
}
/** If {@link Spine.autoUpdate} is `false`, this method allows to update the AnimationState and the Skeleton with the given delta. */
update(deltaSeconds) {
this.internalUpdate(0, deltaSeconds);
}
internalUpdate(_deltaFrame, deltaSeconds) {
this.hasNeverUpdated = false;
const delta = deltaSeconds ?? this._ticker.deltaMS / 1000;
this.state.update(delta);
this.state.apply(this.skeleton);
this.skeletonPhysics.applyTransformMovement();
this.beforeUpdateWorldTransforms(this);
this.skeleton.update(delta);
this.skeleton.updateWorldTransform(Physics.update);
this.afterUpdateWorldTransforms(this);
}
readPhysicsTransform(out, readRotation) {
const transform = this.worldTransform;
out.x = transform.tx;
out.y = transform.ty;
out.z = 0;
if (!readRotation)
return;
// Compose local rotation components instead of extracting an angle from worldTransform,
// which is sheared by rotated children of non-uniformly scaled parents.
let rotation = 0;
for (let object = this; object; object = object.parent) {
rotation += object.rotation
+ (object.skew.y - object.skew.x) / 2;
}
out.rotation = rotation * 180 / Math.PI;
}
/** Render the meshes based on the current skeleton state, render debug information, then call {@link Container.updateTransform}. */
updateTransform() {
this.renderMeshes();
this.sortChildren();
this.debug?.renderDebug(this);
super.updateTransform();
}
/** Destroy Spine game object elements, then call the {@link Container.destroy} with the given options */
destroy(options) {
if (this.autoUpdate)
this.autoUpdate = false;
this._ticker = null;
for (const [, mesh] of this.meshesCache) {
mesh?.destroy();
}
this.state.clearListeners();
this.debug = undefined;
this.meshesCache.clear();
this.slotsObject.clear();
for (const maskKey in this.clippingSlotToPixiMasks) {
const mask = this.clippingSlotToPixiMasks[maskKey];
mask.destroy();
delete this.clippingSlotToPixiMasks[maskKey];
}
super.destroy(options);
}
/**
* Unloads this Spine object's cached {@link SkeletonData}.
*
* Existing Spine objects that use this SkeletonData continue to work. Future Spine objects created with the same
* skeleton, atlas, and scale will parse a new SkeletonData.
* @returns `true` if the cached SkeletonData was removed, otherwise `false`.
*/
unloadFromCache() {
const skeletonData = this.skeleton?.data;
if (!skeletonData)
return false;
const cacheKey = Spine.skeletonDataCacheKeys.get(skeletonData);
if (!cacheKey || Spine.skeletonCache[cacheKey] !== skeletonData)
return false;
delete Spine.skeletonCache[cacheKey];
Spine.skeletonDataCacheKeys.delete(skeletonData);
return true;
}
resetMeshes() {
for (const [, mesh] of this.meshesCache) {
mesh.zIndex = -1;
mesh.visible = false;
}
}
_calculateBounds() {
if (this.hasNeverUpdated) {
this.internalUpdate(0, 0);
this.renderMeshes();
}
}
/**
* Check the existence of a mesh for the given slot.
* If you want to manually handle which meshes go on which slot and how you cache, overwrite this method.
*/
hasMeshForSlot(slot) {
return this.meshesCache.has(slot);
}
/**
* Search the mesh corresponding to the given slot or create it, if it does not exists.
* If you want to manually handle which meshes go on which slot and how you cache, overwrite this method.
*/
getMeshForSlot(slot) {
let mesh = this.hasMeshForSlot(slot) ? this.meshesCache.get(slot) : null;
if (!mesh) {
mesh = this.slotMeshFactory();
this.addChild(mesh);
this.meshesCache.set(slot, mesh);
}
else {
mesh.visible = true;
}
return mesh;
}
slotsObject = new Map();
getSlotFromRef(slotRef) {
let slot;
if (typeof slotRef === 'number')
slot = this.skeleton.slots[slotRef];
else if (typeof slotRef === 'string')
slot = this.skeleton.findSlot(slotRef);
else
slot = slotRef;
if (!slot)
throw new Error(`No slot found with the given slot reference: ${slotRef}`);
return slot;
}
/**
* Add a pixi Container as a child of the Spine object.
* The Container will be rendered coherently with the draw order of the slot.
* If an attachment is active on the slot, the pixi Container will be rendered on top of it.
* If the Container is already attached to the given slot, nothing will happen.
* If the Container is already attached to another slot, it will be removed from that slot
* before adding it to the given one.
* If another Container is already attached to this slot, the old one will be removed from this
* slot before adding it to the current one.
* @param slotRef - The slot index, or the slot name, or the Slot where the pixi object will be added to.
* @param pixiObject - The pixi Container to add.
* @param options - Optional settings for the attachment.
* @param options.followAttachmentTimeline - If true, the attachment will follow the slot's attachment timeline.
* @param options.followSlotColor - If true, the container tint will follow the skeleton and slot colors.
*/
addSlotObject(slotRef, pixiObject, options) {
const slot = this.getSlotFromRef(slotRef);
const oldPixiObject = this.slotsObject.get(slot)?.container;
if (oldPixiObject && oldPixiObject === pixiObject)
return;
// search if the pixiObject was already in another slotObject
for (const [otherSlot, { container: oldPixiObjectAnotherSlot }] of this.slotsObject) {
if (otherSlot !== slot && oldPixiObjectAnotherSlot === pixiObject) {
this.removeSlotObject(otherSlot, pixiObject);
break;
}
}
if (oldPixiObject)
this.removeChild(oldPixiObject);
this.slotsObject.set(slot, {
container: pixiObject,
followAttachmentTimeline: options?.followAttachmentTimeline || false,
followSlotColor: options?.followSlotColor || false,
});
this.addChild(pixiObject);
}
/**
* Return the Container connected to the given slot, if any.
* Otherwise return undefined
* @param pixiObject - The slot index, or the slot name, or the Slot to get the Container from.
* @returns a Container if any, undefined otherwise.
*/
getSlotObject(slotRef) {
const element = this.slotsObject.get(this.getSlotFromRef(slotRef));
return element ? element.container : undefined;
}
/**
* Remove a slot object from the given slot.
* If `pixiObject` is passed and attached to the given slot, remove it from the slot.
* If `pixiObject` is not passed and the given slot has an attached Container, remove it from the slot.
* @param slotRef - The slot index, or the slot name, or the Slot where the pixi object will be remove from.
* @param pixiObject - Optional, The pixi Container to remove.
*/
removeSlotObject(slotRef, pixiObject) {
const slot = this.getSlotFromRef(slotRef);
const slotObject = this.slotsObject.get(slot)?.container;
if (!slotObject)
return;
// if pixiObject is passed, remove only if it is equal to the given one
if (pixiObject && pixiObject !== slotObject)
return;
this.removeChild(slotObject);
this.slotsObject.delete(slot);
}
/**
* Removes all PixiJS containers attached to any slot.
*/
removeSlotObjects() {
for (const [, slotObject] of this.slotsObject) {
slotObject.container.removeFromParent();
}
this.slotsObject.clear();
}
verticesCache = Utils.newFloatArray(1024);
clippingSlotToPixiMasks = {};
pixiMaskCleanup(slot) {
const mask = this.clippingSlotToPixiMasks[slot.data.name];
if (mask) {
delete this.clippingSlotToPixiMasks[slot.data.name];
mask.destroy();
}
}
updateSlotObject(element, slot, zIndex) {
const { container: slotObject, followAttachmentTimeline } = element;
const pose = slot.appliedPose;
const followAttachmentValue = followAttachmentTimeline ? Boolean(pose.attachment) : true;
const drawOrder = this.skeleton.drawOrder.appliedPose;
slotObject.visible = drawOrder.includes(slot) && followAttachmentValue;
if (slotObject.visible) {
const applied = slot.bone.appliedPose;
const matrix = slotObject.localTransform;
matrix.a = applied.a;
matrix.b = applied.c;
matrix.c = -applied.b;
matrix.d = -applied.d;
matrix.tx = applied.worldX;
matrix.ty = applied.worldY;
slotObject.transform.setFromMatrix(matrix);
slotObject.zIndex = zIndex + 1;
slotObject.alpha = this.skeleton.color.a * pose.color.a;
if (element.followSlotColor) {
this.setSlotObjectTint(slotObject, ((255 * this.skeleton.color.r * pose.color.r) << 16) |
((255 * this.skeleton.color.g * pose.color.g) << 8) |
(255 * this.skeleton.color.b * pose.color.b));
}
}
}
setSlotObjectTint(slotObject, tint) {
const tintable = slotObject;
if ("tint" in tintable)
tintable.tint = tint;
for (const child of tintable.children ?? []) {
this.setSlotObjectTint(child, tint);
}
}
updateAndSetPixiMask(pixiMaskSource, pixiObject) {
if (Spine.clipper.isClipping() && pixiMaskSource) {
let mask = this.clippingSlotToPixiMasks[pixiMaskSource.slot.data.name];
if (!mask) {
mask = new Graphics();
this.clippingSlotToPixiMasks[pixiMaskSource.slot.data.name] = mask;
this.addChild(mask);
}
if (!pixiMaskSource.computed) {
pixiMaskSource.computed = true;
const clippingAttachment = pixiMaskSource.slot.appliedPose.attachment;
const worldVerticesLength = clippingAttachment.worldVerticesLength;
if (this.clippingVertAux.length < worldVerticesLength)
this.clippingVertAux = new Float32Array(worldVerticesLength);
clippingAttachment.computeWorldVertices(this.skeleton, pixiMaskSource.slot, 0, worldVerticesLength, this.clippingVertAux, 0, 2);
mask.clear().lineStyle(0).beginFill(0x000000);
mask.moveTo(this.clippingVertAux[0], this.clippingVertAux[1]);
for (let i = 2; i < worldVerticesLength; i += 2) {
mask.lineTo(this.clippingVertAux[i], this.clippingVertAux[i + 1]);
}
mask.finishPoly();
}
pixiObject.mask = mask;
}
else if (pixiObject.mask) {
pixiObject.mask = null;
}
}
/*
* Colors in pixi are premultiplied.
* Pixi blending modes are modified to work with premultiplied colors. We cannot create custom blending modes.
* Textures are loaded as premultiplied (see assers/atlasLoader.ts: alphaMode: `page.pma ? ALPHA_MODES.PMA : ALPHA_MODES.UNPACK`):
* - textures non premultiplied are premultiplied on GPU on upload
* - textures premultiplied are uploaded on GPU as is since they are already premultiplied
*
* We need to take this into consideration and calculates final colors for both light and dark color as if textures were always premultiplied.
* This implies for example that alpha for dark tint is always 1. This is way in DarkTintRenderer we have only the alpha of the light color.
* If we ever want to load texture as non premultiplied on GPU, we must add a new dark alpha parameter to the TintMaterial and set the alpha.
*/
renderMeshes() {
this.resetMeshes();
let triangles = null;
let uvs = null;
let pixiMaskSource = null;
const drawOrder = this.skeleton.drawOrder.appliedPose;
const slots = drawOrder;
for (let i = 0, n = drawOrder.length, slotObjectsCounter = 0; i < n; i++) {
const slot = slots[i];
// render pixi object on the current slot on top of the slot attachment
const pixiObject = this.slotsObject.get(slot);
const zIndex = i + slotObjectsCounter;
if (pixiObject) {
this.updateSlotObject(pixiObject, slot, zIndex + 1);
slotObjectsCounter++;
this.updateAndSetPixiMask(pixiMaskSource, pixiObject.container);
}
const pose = slot.appliedPose;
const useDarkColor = !!pose.darkColor;
const vertexSize = useDarkColor ? Spine.DARK_VERTEX_SIZE : Spine.VERTEX_SIZE;
if (!slot.bone.active) {
Spine.clipper.clipEnd(slot);
this.pixiMaskCleanup(slot);
continue;
}
const attachment = pose.attachment;
let attachmentColor;
let texture;
let numFloats = 0;
const skeleton = this.skeleton;
if (attachment instanceof RegionAttachment) {
const region = attachment;
attachmentColor = region.color;
numFloats = vertexSize * 4;
const sequence = attachment.sequence;
const sequenceIndex = sequence.resolveIndex(pose);
attachment.computeWorldVertices(slot, attachment.getOffsets(pose), this.verticesCache, 0, vertexSize);
triangles = Spine.QUAD_TRIANGLES;
uvs = sequence.getUVs(sequenceIndex);
texture = sequence.regions[sequenceIndex]?.texture;
}
else if (attachment instanceof MeshAttachment) {
const mesh = attachment;
attachmentColor = mesh.color;
numFloats = (mesh.worldVerticesLength >> 1) * vertexSize;
if (numFloats > this.verticesCache.length) {
this.verticesCache = Utils.newFloatArray(numFloats);
}
mesh.computeWorldVertices(skeleton, slot, 0, mesh.worldVerticesLength, this.verticesCache, 0, vertexSize);
triangles = mesh.triangles;
const sequence = attachment.sequence;
const sequenceIndex = sequence.resolveIndex(pose);
uvs = sequence.getUVs(sequenceIndex);
texture = sequence.regions[sequenceIndex]?.texture;
}
else if (attachment instanceof ClippingAttachment) {
Spine.clipper.clipStart(skeleton, slot, attachment);
pixiMaskSource = { slot, computed: false };
continue;
}
else {
if (this.hasMeshForSlot(slot)) {
this.getMeshForSlot(slot).visible = false;
}
Spine.clipper.clipEnd(slot);
this.pixiMaskCleanup(slot);
continue;
}
if (texture != null) {
const skeletonColor = skeleton.color;
const slotColor = pose.color;
const alpha = skeletonColor.a * slotColor.a * attachmentColor.a;
this.lightColor.set(skeletonColor.r * slotColor.r * attachmentColor.r, skeletonColor.g * slotColor.g * attachmentColor.g, skeletonColor.b * slotColor.b * attachmentColor.b, alpha);
if (pose.darkColor != null) {
this.darkColor.set(pose.darkColor.r, pose.darkColor.g, pose.darkColor.b, 1);
}
else {
this.darkColor.set(0, 0, 0, 1);
}
let finalVertices;
let finalVerticesLength;
let finalIndices;
let finalIndicesLength;
if (Spine.clipper.isClipping() && Spine.clipper.clipTriangles(this.verticesCache, triangles, triangles.length, uvs, this.lightColor, this.darkColor, useDarkColor, vertexSize)) {
finalVertices = Spine.clipper.clippedVertices;
finalVerticesLength = finalVertices.length;
finalIndices = Spine.clipper.clippedTriangles;
finalIndicesLength = finalIndices.length;
}
else {
const verts = this.verticesCache;
for (let v = 2, u = 0, n = numFloats; v < n; v += vertexSize, u += 2) {
let tempV = v;
verts[tempV++] = this.lightColor.r;
verts[tempV++] = this.lightColor.g;
verts[tempV++] = this.lightColor.b;
verts[tempV++] = this.lightColor.a;
verts[tempV++] = uvs[u];
verts[tempV++] = uvs[u + 1];
if (useDarkColor) {
verts[tempV++] = this.darkColor.r;
verts[tempV++] = this.darkColor.g;
verts[tempV++] = this.darkColor.b;
verts[tempV++] = this.darkColor.a;
}
}
finalVertices = this.verticesCache;
finalVerticesLength = numFloats;
finalIndices = triangles;
finalIndicesLength = triangles.length;
}
if (finalVerticesLength === 0 || finalIndicesLength === 0) {
Spine.clipper.clipEnd(slot);
continue;
}
const mesh = this.getMeshForSlot(slot);
mesh.renderable = true;
mesh.zIndex = zIndex;
mesh.updateFromSpineData(texture, slot.data.blendMode, slot.data.name, finalVertices, finalVerticesLength, finalIndices, finalIndicesLength, useDarkColor);
}
Spine.clipper.clipEnd(slot);
this.pixiMaskCleanup(slot);
}
Spine.clipper.clipEnd();
}
calculateBounds() {
if (!this._boundsProvider) {
super.calculateBounds();
return;
}
const transform = this.transform;
if (this._boundsSpineID === transform._worldID)
return;
this.updateBounds();
const bounds = this._localBounds;
const p = this._boundsPoint;
p.set(bounds.minX, bounds.minY);
transform.worldTransform.apply(p, p);
this._bounds.minX = p.x;
this._bounds.minY = p.y;
p.set(bounds.maxX, bounds.maxY);
transform.worldTransform.apply(p, p);
this._bounds.maxX = p.x;
this._bounds.maxY = p.y;
}
updateBounds() {
if (!this._boundsProvider || !this._boundsSpineDirty)
return;
this._boundsSpineDirty = false;
if (!this._localBounds) {
this._localBounds = new Bounds();
}
const boundsSpine = this._boundsProvider.calculateBounds(this);
const bounds = this._localBounds;
bounds.clear();
bounds.minX = boundsSpine.x;
bounds.minY = boundsSpine.y;
bounds.maxX = boundsSpine.x + boundsSpine.width;
bounds.maxY = boundsSpine.y + boundsSpine.height;
this.hitArea = this._localBounds.getRectangle();
}
/**
* Set the position of the bone given in input through a {@link IPointData}.
* @param bone: the bone name or the bone instance to set the position
* @param outPos: the new position of the bone.
* @throws {Error}: if the given bone is not found in the skeleton, an error is thrown
*/
setBonePosition(bone, position) {
const actualBone = typeof bone === "string" ? this.skeleton.findBone(bone) : bone;
if (!actualBone)
throw Error(`Cannot set bone position, bone ${String(bone)} not found`);
Spine.vectorAux.set(position.x, position.y);
const applied = actualBone.appliedPose;
if (actualBone.parent) {
const aux = actualBone.parent.appliedPose.worldToLocal(Spine.vectorAux);
applied.x = aux.x;
applied.y = aux.y;
}
else {
applied.x = Spine.vectorAux.x;
applied.y = Spine.vectorAux.y;
}
}
/**
* Return the position of the bone given in input into an {@link IPointData}.
* @param bone: the bone name or the bone instance to get the position from
* @param outPos: an optional {@link IPointData} to use to return the bone position, rathern than instantiating a new object.
* @returns {IPointData | undefined}: the position of the bone, or undefined if no matching bone is found in the skeleton
*/
getBonePosition(bone, outPos) {
const actualBone = typeof bone === "string" ? this.skeleton.findBone(bone) : bone;
if (!actualBone) {
console.error(`Cannot get bone position! Bone ${String(bone)} not found`);
return outPos;
}
if (!outPos) {
outPos = { x: 0, y: 0 };
}
outPos.x = actualBone.appliedPose.worldX;
outPos.y = actualBone.appliedPose.worldY;
return outPos;
}
/** Converts a point from the skeleton coordinate system to the Pixi world coordinate system. */
skeletonToPixiWorldCoordinates(point) {
this.worldTransform.apply(point, point);
}
/** Converts a point from the Pixi world coordinate system to the skeleton coordinate system. */
pixiWorldCoordinatesToSkeleton(point) {
this.worldTransform.applyInverse(point, point);
}
/** Converts a point from the Pixi world coordinate system to the bone's local coordinate system. */
pixiWorldCoordinatesToBone(point, bone) {
this.pixiWorldCoordinatesToSkeleton(point);
if (bone.parent) {
bone.parent.appliedPose.worldToLocal(point);
}
else {
bone.appliedPose.worldToLocal(point);
}
}
/** A cache containing skeleton data and atlases already loaded by {@link Spine.from}. */
static skeletonCache = Object.create(null);
static skeletonDataCacheKeys = new WeakMap();
static getSkeletonCacheKey({ skeleton, atlas, scale = 1 }) {
return `${skeleton}-${atlas}-${scale}`;
}
/**
* Get a convenient initialization configuration for your Spine game object.
* Before instantiating a Spine game object, the skeleton (`.skel` or `.json`) and the atlas text files must be loaded into the Assets. For example:
* ```
* PIXI.Assets.add("sackData", "/assets/sack-pro.skel");
* PIXI.Assets.add("sackAtlas", "/assets/sack-pma.atlas");
* await PIXI.Assets.load(["sackData", "sackAtlas"]);
* ```
* Once a Spine game object is created, its skeleton data is cached into {@link Spine.skeletonCache} using the key:
* `${skeletonAssetName}-${atlasAssetName}-${options?.scale ?? 1}`
*
* @param options - Options to configure the Spine game object. See {@link SpineFromOptions}
* @returns {SpineOptions} The configuration ready to be passed to the Spine constructor
*/
static createOptions({ skeleton, atlas, scale = 1, darkTint, autoUpdate = true, boundsProvider, allowMissingRegions, ticker }) {
const cacheKey = Spine.getSkeletonCacheKey({ skeleton, atlas, scale });
let skeletonData = Spine.skeletonCache[cacheKey];
if (!skeletonData) {
// biome-ignore lint/suspicious/noExplicitAny: json skeleton is any
const skeletonAsset = Assets.get(skeleton);
const atlasAsset = Assets.get(atlas);
const attachmentLoader = new AtlasAttachmentLoader(atlasAsset, allowMissingRegions);
const parser = skeletonAsset instanceof Uint8Array ? new SkeletonBinary(attachmentLoader) : new SkeletonJson(attachmentLoader);
parser.scale = scale;
skeletonData = parser.readSkeletonData(skeletonAsset);
Spine.skeletonCache[cacheKey] = skeletonData;
}
Spine.skeletonDataCacheKeys.set(skeletonData, cacheKey);
return { skeletonData, darkTint, autoUpdate, boundsProvider, ticker };
}
/**
* @deprecated Use directly the Spine constructor or {@link createOptions} to make options and customize it to pass to the constructor
* Before instantiating a Spine game object, the skeleton (`.skel` or `.json`) and the atlas text files must be loaded into the Assets. For example:
* ```
* PIXI.Assets.add("sackData", "/assets/sack-pro.skel");
* PIXI.Assets.add("sackAtlas", "/assets/sack-pma.atlas");
* await PIXI.Assets.load(["sackData", "sackAtlas"]);
* ```
* Once a Spine game object is created, its skeleton data is cached into {@link Spine.skeletonCache} using the key:
* `${skeletonAssetName}-${atlasAssetName}-${options?.scale ?? 1}`
*
* @param options - Options to configure the Spine game object. See {@link SpineFromOptions}
* @returns {Spine} The Spine game object instantiated
*/
static from(options) {
return new Spine(Spine.createOptions(options));
}
get tint() {
return this.skeleton.color.toRgb888();
}
set tint(value) {
Color.rgb888ToColor(this.skeleton.color, value);
}
}
Skeleton.yDown = true;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiU3BpbmUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvU3BpbmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OzsrRUEyQitFO0FBRy9FLE9BQU8sRUFDTixjQUFjLEVBQ2Qsa0JBQWtCLEVBQ2xCLHFCQUFxQixFQUNyQixrQkFBa0IsRUFDbEIsS0FBSyxFQUNMLGNBQWMsRUFDZCxPQUFPLEVBQ1AsZ0JBQWdCLEVBQ2hCLFFBQVEsRUFDUixjQUFjLEVBQ2QsZ0JBQWdCLEVBQ2hCLFlBQVksRUFDWixZQUFZLEVBQ1osdUJBQXVCLEVBQ3ZCLElBQUksRUF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