code
stringlengths
0
56.1M
repo_name
stringlengths
3
57
path
stringlengths
2
176
language
stringclasses
672 values
license
stringclasses
8 values
size
int64
0
56.8M
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS206: Consider reworking classes to avoid initClass * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UAxis from "../../../util/axis.js"; import * as UThree from "../../../util/three.js"; import { Vector2 } from "three/src/math/Vector2.js"; import { View } from "./view.js"; export class Spherical extends View { static initClass() { this.traits = [ "node", "object", "visible", "view", "view3", "spherical", "vertex", ]; } make() { super.make(); this.uniforms = { sphericalBend: this.node.attributes["spherical.bend"], sphericalFocus: this._attributes.make(this._types.number()), sphericalAspectX: this._attributes.make(this._types.number()), sphericalAspectY: this._attributes.make(this._types.number()), sphericalScaleY: this._attributes.make(this._types.number()), viewMatrix: this._attributes.make(this._types.mat4()), }; this.viewMatrix = this.uniforms.viewMatrix.value; this.composer = UThree.transformComposer(); this.aspectX = 1; return (this.aspectY = 1); } unmake() { super.unmake(); delete this.viewMatrix; delete this.objectMatrix; delete this.aspectX; delete this.aspectY; return delete this.uniforms; } change(changed, touched, init) { let aspectX, aspectY, bend, focus, scaleY; if ( !touched["view"] && !touched["view3"] && !touched["spherical"] && !init ) { return; } this.bend = bend = this.props.bend; this.focus = focus = bend > 0 ? 1 / bend - 1 : 0; const p = this.props.position; const s = this.props.scale; const q = this.props.quaternion; const r = this.props.rotation; const g = this.props.range; const e = this.props.eulerOrder; const { x } = g[0]; let y = g[1].x; let z = g[2].x; const dx = g[0].y - x || 1; let dy = g[1].y - y || 1; let dz = g[2].y - z || 1; const sx = s.x; const sy = s.y; const sz = s.z; // Recenter viewport on origin the more it's bent [y, dy] = Array.from(UAxis.recenterAxis(y, dy, bend)); [z, dz] = Array.from(UAxis.recenterAxis(z, dz, bend)); // Watch for negative scales. const idx = dx > 0 ? 1 : -1; const idy = dy > 0 ? 1 : -1; // Adjust viewport range for spherical transform. // As the viewport goes spherical, the X/Y-ranges are interpolated to the Z-range, // creating a perfectly spherical viewport. const adz = Math.abs(dz); const fdx = dx + (adz * idx - dx) * bend; const fdy = dy + (adz * idy - dy) * bend; const sdx = fdx / sx; const sdy = fdy / sy; const sdz = dz / sz; this.aspectX = aspectX = Math.abs(sdx / sdz); this.aspectY = aspectY = Math.abs(sdy / sdz / aspectX); // Scale Y coordinates before transforming, but cap at aspectY/alpha to prevent from poking through the poles mid-transform. // See shaders/glsl/spherical.position.glsl const aspectZ = (((dy / dx) * sx) / sy) * 2; // Factor of 2 due to the fact that in the Y direction we only go 180º from pole to pole. this.scaleY = scaleY = Math.min(aspectY / bend, 1 + (aspectZ - 1) * bend); this.uniforms.sphericalBend.value = bend; this.uniforms.sphericalFocus.value = focus; this.uniforms.sphericalAspectX.value = aspectX; this.uniforms.sphericalAspectY.value = aspectY; this.uniforms.sphericalScaleY.value = scaleY; // Forward transform this.viewMatrix.set( 2 / fdx, 0, 0, -(2 * x + dx) / dx, 0, 2 / fdy, 0, -(2 * y + dy) / dy, 0, 0, 2 / dz, -(2 * z + dz) / dz, 0, 0, 0, 1 //, ); const transformMatrix = this.composer(p, r, q, s, null, e); this.viewMatrix.multiplyMatrices(transformMatrix, this.viewMatrix); if (changed["view.range"] || touched["spherical"]) { return this.trigger({ type: "view.range", }); } } vertex(shader, pass) { if (pass === 1) { shader.pipe("spherical.position", this.uniforms); } return super.vertex(shader, pass); } axis(dimension) { const range = this.props.range[dimension - 1]; let min = range.x; let max = range.y; // Correct Z extents during polar warp. if (dimension === 3 && this.bend > 0) { max = Math.max(Math.abs(max), Math.abs(min)); min = Math.max(-this.focus / this.aspectX + 0.001, min); } return new Vector2(min, max); } } Spherical.initClass();
cchudzicki/mathbox
src/primitives/types/view/spherical.js
JavaScript
mit
4,841
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS206: Consider reworking classes to avoid initClass * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UAxis from "../../../util/axis.js"; import * as UThree from "../../../util/three.js"; import { View } from "./view.js"; export class Stereographic extends View { static initClass() { this.traits = [ "node", "object", "visible", "view", "view3", "stereographic", "vertex", ]; } make() { super.make(); this.uniforms = { stereoBend: this.node.attributes["stereographic.bend"], viewMatrix: this._attributes.make(this._types.mat4()), }; this.viewMatrix = this.uniforms.viewMatrix.value; return (this.composer = UThree.transformComposer()); } unmake() { super.unmake(); delete this.viewMatrix; delete this.rotationMatrix; return delete this.uniforms; } change(changed, touched, init) { let bend; if ( !touched["view"] && !touched["view3"] && !touched["stereographic"] && !init ) { return; } this.bend = bend = this.props.bend; const p = this.props.position; const s = this.props.scale; const q = this.props.quaternion; const r = this.props.rotation; const g = this.props.range; const e = this.props.eulerOrder; const { x } = g[0]; const y = g[1].x; let z = g[2].x; const dx = g[0].y - x || 1; const dy = g[1].y - y || 1; let dz = g[2].y - z || 1; // Recenter viewport on projection point the more it's bent [z, dz] = Array.from(UAxis.recenterAxis(z, dz, bend, 1)); this.uniforms.stereoBend.value = bend; // Forward transform this.viewMatrix.set( 2 / dx, 0, 0, -(2 * x + dx) / dx, 0, 2 / dy, 0, -(2 * y + dy) / dy, 0, 0, 2 / dz, -(2 * z + dz) / dz, 0, 0, 0, 1 //, ); const transformMatrix = this.composer(p, r, q, s, null, e); this.viewMatrix.multiplyMatrices(transformMatrix, this.viewMatrix); if (changed["view.range"] || touched["stereographic"]) { return this.trigger({ type: "view.range", }); } } vertex(shader, pass) { if (pass === 1) { shader.pipe("stereographic.position", this.uniforms); } return super.vertex(shader, pass); } } Stereographic.initClass();
cchudzicki/mathbox
src/primitives/types/view/stereographic.js
JavaScript
mit
2,687
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS206: Consider reworking classes to avoid initClass * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UAxis from "../../../util/axis.js"; import { View } from "./view.js"; export class Stereographic4 extends View { static initClass() { this.traits = [ "node", "object", "visible", "view", "view4", "stereographic", "vertex", ]; } make() { super.make(); this.uniforms = { basisOffset: this._attributes.make(this._types.vec4()), basisScale: this._attributes.make(this._types.vec4()), stereoBend: this.node.attributes["stereographic.bend"], }; this.basisScale = this.uniforms.basisScale.value; this.basisOffset = this.uniforms.basisOffset.value; } unmake() { super.unmake(); delete this.basisScale; delete this.basisOffset; delete this.uniforms; } change(changed, touched, init) { let bend; if ( !touched["view"] && !touched["view4"] && !touched["stereographic"] && !init ) { return; } this.bend = bend = this.props.bend; const p = this.props.position; const s = this.props.scale; const g = this.props.range; const { x } = g[0]; const y = g[1].x; const z = g[2].x; let w = g[3].x; const dx = g[0].y - x || 1; const dy = g[1].y - y || 1; const dz = g[2].y - z || 1; let dw = g[3].y - w || 1; const mult = function (a, b) { a.x *= b.x; a.y *= b.y; a.z *= b.z; a.w *= b.w; }; // Recenter viewport on projection point the more it's bent [w, dw] = Array.from(UAxis.recenterAxis(w, dw, bend, 1)); // 4D axis adjustment this.basisScale.set(2 / dx, 2 / dy, 2 / dz, 2 / dw); this.basisOffset.set( -(2 * x + dx) / dx, -(2 * y + dy) / dy, -(2 * z + dz) / dz, -(2 * w + dw) / dw ); // 4D scale mult(this.basisScale, s); mult(this.basisOffset, s); // 4D position this.basisOffset.add(p); if (changed["view.range"] || touched["stereographic"]) { this.trigger({ type: "view.range", }); } } vertex(shader, pass) { if (pass === 1) { shader.pipe("stereographic4.position", this.uniforms); } return super.vertex(shader, pass); } } Stereographic4.initClass();
cchudzicki/mathbox
src/primitives/types/view/stereographic4.js
JavaScript
mit
2,639
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS206: Consider reworking classes to avoid initClass * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Transform } from "../transform/transform.js"; export class View extends Transform { static initClass() { this.traits = ["node", "object", "visible", "view", "vertex"]; } make() { return this._helpers.visible.make(); } unmake() { return this._helpers.visible.unmake(); } axis(dimension) { return this.props.range[dimension - 1]; } } View.initClass();
cchudzicki/mathbox
src/primitives/types/view/view.js
JavaScript
mit
758
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UData from "../../util/data.js"; import { DataBuffer } from "./databuffer.js"; /* * 1D + history array */ export class ArrayBuffer_ extends DataBuffer { constructor(renderer, shaders, options) { const width = options.width || 1; const history = options.history || 1; options.width = width; options.height = history; options.depth = 1; super(renderer, shaders, options, false); this.width = width; this.history = history; this.samples = width; this.wrap = history > 1; this.build(options); } build(_options) { super.build(); this.index = 0; this.pad = 0; return (this.streamer = this.generate(this.data)); } setActive(i) { return (this.pad = Math.max(0, this.width - i)); } fill() { const { callback } = this; if (typeof callback.reset === "function") { callback.reset(); } const { emit, count, done, reset } = this.streamer; reset(); const limit = this.samples - this.pad; let i = 0; while (!done() && i < limit && callback(emit, i++) !== false) { true; } return Math.floor(count() / this.items); } write(n) { if (n == null) { n = this.samples; } n *= this.items; this.texture.write(this.data, 0, this.index, n, 1); this.dataPointer.set(0.5, this.index + 0.5); this.index = (this.index + this.history - 1) % this.history; return (this.filled = Math.min(this.history, this.filled + 1)); } through(callback, target) { let dst, src; const { consume, done } = (src = this.streamer); const { emit } = (dst = target.streamer); let i = 0; let pipe = () => consume((x, y, z, w) => callback(emit, x, y, z, w, i)); pipe = UData.repeatCall(pipe, this.items); return () => { src.reset(); dst.reset(); const limit = this.samples - this.pad; i = 0; while (!done() && i < limit) { pipe(); i++; } return src.count(); }; } }
cchudzicki/mathbox
src/render/buffer/arraybuffer.js
JavaScript
mit
2,365
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS103: Rewrite code to no longer use __guard__, or convert again using --optional-chaining * DS104: Avoid inline assignments * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UGLSL from "../../util/glsl.js"; import { BackedTexture } from "./texture/backedtexture.js"; import { DataTexture } from "./texture/datatexture.js"; import { Renderable } from "../renderable.js"; import { Vector2 } from "three/src/math/Vector2.js"; /* * Dynamic sprite atlas * * - Allocates variable-sized sprites in rows * - Will grow itself when full */ export class Atlas extends Renderable { constructor(renderer, shaders, options, build) { if (build == null) { build = true; } super(renderer, shaders); if (this.width == null) { this.width = options.width || 512; } if (this.height == null) { this.height = options.height || 512; } if (this.channels == null) { this.channels = options.channels || 4; } if (this.backed == null) { this.backed = options.backed || false; } this.samples = this.width * this.height; if (build) { this.build(options); } } shader(shader) { shader.pipe("map.2d.data", this.uniforms); shader.pipe("sample.2d", this.uniforms); if (this.channels < 4) { shader.pipe( UGLSL.swizzleVec4(["0000", "x000", "xw00", "xyz0"][this.channels]) ); } return shader; } build(options) { let klass; this.klass = klass = this.backed ? BackedTexture : DataTexture; this.texture = new klass( this.renderer, this.width, this.height, this.channels, options ); this.uniforms = { dataPointer: { type: "v2", value: new Vector2(0, 0), }, }; this._adopt(this.texture.uniforms); return this.reset(); } reset() { this.rows = []; return (this.bottom = 0); } resize(width, height) { if (!this.backed) { throw new Error("Cannot resize unbacked texture atlas"); } if (width > 2048 && height > 2048) { console.warn(`Giant text atlas ${width}x${height}.`); } else { console.info(`Resizing text atlas ${width}x${height}.`); } this.texture.resize(width, height); this.width = width; this.height = height; return (this.samples = width * height); } collapse(row) { let left; const { rows } = this; rows.splice(rows.indexOf(row), 1); this.bottom = (left = __guard__(rows[rows.length - 1], (x) => x.bottom)) != null ? left : 0; if (this.last === row) { return (this.last = null); } } allocate(key, width, height, emit) { const w = this.width; const h = this.height; const max = height * 2; if (width > w) { this.resize(w * 2, h * 2); this.last = null; // Try again return this.allocate(key, width, height, emit); } // See if we can append to the last used row (fast code path) let row = this.last; if (row != null) { if (row.height >= height && row.height < max && row.width + width <= w) { row.append(key, width, height, emit); return; } } // Scan all rows and append to the first suitable one (slower code path) let bottom = 0; let index = -1; let top = 0; for (let i = 0; i < this.rows.length; i++) { // Measure gap between rows // Note suitable holes for later row = this.rows[i]; const gap = row.top - bottom; if (gap >= height && index < 0) { index = i; top = bottom; } ({ bottom } = row); if (row.height >= height && row.height < max && row.width + width <= w) { row.append(key, width, height, emit); this.last = row; return; } } // New row (slowest path) if (index >= 0) { // Fill a gap row = new Row(top, height); this.rows.splice(index, 0, row); //console.log 'fill gap', row } else { // Append to bottom top = bottom; bottom += height; // Resize if atlas is full if (bottom >= h) { this.resize(w * 2, h * 2); this.last = null; // Try again return this.allocate(key, width, height, emit); } // Add new row to the end row = new Row(top, height); this.rows.push(row); this.bottom = bottom; } row.append(key, width, height, emit); this.last = row; } read() { return this.texture.textureObject; } write(data, x, y, w, h) { return this.texture.write(data, x, y, w, h); } dispose() { this.texture.dispose(); this.data = null; return super.dispose(); } } class Row { constructor(top, height) { this.top = top; this.bottom = top + height; this.width = 0; this.height = height; this.alive = 0; this.keys = []; } append(key, width, height, emit) { const x = this.width; const y = this.top; this.alive++; this.width += width; this.keys.push(key); return emit(this, x, y); } } function __guard__(value, transform) { return typeof value !== "undefined" && value !== null ? transform(value) : undefined; }
cchudzicki/mathbox
src/render/buffer/atlas.js
JavaScript
mit
5,532
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UData from "../../util/data.js"; import { Renderable } from "../renderable.js"; /* * Base class for sample buffers */ export class Buffer extends Renderable { constructor(renderer, shaders, options) { super(renderer, shaders); if (this.items == null) { this.items = options.items || 1; } if (this.samples == null) { this.samples = options.samples || 1; } if (this.channels == null) { this.channels = options.channels || 4; } if (this.callback == null) { this.callback = options.callback || function () {}; } } dispose() { return super.dispose(); } update() { const n = this.fill(); this.write(n); return n; } setActive(_i, _j, _k, _l) {} setCallback(callback) { this.callback = callback; } write() {} fill() {} generate(data) { return UData.getStreamer(data, this.samples, this.channels, this.items); } }
cchudzicki/mathbox
src/render/buffer/buffer.js
JavaScript
mit
1,296
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS202: Simplify dynamic range loops * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UData from "../../util/data.js"; import * as UGLSL from "../../util/glsl.js"; import { Buffer } from "./buffer.js"; import { DataTexture } from "./texture/datatexture.js"; import { Vector2 } from "three/src/math/Vector2.js"; /* * Data buffer on the GPU * - Stores samples (1-n) x items (1-n) x channels (1-4) * - Provides generic sampler shader * - Provides generic copy/write handler * => specialized into Array/Matrix/VoxelBuffer */ export class DataBuffer extends Buffer { constructor(renderer, shaders, options, build) { if (build == null) { build = true; } const width = options.width || 1; const height = options.height || 1; const depth = options.depth || 1; const samples = width * height * depth; if (!options.samples) { options.samples = samples; } super(renderer, shaders, options); this.width = width; this.height = height; this.depth = depth; if (this.samples == null) { this.samples = samples; } if (build) { this.build(options); } } shader(shader, indices) { if (indices == null) { indices = 4; } if (this.items > 1 || this.depth > 1) { if (indices !== 4) { shader.pipe(UGLSL.extendVec(indices, 4)); } shader.pipe("map.xyzw.texture", this.uniforms); } else { if (indices !== 2) { shader.pipe(UGLSL.truncateVec(indices, 2)); } } const wrap = this.wrap ? ".wrap" : ""; shader.pipe(`map.2d.data${wrap}`, this.uniforms); shader.pipe("sample.2d", this.uniforms); if (this.channels < 4) { shader.pipe( UGLSL.swizzleVec4(["0000", "x000", "xw00", "xyz0"][this.channels]) ); } return shader; } build(options) { this.data = new Float32Array(this.samples * this.channels * this.items); this.texture = new DataTexture( this.renderer, this.items * this.width, this.height * this.depth, this.channels, options ); this.filled = 0; this.used = 0; this._adopt(this.texture.uniforms); this._adopt({ dataPointer: { type: "v2", value: new Vector2() }, textureItems: { type: "f", value: this.items }, textureHeight: { type: "f", value: this.height }, }); this.dataPointer = this.uniforms.dataPointer.value; this.streamer = this.generate(this.data); } dispose() { this.data = null; this.texture.dispose(); return super.dispose(); } getFilled() { return this.filled; } setCallback(callback) { this.callback = callback; return (this.filled = 0); } copy(data) { const n = Math.min(data.length, this.samples * this.channels * this.items); const d = this.data; for ( let i = 0, end = n, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { d[i] = data[i]; } this.write(Math.ceil(n / this.channels / this.items)); } write(n) { if (n == null) { n = this.samples; } let height = n / this.width; n *= this.items; const width = height < 1 ? n : this.items * this.width; height = Math.ceil(height); this.texture.write(this.data, 0, 0, width, height); this.dataPointer.set(0.5, 0.5); this.filled = 1; this.used = n; } through(callback, target) { let dst, src; const { consume, done } = (src = this.streamer); const { emit } = (dst = target.streamer); let i = 0; let pipe = () => consume((x, y, z, w) => callback(emit, x, y, z, w, i)); pipe = UData.repeatCall(pipe, this.items); return () => { src.reset(); dst.reset(); const limit = this.used; i = 0; while (!done() && i < limit) { pipe(); i++; } return src.count(); }; } }
cchudzicki/mathbox
src/render/buffer/databuffer.js
JavaScript
mit
4,188
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS104: Avoid inline assignments * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { DataBuffer } from "./databuffer.js"; /* * 4D array */ export class ItemBuffer extends DataBuffer { build(_options) { super.build(); this.pad = { x: 0, y: 0, z: 0, w: 0 }; return (this.streamer = this.generate(this.data)); } getFilled() { return this.filled; } setActive(i, j, k, l) { let ref; return ( ([this.pad.x, this.pad.y, this.pad.z, this.pad.w] = Array.from( (ref = [ this.width - i, this.height - j, this.depth - k, this.items - l, ]) )), ref ); } fill() { let j, k, l, repeat; const { callback } = this; if (typeof callback.reset === "function") { callback.reset(); } const { emit, skip, count, done, reset } = this.streamer; reset(); const n = this.width; let m = this.height; const p = this.items; const padX = this.pad.x; const padY = this.pad.y; const padW = this.pad.w; const limit = (this.samples - this.pad.z * n * m) * p; let i = (j = k = l = m = 0); if (padX > 0 || padY > 0 || padW > 0) { while (!done() && m < limit) { m++; repeat = callback(emit, i, j, k, l); if (++l === p - padW) { skip(padW); l = 0; if (++i === n - padX) { skip(p * padX); i = 0; if (++j === m - padY) { skip(p * n * padY); j = 0; k++; } } } if (repeat === false) { break; } } } else { while (!done() && m < limit) { m++; repeat = callback(emit, i, j, k, l); if (++l === p) { l = 0; if (++i === n) { i = 0; if (++j === m) { j = 0; k++; } } } if (repeat === false) { break; } } } return Math.floor(count() / this.items); } }
cchudzicki/mathbox
src/render/buffer/itembuffer.js
JavaScript
mit
2,382
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS104: Avoid inline assignments * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UData from "../../util/data.js"; import { DataBuffer } from "./databuffer.js"; /* * 2D + history array */ export class MatrixBuffer extends DataBuffer { constructor(renderer, shaders, options) { const width = options.width || 1; const height = options.height || 1; const history = options.history || 1; options.depth = history; super(renderer, shaders, options, false); this.width = width; this.height = height; this.history = history; this.samples = width * height; this.wrap = history > 1; this.build(options); } build(_options) { super.build(); this.index = 0; this.pad = { x: 0, y: 0 }; return (this.streamer = this.generate(this.data)); } getFilled() { return this.filled; } setActive(i, j) { let ref; return ( ([this.pad.x, this.pad.y] = Array.from( (ref = [Math.max(0, this.width - i), Math.max(0, this.height - j)]) )), ref ); } fill() { let j, k, repeat; const { callback } = this; if (typeof callback.reset === "function") { callback.reset(); } const { emit, skip, count, done, reset } = this.streamer; reset(); const n = this.width; const pad = this.pad.x; const limit = this.samples - this.pad.y * n; let i = (j = k = 0); if (pad) { while (!done() && k < limit) { k++; repeat = callback(emit, i, j); if (++i === n - pad) { skip(pad); i = 0; j++; } if (repeat === false) { break; } } } else { while (!done() && k < limit) { k++; repeat = callback(emit, i, j); if (++i === n) { i = 0; j++; } if (repeat === false) { break; } } } return Math.floor(count() / this.items); } write(n) { if (n == null) { n = this.samples; } n *= this.items; const width = this.width * this.items; const height = Math.ceil(n / width); this.texture.write(this.data, 0, this.index * this.height, width, height); this.dataPointer.set(0.5, this.index * this.height + 0.5); this.index = (this.index + this.history - 1) % this.history; return (this.filled = Math.min(this.history, this.filled + 1)); } through(callback, target) { let dst, j, src; const { consume, skip, done } = (src = this.streamer); const { emit } = (dst = target.streamer); let i = (j = 0); let pipe = () => consume((x, y, z, w) => callback(emit, x, y, z, w, i, j)); pipe = UData.repeatCall(pipe, this.items); return () => { let k; src.reset(); dst.reset(); const n = this.width; const pad = this.pad.x; const limit = this.samples - this.pad.y * n; i = j = k = 0; if (pad) { while (!done() && k < limit) { k++; pipe(); if (++i === n - pad) { skip(pad); i = 0; j++; } } } else { while (!done() && k < limit) { k++; pipe(); if (++i === n) { i = 0; j++; } } } return src.count(); }; } }
cchudzicki/mathbox
src/render/buffer/matrixbuffer.js
JavaScript
mit
3,709
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { RGBAFormat } from "three/src/constants.js"; import { RenderToTexture } from "./rendertotexture.js"; /* * Wrapped RTT for memoizing 4D arrays back to a 2D texture */ export class Memo extends RenderToTexture { constructor(renderer, shaders, options) { let _height, _width; const items = options.items || 1; const channels = options.channels || 4; const width = options.width || 1; const height = options.height || 1; const depth = options.depth || 1; //options.format = [null, THREE.LuminanceFormat, THREE.LuminanceAlphaFormat, THREE.RGBFormat, THREE.RGBAFormat][@channels] options.format = RGBAFormat; options.width = _width = items * width; options.height = _height = height * depth; options.frames = 1; delete options.items; delete options.depth; delete options.channels; super(renderer, shaders, options); if (this.items == null) { this.items = items; } if (this.channels == null) { this.channels = channels; } if (this.width == null) { this.width = width; } this._width = _width; if (this.height == null) { this.height = height; } this._height = _height; if (this.depth == null) { this.depth = depth; } this._adopt({ textureItems: { type: "f", value: this.items }, textureHeight: { type: "f", value: this.height }, }); } shaderAbsolute(shader) { if (shader == null) { shader = this.shaders.shader(); } shader.pipe("map.xyzw.texture", this.uniforms); return super.shaderAbsolute(shader, 1, 2); } } //shader.pipe Util.GLSL.swizzleVec4 ['0000', 'x000', 'xw00', 'xyz0'][@channels] if @channels < 4
cchudzicki/mathbox
src/render/buffer/memo.js
JavaScript
mit
2,064
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS104: Avoid inline assignments * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Buffer } from "./buffer.js"; /* * Buffer for CPU-side use */ export class PushBuffer extends Buffer { constructor(renderer, shaders, options) { const width = options.width || 1; const height = options.height || 1; const depth = options.depth || 1; const samples = width * height * depth; if (!options.samples) { options.samples = samples; } super(renderer, shaders, options); this.width = width; this.height = height; this.depth = depth; if (this.samples == null) { this.samples = samples; } this.build(options); } build(_options) { this.data = []; this.data.length = this.samples; this.filled = 0; this.pad = { x: 0, y: 0, z: 0 }; return (this.streamer = this.generate(this.data)); } dispose() { this.data = null; return super.dispose(); } getFilled() { return this.filled; } setActive(i, j, k) { let ref; return ( ([this.pad.x, this.pad.y, this.pad.z] = Array.from( (ref = [this.width - i, this.height - j, this.depth - k]) )), ref ); } read() { return this.data; } copy(data) { const n = Math.min(data.length, this.samples); const d = this.data; return __range__(0, n, false).map((i) => (d[i] = data[i])); } fill() { let j, k, l, repeat; const { callback } = this; if (typeof callback.reset === "function") { callback.reset(); } const { emit, skip, count, done, reset } = this.streamer; reset(); const n = this.width; const m = this.height; const padX = this.pad.x; const padY = this.pad.y; const limit = this.samples - this.pad.z * n * m; let i = (j = k = l = 0); if (padX > 0 || padY > 0) { while (!done() && l < limit) { l++; repeat = callback(emit, i, j, k); if (++i === n - padX) { skip(padX); i = 0; if (++j === m - padY) { skip(n * padY); j = 0; k++; } } if (repeat === false) { break; } } } else { while (!done() && l < limit) { l++; repeat = callback(emit, i, j, k); if (++i === n) { i = 0; if (++j === m) { j = 0; k++; } } if (repeat === false) { break; } } } this.filled = 1; return count(); } } function __range__(left, right, inclusive) { const range = []; const ascending = left < right; const end = !inclusive ? right : ascending ? right + 1 : right - 1; for (let i = left; ascending ? i < end : i > end; ascending ? i++ : i--) { range.push(i); } return range; }
cchudzicki/mathbox
src/render/buffer/pushbuffer.js
JavaScript
mit
3,193
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS104: Avoid inline assignments * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UData from "../../util/data.js"; import * as UGLSL from "../../util/glsl.js"; import { FloatType, UnsignedByteType } from "three/src/constants.js"; import { Memo } from "./memo.js"; import { MemoScreen } from "../meshes/memoscreen.js"; import { Renderable } from "../renderable.js"; import { Vector4 } from "three/src/math/Vector4.js"; /* * Readback up to 4D array of up to 4D data from GL */ export class Readback extends Renderable { constructor(renderer, shaders, options) { super(renderer, shaders); if (this.items == null) { this.items = options.items || 1; } if (this.channels == null) { this.channels = options.channels || 4; } if (this.width == null) { this.width = options.width || 1; } if (this.height == null) { this.height = options.height || 1; } if (this.depth == null) { this.depth = options.depth || 1; } if (this.type == null) { this.type = options.type || FloatType; } if (this.stpq == null) { this.stpq = options.stpq || false; } this.isFloat = this.type === FloatType; this.active = this.sampled = this.rect = this.pad = null; this.build(options); /* * log precision gl = @gl for name, pass of {Vertex: gl.VERTEX_SHADER, Fragment: gl.FRAGMENT_SHADER} bits = for prec in [gl.LOW_FLOAT, gl.MEDIUM_FLOAT, gl.HIGH_FLOAT] gl.getShaderPrecisionFormat(pass, prec).precision console.log name, 'shader precision', bits */ } build(options) { let channels, encoder, stretch; const { map } = options; const { indexer } = options; const isIndexed = indexer != null && !indexer.empty(); let { stpq } = this; const { items, width, height, depth } = this; let sampler = map; if (isIndexed) { // Preserve original xyzw offset of datapoint to tie it back to the source // Modulus to pack xyzw into a single integer index this._adopt({ indexModulus: { type: "v4", value: new Vector4(items, items * width, items * width * height, 1), }, }); // Build shader to pack XYZ + index into a single RGBA sampler = this.shaders.shader(); sampler.require(map); sampler.require(indexer); //sampler.require UGLSL.identity 'vec4' sampler.pipe("float.index.pack", this.uniforms); } if (this.isFloat && this.channels > 1) { // Memoize multi-channel float data into float buffer first this.floatMemo = new Memo(this.renderer, this.shaders, { items, channels: 4, // non-RGBA render target not supported width, height, depth, history: 0, type: FloatType, }); this.floatCompose = new MemoScreen(this.renderer, this.shaders, { map: sampler, items, width, height, depth, stpq, }); this.floatMemo.adopt(this.floatCompose); // Second pass won't need texture coordinates stpq = false; // Replace sampler with memoized sampler sampler = this.shaders.shader(); this.floatMemo.shaderAbsolute(sampler); } if (this.isFloat) { // Encode float data into byte buffer stretch = this.channels; channels = 4; // one 32-bit float per pixel } else { // Render byte data directly stretch = 1; channels = this.channels; } if (stretch > 1) { // Stretch horizontally, sampling once per channel encoder = this.shaders.shader(); encoder.pipe(UGLSL.mapByte2FloatOffset(stretch)); encoder.require(sampler); encoder.pipe("float.stretch"); encoder.pipe("float.encode"); sampler = encoder; } else if (this.isFloat) { // Direct sampling encoder = this.shaders.shader(); encoder.pipe(sampler); encoder.pipe(UGLSL.truncateVec(4, 1)); encoder.pipe("float.encode"); sampler = encoder; } // Memoize byte data this.byteMemo = new Memo(this.renderer, this.shaders, { items: items * stretch, channels: channels, // non-RGBA render target not supported width, height, depth, history: 0, type: UnsignedByteType, }); this.byteCompose = new MemoScreen(this.renderer, this.shaders, { map: sampler, items: items * stretch, width, height, depth, stpq, }); this.byteMemo.adopt(this.byteCompose); // CPU-side buffers const w = items * width * stretch; const h = height * depth; this.samples = this.width * this.height * this.depth; this.bytes = new Uint8Array(w * h * 4); // non-RGBA render target not supported if (this.isFloat) { this.floats = new Float32Array(this.bytes.buffer); } this.data = this.isFloat ? this.floats : this.bytes; this.streamer = this.generate(this.data); this.active = { items: 0, width: 0, height: 0, depth: 0 }; this.sampled = { items: 0, width: 0, height: 0, depth: 0 }; this.rect = { w: 0, h: 0 }; this.pad = { x: 0, y: 0, z: 0, w: 0 }; this.stretch = stretch; this.isIndexed = isIndexed; return this.setActive(items, width, height, depth); } generate(data) { return UData.getStreamer(data, this.samples, 4, this.items); } // non-RGBA render target not supported setActive(items, width, height, depth) { let ref; if ( items === this.active.items && width === this.active.width && height === this.active.height && depth === this.active.depth ) { return; } // Actively sampled area [ this.active.items, this.active.width, this.active.height, this.active.depth, ] = Array.from([items, width, height, depth]); // Render only necessary samples in RTTs if (this.floatCompose != null) { this.floatCompose.cover(width, height, depth); } if (this.byteCompose != null) { this.byteCompose.cover(width * this.stretch, height, depth); } // Calculate readback buffer geometry ({ items } = this); ({ width } = this.active); height = this.depth === 1 ? this.active.height : this.height; ({ depth } = this.active); const w = items * width * this.stretch; const h = height * depth; // Calculate array paddings on readback [ this.sampled.items, this.sampled.width, this.sampled.height, this.sampled.depth, ] = Array.from([items, width, height, depth]); [this.rect.w, this.rect.h] = Array.from([w, h]); return ( ([this.pad.x, this.pad.y, this.pad.z, this.pad.w] = Array.from( (ref = [ this.sampled.width - this.active.width, this.sampled.height - this.active.height, this.sampled.depth - this.active.depth, this.sampled.items - this.active.items, ]) )), ref ); } update(camera) { if (this.floatMemo != null) { this.floatMemo.render(camera); } return this.byteMemo != null ? this.byteMemo.render(camera) : undefined; } post() { const currentTarget = this.renderer.getRenderTarget(); this.renderer.setRenderTarget(this.byteMemo.target.targets[0]); this.gl.readPixels( 0, 0, this.rect.w, this.rect.h, this.gl.RGBA, this.gl.UNSIGNED_BYTE, this.bytes ); this.renderer.setRenderTarget(currentTarget); } readFloat(n) { return this.floatMemo != null ? this.floatMemo.read(n) : undefined; } readByte(n) { return this.byteMemo != null ? this.byteMemo.read(n) : undefined; } setCallback(callback) { this.emitter = this.callback(callback); } callback(callback) { if (!this.isIndexed) { return callback; } const n = this.width; const m = this.height; const p = this.items; // Decode packed index const f = function (x, y, z, w) { let idx = w; const ll = idx % p; idx = (idx - ll) / p; const ii = idx % n; idx = (idx - ii) / n; const jj = idx % m; idx = (idx - jj) / m; const kk = idx; return callback(x, y, z, w, ii, jj, kk, ll); }; f.reset = () => typeof callback.reset === "function" ? callback.reset() : undefined; return f; } iterate() { let j, k, l; let emit = this.emitter; if (typeof emit.reset === "function") { emit.reset(); } const { consume, skip, count, done, reset } = this.streamer; reset(); const n = this.sampled.width | 0; let m = this.sampled.height | 0; const o = this.sampled.depth | 0; const p = this.sampled.items | 0; const padX = this.pad.x | 0; const padY = this.pad.y | 0; const padZ = this.pad.z | 0; const padW = this.pad.w | 0; const limit = n * m * p * (o - padZ); if (!this.isIndexed) { const callback = emit; emit = (x, y, z, w) => callback(x, y, z, w, i, j, k, l); } let i = (j = k = l = m = 0); while (!done() && m < limit) { m++; const repeat = consume(emit); if (++l === p - padW) { skip(padX); l = 0; if (++i === n - padX) { skip(p * padX); i = 0; if (++j === m - padY) { skip(p * n * padY); j = 0; k++; } } } if (repeat === false) { break; } } return Math.floor(count() / p); } dispose() { if (this.floatMemo != null) { this.floatMemo.unadopt(this.floatCompose); } if (this.floatMemo != null) { this.floatMemo.dispose(); } if (this.floatCompose != null) { this.floatCompose.dispose(); } if (this.byteMemo != null) { this.byteMemo.unadopt(this.byteCompose); } if (this.byteMemo != null) { this.byteMemo.dispose(); } if (this.byteCompose != null) { this.byteCompose.dispose(); } return (this.floatMemo = this.byteMemo = this.floatCompose = this.byteCompose = null); } }
cchudzicki/mathbox
src/render/buffer/readback.js
JavaScript
mit
10,500
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UGLSL from "../../util/glsl.js"; import { PerspectiveCamera } from "three/src/cameras/PerspectiveCamera.js"; import { RenderTarget } from "./texture/rendertarget.js"; import { Renderable } from "../renderable.js"; import { Scene } from "three/src/scenes/Scene.js"; import { Vector2 } from "three/src/math/Vector2.js"; import { Vector3 } from "three/src/math/Vector3.js"; /* * Render-To-Texture with history */ export class RenderToTexture extends Renderable { constructor(renderer, shaders, options) { super(renderer, shaders); this.scene = options.scene != null ? options.scene : new Scene(); this.camera = options.camera; this.build(options); } shaderRelative(shader) { if (shader == null) { shader = this.shaders.shader(); } return shader.pipe("sample.2d", this.uniforms); } shaderAbsolute(shader, frames, indices) { if (frames == null) { frames = 1; } if (indices == null) { indices = 4; } if (shader == null) { shader = this.shaders.shader(); } if (frames <= 1) { if (indices > 2) { shader.pipe(UGLSL.truncateVec(indices, 2)); } shader.pipe("map.2d.data", this.uniforms); return shader.pipe("sample.2d", this.uniforms); } else { const sample2DArray = UGLSL.sample2DArray( Math.min(frames, this.target.frames) ); if (indices < 4) { shader.pipe(UGLSL.extendVec(indices, 4)); } shader.pipe("map.xyzw.2dv"); shader.split(); shader.pipe("map.2d.data", this.uniforms); shader.pass(); return shader.pipe(sample2DArray, this.uniforms); } } build(options) { if (!this.camera) { this.camera = new PerspectiveCamera(); this.camera.position.set(0, 0, 3); this.camera.lookAt(new Vector3()); } if (typeof this.scene.inject === "function") { this.scene.inject(); } this.target = new RenderTarget( this.gl, options.width, options.height, options.frames, options ); this.target.warmup((target) => this.renderer.setRenderTarget(target)); this.renderer.setRenderTarget(null); this._adopt(this.target.uniforms); this._adopt({ dataPointer: { type: "v2", value: new Vector2(0.5, 0.5), }, }); return (this.filled = 0); } adopt(renderable) { return Array.from(renderable.renders).map((object) => this.scene.add(object) ); } unadopt(renderable) { return Array.from(renderable.renders).map((object) => this.scene.remove(object) ); } render(camera) { if (camera == null) { ({ camera } = this); } const currentTarget = this.renderer.getRenderTarget(); this.renderer.setRenderTarget(this.target.write); this.renderer.render( this.scene.scene != null ? this.scene.scene : this.scene, camera ); this.renderer.setRenderTarget(currentTarget); this.target.cycle(); if (this.filled < this.target.frames) { return this.filled++; } } read(frame) { if (frame == null) { frame = 0; } return this.target.reads[Math.abs(frame)]; } getFrames() { return this.target.frames; } getFilled() { return this.filled; } dispose() { if (typeof this.scene.unject === "function") { this.scene.unject(); } this.scene = this.camera = null; this.target.dispose(); return super.dispose(); } }
cchudzicki/mathbox
src/render/buffer/rendertotexture.js
JavaScript
mit
3,888
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS104: Avoid inline assignments * DS202: Simplify dynamic range loops * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Atlas } from "./atlas.js"; import { UnsignedByteType } from "three/src/constants.js"; const SCRATCH_SIZE = 512 / 16; /* * Dynamic text atlas * - Stores entire strings as sprites * - Renders alpha mask (fast) or signed distance field (slow) * - Emits (x,y,width,height) pointers into the atlas */ export class TextAtlas extends Atlas { constructor(renderer, shaders, options) { let left; if (!options.width) { options.width = 256; } if (!options.height) { options.height = 256; } options.type = UnsignedByteType; options.channels = 1; options.backed = true; super(renderer, shaders, options, false); this.font = options.font != null ? options.font : ["sans-serif"]; this.size = options.size || 24; this.style = options.style != null ? options.style : "normal"; this.variant = options.variant != null ? options.variant : "normal"; this.weight = options.weight != null ? options.weight : "normal"; this.outline = (left = +(options.outline != null ? options.outline : 5)) != null ? left : 0; this.gamma = 1; if (typeof navigator !== "undefined") { const ua = navigator.userAgent; if (ua.match(/Chrome/) && ua.match(/OS X/)) { this.gamma = 0.5; } } this.scratchW = this.scratchH = 0; this.build(options); } build(options) { super.build(options); // Prepare line-height with room for outline let lineHeight = 16; lineHeight = this.size; lineHeight += 4 + 2 * Math.min(1, this.outline); const maxWidth = SCRATCH_SIZE * lineHeight; // Prepare scratch canvas const canvas = document.createElement("canvas"); canvas.width = maxWidth; canvas.height = lineHeight; const quote = (str) => `${str.replace(/(['"\\])/g, "\\$1")}`; const font = this.font.map(quote).join(", "); const context = canvas.getContext("2d"); context.font = `${this.style} ${this.variant} ${this.weight} ${this.size}px ${font}`; context.fillStyle = "#FF0000"; context.textAlign = "left"; context.textBaseline = "bottom"; context.lineJoin = "round"; // debug: show scratch canvas /* document.body.appendChild canvas canvas.setAttribute('style', "position: absolute; top: 0; left: 0; z-index: 100; border: 1px solid red; background: rgba(255,0,255,.25);") */ // Cache hex colors for distance field rendering const colors = []; const dilate = this.outline * 3; for ( let i = 0, end = dilate, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { // 8 rgb levels = 1 step = .5 pixel increase const hex = ( "00" + Math.max(0, -i * 8 + 128 - !i * 8).toString(16) ).slice(-2); colors.push("#" + hex + hex + hex); } const scratch = new Uint8Array(maxWidth * lineHeight * 2); this.canvas = canvas; this.context = context; this.lineHeight = lineHeight; this.maxWidth = maxWidth; this.colors = colors; this.scratch = scratch; this._allocate = this.allocate.bind(this); return (this._write = this.write.bind(this)); } reset() { super.reset(); return (this.mapped = {}); } begin() { return Array.from(this.rows).map((row) => (row.alive = 0)); } end() { const { mapped } = this; for (const row of Array.from(this.rows.slice())) { if (row.alive === 0) { for (const key of Array.from(row.keys)) { delete mapped[key]; } this.collapse(row); } } } map(text, emit) { // See if already mapped into atlas const { mapped } = this; const c = mapped[text]; if (c != null) { c.row.alive++; return emit(c.x, c.y, c.w, c.h); } // Draw text (don't recurse stack in @draw so it can be optimized cleanly) this.draw(text); const data = this.scratch; const w = this.scratchW; const h = this.scratchH; // Allocate and write into atlas const allocate = this._allocate; const write = this._write; return allocate(text, w, h, function (row, x, y) { mapped[text] = { x, y, w, h, row }; write(data, x, y, w, h); return emit(x, y, w, h); }); } draw(text) { let data, i, j; let w = this.width; const h = this.lineHeight; const o = this.outline; const ctx = this.context; const dst = this.scratch; const max = this.maxWidth; const { colors } = this; // Bottom aligned const x = o + 1; const y = Math.round(h * 1.05 - 1); // Measure text const m = ctx.measureText(text); w = Math.min(max, Math.ceil(m.width + 2 * x + 1)); // Clear scratch area ctx.clearRect(0, 0, w, h); if (this.outline === 0) { // Alpha sprite (fast) let asc, end; ctx.fillText(text, x, y); ({ data } = ctx.getImageData(0, 0, w, h)); j = 3; // Skip to alpha channel for ( i = 0, end = data.length / 4, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { //dst[i] = 255 * (i%2); # test pattern to check pixel perfect alignment dst[i] = data[j]; j += 4; } this.scratchW = w; return (this.scratchH = h); } else { // Signed distance field sprite (approximation) (slow) // Draw strokes of decreasing width to create nested outlines (absolute distance) let asc1, start; let asc2, end1; ctx.globalCompositeOperation = "source-over"; for ( start = o + 1, i = start, asc1 = start <= 1; asc1 ? i <= 1 : i >= 1; asc1 ? i++ : i-- ) { j = i > 1 ? i * 2 - 2 : i; // Eliminate odd strokes once past > 1px, don't need the detail ctx.strokeStyle = colors[j - 1]; ctx.lineWidth = j; ctx.strokeText(text, x, y); } //console.log 'stroke', j, j+.5, colors[j] // Fill center with multiply blend #FF0000 to mark inside/outside ctx.globalCompositeOperation = "multiply"; ctx.fillText(text, x, y); // Pull image data ({ data } = ctx.getImageData(0, 0, w, h)); j = 0; const { gamma } = this; for ( i = 0, end1 = data.length / 4, asc2 = 0 <= end1; asc2 ? i < end1 : i > end1; asc2 ? i++ : i-- ) { // Get value + mask const a = data[j]; let mask = a ? data[j + 1] / a : 1; if (gamma === 0.5) { mask = Math.sqrt(mask); } mask = Math.min(1, Math.max(0, mask)); // Blend between positive/outside and negative/inside const b = 256 - a; const c = b + (a - b) * mask; // Clamp // (slight expansion to hide errors around the transition) dst[i] = Math.max(0, Math.min(255, c + 2)); j += 4; } // Debug: copy back into canvas // // TODO hide behind debug flag or delete. /* j = 0 for i in [0...data.length / 4] v = dst[i] *data[j] = v *data[j+1] = v data[j+2] = v data[j+3] = 255 j += 4 ctx.putImageData(imageData, 0, 0); */ this.scratchW = w; return (this.scratchH = h); } } }
cchudzicki/mathbox
src/render/buffer/textatlas.js
JavaScript
mit
7,702
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { DataTexture } from "./datatexture.js"; /* Manually allocated GL texture for data streaming, locally backed. Allows partial updates via subImage. Contains local copy of its data to allow quick resizing without gl.copyTexImage2d (which requires render-to-framebuffer) */ export class BackedTexture extends DataTexture { constructor(renderer, width, height, channels, options) { super(renderer, width, height, channels, options); this.data = new this.ctor(this.n); } resize(width, height) { const old = this.data; const oldWidth = this.width; const oldHeight = this.height; this.width = width; this.height = height; this.n = width * height * this.channels; this.data = new this.ctor(this.n); const { gl } = this; const state = this.renderer.state; state.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); gl.texImage2D( gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, this.data ); this.uniforms.dataResolution.value.set(1 / width, 1 / height); return this.write(old, 0, 0, oldWidth, oldHeight); } write(src, x, y, w, h) { let j; const { width } = this; const dst = this.data; const { channels } = this; let i = 0; if (width === w && x === 0) { j = y * w * channels; const n = w * h * channels; while (i < n) { dst[j++] = src[i++]; } } else { const stride = width * channels; const ww = w * channels; const xx = x * channels; let yy = y; const yh = y + h; while (yy < yh) { let k = 0; j = xx + yy * stride; while (k++ < ww) { dst[j++] = src[i++]; } yy++; } } return super.write(src, x, y, w, h); } dispose() { this.data = null; return super.dispose(); } }
cchudzicki/mathbox
src/render/buffer/texture/backedtexture.js
JavaScript
mit
2,240
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as CONST from "three/src/constants.js"; import * as UThree from "../../../util/three.js"; import { Texture } from "three/src/textures/Texture.js"; import { Vector2 } from "three/src/math/Vector2.js"; /* Manually allocated GL texture for data streaming. Allows partial updates via subImage. */ export class DataTexture { constructor(renderer, width, height, channels, options) { this.renderer = renderer; this.width = width; this.height = height; this.channels = channels; this.n = this.width * this.height * this.channels; const gl = this.renderer.getContext(); this.gl = gl; const minFilter = (options != null ? options.minFilter : undefined) != null ? options != null ? options.minFilter : undefined : CONST.NearestFilter; const magFilter = (options != null ? options.magFilter : undefined) != null ? options != null ? options.magFilter : undefined : CONST.NearestFilter; const type = (options != null ? options.type : undefined) != null ? options != null ? options.type : undefined : CONST.FloatType; this.minFilter = UThree.paramToGL(gl, minFilter); this.magFilter = UThree.paramToGL(gl, magFilter); this.type = UThree.paramToGL(gl, type); this.ctor = UThree.paramToArrayStorage(type); this.build(options); } build(options) { const { gl } = this; const state = this.renderer.state; // Make GL texture this.texture = gl.createTexture(); this.format = [null, gl.LUMINANCE, gl.LUMINANCE_ALPHA, gl.RGB, gl.RGBA][ this.channels ]; this.format3 = [ null, CONST.LuminanceFormat, CONST.LuminanceAlphaFormat, CONST.RGBFormat, CONST.RGBAFormat, ][this.channels]; state.bindTexture(gl.TEXTURE_2D, this.texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.minFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.magFilter); // Attach empty data this.data = new this.ctor(this.n); gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); gl.texImage2D( gl.TEXTURE_2D, 0, this.format, this.width, this.height, 0, this.format, this.type, this.data ); // Make wrapper texture object. this.textureObject = new Texture( new Image(), CONST.UVMapping, CONST.ClampToEdgeWrapping, CONST.ClampToEdgeWrapping, options != null ? options.minFilter : undefined, options != null ? options.magFilter : undefined ); // Pre-init texture to trick WebGLRenderer this.textureProperties = this.renderer.properties.get(this.textureObject); this.textureProperties.__webglInit = true; this.textureProperties.__webglTexture = this.texture; this.textureObject.format = this.format3; this.textureObject.type = CONST.FloatType; this.textureObject.unpackAlignment = 1; this.textureObject.flipY = false; this.textureObject.generateMipmaps = false; // Create uniforms this.uniforms = { dataResolution: { type: "v2", value: new Vector2(1 / this.width, 1 / this.height), }, dataTexture: { type: "t", value: this.textureObject, }, }; } write(data, x, y, w, h) { const { gl } = this; const state = this.renderer.state; // Write to rectangle state.bindTexture(gl.TEXTURE_2D, this.texture); gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); return gl.texSubImage2D( gl.TEXTURE_2D, 0, x, y, w, h, this.format, this.type, data ); } dispose() { this.gl.deleteTexture(this.texture); this.textureProperties.__webglInit = false; this.textureProperties.__webglTexture = null; this.textureProperties = null; return (this.textureObject = this.texture = null); } }
cchudzicki/mathbox
src/render/buffer/texture/datatexture.js
JavaScript
mit
4,573
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS202: Simplify dynamic range loops * DS205: Consider reworking code to avoid use of IIFEs * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ /* Virtual RenderTarget that cycles through multiple frames Provides easy access to past rendered frames @reads[] and @write contain WebGLRenderTargets whose internal pointers are rotated automatically */ import { NearestFilter, RGBAFormat, UnsignedByteType, } from "three/src/constants.js"; import { Vector2 } from "three/src/math/Vector2.js"; import { WebGLRenderTarget } from "three/src/renderers/WebGLRenderTarget.js"; export class RenderTarget { constructor(gl, width, height, frames, options) { this.gl = gl; if (options == null) { options = {}; } if (options.minFilter == null) { options.minFilter = NearestFilter; } if (options.magFilter == null) { options.magFilter = NearestFilter; } if (options.format == null) { options.format = RGBAFormat; } if (options.type == null) { options.type = UnsignedByteType; } this.options = options; this.width = width || 1; this.height = height || 1; this.frames = frames || 1; this.buffers = this.frames + 1; this.build(); } build() { let i; const make = () => new WebGLRenderTarget(this.width, this.height, this.options); this.targets = (() => { let asc, end; const result = []; for ( i = 0, end = this.buffers, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { result.push(make()); } return result; })(); const acc = []; this.targets.forEach((target) => acc.push(target.texture)); this.reads = acc; this.write = this.targets[this.buffers - 1]; // Texture access uniforms this.uniforms = { dataResolution: { type: "v2", value: new Vector2(1 / this.width, 1 / this.height), }, dataTexture: { type: "t", value: this.reads[0], }, dataTextures: { type: "tv", value: this.reads, }, }; } cycle() { this.targets.unshift(this.targets.pop()); this.write = this.targets[this.buffers - 1]; this.reads.unshift(this.reads.pop()); this.uniforms.dataTexture.value = this.reads[0]; } warmup(callback) { return (() => { const result = []; for ( let i = 0, end = this.buffers, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { callback(this.write); result.push(this.cycle()); } return result; })(); } dispose() { for (const target of Array.from(this.targets)) { target.dispose(); } return (this.targets = this.reads = this.write = null); } }
cchudzicki/mathbox
src/render/buffer/texture/rendertarget.js
JavaScript
mit
3,143
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS104: Avoid inline assignments * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UData from "../../util/data.js"; import { DataBuffer } from "./databuffer.js"; // // 3D array // export class VoxelBuffer extends DataBuffer { build(_options) { super.build(); this.pad = { x: 0, y: 0, z: 0 }; return (this.streamer = this.generate(this.data)); } setActive(i, j, k) { let ref; return ( ([this.pad.x, this.pad.y, this.pad.z] = Array.from( (ref = [ Math.max(0, this.width - i), Math.max(0, this.height - j), Math.max(0, this.depth - k), ]) )), ref ); } fill() { let j, k, l, repeat; const { callback } = this; if (typeof callback.reset === "function") { callback.reset(); } const { emit, skip, count, done, reset } = this.streamer; reset(); const n = this.width; const m = this.height; const padX = this.pad.x; const padY = this.pad.y; const limit = this.samples - this.pad.z * n * m; let i = (j = k = l = 0); if (padX > 0 || padY > 0) { while (!done() && l < limit) { l++; repeat = callback(emit, i, j, k); if (++i === n - padX) { skip(padX); i = 0; if (++j === m - padY) { skip(n * padY); j = 0; k++; } } if (repeat === false) { break; } } } else { while (!done() && l < limit) { l++; repeat = callback(emit, i, j, k); if (++i === n) { i = 0; if (++j === m) { j = 0; k++; } } if (repeat === false) { break; } } } return Math.floor(count() / this.items); } through(callback, target) { // must be identical sized buffers w/ identical active areas let dst, j, k, src; const { consume, done, skip } = (src = this.streamer); const { emit } = (dst = target.streamer); let i = (j = k = 0); let pipe = () => consume((x, y, z, w) => callback(emit, x, y, z, w, i, j, k)); pipe = UData.repeatCall(pipe, this.items); return () => { let l; src.reset(); dst.reset(); const n = this.width; const m = this.height; const padX = this.pad.x; const padY = this.pad.y; const limit = this.samples - this.pad.z * n * m; i = j = k = l = 0; if (padX > 0 || padY > 0) { while (!done() && l < limit) { l++; pipe(); if (++i === n - padX) { skip(padX); i = 0; if (++j === m - padY) { skip(n * padY); j = 0; k++; } } } } else { while (!done() && l < limit) { l++; pipe(); if (++i === n) { i = 0; if (++j === m) { j = 0; k++; } } } } return src.count(); }; } }
cchudzicki/mathbox
src/render/buffer/voxelbuffer.js
JavaScript
mit
3,390
import { ArrayBuffer_ } from "./buffer/arraybuffer.js"; import { Arrow } from "./meshes/arrow.js"; import { Atlas } from "./buffer/atlas.js"; import { DataBuffer } from "./buffer/databuffer.js"; import { Debug } from "./meshes/debug.js"; import { Face } from "./meshes/face.js"; import { Line } from "./meshes/line.js"; import { MatrixBuffer } from "./buffer/matrixbuffer.js"; import { Memo } from "./buffer/memo.js"; import { MemoScreen } from "./meshes/memoscreen.js"; import { Point } from "./meshes/point.js"; import { PushBuffer } from "./buffer/pushbuffer.js"; import { Readback } from "./buffer/readback.js"; import { RenderToTexture } from "./buffer/rendertotexture.js"; import { Scene } from "./scene.js"; import { Screen } from "./meshes/screen.js"; import { Sprite } from "./meshes/sprite.js"; import { Strip } from "./meshes/strip.js"; import { Surface } from "./meshes/surface.js"; import { TextAtlas } from "./buffer/textatlas.js"; import { VoxelBuffer } from "./buffer/voxelbuffer.js"; export const Classes = { sprite: Sprite, point: Point, line: Line, surface: Surface, face: Face, strip: Strip, arrow: Arrow, screen: Screen, memoScreen: MemoScreen, debug: Debug, dataBuffer: DataBuffer, arrayBuffer: ArrayBuffer_, matrixBuffer: MatrixBuffer, voxelBuffer: VoxelBuffer, pushBuffer: PushBuffer, renderToTexture: RenderToTexture, memo: Memo, readback: Readback, atlas: Atlas, textAtlas: TextAtlas, scene: Scene, };
cchudzicki/mathbox
src/render/classes.js
JavaScript
mit
1,471
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ export class RenderFactory { constructor(classes, renderer, shaders) { this.classes = classes; this.renderer = renderer; this.shaders = shaders; } getTypes() { return Object.keys(this.classes); } make(type, options) { return new this.classes[type](this.renderer, this.shaders, options); } }
cchudzicki/mathbox
src/render/factory.js
JavaScript
mit
631
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS202: Simplify dynamic range loops * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { BufferAttribute } from "three/src/core/BufferAttribute.js"; import { ClipGeometry } from "./clipgeometry.js"; /* Cones to attach as arrowheads on line strips .....> .....> .....> .....> .....> .....> .....> .....> .....> .....> .....> .....> */ export class ArrowGeometry extends ClipGeometry { constructor(options) { let anchor, flip, k, layers, ribbons, samples, sides, strips; let asc, end; super(options); this._clipUniforms(); this.sides = sides = +options.sides || 12; this.samples = samples = +options.samples || 2; this.strips = strips = +options.strips || 1; this.ribbons = ribbons = +options.ribbons || 1; this.layers = layers = +options.layers || 1; this.flip = flip = options.flip != null ? options.flip : false; this.anchor = anchor = options.anchor != null ? options.anchor : flip ? 0 : samples - 1; const arrows = strips * ribbons * layers; const points = (sides + 2) * arrows; const triangles = sides * 2 * arrows; this.setIndex(new BufferAttribute(new Uint32Array(triangles * 3), 1)); this.setAttribute( "position4", new BufferAttribute(new Float32Array(points * 4), 4) ); this.setAttribute( "arrow", new BufferAttribute(new Float32Array(points * 3), 3) ); this.setAttribute( "attach", new BufferAttribute(new Float32Array(points * 2), 2) ); const index = this._emitter("index"); const position = this._emitter("position4"); const arrow = this._emitter("arrow"); const attach = this._emitter("attach"); const circle = []; for ( k = 0, end = sides, asc = 0 <= end; asc ? k < end : k > end; asc ? k++ : k-- ) { const angle = (k / sides) * 2 * Math.PI; circle.push([Math.cos(angle), Math.sin(angle), 1]); } let base = 0; for ( let i = 0, end1 = arrows, asc1 = 0 <= end1; asc1 ? i < end1 : i > end1; asc1 ? i++ : i-- ) { let asc2, end2; const tip = base++; const back = tip + sides + 1; for ( k = 0, end2 = sides, asc2 = 0 <= end2; asc2 ? k < end2 : k > end2; asc2 ? k++ : k-- ) { const a = base + (k % sides); const b = base + ((k + 1) % sides); index(tip); index(a); index(b); index(b); index(a); index(back); } base += sides + 1; } const step = flip ? 1 : -1; const far = flip ? samples - 1 : 0; const near = anchor + step; const x = anchor; for ( let l = 0, end3 = layers, asc3 = 0 <= end3; asc3 ? l < end3 : l > end3; asc3 ? l++ : l-- ) { for ( let z = 0, end4 = ribbons, asc4 = 0 <= end4; asc4 ? z < end4 : z > end4; asc4 ? z++ : z-- ) { for ( let y = 0, end5 = strips, asc5 = 0 <= end5; asc5 ? y < end5 : y > end5; asc5 ? y++ : y-- ) { let asc6, end6; position(x, y, z, l); arrow(0, 0, 0); attach(near, far); for ( k = 0, end6 = sides, asc6 = 0 <= end6; asc6 ? k < end6 : k > end6; asc6 ? k++ : k-- ) { position(x, y, z, l); const c = circle[k]; arrow(c[0], c[1], c[2]); attach(near, far); } position(x, y, z, l); arrow(0, 0, 1); attach(near, far); } } } this._finalize(); this.clip(); } clip(samples, strips, ribbons, layers) { let quads; if (samples == null) { ({ samples } = this); } if (strips == null) { ({ strips } = this); } if (ribbons == null) { ({ ribbons } = this); } if (layers == null) { ({ layers } = this); } this._clipGeometry(samples, strips, ribbons, layers); if (samples > this.anchor) { const dims = [layers, ribbons, strips]; const maxs = [this.layers, this.ribbons, this.strips]; quads = this.sides * this._reduce(dims, maxs); } else { quads = 0; } return this._offsets([ { start: 0, count: quads * 6, materialIndex: 0, }, ]); } }
cchudzicki/mathbox
src/render/geometry/arrowgeometry.js
JavaScript
mit
4,646
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Geometry } from "./geometry.js"; import { Vector4 } from "three/src/math/Vector4.js"; // Instanced geometry that is clippable along 4 dimensions export class ClipGeometry extends Geometry { _clipUniforms() { this.geometryClip = new Vector4(1e10, 1e10, 1e10, 1e10); this.geometryResolution = new Vector4(); this.mapSize = new Vector4(); if (this.uniforms == null) { this.uniforms = {}; } this.uniforms.geometryClip = { type: "v4", value: this.geometryClip, }; this.uniforms.geometryResolution = { type: "v4", value: this.geometryResolution, }; return (this.uniforms.mapSize = { type: "v4", value: this.mapSize, }); } _clipGeometry(width, height, depth, items) { const c = (x) => Math.max(0, x - 1); const r = (x) => 1 / Math.max(1, x - 1); this.geometryClip.set(c(width), c(height), c(depth), c(items)); return this.geometryResolution.set(r(width), r(height), r(depth), r(items)); } _clipMap(mapWidth, mapHeight, mapDepth, mapItems) { return this.mapSize.set(mapWidth, mapHeight, mapDepth, mapItems); } _clipOffsets( factor, width, height, depth, items, _width, _height, _depth, _items ) { const dims = [depth, height, width, items]; const maxs = [_depth, _height, _width, _items]; const elements = this._reduce(dims, maxs); return this._offsets([ { start: 0, count: elements * factor, materialIndex: 0, }, ]); } }
cchudzicki/mathbox
src/render/geometry/clipgeometry.js
JavaScript
mit
1,906
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS202: Simplify dynamic range loops * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { BufferAttribute } from "three/src/core/BufferAttribute.js"; import { ClipGeometry } from "./clipgeometry.js"; /* (flat) Triangle fans arranged in items, columns and rows +-+ +-+ +-+ +-+ |\\\ |\\\ |\\\ |\\\ +-+-+ +-+-+ +-+-+ +-+-+ +-+ +-+ +-+ +-+ |\\\ |\\\ |\\\ |\\\ +-+-+ +-+-+ +-+-+ +-+-+ +-+ +-+ +-+ +-+ |\\\ |\\\ |\\\ |\\\ +-+-+ +-+-+ +-+-+ +-+-+ */ export class FaceGeometry extends ClipGeometry { constructor(options) { let depth, height, items, sides, width; super(options); this._clipUniforms(); this.items = items = +options.items || 2; this.width = width = +options.width || 1; this.height = height = +options.height || 1; this.depth = depth = +options.depth || 1; this.sides = sides = Math.max(0, items - 2); const samples = width * height * depth; const points = items * samples; const triangles = sides * samples; this.setIndex(new BufferAttribute(new Uint32Array(triangles * 3), 1)); this.setAttribute( "position4", new BufferAttribute(new Float32Array(points * 4), 4) ); const index = this._emitter("index"); const position = this._emitter("position4"); let base = 0; for ( let i = 0, end = samples, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { for ( let j = 0, end1 = sides, asc1 = 0 <= end1; asc1 ? j < end1 : j > end1; asc1 ? j++ : j-- ) { index(base); index(base + j + 1); index(base + j + 2); } base += items; } for ( let z = 0, end2 = depth, asc2 = 0 <= end2; asc2 ? z < end2 : z > end2; asc2 ? z++ : z-- ) { for ( let y = 0, end3 = height, asc3 = 0 <= end3; asc3 ? y < end3 : y > end3; asc3 ? y++ : y-- ) { for ( let x = 0, end4 = width, asc4 = 0 <= end4; asc4 ? x < end4 : x > end4; asc4 ? x++ : x-- ) { for ( let l = 0, end5 = items, asc5 = 0 <= end5; asc5 ? l < end5 : l > end5; asc5 ? l++ : l-- ) { position(x, y, z, l); } } } } this._finalize(); this.clip(); } clip(width, height, depth, items) { if (width == null) { ({ width } = this); } if (height == null) { ({ height } = this); } if (depth == null) { ({ depth } = this); } if (items == null) { ({ items } = this); } const sides = Math.max(0, items - 2); this._clipGeometry(width, height, depth, items); return this._clipOffsets( 3, width, height, depth, sides, this.width, this.height, this.depth, this.sides ); } }
cchudzicki/mathbox
src/render/geometry/facegeometry.js
JavaScript
mit
3,247
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS202: Simplify dynamic range loops * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { BufferGeometry } from "three/src/core/BufferGeometry.js"; export class Geometry extends BufferGeometry { constructor() { super(); new BufferGeometry(this); if (this.uniforms == null) { this.uniforms = {}; } if (this.groups == null) { this.groups = []; } } _reduce(dims, maxs) { let multiple = false; for (let i = 0; i < dims.length; i++) { const dim = dims[i]; const max = maxs[i]; if (multiple) { dims[i] = max; } if (dim > 1) { multiple = true; } } return dims.reduce((a, b) => a * b); } _emitter(name) { const attribute = name == "index" ? this.getIndex() : this.getAttribute(name); const dimensions = attribute.itemSize; const { array } = attribute; let offset = 0; const one = function (a) { array[offset++] = a; }; const two = function (a, b) { array[offset++] = a; array[offset++] = b; }; const three = function (a, b, c) { array[offset++] = a; array[offset++] = b; array[offset++] = c; }; const four = function (a, b, c, d) { array[offset++] = a; array[offset++] = b; array[offset++] = c; array[offset++] = d; }; return [null, one, two, three, four][dimensions]; } _finalize() { return; } _offsets(offsets) { this.groups = offsets; } }
cchudzicki/mathbox
src/render/geometry/geometry.js
JavaScript
mit
1,857
export * from "./geometry.js"; export * from "./arrowgeometry.js"; export * from "./facegeometry.js"; export * from "./linegeometry.js"; export * from "./screengeometry.js"; export * from "./spritegeometry.js"; export * from "./stripgeometry.js"; export * from "./surfacegeometry.js";
cchudzicki/mathbox
src/render/geometry/index.js
JavaScript
mit
285
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS202: Simplify dynamic range loops * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { BufferAttribute } from "three/src/core/BufferAttribute.js"; import { ClipGeometry } from "./clipgeometry.js"; /* Line strips arranged in columns and rows +----+ +----+ +----+ +----+ +----+ +----+ +----+ +----+ +----+ +----+ +----+ +----+ */ export class LineGeometry extends ClipGeometry { constructor(options) { let closed, detail, edge, joint, joints, l, layers, ribbons, samples, segments, strips, vertices, x, y, z; super(options); this._clipUniforms(); this.closed = closed = options.closed || false; this.samples = samples = (+options.samples || 2) + (closed ? 1 : 0); this.strips = strips = +options.strips || 1; this.ribbons = ribbons = +options.ribbons || 1; this.layers = layers = +options.layers || 1; this.detail = detail = +options.detail || 1; const lines = samples - 1; this.joints = joints = detail - 1; this.vertices = vertices = (lines - 1) * joints + samples; this.segments = segments = (lines - 1) * joints + lines; const wrap = samples - (closed ? 1 : 0); const points = vertices * strips * ribbons * layers * 2; const quads = segments * strips * ribbons * layers; const triangles = quads * 2; this.setIndex(new BufferAttribute(new Uint32Array(triangles * 3), 1)); this.setAttribute( "position4", new BufferAttribute(new Float32Array(points * 4), 4) ); this.setAttribute( "line", new BufferAttribute(new Float32Array(points * 2), 2) ); this.setAttribute( "strip", new BufferAttribute(new Float32Array(points * 2), 2) ); if (detail > 1) { this.setAttribute( "joint", new BufferAttribute(new Float32Array(points), 1) ); } const index = this._emitter("index"); const position = this._emitter("position4"); const line = this._emitter("line"); const strip = this._emitter("strip"); if (detail > 1) { joint = this._emitter("joint"); } let base = 0; for ( let i = 0, end = ribbons * layers, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { for ( let j = 0, end1 = strips, asc1 = 0 <= end1; asc1 ? j < end1 : j > end1; asc1 ? j++ : j-- ) { for ( let k = 0, end2 = segments, asc2 = 0 <= end2; asc2 ? k < end2 : k > end2; asc2 ? k++ : k-- ) { // note implied - 1 index(base); index(base + 1); index(base + 2); index(base + 2); index(base + 1); index(base + 3); base += 2; } base += 2; } } const edger = closed ? () => 0 : function (x) { if (x === 0) { return -1; } else if (x === samples - 1) { return 1; } else { return 0; } }; if (detail > 1) { let asc3, end3; for ( l = 0, end3 = layers, asc3 = 0 <= end3; asc3 ? l < end3 : l > end3; asc3 ? l++ : l-- ) { let asc4, end4; for ( z = 0, end4 = ribbons, asc4 = 0 <= end4; asc4 ? z < end4 : z > end4; asc4 ? z++ : z-- ) { let asc5, end5; for ( y = 0, end5 = strips, asc5 = 0 <= end5; asc5 ? y < end5 : y > end5; asc5 ? y++ : y-- ) { let asc6, end6, i1; for ( i1 = 0, x = i1, end6 = samples, asc6 = 0 <= end6; asc6 ? i1 < end6 : i1 > end6; asc6 ? i1++ : i1--, x = i1 ) { if (closed) { x = x % wrap; } edge = edger(x); if (edge !== 0) { position(x, y, z, l); position(x, y, z, l); line(edge, 1); line(edge, -1); strip(0, segments); strip(0, segments); joint(0.5); joint(0.5); } else { for ( let m = 0, end7 = detail, asc7 = 0 <= end7; asc7 ? m < end7 : m > end7; asc7 ? m++ : m-- ) { position(x, y, z, l); position(x, y, z, l); line(edge, 1); line(edge, -1); strip(0, segments); strip(0, segments); joint(m / joints); joint(m / joints); } } } } } } } else { let asc8, end8; for ( l = 0, end8 = layers, asc8 = 0 <= end8; asc8 ? l < end8 : l > end8; asc8 ? l++ : l-- ) { let asc9, end9; for ( z = 0, end9 = ribbons, asc9 = 0 <= end9; asc9 ? z < end9 : z > end9; asc9 ? z++ : z-- ) { let asc10, end10; for ( y = 0, end10 = strips, asc10 = 0 <= end10; asc10 ? y < end10 : y > end10; asc10 ? y++ : y-- ) { let asc11, end11, j1; for ( j1 = 0, x = j1, end11 = samples, asc11 = 0 <= end11; asc11 ? j1 < end11 : j1 > end11; asc11 ? j1++ : j1--, x = j1 ) { if (closed) { x = x % wrap; } edge = edger(x); position(x, y, z, l); position(x, y, z, l); line(edge, 1); line(edge, -1); strip(0, segments); strip(0, segments); } } } } } this._finalize(); this.clip(); } clip(samples, strips, ribbons, layers) { if (samples == null) { samples = this.samples - this.closed; } if (strips == null) { ({ strips } = this); } if (ribbons == null) { ({ ribbons } = this); } if (layers == null) { ({ layers } = this); } let segments = Math.max(0, samples - (this.closed ? 0 : 1)); const vertices = samples + (samples - 2) * this.joints; segments = vertices - 1; this._clipGeometry(vertices, strips, ribbons, layers); return this._clipOffsets( 6, segments, strips, ribbons, layers, this.segments, this.strips, this.ribbons, this.layers ); } }
cchudzicki/mathbox
src/render/geometry/linegeometry.js
JavaScript
mit
6,954
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { SurfaceGeometry } from "./surfacegeometry.js"; import { Vector4 } from "three/src/math/Vector4.js"; /* Grid Surface in normalized screen space +----+----+----+----+ | | | | | +----+----+----+----+ | | | | | +----+----+----+----+ +----+----+----+----+ | | | | | +----+----+----+----+ | | | | | +----+----+----+----+ */ export class ScreenGeometry extends SurfaceGeometry { constructor(options) { options.width = Math.max(2, +options.width != null ? +options.width : 2); options.height = Math.max(2, +options.height != null ? +options.height : 2); super(options, false); if (this.uniforms == null) { this.uniforms = {}; } this.uniforms.geometryScale = { type: "v4", value: new Vector4(), }; this.cover(); this.construct(options); } cover(scaleX, scaleY, scaleZ, scaleW) { if (scaleX == null) { scaleX = 1; } this.scaleX = scaleX; if (scaleY == null) { scaleY = 1; } this.scaleY = scaleY; if (scaleZ == null) { scaleZ = 1; } this.scaleZ = scaleZ; if (scaleW == null) { scaleW = 1; } this.scaleW = scaleW; } clip(width, height, surfaces, layers) { if (width == null) { ({ width } = this); } if (height == null) { ({ height } = this); } if (surfaces == null) { ({ surfaces } = this); } if (layers == null) { ({ layers } = this); } super.clip(width, height, surfaces, layers); const invert = (x) => 1 / Math.max(1, x - 1); return this.uniforms.geometryScale.value.set( invert(width) * this.scaleX, invert(height) * this.scaleY, invert(surfaces) * this.scaleZ, invert(layers) * this.scaleW ); } }
cchudzicki/mathbox
src/render/geometry/screengeometry.js
JavaScript
mit
2,151
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS202: Simplify dynamic range loops * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { BufferAttribute } from "three/src/core/BufferAttribute.js"; import { ClipGeometry } from "./clipgeometry.js"; /* Render points as quads +----+ +----+ +----+ +----+ | | | | | | | | +----+ +----+ +----+ +----+ +----+ +----+ +----+ +----+ | | | | | | | | +----+ +----+ +----+ +----+ +----+ +----+ +----+ +----+ | | | | | | | | +----+ +----+ +----+ +----+ */ export class SpriteGeometry extends ClipGeometry { constructor(options) { let depth, height, items, width; super(options); this._clipUniforms(); this.items = items = +options.items || 2; this.width = width = +options.width || 1; this.height = height = +options.height || 1; this.depth = depth = +options.depth || 1; const samples = items * width * height * depth; const points = samples * 4; const triangles = samples * 2; this.setIndex(new BufferAttribute(new Uint32Array(triangles * 3), 1)); this.setAttribute( "position4", new BufferAttribute(new Float32Array(points * 4), 4) ); this.setAttribute( "sprite", new BufferAttribute(new Float32Array(points * 2), 2) ); const index = this._emitter("index"); const position = this._emitter("position4"); const sprite = this._emitter("sprite"); const quad = [ [-1, -1], [-1, 1], [1, -1], [1, 1], ]; let base = 0; for ( let i = 0, end = samples, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { index(base); index(base + 1); index(base + 2); index(base + 1); index(base + 2); index(base + 3); base += 4; } for ( let z = 0, end1 = depth, asc1 = 0 <= end1; asc1 ? z < end1 : z > end1; asc1 ? z++ : z-- ) { for ( let y = 0, end2 = height, asc2 = 0 <= end2; asc2 ? y < end2 : y > end2; asc2 ? y++ : y-- ) { for ( let x = 0, end3 = width, asc3 = 0 <= end3; asc3 ? x < end3 : x > end3; asc3 ? x++ : x-- ) { for ( let l = 0, end4 = items, asc4 = 0 <= end4; asc4 ? l < end4 : l > end4; asc4 ? l++ : l-- ) { for (const v of Array.from(quad)) { position(x, y, z, l); sprite(v[0], v[1]); } } } } } this._finalize(); this.clip(); } clip(width, height, depth, items) { if (width == null) { ({ width } = this); } if (height == null) { ({ height } = this); } if (depth == null) { ({ depth } = this); } if (items == null) { ({ items } = this); } this._clipGeometry(width, height, depth, items); return this._clipOffsets( 6, width, height, depth, items, this.width, this.height, this.depth, this.items ); } }
cchudzicki/mathbox
src/render/geometry/spritegeometry.js
JavaScript
mit
3,426
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS202: Simplify dynamic range loops * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { BufferAttribute } from "three/src/core/BufferAttribute.js"; import { ClipGeometry } from "./clipgeometry.js"; /* Triangle strips arranged in items, columns and rows +--+--+--+ +--+--+--+ +--+--+--+ +--+--+--+ | /| /| / | /| /| / | /| /| / | /| /| / +--+--+/ +--+--+/ +--+--+/ +--+--+/ +--+--+--+ +--+--+--+ +--+--+--+ +--+--+--+ | /| /| / | /| /| / | /| /| / | /| /| / +--+--+/ +--+--+/ +--+--+/ +--+--+/ +--+--+--+ +--+--+--+ +--+--+--+ +--+--+--+ | /| /| / | /| /| / | /| /| / | /| /| / +--+--+/ +--+--+/ +--+--+/ +--+--+/ */ export class StripGeometry extends ClipGeometry { constructor(options) { let depth, height, items, sides, width; super(options); this._clipUniforms(); this.items = items = +options.items || 2; this.width = width = +options.width || 1; this.height = height = +options.height || 1; this.depth = depth = +options.depth || 1; this.sides = sides = Math.max(0, items - 2); const samples = width * height * depth; const points = items * samples; const triangles = sides * samples; this.setIndex(new BufferAttribute(new Uint32Array(triangles * 3), 1)); this.setAttribute( "position4", new BufferAttribute(new Float32Array(points * 4), 4) ); this.setAttribute( "strip", new BufferAttribute(new Float32Array(points * 3), 3) ); const index = this._emitter("index"); const position = this._emitter("position4"); const strip = this._emitter("strip"); let base = 0; for ( let i = 0, end = samples, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { let o = base; for ( let j = 0, end1 = sides, asc1 = 0 <= end1; asc1 ? j < end1 : j > end1; asc1 ? j++ : j-- ) { if (j & 1) { index(o + 1); index(o); index(o + 2); } else { index(o); index(o + 1); index(o + 2); } o++; } base += items; } const last = items - 1; for ( let z = 0, end2 = depth, asc2 = 0 <= end2; asc2 ? z < end2 : z > end2; asc2 ? z++ : z-- ) { for ( let y = 0, end3 = height, asc3 = 0 <= end3; asc3 ? y < end3 : y > end3; asc3 ? y++ : y-- ) { for ( let x = 0, end4 = width, asc4 = 0 <= end4; asc4 ? x < end4 : x > end4; asc4 ? x++ : x-- ) { let f = 1; position(x, y, z, 0); strip(1, 2, f); for ( let l = 1, end5 = last, asc5 = 1 <= end5; asc5 ? l < end5 : l > end5; asc5 ? l++ : l-- ) { position(x, y, z, l); strip(l - 1, l + 1, (f = -f)); } position(x, y, z, last); strip(last - 2, last - 1, -f); } } } this._finalize(); this.clip(); } clip(width, height, depth, items) { if (width == null) { ({ width } = this); } if (height == null) { ({ height } = this); } if (depth == null) { ({ depth } = this); } if (items == null) { ({ items } = this); } const sides = Math.max(0, items - 2); this._clipGeometry(width, height, depth, items); return this._clipOffsets( 3, width, height, depth, sides, this.width, this.height, this.depth, this.sides ); } }
cchudzicki/mathbox
src/render/geometry/stripgeometry.js
JavaScript
mit
3,908
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS202: Simplify dynamic range loops * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { BufferAttribute } from "three/src/core/BufferAttribute.js"; import { ClipGeometry } from "./clipgeometry.js"; /* Grid Surface +----+----+----+----+ | | | | | +----+----+----+----+ | | | | | +----+----+----+----+ +----+----+----+----+ | | | | | +----+----+----+----+ | | | | | +----+----+----+----+ */ export class SurfaceGeometry extends ClipGeometry { constructor(options, build) { if (build == null) { build = true; } super(); // TODO not great... but use this pattern, maybe, to defer construction if // options are missing, NOT the boolean. if (build) { this.construct(options); } } construct(options) { let closedX, closedY, height, layers, segmentsX, segmentsY, surfaces, width; this._clipUniforms(); this.closedX = closedX = options.closedX || false; this.closedY = closedY = options.closedY || false; this.width = width = (+options.width || 2) + (closedX ? 1 : 0); this.height = height = (+options.height || 2) + (closedY ? 1 : 0); this.surfaces = surfaces = +options.surfaces || 1; this.layers = layers = +options.layers || 1; const wrapX = width - (closedX ? 1 : 0); const wrapY = height - (closedY ? 1 : 0); this.segmentsX = segmentsX = Math.max(0, width - 1); this.segmentsY = segmentsY = Math.max(0, height - 1); const points = width * height * surfaces * layers; const quads = segmentsX * segmentsY * surfaces * layers; const triangles = quads * 2; this.setIndex(new BufferAttribute(new Uint32Array(triangles * 3), 1)); this.setAttribute( "position4", new BufferAttribute(new Float32Array(points * 4), 4) ); this.setAttribute( "surface", new BufferAttribute(new Float32Array(points * 2), 2) ); const index = this._emitter("index"); const position = this._emitter("position4"); const surface = this._emitter("surface"); let base = 0; for ( let i = 0, end = surfaces * layers, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { for ( let j = 0, end1 = segmentsY, asc1 = 0 <= end1; asc1 ? j < end1 : j > end1; asc1 ? j++ : j-- ) { for ( let k = 0, end2 = segmentsX, asc2 = 0 <= end2; asc2 ? k < end2 : k > end2; asc2 ? k++ : k-- ) { index(base); index(base + 1); index(base + width); index(base + width); index(base + 1); index(base + width + 1); base++; } base++; } base += width; } const edgerX = closedX ? () => 0 : function (x) { if (x === 0) { return -1; } else if (x === segmentsX) { return 1; } else { return 0; } }; const edgerY = closedY ? () => 0 : function (y) { if (y === 0) { return -1; } else if (y === segmentsY) { return 1; } else { return 0; } }; for ( let l = 0, end3 = layers, asc3 = 0 <= end3; asc3 ? l < end3 : l > end3; asc3 ? l++ : l-- ) { for ( let z = 0, end4 = surfaces, asc4 = 0 <= end4; asc4 ? z < end4 : z > end4; asc4 ? z++ : z-- ) { for ( let i1 = 0, y = i1, end5 = height, asc5 = 0 <= end5; asc5 ? i1 < end5 : i1 > end5; asc5 ? i1++ : i1--, y = i1 ) { if (closedY) { y = y % wrapY; } const edgeY = edgerY(y); for ( let j1 = 0, x = j1, end6 = width, asc6 = 0 <= end6; asc6 ? j1 < end6 : j1 > end6; asc6 ? j1++ : j1--, x = j1 ) { if (closedX) { x = x % wrapX; } const edgeX = edgerX(x); position(x, y, z, l); surface(edgeX, edgeY); } } } } this._finalize(); this.clip(); } clip(width, height, surfaces, layers) { if (width == null) { ({ width } = this); } if (height == null) { ({ height } = this); } if (surfaces == null) { ({ surfaces } = this); } if (layers == null) { ({ layers } = this); } const segmentsX = Math.max(0, width - 1); const segmentsY = Math.max(0, height - 1); this._clipGeometry(width, height, surfaces, layers); return this._clipOffsets( 6, segmentsX, segmentsY, surfaces, layers, this.segmentsX, this.segmentsY, this.surfaces, this.layers ); } map(width, height, surfaces, layers) { if (width == null) { ({ width } = this); } if (height == null) { ({ height } = this); } if (surfaces == null) { ({ surfaces } = this); } if (layers == null) { ({ layers } = this); } return this._clipMap(width, height, surfaces, layers); } }
cchudzicki/mathbox
src/render/geometry/surfacegeometry.js
JavaScript
mit
5,470
export * from "./scene.js"; export { RenderFactory as Factory } from "./factory.js"; export * from "./scene.js"; export * from "./classes.js";
cchudzicki/mathbox
src/render/index.js
JavaScript
mit
143
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { ArrowGeometry } from "../geometry/arrowgeometry.js"; import { Base } from "./base.js"; import { DoubleSide } from "three/src/constants.js"; import { Mesh } from "three/src/objects/Mesh.js"; export class Arrow extends Base { constructor(renderer, shaders, options) { let f; super(renderer, shaders, options); let { uniforms } = options; const { material, position, color, mask, map, combine, stpq, linear } = options; if (uniforms == null) { uniforms = {}; } const hasStyle = uniforms.styleColor != null; this.geometry = new ArrowGeometry({ sides: options.sides, samples: options.samples, strips: options.strips, ribbons: options.ribbons, layers: options.layers, anchor: options.anchor, flip: options.flip, }); this._adopt(uniforms); this._adopt(this.geometry.uniforms); const factory = shaders.material(); const v = factory.vertex; v.pipe(this._vertexColor(color, mask)); v.require(this._vertexPosition(position, material, map, 1, stpq)); v.pipe("arrow.position", this.uniforms); v.pipe("project.position", this.uniforms); factory.fragment = f = this._fragmentColor( hasStyle, material, color, mask, map, 1, stpq, combine, linear ); f.pipe("fragment.color", this.uniforms); const opts = factory.link({ side: DoubleSide, }); this.material = this._material(opts); const object = new Mesh(this.geometry, this.material); object.frustumCulled = false; object.matrixAutoUpdate = false; object.userData = opts; this._raw(object); this.renders = [object]; } dispose() { this.geometry.dispose(); this.material.dispose(); this.renders = this.geometry = this.material = null; return super.dispose(); } }
cchudzicki/mathbox
src/render/meshes/arrow.js
JavaScript
mit
2,232
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as UGLSL from "../../util/glsl.js"; import { RawShaderMaterial } from "three/src/materials/RawShaderMaterial.js"; import { Renderable } from "../renderable.js"; export class Base extends Renderable { constructor(renderer, shaders, options) { super(renderer, shaders, options); this.zUnits = options.zUnits != null ? options.zUnits : 0; } raw() { for (const object of Array.from(this.renders)) { this._raw(object); } return null; } depth(write, test) { for (const object of Array.from(this.renders)) { this._depth(object, write, test); } return null; } polygonOffset(factor, units) { for (const object of Array.from(this.renders)) { this._polygonOffset(object, factor, units); } return null; } show(transparent, blending, order) { return Array.from(this.renders).map((object) => this._show(object, transparent, blending, order) ); } hide() { for (const object of Array.from(this.renders)) { this._hide(object); } return null; } _material(options) { const precision = this.renderer.capabilities.precision; const vertexPrefix = `\ precision ${precision} float; precision ${precision} int; uniform mat4 modelMatrix; uniform mat4 modelViewMatrix; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat3 normalMatrix; uniform vec3 cameraPosition;\ `; const fragmentPrefix = `\ precision ${precision} float; precision ${precision} int; uniform mat4 viewMatrix; uniform vec3 cameraPosition;\ `; const shaderOptions = {}; Object.assign(shaderOptions, options); delete shaderOptions.attributes; delete shaderOptions.varyings; delete shaderOptions.inspect; delete shaderOptions.vertexGraph; delete shaderOptions.fragmentGraph; const material = new RawShaderMaterial(shaderOptions); ["vertexGraph", "fragmentGraph", "inspect"].forEach( (key) => (material[key] = options[key]) ); material.vertexShader = [vertexPrefix, material.vertexShader].join("\n"); material.fragmentShader = [fragmentPrefix, material.fragmentShader].join( "\n" ); return material; } _raw(object) { object.rotationAutoUpdate = false; object.frustumCulled = false; object.matrixAutoUpdate = false; object.material.defaultAttributeValues = undefined; } _depth(object, write, test) { const m = object.material; m.depthWrite = write; return (m.depthTest = test); } _polygonOffset(object, factor, units) { units -= this.zUnits; const enabled = units !== 0; const m = object.material; m.polygonOffset = enabled; if (enabled) { m.polygonOffsetFactor = factor; return (m.polygonOffsetUnits = units); } } _show(object, transparent, blending, order) { // Force transparent to true to ensure all renderables drawn in order transparent = true; const m = object.material; object.renderOrder = -order; object.visible = true; m.transparent = transparent; m.blending = blending; return null; } _hide(object) { return (object.visible = false); } _vertexColor(color, mask) { if (!color && !mask) { return; } const v = this.shaders.shader(); if (color) { v.require(color); v.pipe("mesh.vertex.color", this.uniforms); } if (mask) { v.require(mask); v.pipe("mesh.vertex.mask", this.uniforms); } return v; } _vertexPosition(position, material, map, channels, stpq) { let defs; const v = this.shaders.shader(); if (map || (material && material !== true)) { defs = {}; if (channels > 0 || stpq) { defs.POSITION_MAP = ""; } if (channels > 0) { defs[ ["POSITION_U", "POSITION_UV", "POSITION_UVW", "POSITION_UVWO"][ channels - 1 ] ] = ""; } if (stpq) { defs.POSITION_STPQ = ""; } } v.require(position); return v.pipe("mesh.vertex.position", this.uniforms, defs); } _fragmentColor( hasStyle, material, color, mask, map, channels, stpq, combine, linear ) { const f = this.shaders.shader(); // metacode is terrible let join = false; let gamma = false; const defs = {}; if (channels > 0) { defs[ ["POSITION_U", "POSITION_UV", "POSITION_UVW", "POSITION_UVWO"][ channels - 1 ] ] = ""; } if (stpq) { defs.POSITION_STPQ = ""; } if (hasStyle) { f.pipe("style.color", this.uniforms); join = true; if (color || map || material) { if (!linear || color) { f.pipe("mesh.gamma.in"); } gamma = true; } } if (color) { f.isolate(); f.pipe("mesh.fragment.color", this.uniforms); if (!linear || join) { f.pipe("mesh.gamma.in"); } f.end(); if (join) { f.pipe(UGLSL.binaryOperator("vec4", "*")); } if (linear && join) { f.pipe("mesh.gamma.out"); } join = true; gamma = true; } if (map) { if (!join && combine) { f.pipe(UGLSL.constant("vec4", "vec4(1.0)")); } f.isolate(); f.require(map); f.pipe("mesh.fragment.map", this.uniforms, defs); if (!linear) { f.pipe("mesh.gamma.in"); } f.end(); if (combine) { f.pipe(combine); } else { if (join) { f.pipe(UGLSL.binaryOperator("vec4", "*")); } } join = true; gamma = true; } if (material) { if (!join) { f.pipe(UGLSL.constant("vec4", "vec4(1.0)")); } if (material === true) { f.pipe("mesh.fragment.shaded", this.uniforms); } else { f.require(material); f.pipe("mesh.fragment.material", this.uniforms, defs); } gamma = true; } if (gamma && !linear) { f.pipe("mesh.gamma.out"); } if (mask) { f.pipe("mesh.fragment.mask", this.uniforms); if (join) { f.pipe(UGLSL.binaryOperator("vec4", "*")); } } return f; } }
cchudzicki/mathbox
src/render/meshes/base.js
JavaScript
mit
6,626
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Base } from "./base.js"; import { DoubleSide } from "three/src/constants.js"; import { Mesh } from "three/src/objects/Mesh.js"; import { MeshBasicMaterial } from "three/src/materials/MeshBasicMaterial.js"; import { PlaneGeometry } from "three/src/geometries/PlaneGeometry.js"; export class Debug extends Base { constructor(renderer, shaders, options) { super(renderer, shaders, options); this.geometry = new PlaneGeometry(1, 1); this.material = new MeshBasicMaterial({ map: options.map }); this.material.side = DoubleSide; const object = new Mesh(this.geometry, this.material); object.position.x += options.x || 0; object.position.y += options.y || 0; object.frustumCulled = false; object.scale.set(2, 2, 2); object.__debug = true; this.objects = [object]; } dispose() { this.geometry.dispose(); this.material.dispose(); this.objects = this.geometry = this.material = null; return super.dispose(); } }
cchudzicki/mathbox
src/render/meshes/debug.js
JavaScript
mit
1,291
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Base } from "./base.js"; import { DoubleSide } from "three/src/constants.js"; import { FaceGeometry } from "../geometry/facegeometry.js"; import { Mesh } from "three/src/objects/Mesh.js"; export class Face extends Base { constructor(renderer, shaders, options) { let f; super(renderer, shaders, options); let { uniforms, material } = options; const { position, color, mask, map, combine, stpq, linear } = options; if (uniforms == null) { uniforms = {}; } if (material == null) { material = true; } const hasStyle = uniforms.styleColor != null; this.geometry = new FaceGeometry({ items: options.items, width: options.width, height: options.height, depth: options.depth, }); this._adopt(uniforms); this._adopt(this.geometry.uniforms); const factory = shaders.material(); const v = factory.vertex; v.pipe(this._vertexColor(color, mask)); v.require(this._vertexPosition(position, material, map, 2, stpq)); if (!material) { v.pipe("face.position", this.uniforms); } if (material) { v.pipe("face.position.normal", this.uniforms); } v.pipe("project.position", this.uniforms); factory.fragment = f = this._fragmentColor( hasStyle, material, color, mask, map, 2, stpq, combine, linear ); f.pipe("fragment.color", this.uniforms); const opts = factory.link({ side: DoubleSide, }); this.material = this._material(opts); const object = new Mesh(this.geometry, this.material); object.userData = opts; this._raw(object); this.renders = [object]; } dispose() { this.geometry.dispose(); this.material.dispose(); this.renders = this.geometry = this.material = null; return super.dispose(); } }
cchudzicki/mathbox
src/render/meshes/face.js
JavaScript
mit
2,221
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS104: Avoid inline assignments * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Base } from "./base.js"; import { DoubleSide } from "three/src/constants.js"; import { LineGeometry } from "../geometry/linegeometry.js"; import { Mesh } from "three/src/objects/Mesh.js"; export class Line extends Base { constructor(renderer, shaders, options) { let left; super(renderer, shaders, options); let { uniforms, stroke, join } = options; const { material, position, color, mask, map, combine, stpq, linear, clip, proximity, } = options; if (uniforms == null) { uniforms = {}; } stroke = [null, "dotted", "dashed"][stroke]; const hasStyle = uniforms.styleColor != null; // Line join join = (left = ["miter", "round", "bevel"][join]) != null ? left : "miter"; const detail = { miter: 1, round: 4, bevel: 2 }[join]; this.geometry = new LineGeometry({ samples: options.samples, strips: options.strips, ribbons: options.ribbons, layers: options.layers, anchor: options.anchor, closed: options.closed, detail, }); this._adopt(uniforms); this._adopt(this.geometry.uniforms); const factory = shaders.material(); const defs = {}; if (stroke) { defs.LINE_STROKE = ""; } if (clip) { defs.LINE_CLIP = ""; } if (proximity != null) { defs.LINE_PROXIMITY = ""; } defs["LINE_JOIN_" + join.toUpperCase()] = ""; if (detail > 1) { defs["LINE_JOIN_DETAIL"] = detail; } const v = factory.vertex; v.pipe(this._vertexColor(color, mask)); v.require(this._vertexPosition(position, material, map, 2, stpq)); v.pipe("line.position", this.uniforms, defs); v.pipe("project.position", this.uniforms); const f = factory.fragment; if (stroke) { f.pipe(`fragment.clip.${stroke}`, this.uniforms); } if (clip) { f.pipe("fragment.clip.ends", this.uniforms); } if (proximity != null) { f.pipe("fragment.clip.proximity", this.uniforms); } f.pipe( this._fragmentColor( hasStyle, material, color, mask, map, 2, stpq, combine, linear ) ); f.pipe("fragment.color", this.uniforms); const opts = factory.link({ side: DoubleSide, }); this.material = this._material(opts); const object = new Mesh(this.geometry, this.material); object.userData = opts; this._raw(object); this.renders = [object]; } dispose() { this.geometry.dispose(); this.material.dispose(); this.renders = this.geometry = this.material = null; return super.dispose(); } }
cchudzicki/mathbox
src/render/meshes/line.js
JavaScript
mit
3,092
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Screen } from "./screen.js"; import { Vector2 } from "three/src/math/Vector2.js"; import { Vector4 } from "three/src/math/Vector4.js"; export class MemoScreen extends Screen { constructor(renderer, shaders, options) { const { items, width, height, depth, stpq } = options; const inv = (x) => 1 / Math.max(1, x); const inv1 = (x) => 1 / Math.max(1, x - 1); const uniforms = { remapUVScale: { type: "v2", value: new Vector2(items * width, height * depth), }, remapModulus: { type: "v2", value: new Vector2(items, height), }, remapModulusInv: { type: "v2", value: new Vector2(inv(items), inv(height)), }, remapSTPQScale: { type: "v4", value: new Vector4(inv1(width), inv1(height), inv1(depth), inv1(items)), }, }; const map = shaders.shader(); map.pipe("screen.map.xyzw", uniforms); if (options.map != null) { // Need artifical STPQs because the screen is not the real geometry if (stpq) { map.pipe("screen.map.stpq", uniforms); } map.pipe(options.map); } super(renderer, shaders, { map, linear: true }); this.memo = options; this.uniforms = uniforms; for (const object of Array.from(this.renders)) { object.transparent = false; } } cover(width, height, depth, items) { if (width == null) { ({ width } = this.memo); } if (height == null) { ({ height } = this.memo); } if (depth == null) { ({ depth } = this.memo); } if (items == null) { ({ items } = this.memo); } const inv1 = (x) => 1 / Math.max(1, x - 1); this.uniforms.remapSTPQScale.value.set( inv1(width), inv1(height), inv1(depth), inv1(items) ); const x = width / this.memo.width; let y = depth / this.memo.depth; if (this.memo.depth === 1) { y = height / this.memo.height; } return this.geometry.cover(x, y); } }
cchudzicki/mathbox
src/render/meshes/memoscreen.js
JavaScript
mit
2,425
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS104: Avoid inline assignments * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Base } from "./base.js"; import { DoubleSide } from "three/src/constants.js"; import { Mesh } from "three/src/objects/Mesh.js"; import { SpriteGeometry } from "../geometry/spritegeometry.js"; export class Point extends Base { constructor(renderer, shaders, options) { let f, left; super(renderer, shaders, options); let { uniforms, shape, fill } = options; const { material, position, color, size, mask, map, combine, linear, optical, stpq, } = options; if (uniforms == null) { uniforms = {}; } shape = +shape != null ? +shape : 0; if (fill == null) { fill = true; } const hasStyle = uniforms.styleColor != null; const shapes = [ "circle", "square", "diamond", "up", "down", "left", "right", ]; const passes = [ "circle", "generic", "generic", "generic", "generic", "generic", "generic", ]; const scales = [1.2, 1, 1.414, 1.16, 1.16, 1.16, 1.16]; const pass = passes[shape] != null ? passes[shape] : passes[0]; const _shape = shapes[shape] != null ? shapes[shape] : shapes[0]; const _scale = (left = optical && scales[shape]) != null ? left : 1; const alpha = fill ? pass : `${pass}.hollow`; this.geometry = new SpriteGeometry({ items: options.items, width: options.width, height: options.height, depth: options.depth, }); this._adopt(uniforms); this._adopt(this.geometry.uniforms); const defines = { POINT_SHAPE_SCALE: +(_scale + 0.00001) }; // Shared vertex shader const factory = shaders.material(); const v = factory.vertex; v.pipe(this._vertexColor(color, mask)); // Point sizing if (size) { v.isolate(); v.require(size); v.require("point.size.varying", this.uniforms); v.end(); } else { v.require("point.size.uniform", this.uniforms); } v.require(this._vertexPosition(position, material, map, 2, stpq)); v.pipe("point.position", this.uniforms, defines); v.pipe("project.position", this.uniforms); // Shared fragment shader factory.fragment = f = this._fragmentColor( hasStyle, material, color, mask, map, 2, stpq, combine, linear ); // Split fragment into edge and fill pass for better z layering const edgeFactory = shaders.material(); edgeFactory.vertex.pipe(v); f = edgeFactory.fragment.pipe(factory.fragment); f.require(`point.mask.${_shape}`, this.uniforms); f.require(`point.alpha.${alpha}`, this.uniforms); f.pipe("point.edge", this.uniforms); const fillFactory = shaders.material(); fillFactory.vertex.pipe(v); f = fillFactory.fragment.pipe(factory.fragment); f.require(`point.mask.${_shape}`, this.uniforms); f.require(`point.alpha.${alpha}`, this.uniforms); f.pipe("point.fill", this.uniforms); const fillOpts = fillFactory.link({ side: DoubleSide, }); this.fillMaterial = this._material(fillOpts); const edgeOpts = edgeFactory.link({ side: DoubleSide, }); this.edgeMaterial = this._material(edgeOpts); this.fillObject = new Mesh(this.geometry, this.fillMaterial); this.edgeObject = new Mesh(this.geometry, this.edgeMaterial); this._raw(this.fillObject); this.fillObject.userData = fillOpts; this._raw(this.edgeObject); this.edgeObject.userData = edgeOpts; this.renders = [this.fillObject, this.edgeObject]; } show(transparent, blending, order, depth) { this._show(this.edgeObject, true, blending, order, depth); return this._show(this.fillObject, transparent, blending, order, depth); } dispose() { this.geometry.dispose(); this.edgeMaterial.dispose(); this.fillMaterial.dispose(); this.renders = this.edgeObject = this.fillObject = this.geometry = this.edgeMaterial = this.fillMaterial = null; return super.dispose(); } }
cchudzicki/mathbox
src/render/meshes/point.js
JavaScript
mit
4,483
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Base } from "./base.js"; import { DoubleSide } from "three/src/constants.js"; import { Mesh } from "three/src/objects/Mesh.js"; import { ScreenGeometry } from "../geometry/screengeometry.js"; export class Screen extends Base { constructor(renderer, shaders, options) { let f; super(renderer, shaders, options); let { uniforms } = options; const { map, combine, stpq, linear } = options; if (uniforms == null) { uniforms = {}; } const hasStyle = uniforms.styleColor != null; this.geometry = new ScreenGeometry({ width: options.width, height: options.height, }); this._adopt(uniforms); this._adopt(this.geometry.uniforms); const factory = shaders.material(); const v = factory.vertex; v.pipe("raw.position.scale", this.uniforms); v.fan(); v.pipe("stpq.xyzw.2d", this.uniforms); v.next(); v.pipe("screen.position", this.uniforms); v.join(); factory.fragment = f = this._fragmentColor( hasStyle, false, null, null, map, 2, stpq, combine, linear ); f.pipe("fragment.color", this.uniforms); const opts = factory.link({ side: DoubleSide, }); this.material = this._material(opts); const object = new Mesh(this.geometry, this.material); object.frustumCulled = false; object.userData = opts; this._raw(object); this.renders = [object]; } dispose() { this.geometry.dispose(); this.material.dispose(); this.renders = this.geometry = this.material = null; return super.dispose(); } }
cchudzicki/mathbox
src/render/meshes/screen.js
JavaScript
mit
1,976
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Base } from "./base.js"; import { DoubleSide } from "three/src/constants.js"; import { Mesh } from "three/src/objects/Mesh.js"; import { SpriteGeometry } from "../geometry/spritegeometry.js"; export class Sprite extends Base { constructor(renderer, shaders, options) { let f; super(renderer, shaders, options); let { uniforms } = options; const { material, position, sprite, map, combine, linear, color, mask, stpq, } = options; if (uniforms == null) { uniforms = {}; } const hasStyle = uniforms.styleColor != null; this.geometry = new SpriteGeometry({ items: options.items, width: options.width, height: options.height, depth: options.depth, }); this._adopt(uniforms); this._adopt(this.geometry.uniforms); // Shared vertex shader const factory = shaders.material(); const v = factory.vertex; v.pipe(this._vertexColor(color, mask)); v.require(this._vertexPosition(position, material, map, 2, stpq)); v.require(sprite); v.pipe("sprite.position", this.uniforms); v.pipe("project.position", this.uniforms); // Shared fragment shader factory.fragment = f = this._fragmentColor( hasStyle, material, color, mask, map, 2, stpq, combine, linear ); // Split fragment into edge and fill pass for better z layering const edgeFactory = shaders.material(); edgeFactory.vertex.pipe(v); edgeFactory.fragment.pipe(f); edgeFactory.fragment.pipe("fragment.transparent", this.uniforms); const fillFactory = shaders.material(); fillFactory.vertex.pipe(v); fillFactory.fragment.pipe(f); fillFactory.fragment.pipe("fragment.solid", this.uniforms); const fillOpts = fillFactory.link({ side: DoubleSide, }); this.fillMaterial = this._material(fillOpts); const edgeOpts = edgeFactory.link({ side: DoubleSide, }); this.edgeMaterial = this._material(edgeOpts); this.fillObject = new Mesh(this.geometry, this.fillMaterial); this.edgeObject = new Mesh(this.geometry, this.edgeMaterial); this._raw(this.fillObject); this.fillObject.userData = fillOpts; this._raw(this.edgeObject); this.edgeObject.userData = edgeOpts; this.renders = [this.fillObject, this.edgeObject]; } show(transparent, blending, order, depth) { this._show(this.edgeObject, true, blending, order, depth); return this._show(this.fillObject, transparent, blending, order, depth); } dispose() { this.geometry.dispose(); this.edgeMaterial.dispose(); this.fillMaterial.dispose(); this.nreders = this.geometry = this.edgeMaterial = this.fillMaterial = this.edgeObject = this.fillObject = null; return super.dispose(); } }
cchudzicki/mathbox
src/render/meshes/sprite.js
JavaScript
mit
3,252
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Base } from "./base.js"; import { DoubleSide } from "three/src/constants.js"; import { Mesh } from "three/src/objects/Mesh.js"; import { StripGeometry } from "../geometry/stripgeometry.js"; export class Strip extends Base { constructor(renderer, shaders, options) { let f; super(renderer, shaders, options); let { uniforms, material } = options; const { position, color, mask, map, combine, linear, stpq } = options; if (uniforms == null) { uniforms = {}; } if (material == null) { material = true; } const hasStyle = uniforms.styleColor != null; this.geometry = new StripGeometry({ items: options.items, width: options.width, height: options.height, depth: options.depth, }); this._adopt(uniforms); this._adopt(this.geometry.uniforms); const factory = shaders.material(); const v = factory.vertex; v.pipe(this._vertexColor(color, mask)); v.require(this._vertexPosition(position, material, map, 2, stpq)); if (!material) { v.pipe("mesh.position", this.uniforms); } if (material) { v.pipe("strip.position.normal", this.uniforms); } v.pipe("project.position", this.uniforms); factory.fragment = f = this._fragmentColor( hasStyle, material, color, mask, map, 2, stpq, combine, linear ); f.pipe("fragment.color", this.uniforms); const opts = factory.link({ side: DoubleSide, }); this.material = this._material(opts); const object = new Mesh(this.geometry, this.material); object.userData = opts; this._raw(object); this.renders = [object]; } dispose() { this.geometry.dispose(); this.material.dispose(); this.renders = this.geometry = this.material = null; return super.dispose(); } }
cchudzicki/mathbox
src/render/meshes/strip.js
JavaScript
mit
2,226
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Base } from "./base.js"; import { DoubleSide } from "three/src/constants.js"; import { Mesh } from "three/src/objects/Mesh.js"; import { SurfaceGeometry } from "../geometry/surfacegeometry.js"; export class Surface extends Base { constructor(renderer, shaders, options) { let defs, f; super(renderer, shaders, options); let { uniforms, material } = options; const { position, color, mask, map, combine, linear, stpq, intUV } = options; if (uniforms == null) { uniforms = {}; } if (material == null) { material = true; } const hasStyle = uniforms.styleColor != null; this.geometry = new SurfaceGeometry({ width: options.width, height: options.height, surfaces: options.surfaces, layers: options.layers, closedX: options.closedX, closedY: options.closedY, }); this._adopt(uniforms); this._adopt(this.geometry.uniforms); const factory = shaders.material(); const v = factory.vertex; if (intUV) { defs = { POSITION_UV_INT: "" }; } v.pipe(this._vertexColor(color, mask)); v.require(this._vertexPosition(position, material, map, 2, stpq)); if (!material) { v.pipe("surface.position", this.uniforms, defs); } if (material) { v.pipe("surface.position.normal", this.uniforms, defs); } v.pipe("project.position", this.uniforms); factory.fragment = f = this._fragmentColor( hasStyle, material, color, mask, map, 2, stpq, combine, linear ); f.pipe("fragment.color", this.uniforms); const opts = factory.link({ side: DoubleSide, }); this.material = this._material(opts); const object = new Mesh(this.geometry, this.material); object.userData = opts; this._raw(object); this.renders = [object]; } dispose() { this.geometry.dispose(); this.material.dispose(); this.renders = this.geometry = this.material = null; return super.dispose(); } }
cchudzicki/mathbox
src/render/meshes/surface.js
JavaScript
mit
2,405
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ export class Renderable { constructor(renderer, shaders) { this.renderer = renderer; this.shaders = shaders; this.gl = this.renderer.getContext(); if (this.uniforms == null) { this.uniforms = {}; } } dispose() { this.uniforms = null; } _adopt(uniforms) { for (const key in uniforms) { const value = uniforms[key]; this.uniforms[key] = value; } } _set(uniforms) { for (const key in uniforms) { const value = uniforms[key]; if (this.uniforms[key] != null) { this.uniforms[key].value = value; } } } }
cchudzicki/mathbox
src/render/renderable.js
JavaScript
mit
961
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS101: Remove unnecessary use of Array.from * DS102: Remove unnecessary code created because of implicit returns * DS202: Simplify dynamic range loops * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import { Object3D } from "three/src/core/Object3D.js"; import { PerspectiveCamera } from "three/src/cameras/PerspectiveCamera.js"; import { Renderable } from "./renderable.js"; import { Scene as ThreeScene } from "three/src/scenes/Scene.js"; import { WebGLRenderTarget } from "three/src/renderers/WebGLRenderTarget.js"; /* All MathBox renderables sit inside this root, to keep things tidy. */ class MathBox extends Object3D { constructor() { super(); this.rotationAutoUpdate = false; this.frustumCulled = false; this.matrixAutoUpdate = false; } } /* Holds the root and binds to a THREE.Scene Will hold objects and inject them a few at a time to avoid long UI blocks. Will render injected objects to a 1x1 scratch buffer to ensure availability */ export class Scene extends Renderable { constructor(renderer, shaders, options) { super(renderer, shaders, options); this.root = new MathBox(); if ((options != null ? options.scene : undefined) != null) { this.scene = options.scene; } if (this.scene == null) { this.scene = new ThreeScene(); } this.pending = []; this.async = 0; this.scratch = new WebGLRenderTarget(1, 1); this.camera = new PerspectiveCamera(); } inject(scene) { if (scene != null) { this.scene = scene; } return this.scene.add(this.root); } unject() { return this.scene != null ? this.scene.remove(this.root) : undefined; } add(object) { if (this.async) { return this.pending.push(object); } else { return this._add(object); } } remove(object) { this.pending = this.pending.filter((o) => o !== object); if (object.parent != null) { return this._remove(object); } } _add(object) { return this.root.add(object); } _remove(object) { return this.root.remove(object); } dispose() { if (this.root.parent != null) { return this.unject(); } } warmup(n) { return (this.async = +n || 0); } render() { if (!this.pending.length) { return; } const { children } = this.root; // Insert up to @async children const added = []; for ( let i = 0, end = this.async, asc = 0 <= end; asc ? i < end : i > end; asc ? i++ : i-- ) { const pending = this.pending.shift(); if (!pending) { break; } // Insert new child this._add(pending); added.push(added); } // Remember current visibility const visible = children.map(function (o) { return o.visible; }); // Force only this child visible children.map((o) => (o.visible = !Array.from(added).includes(o))); // Render and throw away const currentTarget = this.renderer.getRenderTarget(); this.renderer.setRenderTarget(this.scratch); this.renderer.render(this.scene, this.camera); this.renderer.setRenderTarget(currentTarget); // Restore visibility return children.map((o, i) => (o.visible = visible[i])); } toJSON() { return this.root.toJSON(); } }
cchudzicki/mathbox
src/render/scene.js
JavaScript
mit
3,521
// TODO: This file was created by bulk-decaffeinate. // Sanity-check the conversion and remove this comment. /* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ import * as ShaderGraph from "shadergraph"; export const Factory = function (snippets) { function fetch(name) { // Built-in library const s = snippets[name]; if (s != null) { return s; } // Load from <script> tags by ID const ref = ["#", ".", ":", "["].includes(name[0]); const sel = ref ? name : `#${name}`; const element = document.querySelector(sel); if (element != null && element.tagName === "SCRIPT") { return element.textContent || element.innerText; } throw new Error(`Unknown shader \`${name}\``); } return ShaderGraph.load(fetch, { autoInspect: true }); };
cchudzicki/mathbox
src/shaders/factory.js
JavaScript
mit
993
export default /* glsl */ `uniform float worldUnit; uniform float lineDepth; uniform float lineWidth; uniform float focusDepth; uniform vec4 geometryClip; uniform float arrowSize; uniform float arrowSpace; attribute vec4 position4; attribute vec3 arrow; attribute vec2 attach; // External vec3 getPosition(vec4 xyzw, float canonical); void getArrowGeometry(vec4 xyzw, float near, float far, out vec3 left, out vec3 right, out vec3 start) { right = getPosition(xyzw, 1.0); left = getPosition(vec4(near, xyzw.yzw), 0.0); start = getPosition(vec4(far, xyzw.yzw), 0.0); } mat4 getArrowMatrix(vec3 left, vec3 right, vec3 start) { float depth = focusDepth; if (lineDepth < 1.0) { // Depth blending float z = max(0.00001, -right.z); depth = mix(z, focusDepth, lineDepth); } vec3 diff = left - right; float l = length(diff); if (l == 0.0) { return mat4(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); } // Construct TBN matrix around shaft vec3 t = normalize(diff); vec3 n = normalize(cross(t, t.yzx + vec3(.1, .2, .3))); vec3 b = cross(n, t); // Shrink arrows when vector gets too small // Approach linear scaling with cubic ease the smaller we get float size = arrowSize * lineWidth * worldUnit * depth * 1.25; diff = right - start; l = length(diff) * arrowSpace; float mini = clamp(1.0 - l / size * .333, 0.0, 1.0); float scale = 1.0 - mini * mini * mini; float range = size * scale; // Size to 2.5:1 ratio float rangeNB = range / 2.5; // Anchor at end position return mat4(vec4(n * rangeNB, 0), vec4(b * rangeNB, 0), vec4(t * range, 0), vec4(right, 1.0)); } vec3 getArrowPosition() { vec3 left, right, start; vec4 p = min(geometryClip, position4); getArrowGeometry(p, attach.x, attach.y, left, right, start); mat4 matrix = getArrowMatrix(left, right, start); return (matrix * vec4(arrow.xyz, 1.0)).xyz; } `;
cchudzicki/mathbox
src/shaders/glsl/arrow.position.js
JavaScript
mit
2,036
export default /* glsl */ `uniform vec4 axisStep; uniform vec4 axisPosition; vec4 getAxisPosition(vec4 xyzw, inout vec4 stpq) { return axisStep * xyzw.x + axisPosition; } `;
cchudzicki/mathbox
src/shaders/glsl/axis.position.js
JavaScript
mit
176
export default /* glsl */ `uniform mat4 viewMatrix; vec4 getCartesianPosition(vec4 position, inout vec4 stpq) { return viewMatrix * vec4(position.xyz, 1.0); } `;
cchudzicki/mathbox
src/shaders/glsl/cartesian.position.js
JavaScript
mit
164
export default /* glsl */ `uniform vec4 basisScale; uniform vec4 basisOffset; uniform vec4 viewScale; uniform vec4 viewOffset; vec4 getCartesian4Position(vec4 position, inout vec4 stpq) { return position * basisScale + basisOffset; } `;
cchudzicki/mathbox
src/shaders/glsl/cartesian4.position.js
JavaScript
mit
239
export default /* glsl */ `uniform vec4 clampLimit; vec4 getClampXYZW(vec4 xyzw) { return clamp(xyzw, vec4(0.0), clampLimit); } `;
cchudzicki/mathbox
src/shaders/glsl/clamp.position.js
JavaScript
mit
133
export default /* glsl */ `vec4 opaqueColor(vec4 color) { return vec4(color.rgb, 1.0); } `;
cchudzicki/mathbox
src/shaders/glsl/color.opaque.js
JavaScript
mit
93
export default /* glsl */ `uniform vec4 geometryClip; attribute vec4 position4; // External vec3 getPosition(vec4 xyzw, float canonical); vec3 getFacePosition() { vec4 p = min(geometryClip, position4); return getPosition(p, 1.0); } `;
cchudzicki/mathbox
src/shaders/glsl/face.position.js
JavaScript
mit
240
export default /* glsl */ `attribute vec4 position4; // External vec3 getPosition(vec4 xyzw, float canonical); varying vec3 vNormal; varying vec3 vLight; varying vec3 vPosition; void getFaceGeometry(vec4 xyzw, out vec3 pos, out vec3 normal) { vec3 a, b, c; a = getPosition(vec4(xyzw.xyz, 0.0), 0.0); b = getPosition(vec4(xyzw.xyz, 1.0), 0.0); c = getPosition(vec4(xyzw.xyz, 2.0), 0.0); pos = getPosition(xyzw, 1.0); normal = normalize(cross(c - a, b - a)); } vec3 getFacePositionNormal() { vec3 center, normal; getFaceGeometry(position4, center, normal); vNormal = normal; vLight = normalize((viewMatrix * vec4(1.0, 2.0, 2.0, 0.0)).xyz); vPosition = -center; return center; } `;
cchudzicki/mathbox
src/shaders/glsl/face.position.normal.js
JavaScript
mit
721
export default /* glsl */ `/* Float encoding technique by Carlos Scheidegger https://github.com/cscheid/lux/blob/master/src/shade/bits/encode_float.js Conversion to GLSL by: http://concord-consortium.github.io/lab/experiments/webgl-gpgpu/script.js */ float shift_right(float v, float amt) { v = floor(v) + 0.5; return floor(v / exp2(amt)); } float shift_left(float v, float amt) { return floor(v * exp2(amt) + 0.5); } float mask_last(float v, float bits) { return mod(v, shift_left(1.0, bits)); } float extract_bits(float num, float from, float to) { from = floor(from + 0.5); to = floor(to + 0.5); return mask_last(shift_right(num, from), to - from); } vec4 encode_float(float val) { if (val == 0.0) return vec4(0, 0, 0, 0); float valuesign = val > 0.0 ? 0.0 : 1.0; val = abs(val); float exponent = floor(log2(val)); float biased_exponent = exponent + 127.0; float fraction = ((val / exp2(exponent)) - 1.0) * 8388608.0; float t = biased_exponent / 2.0; float last_bit_of_biased_exponent = fract(t) * 2.0; float remaining_bits_of_biased_exponent = floor(t); float byte4 = extract_bits(fraction, 0.0, 8.0) / 255.0; float byte3 = extract_bits(fraction, 8.0, 16.0) / 255.0; float byte2 = (last_bit_of_biased_exponent * 128.0 + extract_bits(fraction, 16.0, 23.0)) / 255.0; float byte1 = (valuesign * 128.0 + remaining_bits_of_biased_exponent) / 255.0; return vec4(byte4, byte3, byte2, byte1); } `;
cchudzicki/mathbox
src/shaders/glsl/float.encode.js
JavaScript
mit
1,464
export default /* glsl */ `uniform vec4 indexModulus; vec4 getSample(vec4 xyzw); vec4 getIndex(vec4 xyzw); vec4 floatPackIndex(vec4 xyzw) { vec4 value = getSample(xyzw); vec4 index = getIndex(xyzw); vec4 offset = floor(index + .5) * indexModulus; vec2 sum2 = offset.xy + offset.zw; float sum = sum2.x + sum2.y; return vec4(value.xyz, sum); }`;
cchudzicki/mathbox
src/shaders/glsl/float.index.pack.js
JavaScript
mit
358
export default /* glsl */ `vec4 getSample(vec4 xyzw); float floatStretch(vec4 xyzw, float channelIndex) { vec4 sample = getSample(xyzw); vec2 xy = channelIndex > 1.5 ? sample.zw : sample.xy; return mod(channelIndex, 2.0) > .5 ? xy.y : xy.x; }`;
cchudzicki/mathbox
src/shaders/glsl/float.stretch.js
JavaScript
mit
251
export default /* glsl */ `varying float vClipStrokeWidth; varying float vClipStrokeIndex; varying vec3 vClipStrokeEven; varying vec3 vClipStrokeOdd; varying vec3 vClipStrokePosition; void clipStrokeFragment() { bool odd = mod(vClipStrokeIndex, 2.0) >= 1.0; vec3 tangent; if (odd) { tangent = vClipStrokeOdd; } else { tangent = vClipStrokeEven; } float travel = dot(vClipStrokePosition, normalize(tangent)) / vClipStrokeWidth; if (mod(travel, 16.0) > 8.0) { discard; } } `;
cchudzicki/mathbox
src/shaders/glsl/fragment.clip.dashed.js
JavaScript
mit
509
export default /* glsl */ `varying float vClipStrokeWidth; varying float vClipStrokeIndex; varying vec3 vClipStrokeEven; varying vec3 vClipStrokeOdd; varying vec3 vClipStrokePosition; void clipStrokeFragment() { bool odd = mod(vClipStrokeIndex, 2.0) >= 1.0; vec3 tangent; if (odd) { tangent = vClipStrokeOdd; } else { tangent = vClipStrokeEven; } float travel = dot(vClipStrokePosition, normalize(tangent)) / vClipStrokeWidth; if (mod(travel, 4.0) > 2.0) { discard; } } `;
cchudzicki/mathbox
src/shaders/glsl/fragment.clip.dotted.js
JavaScript
mit
508
export default /* glsl */ `varying vec2 vClipEnds; void clipEndsFragment() { if (vClipEnds.x < 0.0 || vClipEnds.y < 0.0) discard; } `;
cchudzicki/mathbox
src/shaders/glsl/fragment.clip.ends.js
JavaScript
mit
137
export default /* glsl */ `varying float vClipProximity; void clipProximityFragment() { if (vClipProximity >= 0.5) discard; }`;
cchudzicki/mathbox
src/shaders/glsl/fragment.clip.proximity.js
JavaScript
mit
130
export default /* glsl */ `void setFragmentColor(vec4 color) { gl_FragColor = color; }`;
cchudzicki/mathbox
src/shaders/glsl/fragment.color.js
JavaScript
mit
90
export default /* glsl */ `vec4 fragmentRGBA(vec4 rgba, vec4 stpq) { return rgba; }`;
cchudzicki/mathbox
src/shaders/glsl/fragment.map.rgba.js
JavaScript
mit
87
export default /* glsl */ `void setFragmentColor(vec4 color) { if (color.a < 1.0) discard; gl_FragColor = color; }`;
cchudzicki/mathbox
src/shaders/glsl/fragment.solid.js
JavaScript
mit
120
export default /* glsl */ `void setFragmentColor(vec4 color) { if (color.a >= 1.0) discard; gl_FragColor = color; }`;
cchudzicki/mathbox
src/shaders/glsl/fragment.transparent.js
JavaScript
mit
121
export default /* glsl */ `uniform vec4 gridPosition; uniform vec4 gridStep; uniform vec4 gridAxis; vec4 sampleData(vec2 xy); vec4 getGridPosition(vec4 xyzw) { vec4 onAxis = gridAxis * sampleData(vec2(xyzw.y, 0.0)).x; vec4 offAxis = gridStep * xyzw.x + gridPosition; return onAxis + offAxis; } `;
cchudzicki/mathbox
src/shaders/glsl/grid.position.js
JavaScript
mit
305
export default /* glsl */ `uniform float growScale; uniform vec4 growMask; uniform vec4 growAnchor; vec4 getSample(vec4 xyzw); vec4 getGrowSample(vec4 xyzw) { vec4 anchor = xyzw * growMask + growAnchor; vec4 position = getSample(xyzw); vec4 center = getSample(anchor); return mix(center, position, growScale); }`;
cchudzicki/mathbox
src/shaders/glsl/grow.position.js
JavaScript
mit
327
export default /* glsl */ `uniform float joinStride; uniform float joinStrideInv; float getIndex(vec4 xyzw); vec4 getRest(vec4 xyzw); vec4 injectIndices(float a, float b); vec4 getJoinXYZW(vec4 xyzw) { float a = getIndex(xyzw); float b = a * joinStrideInv; float integer = floor(b); float fraction = b - integer; return injectIndices(fraction * joinStride, integer) + getRest(xyzw); } `;
cchudzicki/mathbox
src/shaders/glsl/join.position.js
JavaScript
mit
405
export default /* glsl */ `varying float vPixelSize; vec4 getLabelAlphaColor(vec4 color, vec4 sample) { float mask = clamp(sample.r * 1000.0, 0.0, 1.0); float alpha = (sample.r - .5) * vPixelSize + .5; float a = mask * alpha * color.a; if (a <= 0.0) discard; return vec4(color.xyz, a); } `;
cchudzicki/mathbox
src/shaders/glsl/label.alpha.js
JavaScript
mit
301
export default /* glsl */ `vec2 mapUV(vec4 uvwo, vec4 stpq) { return uvwo.xy; } `;
cchudzicki/mathbox
src/shaders/glsl/label.map.js
JavaScript
mit
84
export default /* glsl */ `uniform float outlineExpand; uniform float outlineStep; uniform vec3 outlineColor; varying float vPixelSize; const float PIXEL_STEP = 255.0 / 16.0; vec4 getLabelOutlineColor(vec4 color, vec4 sample) { float ps = vPixelSize * PIXEL_STEP; float os = outlineStep; float sdf = sample.r - .5 + outlineExpand; vec2 sdfs = vec2(sdf, sdf + os); vec2 alpha = clamp(sdfs * ps + .5, 0.0, 1.0); if (alpha.y <= 0.0) { discard; } vec3 blend = color.xyz; if (alpha.y > alpha.x) { blend = sqrt(mix(outlineColor * outlineColor, blend * blend, alpha.x)); } return vec4(blend, alpha.y * color.a); } `;
cchudzicki/mathbox
src/shaders/glsl/label.outline.js
JavaScript
mit
651
export default /* glsl */ `uniform vec4 layerScale; uniform vec4 layerBias; vec4 layerPosition(vec4 position, inout vec4 stpq) { return layerScale * position + layerBias; } `;
cchudzicki/mathbox
src/shaders/glsl/layer.position.js
JavaScript
mit
178
export default /* glsl */ `// External vec4 sampleData(vec4 xyzw); vec4 lerpDepth(vec4 xyzw) { float x = xyzw.z; float i = floor(x); float f = x - i; vec4 xyzw1 = vec4(xyzw.xy, i, xyzw.w); vec4 xyzw2 = vec4(xyzw.xy, i + 1.0, xyzw.w); vec4 a = sampleData(xyzw1); vec4 b = sampleData(xyzw2); return mix(a, b, f); } `;
cchudzicki/mathbox
src/shaders/glsl/lerp.depth.js
JavaScript
mit
341
export default /* glsl */ `// External vec4 sampleData(vec4 xyzw); vec4 lerpHeight(vec4 xyzw) { float x = xyzw.y; float i = floor(x); float f = x - i; vec4 xyzw1 = vec4(xyzw.x, i, xyzw.zw); vec4 xyzw2 = vec4(xyzw.x, i + 1.0, xyzw.zw); vec4 a = sampleData(xyzw1); vec4 b = sampleData(xyzw2); return mix(a, b, f); } `;
cchudzicki/mathbox
src/shaders/glsl/lerp.height.js
JavaScript
mit
342
export default /* glsl */ `// External vec4 sampleData(vec4 xyzw); vec4 lerpItems(vec4 xyzw) { float x = xyzw.w; float i = floor(x); float f = x - i; vec4 xyzw1 = vec4(xyzw.xyz, i); vec4 xyzw2 = vec4(xyzw.xyz, i + 1.0); vec4 a = sampleData(xyzw1); vec4 b = sampleData(xyzw2); return mix(a, b, f); } `;
cchudzicki/mathbox
src/shaders/glsl/lerp.items.js
JavaScript
mit
327
export default /* glsl */ `// External vec4 sampleData(vec4 xyzw); vec4 lerpWidth(vec4 xyzw) { float x = xyzw.x; float i = floor(x); float f = x - i; vec4 xyzw1 = vec4(i, xyzw.yzw); vec4 xyzw2 = vec4(i + 1.0, xyzw.yzw); vec4 a = sampleData(xyzw1); vec4 b = sampleData(xyzw2); return mix(a, b, f); } `;
cchudzicki/mathbox
src/shaders/glsl/lerp.width.js
JavaScript
mit
327
export default /* glsl */ `// Units and calibration uniform float worldUnit; uniform float lineWidth; uniform float lineDepth; uniform float focusDepth; // General data index uniform vec4 geometryClip; attribute vec4 position4; // (Start/mid/end -1/0/1, top/bottom -1,1) attribute vec2 line; // 0...1 for round or bevel joins #ifdef LINE_JOIN_DETAIL attribute float joint; #else const float joint = 0.0; #endif // Knock out excessively long line segments (e.g. for asymtpotes) #ifdef LINE_PROXIMITY uniform float lineProximity; varying float vClipProximity; #endif // Ghetto line stroking (local only, not global) #ifdef LINE_STROKE varying float vClipStrokeWidth; varying float vClipStrokeIndex; varying vec3 vClipStrokeEven; varying vec3 vClipStrokeOdd; varying vec3 vClipStrokePosition; #endif // External vec3 getPosition(vec4 xyzw, float canonical); // Clip line ends for arrows / decoration #ifdef LINE_CLIP uniform float clipRange; uniform vec2 clipStyle; uniform float clipSpace; attribute vec2 strip; varying vec2 vClipEnds; void clipEnds(vec4 xyzw, vec3 center, vec3 pos) { // Sample end of line strip vec4 xyzwE = vec4(strip.y, xyzw.yzw); vec3 end = getPosition(xyzwE, 0.0); // Sample start of line strip vec4 xyzwS = vec4(strip.x, xyzw.yzw); vec3 start = getPosition(xyzwS, 0.0); // Measure length vec3 diff = end - start; float l = length(diff) * clipSpace; // Arrow length (=2.5x radius) float arrowSize = 1.25 * clipRange * lineWidth * worldUnit; vClipEnds = vec2(1.0); if (clipStyle.y > 0.0) { // Depth blend end float depth = focusDepth; if (lineDepth < 1.0) { float z = max(0.00001, -end.z); depth = mix(z, focusDepth, lineDepth); } // Absolute arrow length float size = arrowSize * depth; // Adjust clip range // Approach linear scaling with cubic ease the smaller we get float mini = clamp(1.0 - l / size * .333, 0.0, 1.0); float scale = 1.0 - mini * mini * mini; float invrange = 1.0 / (size * scale); // Clip end diff = end - center; if(diff == vec3(0.0)) vClipEnds.x = -1.0; else { diff = normalize(end - center); float d = dot(end - pos, diff); vClipEnds.x = d * invrange - 1.0; } } if (clipStyle.x > 0.0) { // Depth blend start float depth = focusDepth; if (lineDepth < 1.0) { float z = max(0.00001, -start.z); depth = mix(z, focusDepth, lineDepth); } // Absolute arrow length float size = arrowSize * depth; // Adjust clip range // Approach linear scaling with cubic ease the smaller we get float mini = clamp(1.0 - l / size * .333, 0.0, 1.0); float scale = 1.0 - mini * mini * mini; float invrange = 1.0 / (size * scale); // Clip start diff = center - start; if(diff == vec3(0.0)) vClipEnds.y = -1.0; else { diff = normalize(center - start); float d = dot(pos - start, diff); vClipEnds.y = d * invrange - 1.0; } } } #endif // Adjust left/center/right to be inside near/far z range const float epsilon = 1e-5; void fixCenter(inout vec3 left, inout vec3 center, inout vec3 right) { if (center.z >= 0.0) { if (left.z < 0.0) { float d = (center.z + epsilon) / (center.z - left.z); center = mix(center, left, d); } else if (right.z < 0.0) { float d = (center.z + epsilon) / (center.z - right.z); center = mix(center, right, d); } } if (left.z >= 0.0) { if (center.z < 0.0) { float d = (left.z + epsilon) / (left.z - center.z); left = mix(left, center, d); } } if (right.z >= 0.0) { if (center.z < 0.0) { float d = (right.z + epsilon) / (right.z - center.z); right = mix(right, center, d); } } } // Sample the source data in an edge-aware manner void getLineGeometry(vec4 xyzw, float edge, out vec3 left, out vec3 center, out vec3 right) { vec4 delta = vec4(1.0, 0.0, 0.0, 0.0); center = getPosition(xyzw, 1.0); left = (edge > -0.5) ? getPosition(xyzw - delta, 0.0) : center; right = (edge < 0.5) ? getPosition(xyzw + delta, 0.0) : center; } // Calculate the position for a vertex along the line, including joins vec3 getLineJoin(float edge, bool odd, vec3 left, vec3 center, vec3 right, float width, float offset, float joint) { vec2 join = vec2(1.0, 0.0); fixCenter(left, center, right); vec4 a = vec4(left.xy, right.xy); vec4 b = a / vec4(left.zz, right.zz); vec2 l = b.xy; vec2 r = b.zw; vec2 c = center.xy / center.z; vec4 d = vec4(l, c) - vec4(c, r); float l1 = dot(d.xy, d.xy); float l2 = dot(d.zw, d.zw); if (l1 + l2 > 0.0) { if (edge > 0.5 || l2 == 0.0) { vec2 nl = normalize(d.xy); vec2 tl = vec2(nl.y, -nl.x); #ifdef LINE_PROXIMITY vClipProximity = 1.0; #endif #ifdef LINE_STROKE vClipStrokeEven = vClipStrokeOdd = normalize(left - center); #endif join = tl; } else if (edge < -0.5 || l1 == 0.0) { vec2 nr = normalize(d.zw); vec2 tr = vec2(nr.y, -nr.x); #ifdef LINE_PROXIMITY vClipProximity = 1.0; #endif #ifdef LINE_STROKE vClipStrokeEven = vClipStrokeOdd = normalize(center - right); #endif join = tr; } else { // Limit join stretch for tiny segments float lmin2 = min(l1, l2) / (width * width); // Hide line segment if ratio of leg lengths exceeds promixity threshold #ifdef LINE_PROXIMITY float lr = l1 / l2; float rl = l2 / l1; float ratio = max(lr, rl); float thresh = lineProximity + 1.0; vClipProximity = (ratio > thresh * thresh) ? 1.0 : 0.0; #endif // Calculate normals/tangents vec2 nl = normalize(d.xy); vec2 nr = normalize(d.zw); // Calculate tangents vec2 tl = vec2(nl.y, -nl.x); vec2 tr = vec2(nr.y, -nr.x); #ifdef LINE_PROXIMITY // Mix tangents according to leg lengths vec2 tc = normalize(mix(tl, tr, l1/(l1+l2))); #else // Average tangent vec2 tc = normalize(tl + tr); #endif // Miter join float cosA = dot(nl, tc); float sinA = max(0.1, abs(dot(tl, tc))); float factor = cosA / sinA; float scale = sqrt(1.0 + min(lmin2, factor * factor)); // Stroke normals #ifdef LINE_STROKE vec3 stroke1 = normalize(left - center); vec3 stroke2 = normalize(center - right); if (odd) { vClipStrokeEven = stroke1; vClipStrokeOdd = stroke2; } else { vClipStrokeEven = stroke2; vClipStrokeOdd = stroke1; } #endif #ifdef LINE_JOIN_MITER // Apply straight up miter join = tc * scale; #endif #ifdef LINE_JOIN_ROUND // Slerp bevel join into circular arc float dotProduct = dot(nl, nr); float angle = acos(dotProduct); float sinT = sin(angle); join = (sin((1.0 - joint) * angle) * tl + sin(joint * angle) * tr) / sinT; #endif #ifdef LINE_JOIN_BEVEL // Direct bevel join between two flat ends float dotProduct = dot(nl, nr); join = mix(tl, tr, joint); #endif #ifdef LINE_JOIN_DETAIL // Check if on inside or outside of joint float crossProduct = nl.x * nr.y - nl.y * nr.x; if (offset * crossProduct < 0.0) { // For near-180-degree bends, correct back to a miter to avoid discontinuities float ratio = clamp(-dotProduct * 2.0 - 1.0, 0.0, 1.0); // Otherwise collapse the inside vertices into one. join = mix(tc * scale, join, ratio * ratio * ratio); } #endif } return vec3(join, 0.0); } else { return vec3(0.0); } } // Calculate final line position vec3 getLinePosition() { vec3 left, center, right, join; // left/center/right float edge = line.x; // up/down float offset = line.y; // Clip data vec4 p = min(geometryClip, position4); edge += max(0.0, position4.x - geometryClip.x); // Get position + adjacent neighbours getLineGeometry(p, edge, left, center, right); #ifdef LINE_STROKE // Set parameters for line stroke fragment shader vClipStrokePosition = center; vClipStrokeIndex = p.x; bool odd = mod(p.x, 2.0) >= 1.0; #else bool odd = true; #endif // Divide line width up/down float width = lineWidth * 0.5; float depth = focusDepth; if (lineDepth < 1.0) { // Depth blending float z = max(0.00001, -center.z); depth = mix(z, focusDepth, lineDepth); } width *= depth; // Convert to world units width *= worldUnit; // Calculate line join join = getLineJoin(edge, odd, left, center, right, width, offset, joint); vec3 pos = center + join * offset * width; #ifdef LINE_STROKE vClipStrokeWidth = width; #endif #ifdef LINE_CLIP clipEnds(p, center, pos); #endif return pos; } `;
cchudzicki/mathbox
src/shaders/glsl/line.position.js
JavaScript
mit
8,759
export default /* glsl */ `uniform vec2 dataResolution; uniform vec2 dataPointer; vec2 map2DData(vec2 xy) { return (xy + dataPointer) * dataResolution; } `;
cchudzicki/mathbox
src/shaders/glsl/map.2d.data.js
JavaScript
mit
159
export default /* glsl */ `uniform vec2 dataResolution; uniform vec2 dataPointer; vec2 map2DData(vec2 xy) { return fract((xy + dataPointer) * dataResolution); } `;
cchudzicki/mathbox
src/shaders/glsl/map.2d.data.wrap.js
JavaScript
mit
166
export default /* glsl */ `void mapXyzw2DV(vec4 xyzw, out vec2 xy, out float z) { xy = xyzw.xy; z = xyzw.z; } `;
cchudzicki/mathbox
src/shaders/glsl/map.xyzw.2dv.js
JavaScript
mit
118
export default /* glsl */ `vec4 alignXYZW(vec4 xyzw) { return floor(xyzw + .5); } `;
cchudzicki/mathbox
src/shaders/glsl/map.xyzw.align.js
JavaScript
mit
87
export default /* glsl */ `uniform float textureItems; uniform float textureHeight; vec2 mapXyzwTexture(vec4 xyzw) { float x = xyzw.x; float y = xyzw.y; float z = xyzw.z; float i = xyzw.w; return vec2(i, y) + vec2(x, z) * vec2(textureItems, textureHeight); } `;
cchudzicki/mathbox
src/shaders/glsl/map.xyzw.texture.js
JavaScript
mit
279
export default /* glsl */ `varying vec4 vColor; vec4 getColor() { return vColor; } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.fragment.color.js
JavaScript
mit
88
export default /* glsl */ `#ifdef POSITION_STPQ varying vec4 vSTPQ; #endif #ifdef POSITION_U varying float vU; #endif #ifdef POSITION_UV varying vec2 vUV; #endif #ifdef POSITION_UVW varying vec3 vUVW; #endif #ifdef POSITION_UVWO varying vec4 vUVWO; #endif vec4 getSample(vec4 uvwo, vec4 stpq); vec4 getMapColor() { #ifdef POSITION_STPQ vec4 stpq = vSTPQ; #else vec4 stpq = vec4(0.0); #endif #ifdef POSITION_U vec4 uvwo = vec4(vU, 0.0, 0.0, 0.0); #endif #ifdef POSITION_UV vec4 uvwo = vec4(vUV, 0.0, 0.0); #endif #ifdef POSITION_UVW vec4 uvwo = vec4(vUVW, 0.0); #endif #ifdef POSITION_UVWO vec4 uvwo = vec4(vUVWO); #endif return getSample(uvwo, stpq); } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.fragment.map.js
JavaScript
mit
695
export default /* glsl */ `varying float vMask; float ease(float t) { t = clamp(t, 0.0, 1.0); return t * t * (3.0 - 2.0 * t); } vec4 maskColor() { if (vMask <= 0.0) discard; return vec4(vec3(1.0), ease(vMask)); } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.fragment.mask.js
JavaScript
mit
225
export default /* glsl */ `#ifdef POSITION_STPQ varying vec4 vSTPQ; #endif #ifdef POSITION_U varying float vU; #endif #ifdef POSITION_UV varying vec2 vUV; #endif #ifdef POSITION_UVW varying vec3 vUVW; #endif #ifdef POSITION_UVWO varying vec4 vUVWO; #endif vec4 getSample(vec4 rgba, vec4 stpq); vec4 getMaterialColor(vec4 rgba) { vec4 stpq = vec4(0.0); #ifdef POSITION_U stpq.x = vU; #endif #ifdef POSITION_UV stpq.xy = vUV; #endif #ifdef POSITION_UVW stpq.xyz = vUVW; #endif #ifdef POSITION_UVWO stpq = vUVWO; #endif #ifdef POSITION_STPQ stpq = vSTPQ; #endif return getSample(rgba, stpq); } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.fragment.material.js
JavaScript
mit
632
export default /* glsl */ `varying vec3 vNormal; varying vec3 vLight; varying vec3 vPosition; vec3 offSpecular(vec3 color) { vec3 c = 1.0 - color; return 1.0 - c * c; } vec4 getShadedColor(vec4 rgba) { vec3 color = rgba.xyz; vec3 color2 = offSpecular(rgba.xyz); vec3 normal = normalize(vNormal); vec3 light = normalize(vLight); vec3 position = normalize(vPosition); float side = gl_FrontFacing ? -1.0 : 1.0; float cosine = side * dot(normal, light); float diffuse = mix(max(0.0, cosine), .5 + .5 * cosine, .1); vec3 halfLight = normalize(light + position); float cosineHalf = max(0.0, side * dot(normal, halfLight)); float specular = pow(cosineHalf, 16.0); return vec4(color * (diffuse * .9 + .05) + .25 * color2 * specular, rgba.a); } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.fragment.shaded.js
JavaScript
mit
782
export default /* glsl */ ``;
cchudzicki/mathbox
src/shaders/glsl/mesh.fragment.texture.js
JavaScript
mit
29
export default /* glsl */ `vec4 getGammaInColor(vec4 rgba) { return vec4(rgba.rgb * rgba.rgb, rgba.a); } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.gamma.in.js
JavaScript
mit
109
export default /* glsl */ `vec4 getGammaOutColor(vec4 rgba) { return vec4(sqrt(rgba.rgb), rgba.a); } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.gamma.out.js
JavaScript
mit
105
export default /* glsl */ `vec4 mapUVWO(vec4 uvwo, vec4 stpq) { return uvwo; } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.map.uvwo.js
JavaScript
mit
83
export default /* glsl */ `uniform vec4 geometryClip; attribute vec4 position4; // External vec3 getPosition(vec4 xyzw, float canonical); vec3 getMeshPosition() { vec4 p = min(geometryClip, position4); return getPosition(p, 1.0); } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.position.js
JavaScript
mit
240
export default /* glsl */ `attribute vec4 position4; uniform vec4 geometryClip; varying vec4 vColor; // External vec4 getSample(vec4 xyzw); void vertexColor() { vec4 p = min(geometryClip, position4); vColor = getSample(p); } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.vertex.color.js
JavaScript
mit
233
export default /* glsl */ `attribute vec4 position4; uniform vec4 geometryResolution; uniform vec4 geometryClip; varying float vMask; // External float getSample(vec4 xyzw); void maskLevel() { vec4 p = min(geometryClip, position4); vMask = getSample(p * geometryResolution); } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.vertex.mask.js
JavaScript
mit
285
export default /* glsl */ `uniform vec4 geometryResolution; #ifdef POSITION_STPQ varying vec4 vSTPQ; #endif #ifdef POSITION_U varying float vU; #endif #ifdef POSITION_UV varying vec2 vUV; #endif #ifdef POSITION_UVW varying vec3 vUVW; #endif #ifdef POSITION_UVWO varying vec4 vUVWO; #endif // External vec3 getPosition(vec4 xyzw, in vec4 stpqIn, out vec4 stpqOut); vec3 getMeshPosition(vec4 xyzw, float canonical) { vec4 stpqOut, stpqIn = xyzw * geometryResolution; vec3 xyz = getPosition(xyzw, stpqIn, stpqOut); #ifdef POSITION_MAP if (canonical > 0.5) { #ifdef POSITION_STPQ vSTPQ = stpqOut; #endif #ifdef POSITION_U vU = stpqOut.x; #endif #ifdef POSITION_UV vUV = stpqOut.xy; #endif #ifdef POSITION_UVW vUVW = stpqOut.xyz; #endif #ifdef POSITION_UVWO vUVWO = stpqOut; #endif } #endif return xyz; } `;
cchudzicki/mathbox
src/shaders/glsl/mesh.vertex.position.js
JavaScript
mit
880
export default /* glsl */ `uniform float transitionEnter; uniform float transitionExit; uniform vec4 transitionScale; uniform vec4 transitionBias; uniform float transitionSkew; uniform float transitionActive; uniform vec4 moveFrom; uniform vec4 moveTo; float ease(float t) { t = clamp(t, 0.0, 1.0); return 1.0 - (2.0 - t) * t; } vec4 getTransitionPosition(vec4 xyzw, inout vec4 stpq) { if (transitionActive < 0.5) return xyzw; float enter = transitionEnter; float exit = transitionExit; float skew = transitionSkew; vec4 scale = transitionScale; vec4 bias = transitionBias; float factor = 1.0 + skew; float offset = dot(vec4(1.0), stpq * scale + bias); float a1 = ease(enter * factor - offset); float a2 = ease(exit * factor + offset - skew); return xyzw + a1 * moveFrom + a2 * moveTo; }`;
cchudzicki/mathbox
src/shaders/glsl/move.position.js
JavaScript
mit
844
export default /* glsl */ `vec4 getMask(vec4 xyzw) { return vec4(1.0); }`;
cchudzicki/mathbox
src/shaders/glsl/object.mask.default.js
JavaScript
mit
76
export default /* glsl */ `varying float vPixelSize; float getDiscHollowAlpha(float mask) { return vPixelSize * (0.5 - 2.0 * abs(sqrt(mask) - .75)); } `;
cchudzicki/mathbox
src/shaders/glsl/point.alpha.circle.hollow.js
JavaScript
mit
156
export default /* glsl */ `varying float vPixelSize; float getDiscAlpha(float mask) { // Approximation: 1 - x*x is approximately linear around x = 1 with slope 2 return vPixelSize * (1.0 - mask); // return vPixelSize * 2.0 * (1.0 - sqrt(mask)); } `;
cchudzicki/mathbox
src/shaders/glsl/point.alpha.circle.js
JavaScript
mit
257
export default /* glsl */ `varying float vPixelSize; float getGenericHollowAlpha(float mask) { return vPixelSize * (0.5 - 2.0 * abs(mask - .75)); } `;
cchudzicki/mathbox
src/shaders/glsl/point.alpha.generic.hollow.js
JavaScript
mit
153