UNPKG

2 kBJavaScriptView Raw
1import { Matrix } from '@pixi/math';
2import { Program } from '../shader/Program.mjs';
3import { Shader } from '../shader/Shader.mjs';
4import { UniformGroup } from '../shader/UniformGroup.mjs';
5
6class BatchShaderGenerator {
7 constructor(vertexSrc, fragTemplate) {
8 this.vertexSrc = vertexSrc;
9 this.fragTemplate = fragTemplate;
10 this.programCache = {};
11 this.defaultGroupCache = {};
12 if (!fragTemplate.includes("%count%")) {
13 throw new Error('Fragment template must contain "%count%".');
14 }
15 if (!fragTemplate.includes("%forloop%")) {
16 throw new Error('Fragment template must contain "%forloop%".');
17 }
18 }
19 generateShader(maxTextures) {
20 if (!this.programCache[maxTextures]) {
21 const sampleValues = new Int32Array(maxTextures);
22 for (let i = 0; i < maxTextures; i++) {
23 sampleValues[i] = i;
24 }
25 this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true);
26 let fragmentSrc = this.fragTemplate;
27 fragmentSrc = fragmentSrc.replace(/%count%/gi, `${maxTextures}`);
28 fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures));
29 this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc);
30 }
31 const uniforms = {
32 tint: new Float32Array([1, 1, 1, 1]),
33 translationMatrix: new Matrix(),
34 default: this.defaultGroupCache[maxTextures]
35 };
36 return new Shader(this.programCache[maxTextures], uniforms);
37 }
38 generateSampleSrc(maxTextures) {
39 let src = "";
40 src += "\n";
41 src += "\n";
42 for (let i = 0; i < maxTextures; i++) {
43 if (i > 0) {
44 src += "\nelse ";
45 }
46 if (i < maxTextures - 1) {
47 src += `if(vTextureId < ${i}.5)`;
48 }
49 src += "\n{";
50 src += `
51 color = texture2D(uSamplers[${i}], vTextureCoord);`;
52 src += "\n}";
53 }
54 src += "\n";
55 src += "\n";
56 return src;
57 }
58}
59
60export { BatchShaderGenerator };
61//# sourceMappingURL=BatchShaderGenerator.mjs.map