text
stringlengths 3
1.05M
|
|---|
/*global require __dirname describe it after */
var should = require('should')
var fs = require('fs')
var async = require('async')
var makedir = require('../.')
// A lot of paths, and repeats, so that you have to handle multiple
// simultaneous makes
var path = require('path')
var rootdir = path.normalize(__dirname)
var path_components = [rootdir,'foo','bar','baz','bat']
var paths = [[rootdir , 'foo','bar','baz','bat']
,[rootdir , 'repos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,[rootdir , 'pos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,[rootdir , 'os','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,[rootdir , 's','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,[rootdir , 'repos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,[rootdir , 'pos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,[rootdir , 'os','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,[rootdir , 's','jem','node-data-proxy','public','data','airbasins','monthly','2007']
];
var relative_paths = [['./relative' , 'foo','bar','baz','bat']
,['./relative' , 'repos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,['./relative' , 'pos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,['./relative' , 'os','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,['./relative' , 's','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,['./relative' , 'repos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,['./relative' , 'pos','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,['./relative' , 'os','jem','node-data-proxy','public','data','airbasins','monthly','2007']
,['./relative' , 's','jem','node-data-proxy','public','data','airbasins','monthly','2007']
];
var modepaths=[];
for (var i = 0; i < 5; i++) {
var d = ['./modes'];
for (var j = 0; i < 5; i++){
d.push( Math.floor(Math.random() * Math.pow(16,4)).toString(16) );
}
modepaths.push(d);
}
after(function(done){
//return done()
function rmdir(p){
var len = p.length
for(var i = 0; i < p.length-1; i++){
var rmp=p.slice(0,len - i).join('/')
try{
fs.rmdirSync(rmp)
} catch (x) {
//console.log(x)
// don't care
}
}
return null
}
rmdir(path_components)
paths.forEach(rmdir)
relative_paths.forEach(rmdir)
modepaths.forEach(rmdir)
fs.rmdirSync('relative')
fs.rmdirSync('modes')
return done()
})
describe('create directories',function(){
it('should create a directory and its parent',function(done){
makedir.makedir(path_components.join('/'),function(err){
should.not.exist(err)
// make all of the pieces exist
var path
for(var i = 0; i < path_components.length; i++){
path = path_components.slice(0,i+1)
var stats = fs.statSync(path.join('/'))
stats.isDirectory().should.be.ok
}
return done()
})
})
it('should create many directories at once',function(done){
async.each(paths
,function(p,cb){
makedir.makedir(p.join('/'),function(err){
should.not.exist(err)
return cb()
})
return null
}
,function(e){
should.not.exist(e)
// make sure all of the paths exist
paths.forEach(function(p){
var stats = fs.statSync(p.join('/'))
stats.isDirectory().should.be.ok
})
return done()
});
return null
})
it('should create many relative path dirs at once',function(done){
async.each(relative_paths
,function(p,cb){
var path = //'./test/'+
p.join('/')
makedir.makedir(path,function(err){
should.not.exist(err)
return cb()
})
return null
}
,function(e){
should.not.exist(e)
// make sure all of the paths exist
paths.forEach(function(p){
var stats = fs.statSync(p.join('/'))
stats.isDirectory().should.be.ok
})
return done()
});
return null
})
it('should create modes',function(done){
async.each(modepaths
,function(p,callback){
// set up a private function, so when p gets reassigned we don't lose it
var mode_path = p.join('/')
var checkp = function(err){
should.not.exist(err)
fs.stat(mode_path,function(err,stat){
should.not.exist(err)
should.exist(stat)
var test = (stat.mode & 0777 )
test.should.equal(0744)
return callback()
})
return null
}
makedir.makedir(mode_path
,0744
,checkp)
return null
}
,done)
});
})
|
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
#
# 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.
"""
Tests covering various infer options using the DIN model.
"""
import tensorflow as tf
import unittest
import pytest
from test_common import get_log, run_validation
@pytest.mark.ipus(1)
class TestDINValidation(unittest.TestCase):
"""Testing some basic infer"""
@classmethod
def setUpClass(cls):
out = run_validation(**{'--use-synthetic-data': True,
'--epochs': 2,
'--seed': 3,
'--learning-rate': '0.1',
'--batches-per-step': 160})
cls.out = out
cls.infer = get_log(out)
def test_val_results(self):
# test_final_validation_auc
final_auc = self.infer
self.assertGreaterEqual(final_auc, 0.0)
|
import assert from "assert";
import alleway from "../index";
describe("semicolon", () => {
let counter = 0;
it(";", async(done) => {
let op = alleway({
"f1": function(a) {
counter++;
return a + 1;
},
"f2": function(v) {
counter++;
return v * 2;
}
});
let v = op.translate("f1;f2;f1;f2");
let res = await v(2);
assert.equal(counter, 4);
done();
});
});
|
const React = require('react')
const {
default: styled
} = require('styled-components')
const BaseComponent = props => {
return <svg width='100%' height='100%' viewBox='0 0 16 16' preserveAspectRatio='xMidYMid meet' {...props}><rect width='100%' height='100%' id='icon-bound' fill='none' /><path d='M3,3H1v13h11v-2H3V3z M12,0H4v13h11V3L12,0z M13,11H6V2h5v2h2V11z' /></svg>
}
const Pages = styled(BaseComponent)`
display: inline-block;
vertical-align: ${props => props.verticalAlign || 'top'};
overflow: hidden;
width: ${props => props.width || props.size || '1em'};
`
module.exports = Pages
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const package_chunk_sort_1 = require("../../utilities/package-chunk-sort");
const base_href_webpack_1 = require("../../lib/base-href-webpack");
const utils_1 = require("./utils");
function getBrowserConfig(wco) {
const { projectRoot, buildOptions, appConfig } = wco;
const appRoot = path.resolve(projectRoot, appConfig.root);
const nodeModules = path.resolve(projectRoot, 'node_modules');
let extraPlugins = [];
// figure out which are the lazy loaded entry points
const lazyChunks = utils_1.lazyChunksFilter([
...utils_1.extraEntryParser(appConfig.scripts, appRoot, 'scripts'),
...utils_1.extraEntryParser(appConfig.styles, appRoot, 'styles')
]);
if (buildOptions.vendorChunk) {
extraPlugins.push(new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
chunks: ['main'],
minChunks: (module) => module.resource && module.resource.startsWith(nodeModules)
}));
}
return {
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(appRoot, appConfig.index),
filename: path.resolve(buildOptions.outputPath, appConfig.index),
chunksSortMode: package_chunk_sort_1.packageChunkSort(appConfig),
excludeChunks: lazyChunks,
xhtml: true
}),
new base_href_webpack_1.BaseHrefWebpackPlugin({
baseHref: buildOptions.baseHref
}),
new webpack.optimize.CommonsChunkPlugin({
minChunks: Infinity,
name: 'inline'
})
].concat(extraPlugins)
};
}
exports.getBrowserConfig = getBrowserConfig;
//# sourceMappingURL=/users/hans/sources/angular-cli/models/webpack-configs/browser.js.map
|
/**
* External dependencies
*/
import { __, _n, sprintf } from '@wordpress/i18n';
import { useEffect } from 'react';
import PropTypes from 'prop-types';
import { speak } from '@wordpress/a11y';
import LoadingMask from '@woocommerce/base-components/loading-mask';
import {
getShippingRatesPackageCount,
getShippingRatesRateCount,
} from '@woocommerce/base-utils';
/**
* Internal dependencies
*/
import Packages from './packages';
import './style.scss';
const ShippingRatesControl = ( {
shippingRates,
shippingRatesLoading,
className,
collapsibleWhenMultiple = false,
noResultsMessage,
renderOption,
} ) => {
useEffect( () => {
if ( shippingRatesLoading ) {
return;
}
const packages = getShippingRatesPackageCount( shippingRates );
const shippingOptions = getShippingRatesRateCount( shippingRates );
if ( shippingOptions === 0 ) {
speak(
__(
'No shipping options were found.',
'woo-gutenberg-products-block'
)
);
} else if ( packages === 1 ) {
speak(
sprintf(
// translators: %d number of shipping options found.
_n(
'%d shipping option was found.',
'%d shipping options were found.',
shippingOptions,
'woo-gutenberg-products-block'
),
shippingOptions
)
);
} else {
speak(
sprintf(
// translators: %d number of shipping packages packages.
_n(
'Shipping option searched for %d package.',
'Shipping options searched for %d packages.',
packages,
'woo-gutenberg-products-block'
),
packages
) +
' ' +
sprintf(
// translators: %d number of shipping options available.
_n(
'%d shipping option was found',
'%d shipping options were found',
shippingOptions,
'woo-gutenberg-products-block'
),
shippingOptions
)
);
}
}, [ shippingRatesLoading, shippingRates ] );
return (
<LoadingMask
isLoading={ shippingRatesLoading }
screenReaderLabel={ __(
'Loading shipping rates…',
'woo-gutenberg-products-block'
) }
showSpinner={ true }
>
<Packages
className={ className }
collapsible={
shippingRates.length > 1 && collapsibleWhenMultiple
}
noResultsMessage={ noResultsMessage }
renderOption={ renderOption }
shippingRates={ shippingRates }
/>
</LoadingMask>
);
};
ShippingRatesControl.propTypes = {
noResultsMessage: PropTypes.string.isRequired,
renderOption: PropTypes.func.isRequired,
className: PropTypes.string,
collapsibleWhenMultiple: PropTypes.bool,
shippingRates: PropTypes.array,
shippingRatesLoading: PropTypes.bool,
};
export default ShippingRatesControl;
export { Packages };
|
import { runAction } from 'cerebral/test';
import { setSuccessFromDocumentTitleAction } from './setSuccessFromDocumentTitleAction';
describe('setSuccessFromDocumentTitleAction,', () => {
it('sets the success message from the documentTitle', async () => {
const result = await runAction(setSuccessFromDocumentTitleAction, {
state: {
caseDetail: {
documents: [
{
documentId: 'abc',
documentTitle: 'Order',
},
],
},
documentId: 'abc',
},
});
expect(result.output.alertSuccess.message).toEqual('Order updated.');
});
it('sets the success message from the documentType if documentTitle is not present', async () => {
const result = await runAction(setSuccessFromDocumentTitleAction, {
state: {
caseDetail: {
documents: [
{
documentId: 'abc',
documentType: 'Order',
},
],
},
documentId: 'abc',
},
});
expect(result.output.alertSuccess.message).toEqual('Order updated.');
});
it('sets the created document success message if state.isCreatingOrder is true', async () => {
const result = await runAction(setSuccessFromDocumentTitleAction, {
state: {
caseDetail: {
documents: [
{
documentId: 'abc',
documentType: 'Order',
},
],
},
documentId: 'abc',
isCreatingOrder: true,
},
});
expect(result.output.alertSuccess.message).toEqual(
'Your document has been successfully created and attached to this message',
);
});
});
|
import os
from . import cases
def get_file(file):
path = os.path.abspath(os.path.dirname(__file__))
return os.path.join(path, file)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-08-01 19:16
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='AcademicDiscipline',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=50, verbose_name='Academic Discipline')),
],
),
migrations.CreateModel(
name='Country',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=50, verbose_name='Country')),
],
),
migrations.CreateModel(
name='Moderator',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('report', models.CharField(max_length=500, verbose_name='Report')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='School',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('department', models.CharField(max_length=30, verbose_name='Department')),
('town', models.CharField(max_length=30, verbose_name='Town')),
('max_level', models.CharField(choices=[('ELEMS', 'Elementary School'), ('PRIMS', 'Primary School'), ('SECUS', 'Secondary School')], max_length=20, verbose_name='Max. level')),
('director_fullname', models.CharField(max_length=25, verbose_name='Full name School director')),
('address', models.CharField(max_length=300, verbose_name='Address')),
('telephone', models.CharField(max_length=25, verbose_name='Telephone')),
('email', models.EmailField(max_length=254, verbose_name='School email')),
('facebook_url', models.CharField(blank=True, max_length=20, verbose_name='Facebook')),
('school_website', models.CharField(blank=True, max_length=20, verbose_name='Website')),
('has_projector', models.BooleanField(verbose_name='Has projector?')),
('has_screen', models.BooleanField(verbose_name='Has screen?')),
('has_webcam', models.BooleanField(verbose_name='Has webcam?')),
('has_videoconf_room', models.BooleanField(verbose_name='Has videoconf room?')),
('has_microphone', models.BooleanField(verbose_name='Has microphone?')),
('has_speakers', models.BooleanField(verbose_name='Has speakers?')),
],
),
migrations.CreateModel(
name='SchoolTeacher',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('degree', models.CharField(max_length=20, verbose_name='Degree')),
('subjects', models.CharField(max_length=40, verbose_name='Subjects')),
('telephone', models.CharField(max_length=25, verbose_name='Telephone')),
('twitter_username', models.CharField(blank=True, max_length=15, verbose_name='Twitter')),
('facebook_profile', models.CharField(blank=True, max_length=30, verbose_name='Facebook')),
('has_IT_training', models.BooleanField(verbose_name='Has IT training?')),
('school', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='in_videoconfs.School')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='ScienceField',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(choices=[('LIFE', 'Life Sciences'), ('APPL', 'Applied Sciences'), ('SOCIAL', 'Social Sciences'), ('PHYS', 'Physical Sciences')], max_length=30, verbose_name='Science Field')),
('description', models.CharField(max_length=300, verbose_name='Description')),
],
),
migrations.CreateModel(
name='Scientist',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('academic_degree', models.CharField(choices=[('MAG', 'Master'), ('PHD', 'PhD'), ('MD', 'MD')], max_length=10, verbose_name='Academic Degree')),
('current_occupation', models.CharField(max_length=40, verbose_name='Occupation')),
('working_place', models.CharField(max_length=40, verbose_name='Working Place')),
('languages', models.CharField(blank=True, max_length=50, verbose_name='Languages')),
('personal_website', models.CharField(blank=True, max_length=30, verbose_name='Website')),
('researchgate_profile', models.CharField(blank=True, max_length=30, verbose_name='ResearchGate')),
('linkedin_profile', models.CharField(blank=True, max_length=30, verbose_name='LinkedIn')),
('twitter_username', models.CharField(blank=True, max_length=15, verbose_name='Twitter')),
('facebook_profile', models.CharField(blank=True, max_length=30, verbose_name='Facebook')),
('referenced_by', models.CharField(max_length=150, verbose_name='Referenced by')),
('is_verified', models.BooleanField(verbose_name='Verified Researcher?')),
('academic_field', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='in_videoconfs.AcademicDiscipline')),
('country_residence', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='in_videoconfs.Country')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='VideoconfSession',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('selected_date', models.DateField()),
('selected_hour', models.DateTimeField()),
('status_school', models.CharField(choices=[('CANCEL', 'Cancelled'), ('VER_REQ', 'To verify requirements'), ('TO_SCH', 'To be scheduled'), ('SCHED', 'Scheduled'), ('IN_PROG', 'In progress'), ('COMPLET', 'Completed')], max_length=7, verbose_name='Status school')),
('status_scientist', models.CharField(choices=[('CANCEL', 'Cancelled'), ('READING', 'Preparing reading'), ('TRAIN', 'Training'), ('TO_SCH', 'To be scheduled'), ('SCHED', 'Scheduled'), ('IN_PROG', 'In progress'), ('COMPLET', 'Completed')], max_length=7, verbose_name='Status scientist')),
('moderator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='in_videoconfs.Moderator')),
('school_teacher', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='in_videoconfs.SchoolTeacher')),
('scientist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='in_videoconfs.Scientist')),
],
),
migrations.AddField(
model_name='academicdiscipline',
name='academic_discipline',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='in_videoconfs.ScienceField'),
),
]
|
import * as utils from './utils/index';
import * as types from './utils/type';
import * as dateFns from 'date-fns';
import dateUtils from 'date-and-time';
import EventEmitter from './utils/events';
import datePicker from './datePicker';
import timePicker from './timePicker';
import defaultOptions from './defaultOptions';
import template from './templates';
import templateselection from './templates/header';
import templateFooter from './templates/footer';
export default class bulmaCalendar extends EventEmitter {
constructor(selector, options = {}) {
super();
this.element = types.isString(selector) ? document.querySelector(selector) : selector;
// An invalid selector or non-DOM node has been provided.
if (!this.element) {
throw new Error('An invalid selector or non-DOM node has been provided.');
}
this._clickEvents = ['click', 'touch'];
this._supportsPassive = utils.detectSupportsPassive();
// Use Element dataset values to override options
const elementConfig = this.element.dataset ? Object.keys(this.element.dataset)
.filter(key => Object.keys(defaultOptions).includes(key))
.reduce((obj, key) => {
return {
...obj,
[key]: this.element.dataset[key]
};
}, {}) : {};
// Set default options - dataset attributes are master
this.options = {
...defaultOptions,
...options,
...elementConfig
};
if (this.options.type === undefined) {
switch (this.element.getAttribute('type')) {
case 'date':
this.options.type = 'date';
break;
case 'time':
this.options.type = 'time';
break;
default:
this.options.type = 'datetime';
break;
}
}
this._id = utils.uuid('datetimePicker');
this.onToggleDateTimePicker = this.onToggleDateTimePicker.bind(this);
this.onCloseDateTimePicker = this.onCloseDateTimePicker.bind(this);
this.onDocumentClickDateTimePicker = this.onDocumentClickDateTimePicker.bind(this);
this.onValidateClickDateTimePicker = this.onValidateClickDateTimePicker.bind(this);
this.onTodayClickDateTimePicker = this.onTodayClickDateTimePicker.bind(this);
this.onClearClickDateTimePicker = this.onClearClickDateTimePicker.bind(this);
this.onCancelClickDateTimePicker = this.onCancelClickDateTimePicker.bind(this);
this.onSelectDateTimePicker = this.onSelectDateTimePicker.bind(this);
// Initiate plugin
this._init();
}
/**
* Initiate all DOM element containing datePicker class
* @method
* @return {Array} Array of all datePicker instances
*/
static attach(selector = 'input[type="date"]', options = {}) {
let instances = new Array();
const elements = types.isString(selector) ? document.querySelectorAll(selector) : Array.isArray(selector) ? selector : [selector];
[].forEach.call(elements, element => {
if (typeof element[this.constructor.name] === 'undefined') {
const instance = new bulmaCalendar(element, options);
element.bulmaCalendar = instance;
instances.push(instance);
} else {
instances.push(element[this.constructor.name]);
}
});
return instances;
}
/****************************************************
* *
* GETTERS and SETTERS *
* *
****************************************************/
/**
* Get id of current instance
*/
get id() {
return this._id;
}
// Set language
set lang(lang = 'en') {
try {
this._locale = require('date-fns/locale/' + lang);
} catch (e) {
lang = 'en';
this._locale = require('date-fns/locale/' + lang);
} finally {
this._lang = lang;
this.datePicker.lang = lang;
this.timePicker.lang = lang;
return this;
}
}
// Get current language
get lang() {
return this._lang;
}
get locale() {
return this._locale;
}
// Set format (set to yyyy-mm-dd HH:mm:ss by default)
set format(format) {
this._format = format;
return this;
}
// Get format
get format() {
return this._format;
}
/**
* * Date setter and getter
*/
set date(date = null) {
this.datePicker.date = date;
return this;
}
// Get date object
get date() {
return this.datePicker.date;
}
set startDate(date = undefined) {
this.datePicker.start = dateUtils.parse(date, this.dateFormat);
return this;
}
get startDate() {
return this.datePicker.start;
}
set endDate(date = undefined) {
this.datePicker.end = dateUtils.parse(date, this.dateFormat);
return this;
}
get endDate() {
return this.datePicker.end;
}
/**
* minDate getter and setters
*/
set minDate(date = undefined) {
this.datePicker.minDate = dateUtils.parse(date, this.dateFormat);
return this;
}
// Get minDate
get minDate() {
return this.datePicker.minDate;
}
// Set maxDate
set maxDate(date = undefined) {
this.datePicker.maxDate = dateUtils.parse(date, this.dateFormat);
return this;
}
// Get maxDate
get maxDate() {
return this.datePicker.maxDate;
}
// Set dateFormat (set to yyyy-mm-dd by default)
set dateFormat(dateFormat) {
this.datePicker.dateFormat = dateFormat;
return this;
}
// Get dateFormat
get dateFormat() {
return this.datePicker.dateFormat;
}
/**
* * Time setter and getter
*/
set time(time = null) {
this.timePicker.time = time;
return this;
}
// Get time object
get time() {
return this.timePicker.time;
}
set startTime(time = undefined) {
this.timePicker.start = time;
return this;
}
get startTime() {
return this.timePicker.start;
}
set endTime(time = undefined) {
this.timePicker.end = time;
return this;
}
get endTime() {
return this.timePicker.end;
}
/**
* minTime getter and setters
*/
set minTime(time = undefined) {
this.timePicker.minTime = time;
return this;
}
// Get minTime
get minTime() {
return this.timePicker.minTime;
}
// Set maxTime
set maxTime(time = undefined) {
this.timePicker.maxTime = time;
return this;
}
// Get maxTime
get maxTime() {
return this.timePicker.maxTime;
}
// Set timeFormat (set to HH:MM:SS by default)
set timeFormat(timeFormat) {
this.timePicker.dateFormat = timeFormat;
return this;
}
// Get timeFormat
get timeFormat() {
return this.timePicker.timeFormat;
}
/****************************************************
* *
* EVENTS FUNCTIONS *
* *
****************************************************/
onSelectDateTimePicker(e) {
this.refresh();
this.save();
if (e.type === 'select' && this.options.closeOnSelect && this.options.displayMode !== 'inline') {
this.hide();
}
this.emit(e.type, this);
}
onDocumentClickDateTimePicker(e) {
// Check is e.target not within datepicker element
const target = e.target || e.srcElement;
if (!this._ui.wrapper.contains(target) && this.options.displayMode !== 'inline' && this._open) {
this.onCloseDateTimePicker(e);
}
}
onToggleDateTimePicker(e) {
if (!this._supportsPassive) {
e.preventDefault();
}
e.stopPropagation();
if (this._open) {
this.hide();
} else {
this.show();
}
}
onValidateClickDateTimePicker(e) {
if (!this._supportsPassive) {
e.preventDefault();
}
e.stopPropagation();
this.save();
this.emit('select', this);
if (this.options.displayMode !== 'inline') {
this.onCloseDateTimePicker(e);
}
}
onTodayClickDateTimePicker(e) {
if (!this._supportsPassive) {
e.preventDefault();
}
e.stopPropagation();
this.datePicker.value(new Date());
this.datePicker.refresh();
this.timePicker.value(new Date());
this.timePicker.refresh();
// TODO: check if closeOnSelect
this.save();
}
onClearClickDateTimePicker(e) {
if (!this._supportsPassive) {
e.preventDefault();
}
e.stopPropagation();
this.clear();
this.emit('clear', this);
}
onCancelClickDateTimePicker(e) {
if (!this._supportsPassive) {
e.preventDefault();
}
e.stopPropagation();
if (this._snapshots.length) {
this.datePicker = this._snapshots[0].datePicker;
this.timePicker = this._snapshots[0].timePicker;
}
this.save();
if (this.options.displayMode !== 'inline') {
this.onCloseDateTimePicker(e);
}
}
onCloseDateTimePicker(e) {
if (!this._supportsPassive) {
e.preventDefault();
}
e.stopPropagation();
this.hide();
}
/****************************************************
* *
* PUBLIC FUNCTIONS *
* *
****************************************************/
isRange() {
return this.options.isRange;
}
/**
* Returns true if datetime picker is open, otherwise false.
* @method isOpen
* @return {boolean}
*/
isOpen() {
return this._open;
}
/**
* Get / Set datetimePicker value
* @param {*} date
*/
value(value = null) {
if (value) {
this.datePicker.value(value);
this.timePicker.value(value);
} else {
let string = '';
switch (this.options.type) {
case 'date':
string = this.datePicker.value();
break;
case 'time':
string = this.timePicker.value();
break;
case 'datetime':
let start = this.datePicker.start ? dateFns.getTime(dateFns.addMinutes(dateFns.addHours(this.datePicker.start, dateFns.getHours(this.timePicker.start)), dateFns.getMinutes(this.timePicker.start))) : undefined;
let end = this.datePicker.end ? dateFns.getTime(this.datePicker.end) : undefined;
if (end && this.options.isRange) {
// This options is not required - in other place i set eod on date
//end = dateFns.getTime(dateFns.addMinutes(dateFns.addHours(this.datePicker.end, dateFns.getHours(this.timePicker.end)), dateFns.getMinutes(this.timePicker.end)));
}
string = start ? dateFns.format(new Date(start), this.format, {
locale: this.locale
}) : '';
if (end) {
string += ` - ${end ? dateFns.format(new Date(end), this.format, { locale: this.locale }) : ''}`;
}
break;
}
return string;
}
}
refresh() {
this._ui.header.start.day.innerHTML = this.datePicker.start ? dateFns.format(this.datePicker.start, 'DD', {
locale: this.locale
}) : '--';
this._ui.header.start.month.innerHTML = this.datePicker.start ? dateFns.format(this.datePicker.start, 'MMMM YYYY', {
locale: this.locale
}) : '';
if (this.datePicker.start) {
this._ui.header.start.weekday.classList.remove('is-hidden');
this._ui.header.start.weekday.innerHTML = this.datePicker.start ? dateFns.format(this.datePicker.start, 'dddd', {
locale: this.locale
}) : '';
} else {
this._ui.header.start.weekday.classList.add('is-hidden');
}
if (this._ui.header.start.hour) {
this._ui.header.start.hour.innerHTML = this.timePicker.start ? dateFns.format(this.timePicker.start, 'HH:mm', {
locale: this.locale
}) : '--:--';
}
if (this._ui.header.end) {
this._ui.header.end.day.innerHTML = this.options.isRange && this.datePicker.end ? dateFns.format(this.datePicker.end, 'DD', {
locale: this.locale
}) : '--';
this._ui.header.end.month.innerHTML = this.options.isRange && this.datePicker.end ? dateFns.format(this.datePicker.end, 'MMMM YYYY', {
locale: this.locale
}) : '';
if (this.datePicker.end) {
this._ui.header.end.weekday.classList.remove('is-hidden');
this._ui.header.end.weekday.innerHTML = this.datePicker.end ? dateFns.format(this.datePicker.end, 'dddd', {
locale: this.locale
}) : '';
} else {
this._ui.header.end.weekday.classList.add('is-hidden');
}
if (this._ui.header.end && this._ui.header.end.hour) {
this._ui.header.end.hour.innerHTML = this.timePicker.end ? dateFns.format(this.timePicker.end, 'HH:mm', {
locale: this.locale
}) : '--:--';
}
}
this.emit('refresh', this);
}
clear() {
this.datePicker.clear();
this.timePicker.clear();
this.refresh();
this.element.value = '';
this._ui.dummy.dummy_1.value = '';
if (this._ui.dummy.dummy_2) {
this._ui.dummy.dummy_2.value = '';
}
this.emit('clear', this);
}
/**
* Show datePicker HTML Component
* @method show
* @return {void}
*/
show() {
this._snapshots = [];
this.snapshot();
if (this.element.value) {
this.datePicker.value(this.element.value);
this.timePicker.value(this.element.value);
}
this.datePicker.show();
this.timePicker.hide();
if (this._ui.modal) {
this._ui.modal.classList.add('is-active');
}
this._ui.wrapper.classList.add('is-active');
this._open = true;
this.emit('show', this);
}
/**
* Hide datePicker HTML Component
* @method hide
* @return {void}
*/
hide() {
this._open = false;
this._focus = false;
if (this._ui.modal) {
this._ui.modal.classList.remove('is-active');
}
this._ui.wrapper.classList.remove('is-active');
this.emit('hide', this);
}
// Set element value to datetime selected based on format
save() {
const date = this.value();
const [start, end] = date.split(' - ');
this.element.value = date;
this._ui.dummy.dummy_1.value = start ? start : '';
if (this._ui.dummy.dummy_2) {
this._ui.dummy.dummy_2.value = end ? end : '';
}
}
snapshot() {
// this._snapshots.push([
// ...this.datePicker,
// ...this.timePicker
// ]);
}
/**
* Destroy datePicker
* @method destroy
* @return {[type]} [description]
*/
destroy() {
this._ui.wrapper.remove();
}
/****************************************************
* *
* PRIVATE FUNCTIONS *
* *
****************************************************/
/**
* Initiate plugin instance
* @method _init
* @return {datePicker} Current plugin instance
*/
_init() {
this._open = false;
this._snapshots = []; // Use to revert selection
// Set component type (date / time / datetime)
// this.options.type = (['date', 'time', 'datetime'].indexOf(this.element.getAttribute('type').toLowerCase()) > -1) ? this.element.getAttribute('type').toLowerCase() : this.options.type;
this._type = (['date', 'time', 'datetime'].indexOf(this.options.type.toLowerCase()) > -1) ? this.options.type.toLowerCase() : 'date';
// Change element type to prevent browser default type="date" behavior
this.element.setAttribute('type', 'text');
this.datePicker = new datePicker({
...this.options,
lang: this.lang
});
this.timePicker = new timePicker({
...this.options,
lang: this.lang
});
if (this.element.value) {
this.datePicker.value(this.element.value);
this.timePicker.value(this.element.value);
}
this.lang = this.options.lang;
// Set export format based on component type
this.format = this._type === 'date' ? this.options.dateFormat : (this._type === 'time' ? this.options.timeFormat : `${this.options.dateFormat} ${this.options.timeFormat}`);
// Force dialog display mode on mobile devices
if (this.options.displayMode === 'default' && window.matchMedia('screen and (max-width: 768px)').matches) {
this.options.displayMode = 'dialog';
}
if (window.matchMedia('screen and (max-width: 768px)').matches) {
if (this.options.displayMode === 'default') {
this.options.displayMode = 'dialog';
}
this.options.displayDual = false;
}
this._build();
this._bindEvents();
this.save();
if (types.isFunction(this.options.onReady)) {
this.on('ready', this.options.onReady);
}
this.emit('ready', this);
}
/**
* Build datePicker HTML component and append it to the DOM
* @method _build
* @return {datePicker} Current plugin instance
*/
_build() {
const headerNode = document.createRange().createContextualFragment(templateselection({
...this.options,
type: this._type,
datePicker: this.options.type !== 'time',
timePicker: this.options.type !== 'date'
}));
const footerNode = document.createRange().createContextualFragment(templateFooter(this.options));
const datetimePickerNode = document.createRange().createContextualFragment(template({
...this.options,
id: this.id
}));
// Save pointer to each datePicker element for later use
this._ui = {
modal: datetimePickerNode.querySelector('.modal'),
wrapper: datetimePickerNode.querySelector('.datetimepicker'),
container: datetimePickerNode.querySelector('.datetimepicker-container'),
dummy: {
container: datetimePickerNode.querySelector('.datetimepicker-dummy'),
wrapper: datetimePickerNode.querySelector('.datetimepicker-dummy-wrapper'),
dummy_1: datetimePickerNode.querySelector('.datetimepicker-dummy .datetimepicker-dummy-input:nth-child(1)'),
dummy_2: datetimePickerNode.querySelector('.datetimepicker-dummy .datetimepicker-dummy-input:nth-child(2)'),
clear: datetimePickerNode.querySelector('.datetimepicker-dummy .datetimepicker-clear-button')
},
calendar: datetimePickerNode.querySelector('.datetimepicker'),
overlay: this.options.displayMode === 'dialog' ? {
background: datetimePickerNode.querySelector('.modal-background'),
close: datetimePickerNode.querySelector('.modal-close')
} : undefined,
header: {
container: headerNode.querySelector('.datetimepicker-header'),
start: {
container: headerNode.querySelector('.datetimepicker-selection-start'),
day: headerNode.querySelector('.datetimepicker-selection-start .datetimepicker-selection-day'),
month: headerNode.querySelector('.datetimepicker-selection-start .datetimepicker-selection-month'),
weekday: headerNode.querySelector('.datetimepicker-selection-start .datetimepicker-selection-weekday'),
hour: headerNode.querySelector('.datetimepicker-selection-start .datetimepicker-selection-hour'),
empty: headerNode.querySelector('.datetimepicker-selection-start .empty')
},
end: this.options.isRange ? {
container: headerNode.querySelector('.datetimepicker-selection-end'),
day: headerNode.querySelector('.datetimepicker-selection-end .datetimepicker-selection-day'),
month: headerNode.querySelector('.datetimepicker-selection-end .datetimepicker-selection-month'),
weekday: headerNode.querySelector('.datetimepicker-selection-end .datetimepicker-selection-weekday'),
hour: headerNode.querySelector('.datetimepicker-selection-end .datetimepicker-selection-hour'),
empty: headerNode.querySelector('.datetimepicker-selection-start .empty')
} : undefined
},
footer: {
container: footerNode.querySelector('.datetimepicker-footer'),
validate: footerNode.querySelector('.datetimepicker-footer-validate'),
today: footerNode.querySelector('.datetimepicker-footer-today'),
clear: footerNode.querySelector('.datetimepicker-footer-clear'),
cancel: footerNode.querySelector('.datetimepicker-footer-cancel'),
}
};
if (!types.BooleanParse(this.options.showHeader)) {
this._ui.header.container.classList.add('is-hidden');
}
if (!types.BooleanParse(this.options.showFooter)) {
this._ui.footer.container.classList.add('is-hidden');
}
if (!types.BooleanParse(this.options.showTodayButton)) {
this._ui.footer.today.classList.add('is-hidden');
}
if (!types.BooleanParse(this.options.showClearButton)) {
this._ui.footer.clear.classList.add('is-hidden');
}
if (this.options.closeOnSelect && this._ui.footer.validate) {
this._ui.footer.validate.classList.add('is-hidden');
}
this._ui.container.appendChild(headerNode);
switch (this._type) {
case 'date':
this._ui.container.appendChild(this.datePicker.render());
break;
case 'time':
this._ui.container.appendChild(this.timePicker.render());
if (this._ui.footer.validate) {
this._ui.footer.validate.classList.remove('is-hidden');
}
if (this._ui.footer.today) {
this._ui.footer.today.classList.add('is-hidden');
}
break;
case 'datetime':
this.options.closeOnSelect = false;
if (this._ui.footer.validate) {
this._ui.footer.validate.classList.remove('is-hidden');
}
this._ui.container.appendChild(this.datePicker.render());
this._ui.container.appendChild(this.timePicker.render());
break;
}
this._ui.wrapper.appendChild(footerNode);
this._ui.wrapper.classList.add(`is-${this.options.color}`);
this._ui.dummy.container.classList.add(`is-${this.options.color}`);
// Add datepicker HTML element to Document Body
this.element.parentNode.insertBefore(datetimePickerNode, this.element.nextSibling);
this._ui.dummy.wrapper.appendChild(this.element);
this.element.classList.add('is-hidden');
// this.element.style.visibility = 'hidden';
// this.element.style.position = 'absolute';
if (this.options.displayMode === 'inline') {
this._ui.wrapper.classList.add('is-active');
} else {
this._ui.dummy.container.classList.remove('is-hidden');
this._ui.wrapper.style.position = 'absolute';
this._ui.wrapper.classList.add('is-datetimepicker-default');
}
this.refresh();
}
/**
* Bind all events
* @method _bindEvents
* @return {void}
*/
_bindEvents() {
this._clickEvents.forEach(clickEvent => {
document.body.addEventListener(clickEvent, this.onDocumentClickDateTimePicker);
});
this.datePicker.on('select', this.onSelectDateTimePicker);
this.datePicker.on('select:start', this.onSelectDateTimePicker);
this.datePicker.on('select:end', this.onSelectDateTimePicker);
this.timePicker.on('select', this.onSelectDateTimePicker);
this.timePicker.on('select:start', this.onSelectDateTimePicker);
this.timePicker.on('select:end', this.onSelectDateTimePicker);
// Bind event to element in order to display/hide datePicker on click
if (this.options.toggleOnInputClick === true) {
this._clickEvents.forEach(clickEvent => {
this._ui.dummy.wrapper.addEventListener(clickEvent, this.onToggleDateTimePicker);
this.element.addEventListener(clickEvent, this.onToggleDateTimePicker);
});
}
if (this.options.displayMode === 'dialog' && this._ui.overlay) {
// Bind close event on Close button
if (this._ui.overlay.close) {
this._clickEvents.forEach(clickEvent => {
this.this._ui.overlay.close.addEventListener(clickEvent, this.onCloseDateTimePicker);
});
}
// Bind close event on overlay based on options
if (this.options.closeOnOverlayClick && this._ui.overlay.background) {
this._clickEvents.forEach(clickEvent => {
this._ui.overlay.background.addEventListener(clickEvent, this.onCloseDateTimePicker);
});
}
}
if (this._ui.footer.validate) {
this._clickEvents.forEach(clickEvent => {
this._ui.footer.validate.addEventListener(clickEvent, this.onValidateClickDateTimePicker);
});
}
if (this._ui.footer.today) {
this._clickEvents.forEach(clickEvent => {
this._ui.footer.today.addEventListener(clickEvent, this.onTodayClickDateTimePicker);
});
}
if (this._ui.footer.clear) {
this._clickEvents.forEach(clickEvent => {
this._ui.footer.clear.addEventListener(clickEvent, this.onClearClickDateTimePicker);
});
}
this._clickEvents.forEach(clickEvent => {
this._ui.dummy.clear.addEventListener(clickEvent, this.onClearClickDateTimePicker);
});
if (this._ui.footer.cancel) {
this._clickEvents.forEach(clickEvent => {
this._ui.footer.cancel.addEventListener(clickEvent, this.onCancelClickDateTimePicker);
});
}
}
}
|
import { __assign } from "tslib";
import * as React from 'react';
import { StyledIconBase } from '../../StyledIconBase';
export var Nlg = React.forwardRef(function (props, ref) {
var attrs = {
"fill": "currentColor",
"xmlns": "http://www.w3.org/2000/svg",
};
return (React.createElement(StyledIconBase, __assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 32 32" }, props, { ref: ref }),
React.createElement("path", { fillRule: "evenodd", d: "M16 32C7.163 32 0 24.837 0 16S7.163 0 16 0s16 7.163 16 16-7.163 16-16 16zm9.515-17.196c-1.518.022-7.748.008-9.344.017-.059 0-.166.11-.167.169-.012.67-.013 1.339 0 2.008.002.063.117.178.18.178 2.394.009 4.788.007 7.183.014.043 0 .13.095.124.133-.643 3.832-4.157 6.577-8.035 6.285-4.278-.323-7.486-4.068-7.035-8.317.334-3.14 2.025-5.37 4.982-6.447 2.923-1.065 5.596-.439 7.903 1.675.032.029.136.033.164.005a119.48 119.48 0 001.521-1.521c.026-.026.03-.118.008-.14-2.236-2.13-4.892-3.096-7.968-2.816-5.432.494-9.5 5.41-8.987 10.827.528 5.58 5.358 9.596 10.922 9.082 5.396-.5 9.464-5.362 8.998-10.74-.015-.164-.044-.268-.113-.331-.067-.061-.171-.083-.336-.08z", key: "k0" })));
});
Nlg.displayName = 'Nlg';
export var NlgDimensions = { height: 32, width: 32 };
|
from ros_compatibility.ros_compatible_node import *
|
from django import template
from django.template.defaultfilters import stringfilter
from machina.models.fields import render_func
register = template.Library()
@register.filter(is_safe=True)
@stringfilter
def rendered(value):
return render_func(value)
|
// This code runs in child site which is embedded in an iframe to
// share auth state with the parent.
if (Meteor.isClient) {
Meteor.startup(function() {
Template.sharedAuthFrame.helpers({
"sharedAuthFrame": function() {
var parentOrigin = null;
var parentSource = null;
if (!(Meteor.settings &&
Meteor.settings.public &&
Meteor.settings.public.sharedAuthDomains)) {
// No domain settings => no worky
throw new Error("shared-auth: Meteor.settings.public.sharedAuthDomains on " + window.location.host + " is not defined.");
}
// Tell the parent about our login state.
var notifyParent = function notifyParent() {
if (!parentOrigin || !parentSource) {
return;
}
//console.log("child announcing auth", localStorage.getItem("Meteor.userId"));
parentSource.postMessage({
"Meteor.loginTokenExpires": localStorage.getItem("Meteor.loginTokenExpires"),
"Meteor.loginToken": localStorage.getItem("Meteor.loginToken"),
"Meteor.userId": localStorage.getItem("Meteor.userId")
}, parentOrigin);
};
// The origin which this frame allows to request auth tokens from us.
var onMessage = function onMessage(event) {
// Ensure we are within allowed origins.
var found = false;
for (var i=0; i < Meteor.settings.public.sharedAuthDomains.length; i++) {
if (Meteor.settings.public.sharedAuthDomains[i] === event.origin) {
found = true;
break;
}
}
if (!found) {
if (event.data === "requestAuth" || event.data === "requestLogout") {
console.log("sharedAuthFrame refusing to share auth with " + event.origin + ", which is not in Meteor.settings.public.sharedAuthDomains:", Meteor.settings.public.sharedAuthDomains);
}
return;
}
// Respond to the message with auth tokens.
if (event.data === "requestAuth") {
// We only set these after we're sure event.origin is in sharedAuthDomains.
//console.log("child received requestAuth");
parentOrigin = event.origin;
parentSource = event.source;
notifyParent();
} else if (event.data === "requestLogout") {
//console.log("child received requestLogout");
Meteor.logout();
}
};
// Update parent if storage changes.
var onStorageChange = function onStorageChange(event) {
if (event.key === "Meteor.loginToken" ||
event.key === "Meteor.loginTokenExpires" ||
event.key === "Meteor.userId") {
//console.log("child login changed", localStorage.getItem("Meteor.userId"));
notifyParent();
}
};
window.addEventListener("storage", onStorageChange, false);
window.addEventListener("message", onMessage, false);
}
});
});
}
|
import React from 'react';
import '../../GlobalStyle/main.css';
import HeroComponent from '../../Components/Hero';
import Layoutcomponent from '../../Components/Layout';
import FeaturedPropertyData from '../../data';
import OverviewComonent from '../../Components/overview';
import AmenitiesComponent from '../../Components/Amenities';
import ConfigurationComponent from '../../Components/ConfigurationComponent';
import PricingComponent from '../../Components/PricingComponent';
import LocationComponent from '../../Components/Location';
const Assertzmarq = () => {
const dataweneed = FeaturedPropertyData.filter((item)=>{
return item.redirect === "prestige-tech-cloud-park"
});
const overviewdata = dataweneed.map((item)=>{
return {"area":item.landarea, "units": item.numberofunits, "floors": item.startingPrice, "towers": item.totalblocks, "var": item.unitvarients, "poss":item.possession, "loc":item.location}
});
const configurationdata = dataweneed.map((item)=>{
return item.area;
})
const pricingdata = dataweneed.map((item)=>{
return item.price
})
const mainImage = dataweneed.map((item)=>{
return item.mainBanner;
})
const locationdata = dataweneed.map((item)=>{
return item.map
})
return (
<Layoutcomponent>
<HeroComponent img={mainImage} quote1="Prestige-tech-cloud-park"/>
<br/>
<OverviewComonent project="Tech Cloud Park Overview" data={overviewdata}/>
<hr/>
<ConfigurationComponent project="Tech Cloud Park Configuration" data={configurationdata}/>
<hr/>
<AmenitiesComponent project="Tech Cloud Park Amenities"/>
<hr/>
<PricingComponent project="Tech Cloud Park Pricing" data={pricingdata}/>
<hr/>
<LocationComponent project="Tech Cloud Park Location" data={locationdata}/>
</Layoutcomponent>
);
};
export default Assertzmarq;
|
var class_keyboard_controller =
[
[ "KeyboardController", "class_keyboard_controller.html#aa1e5c9ea3bf0f4c3803076c70b5605d2", null ],
[ "~KeyboardController", "class_keyboard_controller.html#a9791aa6d6fadf77b4ef3e59cdb7d9b1d", null ],
[ "keyboardInput", "class_keyboard_controller.html#a868853a3f5e49dd7971afb206e7b28c2", null ],
[ "mouseInput", "class_keyboard_controller.html#a6a34d386b9ee4cf2b3d7a780f44ac572", null ],
[ "mouseNotInUi", "class_keyboard_controller.html#adb350814df7deedc3951c458cd65639e", null ],
[ "m_Player", "class_keyboard_controller.html#ab89231a7368be191ccf0fe63f72a76ee", null ],
[ "m_Window", "class_keyboard_controller.html#a5c1d84650c635b7a5bac321945820abe", null ]
];
|
// =================================================================
// MARKER COUNT BANNER
// =================================================================
L.Control.MarkerCountBanner = L.Control.extend({
onAdd: function(map) {
this._div = L.DomUtil.create('div', 'marker-count-banner');
return this._div;
},
setCount: function(count) {
var text = count + ' Funde';
if(count == 0)
text = 'Keine Funde';
else if(count == 1)
text = 'Ein Fund';
this._div.innerHTML = text + ' sichtbar.';
}
});
L.control.markerCountBanner = function (options) {
return new L.Control.MarkerCountBanner(options);
};
// =================================================================
// TOOLTIP TOGGLE BUTTON
// =================================================================
L.Control.TooltipToggle = L.Control.extend({
options: {
position: 'topright',
labelShow: 'Show Tooltips',
labelHide: 'Hide Tooltips',
tooltipText: '',
permanentVisibility: false
},
onAdd: function (map) {
this._button = L.DomUtil.create('div', 'tooltip-toggle');
L.DomEvent.addListener(this._button, 'click', this.toggle, this);
this._update();
return this._button;
},
onRemove: function (map) {
},
isOn: function() {
return this.options.permanentVisibility;
},
toggle: function () {
if(!this._map)
return;
this.options.permanentVisibility = !this.options.permanentVisibility;
this._map.fire('tooltiptoggle');
this._update();
},
_update: function () {
this._button.innerHTML =
'<a href="javascript:void(0)" title="' +
this.options.tooltipText +
'">' +
(this.options.permanentVisibility ? this.options.labelHide : this.options.labelShow) +
'</a>';
}
});
L.control.tooltipToggle = function (options) {
return new L.Control.TooltipToggle(options);
};
|
import logging
import time
from flexget import plugin
from flexget.event import event
from flexget.utils.log import log_once
from flexget.utils.parsers.generic import ParseWarning
from flexget.utils.parsers.movie import MovieParser
from flexget.utils.parsers.series import SeriesParser
from .parser_common import MovieParseResult, SeriesParseResult
log = logging.getLogger('parser_internal')
try:
preferred_clock = time.process_time
except AttributeError:
preferred_clock = time.clock
class ParserInternal:
# movie_parser API
@plugin.priority(1)
def parse_movie(self, data, **kwargs):
log.debug('Parsing movie: `%s` kwargs: %s', data, kwargs)
start = preferred_clock()
parser = MovieParser()
try:
parser.parse(data)
except ParseWarning as pw:
log_once(pw.value, logger=log)
result = MovieParseResult(
data=data,
name=parser.name,
year=parser.year,
quality=parser.quality,
proper_count=parser.proper_count,
valid=bool(parser.name),
)
log.debug('Parsing result: %s (in %s ms)', parser, (preferred_clock() - start) * 1000)
return result
# series_parser API
@plugin.priority(1)
def parse_series(self, data, **kwargs):
log.debug('Parsing series: `%s` kwargs: %s', data, kwargs)
start = preferred_clock()
parser = SeriesParser(**kwargs)
try:
parser.parse(data)
except ParseWarning as pw:
log_once(pw.value, logger=log)
# TODO: Returning this invalid object seems a bit silly, raise an exception is probably better
if not parser.valid:
return SeriesParseResult(valid=False)
result = SeriesParseResult(
data=data,
name=parser.name,
episodes=parser.episodes,
id=parser.id,
id_type=parser.id_type,
quality=parser.quality,
proper_count=parser.proper_count,
special=parser.special,
group=parser.group,
season_pack=parser.season_pack,
strict_name=parser.strict_name,
identified_by=parser.identified_by,
)
log.debug('Parsing result: %s (in %s ms)', parser, (preferred_clock() - start) * 1000)
return result
@event('plugin.register')
def register_plugin():
plugin.register(
ParserInternal, 'parser_internal', interfaces=['movie_parser', 'series_parser'], api_ver=2
)
|
import React from "react";
import { Image } from "react-native";
import { AppLoading } from "expo";
import { Asset } from "expo-asset";
import { Block, GalioProvider } from "galio-framework";
import { NavigationContainer } from "@react-navigation/native";
import { StackNavigator } from "react-navigation";
// Before rendering any navigation stack
import { enableScreens } from "react-native-screens";
enableScreens();
// import Home from './screens/Home';
// import Pro from './screens/Pro';
import Screens from "./navigation/Screens";
import { Images, articles, argonTheme } from "./constants";
// const Navigation = StackNavigator({
// Home:{
// screen: Home,
// },
// profile:{
// screen: Pro,
// }
// })
// cache app images
const assetImages = [
Images.Onboarding,
Images.LogoOnboarding,
Images.Logo,
Images.Pro,
Images.ArgonLogo,
Images.iOSLogo,
Images.androidLogo
];
// cache product images
articles.map(article => assetImages.push(article.image));
function cacheImages(images) {
return images.map(image => {
if (typeof image === "string") {
return Image.prefetch(image);
} else {
return Asset.fromModule(image).downloadAsync();
}
});
}
export default class App extends React.Component {
state = {
isLoadingComplete: false
};
render() {
if (!this.state.isLoadingComplete) {
return (
<AppLoading
startAsync={this._loadResourcesAsync}
onError={this._handleLoadingError}
onFinish={this._handleFinishLoading}
/>
);
} else {
return (
<NavigationContainer>
<GalioProvider theme={argonTheme}>
<Block flex>
<Screens />
</Block>
</GalioProvider>
</NavigationContainer>
);
}
}
_loadResourcesAsync = async () => {
return Promise.all([...cacheImages(assetImages)]);
};
_handleLoadingError = error => {
// In this case, you might want to report the error to your error
// reporting service, for example Sentry
console.warn(error);
};
_handleFinishLoading = () => {
this.setState({ isLoadingComplete: true });
};
}
|
class TypeSignature:
double = b"\x01"
string = b"\x02"
document = b"\x03"
array = b"\x04"
binary = b"\x05"
bool = b"\x08"
null = b"\x0A"
int32 = b"\x10"
uint64 = b"\x11"
int64 = b"\x12"
class EncodeError(Exception):
pass
class DecodeError(Exception):
pass
|
# -*- coding: utf-8 -*-
class Solution:
def isPowerOfTwo(self, n):
return (
n == 1 or
n == 2 or
n == 4 or
n == 8 or
n == 16 or
n == 32 or
n == 64 or
n == 128 or
n == 256 or
n == 512 or
n == 1024 or
n == 2048 or
n == 4096 or
n == 8192 or
n == 16384 or
n == 32768 or
n == 65536 or
n == 131072 or
n == 262144 or
n == 524288 or
n == 1048576 or
n == 2097152 or
n == 4194304 or
n == 8388608 or
n == 16777216 or
n == 33554432 or
n == 67108864 or
n == 134217728 or
n == 268435456 or
n == 536870912 or
n == 1073741824
)
if __name__ == '__main__':
solution = Solution()
assert solution.isPowerOfTwo(1)
assert solution.isPowerOfTwo(16)
assert not solution.isPowerOfTwo(218)
|
var getScrollingRoot = function getScrollingRoot() {
return document.scrollingElement || document.documentElement;
};
/**
* Recursively finds the scroll parent of a node. The scroll parrent of a node
* is the closest node that is scrollable. A node is scrollable if:
* - it is allowed to scroll via CSS ('overflow-y' not visible or hidden);
* - and its children/content are "bigger" than the node's box height.
*
* The root of the document always scrolls by default.
*
* @param {HTMLElement} node Any DOM element.
* @return {HTMLElement} The scroll parent element.
*/
export function getScrollParent(node) {
var parent = node.parentElement;
if (parent == null) return getScrollingRoot();
var _window$getComputedSt = window.getComputedStyle(parent),
overflowY = _window$getComputedSt.overflowY;
var canScroll = overflowY !== 'visible' && overflowY !== 'hidden';
if (canScroll && parent.scrollHeight > parent.clientHeight) {
return parent;
}
return getScrollParent(parent);
}
/**
* Recursively traverses the tree upwards from the given node, capturing all
* ancestor nodes that scroll along with their current 'overflow-y' CSS
* property.
*
* @param {HTMLElement} node Any DOM element.
* @param {Map<HTMLElement,string>} [acc] Accumulator map.
* @return {Map<HTMLElement,string>} Map of ancestors with their 'overflow-y' value.
*/
export function getScrollAncestorsOverflowY(node) {
var acc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Map();
var scrollingRoot = getScrollingRoot();
var scrollParent = getScrollParent(node);
acc.set(scrollParent, scrollParent.style.overflowY);
if (scrollParent === scrollingRoot) return acc;
return getScrollAncestorsOverflowY(scrollParent, acc);
}
/**
* Disabling the scroll on a node involves finding all the scrollable ancestors
* and set their 'overflow-y' CSS property to 'hidden'. When all ancestors have
* 'overflow-y: hidden' (up to the document element) there is no scroll
* container, thus all the scroll outside of the node is disabled. In order to
* enable scroll again, we store the previous value of the 'overflow-y' for
* every ancestor in a closure and reset it back.
*
* @param {HTMLElement} node Any DOM element.
*/
export default function disableScroll(node) {
var scrollAncestorsOverflowY = getScrollAncestorsOverflowY(node);
var toggle = function toggle(on) {
return scrollAncestorsOverflowY.forEach(function (overflowY, ancestor) {
ancestor.style.setProperty('overflow-y', on ? 'hidden' : overflowY);
});
};
toggle(true);
return function () {
return toggle(false);
};
}
|
from dotenv import load_dotenv
load_dotenv()
import os
import json
from typing import Optional
from fastapi import FastAPI, Depends, FastAPI, HTTPException
from pydantic import BaseModel
from fastapi.responses import HTMLResponse
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
import httpx
import base64
import couchdb
import jwt
clear_token = os.getenv("CLEAR_TOKEN")
db_name = os.getenv("DB_NAME")
db_host = os.getenv("DB_HOST")
db_port = os.getenv("DB_PORT")
db_username = os.getenv("DB_USERNAME")
db_password = os.getenv("DB_PASSWORD")
client = None
creds = None
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def retrieve_token(username, password):
client_id = os.getenv("CLIENT_ID")
secret = os.getenv("SECRET")
url = os.getenv("OAUTH_SERVER_URL") + "/token"
grant_type = "password"
usrPass = client_id + ":" + secret
b64Val = base64.b64encode(usrPass.encode()).decode()
headers = {"accept": "application/json", "Authorization": "Basic %s" % b64Val}
data = {
"grant_type": grant_type,
"username": username,
"password": password,
"scope": "all",
}
response = httpx.post(url, headers=headers, data=data)
if response.status_code == httpx.codes.OK:
return response.json()
else:
raise HTTPException(status_code=response.status_code, detail=response.text)
def validate(token: str = Depends(oauth2_scheme)):
res = validate_token_IBM(
token, os.getenv("OAUTH_SERVER_URL"), os.getenv("CLIENT_ID"), os.getenv("SECRET")
)
return res
def validate_token_IBM(token, authURL, clientId, clientSecret=Depends(oauth2_scheme)):
usrPass = clientId + ":" + clientSecret
b64Val = base64.b64encode(usrPass.encode()).decode()
# headers = {'accept': 'application/json', 'Authorization': 'Basic %s' % b64Val}
headers = {
"accept": "application/json",
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded",
"Authorization": "Basic %s" % b64Val,
}
data = {
"client_id": clientId,
"client_secret": clientSecret,
"token": token,
}
url = authURL + "/introspect"
response = httpx.post(url, headers=headers, data=data)
if response.status_code == httpx.codes.OK and response.json()["active"]:
return jwt.decode(token, options={"verify_signature": False})
else:
raise HTTPException(status_code=403, detail="Authorisation failure")
client = couchdb.Server(f'http://{db_username}:{db_password}@{db_host}:{db_port}/')
def getDb():
try:
return client.create(db_name)
except couchdb.PreconditionFailed:
return client[db_name]
class Flagged(BaseModel):
_id: Optional[str]
user_id: str
flagged_string: str
category: str
info: Optional[str]
url: str
class Text(BaseModel):
content: str
@app.get("/", response_class=HTMLResponse)
def read_root():
return open("template.html").read()
# Get auth token
@app.post("/token")
def login(form_data: OAuth2PasswordRequestForm = Depends()):
"""
Gets a token from IBM APP ID, given a username and a password. Depends on OAuth2PasswordRequestForm.
Parameters
----------
OAuth2PasswordRequestForm.form_data.username: str, required
OAuth2PasswordRequestForm.form_data.password: str, required
Returns
-------
token: str
"""
# print(retrieve_token(form_data.username,form_data.password))
return retrieve_token(form_data.username, form_data.password)
@app.get("/mark")
def get_marks(user: dict = Depends(validate)):
db = getDb()
return list(map(lambda item: dict(item.doc.items()), db.view('_all_docs',include_docs=True)))
@app.post("/mark")
def save_mark(item: Flagged, user: dict = Depends(validate)):
db = getDb()
item.user_id = user["sub"]
data = item.dict()
_id, _ = db.save(data)
return data
@app.put("/mark/{_id}")
def update_mark(_id: str, item: Flagged, user: dict = Depends(validate)):
db = getDb()
doc = db[_id]
doc["category"] = item.category
db[doc.id] = doc
return {"status": "success"}
@app.delete("/mark")
def delete_mark(_id: str, user: dict = Depends(validate)):
db = getDb()
my_document = db[_id]
db.delete(my_document)
return {"status": "success"}
@app.get("/categories")
def read_categories():
# fmt: off
return [
#IBM colour-blindness palette used below https://davidmathlogic.com/colorblind/
{
"name": "appropriation",
"colour": "#648FFF",
"description": "To adopt or claim elements of one or more cultures to which you do not belong, consequently causing offence to members of said culture(s) or otherwise achieving some sort of personal gain at the expense of other members of the culture(s)."
},
{
"name": "stereotyping",
"colour": "#785EF0",
"description": "To perpetuate a system of beliefs about superficial characteristics of members of a given ethnic group or nationality, their status, society and cultural norms.",
},
{
"name": "under-representation",
"colour": "#DC267F",
"description": "To have Insufficient or disproportionately low representation of Black, Indigenous, People of Color (BIPOC) individuals, for example in mediums such as media and TV adverts.",
},
{
"name": "gaslighting",
"colour": "#FE6100",
"description": "To use tactics, whether by a person or entity, in order to gain more power by making a victim question their reality. To deny or refuse to see racial bias, which may also include the act of convincing a person that an event/slur/idea is not racist or not as bad as one claims it to be through means of psychological manipulation."
},
{
"name": "racial-slur",
"colour": "#FFB000",
"description": "To insult, or use offensive or hurtful language designed to degrade a person because of their race or culture. This is intentional use of words or phrases to speak of or to members of ethnical groups in a derogatory manor. ",
},
{
"name": "othering",
"colour": "#5DDB2B",
"description": "To label and define a person/group as someone who belongs to a 'socially subordinate' category of society. The practice of othering persons means to use the characteristics of a person's race to exclude and displace such person from the 'superior' social group and separate them from what is classed as normal."
},
]
# fmt: on
@app.put("/analyse")
def analyse_text(text: Text):
db = getDb()
res = []
for item in db.view('_all_docs',include_docs=True):
doc = item.doc
if doc["flagged_string"] in text.content:
res.append({"flag" : doc["flagged_string"], "category" : doc["category"], "info" : doc["info"]})
return {"biased": res}
@app.put("/check")
def check_words(text: Text):
res = []
db = getDb()
for item in db.view('_all_docs',include_docs=True):
doc = item.doc
if doc["category"] == "racial-slur" and doc["flagged_string"].lower() in text.content.lower():
res.append({"flag" : doc["flagged_string"], "category" : doc["category"], "info" : doc["info"]})
line_by_line = []
for i,l in enumerate(text.content.splitlines(),1):
for r in res:
if r["flag"].lower() in l.lower():
line_by_line.append({
"line" : i,
"word" : r["flag"],
"additional_info": r["info"]
})
return line_by_line
|
function getClientInfo() {
return {
"name" : "Test Automation (Javascript)",
"category" : "Tests",
"author" : "Dreamtonics",
"versionNumber" : 0,
"minEditorVersion" : 65537
};
}
function main() {
var mainRef = SV.getProject().getTrack(0).getGroupReference(0);
var mainGroup = mainRef.getTarget();
var myPitchBend = mainGroup.getParameter("PitchDelta");
var myTension = mainGroup.getParameter("Tension");
var numPoints = 1024;
var y = 0, yPrev = 0;
for(var i = 0; i < numPoints; i ++) {
var x = i * SV.QUARTER / 8;
y = (Math.random() - 0.5) * 500;
y = (yPrev * 0.9 + y * 0.1) * 0.99;
yPrev = y;
myPitchBend.add(x, y);
}
y = 0;
yPrev = 0;
for(var i = 0; i < numPoints; i ++) {
var x = i * SV.QUARTER / 8;
y = (Math.random() - 0.5) * 5;
y = (yPrev * 0.97 + y * 0.03) * 0.98;
yPrev = y;
myTension.add(x, y);
}
SV.finish();
}
|
'use strict';
(function() {
var module = angular.module('redash.visualization');
module.config(['VisualizationProvider', function(VisualizationProvider) {
var renderTemplate =
'<map-renderer ' +
'options="visualization.options" query-result="queryResult">' +
'</map-renderer>';
var editTemplate = '<map-editor></map-editor>';
var defaultOptions = {
'height': 500,
'draw': 'Marker',
'classify':'none'
};
VisualizationProvider.registerVisualization({
type: 'MAP',
name: 'Map',
renderTemplate: renderTemplate,
editorTemplate: editTemplate,
defaultOptions: defaultOptions
});
}
]);
module.directive('mapRenderer', function() {
return {
restrict: 'E',
templateUrl: '/views/visualizations/map.html',
link: function($scope, elm, attrs) {
var setBounds = function(){
var b = $scope.visualization.options.bounds;
if(b){
$scope.map.fitBounds([[b._southWest.lat, b._southWest.lng],[b._northEast.lat, b._northEast.lng]]);
} else if ($scope.features.length > 0){
var group= new L.featureGroup($scope.features);
$scope.map.fitBounds(group.getBounds());
}
};
$scope.$watch('[queryResult && queryResult.getData(), visualization.options.draw,visualization.options.latColName,'+
'visualization.options.lonColName,visualization.options.classify,visualization.options.classify]',
function() {
var marker = function(lat,lon){
if (lat == null || lon == null) return;
return L.marker([lat, lon]);
};
var heatpoint = function(lat,lon,obj){
if (lat == null || lon == null) return;
var color = 'red';
if (obj &&
obj[$scope.visualization.options.classify] &&
$scope.visualization.options.classification){
var v = $.grep($scope.visualization.options.classification,function(e){
return e.value == obj[$scope.visualization.options.classify];
});
if (v.length >0) color = v[0].color;
}
var style = {
fillColor:color,
fillOpacity:0.5,
stroke:false
};
return L.circleMarker([lat,lon],style)
};
var color = function(val){
// taken from http://jsfiddle.net/xgJ2e/2/
var h= Math.floor((100 - val) * 120 / 100);
var s = Math.abs(val - 50)/50;
var v = 1;
var rgb, i, data = [];
if (s === 0) {
rgb = [v,v,v];
} else {
h = h / 60;
i = Math.floor(h);
data = [v*(1-s), v*(1-s*(h-i)), v*(1-s*(1-(h-i)))];
switch(i) {
case 0:
rgb = [v, data[2], data[0]];
break;
case 1:
rgb = [data[1], v, data[0]];
break;
case 2:
rgb = [data[0], v, data[2]];
break;
case 3:
rgb = [data[0], data[1], v];
break;
case 4:
rgb = [data[2], data[0], v];
break;
default:
rgb = [v, data[0], data[1]];
break;
}
}
return '#' + rgb.map(function(x){
return ("0" + Math.round(x*255).toString(16)).slice(-2);
}).join('');
};
// Following line is used to avoid "Couldn't autodetect L.Icon.Default.imagePath" error
// https://github.com/Leaflet/Leaflet/issues/766#issuecomment-7741039
L.Icon.Default.imagePath = L.Icon.Default.imagePath || "//api.tiles.mapbox.com/mapbox.js/v2.2.1/images";
function getBounds(e) {
$scope.visualization.options.bounds = $scope.map.getBounds();
}
var queryData = $scope.queryResult.getData();
var classify = $scope.visualization.options.classify;
if (queryData) {
$scope.visualization.options.classification = [];
for (var row in queryData) {
if (queryData[row][classify] &&
$.grep($scope.visualization.options.classification, function (e) {
return e.value == queryData[row][classify]
}).length == 0) {
$scope.visualization.options.classification.push({value: queryData[row][classify], color: null});
}
}
$.each($scope.visualization.options.classification, function (i, c) {
c.color = color(parseInt((i / $scope.visualization.options.classification.length) * 100));
});
if (!$scope.map) {
$scope.map = L.map(elm[0].children[0].children[0])
}
L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo($scope.map);
$scope.features = $scope.features || [];
var tmp_features = [];
var lat_col = $scope.visualization.options.latColName || 'lat';
var lon_col = $scope.visualization.options.lonColName || 'lon';
for (var row in queryData) {
var feature;
if ($scope.visualization.options.draw == 'Marker') {
feature = marker(queryData[row][lat_col], queryData[row][lon_col])
} else if ($scope.visualization.options.draw == 'Color') {
feature = heatpoint(queryData[row][lat_col], queryData[row][lon_col], queryData[row])
}
if (!feature) continue;
var obj_description = '<ul style="list-style-type: none;padding-left: 0">';
for (var k in queryData[row]){
obj_description += "<li>" + k + ": " + queryData[row][k] + "</li>";
}
obj_description += '</ul>';
feature.bindPopup(obj_description);
tmp_features.push(feature);
}
$.each($scope.features, function (i, f) {
$scope.map.removeLayer(f);
});
$scope.features = tmp_features;
$.each($scope.features, function (i, f) {
f.addTo($scope.map)
});
setBounds();
$scope.map.on('focus',function(){
$scope.map.on('moveend', getBounds);
});
$scope.map.on('blur',function(){
$scope.map.off('moveend', getBounds);
});
// We redraw the map if it was loaded in a hidden tab
if ($('a[href="#'+$scope.visualization.id+'"]').length > 0) {
$('a[href="#'+$scope.visualization.id+'"]').on('click', function () {
setTimeout(function() {
$scope.map.invalidateSize(false);
setBounds();
},500);
});
}
}
}, true);
$scope.$watch('visualization.options.height', function() {
if (!$scope.map) return;
$scope.map.invalidateSize(false);
setBounds();
});
}
}
});
module.directive('mapEditor', function() {
return {
restrict: 'E',
templateUrl: '/views/visualizations/map_editor.html',
link: function($scope, elm, attrs) {
$scope.draw_options = ['Marker','Color'];
$scope.classify_columns = $scope.queryResult.columnNames.concat('none');
}
}
});
})();
|
/*
* 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';
const Generator = require('yeoman-generator');
const camelcase = require('camelcase');
const defaultTxValue = 50;
const defaultTxDuration = 20;
const defaultWorkerCount = 1;
const answersObject = {};
let promptAnswers;
module.exports = class extends Generator {
/**
* Prompts questions about the benchmark generator settings.
* @async
*/
async prompting () {
const workspaceQuestions = [{
type: 'input',
name: 'workspace',
message: 'What would you like to name your workspace?',
when: () => !this.options.workspace
}];
const workspaceAnswers = await this.prompt(workspaceQuestions);
this.log('For the workload file...');
const workloadQuestions = [{
type: 'input',
name: 'contractId',
message: 'What is the name of your smart contract?',
when: () => !this.options.contractId
}, {
type: 'input',
name: 'contractVersion',
message: 'What is the version of your smart contract?',
when: () => !this.options.contractVersion
}, {
type: 'input',
name: 'contractFunction',
message: 'Which smart contract function would you like to perform the benchmark on?',
when: () => !this.options.contractFunction
}, {
type: 'input',
name: 'contractArguments',
message: 'What are the arguments of your smart contract function? (e.g. ["arg1", "arg2"])',
when: () => !this.options.contractArguments
}];
const workloadAnswers = await this.prompt(workloadQuestions);
if (workloadAnswers.contractArguments) {
try {
JSON.parse(workloadAnswers.contractArguments);
} catch (error) {
this.log('Error: Incorrect array format. Using empty array for arguments. Defaulting to \'[]\' for arguments');
}
}
this.log('For the benchmark configuration file...');
const benchmarkQuestions = {
initialQuestions: [{
type: 'input',
name: 'benchmarkName',
message: 'What would you like to name your benchmark?',
when: () => !this.options.benchmarkName
}, {
type: 'input',
name: 'benchmarkDescription',
message: 'What description would you like to provide for your benchamrk?',
when: () => !this.options.benchmarkDescription
}],
clientQuestions: [{
type: 'number',
name: 'workers',
message: 'How many workers would you like to have?',
default: defaultWorkerCount,
when: () => !this.options.workers
}],
roundQuestions: [{
type: 'input',
name: 'label',
message: 'What label (hint for test) would you like to provide for your benchmark?',
when: () => !this.options.label
}, {
type: 'list',
name: 'rateController',
message: 'Which rate controller would you like to use?',
choices: [
{name: 'Fixed Rate', value: 'fixed-rate'},
{name: 'Fixed Backlog', value: 'fixed-backlog'},
{name: 'Linear Rate', value: 'linear-rate'},
{name: 'Fixed Feedback Rate', value: 'fixed-feedback-rate'}
],
when: () => !this.options.rateController
}, {
type: 'list',
name: 'txType',
message: 'How would you like to measure the length of the round?',
choices: [
{name: 'Transaction Duration', value:'txDuration'},
{name: 'Transaction Number', value: 'txNumber'}
],
when: () => !this.options.txType
}],
txDurationQuestion : [{
type: 'number',
name: 'txDuration',
message: 'How long would you like the round to last?',
default: defaultTxDuration,
when: () => !this.options.txDuration
}],
txNumberQuestion : [{
type: 'number',
name: 'txNumber',
message: 'How many transactions would you like to have in this round?',
default: defaultTxValue,
when: () => !this.options.txNumber
}]
};
const inititalAnswers = await this.prompt(benchmarkQuestions.initialQuestions);
const clientAnswer = await this.prompt(benchmarkQuestions.clientQuestions);
if (isNaN(parseFloat(this.options.workers)) && isNaN(parseFloat(clientAnswer.workers))) {
this.log(`Error: Not a valid input. Using default client value of ${defaultWorkerCount}.`);
}
if (this.options.workers < 0 || clientAnswer.workers < 0) {
this.log(`Error: Negative values not accepted. Defaulting to ${Math.abs(clientAnswer.workers)}.`);
}
const roundAnswers = await this.prompt(benchmarkQuestions.roundQuestions);
let txValueAnswer;
if (roundAnswers.txType === 'txDuration') {
txValueAnswer = await this.prompt(benchmarkQuestions.txDurationQuestion);
if (isNaN(parseFloat(txValueAnswer.txDuration))) {
this.log(`Error: Not a valid input. Using default txDuration value of ${defaultTxDuration}.`);
}
if (txValueAnswer.txDuration < 0) {
this.log(`Error: Negative values not accepted. Defaulting to ${Math.abs(txValueAnswer.txDuration)}.`);
}
}
if (roundAnswers.txType === 'txNumber') {
txValueAnswer = await this.prompt(benchmarkQuestions.txNumberQuestion);
if (isNaN(parseFloat(txValueAnswer.txNumber))) {
this.log(`Error: Not a valid input. Using default txNumber value of ${defaultTxValue}.`);
}
if (txValueAnswer.txNumber < 0) {
this.log(`Error: Negative values not accepted. Defaulting to ${Math.abs(txValueAnswer.txNumber)}.`);
}
}
Object.assign(this.options, workspaceAnswers, workloadAnswers, inititalAnswers, clientAnswer, roundAnswers, txValueAnswer);
promptAnswers = this.options;
}
/**
* Creates the workload module file/workload.
* @private
*/
_workloadWrite() {
answersObject.contractId = promptAnswers.contractId;
answersObject.contractVersion = promptAnswers.contractVersion;
answersObject.contractFunction = promptAnswers.contractFunction;
answersObject.workload = `${ promptAnswers.contractFunction }.js`;
answersObject.pascalCase = camelcase(promptAnswers.contractFunction, { pascalCase: true });
const argsString = promptAnswers.contractArguments;
if (!argsString) {
answersObject.contractArguments = '[]';
} else {
try {
// Should be able to parse the user input
JSON.parse(argsString);
// Successfully parsed, now set it
answersObject.contractArguments = argsString;
} catch (error) {
answersObject.contractArguments = '[]';
}
}
this.fs.copyTpl(
this.templatePath('workload.js'),
this.destinationPath(`${ promptAnswers.workspace }/benchmarks/workloads/${ answersObject.workload }`), answersObject
);
}
/**
* Creates the benchmark configuration file.
* @private
*/
_configWrite() {
answersObject.benchmarkName = promptAnswers.benchmarkName;
answersObject.benchmarkDescription = promptAnswers.benchmarkDescription;
answersObject.workers = promptAnswers.workers;
answersObject.label = promptAnswers.label;
answersObject.txType = promptAnswers.txType;
answersObject.contractId = promptAnswers.contractId;
if (isNaN(promptAnswers.workers)) {
answersObject.workers = defaultWorkerCount;
} else if (promptAnswers.workers < 0) {
answersObject.workers = Math.abs(promptAnswers.workers);
}
else {
answersObject.workers = promptAnswers.workers;
}
if (promptAnswers.txType === 'txDuration') {
if (isNaN(promptAnswers.txDuration)) {
answersObject.txValue = defaultTxDuration;
} else if (promptAnswers.txDuration < 0) {
answersObject.txValue = Math.abs(promptAnswers.txDuration);
} else {
answersObject.txValue = promptAnswers.txDuration;
}
}
if (promptAnswers.txType === 'txNumber') {
if (isNaN(promptAnswers.txNumber)) {
answersObject.txValue = defaultTxValue;
} else if (promptAnswers.txNumber < 0) {
answersObject.txValue = Math.abs(promptAnswers.txNumber);
}
else {
answersObject.txValue = promptAnswers.txNumber;
}
}
this.fs.copyTpl(
this.templatePath('config.yaml'),
this.destinationPath(`${ promptAnswers.workspace }/benchmarks/config.yaml`), answersObject
);
}
/**
* Creates the benchmark artifacts.
*/
async writing () {
console.log('Generating benchmark files...');
this._workloadWrite();
answersObject.rateController = promptAnswers.rateController;
switch(promptAnswers.rateController) {
case 'fixed-rate':
answersObject.opts = 'tps: 10';
this._configWrite();
break;
case 'fixed-backlog':
answersObject.opts = 'unfinished_per_client: 5';
this._configWrite();
break;
case 'linear-rate':
answersObject.opts = 'startingTps: 25, finishingTps: 75';
this._configWrite();
break;
case 'fixed-feedback-rate':
answersObject.opts = 'tps: 100, unfinished_per_client: 100';
this._configWrite();
break;
}
}
/**
* Called at the end of the benchmark generation.
*/
end(){
console.log('Finished generating benchmark files');
}
};
|
'use strict';
goog.module('grrUi.forms.semanticValueFormDirectiveTest');
const {clearCaches} = goog.require('grrUi.forms.semanticValueFormDirective');
const {formsModule} = goog.require('grrUi.forms.forms');
const {testsModule} = goog.require('grrUi.tests');
describe('semantic value form directive', () => {
let $compile;
let $q;
let $rootScope;
let grrSemanticFormDirectivesRegistryService;
let grrReflectionService;
beforeEach(module(formsModule.name));
beforeEach(module(testsModule.name));
beforeEach(inject(($injector) => {
clearCaches();
$compile = $injector.get('$compile');
$rootScope = $injector.get('$rootScope');
$q = $injector.get('$q');
grrSemanticFormDirectivesRegistryService = $injector.get(
'grrSemanticFormDirectivesRegistryService');
grrReflectionService = $injector.get('grrReflectionService');
grrReflectionService.getRDFValueDescriptor = ((valueType) => {
const deferred = $q.defer();
deferred.resolve({
name: valueType,
mro: [valueType],
});
return deferred.promise;
});
}));
const renderTestTemplate = (value, metadata) => {
$rootScope.value = value;
$rootScope.metadata = metadata;
const template = '<grr-form-value value="value" metadata="metadata" />';
const element = $compile(template)($rootScope);
$rootScope.$apply();
return element;
};
it('shows error message if no corresponding directive found', () => {
const fooValue = {
type: 'Foo',
mro: ['Foo'],
value: 'foo',
};
const element = renderTestTemplate(fooValue);
expect(element.text()).toContain('No directive for type: Foo');
});
it('renders registered type with a corresponding directive', () => {
// This directive does not exist and Angular won't process it,
// but it still will be inserted into DOM and we can check
// that it's inserted correctly.
const directiveMock = {
directive_name: 'theTestDirective',
};
grrSemanticFormDirectivesRegistryService.registerDirective(
'Foo', directiveMock);
const fooValue = {
type: 'Foo',
mro: ['Foo'],
value: 'foo',
};
const element = renderTestTemplate(fooValue);
expect($('the-test-directive', element).length).toBe(1);
// Check that registered directive has "value" attribute specified.
expect($('the-test-directive[value]', element).length).toBe(1);
// Check that metadata are passed to the nested directive.
expect($('the-test-directive[metadata]', element).length).toBe(1);
});
it('destroys nested directive\'s scope if value type is changed', () => {
const directiveFooMock = {
directive_name: 'theFooTestDirective',
};
const directiveBarMock = {
directive_name: 'theBarTestDirective',
};
grrSemanticFormDirectivesRegistryService.registerDirective(
'Foo', directiveFooMock);
grrSemanticFormDirectivesRegistryService.registerDirective(
'Bar', directiveBarMock);
const fooValue = {
type: 'Foo',
mro: ['Foo'],
value: 'foo',
};
const barValue = {
type: 'Bar',
mro: ['Bar'],
value: 'bar',
};
const element = renderTestTemplate(fooValue);
expect($('the-foo-test-directive', element).length).toBe(1);
const fooScope = $('the-foo-test-directive', element).scope();
fooScope.foo = 42;
let firesCount = 0;
fooScope.$watch('foo', () => {
firesCount += 1;
});
// Watcher should be called once when it's installed.
$rootScope.$apply();
expect(firesCount).toBe(1);
// Then it should be called when the value changes.
fooScope.foo = 43;
$rootScope.$apply();
expect(firesCount).toBe(2);
// Change the type of the value handled by directive. This should trigger
// it to replace the nested directive.
angular.extend(fooValue, barValue);
$rootScope.$apply();
expect($('the-bar-test-directive', element).length).toBe(1);
// Watchers installed on the directive's scope that corresponds to the
// previous value type (the-foo-test-directive), shouldn't be fired,
// as this scope is supposed to be destroyed.
fooScope.foo = 44;
$rootScope.$apply();
expect(firesCount).toBe(2);
});
});
exports = {};
|
function DashboardAssistant(args) {
this.default_args = {
'template_data': {
'title':'Dashboard Title',
'message':'Dashboard Message',
'count':99
},
'fromstage':SPAZ_MAIN_STAGENAME,
'template':'dashboard/item-info'
};
this.args = sch.defaults(this.default_args, args);
Mojo.Log.info('DashboardAssistant args: %j', args);
/*
this connects App to this property of the appAssistant
*/
App = Spaz.getAppObj();
SpazAuth.addService(SPAZCORE_ACCOUNT_TWITTER, {
authType: SPAZCORE_AUTHTYPE_OAUTH,
consumerKey: SPAZCORE_CONSUMERKEY_TWITTER,
consumerSecret: SPAZCORE_CONSUMERSECRET_TWITTER,
accessURL: 'https://twitter.com/oauth/access_token'
});
}
DashboardAssistant.prototype.setup = function() {
this.updateDashboard();
var switchButton = this.controller.get("dashboardinfo");
Mojo.Event.listen(switchButton, Mojo.Event.tap, this.launchMain.bindAsEventListener(this));
var stageDocument = this.controller.stageController.document;
Mojo.Event.listen(stageDocument, Mojo.Event.stageActivate,
this.activateWindow.bindAsEventListener(this));
Mojo.Event.listen(stageDocument, Mojo.Event.stageDeactivate,
this.deactivateWindow.bindAsEventListener(this));
};
DashboardAssistant.prototype.activate = function(event) {
/* put in event handlers here that should only be in effect when this scene is active. For
example, key handlers that are observing the document */
};
DashboardAssistant.prototype.deactivate = function(event) {
/* remove any event handlers you added in activate and do any other cleanup that should happen before
this scene is popped or another scene is pushed on top */
};
DashboardAssistant.prototype.cleanup = function(event) {
/* this function should do any cleanup needed before the scene is destroyed as
a result of being popped off the scene stack */
};
DashboardAssistant.prototype.updateDashboard = function(args) {
this.args = sch.defaults(this.default_args, args);
Mojo.Log.error("updateDashboard Args: %j", args);
/*
Use render to convert the object and its properties
along with a view file into a string containing HTML
*/
var renderedInfo = Mojo.View.render({object: this.args.template_data, template: this.args.template});
var infoElement = this.controller.get('dashboardinfo');
infoElement.update(renderedInfo);
/*
Flash the LED, if it's enabled in system settings
*/
this.controller.stageController.indicateNewContent(true);
};
DashboardAssistant.prototype.activateWindow = function() {
Mojo.Log.error("......... Dashboard Assistant - Activate Window");
};
DashboardAssistant.prototype.deactivateWindow = function() {
Mojo.Log.error("......... Dashboard Assistant - Deactivate Window");
};
DashboardAssistant.prototype.launchMain = function() {
this.controller.serviceRequest('palm://com.palm.applicationManager', {
method: 'launch',
parameters: {
id: Mojo.appInfo.id,
params: {'fromstage':this.args.fromstage, 'action':'main_timeline', 'account':App.prefs.get('last_userid')}
}
});
this.controller.window.close();
};
|
import React, { Component } from 'react'
import {
View,
TouchableHighlight,
Text,
StyleSheet,
Dimensions
} from 'react-native'
export default props => {
const stylesButton = [styles.button]
if (props.double) stylesButton.push(styles.buttonDouble)
if (props.triple) stylesButton.push(styles.buttonTriple)
if (props.operation) stylesButton.push(styles.operationButton)
return (
<TouchableHighlight onPress={() => props.onClick(props.label)}>
<Text style={stylesButton}>
{props.label}
</Text>
</TouchableHighlight>
)
}
const styles = StyleSheet.create({
button: {
fontSize: 40,
height: Dimensions.get('window').width / 4,
width: Dimensions.get('window').width / 4,
padding: 20,
backgroundColor: '#f0f0f0f0',
textAlign: 'center',
borderWidth: 1,
borderColor: '#888',
},
operationButton: {
color: '#fff',
backgroundColor: '#fa8231',
},
buttonDouble: {
width: (Dimensions.get('window').width / 4) * 2,
},
buttonTriple: {
width: (Dimensions.get('window').width / 4) * 3,
}
})
|
"""
Unit tests for Unified/RequestInfo.py module
Author: Valentin Kuznetsov <vkuznet [AT] gmail [DOT] com>
"""
from __future__ import division, print_function
import unittest
from WMCore.MicroService.MSTransferor.RequestInfo import RequestInfo
class RequestInfoTest(unittest.TestCase):
"Unit test for RequestInfo module"
def setUp(self):
self.mode = 'test'
self.reqInfo = RequestInfo(microConfig={}, uniConfig={})
if __name__ == '__main__':
unittest.main()
|
define(['exports', 'external'], (function (exports, foo$1) { 'use strict';
var _interopDefaultLegacy = e => e && typeof e === 'object' && 'default' in e ? e : { 'default': e };
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(k => {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: () => e[k]
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var foo__default = /*#__PURE__*/_interopDefaultLegacy(foo$1);
var foo__namespace = /*#__PURE__*/_interopNamespace(foo$1);
var _missingExportShim = void 0;
const foo = 'bar';
var other = /*#__PURE__*/Object.freeze({
__proto__: null,
foo: foo,
missing: _missingExportShim
});
var synthetic = { bar: 'baz' };
console.log(foo__default["default"], foo__namespace, other, bar, _missingExportShim);
var main = 42;
exports["default"] = main;
exports.syntheticMissing = synthetic.syntheticMissing;
Object.keys(foo$1).forEach(k => {
if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
enumerable: true,
get: () => foo$1[k]
});
});
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
(function (root, factory) {
var freeExports = typeof exports == 'object' && exports &&
(typeof root == 'object' && root && root == root.global && (window = root), exports);
// Because of build optimizers
if (typeof define === 'function' && define.amd) {
define(['rx', 'exports'], function (Rx, exports) {
root.Rx = factory(root, exports, Rx);
return root.Rx;
});
} else if (typeof module == 'object' && module && module.exports == freeExports) {
module.exports = factory(root, module.exports, require('./rx'));
} else {
root.Rx = factory(root, {}, root.Rx);
}
}(this, function (global, exp, root, undefined) {
var Observable = root.Observable,
observableProto = Observable.prototype,
AnonymousObservable = root.Internals.AnonymousObservable,
Subject = root.Subject,
AsyncSubject = root.AsyncSubject,
Observer = root.Observer,
ScheduledObserver = root.Internals.ScheduledObserver,
disposableCreate = root.Disposable.create,
disposableEmpty = root.Disposable.empty,
CompositeDisposable = root.CompositeDisposable,
currentThreadScheduler = root.Scheduler.currentThread,
inherits = root.Internals.inherits,
addProperties = root.Internals.addProperties;
// Utilities
var objectDisposed = 'Object has been disposed';
function checkDisposed() {
if (this.isDisposed) {
throw new Error(objectDisposed);
}
}
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param selector [Optional] Selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @return An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* 1 - res = source.publish();
* 2 - res = source.publish(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @return An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return !selector ?
this.multicast(new Subject()) :
this.multicast(function () {
return new Subject();
}, selector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* 1 - res = source.publishLast();
* 2 - res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @return An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return !selector ?
this.multicast(new AsyncSubject()) :
this.multicast(function () {
return new AsyncSubject();
}, selector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* 1 - res = source.publishValue(42);
* 2 - res = source.publishLast(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param initialValue Initial value received by observers upon subscription.
* @return An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* 1 - res = source.replay(null, 3);
* 2 - res = source.replay(null, 3, 500);
* 3 - res = source.replay(null, 3, 500, scheduler);
* 4 - res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @return An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return !selector ?
this.multicast(new ReplaySubject(bufferSize, window, scheduler)) :
this.multicast(function () {
return new ReplaySubject(bufferSize, window, scheduler);
}, selector);
};
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = root.BehaviorSubject = (function () {
function subscribe(observer) {
var ex;
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
ex = this.exception;
if (ex) {
observer.onError(ex);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, Observable);
/**
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
*
* @param value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
BehaviorSubject.super_.constructor.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.exception = null;
}
addProperties(BehaviorSubject.prototype, Observer, {
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
this.value = value;
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}());
// Replay Subject
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = root.ReplaySubject = (function (base) {
var RemovableDisposable = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
RemovableDisposable.prototype.dispose = function () {
this.observer.dispose();
if (!this.subject.isDisposed) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
}
};
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = new RemovableDisposable(this, so);
checkDisposed.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
var n = this.q.length;
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
n++;
so.onError(this.error);
} else if (this.isStopped) {
n++;
so.onCompleted();
}
so.ensureActive(n);
return subscription;
}
inherits(ReplaySubject, Observable);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window and scheduler.
*
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [window] Maximum time length of the replay buffer.
* @param [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, window, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.window = window == null ? Number.MAX_VALUE : window;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
ReplaySubject.super_.constructor.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer, {
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.window) {
this.q.shift();
}
},
onNext: function (value) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onNext(value);
observer.ensureActive();
}
}
},
onError: function (error) {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
}
},
onCompleted: function () {
var observer;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
observer = o[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers = [];
}
},
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}());
var ConnectableObservable = (function () {
inherits(ConnectableObservable, Observable);
function ConnectableObservable(source, subject) {
var state = {
subject: subject,
source: source.asObservable(),
hasSubscription: false,
subscription: null
};
this.connect = function () {
if (!state.hasSubscription) {
state.hasSubscription = true;
state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () {
state.hasSubscription = false;
}));
}
return state.subscription;
};
var subscribe = function (observer) {
return state.subject.subscribe(observer);
};
ConnectableObservable.super_.constructor.call(this, subscribe);
}
ConnectableObservable.prototype.connect = function () { return this.connect(); };
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription = null,
count = 0,
source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect, subscription;
count++;
shouldConnect = count === 1;
subscription = source.subscribe(observer);
if (shouldConnect) {
connectableSubscription = source.connect();
}
return disposableCreate(function () {
subscription.dispose();
count--;
if (count === 0) {
connectableSubscription.dispose();
}
});
});
};
return ConnectableObservable;
}());
return root;
}));
|
// 'use strict'
// import React from 'react'
// import TestUtils from 'react-addons-test-utils'
// import App from '../app/js/App'
// // import CurrentUserStore from '../app/js/stores/CurrentUserStore'
// // import CurrentUserActions from '../app/js/actions/CurrentUserActions'
// // import {ListenerMixin} from 'reflux'
// import TestHelpers from './testHelpers'
// describe('App', function() {
// // it('#componentDidMount should listen to the user store and check login status', function() {
// // sandbox.mock(ListenerMixin).expects('listenTo').withArgs(CurrentUserStore, App._onUserChange).once()
// // sandbox.mock(CurrentUserActions).expects('checkLoginStatus').once()
// // TestUtils.renderIntoDocument(
// // <App params={{}} query={{}}>
// // <div />
// // </App>
// // )
// // })
// it('#onUserChange should set the error state if an error is received', function() {
// const err = { message: 'Test error message.' }
// const app = TestUtils.renderIntoDocument(
// <App params={{}} query={{}}>
// <div />
// </App>
// )
// app.onUserChange(err, null)
// app.state.error.should.eql(err)
// })
// it('#onUserChange should set the user state and clear error if a new user is received', function() {
// const user = TestHelpers.fixtures.user
// const app = TestUtils.renderIntoDocument(
// <App params={{}} query={{}}>
// <div />
// </App>
// )
// app.onUserChange(null, user)
// app.state.currentUser.should.eql(user)
// Should(app.state.error).be.null()
// })
// it('#renderChildren should return all the cloned children', function() {
// const app = TestUtils.renderIntoDocument(
// <App params={{}} query={{}}>
// <div className="test-child" />
// </App>
// )
// TestUtils.findRenderedDOMComponentWithClass(app, 'test-child').should.not.throw()
// })
// })
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# pylint: disable=invalid-name,arguments-differ,no-else-return,unused-argument,missing-docstring
"""
Relay TensorRT codegen.
"""
import os
import numpy as np
import tvm
import tvm.ir
import tvm.relay.transform as transform
from tvm import relay
from tvm.relay.expr import Call, Constant, Tuple, GlobalVar, Var, TupleGetItem
from tvm.relay.build_module import bind_params_by_name
from tvm.relay.transform import _ffi_api
from tvm.relay.expr_functor import ExprMutator
class LegalizeLayoutTranform(ExprMutator):
"""
Legalize Relay layout transforms to transpose ops to simplify TensorRT conversion.
"""
def visit_call(self, expr):
visit = super().visit_call(expr)
if expr.op == tvm.relay.op.get("layout_transform"):
src_layout = expr.attrs["src_layout"]
dst_layout = expr.attrs["dst_layout"]
if src_layout == "NCHW" and dst_layout == "NHWC":
return relay.transpose(visit.args[0], axes=[0, 2, 3, 1])
elif src_layout == "NHWC" and dst_layout == "NCHW":
return relay.transpose(visit.args[0], axes=[0, 3, 1, 2])
elif src_layout == "NDHWC" and dst_layout == "NCDHW":
return relay.transpose(visit.args[0], axes=[0, 4, 1, 2, 3])
elif src_layout == "NCDHW" and dst_layout == "NDHWC":
return relay.transpose(visit.args[0], axes=[0, 2, 3, 4, 1])
elif src_layout == "HWIO" and dst_layout == "OIHW":
return relay.transpose(visit.args[0], axes=[3, 2, 0, 1])
elif src_layout == "HWOI" and dst_layout == "OIHW":
return relay.transpose(visit.args[0], axes=[2, 3, 0, 1])
elif src_layout == "HWIO" and dst_layout == "IOHW":
return relay.transpose(visit.args[0], axes=[2, 3, 0, 1])
return visit
class RemoveDropout(ExprMutator):
"""
Removes all nn.dropout from an expr.
"""
def visit_tuple_getitem(self, expr):
visit = super().visit_tuple_getitem(expr)
if visit.index != 0:
return visit
elif isinstance(visit.tuple_value, Call) and visit.tuple_value.op.name == "nn.dropout":
return visit.tuple_value.args[0]
return visit
@transform.function_pass(opt_level=0)
class LegalizeLayoutTranformPass:
def transform_function(self, func, mod, _):
return LegalizeLayoutTranform().visit(func)
@transform.function_pass(opt_level=0)
class RemoveDropoutPass:
def transform_function(self, func, mod, _):
return RemoveDropout().visit(func)
def GetTrtVersion():
"""Gets the version of TensorRT that TVM is built against.
Returns
-------
ret: Tuple[int]
TensorRT version as a tuple of major, minor, and patch number. If TVM
is not built with TensorRT, an empty tuple is returned instead.
"""
return tuple(map(int, _ffi_api.GetTrtVersion()))
def IsTrtRuntimeAvailable():
if not tvm.get_global_func("relay._transform.GetTrtVersion", True):
return False
return GetTrtVersion() != ()
def check_dynamism(args, op_name):
"""
This function checks for dynamism inside any of the args in the op.
Can be used to offload dynamic ops that are not supported by TRT to
be offloaded to relay VM.
Raises a NotImplementedError if the type of the arg is not of types
Call, Var, Constant, or TupleGetItem.
Parameters
----------
args: a TRT array of the arguments of the op
op_name: name of the op for debugging purposes only
Returns
----------
True if dynamism is present, False otherwise
"""
for arg in args:
if isinstance(arg, (Call, Var, Constant, TupleGetItem)):
for dim_shape in arg.checked_type.shape:
if isinstance(dim_shape, tvm.tir.expr.Any):
print(
"Dynamic inputs are not supported for TensorRT for ",
op_name,
arg.checked_type.shape,
)
return True
elif isinstance(arg, Tuple):
return check_dynamism(arg.fields, op_name)
else:
raise NotImplementedError(type(arg))
return False
def _register_external_op_helper(op_name, supported=True):
@tvm.ir.register_op_attr(op_name, "target.tensorrt")
def _func_wrapper(attrs, args):
if check_dynamism(args, op_name):
return False
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
return supported
return _func_wrapper
def _register_external_op_helper_func(op_name, func, trt_version):
@tvm.ir.register_op_attr(op_name, "target.tensorrt")
def _func_wrapper(attrs, args):
if check_dynamism(args, op_name):
return False
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
return func(attrs, args, op_name, trt_version)
return _func_wrapper
def _register_external_dynamic_check_func(op_name, func):
@tvm.ir.register_op_attr(op_name, "target.tensorrt")
def _func_wrapper(attrs, args):
if check_dynamism(args, op_name):
return False
return func(attrs, args)
return _func_wrapper
def register_tensorrt_annotations(trt_version, use_implicit_batch=True):
if hasattr(register_tensorrt_annotations, "registered"):
# Can't register annotations more than once.
return
register_tensorrt_annotations.registered = True
if not use_implicit_batch and trt_version < (6, 0, 1):
print("Explicit batch mode only available for TRT 6+")
use_implicit_batch = True
# Ops which are always supported
_register_external_op_helper("nn.relu")
_register_external_op_helper("sigmoid")
_register_external_op_helper("tanh")
_register_external_op_helper("subtract")
_register_external_op_helper("multiply")
_register_external_op_helper("divide")
_register_external_op_helper("power")
_register_external_op_helper("maximum")
_register_external_op_helper("minimum")
_register_external_op_helper("exp")
_register_external_op_helper("log")
_register_external_op_helper("sqrt")
_register_external_op_helper("abs")
_register_external_op_helper("negative")
_register_external_op_helper("nn.batch_flatten")
_register_external_op_helper("clip")
# TODO(trevmorr): Temporarily disable split due to TRT bug on xavier.
# _register_external_op_helper("split")
# _register_external_op_helper("slice_like")
def add_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if (
(isinstance(args[0], Constant) or isinstance(args[1], Constant))
and args[0].checked_type.shape[0] == args[0].checked_type.shape[0]
and args[0].checked_type.shape[0] != 1
and (len(args[0].checked_type.shape) > 3 or len(args[1].checked_type.shape) > 3)
):
print("add: bug in TRT with adding batched constants.")
return False
# Skip this add op in TRT to avoid accuracy mismatch
if all([list(map(int, arg.checked_type.shape)) == [1, 546, 1, 1] for arg in args]):
print("add: bug in TRT with add of shape (1, 546, 1, 1).")
return False
return True
def batch_norm_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if int(attrs.axis) != 1 and int(attrs.axis) != 3:
print("nn.batch_norm: axis is {} but must be 1 or 3.".format(int(attrs.axis)))
return False
return True
def softmax_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if use_implicit_batch and int(attrs.axis) == 0:
print("nn.softmax: can't modify batch dimension.")
return False
return True
def conv2d_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if attrs.data_layout != "NCHW":
print("nn.conv2d: data_layout is {} but must be NCHW.".format(attrs.data_layout))
return False
if attrs.kernel_layout != "OIHW":
print("nn.conv2d: kernel_layout is {} but must be OIHW.".format(attrs.kernel_layout))
return False
if attrs.out_layout and attrs.out_layout != "NCHW":
print("nn.conv2d: out_layout is {} but must be NCHW.".format(attrs.out_layout))
return False
return True
def dense_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
input_rank = len(args[0].checked_type.shape)
weight_rank = len(args[1].checked_type.shape)
if input_rank < 2 or input_rank > 4:
print("nn.dense: input has rank {} but must be 2, 3 or 4.".format(input_rank))
return False
if weight_rank != 2:
print("nn.dense: weight has rank {} but must be 2.".format(weight_rank))
return False
return True
def bias_add_whitelist_fn(attrs, args): # pylint: disable=unused-variable
# TODO(trevmorr): BiasAddSimplifier creates a pattern which cannot be
# converted to TRT without binding params and constant folding.
# if trt_version < (6, 0, 1):
# return False
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
input_rank = len(args[0].checked_type.shape)
if input_rank < 2 or input_rank > 4:
print("nn.bias_add: input rank is {} but must be 2, 3 or 4.".format(input_rank))
return False
return True
def max_pool_2d_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if attrs.layout != "NCHW":
print("nn.max_pool2d: layout is {} but must be NCHW.".format(attrs.layout))
return False
if attrs.ceil_mode and trt_version < (5, 1, 5):
print("nn.avg_pool2d: ceil_mode=True requires TensorRT 5.1.5 or greater.")
return False
return True
def avg_pool_2d_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if attrs.layout != "NCHW":
print("nn.avg_pool2d: layout is {} but must be NCHW.".format(attrs.layout))
return False
if (
attrs.count_include_pad
and len(attrs.padding) == 4
and (
int(attrs.padding[0]) != int(attrs.padding[2])
or int(attrs.padding[1]) != int(attrs.padding[3])
)
):
print(
"nn.avg_pool2d: inclusive-counted blended or average "
"pooling is not supported in combination with asymmetric padding"
)
return False
if attrs.ceil_mode and trt_version < (5, 1, 5):
print("nn.avg_pool2d: ceil_mode=True requires TensorRT 5.1.5 or greater.")
return False
return True
def global_max_pool_2d_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if attrs.layout != "NCHW":
print("nn.global_max_pool2d: layout is {} but must be NCHW.".format(attrs.layout))
return False
return True
def global_avg_pool_2d_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if attrs.layout != "NCHW":
print("nn.global_avg_pool2d: layout is {} but must be NCHW.".format(attrs.layout))
return False
return True
def expand_dims_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if use_implicit_batch and int(attrs.axis) == 0:
print("expand_dims: can't modify batch dimension.")
return False
return True
def squeeze_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if not attrs.axis:
print("squeeze: must explicitly set axis.")
return False
if use_implicit_batch and any([axis == 0 for axis in map(int, attrs.axis)]):
print("squeeze: can't modify batch dimension.")
return False
return True
def concatenate_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.dtype != "float32" for x in args[0].checked_type.fields]):
print("Only float32 inputs are supported for TensorRT.")
return False
if not use_implicit_batch:
return True
if int(attrs.axis) == 0:
print("concatenate: can't modify batch dimension.")
return False
if isinstance(args[0], Tuple):
for tuple_input in args[0].fields:
if isinstance(tuple_input, Constant):
print("concatenate: can't concatenate tensors with constants.")
return False
return True
def conv2d_transpose_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if attrs.data_layout != "NCHW":
print(
"nn.conv2d_transpose: data_layout is {} but must be NCHW.".format(attrs.data_layout)
)
return False
if attrs.kernel_layout != "OIHW":
print(
"nn.conv2d_transpose: kernel_layout is {} but must be OIHW.".format(
attrs.kernel_layout
)
)
return False
if attrs.out_layout and attrs.out_layout != "NCHW":
print(
"nn.conv2d_transpose: out_layout is {} but must be NCHW.".format(attrs.out_layout)
)
return False
if attrs.dilation and any([rate != 1 for rate in map(int, attrs.dilation)]):
print("nn.conv2d_transpose: dilation rate must be 1.")
return False
return True
def transpose_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if use_implicit_batch and int(attrs.axes[0]) != 0:
print("transpose: can't modify batch dimension.")
return False
return True
def reshape_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if args[0].checked_type.dtype != "float32":
print("Only float32 inputs are supported for TensorRT.")
return False
if any([x < -1 for x in map(int, attrs.newshape)]):
print("reshape: new shape dims must be explicit.")
return False
if use_implicit_batch:
shape = list(map(int, args[0].checked_type.shape))
new_shape = list(map(int, attrs.newshape))
if len(new_shape) == 0 or len(shape) == 0:
print("reshape: Can't reshape to or from scalar.")
return False
# TRT cannot modify batch dimension.
original_volume = np.prod(shape)
# First, resolve 0.
for i, value in enumerate(new_shape):
if value == 0:
new_shape[i] = shape[i]
# Resolve -1.
for i, value in enumerate(new_shape):
if value == -1:
new_shape[i] = original_volume // np.prod([x for x in new_shape if x != -1])
# Remove batch dimension and see if volumes match
if shape[0] != new_shape[0]:
print("reshape: can't modify batch dimension.")
return False
return True
def pad_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if attrs.pad_mode != "constant":
print("nn.pad: pad mode is {} but must be constant.".format(attrs.pad_mode))
return False
if float(attrs.pad_value) != 0.0:
print("nn.pad: pad value is {} but must be 0.0.".format(float(attrs.pad_value)))
return False
return True
def reduce_whitelist_fn(attrs, args, op_name, trt_version):
if not attrs.axis or len(attrs.axis) == 0:
print("{}: cannot reduce to scalar.".format(op_name))
return False
if attrs.exclude:
print("{}: exclude not supported.".format(op_name))
return False
if use_implicit_batch and any([x == 0 for x in map(int, attrs.axis)]):
print("{}: can't modify batch dimension.".format(op_name))
return False
return True
def trt_5_1_5_whitelist_fn(attrs, args, op_name, trt_version):
if trt_version < (5, 1, 5):
print("{}: requires TensorRT version 5.1.5 or higher.".format(op_name))
return False
return True
_register_external_op_helper_func("sum", reduce_whitelist_fn, trt_version)
_register_external_op_helper_func("prod", reduce_whitelist_fn, trt_version)
_register_external_op_helper_func("max", reduce_whitelist_fn, trt_version)
_register_external_op_helper_func("min", reduce_whitelist_fn, trt_version)
_register_external_op_helper_func("mean", reduce_whitelist_fn, trt_version)
_register_external_op_helper_func("nn.leaky_relu", trt_5_1_5_whitelist_fn, trt_version)
_register_external_op_helper_func("sin", trt_5_1_5_whitelist_fn, trt_version)
_register_external_op_helper_func("cos", trt_5_1_5_whitelist_fn, trt_version)
_register_external_op_helper_func("atan", trt_5_1_5_whitelist_fn, trt_version)
_register_external_op_helper_func("ceil", trt_5_1_5_whitelist_fn, trt_version)
def strided_slice_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if trt_version < (5, 1, 5):
print("strided_slice: requires TensorRT version 5.1.5 or higher.")
return False
if args[0].checked_type.dtype != "float32":
print("strided_slice: only fp32 inputs are supported.")
return False
if use_implicit_batch:
batch_dim_begin_modified = attrs.begin[0] is not None and int(attrs.begin[0]) != 0
batch_dim_end_modified = (
attrs.end[0] is not None
and int(attrs.end[0]) != -1
and int(attrs.end[0]) != int(args[0].checked_type.shape[0])
)
if batch_dim_begin_modified or batch_dim_end_modified:
print("strided_slice: can't modify batch dimension.")
return False
if any([x is not None and x <= 0 for x in attrs.strides]):
print("strided_slice: stride must be positive")
return False
return True
def resize_whitelist_fn(attrs, args): # pylint: disable=unused-variable
# TODO(trevmorr): Output does not match TVM. Disable.
return False
def adapative_max_pool2d_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if len(attrs.output_size) == 0 or any([size != 1 for size in map(int, attrs.output_size)]):
print("nn.adaptive_max_pool2d: output size must be (1, 1).")
return False
return True
def adapative_avg_pool2d_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if len(attrs.output_size) == 0 or any([size != 1 for size in map(int, attrs.output_size)]):
print("nn.adaptive_avg_pool2d: output size must be (1, 1).")
return False
return True
def upsampling_whitelist_fn(attrs, args): # pylint: disable=unused-variable
# TODO(trevmorr): Output does not match TVM. Disable.
return False
def conv3d_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if trt_version < (6, 0, 1):
print("nn.conv3d: requires TensorRT version 6.0.1 or higher.")
return False
if attrs.data_layout != "NCDHW":
print("nn.conv3d: data_layout is {} but must be NCDHW.".format(attrs.data_layout))
return False
if attrs.kernel_layout != "OIDHW":
print("nn.conv3d: kernel_layout is {} but must be OIDHW.".format(attrs.kernel_layout))
return False
if attrs.out_layout and attrs.out_layout != "NCDHW":
print("nn.conv3d: out_layout is {} but must be NCDHW.".format(attrs.out_layout))
return False
return True
def max_pool_3d_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if trt_version < (6, 0, 1):
print("nn.max_pool3d: requires TensorRT version 6.0.1 or higher.")
return False
if attrs.layout != "NCDHW":
print("nn.max_pool3d: layout is {} but must be NCDHW.".format(attrs.layout))
return False
return True
def avg_pool_3d_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if trt_version < (6, 0, 1):
print("nn.avg_pool3d: requires TensorRT version 6.0.1 or higher.")
return False
if attrs.layout != "NCDHW":
print("nn.avg_pool3d: layout is {} but must be NCDHW.".format(attrs.layout))
return False
return True
def conv3d_transpose_whitelist_fn(attrs, args): # pylint: disable=unused-variable
if any([x.checked_type.dtype != "float32" for x in args]):
print("Only float32 inputs are supported for TensorRT.")
return False
if trt_version < (6, 0, 1):
print("nn.conv3d_transpose: requires TensorRT version 6.0.1 or higher.")
return False
if attrs.data_layout != "NCDHW":
print(
"nn.conv3d_transpose: data_layout is {} but must be NCDHW.".format(
attrs.data_layout
)
)
return False
if attrs.kernel_layout != "OIDHW":
print(
"nn.conv3d_transpose: kernel_layout is {} but must be OIDHW.".format(
attrs.kernel_layout
)
)
return False
if attrs.out_layout and attrs.out_layout != "NCDHW":
print(
"nn.conv3d_transpose: out_layout is {} but must be NCDHW.".format(attrs.out_layout)
)
return False
if attrs.dilation and any([rate != 1 for rate in map(int, attrs.dilation)]):
print("nn.conv3d_transpose: dilation rate must be 1.")
return False
if attrs.output_padding and any([x != 0 for x in map(int, attrs.output_padding)]):
print("nn.conv3d_transpose: output padding is not supported.")
return False
return True
_register_external_dynamic_check_func("add", add_whitelist_fn)
_register_external_dynamic_check_func("nn.batch_norm", batch_norm_whitelist_fn)
_register_external_dynamic_check_func("nn.softmax", softmax_whitelist_fn)
_register_external_dynamic_check_func("nn.conv2d", conv2d_whitelist_fn)
_register_external_dynamic_check_func("nn.dense", dense_whitelist_fn)
_register_external_dynamic_check_func("nn.bias_add", bias_add_whitelist_fn)
_register_external_dynamic_check_func("nn.max_pool2d", max_pool_2d_whitelist_fn)
_register_external_dynamic_check_func("nn.avg_pool2d", avg_pool_2d_whitelist_fn)
_register_external_dynamic_check_func("nn.global_max_pool2d", global_max_pool_2d_whitelist_fn)
_register_external_dynamic_check_func("nn.global_avg_pool2d", global_avg_pool_2d_whitelist_fn)
_register_external_dynamic_check_func("expand_dims", expand_dims_whitelist_fn)
_register_external_dynamic_check_func("squeeze", squeeze_whitelist_fn)
_register_external_dynamic_check_func("concatenate", concatenate_whitelist_fn)
_register_external_dynamic_check_func("nn.conv2d_transpose", conv2d_transpose_whitelist_fn)
_register_external_dynamic_check_func("transpose", transpose_whitelist_fn)
_register_external_dynamic_check_func("reshape", reshape_whitelist_fn)
_register_external_dynamic_check_func("nn.pad", pad_whitelist_fn)
_register_external_dynamic_check_func("strided_slice", strided_slice_whitelist_fn)
_register_external_dynamic_check_func("image.resize", resize_whitelist_fn)
_register_external_dynamic_check_func(
"nn.adaptive_max_pool2d", adapative_max_pool2d_whitelist_fn
)
_register_external_dynamic_check_func(
"nn.adaptive_avg_pool2d", adapative_avg_pool2d_whitelist_fn
)
_register_external_dynamic_check_func("nn.upsampling", upsampling_whitelist_fn)
_register_external_dynamic_check_func("nn.conv3d", conv3d_whitelist_fn)
_register_external_dynamic_check_func("nn.max_pool3d", max_pool_3d_whitelist_fn)
_register_external_dynamic_check_func("nn.avg_pool3d", avg_pool_3d_whitelist_fn)
_register_external_dynamic_check_func("nn.conv3d_transpose", conv3d_transpose_whitelist_fn)
class VarReplacer(ExprMutator):
"""
Visit an expression while replacing vars according to var_map. Used by
SubgraphRemover/PruneSubgraphs to return a subgraph originally partitioned to TRT back to TVM.
"""
def __init__(self, var_map):
ExprMutator.__init__(self)
self.var_map = var_map
def visit_var(self, var):
if var in self.var_map:
return self.var_map[var]
return super().visit_var(var)
class SubgraphRemover(ExprMutator):
"""
Reverts subgraphs in subgraphs_to_remove back to TVM instead of using an external codegen.
"""
def __init__(self, subgraphs_to_remove, mod, new_mod):
ExprMutator.__init__(self)
self.subgraphs_to_remove = subgraphs_to_remove
self.mod = mod
self.new_mod = new_mod
def visit_call(self, call):
if isinstance(call.op, GlobalVar):
name = call.op.name_hint
if name in self.subgraphs_to_remove:
# "Inline" the subgraph back into new main function.
func = self.mod[name]
var_map = {}
for arg, param in zip(call.args, func.params):
var_map[param] = super().visit(arg)
new_body = VarReplacer(var_map).visit(func.body)
return new_body
elif name != "main":
# Copy the GlobalVar (subgraph function) to the new module and call.
args = []
for arg in call.args:
args.append(super().visit(arg))
return call.op(*args)
return super().visit_call(call)
def PruneSubgraphs(mod, compiler="tensorrt", use_implicit_batch=True, prune_no_macs=False):
"""
If use_implicit_batch is True, removes subgraphs which were originally partitioned for TRT
that are incompatible with implicit batch mode.
If prune_no_macs is True, also remove subgraph if the number of multiply-accumulates is 0.
This is a heuristic which can improve performance by around 5% because TVM provides better
optimization for certain ops.
Parameters
----------
mod: Module
The module which has been partitioned for tensorrt compiler.
compiler : str
Compiler string, should be "tensorrt".
use_implicit_batch : bool
Which mode we plan to use for TensorRT. Will be used to determine which subgraphs are
valid. In implicit batch mode, all inputs to a subgraph must have the same batch size.
prune_no_macs : bool
Whether to also remove subgraphs which have no multiple-accumulate operations.
Returns
-------
mod: Module
The modified module which has pruned subgraphs reverted back to TVM.
"""
subgraphs_to_remove = []
def is_valid_subgraph(func):
"""Whether a subgraph is valid in TRT.
Returns
-------
compatible : bool
True if the subgraph is compatible with TRT.
"""
if not use_implicit_batch:
return True
input_batch_sizes = []
for var in func.params:
# In implicit batch mode, all inputs must have same batch size
if isinstance(var.checked_type, relay.TupleType):
for tupe_type in var.checked_type.fields:
# Scalar inputs not allowed
if len(tupe_type.shape) == 0:
return False
input_batch_sizes.append(int(tupe_type.shape[0]))
else:
# Scalar inputs not allowed
if len(var.checked_type.shape) == 0:
return False
input_batch_sizes.append(int(var.checked_type.shape[0]))
if len(input_batch_sizes) > 1 and any(
[x != input_batch_sizes[0] for x in input_batch_sizes[1:]]
):
return False
return True
# Remove invalid subgraphs
for subgraph in mod.get_global_vars():
name = subgraph.name_hint
if (
mod[name].attrs
and hasattr(mod[name].attrs, "SkipOptimization")
and mod[name].attrs["SkipOptimization"] == 1
):
continue
if not mod[name].attrs or mod[name].attrs["Compiler"] != compiler:
continue
if not is_valid_subgraph(mod[name]):
subgraphs_to_remove.append(name)
# Remove subgraphs with no multiply-accumulates
if prune_no_macs:
subgraph_with_macs = []
for subgraph in mod.get_global_vars():
name = subgraph.name_hint
if (
mod[name].attrs
and hasattr(mod[name].attrs, "SkipOptimization")
and mod[name].attrs["SkipOptimization"] == 1
):
continue
if not mod[name].attrs or mod[name].attrs["Compiler"] != compiler:
continue
num_macs = relay.analysis.get_total_mac_number(mod[name])
subgraph_with_macs.append([name, num_macs])
print("Subgraphs with computed # of MACS:", subgraph_with_macs)
subgraphs_to_remove.extend([name for name, num_macs in subgraph_with_macs if num_macs == 0])
if len(subgraphs_to_remove) == 0:
return mod
print("Will remove these subgraphs:", subgraphs_to_remove)
# Create new pruned module with functions and type defns from mod
new_mod = tvm.IRModule(mod.functions, mod.type_definitions)
new_mod["main"] = SubgraphRemover(subgraphs_to_remove, mod, new_mod).visit(mod["main"])
return new_mod
def EnableTrt(
mod,
params=None,
trt_version=None,
use_implicit_batch=True,
max_workspace_size=1 << 30,
prune_subgraphs=False,
):
"""Converts the "main" function in the module into one that can be executed using
TensorRT. If any of the operators are not supported by the TensorRT
conversion, the unmodified program will be returned instead.
Parameters
----------
mod: Module
The original module.
params : dict of str to NDArray
Input parameters to the graph that do not change
during inference time. Used for constant folding.
trt_version : Optional[Tuple[int]]
Which version of TensorRT to target for partitioning as a tuple of
(major, minor, patch). If not specified, will attempt to get using
GetTrtVersion.
use_implicit_batch : bool
If false, will use explicit batch mode. Explicit batch mode is
available in TRT 6+. It increases operator coverage but comes at a
performance penalty.
max_workspace_size : int
Number of bytes for TensorRT workspace size.
prune_subgraphs : bool
If true, will prune subgraphs with 0 MACS and run them with TVM instead.
Returns
-------
mod: Module
The modified module which will use the TensorRT runtime if compatible.
"""
if not trt_version:
trt_version = GetTrtVersion()
# If TVM wasn't built against TRT, default to target TRT 6. Since the
# actual conversion to TRT is done at runtime, building against TRT is
# not required for compilation.
if not trt_version:
trt_version = (6, 0, 1)
assert isinstance(trt_version, (list, tuple))
assert len(trt_version) == 3
register_tensorrt_annotations(trt_version, use_implicit_batch=use_implicit_batch)
def _set_optimization_attr(mod, skip_optimization=1):
"""
Prepare the mod such that all functions except main are tagged for SkipOptimization
:param mod: input TRT mod
:param skip_optimization: flag to set SkipOptimization for all functions except main
:return: updated mod
"""
gvs = mod.get_global_vars()
for gv in gvs:
func = mod[gv]
name = gv.name_hint
if name != "main":
new_func = func.with_attr(
"SkipOptimization", tvm.tir.IntImm("int32", skip_optimization)
)
mod.update_func(gv, new_func)
return mod
if params:
# Bind params so that we can use FoldConstant.
mod["main"] = bind_params_by_name(mod["main"], params)
# Apply passes required for TRT
mod = transform.InferType()(mod)
seq = tvm.transform.Sequential(
[
transform.InferType(),
RemoveDropoutPass(),
transform.RemoveUnusedFunctions(),
transform.ConvertLayout(
{
"nn.conv2d": ["NCHW", "default"],
"nn.conv2d_transpose": ["NCHW", "default"],
"nn.conv3d": ["NCDHW", "default"],
}
),
transform.FoldConstant(),
LegalizeLayoutTranformPass(),
transform.InferType(),
]
)
with tvm.transform.PassContext(opt_level=3):
mod = seq(mod)
# Set SkipOptimization for all functions but main for the following passes
mod = _set_optimization_attr(mod, skip_optimization=1)
seq = tvm.transform.Sequential(
[
transform.AnnotateTarget("tensorrt"),
transform.MergeCompilerRegions(),
transform.PartitionGraph(),
transform.InferType(),
]
)
with tvm.transform.PassContext(opt_level=3):
mod = seq(mod)
mod = PruneSubgraphs(mod, use_implicit_batch=use_implicit_batch, prune_no_macs=prune_subgraphs)
# Set SkipOptimization back to 0
mod = _set_optimization_attr(mod, skip_optimization=0)
# Set environment variables used to communicate with TensorRT module.
os.environ["TVM_TENSORRT_MAX_WORKSPACE_SIZE"] = str(max_workspace_size)
os.environ["TVM_TENSORRT_USE_IMPLICIT_BATCH"] = str(int(use_implicit_batch))
return mod
|
# -*- coding: utf-8 -*-
from optparse import OptionParser
import sys,os,platform,time,traceback,getpass
from troubleshooting.framework.variable.variable import *
from troubleshooting.framework.modules.builder import BuilderFactory
from troubleshooting.framework.version.version import VERSION
from troubleshooting.framework.libraries.baseString import getRandomString
from troubleshooting.framework.modules.configuration import ConfigManagerInstance
from troubleshooting.framework.modules.manager import ManagerFactory
from troubleshooting.framework.output.welcome import welcome
from troubleshooting.framework.libraries.system import clean,auto_clean
from troubleshooting.framework.modules.thread import ThreadManager
from troubleshooting.framework.log.logger import logger
from troubleshooting.framework.httpserver.server import server
from troubleshooting.framework.output.browser import Browser
from troubleshooting.framework.remote.client import client
from troubleshooting.framework.libraries.filter import filterCaselist
from troubleshooting.framework.output.progressDialog import ProgressDialog
from troubleshooting.framework.output.report import report
from troubleshooting.framework.output.output import OutPut
from troubleshooting.framework.running.recovery import recovery
class BaseHandle(object):
def __init__(self):
super(BaseHandle,self).__init__()
self.successor = None
def handle(self):
if self.successor:
self.successor.handle()
class ParseArgsHandle(BaseHandle):
def __init__(self):
super(ParseArgsHandle,self).__init__()
def handle(self):
_system_ = platform.system().lower()
opt = OptionParser(version=VERSION)
opt.add_option("-l", "--list", dest="List", help="print list of cases", action="store_true")
opt.add_option("--clean", dest="Clean", help="remove all report directory", action="store_true")
opt.add_option("--readonly", dest="readonly", help="read only mode, can only fetch reports",
action="store_true")
opt.add_option("--host", dest="Host", help="host for remote connection")
opt.add_option("--port", dest="Port", help="port for remote connection ,defaut port is 22", default="22")
opt.add_option("--user", dest="User", help="user for remote connection , default user is root", default="root")
# opt.add_option("--password", dest="Password", help="password for remote connection , default password is arthur", default="root")
opt.add_option("--case", dest="case", help="select the case to run by case name")
opt.add_option("--include", dest="include", help="""select cases to run by tag, Tags can also be combined together with `AND` and `OR` .
Example: --include=coolANDhot""")
opt.add_option("--exclude", dest="exclude", help="""select cases not to run by tag. Tags can also be combined together with `AND` and `OR` .
Example: --include=coolORhot""")
opt.add_option("-r", "--recovery", dest="Recovery")
options, args = opt.parse_args()
reportHash = (getRandomString(5) + ".d")
reportFile = os.path.join(os.getcwd(), "www", reportHash, "report.html")
ConfigManagerInstance.config = {"Case": options.case}
ConfigManagerInstance.config = {"Report": reportFile}
ConfigManagerInstance.config = {"Include": options.include}
ConfigManagerInstance.config = {"Exclude": options.exclude}
ConfigManagerInstance.config = {"Host": options.Host}
ConfigManagerInstance.config = {"Port": options.Port}
ConfigManagerInstance.config = {"User": options.User}
ConfigManagerInstance.config = {"Password":""}
ConfigManagerInstance.config = {"SYSTEM": _system_}
ConfigManagerInstance.config = {"List": options.List}
ConfigManagerInstance.config = {"Clean": options.Clean}
ConfigManagerInstance.config = {"ReadOnly": options.readonly}
ConfigManagerInstance.config = {"Recovery": options.Recovery}
ConfigManagerInstance.config = {"__ReportHash__": reportHash}
ConfigManagerInstance.config = {"__ReportName__": "report.html"}
ConfigManagerInstance.config = {"__ProjectCWD__": os.getcwd()}
super(ParseArgsHandle,self).handle()
class AutoCleanEnvHandle(BaseHandle):
def __init__(self):
super(AutoCleanEnvHandle,self).__init__()
def handle(self):
auto_clean()
super(AutoCleanEnvHandle,self).handle()
class ListHandle(BaseHandle):
def __init__(self):
super(ListHandle,self).__init__()
def handle(self):
if ConfigManagerInstance.config["List"]:
CaseManagerInstance = ManagerFactory().getManager(LAYER.Case)
builderfactory = BuilderFactory()
builderfactory.getBuilder(LAYER.Case).builder()
caseNameList = CaseManagerInstance.get_keyword()
welcome().loadCasePrint(caseNameList)
welcome().ListCasePrint(caseNameList)
else:
super(ListHandle,self).handle()
class CleanHandle(BaseHandle):
def __init__(self):
super(CleanHandle,self).__init__()
def handle(self):
if ConfigManagerInstance.config["Clean"]:
clean()
else:
super(CleanHandle,self).handle()
class ReadOnlyHandle(BaseHandle):
def __init__(self):
super(ReadOnlyHandle,self).__init__()
def handle(self):
if ConfigManagerInstance.config["ReadOnly"]:
try:
cigServer = server(skip_deploy=True)
ThreadManager().start(cigServer)
print "init ReadOnly mode successfully."
linkage = "http://localhost:8888/www/cgi-bin/index.py"
if ConfigManagerInstance.config["SYSTEM"] == SYSTEM.WINDOWS.value:
Browser().openLocalReport(linkage)
else:
print "[Tips]:please visit the webpage %s" % linkage
except Exception, e:
print "Can not init ReadOnly mode."
logger().error(traceback.format_exc())
finally:
while 1:
time.sleep(0.1)
else:
super(ReadOnlyHandle,self).handle()
class TestConnectionForRemoteHandle(BaseHandle):
def __init__(self):
super(TestConnectionForRemoteHandle,self).__init__()
def handle(self):
if ConfigManagerInstance.config["Host"]:
# remote mode
host = ConfigManagerInstance.config["Host"]
port = ConfigManagerInstance.config["Port"]
user = ConfigManagerInstance.config["User"]
if user != "root":
print "WARN: Access right is not enough."
try:
port = int(port)
except:
raise Exception("port must be int type")
if not host:
raise Exception("host is mandatory")
if not port:
raise Exception("port is mandatory")
if not user:
raise Exception("user is mandatory")
while 1:
password = getpass.getpass("password: ")
if password:
break
ConfigManagerInstance.config["Password"] = password
if client().test_connection(host, port, user, password):
super(TestConnectionForRemoteHandle,self).handle()
else:
super(TestConnectionForRemoteHandle,self).handle()
class DoDetectHandle(BaseHandle):
def __init__(self):
super(DoDetectHandle,self).__init__()
def handle(self):
if ConfigManagerInstance.config["Recovery"] is None:
# detect mode
_startTime = time.time()
CaseManagerInstance = ManagerFactory().getManager(LAYER.Case)
builderfactory = BuilderFactory()
builderfactory.getBuilder(LAYER.KeyWords).builder()
builderfactory.getBuilder(LAYER.TestPoint).builder()
builderfactory.getBuilder(LAYER.Case).builder()
OutPutThreadno = ThreadManager().start(OutPut())
caseNameList = CaseManagerInstance.get_keyword()
caseNameList_NeedRun = filterCaselist(caseNameList)
caseNameListLength = len(caseNameList_NeedRun)
if ConfigManagerInstance.config["SYSTEM"] == SYSTEM.LINUX.value:
# local is linux
welcome().logo()
welcome().loadCasePrint(caseNameList_NeedRun)
Progress = ProgressDialog(caseNameListLength)
Progressthreadno = ThreadManager().start(Progress)
try:
for i, caseName in enumerate(caseNameList_NeedRun):
Progress.set(i)
behavior = CaseManagerInstance.run_case(caseName)
Progress.set(i + 1)
if behavior == BEHAVIOR.EXIT:
break
except Exception, e:
traceback.print_exc()
ThreadManager().stop(Progressthreadno)
else:
ThreadManager().join(Progressthreadno)
report().console()
report().writeReport()
finally:
ThreadManager().join(Progressthreadno)
ThreadManager().stop(OutPutThreadno)
elif ConfigManagerInstance.config["SYSTEM"] == SYSTEM.WINDOWS.value:
try:
welcome().logo()
welcome().loadCasePrint(caseNameList_NeedRun)
for caseName in caseNameList_NeedRun:
behavior = CaseManagerInstance.run_case(caseName)
if behavior == BEHAVIOR.EXIT:
break
report().writeReport()
except Exception, e:
traceback.print_exc()
finally:
ThreadManager().stop(OutPutThreadno)
else:
print "unsupport system %s" % ConfigManagerInstance.config["SYSTEM"]
_endTime = time.time()
print "Total cost time: %.3f s" % (_endTime - _startTime)
if ConfigManagerInstance.config["SYSTEM"] == SYSTEM.WINDOWS.value:
try:
ThreadManager().start(server())
reportHash = ConfigManagerInstance.config["__ReportHash__"]
Browser().openLocalReport("http://localhost:8888/www/cgi-bin/index.py?reportHash=%s" % reportHash)
except Exception, e:
print "Report save as %s" % ConfigManagerInstance.config["Report"]
logger().error(traceback.format_exc())
finally:
while 1:
time.sleep(0.1)
else:
print "Report save as %s" % ConfigManagerInstance.config["Report"]
class DoRecoveryHandle(BaseHandle):
def __init__(self):
super(DoRecoveryHandle,self).__init__()
def handle(self):
#recovery mode
if ConfigManagerInstance.config["Recovery"]:
recovery(ConfigManagerInstance.config["Recovery"])
else:
super(DoRecoveryHandle,self).handle()
class ArgsHandleClient(object):
def __init__(self):
super(ArgsHandleClient,self).__init__()
def handle(self):
h0 = ParseArgsHandle()
h0_5 = AutoCleanEnvHandle()
h1 = ListHandle()
h2 = CleanHandle()
h3 = ReadOnlyHandle()
h4 = TestConnectionForRemoteHandle()
h5 = DoDetectHandle()
h6 = DoRecoveryHandle()
h0.successor = h0_5
h0_5.successor = h1
h1.successor = h2
h2.successor = h3
h3.successor = h4
h4.successor = h5
h5.successor = h6
h0.handle()
|
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* 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.
*/
export const PINPOLL_CONFIG = /** @type {!JsonObject} */ ({
'requests': {
'pageview': '${protocol}://${host}/${version}?' +
'url=${sourceUrl}&' +
'sourceHost=${sourceHost}&' +
'sourceHostname=${sourceHostname}&' +
'sourcePath=${sourcePath}&' +
'canonicalUrl=${canonicalUrl}&' +
'platform=AMP&' +
'title=${title}&' +
'referrer=${documentReferrer}&' +
'screenHeight=${screenHeight}&' +
'screenWidth=${screenWidth}&' +
'screenColorDepth=${screenColorDepth}&' +
'ua=${userAgent}&' +
'clientId=${clientId(pinpoll)}',
},
'triggers': {
'pageview': {
'on': 'visible',
'request': 'pageview',
},
},
'vars': {
'version': 'v1',
'protocol': 'https',
'host': 'pa.pinpoll.com',
},
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _defineProperty2 = require('babel-runtime/helpers/defineProperty');
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _classnames2 = require('classnames');
var _classnames3 = _interopRequireDefault(_classnames2);
var _FormattedMessage = require('../../../components/FormattedMessage');
var _FormattedMessage2 = _interopRequireDefault(_FormattedMessage);
var _CSSClassnames = require('../../../utils/CSSClassnames');
var _CSSClassnames2 = _interopRequireDefault(_CSSClassnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
var CLASS_ROOT = _CSSClassnames2.default.CONTROL_ICON;
var COLOR_INDEX = _CSSClassnames2.default.COLOR_INDEX;
var Icon = function (_Component) {
(0, _inherits3.default)(Icon, _Component);
function Icon() {
(0, _classCallCheck3.default)(this, Icon);
return (0, _possibleConstructorReturn3.default)(this, (Icon.__proto__ || (0, _getPrototypeOf2.default)(Icon)).apply(this, arguments));
}
(0, _createClass3.default)(Icon, [{
key: 'render',
value: function render() {
var _classnames;
var _props = this.props;
var a11yTitleId = _props.a11yTitleId;
var className = _props.className;
var colorIndex = _props.colorIndex;
var _props2 = this.props;
var a11yTitle = _props2.a11yTitle;
var size = _props2.size;
var classes = (0, _classnames3.default)(CLASS_ROOT, CLASS_ROOT + '-payment-mastercard', className, (_classnames = {}, (0, _defineProperty3.default)(_classnames, CLASS_ROOT + '--' + size, size), (0, _defineProperty3.default)(_classnames, COLOR_INDEX + '-' + colorIndex, colorIndex), _classnames));
a11yTitle = a11yTitle || _react2.default.createElement(_FormattedMessage2.default, { id: 'payment-mastercard', defaultMessage: 'payment-mastercard' });
return _react2.default.createElement(
'svg',
{ version: '1.1', viewBox: '0 0 24 24', width: '24px', height: '24px', role: 'img', className: classes, 'aria-labelledby': a11yTitleId },
_react2.default.createElement(
'title',
{ id: a11yTitleId },
a11yTitle
),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('rect', { x: '0', y: '0', fill: 'none', width: '24', height: '24' }),
_react2.default.createElement(
'g',
null,
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'M16.8179,5.6966c3.4079,0,6.1812,2.7728,6.1821,6.1848c0.0005,1.6514-0.6422,3.2042-1.8096,4.3722\r c-1.1674,1.168-2.7199,1.8115-4.3729,1.8119c-3.4082,0-6.1817-2.7728-6.1826-6.1846c-0.0005-1.6514,0.6422-3.2042,1.8097-4.3722\r c1.1674-1.1681,2.7198-1.8116,4.371-1.812H16.8179 M16.8174,4.6966c-0.0005,0-0.0014,0-0.0019,0\r c-3.9667,0.001-7.1817,3.2177-7.1807,7.1844c0,0.0013,0,0.0024,0,0.0037c0.0011,3.9664,3.2163,7.1807,7.1826,7.1807\r c0.0005,0,0.0013,0,0.0018,0c3.9669-0.001,7.1819-3.2175,7.1808-7.1844c0-0.0013,0-0.0024,0-0.0037\r C23.9989,7.9111,20.7838,4.6964,16.8174,4.6966L16.8174,4.6966z' })
)
),
_react2.default.createElement('path', { d: 'M14.2193,13.3257H9.7496c-0.0481-0.2432-0.0838-0.4864-0.1069-0.7296h4.6857c0.0233-0.2354,0.0367-0.4736,0.0367-0.7151\r c0-0.0319-0.0009-0.0637-0.0013-0.0955H9.6127c0.0024-0.2432,0.0176-0.4864,0.0449-0.7296h4.66\r c-0.0277-0.2415-0.067-0.4864-0.118-0.7296H9.809C9.8634,10.0832,9.932,9.84,10.0139,9.5968h3.9772\r c-0.0889-0.2432-0.1922-0.5674-0.3097-0.8106h-3.3619c0.1213-0.2432,0.2587-0.4864,0.4121-0.7296h2.5361\r c-0.1688-0.2432-0.3555-0.4864-0.5575-0.7296h-1.414c0.2186-0.3243,0.4593-0.498,0.7206-0.7239\r C10.7405,5.4407,9.0438,4.733,7.1826,4.733c-0.0155,0-0.0308,0-0.0463,0C3.1929,4.733,0,7.949,0,11.8984\r c0,3.9647,3.2178,7.1739,7.1826,7.1739c1.8608,0,3.557-0.701,4.8333-1.8633c0,0-0.0002,0.0078-0.0006,0.0078h0.0015\r c0.2613-0.2432,0.5051-0.4864,0.7292-0.8106h-1.4715c-0.1965-0.2432-0.3751-0.4864-0.5355-0.7296h2.5379\r c0.1543-0.2432,0.2941-0.4864,0.4181-0.7296H10.32c-0.115-0.2432-0.2149-0.5674-0.3002-0.8106h3.9757\r C14.0863,13.8932,14.1611,13.6099,14.2193,13.3257z' })
)
);
}
}]);
return Icon;
}(_react.Component);
Icon.displayName = 'Icon';
exports.default = Icon;
;
Icon.propTypes = {
a11yTitle: _react.PropTypes.string,
a11yTitleId: _react.PropTypes.string,
colorIndex: _react.PropTypes.string,
size: _react.PropTypes.oneOf(['small', 'medium', 'large', 'xlarge', 'huge'])
};
Icon.defaultProps = {
a11yTitleId: 'payment-mastercard-title'
};
Icon.icon = true;
Icon.displayName = 'PaymentMastercard';
module.exports = exports['default'];
|
// send data to the endpoint
var push = (function(){
// look for the shaker.js script, and use it to
// generate an endpoint
var endpoint = (function(){
var scripts = document.scripts;
for(var i = 0; i < scripts.length; i++){
var src = scripts[i].src;
var match = src.match(/(.*)shaker\.js\?(.*)/);
// console.log(src, match);
if(match){
return match.slice(1).join('') + '/push.png';
}
}
}()),
data = [],
timer;
return function(d){
data.push(d);
debounceFlush();
}
function debounceFlush(){
if(timer){
clearTimeout(timer)
}
timer = setTimeout(flush, 10);
}
// send the data to the endpoint
function flush(){
// consume and roll items into a json object
// (this should be the first thing to be rewritten)
var obj = {}, robj, i, j;
while(i = data.shift()){
robj = obj;
while(j = i.shift()){
robj[j] = robj[j] || {};
if(i.length == 1){
robj[j] = i.shift();
}
robj = robj[j];
}
}
if(endpoint){
var jstr = JSON.stringify(obj);
(new Image).src = endpoint + '?d=' + encodeURIComponent(jstr);
} else {
console.log(">>", JSON.stringify(obj));
}
}
})();
// spy on an objects function, when called call back,
// through and replace with original
function Spy(obj,fn,cb){
var original = obj[fn];
obj[fn] = function(){
cb();
obj[fn] = original;
return original.apply(this,arguments);
}
}
function Feature(successArgs){
this.successArgs = successArgs;
this.resolved = false;
};
Feature.prototype.resolve = function(){
this.resolved = true;
if(this.successArgs){
push(this.successArgs);
this.successArgs = null;
}
}
Feature.prototype.spy = function(obj, fns){
var f = this,
fns = fns.split(' ');
for(var i = fns.length; i; i--){
new Spy(obj,fns[i-1],function(){
f.resolve();
});
}
};
function library(name, version, hooks){
// make version default to '_'
if(!hooks){
hooks = version;
version = '_';
}
if(hooks._check()){
/*
key:
0 - failed
1 - unused
2 - used
*/
for(var h in hooks){
if(hooks.hasOwnProperty(h) && h.charAt(0) != '_'){
var state = 1;
// try{
hooks[h](new Feature([name,version,h,2]));
// } catch(e){
// console.error(e);
// state = 0;
// }
push([name,version,h,state]);
}
}
}
};
|
const lib = require ('../@sap/cds-services')
const Service = require ('./Service')
module.exports = class ServiceClient extends Service .and (lib.Client) {
static new (name, model, o) {
const primary = o && o.primary || name === 'db'
const srv = lib.connect.connect (name, o, primary)
return Object.setPrototypeOf (srv, this.prototype)
}
// we should get rid of that:
disconnect(...args) {
const {cds} = global
if (this.name) delete cds.services [this.name]
if (this === cds.db) cds.db = undefined
{ // REVISIT: pretty ugly that we have to keep that in mind to call the ugly's disconnect instead!
const ugly = lib.connect
if (!this._been_here && ugly.hasSession() && ugly.connect(0,0,true) === this) {
return this._been_here=1, ugly.disconnect(...args)
}
}
return super.disconnect(...args)
}
// interims workarounds
on(){} before(){} after(){} emit(){}
}
|
from __future__ import division
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.decomposition import PCA
from sklearn.metrics import roc_auc_score, roc_curve
from keras.models import Sequential, model_from_json, load_model
from keras.layers import Dense, Activation
from keras.optimizers import Adam
from keras.models import Sequential
from six.moves import cPickle as pickle
import timeit
import types
import numpy as np
import pandas
from rep.estimators import XGBoostClassifier
from xgboost import XGBClassifier
from ML_Tools.General.PreProc import *
from ML_Tools.General.Ensemble_Functions import *
from ML_Tools.Plotting_And_Evaluation.Bootstrap import mpRun
from ML_Tools.General.Training import *
from ML_Tools.General.Batch_Train import *
from Class_Features import *
def getClassifier(version=None, nIn=None, compileArgs=None, nOut=1):
model = Sequential()
depth = None
width = None
if version == "modelRelu":
depth = 3
width = 100
model.add(Dense(width, input_dim=nIn, kernel_initializer='he_normal'))
model.add(Activation('relu'))
for i in range(depth):
model.add(Dense(width, kernel_initializer='he_normal'))
model.add(Activation('relu'))
elif version == "modelSelu":
depth = 3
width = 100
model.add(Dense(width, input_dim=nIn, kernel_initializer='VarianceScaling'))
model.add(Activation('selu'))
for i in range(depth):
model.add(Dense(width, kernel_initializer='VarianceScaling'))
model.add(Activation('selu'))
elif version == "modelSwish":
depth = 3
width = 100
model.add(Dense(width, input_dim=nIn, kernel_initializer='he_normal'))
model.add(Activation('swish'))
for i in range(depth):
model.add(Dense(width, kernel_initializer='he_normal'))
model.add(Activation('swish'))
if nOut == 1:
model.add(Dense(1, activation='sigmoid', kernel_initializer='glorot_normal'))
else:
model.add(Dense(nOut, activation='softmax', kernel_initializer='glorot_normal'))
if 'lr' not in compileArgs: compileArgs['lr'] = 0.001
if compileArgs['optimizer'] == 'adam':
optimiser = Adam(lr=compileArgs['lr'], beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
model.compile(loss=compileArgs['loss'], optimizer=optimiser)
return model
|
import { validateAndFix } from "../src/svgo";
import test from "tape";
test("fills essential plugins and default plugins when empty", function(t) {
let opts = {};
opts = validateAndFix(opts);
t.equal(opts.plugins.length, 4);
t.end();
});
test("enable disabled essential plugins", function(t) {
let opts = {
full: true,
plugins: ["removeDoctype", { removeComments: false }]
};
opts = validateAndFix(opts);
t.equal(opts.plugins.length, 4);
t.equal(opts.plugins[1].removeComments, true);
t.end();
});
test("default plugins are set by default", t => {
let opts = {};
opts = validateAndFix(opts);
t.assert(
opts.plugins.find(
p =>
Object.prototype.hasOwnProperty.call(p, "removeViewBox") &&
p.removeViewBox === false
)
);
t.end();
});
|
/*global defineSuite*/
defineSuite([
'DataSources/GeoJsonDataSource',
'Core/Cartesian3',
'Core/Color',
'Core/Event',
'Core/JulianDate',
'Core/PolygonHierarchy',
'Core/RuntimeError',
'DataSources/CallbackProperty',
'DataSources/EntityCollection',
'ThirdParty/when'
], function(
GeoJsonDataSource,
Cartesian3,
Color,
Event,
JulianDate,
PolygonHierarchy,
RuntimeError,
CallbackProperty,
EntityCollection,
when) {
'use strict';
var defaultMarkerSize;
var defaultSymbol;
var defaultMarkerColor;
var defaultStroke;
var defaultStrokeWidth;
var defaultFill;
beforeAll(function() {
defaultMarkerSize = GeoJsonDataSource.markerSize;
defaultSymbol = GeoJsonDataSource.markerSymbol;
defaultMarkerColor = GeoJsonDataSource.markerColor;
defaultStroke = GeoJsonDataSource.stroke;
defaultStrokeWidth = GeoJsonDataSource.strokeWidth;
defaultFill = GeoJsonDataSource.fill;
});
beforeEach(function() {
GeoJsonDataSource.markerSize = defaultMarkerSize;
GeoJsonDataSource.markerSymbol = defaultSymbol;
GeoJsonDataSource.markerColor = defaultMarkerColor;
GeoJsonDataSource.stroke = defaultStroke;
GeoJsonDataSource.strokeWidth = defaultStrokeWidth;
GeoJsonDataSource.fill = defaultFill;
});
var time = new JulianDate();
function coordinatesToCartesian(coordinates) {
return Cartesian3.fromDegrees(coordinates[0], coordinates[1], coordinates[2]);
}
function coordinatesArrayToCartesian(coordinates) {
var result = [];
for (var i = 0; i < coordinates.length; i++) {
result.push(coordinatesToCartesian(coordinates[i]));
}
return result;
}
function multiLineToCartesian(geometry) {
var coordinates = geometry.coordinates;
var result = [];
for (var i = 0; i < coordinates.length; i++) {
result.push(coordinatesArrayToCartesian(coordinates[i]));
}
return result;
}
function polygonCoordinatesToCartesian(coordinates) {
return coordinatesArrayToCartesian(coordinates);
}
function multiPolygonCoordinatesToCartesian(coordinates) {
var result = [];
for (var i = 0; i < coordinates.length; i++) {
result.push(coordinatesArrayToCartesian(coordinates[i][0]));
}
return result;
}
var point = {
type : 'Point',
coordinates : [102.0, 0.5]
};
var pointNamedCrs = {
type : 'Point',
coordinates : [102.0, 0.5],
crs : {
type : 'name',
properties : {
name : 'EPSG:4326'
}
}
};
var pointCrsLinkHref = {
type : 'Point',
coordinates : [102.0, 0.5],
crs : {
type : 'link',
properties : {
href : 'http://crs.invalid'
}
}
};
var pointCrsEpsg = {
type : 'Point',
coordinates : [102.0, 0.5],
crs : {
type : 'EPSG',
properties : {
code : 4326
}
}
};
var lineString = {
type : 'LineString',
coordinates : [[100.0, 0.0], [101.0, 1.0]]
};
var polygon = {
type : 'Polygon',
coordinates : [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]]
};
var polygonWithHoles = {
type : 'Polygon',
coordinates : [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]]
};
var polygonWithHeights = {
type : 'Polygon',
coordinates : [[[100.0, 0.0, 1.0], [101.0, 0.0, 2.0], [101.0, 1.0, 1.0], [100.0, 1.0, 2.0], [100.0, 0.0, 3.0]]]
};
var multiPoint = {
type : 'MultiPoint',
coordinates : [[100.0, 0.0], [101.0, 1.0], [101.0, 3.0]]
};
var multiLineString = {
type : 'MultiLineString',
coordinates : [[[100.0, 0.0], [101.0, 1.0]], [[102.0, 2.0], [103.0, 3.0]]]
};
var multiPolygon = {
type : 'MultiPolygon',
coordinates : [[[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]]]
};
var geometryCollection = {
type : 'GeometryCollection',
geometries : [{
type : 'Point',
coordinates : [100.0, 0.0]
}, {
type : 'LineString',
coordinates : [[101.0, 0.0], [102.0, 1.0]]
}]
};
var feature = {
type : 'Feature',
geometry : point
};
var featureWithNullName = {
type : 'Feature',
geometry : point,
properties : {
name : null
}
};
var featureWithId = {
id : 'myId',
type : 'Feature',
geometry : geometryCollection
};
var featureUndefinedGeometry = {
type : 'Feature'
};
var featureNullGeometry = {
type : 'Feature',
geometry : null
};
var unknownGeometry = {
type : 'TimeyWimey',
coordinates : [0, 0]
};
var featureUnknownGeometry = {
type : 'Feature',
geometry : unknownGeometry
};
var geometryCollectionUnknownType = {
type : 'GeometryCollection',
geometries : [unknownGeometry]
};
var topoJson = {
type : 'Topology',
transform : {
scale : [1, 1],
translate : [0, 0]
},
objects : {
polygon : {
type : 'Polygon',
arcs : [[0, 1, 2, 3]],
properties : {
myProps : 0
}
},
lineString : {
type : 'LineString',
arcs : [4],
properties : {
myProps : 1
}
}
},
arcs : [[[0, 0], [1, 0], [0, 1], [-1, 0], [0, -1]], [[0, 0], [1, 0], [0, 1]], [[1, 1], [-1, 0], [0, -1]], [[1, 1]], [[0, 0]]]
};
var mixedGeometries = {
type : 'GeometryCollection',
geometries : [lineString, polygon, point]
};
it('default constructor has expected values', function() {
var dataSource = new GeoJsonDataSource();
expect(dataSource.changedEvent).toBeInstanceOf(Event);
expect(dataSource.errorEvent).toBeInstanceOf(Event);
expect(dataSource.clock).toBeUndefined();
expect(dataSource.name).toBeUndefined();
expect(dataSource.entities).toBeInstanceOf(EntityCollection);
expect(dataSource.entities.values.length).toEqual(0);
expect(dataSource.show).toBe(true);
});
it('show sets underlying entity collection show.', function() {
var dataSource = new GeoJsonDataSource();
dataSource.show = false;
expect(dataSource.show).toBe(false);
expect(dataSource.show).toEqual(dataSource.entities.show);
dataSource.show = true;
expect(dataSource.show).toBe(true);
expect(dataSource.show).toEqual(dataSource.entities.show);
});
it('Works with null geometry', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(featureNullGeometry).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.properties).toBe(featureNullGeometry.properties);
expect(entity.position).toBeUndefined();
});
});
it('Works with feature', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(feature).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.properties).toBe(feature.properties);
expect(entity.position.getValue(time)).toEqual(coordinatesToCartesian(feature.geometry.coordinates));
expect(entity.billboard).toBeDefined();
});
});
it('Creates default description from properties', function() {
var featureWithProperties = {
type : 'Feature',
geometry : point,
properties : {
prop1 : 'dog',
prop2 : 'cat',
prop3 : 'liger'
}
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(featureWithProperties).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.description).toBeDefined();
var description = entity.description.getValue(time);
expect(description).toContain('prop1');
expect(description).toContain('prop2');
expect(description).toContain('prop3');
expect(description).toContain('dog');
expect(description).toContain('cat');
expect(description).toContain('liger');
});
});
it('Creates custom description string from properties', function() {
var featureWithProperties = {
type : 'Feature',
geometry : point,
properties : {
prop1 : 'dog',
prop2 : 'cat'
}
};
function testDescribe(properties) {
var desc = '';
for (var key in properties) {
if (properties.hasOwnProperty(key)) {
var value = properties[key];
desc += key + ' = ' + value + '. ';
}
}
return desc;
}
var dataSource = new GeoJsonDataSource();
var options = {
describe: testDescribe
};
return dataSource.load(featureWithProperties, options).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.description).toBeDefined();
var description = entity.description.getValue(time);
expect(description).toContain('prop1 = dog.');
expect(description).toContain('prop2 = cat.');
});
});
it('Creates custom description from properties, using a describeProperty', function() {
var featureWithProperties = {
type : 'Feature',
geometry : point,
properties : {
prop1 : 'dog',
prop2 : 'cat'
}
};
function testDescribe(properties) {
var desc = '';
for (var key in properties) {
if (properties.hasOwnProperty(key)) {
var value = properties[key];
desc += key + ' = ' + value + '; ';
}
}
return desc;
}
function createDescriptionCallback(describe, properties, nameProperty) {
var description;
return function(time, result) {
if (!description) {
description = describe(properties, nameProperty);
}
return description;
};
}
function testDescribeProperty(properties, nameProperty) {
return new CallbackProperty(createDescriptionCallback(testDescribe, properties, nameProperty), true);
}
var dataSource = new GeoJsonDataSource();
var options = {
describe: testDescribeProperty
};
return dataSource.load(featureWithProperties, options).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.description).toBeDefined();
var description = entity.description.getValue(time);
expect(description).toContain('prop1 = dog;');
expect(description).toContain('prop2 = cat;');
});
});
it('Uses description if present', function() {
var featureWithDescription = {
type : 'Feature',
geometry : point,
properties : {
prop1 : 'dog',
prop2 : 'cat',
prop3 : 'liger',
description : 'This is my descriptiong!'
}
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(featureWithDescription).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.description).toBeDefined();
expect(entity.description.getValue(time)).toEqual(featureWithDescription.properties.description);
});
});
it('Handles null description', function() {
var featureWithNullDescription = {
type : 'Feature',
geometry : point,
properties : {
description : null
}
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(featureWithNullDescription).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.description).toBeUndefined();
});
});
it('Does not use "name" property as the object\'s name if it is null', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(featureWithNullName).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.name).toBeUndefined();
expect(entity.properties).toBe(featureWithNullName.properties);
expect(entity.position.getValue(time)).toEqual(coordinatesToCartesian(featureWithNullName.geometry.coordinates));
expect(entity.billboard).toBeDefined();
});
});
it('Works with feature with id', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(featureWithId).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.id).toEqual(featureWithId.id);
entity = entityCollection.values[1];
expect(entity.id).toEqual(featureWithId.id + '_2');
});
});
it('Works with null id', function() {
var geojson = {
id : null,
type : 'Feature',
geometry : null
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(geojson).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.id).not.toEqual(null);
});
});
it('Works with null properties', function() {
var geojson = {
type : 'Feature',
geometry : null,
properties : null
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(geojson).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.properties).toBeUndefined();
});
});
it('Has entity collection with link to data source', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(featureWithId).then(function() {
var entityCollection = dataSource.entities;
expect(entityCollection.owner).toEqual(dataSource);
});
});
it('Has entity with link to entity collection', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(featureWithId).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.entityCollection).toEqual(entityCollection);
});
});
it('Works with point geometry', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(point).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.properties).toBe(point.properties);
expect(entity.position.getValue(time)).toEqual(coordinatesToCartesian(point.coordinates));
expect(entity.billboard).toBeDefined();
expect(entity.billboard.image).toBeDefined();
});
});
it('Works with point geometry with simplystyle', function() {
var geojson = {
type : 'Point',
coordinates : [102.0, 0.5],
properties : {
'marker-size' : 'large',
'marker-symbol' : 'bus',
'marker-color' : '#ffffff'
}
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(geojson).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.billboard).toBeDefined();
return when(dataSource._pinBuilder.fromMakiIconId('bus', Color.WHITE, 64)).then(function(image) {
expect(entity.billboard.image.getValue()).toBe(image);
});
});
});
it('Works with point geometry with null simplystyle', function() {
var geojson = {
type : 'Point',
coordinates : [102.0, 0.5],
properties : {
'marker-size' : null,
'marker-symbol' : null,
'marker-color' : null
}
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(geojson).then(function() {
var image = dataSource._pinBuilder.fromColor(GeoJsonDataSource.markerColor, GeoJsonDataSource.markerSize);
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.billboard).toBeDefined();
expect(entity.billboard.image.getValue()).toBe(image);
});
});
it('Works with multipoint geometry', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(multiPoint).then(function() {
var entityCollection = dataSource.entities;
var entities = entityCollection.values;
var expectedPositions = coordinatesArrayToCartesian(multiPoint.coordinates);
for (var i = 0; i < multiPoint.coordinates.length; i++) {
var entity = entities[i];
expect(entity.properties).toBe(multiPoint.properties);
expect(entity.position.getValue(time)).toEqual(expectedPositions[i]);
expect(entity.billboard).toBeDefined();
expect(entity.billboard.image).toBeDefined();
}
});
});
it('Works with lineString geometry', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(lineString).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.properties).toBe(lineString.properties);
expect(entity.polyline.positions.getValue(time)).toEqual(coordinatesArrayToCartesian(lineString.coordinates));
expect(entity.polyline.material.color.getValue(time)).toEqual(GeoJsonDataSource.stroke);
expect(entity.polyline.width.getValue(time)).toEqual(2);
});
});
it('Works with multiLineString geometry', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(multiLineString).then(function() {
var entityCollection = dataSource.entities;
var entities = entityCollection.values;
var lines = multiLineToCartesian(multiLineString);
for (var i = 0; i < multiLineString.coordinates.length; i++) {
var entity = entities[i];
expect(entity.properties).toBe(multiLineString.properties);
expect(entity.polyline.positions.getValue(time)).toEqual(lines[i]);
expect(entity.polyline.material.color.getValue(time)).toEqual(Color.YELLOW);
expect(entity.polyline.width.getValue(time)).toEqual(2);
}
});
});
it('Works with polygon geometry', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(polygon).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.properties).toBe(polygon.properties);
expect(entity.polygon.hierarchy.getValue(time)).toEqual(new PolygonHierarchy(polygonCoordinatesToCartesian(polygon.coordinates[0])));
expect(entity.polygon.perPositionHeight).toBeUndefined();
expect(entity.polygon.material.color.getValue(time)).toEqual(GeoJsonDataSource.fill);
expect(entity.polygon.outline.getValue(time)).toEqual(true);
expect(entity.polygon.outlineWidth.getValue(time)).toEqual(GeoJsonDataSource.strokeWidth);
expect(entity.polygon.outlineColor.getValue(time)).toEqual(GeoJsonDataSource.stroke);
});
});
it('Works with polygon geometry with Heights', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(polygonWithHeights).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.properties).toBe(polygonWithHeights.properties);
expect(entity.polygon.hierarchy.getValue(time)).toEqual(new PolygonHierarchy(polygonCoordinatesToCartesian(polygonWithHeights.coordinates[0])));
expect(entity.polygon.perPositionHeight.getValue(time)).toBe(true);
expect(entity.polygon.material.color.getValue(time)).toEqual(GeoJsonDataSource.fill);
expect(entity.polygon.outline.getValue(time)).toEqual(true);
expect(entity.polygon.outlineWidth.getValue(time)).toEqual(GeoJsonDataSource.strokeWidth);
expect(entity.polygon.outlineColor.getValue(time)).toEqual(GeoJsonDataSource.stroke);
});
});
it('Works with polygon geometry with holes', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(polygonWithHoles).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.properties).toBe(polygonWithHoles.properties);
expect(entity.polygon.hierarchy.getValue(time)).toEqual(new PolygonHierarchy(polygonCoordinatesToCartesian(polygonWithHoles.coordinates[0]), [new PolygonHierarchy(polygonCoordinatesToCartesian(polygonWithHoles.coordinates[1]))]));
});
});
it('Works with multiPolygon geometry', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(multiPolygon).then(function() {
var entityCollection = dataSource.entities;
var entities = entityCollection.values;
var positions = multiPolygonCoordinatesToCartesian(multiPolygon.coordinates);
for (var i = 0; i < multiPolygon.coordinates.length; i++) {
var entity = entities[i];
expect(entity.properties).toBe(multiPolygon.properties);
expect(entity.polygon.hierarchy.getValue(time)).toEqual(new PolygonHierarchy(positions[i]));
}
});
});
it('Works with topojson geometry', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(topoJson).then(function() {
var entityCollection = dataSource.entities;
var entities = entityCollection.values;
var polygon = entities[0];
expect(polygon.properties).toBe(topoJson.objects.polygon.properties);
expect(polygon.polygon.hierarchy).toBeDefined();
var lineString = entities[1];
expect(lineString.properties).toBe(topoJson.objects.lineString.properties);
expect(lineString.polyline).toBeDefined();
});
});
it('Can provide base styling options', function() {
var options = {
markerSize : 10,
markerSymbol : 'bus',
markerColor : Color.GREEN,
stroke : Color.ORANGE,
strokeWidth : 8,
fill : Color.RED
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(mixedGeometries, options).then(function() {
var entityCollection = dataSource.entities;
var entities = entityCollection.values;
var entity = entities[0];
expect(entity.polyline.material.color.getValue()).toEqual(options.stroke);
expect(entity.polyline.width.getValue()).toEqual(options.strokeWidth);
entity = entities[1];
expect(entity.polygon.material.color.getValue()).toEqual(options.fill);
expect(entity.polygon.outlineColor.getValue()).toEqual(options.stroke);
expect(entity.polygon.outlineWidth.getValue()).toEqual(options.strokeWidth);
entity = entities[2];
var expectedImage = dataSource._pinBuilder.fromMakiIconId(options.markerSymbol, options.markerColor, options.markerSize);
expect(entity.billboard.image.getValue()).toEqual(expectedImage);
});
});
it('Can set default graphics', function() {
GeoJsonDataSource.markerSize = 10;
GeoJsonDataSource.markerSymbol = 'bus';
GeoJsonDataSource.markerColor = Color.GREEN;
GeoJsonDataSource.stroke = Color.ORANGE;
GeoJsonDataSource.strokeWidth = 8;
GeoJsonDataSource.fill = Color.RED;
var dataSource = new GeoJsonDataSource();
return dataSource.load(mixedGeometries).then(function() {
var entityCollection = dataSource.entities;
var entities = entityCollection.values;
var entity = entities[0];
expect(entity.polyline.material.color.getValue()).toEqual(GeoJsonDataSource.stroke);
expect(entity.polyline.width.getValue()).toEqual(GeoJsonDataSource.strokeWidth);
entity = entities[1];
expect(entity.polygon.material.color.getValue()).toEqual(GeoJsonDataSource.fill);
expect(entity.polygon.outlineColor.getValue()).toEqual(GeoJsonDataSource.stroke);
expect(entity.polygon.outlineWidth.getValue()).toEqual(GeoJsonDataSource.strokeWidth);
entity = entities[2];
var expectedImage = dataSource._pinBuilder.fromMakiIconId(GeoJsonDataSource.markerSymbol, GeoJsonDataSource.markerColor, GeoJsonDataSource.markerSize);
expect(entity.billboard.image.getValue()).toEqual(expectedImage);
});
});
it('Generates description', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(topoJson).then(function() {
var entityCollection = dataSource.entities;
var entities = entityCollection.values;
var polygon = entities[0];
expect(polygon.description).toBeDefined();
});
});
it('Works with geometrycollection', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(geometryCollection).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.properties).toBe(geometryCollection.properties);
expect(entity.position.getValue(time)).toEqual(coordinatesToCartesian(geometryCollection.geometries[0].coordinates));
expect(entity.billboard).toBeDefined();
entity = entityCollection.values[1];
expect(entity.properties).toBe(geometryCollection.properties);
expect(entity.polyline.positions.getValue(time)).toEqual(coordinatesArrayToCartesian(geometryCollection.geometries[1].coordinates));
});
});
it('Works with named crs', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(pointNamedCrs).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.position.getValue(time)).toEqual(coordinatesToCartesian(point.coordinates));
});
});
it('Works with link crs href', function() {
var projectedPosition = new Cartesian3(1, 2, 3);
GeoJsonDataSource.crsLinkHrefs[pointCrsLinkHref.crs.properties.href] = function(properties) {
expect(properties).toBe(pointCrsLinkHref.crs.properties);
return when(properties.href).then(function(href) {
return function(coordinate) {
expect(coordinate).toBe(pointCrsLinkHref.coordinates);
return projectedPosition;
};
});
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(pointCrsLinkHref).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.position.getValue(time)).toEqual(projectedPosition);
});
});
it('Works with EPSG crs', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(pointCrsEpsg).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.position.getValue(time)).toEqual(coordinatesToCartesian(point.coordinates));
});
});
it('Works with polyline using simplestyle', function() {
var geoJson = {
type : 'Feature',
geometry : {
type : 'LineString',
coordinates : [[100.0, 0.0], [101.0, 1.0]]
},
properties : {
title : 'textMarker',
description : 'My description',
stroke : '#aabbcc',
'stroke-opacity' : 0.5,
'stroke-width' : 5
}
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(geoJson).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.name).toEqual(geoJson.properties.title);
expect(entity.description.getValue(time)).toEqual(geoJson.properties.description);
var expectedColor = Color.fromCssColorString(geoJson.properties.stroke);
expectedColor.alpha = geoJson.properties['stroke-opacity'];
expect(entity.polyline.material.color.getValue(time)).toEqual(expectedColor);
expect(entity.polyline.width.getValue(time)).toEqual(geoJson.properties['stroke-width']);
});
});
it('Works with polyline using null simplestyle values', function() {
var geoJson = {
type : 'Feature',
geometry : {
type : 'LineString',
coordinates : [[100.0, 0.0], [101.0, 1.0]]
},
properties : {
title : null,
description : null,
stroke : null,
'stroke-opacity' : null,
'stroke-width' : null
}
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(geoJson).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.name).toBeUndefined();
expect(entity.description).toBeUndefined();
expect(entity.polyline.material.color.getValue(time)).toEqual(GeoJsonDataSource.stroke);
expect(entity.polyline.width.getValue(time)).toEqual(GeoJsonDataSource.strokeWidth);
});
});
it('Works with polygon using simplestyle', function() {
var geoJson = {
type : 'Feature',
geometry : {
type : 'Polygon',
coordinates : [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]]
},
properties : {
title : 'textMarker',
description : 'My description',
stroke : '#aabbcc',
'stroke-opacity' : 0.5,
'stroke-width' : 5,
fill : '#ccaabb',
'fill-opacity' : 0.25
}
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(geoJson).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.name).toEqual(geoJson.properties.title);
expect(entity.description.getValue(time)).toEqual(geoJson.properties.description);
var expectedFill = Color.fromCssColorString(geoJson.properties.fill);
expectedFill.alpha = geoJson.properties['fill-opacity'];
var expectedOutlineColor = Color.fromCssColorString(geoJson.properties.stroke);
expectedOutlineColor.alpha = geoJson.properties['stroke-opacity'];
expect(entity.polygon.material.color.getValue(time)).toEqual(expectedFill);
expect(entity.polygon.outline.getValue(time)).toEqual(true);
expect(entity.polygon.outlineWidth.getValue(time)).toEqual(5);
expect(entity.polygon.outlineColor.getValue(time)).toEqual(expectedOutlineColor);
});
});
it('Works with polygon using null simplestyle', function() {
var geoJson = {
type : 'Feature',
geometry : {
type : 'Polygon',
coordinates : [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]]
},
properties : {
title : null,
description : null,
stroke : null,
'stroke-opacity' : null,
'stroke-width' : null,
fill : null,
'fill-opacity' : null
}
};
var dataSource = new GeoJsonDataSource();
return dataSource.load(geoJson).then(function() {
var entityCollection = dataSource.entities;
var entity = entityCollection.values[0];
expect(entity.name).toBeUndefined();
expect(entity.description).toBeUndefined();
expect(entity.polygon.material.color.getValue(time)).toEqual(GeoJsonDataSource.fill);
expect(entity.polygon.outline.getValue(time)).toEqual(true);
expect(entity.polygon.outlineWidth.getValue(time)).toEqual(GeoJsonDataSource.strokeWidth);
expect(entity.polygon.outlineColor.getValue(time)).toEqual(GeoJsonDataSource.stroke);
});
});
it('load works with a URL', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load('Data/test.geojson').then(function() {
expect(dataSource.name).toEqual('test.geojson');
});
});
it('Fails when encountering unknown geometry', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(featureUnknownGeometry).then(function() {
fail('should not be called');
}).otherwise(function() {
});
});
it('Fails with undefined geomeetry', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(featureUndefinedGeometry).then(function() {
fail('should not be called');
}).otherwise(function() {
});
});
it('Fails with unknown geomeetry in geometryCollection', function() {
var dataSource = new GeoJsonDataSource();
return dataSource.load(geometryCollectionUnknownType).then(function() {
fail('should not be called');
}).otherwise(function() {
});
});
it('load throws with undefined geoJson', function() {
var dataSource = new GeoJsonDataSource();
expect(function() {
dataSource.load(undefined);
}).toThrowDeveloperError();
});
it('rejects unknown geometry', function() {
return GeoJsonDataSource.load(unknownGeometry).then(function() {
fail('should not be called');
}).otherwise(function(error) {
expect(error).toBeInstanceOf(RuntimeError);
expect(error.message).toContain('Unsupported GeoJSON object type: TimeyWimey');
});
});
it('rejects invalid url', function() {
return GeoJsonDataSource.load('invalid.geojson').then(function() {
fail('should not be called');
}).otherwise(function(error) {
expect(error.statusCode).toBe(404);
});
});
it('rejects null CRS', function() {
var featureWithNullCrs = {
type : 'Feature',
geometry : point,
crs : null
};
return GeoJsonDataSource.load(featureWithNullCrs).then(function() {
fail('should not be called');
}).otherwise(function(error) {
expect(error).toBeInstanceOf(RuntimeError);
expect(error.message).toContain('crs is null.');
});
});
it('rejects unknown CRS', function() {
var featureWithUnknownCrsType = {
type : 'Feature',
geometry : point,
crs : {
type : 'potato',
properties : {}
}
};
return GeoJsonDataSource.load(featureWithUnknownCrsType).then(function() {
fail('should not be called');
}).otherwise(function(error) {
expect(error).toBeInstanceOf(RuntimeError);
expect(error.message).toContain('Unknown crs type: potato');
});
});
it('rejects undefined CRS properties', function() {
var featureWithUndefinedCrsProperty = {
type : 'Feature',
geometry : point,
crs : {
type : 'name'
}
};
return GeoJsonDataSource.load(featureWithUndefinedCrsProperty).then(function() {
fail('should not be called');
}).otherwise(function(error) {
expect(error).toBeInstanceOf(RuntimeError);
expect(error.message).toContain('crs.properties is undefined.');
});
});
it('rejects unknown CRS name', function() {
var featureWithUnknownCrsType = {
type : 'Feature',
geometry : point,
crs : {
type : 'name',
properties : {
name : 'failMe'
}
}
};
return GeoJsonDataSource.load(featureWithUnknownCrsType).then(function() {
fail('should not be called');
}).otherwise(function(error) {
expect(error).toBeInstanceOf(RuntimeError);
expect(error.message).toContain('Unknown crs name: failMe');
});
});
it('rejects unknown CRS link', function() {
var featureWithUnknownCrsType = {
type : 'Feature',
geometry : point,
crs : {
type : 'link',
properties : {
href : 'failMe',
type : 'failMeTwice'
}
}
};
return GeoJsonDataSource.load(featureWithUnknownCrsType).then(function() {
fail('should not be called');
}).otherwise(function(error) {
expect(error).toBeInstanceOf(RuntimeError);
expect(error.message).toContain('Unable to resolve crs link: {"href":"failMe","type":"failMeTwice"}');
});
});
it('load rejects loading non json file', function() {
var dataSource = new GeoJsonDataSource();
var spy = jasmine.createSpy('errorEvent');
dataSource.errorEvent.addEventListener(spy);
// Blue.png is not JSON
return dataSource.load('Data/Images/Blue.png').then(function() {
fail('should not be called');
}).otherwise(function() {
expect(spy).toHaveBeenCalledWith(dataSource, jasmine.any(Error));
});
});
it('load raises loading event', function() {
var dataSource = new GeoJsonDataSource();
var spy = jasmine.createSpy('loadingEvent');
dataSource.loadingEvent.addEventListener(spy);
var promise = dataSource.load('Data/test.geojson');
expect(spy).toHaveBeenCalledWith(dataSource, true);
expect(dataSource.isLoading).toBe(true);
return promise.then(function() {
expect(spy).toHaveBeenCalledWith(dataSource, false);
expect(dataSource.isLoading).toBe(false);
});
});
});
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/qa-test'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
|
import './image-embed-tooltip.scss';
import createTooltip from './tooltip';
export default Quill => class ImageEmbedTooltip extends createTooltip(Quill) {
static TEMPLATE = `
<div class="controls">
<label>Enter image url:</label>
<input class="url" type="text">
<a class="action">Save</a>
</div>`;
constructor(quill, bounds, { spacing = 0 } = {}) {
super(quill, bounds);
this.padding = ' '.repeat(spacing);
this.textbox = this.root.querySelector('input.url');
this.btnAction = this.root.querySelector('a.action');
this.listen();
}
listen() {
const Keyboard = Quill.import('modules/keyboard');
this.btnAction.addEventListener('click', () => this.embedImage());
this.textbox.addEventListener('keydown', e => {
if (Keyboard.match(e, 'enter')) {
this.embedImage();
e.preventDefault();
} else if (Keyboard.match(e, 'escape')) {
this.hide();
e.preventDefault();
}
});
}
show() {
super.show();
this.root.classList.add('ql-image-embed');
this.textbox.select();
}
embedImage() {
const url = this.textbox.value;
if (!url) return;
const { quill } = this;
const range = quill.getSelection(true);
if (range) {
const { padding } = this;
const source = Quill.sources.USER;
let offset = range.index + range.length;
quill.insertText(offset, padding, source);
offset += padding.length;
quill.insertEmbed(offset, 'image', url, source);
offset += 1;
quill.insertText(offset, padding, source);
offset += padding.length;
quill.setSelection(offset, source);
}
this.textbox.value = '';
this.hide();
}
};
|
import gql from 'graphql-tag'
export const schema = gql`
type Message {
id: String!
to: String!
from: String!
userId: String!
user: User!
}
type Query {
messages: [Message!]!
message(id: String!): Message!
}
input CreateMessageInput {
to: String!
from: String!
userId: String!
}
input UpdateMessageInput {
to: String
from: String
userId: String
}
type Mutation {
createMessage(input: CreateMessageInput!): Message!
updateMessage(id: String!, input: UpdateMessageInput!): Message!
deleteMessage(id: String!): Message!
}
`
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-a3426800","chunk-2d21a844","chunk-2d0b9e22","chunk-2d0aa631","chunk-2d0a3741","chunk-2d0e9955"],{"01f0":function(t,e,r){t.exports=r.p+"static/img/video.09ec4416.png"},1194:function(t,e,r){t.exports=r.p+"static/img/logo_login.7918108b.png"},"359c":function(t,e,r){t.exports=r.p+"static/img/github.5d298198.png"},"8dc6":function(t,e,r){t.exports=r.p+"static/img/yuque.5236e459.png"},bc9f:function(t,e,r){t.exports=r.p+"static/img/docs.20eecda0.png"},c3b4:function(t,e,r){},d00b:function(t,e,r){"use strict";var n=r("c3b4"),i=r.n(n);i.a},e49c:function(t,e,r){"use strict";r.r(e);var n=function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("div",{staticClass:"user-layout-wrapper",attrs:{id:"userLayout"}},[r("div",{staticClass:"container"},[t._m(0),t._v(" "),r("div",{staticClass:"main"},[r("el-form",{ref:"loginForm",attrs:{model:t.loginForm,rules:t.rules},nativeOn:{keyup:function(e){return!e.type.indexOf("key")&&t._k(e.keyCode,"enter",13,e.key,"Enter")?null:t.submitForm(e)}}},[r("el-form-item",{attrs:{prop:"username"}},[r("el-input",{attrs:{placeholder:"请输入用户名"},model:{value:t.loginForm.username,callback:function(e){t.$set(t.loginForm,"username",e)},expression:"loginForm.username"}},[r("i",{staticClass:"el-input__icon el-icon-user",attrs:{slot:"suffix"},slot:"suffix"})])],1),t._v(" "),r("el-form-item",{attrs:{prop:"password"}},[r("el-input",{attrs:{type:"lock"===t.lock?"password":"text",placeholder:"请输入密码"},model:{value:t.loginForm.password,callback:function(e){t.$set(t.loginForm,"password",e)},expression:"loginForm.password"}},[r("i",{class:"el-input__icon el-icon-"+t.lock,attrs:{slot:"suffix"},on:{click:t.changeLock},slot:"suffix"})])],1),t._v(" "),r("el-form-item",{staticStyle:{position:"relative"}},[r("el-input",{staticStyle:{width:"60%"},attrs:{name:"logVerify",placeholder:"请输入验证码"},model:{value:t.loginForm.captcha,callback:function(e){t.$set(t.loginForm,"captcha",e)},expression:"loginForm.captcha"}}),t._v(" "),r("div",{staticClass:"vPic"},[t.picPath?r("img",{attrs:{src:t.picPath,width:"100%",height:"100%",alt:"请输入验证码"},on:{click:function(e){return t.loginVefify()}}}):t._e()])],1),t._v(" "),r("el-form-item",[r("el-button",{staticStyle:{width:"100%"},attrs:{type:"primary"},on:{click:t.submitForm}},[t._v("登 录")])],1)],1)],1),t._v(" "),r("div",{staticClass:"footer"},[t._m(1),t._v(" "),r("div",{staticClass:"copyright"},[t._v("\n Copyright © "+t._s(t.curYear)+" 💖flipped-aurora\n ")])])])])},i=[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"top"},[n("div",{staticClass:"desc"},[n("img",{staticClass:"logo_login",attrs:{src:r("1194"),alt:""}})]),t._v(" "),n("div",{staticClass:"header"},[n("a",{attrs:{href:"/"}},[n("span",{staticClass:"title"},[t._v("Gin-Vue-Admin")])])])])},function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"links"},[n("a",{attrs:{href:"http://doc.henrongyi.top/"}},[n("img",{staticClass:"link-icon",attrs:{src:r("bc9f")}})]),t._v(" "),n("a",{attrs:{href:"https://www.yuque.com/flipped-aurora/"}},[n("img",{staticClass:"link-icon",attrs:{src:r("8dc6")}})]),t._v(" "),n("a",{attrs:{href:"https://github.com/flipped-aurora/gin-vue-admin"}},[n("img",{staticClass:"link-icon",attrs:{src:r("359c")}})]),t._v(" "),n("a",{attrs:{href:"https://space.bilibili.com/322210472"}},[n("img",{staticClass:"link-icon",attrs:{src:r("01f0")}})])])}],a=(r("8e6e"),r("ac6a"),r("456d"),r("96cf"),r("3b8d")),s=r("bd86"),c=r("2f62"),o=r("c24f");function l(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function u(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?l(r,!0).forEach(function(e){Object(s["a"])(t,e,r[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):l(r).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))})}return t}var p={name:"Login",data:function(){var t=function(t,e,r){if(e.length<5||e.length>12)return r(new Error("请输入正确的用户名"));r()},e=function(t,e,r){if(e.length<6||e.length>12)return r(new Error("请输入正确的密码"));r()};return{curYear:0,lock:"lock",loginForm:{username:"admin",password:"123456",captcha:"",captchaId:""},rules:{username:[{validator:t,trigger:"blur"}],password:[{validator:e,trigger:"blur"}]},logVerify:"",picPath:""}},created:function(){this.loginVefify(),this.curYear=(new Date).getFullYear()},methods:u({},Object(c["b"])("user",["LoginIn"]),{login:function(){var t=Object(a["a"])(regeneratorRuntime.mark(function t(){return regeneratorRuntime.wrap(function(t){while(1)switch(t.prev=t.next){case 0:return t.next=2,this.LoginIn(this.loginForm);case 2:case"end":return t.stop()}},t,this)}));function e(){return t.apply(this,arguments)}return e}(),submitForm:function(){var t=Object(a["a"])(regeneratorRuntime.mark(function t(){var e=this;return regeneratorRuntime.wrap(function(t){while(1)switch(t.prev=t.next){case 0:this.$refs.loginForm.validate(function(){var t=Object(a["a"])(regeneratorRuntime.mark(function t(r){return regeneratorRuntime.wrap(function(t){while(1)switch(t.prev=t.next){case 0:if(!r){t.next=5;break}e.login(),e.loginVefify(),t.next=8;break;case 5:return e.$message({type:"error",message:"请正确填写登录信息",showClose:!0}),e.loginVefify(),t.abrupt("return",!1);case 8:case"end":return t.stop()}},t)}));return function(e){return t.apply(this,arguments)}}());case 1:case"end":return t.stop()}},t,this)}));function e(){return t.apply(this,arguments)}return e}(),changeLock:function(){"lock"===this.lock?this.lock="unlock":this.lock="lock"},loginVefify:function(){var t=this;Object(o["captcha"])({}).then(function(e){t.picPath=e.data.picPath,t.loginForm.captchaId=e.data.captchaId})}})},f=p,m=(r("d00b"),r("2877")),g=Object(m["a"])(f,n,i,!1,null,"1fce3198",null);e["default"]=g.exports}}]);
|
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
module.exports = AbstractNetworkMessage;
var EventEmitter = require('events').EventEmitter;
var robb = require('robb/src/robb');
var util = require('util');
function AbstractNetworkMessage(options) {
options = options || {};
if (!robb.isUnsignedInt(options.index)) {
throw new Error('Message requires to be reliably sent with an index');
}
this.index = options.index;
if (typeof options.replyCallback === 'function') {
this.replyCallback = options.replyCallback;
} else {
this.replyCallback = null;
}
}
util.inherits(AbstractNetworkMessage, EventEmitter);
AbstractNetworkMessage.type = 'Abstract';
AbstractNetworkMessage.prototype.toJSON = function() {
var type = Object.getPrototypeOf(this).constructor.type;
if (type === AbstractNetworkMessage.type) {
throw new Error('Cannot call toJSON on an AbstractNetworkMessage');
}
return {
type: type,
index: this.index
};
};
|
import Component from './bar-chart-tooltip-component';
export default Component;
|
from django.conf import settings
from .models import LinkList
def get_linklists(request):
res = LinkList.objects.all()
lut = {}
for ll in res:
lut.update({ll.key:ll.link_set.filter(published=True).order_by('sort').all()})
return {
'link_list':lut,
}
all_processors = [
get_linklists,
]
def all(request):
combined = {}
for f in all_processors:
combined.update(f(request))
return combined
|
//This function takes in a string and finds the longest word
function longestWord(str){
var max =0;
var array = [];
var temp = "";
for(var i=0;i<str.length;i++){
if(str[i]!==" "){
temp+=str[i];
}
if(str[i]===" "){
array.push(temp);
temp="";
}
array.push(temp);
}
for(var j=0;j<array.length;j++){
if(array[j].length>max){
max=array[j].length;
temp=array[j];
}
}
return "the longest word is "+temp;
}
console.log(longestWord("a bb ccc dddd eeeee"));
|
import _ from 'lodash';
import BaseEditConditional from './editForm/Base.edit.conditional';
import BaseEditData from './editForm/Base.edit.data';
import BaseEditAPI from './editForm/Base.edit.api';
import BaseEditDisplay from './editForm/Base.edit.display';
import BaseEditLogic from './editForm/Base.edit.logic';
import BaseEditValidation from './editForm/Base.edit.validation';
import BaseEditLayout from './editForm/Base.edit.layout';
import EditFormUtils from './editForm/utils';
export default function(...extend) {
const components = _.cloneDeep([
{
type: 'tabs',
key: 'tabs',
components: [
{
label: 'Display',
key: 'display',
weight: 0,
components: BaseEditDisplay
},
{
label: 'Data',
key: 'data',
weight: 10,
components: BaseEditData
},
{
label: 'Validation',
key: 'validation',
weight: 20,
components: BaseEditValidation
},
{
label: 'API',
key: 'api',
weight: 30,
components: BaseEditAPI
},
{
label: 'Conditional',
key: 'conditional',
weight: 40,
components: BaseEditConditional
},
{
label: 'Logic',
key: 'logic',
weight: 50,
components: BaseEditLogic
},
{
label: 'Layout',
key: 'layout',
weight: 60,
components: BaseEditLayout
}
]
}
]).concat(extend.map((items) => ({
type: 'tabs',
key: 'tabs',
components: items
})));
return {
components: _.unionWith(components, EditFormUtils.unifyComponents).concat({
type: 'hidden',
key: 'type'
})
};
}
|
"""
Zappa core library. You may also want to look at `cli.py` and `util.py`.
"""
##
# Imports
##
from __future__ import print_function
import getpass
import glob
import hashlib
import json
import logging
import os
import random
import shutil
import string
import subprocess
import tarfile
import tempfile
import time
import uuid
import zipfile
from builtins import bytes, int
from distutils.dir_util import copy_tree
from io import open
import requests
from setuptools import find_packages
import boto3
import botocore
import troposphere
import troposphere.apigateway
from botocore.exceptions import ClientError
from lambda_packages import lambda_packages as lambda_packages_orig
from tqdm import tqdm
from .utilities import (add_event_source, conflicts_with_a_neighbouring_module,
contains_python_files_or_subdirs, copytree,
get_topic_name, get_venv_from_python_version,
human_size, remove_event_source)
try:
unicode # Python 2
except NameError:
unicode = str # Python 3
# We lower-case lambda package keys to match lower-cased keys in get_installed_packages()
lambda_packages = {package_name.lower(): val for package_name, val in lambda_packages_orig.items()}
##
# Logging Config
##
logging.basicConfig(format='%(levelname)s:%(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
##
# Policies And Template Mappings
##
ASSUME_POLICY = """{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": [
"apigateway.amazonaws.com",
"lambda.amazonaws.com",
"events.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}"""
ATTACH_POLICY = """{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"xray:PutTraceSegments",
"xray:PutTelemetryRecords"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"ec2:AttachNetworkInterface",
"ec2:CreateNetworkInterface",
"ec2:DeleteNetworkInterface",
"ec2:DescribeInstances",
"ec2:DescribeNetworkInterfaces",
"ec2:DetachNetworkInterface",
"ec2:ModifyNetworkInterfaceAttribute",
"ec2:ResetNetworkInterfaceAttribute"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": "arn:aws:s3:::*"
},
{
"Effect": "Allow",
"Action": [
"kinesis:*"
],
"Resource": "arn:aws:kinesis:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"sns:*"
],
"Resource": "arn:aws:sns:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"sqs:*"
],
"Resource": "arn:aws:sqs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"dynamodb:*"
],
"Resource": "arn:aws:dynamodb:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"route53:*"
],
"Resource": "*"
}
]
}"""
# Latest list: https://docs.aws.amazon.com/general/latest/gr/rande.html#apigateway_region
API_GATEWAY_REGIONS = ['us-east-1', 'us-east-2',
'us-west-1', 'us-west-2',
'eu-central-1',
'eu-north-1',
'eu-west-1', 'eu-west-2', 'eu-west-3',
'eu-north-1',
'ap-northeast-1', 'ap-northeast-2', 'ap-northeast-3',
'ap-southeast-1', 'ap-southeast-2',
'ap-east-1',
'ap-south-1',
'ca-central-1',
'cn-north-1',
'cn-northwest-1',
'sa-east-1',
'us-gov-east-1', 'us-gov-west-1']
# Latest list: https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region
LAMBDA_REGIONS = ['us-east-1', 'us-east-2',
'us-west-1', 'us-west-2',
'eu-central-1',
'eu-north-1',
'eu-west-1', 'eu-west-2', 'eu-west-3',
'eu-north-1',
'ap-northeast-1', 'ap-northeast-2', 'ap-northeast-3',
'ap-southeast-1', 'ap-southeast-2',
'ap-east-1',
'ap-south-1',
'ca-central-1',
'cn-north-1',
'cn-northwest-1',
'sa-east-1',
'us-gov-east-1',
'us-gov-west-1']
# We never need to include these.
# Related: https://github.com/Miserlou/Zappa/pull/56
# Related: https://github.com/Miserlou/Zappa/pull/581
ZIP_EXCLUDES = [
'*.exe', '*.DS_Store', '*.Python', '*.git', '.git/*', '*.zip', '*.tar.gz',
'*.hg', 'pip', 'docutils*', 'setuputils*', '__pycache__/*'
]
# When using ALB as an event source for Lambdas, we need to create an alias
# to ensure that, on zappa update, the ALB doesn't lose permissions to access
# the Lambda.
# See: https://github.com/Miserlou/Zappa/pull/1730
ALB_LAMBDA_ALIAS = 'current-alb-version'
##
# Classes
##
class Zappa(object):
"""
Zappa!
Makes it easy to run Python web applications on AWS Lambda/API Gateway.
"""
##
# Configurables
##
http_methods = ['ANY']
role_name = "ZappaLambdaExecution"
extra_permissions = None
assume_policy = ASSUME_POLICY
attach_policy = ATTACH_POLICY
apigateway_policy = None
cloudwatch_log_levels = ['OFF', 'ERROR', 'INFO']
xray_tracing = False
##
# Credentials
##
boto_session = None
credentials_arn = None
def __init__(self,
boto_session=None,
profile_name=None,
aws_region=None,
load_credentials=True,
desired_role_name=None,
desired_role_arn=None,
runtime='python2.7', # Detected at runtime in CLI
tags=(),
endpoint_urls={},
xray_tracing=False
):
"""
Instantiate this new Zappa instance, loading any custom credentials if necessary.
"""
# Set aws_region to None to use the system's region instead
if aws_region is None:
# https://github.com/Miserlou/Zappa/issues/413
self.aws_region = boto3.Session().region_name
logger.debug("Set region from boto: %s", self.aws_region)
else:
self.aws_region = aws_region
if desired_role_name:
self.role_name = desired_role_name
if desired_role_arn:
self.credentials_arn = desired_role_arn
self.runtime = runtime
if self.runtime == 'python2.7':
self.manylinux_wheel_file_suffix = 'cp27mu-manylinux1_x86_64.whl'
elif self.runtime == 'python3.6':
self.manylinux_wheel_file_suffix = 'cp36m-manylinux1_x86_64.whl'
else:
self.manylinux_wheel_file_suffix = 'cp37m-manylinux1_x86_64.whl'
self.endpoint_urls = endpoint_urls
self.xray_tracing = xray_tracing
# Some common invocations, such as DB migrations,
# can take longer than the default.
# Note that this is set to 300s, but if connected to
# APIGW, Lambda will max out at 30s.
# Related: https://github.com/Miserlou/Zappa/issues/205
long_config_dict = {
'region_name': aws_region,
'connect_timeout': 5,
'read_timeout': 300
}
long_config = botocore.client.Config(**long_config_dict)
if load_credentials:
self.load_credentials(boto_session, profile_name)
# Initialize clients
self.s3_client = self.boto_client('s3')
self.lambda_client = self.boto_client('lambda', config=long_config)
self.elbv2_client = self.boto_client('elbv2')
self.events_client = self.boto_client('events')
self.apigateway_client = self.boto_client('apigateway')
# AWS ACM certificates need to be created from us-east-1 to be used by API gateway
east_config = botocore.client.Config(region_name='us-east-1')
self.acm_client = self.boto_client('acm', config=east_config)
self.logs_client = self.boto_client('logs')
self.iam_client = self.boto_client('iam')
self.iam = self.boto_resource('iam')
self.cloudwatch = self.boto_client('cloudwatch')
self.route53 = self.boto_client('route53')
self.sns_client = self.boto_client('sns')
self.cf_client = self.boto_client('cloudformation')
self.dynamodb_client = self.boto_client('dynamodb')
self.cognito_client = self.boto_client('cognito-idp')
self.sts_client = self.boto_client('sts')
self.tags = tags
self.cf_template = troposphere.Template()
self.cf_api_resources = []
self.cf_parameters = {}
def configure_boto_session_method_kwargs(self, service, kw):
"""Allow for custom endpoint urls for non-AWS (testing and bootleg cloud) deployments"""
if service in self.endpoint_urls and not 'endpoint_url' in kw:
kw['endpoint_url'] = self.endpoint_urls[service]
return kw
def boto_client(self, service, *args, **kwargs):
"""A wrapper to apply configuration options to boto clients"""
return self.boto_session.client(service, *args, **self.configure_boto_session_method_kwargs(service, kwargs))
def boto_resource(self, service, *args, **kwargs):
"""A wrapper to apply configuration options to boto resources"""
return self.boto_session.resource(service, *args, **self.configure_boto_session_method_kwargs(service, kwargs))
def cache_param(self, value):
'''Returns a troposphere Ref to a value cached as a parameter.'''
if value not in self.cf_parameters:
keyname = chr(ord('A') + len(self.cf_parameters))
param = self.cf_template.add_parameter(troposphere.Parameter(
keyname, Type="String", Default=value, tags=self.tags
))
self.cf_parameters[value] = param
return troposphere.Ref(self.cf_parameters[value])
##
# Packaging
##
def copy_editable_packages(self, egg_links, temp_package_path):
""" """
for egg_link in egg_links:
with open(egg_link, 'rb') as df:
egg_path = df.read().decode('utf-8').splitlines()[0].strip()
pkgs = set([x.split(".")[0] for x in find_packages(egg_path, exclude=['test', 'tests'])])
for pkg in pkgs:
copytree(os.path.join(egg_path, pkg), os.path.join(temp_package_path, pkg), metadata=False, symlinks=False)
if temp_package_path:
# now remove any egg-links as they will cause issues if they still exist
for link in glob.glob(os.path.join(temp_package_path, "*.egg-link")):
os.remove(link)
def get_deps_list(self, pkg_name, installed_distros=None):
"""
For a given package, returns a list of required packages. Recursive.
"""
# https://github.com/Miserlou/Zappa/issues/1478. Using `pkg_resources`
# instead of `pip` is the recommended approach. The usage is nearly
# identical.
import pkg_resources
deps = []
if not installed_distros:
installed_distros = pkg_resources.WorkingSet()
for package in installed_distros:
if package.project_name.lower() == pkg_name.lower():
deps = [(package.project_name, package.version)]
for req in package.requires():
deps += self.get_deps_list(pkg_name=req.project_name, installed_distros=installed_distros)
return list(set(deps)) # de-dupe before returning
def create_handler_venv(self):
"""
Takes the installed zappa and brings it into a fresh virtualenv-like folder. All dependencies are then downloaded.
"""
import subprocess
# We will need the currenv venv to pull Zappa from
current_venv = self.get_current_venv()
# Make a new folder for the handler packages
ve_path = os.path.join(os.getcwd(), 'handler_venv')
if os.sys.platform == 'win32':
current_site_packages_dir = os.path.join(current_venv, 'Lib', 'site-packages')
venv_site_packages_dir = os.path.join(ve_path, 'Lib', 'site-packages')
else:
current_site_packages_dir = os.path.join(current_venv, 'lib', get_venv_from_python_version(), 'site-packages')
venv_site_packages_dir = os.path.join(ve_path, 'lib', get_venv_from_python_version(), 'site-packages')
if not os.path.isdir(venv_site_packages_dir):
os.makedirs(venv_site_packages_dir)
# Copy zappa* to the new virtualenv
zappa_things = [z for z in os.listdir(current_site_packages_dir) if z.lower()[:5] == 'zappa']
for z in zappa_things:
copytree(os.path.join(current_site_packages_dir, z), os.path.join(venv_site_packages_dir, z))
# Use pip to download zappa's dependencies. Copying from current venv causes issues with things like PyYAML that installs as yaml
zappa_deps = self.get_deps_list('zappa')
pkg_list = ['{0!s}=={1!s}'.format(dep, version) for dep, version in zappa_deps]
# Need to manually add setuptools
pkg_list.append('setuptools')
command = ["pip", "install", "--quiet", "--target", venv_site_packages_dir] + pkg_list
# This is the recommended method for installing packages if you don't
# to depend on `setuptools`
# https://github.com/pypa/pip/issues/5240#issuecomment-381662679
pip_process = subprocess.Popen(command, stdout=subprocess.PIPE)
# Using communicate() to avoid deadlocks
pip_process.communicate()
pip_return_code = pip_process.returncode
if pip_return_code:
raise EnvironmentError("Pypi lookup failed")
return ve_path
# staticmethod as per https://github.com/Miserlou/Zappa/issues/780
@staticmethod
def get_current_venv():
"""
Returns the path to the current virtualenv
"""
if 'VIRTUAL_ENV' in os.environ:
venv = os.environ['VIRTUAL_ENV']
elif os.path.exists('.python-version'): # pragma: no cover
try:
subprocess.check_output(['pyenv', 'help'], stderr=subprocess.STDOUT)
except OSError:
print("This directory seems to have pyenv's local venv, "
"but pyenv executable was not found.")
with open('.python-version', 'r') as f:
# minor fix in how .python-version is read
# Related: https://github.com/Miserlou/Zappa/issues/921
env_name = f.readline().strip()
bin_path = subprocess.check_output(['pyenv', 'which', 'python']).decode('utf-8')
venv = bin_path[:bin_path.rfind(env_name)] + env_name
else: # pragma: no cover
return None
return venv
def create_lambda_zip( self,
prefix='lambda_package',
handler_file=None,
slim_handler=False,
minify=True,
exclude=None,
use_precompiled_packages=True,
include=None,
venv=None,
output=None,
disable_progress=False,
archive_format='zip'
):
"""
Create a Lambda-ready zip file of the current virtualenvironment and working directory.
Returns path to that file.
"""
# Validate archive_format
if archive_format not in ['zip', 'tarball']:
raise KeyError("The archive format to create a lambda package must be zip or tarball")
# Pip is a weird package.
# Calling this function in some environments without this can cause.. funkiness.
import pip
if not venv:
venv = self.get_current_venv()
build_time = str(int(time.time()))
cwd = os.getcwd()
if not output:
if archive_format == 'zip':
archive_fname = prefix + '-' + build_time + '.zip'
elif archive_format == 'tarball':
archive_fname = prefix + '-' + build_time + '.tar.gz'
else:
archive_fname = output
archive_path = os.path.join(cwd, archive_fname)
# Files that should be excluded from the zip
if exclude is None:
exclude = list()
# Exclude the zip itself
exclude.append(archive_path)
# Make sure that 'concurrent' is always forbidden.
# https://github.com/Miserlou/Zappa/issues/827
if not 'concurrent' in exclude:
exclude.append('concurrent')
def splitpath(path):
parts = []
(path, tail) = os.path.split(path)
while path and tail:
parts.append(tail)
(path, tail) = os.path.split(path)
parts.append(os.path.join(path, tail))
return list(map(os.path.normpath, parts))[::-1]
split_venv = splitpath(venv)
split_cwd = splitpath(cwd)
# Ideally this should be avoided automatically,
# but this serves as an okay stop-gap measure.
if split_venv[-1] == split_cwd[-1]: # pragma: no cover
print(
"Warning! Your project and virtualenv have the same name! You may want "
"to re-create your venv with a new name, or explicitly define a "
"'project_name', as this may cause errors."
)
# First, do the project..
temp_project_path = tempfile.mkdtemp(prefix='zappa-project')
if not slim_handler:
# Slim handler does not take the project files.
if minify:
# Related: https://github.com/Miserlou/Zappa/issues/744
excludes = ZIP_EXCLUDES + exclude + [split_venv[-1]]
copytree(cwd, temp_project_path, metadata=False, symlinks=False, ignore=shutil.ignore_patterns(*excludes))
else:
copytree(cwd, temp_project_path, metadata=False, symlinks=False)
# If a handler_file is supplied, copy that to the root of the package,
# because that's where AWS Lambda looks for it. It can't be inside a package.
if handler_file:
filename = handler_file.split(os.sep)[-1]
shutil.copy(handler_file, os.path.join(temp_project_path, filename))
# Create and populate package ID file and write to temp project path
package_info = {}
package_info['uuid'] = str(uuid.uuid4())
package_info['build_time'] = build_time
package_info['build_platform'] = os.sys.platform
package_info['build_user'] = getpass.getuser()
# TODO: Add git head and info?
# Ex, from @scoates:
# def _get_git_branch():
# chdir(DIR)
# out = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip()
# lambci_branch = environ.get('LAMBCI_BRANCH', None)
# if out == "HEAD" and lambci_branch:
# out += " lambci:{}".format(lambci_branch)
# return out
# def _get_git_hash():
# chdir(DIR)
# return check_output(['git', 'rev-parse', 'HEAD']).strip()
# def _get_uname():
# return check_output(['uname', '-a']).strip()
# def _get_user():
# return check_output(['whoami']).strip()
# def set_id_info(zappa_cli):
# build_info = {
# 'branch': _get_git_branch(),
# 'hash': _get_git_hash(),
# 'build_uname': _get_uname(),
# 'build_user': _get_user(),
# 'build_time': datetime.datetime.utcnow().isoformat(),
# }
# with open(path.join(DIR, 'id_info.json'), 'w') as f:
# json.dump(build_info, f)
# return True
package_id_file = open(os.path.join(temp_project_path, 'package_info.json'), 'w')
dumped = json.dumps(package_info, indent=4)
try:
package_id_file.write(dumped)
except TypeError: # This is a Python 2/3 issue. TODO: Make pretty!
package_id_file.write(unicode(dumped))
package_id_file.close()
# Then, do site site-packages..
egg_links = []
temp_package_path = tempfile.mkdtemp(prefix='zappa-packages')
if os.sys.platform == 'win32':
site_packages = os.path.join(venv, 'Lib', 'site-packages')
else:
site_packages = os.path.join(venv, 'lib', get_venv_from_python_version(), 'site-packages')
egg_links.extend(glob.glob(os.path.join(site_packages, '*.egg-link')))
if minify:
excludes = ZIP_EXCLUDES + exclude
copytree(site_packages, temp_package_path, metadata=False, symlinks=False, ignore=shutil.ignore_patterns(*excludes))
else:
copytree(site_packages, temp_package_path, metadata=False, symlinks=False)
# We may have 64-bin specific packages too.
site_packages_64 = os.path.join(venv, 'lib64', get_venv_from_python_version(), 'site-packages')
if os.path.exists(site_packages_64):
egg_links.extend(glob.glob(os.path.join(site_packages_64, '*.egg-link')))
if minify:
excludes = ZIP_EXCLUDES + exclude
copytree(site_packages_64, temp_package_path, metadata = False, symlinks=False, ignore=shutil.ignore_patterns(*excludes))
else:
copytree(site_packages_64, temp_package_path, metadata = False, symlinks=False)
if egg_links:
self.copy_editable_packages(egg_links, temp_package_path)
copy_tree(temp_package_path, temp_project_path, update=True)
# Then the pre-compiled packages..
if use_precompiled_packages:
print("Downloading and installing dependencies..")
installed_packages = self.get_installed_packages(site_packages, site_packages_64)
try:
for installed_package_name, installed_package_version in installed_packages.items():
if self.have_correct_lambda_package_version(installed_package_name, installed_package_version):
print(" - %s==%s: Using precompiled lambda package " % (installed_package_name, installed_package_version,))
self.extract_lambda_package(installed_package_name, temp_project_path)
else:
cached_wheel_path = self.get_cached_manylinux_wheel(installed_package_name, installed_package_version, disable_progress)
if cached_wheel_path:
# Otherwise try to use manylinux packages from PyPi..
# Related: https://github.com/Miserlou/Zappa/issues/398
shutil.rmtree(os.path.join(temp_project_path, installed_package_name), ignore_errors=True)
with zipfile.ZipFile(cached_wheel_path) as zfile:
zfile.extractall(temp_project_path)
elif self.have_any_lambda_package_version(installed_package_name):
# Finally see if we may have at least one version of the package in lambda packages
# Related: https://github.com/Miserlou/Zappa/issues/855
lambda_version = lambda_packages[installed_package_name][self.runtime]['version']
print(" - %s==%s: Warning! Using precompiled lambda package version %s instead!" % (installed_package_name, installed_package_version, lambda_version, ))
self.extract_lambda_package(installed_package_name, temp_project_path)
# This is a special case!
# SQLite3 is part of the _system_ Python, not a package. Still, it lives in `lambda-packages`.
# Everybody on Python3 gets it!
if self.runtime in ("python3.6", "python3.7"):
print(" - sqlite==python3: Using precompiled lambda package")
self.extract_lambda_package('sqlite3', temp_project_path)
except Exception as e:
print(e)
# XXX - What should we do here?
# Then archive it all up..
if archive_format == 'zip':
print("Packaging project as zip.")
try:
compression_method = zipfile.ZIP_DEFLATED
except ImportError: # pragma: no cover
compression_method = zipfile.ZIP_STORED
archivef = zipfile.ZipFile(archive_path, 'w', compression_method)
elif archive_format == 'tarball':
print("Packaging project as gzipped tarball.")
archivef = tarfile.open(archive_path, 'w|gz')
for root, dirs, files in os.walk(temp_project_path):
for filename in files:
# Skip .pyc files for Django migrations
# https://github.com/Miserlou/Zappa/issues/436
# https://github.com/Miserlou/Zappa/issues/464
if filename[-4:] == '.pyc' and root[-10:] == 'migrations':
continue
# If there is a .pyc file in this package,
# we can skip the python source code as we'll just
# use the compiled bytecode anyway..
if filename[-3:] == '.py' and root[-10:] != 'migrations':
abs_filname = os.path.join(root, filename)
abs_pyc_filename = abs_filname + 'c'
if os.path.isfile(abs_pyc_filename):
# but only if the pyc is older than the py,
# otherwise we'll deploy outdated code!
py_time = os.stat(abs_filname).st_mtime
pyc_time = os.stat(abs_pyc_filename).st_mtime
if pyc_time > py_time:
continue
# Make sure that the files are all correctly chmodded
# Related: https://github.com/Miserlou/Zappa/issues/484
# Related: https://github.com/Miserlou/Zappa/issues/682
os.chmod(os.path.join(root, filename), 0o755)
if archive_format == 'zip':
# Actually put the file into the proper place in the zip
# Related: https://github.com/Miserlou/Zappa/pull/716
zipi = zipfile.ZipInfo(os.path.join(root.replace(temp_project_path, '').lstrip(os.sep), filename))
zipi.create_system = 3
zipi.external_attr = 0o755 << int(16) # Is this P2/P3 functional?
with open(os.path.join(root, filename), 'rb') as f:
archivef.writestr(zipi, f.read(), compression_method)
elif archive_format == 'tarball':
tarinfo = tarfile.TarInfo(os.path.join(root.replace(temp_project_path, '').lstrip(os.sep), filename))
tarinfo.mode = 0o755
stat = os.stat(os.path.join(root, filename))
tarinfo.mtime = stat.st_mtime
tarinfo.size = stat.st_size
with open(os.path.join(root, filename), 'rb') as f:
archivef.addfile(tarinfo, f)
# Create python init file if it does not exist
# Only do that if there are sub folders or python files and does not conflict with a neighbouring module
# Related: https://github.com/Miserlou/Zappa/issues/766
if not contains_python_files_or_subdirs(root):
# if the directory does not contain any .py file at any level, we can skip the rest
dirs[:] = [d for d in dirs if d != root]
else:
if '__init__.py' not in files and not conflicts_with_a_neighbouring_module(root):
tmp_init = os.path.join(temp_project_path, '__init__.py')
open(tmp_init, 'a').close()
os.chmod(tmp_init, 0o755)
arcname = os.path.join(root.replace(temp_project_path, ''),
os.path.join(root.replace(temp_project_path, ''), '__init__.py'))
if archive_format == 'zip':
archivef.write(tmp_init, arcname)
elif archive_format == 'tarball':
archivef.add(tmp_init, arcname)
# And, we're done!
archivef.close()
# Trash the temp directory
shutil.rmtree(temp_project_path)
shutil.rmtree(temp_package_path)
if os.path.isdir(venv) and slim_handler:
# Remove the temporary handler venv folder
shutil.rmtree(venv)
return archive_fname
def extract_lambda_package(self, package_name, path):
"""
Extracts the lambda package into a given path. Assumes the package exists in lambda packages.
"""
lambda_package = lambda_packages[package_name][self.runtime]
# Trash the local version to help with package space saving
shutil.rmtree(os.path.join(path, package_name), ignore_errors=True)
tar = tarfile.open(lambda_package['path'], mode="r:gz")
for member in tar.getmembers():
tar.extract(member, path)
@staticmethod
def get_installed_packages(site_packages, site_packages_64):
"""
Returns a dict of installed packages that Zappa cares about.
"""
import pkg_resources
package_to_keep = []
if os.path.isdir(site_packages):
package_to_keep += os.listdir(site_packages)
if os.path.isdir(site_packages_64):
package_to_keep += os.listdir(site_packages_64)
package_to_keep = [x.lower() for x in package_to_keep]
installed_packages = {package.project_name.lower(): package.version for package in
pkg_resources.WorkingSet()
if package.project_name.lower() in package_to_keep
or package.location.lower() in [site_packages.lower(), site_packages_64.lower()]}
return installed_packages
def have_correct_lambda_package_version(self, package_name, package_version):
"""
Checks if a given package version binary should be copied over from lambda packages.
package_name should be lower-cased version of package name.
"""
lambda_package_details = lambda_packages.get(package_name, {}).get(self.runtime)
if lambda_package_details is None:
return False
# Binaries can be compiled for different package versions
# Related: https://github.com/Miserlou/Zappa/issues/800
if package_version != lambda_package_details['version']:
return False
return True
def have_any_lambda_package_version(self, package_name):
"""
Checks if a given package has any lambda package version. We can try and use it with a warning.
package_name should be lower-cased version of package name.
"""
return lambda_packages.get(package_name, {}).get(self.runtime) is not None
@staticmethod
def download_url_with_progress(url, stream, disable_progress):
"""
Downloads a given url in chunks and writes to the provided stream (can be any io stream).
Displays the progress bar for the download.
"""
resp = requests.get(url, timeout=float(os.environ.get('PIP_TIMEOUT', 2)), stream=True)
resp.raw.decode_content = True
progress = tqdm(unit="B", unit_scale=True, total=int(resp.headers.get('Content-Length', 0)), disable=disable_progress)
for chunk in resp.iter_content(chunk_size=1024):
if chunk:
progress.update(len(chunk))
stream.write(chunk)
progress.close()
def get_cached_manylinux_wheel(self, package_name, package_version, disable_progress=False):
"""
Gets the locally stored version of a manylinux wheel. If one does not exist, the function downloads it.
"""
cached_wheels_dir = os.path.join(tempfile.gettempdir(), 'cached_wheels')
if not os.path.isdir(cached_wheels_dir):
os.makedirs(cached_wheels_dir)
wheel_file = '{0!s}-{1!s}-{2!s}'.format(package_name, package_version, self.manylinux_wheel_file_suffix)
wheel_path = os.path.join(cached_wheels_dir, wheel_file)
if not os.path.exists(wheel_path) or not zipfile.is_zipfile(wheel_path):
# The file is not cached, download it.
wheel_url = self.get_manylinux_wheel_url(package_name, package_version)
if not wheel_url:
return None
print(" - {}=={}: Downloading".format(package_name, package_version))
with open(wheel_path, 'wb') as f:
self.download_url_with_progress(wheel_url, f, disable_progress)
if not zipfile.is_zipfile(wheel_path):
return None
else:
print(" - {}=={}: Using locally cached manylinux wheel".format(package_name, package_version))
return wheel_path
def get_manylinux_wheel_url(self, package_name, package_version):
"""
For a given package name, returns a link to the download URL,
else returns None.
Related: https://github.com/Miserlou/Zappa/issues/398
Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b56880adbae
This function downloads metadata JSON of `package_name` from Pypi
and examines if the package has a manylinux wheel. This function
also caches the JSON file so that we don't have to poll Pypi
every time.
"""
cached_pypi_info_dir = os.path.join(tempfile.gettempdir(), 'cached_pypi_info')
if not os.path.isdir(cached_pypi_info_dir):
os.makedirs(cached_pypi_info_dir)
# Even though the metadata is for the package, we save it in a
# filename that includes the package's version. This helps in
# invalidating the cached file if the user moves to a different
# version of the package.
# Related: https://github.com/Miserlou/Zappa/issues/899
json_file = '{0!s}-{1!s}.json'.format(package_name, package_version)
json_file_path = os.path.join(cached_pypi_info_dir, json_file)
if os.path.exists(json_file_path):
with open(json_file_path, 'rb') as metafile:
data = json.load(metafile)
else:
url = 'https://pypi.python.org/pypi/{}/json'.format(package_name)
try:
res = requests.get(url, timeout=float(os.environ.get('PIP_TIMEOUT', 1.5)))
data = res.json()
except Exception as e: # pragma: no cover
return None
with open(json_file_path, 'wb') as metafile:
jsondata = json.dumps(data)
metafile.write(bytes(jsondata, "utf-8"))
if package_version not in data['releases']:
return None
for f in data['releases'][package_version]:
if f['filename'].endswith(self.manylinux_wheel_file_suffix):
return f['url']
return None
##
# S3
##
def upload_to_s3(self, source_path, bucket_name, disable_progress=False):
r"""
Given a file, upload it to S3.
Credentials should be stored in environment variables or ~/.aws/credentials (%USERPROFILE%\.aws\credentials on Windows).
Returns True on success, false on failure.
"""
try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError:
# This is really stupid S3 quirk. Technically, us-east-1 one has no S3,
# it's actually "US Standard", or something.
# More here: https://github.com/boto/boto3/issues/125
if self.aws_region == 'us-east-1':
self.s3_client.create_bucket(
Bucket=bucket_name,
)
else:
self.s3_client.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={'LocationConstraint': self.aws_region},
)
if self.tags:
tags = {
'TagSet': [{'Key': key, 'Value': self.tags[key]} for key in self.tags.keys()]
}
self.s3_client.put_bucket_tagging(Bucket=bucket_name, Tagging=tags)
if not os.path.isfile(source_path) or os.stat(source_path).st_size == 0:
print("Problem with source file {}".format(source_path))
return False
dest_path = os.path.split(source_path)[1]
try:
source_size = os.stat(source_path).st_size
print("Uploading {0} ({1})..".format(dest_path, human_size(source_size)))
progress = tqdm(total=float(os.path.getsize(source_path)), unit_scale=True, unit='B', disable=disable_progress)
# Attempt to upload to S3 using the S3 meta client with the progress bar.
# If we're unable to do that, try one more time using a session client,
# which cannot use the progress bar.
# Related: https://github.com/boto/boto3/issues/611
try:
self.s3_client.upload_file(
source_path, bucket_name, dest_path,
Callback=progress.update
)
except Exception as e: # pragma: no cover
self.s3_client.upload_file(source_path, bucket_name, dest_path)
progress.close()
except (KeyboardInterrupt, SystemExit): # pragma: no cover
raise
except Exception as e: # pragma: no cover
print(e)
return False
return True
def copy_on_s3(self, src_file_name, dst_file_name, bucket_name):
"""
Copies src file to destination within a bucket.
"""
try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e: # pragma: no cover
# If a client error is thrown, then check that it was a 404 error.
# If it was a 404 error, then the bucket does not exist.
error_code = int(e.response['Error']['Code'])
if error_code == 404:
return False
copy_src = {
"Bucket": bucket_name,
"Key": src_file_name
}
try:
self.s3_client.copy(
CopySource=copy_src,
Bucket=bucket_name,
Key=dst_file_name
)
return True
except botocore.exceptions.ClientError: # pragma: no cover
return False
def remove_from_s3(self, file_name, bucket_name):
"""
Given a file name and a bucket, remove it from S3.
There's no reason to keep the file hosted on S3 once its been made into a Lambda function, so we can delete it from S3.
Returns True on success, False on failure.
"""
try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e: # pragma: no cover
# If a client error is thrown, then check that it was a 404 error.
# If it was a 404 error, then the bucket does not exist.
error_code = int(e.response['Error']['Code'])
if error_code == 404:
return False
try:
self.s3_client.delete_object(Bucket=bucket_name, Key=file_name)
return True
except (botocore.exceptions.ParamValidationError, botocore.exceptions.ClientError): # pragma: no cover
return False
##
# Lambda
##
def create_lambda_function( self,
bucket=None,
function_name=None,
handler=None,
s3_key=None,
description='Zappa Deployment',
timeout=30,
memory_size=512,
publish=True,
vpc_config=None,
dead_letter_config=None,
runtime='python2.7',
aws_environment_variables=None,
aws_kms_key_arn=None,
xray_tracing=False,
local_zip=None,
use_alb=False,
):
"""
Given a bucket and key (or a local path) of a valid Lambda-zip, a function name and a handler, register that Lambda function.
"""
if not vpc_config:
vpc_config = {}
if not dead_letter_config:
dead_letter_config = {}
if not self.credentials_arn:
self.get_credentials_arn()
if not aws_environment_variables:
aws_environment_variables = {}
if not aws_kms_key_arn:
aws_kms_key_arn = ''
kwargs = dict(
FunctionName=function_name,
Runtime=runtime,
Role=self.credentials_arn,
Handler=handler,
Description=description,
Timeout=timeout,
MemorySize=memory_size,
Publish=publish,
VpcConfig=vpc_config,
DeadLetterConfig=dead_letter_config,
Environment={'Variables': aws_environment_variables},
KMSKeyArn=aws_kms_key_arn,
TracingConfig={
'Mode': 'Active' if self.xray_tracing else 'PassThrough'
}
)
if local_zip:
kwargs['Code'] = {
'ZipFile': local_zip
}
else:
kwargs['Code'] = {
'S3Bucket': bucket,
'S3Key': s3_key
}
response = self.lambda_client.create_function(**kwargs)
resource_arn = response['FunctionArn']
version = response['Version']
# If we're using an ALB, let's create an alias mapped to the newly
# created function. This allows clean, no downtime association when
# using application load balancers as an event source.
# See: https://github.com/Miserlou/Zappa/pull/1730
# https://github.com/Miserlou/Zappa/issues/1823
if use_alb:
self.lambda_client.create_alias(
FunctionName=resource_arn,
FunctionVersion=version,
Name=ALB_LAMBDA_ALIAS,
)
if self.tags:
self.lambda_client.tag_resource(Resource=resource_arn, Tags=self.tags)
return resource_arn
def update_lambda_function(self, bucket, function_name, s3_key=None, publish=True, local_zip=None, num_revisions=None):
"""
Given a bucket and key (or a local path) of a valid Lambda-zip, a function name and a handler, update that Lambda function's code.
Optionally, delete previous versions if they exceed the optional limit.
"""
print("Updating Lambda function code..")
kwargs = dict(
FunctionName=function_name,
Publish=publish
)
if local_zip:
kwargs['ZipFile'] = local_zip
else:
kwargs['S3Bucket'] = bucket
kwargs['S3Key'] = s3_key
response = self.lambda_client.update_function_code(**kwargs)
resource_arn = response['FunctionArn']
version = response['Version']
# If the lambda has an ALB alias, let's update the alias
# to point to the newest version of the function. We have to use a GET
# here, as there's no HEAD-esque call to retrieve metadata about a
# function alias.
# Related: https://github.com/Miserlou/Zappa/pull/1730
# https://github.com/Miserlou/Zappa/issues/1823
try:
response = self.lambda_client.get_alias(
FunctionName=function_name,
Name=ALB_LAMBDA_ALIAS,
)
alias_exists = True
except botocore.exceptions.ClientError as e: # pragma: no cover
if "ResourceNotFoundException" not in e.response["Error"]["Code"]:
raise e
alias_exists = False
if alias_exists:
self.lambda_client.update_alias(
FunctionName=function_name,
FunctionVersion=version,
Name=ALB_LAMBDA_ALIAS,
)
if num_revisions:
# Find the existing revision IDs for the given function
# Related: https://github.com/Miserlou/Zappa/issues/1402
versions_in_lambda = []
versions = self.lambda_client.list_versions_by_function(FunctionName=function_name)
for version in versions['Versions']:
versions_in_lambda.append(version['Version'])
while 'NextMarker' in versions:
versions = self.lambda_client.list_versions_by_function(FunctionName=function_name,Marker=versions['NextMarker'])
for version in versions['Versions']:
versions_in_lambda.append(version['Version'])
versions_in_lambda.remove('$LATEST')
# Delete older revisions if their number exceeds the specified limit
for version in versions_in_lambda[::-1][num_revisions:]:
self.lambda_client.delete_function(FunctionName=function_name,Qualifier=version)
return resource_arn
def update_lambda_configuration( self,
lambda_arn,
function_name,
handler,
description='Zappa Deployment',
timeout=30,
memory_size=512,
publish=True,
vpc_config=None,
runtime='python2.7',
aws_environment_variables=None,
aws_kms_key_arn=None
):
"""
Given an existing function ARN, update the configuration variables.
"""
print("Updating Lambda function configuration..")
if not vpc_config:
vpc_config = {}
if not self.credentials_arn:
self.get_credentials_arn()
if not aws_kms_key_arn:
aws_kms_key_arn = ''
if not aws_environment_variables:
aws_environment_variables = {}
# Check if there are any remote aws lambda env vars so they don't get trashed.
# https://github.com/Miserlou/Zappa/issues/987, Related: https://github.com/Miserlou/Zappa/issues/765
lambda_aws_config = self.lambda_client.get_function_configuration(FunctionName=function_name)
if "Environment" in lambda_aws_config:
lambda_aws_environment_variables = lambda_aws_config["Environment"].get("Variables", {})
# Append keys that are remote but not in settings file
for key, value in lambda_aws_environment_variables.items():
if key not in aws_environment_variables:
aws_environment_variables[key] = value
response = self.lambda_client.update_function_configuration(
FunctionName=function_name,
Runtime=runtime,
Role=self.credentials_arn,
Handler=handler,
Description=description,
Timeout=timeout,
MemorySize=memory_size,
VpcConfig=vpc_config,
Environment={'Variables': aws_environment_variables},
KMSKeyArn=aws_kms_key_arn,
TracingConfig={
'Mode': 'Active' if self.xray_tracing else 'PassThrough'
}
)
resource_arn = response['FunctionArn']
if self.tags:
self.lambda_client.tag_resource(Resource=resource_arn, Tags=self.tags)
return resource_arn
def invoke_lambda_function( self,
function_name,
payload,
invocation_type='Event',
log_type='Tail',
client_context=None,
qualifier=None
):
"""
Directly invoke a named Lambda function with a payload.
Returns the response.
"""
return self.lambda_client.invoke(
FunctionName=function_name,
InvocationType=invocation_type,
LogType=log_type,
Payload=payload
)
def rollback_lambda_function_version(self, function_name, versions_back=1, publish=True):
"""
Rollback the lambda function code 'versions_back' number of revisions.
Returns the Function ARN.
"""
response = self.lambda_client.list_versions_by_function(FunctionName=function_name)
# Take into account $LATEST
if len(response['Versions']) < versions_back + 1:
print("We do not have {} revisions. Aborting".format(str(versions_back)))
return False
revisions = [int(revision['Version']) for revision in response['Versions'] if revision['Version'] != '$LATEST']
revisions.sort(reverse=True)
response = self.lambda_client.get_function(FunctionName='function:{}:{}'.format(function_name, revisions[versions_back]))
response = requests.get(response['Code']['Location'])
if response.status_code != 200:
print("Failed to get version {} of {} code".format(versions_back, function_name))
return False
response = self.lambda_client.update_function_code(FunctionName=function_name, ZipFile=response.content, Publish=publish) # pragma: no cover
return response['FunctionArn']
def get_lambda_function(self, function_name):
"""
Returns the lambda function ARN, given a name
This requires the "lambda:GetFunction" role.
"""
response = self.lambda_client.get_function(
FunctionName=function_name)
return response['Configuration']['FunctionArn']
def get_lambda_function_versions(self, function_name):
"""
Simply returns the versions available for a Lambda function, given a function name.
"""
try:
response = self.lambda_client.list_versions_by_function(
FunctionName=function_name
)
return response.get('Versions', [])
except Exception:
return []
def delete_lambda_function(self, function_name):
"""
Given a function name, delete it from AWS Lambda.
Returns the response.
"""
print("Deleting Lambda function..")
return self.lambda_client.delete_function(
FunctionName=function_name,
)
##
# Application load balancer
##
def deploy_lambda_alb( self,
lambda_arn,
lambda_name,
alb_vpc_config,
timeout
):
"""
The `zappa deploy` functionality for ALB infrastructure.
"""
if not alb_vpc_config:
raise EnvironmentError('When creating an ALB, alb_vpc_config must be filled out in zappa_settings.')
if 'SubnetIds' not in alb_vpc_config:
raise EnvironmentError('When creating an ALB, you must supply two subnets in different availability zones.')
if 'SecurityGroupIds' not in alb_vpc_config:
alb_vpc_config["SecurityGroupIds"] = []
if not alb_vpc_config.get('CertificateArn'):
raise EnvironmentError('When creating an ALB, you must supply a CertificateArn for the HTTPS listener.')
print("Deploying ALB infrastructure...")
# Create load balancer
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.create_load_balancer
kwargs = dict(
Name=lambda_name,
Subnets=alb_vpc_config["SubnetIds"],
SecurityGroups=alb_vpc_config["SecurityGroupIds"],
# TODO: Scheme can also be "internal" we need to add a new option for this.
Scheme="internet-facing",
# TODO: Tags might be a useful means of stock-keeping zappa-generated assets.
#Tags=[],
Type="application",
# TODO: can be ipv4 or dualstack (for ipv4 and ipv6) ipv4 is required for internal Scheme.
IpAddressType="ipv4"
)
response = self.elbv2_client.create_load_balancer(**kwargs)
if not(response["LoadBalancers"]) or len(response["LoadBalancers"]) != 1:
raise EnvironmentError("Failure to create application load balancer. Response was in unexpected format. Response was: {}".format(repr(response)))
if response["LoadBalancers"][0]['State']['Code'] == 'failed':
raise EnvironmentError("Failure to create application load balancer. Response reported a failed state: {}".format(response["LoadBalancers"][0]['State']['Reason']))
load_balancer_arn = response["LoadBalancers"][0]["LoadBalancerArn"]
load_balancer_dns = response["LoadBalancers"][0]["DNSName"]
load_balancer_vpc = response["LoadBalancers"][0]["VpcId"]
waiter = self.elbv2_client.get_waiter('load_balancer_available')
# Match the lambda timeout on the load balancer.
self.elbv2_client.modify_load_balancer_attributes(
LoadBalancerArn=load_balancer_arn,
Attributes=[{
'Key': 'idle_timeout.timeout_seconds',
'Value': str(timeout)
}]
)
# Create/associate target group.
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.create_target_group
kwargs = dict(
Name=lambda_name,
TargetType="lambda",
# TODO: Add options for health checks
)
response = self.elbv2_client.create_target_group(**kwargs)
if not(response["TargetGroups"]) or len(response["TargetGroups"]) != 1:
raise EnvironmentError("Failure to create application load balancer target group. Response was in unexpected format. Response was: {}".format(repr(response)))
target_group_arn = response["TargetGroups"][0]["TargetGroupArn"]
# Enable multi-value headers by default.
response = self.elbv2_client.modify_target_group_attributes(
TargetGroupArn=target_group_arn,
Attributes=[
{
'Key': 'lambda.multi_value_headers.enabled',
'Value': 'true'
},
]
)
# Allow execute permissions from target group to lambda.
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambda.Client.add_permission
kwargs = dict(
Action="lambda:InvokeFunction",
FunctionName="{}:{}".format(lambda_arn, ALB_LAMBDA_ALIAS),
Principal="elasticloadbalancing.amazonaws.com",
SourceArn=target_group_arn,
StatementId=lambda_name
)
response = self.lambda_client.add_permission(**kwargs)
# Register target group to lambda association.
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.register_targets
kwargs = dict(
TargetGroupArn=target_group_arn,
Targets=[{"Id": "{}:{}".format(lambda_arn, ALB_LAMBDA_ALIAS)}]
)
response = self.elbv2_client.register_targets(**kwargs)
# Bind listener to load balancer with default rule to target group.
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.create_listener
kwargs = dict(
# TODO: Listeners support custom ssl certificates (Certificates). For now we leave this default.
Certificates=[{"CertificateArn": alb_vpc_config['CertificateArn']}],
DefaultActions=[{
"Type": "forward",
"TargetGroupArn": target_group_arn,
}],
LoadBalancerArn=load_balancer_arn,
Protocol="HTTPS",
# TODO: Add option for custom ports
Port=443,
# TODO: Listeners support custom ssl security policy (SslPolicy). For now we leave this default.
)
response = self.elbv2_client.create_listener(**kwargs)
print("ALB created with DNS: {}".format(load_balancer_dns))
print("Note it may take several minutes for load balancer to become available.")
def undeploy_lambda_alb(self, lambda_name):
"""
The `zappa undeploy` functionality for ALB infrastructure.
"""
print("Undeploying ALB infrastructure...")
# Locate and delete alb/lambda permissions
try:
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambda.Client.remove_permission
self.lambda_client.remove_permission(
FunctionName=lambda_name,
StatementId=lambda_name
)
except botocore.exceptions.ClientError as e: # pragma: no cover
if "ResourceNotFoundException" in e.response["Error"]["Code"]:
pass
else:
raise e
# Locate and delete load balancer
try:
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.describe_load_balancers
response = self.elbv2_client.describe_load_balancers(
Names=[lambda_name]
)
if not(response["LoadBalancers"]) or len(response["LoadBalancers"]) > 1:
raise EnvironmentError("Failure to locate/delete ALB named [{}]. Response was: {}".format(lambda_name, repr(response)))
load_balancer_arn = response["LoadBalancers"][0]["LoadBalancerArn"]
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.describe_listeners
response = self.elbv2_client.describe_listeners(LoadBalancerArn=load_balancer_arn)
if not(response["Listeners"]):
print('No listeners found.')
elif len(response["Listeners"]) > 1:
raise EnvironmentError("Failure to locate/delete listener for ALB named [{}]. Response was: {}".format(lambda_name, repr(response)))
else:
listener_arn = response["Listeners"][0]["ListenerArn"]
# Remove the listener. This explicit deletion of the listener seems necessary to avoid ResourceInUseExceptions when deleting target groups.
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.delete_listener
response = self.elbv2_client.delete_listener(ListenerArn=listener_arn)
# Remove the load balancer and wait for completion
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.delete_load_balancer
response = self.elbv2_client.delete_load_balancer(LoadBalancerArn=load_balancer_arn)
waiter = self.elbv2_client.get_waiter('load_balancers_deleted')
print('Waiting for load balancer [{}] to be deleted..'.format(lambda_name))
waiter.wait(LoadBalancerArns=[load_balancer_arn], WaiterConfig={"Delay": 3})
except botocore.exceptions.ClientError as e: # pragma: no cover
print(e.response["Error"]["Code"])
if "LoadBalancerNotFound" in e.response["Error"]["Code"]:
pass
else:
raise e
# Locate and delete target group
try:
# Locate the lambda ARN
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambda.Client.get_function
response = self.lambda_client.get_function(FunctionName=lambda_name)
lambda_arn = response["Configuration"]["FunctionArn"]
# Locate the target group ARN
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.describe_target_groups
response = self.elbv2_client.describe_target_groups(Names=[lambda_name])
if not(response["TargetGroups"]) or len(response["TargetGroups"]) > 1:
raise EnvironmentError("Failure to locate/delete ALB target group named [{}]. Response was: {}".format(lambda_name, repr(response)))
target_group_arn = response["TargetGroups"][0]["TargetGroupArn"]
# Deregister targets and wait for completion
self.elbv2_client.deregister_targets(
TargetGroupArn=target_group_arn,
Targets=[{"Id": lambda_arn}]
)
waiter = self.elbv2_client.get_waiter('target_deregistered')
print('Waiting for target [{}] to be deregistered...'.format(lambda_name))
waiter.wait(
TargetGroupArn=target_group_arn,
Targets=[{"Id": lambda_arn}],
WaiterConfig={"Delay": 3}
)
# Remove the target group
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html#ElasticLoadBalancingv2.Client.delete_target_group
self.elbv2_client.delete_target_group(TargetGroupArn=target_group_arn)
except botocore.exceptions.ClientError as e: # pragma: no cover
print(e.response["Error"]["Code"])
if "TargetGroupNotFound" in e.response["Error"]["Code"]:
pass
else:
raise e
##
# API Gateway
##
def create_api_gateway_routes( self,
lambda_arn,
api_name=None,
api_key_required=False,
authorization_type='NONE',
authorizer=None,
cors_options=None,
description=None,
endpoint_configuration=None
):
"""
Create the API Gateway for this Zappa deployment.
Returns the new RestAPI CF resource.
"""
restapi = troposphere.apigateway.RestApi('Api')
restapi.Name = api_name or lambda_arn.split(':')[-1]
if not description:
description = 'Created automatically by Zappa.'
restapi.Description = description
endpoint_configuration = [] if endpoint_configuration is None else endpoint_configuration
if self.boto_session.region_name == "us-gov-west-1":
endpoint_configuration.append("REGIONAL")
if endpoint_configuration:
endpoint = troposphere.apigateway.EndpointConfiguration()
endpoint.Types = list(set(endpoint_configuration))
restapi.EndpointConfiguration = endpoint
if self.apigateway_policy:
restapi.Policy = json.loads(self.apigateway_policy)
self.cf_template.add_resource(restapi)
root_id = troposphere.GetAtt(restapi, 'RootResourceId')
invocation_prefix = "aws" if self.boto_session.region_name != "us-gov-west-1" else "aws-us-gov"
invocations_uri = 'arn:' + invocation_prefix + ':apigateway:' + self.boto_session.region_name + ':lambda:path/2015-03-31/functions/' + lambda_arn + '/invocations'
##
# The Resources
##
authorizer_resource = None
if authorizer:
authorizer_lambda_arn = authorizer.get('arn', lambda_arn)
lambda_uri = 'arn:{invocation_prefix}:apigateway:{region_name}:lambda:path/2015-03-31/functions/{lambda_arn}/invocations'.format(
invocation_prefix=invocation_prefix,
region_name=self.boto_session.region_name,
lambda_arn=authorizer_lambda_arn
)
authorizer_resource = self.create_authorizer(
restapi, lambda_uri, authorizer
)
self.create_and_setup_methods( restapi,
root_id,
api_key_required,
invocations_uri,
authorization_type,
authorizer_resource,
0
)
if cors_options:
self.create_and_setup_cors( restapi,
root_id,
invocations_uri,
0,
cors_options
)
resource = troposphere.apigateway.Resource('ResourceAnyPathSlashed')
self.cf_api_resources.append(resource.title)
resource.RestApiId = troposphere.Ref(restapi)
resource.ParentId = root_id
resource.PathPart = "{proxy+}"
self.cf_template.add_resource(resource)
self.create_and_setup_methods( restapi,
resource,
api_key_required,
invocations_uri,
authorization_type,
authorizer_resource,
1
) # pragma: no cover
if cors_options:
self.create_and_setup_cors( restapi,
resource,
invocations_uri,
1,
cors_options
) # pragma: no cover
return restapi
def create_authorizer(self, restapi, uri, authorizer):
"""
Create Authorizer for API gateway
"""
authorizer_type = authorizer.get("type", "TOKEN").upper()
identity_validation_expression = authorizer.get('validation_expression', None)
authorizer_resource = troposphere.apigateway.Authorizer("Authorizer")
authorizer_resource.RestApiId = troposphere.Ref(restapi)
authorizer_resource.Name = authorizer.get("name", "ZappaAuthorizer")
authorizer_resource.Type = authorizer_type
authorizer_resource.AuthorizerUri = uri
authorizer_resource.IdentitySource = "method.request.header.%s" % authorizer.get('token_header', 'Authorization')
if identity_validation_expression:
authorizer_resource.IdentityValidationExpression = identity_validation_expression
if authorizer_type == 'TOKEN':
if not self.credentials_arn:
self.get_credentials_arn()
authorizer_resource.AuthorizerResultTtlInSeconds = authorizer.get('result_ttl', 300)
authorizer_resource.AuthorizerCredentials = self.credentials_arn
if authorizer_type == 'COGNITO_USER_POOLS':
authorizer_resource.ProviderARNs = authorizer.get('provider_arns')
self.cf_api_resources.append(authorizer_resource.title)
self.cf_template.add_resource(authorizer_resource)
return authorizer_resource
def create_and_setup_methods(
self,
restapi,
resource,
api_key_required,
uri,
authorization_type,
authorizer_resource,
depth
):
"""
Set up the methods, integration responses and method responses for a given API Gateway resource.
"""
for method_name in self.http_methods:
method = troposphere.apigateway.Method(method_name + str(depth))
method.RestApiId = troposphere.Ref(restapi)
if type(resource) is troposphere.apigateway.Resource:
method.ResourceId = troposphere.Ref(resource)
else:
method.ResourceId = resource
method.HttpMethod = method_name.upper()
method.AuthorizationType = authorization_type
if authorizer_resource:
method.AuthorizerId = troposphere.Ref(authorizer_resource)
method.ApiKeyRequired = api_key_required
method.MethodResponses = []
self.cf_template.add_resource(method)
self.cf_api_resources.append(method.title)
if not self.credentials_arn:
self.get_credentials_arn()
credentials = self.credentials_arn # This must be a Role ARN
integration = troposphere.apigateway.Integration()
integration.CacheKeyParameters = []
integration.CacheNamespace = 'none'
integration.Credentials = credentials
integration.IntegrationHttpMethod = 'POST'
integration.IntegrationResponses = []
integration.PassthroughBehavior = 'NEVER'
integration.Type = 'AWS_PROXY'
integration.Uri = uri
method.Integration = integration
def create_and_setup_cors(self, restapi, resource, uri, depth, config):
"""
Set up the methods, integration responses and method responses for a given API Gateway resource.
"""
if config is True:
config = {}
method_name = "OPTIONS"
method = troposphere.apigateway.Method(method_name + str(depth))
method.RestApiId = troposphere.Ref(restapi)
if type(resource) is troposphere.apigateway.Resource:
method.ResourceId = troposphere.Ref(resource)
else:
method.ResourceId = resource
method.HttpMethod = method_name.upper()
method.AuthorizationType = "NONE"
method_response = troposphere.apigateway.MethodResponse()
method_response.ResponseModels = {
"application/json": "Empty"
}
response_headers = {
"Access-Control-Allow-Headers": "'%s'" % ",".join(config.get(
"allowed_headers", ["Content-Type", "X-Amz-Date",
"Authorization", "X-Api-Key",
"X-Amz-Security-Token"])),
"Access-Control-Allow-Methods": "'%s'" % ",".join(config.get(
"allowed_methods", ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"])),
"Access-Control-Allow-Origin": "'%s'" % config.get(
"allowed_origin", "*")
}
method_response.ResponseParameters = {
"method.response.header.%s" % key: True for key in response_headers
}
method_response.StatusCode = "200"
method.MethodResponses = [
method_response
]
self.cf_template.add_resource(method)
self.cf_api_resources.append(method.title)
integration = troposphere.apigateway.Integration()
integration.Type = 'MOCK'
integration.PassthroughBehavior = 'NEVER'
integration.RequestTemplates = {
"application/json": "{\"statusCode\": 200}"
}
integration_response = troposphere.apigateway.IntegrationResponse()
integration_response.ResponseParameters = {
"method.response.header.%s" % key: value for key, value in response_headers.items()
}
integration_response.ResponseTemplates = {
"application/json": ""
}
integration_response.StatusCode = "200"
integration.IntegrationResponses = [
integration_response
]
integration.Uri = uri
method.Integration = integration
def deploy_api_gateway( self,
api_id,
stage_name,
stage_description="",
description="",
cache_cluster_enabled=False,
cache_cluster_size='0.5',
variables=None,
cloudwatch_log_level='OFF',
cloudwatch_data_trace=False,
cloudwatch_metrics_enabled=False,
cache_cluster_ttl=300,
cache_cluster_encrypted=False
):
"""
Deploy the API Gateway!
Return the deployed API URL.
"""
print("Deploying API Gateway..")
self.apigateway_client.create_deployment(
restApiId=api_id,
stageName=stage_name,
stageDescription=stage_description,
description=description,
cacheClusterEnabled=cache_cluster_enabled,
cacheClusterSize=cache_cluster_size,
variables=variables or {}
)
if cloudwatch_log_level not in self.cloudwatch_log_levels:
cloudwatch_log_level = 'OFF'
self.apigateway_client.update_stage(
restApiId=api_id,
stageName=stage_name,
patchOperations=[
self.get_patch_op('logging/loglevel', cloudwatch_log_level),
self.get_patch_op('logging/dataTrace', cloudwatch_data_trace),
self.get_patch_op('metrics/enabled', cloudwatch_metrics_enabled),
self.get_patch_op('caching/ttlInSeconds', str(cache_cluster_ttl)),
self.get_patch_op('caching/dataEncrypted', cache_cluster_encrypted)
]
)
return "https://{}.execute-api.{}.amazonaws.com/{}".format(api_id, self.boto_session.region_name, stage_name)
def add_binary_support(self, api_id, cors=False):
"""
Add binary support
"""
response = self.apigateway_client.get_rest_api(
restApiId=api_id
)
if "binaryMediaTypes" not in response or "*/*" not in response["binaryMediaTypes"]:
self.apigateway_client.update_rest_api(
restApiId=api_id,
patchOperations=[
{
'op': "add",
'path': '/binaryMediaTypes/*~1*'
}
]
)
if cors:
# fix for issue 699 and 1035, cors+binary support don't work together
# go through each resource and update the contentHandling type
response = self.apigateway_client.get_resources(restApiId=api_id)
resource_ids = [
item['id'] for item in response['items']
if 'OPTIONS' in item.get('resourceMethods', {})
]
for resource_id in resource_ids:
self.apigateway_client.update_integration(
restApiId=api_id,
resourceId=resource_id,
httpMethod='OPTIONS',
patchOperations=[
{
"op": "replace",
"path": "/contentHandling",
"value": "CONVERT_TO_TEXT"
}
]
)
def remove_binary_support(self, api_id, cors=False):
"""
Remove binary support
"""
response = self.apigateway_client.get_rest_api(
restApiId=api_id
)
if "binaryMediaTypes" in response and "*/*" in response["binaryMediaTypes"]:
self.apigateway_client.update_rest_api(
restApiId=api_id,
patchOperations=[
{
'op': 'remove',
'path': '/binaryMediaTypes/*~1*'
}
]
)
if cors:
# go through each resource and change the contentHandling type
response = self.apigateway_client.get_resources(restApiId=api_id)
resource_ids = [
item['id'] for item in response['items']
if 'OPTIONS' in item.get('resourceMethods', {})
]
for resource_id in resource_ids:
self.apigateway_client.update_integration(
restApiId=api_id,
resourceId=resource_id,
httpMethod='OPTIONS',
patchOperations=[
{
"op": "replace",
"path": "/contentHandling",
"value": ""
}
]
)
def add_api_compression(self, api_id, min_compression_size):
"""
Add Rest API compression
"""
self.apigateway_client.update_rest_api(
restApiId=api_id,
patchOperations=[
{
'op': 'replace',
'path': '/minimumCompressionSize',
'value': str(min_compression_size)
}
]
)
def remove_api_compression(self, api_id):
"""
Remove Rest API compression
"""
self.apigateway_client.update_rest_api(
restApiId=api_id,
patchOperations=[
{
'op': 'replace',
'path': '/minimumCompressionSize',
}
]
)
def get_api_keys(self, api_id, stage_name):
"""
Generator that allows to iterate per API keys associated to an api_id and a stage_name.
"""
response = self.apigateway_client.get_api_keys(limit=500)
stage_key = '{}/{}'.format(api_id, stage_name)
for api_key in response.get('items'):
if stage_key in api_key.get('stageKeys'):
yield api_key.get('id')
def create_api_key(self, api_id, stage_name):
"""
Create new API key and link it with an api_id and a stage_name
"""
response = self.apigateway_client.create_api_key(
name='{}_{}'.format(stage_name, api_id),
description='Api Key for {}'.format(api_id),
enabled=True,
stageKeys=[
{
'restApiId': '{}'.format(api_id),
'stageName': '{}'.format(stage_name)
},
]
)
print('Created a new x-api-key: {}'.format(response['id']))
def remove_api_key(self, api_id, stage_name):
"""
Remove a generated API key for api_id and stage_name
"""
response = self.apigateway_client.get_api_keys(
limit=1,
nameQuery='{}_{}'.format(stage_name, api_id)
)
for api_key in response.get('items'):
self.apigateway_client.delete_api_key(
apiKey="{}".format(api_key['id'])
)
def add_api_stage_to_api_key(self, api_key, api_id, stage_name):
"""
Add api stage to Api key
"""
self.apigateway_client.update_api_key(
apiKey=api_key,
patchOperations=[
{
'op': 'add',
'path': '/stages',
'value': '{}/{}'.format(api_id, stage_name)
}
]
)
def get_patch_op(self, keypath, value, op='replace'):
"""
Return an object that describes a change of configuration on the given staging.
Setting will be applied on all available HTTP methods.
"""
if isinstance(value, bool):
value = str(value).lower()
return {'op': op, 'path': '/*/*/{}'.format(keypath), 'value': value}
def get_rest_apis(self, project_name):
"""
Generator that allows to iterate per every available apis.
"""
all_apis = self.apigateway_client.get_rest_apis(
limit=500
)
for api in all_apis['items']:
if api['name'] != project_name:
continue
yield api
def undeploy_api_gateway(self, lambda_name, domain_name=None, base_path=None):
"""
Delete a deployed REST API Gateway.
"""
print("Deleting API Gateway..")
api_id = self.get_api_id(lambda_name)
if domain_name:
# XXX - Remove Route53 smartly here?
# XXX - This doesn't raise, but doesn't work either.
try:
self.apigateway_client.delete_base_path_mapping(
domainName=domain_name,
basePath='(none)' if base_path is None else base_path
)
except Exception as e:
# We may not have actually set up the domain.
pass
was_deleted = self.delete_stack(lambda_name, wait=True)
if not was_deleted:
# try erasing it with the older method
for api in self.get_rest_apis(lambda_name):
self.apigateway_client.delete_rest_api(
restApiId=api['id']
)
def update_stage_config( self,
project_name,
stage_name,
cloudwatch_log_level,
cloudwatch_data_trace,
cloudwatch_metrics_enabled
):
"""
Update CloudWatch metrics configuration.
"""
if cloudwatch_log_level not in self.cloudwatch_log_levels:
cloudwatch_log_level = 'OFF'
for api in self.get_rest_apis(project_name):
self.apigateway_client.update_stage(
restApiId=api['id'],
stageName=stage_name,
patchOperations=[
self.get_patch_op('logging/loglevel', cloudwatch_log_level),
self.get_patch_op('logging/dataTrace', cloudwatch_data_trace),
self.get_patch_op('metrics/enabled', cloudwatch_metrics_enabled),
]
)
def update_cognito(self, lambda_name, user_pool, lambda_configs, lambda_arn):
LambdaConfig = {}
for config in lambda_configs:
LambdaConfig[config] = lambda_arn
description = self.cognito_client.describe_user_pool(UserPoolId=user_pool)
description_kwargs = {}
for key, value in description['UserPool'].items():
if key in ('UserPoolId', 'Policies', 'AutoVerifiedAttributes', 'SmsVerificationMessage',
'EmailVerificationMessage', 'EmailVerificationSubject', 'VerificationMessageTemplate',
'SmsAuthenticationMessage', 'MfaConfiguration', 'DeviceConfiguration',
'EmailConfiguration', 'SmsConfiguration', 'UserPoolTags',
'AdminCreateUserConfig'):
description_kwargs[key] = value
elif key is 'LambdaConfig':
for lckey, lcvalue in value.items():
if lckey in LambdaConfig:
value[lckey] = LambdaConfig[lckey]
print("value", value)
description_kwargs[key] = value
if 'LambdaConfig' not in description_kwargs:
description_kwargs['LambdaConfig'] = LambdaConfig
if 'TemporaryPasswordValidityDays' in description_kwargs['Policies']['PasswordPolicy']:
description_kwargs['AdminCreateUserConfig'].pop(
'UnusedAccountValidityDays', None)
result = self.cognito_client.update_user_pool(UserPoolId=user_pool, **description_kwargs)
if result['ResponseMetadata']['HTTPStatusCode'] != 200:
print("Cognito: Failed to update user pool", result)
# Now we need to add a policy to the IAM that allows cognito access
result = self.create_event_permission(lambda_name,
'cognito-idp.amazonaws.com',
'arn:aws:cognito-idp:{}:{}:userpool/{}'.
format(self.aws_region,
self.sts_client.get_caller_identity().get('Account'),
user_pool)
)
if result['ResponseMetadata']['HTTPStatusCode'] != 201:
print("Cognito: Failed to update lambda permission", result)
def delete_stack(self, name, wait=False):
"""
Delete the CF stack managed by Zappa.
"""
try:
stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0]
except: # pragma: no cover
print('No Zappa stack named {0}'.format(name))
return False
tags = {x['Key']:x['Value'] for x in stack['Tags']}
if tags.get('ZappaProject') == name:
self.cf_client.delete_stack(StackName=name)
if wait:
waiter = self.cf_client.get_waiter('stack_delete_complete')
print('Waiting for stack {0} to be deleted..'.format(name))
waiter.wait(StackName=name)
return True
else:
print('ZappaProject tag not found on {0}, doing nothing'.format(name))
return False
def create_stack_template( self,
lambda_arn,
lambda_name,
api_key_required,
iam_authorization,
authorizer,
cors_options=None,
description=None,
endpoint_configuration=None
):
"""
Build the entire CF stack.
Just used for the API Gateway, but could be expanded in the future.
"""
auth_type = "NONE"
if iam_authorization and authorizer:
logger.warn("Both IAM Authorization and Authorizer are specified, this is not possible. "
"Setting Auth method to IAM Authorization")
authorizer = None
auth_type = "AWS_IAM"
elif iam_authorization:
auth_type = "AWS_IAM"
elif authorizer:
auth_type = authorizer.get("type", "CUSTOM")
# build a fresh template
self.cf_template = troposphere.Template()
self.cf_template.add_description('Automatically generated with Zappa')
self.cf_api_resources = []
self.cf_parameters = {}
restapi = self.create_api_gateway_routes(
lambda_arn,
api_name=lambda_name,
api_key_required=api_key_required,
authorization_type=auth_type,
authorizer=authorizer,
cors_options=cors_options,
description=description,
endpoint_configuration=endpoint_configuration
)
return self.cf_template
def update_stack(self, name, working_bucket, wait=False, update_only=False, disable_progress=False):
"""
Update or create the CF stack managed by Zappa.
"""
capabilities = []
template = name + '-template-' + str(int(time.time())) + '.json'
with open(template, 'wb') as out:
out.write(bytes(self.cf_template.to_json(indent=None, separators=(',',':')), "utf-8"))
self.upload_to_s3(template, working_bucket, disable_progress=disable_progress)
if self.boto_session.region_name == "us-gov-west-1":
url = 'https://s3-us-gov-west-1.amazonaws.com/{0}/{1}'.format(working_bucket, template)
else:
url = 'https://s3.amazonaws.com/{0}/{1}'.format(working_bucket, template)
tags = [{'Key': key, 'Value': self.tags[key]}
for key in self.tags.keys()
if key != 'ZappaProject']
tags.append({'Key':'ZappaProject','Value':name})
update = True
try:
self.cf_client.describe_stacks(StackName=name)
except botocore.client.ClientError:
update = False
if update_only and not update:
print('CloudFormation stack missing, re-deploy to enable updates')
return
if not update:
self.cf_client.create_stack(StackName=name,
Capabilities=capabilities,
TemplateURL=url,
Tags=tags)
print('Waiting for stack {0} to create (this can take a bit)..'.format(name))
else:
try:
self.cf_client.update_stack(StackName=name,
Capabilities=capabilities,
TemplateURL=url,
Tags=tags)
print('Waiting for stack {0} to update..'.format(name))
except botocore.client.ClientError as e:
if e.response['Error']['Message'] == 'No updates are to be performed.':
wait = False
else:
raise
if wait:
total_resources = len(self.cf_template.resources)
current_resources = 0
sr = self.cf_client.get_paginator('list_stack_resources')
progress = tqdm(total=total_resources, unit='res', disable=disable_progress)
while True:
time.sleep(3)
result = self.cf_client.describe_stacks(StackName=name)
if not result['Stacks']:
continue # might need to wait a bit
if result['Stacks'][0]['StackStatus'] in ['CREATE_COMPLETE', 'UPDATE_COMPLETE']:
break
# Something has gone wrong.
# Is raising enough? Should we also remove the Lambda function?
if result['Stacks'][0]['StackStatus'] in [
'DELETE_COMPLETE',
'DELETE_IN_PROGRESS',
'ROLLBACK_IN_PROGRESS',
'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',
'UPDATE_ROLLBACK_COMPLETE'
]:
raise EnvironmentError("Stack creation failed. "
"Please check your CloudFormation console. "
"You may also need to `undeploy`.")
count = 0
for result in sr.paginate(StackName=name):
done = (1 for x in result['StackResourceSummaries']
if 'COMPLETE' in x['ResourceStatus'])
count += sum(done)
if count:
# We can end up in a situation where we have more resources being created
# than anticipated.
if (count - current_resources) > 0:
progress.update(count - current_resources)
current_resources = count
progress.close()
try:
os.remove(template)
except OSError:
pass
self.remove_from_s3(template, working_bucket)
def stack_outputs(self, name):
"""
Given a name, describes CloudFront stacks and returns dict of the stack Outputs
, else returns an empty dict.
"""
try:
stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0]
return {x['OutputKey']: x['OutputValue'] for x in stack['Outputs']}
except botocore.client.ClientError:
return {}
def get_api_url(self, lambda_name, stage_name):
"""
Given a lambda_name and stage_name, return a valid API URL.
"""
api_id = self.get_api_id(lambda_name)
if api_id:
return "https://{}.execute-api.{}.amazonaws.com/{}".format(api_id, self.boto_session.region_name, stage_name)
else:
return None
def get_api_id(self, lambda_name):
"""
Given a lambda_name, return the API id.
"""
try:
response = self.cf_client.describe_stack_resource(StackName=lambda_name,
LogicalResourceId='Api')
return response['StackResourceDetail'].get('PhysicalResourceId', None)
except: # pragma: no cover
try:
# Try the old method (project was probably made on an older, non CF version)
response = self.apigateway_client.get_rest_apis(limit=500)
for item in response['items']:
if item['name'] == lambda_name:
return item['id']
logger.exception('Could not get API ID.')
return None
except: # pragma: no cover
# We don't even have an API deployed. That's okay!
return None
def create_domain_name(self,
domain_name,
certificate_name,
certificate_body=None,
certificate_private_key=None,
certificate_chain=None,
certificate_arn=None,
lambda_name=None,
stage=None,
base_path=None):
"""
Creates the API GW domain and returns the resulting DNS name.
"""
# This is a Let's Encrypt or custom certificate
if not certificate_arn:
agw_response = self.apigateway_client.create_domain_name(
domainName=domain_name,
certificateName=certificate_name,
certificateBody=certificate_body,
certificatePrivateKey=certificate_private_key,
certificateChain=certificate_chain
)
# This is an AWS ACM-hosted Certificate
else:
agw_response = self.apigateway_client.create_domain_name(
domainName=domain_name,
certificateName=certificate_name,
certificateArn=certificate_arn
)
api_id = self.get_api_id(lambda_name)
if not api_id:
raise LookupError("No API URL to certify found - did you deploy?")
self.apigateway_client.create_base_path_mapping(
domainName=domain_name,
basePath='' if base_path is None else base_path,
restApiId=api_id,
stage=stage
)
return agw_response['distributionDomainName']
def update_route53_records(self, domain_name, dns_name):
"""
Updates Route53 Records following GW domain creation
"""
zone_id = self.get_hosted_zone_id_for_domain(domain_name)
is_apex = self.route53.get_hosted_zone(Id=zone_id)['HostedZone']['Name'][:-1] == domain_name
if is_apex:
record_set = {
'Name': domain_name,
'Type': 'A',
'AliasTarget': {
'HostedZoneId': 'Z2FDTNDATAQYW2', # This is a magic value that means "CloudFront"
'DNSName': dns_name,
'EvaluateTargetHealth': False
}
}
else:
record_set = {
'Name': domain_name,
'Type': 'CNAME',
'ResourceRecords': [
{
'Value': dns_name
}
],
'TTL': 60
}
# Related: https://github.com/boto/boto3/issues/157
# and: http://docs.aws.amazon.com/Route53/latest/APIReference/CreateAliasRRSAPI.html
# and policy: https://spin.atomicobject.com/2016/04/28/route-53-hosted-zone-managment/
# pure_zone_id = zone_id.split('/hostedzone/')[1]
# XXX: ClientError: An error occurred (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation:
# Tried to create an alias that targets d1awfeji80d0k2.cloudfront.net., type A in zone Z1XWOQP59BYF6Z,
# but the alias target name does not lie within the target zone
response = self.route53.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch={
'Changes': [
{
'Action': 'UPSERT',
'ResourceRecordSet': record_set
}
]
}
)
return response
def update_domain_name(self,
domain_name,
certificate_name=None,
certificate_body=None,
certificate_private_key=None,
certificate_chain=None,
certificate_arn=None,
lambda_name=None,
stage=None,
route53=True,
base_path=None):
"""
This updates your certificate information for an existing domain,
with similar arguments to boto's update_domain_name API Gateway api.
It returns the resulting new domain information including the new certificate's ARN
if created during this process.
Previously, this method involved downtime that could take up to 40 minutes
because the API Gateway api only allowed this by deleting, and then creating it.
Related issues: https://github.com/Miserlou/Zappa/issues/590
https://github.com/Miserlou/Zappa/issues/588
https://github.com/Miserlou/Zappa/pull/458
https://github.com/Miserlou/Zappa/issues/882
https://github.com/Miserlou/Zappa/pull/883
"""
print("Updating domain name!")
certificate_name = certificate_name + str(time.time())
api_gateway_domain = self.apigateway_client.get_domain_name(domainName=domain_name)
if not certificate_arn\
and certificate_body and certificate_private_key and certificate_chain:
acm_certificate = self.acm_client.import_certificate(Certificate=certificate_body,
PrivateKey=certificate_private_key,
CertificateChain=certificate_chain)
certificate_arn = acm_certificate['CertificateArn']
self.update_domain_base_path_mapping(domain_name, lambda_name, stage, base_path)
return self.apigateway_client.update_domain_name(domainName=domain_name,
patchOperations=[
{"op" : "replace",
"path" : "/certificateName",
"value" : certificate_name},
{"op" : "replace",
"path" : "/certificateArn",
"value" : certificate_arn}
])
def update_domain_base_path_mapping(self, domain_name, lambda_name, stage, base_path):
"""
Update domain base path mapping on API Gateway if it was changed
"""
api_id = self.get_api_id(lambda_name)
if not api_id:
print("Warning! Can't update base path mapping!")
return
base_path_mappings = self.apigateway_client.get_base_path_mappings(domainName=domain_name)
found = False
for base_path_mapping in base_path_mappings.get('items', []):
if base_path_mapping['restApiId'] == api_id and base_path_mapping['stage'] == stage:
found = True
if base_path_mapping['basePath'] != base_path:
self.apigateway_client.update_base_path_mapping(domainName=domain_name,
basePath=base_path_mapping['basePath'],
patchOperations=[
{"op" : "replace",
"path" : "/basePath",
"value" : '' if base_path is None else base_path}
])
if not found:
self.apigateway_client.create_base_path_mapping(
domainName=domain_name,
basePath='' if base_path is None else base_path,
restApiId=api_id,
stage=stage
)
def get_all_zones(self):
"""Same behaviour of list_host_zones, but transparently handling pagination."""
zones = {'HostedZones': []}
new_zones = self.route53.list_hosted_zones(MaxItems='100')
while new_zones['IsTruncated']:
zones['HostedZones'] += new_zones['HostedZones']
new_zones = self.route53.list_hosted_zones(Marker=new_zones['NextMarker'], MaxItems='100')
zones['HostedZones'] += new_zones['HostedZones']
return zones
def get_domain_name(self, domain_name, route53=True):
"""
Scan our hosted zones for the record of a given name.
Returns the record entry, else None.
"""
# Make sure api gateway domain is present
try:
self.apigateway_client.get_domain_name(domainName=domain_name)
except Exception:
return None
if not route53:
return True
try:
zones = self.get_all_zones()
for zone in zones['HostedZones']:
records = self.route53.list_resource_record_sets(HostedZoneId=zone['Id'])
for record in records['ResourceRecordSets']:
if record['Type'] in ('CNAME', 'A') and record['Name'][:-1] == domain_name:
return record
except Exception as e:
return None
##
# Old, automatic logic.
# If re-introduced, should be moved to a new function.
# Related ticket: https://github.com/Miserlou/Zappa/pull/458
##
# We may be in a position where Route53 doesn't have a domain, but the API Gateway does.
# We need to delete this before we can create the new Route53.
# try:
# api_gateway_domain = self.apigateway_client.get_domain_name(domainName=domain_name)
# self.apigateway_client.delete_domain_name(domainName=domain_name)
# except Exception:
# pass
return None
##
# IAM
##
def get_credentials_arn(self):
"""
Given our role name, get and set the credentials_arn.
"""
role = self.iam.Role(self.role_name)
self.credentials_arn = role.arn
return role, self.credentials_arn
def create_iam_roles(self):
"""
Create and defines the IAM roles and policies necessary for Zappa.
If the IAM role already exists, it will be updated if necessary.
"""
attach_policy_obj = json.loads(self.attach_policy)
assume_policy_obj = json.loads(self.assume_policy)
if self.extra_permissions:
for permission in self.extra_permissions:
attach_policy_obj['Statement'].append(dict(permission))
self.attach_policy = json.dumps(attach_policy_obj)
updated = False
# Create the role if needed
try:
role, credentials_arn = self.get_credentials_arn()
except botocore.client.ClientError:
print("Creating " + self.role_name + " IAM Role..")
role = self.iam.create_role(
RoleName=self.role_name,
AssumeRolePolicyDocument=self.assume_policy
)
self.credentials_arn = role.arn
updated = True
# create or update the role's policies if needed
policy = self.iam.RolePolicy(self.role_name, 'zappa-permissions')
try:
if policy.policy_document != attach_policy_obj:
print("Updating zappa-permissions policy on " + self.role_name + " IAM Role.")
policy.put(PolicyDocument=self.attach_policy)
updated = True
except botocore.client.ClientError:
print("Creating zappa-permissions policy on " + self.role_name + " IAM Role.")
policy.put(PolicyDocument=self.attach_policy)
updated = True
if role.assume_role_policy_document != assume_policy_obj and \
set(role.assume_role_policy_document['Statement'][0]['Principal']['Service']) != set(assume_policy_obj['Statement'][0]['Principal']['Service']):
print("Updating assume role policy on " + self.role_name + " IAM Role.")
self.iam_client.update_assume_role_policy(
RoleName=self.role_name,
PolicyDocument=self.assume_policy
)
updated = True
return self.credentials_arn, updated
def _clear_policy(self, lambda_name):
"""
Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates.
"""
try:
policy_response = self.lambda_client.get_policy(
FunctionName=lambda_name
)
if policy_response['ResponseMetadata']['HTTPStatusCode'] == 200:
statement = json.loads(policy_response['Policy'])['Statement']
for s in statement:
delete_response = self.lambda_client.remove_permission(
FunctionName=lambda_name,
StatementId=s['Sid']
)
if delete_response['ResponseMetadata']['HTTPStatusCode'] != 204:
logger.error('Failed to delete an obsolete policy statement: {}'.format(policy_response))
else:
logger.debug('Failed to load Lambda function policy: {}'.format(policy_response))
except ClientError as e:
if e.args[0].find('ResourceNotFoundException') > -1:
logger.debug('No policy found, must be first run.')
else:
logger.error('Unexpected client error {}'.format(e.args[0]))
##
# CloudWatch Events
##
def create_event_permission(self, lambda_name, principal, source_arn):
"""
Create permissions to link to an event.
Related: http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-configure-event-source.html
"""
logger.debug('Adding new permission to invoke Lambda function: {}'.format(lambda_name))
permission_response = self.lambda_client.add_permission(
FunctionName=lambda_name,
StatementId=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)),
Action='lambda:InvokeFunction',
Principal=principal,
SourceArn=source_arn,
)
if permission_response['ResponseMetadata']['HTTPStatusCode'] != 201:
print('Problem creating permission to invoke Lambda function')
return None # XXX: Raise?
return permission_response
def schedule_events(self, lambda_arn, lambda_name, events, default=True):
"""
Given a Lambda ARN, name and a list of events, schedule this as CloudWatch Events.
'events' is a list of dictionaries, where the dict must contains the string
of a 'function' and the string of the event 'expression', and an optional 'name' and 'description'.
Expressions can be in rate or cron format:
http://docs.aws.amazon.com/lambda/latest/dg/tutorial-scheduled-events-schedule-expressions.html
"""
# The stream sources - DynamoDB, Kinesis and SQS - are working differently than the other services (pull vs push)
# and do not require event permissions. They do require additional permissions on the Lambda roles though.
# http://docs.aws.amazon.com/lambda/latest/dg/lambda-api-permissions-ref.html
pull_services = ['dynamodb', 'kinesis', 'sqs']
# XXX: Not available in Lambda yet.
# We probably want to execute the latest code.
# if default:
# lambda_arn = lambda_arn + ":$LATEST"
self.unschedule_events(lambda_name=lambda_name, lambda_arn=lambda_arn, events=events,
excluded_source_services=pull_services)
for event in events:
function = event['function']
expression = event.get('expression', None) # single expression
expressions = event.get('expressions', None) # multiple expression
kwargs = event.get('kwargs', {}) # optional dict of keyword arguments for the event
event_source = event.get('event_source', None)
description = event.get('description', function)
# - If 'cron' or 'rate' in expression, use ScheduleExpression
# - Else, use EventPattern
# - ex https://github.com/awslabs/aws-lambda-ddns-function
if not self.credentials_arn:
self.get_credentials_arn()
if expression:
expressions = [expression] # same code for single and multiple expression
if expressions:
for index, expression in enumerate(expressions):
name = self.get_scheduled_event_name(event, function, lambda_name, index)
# if it's possible that we truncated name, generate a unique, shortened name
# https://github.com/Miserlou/Zappa/issues/970
if len(name) >= 64:
rule_name = self.get_hashed_rule_name(event, function, lambda_name)
else:
rule_name = name
rule_response = self.events_client.put_rule(
Name=rule_name,
ScheduleExpression=expression,
State='ENABLED',
Description=description,
RoleArn=self.credentials_arn
)
if 'RuleArn' in rule_response:
logger.debug('Rule created. ARN {}'.format(rule_response['RuleArn']))
# Specific permissions are necessary for any trigger to work.
self.create_event_permission(lambda_name, 'events.amazonaws.com', rule_response['RuleArn'])
# Overwriting the input, supply the original values and add kwargs
input_template = '{"time": <time>, ' \
'"detail-type": <detail-type>, ' \
'"source": <source>,' \
'"account": <account>, ' \
'"region": <region>,' \
'"detail": <detail>, ' \
'"version": <version>,' \
'"resources": <resources>,' \
'"id": <id>,' \
'"kwargs": %s' \
'}' % json.dumps(kwargs)
# Create the CloudWatch event ARN for this function.
# https://github.com/Miserlou/Zappa/issues/359
target_response = self.events_client.put_targets(
Rule=rule_name,
Targets=[
{
'Id': 'Id' + ''.join(random.choice(string.digits) for _ in range(12)),
'Arn': lambda_arn,
'InputTransformer': {
'InputPathsMap': {
'time': '$.time',
'detail-type': '$.detail-type',
'source': '$.source',
'account': '$.account',
'region': '$.region',
'detail': '$.detail',
'version': '$.version',
'resources': '$.resources',
'id': '$.id'
},
'InputTemplate': input_template
}
}
]
)
if target_response['ResponseMetadata']['HTTPStatusCode'] == 200:
print("Scheduled {} with expression {}!".format(rule_name, expression))
else:
print("Problem scheduling {} with expression {}.".format(rule_name, expression))
elif event_source:
service = self.service_from_arn(event_source['arn'])
if service not in pull_services:
svc = ','.join(event['event_source']['events'])
self.create_event_permission(
lambda_name,
service + '.amazonaws.com',
event['event_source']['arn']
)
else:
svc = service
rule_response = add_event_source(
event_source,
lambda_arn,
function,
self.boto_session
)
if rule_response == 'successful':
print("Created {} event schedule for {}!".format(svc, function))
elif rule_response == 'failed':
print("Problem creating {} event schedule for {}!".format(svc, function))
elif rule_response == 'exists':
print("{} event schedule for {} already exists - Nothing to do here.".format(svc, function))
elif rule_response == 'dryrun':
print("Dryrun for creating {} event schedule for {}!!".format(svc, function))
else:
print("Could not create event {} - Please define either an expression or an event source".format(name))
@staticmethod
def get_scheduled_event_name(event, function, lambda_name, index=0):
name = event.get('name', function)
if name != function:
# a custom event name has been provided, make sure function name is included as postfix,
# otherwise zappa's handler won't be able to locate the function.
name = '{}-{}'.format(name, function)
if index:
# to ensure unique cloudwatch rule names in the case of multiple expressions
# prefix all entries bar the first with the index
# Related: https://github.com/Miserlou/Zappa/pull/1051
name = '{}-{}'.format(index, name)
# prefix scheduled event names with lambda name. So we can look them up later via the prefix.
return Zappa.get_event_name(lambda_name, name)
@staticmethod
def get_event_name(lambda_name, name):
"""
Returns an AWS-valid Lambda event name.
"""
return '{prefix:.{width}}-{postfix}'.format(prefix=lambda_name, width=max(0, 63 - len(name)), postfix=name)[:64]
@staticmethod
def get_hashed_rule_name(event, function, lambda_name):
"""
Returns an AWS-valid CloudWatch rule name using a digest of the event name, lambda name, and function.
This allows support for rule names that may be longer than the 64 char limit.
"""
event_name = event.get('name', function)
name_hash = hashlib.sha1('{}-{}'.format(lambda_name, event_name).encode('UTF-8')).hexdigest()
return Zappa.get_event_name(name_hash, function)
def delete_rule(self, rule_name):
"""
Delete a CWE rule.
This deletes them, but they will still show up in the AWS console.
Annoying.
"""
logger.debug('Deleting existing rule {}'.format(rule_name))
# All targets must be removed before
# we can actually delete the rule.
try:
targets = self.events_client.list_targets_by_rule(Rule=rule_name)
except botocore.exceptions.ClientError as e:
# This avoids misbehavior if low permissions, related: https://github.com/Miserlou/Zappa/issues/286
error_code = e.response['Error']['Code']
if error_code == 'AccessDeniedException':
raise
else:
logger.debug('No target found for this rule: {} {}'.format(rule_name, e.args[0]))
return
if 'Targets' in targets and targets['Targets']:
self.events_client.remove_targets(Rule=rule_name, Ids=[x['Id'] for x in targets['Targets']])
else: # pragma: no cover
logger.debug('No target to delete')
# Delete our rule.
self.events_client.delete_rule(Name=rule_name)
def get_event_rule_names_for_lambda(self, lambda_arn):
"""
Get all of the rule names associated with a lambda function.
"""
response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn)
rule_names = response['RuleNames']
# Iterate when the results are paginated
while 'NextToken' in response:
response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn,
NextToken=response['NextToken'])
rule_names.extend(response['RuleNames'])
return rule_names
def get_event_rules_for_lambda(self, lambda_arn):
"""
Get all of the rule details associated with this function.
"""
rule_names = self.get_event_rule_names_for_lambda(lambda_arn=lambda_arn)
return [self.events_client.describe_rule(Name=r) for r in rule_names]
def unschedule_events(self, events, lambda_arn=None, lambda_name=None, excluded_source_services=None):
excluded_source_services = excluded_source_services or []
"""
Given a list of events, unschedule these CloudWatch Events.
'events' is a list of dictionaries, where the dict must contains the string
of a 'function' and the string of the event 'expression', and an optional 'name' and 'description'.
"""
self._clear_policy(lambda_name)
rule_names = self.get_event_rule_names_for_lambda(lambda_arn=lambda_arn)
for rule_name in rule_names:
self.delete_rule(rule_name)
print('Unscheduled ' + rule_name + '.')
non_cwe = [e for e in events if 'event_source' in e]
for event in non_cwe:
# TODO: This WILL miss non CW events that have been deployed but changed names. Figure out a way to remove
# them no matter what.
# These are non CWE event sources.
function = event['function']
name = event.get('name', function)
event_source = event.get('event_source', function)
service = self.service_from_arn(event_source['arn'])
# DynamoDB and Kinesis streams take quite a while to setup after they are created and do not need to be
# re-scheduled when a new Lambda function is deployed. Therefore, they should not be removed during zappa
# update or zappa schedule.
if service not in excluded_source_services:
remove_event_source(
event_source,
lambda_arn,
function,
self.boto_session
)
print("Removed event {}{}.".format(
name,
" ({})".format(str(event_source['events'])) if 'events' in event_source else '')
)
###
# Async / SNS
##
def create_async_sns_topic(self, lambda_name, lambda_arn):
"""
Create the SNS-based async topic.
"""
topic_name = get_topic_name(lambda_name)
# Create SNS topic
topic_arn = self.sns_client.create_topic(
Name=topic_name)['TopicArn']
# Create subscription
self.sns_client.subscribe(
TopicArn=topic_arn,
Protocol='lambda',
Endpoint=lambda_arn
)
# Add Lambda permission for SNS to invoke function
self.create_event_permission(
lambda_name=lambda_name,
principal='sns.amazonaws.com',
source_arn=topic_arn
)
# Add rule for SNS topic as a event source
add_event_source(
event_source={
"arn": topic_arn,
"events": ["sns:Publish"]
},
lambda_arn=lambda_arn,
target_function="zappa.asynchronous.route_task",
boto_session=self.boto_session
)
return topic_arn
def remove_async_sns_topic(self, lambda_name):
"""
Remove the async SNS topic.
"""
topic_name = get_topic_name(lambda_name)
removed_arns = []
for sub in self.sns_client.list_subscriptions()['Subscriptions']:
if topic_name in sub['TopicArn']:
self.sns_client.delete_topic(TopicArn=sub['TopicArn'])
removed_arns.append(sub['TopicArn'])
return removed_arns
###
# Async / DynamoDB
##
def _set_async_dynamodb_table_ttl(self, table_name):
self.dynamodb_client.update_time_to_live(
TableName=table_name,
TimeToLiveSpecification={
'Enabled': True,
'AttributeName': 'ttl'
}
)
def create_async_dynamodb_table(self, table_name, read_capacity, write_capacity):
"""
Create the DynamoDB table for async task return values
"""
try:
dynamodb_table = self.dynamodb_client.describe_table(TableName=table_name)
return False, dynamodb_table
# catch this exception (triggered if the table doesn't exist)
except botocore.exceptions.ClientError:
dynamodb_table = self.dynamodb_client.create_table(
AttributeDefinitions=[
{
'AttributeName': 'id',
'AttributeType': 'S'
}
],
TableName=table_name,
KeySchema=[
{
'AttributeName': 'id',
'KeyType': 'HASH'
},
],
ProvisionedThroughput = {
'ReadCapacityUnits': read_capacity,
'WriteCapacityUnits': write_capacity
}
)
if dynamodb_table:
try:
self._set_async_dynamodb_table_ttl(table_name)
except botocore.exceptions.ClientError:
# this fails because the operation is async, so retry
time.sleep(10)
self._set_async_dynamodb_table_ttl(table_name)
return True, dynamodb_table
def remove_async_dynamodb_table(self, table_name):
"""
Remove the DynamoDB Table used for async return values
"""
self.dynamodb_client.delete_table(TableName=table_name)
##
# CloudWatch Logging
##
def fetch_logs(self, lambda_name, filter_pattern='', limit=10000, start_time=0):
"""
Fetch the CloudWatch logs for a given Lambda name.
"""
log_name = '/aws/lambda/' + lambda_name
streams = self.logs_client.describe_log_streams(
logGroupName=log_name,
descending=True,
orderBy='LastEventTime'
)
all_streams = streams['logStreams']
all_names = [stream['logStreamName'] for stream in all_streams]
events = []
response = {}
while not response or 'nextToken' in response:
extra_args = {}
if 'nextToken' in response:
extra_args['nextToken'] = response['nextToken']
# Amazon uses millisecond epoch for some reason.
# Thanks, Jeff.
start_time = start_time * 1000
end_time = int(time.time()) * 1000
response = self.logs_client.filter_log_events(
logGroupName=log_name,
logStreamNames=all_names,
startTime=start_time,
endTime=end_time,
filterPattern=filter_pattern,
limit=limit,
interleaved=True, # Does this actually improve performance?
**extra_args
)
if response and 'events' in response:
events += response['events']
return sorted(events, key=lambda k: k['timestamp'])
def remove_log_group(self, group_name):
"""
Filter all log groups that match the name given in log_filter.
"""
print("Removing log group: {}".format(group_name))
try:
self.logs_client.delete_log_group(logGroupName=group_name)
except botocore.exceptions.ClientError as e:
print("Couldn't remove '{}' because of: {}".format(group_name, e))
def remove_lambda_function_logs(self, lambda_function_name):
"""
Remove all logs that are assigned to a given lambda function id.
"""
self.remove_log_group('/aws/lambda/{}'.format(lambda_function_name))
def remove_api_gateway_logs(self, project_name):
"""
Removed all logs that are assigned to a given rest api id.
"""
for rest_api in self.get_rest_apis(project_name):
for stage in self.apigateway_client.get_stages(restApiId=rest_api['id'])['item']:
self.remove_log_group('API-Gateway-Execution-Logs_{}/{}'.format(rest_api['id'], stage['stageName']))
##
# Route53 Domain Name Entries
##
def get_hosted_zone_id_for_domain(self, domain):
"""
Get the Hosted Zone ID for a given domain.
"""
all_zones = self.get_all_zones()
return self.get_best_match_zone(all_zones, domain)
@staticmethod
def get_best_match_zone(all_zones, domain):
"""Return zone id which name is closer matched with domain name."""
# Related: https://github.com/Miserlou/Zappa/issues/459
public_zones = [zone for zone in all_zones['HostedZones'] if not zone['Config']['PrivateZone']]
zones = {zone['Name'][:-1]: zone['Id'] for zone in public_zones if zone['Name'][:-1] in domain}
if zones:
keys = max(zones.keys(), key=lambda a: len(a)) # get longest key -- best match.
return zones[keys]
else:
return None
def set_dns_challenge_txt(self, zone_id, domain, txt_challenge):
"""
Set DNS challenge TXT.
"""
print("Setting DNS challenge..")
resp = self.route53.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch=self.get_dns_challenge_change_batch('UPSERT', domain, txt_challenge)
)
return resp
def remove_dns_challenge_txt(self, zone_id, domain, txt_challenge):
"""
Remove DNS challenge TXT.
"""
print("Deleting DNS challenge..")
resp = self.route53.change_resource_record_sets(
HostedZoneId=zone_id,
ChangeBatch=self.get_dns_challenge_change_batch('DELETE', domain, txt_challenge)
)
return resp
@staticmethod
def get_dns_challenge_change_batch(action, domain, txt_challenge):
"""
Given action, domain and challenge, return a change batch to use with
route53 call.
:param action: DELETE | UPSERT
:param domain: domain name
:param txt_challenge: challenge
:return: change set for a given action, domain and TXT challenge.
"""
return {
'Changes': [{
'Action': action,
'ResourceRecordSet': {
'Name': '_acme-challenge.{0}'.format(domain),
'Type': 'TXT',
'TTL': 60,
'ResourceRecords': [{
'Value': '"{0}"'.format(txt_challenge)
}]
}
}]
}
##
# Utility
##
def shell(self):
"""
Spawn a PDB shell.
"""
import pdb
pdb.set_trace()
def load_credentials(self, boto_session=None, profile_name=None):
"""
Load AWS credentials.
An optional boto_session can be provided, but that's usually for testing.
An optional profile_name can be provided for config files that have multiple sets
of credentials.
"""
# Automatically load credentials from config or environment
if not boto_session:
# If provided, use the supplied profile name.
if profile_name:
self.boto_session = boto3.Session(profile_name=profile_name, region_name=self.aws_region)
elif os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):
region_name = os.environ.get('AWS_DEFAULT_REGION') or self.aws_region
session_kw = {
"aws_access_key_id": os.environ.get('AWS_ACCESS_KEY_ID'),
"aws_secret_access_key": os.environ.get('AWS_SECRET_ACCESS_KEY'),
"region_name": region_name,
}
# If we're executing in a role, AWS_SESSION_TOKEN will be present, too.
if os.environ.get("AWS_SESSION_TOKEN"):
session_kw["aws_session_token"] = os.environ.get("AWS_SESSION_TOKEN")
self.boto_session = boto3.Session(**session_kw)
else:
self.boto_session = boto3.Session(region_name=self.aws_region)
logger.debug("Loaded boto session from config: %s", boto_session)
else:
logger.debug("Using provided boto session: %s", boto_session)
self.boto_session = boto_session
# use provided session's region in case it differs
self.aws_region = self.boto_session.region_name
if self.boto_session.region_name not in LAMBDA_REGIONS:
print("Warning! AWS Lambda may not be available in this AWS Region!")
if self.boto_session.region_name not in API_GATEWAY_REGIONS:
print("Warning! AWS API Gateway may not be available in this AWS Region!")
@staticmethod
def service_from_arn(arn):
return arn.split(':')[2]
|
const express = require("express");
const logger = require("morgan");
const mongoose = require("mongoose");
const path = require("path");
const compression = require("compression");
const PORT = process.env.PORT || 3000
const db = require("./models");
const app = express();
app.use(logger("dev"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static("public"));
app.use(compression());
mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost/workout", {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
});
// routes
// app.use(require("./routes/routes.js")(app));
app.get("/", (req, res) => res.sendFile(path.join(__dirname, '/public', "index.html")));
app.get("/exercise", (req, res) => res.sendFile(path.join(__dirname, '/public', "exercise.html")));
app.get("/stats", (req, res) => res.sendFile(path.join(__dirname, '/public', "stats.html")));
app.get("/api/workouts", (req, res) => {
db.Workout.aggregate([
{
$addFields: {
totalDuration: {
$sum: '$exercises.duration'
}
}
}
])
.then(data => {
console.log(data);
res.send(data);
})
.catch(err => {
res.send(err);
});
});
app.put('/api/workouts/:id', (req, res) => {
db.Workout.updateOne(
{
_id: req.params.id
},
{
$push: { exercises: req.body }
})
.then(data => {
res.send(data);
})
.catch(err => {
console.log(err)
});
});
app.post('/api/workouts', (req, res) => {
console.log(req.body);
db.Workout.create({})
.then(data => {
res.send(data);
})
.catch(err => {
console.log(err)
});
});
app.get('/api/workouts/range', (req, res) => {
db.Workout.aggregate([
{
$addFields: {
totalDuration: {
$sum: '$exercises.duration'
}
}
}
])
.then(data => {
console.log(data);
res.send(data);
})
.catch(err => {
res.send(err);
});
});
app.listen(PORT, () => {
console.log(`App running on port ${PORT}!`);
});
|
const WebSocketClient = require('websocket').client;
const { SOCKET_MSG_MAX_SIZE } = require('./config');
const logger = require('./utils/logger');
const { parseFiles, openFileInEditor } = require('./api/');
const { SOCKET_MESSAGE_TYPE } = require('../shared/constants');
const projectSourceWatcher = require('./project-source/');
const { detectLanguage } = require('./code-parse/language');
const run = (
{ mediatorEndPoint, namespace, projectName },
{ projectDir, entryPoint, webpackConfigPath, excludeDir }
) => {
const { language, extensions: fileExtensions } = detectLanguage(entryPoint);
const webSocketClient = new WebSocketClient({
maxReceivedFrameSize: SOCKET_MSG_MAX_SIZE,
maxReceivedMessageSize: SOCKET_MSG_MAX_SIZE
});
webSocketClient.on('connectFailed', error => {
logger.error(`Connect error for ${namespace}, error: ${error} `);
});
webSocketClient.on('connect', connection => {
logger.info(
`+ started: source watcher: ${namespace} for: ${projectName}; `,
`setup: dir - ${projectDir}, entry point - ${entryPoint}`
);
connection.on('message', ({ utf8Data }) => {
const message = JSON.parse(utf8Data);
switch (message.type) {
case SOCKET_MESSAGE_TYPE.CLIENT_CONNECTED:
projectSourceWatcher.subscribeOnChange(
namespace,
{
projectName,
projectDir,
entryPoint,
excludeDir,
webpackConfigPath,
language,
fileExtensions
},
{
onInit: data => {
logger.info(`> emit '${SOCKET_MESSAGE_TYPE.SOURCE_INIT_SOURCE_FILES_SYNC}'`);
connection.sendUTF(
JSON.stringify({
type: SOCKET_MESSAGE_TYPE.SOURCE_INIT_SOURCE_FILES_SYNC,
namespace,
data
})
);
},
onChange: data =>
connection.sendUTF(
JSON.stringify({
type: SOCKET_MESSAGE_TYPE.SOURCE_UPDATE_SOURCE_FILE_SYNC,
namespace,
data
})
)
}
);
break;
case SOCKET_MESSAGE_TYPE.CLIENT_REQUEST_FETCH_FILE:
if (message.namespace === namespace) {
parseFiles(message.data, projectDir, language).then(files =>
connection.sendUTF(
JSON.stringify({
type: SOCKET_MESSAGE_TYPE.SOURCE_RESPONSE_FETCH_FILE,
namespace,
data: { files }
})
)
);
}
break;
case SOCKET_MESSAGE_TYPE.CLIENT_OPEN_FILE_IN_EDITOR:
if (message.namespace === namespace) {
openFileInEditor(message.data);
}
break;
default:
logger.warn(`Unhandled message: ${message}`);
}
});
});
webSocketClient.connect(`ws://${mediatorEndPoint}/`);
};
module.exports = {
run
};
|
import os
import dbs_fields
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-bootstrap-fields',
version=dbs_fields.__version__,
packages=find_packages(),
include_package_data=True,
license='MIT',
description="render Django form fields with complete Bootstrap HTML markup",
long_description_content_type='text/markdown',
long_description=README,
url='https://github.com/mtokoly/django-bootstrap-fields',
author='Matthew Tokoly',
author_email='tokoly@gmail.com',
classifiers=[
"Environment :: Web Environment",
"Framework :: Django",
"License :: OSI Approved :: MIT License",
"Programming Language :: JavaScript",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords=['fields', 'forms', 'bootstrap', 'django'],
)
|
import PropTypes from 'prop-types';
import { googleMapsKey } from '../../../etc/config.json';
const InitMap = (mountPoint, options) => {
const loadJS = function (src) {
const ref = window.document.getElementsByTagName("script")[0];
const script = window.document.createElement("script");
script.src = src;
script.id = 'googleMap';
script.async = true;
ref.parentNode.insertBefore(script, ref);
};
const checkLoadedMapScriptBefore = () => {
if (document.getElementById('googleMap') === null) {
return false;
}
return true;
};
if (!checkLoadedMapScriptBefore()) {
loadJS(`https://maps.googleapis.com/maps/api/js?key=${googleMapsKey}&libraries=drawing`);
}
const promise = new Promise((resolve, reject) => {
const timerId = setInterval(() => {
if (window.google !== undefined) {
clearInterval(timerId);
const google = window.google;
const map = new google.maps.Map(mountPoint, options);
resolve(map);
}
}, 100);
});
return promise;
};
InitMap.propTypes = {
mountPoint: PropTypes.node.isRequired,
options: PropTypes.object.isRequired,
};
export default InitMap;
|
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet keypool and interaction with wallet encryption/locking."""
from test_framework.test_framework import TradeTensorTestFramework
from test_framework.util import *
class KeyPoolTest(TradeTensorTestFramework):
def set_test_params(self):
self.num_nodes = 1
def run_test(self):
nodes = self.nodes
addr_before_encrypting = nodes[0].getnewaddress()
addr_before_encrypting_data = nodes[0].validateaddress(addr_before_encrypting)
# Encrypt wallet and wait to terminate
nodes[0].node_encrypt_wallet('test')
# Restart node 0
self.start_node(0)
# Keep creating keys
addr = nodes[0].getnewaddress()
addr_data = nodes[0].validateaddress(addr)
assert_raises_rpc_error(-12, "Keypool ran out, please call keypoolrefill first, or unlock the wallet.",
nodes[0].getnewaddress)
# put six (plus 2) new keys in the keypool (100% external-, +100% internal-keys, 1 in min)
nodes[0].walletpassphrase('test', 12000)
nodes[0].keypoolrefill(6)
nodes[0].walletlock()
wi = nodes[0].getwalletinfo()
assert_equal(wi['keypoolsize'], 7)
# drain the internal keys
nodes[0].getrawchangeaddress()
nodes[0].getrawchangeaddress()
nodes[0].getrawchangeaddress()
nodes[0].getrawchangeaddress()
nodes[0].getrawchangeaddress()
nodes[0].getrawchangeaddress()
nodes[0].getrawchangeaddress()
addr = set()
# the next one should fail
assert_raises_rpc_error(-12, "Keypool ran out", nodes[0].getrawchangeaddress)
# drain the external keys
#addr.add(nodes[0].getnewaddress())
#addr.add(nodes[0].getnewaddress())
#addr.add(nodes[0].getnewaddress())
#addr.add(nodes[0].getnewaddress())
#addr.add(nodes[0].getnewaddress())
#addr.add(nodes[0].getnewaddress())
#addr.add(nodes[0].getnewaddress())
#assert(len(addr) == 7)
# the next one should fail
#assert_raises_rpc_error(-12, "Error: Keypool ran out, please call keypoolrefill first", nodes[0].getnewaddress)
# refill keypool with three new addresses
nodes[0].walletpassphrase('test', 1)
nodes[0].keypoolrefill(3)
# test walletpassphrase timeout
time.sleep(1.1)
assert_equal(nodes[0].getwalletinfo()["unlocked_until"], 0)
# drain them by mining
#nodes[0].generate(1)
#nodes[0].generate(1)
#nodes[0].generate(1)
#assert_raises_rpc_error(-12, "Keypool ran out", nodes[0].generate, 1)
nodes[0].walletpassphrase('test', 100)
nodes[0].keypoolrefill(100)
wi = nodes[0].getwalletinfo()
assert_equal(wi['keypoolsize'], 101)
if __name__ == '__main__':
KeyPoolTest().main()
|
//https://github.com/exupero/saveSvgAsPng
//see also here: https://spin.atomicobject.com/2014/01/21/convert-svg-to-png/
(function() {
const out$ = typeof exports != 'undefined' && exports || typeof define != 'undefined' && {} || this || window;
if (typeof define !== 'undefined') define('save-svg-as-png', [], () => out$);
out$.default = out$;
const xmlNs = 'http://www.w3.org/2000/xmlns/';
const xhtmlNs = 'http://www.w3.org/1999/xhtml';
const svgNs = 'http://www.w3.org/2000/svg';
const doctype = '<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [<!ENTITY nbsp " ">]>';
const urlRegex = /url\(["']?(.+?)["']?\)/;
const fontFormats = {
woff2: 'font/woff2',
woff: 'font/woff',
otf: 'application/x-font-opentype',
ttf: 'application/x-font-ttf',
eot: 'application/vnd.ms-fontobject',
sfnt: 'application/font-sfnt',
svg: 'image/svg+xml'
};
const isElement = obj => obj instanceof HTMLElement || obj instanceof SVGElement;
const requireDomNode = el => {
if (!isElement(el)) throw new Error(`an HTMLElement or SVGElement is required; got ${el}`);
};
const requireDomNodePromise = el =>
new Promise((resolve, reject) => {
if (isElement(el)) resolve(el)
else reject(new Error(`an HTMLElement or SVGElement is required; got ${el}`));
})
const isExternal = url => url && url.lastIndexOf('http',0) === 0 && url.lastIndexOf(window.location.host) === -1;
const getFontMimeTypeFromUrl = fontUrl => {
const formats = Object.keys(fontFormats)
.filter(extension => fontUrl.indexOf(`.${extension}`) > 0)
.map(extension => fontFormats[extension]);
if (formats) return formats[0];
console.error(`Unknown font format for ${fontUrl}. Fonts may not be working correctly.`);
return 'application/octet-stream';
};
const arrayBufferToBase64 = buffer => {
let binary = '';
const bytes = new Uint8Array(buffer);
for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
return window.btoa(binary);
}
const getDimension = (el, clone, dim) => {
const v =
(el.viewBox && el.viewBox.baseVal && el.viewBox.baseVal[dim]) ||
(clone.getAttribute(dim) !== null && !clone.getAttribute(dim).match(/%$/) && parseInt(clone.getAttribute(dim))) ||
el.getBoundingClientRect()[dim] ||
parseInt(clone.style[dim]) ||
parseInt(window.getComputedStyle(el).getPropertyValue(dim));
return typeof v === 'undefined' || v === null || isNaN(parseFloat(v)) ? 0 : v;
};
const getDimensions = (el, clone, width, height) => {
if (el.tagName === 'svg') return {
width: width || getDimension(el, clone, 'width'),
height: height || getDimension(el, clone, 'height')
};
else if (el.getBBox) {
const {x, y, width, height} = el.getBBox();
return {
width: x + width,
height: y + height
};
}
};
const reEncode = data =>
decodeURIComponent(
encodeURIComponent(data)
.replace(/%([0-9A-F]{2})/g, (match, p1) => {
const c = String.fromCharCode(`0x${p1}`);
return c === '%' ? '%25' : c;
})
);
const uriToBlob = uri => {
const byteString = window.atob(uri.split(',')[1]);
const mimeString = uri.split(',')[0].split(':')[1].split(';')[0]
const buffer = new ArrayBuffer(byteString.length);
const intArray = new Uint8Array(buffer);
for (let i = 0; i < byteString.length; i++) {
intArray[i] = byteString.charCodeAt(i);
}
return new Blob([buffer], {type: mimeString});
};
const query = (el, selector) => {
if (!selector) return;
try {
return el.querySelector(selector) || el.parentNode && el.parentNode.querySelector(selector);
} catch(err) {
console.warn(`Invalid CSS selector "${selector}"`, err);
}
};
const detectCssFont = (rule, href) => {
// Match CSS font-face rules to external links.
// @font-face {
// src: local('Abel'), url(https://fonts.gstatic.com/s/abel/v6/UzN-iejR1VoXU2Oc-7LsbvesZW2xOQ-xsNqO47m55DA.woff2);
// }
const match = rule.cssText.match(urlRegex);
const url = (match && match[1]) || '';
if (!url || url.match(/^data:/) || url === 'about:blank') return;
const fullUrl =
url.startsWith('../') ? `${href}/../${url}`
: url.startsWith('./') ? `${href}/.${url}`
: url;
return {
text: rule.cssText,
format: getFontMimeTypeFromUrl(fullUrl),
url: fullUrl
};
};
const inlineImages = el => Promise.all(
Array.from(el.querySelectorAll('image')).map(image => {
let href = image.getAttributeNS('http://www.w3.org/1999/xlink', 'href') || image.getAttribute('href');
if (!href) return Promise.resolve(null);
if (isExternal(href)) {
href += (href.indexOf('?') === -1 ? '?' : '&') + 't=' + new Date().valueOf();
}
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
const img = new Image();
img.crossOrigin = 'anonymous';
img.src = href;
img.onerror = () => reject(new Error(`Could not load ${href}`));
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0);
image.setAttributeNS('http://www.w3.org/1999/xlink', 'href', canvas.toDataURL('image/png'));
resolve(true);
};
});
})
);
const cachedFonts = {};
const inlineFonts = fonts => Promise.all(
fonts.map(font =>
new Promise((resolve, reject) => {
if (cachedFonts[font.url]) return resolve(cachedFonts[font.url]);
const req = new XMLHttpRequest();
req.addEventListener('load', () => {
// TODO: it may also be worth it to wait until fonts are fully loaded before
// attempting to rasterize them. (e.g. use https://developer.mozilla.org/en-US/docs/Web/API/FontFaceSet)
const fontInBase64 = arrayBufferToBase64(req.response);
const fontUri = font.text.replace(urlRegex, `url("data:${font.format};base64,${fontInBase64}")`)+'\n';
cachedFonts[font.url] = fontUri;
resolve(fontUri);
});
req.addEventListener('error', e => {
console.warn(`Failed to load font from: ${font.url}`, e);
cachedFonts[font.url] = null;
resolve(null);
});
req.addEventListener('abort', e => {
console.warn(`Aborted loading font from: ${font.url}`, e);
resolve(null);
});
req.open('GET', font.url);
req.responseType = 'arraybuffer';
req.send();
})
)
).then(fontCss => fontCss.filter(x => x).join(''));
let cachedRules = null;
const styleSheetRules = () => {
if (cachedRules) return cachedRules;
return cachedRules = Array.from(document.styleSheets).map(sheet => {
try {
return {rules: sheet.cssRules, href: sheet.href};
} catch (e) {
console.warn(`Stylesheet could not be loaded: ${sheet.href}`, e);
return {};
}
});
};
const inlineCss = (el, options) => {
const {
selectorRemap,
modifyStyle,
modifyCss,
fonts,
excludeUnusedCss
} = options || {};
const generateCss = modifyCss || ((selector, properties) => {
const sel = selectorRemap ? selectorRemap(selector) : selector;
const props = modifyStyle ? modifyStyle(properties) : properties;
return `${sel}{${props}}\n`;
});
const css = [];
const detectFonts = typeof fonts === 'undefined';
const fontList = fonts || [];
styleSheetRules().forEach(({rules, href}) => {
if (!rules) return;
Array.from(rules).forEach(rule => {
if (typeof rule.style != 'undefined') {
if (query(el, rule.selectorText)) css.push(generateCss(rule.selectorText, rule.style.cssText));
else if (detectFonts && rule.cssText.match(/^@font-face/)) {
const font = detectCssFont(rule, href);
if (font) fontList.push(font);
} else if (!excludeUnusedCss) {
css.push(rule.cssText);
}
}
});
});
return inlineFonts(fontList).then(fontCss => css.join('\n') + fontCss);
};
const downloadOptions = () => {
if (!navigator.msSaveOrOpenBlob && !('download' in document.createElement('a'))) {
return {popup: window.open()};
}
};
//AMG added scaleX and scaleY -- originally, only allowed for a single scale
//AMG added transform keyword
out$.prepareSvg = (el, options, done) => {
requireDomNode(el);
const {
left = 0,
top = 0,
width: w,
height: h,
scaleX = 1,
scaleY = 1,
responsive = false,
excludeCss = false,
transform = null,
} = options || {};
return inlineImages(el).then(() => {
let clone = el.cloneNode(true);
clone.style.backgroundColor = (options || {}).backgroundColor || el.style.backgroundColor;
const {width, height} = getDimensions(el, clone, w, h);
if (el.tagName !== 'svg') {
if (el.getBBox) {
if (clone.getAttribute('transform') != null) {
clone.setAttribute('transform', clone.getAttribute('transform').replace(/translate\(.*?\)/, ''));
}
const svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
svg.appendChild(clone);
clone = svg;
} else {
console.error('Attempted to render non-SVG element', el);
return;
}
}
clone.setAttribute('version', '1.1');
clone.setAttribute('viewBox', [left, top, width, height].join(' '));
if (!clone.getAttribute('xmlns')) clone.setAttributeNS(xmlNs, 'xmlns', svgNs);
if (!clone.getAttribute('xmlns:xlink')) clone.setAttributeNS(xmlNs, 'xmlns:xlink', 'http://www.w3.org/1999/xlink');
if (responsive) {
clone.removeAttribute('width');
clone.removeAttribute('height');
clone.setAttribute('preserveAspectRatio', 'xMinYMin meet');
} else {
clone.setAttribute('width', width * scaleX); //AMG added scaleX
clone.setAttribute('height', height * scaleY); //AMG added scaleY
}
//AMG for transform
if (transform) {
clone.style.transform = transform;
clone.style.transformOrigin = "0px 0px";
}
Array.from(clone.querySelectorAll('foreignObject > *')).forEach(foreignObject => {
foreignObject.setAttributeNS(xmlNs, 'xmlns', foreignObject.tagName === 'svg' ? svgNs : xhtmlNs);
});
if (excludeCss) {
const outer = document.createElement('div');
outer.appendChild(clone);
const src = outer.innerHTML;
if (typeof done === 'function') done(src, width, height);
else return {src, width, height};
} else {
return inlineCss(el, options).then(css => {
const style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.innerHTML = `<![CDATA[\n${css}\n]]>`;
const defs = document.createElement('defs');
defs.appendChild(style);
clone.insertBefore(defs, clone.firstChild);
const outer = document.createElement('div');
outer.appendChild(clone);
const src = outer.innerHTML.replace(/NS\d+:href/gi, 'xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href');
if (typeof done === 'function') done(src, width, height);
else return {src, width, height};
});
}
});
};
out$.svgAsDataUri = (el, options, done) => {
requireDomNode(el);
return out$.prepareSvg(el, options)
.then(({src, width, height}) => {
const svgXml = `data:image/svg+xml;base64,${window.btoa(reEncode(doctype+src))}`;
if (typeof done === 'function') {
done(svgXml, width, height);
}
return svgXml;
});
};
out$.svgAsPngUri = (el, options, done) => {
requireDomNode(el);
const {
encoderType = 'image/png',
encoderOptions = 0.8,
canvg
} = options || {};
const convertToPng = ({src, width, height}) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
//const pixelRatio = window.devicePixelRatio || 1;
//AMG edited to keep the true pixel scale that the user inputs
const pixelRatio = 1;
canvas.width = width * pixelRatio;
canvas.height = height * pixelRatio;
canvas.style.width = `${canvas.width}px`;
canvas.style.height = `${canvas.height}px`;
context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
if (canvg) canvg(canvas, src);
else context.drawImage(src, 0, 0);
let png;
try {
png = canvas.toDataURL(encoderType, encoderOptions);
} catch (e) {
if ((typeof SecurityError !== 'undefined' && e instanceof SecurityError) || e.name === 'SecurityError') {
console.error('Rendered SVG images cannot be downloaded in this browser.');
return;
} else throw e;
}
if (typeof done === 'function') done(png, canvas.width, canvas.height);
return Promise.resolve(png);
}
if (canvg) return out$.prepareSvg(el, options).then(convertToPng);
else return out$.svgAsDataUri(el, options).then(uri => {
return new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => resolve(convertToPng({
src: image,
width: image.width,
height: image.height
}));
image.onerror = () => {
reject(`There was an error loading the data URI as an image on the following SVG\n${window.atob(uri.slice(26))}Open the following link to see browser's diagnosis\n${uri}`);
}
image.src = uri;
})
});
};
out$.download = (name, uri, options) => {
if (navigator.msSaveOrOpenBlob) navigator.msSaveOrOpenBlob(uriToBlob(uri), name);
else {
const saveLink = document.createElement('a');
if ('download' in saveLink) {
saveLink.download = name;
saveLink.style.display = 'none';
document.body.appendChild(saveLink);
try {
const blob = uriToBlob(uri);
const url = URL.createObjectURL(blob);
saveLink.href = url;
saveLink.onclick = () => requestAnimationFrame(() => URL.revokeObjectURL(url));
} catch (e) {
console.error(e);
console.warn('Error while getting object URL. Falling back to string URL.');
saveLink.href = uri;
}
saveLink.click();
document.body.removeChild(saveLink);
} else if (options && options.popup) {
options.popup.document.title = name;
options.popup.location.replace(uri);
}
}
};
out$.saveSvg = (el, name, options) => {
const downloadOpts = downloadOptions(); // don't inline, can't be async
return requireDomNodePromise(el)
.then(el => out$.svgAsDataUri(el, options || {}))
.then(uri => out$.download(name, uri, downloadOpts));
};
out$.saveSvgAsPng = (el, name, options) => {
const downloadOpts = downloadOptions(); // don't inline, can't be async
return requireDomNodePromise(el)
.then(el => out$.svgAsPngUri(el, options || {}))
.then(uri => out$.download(name, uri, downloadOpts));
};
})();
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ic_youtube_searched_for = void 0;
var ic_youtube_searched_for = {
"viewBox": "0 0 24 24",
"children": [{
"name": "path",
"attribs": {
"d": "M0 0h24v24H0V0zm0 0h24v24H0V0z",
"fill": "none"
},
"children": []
}, {
"name": "path",
"attribs": {
"d": "M17.01 14h-.8l-.27-.27c.98-1.14 1.57-2.61 1.57-4.23 0-3.59-2.91-6.5-6.5-6.5s-6.5 3-6.5 6.5H2l3.84 4 4.16-4H6.51C6.51 7 8.53 5 11.01 5s4.5 2.01 4.5 4.5c0 2.48-2.02 4.5-4.5 4.5-.65 0-1.26-.14-1.82-.38L7.71 15.1c.97.57 2.09.9 3.3.9 1.61 0 3.08-.59 4.22-1.57l.27.27v.79l5.01 4.99L22 19l-4.99-5z"
},
"children": []
}]
};
exports.ic_youtube_searched_for = ic_youtube_searched_for;
|
/*!
// ███ █ ████▄ ▄▄▄▄▀ ▄▄▄▄▀ ▄███▄ █▄▄▄▄
// █ █ █ █ █ ▀▀▀ █ ▀▀▀ █ █▀ ▀ █ ▄▀
// █ ▀ ▄ █ █ █ █ █ ██▄▄ █▀▀▌
// █ ▄▀ ███▄ ▀████ █ █ █▄ ▄▀ █ █
// ███ ▀ ▀ ▀ ▀███▀ █
// ▀
// The MIT License
//
// Copyright © 1986 - ∞, Blotter / Bradley Griffith / http://bradley.computer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
*/
!function(){var a="object"==typeof self&&self.self===self&&self||"object"==typeof global&&global.global===global&&global||this,b=a._,c=Array.prototype,d=Object.prototype,e="undefined"!=typeof Symbol?Symbol.prototype:null,f=c.push,g=c.slice,h=d.toString,i=d.hasOwnProperty,j=Array.isArray,k=Object.keys,l=Object.create,m=function(){},n=function(a){return a instanceof n?a:this instanceof n?void(this._wrapped=a):new n(a)};"undefined"==typeof exports||exports.nodeType?a._=n:("undefined"!=typeof module&&!module.nodeType&&module.exports&&(exports=module.exports=n),exports._=n),n.VERSION="1.8.3";var o,p=function(a,b,c){if(void 0===b)return a;switch(null==c?3:c){case 1:return function(c){return a.call(b,c)};case 3:return function(c,d,e){return a.call(b,c,d,e)};case 4:return function(c,d,e,f){return a.call(b,c,d,e,f)}}return function(){return a.apply(b,arguments)}},q=function(a,b,c){return n.iteratee!==o?n.iteratee(a,b):null==a?n.identity:n.isFunction(a)?p(a,b,c):n.isObject(a)?n.matcher(a):n.property(a)};n.iteratee=o=function(a,b){return q(a,b,1/0)};var r=function(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;e<c;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d);case 2:return a.call(this,arguments[0],arguments[1],d)}var f=Array(b+1);for(e=0;e<b;e++)f[e]=arguments[e];return f[b]=d,a.apply(this,f)}},s=function(a){if(!n.isObject(a))return{};if(l)return l(a);m.prototype=a;var b=new m;return m.prototype=null,b},t=function(a){return function(b){return null==b?void 0:b[a]}},u=Math.pow(2,53)-1,v=t("length"),w=function(a){var b=v(a);return"number"==typeof b&&b>=0&&b<=u};n.each=n.forEach=function(a,b,c){b=p(b,c);var d,e;if(w(a))for(d=0,e=a.length;d<e;d++)b(a[d],d,a);else{var f=n.keys(a);for(d=0,e=f.length;d<e;d++)b(a[f[d]],f[d],a)}return a},n.map=n.collect=function(a,b,c){b=q(b,c);for(var d=!w(a)&&n.keys(a),e=(d||a).length,f=Array(e),g=0;g<e;g++){var h=d?d[g]:g;f[g]=b(a[h],h,a)}return f};var x=function(a){var b=function(b,c,d,e){var f=!w(b)&&n.keys(b),g=(f||b).length,h=a>0?0:g-1;for(e||(d=b[f?f[h]:h],h+=a);h>=0&&h<g;h+=a){var i=f?f[h]:h;d=c(d,b[i],i,b)}return d};return function(a,c,d,e){var f=arguments.length>=3;return b(a,p(c,e,4),d,f)}};n.reduce=n.foldl=n.inject=x(1),n.reduceRight=n.foldr=x(-1),n.find=n.detect=function(a,b,c){var d=w(a)?n.findIndex:n.findKey,e=d(a,b,c);if(void 0!==e&&-1!==e)return a[e]},n.filter=n.select=function(a,b,c){var d=[];return b=q(b,c),n.each(a,function(a,c,e){b(a,c,e)&&d.push(a)}),d},n.reject=function(a,b,c){return n.filter(a,n.negate(q(b)),c)},n.every=n.all=function(a,b,c){b=q(b,c);for(var d=!w(a)&&n.keys(a),e=(d||a).length,f=0;f<e;f++){var g=d?d[f]:f;if(!b(a[g],g,a))return!1}return!0},n.some=n.any=function(a,b,c){b=q(b,c);for(var d=!w(a)&&n.keys(a),e=(d||a).length,f=0;f<e;f++){var g=d?d[f]:f;if(b(a[g],g,a))return!0}return!1},n.contains=n.includes=n.include=function(a,b,c,d){return w(a)||(a=n.values(a)),("number"!=typeof c||d)&&(c=0),n.indexOf(a,b,c)>=0},n.invoke=r(function(a,b,c){var d=n.isFunction(b);return n.map(a,function(a){var e=d?b:a[b];return null==e?e:e.apply(a,c)})}),n.pluck=function(a,b){return n.map(a,n.property(b))},n.where=function(a,b){return n.filter(a,n.matcher(b))},n.findWhere=function(a,b){return n.find(a,n.matcher(b))},n.max=function(a,b,c){var d,e,f=-1/0,g=-1/0;if(null==b||"number"==typeof b&&"object"!=typeof a[0]&&null!=a){a=w(a)?a:n.values(a);for(var h=0,i=a.length;h<i;h++)null!=(d=a[h])&&d>f&&(f=d)}else b=q(b,c),n.each(a,function(a,c,d){((e=b(a,c,d))>g||e===-1/0&&f===-1/0)&&(f=a,g=e)});return f},n.min=function(a,b,c){var d,e,f=1/0,g=1/0;if(null==b||"number"==typeof b&&"object"!=typeof a[0]&&null!=a){a=w(a)?a:n.values(a);for(var h=0,i=a.length;h<i;h++)null!=(d=a[h])&&d<f&&(f=d)}else b=q(b,c),n.each(a,function(a,c,d){((e=b(a,c,d))<g||e===1/0&&f===1/0)&&(f=a,g=e)});return f},n.shuffle=function(a){return n.sample(a,1/0)},n.sample=function(a,b,c){if(null==b||c)return w(a)||(a=n.values(a)),a[n.random(a.length-1)];var d=w(a)?n.clone(a):n.values(a),e=v(d);b=Math.max(Math.min(b,e),0);for(var f=e-1,g=0;g<b;g++){var h=n.random(g,f),i=d[g];d[g]=d[h],d[h]=i}return d.slice(0,b)},n.sortBy=function(a,b,c){var d=0;return b=q(b,c),n.pluck(n.map(a,function(a,c,e){return{value:a,index:d++,criteria:b(a,c,e)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;if(c!==d){if(c>d||void 0===c)return 1;if(c<d||void 0===d)return-1}return a.index-b.index}),"value")};var y=function(a,b){return function(c,d,e){var f=b?[[],[]]:{};return d=q(d,e),n.each(c,function(b,e){var g=d(b,e,c);a(f,b,g)}),f}};n.groupBy=y(function(a,b,c){n.has(a,c)?a[c].push(b):a[c]=[b]}),n.indexBy=y(function(a,b,c){a[c]=b}),n.countBy=y(function(a,b,c){n.has(a,c)?a[c]++:a[c]=1});var z=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;n.toArray=function(a){return a?n.isArray(a)?g.call(a):n.isString(a)?a.match(z):w(a)?n.map(a,n.identity):n.values(a):[]},n.size=function(a){return null==a?0:w(a)?a.length:n.keys(a).length},n.partition=y(function(a,b,c){a[c?0:1].push(b)},!0),n.first=n.head=n.take=function(a,b,c){if(null!=a)return null==b||c?a[0]:n.initial(a,a.length-b)},n.initial=function(a,b,c){return g.call(a,0,Math.max(0,a.length-(null==b||c?1:b)))},n.last=function(a,b,c){if(null!=a)return null==b||c?a[a.length-1]:n.rest(a,Math.max(0,a.length-b))},n.rest=n.tail=n.drop=function(a,b,c){return g.call(a,null==b||c?1:b)},n.compact=function(a){return n.filter(a,Boolean)};var A=function(a,b,c,d){d=d||[];for(var e=d.length,f=0,g=v(a);f<g;f++){var h=a[f];if(w(h)&&(n.isArray(h)||n.isArguments(h)))if(b)for(var i=0,j=h.length;i<j;)d[e++]=h[i++];else A(h,b,c,d),e=d.length;else c||(d[e++]=h)}return d};n.flatten=function(a,b){return A(a,b,!1)},n.without=r(function(a,b){return n.difference(a,b)}),n.uniq=n.unique=function(a,b,c,d){n.isBoolean(b)||(d=c,c=b,b=!1),null!=c&&(c=q(c,d));for(var e=[],f=[],g=0,h=v(a);g<h;g++){var i=a[g],j=c?c(i,g,a):i;b?(g&&f===j||e.push(i),f=j):c?n.contains(f,j)||(f.push(j),e.push(i)):n.contains(e,i)||e.push(i)}return e},n.union=r(function(a){return n.uniq(A(a,!0,!0))}),n.intersection=function(a){for(var b=[],c=arguments.length,d=0,e=v(a);d<e;d++){var f=a[d];if(!n.contains(b,f)){var g;for(g=1;g<c&&n.contains(arguments[g],f);g++);g===c&&b.push(f)}}return b},n.difference=r(function(a,b){return b=A(b,!0,!0),n.filter(a,function(a){return!n.contains(b,a)})}),n.unzip=function(a){for(var b=a&&n.max(a,v).length||0,c=Array(b),d=0;d<b;d++)c[d]=n.pluck(a,d);return c},n.zip=r(n.unzip),n.object=function(a,b){for(var c={},d=0,e=v(a);d<e;d++)b?c[a[d]]=b[d]:c[a[d][0]]=a[d][1];return c};var B=function(a){return function(b,c,d){c=q(c,d);for(var e=v(b),f=a>0?0:e-1;f>=0&&f<e;f+=a)if(c(b[f],f,b))return f;return-1}};n.findIndex=B(1),n.findLastIndex=B(-1),n.sortedIndex=function(a,b,c,d){c=q(c,d,1);for(var e=c(b),f=0,g=v(a);f<g;){var h=Math.floor((f+g)/2);c(a[h])<e?f=h+1:g=h}return f};var C=function(a,b,c){return function(d,e,f){var h=0,i=v(d);if("number"==typeof f)a>0?h=f>=0?f:Math.max(f+i,h):i=f>=0?Math.min(f+1,i):f+i+1;else if(c&&f&&i)return f=c(d,e),d[f]===e?f:-1;if(e!==e)return f=b(g.call(d,h,i),n.isNaN),f>=0?f+h:-1;for(f=a>0?h:i-1;f>=0&&f<i;f+=a)if(d[f]===e)return f;return-1}};n.indexOf=C(1,n.findIndex,n.sortedIndex),n.lastIndexOf=C(-1,n.findLastIndex),n.range=function(a,b,c){null==b&&(b=a||0,a=0),c||(c=b<a?-1:1);for(var d=Math.max(Math.ceil((b-a)/c),0),e=Array(d),f=0;f<d;f++,a+=c)e[f]=a;return e},n.chunk=function(a,b){if(null==b||b<1)return[];for(var c=[],d=0,e=a.length;d<e;)c.push(g.call(a,d,d+=b));return c};var D=function(a,b,c,d,e){if(!(d instanceof b))return a.apply(c,e);var f=s(a.prototype),g=a.apply(f,e);return n.isObject(g)?g:f};n.bind=r(function(a,b,c){if(!n.isFunction(a))throw new TypeError("Bind must be called on a function");var d=r(function(e){return D(a,d,b,this,c.concat(e))});return d}),n.partial=r(function(a,b){var c=n.partial.placeholder,d=function(){for(var e=0,f=b.length,g=Array(f),h=0;h<f;h++)g[h]=b[h]===c?arguments[e++]:b[h];for(;e<arguments.length;)g.push(arguments[e++]);return D(a,d,this,this,g)};return d}),n.partial.placeholder=n,n.bindAll=r(function(a,b){b=A(b,!1,!1);var c=b.length;if(c<1)throw new Error("bindAll must be passed function names");for(;c--;){var d=b[c];a[d]=n.bind(a[d],a)}}),n.memoize=function(a,b){var c=function(d){var e=c.cache,f=""+(b?b.apply(this,arguments):d);return n.has(e,f)||(e[f]=a.apply(this,arguments)),e[f]};return c.cache={},c},n.delay=r(function(a,b,c){return setTimeout(function(){return a.apply(null,c)},b)}),n.defer=n.partial(n.delay,n,1),n.throttle=function(a,b,c){var d,e,f,g,h=0;c||(c={});var i=function(){h=!1===c.leading?0:n.now(),d=null,g=a.apply(e,f),d||(e=f=null)},j=function(){var j=n.now();h||!1!==c.leading||(h=j);var k=b-(j-h);return e=this,f=arguments,k<=0||k>b?(d&&(clearTimeout(d),d=null),h=j,g=a.apply(e,f),d||(e=f=null)):d||!1===c.trailing||(d=setTimeout(i,k)),g};return j.cancel=function(){clearTimeout(d),h=0,d=e=f=null},j},n.debounce=function(a,b,c){var d,e,f=function(b,c){d=null,c&&(e=a.apply(b,c))},g=r(function(g){if(d&&clearTimeout(d),c){var h=!d;d=setTimeout(f,b),h&&(e=a.apply(this,g))}else d=n.delay(f,b,this,g);return e});return g.cancel=function(){clearTimeout(d),d=null},g},n.wrap=function(a,b){return n.partial(b,a)},n.negate=function(a){return function(){return!a.apply(this,arguments)}},n.compose=function(){var a=arguments,b=a.length-1;return function(){for(var c=b,d=a[b].apply(this,arguments);c--;)d=a[c].call(this,d);return d}},n.after=function(a,b){return function(){if(--a<1)return b.apply(this,arguments)}},n.before=function(a,b){var c;return function(){return--a>0&&(c=b.apply(this,arguments)),a<=1&&(b=null),c}},n.once=n.partial(n.before,2),n.restArgs=r;var E=!{toString:null}.propertyIsEnumerable("toString"),F=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"],G=function(a,b){var c=F.length,e=a.constructor,f=n.isFunction(e)&&e.prototype||d,g="constructor";for(n.has(a,g)&&!n.contains(b,g)&&b.push(g);c--;)(g=F[c])in a&&a[g]!==f[g]&&!n.contains(b,g)&&b.push(g)};n.keys=function(a){if(!n.isObject(a))return[];if(k)return k(a);var b=[];for(var c in a)n.has(a,c)&&b.push(c);return E&&G(a,b),b},n.allKeys=function(a){if(!n.isObject(a))return[];var b=[];for(var c in a)b.push(c);return E&&G(a,b),b},n.values=function(a){for(var b=n.keys(a),c=b.length,d=Array(c),e=0;e<c;e++)d[e]=a[b[e]];return d},n.mapObject=function(a,b,c){b=q(b,c);for(var d=n.keys(a),e=d.length,f={},g=0;g<e;g++){var h=d[g];f[h]=b(a[h],h,a)}return f},n.pairs=function(a){for(var b=n.keys(a),c=b.length,d=Array(c),e=0;e<c;e++)d[e]=[b[e],a[b[e]]];return d},n.invert=function(a){for(var b={},c=n.keys(a),d=0,e=c.length;d<e;d++)b[a[c[d]]]=c[d];return b},n.functions=n.methods=function(a){var b=[];for(var c in a)n.isFunction(a[c])&&b.push(c);return b.sort()};var H=function(a,b){return function(c){var d=arguments.length;if(b&&(c=Object(c)),d<2||null==c)return c;for(var e=1;e<d;e++)for(var f=arguments[e],g=a(f),h=g.length,i=0;i<h;i++){var j=g[i];b&&void 0!==c[j]||(c[j]=f[j])}return c}};n.extend=H(n.allKeys),n.extendOwn=n.assign=H(n.keys),n.findKey=function(a,b,c){b=q(b,c);for(var d,e=n.keys(a),f=0,g=e.length;f<g;f++)if(d=e[f],b(a[d],d,a))return d};var I=function(a,b,c){return b in c};n.pick=r(function(a,b){var c={},d=b[0];if(null==a)return c;n.isFunction(d)?(b.length>1&&(d=p(d,b[1])),b=n.allKeys(a)):(d=I,b=A(b,!1,!1),a=Object(a));for(var e=0,f=b.length;e<f;e++){var g=b[e],h=a[g];d(h,g,a)&&(c[g]=h)}return c}),n.omit=r(function(a,b){var c,d=b[0];return n.isFunction(d)?(d=n.negate(d),b.length>1&&(c=b[1])):(b=n.map(A(b,!1,!1),String),d=function(a,c){return!n.contains(b,c)}),n.pick(a,d,c)}),n.defaults=H(n.allKeys,!0),n.create=function(a,b){var c=s(a);return b&&n.extendOwn(c,b),c},n.clone=function(a){return n.isObject(a)?n.isArray(a)?a.slice():n.extend({},a):a},n.tap=function(a,b){return b(a),a},n.isMatch=function(a,b){var c=n.keys(b),d=c.length;if(null==a)return!d;for(var e=Object(a),f=0;f<d;f++){var g=c[f];if(b[g]!==e[g]||!(g in e))return!1}return!0};var J,K;J=function(a,b,c,d){if(a===b)return 0!==a||1/a==1/b;if(null==a||null==b)return a===b;if(a!==a)return b!==b;var e=typeof a;return("function"===e||"object"===e||"object"==typeof b)&&K(a,b,c,d)},K=function(a,b,c,d){a instanceof n&&(a=a._wrapped),b instanceof n&&(b=b._wrapped);var f=h.call(a);if(f!==h.call(b))return!1;switch(f){case"[object RegExp]":case"[object String]":return""+a==""+b;case"[object Number]":return+a!=+a?+b!=+b:0==+a?1/+a==1/b:+a==+b;case"[object Date]":case"[object Boolean]":return+a==+b;case"[object Symbol]":return e.valueOf.call(a)===e.valueOf.call(b)}var g="[object Array]"===f;if(!g){if("object"!=typeof a||"object"!=typeof b)return!1;var i=a.constructor,j=b.constructor;if(i!==j&&!(n.isFunction(i)&&i instanceof i&&n.isFunction(j)&&j instanceof j)&&"constructor"in a&&"constructor"in b)return!1}c=c||[],d=d||[];for(var k=c.length;k--;)if(c[k]===a)return d[k]===b;if(c.push(a),d.push(b),g){if((k=a.length)!==b.length)return!1;for(;k--;)if(!J(a[k],b[k],c,d))return!1}else{var l,m=n.keys(a);if(k=m.length,n.keys(b).length!==k)return!1;for(;k--;)if(l=m[k],!n.has(b,l)||!J(a[l],b[l],c,d))return!1}return c.pop(),d.pop(),!0},n.isEqual=function(a,b){return J(a,b)},n.isEmpty=function(a){return null==a||(w(a)&&(n.isArray(a)||n.isString(a)||n.isArguments(a))?0===a.length:0===n.keys(a).length)},n.isElement=function(a){return!(!a||1!==a.nodeType)},n.isArray=j||function(a){return"[object Array]"===h.call(a)},n.isObject=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},n.each(["Arguments","Function","String","Number","Date","RegExp","Error","Symbol","Map","WeakMap","Set","WeakSet"],function(a){n["is"+a]=function(b){return h.call(b)==="[object "+a+"]"}}),n.isArguments(arguments)||(n.isArguments=function(a){return n.has(a,"callee")});var L=a.document&&a.document.childNodes;"function"!=typeof/./&&"object"!=typeof Int8Array&&"function"!=typeof L&&(n.isFunction=function(a){return"function"==typeof a||!1}),n.isFinite=function(a){return!n.isSymbol(a)&&isFinite(a)&&!isNaN(parseFloat(a))},n.isNaN=function(a){return isNaN(a)&&n.isNumber(a)},n.isBoolean=function(a){return!0===a||!1===a||"[object Boolean]"===h.call(a)},n.isNull=function(a){return null===a},n.isUndefined=function(a){return void 0===a},n.has=function(a,b){return null!=a&&i.call(a,b)},n.noConflict=function(){return a._=b,this},n.identity=function(a){return a},n.constant=function(a){return function(){return a}},n.noop=function(){},n.property=t,n.propertyOf=function(a){return null==a?function(){}:function(b){return a[b]}},n.matcher=n.matches=function(a){return a=n.extendOwn({},a),function(b){return n.isMatch(b,a)}},n.times=function(a,b,c){var d=Array(Math.max(0,a));b=p(b,c,1);for(var e=0;e<a;e++)d[e]=b(e);return d},n.random=function(a,b){return null==b&&(b=a,a=0),a+Math.floor(Math.random()*(b-a+1))},n.now=Date.now||function(){return(new Date).getTime()};var M={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},N=n.invert(M),O=function(a){var b=function(b){return a[b]},c="(?:"+n.keys(a).join("|")+")",d=RegExp(c),e=RegExp(c,"g");return function(a){return a=null==a?"":""+a,d.test(a)?a.replace(e,b):a}};n.escape=O(M),n.unescape=O(N),n.result=function(a,b,c){var d=null==a?void 0:a[b];return void 0===d&&(d=c),n.isFunction(d)?d.call(a):d};var P=0;n.uniqueId=function(a){var b=++P+"";return a?a+b:b},n.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var Q=/(.)^/,R={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},S=/\\|'|\r|\n|\u2028|\u2029/g,T=function(a){return"\\"+R[a]};n.template=function(a,b,c){!b&&c&&(b=c),b=n.defaults({},b,n.templateSettings);var d=RegExp([(b.escape||Q).source,(b.interpolate||Q).source,(b.evaluate||Q).source].join("|")+"|$","g"),e=0,f="__p+='";a.replace(d,function(b,c,d,g,h){return f+=a.slice(e,h).replace(S,T),e=h+b.length,c?f+="'+\n((__t=("+c+"))==null?'':_.escape(__t))+\n'":d?f+="'+\n((__t=("+d+"))==null?'':__t)+\n'":g&&(f+="';\n"+g+"\n__p+='"),b}),f+="';\n",b.variable||(f="with(obj||{}){\n"+f+"}\n"),f="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+f+"return __p;\n";var g;try{g=new Function(b.variable||"obj","_",f)}catch(a){throw a.source=f,a}var h=function(a){return g.call(this,a,n)},i=b.variable||"obj";return h.source="function("+i+"){\n"+f+"}",h},n.chain=function(a){var b=n(a);return b._chain=!0,b};var U=function(a,b){return a._chain?n(b).chain():b};n.mixin=function(a){return n.each(n.functions(a),function(b){var c=n[b]=a[b];n.prototype[b]=function(){var a=[this._wrapped];return f.apply(a,arguments),U(this,c.apply(n,a))}}),n},n.mixin(n),n.each(["pop","push","reverse","shift","sort","splice","unshift"],function(a){var b=c[a];n.prototype[a]=function(){var c=this._wrapped;return b.apply(c,arguments),"shift"!==a&&"splice"!==a||0!==c.length||delete c[0],U(this,c)}}),n.each(["concat","join","slice"],function(a){var b=c[a];n.prototype[a]=function(){return U(this,b.apply(this._wrapped,arguments))}}),n.prototype.value=function(){return this._wrapped},n.prototype.valueOf=n.prototype.toJSON=n.prototype.value,n.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return n})}(),function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define(["exports"],b):b(a.THREE={})}(this,function(a){"use strict";function b(){}function c(a,b){this.x=a||0,this.y=b||0}function d(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.")}function e(a,b,c,d){this._x=a||0,this._y=b||0,this._z=c||0,this._w=void 0!==d?d:1}function f(a,b,c){this.x=a||0,this.y=b||0,this.z=c||0}function g(){this.elements=[1,0,0,0,1,0,0,0,1],arguments.length>0&&console.error("THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.")}function h(a,b,d,e,f,i,j,k,l,m){Object.defineProperty(this,"id",{value:zd++}),this.uuid=yd.generateUUID(),this.name="",this.image=void 0!==a?a:h.DEFAULT_IMAGE,this.mipmaps=[],this.mapping=void 0!==b?b:h.DEFAULT_MAPPING,this.wrapS=void 0!==d?d:Ec,this.wrapT=void 0!==e?e:Ec,this.magFilter=void 0!==f?f:Jc,this.minFilter=void 0!==i?i:Lc,this.anisotropy=void 0!==l?l:1,this.format=void 0!==j?j:$c,this.type=void 0!==k?k:Mc,this.offset=new c(0,0),this.repeat=new c(1,1),this.center=new c(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new g,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.encoding=void 0!==m?m:pd,this.version=0,this.onUpdate=null}function i(a,b,c,d){this.x=a||0,this.y=b||0,this.z=c||0,this.w=void 0!==d?d:1}function j(a,b,c){this.uuid=yd.generateUUID(),this.width=a,this.height=b,this.scissor=new i(0,0,a,b),this.scissorTest=!1,this.viewport=new i(0,0,a,b),c=c||{},void 0===c.minFilter&&(c.minFilter=Jc),this.texture=new h(void 0,void 0,c.wrapS,c.wrapT,c.magFilter,c.minFilter,c.format,c.type,c.anisotropy,c.encoding),this.depthBuffer=void 0===c.depthBuffer||c.depthBuffer,this.stencilBuffer=void 0===c.stencilBuffer||c.stencilBuffer,this.depthTexture=void 0!==c.depthTexture?c.depthTexture:null}function k(a,b,c,d,e,f,g,i,j,k,l,m){h.call(this,null,f,g,i,j,k,d,e,l,m),this.image={data:a,width:b,height:c},this.magFilter=void 0!==j?j:Gc,this.minFilter=void 0!==k?k:Gc,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}function l(a,b,c,d,e,f,g,i,j,k){a=void 0!==a?a:[],b=void 0!==b?b:wc,h.call(this,a,b,c,d,e,f,g,i,j,k),this.flipY=!1}function m(){this.seq=[],this.map={}}function n(a,b,c){var d=a[0];if(d<=0||d>0)return a;var e=b*c,f=Cd[e];if(void 0===f&&(f=new Float32Array(e),Cd[e]=f),0!==b){d.toArray(f,0);for(var g=1,h=0;g!==b;++g)h+=c,a[g].toArray(f,h)}return f}function o(a,b){var c=Dd[b];void 0===c&&(c=new Int32Array(b),Dd[b]=c);for(var d=0;d!==b;++d)c[d]=a.allocTextureUnit();return c}function p(a,b){a.uniform1f(this.addr,b)}function q(a,b){a.uniform1i(this.addr,b)}function r(a,b){void 0===b.x?a.uniform2fv(this.addr,b):a.uniform2f(this.addr,b.x,b.y)}function s(a,b){void 0!==b.x?a.uniform3f(this.addr,b.x,b.y,b.z):void 0!==b.r?a.uniform3f(this.addr,b.r,b.g,b.b):a.uniform3fv(this.addr,b)}function t(a,b){void 0===b.x?a.uniform4fv(this.addr,b):a.uniform4f(this.addr,b.x,b.y,b.z,b.w)}function u(a,b){a.uniformMatrix2fv(this.addr,!1,b.elements||b)}function v(a,b){void 0===b.elements?a.uniformMatrix3fv(this.addr,!1,b):(Fd.set(b.elements),a.uniformMatrix3fv(this.addr,!1,Fd))}function w(a,b){void 0===b.elements?a.uniformMatrix4fv(this.addr,!1,b):(Ed.set(b.elements),a.uniformMatrix4fv(this.addr,!1,Ed))}function x(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d),c.setTexture2D(b||Ad,d)}function y(a,b,c){var d=c.allocTextureUnit();a.uniform1i(this.addr,d),c.setTextureCube(b||Bd,d)}function z(a,b){a.uniform2iv(this.addr,b)}function A(a,b){a.uniform3iv(this.addr,b)}function B(a,b){a.uniform4iv(this.addr,b)}function C(a){switch(a){case 5126:return p;case 35664:return r;case 35665:return s;case 35666:return t;case 35674:return u;case 35675:return v;case 35676:return w;case 35678:case 36198:return x;case 35680:return y;case 5124:case 35670:return q;case 35667:case 35671:return z;case 35668:case 35672:return A;case 35669:case 35673:return B}}function D(a,b){a.uniform1fv(this.addr,b)}function E(a,b){a.uniform1iv(this.addr,b)}function F(a,b){a.uniform2fv(this.addr,n(b,this.size,2))}function G(a,b){a.uniform3fv(this.addr,n(b,this.size,3))}function H(a,b){a.uniform4fv(this.addr,n(b,this.size,4))}function I(a,b){a.uniformMatrix2fv(this.addr,!1,n(b,this.size,4))}function J(a,b){a.uniformMatrix3fv(this.addr,!1,n(b,this.size,9))}function K(a,b){a.uniformMatrix4fv(this.addr,!1,n(b,this.size,16))}function L(a,b,c){var d=b.length,e=o(c,d);a.uniform1iv(this.addr,e);for(var f=0;f!==d;++f)c.setTexture2D(b[f]||Ad,e[f])}function M(a,b,c){var d=b.length,e=o(c,d);a.uniform1iv(this.addr,e);for(var f=0;f!==d;++f)c.setTextureCube(b[f]||Bd,e[f])}function N(a){switch(a){case 5126:return D;case 35664:return F;case 35665:return G;case 35666:return H;case 35674:return I;case 35675:return J;case 35676:return K;case 35678:return L;case 35680:return M;case 5124:case 35670:return E;case 35667:case 35671:return z;case 35668:case 35672:return A;case 35669:case 35673:return B}}function O(a,b,c){this.id=a,this.addr=c,this.setValue=C(b.type)}function P(a,b,c){this.id=a,this.addr=c,this.size=b.size,this.setValue=N(b.type)}function Q(a){this.id=a,m.call(this)}function R(a,b){a.seq.push(b),a.map[b.id]=b}function S(a,b,c){var d=a.name,e=d.length;for(Gd.lastIndex=0;;){var f=Gd.exec(d),g=Gd.lastIndex,h=f[1],i="]"===f[2],j=f[3];if(i&&(h|=0),void 0===j||"["===j&&g+2===e){R(c,void 0===j?new O(h,a,b):new P(h,a,b));break}var k=c.map,l=k[h];void 0===l&&(l=new Q(h),R(c,l)),c=l}}function T(a,b,c){m.call(this),this.renderer=c;for(var d=a.getProgramParameter(b,a.ACTIVE_UNIFORMS),e=0;e<d;++e){var f=a.getActiveUniform(b,e),g=f.name;S(f,a.getUniformLocation(b,g),this)}}function U(a,b,c){return void 0===b&&void 0===c?this.set(a):this.setRGB(a,b,c)}function V(a,b){this.min=void 0!==a?a:new c(1/0,1/0),this.max=void 0!==b?b:new c(-1/0,-1/0)}function W(a,b,d,e,g){function h(){var a=new Float32Array([-1,-1,0,0,1,-1,1,0,1,1,1,1,-1,1,0,1]),c=new Uint16Array([0,1,2,0,2,3]);j=b.createBuffer(),k=b.createBuffer(),b.bindBuffer(b.ARRAY_BUFFER,j),b.bufferData(b.ARRAY_BUFFER,a,b.STATIC_DRAW),b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,k),b.bufferData(b.ELEMENT_ARRAY_BUFFER,c,b.STATIC_DRAW),p=b.createTexture(),q=b.createTexture(),d.bindTexture(b.TEXTURE_2D,p),b.texImage2D(b.TEXTURE_2D,0,b.RGB,16,16,0,b.RGB,b.UNSIGNED_BYTE,null),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST),d.bindTexture(b.TEXTURE_2D,q),b.texImage2D(b.TEXTURE_2D,0,b.RGBA,16,16,0,b.RGBA,b.UNSIGNED_BYTE,null),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST),l={vertexShader:["uniform lowp int renderType;","uniform vec3 screenPosition;","uniform vec2 scale;","uniform float rotation;","uniform sampler2D occlusionMap;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","varying float vVisibility;","void main() {","\tvUV = uv;","\tvec2 pos = position;","\tif ( renderType == 2 ) {","\t\tvec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );","\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );","\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );","\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );","\t\tvisibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );","\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );","\t\tvisibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );","\t\tvisibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );","\t\tvisibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );","\t\tvVisibility = visibility.r / 9.0;","\t\tvVisibility *= 1.0 - visibility.g / 9.0;","\t\tvVisibility *= visibility.b / 9.0;","\t\tvVisibility *= 1.0 - visibility.a / 9.0;","\t\tpos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;","\t\tpos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;","\t}","\tgl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );","}"].join("\n"),fragmentShader:["uniform lowp int renderType;","uniform sampler2D map;","uniform float opacity;","uniform vec3 color;","varying vec2 vUV;","varying float vVisibility;","void main() {","\tif ( renderType == 0 ) {","\t\tgl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );","\t} else if ( renderType == 1 ) {","\t\tgl_FragColor = texture2D( map, vUV );","\t} else {","\t\tvec4 texture = texture2D( map, vUV );","\t\ttexture.a *= opacity * vVisibility;","\t\tgl_FragColor = texture;","\t\tgl_FragColor.rgb *= color;","\t}","}"].join("\n")},m=i(l),n={vertex:b.getAttribLocation(m,"position"),uv:b.getAttribLocation(m,"uv")},o={renderType:b.getUniformLocation(m,"renderType"),map:b.getUniformLocation(m,"map"),occlusionMap:b.getUniformLocation(m,"occlusionMap"),opacity:b.getUniformLocation(m,"opacity"),color:b.getUniformLocation(m,"color"),scale:b.getUniformLocation(m,"scale"),rotation:b.getUniformLocation(m,"rotation"),screenPosition:b.getUniformLocation(m,"screenPosition")}}function i(a){var c=b.createProgram(),d=b.createShader(b.FRAGMENT_SHADER),e=b.createShader(b.VERTEX_SHADER),f="precision "+g.precision+" float;\n";return b.shaderSource(d,f+a.fragmentShader),b.shaderSource(e,f+a.vertexShader),b.compileShader(d),b.compileShader(e),b.attachShader(c,d),b.attachShader(c,e),b.linkProgram(c),c}var j,k,l,m,n,o,p,q;this.render=function(a,g,i,l){if(0!==a.length){var r=new f,s=l.w/l.z,t=.5*l.z,u=.5*l.w,v=16/l.w,w=new c(v*s,v),x=new f(1,1,0),y=new c(1,1),z=new V;z.min.set(l.x,l.y),z.max.set(l.x+(l.z-16),l.y+(l.w-16)),void 0===m&&h(),d.useProgram(m),d.initAttributes(),d.enableAttribute(n.vertex),d.enableAttribute(n.uv),d.disableUnusedAttributes(),b.uniform1i(o.occlusionMap,0),b.uniform1i(o.map,1),b.bindBuffer(b.ARRAY_BUFFER,j),b.vertexAttribPointer(n.vertex,2,b.FLOAT,!1,16,0),b.vertexAttribPointer(n.uv,2,b.FLOAT,!1,16,8),b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,k),d.disable(b.CULL_FACE),d.buffers.depth.setMask(!1);for(var A=0,B=a.length;A<B;A++){v=16/l.w,w.set(v*s,v);var C=a[A];if(r.set(C.matrixWorld.elements[12],C.matrixWorld.elements[13],C.matrixWorld.elements[14]),r.applyMatrix4(i.matrixWorldInverse),r.applyMatrix4(i.projectionMatrix),x.copy(r),y.x=l.x+x.x*t+t-8,y.y=l.y+x.y*u+u-8,!0===z.containsPoint(y)){d.activeTexture(b.TEXTURE0),d.bindTexture(b.TEXTURE_2D,null),d.activeTexture(b.TEXTURE1),d.bindTexture(b.TEXTURE_2D,p),b.copyTexImage2D(b.TEXTURE_2D,0,b.RGB,y.x,y.y,16,16,0),b.uniform1i(o.renderType,0),b.uniform2f(o.scale,w.x,w.y),b.uniform3f(o.screenPosition,x.x,x.y,x.z),d.disable(b.BLEND),d.enable(b.DEPTH_TEST),b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0),d.activeTexture(b.TEXTURE0),d.bindTexture(b.TEXTURE_2D,q),b.copyTexImage2D(b.TEXTURE_2D,0,b.RGBA,y.x,y.y,16,16,0),b.uniform1i(o.renderType,1),d.disable(b.DEPTH_TEST),d.activeTexture(b.TEXTURE1),d.bindTexture(b.TEXTURE_2D,p),b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0),C.positionScreen.copy(x),C.customUpdateCallback?C.customUpdateCallback(C):C.updateLensFlares(),b.uniform1i(o.renderType,2),d.enable(b.BLEND);for(var D=0,E=C.lensFlares.length;D<E;D++){var F=C.lensFlares[D];F.opacity>.001&&F.scale>.001&&(x.x=F.x,x.y=F.y,x.z=F.z,v=F.size*F.scale/l.w,w.x=v*s,w.y=v,b.uniform3f(o.screenPosition,x.x,x.y,x.z),b.uniform2f(o.scale,w.x,w.y),b.uniform1f(o.rotation,F.rotation),b.uniform1f(o.opacity,F.opacity),b.uniform3f(o.color,F.color.r,F.color.g,F.color.b),d.setBlending(F.blending,F.blendEquation,F.blendSrc,F.blendDst),e.setTexture2D(F.texture,1),b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0))}}}d.enable(b.CULL_FACE),d.enable(b.DEPTH_TEST),d.buffers.depth.setMask(!0),d.reset()}}}function X(a,b,c,d,e,f,g,i,j){h.call(this,a,b,c,d,e,f,g,i,j),this.needsUpdate=!0}function Y(a,b,c,d,g){function h(){var a=new Float32Array([-.5,-.5,0,0,.5,-.5,1,0,.5,.5,1,1,-.5,.5,0,1]),c=new Uint16Array([0,1,2,0,2,3]);k=b.createBuffer(),l=b.createBuffer(),b.bindBuffer(b.ARRAY_BUFFER,k),b.bufferData(b.ARRAY_BUFFER,a,b.STATIC_DRAW),b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,l),b.bufferData(b.ELEMENT_ARRAY_BUFFER,c,b.STATIC_DRAW),m=i(),n={position:b.getAttribLocation(m,"position"),uv:b.getAttribLocation(m,"uv")},o={uvOffset:b.getUniformLocation(m,"uvOffset"),uvScale:b.getUniformLocation(m,"uvScale"),rotation:b.getUniformLocation(m,"rotation"),scale:b.getUniformLocation(m,"scale"),color:b.getUniformLocation(m,"color"),map:b.getUniformLocation(m,"map"),opacity:b.getUniformLocation(m,"opacity"),modelViewMatrix:b.getUniformLocation(m,"modelViewMatrix"),projectionMatrix:b.getUniformLocation(m,"projectionMatrix"),fogType:b.getUniformLocation(m,"fogType"),fogDensity:b.getUniformLocation(m,"fogDensity"),fogNear:b.getUniformLocation(m,"fogNear"),fogFar:b.getUniformLocation(m,"fogFar"),fogColor:b.getUniformLocation(m,"fogColor"),fogDepth:b.getUniformLocation(m,"fogDepth"),alphaTest:b.getUniformLocation(m,"alphaTest")};var d=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");d.width=8,d.height=8;var e=d.getContext("2d");e.fillStyle="white",e.fillRect(0,0,8,8),p=new X(d)}function i(){var a=b.createProgram(),c=b.createShader(b.VERTEX_SHADER),d=b.createShader(b.FRAGMENT_SHADER);return b.shaderSource(c,["precision "+g.precision+" float;","#define SHADER_NAME SpriteMaterial","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform float rotation;","uniform vec2 scale;","uniform vec2 uvOffset;","uniform vec2 uvScale;","attribute vec2 position;","attribute vec2 uv;","varying vec2 vUV;","varying float fogDepth;","void main() {","\tvUV = uvOffset + uv * uvScale;","\tvec2 alignedPosition = position * scale;","\tvec2 rotatedPosition;","\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;","\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;","\tvec4 mvPosition;","\tmvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );","\tmvPosition.xy += rotatedPosition;","\tgl_Position = projectionMatrix * mvPosition;","\tfogDepth = - mvPosition.z;","}"].join("\n")),b.shaderSource(d,["precision "+g.precision+" float;","#define SHADER_NAME SpriteMaterial","uniform vec3 color;","uniform sampler2D map;","uniform float opacity;","uniform int fogType;","uniform vec3 fogColor;","uniform float fogDensity;","uniform float fogNear;","uniform float fogFar;","uniform float alphaTest;","varying vec2 vUV;","varying float fogDepth;","void main() {","\tvec4 texture = texture2D( map, vUV );","\tgl_FragColor = vec4( color * texture.xyz, texture.a * opacity );","\tif ( gl_FragColor.a < alphaTest ) discard;","\tif ( fogType > 0 ) {","\t\tfloat fogFactor = 0.0;","\t\tif ( fogType == 1 ) {","\t\t\tfogFactor = smoothstep( fogNear, fogFar, fogDepth );","\t\t} else {","\t\t\tconst float LOG2 = 1.442695;","\t\t\tfogFactor = exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 );","\t\t\tfogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );","\t\t}","\t\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );","\t}","}"].join("\n")),b.compileShader(c),b.compileShader(d),b.attachShader(a,c),b.attachShader(a,d),b.linkProgram(a),a}function j(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:b.id-a.id}var k,l,m,n,o,p,q=new f,r=new e,s=new f;this.render=function(e,f,g){if(0!==e.length){void 0===m&&h(),c.useProgram(m),c.initAttributes(),c.enableAttribute(n.position),c.enableAttribute(n.uv),c.disableUnusedAttributes(),c.disable(b.CULL_FACE),c.enable(b.BLEND),b.bindBuffer(b.ARRAY_BUFFER,k),b.vertexAttribPointer(n.position,2,b.FLOAT,!1,16,0),b.vertexAttribPointer(n.uv,2,b.FLOAT,!1,16,8),b.bindBuffer(b.ELEMENT_ARRAY_BUFFER,l),b.uniformMatrix4fv(o.projectionMatrix,!1,g.projectionMatrix.elements),c.activeTexture(b.TEXTURE0),b.uniform1i(o.map,0);var i=0,t=0,u=f.fog;u?(b.uniform3f(o.fogColor,u.color.r,u.color.g,u.color.b),u.isFog?(b.uniform1f(o.fogNear,u.near),b.uniform1f(o.fogFar,u.far),b.uniform1i(o.fogType,1),i=1,t=1):u.isFogExp2&&(b.uniform1f(o.fogDensity,u.density),b.uniform1i(o.fogType,2),i=2,t=2)):(b.uniform1i(o.fogType,0),i=0,t=0);for(var v=0,w=e.length;v<w;v++){var x=e[v];x.modelViewMatrix.multiplyMatrices(g.matrixWorldInverse,x.matrixWorld),x.z=-x.modelViewMatrix.elements[14]}e.sort(j);for(var y=[],v=0,w=e.length;v<w;v++){var x=e[v],z=x.material;if(!1!==z.visible){x.onBeforeRender(a,f,g,void 0,z,void 0),b.uniform1f(o.alphaTest,z.alphaTest),b.uniformMatrix4fv(o.modelViewMatrix,!1,x.modelViewMatrix.elements),x.matrixWorld.decompose(q,r,s),y[0]=s.x,y[1]=s.y;var A=0;f.fog&&z.fog&&(A=t),i!==A&&(b.uniform1i(o.fogType,A),i=A),null!==z.map?(b.uniform2f(o.uvOffset,z.map.offset.x,z.map.offset.y),b.uniform2f(o.uvScale,z.map.repeat.x,z.map.repeat.y)):(b.uniform2f(o.uvOffset,0,0),b.uniform2f(o.uvScale,1,1)),b.uniform1f(o.opacity,z.opacity),b.uniform3f(o.color,z.color.r,z.color.g,z.color.b),b.uniform1f(o.rotation,z.rotation),b.uniform2fv(o.scale,y),c.setBlending(z.blending,z.blendEquation,z.blendSrc,z.blendDst,z.blendEquationAlpha,z.blendSrcAlpha,z.blendDstAlpha,z.premultipliedAlpha),c.buffers.depth.setTest(z.depthTest),c.buffers.depth.setMask(z.depthWrite),c.buffers.color.setMask(z.colorWrite),d.setTexture2D(z.map||p,0),b.drawElements(b.TRIANGLES,6,b.UNSIGNED_SHORT,0),x.onAfterRender(a,f,g,void 0,z,void 0)}}c.enable(b.CULL_FACE),c.reset()}}}function Z(){Object.defineProperty(this,"id",{value:Of++}),this.uuid=yd.generateUUID(),this.name="",this.type="Material",this.fog=!0,this.lights=!0,this.blending=Mb,this.side=Gb,this.flatShading=!1,this.vertexColors=Kb,this.opacity=1,this.transparent=!1,this.blendSrc=$b,this.blendDst=_b,this.blendEquation=Rb,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.depthFunc=ic,this.depthTest=!0,this.depthWrite=!0,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaTest=0,this.premultipliedAlpha=!1,this.overdraw=0,this.visible=!0,this.userData={},this.needsUpdate=!0}function $(a){Z.call(this),this.type="MeshDepthMaterial",this.depthPacking=wd,this.skinning=!1,this.morphTargets=!1,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.setValues(a)}function _(a){Z.call(this),this.type="MeshDistanceMaterial",this.referencePosition=new f,this.nearDistance=1,this.farDistance=1e3,this.skinning=!1,this.morphTargets=!1,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.fog=!1,this.lights=!1,this.setValues(a)}function aa(a,b){this.min=void 0!==a?a:new f(1/0,1/0,1/0),this.max=void 0!==b?b:new f(-1/0,-1/0,-1/0)}function ba(a,b){this.center=void 0!==a?a:new f,this.radius=void 0!==b?b:0}function ca(a,b){this.normal=void 0!==a?a:new f(1,0,0),this.constant=void 0!==b?b:0}function da(a,b,c,d,e,f){this.planes=[void 0!==a?a:new ca,void 0!==b?b:new ca,void 0!==c?c:new ca,void 0!==d?d:new ca,void 0!==e?e:new ca,void 0!==f?f:new ca]}function ea(a,b,e){function g(b,c,d,e,f,g){var h=b.geometry,i=null,j=t,k=b.customDepthMaterial;if(d&&(j=u,k=b.customDistanceMaterial),k)i=k;else{var l=!1;c.morphTargets&&(h&&h.isBufferGeometry?l=h.morphAttributes&&h.morphAttributes.position&&h.morphAttributes.position.length>0:h&&h.isGeometry&&(l=h.morphTargets&&h.morphTargets.length>0)),b.isSkinnedMesh&&!1===c.skinning&&console.warn("THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:",b);var m=b.isSkinnedMesh&&c.skinning,n=0;l&&(n|=q),m&&(n|=r),i=j[n]}if(a.localClippingEnabled&&!0===c.clipShadows&&0!==c.clippingPlanes.length){var o=i.uuid,p=c.uuid,s=v[o];void 0===s&&(s={},v[o]=s);var w=s[p];void 0===w&&(w=i.clone(),s[p]=w),i=w}i.visible=c.visible,i.wireframe=c.wireframe;var x=c.side;return E.renderSingleSided&&x==Ib&&(x=Gb),E.renderReverseSided&&(x===Gb?x=Hb:x===Hb&&(x=Gb)),i.side=x,i.clipShadows=c.clipShadows,i.clippingPlanes=c.clippingPlanes,i.clipIntersection=c.clipIntersection,i.wireframeLinewidth=c.wireframeLinewidth,i.linewidth=c.linewidth,d&&i.isMeshDistanceMaterial&&(i.referencePosition.copy(e),i.nearDistance=f,i.farDistance=g),i}function h(c,d,e,f){if(!1!==c.visible){if(c.layers.test(d.layers)&&(c.isMesh||c.isLine||c.isPoints)&&c.castShadow&&(!c.frustumCulled||k.intersectsObject(c))){c.modelViewMatrix.multiplyMatrices(e.matrixWorldInverse,c.matrixWorld);var i=b.update(c),j=c.material;if(Array.isArray(j))for(var l=i.groups,m=0,n=l.length;m<n;m++){var o=l[m],q=j[o.materialIndex];if(q&&q.visible){var r=g(c,q,f,p,e.near,e.far);a.renderBufferDirect(e,null,i,r,c,o)}}else if(j.visible){var r=g(c,j,f,p,e.near,e.far);a.renderBufferDirect(e,null,i,r,c,null)}}for(var s=c.children,t=0,u=s.length;t<u;t++)h(s[t],d,e,f)}}for(var k=new da,l=new d,m=new c,n=new c(e,e),o=new f,p=new f,q=1,r=2,s=1+(q|r),t=new Array(s),u=new Array(s),v={},w=[new f(1,0,0),new f(-1,0,0),new f(0,0,1),new f(0,0,-1),new f(0,1,0),new f(0,-1,0)],x=[new f(0,1,0),new f(0,1,0),new f(0,1,0),new f(0,1,0),new f(0,0,1),new f(0,0,-1)],y=[new i,new i,new i,new i,new i,new i],z=0;z!==s;++z){var A=0!=(z&q),B=0!=(z&r),C=new $({depthPacking:xd,morphTargets:A,skinning:B});t[z]=C;var D=new _({morphTargets:A,skinning:B});u[z]=D}var E=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Eb,this.renderReverseSided=!0,this.renderSingleSided=!0,this.render=function(b,c,d){if(!1!==E.enabled&&(!1!==E.autoUpdate||!1!==E.needsUpdate)&&0!==b.length){var e=a.context,f=a.state;f.disable(e.BLEND),f.buffers.color.setClear(1,1,1,1),f.buffers.depth.setTest(!0),f.setScissorTest(!1);for(var g,i=0,q=b.length;i<q;i++){var r=b[i],s=r.shadow,t=r&&r.isPointLight;if(void 0!==s){var u=s.camera;if(m.copy(s.mapSize),m.min(n),t){var v=m.x,z=m.y;y[0].set(2*v,z,v,z),y[1].set(0,z,v,z),y[2].set(3*v,z,v,z),y[3].set(v,z,v,z),y[4].set(3*v,0,v,z),y[5].set(v,0,v,z),m.x*=4,m.y*=2}if(null===s.map){var A={minFilter:Gc,magFilter:Gc,format:$c};s.map=new j(m.x,m.y,A),s.map.texture.name=r.name+".shadowMap",u.updateProjectionMatrix()}s.isSpotLightShadow&&s.update(r);var B=s.map,C=s.matrix;p.setFromMatrixPosition(r.matrixWorld),u.position.copy(p),t?(g=6,C.makeTranslation(-p.x,-p.y,-p.z)):(g=1,o.setFromMatrixPosition(r.target.matrixWorld),u.lookAt(o),u.updateMatrixWorld(),C.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),C.multiply(u.projectionMatrix),C.multiply(u.matrixWorldInverse)),a.setRenderTarget(B),a.clear();for(var D=0;D<g;D++){if(t){o.copy(u.position),o.add(w[D]),u.up.copy(x[D]),u.lookAt(o),u.updateMatrixWorld();var F=y[D];f.viewport(F)}l.multiplyMatrices(u.projectionMatrix,u.matrixWorldInverse),k.setFromMatrix(l),h(c,d,u,t)}}else console.warn("THREE.WebGLShadowMap:",r,"has no shadow.")}E.needsUpdate=!1}}}function fa(a){function b(b,c){var d=b.array,e=b.dynamic?a.DYNAMIC_DRAW:a.STATIC_DRAW,f=a.createBuffer();a.bindBuffer(c,f),a.bufferData(c,d,e),b.onUploadCallback();var g=a.FLOAT;return d instanceof Float32Array?g=a.FLOAT:d instanceof Float64Array?console.warn("THREE.WebGLAttributes: Unsupported data buffer format: Float64Array."):d instanceof Uint16Array?g=a.UNSIGNED_SHORT:d instanceof Int16Array?g=a.SHORT:d instanceof Uint32Array?g=a.UNSIGNED_INT:d instanceof Int32Array?g=a.INT:d instanceof Int8Array?g=a.BYTE:d instanceof Uint8Array&&(g=a.UNSIGNED_BYTE),{buffer:f,type:g,bytesPerElement:d.BYTES_PER_ELEMENT,version:b.version}}function c(b,c,d){var e=c.array,f=c.updateRange;a.bindBuffer(d,b),!1===c.dynamic?a.bufferData(d,e,a.STATIC_DRAW):-1===f.count?a.bufferSubData(d,0,e):0===f.count?console.error("THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually."):(a.bufferSubData(d,f.offset*e.BYTES_PER_ELEMENT,e.subarray(f.offset,f.offset+f.count)),f.count=-1)}function d(a){return a.isInterleavedBufferAttribute&&(a=a.data),g[a.uuid]}function e(b){b.isInterleavedBufferAttribute&&(b=b.data);var c=g[b.uuid];c&&(a.deleteBuffer(c.buffer),delete g[b.uuid])}function f(a,d){a.isInterleavedBufferAttribute&&(a=a.data);var e=g[a.uuid];void 0===e?g[a.uuid]=b(a,d):e.version<a.version&&(c(e.buffer,a,d),e.version=a.version)}var g={};return{get:d,remove:e,update:f}}function ga(a,b,c,d){this._x=a||0,this._y=b||0,this._z=c||0,this._order=d||ga.DefaultOrder}function ha(){this.mask=1}function ia(){function a(){i.setFromEuler(h,!1)}function b(){h.setFromQuaternion(i,void 0,!1)}Object.defineProperty(this,"id",{value:Pf++}),this.uuid=yd.generateUUID(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=ia.DefaultUp.clone();var c=new f,h=new ga,i=new e,j=new f(1,1,1);h.onChange(a),i.onChange(b),Object.defineProperties(this,{position:{enumerable:!0,value:c},rotation:{enumerable:!0,value:h},quaternion:{enumerable:!0,value:i},scale:{enumerable:!0,value:j},modelViewMatrix:{value:new d},normalMatrix:{value:new g}}),this.matrix=new d,this.matrixWorld=new d,this.matrixAutoUpdate=ia.DefaultMatrixAutoUpdate,this.matrixWorldNeedsUpdate=!1,this.layers=new ha,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.userData={}}function ja(){ia.call(this),this.type="Camera",this.matrixWorldInverse=new d,this.projectionMatrix=new d}function ka(a,b,c,d,e,f){ja.call(this),this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=a,this.right=b,this.top=c,this.bottom=d,this.near=void 0!==e?e:.1,this.far=void 0!==f?f:2e3,this.updateProjectionMatrix()}function la(a,b,c,d,e,g){this.a=a,this.b=b,this.c=c,this.normal=d&&d.isVector3?d:new f,this.vertexNormals=Array.isArray(d)?d:[],this.color=e&&e.isColor?e:new U,this.vertexColors=Array.isArray(e)?e:[],this.materialIndex=void 0!==g?g:0}function ma(){Object.defineProperty(this,"id",{value:Qf+=2}),this.uuid=yd.generateUUID(),this.name="",this.type="Geometry",this.vertices=[],this.colors=[],this.faces=[],this.faceVertexUvs=[[]],this.morphTargets=[],this.morphNormals=[],this.skinWeights=[],this.skinIndices=[],this.lineDistances=[],this.boundingBox=null,this.boundingSphere=null,this.elementsNeedUpdate=!1,this.verticesNeedUpdate=!1,this.uvsNeedUpdate=!1,this.normalsNeedUpdate=!1,this.colorsNeedUpdate=!1,this.lineDistancesNeedUpdate=!1,this.groupsNeedUpdate=!1}function na(a,b,c){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.uuid=yd.generateUUID(),this.name="",this.array=a,this.itemSize=b,this.count=void 0!==a?a.length/b:0,this.normalized=!0===c,this.dynamic=!1,this.updateRange={offset:0,count:-1},this.onUploadCallback=function(){},this.version=0}function oa(a,b,c){na.call(this,new Int8Array(a),b,c)}function pa(a,b,c){na.call(this,new Uint8Array(a),b,c)}function qa(a,b,c){na.call(this,new Uint8ClampedArray(a),b,c)}function ra(a,b,c){na.call(this,new Int16Array(a),b,c)}function sa(a,b,c){na.call(this,new Uint16Array(a),b,c)}function ta(a,b,c){na.call(this,new Int32Array(a),b,c)}function ua(a,b,c){na.call(this,new Uint32Array(a),b,c)}function va(a,b,c){na.call(this,new Float32Array(a),b,c)}function wa(a,b,c){na.call(this,new Float64Array(a),b,c)}function xa(){this.indices=[],this.vertices=[],this.normals=[],this.colors=[],this.uvs=[],this.uvs2=[],this.groups=[],this.morphTargets={},this.skinWeights=[],this.skinIndices=[],this.boundingBox=null,this.boundingSphere=null,this.verticesNeedUpdate=!1,this.normalsNeedUpdate=!1,this.colorsNeedUpdate=!1,this.uvsNeedUpdate=!1,this.groupsNeedUpdate=!1}function ya(a){if(0===a.length)return-1/0;for(var b=a[0],c=1,d=a.length;c<d;++c)a[c]>b&&(b=a[c]);return b}function za(){Object.defineProperty(this,"id",{value:Rf+=2}),this.uuid=yd.generateUUID(),this.name="",this.type="BufferGeometry",this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0}}function Aa(a,b,c,d,e,f){ma.call(this),this.type="BoxGeometry",this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:f},this.fromBufferGeometry(new Ba(a,b,c,d,e,f)),this.mergeVertices()}function Ba(a,b,c,d,e,g){function h(a,b,c,d,e,g,h,p,q,r,s){var t,u,v=g/q,w=h/r,x=g/2,y=h/2,z=p/2,A=q+1,B=r+1,C=0,D=0,E=new f;for(u=0;u<B;u++){var F=u*w-y;for(t=0;t<A;t++){var G=t*v-x;E[a]=G*d,E[b]=F*e,E[c]=z,k.push(E.x,E.y,E.z),E[a]=0,E[b]=0,E[c]=p>0?1:-1,l.push(E.x,E.y,E.z),m.push(t/q),m.push(1-u/r),C+=1}}for(u=0;u<r;u++)for(t=0;t<q;t++){var H=n+t+A*u,I=n+t+A*(u+1),J=n+(t+1)+A*(u+1),K=n+(t+1)+A*u;j.push(H,I,K),j.push(I,J,K),D+=6}i.addGroup(o,D,s),o+=D,n+=C}za.call(this),this.type="BoxBufferGeometry",this.parameters={width:a,height:b,depth:c,widthSegments:d,heightSegments:e,depthSegments:g};var i=this;a=a||1,b=b||1,c=c||1,d=Math.floor(d)||1,e=Math.floor(e)||1,g=Math.floor(g)||1;var j=[],k=[],l=[],m=[],n=0,o=0;h("z","y","x",-1,-1,c,b,a,g,e,0),h("z","y","x",1,-1,c,b,-a,g,e,1),h("x","z","y",1,1,a,c,b,d,g,2),h("x","z","y",1,-1,a,c,-b,d,g,3),h("x","y","z",1,-1,a,b,c,d,e,4),h("x","y","z",-1,-1,a,b,-c,d,e,5),this.setIndex(j),this.addAttribute("position",new va(k,3)),this.addAttribute("normal",new va(l,3)),this.addAttribute("uv",new va(m,2))}function Ca(a,b,c,d){ma.call(this),this.type="PlaneGeometry",this.parameters={width:a,height:b,widthSegments:c,heightSegments:d},this.fromBufferGeometry(new Da(a,b,c,d)),this.mergeVertices()}function Da(a,b,c,d){za.call(this),this.type="PlaneBufferGeometry",this.parameters={width:a,height:b,widthSegments:c,heightSegments:d},a=a||1,b=b||1;var e,f,g=a/2,h=b/2,i=Math.floor(c)||1,j=Math.floor(d)||1,k=i+1,l=j+1,m=a/i,n=b/j,o=[],p=[],q=[],r=[];for(f=0;f<l;f++){var s=f*n-h;for(e=0;e<k;e++){var t=e*m-g;p.push(t,-s,0),q.push(0,0,1),r.push(e/i),r.push(1-f/j)}}for(f=0;f<j;f++)for(e=0;e<i;e++){var u=e+k*f,v=e+k*(f+1),w=e+1+k*(f+1),x=e+1+k*f;o.push(u,v,x),o.push(v,w,x)}this.setIndex(o),this.addAttribute("position",new va(p,3)),this.addAttribute("normal",new va(q,3)),this.addAttribute("uv",new va(r,2))}function Ea(a){Z.call(this),this.type="MeshBasicMaterial",this.color=new U(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=nc,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.skinning=!1,this.morphTargets=!1,this.lights=!1,this.setValues(a)}function Fa(a){Z.call(this),this.type="ShaderMaterial",this.defines={},this.uniforms={},this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.skinning=!1,this.morphTargets=!1,this.morphNormals=!1,this.extensions={derivatives:!1,fragDepth:!1,drawBuffers:!1,shaderTextureLOD:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv2:[0,0]},this.index0AttributeName=void 0,void 0!==a&&(void 0!==a.attributes&&console.error("THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead."),this.setValues(a))}function Ga(a,b){this.origin=void 0!==a?a:new f,this.direction=void 0!==b?b:new f}function Ha(a,b){this.start=void 0!==a?a:new f,this.end=void 0!==b?b:new f}function Ia(a,b,c){this.a=void 0!==a?a:new f,this.b=void 0!==b?b:new f,this.c=void 0!==c?c:new f}function Ja(a,b){ia.call(this),this.type="Mesh",this.geometry=void 0!==a?a:new za,this.material=void 0!==b?b:new Ea({color:16777215*Math.random()}),this.drawMode=md,this.updateMorphTargets()}function Ka(a,b,c,d){function e(b,d,e,l){var m=d.background;null===m?f(j,k):m&&m.isColor&&(f(m,1),l=!0),(a.autoClear||l)&&a.clear(a.autoClearColor,a.autoClearDepth,a.autoClearStencil),m&&m.isCubeTexture?(void 0===i&&(i=new Ja(new Ba(1,1,1),new Fa({uniforms:Nf.cube.uniforms,vertexShader:Nf.cube.vertexShader,fragmentShader:Nf.cube.fragmentShader,side:Hb,depthTest:!0,depthWrite:!1,fog:!1})),i.geometry.removeAttribute("normal"),i.geometry.removeAttribute("uv"),i.onBeforeRender=function(a,b,c){this.matrixWorld.copyPosition(c.matrixWorld)},c.update(i.geometry)),i.material.uniforms.tCube.value=m,b.push(i,i.geometry,i.material,0,null)):m&&m.isTexture&&(void 0===g&&(g=new ka(-1,1,1,-1,0,1),h=new Ja(new Da(2,2),new Ea({depthTest:!1,depthWrite:!1,fog:!1})),c.update(h.geometry)),h.material.map=m,a.renderBufferDirect(g,null,h.geometry,h.material,h,null))}function f(a,c){b.buffers.color.setClear(a.r,a.g,a.b,c,d)}var g,h,i,j=new U(0),k=0;return{getClearColor:function(){return j},setClearColor:function(a,b){j.set(a),k=void 0!==b?b:1,f(j,k)},getClearAlpha:function(){return k},setClearAlpha:function(a){k=a,f(j,k)},render:e}}function La(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.program&&b.program&&a.program!==b.program?a.program.id-b.program.id:a.material.id!==b.material.id?a.material.id-b.material.id:a.z!==b.z?a.z-b.z:a.id-b.id}function Ma(a,b){return a.renderOrder!==b.renderOrder?a.renderOrder-b.renderOrder:a.z!==b.z?b.z-a.z:a.id-b.id}function Na(){function a(){e=0,f.length=0,g.length=0}function b(a,b,c,h,i){var j=d[e];void 0===j?(j={id:a.id,object:a,geometry:b,material:c,program:c.program,renderOrder:a.renderOrder,z:h,group:i},d[e]=j):(j.id=a.id,j.object=a,j.geometry=b,j.material=c,j.program=c.program,j.renderOrder=a.renderOrder,j.z=h,j.group=i),(!0===c.transparent?g:f).push(j),e++}function c(){f.length>1&&f.sort(La),g.length>1&&g.sort(Ma)}var d=[],e=0,f=[],g=[];return{opaque:f,transparent:g,init:a,push:b,sort:c}}function Oa(){function a(a,b){var d=a.id+","+b.id,e=c[d];return void 0===e&&(e=new Na,c[d]=e),e}function b(){c={}}var c={};return{get:a,dispose:b}}function Pa(a,b){return Math.abs(b[1])-Math.abs(a[1])}function Qa(a){function b(b,e,f,g){var h=b.morphTargetInfluences,i=h.length,j=c[e.id];if(void 0===j){j=[];for(var k=0;k<i;k++)j[k]=[k,0];c[e.id]=j}for(var l=f.morphTargets&&e.morphAttributes.position,m=f.morphNormals&&e.morphAttributes.normal,k=0;k<i;k++){var n=j[k];0!==n[1]&&(l&&e.removeAttribute("morphTarget"+k),m&&e.removeAttribute("morphNormal"+k))}for(var k=0;k<i;k++){var n=j[k];n[0]=k,n[1]=h[k]}j.sort(Pa);for(var k=0;k<8;k++){var n=j[k];if(n){var o=n[0],p=n[1];if(p){l&&e.addAttribute("morphTarget"+k,l[o]),m&&e.addAttribute("morphNormal"+k,m[o]),d[k]=p;continue}}d[k]=0}g.getUniforms().setValue(a,"morphTargetInfluences",d)}var c={},d=new Float32Array(8);return{update:b}}function Ra(a,b,c){function d(a){h=a}function e(a){i=a.type,j=a.bytesPerElement}function f(b,d){a.drawElements(h,d,i,b*j),c.calls++,c.vertices+=d,h===a.TRIANGLES?c.faces+=d/3:h===a.POINTS&&(c.points+=d)}function g(d,e,f){var g=b.get("ANGLE_instanced_arrays");if(null===g)return void console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");g.drawElementsInstancedANGLE(h,f,i,e*j,d.maxInstancedCount),c.calls++,c.vertices+=f*d.maxInstancedCount,h===a.TRIANGLES?c.faces+=d.maxInstancedCount*f/3:h===a.POINTS&&(c.points+=d.maxInstancedCount*f)}var h,i,j;this.setMode=d,this.setIndex=e,this.render=f,this.renderInstances=g}function Sa(a,b,c){function d(a){g=a}function e(b,d){a.drawArrays(g,b,d),c.calls++,c.vertices+=d,g===a.TRIANGLES?c.faces+=d/3:g===a.POINTS&&(c.points+=d)}function f(d,e,f){var h=b.get("ANGLE_instanced_arrays");if(null===h)return void console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");var i=d.attributes.position;i.isInterleavedBufferAttribute?(f=i.data.count,h.drawArraysInstancedANGLE(g,0,f,d.maxInstancedCount)):h.drawArraysInstancedANGLE(g,e,f,d.maxInstancedCount),c.calls++,c.vertices+=f*d.maxInstancedCount,g===a.TRIANGLES?c.faces+=d.maxInstancedCount*f/3:g===a.POINTS&&(c.points+=d.maxInstancedCount*f)}var g;this.setMode=d,this.render=e,this.renderInstances=f}function Ta(a,b,c){function d(a){var e=a.target,f=h[e.id];null!==f.index&&b.remove(f.index);for(var g in f.attributes)b.remove(f.attributes[g]);e.removeEventListener("dispose",d),delete h[e.id];var j=i[e.id];j&&(b.remove(j),delete i[e.id]),j=i[f.id],j&&(b.remove(j),delete i[f.id]),c.geometries--}function e(a,b){var e=h[b.id];return e||(b.addEventListener("dispose",d),b.isBufferGeometry?e=b:b.isGeometry&&(void 0===b._bufferGeometry&&(b._bufferGeometry=(new za).setFromObject(a)),e=b._bufferGeometry),h[b.id]=e,c.geometries++,e)}function f(c){var d=c.index,e=c.attributes;null!==d&&b.update(d,a.ELEMENT_ARRAY_BUFFER);for(var f in e)b.update(e[f],a.ARRAY_BUFFER);var g=c.morphAttributes;for(var f in g)for(var h=g[f],i=0,j=h.length;i<j;i++)b.update(h[i],a.ARRAY_BUFFER)}function g(c){var d=i[c.id];if(d)return d;var e=[],f=c.index,g=c.attributes;if(null!==f)for(var h=f.array,j=0,k=h.length;j<k;j+=3){var l=h[j+0],m=h[j+1],n=h[j+2];e.push(l,m,m,n,n,l)}else for(var h=g.position.array,j=0,k=h.length/3-1;j<k;j+=3){var l=j+0,m=j+1,n=j+2;e.push(l,m,m,n,n,l)}return d=new(ya(e)>65535?ua:sa)(e,1),b.update(d,a.ELEMENT_ARRAY_BUFFER),i[c.id]=d,d}var h={},i={};return{get:e,update:f,getWireframeAttribute:g}}function Ua(){var a={};return{get:function(b){if(void 0!==a[b.id])return a[b.id];var d;switch(b.type){case"DirectionalLight":d={direction:new f,color:new U,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new c};break;case"SpotLight":d={position:new f,direction:new f,color:new U,distance:0,coneCos:0,penumbraCos:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new c};break;case"PointLight":d={position:new f,color:new U,distance:0,decay:0,shadow:!1,shadowBias:0,shadowRadius:1,shadowMapSize:new c,shadowCameraNear:1,shadowCameraFar:1e3};break;case"HemisphereLight":d={direction:new f,skyColor:new U,groundColor:new U};break;case"RectAreaLight":d={color:new U,position:new f,halfWidth:new f,halfHeight:new f}}return a[b.id]=d,d}}}function Va(){function a(a,d,f){for(var i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=f.matrixWorldInverse,r=0,s=a.length;r<s;r++){var t=a[r],u=t.color,v=t.intensity,w=t.distance,x=t.shadow&&t.shadow.map?t.shadow.map.texture:null;if(t.isAmbientLight)i+=u.r*v,j+=u.g*v,k+=u.b*v;else if(t.isDirectionalLight){var y=b.get(t);if(y.color.copy(t.color).multiplyScalar(t.intensity),y.direction.setFromMatrixPosition(t.matrixWorld),e.setFromMatrixPosition(t.target.matrixWorld),y.direction.sub(e),y.direction.transformDirection(q),y.shadow=t.castShadow,t.castShadow){var z=t.shadow;y.shadowBias=z.bias,y.shadowRadius=z.radius,y.shadowMapSize=z.mapSize}c.directionalShadowMap[l]=x,c.directionalShadowMatrix[l]=t.shadow.matrix,c.directional[l]=y,l++}else if(t.isSpotLight){var y=b.get(t);if(y.position.setFromMatrixPosition(t.matrixWorld),y.position.applyMatrix4(q),y.color.copy(u).multiplyScalar(v),y.distance=w,y.direction.setFromMatrixPosition(t.matrixWorld),e.setFromMatrixPosition(t.target.matrixWorld),y.direction.sub(e),y.direction.transformDirection(q),y.coneCos=Math.cos(t.angle),y.penumbraCos=Math.cos(t.angle*(1-t.penumbra)),y.decay=0===t.distance?0:t.decay,y.shadow=t.castShadow,t.castShadow){var z=t.shadow;y.shadowBias=z.bias,y.shadowRadius=z.radius,y.shadowMapSize=z.mapSize}c.spotShadowMap[n]=x,c.spotShadowMatrix[n]=t.shadow.matrix,c.spot[n]=y,n++}else if(t.isRectAreaLight){var y=b.get(t);y.color.copy(u).multiplyScalar(v/(t.width*t.height)),y.position.setFromMatrixPosition(t.matrixWorld),y.position.applyMatrix4(q),h.identity(),g.copy(t.matrixWorld),g.premultiply(q),h.extractRotation(g),y.halfWidth.set(.5*t.width,0,0),y.halfHeight.set(0,.5*t.height,0),y.halfWidth.applyMatrix4(h),y.halfHeight.applyMatrix4(h),c.rectArea[o]=y,o++}else if(t.isPointLight){var y=b.get(t);if(y.position.setFromMatrixPosition(t.matrixWorld),y.position.applyMatrix4(q),y.color.copy(t.color).multiplyScalar(t.intensity),y.distance=t.distance,y.decay=0===t.distance?0:t.decay,y.shadow=t.castShadow,t.castShadow){var z=t.shadow;y.shadowBias=z.bias,y.shadowRadius=z.radius,y.shadowMapSize=z.mapSize,y.shadowCameraNear=z.camera.near,y.shadowCameraFar=z.camera.far}c.pointShadowMap[m]=x,c.pointShadowMatrix[m]=t.shadow.matrix,c.point[m]=y,m++}else if(t.isHemisphereLight){var y=b.get(t);y.direction.setFromMatrixPosition(t.matrixWorld),y.direction.transformDirection(q),y.direction.normalize(),y.skyColor.copy(t.color).multiplyScalar(v),y.groundColor.copy(t.groundColor).multiplyScalar(v),c.hemi[p]=y,p++}}c.ambient[0]=i,c.ambient[1]=j,c.ambient[2]=k,c.directional.length=l,c.spot.length=n,c.rectArea.length=o,c.point.length=m,c.hemi.length=p,c.hash=l+","+m+","+n+","+o+","+p+","+d.length}var b=new Ua,c={hash:"",ambient:[0,0,0],directional:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],point:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]},e=new f,g=new d,h=new d;return{setup:a,state:c}}function Wa(a,b){function c(c){var d=b.frame,f=c.geometry,g=a.get(c,f);return e[g.id]!==d&&(f.isGeometry&&g.updateFromObject(c),a.update(g),e[g.id]=d),g}function d(){e={}}var e={};return{update:c,clear:d}}function Xa(a){for(var b=a.split("\n"),c=0;c<b.length;c++)b[c]=c+1+": "+b[c];return b.join("\n")}function Ya(a,b,c){var d=a.createShader(b);return a.shaderSource(d,c),a.compileShader(d),!1===a.getShaderParameter(d,a.COMPILE_STATUS)&&console.error("THREE.WebGLShader: Shader couldn't compile."),""!==a.getShaderInfoLog(d)&&console.warn("THREE.WebGLShader: gl.getShaderInfoLog()",b===a.VERTEX_SHADER?"vertex":"fragment",a.getShaderInfoLog(d),Xa(c)),d}function Za(a){switch(a){case pd:return["Linear","( value )"];case qd:return["sRGB","( value )"];case sd:return["RGBE","( value )"];case td:return["RGBM","( value, 7.0 )"];case ud:return["RGBM","( value, 16.0 )"];case vd:return["RGBD","( value, 256.0 )"];case rd:return["Gamma","( value, float( GAMMA_FACTOR ) )"];default:throw new Error("unsupported encoding: "+a)}}function $a(a,b){var c=Za(b);return"vec4 "+a+"( vec4 value ) { return "+c[0]+"ToLinear"+c[1]+"; }"}function _a(a,b){var c=Za(b);return"vec4 "+a+"( vec4 value ) { return LinearTo"+c[0]+c[1]+"; }"}function ab(a,b){var c;switch(b){case rc:c="Linear";break;case sc:c="Reinhard";break;case tc:c="Uncharted2";break;case uc:c="OptimizedCineon";break;default:throw new Error("unsupported toneMapping: "+b)}return"vec3 "+a+"( vec3 color ) { return "+c+"ToneMapping( color ); }"}function bb(a,b,c){return a=a||{},[a.derivatives||b.envMapCubeUV||b.bumpMap||b.normalMap||b.flatShading?"#extension GL_OES_standard_derivatives : enable":"",(a.fragDepth||b.logarithmicDepthBuffer)&&c.get("EXT_frag_depth")?"#extension GL_EXT_frag_depth : enable":"",a.drawBuffers&&c.get("WEBGL_draw_buffers")?"#extension GL_EXT_draw_buffers : require":"",(a.shaderTextureLOD||b.envMap)&&c.get("EXT_shader_texture_lod")?"#extension GL_EXT_shader_texture_lod : enable":""].filter(eb).join("\n")}function cb(a){var b=[];for(var c in a){var d=a[c];!1!==d&&b.push("#define "+c+" "+d)}return b.join("\n")}function db(a,b){for(var c={},d=a.getProgramParameter(b,a.ACTIVE_ATTRIBUTES),e=0;e<d;e++){var f=a.getActiveAttrib(b,e),g=f.name;c[g]=a.getAttribLocation(b,g)}return c}function eb(a){return""!==a}function fb(a,b){return a.replace(/NUM_DIR_LIGHTS/g,b.numDirLights).replace(/NUM_SPOT_LIGHTS/g,b.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,b.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,b.numPointLights).replace(/NUM_HEMI_LIGHTS/g,b.numHemiLights)}function gb(a){function b(a,b){var c=Mf[b];if(void 0===c)throw new Error("Can not resolve #include <"+b+">");return gb(c)}var c=/^[ \t]*#include +<([\w\d.]+)>/gm;return a.replace(c,b)}function hb(a){function b(a,b,c,d){for(var e="",f=parseInt(b);f<parseInt(c);f++)e+=d.replace(/\[ i \]/g,"[ "+f+" ]");return e}var c=/for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;return a.replace(c,b)}function ib(a,b,c,d,e,f){var g=a.context,h=d.defines,i=e.vertexShader,j=e.fragmentShader,k="SHADOWMAP_TYPE_BASIC";f.shadowMapType===Eb?k="SHADOWMAP_TYPE_PCF":f.shadowMapType===Fb&&(k="SHADOWMAP_TYPE_PCF_SOFT");var l="ENVMAP_TYPE_CUBE",m="ENVMAP_MODE_REFLECTION",n="ENVMAP_BLENDING_MULTIPLY";if(f.envMap){switch(d.envMap.mapping){case wc:case xc:l="ENVMAP_TYPE_CUBE";break;case Bc:case Cc:l="ENVMAP_TYPE_CUBE_UV";break;case yc:case zc:l="ENVMAP_TYPE_EQUIREC";break;case Ac:l="ENVMAP_TYPE_SPHERE"}switch(d.envMap.mapping){case xc:case zc:m="ENVMAP_MODE_REFRACTION"}switch(d.combine){case nc:n="ENVMAP_BLENDING_MULTIPLY";break;case oc:n="ENVMAP_BLENDING_MIX";break;case pc:n="ENVMAP_BLENDING_ADD"}}var o,p,q=a.gammaFactor>0?a.gammaFactor:1,r=bb(d.extensions,f,b),s=cb(h),t=g.createProgram();d.isRawShaderMaterial?(o=[s].filter(eb).join("\n"),o.length>0&&(o+="\n"),p=[r,s].filter(eb).join("\n"),p.length>0&&(p+="\n")):(o=["precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,s,f.supportsVertexTextures?"#define VERTEX_TEXTURES":"","#define GAMMA_FACTOR "+q,"#define MAX_BONES "+f.maxBones,f.useFog&&f.fog?"#define USE_FOG":"",f.useFog&&f.fogExp?"#define FOG_EXP2":"",f.map?"#define USE_MAP":"",f.envMap?"#define USE_ENVMAP":"",f.envMap?"#define "+m:"",f.lightMap?"#define USE_LIGHTMAP":"",f.aoMap?"#define USE_AOMAP":"",f.emissiveMap?"#define USE_EMISSIVEMAP":"",f.bumpMap?"#define USE_BUMPMAP":"",f.normalMap?"#define USE_NORMALMAP":"",f.displacementMap&&f.supportsVertexTextures?"#define USE_DISPLACEMENTMAP":"",f.specularMap?"#define USE_SPECULARMAP":"",f.roughnessMap?"#define USE_ROUGHNESSMAP":"",f.metalnessMap?"#define USE_METALNESSMAP":"",f.alphaMap?"#define USE_ALPHAMAP":"",f.vertexColors?"#define USE_COLOR":"",f.flatShading?"#define FLAT_SHADED":"",f.skinning?"#define USE_SKINNING":"",f.useVertexTexture?"#define BONE_TEXTURE":"",f.morphTargets?"#define USE_MORPHTARGETS":"",f.morphNormals&&!1===f.flatShading?"#define USE_MORPHNORMALS":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+f.numClippingPlanes,f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+k:"",f.sizeAttenuation?"#define USE_SIZEATTENUATION":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&b.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_COLOR","\tattribute vec3 color;","#endif","#ifdef USE_MORPHTARGETS","\tattribute vec3 morphTarget0;","\tattribute vec3 morphTarget1;","\tattribute vec3 morphTarget2;","\tattribute vec3 morphTarget3;","\t#ifdef USE_MORPHNORMALS","\t\tattribute vec3 morphNormal0;","\t\tattribute vec3 morphNormal1;","\t\tattribute vec3 morphNormal2;","\t\tattribute vec3 morphNormal3;","\t#else","\t\tattribute vec3 morphTarget4;","\t\tattribute vec3 morphTarget5;","\t\tattribute vec3 morphTarget6;","\t\tattribute vec3 morphTarget7;","\t#endif","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(eb).join("\n"),p=[r,"precision "+f.precision+" float;","precision "+f.precision+" int;","#define SHADER_NAME "+e.name,s,f.alphaTest?"#define ALPHATEST "+f.alphaTest:"","#define GAMMA_FACTOR "+q,f.useFog&&f.fog?"#define USE_FOG":"",f.useFog&&f.fogExp?"#define FOG_EXP2":"",f.map?"#define USE_MAP":"",f.envMap?"#define USE_ENVMAP":"",f.envMap?"#define "+l:"",f.envMap?"#define "+m:"",f.envMap?"#define "+n:"",f.lightMap?"#define USE_LIGHTMAP":"",f.aoMap?"#define USE_AOMAP":"",f.emissiveMap?"#define USE_EMISSIVEMAP":"",f.bumpMap?"#define USE_BUMPMAP":"",f.normalMap?"#define USE_NORMALMAP":"",f.specularMap?"#define USE_SPECULARMAP":"",f.roughnessMap?"#define USE_ROUGHNESSMAP":"",f.metalnessMap?"#define USE_METALNESSMAP":"",f.alphaMap?"#define USE_ALPHAMAP":"",f.vertexColors?"#define USE_COLOR":"",f.gradientMap?"#define USE_GRADIENTMAP":"",f.flatShading?"#define FLAT_SHADED":"",f.doubleSided?"#define DOUBLE_SIDED":"",f.flipSided?"#define FLIP_SIDED":"","#define NUM_CLIPPING_PLANES "+f.numClippingPlanes,"#define UNION_CLIPPING_PLANES "+(f.numClippingPlanes-f.numClipIntersection),f.shadowMapEnabled?"#define USE_SHADOWMAP":"",f.shadowMapEnabled?"#define "+k:"",f.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",f.physicallyCorrectLights?"#define PHYSICALLY_CORRECT_LIGHTS":"",f.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",f.logarithmicDepthBuffer&&b.get("EXT_frag_depth")?"#define USE_LOGDEPTHBUF_EXT":"",f.envMap&&b.get("EXT_shader_texture_lod")?"#define TEXTURE_LOD_EXT":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;",f.toneMapping!==qc?"#define TONE_MAPPING":"",f.toneMapping!==qc?Mf.tonemapping_pars_fragment:"",f.toneMapping!==qc?ab("toneMapping",f.toneMapping):"",f.dithering?"#define DITHERING":"",f.outputEncoding||f.mapEncoding||f.envMapEncoding||f.emissiveMapEncoding?Mf.encodings_pars_fragment:"",f.mapEncoding?$a("mapTexelToLinear",f.mapEncoding):"",f.envMapEncoding?$a("envMapTexelToLinear",f.envMapEncoding):"",f.emissiveMapEncoding?$a("emissiveMapTexelToLinear",f.emissiveMapEncoding):"",f.outputEncoding?_a("linearToOutputTexel",f.outputEncoding):"",f.depthPacking?"#define DEPTH_PACKING "+d.depthPacking:"","\n"].filter(eb).join("\n")),i=gb(i),i=fb(i,f),j=gb(j),j=fb(j,f),d.isShaderMaterial||(i=hb(i),j=hb(j));var u=o+i,v=p+j,w=Ya(g,g.VERTEX_SHADER,u),x=Ya(g,g.FRAGMENT_SHADER,v);g.attachShader(t,w),g.attachShader(t,x),void 0!==d.index0AttributeName?g.bindAttribLocation(t,0,d.index0AttributeName):!0===f.morphTargets&&g.bindAttribLocation(t,0,"position"),g.linkProgram(t);var y=g.getProgramInfoLog(t),z=g.getShaderInfoLog(w),A=g.getShaderInfoLog(x),B=!0,C=!0;!1===g.getProgramParameter(t,g.LINK_STATUS)?(B=!1,console.error("THREE.WebGLProgram: shader error: ",g.getError(),"gl.VALIDATE_STATUS",g.getProgramParameter(t,g.VALIDATE_STATUS),"gl.getProgramInfoLog",y,z,A)):""!==y?console.warn("THREE.WebGLProgram: gl.getProgramInfoLog()",y):""!==z&&""!==A||(C=!1),C&&(this.diagnostics={runnable:B,material:d,programLog:y,vertexShader:{log:z,prefix:o},fragmentShader:{log:A,prefix:p}}),g.deleteShader(w),g.deleteShader(x);var D;this.getUniforms=function(){return void 0===D&&(D=new T(g,t,a)),D};var E;return this.getAttributes=function(){return void 0===E&&(E=db(g,t)),E},this.destroy=function(){g.deleteProgram(t),this.program=void 0},Object.defineProperties(this,{uniforms:{get:function(){return console.warn("THREE.WebGLProgram: .uniforms is now .getUniforms()."),this.getUniforms()}},attributes:{get:function(){return console.warn("THREE.WebGLProgram: .attributes is now .getAttributes()."),this.getAttributes()}}}),this.id=Sf++,this.code=c,this.usedTimes=1,this.program=t,this.vertexShader=w,this.fragmentShader=x,this}function jb(a,b,c){function d(a){var b=a.skeleton,d=b.bones;if(c.floatVertexTextures)return 1024;var e=c.maxVertexUniforms,f=Math.floor((e-20)/4),g=Math.min(f,d.length);return g<d.length?(console.warn("THREE.WebGLRenderer: Skeleton has "+d.length+" bones. This GPU supports "+g+"."),0):g}function e(a,b){var c;return a?a.isTexture?c=a.encoding:a.isWebGLRenderTarget&&(console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead."),c=a.texture.encoding):c=pd,c===pd&&b&&(c=rd),c}var f=[],g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"phong",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow"},h=["precision","supportsVertexTextures","map","mapEncoding","envMap","envMapMode","envMapEncoding","lightMap","aoMap","emissiveMap","emissiveMapEncoding","bumpMap","normalMap","displacementMap","specularMap","roughnessMap","metalnessMap","gradientMap","alphaMap","combine","vertexColors","fog","useFog","fogExp","flatShading","sizeAttenuation","logarithmicDepthBuffer","skinning","maxBones","useVertexTexture","morphTargets","morphNormals","maxMorphTargets","maxMorphNormals","premultipliedAlpha","numDirLights","numPointLights","numSpotLights","numHemiLights","numRectAreaLights","shadowMapEnabled","shadowMapType","toneMapping","physicallyCorrectLights","alphaTest","doubleSided","flipSided","numClippingPlanes","numClipIntersection","depthPacking","dithering"];this.getParameters=function(b,f,h,i,j,k,l){var m=g[b.type],n=l.isSkinnedMesh?d(l):0,o=c.precision;null!==b.precision&&(o=c.getMaxPrecision(b.precision))!==b.precision&&console.warn("THREE.WebGLProgram.getParameters:",b.precision,"not supported, using",o,"instead.");var p=a.getRenderTarget();return{shaderID:m,precision:o,supportsVertexTextures:c.vertexTextures,outputEncoding:e(p?p.texture:null,a.gammaOutput),map:!!b.map,mapEncoding:e(b.map,a.gammaInput),envMap:!!b.envMap,envMapMode:b.envMap&&b.envMap.mapping,envMapEncoding:e(b.envMap,a.gammaInput),envMapCubeUV:!!b.envMap&&(b.envMap.mapping===Bc||b.envMap.mapping===Cc),lightMap:!!b.lightMap,aoMap:!!b.aoMap,emissiveMap:!!b.emissiveMap,emissiveMapEncoding:e(b.emissiveMap,a.gammaInput),bumpMap:!!b.bumpMap,normalMap:!!b.normalMap,displacementMap:!!b.displacementMap,roughnessMap:!!b.roughnessMap,metalnessMap:!!b.metalnessMap,specularMap:!!b.specularMap,alphaMap:!!b.alphaMap,gradientMap:!!b.gradientMap,combine:b.combine,vertexColors:b.vertexColors,fog:!!i,useFog:b.fog,fogExp:i&&i.isFogExp2,flatShading:b.flatShading,sizeAttenuation:b.sizeAttenuation,logarithmicDepthBuffer:c.logarithmicDepthBuffer,skinning:b.skinning&&n>0,maxBones:n,useVertexTexture:c.floatVertexTextures,morphTargets:b.morphTargets,morphNormals:b.morphNormals,maxMorphTargets:a.maxMorphTargets,maxMorphNormals:a.maxMorphNormals,numDirLights:f.directional.length,numPointLights:f.point.length,numSpotLights:f.spot.length,numRectAreaLights:f.rectArea.length,numHemiLights:f.hemi.length,numClippingPlanes:j,numClipIntersection:k,dithering:b.dithering,shadowMapEnabled:a.shadowMap.enabled&&l.receiveShadow&&h.length>0,shadowMapType:a.shadowMap.type,toneMapping:a.toneMapping,physicallyCorrectLights:a.physicallyCorrectLights,premultipliedAlpha:b.premultipliedAlpha,alphaTest:b.alphaTest,doubleSided:b.side===Ib,flipSided:b.side===Hb,depthPacking:void 0!==b.depthPacking&&b.depthPacking}},this.getProgramCode=function(b,c){var d=[];if(c.shaderID?d.push(c.shaderID):(d.push(b.fragmentShader),d.push(b.vertexShader)),void 0!==b.defines)for(var e in b.defines)d.push(e),d.push(b.defines[e]);for(var f=0;f<h.length;f++)d.push(c[h[f]]);return d.push(b.onBeforeCompile.toString()),d.push(a.gammaOutput),d.join()},this.acquireProgram=function(c,d,e,g){for(var h,i=0,j=f.length;i<j;i++){var k=f[i];if(k.code===g){h=k,++h.usedTimes;break}}return void 0===h&&(h=new ib(a,b,g,c,d,e),f.push(h)),h},this.releaseProgram=function(a){if(0==--a.usedTimes){var b=f.indexOf(a);f[b]=f[f.length-1],f.pop(),a.destroy()}},this.programs=f}function kb(a,b,c,d,e,f,g){function h(a,b){if(a.width>b||a.height>b){var c=b/Math.max(a.width,a.height),d=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");d.width=Math.floor(a.width*c),d.height=Math.floor(a.height*c);return d.getContext("2d").drawImage(a,0,0,a.width,a.height,0,0,d.width,d.height),console.warn("THREE.WebGLRenderer: image is too big ("+a.width+"x"+a.height+"). Resized to "+d.width+"x"+d.height,a),d}return a}function i(a){return yd.isPowerOfTwo(a.width)&&yd.isPowerOfTwo(a.height)}function j(a){if(a instanceof HTMLImageElement||a instanceof HTMLCanvasElement||a instanceof ImageBitmap){var b=document.createElementNS("http://www.w3.org/1999/xhtml","canvas");b.width=yd.floorPowerOfTwo(a.width),b.height=yd.floorPowerOfTwo(a.height);return b.getContext("2d").drawImage(a,0,0,b.width,b.height),console.warn("THREE.WebGLRenderer: image is not power of two ("+a.width+"x"+a.height+"). Resized to "+b.width+"x"+b.height,a),b}return a}function k(a){return a.wrapS!==Ec||a.wrapT!==Ec||a.minFilter!==Gc&&a.minFilter!==Jc}function l(a,b){return a.generateMipmaps&&b&&a.minFilter!==Gc&&a.minFilter!==Jc}function m(b){return b===Gc||b===Hc||b===Ic?a.NEAREST:a.LINEAR}function n(a){var b=a.target;b.removeEventListener("dispose",n),p(b),b.isVideoTexture&&delete E[b.id],g.textures--}function o(a){var b=a.target;b.removeEventListener("dispose",o),q(b),g.textures--}function p(b){var c=d.get(b);if(b.image&&c.__image__webglTextureCube)a.deleteTexture(c.__image__webglTextureCube);else{if(void 0===c.__webglInit)return;a.deleteTexture(c.__webglTexture)}d.remove(b)}function q(b){var c=d.get(b),e=d.get(b.texture);if(b){if(void 0!==e.__webglTexture&&a.deleteTexture(e.__webglTexture),b.depthTexture&&b.depthTexture.dispose(),b.isWebGLRenderTargetCube)for(var f=0;f<6;f++)a.deleteFramebuffer(c.__webglFramebuffer[f]),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer[f]);else a.deleteFramebuffer(c.__webglFramebuffer),c.__webglDepthbuffer&&a.deleteRenderbuffer(c.__webglDepthbuffer);d.remove(b.texture),d.remove(b)}}function r(b,e){var f=d.get(b);if(b.version>0&&f.__version!==b.version){var g=b.image;if(void 0===g)console.warn("THREE.WebGLRenderer: Texture marked for update but image is undefined",b);else{if(!1!==g.complete)return void v(f,b,e);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete",b)}}c.activeTexture(a.TEXTURE0+e),c.bindTexture(a.TEXTURE_2D,f.__webglTexture)}function s(b,j){var k=d.get(b);if(6===b.image.length)if(b.version>0&&k.__version!==b.version){k.__image__webglTextureCube||(b.addEventListener("dispose",n),k.__image__webglTextureCube=a.createTexture(),g.textures++),c.activeTexture(a.TEXTURE0+j),c.bindTexture(a.TEXTURE_CUBE_MAP,k.__image__webglTextureCube),a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,b.flipY);for(var m=b&&b.isCompressedTexture,o=b.image[0]&&b.image[0].isDataTexture,p=[],q=0;q<6;q++)p[q]=m||o?o?b.image[q].image:b.image[q]:h(b.image[q],e.maxCubemapSize);var r=p[0],s=i(r),t=f.convert(b.format),v=f.convert(b.type);u(a.TEXTURE_CUBE_MAP,b,s);for(var q=0;q<6;q++)if(m)for(var w,x=p[q].mipmaps,y=0,z=x.length;y<z;y++)w=x[y],b.format!==$c&&b.format!==Zc?c.getCompressedTextureFormats().indexOf(t)>-1?c.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+q,y,t,w.width,w.height,0,w.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+q,y,t,w.width,w.height,0,t,v,w.data);else o?c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+q,0,t,p[q].width,p[q].height,0,t,v,p[q].data):c.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+q,0,t,t,v,p[q]);l(b,s)&&a.generateMipmap(a.TEXTURE_CUBE_MAP),k.__version=b.version,b.onUpdate&&b.onUpdate(b)}else c.activeTexture(a.TEXTURE0+j),c.bindTexture(a.TEXTURE_CUBE_MAP,k.__image__webglTextureCube)}function t(b,e){c.activeTexture(a.TEXTURE0+e),c.bindTexture(a.TEXTURE_CUBE_MAP,d.get(b).__webglTexture)}function u(c,g,h){var i;if(h?(a.texParameteri(c,a.TEXTURE_WRAP_S,f.convert(g.wrapS)),a.texParameteri(c,a.TEXTURE_WRAP_T,f.convert(g.wrapT)),a.texParameteri(c,a.TEXTURE_MAG_FILTER,f.convert(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,f.convert(g.minFilter))):(a.texParameteri(c,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(c,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),g.wrapS===Ec&&g.wrapT===Ec||console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.",g),a.texParameteri(c,a.TEXTURE_MAG_FILTER,m(g.magFilter)),a.texParameteri(c,a.TEXTURE_MIN_FILTER,m(g.minFilter)),g.minFilter!==Gc&&g.minFilter!==Jc&&console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.",g)),i=b.get("EXT_texture_filter_anisotropic")){if(g.type===Sc&&null===b.get("OES_texture_float_linear"))return;if(g.type===Tc&&null===b.get("OES_texture_half_float_linear"))return;(g.anisotropy>1||d.get(g).__currentAnisotropy)&&(a.texParameterf(c,i.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(g.anisotropy,e.getMaxAnisotropy())),d.get(g).__currentAnisotropy=g.anisotropy)}}function v(b,d,m){void 0===b.__webglInit&&(b.__webglInit=!0,d.addEventListener("dispose",n),b.__webglTexture=a.createTexture(),d.isVideoTexture&&(E[d.id]=d),g.textures++),c.activeTexture(a.TEXTURE0+m),c.bindTexture(a.TEXTURE_2D,b.__webglTexture),a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,d.flipY),a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,d.premultiplyAlpha),a.pixelStorei(a.UNPACK_ALIGNMENT,d.unpackAlignment);var o=h(d.image,e.maxTextureSize);k(d)&&!1===i(o)&&(o=j(o));var p=i(o),q=f.convert(d.format),r=f.convert(d.type);u(a.TEXTURE_2D,d,p);var s,t=d.mipmaps;if(d.isDepthTexture){var v=a.DEPTH_COMPONENT;if(d.type===Sc){if(!D)throw new Error("Float Depth Texture only supported in WebGL2.0");v=a.DEPTH_COMPONENT32F}else D&&(v=a.DEPTH_COMPONENT16);d.format===bd&&v===a.DEPTH_COMPONENT&&d.type!==Pc&&d.type!==Rc&&(console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."),d.type=Pc,r=f.convert(d.type)),d.format===cd&&(v=a.DEPTH_STENCIL,d.type!==Xc&&(console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."),d.type=Xc,r=f.convert(d.type))),c.texImage2D(a.TEXTURE_2D,0,v,o.width,o.height,0,q,r,null)}else if(d.isDataTexture)if(t.length>0&&p){for(var w=0,x=t.length;w<x;w++)s=t[w],c.texImage2D(a.TEXTURE_2D,w,q,s.width,s.height,0,q,r,s.data);d.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,q,o.width,o.height,0,q,r,o.data);else if(d.isCompressedTexture)for(var w=0,x=t.length;w<x;w++)s=t[w],d.format!==$c&&d.format!==Zc?c.getCompressedTextureFormats().indexOf(q)>-1?c.compressedTexImage2D(a.TEXTURE_2D,w,q,s.width,s.height,0,s.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):c.texImage2D(a.TEXTURE_2D,w,q,s.width,s.height,0,q,r,s.data);else if(t.length>0&&p){for(var w=0,x=t.length;w<x;w++)s=t[w],c.texImage2D(a.TEXTURE_2D,w,q,q,r,s);d.generateMipmaps=!1}else c.texImage2D(a.TEXTURE_2D,0,q,q,r,o);l(d,p)&&a.generateMipmap(a.TEXTURE_2D),b.__version=d.version,d.onUpdate&&d.onUpdate(d)}function w(b,e,g,h){var i=f.convert(e.texture.format),j=f.convert(e.texture.type);c.texImage2D(h,0,i,e.width,e.height,0,i,j,null),a.bindFramebuffer(a.FRAMEBUFFER,b),a.framebufferTexture2D(a.FRAMEBUFFER,g,h,d.get(e.texture).__webglTexture,0),a.bindFramebuffer(a.FRAMEBUFFER,null)}function x(b,c){a.bindRenderbuffer(a.RENDERBUFFER,b),c.depthBuffer&&!c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.RENDERBUFFER,b)):c.depthBuffer&&c.stencilBuffer?(a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_STENCIL,c.width,c.height),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,b)):a.renderbufferStorage(a.RENDERBUFFER,a.RGBA4,c.width,c.height),a.bindRenderbuffer(a.RENDERBUFFER,null)}function y(b,c){if(c&&c.isWebGLRenderTargetCube)throw new Error("Depth Texture with cube render targets is not supported");if(a.bindFramebuffer(a.FRAMEBUFFER,b),!c.depthTexture||!c.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");d.get(c.depthTexture).__webglTexture&&c.depthTexture.image.width===c.width&&c.depthTexture.image.height===c.height||(c.depthTexture.image.width=c.width,c.depthTexture.image.height=c.height,c.depthTexture.needsUpdate=!0),r(c.depthTexture,0);var e=d.get(c.depthTexture).__webglTexture;if(c.depthTexture.format===bd)a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_ATTACHMENT,a.TEXTURE_2D,e,0);else{if(c.depthTexture.format!==cd)throw new Error("Unknown depthTexture format");a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,e,0)}}function z(b){var c=d.get(b),e=!0===b.isWebGLRenderTargetCube;if(b.depthTexture){if(e)throw new Error("target.depthTexture not supported in Cube render targets");y(c.__webglFramebuffer,b)}else if(e){c.__webglDepthbuffer=[];for(var f=0;f<6;f++)a.bindFramebuffer(a.FRAMEBUFFER,c.__webglFramebuffer[f]),c.__webglDepthbuffer[f]=a.createRenderbuffer(),x(c.__webglDepthbuffer[f],b)}else a.bindFramebuffer(a.FRAMEBUFFER,c.__webglFramebuffer),c.__webglDepthbuffer=a.createRenderbuffer(),x(c.__webglDepthbuffer,b);a.bindFramebuffer(a.FRAMEBUFFER,null)}function A(b){var e=d.get(b),f=d.get(b.texture);b.addEventListener("dispose",o),f.__webglTexture=a.createTexture(),g.textures++;var h=!0===b.isWebGLRenderTargetCube,j=i(b);if(h){e.__webglFramebuffer=[];for(var k=0;k<6;k++)e.__webglFramebuffer[k]=a.createFramebuffer()}else e.__webglFramebuffer=a.createFramebuffer();if(h){c.bindTexture(a.TEXTURE_CUBE_MAP,f.__webglTexture),u(a.TEXTURE_CUBE_MAP,b.texture,j);for(var k=0;k<6;k++)w(e.__webglFramebuffer[k],b,a.COLOR_ATTACHMENT0,a.TEXTURE_CUBE_MAP_POSITIVE_X+k);l(b.texture,j)&&a.generateMipmap(a.TEXTURE_CUBE_MAP),c.bindTexture(a.TEXTURE_CUBE_MAP,null)}else c.bindTexture(a.TEXTURE_2D,f.__webglTexture),u(a.TEXTURE_2D,b.texture,j),w(e.__webglFramebuffer,b,a.COLOR_ATTACHMENT0,a.TEXTURE_2D),l(b.texture,j)&&a.generateMipmap(a.TEXTURE_2D),c.bindTexture(a.TEXTURE_2D,null);b.depthBuffer&&z(b)}function B(b){var e=b.texture;if(l(e,i(b))){var f=b.isWebGLRenderTargetCube?a.TEXTURE_CUBE_MAP:a.TEXTURE_2D,g=d.get(e).__webglTexture;c.bindTexture(f,g),a.generateMipmap(f),c.bindTexture(f,null)}}function C(){for(var a in E)E[a].update()}var D="undefined"!=typeof WebGL2RenderingContext&&a instanceof window.WebGL2RenderingContext,E={};this.setTexture2D=r,this.setTextureCube=s,this.setTextureCubeDynamic=t,this.setupRenderTarget=A,this.updateRenderTargetMipmap=B,this.updateVideoTextures=C}function lb(){function a(a){var b=a.uuid,c=d[b];return void 0===c&&(c={},d[b]=c),c}function b(a){delete d[a.uuid]}function c(){d={}}var d={};return{get:a,remove:b,clear:c}}function mb(a,b,c){function d(){var b=!1,c=new i,d=null,e=new i(0,0,0,0);return{setMask:function(c){d===c||b||(a.colorMask(c,c,c,c),d=c)},setLocked:function(a){b=a},setClear:function(b,d,f,g,h){!0===h&&(b*=g,d*=g,f*=g),c.set(b,d,f,g),!1===e.equals(c)&&(a.clearColor(b,d,f,g),e.copy(c))},reset:function(){b=!1,d=null,e.set(-1,0,0,0)}}}function e(){var b=!1,c=null,d=null,e=null;return{setTest:function(b){b?m(a.DEPTH_TEST):n(a.DEPTH_TEST)},setMask:function(d){c===d||b||(a.depthMask(d),c=d)},setFunc:function(b){if(d!==b){if(b)switch(b){case fc:a.depthFunc(a.NEVER);break;case gc:a.depthFunc(a.ALWAYS);break;case hc:a.depthFunc(a.LESS);break;case ic:a.depthFunc(a.LEQUAL);break;case jc:a.depthFunc(a.EQUAL);break;case kc:a.depthFunc(a.GEQUAL);break;case lc:a.depthFunc(a.GREATER);break;case mc:a.depthFunc(a.NOTEQUAL);break;default:a.depthFunc(a.LEQUAL)}else a.depthFunc(a.LEQUAL);d=b}},setLocked:function(a){b=a},setClear:function(b){e!==b&&(a.clearDepth(b),e=b)},reset:function(){b=!1,c=null,d=null,e=null}}}function f(){var b=!1,c=null,d=null,e=null,f=null,g=null,h=null,i=null,j=null;return{setTest:function(b){b?m(a.STENCIL_TEST):n(a.STENCIL_TEST)},setMask:function(d){c===d||b||(a.stencilMask(d),c=d)},setFunc:function(b,c,g){d===b&&e===c&&f===g||(a.stencilFunc(b,c,g),d=b,e=c,f=g)},setOp:function(b,c,d){g===b&&h===c&&i===d||(a.stencilOp(b,c,d),g=b,h=c,i=d)},setLocked:function(a){b=a},setClear:function(b){j!==b&&(a.clearStencil(b),j=b)},reset:function(){b=!1,c=null,d=null,e=null,f=null,g=null,h=null,i=null,j=null}}}function g(b,c,d){var e=new Uint8Array(4),f=a.createTexture();a.bindTexture(b,f),a.texParameteri(b,a.TEXTURE_MIN_FILTER,a.NEAREST),a.texParameteri(b,a.TEXTURE_MAG_FILTER,a.NEAREST);for(var g=0;g<d;g++)a.texImage2D(c+g,0,a.RGBA,1,1,0,a.RGBA,a.UNSIGNED_BYTE,e);return f}function h(){for(var a=0,b=I.length;a<b;a++)I[a]=0}function j(c){if(I[c]=1,0===J[c]&&(a.enableVertexAttribArray(c),J[c]=1),0!==K[c]){b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,0),K[c]=0}}function k(c,d){if(I[c]=1,0===J[c]&&(a.enableVertexAttribArray(c),J[c]=1),K[c]!==d){b.get("ANGLE_instanced_arrays").vertexAttribDivisorANGLE(c,d),K[c]=d}}function l(){for(var b=0,c=J.length;b!==c;++b)J[b]!==I[b]&&(a.disableVertexAttribArray(b),J[b]=0)}function m(b){!0!==L[b]&&(a.enable(b),L[b]=!0)}function n(b){!1!==L[b]&&(a.disable(b),L[b]=!1)}function o(){if(null===M&&(M=[],b.get("WEBGL_compressed_texture_pvrtc")||b.get("WEBGL_compressed_texture_s3tc")||b.get("WEBGL_compressed_texture_etc1")))for(var c=a.getParameter(a.COMPRESSED_TEXTURE_FORMATS),d=0;d<c.length;d++)M.push(c[d]);return M}function p(b){return N!==b&&(a.useProgram(b),N=b,!0)}function q(b,d,e,f,g,h,i,j){if(b!==Lb?m(a.BLEND):n(a.BLEND),b!==Qb){if(b!==O||j!==V)switch(b){case Nb:j?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE,a.ONE,a.ONE)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.SRC_ALPHA,a.ONE));break;case Ob:j?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.ZERO,a.ONE_MINUS_SRC_COLOR,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.ONE_MINUS_SRC_COLOR));break;case Pb:j?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ZERO,a.SRC_COLOR,a.ZERO,a.SRC_ALPHA)):(a.blendEquation(a.FUNC_ADD),a.blendFunc(a.ZERO,a.SRC_COLOR));break;default:j?(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.ONE,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA)):(a.blendEquationSeparate(a.FUNC_ADD,a.FUNC_ADD),a.blendFuncSeparate(a.SRC_ALPHA,a.ONE_MINUS_SRC_ALPHA,a.ONE,a.ONE_MINUS_SRC_ALPHA))}P=null,Q=null,R=null,S=null,T=null,U=null}else g=g||d,h=h||e,i=i||f,d===P&&g===S||(a.blendEquationSeparate(c.convert(d),c.convert(g)),P=d,S=g),e===Q&&f===R&&h===T&&i===U||(a.blendFuncSeparate(c.convert(e),c.convert(f),c.convert(h),c.convert(i)),Q=e,R=f,T=h,U=i);O=b,V=j}function r(b,c){b.side===Ib?n(a.CULL_FACE):m(a.CULL_FACE);var d=b.side===Hb;c&&(d=!d),s(d),!0===b.transparent?q(b.blending,b.blendEquation,b.blendSrc,b.blendDst,b.blendEquationAlpha,b.blendSrcAlpha,b.blendDstAlpha,b.premultipliedAlpha):q(Lb),F.setFunc(b.depthFunc),F.setTest(b.depthTest),F.setMask(b.depthWrite),E.setMask(b.colorWrite),v(b.polygonOffset,b.polygonOffsetFactor,b.polygonOffsetUnits)}function s(b){W!==b&&(b?a.frontFace(a.CW):a.frontFace(a.CCW),W=b)}function t(b){b!==Ab?(m(a.CULL_FACE),b!==X&&(b===Bb?a.cullFace(a.BACK):b===Cb?a.cullFace(a.FRONT):a.cullFace(a.FRONT_AND_BACK))):n(a.CULL_FACE),X=b}function u(b){b!==Y&&(ba&&a.lineWidth(b),Y=b)}function v(b,c,d){b?(m(a.POLYGON_OFFSET_FILL),Z===c&&$===d||(a.polygonOffset(c,d),Z=c,$=d)):n(a.POLYGON_OFFSET_FILL)}function w(b){b?m(a.SCISSOR_TEST):n(a.SCISSOR_TEST)}function x(b){void 0===b&&(b=a.TEXTURE0+_-1),ca!==b&&(a.activeTexture(b),ca=b)}function y(b,c){null===ca&&x();var d=da[ca];void 0===d&&(d={type:void 0,texture:void 0},da[ca]=d),d.type===b&&d.texture===c||(a.bindTexture(b,c||ga[b]),d.type=b,d.texture=c)}function z(){try{a.compressedTexImage2D.apply(a,arguments)}catch(a){console.error("THREE.WebGLState:",a)}}function A(){try{a.texImage2D.apply(a,arguments)}catch(a){console.error("THREE.WebGLState:",a)}}function B(b){!1===ea.equals(b)&&(a.scissor(b.x,b.y,b.z,b.w),ea.copy(b))}function C(b){!1===fa.equals(b)&&(a.viewport(b.x,b.y,b.z,b.w),fa.copy(b))}function D(){for(var b=0;b<J.length;b++)1===J[b]&&(a.disableVertexAttribArray(b),J[b]=0);L={},M=null,ca=null,da={},N=null,O=null,W=null,X=null,E.reset(),F.reset(),G.reset()}var E=new d,F=new e,G=new f,H=a.getParameter(a.MAX_VERTEX_ATTRIBS),I=new Uint8Array(H),J=new Uint8Array(H),K=new Uint8Array(H),L={},M=null,N=null,O=null,P=null,Q=null,R=null,S=null,T=null,U=null,V=!1,W=null,X=null,Y=null,Z=null,$=null,_=a.getParameter(a.MAX_COMBINED_TEXTURE_IMAGE_UNITS),aa=parseFloat(/^WebGL\ ([0-9])/.exec(a.getParameter(a.VERSION))[1]),ba=parseFloat(aa)>=1,ca=null,da={},ea=new i,fa=new i,ga={};return ga[a.TEXTURE_2D]=g(a.TEXTURE_2D,a.TEXTURE_2D,1),ga[a.TEXTURE_CUBE_MAP]=g(a.TEXTURE_CUBE_MAP,a.TEXTURE_CUBE_MAP_POSITIVE_X,6),E.setClear(0,0,0,1),F.setClear(1),G.setClear(0),m(a.DEPTH_TEST),F.setFunc(ic),s(!1),t(Bb),m(a.CULL_FACE),m(a.BLEND),q(Mb),{buffers:{color:E,depth:F,stencil:G},initAttributes:h,enableAttribute:j,enableAttributeAndDivisor:k,disableUnusedAttributes:l,enable:m,disable:n,getCompressedTextureFormats:o,useProgram:p,setBlending:q,setMaterial:r,setFlipSided:s,setCullFace:t,setLineWidth:u,setPolygonOffset:v,setScissorTest:w,activeTexture:x,bindTexture:y,compressedTexImage2D:z,texImage2D:A,scissor:B,viewport:C,reset:D}}function nb(a,b,c){function d(){if(void 0!==f)return f;var c=b.get("EXT_texture_filter_anisotropic");return f=null!==c?a.getParameter(c.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0}function e(b){if("highp"===b){if(a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.HIGH_FLOAT).precision>0&&a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.HIGH_FLOAT).precision>0)return"highp";b="mediump"}return"mediump"===b&&a.getShaderPrecisionFormat(a.VERTEX_SHADER,a.MEDIUM_FLOAT).precision>0&&a.getShaderPrecisionFormat(a.FRAGMENT_SHADER,a.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}var f,g=void 0!==c.precision?c.precision:"highp",h=e(g);h!==g&&(console.warn("THREE.WebGLRenderer:",g,"not supported, using",h,"instead."),g=h);var i=!0===c.logarithmicDepthBuffer,j=a.getParameter(a.MAX_TEXTURE_IMAGE_UNITS),k=a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS),l=a.getParameter(a.MAX_TEXTURE_SIZE),m=a.getParameter(a.MAX_CUBE_MAP_TEXTURE_SIZE),n=a.getParameter(a.MAX_VERTEX_ATTRIBS),o=a.getParameter(a.MAX_VERTEX_UNIFORM_VECTORS),p=a.getParameter(a.MAX_VARYING_VECTORS),q=a.getParameter(a.MAX_FRAGMENT_UNIFORM_VECTORS),r=k>0,s=!!b.get("OES_texture_float");return{getMaxAnisotropy:d,getMaxPrecision:e,precision:g,logarithmicDepthBuffer:i,maxTextures:j,maxVertexTextures:k,maxTextureSize:l,maxCubemapSize:m,maxAttributes:n,maxVertexUniforms:o,maxVaryings:p,maxFragmentUniforms:q,vertexTextures:r,floatFragmentTextures:s,floatVertexTextures:r&&s}}function ob(a,b,c,d){ja.call(this),this.type="PerspectiveCamera",this.fov=void 0!==a?a:50,this.zoom=1,this.near=void 0!==c?c:.1,this.far=void 0!==d?d:2e3,this.focus=10,this.aspect=void 0!==b?b:1,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}function pb(a){ob.call(this),this.cameras=a||[]}function qb(a){function b(){if(null!==e&&e.isPresenting){var b=e.getEyeParameters("left"),d=b.renderWidth,f=b.renderHeight;n=a.getPixelRatio(),m=a.getSize(),a.setDrawingBufferSize(2*d,f,1)}else c.enabled&&a.setDrawingBufferSize(m.width,m.height,n)}var c=this,e=null,f=null,g=null;"undefined"!=typeof window&&"VRFrameData"in window&&(f=new window.VRFrameData);var h=new d,j=new ob;j.bounds=new i(0,0,.5,1),j.layers.enable(1);var k=new ob;k.bounds=new i(.5,0,.5,1),k.layers.enable(2);var l=new pb([j,k]);l.layers.enable(1),l.layers.enable(2);var m,n;"undefined"!=typeof window&&window.addEventListener("vrdisplaypresentchange",b,!1),this.enabled=!1,this.getDevice=function(){return e},this.setDevice=function(a){void 0!==a&&(e=a)},this.setPoseTarget=function(a){void 0!==a&&(g=a)},this.getCamera=function(a){if(null===e)return a;e.depthNear=a.near,e.depthFar=a.far,e.getFrameData(f);var b=f.pose,c=null!==g?g:a;if(null!==b.position?c.position.fromArray(b.position):c.position.set(0,0,0),null!==b.orientation&&c.quaternion.fromArray(b.orientation),c.updateMatrixWorld(),!1===e.isPresenting)return a;j.near=a.near,k.near=a.near,j.far=a.far,k.far=a.far,l.matrixWorld.copy(a.matrixWorld),l.matrixWorldInverse.copy(a.matrixWorldInverse),j.matrixWorldInverse.fromArray(f.leftViewMatrix),k.matrixWorldInverse.fromArray(f.rightViewMatrix);var d=c.parent;null!==d&&(h.getInverse(d.matrixWorld),j.matrixWorldInverse.multiply(h),k.matrixWorldInverse.multiply(h)),j.matrixWorld.getInverse(j.matrixWorldInverse),k.matrixWorld.getInverse(k.matrixWorldInverse),j.projectionMatrix.fromArray(f.leftProjectionMatrix),k.projectionMatrix.fromArray(f.rightProjectionMatrix),l.projectionMatrix.copy(j.projectionMatrix);var i=e.getLayers();if(i.length){var m=i[0];null!==m.leftBounds&&4===m.leftBounds.length&&j.bounds.fromArray(m.leftBounds),null!==m.rightBounds&&4===m.rightBounds.length&&k.bounds.fromArray(m.rightBounds)}return l},this.submitFrame=function(){e&&e.isPresenting&&e.submitFrame()},this.dispose=function(){"undefined"!=typeof window&&window.removeEventListener("vrdisplaypresentchange",b)}}function rb(a){var b={};return{get:function(c){if(void 0!==b[c])return b[c];var d;switch(c){case"WEBGL_depth_texture":d=a.getExtension("WEBGL_depth_texture")||a.getExtension("MOZ_WEBGL_depth_texture")||a.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":d=a.getExtension("EXT_texture_filter_anisotropic")||a.getExtension("MOZ_EXT_texture_filter_anisotropic")||a.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":d=a.getExtension("WEBGL_compressed_texture_s3tc")||a.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":d=a.getExtension("WEBGL_compressed_texture_pvrtc")||a.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;case"WEBGL_compressed_texture_etc1":d=a.getExtension("WEBGL_compressed_texture_etc1");break;default:d=a.getExtension(c)}return null===d&&console.warn("THREE.WebGLRenderer: "+c+" extension not supported."),b[c]=d,d}}}function sb(){function a(){k.value!==d&&(k.value=d,k.needsUpdate=e>0),c.numPlanes=e,c.numIntersection=0}function b(a,b,d,e){var f=null!==a?a.length:0,g=null;if(0!==f){if(g=k.value,!0!==e||null===g){var h=d+4*f,l=b.matrixWorldInverse;j.getNormalMatrix(l),(null===g||g.length<h)&&(g=new Float32Array(h));for(var m=0,n=d;m!==f;++m,n+=4)i.copy(a[m]).applyMatrix4(l,j),i.normal.toArray(g,n),g[n+3]=i.constant}k.value=g,k.needsUpdate=!0}return c.numPlanes=f,g}var c=this,d=null,e=0,f=!1,h=!1,i=new ca,j=new g,k={value:null,needsUpdate:!1};this.uniform=k,this.numPlanes=0,this.numIntersection=0,this.init=function(a,c,g){var h=0!==a.length||c||0!==e||f;return f=c,d=b(a,g,0),e=a.length,h},this.beginShadows=function(){h=!0,b(null)},this.endShadows=function(){h=!1,a()},this.setState=function(c,g,i,j,l,m){if(!f||null===c||0===c.length||h&&!i)h?b(null):a();else{var n=h?0:e,o=4*n,p=l.clippingState||null;k.value=p,p=b(c,j,o,m);for(var q=0;q!==o;++q)p[q]=d[q];l.clippingState=p,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=n}}}function tb(a,b){function c(c){var d;if(c===Dc)return a.REPEAT;if(c===Ec)return a.CLAMP_TO_EDGE;if(c===Fc)return a.MIRRORED_REPEAT;if(c===Gc)return a.NEAREST;if(c===Hc)return a.NEAREST_MIPMAP_NEAREST;if(c===Ic)return a.NEAREST_MIPMAP_LINEAR;if(c===Jc)return a.LINEAR;if(c===Kc)return a.LINEAR_MIPMAP_NEAREST;if(c===Lc)return a.LINEAR_MIPMAP_LINEAR;if(c===Mc)return a.UNSIGNED_BYTE;if(c===Uc)return a.UNSIGNED_SHORT_4_4_4_4;if(c===Vc)return a.UNSIGNED_SHORT_5_5_5_1;if(c===Wc)return a.UNSIGNED_SHORT_5_6_5;if(c===Nc)return a.BYTE;if(c===Oc)return a.SHORT;if(c===Pc)return a.UNSIGNED_SHORT;if(c===Qc)return a.INT;if(c===Rc)return a.UNSIGNED_INT;if(c===Sc)return a.FLOAT;if(c===Tc&&null!==(d=b.get("OES_texture_half_float")))return d.HALF_FLOAT_OES;if(c===Yc)return a.ALPHA;if(c===Zc)return a.RGB;if(c===$c)return a.RGBA;if(c===_c)return a.LUMINANCE;if(c===ad)return a.LUMINANCE_ALPHA;if(c===bd)return a.DEPTH_COMPONENT;if(c===cd)return a.DEPTH_STENCIL;if(c===Rb)return a.FUNC_ADD;if(c===Sb)return a.FUNC_SUBTRACT;if(c===Tb)return a.FUNC_REVERSE_SUBTRACT;if(c===Wb)return a.ZERO;if(c===Xb)return a.ONE;if(c===Yb)return a.SRC_COLOR;if(c===Zb)return a.ONE_MINUS_SRC_COLOR;if(c===$b)return a.SRC_ALPHA;if(c===_b)return a.ONE_MINUS_SRC_ALPHA;if(c===ac)return a.DST_ALPHA;if(c===bc)return a.ONE_MINUS_DST_ALPHA;if(c===cc)return a.DST_COLOR;if(c===dc)return a.ONE_MINUS_DST_COLOR;if(c===ec)return a.SRC_ALPHA_SATURATE;if((c===dd||c===ed||c===fd||c===gd)&&null!==(d=b.get("WEBGL_compressed_texture_s3tc"))){if(c===dd)return d.COMPRESSED_RGB_S3TC_DXT1_EXT;if(c===ed)return d.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(c===fd)return d.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(c===gd)return d.COMPRESSED_RGBA_S3TC_DXT5_EXT}if((c===hd||c===id||c===jd||c===kd)&&null!==(d=b.get("WEBGL_compressed_texture_pvrtc"))){if(c===hd)return d.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(c===id)return d.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(c===jd)return d.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(c===kd)return d.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(c===ld&&null!==(d=b.get("WEBGL_compressed_texture_etc1")))return d.COMPRESSED_RGB_ETC1_WEBGL;if((c===Ub||c===Vb)&&null!==(d=b.get("EXT_blend_minmax"))){if(c===Ub)return d.MIN_EXT;if(c===Vb)return d.MAX_EXT}return c===Xc&&null!==(d=b.get("WEBGL_depth_texture"))?d.UNSIGNED_INT_24_8_WEBGL:0}return{convert:c}}function ub(a){function b(){return null===ba?qa:1}function c(){Ea=new rb(Ca),Ea.get("WEBGL_depth_texture"),Ea.get("OES_texture_float"),Ea.get("OES_texture_float_linear"),Ea.get("OES_texture_half_float"),Ea.get("OES_texture_half_float_linear"),Ea.get("OES_standard_derivatives"),Ea.get("OES_element_index_uint"),Ea.get("ANGLE_instanced_arrays"),bb=new tb(Ca,Ea),Fa=new nb(Ca,Ea,a),Ga=new mb(Ca,Ea,bb),Ga.scissor(la.copy(sa).multiplyScalar(qa)),Ga.viewport(ka.copy(ra).multiplyScalar(qa)),Ha=new lb,Ia=new kb(Ca,Ea,Ga,Ha,Fa,bb,Aa),Ja=new fa(Ca),La=new Ta(Ca,Ja,Aa),Ma=new Wa(La,Ba),Ya=new Qa(Ca),Pa=new jb(_,Ea,Fa),Na=new Va,Ua=new Oa,Xa=new Ka(_,Ga,La,Q),Za=new Sa(Ca,Ea,Ba),$a=new Ra(Ca,Ea,Ba),_a=new W(_,Ca,Ga,Ia,Fa),ab=new Y(_,Ca,Ga,Ia,Fa),_.info.programs=Pa.programs,_.context=Ca,_.capabilities=Fa,_.extensions=Ea,_.properties=Ha,_.renderLists=Ua,_.state=Ga}function e(a){a.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),aa=!0}function g(){console.log("THREE.WebGLRenderer: Context Restored."),aa=!1,c()}function h(a){var b=a.target;b.removeEventListener("dispose",h),j(b)}function j(a){l(a),Ha.remove(a)}function l(a){var b=Ha.get(a).program;a.program=void 0,void 0!==b&&Pa.releaseProgram(b)}function m(a,b,c){a.render(function(a){_.renderBufferImmediate(a,b,c)})}function n(a,b,c,d){if(c&&c.isInstancedBufferGeometry&&null===Ea.get("ANGLE_instanced_arrays"))return void console.error("THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.");void 0===d&&(d=0),Ga.initAttributes();var e=c.attributes,f=b.getAttributes(),g=a.defaultAttributeValues;for(var h in f){var i=f[h];if(i>=0){var j=e[h];if(void 0!==j){var k=j.normalized,l=j.itemSize,m=Ja.get(j);if(void 0===m)continue;var n=m.buffer,o=m.type,p=m.bytesPerElement;if(j.isInterleavedBufferAttribute){var q=j.data,r=q.stride,s=j.offset;q&&q.isInstancedInterleavedBuffer?(Ga.enableAttributeAndDivisor(i,q.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=q.meshPerAttribute*q.count)):Ga.enableAttribute(i),Ca.bindBuffer(Ca.ARRAY_BUFFER,n),Ca.vertexAttribPointer(i,l,o,k,r*p,(d*r+s)*p)}else j.isInstancedBufferAttribute?(Ga.enableAttributeAndDivisor(i,j.meshPerAttribute),void 0===c.maxInstancedCount&&(c.maxInstancedCount=j.meshPerAttribute*j.count)):Ga.enableAttribute(i),Ca.bindBuffer(Ca.ARRAY_BUFFER,n),Ca.vertexAttribPointer(i,l,o,k,0,d*l*p)}else if(void 0!==g){var t=g[h];if(void 0!==t)switch(t.length){case 2:Ca.vertexAttrib2fv(i,t);break;case 3:Ca.vertexAttrib3fv(i,t);break;case 4:Ca.vertexAttrib4fv(i,t);break;default:Ca.vertexAttrib1fv(i,t)}}}}Ga.disableUnusedAttributes()}function o(){if(!eb){var a=cb.getDevice();a&&a.isPresenting?a.requestAnimationFrame(p):window.requestAnimationFrame(p),eb=!0}}function p(a){null!==fb&&fb(a);var b=cb.getDevice();b&&b.isPresenting?b.requestAnimationFrame(p):window.requestAnimationFrame(p)}function q(a,b,c){if(!1!==a.visible){if(a.layers.test(b.layers))if(a.isLight)U.push(a),a.castShadow&&V.push(a);else if(a.isSprite)a.frustumCulled&&!ua.intersectsSprite(a)||Z.push(a);else if(a.isLensFlare)$.push(a);else if(a.isImmediateRenderObject)c&&za.setFromMatrixPosition(a.matrixWorld).applyMatrix4(ya),X.push(a,null,a.material,za.z,null);else if((a.isMesh||a.isLine||a.isPoints)&&(a.isSkinnedMesh&&a.skeleton.update(),!a.frustumCulled||ua.intersectsObject(a))){c&&za.setFromMatrixPosition(a.matrixWorld).applyMatrix4(ya);var d=Ma.update(a),e=a.material;if(Array.isArray(e))for(var f=d.groups,g=0,h=f.length;g<h;g++){var i=f[g],j=e[i.materialIndex];j&&j.visible&&X.push(a,d,j,za.z,i)}else e.visible&&X.push(a,d,e,za.z,null)}for(var k=a.children,g=0,h=k.length;g<h;g++)q(k[g],b,c)}}function r(a,b,c,d){for(var e=0,f=a.length;e<f;e++){var g=a[e],h=g.object,i=g.geometry,j=void 0===d?g.material:d,k=g.group;if(c.isArrayCamera){ja=c;for(var l=c.cameras,m=0,n=l.length;m<n;m++){var o=l[m];if(h.layers.test(o.layers)){var p=o.bounds,q=p.x*oa,r=p.y*pa,t=p.z*oa,u=p.w*pa;Ga.viewport(ka.set(q,r,t,u).multiplyScalar(qa)),s(h,b,o,i,j,k)}}}else ja=null,s(h,b,c,i,j,k)}}function s(a,b,c,d,e,f){if(a.onBeforeRender(_,b,c,d,e,f),a.modelViewMatrix.multiplyMatrices(c.matrixWorldInverse,a.matrixWorld),a.normalMatrix.getNormalMatrix(a.modelViewMatrix),a.isImmediateRenderObject){var g=a.isMesh&&a.matrixWorld.determinant()<0;Ga.setMaterial(e,g);var h=u(c,b.fog,e,a);ha="",m(a,h,e)}else _.renderBufferDirect(c,b.fog,d,e,a,f);a.onAfterRender(_,b,c,d,e,f)}function t(a,b,c){var d=Ha.get(a),e=Pa.getParameters(a,Na.state,V,b,va.numPlanes,va.numIntersection,c),f=Pa.getProgramCode(a,e),g=d.program,i=!0;if(void 0===g)a.addEventListener("dispose",h);else if(g.code!==f)l(a);else{if(void 0!==e.shaderID)return;i=!1}if(i){if(e.shaderID){var j=Nf[e.shaderID];d.shader={name:a.type,uniforms:Jd.clone(j.uniforms),vertexShader:j.vertexShader,fragmentShader:j.fragmentShader}}else d.shader={name:a.type,uniforms:a.uniforms,vertexShader:a.vertexShader,fragmentShader:a.fragmentShader};a.onBeforeCompile(d.shader),g=Pa.acquireProgram(a,d.shader,e,f),d.program=g,a.program=g}var k=g.getAttributes();if(a.morphTargets){a.numSupportedMorphTargets=0;for(var m=0;m<_.maxMorphTargets;m++)k["morphTarget"+m]>=0&&a.numSupportedMorphTargets++}if(a.morphNormals){a.numSupportedMorphNormals=0;for(var m=0;m<_.maxMorphNormals;m++)k["morphNormal"+m]>=0&&a.numSupportedMorphNormals++}var n=d.shader.uniforms;(a.isShaderMaterial||a.isRawShaderMaterial)&&!0!==a.clipping||(d.numClippingPlanes=va.numPlanes,d.numIntersection=va.numIntersection,n.clippingPlanes=va.uniform),d.fog=b,d.lightsHash=Na.state.hash,a.lights&&(n.ambientLightColor.value=Na.state.ambient,n.directionalLights.value=Na.state.directional,n.spotLights.value=Na.state.spot,n.rectAreaLights.value=Na.state.rectArea,n.pointLights.value=Na.state.point,n.hemisphereLights.value=Na.state.hemi,n.directionalShadowMap.value=Na.state.directionalShadowMap,n.directionalShadowMatrix.value=Na.state.directionalShadowMatrix,n.spotShadowMap.value=Na.state.spotShadowMap,n.spotShadowMatrix.value=Na.state.spotShadowMatrix,n.pointShadowMap.value=Na.state.pointShadowMap,n.pointShadowMatrix.value=Na.state.pointShadowMatrix);var o=d.program.getUniforms(),p=T.seqWithValue(o.seq,n);d.uniformsList=p}function u(a,b,c,d){na=0;var e=Ha.get(c);if(wa&&(xa||a!==ia)){var f=a===ia&&c.id===ga;va.setState(c.clippingPlanes,c.clipIntersection,c.clipShadows,a,e,f)}!1===c.needsUpdate&&(void 0===e.program?c.needsUpdate=!0:c.fog&&e.fog!==b?c.needsUpdate=!0:c.lights&&e.lightsHash!==Na.state.hash?c.needsUpdate=!0:void 0===e.numClippingPlanes||e.numClippingPlanes===va.numPlanes&&e.numIntersection===va.numIntersection||(c.needsUpdate=!0)),c.needsUpdate&&(t(c,b,d),c.needsUpdate=!1);var g=!1,h=!1,i=!1,j=e.program,l=j.getUniforms(),m=e.shader.uniforms;if(Ga.useProgram(j.program)&&(g=!0,h=!0,i=!0),c.id!==ga&&(ga=c.id,h=!0),g||a!==ia){if(l.setValue(Ca,"projectionMatrix",a.projectionMatrix),Fa.logarithmicDepthBuffer&&l.setValue(Ca,"logDepthBufFC",2/(Math.log(a.far+1)/Math.LN2)),ia!==(ja||a)&&(ia=ja||a,h=!0,i=!0),c.isShaderMaterial||c.isMeshPhongMaterial||c.isMeshStandardMaterial||c.envMap){var n=l.map.cameraPosition;void 0!==n&&n.setValue(Ca,za.setFromMatrixPosition(a.matrixWorld))}(c.isMeshPhongMaterial||c.isMeshLambertMaterial||c.isMeshBasicMaterial||c.isMeshStandardMaterial||c.isShaderMaterial||c.skinning)&&l.setValue(Ca,"viewMatrix",a.matrixWorldInverse)}if(c.skinning){l.setOptional(Ca,d,"bindMatrix"),l.setOptional(Ca,d,"bindMatrixInverse");var o=d.skeleton;if(o){var p=o.bones;if(Fa.floatVertexTextures){if(void 0===o.boneTexture){var q=Math.sqrt(4*p.length);q=yd.ceilPowerOfTwo(q),q=Math.max(q,4);var r=new Float32Array(q*q*4);r.set(o.boneMatrices);var s=new k(r,q,q,$c,Sc);o.boneMatrices=r,o.boneTexture=s,o.boneTextureSize=q}l.setValue(Ca,"boneTexture",o.boneTexture),l.setValue(Ca,"boneTextureSize",o.boneTextureSize)}else l.setOptional(Ca,o,"boneMatrices")}}return h&&(l.setValue(Ca,"toneMappingExposure",_.toneMappingExposure),l.setValue(Ca,"toneMappingWhitePoint",_.toneMappingWhitePoint),c.lights&&I(m,i),b&&c.fog&&z(m,b),c.isMeshBasicMaterial?v(m,c):c.isMeshLambertMaterial?(v(m,c),A(m,c)):c.isMeshPhongMaterial?(v(m,c),c.isMeshToonMaterial?C(m,c):B(m,c)):c.isMeshStandardMaterial?(v(m,c),c.isMeshPhysicalMaterial?E(m,c):D(m,c)):c.isMeshDepthMaterial?(v(m,c),F(m,c)):c.isMeshDistanceMaterial?(v(m,c),G(m,c)):c.isMeshNormalMaterial?(v(m,c),H(m,c)):c.isLineBasicMaterial?(w(m,c),c.isLineDashedMaterial&&x(m,c)):c.isPointsMaterial?y(m,c):c.isShadowMaterial&&(m.color.value=c.color,m.opacity.value=c.opacity),void 0!==m.ltcMat&&(m.ltcMat.value=Id.LTC_MAT_TEXTURE),void 0!==m.ltcMag&&(m.ltcMag.value=Id.LTC_MAG_TEXTURE),T.upload(Ca,e.uniformsList,m,_)),l.setValue(Ca,"modelViewMatrix",d.modelViewMatrix),l.setValue(Ca,"normalMatrix",d.normalMatrix),l.setValue(Ca,"modelMatrix",d.matrixWorld),j}function v(a,b){a.opacity.value=b.opacity,b.color&&(a.diffuse.value=b.color),b.emissive&&a.emissive.value.copy(b.emissive).multiplyScalar(b.emissiveIntensity),b.map&&(a.map.value=b.map),b.alphaMap&&(a.alphaMap.value=b.alphaMap),b.specularMap&&(a.specularMap.value=b.specularMap),b.envMap&&(a.envMap.value=b.envMap,a.flipEnvMap.value=b.envMap&&b.envMap.isCubeTexture?-1:1,a.reflectivity.value=b.reflectivity,a.refractionRatio.value=b.refractionRatio),b.lightMap&&(a.lightMap.value=b.lightMap,a.lightMapIntensity.value=b.lightMapIntensity),b.aoMap&&(a.aoMap.value=b.aoMap,a.aoMapIntensity.value=b.aoMapIntensity);var c;if(b.map?c=b.map:b.specularMap?c=b.specularMap:b.displacementMap?c=b.displacementMap:b.normalMap?c=b.normalMap:b.bumpMap?c=b.bumpMap:b.roughnessMap?c=b.roughnessMap:b.metalnessMap?c=b.metalnessMap:b.alphaMap?c=b.alphaMap:b.emissiveMap&&(c=b.emissiveMap),void 0!==c){if(c.isWebGLRenderTarget&&(c=c.texture),!0===c.matrixAutoUpdate){var d=c.offset,e=c.repeat,f=c.rotation,g=c.center;c.matrix.setUvTransform(d.x,d.y,e.x,e.y,f,g.x,g.y)}a.uvTransform.value.copy(c.matrix)}}function w(a,b){a.diffuse.value=b.color,a.opacity.value=b.opacity}function x(a,b){a.dashSize.value=b.dashSize,a.totalSize.value=b.dashSize+b.gapSize,a.scale.value=b.scale}function y(a,b){if(a.diffuse.value=b.color,a.opacity.value=b.opacity,a.size.value=b.size*qa,a.scale.value=.5*pa,a.map.value=b.map,null!==b.map){if(!0===b.map.matrixAutoUpdate){var c=b.map.offset,d=b.map.repeat,e=b.map.rotation,f=b.map.center;b.map.matrix.setUvTransform(c.x,c.y,d.x,d.y,e,f.x,f.y)}a.uvTransform.value.copy(b.map.matrix)}}function z(a,b){a.fogColor.value=b.color,b.isFog?(a.fogNear.value=b.near,a.fogFar.value=b.far):b.isFogExp2&&(a.fogDensity.value=b.density)}function A(a,b){b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap)}function B(a,b){a.specular.value=b.specular,a.shininess.value=Math.max(b.shininess,1e-4),b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap),b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale),b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale)),b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias)}function C(a,b){B(a,b),b.gradientMap&&(a.gradientMap.value=b.gradientMap)}function D(a,b){a.roughness.value=b.roughness,a.metalness.value=b.metalness,b.roughnessMap&&(a.roughnessMap.value=b.roughnessMap),b.metalnessMap&&(a.metalnessMap.value=b.metalnessMap),b.emissiveMap&&(a.emissiveMap.value=b.emissiveMap),b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale),b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale)),b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias),b.envMap&&(a.envMapIntensity.value=b.envMapIntensity)}function E(a,b){a.clearCoat.value=b.clearCoat,a.clearCoatRoughness.value=b.clearCoatRoughness,D(a,b)}function F(a,b){b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias)}function G(a,b){b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias),a.referencePosition.value.copy(b.referencePosition),a.nearDistance.value=b.nearDistance,a.farDistance.value=b.farDistance}function H(a,b){b.bumpMap&&(a.bumpMap.value=b.bumpMap,a.bumpScale.value=b.bumpScale),b.normalMap&&(a.normalMap.value=b.normalMap,a.normalScale.value.copy(b.normalScale)),b.displacementMap&&(a.displacementMap.value=b.displacementMap,a.displacementScale.value=b.displacementScale,a.displacementBias.value=b.displacementBias)}function I(a,b){a.ambientLightColor.needsUpdate=b,a.directionalLights.needsUpdate=b,a.pointLights.needsUpdate=b,a.spotLights.needsUpdate=b,a.rectAreaLights.needsUpdate=b,a.hemisphereLights.needsUpdate=b}function J(){var a=na;return a>=Fa.maxTextures&&console.warn("THREE.WebGLRenderer: Trying to use "+a+" texture units while this GPU supports only "+Fa.maxTextures),na+=1,a}console.log("THREE.WebGLRenderer",zb),a=a||{};var K=void 0!==a.canvas?a.canvas:document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),L=void 0!==a.context?a.context:null,M=void 0!==a.alpha&&a.alpha,N=void 0===a.depth||a.depth,O=void 0===a.stencil||a.stencil,P=void 0!==a.antialias&&a.antialias,Q=void 0===a.premultipliedAlpha||a.premultipliedAlpha,R=void 0!==a.preserveDrawingBuffer&&a.preserveDrawingBuffer,S=void 0!==a.powerPreference?a.powerPreference:"default",U=[],V=[],X=null,Z=[],$=[];this.domElement=K,this.context=null,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.gammaFactor=2,this.gammaInput=!1,this.gammaOutput=!1,this.physicallyCorrectLights=!1,this.toneMapping=rc,this.toneMappingExposure=1,this.toneMappingWhitePoint=1,this.maxMorphTargets=8,this.maxMorphNormals=4;var _=this,aa=!1,ba=null,ca=null,ga=-1,ha="",ia=null,ja=null,ka=new i,la=new i,ma=null,na=0,oa=K.width,pa=K.height,qa=1,ra=new i(0,0,oa,pa),sa=new i(0,0,oa,pa),ta=!1,ua=new da,va=new sb,wa=!1,xa=!1,ya=new d,za=new f,Aa={geometries:0,textures:0},Ba={frame:0,calls:0,vertices:0,faces:0,points:0};this.info={render:Ba,memory:Aa,programs:null};var Ca;try{var Da={alpha:M,depth:N,stencil:O,antialias:P,premultipliedAlpha:Q,preserveDrawingBuffer:R,powerPreference:S};if(K.addEventListener("webglcontextlost",e,!1),K.addEventListener("webglcontextrestored",g,!1),null===(Ca=L||K.getContext("webgl",Da)||K.getContext("experimental-webgl",Da)))throw null!==K.getContext("webgl")?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.");void 0===Ca.getShaderPrecisionFormat&&(Ca.getShaderPrecisionFormat=function(){return{rangeMin:1,rangeMax:1,precision:1}})}catch(a){console.error("THREE.WebGLRenderer: "+a.message)}var Ea,Fa,Ga,Ha,Ia,Ja,La,Ma,Na,Pa,Ua,Xa,Ya,Za,$a,_a,ab,bb;c();var cb=new qb(_);this.vr=cb;var db=new ea(_,Ma,Fa.maxTextureSize);this.shadowMap=db,this.getContext=function(){return Ca},this.getContextAttributes=function(){return Ca.getContextAttributes()},this.forceContextLoss=function(){var a=Ea.get("WEBGL_lose_context");a&&a.loseContext()},this.forceContextRestore=function(){var a=Ea.get("WEBGL_lose_context");a&&a.restoreContext()},this.getPixelRatio=function(){return qa},this.setPixelRatio=function(a){void 0!==a&&(qa=a,this.setSize(oa,pa,!1))},this.getSize=function(){return{width:oa,height:pa}},this.setSize=function(a,b,c){var d=cb.getDevice();if(d&&d.isPresenting)return void console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");oa=a,pa=b,K.width=a*qa,K.height=b*qa,!1!==c&&(K.style.width=a+"px",K.style.height=b+"px"),this.setViewport(0,0,a,b)},this.getDrawingBufferSize=function(){return{width:oa*qa,height:pa*qa}},this.setDrawingBufferSize=function(a,b,c){oa=a,pa=b,qa=c,K.width=a*c,K.height=b*c,this.setViewport(0,0,a,b)},this.setViewport=function(a,b,c,d){ra.set(a,pa-b-d,c,d),Ga.viewport(ka.copy(ra).multiplyScalar(qa))},this.setScissor=function(a,b,c,d){sa.set(a,pa-b-d,c,d),Ga.scissor(la.copy(sa).multiplyScalar(qa))},this.setScissorTest=function(a){Ga.setScissorTest(ta=a)},this.getClearColor=function(){return Xa.getClearColor()},this.setClearColor=function(){Xa.setClearColor.apply(Xa,arguments)},this.getClearAlpha=function(){return Xa.getClearAlpha()},this.setClearAlpha=function(){Xa.setClearAlpha.apply(Xa,arguments)},this.clear=function(a,b,c){var d=0;(void 0===a||a)&&(d|=Ca.COLOR_BUFFER_BIT),(void 0===b||b)&&(d|=Ca.DEPTH_BUFFER_BIT),(void 0===c||c)&&(d|=Ca.STENCIL_BUFFER_BIT),Ca.clear(d)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.clearTarget=function(a,b,c,d){this.setRenderTarget(a),this.clear(b,c,d)},this.dispose=function(){K.removeEventListener("webglcontextlost",e,!1),K.removeEventListener("webglcontextrestored",g,!1),Ua.dispose(),cb.dispose()},this.renderBufferImmediate=function(a,b,c){Ga.initAttributes();var d=Ha.get(a);a.hasPositions&&!d.position&&(d.position=Ca.createBuffer()),a.hasNormals&&!d.normal&&(d.normal=Ca.createBuffer()),a.hasUvs&&!d.uv&&(d.uv=Ca.createBuffer()),a.hasColors&&!d.color&&(d.color=Ca.createBuffer());var e=b.getAttributes();if(a.hasPositions&&(Ca.bindBuffer(Ca.ARRAY_BUFFER,d.position),Ca.bufferData(Ca.ARRAY_BUFFER,a.positionArray,Ca.DYNAMIC_DRAW),Ga.enableAttribute(e.position),Ca.vertexAttribPointer(e.position,3,Ca.FLOAT,!1,0,0)),a.hasNormals){if(Ca.bindBuffer(Ca.ARRAY_BUFFER,d.normal),!c.isMeshPhongMaterial&&!c.isMeshStandardMaterial&&!c.isMeshNormalMaterial&&!0===c.flatShading)for(var f=0,g=3*a.count;f<g;f+=9){var h=a.normalArray,i=(h[f+0]+h[f+3]+h[f+6])/3,j=(h[f+1]+h[f+4]+h[f+7])/3,k=(h[f+2]+h[f+5]+h[f+8])/3;h[f+0]=i,h[f+1]=j,h[f+2]=k,h[f+3]=i,h[f+4]=j,h[f+5]=k,h[f+6]=i,h[f+7]=j,h[f+8]=k}Ca.bufferData(Ca.ARRAY_BUFFER,a.normalArray,Ca.DYNAMIC_DRAW),Ga.enableAttribute(e.normal),Ca.vertexAttribPointer(e.normal,3,Ca.FLOAT,!1,0,0)}a.hasUvs&&c.map&&(Ca.bindBuffer(Ca.ARRAY_BUFFER,d.uv),Ca.bufferData(Ca.ARRAY_BUFFER,a.uvArray,Ca.DYNAMIC_DRAW),Ga.enableAttribute(e.uv),Ca.vertexAttribPointer(e.uv,2,Ca.FLOAT,!1,0,0)),a.hasColors&&c.vertexColors!==Kb&&(Ca.bindBuffer(Ca.ARRAY_BUFFER,d.color),Ca.bufferData(Ca.ARRAY_BUFFER,a.colorArray,Ca.DYNAMIC_DRAW),Ga.enableAttribute(e.color),Ca.vertexAttribPointer(e.color,3,Ca.FLOAT,!1,0,0)),Ga.disableUnusedAttributes(),Ca.drawArrays(Ca.TRIANGLES,0,a.count),a.count=0},this.renderBufferDirect=function(a,c,d,e,f,g){var h=f.isMesh&&f.matrixWorld.determinant()<0;Ga.setMaterial(e,h);var i=u(a,c,e,f),j=d.id+"_"+i.id+"_"+(!0===e.wireframe),k=!1;j!==ha&&(ha=j,k=!0),f.morphTargetInfluences&&(Ya.update(f,d,e,i),k=!0);var l=d.index,m=d.attributes.position,o=1;!0===e.wireframe&&(l=La.getWireframeAttribute(d),o=2);var p,q=Za;null!==l&&(p=Ja.get(l),q=$a,q.setIndex(p)),k&&(n(e,i,d),null!==l&&Ca.bindBuffer(Ca.ELEMENT_ARRAY_BUFFER,p.buffer));var r=0;null!==l?r=l.count:void 0!==m&&(r=m.count);var s=d.drawRange.start*o,t=d.drawRange.count*o,v=null!==g?g.start*o:0,w=null!==g?g.count*o:1/0,x=Math.max(s,v),y=Math.min(r,s+t,v+w)-1,z=Math.max(0,y-x+1);if(0!==z){if(f.isMesh)if(!0===e.wireframe)Ga.setLineWidth(e.wireframeLinewidth*b()),q.setMode(Ca.LINES);else switch(f.drawMode){case md:q.setMode(Ca.TRIANGLES);break;case nd:q.setMode(Ca.TRIANGLE_STRIP);break;case od:q.setMode(Ca.TRIANGLE_FAN)}else if(f.isLine){var A=e.linewidth;void 0===A&&(A=1),Ga.setLineWidth(A*b()),f.isLineSegments?q.setMode(Ca.LINES):f.isLineLoop?q.setMode(Ca.LINE_LOOP):q.setMode(Ca.LINE_STRIP)}else f.isPoints&&q.setMode(Ca.POINTS);d&&d.isInstancedBufferGeometry?d.maxInstancedCount>0&&q.renderInstances(d,x,z):q.render(x,z)}},this.compile=function(a,b){U.length=0,V.length=0,a.traverse(function(a){a.isLight&&(U.push(a),a.castShadow&&V.push(a))}),Na.setup(U,V,b),a.traverse(function(b){if(b.material)if(Array.isArray(b.material))for(var c=0;c<b.material.length;c++)t(b.material[c],a.fog,b);else t(b.material,a.fog,b)})};var eb=!1,fb=null;this.animate=function(a){fb=a,o()},this.render=function(a,b,c,d){if(!b||!b.isCamera)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(!aa){ha="",ga=-1,ia=null,!0===a.autoUpdate&&a.updateMatrixWorld(),null===b.parent&&b.updateMatrixWorld(),cb.enabled&&(b=cb.getCamera(b)),ya.multiplyMatrices(b.projectionMatrix,b.matrixWorldInverse),ua.setFromMatrix(ya),U.length=0,V.length=0,Z.length=0,$.length=0,xa=this.localClippingEnabled,wa=va.init(this.clippingPlanes,xa,b),X=Ua.get(a,b),X.init(),q(a,b,_.sortObjects),!0===_.sortObjects&&X.sort(),Ia.updateVideoTextures(),wa&&va.beginShadows(),db.render(V,a,b),Na.setup(U,V,b),wa&&va.endShadows(),Ba.frame++,Ba.calls=0,Ba.vertices=0,Ba.faces=0,Ba.points=0,void 0===c&&(c=null),this.setRenderTarget(c),Xa.render(X,a,b,d);var e=X.opaque,f=X.transparent;if(a.overrideMaterial){var g=a.overrideMaterial;e.length&&r(e,a,b,g),f.length&&r(f,a,b,g)}else e.length&&r(e,a,b),f.length&&r(f,a,b);ab.render(Z,a,b),_a.render($,a,b,ka),c&&Ia.updateRenderTargetMipmap(c),Ga.buffers.depth.setTest(!0),Ga.buffers.depth.setMask(!0),Ga.buffers.color.setMask(!0),Ga.setPolygonOffset(!1),cb.enabled&&cb.submitFrame()}},this.setFaceCulling=function(a,b){Ga.setCullFace(a),Ga.setFlipSided(b===Db)},this.allocTextureUnit=J,this.setTexture2D=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTarget&&(a||(console.warn("THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead."),a=!0),b=b.texture),Ia.setTexture2D(b,c)}}(),this.setTexture=function(){var a=!1;return function(b,c){a||(console.warn("THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead."),a=!0),Ia.setTexture2D(b,c)}}(),this.setTextureCube=function(){var a=!1;return function(b,c){b&&b.isWebGLRenderTargetCube&&(a||(console.warn("THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead."),a=!0),b=b.texture),b&&b.isCubeTexture||Array.isArray(b.image)&&6===b.image.length?Ia.setTextureCube(b,c):Ia.setTextureCubeDynamic(b,c)}}(),this.getRenderTarget=function(){return ba},this.setRenderTarget=function(a){ba=a,a&&void 0===Ha.get(a).__webglFramebuffer&&Ia.setupRenderTarget(a);var b=null,c=!1;if(a){var d=Ha.get(a).__webglFramebuffer;a.isWebGLRenderTargetCube?(b=d[a.activeCubeFace],c=!0):b=d,ka.copy(a.viewport),la.copy(a.scissor),ma=a.scissorTest}else ka.copy(ra).multiplyScalar(qa),la.copy(sa).multiplyScalar(qa),ma=ta;if(ca!==b&&(Ca.bindFramebuffer(Ca.FRAMEBUFFER,b),ca=b),Ga.viewport(ka),Ga.scissor(la),Ga.setScissorTest(ma),c){var e=Ha.get(a.texture);Ca.framebufferTexture2D(Ca.FRAMEBUFFER,Ca.COLOR_ATTACHMENT0,Ca.TEXTURE_CUBE_MAP_POSITIVE_X+a.activeCubeFace,e.__webglTexture,a.activeMipMapLevel)}},this.readRenderTargetPixels=function(a,b,c,d,e,f){if(!a||!a.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");var g=Ha.get(a).__webglFramebuffer;if(g){var h=!1;g!==ca&&(Ca.bindFramebuffer(Ca.FRAMEBUFFER,g),h=!0);try{var i=a.texture,j=i.format,k=i.type;if(j!==$c&&bb.convert(j)!==Ca.getParameter(Ca.IMPLEMENTATION_COLOR_READ_FORMAT))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!(k===Mc||bb.convert(k)===Ca.getParameter(Ca.IMPLEMENTATION_COLOR_READ_TYPE)||k===Sc&&(Ea.get("OES_texture_float")||Ea.get("WEBGL_color_buffer_float"))||k===Tc&&Ea.get("EXT_color_buffer_half_float")))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");Ca.checkFramebufferStatus(Ca.FRAMEBUFFER)===Ca.FRAMEBUFFER_COMPLETE?b>=0&&b<=a.width-d&&c>=0&&c<=a.height-e&&Ca.readPixels(b,c,d,e,bb.convert(j),bb.convert(k),f):console.error("THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.")}finally{h&&Ca.bindFramebuffer(Ca.FRAMEBUFFER,ca)}}}}function vb(){ia.call(this),this.type="Scene",this.background=null,this.fog=null,this.overrideMaterial=null,this.autoUpdate=!0}function wb(a,b,c){var d=this,e=!1,f=0,g=0,h=void 0;this.onStart=void 0,this.onLoad=a,this.onProgress=b,this.onError=c,this.itemStart=function(a){g++,!1===e&&void 0!==d.onStart&&d.onStart(a,f,g),e=!0},this.itemEnd=function(a){f++,void 0!==d.onProgress&&d.onProgress(a,f,g),f===g&&(e=!1,void 0!==d.onLoad&&d.onLoad())},this.itemError=function(a){void 0!==d.onError&&d.onError(a)},this.resolveURL=function(a){return h?h(a):a},this.setURLModifier=function(a){return h=a,this}}function xb(a){this.manager=void 0!==a?a:Uf}function yb(a){this.manager=void 0!==a?a:Uf}void 0===Number.EPSILON&&(Number.EPSILON=Math.pow(2,-52)),void 0===Number.isInteger&&(Number.isInteger=function(a){return"number"==typeof a&&isFinite(a)&&Math.floor(a)===a}),void 0===Math.sign&&(Math.sign=function(a){return a<0?-1:a>0?1:+a}),"name"in Function.prototype==!1&&Object.defineProperty(Function.prototype,"name",{get:function(){return this.toString().match(/^\s*function\s*([^\(\s]*)/)[1]}}),void 0===Object.assign&&function(){Object.assign=function(a){if(void 0===a||null===a)throw new TypeError("Cannot convert undefined or null to object");for(var b=Object(a),c=1;c<arguments.length;c++){var d=arguments[c];if(void 0!==d&&null!==d)for(var e in d)Object.prototype.hasOwnProperty.call(d,e)&&(b[e]=d[e])}return b}}(),Object.assign(b.prototype,{addEventListener:function(a,b){void 0===this._listeners&&(this._listeners={});var c=this._listeners;void 0===c[a]&&(c[a]=[]),-1===c[a].indexOf(b)&&c[a].push(b)},hasEventListener:function(a,b){if(void 0===this._listeners)return!1;var c=this._listeners;return void 0!==c[a]&&-1!==c[a].indexOf(b)},removeEventListener:function(a,b){if(void 0!==this._listeners){var c=this._listeners,d=c[a];if(void 0!==d){var e=d.indexOf(b);-1!==e&&d.splice(e,1)}}},dispatchEvent:function(a){if(void 0!==this._listeners){var b=this._listeners,c=b[a.type];if(void 0!==c){a.target=this;for(var d=c.slice(0),e=0,f=d.length;e<f;e++)d[e].call(this,a)}}}});var zb="89",Ab=0,Bb=1,Cb=2,Db=0,Eb=1,Fb=2,Gb=0,Hb=1,Ib=2,Jb=1,Kb=0,Lb=0,Mb=1,Nb=2,Ob=3,Pb=4,Qb=5,Rb=100,Sb=101,Tb=102,Ub=103,Vb=104,Wb=200,Xb=201,Yb=202,Zb=203,$b=204,_b=205,ac=206,bc=207,cc=208,dc=209,ec=210,fc=0,gc=1,hc=2,ic=3,jc=4,kc=5,lc=6,mc=7,nc=0,oc=1,pc=2,qc=0,rc=1,sc=2,tc=3,uc=4,vc=300,wc=301,xc=302,yc=303,zc=304,Ac=305,Bc=306,Cc=307,Dc=1e3,Ec=1001,Fc=1002,Gc=1003,Hc=1004,Ic=1005,Jc=1006,Kc=1007,Lc=1008,Mc=1009,Nc=1010,Oc=1011,Pc=1012,Qc=1013,Rc=1014,Sc=1015,Tc=1016,Uc=1017,Vc=1018,Wc=1019,Xc=1020,Yc=1021,Zc=1022,$c=1023,_c=1024,ad=1025,bd=1026,cd=1027,dd=2001,ed=2002,fd=2003,gd=2004,hd=2100,id=2101,jd=2102,kd=2103,ld=2151,md=0,nd=1,od=2,pd=3e3,qd=3001,rd=3007,sd=3002,td=3004,ud=3005,vd=3006,wd=3200,xd=3201,yd={DEG2RAD:Math.PI/180,RAD2DEG:180/Math.PI,generateUUID:function(){for(var a=[],b=0;b<256;b++)a[b]=(b<16?"0":"")+b.toString(16).toUpperCase();return function(){var b=4294967295*Math.random()|0,c=4294967295*Math.random()|0,d=4294967295*Math.random()|0,e=4294967295*Math.random()|0;return a[255&b]+a[b>>8&255]+a[b>>16&255]+a[b>>24&255]+"-"+a[255&c]+a[c>>8&255]+"-"+a[c>>16&15|64]+a[c>>24&255]+"-"+a[63&d|128]+a[d>>8&255]+"-"+a[d>>16&255]+a[d>>24&255]+a[255&e]+a[e>>8&255]+a[e>>16&255]+a[e>>24&255]}}(),clamp:function(a,b,c){return Math.max(b,Math.min(c,a))},euclideanModulo:function(a,b){return(a%b+b)%b},mapLinear:function(a,b,c,d,e){return d+(a-b)*(e-d)/(c-b)},lerp:function(a,b,c){return(1-c)*a+c*b},smoothstep:function(a,b,c){return a<=b?0:a>=c?1:(a=(a-b)/(c-b))*a*(3-2*a)},smootherstep:function(a,b,c){return a<=b?0:a>=c?1:(a=(a-b)/(c-b))*a*a*(a*(6*a-15)+10)},randInt:function(a,b){return a+Math.floor(Math.random()*(b-a+1))},randFloat:function(a,b){return a+Math.random()*(b-a)},randFloatSpread:function(a){return a*(.5-Math.random())},degToRad:function(a){return a*yd.DEG2RAD},radToDeg:function(a){return a*yd.RAD2DEG},isPowerOfTwo:function(a){return 0==(a&a-1)&&0!==a},ceilPowerOfTwo:function(a){return Math.pow(2,Math.ceil(Math.log(a)/Math.LN2))},floorPowerOfTwo:function(a){return Math.pow(2,Math.floor(Math.log(a)/Math.LN2))}};Object.defineProperties(c.prototype,{width:{get:function(){return this.x},set:function(a){this.x=a}},height:{get:function(){return this.y},set:function(a){this.y=a}}}),Object.assign(c.prototype,{isVector2:!0,set:function(a,b){return this.x=a,this.y=b,this},setScalar:function(a){return this.x=a,this.y=a,this},setX:function(a){return this.x=a,this},setY:function(a){return this.y=a,this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;default:throw new Error("index is out of range: "+a)}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+a)}},clone:function(){return new this.constructor(this.x,this.y)},copy:function(a){return this.x=a.x,this.y=a.y,this},add:function(a,b){return void 0!==b?(console.warn("THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b)):(this.x+=a.x,this.y+=a.y,this)},addScalar:function(a){return this.x+=a,this.y+=a,this},addVectors:function(a,b){return this.x=a.x+b.x,this.y=a.y+b.y,this},addScaledVector:function(a,b){return this.x+=a.x*b,this.y+=a.y*b,this},sub:function(a,b){return void 0!==b?(console.warn("THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b)):(this.x-=a.x,this.y-=a.y,this)},subScalar:function(a){return this.x-=a,this.y-=a,this},subVectors:function(a,b){return this.x=a.x-b.x,this.y=a.y-b.y,this},multiply:function(a){return this.x*=a.x,this.y*=a.y,this},multiplyScalar:function(a){return this.x*=a,this.y*=a,this},divide:function(a){return this.x/=a.x,this.y/=a.y,this},divideScalar:function(a){return this.multiplyScalar(1/a)},applyMatrix3:function(a){var b=this.x,c=this.y,d=a.elements;return this.x=d[0]*b+d[3]*c+d[6],this.y=d[1]*b+d[4]*c+d[7],this},min:function(a){return this.x=Math.min(this.x,a.x),this.y=Math.min(this.y,a.y),this},max:function(a){return this.x=Math.max(this.x,a.x),this.y=Math.max(this.y,a.y),this},clamp:function(a,b){return this.x=Math.max(a.x,Math.min(b.x,this.x)),this.y=Math.max(a.y,Math.min(b.y,this.y)),this},clampScalar:function(){var a=new c,b=new c;return function(c,d){return a.set(c,c),b.set(d,d),this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this},negate:function(){return this.x=-this.x,this.y=-this.y,this},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)},normalize:function(){return this.divideScalar(this.length()||1)},angle:function(){var a=Math.atan2(this.y,this.x);return a<0&&(a+=2*Math.PI),a},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y;return b*b+c*c},manhattanDistanceTo:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){return this.x+=(a.x-this.x)*b,this.y+=(a.y-this.y)*b,this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y},fromArray:function(a,b){return void 0===b&&(b=0),this.x=a[b],this.y=a[b+1],this},toArray:function(a,b){return void 0===a&&(a=[]),void 0===b&&(b=0),a[b]=this.x,a[b+1]=this.y,a},fromBufferAttribute:function(a,b,c){return void 0!==c&&console.warn("THREE.Vector2: offset has been removed from .fromBufferAttribute()."),this.x=a.getX(b),this.y=a.getY(b),this},rotateAround:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=this.x-a.x,f=this.y-a.y;return this.x=e*c-f*d+a.x,this.y=e*d+f*c+a.y,this}}),Object.assign(d.prototype,{isMatrix4:!0,set:function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){var q=this.elements;return q[0]=a,q[4]=b,q[8]=c,q[12]=d,q[1]=e,q[5]=f,q[9]=g,q[13]=h,q[2]=i,q[6]=j,q[10]=k,q[14]=l,q[3]=m,q[7]=n,q[11]=o,q[15]=p,this},identity:function(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this},clone:function(){return(new d).fromArray(this.elements)},copy:function(a){var b=this.elements,c=a.elements;return b[0]=c[0],b[1]=c[1],b[2]=c[2],b[3]=c[3],b[4]=c[4],b[5]=c[5],b[6]=c[6],b[7]=c[7],b[8]=c[8],b[9]=c[9],b[10]=c[10],b[11]=c[11],b[12]=c[12],b[13]=c[13],b[14]=c[14],b[15]=c[15],this},copyPosition:function(a){var b=this.elements,c=a.elements;return b[12]=c[12],b[13]=c[13],b[14]=c[14],this},extractBasis:function(a,b,c){return a.setFromMatrixColumn(this,0),b.setFromMatrixColumn(this,1),c.setFromMatrixColumn(this,2),this},makeBasis:function(a,b,c){return this.set(a.x,b.x,c.x,0,a.y,b.y,c.y,0,a.z,b.z,c.z,0,0,0,0,1),this},extractRotation:function(){var a=new f;return function(b){var c=this.elements,d=b.elements,e=1/a.setFromMatrixColumn(b,0).length(),f=1/a.setFromMatrixColumn(b,1).length(),g=1/a.setFromMatrixColumn(b,2).length();return c[0]=d[0]*e,c[1]=d[1]*e,c[2]=d[2]*e,c[4]=d[4]*f,c[5]=d[5]*f,c[6]=d[6]*f,c[8]=d[8]*g,c[9]=d[9]*g,c[10]=d[10]*g,this}}(),makeRotationFromEuler:function(a){a&&a.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");var b=this.elements,c=a.x,d=a.y,e=a.z,f=Math.cos(c),g=Math.sin(c),h=Math.cos(d),i=Math.sin(d),j=Math.cos(e),k=Math.sin(e);if("XYZ"===a.order){var l=f*j,m=f*k,n=g*j,o=g*k;b[0]=h*j,b[4]=-h*k,b[8]=i,b[1]=m+n*i,b[5]=l-o*i,b[9]=-g*h,b[2]=o-l*i,b[6]=n+m*i,b[10]=f*h}else if("YXZ"===a.order){var p=h*j,q=h*k,r=i*j,s=i*k;b[0]=p+s*g,b[4]=r*g-q,b[8]=f*i,b[1]=f*k,b[5]=f*j,b[9]=-g,b[2]=q*g-r,b[6]=s+p*g,b[10]=f*h}else if("ZXY"===a.order){var p=h*j,q=h*k,r=i*j,s=i*k;b[0]=p-s*g,b[4]=-f*k,b[8]=r+q*g,b[1]=q+r*g,b[5]=f*j,b[9]=s-p*g,b[2]=-f*i,b[6]=g,b[10]=f*h}else if("ZYX"===a.order){var l=f*j,m=f*k,n=g*j,o=g*k;b[0]=h*j,b[4]=n*i-m,b[8]=l*i+o,b[1]=h*k,b[5]=o*i+l,b[9]=m*i-n,b[2]=-i,b[6]=g*h,b[10]=f*h}else if("YZX"===a.order){var t=f*h,u=f*i,v=g*h,w=g*i;b[0]=h*j,b[4]=w-t*k,b[8]=v*k+u,b[1]=k,b[5]=f*j,b[9]=-g*j,b[2]=-i*j,b[6]=u*k+v,b[10]=t-w*k}else if("XZY"===a.order){var t=f*h,u=f*i,v=g*h,w=g*i;b[0]=h*j,b[4]=-k,b[8]=i*j,b[1]=t*k+w,b[5]=f*j,b[9]=u*k-v,b[2]=v*k-u,b[6]=g*j,b[10]=w*k+t}return b[3]=0,b[7]=0,b[11]=0,b[12]=0,b[13]=0,b[14]=0,b[15]=1,this},makeRotationFromQuaternion:function(a){var b=this.elements,c=a._x,d=a._y,e=a._z,f=a._w,g=c+c,h=d+d,i=e+e,j=c*g,k=c*h,l=c*i,m=d*h,n=d*i,o=e*i,p=f*g,q=f*h,r=f*i;return b[0]=1-(m+o),b[4]=k-r,b[8]=l+q,b[1]=k+r,b[5]=1-(j+o),b[9]=n-p,b[2]=l-q,b[6]=n+p,b[10]=1-(j+m),b[3]=0,b[7]=0,b[11]=0,b[12]=0,b[13]=0,b[14]=0,b[15]=1,this},lookAt:function(){var a=new f,b=new f,c=new f;return function(d,e,f){var g=this.elements;return c.subVectors(d,e),0===c.lengthSq()&&(c.z=1),c.normalize(),a.crossVectors(f,c),0===a.lengthSq()&&(1===Math.abs(f.z)?c.x+=1e-4:c.z+=1e-4,c.normalize(),a.crossVectors(f,c)),a.normalize(),b.crossVectors(c,a),g[0]=a.x,g[4]=b.x,g[8]=c.x,g[1]=a.y,g[5]=b.y,g[9]=c.y,g[2]=a.z,g[6]=b.z,g[10]=c.z,this}}(),multiply:function(a,b){return void 0!==b?(console.warn("THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead."),this.multiplyMatrices(a,b)):this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[4],h=c[8],i=c[12],j=c[1],k=c[5],l=c[9],m=c[13],n=c[2],o=c[6],p=c[10],q=c[14],r=c[3],s=c[7],t=c[11],u=c[15],v=d[0],w=d[4],x=d[8],y=d[12],z=d[1],A=d[5],B=d[9],C=d[13],D=d[2],E=d[6],F=d[10],G=d[14],H=d[3],I=d[7],J=d[11],K=d[15];return e[0]=f*v+g*z+h*D+i*H,e[4]=f*w+g*A+h*E+i*I,e[8]=f*x+g*B+h*F+i*J,e[12]=f*y+g*C+h*G+i*K,e[1]=j*v+k*z+l*D+m*H,e[5]=j*w+k*A+l*E+m*I,e[9]=j*x+k*B+l*F+m*J,e[13]=j*y+k*C+l*G+m*K,e[2]=n*v+o*z+p*D+q*H,e[6]=n*w+o*A+p*E+q*I,e[10]=n*x+o*B+p*F+q*J,e[14]=n*y+o*C+p*G+q*K,e[3]=r*v+s*z+t*D+u*H,e[7]=r*w+s*A+t*E+u*I,e[11]=r*x+s*B+t*F+u*J,e[15]=r*y+s*C+t*G+u*K,this},multiplyScalar:function(a){var b=this.elements;return b[0]*=a,b[4]*=a,b[8]*=a,b[12]*=a,b[1]*=a,b[5]*=a,b[9]*=a,b[13]*=a,b[2]*=a,b[6]*=a,b[10]*=a,b[14]*=a,b[3]*=a,b[7]*=a,b[11]*=a,b[15]*=a,this},applyToBufferAttribute:function(){var a=new f;return function(b){for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix4(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),determinant:function(){var a=this.elements,b=a[0],c=a[4],d=a[8],e=a[12],f=a[1],g=a[5],h=a[9],i=a[13],j=a[2],k=a[6],l=a[10],m=a[14];return a[3]*(+e*h*k-d*i*k-e*g*l+c*i*l+d*g*m-c*h*m)+a[7]*(+b*h*m-b*i*l+e*f*l-d*f*m+d*i*j-e*h*j)+a[11]*(+b*i*k-b*g*m-e*f*k+c*f*m+e*g*j-c*i*j)+a[15]*(-d*g*j-b*h*k+b*g*l+d*f*k-c*f*l+c*h*j)},transpose:function(){var a,b=this.elements;return a=b[1],b[1]=b[4],b[4]=a,a=b[2],b[2]=b[8],b[8]=a,a=b[6],b[6]=b[9],b[9]=a,a=b[3],b[3]=b[12],b[12]=a,a=b[7],b[7]=b[13],b[13]=a,a=b[11],b[11]=b[14],b[14]=a,this},setPosition:function(a){var b=this.elements;return b[12]=a.x,b[13]=a.y,b[14]=a.z,this},getInverse:function(a,b){var c=this.elements,d=a.elements,e=d[0],f=d[1],g=d[2],h=d[3],i=d[4],j=d[5],k=d[6],l=d[7],m=d[8],n=d[9],o=d[10],p=d[11],q=d[12],r=d[13],s=d[14],t=d[15],u=n*s*l-r*o*l+r*k*p-j*s*p-n*k*t+j*o*t,v=q*o*l-m*s*l-q*k*p+i*s*p+m*k*t-i*o*t,w=m*r*l-q*n*l+q*j*p-i*r*p-m*j*t+i*n*t,x=q*n*k-m*r*k-q*j*o+i*r*o+m*j*s-i*n*s,y=e*u+f*v+g*w+h*x;if(0===y){var z="THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";if(!0===b)throw new Error(z);return console.warn(z),this.identity()}var A=1/y;return c[0]=u*A,c[1]=(r*o*h-n*s*h-r*g*p+f*s*p+n*g*t-f*o*t)*A,c[2]=(j*s*h-r*k*h+r*g*l-f*s*l-j*g*t+f*k*t)*A,c[3]=(n*k*h-j*o*h-n*g*l+f*o*l+j*g*p-f*k*p)*A,c[4]=v*A,c[5]=(m*s*h-q*o*h+q*g*p-e*s*p-m*g*t+e*o*t)*A,c[6]=(q*k*h-i*s*h-q*g*l+e*s*l+i*g*t-e*k*t)*A,c[7]=(i*o*h-m*k*h+m*g*l-e*o*l-i*g*p+e*k*p)*A,c[8]=w*A,c[9]=(q*n*h-m*r*h-q*f*p+e*r*p+m*f*t-e*n*t)*A,c[10]=(i*r*h-q*j*h+q*f*l-e*r*l-i*f*t+e*j*t)*A,c[11]=(m*j*h-i*n*h-m*f*l+e*n*l+i*f*p-e*j*p)*A,c[12]=x*A,c[13]=(m*r*g-q*n*g+q*f*o-e*r*o-m*f*s+e*n*s)*A,c[14]=(q*j*g-i*r*g-q*f*k+e*r*k+i*f*s-e*j*s)*A,c[15]=(i*n*g-m*j*g+m*f*k-e*n*k-i*f*o+e*j*o)*A,this},scale:function(a){var b=this.elements,c=a.x,d=a.y,e=a.z;return b[0]*=c,b[4]*=d,b[8]*=e,b[1]*=c,b[5]*=d,b[9]*=e,b[2]*=c,b[6]*=d,b[10]*=e,b[3]*=c,b[7]*=d,b[11]*=e,this},getMaxScaleOnAxis:function(){var a=this.elements,b=a[0]*a[0]+a[1]*a[1]+a[2]*a[2],c=a[4]*a[4]+a[5]*a[5]+a[6]*a[6],d=a[8]*a[8]+a[9]*a[9]+a[10]*a[10];return Math.sqrt(Math.max(b,c,d))},makeTranslation:function(a,b,c){return this.set(1,0,0,a,0,1,0,b,0,0,1,c,0,0,0,1),this},makeRotationX:function(a){var b=Math.cos(a),c=Math.sin(a);return this.set(1,0,0,0,0,b,-c,0,0,c,b,0,0,0,0,1),this},makeRotationY:function(a){var b=Math.cos(a),c=Math.sin(a);return this.set(b,0,c,0,0,1,0,0,-c,0,b,0,0,0,0,1),this},makeRotationZ:function(a){var b=Math.cos(a),c=Math.sin(a);return this.set(b,-c,0,0,c,b,0,0,0,0,1,0,0,0,0,1),this},makeRotationAxis:function(a,b){var c=Math.cos(b),d=Math.sin(b),e=1-c,f=a.x,g=a.y,h=a.z,i=e*f,j=e*g;return this.set(i*f+c,i*g-d*h,i*h+d*g,0,i*g+d*h,j*g+c,j*h-d*f,0,i*h-d*g,j*h+d*f,e*h*h+c,0,0,0,0,1),this},makeScale:function(a,b,c){return this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1),this},makeShear:function(a,b,c){return this.set(1,b,c,0,a,1,c,0,a,b,1,0,0,0,0,1),this},compose:function(a,b,c){return this.makeRotationFromQuaternion(b),this.scale(c),this.setPosition(a),this},decompose:function(){var a=new f,b=new d;return function(c,d,e){var f=this.elements,g=a.set(f[0],f[1],f[2]).length(),h=a.set(f[4],f[5],f[6]).length(),i=a.set(f[8],f[9],f[10]).length();this.determinant()<0&&(g=-g),c.x=f[12],c.y=f[13],c.z=f[14],b.copy(this);var j=1/g,k=1/h,l=1/i;return b.elements[0]*=j,b.elements[1]*=j,b.elements[2]*=j,b.elements[4]*=k,b.elements[5]*=k,b.elements[6]*=k,b.elements[8]*=l,b.elements[9]*=l,b.elements[10]*=l,d.setFromRotationMatrix(b),e.x=g,e.y=h,e.z=i,this}}(),makePerspective:function(a,b,c,d,e,f){void 0===f&&console.warn("THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.");var g=this.elements,h=2*e/(b-a),i=2*e/(c-d),j=(b+a)/(b-a),k=(c+d)/(c-d),l=-(f+e)/(f-e),m=-2*f*e/(f-e);return g[0]=h,g[4]=0,g[8]=j,g[12]=0,g[1]=0,g[5]=i,g[9]=k,g[13]=0,g[2]=0,g[6]=0,g[10]=l,g[14]=m,g[3]=0,g[7]=0,g[11]=-1,g[15]=0,this},makeOrthographic:function(a,b,c,d,e,f){var g=this.elements,h=1/(b-a),i=1/(c-d),j=1/(f-e),k=(b+a)*h,l=(c+d)*i,m=(f+e)*j;return g[0]=2*h,g[4]=0,g[8]=0,g[12]=-k,g[1]=0,g[5]=2*i,g[9]=0,g[13]=-l,g[2]=0,g[6]=0,g[10]=-2*j,g[14]=-m,g[3]=0,g[7]=0,g[11]=0,g[15]=1,this},equals:function(a){for(var b=this.elements,c=a.elements,d=0;d<16;d++)if(b[d]!==c[d])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;c<16;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]),void 0===b&&(b=0);var c=this.elements;return a[b]=c[0],a[b+1]=c[1],a[b+2]=c[2],a[b+3]=c[3],a[b+4]=c[4],a[b+5]=c[5],a[b+6]=c[6],a[b+7]=c[7],a[b+8]=c[8],a[b+9]=c[9],a[b+10]=c[10],a[b+11]=c[11],a[b+12]=c[12],a[b+13]=c[13],a[b+14]=c[14],a[b+15]=c[15],a}}),Object.assign(e,{slerp:function(a,b,c,d){return c.copy(a).slerp(b,d)},slerpFlat:function(a,b,c,d,e,f,g){var h=c[d+0],i=c[d+1],j=c[d+2],k=c[d+3],l=e[f+0],m=e[f+1],n=e[f+2],o=e[f+3];if(k!==o||h!==l||i!==m||j!==n){var p=1-g,q=h*l+i*m+j*n+k*o,r=q>=0?1:-1,s=1-q*q;if(s>Number.EPSILON){var t=Math.sqrt(s),u=Math.atan2(t,q*r);p=Math.sin(p*u)/t,g=Math.sin(g*u)/t}var v=g*r;if(h=h*p+l*v,i=i*p+m*v,j=j*p+n*v,k=k*p+o*v,p===1-g){var w=1/Math.sqrt(h*h+i*i+j*j+k*k);h*=w,i*=w,j*=w,k*=w}}a[b]=h,a[b+1]=i,a[b+2]=j,a[b+3]=k}}),Object.defineProperties(e.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a,this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a,this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a,this.onChangeCallback()}},w:{get:function(){return this._w},set:function(a){this._w=a,this.onChangeCallback()}}}),Object.assign(e.prototype,{set:function(a,b,c,d){return this._x=a,this._y=b,this._z=c,this._w=d,this.onChangeCallback(),this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._w)},copy:function(a){return this._x=a.x,this._y=a.y,this._z=a.z,this._w=a.w,this.onChangeCallback(),this},setFromEuler:function(a,b){if(!a||!a.isEuler)throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var c=a._x,d=a._y,e=a._z,f=a.order,g=Math.cos,h=Math.sin,i=g(c/2),j=g(d/2),k=g(e/2),l=h(c/2),m=h(d/2),n=h(e/2);return"XYZ"===f?(this._x=l*j*k+i*m*n,this._y=i*m*k-l*j*n,this._z=i*j*n+l*m*k,this._w=i*j*k-l*m*n):"YXZ"===f?(this._x=l*j*k+i*m*n,this._y=i*m*k-l*j*n,this._z=i*j*n-l*m*k,this._w=i*j*k+l*m*n):"ZXY"===f?(this._x=l*j*k-i*m*n,this._y=i*m*k+l*j*n,this._z=i*j*n+l*m*k,this._w=i*j*k-l*m*n):"ZYX"===f?(this._x=l*j*k-i*m*n,this._y=i*m*k+l*j*n,this._z=i*j*n-l*m*k,this._w=i*j*k+l*m*n):"YZX"===f?(this._x=l*j*k+i*m*n,this._y=i*m*k+l*j*n,this._z=i*j*n-l*m*k,this._w=i*j*k-l*m*n):"XZY"===f&&(this._x=l*j*k-i*m*n,this._y=i*m*k-l*j*n,this._z=i*j*n+l*m*k,this._w=i*j*k+l*m*n),!1!==b&&this.onChangeCallback(),this},setFromAxisAngle:function(a,b){var c=b/2,d=Math.sin(c);return this._x=a.x*d,this._y=a.y*d,this._z=a.z*d,this._w=Math.cos(c),this.onChangeCallback(),this},setFromRotationMatrix:function(a){var b,c=a.elements,d=c[0],e=c[4],f=c[8],g=c[1],h=c[5],i=c[9],j=c[2],k=c[6],l=c[10],m=d+h+l;return m>0?(b=.5/Math.sqrt(m+1),this._w=.25/b,this._x=(k-i)*b,this._y=(f-j)*b,this._z=(g-e)*b):d>h&&d>l?(b=2*Math.sqrt(1+d-h-l),this._w=(k-i)/b,this._x=.25*b,this._y=(e+g)/b,this._z=(f+j)/b):h>l?(b=2*Math.sqrt(1+h-d-l),this._w=(f-j)/b,this._x=(e+g)/b,this._y=.25*b,this._z=(i+k)/b):(b=2*Math.sqrt(1+l-d-h),this._w=(g-e)/b,this._x=(f+j)/b,this._y=(i+k)/b,this._z=.25*b),this.onChangeCallback(),this},setFromUnitVectors:function(){var a,b=new f;return function(c,d){return void 0===b&&(b=new f),a=c.dot(d)+1,a<1e-6?(a=0,Math.abs(c.x)>Math.abs(c.z)?b.set(-c.y,c.x,0):b.set(0,-c.z,c.y)):b.crossVectors(c,d),this._x=b.x,this._y=b.y,this._z=b.z,this._w=a,this.normalize()}}(),inverse:function(){return this.conjugate().normalize()},conjugate:function(){return this._x*=-1,this._y*=-1,this._z*=-1,this.onChangeCallback(),this},dot:function(a){return this._x*a._x+this._y*a._y+this._z*a._z+this._w*a._w},lengthSq:function(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w},length:function(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)},normalize:function(){var a=this.length();return 0===a?(this._x=0,this._y=0,this._z=0,this._w=1):(a=1/a,this._x=this._x*a,this._y=this._y*a,this._z=this._z*a,this._w=this._w*a),this.onChangeCallback(),this},multiply:function(a,b){return void 0!==b?(console.warn("THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead."),this.multiplyQuaternions(a,b)):this.multiplyQuaternions(this,a)},premultiply:function(a){return this.multiplyQuaternions(a,this)},multiplyQuaternions:function(a,b){var c=a._x,d=a._y,e=a._z,f=a._w,g=b._x,h=b._y,i=b._z,j=b._w;return this._x=c*j+f*g+d*i-e*h,this._y=d*j+f*h+e*g-c*i,this._z=e*j+f*i+c*h-d*g,this._w=f*j-c*g-d*h-e*i,this.onChangeCallback(),this},slerp:function(a,b){if(0===b)return this;if(1===b)return this.copy(a);var c=this._x,d=this._y,e=this._z,f=this._w,g=f*a._w+c*a._x+d*a._y+e*a._z;if(g<0?(this._w=-a._w,this._x=-a._x,this._y=-a._y,this._z=-a._z,g=-g):this.copy(a),g>=1)return this._w=f,this._x=c,this._y=d,this._z=e,this;var h=Math.sqrt(1-g*g);if(Math.abs(h)<.001)return this._w=.5*(f+this._w),this._x=.5*(c+this._x),this._y=.5*(d+this._y),this._z=.5*(e+this._z),this;var i=Math.atan2(h,g),j=Math.sin((1-b)*i)/h,k=Math.sin(b*i)/h;return this._w=f*j+this._w*k,this._x=c*j+this._x*k,this._y=d*j+this._y*k,this._z=e*j+this._z*k,this.onChangeCallback(),this},equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._w===this._w},fromArray:function(a,b){return void 0===b&&(b=0),this._x=a[b],this._y=a[b+1],this._z=a[b+2],this._w=a[b+3],this.onChangeCallback(),this},toArray:function(a,b){return void 0===a&&(a=[]),void 0===b&&(b=0),a[b]=this._x,a[b+1]=this._y,a[b+2]=this._z,a[b+3]=this._w,a},onChange:function(a){return this.onChangeCallback=a,this},onChangeCallback:function(){}}),Object.assign(f.prototype,{isVector3:!0,set:function(a,b,c){return this.x=a,this.y=b,this.z=c,this},setScalar:function(a){return this.x=a,this.y=a,this.z=a,this},setX:function(a){return this.x=a,this},setY:function(a){return this.y=a,this},setZ:function(a){return this.z=a,this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;default:throw new Error("index is out of range: "+a)}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+a)}},clone:function(){return new this.constructor(this.x,this.y,this.z)},copy:function(a){return this.x=a.x,this.y=a.y,this.z=a.z,this},add:function(a,b){return void 0!==b?(console.warn("THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b)):(this.x+=a.x,this.y+=a.y,this.z+=a.z,this)},addScalar:function(a){return this.x+=a,this.y+=a,this.z+=a,this},addVectors:function(a,b){return this.x=a.x+b.x,this.y=a.y+b.y,this.z=a.z+b.z,this},addScaledVector:function(a,b){return this.x+=a.x*b,this.y+=a.y*b,this.z+=a.z*b,this},sub:function(a,b){return void 0!==b?(console.warn("THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b)):(this.x-=a.x,this.y-=a.y,this.z-=a.z,this)},subScalar:function(a){return this.x-=a,this.y-=a,this.z-=a,this},subVectors:function(a,b){return this.x=a.x-b.x,this.y=a.y-b.y,this.z=a.z-b.z,this},multiply:function(a,b){return void 0!==b?(console.warn("THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead."),this.multiplyVectors(a,b)):(this.x*=a.x,this.y*=a.y,this.z*=a.z,this)},multiplyScalar:function(a){return this.x*=a,this.y*=a,this.z*=a,this},multiplyVectors:function(a,b){return this.x=a.x*b.x,this.y=a.y*b.y,this.z=a.z*b.z,this},applyEuler:function(){var a=new e;return function(b){return b&&b.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(a.setFromEuler(b))}}(),applyAxisAngle:function(){var a=new e;return function(b,c){return this.applyQuaternion(a.setFromAxisAngle(b,c))}}(),applyMatrix3:function(a){var b=this.x,c=this.y,d=this.z,e=a.elements;return this.x=e[0]*b+e[3]*c+e[6]*d,this.y=e[1]*b+e[4]*c+e[7]*d,this.z=e[2]*b+e[5]*c+e[8]*d,this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=a.elements,f=1/(e[3]*b+e[7]*c+e[11]*d+e[15]);return this.x=(e[0]*b+e[4]*c+e[8]*d+e[12])*f,this.y=(e[1]*b+e[5]*c+e[9]*d+e[13])*f,this.z=(e[2]*b+e[6]*c+e[10]*d+e[14])*f,this},applyQuaternion:function(a){var b=this.x,c=this.y,d=this.z,e=a.x,f=a.y,g=a.z,h=a.w,i=h*b+f*d-g*c,j=h*c+g*b-e*d,k=h*d+e*c-f*b,l=-e*b-f*c-g*d;return this.x=i*h+l*-e+j*-g-k*-f,this.y=j*h+l*-f+k*-e-i*-g,this.z=k*h+l*-g+i*-f-j*-e,this},project:function(){var a=new d;return function(b){return a.multiplyMatrices(b.projectionMatrix,a.getInverse(b.matrixWorld)),this.applyMatrix4(a)}}(),unproject:function(){var a=new d;return function(b){return a.multiplyMatrices(b.matrixWorld,a.getInverse(b.projectionMatrix)),this.applyMatrix4(a)}}(),transformDirection:function(a){var b=this.x,c=this.y,d=this.z,e=a.elements;return this.x=e[0]*b+e[4]*c+e[8]*d,this.y=e[1]*b+e[5]*c+e[9]*d,this.z=e[2]*b+e[6]*c+e[10]*d,this.normalize()},divide:function(a){return this.x/=a.x,this.y/=a.y,this.z/=a.z,this},divideScalar:function(a){return this.multiplyScalar(1/a)},min:function(a){return this.x=Math.min(this.x,a.x),this.y=Math.min(this.y,a.y),this.z=Math.min(this.z,a.z),this},max:function(a){return this.x=Math.max(this.x,a.x),this.y=Math.max(this.y,a.y),this.z=Math.max(this.z,a.z),this},clamp:function(a,b){return this.x=Math.max(a.x,Math.min(b.x,this.x)),this.y=Math.max(a.y,Math.min(b.y,this.y)),this.z=Math.max(a.z,Math.min(b.z,this.z)),this},clampScalar:function(){var a=new f,b=new f;return function(c,d){return a.set(c,c,c),b.set(d,d,d),this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){return this.x+=(a.x-this.x)*b,this.y+=(a.y-this.y)*b,this.z+=(a.z-this.z)*b,this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},cross:function(a,b){return void 0!==b?(console.warn("THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead."),this.crossVectors(a,b)):this.crossVectors(this,a)},crossVectors:function(a,b){var c=a.x,d=a.y,e=a.z,f=b.x,g=b.y,h=b.z;return this.x=d*h-e*g,this.y=e*f-c*h,this.z=c*g-d*f,this},projectOnVector:function(a){var b=a.dot(this)/a.lengthSq();return this.copy(a).multiplyScalar(b)},projectOnPlane:function(){var a=new f;return function(b){return a.copy(this).projectOnVector(b),this.sub(a)}}(),reflect:function(){var a=new f;return function(b){return this.sub(a.copy(b).multiplyScalar(2*this.dot(b)))}}(),angleTo:function(a){var b=this.dot(a)/Math.sqrt(this.lengthSq()*a.lengthSq());return Math.acos(yd.clamp(b,-1,1))},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,c=this.y-a.y,d=this.z-a.z;return b*b+c*c+d*d},manhattanDistanceTo:function(a){return Math.abs(this.x-a.x)+Math.abs(this.y-a.y)+Math.abs(this.z-a.z)},setFromSpherical:function(a){var b=Math.sin(a.phi)*a.radius;return this.x=b*Math.sin(a.theta),this.y=Math.cos(a.phi)*a.radius,this.z=b*Math.cos(a.theta),this},setFromCylindrical:function(a){return this.x=a.radius*Math.sin(a.theta),this.y=a.y,this.z=a.radius*Math.cos(a.theta),this},setFromMatrixPosition:function(a){var b=a.elements;return this.x=b[12],this.y=b[13],this.z=b[14],this},setFromMatrixScale:function(a){var b=this.setFromMatrixColumn(a,0).length(),c=this.setFromMatrixColumn(a,1).length(),d=this.setFromMatrixColumn(a,2).length();return this.x=b,this.y=c,this.z=d,this},setFromMatrixColumn:function(a,b){return this.fromArray(a.elements,4*b)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z},fromArray:function(a,b){return void 0===b&&(b=0),this.x=a[b],this.y=a[b+1],this.z=a[b+2],this},toArray:function(a,b){return void 0===a&&(a=[]),void 0===b&&(b=0),a[b]=this.x,a[b+1]=this.y,a[b+2]=this.z,a},fromBufferAttribute:function(a,b,c){return void 0!==c&&console.warn("THREE.Vector3: offset has been removed from .fromBufferAttribute()."),this.x=a.getX(b),this.y=a.getY(b),this.z=a.getZ(b),this}}),Object.assign(g.prototype,{isMatrix3:!0,set:function(a,b,c,d,e,f,g,h,i){var j=this.elements;return j[0]=a,j[1]=d,j[2]=g,j[3]=b,j[4]=e,j[5]=h,j[6]=c,j[7]=f,j[8]=i,this},identity:function(){return this.set(1,0,0,0,1,0,0,0,1),this},clone:function(){return(new this.constructor).fromArray(this.elements)},copy:function(a){var b=this.elements,c=a.elements;return b[0]=c[0],b[1]=c[1],b[2]=c[2],b[3]=c[3],b[4]=c[4],b[5]=c[5],b[6]=c[6],b[7]=c[7],b[8]=c[8],this},setFromMatrix4:function(a){var b=a.elements;return this.set(b[0],b[4],b[8],b[1],b[5],b[9],b[2],b[6],b[10]),this},applyToBufferAttribute:function(){var a=new f;return function(b){for(var c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.applyMatrix3(this),b.setXYZ(c,a.x,a.y,a.z);return b}}(),multiply:function(a){return this.multiplyMatrices(this,a)},premultiply:function(a){return this.multiplyMatrices(a,this)},multiplyMatrices:function(a,b){var c=a.elements,d=b.elements,e=this.elements,f=c[0],g=c[3],h=c[6],i=c[1],j=c[4],k=c[7],l=c[2],m=c[5],n=c[8],o=d[0],p=d[3],q=d[6],r=d[1],s=d[4],t=d[7],u=d[2],v=d[5],w=d[8];return e[0]=f*o+g*r+h*u,e[3]=f*p+g*s+h*v,e[6]=f*q+g*t+h*w,e[1]=i*o+j*r+k*u,e[4]=i*p+j*s+k*v,e[7]=i*q+j*t+k*w,e[2]=l*o+m*r+n*u,e[5]=l*p+m*s+n*v,e[8]=l*q+m*t+n*w,this},multiplyScalar:function(a){var b=this.elements;return b[0]*=a,b[3]*=a,b[6]*=a,b[1]*=a,b[4]*=a,b[7]*=a,b[2]*=a,b[5]*=a,b[8]*=a,this},determinant:function(){var a=this.elements,b=a[0],c=a[1],d=a[2],e=a[3],f=a[4],g=a[5],h=a[6],i=a[7],j=a[8];return b*f*j-b*g*i-c*e*j+c*g*h+d*e*i-d*f*h},getInverse:function(a,b){a&&a.isMatrix4&&console.error("THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument.");var c=a.elements,d=this.elements,e=c[0],f=c[1],g=c[2],h=c[3],i=c[4],j=c[5],k=c[6],l=c[7],m=c[8],n=m*i-j*l,o=j*k-m*h,p=l*h-i*k,q=e*n+f*o+g*p;if(0===q){var r="THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";if(!0===b)throw new Error(r);return console.warn(r),this.identity()}var s=1/q;return d[0]=n*s,d[1]=(g*l-m*f)*s,d[2]=(j*f-g*i)*s,d[3]=o*s,d[4]=(m*e-g*k)*s,d[5]=(g*h-j*e)*s,d[6]=p*s,d[7]=(f*k-l*e)*s,d[8]=(i*e-f*h)*s,this},transpose:function(){var a,b=this.elements;return a=b[1],b[1]=b[3],b[3]=a,a=b[2],b[2]=b[6],b[6]=a,a=b[5],b[5]=b[7],b[7]=a,this},getNormalMatrix:function(a){return this.setFromMatrix4(a).getInverse(this).transpose()},transposeIntoArray:function(a){var b=this.elements;return a[0]=b[0],a[1]=b[3],a[2]=b[6],a[3]=b[1],a[4]=b[4],a[5]=b[7],a[6]=b[2],a[7]=b[5],a[8]=b[8],this},setUvTransform:function(a,b,c,d,e,f,g){var h=Math.cos(e),i=Math.sin(e);this.set(c*h,c*i,-c*(h*f+i*g)+f+a,-d*i,d*h,-d*(-i*f+h*g)+g+b,0,0,1)},scale:function(a,b){var c=this.elements;return c[0]*=a,c[3]*=a,c[6]*=a,c[1]*=b,c[4]*=b,c[7]*=b,this},rotate:function(a){var b=Math.cos(a),c=Math.sin(a),d=this.elements,e=d[0],f=d[3],g=d[6],h=d[1],i=d[4],j=d[7];return d[0]=b*e+c*h,d[3]=b*f+c*i,d[6]=b*g+c*j,d[1]=-c*e+b*h,d[4]=-c*f+b*i,d[7]=-c*g+b*j,this},translate:function(a,b){var c=this.elements;return c[0]+=a*c[2],c[3]+=a*c[5],c[6]+=a*c[8],c[1]+=b*c[2],c[4]+=b*c[5],c[7]+=b*c[8],this},equals:function(a){for(var b=this.elements,c=a.elements,d=0;d<9;d++)if(b[d]!==c[d])return!1;return!0},fromArray:function(a,b){void 0===b&&(b=0);for(var c=0;c<9;c++)this.elements[c]=a[c+b];return this},toArray:function(a,b){void 0===a&&(a=[]),void 0===b&&(b=0);var c=this.elements;return a[b]=c[0],a[b+1]=c[1],a[b+2]=c[2],a[b+3]=c[3],a[b+4]=c[4],a[b+5]=c[5],a[b+6]=c[6],a[b+7]=c[7],a[b+8]=c[8],a}});var zd=0;h.DEFAULT_IMAGE=void 0,h.DEFAULT_MAPPING=vc,h.prototype=Object.assign(Object.create(b.prototype),{constructor:h,isTexture:!0,clone:function(){return(new this.constructor).copy(this)},copy:function(a){return this.name=a.name,this.image=a.image,this.mipmaps=a.mipmaps.slice(0),this.mapping=a.mapping,this.wrapS=a.wrapS,this.wrapT=a.wrapT,this.magFilter=a.magFilter,this.minFilter=a.minFilter,this.anisotropy=a.anisotropy,this.format=a.format,this.type=a.type,this.offset.copy(a.offset),this.repeat.copy(a.repeat),this.center.copy(a.center),this.rotation=a.rotation,this.matrixAutoUpdate=a.matrixAutoUpdate,this.matrix.copy(a.matrix),this.generateMipmaps=a.generateMipmaps,this.premultiplyAlpha=a.premultiplyAlpha,this.flipY=a.flipY,this.unpackAlignment=a.unpackAlignment,this.encoding=a.encoding,this},toJSON:function(a){function b(a){var b;if(a instanceof HTMLCanvasElement)b=a;else{b=document.createElementNS("http://www.w3.org/1999/xhtml","canvas"),b.width=a.width,b.height=a.height;var c=b.getContext("2d");a instanceof ImageData?c.putImageData(a,0,0):c.drawImage(a,0,0,a.width,a.height)}return b.width>2048||b.height>2048?b.toDataURL("image/jpeg",.6):b.toDataURL("image/png")}var c=void 0===a||"string"==typeof a;if(!c&&void 0!==a.textures[this.uuid])return a.textures[this.uuid];var d={metadata:{version:4.5,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY};if(void 0!==this.image){var e=this.image;void 0===e.uuid&&(e.uuid=yd.generateUUID()),c||void 0!==a.images[e.uuid]||(a.images[e.uuid]={uuid:e.uuid,url:b(e)}),d.image=e.uuid}return c||(a.textures[this.uuid]=d),d},dispose:function(){this.dispatchEvent({type:"dispose"})},transformUv:function(a){if(this.mapping===vc){if(a.applyMatrix3(this.matrix),a.x<0||a.x>1)switch(this.wrapS){case Dc:a.x=a.x-Math.floor(a.x);break;case Ec:a.x=a.x<0?0:1;break;case Fc:1===Math.abs(Math.floor(a.x)%2)?a.x=Math.ceil(a.x)-a.x:a.x=a.x-Math.floor(a.x)}if(a.y<0||a.y>1)switch(this.wrapT){case Dc:a.y=a.y-Math.floor(a.y);break;case Ec:a.y=a.y<0?0:1;break;case Fc:1===Math.abs(Math.floor(a.y)%2)?a.y=Math.ceil(a.y)-a.y:a.y=a.y-Math.floor(a.y)}this.flipY&&(a.y=1-a.y)}}}),Object.defineProperty(h.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}}),Object.assign(i.prototype,{isVector4:!0,set:function(a,b,c,d){return this.x=a,this.y=b,this.z=c,this.w=d,this},setScalar:function(a){return this.x=a,this.y=a,this.z=a,this.w=a,this},setX:function(a){return this.x=a,this},setY:function(a){return this.y=a,this},setZ:function(a){return this.z=a,this},setW:function(a){return this.w=a,this},setComponent:function(a,b){switch(a){case 0:this.x=b;break;case 1:this.y=b;break;case 2:this.z=b;break;case 3:this.w=b;break;default:throw new Error("index is out of range: "+a)}return this},getComponent:function(a){switch(a){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+a)}},clone:function(){return new this.constructor(this.x,this.y,this.z,this.w)},copy:function(a){return this.x=a.x,this.y=a.y,this.z=a.z,this.w=void 0!==a.w?a.w:1,this},add:function(a,b){return void 0!==b?(console.warn("THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead."),this.addVectors(a,b)):(this.x+=a.x,this.y+=a.y,this.z+=a.z,this.w+=a.w,this)},addScalar:function(a){return this.x+=a,this.y+=a,this.z+=a,this.w+=a,this},addVectors:function(a,b){return this.x=a.x+b.x,this.y=a.y+b.y,this.z=a.z+b.z,this.w=a.w+b.w,this},addScaledVector:function(a,b){return this.x+=a.x*b,this.y+=a.y*b,this.z+=a.z*b,this.w+=a.w*b,this},sub:function(a,b){return void 0!==b?(console.warn("THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead."),this.subVectors(a,b)):(this.x-=a.x,this.y-=a.y,this.z-=a.z,this.w-=a.w,this)},subScalar:function(a){return this.x-=a,this.y-=a,this.z-=a,this.w-=a,this},subVectors:function(a,b){return this.x=a.x-b.x,this.y=a.y-b.y,this.z=a.z-b.z,this.w=a.w-b.w,this},multiplyScalar:function(a){return this.x*=a,this.y*=a,this.z*=a,this.w*=a,this},applyMatrix4:function(a){var b=this.x,c=this.y,d=this.z,e=this.w,f=a.elements;return this.x=f[0]*b+f[4]*c+f[8]*d+f[12]*e,this.y=f[1]*b+f[5]*c+f[9]*d+f[13]*e,this.z=f[2]*b+f[6]*c+f[10]*d+f[14]*e,this.w=f[3]*b+f[7]*c+f[11]*d+f[15]*e,this},divideScalar:function(a){return this.multiplyScalar(1/a)},setAxisAngleFromQuaternion:function(a){this.w=2*Math.acos(a.w);var b=Math.sqrt(1-a.w*a.w);return b<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=a.x/b,this.y=a.y/b,this.z=a.z/b),this},setAxisAngleFromRotationMatrix:function(a){var b,c,d,e,f=.01,g=.1,h=a.elements,i=h[0],j=h[4],k=h[8],l=h[1],m=h[5],n=h[9],o=h[2],p=h[6],q=h[10];if(Math.abs(j-l)<f&&Math.abs(k-o)<f&&Math.abs(n-p)<f){if(Math.abs(j+l)<g&&Math.abs(k+o)<g&&Math.abs(n+p)<g&&Math.abs(i+m+q-3)<g)return this.set(1,0,0,0),this;b=Math.PI;var r=(i+1)/2,s=(m+1)/2,t=(q+1)/2,u=(j+l)/4,v=(k+o)/4,w=(n+p)/4;return r>s&&r>t?r<f?(c=0,d=.707106781,e=.707106781):(c=Math.sqrt(r),d=u/c,e=v/c):s>t?s<f?(c=.707106781,d=0,e=.707106781):(d=Math.sqrt(s),c=u/d,e=w/d):t<f?(c=.707106781,d=.707106781,e=0):(e=Math.sqrt(t),c=v/e,d=w/e),this.set(c,d,e,b),this}var x=Math.sqrt((p-n)*(p-n)+(k-o)*(k-o)+(l-j)*(l-j));return Math.abs(x)<.001&&(x=1),this.x=(p-n)/x,this.y=(k-o)/x,this.z=(l-j)/x,this.w=Math.acos((i+m+q-1)/2),this},min:function(a){return this.x=Math.min(this.x,a.x),this.y=Math.min(this.y,a.y),this.z=Math.min(this.z,a.z),this.w=Math.min(this.w,a.w),this},max:function(a){return this.x=Math.max(this.x,a.x),this.y=Math.max(this.y,a.y),this.z=Math.max(this.z,a.z),this.w=Math.max(this.w,a.w),this},clamp:function(a,b){return this.x=Math.max(a.x,Math.min(b.x,this.x)),this.y=Math.max(a.y,Math.min(b.y,this.y)),this.z=Math.max(a.z,Math.min(b.z,this.z)),this.w=Math.max(a.w,Math.min(b.w,this.w)),this},clampScalar:function(){var a,b;return function(c,d){return void 0===a&&(a=new i,b=new i),a.set(c,c,c,c),b.set(d,d,d,d),this.clamp(a,b)}}(),clampLength:function(a,b){var c=this.length();return this.divideScalar(c||1).multiplyScalar(Math.max(a,Math.min(b,c)))},floor:function(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this},ceil:function(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this},round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this},roundToZero:function(){return this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x),this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y),this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z),this.w=this.w<0?Math.ceil(this.w):Math.floor(this.w),this},negate:function(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},manhattanLength:function(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)},normalize:function(){return this.divideScalar(this.length()||1)},setLength:function(a){return this.normalize().multiplyScalar(a)},lerp:function(a,b){return this.x+=(a.x-this.x)*b,this.y+=(a.y-this.y)*b,this.z+=(a.z-this.z)*b,this.w+=(a.w-this.w)*b,this},lerpVectors:function(a,b,c){return this.subVectors(b,a).multiplyScalar(c).add(a)},equals:function(a){return a.x===this.x&&a.y===this.y&&a.z===this.z&&a.w===this.w},fromArray:function(a,b){return void 0===b&&(b=0),this.x=a[b],this.y=a[b+1],this.z=a[b+2],this.w=a[b+3],this},toArray:function(a,b){return void 0===a&&(a=[]),void 0===b&&(b=0),a[b]=this.x,a[b+1]=this.y,a[b+2]=this.z,a[b+3]=this.w,a},fromBufferAttribute:function(a,b,c){return void 0!==c&&console.warn("THREE.Vector4: offset has been removed from .fromBufferAttribute()."),this.x=a.getX(b),this.y=a.getY(b),this.z=a.getZ(b),this.w=a.getW(b),this}}),j.prototype=Object.assign(Object.create(b.prototype),{constructor:j,isWebGLRenderTarget:!0,setSize:function(a,b){this.width===a&&this.height===b||(this.width=a,this.height=b,this.dispose()),this.viewport.set(0,0,a,b),this.scissor.set(0,0,a,b)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){return this.width=a.width,this.height=a.height,this.viewport.copy(a.viewport),this.texture=a.texture.clone(),this.depthBuffer=a.depthBuffer,this.stencilBuffer=a.stencilBuffer,this.depthTexture=a.depthTexture,this},dispose:function(){this.dispatchEvent({type:"dispose"})}}),k.prototype=Object.create(h.prototype),k.prototype.constructor=k,k.prototype.isDataTexture=!0,l.prototype=Object.create(h.prototype),l.prototype.constructor=l,l.prototype.isCubeTexture=!0,Object.defineProperty(l.prototype,"images",{get:function(){return this.image},set:function(a){this.image=a}});var Ad=new h,Bd=new l,Cd=[],Dd=[],Ed=new Float32Array(16),Fd=new Float32Array(9);Q.prototype.setValue=function(a,b){for(var c=this.seq,d=0,e=c.length;d!==e;++d){var f=c[d];f.setValue(a,b[f.id])}};var Gd=/([\w\d_]+)(\])?(\[|\.)?/g;T.prototype.setValue=function(a,b,c){var d=this.map[b];void 0!==d&&d.setValue(a,c,this.renderer)},T.prototype.setOptional=function(a,b,c){var d=b[c];void 0!==d&&this.setValue(a,c,d)},T.upload=function(a,b,c,d){for(var e=0,f=b.length;e!==f;++e){var g=b[e],h=c[g.id];!1!==h.needsUpdate&&g.setValue(a,h.value,d)}},T.seqWithValue=function(a,b){for(var c=[],d=0,e=a.length;d!==e;++d){var f=a[d];f.id in b&&c.push(f)}return c};var Hd={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};Object.assign(U.prototype,{isColor:!0,r:1,g:1,b:1,set:function(a){return a&&a.isColor?this.copy(a):"number"==typeof a?this.setHex(a):"string"==typeof a&&this.setStyle(a),this},setScalar:function(a){return this.r=a,this.g=a,this.b=a,this},setHex:function(a){return a=Math.floor(a),this.r=(a>>16&255)/255,this.g=(a>>8&255)/255,this.b=(255&a)/255,this},setRGB:function(a,b,c){return this.r=a,this.g=b,this.b=c,this},setHSL:function(){function a(a,b,c){return c<0&&(c+=1),c>1&&(c-=1),c<1/6?a+6*(b-a)*c:c<.5?b:c<2/3?a+6*(b-a)*(2/3-c):a}return function(b,c,d){if(b=yd.euclideanModulo(b,1),c=yd.clamp(c,0,1),d=yd.clamp(d,0,1),0===c)this.r=this.g=this.b=d;else{var e=d<=.5?d*(1+c):d+c-d*c,f=2*d-e;this.r=a(f,e,b+1/3),this.g=a(f,e,b),this.b=a(f,e,b-1/3)}return this}}(),setStyle:function(a){function b(b){void 0!==b&&parseFloat(b)<1&&console.warn("THREE.Color: Alpha component of "+a+" will be ignored.")}var c;if(c=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(a)){var d,e=c[1],f=c[2];switch(e){case"rgb":case"rgba":if(d=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(f))return this.r=Math.min(255,parseInt(d[1],10))/255,this.g=Math.min(255,parseInt(d[2],10))/255,this.b=Math.min(255,parseInt(d[3],10))/255,b(d[5]),this;if(d=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(f))return this.r=Math.min(100,parseInt(d[1],10))/100,this.g=Math.min(100,parseInt(d[2],10))/100,this.b=Math.min(100,parseInt(d[3],10))/100,b(d[5]),this;break;case"hsl":case"hsla":if(d=/^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(f)){var g=parseFloat(d[1])/360,h=parseInt(d[2],10)/100,i=parseInt(d[3],10)/100;return b(d[5]),this.setHSL(g,h,i)}}}else if(c=/^\#([A-Fa-f0-9]+)$/.exec(a)){var j=c[1],k=j.length;if(3===k)return this.r=parseInt(j.charAt(0)+j.charAt(0),16)/255,this.g=parseInt(j.charAt(1)+j.charAt(1),16)/255,this.b=parseInt(j.charAt(2)+j.charAt(2),16)/255,this;if(6===k)return this.r=parseInt(j.charAt(0)+j.charAt(1),16)/255,this.g=parseInt(j.charAt(2)+j.charAt(3),16)/255,this.b=parseInt(j.charAt(4)+j.charAt(5),16)/255,this}if(a&&a.length>0){var j=Hd[a];void 0!==j?this.setHex(j):console.warn("THREE.Color: Unknown color "+a)}return this},clone:function(){return new this.constructor(this.r,this.g,this.b)},copy:function(a){return this.r=a.r,this.g=a.g,this.b=a.b,this},copyGammaToLinear:function(a,b){return void 0===b&&(b=2),this.r=Math.pow(a.r,b),this.g=Math.pow(a.g,b),this.b=Math.pow(a.b,b),this},copyLinearToGamma:function(a,b){void 0===b&&(b=2);var c=b>0?1/b:1;return this.r=Math.pow(a.r,c),this.g=Math.pow(a.g,c),this.b=Math.pow(a.b,c),this},convertGammaToLinear:function(){var a=this.r,b=this.g,c=this.b;return this.r=a*a,this.g=b*b,this.b=c*c,this},convertLinearToGamma:function(){return this.r=Math.sqrt(this.r),this.g=Math.sqrt(this.g),this.b=Math.sqrt(this.b),this},getHex:function(){return 255*this.r<<16^255*this.g<<8^255*this.b<<0},getHexString:function(){return("000000"+this.getHex().toString(16)).slice(-6)},getHSL:function(a){var b,c,d=a||{h:0,s:0,l:0},e=this.r,f=this.g,g=this.b,h=Math.max(e,f,g),i=Math.min(e,f,g),j=(i+h)/2;if(i===h)b=0,c=0;else{var k=h-i;switch(c=j<=.5?k/(h+i):k/(2-h-i),h){case e:b=(f-g)/k+(f<g?6:0);break;case f:b=(g-e)/k+2;break;case g:b=(e-f)/k+4}b/=6}return d.h=b,d.s=c,d.l=j,d},getStyle:function(){return"rgb("+(255*this.r|0)+","+(255*this.g|0)+","+(255*this.b|0)+")"},offsetHSL:function(a,b,c){var d=this.getHSL();return d.h+=a,d.s+=b,d.l+=c,this.setHSL(d.h,d.s,d.l),this},add:function(a){return this.r+=a.r,this.g+=a.g,this.b+=a.b,this},addColors:function(a,b){return this.r=a.r+b.r,this.g=a.g+b.g,this.b=a.b+b.b,this},addScalar:function(a){return this.r+=a,this.g+=a,this.b+=a,this},sub:function(a){return this.r=Math.max(0,this.r-a.r),this.g=Math.max(0,this.g-a.g),this.b=Math.max(0,this.b-a.b),this},multiply:function(a){return this.r*=a.r,this.g*=a.g,this.b*=a.b,this},multiplyScalar:function(a){return this.r*=a,this.g*=a,this.b*=a,this},lerp:function(a,b){return this.r+=(a.r-this.r)*b,this.g+=(a.g-this.g)*b,this.b+=(a.b-this.b)*b,this},equals:function(a){return a.r===this.r&&a.g===this.g&&a.b===this.b},fromArray:function(a,b){return void 0===b&&(b=0),this.r=a[b],this.g=a[b+1],this.b=a[b+2],this},toArray:function(a,b){return void 0===a&&(a=[]),void 0===b&&(b=0),a[b]=this.r,a[b+1]=this.g,a[b+2]=this.b,a},toJSON:function(){return this.getHex()}});var Id={common:{diffuse:{value:new U(15658734)},opacity:{value:1},map:{value:null},uvTransform:{value:new g},alphaMap:{value:null}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new c(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new U(16777215)}},lights:{ambientLightColor:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{},shadow:{},shadowBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}}},points:{diffuse:{value:new U(15658734)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},uvTransform:{value:new g}}},Jd={merge:function(a){for(var b={},c=0;c<a.length;c++){var d=this.clone(a[c]);for(var e in d)b[e]=d[e]}return b},clone:function(a){var b={};for(var c in a){b[c]={};for(var d in a[c]){var e=a[c][d];e&&(e.isColor||e.isMatrix3||e.isMatrix4||e.isVector2||e.isVector3||e.isVector4||e.isTexture)?b[c][d]=e.clone():Array.isArray(e)?b[c][d]=e.slice():b[c][d]=e}}return b}},Kd="#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n",Ld="#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n",Md="#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n",Nd="#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n",Od="#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",Pd="\nvec3 transformed = vec3( position );\n",Qd="\nvec3 objectNormal = vec3( normal );\n",Rd="float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\n\treturn result;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n",Sd="#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n",Td="#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n",Ud="#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n",Vd="#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n",Wd="#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n",Xd="#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif",Yd="#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n",Zd="#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif",$d="#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif",_d="#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\n",ae="#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n",be="vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n",ce="#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n",de="#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n",ee="#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n",fe="#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n",ge=" gl_FragColor = linearToOutputTexel( gl_FragColor );\n",he="\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n",ie="#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n",je="#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n",ke="#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n",le="#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n",me="\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif",ne="#ifdef USE_FOG\n varying float fogDepth;\n#endif\n",oe="#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n",pe="#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif\n",qe="#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n",re="#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n",se="#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",te="vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n",ue="uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n",ve="BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n",we="varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n",xe="PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n",ye="struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( 1, 0, t.y ),\n\t\t\tvec3( 0, t.z, 0 ),\n\t\t\tvec3( t.w, 0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n",ze="\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n",Ae="#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",Be="#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n",Ce="#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif",De="#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\tgl_Position.z *= gl_Position.w;\n\t#endif\n#endif\n",Ee="#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n",Fe="#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n",Ge="#ifdef USE_MAP\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n",He="#ifdef USE_MAP\n\tuniform mat3 uvTransform;\n\tuniform sampler2D map;\n#endif\n",Ie="float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n",Je="#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",Ke="#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n",Le="#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif",Me="#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n",Ne="#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n",Oe="#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n",Pe="vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n",Qe="#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n",Re="vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n",Se="#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n",Te="#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n",Ue="float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n",Ve="#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",We="#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n",Xe="#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n",Ye="#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n",Ze="float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n",$e="#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",_e="#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n",af="#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n",bf="#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n",cf="float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",df="#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",ef="#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n",ff="#ifndef saturate\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n",gf="#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif",hf="#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\n",jf="#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif",kf="#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif",lf="#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif",mf="#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif",nf="#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n",of="uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n",pf="varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}\n",qf="#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n",rf="#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n",sf="#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}\n",tf="#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}\n",uf="uniform sampler2D tEquirect;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n",vf="varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n",wf="uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",xf="uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}\n",yf="uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",zf="#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}\n",Af="uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",Bf="#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",Cf="#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",Df="#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",Ef="#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n",Ff="#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",Gf="#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n",Hf="#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n",If="uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n",Jf="uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",Kf="uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <fog_fragment>\n}\n",Lf="#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n",Mf={alphamap_fragment:Kd,alphamap_pars_fragment:Ld,alphatest_fragment:Md,aomap_fragment:Nd,aomap_pars_fragment:Od,begin_vertex:Pd,beginnormal_vertex:Qd,bsdfs:Rd,bumpmap_pars_fragment:Sd,clipping_planes_fragment:Td,clipping_planes_pars_fragment:Ud,clipping_planes_pars_vertex:Vd,clipping_planes_vertex:Wd,color_fragment:Xd,color_pars_fragment:Yd,color_pars_vertex:Zd,color_vertex:$d,common:_d,cube_uv_reflection_fragment:ae,defaultnormal_vertex:be,displacementmap_pars_vertex:ce,displacementmap_vertex:de,emissivemap_fragment:ee,emissivemap_pars_fragment:fe,encodings_fragment:ge,encodings_pars_fragment:he,envmap_fragment:ie,envmap_pars_fragment:je,envmap_pars_vertex:ke,envmap_vertex:le,fog_vertex:me,fog_pars_vertex:ne,fog_fragment:oe,fog_pars_fragment:pe,gradientmap_pars_fragment:qe,lightmap_fragment:re,lightmap_pars_fragment:se,lights_lambert_vertex:te,lights_pars:ue,lights_phong_fragment:ve,lights_phong_pars_fragment:we,lights_physical_fragment:xe,lights_physical_pars_fragment:ye,lights_template:ze,logdepthbuf_fragment:Ae,logdepthbuf_pars_fragment:Be,logdepthbuf_pars_vertex:Ce,logdepthbuf_vertex:De,map_fragment:Ee,map_pars_fragment:Fe,map_particle_fragment:Ge,map_particle_pars_fragment:He,metalnessmap_fragment:Ie,metalnessmap_pars_fragment:Je,morphnormal_vertex:Ke,morphtarget_pars_vertex:Le,morphtarget_vertex:Me,normal_fragment:Ne,normalmap_pars_fragment:Oe,packing:Pe,premultiplied_alpha_fragment:Qe,project_vertex:Re,dithering_fragment:Se,dithering_pars_fragment:Te,roughnessmap_fragment:Ue,roughnessmap_pars_fragment:Ve,shadowmap_pars_fragment:We,shadowmap_pars_vertex:Xe,shadowmap_vertex:Ye,shadowmask_pars_fragment:Ze,skinbase_vertex:$e,skinning_pars_vertex:_e,skinning_vertex:af,skinnormal_vertex:bf,specularmap_fragment:cf,specularmap_pars_fragment:df,tonemapping_fragment:ef,tonemapping_pars_fragment:ff,uv_pars_fragment:gf,uv_pars_vertex:hf,uv_vertex:jf,uv2_pars_fragment:kf,uv2_pars_vertex:lf,uv2_vertex:mf,worldpos_vertex:nf,cube_frag:of,cube_vert:pf,depth_frag:qf,depth_vert:rf,distanceRGBA_frag:sf,distanceRGBA_vert:tf,equirect_frag:uf,equirect_vert:vf,linedashed_frag:wf,linedashed_vert:xf,meshbasic_frag:yf,meshbasic_vert:zf,meshlambert_frag:Af,meshlambert_vert:Bf,meshphong_frag:Cf,meshphong_vert:Df,meshphysical_frag:Ef,meshphysical_vert:Ff,normal_frag:Gf,normal_vert:Hf,points_frag:If,points_vert:Jf,shadow_frag:Kf,shadow_vert:Lf},Nf={basic:{uniforms:Jd.merge([Id.common,Id.specularmap,Id.envmap,Id.aomap,Id.lightmap,Id.fog]),vertexShader:Mf.meshbasic_vert,fragmentShader:Mf.meshbasic_frag},lambert:{uniforms:Jd.merge([Id.common,Id.specularmap,Id.envmap,Id.aomap,Id.lightmap,Id.emissivemap,Id.fog,Id.lights,{emissive:{value:new U(0)}}]),vertexShader:Mf.meshlambert_vert,fragmentShader:Mf.meshlambert_frag},phong:{uniforms:Jd.merge([Id.common,Id.specularmap,Id.envmap,Id.aomap,Id.lightmap,Id.emissivemap,Id.bumpmap,Id.normalmap,Id.displacementmap,Id.gradientmap,Id.fog,Id.lights,{emissive:{value:new U(0)},specular:{value:new U(1118481)},shininess:{value:30}}]),vertexShader:Mf.meshphong_vert,fragmentShader:Mf.meshphong_frag},standard:{uniforms:Jd.merge([Id.common,Id.envmap,Id.aomap,Id.lightmap,Id.emissivemap,Id.bumpmap,Id.normalmap,Id.displacementmap,Id.roughnessmap,Id.metalnessmap,Id.fog,Id.lights,{emissive:{value:new U(0)},roughness:{value:.5},metalness:{value:.5},envMapIntensity:{value:1}}]),vertexShader:Mf.meshphysical_vert,fragmentShader:Mf.meshphysical_frag},points:{uniforms:Jd.merge([Id.points,Id.fog]),vertexShader:Mf.points_vert,fragmentShader:Mf.points_frag},dashed:{uniforms:Jd.merge([Id.common,Id.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Mf.linedashed_vert,fragmentShader:Mf.linedashed_frag},depth:{uniforms:Jd.merge([Id.common,Id.displacementmap]),vertexShader:Mf.depth_vert,fragmentShader:Mf.depth_frag},normal:{uniforms:Jd.merge([Id.common,Id.bumpmap,Id.normalmap,Id.displacementmap,{opacity:{value:1}}]),vertexShader:Mf.normal_vert,fragmentShader:Mf.normal_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Mf.cube_vert,fragmentShader:Mf.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Mf.equirect_vert,fragmentShader:Mf.equirect_frag},distanceRGBA:{uniforms:Jd.merge([Id.common,Id.displacementmap,{referencePosition:{value:new f},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Mf.distanceRGBA_vert,fragmentShader:Mf.distanceRGBA_frag},shadow:{uniforms:Jd.merge([Id.lights,Id.fog,{color:{value:new U(0)},opacity:{value:1}}]),vertexShader:Mf.shadow_vert,fragmentShader:Mf.shadow_frag}};Nf.physical={uniforms:Jd.merge([Nf.standard.uniforms,{clearCoat:{value:0},clearCoatRoughness:{value:0}}]),vertexShader:Mf.meshphysical_vert,fragmentShader:Mf.meshphysical_frag},Object.assign(V.prototype,{set:function(a,b){return this.min.copy(a),this.max.copy(b),this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new c;return function(b,c){var d=a.copy(c).multiplyScalar(.5);return this.min.copy(b).sub(d),this.max.copy(b).add(d),this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){return this.min.copy(a.min),this.max.copy(a.max),this},makeEmpty:function(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y},getCenter:function(a){var b=a||new c;return this.isEmpty()?b.set(0,0):b.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){var b=a||new c;return this.isEmpty()?b.set(0,0):b.subVectors(this.max,this.min)},expandByPoint:function(a){return this.min.min(a),this.max.max(a),this},expandByVector:function(a){return this.min.sub(a),this.max.add(a),this},expandByScalar:function(a){return this.min.addScalar(-a),this.max.addScalar(a),this},containsPoint:function(a){return!(a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y)},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y},getParameter:function(a,b){return(b||new c).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y))},intersectsBox:function(a){return!(a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y)},clampPoint:function(a,b){return(b||new c).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new c;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),intersect:function(a){return this.min.max(a.min),this.max.min(a.max),this},union:function(a){return this.min.min(a.min),this.max.max(a.max),this},translate:function(a){return this.min.add(a),this.max.add(a),this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}}),X.prototype=Object.create(h.prototype),X.prototype.constructor=X;var Of=0;Z.prototype=Object.assign(Object.create(b.prototype),{constructor:Z,isMaterial:!0,onBeforeCompile:function(){},setValues:function(a){if(void 0!==a)for(var b in a){var c=a[b];if(void 0!==c)if("shading"!==b){var d=this[b];void 0!==d?d&&d.isColor?d.set(c):d&&d.isVector3&&c&&c.isVector3?d.copy(c):this[b]="overdraw"===b?Number(c):c:console.warn("THREE."+this.type+": '"+b+"' is not a property of this material.")}else console.warn("THREE."+this.type+": .shading has been removed. Use the boolean .flatShading instead."),this.flatShading=c===Jb;else console.warn("THREE.Material: '"+b+"' parameter is undefined.")}},toJSON:function(a){function b(a){var b=[];for(var c in a){var d=a[c];delete d.metadata,b.push(d)}return b}var c=void 0===a||"string"==typeof a;c&&(a={textures:{},images:{}});var d={metadata:{version:4.5,type:"Material",generator:"Material.toJSON"}};if(d.uuid=this.uuid,d.type=this.type,""!==this.name&&(d.name=this.name),this.color&&this.color.isColor&&(d.color=this.color.getHex()),void 0!==this.roughness&&(d.roughness=this.roughness),void 0!==this.metalness&&(d.metalness=this.metalness),this.emissive&&this.emissive.isColor&&(d.emissive=this.emissive.getHex()),1!==this.emissiveIntensity&&(d.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(d.specular=this.specular.getHex()),void 0!==this.shininess&&(d.shininess=this.shininess),void 0!==this.clearCoat&&(d.clearCoat=this.clearCoat),void 0!==this.clearCoatRoughness&&(d.clearCoatRoughness=this.clearCoatRoughness),this.map&&this.map.isTexture&&(d.map=this.map.toJSON(a).uuid),this.alphaMap&&this.alphaMap.isTexture&&(d.alphaMap=this.alphaMap.toJSON(a).uuid),this.lightMap&&this.lightMap.isTexture&&(d.lightMap=this.lightMap.toJSON(a).uuid),this.bumpMap&&this.bumpMap.isTexture&&(d.bumpMap=this.bumpMap.toJSON(a).uuid,d.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(d.normalMap=this.normalMap.toJSON(a).uuid,d.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(d.displacementMap=this.displacementMap.toJSON(a).uuid,d.displacementScale=this.displacementScale,d.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(d.roughnessMap=this.roughnessMap.toJSON(a).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(d.metalnessMap=this.metalnessMap.toJSON(a).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(d.emissiveMap=this.emissiveMap.toJSON(a).uuid),this.specularMap&&this.specularMap.isTexture&&(d.specularMap=this.specularMap.toJSON(a).uuid),this.envMap&&this.envMap.isTexture&&(d.envMap=this.envMap.toJSON(a).uuid,d.reflectivity=this.reflectivity),this.gradientMap&&this.gradientMap.isTexture&&(d.gradientMap=this.gradientMap.toJSON(a).uuid),void 0!==this.size&&(d.size=this.size),void 0!==this.sizeAttenuation&&(d.sizeAttenuation=this.sizeAttenuation),this.blending!==Mb&&(d.blending=this.blending),!0===this.flatShading&&(d.flatShading=this.flatShading),this.side!==Gb&&(d.side=this.side),this.vertexColors!==Kb&&(d.vertexColors=this.vertexColors),this.opacity<1&&(d.opacity=this.opacity),!0===this.transparent&&(d.transparent=this.transparent),d.depthFunc=this.depthFunc,d.depthTest=this.depthTest,d.depthWrite=this.depthWrite,0!==this.rotation&&(d.rotation=this.rotation),1!==this.linewidth&&(d.linewidth=this.linewidth),void 0!==this.dashSize&&(d.dashSize=this.dashSize),void 0!==this.gapSize&&(d.gapSize=this.gapSize),void 0!==this.scale&&(d.scale=this.scale),!0===this.dithering&&(d.dithering=!0),this.alphaTest>0&&(d.alphaTest=this.alphaTest),!0===this.premultipliedAlpha&&(d.premultipliedAlpha=this.premultipliedAlpha),!0===this.wireframe&&(d.wireframe=this.wireframe),this.wireframeLinewidth>1&&(d.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(d.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(d.wireframeLinejoin=this.wireframeLinejoin),!0===this.morphTargets&&(d.morphTargets=!0),!0===this.skinning&&(d.skinning=!0),!1===this.visible&&(d.visible=!1),"{}"!==JSON.stringify(this.userData)&&(d.userData=this.userData),c){var e=b(a.textures),f=b(a.images);e.length>0&&(d.textures=e),f.length>0&&(d.images=f)}return d},clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.name=a.name,this.fog=a.fog,this.lights=a.lights,this.blending=a.blending,this.side=a.side,this.flatShading=a.flatShading,this.vertexColors=a.vertexColors,this.opacity=a.opacity,this.transparent=a.transparent,this.blendSrc=a.blendSrc,this.blendDst=a.blendDst,this.blendEquation=a.blendEquation,this.blendSrcAlpha=a.blendSrcAlpha,this.blendDstAlpha=a.blendDstAlpha,this.blendEquationAlpha=a.blendEquationAlpha,this.depthFunc=a.depthFunc,this.depthTest=a.depthTest,this.depthWrite=a.depthWrite,this.colorWrite=a.colorWrite,this.precision=a.precision,this.polygonOffset=a.polygonOffset,this.polygonOffsetFactor=a.polygonOffsetFactor,this.polygonOffsetUnits=a.polygonOffsetUnits,this.dithering=a.dithering,this.alphaTest=a.alphaTest,this.premultipliedAlpha=a.premultipliedAlpha,this.overdraw=a.overdraw,this.visible=a.visible,this.userData=JSON.parse(JSON.stringify(a.userData)),this.clipShadows=a.clipShadows,this.clipIntersection=a.clipIntersection;var b=a.clippingPlanes,c=null;if(null!==b){var d=b.length;c=new Array(d);for(var e=0;e!==d;++e)c[e]=b[e].clone()}return this.clippingPlanes=c,this},dispose:function(){this.dispatchEvent({type:"dispose"})}}),$.prototype=Object.create(Z.prototype),$.prototype.constructor=$,$.prototype.isMeshDepthMaterial=!0,$.prototype.copy=function(a){return Z.prototype.copy.call(this,a),this.depthPacking=a.depthPacking,this.skinning=a.skinning,this.morphTargets=a.morphTargets,this.map=a.map,this.alphaMap=a.alphaMap,this.displacementMap=a.displacementMap,this.displacementScale=a.displacementScale,this.displacementBias=a.displacementBias,this.wireframe=a.wireframe,this.wireframeLinewidth=a.wireframeLinewidth,this},_.prototype=Object.create(Z.prototype),_.prototype.constructor=_,_.prototype.isMeshDistanceMaterial=!0,_.prototype.copy=function(a){return Z.prototype.copy.call(this,a),this.referencePosition.copy(a.referencePosition),this.nearDistance=a.nearDistance,this.farDistance=a.farDistance,this.skinning=a.skinning,this.morphTargets=a.morphTargets,this.map=a.map,this.alphaMap=a.alphaMap,this.displacementMap=a.displacementMap,this.displacementScale=a.displacementScale,this.displacementBias=a.displacementBias,this},Object.assign(aa.prototype,{isBox3:!0,set:function(a,b){return this.min.copy(a),this.max.copy(b),this},setFromArray:function(a){for(var b=1/0,c=1/0,d=1/0,e=-1/0,f=-1/0,g=-1/0,h=0,i=a.length;h<i;h+=3){var j=a[h],k=a[h+1],l=a[h+2];j<b&&(b=j),k<c&&(c=k),l<d&&(d=l),j>e&&(e=j),k>f&&(f=k),l>g&&(g=l)}return this.min.set(b,c,d),this.max.set(e,f,g),this},setFromBufferAttribute:function(a){for(var b=1/0,c=1/0,d=1/0,e=-1/0,f=-1/0,g=-1/0,h=0,i=a.count;h<i;h++){var j=a.getX(h),k=a.getY(h),l=a.getZ(h);j<b&&(b=j),k<c&&(c=k),l<d&&(d=l),j>e&&(e=j),k>f&&(f=k),l>g&&(g=l)}return this.min.set(b,c,d),this.max.set(e,f,g),this},setFromPoints:function(a){this.makeEmpty();for(var b=0,c=a.length;b<c;b++)this.expandByPoint(a[b]);return this},setFromCenterAndSize:function(){var a=new f;return function(b,c){var d=a.copy(c).multiplyScalar(.5);return this.min.copy(b).sub(d),this.max.copy(b).add(d),this}}(),setFromObject:function(a){return this.makeEmpty(),this.expandByObject(a)},clone:function(){return(new this.constructor).copy(this)},copy:function(a){return this.min.copy(a.min),this.max.copy(a.max),this},makeEmpty:function(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this},isEmpty:function(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z},getCenter:function(a){var b=a||new f;return this.isEmpty()?b.set(0,0,0):b.addVectors(this.min,this.max).multiplyScalar(.5)},getSize:function(a){var b=a||new f;return this.isEmpty()?b.set(0,0,0):b.subVectors(this.max,this.min)},expandByPoint:function(a){return this.min.min(a),this.max.max(a),this},expandByVector:function(a){return this.min.sub(a),this.max.add(a),this},expandByScalar:function(a){return this.min.addScalar(-a),this.max.addScalar(a),this},expandByObject:function(){function a(a){var f=a.geometry;if(void 0!==f)if(f.isGeometry){var g=f.vertices;for(c=0,d=g.length;c<d;c++)e.copy(g[c]),e.applyMatrix4(a.matrixWorld),b.expandByPoint(e)}else if(f.isBufferGeometry){var h=f.attributes.position;if(void 0!==h)for(c=0,d=h.count;c<d;c++)e.fromBufferAttribute(h,c).applyMatrix4(a.matrixWorld),b.expandByPoint(e)}}var b,c,d,e=new f;return function(c){return b=this,c.updateMatrixWorld(!0),c.traverse(a),this}}(),containsPoint:function(a){return!(a.x<this.min.x||a.x>this.max.x||a.y<this.min.y||a.y>this.max.y||a.z<this.min.z||a.z>this.max.z)},containsBox:function(a){return this.min.x<=a.min.x&&a.max.x<=this.max.x&&this.min.y<=a.min.y&&a.max.y<=this.max.y&&this.min.z<=a.min.z&&a.max.z<=this.max.z},getParameter:function(a,b){return(b||new f).set((a.x-this.min.x)/(this.max.x-this.min.x),(a.y-this.min.y)/(this.max.y-this.min.y),(a.z-this.min.z)/(this.max.z-this.min.z))},intersectsBox:function(a){return!(a.max.x<this.min.x||a.min.x>this.max.x||a.max.y<this.min.y||a.min.y>this.max.y||a.max.z<this.min.z||a.min.z>this.max.z)},intersectsSphere:function(){var a=new f;return function(b){return this.clampPoint(b.center,a),a.distanceToSquared(b.center)<=b.radius*b.radius}}(),intersectsPlane:function(a){var b,c;return a.normal.x>0?(b=a.normal.x*this.min.x,c=a.normal.x*this.max.x):(b=a.normal.x*this.max.x,c=a.normal.x*this.min.x),a.normal.y>0?(b+=a.normal.y*this.min.y,c+=a.normal.y*this.max.y):(b+=a.normal.y*this.max.y,c+=a.normal.y*this.min.y),a.normal.z>0?(b+=a.normal.z*this.min.z,c+=a.normal.z*this.max.z):(b+=a.normal.z*this.max.z,c+=a.normal.z*this.min.z),b<=a.constant&&c>=a.constant},clampPoint:function(a,b){return(b||new f).copy(a).clamp(this.min,this.max)},distanceToPoint:function(){var a=new f;return function(b){return a.copy(b).clamp(this.min,this.max).sub(b).length()}}(),getBoundingSphere:function(){var a=new f;return function(b){var c=b||new ba;return this.getCenter(c.center),c.radius=.5*this.getSize(a).length(),c}}(),intersect:function(a){return this.min.max(a.min),this.max.min(a.max),this.isEmpty()&&this.makeEmpty(),this},union:function(a){return this.min.min(a.min),this.max.max(a.max),this},applyMatrix4:function(){var a=[new f,new f,new f,new f,new f,new f,new f,new f];return function(b){return this.isEmpty()?this:(a[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(b),a[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(b),a[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(b),a[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(b),a[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(b),a[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(b),a[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(b),a[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(b),this.setFromPoints(a),this)}}(),translate:function(a){return this.min.add(a),this.max.add(a),this},equals:function(a){return a.min.equals(this.min)&&a.max.equals(this.max)}}),Object.assign(ba.prototype,{set:function(a,b){return this.center.copy(a),this.radius=b,this},setFromPoints:function(){var a=new aa;return function(b,c){var d=this.center;void 0!==c?d.copy(c):a.setFromPoints(b).getCenter(d);for(var e=0,f=0,g=b.length;f<g;f++)e=Math.max(e,d.distanceToSquared(b[f]));return this.radius=Math.sqrt(e),this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){return this.center.copy(a.center),this.radius=a.radius,this},empty:function(){return this.radius<=0},containsPoint:function(a){return a.distanceToSquared(this.center)<=this.radius*this.radius},distanceToPoint:function(a){return a.distanceTo(this.center)-this.radius},intersectsSphere:function(a){var b=this.radius+a.radius;return a.center.distanceToSquared(this.center)<=b*b},intersectsBox:function(a){return a.intersectsSphere(this)},intersectsPlane:function(a){return Math.abs(a.distanceToPoint(this.center))<=this.radius},clampPoint:function(a,b){var c=this.center.distanceToSquared(a),d=b||new f;return d.copy(a),c>this.radius*this.radius&&(d.sub(this.center).normalize(),d.multiplyScalar(this.radius).add(this.center)),d},getBoundingBox:function(a){var b=a||new aa;return b.set(this.center,this.center),b.expandByScalar(this.radius),b},applyMatrix4:function(a){return this.center.applyMatrix4(a),this.radius=this.radius*a.getMaxScaleOnAxis(),this},translate:function(a){return this.center.add(a),this},equals:function(a){return a.center.equals(this.center)&&a.radius===this.radius}}),Object.assign(ca.prototype,{set:function(a,b){return this.normal.copy(a),this.constant=b,this},setComponents:function(a,b,c,d){return this.normal.set(a,b,c),this.constant=d,this},setFromNormalAndCoplanarPoint:function(a,b){return this.normal.copy(a),this.constant=-b.dot(this.normal),this},setFromCoplanarPoints:function(){var a=new f,b=new f;return function(c,d,e){var f=a.subVectors(e,d).cross(b.subVectors(c,d)).normalize();return this.setFromNormalAndCoplanarPoint(f,c),this}}(),clone:function(){return(new this.constructor).copy(this)},copy:function(a){return this.normal.copy(a.normal),this.constant=a.constant,this},normalize:function(){var a=1/this.normal.length();return this.normal.multiplyScalar(a),this.constant*=a,this},negate:function(){return this.constant*=-1,this.normal.negate(),this},distanceToPoint:function(a){return this.normal.dot(a)+this.constant},distanceToSphere:function(a){return this.distanceToPoint(a.center)-a.radius},projectPoint:function(a,b){return(b||new f).copy(this.normal).multiplyScalar(-this.distanceToPoint(a)).add(a)},intersectLine:function(){var a=new f;return function(b,c){var d=c||new f,e=b.delta(a),g=this.normal.dot(e);if(0!==g){var h=-(b.start.dot(this.normal)+this.constant)/g;if(!(h<0||h>1))return d.copy(e).multiplyScalar(h).add(b.start)}else if(0===this.distanceToPoint(b.start))return d.copy(b.start)}}(),intersectsLine:function(a){var b=this.distanceToPoint(a.start),c=this.distanceToPoint(a.end);return b<0&&c>0||c<0&&b>0},intersectsBox:function(a){return a.intersectsPlane(this)},intersectsSphere:function(a){return a.intersectsPlane(this)},coplanarPoint:function(a){return(a||new f).copy(this.normal).multiplyScalar(-this.constant)},applyMatrix4:function(){var a=new f,b=new g;return function(c,d){var e=d||b.getNormalMatrix(c),f=this.coplanarPoint(a).applyMatrix4(c),g=this.normal.applyMatrix3(e).normalize();return this.constant=-f.dot(g),this}}(),translate:function(a){return this.constant-=a.dot(this.normal),this},equals:function(a){return a.normal.equals(this.normal)&&a.constant===this.constant}}),Object.assign(da.prototype,{set:function(a,b,c,d,e,f){var g=this.planes;return g[0].copy(a),g[1].copy(b),g[2].copy(c),g[3].copy(d),g[4].copy(e),g[5].copy(f),this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){for(var b=this.planes,c=0;c<6;c++)b[c].copy(a.planes[c]);return this},setFromMatrix:function(a){var b=this.planes,c=a.elements,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],j=c[6],k=c[7],l=c[8],m=c[9],n=c[10],o=c[11],p=c[12],q=c[13],r=c[14],s=c[15];return b[0].setComponents(g-d,k-h,o-l,s-p).normalize(),b[1].setComponents(g+d,k+h,o+l,s+p).normalize(),b[2].setComponents(g+e,k+i,o+m,s+q).normalize(),b[3].setComponents(g-e,k-i,o-m,s-q).normalize(),b[4].setComponents(g-f,k-j,o-n,s-r).normalize(),b[5].setComponents(g+f,k+j,o+n,s+r).normalize(),this},intersectsObject:function(){var a=new ba;return function(b){var c=b.geometry;return null===c.boundingSphere&&c.computeBoundingSphere(),a.copy(c.boundingSphere).applyMatrix4(b.matrixWorld),this.intersectsSphere(a)}}(),intersectsSprite:function(){var a=new ba;return function(b){return a.center.set(0,0,0),a.radius=.7071067811865476,a.applyMatrix4(b.matrixWorld),this.intersectsSphere(a)}}(),intersectsSphere:function(a){for(var b=this.planes,c=a.center,d=-a.radius,e=0;e<6;e++){if(b[e].distanceToPoint(c)<d)return!1}return!0},intersectsBox:function(){var a=new f,b=new f;return function(c){for(var d=this.planes,e=0;e<6;e++){var f=d[e];a.x=f.normal.x>0?c.min.x:c.max.x,b.x=f.normal.x>0?c.max.x:c.min.x,a.y=f.normal.y>0?c.min.y:c.max.y,b.y=f.normal.y>0?c.max.y:c.min.y,a.z=f.normal.z>0?c.min.z:c.max.z,b.z=f.normal.z>0?c.max.z:c.min.z;var g=f.distanceToPoint(a),h=f.distanceToPoint(b);if(g<0&&h<0)return!1}return!0}}(),containsPoint:function(a){for(var b=this.planes,c=0;c<6;c++)if(b[c].distanceToPoint(a)<0)return!1;return!0}}),ga.RotationOrders=["XYZ","YZX","ZXY","XZY","YXZ","ZYX"],ga.DefaultOrder="XYZ",Object.defineProperties(ga.prototype,{x:{get:function(){return this._x},set:function(a){this._x=a,this.onChangeCallback()}},y:{get:function(){return this._y},set:function(a){this._y=a,this.onChangeCallback()}},z:{get:function(){return this._z},set:function(a){this._z=a,this.onChangeCallback()}},order:{get:function(){return this._order},set:function(a){this._order=a,this.onChangeCallback()}}}),Object.assign(ga.prototype,{isEuler:!0,set:function(a,b,c,d){return this._x=a,this._y=b,this._z=c,this._order=d||this._order,this.onChangeCallback(),this},clone:function(){return new this.constructor(this._x,this._y,this._z,this._order)},copy:function(a){return this._x=a._x,this._y=a._y,this._z=a._z,this._order=a._order,this.onChangeCallback(),this},setFromRotationMatrix:function(a,b,c){var d=yd.clamp,e=a.elements,f=e[0],g=e[4],h=e[8],i=e[1],j=e[5],k=e[9],l=e[2],m=e[6],n=e[10];return b=b||this._order,"XYZ"===b?(this._y=Math.asin(d(h,-1,1)),Math.abs(h)<.99999?(this._x=Math.atan2(-k,n),this._z=Math.atan2(-g,f)):(this._x=Math.atan2(m,j),this._z=0)):"YXZ"===b?(this._x=Math.asin(-d(k,-1,1)),Math.abs(k)<.99999?(this._y=Math.atan2(h,n),this._z=Math.atan2(i,j)):(this._y=Math.atan2(-l,f),this._z=0)):"ZXY"===b?(this._x=Math.asin(d(m,-1,1)),Math.abs(m)<.99999?(this._y=Math.atan2(-l,n),this._z=Math.atan2(-g,j)):(this._y=0,this._z=Math.atan2(i,f))):"ZYX"===b?(this._y=Math.asin(-d(l,-1,1)),Math.abs(l)<.99999?(this._x=Math.atan2(m,n),this._z=Math.atan2(i,f)):(this._x=0,this._z=Math.atan2(-g,j))):"YZX"===b?(this._z=Math.asin(d(i,-1,1)),Math.abs(i)<.99999?(this._x=Math.atan2(-k,j),this._y=Math.atan2(-l,f)):(this._x=0,this._y=Math.atan2(h,n))):"XZY"===b?(this._z=Math.asin(-d(g,-1,1)),Math.abs(g)<.99999?(this._x=Math.atan2(m,j),this._y=Math.atan2(h,f)):(this._x=Math.atan2(-k,n),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+b),this._order=b,!1!==c&&this.onChangeCallback(),this},setFromQuaternion:function(){var a=new d;return function(b,c,d){return a.makeRotationFromQuaternion(b),this.setFromRotationMatrix(a,c,d)}}(),setFromVector3:function(a,b){return this.set(a.x,a.y,a.z,b||this._order)},reorder:function(){var a=new e;return function(b){return a.setFromEuler(this),this.setFromQuaternion(a,b)}}(),equals:function(a){return a._x===this._x&&a._y===this._y&&a._z===this._z&&a._order===this._order},fromArray:function(a){return this._x=a[0],this._y=a[1],this._z=a[2],void 0!==a[3]&&(this._order=a[3]),this.onChangeCallback(),this},toArray:function(a,b){return void 0===a&&(a=[]),void 0===b&&(b=0),a[b]=this._x,a[b+1]=this._y,a[b+2]=this._z,a[b+3]=this._order,a},toVector3:function(a){return a?a.set(this._x,this._y,this._z):new f(this._x,this._y,this._z)},onChange:function(a){return this.onChangeCallback=a,this},onChangeCallback:function(){}}),Object.assign(ha.prototype,{set:function(a){this.mask=1<<a|0},enable:function(a){this.mask|=1<<a|0},toggle:function(a){this.mask^=1<<a|0},disable:function(a){this.mask&=~(1<<a|0)},test:function(a){return 0!=(this.mask&a.mask)}});var Pf=0;ia.DefaultUp=new f(0,1,0),ia.DefaultMatrixAutoUpdate=!0,ia.prototype=Object.assign(Object.create(b.prototype),{constructor:ia,isObject3D:!0,onBeforeRender:function(){},onAfterRender:function(){},applyMatrix:function(a){this.matrix.multiplyMatrices(a,this.matrix),this.matrix.decompose(this.position,this.quaternion,this.scale)},applyQuaternion:function(a){return this.quaternion.premultiply(a),this},setRotationFromAxisAngle:function(a,b){this.quaternion.setFromAxisAngle(a,b)},setRotationFromEuler:function(a){this.quaternion.setFromEuler(a,!0)},setRotationFromMatrix:function(a){this.quaternion.setFromRotationMatrix(a)},setRotationFromQuaternion:function(a){this.quaternion.copy(a)},rotateOnAxis:function(){var a=new e;return function(b,c){return a.setFromAxisAngle(b,c),this.quaternion.multiply(a),this}}(),rotateOnWorldAxis:function(){var a=new e;return function(b,c){return a.setFromAxisAngle(b,c),this.quaternion.premultiply(a),this}}(),rotateX:function(){var a=new f(1,0,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateY:function(){var a=new f(0,1,0);return function(b){return this.rotateOnAxis(a,b)}}(),rotateZ:function(){var a=new f(0,0,1);return function(b){return this.rotateOnAxis(a,b)}}(),translateOnAxis:function(){var a=new f;return function(b,c){return a.copy(b).applyQuaternion(this.quaternion),this.position.add(a.multiplyScalar(c)),this}}(),translateX:function(){var a=new f(1,0,0);return function(b){return this.translateOnAxis(a,b)}}(),translateY:function(){var a=new f(0,1,0);return function(b){return this.translateOnAxis(a,b)}}(),translateZ:function(){var a=new f(0,0,1);return function(b){return this.translateOnAxis(a,b)}}(),localToWorld:function(a){return a.applyMatrix4(this.matrixWorld)},worldToLocal:function(){var a=new d;return function(b){return b.applyMatrix4(a.getInverse(this.matrixWorld))}}(),lookAt:function(){var a=new d,b=new f;return function(c,d,e){c.isVector3?b.copy(c):b.set(c,d,e),this.isCamera?a.lookAt(this.position,b,this.up):a.lookAt(b,this.position,this.up),this.quaternion.setFromRotationMatrix(a)}}(),add:function(a){if(arguments.length>1){for(var b=0;b<arguments.length;b++)this.add(arguments[b]);return this}return a===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",a),this):(a&&a.isObject3D?(null!==a.parent&&a.parent.remove(a),a.parent=this,a.dispatchEvent({type:"added"}),this.children.push(a)):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",a),this)},remove:function(a){if(arguments.length>1){for(var b=0;b<arguments.length;b++)this.remove(arguments[b]);return this}var c=this.children.indexOf(a);return-1!==c&&(a.parent=null,a.dispatchEvent({type:"removed"}),this.children.splice(c,1)),this},getObjectById:function(a){return this.getObjectByProperty("id",a)},getObjectByName:function(a){return this.getObjectByProperty("name",a)},getObjectByProperty:function(a,b){if(this[a]===b)return this;for(var c=0,d=this.children.length;c<d;c++){var e=this.children[c],f=e.getObjectByProperty(a,b);if(void 0!==f)return f}},getWorldPosition:function(a){var b=a||new f;return this.updateMatrixWorld(!0),b.setFromMatrixPosition(this.matrixWorld)},getWorldQuaternion:function(){var a=new f,b=new f;return function(c){var d=c||new e;return this.updateMatrixWorld(!0),this.matrixWorld.decompose(a,d,b),d}}(),getWorldRotation:function(){var a=new e;return function(b){var c=b||new ga;return this.getWorldQuaternion(a),c.setFromQuaternion(a,this.rotation.order,!1)}}(),getWorldScale:function(){var a=new f,b=new e;return function(c){var d=c||new f;return this.updateMatrixWorld(!0),this.matrixWorld.decompose(a,b,d),d}}(),getWorldDirection:function(){var a=new e;return function(b){var c=b||new f;return this.getWorldQuaternion(a),c.set(0,0,1).applyQuaternion(a)}}(),raycast:function(){},traverse:function(a){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverse(a)},traverseVisible:function(a){if(!1!==this.visible){a(this);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].traverseVisible(a)}},traverseAncestors:function(a){var b=this.parent;null!==b&&(a(b),b.traverseAncestors(a))},updateMatrix:function(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0},updateMatrixWorld:function(a){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||a)&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix),this.matrixWorldNeedsUpdate=!1,a=!0);for(var b=this.children,c=0,d=b.length;c<d;c++)b[c].updateMatrixWorld(a)},toJSON:function(a){function b(b,c){return void 0===b[c.uuid]&&(b[c.uuid]=c.toJSON(a)),c.uuid}function c(a){var b=[];for(var c in a){var d=a[c];delete d.metadata,b.push(d)}return b}var d=void 0===a||"string"==typeof a,e={};d&&(a={geometries:{},materials:{},textures:{},images:{},shapes:{}},e.metadata={version:4.5,type:"Object",generator:"Object3D.toJSON"});var f={};if(f.uuid=this.uuid,f.type=this.type,""!==this.name&&(f.name=this.name),!0===this.castShadow&&(f.castShadow=!0),!0===this.receiveShadow&&(f.receiveShadow=!0),!1===this.visible&&(f.visible=!1),"{}"!==JSON.stringify(this.userData)&&(f.userData=this.userData),f.matrix=this.matrix.toArray(),void 0!==this.geometry){f.geometry=b(a.geometries,this.geometry);var g=this.geometry.parameters;if(void 0!==g&&void 0!==g.shapes){var h=g.shapes;if(Array.isArray(h))for(var i=0,j=h.length;i<j;i++){var k=h[i];b(a.shapes,k)}else b(a.shapes,h)}}if(void 0!==this.material)if(Array.isArray(this.material)){for(var l=[],i=0,j=this.material.length;i<j;i++)l.push(b(a.materials,this.material[i]));f.material=l}else f.material=b(a.materials,this.material);if(this.children.length>0){f.children=[];for(var i=0;i<this.children.length;i++)f.children.push(this.children[i].toJSON(a).object)}if(d){var m=c(a.geometries),n=c(a.materials),o=c(a.textures),p=c(a.images),h=c(a.shapes);m.length>0&&(e.geometries=m),n.length>0&&(e.materials=n),o.length>0&&(e.textures=o),p.length>0&&(e.images=p),h.length>0&&(e.shapes=h)}return e.object=f,e},clone:function(a){return(new this.constructor).copy(this,a)},copy:function(a,b){if(void 0===b&&(b=!0),this.name=a.name,this.up.copy(a.up),this.position.copy(a.position),this.quaternion.copy(a.quaternion),this.scale.copy(a.scale),this.matrix.copy(a.matrix),this.matrixWorld.copy(a.matrixWorld),this.matrixAutoUpdate=a.matrixAutoUpdate,this.matrixWorldNeedsUpdate=a.matrixWorldNeedsUpdate,this.layers.mask=a.layers.mask,this.visible=a.visible,this.castShadow=a.castShadow,this.receiveShadow=a.receiveShadow,this.frustumCulled=a.frustumCulled,this.renderOrder=a.renderOrder,this.userData=JSON.parse(JSON.stringify(a.userData)),!0===b)for(var c=0;c<a.children.length;c++){var d=a.children[c];this.add(d.clone())}return this}}),ja.prototype=Object.assign(Object.create(ia.prototype),{constructor:ja,isCamera:!0,copy:function(a,b){return ia.prototype.copy.call(this,a,b),this.matrixWorldInverse.copy(a.matrixWorldInverse),this.projectionMatrix.copy(a.projectionMatrix),this},getWorldDirection:function(){var a=new e;return function(b){var c=b||new f;return this.getWorldQuaternion(a),c.set(0,0,-1).applyQuaternion(a)}}(),updateMatrixWorld:function(a){ia.prototype.updateMatrixWorld.call(this,a),this.matrixWorldInverse.getInverse(this.matrixWorld)},clone:function(){return(new this.constructor).copy(this)}}),ka.prototype=Object.assign(Object.create(ja.prototype),{constructor:ka,isOrthographicCamera:!0,copy:function(a,b){return ja.prototype.copy.call(this,a,b),this.left=a.left,this.right=a.right,this.top=a.top,this.bottom=a.bottom,this.near=a.near,this.far=a.far,this.zoom=a.zoom,this.view=null===a.view?null:Object.assign({},a.view),this},setViewOffset:function(a,b,c,d,e,f){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=a,this.view.fullHeight=b,this.view.offsetX=c,this.view.offsetY=d,this.view.width=e,this.view.height=f,this.updateProjectionMatrix()},clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=(this.right-this.left)/(2*this.zoom),b=(this.top-this.bottom)/(2*this.zoom),c=(this.right+this.left)/2,d=(this.top+this.bottom)/2,e=c-a,f=c+a,g=d+b,h=d-b;if(null!==this.view&&this.view.enabled){var i=this.zoom/(this.view.width/this.view.fullWidth),j=this.zoom/(this.view.height/this.view.fullHeight),k=(this.right-this.left)/this.view.width,l=(this.top-this.bottom)/this.view.height;e+=k*(this.view.offsetX/i),f=e+k*(this.view.width/i),g-=l*(this.view.offsetY/j),h=g-l*(this.view.height/j)}this.projectionMatrix.makeOrthographic(e,f,g,h,this.near,this.far)},toJSON:function(a){var b=ia.prototype.toJSON.call(this,a);return b.object.zoom=this.zoom,b.object.left=this.left,b.object.right=this.right,b.object.top=this.top,b.object.bottom=this.bottom,b.object.near=this.near,b.object.far=this.far,null!==this.view&&(b.object.view=Object.assign({},this.view)),b}}),Object.assign(la.prototype,{clone:function(){return(new this.constructor).copy(this)},copy:function(a){this.a=a.a,this.b=a.b,this.c=a.c,this.normal.copy(a.normal),this.color.copy(a.color),this.materialIndex=a.materialIndex;for(var b=0,c=a.vertexNormals.length;b<c;b++)this.vertexNormals[b]=a.vertexNormals[b].clone();for(var b=0,c=a.vertexColors.length;b<c;b++)this.vertexColors[b]=a.vertexColors[b].clone();return this}});var Qf=0;ma.prototype=Object.assign(Object.create(b.prototype),{constructor:ma,isGeometry:!0,applyMatrix:function(a){for(var b=(new g).getNormalMatrix(a),c=0,d=this.vertices.length;c<d;c++){this.vertices[c].applyMatrix4(a)}for(var c=0,d=this.faces.length;c<d;c++){var e=this.faces[c];e.normal.applyMatrix3(b).normalize();for(var f=0,h=e.vertexNormals.length;f<h;f++)e.vertexNormals[f].applyMatrix3(b).normalize()}return null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this.verticesNeedUpdate=!0,this.normalsNeedUpdate=!0,this},rotateX:function(){var a=new d;return function(b){return a.makeRotationX(b),this.applyMatrix(a),this}}(),rotateY:function(){var a=new d;return function(b){return a.makeRotationY(b),this.applyMatrix(a),this}}(),rotateZ:function(){var a=new d;return function(b){return a.makeRotationZ(b),this.applyMatrix(a),this}}(),translate:function(){var a=new d;return function(b,c,d){return a.makeTranslation(b,c,d),this.applyMatrix(a),this}}(),scale:function(){var a=new d;return function(b,c,d){return a.makeScale(b,c,d),this.applyMatrix(a),this}}(),lookAt:function(){var a=new ia;return function(b){a.lookAt(b),a.updateMatrix(),this.applyMatrix(a.matrix)}}(),fromBufferGeometry:function(a){function b(a,b,c,e){var f=void 0!==i?[m[a].clone(),m[b].clone(),m[c].clone()]:[],g=void 0!==j?[d.colors[a].clone(),d.colors[b].clone(),d.colors[c].clone()]:[],h=new la(a,b,c,f,g,e);d.faces.push(h),void 0!==k&&d.faceVertexUvs[0].push([n[a].clone(),n[b].clone(),n[c].clone()]),void 0!==l&&d.faceVertexUvs[1].push([o[a].clone(),o[b].clone(),o[c].clone()])}var d=this,e=null!==a.index?a.index.array:void 0,g=a.attributes,h=g.position.array,i=void 0!==g.normal?g.normal.array:void 0,j=void 0!==g.color?g.color.array:void 0,k=void 0!==g.uv?g.uv.array:void 0,l=void 0!==g.uv2?g.uv2.array:void 0;void 0!==l&&(this.faceVertexUvs[1]=[]);for(var m=[],n=[],o=[],p=0,q=0;p<h.length;p+=3,q+=2)d.vertices.push(new f(h[p],h[p+1],h[p+2])),void 0!==i&&m.push(new f(i[p],i[p+1],i[p+2])),void 0!==j&&d.colors.push(new U(j[p],j[p+1],j[p+2])),void 0!==k&&n.push(new c(k[q],k[q+1])),void 0!==l&&o.push(new c(l[q],l[q+1]));var r=a.groups;if(r.length>0)for(var p=0;p<r.length;p++)for(var s=r[p],t=s.start,u=s.count,q=t,v=t+u;q<v;q+=3)void 0!==e?b(e[q],e[q+1],e[q+2],s.materialIndex):b(q,q+1,q+2,s.materialIndex);else if(void 0!==e)for(var p=0;p<e.length;p+=3)b(e[p],e[p+1],e[p+2]);else for(var p=0;p<h.length/3;p+=3)b(p,p+1,p+2);return this.computeFaceNormals(),null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone()),null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone()),this},center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();return this.translate(a.x,a.y,a.z),a},normalize:function(){this.computeBoundingSphere();var a=this.boundingSphere.center,b=this.boundingSphere.radius,c=0===b?1:1/b,e=new d;return e.set(c,0,0,-c*a.x,0,c,0,-c*a.y,0,0,c,-c*a.z,0,0,0,1),this.applyMatrix(e),this},computeFaceNormals:function(){for(var a=new f,b=new f,c=0,d=this.faces.length;c<d;c++){var e=this.faces[c],g=this.vertices[e.a],h=this.vertices[e.b],i=this.vertices[e.c];a.subVectors(i,h),b.subVectors(g,h),a.cross(b),a.normalize(),e.normal.copy(a)}},computeVertexNormals:function(a){void 0===a&&(a=!0);var b,c,d,e,g,h;for(h=new Array(this.vertices.length),b=0,c=this.vertices.length;b<c;b++)h[b]=new f;if(a){var i,j,k,l=new f,m=new f;for(d=0,e=this.faces.length;d<e;d++)g=this.faces[d],i=this.vertices[g.a],j=this.vertices[g.b],k=this.vertices[g.c],l.subVectors(k,j),m.subVectors(i,j),l.cross(m),h[g.a].add(l),h[g.b].add(l),h[g.c].add(l)}else for(this.computeFaceNormals(),d=0,e=this.faces.length;d<e;d++)g=this.faces[d],h[g.a].add(g.normal),h[g.b].add(g.normal),h[g.c].add(g.normal);for(b=0,c=this.vertices.length;b<c;b++)h[b].normalize();for(d=0,e=this.faces.length;d<e;d++){g=this.faces[d];var n=g.vertexNormals;3===n.length?(n[0].copy(h[g.a]),n[1].copy(h[g.b]),n[2].copy(h[g.c])):(n[0]=h[g.a].clone(),n[1]=h[g.b].clone(),n[2]=h[g.c].clone())}this.faces.length>0&&(this.normalsNeedUpdate=!0)},computeFlatVertexNormals:function(){var a,b,c;for(this.computeFaceNormals(),a=0,b=this.faces.length;a<b;a++){c=this.faces[a];var d=c.vertexNormals;3===d.length?(d[0].copy(c.normal),d[1].copy(c.normal),d[2].copy(c.normal)):(d[0]=c.normal.clone(),d[1]=c.normal.clone(),d[2]=c.normal.clone())}this.faces.length>0&&(this.normalsNeedUpdate=!0)},computeMorphNormals:function(){var a,b,c,d,e;for(c=0,d=this.faces.length;c<d;c++)for(e=this.faces[c],e.__originalFaceNormal?e.__originalFaceNormal.copy(e.normal):e.__originalFaceNormal=e.normal.clone(),e.__originalVertexNormals||(e.__originalVertexNormals=[]),a=0,b=e.vertexNormals.length;a<b;a++)e.__originalVertexNormals[a]?e.__originalVertexNormals[a].copy(e.vertexNormals[a]):e.__originalVertexNormals[a]=e.vertexNormals[a].clone();var g=new ma;for(g.faces=this.faces,a=0,b=this.morphTargets.length;a<b;a++){if(!this.morphNormals[a]){this.morphNormals[a]={},this.morphNormals[a].faceNormals=[],this.morphNormals[a].vertexNormals=[];var h,i,j=this.morphNormals[a].faceNormals,k=this.morphNormals[a].vertexNormals;for(c=0,d=this.faces.length;c<d;c++)h=new f,i={a:new f,b:new f,c:new f},j.push(h),k.push(i)}var l=this.morphNormals[a];g.vertices=this.morphTargets[a].vertices,g.computeFaceNormals(),g.computeVertexNormals();var h,i;for(c=0,d=this.faces.length;c<d;c++)e=this.faces[c],h=l.faceNormals[c],i=l.vertexNormals[c],h.copy(e.normal),i.a.copy(e.vertexNormals[0]),i.b.copy(e.vertexNormals[1]),i.c.copy(e.vertexNormals[2])}for(c=0,d=this.faces.length;c<d;c++)e=this.faces[c],e.normal=e.__originalFaceNormal,e.vertexNormals=e.__originalVertexNormals},computeLineDistances:function(){for(var a=0,b=this.vertices,c=0,d=b.length;c<d;c++)c>0&&(a+=b[c].distanceTo(b[c-1])),this.lineDistances[c]=a},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new aa),this.boundingBox.setFromPoints(this.vertices)},computeBoundingSphere:function(){null===this.boundingSphere&&(this.boundingSphere=new ba),this.boundingSphere.setFromPoints(this.vertices)},merge:function(a,b,c){if(!a||!a.isGeometry)return void console.error("THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.",a);var d,e=this.vertices.length,f=this.vertices,h=a.vertices,i=this.faces,j=a.faces,k=this.faceVertexUvs[0],l=a.faceVertexUvs[0],m=this.colors,n=a.colors;void 0===c&&(c=0),void 0!==b&&(d=(new g).getNormalMatrix(b));for(var o=0,p=h.length;o<p;o++){var q=h[o],r=q.clone();void 0!==b&&r.applyMatrix4(b),f.push(r)}for(var o=0,p=n.length;o<p;o++)m.push(n[o].clone());for(o=0,p=j.length;o<p;o++){var s,t,u,v=j[o],w=v.vertexNormals,x=v.vertexColors;s=new la(v.a+e,v.b+e,v.c+e),s.normal.copy(v.normal),void 0!==d&&s.normal.applyMatrix3(d).normalize();for(var y=0,z=w.length;y<z;y++)t=w[y].clone(),void 0!==d&&t.applyMatrix3(d).normalize(),s.vertexNormals.push(t);s.color.copy(v.color);for(var y=0,z=x.length;y<z;y++)u=x[y],s.vertexColors.push(u.clone());s.materialIndex=v.materialIndex+c,i.push(s)}for(o=0,p=l.length;o<p;o++){var A=l[o],B=[];if(void 0!==A){for(var y=0,z=A.length;y<z;y++)B.push(A[y].clone());k.push(B)}}},mergeMesh:function(a){if(!a||!a.isMesh)return void console.error("THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.",a);a.matrixAutoUpdate&&a.updateMatrix(),this.merge(a.geometry,a.matrix)},mergeVertices:function(){var a,b,c,d,e,f,g,h,i={},j=[],k=[],l=4,m=Math.pow(10,l);for(c=0,d=this.vertices.length;c<d;c++)a=this.vertices[c],b=Math.round(a.x*m)+"_"+Math.round(a.y*m)+"_"+Math.round(a.z*m),void 0===i[b]?(i[b]=c,j.push(this.vertices[c]),k[c]=j.length-1):k[c]=k[i[b]];var n=[];for(c=0,d=this.faces.length;c<d;c++){e=this.faces[c],e.a=k[e.a],e.b=k[e.b],e.c=k[e.c],f=[e.a,e.b,e.c];for(var o=0;o<3;o++)if(f[o]===f[(o+1)%3]){n.push(c);break}}for(c=n.length-1;c>=0;c--){var p=n[c];for(this.faces.splice(p,1),g=0,h=this.faceVertexUvs.length;g<h;g++)this.faceVertexUvs[g].splice(p,1)}var q=this.vertices.length-j.length;return this.vertices=j,q},setFromPoints:function(a){this.vertices=[];for(var b=0,c=a.length;b<c;b++){var d=a[b];this.vertices.push(new f(d.x,d.y,d.z||0))}return this},sortFacesByMaterialIndex:function(){function a(a,b){return a.materialIndex-b.materialIndex}for(var b=this.faces,c=b.length,d=0;d<c;d++)b[d]._id=d;b.sort(a);var e,f,g=this.faceVertexUvs[0],h=this.faceVertexUvs[1];g&&g.length===c&&(e=[]),h&&h.length===c&&(f=[]);for(var d=0;d<c;d++){var i=b[d]._id;e&&e.push(g[i]),f&&f.push(h[i])}e&&(this.faceVertexUvs[0]=e),f&&(this.faceVertexUvs[1]=f)},toJSON:function(){function a(a,b,c){return c?a|1<<b:a&~(1<<b)}function b(a){var b=a.x.toString()+a.y.toString()+a.z.toString();return void 0!==m[b]?m[b]:(m[b]=l.length/3,l.push(a.x,a.y,a.z),m[b])}function c(a){var b=a.r.toString()+a.g.toString()+a.b.toString();return void 0!==o[b]?o[b]:(o[b]=n.length,n.push(a.getHex()),o[b])}function d(a){var b=a.x.toString()+a.y.toString();return void 0!==q[b]?q[b]:(q[b]=p.length/2,p.push(a.x,a.y),q[b])}var e={metadata:{version:4.5,type:"Geometry",generator:"Geometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,""!==this.name&&(e.name=this.name),void 0!==this.parameters){var f=this.parameters;for(var g in f)void 0!==f[g]&&(e[g]=f[g]);return e}for(var h=[],i=0;i<this.vertices.length;i++){var j=this.vertices[i];h.push(j.x,j.y,j.z)}for(var k=[],l=[],m={},n=[],o={},p=[],q={},i=0;i<this.faces.length;i++){var r=this.faces[i],s=void 0!==this.faceVertexUvs[0][i],t=r.normal.length()>0,u=r.vertexNormals.length>0,v=1!==r.color.r||1!==r.color.g||1!==r.color.b,w=r.vertexColors.length>0,x=0;if(x=a(x,0,0),x=a(x,1,!0),x=a(x,2,!1),x=a(x,3,s),x=a(x,4,t),x=a(x,5,u),x=a(x,6,v),x=a(x,7,w),k.push(x),k.push(r.a,r.b,r.c),k.push(r.materialIndex),s){var y=this.faceVertexUvs[0][i];k.push(d(y[0]),d(y[1]),d(y[2]))}if(t&&k.push(b(r.normal)),u){var z=r.vertexNormals;k.push(b(z[0]),b(z[1]),b(z[2]))}if(v&&k.push(c(r.color)),w){var A=r.vertexColors;k.push(c(A[0]),c(A[1]),c(A[2]))}}return e.data={},e.data.vertices=h,e.data.normals=l,n.length>0&&(e.data.colors=n),p.length>0&&(e.data.uvs=[p]),e.data.faces=k,e},clone:function(){return(new ma).copy(this)},copy:function(a){var b,c,d,e,f,g;this.vertices=[],this.colors=[],this.faces=[],this.faceVertexUvs=[[]],this.morphTargets=[],this.morphNormals=[],this.skinWeights=[],this.skinIndices=[],this.lineDistances=[],this.boundingBox=null,this.boundingSphere=null,this.name=a.name;var h=a.vertices;for(b=0,c=h.length;b<c;b++)this.vertices.push(h[b].clone());var i=a.colors;for(b=0,c=i.length;b<c;b++)this.colors.push(i[b].clone());var j=a.faces;for(b=0,c=j.length;b<c;b++)this.faces.push(j[b].clone());for(b=0,c=a.faceVertexUvs.length;b<c;b++){var k=a.faceVertexUvs[b];for(void 0===this.faceVertexUvs[b]&&(this.faceVertexUvs[b]=[]),d=0,e=k.length;d<e;d++){var l=k[d],m=[];for(f=0,g=l.length;f<g;f++){var n=l[f];m.push(n.clone())}this.faceVertexUvs[b].push(m)}}var o=a.morphTargets;for(b=0,c=o.length;b<c;b++){var p={};if(p.name=o[b].name,void 0!==o[b].vertices)for(p.vertices=[],d=0,e=o[b].vertices.length;d<e;d++)p.vertices.push(o[b].vertices[d].clone());if(void 0!==o[b].normals)for(p.normals=[],d=0,e=o[b].normals.length;d<e;d++)p.normals.push(o[b].normals[d].clone());this.morphTargets.push(p)}var q=a.morphNormals;for(b=0,c=q.length;b<c;b++){var r={};if(void 0!==q[b].vertexNormals)for(r.vertexNormals=[],d=0,e=q[b].vertexNormals.length;d<e;d++){var s=q[b].vertexNormals[d],t={};t.a=s.a.clone(),t.b=s.b.clone(),t.c=s.c.clone(),r.vertexNormals.push(t)}if(void 0!==q[b].faceNormals)for(r.faceNormals=[],d=0,e=q[b].faceNormals.length;d<e;d++)r.faceNormals.push(q[b].faceNormals[d].clone());this.morphNormals.push(r)}var u=a.skinWeights;for(b=0,c=u.length;b<c;b++)this.skinWeights.push(u[b].clone());var v=a.skinIndices;for(b=0,c=v.length;b<c;b++)this.skinIndices.push(v[b].clone());var w=a.lineDistances;for(b=0,c=w.length;b<c;b++)this.lineDistances.push(w[b]);var x=a.boundingBox;null!==x&&(this.boundingBox=x.clone());var y=a.boundingSphere;return null!==y&&(this.boundingSphere=y.clone()),this.elementsNeedUpdate=a.elementsNeedUpdate,this.verticesNeedUpdate=a.verticesNeedUpdate,this.uvsNeedUpdate=a.uvsNeedUpdate,this.normalsNeedUpdate=a.normalsNeedUpdate,this.colorsNeedUpdate=a.colorsNeedUpdate,this.lineDistancesNeedUpdate=a.lineDistancesNeedUpdate,this.groupsNeedUpdate=a.groupsNeedUpdate,this},dispose:function(){this.dispatchEvent({type:"dispose"})}}),Object.defineProperty(na.prototype,"needsUpdate",{set:function(a){!0===a&&this.version++}}),Object.assign(na.prototype,{isBufferAttribute:!0,setArray:function(a){if(Array.isArray(a))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.count=void 0!==a?a.length/this.itemSize:0,this.array=a},setDynamic:function(a){return this.dynamic=a,this},copy:function(a){return this.array=new a.array.constructor(a.array),this.itemSize=a.itemSize,this.count=a.count,this.normalized=a.normalized,this.dynamic=a.dynamic,this},copyAt:function(a,b,c){a*=this.itemSize,c*=b.itemSize;for(var d=0,e=this.itemSize;d<e;d++)this.array[a+d]=b.array[c+d];return this},copyArray:function(a){return this.array.set(a),this},copyColorsArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyColorsArray(): color is undefined",d),f=new U),b[c++]=f.r,b[c++]=f.g,b[c++]=f.b}return this},copyIndicesArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];b[c++]=f.a,b[c++]=f.b,b[c++]=f.c}return this},copyVector2sArray:function(a){for(var b=this.array,d=0,e=0,f=a.length;e<f;e++){var g=a[e];void 0===g&&(console.warn("THREE.BufferAttribute.copyVector2sArray(): vector is undefined",e),g=new c),b[d++]=g.x,b[d++]=g.y}return this},copyVector3sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var g=a[d];void 0===g&&(console.warn("THREE.BufferAttribute.copyVector3sArray(): vector is undefined",d),g=new f),b[c++]=g.x,b[c++]=g.y,b[c++]=g.z}return this},copyVector4sArray:function(a){for(var b=this.array,c=0,d=0,e=a.length;d<e;d++){var f=a[d];void 0===f&&(console.warn("THREE.BufferAttribute.copyVector4sArray(): vector is undefined",d),f=new i),b[c++]=f.x,b[c++]=f.y,b[c++]=f.z,b[c++]=f.w}return this},set:function(a,b){return void 0===b&&(b=0),this.array.set(a,b),this},getX:function(a){return this.array[a*this.itemSize]},setX:function(a,b){return this.array[a*this.itemSize]=b,this},getY:function(a){return this.array[a*this.itemSize+1]},setY:function(a,b){return this.array[a*this.itemSize+1]=b,this},getZ:function(a){return this.array[a*this.itemSize+2]},setZ:function(a,b){return this.array[a*this.itemSize+2]=b,this},getW:function(a){return this.array[a*this.itemSize+3]},setW:function(a,b){return this.array[a*this.itemSize+3]=b,this},setXY:function(a,b,c){return a*=this.itemSize,this.array[a+0]=b,this.array[a+1]=c,this},setXYZ:function(a,b,c,d){return a*=this.itemSize,this.array[a+0]=b,this.array[a+1]=c,this.array[a+2]=d,this},setXYZW:function(a,b,c,d,e){return a*=this.itemSize,this.array[a+0]=b,this.array[a+1]=c,this.array[a+2]=d,this.array[a+3]=e,this},onUpload:function(a){return this.onUploadCallback=a,this},clone:function(){return new this.constructor(this.array,this.itemSize).copy(this)}}),oa.prototype=Object.create(na.prototype),oa.prototype.constructor=oa,pa.prototype=Object.create(na.prototype),pa.prototype.constructor=pa,qa.prototype=Object.create(na.prototype),qa.prototype.constructor=qa,ra.prototype=Object.create(na.prototype),ra.prototype.constructor=ra,sa.prototype=Object.create(na.prototype),sa.prototype.constructor=sa,ta.prototype=Object.create(na.prototype),ta.prototype.constructor=ta,ua.prototype=Object.create(na.prototype),ua.prototype.constructor=ua,va.prototype=Object.create(na.prototype),va.prototype.constructor=va,wa.prototype=Object.create(na.prototype),wa.prototype.constructor=wa,Object.assign(xa.prototype,{computeGroups:function(a){for(var b,c=[],d=void 0,e=a.faces,f=0;f<e.length;f++){var g=e[f];g.materialIndex!==d&&(d=g.materialIndex,void 0!==b&&(b.count=3*f-b.start,c.push(b)),b={start:3*f,materialIndex:d})}void 0!==b&&(b.count=3*f-b.start,c.push(b)),this.groups=c},fromGeometry:function(a){var b,d=a.faces,e=a.vertices,f=a.faceVertexUvs,g=f[0]&&f[0].length>0,h=f[1]&&f[1].length>0,i=a.morphTargets,j=i.length;if(j>0){b=[];for(var k=0;k<j;k++)b[k]=[];this.morphTargets.position=b}var l,m=a.morphNormals,n=m.length;if(n>0){l=[];for(var k=0;k<n;k++)l[k]=[];this.morphTargets.normal=l}for(var o=a.skinIndices,p=a.skinWeights,q=o.length===e.length,r=p.length===e.length,k=0;k<d.length;k++){var s=d[k];this.vertices.push(e[s.a],e[s.b],e[s.c]);var t=s.vertexNormals;if(3===t.length)this.normals.push(t[0],t[1],t[2]);else{var u=s.normal;this.normals.push(u,u,u)}var v=s.vertexColors;if(3===v.length)this.colors.push(v[0],v[1],v[2]);else{var w=s.color;this.colors.push(w,w,w)}if(!0===g){var x=f[0][k];void 0!==x?this.uvs.push(x[0],x[1],x[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ",k),this.uvs.push(new c,new c,new c))}if(!0===h){var x=f[1][k];void 0!==x?this.uvs2.push(x[0],x[1],x[2]):(console.warn("THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ",k),this.uvs2.push(new c,new c,new c))}for(var y=0;y<j;y++){var z=i[y].vertices;b[y].push(z[s.a],z[s.b],z[s.c])}for(var y=0;y<n;y++){var A=m[y].vertexNormals[k];l[y].push(A.a,A.b,A.c)}q&&this.skinIndices.push(o[s.a],o[s.b],o[s.c]),r&&this.skinWeights.push(p[s.a],p[s.b],p[s.c])}return this.computeGroups(a),this.verticesNeedUpdate=a.verticesNeedUpdate,this.normalsNeedUpdate=a.normalsNeedUpdate,this.colorsNeedUpdate=a.colorsNeedUpdate,this.uvsNeedUpdate=a.uvsNeedUpdate,this.groupsNeedUpdate=a.groupsNeedUpdate,this}});var Rf=1;za.prototype=Object.assign(Object.create(b.prototype),{constructor:za,isBufferGeometry:!0,getIndex:function(){return this.index},setIndex:function(a){Array.isArray(a)?this.index=new(ya(a)>65535?ua:sa)(a,1):this.index=a},addAttribute:function(a,b){return b&&b.isBufferAttribute||b&&b.isInterleavedBufferAttribute?"index"===a?(console.warn("THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute."),void this.setIndex(b)):(this.attributes[a]=b,this):(console.warn("THREE.BufferGeometry: .addAttribute() now expects ( name, attribute )."),void this.addAttribute(a,new na(arguments[1],arguments[2])))},getAttribute:function(a){return this.attributes[a]},removeAttribute:function(a){return delete this.attributes[a],this},addGroup:function(a,b,c){this.groups.push({start:a,count:b,materialIndex:void 0!==c?c:0})},clearGroups:function(){this.groups=[]},setDrawRange:function(a,b){this.drawRange.start=a,this.drawRange.count=b},applyMatrix:function(a){var b=this.attributes.position;void 0!==b&&(a.applyToBufferAttribute(b),b.needsUpdate=!0);var c=this.attributes.normal;if(void 0!==c){(new g).getNormalMatrix(a).applyToBufferAttribute(c),c.needsUpdate=!0}return null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this},rotateX:function(){var a=new d;return function(b){return a.makeRotationX(b),this.applyMatrix(a),this}}(),rotateY:function(){var a=new d;return function(b){return a.makeRotationY(b),this.applyMatrix(a),this}}(),rotateZ:function(){var a=new d;return function(b){return a.makeRotationZ(b),this.applyMatrix(a),this}}(),translate:function(){var a=new d;return function(b,c,d){return a.makeTranslation(b,c,d),this.applyMatrix(a),this}}(),scale:function(){var a=new d;return function(b,c,d){return a.makeScale(b,c,d),this.applyMatrix(a),this}}(),lookAt:function(){var a=new ia;return function(b){a.lookAt(b),a.updateMatrix(),this.applyMatrix(a.matrix)}}(),center:function(){this.computeBoundingBox();var a=this.boundingBox.getCenter().negate();return this.translate(a.x,a.y,a.z),a},setFromObject:function(a){var b=a.geometry;if(a.isPoints||a.isLine){var c=new va(3*b.vertices.length,3),d=new va(3*b.colors.length,3);if(this.addAttribute("position",c.copyVector3sArray(b.vertices)),this.addAttribute("color",d.copyColorsArray(b.colors)),b.lineDistances&&b.lineDistances.length===b.vertices.length){var e=new va(b.lineDistances.length,1);this.addAttribute("lineDistance",e.copyArray(b.lineDistances))}null!==b.boundingSphere&&(this.boundingSphere=b.boundingSphere.clone()),null!==b.boundingBox&&(this.boundingBox=b.boundingBox.clone())}else a.isMesh&&b&&b.isGeometry&&this.fromGeometry(b);return this},setFromPoints:function(a){for(var b=[],c=0,d=a.length;c<d;c++){var e=a[c];b.push(e.x,e.y,e.z||0)}return this.addAttribute("position",new va(b,3)),this},updateFromObject:function(a){var b=a.geometry;if(a.isMesh){var c=b.__directGeometry;if(!0===b.elementsNeedUpdate&&(c=void 0,b.elementsNeedUpdate=!1),void 0===c)return this.fromGeometry(b);c.verticesNeedUpdate=b.verticesNeedUpdate,c.normalsNeedUpdate=b.normalsNeedUpdate,c.colorsNeedUpdate=b.colorsNeedUpdate,c.uvsNeedUpdate=b.uvsNeedUpdate,c.groupsNeedUpdate=b.groupsNeedUpdate,b.verticesNeedUpdate=!1,b.normalsNeedUpdate=!1,b.colorsNeedUpdate=!1,b.uvsNeedUpdate=!1,b.groupsNeedUpdate=!1,b=c}var d;return!0===b.verticesNeedUpdate&&(d=this.attributes.position,void 0!==d&&(d.copyVector3sArray(b.vertices),d.needsUpdate=!0),b.verticesNeedUpdate=!1),!0===b.normalsNeedUpdate&&(d=this.attributes.normal,void 0!==d&&(d.copyVector3sArray(b.normals),d.needsUpdate=!0),b.normalsNeedUpdate=!1),!0===b.colorsNeedUpdate&&(d=this.attributes.color,void 0!==d&&(d.copyColorsArray(b.colors),d.needsUpdate=!0),b.colorsNeedUpdate=!1),b.uvsNeedUpdate&&(d=this.attributes.uv,void 0!==d&&(d.copyVector2sArray(b.uvs),d.needsUpdate=!0),b.uvsNeedUpdate=!1),b.lineDistancesNeedUpdate&&(d=this.attributes.lineDistance,void 0!==d&&(d.copyArray(b.lineDistances),d.needsUpdate=!0),b.lineDistancesNeedUpdate=!1),b.groupsNeedUpdate&&(b.computeGroups(a.geometry),this.groups=b.groups,b.groupsNeedUpdate=!1),this},fromGeometry:function(a){return a.__directGeometry=(new xa).fromGeometry(a),this.fromDirectGeometry(a.__directGeometry)},fromDirectGeometry:function(a){var b=new Float32Array(3*a.vertices.length);if(this.addAttribute("position",new na(b,3).copyVector3sArray(a.vertices)),a.normals.length>0){var c=new Float32Array(3*a.normals.length);this.addAttribute("normal",new na(c,3).copyVector3sArray(a.normals))}if(a.colors.length>0){var d=new Float32Array(3*a.colors.length);this.addAttribute("color",new na(d,3).copyColorsArray(a.colors))}if(a.uvs.length>0){var e=new Float32Array(2*a.uvs.length);this.addAttribute("uv",new na(e,2).copyVector2sArray(a.uvs))}if(a.uvs2.length>0){var f=new Float32Array(2*a.uvs2.length);this.addAttribute("uv2",new na(f,2).copyVector2sArray(a.uvs2))}if(a.indices.length>0){var g=ya(a.indices)>65535?Uint32Array:Uint16Array,h=new g(3*a.indices.length);this.setIndex(new na(h,1).copyIndicesArray(a.indices))}this.groups=a.groups;for(var i in a.morphTargets){for(var j=[],k=a.morphTargets[i],l=0,m=k.length;l<m;l++){var n=k[l],o=new va(3*n.length,3);j.push(o.copyVector3sArray(n))}this.morphAttributes[i]=j}if(a.skinIndices.length>0){var p=new va(4*a.skinIndices.length,4);this.addAttribute("skinIndex",p.copyVector4sArray(a.skinIndices))}if(a.skinWeights.length>0){var q=new va(4*a.skinWeights.length,4);this.addAttribute("skinWeight",q.copyVector4sArray(a.skinWeights))}return null!==a.boundingSphere&&(this.boundingSphere=a.boundingSphere.clone()),null!==a.boundingBox&&(this.boundingBox=a.boundingBox.clone()),this},computeBoundingBox:function(){null===this.boundingBox&&(this.boundingBox=new aa);var a=this.attributes.position;void 0!==a?this.boundingBox.setFromBufferAttribute(a):this.boundingBox.makeEmpty(),(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)},computeBoundingSphere:function(){var a=new aa,b=new f;return function(){null===this.boundingSphere&&(this.boundingSphere=new ba);var c=this.attributes.position;if(c){var d=this.boundingSphere.center;a.setFromBufferAttribute(c),a.getCenter(d);for(var e=0,f=0,g=c.count;f<g;f++)b.x=c.getX(f),b.y=c.getY(f),b.z=c.getZ(f),e=Math.max(e,d.distanceToSquared(b));this.boundingSphere.radius=Math.sqrt(e),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}}(),computeFaceNormals:function(){},computeVertexNormals:function(){var a=this.index,b=this.attributes,c=this.groups;if(b.position){var d=b.position.array;if(void 0===b.normal)this.addAttribute("normal",new na(new Float32Array(d.length),3));else for(var e=b.normal.array,g=0,h=e.length;g<h;g++)e[g]=0;var i,j,k,l=b.normal.array,m=new f,n=new f,o=new f,p=new f,q=new f;if(a){var r=a.array;0===c.length&&this.addGroup(0,r.length);for(var s=0,t=c.length;s<t;++s)for(var u=c[s],v=u.start,w=u.count,g=v,h=v+w;g<h;g+=3)i=3*r[g+0],j=3*r[g+1],k=3*r[g+2],m.fromArray(d,i),n.fromArray(d,j),o.fromArray(d,k),p.subVectors(o,n),q.subVectors(m,n),p.cross(q),l[i]+=p.x,l[i+1]+=p.y,l[i+2]+=p.z,l[j]+=p.x,l[j+1]+=p.y,l[j+2]+=p.z,l[k]+=p.x,l[k+1]+=p.y,l[k+2]+=p.z}else for(var g=0,h=d.length;g<h;g+=9)m.fromArray(d,g),n.fromArray(d,g+3),o.fromArray(d,g+6),p.subVectors(o,n),q.subVectors(m,n),p.cross(q),l[g]=p.x,l[g+1]=p.y,l[g+2]=p.z,l[g+3]=p.x,l[g+4]=p.y,l[g+5]=p.z,l[g+6]=p.x,l[g+7]=p.y,l[g+8]=p.z;this.normalizeNormals(),b.normal.needsUpdate=!0}},merge:function(a,b){if(!a||!a.isBufferGeometry)return void console.error("THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.",a);void 0===b&&(b=0);var c=this.attributes;for(var d in c)if(void 0!==a.attributes[d])for(var e=c[d],f=e.array,g=a.attributes[d],h=g.array,i=g.itemSize,j=0,k=i*b;j<h.length;j++,k++)f[k]=h[j];return this},normalizeNormals:function(){var a=new f;return function(){for(var b=this.attributes.normal,c=0,d=b.count;c<d;c++)a.x=b.getX(c),a.y=b.getY(c),a.z=b.getZ(c),a.normalize(),b.setXYZ(c,a.x,a.y,a.z)}}(),toNonIndexed:function(){if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed."),this;var a=new za,b=this.index.array,c=this.attributes;for(var d in c){for(var e=c[d],f=e.array,g=e.itemSize,h=new f.constructor(b.length*g),i=0,j=0,k=0,l=b.length;k<l;k++){i=b[k]*g;for(var m=0;m<g;m++)h[j++]=f[i++]}a.addAttribute(d,new na(h,g))}return a},toJSON:function(){var a={metadata:{version:4.5,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(a.uuid=this.uuid,a.type=this.type,""!==this.name&&(a.name=this.name),void 0!==this.parameters){var b=this.parameters;for(var c in b)void 0!==b[c]&&(a[c]=b[c]);return a}a.data={attributes:{}};var d=this.index;if(null!==d){var e=Array.prototype.slice.call(d.array);a.data.index={type:d.array.constructor.name,array:e}}var f=this.attributes;for(var c in f){var g=f[c],e=Array.prototype.slice.call(g.array);a.data.attributes[c]={itemSize:g.itemSize,type:g.array.constructor.name,array:e,normalized:g.normalized}}var h=this.groups;h.length>0&&(a.data.groups=JSON.parse(JSON.stringify(h)));var i=this.boundingSphere;return null!==i&&(a.data.boundingSphere={center:i.center.toArray(),radius:i.radius}),a},clone:function(){return(new za).copy(this)},copy:function(a){var b,c,d;this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.name=a.name;var e=a.index;null!==e&&this.setIndex(e.clone());var f=a.attributes;for(b in f){var g=f[b];this.addAttribute(b,g.clone())}var h=a.morphAttributes;for(b in h){var i=[],j=h[b];for(c=0,d=j.length;c<d;c++)i.push(j[c].clone());this.morphAttributes[b]=i}var k=a.groups;for(c=0,d=k.length;c<d;c++){var l=k[c];this.addGroup(l.start,l.count,l.materialIndex)}var m=a.boundingBox;null!==m&&(this.boundingBox=m.clone());var n=a.boundingSphere;return null!==n&&(this.boundingSphere=n.clone()),this.drawRange.start=a.drawRange.start,this.drawRange.count=a.drawRange.count,this},dispose:function(){this.dispatchEvent({type:"dispose"})}}),Aa.prototype=Object.create(ma.prototype),Aa.prototype.constructor=Aa,Ba.prototype=Object.create(za.prototype),Ba.prototype.constructor=Ba,Ca.prototype=Object.create(ma.prototype),Ca.prototype.constructor=Ca,Da.prototype=Object.create(za.prototype),Da.prototype.constructor=Da,Ea.prototype=Object.create(Z.prototype),Ea.prototype.constructor=Ea,Ea.prototype.isMeshBasicMaterial=!0,Ea.prototype.copy=function(a){return Z.prototype.copy.call(this,a),this.color.copy(a.color),this.map=a.map,this.lightMap=a.lightMap,this.lightMapIntensity=a.lightMapIntensity,this.aoMap=a.aoMap,this.aoMapIntensity=a.aoMapIntensity,this.specularMap=a.specularMap,this.alphaMap=a.alphaMap,this.envMap=a.envMap,this.combine=a.combine,this.reflectivity=a.reflectivity,this.refractionRatio=a.refractionRatio,this.wireframe=a.wireframe,this.wireframeLinewidth=a.wireframeLinewidth,this.wireframeLinecap=a.wireframeLinecap,this.wireframeLinejoin=a.wireframeLinejoin,this.skinning=a.skinning,this.morphTargets=a.morphTargets,this},Fa.prototype=Object.create(Z.prototype),Fa.prototype.constructor=Fa,Fa.prototype.isShaderMaterial=!0,Fa.prototype.copy=function(a){return Z.prototype.copy.call(this,a),this.fragmentShader=a.fragmentShader,this.vertexShader=a.vertexShader,this.uniforms=Jd.clone(a.uniforms),this.defines=a.defines,this.wireframe=a.wireframe,this.wireframeLinewidth=a.wireframeLinewidth,this.lights=a.lights,this.clipping=a.clipping,this.skinning=a.skinning,this.morphTargets=a.morphTargets,this.morphNormals=a.morphNormals,this.extensions=a.extensions,this},Fa.prototype.toJSON=function(a){var b=Z.prototype.toJSON.call(this,a);return b.uniforms=this.uniforms,b.vertexShader=this.vertexShader,b.fragmentShader=this.fragmentShader,b},Object.assign(Ga.prototype,{set:function(a,b){return this.origin.copy(a),this.direction.copy(b),this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){return this.origin.copy(a.origin),this.direction.copy(a.direction),this},at:function(a,b){return(b||new f).copy(this.direction).multiplyScalar(a).add(this.origin)},lookAt:function(a){return this.direction.copy(a).sub(this.origin).normalize(),this},recast:function(){var a=new f;return function(b){return this.origin.copy(this.at(b,a)),this}}(),closestPointToPoint:function(a,b){var c=b||new f;c.subVectors(a,this.origin);var d=c.dot(this.direction);return d<0?c.copy(this.origin):c.copy(this.direction).multiplyScalar(d).add(this.origin)},distanceToPoint:function(a){return Math.sqrt(this.distanceSqToPoint(a))},distanceSqToPoint:function(){var a=new f;return function(b){var c=a.subVectors(b,this.origin).dot(this.direction);return c<0?this.origin.distanceToSquared(b):(a.copy(this.direction).multiplyScalar(c).add(this.origin),a.distanceToSquared(b))}}(),distanceSqToSegment:function(){var a=new f,b=new f,c=new f;return function(d,e,f,g){a.copy(d).add(e).multiplyScalar(.5),b.copy(e).sub(d).normalize(),c.copy(this.origin).sub(a);var h,i,j,k,l=.5*d.distanceTo(e),m=-this.direction.dot(b),n=c.dot(this.direction),o=-c.dot(b),p=c.lengthSq(),q=Math.abs(1-m*m);if(q>0)if(h=m*o-n,i=m*n-o,k=l*q,h>=0)if(i>=-k)if(i<=k){var r=1/q;h*=r,i*=r,j=h*(h+m*i+2*n)+i*(m*h+i+2*o)+p}else i=l,h=Math.max(0,-(m*i+n)),j=-h*h+i*(i+2*o)+p;else i=-l,h=Math.max(0,-(m*i+n)),j=-h*h+i*(i+2*o)+p;else i<=-k?(h=Math.max(0,-(-m*l+n)),i=h>0?-l:Math.min(Math.max(-l,-o),l),j=-h*h+i*(i+2*o)+p):i<=k?(h=0,i=Math.min(Math.max(-l,-o),l),j=i*(i+2*o)+p):(h=Math.max(0,-(m*l+n)),i=h>0?l:Math.min(Math.max(-l,-o),l),j=-h*h+i*(i+2*o)+p);else i=m>0?-l:l,h=Math.max(0,-(m*i+n)),j=-h*h+i*(i+2*o)+p;return f&&f.copy(this.direction).multiplyScalar(h).add(this.origin),g&&g.copy(b).multiplyScalar(i).add(a),j}}(),intersectSphere:function(){var a=new f;return function(b,c){a.subVectors(b.center,this.origin);var d=a.dot(this.direction),e=a.dot(a)-d*d,f=b.radius*b.radius;if(e>f)return null;var g=Math.sqrt(f-e),h=d-g,i=d+g;return h<0&&i<0?null:h<0?this.at(i,c):this.at(h,c)}}(),intersectsSphere:function(a){return this.distanceToPoint(a.center)<=a.radius},distanceToPlane:function(a){var b=a.normal.dot(this.direction);if(0===b)return 0===a.distanceToPoint(this.origin)?0:null;var c=-(this.origin.dot(a.normal)+a.constant)/b;return c>=0?c:null},intersectPlane:function(a,b){var c=this.distanceToPlane(a);return null===c?null:this.at(c,b)},intersectsPlane:function(a){var b=a.distanceToPoint(this.origin);return 0===b||a.normal.dot(this.direction)*b<0},intersectBox:function(a,b){var c,d,e,f,g,h,i=1/this.direction.x,j=1/this.direction.y,k=1/this.direction.z,l=this.origin;return i>=0?(c=(a.min.x-l.x)*i,d=(a.max.x-l.x)*i):(c=(a.max.x-l.x)*i,d=(a.min.x-l.x)*i),j>=0?(e=(a.min.y-l.y)*j,f=(a.max.y-l.y)*j):(e=(a.max.y-l.y)*j,f=(a.min.y-l.y)*j),c>f||e>d?null:((e>c||c!==c)&&(c=e),(f<d||d!==d)&&(d=f),k>=0?(g=(a.min.z-l.z)*k,h=(a.max.z-l.z)*k):(g=(a.max.z-l.z)*k,h=(a.min.z-l.z)*k),c>h||g>d?null:((g>c||c!==c)&&(c=g),(h<d||d!==d)&&(d=h),d<0?null:this.at(c>=0?c:d,b)))},intersectsBox:function(){var a=new f;return function(b){return null!==this.intersectBox(b,a)}}(),intersectTriangle:function(){var a=new f,b=new f,c=new f,d=new f;return function(e,f,g,h,i){b.subVectors(f,e),c.subVectors(g,e),d.crossVectors(b,c);var j,k=this.direction.dot(d);if(k>0){if(h)return null;j=1}else{if(!(k<0))return null;j=-1,k=-k}a.subVectors(this.origin,e);var l=j*this.direction.dot(c.crossVectors(a,c));if(l<0)return null;var m=j*this.direction.dot(b.cross(a));if(m<0)return null;if(l+m>k)return null;var n=-j*a.dot(d);return n<0?null:this.at(n/k,i)}}(),applyMatrix4:function(a){return this.origin.applyMatrix4(a),this.direction.transformDirection(a),this},equals:function(a){return a.origin.equals(this.origin)&&a.direction.equals(this.direction)}}),Object.assign(Ha.prototype,{set:function(a,b){return this.start.copy(a),this.end.copy(b),this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){return this.start.copy(a.start),this.end.copy(a.end),this},getCenter:function(a){return(a||new f).addVectors(this.start,this.end).multiplyScalar(.5)},delta:function(a){return(a||new f).subVectors(this.end,this.start)},distanceSq:function(){return this.start.distanceToSquared(this.end)},distance:function(){return this.start.distanceTo(this.end)},at:function(a,b){var c=b||new f;return this.delta(c).multiplyScalar(a).add(this.start)},closestPointToPointParameter:function(){var a=new f,b=new f;return function(c,d){a.subVectors(c,this.start),b.subVectors(this.end,this.start);var e=b.dot(b),f=b.dot(a),g=f/e;return d&&(g=yd.clamp(g,0,1)),g}}(),closestPointToPoint:function(a,b,c){var d=this.closestPointToPointParameter(a,b),e=c||new f;return this.delta(e).multiplyScalar(d).add(this.start)},applyMatrix4:function(a){return this.start.applyMatrix4(a),this.end.applyMatrix4(a),this},equals:function(a){return a.start.equals(this.start)&&a.end.equals(this.end)}}),Object.assign(Ia,{normal:function(){var a=new f;return function(b,c,d,e){var g=e||new f;g.subVectors(d,c),a.subVectors(b,c),g.cross(a);var h=g.lengthSq();return h>0?g.multiplyScalar(1/Math.sqrt(h)):g.set(0,0,0)}}(),barycoordFromPoint:function(){var a=new f,b=new f,c=new f;return function(d,e,g,h,i){a.subVectors(h,e),b.subVectors(g,e),c.subVectors(d,e);var j=a.dot(a),k=a.dot(b),l=a.dot(c),m=b.dot(b),n=b.dot(c),o=j*m-k*k,p=i||new f;if(0===o)return p.set(-2,-1,-1);var q=1/o,r=(m*l-k*n)*q,s=(j*n-k*l)*q;return p.set(1-r-s,s,r)}}(),containsPoint:function(){var a=new f;return function(b,c,d,e){var f=Ia.barycoordFromPoint(b,c,d,e,a);return f.x>=0&&f.y>=0&&f.x+f.y<=1}}()}),Object.assign(Ia.prototype,{set:function(a,b,c){return this.a.copy(a),this.b.copy(b),this.c.copy(c),this},setFromPointsAndIndices:function(a,b,c,d){return this.a.copy(a[b]),this.b.copy(a[c]),this.c.copy(a[d]),this},clone:function(){return(new this.constructor).copy(this)},copy:function(a){return this.a.copy(a.a),this.b.copy(a.b),this.c.copy(a.c),this},area:function(){var a=new f,b=new f;return function(){return a.subVectors(this.c,this.b),b.subVectors(this.a,this.b),.5*a.cross(b).length()}}(),midpoint:function(a){return(a||new f).addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)},normal:function(a){return Ia.normal(this.a,this.b,this.c,a)},plane:function(a){return(a||new ca).setFromCoplanarPoints(this.a,this.b,this.c)},barycoordFromPoint:function(a,b){return Ia.barycoordFromPoint(a,this.a,this.b,this.c,b)},containsPoint:function(a){return Ia.containsPoint(a,this.a,this.b,this.c)},closestPointToPoint:function(){var a=new ca,b=[new Ha,new Ha,new Ha],c=new f,d=new f;return function(e,g){var h=g||new f,i=1/0;if(a.setFromCoplanarPoints(this.a,this.b,this.c),a.projectPoint(e,c),!0===this.containsPoint(c))h.copy(c);else{b[0].set(this.a,this.b),b[1].set(this.b,this.c),b[2].set(this.c,this.a);for(var j=0;j<b.length;j++){b[j].closestPointToPoint(c,!0,d);var k=c.distanceToSquared(d);k<i&&(i=k,h.copy(d))}}return h}}(),equals:function(a){return a.a.equals(this.a)&&a.b.equals(this.b)&&a.c.equals(this.c)}}),Ja.prototype=Object.assign(Object.create(ia.prototype),{constructor:Ja,isMesh:!0,setDrawMode:function(a){this.drawMode=a},copy:function(a){return ia.prototype.copy.call(this,a),this.drawMode=a.drawMode,void 0!==a.morphTargetInfluences&&(this.morphTargetInfluences=a.morphTargetInfluences.slice()),void 0!==a.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},a.morphTargetDictionary)),this},updateMorphTargets:function(){var a,b,c,d=this.geometry;if(d.isBufferGeometry){var e=d.morphAttributes,f=Object.keys(e);if(f.length>0){var g=e[f[0]];if(void 0!==g)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=g.length;a<b;a++)c=g[a].name||String(a),this.morphTargetInfluences.push(0),this.morphTargetDictionary[c]=a}}else{var h=d.morphTargets;if(void 0!==h&&h.length>0)for(this.morphTargetInfluences=[],this.morphTargetDictionary={},a=0,b=h.length;a<b;a++)c=h[a].name||String(a),this.morphTargetInfluences.push(0),this.morphTargetDictionary[c]=a}},raycast:function(){function a(a,b,c,d,e,f,g){return Ia.barycoordFromPoint(a,b,c,d,s),e.multiplyScalar(s.x),f.multiplyScalar(s.y),g.multiplyScalar(s.z),e.add(f).add(g),e.clone()}function b(a,b,c,d,e,f,g,h){if(null===(b.side===Hb?d.intersectTriangle(g,f,e,!0,h):d.intersectTriangle(e,f,g,b.side!==Ib,h)))return null;u.copy(h),u.applyMatrix4(a.matrixWorld);var i=c.ray.origin.distanceTo(u);return i<c.near||i>c.far?null:{distance:i,point:u.clone(),object:a}}function e(c,d,e,f,g,h,i,m){j.fromBufferAttribute(f,h),k.fromBufferAttribute(f,i),l.fromBufferAttribute(f,m);var n=b(c,c.material,d,e,j,k,l,t);return n&&(g&&(p.fromBufferAttribute(g,h),q.fromBufferAttribute(g,i),r.fromBufferAttribute(g,m),n.uv=a(t,j,k,l,p,q,r)),n.face=new la(h,i,m,Ia.normal(j,k,l)),n.faceIndex=h),n}var g=new d,h=new Ga,i=new ba,j=new f,k=new f,l=new f,m=new f,n=new f,o=new f,p=new c,q=new c,r=new c,s=new f,t=new f,u=new f;return function(c,d){var f=this.geometry,s=this.material,u=this.matrixWorld;if(void 0!==s&&(null===f.boundingSphere&&f.computeBoundingSphere(),i.copy(f.boundingSphere),i.applyMatrix4(u),!1!==c.ray.intersectsSphere(i)&&(g.getInverse(u),h.copy(c.ray).applyMatrix4(g),null===f.boundingBox||!1!==h.intersectsBox(f.boundingBox)))){var v;if(f.isBufferGeometry){var w,x,y,z,A,B=f.index,C=f.attributes.position,D=f.attributes.uv;if(null!==B)for(z=0,A=B.count;z<A;z+=3)w=B.getX(z),x=B.getX(z+1),y=B.getX(z+2),(v=e(this,c,h,C,D,w,x,y))&&(v.faceIndex=Math.floor(z/3),d.push(v));else if(void 0!==C)for(z=0,A=C.count;z<A;z+=3)w=z,x=z+1,y=z+2,(v=e(this,c,h,C,D,w,x,y))&&(v.index=w,d.push(v))}else if(f.isGeometry){var E,F,G,H,I=Array.isArray(s),J=f.vertices,K=f.faces,L=f.faceVertexUvs[0];L.length>0&&(H=L);for(var M=0,N=K.length;M<N;M++){var O=K[M],P=I?s[O.materialIndex]:s;if(void 0!==P){if(E=J[O.a],F=J[O.b],G=J[O.c],!0===P.morphTargets){var Q=f.morphTargets,R=this.morphTargetInfluences;j.set(0,0,0),k.set(0,0,0),l.set(0,0,0);for(var S=0,T=Q.length;S<T;S++){var U=R[S];if(0!==U){var V=Q[S].vertices;j.addScaledVector(m.subVectors(V[O.a],E),U),k.addScaledVector(n.subVectors(V[O.b],F),U),l.addScaledVector(o.subVectors(V[O.c],G),U)}}j.add(E),k.add(F),l.add(G),E=j,F=k,G=l}if(v=b(this,P,c,h,E,F,G,t)){if(H&&H[M]){var W=H[M];p.copy(W[0]),q.copy(W[1]),r.copy(W[2]),v.uv=a(t,E,F,G,p,q,r)}v.face=O,v.faceIndex=M,d.push(v)}}}}}}}(),clone:function(){return new this.constructor(this.geometry,this.material).copy(this)}});var Sf=0;ob.prototype=Object.assign(Object.create(ja.prototype),{constructor:ob,isPerspectiveCamera:!0,copy:function(a,b){return ja.prototype.copy.call(this,a,b),this.fov=a.fov,this.zoom=a.zoom,this.near=a.near,this.far=a.far,this.focus=a.focus,this.aspect=a.aspect,this.view=null===a.view?null:Object.assign({},a.view),this.filmGauge=a.filmGauge,this.filmOffset=a.filmOffset,this},setFocalLength:function(a){var b=.5*this.getFilmHeight()/a;this.fov=2*yd.RAD2DEG*Math.atan(b),this.updateProjectionMatrix()},getFocalLength:function(){var a=Math.tan(.5*yd.DEG2RAD*this.fov);return.5*this.getFilmHeight()/a},getEffectiveFOV:function(){return 2*yd.RAD2DEG*Math.atan(Math.tan(.5*yd.DEG2RAD*this.fov)/this.zoom)},getFilmWidth:function(){return this.filmGauge*Math.min(this.aspect,1)},getFilmHeight:function(){return this.filmGauge/Math.max(this.aspect,1)},setViewOffset:function(a,b,c,d,e,f){this.aspect=a/b,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=a,this.view.fullHeight=b,this.view.offsetX=c,this.view.offsetY=d,this.view.width=e,this.view.height=f,this.updateProjectionMatrix()},clearViewOffset:function(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()},updateProjectionMatrix:function(){var a=this.near,b=a*Math.tan(.5*yd.DEG2RAD*this.fov)/this.zoom,c=2*b,d=this.aspect*c,e=-.5*d,f=this.view;if(null!==this.view&&this.view.enabled){var g=f.fullWidth,h=f.fullHeight;e+=f.offsetX*d/g,b-=f.offsetY*c/h,d*=f.width/g,c*=f.height/h}var i=this.filmOffset;0!==i&&(e+=a*i/this.getFilmWidth()),this.projectionMatrix.makePerspective(e,e+d,b,b-c,a,this.far)},toJSON:function(a){var b=ia.prototype.toJSON.call(this,a);return b.object.fov=this.fov,b.object.zoom=this.zoom,b.object.near=this.near,b.object.far=this.far,b.object.focus=this.focus,b.object.aspect=this.aspect,null!==this.view&&(b.object.view=Object.assign({},this.view)),b.object.filmGauge=this.filmGauge,b.object.filmOffset=this.filmOffset,b}}),pb.prototype=Object.assign(Object.create(ob.prototype),{constructor:pb,isArrayCamera:!0}),vb.prototype=Object.assign(Object.create(ia.prototype),{constructor:vb,copy:function(a,b){return ia.prototype.copy.call(this,a,b),null!==a.background&&(this.background=a.background.clone()),null!==a.fog&&(this.fog=a.fog.clone()),null!==a.overrideMaterial&&(this.overrideMaterial=a.overrideMaterial.clone()),this.autoUpdate=a.autoUpdate,this.matrixAutoUpdate=a.matrixAutoUpdate,this},toJSON:function(a){var b=ia.prototype.toJSON.call(this,a);return null!==this.background&&(b.object.background=this.background.toJSON(a)),null!==this.fog&&(b.object.fog=this.fog.toJSON()),b}});var Tf={enabled:!1,files:{},add:function(a,b){!1!==this.enabled&&(this.files[a]=b)},get:function(a){if(!1!==this.enabled)return this.files[a]},remove:function(a){delete this.files[a]},clear:function(){this.files={}}},Uf=new wb;Object.assign(xb.prototype,{crossOrigin:"Anonymous",load:function(a,b,c,d){void 0===a&&(a=""),void 0!==this.path&&(a=this.path+a),a=this.manager.resolveURL(a);var e=this,f=Tf.get(a);if(void 0!==f)return e.manager.itemStart(a),setTimeout(function(){b&&b(f),e.manager.itemEnd(a)},0),f;var g=document.createElementNS("http://www.w3.org/1999/xhtml","img");return g.addEventListener("load",function(){Tf.add(a,this),b&&b(this),e.manager.itemEnd(a)},!1),g.addEventListener("error",function(b){d&&d(b),e.manager.itemEnd(a),e.manager.itemError(a)},!1),"data:"!==a.substr(0,5)&&void 0!==this.crossOrigin&&(g.crossOrigin=this.crossOrigin),e.manager.itemStart(a),g.src=a,g},setCrossOrigin:function(a){return this.crossOrigin=a,this},setPath:function(a){return this.path=a,this}}),Object.assign(yb.prototype,{crossOrigin:"Anonymous",load:function(a,b,c,d){var e=new h,f=new xb(this.manager);return f.setCrossOrigin(this.crossOrigin),f.setPath(this.path),f.load(a,function(c){e.image=c;var d=a.search(/\.(jpg|jpeg)$/)>0||0===a.search(/^data\:image\/jpeg/);e.format=d?Zc:$c,e.needsUpdate=!0,void 0!==b&&b(e)},c,d),e},setCrossOrigin:function(a){return this.crossOrigin=a,this},setPath:function(a){return this.path=a,this}}),a.WebGLRenderTarget=j,a.WebGLRenderer=ub,a.Scene=vb,a.Mesh=Ja,a.DataTexture=k,a.PlaneGeometry=Ca,a.ShaderMaterial=Fa,a.MeshBasicMaterial=Ea,a.Material=Z,a.TextureLoader=yb,a.OrthographicCamera=ka,a.ClampToEdgeWrapping=Ec,a.FloatType=Sc,a.LinearFilter=Jc,a.NearestFilter=Gc,a.NearestMipMapNearestFilter=Hc,a.RepeatWrapping=Dc,a.RGBAFormat=$c,a.UnsignedByteType=Mc,Object.defineProperty(a,"__esModule",{value:!0})}),require=function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c||a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){(function(b){b.THREE=a("three"),THREE={ClampToEdgeWrapping:THREE.ClampToEdgeWrapping,DataTexture:THREE.DataTexture,FloatType:THREE.FloatType,LinearFilter:THREE.LinearFilter,Material:THREE.Material,Mesh:THREE.Mesh,MeshBasicMaterial:THREE.MeshBasicMaterial,NearestFilter:THREE.NearestFilter,NearestMipMapNearestFilter:THREE.NearestMipMapNearestFilter,OrthographicCamera:THREE.OrthographicCamera,PlaneGeometry:THREE.PlaneGeometry,RepeatWrapping:THREE.RepeatWrapping,RGBAFormat:THREE.RGBAFormat,Scene:THREE.Scene,ShaderMaterial:THREE.ShaderMaterial,TextureLoader:THREE.TextureLoader,UnsignedByteType:THREE.UnsignedByteType,WebGLRenderer:THREE.WebGLRenderer,WebGLRenderTarget:THREE.WebGLRenderTarget}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{three:"three"}],three:[function(a,b,c){b.exports=window.THREE},{}]},{},[1]);var Detector={canvas:!!window.CanvasRenderingContext2D,webgl:function(){try{var a=document.createElement("canvas");return!(!window.WebGLRenderingContext||!a.getContext("webgl")&&!a.getContext("experimental-webgl"))}catch(a){return!1}}(),workers:!!window.Worker,fileapi:window.File&&window.FileReader&&window.FileList&&window.Blob,getWebGLErrorMessage:function(){var a=document.createElement("div");return a.id="webgl-error-message",a.style.fontFamily="monospace",a.style.fontSize="13px",a.style.fontWeight="normal",a.style.textAlign="center",a.style.background="#fff",a.style.color="#000",a.style.padding="1.5em",a.style.width="400px",a.style.margin="5em auto 0",this.webgl||(a.innerHTML=window.WebGLRenderingContext?['Your graphics card does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" style="color:#000">WebGL</a>.<br />','Find out how to get it <a href="http://get.webgl.org/" style="color:#000">here</a>.'].join("\n"):['Your browser does not seem to support <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation" style="color:#000">WebGL</a>.<br/>','Find out how to get it <a href="http://get.webgl.org/" style="color:#000">here</a>.'].join("\n")),a},addGetWebGLMessage:function(a){var b,c,d;a=a||{},b=void 0!==a.parent?a.parent:document.body,c=void 0!==a.id?a.id:"oldie",d=Detector.getWebGLErrorMessage(),d.id=c,b.appendChild(d)}};"object"==typeof module&&(module.exports=Detector),function(a,b){"use strict";function c(){if(a.postMessage&&!a.importScripts){var b=!0,c=a.onmessage;return a.onmessage=function(){b=!1},a.postMessage("","*"),a.onmessage=c,b}}function d(){return a.navigator&&/Trident/.test(a.navigator.userAgent)}if(!d()&&(a.msSetImmediate||a.setImmediate))return void(a.setImmediate||(a.setImmediate=a.msSetImmediate,a.clearImmediate=a.msClearImmediate));var e=a.document,f=Array.prototype.slice,g=Object.prototype.toString,h={};h.polifill={},h.nextId=1,h.tasks={},h.lock=!1,h.run=function(b){if(h.lock)a.setTimeout(h.wrap(h.run,b),0);else{var c=h.tasks[b];if(c){h.lock=!0;try{c()}finally{h.clear(b),h.lock=!1}}}},h.wrap=function(a){var c=f.call(arguments,1);return function(){a.apply(b,c)}},h.create=function(a){return h.tasks[h.nextId]=h.wrap.apply(b,a),h.nextId++},h.clear=function(a){delete h.tasks[a]},h.polifill.messageChannel=function(){var b=new a.MessageChannel;return b.port1.onmessage=function(a){h.run(Number(a.data))},function(){var a=h.create(arguments);return b.port2.postMessage(a),a}},h.polifill.nextTick=function(){return function(){var b=h.create(arguments);return a.process.nextTick(h.wrap(h.run,b)),b}},h.polifill.postMessage=function(){var b="setImmediate$"+Math.random()+"$",c=function(c){c.source===a&&"string"==typeof c.data&&0===c.data.indexOf(b)&&h.run(Number(c.data.slice(b.length)))};return a.addEventListener?a.addEventListener("message",c,!1):a.attachEvent("onmessage",c),function(){var c=h.create(arguments);return a.postMessage(b+c,"*"),c}},h.polifill.readyStateChange=function(){var a=e.documentElement;return function(){var b=h.create(arguments),c=e.createElement("script");return c.onreadystatechange=function(){h.run(b),c.onreadystatechange=null,a.removeChild(c),c=null},a.appendChild(c),b}},h.polifill.setTimeout=function(){return function(){var b=h.create(arguments);return a.setTimeout(h.wrap(h.run,b),0),b}};var i;i=d()?"setTimeout":"[object process]"===g.call(a.process)?"nextTick":c()?"postMessage":a.MessageChannel?"messageChannel":e&&"onreadystatechange"in e.createElement("script")?"readyStateChange":"setTimeout";var j=Object.getPrototypeOf&&Object.getPrototypeOf(a);j=j&&j.setTimeout?j:a,j.setImmediate=h.polifill[i](),j.setImmediate.usePolifill=i,j.msSetImmediate=j.setImmediate,j.clearImmediate=h.clear,j.msClearImmediate=h.clear}(function(){return this||(0,eval)("this")}()),function(){"use strict";function a(){}function b(a,b){for(var c=a.length;c--;)if(a[c].listener===b)return c;return-1}function c(a){return function(){return this[a].apply(this,arguments)}}var d=a.prototype,e=this,f=e.EventEmitter;d.getListeners=function(a){var b,c,d=this._getEvents();if(a instanceof RegExp){b={};for(c in d)d.hasOwnProperty(c)&&a.test(c)&&(b[c]=d[c])}else b=d[a]||(d[a]=[]);return b},d.flattenListeners=function(a){var b,c=[];for(b=0;b<a.length;b+=1)c.push(a[b].listener);return c},d.getListenersAsObject=function(a){var b,c=this.getListeners(a);return c instanceof Array&&(b={},b[a]=c),b||c},d.addListener=function(a,c){var d,e=this.getListenersAsObject(a),f="object"==typeof c;for(d in e)e.hasOwnProperty(d)&&-1===b(e[d],c)&&e[d].push(f?c:{listener:c,once:!1});return this},d.on=c("addListener"),d.addOnceListener=function(a,b){return this.addListener(a,{listener:b,once:!0})},d.once=c("addOnceListener"),d.defineEvent=function(a){return this.getListeners(a),this},d.defineEvents=function(a){for(var b=0;b<a.length;b+=1)this.defineEvent(a[b]);return this},d.removeListener=function(a,c){var d,e,f=this.getListenersAsObject(a);for(e in f)f.hasOwnProperty(e)&&-1!==(d=b(f[e],c))&&f[e].splice(d,1);return this},d.off=c("removeListener"),d.addListeners=function(a,b){return this.manipulateListeners(!1,a,b)},d.removeListeners=function(a,b){return this.manipulateListeners(!0,a,b)},d.manipulateListeners=function(a,b,c){var d,e,f=a?this.removeListener:this.addListener,g=a?this.removeListeners:this.addListeners;if("object"!=typeof b||b instanceof RegExp)for(d=c.length;d--;)f.call(this,b,c[d]);else for(d in b)b.hasOwnProperty(d)&&(e=b[d])&&("function"==typeof e?f.call(this,d,e):g.call(this,d,e));return this},d.removeEvent=function(a){var b,c=typeof a,d=this._getEvents();if("string"===c)delete d[a];else if(a instanceof RegExp)for(b in d)d.hasOwnProperty(b)&&a.test(b)&&delete d[b];else delete this._events;return this},d.removeAllListeners=c("removeEvent"),d.emitEvent=function(a,b){var c,d,e,f,g=this.getListenersAsObject(a);for(f in g)if(g.hasOwnProperty(f))for(c=g[f].slice(0),e=c.length;e--;)d=c[e],!0===d.once&&this.removeListener(a,d.listener),d.listener.apply(this,b||[])===this._getOnceReturnValue()&&this.removeListener(a,d.listener);return this},d.trigger=c("emitEvent"),d.emit=function(a){var b=Array.prototype.slice.call(arguments,1);return this.emitEvent(a,b)},d.setOnceReturnValue=function(a){return this._onceReturnValue=a,this},d._getOnceReturnValue=function(){return!this.hasOwnProperty("_onceReturnValue")||this._onceReturnValue},d._getEvents=function(){return this._events||(this._events={})},a.noConflict=function(){return e.EventEmitter=f,a},"function"==typeof define&&define.amd?define(function(){return a}):"object"==typeof module&&module.exports?module.exports=a:e.EventEmitter=a}.call(this),GrowingPacker=function(){},GrowingPacker.prototype={fit:function(a){var b,c,d,e=a.length,f=e>0?a[0].w:0,g=e>0?a[0].h:0;for(this.root={x:0,y:0,w:f,h:g},b=0;b<e;b++)d=a[b],(c=this.findNode(this.root,d.w,d.h))?d.fit=this.splitNode(c,d.w,d.h):d.fit=this.growNode(d.w,d.h)},findNode:function(a,b,c){return a.used?this.findNode(a.right,b,c)||this.findNode(a.down,b,c):b<=a.w&&c<=a.h?a:null},splitNode:function(a,b,c){return a.used=!0,a.down={x:a.x,y:a.y+c,w:a.w,h:a.h-c},a.right={x:a.x+b,y:a.y,w:a.w-b,h:c},a},growNode:function(a,b){var c=a<=this.root.w,d=b<=this.root.h,e=d&&this.root.h>=this.root.w+a,f=c&&this.root.w>=this.root.h+b;return e?this.growRight(a,b):f?this.growDown(a,b):d?this.growRight(a,b):c?this.growDown(a,b):null},growRight:function(a,b){this.root={used:!0,x:0,y:0,w:this.root.w+a,h:this.root.h,down:this.root,right:{x:this.root.w,y:0,w:a,h:this.root.h}};var c=this.findNode(this.root,a,b);return c?this.splitNode(c,a,b):null},growDown:function(a,b){this.root={used:!0,x:0,y:0,w:this.root.w,h:this.root.h+b,down:{x:0,y:this.root.h,w:this.root.w,h:b},right:this.root};var c=this.findNode(this.root,a,b);return c?this.splitNode(c,a,b):null}},function(){function a(a,d){var e=(new Date).getTime(),f=Math.max(0,16-(e-c)),g=b.setTimeout(function(){a(e+f)},f);return c=e+f,g}for(var b=this,c=0,d=["ms","moz","webkit","o"],e=0;e<d.length&&!b.requestAnimationFrame;++e)b.requestAnimationFrame=b[d[e]+"RequestAnimationFrame"],b.cancelAnimationFrame=b[d[e]+"CancelAnimationFrame"]||b[d[e]+"CancelRequestAnimationFrame"];b.requestAnimationFrame||(b.requestAnimationFrame=a),b.cancelAnimationFrame||(b.cancelAnimationFrame=function(a){clearTimeout(a)}),"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=b.requestAnimationFrame),exports.requestAnimationFrame=b.requestAnimationFrame):b.requestAnimationFrame=b.requestAnimationFrame,"function"==typeof define&&define.amd&&define("requestAnimationFrame",[],function(){return b.requestAnimationFrame})}(),function(a,b,c,d,e){var f=this,g=f.Blotter=a=function(a,b){d.webgl||g.Messaging.throwError("Blotter",!1,"device does not support webgl"),this._texts=[],this._textEventBindings={},this._scopes={},this._scopeEventBindings={},this._renderer=new g.Renderer,this._startTime=0,this._lastDrawTime=0,this.init.apply(this,arguments)};g.prototype=function(){function a(){var a=Date.now();this._material.uniforms.uTimeDelta.value=(a-(this._lastDrawTime||a))/1e3,this._material.uniforms.uGlobalTime.value=(a-this._startTime)/1e3,this._lastDrawTime=a}function c(){a.call(this),b.each(this._scopes,b.bind(function(a){a.playing&&a.render(),this.trigger("render")},this))}function d(a){if(this.mappingMaterial){var b=this._material.uniforms[a].value;this.mappingMaterial.uniformInterface[a].value=b}}function e(a,b){if(this.mappingMaterial){var c=this._scopes[a],d=c.material.uniforms[b].value;this.mappingMaterial.textUniformInterface[a][b].value=d}}function f(){var a,c,d;a=b.bind(function(){return b.bind(function(a){g.MappingBuilder.build(this._texts,b.bind(function(b){this._mapping=b,this._mapping.ratio=this.ratio,a()},this))},this)},this),c=b.bind(function(){return b.bind(function(a){g.MappingMaterialBuilder.build(this._mapping,this._material,b.bind(function(b){this.mappingMaterial=b,a()},this))},this)},this),d=[a(),c()],b(d).reduceRight(b.wrap,b.bind(function(){this._renderer.stop(),b.each(this._scopes,b.bind(function(a,b){a.mappingMaterial=this.mappingMaterial,a.needsUpdate=!0},this)),this._renderer.material=this.mappingMaterial.shaderMaterial,this._renderer.width=this._mapping.width,this._renderer.height=this._mapping.height,this.autostart&&this.start(),this.trigger(this.lastUpdated?"update":"ready"),this.lastUpdated=Date.now()},this))()}return{constructor:g,get needsUpdate(){},set needsUpdate(a){!0===a&&f.call(this)},get material(){return this._material},set material(a){this.setMaterial(a)},get texts(){return this._texts},set texts(a){this.removeTexts(this._texts),this.addTexts(a)},get imageData(){return this._renderer.imageData},init:function(a,d){d=d||{},b.defaults(this,d,{ratio:g.CanvasUtils.pixelRatio,autobuild:!0,autostart:!0,autoplay:!0}),this.setMaterial(a),this.addTexts(d.texts),this._renderer.on("render",b.bind(c,this)),this.autobuild&&(this.needsUpdate=!0),this.autostart&&this.start()},start:function(){this.autostart=!0,this._startTime=Date.now(),this._renderer.start()},stop:function(){this.autostart=!1,this._renderer.stop()},teardown:function(){this._renderer.teardown()},setMaterial:function(a){g.Messaging.ensureInstanceOf(a,g.Material,"Blotter.Material","Blotter","setMaterial"),this._material=a,this._materialEventBinding&&this._materialEventBinding.unsetEventCallbacks(),this._materialEventBinding=new g.ModelEventBinding(a,{update:b.bind(function(){f.call(this)},this),updateUniform:b.bind(function(a){d.call(this,a)},this)}),a.on("update",this._materialEventBinding.eventCallbacks.update),a.on("update:uniform",this._materialEventBinding.eventCallbacks.updateUniform)},addText:function(a){this.addTexts(a)},addTexts:function(a){var c=g.TextUtils.filterTexts(a),d=b.difference(c,this._texts);b.each(d,b.bind(function(a){this._texts.push(a),this._textEventBindings[a.id]=new g.ModelEventBinding(a,{update:b.bind(function(){f.call(this)},this)}),a.on("update",this._textEventBindings[a.id].eventCallbacks.update),this._scopes[a.id]=new g.RenderScope(a,this),this._scopeEventBindings[a.id]=new g.ModelEventBinding(this._scopes[a.id],{updateUniform:b.bind(function(b){e.call(this,a.id,b)},this)}),this._scopes[a.id].on("update:uniform",this._scopeEventBindings[a.id].eventCallbacks.updateUniform)},this))},removeText:function(a){this.removeTexts(a)},removeTexts:function(a){var c=g.TextUtils.filterTexts(a),d=b.intersection(this._texts,c);b.each(d,b.bind(function(a){this._texts=b.without(this._texts,a),this._textEventBindings[a.id].unsetEventCallbacks(),this._scopeEventBindings[a.id].unsetEventCallbacks(),delete this._textEventBindings[a.id],delete this._scopeEventBindings[a.id],delete this._scopes[a.id]},this))},forText:function(a){return g.Messaging.ensureInstanceOf(a,g.Text,"Blotter.Text","Blotter","forText"),this._scopes[a.id]?this._scopes[a.id]:void g.Messaging.logError("Blotter","forText","Blotter.Text object not found in blotter")},boundsForText:function(a){return g.Messaging.ensureInstanceOf(a,g.Text,"Blotter.Text","Blotter","boundsForText"),this._scopes[a.id]?this._mapping?this.mappingMaterial.boundsForText(a):void 0:void g.Messaging.logError("Blotter","boundsForText","Blotter.Text object not found in blotter")}}}(),b.extend(g.prototype,e.prototype),g.Version="v0.1.0",g.webglRenderer=g.webglRenderer||new c.WebGLRenderer({antialias:!0,alpha:!0,premultipliedAlpha:!1}),g.Assets=g.Assets||{},g.Assets.Shaders=g.Assets.Shaders||{}}(this.Blotter,this._,this.THREE,this.Detector,this.EventEmitter),function(a){a.Math={generateUUID:function(){for(var a=[],b=0;b<256;b++)a[b]=(b<16?"0":"")+b.toString(16).toUpperCase();return function(){var b=4294967295*Math.random()|0,c=4294967295*Math.random()|0,d=4294967295*Math.random()|0,e=4294967295*Math.random()|0;return a[255&b]+a[b>>8&255]+a[b>>16&255]+a[b>>24&255]+"-"+a[255&c]+a[c>>8&255]+"-"+a[c>>16&15|64]+a[c>>24&255]+"-"+a[63&d|128]+a[d>>8&255]+"-"+a[d>>16&255]+a[d>>24&255]+a[255&e]+a[e>>8&255]+a[e>>16&255]+a[e>>24&255]}}()}}(this.Blotter),function(a){a.Messaging=function(){function a(a,b,c){return a+(b?"#"+b:"")+": "+c}return{ensureInstanceOf:function(a,b,c,d,e){if(!(a instanceof b))return void this.logError(d,e,"argument must be instanceof "+c)},logError:function(b,c,d){var e=a(b,c,d);console.error(e)},logWarning:function(b,c,d){var e=a(b,c,d);console.warn(e)},throwError:function(b,c,d){throw a(b,c,d)}}}()}(this.Blotter),function(a,b){a._extendWithGettersSetters=function(a){return b.each(Array.prototype.slice.call(arguments,1),function(b){if(b)for(var c in b)a[c]&&Object.getOwnPropertyDescriptor(a,c)&&Object.getOwnPropertyDescriptor(a,c).set?Object.getOwnPropertyDescriptor(a,c).set(b[c]):a[c]=b[c]}),a}}(this.Blotter,this._),function(a){a.VendorPrefixes=["ms","moz","webkit","o"]}(this.Blotter),function(a,b){a.ModelEventBinding=function(a,b){this.model=a,this.eventCallbacks=b||{}},a.ModelEventBinding.prototype={constructor:a.ModelEventBinding,unsetEventCallbacks:function(){b.each(this.eventCallbacks,b.bind(function(a,b){this.model.off(b,a)},this))}}}(this.Blotter,this._),function(a){a.CanvasUtils={canvas:function(a,b,c){c=c||{};var d=document.createElement("canvas");return d.className=c.class,d.innerHTML=c.html,d.width=a,d.height=b,d},hiDpiCanvas:function(a,b,c,d){c=c||this.pixelRatio,d=d||{};var e=document.createElement("canvas");return e.className=d.class,e.innerHTML=d.html,this.updateCanvasSize(e,a,b,c),e},updateCanvasSize:function(a,b,c,d){d=d||1,a.width=b*d,a.height=c*d,a.style.width=b+"px",a.style.height=c+"px",a.getContext("2d").setTransform(d,0,0,d,0,0)},pixelRatio:function(){for(var b=document.createElement("canvas").getContext("2d"),c=window.devicePixelRatio||1,d=b.backingStorePixelRatio,e=0;e<a.VendorPrefixes.length&&!d;++e)d=b[a.VendorPrefixes[e]+"BackingStorePixelRatio"];return d=d||1,c/d}(),mousePosition:function(a,b){var c=a.getBoundingClientRect();return{x:b.clientX-c.left,y:b.clientY-c.top}},normalizedMousePosition:function(a,b){var c=a.getBoundingClientRect(),d=this.mousePosition(a,b);return{x:d.x/c.width,y:d.y/c.height}}}}(this.Blotter),function(a,b){a.PropertyDefaults={family:"sans-serif",size:12,leading:1.5,fill:"#000",style:"normal",weight:400,padding:0,paddingTop:0,paddingRight:0,paddingBottom:0,paddingLeft:0},a.TextUtils={Properties:b.keys(a.PropertyDefaults),ensurePropertyValues:function(c){return c=b.defaults(c||{},a.PropertyDefaults)},filterTexts:function(c){return c=c instanceof a.Text?[c]:b.toArray(c),b.filter(c,b.bind(function(b){var c=b instanceof a.Text;return c||a.Messaging.logWarning("Blotter.TextUtils","filterTexts","object must be instance of Blotter.Text"),c},this))},stringifiedPadding:function(a){var b=a||this.ensurePropertyValues();return(a.paddingTop||b.padding)+"px "+(b.paddingRight||b.padding)+"px "+(b.paddingBottom||b.padding)+"px "+(b.paddingLeft||b.padding)+"px"},sizeForText:function(a,b){var c,d=document.createElement("span");return b=this.ensurePropertyValues(b),d.innerHTML=a,d.style.display="inline-block",d.style.fontFamily=b.family,d.style.fontSize=b.size+"px",d.style.fontWeight=b.weight,d.style.fontStyle=b.style,d.style.lineHeight=b.leading,d.style.maxWidth="none",d.style.padding=this.stringifiedPadding(b),d.style.position="absolute",d.style.width="auto",d.style.visibility="hidden",document.body.appendChild(d),c={w:d.offsetWidth,h:d.offsetHeight},document.body.removeChild(d),c}}}(this.Blotter,this._),function(a,b){a.UniformUtils={UniformTypes:["1f","2f","3f","4f"],defaultUniforms:{uResolution:{type:"2f",value:[0,0]},uGlobalTime:{type:"1f",value:0},uTimeDelta:{type:"1f",value:0},uBlendColor:{type:"4f",value:[1,1,1,1]},uPixelRatio:{type:"1f",value:a.CanvasUtils.pixelRatio}},validValueForUniformType:function(a,c){var d=!1,e=function(a){return!isNaN(a)};switch(a){case"1f":d=!isNaN(c)&&[c].every(e);break;case"2f":d=b.isArray(c)&&2==c.length&&c.every(e);break;case"3f":d=b.isArray(c)&&3==c.length&&c.every(e);break;case"4f":d=b.isArray(c)&&4==c.length&&c.every(e)}return d},glslDataTypeForUniformType:function(a){var b;switch(a){case"1f":b="float";break;case"2f":b="vec2";break;case"3f":b="vec3";break;case"4f":b="vec4"}return b},fullSwizzleStringForUniformType:function(a){var b;switch(a){case"1f":b="x";break;case"2f":b="xy";break;case"3f":b="xyz";break;case"4f":b="xyzw"}return b},extractValidUniforms:function(c){return c=c||{},b.reduce(c,function(c,d,e){return-1==a.UniformUtils.UniformTypes.indexOf(d.type)?(a.Messaging.logError("Blotter.UniformUtils","extractValidUniforms","uniforms must be one of type: "+a.UniformUtils.UniformTypes.join(", ")),c):a.UniformUtils.validValueForUniformType(d.type,d.value)?(c[e]=b.pick(d,"type","value"),c):(a.Messaging.logError("Blotter.UniformUtils","extractValidUniforms","uniform value for "+e+" is incorrect for type: "+d.type),c)},{})},ensureHasRequiredDefaultUniforms:function(b,c,d){if(!a.UniformUtils.hasRequiredDefaultUniforms(b))return void this.logError(c,d,"uniforms object is missing required default uniforms defined in Blotter.UniformUtils.defaultUniforms")},hasRequiredDefaultUniforms:function(c){return!b.difference(b.allKeys(a.UniformUtils.defaultUniforms),b.allKeys(c)).length}}}(this.Blotter,this._),function(a,b,c,d){a.Text=function(b,c){this.id=a.Math.generateUUID(),this.value=b,this.properties=c},a.Text.prototype={constructor:a.Text,get needsUpdate(){},set needsUpdate(a){!0===a&&this.trigger("update")},get properties(){return this._properties},set properties(b){this._properties=a.TextUtils.ensurePropertyValues(b)}},a._extendWithGettersSetters(a.Text.prototype,d.prototype)}(this.Blotter,this._,this.THREE,this.EventEmitter),function(a,b){a.Assets.Shaders.Blending=["//","// Author : Bradley Griffith","// License : Distributed under the MIT License.","//","","// Returns the resulting blend color by blending a top color over a base color","highp vec4 normalBlend(highp vec4 topColor, highp vec4 baseColor) {"," highp vec4 blend = vec4(0.0);"," // HACK"," // Cant divide by 0 (see the 'else' alpha) and after a lot of attempts"," // this simply seems like the only solution Im going to be able to come up with to get alpha back."," if (baseColor.a == 1.0) {"," baseColor.a = 0.9999999;"," };"," if (topColor.a >= 1.0) {"," blend.a = topColor.a;"," blend.r = topColor.r;"," blend.g = topColor.g;"," blend.b = topColor.b;"," } else if (topColor.a == 0.0) {"," blend.a = baseColor.a;"," blend.r = baseColor.r;"," blend.g = baseColor.g;"," blend.b = baseColor.b;"," } else {"," blend.a = 1.0 - (1.0 - topColor.a) * (1.0 - baseColor.a); // alpha"," blend.r = (topColor.r * topColor.a / blend.a) + (baseColor.r * baseColor.a * (1.0 - topColor.a) / blend.a);"," blend.g = (topColor.g * topColor.a / blend.a) + (baseColor.g * baseColor.a * (1.0 - topColor.a) / blend.a);"," blend.b = (topColor.b * topColor.a / blend.a) + (baseColor.b * baseColor.a * (1.0 - topColor.a) / blend.a);"," }"," return blend;","}","// Returns a vec4 representing the original top color that would have been needed to blend","// against a passed in base color in order to result in the passed in blend color.","highp vec4 normalUnblend(highp vec4 blendColor, highp vec4 baseColor) {"," highp vec4 unblend = vec4(0.0);"," // HACKY"," // Cant divide by 0 (see alpha) and after a lot of attempts"," // this simply seems like the only solution Im going to be able to come up with to get alpha back."," if (baseColor.a == 1.0) {"," baseColor.a = 0.9999999;"," }"," unblend.a = 1.0 - ((1.0 - blendColor.a) / (1.0 - baseColor.a));"," // Round to two decimal places"," unblend.a = (sign(100.0 * unblend.a) * floor(abs(100.0 * unblend.a) + 0.5)) / 100.0;"," if (unblend.a >= 1.0) {"," unblend.r = blendColor.r;"," unblend.g = blendColor.g;"," unblend.b = blendColor.b;"," } else if (unblend.a == 0.0) {"," unblend.r = baseColor.r;"," unblend.g = baseColor.g;"," unblend.b = baseColor.b;"," } else {"," unblend.r = (blendColor.r - (baseColor.r * baseColor.a * (1.0 - unblend.a) / blendColor.a)) / (unblend.a / blendColor.a);"," unblend.g = (blendColor.g - (baseColor.g * baseColor.a * (1.0 - unblend.a) / blendColor.a)) / (unblend.a / blendColor.a);"," unblend.b = (blendColor.b - (baseColor.b * baseColor.a * (1.0 - unblend.a) / blendColor.a)) / (unblend.a / blendColor.a);"," }"," return unblend;","}"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.Inf=["//","// Author : Bradley Griffith","// License : Distributed under the MIT License.","//","bool isinf(float val) {"," return (val != 0.0 && val * 2.0 == val) ? true : false;","}"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.LineMath=[a.Assets.Shaders.Inf,"","//","// Author : Bradley Griffith","// License : Distributed under the MIT License.","//","","// Returns the slope of a line given the degrees of the angle on which that line is rotated;","float slopeForDegrees(float deg) {"," // Ensure degrees stay withing 0.0 - 360.0"," deg = mod(deg, 360.0);"," float radians = deg * (PI / 180.0);"," return tan(radians);","}","// Given x, a slope, and another point, find y for x.","float yForXOnSlope(float x, float slope, vec2 p2) {"," return -1.0 * ((slope * (p2.x - x)) - p2.y);","}","// Given y, a slope, and another point, find x for y.","float xForYOnSlope(float y, float slope, vec2 p2) {"," return ((y - p2.y) + (slope * p2.x)) / slope;","}","// Returns slope adjusted for screen ratio.","float normalizedSlope(float slope, vec2 resolution) {"," vec2 p = vec2(1.0) / resolution;"," return ((slope * 100.0) / p.x) / (100.0 / p.x);","}","// Returns offsets (+/-) for any coordinate at distance given slope.","// Note: This function does not normalize distance.","// Note: This function does not adjust slope for screen ratio.","vec2 offsetsForCoordAtDistanceOnSlope(float d, float slope) {"," return vec2("," (d * cos(atan(slope))),"," (d * sin(atan(slope)))"," );","}","// Returns a boolean designating whether or not an infinite line intersects with an infinite line, and sets an `out` variable for the intersection point if it is found.","// Note: This function does not adjust slope for screen ratio.","bool lineLineIntersection (out vec2 intersect, in vec2 p1, in float m1, in vec2 p2, in float m2) {"," // See: http://gamedev.stackexchange.com/questions/44720/line-intersection-from-parametric-equation"," // http://stackoverflow.com/questions/41687083/formula-to-determine-if-an-infinite-line-and-a-line-segment-intersect/41687904#41687904"," bool isIntersecting = false;"," float dx = 1.0;"," float dy = m1;"," float dxx = 1.0;"," float dyy = m2;"," float denominator = ((dxx * dy) - (dyy * dx));"," if (denominator == 0.0) {"," // Lines are parallel"," return isIntersecting;"," }"," if (isinf(dy)) {"," float y = yForXOnSlope(p1.x, m2, p2);"," isIntersecting = true;"," intersect = vec2(p1.x, y);"," return isIntersecting;"," }"," if (isinf(dyy)) {"," float y = yForXOnSlope(p2.x, m1, p1);"," isIntersecting = true;"," intersect = vec2(p2.x, y);"," return isIntersecting;"," }"," float u = ((dx * (p2.y - p1.y)) + (dy * (p1.x - p2.x))) / denominator;"," isIntersecting = true;"," intersect = p2 + (u * vec2(dxx, dyy));"," return isIntersecting;","}","// Returns a boolean designating whether or not an infinite line intersects with a line segment, and sets an `out` variable for the intersection point if it is found.","// Note: This function does not adjust slope for screen ratio.","bool lineLineSegmentIntersection (out vec2 intersect, in vec2 point, in float m, in vec2 pA, in vec2 pB) {"," // See: http://gamedev.stackexchange.com/questions/44720/line-intersection-from-parametric-equation"," // http://stackoverflow.com/questions/41687083/formula-to-determine-if-an-infinite-line-and-a-line-segment-intersect/41687904#41687904"," bool isIntersecting = false;"," float dx = 1.0;"," float dy = m;"," float dxx = pB.x - pA.x;"," float dyy = pB.y - pA.y;"," float denominator = ((dxx * dy) - (dyy * dx));"," if (denominator == 0.0 || (isinf(dyy / dxx) && isinf(dy))) {"," // Lines are parallel"," return isIntersecting;"," }"," if (isinf(dy)) {"," float m2 = dyy / dxx;"," float y = yForXOnSlope(point.x, m2, pB);"," isIntersecting = true;"," intersect = vec2(point.x, y);"," return isIntersecting;"," }"," float u = ((dx * (pA.y - point.y)) + (dy * (point.x - pA.x))) / denominator;"," if (u >= 0.0 && u <= 1.0) {"," // Intersection occured on line segment"," isIntersecting = true;"," intersect = pA + (u * vec2(dxx, dyy));"," }"," return isIntersecting;","}","// Dev Note: Terrible code. Needs refactor. Just trying to find ","// which two edges of the rect the intersections occur at.","void intersectsOnRectForLine(out vec2 iA, out vec2 iB, in vec2 rMinXY, in vec2 rMaxXY, in vec2 point, in float slope) {"," bool firstIntersectFound = false;"," vec2 intersectLeft = vec2(0.0);"," vec2 intersectTop = vec2(0.0);"," vec2 intersectRight = vec2(0.0);"," vec2 intersectBottom = vec2(0.0);"," bool intersectsLeft = lineLineSegmentIntersection(intersectLeft, point, slope, rMinXY, vec2(rMinXY.x, rMaxXY.y));"," bool intersectsTop = lineLineSegmentIntersection(intersectTop, point, slope, vec2(rMinXY.x, rMaxXY.y), rMaxXY);"," bool intersectsRight = lineLineSegmentIntersection(intersectRight, point, slope, rMaxXY, vec2(rMaxXY.x, rMinXY.y));"," bool intersectsBottom = lineLineSegmentIntersection(intersectBottom, point, slope, rMinXY, vec2(rMaxXY.x, rMinXY.y));"," if (intersectsLeft) {"," if (firstIntersectFound) {"," iB = intersectLeft;"," }"," else {"," iA = intersectLeft;"," firstIntersectFound = true;"," }"," }"," if (intersectsTop) {"," if (firstIntersectFound) {"," iB = intersectTop;"," }"," else {"," iA = intersectTop;"," firstIntersectFound = true;"," }"," }"," if (intersectsRight) {"," if (firstIntersectFound) {"," iB = intersectRight;"," }"," else {"," iA = intersectRight;"," firstIntersectFound = true;"," }"," }"," if (intersectsBottom) {"," if (firstIntersectFound) {"," iB = intersectBottom;"," }"," else {"," iA = intersectBottom;"," }"," }","}"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.BlinnPhongSpecular=["//","// Author : Reza Ali","// License : Distributed under the MIT License.","//","","float blinnPhongSpecular( vec3 lightDirection, vec3 viewDirection, vec3 surfaceNormal, float shininess ) {",""," //Calculate Blinn-Phong power"," vec3 H = normalize(viewDirection + lightDirection);"," return pow(max(0.0, dot(surfaceNormal, H)), shininess);","}"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.Easing=["//","// Author : Reza Ali","// License : Distributed under the MIT License.","//","","float linear( float t, float b, float c, float d )","{"," return t * ( c / d ) + b;","}","","float linear( float t )","{"," return t;","}","","float inQuad( float t, float b, float c, float d )","{"," return c * ( t /= d ) * t + b;","}","","float inQuad( float t )","{"," return t * t;","}","","float outQuad( float t, float b, float c, float d )","{"," return -c * ( t /= d ) * ( t - 2.0 ) + b;","}","","float outQuad( float t )","{"," return - ( t -= 1.0 ) * t + 1.0;","}","","float inOutQuad( float t, float b, float c, float d )","{"," if( ( t /= d / 2.0 ) < 1.0 ) {"," return c / 2.0 * t * t + b;"," }"," return - c / 2.0 * ( ( --t ) * ( t - 2.0 ) - 1.0 ) + b;","}","","float inOutQuad( float t )","{"," if( ( t /= 0.5 ) < 1.0 ) return 0.5 * t * t;"," return -0.5 * ( ( --t ) * ( t-2 ) - 1 );","}","","float inCubic( float t, float b, float c, float d )","{"," return c * ( t /= d ) * t * t + b;","}","","float inCubic( float t )","{"," return t * t * t;","}","","float outCubic( float t, float b, float c, float d )","{"," return c * ( ( t = t/d - 1.0 ) * t * t + 1.0 ) + b;","}","","float outCubic( float t )","{"," return ( ( --t ) * t * t + 1.0 );","}","","float inOutCubic( float t, float b, float c, float d )","{"," if( ( t /= d / 2.0 ) < 1.0 ) return c / 2.0 * t * t * t + b;"," return c / 2.0 * ( ( t -= 2.0 ) * t * t + 2.0 ) + b;","}","","float inOutCubic( float t )","{"," if( ( t /= 0.5 ) < 1.0 ) return 0.5 * t * t * t;"," return 0.5 * ( ( t -= 2.0 ) * t * t + 2.0 );","}","","float inQuart( float t, float b, float c, float d )","{"," return c * ( t /= d ) * t * t * t + b;","}","","float inQuart( float t )","{"," return t * t * t * t;","}","","float outQuart( float t, float b, float c, float d )","{"," return -c * ( ( t = t/d - 1.0 ) * t * t * t - 1.0 ) + b;","}","","float outQuart( float t )","{"," return - ( ( --t ) * t * t * t - 1.0 );","}","","float inOutQuart( float t, float b, float c, float d )","{"," if ( ( t /= d / 2.0 ) < 1.0 ) return c / 2.0 * t * t * t * t + b;"," return -c / 2.0 * ( ( t -= 2.0 ) * t * t * t - 2.0 ) + b;","}","","float inOutQuart( float t )","{"," if ( (t /= 0.5 ) < 1.0 ) return 0.5 * t * t * t * t;"," return -0.5 * ( ( t -= 2.0 ) * t * t * t - 2.0 );","}","","float inQuint( float t, float b, float c, float d )","{"," return c * ( t /= d ) * t * t * t * t + b;","}","","float inQuint( float t )","{"," return t * t * t * t * t;","}","","float outQuint( float t, float b, float c, float d )","{"," return c * ( ( t = t/d - 1.0) * t * t * t * t + 1.0 ) + b;","}","","float outQuint( float t )","{"," return ( ( --t ) * t * t * t * t + 1.0 );","}","","float inOutQuint( float t, float b, float c, float d )","{"," if( ( t /= d /2.0 ) < 1.0 ) return c / 2.0 * t * t * t * t * t + b;"," return c / 2.0 * ( ( t -= 2.0 ) * t * t * t * t + 2.0) + b;","}","","float inOutQuint( float t )","{"," if ( ( t /= 0.5 ) < 1.0 ) return 0.5 * t * t * t * t * t;"," return 0.5 * ( ( t -= 2 ) * t * t * t * t + 2.0 );","}","","float inSine( float t, float b, float c, float d )","{"," return -c * cos( t / d * ( 1.5707963268 ) ) + c + b;","}","","float inSine( float t )","{"," return -1.0 * cos( t * ( 1.5707963268 ) ) + 1.0;","}","","float outSine( float t, float b, float c, float d )","{"," return c * sin( t / d * ( 1.5707963268 ) ) + b;","}","","float outSine( float t )","{"," return sin( t * ( 1.5707963268 ) );","}","","float inOutSine( float t, float b, float c, float d )","{"," return - c / 2.0 * ( cos( 3.1415926536 * t / d ) - 1.0 ) + b;","}","","float inOutSine( float t )","{"," return -0.5 * ( cos( 3.1415926536 * t ) - 1.0 );","}","","float inExpo( float t, float b, float c, float d )","{"," return ( t == 0.0 ) ? b : c * pow( 2.0, 10.0 * ( t / d - 1.0 ) ) + b;","}","","float inExpo( float t )","{"," return ( t == 0 ) ? 0.0 : pow( 2.0, 10.0 * ( t - 1.0 ) );","}","","float outExpo( float t, float b, float c, float d )","{"," return ( t == d ) ? b + c : c * ( - pow( 2.0, -10.0 * t / d ) + 1.0 ) + b;","}","","float outExpo( float t )","{"," return ( t == 1.0 ) ? 1.0 : ( - pow( 2.0, -10.0 * t ) + 1.0 );","}","","float inOutExpo( float t, float b, float c, float d )","{"," if( t == 0 ) return b;"," if( t == d ) return b + c;"," if(( t /= d / 2.0 ) < 1.0 ) return c / 2.0 * pow( 2.0, 10.0 * ( t - 1.0 ) ) + b;"," return c / 2.0 * ( - pow( 2.0, -10.0 * --t ) + 2.0 ) + b;","}","","float inOutExpo( float t )","{"," if( t == 0.0 ) return 0.0;"," if( t == 1.0 ) return 1.0;"," if( ( t /= 0.5 ) < 1.0 ) return 0.5 * pow( 2.0, 10.0 * ( t - 1.0 ) );"," return 0.5 * ( - pow( 2.0, -10.0 * --t ) + 2.0 );","}","","float inCirc( float t, float b, float c, float d )","{"," return -c * ( sqrt( 1.0 - (t/=d)*t) - 1) + b;","}","","float inCirc( float t )","{"," return - ( sqrt( 1.0 - t*t) - 1);","}","","float outCirc( float t, float b, float c, float d )","{"," return c * sqrt( 1.0 - (t=t/d-1)*t) + b;","}","","float outCirc( float t )","{"," return sqrt( 1.0 - (--t)*t);","}","","float inOutCirc( float t, float b, float c, float d )","{"," if ( ( t /= d / 2.0 ) < 1 ) return - c / 2.0 * ( sqrt( 1.0 - t * t ) - 1.0 ) + b;"," return c / 2.0 * ( sqrt( 1.0 - ( t -= 2.0 ) * t ) + 1.0 ) + b;","}","","float inOutCirc( float t )","{"," if( ( t /= 0.5 ) < 1.0 ) return -0.5 * ( sqrt( 1.0 - t * t ) - 1.0 );"," return 0.5 * ( sqrt( 1.0 - ( t -= 2.0 ) * t ) + 1.0 );","}","","float inElastic( float t, float b, float c, float d )","{"," float s = 1.70158; float p = 0.0; float a = c;"," if( t == 0 ) return b; if( ( t /= d ) == 1 ) return b + c;"," p = d * 0.3;"," if( a < abs( c ) ) { a = c; float s = p / 4.0; }"," else s = 0.1591549431 * p / ( 6.2831853072 ) * asin( c / a );"," return -( a * pow( 2.0, 10.0 * ( t -= 1.0 ) ) * sin( ( t * d - s ) * ( 6.2831853072 ) / p ) ) + b;","}","","float inElastic( float t )","{"," float s = 1.70158; float p = 0.0; float a = 1.0;"," if( t == 0.0 ) return 0.0;"," if( t == 1.0 ) return 1.0;"," p = 0.3;"," s = p / ( 6.2831853072 ) * asin( 1.0 / a );"," return -( a * pow( 2.0, 10.0 * ( t -= 1.0 ) ) * sin( ( t - s ) * ( 6.2831853072 ) / p ) );","}","","float outElastic( float t, float b, float c, float d )","{"," float s = 1.70158; float p = 0.0; float a = c;"," if( t == 0.0 ) return b;"," if( (t /= d ) == 1.0 ) return b + c;"," p = d * 0.3;"," if( a < abs( c ) ) { a = c; s = p / 4.0; }"," else { s = p / ( 6.2831853072 ) * asin( c / a ); }"," return a * pow( 2.0, -10.0 * t ) * sin( ( t * d - s ) * ( 6.2831853072 ) / p ) + c + b;","}","","float outElastic( float t )","{"," float s = 1.70158; float p = 0.0 ; float a = 1.0;"," if( t == 0.0 ) return 0.0; if( t == 1.0 ) return 1.0;"," p = 0.3;"," s = p / ( 6.2831853072 ) * asin( 1.0 / a );"," return a * pow( 2.0, -10.0 * t ) * sin( ( t - s ) * ( 6.2831853072 ) / p ) + 1.0;","}","","float inOutElastic( float t, float b, float c, float d )","{"," float s = 1.70158; float p = 0.0; float a = c;"," if( t == 0.0 ) return b;"," if( ( t /= d / 2.0 ) == 2.0 ) return b + c;"," p = d * ( 0.3 * 1.5 );"," if( a < abs( c ) ) { a = c; s = p / 4.0; }"," else { s = p / ( 6.2831853072 ) * asin( c / a ); }"," if( t < 1.0 ) return -0.5 * ( a * pow( 2.0, 10.0 * ( t -= 1.0 ) ) * sin( ( t * d - s ) * ( 6.2831853072 ) / p ) ) + b;"," return a * pow( 2.0, -10.0 * ( t -= 1.0 ) ) * sin( ( t * d - s ) * ( 6.2831853072 ) / p ) * 0.5 + c + b;","}","","float inOutElastic( float t )","{"," float s = 1.70158; float p = 0; float a = 1.0;"," if( t == 0 ) return 0.0;"," if( ( t /= 0.5 ) == 2.0 ) return 1.0;"," p = ( 0.3 * 1.5 );"," s = p / ( 6.2831853072 ) * asin( 1.0 / a );"," if( t < 1.0 ) return -0.5 * ( a * pow( 2.0, 10.0 * ( t -= 1.0 ) ) * sin( ( t - s ) * ( 6.2831853072 ) / p ) );"," return a * pow( 2.0, -10.0 * ( t -= 1.0 ) ) * sin( ( t - s ) * ( 6.2831853072 ) / p ) * 0.5 + 1.0;","}","","float inBack( float t, float b, float c, float d )","{"," float s = 1.70158;"," return c * ( t /= d ) * t * ( ( s + 1.0 ) * t - s ) + b;","}","","float inBack( float t )","{"," float s = 1.70158;"," return t * t * ( ( s + 1.0 ) * t - s);","}","","float outBack( float t, float b, float c, float d )","{"," float s = 1.70158;"," return c * ( ( t = t / d - 1.0 ) * t * ( ( s + 1.0 ) * t + s ) + 1.0 ) + b;","}","","float outBack( float t )","{"," float s = 1.70158;"," return ( ( --t ) * t * ( ( s + 1.0 ) * t + s ) + 1.0);","}","","float inOutBack( float t, float b, float c, float d )","{"," float s = 1.70158;"," if( ( t /= d / 2.0 ) < 1.0 ) return c / 2.0 * ( t * t * ( ( ( s *= 1.525 ) + 1.0 ) * t - s ) ) + b;"," return c / 2.0 * ( ( t -= 2.0 ) * t * ( ( ( s *= ( 1.525 ) ) + 1.0 ) * t + s ) + 2.0 ) + b;","}","","float inOutBack( float t )","{"," float s = 1.70158;"," if( ( t /= 0.5 ) < 1.0 ) return 0.5 * ( t * t * ( ( ( s *= 1.525 ) + 1.0 ) * t - s ) );"," return 0.5 * ( ( t -= 2 ) * t * ( ( ( s *= ( 1.525 ) ) + 1.0 ) * t + s ) + 2.0 );","}","","float outBounce( float t, float b, float c, float d )","{"," if( ( t /= d ) < ( 1.0 / 2.75 ) ) {"," return c * ( 7.5625 * t * t ) + b;"," } else if ( t < ( 2.0 / 2.75 ) ) {"," return c * ( 7.5625 * ( t -= ( 1.5 / 2.75 ) ) * t + 0.75 ) + b;"," } else if ( t < ( 2.5 / 2.75 ) ) {"," return c * ( 7.5625 * ( t -= ( 2.25 / 2.75 ) ) * t + 0.9375 ) + b;"," } else {"," return c * ( 7.5625 * ( t -= ( 2.625 / 2.75 ) ) * t + 0.984375 ) + b;"," }","}","","float outBounce( float t )","{"," if( t < ( 1.0 / 2.75 ) ) {"," return ( 7.5625 * t * t );"," } else if ( t < ( 2.0 / 2.75 ) ) {"," return ( 7.5625 * ( t-= ( 1.5 / 2.75 ) ) * t + .75 );"," } else if ( t < ( 2.5 / 2.75 ) ) {"," return ( 7.5625 * ( t -= ( 2.25 / 2.75 ) ) * t + 0.9375 );"," } else {"," return ( 7.5625 * ( t -= ( 2.625 / 2.75 ) ) * t + 0.984375 );"," }","}","","float inBounce( float t, float b, float c, float d )","{"," return c - outBounce( d - t, 0.0, c, d ) + b;","}","","float inBounce( float t )","{"," return 1.0 - outBounce( 1.0 - t);","}","","float inOutBounce( float t, float b, float c, float d )","{"," if ( t < d /2.0 ) return inBounce ( t * 2.0, 0.0, c, d ) * 0.5 + b;"," return outBounce ( t * 2.0 - d, 0, c, d ) * 0.5 + c * 0.5 + b;","}","","float inOutBounce( float t )","{"," if ( t < 0.5 ) return inBounce( t * 2.0 ) * 0.5;"," return outBounce( t * 2.0 - 1.0 ) * 0.5 + 0.5;","}"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.Gamma=["//","// Author : Reza Ali","// License : Distributed under the MIT License.","//","","const vec3 cGammaCorrection = vec3( 0.4545454545 );","","vec3 gamma( in vec3 color )","{"," return pow( color, cGammaCorrection );","}","","vec4 gamma( in vec4 color )","{"," return vec4( gamma( color.rgb ), color.a );","}"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.Map=["//","// Author : Reza Ali","// License : Distributed under the MIT License.","//","","float map( float value, float inMin, float inMax, float outMin, float outMax )","{"," return ( (value - inMin) / ( inMax - inMin ) * ( outMax - outMin ) ) + outMin;","}"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.Noise=["//","// Author : Patricio Gonzalez Vivo and Jen Lowe","// License : Distributed under the MIT License.","// Source : https://github.com/patriciogonzalezvivo/thebookofshaders","//","float random (in float _x) {"," return fract(sin(_x)*1e4);","}","","float random (in vec2 co) {"," return fract(sin(dot(co.xy,vec2(12.9898,78.233)))*43758.5453);","}","","float noise (in float _x) {"," float i = floor(_x);"," float f = fract(_x);"," float u = f * f * (3.0 - 2.0 * f);"," return mix(random(i), random(i + 1.0), u);","}","","float noise (in vec2 _st) {"," vec2 i = floor(_st);"," vec2 f = fract(_st);"," // Four corners in 2D of a tile"," float a = random(i);"," float b = random(i + vec2(1.0, 0.0));"," float c = random(i + vec2(0.0, 1.0));"," float d = random(i + vec2(1.0, 1.0));"," vec2 u = f * f * (3.0 - 2.0 * f);"," return mix(a, b, u.x) + "," (c - a)* u.y * (1.0 - u.x) + "," (d - b) * u.x * u.y;","}"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.Noise2D=["//","// Description : Array and textureless GLSL 2D simplex noise function.","// Author : Ian McEwan, Ashima Arts.","// Maintainer : ijm","// Lastmod : 20110822 (ijm)","// License : Copyright (C) 2011 Ashima Arts. All rights reserved.","// Distributed under the MIT License. See LICENSE file.","// https://github.com/ashima/webgl-noise","//","","vec2 n2mod289(vec2 x) {"," return x - floor(x * (1.0 / 289.0)) * 289.0;","}","","vec3 n2mod289(vec3 x) {"," return x - floor(x * (1.0 / 289.0)) * 289.0;","}","","vec4 n2mod289(vec4 x) {"," return x - floor(x * (1.0 / 289.0)) * 289.0;","}","","vec3 permute(vec3 x) {"," return n2mod289(((x*34.0)+1.0)*x);","}","","float snoise(vec2 v)"," {"," const vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0"," 0.366025403784439, // 0.5*(sqrt(3.0)-1.0)"," -0.577350269189626, // -1.0 + 2.0 * C.x"," 0.024390243902439); // 1.0 / 41.0","// First corner"," vec2 i = floor(v + dot(v, C.yy) );"," vec2 x0 = v - i + dot(i, C.xx);","","// Other corners"," vec2 i1;"," //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0"," //i1.y = 1.0 - i1.x;"," i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);"," // x0 = x0 - 0.0 + 0.0 * C.xx ;"," // x1 = x0 - i1 + 1.0 * C.xx ;"," // x2 = x0 - 1.0 + 2.0 * C.xx ;"," vec4 x12 = x0.xyxy + C.xxzz;"," x12.xy -= i1;","","// Permutations"," i = n2mod289(i); // Avoid truncation effects in permutation"," vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 ))"," + i.x + vec3(0.0, i1.x, 1.0 ));",""," vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0);"," m = m*m ;"," m = m*m ;","","// Gradients: 41 points uniformly over a line, mapped onto a diamond.","// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)",""," vec3 x = 2.0 * fract(p * C.www) - 1.0;"," vec3 h = abs(x) - 0.5;"," vec3 ox = floor(x + 0.5);"," vec3 a0 = x - ox;","","// Normalise gradients implicitly by scaling m","// Approximation of: m *= inversesqrt( a0*a0 + h*h );"," m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h );","","// Compute final noise value at P"," vec3 g;"," g.x = a0.x * x0.x + h.x * x0.y;"," g.yz = a0.yz * x12.xz + h.yz * x12.yw;"," return 130.0 * dot(m, g);","}"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.Noise3D=["//","// Description : Array and textureless GLSL 2D/3D/4D simplex","// noise functions.","// Author : Ian McEwan, Ashima Arts.","// Maintainer : ijm","// Lastmod : 20110822 (ijm)","// License : Copyright (C) 2011 Ashima Arts. All rights reserved.","// Distributed under the MIT License. See LICENSE file.","// https://github.com/ashima/webgl-noise","//","","vec2 n3mod289(vec2 x) {"," return x - floor(x * (1.0 / 289.0)) * 289.0;","}","","vec3 n3mod289(vec3 x) {"," return x - floor(x * (1.0 / 289.0)) * 289.0;","}","","vec4 n3mod289(vec4 x) {"," return x - floor(x * (1.0 / 289.0)) * 289.0;","}","","vec4 permute(vec4 x) {"," return n3mod289(((x*34.0)+1.0)*x);","}","","vec4 taylorInvSqrt(vec4 r)","{"," return 1.79284291400159 - 0.85373472095314 * r;","}","","float snoise(vec3 v)"," {"," const vec2 C = vec2(1.0/6.0, 1.0/3.0) ;"," const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);","","// First corner"," vec3 i = floor(v + dot(v, C.yyy) );"," vec3 x0 = v - i + dot(i, C.xxx) ;","","// Other corners"," vec3 g = step(x0.yzx, x0.xyz);"," vec3 l = 1.0 - g;"," vec3 i1 = min( g.xyz, l.zxy );"," vec3 i2 = max( g.xyz, l.zxy );",""," // x0 = x0 - 0.0 + 0.0 * C.xxx;"," // x1 = x0 - i1 + 1.0 * C.xxx;"," // x2 = x0 - i2 + 2.0 * C.xxx;"," // x3 = x0 - 1.0 + 3.0 * C.xxx;"," vec3 x1 = x0 - i1 + C.xxx;"," vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y"," vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y","","// Permutations"," i = n3mod289(i);"," vec4 p = permute( permute( permute("," i.z + vec4(0.0, i1.z, i2.z, 1.0 ))"," + i.y + vec4(0.0, i1.y, i2.y, 1.0 ))"," + i.x + vec4(0.0, i1.x, i2.x, 1.0 ));","","// Gradients: 7x7 points over a square, mapped onto an octahedron.","// The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)"," float n_ = 0.142857142857; // 1.0/7.0"," vec3 ns = n_ * D.wyz - D.xzx;",""," vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7)",""," vec4 x_ = floor(j * ns.z);"," vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)",""," vec4 x = x_ *ns.x + ns.yyyy;"," vec4 y = y_ *ns.x + ns.yyyy;"," vec4 h = 1.0 - abs(x) - abs(y);",""," vec4 b0 = vec4( x.xy, y.xy );"," vec4 b1 = vec4( x.zw, y.zw );",""," //vec4 s0 = vec4(lessThan(b0,0.0))*2.0 - 1.0;"," //vec4 s1 = vec4(lessThan(b1,0.0))*2.0 - 1.0;"," vec4 s0 = floor(b0)*2.0 + 1.0;"," vec4 s1 = floor(b1)*2.0 + 1.0;"," vec4 sh = -step(h, vec4(0.0));",""," vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;"," vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;",""," vec3 p0 = vec3(a0.xy,h.x);"," vec3 p1 = vec3(a0.zw,h.y);"," vec3 p2 = vec3(a1.xy,h.z);"," vec3 p3 = vec3(a1.zw,h.w);","","//Normalise gradients"," vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));"," p0 *= norm.x;"," p1 *= norm.y;"," p2 *= norm.z;"," p3 *= norm.w;","","// Mix final noise value"," vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);"," m = m * m;"," return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),"," dot(p2,x2), dot(p3,x3) ) );"," }"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.Noise4D=["//","// Description : Array and textureless GLSL 2D/3D/4D simplex","// noise functions.","// Author : Ian McEwan, Ashima Arts.","// Maintainer : ijm","// Lastmod : 20110822 (ijm)","// License : Copyright (C) 2011 Ashima Arts. All rights reserved.","// Distributed under the MIT License. See LICENSE file.","// https://github.com/ashima/webgl-noise","//","","vec4 mod289(vec4 x) {"," return x - floor(x * (1.0 / 289.0)) * 289.0; }","","float mod289(float x) {"," return x - floor(x * (1.0 / 289.0)) * 289.0; }","","vec4 permute(vec4 x) {"," return mod289(((x*34.0)+1.0)*x);","}","","float permute(float x) {"," return mod289(((x*34.0)+1.0)*x);","}","","vec4 taylorInvSqrt(vec4 r)","{"," return 1.79284291400159 - 0.85373472095314 * r;","}","","float taylorInvSqrt(float r)","{"," return 1.79284291400159 - 0.85373472095314 * r;","}","","vec4 grad4(float j, vec4 ip)"," {"," const vec4 ones = vec4(1.0, 1.0, 1.0, -1.0);"," vec4 p,s;",""," p.xyz = floor( fract (vec3(j) * ip.xyz) * 7.0) * ip.z - 1.0;"," p.w = 1.5 - dot(abs(p.xyz), ones.xyz);"," s = vec4(lessThan(p, vec4(0.0)));"," p.xyz = p.xyz + (s.xyz*2.0 - 1.0) * s.www;",""," return p;"," }","","// (sqrt(5) - 1)/4 = F4, used once below","#define F4 0.309016994374947451","","float snoise(vec4 v)"," {"," const vec4 C = vec4( 0.138196601125011, // (5 - sqrt(5))/20 G4"," 0.276393202250021, // 2 * G4"," 0.414589803375032, // 3 * G4"," -0.447213595499958); // -1 + 4 * G4","","// First corner"," vec4 i = floor(v + dot(v, vec4(F4)) );"," vec4 x0 = v - i + dot(i, C.xxxx);","","// Other corners","","// Rank sorting originally contributed by Bill Licea-Kane, AMD (formerly ATI)"," vec4 i0;"," vec3 isX = step( x0.yzw, x0.xxx );"," vec3 isYZ = step( x0.zww, x0.yyz );","// i0.x = dot( isX, vec3( 1.0 ) );"," i0.x = isX.x + isX.y + isX.z;"," i0.yzw = 1.0 - isX;","// i0.y += dot( isYZ.xy, vec2( 1.0 ) );"," i0.y += isYZ.x + isYZ.y;"," i0.zw += 1.0 - isYZ.xy;"," i0.z += isYZ.z;"," i0.w += 1.0 - isYZ.z;",""," // i0 now contains the unique values 0,1,2,3 in each channel"," vec4 i3 = clamp( i0, 0.0, 1.0 );"," vec4 i2 = clamp( i0-1.0, 0.0, 1.0 );"," vec4 i1 = clamp( i0-2.0, 0.0, 1.0 );",""," // x0 = x0 - 0.0 + 0.0 * C.xxxx"," // x1 = x0 - i1 + 1.0 * C.xxxx"," // x2 = x0 - i2 + 2.0 * C.xxxx"," // x3 = x0 - i3 + 3.0 * C.xxxx"," // x4 = x0 - 1.0 + 4.0 * C.xxxx"," vec4 x1 = x0 - i1 + C.xxxx;"," vec4 x2 = x0 - i2 + C.yyyy;"," vec4 x3 = x0 - i3 + C.zzzz;"," vec4 x4 = x0 + C.wwww;","","// Permutations"," i = mod289(i);"," float j0 = permute( permute( permute( permute(i.w) + i.z) + i.y) + i.x);"," vec4 j1 = permute( permute( permute( permute ("," i.w + vec4(i1.w, i2.w, i3.w, 1.0 ))"," + i.z + vec4(i1.z, i2.z, i3.z, 1.0 ))"," + i.y + vec4(i1.y, i2.y, i3.y, 1.0 ))"," + i.x + vec4(i1.x, i2.x, i3.x, 1.0 ));","","// Gradients: 7x7x6 points over a cube, mapped onto a 4-cross polytope","// 7*7*6 = 294, which is close to the ring size 17*17 = 289."," vec4 ip = vec4(1.0/294.0, 1.0/49.0, 1.0/7.0, 0.0) ;",""," vec4 p0 = grad4(j0, ip);"," vec4 p1 = grad4(j1.x, ip);"," vec4 p2 = grad4(j1.y, ip);"," vec4 p3 = grad4(j1.z, ip);"," vec4 p4 = grad4(j1.w, ip);","","// Normalise gradients"," vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));"," p0 *= norm.x;"," p1 *= norm.y;"," p2 *= norm.z;"," p3 *= norm.w;"," p4 *= taylorInvSqrt(dot(p4,p4));","","// Mix contributions from the five corners"," vec3 m0 = max(0.6 - vec3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0);"," vec2 m1 = max(0.6 - vec2(dot(x3,x3), dot(x4,x4) ), 0.0);"," m0 = m0 * m0;"," m1 = m1 * m1;"," return 49.0 * ( dot(m0*m0, vec3( dot( p0, x0 ), dot( p1, x1 ), dot( p2, x2 )))"," + dot(m1*m1, vec2( dot( p3, x3 ), dot( p4, x4 ) ) ) ) ;",""," }"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.PI=["//","// Author : Reza Ali","// License : Distributed under the MIT License.","//","","#define TWO_PI 6.2831853072","#define PI 3.14159265359","#define HALF_PI 1.57079632679"].join("\n")}(this.Blotter,this._),function(a,b){a.Assets.Shaders.Random=["//","// Author : Patricio Gonzalez Vivo and Jen Lowe","// License : Distributed under the MIT License.","// Source : https://github.com/patriciogonzalezvivo/thebookofshaders","//","","float random (in float _x) {"," return fract(sin(_x)*1e4);","}","","float random (in vec2 co) {"," return fract(sin(dot(co.xy,vec2(12.9898,78.233)))*43758.5453);","}"].join("\n")}(this.Blotter,this._),function(a,b){a.Mapping=function(a,b,c,d){this.texts=a,this._textBounds=b,this._width=c,this._height=d,this._ratio=1},a.Mapping.prototype=function(){function c(b,c){return c=c||a.TextUtils.ensurePropertyValues().leading,isNaN(c)?-1!==c.toString().indexOf("px")?c=parseInt(c):-1!==c.toString().indexOf("%")&&(c=parseInt(c)/100*b):c*=b,c}return{constructor:a.Mapping,get ratio(){return this._ratio},set ratio(a){this._ratio=a||1},get width(){return this._width*this._ratio},get height(){return this._height*this._ratio},boundsForText:function(b){a.Messaging.ensureInstanceOf(b,a.Text,"Blotter.Text","Blotter.Mapping","boundsForText");var c=this._textBounds[b.id];return c&&(c={w:c.w*this._ratio,h:c.h*this._ratio,x:c.x*this._ratio,y:c.y*this._ratio}),c},toCanvas:function(d){var e=a.CanvasUtils.hiDpiCanvas(this._width,this._height,this._ratio),f=e.getContext("2d",{alpha:!1}),g=new Image;f.textBaseline="middle";for(var h=0;h<this.texts.length;h++){var i=this.texts[h],j=this._textBounds[i.id],k=c.call(this,i.properties.size,i.properties.leading)/2;f.font=i.properties.style+" "+i.properties.weight+" "+i.properties.size+"px "+i.properties.family,f.save(),f.translate(j.x+i.properties.paddingLeft,this._height-(j.y+j.h)+i.properties.paddingTop),f.fillStyle=i.properties.fill,f.fillText(i.value,0,Math.round(k)),f.restore()}g.onload=b.bind(function(){f.save(),f.scale(1,-1),f.clearRect(0,-1*this._height,this._width,this._height),f.drawImage(g,0,-1*this._height,this._width,this._height),f.restore(),d(e)},this),g.src=e.toDataURL("image/png")}}}()}(this.Blotter,this._),function(a,b,c){a.MappingMaterial=function(a,b,c,d){this.mapping=a,this.material=b,this.shaderMaterial=c,this._userUniformDataTextureObjects=d,this.init.apply(this,arguments)},a.MappingMaterial.prototype=function(){function d(a,b,c,d){var e=d.type;"1f"==e?(c[4*b]=a,c[4*b+1]=0,c[4*b+2]=0,c[4*b+3]=0):"2f"==e?(c[4*b]=a[0],c[4*b+1]=a[1],c[4*b+2]=0,c[4*b+3]=0):"3f"==e?(c[4*b]=a[0],c[4*b+1]=a[1],c[4*b+2]=a[2],c[4*b+3]=0):"4f"==e?(c[4*b]=a[0],c[4*b+1]=a[1],c[4*b+2]=a[2],c[4*b+3]=a[3]):(c[4*b]=0,c[4*b+1]=0,c[4*b+2]=0,c[4*b+3]=0)}function e(d){var e={_type:d.userUniform.type,_value:d.userUniform.value,get value(){return this._value},set value(b){if(!a.UniformUtils.validValueForUniformType(this._type,b))return void a.Messaging.logError("Blotter.MappingMaterial",!1,"uniform value not valid for uniform type: "+this._type);this._value=b,this.trigger("update")}};return b.extend(e,c.prototype),e}function f(a,c){return b.reduce(a.texts,function(a,f,g){return a[f.id]=b.reduce(c.userUniforms,function(a,b,f){var h=b.position+g;return a[f]=e(b),a[f].on("update",function(){d(a[f].value,h,c.data,b.userUniform),c.texture.needsUpdate=!0}),a[f].value=b.userUniform.value,a},{}),a},{})}function g(a,c,d){return b.reduce(c.userUniforms,function(f,g,h){return f[h]=e(g),f[h].on("update",function(){b.each(a.texts,function(a){d[a.id][h].value=f[h].value}),c.texture.needsUpdate=!0}),f},{})}return{constructor:a.MappingMaterial,get uniforms(){return this.material.uniforms},get mainImage(){return this.material.mainImage},get width(){return this.mapping.width},get height(){return this.mapping.height},get ratio(){return this.mapping.ratio},init:function(a,b,c,d){this.textUniformInterface=f(this.mapping,this._userUniformDataTextureObjects),this.uniformInterface=g(this.mapping,this._userUniformDataTextureObjects,this.textUniformInterface)},boundsForText:function(b){return a.Messaging.ensureInstanceOf(b,a.Text,"Blotter.Text","Blotter.MappingMaterial","boundsForText"),this.mapping.boundsForText(b)}}}()}(this.Blotter,this._,this.EventEmitter),function(a,b,c){a.Material=function(){this.init.apply(this,arguments)},a.Material.prototype=function(){function d(){return["void mainImage( out vec4 mainImage, in vec2 fragCoord ) {","mainImage = textTexture(fragCoord / uResolution);","}"].join("\n")}function e(d){var e={_type:d.type,_value:d.value,get type(){return this._type},set type(a){this._type=a},get value(){return this._value},set value(b){if(!a.UniformUtils.validValueForUniformType(this._type,b))return void a.Messaging.logError("Blotter.Material",!1,"uniform value not valid for uniform type: "+this._type);this._value=b,this.trigger("update")}};return b.extend(e,c.prototype),e}function f(a){return b.reduce(a,b.bind(function(a,c,d){return a[d]=e(c),a[d].on("update",b.bind(function(){this.trigger("update:uniform",[d])},this)),a},this),{})}return{constructor:a.Material,get needsUpdate(){},set needsUpdate(a){!0===a&&this.trigger("update")},get mainImage(){return this._mainImage},set mainImage(a){this._mainImage=a||d()},get uniforms(){return this._uniforms},set uniforms(c){this._uniforms=f.call(this,a.UniformUtils.extractValidUniforms(b.extend(c,a.UniformUtils.defaultUniforms)))},init:function(){this.mainImage=d(),this.uniforms={}}}}(),a._extendWithGettersSetters(a.Material.prototype,c.prototype)}(this.Blotter,this._,this.EventEmitter),function(a,b){a.ShaderMaterial=function(b,c){a.Material.apply(this,arguments)},a.ShaderMaterial.prototype=Object.create(a.Material.prototype),a._extendWithGettersSetters(a.ShaderMaterial.prototype,function(){return{constructor:a.ShaderMaterial,init:function(a,c){b.defaults(this,c),this.mainImage=a}}}())}(this.Blotter,this._),function(a,b,c){a.RenderScope=function(b,c){this.text=b,this.blotter=c,this.material={mainImage:this.blotter.material.mainImage},this._mappingMaterial=c.mappingMaterial,this.playing=this.blotter.autoplay,this.timeDelta=0,this.lastDrawTime=!1,this.frameCount=0,this.domElement=a.CanvasUtils.hiDpiCanvas(0,0,this.blotter.ratio,{class:"b-canvas",html:b.value}),this.context=this.domElement.getContext("2d")},a.RenderScope.prototype=function(){function d(){function b(b){c.domElement.addEventListener(b,function(d){var e=a.CanvasUtils.normalizedMousePosition(c.domElement,d);c.emit(b,e)},!1)}for(var c=this,d=["mousedown","mouseup","mousemove","mouseenter","mouseleave"],e=0;e<d.length;e++){b(d[e])}}function e(a,b){var c=a.boundsForText(b);if(c)return{w:c.w,h:c.h,x:-1*Math.floor(c.x),y:-1*Math.floor(a.height-(c.y+c.h))}}function f(a,c){b.each(a,function(a,b){var d=c[b];if(d){var e=d.type==a.type,f=d.value==a.value;e&&!f&&(d.value=a.value)}})}function g(d){var e={_type:d.type,_value:d.value,get type(){return this._type},set type(b){a.Messaging.logError("Blotter.RenderScope",!1,"uniform types may not be updated through a text scope")},get value(){return this._value},set value(b){if(!a.UniformUtils.validValueForUniformType(this._type,b))return void a.Messaging.logError("Blotter.RenderScope",!1,"uniform value not valid for uniform type: "+this._type);this._value=b,this.trigger("update")}};return b.extend(e,c.prototype),e}function h(a){return b.reduce(a,b.bind(function(a,c,d){return a[d]=g(c),a[d].on("update",b.bind(function(){this.trigger("update:uniform",[d])},this)),a},this),{})}function i(){var b=this._mappingMaterial,c=b&&e(b,this.text),d=this.material.uniforms;b&&c&&(a.CanvasUtils.updateCanvasSize(this.domElement,c.w/this.blotter.ratio,c.h/this.blotter.ratio,this.blotter.ratio),this.domElement.innerHTML=this.text.value,this.bounds=c,this.material.uniforms=h.call(this,b.uniforms),this.material.mainImage=b.mainImage,d&&f(d,this.material.uniforms),this.trigger(this.lastUpdated?"update":"ready"),this.lastUpdated=Date.now())}return{constructor:a.RenderScope,get needsUpdate(){},set needsUpdate(a){!0===a&&i.call(this)},get mappingMaterial(){},set mappingMaterial(a){this._mappingMaterial=a},play:function(){this.playing=!0},pause:function(){this.playing=!1},render:function(){if(this.bounds){var a=Date.now();this.frameCount+=1,this.timeDelta=(a-(this.lastDrawTime||a))/1e3,this.lastDrawTime=a,this.context.clearRect(0,0,this.domElement.width,this.domElement.height),this.context.putImageData(this.blotter.imageData,this.bounds.x,this.bounds.y),this.trigger("render",[this.frameCount])}},appendTo:function(a){return"function"==typeof a.append?a.append(this.domElement):a.appendChild(this.domElement),d.call(this),this}}}(),a._extendWithGettersSetters(a.RenderScope.prototype,c.prototype)}(this.Blotter,this._,this.EventEmitter),function(a,b,c,d){var e=this;a.Renderer=function(){this._currentAnimationLoop=!1,this._scene=new c.Scene,this._plane=new c.PlaneGeometry(1,1),this._material=new c.MeshBasicMaterial,this._mesh=new c.Mesh(this._plane,this._material),this._scene.add(this._mesh),this._camera=new c.OrthographicCamera(.5,.5,.5,.5,0,100),this.init.apply(this,arguments)},a.Renderer.prototype=function(){function d(a,b){var d=new c.WebGLRenderTarget(a,b,{minFilter:c.LinearFilter,magFilter:c.LinearFilter,format:c.RGBAFormat,type:c.UnsignedByteType});return d.texture.generateMipmaps=!1,d.width=a,d.height=b,d}function f(){a.webglRenderer.render(this._scene,this._camera,this._renderTarget),a.webglRenderer.readRenderTargetPixels(this._renderTarget,0,0,this._renderTarget.width,this._renderTarget.height,this._imageDataArray),this.trigger("render"),this._currentAnimationLoop=e.requestAnimationFrame(b.bind(f,this))}return{constructor:a.Renderer,get material(){},set material(a){a instanceof c.Material&&(this._material=a,this._mesh.material=a)},get width(){return this._width},set width(a){this.setSize(a,this._height)},get height(){return this._height},set height(a){this.setSize(this._width,a)},init:function(){this.setSize(1,1)},start:function(){this._currentAnimationLoop||f.call(this)},stop:function(){this._currentAnimationLoop&&(e.cancelAnimationFrame(this._currentAnimationLoop),this._currentAnimationLoop=void 0)},setSize:function(a,b){this._width=a||1,this._height=b||1,this._mesh.scale.set(this._width,this._height,1),this._camera.left=this._width/-2,this._camera.right=this._width/2,this._camera.top=this._height/2,this._camera.bottom=this._height/-2,this._camera.updateProjectionMatrix(),this._renderTarget=d(this._width,this._height),this._viewBuffer=new ArrayBuffer(this._width*this._height*4),this._imageDataArray=new Uint8Array(this._viewBuffer),this._clampedImageDataArray=new Uint8ClampedArray(this._viewBuffer),this.imageData=new ImageData(this._clampedImageDataArray,this._width,this._height)},teardown:function(){this.stop()}}}(),a._extendWithGettersSetters(a.Renderer.prototype,d.prototype)}(this.Blotter,this._,this.THREE,this.EventEmitter),function(a,b,c,d){a.BoundsDataTextureBuilder=function(){function a(a){for(var b=a.texts,c=new Float32Array(4*b.length),d=0;d<b.length;d++){var e=b[d],f=a.boundsForText(e);c[4*d]=f.x,c[4*d+1]=a.height-(f.y+f.h),c[4*d+2]=f.w,c[4*d+3]=f.h}return c}return{build:function(b,e){d(function(){var d=a(b),f=new c.DataTexture(d,b.texts.length,1,c.RGBAFormat,c.FloatType);f.needsUpdate=!0,e(f)})}}}()}(this.Blotter,this._,this.THREE,this.setImmediate),function(a,b,c,d){a.IndicesDataTextureBuilder=function(){function a(a,b,c,d){for(var e=a.ratio,f=new Float32Array(c*b*4),g=b%1,h=1/a.texts.length/2,i=1;i<f.length/4;i++){for(var j=Math.ceil(i/(b-g)),k=i-(b-g)*(j-1),l=0,m=0,n=0,o=0;o<a.texts.length;o++){var p=a.texts[o],q=a.boundsForText(p),r=q.w/e*d,s=q.h/e*d,t=q.x/e*d,u=q.y/e*d;if(j>=u&&j<=u+s&&k>=t&&k<=t+r){l=o/a.texts.length+h,n=1;break}}var v=i-1;f[4*v+0]=l,f[4*v+1]=m,f[4*v+2]=m,f[4*v+3]=n}return f}return{build:function(b,e){var f=.5;d(function(){var d=b.width/b.ratio*f,g=b.height/b.ratio*f,h=a(b,d,g,f),i=new c.DataTexture(h,d,g,c.RGBAFormat,c.FloatType);i.flipY=!0,i.needsUpdate=!0,e(i)})}}}()}(this.Blotter,this._,this.THREE,this.setImmediate),function(a,b,c){a.TextTextureBuilder=function(){return{build:function(a,d){var e,f=new c.TextureLoader;a.toCanvas(b.bind(function(a){e=a.toDataURL(),f.load(e,b.bind(function(a){a.minFilter=c.LinearFilter,a.magFilter=c.LinearFilter,a.generateMipmaps=!0,a.needsUpdate=!0,d(a)},this))},this))}}}()}(this.Blotter,this._,this.THREE),function(a,b,c,d,e){a.MappingBuilder=function(){function c(a,b){var c=a.w*a.h;return b.w*b.h-c}function f(c){return b.reduce(c,function(b,c){var d=a.TextUtils.sizeForText(c.value,c.properties);return b[c.id]=d,b},[])}return{build:function(b,g){e(function(){var e=a.TextUtils.filterTexts(b),h=f(e),i=new d,j=[],k={};for(var l in h)if(h.hasOwnProperty(l)){var m=h[l];m.referenceId=l,j.push(m)}i.fit(j.sort(c));for(var n=0;n<j.length;n++){var o=j[n];k[o.referenceId]={w:o.w,h:o.h,x:o.fit.x,y:i.root.h-(o.fit.y+o.h)}}g(new a.Mapping(e,k,i.root.w,i.root.h))})}}}()}(this.Blotter,this._,this.THREE,this.GrowingPacker,this.setImmediate),function(a,b,c){a.MappingMaterialBuilder=function(){function d(){return["varying vec2 _vTexCoord;","void main() {"," _vTexCoord = uv;"," gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);","}"].join("\n")}function e(c,d,e){var f,g={publicUniformDeclarations:"",publicUniformDefinitions:""},h=(1/c.data.length/2).toFixed(20),i=c.texture.image.width.toFixed(1);return b.reduce(c.userUniforms,function(b,c,e){var f=a.UniformUtils.fullSwizzleStringForUniformType(c.userUniform.type),g=a.UniformUtils.glslDataTypeForUniformType(c.userUniform.type),j="(("+c.position.toFixed(1)+" + ((textIndex - ((1.0 / "+d.toFixed(1)+") / 2.0)) * "+d.toFixed(1)+")) / "+i+") + "+h;return b.publicUniformDeclarations+=g+" "+e+";\n",b.publicUniformDefinitions+=" "+e+" = texture2D(_userUniformsTexture, vec2("+j+", 0.5))."+f+";\n",b},g),f=[a.Assets.Shaders.Blending,a.Assets.Shaders.TextTexture,"uniform sampler2D _uSampler;","uniform vec2 _uCanvasResolution;","uniform sampler2D _uTextIndicesTexture;","uniform sampler2D _uTextBoundsTexture;","varying vec2 _vTexCoord;","vec4 _textBounds;","uniform sampler2D _userUniformsTexture;",g.publicUniformDeclarations,"// Helper function used by user programs to retrieve texel color information within the bounds of","// any given text. This is to be used instead of `texture2D` in the fragment sources for all Blotter materials.","vec4 textTexture(vec2 coord) {"," vec2 adjustedFragCoord = _textBounds.xy + vec2((_textBounds.z * coord.x), (_textBounds.w * coord.y));"," vec2 uv = adjustedFragCoord.xy / _uCanvasResolution;"," // If adjustedFragCoord falls outside the bounds of the current texel's text, return `vec4(0.0)`."," if (adjustedFragCoord.x < _textBounds.x ||"," adjustedFragCoord.x > _textBounds.x + _textBounds.z ||"," adjustedFragCoord.y < _textBounds.y ||"," adjustedFragCoord.y > _textBounds.y + _textBounds.w) {"," return vec4(0.0);"," }"," return texture2D(_uSampler, uv);","}","void mainImage(out vec4 mainImage, in vec2 fragCoord);",e,"void main(void) {"," vec4 textIndexData = texture2D(_uTextIndicesTexture, _vTexCoord);"," float textIndex = textIndexData.r;"," float textAlpha = textIndexData.a;"," _textBounds = texture2D(_uTextBoundsTexture, vec2(textIndex, 0.5));",g.publicUniformDefinitions," uResolution = _textBounds.zw;"," vec2 fragCoord = gl_FragCoord.xy - _textBounds.xy;"," vec4 outColor;"," mainImage(outColor, fragCoord);"," outColor.a = outColor.a * textAlpha;"," gl_FragColor = outColor;","}"],f.join("\n")}function f(b,c){a.TextTextureBuilder.build(b,function(a){c(a)})}function g(c,d){var e,f,g,h=[];e=function(){return function(b){a.IndicesDataTextureBuilder.build(c,function(a){h.push({uniformName:"_uTextIndicesTexture",texture:a}),b()})}},f=function(){return function(b){a.BoundsDataTextureBuilder.build(c,function(a){h.push({uniformName:"_uTextBoundsTexture",texture:a}),b()})}},g=[e(),f()],b(g).reduceRight(b.wrap,function(){d(h)})()}function h(d,e,f){a.UniformUtils.ensureHasRequiredDefaultUniforms(d,"Blotter.MappingMaterialBuilder","_buildUserUniformDataTextureObjects"),d=a.UniformUtils.extractValidUniforms(d);var g=Object.keys(d).length*e,h=new Float32Array(4*g),i=new c.DataTexture(h,g,1,c.RGBAFormat,c.FloatType),j={data:h,texture:i,userUniforms:{}};b.reduce(d,function(a,b,c){var f=Object.keys(d).indexOf(c)*e;return a.userUniforms[c]={userUniform:b,position:f},a},j),f(j)}function i(a){return b.reduce(a,function(a,b){return a[b.uniformName]={type:"t",value:b.texture},a},{})}function j(a){return{_userUniformsTexture:{type:"t",value:a.texture}}}function k(a,c,d,e,f){var g={_uSampler:{type:"t",value:d},_uCanvasResolution:{type:"2f",value:[a,c]}};return b.extend(g,i(e)),b.extend(g,j(f)),g}function l(a,b,d){var e=new c.ShaderMaterial({vertexShader:a,fragmentShader:b,uniforms:d});return e.depthTest=!1,e.depthWrite=!1,e.premultipliedAlpha=!1,e}return{build:function(c,i,j){var m,n,o,p,q;m=function(){return function(a){f(c,function(b){o=b,a()})}},n=function(){return function(a){g(c,function(b){p=b,a()})}},buildUserUniformDataTextureObjects=function(){return function(a){h(i.uniforms,c.texts.length,function(b){userUniformDataTextureObjects=b,a()})}},q=[m(),n(),buildUserUniformDataTextureObjects()],b(q).reduceRight(b.wrap,function(){var f=k(c.width,c.height,o,p,userUniformDataTextureObjects),g=(b.omit(f,"_uCanvasResolution","_uSampler","_uTextBoundsTexture","_uTextIndicesTexture"),l(d(),e(userUniformDataTextureObjects,c.texts.length,i.mainImage),f));j(new a.MappingMaterial(c,i,g,userUniformDataTextureObjects))})()}}}()}(this.Blotter,this._,this.THREE);
(function(Blotter) {
Blotter.LiquidDistortMaterial = function() {
Blotter.Material.apply(this, arguments);
};
Blotter.LiquidDistortMaterial.prototype = Object.create(Blotter.Material.prototype);
Blotter._extendWithGettersSetters(Blotter.LiquidDistortMaterial.prototype, (function () {
function _mainImageSrc () {
var mainImageSrc = [
Blotter.Assets.Shaders.Noise3D,
"void mainImage( out vec4 mainImage, in vec2 fragCoord )",
"{",
" // Setup ========================================================================",
" vec2 uv = fragCoord.xy / uResolution.xy;",
" float z = uSeed + uGlobalTime * uSpeed;",
" uv += snoise(vec3(uv, z)) * uVolatility;",
" mainImage = textTexture(uv);",
"}"
].join("\n");
return mainImageSrc;
}
return {
constructor : Blotter.LiquidDistortMaterial,
init : function () {
this.mainImage = _mainImageSrc();
this.uniforms = {
uSpeed : { type : "1f", value : 1.0 },
uVolatility : { type : "1f", value : 0.15 },
uSeed : { type : "1f", value : 0.1 }
};
}
};
})());
})(
this.Blotter
);
// BLOTTER - Example 2
var text = new Blotter.Text("bree corn", {
family : "'garamond', serif",
size : 127,
fill : "#214094",
paddingLeft : 150,
paddingRight : 140,
paddingTop : 150
});
var material = new Blotter.LiquidDistortMaterial();
var canvas = document.body;
var mult = 0;
window.addEventListener('mousemove', draw, false);
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
// Play with the value for uSpeed. Lower values slow
// down animation, while higher values speed it up. At
// a speed of 0.0, animation is stopped entirely.
material.uniforms.uSpeed.value = 0.2;
// Try uncommenting the following line to play with
// the "volatility" of the effect. Higher values here will
// produce more dramatic changes in the appearance of your
// text as it animates, but you will likely want to keep
// the value below 1.0.
var blotter = new Blotter(material, {
texts : text
});
function draw(e) {
var pos = getMousePos(canvas, e);
posx = pos.x;
posy = pos.y;
mult = posx.map(0, document.body.clientWidth, 0, 50); // 0
blotter.texts.size = 27 + mult;
}
blotter.needsUpdate = true;
var elem = document.getElementById("distortion-text");
var scope = blotter.forText(text);
scope.appendTo(elem);
Number.prototype.map = function (in_min, in_max, out_min, out_max) {
return (this - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
|
from selenium import webdriver
options = webdriver.ChromeOptions();
options.add_argument('--user-data-dir=./User_Data')
# driver = webdriver.Chrome(executable_path='./chromedriver/chromedriver')
driver = webdriver.Chrome('./chromedriver/chromedriver_mac64_74', chrome_options=options)
driver.get('https://web.whatsapp.com/')
# name = input('Enter the name of user or group : ')
name_list = ['Edmund Situmorang', 'Mom']
msg = input('Enter your message : ')
count = int(input('Enter the count : '))
input('Enter anything after scanning QR code')
for name in name_list:
user = driver.find_element_by_xpath('//span[@title = "{}"]'.format(name))
user.click()
msg_box = driver.find_element_by_class_name('_2S1VP')
for i in range(count):
msg_box.send_keys(msg)
button = driver.find_element_by_class_name('_35EW6')
button.click()
|
import logging
import os
import sys
import pytest
from mms.context import Context
from mms.service import Service
from mms.service import emit_metrics
logging.basicConfig(stream=sys.stdout, format="%(message)s", level=logging.INFO)
# noinspection PyClassHasNoInit
class TestService:
model_name = 'testmodel'
model_dir = os.path.abspath('mms/tests/unit_tests/test_utils/')
manifest = "testmanifest"
data = [
{"requestId": b"123", "parameters": [
{"name": "xyz", "value": "abc", "contentType": "text/csv"}
], "data": b""}
]
@pytest.fixture()
def service(self, mocker):
service = object.__new__(Service)
service._entry_point = mocker.MagicMock(return_value=['prediction'])
service._context = Context(self.model_name, self.model_dir, self.manifest, 1, 0, '1.0')
return service
def test_predict(self, service, mocker):
create_predict_response = mocker.patch("mms.service.create_predict_response")
service.predict(self.data)
create_predict_response.assert_called()
def test_with_nil_request(self, service):
with pytest.raises(ValueError, match=r"Received invalid inputs"):
service.retrieve_data_for_inference(None)
def test_valid_req(self, service):
headers, input_batch, req_to_id_map = service.retrieve_data_for_inference(self.data)
assert headers[0].get_request_property("xyz").get("content-type") == "text/csv"
assert input_batch[0] == {"xyz": "abc"}
assert req_to_id_map == {0: "123"}
# noinspection PyClassHasNoInit
class TestEmitMetrics:
def test_emit_metrics(self, caplog):
metrics = {'test_emit_metrics': True}
emit_metrics(metrics)
assert "[METRICS]" in caplog.text
|
import React from 'react'
import Title from '../Title'
import tips from '../../constants/tips'
import styles from '../../css/tips.module.css'
const Tips = () => {
return (
<section className={styles.tips}>
<Title title="hot" subtitle="tips"/>
<div className={styles.center}>
{tips.map((item,index)=>{
return (
<article key={index} className={styles.tip}>
<span>{item.icon}</span>
<h4>{item.title}</h4>
<p>{item.text}</p>
</article>
)
})}
</div>
</section>
)
}
export default Tips;
|
const path = require('path');
exports.createPages = ({boundActionCreators, graphql}) => {
const {createPage} = boundActionCreators
const postTemplate = path.resolve('src/templates/blog-post.js')
return graphql(`
{
allMarkdownRemark {
edges {
node {
html
id
frontmatter {
path
title
date
author
}
}
}
}
}
`).then(res => {
if(res.errors) {
return Promise.reject(res.errors)
}
res.data.allMarkdownRemark.edges.forEach(({node}) => {
createPage({
path: node.frontmatter.path,
component: postTemplate
})
})
})
}
|
define(["exports", "../../../../@polymer/polymer/polymer-element.js", "../../../../@polymer/app-route/app-route.js", "../../../../@polymer/iron-ajax/iron-ajax.js", "../../../../@polymer/app-layout/app-toolbar/app-toolbar.js", "../../../../@polymer/marked-element/marked-element.js", "../../../simple-icon/simple-icon.js", "../../../simple-icon/lib/simple-icons.js", "../../../simple-icon/lib/simple-icon-button.js", "../../../hax-iconset/lib/simple-hax-iconset.js", "../../../../@polymer/paper-dialog/paper-dialog.js", "../../../../@polymer/polymer/lib/elements/dom-if.js", "../../../../@polymer/paper-badge/paper-badge.js", "../../../../@polymer/paper-toast/paper-toast.js", "../../../../@vaadin/vaadin-split-layout/vaadin-split-layout.js", "../../../lrnsys-layout/lib/lrnsys-dialog.js", "../../../lrnsys-button/lrnsys-button.js", "../../../lrnsys-comment/lib/lrnsys-comment-list.js", "../../../elmsln-loading/elmsln-loading.js", "./lrnapp-studio-submission-object.js", "./lrnapp-studio-submission-comments.js", "./lrnapp-studio-submission-comment.js"], function (_exports, _polymerElement, _appRoute, _ironAjax, _appToolbar, _markedElement, _simpleIcon, _simpleIcons, _simpleIconButton, _simpleHaxIconset, _paperDialog, _domIf, _paperBadge, _paperToast, _vaadinSplitLayout, _lrnsysDialog, _lrnsysButton, _lrnsysCommentList, _elmslnLoading, _lrnappStudioSubmissionObject, _lrnappStudioSubmissionComments, _lrnappStudioSubmissionComment) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.LrnappStudioSubmissionPage = void 0;
function _templateObject_4be0ce5099b011eb851ed31c596cbbd8() {
var data = babelHelpers.taggedTemplateLiteral(["\n <style>\n [hidden] {\n display: none !important;\n }\n :host {\n display: block;\n position: relative;\n }\n\n p {\n font-size: 14px;\n line-height: 18px;\n }\n\n h1 {\n margin: 0;\n text-align: left;\n }\n\n iron-selector {\n line-height: 1em;\n }\n\n iron-selector lrnsys-button {\n display: inline-flex;\n }\n\n img.image {\n margin: 0 0.5em;\n }\n\n lrnsys-dialog {\n display: inline;\n }\n\n .contain {\n width: 10em;\n height: 10em;\n background: #ddd;\n }\n\n .center {\n margin: auto;\n width: 100%;\n }\n\n .title {\n color: #222;\n font-size: 2rem;\n font-weight: 600;\n line-height: 2.5rem;\n padding: 0.25rem 0;\n white-space: nowrap;\n overflow-x: hidden;\n text-overflow: ellipsis;\n margin-top: 1rem;\n text-transform: uppercase;\n text-align: left;\n }\n\n .author {\n color: #555;\n font-size: 1rem;\n font-weight: 500;\n font-style: normal;\n line-height: 1rem;\n padding: 0.25rem 0 0.5rem 0;\n margin: 0;\n text-transform: capitalize;\n }\n\n .comments {\n text-align: right;\n margin: 0;\n font-size: 1.5em;\n }\n\n .submission-page-wrapper {\n padding: 0;\n --vaadin-split-layout-splitter: {\n min-width: 0.4em;\n background: var(--paper-amber-200);\n }\n }\n\n .submission-page {\n width: 70vw;\n }\n\n .submission-page-card {\n width: 100%;\n margin: 0;\n padding: 0 0 2em 1em;\n }\n\n .submission-comments {\n overflow-y: hidden;\n padding: 0;\n margin: 0;\n }\n\n elmsln-loading {\n position: absolute;\n display: none;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(255, 255, 255, 0.8);\n z-index: 10;\n align-items: flex-end;\n justify-content: center;\n }\n\n :host([saving]) elmsln-loading {\n display: block;\n }\n\n elmsln-loading {\n top: calc(50% - 5vmax);\n left: calc(50% - 5vmax);\n position: fixed;\n transform-origin: center center;\n width: 10vmax !important;\n height: 10vmax !important;\n }\n\n iron-pages {\n width: 100%;\n }\n\n paper-dialog {\n width: 50%;\n width: 50vmax;\n padding: 1em;\n z-index: 99999;\n }\n\n lrnapp-studio-submission-object {\n width: 100%;\n }\n\n .assignment-body {\n padding: 2em;\n }\n\n simple-icon {\n margin: 0.2em;\n }\n </style>\n\n <app-route\n route=\"{{route}}\"\n pattern=\"/edit\"\n tail=\"{{tail}}\"\n active=\"{{editPage}}\"\n >\n </app-route>\n\n <iron-ajax\n id=\"ajaxRequest\"\n auto=\"\"\n url=\"[[reqUrl]]\"\n method=\"GET\"\n params=\"[[reqParams]]\"\n content-type=\"application/json\"\n handle-as=\"json\"\n on-response=\"_handleResponse\"\n ></iron-ajax>\n <!-- Update Submission Node -->\n <iron-ajax\n id=\"ajaxUpdateRequest\"\n url=\"[[reqUrl]]\"\n method=\"PUT\"\n body=\"[[submission]]\"\n params=\"[[reqParams]]\"\n content-type=\"application/json\"\n handle-as=\"json\"\n on-response=\"_handleUpdateResponse\"\n ></iron-ajax>\n <!-- Delete Submission Node -->\n <iron-ajax\n id=\"ajaxDeleteRequest\"\n url=\"[[reqUrl]]\"\n method=\"DELETE\"\n params=\"[[reqParams]]\"\n content-type=\"application/json\"\n handle-as=\"json\"\n on-response=\"_handleDeleteResponse\"\n ></iron-ajax>\n\n <app-toolbar class=\"amber lighten-3\" hidden$=\"[[hideMenuBar]]\">\n <template is=\"dom-if\" if=\"[[showComments]]\">\n <lrnsys-button\n on-click=\"_backToStudio\"\n icon=\"arrow-back\"\n label=\"See in studio\"\n hover-class=\"amber darken-4 white-text\"\n ></lrnsys-button>\n </template>\n <template is=\"dom-if\" if=\"[[!showComments]]\">\n <lrnsys-button\n on-click=\"_backToKanban\"\n icon=\"arrow-back\"\n label=\"Back to project management\"\n hover-class=\"amber darken-4 white-text\"\n ></lrnsys-button>\n </template>\n <div spacer=\"\" main-title=\"\">[[submission.attributes.title]]</div>\n <div spacer=\"\">\n <lrnsys-dialog\n raised\n header=\"[[submission.relationships.assignment.attributes.title]]\"\n >\n <span slot=\"button\"\n ><simple-icon icon=\"icons:assignment\"></simple-icon>Assignment\n Details</span\n >\n <div class=\"assignment-body\">\n <marked-element\n id=\"assignment-body\"\n markdown=\"[[submission.relationships.assignment.attributes.body]]\"\n ></marked-element>\n </div>\n </lrnsys-dialog>\n </div>\n <div>\n <simple-icon\n id=\"comment-count\"\n icon=\"communication:forum\"\n ></simple-icon>\n [[submission.meta.comment_count]] Comments\n <paper-badge\n hidden$=\"[[displayNewBadge(submission.meta.comment_new)]]\"\n for=\"comment-count\"\n label$=\"[[submission.meta.comment_new]]\"\n ></paper-badge>\n </div>\n <div hidden$=\"[[editPage]]\">\n <lrnsys-button\n on-click=\"_setEditRoute\"\n icon=\"create\"\n label=\"Edit\"\n hover-class=\"amber darken-4 white-text\"\n hidden$=\"[[!submission.meta.canUpdate]]\"\n ></lrnsys-button>\n </div>\n <div hidden$=\"[[!editPage]]\">\n <lrnsys-button\n on-click=\"_resetRoute\"\n icon=\"cancel\"\n label=\"Cancel\"\n hover-class=\"amber darken-4 white-text\"\n hidden$=\"[[!submission.meta.canUpdate]]\"\n ></lrnsys-button>\n </div>\n </app-toolbar>\n\n <vaadin-split-layout class=\"submission-page-wrapper\">\n <div\n id=\"commentcolumn\"\n class=\"submission-comments\"\n style=\"min-width: 25%; max-width: 40%; width:30%;\"\n >\n <template is=\"dom-if\" if=\"[[showComments]]\">\n <lrnsys-comment-list\n comment-ops-base=\"{{commentOpsBase}}\"\n csrf-token=\"[[csrfToken]]\"\n source-path=\"{{commentsUrl}}\"\n create-stub-url=\"{{createStubUrl}}\"\n ></lrnsys-comment-list>\n </template>\n </div>\n <div id=\"submissioncolumn\" style=\"width:70%;\">\n <lrnapp-studio-submission-object\n submission=\"{{submission}}\"\n edit=\"[[editPage]]\"\n ></lrnapp-studio-submission-object>\n </div>\n <simple-icon class=\"splitter-handle\" icon=\"more-vert\"></simple-icon>\n </vaadin-split-layout>\n\n <elmsln-loading></elmsln-loading>\n\n <paper-dialog id=\"deletedialog\">\n <h2>Delete submission?</h2>\n <p>Are you sure you want to delete this submission?</p>\n <div class=\"buttons\">\n <button dialog-dismiss=\"\">Cancel</button>\n <button dialog-confirm=\"\" on-click=\"_submissionDeleteConfirmed\">\n Delete\n </button>\n </div>\n </paper-dialog>\n <paper-dialog id=\"publishdialog\">\n <h2>Ready to publish?</h2>\n <p>\n By publishing, the author of this submission will be able to view your\n feedback. Are you ready to publish?\n </p>\n <div class=\"buttons\">\n <button dialog-dismiss=\"\">Cancel</button>\n <button dialog-confirm=\"\" on-click=\"_submissionPublishConfirmed\">\n Yes Publish\n </button>\n </div>\n </paper-dialog>\n\n <paper-toast id=\"toast\"></paper-toast>\n "]);
_templateObject_4be0ce5099b011eb851ed31c596cbbd8 = function _templateObject_4be0ce5099b011eb851ed31c596cbbd8() {
return data;
};
return data;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = babelHelpers.getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = babelHelpers.getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return babelHelpers.possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var LrnappStudioSubmissionPage = /*#__PURE__*/function (_PolymerElement) {
babelHelpers.inherits(LrnappStudioSubmissionPage, _PolymerElement);
var _super = _createSuper(LrnappStudioSubmissionPage);
function LrnappStudioSubmissionPage() {
babelHelpers.classCallCheck(this, LrnappStudioSubmissionPage);
return _super.apply(this, arguments);
}
babelHelpers.createClass(LrnappStudioSubmissionPage, [{
key: "connectedCallback",
value: function connectedCallback() {
babelHelpers.get(babelHelpers.getPrototypeOf(LrnappStudioSubmissionPage.prototype), "connectedCallback", this).call(this);
this.addEventListener("submissionDeleteClicked", this._submissionDeleteClicked.bind(this));
this.addEventListener("submissionPublishClicked", this._submissionPublishClicked.bind(this));
this.addEventListener("submissionSaveDraftClicked", this._submissionSaveDraftClicked.bind(this));
}
}, {
key: "disconnectedCallback",
value: function disconnectedCallback() {
this.removeEventListener("submissionDeleteClicked", this._submissionDeleteClicked.bind(this));
this.removeEventListener("submissionPublishClicked", this._submissionPublishClicked.bind(this));
this.removeEventListener("submissionSaveDraftClicked", this._submissionSaveDraftClicked.bind(this));
babelHelpers.get(babelHelpers.getPrototypeOf(LrnappStudioSubmissionPage.prototype), "disconnectedCallback", this).call(this);
}
}, {
key: "_backToStudio",
/**
* Go back to the studio relative to the app's path.
*/
value: function _backToStudio(e) {
window.location.href = this.basePath + "lrnapp-open-studio";
}
/**
* Go back to the studio relative to the app's path.
*/
}, {
key: "_backToKanban",
value: function _backToKanban(e) {
window.location.href = this.basePath + "lrnapp-studio-kanban";
}
/**
* Trigger the page router to invoke edit state.
*/
}, {
key: "_setEditRoute",
value: function _setEditRoute(e) {
this.set("route.path", "edit");
this.notifyPath("route.path");
}
/**
* Trigger the page router to invoke edit state.
*/
}, {
key: "_resetRoute",
value: function _resetRoute(e) {
this.set("route.path", "");
this.notifyPath("route.path");
}
/**
* if we should show new badge based on new comment count.
*/
}, {
key: "displayNewBadge",
value: function displayNewBadge(count) {
if (count == 0) {
return true;
}
return false;
}
}, {
key: "_computeCommentsUrl",
value: function _computeCommentsUrl(id, endPoint, csrfToken) {
return endPoint + "/api/submissions/" + id + "/comments?token=" + csrfToken;
}
}, {
key: "_computeCommentsOpsUrl",
value: function _computeCommentsOpsUrl(id, endPoint, csrfToken) {
return endPoint + "/api/submissions/" + id + "/comments";
}
}, {
key: "_computeCommentsStubUrl",
value: function _computeCommentsStubUrl(id, endPoint, csrfToken) {
return endPoint + "/api/submissions/" + id + "/comments/create-stub?token=" + csrfToken;
}
}, {
key: "_urlVarsChanged",
value: function _urlVarsChanged(id, endPoint) {
this.reqUrl = endPoint + "/api/submissions/" + id;
}
}, {
key: "_paramsChanged",
value: function _paramsChanged(csrfToken) {
var params = this.reqParams || {};
params.token = csrfToken;
this.reqParams = params;
}
}, {
key: "_handleResponse",
value: function _handleResponse(data) {
var _this = this;
// empty response means no access or deleted item
if (data.detail.response.data) {
this.set("submission", {});
setTimeout(function () {
_this.set("submission", data.detail.response.data);
window.dispatchEvent(new Event("resize"));
}, 0);
}
}
}, {
key: "_isReply",
value: function _isReply(data) {
this.thread = submission.relationships.comments.data.attributes.thread;
}
}, {
key: "_submissionSaveDraftClicked",
value: function _submissionSaveDraftClicked(e) {
this.saving = true;
this.shadowRoot.querySelector("#ajaxUpdateRequest").generateRequest();
}
}, {
key: "_submissionPublishClicked",
value: function _submissionPublishClicked(e) {
this.shadowRoot.querySelector("#publishdialog").open();
}
}, {
key: "_submissionPublishConfirmed",
value: function _submissionPublishConfirmed(e) {
this.saving = true;
this.shadowRoot.querySelector("#ajaxUpdateRequest").generateRequest();
}
}, {
key: "_submissionDeleteClicked",
value: function _submissionDeleteClicked(e) {
this.shadowRoot.querySelector("#deletedialog").open();
}
}, {
key: "_submissionDeleteConfirmed",
value: function _submissionDeleteConfirmed(e) {
this.saving = true;
this.$.ajaxDeleteRequest.generateRequest();
}
}, {
key: "_handleUpdateResponse",
value: function _handleUpdateResponse(res) {
var root = this;
var status = res.detail.response.status;
var submission = res.detail.response.data;
root.saving = false;
if (status === 200) {
root.set("submission", {});
root.set("submission", submission);
root.set("route.path", ""); // display a submission published notification
if (submission.attributes.state === "submission_ready") {
this.$.toast.show("Published!");
} // @todo replace this with the page just being there once we fix the lazy load dilema
window.location.href = this.endPoint + "/submissions/" + submission.id;
}
}
}, {
key: "_handleDeleteResponse",
value: function _handleDeleteResponse(res) {
var root = this;
var status = res.detail.response.status;
root.saving = false;
if (status === 200) {
window.location.href = this.basePath + "lrnapp-studio-kanban?deletetoast";
}
}
}, {
key: "_computeShowComments",
value: function _computeShowComments(submission) {
try {
var type = submission.meta.submissionType;
if (type !== "critique" && submission.attributes.state == "submission_ready") {
return true;
}
} catch (error) {}
return false;
}
/**
* Simple way to convert from object to array.
*/
}, {
key: "_toArray",
value: function _toArray(obj) {
if (babelHelpers.typeof(obj) === "object" && obj !== null) {
return Object.keys(obj).map(function (key) {
return obj[key];
});
}
return [];
}
}], [{
key: "template",
get: function get() {
return (0, _polymerElement.html)(_templateObject_4be0ce5099b011eb851ed31c596cbbd8());
}
}, {
key: "tag",
get: function get() {
return "lrnapp-studio-submission-page";
}
}, {
key: "properties",
get: function get() {
var _ref;
return _ref = {
id: {
type: String
},
hideMenuBar: {
type: Boolean,
value: false
},
elmslnCourse: {
type: String
},
elmslnSection: {
type: String
},
basePath: {
type: String
},
csrfToken: {
type: String
},
endPoint: {
type: String
}
}, babelHelpers.defineProperty(_ref, "endPoint", {
type: String
}), babelHelpers.defineProperty(_ref, "basePath", {
type: String
}), babelHelpers.defineProperty(_ref, "csrfToken", {
type: String
}), babelHelpers.defineProperty(_ref, "reqUrl", {
type: String
}), babelHelpers.defineProperty(_ref, "reqParams", {
type: Object
}), babelHelpers.defineProperty(_ref, "submission", {
type: Object,
notify: true,
value: null
}), babelHelpers.defineProperty(_ref, "commentsUrl", {
type: String,
computed: "_computeCommentsUrl(id, endPoint, csrfToken)"
}), babelHelpers.defineProperty(_ref, "createStubUrl", {
type: String,
computed: "_computeCommentsStubUrl(id, endPoint, csrfToken)"
}), babelHelpers.defineProperty(_ref, "commentOpsBase", {
type: String,
computed: "_computeCommentsOpsUrl(id, endPoint, csrfToken)"
}), babelHelpers.defineProperty(_ref, "editPage", {
type: Boolean,
reflectToAttribute: true
}), babelHelpers.defineProperty(_ref, "saving", {
type: Boolean,
value: false,
notify: true,
reflectToAttribute: true
}), babelHelpers.defineProperty(_ref, "showComments", {
type: Boolean,
computed: "_computeShowComments(submission)"
}), _ref;
}
}, {
key: "observers",
get: function get() {
return ["_urlVarsChanged(id, endPoint)", "_paramsChanged(csrfToken)", "_bodyChanged(title)"];
}
}]);
return LrnappStudioSubmissionPage;
}(_polymerElement.PolymerElement);
_exports.LrnappStudioSubmissionPage = LrnappStudioSubmissionPage;
window.customElements.define(LrnappStudioSubmissionPage.tag, LrnappStudioSubmissionPage);
});
|
# 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.
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
# import sys
import openstackdocstheme
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
# extensions = ['sphinx.ext.todo']
# Add any paths that contain templates here, relative to this directory.
# templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Architecture Design Guide'
bug_tag = u'arch-design-draft'
copyright = u'2015-2016, OpenStack contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.9'
# The full version, including alpha/beta/rc tags.
release = '0.9'
# A few variables have to be set for the log-a-bug feature.
# giturl: The location of conf.py on Git. Must be set manually.
# gitsha: The SHA checksum of the bug description. Automatically extracted from git log.
# bug_tag: Tag for categorizing the bug. Must be set manually.
# These variables are passed to the logabug code via html_context.
giturl = u'http://git.openstack.org/cgit/openstack/openstack-manuals/tree/doc/arch-design-draft/source'
git_cmd = "/usr/bin/git log | head -n1 | cut -f2 -d' '"
gitsha = os.popen(git_cmd).read().strip('\n')
html_context = {"gitsha": gitsha, "bug_tag": bug_tag,
"giturl": giturl}
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['common/cli*', 'common/nova*', 'common/get_started_*',
'common/dashboard_customizing.rst']
# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'openstackdocs'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = [openstackdocstheme.get_html_theme_path()]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = []
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# So that we can enable "log-a-bug" links from each output HTML page, this
# variable must be set to a format that includes year, month, day, hours and
# minutes.
html_last_updated_fmt = '%Y-%m-%d %H:%M'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
html_use_index = False
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'arch-design-draft'
# If true, publish source files
html_copy_source = False
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'ArchGuideRst.tex', u'Architecture Design Guide',
u'OpenStack contributors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'ArchDesignRst', u'Architecture Design Guide',
[u'OpenStack contributors'], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'ArchDesignRst', u'Architecture Design Guide',
u'OpenStack contributors', 'ArchDesignRst',
'To reap the benefits of OpenStack, you should plan, design,'
'and architect your cloud properly, taking user needs into'
'account and understanding the use cases.'
'commands.', 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
# -- Options for Internationalization output ------------------------------
locale_dirs = ['locale/']
|
/*!
* Keen UI v1.0.0 (https://github.com/JosephusPaye/keen-ui)
* (c) 2017 Josephus Paye II
* Released under the MIT License.
*/
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.UiSelect=t():(e.KeenUI=e.KeenUI||{},e.KeenUI.UiSelect=t())}(this,function(){return function(e){function t(n){if(i[n])return i[n].exports;var r=i[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var i={};return t.m=e,t.c=i,t.i=function(e){return e},t.d=function(e,i,n){t.o(e,i)||Object.defineProperty(e,i,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var i=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(i,"a",i),i},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=318)}([function(e,t){var i=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=i)},function(e,t,i){e.exports=!i(12)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,i){var n=i(13),r=i(31),o=i(17),s=Object.defineProperty;t.f=i(1)?Object.defineProperty:function(e,t,i){if(n(e),t=o(t,!0),n(i),r)try{return s(e,t,i)}catch(e){}if("get"in i||"set"in i)throw TypeError("Accessors not supported!");return"value"in i&&(e[t]=i.value),e}},function(e,t){var i={}.hasOwnProperty;e.exports=function(e,t){return i.call(e,t)}},function(e,t,i){var n=i(52),r=i(18);e.exports=function(e){return n(r(e))}},function(e,t,i){var n=i(2),r=i(14);e.exports=i(1)?function(e,t,i){return n.f(e,t,r(1,i))}:function(e,t,i){return e[t]=i,e}},function(e,t,i){var n=i(25)("wks"),r=i(16),o=i(0).Symbol,s="function"==typeof o,a=e.exports=function(e){return n[e]||(n[e]=s&&o[e]||(s?o:r)("Symbol."+e))};a.store=n},function(e,t){e.exports=function(){var e=[];return e.toString=function(){for(var e=[],t=0;t<this.length;t++){var i=this[t];i[2]?e.push("@media "+i[2]+"{"+i[1]+"}"):e.push(i[1])}return e.join("")},e.i=function(t,i){"string"==typeof t&&(t=[[null,t,""]]);for(var n={},r=0;r<this.length;r++){var o=this[r][0];"number"==typeof o&&(n[o]=!0)}for(r=0;r<t.length;r++){var s=t[r];"number"==typeof s[0]&&n[s[0]]||(i&&!s[2]?s[2]=i:i&&(s[2]="("+s[2]+") and ("+i+")"),e.push(s))}},e}},function(e,t){e.exports=function(e,t,i,n){var r,o=e=e||{},s=typeof e.default;"object"!==s&&"function"!==s||(r=e,o=e.default);var a="function"==typeof o?o.options:o;if(t&&(a.render=t.render,a.staticRenderFns=t.staticRenderFns),i&&(a._scopeId=i),n){var l=a.computed||(a.computed={});Object.keys(n).forEach(function(e){var t=n[e];l[e]=function(){return t}})}return{esModule:r,exports:o,options:a}}},function(e,t){function i(e,t){for(var i=0;i<e.length;i++){var n=e[i],r=c[n.id];if(r){r.refs++;for(var o=0;o<r.parts.length;o++)r.parts[o](n.parts[o]);for(;o<n.parts.length;o++)r.parts.push(a(n.parts[o],t))}else{for(var s=[],o=0;o<n.parts.length;o++)s.push(a(n.parts[o],t));c[n.id]={id:n.id,refs:1,parts:s}}}}function n(e){for(var t=[],i={},n=0;n<e.length;n++){var r=e[n],o=r[0],s=r[1],a=r[2],l=r[3],u={css:s,media:a,sourceMap:l};i[o]?i[o].parts.push(u):t.push(i[o]={id:o,parts:[u]})}return t}function r(e,t){var i=d(),n=v[v.length-1];if("top"===e.insertAt)n?n.nextSibling?i.insertBefore(t,n.nextSibling):i.appendChild(t):i.insertBefore(t,i.firstChild),v.push(t);else{if("bottom"!==e.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");i.appendChild(t)}}function o(e){e.parentNode.removeChild(e);var t=v.indexOf(e);t>=0&&v.splice(t,1)}function s(e){var t=document.createElement("style");return t.type="text/css",r(e,t),t}function a(e,t){var i,n,r;if(t.singleton){var a=g++;i=h||(h=s(t)),n=l.bind(null,i,a,!1),r=l.bind(null,i,a,!0)}else i=s(t),n=u.bind(null,i),r=function(){o(i)};return n(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;n(e=t)}else r()}}function l(e,t,i,n){var r=i?"":n.css;if(e.styleSheet)e.styleSheet.cssText=m(t,r);else{var o=document.createTextNode(r),s=e.childNodes;s[t]&&e.removeChild(s[t]),s.length?e.insertBefore(o,s[t]):e.appendChild(o)}}function u(e,t){var i=t.css,n=t.media,r=t.sourceMap;if(n&&e.setAttribute("media",n),r&&(i+="\n/*# sourceURL="+r.sources[0]+" */",i+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(r))))+" */"),e.styleSheet)e.styleSheet.cssText=i;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(i))}}var c={},f=function(e){var t;return function(){return"undefined"==typeof t&&(t=e.apply(this,arguments)),t}},p=f(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),d=f(function(){return document.head||document.getElementsByTagName("head")[0]}),h=null,g=0,v=[];e.exports=function(e,t){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");t=t||{},"undefined"==typeof t.singleton&&(t.singleton=p()),"undefined"==typeof t.insertAt&&(t.insertAt="bottom");var r=n(e);return i(r,t),function(e){for(var o=[],s=0;s<r.length;s++){var a=r[s],l=c[a.id];l.refs--,o.push(l)}if(e){var u=n(e);i(u,t)}for(var s=0;s<o.length;s++){var l=o[s];if(0===l.refs){for(var f=0;f<l.parts.length;f++)l.parts[f]();delete c[l.id]}}}};var m=function(){var e=[];return function(t,i){return e[t]=i,e.filter(Boolean).join("\n")}}()},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){var i=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=i)},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t,i){var n=i(10);e.exports=function(e){if(!n(e))throw TypeError(e+" is not an object!");return e}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,i){var n=i(37),r=i(19);e.exports=Object.keys||function(e){return n(e,r)}},function(e,t){var i=0,n=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++i+n).toString(36))}},function(e,t,i){var n=i(10);e.exports=function(e,t){if(!n(e))return e;var i,r;if(t&&"function"==typeof(i=e.toString)&&!n(r=i.call(e)))return r;if("function"==typeof(i=e.valueOf)&&!n(r=i.call(e)))return r;if(!t&&"function"==typeof(i=e.toString)&&!n(r=i.call(e)))return r;throw TypeError("Can't convert object to primitive value")}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t){e.exports={}},function(e,t){e.exports=!0},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,i){var n=i(2).f,r=i(3),o=i(6)("toStringTag");e.exports=function(e,t,i){e&&!r(e=i?e:e.prototype,o)&&n(e,o,{configurable:!0,value:t})}},function(e,t,i){var n=i(25)("keys"),r=i(16);e.exports=function(e){return n[e]||(n[e]=r(e))}},function(e,t,i){var n=i(0),r="__core-js_shared__",o=n[r]||(n[r]={});e.exports=function(e){return o[e]||(o[e]={})}},function(e,t){var i=Math.ceil,n=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?n:i)(e)}},function(e,t,i){var n=i(0),r=i(11),o=i(21),s=i(28),a=i(2).f;e.exports=function(e){var t=r.Symbol||(r.Symbol=o?{}:n.Symbol||{});"_"==e.charAt(0)||e in t||a(t,e,{value:s.f(e)})}},function(e,t,i){t.f=i(6)},function(e,t,i){var n=i(0),r=i(11),o=i(42),s=i(5),a="prototype",l=function(e,t,i){var u,c,f,p=e&l.F,d=e&l.G,h=e&l.S,g=e&l.P,v=e&l.B,m=e&l.W,y=d?r:r[t]||(r[t]={}),_=y[a],b=d?n:h?n[t]:(n[t]||{})[a];d&&(i=t);for(u in i)c=!p&&b&&void 0!==b[u],c&&u in y||(f=c?b[u]:i[u],y[u]=d&&"function"!=typeof b[u]?i[u]:v&&c?o(f,n):m&&b[u]==f?function(e){var t=function(t,i,n){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,i)}return new e(t,i,n)}return e.apply(this,arguments)};return t[a]=e[a],t}(f):g&&"function"==typeof f?o(Function.call,f):f,g&&((y.virtual||(y.virtual={}))[u]=f,e&l.R&&_&&!_[u]&&s(_,u,f)))};l.F=1,l.G=2,l.S=4,l.P=8,l.B=16,l.W=32,l.U=64,l.R=128,e.exports=l},function(e,t,i){var n=i(10),r=i(0).document,o=n(r)&&n(r.createElement);e.exports=function(e){return o?r.createElement(e):{}}},function(e,t,i){e.exports=!i(1)&&!i(12)(function(){return 7!=Object.defineProperty(i(30)("div"),"a",{get:function(){return 7}}).a})},function(e,t){var i={}.toString;e.exports=function(e){return i.call(e).slice(8,-1)}},function(e,t,i){"use strict";var n=i(21),r=i(29),o=i(38),s=i(5),a=i(3),l=i(20),u=i(54),c=i(23),f=i(61),p=i(6)("iterator"),d=!([].keys&&"next"in[].keys()),h="@@iterator",g="keys",v="values",m=function(){return this};e.exports=function(e,t,i,y,_,b,x){u(i,t,y);var w,k,S,O=function(e){if(!d&&e in P)return P[e];switch(e){case g:return function(){return new i(this,e)};case v:return function(){return new i(this,e)}}return function(){return new i(this,e)}},C=t+" Iterator",j=_==v,I=!1,P=e.prototype,E=P[p]||P[h]||_&&P[_],M=E||O(_),T=_?j?O("entries"):M:void 0,D="Array"==t?P.entries||E:E;if(D&&(S=f(D.call(new e)),S!==Object.prototype&&(c(S,C,!0),n||a(S,p)||s(S,p,m))),j&&E&&E.name!==v&&(I=!0,M=function(){return E.call(this)}),n&&!x||!d&&!I&&P[p]||s(P,p,M),l[t]=M,l[C]=m,_)if(w={values:j?M:O(v),keys:b?M:O(g),entries:T},x)for(k in w)k in P||o(P,k,w[k]);else r(r.P+r.F*(d||I),t,w);return w}},function(e,t,i){var n=i(13),r=i(58),o=i(19),s=i(24)("IE_PROTO"),a=function(){},l="prototype",u=function(){var e,t=i(30)("iframe"),n=o.length,r="<",s=">";for(t.style.display="none",i(51).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write(r+"script"+s+"document.F=Object"+r+"/script"+s),e.close(),u=e.F;n--;)delete u[l][o[n]];return u()};e.exports=Object.create||function(e,t){var i;return null!==e?(a[l]=n(e),i=new a,a[l]=null,i[s]=e):i=u(),void 0===t?i:r(i,t)}},function(e,t,i){var n=i(37),r=i(19).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return n(e,r)}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,i){var n=i(3),r=i(4),o=i(49)(!1),s=i(24)("IE_PROTO");e.exports=function(e,t){var i,a=r(e),l=0,u=[];for(i in a)i!=s&&n(a,i)&&u.push(i);for(;t.length>l;)n(a,i=t[l++])&&(~o(u,i)||u.push(i));return u}},function(e,t,i){e.exports=i(5)},function(e,t,i){i(78);var n=i(8)(i(74),i(77),null,null);e.exports=n.exports},,function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,i){var n=i(41);e.exports=function(e,t,i){if(n(e),void 0===t)return e;switch(i){case 1:return function(i){return e.call(t,i)};case 2:return function(i,n){return e.call(t,i,n)};case 3:return function(i,n,r){return e.call(t,i,n,r)}}return function(){return e.apply(t,arguments)}}},function(e,t,i){e.exports={default:i(46),__esModule:!0}},function(e,t,i){e.exports={default:i(47),__esModule:!0}},function(e,t,i){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var r=i(44),o=n(r),s=i(43),a=n(s),l="function"==typeof a.default&&"symbol"==typeof o.default?function(e){return typeof e}:function(e){return e&&"function"==typeof a.default&&e.constructor===a.default&&e!==a.default.prototype?"symbol":typeof e};t.default="function"==typeof a.default&&"symbol"===l(o.default)?function(e){return"undefined"==typeof e?"undefined":l(e)}:function(e){return e&&"function"==typeof a.default&&e.constructor===a.default&&e!==a.default.prototype?"symbol":"undefined"==typeof e?"undefined":l(e)}},function(e,t,i){i(69),i(67),i(70),i(71),e.exports=i(11).Symbol},function(e,t,i){i(68),i(72),e.exports=i(28).f("iterator")},function(e,t){e.exports=function(){}},function(e,t,i){var n=i(4),r=i(64),o=i(63);e.exports=function(e){return function(t,i,s){var a,l=n(t),u=r(l.length),c=o(s,u);if(e&&i!=i){for(;u>c;)if(a=l[c++],a!=a)return!0}else for(;u>c;c++)if((e||c in l)&&l[c]===i)return e||c||0;return!e&&-1}}},function(e,t,i){var n=i(15),r=i(36),o=i(22);e.exports=function(e){var t=n(e),i=r.f;if(i)for(var s,a=i(e),l=o.f,u=0;a.length>u;)l.call(e,s=a[u++])&&t.push(s);return t}},function(e,t,i){e.exports=i(0).document&&document.documentElement},function(e,t,i){var n=i(32);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==n(e)?e.split(""):Object(e)}},function(e,t,i){var n=i(32);e.exports=Array.isArray||function(e){return"Array"==n(e)}},function(e,t,i){"use strict";var n=i(34),r=i(14),o=i(23),s={};i(5)(s,i(6)("iterator"),function(){return this}),e.exports=function(e,t,i){e.prototype=n(s,{next:r(1,i)}),o(e,t+" Iterator")}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,i){var n=i(15),r=i(4);e.exports=function(e,t){for(var i,o=r(e),s=n(o),a=s.length,l=0;a>l;)if(o[i=s[l++]]===t)return i}},function(e,t,i){var n=i(16)("meta"),r=i(10),o=i(3),s=i(2).f,a=0,l=Object.isExtensible||function(){return!0},u=!i(12)(function(){return l(Object.preventExtensions({}))}),c=function(e){s(e,n,{value:{i:"O"+ ++a,w:{}}})},f=function(e,t){if(!r(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!o(e,n)){if(!l(e))return"F";if(!t)return"E";c(e)}return e[n].i},p=function(e,t){if(!o(e,n)){if(!l(e))return!0;if(!t)return!1;c(e)}return e[n].w},d=function(e){return u&&h.NEED&&l(e)&&!o(e,n)&&c(e),e},h=e.exports={KEY:n,NEED:!1,fastKey:f,getWeak:p,onFreeze:d}},function(e,t,i){var n=i(2),r=i(13),o=i(15);e.exports=i(1)?Object.defineProperties:function(e,t){r(e);for(var i,s=o(t),a=s.length,l=0;a>l;)n.f(e,i=s[l++],t[i]);return e}},function(e,t,i){var n=i(22),r=i(14),o=i(4),s=i(17),a=i(3),l=i(31),u=Object.getOwnPropertyDescriptor;t.f=i(1)?u:function(e,t){if(e=o(e),t=s(t,!0),l)try{return u(e,t)}catch(e){}if(a(e,t))return r(!n.f.call(e,t),e[t])}},function(e,t,i){var n=i(4),r=i(35).f,o={}.toString,s="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],a=function(e){try{return r(e)}catch(e){return s.slice()}};e.exports.f=function(e){return s&&"[object Window]"==o.call(e)?a(e):r(n(e))}},function(e,t,i){var n=i(3),r=i(65),o=i(24)("IE_PROTO"),s=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=r(e),n(e,o)?e[o]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?s:null}},function(e,t,i){var n=i(26),r=i(18);e.exports=function(e){return function(t,i){var o,s,a=String(r(t)),l=n(i),u=a.length;return l<0||l>=u?e?"":void 0:(o=a.charCodeAt(l),o<55296||o>56319||l+1===u||(s=a.charCodeAt(l+1))<56320||s>57343?e?a.charAt(l):o:e?a.slice(l,l+2):(o-55296<<10)+(s-56320)+65536)}}},function(e,t,i){var n=i(26),r=Math.max,o=Math.min;e.exports=function(e,t){return e=n(e),e<0?r(e+t,0):o(e,t)}},function(e,t,i){var n=i(26),r=Math.min;e.exports=function(e){return e>0?r(n(e),9007199254740991):0}},function(e,t,i){var n=i(18);e.exports=function(e){return Object(n(e))}},function(e,t,i){"use strict";var n=i(48),r=i(55),o=i(20),s=i(4);e.exports=i(33)(Array,"Array",function(e,t){this._t=s(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,i=this._i++;return!e||i>=e.length?(this._t=void 0,r(1)):"keys"==t?r(0,i):"values"==t?r(0,e[i]):r(0,[i,e[i]])},"values"),o.Arguments=o.Array,n("keys"),n("values"),n("entries")},function(e,t){},function(e,t,i){"use strict";var n=i(62)(!0);i(33)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,i=this._i;return i>=t.length?{value:void 0,done:!0}:(e=n(t,i),this._i+=e.length,{value:e,done:!1})})},function(e,t,i){"use strict";var n=i(0),r=i(3),o=i(1),s=i(29),a=i(38),l=i(57).KEY,u=i(12),c=i(25),f=i(23),p=i(16),d=i(6),h=i(28),g=i(27),v=i(56),m=i(50),y=i(53),_=i(13),b=i(4),x=i(17),w=i(14),k=i(34),S=i(60),O=i(59),C=i(2),j=i(15),I=O.f,P=C.f,E=S.f,M=n.Symbol,T=n.JSON,D=T&&T.stringify,B="prototype",A=d("_hidden"),F=d("toPrimitive"),N={}.propertyIsEnumerable,L=c("symbol-registry"),z=c("symbols"),U=c("op-symbols"),$=Object[B],R="function"==typeof M,V=n.QObject,q=!V||!V[B]||!V[B].findChild,H=o&&u(function(){return 7!=k(P({},"a",{get:function(){return P(this,"a",{value:7}).a}})).a})?function(e,t,i){var n=I($,t);n&&delete $[t],P(e,t,i),n&&e!==$&&P($,t,n)}:P,K=function(e){var t=z[e]=k(M[B]);return t._k=e,t},J=R&&"symbol"==typeof M.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof M},G=function(e,t,i){return e===$&&G(U,t,i),_(e),t=x(t,!0),_(i),r(z,t)?(i.enumerable?(r(e,A)&&e[A][t]&&(e[A][t]=!1),i=k(i,{enumerable:w(0,!1)})):(r(e,A)||P(e,A,w(1,{})),e[A][t]=!0),H(e,t,i)):P(e,t,i)},W=function(e,t){_(e);for(var i,n=m(t=b(t)),r=0,o=n.length;o>r;)G(e,i=n[r++],t[i]);return e},Q=function(e,t){return void 0===t?k(e):W(k(e),t)},Y=function(e){var t=N.call(this,e=x(e,!0));return!(this===$&&r(z,e)&&!r(U,e))&&(!(t||!r(this,e)||!r(z,e)||r(this,A)&&this[A][e])||t)},X=function(e,t){if(e=b(e),t=x(t,!0),e!==$||!r(z,t)||r(U,t)){var i=I(e,t);return!i||!r(z,t)||r(e,A)&&e[A][t]||(i.enumerable=!0),i}},Z=function(e){for(var t,i=E(b(e)),n=[],o=0;i.length>o;)r(z,t=i[o++])||t==A||t==l||n.push(t);return n},ee=function(e){for(var t,i=e===$,n=E(i?U:b(e)),o=[],s=0;n.length>s;)!r(z,t=n[s++])||i&&!r($,t)||o.push(z[t]);return o};R||(M=function(){if(this instanceof M)throw TypeError("Symbol is not a constructor!");var e=p(arguments.length>0?arguments[0]:void 0),t=function(i){this===$&&t.call(U,i),r(this,A)&&r(this[A],e)&&(this[A][e]=!1),H(this,e,w(1,i))};return o&&q&&H($,e,{configurable:!0,set:t}),K(e)},a(M[B],"toString",function(){return this._k}),O.f=X,C.f=G,i(35).f=S.f=Z,i(22).f=Y,i(36).f=ee,o&&!i(21)&&a($,"propertyIsEnumerable",Y,!0),h.f=function(e){return K(d(e))}),s(s.G+s.W+s.F*!R,{Symbol:M});for(var te="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ie=0;te.length>ie;)d(te[ie++]);for(var te=j(d.store),ie=0;te.length>ie;)g(te[ie++]);s(s.S+s.F*!R,"Symbol",{for:function(e){return r(L,e+="")?L[e]:L[e]=M(e)},keyFor:function(e){if(J(e))return v(L,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){q=!0},useSimple:function(){q=!1}}),s(s.S+s.F*!R,"Object",{create:Q,defineProperty:G,defineProperties:W,getOwnPropertyDescriptor:X,getOwnPropertyNames:Z,getOwnPropertySymbols:ee}),T&&s(s.S+s.F*(!R||u(function(){var e=M();return"[null]"!=D([e])||"{}"!=D({a:e})||"{}"!=D(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!J(e)){for(var t,i,n=[e],r=1;arguments.length>r;)n.push(arguments[r++]);return t=n[1],"function"==typeof t&&(i=t),!i&&y(t)||(t=function(e,t){if(i&&(t=i.call(this,e,t)),!J(t))return t}),n[1]=t,D.apply(T,n)}}}),M[B][F]||i(5)(M[B],F,M[B].valueOf),f(M,"Symbol"),f(Math,"Math",!0),f(n.JSON,"JSON",!0)},function(e,t,i){i(27)("asyncIterator")},function(e,t,i){i(27)("observable")},function(e,t,i){i(66);for(var n=i(0),r=i(5),o=i(20),s=i(6)("toStringTag"),a=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],l=0;l<5;l++){var u=a[l],c=n[u],f=c&&c.prototype;f&&!f[s]&&r(f,s,u),o[u]=o.Array}},function(e,t,i){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.KeenUiConfig=void 0;var r=i(79),o=n(r),s=i(80),a=n(s),l=i(83),u=n(l),c={disableRipple:!1,UiAutocomplete:{keys:{label:"label",value:"value",image:"image"}},UiCheckboxGroup:{keys:{id:"id",name:"name",class:"class",label:"label",value:"value",disabled:"disabled"}},UiMenu:{keys:{icon:"icon",type:"type",label:"label",secondaryText:"secondaryText",iconProps:"iconProps",disabled:"disabled"}},UiRadioGroup:{keys:{id:"id",class:"class",label:"label",value:"value",checked:"checked",disabled:"disabled"}},UiSelect:{keys:{label:"label",value:"value",image:"image"}}},f=t.KeenUiConfig=function(){function e(){(0,o.default)(this,e),this.data=(0,u.default)(c,window.KeenUiConfig?window.KeenUiConfig:{})}return(0,a.default)(e,[{key:"set",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.data=(0,u.default)(this.data,e)}}]),e}();t.default=new f},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={name:"ui-icon",props:{icon:String,iconSet:{type:String,default:"material-icons"},ariaLabel:String,removeText:{type:Boolean,default:!1},useSvg:{type:Boolean,default:!1}}}},function(e,t,i){e.exports={default:i(81),__esModule:!0}},function(e,t,i){t=e.exports=i(7)(),t.push([e.i,".ui-icon{cursor:inherit;display:inline-block;font-size:1.5rem;height:1em;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;vertical-align:middle;width:1em}.ui-icon svg{fill:currentColor;height:1em;margin:0;padding:0;width:1em}",""])},function(e,t){e.exports={render:function(){var e=this;e.$createElement;return e._c("span",{staticClass:"ui-icon",class:[e.iconSet,e.icon],attrs:{"aria-label":e.ariaLabel}},[e.useSvg?e._c("svg",{staticClass:"ui-icon__svg"},[e._c("use",{attrs:{"xmlns:xlink":"http://www.w3.org/1999/xlink","xlink:href":"#"+e.icon}})]):e._t("default",[e._v(e._s(e.removeText?null:e.icon))])],2)},staticRenderFns:[]}},function(e,t,i){var n=i(76);"string"==typeof n&&(n=[[e.i,n,""]]);i(9)(n,{});n.locals&&(e.exports=n.locals)},function(e,t,i){"use strict";t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,i){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var r=i(75),o=n(r);t.default=function(){function e(e,t){for(var i=0;i<t.length;i++){var n=t[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),(0,o.default)(e,n.key,n)}}return function(t,i,n){return i&&e(t.prototype,i),n&&e(t,n),t}}()},function(e,t,i){i(82);var n=i(11).Object;e.exports=function(e,t,i){return n.defineProperty(e,t,i)}},function(e,t,i){var n=i(29);n(n.S+n.F*!i(1),"Object",{defineProperty:i(2).f})},function(e,t,i){"use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Sources cannot be null or undefined");return Object(e)}function r(e,t,i){var n=t[i];if(void 0!==n&&null!==n){if(a.call(e,i)&&(void 0===e[i]||null===e[i]))throw new TypeError("Cannot convert undefined or null to object ("+i+")");a.call(e,i)&&s(n)?e[i]=o(Object(e[i]),t[i]):e[i]=n}}function o(e,t){if(e===t)return e;t=Object(t);for(var i in t)a.call(t,i)&&r(e,t,i);if(Object.getOwnPropertySymbols)for(var n=Object.getOwnPropertySymbols(t),o=0;o<n.length;o++)l.call(t,n[o])&&r(e,t,n[o]);return e}var s=i(84),a=Object.prototype.hasOwnProperty,l=Object.prototype.propertyIsEnumerable;e.exports=function(e){e=n(e);for(var t=1;t<arguments.length;t++)o(e,arguments[t]);return e}},function(e,t,i){"use strict";e.exports=function(e){var t=typeof e;return null!==e&&("object"===t||"function"===t)}},,,,,,,,function(e,t,i){i(97);var n=i(8)(i(94),i(96),null,null);e.exports=n.exports},,function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={name:"ui-progress-circular",props:{type:{type:String,default:"indeterminate"},color:{type:String,default:"primary"},progress:{type:Number,default:0},size:{type:Number,default:32},stroke:Number,autoStroke:{type:Boolean,default:!0},disableTransition:{type:Boolean,default:!1}},computed:{classes:function(){return["ui-progress-circular--color-"+this.color,"ui-progress-circular--type-"+this.type]},strokeDashArray:function(){var e=2*Math.PI*this.radius;return Math.round(1e3*e)/1e3},strokeDashOffset:function(){var e=this.moderateProgress(this.progress),t=2*Math.PI*this.radius;return(100-e)/100*t},radius:function(){var e=this.stroke?this.stroke:4;return(this.size-e)/2},calculatedStroke:function(){return this.stroke?this.stroke:this.autoStroke?parseInt(this.size/8,10):4}},methods:{moderateProgress:function(e){return isNaN(e)||e<0?0:e>100?100:e}}}},function(e,t,i){t=e.exports=i(7)(),t.push([e.i,".ui-progress-circular{position:relative}.ui-progress-circular__determinate{transform:rotate(270deg)}.ui-progress-circular__determinate-path{stroke-dashoffset:0;transition:stroke-dashoffset .3s}.ui-progress-circular__indeterminate{animation:ui-progress-circular-rotate .7s linear infinite;bottom:0;height:100%;left:0;margin:auto;position:absolute;right:0;top:0;transform-origin:center center;width:100%}.ui-progress-circular__indeterminate-path{stroke-dasharray:89,200;stroke-dashoffset:-35px;stroke-linecap:round}.ui-progress-circular--color-multi-color .ui-progress-circular__determinate-path{stroke:#2196f3}.ui-progress-circular--color-multi-color .ui-progress-circular__indeterminate-path{animation:ui-progress-circular-color 6s ease-in-out infinite}.ui-progress-circular--color-primary .ui-progress-circular__determinate-path,.ui-progress-circular--color-primary .ui-progress-circular__indeterminate-path{stroke:#2196f3}.ui-progress-circular--color-accent .ui-progress-circular__determinate-path,.ui-progress-circular--color-accent .ui-progress-circular__indeterminate-path{stroke:#d500f9}.ui-progress-circular--color-black .ui-progress-circular__determinate-path,.ui-progress-circular--color-black .ui-progress-circular__indeterminate-path{stroke:#212121}.ui-progress-circular--color-white .ui-progress-circular__determinate-path,.ui-progress-circular--color-white .ui-progress-circular__indeterminate-path{stroke:#fff}.ui-progress-circular--transition-fade-enter-active,.ui-progress-circular--transition-fade-leave-active{transition:opacity .3s ease,transform .3s ease}.ui-progress-circular--transition-fade-enter,.ui-progress-circular--transition-fade-leave-active{opacity:0;transform:scale(0)}@keyframes ui-progress-circular-rotate{to{transform:rotate(1turn)}}@keyframes ui-progress-circular-color{0%,to{stroke:#f44336}40%{stroke:#2196f3}66%{stroke:#4caf50}80%,90%{stroke:#ff9800}}",""])},function(e,t){e.exports={render:function(){var e=this;e.$createElement;return e._c("transition",{attrs:{name:e.disableTransition?null:"ui-progress-circular--transition-fade"}},[e._c("div",{staticClass:"ui-progress-circular",class:e.classes,style:{width:e.size+"px",height:e.size+"px"}},["determinate"===e.type?e._c("svg",{staticClass:"ui-progress-circular__determinate",attrs:{role:"progressbar","aria-valuemax":100,"aria-valuemin":0,"aria-valuenow":e.progress,height:e.size,width:e.size}},[e._c("circle",{staticClass:"ui-progress-circular__determinate-path",style:{"stroke-dashoffset":e.strokeDashOffset,"stroke-width":e.calculatedStroke},attrs:{fill:"transparent","stroke-dashoffset":"0",cx:e.size/2,cy:e.size/2,r:e.radius,"stroke-dasharray":e.strokeDashArray}})]):e._c("svg",{staticClass:"ui-progress-circular__indeterminate",attrs:{role:"progressbar",viewBox:"25 25 50 50","aria-valuemax":100,"aria-valuemin":0}},[e._c("circle",{staticClass:"ui-progress-circular__indeterminate-path",attrs:{cx:"50",cy:"50",fill:"none",r:"20","stroke-miterlimit":"10","stroke-width":e.calculatedStroke}})])])])},staticRenderFns:[]}},function(e,t,i){var n=i(95);"string"==typeof n&&(n=[[e.i,n,""]]);i(9)(n,{});n.locals&&(e.exports=n.locals)},,,,,,,function(e,t,i){e.exports={default:i(112),__esModule:!0}},,,,,,,,function(e,t,i){var n=i(11),r=n.JSON||(n.JSON={stringify:JSON.stringify});e.exports=function(e){return r.stringify.apply(r,arguments)}},,,,function(e,t,i){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function r(e){return null!==e&&"object"===("undefined"==typeof e?"undefined":(0,f.default)(e))}function o(e,t){return e==t||!(!r(e)||!r(t))&&(0,u.default)(e)===(0,u.default)(t)}function s(e,t){for(var i=0;i<e.length;i++)if(o(e[i],t))return i;return-1}function a(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return e.substr(i,t.length)===t}Object.defineProperty(t,"__esModule",{value:!0});var l=i(104),u=n(l),c=i(45),f=n(c);t.isObject=r,t.looseEqual=o,t.looseIndexOf=s,t.startsWith=a},,,,,,,,,,,,,function(e,t,i){"use strict";function n(e,t){if(e){t=t||e.parentElement;var i=e.offsetTop,n=t.scrollTop,r=i+e.offsetHeight,o=t.offsetHeight;return i>=n&&r<=o}}function r(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{container:null,marginTop:0};e&&(t.container=t.container||e.parentElement,n(e,t.container)||(t.container.scrollTop=e.offsetTop-t.marginTop))}function o(e){e&&(e.scrollTop=0)}Object.defineProperty(t,"__esModule",{value:!0}),t.inView=n,t.scrollIntoView=r,t.resetScroll=o,t.default={inView:n,scrollIntoView:r,resetScroll:o}},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t,i){"use strict";function n(e,t){var i=t.length,n=e.length;if(n>i)return!1;if(n===i)return e===t;e:for(var r=0,o=0;r<n;r++){for(var s=e.charCodeAt(r);o<i;)if(t.charCodeAt(o++)===s)continue e;return!1}return!0}e.exports=n},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t,i){i(276);var n=i(8)(i(213),i(253),null,null);e.exports=n.exports},,,,,,,,,,,,,,,,,,,,,,function(e,t,i){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var r=i(104),o=n(r),s=i(39),a=n(s),l=i(92),u=n(l),c=i(248),f=n(c),p=i(73),d=n(p),h=i(160),g=n(h),v=i(116),m=i(129);t.default={name:"ui-select",props:{name:String,value:{type:[String,Number,Object,Array],required:!0},options:{type:Array,default:function(){return[]}},placeholder:String,icon:String,iconPosition:{type:String,default:"left"},label:String,floatingLabel:{type:Boolean,default:!1},type:{type:String,default:"basic"},multiple:{type:Boolean,default:!1},multipleDelimiter:{type:String,default:", "},hasSearch:{type:Boolean,default:!1},searchPlaceholder:{type:String,default:"Search"},filter:Function,disableFilter:{type:Boolean,default:!1},loading:{type:Boolean,default:!1},noResults:{type:Boolean,default:!1},keys:{type:Object,default:function(){return d.default.data.UiSelect.keys}},invalid:{type:Boolean,default:!1},help:String,error:String,disabled:{type:Boolean,default:!1}},data:function(){return{query:"",isActive:!1,isTouched:!1,selectedIndex:-1,highlightedIndex:-1,showDropdown:!1,initialValue:(0,o.default)(this.value)}},computed:{classes:function(){return["ui-select--type-"+this.type,"ui-select--icon-position-"+this.iconPosition,{"is-active":this.isActive},{"is-invalid":this.invalid},{"is-touched":this.isTouched},{"is-disabled":this.disabled},{"is-multiple":this.multiple},{"has-label":this.hasLabel},{"has-floating-label":this.hasFloatingLabel}]},labelClasses:function(){return{"is-inline":this.hasFloatingLabel&&this.isLabelInline,"is-floating":this.hasFloatingLabel&&!this.isLabelInline}},hasLabel:function(){return Boolean(this.label)||Boolean(this.$slots.default)},hasFloatingLabel:function(){return this.hasLabel&&this.floatingLabel},isLabelInline:function(){return 0===this.value.length&&!this.isActive},hasFeedback:function(){return Boolean(this.help)||Boolean(this.error)},showError:function(){return this.invalid&&Boolean(this.error)},showHelp:function(){return!this.showError&&Boolean(this.help)},filteredOptions:function(){var e=this;return this.disableFilter?this.options:this.options.filter(function(t,i){return e.filter?e.filter(t,e.query):e.defaultFilter(t,i)})},displayText:function(){var e=this;return this.multiple?this.value.length>0?this.value.map(function(t){return t[e.keys.label]||t}).join(this.multipleDelimiter):"":this.value?this.value[this.keys.label]||this.value:""},hasDisplayText:function(){return Boolean(this.displayText.length)},hasNoResults:function(){return!this.loading&&0!==this.query.length&&(this.disableFilter?this.noResults:0===this.filteredOptions.length)},submittedValue:function(){var e=this;if(this.name&&this.value)return Array.isArray(this.value)?this.value.map(function(t){return t[e.keys.value]||t}).join(","):this.value[this.keys.value]||this.value}},watch:{filteredOptions:function(){this.highlightedIndex=0,(0,m.resetScroll)(this.$refs.optionsList)},showDropdown:function(){this.showDropdown?(this.onOpen(),this.$emit("dropdown-open")):(this.onClose(),this.$emit("dropdown-close"))},query:function(){this.$emit("query-change",this.query)}},created:function(){this.value&&""!==this.value||this.setValue(null)},mounted:function(){document.addEventListener("click",this.onExternalClick)},beforeDestroy:function(){document.removeEventListener("click",this.onExternalClick)},methods:{setValue:function(e){e=e?e:this.multiple?[]:"",this.$emit("input",e),this.$emit("change",e)},highlightOption:function(e){
var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{autoScroll:!0};if(this.highlightedIndex!==e&&0!==this.$refs.options.length){var i=0,n=this.$refs.options.length-1;e<i?e=n:e>n&&(e=i),this.highlightedIndex=e,t.autoScroll&&this.scrollOptionIntoView(this.$refs.options[e].$el)}},selectHighlighted:function(e,t){this.$refs.options.length>0&&(t.preventDefault(),this.selectOption(this.$refs.options[e].option,e))},selectOption:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{autoClose:!0},n=this.multiple&&!this.isOptionSelected(e);this.multiple?this.updateOption(e,{select:n}):(this.setValue(e),this.selectedIndex=t),this.$emit("select",e,{selected:!this.multiple||n}),this.highlightedIndex=t,this.clearQuery(),!this.multiple&&i.autoClose&&this.closeDropdown()},isOptionSelected:function(e){return this.multiple?(0,v.looseIndexOf)(this.value,e)>-1:(0,v.looseEqual)(this.value,e)},updateOption:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{select:!0},i=[],n=!1,r=(0,v.looseIndexOf)(this.value,e);t.select&&r<0&&(i=this.value.concat(e),n=!0),!t.select&&r>-1&&(i=this.value.slice(0,r).concat(this.value.slice(r+1)),n=!0),n&&this.setValue(i)},defaultFilter:function(e){var t=this.query.toLowerCase(),i=e[this.keys.label]||e;return"string"==typeof i&&(i=i.toLowerCase()),(0,g.default)(t,i)},clearQuery:function(){this.query=""},toggleDropdown:function(){this[this.showDropdown?"closeDropdown":"openDropdown"]()},openDropdown:function(){this.disabled||(this.showDropdown=!0,this.isActive||(this.isActive=!0))},closeDropdown:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{autoBlur:!1};this.showDropdown=!1,this.isTouched||(this.isTouched=!0,this.$emit("touch")),e.autoBlur?this.isActive=!1:this.$refs.label.focus()},onFocus:function(e){this.isActive||(this.isActive=!0,this.$emit("focus",e))},onBlur:function(e){this.isActive=!1,this.$emit("blur",e),this.showDropdown&&this.closeDropdown({autoBlur:!0})},onOpen:function(){var e=this;this.$nextTick(function(){e.$refs[e.hasSearch?"searchInput":"dropdown"].focus(),e.scrollOptionIntoView(e.$refs.optionsList.querySelector(".is-selected"))})},onClose:function(){this.highlightedIndex=this.multiple?-1:this.selectedIndex},onExternalClick:function(e){this.$el.contains(e.target)||(this.showDropdown?this.closeDropdown({autoBlur:!0}):this.isActive&&(this.isActive=!1))},scrollOptionIntoView:function(e){(0,m.scrollIntoView)(e,{container:this.$refs.optionsList,marginTop:180})},reset:function(){this.setValue(JSON.parse(this.initialValue)),this.clearQuery(),this.resetTouched(),this.selectedIndex=-1,this.highlightedIndex=-1},resetTouched:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{touched:!1};this.isTouched=e.touched}},components:{UiIcon:a.default,UiProgressCircular:u.default,UiSelectOption:f.default}}},function(e,t,i){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var r=i(39),o=n(r);t.default={name:"ui-select-option",props:{option:{type:[String,Object],required:!0},type:{type:String,default:"basic"},multiple:{type:Boolean,default:!1},highlighted:{type:Boolean,default:!1},selected:{type:Boolean,default:!1},keys:{type:Object,default:function(){return{label:"label",image:"image"}}}},computed:{classes:function(){return["ui-select-option--type-"+this.type,{"is-highlighted":this.highlighted},{"is-selected":this.selected}]},imageStyle:function(){return{"background-image":"url("+this.option[this.keys.image]+")"}}},components:{UiIcon:o.default}}},,,,,,,,,,,,function(e,t,i){t=e.exports=i(7)(),t.push([e.i,".ui-select{-ms-flex-align:start;align-items:flex-start;display:-ms-flexbox;display:flex;font-family:Roboto,-apple-system,BlinkMacSystemFont,Segoe UI,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica,Arial,sans-serif;margin-bottom:1rem;outline:none;position:relative}.ui-select:hover:not(.is-disabled) .ui-select__label-text{color:rgba(0,0,0,.75)}.ui-select:hover:not(.is-disabled) .ui-select__display{border-bottom-color:rgba(0,0,0,.3)}.ui-select:hover:not(.is-disabled) .ui-select__dropdown-button{color:rgba(0,0,0,.87)}.ui-select.is-active:not(.is-disabled) .ui-select__icon-wrapper .ui-icon,.ui-select.is-active:not(.is-disabled) .ui-select__label-text{color:#2196f3}.ui-select.is-active:not(.is-disabled) .ui-select__display{border-bottom-color:#2196f3;border-bottom-width:2px}.ui-select.has-floating-label .ui-select__label-text{display:table}.ui-select.has-floating-label .ui-select__label-text.is-inline{color:rgba(0,0,0,.54);cursor:pointer;transform:translateY(1.625rem) scale(1.1)}.ui-select.has-floating-label .ui-select__label-text.is-floating{transform:translateY(0) scale(1)}.ui-select.has-label .ui-select__icon-wrapper{padding-top:1.5rem}.ui-select.has-label .ui-select__dropdown-button{top:1.6875rem}.ui-select:not(.is-multiple) .ui-select__display{height:2rem;line-height:1}.ui-select.is-multiple .ui-select__display{line-height:1.4;padding-bottom:.25rem;padding-top:.25rem}.ui-select.is-invalid:not(.is-disabled) .ui-select__icon-wrapper .ui-icon,.ui-select.is-invalid:not(.is-disabled) .ui-select__label-text{color:#f44336}.ui-select.is-invalid:not(.is-disabled) .ui-select__display{border-bottom-color:#f44336}.ui-select.is-invalid:not(.is-disabled) .ui-select__feedback{color:#f44336}.ui-select.is-disabled .ui-select__display{border-bottom-style:dotted;border-bottom-width:2px;color:rgba(0,0,0,.38);cursor:default}.ui-select.is-disabled .ui-select__display-value.is-placeholder,.ui-select.is-disabled .ui-select__dropdown-button{color:rgba(0,0,0,.38);opacity:.6}.ui-select.is-disabled .ui-select__icon-wrapper .ui-icon{opacity:.6}.ui-select.is-disabled .ui-select__feedback{opacity:.8}.ui-select__label{display:block;margin:0;outline:none;padding:0;position:relative;width:100%}.ui-select__icon-wrapper{-ms-flex-negative:0;flex-shrink:0;margin-right:.75rem;padding-top:.25rem}.ui-select__icon-wrapper .ui-icon{color:rgba(0,0,0,.54)}.ui-select__content{-ms-flex-positive:1;flex-grow:1}.ui-select__label-text{color:rgba(0,0,0,.54);font-size:.9375rem;line-height:normal;margin-bottom:0;transform-origin:left;transition:color .1s ease,transform .2s ease}.ui-select__display{-ms-flex-align:center;align-items:center;border:none;border-bottom-color:rgba(0,0,0,.12);border-bottom-style:solid;border-bottom-width:1px;color:rgba(0,0,0,.87);cursor:pointer;display:-ms-flexbox;display:flex;font-family:Roboto,-apple-system,BlinkMacSystemFont,Segoe UI,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica,Arial,sans-serif;font-size:1rem;font-weight:400;padding:0;transition:border .1s ease;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;width:100%}.ui-select__display-value{-ms-flex-positive:1;flex-grow:1}.ui-select__display-value.is-placeholder{color:rgba(0,0,0,.38)}.ui-select__dropdown-button{color:rgba(0,0,0,.54);font-size:1.125rem;margin-left:auto;margin-right:-.25rem}.ui-select__dropdown{background-color:#fff;box-shadow:1px 2px 8px #757575;color:rgba(0,0,0,.87);display:block;list-style-type:none;margin:0;margin-bottom:.5rem;min-width:11.25rem;outline:none;padding:0;position:absolute;width:100%;z-index:60}.ui-select__search-input{background:none;border:none;border-bottom-color:rgba(0,0,0,.12);border-bottom-style:solid;border-bottom-width:1px;border-radius:0;color:rgba(0,0,0,.87);cursor:auto;font-family:Roboto,-apple-system,BlinkMacSystemFont,Segoe UI,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica,Arial,sans-serif;font-size:.9375rem;font-weight:400;height:2.25rem;outline:none;padding:0 .75rem;padding-left:2.5rem;transition:border .1s ease;width:100%}.ui-select__search-input::-ms-clear{display:none}.ui-select__search-input:focus+.ui-select__search-icon{color:#2196f3}.ui-select__search-icon,.ui-select__search-progress{position:absolute;top:.5rem}.ui-select__search-icon{color:rgba(0,0,0,.54);font-size:1.25rem;left:.75rem}.ui-select__search-progress{right:.75rem}.ui-select__options{background-color:#fff;color:rgba(0,0,0,.87);display:block;list-style-type:none;margin:0;max-height:16rem;min-width:100%;overflow-y:auto;padding:0;position:relative}.ui-select__no-results{color:rgba(0,0,0,.54);font-size:.875rem;padding:.5rem .75rem;width:100%}.ui-select__feedback{color:rgba(0,0,0,.54);font-size:.875rem;line-height:1.2;margin:0;padding-top:.25rem;position:relative}.ui-select--icon-position-right .ui-select__icon-wrapper{margin-left:.5rem;margin-right:0;-ms-flex-order:1;order:1}.ui-select--transition-fade-enter-active,.ui-select--transition-fade-leave-active{transition:opacity .2s ease}.ui-select--transition-fade-enter,.ui-select--transition-fade-leave-active{opacity:0}",""])},,,function(e,t,i){t=e.exports=i(7)(),t.push([e.i,".ui-select-option{-ms-flex-align:center;align-items:center;cursor:pointer;display:-ms-flexbox;display:flex;font-family:Roboto,-apple-system,BlinkMacSystemFont,Segoe UI,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica,Arial,sans-serif;font-size:.9375rem;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.ui-select-option.is-selected{background-color:rgba(0,0,0,.05);color:#2196f3;font-weight:500}.ui-select-option.is-selected .ui-select-option__checkbox{color:#2196f3}.ui-select-option.is-highlighted{background-color:rgba(0,0,0,.1)}.ui-select-option__basic,.ui-select-option__image-text{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ui-select-option__image{display:-ms-flexbox;display:flex;-ms-flex-align:center;align-items:center}.ui-select-option__image-object{background-position:50%;background-size:cover;border-radius:50%;height:2rem;margin-right:.75rem;width:2rem}.ui-select-option__checkbox{color:rgba(0,0,0,.38);margin-left:auto}.ui-select-option--type-basic{padding:.375rem .75rem}.ui-select-option--type-image{padding:.25rem .75rem}",""])},,,,,,,,,,,,,,,,,,,function(e,t,i){i(279);var n=i(8)(i(214),i(256),null,null);e.exports=n.exports},,,,,function(e,t){e.exports={render:function(){var e=this;e.$createElement;return e._c("div",{staticClass:"ui-select",class:e.classes},[e.name?e._c("input",{staticClass:"ui-select__hidden-input",attrs:{type:"hidden",name:e.name},domProps:{value:e.submittedValue}}):e._e(),e._v(" "),e.icon||e.$slots.icon?e._c("div",{staticClass:"ui-select__icon-wrapper"},[e._t("icon",[e._c("ui-icon",{attrs:{icon:e.icon}})])],2):e._e(),e._v(" "),e._c("div",{staticClass:"ui-select__content"},[e._c("div",{ref:"label",staticClass:"ui-select__label",attrs:{tabindex:e.disabled?null:"0"},on:{click:e.toggleDropdown,focus:e.onFocus,keydown:[function(t){e._k(t.keyCode,"enter",13)||(t.preventDefault(),e.openDropdown(t))},function(t){e._k(t.keyCode,"space",32)||(t.preventDefault(),e.openDropdown(t))},function(t){e._k(t.keyCode,"tab",9)||e.onBlur(t)}]}},[e.label||e.$slots.default?e._c("div",{staticClass:"ui-select__label-text",class:e.labelClasses},[e._t("default",[e._v(e._s(e.label))])],2):e._e(),e._v(" "),e._c("div",{staticClass:"ui-select__display"},[e._c("div",{staticClass:"ui-select__display-value",class:{"is-placeholder":!e.hasDisplayText}},[e._v("\n "+e._s(e.hasDisplayText?e.displayText:e.hasFloatingLabel&&e.isLabelInline?null:e.placeholder)+"\n ")]),e._v(" "),e._c("ui-icon",{staticClass:"ui-select__dropdown-button"},[e._c("svg",{attrs:{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24"}},[e._c("path",{attrs:{d:"M6.984 9.984h10.03L12 15z"}})])])],1),e._v(" "),e._c("transition",{attrs:{name:"ui-select--transition-fade"}},[e._c("div",{directives:[{name:"show",rawName:"v-show",value:e.showDropdown,expression:"showDropdown"}],ref:"dropdown",staticClass:"ui-select__dropdown",attrs:{tabindex:"-1"},on:{keydown:[function(t){e._k(t.keyCode,"down",40)||(t.preventDefault(),e.highlightOption(e.highlightedIndex+1))},function(t){e._k(t.keyCode,"enter",13)||(t.preventDefault(),t.stopPropagation(),e.selectHighlighted(e.highlightedIndex,t))},function(t){e._k(t.keyCode,"esc",27)||(t.preventDefault(),e.closeDropdown())},function(t){e._k(t.keyCode,"tab",9)||e.onBlur(t)},function(t){e._k(t.keyCode,"up",38)||(t.preventDefault(),e.highlightOption(e.highlightedIndex-1))}]}},[e.hasSearch?e._c("div",{staticClass:"ui-select__search",on:{click:function(e){e.stopPropagation()},keydown:function(t){e._k(t.keyCode,"space",32)||t.stopPropagation()}}},[e._c("input",{directives:[{name:"model",rawName:"v-model",value:e.query,expression:"query"}],ref:"searchInput",staticClass:"ui-select__search-input",attrs:{autocomplete:"off",type:"text",placeholder:e.searchPlaceholder},domProps:{value:e._s(e.query)},on:{input:function(t){t.target.composing||(e.query=t.target.value)}}}),e._v(" "),e._c("ui-icon",{staticClass:"ui-select__search-icon"},[e._c("svg",{attrs:{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24"}},[e._c("path",{attrs:{d:"M9.516 14.016c2.484 0 4.5-2.016 4.5-4.5s-2.016-4.5-4.5-4.5-4.5 2.016-4.5 4.5 2.016 4.5 4.5 4.5zm6 0l4.97 4.97-1.5 1.5-4.97-4.97v-.797l-.28-.282c-1.126.984-2.626 1.547-4.22 1.547-3.61 0-6.516-2.86-6.516-6.47S5.906 3 9.516 3s6.47 2.906 6.47 6.516c0 1.594-.564 3.094-1.548 4.22l.28.28h.798z"}})])]),e._v(" "),e._c("ui-progress-circular",{directives:[{name:"show",rawName:"v-show",value:e.loading,expression:"loading"}],staticClass:"ui-select__search-progress",attrs:{size:20,stroke:4}})],1):e._e(),e._v(" "),e._c("ul",{ref:"optionsList",staticClass:"ui-select__options"},[e._l(e.filteredOptions,function(t,i){return e._c("ui-select-option",{ref:"options",refInFor:!0,attrs:{highlighted:e.highlightedIndex===i,keys:e.keys,multiple:e.multiple,option:t,selected:e.isOptionSelected(t),type:e.type},nativeOn:{click:function(n){n.stopPropagation(),e.selectOption(t,i)},mouseover:function(t){t.stopPropagation(),e.highlightOption(i,{autoScroll:!1})}}},[e._t("option",null,{highlighted:e.highlightedIndex===i,index:i,option:t,selected:e.isOptionSelected(t)})],2)}),e._v(" "),e._c("div",{directives:[{name:"show",rawName:"v-show",value:e.hasNoResults,expression:"hasNoResults"}],staticClass:"ui-select__no-results"},[e._t("no-results",[e._v("No results found")])],2)],2)])])],1),e._v(" "),e.hasFeedback?e._c("div",{staticClass:"ui-select__feedback"},[e.showError?e._c("div",{staticClass:"ui-select__feedback-text"},[e._t("error",[e._v(e._s(e.error))])],2):e.showHelp?e._c("div",{staticClass:"ui-select__feedback-text"},[e._t("help",[e._v(e._s(e.help))])],2):e._e()]):e._e()])])},staticRenderFns:[]}},,,function(e,t){e.exports={render:function(){var e=this;e.$createElement;return e._c("li",{staticClass:"ui-select-option",class:e.classes},[e._t("default",["basic"===e.type?e._c("div",{staticClass:"ui-select-option__basic"},[e._v("\n "+e._s(e.option[e.keys.label]||e.option)+"\n ")]):e._e(),e._v(" "),"image"===e.type?e._c("div",{staticClass:"ui-select-option__image"},[e._c("div",{staticClass:"ui-select-option__image-object",style:e.imageStyle}),e._v(" "),e._c("div",{staticClass:"ui-select-option__image-text"},[e._v(e._s(e.option[e.keys.label]))])]):e._e(),e._v(" "),e.multiple?e._c("div",{staticClass:"ui-select-option__checkbox"},[e.selected?e._c("ui-icon",[e._c("svg",{attrs:{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24"}},[e._c("path",{attrs:{d:"M9.984 17.016l9-9-1.406-1.453-7.594 7.594-3.563-3.563L5.016 12zm9-14.016C20.11 3 21 3.938 21 5.016v13.97C21 20.062 20.11 21 18.984 21H5.014C3.89 21 3 20.064 3 18.986V5.015C3 3.94 3.89 3 5.014 3h13.97z"}})])]):e._c("ui-icon",[e._c("svg",{attrs:{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24"}},[e._c("path",{attrs:{d:"M18.984 3C20.062 3 21 3.938 21 5.016v13.97C21 20.062 20.062 21 18.984 21H5.014C3.938 21 3 20.064 3 18.986V5.015C3 3.94 3.936 3 5.014 3h13.97zm0 2.016H5.014v13.97h13.97V5.015z"}})])])],1):e._e()])],2)},staticRenderFns:[]}},,,,,,,,,,,,,,,,,,,,function(e,t,i){var n=i(226);"string"==typeof n&&(n=[[e.i,n,""]]);i(9)(n,{});n.locals&&(e.exports=n.locals)},,,function(e,t,i){var n=i(229);"string"==typeof n&&(n=[[e.i,n,""]]);i(9)(n,{});n.locals&&(e.exports=n.locals)},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(e,t,i){e.exports=i(191)}])});
|
function generateHTML(processInstanceCounts) {
const body = processInstanceCounts
.map(
element => `<tr>
<td>${element.key}</td>
<td>${element.instanceCount}</td>
</tr>`
)
.join("\n");
return `
<section>
<div class="inner">
<h3>Camunda Cockpit Plugin</h3>
<table class="table table-bordered table-hover table-condensed">
<thead>
<tr>
<th>Key</th>
<th>Instances</th>
</tr>
</thead>
<tbody>
${body}
</tbody>
</table>
</div>
</section>`;
}
export default {
id: "cockpit-plugin",
pluginPoint: "cockpit.processes.dashboard",
priority: 12,
render: (container, { api }) => {
fetch(
`${api.cockpitApi}/plugin/cockpit-plugin/${api.engine}/process-instance`
).then(async res => {
const processInstanceCounts = await res.json();
container.innerHTML = generateHTML(processInstanceCounts);
});
}
};
|
import { SFRPG } from "../config.js"
import { RPC } from "../rpc.js";
const itemSizeArmorClassModifier = {
"fine": 8,
"diminutive": 4,
"tiny": 2,
"small": 1,
"medium": 0,
"large": 1,
"huge": 2,
"gargantuan": 4,
"colossal": 8
};
/**
* Override and extend the core ItemSheet implementation to handle SFRPG specific item types
* @type {ItemSheet}
*/
export class ItemSheetSFRPG extends ItemSheet {
constructor(...args) {
super(...args);
/**
* The tab being browsed
* @type {string}
*/
this._sheetTab = null;
/**
* The scroll position on the active tab
* @type {number}
*/
this._scrollTab = 100;
}
/* -------------------------------------------- */
static get defaultOptions() {
return mergeObject(super.defaultOptions, {
width: 715,
height: 600,
classes: ["sfrpg", "sheet", "item"],
resizable: true,
scrollY: [".tab.details"],
tabs: [
{navSelector: ".tabs", contentSelector: ".sheet-body", initial: "description"},
{navSelector: ".descTabs", contentSelector: ".desc-body", initial: "description"}
]
});
}
/* -------------------------------------------- */
/**
* Return a dynamic reference to the HTML template path used to render this Item Sheet
* @return {string}
*/
get template() {
const path = "systems/sfrpg/templates/items";
return `${path}/${this.item.data.type}.html`;
}
/* -------------------------------------------- */
parseNumber(value, defaultValue) {
if (value === 0 || value instanceof Number) return value;
else if (!value) return defaultValue;
let numericValue = Number(value);
if (Number.isNaN(numericValue)) {
return defaultValue;
}
return numericValue;
}
/**
* Prepare item sheet data
* Start with the base item data and extending with additional properties for rendering.
*/
getData() {
const data = super.getData();
data.labels = this.item.labels;
// Include CONFIG values
data.config = CONFIG.SFRPG;
// Item Type, Status, and Details
data.itemType = game.i18n.format(`ITEM.Type${data.item.type.titleCase()}`);
data.itemStatus = this._getItemStatus(data.item);
data.itemProperties = this._getItemProperties(data.item);
data.isPhysical = data.item.data.hasOwnProperty("quantity");
data.hasLevel = data.item.data.hasOwnProperty("level") && data.item.type !== "spell";
data.hasHands = data.item.data.hasOwnProperty("hands");
data.hasProficiency = data.item.data.proficient === true || data.item.data.proficient === false;
data.isFeat = this.type === "feat";
data.isVehicleAttack = data.item.type === "vehicleAttack";
data.isVehicleSystem = data.item.type === "vehicleSystem";
data.isGM = game.user.isGM;
// Physical items
const physicalItems = ["weapon", "equipment", "consumable", "goods", "container", "technological", "magic", "hybrid", "upgrade", "augmentation", "shield", "weaponAccessory"];
data.isPhysicalItem = physicalItems.includes(data.item.type);
// Item attributes
let itemData = this.item.data.data;
data.placeholders = {};
if (data.isPhysicalItem) {
if (itemData.attributes) {
let itemLevel = this.parseNumber(itemData.level, 1) + (itemData.attributes.customBuilt ? 2 : 0);
let sizeModifier = itemSizeArmorClassModifier[itemData.attributes.size];
let dexterityModifier = this.parseNumber(itemData.attributes.dex?.mod, -5);
data.placeholders.hardness = this.parseNumber(itemData.attributes.hardness, 5 + itemData.attributes.sturdy ? 2 * itemLevel : itemLevel);
data.placeholders.maxHitpoints = this.parseNumber(itemData.attributes.hp?.max, (itemData.attributes.sturdy ? 15 + 3 * itemLevel : 5 + itemLevel) + (itemLevel >= 15 ? 30 : 0));
data.placeholders.armorClass = this.parseNumber(itemData.attributes.ac, 10 + sizeModifier + dexterityModifier);
data.placeholders.dexterityModifier = dexterityModifier;
data.placeholders.sizeModifier = sizeModifier;
data.placeholders.savingThrow = {};
data.placeholders.savingThrow.formula = `@itemLevel + @owner.abilities.dex.mod`;
data.placeholders.savingThrow.value = this._computeSavingThrowValue(itemLevel, data.placeholders.savingThrow.formula);
} else {
let itemLevel = this.parseNumber(itemData.level, 1);
let sizeModifier = 0;
let dexterityModifier = -5;
data.placeholders.hardness = 5 + itemLevel;
data.placeholders.maxHitpoints = (5 + itemLevel) + (itemLevel >= 15 ? 30 : 0);
data.placeholders.armorClass = 10 + sizeModifier + dexterityModifier;
data.placeholders.dexterityModifier = dexterityModifier;
data.placeholders.sizeModifier = sizeModifier;
data.placeholders.savingThrow = {};
data.placeholders.savingThrow.formula = `@itemLevel + @owner.abilities.dex.mod`;
data.placeholders.savingThrow.value = this._computeSavingThrowValue(itemLevel, data.placeholders.savingThrow.formula);
}
}
data.selectedSize = (itemData.attributes && itemData.attributes.size) ? itemData.attributes.size : "medium";
// Category
data.category = this._getItemCategory(data.item);
// Armor specific details
data.isPowerArmor = data.item.data.hasOwnProperty("armor") && data.item.data.armor.type === 'power';
// Action Details
data.hasAttackRoll = this.item.hasAttack;
data.isHealing = data.item.data.actionType === "heal";
// Vehicle Attacks
if (data.isVehicleAttack) {
data.placeholders.savingThrow = {};
data.placeholders.savingThrow.value = data.item.data.save.dc;
}
data.modifiers = this.item.data.data.modifiers;
data.hasSpeed = this.item.data.data.weaponType === "tracking" || (this.item.data.data.special && this.item.data.data.special["limited"]);
data.hasCapacity = this.item.hasCapacity();
return data;
}
/* -------------------------------------------- */
_computeSavingThrowValue(itemLevel, formula) {
try {
const rollData = {
owner: this.item.actor ? duplicate(this.item.actor.data.data) : {abilities: {dex: {mod: 0}}},
item: duplicate(this.item.data.data),
itemLevel: itemLevel
};
if (!rollData.owner.abilities?.dex?.mod) {
rollData.owner.abilities = {dex: {mod: 0}};
}
const saveRoll = new Roll(formula, rollData).roll();
return saveRoll.total;
} catch (err) {
return 10;
}
}
/**
* Get the text item status which is shown beneath the Item type in the top-right corner of the sheet
* @return {string}
* @private
*/
_getItemStatus(item) {
if (["weapon", "equipment", "shield"].includes(item.type)) return item.data.equipped ? "Equipped" : "Unequipped";
else if (item.type === "starshipWeapon") return item.data.mount.mounted ? "Mounted" : "Not Mounted";
else if (item.type === "augmentation") return `${item.data.type} (${item.data.system})`;
else if (item.type === "vehicleSystem")
{
// Only systems which can be activated have an activation status
if (item.data.canBeActivated === false) {
return ""
}
return item.data.isActivated ? "Activated" : "Not Activated";
}
}
/* -------------------------------------------- */
/**
* Get the Array of item properties which are used in the small sidebar of the description tab
* @return {Array}
* @private
*/
_getItemProperties(item) {
const props = [];
const labels = this.item.labels;
if (item.type === "weapon") {
props.push(...Object.entries(item.data.properties)
.filter(e => e[1] === true)
.map(e => CONFIG.SFRPG.weaponProperties[e[0]]));
} else if (item.type === "spell") {
props.push(
labels.components,
labels.materials,
item.data.concentration ? "Concentration" : null,
item.data.sr ? "Spell Resistence" : null,
item.data.dismissible ? "Dismissible" : null
)
} else if (item.type === "equipment") {
props.push(CONFIG.SFRPG.armorTypes[item.data.armor.type]);
props.push(labels.armor);
} else if (item.type === "feat") {
props.push(labels.featType);
} else if (item.type === "starshipWeapon") {
props.push(CONFIG.SFRPG.starshipWeaponTypes[item.data.weaponType]);
props.push(CONFIG.SFRPG.starshipWeaponClass[item.data.class]);
} else if (item.type === "shield") {
if (item.data.dex) props.push(game.i18n.format("SFRPG.Items.Shield.Dex", { dex: item.data.dex.signedString() }));
if (item.data.acp) props.push(game.i18n.format("SFRPG.Items.Shield.ACP", { acp: item.data.acp.signedString() }));
let wieldedBonus = item.data.proficient ? item.data.bonus.wielded : 0;
let alignedBonus = item.data.proficient ? item.data.bonus.aligned : 0;
props.push(game.i18n.format("SFRPG.Items.Shield.ShieldBonus", { wielded: wieldedBonus.signedString(), aligned: alignedBonus.signedString() }));
}
// Action type
if (item.data.actionType) {
props.push(CONFIG.SFRPG.itemActionTypes[item.data.actionType]);
}
// Action usage
if ((item.type !== "weapon") && item.data.activation && !isObjectEmpty(item.data.activation)) {
props.push(
labels.activation,
labels.range,
labels.target,
labels.duration
)
}
return props.filter(p => !!p);
}
_getItemCategory(item) {
let category = {
enabled: false,
value: "",
tooltip: ""
};
if (item.type === "weapon") {
category.enabled = true;
category.value = SFRPG.weaponTypes[item.data.weaponType];
category.tooltip = "SFRPG.ItemSheet.Weapons.Category";
} else if (item.type === "equipment") {
category.enabled = true;
category.value = SFRPG.equipmentTypes[item.data.armor.type];
category.tooltip = "SFRPG.Items.Equipment.Category";
} else if (item.type === "consumable") {
category.enabled = true;
category.value = SFRPG.consumableTypes[item.data.consumableType];
category.tooltip = "SFRPG.ItemSheet.Consumables.Category";
}
return category;
}
/* -------------------------------------------- */
setPosition(position = {}) {
if (this._sheetTab === "details") position.height = "auto";
return super.setPosition(position);
}
/* -------------------------------------------- */
/* Form Submission */
/* -------------------------------------------- */
/**
* Extend the parent class _updateObject method to ensure that damage ends up in an Array
* @private
*/
_updateObject(event, formData) {
// Handle Damage Array
let damage = Object.entries(formData).filter(e => e[0].startsWith("data.damage.parts"));
formData["data.damage.parts"] = damage.reduce((arr, entry) => {
let [i, j] = entry[0].split(".").slice(3);
if (!arr[i]) arr[i] = [];
arr[i][j] = entry[1];
return arr;
}, []);
// Handle Critical Damage Array
let criticalDamage = Object.entries(formData).filter(e => e[0].startsWith("data.critical.parts"));
formData["data.critical.parts"] = criticalDamage.reduce((arr, entry) => {
let [i, j] = entry[0].split(".").slice(3);
if (!arr[i]) arr[i] = [];
arr[i][j] = entry[1];
return arr;
}, []);
// Handle Ability Adjustments array
let abilityMods = Object.entries(formData).filter(e => e[0].startsWith("data.abilityMods.parts"));
formData["data.abilityMods.parts"] = abilityMods.reduce((arr, entry) => {
let [i, j] = entry[0].split(".").slice(3);
if (!arr[i]) arr[i] = [];
arr[i][j] = entry[1];
return arr;
}, []);
// Update the Item
super._updateObject(event, formData);
}
/* -------------------------------------------- */
/**
* Activate listeners for interactive item sheet events
*/
activateListeners(html) {
super.activateListeners(html);
// Save scroll position
html.find(".tab.active")[0].scrollTop = this._scrollTab;
html.find(".tab").scroll(ev => this._scrollTab = ev.currentTarget.scrollTop);
// Modify damage formula
html.find(".damage-control").click(this._onDamageControl.bind(this));
html.find(".ability-adjustments-control").click(this._onAbilityAdjustmentsControl.bind(this));
html.find('.modifier-create').click(this._onModifierCreate.bind(this));
html.find('.modifier-edit').click(this._onModifierEdit.bind(this));
html.find('.modifier-delete').click(this._onModifierDelete.bind(this));
html.find('.modifier-toggle').click(this._onToggleModifierEnabled.bind(this));
html.find('.add-storage').click(this._onAddStorage.bind(this));
html.find('.remove-storage').click(this._onRemoveStorage.bind(this));
html.find('select[name="storage.type"]').change(this._onChangeStorageType.bind(this));
html.find('select[name="storage.subtype"]').change(this._onChangeStorageSubtype.bind(this));
html.find('input[name="storage.amount"]').change(this._onChangeStorageAmount.bind(this));
html.find('select[name="storage.weightProperty"]').change(this._onChangeStorageWeightProperty.bind(this));
html.find('input[class="storage.acceptsType"]').change(this._onChangeStorageAcceptsItem.bind(this));
html.find('input[name="storage.affectsEncumbrance"]').change(this._onChangeStorageAffectsEncumbrance.bind(this));
html.find('input[class="data.supportedSizes"]').change(this._onChangeSupportedStarshipSizes.bind(this));
}
/* -------------------------------------------- */
async _onAbilityAdjustmentsControl(event) {
event.preventDefault();
const a = event.currentTarget;
// Add new ability adjustment component
if (a.classList.contains("add-ability-adjustment")) {
await this._onSubmit(event);
const abilityMods = this.item.data.data.abilityMods;
return this.item.update({
"data.abilityMods.parts": abilityMods.parts.concat([
[0, ""]
])
});
}
// Remove an ability adjustment component
if (a.classList.contains("delete-ability-adjustment")) {
await this._onSubmit(event);
const li = a.closest(".ability-adjustment-part");
const abilityMods = duplicate(this.item.data.data.abilityMods);
abilityMods.parts.splice(Number(li.dataset.abilityAdjustment), 1);
return this.item.update({
"data.abilityMods.parts": abilityMods.parts
});
}
}
/**
* Add or remove a damage part from the damage formula
* @param {Event} event The original click event
* @return {Promise}
* @private
*/
async _onDamageControl(event) {
event.preventDefault();
const a = event.currentTarget;
// Add new damage component
if (a.classList.contains("add-damage")) {
await this._onSubmit(event); // Submit any unsaved changes
const damage = this.item.data.data.damage;
return this.item.update({
"data.damage.parts": damage.parts.concat([
["", ""]
])
});
}
// Remove a damage component
if (a.classList.contains("delete-damage")) {
await this._onSubmit(event); // Submit any unsaved changes
const li = a.closest(".damage-part");
const damage = duplicate(this.item.data.data.damage);
damage.parts.splice(Number(li.dataset.damagePart), 1);
return this.item.update({
"data.damage.parts": damage.parts
});
}
// Add new critical damage component
if (a.classList.contains("add-critical-damage")) {
await this._onSubmit(event); // Submit any unsaved changes
const criticalDamage = this.item.data.data.critical;
return this.item.update({
"data.critical.parts": criticalDamage.parts.concat([
["", ""]
])
});
}
// Remove a critical damage component
if (a.classList.contains("delete-critical-damage")) {
await this._onSubmit(event); // Submit any unsaved changes
const li = a.closest(".damage-part");
const criticalDamage = duplicate(this.item.data.data.critical);
criticalDamage.parts.splice(Number(li.dataset.criticalPart), 1);
return this.item.update({
"data.critical.parts": criticalDamage.parts
});
}
}
/**
* Add a modifer to this item.
*
* @param {Event} event The originating click event
*/
_onModifierCreate(event) {
event.preventDefault();
const target = $(event.currentTarget);
this.item.addModifier({
name: "New Modifier"
});
}
/**
* Delete a modifier from the item.
*
* @param {Event} event The originating click event
*/
async _onModifierDelete(event) {
event.preventDefault();
const target = $(event.currentTarget);
const modifierId = target.closest('.item.modifier').data('modifierId');
await this.item.deleteModifier(modifierId);
}
/**
* Edit a modifier for an item.
*
* @param {Event} event The orginating click event
*/
_onModifierEdit(event) {
event.preventDefault();
const target = $(event.currentTarget);
const modifierId = target.closest('.item.modifier').data('modifierId');
this.item.editModifier(modifierId);
}
/**
* Toggle a modifier to be enabled or disabled.
*
* @param {Event} event The originating click event
*/
async _onToggleModifierEnabled(event) {
event.preventDefault();
const target = $(event.currentTarget);
const modifierId = target.closest('.item.modifier').data('modifierId');
const modifiers = duplicate(this.item.data.data.modifiers);
const modifier = modifiers.find(mod => mod._id === modifierId);
modifier.enabled = !modifier.enabled;
await this.item.update({
'data.modifiers': modifiers
});
}
async _onAddStorage(event) {
event.preventDefault();
let storage = duplicate(this.item.data.data.container.storage);
storage.push({
type: "bulk",
subtype: "",
amount: 0,
acceptsType: [],
weightMultiplier: 1,
weightProperty: ""
});
await this.item.update({
"data.container.storage": storage
});
}
async _onRemoveStorage(event) {
event.preventDefault();
let li = $(event.currentTarget).parents(".storage-slot");
const slotIndex = li.attr("data-slot-index");
let storage = duplicate(this.item.data.data.container.storage);
storage.splice(slotIndex, 1);
await this.item.update({
"data.container.storage": storage
});
}
async _onChangeStorageType(event) {
event.preventDefault();
event.stopImmediatePropagation();
let li = $(event.currentTarget).parents(".storage-slot");
const slotIndex = li.attr("data-slot-index");
let storage = duplicate(this.item.data.data.container.storage);
storage[slotIndex].type = event.currentTarget.value;
if (storage[slotIndex].type === "bulk") {
storage[slotIndex].subtype = "";
storage[slotIndex].weightProperty = "bulk";
} else {
storage[slotIndex].weightProperty = "";
}
await this.item.update({
"data.container.storage": storage
});
}
async _onChangeStorageSubtype(event) {
event.preventDefault();
event.stopImmediatePropagation();
let li = $(event.currentTarget).parents(".storage-slot");
const slotIndex = li.attr("data-slot-index");
let storage = duplicate(this.item.data.data.container.storage);
storage[slotIndex].subtype = event.currentTarget.value;
await this.item.update({
"data.container.storage": storage
});
}
async _onChangeStorageAmount(event) {
event.preventDefault();
event.stopImmediatePropagation();
let li = $(event.currentTarget).parents(".storage-slot");
const slotIndex = li.attr("data-slot-index");
const inputNumber = Number(event.currentTarget.value);
if (!Number.isNaN(inputNumber)) {
let storage = duplicate(this.item.data.data.container.storage);
storage[slotIndex].amount = inputNumber;
await this.item.update({
"data.container.storage": storage
});
}
}
async _onChangeStorageWeightProperty(event) {
event.preventDefault();
event.stopImmediatePropagation();
let li = $(event.currentTarget).parents(".storage-slot");
const slotIndex = li.attr("data-slot-index");
let storage = duplicate(this.item.data.data.container.storage);
storage[slotIndex].weightProperty = event.currentTarget.value;
await this.item.update({
"data.container.storage": storage
});
}
async _onChangeStorageAcceptsItem(event) {
event.preventDefault();
event.stopImmediatePropagation();
let li = $(event.currentTarget).parents(".storage-slot");
const slotIndex = li.attr("data-slot-index");
const itemType = event.currentTarget.name;
const enabled = event.currentTarget.checked;
let storage = duplicate(this.item.data.data.container.storage);
if (enabled) {
if (!storage[slotIndex].acceptsType.includes(itemType)) {
storage[slotIndex].acceptsType.push(itemType);
}
} else {
if (storage[slotIndex].acceptsType.includes(itemType)) {
storage[slotIndex].acceptsType = storage[slotIndex].acceptsType.filter(x => x !== itemType);
}
}
await this.item.update({
"data.container.storage": storage
});
}
async _onChangeSupportedStarshipSizes(event) {
event.preventDefault();
event.stopImmediatePropagation();
const toggleSize = event.currentTarget.name;
const enabled = event.currentTarget.checked;
let supportedSizes = duplicate(this.item.data.data.supportedSizes);
if (enabled && !supportedSizes.includes(toggleSize)) {
supportedSizes.push(toggleSize);
} else if (!enabled && supportedSizes.includes(toggleSize)) {
supportedSizes = supportedSizes.filter(x => x !== toggleSize);
}
await this.item.update({
"data.supportedSizes": supportedSizes
});
}
async _onChangeStorageAffectsEncumbrance(event) {
event.preventDefault();
event.stopImmediatePropagation();
let li = $(event.currentTarget).parents(".storage-slot");
const slotIndex = li.attr("data-slot-index");
let storage = duplicate(this.item.data.data.container.storage);
storage[slotIndex].affectsEncumbrance = event.currentTarget.checked;
await this.item.update({
"data.container.storage": storage
});
}
/** @override */
async _render(...args) {
await super._render(...args);
if (this.rendered) {
tippy('[data-tippy-content]', {
allowHTML: true,
arrow: false,
placement: 'top-start',
duration: [500, null],
delay: [800, null]
});
}
}
}
|
import PropTypes from 'prop-types';
import React from 'react';
import Textarea from 'react-textarea-autosize';
export default class TextControl extends React.Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
forID: PropTypes.string,
value: PropTypes.node,
classNameWrapper: PropTypes.string.isRequired,
setActiveStyle: PropTypes.func.isRequired,
setInactiveStyle: PropTypes.func.isRequired,
};
/**
* Always update to ensure `react-textarea-autosize` properly calculates
* height. Certain situations, such as this widget being nested in a list
* item that gets rearranged, can leave the textarea in a minimal height
* state. Always updating should generally be low cost, but this should be
* optimized in the future.
*/
shouldComponentUpdate(nextProps) {
return true;
}
render() {
const {
forID,
value,
onChange,
classNameWrapper,
setActiveStyle,
setInactiveStyle,
} = this.props;
return (
<Textarea
id={forID}
value={value || ''}
className={classNameWrapper}
onFocus={setActiveStyle}
onBlur={setInactiveStyle}
style={{ minHeight: '140px' }}
onChange={e => onChange(e.target.value)}
/>
);
}
}
|
'use strict';
const path = require('path');
const stringUtil = require('ember-cli-string-utils');
const pathUtil = require('ember-cli-path-utils');
const getPathOption = require('ember-cli-get-component-path-option');
const normalizeEntityName = require('ember-cli-normalize-entity-name');
const isModuleUnificationProject = require('../module-unification').isModuleUnificationProject;
module.exports = {
description: 'Generates a component.',
availableOptions: [
{
name: 'path',
type: String,
default: 'components',
aliases: [{ 'no-path': '' }],
},
],
filesPath: function() {
let filesDirectory = 'files';
if (isModuleUnificationProject(this.project)) {
filesDirectory = 'module-unification-files';
}
return path.join(this.path, filesDirectory);
},
fileMapTokens: function() {
if (isModuleUnificationProject(this.project)) {
return {
__root__(options) {
if (options.inRepoAddon) {
return path.join('packages', options.inRepoAddon, 'src');
}
if (options.inDummy) {
return path.join('tests', 'dummy', 'src');
}
return 'src';
},
__path__(options) {
return path.join('ui', 'components', options.dasherizedModuleName);
},
};
} else {
return {
__path__: function(options) {
if (options.pod) {
return path.join(options.podPath, options.locals.path, options.dasherizedModuleName);
} else {
return 'components';
}
},
__templatepath__: function(options) {
if (options.pod) {
return path.join(options.podPath, options.locals.path, options.dasherizedModuleName);
}
return 'templates/components';
},
__templatename__: function(options) {
if (options.pod) {
return 'template';
}
return options.dasherizedModuleName;
},
};
}
},
normalizeEntityName: function(entityName) {
return normalizeEntityName(entityName);
},
locals: function(options) {
let templatePath = '';
let importTemplate = '';
let contents = '';
// if we're in an addon, build import statement
if (options.project.isEmberCLIAddon() || (options.inRepoAddon && !options.inDummy)) {
if (options.pod) {
templatePath = './template';
} else {
templatePath =
pathUtil.getRelativeParentPath(options.entity.name) +
'templates/components/' +
stringUtil.dasherize(options.entity.name);
}
importTemplate = "import layout from '" + templatePath + "';\n";
contents = '\n layout';
}
return {
importTemplate: importTemplate,
contents: contents,
path: getPathOption(options),
};
},
};
|
//@ts-check
/**
* How warnings and checks are handles, eg missing type annotations etc.
* - `fatal`: Throw an error and make the build fail.
* - `error`: Log an error at the error level, but continue
* - `warning`: Log the message at the warning level, and continue
* - `info`: Log the message at the info level
* - `level`: Ignore and proceed
* @type {{[P in SeverityLevel]: SeverityLevel}}
*/
const Level = {
error: "error",
fatal: "fatal",
ignore: "ignore",
info: "info",
warning: "warning",
};
/** @type {SeveritySettingsConfig} */
const DefaultSeveritySettings = {
unsupportedTag: Level.fatal,
codeDuplicateProperty: Level.fatal,
codeDuplicateMethod: Level.fatal,
docOnGetterAndSetter: Level.fatal,
docParseError: Level.fatal,
namespaceInvalidMethodSignature: Level.fatal,
tsDiagnosticsError: Level.fatal,
tsDiagnosticsWarning: Level.warning,
tsDiagnosticsSuggestion: Level.info,
tsDiagnosticsMessage: Level.info,
tsSuperfluousOverride: Level.fatal,
tsMissingParentDoc: Level.fatal,
tsMissingOverride: Level.fatal,
tagTooFewParams: Level.fatal,
tagInitializerForRest: Level.fatal,
tagNotPlain: Level.fatal,
tagOptionalForRest: Level.fatal,
tagNameInvalidIndex: Level.fatal,
tagInvalidPattern: Level.fatal,
tagTypeOnDestructuredParameter: Level.fatal,
tagReadonlyWithSetter: Level.fatal,
tagConflictingConstantType: Level.fatal,
tagConflictingParamInitializers: Level.fatal,
tagConflictingPatternInitializers: Level.fatal,
tagConflictingMethodAndProp: Level.fatal,
tagConflictingMethodInComments: Level.fatal,
tagConflictingPropInComments: Level.fatal,
tagMissingConstant: Level.fatal,
tagMissingIdentParameter: Level.fatal,
tagMissingFunction: Level.fatal,
tagMissingMethod: Level.fatal,
tagMissingName: Level.fatal,
tagMissingNext: Level.fatal,
tagMissingParam: Level.fatal,
tagMissingParamForStructure: Level.fatal,
tagMissingParentProp: Level.fatal,
tagMissingPattern: Level.fatal,
tagMissingReturn: Level.fatal,
tagMissingStructure: Level.fatal,
tagMissingType: Level.fatal,
tagMissingYield: Level.fatal,
tagMissingTypedef: Level.fatal,
tagDuplicateAbstract: Level.fatal,
tagDuplicateAsync: Level.fatal,
tagDuplicateClassOrInterface: Level.fatal,
tagDuplicateDefault: Level.fatal,
tagDuplicateExtends: Level.fatal,
tagDuplicateGenerator: Level.fatal,
tagDuplicateImplements: Level.fatal,
tagDuplicateMethod: Level.fatal,
tagDuplicateNext: Level.fatal,
tagDuplicateParameter: Level.fatal,
tagDuplicatePattern: Level.fatal,
tagDuplicateReadonly: Level.fatal,
tagDuplicateReturn: Level.fatal,
tagDuplicateStructure: Level.fatal,
tagDuplicateTemplate: Level.fatal,
tagDuplicateThis: Level.fatal,
tagDuplicateType: Level.fatal,
tagDuplicateVisibilityModifier: Level.fatal,
tagDuplicateYield: Level.fatal,
tagSuperfluousReturn: Level.fatal,
tagSuperfluousParameter: Level.fatal,
tagSuperfluousDesc: Level.fatal,
tagSuperfluousNext: Level.fatal,
tagSuperfluousType: Level.fatal,
tagSuperfluousPattern: Level.fatal,
tagSuperfluousYield: Level.fatal,
tagSuperfluousTypedef: Level.fatal,
propDuplicateIfaceOrClass: Level.fatal,
propInvalidIfaceOrClass: Level.fatal,
tagOverriddenMissingDesc: Level.ignore,
symbolOverriddenMissingDesc: Level.ignore,
symbolMissingDesc: Level.fatal,
propMissingDesc: Level.fatal,
tagMissingDesc: Level.fatal,
tagParamMissingDesc: Level.fatal,
tagReturnMissingDesc: Level.fatal,
tagTemplateMissingDesc: Level.fatal,
tagTypedefMissingDesc: Level.fatal,
};
/**
* @param {string | undefined} setting
* @return {setting is keyof SeveritySettingsConfig}
*/
function isSeveritySetting(setting) {
return setting !== undefined && setting in DefaultSeveritySettings;
}
/**
* @param {string | undefined} level
* @return {level is SeverityLevel}
*/
function isSeverityLevel(level) {
return level !== undefined && level in Level;
}
/**
* Creates the default severity level of various checks.
* @param {Partial<SeveritySettingsConfig>} overrides
* @return {SeveritySettingsConfig}
*/
function createDefaultSeveritySettings(overrides = {}) {
return Object.assign({}, DefaultSeveritySettings, overrides);
}
function getSortedSeveritySettingKeys() {
return Object.keys(DefaultSeveritySettings).sort();
}
module.exports = {
createDefaultSeveritySettings,
getSortedSeveritySettingKeys,
isSeverityLevel,
isSeveritySetting,
Level,
};
|
import React from 'react';
// Material UI
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';
import Checkbox from '@material-ui/core/Checkbox';
import IconButton from '@material-ui/core/IconButton';
import DeleteIcon from '@material-ui/icons/Delete';
import EditIcon from '@material-ui/icons/Edit';
import Avatar from '@material-ui/core/Avatar';
export default class ItemListComponent extends React.PureComponent {
constructor(arg){
super(arg);
this.state = {
uploadImageVisible : false
};
}
remove() {
this.props.remove(this.props.item);
}
toggleVisible(){
this.props.toggleVisible(this.props.item);
}
render(){
let styleClass = this.props.item.edited ? 'adminListComponent-edit' : 'adminListComponent';
return <TableRow
className={styleClass}
onClick={() => { this.props.edit(this.props.item); }
}
style={{ cursor: 'pointer' }}
>
<TableCell>{this.props.item.category.title}</TableCell>
<TableCell>
<Avatar
alt="Thumbnail" src={this.props.item.image.source}/>
</TableCell>
<TableCell>{this.props.item.name}</TableCell>
<TableCell style={wrapping}>{this.props.item.info}</TableCell>
<TableCell>
<Checkbox
checked={this.props.item.visible ? true : false}
// onChange={this.toggleVisible.bind(this)}
onClick={(event) => {
event.stopPropagation();
this.toggleVisible();
}}
/>
</TableCell>
<TableCell>
<IconButton onClick={(event) => {
event.stopPropagation();
this.props.toggleDialog('DELETE', this.props.item.name, this.props.item);
}}>
<DeleteIcon />
</IconButton>
</TableCell>
{/* <TableCell>
<IconButton onClick={() => this.props.edit(this.props.item)}>
<EditIcon />
</IconButton>
</TableCell> */}
</TableRow>
;
}
}
const wrapping = {
maxWidth: '50px',
wordWrap: 'break-word'
};
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
import yaml
from airflow.contrib.kubernetes.pod import Pod
from airflow.contrib.kubernetes.kubernetes_request_factory.kubernetes_request_factory \
import KubernetesRequestFactory
class SimplePodRequestFactory(KubernetesRequestFactory):
"""
Request generator for a simple pod.
"""
_yaml = """apiVersion: v1
kind: Pod
metadata:
name: name
spec:
containers:
- name: base
image: airflow-worker:latest
command: ["/usr/local/airflow/entrypoint.sh", "/bin/bash sleep 25"]
restartPolicy: Never
"""
def __init__(self):
pass
def create(self, pod):
# type: (Pod) -> dict
req = yaml.safe_load(self._yaml)
self.extract_name(pod, req)
self.extract_labels(pod, req)
self.extract_image(pod, req)
self.extract_image_pull_policy(pod, req)
self.extract_cmds(pod, req)
self.extract_args(pod, req)
self.extract_node_selector(pod, req)
self.extract_env_and_secrets(pod, req)
self.extract_volume_secrets(pod, req)
self.attach_ports(pod, req)
self.attach_volumes(pod, req)
self.attach_volume_mounts(pod, req)
self.extract_resources(pod, req)
self.extract_service_account_name(pod, req)
self.extract_init_containers(pod, req)
self.extract_image_pull_secrets(pod, req)
self.extract_annotations(pod, req)
self.extract_affinity(pod, req)
self.extract_hostnetwork(pod, req)
self.extract_tolerations(pod, req)
self.extract_security_context(pod, req)
self.extract_dnspolicy(pod, req)
return req
class ExtractXcomPodRequestFactory(KubernetesRequestFactory):
"""
Request generator for a pod with sidecar container.
"""
XCOM_MOUNT_PATH = '/airflow/xcom'
SIDECAR_CONTAINER_NAME = 'airflow-xcom-sidecar'
_yaml = """apiVersion: v1
kind: Pod
metadata:
name: name
spec:
volumes:
- name: xcom
emptyDir: {{}}
containers:
- name: base
image: airflow-worker:latest
command: ["/usr/local/airflow/entrypoint.sh", "/bin/bash sleep 25"]
volumeMounts:
- name: xcom
mountPath: {xcomMountPath}
- name: {sidecarContainerName}
image: python:3.5-alpine
command:
- python
- -c
- |
import time
while True:
try:
time.sleep(3600)
except KeyboardInterrupt:
exit(0)
volumeMounts:
- name: xcom
mountPath: {xcomMountPath}
restartPolicy: Never
""".format(xcomMountPath=XCOM_MOUNT_PATH, sidecarContainerName=SIDECAR_CONTAINER_NAME)
def __init__(self):
pass
def create(self, pod):
# type: (Pod) -> dict
req = yaml.safe_load(self._yaml)
self.extract_name(pod, req)
self.extract_labels(pod, req)
self.extract_image(pod, req)
self.extract_image_pull_policy(pod, req)
self.extract_cmds(pod, req)
self.extract_args(pod, req)
self.extract_node_selector(pod, req)
self.extract_env_and_secrets(pod, req)
self.extract_volume_secrets(pod, req)
self.attach_ports(pod, req)
self.attach_volumes(pod, req)
self.attach_volume_mounts(pod, req)
self.extract_resources(pod, req)
self.extract_service_account_name(pod, req)
self.extract_init_containers(pod, req)
self.extract_image_pull_secrets(pod, req)
self.extract_annotations(pod, req)
self.extract_affinity(pod, req)
self.extract_hostnetwork(pod, req)
self.extract_tolerations(pod, req)
self.extract_security_context(pod, req)
self.extract_dnspolicy(pod, req)
return req
|
$(document).ready(function(){
var stored_lesson_data = '';
var result_pool = [];
var content_pool = [];
var active_content = "";
var active_content_data = {};
var content_order = [];
var lesson_data = {};
var active_portal = "youtube";
var url = $("#url").val();
var blackboard_id = $("#blackboard_id").val();
var lesson_id = $("#lesson_id").val();
var main_url = $("#main_url").val();
var assigned = $("#assigned").val();
var education_level = $("#education_level").val();
var image_resources = $("#image_resources").val();
var account_id = $("#account_id").val();
var start_url = $("#start_url").val();
var google_meet = $("#google_meet").val();
var checked_ids = [];
var role = $("#role").val();
var role2 = $("#role").val();
var folders = "#folder_1,#folder_2,#folder_3,#folder_4,#folder_5";
var folder_names = "Engage,Explore,Explain,Explain,Explore";
var youtube_looper = 0;
var google_looper = 0;
if(education_level=="tertiary"){
folder_names = "Introduction,Lesson Proper,Examination";
folders = "#folder_1,#folder_2,#folder_3";
}
var the_learning_plan = tinymce.init({
selector: '.tinymce',
plugins: 'advlist autolink lists link image charmap print preview hr anchor pagebreak paste',
toolbar_mode: 'floating',
paste_data_images: true,
height : "700",
});
var jstree = $('#jstree_demo_div').jstree({
"checkbox" : {
"keep_selected_style" : false
},
"plugins" : [ "checkbox" ]
});
$(".notification_control").hide();
$("select").on("click" , function() {
$(this).parent(".select-box").toggleClass("open");
});
$(document).mouseup(function (e)
{
var container = $(".select-box");
if (container.has(e.target).length === 0)
{
container.removeClass("open");
}
});
$("select").on("change" , function() {
var selection = $(this).find("option:selected").text(),
labelFor = $(this).attr("id"),
label = $("[for='" + labelFor + "']");
label.find(".label-desc").html(selection);
change_detected();
});
if($("#lesson_type").val()=="classroom"){
$(".notification_control").hide();
}else if($("#lesson_type").val()=="virtual"){
$(".notification_control").show();
$(".start_class").find("span").text("Start Meet");
$(".start_class").find("img").attr("src",image_resources+"google_meet.png");
$(".virtual_link").attr("href",google_meet);
}else if($("#lesson_type").val()=="zoom"){
$(".notification_control").show();
var zoom_link = main_url+"lms/lesson/zoom_checker/"+lesson_id;
$(".start_class").find("span").text("Start Zoom");
$(".start_class").find("img").attr("src",image_resources+"zoom.png");
$(".virtual_link").attr("href",zoom_link);
}
$.each($(".select"),function(key,value){
var selection = $(this).find("option:selected").text(),
labelFor = $(this).attr("id"),
label = $("[for='" + labelFor + "']");
label.find(".label-desc").html(selection);
});
if(assigned){
$.each(assigned.split(","),function(key,value){
checked_ids.push("student_"+value);
});
$.jstree.reference('#jstree_demo_div').select_node(checked_ids);
}
function unescapeHtml(safe) {
return safe.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'");
}
var view_text = new Quill('#view_text', {
theme: 'snow',
"modules": {
"toolbar": false
}
});
$("#view_text").hide();
// deploy_stored_data(stored_lesson_data);
adjust_iframe();
$(".instruction").hide();
$(".instructions").show();
$(".upload_actions").hide();
$("loader").show();
$(document).ready(function(){
$(".loader").hide();
});
var key = "AIzaSyDPVDhRW5LcKc7giRwsZtyHSDE_3O2TXsI";
var cx = "005829641482717962768:2e59rdva9xk";
var youtube_keys = [
"AIzaSyCQABaeip2nXZiL5sr1aTf0Oq3VbfPK_-k",
"AIzaSyDPVDhRW5LcKc7giRwsZtyHSDE_3O2TXsI",
"AIzaSyDsB_WGyzL6VpZcoxoCRGTclvh5nkWixJc",
"AIzaSyA3pDViRGgZvU1n7GcvTlbs533Nkf5z4co",
"AIzaSyBpB251vsnGdn7P0t2EOuBX7AtW05bYYws",
"AIzaSyAvtCp9gxcaFC5WvOdioqLH47r_lacdyCs",
"AIzaSyA3eZ1yVlYplPkiwNJUhbqrDG-GSm8NcyE",
"AIzaSyDb3Ct7i14iJuTnIVitiE5zAV3WpYEQOZU",
"AIzaSyB9TfPawPi4983afD7iS4T6tLk3IX1DQRU",
"AIzaSyBCBJ4M9e8UwwheDswtzeEzQet2NqpNqXk",
"AIzaSyCgCYgXFwxGQDXXJ5HQLT1-y3RHQgFeR6A",
"AIzaSyBdGeCpF6CKj-MV7u4Y7Y0vpPN734kEQ7Q",
"AIzaSyDjQcoNgTCMQ-3UNZKyKlUjvu_rTLMiGrk",
"AIzaSyD5XJk6zChsrNOAkNAFq03Uimzd6snZmZU",
"AIzaSyDprs4aO50BEfUw9JnQtCLEk2A2dwjUNU8",
"AIzaSyCqUeIDK547rVKmvRAqGJ9DHBGsI43geFg",
"AIzaSyAQXo8CIgqtXrrdPZP-JjNXHCHCwRiL5hU",
"AIzaSyClbNhvbQU9A8zdtXAOhOzdaQfWxG77Dpg",
"AIzaSyB6qupMjROOkodPGKk8cztd_I06HNP63Cc",
"AIzaSyBdGeCpF6CKjMV7u4Y7Y0vpPN734kEQ7Q",
];
var google_keys = [
"AIzaSyCa2SdElivdp3iAh3d25YGP5mhkYyTXgxs",
"AIzaSyDPVDhRW5LcKc7giRwsZtyHSDE_3O2TXsI",
"AIzaSyDixpRH3jO6vOJir4JnDA1U_8DYGfOtvHo",
"AIzaSyCKCH9YY-tNPS_hCfjdwv2gQkbVuFL67f4",
];
// window.addEventListener("resize", adjust_iframe());
function youtube_search(query,maxResults = 5){
var youtube_api = "https://www.googleapis.com/youtube/v3/search?part=snippet&q="+query+"&type=video&maxResults="+maxResults+"&key="+youtube_keys[youtube_looper];
$.ajax({
url: youtube_api,
context: document.body
}).done(function(data) {
console.log(google_keys[google_looper]+" Worked");
var processed_data = process_data(data,"youtube");
result_pool = processed_data;
populate_search_content(processed_data);
}).error(function(){
console.log(youtube_keys[youtube_looper]+" Did not work!");
youtube_looper++;
youtube_search();
});
}
function google_search(query,maxResults = 5){
var api = "https://www.googleapis.com/customsearch/v1?key="+google_keys[google_looper]+"&cx="+cx+"&q="+query;
$.ajax({
url: api,
context: document.body
}).done(function(data) {
console.log(google_keys[google_looper]+" Worked");
var processed_data = process_data(data,"google");
result_pool = processed_data;
populate_search_content(processed_data);
}).error(function(){
console.log(google_keys[google_looper]+" Did not work!");
google_looper++;
google_search();
});
}
function google_image_search(query,maxResults = 10){
var api = "https://www.googleapis.com/customsearch/v1?key="+google_keys[google_looper]+"&cx="+cx+"&searchType=image&q="+query;
$.ajax({
url: api,
context: document.body
}).done(function(data) {
var processed_data = process_data(data,"google_image");
result_pool = processed_data;
populate_search_content(processed_data);
}).error(function(){
console.log(google_keys[google_looper]+" Did not work!");
google_looper++;
google_search();
});
}
function my_resources_search(query){
var api = url+"my_resources/"+query;
$.ajax({
url: api,
context: document.body
}).done(function(data) {
var processed_data = process_data(data,"my_resources");
result_pool = processed_data;
populate_search_content(processed_data);
});
}
function cms_resources_search(query){
var api = url+"cms_resources/"+query;
$.ajax({
url: api,
context: document.body
}).done(function(data) {
var processed_data = process_data(data,"cms_resources");
result_pool = processed_data;
populate_search_content(processed_data);
});
}
function reset_result_pool(){
result_pool = {};
}
function portal_change(portal_name){
active_portal = portal_name;
$(".instruction").hide();
$(".upload_actions").hide();
if(active_portal=="my_resources"){
$(".my_resources_instructions").show();
$(".upload_actions").show();
}else if(active_portal=="cms_resources"){
$(".cms_resources_instructions").show();
}else{
$(".instructions").show();
}
}
function reset_population(){
$(".content_result").remove();
reset_result_pool();
}
function generate_id(){
var n = new Date().getTime();
return n;
}
function sort_content_order(){
content_order = [];
$.each($(".folder_contents"),function(key,ul){
$.each($(ul).find("li"),function(li_key,li_value){
content_order.push($(li_value).attr("result_id"));
});
});
change_detected();
}
function process_data(data,type){
var data_population = [];
switch(type) {
case "youtube":
data.items.forEach(function(item, index, arr){
data_population[index] = {
result_id:generate_id()+"_"+index,
title:item.snippet.title,
description:item.snippet.description,
image:encodeURIComponent(item.snippet.thumbnails.high.url),
type:"youtube",
source: encodeURIComponent("https://www.youtube.com/embed/"+item.id.videoId),
};
});
return data_population;
break;
case "google":
data.items.forEach(function(item, index, arr){
var has_pagemap = item.hasOwnProperty("pagemap");
var has_image = false;
if(has_pagemap){
has_image = item.pagemap.hasOwnProperty("cse_image");
}
data_population[index] = {
result_id:generate_id()+"_"+index,
title:item.title,
description:item.snippet,
image:$("#lms_link").val()+"images/website.png",
type:"website",
source:encodeURIComponent(item.link),
};
if(has_image){
data_population[index].image = encodeURIComponent(item.pagemap.cse_image[0].src);
}
});
return data_population;
break;
case "google_image":
data.items.forEach(function(item, index, arr){
data_population[index] = {
result_id:generate_id()+"_"+index,
title:item.title,
description:item.snippet,
image:encodeURIComponent(item.link),
type:"image",
source:encodeURIComponent(item.link),
};
});
return data_population;
break;
case "my_resources":
data = JSON.parse(data);
if(data){
$(".instruction").hide();
data.forEach(function(item, index, arr){
data_population[index] = {
result_id:generate_id()+"_"+index,
title:item.name,
description:item.description,
text_value:item.text_value,
type:item.type,
source:encodeURIComponent(main_url+'uploads/lms_my_resources/'+item.link),
};
if(item.type=="csv"||item.type=="xlsx"||item.type=="xls"){
data_population[index].image = encodeURIComponent(main_url+'backend/lms/images/excel.png');
}else if(item.type=="pptx"||item.type=="ppt"){
data_population[index].image = encodeURIComponent(main_url+'backend/lms/images/powerpoint.png');
}else if(item.type=="docx"||item.type=="doc"){
data_population[index].image = encodeURIComponent(main_url+'backend/lms/images/word.svg');
}else if(item.type=="image"){
data_population[index].image = encodeURIComponent(main_url+'uploads/lms_my_resources/'+item.link);
}else if(item.type=="video"){
data_population[index].image = encodeURIComponent(main_url+'backend/lms/images/video.svg');
}else if(item.type=="text"){
data_population[index].image = encodeURIComponent(main_url+'backend/lms/images/text.png');
}else if(item.type=="youtube"){
if(item.image){
data_population[index].image = encodeURIComponent(item.image);
}else{
data_population[index].image = encodeURIComponent(main_url+'backend/lms/images/video.svg');
}
data_population[index].source = encodeURIComponent(item.link);
}
else if(item.type=="website"){
data_population[index].image = encodeURIComponent(main_url+'backend/lms/images/video.svg');
data_population[index].source = encodeURIComponent(item.link);
}
});
}else{
$(".instruction").show();
}
return data_population;
break;
case "cms_resources":
data = JSON.parse(data);
if(data){
data.forEach(function(item, index, arr){
data_population[index] = {
result_id:generate_id()+"_"+index,
title:item.name,
description:item.description,
image:encodeURIComponent(item.link),
type:item.type,
source:main_url+'uploads/lms_cms_resources/'+item.filename,
};
});
console.log(data_population);
}
return data_population;
break;
default:
return null;
}
}
function update_active_content(data){
active_content = data;
}
function get_content_data(result_id) {
var return_data;
content_pool.forEach(function(item, index, arr){
if(result_id == item.content.result_id){
return_data = item;
}
});
return return_data;
}
function adjust_iframe(){
switch (screen.height) {
case 720:
// $(".student_view_content_iframe").css("height","537px");
break;
case 900:
// $(".student_view_content_iframe").css("height","717px");
break;
}
}
function render_student_view(){
$(".content_type").hide();
$(".video_content").attr("src","");
if(active_content_data){
$(".student_view_title").text(active_content_data.content.title);
switch (active_content_data.content.type){
case "youtube":
$(".student_view_content_iframe").show();
$(".student_view_content_iframe").attr("src",decodeURIComponent(active_content_data.content.source));
break;
case "image":
$(".image_content").show();
$(".image_content").css("height",screen.height);
$(".image_content").attr("src",decodeURIComponent(active_content_data.content.source));
$(".image_content").attr("data-src",decodeURIComponent(active_content_data.content.source));
$(document).find('[data-magnify=gallery]').magnify();
break;
case "video":
$(".video_content").show();
$(".video_content").css("height",screen.height-180);
$(".video_content").attr("src",decodeURIComponent(active_content_data.content.source));
$(".video_content").bind('contextmenu',function() { return false; });
break;
case "website":
$(".student_view_content_iframe").show();
$(".student_view_content_iframe").css("height",screen.height-180);
$(".student_view_content_iframe").attr("src",decodeURIComponent(active_content_data.content.source));
break;
case "pdf":
$(".student_view_content_iframe").show();
$(".student_view_content_iframe").css("height",screen.height-180);
$(".student_view_content_iframe").attr("src",$("#pdfjs").val()+active_content_data.content.source);
break;
case "text":
$(".html_content").show();
$(".html_content").css("height",screen.height-180);
$(".html_content").css("background-color","#d2cece");
view_text.setContents(JSON.parse(unescapeHtml(active_content_data.content.text_value)));
var rendered_text = view_text.container.innerHTML;
$(rendered_text).find("div[contenteditable*='true']").attr("contenteditable","false");
$(".html_content").html($(rendered_text).html());
break;
default:
$(".student_view_content_iframe").show();
$(".student_view_content_iframe").css("height",screen.height-180);
$(".student_view_content_iframe").attr("src",'https://view.officeapps.live.com/op/view.aspx?src='+decodeURIComponent(active_content_data.content.source)+'&embedded=true');
break;
}
$(".student_view_title").text(active_content_data.content.title);
}else{
}
}
function reset_student_view(){
$(".student_view_content_iframe").attr("src","");
}
function get_current_order(){
var return_key = 0;
$.each(content_order,function(key,value){
if(active_content_data.content.result_id==value){
return_key = key;
}
});
return return_key;
}
function get_slides(order){
active_content_data = get_content_data(content_order[order]);
active_content = content_order[order];
render_student_view();
}
function get_next(){
var end_order = content_order.length-1;
var current_order = get_current_order();
if(current_order<end_order){
var next_order = current_order+1;
active_content_data = get_content_data(content_order[next_order]);
active_content = content_order[next_order];
render_student_view();
}else{
$(".next").attr("disabled","disabled");
}
}
function get_previous(){
var current_order = get_current_order();
if(current_order>0){
var next_order = current_order-1;
active_content_data = get_content_data(content_order[next_order]);
active_content = content_order[next_order];
render_student_view();
}
}
function populate_slides(){
$(".actual_slide").remove();
$.each(content_order,function(key,value){
var new_slide = $(".slide_clone").clone();
new_slide.css("display","inline-block");
new_slide.addClass("actual_slide");
new_slide.removeClass("slide_clone");
var new_slide_data = decodeURIComponent(get_content_data(value).content.image);
new_slide.find("img").attr("src",new_slide_data);
$(".student_view_slides").append(new_slide);
});
check_active_thumbnail();
}
function check_active_thumbnail(){
$(document).find(".slide_active").removeClass("slide_active");
$.each(content_order,function(key,value){
if(active_content == value){
$(".actual_slide").eq(key).addClass("slide_active");
}
});
}
function remove_content(result_id){
content_order = $.grep(content_order, function(value) {
return value != result_id;
});
$.each(content_pool,function(key,value){
if(value){
if($.inArray(value.content.result_id, content_order)<0){
delete content_pool[key];
}
}
// if(value.content.result_id == result_id){
// content_pool.splice(key,1);
// }
});
var reiterate_content_pool = [];
$.each(content_pool,function(key,value){
if(value){
reiterate_content_pool.push(value);
}
});
content_pool = reiterate_content_pool;
}
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
function change_detected(){
var title = $(".title").val();
var update_url = $("#site_url").val();
var id = $("#lesson_id").val();
var lesson_type = $("#lesson_type").val();
var email_notification = $("#email_notification").prop("checked");
var allow_view = $("#allow_view").prop("checked");
var start_date = $(".date_range").data('daterangepicker').startDate.toDate();
var end_date = $(".date_range").data('daterangepicker').endDate.toDate();
// var learning_plan_text = JSON.stringify(learning_plan.getContents());
var subject_id = $("#subject").val();
var grade_id = $("#grade").val();
education_level = $("#education_level").val();
var term = $("#term").val();
var shared = $("#shared").val();
start_date = moment(start_date).format("YYYY-MM-DD HH:mm:ss");
end_date = moment(end_date).format("YYYY-MM-DD HH:mm:ss");
if(email_notification){
email_notification = "1";
}else{
email_notification = "0";
}
if(allow_view){
allow_view = "1";
}else{
allow_view = "0";
}
var student_ids = [];
$.each(jstree.jstree("get_checked",null,true),function(key,value){
if(value.includes('student')){
student_id = value.replace('student_','');
student_ids.push(student_id);
}
});
lesson_data = {
id:id,
title:title,
content_order:content_order,
content_pool:content_pool,
lesson_type:lesson_type,
email_notification:email_notification,
start_date:start_date,
end_date:end_date,
allow_view:allow_view,
learning_plan:tinymce.get('the_learning_plan').getContent(),
assigned:student_ids.join(','),
folder_names:"Engage,Explore,Explain,Extend,LAS",
subject_id:subject_id,
grade_id:grade_id,
education_level:education_level,
term:term,
shared:shared,
};
$.ajax({
url: update_url,
method:"POST",
data: lesson_data,
}).done(function(data) {
// console.log(data);
});
}
function deploy_stored_data(){
var id = $("#lesson_id").val();
var get_url = $("#url").val()+"get/"+id;
//jstree
var checked_ids = [];
if(assigned){
$.each(assigned.split(","),function(key,value){
checked_ids.push("student_"+value);
});
$.jstree.reference('#jstree_demo_div').select_node(checked_ids);
}
//jstree
$.ajax({
url: get_url,
method:"POST",
}).done(function(data) {
var parsed_data = JSON.parse(data);
content_order = JSON.parse(parsed_data.content_order);
if(JSON.parse(parsed_data.content_pool)){
content_pool = JSON.parse(parsed_data.content_pool);
}else{
content_pool = [];
}
folder_names = parsed_data.folder_names;
populate_content(content_pool);
});
}
$( function() {
$(folders+",#result_container" ).sortable({
connectWith: ".connectedSortable",
receive: function(event,ui) {
if (this === ui.item.parent()[0]) {
if(ui.item.parent().attr("id")!="result_container"){
$(ui.item[0]).removeClass('content_result');
$(ui.item[0]).addClass('content_already');
var result_id = $(ui.item[0]).attr("result_id");
result_pool.forEach(function(item, index, arr){
if(result_id==item.result_id){
item.status = "fresh";
item.state = "online";
item.blackboard_id = blackboard_id;
var folder_id = ui.item.parent().attr("id");
var content = {folder_id:folder_id,content:item}
content_pool.push(content);
}
});
}
}
sort_content_order();
},
stop:function(event,ui){
sort_content_order();
},
beforeStop: function(ev, ui) {
if ($(ui.item).hasClass('content_already') && $(ui.placeholder).parent()[0] != this) {
$(this).sortable('cancel');
}
}
}).disableSelection();
});
$("#learning_plan_save").click(function(){
change_detected();
alert("Learning Plan successfully saved");
});
$(".extremeright_icon").click(function(){
var portal_name = $(this).attr("portal");
$(".extremeright_icon").removeClass("icon_active");
$(this).addClass("icon_active");
portal_change(portal_name);
reset_population();
$(".submit_button").click();
});
$('.trigger').click(function() {
// $('.slider').toggleClass('close');
var trigger_id = $(this).attr("id");
if($('.'+trigger_id+'_slider').hasClass('close')){
$(".trigger").removeClass('active_trigger');
$('.slider').addClass('close');
$(this).addClass('active_trigger');
$('.'+trigger_id+'_slider').removeClass('close');
}else{
$(this).removeClass('active_trigger');
$('.'+trigger_id+'_slider').addClass('close');
}
});
$(".folder_container").hide();
$(".folder_container").eq(0).show();
$(".folder").click(function(){
var folder_index = $(this).index();
$('.folder').removeClass('folder_active');
$(this).addClass('folder_active');
$(".folder_container").hide();
$(".folder_container").eq(folder_index).show();
});
function populate_search_content(data){
var populous = $(".content_hidden").clone();
data.forEach(function(item, index, arr){
populous = $(".content_hidden").clone();
$(populous).removeClass("content_hidden");
$(populous).addClass("content_result");
$(populous).show();
switch(item.type) {
case "youtube":
$(populous).find(".theme").css("background-color","rgb(255, 68, 68)");
break;
case "website":
$(populous).find(".theme").css("background-color","rgb(0, 84, 169)");
break;
case "image":
$(populous).find(".theme").css("background-color","rgb(56, 177, 55)");
break;
case "csv"||"xls"||"xlsx":
$(populous).find(".theme").css("background-color","rgb(33, 115, 70)");
break;
case "text":
$(populous).find(".theme").css("background-color","rgb(33, 115, 70)");
break;
case "docx":
$(populous).find(".theme").css("background-color","rgb(42, 86, 153)");
break;
case "epub":
$(populous).find(".theme").css("background-color","rgb(56, 177, 55)");
break;
case "pptx":
$(populous).find(".theme").css("background-color","rgb(56, 177, 55)");
break;
}
if(item.type!="text"){
$(populous).attr("result_id",item.result_id);
$(populous).find(".content_header").find("span").text(item.title);
$(populous).find(".content_body").find("img").attr("src",decodeURIComponent(item.image));
$(populous).find(".content_footer").find("textarea").text(item.description);
$(".search_content").last().after($(populous));
}else{
$(populous).attr("result_id",item.result_id);
$(populous).find(".content_header").find("span").text(item.title);
$(populous).find(".content_body").find("img").after("<div id='"+item.result_id+"' class='text_content'></div>");
$(populous).find(".content_body").find("img").remove();
view_text.setContents(JSON.parse(unescapeHtml(item.text_value)));
$(populous).find(".content_body").find(".text_content").html(view_text.container.innerHTML);
$(populous).find(".content_footer").find("textarea").text(item.description);
$(".search_content").last().after($(populous));
}
});
}
function populate_content(data){
var populous = $(".content_hidden").clone();
var sorted_data = [];
if(content_order){
content_order.forEach(function(content_id, index_order, arr_order){
data.forEach(function(item, index, arr){
if(item.content.result_id==content_id){
sorted_data.push(item);
}
});
});
sorted_data.forEach(function(item, index, arr){
populous = $(".content_hidden").clone();
$(populous).removeClass("content_hidden");
$(populous).show();
switch(item.content.type) {
case "youtube":
$(populous).find('.theme').css("background-color","rgb(255, 68, 68)");
break;
case "video":
$(populous).find('.theme').css("background-color","rgb(255, 68, 68)");
break;
case "website":
$(populous).find('.theme').css("background-color","rgb(0, 84, 169)");
break;
case "pdf":
$(populous).find('.theme').css("background-color","rgb(0, 84, 169)");
break;
case "image":
$(populous).find('.theme').css("background-color","rgb(56, 177, 55)");
break;
case "text":
$(populous).find('.theme').css("background-color","rgb(33, 115, 70)");
break;
}
if(item.content.type!="text"){
$(populous).attr("result_id",item.content.result_id);
$(populous).find(".content_header").find("span").text(item.content.title);
$(populous).find(".content_body").find("img").attr("src",decodeURIComponent(item.content.image));
$(populous).find(".content_footer").find("textarea").text(item.content.description);
$(populous).removeClass('content_result');
$(populous).addClass('content_already');
}else{
$(populous).attr("result_id",item.content.result_id);
$(populous).find(".content_header").find("span").text(item.content.title);
$(populous).find(".content_body").find("img").after("<div id='"+item.content.result_id+"' class='text_content'></div>");
$(populous).find(".content_body").find("img").remove();
$(populous).addClass('content_already');
view_text.setContents(JSON.parse(unescapeHtml(item.content.text_value)));
$(populous).find(".content_body").find(".text_content").html(view_text.container.innerHTML);
$(populous).find(".content_footer").find("textarea").text(item.content.description);
$(".search_content").last().after($(populous));
}
$("#"+item.folder_id).append($(populous));
});
}else{
console.log("No content");
}
}
$("#search_portal").on("keyup",function(event){
if (event.keyCode === 13) {
event.preventDefault();
reset_population();
$(".submit_button").click();
}
});
$(".submit_button").on("click",function(){
var search = $("#search_portal").val();
switch(active_portal) {
case "youtube":
youtube_search(search);
break;
case "google":
google_search(search);
break;
case "google_image":
google_image_search(search);
break;
case "my_resources":
my_resources_search(search);
break;
case "cms_resources":
cms_resources_search(search);
break;
default:
return null;
}
});
$(".slideshow_action").click(function(){
$(".edit_area").toggleClass("close_edit");
$(".student_view").toggleClass("student_view_close");
active_content_data = get_content_data(content_order[0]);
active_content = content_order[0];
adjust_iframe();
render_student_view();
populate_slides();
});
$(document).on("dblclick",".content_already",function(){
var result_id = $(this).attr("result_id");
update_active_content(result_id);
active_content_data = get_content_data(result_id);
$(".edit_area").toggleClass("close_edit");
$(".student_view").toggleClass("student_view_close");
render_student_view();
});
$(".student_view-title").click(function(){
$(".student_view-slideshows").toggleClass("slideshows_close");
});
$(".next").click(function(){
get_next();
check_active_thumbnail();
});
$(".previous").click(function(){
get_previous();
check_active_thumbnail();
});
$('.student_view_slides').hide();
$(".student_view_title").click(function(){
$('.student_view_slides').slideToggle("fast");
});
$('.student_view_slides').mousewheel(function(e, delta) {
this.scrollLeft -= (delta * 40);
e.preventDefault();
});
$(".slide").click(function(){
$(".slide").removeClass("slide_active");
$(this).addClass("slide_active");
});
$(document).on("dblclick",".content_already",function(){
populate_slides();
});
$(document).on("click",".actual_slide",function(){
var the_index = $(this).index()-1;
get_slides(the_index);
check_active_thumbnail();
});
$(document).on("mouseover",".content_already",function(){
$(this).find(".content_close").show();
});
$(document).on("mouseout",".content_already",function(){
$(this).find(".content_close").hide();
});
$(document).on("click",".content_close",function(){
var delete_li = $(this).parent().parent();
var delete_result_id = $(this).parent().parent().attr("result_id");
remove_content(delete_result_id);
$(delete_li).remove();
change_detected();
});
$(document).on("click",".content_footer",function(){
// $(this).parent().find(".content_body").find("img").addClass("hide_img");
// $(this).parent().find(".content_footer").find("span").addClass("description_display");
// $(this).parent().find(".content_footer").find("textarea").addClass("description_display");
});
function check_offline_files(){
console.log("Check Offline Files Running...");
$(document).find(".content_already");
var check_data = [];
$.each(content_pool,function(key,value){
check_data.push({key:value.content.result_id,data:value});
});
$.ajax({
url: url+'check_offline_files',
method:"POST",
data: {data:check_data,blackboard_id:blackboard_id},
}).done(function(data) {
if(data!="empty"){
var parsed_data = JSON.parse(data);
if(parsed_data.length){
$.each(parsed_data,function(parsed_data_key,parsed_data_value){
$.each(content_pool,function(content_pool_key,content_pool_value){
if(content_pool_value.content.result_id == parsed_data_value.key){
content_pool[parsed_data_key].content.source = parsed_data_value.source;
content_pool[parsed_data_key].content.type = parsed_data_value.type;
content_pool[parsed_data_key].content.status = parsed_data_value.status;
var the_li = $("li[result_id='"+content_pool[parsed_data_key].content.result_id+"']");
if(parsed_data_value.status == "checking"){
the_li.find(".download_status_container").css("background-color","#427fed");
the_li.find(".download_status_container").find("span").text("Checking...");
}else if(parsed_data_value.status == "completed"){
the_li.find(".download_status_container").css("background-color","green");
the_li.find(".download_status_container").find("span").text("O2O Available");
}else if(parsed_data_value.status == "downloading"){
the_li.find(".download_status_container").css("background-color","#e228ba");
the_li.find(".download_status_container").find("span").text("O2O In Progress");
}else if(parsed_data_value.status == "not_downloadable"){
the_li.find(".download_status_container").css("background-color","#427fed");
the_li.find(".download_status_container").find("span").text("Available Online");
}
}
});
});
console.log("File Check Complete");
}else{
}
}else{
console.log("Empty");
}
});
}
function check_thumbnails(){
console.log("Check thumbnails running...");
var check_data = [];
$.each(content_pool,function(key,value){
check_data.push({key:key,result_id:value.content.result_id,image:value.content.image,type:value.content.type});
});
$.ajax({
url: url+'check_thumbnail',
method:"POST",
data: {data:check_data,blackboard_id:blackboard_id},
}).done(function(data) {
if(data!="empty"){
var parsed_data = JSON.parse(data);
if(parsed_data.length){
$.each(parsed_data,function(parsed_data_key,parsed_data_value){
$.each(content_pool,function(content_pool_key,content_pool_value){
if(parsed_data_value.key == content_pool_value.content.result_id){
content_pool[parsed_data_key].content.image = encodeURIComponent(parsed_data_value.offline_thumbnail);
}
});
});
// change_detected();
}else{
}
}else{
console.log("No content found");
}
});
}
$(document).ready(function(){
deploy_stored_data();
});
$(".title").change(function(){
change_detected();
});
$("#lesson_type").change(function(){
var the_val = $(this).val();
if(the_val=="classroom"){
$(".notification_control").hide();
// $(".start_class").hide("slide", {direction: "right"}, 1000);
$(".start_class").animate({width:"0"},400,function(){
$(".start_class").hide();
$(".actions").not(".start_class").animate({width:"16.5%"});
});
}else if(the_val=="virtual"){
$(".notification_control").show();
$(".actions").not(".start_class").animate({width:"14%"},400,function(){
$(".start_class").show();
$(".start_class").animate({width:"14%"});
});
$(".start_class").find("span").text("Start Meet");
$(".start_class").find("img").attr("src",image_resources+"google_meet.png");
$(".virtual_link").attr("href",google_meet);
}else if(the_val=="zoom"){
// $(".zoom_modal_container").show("slow","linear");
// check_zoom_schedule();
$(".notification_control").show();
$(".actions").not(".start_class").animate({width:"14%"},400,function(){
$(".start_class").show();
$(".start_class").animate({width:"14%"});
});
var zoom_link = main_url+"lms/lesson/zoom_checker/"+lesson_id;
console.log(zoom_link);
$("#start_class").find("span").text("Start Zoom");
$("#start_class").find("img").attr("src",$("#image_resources").val()+"zoom.png");
$(".virtual_link").attr("href",zoom_link);
}else{
$(".start_class").animate({width:"0"},400,function(){
$(".start_class").hide();
$(".actions").not(".start_class").animate({width:"16.5%"});
});
}
});
$(".my_upload_button").click(function(){
$(".upload_input").click();
});
$(".upload_input").change(function(){
$(".upload_form").submit();
});
$(".upload_form").on("submit",function(e){
e.preventDefault();
var upload_url = url+"upload/my_resources/"+lesson_id;
$.ajax({
url: upload_url,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
console.log(data);
$("div[portal='my_resources']").click();
},
error: function(e){
alert("error");
}
});
});
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("add_text_close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
// Get the modal
var vimeo_modal = document.getElementById("vimeo_modal");
// Get the button that opens the modal
var vimeo_btn = document.getElementById("vimeo_btn");
// Get the <span> element that closes the modal
var vimeo_span = document.getElementsByClassName("vimeo_modal_close")[0];
// When the user clicks on the button, open the modal
vimeo_btn.onclick = function() {
vimeo_modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
vimeo_span.onclick = function() {
vimeo_modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == vimeo_modal) {
vimeo_modal.style.display = "none";
}
}
var learning_plan = new Quill('#learning_plan_text', {
theme: 'snow',
modules: {
table: true,
}
});
var objective = new Quill('#objective_text', {
theme: 'snow',
});
var add_text = new Quill('#add_text', {
theme: 'snow',
});
// add_text.setHtml('<div class="ql-editor" data-gramm="false" contenteditable="true"><p>asdfasdfasfd</p></div><div class="ql-clipboard" contenteditable="true" tabindex="-1"></div><div class="ql-tooltip ql-hidden"><a class="ql-preview" target="_blank" href="about:blank"></a><input type="text" data-formula="e=mc^2" data-link="https://quilljs.com" data-video="Embed URL"><a class="ql-action"></a><a class="ql-remove"></a></div>');
$(".add_text_done").click(function(){
var text_title = $("#text_title").val();
var text_value = JSON.stringify(add_text.getContents());
var add_text_url = url+"upload/add_text/"+lesson_id;
console.log(text_value);
$.ajax({
url: add_text_url,
type: "POST",
data: {title:text_title,text_value:text_value},
success: function(data)
{
console.log(data);
$("div[portal='my_resources']").click();
},
error: function(e){
alert("Something Went Wrong");
}
});
});
$(".vimeo_modal_done").click(function(){
var link = $("#vimeo_url").val();
var name = $("#vimeo_title").val();
var description = $("#vimeo_description").val();
var type = "youtube";
var vimeo_url = url+"upload/vimeo/"+lesson_id;
$.ajax({
url: vimeo_url,
type: "POST",
data: {link:link,name:name,type:type,description:description},
success: function(data)
{
console.log(data);
// console.log(data);
$("div[portal='my_resources']").click();
},
error: function(e){
alert("Something Went Wrong");
}
});
});
$(".close_student_view").click(function(){
$(".video_content").attr("src","");
$(".edit_area").toggleClass("close_edit");
$(".student_view").toggleClass("student_view_close");
reset_student_view();
});
if(role2!="admin"){
$(".close_student_view").click(function(){
window.location.replace(url+"index");
});
setTimeout(function(){
$(".slideshow_action").click();
},1500);
$(".edit_area").hide();
}
$(".assign_save").click(function(){
change_detected();
alert("Lesson has been assigned successfully");
});
$(".date_range").change(function(e){
change_detected();
// if($("#lesson_type").val()=="zoom"){
// if(confirm("Changing the schedule will remove you from the current slot. Are you sure you want to change the schedule?")){
// check_zoom_schedule();
// }
// }
});
function send_emails_now(){
var send_email_notification_url = $("#url").val()+"send_email_notification_godaddy";
var student_ids = [];
alert("Please wait for a while. Currently sending Notifications.");
$.each(jstree.jstree("get_checked",null,true),function(key,value){
if(value.includes('student')){
student_id = value.replace('student_','');
student_ids.push(student_id);
}
});
var student_ids = encodeURIComponent(student_ids.join(','));
var lesson_id = $("#lesson_id").val();
var email_notification = $("#email_notification").prop("checked");
// window.open(send_email_notification_url+"/"+lesson_id+"/"+email_notification+"/"+student_ids,"_blank");
$.ajax({
url: send_email_notification_url+"/"+lesson_id+"/"+email_notification+"/"+student_ids,
type: "GET",
// data: {
// student_ids:student_ids,
// lesson_id:$("#lesson_id").val(),
// email_notification:$("#email_notification").prop("checked"),
// },
success: function(data)
{
alert("Email Sent Successfully!");
},
error: function(e){
}
});
}
$("#send_emails_now").click(function(){
send_emails_now();
});
function send_email_notification(){
var send_email_notification_url = $("#url").val()+"send_email_notification_godaddy";
var student_ids = [];
$.each(jstree.jstree("get_checked",null,true),function(key,value){
if(value.includes('student')){
student_id = value.replace('student_','');
student_ids.push(student_id);
}
});
$.ajax({
url: send_email_notification_url,
type: "POST",
data: {
student_ids:student_ids,
lesson_id:$("#lesson_id").val(),
email_notification:$("#email_notification").prop("checked"),
},
success: function(data)
{
console.log(data);
var the_data = JSON.parse(data);
},
error: function(e){
}
});
}
});
if($(".start_date").val()){
$('.date_range').daterangepicker({
timePicker: true,
startDate: moment($(".start_date").val()),
endDate: moment($(".end_date").val()),
locale: {
format: 'MMMM DD hh:mm A'
}
});
}else{
$('.date_range').daterangepicker({
timePicker: true,
startDate: moment().startOf('hour').add(1, 'minute'),
endDate: moment().startOf('hour').add(1, 'hour'),
locale: {
format: 'MMMM DD hh:mm A'
}
});
}
function fetch_chat(){
var fetch_chat_url = $(url).val()+"fetch_chat";
var chat_lesson_id = $(lesson_id).val();
$.ajax({
url: fetch_chat_url,
type: "POST",
data: {lesson_id:chat_lesson_id},
success: function(data)
{
var chats = JSON.parse(data);
var chat_html = '';
var user_type = '';
$(".dicussion_container").empty();
$.each(chats,function(key,value){
if(value.account_type=="admin"){
user_type = value.firstname+" "+value.lastname;
}else{
user_type = value.firstname+" "+value.lastname;
}
chat_html = '<div class="chat_container">';
chat_html += '<div class="the_chat">';
chat_html += '<span class="user_type">'+user_type+': </span><span class="chat_content">'+value.content+'</span>';
chat_html += '</div>';
chat_html += '</div>';
// $(chat_clone).find(".chat_content");
// $(chat_html).find(".chat_content").text("asdasd");
$(".dicussion_container").append(chat_html);
});
},
error: function(e){
}
});
}
fetch_chat();
// setInterval(function(){
// fetch_chat();
// },5000);
function send_chat(student_chat){
var chat_url = $(url).val()+"send_chat";
if(student_chat){
var chat_content = student_chat;
}else{
var chat_content = $(".chat_text").eq(0).val();
}
var chat_lesson_id = $(lesson_id).val();
$.ajax({
url: chat_url,
type: "POST",
data: {content:chat_content,lesson_id:chat_lesson_id},
success: function(data)
{
console.log(data);
$(".chat_text").val('');
fetch_chat();
},
error: function(e){
}
});
}
function check_zoom_schedule(){
var check_zoom_schedule_url = $(url).val()+"check_zoom_schedule";
var start_date = $(".date_range").data('daterangepicker').startDate.toDate();
var end_date = $(".date_range").data('daterangepicker').endDate.toDate();
start_date = moment(start_date).format("YYYY-MM-DD HH:mm:ss");
end_date = moment(end_date).format("YYYY-MM-DD HH:mm:ss");
$.ajax({
url: check_zoom_schedule_url,
type: "POST",
data: {
start_date:start_date,
end_date:end_date,
lesson_id:$(lesson_id).val(),
account_id:$(account_id).val(),
},
success: function(data)
{
var the_data = JSON.parse(data);
$(".zoom_label").text(the_data.message);
if(the_data.status=="success"){
$(".zoom_email_used").text("("+the_data.zoom_email+")");
$(".notification_control").show();
$(".actions").not(".start_class").animate({width:"14%"},400,function(){
$(".start_class").show();
$(".start_class").animate({width:"14%"});
});
$(".start_class").find("span").text("Start Zoom");
$(".start_class").find("img").attr("src",$(image_resources).val()+"zoom.png");
$(".virtual_link").attr("href",the_data.start_url);
}else{
}
$(".zoom_modal_container").hide("slow","linear");
},
error: function(e){
}
});
}
$(".teacher_tools_button").click(function(){
$(".teacher_tools").toggle();
var width = document.getElementById('teacher_tools').offsetWidth;
$(".student_view_slides").hide();
$(".student_view_content").toggle();
$("#classroomscreen").css("width",width+70);
});
$(".formula_board_button").click(function(){
$(".formula_board").toggle();
// var width = document.getElementById('formula_board').offsetWidth;
$(".student_view_slides").hide();
$(".student_view_content").toggle();
// $("#classroomscreen").css("width",width+70);
});
$(".annotate_button").click(function(){
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
if($(this).hasClass("annotate_active")){
$(".annotate").css("display","none");
$(this).removeClass("annotate_active");
canvas.width = 0;
canvas.height = 0;
}else{
$(".annotate").css("display","block");
$(this).addClass("annotate_active");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
// var width = document.getElementById('formula_board').offsetWidth;
// $(".student_view_slides").hide();
// $(".student_view_content").toggle();
// $("#classroomscreen").css("width",width+70);
});
|
// Get the category url value and opens new tab using that URL
// Also this is the cop button
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('cop');
// onClick's logic below:
link.addEventListener('click', function() {
// Get category URL
chrome.storage.sync.get('category', function(r) {
var categoryUrl = r['category'];
chrome.tabs.create({url: categoryUrl});
});
});
});
|
'use strict';
angular.module('TwitterApplication')
.controller('contentCtrl', function($scope, $http, SearchService, $rootScope) {
console.log("Content controller has loaded successfully");
$scope.deleteTweet = function(id) {
$rootScope.obj.tweets = $rootScope.obj.tweets.filter(function (obj) {
return obj.id != +id;
})
};
});
|
/*!
* robust-admin-theme (https://pixinvent.com/bootstrap-admin-template/robust)
* Copyright 2018 PIXINVENT
* Licensed under the Themeforest Standard Licenses
*/
!function(window,document,$){"use strict";$(".icheck-task input").iCheck({checkboxClass:"icheckbox_square-blue",radioClass:"iradio_square-blue"});var movedBrooklyn=new GMaps({div:"#moved-brooklyn",lat:40.650002,lng:-73.949997,height:400});movedBrooklyn.addMarker({lat:40.650002,lng:-73.949997,title:"Moved Brooklyn",infoWindow:{content:"<h3>Moved Brooklyn</h3> <p>Our new office with more team members.</p>"}})}(window,document,jQuery);
|
// package: service
// file: service/publishedReceipt.proto
var service_publishedReceipt_pb = require("../service/publishedReceipt_pb");
var model_publishedReceipt_pb = require("../model/publishedReceipt_pb");
var grpc = require("@improbable-eng/grpc-web").grpc;
var PublishedReceiptService = (function () {
function PublishedReceiptService() {}
PublishedReceiptService.serviceName = "service.PublishedReceiptService";
return PublishedReceiptService;
}());
PublishedReceiptService.GetPublishedReceipts = {
methodName: "GetPublishedReceipts",
service: PublishedReceiptService,
requestStream: false,
responseStream: false,
requestType: model_publishedReceipt_pb.GetPublishedReceiptsRequest,
responseType: model_publishedReceipt_pb.GetPublishedReceiptsResponse
};
exports.PublishedReceiptService = PublishedReceiptService;
function PublishedReceiptServiceClient(serviceHost, options) {
this.serviceHost = serviceHost;
this.options = options || {};
}
PublishedReceiptServiceClient.prototype.getPublishedReceipts = function getPublishedReceipts(requestMessage, metadata, callback) {
if (arguments.length === 2) {
callback = arguments[1];
}
var client = grpc.unary(PublishedReceiptService.GetPublishedReceipts, {
request: requestMessage,
host: this.serviceHost,
metadata: metadata,
transport: this.options.transport,
debug: this.options.debug,
onEnd: function (response) {
if (callback) {
if (response.status !== grpc.Code.OK) {
var err = new Error(response.statusMessage);
err.code = response.status;
err.metadata = response.trailers;
callback(err, null);
} else {
callback(null, response.message);
}
}
}
});
return {
cancel: function () {
callback = null;
client.close();
}
};
};
exports.PublishedReceiptServiceClient = PublishedReceiptServiceClient;
|
class ContestResult():
def __init__(self):
self.winner = ""
self.second_place = ""
self.third_place = ""
def set_winner(self, name):
self.winner = name
def set_second_place(self, name):
self.second_place = name
def set_third_place(self, name):
self.third_place = name
def get_winner(self):
return self.winner
def get_second_place(self):
return self.second_place
def get_third_place(self):
return self.third_place
|
from typing import *
import numpy as np
from .algorithms import acl_list
from .algorithms import fista_dinput_dense
from .cpp import *
import warnings
import time
def approximate_PageRank(G,
ref_nodes,
timeout: float = 100,
iterations: int = 1000000,
alpha: float = 0.15,
rho: float = 1.0e-6,
epsilon: float = 1.0e-2,
ys: Sequence[float] = None,
cpp: bool = True,
normalize: bool = True,
normalized_objective: bool = True,
method: str = "acl",
use_distribution: bool = False,
distribution: list = []):
"""
Computes PageRank vector locally.
--------------------------------
When method is "acl" or "acl_weighted":
Uses the Andersen Chung and Lang (ACL) Algorithm. For details please refer to:
R. Andersen, F. Chung and K. Lang. Local Graph Partitioning using PageRank Vectors
link: http://www.cs.cmu.edu/afs/cs/user/glmiller/public/Scientific-Computing/F-11/RelatedWork/local_partitioning_full.pdf.
When method is "l1reg":
Uses the Fast Iterative Soft Thresholding Algorithm (FISTA). This algorithm solves the l1-regularized
personalized PageRank problem.
The l1-regularized personalized PageRank problem is defined as
min rho*||p||_1 + <c,p> + <p,Q*p>
where p is the PageRank vector, ||p||_1 is the l1-norm of p, rho is the regularization parameter
of the l1-norm, c is the right hand side of the personalized PageRank linear system and Q is the
symmetrized personalized PageRank matrix.
For details please refer to:
K. Fountoulakis, F. Roosta-Khorasani, J. Shun, X. Cheng and M. Mahoney. Variational
Perspective on Local Graph Clustering. arXiv:1602.01886, 2017.
arXiv link:https://arxiv.org/abs/1602.01886
When method is "l1reg-rand":
Uses a randomized proximal coordinate descent method.
Parameters
----------
G: GraphLocal
ref_nodes: Sequence[int]
A sequence of reference nodes, i.e., nodes of interest around which
we are looking for a target cluster.
Parameters (optional)
---------------------
alpha: float
Default == 0.15
Teleportation parameter of the personalized PageRank linear system.
The smaller the more global the personalized PageRank vector is.
rho: float
Defaul == 1.0e-6
Regularization parameter for the l1-norm of the model.
iterations: int
Default = 1000000
Maximum number of iterations of ACL algorithm.
timeout: float
Default = 100
Maximum time in seconds
method: string
Default = 'acl'
Which method to use.
Options: 'l1reg', 'acl'.
normalize: bool
Default = True
Normalize the output to be directly input into sweepcut routines.
normalized_objective: bool
Default = True
Use normalized Laplacian in the objective function, works only for "method=l1reg" and "cpp=True"
cpp: bool
default = True
Use the faster C++ version or not.
Extra parameters for "l1reg" or "l1reg-rand" (optional)
-------------------------------------------
epsilon: float64
Default == 1.0e-2
Tolerance for FISTA for solving the l1-regularized personalized PageRank problem.
ys: Sequence[float]
Defaul == None
Initial solutions for l1-regularized PageRank algorithm.
If not provided then it is initialized to zero.
This is only used for the C++ version of FISTA.
Returns
-------
An np.ndarray (1D embedding) of the nodes.
"""
if G._weighted and method not in ["acl_weighted","l1reg-rand","l1reg"]:
warnings.warn("The weights of the graph will be discarded. Use approximate_PageRank_weighted or l1reg-rand instead if you want to keep the edge weights.")
if method == "acl":
#print("Uses the Andersen Chung and Lang (ACL) Algorithm.")
if ys != None:
warnings.warn("\"acl\" doesn't support initial solutions, please use \"l1reg\" instead.")
if cpp:
# start = time.time()
n = G.adjacency_matrix.shape[0]
(length,xids,values) = aclpagerank_cpp(n,G.ai,G.aj,alpha,rho,ref_nodes,iterations)
# TODO, implement this in the C++ function
if normalize:
for i in range(len(xids)): # we can't use degrees because it could be weighted
values[i] /= (G.ai[xids[i]+1]-G.ai[xids[i]])
# end = time.time()
# print(" Elapsed time acl with rounding: ", end - start)
return (xids,values)
else:
return acl_list(ref_nodes, G, alpha = alpha, rho = rho, max_iter = iterations, max_time = timeout)
elif method == "acl_weighted":
if ys != None:
warnings.warn("\"acl_weighted\" doesn't support initial solutions, please use \"l1reg\" instead.")
if cpp:
n = G.adjacency_matrix.shape[0]
(length,xids,values) = aclpagerank_weighted_cpp(n,G.ai,G.aj,G.adjacency_matrix.data,alpha,rho,
ref_nodes,iterations)
if normalize:
values *= G.dn[xids] # those are inverse degrees
return (xids,values)
else:
raise Exception("There is only C++ version for acl weighted.")
elif method == "l1reg" or method == "l1reg-rand":
#print("Uses the Fast Iterative Soft Thresholding Algorithm (FISTA).")
# TODO fix the following warning
# warnings.warn("The normalization of this routine hasn't been adjusted to the new system yet")
# start = time.time()
algo = proxl1PRaccel_cpp if method == "l1reg" else proxl1PRrand_cpp
if cpp:
if method == "l1reg":
p = algo(G.ai, G.aj, G.adjacency_matrix.data, ref_nodes, G.d, G.d_sqrt, G.dn_sqrt, alpha = alpha,
rho = rho, epsilon = epsilon, maxiter = iterations, max_time = timeout, normalized_objective = normalized_objective,
use_distribution = use_distribution, distribution = distribution)[2]
else:
(length,xids,values) = algo(G.ai, G.aj, G.adjacency_matrix.data, ref_nodes, G.d, G.d_sqrt, G.dn_sqrt, alpha = alpha,
rho = rho, epsilon = epsilon, maxiter = iterations, max_time = timeout, normalized_objective = normalized_objective)
else:
p = fista_dinput_dense(ref_nodes, G, alpha = alpha, rho = rho, epsilon = epsilon, max_iter = iterations, max_time = timeout)
# convert result to a sparse vector
# nonzeros = np.count_nonzero(p)
# end = time.time()
# print(" Elapsed time l1reg with rounding: ", end - start)
# start = time.time()
# idx = np.nonzero(p)[0]
# end = time.time()
# print(" Elapsed time one: ", end - start)
# start = time.time()
# vals = p[idx]
# end = time.time()
# print(" Elapsed time two: ", end - start)
# start = time.time()
if normalize:
if method == "l1reg":
# convert result to a sparse vector
nonzeros = np.count_nonzero(p)
xids = np.zeros(nonzeros,dtype=np.dtype(G.aj[0]))
values = np.zeros(nonzeros,dtype=np.float64)
it = 0
for i in range(len(p)):
if p[i] != 0:
xids[it] = i
values[it] = p[i]*1.0 * G.dn[i] if normalize else p[i]
it += 1
else:
values = np.multiply(G.dn[xids], values)
return (xids,values)
else:
raise Exception("Unknown method, available methods are \"acl\" or \"acl_weighted\" or \"l1reg\" or \"l1reg-rand\".")
|
"use strict";
const util = require('util');
const castv2Cli = require('castv2-client');
const RequestResponseController = castv2Cli.RequestResponseController;
const httpClient = require('request');
const YOUTUBE_BASE_URL = 'https://www.youtube.com/';
const LOUNGE_TOKEN_URL = YOUTUBE_BASE_URL + "api/lounge/pairing/get_lounge_token_batch";
const BIND_URL = YOUTUBE_BASE_URL + "api/lounge/bc/bind";
const sIdRegex = /"c","(.*?)","/g;
const playListIdRegex = /listId":"(.*?)"/g;
const gSessionIdRegex = /"S","(.*?)"]/g;
function YouTubeController(client, sourceId, destinationId) {
RequestResponseController.call(this, client, sourceId, destinationId, 'urn:x-cast:com.google.youtube.mdx');
this.currentSession = null;
this.on('message', onmessage);
this.once('close', onclose);
var self = this;
function onmessage(data, broadcast) {
if(data.type === 'MEDIA_STATUS' && broadcast) {
var status = data.status[0];
// Sometimes an empty status array can come through; if so don't emit it
if (!status) return;
self.currentSession = status;
self.emit('status', status);
}
}
function onclose() {
self.removeListener('message', onmessage);
}
}
util.inherits(YouTubeController, RequestResponseController);
YouTubeController.prototype.load = function (videoId, callback) {
var screenId, loungeToken;
var sId, gSessionId, playlistId;
// 1. Fetch screen ID
this.controlRequest({ type: 'getMdxSessionStatus' }, function(err, response) {
if (err) return callback(err);
if (!response.data || !response.data.screenId) {
return callback(new Error('Failed to fetch screenID'));
} else {
screenId = response.data.screenId;
}
// 2. Fetch lounge token
var loungeTokenRequest = {
'url': LOUNGE_TOKEN_URL,
'headers': { "Origin": YOUTUBE_BASE_URL },
'form': { 'screen_ids': screenId }
};
httpClient.post(loungeTokenRequest, function(loungeTokenErr, loungeTokenResponse, loungeTokenBody) {
if (loungeTokenErr) return callback(loungeTokenErr);
if (loungeTokenResponse.statusCode !== 200) return callback(new Error('Lounge token request failed'));
var loungeTokenBodyParsed = JSON.parse(loungeTokenBody);
loungeToken = loungeTokenBodyParsed.screens[0].loungeToken;
// 3. Initialize queue
var queueRequest = {
'url': BIND_URL,
'form': {
'count': 0
},
'qs': {
'device': 'REMOTE_CONTROL',
'id': '12345678-9ABC-4DEF-0123-0123456789AB',
'name': 'Desktop&app=youtube-desktop',
'mdx-version': 3,
'loungeIdToken': loungeToken,
'VER': 8,
'v': 2,
't': 1,
'ui': 1,
'RID': 75956,
'CVER': 1,
'method': 'setPlaylist',
'params': '%7B%22videoId%22%3A%22' + videoId + '%22%2C%22currentTime%22%3A5%2C%22currentIndex%22%3A0%7D',
'TYPE': ''
}
};
httpClient.post(queueRequest, function(queueErr, queueResponse, queueBody) {
if (queueErr) return callback(queueErr);
if (queueResponse.statusCode !== 200) return callback(new Error('Queue request failed'));
callback(null);
});
});
});
};
YouTubeController.prototype.controlRequest = function (data, callback) {
var self = this;
function onmessage(response) {
self.removeListener('message', onmessage);
if (response.type === 'INVALID_REQUEST') {
return callback(new Error('Invalid request: ' + response.reason));
}
callback(null, response);
}
this.on('message', onmessage);
this.send(data);
};
module.exports = YouTubeController;
|
angular.module('mean.system').factory('Data',['$stateParams', function($stateParams){
var brands = {
television: ['alba','aqualite','bush','cello','e-motion','lg','panasonic','toshiba','philips','sharp','samsung', 'jvc','sony','hitachi','digihome','logik','sandstrom','jmb','luxor','blaupunkt','foehn & hirsch','furrion','hannspree','technika','linsar','akai'],
laptop:['advent','acer','asus','apple','dell','fujitsu','hp','lenovo','samsung','sony','toshiba','packard bell','compaq','medion'],
camera:['fujifilm', 'nikon', 'canon','panasonic','olympus','samsung','vivitar','pentax','polaroid','ricoh','sony'],
tablet:['acer','samsung','sony','archos','toshiba','kobo','hp','arnova','prestigio','gemini','asus','google','apple','microsoft','nook','lenovo','kindle']
}
var retailers = {
television:['argos','currys','littlewoods','ebuyer','selfridges', 'coop electrical','john lewis','tesco', 'prc direct','sonic direct','hughes direct','electrical discount uk'],
laptop:['argos','currys','littlewoods','coop electrical','ebuyer','medion','zavvi','sonic direct'],
camera:['argos','currys','littlewoods','jessops'],
tablet:['argos','currys','littlewoods']
};
var selectedRetailers = {
television:[],
laptop:[],
camera:[],
tablet:[]
};
var selectedBrands = {
television:[],
laptop:[],
camera:[],
tablet:[]
}
var filters = {
television:{
priceMin: 0,
priceMax: 5000,
screenMin: 0,
screenMax: 80
},
laptop:{
priceMin: 0,
priceMax: 3000,
screenMin: 0,
screenMax: 30
},
tablet:{
priceMin: 0,
priceMax: 1000
},
camera:{
priceMin: 0,
priceMax: 3000
}
}
return{
brands:brands,
retailers:retailers,
selectedBrands:selectedBrands,
selectedRetailers:selectedRetailers,
filters: filters
}
}]);
|
import numpy as onp
import jax.numpy as jnp
from jax import lax
from flax.optim import OptimizerDef
from flax import struct
@struct.dataclass
class _MadgradHyperParams:
learning_rate: onp.ndarray
beta: onp.ndarray
eps: onp.ndarray
weight_decay: onp.ndarray
use_adamWStyle_weightDecay: onp.bool
@struct.dataclass
class _MadgradParamState:
initial_param: onp.ndarray
grad_sum: onp.ndarray
grad_sum_sq: onp.ndarray
class Madgrad(OptimizerDef):
"""
MADGRAD: Momentumized, Adaptive, Dual Averaged Gradient Method for Stochastic Optimization.
https://github.com/facebookresearch/madgrad
Differences with reference implementation:
- this version uses a AdamW style weight decay by default
- the learning rate has been remapped such that it acts linearly
Notes:
- Madgrad with use_adamWStyle_weightDecay=False usually requires less weight decay than other optimizer (often 0).
- The optimal learning rate will usually not be the one used by SGD or Adam.
Some good values include :
- 0.005 for 152 layer PreActResNet on CIFAR10,
- 0.01 for ResNet-50 on ImageNet,
- 0.085 for IWSLT14 using transformer_iwslt_de_en,
- 0.03 for RoBERTa training on BookWiki using BERT_BASE.
"""
def __init__(self, learning_rate=5e-2, beta=0.9, eps=1e-6, weight_decay=0.0, use_adamWStyle_weightDecay=True):
hyper_params = _MadgradHyperParams(learning_rate, beta, eps, weight_decay, use_adamWStyle_weightDecay)
super().__init__(hyper_params)
def init_param_state(self, param):
return _MadgradParamState(param, jnp.zeros_like(param), jnp.zeros_like(param))
def apply_param_gradient(self, step, hyper_params, param, state, grad):
beta = hyper_params.beta
weight_decay = hyper_params.weight_decay
learning_rate = hyper_params.learning_rate
eps = hyper_params.eps
# weight decay
if not hyper_params.use_adamWStyle_weightDecay:
grad += weight_decay * param
# gradient accumulation
# power(3/2) added such that learning_rate is the actual step size rather than lr / cbrt(lr)
weighted_lr = jnp.power(learning_rate, 3./2.) * jnp.sqrt(step + 1)
grad_sum = state.grad_sum + weighted_lr * grad
grad_sum_sq = state.grad_sum_sq + weighted_lr * lax.square(grad)
# parameter update
new_param = state.initial_param - grad_sum / (jnp.cbrt(grad_sum_sq) + eps)
new_param = beta*param + (1. - beta)*new_param # momentum
# AdamW-style weight decay
if hyper_params.use_adamWStyle_weightDecay:
new_param -= (1. - beta) * learning_rate * weight_decay * param
new_state = _MadgradParamState(state.initial_param, grad_sum, grad_sum_sq)
return new_param, new_state
|
jQuery(document).ready( function($){
if($(".comments-area").size()>0){
$(".comment-form .form-submit input").addClass('btn btn-default');
$('.comment-list li .children:first-of-type').hide();
$(".show-comment-replies").on("click", function(evt){
$(evt.target).closest('article').next('').slideToggle();
$(evt.target).children('span').toggleClass('text-hide');
evt.preventDefault();
});
}
if($(".tiles").size()>0){
$(".tiles").on("click", function(evt){
if($(evt.target).hasClass('item')){
var link =$(evt.target).find('a');
console.log(link.attr('href'));
window.location=link.attr('href');
}
});
}
if($(".navbar-collapse").size() > 0 ) {
$(window).on( "resize" , function () {
$(".navbar-collapse.in").each( function () {
$(this).removeClass("in").addClass("collapse");//siblings(".navbar-header").find(".navbar-toggle").trigger("click");
});
});
}
});
|
'use strict'
const { dialog, Menu } = require('electron')
const fs = require('fs')
const url = require('url')
const util = require('util')
const ipcMainUtils = require('@electron/internal/browser/ipc-main-internal-utils')
const readFile = util.promisify(fs.readFile)
const convertToMenuTemplate = function (event, items) {
return items.map(function (item) {
const transformed = item.type === 'subMenu' ? {
type: 'submenu',
label: item.label,
enabled: item.enabled,
submenu: convertToMenuTemplate(event, item.subItems)
} : item.type === 'separator' ? {
type: 'separator'
} : item.type === 'checkbox' ? {
type: 'checkbox',
label: item.label,
enabled: item.enabled,
checked: item.checked
} : {
type: 'normal',
label: item.label,
enabled: item.enabled
}
if (item.id != null) {
transformed.click = function () {
event._replyInternal('ELECTRON_INSPECTOR_CONTEXT_MENU_CLICK', item.id)
}
}
return transformed
})
}
const getEditMenuItems = function () {
return [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'pasteAndMatchStyle' },
{ role: 'delete' },
{ role: 'selectAll' }
]
}
const isChromeDevTools = function (pageURL) {
const { protocol } = url.parse(pageURL)
return protocol === 'chrome-devtools:'
}
const assertChromeDevTools = function (contents, api) {
const pageURL = contents._getURL()
if (!isChromeDevTools(pageURL)) {
console.error(`Blocked ${pageURL} from calling ${api}`)
throw new Error(`Blocked ${api}`)
}
}
ipcMainUtils.handle('ELECTRON_INSPECTOR_CONTEXT_MENU', function (event, items, isEditMenu) {
assertChromeDevTools(event.sender, 'window.InspectorFrontendHost.showContextMenuAtPoint()')
const template = isEditMenu ? getEditMenuItems() : convertToMenuTemplate(event, items)
const menu = Menu.buildFromTemplate(template)
const window = event.sender.getOwnerBrowserWindow()
menu.once('menu-will-close', () => {
// menu-will-close is emitted before the click handler, but needs to be sent after.
// otherwise, DevToolsAPI.contextMenuCleared() would be called before
// DevToolsAPI.contextMenuItemSelected(id) and the menu will not work properly.
setTimeout(() => {
event._replyInternal('ELECTRON_INSPECTOR_CONTEXT_MENU_CLOSE')
})
})
menu.popup({ window })
})
ipcMainUtils.handle('ELECTRON_INSPECTOR_SELECT_FILE', async function (event) {
assertChromeDevTools(event.sender, 'window.UI.createFileSelectorElement()')
const result = await dialog.showOpenDialog({})
if (result.canceled) return []
const path = result.filePaths[0]
const data = await readFile(path)
return [path, data]
})
ipcMainUtils.handle('ELECTRON_INSPECTOR_CONFIRM', async function (event, message = '', title = '') {
assertChromeDevTools(event.sender, 'window.confirm()')
const options = {
message: String(message),
title: String(title),
buttons: ['OK', 'Cancel'],
cancelId: 1
}
const window = event.sender.getOwnerBrowserWindow()
const { response } = await dialog.showMessageBox(window, options)
return response === 0
})
|
from easydict import EasyDict
hopper_ddpg_default_config = dict(
env=dict(
env_id='Hopper-v3',
norm_obs=dict(use_norm=False, ),
norm_reward=dict(use_norm=False, ),
collector_env_num=1,
evaluator_env_num=8,
use_act_scale=True,
n_evaluator_episode=8,
stop_value=6000,
),
policy=dict(
cuda=True,
on_policy=False,
random_collect_size=25000,
model=dict(
obs_shape=11,
action_shape=3,
twin_critic=False,
actor_head_hidden_size=256,
critic_head_hidden_size=256,
actor_head_type='regression',
),
learn=dict(
update_per_collect=1,
batch_size=256,
learning_rate_actor=1e-3,
learning_rate_critic=1e-3,
ignore_done=False,
target_theta=0.005,
discount_factor=0.99,
actor_update_freq=1,
noise=False,
),
collect=dict(
n_sample=1,
unroll_len=1,
noise_sigma=0.1,
),
other=dict(replay_buffer=dict(replay_buffer_size=1000000, ), ),
)
)
hopper_ddpg_default_config = EasyDict(hopper_ddpg_default_config)
main_config = hopper_ddpg_default_config
hopper_ddpg_default_create_config = dict(
env=dict(
type='mujoco',
import_names=['dizoo.mujoco.envs.mujoco_env'],
),
env_manager=dict(type='base'),
policy=dict(
type='ddpg',
import_names=['ding.policy.ddpg'],
),
replay_buffer=dict(type='naive', ),
)
hopper_ddpg_default_create_config = EasyDict(hopper_ddpg_default_create_config)
create_config = hopper_ddpg_default_create_config
|
import "@ui5/webcomponents/dist/Avatar.js";
import "@ui5/webcomponents/dist/AvatarGroup.js";
import "@ui5/webcomponents/dist/Badge";
import "@ui5/webcomponents-fiori/dist/Bar";
import "@ui5/webcomponents/dist/Button";
import "@ui5/webcomponents/dist/Calendar";
import "@ui5/webcomponents/dist/Card";
import "@ui5/webcomponents/dist/Carousel";
import "@ui5/webcomponents/dist/CheckBox";
import "@ui5/webcomponents/dist/ComboBox";
import "@ui5/webcomponents/dist/DatePicker";
import "@ui5/webcomponents/dist/DateRangePicker.js";
import "@ui5/webcomponents/dist/DateTimePicker.js";
import "@ui5/webcomponents/dist/DurationPicker.js";
import "@ui5/webcomponents/dist/Icon";
import "@ui5/webcomponents/dist/Label";
import "@ui5/webcomponents/dist/Input";
import "@ui5/webcomponents/dist/Link";
import "@ui5/webcomponents/dist/List.js";
import "@ui5/webcomponents/dist/StandardListItem.js";
import "@ui5/webcomponents/dist/CustomListItem.js";
import "@ui5/webcomponents/dist/GroupHeaderListItem.js";
import "@ui5/webcomponents/dist/Panel";
import "@ui5/webcomponents-fiori/dist/ShellBar";
import "@ui5/webcomponents/dist/TabContainer";
import "@ui5/webcomponents/dist/Tab";
import "@ui5/webcomponents/dist/TabSeparator";
import "@ui5/webcomponents/dist/Table.js";
import "@ui5/webcomponents/dist/TableColumn.js";
import "@ui5/webcomponents/dist/TableRow.js";
import "@ui5/webcomponents/dist/TableCell.js";
import "@ui5/webcomponents/dist/TextArea";
import "@ui5/webcomponents-fiori/dist/Timeline";
import "@ui5/webcomponents/dist/TimePicker.js";
import "@ui5/webcomponents/dist/Title";
import "@ui5/webcomponents-fiori/dist/Wizard.js";
import "@ui5/webcomponents-fiori/dist/Page.js";
import "@ui5/webcomponents-fiori/dist/Wizard.js";
//import "@ui5/webcomponents/dist/Assets-static.js";
//import "@ui5/webcomponents-icons/dist/Assets.js";
//import "@ui5/webcomponents-fiori/dist/Assets-static.js";
// "@ui5/webcomponents-icons/dist/action-settings.js";
// import "@ui5/webcomponents-icons/dist/home.js"
import "./icons.js"
|
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
#############################################################################
## ##
## Copyright (C) 2013 Cassidian CyberSecurity SAS. All rights reserved. ##
## This document is the property of Cassidian CyberSecurity SAS, it may ##
## not be circulated without prior licence ##
## ##
## Author: Ivan Fontarensky <ivan.fontarensky@cassidian.com> ##
## ##
#############################################################################
__author__ = 'ifontarensky'
import sys
import argparse
from disass.Disass32 import Disass32
#Tested on
# c7a0398cfb7c40ce7a8cc9acdb28cb0f107a2e892b5fa5ed7700563c8c1540ab
def reverse(path, verbose):
disass = Disass32(path=path, verbose=verbose)
disass.go_to_next_call('InternetConnectA')
try:
addr = disass.get_arguments(2)
print " CC\t: %s" % disass.get_string(addr)
except:
pass
if not disass.go_to_next_call('HttpOpenRequestA'):
return
try:
lpszVerb = disass.get_string(disass.get_arguments(2))
lpszObjectName = disass.get_string(disass.get_arguments(3))
lpszVersion = disass.get_string(disass.get_arguments(4))
print " Request\t: %s %s %s" % (lpszVerb,lpszObjectName,lpszVersion)
except Exception as e:
print str(e)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='letusgo_parser')
parser.add_argument('--verbose', '-v', help='Do not output anything on the standard output.', action='store_true',
default=False)
parser.add_argument('path', help='path to analyze', nargs="*")
args = parser.parse_args()
if len(args.path) == 0:
print "Usage : apt1_letusgo_parser.py apt1_letusgo.infected"
sys.exit(1)
for path in args.path:
reverse(path=path, verbose=args.verbose)
|
// GENERATED CODE -- DO NOT EDIT!
// Original file comments:
// Copyright 2020 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';
var grpc = require('grpc');
var google_ads_googleads_v3_services_ad_group_ad_label_service_pb = require('../../../../../google/ads/googleads/v3/services/ad_group_ad_label_service_pb.js');
var google_ads_googleads_v3_resources_ad_group_ad_label_pb = require('../../../../../google/ads/googleads/v3/resources/ad_group_ad_label_pb.js');
var google_api_annotations_pb = require('../../../../../google/api/annotations_pb.js');
var google_api_client_pb = require('../../../../../google/api/client_pb.js');
var google_api_field_behavior_pb = require('../../../../../google/api/field_behavior_pb.js');
var google_api_resource_pb = require('../../../../../google/api/resource_pb.js');
var google_rpc_status_pb = require('../../../../../google/rpc/status_pb.js');
function serialize_google_ads_googleads_v3_resources_AdGroupAdLabel(arg) {
if (!(arg instanceof google_ads_googleads_v3_resources_ad_group_ad_label_pb.AdGroupAdLabel)) {
throw new Error('Expected argument of type google.ads.googleads.v3.resources.AdGroupAdLabel');
}
return Buffer.from(arg.serializeBinary());
}
function deserialize_google_ads_googleads_v3_resources_AdGroupAdLabel(buffer_arg) {
return google_ads_googleads_v3_resources_ad_group_ad_label_pb.AdGroupAdLabel.deserializeBinary(new Uint8Array(buffer_arg));
}
function serialize_google_ads_googleads_v3_services_GetAdGroupAdLabelRequest(arg) {
if (!(arg instanceof google_ads_googleads_v3_services_ad_group_ad_label_service_pb.GetAdGroupAdLabelRequest)) {
throw new Error('Expected argument of type google.ads.googleads.v3.services.GetAdGroupAdLabelRequest');
}
return Buffer.from(arg.serializeBinary());
}
function deserialize_google_ads_googleads_v3_services_GetAdGroupAdLabelRequest(buffer_arg) {
return google_ads_googleads_v3_services_ad_group_ad_label_service_pb.GetAdGroupAdLabelRequest.deserializeBinary(new Uint8Array(buffer_arg));
}
function serialize_google_ads_googleads_v3_services_MutateAdGroupAdLabelsRequest(arg) {
if (!(arg instanceof google_ads_googleads_v3_services_ad_group_ad_label_service_pb.MutateAdGroupAdLabelsRequest)) {
throw new Error('Expected argument of type google.ads.googleads.v3.services.MutateAdGroupAdLabelsRequest');
}
return Buffer.from(arg.serializeBinary());
}
function deserialize_google_ads_googleads_v3_services_MutateAdGroupAdLabelsRequest(buffer_arg) {
return google_ads_googleads_v3_services_ad_group_ad_label_service_pb.MutateAdGroupAdLabelsRequest.deserializeBinary(new Uint8Array(buffer_arg));
}
function serialize_google_ads_googleads_v3_services_MutateAdGroupAdLabelsResponse(arg) {
if (!(arg instanceof google_ads_googleads_v3_services_ad_group_ad_label_service_pb.MutateAdGroupAdLabelsResponse)) {
throw new Error('Expected argument of type google.ads.googleads.v3.services.MutateAdGroupAdLabelsResponse');
}
return Buffer.from(arg.serializeBinary());
}
function deserialize_google_ads_googleads_v3_services_MutateAdGroupAdLabelsResponse(buffer_arg) {
return google_ads_googleads_v3_services_ad_group_ad_label_service_pb.MutateAdGroupAdLabelsResponse.deserializeBinary(new Uint8Array(buffer_arg));
}
// Proto file describing the Ad Group Ad Label service.
//
// Service to manage labels on ad group ads.
var AdGroupAdLabelServiceService = exports.AdGroupAdLabelServiceService = {
// Returns the requested ad group ad label in full detail.
getAdGroupAdLabel: {
path: '/google.ads.googleads.v3.services.AdGroupAdLabelService/GetAdGroupAdLabel',
requestStream: false,
responseStream: false,
requestType: google_ads_googleads_v3_services_ad_group_ad_label_service_pb.GetAdGroupAdLabelRequest,
responseType: google_ads_googleads_v3_resources_ad_group_ad_label_pb.AdGroupAdLabel,
requestSerialize: serialize_google_ads_googleads_v3_services_GetAdGroupAdLabelRequest,
requestDeserialize: deserialize_google_ads_googleads_v3_services_GetAdGroupAdLabelRequest,
responseSerialize: serialize_google_ads_googleads_v3_resources_AdGroupAdLabel,
responseDeserialize: deserialize_google_ads_googleads_v3_resources_AdGroupAdLabel,
},
// Creates and removes ad group ad labels.
// Operation statuses are returned.
mutateAdGroupAdLabels: {
path: '/google.ads.googleads.v3.services.AdGroupAdLabelService/MutateAdGroupAdLabels',
requestStream: false,
responseStream: false,
requestType: google_ads_googleads_v3_services_ad_group_ad_label_service_pb.MutateAdGroupAdLabelsRequest,
responseType: google_ads_googleads_v3_services_ad_group_ad_label_service_pb.MutateAdGroupAdLabelsResponse,
requestSerialize: serialize_google_ads_googleads_v3_services_MutateAdGroupAdLabelsRequest,
requestDeserialize: deserialize_google_ads_googleads_v3_services_MutateAdGroupAdLabelsRequest,
responseSerialize: serialize_google_ads_googleads_v3_services_MutateAdGroupAdLabelsResponse,
responseDeserialize: deserialize_google_ads_googleads_v3_services_MutateAdGroupAdLabelsResponse,
},
};
exports.AdGroupAdLabelServiceClient = grpc.makeGenericClientConstructor(AdGroupAdLabelServiceService);
|
/**
* @file 组件预热
* @author errorrik(errorrik@gmail.com)
*/
var ExprType = require('../parser/expr-type');
var each = require('../util/each');
var createEl = require('../browser/create-el');
var getPropHandler = require('./get-prop-handler');
var getANodeProp = require('./get-a-node-prop');
var isBrowser = require('../browser/is-browser');
/**
* 组件预热,分析组件aNode的数据引用等信息
*
* @param {Function} ComponentClass 组件类
*/
function componentPreheat(ComponentClass) {
var stack = [];
function recordHotspotData(refs, notContentData) {
var len = stack.length;
each(stack, function (aNode, index) {
if (!notContentData || index !== len - 1) {
each(refs, function (ref) {
aNode.hotspot.data[ref] = 1;
});
}
});
}
function analyseANodeHotspot(aNode) {
if (!aNode.hotspot) {
stack.push(aNode);
if (aNode.textExpr) {
aNode.hotspot = {data: {}};
recordHotspotData(analyseExprDataHotspot(aNode.textExpr));
}
else {
var sourceNode;
if (isBrowser && aNode.tagName && !/^(template|slot|select|input|option)$/i.test(aNode.tagName)) {
sourceNode = createEl(aNode.tagName);
}
aNode.hotspot = {
data: {},
dynamicProps: [],
xProps: [],
props: {},
sourceNode: sourceNode
};
// === analyse hotspot data: start
each(aNode.vars, function (varItem) {
recordHotspotData(analyseExprDataHotspot(varItem.expr));
});
each(aNode.props, function (prop) {
recordHotspotData(analyseExprDataHotspot(prop.expr));
});
/* eslint-disable guard-for-in */
for (var key in aNode.directives) {
var directive = aNode.directives[key];
recordHotspotData(analyseExprDataHotspot(directive.value), key !== 'html');
}
/* eslint-enable guard-for-in */
each(aNode.elses, function (child) {
analyseANodeHotspot(child);
});
each(aNode.children, function (child) {
analyseANodeHotspot(child);
});
// === analyse hotspot data: end
// === analyse hotspot props: start
each(aNode.props, function (prop, index) {
aNode.hotspot.props[prop.name] = index;
if (prop.name === 'id') {
prop.id = true;
aNode.hotspot.idProp = prop;
aNode.hotspot.dynamicProps.push(prop);
}
else if (prop.expr.value != null) {
if (sourceNode) {
getPropHandler(aNode.tagName, prop.name)
.prop(sourceNode, prop.expr.value, prop.name, aNode);
}
}
else {
if (prop.x) {
aNode.hotspot.xProps.push(prop);
}
aNode.hotspot.dynamicProps.push(prop);
}
});
// ie 下,如果 option 没有 value 属性,select.value = xx 操作不会选中 option
// 所以没有设置 value 时,默认把 option 的内容作为 value
if (aNode.tagName === 'option'
&& !getANodeProp(aNode, 'value')
&& aNode.children[0]
) {
var valueProp = {
name: 'value',
expr: aNode.children[0].textExpr
};
aNode.props.push(valueProp);
aNode.hotspot.dynamicProps.push(valueProp);
aNode.hotspot.props.value = aNode.props.length - 1;
}
// === analyse hotspot props: end
}
stack.pop();
}
}
analyseANodeHotspot(ComponentClass.prototype.aNode);
}
/**
* 分析表达式的数据引用
*
* @param {Object} expr 要分析的表达式
* @return {Array}
*/
function analyseExprDataHotspot(expr) {
var refs = [];
function analyseExprs(exprs) {
each(exprs, function (expr) {
refs = refs.concat(analyseExprDataHotspot(expr));
});
}
switch (expr.type) {
case ExprType.ACCESSOR:
var paths = expr.paths;
refs.push(paths[0].value);
if (paths.length > 1) {
refs.push(paths[0].value + '.' + (paths[1].value || '*'));
}
analyseExprs(paths.slice(1));
break;
case ExprType.UNARY:
return analyseExprDataHotspot(expr.expr);
case ExprType.TEXT:
case ExprType.BINARY:
case ExprType.TERTIARY:
analyseExprs(expr.segs);
break;
case ExprType.INTERP:
refs = analyseExprDataHotspot(expr.expr);
each(expr.filters, function (filter) {
analyseExprs(filter.name.paths);
analyseExprs(filter.args);
});
break;
}
return refs;
}
exports = module.exports = componentPreheat;
|
import React, {useState} from "react";
import Button from '@mui/material/Button';
// import DeleteIcon from '@mui/icons-material/Delete';
export default function ItemDelete({books}) {
const [updateList, setUpdateList] = useState([]);
return (
<Button variant="outlined"
color="error"
// startIcon={<DeleteIcon />}
onClick={() => {updateList.filter(books => {
setUpdateList()
})
}}>
Delete
</Button>
)
};
|
/**
* js/component/pageMenu.js
*/
let $ = require('jquery');
let event = require('Services/event');
let ajax = require('Services/ajax');
let modal = require('Component/modal');
let notify = require('Component/notify');
let pageMenu = require('Component/pageMenu');
function loadHelp(url) {
ajax.get({url: url}).then(function(response) {
let content = $('<div class="help-content">' + response.data.content + '</div>');
// This allows the links in the embedded help docs to load in the current view
content.find('a.help-link').click(function(e) {
clickHelpLink(this, e);
});
help.augmentMarkup(content);
modal.display('Help', content);
}).catch(function() {
notify.error("Oh man, it looks like we can't find the help section for this page.");
}).finally(function() {
pageMenu.close();
});
}
function clickHelpLink(link, e) {
// Allow the link to load in a new tab
let clickEvent = event(e);
if (clickEvent.openingInNewWindow()) {
pageMenu.close();
return;
}
clickEvent.preventDefault();
let url = $(link).attr('href');
loadHelp(url);
}
$(function() {
$(".load-help-link").click(function(e) {
clickHelpLink(this, e);
});
});
let help = {};
help.augmentMarkup = function(content) {
let augmentedContent = $(content);
augmentedContent.find('.tip').prepend("<h5>Tip!</h5>");
augmentedContent.find('.note').prepend("<h5>Note</h5>");
return augmentedContent;
};
module.exports = help;
|
import imageio
import re
from pydot import Dot, Edge, Node, Subgraph
class Machine:
"""
The abstract class for a Turing Machine.
"""
def __init__(self):
"""
Initializes the Machine object.
"""
self._symbols = set()
self._blank_symbol = None
self._states = set()
self._start_state = None
self._end_states = set()
self._transitions = {}
self._current_state = None
self._tape = None
self._head = None
def _set_symbol(self, symbol, blank=False):
"""
Adds a symbol to the set of symbols of the Machine.
Sets the blank symbol only if it is not already set.
Arguments:
symbol {str} -- symbol
Keyword Arguments:
blank {bool} -- whether the symbol must be set as the blank symbol (default: {False})
"""
self._symbols.add(symbol)
try:
assert self._blank_symbol == None or not blank
if blank:
self._blank_symbol = symbol
except:
raise Exception(
f"Machine got blank symbol '{symbol}' which is already set to '{self._blank_symbol}'"
)
def _set_state(self, state, start=False, end=False):
"""
Adds a state to the set of states of the Machine.
Sets the start state only if it is not already set.
Arguments:
state {str} -- state
Keyword Arguments:
start {bool} -- whether the symbol must be set as the start state (default: {False})
end {bool} -- whether the symbol must be set as the end state (default: {False})
"""
self._states.add(state)
if end:
self._end_states.add(state)
try:
assert self._start_state == None or not start
if start:
self._start_state = state
except:
raise Exception(
f"Machine got start state '{state}' which is already set to '{self._start_state}'"
)
def _set_transition(
self, current_state, current_symbol, next_symbol, direction, next_state
):
"""
Adds a transition to the set of transitions of the Machine.
Arguments:
current_state {str} -- current State
current_symbol {str} -- current Symbol
next_symbol {str} -- next Symbol
direction {bool} -- direction
next_state {str} -- next State
"""
self._set_symbol(current_symbol)
self._set_symbol(next_symbol)
self._set_state(current_state)
self._set_state(next_state)
if self._transitions.get(current_state) is None:
self._transitions[current_state] = {}
self._transitions[current_state][current_symbol] = (
next_symbol,
direction,
next_state,
)
def parse(self, definition):
"""
Parses a definition for a Machine object.
Arguments:
definition {str} -- definition
"""
comment_re = re.compile(r"(#.*)")
state_re = re.compile(r"^([a-zA-Z_][a-zA-Z0-9_]*)([.*])?$")
transition_re = re.compile(
r"^'(.)'\s+'(.)'\s+([<>])\s+([a-zA-Z_][a-zA-Z0-9_]*)$"
)
lines = list(
filter(
lambda x: len(x) > 0,
map(lambda x: comment_re.sub("", x).strip(), definition.split("\n")),
)
)
self._set_symbol(lines.pop(0)[1], True)
scope_state = None
for l in lines:
try:
g = state_re.match(l).groups()
scope_state = g[0]
special = g[1] if g[1] is not None else ""
self._set_state(scope_state, "*" in special, "." in special)
except:
pass
try:
g = transition_re.match(l).groups()
self._set_transition(scope_state, g[0], g[1], g[2] is ">", g[3])
except:
pass
def reset(self, tape):
"""
Resets the tape, head and state of the Machine.
Arguments:
tape {[type]} -- string of tape symbols
"""
self._current_state = self._start_state
self._tape = list(tape)
self._head = 0
def step(self):
"""
Performs one Machine step.
Returns:
{bool} -- whether or not the Machine halted
"""
try:
current_symbol = self._tape[self._head]
next_symbol, direction, self._current_state = self._transitions.get(
self._current_state
).get(current_symbol)
except:
return True
self._tape[self._head] = next_symbol
self._head += 1 if direction else -1
if self._head < 0:
self._tape.insert(0, self._blank_symbol)
self._head = 0
elif self._head >= len(self._tape):
self._tape.append(self._blank_symbol)
self._head = len(self._tape) - 1
return False
def run(self, tape, max_steps=200, animate=False, **kwargs):
"""
Performs a computation by the Machine on a tape
Arguments:
tape {str} -- string of tape symbols
Keyword Arguments:
max_steps {int} -- maximum steps before forcing halt (default: {200})
animate {bool} -- whether to call animation functionality (default: {False})
Returns:
({bool}, {bool}, {str}) -- whether it halted, whether it accepted, final tape
"""
self.reset(tape)
halt = False
if animate:
try:
assert kwargs.get("filename") is not None
except:
raise Exception("Specify a filename to save the animation")
images = []
for _ in range(max_steps):
if animate:
images.append(
imageio.imread(self.graph(False).create(prog="dot", format="png"))
)
images.append(
imageio.imread(self.graph(True).create(prog="dot", format="png"))
)
halt = self.step()
if halt:
break
if animate:
imageio.mimsave(kwargs.get("filename"), images, fps=kwargs.get("fps"))
return (
halt,
halt and self._current_state in self._end_states,
"".join(self._tape).strip(self._blank_symbol),
)
def graph(self, context=None, **kwargs):
"""
Returns a graph object
Keyword Arguments:
context {bool|None} -- controls the animations (default: {None})
Returns:
[pydot.Dot] -- graph object
"""
graph = Dot(graph_type="digraph", rankdir=("LR" if context is None else "TB"))
machine_graph = Subgraph(
graph_name="cluster_machine", graph_type="digraph", label="MACHINE"
)
for current_state in sorted(self._states):
node_args = {}
shape = "circle"
shape = ("double" if current_state in self._end_states else "") + shape
node_args["shape"] = shape
if context is not None and current_state == self._current_state:
node_args["fillcolor"] = "cyan"
node_args["style"] = "filled"
machine_graph.add_node(Node(current_state, **node_args))
machine_graph.add_node(Node("0", shape="point"))
machine_graph.add_edge(Edge("0", self._start_state))
for current_state in self._states:
transitions = self._transitions.get(current_state)
if transitions:
for current_symbol in transitions:
next_symbol, direction, next_state = transitions.get(current_symbol)
label = f"'{current_symbol}' '{next_symbol}' {'R' if direction else 'L'}"
edge_args = {}
if (
context
and current_state == self._current_state
and current_symbol == self._tape[self._head]
):
edge_args["color"] = "cyan"
machine_graph.add_edge(
Edge(current_state, next_state, label=label, **edge_args)
)
graph.add_subgraph(machine_graph)
if context is not None:
tape_graph = Subgraph(
graph_name="cluster_tape", graph_type="digraph", label="TAPE"
)
tape = []
for index in range(-4 + self._head, 5 + self._head):
tape.append(
f"<t{index}> {self._tape[index] if 0 <= index < len(self._tape) else self._blank_symbol}"
)
tape_graph.add_node(Node("tape", label="|".join(tape), shape="record"))
tape_graph.add_node(Node("t0", shape="point"))
tape_graph.add_edge(Edge("t0", f"tape:t{self._head}"))
graph.add_subgraph(tape_graph)
if kwargs.get("filename"):
graph.write(kwargs.get("filename"), format="png")
return f"Graph saved to {kwargs.get('filename')}"
return graph
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M3 10h11v2H3zm0-4h11v2H3zm0 8h7v2H3zm13-1v8l6-4z"
}), 'PlaylistPlaySharp');
exports.default = _default;
|
(function(e){"function"==typeof define&&define.amd?define(["jquery","moment"],e):e(jQuery,moment)})(function(e,t){var n={1:"१",2:"२",3:"३",4:"४",5:"५",6:"६",7:"७",8:"८",9:"९",0:"०"},a={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"};(t.defineLocale||t.lang).call(t,"hi",{months:"जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर".split("_"),monthsShort:"जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.".split("_"),weekdays:"रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार".split("_"),weekdaysShort:"रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि".split("_"),weekdaysMin:"र_सो_मं_बु_गु_शु_श".split("_"),longDateFormat:{LT:"A h:mm बजे",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, LT",LLLL:"dddd, D MMMM YYYY, LT"},calendar:{sameDay:"[आज] LT",nextDay:"[कल] LT",nextWeek:"dddd, LT",lastDay:"[कल] LT",lastWeek:"[पिछले] dddd, LT",sameElse:"L"},relativeTime:{future:"%s में",past:"%s पहले",s:"कुछ ही क्षण",m:"एक मिनट",mm:"%d मिनट",h:"एक घंटा",hh:"%d घंटे",d:"एक दिन",dd:"%d दिन",M:"एक महीने",MM:"%d महीने",y:"एक वर्ष",yy:"%d वर्ष"},preparse:function(e){return e.replace(/[१२३४५६७८९०]/g,function(e){return a[e]})},postformat:function(e){return e.replace(/\d/g,function(e){return n[e]})},meridiem:function(e){return 4>e?"रात":10>e?"सुबह":17>e?"दोपहर":20>e?"शाम":"रात"},week:{dow:0,doy:6}}),e.fullCalendar.datepickerLang("hi","hi",{closeText:"बंद",prevText:"पिछला",nextText:"अगला",currentText:"आज",monthNames:["जनवरी ","फरवरी","मार्च","अप्रेल","मई","जून","जूलाई","अगस्त ","सितम्बर","अक्टूबर","नवम्बर","दिसम्बर"],monthNamesShort:["जन","फर","मार्च","अप्रेल","मई","जून","जूलाई","अग","सित","अक्ट","नव","दि"],dayNames:["रविवार","सोमवार","मंगलवार","बुधवार","गुरुवार","शुक्रवार","शनिवार"],dayNamesShort:["रवि","सोम","मंगल","बुध","गुरु","शुक्र","शनि"],dayNamesMin:["रवि","सोम","मंगल","बुध","गुरु","शुक्र","शनि"],weekHeader:"हफ्ता",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""}),e.fullCalendar.lang("hi",{defaultButtonText:{month:"महीना",week:"सप्ताह",day:"दिन",list:"कार्यसूची"},allDayText:"सभी दिन"})});
|
"use strict";
exports.__esModule = true;
exports.default = void 0;
var _popover = _interopRequireDefault(require("./popover"));
exports.BPopover = _popover.default;
var _popover2 = _interopRequireDefault(require("../../directives/popover/popover"));
var _plugins = require("../../utils/plugins");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var components = {
BPopover: _popover.default
};
var directives = {
VBPopover: _popover2.default
};
var _default = {
install: (0, _plugins.installFactory)({
components: components,
directives: directives
})
};
exports.default = _default;
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long
# pylint: disable=too-few-public-methods
import unittest
import mock
from azure.cli.core.azclierror import ValidationError
from azure.mgmt.web import WebSiteManagementClient
from azure.mgmt.web.models import HostingEnvironmentProfile
from azure.mgmt.network.models import (Subnet, RouteTable, Route, NetworkSecurityGroup, SecurityRule, Delegation)
from azure.cli.core.adal_authentication import AdalAuthentication
from azure.cli.command_modules.appservice.appservice_environment import (show_appserviceenvironment,
list_appserviceenvironments,
list_appserviceenvironment_plans,
list_appserviceenvironment_addresses,
create_appserviceenvironment_arm,
update_appserviceenvironment,
delete_appserviceenvironment)
class AppServiceEnvironmentScenarioMockTest(unittest.TestCase):
def setUp(self):
self.mock_logger = mock.MagicMock()
self.mock_cmd = mock.MagicMock()
self.mock_cmd.cli_ctx = mock.MagicMock()
self.client = WebSiteManagementClient(AdalAuthentication(lambda: ('bearer', 'secretToken')), '123455678')
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_ase_client_factory', autospec=True)
def test_app_service_environment_show(self, ase_client_factory_mock):
ase_name = 'mock_ase_name'
rg_name = 'mock_rg_name'
ase_client = mock.MagicMock()
ase_client_factory_mock.return_value = ase_client
host_env = HostingEnvironmentProfile(id='id1')
host_env.name = ase_name
host_env.resource_group = rg_name
ase_client.get.return_value = host_env
ase_client.list.return_value = [host_env]
result = show_appserviceenvironment(self.mock_cmd, ase_name, None)
# Assert same name
self.assertEqual(result.name, ase_name)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_ase_client_factory', autospec=True)
def test_app_service_environment_list(self, ase_client_factory_mock):
ase_name_1 = 'mock_ase_name_1'
ase_name_2 = 'mock_ase_name_2'
rg_name_1 = 'mock_rg_name_1'
rg_name_2 = 'mock_rg_name_2'
ase_client = mock.MagicMock()
ase_client_factory_mock.return_value = ase_client
host_env1 = HostingEnvironmentProfile(id='id1')
host_env1.name = ase_name_1
host_env1.resource_group = rg_name_1
host_env2 = HostingEnvironmentProfile(id='id2')
host_env2.name = ase_name_2
host_env2.resource_group = rg_name_2
ase_client.list.return_value = [host_env1, host_env2]
# Assert listvips is called
list_appserviceenvironment_addresses(self.mock_cmd, ase_name_1)
ase_client.get_vip_info.assert_called_with(rg_name_1, ase_name_1)
# Assert list_app_service_plans is called
list_appserviceenvironment_plans(self.mock_cmd, ase_name_2)
ase_client.list_app_service_plans.assert_called_with(rg_name_2, ase_name_2)
# Assert list return two instances
result = list_appserviceenvironments(self.mock_cmd, None)
self.assertEqual(len(result), 2)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_unique_deployment_name', autospec=True)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_resource_client_factory', autospec=True)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_network_client_factory', autospec=True)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_ase_client_factory', autospec=True)
def test_app_service_environment_create(self, ase_client_factory_mock, network_client_factory_mock,
resource_client_factory_mock, deployment_name_mock):
ase_name = 'mock_ase_name'
rg_name = 'mock_rg_name'
vnet_name = 'mock_vnet_name'
subnet_name = 'mock_subnet_name'
deployment_name = 'mock_deployment_name'
ase_client = mock.MagicMock()
ase_client_factory_mock.return_value = ase_client
resource_client_mock = mock.MagicMock()
resource_client_factory_mock.return_value = resource_client_mock
deployment_name_mock.return_value = deployment_name
network_client = mock.MagicMock()
network_client_factory_mock.return_value = network_client
subnet = Subnet(id=1, address_prefix='10.10.10.10/25')
network_client.subnets.get.return_value = subnet
# assert that ValidationError raised when called with small subnet
with self.assertRaises(ValidationError):
create_appserviceenvironment_arm(self.mock_cmd, resource_group_name=rg_name, name=ase_name,
subnet=subnet_name, vnet_name=vnet_name,
ignore_network_security_group=True, ignore_route_table=True,
location='westeurope')
subnet = Subnet(id=1, address_prefix='10.10.10.10/24')
network_client.subnets.get.return_value = subnet
create_appserviceenvironment_arm(self.mock_cmd, resource_group_name=rg_name, name=ase_name,
subnet=subnet_name, vnet_name=vnet_name,
ignore_network_security_group=True, ignore_route_table=True,
location='westeurope')
# Assert create_or_update is called with correct rg and deployment name
resource_client_mock.deployments.create_or_update.assert_called_once()
self.assertEqual(resource_client_mock.deployments.create_or_update.call_args[0][0], rg_name)
self.assertEqual(resource_client_mock.deployments.create_or_update.call_args[0][1], deployment_name)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_location_from_resource_group', autospec=True)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_ase_client_factory', autospec=True)
def test_app_service_environment_update(self, ase_client_factory_mock, resource_group_mock):
ase_name = 'mock_ase_name'
rg_name = 'mock_rg_name'
ase_client = mock.MagicMock()
ase_client_factory_mock.return_value = ase_client
resource_group_mock.return_value = rg_name
host_env = HostingEnvironmentProfile(id='id1')
host_env.name = ase_name
host_env.kind = 'ASEv2'
host_env.resource_group = rg_name
host_env.worker_pools = []
ase_client.get.return_value = host_env
ase_client.list.return_value = [host_env]
update_appserviceenvironment(self.mock_cmd, ase_name, front_end_scale_factor=10)
# Assert create_or_update is called with correct properties
assert_host_env = HostingEnvironmentProfile(id='id1')
assert_host_env.name = ase_name
assert_host_env.kind = 'ASEv2'
assert_host_env.resource_group = rg_name
assert_host_env.worker_pools = []
assert_host_env.internal_load_balancing_mode = None
assert_host_env.front_end_scale_factor = 10
ase_client.begin_create_or_update.assert_called_once_with(resource_group_name=rg_name, name=ase_name,
hosting_environment_envelope=assert_host_env)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_location_from_resource_group', autospec=True)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_ase_client_factory', autospec=True)
def test_app_service_environment_delete(self, ase_client_factory_mock, resource_group_mock):
ase_name = 'mock_ase_name'
rg_name = 'mock_rg_name'
ase_client = mock.MagicMock()
ase_client_factory_mock.return_value = ase_client
resource_group_mock.return_value = rg_name
host_env = HostingEnvironmentProfile(id='id1')
host_env.name = ase_name
host_env.resource_group = rg_name
host_env.worker_pools = []
ase_client.get.return_value = host_env
ase_client.list.return_value = [host_env]
delete_appserviceenvironment(self.mock_cmd, ase_name)
# Assert delete is called with correct properties
assert_host_env = HostingEnvironmentProfile(id='id1')
assert_host_env.name = ase_name
assert_host_env.resource_group = rg_name
ase_client.begin_delete.assert_called_once_with(name=ase_name, resource_group_name=rg_name)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_unique_deployment_name', autospec=True)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_resource_client_factory', autospec=True)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_network_client_factory', autospec=True)
@mock.patch('azure.cli.command_modules.appservice.appservice_environment._get_ase_client_factory', autospec=True)
def test_app_service_environment_v3_create(self, ase_client_factory_mock, network_client_factory_mock,
resource_client_factory_mock, deployment_name_mock):
ase_name = 'mock_ase_name'
rg_name = 'mock_rg_name'
vnet_name = 'mock_vnet_name'
subnet_name = 'mock_subnet_name'
deployment_name = 'mock_deployment_name'
ase_client = mock.MagicMock()
ase_client_factory_mock.return_value = ase_client
resource_client_mock = mock.MagicMock()
resource_client_factory_mock.return_value = resource_client_mock
deployment_name_mock.return_value = deployment_name
network_client = mock.MagicMock()
network_client_factory_mock.return_value = network_client
subnet = Subnet(id=1, address_prefix='10.10.10.10/24')
hosting_delegation = Delegation(id=1, service_name='Microsoft.Web/hostingEnvironments')
subnet.delegations = [hosting_delegation]
network_client.subnets.get.return_value = subnet
create_appserviceenvironment_arm(self.mock_cmd, resource_group_name=rg_name, name=ase_name,
subnet=subnet_name, vnet_name=vnet_name, kind='ASEv3',
location='westeurope')
# Assert create_or_update is called with correct rg and deployment name
resource_client_mock.deployments.create_or_update.assert_called_once()
self.assertEqual(resource_client_mock.deployments.create_or_update.call_args[0][0], rg_name)
self.assertEqual(resource_client_mock.deployments.create_or_update.call_args[0][1], deployment_name)
if __name__ == '__main__':
unittest.main()
|
(function() {
angular
.module('app.free')
.factory('FreeFactory', FreeFactory);
function FreeFactory($http, $q, $timeout){
var services = {
play: play,
createSeqArray: createSeqArray,
cycleColumns: cycleColumns,
findUnit: findUnit,
timeout: timeout
};
ion.sound({
sounds: [
{
name: "kick",
volume: 0.5,
preload: false
},
{
name: "snare",
volume: 0.5,
preload: false
},
{
name: "high_hat",
volume: 0.5,
preload: false
}
],
volume: 0.5,
path: "sounds/",
preload: true,
multiplay: true
});
function play (sample) {
console.log(sample);
ion.sound.play(sample);
}
function createSeqArray(array, rows, columns) {
//create rows
for (var i = 0; i < rows; i++) {
array.push([]);
for (var j = 0; j < columns; j++) {
array[i].push({
row: i,
col: j
});
}
}
}
function findUnit(array, r, c, cb) {
cb(array[r][c]);
}
// cycles through a single row's columns
function cycleColumns(row, cb) {
for (var i = 0; i < row.length; i++) {
cb(row, row[i], i);
}
}
function timeout(object, index, time, cb) {
$timeout(function() {
cb(object);
}, index * time);
}
return services;
}
})();
|
(function() {
var controlBase = Vue.component("controls-base", {
props: ["name", "value", "fields"],
methods: {
change: function(value) {
// console.log(this.name, value);
this.$emit("change", {
name: this.name,
value: value
});
}
}
});
Vue.component("control-string", {
template: Kooboo.getTemplate(
"/_Admin/Scripts/components/extensionEditor/string.html"
),
extends: controlBase
});
Vue.component("control-textarea", {
template: Kooboo.getTemplate(
"/_Admin/Scripts/components/extensionEditor/textarea.html"
),
extends: controlBase
});
Vue.component("control-checkbox", {
template: Kooboo.getTemplate(
"/_Admin/Scripts/components/extensionEditor/checkbox.html"
),
extends: controlBase,
computed: {
checked: function() {
return this.value === "True" || this.value === "true";
}
}
});
Vue.component("control-order", {
template: Kooboo.getTemplate(
"/_Admin/Scripts/components/extensionEditor/orderBy.html"
),
extends: controlBase,
computed: {
selectedValue: function() {
var self = this;
var value = this.value;
if (this.fields && this.fields.length) {
if (
!this.value ||
!_.some(this.fields, function(field) {
return self.value === field.name;
})
) {
value = this.fields[0].name;
this.change(value);
}
}
return value;
}
}
});
Vue.component("control-filter", {
template: Kooboo.getTemplate(
"/_Admin/Scripts/components/extensionEditor/filter.html"
),
extends: controlBase,
data: function() {
return {
values: []
};
},
created: function() {
var self = this;
this.debounceChange = _.debounce(function() {
if (self.fields && self.fields.length) {
self.change(self.values);
} else {
self.change([]);
}
}, 400);
},
methods: {
selectField: function(filter) {
if (this.fields) {
var choosedOperator = this.fields.filter(function(item) {
return item.name === filter.key;
})[0];
if (choosedOperator) {
filter.operators = choosedOperator.operators;
if (
!filter.comparison ||
filter.operators.indexOf(filter.comparison) === -1
) {
filter.comparison = filter.operators[0];
}
} else {
filter.operators = [];
filter.comparison = "";
}
}
},
add: function() {
var filter = {
key: this.fields ? this.fields[0].name : "Id",
value: "",
comparison: ""
};
this.selectField(filter);
this.values.push(filter);
},
remove: function(i) {
this.values.splice(i, 1);
}
},
watch: {
fields: function(val) {
var self = this;
this.values = [];
if (val && val.length) {
if (
this.value !== undefined &&
this.value !== "" &&
this.value !== "[{}]"
) {
var values = JSON.parse(this.value);
if (Array.isArray(values) && values.length) {
values.forEach(function(item) {
var filter = {
key: item.FieldName,
value: item.FieldValue,
comparison: item.Comparer
};
self.selectField(filter);
self.values.push(filter);
});
}
}
}
},
values: {
handler: function() {
this.debounceChange();
},
deep: true
}
}
});
var controlCollection = Vue.component("control-collection", {
template: Kooboo.getTemplate(
"/_Admin/Scripts/components/extensionEditor/collection.html"
),
extends: controlBase,
data: function() {
return {
values: []
};
},
created: function() {
var self = this;
this.debounceChange = _.debounce(function() {
self.change(self.values);
}, 400);
},
mounted: function() {
if (!this.value) {
var values = JSON.parse(this.value);
if (Array.isArray(values) && values.length) {
this.values = values;
} else {
this.values = [];
}
} else {
this.values = [];
}
},
methods: {
add: function() {
this.values.push({
value: ""
});
},
remove: function(i) {
this.values.splice(i, 1);
}
},
watch: {
values: {
handler: function() {
this.debounceChange();
},
deep: true
}
}
});
Vue.component("control-dictionary", {
template: Kooboo.getTemplate(
"/_Admin/Scripts/components/extensionEditor/dictionary.html"
),
extends: controlCollection,
methods: {
add: function() {
this.values.push({
key: "",
value: ""
});
}
}
});
})();
|