UNPKG

14.8 kBJavaScriptView Raw
1"use strict";
2var color = require("@pixi/color"), constants = require("@pixi/constants"), extensions = require("@pixi/extensions"), settings = require("@pixi/settings"), utils = require("@pixi/utils"), ViewableBuffer = require("../geometry/ViewableBuffer.js"), checkMaxIfStatementsInShader = require("../shader/utils/checkMaxIfStatementsInShader.js"), State = require("../state/State.js"), BaseTexture = require("../textures/BaseTexture.js"), BatchDrawCall = require("./BatchDrawCall.js"), BatchGeometry = require("./BatchGeometry.js"), BatchShaderGenerator = require("./BatchShaderGenerator.js"), BatchTextureArray = require("./BatchTextureArray.js"), canUploadSameBuffer = require("./canUploadSameBuffer.js"), maxRecommendedTextures = require("./maxRecommendedTextures.js"), ObjectRenderer = require("./ObjectRenderer.js"), texture$1 = require("./texture.frag.js"), texture = require("./texture.vert.js");
3const _BatchRenderer = class _BatchRenderer2 extends ObjectRenderer.ObjectRenderer {
4 /**
5 * This will hook onto the renderer's `contextChange`
6 * and `prerender` signals.
7 * @param {PIXI.Renderer} renderer - The renderer this works for.
8 */
9 constructor(renderer) {
10 super(renderer), this.setShaderGenerator(), this.geometryClass = BatchGeometry.BatchGeometry, this.vertexSize = 6, this.state = State.State.for2d(), this.size = _BatchRenderer2.defaultBatchSize * 4, this._vertexCount = 0, this._indexCount = 0, this._bufferedElements = [], this._bufferedTextures = [], this._bufferSize = 0, this._shader = null, this._packedGeometries = [], this._packedGeometryPoolSize = 2, this._flushId = 0, this._aBuffers = {}, this._iBuffers = {}, this.maxTextures = 1, this.renderer.on("prerender", this.onPrerender, this), renderer.runners.contextChange.add(this), this._dcIndex = 0, this._aIndex = 0, this._iIndex = 0, this._attributeBuffer = null, this._indexBuffer = null, this._tempBoundTextures = [];
11 }
12 /**
13 * The maximum textures that this device supports.
14 * @static
15 * @default 32
16 */
17 static get defaultMaxTextures() {
18 return this._defaultMaxTextures = this._defaultMaxTextures ?? maxRecommendedTextures.maxRecommendedTextures(32), this._defaultMaxTextures;
19 }
20 static set defaultMaxTextures(value) {
21 this._defaultMaxTextures = value;
22 }
23 /**
24 * Can we upload the same buffer in a single frame?
25 * @static
26 */
27 static get canUploadSameBuffer() {
28 return this._canUploadSameBuffer = this._canUploadSameBuffer ?? canUploadSameBuffer.canUploadSameBuffer(), this._canUploadSameBuffer;
29 }
30 static set canUploadSameBuffer(value) {
31 this._canUploadSameBuffer = value;
32 }
33 /**
34 * @see PIXI.BatchRenderer#maxTextures
35 * @deprecated since 7.1.0
36 * @readonly
37 */
38 get MAX_TEXTURES() {
39 return utils.deprecation("7.1.0", "BatchRenderer#MAX_TEXTURES renamed to BatchRenderer#maxTextures"), this.maxTextures;
40 }
41 /**
42 * The default vertex shader source
43 * @readonly
44 */
45 static get defaultVertexSrc() {
46 return texture.default;
47 }
48 /**
49 * The default fragment shader source
50 * @readonly
51 */
52 static get defaultFragmentTemplate() {
53 return texture$1.default;
54 }
55 /**
56 * Set the shader generator.
57 * @param {object} [options]
58 * @param {string} [options.vertex=PIXI.BatchRenderer.defaultVertexSrc] - Vertex shader source
59 * @param {string} [options.fragment=PIXI.BatchRenderer.defaultFragmentTemplate] - Fragment shader template
60 */
61 setShaderGenerator({
62 vertex = _BatchRenderer2.defaultVertexSrc,
63 fragment = _BatchRenderer2.defaultFragmentTemplate
64 } = {}) {
65 this.shaderGenerator = new BatchShaderGenerator.BatchShaderGenerator(vertex, fragment);
66 }
67 /**
68 * Handles the `contextChange` signal.
69 *
70 * It calculates `this.maxTextures` and allocating the packed-geometry object pool.
71 */
72 contextChange() {
73 const gl = this.renderer.gl;
74 settings.settings.PREFER_ENV === constants.ENV.WEBGL_LEGACY ? this.maxTextures = 1 : (this.maxTextures = Math.min(
75 gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS),
76 _BatchRenderer2.defaultMaxTextures
77 ), this.maxTextures = checkMaxIfStatementsInShader.checkMaxIfStatementsInShader(
78 this.maxTextures,
79 gl
80 )), this._shader = this.shaderGenerator.generateShader(this.maxTextures);
81 for (let i = 0; i < this._packedGeometryPoolSize; i++)
82 this._packedGeometries[i] = new this.geometryClass();
83 this.initFlushBuffers();
84 }
85 /** Makes sure that static and dynamic flush pooled objects have correct dimensions. */
86 initFlushBuffers() {
87 const {
88 _drawCallPool,
89 _textureArrayPool
90 } = _BatchRenderer2, MAX_SPRITES = this.size / 4, MAX_TA = Math.floor(MAX_SPRITES / this.maxTextures) + 1;
91 for (; _drawCallPool.length < MAX_SPRITES; )
92 _drawCallPool.push(new BatchDrawCall.BatchDrawCall());
93 for (; _textureArrayPool.length < MAX_TA; )
94 _textureArrayPool.push(new BatchTextureArray.BatchTextureArray());
95 for (let i = 0; i < this.maxTextures; i++)
96 this._tempBoundTextures[i] = null;
97 }
98 /** Handles the `prerender` signal. It ensures that flushes start from the first geometry object again. */
99 onPrerender() {
100 this._flushId = 0;
101 }
102 /**
103 * Buffers the "batchable" object. It need not be rendered immediately.
104 * @param {PIXI.DisplayObject} element - the element to render when
105 * using this renderer
106 */
107 render(element) {
108 element._texture.valid && (this._vertexCount + element.vertexData.length / 2 > this.size && this.flush(), this._vertexCount += element.vertexData.length / 2, this._indexCount += element.indices.length, this._bufferedTextures[this._bufferSize] = element._texture.baseTexture, this._bufferedElements[this._bufferSize++] = element);
109 }
110 buildTexturesAndDrawCalls() {
111 const {
112 _bufferedTextures: textures,
113 maxTextures
114 } = this, textureArrays = _BatchRenderer2._textureArrayPool, batch = this.renderer.batch, boundTextures = this._tempBoundTextures, touch = this.renderer.textureGC.count;
115 let TICK = ++BaseTexture.BaseTexture._globalBatch, countTexArrays = 0, texArray = textureArrays[0], start = 0;
116 batch.copyBoundTextures(boundTextures, maxTextures);
117 for (let i = 0; i < this._bufferSize; ++i) {
118 const tex = textures[i];
119 textures[i] = null, tex._batchEnabled !== TICK && (texArray.count >= maxTextures && (batch.boundArray(texArray, boundTextures, TICK, maxTextures), this.buildDrawCalls(texArray, start, i), start = i, texArray = textureArrays[++countTexArrays], ++TICK), tex._batchEnabled = TICK, tex.touched = touch, texArray.elements[texArray.count++] = tex);
120 }
121 texArray.count > 0 && (batch.boundArray(texArray, boundTextures, TICK, maxTextures), this.buildDrawCalls(texArray, start, this._bufferSize), ++countTexArrays, ++TICK);
122 for (let i = 0; i < boundTextures.length; i++)
123 boundTextures[i] = null;
124 BaseTexture.BaseTexture._globalBatch = TICK;
125 }
126 /**
127 * Populating drawcalls for rendering
128 * @param texArray
129 * @param start
130 * @param finish
131 */
132 buildDrawCalls(texArray, start, finish) {
133 const {
134 _bufferedElements: elements,
135 _attributeBuffer,
136 _indexBuffer,
137 vertexSize
138 } = this, drawCalls = _BatchRenderer2._drawCallPool;
139 let dcIndex = this._dcIndex, aIndex = this._aIndex, iIndex = this._iIndex, drawCall = drawCalls[dcIndex];
140 drawCall.start = this._iIndex, drawCall.texArray = texArray;
141 for (let i = start; i < finish; ++i) {
142 const sprite = elements[i], tex = sprite._texture.baseTexture, spriteBlendMode = utils.premultiplyBlendMode[tex.alphaMode ? 1 : 0][sprite.blendMode];
143 elements[i] = null, start < i && drawCall.blend !== spriteBlendMode && (drawCall.size = iIndex - drawCall.start, start = i, drawCall = drawCalls[++dcIndex], drawCall.texArray = texArray, drawCall.start = iIndex), this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex), aIndex += sprite.vertexData.length / 2 * vertexSize, iIndex += sprite.indices.length, drawCall.blend = spriteBlendMode;
144 }
145 start < finish && (drawCall.size = iIndex - drawCall.start, ++dcIndex), this._dcIndex = dcIndex, this._aIndex = aIndex, this._iIndex = iIndex;
146 }
147 /**
148 * Bind textures for current rendering
149 * @param texArray
150 */
151 bindAndClearTexArray(texArray) {
152 const textureSystem = this.renderer.texture;
153 for (let j = 0; j < texArray.count; j++)
154 textureSystem.bind(texArray.elements[j], texArray.ids[j]), texArray.elements[j] = null;
155 texArray.count = 0;
156 }
157 updateGeometry() {
158 const {
159 _packedGeometries: packedGeometries,
160 _attributeBuffer: attributeBuffer,
161 _indexBuffer: indexBuffer
162 } = this;
163 _BatchRenderer2.canUploadSameBuffer ? (packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData), packedGeometries[this._flushId]._indexBuffer.update(indexBuffer), this.renderer.geometry.updateBuffers()) : (this._packedGeometryPoolSize <= this._flushId && (this._packedGeometryPoolSize++, packedGeometries[this._flushId] = new this.geometryClass()), packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData), packedGeometries[this._flushId]._indexBuffer.update(indexBuffer), this.renderer.geometry.bind(packedGeometries[this._flushId]), this.renderer.geometry.updateBuffers(), this._flushId++);
164 }
165 drawBatches() {
166 const dcCount = this._dcIndex, { gl, state: stateSystem } = this.renderer, drawCalls = _BatchRenderer2._drawCallPool;
167 let curTexArray = null;
168 for (let i = 0; i < dcCount; i++) {
169 const { texArray, type, size, start, blend } = drawCalls[i];
170 curTexArray !== texArray && (curTexArray = texArray, this.bindAndClearTexArray(texArray)), this.state.blendMode = blend, stateSystem.set(this.state), gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2);
171 }
172 }
173 /** Renders the content _now_ and empties the current batch. */
174 flush() {
175 this._vertexCount !== 0 && (this._attributeBuffer = this.getAttributeBuffer(this._vertexCount), this._indexBuffer = this.getIndexBuffer(this._indexCount), this._aIndex = 0, this._iIndex = 0, this._dcIndex = 0, this.buildTexturesAndDrawCalls(), this.updateGeometry(), this.drawBatches(), this._bufferSize = 0, this._vertexCount = 0, this._indexCount = 0);
176 }
177 /** Starts a new sprite batch. */
178 start() {
179 this.renderer.state.set(this.state), this.renderer.texture.ensureSamplerType(this.maxTextures), this.renderer.shader.bind(this._shader), _BatchRenderer2.canUploadSameBuffer && this.renderer.geometry.bind(this._packedGeometries[this._flushId]);
180 }
181 /** Stops and flushes the current batch. */
182 stop() {
183 this.flush();
184 }
185 /** Destroys this `BatchRenderer`. It cannot be used again. */
186 destroy() {
187 for (let i = 0; i < this._packedGeometryPoolSize; i++)
188 this._packedGeometries[i] && this._packedGeometries[i].destroy();
189 this.renderer.off("prerender", this.onPrerender, this), this._aBuffers = null, this._iBuffers = null, this._packedGeometries = null, this._attributeBuffer = null, this._indexBuffer = null, this._shader && (this._shader.destroy(), this._shader = null), super.destroy();
190 }
191 /**
192 * Fetches an attribute buffer from `this._aBuffers` that can hold atleast `size` floats.
193 * @param size - minimum capacity required
194 * @returns - buffer than can hold atleast `size` floats
195 */
196 getAttributeBuffer(size) {
197 const roundedP2 = utils.nextPow2(Math.ceil(size / 8)), roundedSizeIndex = utils.log2(roundedP2), roundedSize = roundedP2 * 8;
198 this._aBuffers.length <= roundedSizeIndex && (this._iBuffers.length = roundedSizeIndex + 1);
199 let buffer = this._aBuffers[roundedSize];
200 return buffer || (this._aBuffers[roundedSize] = buffer = new ViewableBuffer.ViewableBuffer(roundedSize * this.vertexSize * 4)), buffer;
201 }
202 /**
203 * Fetches an index buffer from `this._iBuffers` that can
204 * have at least `size` capacity.
205 * @param size - minimum required capacity
206 * @returns - buffer that can fit `size` indices.
207 */
208 getIndexBuffer(size) {
209 const roundedP2 = utils.nextPow2(Math.ceil(size / 12)), roundedSizeIndex = utils.log2(roundedP2), roundedSize = roundedP2 * 12;
210 this._iBuffers.length <= roundedSizeIndex && (this._iBuffers.length = roundedSizeIndex + 1);
211 let buffer = this._iBuffers[roundedSizeIndex];
212 return buffer || (this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize)), buffer;
213 }
214 /**
215 * Takes the four batching parameters of `element`, interleaves
216 * and pushes them into the batching attribute/index buffers given.
217 *
218 * It uses these properties: `vertexData` `uvs`, `textureId` and
219 * `indicies`. It also uses the "tint" of the base-texture, if
220 * present.
221 * @param {PIXI.DisplayObject} element - element being rendered
222 * @param attributeBuffer - attribute buffer.
223 * @param indexBuffer - index buffer
224 * @param aIndex - number of floats already in the attribute buffer
225 * @param iIndex - number of indices already in `indexBuffer`
226 */
227 packInterleavedGeometry(element, attributeBuffer, indexBuffer, aIndex, iIndex) {
228 const {
229 uint32View,
230 float32View
231 } = attributeBuffer, packedVertices = aIndex / this.vertexSize, uvs = element.uvs, indicies = element.indices, vertexData = element.vertexData, textureId = element._texture.baseTexture._batchLocation, alpha = Math.min(element.worldAlpha, 1), argb = color.Color.shared.setValue(element._tintRGB).toPremultiplied(alpha, element._texture.baseTexture.alphaMode > 0);
232 for (let i = 0; i < vertexData.length; i += 2)
233 float32View[aIndex++] = vertexData[i], float32View[aIndex++] = vertexData[i + 1], float32View[aIndex++] = uvs[i], float32View[aIndex++] = uvs[i + 1], uint32View[aIndex++] = argb, float32View[aIndex++] = textureId;
234 for (let i = 0; i < indicies.length; i++)
235 indexBuffer[iIndex++] = packedVertices + indicies[i];
236 }
237};
238_BatchRenderer.defaultBatchSize = 4096, /** @ignore */
239_BatchRenderer.extension = {
240 name: "batch",
241 type: extensions.ExtensionType.RendererPlugin
242}, /**
243* Pool of `BatchDrawCall` objects that `flush` used
244* to create "batches" of the objects being rendered.
245*
246* These are never re-allocated again.
247* Shared between all batch renderers because it can be only one "flush" working at the moment.
248* @member {PIXI.BatchDrawCall[]}
249*/
250_BatchRenderer._drawCallPool = [], /**
251* Pool of `BatchDrawCall` objects that `flush` used
252* to create "batches" of the objects being rendered.
253*
254* These are never re-allocated again.
255* Shared between all batch renderers because it can be only one "flush" working at the moment.
256* @member {PIXI.BatchTextureArray[]}
257*/
258_BatchRenderer._textureArrayPool = [];
259let BatchRenderer = _BatchRenderer;
260extensions.extensions.add(BatchRenderer);
261exports.BatchRenderer = BatchRenderer;
262//# sourceMappingURL=BatchRenderer.js.map