demodernizeShader.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * Transpiles a [GLSL 3.00]{@link https://registry.khronos.org/OpenGL/specs/es/3.0/GLSL_ES_Specification_3.00.pdf}
  3. * shader to a [GLSL 1.00]{@link https://registry.khronos.org/OpenGL/specs/es/2.0/GLSL_ES_Specification_1.00.pdf} shader.
  4. *
  5. * This function does not aim to provide a comprehensive transpilation from GLSL 3.00 to GLSL 1.00; only the functionality
  6. * used within the CesiumJS shaders is supported.
  7. *
  8. * @private
  9. *
  10. * @param {string} input The GLSL 3.00 shader.
  11. * @param {boolean} isFragmentShader True if the shader is a fragment shader.
  12. *
  13. * @return {string}
  14. */
  15. function demodernizeShader(input, isFragmentShader) {
  16. let output = input;
  17. // Remove version string got GLSL 3.00.
  18. output = output.replaceAll(`version 300 es`, ``);
  19. // Replace all texture calls with texture2D
  20. output = output.replaceAll(
  21. /(texture\()/g,
  22. `texture2D(` // Trailing ')' is included in the match group.
  23. );
  24. if (isFragmentShader) {
  25. // Replace the in with varying.
  26. output = output.replaceAll(/(in)\s+(vec\d|mat\d|float)/g, `varying $2`);
  27. if (/out_FragData_(\d+)/.test(output)) {
  28. output = `#extension GL_EXT_draw_buffers : enable\n${output}`;
  29. // Remove all layout declarations for out_FragData.
  30. output = output.replaceAll(
  31. /layout\s+\(location\s*=\s*\d+\)\s*out\s+vec4\s+out_FragData_\d+;/g,
  32. ``
  33. );
  34. // Replace out_FragData with gl_FragData.
  35. output = output.replaceAll(/out_FragData_(\d+)/g, `gl_FragData[$1]`);
  36. }
  37. // Remove all layout declarations for out_FragColor.
  38. output = output.replaceAll(
  39. /layout\s+\(location\s*=\s*0\)\s*out\s+vec4\s+out_FragColor;/g,
  40. ``
  41. );
  42. // Replace out_FragColor with gl_FragColor.
  43. output = output.replaceAll(/out_FragColor/g, `gl_FragColor`);
  44. output = output.replaceAll(/out_FragColor\[(\d+)\]/g, `gl_FragColor[$1]`);
  45. if (/gl_FragDepth/.test(output)) {
  46. output = `#extension GL_EXT_frag_depth : enable\n${output}`;
  47. // Replace gl_FragDepth with gl_FragDepthEXT.
  48. output = output.replaceAll(/gl_FragDepth/g, `gl_FragDepthEXT`);
  49. }
  50. } else {
  51. // Replace the in with attribute.
  52. output = output.replaceAll(/(in)\s+(vec\d|mat\d|float)/g, `attribute $2`);
  53. // Replace the out with varying.
  54. output = output.replaceAll(
  55. /(out)\s+(vec\d|mat\d|float)\s+([\w]+);/g,
  56. `varying $2 $3;`
  57. );
  58. }
  59. // Add version string for GLSL 1.00.
  60. output = `#version 100\n${output}`;
  61. return output;
  62. }
  63. export default demodernizeShader;