@webxr-jp/mtoon-atlas 0.5.0 → 0.6.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/index.cjs CHANGED
@@ -45,10 +45,13 @@ __export(src_exports, {
45
45
  clearKtx2LoaderCache: () => clearKtx2LoaderCache,
46
46
  createPaddedParameterBuffer: () => createPaddedParameterBuffer,
47
47
  extractParameterBufferFromTexture: () => extractParameterBufferFromTexture,
48
+ extractRgbaData: () => extractRgbaData,
48
49
  getKtx2Renderer: () => getKtx2Renderer,
50
+ getKtx2Source: () => getKtx2Source,
49
51
  getKtx2TranscoderPath: () => getKtx2TranscoderPath,
50
52
  getMToonRenderOrder: () => getMToonRenderOrder,
51
53
  getMaxParameterUBOSlots: () => getMaxParameterUBOSlots,
54
+ isCompressedTexture: () => isCompressedTexture,
52
55
  rememberKtx2Source: () => rememberKtx2Source,
53
56
  resolveKtx2Loader: () => resolveKtx2Loader,
54
57
  resolveParameterBucketSlots: () => resolveParameterBucketSlots,
@@ -756,11 +759,14 @@ var MTOON_ATLAS_EXTENSION_NAME = "XRIFT_mtoon_atlas";
756
759
 
757
760
  // src/extensions/MToonAtlasLoaderPlugin.ts
758
761
  var SRGB_ATLAS_SLOTS = ["baseColor", "shade", "emissive", "matcap", "rim"];
762
+ function resolveAtlasTextureColorSpace(slot) {
763
+ return SRGB_ATLAS_SLOTS.includes(slot) ? import_three2.SRGBColorSpace : import_three2.NoColorSpace;
764
+ }
759
765
  function applyAtlasTextureColorSpace(texture, slot, isKtx2) {
760
766
  if (isKtx2) {
761
767
  return;
762
768
  }
763
- texture.colorSpace = SRGB_ATLAS_SLOTS.includes(slot) ? import_three2.SRGBColorSpace : import_three2.NoColorSpace;
769
+ texture.colorSpace = resolveAtlasTextureColorSpace(slot);
764
770
  }
765
771
  var MToonAtlasLoaderPlugin = class {
766
772
  constructor(parser, options = {}) {
@@ -768,6 +774,13 @@ var MToonAtlasLoaderPlugin = class {
768
774
  // 画像インデックス -> 元 KTX2 バイナリの複製(再エクスポート用、issue #39)
769
775
  // 同じアトラス画像が複数マテリアルから参照されるため、画像単位でメモ化する
770
776
  this.ktx2SourceByImageIndex = /* @__PURE__ */ new Map();
777
+ // WebGPURenderer は THREE.Texture インスタンス単位で GPU リソースを管理するため、
778
+ // マテリアルごとに clone() すると同一アトラステクスチャがマテリアル数倍に増殖する。
779
+ // ロード単位で Promise をキャッシュし、同一条件のテクスチャ/パラメータを全マテリアルで共有する
780
+ this.atlasTextureCache = /* @__PURE__ */ new Map();
781
+ this.ktx2TextureCache = /* @__PURE__ */ new Map();
782
+ this.parameterDataCache = /* @__PURE__ */ new Map();
783
+ this.parameterTextureCache = /* @__PURE__ */ new Map();
771
784
  this.parser = parser;
772
785
  this.injectedKtx2Loader = options.ktx2Loader;
773
786
  this.ktx2TranscoderPath = options.ktx2TranscoderPath;
@@ -905,11 +918,22 @@ var MToonAtlasLoaderPlugin = class {
905
918
  }
906
919
  return { data: floatData, width, height };
907
920
  }
921
+ /**
922
+ * パラメータ画像をキャッシュ付きで16bit精度デコードする(TSL / UBO 版向け)
923
+ */
924
+ _getParameterData16bit(textureIndex) {
925
+ let cached = this.parameterDataCache.get(textureIndex);
926
+ if (!cached) {
927
+ cached = this._loadParameterData16bit(textureIndex);
928
+ this.parameterDataCache.set(textureIndex, cached);
929
+ }
930
+ return cached;
931
+ }
908
932
  /**
909
933
  * パラメータテクスチャを16bit精度で読み込む(GLSL 版向け)
910
934
  */
911
935
  async _loadParameterTexture16bit(textureIndex) {
912
- const { data, width, height } = await this._loadParameterData16bit(textureIndex);
936
+ const { data, width, height } = await this._getParameterData16bit(textureIndex);
913
937
  const texture = new import_three2.DataTexture(data, width, height, import_three2.RGBAFormat, import_three2.FloatType);
914
938
  texture.flipY = false;
915
939
  texture.colorSpace = import_three2.NoColorSpace;
@@ -918,6 +942,17 @@ var MToonAtlasLoaderPlugin = class {
918
942
  texture.needsUpdate = true;
919
943
  return texture;
920
944
  }
945
+ /**
946
+ * パラメータテクスチャをキャッシュ付きで取得する(GLSL 版向け)
947
+ */
948
+ _getParameterTexture16bit(textureIndex) {
949
+ let cached = this.parameterTextureCache.get(textureIndex);
950
+ if (!cached) {
951
+ cached = this._loadParameterTexture16bit(textureIndex);
952
+ this.parameterTextureCache.set(textureIndex, cached);
953
+ }
954
+ return cached;
955
+ }
921
956
  /**
922
957
  * KTX2テクスチャを直接読み込む
923
958
  * GLTFLoaderのloadTextureがKTX2を正しく処理できない場合のフォールバック
@@ -988,51 +1023,78 @@ var MToonAtlasLoaderPlugin = class {
988
1023
  return null;
989
1024
  }
990
1025
  }
991
- async _loadMaterialAsync(materialIndex) {
992
- const materialDef = this.parser.json.materials[materialIndex];
993
- const extension = materialDef.extensions[MTOON_ATLAS_EXTENSION_NAME];
994
- const pending = [];
995
- const atlasedTextures = {};
996
- const loadTexture = async (key, textureInfo) => {
997
- if (textureInfo) {
998
- try {
999
- const textureDef = this.parser.json.textures?.[textureInfo.index];
1000
- const isKtx2 = textureDef?.extensions?.KHR_texture_basisu !== void 0;
1001
- let loadedTexture = null;
1002
- if (isKtx2) {
1003
- loadedTexture = await this._loadKtx2Texture(textureInfo.index);
1004
- } else {
1005
- loadedTexture = await this.parser.loadTexture(textureInfo.index);
1026
+ /**
1027
+ * アトラステクスチャをキャッシュ付きで取得する
1028
+ *
1029
+ * WebGPURenderer は THREE.Texture インスタンスごとに GPU テクスチャを作成・アップロードするため、
1030
+ * 同一 textureIndex に対してマテリアル数分だけ clone() すると GPU メモリとアップロードが増殖する。
1031
+ * そのためロード単位で Promise をメモ化し、全マテリアルで同一インスタンスを共有する。
1032
+ *
1033
+ * - KTX2: DFD 由来の colorSpace をそのまま尊重し、自前生成の CompressedTexture を clone() せず共有する。
1034
+ * - 非 KTX2 (PNG 等): GLTFLoader の内部キャッシュを汚さないよう初回のみ clone() し、
1035
+ * `textureIndex:colorSpace` 単位で共有する(別スロットでの sRGB / NoColorSpace 衝突を防ぐ)。
1036
+ */
1037
+ _getAtlasedTexture(key, textureIndex) {
1038
+ const textureDef = this.parser.json.textures?.[textureIndex];
1039
+ const isKtx2 = textureDef?.extensions?.KHR_texture_basisu !== void 0;
1040
+ if (isKtx2) {
1041
+ let cached2 = this.ktx2TextureCache.get(textureIndex);
1042
+ if (!cached2) {
1043
+ cached2 = this._loadKtx2Texture(textureIndex).then((texture) => {
1044
+ if (!texture) {
1045
+ console.warn(`MToonAtlasLoaderPlugin: \u30C6\u30AF\u30B9\u30C1\u30E3 ${key} (index: ${textureIndex}) \u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F`);
1006
1046
  }
1047
+ return texture;
1048
+ });
1049
+ this.ktx2TextureCache.set(textureIndex, cached2);
1050
+ }
1051
+ return cached2;
1052
+ }
1053
+ const colorSpace = resolveAtlasTextureColorSpace(key);
1054
+ const cacheKey = `${textureIndex}:${colorSpace}`;
1055
+ let cached = this.atlasTextureCache.get(cacheKey);
1056
+ if (!cached) {
1057
+ cached = (async () => {
1058
+ try {
1059
+ const loadedTexture = await this.parser.loadTexture(textureIndex);
1007
1060
  if (!loadedTexture) {
1008
- console.warn(`MToonAtlasLoaderPlugin: \u30C6\u30AF\u30B9\u30C1\u30E3 ${key} (index: ${textureInfo.index}) \u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F`);
1009
- return;
1061
+ console.warn(`MToonAtlasLoaderPlugin: \u30C6\u30AF\u30B9\u30C1\u30E3 ${key} (index: ${textureIndex}) \u306E\u8AAD\u307F\u8FBC\u307F\u306B\u5931\u6557\u3057\u307E\u3057\u305F`);
1062
+ return null;
1010
1063
  }
1011
1064
  const texture = loadedTexture.clone();
1012
1065
  if ("source" in loadedTexture && loadedTexture.source) {
1013
1066
  texture.source = loadedTexture.source;
1014
1067
  }
1015
1068
  texture.flipY = false;
1016
- applyAtlasTextureColorSpace(texture, key, isKtx2);
1017
- atlasedTextures[key] = texture;
1069
+ applyAtlasTextureColorSpace(texture, key, false);
1070
+ return texture;
1018
1071
  } catch (error) {
1019
- console.warn(`MToonAtlasLoaderPlugin: \u30C6\u30AF\u30B9\u30C1\u30E3 ${key} (index: ${textureInfo.index}) \u306E\u8AAD\u307F\u8FBC\u307F\u4E2D\u306B\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F:`, error);
1072
+ console.warn(`MToonAtlasLoaderPlugin: \u30C6\u30AF\u30B9\u30C1\u30E3 ${key} (index: ${textureIndex}) \u306E\u8AAD\u307F\u8FBC\u307F\u4E2D\u306B\u30A8\u30E9\u30FC\u304C\u767A\u751F\u3057\u307E\u3057\u305F:`, error);
1073
+ return null;
1020
1074
  }
1021
- }
1022
- };
1075
+ })();
1076
+ this.atlasTextureCache.set(cacheKey, cached);
1077
+ }
1078
+ return cached;
1079
+ }
1080
+ async _loadMaterialAsync(materialIndex) {
1081
+ const materialDef = this.parser.json.materials[materialIndex];
1082
+ const extension = materialDef.extensions[MTOON_ATLAS_EXTENSION_NAME];
1083
+ const pending = [];
1084
+ const atlasedTextures = {};
1023
1085
  const prefersBuffer = this.materialType.prefersParameterBuffer === true;
1024
1086
  let parameterData = null;
1025
1087
  let parameterTexture = null;
1026
1088
  if (extension.parameterTexture && extension.parameterTexture.index >= 0) {
1027
1089
  if (prefersBuffer) {
1028
1090
  pending.push(
1029
- this._loadParameterData16bit(extension.parameterTexture.index).then(({ data }) => {
1091
+ this._getParameterData16bit(extension.parameterTexture.index).then(({ data }) => {
1030
1092
  parameterData = data;
1031
1093
  })
1032
1094
  );
1033
1095
  } else {
1034
1096
  pending.push(
1035
- this._loadParameterTexture16bit(extension.parameterTexture.index).then((tex) => {
1097
+ this._getParameterTexture16bit(extension.parameterTexture.index).then((tex) => {
1036
1098
  parameterTexture = tex;
1037
1099
  })
1038
1100
  );
@@ -1040,7 +1102,15 @@ var MToonAtlasLoaderPlugin = class {
1040
1102
  }
1041
1103
  if (extension.atlasedTextures) {
1042
1104
  for (const [key, value] of Object.entries(extension.atlasedTextures)) {
1043
- pending.push(loadTexture(key, value));
1105
+ if (value) {
1106
+ pending.push(
1107
+ this._getAtlasedTexture(key, value.index).then((texture) => {
1108
+ if (texture) {
1109
+ atlasedTextures[key] = texture;
1110
+ }
1111
+ })
1112
+ );
1113
+ }
1044
1114
  }
1045
1115
  }
1046
1116
  await Promise.all(pending);
@@ -1116,6 +1186,73 @@ var MToonAtlasLoaderPlugin = class {
1116
1186
  var import_three3 = require("three");
1117
1187
  var import_fast_png2 = require("fast-png");
1118
1188
  var import_texture_compression = require("@webxr-jp/texture-compression");
1189
+
1190
+ // src/extensions/extract-rgba-data.ts
1191
+ async function extractRgbaData(image) {
1192
+ if (image.data && image.width && image.height) {
1193
+ const srcData = image.data;
1194
+ const isFloatData = srcData instanceof Float32Array || srcData.constructor?.name === "Float32Array";
1195
+ const pixelCount = image.width * image.height * 4;
1196
+ if (isFloatData) {
1197
+ const rgbaData = new Uint8Array(pixelCount);
1198
+ for (let i = 0; i < pixelCount; i++) {
1199
+ rgbaData[i] = Math.round(Math.min(1, Math.max(0, srcData[i])) * 255);
1200
+ }
1201
+ return rgbaData;
1202
+ } else {
1203
+ return new Uint8Array(srcData);
1204
+ }
1205
+ }
1206
+ if (image instanceof HTMLCanvasElement) {
1207
+ const ctx = image.getContext("2d");
1208
+ if (ctx) {
1209
+ const imageData = ctx.getImageData(0, 0, image.width, image.height);
1210
+ return new Uint8Array(imageData.data);
1211
+ }
1212
+ }
1213
+ if (typeof OffscreenCanvas !== "undefined" && image instanceof OffscreenCanvas) {
1214
+ const ctx = image.getContext("2d");
1215
+ if (ctx) {
1216
+ const imageData = ctx.getImageData(0, 0, image.width, image.height);
1217
+ return new Uint8Array(imageData.data);
1218
+ }
1219
+ }
1220
+ if (image instanceof HTMLImageElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) {
1221
+ const canvas = document.createElement("canvas");
1222
+ canvas.width = image.width;
1223
+ canvas.height = image.height;
1224
+ const ctx = canvas.getContext("2d");
1225
+ if (ctx) {
1226
+ ctx.drawImage(image, 0, 0);
1227
+ const imageData = ctx.getImageData(0, 0, image.width, image.height);
1228
+ return new Uint8Array(imageData.data);
1229
+ }
1230
+ }
1231
+ if (typeof image.toDataURL === "function") {
1232
+ return new Promise((resolve, reject) => {
1233
+ const dataUrl = image.toDataURL("image/png");
1234
+ const img = new Image();
1235
+ img.onload = () => {
1236
+ const canvas = document.createElement("canvas");
1237
+ canvas.width = img.width;
1238
+ canvas.height = img.height;
1239
+ const ctx = canvas.getContext("2d");
1240
+ if (ctx) {
1241
+ ctx.drawImage(img, 0, 0);
1242
+ const imageData = ctx.getImageData(0, 0, img.width, img.height);
1243
+ resolve(new Uint8Array(imageData.data));
1244
+ } else {
1245
+ reject(new Error("Canvas 2D context\u53D6\u5F97\u306B\u5931\u6557"));
1246
+ }
1247
+ };
1248
+ img.onerror = () => reject(new Error("\u753B\u50CF\u306E\u30ED\u30FC\u30C9\u306B\u5931\u6557"));
1249
+ img.src = dataUrl;
1250
+ });
1251
+ }
1252
+ throw new Error("\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u306A\u3044\u753B\u50CF\u5F62\u5F0F\u3067\u3059");
1253
+ }
1254
+
1255
+ // src/extensions/MToonAtlasExporterPlugin.ts
1119
1256
  var MToonAtlasExporterPlugin = class {
1120
1257
  constructor(writer) {
1121
1258
  this.name = MTOON_ATLAS_EXTENSION_NAME;
@@ -1156,6 +1293,10 @@ var MToonAtlasExporterPlugin = class {
1156
1293
  * テクスチャ圧縮オプションを設定
1157
1294
  * 設定された場合、アトラステクスチャを KTX2 形式で圧縮してエクスポート
1158
1295
  *
1296
+ * @deprecated `optimizeModel(vrm, { textureCompression })` 側での KTX2 圧縮を推奨します。
1297
+ * 最適化時に圧縮・キャッシュされたテクスチャは、このオプションを指定しなくても
1298
+ * そのまま KTX2 バイナリとしてパススルー出力されます。
1299
+ *
1159
1300
  * @param options - 圧縮オプション
1160
1301
  */
1161
1302
  setTextureCompressionOptions(options) {
@@ -1673,60 +1814,7 @@ var MToonAtlasExporterPlugin = class {
1673
1814
  * @returns RGBA形式のUint8Array
1674
1815
  */
1675
1816
  async extractRgbaData(image) {
1676
- if (image.data && image.width && image.height) {
1677
- const srcData = image.data;
1678
- const isFloatData = srcData instanceof Float32Array || srcData.constructor?.name === "Float32Array";
1679
- const pixelCount = image.width * image.height * 4;
1680
- if (isFloatData) {
1681
- const rgbaData = new Uint8Array(pixelCount);
1682
- for (let i = 0; i < pixelCount; i++) {
1683
- rgbaData[i] = Math.round(Math.min(1, Math.max(0, srcData[i])) * 255);
1684
- }
1685
- return rgbaData;
1686
- } else {
1687
- return new Uint8Array(srcData);
1688
- }
1689
- }
1690
- if (image instanceof HTMLCanvasElement) {
1691
- const ctx = image.getContext("2d");
1692
- if (ctx) {
1693
- const imageData = ctx.getImageData(0, 0, image.width, image.height);
1694
- return new Uint8Array(imageData.data);
1695
- }
1696
- }
1697
- if (image instanceof HTMLImageElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) {
1698
- const canvas = document.createElement("canvas");
1699
- canvas.width = image.width;
1700
- canvas.height = image.height;
1701
- const ctx = canvas.getContext("2d");
1702
- if (ctx) {
1703
- ctx.drawImage(image, 0, 0);
1704
- const imageData = ctx.getImageData(0, 0, image.width, image.height);
1705
- return new Uint8Array(imageData.data);
1706
- }
1707
- }
1708
- if (typeof image.toDataURL === "function") {
1709
- return new Promise((resolve, reject) => {
1710
- const dataUrl = image.toDataURL("image/png");
1711
- const img = new Image();
1712
- img.onload = () => {
1713
- const canvas = document.createElement("canvas");
1714
- canvas.width = img.width;
1715
- canvas.height = img.height;
1716
- const ctx = canvas.getContext("2d");
1717
- if (ctx) {
1718
- ctx.drawImage(img, 0, 0);
1719
- const imageData = ctx.getImageData(0, 0, img.width, img.height);
1720
- resolve(new Uint8Array(imageData.data));
1721
- } else {
1722
- reject(new Error("Canvas 2D context\u53D6\u5F97\u306B\u5931\u6557"));
1723
- }
1724
- };
1725
- img.onerror = () => reject(new Error("\u753B\u50CF\u306E\u30ED\u30FC\u30C9\u306B\u5931\u6557"));
1726
- img.src = dataUrl;
1727
- });
1728
- }
1729
- throw new Error("\u30B5\u30DD\u30FC\u30C8\u3055\u308C\u3066\u3044\u306A\u3044\u753B\u50CF\u5F62\u5F0F\u3067\u3059");
1817
+ return extractRgbaData(image);
1730
1818
  }
1731
1819
  /**
1732
1820
  * テクスチャを PNG 形式で処理してBINチャンクに書き込む(従来の処理)
@@ -2111,10 +2199,13 @@ var MToonAtlasExporterPlugin = class {
2111
2199
  clearKtx2LoaderCache,
2112
2200
  createPaddedParameterBuffer,
2113
2201
  extractParameterBufferFromTexture,
2202
+ extractRgbaData,
2114
2203
  getKtx2Renderer,
2204
+ getKtx2Source,
2115
2205
  getKtx2TranscoderPath,
2116
2206
  getMToonRenderOrder,
2117
2207
  getMaxParameterUBOSlots,
2208
+ isCompressedTexture,
2118
2209
  rememberKtx2Source,
2119
2210
  resolveKtx2Loader,
2120
2211
  resolveParameterBucketSlots,