KITASENJU DESIGN BLOG

memo, html, javascript, unity

typescript + glslify を使う

npm install

npm install glslify
npm install glsl-random

@types/glslifyがなかったのでつくる

chatGPTに教えてもらった。

glslify.d.tsというファイルを glslを入れてるフォルダに入れた

// glslify.d.ts
declare module 'glslify' {
  interface GlslifyOptions {
    basedir?: string;
    transform?: Array<string | [string, object]>;
    inline?: boolean;
  }

  function glslify(source: string, options?: GlslifyOptions): string;

  export = glslify;
}

typescript上で文字列をglslifyでコンパイル

import glslify from 'glslify';

const vertexShaderSource = `
  attribute vec4 a_Position;
  void main() {
    gl_Position = a_Position;
  }
`;

const compiledVertexShaderSource = glslify(vertexShaderSource);

shader

varying vec2 vUv;

void main() {
    vUv = uv;
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
  #pragma glslify: random = require(glsl-random)

  uniform sampler2D tex;
  varying vec2 vUv;

  void main() {
    
    gl_FragColor = vec4(
      random(vUv),
      0.0,
      1.0,
      1.0
    );

  }

webpack.config.js

glslify-loaderというのが必要?

// pathモジュールの読み込み
const path = require("path");
 
module.exports = {
  // モードを開発モードにする
  //mode: "production",
  mode: "development",
  // 入力ファイル設定
  entry: [path.resolve(__dirname, "./src/index.ts")],
  // 出力ファイル設定
  output: {
    // 出力されるファイル名
    filename: "bundle.js",
    // 出力先ディレクトリ
    path: path.resolve(__dirname, "dist/js")
  },
 
  // モジュール設定
  module: {
    rules: [
      {
        // ts-loaderの設定
        test: /\.(js|ts|tsx)?$/,
        use: "ts-loader",
        exclude: /node_modules/
      },
      {
        test: /.(vert|frag)$/,
        use: ['raw-loader', 'glslify-loader'],
        include: [path.resolve(__dirname, 'src')],
        exclude: /node_modules/
      }      
    ]
  },
  // モジュール解決
  resolve: {
    extensions: [".ts", ".js", ".json"]
  },
 
  // 開発モード設定
  devtool: "source-map",

  devServer: {
    contentBase: "./dist",
    open: true
  }
};

参考

glslifyでGLSLをモジュール化しよう - Qiita

"FOOTER"