All files / src/datguif datguif.ts

0% Statements 0/69
0% Branches 0/37
0% Functions 0/20
0% Lines 0/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import * as dat from 'dat.gui';
import * as is from '../is/is';
import * as color from '../mathf/color';
 
export interface DatGuifFolder {
  name: string;
  // Date Gui folder instance.
  gui: dat.GUI;
}
 
export interface guiDisplayConfig {
  keyName: string;
  /**
   * Optional min value to cap number range.
   */
  min?: number;
  /**
   * Optional max value to cap number range.
   */
  max?: number;
  /**
   * Optional step value.
   */
  step?: number;
 
  /**
   * Optional step value.
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  options?: any;
 
  /**
   * Optional call back when this config update.
   */
  callback: Function;
}
 
/**
 * Wrapper around https://github.com/dataarts/dat.gui/blob/master/API.md
 * to make an object output easier.
 *
 * ```ts
 *
 * const gui = new Datguif();
 *
 * // Register an update callback.
 * gui.onUpdate(()=> {
 *   console.log('gui controls updated');
 * })
 *
 *
 * gui.addFolder('Lights').open();
 * gui.addFolder('Other Config');
 *
 *
 * // Add a subfolder to lights
 * gui.addFolder('Directional Lights', 'Lights');
 * gui.addFolder('Atmosphere Lights', 'Lights');
 *
 *
 * const otherConfig = {
 *   'scale': 0.5,
 *   'optimize': false
 * }
 *
 * const directionalLight = {
 *   'intensity': 0.5,
 *   'show': false,
 *   'castShadow': true,
 * }
 *
 *
 * // Add the directional light to the Directional Lights folder.
 * // Only show intensity and castShadow properties.
 * gui.addObjectToFolder('Directional Lights',
 *   directionalLights,
 *  [
 *   { keyName: 'castShadow'},
 *   { keyName: 'intensity', min: 0, max: 100, callback: ()=> {
 *        console.log('intensity just changed');
 *   }},
 *   { keyName: 'ease', ['linear', 'easeInOutQuad']}
 * ]);
 *
 *
 * // Add the scale option to the Other config folder.
 * gui.addObjectPropertyToFolder(
 *   'Other Config',
 *   otherConfig,
 *  {
 *    keyname: 'scale'
 *  }
 * )
 *
 *
 * // Add functions.
 * guid.addToFolder(
 *  ()=> {
 *    // refresh code.
 *    console.log('hohoho');
 *  },
 *  'Refresh'
 * )
 *
 *
 * ```
 */
export class Datguif {
  private gui: dat.GUI;
  private folders: Array<DatGuifFolder>;
  private updateCallbacks: Array<Function>;
 
  constructor(
    //@see https://github.com/dataarts/dat.gui/blob/master/API.md#new_GUI_new
    guiParams: dat.GUIParams
  ) {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const options: any = guiParams;
    if (!options) {
      options.load = JSON;
    }
 
    this.gui = new dat.GUI(options);
    this.folders = [];
    this.updateCallbacks = [];
  }
 
  getGui(): dat.GUI {
    return this.gui;
  }
 
  /**
   * Adds an update callback.
   */
  onUpdate(callback: Function) {
    this.updateCallbacks.push(callback);
  }
 
  runUpdate() {
    this.updateCallbacks.forEach((callback) => {
      callback();
    });
  }
 
  // Adds a to level button
  addButton(label: string, callback: Function) {
    const id = label.replace(' ', '_');
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const obj: any = {};
    obj[id] = callback;
    this.gui.add(obj, label.replace(' ', '_'));
  }
 
  /**
   *
   * Add a folder to the datguif system.
   *
   * @param folderName
   * @param parentFolder
   */
  addFolder(folderName: string, parentFolderName?: string): dat.GUI {
    let folder;
    if (this.folderExists(folderName)) {
      throw new Error('Folder names must be unique');
    }
 
    if (parentFolderName) {
      const parentFolder: dat.GUI = this.getFolder(parentFolderName).gui;
      folder = parentFolder.addFolder(folderName);
    } else {
      folder = this.gui.addFolder(folderName);
    }
    this.folders.push({
      name: folderName,
      gui: folder,
    });
    return folder;
  }
 
  /**
   * Checks if a folder of a given name already exists.
   */
  folderExists(folderName: string): boolean {
    const folder = this.folders.filter((f) => {
      return f.name === folderName;
    })[0];
 
    return !!folder;
  }
 
  getFolder(folderName: string): DatGuifFolder {
    const folder = this.folders.filter((f) => {
      return f.name === folderName;
    })[0];
 
    if (!folder) {
      throw new Error('No folder named:' + folderName + ' was found');
    }
 
    return folder;
  }
 
  addToFolder(folderName: string, obj: Record<string, any>, keyName: string) {
    const folder = this.getFolder(folderName);
    folder.gui.add(obj, keyName);
  }
 
  addObjectPropertyToFolder(
    folderName: string,
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    obj: any,
    config: guiDisplayConfig
  ) {
    const folder = this.getFolder(folderName);
    const value = obj[config.keyName];
 
    if (!is.defined(value)) {
      return;
    }
 
    // If this looks "color" like.  Convert it to color and then handle
    // the update when it comes back. (Support for Three.Color)
    if (value.r && value.g && value.b) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const colorObj: any = {};
      colorObj[config.keyName] = color.normalizedRgbToRgb(
        color.colorRgbToRgb(value)
      );
 
      folder.gui.addColor(colorObj, config.keyName).onChange(() => {
        // // Convert it back.
        const converted = {
          r: color.rgbToNormalizedRgb(colorObj[config.keyName])[0],
          g: color.rgbToNormalizedRgb(colorObj[config.keyName])[1],
          b: color.rgbToNormalizedRgb(colorObj[config.keyName])[2],
        };
        obj[config.keyName] = converted;
 
        config.callback && config.callback();
        this.runUpdate();
      });
 
      return;
    }
 
    // Support for #FFFFFF type colors.
    if (is.cssHex(value)) {
      folder.gui.addColor(obj, config.keyName).onChange(() => {
        config.callback && config.callback();
        this.runUpdate();
      });
      return;
    }
 
    if (is.defined(config.options)) {
      folder.gui.add(obj, config.keyName, config.options).onChange(() => {
        config.callback && config.callback();
        this.runUpdate();
      });
      return;
    }
 
    if (is.defined(config.min) && is.defined(config.max)) {
      folder.gui
        .add(obj, config.keyName, +config.min!, +config.max!)
        .step(config.step || 0.1)
        .onChange(() => {
          config.callback && config.callback();
          this.runUpdate();
        });
      return;
    }
 
    folder.gui.add(obj, config.keyName).onChange(() => {
      config.callback && config.callback();
      this.runUpdate();
    });
  }
 
  addObjectToFolder(
    folderName: string,
    obj: Object,
    mapping: Array<guiDisplayConfig>
  ) {
    this.gui.remember(obj);
    for (const key in obj) {
      // Check if this key should be displayed.
      const config = mapping.filter((c) => {
        return c.keyName === key;
      })[0];
 
      if (config) {
        this.addObjectPropertyToFolder(folderName, obj, config);
      }
    }
  }
}