<commit_before>'use strict';

module.exports = function(grunt) {

  require('load-grunt-tasks')(grunt);

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    watch: {
      gruntfile: {
        files: ['gruntfile.js']
      },
      sass: {
        files: ['resources/src/scss/**/*.scss'],
        tasks: ['sass:dev', 'autoprefixer:dev']
      }
    },

    //Compile SCSS
    sass: {
      dev: {
        options: {
          sourceMap: true,
          outputStyle: 'expanded'
        },
        files: {
          'resources/public/basic.css': 'resources/src/scss/basic.scss',
          'resources/public/ie8.css': 'resources/src/scss/ie8.scss',
          'resources/public/modern.css': 'resources/src/scss/modern.scss'
        }
      },
      dist: {
        options: {
          sourceMap: false,
          outputStyle: 'compressed'
        },
        files: {
          'resources/public/basic.css': 'resources/src/scss/basic.scss',
          'resources/public/ie8.css': 'resources/src/scss/ie8.scss',
          'resources/public/modern.css': 'resources/src/scss/modern.scss'
        }
      }
    },
    //Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 2 version', 'ie 8', 'ie 9']
      },
      dev: {
        options: {
          map: true,
        },
        no_dest: {
          src: 'resources/public/modern.css'
        }
      },
      dist: {
        options: {
          map: false,
        },
        no_dest: {
          src: 'resources/public/modern.css'
        }
      }
    },

    //JAVASCRIPT
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'resources/src/custom/{,*/}*.js',
        '!resources/src/vendor/*'
      ]
    },
    //Stick everything together, you'll need to specify JS files in the correct order here.
    concat: {
      dist: {
        src: [
          'resources/src/js/vendor/jquery-1.11.2.js',
          'resources/src/js/vendor/webfont.js',
          'resources/src/js/custom/**/*.js'
        ],
        dest: 'resources/public/scripts.js',
      },
    },
    //Uglify
    uglify: {
      modernizr: {
        src: 'resources/src/js/vendor/modernizr.js',
        dest: 'resources/public/modernizr.min.js'
      },
      build: {
        src: 'resources/public/scripts.js',
        dest: 'resources/public/scripts.min.js'
      }
    }
  });

  grunt.registerTask('dev',[
    'sass:dev',
    'autoprefixer:dev',
    'jshint',
    'concat',
    'uglify',
    'watch'
  ]);

  grunt.registerTask('build',[
    'sass:dist',
    'autoprefixer:dist',
    'jshint',
    'concat',
    'uglify'
  ]);

  grunt.registerTask('default', [
    'build'
  ]);
};<commit_msg>GR - minfication is currently overwriting custom styles - turning off<commit_after>'use strict';

module.exports = function(grunt) {

  require('load-grunt-tasks')(grunt);

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    watch: {
      gruntfile: {
        files: ['gruntfile.js']
      },
      sass: {
        files: ['resources/src/scss/**/*.scss'],
        tasks: ['sass:dev', 'autoprefixer:dev']
      }
    },

    //Compile SCSS
    sass: {
      dev: {
        options: {
          sourceMap: true,
          outputStyle: 'expanded'
        },
        files: {
          'resources/public/basic.css': 'resources/src/scss/basic.scss',
          'resources/public/ie8.css': 'resources/src/scss/ie8.scss',
          'resources/public/modern.css': 'resources/src/scss/modern.scss'
        }
      },
      dist: {
        options: {
          sourceMap: false,
          outputStyle: 'expanded'
        },
        files: {
          'resources/public/basic.css': 'resources/src/scss/basic.scss',
          'resources/public/ie8.css': 'resources/src/scss/ie8.scss',
          'resources/public/modern.css': 'resources/src/scss/modern.scss'
        }
      }
    },
    //Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 2 version', 'ie 8', 'ie 9']
      },
      dev: {
        options: {
          map: true,
        },
        no_dest: {
          src: 'resources/public/modern.css'
        }
      },
      dist: {
        options: {
          map: false,
        },
        no_dest: {
          src: 'resources/public/modern.css'
        }
      }
    },

    //JAVASCRIPT
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'resources/src/custom/{,*/}*.js',
        '!resources/src/vendor/*'
      ]
    },
    //Stick everything together, you'll need to specify JS files in the correct order here.
    concat: {
      dist: {
        src: [
          'resources/src/js/vendor/jquery-1.11.2.js',
          'resources/src/js/vendor/webfont.js',
          'resources/src/js/custom/**/*.js'
        ],
        dest: 'resources/public/scripts.js',
      },
    },
    //Uglify
    uglify: {
      modernizr: {
        src: 'resources/src/js/vendor/modernizr.js',
        dest: 'resources/public/modernizr.min.js'
      },
      build: {
        src: 'resources/public/scripts.js',
        dest: 'resources/public/scripts.min.js'
      }
    }
  });

  grunt.registerTask('dev',[
    'sass:dev',
    'autoprefixer:dev',
    'jshint',
    'concat',
    'uglify',
    'watch'
  ]);

  grunt.registerTask('build',[
    'sass:dist',
    'autoprefixer:dist',
    'jshint',
    'concat',
    'uglify'
  ]);

  grunt.registerTask('default', [
    'build'
  ]);
};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  'use strict';
  var pkg = grunt.file.readJSON('package.json');

  grunt.initConfig({
    srcDir: "src",
    buildDir: "bin",

    watch: {
      jsx: {
        files: ['<%= srcDir %>/*.jsx'],
        tasks: ['exec:make_compiler']
      },
    },

    exec: {
      make_compiler: {
        command: "make compiler",
      },
    },
  });

  for (var key in pkg.devDependencies) {
    if (/grunt-/.test(key)) {
      grunt.loadNpmTasks(key);
    }
  }

  grunt.registerTask('default', ['exec:make_compiler']);
};
// vim: set expandtab tabstop=2 shiftwidth=2:
<commit_msg>do not watch src/meta.jsx on `grunt watch`<commit_after>module.exports = function(grunt) {
  'use strict';
  var pkg = grunt.file.readJSON('package.json');

  grunt.initConfig({
    srcDir: "src",
    buildDir: "bin",

    watch: {
      jsx: {
        files: ['<%= srcDir %>/*.jsx', '!<%= srcDir %>/meta.jsx'],
        tasks: ['exec:make_compiler']
      },
    },

    exec: {
      make_compiler: {
        command: "make compiler",
      },
    },
  });

  for (var key in pkg.devDependencies) {
    if (/grunt-/.test(key)) {
      grunt.loadNpmTasks(key);
    }
  }

  grunt.registerTask('default', ['exec:make_compiler']);
};
// vim: set expandtab tabstop=2 shiftwidth=2:
<|endoftext|>


<commit_before>/*
[============================== AUTOMATIC RELEASE NOTES ==============================]
|                                                                                |
| When starting grunt release dont update the version of the root package.json        |
| This file is used for automatic updates.                                            |
|                                                                                |
| Edit if after releasing - only update the src/package.json and start your release   |
| process.                                                                            |
|                                                                                |
| Grunt will open the necessary Websites for editing the root package.json and making |
| your releasetag.                                                                    |
|                                                                                |
[=====================================================================================]
*/

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        srcpkg: grunt.file.readJSON('src/package.json'),

        shell: {
            npmInstall: {
                command: 'cd src && npm install'
            },

            devInstall: {
                command: 'mv nwjs-v0.12.0-win-x64 nw && copy cfg\\package.json nw\\package.json && cd nw & npm install'
            },

            devInstallMac64: {
                command: 'mv nwjs-v0.12.0-osx-x64 nw && cp cfg/package.json nw/package.json && cd nw && npm install'
            },

            devInstallTux32: {
                command: 'tar -xzvf cache/nwdev.tar.gz && mv nwjs-v0.12.0-linux-ia32 nw && cp cfg/package.json nw/package.json && cd nw && npm install'
            },

            devInstallTux64: {
                command: 'tar -xzvf cache/nwdev.tar.gz && mv nwjs-v0.12.0-linux-x64 nw && cp cfg/package.json nw/package.json && cd nw && npm install'
            },

            osxUnzip: {
                command: 'unzip ./cache/nwdev.zip'
            },

            gitCommit: {
                command: 'git commit -a -m "Release Version <%= srcpkg.version %>"'
            },

            purgeBuilds: {
                command: 'rm -rf build/*'
            }
        },

        open: {
            newRelease: {
                path: 'https://github.com/FreaKzero/ssgl-doom-launcher/releases/new',
            },

            editPackage: {
                path: 'https://github.com/FreaKzero/ssgl-doom-launcher/edit/master/package.json'
            }
        },

        nwjs: {
            win: {
                options: {
                    platforms: ['win'],
                    buildDir: './build',
                    version: '0.12.0',
                    winIco: './icons/ssgl1.ico'
                },
                src: ['./build/pre/**/**']
            },

            tux: {
                options: {
                    platforms: ['linux'],
                    buildDir: './build',
                    version: '0.12.0'
                },
                src: ['./build/pre/**/**']
            },

            mac: {
                options: {
                    platforms: ['osx64'],
                    buildDir: './build',
                    version: '0.12.0',
                    macIcns: './icons/ssgl.icns'
                },
                src: ['./build/pre/**/**']
            }
        },

        curl: {

            mac64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-osx-x64.zip',
                dest: './cache/nwdev.zip'
            },

            win64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-win-x64.zip',
                dest: './cache/nwdev.zip'
            },

            nwdevTux32: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-linux-ia32.tar.gz',
                dest: './cache/nwdev.tar.gz'
            },

            nwdevTux64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-linux-x64.tar.gz',
                dest: './cache/nwdev.tar.gz'
            }
        },

        unzip: {
            nwdev: {
                src: './cache/nwdev.zip',
                dest: './'
            }
        },

        compress: {
            tux32: {
                options: {
                    archive: './build/RELEASE/linux32.tar.gz',
                    mode: 'tgz'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/linux32/'
                }]
            },

            tux64: {
                options: {
                    archive: './build/RELEASE/linux64.tar.gz',
                    mode: 'tgz'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/linux64/'
                }]
            },
            mac64: {
                options: {
                    archive: './build/RELEASE/macos64.tar.gz',
                    mode: 'tgz'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/linux64/'
                }]
            },

            win32: {
                options: {
                    archive: './build/RELEASE/win32.zip'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/win32/'
                }]
            },

            win64: {
                options: {
                    archive: './build/RELEASE/win64.zip'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/win64/'
                }]
            }
        },

        concat: {
            options: {
                separator: '\n\n',
                stripBanners: true,
            },

            dist: {
                src: ['src/app/_mixins.js',
                      'src/app/main.js',
                      'src/app/templates.js',
                      'src/app/controllers/*.js',
                      'src/app/directives/*.js',
                      'src/app/services/**.js'
                ],
                dest: 'build/pre/app.js',
            }
        },

        uglify: {
            options: {
                mangle: false
            },

            build: {
                files: {
                    'build/pre/app.js': ['build/pre/app.js']
                }
            }
        },

        ngtemplates: {
            app: {
                cwd: 'src/',
                src: 'app/templates/*.html',
                dest: 'src/app/templates.js',
                options: {
                    htmlmin: {
                        collapseWhitespace: true,
                        collapseBooleanAttributes: true
                    },

                    bootstrap: function(module, script) {
                        return "app.run(['$templateCache', function($templateCache) {" + "\n" + script + '}]);';
                    }
                }
            }
        },

        copy: {
            main: {
                src: ['index.html', 'package.json', 'node_modules/**', 'app/assets/**', 'app/font/**', 'app/lib/**'],
                cwd: 'src/',
                dest: 'build/pre',
                expand: true
            }
        },

        yuidoc: {
            compile: {
                name: 'Super Shotgun Launcher',
                version: '<%= pkg.version %>',
                url: '<%= pkg.homepage %>',
                options: {
                    paths: './src/app',
                    outdir: './docs',
                    exclude: 'lib'
                }
            }
        }

    });

    // Plugins

    grunt.loadNpmTasks('grunt-nw-builder');
    grunt.loadNpmTasks('grunt-shell');
    grunt.loadNpmTasks('grunt-curl');
    grunt.loadNpmTasks('grunt-zip');
    grunt.loadNpmTasks('grunt-contrib-yuidoc');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.loadNpmTasks('grunt-open');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-angular-templates');
    grunt.loadNpmTasks('grunt-contrib-copy');

    grunt.registerTask('build-js', ['ngtemplates', 'concat', 'uglify', 'copy']);

    grunt.registerTask('build-win', ['build-js', 'nwjs:win']);
    grunt.registerTask('build-linux', ['build-js', 'nwjs:tux']);
    grunt.registerTask('build-mac', ['build-js', 'nwjs:mac']);

    grunt.registerTask('init', ['shell:npmInstall']);

    grunt.registerTask('build-devenv-win', ['curl:win64', 'unzip', 'shell:devInstall']);
    grunt.registerTask('build-devenv-mac', ['curl:mac64', 'shell:osxUnzip', 'shell:devInstallMac64']);

    grunt.registerTask('build-devenv-linux32', ['curl:nwdevTux32', 'shell:devInstallTux32']);
    grunt.registerTask('build-devenv-linux64', ['curl:nwdevTux64', 'shell:devInstallTux64']);

    grunt.registerTask('release', [
        'shell:purgeBuilds',
        'build-js',
        'nwjs',
        'compress',
        'gitCommit'
    ]);

};
<commit_msg>Own releasescript for mac<commit_after>/*
[============================== AUTOMATIC RELEASE NOTES ==============================]
|                                                                                |
| When starting grunt release dont update the version of the root package.json        |
| This file is used for automatic updates.                                            |
|                                                                                |
| Edit if after releasing - only update the src/package.json and start your release   |
| process.                                                                            |
|                                                                                |
| Grunt will open the necessary Websites for editing the root package.json and making |
| your releasetag.                                                                    |
|                                                                                |
[=====================================================================================]
*/

module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        srcpkg: grunt.file.readJSON('src/package.json'),

        shell: {
            npmInstall: {
                command: 'cd src && npm install'
            },

            devInstall: {
                command: 'mv nwjs-v0.12.0-win-x64 nw && copy cfg\\package.json nw\\package.json && cd nw & npm install'
            },

            devInstallMac64: {
                command: 'mv nwjs-v0.12.0-osx-x64 nw && cp cfg/package.json nw/package.json && cd nw && npm install'
            },

            devInstallTux32: {
                command: 'tar -xzvf cache/nwdev.tar.gz && mv nwjs-v0.12.0-linux-ia32 nw && cp cfg/package.json nw/package.json && cd nw && npm install'
            },

            devInstallTux64: {
                command: 'tar -xzvf cache/nwdev.tar.gz && mv nwjs-v0.12.0-linux-x64 nw && cp cfg/package.json nw/package.json && cd nw && npm install'
            },

            osxUnzip: {
                command: 'unzip ./cache/nwdev.zip'
            },

            gitCommit: {
                command: 'git commit -a -m "Release Version <%= srcpkg.version %>"'
            },

            purgeBuilds: {
                command: 'rm -rf build/*'
            }
        },

        open: {
            newRelease: {
                path: 'https://github.com/FreaKzero/ssgl-doom-launcher/releases/new',
            },

            editPackage: {
                path: 'https://github.com/FreaKzero/ssgl-doom-launcher/edit/master/package.json'
            }
        },

        nwjs: {
            win: {
                options: {
                    platforms: ['win'],
                    buildDir: './build',
                    version: '0.12.0',
                    winIco: './icons/ssgl1.ico'
                },
                src: ['./build/pre/**/**']
            },

            tux: {
                options: {
                    platforms: ['linux'],
                    buildDir: './build',
                    version: '0.12.0'
                },
                src: ['./build/pre/**/**']
            },

            mac: {
                options: {
                    platforms: ['osx64'],
                    buildDir: './build',
                    version: '0.12.0',
                    macIcns: './icons/ssgl.icns'
                },
                src: ['./build/pre/**/**']
            }
        },

        curl: {

            mac64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-osx-x64.zip',
                dest: './cache/nwdev.zip'
            },

            win64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-win-x64.zip',
                dest: './cache/nwdev.zip'
            },

            nwdevTux32: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-linux-ia32.tar.gz',
                dest: './cache/nwdev.tar.gz'
            },

            nwdevTux64: {
                src: 'http://dl.nwjs.io/v0.12.0/nwjs-v0.12.0-linux-x64.tar.gz',
                dest: './cache/nwdev.tar.gz'
            }
        },

        unzip: {
            nwdev: {
                src: './cache/nwdev.zip',
                dest: './'
            }
        },

        compress: {
            tux32: {
                options: {
                    archive: './build/RELEASE/linux32.tar.gz',
                    mode: 'tgz'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/linux32/'
                }]
            },

            tux64: {
                options: {
                    archive: './build/RELEASE/linux64.tar.gz',
                    mode: 'tgz'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/linux64/'
                }]
            },
            mac64: {
                options: {
                    archive: './build/RELEASE/macos64.tar.gz',
                    mode: 'tgz'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/linux64/'
                }]
            },

            win32: {
                options: {
                    archive: './build/RELEASE/win32.zip'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/win32/'
                }]
            },

            win64: {
                options: {
                    archive: './build/RELEASE/win64.zip'
                },
                files: [{
                    src: ['**/*'],
                    expand: true,
                    cwd: './build/SSGL/win64/'
                }]
            }
        },

        concat: {
            options: {
                separator: '\n\n',
                stripBanners: true,
            },

            dist: {
                src: ['src/app/_mixins.js',
                      'src/app/main.js',
                      'src/app/templates.js',
                      'src/app/controllers/*.js',
                      'src/app/directives/*.js',
                      'src/app/services/**.js'
                ],
                dest: 'build/pre/app.js',
            }
        },

        uglify: {
            options: {
                mangle: false
            },

            build: {
                files: {
                    'build/pre/app.js': ['build/pre/app.js']
                }
            }
        },

        ngtemplates: {
            app: {
                cwd: 'src/',
                src: 'app/templates/*.html',
                dest: 'src/app/templates.js',
                options: {
                    htmlmin: {
                        collapseWhitespace: true,
                        collapseBooleanAttributes: true
                    },

                    bootstrap: function(module, script) {
                        return "app.run(['$templateCache', function($templateCache) {" + "\n" + script + '}]);';
                    }
                }
            }
        },

        copy: {
            main: {
                src: ['index.html', 'package.json', 'node_modules/**', 'app/assets/**', 'app/font/**', 'app/lib/**'],
                cwd: 'src/',
                dest: 'build/pre',
                expand: true
            }
        },

        yuidoc: {
            compile: {
                name: 'Super Shotgun Launcher',
                version: '<%= pkg.version %>',
                url: '<%= pkg.homepage %>',
                options: {
                    paths: './src/app',
                    outdir: './docs',
                    exclude: 'lib'
                }
            }
        }
    });

    // Plugins

    grunt.loadNpmTasks('grunt-nw-builder');
    grunt.loadNpmTasks('grunt-shell');
    grunt.loadNpmTasks('grunt-curl');
    grunt.loadNpmTasks('grunt-zip');
    grunt.loadNpmTasks('grunt-contrib-yuidoc');
    grunt.loadNpmTasks('grunt-contrib-compress');
    grunt.loadNpmTasks('grunt-open');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-angular-templates');
    grunt.loadNpmTasks('grunt-contrib-copy');

    grunt.registerTask('build-js', ['ngtemplates', 'concat', 'uglify', 'copy']);

    grunt.registerTask('build-win', ['build-js', 'nwjs:win']);
    grunt.registerTask('build-linux', ['build-js', 'nwjs:tux']);
    grunt.registerTask('build-mac', ['build-js', 'nwjs:mac']);

    grunt.registerTask('init', ['shell:npmInstall']);

    grunt.registerTask('build-devenv-win', ['curl:win64', 'unzip', 'shell:devInstall']);
    grunt.registerTask('build-devenv-mac', ['curl:mac64', 'shell:osxUnzip', 'shell:devInstallMac64']);

    grunt.registerTask('build-devenv-linux32', ['curl:nwdevTux32', 'shell:devInstallTux32']);
    grunt.registerTask('build-devenv-linux64', ['curl:nwdevTux64', 'shell:devInstallTux64']);

    grunt.registerTask('releaseMac', [
        'shell:purgeBuilds',
        'build-js',
        'nwjs:mac',
        'compress:mac'
    ]);

    grunt.registerTask('release', [
        'shell:purgeBuilds',
        'build-js',
        'nwjs:win',
        'nwjs:tux',
        'compress:tux32',
        'compress:tux64',
        'compress:win32',
        'compress:win64',
        'gitCommit'
    ]);

};
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');

const ContextReplacementPlugin = webpack.ContextReplacementPlugin;
const LoaderOptionsPlugin = webpack.LoaderOptionsPlugin;

const webpackUtils = require('./webpack.utils');

const getCommonConfig = (type) => {
    const tsconfigType = type !== 'dev' ? `.${ type }` : '';

    return {
        module: {
            rules: [
                {
                    exclude: /node_modules/,
                    test: /\.ts$/,
                    use: [
                        'awesome-typescript-loader?configFileName=' + webpackUtils.rootPath(`tsconfig${ tsconfigType }.json`),
                        'angular2-template-loader?keepUrl=true'
                    ]
                },
                { test: /\.html$/, use: 'raw-loader' },
                {
                    use: ['url-loader?limit=10000'],
                    test: /\.(woff2?|ttf|eot|svg|jpg|jpeg|json|gif|png)(\?v=\d+\.\d+\.\d+)?$/
                }
            ]
        },
        performance: { hints: false },
        plugins: [
            new ContextReplacementPlugin(
                /angular(\\|\/)core(\\|\/)@angular/,
                __dirname
            ),
            new LoaderOptionsPlugin({
                debug: true,
                options: {
                    emitErrors: true
                }
            })
        ],
        resolve: {
            extensions: [ '.js', '.ts' ],
            modules: [ webpackUtils.rootPath('node_modules') ]
        }
    };
};

module.exports = (type, typeConfig) => {
    const configs = [getCommonConfig(type), typeConfig];
    const customConfigPath = webpackUtils.rootPath('configs', `webpack.${ type }.js`);

    if (fs.existsSync(customConfigPath)) {
        let customConfig = require(customConfigPath);

        if (Object.prototype.toString.call(customConfig) === '[object Function]') {
            customConfig = customConfig();
        }

        configs.push(customConfig);
    }

    return webpackMerge.apply(null, configs);
};
<commit_msg>Error in WebPack build #49 (#50)<commit_after>'use strict';

const fs = require('fs');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');

const ExtractTextPlugin = require("extract-text-webpack-plugin");
const ContextReplacementPlugin = webpack.ContextReplacementPlugin;
const LoaderOptionsPlugin = webpack.LoaderOptionsPlugin;

const webpackUtils = require('./webpack.utils');

const getCommonConfig = (type) => {
    const tsconfigType = type !== 'dev' ? `.${ type }` : '';

    return {
        module: {
            rules: [
                {
                    exclude: /node_modules/,
                    test: /\.ts$/,
                    use: [
                        'awesome-typescript-loader?configFileName=' + webpackUtils.rootPath(`tsconfig${ tsconfigType }.json`),
                        'angular2-template-loader?keepUrl=true'
                    ]
                },
                { test: /\.html$/, use: 'raw-loader' },
                {
                    use: ['url-loader?limit=10000'],
                    test: /\.(woff2?|ttf|eot|svg|jpg|jpeg|json|gif|png)(\?v=\d+\.\d+\.\d+)?$/
                }
            ]
        },
        performance: { hints: false },
        plugins: [
            new ContextReplacementPlugin(
                /angular(\\|\/)core(\\|\/)@angular/,
                __dirname
            ),
            new LoaderOptionsPlugin({
                debug: true,
                options: {
                    emitErrors: true
                }
            }),
            new ExtractTextPlugin("*.css")
        ],
        resolve: {
            extensions: [ '.js', '.ts' ],
            modules: [ webpackUtils.rootPath('node_modules') ]
        }
    };
};

module.exports = (type, typeConfig) => {
    const configs = [getCommonConfig(type), typeConfig];
    const customConfigPath = webpackUtils.rootPath('configs', `webpack.${ type }.js`);

    if (fs.existsSync(customConfigPath)) {
        let customConfig = require(customConfigPath);

        if (Object.prototype.toString.call(customConfig) === '[object Function]') {
            customConfig = customConfig();
        }

        configs.push(customConfig);
    }

    return webpackMerge.apply(null, configs);
};
<|endoftext|>


<commit_before>/*
 Course Generator V2.0
 ----------------------------
 Authors:
   William "Wistaro" Romiguières    (this script)
   "Anonyme0"                       (part of this script)
   Adrien "Adriweb" Bertrand        (this script + tivars_lib_cpp)
 ----------------------------
 Help: tiplanet.org
 */

window.whichViewer = 'smallViewer';

let courseHeader = "";

let withMenu = false;
let chosenCalc = 'CE';

let lastFilePath = null;

let nbParties = 1;
let parties = [];

function isInt(value)
{
    return !isNaN(value) && (x => (x|0) === x)(parseFloat(value))
}

function startWizard()
{
    parties = [];
    $("#myText0").remove();

    do {
        nbParties = prompt('Combien de parties ? (1-6)');
    } while (!isInt(nbParties) || nbParties < 1 || nbParties > 6);
    nbParties = parseInt(nbParties);

    withMenu = true;

    const menuName = prompt('Titre de votre menu (sommaire des parties) ?', 'Sommaire');
    courseHeader += `\nLbl 0\nMenu("${menuName.toUpperCase()}"`;

    for (var i = 0; i < nbParties; i++)
    {
        parties[i] = prompt(`Titre de la partie n°${(i+1)}`);
        courseHeader += `,"${parties[i].toUpperCase()}",${(i+1)}`;
        $('.step2').fadeIn(1000).append(`<textarea id="myText${i}" title="Votre texte ici" name="myText${i}" placeholder="Écrivez votre texte dans cette zone">Votre cours, partie ${(i+1)}! </textarea><br />`);
    }
    registerPreviewHandler();

    courseHeader += ",\"Quitter\",Q\n";
}

function generateCourseForSmallViewer()
{
    let courseInit = "FnOff :0→Xmin:0→Ymin:1→∆X:1→∆Y:AxesOff:ClrDraw\n";
    if (chosenCalc === "83PCE") { courseInit += "BackgroundOff\n"; }

    const MIN_PAS_X      = 0;
    const MIN_PAS_Y      = (chosenCalc === "83PCE") ? 12 :  7;
    const MAX_CHAR_LINE  = (chosenCalc === "83PCE") ? 36 : 23;
    const LAST_LINE      = (chosenCalc === "83PCE") ? 13 :  9;

    let newCourse =  ((chosenCalc === "83PCE") ? "12→W\n" : "7→W\n") + courseInit + courseHeader;

    for (var part = 0; part < nbParties; part++)
    {
        let bufferStr = "";

        newCourse += `Lbl ${(part+1)}\n`;

        let inputStr = $(`#myText${part}`).val();

        if (chosenCalc === "83") { inputStr = inputStr.toUpperCase(); }

        inputStr = inputStr.replace(/"/g, "''")     // replacing " by ''
                           .replace(/→/g, "->")     // replacing arrow

        const splitInput = inputStr.split('\n');

        for (var i = 0; i < splitInput.length; i++)
        {
            const val = splitInput[i];
            bufferStr += val;

            if (val.length < MAX_CHAR_LINE)
            {
                for (var idxSpace = 1; idxSpace <= MAX_CHAR_LINE - val.length; idxSpace++)
                {
                    bufferStr += " ";
                }
            } else {
                let nbFullLines = (val.length / MAX_CHAR_LINE)|0;
                let nbSpaces = MAX_CHAR_LINE - val.substring(nbFullLines*MAX_CHAR_LINE,val.length).length;

                for (var idxSpace = 1; idxSpace <= nbSpaces; idxSpace++)
                {
                    bufferStr += " ";
                }
            }
        }

        inputStr = bufferStr;

        let Cptlines = 0;
        let CptlinesSave = 0;
        let CptPages = 1;
        let YText = 0;
        let XText = 0;

        newCourse += "\nDelVar V\n";

        let currentSubStr = "";

        for (var i = 0; i < inputStr.length; i++)
        {
            if ((i % MAX_CHAR_LINE) === 0)
            {
                currentSubStr = inputStr.substring(i, i + MAX_CHAR_LINE);

                newCourse += `"${currentSubStr}\nprgmZTEXT\n`;

                Cptlines++;
                CptlinesSave++;
                YText += MIN_PAS_Y;
            }
            if (Cptlines === LAST_LINE)
            {
                newCourse += "Pause :ClrDraw:DelVar V\n";
                YText = 0;
                Cptlines = 0;
                CptPages++;
            }
        }

        newCourse += "Pause :ClrDraw\n";
        newCourse += withMenu ? "Goto 0\n" : "Disp \"";
    }

    newCourse += "\nLbl Q\nClrDraw:Disp \"";

    const titlePrgm = $("#prgmName").val();
    //newCourse+="\n\"      Titre:"+titlePrgm+"→Y₁\n";

    create8xpFile(titlePrgm, newCourse);
}

function generateCourseForLargeViewer()
{
    // Encodage...
    text = $('#myText0').val().replace(/\"/g, "'"); //remplace les " par des '
    let cor = text.split("\n");
    let bc = cor;
    // 83PCE
    if (chosenCalc === "83PCE")
    {
        for(var i = 0; i < bc.length-1; i++)
        { // -1 pour pas completer d'espaces la dernière ligne
            if (bc[i].length > 26) {
                var n = 26-(bc[i].length-(Math.floor(bc[i].length/26)*26)); // calcul d'espaces nécessaires pour finir la ligne
            } else {
                var n = 26-(bc[i].length % 26);
            }
            if (n != 26) { // Pour annuler le retour à la ligne par espace lorsqu'une ligne fait 26 caractères
                for(var a = 0; a < n; a++) {
                    cor[i] += " ";
                }
            }
        }
        // 82a
    } else {
        for(var i = 0; i < bc.length-1; i++)
        {
            if (bc[i].length > 16) {
                var n = 16-(bc[i].length-(Math.floor(bc[i].length/16)*16));
            } else {
                var n = 16-(bc[i].length % 16);
            }
            if (n != 16) {
                for(var a = 0; a < n; a++) {
                    cor[i] += " ";
                }
            }
        }
    }
    cor = cor.join("");

    // Encodage...
    cor = '"' + cor + '"\nprgmSTRVIEW';

    const titlePrgm = $("#prgmName").val();
    create8xpFile(titlePrgm, cor);
}

function create8xpFile(title, content)
{
    try
    {
        const lib = Module;

        if (lastFilePath !== null)
        {
            FS.unlink(lastFilePath);
            lastFilePath = null;
        }

        const txt = unescape(encodeURIComponent(content)); // encoding issues...

        const prgm = lib.TIVarFile.createNew(lib.TIVarType.createFromName("Program"), title, lib.TIModel.createFromName(chosenCalc));

        prgm.setContentFromString(txt);
        const filePath = prgm.saveVarToFile("", title);
        lastFilePath = filePath;

        const file = FS.readFile(filePath, {encoding: 'binary'});
        if (file)
        {
            const blob = new Blob([file], {type: 'application/octet-stream'});
            window['saveAs'](blob, filePath.split('/').pop());
        } else {
            alert('Impossible de récupérer le fichier généré:(');
        }

    } catch (e)
    {
        alert('Hmmm. Une erreur est survenue. ' + e.toString());
    }
}
<commit_msg>Add black font, fix number of symbols by lines on b&w models<commit_after>/*
 Course Generator V2.0
 ----------------------------
 Authors:
   William "Wistaro" Romiguières    (this script)
   "Anonyme0"                       (part of this script)
   Adrien "Adriweb" Bertrand        (this script + tivars_lib_cpp)
 ----------------------------
 Help: tiplanet.org
 */

window.whichViewer = 'smallViewer';

let courseHeader = "";

let withMenu = false;
let chosenCalc = 'CE';

let lastFilePath = null;

let nbParties = 1;
let parties = [];

function isInt(value)
{
    return !isNaN(value) && (x => (x|0) === x)(parseFloat(value))
}

function startWizard()
{
    parties = [];
    $("#myText0").remove();

    do {
        nbParties = prompt('Combien de parties ? (1-6)');
    } while (!isInt(nbParties) || nbParties < 1 || nbParties > 6);
    nbParties = parseInt(nbParties);

    withMenu = true;

    const menuName = prompt('Titre de votre menu (sommaire des parties) ?', 'Sommaire');
    courseHeader += `\nLbl 0\nMenu("${menuName.toUpperCase()}"`;

    for (var i = 0; i < nbParties; i++)
    {
        parties[i] = prompt(`Titre de la partie n°${(i+1)}`);
        courseHeader += `,"${parties[i].toUpperCase()}",${(i+1)}`;
        $('.step2').fadeIn(1000).append(`<textarea id="myText${i}" title="Votre texte ici" name="myText${i}" placeholder="Écrivez votre texte dans cette zone">Votre cours, partie ${(i+1)}! </textarea><br />`);
    }
    registerPreviewHandler();

    courseHeader += ",\"Quitter\",Q\n";
}

function generateCourseForSmallViewer()
{
    let courseInit = "FnOff :0→Xmin:0→Ymin:1→∆X:1→∆Y:AxesOff:ClrDraw:\n";
    if (chosenCalc === "83PCE") { courseInit += "BackgroundOff:TextColor(BLACK\n"; }

    const MIN_PAS_X      = 0;
    const MIN_PAS_Y      = (chosenCalc === "83PCE") ? 12 :  7;
    const MAX_CHAR_LINE  = (chosenCalc === "83PCE") ? 36 : 28;
    const LAST_LINE      = (chosenCalc === "83PCE") ? 13 :  9;

    let newCourse =  ((chosenCalc === "83PCE") ? "12→W\n" : "7→W\n") + courseInit + courseHeader;

    for (var part = 0; part < nbParties; part++)
    {
        let bufferStr = "";

        newCourse += `Lbl ${(part+1)}\n`;

        let inputStr = $(`#myText${part}`).val();

        if (chosenCalc === "83") { inputStr = inputStr.toUpperCase(); }

        inputStr = inputStr.replace(/"/g, "''")     // replacing " by ''
                           .replace(/→/g, "->")     // replacing arrow

        const splitInput = inputStr.split('\n');

        for (var i = 0; i < splitInput.length; i++)
        {
            const val = splitInput[i];
            bufferStr += val;

            if (val.length < MAX_CHAR_LINE)
            {
                for (var idxSpace = 1; idxSpace <= MAX_CHAR_LINE - val.length; idxSpace++)
                {
                    bufferStr += " ";
                }
            } else {
                let nbFullLines = (val.length / MAX_CHAR_LINE)|0;
                let nbSpaces = MAX_CHAR_LINE - val.substring(nbFullLines*MAX_CHAR_LINE,val.length).length;

                for (var idxSpace = 1; idxSpace <= nbSpaces; idxSpace++)
                {
                    bufferStr += " ";
                }
            }
        }

        inputStr = bufferStr;

        let Cptlines = 0;
        let CptlinesSave = 0;
        let CptPages = 1;
        let YText = 0;
        let XText = 0;

        newCourse += "\nDelVar V\n";

        let currentSubStr = "";

        for (var i = 0; i < inputStr.length; i++)
        {
            if ((i % MAX_CHAR_LINE) === 0)
            {
                currentSubStr = inputStr.substring(i, i + MAX_CHAR_LINE);

                newCourse += `"${currentSubStr}\nprgmZTEXT\n`;

                Cptlines++;
                CptlinesSave++;
                YText += MIN_PAS_Y;
            }
            if (Cptlines === LAST_LINE)
            {
                newCourse += "Pause :ClrDraw:DelVar V\n";
                YText = 0;
                Cptlines = 0;
                CptPages++;
            }
        }

        newCourse += "Pause :ClrDraw\n";
        newCourse += withMenu ? "Goto 0\n" : "Disp \"";
    }

    newCourse += "\nLbl Q\nClrDraw:Disp \"";

    const titlePrgm = $("#prgmName").val();
    //newCourse+="\n\"      Titre:"+titlePrgm+"→Y₁\n";

    create8xpFile(titlePrgm, newCourse);
}

function generateCourseForLargeViewer()
{
    // Encodage...
    text = $('#myText0').val().replace(/\"/g, "'"); //remplace les " par des '
    let cor = text.split("\n");
    let bc = cor;
    // 83PCE
    if (chosenCalc === "83PCE")
    {
        for(var i = 0; i < bc.length-1; i++)
        { // -1 pour pas completer d'espaces la dernière ligne
            if (bc[i].length > 26) {
                var n = 26-(bc[i].length-(Math.floor(bc[i].length/26)*26)); // calcul d'espaces nécessaires pour finir la ligne
            } else {
                var n = 26-(bc[i].length % 26);
            }
            if (n != 26) { // Pour annuler le retour à la ligne par espace lorsqu'une ligne fait 26 caractères
                for(var a = 0; a < n; a++) {
                    cor[i] += " ";
                }
            }
        }
        // 82a
    } else {
        for(var i = 0; i < bc.length-1; i++)
        {
            if (bc[i].length > 16) {
                var n = 16-(bc[i].length-(Math.floor(bc[i].length/16)*16));
            } else {
                var n = 16-(bc[i].length % 16);
            }
            if (n != 16) {
                for(var a = 0; a < n; a++) {
                    cor[i] += " ";
                }
            }
        }
    }
    cor = cor.join("");

    // Encodage...
    cor = '"' + cor + '"\nprgmSTRVIEW';

    const titlePrgm = $("#prgmName").val();
    create8xpFile(titlePrgm, cor);
}

function create8xpFile(title, content)
{
    try
    {
        const lib = Module;

        if (lastFilePath !== null)
        {
            FS.unlink(lastFilePath);
            lastFilePath = null;
        }

        const txt = unescape(encodeURIComponent(content)); // encoding issues...

        const prgm = lib.TIVarFile.createNew(lib.TIVarType.createFromName("Program"), title, lib.TIModel.createFromName(chosenCalc));

        prgm.setContentFromString(txt);
        const filePath = prgm.saveVarToFile("", title);
        lastFilePath = filePath;

        const file = FS.readFile(filePath, {encoding: 'binary'});
        if (file)
        {
            const blob = new Blob([file], {type: 'application/octet-stream'});
            window['saveAs'](blob, filePath.split('/').pop());
        } else {
            alert('Impossible de récupérer le fichier généré:(');
        }

    } catch (e)
    {
        alert('Hmmm. Une erreur est survenue. ' + e.toString());
    }
}
<|endoftext|>


<commit_before>Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] == obj) {
      return true;
    }
  }
  return false;
}

Array.prototype.mode = function () {
  var histogram = {};
  for (var i = 0; i < this.length; i++) {
    if (histogram[this[i]]) {
      histogram[this[i]]++;
    } else {
      histogram[this[i]] = 1;
    }
  }
  var maxIndex = 0;
  var maxValue = 0;
  for (var key in histogram) {
    if (histogram[key] > maxValue) {
      maxIndex = key;
      maxValue = histogram[key];
    }
  }
  return maxIndex;
}

Array.prototype.max = function() {
  return Math.max.apply(Math, this);
};

Array.prototype.min = function() {
  return Math.min.apply(Math, this);
};

Array.prototype.sum = function() {
  var sum = 0;
  for (var i = this.length - 1; i >= 0; i--) {
    sum += this[i];
  }
  return sum;
};

Array.prototype.average = function() {
  if (!this.length) return 0;
  return this.sum() / this.length;
};

Array.prototype.median = function() {
  if (!this.length) return 0;
  var sorted = this.clone().sort();
  var lower = sorted[Math.floor((sorted.length + 1) / 2) - 1];
  if (sorted.length == 1) {
    return sorted[0];
  } else if (sorted.length % 2) {
    return lower;
  } else {
    var upper = sorted[Math.floor((sorted.length + 1) / 2)];
    return (lower + upper) / 2;
  }
};

Array.prototype.clone = function() {
  var newArr = [];
  for (var i = 0; i < this.length; i++) {
    newArr.push(this[i]);
  }
  return newArr;
};

window.location.queryString = function() {
  var result = {};
  var raw_string = decodeURI(location.search);

  if (!raw_string || raw_string.length == 0) {
    return result;
  }

  raw_string = raw_string.substring(1);  // trim leading '?'

  var name_values = raw_string.split("&");
  for (var i = 0; i < name_values.length; ++i) {
    var elts = name_values[i].split('=');
    if (result[elts[0]])
      result[elts[0]] += "," + elts[1];
    else
      result[elts[0]] = elts[1];
  }

  return result;
};

// Wrapper around XHR.
function XHRGet(url, callback, data) {
  var self = this;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.send();

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status != 200) {
        alert("Error: could not download (" + url + "): " + xhr.status);
      }
      callback(xhr.responseText, data);
    }
  }
}

// Given a stddev and a sample count, compute the stderr
function stderr(stddev, sample_count) {
  return stddev / Math.sqrt(sample_count);
}

// Given a stderr, compute the 95% confidence interval
function ci(stderr) {
  return 1.96 * stderr;
}

// Returns true if the given averages have a statistically significant
// difference based on their standard deviations.
function isSignificant(avg1, stddev1, len1, avg2, stddev2, len2) {
    var ci1 = ci(stderr(stddev1, len1));
    var ci2 = ci(stderr(stddev2, len2));
    return (avg1 + ci1) < (avg2 - ci2) || (avg1 - ci1) > (avg2 + ci2);
}

// Sets the selected option of the <select> with id=|id|.
function setSelectValue(id, value) {
    if (!id || !value) return;
    var elt = document.getElementById(id);
    if (!elt) return;
    for (var i = 0; i < elt.options.length; i++) {
        if (elt.options[i].value == value) {
          elt.options[i].selected = true
        } else {
          elt.options[i].selected = false;
        }
    }
}

// Gets the value of the selected option of the <select> with id=|id|.
function getSelectValue(id) {
    var elt = document.getElementById(id);
    if (!elt) return "";
    return elt[elt.selectedIndex].value;
}

// Sets the parameters in the URL fragment to those in the |newParams|
// key:value map.
function setParams(params) {
    var hashString = "";
    for (var param in params) {
      if (!param) continue;
      hashString += "&" + param + "=" + encodeURIComponent(params[param]);
    }
    window.location.hash = "#" + hashString.substring(1);
}

// Returns a key:value map of all parameters in the URL fragment.
function getParams() {
    var map = {};
    var hash = window.location.hash.substring(1);
    pairs = hash.split("&");
    for (var i = 0; i < pairs.length; i++) {
        var key_val = pairs[i].split("=");
        map[key_val[0]] = decodeURIComponent(key_val[1]);
    }
    return map;
}
<commit_msg>Fix median calculation.<commit_after>Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] == obj) {
      return true;
    }
  }
  return false;
}

Array.prototype.mode = function () {
  var histogram = {};
  for (var i = 0; i < this.length; i++) {
    if (histogram[this[i]]) {
      histogram[this[i]]++;
    } else {
      histogram[this[i]] = 1;
    }
  }
  var maxIndex = 0;
  var maxValue = 0;
  for (var key in histogram) {
    if (histogram[key] > maxValue) {
      maxIndex = key;
      maxValue = histogram[key];
    }
  }
  return maxIndex;
}

Array.prototype.max = function() {
  return Math.max.apply(Math, this);
};

Array.prototype.min = function() {
  return Math.min.apply(Math, this);
};

Array.prototype.sum = function() {
  var sum = 0;
  for (var i = this.length - 1; i >= 0; i--) {
    sum += this[i];
  }
  return sum;
};

Array.prototype.average = function() {
  if (!this.length) return 0;
  return this.sum() / this.length;
};

function sortNumber(a, b) {
  return a - b;
}

Array.prototype.median = function() {
  if (!this.length) return 0;
  var sorted = this.clone().sort(sortNumber);
  var lower = sorted[Math.floor((sorted.length + 1) / 2) - 1];
  if (sorted.length == 1) {
    return sorted[0];
  } else if (sorted.length % 2) {
    return lower;
  } else {
    var upper = sorted[Math.floor((sorted.length + 1) / 2)];
    return (lower + upper) / 2;
  }
};

Array.prototype.clone = function() {
  var newArr = [];
  for (var i = 0; i < this.length; i++) {
    newArr.push(this[i]);
  }
  return newArr;
};

window.location.queryString = function() {
  var result = {};
  var raw_string = decodeURI(location.search);

  if (!raw_string || raw_string.length == 0) {
    return result;
  }

  raw_string = raw_string.substring(1);  // trim leading '?'

  var name_values = raw_string.split("&");
  for (var i = 0; i < name_values.length; ++i) {
    var elts = name_values[i].split('=');
    if (result[elts[0]])
      result[elts[0]] += "," + elts[1];
    else
      result[elts[0]] = elts[1];
  }

  return result;
};

// Wrapper around XHR.
function XHRGet(url, callback, data) {
  var self = this;
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.send();

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status != 200) {
        alert("Error: could not download (" + url + "): " + xhr.status);
      }
      callback(xhr.responseText, data);
    }
  }
}

// Given a stddev and a sample count, compute the stderr
function stderr(stddev, sample_count) {
  return stddev / Math.sqrt(sample_count);
}

// Given a stderr, compute the 95% confidence interval
function ci(stderr) {
  return 1.96 * stderr;
}

// Returns true if the given averages have a statistically significant
// difference based on their standard deviations.
function isSignificant(avg1, stddev1, len1, avg2, stddev2, len2) {
    var ci1 = ci(stderr(stddev1, len1));
    var ci2 = ci(stderr(stddev2, len2));
    return (avg1 + ci1) < (avg2 - ci2) || (avg1 - ci1) > (avg2 + ci2);
}

// Sets the selected option of the <select> with id=|id|.
function setSelectValue(id, value) {
    if (!id || !value) return;
    var elt = document.getElementById(id);
    if (!elt) return;
    for (var i = 0; i < elt.options.length; i++) {
        if (elt.options[i].value == value) {
          elt.options[i].selected = true
        } else {
          elt.options[i].selected = false;
        }
    }
}

// Gets the value of the selected option of the <select> with id=|id|.
function getSelectValue(id) {
    var elt = document.getElementById(id);
    if (!elt) return "";
    return elt[elt.selectedIndex].value;
}

// Sets the parameters in the URL fragment to those in the |newParams|
// key:value map.
function setParams(params) {
    var hashString = "";
    for (var param in params) {
      if (!param) continue;
      hashString += "&" + param + "=" + encodeURIComponent(params[param]);
    }
    window.location.hash = "#" + hashString.substring(1);
}

// Returns a key:value map of all parameters in the URL fragment.
function getParams() {
    var map = {};
    var hash = window.location.hash.substring(1);
    pairs = hash.split("&");
    for (var i = 0; i < pairs.length; i++) {
        var key_val = pairs[i].split("=");
        map[key_val[0]] = decodeURIComponent(key_val[1]);
    }
    return map;
}
<|endoftext|>


<commit_before>(function(){

	// if(module.exports !== undefined){
	// 	this.print = console.log;
	// }

	// Initialization
	function Init(){
		this.args = (function(a){
			return [].slice.call(a[0]);
		}(arguments));
		this.count = 10;
	}

	// Take input and generate data base on the input
	Init.prototype.style = function(){
		if (arguments.length){
			localargs = [].slice.call(arguments);
			(function(a,b,c){
				switch(true){
					case (a[0] === 'default') :
						// if(this.module.exports === undefined){
						for(i = 1; i <= c; i++){
							// Default formatted data[mongodb test data format]
							db[b]['insert'](
								{"address": {
									"building": Math.floor(Math.random()*10001),
									"coord": [-(Math.random()*100000001/1000000).toFixed(6), (Math.random()*100000001/1000000).toFixed(6)],
									"street": ['East','South','West','North'][Math.floor(Math.random()*4)]+' '+Math.floor(Math.random()*101)+' Street',
									"zipcode": Math.floor(Math.random()*10001)
									},
									 "borough": ["Manhattan","Brooklyn","Queens","Staten","Bronx"][Math.floor(Math.random()*5)],
									 "cuisine": ["Bakery","Hamburgers","Irish","American","Jewish","Delicatessen","Ice","Chinese","Chicken","Turkish","Caribbean","Donuts","Sandwiches"][Math.floor(Math.random()*13)],
									 "grades": [
								 			{
								 				"date": {
								 					"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
								 					},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											},
											{
												"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
												},
											 "grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											},
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 },
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 },
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 }
									 	],
									 "name": ["Morris","Wendy","Riviera","Tov","Brunos","Kosher","Wilken","Regina","Taste","Wild","Seuda","Carvel","Nordic","Glorious","The","Sal","Bully","Steve","Harriet","Angelika"][Math.floor(Math.random()*20)]+" Shop",
									 "restaurant_id": String(Math.floor(Math.random()*30000000))
								}
							);
						}
						print("\nAwesome ~ Generated "+c+" default test data\nUse db[collection].find().pretty(); to view :)\n");
						// }else{
						// 	print("This is for NodeJS testing environment,so it does not support adding items to the database~ :)");
						// }
						break;
					case typeof a[0] === 'object' && !Array.isArray(a[0]) && !isEmpty(a[0]) :
						for(z = 1; z <= c; z++){
							// Create an outer empty obj to collect the output
							var result = {};
							var nestStack = [];
							var reachEnd = false;
							var digitReg = /^d\d*/;
							var nameReg = /^n,[mf]/;
							// Recursion for nesting obj or array
							(function(obj,nest){

								// Basic setting
								var arr = [];
								for(var i in obj){
									arr.push(i);
								}

								for(var j = 0 ; j < arr.length; j++ ){

									if(obj[arr[j]] === 's'){
										// Handle string
										if(nest && !reachEnd){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomString()');
										}else if(nest && reachEnd){
											nestStack.pop();
											if(nestStack.length !== 1){
												eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomString()')
											}else{
												eval('result["'+ nestStack[0]+'"]["'+arr[j]+'"] = randomString()')
											}
										}else{
											result[arr[j]] = randomString()
										};

									}
									// Handle digit
									else if(obj[arr[j]] === 'd' || digitReg.test(obj[arr[j]]) ){

										var randomDigitResult;
										if (obj[arr[j]] !== 'd'){
											var match = obj[arr[j]].match(digitReg);
											if (match.length){
												match[0].substr(1, match.length);
												randomDigitResult = randomNumber(Number(match[0]));
											}

										}else{
											randomDigitResult = randomNumber();
										}

										if(nest && !reachEnd){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomDigitResult')
										}else if(nest && reachEnd){
											nestStack.pop();
											if(nestStack.length !== 1){
												eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomDigitResult')
											}else{
												eval('result["'+ nestStack[0]+'"]["'+arr[j]+'"] = randomDigitResult')
											}
										}else{
											result[arr[j]] = randomDigitResult
										};

									}
									// Handle boolean
									else if(obj[arr[j]] === 'b'){
										if(nest && !reachEnd){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomBool()')
										}else if(nest && reachEnd){
											nestStack.pop();
											if(nestStack.length !== 1){
												eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomBool()')
											}else{
												eval('result["'+ nestStack[0]+'"]["'+arr[j]+'"] = randomBool()')
											}
										}else{
											result[arr[j]] = randomBool()
										};

									}
									// Handle name
									else if(obj[arr[j]] === 'n' || nameReg.test(obj[arr[j]]) ){

										var randomNameResult;
										if (obj[arr[j]] !== 'n'){
											var match = obj[arr[j]].match(digitReg);
											if (match.length){

												if(match[0] === 'n,m'){
													randomNameResult = randomName('m');
												}else if(match[0] === 'n,f'){
													randomNameResult = randomName('f');
												}else{
													randomNameResult = randomName();
												}
											}

										}else{
											randomNameResult = randomName();
										}

										if(nest && !reachEnd){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomNameResult');
										}else if(nest && reachEnd){
											nestStack.pop();
											if(nestStack.length !== 1){
												eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomNameResult');
											}else{
												eval('result["'+ nestStack[0]+'"]["'+arr[j]+'"] = randomNameResult');
											}
										}else{
											result[arr[j]] = randomNameResult;
										};

									}
									// Check if the current input is an obj
									else if(typeof obj[arr[j]] === 'object' && !Array.isArray(obj[arr[j]]) && !isEmpty(obj[arr[j]]) ){

										if(nest){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = {}')
										}else{
											result[arr[j]] = {};
										}
										nestStack.push(arr[j]);
										arguments.callee(obj[arr[j]], arr[j]);
									}
									// Check if the current input is an array
									else if(typeof obj[arr[j]] === 'object' && Array.isArray(obj[arr[j]]) && obj[arr[j]].length){

										if(nest){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = []')
										}else{
											result[arr[j]] = [];
										}
										nestStack.push(arr[j]);
										arguments.callee(obj[arr[j]], arr[j]);

									}
									else{
										print('\nOops, Wrong input, Plz check the documentation\nOr try gen_Init[collection].style(\'default\'); to get the default testing data :)\n ');
									}
									if(j == arr.length-1){
										reachEnd = true;
										nestStack.pop();
									}else{
										reachEnd = false;
									}
								}
							})(a[0])
							if(this.module.exports === undefined){
								db[b]['insert'](result);
							}
						}
						print("\nAwesome ~ Generated "+c+" default test data\nUse db[collection].find().pretty(); to view :)\n");
						break;
					default :
						print('\nOops, Wrong input, Plz check the documentation\nOr try gen_Init[collection].style(\'default\'); to get the default testing data :)\n ');
						break;
				}
				// Hoisting functions
				function randomDate(start, end) {
				    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
				}

				// Check if the given obj is empty
				function isEmpty(obj) {
				    if (obj == null) return true;
				    if (obj.length > 0)    return false;
				    if (obj.length === 0)  return true;
				    for (var key in obj) {
				        if (Object.prototype.hasOwnProperty.call(obj, key)) return false;
				    }
				    return true;
				}

				// Handle random string
				function randomString(){
				    var text = "";
				    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

				    for( var i=0; i < 7; i++ )
				        text += possible.charAt(Math.floor(Math.random() * possible.length));

				    return text;
				}

				// Handle random number
				function randomNumber(){
					return !arguments.length ? Math.floor(Math.random()*101) : Math.floor(Math.random()*(1+arguments[0]));
				}

				// Handle random boolean
				function randomBool(){
					return [true,false][Math.floor(Math.random()*2)]
				}

				// Handle random name
				function randomName(){
					var Male = ["Nickolas","Ramon","Lou","Luciano","Mickey","Silas","Michael","Charles","Eusebio","Boyce","Martin","Rosendo","Val","Marcus","Berry","Lyndon","Chung","Kenton","Jackie","Tyron","Reid","Herb","Felipe","Lyle","Lowell","Salvador","Enrique","Hosea","Micheal","Rhett","Denver","Jimmy","Frederick","Otha","Anibal","Warren","Andre","Jim","Weldon","Blaine","Mariano","Gavin","Raymon","Jarrod","Nicolas","Minh","Justin","Johnny","Felix","Barry"];

					var Female = ["Estefana","Danyel","Leonora","Velva","Celia","Cindie","Florine","Misty","Penny","Rosemarie","Creola","Nada","Carri","Lashanda","Letha","Aracelis","Arletta","Sherley","Herlinda","Pura","Gwyn","Carisa","Charmaine","Krishna","Katie","Dia","Bobbi","Criselda","Tamie","Azalee","Opal","Lyndsey","Paulita","Saran","Raylene","Corine","Jeanette","Delta","Despina","Sharonda","Claretta","Kacie","Toni","Elisabeth","Katherina","Elke","Tamala","Joy","Shandi","Devora"];

					return arguments.length ? arguments[0] === 'm' ? Male[Math.floor(Math.random()*50)] : arguments[0] === 'f' ? Female[Math.floor(Math.random()*50)] : Male.concat(Female)[Math.floor(Math.random()*100)] : Male.concat(Female)[Math.floor(Math.random()*100)];
				}
			}(localargs, this.args, this.count))
		}else{
			print("You can define some options or use gen_Init(...).style('default')" );
		}
	};

	// Specify the amount of data to insert
	Init.prototype.total = function(n){
		this.count = n;
		return this;
	}

	// Output to the global
	this.gen_Init = function(){
		return new Init(arguments);
	}

}.call(this))

<commit_msg>bug fix<commit_after>(function(){

	// if(module.exports !== undefined){
	// 	this.print = console.log;
	// }

	// Initialization
	function Init(){
		this.args = (function(a){
			return [].slice.call(a[0]);
		}(arguments));
		this.count = 10;
	}

	// Take input and generate data base on the input
	Init.prototype.style = function(){
		if (arguments.length){
			localargs = [].slice.call(arguments);
			(function(a,b,c){
				switch(true){
					case (a[0] === 'default') :
						// if(this.module.exports === undefined){
						for(i = 1; i <= c; i++){
							// Default formatted data[mongodb test data format]
							db[b]['insert'](
								{"address": {
									"building": Math.floor(Math.random()*10001),
									"coord": [-(Math.random()*100000001/1000000).toFixed(6), (Math.random()*100000001/1000000).toFixed(6)],
									"street": ['East','South','West','North'][Math.floor(Math.random()*4)]+' '+Math.floor(Math.random()*101)+' Street',
									"zipcode": Math.floor(Math.random()*10001)
									},
									 "borough": ["Manhattan","Brooklyn","Queens","Staten","Bronx"][Math.floor(Math.random()*5)],
									 "cuisine": ["Bakery","Hamburgers","Irish","American","Jewish","Delicatessen","Ice","Chinese","Chicken","Turkish","Caribbean","Donuts","Sandwiches"][Math.floor(Math.random()*13)],
									 "grades": [
								 			{
								 				"date": {
								 					"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
								 					},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											},
											{
												"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
												},
											 "grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											},
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 },
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 },
											 {
											 	"date": {
											 		"date": randomDate(new Date(2000, 0, 1), new Date()).getTime()
											 	},
											 	"grade": "ABCD"[Math.floor(Math.random()*4)], "score": Math.floor(Math.random()*11)
											 }
									 	],
									 "name": ["Morris","Wendy","Riviera","Tov","Brunos","Kosher","Wilken","Regina","Taste","Wild","Seuda","Carvel","Nordic","Glorious","The","Sal","Bully","Steve","Harriet","Angelika"][Math.floor(Math.random()*20)]+" Shop",
									 "restaurant_id": String(Math.floor(Math.random()*30000000))
								}
							);
						}
						print("\nAwesome ~ Generated "+c+" default test data\nUse db[collection].find().pretty(); to view :)\n");
						// }else{
						// 	print("This is for NodeJS testing environment,so it does not support adding items to the database~ :)");
						// }
						break;
					case typeof a[0] === 'object' && !Array.isArray(a[0]) && !isEmpty(a[0]) :
						for(z = 1; z <= c; z++){
							// Create an outer empty obj to collect the output
							var result = {};
							var nestStack = [];
							var reachEnd = false;
							var digitReg = /^d\d*/;
							var nameReg = /^n,[mf]/;
							// Recursion for nesting obj or array
							(function(obj,nest){

								// Basic setting
								var arr = [];
								for(var i in obj){
									arr.push(i);
								}

								for(var j = 0 ; j < arr.length; j++ ){

									if(obj[arr[j]] === 's'){
										// Handle string
										if(nest && !reachEnd){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomString()');
										}else if(nest && reachEnd){
											nestStack.pop();
											if(nestStack.length !== 1){
												eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomString()')
											}else{
												eval('result["'+ nestStack[0]+'"]["'+arr[j]+'"] = randomString()')
											}
										}else{
											result[arr[j]] = randomString()
										};

									}
									// Handle digit
									else if(!Array.isArray(obj[arr[j]]) && typeof obj[arr[j]] !== 'object' && (obj[arr[j]] === 'd' || digitReg.test(obj[arr[j]].toString()) ) ){

										var randomDigitResult;
										if (obj[arr[j]] !== 'd' && obj[arr[j]].toString().match(digitReg).length ){
											var match = obj[arr[j]].toString().match(digitReg);
											if (match.length){
												match[0].substr(1, match.length);
												randomDigitResult = randomNumber(Number(match[0]));
											}else{
												randomDigitResult = randomNumber();
											}

										}else{
											randomDigitResult = randomNumber();
										}

										if(nest && !reachEnd){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomDigitResult')
										}else if(nest && reachEnd){
											nestStack.pop();
											if(nestStack.length !== 1){
												eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomDigitResult')
											}else{
												eval('result["'+ nestStack[0]+'"]["'+arr[j]+'"] = randomDigitResult')
											}
										}else{
											result[arr[j]] = randomDigitResult
										};

									}
									// Handle boolean
									else if(obj[arr[j]] === 'b'){
										if(nest && !reachEnd){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomBool()')
										}else if(nest && reachEnd){
											nestStack.pop();
											if(nestStack.length !== 1){
												eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomBool()')
											}else{
												eval('result["'+ nestStack[0]+'"]["'+arr[j]+'"] = randomBool()')
											}
										}else{
											result[arr[j]] = randomBool()
										};

									}
									// Handle name
									else if(!Array.isArray(obj[arr[j]]) && typeof obj[arr[j]] !== 'object' && (obj[arr[j]] === 'n' || nameReg.test(obj[arr[j]].toString()) ) ){

										var randomNameResult;
										if (obj[arr[j]] !== 'n' && obj[arr[j]].toString().match(nameReg).length){
											var match = obj[arr[j]].toString().match(digitReg);
											if (match.length){

												if(match[0] === 'n,m'){
													randomNameResult = randomName('m');
												}else if(match[0] === 'n,f'){
													randomNameResult = randomName('f');
												}else{
													randomNameResult = randomName();
												}
											}else{
												randomNameResult = randomName();
											}

										}else{
											randomNameResult = randomName();
										}

										if(nest && !reachEnd){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomNameResult');
										}else if(nest && reachEnd){
											nestStack.pop();
											if(nestStack.length !== 1){
												eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = randomNameResult');
											}else{
												eval('result["'+ nestStack[0]+'"]["'+arr[j]+'"] = randomNameResult');
											}
										}else{
											result[arr[j]] = randomNameResult;
										};

									}
									// Check if the current input is an obj
									else if(typeof obj[arr[j]] === 'object' && !Array.isArray(obj[arr[j]]) && !isEmpty(obj[arr[j]]) ){

										if(nest){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = {}')
										}else{
											result[arr[j]] = {};
										}
										nestStack.push(arr[j]);
										arguments.callee(obj[arr[j]], arr[j]);
									}
									// Check if the current input is an array
									else if(typeof obj[arr[j]] === 'object' && Array.isArray(obj[arr[j]]) && obj[arr[j]].length){

										if(nest){
											eval('result["'+ nestStack.join('"]["')+'"]["'+arr[j]+'"] = []')
										}else{
											result[arr[j]] = [];
										}
										nestStack.push(arr[j]);
										arguments.callee(obj[arr[j]], arr[j]);

									}
									else{
										print('\nOops, Wrong input, Plz check the documentation\nOr try gen_Init[collection].style(\'default\'); to get the default testing data :)\n ');
									}
									if(j == arr.length-1){
										reachEnd = true;
										nestStack.pop();
									}else{
										reachEnd = false;
									}
								}
							})(a[0])
							if(this.module.exports === undefined){
								db[b]['insert'](result);
							}
						}
						print("\nAwesome ~ Generated "+c+" default test data\nUse db[collection].find().pretty(); to view :)\n");
						break;
					default :
						print('\nOops, Wrong input, Plz check the documentation\nOr try gen_Init[collection].style(\'default\'); to get the default testing data :)\n ');
						break;
				}
				// Hoisting functions
				function randomDate(start, end) {
				    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
				}

				// Check if the given obj is empty
				function isEmpty(obj) {
				    if (obj == null) return true;
				    if (obj.length > 0)    return false;
				    if (obj.length === 0)  return true;
				    for (var key in obj) {
				        if (Object.prototype.hasOwnProperty.call(obj, key)) return false;
				    }
				    return true;
				}

				// Handle random string
				function randomString(){
				    var text = "";
				    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

				    for( var i=0; i < 7; i++ )
				        text += possible.charAt(Math.floor(Math.random() * possible.length));

				    return text;
				}

				// Handle random number
				function randomNumber(){
					return !arguments.length ? Math.floor(Math.random()*101) : Math.floor(Math.random()*(1+arguments[0]));
				}

				// Handle random boolean
				function randomBool(){
					return [true,false][Math.floor(Math.random()*2)]
				}

				// Handle random name
				function randomName(){
					var Male = ["Nickolas","Ramon","Lou","Luciano","Mickey","Silas","Michael","Charles","Eusebio","Boyce","Martin","Rosendo","Val","Marcus","Berry","Lyndon","Chung","Kenton","Jackie","Tyron","Reid","Herb","Felipe","Lyle","Lowell","Salvador","Enrique","Hosea","Micheal","Rhett","Denver","Jimmy","Frederick","Otha","Anibal","Warren","Andre","Jim","Weldon","Blaine","Mariano","Gavin","Raymon","Jarrod","Nicolas","Minh","Justin","Johnny","Felix","Barry"];

					var Female = ["Estefana","Danyel","Leonora","Velva","Celia","Cindie","Florine","Misty","Penny","Rosemarie","Creola","Nada","Carri","Lashanda","Letha","Aracelis","Arletta","Sherley","Herlinda","Pura","Gwyn","Carisa","Charmaine","Krishna","Katie","Dia","Bobbi","Criselda","Tamie","Azalee","Opal","Lyndsey","Paulita","Saran","Raylene","Corine","Jeanette","Delta","Despina","Sharonda","Claretta","Kacie","Toni","Elisabeth","Katherina","Elke","Tamala","Joy","Shandi","Devora"];

					return arguments.length ? arguments[0] === 'm' ? Male[Math.floor(Math.random()*50)] : arguments[0] === 'f' ? Female[Math.floor(Math.random()*50)] : Male.concat(Female)[Math.floor(Math.random()*100)] : Male.concat(Female)[Math.floor(Math.random()*100)];
				}
			}(localargs, this.args, this.count))
		}else{
			print("You can define some options or use gen_Init(...).style('default')" );
		}
	};

	// Specify the amount of data to insert
	Init.prototype.total = function(n){
		this.count = n;
		return this;
	}

	// Output to the global
	this.gen_Init = function(){
		return new Init(arguments);
	}

}.call(this))

<|endoftext|>


<commit_before>var echarts = require('echarts/lib/echarts');
var graphicGL = require('../../util/graphicGL');
var retrieve = require('../../util/retrieve');
var format = require('../../util/format');
var BarsGeometry = require('../../util/geometry/Bars3DGeometry');
var LabelsBuilder = require('../../component/common/LabelsBuilder');
var vec3 = require('qtek/lib/dep/glmatrix').vec3;

function getShader(shading) {
    var shader = graphicGL.createShader('ecgl.' + shading);
    shader.define('both', 'VERTEX_COLOR');
    return shader;
}

module.exports = echarts.extendChartView({

    type: 'bar3D',

    __ecgl__: true,

    init: function (ecModel, api) {

        this.groupGL = new graphicGL.Node();

        var materials = {};
        graphicGL.COMMON_SHADERS.forEach(function (shading) {
            materials[shading] = new graphicGL.Material({
                shader: getShader(shading)
            });
        });

        this._materials = materials;

        this._api = api;

        this._labelsBuilder = new LabelsBuilder(256, 256, api);
        var self = this;
        this._labelsBuilder.getLabelPosition = function (dataIndex, position, distance) {
            if (self._data) {
                var layout = self._data.getItemLayout(dataIndex);
                var start = layout[0];
                var dir = layout[1];
                var height = layout[2][1];
                return vec3.scaleAndAdd([], start, dir, distance + height);
            }
            else {
                return [0, 0];
            }
        };

        // Give a large render order.
        this._labelsBuilder.getMesh().renderOrder = 100;
    },

    render: function (seriesModel, ecModel, api) {

        // Swap barMesh
        var tmp = this._prevBarMesh;
        this._prevBarMesh = this._barMesh;
        this._barMesh = tmp;

        if (!this._barMesh) {
            this._barMesh = new graphicGL.Mesh({
                geometry: new BarsGeometry(),
                shadowDepthMaterial: new graphicGL.Material({
                    shader: new graphicGL.Shader({
                        vertex: graphicGL.Shader.source('ecgl.sm.depth.vertex'),
                        fragment: graphicGL.Shader.source('ecgl.sm.depth.fragment')
                    })
                }),
                // Only cartesian3D enable culling
                // FIXME Performance
                culling: seriesModel.coordinateSystem.type === 'cartesian3D',
                // Render after axes
                renderOrder: 10,
                // Render normal in normal pass
                renderNormal: true
            });
        }

        this.groupGL.remove(this._prevBarMesh);
        this.groupGL.add(this._barMesh);
        this.groupGL.add(this._labelsBuilder.getMesh());

        var coordSys = seriesModel.coordinateSystem;
        this._doRender(seriesModel, api);
        if (coordSys && coordSys.viewGL) {
            coordSys.viewGL.add(this.groupGL);

            var methodName = coordSys.viewGL.isLinearSpace() ? 'define' : 'undefine';
            this._barMesh.material.shader[methodName]('fragment', 'SRGB_DECODE');
        }

        this._data = seriesModel.getData();

        this._labelsBuilder.updateData(this._data);

        this._labelsBuilder.updateLabels();

        this._updateAnimation(seriesModel);
    },

    _updateAnimation: function (seriesModel) {
        graphicGL.updateVertexAnimation(
            [['prevPosition', 'position'],
            ['prevNormal', 'normal']],
            this._prevBarMesh,
            this._barMesh,
            seriesModel
        );
    },

    _doRender: function (seriesModel, api) {
        var data = seriesModel.getData();
        var shading = seriesModel.get('shading');
        var enableNormal = shading !== 'color';
        var self = this;
        var barMesh = this._barMesh;

        if (this._materials[shading]) {
            barMesh.material = this._materials[shading];
        }
        else {
            if (__DEV__) {
                console.warn('Unkown shading ' + shading);
            }
            barMesh.material = this._materials.lambert;
        }
        graphicGL.setMaterialFromModel(
            shading, barMesh.material, seriesModel, api
        );

        barMesh.geometry.enableNormal = enableNormal;

        barMesh.geometry.resetOffset();

        // Bevel settings
        var bevelSize = seriesModel.get('bevelSize');
        var bevelSegments = seriesModel.get('bevelSmoothness');
        barMesh.geometry.bevelSegments = bevelSegments;

        barMesh.geometry.bevelSize = bevelSize;

        var colorArr = [];
        var vertexColors = new Float32Array(data.count() * 4);
        var colorOffset = 0;
        var barCount = 0;
        var hasTransparent = false;

        data.each(function (idx) {
            if (!data.hasValue(idx)) {
                return;
            }
            var color = data.getItemVisual(idx, 'color');

            var opacity = data.getItemVisual(idx, 'opacity');
            if (opacity == null) {
                opacity = 1;
            }

            graphicGL.parseColor(color, colorArr);
            colorArr[3] *= opacity;
            vertexColors[colorOffset++] = colorArr[0];
            vertexColors[colorOffset++] = colorArr[1];
            vertexColors[colorOffset++] = colorArr[2];
            vertexColors[colorOffset++] = colorArr[3];

            if (colorArr[3] > 0) {
                barCount++;
            }
            if (colorArr[3] < 0.99) {
                hasTransparent = true;
            }
        });

        barMesh.geometry.setBarCount(barCount);

        var orient = data.getLayout('orient');

        // Map of dataIndex and barIndex.
        var barIndexOfData = this._barIndexOfData = new Int32Array(data.count());
        var barCount = 0;
        data.each(function (idx) {
            if (!data.hasValue(idx)) {
                barIndexOfData[idx] = -1;
                return;
            }
            var layout = data.getItemLayout(idx);
            var start = layout[0];
            var dir = layout[1];
            var size = layout[2];

            var idx4 = idx * 4;
            colorArr[0] = vertexColors[idx4++];
            colorArr[1] = vertexColors[idx4++];
            colorArr[2] = vertexColors[idx4++];
            colorArr[3] = vertexColors[idx4++];
            if (colorArr[3] > 0) {
                self._barMesh.geometry.addBar(start, dir, orient, size, colorArr, idx);
                barIndexOfData[idx] = barCount++;
            }
        });

        barMesh.geometry.dirty();
        barMesh.geometry.updateBoundingBox();

        var material = barMesh.material;
        material.transparent = hasTransparent;
        material.depthMask = !hasTransparent;
        barMesh.geometry.sortTriangles = hasTransparent;

        this._initHandler(seriesModel, api);
    },

    _initHandler: function (seriesModel, api) {
        var data = seriesModel.getData();
        var barMesh = this._barMesh;
        var isCartesian3D = seriesModel.coordinateSystem.type === 'cartesian3D';

        barMesh.seriesIndex = seriesModel.seriesIndex;

        var lastDataIndex = -1;
        barMesh.off('mousemove');
        barMesh.off('mouseout');
        barMesh.on('mousemove', function (e) {
            var dataIndex = barMesh.geometry.getDataIndexOfVertex(e.triangle[0]);
            if (dataIndex !== lastDataIndex) {
                this._downplay(lastDataIndex);
                this._highlight(dataIndex);
                this._labelsBuilder.updateLabels([dataIndex]);

                if (isCartesian3D) {
                    api.dispatchAction({
                        type: 'grid3DShowAxisPointer',
                        value: [data.get('x', dataIndex), data.get('y', dataIndex), data.get('z', dataIndex)]
                    });
                }
            }

            lastDataIndex = dataIndex;
            barMesh.dataIndex = dataIndex;
        }, this);
        barMesh.on('mouseout', function (e) {
            this._downplay(lastDataIndex);
            this._labelsBuilder.updateLabels();
            lastDataIndex = -1;
            barMesh.dataIndex = -1;

            if (isCartesian3D) {
                api.dispatchAction({
                    type: 'grid3DHideAxisPointer'
                });
            }
        }, this);
    },

    _highlight: function (dataIndex) {
        var data = this._data;
        if (!data) {
            return;
        }
        var barIndex = this._barIndexOfData[dataIndex];
        if (barIndex < 0) {
            return;
        }

        var itemModel = data.getItemModel(dataIndex);
        var emphasisItemStyleModel = itemModel.getModel('emphasis.itemStyle');
        var emphasisColor = emphasisItemStyleModel.get('color');
        var emphasisOpacity = emphasisItemStyleModel.get('opacity');
        if (emphasisColor == null) {
            var color = data.getItemVisual(dataIndex, 'color');
            emphasisColor = echarts.color.lift(color, -0.4);
        }
        if (emphasisOpacity == null) {
            emphasisOpacity = data.getItemVisual(dataIndex, 'opacity');
        }
        var colorArr = graphicGL.parseColor(emphasisColor);
        colorArr[3] *= emphasisOpacity;

        this._barMesh.geometry.setColor(barIndex, colorArr);

        this._api.getZr().refresh();
    },

    _downplay: function (dataIndex) {
        var data = this._data;
        if (!data) {
            return;
        }
        var barIndex = this._barIndexOfData[dataIndex];
        if (barIndex < 0) {
            return;
        }

        var color = data.getItemVisual(dataIndex, 'color');
        var opacity = data.getItemVisual(dataIndex, 'opacity');

        var colorArr = graphicGL.parseColor(color);
        colorArr[3] *= opacity;

        this._barMesh.geometry.setColor(barIndex, colorArr);

        this._api.getZr().refresh();
    },

    highlight: function (seriesModel, ecModel, api, payload) {
        this._toggleStatus('highlight', seriesModel, ecModel, api, payload);
    },

    downplay: function (seriesModel, ecModel, api, payload) {
        this._toggleStatus('downplay', seriesModel, ecModel, api, payload);
    },

    _toggleStatus: function (status, seriesModel, ecModel, api, payload) {
        var data = seriesModel.getData();
        var dataIndex = retrieve.queryDataIndex(data, payload);

        var self = this;
        if (dataIndex != null) {
            echarts.util.each(format.normalizeToArray(dataIndex), function (dataIdx) {
                status === 'highlight' ? this._highlight(dataIdx) : this._downplay(dataIdx);
            }, this);
        }
        else {
            data.each(function (dataIdx) {
                status === 'highlight' ? self._highlight(dataIdx) : self._downplay(dataIdx);
            });
        }
    },

    remove: function () {
        this.groupGL.removeAll();
    },

    dispose: function () {
        this.groupGL.removeAll();
    }
});<commit_msg>bar3D optimize<commit_after>var echarts = require('echarts/lib/echarts');
var graphicGL = require('../../util/graphicGL');
var retrieve = require('../../util/retrieve');
var format = require('../../util/format');
var BarsGeometry = require('../../util/geometry/Bars3DGeometry');
var LabelsBuilder = require('../../component/common/LabelsBuilder');
var vec3 = require('qtek/lib/dep/glmatrix').vec3;

function getShader(shading) {
    var shader = graphicGL.createShader('ecgl.' + shading);
    shader.define('both', 'VERTEX_COLOR');
    return shader;
}

module.exports = echarts.extendChartView({

    type: 'bar3D',

    __ecgl__: true,

    init: function (ecModel, api) {

        this.groupGL = new graphicGL.Node();

        var materials = {};
        graphicGL.COMMON_SHADERS.forEach(function (shading) {
            materials[shading] = new graphicGL.Material({
                shader: getShader(shading)
            });
        });

        this._materials = materials;

        this._api = api;

        this._labelsBuilder = new LabelsBuilder(256, 256, api);
        var self = this;
        this._labelsBuilder.getLabelPosition = function (dataIndex, position, distance) {
            if (self._data) {
                var layout = self._data.getItemLayout(dataIndex);
                var start = layout[0];
                var dir = layout[1];
                var height = layout[2][1];
                return vec3.scaleAndAdd([], start, dir, distance + height);
            }
            else {
                return [0, 0];
            }
        };

        // Give a large render order.
        this._labelsBuilder.getMesh().renderOrder = 100;
    },

    render: function (seriesModel, ecModel, api) {

        // Swap barMesh
        var tmp = this._prevBarMesh;
        this._prevBarMesh = this._barMesh;
        this._barMesh = tmp;

        if (!this._barMesh) {
            this._barMesh = new graphicGL.Mesh({
                geometry: new BarsGeometry(),
                shadowDepthMaterial: new graphicGL.Material({
                    shader: new graphicGL.Shader({
                        vertex: graphicGL.Shader.source('ecgl.sm.depth.vertex'),
                        fragment: graphicGL.Shader.source('ecgl.sm.depth.fragment')
                    })
                }),
                // Only cartesian3D enable culling
                // FIXME Performance
                culling: seriesModel.coordinateSystem.type === 'cartesian3D',
                // Render after axes
                renderOrder: 10,
                // Render normal in normal pass
                renderNormal: true
            });
        }

        this.groupGL.remove(this._prevBarMesh);
        this.groupGL.add(this._barMesh);
        this.groupGL.add(this._labelsBuilder.getMesh());

        var coordSys = seriesModel.coordinateSystem;
        this._doRender(seriesModel, api);
        if (coordSys && coordSys.viewGL) {
            coordSys.viewGL.add(this.groupGL);

            var methodName = coordSys.viewGL.isLinearSpace() ? 'define' : 'undefine';
            this._barMesh.material.shader[methodName]('fragment', 'SRGB_DECODE');
        }

        this._data = seriesModel.getData();

        this._labelsBuilder.updateData(this._data);

        this._labelsBuilder.updateLabels();

        this._updateAnimation(seriesModel);
    },

    _updateAnimation: function (seriesModel) {
        graphicGL.updateVertexAnimation(
            [['prevPosition', 'position'],
            ['prevNormal', 'normal']],
            this._prevBarMesh,
            this._barMesh,
            seriesModel
        );
    },

    _doRender: function (seriesModel, api) {
        var data = seriesModel.getData();
        var shading = seriesModel.get('shading');
        var enableNormal = shading !== 'color';
        var self = this;
        var barMesh = this._barMesh;

        if (this._materials[shading]) {
            barMesh.material = this._materials[shading];
        }
        else {
            if (__DEV__) {
                console.warn('Unkown shading ' + shading);
            }
            barMesh.material = this._materials.lambert;
        }
        graphicGL.setMaterialFromModel(
            shading, barMesh.material, seriesModel, api
        );

        barMesh.geometry.enableNormal = enableNormal;

        barMesh.geometry.resetOffset();

        // Bevel settings
        var bevelSize = seriesModel.get('bevelSize');
        var bevelSegments = seriesModel.get('bevelSmoothness');
        barMesh.geometry.bevelSegments = bevelSegments;

        barMesh.geometry.bevelSize = bevelSize;

        var colorArr = [];
        var vertexColors = new Float32Array(data.count() * 4);
        var colorOffset = 0;
        var barCount = 0;
        var hasTransparent = false;

        data.each(function (idx) {
            if (!data.hasValue(idx)) {
                return;
            }
            var color = data.getItemVisual(idx, 'color');

            var opacity = data.getItemVisual(idx, 'opacity');
            if (opacity == null) {
                opacity = 1;
            }

            graphicGL.parseColor(color, colorArr);
            colorArr[3] *= opacity;
            vertexColors[colorOffset++] = colorArr[0];
            vertexColors[colorOffset++] = colorArr[1];
            vertexColors[colorOffset++] = colorArr[2];
            vertexColors[colorOffset++] = colorArr[3];

            if (colorArr[3] > 0) {
                barCount++;
                if (colorArr[3] < 0.99) {
                    hasTransparent = true;
                }
            }
        });

        barMesh.geometry.setBarCount(barCount);

        var orient = data.getLayout('orient');

        // Map of dataIndex and barIndex.
        var barIndexOfData = this._barIndexOfData = new Int32Array(data.count());
        var barCount = 0;
        data.each(function (idx) {
            if (!data.hasValue(idx)) {
                barIndexOfData[idx] = -1;
                return;
            }
            var layout = data.getItemLayout(idx);
            var start = layout[0];
            var dir = layout[1];
            var size = layout[2];

            var idx4 = idx * 4;
            colorArr[0] = vertexColors[idx4++];
            colorArr[1] = vertexColors[idx4++];
            colorArr[2] = vertexColors[idx4++];
            colorArr[3] = vertexColors[idx4++];
            if (colorArr[3] > 0) {
                self._barMesh.geometry.addBar(start, dir, orient, size, colorArr, idx);
                barIndexOfData[idx] = barCount++;
            }
        });

        barMesh.geometry.dirty();
        barMesh.geometry.updateBoundingBox();

        var material = barMesh.material;
        material.transparent = hasTransparent;
        material.depthMask = !hasTransparent;
        barMesh.geometry.sortTriangles = hasTransparent;

        this._initHandler(seriesModel, api);
    },

    _initHandler: function (seriesModel, api) {
        var data = seriesModel.getData();
        var barMesh = this._barMesh;
        var isCartesian3D = seriesModel.coordinateSystem.type === 'cartesian3D';

        barMesh.seriesIndex = seriesModel.seriesIndex;

        var lastDataIndex = -1;
        barMesh.off('mousemove');
        barMesh.off('mouseout');
        barMesh.on('mousemove', function (e) {
            var dataIndex = barMesh.geometry.getDataIndexOfVertex(e.triangle[0]);
            if (dataIndex !== lastDataIndex) {
                this._downplay(lastDataIndex);
                this._highlight(dataIndex);
                this._labelsBuilder.updateLabels([dataIndex]);

                if (isCartesian3D) {
                    api.dispatchAction({
                        type: 'grid3DShowAxisPointer',
                        value: [data.get('x', dataIndex), data.get('y', dataIndex), data.get('z', dataIndex)]
                    });
                }
            }

            lastDataIndex = dataIndex;
            barMesh.dataIndex = dataIndex;
        }, this);
        barMesh.on('mouseout', function (e) {
            this._downplay(lastDataIndex);
            this._labelsBuilder.updateLabels();
            lastDataIndex = -1;
            barMesh.dataIndex = -1;

            if (isCartesian3D) {
                api.dispatchAction({
                    type: 'grid3DHideAxisPointer'
                });
            }
        }, this);
    },

    _highlight: function (dataIndex) {
        var data = this._data;
        if (!data) {
            return;
        }
        var barIndex = this._barIndexOfData[dataIndex];
        if (barIndex < 0) {
            return;
        }

        var itemModel = data.getItemModel(dataIndex);
        var emphasisItemStyleModel = itemModel.getModel('emphasis.itemStyle');
        var emphasisColor = emphasisItemStyleModel.get('color');
        var emphasisOpacity = emphasisItemStyleModel.get('opacity');
        if (emphasisColor == null) {
            var color = data.getItemVisual(dataIndex, 'color');
            emphasisColor = echarts.color.lift(color, -0.4);
        }
        if (emphasisOpacity == null) {
            emphasisOpacity = data.getItemVisual(dataIndex, 'opacity');
        }
        var colorArr = graphicGL.parseColor(emphasisColor);
        colorArr[3] *= emphasisOpacity;

        this._barMesh.geometry.setColor(barIndex, colorArr);

        this._api.getZr().refresh();
    },

    _downplay: function (dataIndex) {
        var data = this._data;
        if (!data) {
            return;
        }
        var barIndex = this._barIndexOfData[dataIndex];
        if (barIndex < 0) {
            return;
        }

        var color = data.getItemVisual(dataIndex, 'color');
        var opacity = data.getItemVisual(dataIndex, 'opacity');

        var colorArr = graphicGL.parseColor(color);
        colorArr[3] *= opacity;

        this._barMesh.geometry.setColor(barIndex, colorArr);

        this._api.getZr().refresh();
    },

    highlight: function (seriesModel, ecModel, api, payload) {
        this._toggleStatus('highlight', seriesModel, ecModel, api, payload);
    },

    downplay: function (seriesModel, ecModel, api, payload) {
        this._toggleStatus('downplay', seriesModel, ecModel, api, payload);
    },

    _toggleStatus: function (status, seriesModel, ecModel, api, payload) {
        var data = seriesModel.getData();
        var dataIndex = retrieve.queryDataIndex(data, payload);

        var self = this;
        if (dataIndex != null) {
            echarts.util.each(format.normalizeToArray(dataIndex), function (dataIdx) {
                status === 'highlight' ? this._highlight(dataIdx) : this._downplay(dataIdx);
            }, this);
        }
        else {
            data.each(function (dataIdx) {
                status === 'highlight' ? self._highlight(dataIdx) : self._downplay(dataIdx);
            });
        }
    },

    remove: function () {
        this.groupGL.removeAll();
    },

    dispose: function () {
        this.groupGL.removeAll();
    }
});<|endoftext|>