glsl-source.ts 2.24 KB
Newer Older
gaoqiong's avatar
gaoqiong committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

/**
 * represent a version irrelevant abstraction of for GLSL source code
 */
export interface Glsl {
  readonly version: string;
  readonly attribute: string;
  readonly varyingVertex: string;
  readonly varyingFrag: string;
  readonly texture2D: string;
  readonly output: string;
  readonly outputDeclaration: string;
}

const GLSL_ES_2_0: Glsl = {
  version: '',
  attribute: 'attribute',
  varyingVertex: 'varying',
  varyingFrag: 'varying',
  texture2D: 'texture2D',
  output: 'gl_FragColor',
  outputDeclaration: '',
};
const GLSL_ES_3_0: Glsl = {
  version: '#version 300 es',
  attribute: 'in',
  varyingVertex: 'out',
  varyingFrag: 'in',
  texture2D: 'texture',
  output: 'outputColor',
  outputDeclaration: 'out vec4 outputColor;',
};

export function getGlsl(version: 1|2) {
  return version === 1 ? GLSL_ES_2_0 : GLSL_ES_3_0;
}

export function getVertexShaderSource(version: 1|2): string {
  const glsl = getGlsl(version);
  return `${glsl.version}
      precision highp float;
      ${glsl.attribute} vec3 position;
      ${glsl.attribute} vec2 textureCoord;

      ${glsl.varyingVertex} vec2 TexCoords;

      void main()
      {
          gl_Position = vec4(position, 1.0);
          TexCoords = textureCoord;
      }`;
}

export function getFragShaderPreamble(version: 1|2): string {
  const glsl = getGlsl(version);
  return `${glsl.version}
    precision highp float;
    precision highp int;
    precision highp sampler2D;
    ${glsl.varyingFrag} vec2 TexCoords;
    ${glsl.outputDeclaration}
    const vec2 halfCR = vec2(0.5, 0.5);

    // Custom vector types to handle higher dimenalities.
    struct ivec5
    {
      int x;
      int y;
      int z;
      int w;
      int u;
    };

    struct ivec6
    {
      int x;
      int y;
      int z;
      int w;
      int u;
      int v;
    };

    int imod(int x, int y) {
      return x - y * (x / y);
    }

    `;
}

export function getDefaultFragShaderMain(version: 1|2, outputShapeLength: number): string {
  const glsl = getGlsl(version);
  return `
  void main() {
    int indices[${outputShapeLength}];
    toVec(TexCoords, indices);
    vec4 result = vec4(process(indices));
    ${glsl.output} = result;
  }
  `;
}