<commit_before>var basicAuth = require('basic-auth');
var crypto  = require('crypto');

/**
 * Simple basic auth middleware for use with Express 4.x.
 *
 * @example
 * app.use('/api-requiring-auth', utils.basicAuth('username', 'password'));
 *
 * @param   {string}   username Expected username
 * @param   {string}   password Expected password
 * @returns {function} Express 4 middleware requiring the given credentials
 */
/*
exports.basicAuth = function(username, password, conf, crypto) {
  return function(req, res, next) {
    var user = basicAuth(req);

    if (!user || user.name !== username || user.pass !== password) {
      res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
      return res.send(401);
    }

    next();
  };
};
*/

exports.basicAuth = function(conf) {
    return function(req, res, next) {
        var user = basicAuth(req);

        var cipher = crypto.createCipher('aes-256-cbc', conf.application.salt);
        cipher.update(user.pass, 'utf8', 'base64');
        if (!user || !(cipher.final('base64') === conf.application.password) && user.name === conf.application.username ) {
            res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
            return res.send(401);
        }

        next();
    };
};
<commit_msg>Bugfix<commit_after>var basicAuth = require('basic-auth');
var crypto  = require('crypto');

/**
 * Simple basic auth middleware for use with Express 4.x.
 *
 * @example
 * app.use('/api-requiring-auth', utils.basicAuth('username', 'password'));
 *
 * @param   {string}   username Expected username
 * @param   {string}   password Expected password
 * @returns {function} Express 4 middleware requiring the given credentials
 */
/*
exports.basicAuth = function(username, password, conf, crypto) {
  return function(req, res, next) {
    var user = basicAuth(req);

    if (!user || user.name !== username || user.pass !== password) {
      res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
      return res.send(401);
    }

    next();
  };
};
*/

exports.basicAuth = function(conf) {
    return function(req, res, next) {
        var user = basicAuth(req);
        if (!user) {
            res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
            return res.send(401);
        }
        var cipher = crypto.createCipher('aes-256-cbc', conf.application.salt);
        cipher.update(user.pass, 'utf8', 'base64');
        if (!user || !(cipher.final('base64') === conf.application.password) && user.name === conf.application.username ) {
            res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
            return res.send(401);
        }

        next();
    };
};
<|endoftext|>


<commit_before>var fs = require('fs');

var heroesJSON  = require('./json/heroes.json');
var neutralJSON = require('./json/neutral.json');
var redJSON     = require('./json/red.json');
var greenJSON   = require('./json/green.json');
var blueJSON    = require('./json/blue.json');
var blackJSON   = require('./json/black.json');
var whiteJSON   = require('./json/white.json');
var purpleJSON  = require('./json/purple.json');
var rulingsJSON = require('./json/rulings.json');

import { toURL } from './src/utils';

const keywordRulings = rulingsJSON['General'].reduce((acc, ruling) => {
	if (!acc[ruling.card]) { acc[ruling.card] = []; }
	acc[ruling.card].push(ruling);
	return acc;
}, {});

const urlKeywordToKeyword = Object.keys(keywordRulings).reduce((acc, keyword) => {
	let urlKeyword = keyword.toLowerCase();
	if (urlKeyword.lastIndexOf(' x') === urlKeyword.length - 2) {
		urlKeyword = urlKeyword.slice(0, -2);
	}
	acc[urlKeyword] = keyword;
	return acc;
}, {});

const cardSpecificRulings = Object.keys(rulingsJSON).filter((key) => { return key !== 'General'; }).reduce((acc, key) => {
	const rulingsByCard = rulingsJSON[key].reduce((acc, ruling) => {
		if (!acc[ruling.card]) { acc[ruling.card] = []; }
		acc[ruling.card].push(ruling);
		return acc;
	}, {});

	return {...acc, ...rulingsByCard};
}, {});

const cardTextKeys = 	[
	'rules_text_1', 'rules_text_2', 'rules_text_3',
	'base_text_1', 'base_text_2', 'base_text_3',
	'mid_text_1', 'mid_text_2', 'mid_text_3',
	'max_text_1', 'max_text_2', 'max_text_3',
	'subtype'
];

const urlKeywords = Object.keys(urlKeywordToKeyword);

const cardsJSON = [].concat(heroesJSON, neutralJSON, redJSON, greenJSON, blueJSON, blackJSON, whiteJSON, purpleJSON);

let data = cardsJSON.reduce((acc, item) => {
	const { cards, specs, heroes, colors, starters, urlCardToCard, urlColorToColor, urlColorToSpecs, urlSpecToSpec, urlSpecToColor } = acc;

	if (!item.sirlins_filename) { return acc; }

	// HACK: Fixing the URL for "Research & Development"
	item.sirlins_filename = item.sirlins_filename.replace('&', '');

	//
	cards[item.name] = item;

	// add card-specific rulings
	item.rulings = cardSpecificRulings[item.name];

	// search card text for keywords (for general rulings)
	let uniqueKeywords = {};
	cardTextKeys.forEach((key) => {
		if (item[key]) {
			const cardText = item[key].replace(/\(.*?\)/g, ''); // remove parenthetical text
			urlKeywords.forEach((keyword) => {
				if (cardText.toLowerCase().indexOf(keyword) !== -1) {
					uniqueKeywords[urlKeywordToKeyword[keyword]] = true;
				}
			});
		}
	});
	item.keywords = Object.keys(uniqueKeywords);

	//
	if (item.spec) {
		if (!specs[item.spec]) { specs[item.spec] = []; }
		specs[item.spec].push(item.name);
	}

	//
	if (item.type === 'Hero' && item.spec) {
		heroes[item.spec] = item.name;
	}

	//
	if (item.color) {
		if (!colors[item.color]) { colors[item.color] = []; }
		colors[item.color].push(item.name);
	}

	//
	if (item.starting_zone === 'deck' && item.color) {
		if (!starters[item.color]) { starters[item.color] = []; }
		starters[item.color].push(item.name);
	}

	//
	const urlName = toURL(item.name);
	urlCardToCard[urlName] = item.name;

	if (item.color && item.spec) {
		const urlColor = toURL(item.color);
		const urlSpec = toURL(item.spec);
		urlColorToColor[urlColor] = item.color;
		urlSpecToSpec[urlSpec] = item.spec;
		urlSpecToColor[urlSpec] = item.color;

		if (!urlColorToSpecs[urlColor]) { urlColorToSpecs[urlColor] = []; }
		if (!urlColorToSpecs[urlColor].includes(item.spec)) { urlColorToSpecs[urlColor].push(item.spec); }
	}

	// TODO: come up with something better for searches...
	item.searchableText = toURL(item.name).replace(/_/g, ' ');
	if (item.color)            { item.searchableText += ' ' + toURL(item.color).replace(/_/g, ' '); }
	if (item.spec)             { item.searchableText += ' ' + toURL(item.spec).replace(/_/g, ' '); }
	if (item.subtype)          { item.searchableText += ' ' + toURL(item.subtype).replace(/_/g, ' '); }
	if (item.tech_level == 0)  { item.searchableText += ' ' + 'tech 0'; }
	if (item.tech_level === 1) { item.searchableText += ' ' + 'tech i 1'; }
	if (item.tech_level === 2) { item.searchableText += ' ' + 'tech ii 2'; }
	if (item.tech_level === 3) { item.searchableText += ' ' + 'tech iii 3'; }
	if (item.type === 'Hero')  { item.searchableText += ' ' + 'hero'; }
	if (item.type && item.type.indexOf('Spell') !== -1) { item.searchableText += ' ' + item.type.toLowerCase() + ' magic'; }
	if (item.tech_level == 0 || item.type === 'Minor Spell')  { item.searchableText += ' starter'; }
	item.searchableText += ' ' + item.keywords.map(x => toURL(x).replace(/_/g, ' ')).join(' ');

	return acc;
}, { cards: {}, specs: {}, heroes: {}, colors: {}, starters: {}, urlCardToCard: {}, urlColorToColor: {}, urlColorToSpecs: {}, urlSpecToSpec: {}, urlSpecToColor: {} });

data.keywordRulings = keywordRulings;

fs.writeFileSync('src/cardData.json', JSON.stringify(data, null, '  '));
<commit_msg>adding normal type to search text<commit_after>var fs = require('fs');

var heroesJSON  = require('./json/heroes.json');
var neutralJSON = require('./json/neutral.json');
var redJSON     = require('./json/red.json');
var greenJSON   = require('./json/green.json');
var blueJSON    = require('./json/blue.json');
var blackJSON   = require('./json/black.json');
var whiteJSON   = require('./json/white.json');
var purpleJSON  = require('./json/purple.json');
var rulingsJSON = require('./json/rulings.json');

import { toURL } from './src/utils';

const keywordRulings = rulingsJSON['General'].reduce((acc, ruling) => {
	if (!acc[ruling.card]) { acc[ruling.card] = []; }
	acc[ruling.card].push(ruling);
	return acc;
}, {});

const urlKeywordToKeyword = Object.keys(keywordRulings).reduce((acc, keyword) => {
	let urlKeyword = keyword.toLowerCase();
	if (urlKeyword.lastIndexOf(' x') === urlKeyword.length - 2) {
		urlKeyword = urlKeyword.slice(0, -2);
	}
	acc[urlKeyword] = keyword;
	return acc;
}, {});

const cardSpecificRulings = Object.keys(rulingsJSON).filter((key) => { return key !== 'General'; }).reduce((acc, key) => {
	const rulingsByCard = rulingsJSON[key].reduce((acc, ruling) => {
		if (!acc[ruling.card]) { acc[ruling.card] = []; }
		acc[ruling.card].push(ruling);
		return acc;
	}, {});

	return {...acc, ...rulingsByCard};
}, {});

const cardTextKeys = 	[
	'rules_text_1', 'rules_text_2', 'rules_text_3',
	'base_text_1', 'base_text_2', 'base_text_3',
	'mid_text_1', 'mid_text_2', 'mid_text_3',
	'max_text_1', 'max_text_2', 'max_text_3',
	'subtype'
];

const urlKeywords = Object.keys(urlKeywordToKeyword);

const cardsJSON = [].concat(heroesJSON, neutralJSON, redJSON, greenJSON, blueJSON, blackJSON, whiteJSON, purpleJSON);

let data = cardsJSON.reduce((acc, item) => {
	const { cards, specs, heroes, colors, starters, urlCardToCard, urlColorToColor, urlColorToSpecs, urlSpecToSpec, urlSpecToColor } = acc;

	if (!item.sirlins_filename) { return acc; }

	// HACK: Fixing the URL for "Research & Development"
	item.sirlins_filename = item.sirlins_filename.replace('&', '');

	//
	cards[item.name] = item;

	// add card-specific rulings
	item.rulings = cardSpecificRulings[item.name];

	// search card text for keywords (for general rulings)
	let uniqueKeywords = {};
	cardTextKeys.forEach((key) => {
		if (item[key]) {
			const cardText = item[key].replace(/\(.*?\)/g, ''); // remove parenthetical text
			urlKeywords.forEach((keyword) => {
				if (cardText.toLowerCase().indexOf(keyword) !== -1) {
					uniqueKeywords[urlKeywordToKeyword[keyword]] = true;
				}
			});
		}
	});
	item.keywords = Object.keys(uniqueKeywords);

	//
	if (item.spec) {
		if (!specs[item.spec]) { specs[item.spec] = []; }
		specs[item.spec].push(item.name);
	}

	//
	if (item.type === 'Hero' && item.spec) {
		heroes[item.spec] = item.name;
	}

	//
	if (item.color) {
		if (!colors[item.color]) { colors[item.color] = []; }
		colors[item.color].push(item.name);
	}

	//
	if (item.starting_zone === 'deck' && item.color) {
		if (!starters[item.color]) { starters[item.color] = []; }
		starters[item.color].push(item.name);
	}

	//
	const urlName = toURL(item.name);
	urlCardToCard[urlName] = item.name;

	if (item.color && item.spec) {
		const urlColor = toURL(item.color);
		const urlSpec = toURL(item.spec);
		urlColorToColor[urlColor] = item.color;
		urlSpecToSpec[urlSpec] = item.spec;
		urlSpecToColor[urlSpec] = item.color;

		if (!urlColorToSpecs[urlColor]) { urlColorToSpecs[urlColor] = []; }
		if (!urlColorToSpecs[urlColor].includes(item.spec)) { urlColorToSpecs[urlColor].push(item.spec); }
	}

	// TODO: come up with something better for searches...
	item.searchableText = toURL(item.name).replace(/_/g, ' ');
	if (item.color)            { item.searchableText += ' ' + toURL(item.color).replace(/_/g, ' '); }
	if (item.spec)             { item.searchableText += ' ' + toURL(item.spec).replace(/_/g, ' '); }
	if (item.type)             { item.searchableText += ' ' + toURL(item.type).replace(/_/g, ' '); }
	if (item.subtype)          { item.searchableText += ' ' + toURL(item.subtype).replace(/_/g, ' '); }
	if (item.tech_level == 0)  { item.searchableText += ' tech 0'; }
	if (item.tech_level === 1) { item.searchableText += ' tech i 1'; }
	if (item.tech_level === 2) { item.searchableText += ' tech ii 2'; }
	if (item.tech_level === 3) { item.searchableText += ' tech iii 3'; }
	if (item.type && item.type.indexOf('Spell') !== -1) { item.searchableText += ' ' + item.type.toLowerCase() + ' magic'; }
	if (item.tech_level == 0 || item.type === 'Minor Spell')  { item.searchableText += ' starter'; }
	item.searchableText += ' ' + item.keywords.map(x => toURL(x).replace(/_/g, ' ')).join(' ');

	return acc;
}, { cards: {}, specs: {}, heroes: {}, colors: {}, starters: {}, urlCardToCard: {}, urlColorToColor: {}, urlColorToSpecs: {}, urlSpecToSpec: {}, urlSpecToColor: {} });

data.keywordRulings = keywordRulings;

fs.writeFileSync('src/cardData.json', JSON.stringify(data, null, '  '));
<|endoftext|>


<commit_before>/***
 * This file will contain all the scripts required for display entries to judges.
***/
/* If it doesn't look like there's a contest ID in the URL, show an alert, and go back one page. */
if (window.location.search.indexOf("?contest") === -1) {
	alert("Contest ID not found!");

	window.history.back();
}

if (window.location.search.indexOf("&entries") === -1) {
	alert("Please specify the number of entries you'd like to view!");

	window.history.back();
}

/* Locate the contest ID in the URL, and store it for later use. */
var contestId = window.location.href.split("?contest=")[1].split("&entries")[0];
var numberOfEntries = window.location.href.split("&entries=")[1] === "all" ? null : parseInt(window.location.href.split("&entries=")[1], 10);

/* Go ahead and find the div that we'll store all the entries in. */
var entriesList = document.querySelector(".media-list");

console.log("Contest found!");
console.log("Contest ID: " + contestId);
console.log("We're going to load " + numberOfEntries + " entries!");

/* Hide elements that we've marked with the class "hideWhileLoad". */
$(".hideWhileLoad").css("display", "none");

/* Attempt to load a contest, based on the ID we found in the URL. */
Contest_Judging_System.loadContest(contestId, function(contest) {

	/* Randomly pick n entries, and then display them on the page. */
	Contest_Judging_System.get_N_Entries(numberOfEntries === null ? 400000 : numberOfEntries, contest.id, function(entries) {

		/* Setup the page */
		$("title").text(contest.name);
		$("#contestName").text(contest.name);
		$("#contestDescription").html("Description coming soon!");

		var detailsDiv = document.getElementById("contestDescription");
		detailsDiv.innerHTML = contest.desc || "No description found!";

		console.log(contest.desc);
		/* Add all entries to the page */
		for (var i in entries) {
            console.log(entries[i]);
            /* The JSON object corresponding to this entry. */
            var curr = entries[i];

            /* Create a list item element, and give it Bootstrap's "media" class. */
            var mediaListItem = document.createElement("li");
            mediaListItem.className = "media entry";

            /* Create a div element, and give it Bootstrap's "media-left" class. */
            var mediaLeftDiv = document.createElement("div");
            mediaLeftDiv.className = "media-left";

            /* Create a link element, and set it's href to the URL of this entry... */
            var aElem = document.createElement("a");
            // aElem.href = "https://www.khanacademy.org/computer-programming/entry/" + curr.id;
            aElem.href = "entry.html?contest=" + contestId + "&entry=" + curr.id;

            /* Create an image element and set it's src to this entry's thumbnail */
            var mediaObj = document.createElement("img");
            mediaObj.src = "https://www.khanacademy.org/"+curr.img;
            mediaObj.alt = "Entry thumbnail";

            /* Create a div element, and give it Bootstrap's "media-body" class. */
            var mediaBody = document.createElement("div");
            mediaBody.className = "media-body";

            /* Create a heading element (tier 4), and set it's text to this entry's name. */
            var mediaHeading = document.createElement("h4");
            mediaHeading.textContent = curr.name;

            /* Create a div that will hold more information about this entry */
            var infoDiv = document.createElement("div");
            infoDiv.className = "info";

            /* Create a heading element (tier 5), to mark the "Score" heading */
            var scoreHeading = document.createElement("h5");
            scoreHeading.textContent = "Score:";

            /* Create an unordered list element that will be used to display score information for this entry. */
            var scoreList = document.createElement("ul");

            /* Go through all the score information for this entry, and create a list item for it. */
            for (var rubric in curr.scores.rubric) {
                (function() {
                    /* This is in a function wrapper so rubric and scoreList will not be lost. */
                    var currRubric = rubric;
                    var currScoreList = scoreList;

                    /* We don't need to look for a max for the "NumberOfJudges" rubric, so if we're currently at it, return. */
                    if (currRubric === "NumberOfJudges") {
                        return;
                    }

                    var val = Math.floor(curr.scores.rubric[rubric].avg);

                    Contest_Judging_System.getRubrics(function(rubrics) {
                        var max = rubrics[currRubric].max;
                        /* Credit to @NobleMushtak for the following idea. */
                        var selectedRubric = currRubric.replace(/_/gi, " ");

                        if (rubrics[currRubric].hasOwnProperty("keys")) {
                            console.log(rubrics[currRubric].keys);
                            val = rubrics[currRubric].keys[val];
                            console.log("Value switched to a key!");

                            var listItem = document.createElement("li");
                            listItem.textContent = selectedRubric + ": " + val;

                            currScoreList.appendChild(listItem);
                            console.log(listItem);
                        } else {
                            var listItem = document.createElement("li");
                            listItem.textContent = selectedRubric + ": " + val + " out of " + max;
                            currScoreList.appendChild(listItem);
                            console.log(listItem);
                        }
                    });
                })();
            }

            /* Append everything */
            infoDiv.appendChild(scoreHeading);
            infoDiv.appendChild(scoreList);
            aElem.appendChild(mediaObj);
            mediaLeftDiv.appendChild(aElem);
            mediaBody.appendChild(mediaHeading);
            mediaListItem.appendChild(mediaLeftDiv);
            mediaBody.appendChild(infoDiv);
            mediaListItem.appendChild(mediaBody);
            entriesList.appendChild(mediaListItem);
        }

		/* Hide the loading div and show items that were hidden during loading. */
		$("#loading").css("display", "none");
		$(".hideWhileLoad").css("display", "block");
	});
});<commit_msg>Fixed a small bug<commit_after>/***
 * This file will contain all the scripts required for display entries to judges.
***/
/* If it doesn't look like there's a contest ID in the URL, show an alert, and go back one page. */
if (window.location.search.indexOf("?contest") === -1) {
	alert("Contest ID not found!");

	window.history.back();
}

if (window.location.search.indexOf("&entries") === -1) {
	alert("Please specify the number of entries you'd like to view!");

	window.history.back();
}

/* Locate the contest ID in the URL, and store it for later use. */
var contestId = window.location.href.split("?contest=")[1].split("&entries")[0];
var numberOfEntries = window.location.href.split("&entries=")[1] === "all" ? null : parseInt(window.location.href.split("&entries=")[1], 10);

/* Go ahead and find the div that we'll store all the entries in. */
var entriesList = document.querySelector(".media-list");

console.log("Contest found!");
console.log("Contest ID: " + contestId);
console.log("We're going to load " + numberOfEntries + " entries!");

/* Hide elements that we've marked with the class "hideWhileLoad". */
$(".hideWhileLoad").css("display", "none");

/* Attempt to load a contest, based on the ID we found in the URL. */
Contest_Judging_System.loadContest(contestId, function(contest) {

	/* Randomly pick n entries, and then display them on the page. */
	Contest_Judging_System.get_N_Entries(numberOfEntries === null ? 400000 : numberOfEntries, contest.id, function(entries) {

		/* Setup the page */
		$("title").text(contest.name);
		$("#contestName").text(contest.name);
		$("#contestDescription").html("Description coming soon!");

		var detailsDiv = document.getElementById("contestDescription");
		detailsDiv.innerHTML = contest.desc || "No description found!";

		console.log(contest.desc);
		/* Add all entries to the page */
		for (var i in entries) {
            console.log(entries[i]);
            /* The JSON object corresponding to this entry. */
            var curr = entries[i];

            /* Create a list item element, and give it Bootstrap's "media" class. */
            var mediaListItem = document.createElement("li");
            mediaListItem.className = "media entry";

            /* Create a div element, and give it Bootstrap's "media-left" class. */
            var mediaLeftDiv = document.createElement("div");
            mediaLeftDiv.className = "media-left";

            /* Create a link element, and set it's href to the URL of this entry... */
            var aElem = document.createElement("a");
            // aElem.href = "https://www.khanacademy.org/computer-programming/entry/" + curr.id;
            aElem.href = "entry.html?contest=" + contestId + "&entry=" + curr.id;

            /* Create an image element and set it's src to this entry's thumbnail */
            var mediaObj = document.createElement("img");
            mediaObj.src = "https://www.khanacademy.org/" + curr.thumb;
            mediaObj.alt = "Entry thumbnail";

            /* Create a div element, and give it Bootstrap's "media-body" class. */
            var mediaBody = document.createElement("div");
            mediaBody.className = "media-body";

            /* Create a heading element (tier 4), and set it's text to this entry's name. */
            var mediaHeading = document.createElement("h4");
            mediaHeading.textContent = curr.name;

            /* Create a div that will hold more information about this entry */
            var infoDiv = document.createElement("div");
            infoDiv.className = "info";

            /* Create a heading element (tier 5), to mark the "Score" heading */
            var scoreHeading = document.createElement("h5");
            scoreHeading.textContent = "Score:";

            /* Create an unordered list element that will be used to display score information for this entry. */
            var scoreList = document.createElement("ul");

            /* Go through all the score information for this entry, and create a list item for it. */
            for (var rubric in curr.scores.rubric) {
                (function() {
                    /* This is in a function wrapper so rubric and scoreList will not be lost. */
                    var currRubric = rubric;
                    var currScoreList = scoreList;

                    /* We don't need to look for a max for the "NumberOfJudges" rubric, so if we're currently at it, return. */
                    if (currRubric === "NumberOfJudges") {
                        return;
                    }

                    var val = Math.floor(curr.scores.rubric[rubric].avg);

                    Contest_Judging_System.getRubrics(function(rubrics) {
                        var max = rubrics[currRubric].max;
                        /* Credit to @NobleMushtak for the following idea. */
                        var selectedRubric = currRubric.replace(/_/gi, " ");

                        if (rubrics[currRubric].hasOwnProperty("keys")) {
                            console.log(rubrics[currRubric].keys);
                            val = rubrics[currRubric].keys[val];
                            console.log("Value switched to a key!");

                            var listItem = document.createElement("li");
                            listItem.textContent = selectedRubric + ": " + val;

                            currScoreList.appendChild(listItem);
                            console.log(listItem);
                        } else {
                            var listItem = document.createElement("li");
                            listItem.textContent = selectedRubric + ": " + val + " out of " + max;
                            currScoreList.appendChild(listItem);
                            console.log(listItem);
                        }
                    });
                })();
            }

            /* Append everything */
            infoDiv.appendChild(scoreHeading);
            infoDiv.appendChild(scoreList);
            aElem.appendChild(mediaObj);
            mediaLeftDiv.appendChild(aElem);
            mediaBody.appendChild(mediaHeading);
            mediaListItem.appendChild(mediaLeftDiv);
            mediaBody.appendChild(infoDiv);
            mediaListItem.appendChild(mediaBody);
            entriesList.appendChild(mediaListItem);
        }

		/* Hide the loading div and show items that were hidden during loading. */
		$("#loading").css("display", "none");
		$(".hideWhileLoad").css("display", "block");
	});
});<|endoftext|>


<commit_before>'use strict';

var memoize        = require('memoizee/plain')
  , validDb        = require('dbjs/valid-dbjs')
  , defineFile     = require('dbjs-ext/object/file')
  , defineJpegFile = require('dbjs-ext/object/file/image-file/jpeg-file')
  , docMimeTypes   = require('../utils/microsoft-word-doc-mime-types');

module.exports = memoize(function (db) {
	var File, JpegFile;
	validDb(db);
	File               = defineFile(db);
	File.prototype.url = function () {
		return this.path ? '/' + this.path.split('/').map(encodeURIComponent).join('/') : null;
	};
	JpegFile = defineJpegFile(db);
	File.prototype.defineProperties({
		preview: { type: File, value: function () {
			return this.isPreviewGenerated ? this.generatedPreview : this;
		} },
		isPreviewGenerated: { type: db.Boolean, value: true },
		generatedPreview: { type: File, nested: true },
		thumb: { type: JpegFile, nested: true }
	});
	File.accept = ['image/jpeg', 'application/pdf', 'image/png'].concat(docMimeTypes);

	return File;
}, { normalizer: require('memoizee/normalizers/get-1')() });
<commit_msg>Add File methods for proper JSON snapshots<commit_after>'use strict';

var memoize        = require('memoizee/plain')
  , validDb        = require('dbjs/valid-dbjs')
  , defineFile     = require('dbjs-ext/object/file')
  , defineJpegFile = require('dbjs-ext/object/file/image-file/jpeg-file')
  , docMimeTypes   = require('../utils/microsoft-word-doc-mime-types');

module.exports = memoize(function (db) {
	var File, JpegFile;
	validDb(db);
	File               = defineFile(db);
	File.prototype.url = function () {
		return this.path ? '/' + this.path.split('/').map(encodeURIComponent).join('/') : null;
	};
	JpegFile = defineJpegFile(db);
	File.prototype.defineProperties({
		preview: { type: File, value: function () {
			return this.isPreviewGenerated ? this.generatedPreview : this;
		} },
		isPreviewGenerated: { type: db.Boolean, value: true },
		generatedPreview: { type: File, nested: true },
		thumb: { type: JpegFile, nested: true },
		toJSON: { value: function (descriptor) {
			return { kind: 'file', url: this.url, thumbUrl: this.thumb.url };
		} },
		isEmpty: { value: function (ignore) { return !this.path; } }
	});
	File.accept = ['image/jpeg', 'application/pdf', 'image/png'].concat(docMimeTypes);

	return File;
}, { normalizer: require('memoizee/normalizers/get-1')() });
<|endoftext|>


<commit_before>(function () {
    "use strict";
    /*global Cesium,Sandbox*/

    Sandbox.BingMaps = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // Bing Maps
            var bing = new Cesium.BingMapsTileProvider({
                server : 'dev.virtualearth.net',
                mapStyle : Cesium.BingMapsStyle.AERIAL,
                // Some versions of Safari support WebGL, but don't correctly implement
                // cross-origin image loading, so we need to load Bing imagery using a proxy.
                proxy : Cesium.FeatureDetection.supportsCrossOriginImagery() ? undefined : new Cesium.DefaultProxy('/proxy/')
            });

            primitives.getCentralBody().dayTileProvider = bing;
        };
    };

    Sandbox.ArcGIS = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // ArcGIS World Street Maps
            var arcgis = new Cesium.ArcGISMapServerTileProvider({
                host : 'server.arcgisonline.com',
                root : 'ArcGIS/rest',
                service : 'World_Street_Map',
                proxy : new Cesium.DefaultProxy('/proxy/')
            });

            primitives.getCentralBody().dayTileProvider = arcgis;
        };
    };

    Sandbox.OSM = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // OpenStreetMaps
            var osm = new Cesium.OpenStreetMapTileProvider({
                proxy : new Cesium.DefaultProxy('/proxy/')
            });

            primitives.getCentralBody().dayTileProvider = osm;
        };
    };

    Sandbox.MQOSM = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // MapQuest OpenStreetMaps
            var mqOsm = new Cesium.OpenStreetMapTileProvider({
                url : 'http://otile1.mqcdn.com/tiles/1.0.0/osm/',
                proxy : new Cesium.DefaultProxy('/proxy/')
            });

            primitives.getCentralBody().dayTileProvider = mqOsm;
        };
    };

    Sandbox.MQAerialOSM = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // MapQuest Aerial OpenStreetMaps
            var mqAerialOsm = new Cesium.OpenStreetMapTileProvider({
                url : 'http://oatile1.mqcdn.com/naip/',
                proxy : new Cesium.DefaultProxy('/proxy/')
            });

            primitives.getCentralBody().dayTileProvider = mqAerialOsm;
        };
    };

    Sandbox.Stamen = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // Stamen maps: http://maps.stamen.com
            // Other map urls:
            // * http://tile.stamen.com/watercolor/
            // * http://tile.stamen.com/terrain/
            var layer = new Cesium.OpenStreetMapTileProvider({
                url : 'http://tile.stamen.com/toner/',
                fileExtension : 'jpg',
                proxy : new Cesium.DefaultProxy('/proxy/'),
                credit : 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA.'
            });

            primitives.getCentralBody().dayTileProvider = layer;
        };
    };

    Sandbox.Single = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // Single texture
            var single = new Cesium.SingleTileProvider('Images/NE2_50M_SR_W_4096.jpg');

            primitives.getCentralBody().dayTileProvider = single;
        };
    };

    Sandbox.CompositeTiler = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // Bing Maps
            var bing = new Cesium.BingMapsTileProvider({
                server : 'dev.virtualearth.net',
                mapStyle : Cesium.BingMapsStyle.AERIAL,
                // Some versions of Safari support WebGL, but don't correctly implement
                // cross-origin image loading, so we need to load Bing imagery using a proxy.
                proxy : Cesium.FeatureDetection.supportsCrossOriginImagery() ? undefined : new Cesium.DefaultProxy('/proxy/')
            });

            // Single texture
            var single = new Cesium.SingleTileProvider('Images/NE2_50M_SR_W_4096.jpg');

            // Composite tile provider
            var composite = new Cesium.CompositeTileProvider([{
                provider : single,
                height : 1000000
            }, {
                provider : bing,
                height : 0
            }], scene.getCamera(), ellipsoid);

            primitives.getCentralBody().dayTileProvider = composite;
        };
    };

}());
<commit_msg>Update Sandbox to call correct constructor.<commit_after>(function () {
    "use strict";
    /*global Cesium,Sandbox*/

    Sandbox.BingMaps = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // Bing Maps
            var bing = new Cesium.BingMapsTileProvider({
                server : 'dev.virtualearth.net',
                mapStyle : Cesium.BingMapsStyle.AERIAL,
                // Some versions of Safari support WebGL, but don't correctly implement
                // cross-origin image loading, so we need to load Bing imagery using a proxy.
                proxy : Cesium.FeatureDetection.supportsCrossOriginImagery() ? undefined : new Cesium.DefaultProxy('/proxy/')
            });

            primitives.getCentralBody().dayTileProvider = bing;
        };
    };

    Sandbox.ArcGIS = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // ArcGIS World Street Maps
            var arcgis = new Cesium.ArcGISMapServerTileProvider({
                url : 'http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
                proxy : new Cesium.DefaultProxy('/proxy/')
            });

            primitives.getCentralBody().dayTileProvider = arcgis;
        };
    };

    Sandbox.OSM = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // OpenStreetMaps
            var osm = new Cesium.OpenStreetMapTileProvider({
                proxy : new Cesium.DefaultProxy('/proxy/')
            });

            primitives.getCentralBody().dayTileProvider = osm;
        };
    };

    Sandbox.MQOSM = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // MapQuest OpenStreetMaps
            var mqOsm = new Cesium.OpenStreetMapTileProvider({
                url : 'http://otile1.mqcdn.com/tiles/1.0.0/osm/',
                proxy : new Cesium.DefaultProxy('/proxy/')
            });

            primitives.getCentralBody().dayTileProvider = mqOsm;
        };
    };

    Sandbox.MQAerialOSM = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // MapQuest Aerial OpenStreetMaps
            var mqAerialOsm = new Cesium.OpenStreetMapTileProvider({
                url : 'http://oatile1.mqcdn.com/naip/',
                proxy : new Cesium.DefaultProxy('/proxy/')
            });

            primitives.getCentralBody().dayTileProvider = mqAerialOsm;
        };
    };

    Sandbox.Stamen = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // Stamen maps: http://maps.stamen.com
            // Other map urls:
            // * http://tile.stamen.com/watercolor/
            // * http://tile.stamen.com/terrain/
            var layer = new Cesium.OpenStreetMapTileProvider({
                url : 'http://tile.stamen.com/toner/',
                fileExtension : 'jpg',
                proxy : new Cesium.DefaultProxy('/proxy/'),
                credit : 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA.'
            });

            primitives.getCentralBody().dayTileProvider = layer;
        };
    };

    Sandbox.Single = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // Single texture
            var single = new Cesium.SingleTileProvider('Images/NE2_50M_SR_W_4096.jpg');

            primitives.getCentralBody().dayTileProvider = single;
        };
    };

    Sandbox.CompositeTiler = function (scene, ellipsoid, primitives) {
        this.code = function () {
            // Bing Maps
            var bing = new Cesium.BingMapsTileProvider({
                server : 'dev.virtualearth.net',
                mapStyle : Cesium.BingMapsStyle.AERIAL,
                // Some versions of Safari support WebGL, but don't correctly implement
                // cross-origin image loading, so we need to load Bing imagery using a proxy.
                proxy : Cesium.FeatureDetection.supportsCrossOriginImagery() ? undefined : new Cesium.DefaultProxy('/proxy/')
            });

            // Single texture
            var single = new Cesium.SingleTileProvider('Images/NE2_50M_SR_W_4096.jpg');

            // Composite tile provider
            var composite = new Cesium.CompositeTileProvider([{
                provider : single,
                height : 1000000
            }, {
                provider : bing,
                height : 0
            }], scene.getCamera(), ellipsoid);

            primitives.getCentralBody().dayTileProvider = composite;
        };
    };

}());
<|endoftext|>


<commit_before>// Test the widget framework.
casper.notebook_test(function () {
    var index;

    // Test widget dependencies ////////////////////////////////////////////////
    this.then(function () {

        // Check if the WidgetManager class is defined.
        this.test.assert(this.evaluate(function() {
            return IPython.WidgetManager != undefined;
        }), 'WidgetManager class is defined');
    });

    index = this.append_cell(
        'from IPython.html import widgets\n' +
        'from IPython.display import display, clear_output\n' +
        'print("Success")');
    this.execute_cell_then(index);

    this.wait(500); // Wait for require.js async callbacks to load dependencies.

    this.then(function () {
        // Check if the widget manager has been instanciated.
        this.test.assert(this.evaluate(function() {
            return IPython.widget_manager != undefined;
        }), 'Notebook widget manager instanciated');
    });

    // Check widget mapping ////////////////////////////////////////////////////
    index = this.append_cell(
        'names = [name for name in dir(widgets)' +
        ' if name.endswith("Widget") and name!= "Widget"]\n' +
        'for name in names:\n' +
        '    print(name)\n');
    this.execute_cell_then(index, function(index){

        // Get the widget names that are registered with the widget manager.  Assume
        // a 1 to 1 mapping of model and widgets names (model names just have 'model'
        // suffixed).
        var javascript_names = this.evaluate(function () {
            names = [];
            for (var name in IPython.widget_manager.widget_model_types) {
                names.push(name.replace('Model',''));
            }
            return names;
        });

        // Get the widget names registered in python.
        var python_names = this.get_output_cell(index).text.split('\n');

        // Make sure the two lists have the same items.
        for (var i in javascript_names) {
            var javascript_name = javascript_names[i];
            var found = false;
            for (var j in python_names) {
                var python_name = python_names[j];
                if (python_name==javascript_name) {
                    found = true;
                    break;
                }
            }
            this.test.assert(found, javascript_name + ' exists in python');
        }
        for (var i in python_names) {
            var python_name = python_names[i];
            if (python_name.length > 0) {
                var found = false;
                for (var j in javascript_names) {
                    var javascript_name = javascript_names[j];
                    if (python_name==javascript_name) {
                        found = true;
                        break;
                    }
                }
                this.test.assert(found, python_name + ' exists in javascript');
            }
        }
    });

    // Test bool widget ////////////////////////////////////////////////////////
    var bool_index = this.append_cell(
        'bool_widget = widgets.BoolWidget(description="Title")\n' +
        'display(bool_widget)\n'+
        'display(bool_widget, view_name="ToggleButtonView")\n' +
        'print("Success")');
    this.execute_cell_then(bool_index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Create bool widget cell executed with correct output.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea'),
            'Widget subarea exists.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea .widget-hbox-single input'),
            'Checkbox exists.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea .widget-hbox-single .widget-hlabel'),
            'Checkbox label exists.');

        this.test.assert(this.cell_element_function(index,
            '.widget-area .widget-subarea .widget-hbox-single .widget-hlabel', 'html')=="Title",
            'Checkbox labeled correctly.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea div button'),
            'Toggle button exists.');

        this.test.assert(this.cell_element_function(index,
            '.widget-area .widget-subarea div button', 'html')=="Title",
            'Toggle button labeled correctly.');

    });

    // Test button widget //////////////////////////////////////////////////////
    var button_index = this.append_cell(
        'button = widgets.ButtonWidget(description="Title")\n' +
        'display(button)\n'+
        'print("Success")\n' +
        'def handle_click(sender):\n' +
        '    print("Clicked")\n' +
        'button.on_click(handle_click)');
    this.execute_cell_then(button_index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Create button cell executed with correct output.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea'),
            'Widget subarea exists.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea button'),
            'Widget button exists.');

        this.test.assert(this.cell_element_function(index,
            '.widget-area .widget-subarea button', 'html')=='Title',
            'Set button description.');

        this.cell_element_function(index,
            '.widget-area .widget-subarea button', 'click');
    });

    this.wait(500); // Wait for click to execute in kernel and write output

    this.then(function () {
        this.test.assert(this.get_output_cell(button_index, 1).text == 'Clicked\n',
            'Button click event fires.');
    });

    index = this.append_cell(
        'button.close()\n'+
        'print("Success")\n');
    this.execute_cell_then(index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Close button cell executed with correct output.');

        this.test.assert(! this.cell_element_exists(button_index,
            '.widget-area .widget-subarea button'),
            'Widget button doesn\'t exists.');
    });
});

<commit_msg>Added test to check initial states of bool views<commit_after>// Test the widget framework.
casper.notebook_test(function () {
    var index;

    // Test widget dependencies ////////////////////////////////////////////////
    this.then(function () {

        // Check if the WidgetManager class is defined.
        this.test.assert(this.evaluate(function() {
            return IPython.WidgetManager != undefined;
        }), 'WidgetManager class is defined');
    });

    index = this.append_cell(
        'from IPython.html import widgets\n' +
        'from IPython.display import display, clear_output\n' +
        'print("Success")');
    this.execute_cell_then(index);

    this.wait(500); // Wait for require.js async callbacks to load dependencies.

    this.then(function () {
        // Check if the widget manager has been instanciated.
        this.test.assert(this.evaluate(function() {
            return IPython.widget_manager != undefined;
        }), 'Notebook widget manager instanciated');
    });

    // Check widget mapping ////////////////////////////////////////////////////
    index = this.append_cell(
        'names = [name for name in dir(widgets)' +
        ' if name.endswith("Widget") and name!= "Widget"]\n' +
        'for name in names:\n' +
        '    print(name)\n');
    this.execute_cell_then(index, function(index){

        // Get the widget names that are registered with the widget manager.  Assume
        // a 1 to 1 mapping of model and widgets names (model names just have 'model'
        // suffixed).
        var javascript_names = this.evaluate(function () {
            names = [];
            for (var name in IPython.widget_manager.widget_model_types) {
                names.push(name.replace('Model',''));
            }
            return names;
        });

        // Get the widget names registered in python.
        var python_names = this.get_output_cell(index).text.split('\n');

        // Make sure the two lists have the same items.
        for (var i in javascript_names) {
            var javascript_name = javascript_names[i];
            var found = false;
            for (var j in python_names) {
                var python_name = python_names[j];
                if (python_name==javascript_name) {
                    found = true;
                    break;
                }
            }
            this.test.assert(found, javascript_name + ' exists in python');
        }
        for (var i in python_names) {
            var python_name = python_names[i];
            if (python_name.length > 0) {
                var found = false;
                for (var j in javascript_names) {
                    var javascript_name = javascript_names[j];
                    if (python_name==javascript_name) {
                        found = true;
                        break;
                    }
                }
                this.test.assert(found, python_name + ' exists in javascript');
            }
        }
    });

    // Test bool widget ////////////////////////////////////////////////////////
    var bool_index = this.append_cell(
        'bool_widget = widgets.BoolWidget(description="Title", value=True)\n' +
        'display(bool_widget)\n'+
        'display(bool_widget, view_name="ToggleButtonView")\n' +
        'print("Success")');
    this.execute_cell_then(bool_index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Create bool widget cell executed with correct output.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea'),
            'Widget subarea exists.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea .widget-hbox-single input'),
            'Checkbox exists.');

        this.test.assert(this.cell_element_function(index,
            '.widget-area .widget-subarea .widget-hbox-single input', 'val')==true,
            'Checkbox is checked.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea .widget-hbox-single .widget-hlabel'),
            'Checkbox label exists.');

        this.test.assert(this.cell_element_function(index,
            '.widget-area .widget-subarea .widget-hbox-single .widget-hlabel', 'html')=="Title",
            'Checkbox labeled correctly.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea div button'),
            'Toggle button exists.');

        this.test.assert(this.cell_element_function(index,
            '.widget-area .widget-subarea div button', 'html')=="Title",
            'Toggle button labeled correctly.');

        this.test.assert(this.cell_element_function(index,
            '.widget-area .widget-subarea div button', 'hasClass', ['active']),
            'Toggle button is toggled.');

    });

    // Test button widget //////////////////////////////////////////////////////
    var button_index = this.append_cell(
        'button = widgets.ButtonWidget(description="Title")\n' +
        'display(button)\n'+
        'print("Success")\n' +
        'def handle_click(sender):\n' +
        '    print("Clicked")\n' +
        'button.on_click(handle_click)');
    this.execute_cell_then(button_index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Create button cell executed with correct output.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea'),
            'Widget subarea exists.');

        this.test.assert(this.cell_element_exists(index,
            '.widget-area .widget-subarea button'),
            'Widget button exists.');

        this.test.assert(this.cell_element_function(index,
            '.widget-area .widget-subarea button', 'html')=='Title',
            'Set button description.');

        this.cell_element_function(index,
            '.widget-area .widget-subarea button', 'click');
    });

    this.wait(500); // Wait for click to execute in kernel and write output

    this.then(function () {
        this.test.assert(this.get_output_cell(button_index, 1).text == 'Clicked\n',
            'Button click event fires.');
    });

    index = this.append_cell(
        'button.close()\n'+
        'print("Success")\n');
    this.execute_cell_then(index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Close button cell executed with correct output.');

        this.test.assert(! this.cell_element_exists(button_index,
            '.widget-area .widget-subarea button'),
            'Widget button doesn\'t exists.');
    });
});

<|endoftext|>


<commit_before>// namespace
var MPLAY = MPLAY || {};

(function() {
	"use_strict";

	/**
	 *
	 * @class Page1_1
	 * @augments MPLAY.MPlayPage
	 */
	var Page1_1 = function() {
		MPLAY.MPlayPage.call(this);
	};

	Page1_1.prototype = Object.create(MPLAY.MPlayPage.prototype);
	Page1_1.prototype.constructor = Page1_1;

	/**
	 * @override
	 */
	Page1_1.prototype._onLoad = function() {
		MPLAY.MPlayPage.prototype._onLoad.call(this);

		var foregroundImg = "/static/gnovel/res/textures/backgrounds/uc foreground with characters.png";
		this.setupUcBackground(foregroundImg);

		this._background_empty = this.createImage("/static/gnovel/res/textures/backgrounds/uc foreground png.png", new THREE.Vector3(0, 0, this._background3Layer-1), 1920, 1080);
		//this._background_empty.scale.set(.90,.85,1);
		this._background_empty.material.opacity = 0;
		this._background_empty.scale.set(.85, .80, 1);
		this._addToSceneBg(this._background_empty);

		var geometry = new THREE.PlaneBufferGeometry(1920, 1080);
		var material = new THREE.MeshBasicMaterial( {color: 0x000000, transparent:true } );
		this._transitionBgImg = new THREE.Mesh(geometry,material);
		this._transitionBgImg.position.z = 150;

		this._transitionBg = "transitionbg";

		this._setObjectTag(this._transitionBg,this._transitionBgImg);
	};

	Page1_1.prototype._createFlowElements = function() {
		var priya = "%" + this._priya;
		var ryan = "%" + this._ryan;
		var cat = "%" + this._cat;
		var transitionBg = "%" + this._transitionBg;
		var background = this._background_empty;

		var o = null;

		var catsPhoneStatus = this._owner.getSavedData("catsPhoneStatus");

		// variables from scene 1
		var isWalletWithWaiter = (catsPhoneStatus == 0 || catsPhoneStatus == 2);
		var player = this._player;

			o = [
				//FIXME transition of this flow doesn't work
				//FIXME Adjust positions for characters too!
				// {type: "show_context", text: "Right after class, you meet up with your study group in the CUC.", waitUntilShown: true},
				//switch foreground with empty foreground
				// 	{type: "custom", func: function(page){
				// 		page.tweenMat(background,{
				// 			opacity: 1,
				// 			easing: TWEEN.Easing.Cubic.Out,
				// 			duration: 200,
				// 		});
				// 		page.tweenMat(page._background3,{
				// 			opacity: 0,
				// 			easing: TWEEN.Easing.Cubic.Out,
				// 			duration: 800,
				// 			onComplete: function() {
				// 				page._removeFromSceneBg(page._background3);
				// 			},
				// 		});
				// 	}},
				// {type: "show", img: ryan, expression: "happy", position: "center", waitUntilShown: false},
				// /*{type: "custom", func: function(page) {
				// 	page.getOwner().getSoundManager().play("Hey-Ryan-e");
				// }},*/
				// // {type: "play", audio: "Hey-Ryan-e"},
				// {type: "dialog", speaker: "Ryan", position: "left", text: "Awesome!  Both you and Priya are in my group.  This is Priya.  I told you about her earlier."},
				// // transition of this flow doesn't work
				// {type: "hide", img: ryan, waitUntilHidden: false},
				// // transition of this flow doesn't work
				// {type: "show", img: priya, expression: "happy", position: "left", waitUntilShown: false},
				// // {type: "custom", func: function(page) {
				// // 	page.getOwner().getSoundManager().play("Hello-Priya");
				// // }},
				// // {type: "play", audio: "Hello-Priya"},
				// {type: "dialog", speaker: "Priya", text: "Ryan here helped me so much last semester.  Always goes out of his way.  Nice to meet you."},
				// // transition of this flow doesn't work
				// {type: "hide", img: priya, waitUntilHidden: false},
				// // transition of this flow doesn't work
				//
				// {type: "show", img: cat, expression: "sad", position: "right", waitUntilShown: false, flip: true},
				// // {type: "play", audio: "Ohhi-Cat"},
				// {type: "dialog", speaker: "Cat", position: "right", text: "Hey, my name is Cat. Uhh… sorry I’m a little distracted. I lost my wallet yesterday."},
				// {type: "show", img: ryan, expression: "thoughtful", position: "left", waitUntilShown: false},
				//
				// //
				// {type: "compare", leftop: isWalletWithWaiter, operator: "equal", rightop: 1, goTrue: "#wallet_withwaiter", goFalse: "#wallet_atpolice"},
				// {type: "dialog", speaker: "Ryan", text: "Were you at Scottie's yesterday?  We found a wallet there. Might be yours.", label: "wallet_withwaiter"},
				// {type: "show", img: cat, expression: "happy", position: "right", waitUntilShown: false, flip: true},
				// {type: "dialog", speaker: "Cat", text: "That’s great! Do you guys have it with you?"},
				// {type: "show", img: ryan, position: "left", waitUntilShown: false},
				// {type: "dialog", speaker: "Ryan", text: "We left it with the waiter."},
				// {type: "hide", img: ryan},
				// {type: "show", img: priya, expression: "happy", position: "left", waitUntilShown: false},
				// {type: "custom", func: function(page) {
				// 	return page.getRelationshipManager().getRelationship("Priya");
				// }, label: "priyaRelationshipScore"},
				// {type: "compare", leftop: "$priyaRelationshipScore", operator: "greater", rightop: 0, goTrue: "#chances", goFalse: "#checkout"},
				// {type: "dialog", speaker: "Priya", text: "What are the chances!", label: "chances"},
				// {type: "jump", condition: true, goTrue: "#aside1", goFalse: "#aside1"},
				// {type: "jump", condition: true, goTrue: 1000, goFalse: 1000},
				//
				// {type: "dialog", speaker: "Priya", text: "It’s worth checking out.", label: "checkout"},
				// {type: "jump", condition: true, goTrue: "#aside1", goFalse: "#aside1"},
				// {type: "jump", condition: true, goTrue: 1000, goFalse: 1000},
				//
				// //if You left it with the bartender
				//
				// // if you have the phone with you
				// {type: "show", img: ryan, position: "center", expression: "thoughtful", waitUntilShown: false, label: "wallet_atpolice"},
				// {type: "custom", func: function(page) {
				// 	page.getRelationshipManager().addRelationship("Cat", 1);
				// 	page.getRelationshipManager().addRelationship("Priya", 1);
				// }},
				// {type: "dialog", speaker: "Ryan", position: "left", text: "Cat, is your last name Davis? " + player + " and I found a wallet at Scottie’s yesterday. We turned it into campus police."},
				// {type: "show", img: cat, position: "right", expression: "happy", waitUntilShown: false, flip: true},
				// {type: "dialog", speaker: "Cat", text: "That's great, you're both lifesavers!"},
				// // {type: "choices", choices : [{text: "No Problem.", go: "#lifesaver"}, {text : "Happy to help!", go : "#lifesaver"}]},
				// {type: "custom", func: function(page) {
				// 	return page.getRelationshipManager().getRelationship("Ryan");
				// }, label: "ryanRelationshipScore"},
				// {type: "compare", leftop: "$ryanRelationshipScore", operator: "greater", rightop: 0, goTrue: "#happyryan", goFalse: "#neutralryan"},
				//
				// {type: "show", img: ryan, expression: "happy", position: "left", waitUntilShown: false, label: "happyryan"},
				// {type: "dialog", speaker: "Ryan", text: player + " here is the lifesaver, I'm just the messenger"},
				// {type: "jump", condition: true, goTrue: "#aside1", goFalse: "#aside1"},
				//
				// {type: "show", img: ryan, position: "left", waitUntilShown: false, label: "neutralryan"},
				// {type: "dialog", speaker: "Ryan", text: "Yeah, lucky break."},
				// {type: "jump", condition: true, goTrue: "#aside1", goFalse: "#aside1"},
				//
				// // if you left the phone at the bar
				// /*{type: "show", img: ryan, label: "phone_notpicked"},
				// {type: "dialog", speaker: "Ryan", text: "I think there was a phone at Scottie's yesterday? We found a phone there."},
				// {type: "hide", img: ryan, waitUntilHidden: false},
				// {type: "show", img: cat, flip: true},
				// {type: "dialog", speaker: "Cat", text: "Hopefully it’s still there.  I’ll call them."},
				// {type: "hide", img: cat, waitUntilHidden: false},
				// */
				//
				// {type: "nothing", label: "aside1"},
				// {type: "hide", img: ryan},
				// {type: "hide", img: cat},
				// {type: "hide", img: priya},
				// {type: "show_context", text: "The group leaves...some time passes"},
				//
				// {type: "open_phone", layout:"text", people: [this._priya, this._ryan, this._cat]},
				// {type: "add_phone_textbox",
				// 	speaker: this._priya,
				// 	text: "I’m going to grab a coffee – anyone want to join?"},
				// {type: "add_phone_textbox",
				// 	speaker: this._cat,
				// 	text: "Thx!  But I’m actually at the gym right now.  U guys should come!"},
				// {type: "add_phone_textbox",
				// 	speaker: this._ryan,
				// 	text: "Can’t – wish I could join for coffee, need to study.  My comp systems class is kicking my ass!"},
				//
				// {type: "choices",
				// choices :
				// 	[{text: "Grab a coffee at the café with Priya.", go: "#gocafe", relationship: [{name:this._priya, score:1}]},
				// 	{text : "Workout at the gym with Cat.", go : "#gogym", relationship: [{name:this._cat, score:1}]},
				// 	{text: "Head home for the day.", go: "#gohome"}]
				// },
				// {type: "close_phone", label: "gocafe"},
				// {type: "goto", page: "scene 3.a"},
				// {type: "close_phone", label: "gogym"},
				// {type: "goto", page: "scene 3.b"},
				//
				// {type: "close_phone", label: "gohome"},
				// /*{type: "custom", func: function(page) {
				// 	page.getRelationshipManager().addRelationship("Cat", -1);
				// 	page.getRelationshipManager().addRelationship("Priya", -1);
				// }},*/
				// {type: "goto", page: "scene 4"},
			];

		return o;
	};

	Page1_1.prototype._createRandomPlaylist = function() {
		var playlist = null;
		playlist = [
					{audio:"Uc-girllaughing", playrate: 0.02, noreplay: true},
					{audio:"Uc-mantalking", playrate: 0.02, noreplay: true},
					{audio:"Uc-womantalking", playrate: 0.03, noreplay: true},
					{audio:"Uc-steps", playrate: 0.1}
					];
		return playlist;
	};

	/**
	 * @override
	 */
	Page1_1.prototype._onUnload = function() {
		MPLAY.MPlayPage.prototype._onUnload.call(this);

		if (this._owner._ambient != null) {
			this._tweenVolumeOut();
		}
	};

	Page1_1.prototype._onStart = function() {
		MPLAY.MPlayPage.prototype._onStart.call(this);

		this._owner._ambient = this._owner.getSoundManager().play("UC-bg", {interrupt: this._owner.getSoundManager().INTERRUPT_ANY, loop: -1, volume: 0.0});
		this._tweenVolumeIn();
	};

	/**
	 * @override
	 */
	Page1_1.prototype._update = function() {
		MPLAY.MPlayPage.prototype._update.call(this);

		this._multiTracksPlayer.shuffle();
	};

	MPLAY.Page1_1 = Page1_1;
}());
<commit_msg>reverted page1_1.js<commit_after>// namespace
var MPLAY = MPLAY || {};

(function() {
	"use_strict";

	/**
	 *
	 * @class Page1_1
	 * @augments MPLAY.MPlayPage
	 */
	var Page1_1 = function() {
		MPLAY.MPlayPage.call(this);
	};

	Page1_1.prototype = Object.create(MPLAY.MPlayPage.prototype);
	Page1_1.prototype.constructor = Page1_1;

	/**
	 * @override
	 */
	Page1_1.prototype._onLoad = function() {
		MPLAY.MPlayPage.prototype._onLoad.call(this);

		var foregroundImg = "/static/gnovel/res/textures/backgrounds/uc foreground with characters.png";
		this.setupUcBackground(foregroundImg);

		this._background_empty = this.createImage("/static/gnovel/res/textures/backgrounds/uc foreground png.png", new THREE.Vector3(0, 0, this._background3Layer-1), 1920, 1080);
		//this._background_empty.scale.set(.90,.85,1);
		this._background_empty.material.opacity = 0;
		this._background_empty.scale.set(.85, .80, 1);
		this._addToSceneBg(this._background_empty);

		var geometry = new THREE.PlaneBufferGeometry(1920, 1080);
		var material = new THREE.MeshBasicMaterial( {color: 0x000000, transparent:true } );
		this._transitionBgImg = new THREE.Mesh(geometry,material);
		this._transitionBgImg.position.z = 150;

		this._transitionBg = "transitionbg";

		this._setObjectTag(this._transitionBg,this._transitionBgImg);
	};

	Page1_1.prototype._createFlowElements = function() {
		var priya = "%" + this._priya;
		var ryan = "%" + this._ryan;
		var cat = "%" + this._cat;
		var transitionBg = "%" + this._transitionBg;
		var background = this._background_empty;

		var o = null;

		var catsPhoneStatus = this._owner.getSavedData("catsPhoneStatus");

		// variables from scene 1
		var isWalletWithWaiter = (catsPhoneStatus == 0 || catsPhoneStatus == 2);
		var player = this._player;

			o = [
				//FIXME transition of this flow doesn't work
				//FIXME Adjust positions for characters too!
				{type: "show_context", text: "Right after class, you meet up with your study group in the CUC.", waitUntilShown: true},
				//switch foreground with empty foreground
					{type: "custom", func: function(page){
						page.tweenMat(background,{
							opacity: 1,
							easing: TWEEN.Easing.Cubic.Out,
							duration: 200,
						});
						page.tweenMat(page._background3,{
							opacity: 0,
							easing: TWEEN.Easing.Cubic.Out,
							duration: 800,
							onComplete: function() {
								page._removeFromSceneBg(page._background3);
							},
						});
					}},
				{type: "show", img: ryan, expression: "happy", position: "center", waitUntilShown: false},
				/*{type: "custom", func: function(page) {
					page.getOwner().getSoundManager().play("Hey-Ryan-e");
				}},*/
				// {type: "play", audio: "Hey-Ryan-e"},
				{type: "dialog", speaker: "Ryan", position: "left", text: "Awesome!  Both you and Priya are in my group.  This is Priya.  I told you about her earlier."},
				// transition of this flow doesn't work
				{type: "hide", img: ryan, waitUntilHidden: false},
				// transition of this flow doesn't work
				{type: "show", img: priya, expression: "happy", position: "left", waitUntilShown: false},
				// {type: "custom", func: function(page) {
				// 	page.getOwner().getSoundManager().play("Hello-Priya");
				// }},
				// {type: "play", audio: "Hello-Priya"},
				{type: "dialog", speaker: "Priya", text: "Ryan here helped me so much last semester.  Always goes out of his way.  Nice to meet you."},
				// transition of this flow doesn't work
				{type: "hide", img: priya, waitUntilHidden: false},
				// transition of this flow doesn't work

				{type: "show", img: cat, expression: "sad", position: "right", waitUntilShown: false, flip: true},
				// {type: "play", audio: "Ohhi-Cat"},
				{type: "dialog", speaker: "Cat", position: "right", text: "Hey, my name is Cat. Uhh… sorry I’m a little distracted. I lost my wallet yesterday."},
				{type: "show", img: ryan, expression: "thoughtful", position: "left", waitUntilShown: false},

				//
				{type: "compare", leftop: isWalletWithWaiter, operator: "equal", rightop: 1, goTrue: "#wallet_withwaiter", goFalse: "#wallet_atpolice"},
				{type: "dialog", speaker: "Ryan", text: "Were you at Scottie's yesterday?  We found a wallet there. Might be yours.", label: "wallet_withwaiter"},
				{type: "show", img: cat, expression: "happy", position: "right", waitUntilShown: false, flip: true},
				{type: "dialog", speaker: "Cat", text: "That’s great! Do you guys have it with you?"},
				{type: "show", img: ryan, position: "left", waitUntilShown: false},
				{type: "dialog", speaker: "Ryan", text: "We left it with the waiter."},
				{type: "hide", img: ryan},
				{type: "show", img: priya, expression: "happy", position: "left", waitUntilShown: false},
				{type: "custom", func: function(page) {
					return page.getRelationshipManager().getRelationship("Priya");
				}, label: "priyaRelationshipScore"},
				{type: "compare", leftop: "$priyaRelationshipScore", operator: "greater", rightop: 0, goTrue: "#chances", goFalse: "#checkout"},
				{type: "dialog", speaker: "Priya", text: "What are the chances!", label: "chances"},
				{type: "jump", condition: true, goTrue: "#aside1", goFalse: "#aside1"},
				{type: "jump", condition: true, goTrue: 1000, goFalse: 1000},

				{type: "dialog", speaker: "Priya", text: "It’s worth checking out.", label: "checkout"},
				{type: "jump", condition: true, goTrue: "#aside1", goFalse: "#aside1"},
				{type: "jump", condition: true, goTrue: 1000, goFalse: 1000},

				//if You left it with the bartender

				// if you have the phone with you
				{type: "show", img: ryan, position: "center", expression: "thoughtful", waitUntilShown: false, label: "wallet_atpolice"},
				{type: "custom", func: function(page) {
					page.getRelationshipManager().addRelationship("Cat", 1);
					page.getRelationshipManager().addRelationship("Priya", 1);
				}},
				{type: "dialog", speaker: "Ryan", position: "left", text: "Cat, is your last name Davis? " + player + " and I found a wallet at Scottie’s yesterday. We turned it into campus police."},
				{type: "show", img: cat, position: "right", expression: "happy", waitUntilShown: false, flip: true},
				{type: "dialog", speaker: "Cat", text: "That's great, you're both lifesavers!"},
				// {type: "choices", choices : [{text: "No Problem.", go: "#lifesaver"}, {text : "Happy to help!", go : "#lifesaver"}]},
				{type: "custom", func: function(page) {
					return page.getRelationshipManager().getRelationship("Ryan");
				}, label: "ryanRelationshipScore"},
				{type: "compare", leftop: "$ryanRelationshipScore", operator: "greater", rightop: 0, goTrue: "#happyryan", goFalse: "#neutralryan"},

				{type: "show", img: ryan, expression: "happy", position: "left", waitUntilShown: false, label: "happyryan"},
				{type: "dialog", speaker: "Ryan", text: player + " here is the lifesaver, I'm just the messenger"},
				{type: "jump", condition: true, goTrue: "#aside1", goFalse: "#aside1"},

				{type: "show", img: ryan, position: "left", waitUntilShown: false, label: "neutralryan"},
				{type: "dialog", speaker: "Ryan", text: "Yeah, lucky break."},
				{type: "jump", condition: true, goTrue: "#aside1", goFalse: "#aside1"},

				// if you left the phone at the bar
				/*{type: "show", img: ryan, label: "phone_notpicked"},
				{type: "dialog", speaker: "Ryan", text: "I think there was a phone at Scottie's yesterday? We found a phone there."},
				{type: "hide", img: ryan, waitUntilHidden: false},
				{type: "show", img: cat, flip: true},
				{type: "dialog", speaker: "Cat", text: "Hopefully it’s still there.  I’ll call them."},
				{type: "hide", img: cat, waitUntilHidden: false},
				*/

				{type: "nothing", label: "aside1"},
				{type: "hide", img: ryan},
				{type: "hide", img: cat},
				{type: "hide", img: priya},
				{type: "show_context", text: "The group leaves...some time passes"},

				{type: "open_phone", layout:"text", people: [this._priya, this._ryan, this._cat]},
				{type: "add_phone_textbox",
					speaker: this._priya,
					text: "I’m going to grab a coffee – anyone want to join?"},
				{type: "add_phone_textbox",
					speaker: this._cat,
					text: "Thx!  But I’m actually at the gym right now.  U guys should come!"},
				{type: "add_phone_textbox",
					speaker: this._ryan,
					text: "Can’t – wish I could join for coffee, need to study.  My comp systems class is kicking my ass!"},

				{type: "choices",
				choices :
					[{text: "Grab a coffee at the café with Priya.", go: "#gocafe", relationship: [{name:this._priya, score:1}]},
					{text : "Workout at the gym with Cat.", go : "#gogym", relationship: [{name:this._cat, score:1}]},
					{text: "Head home for the day.", go: "#gohome"}]
				},
				{type: "close_phone", label: "gocafe"},
				{type: "goto", page: "scene 3.a"},
				{type: "close_phone", label: "gogym"},
				{type: "goto", page: "scene 3.b"},

				{type: "close_phone", label: "gohome"},
				/*{type: "custom", func: function(page) {
					page.getRelationshipManager().addRelationship("Cat", -1);
					page.getRelationshipManager().addRelationship("Priya", -1);
				}},*/
				{type: "goto", page: "scene 4"},
			];

		return o;
	};

	Page1_1.prototype._createRandomPlaylist = function() {
		var playlist = null;
		playlist = [
					{audio:"Uc-girllaughing", playrate: 0.02, noreplay: true},
					{audio:"Uc-mantalking", playrate: 0.02, noreplay: true},
					{audio:"Uc-womantalking", playrate: 0.03, noreplay: true},
					{audio:"Uc-steps", playrate: 0.1}
					];
		return playlist;
	};

	/**
	 * @override
	 */
	Page1_1.prototype._onUnload = function() {
		MPLAY.MPlayPage.prototype._onUnload.call(this);

		if (this._owner._ambient != null) {
			this._tweenVolumeOut();
		}
	};

	Page1_1.prototype._onStart = function() {
		MPLAY.MPlayPage.prototype._onStart.call(this);

		this._owner._ambient = this._owner.getSoundManager().play("UC-bg", {interrupt: this._owner.getSoundManager().INTERRUPT_ANY, loop: -1, volume: 0.0});
		this._tweenVolumeIn();
	};

	/**
	 * @override
	 */
	Page1_1.prototype._update = function() {
		MPLAY.MPlayPage.prototype._update.call(this);

		this._multiTracksPlayer.shuffle();
	};

	MPLAY.Page1_1 = Page1_1;
}());
<|endoftext|>


<commit_before>/**
 * @author spite / http://www.clicktorelease.com/
 * @author mrdoob / http://mrdoob.com/
 */

THREE.BufferGeometryUtils = {

	fromGeometry: function geometryToBufferGeometry( geometry, settings ) {

		if ( geometry instanceof THREE.BufferGeometry ) {

			return geometry;

		}

		settings = settings || { 'vertexColors': THREE.NoColors };

		var vertices = geometry.vertices;
		var faces = geometry.faces;
		var faceVertexUvs = geometry.faceVertexUvs;
		var vertexColors = settings.vertexColors;
		var hasFaceVertexUv = faceVertexUvs[ 0 ].length > 0;
		var hasFaceVertexNormals = faces[ 0 ].vertexNormals.length == 3;

		var bufferGeometry = new THREE.BufferGeometry();

		bufferGeometry.attributes = {

			position: {
				itemSize: 3,
				array: new Float32Array( faces.length * 3 * 3 )
			},
			normal: {
				itemSize: 3,
				array: new Float32Array( faces.length * 3 * 3 )
			}

		}

		var positions = bufferGeometry.attributes.position.array;
		var normals = bufferGeometry.attributes.normal.array;

		if ( vertexColors !== THREE.NoColors ) {

			bufferGeometry.attributes.color = {
				itemSize: 3,
				array: new Float32Array( faces.length * 3 * 3 )
			};

			var colors = bufferGeometry.attributes.color.array;

		}

		if ( hasFaceVertexUv === true ) {

			bufferGeometry.attributes.uv = {
				itemSize: 2,
				array: new Float32Array( faces.length * 3 * 2 )
			};

			var uvs = bufferGeometry.attributes.uv.array;

		}

		var i2 = 0, i3 = 0;

		for ( var i = 0; i < faces.length; i ++ ) {

			var face = faces[ i ];

			var a = vertices[ face.a ];
			var b = vertices[ face.b ];
			var c = vertices[ face.c ];

			positions[ i3     ] = a.x;
			positions[ i3 + 1 ] = a.y;
			positions[ i3 + 2 ] = a.z;

			positions[ i3 + 3 ] = b.x;
			positions[ i3 + 4 ] = b.y;
			positions[ i3 + 5 ] = b.z;

			positions[ i3 + 6 ] = c.x;
			positions[ i3 + 7 ] = c.y;
			positions[ i3 + 8 ] = c.z;

			if ( hasFaceVertexNormals === true ) {

				var na = face.vertexNormals[ 0 ];
				var nb = face.vertexNormals[ 1 ];
				var nc = face.vertexNormals[ 2 ];

				normals[ i3     ] = na.x;
				normals[ i3 + 1 ] = na.y;
				normals[ i3 + 2 ] = na.z;

				normals[ i3 + 3 ] = nb.x;
				normals[ i3 + 4 ] = nb.y;
				normals[ i3 + 5 ] = nb.z;

				normals[ i3 + 6 ] = nc.x;
				normals[ i3 + 7 ] = nc.y;
				normals[ i3 + 8 ] = nc.z;

			} else {

				var n = face.normal;

				normals[ i3     ] = n.x;
				normals[ i3 + 1 ] = n.y;
				normals[ i3 + 2 ] = n.z;

				normals[ i3 + 3 ] = n.x;
				normals[ i3 + 4 ] = n.y;
				normals[ i3 + 5 ] = n.z;

				normals[ i3 + 6 ] = n.x;
				normals[ i3 + 7 ] = n.y;
				normals[ i3 + 8 ] = n.z;

			}

			if ( vertexColors === THREE.FaceColors ) {

				var fc = face.color;

				colors[ i3     ] = fc.r;
				colors[ i3 + 1 ] = fc.g;
				colors[ i3 + 2 ] = fc.b;

				colors[ i3 + 3 ] = fc.r;
				colors[ i3 + 4 ] = fc.g;
				colors[ i3 + 5 ] = fc.b;

				colors[ i3 + 6 ] = fc.r;
				colors[ i3 + 7 ] = fc.g;
				colors[ i3 + 8 ] = fc.b;

			} else if ( vertexColors === THREE.VertexColors ) {

				var vca = face.vertexColors[ 0 ];
				var vcb = face.vertexColors[ 1 ];
				var vcc = face.vertexColors[ 2 ];

				colors[ i3     ] = vca.r;
				colors[ i3 + 1 ] = vca.g;
				colors[ i3 + 2 ] = vca.b;

				colors[ i3 + 3 ] = vcb.r;
				colors[ i3 + 4 ] = vcb.g;
				colors[ i3 + 5 ] = vcb.b;

				colors[ i3 + 6 ] = vcc.r;
				colors[ i3 + 7 ] = vcc.g;
				colors[ i3 + 8 ] = vcc.b;

			}

			if ( hasFaceVertexUv === true ) {

				var uva = faceVertexUvs[ 0 ][ i ][ 0 ];
				var uvb = faceVertexUvs[ 0 ][ i ][ 1 ];
				var uvc = faceVertexUvs[ 0 ][ i ][ 2 ];

				uvs[ i2     ] = uva.x;
				uvs[ i2 + 1 ] = uva.y;

				uvs[ i2 + 2 ] = uvb.x;
				uvs[ i2 + 3 ] = uvb.y;

				uvs[ i2 + 4 ] = uvc.x;
				uvs[ i2 + 5 ] = uvc.y;

			}

			i3 += 9;
			i2 += 6;

		}

		bufferGeometry.computeBoundingSphere();

		return bufferGeometry;

	}

}
<commit_msg>BufferGeometryUtils: Minor code clean up.<commit_after>/**
 * @author spite / http://www.clicktorelease.com/
 * @author mrdoob / http://mrdoob.com/
 */

THREE.BufferGeometryUtils = {

	fromGeometry: function geometryToBufferGeometry( geometry, settings ) {

		if ( geometry instanceof THREE.BufferGeometry ) {

			return geometry;

		}

		settings = settings || { 'vertexColors': THREE.NoColors };

		var vertices = geometry.vertices;
		var faces = geometry.faces;
		var faceVertexUvs = geometry.faceVertexUvs;
		var vertexColors = settings.vertexColors;
		var hasFaceVertexUv = faceVertexUvs[ 0 ].length > 0;
		var hasFaceVertexNormals = faces[ 0 ].vertexNormals.length == 3;

		var bufferGeometry = new THREE.BufferGeometry();

		bufferGeometry.attributes = {

			position: {
				itemSize: 3,
				array: new Float32Array( faces.length * 3 * 3 )
			},
			normal: {
				itemSize: 3,
				array: new Float32Array( faces.length * 3 * 3 )
			}

		}

		var positions = bufferGeometry.attributes.position.array;
		var normals = bufferGeometry.attributes.normal.array;

		if ( vertexColors !== THREE.NoColors ) {

			bufferGeometry.attributes.color = {
				itemSize: 3,
				array: new Float32Array( faces.length * 3 * 3 )
			};

			var colors = bufferGeometry.attributes.color.array;

		}

		if ( hasFaceVertexUv === true ) {

			bufferGeometry.attributes.uv = {
				itemSize: 2,
				array: new Float32Array( faces.length * 3 * 2 )
			};

			var uvs = bufferGeometry.attributes.uv.array;

		}

		for ( var i = 0, i2 = 0, i3 = 0; i < faces.length; i ++, i2 += 6, i3 += 9 ) {

			var face = faces[ i ];

			var a = vertices[ face.a ];
			var b = vertices[ face.b ];
			var c = vertices[ face.c ];

			positions[ i3     ] = a.x;
			positions[ i3 + 1 ] = a.y;
			positions[ i3 + 2 ] = a.z;

			positions[ i3 + 3 ] = b.x;
			positions[ i3 + 4 ] = b.y;
			positions[ i3 + 5 ] = b.z;

			positions[ i3 + 6 ] = c.x;
			positions[ i3 + 7 ] = c.y;
			positions[ i3 + 8 ] = c.z;

			if ( hasFaceVertexNormals === true ) {

				var na = face.vertexNormals[ 0 ];
				var nb = face.vertexNormals[ 1 ];
				var nc = face.vertexNormals[ 2 ];

				normals[ i3     ] = na.x;
				normals[ i3 + 1 ] = na.y;
				normals[ i3 + 2 ] = na.z;

				normals[ i3 + 3 ] = nb.x;
				normals[ i3 + 4 ] = nb.y;
				normals[ i3 + 5 ] = nb.z;

				normals[ i3 + 6 ] = nc.x;
				normals[ i3 + 7 ] = nc.y;
				normals[ i3 + 8 ] = nc.z;

			} else {

				var n = face.normal;

				normals[ i3     ] = n.x;
				normals[ i3 + 1 ] = n.y;
				normals[ i3 + 2 ] = n.z;

				normals[ i3 + 3 ] = n.x;
				normals[ i3 + 4 ] = n.y;
				normals[ i3 + 5 ] = n.z;

				normals[ i3 + 6 ] = n.x;
				normals[ i3 + 7 ] = n.y;
				normals[ i3 + 8 ] = n.z;

			}

			if ( vertexColors === THREE.FaceColors ) {

				var fc = face.color;

				colors[ i3     ] = fc.r;
				colors[ i3 + 1 ] = fc.g;
				colors[ i3 + 2 ] = fc.b;

				colors[ i3 + 3 ] = fc.r;
				colors[ i3 + 4 ] = fc.g;
				colors[ i3 + 5 ] = fc.b;

				colors[ i3 + 6 ] = fc.r;
				colors[ i3 + 7 ] = fc.g;
				colors[ i3 + 8 ] = fc.b;

			} else if ( vertexColors === THREE.VertexColors ) {

				var vca = face.vertexColors[ 0 ];
				var vcb = face.vertexColors[ 1 ];
				var vcc = face.vertexColors[ 2 ];

				colors[ i3     ] = vca.r;
				colors[ i3 + 1 ] = vca.g;
				colors[ i3 + 2 ] = vca.b;

				colors[ i3 + 3 ] = vcb.r;
				colors[ i3 + 4 ] = vcb.g;
				colors[ i3 + 5 ] = vcb.b;

				colors[ i3 + 6 ] = vcc.r;
				colors[ i3 + 7 ] = vcc.g;
				colors[ i3 + 8 ] = vcc.b;

			}

			if ( hasFaceVertexUv === true ) {

				var uva = faceVertexUvs[ 0 ][ i ][ 0 ];
				var uvb = faceVertexUvs[ 0 ][ i ][ 1 ];
				var uvc = faceVertexUvs[ 0 ][ i ][ 2 ];

				uvs[ i2     ] = uva.x;
				uvs[ i2 + 1 ] = uva.y;

				uvs[ i2 + 2 ] = uvb.x;
				uvs[ i2 + 3 ] = uvb.y;

				uvs[ i2 + 4 ] = uvc.x;
				uvs[ i2 + 5 ] = uvc.y;

			}

		}

		bufferGeometry.computeBoundingSphere();

		return bufferGeometry;

	}

}
<|endoftext|>