Make code prettier

This updates ESLint and our shared eslint-config-openlayers to use Prettier.  Most formatting changes were automatically applied with this:

    npm run lint -- --fix

A few manual changes were required:

 * In `examples/offscreen-canvas.js`, the `//eslint-disable-line` comment needed to be moved to the appropriate line to disable the error about the `'worker-loader!./offscreen-canvas.worker.js'` import.
 * In `examples/webpack/exapmle-builder.js`, spaces could not be added after a couple `function`s for some reason.  While editing this, I reworked `ExampleBuilder` to be a class.
 * In `src/ol/format/WMSGetFeatureInfo.js`, the `// @ts-ignore` comment needed to be moved down one line so it applied to the `parsersNS` argument.
This commit is contained in:
Tim Schaub
2020-04-06 12:25:12 -06:00
parent 53b48baf62
commit 054af09032
790 changed files with 46833 additions and 33765 deletions
+3 -5
View File
@@ -1,8 +1,8 @@
/**
* @module ol/webgl/Buffer
*/
import {STATIC_DRAW, STREAM_DRAW, DYNAMIC_DRAW} from '../webgl.js';
import {ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER} from '../webgl.js';
import {DYNAMIC_DRAW, STATIC_DRAW, STREAM_DRAW} from '../webgl.js';
import {assert} from '../asserts.js';
/**
@@ -13,7 +13,7 @@ import {assert} from '../asserts.js';
export const BufferUsage = {
STATIC_DRAW: STATIC_DRAW,
STREAM_DRAW: STREAM_DRAW,
DYNAMIC_DRAW: DYNAMIC_DRAW
DYNAMIC_DRAW: DYNAMIC_DRAW,
};
/**
@@ -33,14 +33,12 @@ export const BufferUsage = {
* @api
*/
class WebGLArrayBuffer {
/**
* @param {number} type Buffer type, either ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER.
* @param {number=} opt_usage Intended usage, either `STATIC_DRAW`, `STREAM_DRAW` or `DYNAMIC_DRAW`.
* Default is `DYNAMIC_DRAW`.
*/
constructor(type, opt_usage) {
/**
* @private
* @type {Float32Array|Uint32Array}
@@ -75,7 +73,7 @@ class WebGLArrayBuffer {
* @param {Array<number>} array Numerical array
*/
fromArray(array) {
this.array = (getArrayClassForType(this.type)).from(array);
this.array = getArrayClassForType(this.type).from(array);
}
/**
+1 -1
View File
@@ -7,5 +7,5 @@
*/
export default {
LOST: 'webglcontextlost',
RESTORED: 'webglcontextrestored'
RESTORED: 'webglcontextrestored',
};
+232 -102
View File
@@ -1,23 +1,29 @@
/**
* @module ol/webgl/Helper
*/
import {getUid} from '../util.js';
import Disposable from '../Disposable.js';
import {clear} from '../obj.js';
import ContextEventType from '../webgl/ContextEventType.js';
import Disposable from '../Disposable.js';
import WebGLPostProcessingPass from './PostProcessingPass.js';
import {
FLOAT,
UNSIGNED_BYTE,
UNSIGNED_INT,
UNSIGNED_SHORT,
getContext,
getSupportedExtensions,
} from '../webgl.js';
import {assert} from '../asserts.js';
import {clear} from '../obj.js';
import {
compose as composeTransform,
create as createTransform,
reset as resetTransform,
rotate as rotateTransform,
scale as scaleTransform
scale as scaleTransform,
} from '../transform.js';
import {create, fromTransform} from '../vec/mat4.js';
import WebGLPostProcessingPass from './PostProcessingPass.js';
import {FLOAT, getContext, getSupportedExtensions, UNSIGNED_BYTE, UNSIGNED_INT, UNSIGNED_SHORT} from '../webgl.js';
import {getUid} from '../util.js';
import {includes} from '../array.js';
import {assert} from '../asserts.js';
/**
* @typedef {Object} BufferCacheEntry
@@ -30,8 +36,8 @@ import {assert} from '../asserts.js';
* @enum {number}
*/
export const ShaderType = {
FRAGMENT_SHADER: 0x8B30,
VERTEX_SHADER: 0x8B31
FRAGMENT_SHADER: 0x8b30,
VERTEX_SHADER: 0x8b31,
};
/**
@@ -45,7 +51,7 @@ export const DefaultUniform = {
OFFSET_ROTATION_MATRIX: 'u_offsetRotateMatrix',
TIME: 'u_time',
ZOOM: 'u_zoom',
RESOLUTION: 'u_resolution'
RESOLUTION: 'u_resolution',
};
/**
@@ -57,7 +63,7 @@ export const AttributeType = {
UNSIGNED_BYTE: UNSIGNED_BYTE,
UNSIGNED_SHORT: UNSIGNED_SHORT,
UNSIGNED_INT: UNSIGNED_INT,
FLOAT: FLOAT
FLOAT: FLOAT,
};
/**
@@ -242,7 +248,9 @@ class WebGLHelper extends Disposable {
this.boundHandleWebGLContextLost_ = this.handleWebGLContextLost.bind(this);
/** @private */
this.boundHandleWebGLContextRestored_ = this.handleWebGLContextRestored.bind(this);
this.boundHandleWebGLContextRestored_ = this.handleWebGLContextRestored.bind(
this
);
/**
* @private
@@ -252,7 +260,6 @@ class WebGLHelper extends Disposable {
this.canvas_.style.position = 'absolute';
this.canvas_.style.left = '0';
/**
* @private
* @type {WebGLRenderingContext}
@@ -275,8 +282,14 @@ class WebGLHelper extends Disposable {
assert(includes(getSupportedExtensions(), 'OES_element_index_uint'), 63);
gl.getExtension('OES_element_index_uint');
this.canvas_.addEventListener(ContextEventType.LOST, this.boundHandleWebGLContextLost_);
this.canvas_.addEventListener(ContextEventType.RESTORED, this.boundHandleWebGLContextRestored_);
this.canvas_.addEventListener(
ContextEventType.LOST,
this.boundHandleWebGLContextLost_
);
this.canvas_.addEventListener(
ContextEventType.RESTORED,
this.boundHandleWebGLContextRestored_
);
/**
* @private
@@ -319,7 +332,7 @@ class WebGLHelper extends Disposable {
for (const name in options.uniforms) {
this.uniforms_.push({
name: name,
value: options.uniforms[name]
value: options.uniforms[name],
});
}
}
@@ -331,15 +344,17 @@ class WebGLHelper extends Disposable {
* @type {Array<WebGLPostProcessingPass>}
* @private
*/
this.postProcessPasses_ = options.postProcesses ? options.postProcesses.map(function(options) {
return new WebGLPostProcessingPass({
webGlContext: gl,
scaleRatio: options.scaleRatio,
vertexShader: options.vertexShader,
fragmentShader: options.fragmentShader,
uniforms: options.uniforms
});
}) : [new WebGLPostProcessingPass({webGlContext: gl})];
this.postProcessPasses_ = options.postProcesses
? options.postProcesses.map(function (options) {
return new WebGLPostProcessingPass({
webGlContext: gl,
scaleRatio: options.scaleRatio,
vertexShader: options.vertexShader,
fragmentShader: options.fragmentShader,
uniforms: options.uniforms,
});
})
: [new WebGLPostProcessingPass({webGlContext: gl})];
/**
* @type {string|null}
@@ -369,7 +384,7 @@ class WebGLHelper extends Disposable {
const webGlBuffer = gl.createBuffer();
bufferCache = {
buffer: buffer,
webGlBuffer: webGlBuffer
webGlBuffer: webGlBuffer,
};
this.bufferCache_[bufferKey] = bufferCache;
}
@@ -405,8 +420,14 @@ class WebGLHelper extends Disposable {
* Clean up.
*/
disposeInternal() {
this.canvas_.removeEventListener(ContextEventType.LOST, this.boundHandleWebGLContextLost_);
this.canvas_.removeEventListener(ContextEventType.RESTORED, this.boundHandleWebGLContextRestored_);
this.canvas_.removeEventListener(
ContextEventType.LOST,
this.boundHandleWebGLContextLost_
);
this.canvas_.removeEventListener(
ContextEventType.RESTORED,
this.boundHandleWebGLContextRestored_
);
}
/**
@@ -464,7 +485,10 @@ class WebGLHelper extends Disposable {
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, opt_disableAlphaBlend ? gl.ZERO : gl.ONE_MINUS_SRC_ALPHA);
gl.blendFunc(
gl.ONE,
opt_disableAlphaBlend ? gl.ZERO : gl.ONE_MINUS_SRC_ALPHA
);
gl.useProgram(this.currentProgram_);
this.applyFrameState(frameState);
@@ -495,7 +519,10 @@ class WebGLHelper extends Disposable {
finalizeDraw(frameState) {
// apply post processes using the next one as target
for (let i = 0; i < this.postProcessPasses_.length; i++) {
this.postProcessPasses_[i].apply(frameState, this.postProcessPasses_[i + 1] || null);
this.postProcessPasses_[i].apply(
frameState,
this.postProcessPasses_[i + 1] || null
);
}
}
@@ -533,12 +560,24 @@ class WebGLHelper extends Disposable {
rotateTransform(offsetRotateMatrix, -rotation);
}
this.setUniformMatrixValue(DefaultUniform.OFFSET_SCALE_MATRIX, fromTransform(this.tmpMat4_, offsetScaleMatrix));
this.setUniformMatrixValue(DefaultUniform.OFFSET_ROTATION_MATRIX, fromTransform(this.tmpMat4_, offsetRotateMatrix));
this.setUniformMatrixValue(
DefaultUniform.OFFSET_SCALE_MATRIX,
fromTransform(this.tmpMat4_, offsetScaleMatrix)
);
this.setUniformMatrixValue(
DefaultUniform.OFFSET_ROTATION_MATRIX,
fromTransform(this.tmpMat4_, offsetRotateMatrix)
);
this.setUniformFloatValue(DefaultUniform.TIME, (Date.now() - this.startTime_) * 0.001);
this.setUniformFloatValue(
DefaultUniform.TIME,
(Date.now() - this.startTime_) * 0.001
);
this.setUniformFloatValue(DefaultUniform.ZOOM, frameState.viewState.zoom);
this.setUniformFloatValue(DefaultUniform.RESOLUTION, frameState.viewState.resolution);
this.setUniformFloatValue(
DefaultUniform.RESOLUTION,
frameState.viewState.resolution
);
}
/**
@@ -551,51 +590,86 @@ class WebGLHelper extends Disposable {
let value;
let textureSlot = 0;
this.uniforms_.forEach(function(uniform) {
value = typeof uniform.value === 'function' ? uniform.value(frameState) : uniform.value;
this.uniforms_.forEach(
function (uniform) {
value =
typeof uniform.value === 'function'
? uniform.value(frameState)
: uniform.value;
// apply value based on type
if (value instanceof HTMLCanvasElement || value instanceof HTMLImageElement || value instanceof ImageData) {
// create a texture & put data
if (!uniform.texture) {
uniform.prevValue = undefined;
uniform.texture = gl.createTexture();
// apply value based on type
if (
value instanceof HTMLCanvasElement ||
value instanceof HTMLImageElement ||
value instanceof ImageData
) {
// create a texture & put data
if (!uniform.texture) {
uniform.prevValue = undefined;
uniform.texture = gl.createTexture();
}
gl.activeTexture(gl[`TEXTURE${textureSlot}`]);
gl.bindTexture(gl.TEXTURE_2D, uniform.texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
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);
const imageReady =
!(value instanceof HTMLImageElement) ||
/** @type {HTMLImageElement} */ (value).complete;
if (imageReady && uniform.prevValue !== value) {
uniform.prevValue = value;
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
gl.RGBA,
gl.UNSIGNED_BYTE,
value
);
}
// fill texture slots by increasing index
gl.uniform1i(this.getUniformLocation(uniform.name), textureSlot++);
} else if (Array.isArray(value) && value.length === 6) {
this.setUniformMatrixValue(
uniform.name,
fromTransform(this.tmpMat4_, value)
);
} else if (Array.isArray(value) && value.length <= 4) {
switch (value.length) {
case 2:
gl.uniform2f(
this.getUniformLocation(uniform.name),
value[0],
value[1]
);
return;
case 3:
gl.uniform3f(
this.getUniformLocation(uniform.name),
value[0],
value[1],
value[2]
);
return;
case 4:
gl.uniform4f(
this.getUniformLocation(uniform.name),
value[0],
value[1],
value[2],
value[3]
);
return;
default:
return;
}
} else if (typeof value === 'number') {
gl.uniform1f(this.getUniformLocation(uniform.name), value);
}
gl.activeTexture(gl[`TEXTURE${textureSlot}`]);
gl.bindTexture(gl.TEXTURE_2D, uniform.texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
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);
const imageReady = !(value instanceof HTMLImageElement) || /** @type {HTMLImageElement} */(value).complete;
if (imageReady && uniform.prevValue !== value) {
uniform.prevValue = value;
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, value);
}
// fill texture slots by increasing index
gl.uniform1i(this.getUniformLocation(uniform.name), textureSlot++);
} else if (Array.isArray(value) && value.length === 6) {
this.setUniformMatrixValue(uniform.name, fromTransform(this.tmpMat4_, value));
} else if (Array.isArray(value) && value.length <= 4) {
switch (value.length) {
case 2:
gl.uniform2f(this.getUniformLocation(uniform.name), value[0], value[1]);
return;
case 3:
gl.uniform3f(this.getUniformLocation(uniform.name), value[0], value[1], value[2]);
return;
case 4:
gl.uniform4f(this.getUniformLocation(uniform.name), value[0], value[1], value[2], value[3]);
return;
default:
return;
}
} else if (typeof value === 'number') {
gl.uniform1f(this.getUniformLocation(uniform.name), value);
}
}.bind(this));
}.bind(this)
);
}
/**
@@ -645,17 +719,27 @@ class WebGLHelper extends Disposable {
getProgram(fragmentShaderSource, vertexShaderSource) {
const gl = this.getGL();
const fragmentShader = this.compileShader(fragmentShaderSource, gl.FRAGMENT_SHADER);
const vertexShader = this.compileShader(vertexShaderSource, gl.VERTEX_SHADER);
const fragmentShader = this.compileShader(
fragmentShaderSource,
gl.FRAGMENT_SHADER
);
const vertexShader = this.compileShader(
vertexShaderSource,
gl.VERTEX_SHADER
);
this.shaderCompileErrors_ = null;
if (gl.getShaderInfoLog(fragmentShader)) {
this.shaderCompileErrors_ =
`Fragment shader compilation failed:\n${gl.getShaderInfoLog(fragmentShader)}`;
this.shaderCompileErrors_ = `Fragment shader compilation failed:\n${gl.getShaderInfoLog(
fragmentShader
)}`;
}
if (gl.getShaderInfoLog(vertexShader)) {
this.shaderCompileErrors_ = (this.shaderCompileErrors_ || '') +
`Vertex shader compilation failed:\n${gl.getShaderInfoLog(vertexShader)}`;
this.shaderCompileErrors_ =
(this.shaderCompileErrors_ || '') +
`Vertex shader compilation failed:\n${gl.getShaderInfoLog(
vertexShader
)}`;
}
const program = gl.createProgram();
@@ -682,7 +766,10 @@ class WebGLHelper extends Disposable {
*/
getUniformLocation(name) {
if (this.uniformLocations_[name] === undefined) {
this.uniformLocations_[name] = this.getGL().getUniformLocation(this.currentProgram_, name);
this.uniformLocations_[name] = this.getGL().getUniformLocation(
this.currentProgram_,
name
);
}
return this.uniformLocations_[name];
}
@@ -695,7 +782,10 @@ class WebGLHelper extends Disposable {
*/
getAttributeLocation(name) {
if (this.attribLocations_[name] === undefined) {
this.attribLocations_[name] = this.getGL().getAttribLocation(this.currentProgram_, name);
this.attribLocations_[name] = this.getGL().getAttribLocation(
this.currentProgram_,
name
);
}
return this.attribLocations_[name];
}
@@ -715,11 +805,15 @@ class WebGLHelper extends Disposable {
const center = frameState.viewState.center;
resetTransform(transform);
composeTransform(transform,
0, 0,
2 / (resolution * size[0]), 2 / (resolution * size[1]),
composeTransform(
transform,
0,
0,
2 / (resolution * size[0]),
2 / (resolution * size[1]),
-rotation,
-center[0], -center[1]
-center[0],
-center[1]
);
return transform;
}
@@ -741,7 +835,11 @@ class WebGLHelper extends Disposable {
* @api
*/
setUniformMatrixValue(uniform, value) {
this.getGL().uniformMatrix4fv(this.getUniformLocation(uniform), false, value);
this.getGL().uniformMatrix4fv(
this.getUniformLocation(uniform),
false,
value
);
}
/**
@@ -761,8 +859,14 @@ class WebGLHelper extends Disposable {
return;
}
this.getGL().enableVertexAttribArray(location);
this.getGL().vertexAttribPointer(location, size, type,
false, stride, offset);
this.getGL().vertexAttribPointer(
location,
size,
type,
false,
stride,
offset
);
}
/**
@@ -777,7 +881,13 @@ class WebGLHelper extends Disposable {
let offset = 0;
for (let i = 0; i < attributes.length; i++) {
const attr = attributes[i];
this.enableAttributeArray_(attr.name, attr.size, attr.type || FLOAT, stride, offset);
this.enableAttributeArray_(
attr.name,
attr.size,
attr.type || FLOAT,
stride,
offset
);
offset += attr.size * getByteSizeFromType(attr.type);
}
}
@@ -795,8 +905,7 @@ class WebGLHelper extends Disposable {
* WebGL context was restored
* @private
*/
handleWebGLContextRestored() {
}
handleWebGLContextRestored() {}
/**
* Will create or reuse a given webgl texture and apply the given size. If no image data
@@ -821,9 +930,26 @@ class WebGLHelper extends Disposable {
const type = gl.UNSIGNED_BYTE;
gl.bindTexture(gl.TEXTURE_2D, texture);
if (opt_data) {
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, format, type, opt_data);
gl.texImage2D(
gl.TEXTURE_2D,
level,
internalFormat,
format,
type,
opt_data
);
} else {
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, size[0], size[1], border, format, type, null);
gl.texImage2D(
gl.TEXTURE_2D,
level,
internalFormat,
size[0],
size[1],
border,
format,
type,
null
);
}
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
@@ -855,11 +981,15 @@ export function computeAttributesStride(attributes) {
*/
function getByteSizeFromType(type) {
switch (type) {
case AttributeType.UNSIGNED_BYTE: return Uint8Array.BYTES_PER_ELEMENT;
case AttributeType.UNSIGNED_SHORT: return Uint16Array.BYTES_PER_ELEMENT;
case AttributeType.UNSIGNED_INT: return Uint32Array.BYTES_PER_ELEMENT;
case AttributeType.UNSIGNED_BYTE:
return Uint8Array.BYTES_PER_ELEMENT;
case AttributeType.UNSIGNED_SHORT:
return Uint16Array.BYTES_PER_ELEMENT;
case AttributeType.UNSIGNED_INT:
return Uint32Array.BYTES_PER_ELEMENT;
case AttributeType.FLOAT:
default: return Float32Array.BYTES_PER_ELEMENT;
default:
return Float32Array.BYTES_PER_ELEMENT;
}
}
+104 -38
View File
@@ -97,7 +97,6 @@ const DEFAULT_FRAGMENT_SHADER = `
* @api
*/
class WebGLPostProcessingPass {
/**
* @param {Options} options Options.
*/
@@ -115,10 +114,16 @@ class WebGLPostProcessingPass {
// compile the program for the frame buffer
// TODO: make compilation errors show up
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, options.vertexShader || DEFAULT_VERTEX_SHADER);
gl.shaderSource(
vertexShader,
options.vertexShader || DEFAULT_VERTEX_SHADER
);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, options.fragmentShader || DEFAULT_FRAGMENT_SHADER);
gl.shaderSource(
fragmentShader,
options.fragmentShader || DEFAULT_FRAGMENT_SHADER
);
gl.compileShader(fragmentShader);
this.renderTargetProgram_ = gl.createProgram();
gl.attachShader(this.renderTargetProgram_, vertexShader);
@@ -127,20 +132,26 @@ class WebGLPostProcessingPass {
// bind the vertices buffer for the frame buffer
this.renderTargetVerticesBuffer_ = gl.createBuffer();
const verticesArray = [
-1, -1,
1, -1,
-1, 1,
1, -1,
1, 1,
-1, 1
];
const verticesArray = [-1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1];
gl.bindBuffer(gl.ARRAY_BUFFER, this.renderTargetVerticesBuffer_);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verticesArray), gl.STATIC_DRAW);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array(verticesArray),
gl.STATIC_DRAW
);
this.renderTargetAttribLocation_ = gl.getAttribLocation(this.renderTargetProgram_, 'a_position');
this.renderTargetUniformLocation_ = gl.getUniformLocation(this.renderTargetProgram_, 'u_screenSize');
this.renderTargetTextureLocation_ = gl.getUniformLocation(this.renderTargetProgram_, 'u_image');
this.renderTargetAttribLocation_ = gl.getAttribLocation(
this.renderTargetProgram_,
'a_position'
);
this.renderTargetUniformLocation_ = gl.getUniformLocation(
this.renderTargetProgram_,
'u_screenSize'
);
this.renderTargetTextureLocation_ = gl.getUniformLocation(
this.renderTargetProgram_,
'u_image'
);
/**
* Holds info about custom uniforms used in the post processing pass
@@ -148,12 +159,15 @@ class WebGLPostProcessingPass {
* @private
*/
this.uniforms_ = [];
options.uniforms && Object.keys(options.uniforms).forEach(function(name) {
this.uniforms_.push({
value: options.uniforms[name],
location: gl.getUniformLocation(this.renderTargetProgram_, name)
});
}.bind(this));
options.uniforms &&
Object.keys(options.uniforms).forEach(
function (name) {
this.uniforms_.push({
value: options.uniforms[name],
location: gl.getUniformLocation(this.renderTargetProgram_, name),
});
}.bind(this)
);
}
/**
@@ -176,7 +190,7 @@ class WebGLPostProcessingPass {
const gl = this.getGL();
const textureSize = [
gl.drawingBufferWidth * this.scaleRatio_,
gl.drawingBufferHeight * this.scaleRatio_
gl.drawingBufferHeight * this.scaleRatio_,
];
// rendering goes to my buffer
@@ -184,8 +198,11 @@ class WebGLPostProcessingPass {
gl.viewport(0, 0, textureSize[0], textureSize[1]);
// if size has changed: adjust canvas & render target texture
if (!this.renderTargetTextureSize_ ||
this.renderTargetTextureSize_[0] !== textureSize[0] || this.renderTargetTextureSize_[1] !== textureSize[1]) {
if (
!this.renderTargetTextureSize_ ||
this.renderTargetTextureSize_[0] !== textureSize[0] ||
this.renderTargetTextureSize_[1] !== textureSize[1]
) {
this.renderTargetTextureSize_ = textureSize;
// create a new texture
@@ -196,16 +213,30 @@ class WebGLPostProcessingPass {
const type = gl.UNSIGNED_BYTE;
const data = null;
gl.bindTexture(gl.TEXTURE_2D, this.renderTargetTexture_);
gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
textureSize[0], textureSize[1],
border, format, type, data);
gl.texImage2D(
gl.TEXTURE_2D,
level,
internalFormat,
textureSize[0],
textureSize[1],
border,
format,
type,
data
);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
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);
// bind the texture to the framebuffer
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.renderTargetTexture_, 0);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
this.renderTargetTexture_,
0
);
}
}
@@ -219,7 +250,10 @@ class WebGLPostProcessingPass {
const gl = this.getGL();
const size = frameState.size;
gl.bindFramebuffer(gl.FRAMEBUFFER, nextPass ? nextPass.getFrameBuffer() : null);
gl.bindFramebuffer(
gl.FRAMEBUFFER,
nextPass ? nextPass.getFrameBuffer() : null
);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, this.renderTargetTexture_);
@@ -234,7 +268,14 @@ class WebGLPostProcessingPass {
gl.useProgram(this.renderTargetProgram_);
gl.enableVertexAttribArray(this.renderTargetAttribLocation_);
gl.vertexAttribPointer(this.renderTargetAttribLocation_, 2, gl.FLOAT, false, 0, 0);
gl.vertexAttribPointer(
this.renderTargetAttribLocation_,
2,
gl.FLOAT,
false,
0,
0
);
gl.uniform2f(this.renderTargetUniformLocation_, size[0], size[1]);
gl.uniform1i(this.renderTargetTextureLocation_, 0);
@@ -261,8 +302,11 @@ class WebGLPostProcessingPass {
let value;
let textureSlot = 1;
this.uniforms_.forEach(function(uniform) {
value = typeof uniform.value === 'function' ? uniform.value(frameState) : uniform.value;
this.uniforms_.forEach(function (uniform) {
value =
typeof uniform.value === 'function'
? uniform.value(frameState)
: uniform.value;
// apply value based on type
if (value instanceof HTMLCanvasElement || value instanceof ImageData) {
@@ -277,15 +321,30 @@ class WebGLPostProcessingPass {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
if (value instanceof ImageData) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, value.width, value.height, 0,
gl.UNSIGNED_BYTE, new Uint8Array(value.data));
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
gl.RGBA,
value.width,
value.height,
0,
gl.UNSIGNED_BYTE,
new Uint8Array(value.data)
);
} else {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, value);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
gl.RGBA,
gl.UNSIGNED_BYTE,
value
);
}
// fill texture slots
gl.uniform1i(uniform.location, textureSlot++);
} else if (Array.isArray(value)) {
switch (value.length) {
case 2:
@@ -295,9 +354,16 @@ class WebGLPostProcessingPass {
gl.uniform3f(uniform.location, value[0], value[1], value[2]);
return;
case 4:
gl.uniform4f(uniform.location, value[0], value[1], value[2], value[3]);
gl.uniform4f(
uniform.location,
value[0],
value[1],
value[2],
value[3]
);
return;
default:
return;
default: return;
}
} else if (typeof value === 'number') {
gl.uniform1f(uniform.location, value);
+18 -4
View File
@@ -14,7 +14,6 @@ const tmpArray4 = new Uint8Array(4);
* @api
*/
class WebGLRenderTarget {
/**
* @param {import("./Helper.js").default} helper WebGL helper; mandatory.
* @param {Array<number>} [opt_size] Expected size of the render target texture; note: this can be changed later on.
@@ -106,7 +105,15 @@ class WebGLRenderTarget {
const gl = this.helper_.getGL();
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer_);
gl.readPixels(0, 0, size[0], size[1], gl.RGBA, gl.UNSIGNED_BYTE, this.data_);
gl.readPixels(
0,
0,
size[0],
size[1],
gl.RGBA,
gl.UNSIGNED_BYTE,
this.data_
);
this.dataCacheDirty_ = false;
}
return this.data_;
@@ -131,7 +138,8 @@ class WebGLRenderTarget {
}
this.readAll();
const index = Math.floor(x) + (this.size_[1] - Math.floor(y) - 1) * this.size_[0];
const index =
Math.floor(x) + (this.size_[1] - Math.floor(y) - 1) * this.size_[0];
tmpArray4[0] = this.data_[index * 4];
tmpArray4[1] = this.data_[index * 4 + 1];
tmpArray4[2] = this.data_[index * 4 + 2];
@@ -164,7 +172,13 @@ class WebGLRenderTarget {
gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer_);
gl.viewport(0, 0, size[0], size[1]);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture_, 0);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
this.texture_,
0
);
this.data_ = new Uint8Array(size[0] * size[1] * 4);
}
+99 -46
View File
@@ -3,7 +3,11 @@
* @module ol/webgl/ShaderBuilder
*/
import {expressionToGlsl, getStringNumberEquivalent, ValueTypes} from '../style/expressions.js';
import {
ValueTypes,
expressionToGlsl,
getStringNumberEquivalent,
} from '../style/expressions.js';
/**
* @typedef {Object} VaryingDescription
@@ -127,7 +131,7 @@ export class ShaderBuilder {
this.varyings.push({
name: name,
type: type,
expression: expression
expression: expression,
});
return this;
}
@@ -271,9 +275,9 @@ export class ShaderBuilder {
* @returns {string} The full shader as a string.
*/
getSymbolVertexShader(forHitDetection) {
const offsetMatrix = this.rotateWithView ?
'u_offsetScaleMatrix * u_offsetRotateMatrix' :
'u_offsetScaleMatrix';
const offsetMatrix = this.rotateWithView
? 'u_offsetScaleMatrix * u_offsetRotateMatrix'
: 'u_offsetScaleMatrix';
let attributes = this.attributes;
let varyings = this.varyings;
@@ -283,7 +287,7 @@ export class ShaderBuilder {
varyings = varyings.concat({
name: 'v_hitColor',
type: 'vec4',
expression: 'a_hitColor'
expression: 'a_hitColor',
});
}
@@ -294,19 +298,25 @@ uniform mat4 u_offsetRotateMatrix;
uniform float u_time;
uniform float u_zoom;
uniform float u_resolution;
${this.uniforms.map(function(uniform) {
${this.uniforms
.map(function (uniform) {
return 'uniform ' + uniform + ';';
}).join('\n')}
})
.join('\n')}
attribute vec2 a_position;
attribute float a_index;
${attributes.map(function(attribute) {
${attributes
.map(function (attribute) {
return 'attribute ' + attribute + ';';
}).join('\n')}
})
.join('\n')}
varying vec2 v_texCoord;
varying vec2 v_quadCoord;
${varyings.map(function(varying) {
${varyings
.map(function (varying) {
return 'varying ' + varying.type + ' ' + varying.name + ';';
}).join('\n')}
})
.join('\n')}
void main(void) {
mat4 offsetMatrix = ${offsetMatrix};
vec2 halfSize = ${this.sizeExpression} * 0.5;
@@ -336,9 +346,11 @@ void main(void) {
u = a_index == 0.0 || a_index == 3.0 ? 0.0 : 1.0;
v = a_index == 2.0 || a_index == 3.0 ? 0.0 : 1.0;
v_quadCoord = vec2(u, v);
${varyings.map(function(varying) {
${varyings
.map(function (varying) {
return ' ' + varying.name + ' = ' + varying.expression + ';';
}).join('\n')}
})
.join('\n')}
}`;
}
@@ -354,8 +366,9 @@ ${varyings.map(function(varying) {
* @returns {string} The full shader as a string.
*/
getSymbolFragmentShader(forHitDetection) {
const hitDetectionBypass = forHitDetection ?
' if (gl_FragColor.a < 0.1) { discard; } gl_FragColor = v_hitColor;' : '';
const hitDetectionBypass = forHitDetection
? ' if (gl_FragColor.a < 0.1) { discard; } gl_FragColor = v_hitColor;'
: '';
let varyings = this.varyings;
@@ -363,7 +376,7 @@ ${varyings.map(function(varying) {
varyings = varyings.concat({
name: 'v_hitColor',
type: 'vec4',
expression: 'a_hitColor'
expression: 'a_hitColor',
});
}
@@ -371,14 +384,18 @@ ${varyings.map(function(varying) {
uniform float u_time;
uniform float u_zoom;
uniform float u_resolution;
${this.uniforms.map(function(uniform) {
${this.uniforms
.map(function (uniform) {
return 'uniform ' + uniform + ';';
}).join('\n')}
})
.join('\n')}
varying vec2 v_texCoord;
varying vec2 v_quadCoord;
${varyings.map(function(varying) {
${varyings
.map(function (varying) {
return 'varying ' + varying.type + ' ' + varying.name + ';';
}).join('\n')}
})
.join('\n')}
void main(void) {
if (${this.discardExpression}) { discard; }
gl_FragColor = ${this.colorExpression};
@@ -422,12 +439,28 @@ export function parseLiteralStyle(style) {
inFragmentShader: false,
variables: [],
attributes: [],
stringLiteralsMap: {}
stringLiteralsMap: {},
};
const parsedSize = expressionToGlsl(vertContext, size, ValueTypes.NUMBER_ARRAY | ValueTypes.NUMBER);
const parsedOffset = expressionToGlsl(vertContext, offset, ValueTypes.NUMBER_ARRAY);
const parsedTexCoord = expressionToGlsl(vertContext, texCoord, ValueTypes.NUMBER_ARRAY);
const parsedRotation = expressionToGlsl(vertContext, rotation, ValueTypes.NUMBER);
const parsedSize = expressionToGlsl(
vertContext,
size,
ValueTypes.NUMBER_ARRAY | ValueTypes.NUMBER
);
const parsedOffset = expressionToGlsl(
vertContext,
offset,
ValueTypes.NUMBER_ARRAY
);
const parsedTexCoord = expressionToGlsl(
vertContext,
texCoord,
ValueTypes.NUMBER_ARRAY
);
const parsedRotation = expressionToGlsl(
vertContext,
rotation,
ValueTypes.NUMBER
);
/**
* @type {import("../style/expressions.js").ParsingContext}
@@ -436,16 +469,26 @@ export function parseLiteralStyle(style) {
inFragmentShader: true,
variables: vertContext.variables,
attributes: [],
stringLiteralsMap: vertContext.stringLiteralsMap
stringLiteralsMap: vertContext.stringLiteralsMap,
};
const parsedColor = expressionToGlsl(fragContext, color, ValueTypes.COLOR);
const parsedOpacity = expressionToGlsl(fragContext, opacity, ValueTypes.NUMBER);
const parsedOpacity = expressionToGlsl(
fragContext,
opacity,
ValueTypes.NUMBER
);
let opacityFilter = '1.0';
const visibleSize = `vec2(${expressionToGlsl(fragContext, size, ValueTypes.NUMBER_ARRAY | ValueTypes.NUMBER)}).x`;
const visibleSize = `vec2(${expressionToGlsl(
fragContext,
size,
ValueTypes.NUMBER_ARRAY | ValueTypes.NUMBER
)}).x`;
switch (symbStyle.symbolType) {
case 'square': break;
case 'image': break;
case 'square':
break;
case 'image':
break;
// taken from https://thebookofshaders.com/07/
case 'circle':
opacityFilter = `(1.0-smoothstep(1.-4./${visibleSize},1.,dot(v_quadCoord-.5,v_quadCoord-.5)*4.))`;
@@ -456,7 +499,8 @@ export function parseLiteralStyle(style) {
opacityFilter = `(1.0-smoothstep(.5-3./${visibleSize},.5,cos(floor(.5+${a}/2.094395102)*2.094395102-${a})*length(${st})))`;
break;
default: throw new Error('Unexpected symbol type: ' + symbStyle.symbolType);
default:
throw new Error('Unexpected symbol type: ' + symbStyle.symbolType);
}
const builder = new ShaderBuilder()
@@ -466,10 +510,15 @@ export function parseLiteralStyle(style) {
.setTextureCoordinateExpression(parsedTexCoord)
.setSymbolRotateWithView(!!symbStyle.rotateWithView)
.setColorExpression(
`vec4(${parsedColor}.rgb, ${parsedColor}.a * ${parsedOpacity} * ${opacityFilter})`);
`vec4(${parsedColor}.rgb, ${parsedColor}.a * ${parsedOpacity} * ${opacityFilter})`
);
if (style.filter) {
const parsedFilter = expressionToGlsl(fragContext, style.filter, ValueTypes.BOOLEAN);
const parsedFilter = expressionToGlsl(
fragContext,
style.filter,
ValueTypes.BOOLEAN
);
builder.setFragmentDiscardExpression(`!${parsedFilter}`);
}
@@ -477,11 +526,13 @@ export function parseLiteralStyle(style) {
const uniforms = {};
// define one uniform per variable
fragContext.variables.forEach(function(varName) {
fragContext.variables.forEach(function (varName) {
builder.addUniform(`float u_${varName}`);
uniforms[`u_${varName}`] = function() {
uniforms[`u_${varName}`] = function () {
if (!style.variables || style.variables[varName] === undefined) {
throw new Error(`The following variable is missing from the style: ${varName}`);
throw new Error(
`The following variable is missing from the style: ${varName}`
);
}
let value = style.variables[varName];
if (typeof value === 'string') {
@@ -494,15 +545,17 @@ export function parseLiteralStyle(style) {
if (symbStyle.symbolType === 'image' && symbStyle.src) {
const texture = new Image();
texture.src = symbStyle.src;
builder.addUniform('sampler2D u_texture')
.setColorExpression(builder.getColorExpression() +
' * texture2D(u_texture, v_texCoord)');
builder
.addUniform('sampler2D u_texture')
.setColorExpression(
builder.getColorExpression() + ' * texture2D(u_texture, v_texCoord)'
);
uniforms['u_texture'] = texture;
}
// for each feature attribute used in the fragment shader, define a varying that will be used to pass data
// from the vertex to the fragment shader, as well as an attribute in the vertex shader (if not already present)
fragContext.attributes.forEach(function(attrName) {
fragContext.attributes.forEach(function (attrName) {
if (vertContext.attributes.indexOf(attrName) === -1) {
vertContext.attributes.push(attrName);
}
@@ -510,24 +563,24 @@ export function parseLiteralStyle(style) {
});
// for each feature attribute used in the vertex shader, define an attribute in the vertex shader.
vertContext.attributes.forEach(function(attrName) {
vertContext.attributes.forEach(function (attrName) {
builder.addAttribute(`float a_${attrName}`);
});
return {
builder: builder,
attributes: vertContext.attributes.map(function(attributeName) {
attributes: vertContext.attributes.map(function (attributeName) {
return {
name: attributeName,
callback: function(feature, props) {
callback: function (feature, props) {
let value = props[attributeName];
if (typeof value === 'string') {
value = getStringNumberEquivalent(vertContext, value);
}
return value !== undefined ? value : -9999999; // to avoid matching with the first string literal
}
},
};
}),
uniforms: uniforms
uniforms: uniforms,
};
}