<commit_before>/**
 * The default templates for the shipped modules. The templates are organized according to the `Module.name` property.
 * @type {Object}
 */
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports['default'] = {
  _globals: {
    appName: 'Soundworks'
  },
  checkin: {
    wait: '...',
    labelPrefix: 'Go to',
    labelPostfix: 'Touch the screen
when you are ready.',
    error: 'Sorry, we cannot accept any more connections at the moment, please try again later.'
  },
  loader: {
    loading: 'Loading sounds…'
  },
  locator: {
    instructions: 'Define your position in the area',
    send: 'Send'
  },
  orientation: {
    instructions: 'Point the phone exactly in front of you, and touch the screen.'
  },
  placer: {
    instructions: 'Select your position',
    confirm: 'ok'
  },
  sync: {
    wait: 'Clock syncing, stand by…'
  },
  welcome: {
    welcome: 'Welcome to',
    touchScreen: 'Touch the screen to join!',
    errorIosVersion: 'This application requires at least iOS 7 with Safari or Chrome.',
    errorAndroidVersion: 'This application requires at least Android 4.2 with Chrome.',
    errorRequireMobile: 'This application is designed for iOS and Android mobile devices.',
    errorDefault: 'Sorry, the application cannot work properly on your device.'
  }
};
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9jbGllbnQvZGlzcGxheS9kZWZhdWx0VGV4dENvbnRlbnRzLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztxQkFJZTtBQUNiLFVBQVEsRUFBRTtBQUNSLFdBQU8sRUFBRSxZQUFZO0dBQ3RCO0FBQ0QsU0FBTyxFQUFFO0FBQ1AsUUFBSSxFQUFFLEtBQUs7QUFDWCxlQUFXLEVBQUUsT0FBTztBQUNwQixnQkFBWSxFQUFFLGlFQUFpRTtBQUMvRSxTQUFLLEVBQUUscUZBQXFGO0dBQzdGO0FBQ0QsUUFBTSxFQUFFO0FBQ04sV0FBTyxFQUFFLGlCQUFpQjtHQUMzQjtBQUNELFNBQU8sRUFBRTtBQUNQLGdCQUFZLEVBQUUsa0NBQWtDO0FBQ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9yIGlPUyBhbmQgQW5kcm9pZCBtb2JpbGUgZGV2aWNlcy4nLFxuICAgIGVycm9yRGVmYXVsdDogJ1NvcnJ5LCB0aGUgYXBwbGljYXRpb24gY2Fubm90IHdvcmsgcHJvcGVybHkgb24geW91ciBkZXZpY2UuJyxcbiAgfSxcbn07Il19<commit_msg>fixed sync<commit_after>/**
 * The default templates for the shipped modules. The templates are organized according to the `Module.name` property.
 * @type {Object}
 */
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports['default'] = {
  _globals: {
    appName: 'Soundworks'
  },
  checkin: {
    wait: '...',
    labelPrefix: 'Go to',
    labelPostfix: 'Touch the screen
when you are ready.',
    error: 'Sorry, we cannot accept any more connections at the moment, please try again later.'
  },
  loader: {
    loading: 'Loading sounds…'
  },
  locator: {
    instructions: 'Define your position in the area',
    send: 'Send'
  },
  orientation: {
    instructions: 'Point the phone exactly in front of you, and touch the screen.'
  },
  placer: {
    instructions: 'Select your position',
    confirm: 'ok'
  },
  sync: {
    wait: 'Clock syncing,
stand by…'
  },
  welcome: {
    welcome: 'Welcome to',
    touchScreen: 'Touch the screen to join!',
    errorIosVersion: 'This application requires at least iOS 7 with Safari or Chrome.',
    errorAndroidVersion: 'This application requires at least Android 4.2 with Chrome.',
    errorRequireMobile: 'This application is designed for iOS and Android mobile devices.',
    errorDefault: 'Sorry, the application cannot work properly on your device.'
  }
};
module.exports = exports['default'];
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInNyYy9jbGllbnQvZGlzcGxheS9kZWZhdWx0VGV4dENvbnRlbnRzLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztxQkFJZTtBQUNiLFVBQVEsRUFBRTtBQUNSLFdBQU8sRUFBRSxZQUFZO0dBQ3RCO0FBQ0QsU0FBTyxFQUFFO0FBQ1AsUUFBSSxFQUFFLEtBQUs7QUFDWCxlQUFXLEVBQUUsT0FBTztBQUN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ICAgIGVycm9yQW5kcm9pZFZlcnNpb246ICdUaGlzIGFwcGxpY2F0aW9uIHJlcXVpcmVzIGF0IGxlYXN0IEFuZHJvaWQgNC4yIHdpdGggQ2hyb21lLicsXG4gICAgZXJyb3JSZXF1aXJlTW9iaWxlOiAnVGhpcyBhcHBsaWNhdGlvbiBpcyBkZXNpZ25lZCBmb3IgaU9TIGFuZCBBbmRyb2lkIG1vYmlsZSBkZXZpY2VzLicsXG4gICAgZXJyb3JEZWZhdWx0OiAnU29ycnksIHRoZSBhcHBsaWNhdGlvbiBjYW5ub3Qgd29yayBwcm9wZXJseSBvbiB5b3VyIGRldmljZS4nLFxuICB9LFxufTtcbiJdfQ==<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

define([
    "httpmonitor/lib/trace",
    "httpmonitor/lib/object",
    "httpmonitor/lib/menu",
    "httpmonitor/lib/string",
    "httpmonitor/lib/events",
    "httpmonitor/base/module",
    "httpmonitor/chrome/chrome",
],
function(FBTrace, Obj, Menu, Str, Events, Module, Chrome) {

// ********************************************************************************************* //
// Module

/**
 * @module
 */
var TabListMenu = Obj.extend(Module,
/** @lends TabListMenu */
{
    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Initialization

    initialize: function()
    {
        Module.initialize.apply(this, arguments);

        this.updateUI();
    },

    shutdown: function()
    {
        Module.shutdown.apply(this, arguments);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // XUL Event Handlers

    onShowing: function(popup)
    {
        // Create temporary menu item.
        Menu.createMenuItem(popup, {
            nol10n: true,
            image: "chrome://httpmonitor/skin/loading_16.gif",
            label: "Fetching list of remote tabs...",
            disabled: true,
        });

        var self = this;

        // Context is not available at this moment, it's going to be created
        // by selecting a tab though this menu so, use the proxy from global
        // HttpMonitor (application) object.
        var proxy = top.HttpMonitor.proxy;

        proxy.getTabs(function(tabs)
        {
            self.clear(popup);

            // Populate the popup menu with entries (list of tab titles).
            for (var i=0; i<tabs.length; ++i)
            {
                var tab = tabs[i];
                var item = {
                    nol10n: true,
                    label: tab.label,
                    type: "radio",
                    checked: self.currentTab == tab.id,
                    command: self.selectTab.bind(self, tab)
                };
                Menu.createMenuItem(popup, item);
            }
        });

        // Yep, show the menu immediattely. Note that it can be populated asynchronously.
        return true;
    },

    onHidden: function(popup)
    {
        this.clear(popup);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // UI

    updateUI: function()
    {
        var menu = Chrome.$("httpMonitorTabListMenu");

        var label = "Select Tab";
        var context = Chrome.currentContext;
        var tab = context ? context.tab : null;
        if (tab)
            label = Str.cropString(tab.label, 100);

        menu.setAttribute("label", label + " ");
    },

    clear: function(popup)
    {
        while (popup.childNodes.length > 0)
            popup.removeChild(popup.lastChild);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Connection Listener

    onConnect: function()
    {
        this.updateUI();
    },

    onDisconnect: function()
    {
        this.updateUI();
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Commands

    selectTab: function(tab)
    {
        Events.dispatch(this.fbListeners, "onSelectTab", [tab]);
    },
});

// ********************************************************************************************* //
// Registration

Chrome.registerModule(TabListMenu);

return TabListMenu;

// ********************************************************************************************* //
});
<commit_msg>Hack fix for a chrome URL for loading graphic<commit_after>/* See license.txt for terms of usage */

define([
    "httpmonitor/lib/trace",
    "httpmonitor/lib/object",
    "httpmonitor/lib/menu",
    "httpmonitor/lib/string",
    "httpmonitor/lib/events",
    "httpmonitor/base/module",
    "httpmonitor/chrome/chrome",
],
function(FBTrace, Obj, Menu, Str, Events, Module, Chrome) {

// ********************************************************************************************* //
// Module

/**
 * @module
 */
var TabListMenu = Obj.extend(Module,
/** @lends TabListMenu */
{
    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Initialization

    initialize: function()
    {
        Module.initialize.apply(this, arguments);

        this.updateUI();
    },

    shutdown: function()
    {
        Module.shutdown.apply(this, arguments);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // XUL Event Handlers

    onShowing: function(popup)
    {
        // Create temporary menu item.
        Menu.createMenuItem(popup, {
            nol10n: true,
            image: "chrome://browser/skin/devtools/netmonitor-loading_16.gif",
            label: "Fetching list of remote tabs...",
            disabled: true,
        });

        var self = this;

        // Context is not available at this moment, it's going to be created
        // by selecting a tab though this menu so, use the proxy from global
        // HttpMonitor (application) object.
        var proxy = top.HttpMonitor.proxy;

        proxy.getTabs(function(tabs)
        {
            self.clear(popup);

            // Populate the popup menu with entries (list of tab titles).
            for (var i=0; i<tabs.length; ++i)
            {
                var tab = tabs[i];
                var item = {
                    nol10n: true,
                    label: tab.label,
                    type: "radio",
                    checked: self.currentTab == tab.id,
                    command: self.selectTab.bind(self, tab)
                };
                Menu.createMenuItem(popup, item);
            }
        });

        // Yep, show the menu immediattely. Note that it can be populated asynchronously.
        return true;
    },

    onHidden: function(popup)
    {
        this.clear(popup);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // UI

    updateUI: function()
    {
        var menu = Chrome.$("httpMonitorTabListMenu");

        var label = "Select Tab";
        var context = Chrome.currentContext;
        var tab = context ? context.tab : null;
        if (tab)
            label = Str.cropString(tab.label, 100);

        menu.setAttribute("label", label + " ");
    },

    clear: function(popup)
    {
        while (popup.childNodes.length > 0)
            popup.removeChild(popup.lastChild);
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Connection Listener

    onConnect: function()
    {
        this.updateUI();
    },

    onDisconnect: function()
    {
        this.updateUI();
    },

    // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
    // Commands

    selectTab: function(tab)
    {
        Events.dispatch(this.fbListeners, "onSelectTab", [tab]);
    },
});

// ********************************************************************************************* //
// Registration

Chrome.registerModule(TabListMenu);

return TabListMenu;

// ********************************************************************************************* //
});
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// sample-metadata:
//   title: Cloud Tasks Create HTTP Target
//   description: Create Cloud Tasks with a HTTP Target
//   usage: node createHttpTask.js <projectId> <queueName> <location> <url> <payload> <delayInSeconds>

/**
 * Create a task with an HTTP target for a given queue with an arbitrary payload.
 */
function main(
  project = 'my-project-id', // Your GCP Project id
  queue = 'my-appengine-queue', // Name of your Queue
  location = 'us-central1', // The GCP region of your queue
  url = 'https://example.com/taskhandler', // The full url path that the request will be sent to
  payload = 'Hello, World!', // The task HTTP request body
  inSeconds = 0 // Delay in task execution
) {
  // [START cloud_tasks_create_http_task]
  // Imports the Google Cloud Tasks library.
  const {CloudTasksClient} = require('@google-cloud/tasks');

  // Instantiates a client.
  const client = new CloudTasksClient();

  async function createHttpTask() {
    // TODO(developer): Uncomment these lines and replace with your values.
    // const project = 'my-project-id';
    // const queue = 'my-queue';
    // const location = 'us-central1';
    // const url = 'https://example.com/taskhandler';
    // const payload = 'Hello, World!';
    // const inSeconds = 180;

    // Construct the fully qualified queue name.
    const parent = client.queuePath(project, location, queue);

    const task = {
      httpRequest: {
        httpMethod: 'POST',
        url,
      },
    };

    if (payload) {
      task.httpRequest.body = Buffer.from(payload).toString('base64');
    }

    if (inSeconds) {
      // The time when the task is scheduled to be attempted.
      task.scheduleTime = {
        seconds: inSeconds + Date.now() / 1000,
      };
    }

    // Send create task request.
    console.log('Sending task:');
    console.log(task);
    const request = {parent: parent, task: task};
    const [response] = await client.createTask(request);
    console.log(`Created task ${response.name}`);
  }
  createHttpTask();
  // [END cloud_tasks_create_http_task]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});

main(...process.argv.slice(2));
<commit_msg>fix: wrapping param inSeconds with parseInt to ensure correct addition (#655)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// sample-metadata:
//   title: Cloud Tasks Create HTTP Target
//   description: Create Cloud Tasks with a HTTP Target
//   usage: node createHttpTask.js <projectId> <queueName> <location> <url> <payload> <delayInSeconds>

/**
 * Create a task with an HTTP target for a given queue with an arbitrary payload.
 */
function main(
  project = 'my-project-id', // Your GCP Project id
  queue = 'my-appengine-queue', // Name of your Queue
  location = 'us-central1', // The GCP region of your queue
  url = 'https://example.com/taskhandler', // The full url path that the request will be sent to
  payload = 'Hello, World!', // The task HTTP request body
  inSeconds = 0 // Delay in task execution
) {
  // [START cloud_tasks_create_http_task]
  // Imports the Google Cloud Tasks library.
  const {CloudTasksClient} = require('@google-cloud/tasks');

  // Instantiates a client.
  const client = new CloudTasksClient();

  async function createHttpTask() {
    // TODO(developer): Uncomment these lines and replace with your values.
    // const project = 'my-project-id';
    // const queue = 'my-queue';
    // const location = 'us-central1';
    // const url = 'https://example.com/taskhandler';
    // const payload = 'Hello, World!';
    // const inSeconds = 180;

    // Construct the fully qualified queue name.
    const parent = client.queuePath(project, location, queue);

    const task = {
      httpRequest: {
        httpMethod: 'POST',
        url,
      },
    };

    if (payload) {
      task.httpRequest.body = Buffer.from(payload).toString('base64');
    }

    if (inSeconds) {
      // The time when the task is scheduled to be attempted.
      task.scheduleTime = {
        seconds: parseInt(inSeconds) + Date.now() / 1000,
      };
    }

    // Send create task request.
    console.log('Sending task:');
    console.log(task);
    const request = {parent: parent, task: task};
    const [response] = await client.createTask(request);
    console.log(`Created task ${response.name}`);
  }
  createHttpTask();
  // [END cloud_tasks_create_http_task]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});

main(...process.argv.slice(2));
<|endoftext|>


<commit_before>'use strict';

var servers = {
	localHub: 'https://local.xena.ucsc.edu:7223',
	publicHub: 'https://ucscpublic.xenahubs.net',
	tcgaHub: 'https://tcga.xenahubs.net',
	icgcHub: 'https://icgc.xenahubs.net',
	toilHub: 'https://toil.xenahubs.net',
	pcawgHub: 'https://pcawg.xenahubs.net',
	singlecellHub: 'https://singlecell.xenahubs.net',
	pancanAtlasHub: 'https://pancanatlas.xenahubs.net',
	treehouseHub: 'https://xena.treehouse.gi.ucsc.edu',
	gdcHub: "https://gdc.xenahubs.net"
};

module.exports = {
	servers,
	serverNames: {
		[servers.localHub]: "My computer hub",
		[servers.publicHub]: 'UCSC public hub',
		[servers.tcgaHub]: 'TCGA hub',
		[servers.icgcHub]: 'ICGC hub',
		[servers.toilHub]: 'GA4GH (TOIL) hub',
		[servers.pcawgHub]: 'PCAWG public hub',
		[servers.singlecellHub]: 'Single-cell RNAseq hub',
		[servers.pancanAtlasHub]: 'Pan-Cancer Atlas Hub',
		[servers.treehouseHub]: 'Treehouse Hub',
		[servers.gdcHub]: 'GDC Hub'
	},
	defaultServers: [
		servers.localHub,
		servers.publicHub,
		servers.tcgaHub,
		servers.pancanAtlasHub,
		servers.icgcHub,
		servers.toilHub,
		servers.treehouseHub,
		servers.gdcHub
	],
	publicServers: [
		servers.publicHub,
		servers.tcgaHub,
		servers.icgcHub,
		servers.toilHub,
		servers.pancanAtlasHub,
		servers.pcawgHub,
		servers.treehouseHub,
		servers.gdcHub
	]
};
<commit_msg>toil hub label change<commit_after>'use strict';

var servers = {
	localHub: 'https://local.xena.ucsc.edu:7223',
	publicHub: 'https://ucscpublic.xenahubs.net',
	tcgaHub: 'https://tcga.xenahubs.net',
	icgcHub: 'https://icgc.xenahubs.net',
	toilHub: 'https://toil.xenahubs.net',
	pcawgHub: 'https://pcawg.xenahubs.net',
	singlecellHub: 'https://singlecell.xenahubs.net',
	pancanAtlasHub: 'https://pancanatlas.xenahubs.net',
	treehouseHub: 'https://xena.treehouse.gi.ucsc.edu',
	gdcHub: "https://gdc.xenahubs.net"
};

module.exports = {
	servers,
	serverNames: {
		[servers.localHub]: "My computer hub",
		[servers.publicHub]: 'UCSC public hub',
		[servers.tcgaHub]: 'TCGA hub',
		[servers.icgcHub]: 'ICGC hub',
		[servers.toilHub]: 'UCSC Toil RNAseq Recompute',
		[servers.pcawgHub]: 'PCAWG public hub',
		[servers.singlecellHub]: 'Single-cell RNAseq hub',
		[servers.pancanAtlasHub]: 'Pan-Cancer Atlas Hub',
		[servers.treehouseHub]: 'Treehouse Hub',
		[servers.gdcHub]: 'GDC Hub'
	},
	defaultServers: [
		servers.localHub,
		servers.publicHub,
		servers.tcgaHub,
		servers.pancanAtlasHub,
		servers.icgcHub,
		servers.toilHub,
		servers.treehouseHub,
		servers.gdcHub
	],
	publicServers: [
		servers.publicHub,
		servers.tcgaHub,
		servers.icgcHub,
		servers.toilHub,
		servers.pancanAtlasHub,
		servers.pcawgHub,
		servers.treehouseHub,
		servers.gdcHub
	]
};
<|endoftext|>


<commit_before>var meshCommon = function() {
	var meshCommon = {};
	//IMPORTANT! Before you call any of these functions, run this function on your blocks array!
	//This makes it so all empty blocks become AIR, I found this makes the
	//greedy mesher about 20% faster (even with the preprocessing).
	meshCommon.preprocessBlocks = function (blocks) {
		for (var index = 0; index < blocks.length; index++) {
			if (Block.isInvisible(blocks[index])) {
				blocks[index] = Block.AIR;
			}
		}
	}

	//The order is important here! It makes sure the normals line up with the 'face numbers' given
	//by Block.getColors.
	meshCommon.LOOP_CUBEFACES_DATA = [
		{faceDirection: 1,  compX: 1, compY: 2, compZ: 0},
		{faceDirection: -1, compX: 1, compY: 2, compZ: 0},
		{faceDirection: 1,  compX: 2, compY: 0, compZ: 1},
		{faceDirection: -1, compX: 2, compY: 0, compZ: 1},
		{faceDirection: 1,  compX: 0, compY: 1, compZ: 2},
		{faceDirection: -1, compX: 0, compY: 1, compZ: 2}
	];

	function noiseFunc(bcX, bcY, bcZ, voxelization) {
		function n(q) {
			return perlinNoise(Math.abs(bcX) / q, Math.abs(bcY) / q, Math.abs(bcZ) / q);
		}
		var val = n(8) + n(32);
		if (abs(voxelization - 4) > 0.001) val += n(4);
		if (abs(voxelization - 2) > 0.001) val += n(2);
		return clamp(val / 2 + 0.5, 0.0, 1.0);
	}

	meshCommon.getVoxelatedBlockType = function(ocXStart, ocYStart, ocZStart, voxelization, blocks) {
		if(voxelization == 1) {
			return blocks[
						ocXStart * CHUNK_WIDTH * CHUNK_HEIGHT +
						ocYStart * CHUNK_WIDTH +
						ocZStart
					];
		}

		//Ugh... have to sample to find the block
		var blockCounts = [];

		//If we wanted to allow for say, voxelization of 3 (meaning the edges
		//are different size) this would be where we would do part of it... it would
		//make the chunk boundaries look bad though.

		var ocXEnd = ocXStart + voxelization;
		var ocYEnd = ocYStart + voxelization;
		var ocZEnd = ocZStart + voxelization;

		for (var ocX = ocXStart; ocX < ocXEnd; ocX++) {
			for (var ocY = ocYStart; ocY < ocYEnd; ocY++) {
				for (var ocZ = ocZStart; ocZ < ocZEnd; ocZ++) {
					var sampleBlockType = blocks[
							ocX * CHUNK_WIDTH * CHUNK_HEIGHT +
							ocY * CHUNK_WIDTH +
							ocZ
						];
					if (!blockCounts[sampleBlockType]) {
						blockCounts[sampleBlockType] = 0;
					}
					blockCounts[sampleBlockType]++;
				}
			}
		}

		//We make our block the most common block, excluding non-solid blocks.
		//However if we are all air, then we do become air (really we just don't
		//render).
		var maxCount = 0;
		var planeBlock = Block.AIR; //Eh... slightly different than simpleMesher, but will result in the same thing.

		for(var blockType = 0; blockType < blockCounts.length; blockType++) {
			var blockCount = blockCounts[blockType];
			if (blockCount > maxCount && blockType != Block.AIR) {
				maxCount = blockCount;
				planeBlock = blockType;
			}
		}

		return planeBlock;
	}

	meshCommon.getNeighbourBlockType = function(ocXStart, ocYStart, ocZStart, blocks, neighbourComp, voxelization) {
		var sampleSizeArr = [voxelization, voxelization, voxelization];
		sampleSizeArr[neighbourComp] = 1;
		for (var ocX = ocXStart; ocX < sampleSizeArr[0] + ocXStart; ocX++) {
			for (var ocY = ocYStart; ocY < sampleSizeArr[1] + ocYStart; ocY++) {
				for (var ocZ = ocZStart; ocZ < sampleSizeArr[2] + ocZStart; ocZ++) {
					var adjBlock = blocks[
							ocX * CHUNK_WIDTH * CHUNK_HEIGHT +
							ocY * CHUNK_WIDTH +
							ocZ];
					if (adjBlock == Block.AIR) {
						return Block.AIR;
					}
				}
			}
		}
		return Block.DIRT; //Any solid would do
	}

	//ocArr is an in/out, if it is beyond the bounds of the cc chunk, a neighbour chunk's data
	//  is returned and oc is modified to be relative to that.
	//compZ is the dimension in ocArr we should check.
	//Assumes ocArr is only 1 off, which makes it easier for greedyMesher.
	//Returns null if the chunk does not exist
	var chunkDims = [CHUNK_WIDTH, CHUNK_HEIGHT, CHUNK_DEPTH];
	meshCommon.getBlockData = function(manager, blocks, ccArr, ocArr, compZ) {
		var ccDirection = 0;
		if (ocArr[compZ] < 0) {
			ocArr[compZ] = chunkDims[compZ] - 1;
			ccDirection = -1;
		}
		else if (ocArr[compZ] >= chunkDims[compZ]) {
			ocArr[compZ] = 0;
			ccDirection = +1;
		} else {
			return blocks;
		}

		ccArr[compZ] += ccDirection;
		var neighbourChunk = manager.chunkAt(ccArr[0], ccArr[1], ccArr[2]);
		ccArr[compZ] -= ccDirection;

		if(!neighbourChunk) return null;

		return neighbourChunk.blocks;
	}

	meshCommon.addQuad = function(bcX, bcY, bcZ, quadWidth, quadHeight, compZ, faceDirection, voxelization, verts) {
		//The face direction is always right-hand rule, so we place the vertices accordingly
		var counterClockwise = [
				[0, 0],
				[1, 0],
				[1, 1],
				[0, 1],
				[0.5, 0.5]
			];
		var clockwise = [
				[0, 0],
				[0, 1],
				[1, 1],
				[1, 0],
				[0.5, 0.5]
			];
		var offsetArray = faceDirection == 1 ? counterClockwise : clockwise;

		var bcVerts = [bcX, bcY, bcZ];

		if (faceDirection == 1) {
			bcVerts[compZ] += voxelization;
		}

		for (var iVertex = 0; iVertex < offsetArray.length; iVertex++) {
			var offsets = offsetArray[iVertex];

			bcVerts[(compZ + 1) % 3] += quadWidth * offsets[0];
			bcVerts[(compZ + 2) % 3] += quadHeight * offsets[1];

			verts.push(bcVerts[0], bcVerts[1], bcVerts[2]);

			bcVerts[(compZ + 1) % 3] -= quadWidth * offsets[0];
			bcVerts[(compZ + 2) % 3] -= quadHeight * offsets[1];
		}
	}

	//This is the function which most meshers should call to create their return structure.

	//Takes:
	//var verts = []; //Each vertice is made of 3 integers (3D point)
	//var blockTypes = []; //1 per face, which is has 5 points, so 15 verts
	//var faceNumbers = []; //same a blockTypes in size
	//var indexes = []; //indexes for triangles of points in verts
	meshCommon.generateGeometry = function(verts, blockTypes, faceNumbers, indexes, voxelization) {
		function copy(src, dst) {
			for (var i = 0; i < src.length; i++) {
				dst[i] = src[i];
			}
		}

		var vertsa = new Float32Array(verts.length);
		copy(verts, vertsa);

		//Bunch of squares, point in each corner and one in the middle
		//Each point is made up of 3 numbers
		for(var iVert = 0; iVert < verts.length / 3; iVert += 5) {
			indexes.push(iVert, iVert + 1, iVert + 4);
			indexes.push(iVert + 1, iVert + 2, iVert + 4);
			indexes.push(iVert + 2, iVert + 3, iVert + 4);
			indexes.push(iVert + 3, iVert, iVert + 4);
		}

		var color = [];

		for(var iFace = 0; iFace < verts.length / 15; iFace++) {
			var iVertexStart = iFace * 15;
			var blockType = blockTypes[iFace];
			var faceNumber = faceNumbers[iFace];

			var colours = Block.getColours(blockType, faceNumber);
			var c = colours.light;
			var c2 = colours.dark;

			for(var iVertex = 0; iVertex < 5; iVertex++) {
				var iVS = iVertexStart;
				var noise = noiseFunc(verts[iVS], verts[iVS + 1], verts[iVS + 2], voxelization);

				var r = c.r*noise + c2.r*(1 - noise);
				var g = c.g*noise + c2.g*(1 - noise);
				var b = c.b*noise + c2.b*(1 - noise);
				color.push(r/255, g/255, b/255);

				iVertexStart += 3;
			}
		}

		var indexa = new Uint16Array(indexes.length);
		copy(indexes, indexa);

		var colora = new Float32Array(color.length);
		copy(color, colora);

		var attributes = {
			position: { //x, y, z (triangles)
				itemSize: 3,
				array: vertsa,
				numItems: verts.length,
			},
			index: {    //triangle indices inside position (so *3 for real index), every 3 make up a triangle.
				itemSize: 1,
				array: indexa,
				numItems: indexes.length,
			},
			color: {    //colors of positions (vertices), we use a vertex shader
						//(possibly a built in one) to color the faces based on these.
				itemSize: 3,
				array: colora,
				numItems: color.length,
			},
		};
		var offsets = [{ //Just states the indexes used, you could theoretically have multiple of these?
			start: 0,
			count: indexes.length,
			index: 0,
		}];

		return {
			attributes: attributes,
			offsets: offsets,
			transferables: [vertsa.buffer, indexa.buffer, colora.buffer],
		};
	}

	return meshCommon;
}();<commit_msg>Cleaned up some inconsistent array length references.<commit_after>var meshCommon = function() {
	var meshCommon = {};
	//IMPORTANT! Before you call any of these functions, run this function on your blocks array!
	//This makes it so all empty blocks become AIR, I found this makes the
	//greedy mesher about 20% faster (even with the preprocessing).
	meshCommon.preprocessBlocks = function (blocks) {
		for (var index = 0; index < blocks.length; index++) {
			if (Block.isInvisible(blocks[index])) {
				blocks[index] = Block.AIR;
			}
		}
	}

	//The order is important here! It makes sure the normals line up with the 'face numbers' given
	//by Block.getColors.
	meshCommon.LOOP_CUBEFACES_DATA = [
		{faceDirection: 1,  compX: 1, compY: 2, compZ: 0},
		{faceDirection: -1, compX: 1, compY: 2, compZ: 0},
		{faceDirection: 1,  compX: 2, compY: 0, compZ: 1},
		{faceDirection: -1, compX: 2, compY: 0, compZ: 1},
		{faceDirection: 1,  compX: 0, compY: 1, compZ: 2},
		{faceDirection: -1, compX: 0, compY: 1, compZ: 2}
	];

	function noiseFunc(bcX, bcY, bcZ, voxelization) {
		function n(q) {
			return perlinNoise(Math.abs(bcX) / q, Math.abs(bcY) / q, Math.abs(bcZ) / q);
		}
		var val = n(8) + n(32);
		if (abs(voxelization - 4) > 0.001) val += n(4);
		if (abs(voxelization - 2) > 0.001) val += n(2);
		return clamp(val / 2 + 0.5, 0.0, 1.0);
	}

	meshCommon.getVoxelatedBlockType = function(ocXStart, ocYStart, ocZStart, voxelization, blocks) {
		if(voxelization == 1) {
			return blocks[
						ocXStart * CHUNK_WIDTH * CHUNK_HEIGHT +
						ocYStart * CHUNK_WIDTH +
						ocZStart
					];
		}

		//Ugh... have to sample to find the block
		var blockCounts = [];

		//If we wanted to allow for say, voxelization of 3 (meaning the edges
		//are different size) this would be where we would do part of it... it would
		//make the chunk boundaries look bad though.

		var ocXEnd = ocXStart + voxelization;
		var ocYEnd = ocYStart + voxelization;
		var ocZEnd = ocZStart + voxelization;

		for (var ocX = ocXStart; ocX < ocXEnd; ocX++) {
			for (var ocY = ocYStart; ocY < ocYEnd; ocY++) {
				for (var ocZ = ocZStart; ocZ < ocZEnd; ocZ++) {
					var sampleBlockType = blocks[
							ocX * CHUNK_WIDTH * CHUNK_HEIGHT +
							ocY * CHUNK_WIDTH +
							ocZ
						];
					if (!blockCounts[sampleBlockType]) {
						blockCounts[sampleBlockType] = 0;
					}
					blockCounts[sampleBlockType]++;
				}
			}
		}

		//We make our block the most common block, excluding non-solid blocks.
		//However if we are all air, then we do become air (really we just don't
		//render).
		var maxCount = 0;
		var planeBlock = Block.AIR; //Eh... slightly different than simpleMesher, but will result in the same thing.

		for(var blockType = 0; blockType < blockCounts.length; blockType++) {
			var blockCount = blockCounts[blockType];
			if (blockCount > maxCount && blockType != Block.AIR) {
				maxCount = blockCount;
				planeBlock = blockType;
			}
		}

		return planeBlock;
	}

	meshCommon.getNeighbourBlockType = function(ocXStart, ocYStart, ocZStart, blocks, neighbourComp, voxelization) {
		var sampleSizeArr = [voxelization, voxelization, voxelization];
		sampleSizeArr[neighbourComp] = 1;
		for (var ocX = ocXStart; ocX < sampleSizeArr[0] + ocXStart; ocX++) {
			for (var ocY = ocYStart; ocY < sampleSizeArr[1] + ocYStart; ocY++) {
				for (var ocZ = ocZStart; ocZ < sampleSizeArr[2] + ocZStart; ocZ++) {
					var adjBlock = blocks[
							ocX * CHUNK_WIDTH * CHUNK_HEIGHT +
							ocY * CHUNK_WIDTH +
							ocZ];
					if (adjBlock == Block.AIR) {
						return Block.AIR;
					}
				}
			}
		}
		return Block.DIRT; //Any solid would do
	}

	//ocArr is an in/out, if it is beyond the bounds of the cc chunk, a neighbour chunk's data
	//  is returned and oc is modified to be relative to that.
	//compZ is the dimension in ocArr we should check.
	//Assumes ocArr is only 1 off, which makes it easier for greedyMesher.
	//Returns null if the chunk does not exist
	var chunkDims = [CHUNK_WIDTH, CHUNK_HEIGHT, CHUNK_DEPTH];
	meshCommon.getBlockData = function(manager, blocks, ccArr, ocArr, compZ) {
		var ccDirection = 0;
		if (ocArr[compZ] < 0) {
			ocArr[compZ] = chunkDims[compZ] - 1;
			ccDirection = -1;
		}
		else if (ocArr[compZ] >= chunkDims[compZ]) {
			ocArr[compZ] = 0;
			ccDirection = +1;
		} else {
			return blocks;
		}

		ccArr[compZ] += ccDirection;
		var neighbourChunk = manager.chunkAt(ccArr[0], ccArr[1], ccArr[2]);
		ccArr[compZ] -= ccDirection;

		if(!neighbourChunk) return null;

		return neighbourChunk.blocks;
	}

	meshCommon.addQuad = function(bcX, bcY, bcZ, quadWidth, quadHeight, compZ, faceDirection, voxelization, verts) {
		//The face direction is always right-hand rule, so we place the vertices accordingly
		var counterClockwise = [
				[0, 0],
				[1, 0],
				[1, 1],
				[0, 1],
				[0.5, 0.5]
			];
		var clockwise = [
				[0, 0],
				[0, 1],
				[1, 1],
				[1, 0],
				[0.5, 0.5]
			];
		var offsetArray = faceDirection == 1 ? counterClockwise : clockwise;

		var bcVerts = [bcX, bcY, bcZ];

		if (faceDirection == 1) {
			bcVerts[compZ] += voxelization;
		}

		for (var iVertex = 0; iVertex < offsetArray.length; iVertex++) {
			var offsets = offsetArray[iVertex];

			bcVerts[(compZ + 1) % 3] += quadWidth * offsets[0];
			bcVerts[(compZ + 2) % 3] += quadHeight * offsets[1];

			verts.push(bcVerts[0], bcVerts[1], bcVerts[2]);

			bcVerts[(compZ + 1) % 3] -= quadWidth * offsets[0];
			bcVerts[(compZ + 2) % 3] -= quadHeight * offsets[1];
		}
	}

	//This is the function which most meshers should call to create their return structure.

	//Takes:
	//var verts = []; //Each vertice is made of 3 integers (3D point)
	//var blockTypes = []; //1 per face, which is has 5 points, so 15 verts
	//var faceNumbers = []; //same a blockTypes in size
	//var indexes = []; //indexes for triangles of points in verts
	meshCommon.generateGeometry = function(verts, blockTypes, faceNumbers, indexes, voxelization) {
		function copy(src, dst) {
			for (var i = 0; i < src.length; i++) {
				dst[i] = src[i];
			}
		}

		var vertsa = new Float32Array(verts.length);
		copy(verts, vertsa);

		//Bunch of squares, point in each corner and one in the middle
		//Each point is made up of 3 numbers
		for(var iVert = 0; iVert < verts.length / 3; iVert += 5) {
			indexes.push(iVert, iVert + 1, iVert + 4);
			indexes.push(iVert + 1, iVert + 2, iVert + 4);
			indexes.push(iVert + 2, iVert + 3, iVert + 4);
			indexes.push(iVert + 3, iVert, iVert + 4);
		}

		var color = [];

		for(var iFace = 0; iFace < verts.length / 15; iFace++) {
			var iVertexStart = iFace * 15;
			var blockType = blockTypes[iFace];
			var faceNumber = faceNumbers[iFace];

			var colours = Block.getColours(blockType, faceNumber);
			var c = colours.light;
			var c2 = colours.dark;

			for(var iVertex = 0; iVertex < 5; iVertex++) {
				var iVS = iVertexStart;
				var noise = noiseFunc(verts[iVS], verts[iVS + 1], verts[iVS + 2], voxelization);

				var r = c.r*noise + c2.r*(1 - noise);
				var g = c.g*noise + c2.g*(1 - noise);
				var b = c.b*noise + c2.b*(1 - noise);
				color.push(r/255, g/255, b/255);

				iVertexStart += 3;
			}
		}

		var indexa = new Uint16Array(indexes.length);
		copy(indexes, indexa);

		var colora = new Float32Array(color.length);
		copy(color, colora);

		var attributes = {
			position: { //x, y, z (triangles)
				itemSize: 3,
				array: vertsa,
				numItems: vertsa.length,
			},
			index: {    //triangle indices inside position (so *3 for real index), every 3 make up a triangle.
				itemSize: 1,
				array: indexa,
				numItems: indexa.length,
			},
			color: {    //colors of positions (vertices), we use a vertex shader
						//(possibly a built in one) to color the faces based on these.
				itemSize: 3,
				array: colora,
				numItems: colora.length,
			},
		};
		var offsets = [{ //Just states the indexes used, you could theoretically have multiple of these?
			start: 0,
			count: indexes.length,
			index: 0,
		}];

		return {
			attributes: attributes,
			offsets: offsets,
			transferables: [vertsa.buffer, indexa.buffer, colora.buffer],
		};
	}

	return meshCommon;
}();<|endoftext|>


<commit_before>var card_width = 300;
var card_height = 186;
var half_card_width = card_width / 2;
var half_card_height = card_height / 2;

var next_outgoing_i = 0; /* the index of the next node that's outgoing */
var next_incoming_i = 0;

/* Which card is currently displayed in the middle of the screen? */
var current_card = null;

/* Height of rendered graph */
var graph_height = null;
var min_graph_height = 808;

var nodes = [];
var cards = [];
var relations = []; // relations are between nodes
var links = []; // links are between cards

var nodes = [];
var relations = [];

function indexOfNode(node_id) {
    for (i = 0; i < nodes.length; i++) {
        if (nodes[i].id === node_id) {
            return i;
        }
    }
    return -1; // not found
}

function indexOfRelation(relation_id) {
    for (i = 0; i < relations.length; i++) {
        if (relations[i].id === relation_id) {
            return i;
        }
    }
    return -1; // not found
}

function set_incoming_and_outgoing(relation) {
    if (get_other_id(relation) === null) {
        relation.from.outgoing.push(relation.to);
        relation.to.incoming.push(relation.from);
    }
}

function set_relation_id(relation, node) {
    if (relation.from === node.id) {
        relation.from = node;
    } else if (relation.to === node.id) {
        relation.to = node;
    } else {
        console.log("Uh oh, node " + node.id + " not found for relation " + relation.id);
    }

    set_incoming_and_outgoing(relation);
}

function get_other_id(relation) {
    // call this after calling "set_relation_id"
    if (typeof relation.from === 'number') {
        return relation.from;
    } else if (typeof relation.to === 'number') {
        return relation.to;
    } else {
        return null;
    }
}

function ajax_get_node(node_id, callback) {
    // if node already exists, DON'T evenn call this function!
    // mock ajax function for now
    $.ajax({
        url: "mock_ajax/" + node_id + ".json",
        type: "GET",
        dataType: "json",
    }).done(function (data) {
        data.incoming = [];
        data.outgoing = [];
        nodes.push(data);
        if (typeof callback !== 'undefined') {
            callback(data);
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("Failed to get node " + node_id + ": " + errorThrown);
    });
}

function ajax_get_relation_nodes_function(new_relation, existing_node) {
    // http://stackoverflow.com/a/750506/257583
    return function () {
        if (indexOfRelation(new_relation.id) === -1) { // it's a new relation
            set_relation_id(new_relation, existing_node);
            var missing_id = get_other_id(new_relation);
            var missing_index = indexOfNode(missing_id);
            if (missing_index === -1) { // node is currently missing
                ajax_get_node(missing_id, function (new_node) {
                    set_relation_id(new_relation, new_node);
                    relations.push(new_relation);
                    draw_graph();
                })
            } else { // node already exists, just use it
                set_relation_id(new_relation, nodes[missing_index]);
                relations.push(new_relation);
            }
        }
    }
}

function ajax_get_relations_of(node, callback) {
    // get relations and make sure that nodes for relations get fetched as well
    // mock ajax function for now
    $.ajax({
        url: "mock_ajax/arg_" + node.id + "_relations.json",
        type: "GET",
        dataType: "json",
    }).done(function (data) {
        ajax_relation_nodes_functions = []
        for (var i = 0; i < data.length; i++) {
            ajax_relation_nodes_functions.push(ajax_get_relation_nodes_function(data[i], node));
        }
        for (var i = 0; i < ajax_relation_nodes_functions.length; i++) {
            ajax_relation_nodes_functions[i]();
        }
        if (typeof callback !== 'undefined') {
            callback(data);
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("Failed to get relations of node " + node.id + ": " + errorThrown);
    });
}

function ajax_get_card(node) {
    ajax_get_relations_of(node, function (relations) {
        draw_graph();
    });
}

function is_outgoing(node) {
    return current_card.outgoing.indexOf(node) != -1;
}

function is_incoming(node) {
    return current_card.incoming.indexOf(node) != -1;
}

function node_visible(node) {
    return (node == current_card) || is_outgoing(node) || is_incoming(node);
}

function link_visible(link) {
    // both ends of a link must be visible for a link to be visible
    return node_visible(link.from) && node_visible(link.to);
}

function x_pos(node) {
    if (node == current_card) {
        node.i = 0; // doesn't matter for current_card
        return (window.innerWidth / 2) - half_card_width;
    } else if (is_outgoing(node)) {
        if (node.i == null) {
            node.i = next_outgoing_i;
            next_outgoing_i++;
        }
        return node.i * (card_width + 10) + 10;
    } else if (is_incoming(node)) {
        if (node.i == null) {
            node.i = next_incoming_i;
            next_incoming_i++;
        }
        return node.i * (card_width + 10) + 10;
    } else {
        if (node.previously_current) {
            return window.innerWidth + 10;
        } else if (node.previously_outgoing || node.previously_incoming) {
            return (window.innerWidth / 2) - half_card_width;
        }
    }
}

function y_pos(node) {
    if (node == current_card) {
        return (graph_height / 2) - half_card_height;
    } else if (is_outgoing(node)) {
        return 10;
    } else if (is_incoming(node)) {
        return graph_height - 10 - card_height;
    } else {
        if (node.previously_current) {
            return (graph_height / 2) - half_card_height;
        } else if (node.previously_outgoing) {
            return -10 - card_height;
        } else if (node.previously_incoming) {
            return graph_height + 10;
        } else {
            console.log(node);
        }
    }
}

function pos2str(pos) {
    return pos[0] + "," + pos[1] + " ";
}

function compute_link_bezier_curve(link) {
    var from = link.from;
    var to = link.to;
    var start_pos = [x_pos(from, from.i) + half_card_width, y_pos(from, from.i)];
    var end_pos = [x_pos(to, to.i) + half_card_width,
                    /* marker-widht is 3, stroke-width is 5 */
                   y_pos(to, to.i) + card_height + (5 * 3)];
    var height = end_pos[1] - start_pos[1];
    var control1 = [start_pos[0], start_pos[1] + (height / 2)];
    var control2 = [end_pos[0], end_pos[1] - (height / 2)];
    return "M" + pos2str(start_pos) + "C" + pos2str(control1)
            + pos2str(control2) + pos2str(end_pos);
}

function reset_globals() {
    for (var i=0; i < nodes.length; i++) {
        node = nodes[i];
        node.i = null;
    }
    next_outgoing_i = 0;
    next_incoming_i = 0;
}

function make_cards() {
    var svg = d3.select("svg#graph");
    cards = svg.selectAll("g").data(nodes);
    new_cards = cards.enter().append("g").classed("argument", true);
    new_cards.append("rect").attr("width", card_width).attr("height", card_height)
                .style("opacity", 0);
    var switch_objects = new_cards.append("switch");
    switch_objects.append("foreignObject").classed("foreign-object", true)
            .attr("requiredFeatures", "http://www.w3.org/TR/SVG11/feature#Extensibility")
            .attr("width", card_width).attr("height", card_height)
            .append("xhtml:div").classed("summary", true).append("p")
            .classed("summary", true).text(function (d) {
                return d.summary;
            }).attr("xmlns", "http://www.w3.org/1999/xhtml");
    switch_objects.append("text").attr("x", 100).attr("y", 100)
        .text("Sorry, your browser is not currently supported.");
    new_cards.on("click", function (d) {
        current_card = d;
        ajax_get_card(d);
        draw_graph();
    })
}

function make_links() {
    var svg = d3.select("svg#graph");
    links = svg.selectAll("path").data(relations);
    links.enter().append("path")
        .attr("class", function(d) {
            return d.type;
        }).attr("marker-end", function(d) {
            return "url(#arrow-" + d.type + ")";
        }).style("opacity", 0);
}

function draw_graph() {
    reset_globals();
    make_cards();
    make_links();

    var svg = d3.select("svg#graph");
    d3.selectAll("g rect").transition().duration(500)
        .attr("x", x_pos).attr("y", y_pos).style("opacity", 1);
    // http://stackoverflow.com/a/11743721/257583
    // also, doesn't matter if the text is opaque or not since it's the same color as the background
    d3.selectAll(".foreign-object").transition().duration(500).attr("x", x_pos).attr("y", y_pos);
    cards.each(function (d) {
        if (current_card == d) {
            d.previously_current = true;
            d.previously_outgoing = false;
            d.previously_incoming = false;
        } else if (is_outgoing(d)) {
            d.previously_current = false;
            d.previously_outgoing = true;
            d.previously_incoming = false;
        } else if (is_incoming(d)) {
            d.previously_current = false;
            d.previously_outgoing = false;
            d.previously_incoming = true;
        } // else shouldn't happen
    });
    links.transition().duration(500).style("opacity", function (d) {
        // if one end of the link is currently displayed, then the other is too
        if (link_visible(d)) {
            return 1;
        } else {
            return 0;
        }
    }).attr("d", compute_link_bezier_curve);
}

window.onload = function () {
    if ($("#graph").height() < min_graph_height) {
        alert("Whoops, looks like some things won't be displaying correctly. Please tell us about this.");
    }
    graph_height = $("#graph").height();
    ajax_get_node(2, function (data) {
        current_card = data;
        draw_graph();

        ajax_get_relations_of(nodes[0], function (data) {
            draw_graph();
        })
    })

    draw_graph();
}<commit_msg>Added ability to drag top row around<commit_after>var card_width = 300;
var card_height = 186;
var half_card_width = card_width / 2;
var half_card_height = card_height / 2;

var next_outgoing_i = 0; /* the index of the next node that's outgoing */
var next_incoming_i = 0;

/* Which card is currently displayed in the middle of the screen? */
var current_card = null;

/* Height of rendered graph */
var graph_height = null;
var min_graph_height = 808;

// scrolling
var top_row_offset = 0;
var bottom_row_offset = 0;

var nodes = [];
var cards = [];
var relations = []; // relations are between nodes
var links = []; // links are between cards

var nodes = [];
var relations = [];

function indexOfNode(node_id) {
    for (i = 0; i < nodes.length; i++) {
        if (nodes[i].id === node_id) {
            return i;
        }
    }
    return -1; // not found
}

function indexOfRelation(relation_id) {
    for (i = 0; i < relations.length; i++) {
        if (relations[i].id === relation_id) {
            return i;
        }
    }
    return -1; // not found
}

function set_incoming_and_outgoing(relation) {
    if (get_other_id(relation) === null) {
        relation.from.outgoing.push(relation.to);
        relation.to.incoming.push(relation.from);
    }
}

function set_relation_id(relation, node) {
    if (relation.from === node.id) {
        relation.from = node;
    } else if (relation.to === node.id) {
        relation.to = node;
    } else {
        console.log("Uh oh, node " + node.id + " not found for relation " + relation.id);
    }

    set_incoming_and_outgoing(relation);
}

function get_other_id(relation) {
    // call this after calling "set_relation_id"
    if (typeof relation.from === 'number') {
        return relation.from;
    } else if (typeof relation.to === 'number') {
        return relation.to;
    } else {
        return null;
    }
}

function ajax_get_node(node_id, callback) {
    // if node already exists, DON'T evenn call this function!
    // mock ajax function for now
    $.ajax({
        url: "mock_ajax/" + node_id + ".json",
        type: "GET",
        dataType: "json",
    }).done(function (data) {
        data.incoming = [];
        data.outgoing = [];
        nodes.push(data);
        if (typeof callback !== 'undefined') {
            callback(data);
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("Failed to get node " + node_id + ": " + errorThrown);
    });
}

function ajax_get_relation_nodes_function(new_relation, existing_node) {
    // http://stackoverflow.com/a/750506/257583
    return function () {
        if (indexOfRelation(new_relation.id) === -1) { // it's a new relation
            set_relation_id(new_relation, existing_node);
            var missing_id = get_other_id(new_relation);
            var missing_index = indexOfNode(missing_id);
            if (missing_index === -1) { // node is currently missing
                ajax_get_node(missing_id, function (new_node) {
                    set_relation_id(new_relation, new_node);
                    relations.push(new_relation);
                    draw_graph();
                })
            } else { // node already exists, just use it
                set_relation_id(new_relation, nodes[missing_index]);
                relations.push(new_relation);
            }
        }
    }
}

function ajax_get_relations_of(node, callback) {
    // get relations and make sure that nodes for relations get fetched as well
    // mock ajax function for now
    $.ajax({
        url: "mock_ajax/arg_" + node.id + "_relations.json",
        type: "GET",
        dataType: "json",
    }).done(function (data) {
        ajax_relation_nodes_functions = []
        for (var i = 0; i < data.length; i++) {
            ajax_relation_nodes_functions.push(ajax_get_relation_nodes_function(data[i], node));
        }
        for (var i = 0; i < ajax_relation_nodes_functions.length; i++) {
            ajax_relation_nodes_functions[i]();
        }
        if (typeof callback !== 'undefined') {
            callback(data);
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        console.log("Failed to get relations of node " + node.id + ": " + errorThrown);
    });
}

function ajax_get_card(node) {
    ajax_get_relations_of(node, function (relations) {
        draw_graph();
    });
}

function is_outgoing(node) {
    return current_card.outgoing.indexOf(node) != -1;
}

function is_incoming(node) {
    return current_card.incoming.indexOf(node) != -1;
}

function node_visible(node) {
    return (node == current_card) || is_outgoing(node) || is_incoming(node);
}

function link_visible(link) {
    // both ends of a link must be visible for a link to be visible
    return node_visible(link.from) && node_visible(link.to);
}

function x_pos(node) {
    if (node == current_card) {
        node.i = 0; // doesn't matter for current_card
        return (window.innerWidth / 2) - half_card_width;
    } else if (is_outgoing(node)) {
        if (node.i == null) {
            node.i = next_outgoing_i;
            next_outgoing_i++;
        }
        return top_row_offset + (node.i * (card_width + 10) + 10);
    } else if (is_incoming(node)) {
        if (node.i == null) {
            node.i = next_incoming_i;
            next_incoming_i++;
        }
        return node.i * (card_width + 10) + 10;
    } else {
        if (node.previously_current) {
            return window.innerWidth + 10;
        } else if (node.previously_outgoing || node.previously_incoming) {
            return (window.innerWidth / 2) - half_card_width;
        }
    }
}

function y_pos(node) {
    if (node == current_card) {
        return (graph_height / 2) - half_card_height;
    } else if (is_outgoing(node)) {
        return 10;
    } else if (is_incoming(node)) {
        return graph_height - 10 - card_height;
    } else {
        if (node.previously_current) {
            return (graph_height / 2) - half_card_height;
        } else if (node.previously_outgoing) {
            return -10 - card_height;
        } else if (node.previously_incoming) {
            return graph_height + 10;
        } else {
            console.log(node);
        }
    }
}

var drag = d3.behavior.drag()
            .on("drag", function () {
                console.log("woo");
                if (d3.event.y <= (card_height + 20)) {
                    top_row_offset += d3.event.dx;
                    draw_graph();
                }
            })

function pos2str(pos) {
    return pos[0] + "," + pos[1] + " ";
}

function compute_link_bezier_curve(link) {
    var from = link.from;
    var to = link.to;
    var start_pos = [x_pos(from, from.i) + half_card_width, y_pos(from, from.i)];
    var end_pos = [x_pos(to, to.i) + half_card_width,
                    /* marker-widht is 3, stroke-width is 5 */
                   y_pos(to, to.i) + card_height + (5 * 3)];
    var height = end_pos[1] - start_pos[1];
    var control1 = [start_pos[0], start_pos[1] + (height / 2)];
    var control2 = [end_pos[0], end_pos[1] - (height / 2)];
    return "M" + pos2str(start_pos) + "C" + pos2str(control1)
            + pos2str(control2) + pos2str(end_pos);
}

function reset_globals() {
    for (var i=0; i < nodes.length; i++) {
        node = nodes[i];
        node.i = null;
    }
    next_outgoing_i = 0;
    next_incoming_i = 0;
}

function make_cards() {
    var svg = d3.select("svg#graph");
    cards = svg.selectAll("g").data(nodes);
    new_cards = cards.enter().append("g").classed("argument", true);
    new_cards.append("rect").attr("width", card_width).attr("height", card_height)
                .style("opacity", 0).call(drag);
    var switch_objects = new_cards.append("switch");
    switch_objects.append("foreignObject").classed("foreign-object", true)
            .attr("requiredFeatures", "http://www.w3.org/TR/SVG11/feature#Extensibility")
            .attr("width", card_width).attr("height", card_height)
            .append("xhtml:div").classed("summary", true).append("p")
            .classed("summary", true).text(function (d) {
                return d.summary;
            }).attr("xmlns", "http://www.w3.org/1999/xhtml");
    switch_objects.append("text").attr("x", 100).attr("y", 100)
        .text("Sorry, your browser is not currently supported.");
    new_cards.on("click", function (d) {
        if (d3.event.defaultPrevented) return;
        current_card = d;
        ajax_get_card(d);
        draw_graph();
    })
}

function make_links() {
    var svg = d3.select("svg#graph");
    links = svg.selectAll("path").data(relations);
    links.enter().append("path")
        .attr("class", function(d) {
            return d.type;
        }).attr("marker-end", function(d) {
            return "url(#arrow-" + d.type + ")";
        }).style("opacity", 0);
}

function draw_graph() {
    reset_globals();
    make_cards();
    make_links();

    var svg = d3.select("svg#graph");
    d3.selectAll("g rect").transition().duration(500)
        .attr("x", x_pos).attr("y", y_pos).style("opacity", 1);
    // http://stackoverflow.com/a/11743721/257583
    // also, doesn't matter if the text is opaque or not since it's the same color as the background
    d3.selectAll(".foreign-object").transition().duration(500).attr("x", x_pos).attr("y", y_pos);
    cards.each(function (d) {
        if (current_card == d) {
            d.previously_current = true;
            d.previously_outgoing = false;
            d.previously_incoming = false;
        } else if (is_outgoing(d)) {
            d.previously_current = false;
            d.previously_outgoing = true;
            d.previously_incoming = false;
        } else if (is_incoming(d)) {
            d.previously_current = false;
            d.previously_outgoing = false;
            d.previously_incoming = true;
        } // else shouldn't happen
    });
    links.transition().duration(500).style("opacity", function (d) {
        // if one end of the link is currently displayed, then the other is too
        if (link_visible(d)) {
            return 1;
        } else {
            return 0;
        }
    }).attr("d", compute_link_bezier_curve);
}

window.onload = function () {
    if ($("#graph").height() < min_graph_height) {
        alert("Whoops, looks like some things won't be displaying correctly. Please tell us about this.");
    }
    graph_height = $("#graph").height();
    ajax_get_node(1, function (data) {
        current_card = data;
        draw_graph();

        ajax_get_relations_of(nodes[0], function (data) {
            draw_graph();
        })
    })

    draw_graph();
}<|endoftext|>


<commit_before>import React from "react";

export default class Control extends React.Component {
  constructor () {
    super()
    this.state = {first_name: "",
                  last_name: "",
                  agency: "",
                  dept: "",
                  title: "",
                  sortby: "wage",
                  direction: "desc"
                }
  }

  on_change(e){
    this.setState({[e.target.id]: e.target.value})
  }

  handleSubmit(e){
    var filters = {
      first_name: this.state.first_name,
      last_name: this.state.last_name,
      agency: this.state.agency,
      dept: this.state.dept,
      title: this.state.title,
      sortby: this.state.sortby,
      direction: this.state.direction
    };
    Object.keys(filters).forEach(function(key) {
      if (filters[key] == "") {
        delete filters[key]
      }
    })
    this.props.handleSubmit(filters);
  }

  handleClear(e){
    this.setState({first_name: "",
                  last_name: "",
                  agency: "",
                  dept: "",
                  title: "",
                  sortby: "wage",
                  direction: "desc"
                }, this.handleSubmit);
  }

  handleKeyPress(e){
    if (e.key === 'Enter') {
      this.handleSubmit(e)
    }
  }

  render() {
    return (
      <form className="form-horizontal" onKeyPress={this.handleKeyPress.bind(this)} method="get">

            First name:
            <input type="text" className="form-control" id="first_name" onChange={ this.on_change.bind(this) } name="first_name" value={ this.state.first_name }/>

            Last name:
            <input type="text" className="form-control" id="last_name" name="last_name" onChange={ this.on_change.bind(this)} value={ this.state.last_name }/>

            Title:
            <input type="text" className="form-control" id="title" name="title" onChange={ this.on_change.bind(this)} value={ this.state.title }/>

            Agency:
            <input type="text" className="form-control" id="agency" name="agency" onChange={ this.on_change.bind(this)} value={ this.state.agency }/>

            Dept:
            <input type="text" className="form-control" id="dept" name="dept" onChange={ this.on_change.bind(this)} value={ this.state.dept }/>

            Order by:
            <select className="form-control" id="sortby" value={this.state.sortby} onChange={this.on_change.bind(this)}>
              <option value="first_name">First name</option>
              <option value="last_name">Last name</option>
              <option value="agency">Agency</option>
              <option value="dept">Dept</option>
              <option value="title">Title</option>
              <option value="wage">Wage</option>
              <option value="year">Year</option>
            </select>

            Direction:
            <select className="form-control" id="direction" value={this.state.direction} onChange={this.on_change.bind(this)}>
              <option value="asc">Ascending</option>
              <option value="desc">Descending</option>
            </select>

            <button type="button" className="btn btn-primary btn-lg btn-block" onClick={ this.handleSubmit.bind(this) }>Search</button>

            <button type="button" className="btn btn-info btn-lg btn-block" onClick={ this.props.showPlot }>
              Plot
            </button>

            <button type="button" className="btn btn-warning btn-lg btn-block" onClick={ this.handleClear.bind(this) }>Clear</button>

      </form>
    );
  }
}
<commit_msg>saving screen space<commit_after>import React from "react";

export default class Control extends React.Component {
  constructor () {
    super()
    this.state = {first_name: "",
                  last_name: "",
                  agency: "",
                  dept: "",
                  title: "",
                  sortby: "wage",
                  direction: "desc"
                }
  }

  on_change(e){
    this.setState({[e.target.id]: e.target.value})
  }

  handleSubmit(e){
    var filters = {
      first_name: this.state.first_name,
      last_name: this.state.last_name,
      agency: this.state.agency,
      dept: this.state.dept,
      title: this.state.title,
      sortby: this.state.sortby,
      direction: this.state.direction
    };
    Object.keys(filters).forEach(function(key) {
      if (filters[key] == "") {
        delete filters[key]
      }
    })
    this.props.handleSubmit(filters);
  }

  handleClear(e){
    this.setState({first_name: "",
                  last_name: "",
                  agency: "",
                  dept: "",
                  title: "",
                  sortby: "wage",
                  direction: "desc"
                }, this.handleSubmit);
  }

  handleKeyPress(e){
    if (e.key === 'Enter') {
      this.handleSubmit(e)
    }
  }

  render() {
    return (
      <form className="form-horizontal" onKeyPress={this.handleKeyPress.bind(this)} method="get">

            First name:
            <input type="text" className="form-control" id="first_name" onChange={ this.on_change.bind(this) } name="first_name" value={ this.state.first_name }/>

            Last name:
            <input type="text" className="form-control" id="last_name" name="last_name" onChange={ this.on_change.bind(this)} value={ this.state.last_name }/>

            Title:
            <input type="text" className="form-control" id="title" name="title" onChange={ this.on_change.bind(this)} value={ this.state.title }/>

            Agency:
            <input type="text" className="form-control" id="agency" name="agency" onChange={ this.on_change.bind(this)} value={ this.state.agency }/>

            Dept:
            <input type="text" className="form-control" id="dept" name="dept" onChange={ this.on_change.bind(this)} value={ this.state.dept }/>

            Order by:
            <select className="form-control" id="sortby" value={this.state.sortby} onChange={this.on_change.bind(this)}>
              <option value="first_name">First name</option>
              <option value="last_name">Last name</option>
              <option value="agency">Agency</option>
              <option value="dept">Dept</option>
              <option value="title">Title</option>
              <option value="wage">Wage</option>
              <option value="year">Year</option>
            </select>

            Direction:
            <select className="form-control" id="direction" value={this.state.direction} onChange={this.on_change.bind(this)}>
              <option value="asc">Ascending</option>
              <option value="desc">Descending</option>
            </select>

            <button type="button" className="btn btn-primary btn-lg btn-block" onClick={ this.handleSubmit.bind(this) }>Search</button>

            <button type="button" className="btn btn-info btn-lg btn-block" onClick={ this.props.showPlot }>

              Plot

              Plot

            </button>

            <button type="button" className="btn btn-warning btn-lg btn-block" onClick={ this.handleClear.bind(this) }>Clear</button>

      </form>
    );
  }
}
<|endoftext|>


<commit_before>;(function () {
  'use strict'

  angular
    .module('app.core')
    .directive('ngEnter', ngEnter)

  function ngEnter () {
    return function (scope, element, attrs) {
      element.bind('keydown keypress', function (event) {
        if (event.which === 13) {
          scope.$apply(function () {
            scope.$eval(attrs.ngEnter)
          })
          event.preventDefault()
        }
      })
    }
  }
})()
<commit_msg>#41 add timeout for the digest loop error<commit_after>;(function () {
  'use strict'

  angular
    .module('app.core')
    .directive('ngEnter', ngEnter)

  function ngEnter () {
    return function (scope, element, attrs) {
      element.bind('keydown keypress', function (event) {
        if (event.which === 13) {
          setTimeout(function () { // added set time because of the digest loop
            scope.$apply(function () {
              scope.$eval(attrs.ngEnter)
            })
          })
          event.preventDefault()
        }
      })
    }
  }
})()
<|endoftext|>


<commit_before>// Copyright 2020, University of Colorado Boulder

/**
 * Generates JS modules from resources such as images or sounds.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Jonathan Olson (PhET Interactive Simulations)
 */
'use strict';

const _ = require( 'lodash' ); // eslint-disable-line require-statement-match
const createMipmap = require( './createMipmap' );
const fs = require( 'fs' );
const grunt = require( 'grunt' );
const loadFileAsDataURI = require( '../common/loadFileAsDataURI' );
const updateCopyrightForGeneratedFile = require( './updateCopyrightForGeneratedFile' );

// disable lint in compiled files
const HEADER = '/* eslint-disable */';

// supported image types, not case-sensitive
const IMAGE_SUFFIXES = [ '.png', '.jpg', '.cur' ];

// String replacement
const replace = ( string, search, replacement ) => string.split( search ).join( replacement );

/**
 * Transform an image file to a JS file that loads the image.
 * @param {string} abspath - the absolute path of the image
 */
const modulifyImage = abspath => {
  const dataURI = loadFileAsDataURI( abspath );

  const contents = `${HEADER}
var img = new Image();
window.phetImages.push( img );
img.src = '${dataURI}';
export default img;
`;

  fs.writeFileSync( convertSuffix( abspath, '.js' ), contents );
};

/**
 * Transform an image file to a JS file that loads the image as a mipmap.
 * @param {string} abspath - the absolute path of the image
 */
const modulifyMipmap = async abspath => {

  // defaults.  TODO: do we need to support non-defaults?  See https://github.com/phetsims/chipper/issues/820
  const options = {
    level: 4, // maximum level
    quality: 98
  };

  try {
    const mipmaps = await createMipmap( abspath, options.level, options.quality );
    const entry = mipmaps.map( ( { width, height, url } ) => ( { width: width, height: height, url: url } ) );

    const mipmapContents = `${HEADER}
var mipmaps = ${JSON.stringify( entry, null, 2 )};
mipmaps.forEach( function( mipmap ) {
  mipmap.img = new Image();
  window.phetImages.push( mipmap.img ); // make sure it's loaded before the sim launches
  mipmap.img.src = mipmap.url; // trigger the loading of the image for its level
  mipmap.canvas = document.createElement( 'canvas' );
  mipmap.canvas.width = mipmap.width;
  mipmap.canvas.height = mipmap.height;
  var context = mipmap.canvas.getContext( '2d' );
  mipmap.updateCanvas = function() {
    if ( mipmap.img.complete && ( typeof mipmap.img.naturalWidth === 'undefined' || mipmap.img.naturalWidth > 0 ) ) {
      context.drawImage( mipmap.img, 0, 0 );
      delete mipmap.updateCanvas;
    }
  };
} );
export default mipmaps;`;
    fs.writeFileSync( convertSuffix( abspath, '.js' ), mipmapContents );
  }
  catch( e ) {
    console.log( `Image could not be mipmapped: ${abspath}` );
  }
};

/**
 * Convert .png => _png_mipmap.js, etc.
 * @param {string} abspath - the absolute path
 * @param {string} suffix - the new suffix, such as '.js'
 */
const convertSuffix = ( abspath, suffix ) => {
  const lastDotIndex = abspath.lastIndexOf( '.' );
  return abspath.substring( 0, lastDotIndex ) + '_' + abspath.substring( lastDotIndex + 1 ) + suffix;
};

/**
 * Determines the suffix from a filename, everything after the final '.'
 * @param {string} filename
 */
const getSuffix = filename => {
  const index = filename.lastIndexOf( '.' );
  return filename.substring( index );
};

/**
 * Creates a *.js file corresponding to matching resources such as images or sounds.
 * @param {string} abspath
 * @param {string} rootdir
 * @param {string} subdir
 * @param {string} filename
 */
const modulifyFile = async ( abspath, rootdir, subdir, filename ) => {

  if ( subdir && ( subdir.startsWith( 'images' ) ||

                   // for brand
                   subdir.startsWith( 'phet/images' ) ||
                   subdir.startsWith( 'phet-io/images' ) ||
                   subdir.startsWith( 'adapted-from-phet/images' ) )
       && IMAGE_SUFFIXES.indexOf( getSuffix( filename ) ) >= 0 ) {
    modulifyImage( abspath );
  }

  if ( subdir && ( subdir.startsWith( 'mipmaps' ) ||

                   // for brand
                   subdir.startsWith( 'phet/mipmaps' ) ||
                   subdir.startsWith( 'phet-io/mipmaps' ) ||
                   subdir.startsWith( 'adapted-from-phet/mipmaps' ) )
       && IMAGE_SUFFIXES.indexOf( getSuffix( filename ) ) >= 0 ) {
    await modulifyMipmap( abspath );
  }

  // TODO: https://github.com/phetsims/chipper/issues/872 factor out duplicates
  if ( subdir && subdir.startsWith( 'sounds' ) ) {
    if ( filename.endsWith( '.mp3' ) ) {
      const x = loadFileAsDataURI( abspath );

      const contents = `${HEADER}
export default {
  name: '${filename}',
  base64: '${x}'
};`;

      const outputFilename = replace( abspath, '.mp3', '_mp3.js' );
      fs.writeFileSync( outputFilename, contents );
    }
    if ( filename.endsWith( '.wav' ) ) {
      const x = loadFileAsDataURI( abspath );

      const contents = `${HEADER}
export default {
  name: '${filename}',
  base64: '${x}'
};`;

      const outputFilename = replace( abspath, '.wav', '_wav.js' );
      fs.writeFileSync( outputFilename, contents );
    }
  }
};

/**
 * Entry point for modulify, which transforms all of the resources in a repo to *.js files.
 * @parm {string} repo, the name of a repo, such as 'joist'
 */
module.exports = async function( repo ) {
  console.log( `modulifying ${repo}` );
  const relativeFiles = [];
  grunt.file.recurse( `../${repo}`, async ( abspath, rootdir, subdir, filename ) => {
    relativeFiles.push( { abspath: abspath, rootdir: rootdir, subdir: subdir, filename: filename } );
  } );

  for ( let i = 0; i < relativeFiles.length; i++ ) {
    const entry = relativeFiles[ i ];
    await modulifyFile( entry.abspath, entry.rootdir, entry.subdir, entry.filename );
  }

  const packageObject = grunt.file.readJSON( `../${repo}/package.json` );
  if ( fs.existsSync( `../${repo}/${repo}-strings_en.json` ) && packageObject.phet && packageObject.phet.requirejsNamespace ) {
    const stringModuleFile = `../${repo}/js/${repo}-strings.js`;
    const namespace = _.camelCase( repo );
    fs.writeFileSync( stringModuleFile, `// Copyright ${new Date().getFullYear()}, University of Colorado Boulder

/**
 * Auto-generated from modulify, DO NOT manually modify.
 */

import getStringModule from '../../chipper/js/getStringModule.js';
import ${namespace} from './${namespace}.js';

const ${namespace}Strings = getStringModule( '${packageObject.phet.requirejsNamespace}' );

${namespace}.register( '${namespace}Strings', ${namespace}Strings );

export default ${namespace}Strings;
` );
    await updateCopyrightForGeneratedFile( repo, stringModuleFile );

    const namespaceFile = `../${repo}/js/${namespace}.js`;
    if ( !fs.existsSync( namespaceFile ) ) {
      fs.writeFileSync( namespaceFile, `// Copyright ${new Date().getFullYear()}, University of Colorado Boulder

/**
 * Creates the namespace for this simulation.
 */

// modules
import Namespace from '../../phet-core/js/Namespace.js';

export default new Namespace( '${namespace}' );
` );
      await updateCopyrightForGeneratedFile( repo, namespaceFile );
    }
  }
};<commit_msg>Prepare for code review, see https://github.com/phetsims/chipper/issues/872<commit_after>// Copyright 2020, University of Colorado Boulder

/**
 * Generates JS modules from resources such as images or sounds.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Jonathan Olson (PhET Interactive Simulations)
 */
'use strict';

const _ = require( 'lodash' ); // eslint-disable-line require-statement-match
const createMipmap = require( './createMipmap' );
const fs = require( 'fs' );
const grunt = require( 'grunt' );
const loadFileAsDataURI = require( '../common/loadFileAsDataURI' );
const updateCopyrightForGeneratedFile = require( './updateCopyrightForGeneratedFile' );

// disable lint in compiled files
const HEADER = '/* eslint-disable */';

// supported image types, not case-sensitive
const IMAGE_SUFFIXES = [ '.png', '.jpg', '.cur' ];

/**
 * String replacement
 * @param {string} string - the string which will be searched
 * @param {string} search - the text to be replaced
 * @param {string} replacement - the new text
 * @returns {string}
 */
const replace = ( string, search, replacement ) => string.split( search ).join( replacement );

/**
 * Transform an image file to a JS file that loads the image.
 * @param {string} abspath - the absolute path of the image
 */
const modulifyImage = abspath => {
  const dataURI = loadFileAsDataURI( abspath );

  const contents = `${HEADER}
var img = new Image();
window.phetImages.push( img );
img.src = '${dataURI}';
export default img;
`;

  fs.writeFileSync( convertSuffix( abspath, '.js' ), contents );
};

/**
 * Transform an image file to a JS file that loads the image as a mipmap.
 * @param {string} abspath - the absolute path of the image
 */
const modulifyMipmap = async abspath => {

  // Defaults.  TODO: do we need to support non-defaults?  See https://github.com/phetsims/chipper/issues/820
  // TODO: Or do we need to support mipmaps at all?  See https://github.com/phetsims/chipper/issues/840
  const options = {
    level: 4, // maximum level
    quality: 98
  };

  try {
    const mipmaps = await createMipmap( abspath, options.level, options.quality );
    const entry = mipmaps.map( ( { width, height, url } ) => ( { width: width, height: height, url: url } ) );

    // To the REVIEWER, should we use const/let/arrow functions in the modulified files?  See https://github.com/phetsims/chipper/issues/872
    const mipmapContents = `${HEADER}
var mipmaps = ${JSON.stringify( entry, null, 2 )};
mipmaps.forEach( function( mipmap ) {
  mipmap.img = new Image();
  window.phetImages.push( mipmap.img ); // make sure it's loaded before the sim launches
  mipmap.img.src = mipmap.url; // trigger the loading of the image for its level
  mipmap.canvas = document.createElement( 'canvas' );
  mipmap.canvas.width = mipmap.width;
  mipmap.canvas.height = mipmap.height;
  var context = mipmap.canvas.getContext( '2d' );
  mipmap.updateCanvas = function() {
    if ( mipmap.img.complete && ( typeof mipmap.img.naturalWidth === 'undefined' || mipmap.img.naturalWidth > 0 ) ) {
      context.drawImage( mipmap.img, 0, 0 );
      delete mipmap.updateCanvas;
    }
  };
} );
export default mipmaps;`;
    fs.writeFileSync( convertSuffix( abspath, '.js' ), mipmapContents );
  }
  catch( e ) {

    // This is an async function, so I'm not sure whether we can throw out of it.  To the REVIEWER, what do you recommend?  See https://github.com/phetsims/chipper/issues/872
    console.log( `Image could not be mipmapped: ${abspath}` );
  }
};

/**
 * Convert .png => _png_mipmap.js, etc.
 * @param {string} abspath - the absolute path
 * @param {string} suffix - the new suffix, such as '.js'
 */
const convertSuffix = ( abspath, suffix ) => {
  const lastDotIndex = abspath.lastIndexOf( '.' );
  return abspath.substring( 0, lastDotIndex ) + '_' + abspath.substring( lastDotIndex + 1 ) + suffix;
};

/**
 * Determines the suffix from a filename, everything after the final '.'
 * @param {string} filename
 */
const getSuffix = filename => {
  const index = filename.lastIndexOf( '.' );
  return filename.substring( index );
};

/**
 * Creates a *.js file corresponding to matching resources such as images or sounds.
 * @param {string} abspath
 * @param {string} rootdir
 * @param {string} subdir
 * @param {string} filename
 */
const modulifyFile = async ( abspath, rootdir, subdir, filename ) => {

  // To the REVIEWER: Should this code be factored out?  Note that one is await and the other is not.  See https://github.com/phetsims/chipper/issues/872
  if ( subdir && ( subdir.startsWith( 'images' ) ||

                   // for brand
                   subdir.startsWith( 'phet/images' ) ||
                   subdir.startsWith( 'phet-io/images' ) ||
                   subdir.startsWith( 'adapted-from-phet/images' ) )
       && IMAGE_SUFFIXES.indexOf( getSuffix( filename ) ) >= 0 ) {
    modulifyImage( abspath );
  }

  if ( subdir && ( subdir.startsWith( 'mipmaps' ) ||

                   // for brand
                   subdir.startsWith( 'phet/mipmaps' ) ||
                   subdir.startsWith( 'phet-io/mipmaps' ) ||
                   subdir.startsWith( 'adapted-from-phet/mipmaps' ) )
       && IMAGE_SUFFIXES.indexOf( getSuffix( filename ) ) >= 0 ) {
    await modulifyMipmap( abspath );
  }

  // TODO: https://github.com/phetsims/chipper/issues/872 factor out duplicates
  if ( subdir && subdir.startsWith( 'sounds' ) ) {

    /**
     * Output supported sound formats.
     * @param {string} soundFileSuffix
     * @param {string} jsFileSuffix
     */
    const mapSounds = ( soundFileSuffix, jsFileSuffix ) => {
      if ( filename.endsWith( soundFileSuffix ) ) {
        const x = loadFileAsDataURI( abspath );

        const contents = `${HEADER}
export default {
  name: '${filename}',
  base64: '${x}'
};`;

        const outputFilename = replace( abspath, soundFileSuffix, jsFileSuffix );
        fs.writeFileSync( outputFilename, contents );
      }
    };

    mapSounds( '.mp3', '_mp3.js' );
    mapSounds( '.wav', '_wav.js' );
  }
};

/**
 * Entry point for modulify, which transforms all of the resources in a repo to *.js files.
 * @parm {string} repo, the name of a repo, such as 'joist'
 */
module.exports = async function( repo ) {
  console.log( `modulifying ${repo}` );
  const relativeFiles = [];
  grunt.file.recurse( `../${repo}`, async ( abspath, rootdir, subdir, filename ) => {
    relativeFiles.push( { abspath: abspath, rootdir: rootdir, subdir: subdir, filename: filename } );
  } );

  for ( let i = 0; i < relativeFiles.length; i++ ) {
    const entry = relativeFiles[ i ];
    await modulifyFile( entry.abspath, entry.rootdir, entry.subdir, entry.filename );
  }

  // Create the namespace file, if it did not already exist
  const packageObject = grunt.file.readJSON( `../${repo}/package.json` );
  if ( fs.existsSync( `../${repo}/${repo}-strings_en.json` ) && packageObject.phet && packageObject.phet.requirejsNamespace ) {
    const stringModuleFile = `../${repo}/js/${repo}-strings.js`;
    const namespace = _.camelCase( repo );
    fs.writeFileSync( stringModuleFile,

      `// Copyright ${new Date().getFullYear()}, University of Colorado Boulder

/**
 * Auto-generated from modulify, DO NOT manually modify.
 */

import getStringModule from '../../chipper/js/getStringModule.js';
import ${namespace} from './${namespace}.js';

const ${namespace}Strings = getStringModule( '${packageObject.phet.requirejsNamespace}' );

${namespace}.register( '${namespace}Strings', ${namespace}Strings );

export default ${namespace}Strings;
` );
    await updateCopyrightForGeneratedFile( repo, stringModuleFile );

    const namespaceFile = `../${repo}/js/${namespace}.js`;
    if ( !fs.existsSync( namespaceFile ) ) {
      fs.writeFileSync( namespaceFile, `// Copyright ${new Date().getFullYear()}, University of Colorado Boulder

/**
 * Creates the namespace for this simulation.
 */

// modules
import Namespace from '../../phet-core/js/Namespace.js';

export default new Namespace( '${namespace}' );
` );
      await updateCopyrightForGeneratedFile( repo, namespaceFile );
    }
  }
};<|endoftext|>