@crysound/crychart 1.0.5 → 1.0.7

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/crychart.js CHANGED
@@ -16209,6 +16209,294 @@ var LineStripRenderer = class {
16209
16209
  }
16210
16210
  };
16211
16211
 
16212
+ // src/shared-webgl-context.ts
16213
+ var cores = /* @__PURE__ */ new WeakMap();
16214
+ var claimedCanvases = /* @__PURE__ */ new WeakMap();
16215
+ function sharedContextCore(context) {
16216
+ const core = cores.get(context);
16217
+ if (!core) throw new TypeError("Expected a valid SharedWebGLContext");
16218
+ return core;
16219
+ }
16220
+ function resetSharedBaseline(gl, width, height, maxVertexAttribs) {
16221
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
16222
+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
16223
+ gl.drawBuffers([gl.BACK]);
16224
+ gl.readBuffer(gl.BACK);
16225
+ gl.bindVertexArray(null);
16226
+ for (let i = 0; i < maxVertexAttribs; i++) {
16227
+ gl.disableVertexAttribArray(i);
16228
+ gl.vertexAttribDivisor(i, 0);
16229
+ }
16230
+ gl.bindBuffer(gl.ARRAY_BUFFER, null);
16231
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
16232
+ gl.bindBuffer(gl.PIXEL_UNPACK_BUFFER, null);
16233
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
16234
+ gl.bindBuffer(gl.COPY_READ_BUFFER, null);
16235
+ gl.bindBuffer(gl.COPY_WRITE_BUFFER, null);
16236
+ gl.bindBuffer(gl.UNIFORM_BUFFER, null);
16237
+ gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);
16238
+ for (let unit = 2; unit >= 0; unit--) {
16239
+ gl.activeTexture(gl.TEXTURE0 + unit);
16240
+ gl.bindTexture(gl.TEXTURE_2D, null);
16241
+ gl.bindSampler(unit, null);
16242
+ }
16243
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
16244
+ gl.pixelStorei(gl.PACK_ALIGNMENT, 4);
16245
+ gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0);
16246
+ gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0);
16247
+ gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
16248
+ gl.pixelStorei(gl.UNPACK_IMAGE_HEIGHT, 0);
16249
+ gl.pixelStorei(gl.UNPACK_SKIP_IMAGES, 0);
16250
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
16251
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
16252
+ gl.useProgram(null);
16253
+ gl.colorMask(true, true, true, true);
16254
+ gl.depthMask(true);
16255
+ gl.stencilMask(255);
16256
+ for (const capability of [
16257
+ gl.DEPTH_TEST,
16258
+ gl.STENCIL_TEST,
16259
+ gl.CULL_FACE,
16260
+ gl.RASTERIZER_DISCARD,
16261
+ gl.SAMPLE_ALPHA_TO_COVERAGE,
16262
+ gl.SAMPLE_COVERAGE,
16263
+ gl.SCISSOR_TEST,
16264
+ gl.POLYGON_OFFSET_FILL
16265
+ ]) {
16266
+ gl.disable(capability);
16267
+ }
16268
+ gl.enable(gl.BLEND);
16269
+ gl.enable(gl.DITHER);
16270
+ gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
16271
+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
16272
+ gl.viewport(0, 0, width, height);
16273
+ gl.scissor(0, 0, width, height);
16274
+ }
16275
+ var SharedContextCore = class {
16276
+ canvas;
16277
+ cullOffscreen;
16278
+ antialias;
16279
+ ownsCanvas;
16280
+ clients = /* @__PURE__ */ new Set();
16281
+ observer;
16282
+ observedRoots = /* @__PURE__ */ new Map();
16283
+ offscreenClients = /* @__PURE__ */ new Set();
16284
+ gl = null;
16285
+ attempted = false;
16286
+ disposed = false;
16287
+ maxVertexAttribs = 0;
16288
+ pendingPresent;
16289
+ chartDraws = 0;
16290
+ blits = 0;
16291
+ backingResizes = 0;
16292
+ contextLosses = 0;
16293
+ contextRestores = 0;
16294
+ onLost = (event) => {
16295
+ event.preventDefault();
16296
+ this.contextLosses++;
16297
+ };
16298
+ onRestore = () => {
16299
+ this.contextRestores++;
16300
+ };
16301
+ constructor(options) {
16302
+ if (options !== void 0 && (typeof options !== "object" || options === null)) {
16303
+ throw new TypeError("SharedWebGLContext options must be an object");
16304
+ }
16305
+ if (options?.canvas !== void 0) {
16306
+ if (typeof options.canvas !== "object" || options.canvas === null || typeof options.canvas.getContext !== "function") {
16307
+ throw new TypeError("SharedWebGLContext canvas must provide getContext");
16308
+ }
16309
+ if (claimedCanvases.has(options.canvas)) {
16310
+ throw new Error("Canvas is already bound to an active SharedWebGLContext");
16311
+ }
16312
+ this.canvas = options.canvas;
16313
+ this.ownsCanvas = false;
16314
+ claimedCanvases.set(options.canvas, this);
16315
+ } else if (typeof document !== "undefined") {
16316
+ this.canvas = document.createElement("canvas");
16317
+ this.ownsCanvas = true;
16318
+ } else {
16319
+ this.canvas = void 0;
16320
+ this.ownsCanvas = false;
16321
+ }
16322
+ this.antialias = options?.antialias === true;
16323
+ this.cullOffscreen = options?.cullOffscreen !== false;
16324
+ }
16325
+ acquire() {
16326
+ if (this.disposed) return null;
16327
+ if (this.attempted) return this.gl;
16328
+ this.attempted = true;
16329
+ if (!this.canvas) return null;
16330
+ let gl = null;
16331
+ try {
16332
+ gl = this.canvas.getContext("webgl2", {
16333
+ alpha: true,
16334
+ antialias: this.antialias,
16335
+ depth: false,
16336
+ stencil: false,
16337
+ premultipliedAlpha: true,
16338
+ preserveDrawingBuffer: false
16339
+ });
16340
+ } catch {
16341
+ gl = null;
16342
+ }
16343
+ if (gl) {
16344
+ this.gl = gl;
16345
+ const maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
16346
+ this.maxVertexAttribs = typeof maxAttribs === "number" && maxAttribs > 0 ? maxAttribs : 0;
16347
+ this.canvas.addEventListener("webglcontextlost", this.onLost);
16348
+ this.canvas.addEventListener("webglcontextrestored", this.onRestore);
16349
+ }
16350
+ return this.gl;
16351
+ }
16352
+ isAvailable() {
16353
+ const gl = this.acquire();
16354
+ return gl !== null && !this.disposed && !gl.isContextLost();
16355
+ }
16356
+ isDisposed() {
16357
+ return this.disposed;
16358
+ }
16359
+ getChartCount() {
16360
+ return this.clients.size;
16361
+ }
16362
+ getStats() {
16363
+ const active2 = this.gl !== null && !this.disposed;
16364
+ return {
16365
+ available: active2 && !this.gl.isContextLost(),
16366
+ disposed: this.disposed,
16367
+ registeredCharts: this.clients.size,
16368
+ offscreenCharts: this.offscreenClients.size,
16369
+ backingWidth: active2 && this.canvas ? this.canvas.width : 0,
16370
+ backingHeight: active2 && this.canvas ? this.canvas.height : 0,
16371
+ chartDraws: this.chartDraws,
16372
+ blits: this.blits,
16373
+ backingResizes: this.backingResizes,
16374
+ contextLosses: this.contextLosses,
16375
+ contextRestores: this.contextRestores
16376
+ };
16377
+ }
16378
+ register(client) {
16379
+ if (this.disposed) throw new Error("SharedWebGLContext has been disposed");
16380
+ if (this.clients.has(client)) return;
16381
+ this.clients.add(client);
16382
+ if (this.cullOffscreen && typeof IntersectionObserver === "function") {
16383
+ if (!this.observer) {
16384
+ this.observer = new IntersectionObserver(
16385
+ (entries) => {
16386
+ for (const entry of entries) {
16387
+ const targetClient = this.observedRoots.get(entry.target);
16388
+ if (!targetClient) continue;
16389
+ const offscreen = !entry.isIntersecting;
16390
+ if (offscreen) this.offscreenClients.add(targetClient);
16391
+ else this.offscreenClients.delete(targetClient);
16392
+ targetClient.setOffscreen?.(offscreen);
16393
+ }
16394
+ },
16395
+ { threshold: 0 }
16396
+ );
16397
+ }
16398
+ this.observedRoots.set(client.root, client);
16399
+ this.observer.observe(client.root);
16400
+ }
16401
+ }
16402
+ unregister(client) {
16403
+ this.clients.delete(client);
16404
+ this.offscreenClients.delete(client);
16405
+ if (this.observedRoots.delete(client.root)) {
16406
+ this.observer?.unobserve(client.root);
16407
+ }
16408
+ }
16409
+ beginChartDraw(pixelWidth, pixelHeight) {
16410
+ this.pendingPresent = void 0;
16411
+ const gl = this.acquire();
16412
+ if (!gl || this.disposed || gl.isContextLost()) return false;
16413
+ const canvas = this.canvas;
16414
+ const width = Math.max(1, Math.round(pixelWidth));
16415
+ const height = Math.max(1, Math.round(pixelHeight));
16416
+ let resized = false;
16417
+ if (canvas.width !== width) {
16418
+ canvas.width = width;
16419
+ resized = true;
16420
+ }
16421
+ if (canvas.height !== height) {
16422
+ canvas.height = height;
16423
+ resized = true;
16424
+ }
16425
+ if (resized) this.backingResizes++;
16426
+ resetSharedBaseline(gl, width, height, this.maxVertexAttribs);
16427
+ gl.disable(gl.SCISSOR_TEST);
16428
+ gl.clearColor(0, 0, 0, 0);
16429
+ gl.clear(gl.COLOR_BUFFER_BIT);
16430
+ this.pendingPresent = { width, height };
16431
+ this.chartDraws++;
16432
+ return true;
16433
+ }
16434
+ present(target, pixelWidth, pixelHeight) {
16435
+ const pending = this.pendingPresent;
16436
+ this.pendingPresent = void 0;
16437
+ const width = Math.max(1, Math.round(pixelWidth));
16438
+ const height = Math.max(1, Math.round(pixelHeight));
16439
+ if (!pending || !target || !this.canvas || pending.width !== width || pending.height !== height) {
16440
+ return;
16441
+ }
16442
+ target.save();
16443
+ target.setTransform(1, 0, 0, 1, 0, 0);
16444
+ target.globalAlpha = 1;
16445
+ target.globalCompositeOperation = "copy";
16446
+ target.imageSmoothingEnabled = false;
16447
+ target.drawImage(this.canvas, 0, 0);
16448
+ target.restore();
16449
+ this.blits++;
16450
+ }
16451
+ dispose() {
16452
+ if (this.disposed) return;
16453
+ this.disposed = true;
16454
+ this.pendingPresent = void 0;
16455
+ this.observer?.disconnect();
16456
+ this.observer = void 0;
16457
+ this.observedRoots.clear();
16458
+ this.offscreenClients.clear();
16459
+ this.clients.clear();
16460
+ if (this.canvas) {
16461
+ if (this.gl) {
16462
+ this.canvas.removeEventListener("webglcontextlost", this.onLost);
16463
+ this.canvas.removeEventListener("webglcontextrestored", this.onRestore);
16464
+ }
16465
+ if (this.ownsCanvas) {
16466
+ this.gl?.getExtension("WEBGL_lose_context")?.loseContext();
16467
+ this.canvas.width = 1;
16468
+ this.canvas.height = 1;
16469
+ } else {
16470
+ claimedCanvases.delete(this.canvas);
16471
+ }
16472
+ }
16473
+ this.gl = null;
16474
+ }
16475
+ };
16476
+ var SharedWebGLContext = class {
16477
+ constructor(options) {
16478
+ cores.set(this, new SharedContextCore(options));
16479
+ }
16480
+ /** Lazily acquires the shared WebGL2 context on first call and caches the result without retrying. */
16481
+ isAvailable() {
16482
+ return sharedContextCore(this).isAvailable();
16483
+ }
16484
+ isDisposed() {
16485
+ return sharedContextCore(this).isDisposed();
16486
+ }
16487
+ /** Number of charts currently registered with this shared context. */
16488
+ getChartCount() {
16489
+ return sharedContextCore(this).getChartCount();
16490
+ }
16491
+ getStats() {
16492
+ return sharedContextCore(this).getStats();
16493
+ }
16494
+ /** Idempotently disposes the shared context. Dispose all registered charts first. */
16495
+ dispose() {
16496
+ sharedContextCore(this).dispose();
16497
+ }
16498
+ };
16499
+
16212
16500
  // src/render.ts
16213
16501
  var iconVertex = `#version 300 es
16214
16502
  precision highp float;
@@ -16354,7 +16642,15 @@ var DataRenderer = class {
16354
16642
  this.ownedCoverageFrame = options.ownedCoverageFrame === true;
16355
16643
  this.gpuClipPolicy = options.gpuClipPolicy ?? "legacy";
16356
16644
  let gl = null;
16357
- try {
16645
+ let contextEvents = canvas;
16646
+ if (options.renderer !== "canvas2d" && options.sharedContext) {
16647
+ const core = sharedContextCore(options.sharedContext);
16648
+ gl = core.acquire();
16649
+ if (gl && core.canvas) {
16650
+ this.sharedContext = options.sharedContext;
16651
+ contextEvents = core.canvas;
16652
+ }
16653
+ } else try {
16358
16654
  if (options.renderer !== "canvas2d") gl = canvas.getContext("webgl2", {
16359
16655
  alpha: true,
16360
16656
  antialias: options.antialias ?? false,
@@ -16365,11 +16661,12 @@ var DataRenderer = class {
16365
16661
  }
16366
16662
  if (options.renderer === "webgl2" && !gl) throw new Error("CRYChart WebGL2 renderer is unavailable");
16367
16663
  this.gl = gl;
16664
+ this.contextEvents = contextEvents;
16368
16665
  this.backend = gl ? "webgl2" : "canvas2d";
16369
16666
  if (gl) {
16370
16667
  this.init(gl);
16371
- canvas.addEventListener("webglcontextlost", this.onLost);
16372
- canvas.addEventListener("webglcontextrestored", this.onRestore);
16668
+ this.contextEvents.addEventListener("webglcontextlost", this.onLost);
16669
+ this.contextEvents.addEventListener("webglcontextrestored", this.onRestore);
16373
16670
  } else
16374
16671
  try {
16375
16672
  this.ctx = canvas.getContext("2d");
@@ -16401,6 +16698,8 @@ var DataRenderer = class {
16401
16698
  lost = false;
16402
16699
  iconPipeline;
16403
16700
  iconTextures = /* @__PURE__ */ new Map();
16701
+ sharedContext;
16702
+ contextEvents;
16404
16703
  stats = {
16405
16704
  frames: 0,
16406
16705
  uploads: 0,
@@ -17125,8 +17424,8 @@ var DataRenderer = class {
17125
17424
  this.attributeBuffers.clear();
17126
17425
  if (this.program) this.gl.deleteProgram(this.program);
17127
17426
  }
17128
- this.canvas.removeEventListener("webglcontextlost", this.onLost);
17129
- this.canvas.removeEventListener("webglcontextrestored", this.onRestore);
17427
+ this.contextEvents.removeEventListener("webglcontextlost", this.onLost);
17428
+ this.contextEvents.removeEventListener("webglcontextrestored", this.onRestore);
17130
17429
  }
17131
17430
  };
17132
17431
  function appendPointPath(ctx, x, y, size, shape, rotation) {
@@ -18004,8 +18303,9 @@ var DataRendererHeatmap = class {
18004
18303
  this.canvas = canvas;
18005
18304
  this.options = options;
18006
18305
  this.initialize();
18007
- canvas.addEventListener("webglcontextlost", this.contextLost);
18008
- canvas.addEventListener("webglcontextrestored", this.contextRestored);
18306
+ const events = this.options.contextEvents ?? this.canvas;
18307
+ events.addEventListener("webglcontextlost", this.contextLost);
18308
+ events.addEventListener("webglcontextrestored", this.contextRestored);
18009
18309
  }
18010
18310
  stats = { frames: 0, uploads: 0, textureUploads: 0, paletteUploads: 0, uploadedBytes: 0, drawCalls: 0, cells: 0, renderTimeMs: 0, cachedTextures: 0, cacheBytes: 0, contextRestores: 0 };
18011
18311
  entries = /* @__PURE__ */ new Map();
@@ -18296,8 +18596,9 @@ var DataRendererHeatmap = class {
18296
18596
  this.program = void 0;
18297
18597
  this.stats.cachedTextures = 0;
18298
18598
  this.stats.cacheBytes = 0;
18299
- this.canvas.removeEventListener("webglcontextlost", this.contextLost);
18300
- this.canvas.removeEventListener("webglcontextrestored", this.contextRestored);
18599
+ const events = this.options.contextEvents ?? this.canvas;
18600
+ events.removeEventListener("webglcontextlost", this.contextLost);
18601
+ events.removeEventListener("webglcontextrestored", this.contextRestored);
18301
18602
  }
18302
18603
  };
18303
18604
 
@@ -18851,6 +19152,35 @@ var integer = (value, minimum = 0) => {
18851
19152
  var rgba = (color2) => [color2.r, color2.g, color2.b, color2.a];
18852
19153
  var meshFillColor = (fill, fallback) => fill.kind === "empty" ? ColorRGBA(0, 0, 0, 0) : fill.getColor?.() ?? fallback;
18853
19154
  var finiteVertex2 = (values, index) => Number.isFinite(values[index * 3]) && Number.isFinite(values[index * 3 + 1]) && Number.isFinite(values[index * 3 + 2]);
19155
+ function structuredWireEdges(indices, count) {
19156
+ const columns = indices[1], rows = count / columns;
19157
+ if (!Number.isInteger(columns) || columns < 2 || !Number.isInteger(rows) || rows < 2 || indices.length !== (rows - 1) * (columns - 1) * 6) return void 0;
19158
+ let offset = 0;
19159
+ for (let row = 0; row + 1 < rows; row++) for (let col = 0; col + 1 < columns; col++, offset += 6) {
19160
+ const i = row * columns + col, below = i + columns;
19161
+ if (indices[offset] !== i || indices[offset + 1] !== below || indices[offset + 2] !== i + 1 || indices[offset + 3] !== i + 1 || indices[offset + 4] !== below || indices[offset + 5] !== below + 1) return void 0;
19162
+ }
19163
+ const pairs = new Uint32Array((rows * (columns - 1) + (rows - 1) * columns + (rows - 1) * (columns - 1)) * 2);
19164
+ let length = 0;
19165
+ for (let row = 0; row + 1 < rows; row++) for (let col = 0; col + 1 < columns; col++) {
19166
+ const i = row * columns + col, below = i + columns;
19167
+ if (col === 0) {
19168
+ pairs[length++] = i;
19169
+ pairs[length++] = below;
19170
+ }
19171
+ pairs[length++] = below;
19172
+ pairs[length++] = i + 1;
19173
+ if (row === 0) {
19174
+ pairs[length++] = i + 1;
19175
+ pairs[length++] = i;
19176
+ }
19177
+ pairs[length++] = below;
19178
+ pairs[length++] = below + 1;
19179
+ pairs[length++] = below + 1;
19180
+ pairs[length++] = i + 1;
19181
+ }
19182
+ return pairs;
19183
+ }
18854
19184
  function mergedRanges(ranges, width = 1) {
18855
19185
  const sorted = ranges.filter((range) => range.count > 0).map((range) => ({ start: range.start, count: range.count })).sort((a, b) => a.start - b.start), out = [];
18856
19186
  for (const range of sorted) {
@@ -19077,28 +19407,34 @@ var MeshSeries3D = class extends Series3DBase {
19077
19407
  dirty = [];
19078
19408
  styleDirty = true;
19079
19409
  compiled;
19410
+ wireTopology;
19080
19411
  boundsCache;
19081
19412
  setGeometry(input) {
19082
19413
  this.assertAlive();
19083
19414
  if (!input?.positions || input.positions.length % 3) throw new RangeError("Mesh positions require complete XYZ vertices");
19084
19415
  const positions = Float64Array.from(input.positions), count = positions.length / 3;
19085
- const indices = input.indices ? Uint32Array.from(input.indices, (index) => {
19086
- if (!Number.isSafeInteger(index) || index < 0 || index >= count) throw new RangeError("Mesh index outside vertex range");
19087
- return index;
19088
- }) : Uint32Array.from({ length: Math.floor(count / 3) * 3 }, (_, index) => index);
19416
+ const unsignedIndices = input.indices instanceof Uint32Array;
19417
+ if (input.indices) for (let i = 0; i < input.indices.length; i++) {
19418
+ const index = input.indices[i];
19419
+ if (index >= count || !unsignedIndices && (!Number.isSafeInteger(index) || index < 0)) throw new RangeError("Mesh index outside vertex range");
19420
+ }
19421
+ const indices = input.indices ? Uint32Array.from(input.indices) : Uint32Array.from({ length: Math.floor(count / 3) * 3 }, (_, index) => index);
19089
19422
  if (indices.length % 3) throw new RangeError("Mesh indices require complete triangles");
19090
19423
  if (input.values && input.values.length !== count || input.colors && input.colors.length !== count * 4) throw new RangeError("Mesh values/colors do not match vertex count");
19091
19424
  const colors = input.colors ? Float32Array.from(input.colors) : void 0;
19092
19425
  if (colors && !colors.every((value) => Number.isFinite(value) && value >= 0 && value <= 1)) throw new RangeError("Mesh colors require normalized finite RGBA");
19426
+ const sameTopology = positions.length === this.vertices.length && indices.length === this.indices.length && indices.every((value, index) => value === this.indices[index]);
19093
19427
  this.vertices = positions;
19094
- this.indices = indices;
19428
+ if (!sameTopology) {
19429
+ this.indices = indices;
19430
+ this.topologyRevision++;
19431
+ this.compiled = void 0;
19432
+ }
19095
19433
  this.scalarValues = input.values ? Float32Array.from(input.values) : void 0;
19096
19434
  this.vertexColors = colors;
19097
- this.topologyRevision++;
19098
19435
  this.geometryRevision++;
19099
19436
  this.dirty = [{ start: 0, count }];
19100
19437
  this.styleDirty = true;
19101
- this.compiled = void 0;
19102
19438
  this.changed();
19103
19439
  return this;
19104
19440
  }
@@ -19187,28 +19523,62 @@ var MeshSeries3D = class extends Series3DBase {
19187
19523
  for (const range of ranges) for (let i = range.start; i < range.start + range.count; i++) {
19188
19524
  if (!all && !finiteVertex2(positions, i)) invalidVertices--;
19189
19525
  const point = this.normalizedVertex(i, normalize);
19190
- positions.set([point.x, point.y, point.z], i * 3);
19526
+ positions[i * 3] = point.x;
19527
+ positions[i * 3 + 1] = point.y;
19528
+ positions[i * 3 + 2] = point.z;
19191
19529
  if (!finiteVertex2(positions, i)) invalidVertices++;
19192
19530
  }
19193
19531
  const colorRanges = all || this.styleDirty ? [{ start: 0, count }] : ranges;
19194
- for (const range of colorRanges) for (let i = range.start; i < range.start + range.count; i++) colors.set(rgba(this.colorAt(i)), i * 4);
19532
+ for (const range of colorRanges) for (let i = range.start; i < range.start + range.count; i++) {
19533
+ const color2 = this.colorAt(i);
19534
+ colors[i * 4] = color2.r;
19535
+ colors[i * 4 + 1] = color2.g;
19536
+ colors[i * 4 + 2] = color2.b;
19537
+ colors[i * 4 + 3] = color2.a;
19538
+ }
19195
19539
  const normal = ranges.length ? this.updateNormals(positions, all ? void 0 : previous?.packet.normals, ranges) : { values: previous?.packet.normals ?? meshNormals(positions, this.indices), ranges: [] };
19196
19540
  const packet = { id: this.id, revision: ++this.packetRevision, previousRevision: previous?.packet.revision, count, mode: "triangles", positions, colors, normals: normal.values, indices: this.indices, indexRevision: this.topologyRevision, allFinite: invalidVertices === 0, lighting: this.lighting, ...this.renderingState(), color: [1, 1, 1, 1], thickness: 0, pointSize: 0, positionUpdateRanges: all ? void 0 : mergedRanges(ranges, 3), colorUpdateRanges: all ? void 0 : mergedRanges(colorRanges, 4), normalUpdateRanges: all ? void 0 : normal.ranges };
19197
19541
  const packets = [packet];
19198
19542
  let wire;
19199
19543
  if (this.wireframe.getThickness() > 0 && meshFillColor(this.wireframe.getFillStyle(), ColorRGBA(0, 0, 0)).a > 0) {
19200
- const edges = /* @__PURE__ */ new Set(), values = [];
19201
- for (let i = 0; i < this.indices.length; i += 3) {
19202
- const triangle2 = [this.indices[i], this.indices[i + 1], this.indices[i + 2]];
19203
- if (!triangle2.every((index) => finiteVertex2(positions, index))) continue;
19204
- for (let j = 0; j < 3; j++) {
19205
- const a = triangle2[j], b = triangle2[(j + 1) % 3], key = a < b ? `${a}:${b}` : `${b}:${a}`;
19206
- if (edges.has(key)) continue;
19207
- edges.add(key);
19208
- values.push(positions[a * 3], positions[a * 3 + 1], positions[a * 3 + 2], positions[b * 3], positions[b * 3 + 1], positions[b * 3 + 2], NaN, NaN, NaN);
19544
+ const valid2 = new Uint8Array(this.indices.length / 3);
19545
+ if (invalidVertices === 0) valid2.fill(1);
19546
+ else for (let i = 0; i < this.indices.length; i += 3) valid2[i / 3] = finiteVertex2(positions, this.indices[i]) && finiteVertex2(positions, this.indices[i + 1]) && finiteVertex2(positions, this.indices[i + 2]) ? 1 : 0;
19547
+ let topology = this.wireTopology;
19548
+ if (!topology || topology.indices.length !== this.indices.length || !this.indices.every((value, index) => value === topology.indices[index]) || !valid2.every((value, index) => value === topology.valid[index])) {
19549
+ const gridPairs = invalidVertices === 0 ? structuredWireEdges(this.indices, count) : void 0;
19550
+ if (gridPairs) topology = this.wireTopology = { indices: this.indices.slice(), valid: valid2, pairs: gridPairs };
19551
+ else {
19552
+ const edges = /* @__PURE__ */ new Set(), pairs = new Uint32Array(this.indices.length * 2);
19553
+ const numericKeys = Number.isSafeInteger(count * count);
19554
+ let length = 0;
19555
+ for (let i = 0; i < this.indices.length; i += 3) {
19556
+ if (!valid2[i / 3]) continue;
19557
+ for (let j = 0; j < 3; j++) {
19558
+ const a = this.indices[i + j], b = this.indices[i + (j + 1) % 3];
19559
+ const low = Math.min(a, b), high = Math.max(a, b);
19560
+ const key = numericKeys ? low * count + high : `${low}:${high}`;
19561
+ if (edges.has(key)) continue;
19562
+ edges.add(key);
19563
+ pairs[length++] = a;
19564
+ pairs[length++] = b;
19565
+ }
19566
+ }
19567
+ topology = this.wireTopology = { indices: this.indices.slice(), valid: valid2, pairs: pairs.subarray(0, length) };
19209
19568
  }
19210
19569
  }
19211
- wire = { id: -this.id, revision: packet.revision, count: values.length / 3, mode: "line", positions: Float32Array.from(values), ...this.renderingState(), color: rgba(meshFillColor(this.wireframe.getFillStyle(), ColorRGBA(0, 0, 0))), thickness: this.wireframe.getThickness(), pointSize: 0 };
19570
+ const values = new Float32Array(topology.pairs.length / 2 * 9);
19571
+ for (let i = 0, out = 0; i < topology.pairs.length; i += 2, out += 9) {
19572
+ const a = topology.pairs[i] * 3, b = topology.pairs[i + 1] * 3;
19573
+ values[out] = positions[a];
19574
+ values[out + 1] = positions[a + 1];
19575
+ values[out + 2] = positions[a + 2];
19576
+ values[out + 3] = positions[b];
19577
+ values[out + 4] = positions[b + 1];
19578
+ values[out + 5] = positions[b + 2];
19579
+ values[out + 6] = values[out + 7] = values[out + 8] = NaN;
19580
+ }
19581
+ wire = { id: -this.id, revision: packet.revision, count: values.length / 3, mode: "line", positions: values, ...this.renderingState(), color: rgba(meshFillColor(this.wireframe.getFillStyle(), ColorRGBA(0, 0, 0))), thickness: this.wireframe.getThickness(), pointSize: 0 };
19212
19582
  packets.push(wire);
19213
19583
  }
19214
19584
  this.compiled = { key: axisKey, revision: this.revision, packet, wire, packets, invalidVertices };
@@ -19218,6 +19588,7 @@ var MeshSeries3D = class extends Series3DBase {
19218
19588
  }
19219
19589
  dispose() {
19220
19590
  this.compiled = void 0;
19591
+ this.wireTopology = void 0;
19221
19592
  this.vertices = new Float64Array(0);
19222
19593
  this.indices = new Uint32Array(0);
19223
19594
  this.scalarValues = void 0;
@@ -20537,6 +20908,11 @@ var ChartXY = class {
20537
20908
  observer;
20538
20909
  overlayContext;
20539
20910
  underlayContext;
20911
+ sharedCore;
20912
+ sharedPresent = null;
20913
+ sharedClient;
20914
+ sharedOffscreen = false;
20915
+ sharedDeferred = false;
20540
20916
  heatmapRenderer;
20541
20917
  heatmapPalettes = /* @__PURE__ */ new Map();
20542
20918
  heatCache = /* @__PURE__ */ new Map();
@@ -20623,7 +20999,7 @@ var ChartXY = class {
20623
20999
  this.underlay = underlay;
20624
21000
  this.overlay = overlay;
20625
21001
  try {
20626
- this.renderer = new DataRenderer(data, { antialias: options.antialias, renderer: options.renderer, lineCoverageUnion: options.experimentalLineCoverage === true, ownedCoverageFrame: options.experimentalOwnedCoverageFrame === true, gpuClipPolicy: this.gpuClipPolicy });
21002
+ this.renderer = new DataRenderer(data, { antialias: options.antialias, renderer: options.renderer, lineCoverageUnion: options.experimentalLineCoverage === true, ownedCoverageFrame: options.experimentalOwnedCoverageFrame === true, gpuClipPolicy: this.gpuClipPolicy, sharedContext: options.sharedContext ?? void 0 });
20627
21003
  } catch (error) {
20628
21004
  this.cssTextFonts?.dispose();
20629
21005
  root.remove();
@@ -20643,6 +21019,18 @@ var ChartXY = class {
20643
21019
  });
20644
21020
  this.observer.observe(container);
20645
21021
  }
21022
+ if (this.renderer?.sharedContext) {
21023
+ const sharedCore = sharedContextCore(this.renderer.sharedContext);
21024
+ this.sharedCore = sharedCore;
21025
+ this.sharedPresent = data.getContext("2d");
21026
+ const client = {
21027
+ root,
21028
+ setOffscreen: (offscreen) => this.setSharedOffscreen(offscreen)
21029
+ };
21030
+ this.sharedClient = client;
21031
+ sharedCore.register(client);
21032
+ this.cleanups.push(() => sharedCore.unregister(client));
21033
+ }
20646
21034
  }
20647
21035
  this.engine = {
20648
21036
  container: this.root ?? this.container,
@@ -21388,8 +21776,26 @@ var ChartXY = class {
21388
21776
  this.cancelAxisScrollAnimations();
21389
21777
  for (const series of this.series) series.cancelHighlightAnimation?.();
21390
21778
  }
21779
+ setSharedOffscreen(offscreen) {
21780
+ if (offscreen === this.sharedOffscreen || this.disposed) return;
21781
+ this.sharedOffscreen = offscreen;
21782
+ if (offscreen) {
21783
+ if (this.frame && typeof cancelAnimationFrame === "function") {
21784
+ cancelAnimationFrame(this.frame);
21785
+ this.frame = 0;
21786
+ this.sharedDeferred = true;
21787
+ }
21788
+ } else if (this.sharedDeferred) {
21789
+ this.sharedDeferred = false;
21790
+ this.invalidate();
21791
+ }
21792
+ }
21391
21793
  invalidate() {
21392
21794
  if (this.disposed || this.frame || this.rendering || !this.root) return;
21795
+ if (this.sharedOffscreen) {
21796
+ this.sharedDeferred = true;
21797
+ return;
21798
+ }
21393
21799
  if (typeof requestAnimationFrame === "function")
21394
21800
  this.frame = requestAnimationFrame((timestamp) => {
21395
21801
  this.frame = 0;
@@ -21843,6 +22249,8 @@ var ChartXY = class {
21843
22249
  ctx.drawImage(cache.canvas, r.left, r.top, r.width, r.height);
21844
22250
  }
21845
22251
  renderData(packets) {
22252
+ const shared = this.sharedCore;
22253
+ if (shared && !shared.beginChartDraw(this.canvas.width, this.canvas.height)) return;
21846
22254
  const grids = [];
21847
22255
  for (const s of this.series) {
21848
22256
  if (!(s instanceof HeatmapSeries) || !s.visible || s.disposed || !this.gpuHeatmap(s))
@@ -21913,7 +22321,7 @@ var ChartXY = class {
21913
22321
  this.heatmapRenderer = new DataRendererHeatmap(
21914
22322
  this.renderer.gl,
21915
22323
  this.canvas,
21916
- { clipPolicy: this.gpuClipPolicy }
22324
+ { clipPolicy: this.gpuClipPolicy, contextEvents: this.renderer.contextEvents }
21917
22325
  );
21918
22326
  const gl = this.renderer?.gl;
21919
22327
  const rasterTarget = this.gpuClipPolicy === "contained" && gl ? rasterTargetForRect(null, gl.drawingBufferWidth, gl.drawingBufferHeight, this.plot, this.dpr) : void 0;
@@ -21930,6 +22338,7 @@ var ChartXY = class {
21930
22338
  clear: grids.length === 0,
21931
22339
  rasterTarget
21932
22340
  });
22341
+ if (shared) shared.present(this.sharedPresent, this.canvas.width, this.canvas.height);
21933
22342
  }
21934
22343
  gpuHeatmap(s) {
21935
22344
  return !!this.renderer?.gl && s.axisX.type !== "logarithmic" && s.axisY.type !== "logarithmic";
@@ -23189,7 +23598,8 @@ var Chart3D = class extends ChartXY {
23189
23598
  gpuPackets = /* @__PURE__ */ new Map();
23190
23599
  gpuRevision = 0;
23191
23600
  constructor(options = {}) {
23192
- super({ ...options, antialias: options.antialias ?? true });
23601
+ if (options.sharedContext) throw new UnsupportedFeatureError("shared WebGL contexts for Chart3D");
23602
+ super({ ...options, sharedContext: null, antialias: options.antialias ?? true });
23193
23603
  this.cameraModel = options.experimental3DCameraModel === "legacy" ? "legacy" : "world";
23194
23604
  this.axesZ.push(new Axis(this, "z", options.defaultAxisZ));
23195
23605
  this.coordsAxis.z = this.axesZ[0];
@@ -24764,7 +25174,8 @@ function createCRYChartAdapter(container, options = {}) {
24764
25174
  const chart = new ChartXY({
24765
25175
  container,
24766
25176
  legend: { visible: false },
24767
- ...options.xScale === "logarithmic" ? { defaultAxisX: { type: "logarithmic", base: 10 } } : {}
25177
+ ...options.xScale === "logarithmic" ? { defaultAxisX: { type: "logarithmic", base: 10 } } : {},
25178
+ ...options.sharedContext ? { sharedContext: options.sharedContext } : {}
24768
25179
  });
24769
25180
  const entries = /* @__PURE__ */ new Map();
24770
25181
  let disposed = false;
@@ -24940,12 +25351,27 @@ function createCRYChartAdapter(container, options = {}) {
24940
25351
  }
24941
25352
 
24942
25353
  // src/index.ts
24943
- function cryChart(_options = {}) {
25354
+ function cryChart(options = {}) {
25355
+ if (options.sharedContext !== void 0 && options.sharedContextOptions !== void 0) {
25356
+ throw new TypeError(
25357
+ "Pass either sharedContext or sharedContextOptions, not both"
25358
+ );
25359
+ }
25360
+ if (options.sharedContext !== void 0 && !(options.sharedContext instanceof SharedWebGLContext)) {
25361
+ throw new TypeError("sharedContext must be a SharedWebGLContext");
25362
+ }
25363
+ if (options.sharedContext?.isDisposed()) {
25364
+ throw new Error("sharedContext has been disposed");
25365
+ }
25366
+ const shared = options.sharedContext ?? (options.sharedContextOptions ? new SharedWebGLContext(options.sharedContextOptions) : void 0);
25367
+ const ownsShared = !options.sharedContext && shared !== void 0;
24944
25368
  const owned2 = /* @__PURE__ */ new Set();
24945
25369
  let disposed = false;
24946
- const create = (ctor, options = {}) => {
25370
+ const create = (ctor, opts = {}) => {
24947
25371
  if (disposed) throw new Error("Chart context has been disposed");
24948
- const chart = new ctor(options);
25372
+ const injects = shared !== void 0 && (ctor === ChartXY || ctor === Polar || ctor === Dashboard) && !("sharedContext" in opts);
25373
+ const finalOptions = injects ? { ...opts, sharedContext: shared } : opts;
25374
+ const chart = new ctor(finalOptions);
24949
25375
  owned2.add(chart);
24950
25376
  chart.onDispose(() => owned2.delete(chart));
24951
25377
  return chart;
@@ -24976,17 +25402,25 @@ function cryChart(_options = {}) {
24976
25402
  } catch (error) {
24977
25403
  errors.push(error);
24978
25404
  }
25405
+ if (ownsShared) try {
25406
+ shared.dispose();
25407
+ } catch (error) {
25408
+ errors.push(error);
25409
+ }
24979
25410
  if (errors.length) throw new AggregateError(errors, "Some chart disposal callbacks failed");
24980
25411
  }
24981
25412
  },
24982
25413
  isDisposed: () => disposed,
24983
25414
  /** Live charts owned by this context; disposed charts are released immediately. */
24984
- getChartCount: () => owned2.size
25415
+ getChartCount: () => owned2.size,
25416
+ /** Shared WebGL2 context used by this context; undefined when not enabled. */
25417
+ getSharedContext: () => shared
24985
25418
  };
24986
25419
  }
24987
- var version = "1.0.5";
25420
+ var version = "1.0.7";
24988
25421
  var Dashboard = class {
24989
25422
  root;
25423
+ sharedContext;
24990
25424
  cells = /* @__PURE__ */ new Map();
24991
25425
  children = /* @__PURE__ */ new Set();
24992
25426
  events = new EventHub();
@@ -24998,6 +25432,7 @@ var Dashboard = class {
24998
25432
  throw new Error("Dashboard requires a DOM");
24999
25433
  const container = typeof options.container === "string" ? document.getElementById(options.container) : options.container ?? document.body;
25000
25434
  if (!container) throw new Error("Dashboard container was not found");
25435
+ this.sharedContext = options.sharedContext;
25001
25436
  this.root = document.createElement("div");
25002
25437
  this.columns = options.numberOfColumns ?? 2;
25003
25438
  this.rows = options.numberOfRows ?? 2;
@@ -25010,8 +25445,13 @@ var Dashboard = class {
25010
25445
  cell.style.cssText = `min-height:0;min-width:0;grid-column:${(options.columnIndex ?? 0) + 1}/span ${options.columnSpan ?? 1};grid-row:${(options.rowIndex ?? 0) + 1}/span ${options.rowSpan ?? 1}`;
25011
25446
  this.root.append(cell);
25012
25447
  let chart;
25448
+ const inject = this.sharedContext && (Ctor === ChartXY || Ctor === Polar) && !("sharedContext" in options);
25013
25449
  try {
25014
- chart = new Ctor({ ...options, container: cell });
25450
+ chart = new Ctor({
25451
+ ...options,
25452
+ ...inject ? { sharedContext: this.sharedContext } : {},
25453
+ container: cell
25454
+ });
25015
25455
  } catch (error) {
25016
25456
  cell.remove();
25017
25457
  throw error;
@@ -25162,6 +25602,7 @@ export {
25162
25602
  SegmentFigure,
25163
25603
  SegmentSeries,
25164
25604
  Series3DBase,
25605
+ SharedWebGLContext,
25165
25606
  SimpleShadingStyle,
25166
25607
  SlicedHierarchyChart,
25167
25608
  SolidFill,