@aether-stack-dev/client-sdk 1.2.5 → 1.3.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/react.js CHANGED
@@ -7,6 +7,14 @@ var jsxRuntime = require('react/jsx-runtime');
7
7
  var THREE = require('three');
8
8
  var GLTFLoader_js = require('three/examples/jsm/loaders/GLTFLoader.js');
9
9
  var threeVrm = require('@pixiv/three-vrm');
10
+ var threeVrmAnimation = require('@pixiv/three-vrm-animation');
11
+ var EffectComposer_js = require('three/examples/jsm/postprocessing/EffectComposer.js');
12
+ var RenderPass_js = require('three/examples/jsm/postprocessing/RenderPass.js');
13
+ var UnrealBloomPass_js = require('three/examples/jsm/postprocessing/UnrealBloomPass.js');
14
+ var SSAOPass_js = require('three/examples/jsm/postprocessing/SSAOPass.js');
15
+ var BokehPass_js = require('three/examples/jsm/postprocessing/BokehPass.js');
16
+ var OutputPass_js = require('three/examples/jsm/postprocessing/OutputPass.js');
17
+ var RGBELoader_js = require('three/examples/jsm/loaders/RGBELoader.js');
10
18
 
11
19
  function _interopNamespaceDefault(e) {
12
20
  var n = Object.create(null);
@@ -49,8 +57,18 @@ const CRITICAL_BLENDSHAPES = [
49
57
  'jawOpen', 'eyeBlinkLeft', 'eyeBlinkRight',
50
58
  ];
51
59
  const DEFAULT_BLENDSHAPE_MAP = Object.fromEntries(ARKIT_BLENDSHAPES.map(name => [name, name]));
52
- ({
53
- ...DEFAULT_BLENDSHAPE_MAP});
60
+ const VROID_BLENDSHAPE_MAP = {
61
+ ...DEFAULT_BLENDSHAPE_MAP,
62
+ jawOpen: 'Fcl_MTH_A',
63
+ mouthFunnel: 'Fcl_MTH_U',
64
+ mouthSmileLeft: 'Fcl_MTH_Fun',
65
+ mouthSmileRight: 'Fcl_MTH_Fun',
66
+ eyeBlinkLeft: 'Fcl_EYE_Close_L',
67
+ eyeBlinkRight: 'Fcl_EYE_Close_R',
68
+ browDownLeft: 'Fcl_BRW_Angry_L',
69
+ browDownRight: 'Fcl_BRW_Angry_R',
70
+ browInnerUp: 'Fcl_BRW_Surprised',
71
+ };
54
72
 
55
73
  const IDX_JAW_OPEN = ARKIT_BLENDSHAPES.indexOf('jawOpen');
56
74
  const IDX_MOUTH_FUNNEL = ARKIT_BLENDSHAPES.indexOf('mouthFunnel');
@@ -818,7 +836,6 @@ function useAStackCSR(options) {
818
836
  };
819
837
  }
820
838
 
821
- const DEFAULT_MAX_MODEL_SIZE = 30 * 1024 * 1024; // 30MB
822
839
  const HIGH_VERTEX_THRESHOLD = 100000;
823
840
  function buildCompatibilityReport(vrm) {
824
841
  const foundNames = new Set();
@@ -855,67 +872,3328 @@ function buildCompatibilityReport(vrm) {
855
872
  const supported = [];
856
873
  const missing = [];
857
874
  for (const name of ARKIT_BLENDSHAPES) {
858
- if (foundNames.has(name) || foundNames.has(name.toLowerCase())) {
875
+ const vroidMapped = VROID_BLENDSHAPE_MAP[name];
876
+ if (foundNames.has(name) || foundNames.has(name.toLowerCase())
877
+ || (vroidMapped && (foundNames.has(vroidMapped) || foundNames.has(vroidMapped.toLowerCase())))) {
859
878
  supported.push(name);
860
879
  }
861
880
  else {
862
- missing.push(name);
863
- }
864
- }
865
- const warnings = [];
866
- for (const name of CRITICAL_BLENDSHAPES) {
867
- if (missing.includes(name)) {
868
- warnings.push(`Missing critical blendshape: ${name}`);
881
+ missing.push(name);
882
+ }
883
+ }
884
+ const warnings = [];
885
+ for (const name of CRITICAL_BLENDSHAPES) {
886
+ if (missing.includes(name)) {
887
+ warnings.push(`Missing critical blendshape: ${name}`);
888
+ }
889
+ }
890
+ if (vertexCount > HIGH_VERTEX_THRESHOLD) {
891
+ warnings.push(`High vertex count (${vertexCount.toLocaleString()}) may impact performance`);
892
+ }
893
+ return {
894
+ supported: supported.length,
895
+ missing,
896
+ warnings,
897
+ modelStats: { vertexCount, textureCount, morphTargetCount },
898
+ };
899
+ }
900
+
901
+ function createPostProcessing(renderer, scene, camera, config, width, height) {
902
+ const composer = new EffectComposer_js.EffectComposer(renderer);
903
+ composer.addPass(new RenderPass_js.RenderPass(scene, camera));
904
+ if (config.bloom !== undefined && config.bloom > 0) {
905
+ composer.addPass(new UnrealBloomPass_js.UnrealBloomPass(new THREE__namespace.Vector2(width, height), config.bloom * 0.8, 0.4, 0.85));
906
+ }
907
+ if (config.ao !== undefined && config.ao > 0) {
908
+ const ssao = new SSAOPass_js.SSAOPass(scene, camera, width, height);
909
+ ssao.kernelRadius = 8 * config.ao;
910
+ ssao.minDistance = 0.005;
911
+ ssao.maxDistance = 0.1;
912
+ composer.addPass(ssao);
913
+ }
914
+ if (config.dof) {
915
+ composer.addPass(new BokehPass_js.BokehPass(scene, camera, { focus: 1.4, aperture: 0.002, maxblur: 0.005 }));
916
+ }
917
+ composer.addPass(new OutputPass_js.OutputPass());
918
+ return {
919
+ composer,
920
+ dispose: () => { composer.renderTarget1.dispose(); composer.renderTarget2.dispose(); },
921
+ setSize: (w, h) => composer.setSize(w, h),
922
+ };
923
+ }
924
+ const FPS_SAMPLE_SIZE = 60;
925
+ const FPS_THRESHOLD = 30;
926
+ class FpsMonitor {
927
+ constructor() {
928
+ this.samples = [];
929
+ this.lastTime = 0;
930
+ this.disabled = false;
931
+ }
932
+ tick(time) {
933
+ if (this.lastTime > 0) {
934
+ const delta = time - this.lastTime;
935
+ if (delta > 0)
936
+ this.samples.push(1000 / delta);
937
+ if (this.samples.length > FPS_SAMPLE_SIZE)
938
+ this.samples.shift();
939
+ }
940
+ this.lastTime = time;
941
+ if (this.samples.length >= FPS_SAMPLE_SIZE) {
942
+ const avg = this.samples.reduce((a, b) => a + b, 0) / this.samples.length;
943
+ if (avg < FPS_THRESHOLD) {
944
+ this.disabled = true;
945
+ console.warn(`[VRM] Post-processing auto-disabled (avg FPS: ${avg.toFixed(0)})`);
946
+ }
947
+ }
948
+ }
949
+ reset() {
950
+ this.samples = [];
951
+ this.lastTime = 0;
952
+ this.disabled = false;
953
+ }
954
+ }
955
+
956
+ /*!
957
+ fflate - fast JavaScript compression/decompression
958
+ <https://101arrowz.github.io/fflate>
959
+ Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
960
+ version 0.8.2
961
+ */
962
+
963
+
964
+ // aliases for shorter compressed code (most minifers don't do this)
965
+ var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;
966
+ // fixed length extra bits
967
+ var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);
968
+ // fixed distance extra bits
969
+ var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);
970
+ // code length index map
971
+ var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
972
+ // get base, reverse index map from extra bits
973
+ var freb = function (eb, start) {
974
+ var b = new u16(31);
975
+ for (var i = 0; i < 31; ++i) {
976
+ b[i] = start += 1 << eb[i - 1];
977
+ }
978
+ // numbers here are at max 18 bits
979
+ var r = new i32(b[30]);
980
+ for (var i = 1; i < 30; ++i) {
981
+ for (var j = b[i]; j < b[i + 1]; ++j) {
982
+ r[j] = ((j - b[i]) << 5) | i;
983
+ }
984
+ }
985
+ return { b: b, r: r };
986
+ };
987
+ var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;
988
+ // we can ignore the fact that the other numbers are wrong; they never happen anyway
989
+ fl[28] = 258, revfl[258] = 28;
990
+ var _b = freb(fdeb, 0), fd = _b.b;
991
+ // map of value to reverse (assuming 16 bits)
992
+ var rev = new u16(32768);
993
+ for (var i = 0; i < 32768; ++i) {
994
+ // reverse table algorithm from SO
995
+ var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1);
996
+ x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2);
997
+ x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4);
998
+ rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1;
999
+ }
1000
+ // create huffman tree from u8 "map": index -> code length for code index
1001
+ // mb (max bits) must be at most 15
1002
+ // TODO: optimize/split up?
1003
+ var hMap = (function (cd, mb, r) {
1004
+ var s = cd.length;
1005
+ // index
1006
+ var i = 0;
1007
+ // u16 "map": index -> # of codes with bit length = index
1008
+ var l = new u16(mb);
1009
+ // length of cd must be 288 (total # of codes)
1010
+ for (; i < s; ++i) {
1011
+ if (cd[i])
1012
+ ++l[cd[i] - 1];
1013
+ }
1014
+ // u16 "map": index -> minimum code for bit length = index
1015
+ var le = new u16(mb);
1016
+ for (i = 1; i < mb; ++i) {
1017
+ le[i] = (le[i - 1] + l[i - 1]) << 1;
1018
+ }
1019
+ var co;
1020
+ if (r) {
1021
+ // u16 "map": index -> number of actual bits, symbol for code
1022
+ co = new u16(1 << mb);
1023
+ // bits to remove for reverser
1024
+ var rvb = 15 - mb;
1025
+ for (i = 0; i < s; ++i) {
1026
+ // ignore 0 lengths
1027
+ if (cd[i]) {
1028
+ // num encoding both symbol and bits read
1029
+ var sv = (i << 4) | cd[i];
1030
+ // free bits
1031
+ var r_1 = mb - cd[i];
1032
+ // start value
1033
+ var v = le[cd[i] - 1]++ << r_1;
1034
+ // m is end value
1035
+ for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
1036
+ // every 16 bit value starting with the code yields the same result
1037
+ co[rev[v] >> rvb] = sv;
1038
+ }
1039
+ }
1040
+ }
1041
+ }
1042
+ else {
1043
+ co = new u16(s);
1044
+ for (i = 0; i < s; ++i) {
1045
+ if (cd[i]) {
1046
+ co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);
1047
+ }
1048
+ }
1049
+ }
1050
+ return co;
1051
+ });
1052
+ // fixed length tree
1053
+ var flt = new u8(288);
1054
+ for (var i = 0; i < 144; ++i)
1055
+ flt[i] = 8;
1056
+ for (var i = 144; i < 256; ++i)
1057
+ flt[i] = 9;
1058
+ for (var i = 256; i < 280; ++i)
1059
+ flt[i] = 7;
1060
+ for (var i = 280; i < 288; ++i)
1061
+ flt[i] = 8;
1062
+ // fixed distance tree
1063
+ var fdt = new u8(32);
1064
+ for (var i = 0; i < 32; ++i)
1065
+ fdt[i] = 5;
1066
+ // fixed length map
1067
+ var flrm = /*#__PURE__*/ hMap(flt, 9, 1);
1068
+ // fixed distance map
1069
+ var fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
1070
+ // find max of array
1071
+ var max = function (a) {
1072
+ var m = a[0];
1073
+ for (var i = 1; i < a.length; ++i) {
1074
+ if (a[i] > m)
1075
+ m = a[i];
1076
+ }
1077
+ return m;
1078
+ };
1079
+ // read d, starting at bit p and mask with m
1080
+ var bits = function (d, p, m) {
1081
+ var o = (p / 8) | 0;
1082
+ return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;
1083
+ };
1084
+ // read d, starting at bit p continuing for at least 16 bits
1085
+ var bits16 = function (d, p) {
1086
+ var o = (p / 8) | 0;
1087
+ return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));
1088
+ };
1089
+ // get end of byte
1090
+ var shft = function (p) { return ((p + 7) / 8) | 0; };
1091
+ // typed array slice - allows garbage collector to free original reference,
1092
+ // while being more compatible than .slice
1093
+ var slc = function (v, s, e) {
1094
+ if (e == null || e > v.length)
1095
+ e = v.length;
1096
+ // can't use .constructor in case user-supplied
1097
+ return new u8(v.subarray(s, e));
1098
+ };
1099
+ // error codes
1100
+ var ec = [
1101
+ 'unexpected EOF',
1102
+ 'invalid block type',
1103
+ 'invalid length/literal',
1104
+ 'invalid distance',
1105
+ 'stream finished',
1106
+ 'no stream handler',
1107
+ ,
1108
+ 'no callback',
1109
+ 'invalid UTF-8 data',
1110
+ 'extra field too long',
1111
+ 'date not in range 1980-2099',
1112
+ 'filename too long',
1113
+ 'stream finishing',
1114
+ 'invalid zip data'
1115
+ // determined by unknown compression method
1116
+ ];
1117
+ var err = function (ind, msg, nt) {
1118
+ var e = new Error(msg || ec[ind]);
1119
+ e.code = ind;
1120
+ if (Error.captureStackTrace)
1121
+ Error.captureStackTrace(e, err);
1122
+ if (!nt)
1123
+ throw e;
1124
+ return e;
1125
+ };
1126
+ // expands raw DEFLATE data
1127
+ var inflt = function (dat, st, buf, dict) {
1128
+ // source length dict length
1129
+ var sl = dat.length, dl = 0;
1130
+ if (!sl || st.f && !st.l)
1131
+ return buf || new u8(0);
1132
+ var noBuf = !buf;
1133
+ // have to estimate size
1134
+ var resize = noBuf || st.i != 2;
1135
+ // no state
1136
+ var noSt = st.i;
1137
+ // Assumes roughly 33% compression ratio average
1138
+ if (noBuf)
1139
+ buf = new u8(sl * 3);
1140
+ // ensure buffer can fit at least l elements
1141
+ var cbuf = function (l) {
1142
+ var bl = buf.length;
1143
+ // need to increase size to fit
1144
+ if (l > bl) {
1145
+ // Double or set to necessary, whichever is greater
1146
+ var nbuf = new u8(Math.max(bl * 2, l));
1147
+ nbuf.set(buf);
1148
+ buf = nbuf;
1149
+ }
1150
+ };
1151
+ // last chunk bitpos bytes
1152
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
1153
+ // total bits
1154
+ var tbts = sl * 8;
1155
+ do {
1156
+ if (!lm) {
1157
+ // BFINAL - this is only 1 when last chunk is next
1158
+ final = bits(dat, pos, 1);
1159
+ // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
1160
+ var type = bits(dat, pos + 1, 3);
1161
+ pos += 3;
1162
+ if (!type) {
1163
+ // go to end of byte boundary
1164
+ var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
1165
+ if (t > sl) {
1166
+ if (noSt)
1167
+ err(0);
1168
+ break;
1169
+ }
1170
+ // ensure size
1171
+ if (resize)
1172
+ cbuf(bt + l);
1173
+ // Copy over uncompressed data
1174
+ buf.set(dat.subarray(s, t), bt);
1175
+ // Get new bitpos, update byte count
1176
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
1177
+ continue;
1178
+ }
1179
+ else if (type == 1)
1180
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
1181
+ else if (type == 2) {
1182
+ // literal lengths
1183
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
1184
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
1185
+ pos += 14;
1186
+ // length+distance tree
1187
+ var ldt = new u8(tl);
1188
+ // code length tree
1189
+ var clt = new u8(19);
1190
+ for (var i = 0; i < hcLen; ++i) {
1191
+ // use index map to get real code
1192
+ clt[clim[i]] = bits(dat, pos + i * 3, 7);
1193
+ }
1194
+ pos += hcLen * 3;
1195
+ // code lengths bits
1196
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
1197
+ // code lengths map
1198
+ var clm = hMap(clt, clb, 1);
1199
+ for (var i = 0; i < tl;) {
1200
+ var r = clm[bits(dat, pos, clbmsk)];
1201
+ // bits read
1202
+ pos += r & 15;
1203
+ // symbol
1204
+ var s = r >> 4;
1205
+ // code length to copy
1206
+ if (s < 16) {
1207
+ ldt[i++] = s;
1208
+ }
1209
+ else {
1210
+ // copy count
1211
+ var c = 0, n = 0;
1212
+ if (s == 16)
1213
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
1214
+ else if (s == 17)
1215
+ n = 3 + bits(dat, pos, 7), pos += 3;
1216
+ else if (s == 18)
1217
+ n = 11 + bits(dat, pos, 127), pos += 7;
1218
+ while (n--)
1219
+ ldt[i++] = c;
1220
+ }
1221
+ }
1222
+ // length tree distance tree
1223
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
1224
+ // max length bits
1225
+ lbt = max(lt);
1226
+ // max dist bits
1227
+ dbt = max(dt);
1228
+ lm = hMap(lt, lbt, 1);
1229
+ dm = hMap(dt, dbt, 1);
1230
+ }
1231
+ else
1232
+ err(1);
1233
+ if (pos > tbts) {
1234
+ if (noSt)
1235
+ err(0);
1236
+ break;
1237
+ }
1238
+ }
1239
+ // Make sure the buffer can hold this + the largest possible addition
1240
+ // Maximum chunk size (practically, theoretically infinite) is 2^17
1241
+ if (resize)
1242
+ cbuf(bt + 131072);
1243
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
1244
+ var lpos = pos;
1245
+ for (;; lpos = pos) {
1246
+ // bits read, code
1247
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
1248
+ pos += c & 15;
1249
+ if (pos > tbts) {
1250
+ if (noSt)
1251
+ err(0);
1252
+ break;
1253
+ }
1254
+ if (!c)
1255
+ err(2);
1256
+ if (sym < 256)
1257
+ buf[bt++] = sym;
1258
+ else if (sym == 256) {
1259
+ lpos = pos, lm = null;
1260
+ break;
1261
+ }
1262
+ else {
1263
+ var add = sym - 254;
1264
+ // no extra bits needed if less
1265
+ if (sym > 264) {
1266
+ // index
1267
+ var i = sym - 257, b = fleb[i];
1268
+ add = bits(dat, pos, (1 << b) - 1) + fl[i];
1269
+ pos += b;
1270
+ }
1271
+ // dist
1272
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
1273
+ if (!d)
1274
+ err(3);
1275
+ pos += d & 15;
1276
+ var dt = fd[dsym];
1277
+ if (dsym > 3) {
1278
+ var b = fdeb[dsym];
1279
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
1280
+ }
1281
+ if (pos > tbts) {
1282
+ if (noSt)
1283
+ err(0);
1284
+ break;
1285
+ }
1286
+ if (resize)
1287
+ cbuf(bt + 131072);
1288
+ var end = bt + add;
1289
+ if (bt < dt) {
1290
+ var shift = dl - dt, dend = Math.min(dt, end);
1291
+ if (shift + bt < 0)
1292
+ err(3);
1293
+ for (; bt < dend; ++bt)
1294
+ buf[bt] = dict[shift + bt];
1295
+ }
1296
+ for (; bt < end; ++bt)
1297
+ buf[bt] = buf[bt - dt];
1298
+ }
1299
+ }
1300
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
1301
+ if (lm)
1302
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
1303
+ } while (!final);
1304
+ // don't reallocate for streams or user buffers
1305
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
1306
+ };
1307
+ // empty
1308
+ var et = /*#__PURE__*/ new u8(0);
1309
+ // zlib start
1310
+ var zls = function (d, dict) {
1311
+ if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
1312
+ err(6, 'invalid zlib data');
1313
+ if ((d[1] >> 5 & 1) == 1)
1314
+ err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');
1315
+ return (d[1] >> 3 & 4) + 2;
1316
+ };
1317
+ /**
1318
+ * Expands Zlib data
1319
+ * @param data The data to decompress
1320
+ * @param opts The decompression options
1321
+ * @returns The decompressed version of the data
1322
+ */
1323
+ function unzlibSync(data, opts) {
1324
+ return inflt(data.subarray(zls(data), -4), { i: 2 }, opts, opts);
1325
+ }
1326
+ // text decoder
1327
+ var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();
1328
+ // text decoder stream
1329
+ var tds = 0;
1330
+ try {
1331
+ td.decode(et, { stream: true });
1332
+ tds = 1;
1333
+ }
1334
+ catch (e) { }
1335
+
1336
+ // Referred to the original Industrial Light & Magic OpenEXR implementation and the TinyEXR / Syoyo Fujita
1337
+ // implementation, so I have preserved their copyright notices.
1338
+
1339
+ // /*
1340
+ // Copyright (c) 2014 - 2017, Syoyo Fujita
1341
+ // All rights reserved.
1342
+
1343
+ // Redistribution and use in source and binary forms, with or without
1344
+ // modification, are permitted provided that the following conditions are met:
1345
+ // * Redistributions of source code must retain the above copyright
1346
+ // notice, this list of conditions and the following disclaimer.
1347
+ // * Redistributions in binary form must reproduce the above copyright
1348
+ // notice, this list of conditions and the following disclaimer in the
1349
+ // documentation and/or other materials provided with the distribution.
1350
+ // * Neither the name of the Syoyo Fujita nor the
1351
+ // names of its contributors may be used to endorse or promote products
1352
+ // derived from this software without specific prior written permission.
1353
+
1354
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1355
+ // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1356
+ // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1357
+ // DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
1358
+ // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
1359
+ // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
1360
+ // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
1361
+ // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1362
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
1363
+ // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1364
+ // */
1365
+
1366
+ // // TinyEXR contains some OpenEXR code, which is licensed under ------------
1367
+
1368
+ // ///////////////////////////////////////////////////////////////////////////
1369
+ // //
1370
+ // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
1371
+ // // Digital Ltd. LLC
1372
+ // //
1373
+ // // All rights reserved.
1374
+ // //
1375
+ // // Redistribution and use in source and binary forms, with or without
1376
+ // // modification, are permitted provided that the following conditions are
1377
+ // // met:
1378
+ // // * Redistributions of source code must retain the above copyright
1379
+ // // notice, this list of conditions and the following disclaimer.
1380
+ // // * Redistributions in binary form must reproduce the above
1381
+ // // copyright notice, this list of conditions and the following disclaimer
1382
+ // // in the documentation and/or other materials provided with the
1383
+ // // distribution.
1384
+ // // * Neither the name of Industrial Light & Magic nor the names of
1385
+ // // its contributors may be used to endorse or promote products derived
1386
+ // // from this software without specific prior written permission.
1387
+ // //
1388
+ // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1389
+ // // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1390
+ // // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1391
+ // // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1392
+ // // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1393
+ // // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1394
+ // // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1395
+ // // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1396
+ // // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1397
+ // // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1398
+ // // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1399
+ // //
1400
+ // ///////////////////////////////////////////////////////////////////////////
1401
+
1402
+ // // End of OpenEXR license -------------------------------------------------
1403
+
1404
+
1405
+ /**
1406
+ * A loader for the OpenEXR texture format.
1407
+ *
1408
+ * `EXRLoader` currently supports uncompressed, ZIP(S), RLE, PIZ and DWA/B compression.
1409
+ * Supports reading as UnsignedByte, HalfFloat and Float type data texture.
1410
+ *
1411
+ * ```js
1412
+ * const loader = new EXRLoader();
1413
+ * const texture = await loader.loadAsync( 'textures/memorial.exr' );
1414
+ * ```
1415
+ *
1416
+ * @augments DataTextureLoader
1417
+ * @three_import import { EXRLoader } from 'three/addons/loaders/EXRLoader.js';
1418
+ */
1419
+ class EXRLoader extends THREE.DataTextureLoader {
1420
+
1421
+ /**
1422
+ * Constructs a new EXR loader.
1423
+ *
1424
+ * @param {LoadingManager} [manager] - The loading manager.
1425
+ */
1426
+ constructor( manager ) {
1427
+
1428
+ super( manager );
1429
+
1430
+ /**
1431
+ * The texture type.
1432
+ *
1433
+ * @type {(HalfFloatType|FloatType)}
1434
+ * @default HalfFloatType
1435
+ */
1436
+ this.type = THREE.HalfFloatType;
1437
+
1438
+ /**
1439
+ * Texture output format.
1440
+ *
1441
+ * @type {(RGBAFormat|RGFormat|RedFormat)}
1442
+ * @default RGBAFormat
1443
+ */
1444
+ this.outputFormat = THREE.RGBAFormat;
1445
+
1446
+ }
1447
+
1448
+ /**
1449
+ * Parses the given EXR texture data.
1450
+ *
1451
+ * @param {ArrayBuffer} buffer - The raw texture data.
1452
+ * @return {DataTextureLoader~TexData} An object representing the parsed texture data.
1453
+ */
1454
+ parse( buffer ) {
1455
+
1456
+ const USHORT_RANGE = ( 1 << 16 );
1457
+ const BITMAP_SIZE = ( USHORT_RANGE >> 3 );
1458
+
1459
+ const HUF_ENCBITS = 16; // literal (value) bit length
1460
+ const HUF_DECBITS = 14; // decoding bit size (>= 8)
1461
+
1462
+ const HUF_ENCSIZE = ( 1 << HUF_ENCBITS ) + 1; // encoding table size
1463
+ const HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
1464
+ const HUF_DECMASK = HUF_DECSIZE - 1;
1465
+
1466
+ const NBITS = 16;
1467
+ const A_OFFSET = 1 << ( NBITS - 1 );
1468
+ const MOD_MASK = ( 1 << NBITS ) - 1;
1469
+
1470
+ const SHORT_ZEROCODE_RUN = 59;
1471
+ const LONG_ZEROCODE_RUN = 63;
1472
+ const SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
1473
+
1474
+ const ULONG_SIZE = 8;
1475
+ const FLOAT32_SIZE = 4;
1476
+ const INT32_SIZE = 4;
1477
+ const INT16_SIZE = 2;
1478
+ const INT8_SIZE = 1;
1479
+
1480
+ const STATIC_HUFFMAN = 0;
1481
+ const DEFLATE = 1;
1482
+
1483
+ const UNKNOWN = 0;
1484
+ const LOSSY_DCT = 1;
1485
+ const RLE = 2;
1486
+
1487
+ const logBase = Math.pow( 2.7182818, 2.2 );
1488
+
1489
+ function reverseLutFromBitmap( bitmap, lut ) {
1490
+
1491
+ let k = 0;
1492
+
1493
+ for ( let i = 0; i < USHORT_RANGE; ++ i ) {
1494
+
1495
+ if ( ( i == 0 ) || ( bitmap[ i >> 3 ] & ( 1 << ( i & 7 ) ) ) ) {
1496
+
1497
+ lut[ k ++ ] = i;
1498
+
1499
+ }
1500
+
1501
+ }
1502
+
1503
+ const n = k - 1;
1504
+
1505
+ while ( k < USHORT_RANGE ) lut[ k ++ ] = 0;
1506
+
1507
+ return n;
1508
+
1509
+ }
1510
+
1511
+ function hufClearDecTable( hdec ) {
1512
+
1513
+ for ( let i = 0; i < HUF_DECSIZE; i ++ ) {
1514
+
1515
+ hdec[ i ] = {};
1516
+ hdec[ i ].len = 0;
1517
+ hdec[ i ].lit = 0;
1518
+ hdec[ i ].p = null;
1519
+
1520
+ }
1521
+
1522
+ }
1523
+
1524
+ const getBitsReturn = { l: 0, c: 0, lc: 0 };
1525
+
1526
+ function getBits( nBits, c, lc, uInt8Array, inOffset ) {
1527
+
1528
+ while ( lc < nBits ) {
1529
+
1530
+ c = ( c << 8 ) | parseUint8Array( uInt8Array, inOffset );
1531
+ lc += 8;
1532
+
1533
+ }
1534
+
1535
+ lc -= nBits;
1536
+
1537
+ getBitsReturn.l = ( c >> lc ) & ( ( 1 << nBits ) - 1 );
1538
+ getBitsReturn.c = c;
1539
+ getBitsReturn.lc = lc;
1540
+
1541
+ }
1542
+
1543
+ const hufTableBuffer = new Array( 59 );
1544
+
1545
+ function hufCanonicalCodeTable( hcode ) {
1546
+
1547
+ for ( let i = 0; i <= 58; ++ i ) hufTableBuffer[ i ] = 0;
1548
+ for ( let i = 0; i < HUF_ENCSIZE; ++ i ) hufTableBuffer[ hcode[ i ] ] += 1;
1549
+
1550
+ let c = 0;
1551
+
1552
+ for ( let i = 58; i > 0; -- i ) {
1553
+
1554
+ const nc = ( ( c + hufTableBuffer[ i ] ) >> 1 );
1555
+ hufTableBuffer[ i ] = c;
1556
+ c = nc;
1557
+
1558
+ }
1559
+
1560
+ for ( let i = 0; i < HUF_ENCSIZE; ++ i ) {
1561
+
1562
+ const l = hcode[ i ];
1563
+ if ( l > 0 ) hcode[ i ] = l | ( hufTableBuffer[ l ] ++ << 6 );
1564
+
1565
+ }
1566
+
1567
+ }
1568
+
1569
+ function hufUnpackEncTable( uInt8Array, inOffset, ni, im, iM, hcode ) {
1570
+
1571
+ const p = inOffset;
1572
+ let c = 0;
1573
+ let lc = 0;
1574
+
1575
+ for ( ; im <= iM; im ++ ) {
1576
+
1577
+ if ( p.value - inOffset.value > ni ) return false;
1578
+
1579
+ getBits( 6, c, lc, uInt8Array, p );
1580
+
1581
+ const l = getBitsReturn.l;
1582
+ c = getBitsReturn.c;
1583
+ lc = getBitsReturn.lc;
1584
+
1585
+ hcode[ im ] = l;
1586
+
1587
+ if ( l == LONG_ZEROCODE_RUN ) {
1588
+
1589
+ if ( p.value - inOffset.value > ni ) {
1590
+
1591
+ throw new Error( 'Something wrong with hufUnpackEncTable' );
1592
+
1593
+ }
1594
+
1595
+ getBits( 8, c, lc, uInt8Array, p );
1596
+
1597
+ let zerun = getBitsReturn.l + SHORTEST_LONG_RUN;
1598
+ c = getBitsReturn.c;
1599
+ lc = getBitsReturn.lc;
1600
+
1601
+ if ( im + zerun > iM + 1 ) {
1602
+
1603
+ throw new Error( 'Something wrong with hufUnpackEncTable' );
1604
+
1605
+ }
1606
+
1607
+ while ( zerun -- ) hcode[ im ++ ] = 0;
1608
+
1609
+ im --;
1610
+
1611
+ } else if ( l >= SHORT_ZEROCODE_RUN ) {
1612
+
1613
+ let zerun = l - SHORT_ZEROCODE_RUN + 2;
1614
+
1615
+ if ( im + zerun > iM + 1 ) {
1616
+
1617
+ throw new Error( 'Something wrong with hufUnpackEncTable' );
1618
+
1619
+ }
1620
+
1621
+ while ( zerun -- ) hcode[ im ++ ] = 0;
1622
+
1623
+ im --;
1624
+
1625
+ }
1626
+
1627
+ }
1628
+
1629
+ hufCanonicalCodeTable( hcode );
1630
+
1631
+ }
1632
+
1633
+ function hufLength( code ) {
1634
+
1635
+ return code & 63;
1636
+
1637
+ }
1638
+
1639
+ function hufCode( code ) {
1640
+
1641
+ return code >> 6;
1642
+
1643
+ }
1644
+
1645
+ function hufBuildDecTable( hcode, im, iM, hdecod ) {
1646
+
1647
+ for ( ; im <= iM; im ++ ) {
1648
+
1649
+ const c = hufCode( hcode[ im ] );
1650
+ const l = hufLength( hcode[ im ] );
1651
+
1652
+ if ( c >> l ) {
1653
+
1654
+ throw new Error( 'Invalid table entry' );
1655
+
1656
+ }
1657
+
1658
+ if ( l > HUF_DECBITS ) {
1659
+
1660
+ const pl = hdecod[ ( c >> ( l - HUF_DECBITS ) ) ];
1661
+
1662
+ if ( pl.len ) {
1663
+
1664
+ throw new Error( 'Invalid table entry' );
1665
+
1666
+ }
1667
+
1668
+ pl.lit ++;
1669
+
1670
+ if ( pl.p ) {
1671
+
1672
+ const p = pl.p;
1673
+ pl.p = new Array( pl.lit );
1674
+
1675
+ for ( let i = 0; i < pl.lit - 1; ++ i ) {
1676
+
1677
+ pl.p[ i ] = p[ i ];
1678
+
1679
+ }
1680
+
1681
+ } else {
1682
+
1683
+ pl.p = new Array( 1 );
1684
+
1685
+ }
1686
+
1687
+ pl.p[ pl.lit - 1 ] = im;
1688
+
1689
+ } else if ( l ) {
1690
+
1691
+ let plOffset = 0;
1692
+
1693
+ for ( let i = 1 << ( HUF_DECBITS - l ); i > 0; i -- ) {
1694
+
1695
+ const pl = hdecod[ ( c << ( HUF_DECBITS - l ) ) + plOffset ];
1696
+
1697
+ if ( pl.len || pl.p ) {
1698
+
1699
+ throw new Error( 'Invalid table entry' );
1700
+
1701
+ }
1702
+
1703
+ pl.len = l;
1704
+ pl.lit = im;
1705
+
1706
+ plOffset ++;
1707
+
1708
+ }
1709
+
1710
+ }
1711
+
1712
+ }
1713
+
1714
+ return true;
1715
+
1716
+ }
1717
+
1718
+ const getCharReturn = { c: 0, lc: 0 };
1719
+
1720
+ function getChar( c, lc, uInt8Array, inOffset ) {
1721
+
1722
+ c = ( c << 8 ) | parseUint8Array( uInt8Array, inOffset );
1723
+ lc += 8;
1724
+
1725
+ getCharReturn.c = c;
1726
+ getCharReturn.lc = lc;
1727
+
1728
+ }
1729
+
1730
+ const getCodeReturn = { c: 0, lc: 0 };
1731
+
1732
+ function getCode( po, rlc, c, lc, uInt8Array, inOffset, outBuffer, outBufferOffset, outBufferEndOffset ) {
1733
+
1734
+ if ( po == rlc ) {
1735
+
1736
+ if ( lc < 8 ) {
1737
+
1738
+ getChar( c, lc, uInt8Array, inOffset );
1739
+ c = getCharReturn.c;
1740
+ lc = getCharReturn.lc;
1741
+
1742
+ }
1743
+
1744
+ lc -= 8;
1745
+
1746
+ let cs = ( c >> lc );
1747
+ cs = new Uint8Array( [ cs ] )[ 0 ];
1748
+
1749
+ if ( outBufferOffset.value + cs > outBufferEndOffset ) {
1750
+
1751
+ return false;
1752
+
1753
+ }
1754
+
1755
+ const s = outBuffer[ outBufferOffset.value - 1 ];
1756
+
1757
+ while ( cs -- > 0 ) {
1758
+
1759
+ outBuffer[ outBufferOffset.value ++ ] = s;
1760
+
1761
+ }
1762
+
1763
+ } else if ( outBufferOffset.value < outBufferEndOffset ) {
1764
+
1765
+ outBuffer[ outBufferOffset.value ++ ] = po;
1766
+
1767
+ } else {
1768
+
1769
+ return false;
1770
+
1771
+ }
1772
+
1773
+ getCodeReturn.c = c;
1774
+ getCodeReturn.lc = lc;
1775
+
1776
+ }
1777
+
1778
+ function UInt16( value ) {
1779
+
1780
+ return ( value & 0xFFFF );
1781
+
1782
+ }
1783
+
1784
+ function Int16( value ) {
1785
+
1786
+ const ref = UInt16( value );
1787
+ return ( ref > 0x7FFF ) ? ref - 0x10000 : ref;
1788
+
1789
+ }
1790
+
1791
+ const wdec14Return = { a: 0, b: 0 };
1792
+
1793
+ function wdec14( l, h ) {
1794
+
1795
+ const ls = Int16( l );
1796
+ const hs = Int16( h );
1797
+
1798
+ const hi = hs;
1799
+ const ai = ls + ( hi & 1 ) + ( hi >> 1 );
1800
+
1801
+ const as = ai;
1802
+ const bs = ai - hi;
1803
+
1804
+ wdec14Return.a = as;
1805
+ wdec14Return.b = bs;
1806
+
1807
+ }
1808
+
1809
+ function wdec16( l, h ) {
1810
+
1811
+ const m = UInt16( l );
1812
+ const d = UInt16( h );
1813
+
1814
+ const bb = ( m - ( d >> 1 ) ) & MOD_MASK;
1815
+ const aa = ( d + bb - A_OFFSET ) & MOD_MASK;
1816
+
1817
+ wdec14Return.a = aa;
1818
+ wdec14Return.b = bb;
1819
+
1820
+ }
1821
+
1822
+ function wav2Decode( buffer, j, nx, ox, ny, oy, mx ) {
1823
+
1824
+ const w14 = mx < ( 1 << 14 );
1825
+ const n = ( nx > ny ) ? ny : nx;
1826
+ let p = 1;
1827
+ let p2;
1828
+ let py;
1829
+
1830
+ while ( p <= n ) p <<= 1;
1831
+
1832
+ p >>= 1;
1833
+ p2 = p;
1834
+ p >>= 1;
1835
+
1836
+ while ( p >= 1 ) {
1837
+
1838
+ py = 0;
1839
+ const ey = py + oy * ( ny - p2 );
1840
+ const oy1 = oy * p;
1841
+ const oy2 = oy * p2;
1842
+ const ox1 = ox * p;
1843
+ const ox2 = ox * p2;
1844
+ let i00, i01, i10, i11;
1845
+
1846
+ for ( ; py <= ey; py += oy2 ) {
1847
+
1848
+ let px = py;
1849
+ const ex = py + ox * ( nx - p2 );
1850
+
1851
+ for ( ; px <= ex; px += ox2 ) {
1852
+
1853
+ const p01 = px + ox1;
1854
+ const p10 = px + oy1;
1855
+ const p11 = p10 + ox1;
1856
+
1857
+ if ( w14 ) {
1858
+
1859
+ wdec14( buffer[ px + j ], buffer[ p10 + j ] );
1860
+
1861
+ i00 = wdec14Return.a;
1862
+ i10 = wdec14Return.b;
1863
+
1864
+ wdec14( buffer[ p01 + j ], buffer[ p11 + j ] );
1865
+
1866
+ i01 = wdec14Return.a;
1867
+ i11 = wdec14Return.b;
1868
+
1869
+ wdec14( i00, i01 );
1870
+
1871
+ buffer[ px + j ] = wdec14Return.a;
1872
+ buffer[ p01 + j ] = wdec14Return.b;
1873
+
1874
+ wdec14( i10, i11 );
1875
+
1876
+ buffer[ p10 + j ] = wdec14Return.a;
1877
+ buffer[ p11 + j ] = wdec14Return.b;
1878
+
1879
+ } else {
1880
+
1881
+ wdec16( buffer[ px + j ], buffer[ p10 + j ] );
1882
+
1883
+ i00 = wdec14Return.a;
1884
+ i10 = wdec14Return.b;
1885
+
1886
+ wdec16( buffer[ p01 + j ], buffer[ p11 + j ] );
1887
+
1888
+ i01 = wdec14Return.a;
1889
+ i11 = wdec14Return.b;
1890
+
1891
+ wdec16( i00, i01 );
1892
+
1893
+ buffer[ px + j ] = wdec14Return.a;
1894
+ buffer[ p01 + j ] = wdec14Return.b;
1895
+
1896
+ wdec16( i10, i11 );
1897
+
1898
+ buffer[ p10 + j ] = wdec14Return.a;
1899
+ buffer[ p11 + j ] = wdec14Return.b;
1900
+
1901
+
1902
+ }
1903
+
1904
+ }
1905
+
1906
+ if ( nx & p ) {
1907
+
1908
+ const p10 = px + oy1;
1909
+
1910
+ if ( w14 )
1911
+ wdec14( buffer[ px + j ], buffer[ p10 + j ] );
1912
+ else
1913
+ wdec16( buffer[ px + j ], buffer[ p10 + j ] );
1914
+
1915
+ i00 = wdec14Return.a;
1916
+ buffer[ p10 + j ] = wdec14Return.b;
1917
+
1918
+ buffer[ px + j ] = i00;
1919
+
1920
+ }
1921
+
1922
+ }
1923
+
1924
+ if ( ny & p ) {
1925
+
1926
+ let px = py;
1927
+ const ex = py + ox * ( nx - p2 );
1928
+
1929
+ for ( ; px <= ex; px += ox2 ) {
1930
+
1931
+ const p01 = px + ox1;
1932
+
1933
+ if ( w14 )
1934
+ wdec14( buffer[ px + j ], buffer[ p01 + j ] );
1935
+ else
1936
+ wdec16( buffer[ px + j ], buffer[ p01 + j ] );
1937
+
1938
+ i00 = wdec14Return.a;
1939
+ buffer[ p01 + j ] = wdec14Return.b;
1940
+
1941
+ buffer[ px + j ] = i00;
1942
+
1943
+ }
1944
+
1945
+ }
1946
+
1947
+ p2 = p;
1948
+ p >>= 1;
1949
+
1950
+ }
1951
+
1952
+ return py;
1953
+
1954
+ }
1955
+
1956
+ function hufDecode( encodingTable, decodingTable, uInt8Array, inOffset, ni, rlc, no, outBuffer, outOffset ) {
1957
+
1958
+ let c = 0;
1959
+ let lc = 0;
1960
+ const outBufferEndOffset = no;
1961
+ const inOffsetEnd = Math.trunc( inOffset.value + ( ni + 7 ) / 8 );
1962
+
1963
+ while ( inOffset.value < inOffsetEnd ) {
1964
+
1965
+ getChar( c, lc, uInt8Array, inOffset );
1966
+
1967
+ c = getCharReturn.c;
1968
+ lc = getCharReturn.lc;
1969
+
1970
+ while ( lc >= HUF_DECBITS ) {
1971
+
1972
+ const index = ( c >> ( lc - HUF_DECBITS ) ) & HUF_DECMASK;
1973
+ const pl = decodingTable[ index ];
1974
+
1975
+ if ( pl.len ) {
1976
+
1977
+ lc -= pl.len;
1978
+
1979
+ getCode( pl.lit, rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset );
1980
+
1981
+ c = getCodeReturn.c;
1982
+ lc = getCodeReturn.lc;
1983
+
1984
+ } else {
1985
+
1986
+ if ( ! pl.p ) {
1987
+
1988
+ throw new Error( 'hufDecode issues' );
1989
+
1990
+ }
1991
+
1992
+ let j;
1993
+
1994
+ for ( j = 0; j < pl.lit; j ++ ) {
1995
+
1996
+ const l = hufLength( encodingTable[ pl.p[ j ] ] );
1997
+
1998
+ while ( lc < l && inOffset.value < inOffsetEnd ) {
1999
+
2000
+ getChar( c, lc, uInt8Array, inOffset );
2001
+
2002
+ c = getCharReturn.c;
2003
+ lc = getCharReturn.lc;
2004
+
2005
+ }
2006
+
2007
+ if ( lc >= l ) {
2008
+
2009
+ if ( hufCode( encodingTable[ pl.p[ j ] ] ) == ( ( c >> ( lc - l ) ) & ( ( 1 << l ) - 1 ) ) ) {
2010
+
2011
+ lc -= l;
2012
+
2013
+ getCode( pl.p[ j ], rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset );
2014
+
2015
+ c = getCodeReturn.c;
2016
+ lc = getCodeReturn.lc;
2017
+
2018
+ break;
2019
+
2020
+ }
2021
+
2022
+ }
2023
+
2024
+ }
2025
+
2026
+ if ( j == pl.lit ) {
2027
+
2028
+ throw new Error( 'hufDecode issues' );
2029
+
2030
+ }
2031
+
2032
+ }
2033
+
2034
+ }
2035
+
2036
+ }
2037
+
2038
+ const i = ( 8 - ni ) & 7;
2039
+
2040
+ c >>= i;
2041
+ lc -= i;
2042
+
2043
+ while ( lc > 0 ) {
2044
+
2045
+ const pl = decodingTable[ ( c << ( HUF_DECBITS - lc ) ) & HUF_DECMASK ];
2046
+
2047
+ if ( pl.len ) {
2048
+
2049
+ lc -= pl.len;
2050
+
2051
+ getCode( pl.lit, rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset );
2052
+
2053
+ c = getCodeReturn.c;
2054
+ lc = getCodeReturn.lc;
2055
+
2056
+ } else {
2057
+
2058
+ throw new Error( 'hufDecode issues' );
2059
+
2060
+ }
2061
+
2062
+ }
2063
+
2064
+ return true;
2065
+
2066
+ }
2067
+
2068
+ function hufUncompress( uInt8Array, inDataView, inOffset, nCompressed, outBuffer, nRaw ) {
2069
+
2070
+ const outOffset = { value: 0 };
2071
+ const initialInOffset = inOffset.value;
2072
+
2073
+ const im = parseUint32( inDataView, inOffset );
2074
+ const iM = parseUint32( inDataView, inOffset );
2075
+
2076
+ inOffset.value += 4;
2077
+
2078
+ const nBits = parseUint32( inDataView, inOffset );
2079
+
2080
+ inOffset.value += 4;
2081
+
2082
+ if ( im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE ) {
2083
+
2084
+ throw new Error( 'Something wrong with HUF_ENCSIZE' );
2085
+
2086
+ }
2087
+
2088
+ const freq = new Array( HUF_ENCSIZE );
2089
+ const hdec = new Array( HUF_DECSIZE );
2090
+
2091
+ hufClearDecTable( hdec );
2092
+
2093
+ const ni = nCompressed - ( inOffset.value - initialInOffset );
2094
+
2095
+ hufUnpackEncTable( uInt8Array, inOffset, ni, im, iM, freq );
2096
+
2097
+ if ( nBits > 8 * ( nCompressed - ( inOffset.value - initialInOffset ) ) ) {
2098
+
2099
+ throw new Error( 'Something wrong with hufUncompress' );
2100
+
2101
+ }
2102
+
2103
+ hufBuildDecTable( freq, im, iM, hdec );
2104
+
2105
+ hufDecode( freq, hdec, uInt8Array, inOffset, nBits, iM, nRaw, outBuffer, outOffset );
2106
+
2107
+ }
2108
+
2109
+ function applyLut( lut, data, nData ) {
2110
+
2111
+ for ( let i = 0; i < nData; ++ i ) {
2112
+
2113
+ data[ i ] = lut[ data[ i ] ];
2114
+
2115
+ }
2116
+
2117
+ }
2118
+
2119
+ function predictor( source ) {
2120
+
2121
+ for ( let t = 1; t < source.length; t ++ ) {
2122
+
2123
+ const d = source[ t - 1 ] + source[ t ] - 128;
2124
+ source[ t ] = d;
2125
+
2126
+ }
2127
+
2128
+ }
2129
+
2130
+ function interleaveScalar( source, out ) {
2131
+
2132
+ let t1 = 0;
2133
+ let t2 = Math.floor( ( source.length + 1 ) / 2 );
2134
+ let s = 0;
2135
+ const stop = source.length - 1;
2136
+
2137
+ while ( true ) {
2138
+
2139
+ if ( s > stop ) break;
2140
+ out[ s ++ ] = source[ t1 ++ ];
2141
+
2142
+ if ( s > stop ) break;
2143
+ out[ s ++ ] = source[ t2 ++ ];
2144
+
2145
+ }
2146
+
2147
+ }
2148
+
2149
+ function decodeRunLength( source ) {
2150
+
2151
+ let size = source.byteLength;
2152
+ const out = new Array();
2153
+ let p = 0;
2154
+
2155
+ const reader = new DataView( source );
2156
+
2157
+ while ( size > 0 ) {
2158
+
2159
+ const l = reader.getInt8( p ++ );
2160
+
2161
+ if ( l < 0 ) {
2162
+
2163
+ const count = - l;
2164
+ size -= count + 1;
2165
+
2166
+ for ( let i = 0; i < count; i ++ ) {
2167
+
2168
+ out.push( reader.getUint8( p ++ ) );
2169
+
2170
+ }
2171
+
2172
+
2173
+ } else {
2174
+
2175
+ const count = l;
2176
+ size -= 2;
2177
+
2178
+ const value = reader.getUint8( p ++ );
2179
+
2180
+ for ( let i = 0; i < count + 1; i ++ ) {
2181
+
2182
+ out.push( value );
2183
+
2184
+ }
2185
+
2186
+ }
2187
+
2188
+ }
2189
+
2190
+ return out;
2191
+
2192
+ }
2193
+
2194
+ function lossyDctDecode( cscSet, rowPtrs, channelData, acBuffer, dcBuffer, outBuffer ) {
2195
+
2196
+ let dataView = new DataView( outBuffer.buffer );
2197
+
2198
+ const width = channelData[ cscSet.idx[ 0 ] ].width;
2199
+ const height = channelData[ cscSet.idx[ 0 ] ].height;
2200
+
2201
+ const numComp = 3;
2202
+
2203
+ const numFullBlocksX = Math.floor( width / 8.0 );
2204
+ const numBlocksX = Math.ceil( width / 8.0 );
2205
+ const numBlocksY = Math.ceil( height / 8.0 );
2206
+ const leftoverX = width - ( numBlocksX - 1 ) * 8;
2207
+ const leftoverY = height - ( numBlocksY - 1 ) * 8;
2208
+
2209
+ const currAcComp = { value: 0 };
2210
+ const currDcComp = new Array( numComp );
2211
+ const dctData = new Array( numComp );
2212
+ const halfZigBlock = new Array( numComp );
2213
+ const rowBlock = new Array( numComp );
2214
+ const rowOffsets = new Array( numComp );
2215
+
2216
+ for ( let comp = 0; comp < numComp; ++ comp ) {
2217
+
2218
+ rowOffsets[ comp ] = rowPtrs[ cscSet.idx[ comp ] ];
2219
+ currDcComp[ comp ] = ( comp < 1 ) ? 0 : currDcComp[ comp - 1 ] + numBlocksX * numBlocksY;
2220
+ dctData[ comp ] = new Float32Array( 64 );
2221
+ halfZigBlock[ comp ] = new Uint16Array( 64 );
2222
+ rowBlock[ comp ] = new Uint16Array( numBlocksX * 64 );
2223
+
2224
+ }
2225
+
2226
+ for ( let blocky = 0; blocky < numBlocksY; ++ blocky ) {
2227
+
2228
+ let maxY = 8;
2229
+
2230
+ if ( blocky == numBlocksY - 1 )
2231
+ maxY = leftoverY;
2232
+
2233
+ let maxX = 8;
2234
+
2235
+ for ( let blockx = 0; blockx < numBlocksX; ++ blockx ) {
2236
+
2237
+ if ( blockx == numBlocksX - 1 )
2238
+ maxX = leftoverX;
2239
+
2240
+ for ( let comp = 0; comp < numComp; ++ comp ) {
2241
+
2242
+ halfZigBlock[ comp ].fill( 0 );
2243
+
2244
+ // set block DC component
2245
+ halfZigBlock[ comp ][ 0 ] = dcBuffer[ currDcComp[ comp ] ++ ];
2246
+ // set block AC components
2247
+ unRleAC( currAcComp, acBuffer, halfZigBlock[ comp ] );
2248
+
2249
+ // UnZigZag block to float
2250
+ unZigZag( halfZigBlock[ comp ], dctData[ comp ] );
2251
+ // decode float dct
2252
+ dctInverse( dctData[ comp ] );
2253
+
2254
+ }
2255
+
2256
+ {
2257
+
2258
+ csc709Inverse( dctData );
2259
+
2260
+ }
2261
+
2262
+ for ( let comp = 0; comp < numComp; ++ comp ) {
2263
+
2264
+ convertToHalf( dctData[ comp ], rowBlock[ comp ], blockx * 64 );
2265
+
2266
+ }
2267
+
2268
+ } // blockx
2269
+
2270
+ let offset = 0;
2271
+
2272
+ for ( let comp = 0; comp < numComp; ++ comp ) {
2273
+
2274
+ const type = channelData[ cscSet.idx[ comp ] ].type;
2275
+
2276
+ for ( let y = 8 * blocky; y < 8 * blocky + maxY; ++ y ) {
2277
+
2278
+ offset = rowOffsets[ comp ][ y ];
2279
+
2280
+ for ( let blockx = 0; blockx < numFullBlocksX; ++ blockx ) {
2281
+
2282
+ const src = blockx * 64 + ( ( y & 0x7 ) * 8 );
2283
+
2284
+ dataView.setUint16( offset + 0 * INT16_SIZE * type, rowBlock[ comp ][ src + 0 ], true );
2285
+ dataView.setUint16( offset + 1 * INT16_SIZE * type, rowBlock[ comp ][ src + 1 ], true );
2286
+ dataView.setUint16( offset + 2 * INT16_SIZE * type, rowBlock[ comp ][ src + 2 ], true );
2287
+ dataView.setUint16( offset + 3 * INT16_SIZE * type, rowBlock[ comp ][ src + 3 ], true );
2288
+
2289
+ dataView.setUint16( offset + 4 * INT16_SIZE * type, rowBlock[ comp ][ src + 4 ], true );
2290
+ dataView.setUint16( offset + 5 * INT16_SIZE * type, rowBlock[ comp ][ src + 5 ], true );
2291
+ dataView.setUint16( offset + 6 * INT16_SIZE * type, rowBlock[ comp ][ src + 6 ], true );
2292
+ dataView.setUint16( offset + 7 * INT16_SIZE * type, rowBlock[ comp ][ src + 7 ], true );
2293
+
2294
+ offset += 8 * INT16_SIZE * type;
2295
+
2296
+ }
2297
+
2298
+ }
2299
+
2300
+ // handle partial X blocks
2301
+ if ( numFullBlocksX != numBlocksX ) {
2302
+
2303
+ for ( let y = 8 * blocky; y < 8 * blocky + maxY; ++ y ) {
2304
+
2305
+ const offset = rowOffsets[ comp ][ y ] + 8 * numFullBlocksX * INT16_SIZE * type;
2306
+ const src = numFullBlocksX * 64 + ( ( y & 0x7 ) * 8 );
2307
+
2308
+ for ( let x = 0; x < maxX; ++ x ) {
2309
+
2310
+ dataView.setUint16( offset + x * INT16_SIZE * type, rowBlock[ comp ][ src + x ], true );
2311
+
2312
+ }
2313
+
2314
+ }
2315
+
2316
+ }
2317
+
2318
+ } // comp
2319
+
2320
+ } // blocky
2321
+
2322
+ const halfRow = new Uint16Array( width );
2323
+ dataView = new DataView( outBuffer.buffer );
2324
+
2325
+ // convert channels back to float, if needed
2326
+ for ( let comp = 0; comp < numComp; ++ comp ) {
2327
+
2328
+ channelData[ cscSet.idx[ comp ] ].decoded = true;
2329
+ const type = channelData[ cscSet.idx[ comp ] ].type;
2330
+
2331
+ if ( channelData[ comp ].type != 2 ) continue;
2332
+
2333
+ for ( let y = 0; y < height; ++ y ) {
2334
+
2335
+ const offset = rowOffsets[ comp ][ y ];
2336
+
2337
+ for ( let x = 0; x < width; ++ x ) {
2338
+
2339
+ halfRow[ x ] = dataView.getUint16( offset + x * INT16_SIZE * type, true );
2340
+
2341
+ }
2342
+
2343
+ for ( let x = 0; x < width; ++ x ) {
2344
+
2345
+ dataView.setFloat32( offset + x * INT16_SIZE * type, decodeFloat16( halfRow[ x ] ), true );
2346
+
2347
+ }
2348
+
2349
+ }
2350
+
2351
+ }
2352
+
2353
+ }
2354
+
2355
+ function lossyDctChannelDecode( channelIndex, rowPtrs, channelData, acBuffer, dcBuffer, outBuffer ) {
2356
+
2357
+ const dataView = new DataView( outBuffer.buffer );
2358
+ const cd = channelData[ channelIndex ];
2359
+ const width = cd.width;
2360
+ const height = cd.height;
2361
+
2362
+ const numBlocksX = Math.ceil( width / 8.0 );
2363
+ const numBlocksY = Math.ceil( height / 8.0 );
2364
+ const numFullBlocksX = Math.floor( width / 8.0 );
2365
+ const leftoverX = width - ( numBlocksX - 1 ) * 8;
2366
+ const leftoverY = height - ( numBlocksY - 1 ) * 8;
2367
+
2368
+ const currAcComp = { value: 0 };
2369
+ let currDcComp = 0;
2370
+ const dctData = new Float32Array( 64 );
2371
+ const halfZigBlock = new Uint16Array( 64 );
2372
+ const rowBlock = new Uint16Array( numBlocksX * 64 );
2373
+
2374
+ for ( let blocky = 0; blocky < numBlocksY; ++ blocky ) {
2375
+
2376
+ let maxY = 8;
2377
+
2378
+ if ( blocky == numBlocksY - 1 ) maxY = leftoverY;
2379
+
2380
+ for ( let blockx = 0; blockx < numBlocksX; ++ blockx ) {
2381
+
2382
+ halfZigBlock.fill( 0 );
2383
+ halfZigBlock[ 0 ] = dcBuffer[ currDcComp ++ ];
2384
+ unRleAC( currAcComp, acBuffer, halfZigBlock );
2385
+ unZigZag( halfZigBlock, dctData );
2386
+ dctInverse( dctData );
2387
+ convertToHalf( dctData, rowBlock, blockx * 64 );
2388
+
2389
+ }
2390
+
2391
+ // Write decoded data to output buffer
2392
+ for ( let y = 8 * blocky; y < 8 * blocky + maxY; ++ y ) {
2393
+
2394
+ let offset = rowPtrs[ channelIndex ][ y ];
2395
+
2396
+ for ( let blockx = 0; blockx < numFullBlocksX; ++ blockx ) {
2397
+
2398
+ const src = blockx * 64 + ( ( y & 0x7 ) * 8 );
2399
+
2400
+ for ( let x = 0; x < 8; ++ x ) {
2401
+
2402
+ dataView.setUint16( offset + x * INT16_SIZE * cd.type, rowBlock[ src + x ], true );
2403
+
2404
+ }
2405
+
2406
+ offset += 8 * INT16_SIZE * cd.type;
2407
+
2408
+ }
2409
+
2410
+ if ( numBlocksX != numFullBlocksX ) {
2411
+
2412
+ const src = numFullBlocksX * 64 + ( ( y & 0x7 ) * 8 );
2413
+
2414
+ for ( let x = 0; x < leftoverX; ++ x ) {
2415
+
2416
+ dataView.setUint16( offset + x * INT16_SIZE * cd.type, rowBlock[ src + x ], true );
2417
+
2418
+ }
2419
+
2420
+ }
2421
+
2422
+ }
2423
+
2424
+ }
2425
+
2426
+ cd.decoded = true;
2427
+
2428
+ }
2429
+
2430
+ function unRleAC( currAcComp, acBuffer, halfZigBlock ) {
2431
+
2432
+ let acValue;
2433
+ let dctComp = 1;
2434
+
2435
+ while ( dctComp < 64 ) {
2436
+
2437
+ acValue = acBuffer[ currAcComp.value ];
2438
+
2439
+ if ( acValue == 0xff00 ) {
2440
+
2441
+ dctComp = 64;
2442
+
2443
+ } else if ( acValue >> 8 == 0xff ) {
2444
+
2445
+ dctComp += acValue & 0xff;
2446
+
2447
+ } else {
2448
+
2449
+ halfZigBlock[ dctComp ] = acValue;
2450
+ dctComp ++;
2451
+
2452
+ }
2453
+
2454
+ currAcComp.value ++;
2455
+
2456
+ }
2457
+
2458
+ }
2459
+
2460
+ function unZigZag( src, dst ) {
2461
+
2462
+ dst[ 0 ] = decodeFloat16( src[ 0 ] );
2463
+ dst[ 1 ] = decodeFloat16( src[ 1 ] );
2464
+ dst[ 2 ] = decodeFloat16( src[ 5 ] );
2465
+ dst[ 3 ] = decodeFloat16( src[ 6 ] );
2466
+ dst[ 4 ] = decodeFloat16( src[ 14 ] );
2467
+ dst[ 5 ] = decodeFloat16( src[ 15 ] );
2468
+ dst[ 6 ] = decodeFloat16( src[ 27 ] );
2469
+ dst[ 7 ] = decodeFloat16( src[ 28 ] );
2470
+ dst[ 8 ] = decodeFloat16( src[ 2 ] );
2471
+ dst[ 9 ] = decodeFloat16( src[ 4 ] );
2472
+
2473
+ dst[ 10 ] = decodeFloat16( src[ 7 ] );
2474
+ dst[ 11 ] = decodeFloat16( src[ 13 ] );
2475
+ dst[ 12 ] = decodeFloat16( src[ 16 ] );
2476
+ dst[ 13 ] = decodeFloat16( src[ 26 ] );
2477
+ dst[ 14 ] = decodeFloat16( src[ 29 ] );
2478
+ dst[ 15 ] = decodeFloat16( src[ 42 ] );
2479
+ dst[ 16 ] = decodeFloat16( src[ 3 ] );
2480
+ dst[ 17 ] = decodeFloat16( src[ 8 ] );
2481
+ dst[ 18 ] = decodeFloat16( src[ 12 ] );
2482
+ dst[ 19 ] = decodeFloat16( src[ 17 ] );
2483
+
2484
+ dst[ 20 ] = decodeFloat16( src[ 25 ] );
2485
+ dst[ 21 ] = decodeFloat16( src[ 30 ] );
2486
+ dst[ 22 ] = decodeFloat16( src[ 41 ] );
2487
+ dst[ 23 ] = decodeFloat16( src[ 43 ] );
2488
+ dst[ 24 ] = decodeFloat16( src[ 9 ] );
2489
+ dst[ 25 ] = decodeFloat16( src[ 11 ] );
2490
+ dst[ 26 ] = decodeFloat16( src[ 18 ] );
2491
+ dst[ 27 ] = decodeFloat16( src[ 24 ] );
2492
+ dst[ 28 ] = decodeFloat16( src[ 31 ] );
2493
+ dst[ 29 ] = decodeFloat16( src[ 40 ] );
2494
+
2495
+ dst[ 30 ] = decodeFloat16( src[ 44 ] );
2496
+ dst[ 31 ] = decodeFloat16( src[ 53 ] );
2497
+ dst[ 32 ] = decodeFloat16( src[ 10 ] );
2498
+ dst[ 33 ] = decodeFloat16( src[ 19 ] );
2499
+ dst[ 34 ] = decodeFloat16( src[ 23 ] );
2500
+ dst[ 35 ] = decodeFloat16( src[ 32 ] );
2501
+ dst[ 36 ] = decodeFloat16( src[ 39 ] );
2502
+ dst[ 37 ] = decodeFloat16( src[ 45 ] );
2503
+ dst[ 38 ] = decodeFloat16( src[ 52 ] );
2504
+ dst[ 39 ] = decodeFloat16( src[ 54 ] );
2505
+
2506
+ dst[ 40 ] = decodeFloat16( src[ 20 ] );
2507
+ dst[ 41 ] = decodeFloat16( src[ 22 ] );
2508
+ dst[ 42 ] = decodeFloat16( src[ 33 ] );
2509
+ dst[ 43 ] = decodeFloat16( src[ 38 ] );
2510
+ dst[ 44 ] = decodeFloat16( src[ 46 ] );
2511
+ dst[ 45 ] = decodeFloat16( src[ 51 ] );
2512
+ dst[ 46 ] = decodeFloat16( src[ 55 ] );
2513
+ dst[ 47 ] = decodeFloat16( src[ 60 ] );
2514
+ dst[ 48 ] = decodeFloat16( src[ 21 ] );
2515
+ dst[ 49 ] = decodeFloat16( src[ 34 ] );
2516
+
2517
+ dst[ 50 ] = decodeFloat16( src[ 37 ] );
2518
+ dst[ 51 ] = decodeFloat16( src[ 47 ] );
2519
+ dst[ 52 ] = decodeFloat16( src[ 50 ] );
2520
+ dst[ 53 ] = decodeFloat16( src[ 56 ] );
2521
+ dst[ 54 ] = decodeFloat16( src[ 59 ] );
2522
+ dst[ 55 ] = decodeFloat16( src[ 61 ] );
2523
+ dst[ 56 ] = decodeFloat16( src[ 35 ] );
2524
+ dst[ 57 ] = decodeFloat16( src[ 36 ] );
2525
+ dst[ 58 ] = decodeFloat16( src[ 48 ] );
2526
+ dst[ 59 ] = decodeFloat16( src[ 49 ] );
2527
+
2528
+ dst[ 60 ] = decodeFloat16( src[ 57 ] );
2529
+ dst[ 61 ] = decodeFloat16( src[ 58 ] );
2530
+ dst[ 62 ] = decodeFloat16( src[ 62 ] );
2531
+ dst[ 63 ] = decodeFloat16( src[ 63 ] );
2532
+
2533
+ }
2534
+
2535
+ function dctInverse( data ) {
2536
+
2537
+ const a = 0.5 * Math.cos( 3.14159 / 4.0 );
2538
+ const b = 0.5 * Math.cos( 3.14159 / 16.0 );
2539
+ const c = 0.5 * Math.cos( 3.14159 / 8.0 );
2540
+ const d = 0.5 * Math.cos( 3.0 * 3.14159 / 16.0 );
2541
+ const e = 0.5 * Math.cos( 5.0 * 3.14159 / 16.0 );
2542
+ const f = 0.5 * Math.cos( 3.0 * 3.14159 / 8.0 );
2543
+ const g = 0.5 * Math.cos( 7.0 * 3.14159 / 16.0 );
2544
+
2545
+ const alpha = new Array( 4 );
2546
+ const beta = new Array( 4 );
2547
+ const theta = new Array( 4 );
2548
+ const gamma = new Array( 4 );
2549
+
2550
+ for ( let row = 0; row < 8; ++ row ) {
2551
+
2552
+ const rowPtr = row * 8;
2553
+
2554
+ alpha[ 0 ] = c * data[ rowPtr + 2 ];
2555
+ alpha[ 1 ] = f * data[ rowPtr + 2 ];
2556
+ alpha[ 2 ] = c * data[ rowPtr + 6 ];
2557
+ alpha[ 3 ] = f * data[ rowPtr + 6 ];
2558
+
2559
+ beta[ 0 ] = b * data[ rowPtr + 1 ] + d * data[ rowPtr + 3 ] + e * data[ rowPtr + 5 ] + g * data[ rowPtr + 7 ];
2560
+ beta[ 1 ] = d * data[ rowPtr + 1 ] - g * data[ rowPtr + 3 ] - b * data[ rowPtr + 5 ] - e * data[ rowPtr + 7 ];
2561
+ beta[ 2 ] = e * data[ rowPtr + 1 ] - b * data[ rowPtr + 3 ] + g * data[ rowPtr + 5 ] + d * data[ rowPtr + 7 ];
2562
+ beta[ 3 ] = g * data[ rowPtr + 1 ] - e * data[ rowPtr + 3 ] + d * data[ rowPtr + 5 ] - b * data[ rowPtr + 7 ];
2563
+
2564
+ theta[ 0 ] = a * ( data[ rowPtr + 0 ] + data[ rowPtr + 4 ] );
2565
+ theta[ 3 ] = a * ( data[ rowPtr + 0 ] - data[ rowPtr + 4 ] );
2566
+ theta[ 1 ] = alpha[ 0 ] + alpha[ 3 ];
2567
+ theta[ 2 ] = alpha[ 1 ] - alpha[ 2 ];
2568
+
2569
+ gamma[ 0 ] = theta[ 0 ] + theta[ 1 ];
2570
+ gamma[ 1 ] = theta[ 3 ] + theta[ 2 ];
2571
+ gamma[ 2 ] = theta[ 3 ] - theta[ 2 ];
2572
+ gamma[ 3 ] = theta[ 0 ] - theta[ 1 ];
2573
+
2574
+ data[ rowPtr + 0 ] = gamma[ 0 ] + beta[ 0 ];
2575
+ data[ rowPtr + 1 ] = gamma[ 1 ] + beta[ 1 ];
2576
+ data[ rowPtr + 2 ] = gamma[ 2 ] + beta[ 2 ];
2577
+ data[ rowPtr + 3 ] = gamma[ 3 ] + beta[ 3 ];
2578
+
2579
+ data[ rowPtr + 4 ] = gamma[ 3 ] - beta[ 3 ];
2580
+ data[ rowPtr + 5 ] = gamma[ 2 ] - beta[ 2 ];
2581
+ data[ rowPtr + 6 ] = gamma[ 1 ] - beta[ 1 ];
2582
+ data[ rowPtr + 7 ] = gamma[ 0 ] - beta[ 0 ];
2583
+
2584
+ }
2585
+
2586
+ for ( let column = 0; column < 8; ++ column ) {
2587
+
2588
+ alpha[ 0 ] = c * data[ 16 + column ];
2589
+ alpha[ 1 ] = f * data[ 16 + column ];
2590
+ alpha[ 2 ] = c * data[ 48 + column ];
2591
+ alpha[ 3 ] = f * data[ 48 + column ];
2592
+
2593
+ beta[ 0 ] = b * data[ 8 + column ] + d * data[ 24 + column ] + e * data[ 40 + column ] + g * data[ 56 + column ];
2594
+ beta[ 1 ] = d * data[ 8 + column ] - g * data[ 24 + column ] - b * data[ 40 + column ] - e * data[ 56 + column ];
2595
+ beta[ 2 ] = e * data[ 8 + column ] - b * data[ 24 + column ] + g * data[ 40 + column ] + d * data[ 56 + column ];
2596
+ beta[ 3 ] = g * data[ 8 + column ] - e * data[ 24 + column ] + d * data[ 40 + column ] - b * data[ 56 + column ];
2597
+
2598
+ theta[ 0 ] = a * ( data[ column ] + data[ 32 + column ] );
2599
+ theta[ 3 ] = a * ( data[ column ] - data[ 32 + column ] );
2600
+
2601
+ theta[ 1 ] = alpha[ 0 ] + alpha[ 3 ];
2602
+ theta[ 2 ] = alpha[ 1 ] - alpha[ 2 ];
2603
+
2604
+ gamma[ 0 ] = theta[ 0 ] + theta[ 1 ];
2605
+ gamma[ 1 ] = theta[ 3 ] + theta[ 2 ];
2606
+ gamma[ 2 ] = theta[ 3 ] - theta[ 2 ];
2607
+ gamma[ 3 ] = theta[ 0 ] - theta[ 1 ];
2608
+
2609
+ data[ 0 + column ] = gamma[ 0 ] + beta[ 0 ];
2610
+ data[ 8 + column ] = gamma[ 1 ] + beta[ 1 ];
2611
+ data[ 16 + column ] = gamma[ 2 ] + beta[ 2 ];
2612
+ data[ 24 + column ] = gamma[ 3 ] + beta[ 3 ];
2613
+
2614
+ data[ 32 + column ] = gamma[ 3 ] - beta[ 3 ];
2615
+ data[ 40 + column ] = gamma[ 2 ] - beta[ 2 ];
2616
+ data[ 48 + column ] = gamma[ 1 ] - beta[ 1 ];
2617
+ data[ 56 + column ] = gamma[ 0 ] - beta[ 0 ];
2618
+
2619
+ }
2620
+
2621
+ }
2622
+
2623
+ function csc709Inverse( data ) {
2624
+
2625
+ for ( let i = 0; i < 64; ++ i ) {
2626
+
2627
+ const y = data[ 0 ][ i ];
2628
+ const cb = data[ 1 ][ i ];
2629
+ const cr = data[ 2 ][ i ];
2630
+
2631
+ data[ 0 ][ i ] = y + 1.5747 * cr;
2632
+ data[ 1 ][ i ] = y - 0.1873 * cb - 0.4682 * cr;
2633
+ data[ 2 ][ i ] = y + 1.8556 * cb;
2634
+
2635
+ }
2636
+
2637
+ }
2638
+
2639
+ function convertToHalf( src, dst, idx ) {
2640
+
2641
+ for ( let i = 0; i < 64; ++ i ) {
2642
+
2643
+ dst[ idx + i ] = THREE.DataUtils.toHalfFloat( toLinear( src[ i ] ) );
2644
+
2645
+ }
2646
+
2647
+ }
2648
+
2649
+ function toLinear( float ) {
2650
+
2651
+ if ( float <= 1 ) {
2652
+
2653
+ return Math.sign( float ) * Math.pow( Math.abs( float ), 2.2 );
2654
+
2655
+ } else {
2656
+
2657
+ return Math.sign( float ) * Math.pow( logBase, Math.abs( float ) - 1.0 );
2658
+
2659
+ }
2660
+
2661
+ }
2662
+
2663
+ function uncompressRAW( info ) {
2664
+
2665
+ return new DataView( info.array.buffer, info.offset.value, info.size );
2666
+
2667
+ }
2668
+
2669
+ function uncompressRLE( info ) {
2670
+
2671
+ const compressed = info.viewer.buffer.slice( info.offset.value, info.offset.value + info.size );
2672
+
2673
+ const rawBuffer = new Uint8Array( decodeRunLength( compressed ) );
2674
+ const tmpBuffer = new Uint8Array( rawBuffer.length );
2675
+
2676
+ predictor( rawBuffer ); // revert predictor
2677
+
2678
+ interleaveScalar( rawBuffer, tmpBuffer ); // interleave pixels
2679
+
2680
+ return new DataView( tmpBuffer.buffer );
2681
+
2682
+ }
2683
+
2684
+ function uncompressZIP( info ) {
2685
+
2686
+ const compressed = info.array.slice( info.offset.value, info.offset.value + info.size );
2687
+
2688
+ const rawBuffer = unzlibSync( compressed );
2689
+ const tmpBuffer = new Uint8Array( rawBuffer.length );
2690
+
2691
+ predictor( rawBuffer ); // revert predictor
2692
+
2693
+ interleaveScalar( rawBuffer, tmpBuffer ); // interleave pixels
2694
+
2695
+ return new DataView( tmpBuffer.buffer );
2696
+
2697
+ }
2698
+
2699
+ function uncompressPIZ( info ) {
2700
+
2701
+ const inDataView = info.viewer;
2702
+ const inOffset = { value: info.offset.value };
2703
+
2704
+ const outBuffer = new Uint16Array( info.columns * info.lines * ( info.inputChannels.length * info.type ) );
2705
+ const bitmap = new Uint8Array( BITMAP_SIZE );
2706
+
2707
+ // Setup channel info
2708
+ let outBufferEnd = 0;
2709
+ const pizChannelData = new Array( info.inputChannels.length );
2710
+ for ( let i = 0, il = info.inputChannels.length; i < il; i ++ ) {
2711
+
2712
+ pizChannelData[ i ] = {};
2713
+ pizChannelData[ i ][ 'start' ] = outBufferEnd;
2714
+ pizChannelData[ i ][ 'end' ] = pizChannelData[ i ][ 'start' ];
2715
+ pizChannelData[ i ][ 'nx' ] = info.columns;
2716
+ pizChannelData[ i ][ 'ny' ] = info.lines;
2717
+ pizChannelData[ i ][ 'size' ] = info.type;
2718
+
2719
+ outBufferEnd += pizChannelData[ i ].nx * pizChannelData[ i ].ny * pizChannelData[ i ].size;
2720
+
2721
+ }
2722
+
2723
+ // Read range compression data
2724
+
2725
+ const minNonZero = parseUint16( inDataView, inOffset );
2726
+ const maxNonZero = parseUint16( inDataView, inOffset );
2727
+
2728
+ if ( maxNonZero >= BITMAP_SIZE ) {
2729
+
2730
+ throw new Error( 'Something is wrong with PIZ_COMPRESSION BITMAP_SIZE' );
2731
+
2732
+ }
2733
+
2734
+ if ( minNonZero <= maxNonZero ) {
2735
+
2736
+ for ( let i = 0; i < maxNonZero - minNonZero + 1; i ++ ) {
2737
+
2738
+ bitmap[ i + minNonZero ] = parseUint8( inDataView, inOffset );
2739
+
2740
+ }
2741
+
2742
+ }
2743
+
2744
+ // Reverse LUT
2745
+ const lut = new Uint16Array( USHORT_RANGE );
2746
+ const maxValue = reverseLutFromBitmap( bitmap, lut );
2747
+
2748
+ const length = parseUint32( inDataView, inOffset );
2749
+
2750
+ // Huffman decoding
2751
+ hufUncompress( info.array, inDataView, inOffset, length, outBuffer, outBufferEnd );
2752
+
2753
+ // Wavelet decoding
2754
+ for ( let i = 0; i < info.inputChannels.length; ++ i ) {
2755
+
2756
+ const cd = pizChannelData[ i ];
2757
+
2758
+ for ( let j = 0; j < pizChannelData[ i ].size; ++ j ) {
2759
+
2760
+ wav2Decode(
2761
+ outBuffer,
2762
+ cd.start + j,
2763
+ cd.nx,
2764
+ cd.size,
2765
+ cd.ny,
2766
+ cd.nx * cd.size,
2767
+ maxValue
2768
+ );
2769
+
2770
+ }
2771
+
2772
+ }
2773
+
2774
+ // Expand the pixel data to their original range
2775
+ applyLut( lut, outBuffer, outBufferEnd );
2776
+
2777
+ // Rearrange the pixel data into the format expected by the caller.
2778
+ let tmpOffset = 0;
2779
+ const tmpBuffer = new Uint8Array( outBuffer.buffer.byteLength );
2780
+ for ( let y = 0; y < info.lines; y ++ ) {
2781
+
2782
+ for ( let c = 0; c < info.inputChannels.length; c ++ ) {
2783
+
2784
+ const cd = pizChannelData[ c ];
2785
+
2786
+ const n = cd.nx * cd.size;
2787
+ const cp = new Uint8Array( outBuffer.buffer, cd.end * INT16_SIZE, n * INT16_SIZE );
2788
+
2789
+ tmpBuffer.set( cp, tmpOffset );
2790
+ tmpOffset += n * INT16_SIZE;
2791
+ cd.end += n;
2792
+
2793
+ }
2794
+
2795
+ }
2796
+
2797
+ return new DataView( tmpBuffer.buffer );
2798
+
2799
+ }
2800
+
2801
+ function uncompressPXR( info ) {
2802
+
2803
+ const compressed = info.array.slice( info.offset.value, info.offset.value + info.size );
2804
+
2805
+ const rawBuffer = unzlibSync( compressed );
2806
+
2807
+ const byteSize = info.inputChannels.length * info.lines * info.columns * info.totalBytes;
2808
+ const tmpBuffer = new ArrayBuffer( byteSize );
2809
+ const viewer = new DataView( tmpBuffer );
2810
+
2811
+ let tmpBufferEnd = 0;
2812
+ let writePtr = 0;
2813
+ const ptr = new Array( 4 );
2814
+
2815
+ for ( let y = 0; y < info.lines; y ++ ) {
2816
+
2817
+ for ( let c = 0; c < info.inputChannels.length; c ++ ) {
2818
+
2819
+ let pixel = 0;
2820
+
2821
+ const type = info.inputChannels[ c ].pixelType;
2822
+ switch ( type ) {
2823
+
2824
+ case 1:
2825
+
2826
+ ptr[ 0 ] = tmpBufferEnd;
2827
+ ptr[ 1 ] = ptr[ 0 ] + info.columns;
2828
+ tmpBufferEnd = ptr[ 1 ] + info.columns;
2829
+
2830
+ for ( let j = 0; j < info.columns; ++ j ) {
2831
+
2832
+ const diff = ( rawBuffer[ ptr[ 0 ] ++ ] << 8 ) | rawBuffer[ ptr[ 1 ] ++ ];
2833
+
2834
+ pixel += diff;
2835
+
2836
+ viewer.setUint16( writePtr, pixel, true );
2837
+ writePtr += 2;
2838
+
2839
+ }
2840
+
2841
+ break;
2842
+
2843
+ case 2:
2844
+
2845
+ ptr[ 0 ] = tmpBufferEnd;
2846
+ ptr[ 1 ] = ptr[ 0 ] + info.columns;
2847
+ ptr[ 2 ] = ptr[ 1 ] + info.columns;
2848
+ tmpBufferEnd = ptr[ 2 ] + info.columns;
2849
+
2850
+ for ( let j = 0; j < info.columns; ++ j ) {
2851
+
2852
+ const diff = ( rawBuffer[ ptr[ 0 ] ++ ] << 24 ) | ( rawBuffer[ ptr[ 1 ] ++ ] << 16 ) | ( rawBuffer[ ptr[ 2 ] ++ ] << 8 );
2853
+
2854
+ pixel += diff;
2855
+
2856
+ viewer.setUint32( writePtr, pixel, true );
2857
+ writePtr += 4;
2858
+
2859
+ }
2860
+
2861
+ break;
2862
+
2863
+ }
2864
+
2865
+ }
2866
+
2867
+ }
2868
+
2869
+ return viewer;
2870
+
2871
+ }
2872
+
2873
+ function uncompressDWA( info ) {
2874
+
2875
+ const inDataView = info.viewer;
2876
+ const inOffset = { value: info.offset.value };
2877
+ const outBuffer = new Uint8Array( info.columns * info.lines * ( info.inputChannels.length * info.type * INT16_SIZE ) );
2878
+
2879
+ // Read compression header information
2880
+ const dwaHeader = {
2881
+
2882
+ version: parseInt64( inDataView, inOffset ),
2883
+ unknownUncompressedSize: parseInt64( inDataView, inOffset ),
2884
+ unknownCompressedSize: parseInt64( inDataView, inOffset ),
2885
+ acCompressedSize: parseInt64( inDataView, inOffset ),
2886
+ dcCompressedSize: parseInt64( inDataView, inOffset ),
2887
+ rleCompressedSize: parseInt64( inDataView, inOffset ),
2888
+ rleUncompressedSize: parseInt64( inDataView, inOffset ),
2889
+ rleRawSize: parseInt64( inDataView, inOffset ),
2890
+ totalAcUncompressedCount: parseInt64( inDataView, inOffset ),
2891
+ totalDcUncompressedCount: parseInt64( inDataView, inOffset ),
2892
+ acCompression: parseInt64( inDataView, inOffset )
2893
+
2894
+ };
2895
+
2896
+ if ( dwaHeader.version < 2 )
2897
+ throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' version ' + dwaHeader.version + ' is unsupported' );
2898
+
2899
+ // Read channel ruleset information
2900
+ const channelRules = new Array();
2901
+ let ruleSize = parseUint16( inDataView, inOffset ) - INT16_SIZE;
2902
+
2903
+ while ( ruleSize > 0 ) {
2904
+
2905
+ const name = parseNullTerminatedString( inDataView.buffer, inOffset );
2906
+ const value = parseUint8( inDataView, inOffset );
2907
+ const compression = ( value >> 2 ) & 3;
2908
+ const csc = ( value >> 4 ) - 1;
2909
+ const index = new Int8Array( [ csc ] )[ 0 ];
2910
+ const type = parseUint8( inDataView, inOffset );
2911
+
2912
+ channelRules.push( {
2913
+ name: name,
2914
+ index: index,
2915
+ type: type,
2916
+ compression: compression,
2917
+ } );
2918
+
2919
+ ruleSize -= name.length + 3;
2920
+
2921
+ }
2922
+
2923
+ // Classify channels
2924
+ const channels = EXRHeader.channels;
2925
+ const channelData = new Array( info.inputChannels.length );
2926
+
2927
+ for ( let i = 0; i < info.inputChannels.length; ++ i ) {
2928
+
2929
+ const cd = channelData[ i ] = {};
2930
+ const channel = channels[ i ];
2931
+
2932
+ cd.name = channel.name;
2933
+ cd.compression = UNKNOWN;
2934
+ cd.decoded = false;
2935
+ cd.type = channel.pixelType;
2936
+ cd.pLinear = channel.pLinear;
2937
+ cd.width = info.columns;
2938
+ cd.height = info.lines;
2939
+
2940
+ }
2941
+
2942
+ const cscSet = {
2943
+ idx: new Array( 3 )
2944
+ };
2945
+
2946
+ for ( let offset = 0; offset < info.inputChannels.length; ++ offset ) {
2947
+
2948
+ const cd = channelData[ offset ];
2949
+
2950
+ for ( let i = 0; i < channelRules.length; ++ i ) {
2951
+
2952
+ const rule = channelRules[ i ];
2953
+
2954
+ if ( cd.name == rule.name ) {
2955
+
2956
+ cd.compression = rule.compression;
2957
+
2958
+ if ( rule.index >= 0 ) {
2959
+
2960
+ cscSet.idx[ rule.index ] = offset;
2961
+
2962
+ }
2963
+
2964
+ cd.offset = offset;
2965
+
2966
+ }
2967
+
2968
+ }
2969
+
2970
+ }
2971
+
2972
+ let acBuffer, dcBuffer, rleBuffer;
2973
+
2974
+ // Read DCT - AC component data
2975
+ if ( dwaHeader.acCompressedSize > 0 ) {
2976
+
2977
+ switch ( dwaHeader.acCompression ) {
2978
+
2979
+ case STATIC_HUFFMAN:
2980
+
2981
+ acBuffer = new Uint16Array( dwaHeader.totalAcUncompressedCount );
2982
+ hufUncompress( info.array, inDataView, inOffset, dwaHeader.acCompressedSize, acBuffer, dwaHeader.totalAcUncompressedCount );
2983
+ break;
2984
+
2985
+ case DEFLATE:
2986
+
2987
+ const compressed = info.array.slice( inOffset.value, inOffset.value + dwaHeader.totalAcUncompressedCount );
2988
+ const data = unzlibSync( compressed );
2989
+ acBuffer = new Uint16Array( data.buffer );
2990
+ inOffset.value += dwaHeader.totalAcUncompressedCount;
2991
+ break;
2992
+
2993
+ }
2994
+
2995
+
2996
+ }
2997
+
2998
+ // Read DCT - DC component data
2999
+ if ( dwaHeader.dcCompressedSize > 0 ) {
3000
+
3001
+ const zlibInfo = {
3002
+ array: info.array,
3003
+ offset: inOffset,
3004
+ size: dwaHeader.dcCompressedSize
3005
+ };
3006
+ dcBuffer = new Uint16Array( uncompressZIP( zlibInfo ).buffer );
3007
+ inOffset.value += dwaHeader.dcCompressedSize;
3008
+
3009
+ }
3010
+
3011
+ // Read RLE compressed data
3012
+ if ( dwaHeader.rleRawSize > 0 ) {
3013
+
3014
+ const compressed = info.array.slice( inOffset.value, inOffset.value + dwaHeader.rleCompressedSize );
3015
+ const data = unzlibSync( compressed );
3016
+ rleBuffer = decodeRunLength( data.buffer );
3017
+
3018
+ inOffset.value += dwaHeader.rleCompressedSize;
3019
+
3020
+ }
3021
+
3022
+ // Prepare outbuffer data offset
3023
+ let outBufferEnd = 0;
3024
+ const rowOffsets = new Array( channelData.length );
3025
+ for ( let i = 0; i < rowOffsets.length; ++ i ) {
3026
+
3027
+ rowOffsets[ i ] = new Array();
3028
+
3029
+ }
3030
+
3031
+ for ( let y = 0; y < info.lines; ++ y ) {
3032
+
3033
+ for ( let chan = 0; chan < channelData.length; ++ chan ) {
3034
+
3035
+ rowOffsets[ chan ].push( outBufferEnd );
3036
+ outBufferEnd += channelData[ chan ].width * info.type * INT16_SIZE;
3037
+
3038
+ }
3039
+
3040
+ }
3041
+
3042
+ // Decode lossy DCT data if we have a valid color space conversion set with the first RGB channel present
3043
+ if ( cscSet.idx[ 0 ] !== undefined && channelData[ cscSet.idx[ 0 ] ] ) {
3044
+
3045
+ lossyDctDecode( cscSet, rowOffsets, channelData, acBuffer, dcBuffer, outBuffer );
3046
+
3047
+ }
3048
+
3049
+ // Decode other channels
3050
+ for ( let i = 0; i < channelData.length; ++ i ) {
3051
+
3052
+ const cd = channelData[ i ];
3053
+
3054
+ if ( cd.decoded ) continue;
3055
+
3056
+ switch ( cd.compression ) {
3057
+
3058
+ case RLE:
3059
+
3060
+ let row = 0;
3061
+ let rleOffset = 0;
3062
+
3063
+ for ( let y = 0; y < info.lines; ++ y ) {
3064
+
3065
+ let rowOffsetBytes = rowOffsets[ i ][ row ];
3066
+
3067
+ for ( let x = 0; x < cd.width; ++ x ) {
3068
+
3069
+ for ( let byte = 0; byte < INT16_SIZE * cd.type; ++ byte ) {
3070
+
3071
+ outBuffer[ rowOffsetBytes ++ ] = rleBuffer[ rleOffset + byte * cd.width * cd.height ];
3072
+
3073
+ }
3074
+
3075
+ rleOffset ++;
3076
+
3077
+ }
3078
+
3079
+ row ++;
3080
+
3081
+ }
3082
+
3083
+ break;
3084
+
3085
+ case LOSSY_DCT:
3086
+
3087
+ lossyDctChannelDecode( i, rowOffsets, channelData, acBuffer, dcBuffer, outBuffer );
3088
+
3089
+ break;
3090
+
3091
+ default:
3092
+ throw new Error( 'EXRLoader.parse: unsupported channel compression' );
3093
+
3094
+ }
3095
+
3096
+ }
3097
+
3098
+ return new DataView( outBuffer.buffer );
3099
+
3100
+ }
3101
+
3102
+ function parseNullTerminatedString( buffer, offset ) {
3103
+
3104
+ const uintBuffer = new Uint8Array( buffer );
3105
+ let endOffset = 0;
3106
+
3107
+ while ( uintBuffer[ offset.value + endOffset ] != 0 ) {
3108
+
3109
+ endOffset += 1;
3110
+
3111
+ }
3112
+
3113
+ const stringValue = new TextDecoder().decode(
3114
+ uintBuffer.slice( offset.value, offset.value + endOffset )
3115
+ );
3116
+
3117
+ offset.value = offset.value + endOffset + 1;
3118
+
3119
+ return stringValue;
3120
+
3121
+ }
3122
+
3123
+ function parseFixedLengthString( buffer, offset, size ) {
3124
+
3125
+ const stringValue = new TextDecoder().decode(
3126
+ new Uint8Array( buffer ).slice( offset.value, offset.value + size )
3127
+ );
3128
+
3129
+ offset.value = offset.value + size;
3130
+
3131
+ return stringValue;
3132
+
3133
+ }
3134
+
3135
+ function parseRational( dataView, offset ) {
3136
+
3137
+ const x = parseInt32( dataView, offset );
3138
+ const y = parseUint32( dataView, offset );
3139
+
3140
+ return [ x, y ];
3141
+
3142
+ }
3143
+
3144
+ function parseTimecode( dataView, offset ) {
3145
+
3146
+ const x = parseUint32( dataView, offset );
3147
+ const y = parseUint32( dataView, offset );
3148
+
3149
+ return [ x, y ];
3150
+
3151
+ }
3152
+
3153
+ function parseInt32( dataView, offset ) {
3154
+
3155
+ const Int32 = dataView.getInt32( offset.value, true );
3156
+
3157
+ offset.value = offset.value + INT32_SIZE;
3158
+
3159
+ return Int32;
3160
+
3161
+ }
3162
+
3163
+ function parseUint32( dataView, offset ) {
3164
+
3165
+ const Uint32 = dataView.getUint32( offset.value, true );
3166
+
3167
+ offset.value = offset.value + INT32_SIZE;
3168
+
3169
+ return Uint32;
3170
+
3171
+ }
3172
+
3173
+ function parseUint8Array( uInt8Array, offset ) {
3174
+
3175
+ const Uint8 = uInt8Array[ offset.value ];
3176
+
3177
+ offset.value = offset.value + INT8_SIZE;
3178
+
3179
+ return Uint8;
3180
+
3181
+ }
3182
+
3183
+ function parseUint8( dataView, offset ) {
3184
+
3185
+ const Uint8 = dataView.getUint8( offset.value );
3186
+
3187
+ offset.value = offset.value + INT8_SIZE;
3188
+
3189
+ return Uint8;
3190
+
3191
+ }
3192
+
3193
+ const parseInt64 = function ( dataView, offset ) {
3194
+
3195
+ let int;
3196
+
3197
+ if ( 'getBigInt64' in DataView.prototype ) {
3198
+
3199
+ int = Number( dataView.getBigInt64( offset.value, true ) );
3200
+
3201
+ } else {
3202
+
3203
+ int = dataView.getUint32( offset.value + 4, true ) + Number( dataView.getUint32( offset.value, true ) << 32 );
3204
+
3205
+ }
3206
+
3207
+ offset.value += ULONG_SIZE;
3208
+
3209
+ return int;
3210
+
3211
+ };
3212
+
3213
+ function parseFloat32( dataView, offset ) {
3214
+
3215
+ const float = dataView.getFloat32( offset.value, true );
3216
+
3217
+ offset.value += FLOAT32_SIZE;
3218
+
3219
+ return float;
3220
+
3221
+ }
3222
+
3223
+ function decodeFloat32( dataView, offset ) {
3224
+
3225
+ return THREE.DataUtils.toHalfFloat( parseFloat32( dataView, offset ) );
3226
+
3227
+ }
3228
+
3229
+ // https://stackoverflow.com/questions/5678432/decompressing-half-precision-floats-in-javascript
3230
+ function decodeFloat16( binary ) {
3231
+
3232
+ const exponent = ( binary & 0x7C00 ) >> 10,
3233
+ fraction = binary & 0x03FF;
3234
+
3235
+ return ( binary >> 15 ? -1 : 1 ) * (
3236
+ exponent ?
3237
+ (
3238
+ exponent === 0x1F ?
3239
+ fraction ? NaN : Infinity :
3240
+ Math.pow( 2, exponent - 15 ) * ( 1 + fraction / 0x400 )
3241
+ ) :
3242
+ 6.103515625e-5 * ( fraction / 0x400 )
3243
+ );
3244
+
3245
+ }
3246
+
3247
+ function parseUint16( dataView, offset ) {
3248
+
3249
+ const Uint16 = dataView.getUint16( offset.value, true );
3250
+
3251
+ offset.value += INT16_SIZE;
3252
+
3253
+ return Uint16;
3254
+
3255
+ }
3256
+
3257
+ function parseFloat16( buffer, offset ) {
3258
+
3259
+ return decodeFloat16( parseUint16( buffer, offset ) );
3260
+
3261
+ }
3262
+
3263
+ function parseChlist( dataView, buffer, offset, size ) {
3264
+
3265
+ const startOffset = offset.value;
3266
+ const channels = [];
3267
+
3268
+ while ( offset.value < ( startOffset + size - 1 ) ) {
3269
+
3270
+ const name = parseNullTerminatedString( buffer, offset );
3271
+ const pixelType = parseInt32( dataView, offset );
3272
+ const pLinear = parseUint8( dataView, offset );
3273
+ offset.value += 3; // reserved, three chars
3274
+ const xSampling = parseInt32( dataView, offset );
3275
+ const ySampling = parseInt32( dataView, offset );
3276
+
3277
+ channels.push( {
3278
+ name: name,
3279
+ pixelType: pixelType,
3280
+ pLinear: pLinear,
3281
+ xSampling: xSampling,
3282
+ ySampling: ySampling
3283
+ } );
3284
+
3285
+ }
3286
+
3287
+ offset.value += 1;
3288
+
3289
+ return channels;
3290
+
3291
+ }
3292
+
3293
+ function parseChromaticities( dataView, offset ) {
3294
+
3295
+ const redX = parseFloat32( dataView, offset );
3296
+ const redY = parseFloat32( dataView, offset );
3297
+ const greenX = parseFloat32( dataView, offset );
3298
+ const greenY = parseFloat32( dataView, offset );
3299
+ const blueX = parseFloat32( dataView, offset );
3300
+ const blueY = parseFloat32( dataView, offset );
3301
+ const whiteX = parseFloat32( dataView, offset );
3302
+ const whiteY = parseFloat32( dataView, offset );
3303
+
3304
+ return { redX: redX, redY: redY, greenX: greenX, greenY: greenY, blueX: blueX, blueY: blueY, whiteX: whiteX, whiteY: whiteY };
3305
+
3306
+ }
3307
+
3308
+ function parseCompression( dataView, offset ) {
3309
+
3310
+ const compressionCodes = [
3311
+ 'NO_COMPRESSION',
3312
+ 'RLE_COMPRESSION',
3313
+ 'ZIPS_COMPRESSION',
3314
+ 'ZIP_COMPRESSION',
3315
+ 'PIZ_COMPRESSION',
3316
+ 'PXR24_COMPRESSION',
3317
+ 'B44_COMPRESSION',
3318
+ 'B44A_COMPRESSION',
3319
+ 'DWAA_COMPRESSION',
3320
+ 'DWAB_COMPRESSION'
3321
+ ];
3322
+
3323
+ const compression = parseUint8( dataView, offset );
3324
+
3325
+ return compressionCodes[ compression ];
3326
+
3327
+ }
3328
+
3329
+ function parseBox2i( dataView, offset ) {
3330
+
3331
+ const xMin = parseInt32( dataView, offset );
3332
+ const yMin = parseInt32( dataView, offset );
3333
+ const xMax = parseInt32( dataView, offset );
3334
+ const yMax = parseInt32( dataView, offset );
3335
+
3336
+ return { xMin: xMin, yMin: yMin, xMax: xMax, yMax: yMax };
3337
+
3338
+ }
3339
+
3340
+ function parseLineOrder( dataView, offset ) {
3341
+
3342
+ const lineOrders = [
3343
+ 'INCREASING_Y',
3344
+ 'DECREASING_Y',
3345
+ 'RANDOM_Y',
3346
+ ];
3347
+
3348
+ const lineOrder = parseUint8( dataView, offset );
3349
+
3350
+ return lineOrders[ lineOrder ];
3351
+
3352
+ }
3353
+
3354
+ function parseEnvmap( dataView, offset ) {
3355
+
3356
+ const envmaps = [
3357
+ 'ENVMAP_LATLONG',
3358
+ 'ENVMAP_CUBE'
3359
+ ];
3360
+
3361
+ const envmap = parseUint8( dataView, offset );
3362
+
3363
+ return envmaps[ envmap ];
3364
+
3365
+ }
3366
+
3367
+ function parseTiledesc( dataView, offset ) {
3368
+
3369
+ const levelModes = [
3370
+ 'ONE_LEVEL',
3371
+ 'MIPMAP_LEVELS',
3372
+ 'RIPMAP_LEVELS',
3373
+ ];
3374
+
3375
+ const roundingModes = [
3376
+ 'ROUND_DOWN',
3377
+ 'ROUND_UP',
3378
+ ];
3379
+
3380
+ const xSize = parseUint32( dataView, offset );
3381
+ const ySize = parseUint32( dataView, offset );
3382
+ const modes = parseUint8( dataView, offset );
3383
+
3384
+ return {
3385
+ xSize: xSize,
3386
+ ySize: ySize,
3387
+ levelMode: levelModes[ modes & 0xf ],
3388
+ roundingMode: roundingModes[ modes >> 4 ]
3389
+ };
3390
+
3391
+ }
3392
+
3393
+ function parseV2f( dataView, offset ) {
3394
+
3395
+ const x = parseFloat32( dataView, offset );
3396
+ const y = parseFloat32( dataView, offset );
3397
+
3398
+ return [ x, y ];
3399
+
3400
+ }
3401
+
3402
+ function parseV3f( dataView, offset ) {
3403
+
3404
+ const x = parseFloat32( dataView, offset );
3405
+ const y = parseFloat32( dataView, offset );
3406
+ const z = parseFloat32( dataView, offset );
3407
+
3408
+ return [ x, y, z ];
3409
+
3410
+ }
3411
+
3412
+ function parseValue( dataView, buffer, offset, type, size ) {
3413
+
3414
+ if ( type === 'string' || type === 'stringvector' || type === 'iccProfile' ) {
3415
+
3416
+ return parseFixedLengthString( buffer, offset, size );
3417
+
3418
+ } else if ( type === 'chlist' ) {
3419
+
3420
+ return parseChlist( dataView, buffer, offset, size );
3421
+
3422
+ } else if ( type === 'chromaticities' ) {
3423
+
3424
+ return parseChromaticities( dataView, offset );
3425
+
3426
+ } else if ( type === 'compression' ) {
3427
+
3428
+ return parseCompression( dataView, offset );
3429
+
3430
+ } else if ( type === 'box2i' ) {
3431
+
3432
+ return parseBox2i( dataView, offset );
3433
+
3434
+ } else if ( type === 'envmap' ) {
3435
+
3436
+ return parseEnvmap( dataView, offset );
3437
+
3438
+ } else if ( type === 'tiledesc' ) {
3439
+
3440
+ return parseTiledesc( dataView, offset );
3441
+
3442
+ } else if ( type === 'lineOrder' ) {
3443
+
3444
+ return parseLineOrder( dataView, offset );
3445
+
3446
+ } else if ( type === 'float' ) {
3447
+
3448
+ return parseFloat32( dataView, offset );
3449
+
3450
+ } else if ( type === 'v2f' ) {
3451
+
3452
+ return parseV2f( dataView, offset );
3453
+
3454
+ } else if ( type === 'v3f' ) {
3455
+
3456
+ return parseV3f( dataView, offset );
3457
+
3458
+ } else if ( type === 'int' ) {
3459
+
3460
+ return parseInt32( dataView, offset );
3461
+
3462
+ } else if ( type === 'rational' ) {
3463
+
3464
+ return parseRational( dataView, offset );
3465
+
3466
+ } else if ( type === 'timecode' ) {
3467
+
3468
+ return parseTimecode( dataView, offset );
3469
+
3470
+ } else if ( type === 'preview' ) {
3471
+
3472
+ offset.value += size;
3473
+ return 'skipped';
3474
+
3475
+ } else {
3476
+
3477
+ offset.value += size;
3478
+ return undefined;
3479
+
3480
+ }
3481
+
3482
+ }
3483
+
3484
+ function roundLog2( x, mode ) {
3485
+
3486
+ const log2 = Math.log2( x );
3487
+ return mode == 'ROUND_DOWN' ? Math.floor( log2 ) : Math.ceil( log2 );
3488
+
3489
+ }
3490
+
3491
+ function calculateTileLevels( tiledesc, w, h ) {
3492
+
3493
+ let num = 0;
3494
+
3495
+ switch ( tiledesc.levelMode ) {
3496
+
3497
+ case 'ONE_LEVEL':
3498
+ num = 1;
3499
+ break;
3500
+
3501
+ case 'MIPMAP_LEVELS':
3502
+ num = roundLog2( Math.max( w, h ), tiledesc.roundingMode ) + 1;
3503
+ break;
3504
+
3505
+ case 'RIPMAP_LEVELS':
3506
+ throw new Error( 'THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.' );
3507
+
3508
+ }
3509
+
3510
+ return num;
3511
+
3512
+ }
3513
+
3514
+ function calculateTiles( count, dataSize, size, roundingMode ) {
3515
+
3516
+ const tiles = new Array( count );
3517
+
3518
+ for ( let i = 0; i < count; i ++ ) {
3519
+
3520
+ const b = ( 1 << i );
3521
+ let s = ( dataSize / b ) | 0;
3522
+
3523
+ if ( roundingMode == 'ROUND_UP' && s * b < dataSize ) s += 1;
3524
+
3525
+ const l = Math.max( s, 1 );
3526
+
3527
+ tiles[ i ] = ( ( l + size - 1 ) / size ) | 0;
3528
+
3529
+ }
3530
+
3531
+ return tiles;
3532
+
3533
+ }
3534
+
3535
+ function parseTiles() {
3536
+
3537
+ const EXRDecoder = this;
3538
+ const offset = EXRDecoder.offset;
3539
+ const tmpOffset = { value: 0 };
3540
+
3541
+ for ( let tile = 0; tile < EXRDecoder.tileCount; tile ++ ) {
3542
+
3543
+ const tileX = parseInt32( EXRDecoder.viewer, offset );
3544
+ const tileY = parseInt32( EXRDecoder.viewer, offset );
3545
+ offset.value += 8; // skip levels - only parsing top-level
3546
+ EXRDecoder.size = parseUint32( EXRDecoder.viewer, offset );
3547
+
3548
+ const startX = tileX * EXRDecoder.blockWidth;
3549
+ const startY = tileY * EXRDecoder.blockHeight;
3550
+ EXRDecoder.columns = ( startX + EXRDecoder.blockWidth > EXRDecoder.width ) ? EXRDecoder.width - startX : EXRDecoder.blockWidth;
3551
+ EXRDecoder.lines = ( startY + EXRDecoder.blockHeight > EXRDecoder.height ) ? EXRDecoder.height - startY : EXRDecoder.blockHeight;
3552
+
3553
+ const bytesBlockLine = EXRDecoder.columns * EXRDecoder.totalBytes;
3554
+ const isCompressed = EXRDecoder.size < EXRDecoder.lines * bytesBlockLine;
3555
+ const viewer = isCompressed ? EXRDecoder.uncompress( EXRDecoder ) : uncompressRAW( EXRDecoder );
3556
+
3557
+ offset.value += EXRDecoder.size;
3558
+
3559
+ for ( let line = 0; line < EXRDecoder.lines; line ++ ) {
3560
+
3561
+ const lineOffset = line * EXRDecoder.columns * EXRDecoder.totalBytes;
3562
+
3563
+ for ( let channelID = 0; channelID < EXRDecoder.inputChannels.length; channelID ++ ) {
3564
+
3565
+ const name = EXRHeader.channels[ channelID ].name;
3566
+ const lOff = EXRDecoder.channelByteOffsets[ name ] * EXRDecoder.columns;
3567
+ const cOff = EXRDecoder.decodeChannels[ name ];
3568
+
3569
+ if ( cOff === undefined ) continue;
3570
+
3571
+ tmpOffset.value = lineOffset + lOff;
3572
+ const outLineOffset = ( EXRDecoder.height - ( 1 + startY + line ) ) * EXRDecoder.outLineWidth;
3573
+
3574
+ for ( let x = 0; x < EXRDecoder.columns; x ++ ) {
3575
+
3576
+ const outIndex = outLineOffset + ( x + startX ) * EXRDecoder.outputChannels + cOff;
3577
+ EXRDecoder.byteArray[ outIndex ] = EXRDecoder.getter( viewer, tmpOffset );
3578
+
3579
+ }
3580
+
3581
+ }
3582
+
3583
+ }
3584
+
3585
+ }
3586
+
3587
+ }
3588
+
3589
+ function parseScanline() {
3590
+
3591
+ const EXRDecoder = this;
3592
+ const offset = EXRDecoder.offset;
3593
+ const tmpOffset = { value: 0 };
3594
+
3595
+ for ( let scanlineBlockIdx = 0; scanlineBlockIdx < EXRDecoder.height / EXRDecoder.blockHeight; scanlineBlockIdx ++ ) {
3596
+
3597
+ const line = parseInt32( EXRDecoder.viewer, offset ) - EXRHeader.dataWindow.yMin; // line_no
3598
+ EXRDecoder.size = parseUint32( EXRDecoder.viewer, offset ); // data_len
3599
+ EXRDecoder.lines = ( ( line + EXRDecoder.blockHeight > EXRDecoder.height ) ? ( EXRDecoder.height - line ) : EXRDecoder.blockHeight );
3600
+
3601
+ const bytesPerLine = EXRDecoder.columns * EXRDecoder.totalBytes;
3602
+ const isCompressed = EXRDecoder.size < EXRDecoder.lines * bytesPerLine;
3603
+ const viewer = isCompressed ? EXRDecoder.uncompress( EXRDecoder ) : uncompressRAW( EXRDecoder );
3604
+
3605
+ offset.value += EXRDecoder.size;
3606
+
3607
+ for ( let line_y = 0; line_y < EXRDecoder.blockHeight; line_y ++ ) {
3608
+
3609
+ const scan_y = scanlineBlockIdx * EXRDecoder.blockHeight;
3610
+ const true_y = line_y + EXRDecoder.scanOrder( scan_y );
3611
+ if ( true_y >= EXRDecoder.height ) continue;
3612
+
3613
+ const lineOffset = line_y * bytesPerLine;
3614
+ const outLineOffset = ( EXRDecoder.height - 1 - true_y ) * EXRDecoder.outLineWidth;
3615
+
3616
+ for ( let channelID = 0; channelID < EXRDecoder.inputChannels.length; channelID ++ ) {
3617
+
3618
+ const name = EXRHeader.channels[ channelID ].name;
3619
+ const lOff = EXRDecoder.channelByteOffsets[ name ] * EXRDecoder.columns;
3620
+ const cOff = EXRDecoder.decodeChannels[ name ];
3621
+
3622
+ if ( cOff === undefined ) continue;
3623
+
3624
+ tmpOffset.value = lineOffset + lOff;
3625
+
3626
+ for ( let x = 0; x < EXRDecoder.columns; x ++ ) {
3627
+
3628
+ const outIndex = outLineOffset + x * EXRDecoder.outputChannels + cOff;
3629
+ EXRDecoder.byteArray[ outIndex ] = EXRDecoder.getter( viewer, tmpOffset );
3630
+
3631
+ }
3632
+
3633
+ }
3634
+
3635
+ }
3636
+
3637
+ }
3638
+
3639
+ }
3640
+
3641
+ function parseHeader( dataView, buffer, offset ) {
3642
+
3643
+ const EXRHeader = {};
3644
+
3645
+ if ( dataView.getUint32( 0, true ) != 20000630 ) { // magic
3646
+
3647
+ throw new Error( 'THREE.EXRLoader: Provided file doesn\'t appear to be in OpenEXR format.' );
3648
+
3649
+ }
3650
+
3651
+ EXRHeader.version = dataView.getUint8( 4 );
3652
+
3653
+ const spec = dataView.getUint8( 5 ); // fullMask
3654
+
3655
+ EXRHeader.spec = {
3656
+ singleTile: !! ( spec & 2 ),
3657
+ longName: !! ( spec & 4 ),
3658
+ deepFormat: !! ( spec & 8 ),
3659
+ multiPart: !! ( spec & 16 ),
3660
+ };
3661
+
3662
+ // start of header
3663
+
3664
+ offset.value = 8; // start at 8 - after pre-amble
3665
+
3666
+ let keepReading = true;
3667
+
3668
+ while ( keepReading ) {
3669
+
3670
+ const attributeName = parseNullTerminatedString( buffer, offset );
3671
+
3672
+ if ( attributeName === '' ) {
3673
+
3674
+ keepReading = false;
3675
+
3676
+ } else {
3677
+
3678
+ const attributeType = parseNullTerminatedString( buffer, offset );
3679
+ const attributeSize = parseUint32( dataView, offset );
3680
+ const attributeValue = parseValue( dataView, buffer, offset, attributeType, attributeSize );
3681
+
3682
+ if ( attributeValue === undefined ) {
3683
+
3684
+ console.warn( `THREE.EXRLoader: Skipped unknown header attribute type \'${attributeType}\'.` );
3685
+
3686
+ } else {
3687
+
3688
+ EXRHeader[ attributeName ] = attributeValue;
3689
+
3690
+ }
3691
+
3692
+ }
3693
+
3694
+ }
3695
+
3696
+ if ( ( spec & -7 ) != 0 ) { // unsupported deep-image, multi-part
3697
+
3698
+ console.error( 'THREE.EXRHeader:', EXRHeader );
3699
+ throw new Error( 'THREE.EXRLoader: Provided file is currently unsupported.' );
3700
+
3701
+ }
3702
+
3703
+ return EXRHeader;
3704
+
3705
+ }
3706
+
3707
+ function setupDecoder( EXRHeader, dataView, uInt8Array, offset, outputType, outputFormat ) {
3708
+
3709
+ const EXRDecoder = {
3710
+ size: 0,
3711
+ viewer: dataView,
3712
+ array: uInt8Array,
3713
+ offset: offset,
3714
+ width: EXRHeader.dataWindow.xMax - EXRHeader.dataWindow.xMin + 1,
3715
+ height: EXRHeader.dataWindow.yMax - EXRHeader.dataWindow.yMin + 1,
3716
+ inputChannels: EXRHeader.channels,
3717
+ channelByteOffsets: {},
3718
+ shouldExpand: false,
3719
+ scanOrder: null,
3720
+ totalBytes: null,
3721
+ columns: null,
3722
+ lines: null,
3723
+ type: null,
3724
+ uncompress: null,
3725
+ getter: null,
3726
+ format: null,
3727
+ colorSpace: THREE.LinearSRGBColorSpace,
3728
+ };
3729
+
3730
+ switch ( EXRHeader.compression ) {
3731
+
3732
+ case 'NO_COMPRESSION':
3733
+ EXRDecoder.blockHeight = 1;
3734
+ EXRDecoder.uncompress = uncompressRAW;
3735
+ break;
3736
+
3737
+ case 'RLE_COMPRESSION':
3738
+ EXRDecoder.blockHeight = 1;
3739
+ EXRDecoder.uncompress = uncompressRLE;
3740
+ break;
3741
+
3742
+ case 'ZIPS_COMPRESSION':
3743
+ EXRDecoder.blockHeight = 1;
3744
+ EXRDecoder.uncompress = uncompressZIP;
3745
+ break;
3746
+
3747
+ case 'ZIP_COMPRESSION':
3748
+ EXRDecoder.blockHeight = 16;
3749
+ EXRDecoder.uncompress = uncompressZIP;
3750
+ break;
3751
+
3752
+ case 'PIZ_COMPRESSION':
3753
+ EXRDecoder.blockHeight = 32;
3754
+ EXRDecoder.uncompress = uncompressPIZ;
3755
+ break;
3756
+
3757
+ case 'PXR24_COMPRESSION':
3758
+ EXRDecoder.blockHeight = 16;
3759
+ EXRDecoder.uncompress = uncompressPXR;
3760
+ break;
3761
+
3762
+ case 'DWAA_COMPRESSION':
3763
+ EXRDecoder.blockHeight = 32;
3764
+ EXRDecoder.uncompress = uncompressDWA;
3765
+ break;
3766
+
3767
+ case 'DWAB_COMPRESSION':
3768
+ EXRDecoder.blockHeight = 256;
3769
+ EXRDecoder.uncompress = uncompressDWA;
3770
+ break;
3771
+
3772
+ default:
3773
+ throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' is unsupported' );
3774
+
3775
+ }
3776
+
3777
+ const channels = {};
3778
+ for ( const channel of EXRHeader.channels ) {
3779
+
3780
+ switch ( channel.name ) {
3781
+
3782
+ case 'Y':
3783
+ case 'R':
3784
+ case 'G':
3785
+ case 'B':
3786
+ case 'A':
3787
+ channels[ channel.name ] = true;
3788
+ EXRDecoder.type = channel.pixelType;
3789
+
3790
+ }
3791
+
3792
+ }
3793
+
3794
+ // RGB images will be converted to RGBA format, preventing software emulation in select devices.
3795
+ let fillAlpha = false;
3796
+ let invalidOutput = false;
3797
+
3798
+ // Validate if input texture contain supported channels
3799
+ if ( channels.R && channels.G && channels.B ) {
3800
+
3801
+ EXRDecoder.outputChannels = 4;
3802
+
3803
+ } else if ( channels.Y ) {
3804
+
3805
+ EXRDecoder.outputChannels = 1;
3806
+
3807
+ } else {
3808
+
3809
+ throw new Error( 'EXRLoader.parse: file contains unsupported data channels.' );
3810
+
3811
+ }
3812
+
3813
+ // Setup output texture configuration
3814
+ switch ( EXRDecoder.outputChannels ) {
3815
+
3816
+ case 4:
3817
+
3818
+ if ( outputFormat == THREE.RGBAFormat ) {
3819
+
3820
+ fillAlpha = ! channels.A;
3821
+ EXRDecoder.format = THREE.RGBAFormat;
3822
+ EXRDecoder.colorSpace = THREE.LinearSRGBColorSpace;
3823
+ EXRDecoder.outputChannels = 4;
3824
+ EXRDecoder.decodeChannels = { R: 0, G: 1, B: 2, A: 3 };
3825
+
3826
+ } else if ( outputFormat == THREE.RGFormat ) {
3827
+
3828
+ EXRDecoder.format = THREE.RGFormat;
3829
+ EXRDecoder.colorSpace = THREE.LinearSRGBColorSpace;
3830
+ EXRDecoder.outputChannels = 2;
3831
+ EXRDecoder.decodeChannels = { R: 0, G: 1 };
3832
+
3833
+ } else if ( outputFormat == THREE.RedFormat ) {
3834
+
3835
+ EXRDecoder.format = THREE.RedFormat;
3836
+ EXRDecoder.colorSpace = THREE.LinearSRGBColorSpace;
3837
+ EXRDecoder.outputChannels = 1;
3838
+ EXRDecoder.decodeChannels = { R: 0 };
3839
+
3840
+ } else {
3841
+
3842
+ invalidOutput = true;
3843
+
3844
+ }
3845
+
3846
+ break;
3847
+
3848
+ case 1:
3849
+
3850
+ if ( outputFormat == THREE.RGBAFormat ) {
3851
+
3852
+ fillAlpha = true;
3853
+ EXRDecoder.format = THREE.RGBAFormat;
3854
+ EXRDecoder.colorSpace = THREE.LinearSRGBColorSpace;
3855
+ EXRDecoder.outputChannels = 4;
3856
+ EXRDecoder.shouldExpand = true;
3857
+ EXRDecoder.decodeChannels = { Y: 0 };
3858
+
3859
+ } else if ( outputFormat == THREE.RGFormat ) {
3860
+
3861
+ EXRDecoder.format = THREE.RGFormat;
3862
+ EXRDecoder.colorSpace = THREE.LinearSRGBColorSpace;
3863
+ EXRDecoder.outputChannels = 2;
3864
+ EXRDecoder.shouldExpand = true;
3865
+ EXRDecoder.decodeChannels = { Y: 0 };
3866
+
3867
+ } else if ( outputFormat == THREE.RedFormat ) {
3868
+
3869
+ EXRDecoder.format = THREE.RedFormat;
3870
+ EXRDecoder.colorSpace = THREE.LinearSRGBColorSpace;
3871
+ EXRDecoder.outputChannels = 1;
3872
+ EXRDecoder.decodeChannels = { Y: 0 };
3873
+
3874
+ } else {
3875
+
3876
+ invalidOutput = true;
3877
+
3878
+ }
3879
+
3880
+ break;
3881
+
3882
+ default:
3883
+
3884
+ invalidOutput = true;
3885
+
3886
+ }
3887
+
3888
+ if ( invalidOutput ) throw new Error( 'EXRLoader.parse: invalid output format for specified file.' );
3889
+
3890
+ if ( EXRDecoder.type == 1 ) {
3891
+
3892
+ // half
3893
+ switch ( outputType ) {
3894
+
3895
+ case THREE.FloatType:
3896
+ EXRDecoder.getter = parseFloat16;
3897
+ break;
3898
+
3899
+ case THREE.HalfFloatType:
3900
+ EXRDecoder.getter = parseUint16;
3901
+ break;
3902
+
3903
+ }
3904
+
3905
+ } else if ( EXRDecoder.type == 2 ) {
3906
+
3907
+ // float
3908
+ switch ( outputType ) {
3909
+
3910
+ case THREE.FloatType:
3911
+ EXRDecoder.getter = parseFloat32;
3912
+ break;
3913
+
3914
+ case THREE.HalfFloatType:
3915
+ EXRDecoder.getter = decodeFloat32;
3916
+
3917
+ }
3918
+
3919
+ } else {
3920
+
3921
+ throw new Error( 'EXRLoader.parse: unsupported pixelType ' + EXRDecoder.type + ' for ' + EXRHeader.compression + '.' );
3922
+
3923
+ }
3924
+
3925
+ EXRDecoder.columns = EXRDecoder.width;
3926
+ const size = EXRDecoder.width * EXRDecoder.height * EXRDecoder.outputChannels;
3927
+
3928
+ switch ( outputType ) {
3929
+
3930
+ case THREE.FloatType:
3931
+ EXRDecoder.byteArray = new Float32Array( size );
3932
+
3933
+ // Fill initially with 1s for the alpha value if the texture is not RGBA, RGB values will be overwritten
3934
+ if ( fillAlpha )
3935
+ EXRDecoder.byteArray.fill( 1, 0, size );
3936
+
3937
+ break;
3938
+
3939
+ case THREE.HalfFloatType:
3940
+ EXRDecoder.byteArray = new Uint16Array( size );
3941
+
3942
+ if ( fillAlpha )
3943
+ EXRDecoder.byteArray.fill( 0x3C00, 0, size ); // Uint16Array holds half float data, 0x3C00 is 1
3944
+
3945
+ break;
3946
+
3947
+ default:
3948
+ console.error( 'THREE.EXRLoader: unsupported type: ', outputType );
3949
+ break;
3950
+
3951
+ }
3952
+
3953
+ let byteOffset = 0;
3954
+ for ( const channel of EXRHeader.channels ) {
3955
+
3956
+ if ( EXRDecoder.decodeChannels[ channel.name ] !== undefined ) {
3957
+
3958
+ EXRDecoder.channelByteOffsets[ channel.name ] = byteOffset;
3959
+
3960
+ }
3961
+
3962
+ byteOffset += channel.pixelType * 2;
3963
+
3964
+ }
3965
+
3966
+ EXRDecoder.totalBytes = byteOffset;
3967
+ EXRDecoder.outLineWidth = EXRDecoder.width * EXRDecoder.outputChannels;
3968
+
3969
+ if ( EXRHeader.lineOrder === 'INCREASING_Y' ) {
3970
+
3971
+ EXRDecoder.scanOrder = ( y ) => y;
3972
+
3973
+ } else {
3974
+
3975
+ EXRDecoder.scanOrder = ( y ) => EXRDecoder.height - 1 - y;
3976
+
3977
+ }
3978
+
3979
+ if ( EXRHeader.spec.singleTile ) {
3980
+
3981
+ EXRDecoder.blockHeight = EXRHeader.tiles.ySize;
3982
+ EXRDecoder.blockWidth = EXRHeader.tiles.xSize;
3983
+
3984
+ const numXLevels = calculateTileLevels( EXRHeader.tiles, EXRDecoder.width, EXRDecoder.height );
3985
+ // const numYLevels = calculateTileLevels( EXRHeader.tiles, EXRDecoder.width, EXRDecoder.height );
3986
+
3987
+ const numXTiles = calculateTiles( numXLevels, EXRDecoder.width, EXRHeader.tiles.xSize, EXRHeader.tiles.roundingMode );
3988
+ const numYTiles = calculateTiles( numXLevels, EXRDecoder.height, EXRHeader.tiles.ySize, EXRHeader.tiles.roundingMode );
3989
+
3990
+ EXRDecoder.tileCount = numXTiles[ 0 ] * numYTiles[ 0 ];
3991
+
3992
+ for ( let l = 0; l < numXLevels; l ++ )
3993
+ for ( let y = 0; y < numYTiles[ l ]; y ++ )
3994
+ for ( let x = 0; x < numXTiles[ l ]; x ++ )
3995
+ parseInt64( dataView, offset ); // tileOffset
3996
+
3997
+ EXRDecoder.decode = parseTiles.bind( EXRDecoder );
3998
+
3999
+ } else {
4000
+
4001
+ EXRDecoder.blockWidth = EXRDecoder.width;
4002
+ const blockCount = Math.ceil( EXRDecoder.height / EXRDecoder.blockHeight );
4003
+
4004
+ for ( let i = 0; i < blockCount; i ++ )
4005
+ parseInt64( dataView, offset ); // scanlineOffset
4006
+
4007
+ EXRDecoder.decode = parseScanline.bind( EXRDecoder );
4008
+
4009
+ }
4010
+
4011
+ return EXRDecoder;
4012
+
4013
+ }
4014
+
4015
+ // start parsing file [START]
4016
+ const offset = { value: 0 };
4017
+ const bufferDataView = new DataView( buffer );
4018
+ const uInt8Array = new Uint8Array( buffer );
4019
+
4020
+ // get header information and validate format.
4021
+ const EXRHeader = parseHeader( bufferDataView, buffer, offset );
4022
+
4023
+ // get input compression information and prepare decoding.
4024
+ const EXRDecoder = setupDecoder( EXRHeader, bufferDataView, uInt8Array, offset, this.type, this.outputFormat );
4025
+
4026
+ // parse input data
4027
+ EXRDecoder.decode();
4028
+
4029
+ // output texture post-processing
4030
+ if ( EXRDecoder.shouldExpand ) {
4031
+
4032
+ const byteArray = EXRDecoder.byteArray;
4033
+
4034
+ if ( this.outputFormat == THREE.RGBAFormat ) {
4035
+
4036
+ for ( let i = 0; i < byteArray.length; i += 4 )
4037
+ byteArray[ i + 2 ] = ( byteArray[ i + 1 ] = byteArray[ i ] );
4038
+
4039
+ } else if ( this.outputFormat == THREE.RGFormat ) {
4040
+
4041
+ for ( let i = 0; i < byteArray.length; i += 2 )
4042
+ byteArray[ i + 1 ] = byteArray[ i ];
4043
+
4044
+ }
4045
+
4046
+ }
4047
+
4048
+ return {
4049
+ header: EXRHeader,
4050
+ width: EXRDecoder.width,
4051
+ height: EXRDecoder.height,
4052
+ data: EXRDecoder.byteArray,
4053
+ format: EXRDecoder.format,
4054
+ colorSpace: EXRDecoder.colorSpace,
4055
+ type: this.type,
4056
+ };
4057
+
4058
+ }
4059
+
4060
+ /**
4061
+ * Sets the texture type.
4062
+ *
4063
+ * @param {(HalfFloatType|FloatType)} value - The texture type to set.
4064
+ * @return {EXRLoader} A reference to this loader.
4065
+ */
4066
+ setDataType( value ) {
4067
+
4068
+ this.type = value;
4069
+ return this;
4070
+
4071
+ }
4072
+
4073
+ /**
4074
+ * Sets texture output format. Defaults to `RGBAFormat`.
4075
+ *
4076
+ * @param {(RGBAFormat|RGFormat|RedFormat)} value - Texture output format.
4077
+ * @return {EXRLoader} A reference to this loader.
4078
+ */
4079
+ setOutputFormat( value ) {
4080
+
4081
+ this.outputFormat = value;
4082
+ return this;
4083
+
4084
+ }
4085
+
4086
+ load( url, onLoad, onProgress, onError ) {
4087
+
4088
+ function onLoadCallback( texture, texData ) {
4089
+
4090
+ texture.colorSpace = texData.colorSpace;
4091
+ texture.minFilter = THREE.LinearFilter;
4092
+ texture.magFilter = THREE.LinearFilter;
4093
+ texture.generateMipmaps = false;
4094
+ texture.flipY = false;
4095
+
4096
+ if ( onLoad ) onLoad( texture, texData );
4097
+
4098
+ }
4099
+
4100
+ return super.load( url, onLoadCallback, onProgress, onError );
4101
+
4102
+ }
4103
+
4104
+ }
4105
+
4106
+ function loadEnvironment(renderer, url) {
4107
+ return new Promise((resolve, reject) => {
4108
+ const pmrem = new THREE__namespace.PMREMGenerator(renderer);
4109
+ pmrem.compileEquirectangularShader();
4110
+ const onLoad = (texture) => {
4111
+ const envMap = pmrem.fromEquirectangular(texture).texture;
4112
+ texture.dispose();
4113
+ pmrem.dispose();
4114
+ resolve({ envMap, dispose: () => envMap.dispose() });
4115
+ };
4116
+ const cleanUrl = url.split('?')[0].split('#')[0].toLowerCase();
4117
+ if (cleanUrl.endsWith('.exr')) {
4118
+ new EXRLoader().load(url, onLoad, undefined, reject);
4119
+ }
4120
+ else {
4121
+ new RGBELoader_js.RGBELoader().load(url, onLoad, undefined, reject);
869
4122
  }
870
- }
871
- if (vertexCount > HIGH_VERTEX_THRESHOLD) {
872
- warnings.push(`High vertex count (${vertexCount.toLocaleString()}) may impact performance`);
873
- }
874
- return {
875
- supported: supported.length,
876
- missing,
877
- warnings,
878
- modelStats: { vertexCount, textureCount, morphTargetCount },
879
- };
4123
+ });
880
4124
  }
881
- function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = '/models/avatar.vrm', backgroundColor = 0x1a1a2e, blendshapeMap, onModelLoad, maxModelSize = DEFAULT_MAX_MODEL_SIZE, }) {
4125
+
4126
+ const DEFAULT_MAX_MODEL_SIZE = 30 * 1024 * 1024; // 30MB
4127
+ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https://xwqtyabmavpacejuypyp.supabase.co/storage/v1/object/public/vrm-templates/5705015963733407866.vrm', backgroundColor = 0xffffff, blendshapeMap, expressionOverrides, onModelLoad, maxModelSize = DEFAULT_MAX_MODEL_SIZE, cameraPosition, cameraTarget, cameraFov, lightIntensity, idleAnimationUrl, animationSpeed = 1, animationWeight = 1, animationCrossfade = 0.5, postProcessing, environmentUrl, environmentIntensity, environmentBlur, environmentZoom, onEnvironmentLoad, features, orbitAngle, orbitElevation, avatarRotation, onOrbitChange, }) {
882
4128
  const containerRef = react.useRef(null);
883
4129
  const rendererRef = react.useRef(null);
884
4130
  const sceneRef = react.useRef(null);
885
4131
  const cameraRef = react.useRef(null);
886
4132
  const vrmRef = react.useRef(null);
4133
+ const lightsRef = react.useRef(null);
4134
+ const onModelLoadRef = react.useRef(onModelLoad);
4135
+ onModelLoadRef.current = onModelLoad;
4136
+ const animSpeedRef = react.useRef(animationSpeed);
4137
+ animSpeedRef.current = animationSpeed;
4138
+ const animWeightRef = react.useRef(animationWeight);
4139
+ animWeightRef.current = animationWeight;
4140
+ const animCrossfadeRef = react.useRef(animationCrossfade);
4141
+ animCrossfadeRef.current = animationCrossfade;
4142
+ const exprOverridesRef = react.useRef(expressionOverrides);
4143
+ exprOverridesRef.current = expressionOverrides;
4144
+ const featuresRef = react.useRef(features);
4145
+ featuresRef.current = features;
4146
+ const envZoomRef = react.useRef(environmentZoom);
4147
+ envZoomRef.current = environmentZoom;
4148
+ const onEnvLoadRef = react.useRef(onEnvironmentLoad);
4149
+ onEnvLoadRef.current = onEnvironmentLoad;
887
4150
  const [loading, setLoading] = react.useState(true);
888
4151
  const [error, setError] = react.useState(null);
889
4152
  const animationFrameRef = react.useRef(0);
890
4153
  const animationTimeRef = react.useRef(0);
4154
+ const mixerRef = react.useRef(null);
4155
+ const clipActionRef = react.useRef(null);
4156
+ const composerRef = react.useRef(null);
4157
+ const envMapRef = react.useRef(null);
4158
+ const bgSceneRef = react.useRef(new THREE__namespace.Scene());
4159
+ react.useRef(null);
4160
+ const fpsMonitorRef = react.useRef(new FpsMonitor());
4161
+ const orbitRef = react.useRef({ angle: 0, targetAngle: 0, elevation: 0, targetElevation: 0, zoomOffset: 0, dragging: false, lastX: 0, lastY: 0 });
4162
+ const orbitAnglePropRef = react.useRef(orbitAngle);
4163
+ orbitAnglePropRef.current = orbitAngle;
4164
+ const onOrbitChangeRef = react.useRef(onOrbitChange);
4165
+ onOrbitChangeRef.current = onOrbitChange;
4166
+ const baseCamRef = react.useRef({ distance: 1.2, height: 1.4, targetY: 1.3 });
4167
+ const idleRef = react.useRef({ blinkNext: 2 + Math.random() * 4, blinkPhase: 0, blinkStart: 0,
4168
+ happy: 0, happyTarget: 0, browInner: 0, browTarget: 0, cheek: 0, cheekTarget: 0, microNext: 3,
4169
+ eyeX: 0, eyeY: 0, eyeTargetX: 0, eyeTargetY: 0, eyeNext: 1 });
4170
+ const isA2FActiveRef = react.useRef(false);
4171
+ const idleMorphsRef = react.useRef([]);
4172
+ const springSettleFramesRef = react.useRef(0);
891
4173
  const applyBlendshapes = react.useCallback((vrm, shapes) => {
892
4174
  const arkitMap = {};
893
4175
  ARKIT_BLENDSHAPES.forEach((name, i) => {
894
4176
  arkitMap[name] = shapes[i] || 0;
895
4177
  });
896
- const mouthOpen = arkitMap.jawOpen || 0;
4178
+ const mouthOpen = arkitMap.jawOpen || 0, funnel = arkitMap.mouthFunnel || 0;
897
4179
  const smile = ((arkitMap.mouthSmileLeft || 0) + (arkitMap.mouthSmileRight || 0)) / 2;
898
- const funnel = arkitMap.mouthFunnel || 0;
899
- const blinkLeft = arkitMap.eyeBlinkLeft || 0;
900
- const blinkRight = arkitMap.eyeBlinkRight || 0;
4180
+ const blinkLeft = arkitMap.eyeBlinkLeft || 0, blinkRight = arkitMap.eyeBlinkRight || 0;
901
4181
  if (vrm.expressionManager) {
902
4182
  vrm.expressionManager.expressions.forEach(exp => {
903
4183
  vrm.expressionManager?.setValue(exp.expressionName, 0);
904
4184
  });
905
- const trySetExpression = (name, value) => {
4185
+ const trySet = (name, value) => {
906
4186
  try {
907
4187
  vrm.expressionManager?.setValue(name, Math.min(Math.max(value, 0), 1));
908
4188
  }
909
- catch {
910
- // Expression doesn't exist
911
- }
4189
+ catch { }
912
4190
  };
913
- trySetExpression('aa', mouthOpen * 1.5);
914
- trySetExpression('happy', smile * 2);
915
- trySetExpression('blink', (blinkLeft + blinkRight) / 2);
916
- trySetExpression('blinkLeft', blinkLeft);
917
- trySetExpression('blinkRight', blinkRight);
918
- trySetExpression('ou', funnel);
4191
+ trySet('aa', mouthOpen * 1.5);
4192
+ trySet('happy', smile * 2);
4193
+ trySet('blink', (blinkLeft + blinkRight) / 2);
4194
+ trySet('blinkLeft', blinkLeft);
4195
+ trySet('blinkRight', blinkRight);
4196
+ trySet('ou', funnel);
919
4197
  vrm.expressionManager.update();
920
4198
  }
921
4199
  vrm.scene.traverse((obj) => {
@@ -958,20 +4236,21 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = '/models
958
4236
  container.appendChild(renderer.domElement);
959
4237
  rendererRef.current = renderer;
960
4238
  const scene = new THREE__namespace.Scene();
961
- scene.background = new THREE__namespace.Color(backgroundColor);
4239
+ scene.background = backgroundColor === null ? null : new THREE__namespace.Color(backgroundColor ?? 0xffffff);
962
4240
  sceneRef.current = scene;
963
4241
  const camera = new THREE__namespace.PerspectiveCamera(30, width / height, 0.1, 20);
964
4242
  camera.position.set(0, 1.4, 1.2);
965
4243
  camera.lookAt(0, 1.3, 0);
966
4244
  cameraRef.current = camera;
967
- const ambientLight = new THREE__namespace.AmbientLight(0xffffff, 0.6);
4245
+ const ambientLight = new THREE__namespace.AmbientLight(0xffffff, 1.0);
968
4246
  scene.add(ambientLight);
969
- const directionalLight = new THREE__namespace.DirectionalLight(0xffffff, 0.8);
4247
+ const directionalLight = new THREE__namespace.DirectionalLight(0xffffff, 1.2);
970
4248
  directionalLight.position.set(1, 1, 1);
971
4249
  scene.add(directionalLight);
972
- const backLight = new THREE__namespace.DirectionalLight(0x4a9eff, 0.3);
4250
+ const backLight = new THREE__namespace.DirectionalLight(0x4a9eff, 0.4);
973
4251
  backLight.position.set(-1, 1, -1);
974
4252
  scene.add(backLight);
4253
+ lightsRef.current = { ambient: ambientLight, directional: directionalLight, back: backLight };
975
4254
  let cancelled = false;
976
4255
  // Size guard: fire HEAD check in parallel — if model is too large, cancel before render
977
4256
  if (maxModelSize > 0) {
@@ -986,7 +4265,7 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = '/models
986
4265
  const errMsg = `Model too large (${sizeMB}MB, limit ${limitMB}MB)`;
987
4266
  setError(errMsg);
988
4267
  setLoading(false);
989
- onModelLoad?.({
4268
+ onModelLoadRef.current?.({
990
4269
  supported: 0, missing: [...ARKIT_BLENDSHAPES], warnings: [errMsg],
991
4270
  modelStats: { vertexCount: 0, textureCount: 0, morphTargetCount: 0 },
992
4271
  });
@@ -1002,12 +4281,44 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = '/models
1002
4281
  if (vrm) {
1003
4282
  scene.add(vrm.scene);
1004
4283
  vrmRef.current = vrm;
4284
+ const mc = [];
4285
+ vrm.scene.traverse((o) => {
4286
+ const mesh = o;
4287
+ if (!mesh.isMesh)
4288
+ return;
4289
+ const d = mesh.morphTargetDictionary, inf = mesh.morphTargetInfluences;
4290
+ if (!d || !inf)
4291
+ return;
4292
+ const e = { inf };
4293
+ if (d['browInnerUp'] !== undefined)
4294
+ e.brow = d['browInnerUp'];
4295
+ if (d['cheekSquintLeft'] !== undefined)
4296
+ e.cheekL = d['cheekSquintLeft'];
4297
+ if (d['cheekSquintRight'] !== undefined)
4298
+ e.cheekR = d['cheekSquintRight'];
4299
+ if (e.brow !== undefined || e.cheekL !== undefined)
4300
+ mc.push(e);
4301
+ });
4302
+ idleMorphsRef.current = mc;
4303
+ // Apply idle pose immediately so the model never renders in T-pose
4304
+ const humanoid = vrm.humanoid;
4305
+ if (humanoid) {
4306
+ const b = (n) => humanoid.getNormalizedBoneNode(n);
4307
+ const lArm = b(threeVrm.VRMHumanBoneName.LeftUpperArm), rArm = b(threeVrm.VRMHumanBoneName.RightUpperArm);
4308
+ if (lArm)
4309
+ lArm.rotation.z = -1;
4310
+ if (rArm)
4311
+ rArm.rotation.z = 1.0;
4312
+ }
4313
+ vrm.update(0);
4314
+ vrm.springBoneManager?.reset();
4315
+ springSettleFramesRef.current = 30;
1005
4316
  setLoading(false);
1006
4317
  const report = buildCompatibilityReport(vrm);
1007
4318
  if (report.warnings.length > 0) {
1008
4319
  console.warn('[VRM] Compatibility warnings:', report.warnings);
1009
4320
  }
1010
- onModelLoad?.(report);
4321
+ onModelLoadRef.current?.(report);
1011
4322
  }
1012
4323
  }, () => { }, (err) => {
1013
4324
  if (cancelled)
@@ -1028,72 +4339,460 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = '/models
1028
4339
  animationTimeRef.current += delta;
1029
4340
  if (vrmRef.current) {
1030
4341
  vrmRef.current.update(delta);
4342
+ if (featuresRef.current?.springBones === false || springSettleFramesRef.current > 0) {
4343
+ vrmRef.current.springBoneManager?.reset();
4344
+ if (springSettleFramesRef.current > 0)
4345
+ springSettleFramesRef.current--;
4346
+ }
4347
+ if (mixerRef.current)
4348
+ mixerRef.current.update(delta);
1031
4349
  const humanoid = vrmRef.current.humanoid;
1032
- if (humanoid) {
1033
- const time = animationTimeRef.current;
1034
- const breathCycle = time * 1.2;
1035
- const breathIntensity = 0.03;
1036
- const idleSway = time * 0.5;
1037
- const swayIntensity = 0.02;
1038
- const headBob = time * 0.7;
1039
- const headBobIntensity = 0.015;
1040
- const spineBone = humanoid.getNormalizedBoneNode(threeVrm.VRMHumanBoneName.Spine);
1041
- if (spineBone) {
1042
- spineBone.rotation.x = Math.sin(breathCycle) * breathIntensity;
1043
- spineBone.rotation.z = Math.sin(idleSway) * swayIntensity * 0.3;
4350
+ if (featuresRef.current?.idleAnimation !== false && humanoid && !clipActionRef.current) {
4351
+ const t = animationTimeRef.current, br = t * 1.2, sw = t * 0.5, hb = t * 0.7;
4352
+ const b = (n) => humanoid.getNormalizedBoneNode(n);
4353
+ const spine = b(threeVrm.VRMHumanBoneName.Spine);
4354
+ if (spine) {
4355
+ spine.rotation.x = Math.sin(br) * 0.03;
4356
+ spine.rotation.z = Math.sin(sw) * 0.006;
4357
+ }
4358
+ const chest = b(threeVrm.VRMHumanBoneName.Chest);
4359
+ if (chest) {
4360
+ chest.rotation.x = Math.sin(br + 0.3) * 0.015;
4361
+ chest.rotation.z = Math.sin(sw + 0.5) * 0.004;
1044
4362
  }
1045
- const chestBone = humanoid.getNormalizedBoneNode(threeVrm.VRMHumanBoneName.Chest);
1046
- if (chestBone) {
1047
- chestBone.rotation.x = Math.sin(breathCycle + 0.3) * breathIntensity * 0.5;
1048
- chestBone.rotation.z = Math.sin(idleSway + 0.5) * swayIntensity * 0.2;
4363
+ const neck = b(threeVrm.VRMHumanBoneName.Neck);
4364
+ if (neck) {
4365
+ neck.rotation.x = Math.sin(hb) * 0.015;
4366
+ neck.rotation.y = Math.sin(sw * 0.7) * 0.01;
1049
4367
  }
1050
- const neckBone = humanoid.getNormalizedBoneNode(threeVrm.VRMHumanBoneName.Neck);
1051
- if (neckBone) {
1052
- neckBone.rotation.x = Math.sin(headBob) * headBobIntensity;
1053
- neckBone.rotation.y = Math.sin(idleSway * 0.7) * swayIntensity * 0.5;
4368
+ const head = b(threeVrm.VRMHumanBoneName.Head);
4369
+ if (head) {
4370
+ head.rotation.x = Math.sin(hb + 0.5) * 0.006;
4371
+ head.rotation.y = Math.sin(sw * 0.6 + 0.8) * 0.006;
1054
4372
  }
1055
- const headBone = humanoid.getNormalizedBoneNode(threeVrm.VRMHumanBoneName.Head);
1056
- if (headBone) {
1057
- headBone.rotation.x = Math.sin(headBob + 0.5) * headBobIntensity * 0.4;
1058
- headBone.rotation.y = Math.sin(idleSway * 0.6 + 0.8) * swayIntensity * 0.3;
4373
+ const lSh = b(threeVrm.VRMHumanBoneName.LeftShoulder), rSh = b(threeVrm.VRMHumanBoneName.RightShoulder);
4374
+ if (lSh)
4375
+ lSh.rotation.z = Math.sin(br) * 0.006;
4376
+ if (rSh)
4377
+ rSh.rotation.z = -Math.sin(br) * 0.006;
4378
+ const lArm = b(threeVrm.VRMHumanBoneName.LeftUpperArm), rArm = b(threeVrm.VRMHumanBoneName.RightUpperArm);
4379
+ if (lArm)
4380
+ lArm.rotation.z = -1 + Math.sin(sw * 0.4) * 0.02;
4381
+ if (rArm)
4382
+ rArm.rotation.z = 1.0 + Math.sin(sw * 0.4 + 0.5) * 0.02;
4383
+ }
4384
+ if (featuresRef.current?.microExpressions !== false && vrmRef.current.expressionManager && !isA2FActiveRef.current &&
4385
+ !Object.keys(exprOverridesRef.current ?? {}).length) {
4386
+ const idle = idleRef.current, t = animationTimeRef.current;
4387
+ let bv = 0;
4388
+ if (idle.blinkPhase === 0 && t >= idle.blinkNext) {
4389
+ idle.blinkPhase = 1;
4390
+ idle.blinkStart = t;
4391
+ }
4392
+ if (idle.blinkPhase === 1) {
4393
+ bv = Math.min((t - idle.blinkStart) / 0.15, 1);
4394
+ if (bv >= 1) {
4395
+ idle.blinkPhase = 2;
4396
+ idle.blinkStart = t;
4397
+ }
4398
+ }
4399
+ else if (idle.blinkPhase === 2) {
4400
+ bv = 1 - Math.min((t - idle.blinkStart) / 0.15, 1);
4401
+ if (bv <= 0) {
4402
+ idle.blinkPhase = 0;
4403
+ idle.blinkNext = t + 2 + Math.random() * 4;
4404
+ }
4405
+ }
4406
+ if (t >= idle.microNext) {
4407
+ idle.happyTarget = Math.random() * 0.1;
4408
+ idle.browTarget = Math.random() * 0.08;
4409
+ idle.cheekTarget = Math.random() * 0.05;
4410
+ idle.microNext = t + 3 + Math.random() * 5;
1059
4411
  }
1060
- const leftShoulder = humanoid.getNormalizedBoneNode(threeVrm.VRMHumanBoneName.LeftShoulder);
1061
- const rightShoulder = humanoid.getNormalizedBoneNode(threeVrm.VRMHumanBoneName.RightShoulder);
1062
- if (leftShoulder) {
1063
- leftShoulder.rotation.z = Math.sin(breathCycle) * breathIntensity * 0.2;
4412
+ idle.happy += (idle.happyTarget - idle.happy) * 0.02;
4413
+ idle.browInner += (idle.browTarget - idle.browInner) * 0.02;
4414
+ idle.cheek += (idle.cheekTarget - idle.cheek) * 0.02;
4415
+ if (t >= idle.eyeNext) {
4416
+ idle.eyeTargetX = (Math.random() - 0.5) * 0.06;
4417
+ idle.eyeTargetY = (Math.random() - 0.5) * 0.04;
4418
+ idle.eyeNext = t + 1.5 + Math.random() * 3;
4419
+ }
4420
+ idle.eyeX += (idle.eyeTargetX - idle.eyeX) * 0.03;
4421
+ idle.eyeY += (idle.eyeTargetY - idle.eyeY) * 0.03;
4422
+ const em = vrmRef.current.expressionManager;
4423
+ try {
4424
+ em.setValue('blink', Math.max(bv, 0));
1064
4425
  }
1065
- if (rightShoulder) {
1066
- rightShoulder.rotation.z = -Math.sin(breathCycle) * breathIntensity * 0.2;
4426
+ catch { }
4427
+ try {
4428
+ em.setValue('happy', Math.max(idle.happy, 0));
1067
4429
  }
1068
- const leftUpperArm = humanoid.getNormalizedBoneNode(threeVrm.VRMHumanBoneName.LeftUpperArm);
1069
- const rightUpperArm = humanoid.getNormalizedBoneNode(threeVrm.VRMHumanBoneName.RightUpperArm);
1070
- if (leftUpperArm) {
1071
- leftUpperArm.rotation.z = -1 + Math.sin(idleSway * 0.4) * 0.02;
4430
+ catch { }
4431
+ em.update();
4432
+ for (const m of idleMorphsRef.current) {
4433
+ if (m.brow !== undefined)
4434
+ m.inf[m.brow] = idle.browInner;
4435
+ if (m.cheekL !== undefined)
4436
+ m.inf[m.cheekL] = idle.cheek;
4437
+ if (m.cheekR !== undefined)
4438
+ m.inf[m.cheekR] = idle.cheek;
1072
4439
  }
1073
- if (rightUpperArm) {
1074
- rightUpperArm.rotation.z = 1.0 + Math.sin(idleSway * 0.4 + 0.5) * 0.02;
4440
+ if (humanoid) {
4441
+ for (const bn of [threeVrm.VRMHumanBoneName.LeftEye, threeVrm.VRMHumanBoneName.RightEye]) {
4442
+ const eye = humanoid.getNormalizedBoneNode(bn);
4443
+ if (eye) {
4444
+ eye.rotation.x = idle.eyeY;
4445
+ eye.rotation.y = idle.eyeX;
4446
+ }
4447
+ }
1075
4448
  }
1076
4449
  }
1077
4450
  }
1078
- renderer.render(scene, camera);
4451
+ // Smooth lerp for spherical orbit (azimuth + elevation)
4452
+ const orbit = orbitRef.current;
4453
+ const elevDiff = orbit.targetElevation - orbit.elevation;
4454
+ const angleDiff = orbit.targetAngle - orbit.angle;
4455
+ if (Math.abs(elevDiff) > 0.0005 || Math.abs(angleDiff) > 0.0005) {
4456
+ orbit.elevation += elevDiff * 0.1;
4457
+ orbit.angle += angleDiff * 0.1;
4458
+ const base = baseCamRef.current;
4459
+ const d = Math.max(0.3, base.distance + orbit.zoomOffset);
4460
+ const cosEl = Math.cos(orbit.elevation);
4461
+ const sinEl = Math.sin(orbit.elevation);
4462
+ camera.position.set(Math.sin(orbit.angle) * cosEl * d, base.height + sinEl * d, Math.cos(orbit.angle) * cosEl * d);
4463
+ camera.lookAt(0, base.targetY, 0);
4464
+ }
4465
+ const pipeline = composerRef.current;
4466
+ const ez = envZoomRef.current;
4467
+ const hasBgZoom = ez && ez !== 1 && scene.background && envMapRef.current;
4468
+ if (hasBgZoom && !pipeline) {
4469
+ const baseFov = camera.fov;
4470
+ const bgScene = bgSceneRef.current;
4471
+ bgScene.backgroundBlurriness = scene.backgroundBlurriness;
4472
+ bgScene.backgroundIntensity = scene.backgroundIntensity ?? 1;
4473
+ camera.fov = baseFov / ez;
4474
+ camera.updateProjectionMatrix();
4475
+ renderer.render(bgScene, camera);
4476
+ camera.fov = baseFov;
4477
+ camera.updateProjectionMatrix();
4478
+ const savedBg = scene.background;
4479
+ scene.background = null;
4480
+ renderer.autoClear = false;
4481
+ renderer.clearDepth();
4482
+ renderer.render(scene, camera);
4483
+ renderer.autoClear = true;
4484
+ scene.background = savedBg;
4485
+ }
4486
+ else if (pipeline && !fpsMonitorRef.current.disabled) {
4487
+ pipeline.composer.render();
4488
+ fpsMonitorRef.current.tick(performance.now());
4489
+ }
4490
+ else {
4491
+ renderer.render(scene, camera);
4492
+ }
1079
4493
  };
1080
4494
  animate();
1081
4495
  return () => {
1082
4496
  cancelled = true;
1083
4497
  cancelAnimationFrame(animationFrameRef.current);
4498
+ clipActionRef.current = null;
4499
+ mixerRef.current = null;
4500
+ composerRef.current?.dispose();
4501
+ composerRef.current = null;
4502
+ envMapRef.current?.dispose();
4503
+ envMapRef.current = null;
1084
4504
  renderer.dispose();
1085
4505
  if (container && renderer.domElement) {
1086
4506
  container.removeChild(renderer.domElement);
1087
4507
  }
1088
4508
  };
1089
- }, [width, height, modelUrl, backgroundColor, maxModelSize, onModelLoad]);
4509
+ }, [width, height, modelUrl, maxModelSize]);
4510
+ react.useEffect(() => {
4511
+ composerRef.current?.dispose();
4512
+ composerRef.current = null;
4513
+ fpsMonitorRef.current.reset();
4514
+ const renderer = rendererRef.current, scene = sceneRef.current, camera = cameraRef.current;
4515
+ const pp = features?.postProcessing ?? postProcessing;
4516
+ if (!renderer || !scene || !camera || !pp)
4517
+ return;
4518
+ const hasAnyEffect = (pp.bloom && pp.bloom > 0) || (pp.ao && pp.ao > 0) || pp.dof;
4519
+ if (!hasAnyEffect)
4520
+ return;
4521
+ composerRef.current = createPostProcessing(renderer, scene, camera, pp, width, height);
4522
+ return () => { composerRef.current?.dispose(); composerRef.current = null; };
4523
+ }, [postProcessing, features, width, height]);
4524
+ // Load/unload .vrma animation clip — crossfade between clips
4525
+ react.useEffect(() => {
4526
+ const vrm = vrmRef.current;
4527
+ const fade = animCrossfadeRef.current;
4528
+ if (!idleAnimationUrl) {
4529
+ const old = clipActionRef.current;
4530
+ if (old) {
4531
+ old.fadeOut(fade);
4532
+ setTimeout(() => {
4533
+ old.stop();
4534
+ if (clipActionRef.current === old)
4535
+ clipActionRef.current = null;
4536
+ if (mixerRef.current && !clipActionRef.current) {
4537
+ mixerRef.current.stopAllAction();
4538
+ mixerRef.current = null;
4539
+ }
4540
+ }, fade * 1000);
4541
+ }
4542
+ return;
4543
+ }
4544
+ if (!vrm)
4545
+ return;
4546
+ let cancelled = false;
4547
+ const loader = new GLTFLoader_js.GLTFLoader();
4548
+ loader.register((parser) => new threeVrmAnimation.VRMAnimationLoaderPlugin(parser));
4549
+ loader.load(idleAnimationUrl, (gltf) => {
4550
+ if (cancelled || !vrmRef.current)
4551
+ return;
4552
+ const animations = gltf.userData.vrmAnimations;
4553
+ if (!animations || animations.length === 0)
4554
+ return;
4555
+ const mixer = mixerRef.current ?? new THREE__namespace.AnimationMixer(vrmRef.current.scene);
4556
+ mixerRef.current = mixer;
4557
+ const clip = threeVrmAnimation.createVRMAnimationClip(animations[0], vrmRef.current);
4558
+ const newAction = mixer.clipAction(clip);
4559
+ newAction.setLoop(THREE__namespace.LoopPingPong, Infinity);
4560
+ newAction.timeScale = animSpeedRef.current;
4561
+ newAction.setEffectiveWeight(animWeightRef.current);
4562
+ const oldAction = clipActionRef.current;
4563
+ const cf = animCrossfadeRef.current;
4564
+ if (oldAction) {
4565
+ newAction.reset().play();
4566
+ oldAction.crossFadeTo(newAction, cf, true);
4567
+ setTimeout(() => { oldAction.stop(); mixer.uncacheAction(oldAction.getClip()); }, cf * 1000);
4568
+ }
4569
+ else {
4570
+ newAction.reset().fadeIn(cf).play();
4571
+ }
4572
+ clipActionRef.current = newAction;
4573
+ }, () => { }, (err) => {
4574
+ if (cancelled)
4575
+ return;
4576
+ console.warn('[VRM] Failed to load animation clip:', err);
4577
+ });
4578
+ return () => { cancelled = true; };
4579
+ }, [idleAnimationUrl, loading]);
4580
+ // Update animation speed/weight in real time
4581
+ react.useEffect(() => {
4582
+ if (clipActionRef.current)
4583
+ clipActionRef.current.timeScale = animationSpeed;
4584
+ }, [animationSpeed]);
4585
+ react.useEffect(() => {
4586
+ if (clipActionRef.current)
4587
+ clipActionRef.current.setEffectiveWeight(animationWeight);
4588
+ }, [animationWeight]);
4589
+ // Update background in-place (skip when HDRI active)
4590
+ react.useEffect(() => {
4591
+ if (sceneRef.current && !environmentUrl) {
4592
+ sceneRef.current.background = backgroundColor === null ? null : new THREE__namespace.Color(backgroundColor ?? 0xffffff);
4593
+ }
4594
+ }, [backgroundColor, environmentUrl]);
4595
+ // HDRI environment map loading — keep old envMap visible until new one is ready
4596
+ react.useEffect(() => {
4597
+ const scene = sceneRef.current, renderer = rendererRef.current;
4598
+ if (!scene || !renderer || !environmentUrl) {
4599
+ envMapRef.current?.dispose();
4600
+ envMapRef.current = null;
4601
+ if (scene) {
4602
+ scene.environment = null;
4603
+ scene.background = null;
4604
+ scene.backgroundBlurriness = 0;
4605
+ scene.environmentIntensity = 1;
4606
+ }
4607
+ return;
4608
+ }
4609
+ let cancelled = false;
4610
+ const prev = envMapRef.current;
4611
+ loadEnvironment(renderer, environmentUrl).then(r => {
4612
+ if (cancelled) {
4613
+ r.dispose();
4614
+ return;
4615
+ }
4616
+ prev?.dispose();
4617
+ scene.environment = r.envMap;
4618
+ scene.background = r.envMap;
4619
+ scene.backgroundBlurriness = environmentBlur ?? 0;
4620
+ scene.environmentIntensity = environmentIntensity ?? 1;
4621
+ scene.backgroundIntensity = environmentIntensity ?? 1;
4622
+ bgSceneRef.current.background = r.envMap;
4623
+ envMapRef.current = { dispose: r.dispose, envMap: r.envMap };
4624
+ onEnvLoadRef.current?.();
4625
+ }).catch(e => console.warn('[VRM] HDRI load failed:', e));
4626
+ return () => { cancelled = true; };
4627
+ }, [environmentUrl]);
4628
+ // Update HDRI intensity/blur without reloading
4629
+ react.useEffect(() => {
4630
+ if (!sceneRef.current || !envMapRef.current)
4631
+ return;
4632
+ sceneRef.current.backgroundBlurriness = environmentBlur ?? 0;
4633
+ sceneRef.current.environmentIntensity = environmentIntensity ?? 1;
4634
+ sceneRef.current.backgroundIntensity = environmentIntensity ?? 1;
4635
+ }, [environmentIntensity, environmentBlur]);
4636
+ // Update camera base values and apply orbit
4637
+ react.useEffect(() => {
4638
+ const pos = cameraPosition ?? [0, 1.4, 1.2];
4639
+ const target = cameraTarget ?? [0, 1.3, 0];
4640
+ baseCamRef.current = { distance: pos[2], height: pos[1], targetY: target[1] };
4641
+ if (orbitAnglePropRef.current === undefined) {
4642
+ orbitRef.current.angle = 0;
4643
+ orbitRef.current.targetAngle = 0;
4644
+ }
4645
+ orbitRef.current.zoomOffset = 0;
4646
+ if (orbitElevation === undefined) {
4647
+ orbitRef.current.elevation = 0;
4648
+ orbitRef.current.targetElevation = 0;
4649
+ }
4650
+ const camera = cameraRef.current;
4651
+ if (!camera)
4652
+ return;
4653
+ const d = baseCamRef.current.distance;
4654
+ camera.position.set(0, baseCamRef.current.height, d);
4655
+ camera.lookAt(0, baseCamRef.current.targetY, 0);
4656
+ if (cameraFov !== undefined && camera.fov !== cameraFov) {
4657
+ camera.fov = cameraFov;
4658
+ camera.updateProjectionMatrix();
4659
+ }
4660
+ }, [cameraPosition, cameraTarget, cameraFov]);
4661
+ // Prop-driven orbit angle
4662
+ react.useEffect(() => {
4663
+ if (orbitAngle !== undefined) {
4664
+ orbitRef.current.targetAngle = orbitAngle;
4665
+ }
4666
+ }, [orbitAngle]);
4667
+ // Prop-driven orbit elevation
4668
+ react.useEffect(() => {
4669
+ if (orbitElevation !== undefined) {
4670
+ orbitRef.current.targetElevation = orbitElevation;
4671
+ }
4672
+ }, [orbitElevation]);
4673
+ // Prop-driven avatar rotation
4674
+ react.useEffect(() => {
4675
+ if (avatarRotation !== undefined && vrmRef.current) {
4676
+ vrmRef.current.scene.rotation.y = avatarRotation;
4677
+ }
4678
+ }, [avatarRotation, loading]);
4679
+ // Mouse orbit (horizontal only) + scroll zoom
4680
+ react.useEffect(() => {
4681
+ const container = containerRef.current;
4682
+ if (!container)
4683
+ return;
4684
+ const applyCameraOrbit = () => {
4685
+ const camera = cameraRef.current;
4686
+ if (!camera)
4687
+ return;
4688
+ const base = baseCamRef.current;
4689
+ const orbit = orbitRef.current;
4690
+ const d = Math.max(0.3, base.distance + orbit.zoomOffset);
4691
+ const cosEl = Math.cos(orbit.elevation);
4692
+ const sinEl = Math.sin(orbit.elevation);
4693
+ camera.position.set(Math.sin(orbit.angle) * cosEl * d, base.height + sinEl * d, Math.cos(orbit.angle) * cosEl * d);
4694
+ camera.lookAt(0, base.targetY, 0);
4695
+ };
4696
+ const onWheel = (e) => {
4697
+ e.preventDefault();
4698
+ orbitRef.current.zoomOffset += e.deltaY * 0.002;
4699
+ applyCameraOrbit();
4700
+ };
4701
+ const onMouseDown = (e) => {
4702
+ orbitRef.current.dragging = true;
4703
+ orbitRef.current.lastX = e.clientX;
4704
+ orbitRef.current.lastY = e.clientY;
4705
+ };
4706
+ const onMouseMove = (e) => {
4707
+ if (!orbitRef.current.dragging)
4708
+ return;
4709
+ const dx = e.clientX - orbitRef.current.lastX;
4710
+ const dy = e.clientY - orbitRef.current.lastY;
4711
+ orbitRef.current.lastX = e.clientX;
4712
+ orbitRef.current.lastY = e.clientY;
4713
+ orbitRef.current.angle -= dx * 0.005;
4714
+ orbitRef.current.targetAngle = orbitRef.current.angle;
4715
+ orbitRef.current.elevation = Math.max(-Math.PI / 3, Math.min(Math.PI / 3, orbitRef.current.elevation + dy * 0.005));
4716
+ orbitRef.current.targetElevation = orbitRef.current.elevation;
4717
+ applyCameraOrbit();
4718
+ onOrbitChangeRef.current?.(orbitRef.current.angle, orbitRef.current.elevation);
4719
+ };
4720
+ const onMouseUp = () => {
4721
+ orbitRef.current.dragging = false;
4722
+ };
4723
+ const onKeyDown = (e) => {
4724
+ const o = orbitRef.current;
4725
+ if (e.key === 'ArrowUp') {
4726
+ e.preventDefault();
4727
+ o.targetElevation = Math.min(o.targetElevation + 0.1, Math.PI / 3);
4728
+ }
4729
+ else if (e.key === 'ArrowDown') {
4730
+ e.preventDefault();
4731
+ o.targetElevation = Math.max(o.targetElevation - 0.1, -Math.PI / 3);
4732
+ }
4733
+ else if (e.key === 'ArrowLeft') {
4734
+ e.preventDefault();
4735
+ o.targetAngle += 0.15;
4736
+ }
4737
+ else if (e.key === 'ArrowRight') {
4738
+ e.preventDefault();
4739
+ o.targetAngle -= 0.15;
4740
+ }
4741
+ onOrbitChangeRef.current?.(o.targetAngle, o.targetElevation);
4742
+ };
4743
+ container.addEventListener('wheel', onWheel, { passive: false });
4744
+ container.addEventListener('mousedown', onMouseDown);
4745
+ window.addEventListener('mousemove', onMouseMove);
4746
+ window.addEventListener('mouseup', onMouseUp);
4747
+ window.addEventListener('keydown', onKeyDown);
4748
+ return () => {
4749
+ container.removeEventListener('wheel', onWheel);
4750
+ container.removeEventListener('mousedown', onMouseDown);
4751
+ window.removeEventListener('mousemove', onMouseMove);
4752
+ window.removeEventListener('mouseup', onMouseUp);
4753
+ window.removeEventListener('keydown', onKeyDown);
4754
+ };
4755
+ }, []);
4756
+ // Update lighting in-place
4757
+ react.useEffect(() => {
4758
+ if (!lightsRef.current)
4759
+ return;
4760
+ const intensity = lightIntensity ?? 1;
4761
+ lightsRef.current.ambient.intensity = 1.0 * intensity;
4762
+ lightsRef.current.directional.intensity = 1.2 * intensity;
4763
+ lightsRef.current.back.intensity = 0.4 * intensity;
4764
+ }, [lightIntensity]);
1090
4765
  react.useEffect(() => {
4766
+ isA2FActiveRef.current = blendshapes.some(v => v !== 0);
1091
4767
  if (vrmRef.current && blendshapes.length > 0) {
1092
4768
  applyBlendshapes(vrmRef.current, blendshapes);
1093
4769
  }
1094
4770
  }, [blendshapes, applyBlendshapes]);
4771
+ react.useEffect(() => {
4772
+ const vrm = vrmRef.current;
4773
+ if (!vrm?.expressionManager)
4774
+ return;
4775
+ const hasLiveData = blendshapes.some(v => v !== 0);
4776
+ if (hasLiveData)
4777
+ return;
4778
+ if (features?.expressionPresets === false)
4779
+ return;
4780
+ vrm.expressionManager.expressions.forEach(exp => {
4781
+ vrm.expressionManager.setValue(exp.expressionName, 0);
4782
+ });
4783
+ if (expressionOverrides) {
4784
+ for (const [name, value] of Object.entries(expressionOverrides)) {
4785
+ try {
4786
+ vrm.expressionManager.setValue(name, Math.min(Math.max(value, 0), 1));
4787
+ }
4788
+ catch { /* expression doesn't exist on this model */ }
4789
+ }
4790
+ }
4791
+ vrm.expressionManager.update();
4792
+ }, [expressionOverrides, blendshapes]);
1095
4793
  return (jsxRuntime.jsxs("div", { className: "relative", style: { width, height }, children: [jsxRuntime.jsx("div", { ref: containerRef, className: "rounded-lg overflow-hidden" }), loading && (jsxRuntime.jsx("div", { className: "absolute inset-0 flex items-center justify-center bg-gray-800 rounded-lg", children: jsxRuntime.jsx("div", { className: "text-white text-sm", children: "Loading VRM avatar..." }) })), error && (jsxRuntime.jsx("div", { className: "absolute inset-0 flex items-center justify-center bg-red-900/50 rounded-lg", children: jsxRuntime.jsx("div", { className: "text-white text-sm", children: error }) }))] }));
1096
4794
  }
1097
4795
 
1098
4796
  exports.VRMAvatar = VRMAvatar;
4797
+ exports.VROID_BLENDSHAPE_MAP = VROID_BLENDSHAPE_MAP;
1099
4798
  exports.useAStackCSR = useAStackCSR;