4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

three.jsのloaderをpromise.all()で管理したい

Posted at

three.jsの素材を並列処理で読み込む処理を作ってみました。
promise.allで監視し、全てのロードが完了すると次へ進みます。
setting.asset.typeでthreeの各種ローダーを切り替えられるようにしてみた。

参考にさせていただいたドキュメント
script.js
{

  // 素材
  const setting = {
    asset: [
      { id: 'tex_Floor', type: 'texture', url: 'img/texture-floor.png' },
      { id: 'tex_wallpaper', type: 'texture', url: 'img/texture-wallpaper.png' }
    ]
  };

  // ロードデータを格納
  // asset.idで参照
  const asset = [];

  // ================
  // アセット読み込み
  // ================

  // arg1: src var,
  // arg2: output var
  function assetLoader(src, dist) {

    // three.js loader
    function threeLoader(asset) {
      return new Promise(resolve => {
        switch(asset.type) {
          case 'texture':
            new THREE.TextureLoader().load(asset.url, resolve);
            break;
          case 'json':
            new THREE.JSONLoader().load(asset.url, resolve);
            break;
        }
      });
    }

    // promiseAll
    (async () => {
      const promises = [];
      for(let i = 0; i < src.length; i += 1) {
        promises[i] = threeLoader(src[i]);
      }
      const result = await Promise.all(promises);

      // Promise.all完了後distへ格納
      for(let i = 0; i < src.length; i += 1) {
        const key = src[i].id;
        dist[key] = result[i];
      }
      callback();
    })();

  }
  assetLoader(setting.asset, asset);

  // ========
  // callback
  // ========

  function callback() {
    console.log(asset);
  }

}
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?