text
stringlengths
7
3.69M
/* * grunt-topojson * https://github.com/mark.dimarco/grunt-topojson * * Copyright (c) 2014 Mark DiMarco * Licensed under the MIT license. */ 'use strict'; var topojson = require('topojson'); var _ = require('underscore'); module.exports = function(grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('topojson', 'Convert GeoJSON to TopoJSON', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ punctuation: '.', separator: ', ', target: this.target }); // Iterate over all specified file groups. this.files.forEach(function(f) { // Concat specified files. var src = f.src.filter(function(filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).map(function(filepath) { // Read file source. return grunt.file.read(filepath); }).join(grunt.util.normalizelf(options.separator)); var srcLength = src.length; var geoJSON = JSON.parse(src); /* If an `idProperty` is specified, look for that under the `properties` object. Default topojson behavior: `id` property */ if ( !_.isUndefined(options.idProperty) ) { options.id = function(d) { return d && d.properties && d.properties[options.idProperty]; }; } /* If `copyProperties` specified, only copy those properties. If an empty array is sent, copy no properties. If nothing is sent (null, undefined), default to copying all properties. */ if ( _.isArray(options.copyProperties) ) { options['property-transform'] = function(properties, key, value) { if ( _.contains(options.copyProperties, key)) { properties[key] = value; } return true; }; } else { options['property-transform'] = function(properties, key, value) { properties[key] = value; return true; }; } /* Set the collection name */ var collection = {}; if ( !_.isUndefined(options.collectionName) ) { collection[options.collectionName] = geoJSON; } else { collection[options.target] = geoJSON; } /* Convert GeoJSON to TopoJSON */ var topology = topojson.topology(collection, options); var targetLength = JSON.stringify(topology).length; // Write the destination file. grunt.file.write(f.dest, JSON.stringify(topology)); // Print a success message. grunt.log.writeln('File "' + f.dest + '" created.'); grunt.log.writeln('Original GeoJSON Size:', ~~(srcLength / 1024), 'KB. '); grunt.log.writeln('TopoJSON Size:', ~~(targetLength / 1024), 'KB\n'); }); }); };
function getTotalX(one,two) { let fs = one.reduce((a,b) => Math.max(a, b)) let sc = two.reduce((a,b) => Math.min(a,b)) let middle = Array.apply(null, Array(sc)).map((a,b) => b+1).filter(i => i % fs == 0) return middle } // console.log(getTotalX([2],[20,30,12])) // should yield 1 // console.log(getTotalX([2,4],[16,32,96])) // should yield
var queue = exports.q || exports; // if string syntax, setup as function if (exports.hasOwnProperty('q')) { // if string syntax exports = window['@@name'] = function () { var args = Array.prototype.slice.call(arguments); var method = args.shift(); if (exports.hasOwnProperty(method)) { exports[method].apply(exports, args); } }; } // make the widget a dispatcher dispatcher(exports); function setup() { var i = queue.length; while(i--) { var args = Array.prototype.slice.call(queue[i]); var method = args.shift(); if (method === 'authorize' || method === 'on') { if (exports.hasOwnProperty(method)) { queue.splice(i, 1); exports[method].apply(exports, args); } } } } /** * Fired by init.js if successful, initializes the rest of the queued items */ exports.on('authorize::success', function () { var len = queue.length; for (var i = 0; i < len; i += 1) { var args = Array.prototype.slice.call(queue[i]); var method = args.shift(); if (exports.hasOwnProperty(method)) { try { exports[method].apply(exports, args); } catch (e) { } } } queue.length = 0; }); setTimeout(setup);
import Store from '../store'; import Dispatcher from '../dispatcher'; import symbols from '../symbols'; /** * A Store is a singleton whose job is to contain data and notify changes * to listeners. * * We'll usually use EventEmitter to manage subscriptions and event notifications * but that code is best kept in one place - a Store object. * * Each specific store is responsible for a specific type of data. */ const UsersStore = Object.assign({}, Store, { text: "Hello World", setText: function(text) { this.text = text; this.trigger(); }, }); /** * A dispatcher makes sure an action doesn't need to know which store * it affects. * * Every action is delivered to EVERY store in the system. * * An action represents an event, and the store is responsible to modifying * its data according to the event. * A dispatchToken is used to specify event handling order: each store can use * another store's dispatch token to wait for that store to handle the event * via the method Dispatcher.waitFor(anotherStoreDispatchToken) */ UsersStore.dispatchToken = Dispatcher.register(function(action) { switch(action.type) { // handle incoming events and modify store data case symbols.SET_HELLO_TEXT: UsersStore.setText(action.payload); break; } }); export default UsersStore;
/** * Javascript for animal page */ {aBreedsVar} $(document).ready(function() { $('#selSpecie').change(function(){ setBreedOptions(this.value); }); $('#frmEntryPane').click(function() { if ($('#boiteaddmsg').is(':visible')) { $('#boiteaddmsg').slideUp(); $('#frmEntryPane').text('{lang_click_new_animal}'); resetForm(); } else { $('#boiteaddmsg').slideDown(); $('#frmEntryPane').html('<img class="commonImage" title="{lang_hide_new_animal_form}" src="/images/btn-delete.gif" />'); $('#frmAnimal').focus(); } return false; }); // Padding of entry fields $('.divAnimalEntry label').css({textAlign:"right", paddingRight:"10px", display:"block", width:"110px", float:"left", marginTop:"3px"}); $('.divAnimalEntry input,select').css({display:"block", float:"left", marginBottom:"1px"}); $('.divAnimalEntry br').css({clear:"left"}); // Padding of entry fields on the right $('.divAnimalEntryR label').css({textAlign:"right", paddingRight:"10px", display:"block", width:"80px", float:"left", marginTop:"3px"}); $('.divAnimalEntryR input[type=text]').css({display:"block", float:"left", marginBottom:"1px"}); $('.divAnimalEntryR input[type=checkbox]').css({textAlign:"left", float:"left", display:"block", margin:"1px 0px 0px 65px"}); $('.lblChkR').css({display:"block", textAlign:"left", float:"left", width:"210px", margin:"2px 0px 0px 0px"}); $('.divAnimalEntryR br').css({clear:"left"}); Date.firstDayOfWeek = 7; Date.format = 'mm/dd/yyyy'; $('.date-pick').datePicker({ startDate:'01/01/1990' }); // Default N/A for animal death date $('#frmDeathDate').focus(function(){ if (this.value == 'n/a') { this.value = ''; } }); $('#frmDeathDate').blur(function(){ if (this.value == '') { this.value = 'n/a'; } }); // Show auto hide message if it contains something if (($('#autoHideMessage').text() != '')) { $('.autoHidePane').css('display', 'inline'); } // Add submit button clears hidden: updateRowId so that it's understood to be an Add and not Update. $('#addRowBtn').click(function() { $('#updateRowId').val('') }); // Cancel update button $('#updateRowCancelBtn').click(function() { $('#frmEntryPane').text('{lang_click_new_animal}'); $('#boiteaddmsg').hide(); resetForm(); }); $('#frmEntryPane').html('<img class="commonImage" title="{lang_hide_new_animal_form}" src="/images/btn-delete.gif" />'); $("#tblSortable").tablesorter({ cssHeader: 'headSort', sortList:[[0,0]], headers: { 3: { sorter: false }, 4: { sorter: false } } }); }); function setBreedOptions(specieId) { var strOptions = ''; var isEmpty = true; for (var i in aBreedsVar[specieId]) { isEmpty = false; strOptions += "<option value='" + i + "'>" + aBreedsVar[specieId][i] + "</option>"; } if (isEmpty) { $('#selBreed').html('<option value="">{lang_dropdown_empty}</option>'); } else { $('#selBreed').html('<option value="">{lang_dropdown_select}</option>' + strOptions); } } // Validation function entryValidate() { var errMsg = ''; if ($('#frmDeathDate').val() != 'n/a') { if (isDate($('#frmDeathDate').val()) == false) { errMsg = "\n\t" + '{lang_pls_enter_valid_deathdate}' + errMsg; } } if ($('#frmBirthDate').val() != "") { if (isDate($('#frmBirthDate').val()) == false) { errMsg = "\n\t" + '{lang_pls_enter_valid_birthdate}' + errMsg; } } if ($('#selSpecie').val() == 0) { errMsg = "\n\t" + '{lang_pls_select_specie}' + errMsg; $('#selSpecie').focus(); } if ($('#selGender').val() == 0) { errMsg = "\n\t" + '{lang_pls_select_animal_gender}' + errMsg; $('#selGender').focus(); } if ($('#frmAnimal').val() == "") { errMsg = "\n\t" + '{lang_pls_enter_animal_name}' + errMsg; $('#frmAnimal').focus(); } if (errMsg == '') { if ($('#frmDeathDate').val() == 'n/a') { $('#frmDeathDate').val(''); } return true; } alert('{lang_correct_the_following}' + "\n" + errMsg); return false; } function rowDelete(rKey) { var ans = confirm('{lang_confirm_delete_animal}'); if (ans) { showMessage('{lang_processing}...', '<div style="line-height:25px"><img style="vertical-align:middle; padding-right: 10px;" border="0" src="/images/loading.gif" />{lang_wait_deleting_animal}...</div>', 'middle'); $.ajax({ type: "POST", url: "/animals/delete/" + rKey, success: function(msg){ if (msg == 'SUCCESS') { showMessage('{lang_success}', '{lang_animal_deletion_ok}', 'top'); setTimeout('hideMessage();', 3000); $('#row_' + rKey).hide(); // Hide from grid } else { showMessage('{lang_failure}', '{lang_animal_deletion_error}', 'middle'); } } }); } return false; } /** * Ajax call to get an animal */ function rowEdit(rKey, paramAnimalName) { // Reset entry form first. resetForm(); $('#updateRowId').val(rKey); nPhoneInstance = 0; $('#boiteaddmsg').slideDown(); $('#frmEntryPane').html('<img class="commonImage" title="{lang_hide_new_animal_form}" src="/images/btn-delete.gif" />'); // Ajax call to get client data showMessage('{lang_processing}...', '<div style="line-height:25px"><img style="vertical-align:middle; padding-right: 10px;" border="0" src="/images/loading.gif" />{lang_wait_reading_animal}...</div>', '400'); $.ajax({ type: "GET", url: "/animals/getJsonAnimal/" + rKey, contentType: "application/json; charset=utf-8", dataType: "json", async: false, success: function(ajaxRetVal){ window.aAnimal = ajaxRetVal; } }); //~ for(var i in aAnimal) { //~ // Loop to decode Db values //~ var chars = new Array ('&','à','á','â','ã','ä','å','æ','ç','è','é', //~ 'ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô', //~ 'õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ','À', //~ 'Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë', //~ 'Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö', //~ 'Ø','Ù','Ú','Û','Ü','Ý','Þ','€','\"','ß','<', //~ '>','¢','£','¤','¥','¦','§','¨','©','ª','«', //~ '¬','*','®','¯','°','±','²','³','´','µ','¶', //~ '·','¸','¹','º','»','¼','½','¾'); //~ var entities = new Array ('&amp;','&agrave;','&aacute;','&acirc;','&atilde;','&auml;','&aring;', //~ 'aelig;','&ccedil;','&egrave;','&eacute;','&ecirc;','&euml;','&igrave;', //~ 'iacute;','&icirc;','&iuml;','&eth;','&ntilde;','&ograve;','&oacute;', //~ 'ocirc;','&otilde;','&ouml;','&oslash;','&ugrave;','&uacute;','&ucirc;', //~ 'uuml;','&yacute;','&thorn;','&yuml;','&Agrave;','&Aacute;','&Acirc;', //~ 'Atilde;','&Auml;','&Aring;','&AElig;','&Ccedil;','&Egrave;','&Eacute;', //~ 'Ecirc;','&Euml;','&Igrave;','&Iacute;','&Icirc;','&Iuml;','&ETH;','&Ntilde;', //~ 'Ograve;','&Oacute;','&Ocirc;','&Otilde;','&Ouml;','&Oslash;','&Ugrave;', //~ 'Uacute;','&Ucirc;','&Uuml;','&Yacute;','&THORN;','&euro;','&quot;','&szlig;', //~ 'lt;','&gt;','&cent;','&pound;','&curren;','&yen;','&brvbar;','&sect;','&uml;', //~ 'copy;','&ordf;','&laquo;','&not;','&shy;','&reg;','&macr;','&deg;','&plusmn;', //~ 'sup2;','&sup3;','&acute;','&micro;','&para;','&middot;','&cedil;','&sup1;', //~ 'ordm;','&raquo;','&frac14;','&frac12;','&frac34;'); //~ var from = chars; //~ var to = entities; //~ for (var j = 0; j < from.length; j++) { //~ myRegExp = new RegExp(); //~ myRegExp.compile(to[j],'g') //~ aAnimal[i] = aAnimal[i].replace (myRegExp,from[j]); //~ } //~ aAnimal[i] = texte; //aAnimal[i] = aAnimal[i].replace(/&#(\d+);/g, //~ } // Assign values from DB $('#frmAnimal').val(paramAnimalName); $('#frmExternalId').val(aAnimal['animalExternalId']); $('#selGender').val(aAnimal['genderId']); $('#selSpecie').val(aAnimal['specieId']); setBreedOptions(aAnimal['specieId']); $('#selBreed').val(aAnimal['raceId']); if (aAnimal['birthDate']) { // Get the date stripping the time. aAnimal['birthDate'] = aAnimal['birthDate'].substring(0, 10); if (aAnimal['birthDate'] == '0000-00-00') { $('#frmBirthDate').val(''); } else { var aBirthDate = aAnimal['birthDate'].split('-'); $('#frmBirthDate').val(aBirthDate[1] + '/' + aBirthDate[2] + '/' + aBirthDate[0]); $('#frmBirthDate').dpSetSelected($('#frmBirthDate').val()); } } if (aAnimal['deathDate']) { // Get the date stripping the time. aAnimal['deathDate'] = aAnimal['deathDate'].substring(0, 10); if (aAnimal['deathDate'] == '0000-00-00') { $('#frmDeathDate').val('n/a'); } else { var aDeathDate = aAnimal['deathDate'].split('-'); $('#frmDeathDate').val(aDeathDate[1] + '/' + aDeathDate[2] + '/' + aDeathDate[0]); $('#frmDeathDate').dpSetSelected($('#frmDeathDate').val()); } } $('#chkIdentified').check(aAnimal['identifiedBoolean'] == 0 ? 'off' : 'on'); $('#chkActive').check(aAnimal['activeBoolean'] == 0 ? 'off' : 'on'); $('#chkVaccinated').check(aAnimal['vaccinatedBoolean'] == 0 ? 'off' : 'on'); $('#chkInsured').check(aAnimal['insuredBoolean'] == 0 ? 'off' : 'on'); // Hide Ajax message hideMessage(); $('.updateButtonFamily').show(); $('#frmAnimal').focus(); return false; } /** * Initializes message entry form */ function resetForm() { $("#form1")[0].reset(); $('.updateButtonFamily').hide(); } // eof
/* globals commonTests */ const THIRD_PARTY_ORIGIN = 'https://good.third-party.site'; const THIRD_PARTY_TRACKER_ORIGIN = 'https://broken.third-party.site'; const storeButton = document.querySelector('#store'); const retriveButton = document.querySelector('#retrive'); const downloadButton = document.querySelector('#download'); const testsDiv = document.querySelector('#tests'); const testsSummaryDiv = document.querySelector('#tests-summary'); const testsDetailsElement = document.querySelector('#tests-details'); // object that contains results of all tests const results = { page: 'storage-blocking', date: null, results: [] }; function create3pIframeTest (name, origin) { return { id: `${name} third party iframe`, store: (data) => { let res, rej; const promise = new Promise((resolve, reject) => { res = resolve; rej = reject; }); const iframe = document.createElement('iframe'); iframe.src = `${origin}/privacy-protections/storage-blocking/iframe.html?data=${data}`; iframe.style.width = '10px'; iframe.style.height = '10px'; let failTimeout = null; function cleanUp (msg) { if (msg.origin === origin && msg.data) { res(msg.data); clearTimeout(failTimeout); document.body.removeChild(iframe); window.removeEventListener('message', cleanUp); } } window.addEventListener('message', cleanUp); iframe.addEventListener('load', () => { failTimeout = setTimeout(() => rej('timeout'), 1000); }); document.body.appendChild(iframe); return promise; }, retrive: () => { let res, rej; const promise = new Promise((resolve, reject) => { res = resolve; rej = reject; }); const iframe = document.createElement('iframe'); iframe.src = `${origin}/privacy-protections/storage-blocking/iframe.html`; iframe.style.width = '10px'; iframe.style.height = '10px'; let failTimeout = null; function cleanUp (msg) { if (msg.origin === origin && msg.data) { res(msg.data); clearTimeout(failTimeout); document.body.removeChild(iframe); window.removeEventListener('message', cleanUp); } } window.addEventListener('message', cleanUp); iframe.addEventListener('load', () => { failTimeout = setTimeout(() => rej('timeout'), 1000); }); document.body.appendChild(iframe); return promise; } }; } const tests = [ { id: 'first party header cookie', store: (data) => { return fetch(`/set-cookie?value=${data}`).then(r => { if (!r.ok) { throw new Error('Request failed.'); } }); }, retrive: () => { return fetch('/reflect-headers') .then(r => r.json()) .then(data => data.headers.cookie.match(/headerdata=([0-9]+)/)[1]); } }, { id: 'safe third party header cookie', store: (data) => { return fetch(`${THIRD_PARTY_ORIGIN}/set-cookie?value=${data}`, { credentials: 'include' }).then(r => { if (!r.ok) { throw new Error('Request failed.'); } }); }, retrive: () => { return fetch(`${THIRD_PARTY_ORIGIN}/reflect-headers`, { credentials: 'include' }) .then(r => r.json()) .then(data => data.headers.cookie.match(/headerdata=([0-9]+)/)[1]); } }, { id: 'tracking third party header cookie', store: (data) => { return fetch(`${THIRD_PARTY_TRACKER_ORIGIN}/set-cookie?value=${data}`, { credentials: 'include' }).then(r => { if (!r.ok) { throw new Error('Request failed.'); } }); }, retrive: () => { return fetch(`${THIRD_PARTY_TRACKER_ORIGIN}/reflect-headers`, { credentials: 'include' }) .then(r => r.json()) .then(data => data.headers.cookie.match(/headerdata=([0-9]+)/)[1]); } }, create3pIframeTest('safe', THIRD_PARTY_ORIGIN), create3pIframeTest('tracking', THIRD_PARTY_TRACKER_ORIGIN), { id: 'browser cache', store: (data) => { // already done before all tests }, retrive: () => { return fetch('/cached-random-number', { cache: 'force-cache' }).then(r => r.text()); } }, { id: 'memory', store: (data) => { window.randomNumber = data; }, retrive: () => { return window.randomNumber; } }, { id: 'window.name', store: (data) => { window.name = data; }, retrive: () => { return window.name; } }, { id: 'history', store: (data) => { history.pushState({ data: data }, 'data', `#${data}`); }, retrive: () => { if (history.state) { return history.state.data; } const hash = (new URL(location.href)).hash; if (hash) { return hash.replace('#', ''); } } }, { id: 'service worker', store: (data) => { return navigator.serviceWorker.register(`./service-worker.js?data=${data}`, { scope: './' }) .then(() => 'OK') .catch((error) => { console.log('Registration failed with ' + error); }); }, retrive: () => { return fetch('./service-worker-data') .then(r => { if (r.ok) { return r.text(); } throw new Error(`Invalid response (${r.status})`); }); } } ]; function storeData () { storeButton.setAttribute('disabled', 'disabled'); downloadButton.setAttribute('disabled', 'disabled'); testsDiv.removeAttribute('hidden'); let all = 0; let failed = 0; testsDetailsElement.innerHTML = ''; function updateSummary (data) { testsSummaryDiv.innerText = `Stored random number "${data}" using ${all} storage mechanisms${failed > 0 ? ` (${failed} failed)` : ''}. Click for details.`; } fetch('/cached-random-number', { cache: 'reload' }) .then(r => r.text()) .then(randomNumber => { tests.concat(commonTests).forEach(test => { all++; const li = document.createElement('li'); li.id = `test-${test.id.replace(/ /g, '-')}`; li.innerHTML = `${test.id} - <span class='value'>OK</span>`; const valueSpan = li.querySelector('.value'); testsDetailsElement.appendChild(li); try { const result = test.store(randomNumber); if (result instanceof Promise) { valueSpan.innerText = '…'; result .then(result => { if (Array.isArray(result)) { valueSpan.innerHTML = `<ul>${result.map(r => `<li>${r.test} - ${r.result}</li>`).join('')}</ul>`; } else if (result && result !== 'OK') { valueSpan.innerHTML = JSON.stringify(result, null, 2); } else { valueSpan.innerText = 'OK'; } }) .catch(e => { valueSpan.innerHTML = `❌ error thrown ("${e.message ? e.message : e}")`; failed++; updateSummary(randomNumber); }); } } catch (e) { valueSpan.innerHTML = `❌ error thrown ("${e.message ? e.message : e}")`; failed++; } }); updateSummary(randomNumber); storeButton.removeAttribute('disabled'); }); } function retrieveData () { testsDiv.removeAttribute('hidden'); results.results.length = 0; results.date = (new Date()).toUTCString(); let all = 0; let failed = 0; testsDetailsElement.innerHTML = ''; function updateSummary () { testsSummaryDiv.innerText = `Retrieved data from ${all} storage mechanisms${failed > 0 ? ` (${failed} failed)` : ''}. Click for details.`; } tests.concat(commonTests).forEach(test => { all++; const resultObj = { id: test.id, value: null }; results.results.push(resultObj); const li = document.createElement('li'); li.id = `test-${test.id.replace(' ', '-')}`; li.innerHTML = `${test.id} - <span class='value'>…</span>`; const valueSpan = li.querySelector('.value'); testsDetailsElement.appendChild(li); try { const result = test.retrive(); if (result instanceof Promise) { result .then(data => { if (Array.isArray(data)) { valueSpan.innerHTML = `<ul>${data.map(r => `<li>${r.test} - ${r.result}</li>`).join('')}</ul>`; } else if (data) { valueSpan.innerHTML = JSON.stringify(data, null, 2); } resultObj.value = data; }) .catch(e => { failed++; valueSpan.innerHTML = `❌ error thrown ("${e.message ? e.message : e}")`; updateSummary(); }); } else { valueSpan.innerText = JSON.stringify(result, null, 2) || undefined; resultObj.value = result || null; } } catch (e) { failed++; valueSpan.innerHTML = `❌ error thrown ("${e.message ? e.message : e}")`; } }); updateSummary(); downloadButton.removeAttribute('disabled'); } function downloadTheResults () { const data = JSON.stringify(results, null, 2); const a = document.createElement('a'); const url = window.URL.createObjectURL(new Blob([data], { type: 'application/json' })); a.href = url; a.download = 'storage-blocking-results.json'; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); a.remove(); } downloadButton.addEventListener('click', () => downloadTheResults()); // run tests if button was clicked or… storeButton.addEventListener('click', () => storeData()); retriveButton.addEventListener('click', () => retrieveData()); // if url query is '?store' store the data immadiatelly if (document.location.search === '?store') { storeData(); } // if url query is '?retrive' retrieve the data immadiatelly if (document.location.search === '?retrive') { retrieveData(); }
import {DetailedError} from "src/base/DetailedError.js"; import {createTextureByDrawingToCanvas} from "src/draw/util.js"; import {Rect} from "src/geo/Rect.js"; // Work around WebStorm not recognizing some WebGL types. //noinspection ConstantIfStatementJS if (false) { //noinspection JSUnusedLocalSymbols function WebGLBuffer() {} //noinspection JSUnusedLocalSymbols function WebGLProgram() {} //noinspection JSUnusedLocalSymbols function WebGLShader() {} //noinspection JSUnusedLocalSymbols function WebGLTexture() {} } /** * @param {!WebGLRenderingContext} gl */ const VERTEX_SHADER_SOURCE = ` attribute vec4 aVertexPosition; attribute vec4 aVertexColor; attribute vec2 aTextureCoord; uniform mat4 uMatrix; varying lowp vec4 vColor; varying highp vec2 vTextureCoord; void main(void) { gl_Position = uMatrix * aVertexPosition; vColor = aVertexColor; vTextureCoord = aTextureCoord; }`; const FRAGMENT_SHADER_SOURCE = ` precision highp float; varying lowp vec4 vColor; varying highp vec2 vTextureCoord; uniform sampler2D uSampler; void main(void) { vec4 pixel = texture2D(uSampler, vTextureCoord); gl_FragColor = (pixel * pixel.a) + vColor * (1.0 - pixel.a); }`; /** * @param {!WebGLRenderingContext} gl * @returns {{ * programInfo: { * program: *, * attribLocations: !{ * vertexPosition: *, * vertexColor: * * }, * uniformLocations: !{ * matrix: * * } * }, * buffers: !{ * position: !WebGLBuffer, * color: !WebGLBuffer, * indices: !WebGLBuffer, * textureCoords: !WebGLBuffer * }, * arrowTexture: !WebGLTexture * }} */ function initShaders(gl) { let shaderProgram = createShaderProgram(gl, VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE); let programInfo = { program: shaderProgram, attribLocations: { vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'), vertexColor: gl.getAttribLocation(shaderProgram, 'aVertexColor'), textureCoord: gl.getAttribLocation(shaderProgram, 'aTextureCoord'), }, uniformLocations: { matrix: gl.getUniformLocation(shaderProgram, 'uMatrix'), texture: gl.getUniformLocation(shaderProgram, 'uSampler'), }, }; let buffers = createBuffers(gl); let arrowTexture = createArrowTexture(gl); return {programInfo, buffers, arrowTexture}; } /** * @param {!WebGLRenderingContext} gl * @returns {!{position: !WebGLBuffer, color: !WebGLBuffer, indices: !WebGLBuffer, textureCoords: !WebGLBuffer}} */ function createBuffers(gl) { const positionBuffer = gl.createBuffer(); const colorBuffer = gl.createBuffer(); const indexBuffer = gl.createBuffer(); const textureCoordBuffer = gl.createBuffer(); return { position: positionBuffer, color: colorBuffer, indices: indexBuffer, textureCoords: textureCoordBuffer, }; } /** * @param {!WebGLRenderingContext} gl * @param {!string} vertexShaderSource * @param {!string} fragmentShaderSource * @returns {!WebGLProgram} */ function createShaderProgram(gl, vertexShaderSource, fragmentShaderSource) { const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource); const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource); const shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { let info = gl.getProgramInfoLog(shaderProgram); throw new DetailedError('Unable to initialize the shader program.', {info, vertexShaderSource, fragmentShaderSource}); } return shaderProgram; } /** * @param {!WebGLRenderingContext} gl * @param {!int} type * @param {!string} source * @returns {WebGLShader} */ function createShader(gl, type, source) { const shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { let info = gl.getShaderInfoLog(shader); gl.deleteShader(shader); throw new DetailedError('Bad shader', {type, source, info}); } return shader; } /** * @param {!WebGLRenderingContext} gl * @returns {!WebGLTexture} */ function createArrowTexture(gl) { let r = 128; return createTextureByDrawingToCanvas(gl, 8*r, 8*r, ctx => { function drawCell(x, y, drawer) { ctx.save(); try { ctx.beginPath(); ctx.translate(r * x * 2, r * y * 2); drawer(ctx); } finally { ctx.restore(); } } function textCell(x, y, text) { drawCell(x, y, () => { ctx.fillStyle = 'black'; ctx.font = '180px sans-serif'; let w = ctx.measureText(text).width; ctx.fillText(text, r - w/2, r*1.2); }); } ctx.save(); drawArrow(ctx, r); ctx.translate(r*4, 0); ctx.rotate(Math.PI/2); drawArrow(ctx, r); ctx.restore(); drawCell(0, 1, () => { ctx.translate(0, r/2); drawArrow(ctx, r/2); ctx.translate(r*2, r); drawArrow(ctx, -r/2); }); drawCell(1, 1, () => { ctx.arc(r, r, r/2, 0, 2*Math.PI); ctx.fillStyle = 'green'; ctx.fill(); ctx.fillStyle = 'black'; ctx.font = '120px monospace'; ctx.fillText('S', r, r); }); drawCell(2, 0, () => { ctx.arc(r, r, r/2, 0, 2*Math.PI); ctx.fillStyle = 'red'; ctx.fill(); }); textCell(2, 1, '|?\u27E9'); textCell(2, 2, '|0\u27E9'); textCell(2, 3, '|1\u27E9'); textCell(3, 0, '|+\u27E9'); textCell(3, 1, '|-\u27E9'); textCell(3, 2, '|+i\u27E9'); textCell(3, 3, '|-i\u27E9'); textCell(0, 2, 'Slam'); }); } /** * @param {!CanvasRenderingContext2D} ctx * @param {!number} r */ function drawArrow(ctx, r) { ctx.beginPath(); ctx.moveTo(r, 0); ctx.lineTo(r, r/2); ctx.lineTo(2*r, r/2); ctx.lineTo(2*r, 3*r/2); ctx.lineTo(r, 3*r/2); ctx.lineTo(r, 2*r); ctx.lineTo(0, r); ctx.lineTo(r, 0); ctx.fillStyle = 'blue'; ctx.fill(); } /** * @param {!int} x * @param {!int} y * @returns {!Rect} */ function textureCell(x, y) { return new Rect(x, y, 1, 1).scaledBy(0.25); } /** @type {!Rect} */ const H_ARROW_TEXTURE_RECT = textureCell(0, 0); /** @type {!Rect} */ const H_INIT_TEXTURE_RECT = textureCell(0, 1); /** @type {!Rect} */ const SLAM_TEXTURE_RECT = textureCell(0, 2); /** @type {!Rect} */ const V_ARROW_TEXTURE_RECT = textureCell(1, 0); /** @type {!Rect} */ const S_TEXTURE_RECT = textureCell(1, 1); /** @type {!Rect} */ const DISPLAY_TEXTURE_RECT = textureCell(2, 0); /** @type {!Rect} */ const KET_UNKNOWN_RECT = textureCell(2, 1); /** @type {!Rect} */ const KET_OFF_RECT = textureCell(2, 2); /** @type {!Rect} */ const KET_ON_RECT = textureCell(2, 3); /** @type {!Rect} */ const KET_PLUS_RECT = textureCell(3, 0); /** @type {!Rect} */ const KET_MINUS_RECT = textureCell(3, 1); /** @type {!Rect} */ const KET_PLUS_I_RECT = textureCell(3, 2); /** @type {!Rect} */ const KET_MINUS_I_RECT = textureCell(3, 3); export { initShaders, H_ARROW_TEXTURE_RECT, V_ARROW_TEXTURE_RECT, S_TEXTURE_RECT, H_INIT_TEXTURE_RECT, DISPLAY_TEXTURE_RECT, KET_UNKNOWN_RECT, KET_PLUS_I_RECT, KET_MINUS_I_RECT, KET_PLUS_RECT, KET_MINUS_RECT, KET_OFF_RECT, KET_ON_RECT, SLAM_TEXTURE_RECT, }
import Component from 'ember-appointment-slots-pickers/components/slots-picker/base/component'; import { computed } from '@ember/object'; import layout from './template'; export default Component.extend({ layout, selected: computed('multiSelected', function () { const selected = this.multiSelected; return selected && selected.length ? this.multiSelected[0] : null; }) });
import React from 'react' import PropTypes from 'prop-types' import Typography from '@material-ui/core/Typography' import { withStyles } from '@material-ui/core/styles' class Total extends React.PureComponent { render() { const { classes, total } = this.props return do { if (total < 0) { null } else { ( <div className={classes.root}> <Typography> <strong>{total}</strong> {total == 1 ? 'record' : 'records'} </Typography> </div> ) } } } } const styles = { root: { flexGrow: 1 } } export default withStyles(styles)(Total)
module.exports = (...args) => { process.env.IS_DEBUG && console.log(...args); };
// pages/meirituijan/meirituijan.js import axios from "../../util/axios.js"; import PubSub from 'pubsub-js'; Page({ /** * 页面的初始数据 */ data: { commentList: [], day: "", month: "", songIndex: null }, // 去song页面 toSong(event) { // 路由传参,将当前的id值传递过去,拿到id值取发送请求,获取数据 let { songid, index } = event.currentTarget.dataset wx: wx.navigateTo({ url: '/pages/song/song?songId=' + songid, }) // 拿到当前歌曲的下标,保存到状态中 this.setData({ songIndex: index }) }, /** * 生命周期函数--监听页面加载 */ onLoad: async function(options) { // 设置日期 let day = new Date().getDate(); let month = new Date().getMonth() + 1; this.setData({ day, month }) // 没登录就去登录 let cookies = wx.getStorageSync("cookies") // 当没有登录时就去登录页面 if (!cookies) { wx.showModal({ title: "请先登录", content: "该功能需要登录账号", cancelText: "回到首页", confirmText: "去登陆", success: ({ confirm }) => { //可以通过data中的cancel或者confirm判断当前是点击了取消还是确定 // console.log('success', confirm) if (confirm) { //如果用户点击了去登陆,就跳转到登录页面 wx.redirectTo({ url: '/pages/login/login', }) } else { wx.switchTab({ url: '/pages/index/index', }) } } }) return } // 获取每日推荐的歌曲 const res = await axios("recommend/songs"); let commentList = res.recommend.slice(0, 14); this.setData({ commentList }) // 接受song页面发来的消息,说要切换下一首 PubSub.subscribe("changeSong", (msg, data) => { let { songIndex, commentList } = this.data; // 判断点击的是上一首还是下一首 if (data === "pre") { // 第一首歌的上一首是最后一首 songIndex === 0 ? songIndex = commentList.length - 1 : songIndex--; } if (data === "next") { // 最后一首歌的下一首歌是第一首歌 songIndex === commentList.length - 1 ? songIndex = 0 : songIndex++; } // 修改下标的值 this.setData({ songIndex }) // 通过下标的值,得到对饮给的id值 const songId = commentList[songIndex].id; // 将id值传第给送页面 PubSub.publish("songId", songId) }) }, /** * 生命周期函数--监听页面初次渲染完成/recommend/songs */ onReady: function() { }, /** * 生命周期函数--监听页面显示 */ onShow: function() { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function() { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function() { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function() { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function() { }, /** * 用户点击右上角分享 */ onShareAppMessage: function() { } })
const express = require('express'); const routes = require('./routes'); require('./database'); const app = express(); app.use(express.urlencoded()); app.use(function (req, res, next) { res.header('Access-Control-Allow-Origin: *'); res.header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); res.header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); res.header('Access-Control-Allow-Credentials', true); next(); }); app.use(routes); app.listen(3333);
import React from "react"; import { connect } from "react-redux"; import { fetchTrendingList, fetchCoinData, setVisibilityFilter } from "../actions"; class TrendingList extends React.Component { componentDidMount() { this.props.fetchTrendingList(); } handleClick(coin) { this.props.fetchCoinData(coin); this.props.setVisibilityFilter("DISPLAY_ONE_COIN"); } render() { return ( <div className="vertical container box limit"> <h4>Tendances</h4> <table> <tbody> {this.props.coinList.map((coin) => ( <tr key={coin.id} className="clickable" onClick={() => this.handleClick(coin.id)} > <td> <div className="left container"> <img className="pic" src={coin.logo} alt={coin.name} ></img> <p>{coin.name}</p> </div> </td> </tr> ))} </tbody> </table> </div> ); } } const mapStateToProps = (state) => { return { coinList: state.trendingCoinList }; }; export default connect(mapStateToProps, { fetchTrendingList, fetchCoinData, setVisibilityFilter, })(TrendingList);
var os = require('os'); var proc = require('child_process'); var hubiquitus = require(__dirname + '/../../index'); os.cpus().forEach(function () { proc.fork(__dirname + '/launcher'); }); hubiquitus.start({discoveryAddr: 'udp://224.0.0.1:5555'}) .send('anonymous', 'test', 'start') .addActor('test', function () { setTimeout(function () { var n = 20; hubiquitus.send('test', 'fibonacci', n, 300000, function (req) { console.log('Result :', 'ƒ ' + n + ' = ' + req.content); }); }.bind(this), 1000); });
(function(ns) { 'use strict'; ns.Animal = function Animal (name, dob) { if (typeof name !== 'string') { throw new TypeError('Please give a name to your animal'); } this.dob = new Date(dob); if (this.dob.toString() === 'Invalid Date') { throw new TypeError('Please enter the date of birth in a valid format'); } if (name) { this.name = name; } this.name = name; }; ns.Animal.prototype.age = function age() { if (this.isDead) { throw new Error('This animal is dead'); } return Math.floor( (Date.now() - this.dob) / 1000 / 60 / 60 / 24 / 365.25 ); }; ns.Animal.prototype.expire = function expire() { return (this.isDead = true); }; ns.Animal.prototype.name = 'Larry'; ns.ZooError = function ZooError(message) { this.name = 'ZooError'; this.message = message || 'ERROR'; this.stack = (new Error()).stack; }; ns.ZooError.prototype = Object.create(Error.prototype); ns.ZooError.prototype.constructor = ns.ZooError; window.zoo = ns; })(window.zoo || {});
var Zia; (function (Zia) { var Texture = (function () { function Texture(graphicsDevice, options, textureType) { var gl = this._gl = graphicsDevice.gl; this._texture = this._gl.createTexture(); this._textureType = textureType; this._options = Zia.ObjectUtil.reverseMerge(options || {}, { filter: 3 /* MinNearestMagMipLinear */, wrapS: 0 /* Repeat */, wrapT: 0 /* Repeat */ }); gl.bindTexture(textureType, this._texture); gl.texParameteri(textureType, gl.TEXTURE_WRAP_S, Zia.TextureWrapUtil._map(gl, this._options.wrapS)); gl.texParameteri(textureType, gl.TEXTURE_WRAP_T, Zia.TextureWrapUtil._map(gl, this._options.wrapT)); var mappedFilterValues = Zia.TextureFilterUtil._map(gl, this._options.filter); gl.texParameteri(textureType, gl.TEXTURE_MIN_FILTER, mappedFilterValues[0]); gl.texParameteri(textureType, gl.TEXTURE_MAG_FILTER, mappedFilterValues[1]); gl.bindTexture(textureType, null); } Texture.prototype._setData = function (setImageDataCallback, flipY) { var gl = this._gl; var textureType = this._textureType; gl.activeTexture(gl.TEXTURE0); gl.bindTexture(textureType, this._texture); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY); setImageDataCallback(gl); gl.bindTexture(textureType, null); }; Texture.prototype._generateMipmap = function () { var gl = this._gl; var textureType = this._textureType; gl.activeTexture(gl.TEXTURE0); gl.bindTexture(textureType, this._texture); gl.generateMipmap(textureType); gl.bindTexture(textureType, null); }; Texture.prototype.destroy = function () { this._gl.deleteTexture(this._texture); }; return Texture; })(); Zia.Texture = Texture; })(Zia || (Zia = {}));
var React = require('react'); var CartList = require('./CartList.jsx'); var CartBox = React.createClass({ render: function(){ return ( <div> <CartList products={ this.props.products } removeFromCart = {this.props.removeFromCart}></CartList> </div> ) } }) module.exports = CartBox;
$(document).ready(function () { var id_usuario = $('#id_usuario').val(); var fecha_hoy = $('#fecha_hoy').val(); var page = $('#txtPage').val(); var funcion = ""; var id_usuario = $('#id_usuario').val(); buscar_avatar(id_usuario); if(page=="adm"){ buscarGestionReservas(); } if(page=="create"){ listar_items(); } function buscar_avatar(id) { funcion = 'buscarAvatar'; $.post('../../Controlador/usuario_controler.php', { id, funcion }, (response) => { const usuario = JSON.parse(response); $('#avatar4').attr('src', usuario.avatar); }); } $(document).on('keyup', '#TxtBuscarReserva', function () { let consulta = $(this).val(); if (consulta != "") { buscarGestionReservas(consulta); } else { buscarGestionReservas(); } }); function buscarGestionReservas(consulta) { var funcion = "buscar"; $.post('../../Controlador/reserva_controler.php', { consulta, funcion }, (response) => { const reservas = JSON.parse(response); let num = 0; let template = `<div class="col-md-12"> <div class="card"> <div class="card-body"> <table class="table table-bordered table-responsive center-all"> <thead class='notiHeader'> <tr> <th>#</th> <th>Estado</th> <th >Fecha</th> <th >Visitante</th> <th >Descuento</th> <th >Valor Descuento</th> <th >Total</th> <th >Acción</th> </tr> </thead> <tbody>`; reservas.forEach(reserva => { fecha = reserva.fecha_inicio; if (reserva.fecha_fin != '0000-00-00') { fecha = reserva.fecha_inicio + " - " + reserva.fecha_fin; } num += 1; template += ` <tr idReserva=${reserva.id}> <td >${num}</td> <td >${reserva.estado_visita}</td> <td >${fecha}</td> <td >${reserva.nombre_completo} / ${reserva.doc_id}</td> <td >${reserva.nombre_descuento}</td> <td >${reserva.descuento}</td> <td >${reserva.valor_total}</td> <td > <button class='editReserva btn btn-sm btn-primary mr-1' type='button' data-bs-toggle="modal" data-bs-target="#ModalEditar_reserva"> <i class="fas fa-pencil-alt"></i> </button>`; template += ` </td> </tr>`; }); template += ` </tbody> </table> </div> </div>`; $('#busquedaVisita').html(template); contar_visitas(); }); } $('#form_crear_reserva').submit(e => { //campos reserva let fecha_inicio = $('#txtFechaInicio').val(); let fecha_fin = $('#txtFechaFinal').val(); let id_visitante = $('#txtId_visitante').val(); let id_descuento = $('#selDescuento').val(); // campos visitante let doc_id = $('#txtDoc_id').val(); let nombre_completo = $('#txtNombre_completo').val(); let cel_usuario = $('#txtTelefono').val(); let email_usuario = $('#txtEmail').val(); let id_nacionalidad = $('#selNacionalidad').val(); let id_municipio = $('#selMunicipio').val(); if (fecha_hoy >= '01-01-2021' && fecha_hoy >= fecha_inicio) { if (fecha_fin >= fecha_inicio) { funcion = 'crear'; $.post('../../Controlador/reserva_controler.php', { funcion, fecha_inicio, fecha_fin, id_visitante, id_descuento, doc_id, nombre_completo, cel_usuario, email_usuario, id_nacionalidad, id_municipio }, (response) => { console.log(response); if (response == 'creado') { $(location).attr('href', '../../Vista/adm_reservas.php?modulo=reservas'); } else { $('#noCreate').hide('slow'); $('#noCreate').show(1000); $('#noCreate').hide(2000); $('#noCreate').html(response); } }); } else { $('#noCreate').html("La fecha final debe ser mayor o igual que la inicial"); $('#noCreate').hide('slow'); $('#noCreate').show(1000); $('#noCreate').hide(2000); } } else { $('#noCreate').html("La fecha inicial ingresada no es correcta"); $('#noCreate').hide('slow'); $('#noCreate').show(1000); $('#noCreate').hide(2000); } e.preventDefault(); }); $(document).on('click', '.editReserva', (e) => { const elemento = $(this)[0].activeElement.parentElement.parentElement.parentElement.parentElement; const id = $(elemento).attr('idReserva'); $('#txtIdReserva').val(id); funcion = 'cargar'; $.post('../../Controlador/usuario_controler.php', { id, funcion }, (response) => { const obj = JSON.parse(response); $('#txtDoc2').val(obj.estado_reserva); $('#txtRegionEd').val(obj.fecha_inicio); $('#selCargoEd').val(obj.fecha_fin); $('#selCargoEd').val(obj.id_descuento); $('#selCargoEd').val(obj.nombre_completo); $('#selCargoEd').val(obj.doc_id); }); }); $('#form_update_cc').submit(e => { let id = $('#txtIdCc').val(); funcion = 'update_cc'; let doc = $('#txtDoc2').val(); let id_sede = $('#txtSedeEd').val(); let id_cargo = $('#selCargoEd').val(); $.post('../../Controlador/usuario_controler.php', { id, funcion, doc, id_sede, id_cargo }, (response) => { if (response == 'update') { buscarGestionVisitas(); $('#updateCc').hide('slow'); $('#updateCc').show(1000); $('#updateCc').hide(2000); $('#form_update_cc').trigger('reset'); buscarGestionVisitas(); } else { $('#noUpdateCc').hide('slow'); $('#noUpdateCc').show(1000); $('#noUpdateCc').html(response); } }); e.preventDefault(); }); function contar_visitas() { funcion = 'contar_visitas'; $.post('../../Controlador/visita_controler.php', { funcion }, (response) => { const obj = JSON.parse(response); $('#liBadge').html(obj.cantidad + " visitas registradas"); }); } $("#txtDoc").blur(function () { funcion = 'buscar_visitante'; let documento = $('#txtDoc').val(); $.post('../../Controlador/usuario_controler.php', { documento, funcion }, (response) => { const usuario = JSON.parse(response); $('#txtNombreUsuario').val(usuario.nombre_completo); $('#txtTelefono').val(usuario.cel_usuario); $('#txtEmail').val(usuario.email_usuario); $('#selNacionalidad').val(usuario.id_nacionalidad); $('#selmunicipio').val(usuario.id_municipio); }); }); $("#txtDoc_idItem").blur(function () { funcion = 'buscar_visitante'; let documento = $('#txtDoc_idItem').val(); $.post('../../Controlador/usuario_controler.php', { documento, funcion }, (response) => { const usuario = JSON.parse(response); $('#txtNombre_completo').val(usuario.nombre_completo); $('#txtTelefono').val(usuario.cel_usuario); $('#txtEmail').val(usuario.email_usuario); $('#selNacionalidad').val(usuario.id_nacionalidad); $('#selmunicipio').val(usuario.id_municipio); }); }); function listar_items() { var funcion = "listar_items"; $.post('../../Controlador/reserva_controler.php', { funcion }, (response) => { const items = JSON.parse(response); let num = 0; let template = ``; items.forEach(item => { num += 1; template += `<tr idItem=${item.id}> <td >${num}</td> <td >${item.estado_visita}</td> <td >${item.estado_visita}</td> <td >${item.estado_visita}</td> <td >${item.estado_visita}</td> <td >${item.estado_visita}</td> <td > <button class='editItem btn btn-sm btn-primary mr-1' type='button' data-bs-toggle="modal" data-bs-target="#ModalEditar_reserva"> <i class="fas fa-pencil-alt"></i> </button>`; template += ` </td> </tr>`; }); $('#bodyItems').html(template); contar_visitas(); }); } }); function validarNacionalidad(valor) { if (valor == 43) { document.getElementById('divMunicipio').style.display = ''; } else { document.getElementById('divMunicipio').style.display = 'none'; } } function validarTipoVisita(tipo) { if (tipo <= 1) { document.getElementById('divFinVisita').style.display = 'none'; } else { document.getElementById('divFinVisita').style.display = ''; } }
import { connect } from 'react-redux'; import RatingStarForm from './star_rating'; const mSTP = (state,ownProps) => { return { readOnly: ownProps.readOnly, rate: ownProps.rate } }; export default connect(mSTP, null)(RatingStarForm);
import React from "react"; import Form from "../../components/Form/form"; const inputsList = { search: "" }; const inputs = [ { label: "Введите данные для поиска", variant: "standard", type: "text", name: "search", id: "search" } ]; const SearchBar = () => { const onSubmit = (e, formData) => { e.preventDefault(); console.log("stab search"); }; return ( <Form inputs={inputs} formHeader="Поиск по базе клиентов" submitTitle="Искать" submit={onSubmit} inputsData={inputsList} /> ); }; export default SearchBar;
$(function() { var showPromo = false; $(window).scroll(function() { var textHeight = $(".body-text").offset().top; // console.log("TextHeight: " + textHeight); if ($(this).scrollTop() >= textHeight) { if (!showPromo) { showPromo = true; $(".secondary-promo").animate({ opacity: 1, }, 1000) } } else { if (showPromo) { showPromo = !showPromo; $(".secondary-promo").animate({ opacity: 0, }, 100) } } }); });
import './style' import h from '@kuba/h' function component () { return ( <input className='search__input' type='search' name='search' placeholder='Busque por produto, categoria ou marca' /> ) } export default component
import BaseCollapse from 'ember-bootstrap/components/base/bs-collapse'; import { classNameBindings } from '@ember-decorators/component'; @classNameBindings('showContent:in') export default class Collapse extends BaseCollapse {}
test('toHaveBeenCalledWith(arrayContaining)', () => { const myFunction = jest.fn(); myFunction([1, 2, 3]); expect(myFunction).toHaveBeenCalledWith(expect.arrayContaining([2])); }); test('toHaveBeenCalledWith(objectContaining)', () => { const myFunction = jest.fn(); myFunction({ name: 'Hugo', website: 'codewithhugo.com' }); expect(myFunction).toHaveBeenCalledWith( expect.objectContaining({ name: 'Hugo' }) ); }); test('toHaveBeenCalledWith(nested object/array containing)', () => { const myFunction = jest.fn(); myFunction([ {age: 21, counsinIds: [1]}, {age: 22, counsinIds: [1, 3]}, {age: 23} ]); expect(myFunction).toHaveBeenCalledWith( expect.arrayContaining([ expect.objectContaining({ age: 22, counsinIds: expect.arrayContaining([3]) }) ]) ); });
import IdArray from "../loose/idArray.mjs"; import {decodeNetMsg,encodeNetMsg} from "../loose/netMsg.mjs"; import {MetaRadar, MetaMove, UnknownComponent} from "./components.mjs"; export default class Ship { constructor(network) { this.network = network ; this.componentTypes = [] ; this.components = [] ; this.fullyConnectedCallbacks = [] ; this.fullyConnected = false ; } init() { ////{ //// let res = encodeNetMsg({testByte:246,testArray:[1,6,7]}, [255,0],upMsgStructure.ship.test); //// log(res); //// this.socket.send(res); ////} ////{ //// let res = encodeNetMsg({}, [0,0],upMsgStructure.metaRadar.read); //// log(res); //// this.socket.send(res); ////} ////{ //// let res = encodeNetMsg({}, [0,1],upMsgStructure.metaRadar.stream); //// log(res); //// this.socket.send(res); ////} } update() { for (let msgData of this.network) { if (msgData[1] == 255) { var msgType = downMsgType.ship.findKey(msgData[2]); let msg = decodeNetMsg(msgData, [255,0],downMsgStructure.ship[msgType]); this["msg_"+msgType](msg); console.log(msg); } else { let component = msgData[1]; let componentType = this.componentTypes[component]; let msgType = downMsgType[this.componentTypes[msgData[1]]] .findKey(msgData[2]); let msg = decodeNetMsg ( msgData , [component,msgData[2]], downMsgStructure [ componentType ] [ msgType ] ); this.getComponent(component)["msg_"+msgType](msg); ////this.ship.msg_components(msg); } ////if (msg.component==-1) { //// this.ship["msg_"+msg.type](msg); ////} ////else { //// try { //// this.ship.components[msg.component]["msg_"+msg.type](msg); //// } //// catch (e) { //// console.log(msg); //// throw e; //// } ////} } for (let component of this.components) { if (component!=null) { component.update(); } } } onFullyConnected(callback) { this.fullyConnectedCallbacks.push(callback); } msg_components(msg) { this.componentTypes = msg.components.map(typeId=>componentType.findKey(typeId)); this.components = Array(this.components.length).fill(null); this.fullyConnected = true; for (let callback of this.fullyConnectedCallbacks) { callback(); } } getComponent(component, which) { if (typeof component == "string") { if (typeof which == "undefined") { return this.componentTypes .map((type,i)=>i) .filter(i=>this.componentTypes[i]==component) .map(i=>this.getComponent(i)) ; } else { return this.getComponent( this.componentTypes .map((type,i)=>i) .filter(i=>this.componentTypes[i]==component) [which] ); } } else { if (this.components[component] == null) { this.components[component] = this.createComponent(this.componentTypes[component], component); } return this.components[component]; } } createComponent(type,id) { switch (type) { case "metaRadar": return new MetaRadar(((type,msg)=>{this.send(id,type,msg)}).bind(this), id); case "metaMove": return new MetaMove(((type,msg)=>{this.send(id,type,msg)}).bind(this), id); default: return null; } } send(component, type, msg) { let compType = this.componentTypes[component]; this.network.send(encodeNetMsg(msg,[component,upMsgType[compType][type]], upMsgStructure[compType][type])); } ////addEntity(args) { //// if (!args) args={}; //// //// var entity = {}; //// if (args.entity) //// entity = args.entity; //// //// if (!args.pos ) { args.pos = vec() ; } //// if (!args.rot ) { args.rot = 0 ; } //// entity.pos = args.pos; //// entity.rot = args.rot; //// //// if (args.player ) { this.player = entity ; } //// //// this.ui .onAddEntity(entity); //// this.entities.push(entity); //// //// return entity; ////} } ////class ShipView { //// constructor(ship) { //// this.ship = ship ; //// this.ships = [] ; //// this.us = {pos:vec(),rot:0} ; //// this.type = "shipView" ; //// } //// msg_setUs(msg) { //// var ship = {}; //// this.us.pos = msg.pos ; //// this.us.rot = msg.rot ; //// } //// msg_addShip(msg) { //// var ship = {}; //// ship.pos = msg.pos ; //// ship.rot = msg.rot ; //// this.ships.push(ship); //// } ////} ////class Thruster { //// constructor(ship) { //// this.ship = ship ; //// this.state = 0 ; //// } //// msg_setState(msg) { //// this.state = msg.state; //// } ////} var componentType = { "metaRadar" : 0 , "metaMove" : 1 , } var downMsgType = { ship: { components : 0 , }, metaRadar:{ add : 0 , update : 1 , remove : 2 , moveAll : 3 , }, metaMove:{ update : 0 , }, } var upMsgType = { ship:{ test : 0 , }, metaRadar:{ read : 0 , stream : 1 , }, metaMove:{ read : 0 , stream : 1 , "set" : 2 , }, } var downMsgStructure = { ship:{ components: { type:"object", values:[ {name:"components",type:"array",length:"dynamic",content:{type:"ubyte"},}, ], } }, metaRadar:{ add: { type:"object", values:[ { name : "id" , type : "ushort" , }, { name : "pos" , type : "array" , length : 2 , content : {type:"float"} , }, { name : "ori" , type : "float" , }, ], }, update: { type:"object", values:[ { name : "id" , type : "ushort" , }, { name : "pos" , type : "array" , length : 2 , content : {type:"float"} , }, { name : "ori" , type : "float" , }, ], }, remove: { type:"object", values:[ { name : "id" , type : "ushort" , }, ], }, moveAll: { type:"object", values:[ { name : "pos" , type : "array" , length : 2 , content : {type:"float"} , }, { name : "ori" , type : "float" , }, ], }, }, metaMove:{ update: { type:"object", values:[ { name : "axis" , type : "ubyte" , }, { name : "value" , type : "float" , }, ], }, }, } var upMsgStructure = { ship:{ test: { type:"object", values:[ { name : "testByte" , type : "ubyte" , }, { name : "testArray" , type : "array" , length : "dynamic" , content : {type:"ubyte"} , }, ], }, }, metaRadar:{ read: { type:"object", values:[], }, stream: { type:"object", values:[], }, }, metaMove:{ read: { type:"object", values:[], }, stream: { type:"object", values:[], }, "set": { type:"object", values:[ { name : "axis" , type : "ubyte" , }, { name : "value" , type : "float" , }, ], }, }, }
const chai = require("chai"); const chaiHttp = require("chai-http"); const server = require("../server"); chai.should(); const expect = chai.expect; chai.use(chaiHttp); const userCredentials = { userName: '[email protected]', password: 'password' } // before any test user is logged in var authenticatedUser = chai.request.agent(server); before((done) => { authenticatedUser .post('/login') .send(userCredentials) .end((err, response) => { expect(response.statusCode).to.equal(200); done(); }); }); describe("POST /message", () => { it("should add the message if there is a sender ", (done) => { const message = { receiver_username: "[email protected]", content: "huhueirityiue" }; authenticatedUser .post("/message") .send(message) .end((err, response) => { expect(response.statusCode).to.equal(200); done(); }); }); it("should not add the message when receiver_username is empty ", (done) => { const message = { receiver_username: "", content: "huhueirityiue" }; authenticatedUser .post("/message") .send(message) .end((err, response) => { response.text.should.be.eq("receiver_username should not be empty!"); done(); }); }); it("should not add the message when the message is too long ", (done) => { const message = { receiver_username: "[email protected]", content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s" }; authenticatedUser .post("/message") .send(message) .end((err, response) => { response.text.should.be.eq("message is too long"); done(); }); }); });
export const getCatFactsEndpoint = state => state.appConfig.endpoints.catFacts; export const boo = 'boo'; // This is just to remove the annoying "Prefer default export" ESLint error.
/* * Copyright (c) 2014. * * @Author Andy Tang */ (function LinkedHashMapSpecScope(undefined) { 'use strict'; describe('LinkedHashMap', function LinkedHashMapSpec() { describe('initalizing an LinkedHashMap', function initializingLinkedHashMap() { it('should be able to add an entry to the list', function addToEmpty() { var list = new LinkedHashMap(); list.add(0, 'hello'); expect(list.getById(0).getValue()).toEqual('hello'); expect(list.getById(0).getNext()).toEqual(null); expect(list.getById(0).getPrevious()).toEqual(null); }); it('should be able to add the first entry with addFirst', function addFirstAsFirst() { var list = new LinkedHashMap(); list.addFirst(0, 'hello'); expect(list.getById(0).getValue()).toEqual('hello'); expect(list.getById(0).getNext()).toEqual(null); expect(list.getById(0).getPrevious()).toEqual(null); }); it('should be able to add the first entry with addLast', function addLastAsFirst() { var list = new LinkedHashMap(); list.addLast(0, 'hello'); expect(list.getById(0).getValue()).toEqual('hello'); expect(list.getById(0).getNext()).toEqual(null); expect(list.getById(0).getPrevious()).toEqual(null); }); it('should return false when trying to remove something that has not been added', function removeGhost() { var list = new LinkedHashMap(); expect(list.remove('ghost')).toEqual(false); }); it('should return false when trying to remove the first or lastwhen empty', function firstEmpty() { var list = new LinkedHashMap(); expect(list.removeFirst()).toEqual(false); expect(list.removeLast()).toEqual(false); }); it('should return true when the map is empty, but false when it is not', function emptyMap() { var list = new LinkedHashMap(); expect(list.isEmpty()).toEqual(true); list.add(0, 'hello'); expect(list.isEmpty()).toEqual(false); }); }); describe('modifying an LinkedHashMap', function modifyLinkedHashMapSpecs() { var list; beforeEach(function beforeEach() { list = new LinkedHashMap(); list.add(0, 'one'); list.add(1, 'two'); list.add(2, 'three'); }); it('should be able to get the first entry of an list', function firstOfList() { var first = list.getFirst(); expect(first.getValue()).toEqual('one'); expect(first.getNext()).toEqual(list.getById(1)); expect(first.getPrevious()).toEqual(null); }); it('should be able to get the last entry of an list', function lastOfList() { var last = list.getLast(); expect(last.getValue()).toEqual('three'); expect(last.getNext()).toEqual(null); expect(last.getPrevious()).toEqual(list.getById(1)); }); it('should be able to add a node after another node', function addAfter() { var middle = list.getById(1); var newNode = list.addAfter(1, 3, 'four'); expect(middle.getNext()).toEqual(newNode); expect(newNode.getPrevious()).toEqual(middle); expect(newNode.getNext()).toEqual(list.getLast()); }); it('should be able to add a node before another node', function addBefore() { var middle = list.getById(1); var newNode = list.addBefore(1, 3, 'four'); expect(middle.getPrevious()).toEqual(newNode); expect(newNode.getNext()).toEqual(middle); expect(newNode.getPrevious()).toEqual(list.getFirst()); }); it('should be able to add a node at the beginning of the list', function addFirst() { var first = list.getFirst(); var newNode = list.addFirst(3, 'four'); expect(first.getPrevious()).toEqual(newNode); expect(newNode.getNext()).toEqual(first); expect(newNode.getPrevious()).toEqual(null); }); it('should be able to add a node at the end of the list', function addLast() { var last = list.getLast(); var newNode = list.addLast(3, 'four'); expect(last.getNext()).toEqual(newNode); expect(newNode.getPrevious()).toEqual(last); expect(newNode.getNext()).toEqual(null); }); it('should be able to delete the first entry', function removeFirst() { list.removeFirst(); var first = list.getFirst(); expect(first.getValue()).toEqual('two'); expect(first.getPrevious()).toEqual(null); }); it('should be able to delete all entries', function removeFirstWithRemove() { list.remove(0); list.remove(1); list.remove(2); expect(list.isEmpty()).toEqual(true); }); it('should be able to remove the last entry', function removeLast() { list.removeLast(); var last = list.getLast(); expect(last.getValue()).toEqual('two'); expect(last.getNext()).toEqual(null); }); it('should be able to remove an entry in the middle', function remove() { list.remove(1); expect(function keyNotFound() { list.getById(1); }).toThrow(new Error('key not found')); expect(list.getFirst().getNext()).toEqual(list.getLast()); expect(list.getLast().getPrevious()).toEqual(list.getFirst()); }); it('should prevent adding the same key twice', function preventDuplicateKey() { expect(function testDuplicateKey() { list.add(1, 'something'); }).toThrow(new Error('key already exists in LinkedHashMap')); }); it('should throw an error when a key is not found in the hashMap', function keyNotFound() { expect(function throwNotFound() { list.getById('nonexisting'); }).toThrow(new Error('key not found')); }); it('should throw an error when attempted to add after an non existing node', function addAfterNono() { expect(function testNono() { list.addAfter('nono', 'what', 'ever'); }).toThrow(new Error('key not found')); }); it('should be able to add before the first node', function addBeforeFirst() { list.addBefore(0, 3, 'four'); expect(list.getFirst().getValue()).toEqual('four'); }); it('should be able to add after the last node', function addAfterLast() { list.addAfter(2, 3, 'four'); expect(list.getLast().getValue()).toEqual('four'); }); it('should be able to loop through an list', function loop() { for (var node = list.getFirst(); node; node = node.getNext()) { } expect(node).toEqual(null); }); it('should return the size of the list', function getSize() { expect(list.getSize()).toEqual(3); }); }); }); }());
import debug from 'debug' import React, {Component} from 'react' import {bindActionCreators} from 'redux' import {connect} from 'react-redux' import {Link} from 'react-router' import * as actions from './session/actions' import getAuth from './session/session' const dbg = debug('app:top-nav') @connect( (state) => { dbg('connect: state=%o', state) return { session: state.session } }, (dispatch) => { dbg('connect: actions=%o', actions) return bindActionCreators(actions, dispatch) } ) export default class TopNav extends Component { render() { dbg('render: props=%o', this.props) const {session, logout, login} = this.props const auth = getAuth(session) return ( <nav className='navbar navbar-default navbar-fixed-top'> <div className='container'> <div className='navbar-header'> <a className='navbar-brand' href='#'>Redux Scratch</a> </div> <div id='navbar' className='collapse navbar-collapse'> <ul className='nav navbar-nav'> <li> <Link to='/home' activeClassName='active'>Homie</Link> </li> <li> <Link to='/stuff' activeClassName='active'>Stuff</Link> </li> <li> <Link to='/nonsense' activeClassName='active'>Nonsense</Link> </li> <li> <Link to='/gallery' activeClassName='active'>Gallery</Link> </li> <li> <Link to='/skills' activeClassName='active'>Skills</Link> </li> { auth.hasPrivs(['web-client-1.scope-1']) && <li> <Link to='/patients' activeClassName='active'>Patients</Link> </li> } <li> <Link to='/scroll' activeClassName='active'>Scroll</Link> </li> <li> <Link to='griddle' activeClassName='active'>Griddle</Link> </li> </ul> <ul className='nav navbar-nav navbar-right'> { session.token ? ( <li> <button onClick={logout} className='btn btn-default navbar-btn'> Logout </button> </li> ) : ( <li> <button onClick={()=>login('patients')} className='btn btn-default navbar-btn'> Login </button> </li> ) } </ul> </div> </div> </nav> ) } }
import React from "react"; import InfiniteScroll from "react-infinite-scroll-component"; import "./App.css"; import collegeImage from "./college.jpg"; import StarRatings from "react-star-ratings"; import Discount from "./Discount"; import Rate from "./Rate"; class App extends React.Component { state = { items: Array.from({ length: 10 }), }; fetchMoreData = () => { // a fake async api call like which sends // 10 more records in 3 secs setTimeout(() => { this.setState({ items: this.state.items.concat(Array.from({ length: 10 })), }); }, 2000); }; render() { return ( <div> <div style={styles.mainContainer}> <div style={styles.headContainer}> <p>Colleges in North India....</p> </div> <div style={styles.leftContainer}> <InfiniteScroll dataLength={this.state.items.length} next={this.fetchMoreData} hasMore={true} loader={<h4>Loading...</h4>} > {this.state.items.map((i, index) => ( <div style={styles.style}> <div style={styles.imageContainer}> <img style={{ height: 150, width: "100%", opacity: 0.3 }} src={collegeImage} alt="College " /> <div style={styles.textBlock}> <p style={{ fontSize: 10, margin: 0 }}> <span style={{ fontSize: 14, fontWeight: "bold" }}> 3.9 </span> /5 </p> <p style={{ marginTop: 0, fontSize: 11, margon: 0 }}> Very Good </p> </div> <div style={styles.textBlockBottom}> <p style={{ marginTop: 5, fontSize: 10 }}> Best College 2018 </p> </div> <div style={styles.textBlockBottomSecond}> <p style={{ marginTop: 5, fontSize: 10 }}>2kms away</p> </div> <div style={styles.textBlockBottomRight}> <p style={{ marginTop: 5, fontSize: 10, fontWeight: "bold", }} > #7 in 260 colleges in north campus </p> </div> </div> <div style={styles.details}> <div style={styles.leftDeails}> <span style={{ color: "#3f3b3b", fontSize: 15, fontWeight: "bold", }} > Hansraj College Delhi University <span style={{ marginLeft: 8, alignItems: "center", alignContent: "center", }} > <StarRatings rating={4} starRatedColor="#424242" numberOfStars={5} starDimension="11px" starSpacing="1px" /> </span> </span> <p style={{ fontSize: 9, marginTop: 0, }} > Near Vishwavidyalya Metro Station{" "} <span style={styles.greyDetails}> {" "} | 2 Kms away from bus stand </span> </p> <span style={{ marginTop: 0 }}> <span style={{ color: "#34b597", fontSize: 9, fontWeight: "bold", marginTop: 0, }} > 93% Match : </span> <span style={{ fontSize: 9, fontWeight: "bold", }} > 2.5kms </span> <span style={styles.greyDetails}>from GTB Nagar,</span> <span style={{ fontSize: 9, fontWeight: "bold", }} > 7kms </span> <span style={styles.greyDetails}> {" "}from Rajiv Chowk{" "} </span> </span> <p style={{ background: "#cdf5e8", borderTopRightRadius: 10, borderBottomRightRadius: 10, marginTop: 6, alignItems: "center", }} > <span style={styles.greyDetails}> Flat </span> <span style={{ fontSize: 9, fontWeight: "bold" }}> Rs. </span> <span style={{ color: "#34b597", fontSize: 9, fontWeight: "bold", }} > 2000{" "} </span> <span style={{ fontSize: 9, fontWeight: "bold", }} > off + upto Rs{" "} </span> <span style={{ color: "#34b597", fontSize: 9, fontWeight: "bold", }} > 500 </span> <span style={{ fontSize: 9, fontWeight: "bold", }} > {" "} wallet! to avail. . .{" "} </span> <span style={{ color: "#4c9aaf", fontSize: 9, fontWeight: "bold", }} > LOGIN </span> </p> </div> <div style={styles.rightDetails}> <div style={{ flex: 1, flexDirection: "row", display: "flex", contentAlign:'right', justifyContent:'space-between' }} > <Rate /> <Discount /> </div> <span style={{ color: "#de1621", fontSize: 17, fontWeight: "bold", marginTop: 0, }} > {" "} ₹ 5,768 </span> <p style={{ fontSize: 8, marginTop: 0, }} > per Semester (3months) </p> <p style={{ color: "#34b597", fontSize: 9, fontWeight: "bold", }} > Free Cancellation . Free Wi-Fi </p> </div> </div> </div> ))} </InfiniteScroll> </div> {/* Right Container */} <div style={styles.rightContainer}> <InfiniteScroll dataLength={this.state.items.length} next={this.fetchMoreData} hasMore={true} loader={<h4>Loading...</h4>} > {this.state.items.map((i, index) => ( <div style={styles.style}> <div style={styles.imageContainer}> <img style={{ height: 150, width: "100%", opacity: 0.3 }} src={collegeImage} alt="College " /> <div style={styles.textBlock}> <p style={{ fontSize: 10, margin: 0 }}> <span style={{ fontSize: 14, fontWeight: "bold" }}> 3.9 </span> /5 </p> <p style={{ marginTop: 0, fontSize: 11, margon: 0 }}> Very Good </p> </div> <div style={styles.textBlockBottom}> <p style={{ marginTop: 5, fontSize: 10 }}> Best College 2018 </p> </div> <div style={styles.textBlockBottomSecond}> <p style={{ marginTop: 5, fontSize: 10 }}>2kms away</p> </div> <div style={styles.textBlockBottomRight}> <p style={{ marginTop: 5, fontSize: 10, fontWeight: "bold", }} > #7 in 260 colleges in north campus </p> </div> </div> <div style={styles.details}> <div style={styles.leftDeails}> <span style={{ color: "#3f3b3b", fontSize: 15, fontWeight: "bold", }} > Hansraj College Delhi University <span style={{ marginLeft: 8, alignItems: "center", alignContent: "center", }} > <StarRatings rating={4} starRatedColor="#424242" numberOfStars={5} starDimension="11px" starSpacing="1px" /> </span> </span> <p style={{ fontSize: 9, marginTop: 0, }} > Near Vishwavidyalya Metro Station{" "} <span style={styles.greyDetails}> {" "} | 2 Kms away from bus stand </span> </p> <span style={{ marginTop: 0 }}> <span style={{ color: "#34b597", fontSize: 9, fontWeight: "bold", marginTop: 0, }} > 93% Match : </span> <span style={{ fontSize: 9, fontWeight: "bold", }} > 2.5kms </span> <span style={styles.greyDetails}>from GTB Nagar,</span> <span style={{ fontSize: 9, fontWeight: "bold", }} > 7kms </span> <span style={styles.greyDetails}> {" "}from Rajiv Chowk{" "} </span> </span> <p style={{ background: "#cdf5e8", borderTopRightRadius: 10, borderBottomRightRadius: 10, marginTop: 6, alignItems: "center", }} > <span style={styles.greyDetails}> Flat </span> <span style={{ fontSize: 9, fontWeight: "bold" }}> Rs. </span> <span style={{ color: "#34b597", fontSize: 9, fontWeight: "bold", }} > 2000{" "} </span> <span style={{ fontSize: 9, fontWeight: "bold", }} > off + upto Rs{" "} </span> <span style={{ color: "#34b597", fontSize: 9, fontWeight: "bold", }} > 500 </span> <span style={{ fontSize: 9, fontWeight: "bold", }} > {" "} wallet! to avail. . .{" "} </span> <span style={{ color: "#4c9aaf", fontSize: 9, fontWeight: "bold", }} > LOGIN </span> </p> </div> <div style={styles.rightDetails}> <div style={{ flex: 1, flexDirection: "row", display: "flex", contentAlign:'right', justifyContent:'space-between' }} > <Rate /> <Discount /> </div> <span style={{ color: "#de1621", fontSize: 17, fontWeight: "bold", marginTop: 0, }} > {" "} ₹ 5,768 </span> <p style={{ fontSize: 8, marginTop: 0, }} > per Semester (3months) </p> <p style={{ color: "#34b597", fontSize: 9, fontWeight: "bold", }} > Free Cancellation . Free Wi-Fi </p> </div> </div> </div> ))} </InfiniteScroll> </div> </div> </div> ); } } const styles = { style: { flex: 1, width: 500, height: 255, margin: 50, borderRadius: 5, overflow: "hidden", boxShadow: "1px 1px 2px 1px #bfbdbd", }, imageContainer: { position: "relative", backgroundColor: "black", }, textBlock: { position: "absolute", top: "10px", right: "10px", backgroundColor: "#f5a821", color: "white", paddingLeft: "8px", paddingRight: "8px", textAlign: "center", borderRadius: 5, }, textBlockBottom: { position: "absolute", bottom: "10px", left: "10px", backgroundColor: "white", color: "grey", paddingLeft: "15px", paddingRight: "15px", textAlign: "center", borderRadius: 15, }, textBlockBottomSecond: { position: "absolute", bottom: "10px", left: "130px", backgroundColor: "white", color: "grey", paddingLeft: "15px", paddingRight: "15px", textAlign: "center", borderRadius: 15, }, textBlockBottomRight: { position: "absolute", bottom: "10px", right: "-5px", color: "white", paddingLeft: "15px", paddingRight: "15px", textAlign: "center", borderRadius: 15, }, headContainer: { flex: 1, marginLeft: 50, }, mainContainer: { flex: 1, marginLeft: 50, }, leftContainer: { float: "left", }, rightContainer: { flex: 1, float: "right", marginRight: 70, }, image: { flex: 1, height: "60%", }, details: { height: "39%", width: "99.2%", flex: 1, }, leftDeails: { float: "left", marginLeft: 15, }, rightDetails: { flex: 1, textAlign: "right", height: "100%", float: "right", marginRight: 15, }, lineOverText: { textDecoration: "line-through", fontSize: 10, }, greyDetails: { color: "grey", fontSize: 9, }, }; export default App;
import axios from "axios"; import "./data-mock"; const server = "http://localhost:3000"; const api = axios.create({ baseURL: server, timeout: 1000, headers: { "X-Custom-Header": "foobar" } }); function makeCancelable(promise) { let hasCanceled = false; const wrappedPromise = new Promise((resolve, reject) => { promise.then( val => hasCanceled ? reject(new Error({ isCanceled: true })) : resolve(val), err => hasCanceled ? reject(new Error({ isCanceled: true })) : reject(err) ); }); return { promise: wrappedPromise, cancel() { hasCanceled = true; } }; } // get all tweets export function getTweets() { return makeCancelable(api.get("/tweets")); } export function getUserById(userId) { return makeCancelable(api.get(`/user?id=${userId}`)); } /** * * @param {String} name user name */ export function getUserByName(name) { return new Promise((resolve, reject) => { api .get(`/user?name=${name}`) .then(user => resolve(user.data)) .catch(err => reject(err)); }); } // explore page, get global trendings export function getGlobalTrends() { return makeCancelable(api.get("/trends?limit=5")); } // get all trends export function getTrends() { return makeCancelable(api.get("/trends")); } /** * return recommending following users * @param {number} limit the number of users of returned, default 20. */ export function getRelatedUsers(limit) { const url = limit ? `/relatedusers?limit=${limit}` : "/relatedusers"; return makeCancelable(api.get(url)); } export function getEvent() { const url = "/bigevent"; return makeCancelable(api.get(url)); } export function getNewEvents() { const url = "/newevents"; return makeCancelable(api.get(url)); } export function getRecommendUsers() { const url = "/recommendusers"; return makeCancelable(api.get(url)); } export function getPopularArticles() { const url = "/populararticles"; return makeCancelable(api.get(url)); } export function getSearchRecommend(query) { const url = `/searchrecommend?query=${query}`; return makeCancelable(api.get(url)); } export function getNotifications() { const url = "/notifications"; return makeCancelable(api.get(url)); } export function searchHot() { const url = "/searchhot"; return makeCancelable(api.get(url)); } export function getRecommendScreenName() { const url = "/recommendscreenname"; return makeCancelable(api.get(url)); } export function getRecommendFollowings() { const url = "/recommendfollowings"; return makeCancelable(api.get(url)); }
'use strict'; const { Genre, connect, disconnect, } = require('./database.js'); const { runMigrations, rollbackMigrations } = require('../migrations/run.js'); beforeAll(async () => { await runMigrations(); }); describe('Testing Author table', async () => { it('Checks if genres are retrieved from database', async () => { const queries = await connect(); const genres = await queries.getAllGenres(); expect(genres.length).toBeGreaterThanOrEqual(5); }); }); afterAll(async () => { await rollbackMigrations(); await disconnect(); });
export const weddings = { heroImgUrl: 'https://images.unsplash.com/photo-1457102053979-b1da354f1785?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=654265c814f344788651a3cb33d01da1&auto=format&fit=crop&w=1267&q=80', pageTitle: 'Weddings', pageSlogan: 'Plan the perfect wedding. Get introduced to the right professionals', };
var mongoose = require('mongoose'); var User = require('./user'); var TripComponent = require('./trip-component'); var Schema = mongoose.Schema; var policySchema = new Schema({ id: Schema.Types.ObjectId, name: String, permittedComponents: [TripComponent], basePrice: Number, isGeneralPolicy: Boolean }); module.exports = policySchema;
var can = document.getElementById('c'), mycontext = can.getContext('2d'); mycontext.fillStyle='rgba(100,20,10,0.43)'; mycontext.fillRect(0, 0, 1280, 400); mycontext.font='140px Arial'; mycontext.lineWidth =4; mycontext.strokeStyle='#ddd'; mycontext.fillStyle='#00f'; mycontext.strokeText('E', 200, 180); mycontext.fillText('E', 200, 180); mycontext.fillStyle='#901'; mycontext.strokeText('d', 300, 150); mycontext.fillText('d', 300, 150); mycontext.fillStyle='#012'; mycontext.strokeText('u',380, 190); mycontext.fillText('u', 380, 190); mycontext.fillStyle='#120'; mycontext.strokeText('G',470, 140); mycontext.fillText('G', 470, 140); mycontext.fillStyle='#009'; mycontext.strokeText('a',580,200); mycontext.fillText('a', 580, 200); mycontext.fillStyle='#f00'; mycontext.strokeText('m',660, 180); mycontext.fillText('m', 660 ,180); mycontext.fillStyle='#410'; mycontext.strokeText('e',770, 240); mycontext.fillText('e', 770, 240); mycontext.font='70px Arial'; mycontext.fillStyle='#fff'; mycontext.fillText('welcome', 400, 340);
import { put, take, call, fork } from 'redux-saga/effects'; import * as types from '../constants/ActionTypes'; export function* requestStorySetList() { try { } catch (error) { yield put(receiveArticleList([], typeId)); toastShort('网络发生错误,请重试'); } } export function* watchRequestStorySetList() { while (true) { yield take(types.REQUEST_STORYSET_LIST); yield fork(requestStorySetList); } }
// 可用支付方式 var DM_PayTypeList = function(){ MessageMachine.call(this); // url this.url = url_host+"/pay/paymentType.json"; // template this._template= '\ {{if status == 1}}\ <div id="{{payType}}" onclick="changeTab(id);">\ <div class="ub ub-fh ub-ac">\ <div class="ub-img umwh-1 umar-r" style="background-image:url({{logo}})"></div>\ <div class="ub-f1 umar-l f-big2">{{name}}</div>\ <div class="cbximg umwh"></div>\ </div>\ </div>\ {{/if}}\ '; // set Render this.setRender(this._template); // 数据格式转换 this.transfer = function(data){ return data; } // 测试数据 this.getTestData = function(){ var response = '{}'; return JSON.parse(response); } }
import {fromJS} from "immutable"; import * as constants from "./actionTypes"; const defaultState = fromJS({ searchParams: {}, createUserInfo: {}, tableData: {count: 0, num: 0, data: []}, visible: false, pagination: { current: 1, pageSize: 10, total: 0 }, userInfo: {}, myInfo: { isLogin: false, isRegister:false, token: "" }, // isLogin: false, typeOption: [ {key: "-2", value: "所有用户"}, {key: "0", value: "普通用户"}, {key: "1", value: "管理员"}, {key: "2", value: "后台操作员"}, // {key:"3",value:""}, ], stateOption: [ {key: "-2", value: "所有用户"}, {key: "-1", value: "不存在"}, {key: "0", value: "已删除"}, {key: "1", value: "正常"}, ], deviceInfo:{ count:0, num:0, data: [ { device_type: 0, device_id: 'web_device_0', device_state: 0, update_at: '2021-05-11T22:29:36.92+08:00', ram_name: 'web_device_0', client_id: 'GID_device@@@web_device_0', current_user: '609a281ed6501d103a590c6f', current_hard_devices_id_list: [ 'hard_device_0', 'hard_device_1' ], hard_device_list: [ { _id: '607a8c395f6bcc080b79c108', current_sensors_id_list: [ 'sensor_0' ], current_web_device_id: 'web_device_0', device_id: 'hard_device_0', device_state: 0, device_type: 0, sensor_list: [ { _id: '60a1012896d6819a0b3ea280', create_at: '2021-05-16T19:25:28.567+08:00', current_hard_device_id: 'hard_device_0', device_id: 'sensor_0', device_state: 0, device_type: 0, update_at: '2021-05-16T19:25:28.567+08:00' } ] }, { _id: '607a8c395f6bcc080b79c109', current_sensors_id_list: null, current_web_device_id: 'web_device_0', device_id: 'hard_device_1', device_state: 0, device_type: 0, sensor_list: [] } ], _id: '607a8c395f6bcc080b79bd20' } ], }, }) // eslint-disable-next-line import/no-anonymous-default-export export default (state = defaultState, action) => { // const newState = JSON.parse(JSON.stringify(state)) switch (action.type) { case constants.CHANGE_LIST_DATA: // console.log(state, action) // state = state.set("tableData", action.value) // console.log(state, action) // newState.searchParams = action.value console.log("tableData", action.value) console.log("state", state) state.set("tableData", action.value) state = state.setIn(['tableData'], fromJS(action.value)) // console.log("state",state.get("tableData")) // state.merge({ // "tableData":action.value.valueOf() // }) break case constants.CHANGE_PAGINATION: return state.setIn(['pagination'], fromJS(action.value)) case constants.CHANGE_SEARCH_PARAMS: const searchParams = state.get("searchParams").toJS() searchParams[action.value.key] = action.value.value return state.set("searchParams", fromJS(searchParams)) case constants.CHANGE_VISIBLE: return state.set("visible", fromJS(action.value)) case constants.CHANGE_USER_INFO: console.log("dsdfds= ", action.value) return state.set("userInfo", fromJS(action.value)) case constants.LOGIN: return state.set("myInfo", fromJS(action.value)) case constants.CHANGE_DEVICE_INFO: return state.set("deviceInfo", fromJS(action.value)) default: break } return state }
const form = document.forms.namedItem('button1'); let today = new Date().toISOString().substr(0, 10); document.querySelector("#date").value = today; form.addEventListener ( 'submit', (event) => { event.preventDefault(); document.location.href = "books.html"; } );
const DecoJardin=require('../Modele/decojardinModel') exports.create=(req,res)=>{ const newDecoJardin=new DecoJardin({ name:req.body.name, ImageDecojardin:req.file.originalname, categori:req.body.categori, prix:req.body.prix, quantite:req.body.quantite }) newDecoJardin.save() .then(result=>res.status(200).json({ message:"Deco jardin added" })) .catch(er=>console.log(er)) } exports.findDecoJardin=(req,res)=>{ DecoJardin.find() .then(result=>res.send(result)) .catch(er=>console.log(er)) }; exports.SortDecoJardinname=(req,res)=>{ DecoJardin.find() .sort({name:1}) .exec((err,data) => err ?console.log(err) : res.send(dada)) }; exports .SortDecoJardinprix=(req,res)=>{ DecoJardin.find() .sort({prix:1}) .exec((err,data) =>err ? console.log(err):res.send(data)); }; exports.DeleteJardin=(req,res)=>{ let id=req.params.id DecoJardin.findByIdAndDelete({_id:id}) .then(result=>res.send(result)) .catch(er=>console.log(er)) }; exports.findJardinId=(req,res)=>{ let id=req.params.id DecoJardin.findById({_id:id}) .then(result=>res.send(result)) .catch(er=>console.log(er)) }; exports.EditJardin=(req,res)=>{ let id=req.params.id DecoJardin.findByIdAndUpdate({_id:id},req.body) .then(result=>res.send(result)) .catch(er=>console.log(er)) }
let BaseMenu = require("./basemenu.js"); /** * The Class Selection menu. Displays a list of classes to choose from. When this menu is loaded, it must be passed an object containing the unit to be modified. On selection, the menu will set the unit's class, then either exit or continue along the character creation process if the flag is set. * @name ClassSelect * @type ElonaJS.UI.Menus.BaseMenu * @memberof! ElonaJS.UI.Menus */ let ClassSelect = new BaseMenu(); ClassSelect.Customize({centered: true, size: {w: 720, h: 500}}); ClassSelect.sounds.select = "spell"; ClassSelect._OnLoad = function(parameters){ this.parameters = parameters; let race = DB.Races.GetByID(parameters.unit.GetRace()); let rimgdet = DB.Graphics.GetByID("character." + race.pic.female); if(this.init){ this.options.current = 0; this.options.page = 0; this.components.CPrev1.SetImage("character." + race.pic.female); this.components.CPrev2.SetImage("character." + race.pic.male); this.components.CPrev1.SetBasePosition(330, 63 - rimgdet.h); this.components.CPrev2.SetBasePosition(330 + 20 + rimgdet.w, 63 - rimgdet.h); this.components.Race.SetText(i18n("ui.classselect.race", {race: DB.Races.GetByID(parameters.unit.race).name})); return; } this.bgcur = 3; this.bgcounter = 0; this.init = true; new UI.Components.Image({id: "Background", img: "void", alignment: "fill", position: {z: -1}}).Attach(this); new UI.Components.Image({id: "Paper", img: "interface.paper", width: 720, height: 500, shadow: {distance: 10, blur: 0}, position: {z: 0}}).Attach(this); new UI.Components.Image({id: "BG_Deco", img: "cbg3", position: {x: 30, y: 40, z: 1}, width: 290, height: 430, alpha: 0.2}).Attach(this); new UI.Components.Text({id: "Desc", position: {x: 210, y: 70}, wrap: {width: 460, spacing: 16}, text: ""}).Attach(this); new UI.Components.Text({id: "Help", alignment: "bottom-left", i18n: "hints.help", position: {x: 30, y: -22}}).Attach(this); new UI.Components.Text({id: "Race", text: "Race: ", position: {x: 520, y: 40}}).Attach(this); new UI.Components.Text({id: "PageNum", position: {x: 640, y: 475}, size: 10}).Attach(this); new UI.Components.Image({id: "CPrev1", img: "character." + race.pic.female, position: {x: 350, y: 15, z: 3}, alpha: 1, scale: 1}).Attach(this); new UI.Components.Image({id: "CPrev2", img: "character." + race.pic.male, position: {x: 400, y: 15, z: 3}, alpha: 1, scale: 1}).Attach(this); new UI.Components.PaperHeader({ id: "Header", text: {i18n: "ui.classselect.title"} }).Attach(this); new UI.Components.PaperFooter({ id: "Hint", position: {x: 35, y: 470}, rect: {width: 625}, text: {i18n: "hints.3b"} }).Attach(this); new UI.Components.SectionHeader({ id: "Classes", position: {x: 35, y: 40}, text: {i18n: "ui.classselect.section1"} }).Attach(this); new UI.Components.SectionHeader({ id: "Details", position: {x: 205, y: 40}, text: {i18n: "ui.classselect.section2"} }).Attach(this); new UI.Components.SectionHeader({ id: "AttributeBonuses", position: {x: 205, y: 205}, text: {i18n: "ui.classselect.section3"} }).Attach(this); new UI.Components.SectionHeader({ id: "TrainedSkills", position: {x: 205, y: 285}, text: {i18n: "ui.classselect.section4"} }).Attach(this); new UI.Components.Guide({ position: {x: 0, y: 0}, id: "Guide", text: {i18n: "ui.classselect.guide"} }).Attach(this); this.components.CPrev1.SetBasePosition(330, 63 - rimgdet.h); this.components.CPrev2.SetBasePosition(330 + 20 + rimgdet.w, 63 - rimgdet.h); this.components.Race.SetText(i18n("ui.classselect.race", {race: DB.Races.GetByID(parameters.unit.race).name})); let attb = DB.Attributes.Search({primary: true}); for(let i = 0; i < attb.length; i++){ let val = attb[i]; new UI.Components.Image({id: val.id, img: val.icon, position: {x: 210 + 130 * (i%3), y: 225 + 19 * Math.floor(i/3), z: 3}}).Attach(this, "attb_icons"); new UI.Components.Text({id: val.id, position: {x: 230 + 130 * (i%3), y: 225 + 19 * Math.floor(i/3)}}).Attach(this, "attb_text"); } this._BuildList(); this.components.PageNum.SetText(i18n("ui.Page", {cur: this.options.GetPage(), max: this.options.GetMaxPages()})); } ClassSelect._BuildList = function(){ if(!this.classes) this.classes = DB.Classes.Search({playable: true}); let classes = this.classes; let opt = []; for(let i = 0; i < classes.length; i++){ let no = {text:{}, preview: {}}; no.text.i18n = classes[i].name; no.preview.desc = classes[i].description; no.preview.class = classes[i]; opt.push(no); } this.options.CustomizeList({ position: {x: 75, y: 70}, perpage: 20 }); this.options.Set(opt); } ClassSelect._PreviewData = function(){ let op = this.options.GetCurrentOption(); this.components.Desc.SetText(i18n(op.preview.desc)); this._FormatAttributes(); this._FormatSkills(); this.bgcounter++; if(this.bgcounter > 3){ this.bgcounter = 0; (this.bgcur < 8 ? this.bgcur++ : this.bgcur = 1); this.components.BG_Deco.SetImage("cbg" + this.bgcur); } this.AlignElements(); } ClassSelect._FormatAttributes = function(){ let op = this.options.GetCurrentOption(); let attb = DB.Attributes.Search({primary: true}); let atbStr = i18n("attributes.magnitude"); let cstats = op.preview.class.base_attributes; for(let i = 0, arr = Object.keys(attb); i < arr.length; i++){ let val = attb[i].id; if(this.components.attb_text[val]){ let str; let style = {fill: "black"}; if (cstats[val] == 0){str = i18n("attributes.magnitude.none"); style.fill = "rgb(120, 120, 120)";} else if (cstats[val] > 13){str = i18n("attributes.magnitude.best"); style.fill = "rgb(0, 0, 200)";} else if (cstats[val] > 11){str = i18n("attributes.magnitude.great"); style.fill = "rgb(0, 0, 200)";} else if (cstats[val] > 9){str = i18n("attributes.magnitude.good"); style.fill = "rgb(0, 0, 150)";} else if (cstats[val] > 7){str = i18n("attributes.magnitude.not_bad"); style.fill = "rgb(0, 0, 150)";} else if (cstats[val] > 5){str = i18n("attributes.magnitude.normal"); style.fill = "rgb(0, 0, 0)";} else if (cstats[val] > 3){str = i18n("attributes.magnitude.little"); style.fill = "rgb(150, 0, 0)";} else if (cstats[val] > 0){str = i18n("attributes.magnitude.slight"); style.fill = "rgb(200, 0, 0)";} this.components.attb_text[val].SetText(i18n(DB.Attributes.GetByID(val).short).initCap() + ": " + str); this.components.attb_text[val].UpdateStyle(style); } } } ClassSelect._FormatSkills = function(){ let op = this.options.GetCurrentOption(); let attb = op.preview.class.base_skills; let o = 1; let nwep = 0; let wpnstr = i18n("ui.classselect.wepprefix"); for(let i = 0, arr = Object.keys(attb); i < arr.length; i++){ let val = arr[i]; let skill = DB.Skills.GetByID(val); if(skill.type == "weapon"){ if(nwep > 0) wpnstr += ", "; wpnstr += i18n(skill.name).initCap(); nwep++; continue; } if(!this.components.SkillText){ this.components.SkillText = {}; this.components.SkillDesc = {}; this.components.SkillImages = {}; } if(this.components.SkillText[o]){ this.components.SkillText[o].SetText(i18n(skill.name).initCap()); this.components.SkillDesc[o].SetText(i18n(skill.desc1)); this.components.SkillImages[o].SetImage(DB.Attributes.GetByID(skill.attr).icon); } else{ new UI.Components.Text({id: o, i18n: skill.name, position: {x: 230, y: 310 + 16 * o}}).Attach(this, "SkillText"); this.components.SkillText[o].SetText(i18n(skill.name).initCap()); new UI.Components.Text({id: o, i18n: skill.desc1, position: {x: 340, y: 310 + 16 * o}}).Attach(this, "SkillDesc"); new UI.Components.Image({id: o, img: DB.Attributes.GetByID(skill.attr).icon, position: {x: 210, y: 310 + 16 * o, z: 3}}).Attach(this, "SkillImages"); } o++; } if(!this.components.SkillText[0]){ new UI.Components.Text({id: "0", text: wpnstr, position: {x: 230, y: 310}}).Attach(this, "SkillText"); new UI.Components.Image({id: "0", img: DB.Attributes.GetByID("Strength").icon, position: {x: 210, y: 310, z: 3}}).Attach(this, "SkillImages"); } else { this.components.SkillText[0].SetText(wpnstr); } for(let i = 1, arr = Object.keys(this.components.SkillText); i < arr.length; i++){ if(i < o){ this.components.SkillText[i].Show(); this.components.SkillDesc[i].Show(); this.components.SkillImages[i].Show(); } else { this.components.SkillText[i].Hide(); this.components.SkillDesc[i].Hide(); this.components.SkillImages[i].Hide(); } } } ClassSelect._OnSelect = function(){ this.parameters.unit.SetClass(this.options.GetCurrentOption().preview.class.id); UI.UnloadMenu(this); if(this.parameters.creation){ UI.LoadMenu("AttributeRoll", this.parameters); } } ClassSelect._OnBack = function(){ UI.UnloadMenu(this); if(this.parameters.creation) UI.LoadMenu("GenderSelect", this.parameters); } module.exports = ClassSelect;
import React from 'react'; import { makeStyles, Typography, Card } from '@material-ui/core'; const useStyles = makeStyles(theme => ({ box: { marginTop: 10 + 'em', marginLeft: 2 + 'em', marginRight: 2 + 'em', backgroundColor: '#b53838', overflow: 'hidden', color: 'white', padding: 10 + 'px', maxWidth: 400 } })); function Alert({message}){ const classes = useStyles(); return ( <Card component='div' className={classes.box}> <Typography variant='h3'>{message}</Typography> </Card> ) } export default Alert;
import { Button, Form, Input } from 'antd'; import React, { memo, useCallback, useEffect, useState } from 'react'; import { useHistory } from 'react-router-dom'; import { useSecurityContext } from '../context/SecurityContext'; import styled from 'styled-components'; const Container = styled.div` min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; `; const Box = styled.div` padding: 24px 24px 0 24px; border: 1px solid white; border-radius: 5px; `; const layout = { layout: "vertical", }; const tailLayout = { wrapperCol: { offset: 8, span: 16 }, }; const Login = () => { const { isAuthenticated, login } = useSecurityContext(); const { push } = useHistory(); const [loading, setLoading] = useState(false); useEffect(() => { if (isAuthenticated) { push('/') } }, [isAuthenticated, push]); const onFinish = useCallback(async values => { try { setLoading(true); await login(values); } catch (e) { setLoading(false); } }, [login]); return ( <Container> <Box> <Form {...layout} name="basic" onFinish={onFinish} > <Form.Item name="email" rules={[{ required: true, message: 'Please input your email!' }]} > <Input placeholder="email" /> </Form.Item> <Form.Item name="password" rules={[{ required: true, message: 'Please input your password!' }]} > <Input.Password placeholder="Password" /> </Form.Item> <Form.Item {...tailLayout}> <Button type="primary" htmlType="submit" loading={loading}> Submit </Button> </Form.Item> </Form> </Box> </Container> ); }; export default memo(Login);
import server from './server'; import logger from 'winston'; import * as fake from './fake'; const port = process.env.PORT || 3000; server.create(port).run(() => { logger.info('Running on port %s', port); }); fake.start();
const xss = require('xss') const { exec } = require('../db/mysql.js') const getList = (author, keyword) => { let sql = `select * from blogs where 1=1 ` if (author) { sql += `and author='${author}' ` } if (keyword) { sql += `and title like '%${keyword}%' ` } sql += `order by createtime desc` return exec(sql) } const getDetail = (id) => { let sql = `select * from blogs where id='${id}'` return exec(sql).then(rows => { return rows[0] }) } const newBlog = (author, blogData = {}) => { // blogData 包含 title content const title = xss(blogData.title) const content = xss(blogData.content) const createtime = new Date().getTime() let sql = ` insert into blogs(title,content,createtime,author) values('${title}','${content}',${createtime},'${author}');` return exec(sql).then(res => { return { id: res.insertId } }) } const updateBlog = (id, author, blogData = {}) => { // blogData 包含 title content const { title, content } = blogData let sql = `update blogs set title='${title}', content='${content}' where id=${id} and author='${author}'` return exec(sql).then(res => { return res.affectedRows > 0 }) } const deleteBlog = (id, author) => { let sql = `delete from blogs where id=${id} and author='${author}'` return exec(sql).then(res => { return res.affectedRows > 0 }) } module.exports = { getList, getDetail, newBlog, updateBlog, deleteBlog }
'use strict'; /** * @ngdoc overview * @name friendsFeedApp * @description This is a simple angular app to mimic a news feed based on friendship (friends can see each other's posts) * # friendsFeedApp * * Main module of the application. */ angular .module('friendsFeedApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch', 'restangular', 'friendsFeedApp.services', 'friendsFeedApp.directives' ]) .constant("AppConfig", { "api_url": "http://friends-feed-api.natabarbosa.com", "image_server_url": "http://friends-feed-api.natabarbosa.com" }) .config(function($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl', controllerAs: 'main' }) .otherwise({ redirectTo: '/' }); }) .config(function(RestangularProvider, AppConfig) { RestangularProvider.setBaseUrl(AppConfig.api_url); RestangularProvider.setRestangularFields({ id: "_id" }); }); angular.module('friendsFeedApp.services', []); angular.module('friendsFeedApp.directives', []);
import AuthApi from '../api/AuthApi'; import MainApi from '../api/MainApi'; export const SET_TEACHER_LIST = 'SET_TEACHER_LIST'; export const getAllTeacher = (name) => async (dispatch) => { try { const response = await MainApi.get( `/teachers?page=0&size=10&sort=createdAt,desc&name=${name}`, ); if (response.status === 200) { dispatch({type: SET_TEACHER_LIST, payload: response.data}); } if (response.status === 204) { dispatch({type: SET_TEACHER_LIST, payload: {content: []}}); } } catch (error) { // error.response && message.error(error.response.data.message) console.log(error); } };
import React, {Component} from 'react'; import {render} from 'react-dom'; import {IMG_CONSTANT, APP_CONSTANT} from '../constants/application.constants'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import {registerUser} from '../actions/registerAction'; import {contactUs, facebookRegister} from '../actions/loginAction'; import {isValidEmail} from '../utils/Validation'; let serialize = require('form-serialize'); import _ from "lodash"; const Captcha = require('react-captcha'); import toastr from 'toastr'; import Spinner from 'react-spinner'; let imagePath= IMG_CONSTANT.BASE_PATH; class Registration extends Component { constructor(props,context) { super(props,context); this.onfieldChange= this.onfieldChange.bind(this); this.onfieldBlur= this.onfieldBlur.bind(this); this.onSubmit=this.onSubmit.bind(this); this.state = { Fname: "", Lname:"", email: "", newPass : "", rePass : "", errPass1 : "", errPass2 : "", a:"",b:"", errEmail:"", isRobot: true, FB_UserDetails:{}, isExists:true, fb_id:"" } } componentWillMount(){ if(this.props.userDetails!=null){ this.state.isExists = this.props.userDetails.exists; this.setState({ FB_UserDetails:this.props.userDetails, Fname : this.props.userDetails.first_name, Lname : this.props.userDetails.last_name, email : this.props.userDetails.email, fb_id : this.props.userDetails.fb_id, isExists : this.props.userDetails.exists }); } else{ this.state.FB_UserDetails = Object.assign({},null); } } componentDidMount(){ if(this.props.userDetails!=null){ this.refs.zipcode.focus(); } } onCaptchaClick(value){ ///this.state.isRobot = false; } onfieldChange(e){ if(e.target.name == "email"){ let errors = isValidEmail(e.target.value); if(errors == false){ this.setState({ errEmail : (<span className="err-msg"> Invalid Email</span>), email : "" }); } else{ this.setState({ errEmail : "", email : e.target.value }); } } } onfieldBlur(e){ } onCancelClick(){ this.state.isExists = true; this.state.FB_UserDetails = Object.assign({},null); this.context.router.push('/'); } onSubmit(){ if(this.state.isRobot){ toastr.error("Please Validate ReCaptcha"); }else{ this.setState({ajaxCallInProgress:true}); let form = document.querySelector('#registration_page'); let formData = serialize(form, {hash: true }); if(!(_.has(formData, 'is_private'))){ _.set(formData, 'is_private', false); }else{ _.set(formData, 'is_private', true); } this.props.registerUser(formData).then((data)=>{ this.setState({ajaxCallInProgress:false}); this.context.router.push('/home'); }).catch((error)=>{ this.setState({ajaxCallInProgress:false}); }); } } facebookRegister(){ if(this.state.isRobot){ toastr.error("Please Validate ReCaptcha"); }else{ this.setState({ajaxCallInProgress:true}); let form = document.querySelector('#registration_page'); let formData = serialize(form, {hash: true }); if(!(_.has(formData, 'is_private'))){ _.set(formData, 'is_private', false); }else{ _.set(formData, 'is_private', true); } this.props.facebookRegister(formData).then((data)=>{ this.setState({ajaxCallInProgress:false}); this.context.router.push('/home'); }).catch((error)=>{ this.setState({ajaxCallInProgress:false}); }); } } /* Validation */ onRequired(e) { if(e.target.name == "first_name"){ if(e.target.value == ""){ this.setState({ a:(<span className="err-msg"> First Name is Required</span> ), Fname:null }); } else{ this.setState({ a: null, Fname:e.target.value }) ; } } if(e.target.name == "last_name"){ if(e.target.value == ""){ this.setState({ b:(<span className="err-msg"> Last Name is Required</span> ), Lname:null }); } else{ this.setState({ b: null, Lname:e.target.value }) ; } } if(e.target.name == "zipcode"){ if(e.target.value == "" || e.target.value.length < 5){ this.setState({ c:(<span className="err-msg"> Please enter valid Zipcode</span> ), zipCode:null }); } else{ this.setState({ c: null, zipCode:e.target.value }) ; } } } validatePass(e){ if(e.target.name == "password"){ if(e.target.value == ""){ this.setState({ errPass1 : ( <span className="err-msg"> Please enter your Password </span> ), newPass : "" }); } else{ this.setState({ errPass1 : "", newPass : e.target.value }); } if((this.state.rePass != "") && (this.state.rePass != e.target.value)){ this.setState({ errPass2 : (<span className="err-msg">Password Doesnt Match</span>), }); } else{ this.setState({ errPass2 : "" }); } } if(e.target.name == "confirmPassword"){ if(this.state.newPass != e.target.value ) { this.setState({ errPass2 : (<span className="err-msg">Password Doesnt Match</span>), rePass : null }); } else{ this.setState({ errPass2 : "", rePass : e.target.value }); } } } zipCodeEvent(e) { const re = /[0-9]+/g; if ((!re.test(e.key)) || (e.target.value.length >= 5)) { e.preventDefault(); } } onlyTexts(e){ const re = /[a-zA-Z]+/g; if (!re.test(e.key)) { e.preventDefault(); } } /* validation code over */ onSendClick(){ let form = document.querySelector('#contactForm'); let formData = serialize(form, { hash: true }); this.props.contactUs(formData).then(()=>{ $("#useremails").val(''); $('#contactMessage').val(''); $("#myModal").modal('hide'); $('#secondModal').modal('hide'); }).catch((error)=>{ }); } render() { return( <div className="regis"> <div className="bgLoginReg"> <div className="BgadminDashboard"></div> </div> <div className="login-page"> <div className="navigation"> <div className="logo_login"> <img src={imagePath + "Golf_CNX_Logo.png"}></img> </div> <div className="menu-right"> <a data-toggle="modal" data-target="#myModal" className="txtwhite"> Contact Us</a> <div className="modal fade addInvite" id="myModal" role="dialog" data-backdrop="static"> {this.state.ajaxCallInProgress?(<div><Spinner /></div>):(<form action="" method="post" id="contactForm" name="contactForm" ref="contactForm"> <div className="modal-dialog modal-sm mt15pc"> <div className="modal-content"> <div className="modal-header col-sm-12 modalHeader"><h4 className="m0px">CONTACT ADMIN</h4></div> <div className="modal-body col-sm-12 bgwhite mb0px"> <div className="col-sm-12"> <label>Name:</label><input type="text" placeholder="John Doe" id="name" name="name" className="form-control"/> </div> <div className="col-sm-12"> <label>Email:</label><input type="email" placeholder="[email protected]" id="email" name="email" className="form-control"/> </div> <div className="col-sm-12"> <label>Message</label> <textarea className="txtarea form-control invtTxtArea" id="contactMessage" name="message" /> </div> </div> <div className="modal-footer col-sm-12 bgwhite"> <button type="button" className="btnSend" id="btnSend" onClick={this.onSendClick.bind(this)} >Send</button> <button type="button" className="btnCncl" data-dismiss="modal">Cancel</button> </div> </div> </div> </form>)} </div> </div> </div> <div className="regisCenterPage"> <div className="middlealign"> <div className="logoLoginPage"> <img src={imagePath + "Golf_login_Logo.png"} className="logogolf" ></img> </div> </div> <div> <form name="registration_page" id="registration_page" ref="registration_page" action="" method="post"> <div className="form-group txtwhite"> <input type="text" id="first_name" name="first_name" key="first_name" className="formcontrol" defaultValue={this.state.FB_UserDetails.first_name} placeholder="First Name" onChange={this.onRequired.bind(this)} onKeyPress={this.onlyTexts.bind(this)}/> {this.state.a} </div> <div> <input type="text" id="last_name" key="last_name" name="last_name" className="formcontrol txtwhite" defaultValue={this.state.FB_UserDetails.last_name} placeholder="Last Name" onChange={this.onRequired.bind(this)} onKeyPress={this.onlyTexts.bind(this)}/> {this.state.b} </div> <div> <input type="email" name="email" id="email" key="email" className="formcontrol mt10px txtwhite" defaultValue={this.state.FB_UserDetails.email != null && this.state.FB_UserDetails.email != undefined ? this.state.FB_UserDetails.email:""} placeholder="Email" onChange={this.onfieldChange.bind(this)}/> </div> {this.state.errEmail} { this.props.userDetails!=null && this.props.userDetails!=undefined ? (<div></div>):(<div> <div> <input type="password" id="password" name="password" key="password" className="formcontrol mt10px txtwhite" value={this.state.newPass} onChange={this.validatePass.bind(this)} placeholder="Password"/> </div> {this.state.errPass1} <div> <input type="password" name="confirmPassword" key="confirmPassword" id="confirmPassword" className="formcontrol mt10px txtwhite" placeholder="Repeat Password" onChange={this.validatePass.bind(this)}/> </div> {this.state.errPass2} </div>)} <div> <input type="zipcode" name="zipcode" key="zipcode" id="zipcode" ref="zipcode" className="formcontrol mt10px txtwhite" placeholder="Zip Code" onChange={this.onRequired.bind(this)} onKeyPress={this.zipCodeEvent.bind(this)}/> </div> {this.state.c} <div> <input type="hidden" name="fb_id" key="fb_id" id="fb_id" className="formcontrol mt10px txtwhite" defaultValue={this.state.FB_UserDetails.fb_id} /> </div> <div className=" mrgtopp10px" > <span className="switchround mrgtop10px">Private Account:</span> <label className="switch switch_resp ml23pc"> <input type="checkbox" onChange={this.onfieldChange} name="is_private" key="is_private" id="is_private"/> <div className="slider round"></div> </label> </div> <div className="ml40pc captchaAlign"> <Captcha className="recaptcha_Style" sitekey = {APP_CONSTANT.SITE_KEY} lang = 'en' theme = 'light' type = 'image' callback={(value) => {this.setState({isRobot:false}) } }/> </div> </form> </div> <div className="col-sm-12"> {this.props.userDetails!=null && this.props.userDetails!=undefined ?(<div className="col-sm-6"> <input type="button" className="btn registsign" disabled= {this.state.isRobot || !this.state.Fname || !this.state.Lname || !this.state.email || !this.state.zipCode || this.state.errEmail } onClick={this.facebookRegister.bind(this)} value="Sign Up"/> {/*<button className="btn registsign" disabled= { !this.state.Fname || !this.state.Lname || !this.state.email || !this.state.zipCode || this.state.errEmail } onClick={this.facebookRegister.bind(this)}>Sign Up</button>*/} </div> ):(<div className="col-sm-6"> <input type="button" className="btn registsign" onClick={this.onSubmit} disabled= {this.state.isRobot || !this.state.Fname || !this.state.Lname || !this.state.newPass || !this.state.email || !this.state.rePass || !this.state.zipCode || this.state.errEmail || this.state.errPass2} value="Sign Up"/> {/*<button className="btn registsign" onClick={this.onSubmit} disabled= { !this.state.Fname || !this.state.Lname || !this.state.newPass || !this.state.email || !this.state.rePass || !this.state.zipCode || this.state.errEmail || this.state.errPass2} >Sign Up</button>*/} </div>)} <div className="col-sm-6"> <input onClick={this.onCancelClick.bind(this)} className="btn registcancel" value="Cancel"/> {/*<button onClick={this.onCancelClick.bind(this)} className="btn registcancel"> Cancel</button>*/} </div> </div> </div> </div> </div> ); } } Registration.contextTypes={ router:React.PropTypes.object.isRequired }; function mapStateToProps(state){ return{ registerDetails:state.registerUser, userDetails: state.activeUser, }; } function matchDispatchToProps(dispatch){ return bindActionCreators({registerUser, contactUs,facebookRegister},dispatch); } export default connect(mapStateToProps,matchDispatchToProps) (Registration)
export const SliderData = [ { image:'https://s3.us-west-2.amazonaws.com/com.admitonelive.content.images/react-admitonelive/1610659452321-Alec-Benjamin.jpg', link:'#', title:'Music of Cream', date:'Apr 11, Sun - 8:00pm', place:'Phoenix Concert Theatre - Toronto, ON', }, { image:'https://s3.us-west-2.amazonaws.com/com.admitonelive.content.images/react-admitonelive/1610659259047-Ferris-And-Sylvester-Sept11.jpg', link:'#', title:'FLOW', date:'Jun 12, Sat - 8:00pm', place:'Phoenix Concert Theatre - Toronto, ON', }, ]
import React from "react"; import { Story } from "storybook/assets/styles/common.styles"; import Select from "../SelectExample"; const ScreenerStory = () => ( <Story> <Select placeholder="Tell me a story..." size="small" a11yText="story"> <option value="Pepsi">Pepsi</option> <option value="Coke">Coke</option> </Select> <Select placeholder="Tell me a story..." a11yText="story"> <option value="Pepsi">Pepsi</option> <option value="Coke">Coke</option> </Select> <Select placeholder="Tell me a story..." size="large" a11yText="story"> <option value="Pepsi">Pepsi</option> <option value="Coke">Coke</option> </Select> <Select isDisabled value="This is my disabled story" a11yText="story"> <option value="Pepsi">Pepsi</option> <option value="Coke">Coke</option> </Select> <Select isReadOnly value="This is my read only story" a11yText="story"> <option value="Pepsi">Pepsi</option> <option value="Coke">Coke</option> </Select> <Select hasError value="This is my error story" a11yText="story"> <option value="Pepsi">Pepsi</option> <option value="Coke">Coke</option> </Select> <Select value="Pepsi" a11yText="story"> <option value="Pepsi">Pepsi</option> <option value="Coke">Coke</option> </Select> </Story> ); export default ScreenerStory;
define(["DeferredUtil","WebSite","assert"], function (DU,WebSite,A) { var CPR=function (ns, url) { A.is(arguments,[String,String]); return { getNamespace:function () {return ns;}, sourceDir: function () {return null;}, getDependingProjects: function () {return [];},// virtual loadDependingClasses: function (ctx) { //Same as projectCompiler /TPR/this/ (XXXX) var task=DU.directPromise(); var myNsp=this.getNamespace(); this.getDependingProjects().forEach(function (p) { if (p.getNamespace()==myNsp) return; task=task.then(function () { return p.loadClasses(ctx); }); }); return task; }, loadClasses: function (ctx) { console.log("Loading compiled classes ns=",ns,"url=",url); var src = url+(WebSite.serverType==="BA"?"?"+Math.random():""); var t=this; return this.loadDependingClasses(ctx).then(function () { return t.requirejs(src); }).then(function () { console.log("Done Loading compiled classes ns=",ns,"url=",src,Tonyu.classes); }); }, requirejs: function (src) { return DU.promise(function (s) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); if (typeof tonyu_app_version==="string") src+="?"+tonyu_app_version; script.src = src; var done = false; script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; console.log("Done load ",src); script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } s(); } }; head.insertBefore( script, head.firstChild ); }); }, loadClassesOLD: function (ctx) { console.log("Load compiled classes ns=",ns,"url=",url); var d=new $.Deferred; var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = url+(WebSite.serverType==="BA"?"?"+Math.random():""); var done = false; script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } console.log("Done Load compiled classes ns=",ns,"url=",url,Tonyu.classes); //same as projectCompiler (XXXX) /*var cls=Tonyu.classes; ns.split(".").forEach(function (c) { if (cls) cls=cls[c]; // comment out : when empty concat.js //if (!cls) throw new Error("namespace Not found :"+ns); }); if (cls) { for (var cln in cls) { var cl=cls[cln]; var m=Tonyu.klass.getMeta(cl); ctx.classes[m.fullName]=m; } }*/ //------------------XXXX d.resolve(); } }; this.loadDependingClasses(ctx).then(function () { head.insertBefore( script, head.firstChild ); }); return d.promise(); } } }; return CPR; });
$(document).ready(function() { if ($("#alertSuccess").text().trim() == "") { $("#alertSuccess").hide(); } $("#alertError").hide(); refresh(); }); $(document).on("click","#btnSave",function(event) { $("#alertSuccess").text(""); $("#alertSuccess").hide(); $("#alertError").text(""); $("#alertError").hide(); var status = validateJobForm(); if (status != true) { $("#alertError").text(status); $("#alertError").show(); return; } if(status == true){ setTimeout(myfuction,3000); document.getElementById("applyform").submit(); } }); function validateJobForm() { if ($("#youremail").val().trim() == "") { return "Insert email Address."; } var statusemail = validateEmail(); if( statusemail != true ){ return "Invalid Email Address" } if($("#FormControlFile1").val().trim() == ""){ return "Insert Your CV file" } return true; } function validateEmail() { var emailID = document.applyform.youremail.value; atpos = emailID.indexOf("@"); dotpos = emailID.lastIndexOf("."); if (atpos < 1 || ( dotpos - atpos < 2 )) { document.applyform.youremail.focus() ; return false; } return( true ); } function myfuction() { window.location = "http://localhost/HCI_Project_CV.LK/Forieng_vacancy.php"; }
//aliases for pixi container var stage; var renderer = PIXI.autoDetectRenderer(512, 512), TextureCache = PIXI.utils.TextureCache, Sprite = PIXI.Sprite, resources = PIXI.loader.resources; var upKey = keyboard(87); var downKey = keyboard(83); var leftKey = keyboard(65); var rightKey = keyboard(68); var player; var en; function init(){ stage = new Level(); document.body.appendChild(renderer.view); gameLoop(); } function gameLoop(){ //Loop this function 60 times per second requestAnimationFrame(gameLoop); player.actuate(upKey,downKey,leftKey,rightKey); children = stage.children; for (var i=0; i < children.length; i++ ){ child = children[i]; if (child instanceof Entity) { child.onUpdate(); checkCollisions(child,children,child.onCollision); } } //Render the stage renderer.render(stage); }
module.exports = class TypeWrapper { constructor( type, opts ) { this.type = type; if ( opts ) { Object.keys( opts ).forEach( k => { this[ k ] = opts[ k ]; } ); } } nullable( val = true ) { this.isNull = val; return this; } };
/** * @file .eslintrc.js * @author suyan wang * @description eslint config file */ module.exports = { extends: [ '@ecomfe/eslint-config', '@ecomfe/eslint-config/typescript' ], rules: { "comma-dangle": ["error", "never"] }, ignorePatterns: [ 'node_modules/*', '.eslintrc.js', 'dist/*', 'tsconfig/base.json' ] };
import React from "react"; import { Link } from "react-router-dom"; import "./components.css"; const bg = "hsla(120,100%,75%,0.3)"; const HomeComponent = ({ name, src, link, alert }) => { return ( <div className="col compHome"> <Link to={link} className="text-decoration-none"> <div className="card text-center m-2 p-2" style={{ cursor: "pointer", backgroundColor: `${bg}`, }} title={name} > <img src={src} alt={name} title={name} className="m-auto imageHome" /> <h5 className={`text-center m-2 alert ${alert}`}>{name}</h5> </div> </Link> </div> ); }; export default HomeComponent;
const fs = require('fs'); module.exports.directoryExists = (filePath) => { try { return fs.statSync(filePath).isDirectory(); } catch (err) { return false; } }; module.exports.fileExists = (filePath) => { try { return fs.statSync(filePath).isFile(); } catch (err) { return false; } };
var trim = require('./') var test = require('tape') test('trims query and hash parameters off a URL', function (t) { // don't modify empty URLs t.equal(trim(''), '') t.equal(trim(), '') t.equal(trim('http://localhost:9966///'), 'http://localhost:9966/') t.equal(trim('http://localhost:9966'), 'http://localhost:9966/') t.equal(trim('http://localhost:9966/'), 'http://localhost:9966/') t.equal(trim('http://localhost:9966/#'), 'http://localhost:9966/') t.equal(trim('http://localhost:9966/?'), 'http://localhost:9966/') t.equal(trim('http://localhost:9966/#something'), 'http://localhost:9966/') t.equal(trim('http://localhost:9966/a#something'), 'http://localhost:9966/a') t.equal(trim('http://localhost:9966/foo/bar?test=2#something'), 'http://localhost:9966/foo/bar') t.equal(trim('/path?foo'), '/path') t.equal(trim('/path#test?foo'), '/path') t.equal(trim('/'), '/') t.equal(trim('//'), '/') t.end() })
(function($){ //field inputs var company_price = $('.company_price input'), less = $('.less input'), net_price = $('.net_price input'); var wRate = $('.wRate input'), wPrice = $('.wPrice input'), rRate = $('.rRate input'), rPrice = $('.rPrice input'); $(company_price).blur(function(){ compute_net_price(); compute_wholesale_price(); compute_retail_price(); }); $(less).blur(function(){ compute_net_price(); compute_wholesale_price(); compute_retail_price(); }); $(wRate).blur(function(){ compute_wholesale_price(); }); $(rRate).blur(function(){ compute_retail_price(); }); function compute_net_price(){ np = $(company_price).val() - ( $(company_price).val() * ($(less).val()/100) ); $(net_price).val(np.toFixed(2)); } function compute_wholesale_price(){ wp = parseFloat($(net_price).val()) + parseFloat(( $(net_price).val() * (($(wRate).val())/100) )); $(wPrice).val(wp.toFixed(2)); } function compute_retail_price(){ rp = parseFloat($(net_price).val()) + parseFloat(( $(net_price).val() * (($(rRate).val())/100) )); $(rPrice).val(rp.toFixed(2)); } })(jQuery);
//ownersController.js (function () { "use strict"; //create a controller: (getting the existing module) angular.module("appOwner") .controller("ownersController", ownersController); //$http - call to server function ownersController($http,$scope) { //ViewModel var vm = this; //Array of the information vm.owners = []; vm.newOwner = {}; //Error message vm.errorMessage = ""; vm.isBusy = true; //sorting $scope.sortColumn = ''; $scope.reverseSort = false; $scope.sortData = function (column) { $scope.reverseSort = ($scope.sortColumn == column) ? !$scope.reverseSort : false; $scope.sortColumn = column; }; $scope.getSortClass = function (column) { if ($scope.sortColumn == column) { return $scope.reverseSort ? 'glyphicon glyphicon-chevron-down' : 'glyphicon glyphicon-chevron-up'; } return ''; }; //Get information from api get request $http.get("api/ownerships") .then(function (response) { //success angular.copy(response.data, vm.owners); }, function (error) { //failure vm.errorMessage = "Failed to load data: " + error; }) .finally(function () { vm.isBusy = false; }); //Add owner to database vm.addOwner = function () { vm.isBusy = true; vm.errorMessage = ""; $http.post("/api/ownerships", vm.newOwner) .then(function (response) { //Success vm.owners.push(response.data); vm.newOwner = {}; }, function () { //Failure vm.errorMessage = "Failed to add owner:"; }) .finally(function () { vm.isBusy = false; }); }; //Delete owner vm.deleteOwner = function (petId) { $http.delete("/api/ownerships/" + petId) .then(function (response) { var owners = vm.owners.filter(function (o) { return o.ID !== petId; }); vm.owners = owners; }, function () { //Failure vm.errorMessage = "Failed to delete owner"; }) .finally(function () { vm.isBusy = false; }); }; }; }());
const express=require("express"); const bodyParser=require("body-parser"); const db=require("./dbutils"); const app=express(); app.use(bodyParser.urlencoded({extended:false})); app.use(bodyParser.json()) //配置数据库的信息 db.config("mongodb://127.0.0.1:27017","userInfo"); //注册 app.post("/registry",function(request,response){ //获取请求信息 var username=request.body.username; var password=request.body.password; var sex=request.body.sex; var email=request.body.email; var phone=request.body.phone; db.insertOne("user",{ username:username, password:password, sex:sex, email:email, phone:phone },function(err,obj){ if(obj==null){ //返回注册失败的信息 response.send({ info:"注册失败", url:'/registry' }); }else{ //返回注册成功的信息 response.send({ info:"注册成功", url:'/login' }); } }) }); //登录 app.post("/login",function(request,response){ //获取请求信息 var username=request.body.username; var password=request.body.password; db.findOne("user",{ username:username, password:password },function(err,obj){ if(obj==null){ //返回登录失败的信息 response.send({ info:"登录失败,用户名或密码不匹配", url:'/login' }); }else{ //返回注册成功的信息 response.send({ info:"登录成功", url:'/' }); } }) }); app.listen(3000);
import fetch from 'isomorphic-fetch'; export const getUsername = () => { return fetch('/api2/profile/', { method: 'GET', credentials: 'include' }); };
import React, {Component} from 'react'; import classes from './Logo.css'; import burgerLogo from '../../assets/images/burger-logo.png'; class logo extends Component { state = { loading: true } handleImageLoaded = () => { this.setState({loading: false}); } render () { return ( <div className={classes.Logo} style={{ transform: this.props.loading ? 'translateX(-100vh)' : 'translateX(0)', visibility: this.state.loading ? 'hidden' : 'visible' }} > <img onLoad={this.handleImageLoaded} src={burgerLogo} alt="MyBurger" /> </div> ); } } export default logo;
import isBrowser from './feature-detection/is-browser' import generateID from './id/generate-id' import IDGenerator from './id/id-generator' import deepExtend from './object/deep-extend' import extend from './object/extend' import indexOfRegex from './string/index-of-regex' import lastIndexOfRegex from './string/last-index-of-regex' import isArray from './type-checking/is-array' import isDefined from './type-checking/is-defined' import isInteger from './type-checking/is-integer' import isIterable from './type-checking/is-iterable' import isNaturalNumber from './type-checking/is-natural-number' import isNumeric from './type-checking/is-numeric' import isObject from './type-checking/is-object' import isPlainObject from './type-checking/is-plain-object' import buildUri from './uri/build-uri' import parseUri from './uri/parse-uri' import isValidUrl from './validation/is-valid-url' // aliases for backwards compatibility const deepMerge = deepExtend export { isBrowser, generateID, IDGenerator, deepExtend, deepMerge, extend, indexOfRegex, lastIndexOfRegex, isArray, isDefined, isInteger, isIterable, isNaturalNumber, isNumeric, isObject, isPlainObject, buildUri, parseUri, isValidUrl, } export default { isBrowser, generateID, IDGenerator, deepExtend, deepMerge, extend, indexOfRegex, lastIndexOfRegex, isArray, isDefined, isInteger, isIterable, isNaturalNumber, isNumeric, isObject, isPlainObject, buildUri, parseUri, isValidUrl, }
function checkStorage(available, ordered) { let message; // Пиши код ниже этой строки if (ordered == 0) { message = "В заказе еще нет товаров"; } else if (ordered > available) { message = "Слишком большой заказ, на складе недостаточно товаров!"; } else { message = "Заказ оформлен, с вами свяжется менеджер"; } console.log(message); // Пиши код выше этой строки return message; } checkStorage(100, 50); checkStorage(100, 130); checkStorage(70, 0); checkStorage(200, 20); checkStorage(200, 250); checkStorage(150, 0);
let operador = null; function insert(num, op = false) { var numero = document.querySelector('.tela').innerText; console.log(numero, num) document.querySelector('.tela').innerText = numero + num if (op) { operador = num; console.log(operador) } } function clean () { document.querySelector('.tela').innerHTML = ""; } function back () { console.log ('chegou aqui') var resultado = document.getElementById('resulttela').innerText; document.getElementById('resulttela').innerHTML = resultado.substring(0, resultado.length -1); console.log( document.getElementById('resulttela').innerText); } function calc () { const calc = document.getElementById('resulttela').innerText; const numeros = calc.split(operador); let resultado = 0; if(operador === '-')resultado = parseInt(numeros[0])-parseInt(numeros[1]) if(operador === '+')resultado = parseInt(numeros[0])+parseInt(numeros[1]) if(operador === '*')resultado = parseInt(numeros[0])*parseInt(numeros[1]) if(operador === '÷')resultado = parseInt(numeros[0])/parseInt(numeros[1]) if(operador === '%')resultado = parseInt(numeros[0])%parseInt(numeros[1]) document.querySelector('.tela').innerText = resultado; }
// internal variables var _canvas; var _midi; var _fps = 60; var _width; var _height; var _ctx; var _obsts = []; var _rateOfChange = 0; var _playerX; var _projectedPos; var _playerY = 140; var _lastNote = 60; var _state; var _lastT = 0; var _numKeysPressed = 0; var _curNote = 60; var _bottomNote = 21; var _topNote = 108; var _pressedNotes = new Set(); var _selectedKeyboard; // constants var NOTENAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]; // game states const NEW = 0; const GAME = 1; const OVER = 2; // variables that change how the game behaves const flyableSpace = 350; const obstacleHeight = 15; const maxRateOfChange = 25; const playerSize = 15; const speed = 3.5; function noteNumberToName(midiNumber) { let noteNameInd = midiNumber % 12; let octave = Math.floor(midiNumber/12); return NOTENAMES[noteNameInd] + octave; } function init() { _canvas = document.getElementById("main") _width = window.innerWidth; _height = window.innerHeight; _canvas.width = _width; _canvas.height = _height; _ctx = _canvas.getContext("2d") _playerX = _width * (_lastNote-_bottomNote)/(_topNote-_bottomNote); _state = NEW; reset(); requestAnimationFrame(step); navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure); } function reset() { _obsts = []; _lastNote = 60; _playerdX = 0; _playerX = _width * (_lastNote-_bottomNote)/(_topNote-_bottomNote); _projectedPos = _playerX; } function onMIDISuccess(a) { _midi = a; let inputs = _midi.inputs.values(); for (input = inputs.next(); input && !input.done; input = inputs.next()) { input.value.onmidimessage = onMIDIMessage; } } function onMIDIMessage(e) { let data = e.data; let type = data[0] & 0xf0; let note = data[1]; let target = e.target; if(type == 144) { // note down _numKeysPressed++; _pressedNotes.add(note); if(_state == NEW) { if(_numKeysPressed == 2) { _topNote = Math.max(..._pressedNotes); _bottomNote = Math.min(..._pressedNotes); _selectedKeyboard = target; console.log("calibrated", _topNote, _bottomNote); } else if(note == 60 && target == _selectedKeyboard) { reset(); _state = GAME; } } else if(_state == GAME) { if(target == _selectedKeyboard) { if(note == _lastNote+1) { _lastNote = note; _curNote = note; } else if(note == _lastNote-1) { _lastNote = note; _curNote = note; } } _projectedPos = _width * (_lastNote-_bottomNote)/(_topNote-_bottomNote) } else if(_state == OVER && note == 60) { reset(); _state = NEW; } } else if (type == 128) { // note up _numKeysPressed--; _pressedNotes.delete(note); } } function onMIDIFailure(e) { console.error(e) } function mvObsts() { for(let obst_idx in _obsts) { _obsts[obst_idx].y -= speed; } } function rmOldObsts() { if(_obsts.length > 0 && _obsts[0].y + obstacleHeight < 0) _obsts.splice(0, 1); } function fillObsts() { if(_obsts.length == 0) { _obsts.push({ x: _width/2, y: 0 }); } let cury = _obsts[_obsts.length - 1].y; while(cury + obstacleHeight < _height) { let curx = _obsts[_obsts.length - 1].x; let nextx = curx + _rateOfChange; let nexty = cury + obstacleHeight; let rightBound = _width-flyableSpace/2; let leftBound = flyableSpace/2; nextx = Math.min(rightBound, Math.max(leftBound, nextx)); if(nextx == leftBound || nextx == rightBound) _rateOfChange *= -.25; _obsts.push({ x: nextx, y: nexty }) cury = nexty; _rateOfChange += (Math.random() - .5)*3; _rateOfChange = Math.max(-maxRateOfChange, Math.min(maxRateOfChange, _rateOfChange)); } } function isCollide() { for(let obst_idx in _obsts) { let obst = _obsts[obst_idx]; if(obst.y < _playerY+playerSize && obst.y + obstacleHeight > _playerY) { if(_playerX < obst.x-flyableSpace/2 || _playerX+playerSize > obst.x+flyableSpace/2) { return true; } } else if (obst.y > _playerY+playerSize) { break; } } return false; } function drawPlayer() { if(_state != OVER) { _ctx.rect(_playerX, _playerY, 15, 15); _ctx.fillStyle = "#fff"; _ctx.fill(); } } function drawObstacles() { const gap = 0; for(let obst_idx in _obsts) { let obst = _obsts[obst_idx]; let leftBound = obst.x - flyableSpace/2; _ctx.rect(0, obst.y, leftBound, obstacleHeight-gap); let rightBound = obst.x + flyableSpace/2; _ctx.rect(rightBound, obst.y, _width-rightBound, obstacleHeight-gap); } _ctx.fillStyle = "#fff"; _ctx.fill(); } function drawText() { const leftMargin = 60; _ctx.globalCompositeOperation = 'difference'; switch(_state) { case NEW: _ctx.font = "90pt VT323"; _ctx.fillText("Helikeypter", leftMargin, 100); _ctx.font = "40pt VT323"; _ctx.fillText("Instructions:", leftMargin, 200); _ctx.font = "30pt VT323"; _ctx.fillText("Move left and right by moving up and down chromatic", leftMargin, 250); _ctx.fillText("scales. Start by pressing middle C.", leftMargin, 285); _ctx.fillText("Press the highest and lowest keys on your keyboard to", leftMargin, 335); _ctx.fillText("calibrate the game for your keyboard.", leftMargin, 370); if(_selectedKeyboard) { _ctx.fillText("Current keyboard: ", leftMargin, 420); _ctx.fillText(_selectedKeyboard.name, leftMargin+50, 455); _ctx.fillText((_topNote-_bottomNote+1)+" keys, " +noteNumberToName(_bottomNote)+"-"+noteNumberToName(_topNote), leftMargin+50, 490); } else { _ctx.fillText("No keyboard selected", leftMargin, 420); } break; case GAME: _ctx.font = "30pt VT323"; _ctx.fillText(noteNumberToName(_curNote), leftMargin, leftMargin); break; case OVER: _ctx.font = "90pt VT323"; _ctx.fillText("Game over!", leftMargin, 100); _ctx.font = "30pt VT323"; _ctx.fillText("Press middle C to restart.", leftMargin+10, 135); break; } _ctx.globalCompositeOperation = 'normal'; } function update(t) { if(_state == NEW && _obsts.length > Math.floor(_playerY/obstacleHeight)) { _projectedPos = _obsts[Math.floor(_playerY/obstacleHeight)].x; } dx = (_projectedPos - _playerX)*(t-_lastT)/250; _playerX += dx; if(isCollide() && _state == GAME) { _state = OVER; } mvObsts(); rmOldObsts(); fillObsts(); } function step(t) { // clear screen _ctx.clearRect(0, 0, _width, _height); _ctx.fillStyle = "#000"; _ctx.fillRect(0, 0, _width, _height); update(t); _ctx.beginPath(); drawPlayer(); drawObstacles(); drawText(); _lastT = t; requestAnimationFrame(step); } init();
$(document).ready(function(){ var date = new Date(); console.log(date) var dd = parseInt(String(date.getDate()).padStart(2, '0')); var mm = parseInt(String(date.getMonth() + 1).padStart(2, '0')); //January is 0! var yyyy = date.getFullYear(); photoOfDay(yyyy,mm,dd); function photoOfDay(yyyy,mm,dd){ $("#todayDate").text(mm+"-"+dd+"-"+yyyy) var api_key = "tEZcdcYgqv4qRNe0W8QrLu2ed5kywhjxxLWvofzI" var queryURL = "https://api.nasa.gov/planetary/apod?api_key="+api_key+"&date="+yyyy+"-"+mm+"-"+dd; $.ajax({ url: queryURL, method: "GET" }).then(function(response){ var photo = response.url; var title = response.title; console.log("Hell0",title) if(photo.includes("youtube")){ console.log("youtube") $("#photoSpot").hide("#photoHere") $('.video').show("#videoHere") $("#iframe").attr("src", photo) $("#photoTitle").text(title) } else{ $("#photoSpot").show("#photoHere") $("#photoTitle").text(title) $("#photoHere").css("background-image", 'url("' + photo +'")') $('.video').hide("#videoHere") } }) }; $("#leftbtn").click(function(){ console.log("left") if(dd===1){ dd = 30; mm = mm-1 }if(dd>1){ dd = dd-1; } if(mm === 1 && dd === 1){ mm = 12 yyyy = 2020 dd = 30 } console.log(dd) photoOfDay(yyyy,mm,dd) }) $("#rightbtn").click(function(){ var current = parseInt(String(date.getDate()).padStart(2, '0')); console.log("Current: ", current) console.log("Right Click: ", yyyy, mm, dd) if(dd >= 1&& dd!=current){ dd++ console.log("Next Day:", dd) console.log("Current: ", current) photoOfDay(yyyy,mm,dd) } if(dd === current){ dd = current; photoOfDay(yyyy,mm,dd) } if(dd === 30){ dd = 1 mm++ photoOfDay(yyyy,mm,dd) } }) })
import { getItem } from "utils"; const initialState = { page: 1, perPage: 15, photos: getItem(48), photo: null, editModal: false, errorModal: false, refetch: false, loader: false, numObjects: 0 }; const reducer = (state = initialState, action) => { switch (action.type) { case "UPLOAD_PHOTO": return { ...state, photo: action.photo, editModal: true }; case "SAVE_PHOTO": return { ...state, photos: [...action.photos, ...getItem(48)], loader: false, numObjects: action.numObjects }; case "TOGGLE_EDIT_MODAL": return { ...state, [action.modal]: !state[action.modal], ...action.action }; case "TOGGLE_REFETCH": return { ...state, refetch: !state.refetch, editModal: false }; case "TOGGLE_ERROR_MODAL": return { ...state, errorModal: !state.errorModal }; case "TOGGLE_LOADER": return { ...state, loader: !state.loader }; case "CHANGE_PAGE": return { ...state, page: action.page }; default: return state; } }; export { initialState, reducer };
/* app.js * Base component that implement the render() method and is responsible toload the HTML content. * @Author: Kailash Sharma * @Since: 28-Apr-2016 */ import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import { browserHistory } from 'react-router' import configureStore from './store/configureStore'; import createRoutes from './routes/index'; import { Provider } from 'react-redux'; //const history = useRouterHistory(createHashHistory)({ queryKey: false }); let reduxState; if (window.__REDUX_STATE__) { try { reduxState = JSON.parse(unescape(__REDUX_STATE__)); } catch (e) { } } const store = configureStore(reduxState); ReactDOM.render(( <Provider store={store}> { createRoutes(browserHistory ) } </Provider> ), document.getElementById('root'));
import {Text, TouchableOpacity, View, StyleSheet, Keyboard} from "react-native"; import React, {useEffect, useState} from "react"; export const AppButton = ({text = 'Начать', onPress, disabled, style={}}) => { const disabledStyle = disabled ? { backgroundColor: 'rgba(0, 0, 0, 0.1)' } : {} useEffect(() => { Keyboard.addListener("keyboardDidShow", _keyboardDidShow); Keyboard.addListener("keyboardDidHide", _keyboardDidHide); // cleanup function return () => { Keyboard.removeListener("keyboardDidShow", _keyboardDidShow); Keyboard.removeListener("keyboardDidHide", _keyboardDidHide); }; }, []); const [keyboardStatus, setKeyboardStatus] = useState(undefined); const _keyboardDidShow = () => setKeyboardStatus("Keyboard Shown"); const _keyboardDidHide = () => setKeyboardStatus("Keyboard Hidden"); return ( <> {keyboardStatus === 'Keyboard Shown' ? <></> : <TouchableOpacity activeOpacity={0.7} style={styles.buttonWrapper} onPress={onPress} disabled={disabled}> <View style={{...styles.buttonStart, ...disabledStyle, style }}> <Text style={styles.buttonText}>{text}</Text> </View> </TouchableOpacity> } </> ) }; const styles = StyleSheet.create({ buttonWrapper: { flexDirection: "column", width: "100%", height: 72 }, buttonStart: { borderRadius: 16, height: 72, width: "100%", flexDirection: "row", justifyContent: "center", alignItems: "center", backgroundColor: '#459F40' }, buttonText: { fontFamily: 'Inter-Bold', color: "#fff", fontWeight: "500", fontSize: 24, lineHeight: 28, } })
// var commandService = require("commandService"); // var componentService = require("componentService"); // // var columns = {}; // // var columnsFromServer = []; // // var isColumnSet = false; // // var notifications = []; // // var columnViewIsOpenned = false; // // commandService.on("allColumns", function(response) { // if (isColumnSet == false) { // isColumnSet = true; // columnsFromServer = response.body; // if (columnViewIsOpenned == true) { // showColumns(); // } // } // // }); // // commandService.on("msg", function(response) { // var body = response.body; // columns[body.column] = columns[body.column] || []; // columns[body.column].push(body.msg); // }); // // commandService.on("tokenInvalid", function(response) { // // notifications.push({errorMessage: "Token invalid for provider : "+response.body.providerName}); // // showNotificationSection(); // }); // // // // function showNotificationSection() { // // componentService.removeRowFromTableViewSection($.sectionNotifications.rowCount); // // for(var i=0; i<notifications.length; i++) { // // var row = componentService.createRowForColumn(notifications[i].errorMessage, i, notifications.length); // // $.sectionNotifications.add(row); // // } // // $.tableView.setData($.tableView.data); // // } // // function showColumns() { // for(var i=0; i<columnsFromServer.length; i++) { // var row = componentService.createRowForColumn(columnsFromServer[i].title, i, columnsFromServer.length); // $.sectionColumns.add(row); // columns[columnsFromServer[i].title] = columns[columnsFromServer[i].title] || []; // } // // $.tableView.setData($.tableView.data); // $.tableView.separatorColor = 'transparent'; // // $.tableView.addEventListener('click', function(e) { // Ti.API.debug("blabla"); // var columnTitle = e.row.children[0].text; // Ti.API.debug("test "+columnTitle); // var msg = columns[columnTitle]; // }); // } // // $.allColumns.addEventListener("open", function() { // columnViewIsOpenned = true; // showColumns(); // }); // // commandService.connectWithSkimbo(); // //
//sample variable as function var sumthem = function(x, y) { return x + y; }; console.log(sumthem(10,5));
Meteor.publish('images.byCategory', function(categoryId) { check(categoryId, String); return Images.find({ categoryId: categoryId }); });
module.exports = { "presets": [ [ "babel-preset-gatsby", ], ], "plugins": [ [ "babel-plugin-ttag", { "resolve": { "translations": process.env.LOCALE === "es" ? "es.po" : "default", }, }, ], ], }
import React, { Component } from 'react'; import API from '../../services/api'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faBackspace } from '@fortawesome/free-solid-svg-icons'; import { Link } from "react-router-dom"; export default class PedidoDetalhes extends Component { state = { pedido: {}, cliente: {}, produtos: [], } async componentDidMount() { const { id } = this.props.match.params; const response = await API.get(`pedido/buscar/${id}`); this.setState({ pedido: response.data }); this.setState({ cliente: response.data.cliente }); this.setState({ produtos: response.data.produto }); } render() { const { pedido, cliente, produtos } = this.state; return( <div className="container"> <br /><br /> <div className="row"> <div className="col-md-12"> <h4 className="center">DETALHES</h4> </div> </div> <br /><br /> <div className="row"> <div className="col-md-12"> <form> <div className="form-group row"> <label className="col-sm-3 col-form-label"><p className="textDetail">ID:</p></label> <div className="col-sm-9"> <input type="text" readOnly className="form-control-plaintext" id="staticEmail" value={pedido.id || ''} /> </div> </div> <div className="form-group row"> <label className="col-sm-3 col-form-label"><p className="textDetail">Cliente:</p></label> <div className="col-sm-9"> <input type="text" readOnly className="form-control-plaintext" id="staticEmail" value={cliente.nome || ''} /> </div> </div> {produtos.map(produto => ( <div key={produto.id} className="form-group row"> <label className="col-sm-3 col-form-label"><p className="textDetail">Nome Produto:</p></label> <div className="col-sm-9"> <input type="text" readOnly className="form-control-plaintext" id="staticEmail" value={produto.nome || ''} /> </div> <label className="col-sm-3 col-form-label"><p className="textDetail">Preço Produto:</p></label> <div className="col-sm-9"> <input type="text" readOnly className="form-control-plaintext" id="staticEmail" value={produto.preco || ''} /> </div> </div> ))} <div className="form-group row"> <label className="col-sm-3 col-form-label"><p className="textDetail">Data da compra:</p></label> <div className="col-sm-9"> <input type="text" readOnly className="form-control-plaintext" id="staticEmail" value={pedido.dataDaCompra || ''} /> </div> </div> <div className="form-group row"> <label className="col-sm-3 col-form-label"><p className="textDetail">Total da compra:</p></label> <div className="col-sm-9"> <input type="text" readOnly className="form-control-plaintext" id="staticEmail" value={pedido.totalDaCompra || ''} /> </div> </div> </form> <br /> <Link to="/pedido" className="btn btn-outline-dark btn-xs"><FontAwesomeIcon icon={faBackspace} /> Voltar</Link> </div> </div> <br /> <br /> <br /> </div> ); } }
var syllabus = { 19: { title: 'Unit 1 - Getting Started: Preview & Setup', lessons: { 48: '1.1 Welcome to MobileCSP', 69: '1.2 Mazes, Algorithms, and Programs', 49: '1.3 Google Account and Portfolio Set Up', 50: '1.4 App Inventor Setup', 70: '1.5 Blown to Bits (BB)', 126: '1.6 Successful Learning in Mobile CSP', 133: '1.7 Wrap Up' } }, 1: { title: 'Unit 2 - Introduction to Mobile Apps & Pair Programming', lessons: { 43: '2.1 Unit Overview', 45: '2.2 I Have a Dream Tutorial', 146: '2.3 The Internet and the Cloud', 56: '2.4 I Have a Dream, Part 2', 46: '2.5 Mobile Devices and Apps: Hardware and Software', 184: '2.6 Algorithm Basics (Revised)', 47: '2.7 I Have a Dream Projects', 61: '2.8 What is Abstraction', 63: '2.9 Binary Numbers', 156: '2.10 Hardware Abstractions: Logic Gates', 62: '2.11 BB: The Digital Explosion', 134: '2.12 Wrap Up' } }, 22: { title: 'Unit 3 - Creating Graphics & Images Bit by Bit', lessons: { 31: '3.1 Unit Overview', 150: '3.2 Paint Pot Tutorial', 34: '3.3 Representing Images', 151: '3.4 Paint Pot Projects', 164: '3.5 Paint Pot Refactoring and Documentation', 37: '3.6 Error Detection', 30: '3.7 Parity Error Checking', 101: '3.8 Map Tour Tutorial (REVISED)', 187: '3.9 Map Tour With GPS and TinyDB (NEW)', 143: '3.10 BB: Electronic Documents', 135: '3.11 Wrap Up', } }, 23: { title: 'Unit 4 - Exploring Computing: Animation, Simulation, & Modeling', lessons: { 54: '4.1 Unit Overview', 53: '4.2 Turn Off Lights Tutorial (REVISED)', 55: '4.3 Turn Off Lights Projects (REVISED)', 166: '4.4 Logo Part I (REVISED with AP pseudocode)', 64: '4.5 Coin Flip Simulation Tutorial (REVISED)', 68: '4.6 Coin Flip Experiment', 65: '4.7 Pseudo Random Numbers', 66: '4.8 Coin Flip Simulation Projects', 67: '4.9 Real World Models', 154: '4.10 Abstraction: Inside the CPU', 109: '4.11 BB: Privacy', 136: '4.12 Wrap Up', } }, 24: { title: 'Unit 5 - Algorithms & Procedural Abstraction', lessons: { 71: '5.1 Unit Overview', 167: '5.2 Logo Part 2', 161: '5.3 Search Algorithms', 76: '5.4 Sorting Algorithms', 173: '5.5 Caesar Cipher App (NEW)', 189: '5.6 Debugging Caesar Cipher (NEW)', 95: '5.7 Analyzing Algorithms', 162: '5.8 Limits of Algorithms', 98: '5.9 BB: Web Searches', 137: '5.10 Wrap Up', } }, 26: { title: 'Unit 6 - Using and Analyzing Data & Information', lessons: { 77: '6.1 Unit Overview', 80: '6.2 Quizz App (revised)', 82: '6.3 Quiz App Projects (revised)', 87: '6.4 Big Data', 159: '6.5 Clicker App With TinyWebDB (NEW)', 183: '6.6 Clicker App with Firebase (NEW)', 188: '6.7 Visualizing Data (revised)', 165: '6.8 Data Visualization Project', 81: '6.9 BB: Who Owns the Bits?', 138: '6.10 Wrap Up', } }, 25: { title: 'Unit 7 - Communication Through The Internet', lessons: { 116: '7.1 Overview', 99: '7.2 Internet: Basic Concepts and Terminology', 111: '7.3 Socially Aware App: Broadcast Hub Tutorial', 102: '7.4 Internet Architecture and Packet Switching', 190: '7.5 IP Addresses and Domain Names (NEW)', 122: '7.6 Cryptography Basics', 108: '7.7 Cryptography: Securing the Internet', 163: '7.8 BB: Cryptography and the Government', 139: '7.9 Wrap Up', } }, 127: { title: 'Unit 8 - AP CS Principles Exam Prep', lessons: { 129: '8.1 Unit Overview', 130: '8.2 About the AP CS Principles Exam', 181: '8.3 AP CSP Pseudocode', 185: '8.4 Tracing Pseudocode Exercises', 131: '8.5 Sample Exam Questions', 168: '8.6 The Mobile CS Principles Quiz App', 169: '8.7 Additional Resources', } }, 149: { title: 'Unit 9 - Beyond the AP CSP Exam', lessons: { 186: '9.1 Unit Overview', 78: '9.2 Magic 8 Ball Tutorial and Projects (Optional)', 153: '9.3 Persisting Photos Tutorial and Projects (Optional)', 103: '9.4 Where is North: A Compass App (Optional)', 105: '9.5 My Directions Tutorial (Options)', 96: '9.6 The Pong Game', 97: '9.7 Debugging Pong', 83: '9.8 Multiple Choice Quiz App: List of Lists (Optional)', 89: '9.9 Hello World Fusion Table App (Optional)', 110: '9.10 No Texting While Busy Tutorial (Optional)', 172: '9.11 Learn More about Programming & Careers', } }, 175: { title: 'Unit 10 - Additional Resources', lessons: { } }, 176: { title: 'Unit 11 - Archived Lessons', lessons: { } } }
// Move class function Move(round){ var self = this; // methods self.started = function(){ //console.log("move start"); //console.log(self); ANIMIX.activeMove = true; $( ui.grid ).on( "mousedown", ui.tile, { round: round }, tileMgr.validate ); }; // Move.started() self.ended = function(){ ANIMIX.activeMove = false; //logger.status("move ended!"); //if move is complete if ( ANIMIX.currDomNodes.length === 3 ){ // update stats statsMgr.updateOnCompleteMove( round ); floorMgr.addPartyAnimal( round ); // drop tiles above. drop new tiles from the top gridMgr.updateGrid( ANIMIX.currDomNodes ); } else { logger.status("Move not completed, not enough tiles"); } gridMgr.resetAfterMove(); }; // Move.ended() }; // Move()
import React, {useState} from 'react' import man from '../../assets/images/dashboard/user.png' import { Dropdown, DropdownToggle, DropdownMenu } from 'reactstrap'; import {Users,MessageSquare,FileText,Settings,LogOut} from 'react-feather' const UserActivity = () => { const [dropdownOpen, setDropdownOpen] = useState(false); const toggle = () => setDropdownOpen(prevState => !prevState); return( <Dropdown isOpen={dropdownOpen} toggle={toggle}> <DropdownToggle> <span className="media user-header"><img className="mr-2 rounded-circle img-35" src={man} style={{width:"35px",height:"35px"}} alt=""/> <span className="media-body"> <span className="f-12 f-w-600">Elana Saint</span> <span className="d-block">Admin</span></span></span> </DropdownToggle> <DropdownMenu className="p-0"> <ul className="profile-dropdown"> <li className="gradient-primary-1"> <h6 className="mb-0">Elana Saint</h6><span>Web Designer</span> </li> <li><Users/>Profile</li> <li><MessageSquare/>Inbox</li> <li><FileText/>Taskboard</li> <li><Settings/>Settings</li> <li><LogOut/>Logout</li> </ul> </DropdownMenu> </Dropdown> ) } export default UserActivity
/** * Created by nnnyyy on 2018-11-21. */ 'use strict'; import P from '../common/protocol'; class Global { constructor() { this.vBus = new Vue(); } connectSocket() { console.log('socket connecting...'); this.socket = io(); this.initSocketListener(); } initSocketListener() { const g = this; this.socket.on(P.SOCK.QuizData, function(packet) { g.onQuizData(packet); }); this.socket.on(P.SOCK.QuizDataResult, function(packet) { g.onQuizDataResult(packet); }); this.socket.on(P.SOCK.AlertMsg, function(packet) { g.onAlertMsg(packet); }); this.socket.on(P.SOCK.ComboInfo, function(packet) { g.onComboInfo(packet); }); this.socket.on(P.SOCK.QuizAnswerCnt, function(packet) { g.onQuizAnswerCnt(packet); }); this.socket.on(P.SOCK.CurrentComboRank, function(packet) { g.onCurrentComboRank(packet); }); this.socket.on(P.SOCK.AnswerFirstSelectUser, function(packet) { g.onAnswerFirstSelectUser(packet); }); this.socket.on(P.SOCK.QuizRecordRank, function(packet) { g.onQuizRecordRank(packet); }); } isMobile() { if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) { // is mobile.. return true; } return false; } emit(protocol, data) { this.vBus.$bus.$emit(protocol, data); } on( protocol, cb ) { this.vBus.$bus.$on(protocol, cb); } hget( addr, cb ) { this.vBus.$http.get(addr).then(res => cb(res.data)) .catch(err => console.log(err)); } hpost( addr, item, cb ) { this.vBus.$http.post(addr, item).then(res => cb(res.data)) .catch(err => console.log(err)); } sendPacket( protocol, packetData ) { this.socket.emit(protocol, packetData); } setQuizInfo() { const info = {q: "테스트 문제입니다", a: [ "테스트1", "테스트2", "테스트3" ]}; this.vBus.$bus.$emit("QuizInfo", JSON.stringify(info)); this.vBus.$bus.$emit(P.StartTimer, 10000); } onQuizData( packet ) { this.vBus.$bus.$emit(P.SOCK.QuizData, JSON.stringify( packet )); if( packet.state == 0 ) { this.vBus.$bus.$emit(P.StartTimer, { remain: packet.tRemain, max: 10000 }); } } onQuizDataResult( packet ) { this.vBus.$bus.$emit(P.SOCK.QuizDataResult, JSON.stringify( packet )); } onAlertMsg( packet ) { this.vBus.$bus.$emit(P.SetAlertMsg, packet.msg); } onComboInfo( packet ) { this.showComboAlert( packet.cnt ); this.vBus.$bus.$emit(P.SOCK.ComboInfo, packet); } onQuizAnswerCnt( packet ) { this.vBus.$bus.$emit(P.SOCK.QuizAnswerCnt, packet); } onCurrentComboRank( packet ) { this.vBus.$bus.$emit(P.SOCK.CurrentComboRank, packet); } onAnswerFirstSelectUser( packet ) { const msg = packet.nick + '님이 제일 먼저 선택했습니다'; this.vBus.$bus.$emit(P.SetAlertMsg, msg); } onQuizRecordRank( packet ) { this.vBus.$bus.$emit(P.SOCK.QuizRecordRank, packet); } showComboAlert( cnt ) { if( cnt < 2 ) return; if( cnt == 5 ) { this.vBus.$bus.$emit(P.OpenGachaBox, {name: '놀라셨죠? 아직 테스트 중이라 뭐 없어요~ㅋㅋ'}); } let msg = cnt + " 콤보!"; if( cnt >= 10 && cnt % 5 == 0 ) { msg += ' 대단합니다!'; } this.vBus.$bus.$emit(P.SetAlertMsg, msg); } } const GlobalObject = new Global(); export default GlobalObject
import { createStore, applyMiddleware, compose, combineReducers } from 'redux' import { connectRoutes } from 'redux-first-router' import reduxThunk from 'redux-thunk' // import persistState from 'redux-localstorage' import routesMap from './routes' import options from './options' import * as reducers from './reducers' import * as actionCreators from './actions' export default history => { const { reducer, middleware, enhancer } = connectRoutes( history, routesMap, options ) const rootReducer = combineReducers({ ...reducers, location: reducer }) const middlewares = applyMiddleware(middleware) const REDUX_THUNK = applyMiddleware(reduxThunk) const enhancers = compose( enhancer, middlewares, REDUX_THUNK ) const initialClientState = {} const preLoadedState = { ...initialClientState } const store = createStore(rootReducer, preLoadedState, enhancers) if (module.hot && process.env.NODE_ENV === 'development') { module.hot.accept('./reducers', () => { const reducers = require('./reducers') // eslint-disable-line global-require const rootReducer = combineReducers({ ...reducers, location: reducer }) store.replaceReducer(rootReducer) }) } return store }
// react-bootstrap components import React, { useEffect, useState } from "react"; import { Form } from "react-bootstrap"; import NotificationAlert from "react-notification-alert"; import axios from "axios"; import SERVER from "../globals"; import { Badge, Button, Card, Navbar, Nav, Container, Row, Col, } from "react-bootstrap"; import Meta from "Meta/Meta"; function Icons({history,location}) { const [name,setName]=useState(""); const [email,setEmail]=useState(""); const [cc,setCC]=useState("") const useremail=localStorage.getItem("email"); const submitHandler = (e) => { e.preventDefault(); const user = JSON.parse(localStorage.getItem("response")); const token=user.data.token const useremail = user.data.user.email; const datatosend={ name, email, cc, } console.log(datatosend) console.log(cc) const id = user.data.user._id; console.log(token) axios.post(`${SERVER}/api/sendmail/${id}` ,datatosend).then(notify("tc",`Email sent to ${email} CC:${cc}`)) } const notificationAlertRef = React.useRef(null); const notify = (place,message) => { var color = Math.floor(Math.random() * 5 + 1); var type; var message; switch (color) { case 1: type = "success"; break; case 2: type = "danger"; break; case 4: type = "warning"; break; case 5: type = "info"; break; default: break; } var options = {}; options = { place: place, message: message, type: type, icon: "nc-icon nc-bell-55", autoDismiss: 7, }; notificationAlertRef.current.notificationAlert(options); }; const isLoggedIn = () => { return localStorage.getItem("response") ? true : false; }; const redirect = location.search ? location.search.split("=")[1] : "/login"; useEffect(() => { if (!isLoggedIn()) { history.push(redirect); } }, []); return ( <> <Meta></Meta> <div className="rna-container"> <NotificationAlert ref={notificationAlertRef} /> </div> <Container fluid> <Row> <Col xs={12} md={6}> <h3>Send Email</h3> <Form onSubmit={ submitHandler }> <Form.Group controlId="name"> <Form.Label>Name</Form.Label> <Form.Control type="name" placeholder="Enter Name" name="name" value={name} onChange={(e)=>setName(e.target.value)} ></Form.Control> </Form.Group> <Form.Group controlId="name"> <Form.Label>Email</Form.Label> <Form.Control type="name" placeholder="Enter Email" value={email} name="email" onChange={(e)=>setEmail(e.target.value)} ></Form.Control> </Form.Group> <Form.Group controlId="name"> <Form.Label>CC</Form.Label> <Form.Control type="cc" placeholder="Enter CC" value={cc} name="cc" onChange={(e)=>setCC(e.target.value)} ></Form.Control> </Form.Group> <Button type="submit" variant="primary"> Send Mail </Button> </Form> </Col> </Row> </Container> </> ); } export default Icons;
import React, { Component } from 'react'; import classnames from 'classnames'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import { Card, CardHeader, IconButton, CardContent, Typography, Grid, Collapse } from '@material-ui/core'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import CheckMark from '@material-ui/icons/CheckCircle'; import RemoveCircle from '@material-ui/icons/RemoveCircle'; const styles = theme => ({ card: { width: '100%', gridColumn: '1 / span 5', boxShadow: 'none', borderRadius: 0, }, expand: { transform: 'rotate(0deg)', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shortest, }), }, expandOpen: { transform: 'rotate(180deg)', }, pricing: { padding: "8px 0", }, bgdark: { backgroundColor: '#d6d6d6', }, bglight: { backgroundColor: '#eeeeee', marginBottom: '0px !important' }, cardHead: { padding: '0 0 0 16px', marginBottom: 2, '&:last-child':{ padding: '0 0 0 16px', } }, cardBody:{ backgroundColor: 'white', padding: 0, '&:last-child': { padding: 0, } }, cardRow: { width: '100%', display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', alignItems: 'center', justifyItems: 'center', borderBottom: '1px solid #d7dce0', }, start: { alignSelf: 'start', paddingLeft: '16px', lineHeight: 2.5 }, gi: { borderLeft: '1px solid #d7dce0', width: '100%', height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', "&:first-child": { borderLeft: 'none' } } }) class TableRow extends Component { state = { expanded: false, } handleExpandClick = () => { this.setState(state => ({ expanded: !state.expanded })); } render() { const { classes, title, content, monthly } = this.props; const priceDisplay = monthly ? "monthly": "yearly"; const displayContent = content.map( (row,index) => { const rowHeadkey = Object.keys(row)[0]; const rowHead = rowHeadkey.split('_').join(" "); return ( <div className={classes.cardRow} key={index}> {(title !== 'Pricing') ? ( <React.Fragment> <div className={classes.gi}> <Typography className={classes.start} variant="body1">{rowHead}</Typography> </div> <div className={classes.gi}> {row[rowHeadkey].practice_dashboard ? <CheckMark color="secondary" /> : <RemoveCircle nativeColor="#e01f20" />} </div> <div className={classes.gi}> {row[rowHeadkey].true_paperless ? <CheckMark color="secondary" /> : <RemoveCircle nativeColor="#e01f20" />} </div> <div className={classes.gi}> {row[rowHeadkey].patient_engagement ? <CheckMark color="secondary" /> : <RemoveCircle nativeColor="#e01f20" />} </div> <div className={classes.gi}> {row[rowHeadkey].the_works ? <CheckMark color="secondary" /> : <RemoveCircle nativeColor="#e01f20" />} </div> </React.Fragment> ) : ( <React.Fragment> <div className={classes.gi} id={rowHead === "Plan Cost" ? "scrollEl" : ""}> <Typography className={classes.start} variant="body1">{rowHead}</Typography> </div> <div className={classes.gi}> <Typography variant="body1">${rowHead === "Plan Cost" ? row[rowHeadkey].practice_dashboard[priceDisplay] : row[rowHeadkey].practice_dashboard}</Typography> </div> <div className={classes.gi}> <Typography variant="body1">${rowHead === "Plan Cost" ? row[rowHeadkey].true_paperless[priceDisplay] : row[rowHeadkey].true_paperless}</Typography> </div> <div className={classes.gi}> <Typography variant="body1">${rowHead === "Plan Cost" ? row[rowHeadkey].patient_engagement[priceDisplay] : row[rowHeadkey].patient_engagement}</Typography> </div> <div className={classes.gi}> <Typography variant="body1">${rowHead === "Plan Cost" ? row[rowHeadkey].the_works[priceDisplay] : row[rowHeadkey].the_works}</Typography> </div> </React.Fragment> ) } </div> ) }) return ( <Card className={classes.card}> <CardContent className={`${title === "Pricing" ? classes.bglight : classes.bgdark} ${classes.cardHead}`}> <Grid container justify='flex-start' alignItems='center' > { title === 'Pricing' ?( <Typography variant="h6" className={classes.pricing}>{title}</Typography> ):( <React.Fragment> <Typography variant="h6">{title}</Typography> <IconButton className={classnames(classes.expand, { [classes.expandOpen]: this.state.expanded, })} onClick={this.handleExpandClick} aria-expanded={this.state.expanded} aria-label="Show more" > <ExpandMoreIcon color="primary" /> </IconButton> </React.Fragment> )} </Grid> </CardContent> <Collapse in={title === 'Pricing' ? true : this.state.expanded } timeout="auto" unmountOnExit> <CardContent className={classes.cardBody}> {displayContent} </CardContent> </Collapse> {title === 'Pricing' && ( <CardContent className={`${classes.cardHead} ${classes.bglight}`} // style={{marginBottom: 0}} > <Grid container justify='flex-start' alignItems='center' > <Typography variant="h6" className={classes.pricing} >Features</Typography> </Grid> </CardContent> )} </Card> ) } } export default withStyles(styles, { withTheme: true })(TableRow)
//------------------------------------------------------------------------------------------------------------ // // MatrixEngine Core Program // build number 1.0.20130523 // //------------------------------------------------------------------------------------------------------------ var MxeProject = function() { this.contentsFile = null; this.contentsClass = null; this.controllerFile = null; this.controllerClass = null; this.requiredFiles = []; }; var MxePlayer = function() { this.initialize.apply(this, arguments); }; MxePlayer.prototype.initialize = function(canvas) { this.options = { imageSync: false, imageBulkLoad: true, controllFPS: true, normalizeTouchID: false, enableRuntimeIK: true, }; this.project = null; this.canvas = canvas; /* test context lost this.canvas = WebGLDebugUtils.makeLostContextSimulatingCanvas(this.canvas); setTimeout(function(){ canvas.loseContextInNCalls(5); }, 10000); */ this.touchIDNormalizer = new MxeTouchIDNormalizer(this); this.touchObjects = {length:0}; this.onClickListenerCount = 0; this.contents = null; this.fpsElement = null; this.waitingImages = false; this.frameCount = 0; this.lastUpdate = 0.0; this.startTime = 0.0; this.glContextValid = false; this.render = new MxeRender(this); this.isSmartPhone = MxeUtil.detectSmartPhone(); this.pauseStatus = 0; //0:none 1:request 2:paused var player = this; this.canvas.addEventListener( 'touchstart', function(e) { //------------------------------------------------- e.preventDefault(); if(player.options.normalizeTouchID){ player.touchIDNormalizer.onTouchStart(e); } for(var i=0; i<e.changedTouches.length; i++){ var id = e.changedTouches[i].identifier; if(player.options.normalizeTouchID){ id = player.touchIDNormalizer.normalize(id); } var touch = e.changedTouches[i]; var sf = player.getCanvasScaleFactor(); var mouseX = touch.pageX * sf; var mouseY = touch.pageY * sf; //------------------------------------------------- player.onMouseDownHandler(mouseX, mouseY, id, e.touches.length, e); } }, false); var touchEndAndCancelListener = function(e){ e.preventDefault(); for(var i=0; i<e.changedTouches.length; i++){ var id = e.changedTouches[i].identifier; if(player.options.normalizeTouchID){ id = player.touchIDNormalizer.normalize(id); } var touchObject = player.getTouchObject(0); player.onMouseUpHandler(touchObject.mouseX, touchObject.mouseY, id, e.touches.length, e); player.deleteTouchObject(id); } if(player.options.normalizeTouchID){ player.touchIDNormalizer.onTouchEnd(e); } }; this.canvas.addEventListener( 'touchend', touchEndAndCancelListener, false); this.canvas.addEventListener( 'touchcancel', touchEndAndCancelListener, false); this.canvas.addEventListener( 'touchmove', function(e) { e.preventDefault(); for(var i=0; i<e.changedTouches.length; i++){ var id = e.changedTouches[i].identifier; if(player.options.normalizeTouchID){ id = player.touchIDNormalizer.normalize(id); } var touch = e.changedTouches[i]; var sf = player.getCanvasScaleFactor(); var mouseX = touch.pageX * sf; var mouseY = touch.pageY * sf; player.onMouseMoveHandler(mouseX, mouseY, id, e.touches.length, e); } }, false); this.canvas.addEventListener( 'mousedown', function(e) { //------------------------------------------------- var rect = e.target.getBoundingClientRect(); var sf = player.getCanvasScaleFactor(); var mouseX = (e.clientX - rect.left) * sf; var mouseY = (e.clientY - rect.top) * sf; //------------------------------------------------- player.onMouseDownHandler(mouseX, mouseY, 0, 1, e); }, false); var mouseUpListener = function(e) { //------------------------------------------------- var rect = e.target.getBoundingClientRect(); var sf = player.getCanvasScaleFactor(); var mouseX = (e.clientX - rect.left) * sf; var mouseY = (e.clientY - rect.top) * sf; //------------------------------------------------- player.onMouseUpHandler(mouseX, mouseY, 0, 1, e); }; this.canvas.addEventListener( 'mouseup', mouseUpListener, false); this.canvas.addEventListener( 'mouseout', function(e) { var touchObject = player.getTouchObject(0); if(touchObject.mouseStatus === 1) mouseUpListener(e); }, false); this.canvas.addEventListener( 'mousemove', function(e) { //------------------------------------------------- var rect = e.target.getBoundingClientRect(); var sf = player.getCanvasScaleFactor(); var mouseX = (e.clientX - rect.left) * sf; var mouseY = (e.clientY - rect.top) * sf; //------------------------------------------------- player.onMouseMoveHandler(mouseX, mouseY, 0, 1, e); }, false); this.canvas.addEventListener( 'webglcontextlost', function(e) { e.preventDefault(); player.glContextValid = false; }, false); this.canvas.addEventListener( 'webglcontextrestored', function(e) { MxeUtil.log("gl context restored."); e.preventDefault(); player.initGL(); //player.animationFrame(player)(); player.update(); }, false); }; MxePlayer.prototype.createTouchObject = function(id) { var to = this.touchObjects[id] = { mouseStatus: 0, //1:down mouseX: 0, mouseY: 0, tagObject: {}, }; ++this.touchObjects.length; return to; }; MxePlayer.prototype.deleteTouchObject = function(id) { delete this.touchObjects[id]; --this.touchObjects.length; //TODO check length===touches.length }; MxePlayer.prototype.getTouchObject = function(id) { var to = this.touchObjects[id]; if(to) return to; return this.createTouchObject(id); }; MxePlayer.prototype.getTouchTag = function(id) { if(! this.touchObjects[id]) return null; return this.touchObjects[id].tagObject; }; MxePlayer.prototype.initGL = function() { var i, j; this.glContextValid = this.render.initGL(); if(! this.glContextValid) return; var castArray = [ this.contents.modelCasts, this.contents.textureCasts, this.contents.bitmapCasts, this.contents.textCasts, this.contents.movieCasts, this.contents.shaderCasts, ]; var casts; for(i=0; i<castArray.length; i++){ casts = castArray[i]; for(j=0; j<casts.length; j++){ if(casts[j] == null) continue; casts[j].initGL(this.render.gl); } } }; MxePlayer.loadScriptQueue = []; MxePlayer.registerContentsClass = function(contentsClass){ var req = MxePlayer.loadScriptQueue[0]; if(req) req.contentsClass = contentsClass; }; MxePlayer.registerControllerClass = function(controllerClass){ var req = MxePlayer.loadScriptQueue[0]; if(req) req.controllerClass = controllerClass; }; //for sequencial load MxePlayer.loadScript = function(path, callback) { var item = document.getElementsByTagName('head').item(0); var loadExec = function(path_, onload_, onerror_){ var script = document.createElement('script'); script.src = path_; script.type = 'text/javascript'; script.defer = true; script.onload = onload_; script.onerror = onerror_; item.appendChild(script); }; var onError = function() { var req = MxePlayer.loadScriptQueue[0]; var msg = "can't load script "; if(req) msg = msg + "'" + req.path + "'."; else msg = msg + "'(unknown)'."; throw new MxeException("loadscript", msg); }; var onLoad = function() { var result = MxePlayer.loadScriptQueue.shift(); if(result.callback) result.callback(result); if(MxePlayer.loadScriptQueue.length > 0) loadNext(); }; var loadNext = function(){ var req = MxePlayer.loadScriptQueue[0]; loadExec(req.path, onLoad, onError); }; MxePlayer.loadScriptQueue.push({ path: path, callback: callback }); if(MxePlayer.loadScriptQueue.length === 1) loadNext(); } MxePlayer.prototype.loadProject = function() { var loadCounter = 0; var requiredCounter = 0; var player = this; if(this.project.requiredFiles) requiredCounter+= this.project.requiredFiles.length; if(! this.project.contentsClass){ if(window.MxeDefaultContents){ this.project.contentsClass = window.MxeDefaultContents; //for legacy }else{ if(! this.project.contentsFile){ this.project.contentsFile = "js/matrixengine-contents.js"; //default } requiredCounter++; } } if(! this.project.controllerClass){ if(this.project.controllerFile){ requiredCounter++; } } var onLoad = function(result) { if(result.contentsClass){ player.project.contentsClass = result.contentsClass; } if(result.controllerClass){ player.project.controllerClass = result.controllerClass; } loadCounter++; if(loadCounter === requiredCounter) player.startPlay(); }; if(requiredCounter === 0){ player.startPlay(); return; } for(var i=0; i<this.project.requiredFiles.length; i++){ MxePlayer.loadScript(this.project.requiredFiles[i], onLoad); } if(this.project.contentsFile) MxePlayer.loadScript(this.project.contentsFile, onLoad); if(this.project.controllerFile) MxePlayer.loadScript(this.project.controllerFile, onLoad); }; MxePlayer.prototype.setProject = function(project) { if(this.project !== null){ //TODO project jump //error MxeUtil.log("ERROR: player already has a project."); return; } this.project = project; /* if(this.contents !== null){ //TODO project jump //error MxeUtil.log("ERROR: player already has a project."); return; } var contentsClass = project.contentsClass; if(contentsClass === null){ contentsClass = MxeDefaultContents; } this.contents = new contentsClass(this); if(project.controllerClass !== null){ this.contents.controller = new project.controllerClass(this.contents); } */ }; MxePlayer.prototype.startPlay = function() { this.contents = new this.project.contentsClass(this); if(this.project.controllerClass !== null){ this.contents.controller = new this.project.controllerClass(this.contents); } this.initGL(); if(this.options.imageBulkLoad) this.contents.loadAllImages(); this.update(); }; MxePlayer.prototype.start = function() { this.loadProject(); }; MxePlayer.prototype.update = function(){ if(this.options.imageSync && this.contents.countLoadingImages() > 0){ this.loadingFrame(this)(); return; } this.animationFrame(this)(); }; MxePlayer.prototype.pause = function(){ if(this.pauseStatus === 0){ this.pauseStatus = 1; //request pause } }; MxePlayer.prototype.resume = function(){ if(this.pauseStatus === 2 || this.pauseStatus === 1){ //paused or request pause this.pauseStatus = 0; this.update(); } }; MxePlayer.prototype.makeFrame = function() { var i; var scoreLength = this.contents.scores.length; for(var i=0; i<scoreLength; i++) this.contents.scores[i].makeFrame(-1); }; MxePlayer.prototype.prepareRender = function() { this.render.render3D.currentCameraTrack = null; this.render.render3D.clearLightList(); this.render.render3D.clearRenderList(); this.render.render2D.clearRenderList(); var i; var scoreLength = this.contents.scores.length; //depth-first search this.contents.scores[0].prepareRender(this.render, this.options.enableRuntimeIK); this.render.prepare(); for(var i=0; i<scoreLength; i++) this.contents.scores[i].applyCamera(this.render.render3D.viewMatrix); }; MxePlayer.prototype.enterFrame = function() { var me = new MxeEvent(null); var score; for(var i=0; i<this.contents.scores.length; i++){ score = this.contents.scores[i]; score.onEnterFrameHandler(me); } }; MxePlayer.prototype.exitFrame = function() { this.render.validSelectionBuffer = false; var score; var me = new MxeEvent(null); for(var i=0; i<this.contents.scores.length; i++){ score = this.contents.scores[i]; score.onExitFrameHandler(me); } }; MxePlayer.prototype.drawScene = function() { this.render.drawScene(MxeRender.def.RM_DEFAULT); }; MxePlayer.prototype.loadingFrame = function(player) { return function(){ if(player.pauseStatus === 1 || player.pauseStatus === 2){ //request pause or paused player.pauseStatus = 2; return; } if(player.options.imageSync && player.contents.countLoadingImages() > 0){ requestAnimFrame(player.loadingFrame(player)); }else{ requestAnimFrame(player.animationFrame(player)); } }; } MxePlayer.prototype.animationFrame = function(player) { return function(){ if(player.glContextValid){ player.mainTask(); if(player.pauseStatus === 1 || player.pauseStatus === 2){ //request pause or paused player.pauseStatus = 2; return; } requestAnimFrame(player.animationFrame(player)); //var loopInterval = setTimeout(player.animationFrame(player), // 1000 / 30.0); } }; }; MxePlayer.prototype.updateViewport = function(){ this.render.updateViewport(); }; MxePlayer.prototype.checkTime = function() { var result = false; if(this.frameCount === 0){ result = true; this.startTime = this.lastUpdate = (new Date()).getTime(); }else{ var now = (new Date()).getTime(); var past = now - this.lastUpdate; var frameTime = 0.0; if(this.options.controllFPS) frameTime = 1000.0/this.contents.frameRate; var diff = frameTime - past; if(diff <= 0){ result = true; this.lastUpdate = now + Math.max(diff, -frameTime); this.updateFPS(now); } } return result; }; MxePlayer.prototype.getTime = function() { return this.lastUpdate-this.startTime; }; MxePlayer.prototype.mainTask = function() { if(! this.checkTime()) return; if(! this.waitingImages){ this.updateViewport(); this.makeFrame(); this.enterFrame(); this.prepareRender(); } if(this.options.imageSync && this.contents.countLoadingImages() > 0){ this.waitingImages = true; return; } this.waitingImages = false; this.drawScene(); this.exitFrame(); this.frameCount++; }; MxePlayer.prototype.getCanvasScaleFactor = function (){ return this.canvas.width/this.canvas.clientWidth; }; MxePlayer.prototype.onMouseDownHandler = function(mouseX, mouseY, id, touchCount, e) { /* test context lost //this.canvas.loseContext(); this.canvas.setRestoreTimeout(5000); // recover in 5 seconds */ if(this.contents === null) return; if(this.onClickListenerCount > 0){ var selectionID = this.render.getSelectionID(mouseX, mouseY); var renderItem = this.render.getRenderItemBySelectionID(selectionID); if(renderItem === null){ //no object or error }else{ /* MxeUtil.log("-------"); MxeUtil.log('('+mouseX+','+mouseY+')'+pix[0]+','+pix[1]+','+pix[2]+','+pix[3]); MxeUtil.log("selectionID="+selectionID); MxeUtil.log("sector="+renderItem[1].index); MxeUtil.log("track="+renderItem[2].index); */ var me; var track; if(renderItem[0] === 0){ //CT_MODEL track = renderItem[2][0]; if(track.boneInfo !== null) track = track.boneInfo.modelTrack; me = new MxeEvent(e); me.sector = renderItem[1]; me.x = mouseX; me.y = mouseY; track.onClickHandler(me); }else if(renderItem[0] === 1){ //CT_TEXTURE(billboard) track = renderItem[1]; me = new MxeEvent(e); me.x = mouseX; me.y = mouseY; track.onClickHandler(me); }else if(renderItem[0] === 2 || renderItem[0] === 3 || renderItem[0] === 29){ //CT_BITMAP, CT_TEXT, CT_PROCEDURAL track = renderItem[1]; me = new MxeEvent(e); me.x = mouseX; me.y = mouseY; track.onClickHandler(me); }else{ //not support } } } var touchObject = this.getTouchObject(id); touchObject.mouseStatus = 1; touchObject.mouseX = mouseX; touchObject.mouseY = mouseY; var mouseDownEvent = new MxeEvent(e); mouseDownEvent.x = mouseX; mouseDownEvent.y = mouseY; mouseDownEvent.touchID = id; mouseDownEvent.touchTag = touchObject.tagObject; mouseDownEvent.touchCount = touchCount; for(var i=0; i<this.contents.scores.length; i++){ this.contents.scores[i].onMouseDownHandler(mouseDownEvent); } }; MxePlayer.prototype.onMouseUpHandler = function(mouseX, mouseY, id, touchCount, e) { if(this.contents === null) return; var mouseUpEvent = new MxeEvent(e); var touchObject = this.getTouchObject(id); mouseUpEvent.x = mouseX; mouseUpEvent.y = mouseY; mouseUpEvent.touchID = id; mouseUpEvent.touchTag = touchObject.tagObject; mouseUpEvent.touchCount = touchCount; touchObject.mouseStatus = 0; for(var i=0; i<this.contents.scores.length; i++){ this.contents.scores[i].onMouseUpHandler(mouseUpEvent); } }; MxePlayer.prototype.onMouseMoveHandler = function(mouseX, mouseY, id, touchCount, e) { if(this.contents === null) return; var mouseMoveEvent = new MxeEvent(e); var touchObject = this.getTouchObject(id); mouseMoveEvent.x = mouseX; mouseMoveEvent.y = mouseY; mouseMoveEvent.touchID = id; mouseMoveEvent.touchTag = touchObject.tagObject; mouseMoveEvent.touchCount = touchCount; touchObject.mouseX = mouseX; touchObject.mouseY = mouseY; for(var i=0; i<this.contents.scores.length; i++){ this.contents.scores[i].onMouseMoveHandler(mouseMoveEvent); } }; MxePlayer.prototype.addEventListener = function(eventType, listener, userObj) { var func = this.addEventListenerFuncs[eventType]; if(func === undefined) return false; func.apply(this, [listener, userObj]); return true; }; MxePlayer.prototype.addOnMouseDownListener = function(listener, userObj) { if(this.onMouseDownListeners === null){ this.onMouseDownListeners = new Array(); } this.onMouseDownListeners.push([listener, userObj]); }; MxePlayer.prototype.addOnMouseUpListener = function(listener, userObj) { if(this.onMouseUpListeners === null){ this.onMouseUpListeners = new Array(); } this.onMouseUpListeners.push([listener, userObj]); }; MxePlayer.prototype.addOnMouseMoveListener = function(listener, userObj) { if(this.onMouseMoveListeners === null){ this.onMouseMoveListeners = new Array(); } this.onMouseMoveListeners.push([listener, userObj]); }; MxePlayer.prototype.showFPS = function() { if(this.fpsElement !== null) return; this.fpsElement = document.createElement('span'); //this.fpsElement.id = "id"; this.fpsElement.innerHTML = "FPS:00.00"; this.fpsElement.style.backgroundColor = '#000088'; this.fpsElement.style.color = '#ccccdc'; this.fpsElement.style.position = "absolute"; this.fpsElement.style.top = this.canvas.offsetTop; this.fpsElement.style.left = this.canvas.offsetLeft; this.fpsElement.style.zIndex = 0; var parent = this.canvas.offsetParent; //var parent = document.getElementsByTagName("body").item(0); parent.appendChild(this.fpsElement); this.fpsElement.fpsAvrTime = 0.0; this.fpsElement.fpsPreTime = (new Date()).getTime(); this.fpsElement.fpsUpdateCounter = 0; }; MxePlayer.prototype.hideFPS = function() { if(this.fpsElement === null) return; var parent = this.canvas.offsetParent; parent.removeChild(this.fpsElement); this.fpsElement = null; }; MxePlayer.prototype.updateFPS = function(nowTime) { if(this.fpsElement === null) return; var diffTime = nowTime - this.fpsElement.fpsPreTime; this.fpsElement.fpsAvrTime = this.fpsElement.fpsAvrTime*0.9 + diffTime*0.1; this.fpsElement.fpsPreTime = nowTime; if(this.fpsElement.fpsUpdateCounter === 30){ this.fpsElement.fpsUpdateCounter = 0; var fps = 0.0; if(this.fpsElement.fpsAvrTime > 0.0){ fps = 1000/this.fpsElement.fpsAvrTime; fps = Math.round(fps*100)/100; } this.fpsElement.innerHTML = "FPS:"+fps; } this.fpsElement.fpsUpdateCounter++; }; //TODO remove listener var MxeCast = function () { this.initialize.apply(this, arguments); }; MxeCast.prototype.initialize = function(contents, index, label) { this.contents = contents; this.index = index; this.label = label; this.tag = 0; this.castType = -1; }; MxeCast.def = { // cast type ID CT_MODEL : 0, CT_TEXTURE : 1, CT_BITMAP : 2, CT_TEXT : 3, CT_WAVE : 4, CT_MIDI : 5, CT_SCRIPT : 6, CT_CAMERA : 7, CT_LIGHT : 8, CT_AVI : 9, CT_LINK : 10, CT_3DSOUND : 11, CT_WAVEEX : 12, CT_LISTENER : 13, CT_AVICTRL : 14, CT_MATERIAL : 15, CT_AVIBILL : 16, CT_BILTEXANM : 17, CT_TEXNUMANM : 18, CT_MODELWRAP : 19, CT_MODELNUM : 20, CT_TRANSFORM : 21, CT_LOOPTRACK : 22, CT_FREEBITMAP : 23, CT_SHADER : 24, CT_BMPBILL : 25, CT_PARTICLE : 26, CT_RESOURCE : 27, CT_METACAST : 28, CT_PROCEDURAL : 29, CT_PROCEDURAL3D: 30, }; MxeCast.prototype.prepareRender = function(render, frame) { }; var MxeContents = function() { this.initialize.apply(this, arguments); }; MxeContents.prototype.initialize = function() { this.player = null; this.controller = null; this.backgroundColor = null; this.modelCasts = null; this.modelCastsL = null; this.cameraCasts = null; this.cameraCastsL = null; this.textureCasts = null; this.textureCastsL = null; this.bitmapCasts = null; this.bitmapCastsL = null; this.textCasts = null; this.textCastsL = null; this.proceduralCasts = null; this.proceduralCastsL = null; this.movieCasts = null; this.movidCastsL = null; this.shaderCasts = null; this.shaderCastsL = null; this.scores = null; this.scoresL = null; //contents properties this.frameRate = 0.0; this.presetWidth = 0; this.presetHeight = 0; }; MxeContents.prototype.loadAllImages = function() { var i; var cast; for(i=0; i<this.textureCasts.length; i++){ cast = this.textureCasts[i]; if(cast == null) continue; cast.prepare(); } for(i=0; i<this.bitmapCasts.length; i++){ cast = this.bitmapCasts[i]; if(cast == null) continue; cast.prepare(); } }; MxeContents.prototype.countLoadingImages = function() { var i; var result = 0; var cast; for(i=0; i<this.textureCasts.length; i++){ cast = this.textureCasts[i]; if(cast == null) continue; if(cast.prepareStatus === 1) result++; //preparing now } for(i=0; i<this.bitmapCasts.length; i++){ cast = this.bitmapCasts[i]; if(cast == null) continue; if(cast.prepareStatus === 1) result++; //preparing now } return result; }; var MxeRender2D = function() { this.initialize.apply(this, arguments); }; MxeRender2D.prototype.initialize = function(render) { this.render = render; this.gl = null; this.backRenderList = []; this.backRenderCount = 0; this.frontRenderList = []; this.frontRenderCount = 0; this.vertBuffer = null; this.uvBuffer = null; this.indexBuffer = null; this.pMatrix = mat4.create(); mat4.identity(this.pMatrix); this.vMatrix = mat4.create(); mat4.identity(this.vMatrix); this.textureUVMargin = new Float32Array(2); this.textureUVScale = new Float32Array(2); this.shaderRequestOptions = new MxeShaderRequestOptions(); this.shaderRequestOptions.useLighting = false; this.ofsCanvas = null; this.ofsContext = null; this.polygonColor = new Float32Array([1.0, 1.0, 1.0, 1.0]); this.transparentColor = new Float32Array([0, 0, 0, 0]); }; MxeRender2D.prototype.initGL = function(gl) { this.gl = gl; var x1 = -1.0; var x2 = 1.0; var y1 = -1.0; var y2 = 1.0; var vertices; this.vertBuffer = gl.createBuffer(); if(this.vertBuffer !== null){ gl.bindBuffer(gl.ARRAY_BUFFER, this.vertBuffer); vertices = [ x1, y1, 0.0, x2, y1, 0.0, x2, y2, 0.0, x1, y2, 0.0 ]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); this.vertBuffer.itemSize = 3; this.vertBuffer.numItems = 4; } this.uvBuffer = gl.createBuffer(); if(this.uvBuffer !== null){ gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); vertices = [ 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0 ]; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); this.uvBuffer.itemSize = 2; this.uvBuffer.numItems = 4; } this.indexBuffer = gl.createBuffer(); if(this.indexBuffer !== null){ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); //var indices = [ 0, 1, 3, 2 ]; var indices = [ 3, 1, 0, 1, 3, 2 ]; gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW); this.indexBuffer.itemSize = 1; this.indexBuffer.numItems = 6; } }; MxeRender2D.prototype.clearRenderList = function() { this.backRenderCount = 0; this.frontRenderCount = 0; }; MxeRender2D.prototype.addBackRenderList = function(renderList) { for(var i=0; i<renderList.length; i++){ this.backRenderList[this.backRenderCount++] = renderList[i]; } }; MxeRender2D.prototype.addFrontRenderList = function(renderList) { for(var i=0; i<renderList.length; i++){ this.frontRenderList[this.frontRenderCount++] = renderList[i]; } }; MxeRender2D.prototype.prepare = function() { }; MxeRender2D.prototype.getOffscreenContext = function() { if(this.ofsCanvas) return this.ofsContext; this.createOffscreenCanvas(256, 256); this.ofsContext = this.ofsCanvas.getContext("2d"); return this.ofsContext; }; MxeRender2D.prototype.createOffscreenCanvas = function(w, h) { this.ofsCanvas = document.createElement("canvas"); this.resizeOffscreenCanvas(w, h); }; MxeRender2D.prototype.resizeOffscreenCanvas = function(w, h) { this.ofsCanvas.width = w; this.ofsCanvas.height = h; //this.ofsContext = this.ofsCanvas.getContext("2d"); }; MxeRender2D.prototype.drawBackRenderList = function(renderMode, selectionOffset) { for(var i=0; i<this.backRenderCount; i++){ this.drawItem(this.backRenderList[i], renderMode, i+selectionOffset); } return this.backRenderCount; }; MxeRender2D.prototype.drawFrontRenderList = function(renderMode, selectionOffset) { for(var i=0; i<this.frontRenderCount; i++){ this.drawItem(this.frontRenderList[i], renderMode, i+selectionOffset); } return this.frontRenderCount; }; MxeRender2D.prototype.setAlphaBlend = function(frame, renderMode) { var gl = this.gl; if(renderMode === MxeRender.def.RM_SELECTION){ gl.disable(gl.BLEND); return; } var cast = frame.cast; if(! cast.alphaBlendable){ gl.disable(gl.BLEND); return; } var useBlend = frame.useBlending || (cast.castType === MxeCast.def.CT_TEXT) || frame.alpha < 1.0 || (cast.alphaType !== 0); if(useBlend){ gl.enable(gl.BLEND); gl.blendFuncSeparate( frame.blendFactorSrc, frame.blendFactorDst, frame.blendFactorAlphaSrc, frame.blendFactorAlphaDst); }else{ gl.disable(gl.BLEND); } }; MxeRender2D.prototype.setScissor = function(frame, renderMode) { var gl = this.gl; if(frame.clippingMode === 0){ gl.disable(gl.SCISSOR_TEST); return; } if(frame.clippingMode === 1){ //world mode var left = frame.clippingRect[0]; var top = frame.clippingRect[1]; var right = frame.clippingRect[2]; var bottom = frame.clippingRect[3]; gl.scissor(left, this.render.viewportHeight-bottom, right-left, bottom-top); gl.enable(gl.SCISSOR_TEST); return; } if(frame.clippingMode === 2){ //local mode //TODO gl.disable(gl.SCISSOR_TEST); return; } gl.disable(gl.SCISSOR_TEST); }; MxeRender2D.prototype.drawItem = function(renderItem, renderMode, selectionID) { this.drawFrame(renderItem[1].frame, renderMode, selectionID); }; MxeRender2D.prototype.drawFrame = function(frame, renderMode, selectionID) { if(this.vertBuffer === null) return; if(! frame.worldVisible) return; if(renderMode !== MxeRender.def.RM_SELECTION && frame.alpha === 0.0) return; var cast = frame.cast; if(cast === null) return; if(cast.onDraw){ //PRPCEDURAL cast.onDraw(this.render, frame, renderMode, selectionID); return; } if(! cast.getPrepared()) return; if(! cast.glTexture) return; var gl = this.gl; this.shaderRequestOptions.renderMode = renderMode; if(frame.enableTransparentDiscard) this.shaderRequestOptions.alphaType = cast.alphaType; else this.shaderRequestOptions.alphaType = cast.alphaType & 2; var isText = this.shaderRequestOptions.isText = (cast.castType == MxeCast.def.CT_TEXT); var shaderProgram = this.render.requestShaderProgram(this.shaderRequestOptions); this.render.setShaderProgram(shaderProgram); gl.disable(gl.CULL_FACE); gl.disable(gl.DEPTH_TEST); gl.depthMask(false); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, cast.glTexture); gl.uniform1i(shaderProgram.uniforms.uTexture0, 0); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, frame.magFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, frame.minFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, frame.wrap_s); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, frame.wrap_t); //set bufferes gl.bindBuffer(gl.ARRAY_BUFFER, this.vertBuffer); gl.enableVertexAttribArray(shaderProgram.attributes.atVertex); gl.vertexAttribPointer(shaderProgram.attributes.atVertex, this.vertBuffer.itemSize, gl.FLOAT, false, 0, 0); //if(shaderProgram.attributes.atNormal > -1){ // gl.disableVertexAttribArray(shaderProgram.attributes.atNormal); //} if(shaderProgram.attributes.atUV[0] > -1){ gl.enableVertexAttribArray(shaderProgram.attributes.atUV[0]); gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); gl.vertexAttribPointer(shaderProgram.attributes.atUV[0], this.uvBuffer.itemSize, gl.FLOAT, false, 0, 0); } //if(shaderProgram.attributes.atWeight0 > -1){ // gl.disableVertexAttribArray(shaderProgram.attributes.atWeight0); //} //if(shaderProgram.attributes.atWeight1 > -1){ // gl.disableVertexAttribArray(shaderProgram.attributes.atWeight1); //} //if(shaderProgram.attributes.atVColor > -1){ // gl.disableVertexAttribArray(shaderProgram.attributes.atVColor); // if(shaderProgram.uniforms.uEnableVColor !== null){ // gl.uniform1i(shaderProgram.uniforms.uEnableVColor, 0); // } //} gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); gl.uniform1i(shaderProgram.uniforms.uBlendMode[0], 1); gl.uniformMatrix4fv(shaderProgram.uniforms.uProjMatrix, false, this.pMatrix); gl.uniformMatrix4fv(shaderProgram.uniforms.uViewMatrix, false, this.vMatrix); gl.uniform1i(shaderProgram.uniforms.uNBlend, 0); gl.uniformMatrix4fv(shaderProgram.uniforms.uWorldMatrix, false, frame.viewMatrix); if(shaderProgram.uniforms.uFogStart !== null){ gl.uniform1f(shaderProgram.uniforms.uFogStart, 0.0); } if(shaderProgram.uniforms.uFogEnd !== null){ gl.uniform1f(shaderProgram.uniforms.uFogEnd, 0.0); } if(shaderProgram.uniforms.uFogFactor !== null){ gl.uniform1f(shaderProgram.uniforms.uFogFactor, 0.0); } if(shaderProgram.uniforms.uEnableVColor !== null){ gl.uniform1i(shaderProgram.uniforms.uEnableVColor, 0); } if(renderMode === MxeRender.def.RM_SELECTION){ /* //32bit case var sred = ((selectionID >> 16))/255.0; var sgreen = (((selectionID >> 8) & 0xff))/255.0; var sblue = ((selectionID & 0xff))/255.0; gl.uniform4fv(shaderProgram.uniforms.uMatDiffuse, [sred, sgreen, sblue, 1.0]); */ //16bit case if(selectionID > 0xffff){ //error overflow gl.uniform4fv(shaderProgram.uniforms.uMatDiffuse, [1.0, 1.0, 1.0, 1.0]); }else{ var sa = (( selectionID >> 12) )/15.0; var sb = (((selectionID >> 8 ) & 0xf))/15.0; var sg = (((selectionID >> 4 ) & 0xf))/15.0; var sr = (( selectionID & 0xf))/15.0; gl.uniform4fv(shaderProgram.uniforms.uMatDiffuse, [sr, sg, sb, sa]); } }else{ if(isText){ gl.uniform4fv(shaderProgram.uniforms.uTextColor, cast.color); if(cast.bgTransparent){ this.transparentColor[0] = cast.color[0]; this.transparentColor[1] = cast.color[1]; this.transparentColor[2] = cast.color[2]; gl.uniform4fv(shaderProgram.uniforms.uTextBgColor, this.transparentColor); }else{ gl.uniform4fv(shaderProgram.uniforms.uTextBgColor, cast.backgroundColor); } } if(shaderProgram.uniforms.uMatDiffuse !== null){ this.polygonColor[3] = frame.alpha; gl.uniform4fv(shaderProgram.uniforms.uMatDiffuse, this.polygonColor); } } if(shaderProgram.uniforms.uTextureMargin[0] !== null){ this.textureUVMargin[0] = 0.0; this.textureUVMargin[1] = 0.0; gl.uniform2fv(shaderProgram.uniforms.uTextureMargin[0], this.textureUVMargin); } if(shaderProgram.uniforms.uTextureScale[0] !== null){ this.textureUVScale[0] = cast.getWidth() / cast.textureWidth; this.textureUVScale[1] = cast.getHeight() / cast.textureHeight; gl.uniform2fv(shaderProgram.uniforms.uTextureScale[0], this.textureUVScale); } this.setAlphaBlend(frame, renderMode); this.setScissor(frame, renderMode); gl.drawElements(gl.TRIANGLES, this.indexBuffer.numItems, gl.UNSIGNED_SHORT, 0); }; var MxeRender3D = function() { this.initialize.apply(this, arguments); }; MxeRender3D.prototype.initialize = function(render) { this.render = render; this.gl = null; this.renderList = []; this.renderCount = 0; this.alphaRenderList = []; this.alphaRenderCount = 0; this.lightList = []; this.lightCount = 0; this.currentCameraTrack = null; this.projMatrix = mat4.create(); this.viewProjMatrix = mat4.create(); //this.viewMatrix = mat4.create(); this.viewMatrix = mat4.create(); this.identityMatrix = mat4.create(); mat4.identity(this.identityMatrix); //this.identityMatrix[10] = -1.0; this.workMatrix = mat4.create(); this.workVector = new Float32Array(4); this.workPole = new Int8Array(3); this.textureUVMargin = new Float32Array(2); this.textureUVScale = new Float32Array(2); this.clipBoxes = new Array(2); //for clipping work this.shaderOptions = new MxeShaderRequestOptions(); //for shader-- this.blendMatricesBuffer = new Float32Array((MxeRender.def.MAX_BONE-1)*16); this.lightTypeBuffer = new Int32Array(MxeRender.def.MAX_LIGHT); this.lightColBuffer = new Float32Array(MxeRender.def.MAX_LIGHT*3); //this.lightMatricesBuffer = new Float32Array(MxeRender.def.MAX_LIGHT*16); this.lightDirBuffer = new Float32Array(MxeRender.def.MAX_LIGHT*3); this.lightPosBuffer = new Float32Array(MxeRender.def.MAX_LIGHT*3); this.lightAmbient = new Float32Array(3); this.lightAtt0Buffer = new Float32Array(MxeRender.def.MAX_LIGHT); this.lightAtt1Buffer = new Float32Array(MxeRender.def.MAX_LIGHT); this.lightAtt2Buffer = new Float32Array(MxeRender.def.MAX_LIGHT); this.lightRangeBuffer = new Float32Array(MxeRender.def.MAX_LIGHT); this.spotExpBuffer = new Float32Array(MxeRender.def.MAX_LIGHT); this.spotCutOffBuffer = new Float32Array(MxeRender.def.MAX_LIGHT); this.cameraPos = new Float32Array(3); //camera pos dummy //--for shader //init billboard model this.initBillboardModel(); }; MxeRender3D.prototype.initBillboardModel = function() { this.billboardModel = new MxeModel(null, -1, "BillboadModel"); this.billboardModel.sectors = new Array(1); this.billboardModel.sectorsL = {}; var bbsector; this.billboardModel.sectors[0] = this.billboardModel.sectorsL["g0"] = bbsector = new MxeSector(this.billboardModel, 0, "g0"); bbsector.vertexSrc = { position: new Float32Array([-0.5, -0.5, 0.0, 0.5, -0.5, 0.0, -0.5, 0.5, 0.0, 0.5, 0.5, 0.0,]), normal: new Float32Array([0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0,]), texture: [new Float32Array([0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0,])], index: new Uint16Array([2, 3, 1, 2, 1, 0,]), }; bbsector.indexLength = 6; bbsector.boxMin = new Float32Array([-0.5, -0.5, 0.0]); bbsector.boxMax = new Float32Array([0.5, 0.5, 0.0]); this.billboardRenderItem = [0, bbsector, [null]]; }; MxeRender3D.prototype.initGL = function(gl) { this.gl = gl; this.billboardModel.initGL(gl); }; MxeRender3D.prototype.clearRenderList = function() { this.renderCount = 0; this.alphaRenderCount = 0; }; MxeRender3D.prototype.addRenderList = function(renderList) { for(var i=0; i<renderList.length; i++){ if(this.getItemAlphaType(renderList[i]) < 2){ this.renderList[this.renderCount++] = renderList[i]; }else{ this.alphaRenderList[this.alphaRenderCount++] = renderList[i]; } } }; MxeRender3D.prototype.clearLightList = function() { this.lightCount = 0; this.lightAmbient[0] = this.lightAmbient[1] = this.lightAmbient[2] = 0.0; for(var i=0; i<MxeRender.def.MAX_LIGHT; i++){ this.lightTypeBuffer[i] = 0; } }; MxeRender3D.prototype.addLight = function(track) { var lightFrame = track.frame; var light = lightFrame.cast; if(light.type === 3){ this.lightAmbient[0]+= light.color[0]; if(this.lightAmbient[0] > 1.0) this.lightAmbient[0] = 1.0; this.lightAmbient[1]+= light.color[1]; if(this.lightAmbient[1] > 1.0) this.lightAmbient[1] = 1.0; this.lightAmbient[2]+= light.color[2]; if(this.lightAmbient[2] > 1.0) this.lightAmbient[2] = 1.0; return; } if(this.lightCount < MxeRender.def.MAX_LIGHT){ var offsetVec3 = this.lightCount*3; this.lightTypeBuffer[this.lightCount] = light.type + 1; //0 is light off this.lightColBuffer.set(light.color, offsetVec3); //this.lightMatricesBuffer.set(lightFrame.viewWorldMatrix, this.lightCount*16); this.workVector[0] = this.workVector[1] = this.workVector[3] = 0.0; this.workVector[2] = 1.0; mat4.multiplyVec4(lightFrame.worldMatrix, this.workVector); vec3.normalize(this.workVector); this.lightDirBuffer[offsetVec3 ] = this.workVector[0]; this.lightDirBuffer[offsetVec3+1] = this.workVector[1]; this.lightDirBuffer[offsetVec3+2] = this.workVector[2]; this.lightPosBuffer[offsetVec3 ] = lightFrame.worldMatrix[12]; this.lightPosBuffer[offsetVec3+1] = lightFrame.worldMatrix[13]; this.lightPosBuffer[offsetVec3+2] = lightFrame.worldMatrix[14]; this.lightAtt0Buffer[this.lightCount] = 0.0; this.lightAtt1Buffer[this.lightCount] = 0.0; this.lightAtt2Buffer[this.lightCount] = 0.0; this.lightRangeBuffer = light.distance; this.spotExpBuffer[this.lightCount] = 0.0; this.spotCutOffBuffer[this.lightCount] = 180.0; if(light.type === MxeLight.def.TYPE_POINT || light.type === MxeLight.def.TYPE_SPOT){ this.lightAtt0Buffer[this.lightCount] = light.dropOffRate3; this.lightAtt1Buffer[this.lightCount] = light.dropOffRate1 * 0.0001; this.lightAtt2Buffer[this.lightCount] = light.dropOffRate2 * 0.000004; if(light.type === MxeLight.def.TYPE_SPOT){ var phi = light.cutOffAnglePhi; if(phi < light.cutOffAngle) phi = light.cutOffAngle; var exp = 128.0; if(light.cutOffAngle !== 0.0) ((phi + 0.01) / light.cutOffAngle - 1.0) * 20.0; if(exp > 128.0) exp = 128.0; this.spotExpBuffer[this.lightCount] = exp; this.spotCutOffBuffer[this.lightCount] = phi * 0.5; } } this.lightList[this.lightCount] = track; this.lightCount++; } }; MxeRender3D.prototype.drawBillboard = function(renderItem, renderMode, selectionOffset) { var bbcast = renderItem[1].frame.getCast(); if(bbcast === null) return; var bbinfo = bbcast.billboardInfo; if(bbinfo === null) return; var bbsector = this.billboardModel.sectors[0]; bbsector.material = bbinfo.material; this.billboardRenderItem[2][0] = renderItem[1]; this.drawSector(this.billboardRenderItem, renderMode, selectionOffset); bbsector.material = null; }; MxeRender3D.prototype.drawRenderList = function(renderMode, selectionOffset) { var item; var i; for(i=0; i<this.renderCount; i++){ item = this.renderList[i]; if(item[0] === 0){ //CT_MODEL, draw model sector this.drawSector(item, renderMode, i+selectionOffset); }else if(item[0] === 1){ //CT_TEXTURE, draw billboard this.drawBillboard(item, renderMode, i+selectionOffset); } } selectionOffset+= this.renderCount; for(i=0; i<this.alphaRenderCount; i++){ item = this.alphaRenderList[i]; if(item[0] === 0){ //CT_MODEL, draw model sector this.drawSector(item, renderMode, i+selectionOffset); }else if(item[0] === 1){ //CT_TEXTURE, draw billboard this.drawBillboard(item, renderMode, i+selectionOffset); } } return this.renderCount + this.alphaRenderCount; }; MxeRender3D.prototype.prepare = function() { var camTrack = this.currentCameraTrack; var gl = this.gl; if(camTrack === null){ //no camera }else{ var camCast = camTrack.frame.cast; camCast.prepareRender(this, camTrack.frame); if(this.render.options.useMatrixEnginePerspective){ MxeGeom.mat4.perspective(camCast.cameraAngle, this.render.viewportWidth / this.render.viewportHeight, camCast.near, camCast.far, this.projMatrix); }else{ mat4.perspective(camCast.cameraAngle, this.render.viewportWidth / this.render.viewportHeight, camCast.near, camCast.far, this.projMatrix); } var camMatrix = camTrack.frame.worldMatrix; this.cameraPos[0] = camMatrix[12]; this.cameraPos[1] = camMatrix[13]; this.cameraPos[2] = camMatrix[14]; mat4.identity(this.workMatrix); mat4.scale(this.workMatrix, camTrack.frame.worldSiz); mat4.inverse(camMatrix, this.viewMatrix); mat4.multiply(this.workMatrix, this.viewMatrix, this.viewMatrix); MxeGeom.mat4.switchHand(this.viewMatrix); mat4.multiply(this.projMatrix, this.viewMatrix, this.viewProjMatrix); } //sort alpha polygons if(this.render.options.enableTanslucentZSort){ this.alphaRenderList.length = this.alphaRenderCount; var sector; var cast; for(i=0; i<this.alphaRenderCount; i++){ item = this.alphaRenderList[i]; if(item[0] === 0){ //CT_MODEL sector = item[1]; if(sector.boxMin == null){ item[3] = 0.0; continue; } vec3.add(sector.boxMin, sector.boxMax, this.workVector); this.workVector[0]/= 2.0; this.workVector[1]/= 2.0; this.workVector[2]/= 2.0; this.workVector[3] = 1.0; if(sector.isSkin){ mat4.multiplyVec4(item[2][0].frame.skinMatrix, this.workVector, this.workVector); //TODO other bones }else{ mat4.multiplyVec4(item[2][0].frame.worldMatrix, this.workVector, this.workVector); } mat4.multiplyVec4(this.render.viewMatrix, this.workVector, this.workVector); item[3] = this.workVector[2]; }else if(item[0] === 1){ //CT_TEXTURE(billboard) cast = item[1].frame.getCast(); if(cast === null){ item[3] = 0.0; continue; } this.workVector[0] = 0.0; this.workVector[1] = 0.0; this.workVector[2] = -cast.billboardInfo.pos[2]; mat4.multiplyVec4(item[1].frame.billboardMatrix, this.workVector, this.workVector); item[3] = this.workVector[2]; }else{ //unknown item[3] = 0.0; continue; } } this.alphaRenderList.sort( function(a, b){ if(a[3] < b[3]) return -1; if(a[3] > b[3]) return 1; return 0; } ); } }; MxeRender3D.prototype.getItemAlphaType = function(renderItem) { if(renderItem[0] === 0){ //CT_MODEL var sector = renderItem[1]; var material = sector.material; var textureInfo = material.textureInfo[0]; //TODO vertex color //TODO material track if(material.useBlending || material.hasTransrucentVertex) return MxeMaterial.def.HAS_TRANSLUCENT; if(0.0 < material.color[3] && material.color[3] < 1.0) return MxeMaterial.def.HAS_TRANSLUCENT; if(textureInfo !== null && textureInfo.cast !== null){ var textureCast = textureInfo.cast; return textureCast.alphaType; } return 0; }else if(renderItem[0] === 1){ //CT_TEXTURE var cast = renderItem[1].frame.getCast(); //TODO material track if(cast !== null){ if(cast.billboardInfo !== null){ if(cast.billboardInfo.material.hasTransrucentVertex) return MxeMaterial.def.HAS_TRANSLUCENT; if(0.0 < cast.billboardInfo.material.color[3] && cast.billboardInfo.material.color[3] < 1.0) return MxeMaterial.def.HAS_TRANSLUCENT; } return cast.alphaType; } return 0; } return 0; }; MxeRender3D.prototype.getItemMaterial = function(renderItem) { if(renderItem[0] === 0){ //CT_MODEL return renderItem[1].material; }else if(renderItem[0] === 1){ //CT_TEXTURE var cast = renderItem[1].frame.getCast(); if(cast !== null){ if(cast.billboardInfo !== null){ return cast.billboardInfo.material; } } return null; } return null; }; MxeRender3D.prototype.setAlphaBlend = function(renderItem, renderMode) { var gl = this.gl; if(renderMode === MxeRender.def.RM_SELECTION){ gl.disable(gl.BLEND); gl.depthMask(true); return; } var itemAlphaType = this.getItemAlphaType(renderItem); if(itemAlphaType !== 0){ var material = this.getItemMaterial(renderItem); gl.enable(gl.BLEND); gl.blendFuncSeparate( material.blendFactorSrc, material.blendFactorDst, material.blendFactorAlphaSrc, material.blendFactorAlphaDst); //detect depth mask var depthMask = material.depthMask && ! material.useBlending; depthMask = depthMask && (material.color[3] > 0.95); gl.depthMask(depthMask); }else{ gl.disable(gl.BLEND); gl.depthMask(true); } }; MxeRender3D.prototype.checkClip = function(v, depthNear, depthFar, poles) { var initFlag = (poles[0] === 3); if(initFlag) poles[0] = poles[1] = poles[2] = 0; var z = v[3]; if(z < depthNear) poles[2]--; else if(depthFar < z) poles[2]++; if(Math.abs(z) < 1e-6) if(z < 0.0) z = -1e-6; else z = 1e-6; var x = v[0]/z; if(x < -1.0) poles[0]--; else if(1.0 < x) poles[0]++; var y = v[1]/z; if(y < -1.0) poles[1]--; else if(1.0 < y) poles[1]++; if(! initFlag){ poles[0]/=2; poles[1]/=2; poles[2]/=2; } if(poles[0] === 0 && poles[1] === 0 && poles[2] === 0){ return true; }else{ return false; } }; MxeRender3D.prototype.drawSector = function(renderItem, renderMode, selectionID) { var gl = this.gl; var sector = renderItem[1]; var frame; var i, j, k, l; var bones = renderItem[2]; var gm; var cameraCast; //check visibility if(renderMode !== MxeRender.def.RM_SELECTION) if(sector.material.color[3] === 0.0) return; for(i=0; i<bones.length; i++){ frame = bones[i].frame; if(! frame.worldVisible) return; } cameraCast = this.currentCameraTrack.frame.getCast(); var isBillboard = (bones[0].billboardType > 0); //cpu clipping var boxes = this.clipBoxes; var clipout = true; if(this.render.options.enableCPUClipping && sector.boxMin !== null){ for(i=0; i<bones.length; i++){ frame = bones[i].frame; if(isBillboard){ mat4.multiply(this.projMatrix, frame.billboardMatrix, this.workMatrix); }else{ if(sector.isSkin) gm = frame.skinMatrix; else gm = frame.worldMatrix; mat4.multiply(this.viewProjMatrix, gm, this.workMatrix); } boxes[0] = sector.boxMin; boxes[1] = sector.boxMax; this.workPole[0] = 3; //3 is init flag for(j=0; j<2; j++){ for(k=0; k<2; k++){ for(l=0; l<2; l++){ this.workVector[0] = boxes[j][0]; this.workVector[1] = boxes[k][1]; this.workVector[2] = boxes[l][2]; this.workVector[3] = 1.0; mat4.multiplyVec4(this.workMatrix, this.workVector, this.workVector); if(this.checkClip(this.workVector, cameraCast.near, cameraCast.far*sector.material.clippingValue, this.workPole)){ clipout = false; break; } if(boxes[0][2] === boxes[1][2]) break; } if(! clipout) break; if(boxes[0][1] === boxes[1][1]) break; } if(! clipout) break; if(boxes[0][0] === boxes[1][0]) break; } if(! clipout) break; } if(clipout) return; } //set shader var shaderProgram = null; if(sector.material.shaderCast !== null && renderMode !== MxeRender.def.RM_SELECTION){ shaderProgram = sector.material.shaderCast.program; useShaderCast = true; this.render.setShaderProgram(shaderProgram); sector.material.shaderCast.commitUniformValues(gl); }else{ this.shaderOptions.renderMode = renderMode; this.shaderOptions.alphaType = this.getItemAlphaType(renderItem); this.shaderOptions.useLighting = this.render.options.enableLighting && sector.material.enableLighting; this.shaderOptions.useSpecular = this.render.options.enableSpecularLighting && (sector.material.shininess > 0.0); shaderProgram = this.render.requestShaderProgram(this.shaderOptions); this.render.setShaderProgram(shaderProgram); } //set depth test if(sector.material.depthTest){ gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); }else{ gl.disable(gl.DEPTH_TEST); } //set lights if(shaderProgram.uniforms.uLightCount !== null) gl.uniform1i(shaderProgram.uniforms.uLightCount, this.lightCount); if(shaderProgram.uniforms.uLightAmbient !== null) gl.uniform3fv(shaderProgram.uniforms.uLightAmbient, this.lightAmbient); if(shaderProgram.uniforms.uLightType !== null) gl.uniform1iv(shaderProgram.uniforms.uLightType, this.lightTypeBuffer); if(shaderProgram.uniforms.uLightCol !== null) gl.uniform3fv(shaderProgram.uniforms.uLightCol, this.lightColBuffer); //if(shaderProgram.uniforms.uLightMatrix !== null) // gl.uniformMatrix4fv(shaderProgram.uniforms.uLightMatrix, false, this.lightMatricesBuffer); if(shaderProgram.uniforms.uLightAtt0 !== null) gl.uniform1f(shaderProgram.uniforms.uLightAtt0, this.lightAtt0Buffer); if(shaderProgram.uniforms.uLightAtt1 !== null) gl.uniform1f(shaderProgram.uniforms.uLightAtt1, this.lightAtt1Buffer); if(shaderProgram.uniforms.uLightAtt2 !== null) gl.uniform1f(shaderProgram.uniforms.uLightAtt2, this.lightAtt2Buffer); if(shaderProgram.uniforms.uLightRange !== null) gl.uniform1f(shaderProgram.uniforms.uLightRange, this.lightRangeBuffer); if(shaderProgram.uniforms.uSpotExponent !== null) gl.uniform1f(shaderProgram.uniforms.uSpotExponent, this.spotExpBuffer); if(shaderProgram.uniforms.uSpotCutoff !== null) gl.uniform1f(shaderProgram.uniforms.uSpotCutoff, this.spotCutOffBuffer); if(shaderProgram.uniforms.uLightDir !== null) gl.uniform3fv(shaderProgram.uniforms.uLightDir, this.lightDirBuffer); if(shaderProgram.uniforms.uLightPos !== null) gl.uniform3fv(shaderProgram.uniforms.uLightPos, this.lightPosBuffer); //set camera pos if(shaderProgram.uniforms.uCameraPos !== null) gl.uniform3fv(shaderProgram.uniforms.uCameraPos, this.cameraPos); //gl.uniform3fv(shaderProgram.uniforms.uCameraPos, this.originPoint); //check texture for(i=0; i<sector.material.textureInfo.length; i++){ var textureInfo = sector.material.textureInfo[i]; if(! textureInfo || textureInfo.cast === null){ if(shaderProgram.uniforms.uBlendMode[i] !== null) gl.uniform1i(shaderProgram.uniforms.uBlendMode[i], 0); continue; } var textureCast = textureInfo.cast; if(! textureCast.getPrepared()) return; //skip render //gl.enable(gl.TEXTURE_2D); //webgl not support gl.activeTexture(gl.TEXTURE0+i); gl.bindTexture(gl.TEXTURE_2D, textureCast.glTexture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, textureInfo.wrap_s); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, textureInfo.wrap_t); if(shaderProgram.uniforms.uTexture[i]) gl.uniform1i(shaderProgram.uniforms.uTexture[i], i); if(shaderProgram.uniforms.uBlendMode[i] !== null) gl.uniform1i(shaderProgram.uniforms.uBlendMode[i], textureInfo.blendMode+1); if(shaderProgram.uniforms.uBlendValue[i] !== null) gl.uniform1f(shaderProgram.uniforms.uBlendValue[i], textureInfo.blendValue); var texRatioU = 1.0; var texRatioV = 1.0; if(shaderProgram.uniforms.uTextureScale[i] !== null){ this.textureUVScale[0] = 1.0; if(textureInfo.repeat[0] !== 1.0) this.textureUVScale[0]*= textureInfo.repeat[0]; if(textureInfo.cast.image.width !== textureInfo.cast.textureWidth){ texRatioU = textureInfo.cast.image.width / textureInfo.cast.textureWidth; this.textureUVScale[0]*= texRatioU; } this.textureUVScale[1] = 1.0; if(textureInfo.repeat[1] !== 1.0) this.textureUVScale[1]*= textureInfo.repeat[1]; if(textureInfo.cast.image.height !== textureInfo.cast.textureHeight){ texRatioV = textureInfo.cast.image.height / textureInfo.cast.textureHeight; this.textureUVScale[1]*= texRatioV; } gl.uniform2fv(shaderProgram.uniforms.uTextureScale[i], this.textureUVScale); } if(shaderProgram.uniforms.uTextureMargin[i] !== null){ this.textureUVMargin[0] = -textureInfo.offset[0]; if(textureInfo.repeat[0] !== 1.0){ this.textureUVMargin[0]-= (0.5*textureInfo.repeat[0]-0.5)*texRatioU; } this.textureUVMargin[1] = textureInfo.offset[1]; if(textureInfo.repeat[1] !== 1.0){ this.textureUVMargin[1]-= (0.5*textureInfo.repeat[1]-0.5)*texRatioV; } gl.uniform2fv(shaderProgram.uniforms.uTextureMargin[i], this.textureUVMargin); } if(shaderProgram.uniforms.uWrapMode[i] !== null){ gl.uniform1i(shaderProgram.uniforms.uWrapMode[i], textureInfo.mapType); } } //set bufferes gl.bindBuffer(gl.ARRAY_BUFFER, sector.positionBuffer); gl.enableVertexAttribArray(shaderProgram.attributes.atVertex); gl.vertexAttribPointer(shaderProgram.attributes.atVertex, sector.positionBuffer.itemSize, gl.FLOAT, false, 0, 0); //normal if(shaderProgram.attributes.atNormal > -1){ gl.enableVertexAttribArray(shaderProgram.attributes.atNormal); gl.bindBuffer(gl.ARRAY_BUFFER, sector.normalBuffer); gl.vertexAttribPointer(shaderProgram.attributes.atNormal, sector.normalBuffer.itemSize, gl.FLOAT, false, 0, 0); } //vertex color if(shaderProgram.attributes.atVColor > -1){ if(sector.colorBuffer === null){ if(shaderProgram.uniforms.uEnableVColor !== null){ gl.uniform1i(shaderProgram.uniforms.uEnableVColor, 0); } }else{ if(shaderProgram.uniforms.uEnableVColor !== null){ gl.uniform1i(shaderProgram.uniforms.uEnableVColor, 1); } gl.enableVertexAttribArray(shaderProgram.attributes.atVColor); gl.bindBuffer(gl.ARRAY_BUFFER, sector.colorBuffer); gl.vertexAttribPointer(shaderProgram.attributes.atVColor, sector.colorBuffer.itemSize, gl.FLOAT, false, 0, 0); } } if(sector.uvBuffer !== null){ for(var i=0; i<sector.uvBuffer.length; i++){ if(shaderProgram.attributes.atUV[i] > -1){ if(sector.uvBuffer === null || sector.uvBuffer[i] === null){ //gl.disableVertexAttribArray(shaderProgram.attributes.atUV[i]); }else{ gl.enableVertexAttribArray(shaderProgram.attributes.atUV[i]); gl.bindBuffer(gl.ARRAY_BUFFER, sector.uvBuffer[i]); gl.vertexAttribPointer(shaderProgram.attributes.atUV[i], sector.uvBuffer[i].itemSize, gl.FLOAT, false, 0, 0); } } } } if(shaderProgram.attributes.atWeight0 > -1){ if(sector.boneWeightBuffer === null){ //gl.disableVertexAttribArray(shaderProgram.attributes.atWeight0); //gl.disableVertexAttribArray(shaderProgram.attributes.atWeight1); }else{ gl.bindBuffer(gl.ARRAY_BUFFER, sector.boneWeightBuffer); gl.enableVertexAttribArray(shaderProgram.attributes.atWeight0); if(bones.length < 4){ gl.vertexAttribPointer(shaderProgram.attributes.atWeight0, bones.length, gl.FLOAT, false, bones.length*4, 0); //gl.disableVertexAttribArray(shaderProgram.attributes.atWeight1); }else{ gl.vertexAttribPointer(shaderProgram.attributes.atWeight0, 3, gl.FLOAT, false, bones.length*4, 0); gl.enableVertexAttribArray(shaderProgram.attributes.atWeight1); gl.vertexAttribPointer(shaderProgram.attributes.atWeight1, bones.length-3, gl.FLOAT, false, bones.length*4, 3*4); } } } if(shaderProgram.uniforms.uProjMatrix !== null) gl.uniformMatrix4fv(shaderProgram.uniforms.uProjMatrix, false, this.projMatrix); if(shaderProgram.uniforms.uViewMatrix !== null) if(isBillboard) gl.uniformMatrix4fv(shaderProgram.uniforms.uViewMatrix, false, this.identityMatrix); //because view is identity else gl.uniformMatrix4fv(shaderProgram.uniforms.uViewMatrix, false, this.viewMatrix); if(shaderProgram.uniforms.uViewProjMatrix !== null) if(isBillboard) gl.uniformMatrix4fv(shaderProgram.uniforms.uViewProjMatrix, false, this.projMatrix); //because view is identity! else gl.uniformMatrix4fv(shaderProgram.uniforms.uViewProjMatrix, false, this.viewProjMatrix); if(shaderProgram.uniforms.uWorldViewProjMatrix !== null){ var vpmatrix; if(isBillboard) vpmatrix = this.projMatrix; else vpmatrix = this.viewProjMatrix; if(sector.isSkin){ mat4.multiply(vpmatrix, bones[0].frame.skinMatrix, this.workMatrix); }else{ mat4.multiply(vpmatrix, bones[0].frame.worldMatrix, this.workMatrix); } gl.uniformMatrix4fv(shaderProgram.uniforms.uWorldViewProjMatrix, false, this.workMatrix); } if(renderMode === MxeRender.def.RM_DEFAULT){ if(shaderProgram.uniforms.uMatDiffuse !== null) gl.uniform4fv(shaderProgram.uniforms.uMatDiffuse, sector.material.color); if(shaderProgram.uniforms.uMatSpecular !== null) gl.uniform3fv(shaderProgram.uniforms.uMatSpecular, sector.material.specularColor); if(shaderProgram.uniforms.uMatEmissive !== null) gl.uniform3fv(shaderProgram.uniforms.uMatEmissive, sector.material.emissionColor); if(shaderProgram.uniforms.uPower !== null){ var pow = 0.0; //default specular off if(sector.material.shininess > 0.0){ pow = 30.0*(1.0 - sector.material.shininess); if(pow <= 0.0) pow = 0.00001; } gl.uniform1f(shaderProgram.uniforms.uPower, pow); } if(sector.material.enableFog && cameraCast.fogEnable){ if(shaderProgram.uniforms.uFogColor !== null) gl.uniform3fv(shaderProgram.uniforms.uFogColor, cameraCast.fogColor); if(shaderProgram.uniforms.uFogStart !== null) gl.uniform1f(shaderProgram.uniforms.uFogStart, cameraCast.fogNear); if(shaderProgram.uniforms.uFogEnd !== null){ gl.uniform1f(shaderProgram.uniforms.uFogEnd, cameraCast.fogFar); } if(shaderProgram.uniforms.uFogFactor !== null){ gl.uniform1f(shaderProgram.uniforms.uFogFactor, cameraCast.fogFactor); } }else{ if(shaderProgram.uniforms.uFogStart !== null){ gl.uniform1f(shaderProgram.uniforms.uFogStart, 0.0); } if(shaderProgram.uniforms.uFogEnd !== null){ gl.uniform1f(shaderProgram.uniforms.uFogEnd, 0.0); } if(shaderProgram.uniforms.uFogFactor !== null){ gl.uniform1f(shaderProgram.uniforms.uFogFactor, 0.0); } } } else if(renderMode === MxeRender.def.RM_SELECTION){ /* //32bit case var sred = ((selectionID >> 16))/255.0; var sgreen = (((selectionID >> 8) & 0xff))/255.0; var sblue = ((selectionID & 0xff))/255.0; gl.uniform4fv(shaderProgram.uniforms.uMatDiffuse, [sred, sgreen, sblue, 1.0]); */ //16bit case if(selectionID > 0xffff){ //error overflow gl.uniform4fv(shaderProgram.uniforms.uMatDiffuse, [1.0, 1.0, 1.0, 1.0]); }else{ var sa = (( selectionID >> 12) )/15.0; var sb = (((selectionID >> 8 ) & 0xf))/15.0; var sg = (((selectionID >> 4 ) & 0xf))/15.0; var sr = (( selectionID & 0xf))/15.0; gl.uniform4fv(shaderProgram.uniforms.uMatDiffuse, [sr, sg, sb, sa]); } } if(shaderProgram.uniforms.uNBlend !== null){ gl.uniform1i(shaderProgram.uniforms.uNBlend, bones.length); } if(shaderProgram.uniforms.uWorldMatrix !== null){ if(isBillboard){ gl.uniformMatrix4fv(shaderProgram.uniforms.uWorldMatrix, false, bones[0].frame.billboardMatrix); }else if(sector.isSkin){ gl.uniformMatrix4fv(shaderProgram.uniforms.uWorldMatrix, false, bones[0].frame.skinMatrix); }else{ gl.uniformMatrix4fv(shaderProgram.uniforms.uWorldMatrix, false, bones[0].frame.worldMatrix); } } if(shaderProgram.uniforms.uBlendMatrix !== null && bones.length > 1){ for(i=0; i<bones.length-1; i++){ frame = bones[i+1].frame; if(sector.isSkin){ this.blendMatricesBuffer.set(frame.skinMatrix, i*16); }else{ this.blendMatricesBuffer.set(frame.worldMatrix, i*16); } } gl.uniformMatrix4fv(shaderProgram.uniforms.uBlendMatrix, false, this.blendMatricesBuffer); } //TODO 4poly this.setAlphaBlend(renderItem, renderMode); if(sector.material.doubleSided){ gl.disable(gl.CULL_FACE); }else{ gl.enable(gl.CULL_FACE); } //set user shader parameter if(shaderProgram.uniforms.uUserFloatArray !== null){ gl.uniform1fv(shaderProgram.uniforms.uUserFloatArray, sector.model.shaderUserFloatArray); } if(shaderProgram.uniforms.uUserIntArray !== null){ gl.uniform1iv(shaderProgram.uniforms.uUserIntArray, sector.model.shaderUserIntArray); } if(shaderProgram.uniforms.uTime !== null){ gl.uniform1f(shaderProgram.uniforms.uTime, this.render.player.getTime()/1000.0); } if(shaderProgram.uniforms.uRandom !== null){ gl.uniform1i(shaderProgram.uniforms.uRandom, Math.floor(Math.random()*MxeRender.def.MAX_SHADER_RANDOM+1)); } gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, sector.indexBuffer); gl.drawElements(gl.TRIANGLES, sector.indexLength, gl.UNSIGNED_SHORT, sector.indexOffset*2); }; var MxeRender = function() { this.initialize.apply(this, arguments); }; MxeRender.prototype.initialize = function(player) { this.player = player; this.gl = null; this.viewportWidth = 0; this.viewportHeight = 0; this.options = { enableLighting: true, enableSpecularLighting: true, enableCPUClipping: true, useMatrixEnginePerspective: true, enableTanslucentZSort: false, shaderBulkBuild: true, enableAntialias: false, }; this.validSelectionBuffer = false; this.onDrawBGListeners = null; this.onExitDrawListeners = null; this.renderEvent = new MxeEvent(null); this.render3D = new MxeRender3D(this); this.render2D = new MxeRender2D(this); this.bgRenderFrame = new MxeFrame2D(null); this.bgRenderFrame.blendFactorSrc = 0x0302; //GL_SRC_ALPHA; this.bgRenderFrame.blendFactorDst = 0x0303; //GL_ONE_MINUS_SRC_ALPHA this.bgRenderFrame.blendFactorAlphaSrc = 0x0302; //GL_SRC_ALPHA this.bgRenderFrame.blendFactorAlphaDst = 0x0304; //GL_DST_ALPHA //shader sources this.FS_SRC = new Array(4); //selection fragment shader this.FS_SRC[0] = '\ precision mediump float;\ varying vec2 vTextureCoord;\ uniform sampler2D uTexture0;\ uniform vec4 uMatDiffuse;\ \ void main(void) {\ gl_FragColor = uMatDiffuse;\ }\ '; //basic this.FS_SRC[1] = '\ precision mediump float;\ uniform sampler2D uTexture0;\ uniform int uBlendMode0;\ uniform vec3 uFogColor;\ varying vec2 vTextureCoord;\ varying vec4 vDiffuseColor;\ varying vec4 vSpecularColor;\ varying lowp float vFogIntensity;\ vec4 textureColor;\ \ void main(void) {\ if (uBlendMode0 == 0){\ gl_FragColor = vDiffuseColor + vSpecularColor;\ }else{\ textureColor = texture2D(uTexture0, vec2(vTextureCoord.s, vTextureCoord.t));\ if(uBlendMode0 == 1){\ gl_FragColor = textureColor * vDiffuseColor + vSpecularColor;\ }else if(uBlendMode0 == 2){\ gl_FragColor = vec4(textureColor.rgb + vDiffuseColor.rgb, textureColor.a * vDiffuseColor.a) + vSpecularColor;\ }else if(uBlendMode0 == 3){\ textureColor = vec4(vec3(1.0 - textureColor.rgb), textureColor.a);\ gl_FragColor = textureColor * vDiffuseColor + vSpecularColor;\ }\ }\ gl_FragColor = vec4(mix(gl_FragColor.rgb, uFogColor, vFogIntensity), gl_FragColor.a);\ }\ '; //transparent discard(very slow) this.FS_SRC[2] = '\ precision mediump float;\ uniform sampler2D uTexture0;\ uniform int uBlendMode0;\ uniform vec3 uFogColor;\ varying vec2 vTextureCoord;\ varying vec4 vDiffuseColor;\ varying vec4 vSpecularColor;\ varying lowp float vFogIntensity;\ vec4 textureColor;\ \ void main(void) {\ if (uBlendMode0 == 0){\ gl_FragColor = vDiffuseColor + vSpecularColor;\ }else{\ textureColor = texture2D(uTexture0, vec2(vTextureCoord.s, vTextureCoord.t));\ if(uBlendMode0 == 1){\ gl_FragColor = textureColor * vDiffuseColor + vSpecularColor;\ }else if(uBlendMode0 == 2){\ gl_FragColor = vec4(textureColor.rgb + vDiffuseColor.rgb, textureColor.a * vDiffuseColor.a) + vSpecularColor;\ }else if(uBlendMode0 == 3){\ textureColor = vec4(vec3(1.0 - textureColor.rgb), textureColor.a);\ gl_FragColor = textureColor * vDiffuseColor + vSpecularColor;\ }\ }\ gl_FragColor = vec4(mix(gl_FragColor.rgb, uFogColor, vFogIntensity), gl_FragColor.a);\ if(gl_FragColor.a == 0.0) discard;\ }\ '; //for text this.FS_SRC[3] = '\ precision mediump float;\ uniform sampler2D uTexture0;\ uniform int uBlendMode0;\ uniform vec4 uTextColor;\ uniform vec4 uTextBgColor;\ varying vec2 vTextureCoord;\ varying vec4 vDiffuseColor;\ varying vec4 vSpecularColor;\ varying lowp float vFogIntensity;\ float textAlpha;\ \ void main(void) {\ textAlpha = texture2D(uTexture0, vec2(vTextureCoord.s, vTextureCoord.t)).r;\ gl_FragColor = mix(uTextBgColor, uTextColor, textAlpha);\ }\ '; this.VS_SRC = new Array(4); //selection vertex shader this.VS_SRC[0] = '\ attribute vec3 atVertex;\ attribute vec3 atNormal;\ attribute vec2 atUV0;\ attribute vec3 atWeight0;\ attribute vec3 atWeight1;\ \ uniform mat4 uWorldMatrix;\ uniform mat4 uViewMatrix;\ uniform mat4 uProjMatrix;\ uniform int uNBlend;\ uniform mat4 uBlendMatrix[5];\ uniform vec2 uTextureMargin0;\ uniform vec2 uTextureScale0;\ \ varying vec2 vTextureCoord;\ \ void main(void) {\ mat4 finalMatrix = uWorldMatrix;\ if(uNBlend > 1){\ finalMatrix = uWorldMatrix*atWeight0[0] + uBlendMatrix[0]*atWeight0[1] + uBlendMatrix[1]*atWeight0[2];\ }\ if(uNBlend > 3){\ finalMatrix = finalMatrix + uBlendMatrix[2]*atWeight1[0] + uBlendMatrix[3]*atWeight1[1] + uBlendMatrix[4]*atWeight1[2];\ }\ finalMatrix = uProjMatrix * uViewMatrix * finalMatrix;\ gl_Position = finalMatrix * vec4(atVertex, 1.0);\ vTextureCoord = atUV0*uTextureScale0 + uTextureMargin0;\ }\ '; //no lighting this.VS_SRC[1] = '\ attribute vec3 atVertex;\ attribute vec3 atNormal;\ attribute vec2 atUV0;\ attribute vec3 atWeight0;\ attribute vec3 atWeight1;\ attribute vec4 atVColor;\ \ uniform mat4 uWorldMatrix;\ uniform mat4 uProjMatrix;\ uniform mat4 uViewMatrix;\ uniform int uNBlend;\ uniform mat4 uBlendMatrix[5];\ uniform vec4 uMatDiffuse;\ uniform vec3 uMatEmissive;\ uniform float uFogStart;\ uniform float uFogEnd;\ uniform float uFogFactor;\ uniform vec2 uTextureMargin0;\ uniform vec2 uTextureScale0;\ uniform int uEnableVColor;\ varying vec2 vTextureCoord;\ varying vec4 vDiffuseColor;\ varying vec4 vSpecularColor;\ varying lowp float vFogIntensity;\ \ void main(void) {\ mat4 finalMatrix = uWorldMatrix;\ if(uNBlend > 1){\ finalMatrix = uWorldMatrix*atWeight0[0] + uBlendMatrix[0]*atWeight0[1] + uBlendMatrix[1]*atWeight0[2];\ }\ if(uNBlend > 3){\ finalMatrix = finalMatrix + uBlendMatrix[2]*atWeight1[0] + uBlendMatrix[3]*atWeight1[1] + uBlendMatrix[4]*atWeight1[2];\ }\ finalMatrix = uProjMatrix * uViewMatrix * finalMatrix;\ gl_Position = finalMatrix * vec4(atVertex, 1.0);\ vTextureCoord = atUV0*uTextureScale0 + uTextureMargin0;\ vec4 matDiffuse;\ if(uEnableVColor == 1)\ matDiffuse = atVColor;\ else\ matDiffuse = uMatDiffuse;\ vDiffuseColor = vec4(matDiffuse.rgb+uMatEmissive, matDiffuse.a);\ vSpecularColor = vec4(0.0);\ vFogIntensity = clamp((length(gl_Position.xyz)-uFogStart)*uFogFactor, 0.0, 1.0);\ }\ '; //basic vertex shader this.VS_SRC[2] = '\ attribute vec3 atVertex;\ attribute vec3 atNormal;\ attribute vec2 atUV0;\ attribute vec3 atWeight0;\ attribute vec3 atWeight1;\ attribute vec4 atVColor;\ \ uniform mat4 uWorldMatrix;\ uniform mat4 uViewMatrix;\ uniform mat4 uProjMatrix;\ uniform int uNBlend;\ uniform mat4 uBlendMatrix[5];\ uniform vec4 uMatDiffuse;\ uniform vec3 uMatEmissive;\ uniform vec3 uMatSpecular;\ uniform float uPower;\ uniform float uFogStart;\ uniform float uFogEnd;\ uniform float uFogFactor;\ uniform vec2 uTextureMargin0;\ uniform vec2 uTextureScale0;\ uniform int uEnableVColor;\ uniform int uLightCount;\ uniform vec3 uLightAmbient;\ uniform int uLightType[4];\ uniform vec3 uLightCol[4];\ uniform vec3 uLightDir[4];\ uniform vec3 uCameraPos;\ \ varying vec2 vTextureCoord;\ varying vec4 vDiffuseColor;\ varying vec4 vSpecularColor;\ varying lowp float vFogIntensity;\ \ vec3 addDiffuseLight(vec3 srcColor, vec3 normal, int lttype, vec3 ltdir, vec3 ltcol) {\ float norm = max(dot(-normal, ltdir), 0.0);\ return norm*ltcol+srcColor;\ }\ \ void main(void) {\ mat4 finalMatrix = uWorldMatrix;\ if(uNBlend > 1){\ finalMatrix = uWorldMatrix*atWeight0[0] + uBlendMatrix[0]*atWeight0[1] + uBlendMatrix[1]*atWeight0[2];\ }\ if(uNBlend > 3){\ finalMatrix = finalMatrix + uBlendMatrix[2]*atWeight1[0] + uBlendMatrix[3]*atWeight1[1] + uBlendMatrix[4]*atWeight1[2];\ }\ vec3 vertNormal = normalize(mat3(finalMatrix[0].xyz, finalMatrix[1].xyz, finalMatrix[2].xyz)*atNormal);\ vec3 vertDir = normalize((finalMatrix * vec4(atVertex, 1.0)).xyz - uCameraPos);\ finalMatrix = uProjMatrix * uViewMatrix * finalMatrix;\ gl_Position = finalMatrix * vec4(atVertex, 1.0);\ vTextureCoord = atUV0*uTextureScale0 + uTextureMargin0;\ vec3 diffColor = uLightAmbient;\ if(uLightCount > 0){\ diffColor = addDiffuseLight(diffColor, vertNormal, uLightType[0], uLightDir[0], uLightCol[0]);\ }\ if(uLightCount > 1){\ diffColor = addDiffuseLight(diffColor, vertNormal, uLightType[1], uLightDir[1], uLightCol[1]);\ }\ if(uLightCount > 2){\ diffColor = addDiffuseLight(diffColor, vertNormal, uLightType[2], uLightDir[2], uLightCol[2]);\ }\ if(uLightCount > 3){\ diffColor = addDiffuseLight(diffColor, vertNormal, uLightType[3], uLightDir[3], uLightCol[3]);\ }\ vec4 matDiffuse;\ if(uEnableVColor == 1)\ matDiffuse = atVColor;\ else\ matDiffuse = uMatDiffuse;\ vDiffuseColor = vec4(matDiffuse.rgb*diffColor+uMatEmissive, matDiffuse.a);\ vSpecularColor = vec4(0.0);\ vFogIntensity = clamp((length(gl_Position.xyz)-uFogStart)*uFogFactor, 0.0, 1.0);\ }\ '; //specular vertex shader this.VS_SRC[3] = '\ attribute vec3 atVertex;\ attribute vec3 atNormal;\ attribute vec2 atUV0;\ attribute vec3 atWeight0;\ attribute vec3 atWeight1;\ attribute vec4 atVColor;\ \ uniform mat4 uWorldMatrix;\ uniform mat4 uViewMatrix;\ uniform mat4 uProjMatrix;\ uniform int uNBlend;\ uniform mat4 uBlendMatrix[5];\ uniform vec4 uMatDiffuse;\ uniform vec3 uMatEmissive;\ uniform vec3 uMatSpecular;\ uniform float uPower;\ uniform float uFogStart;\ uniform float uFogEnd;\ uniform float uFogFactor;\ uniform vec2 uTextureMargin0;\ uniform vec2 uTextureScale0;\ uniform int uEnableVColor;\ uniform int uLightCount;\ uniform vec3 uLightAmbient;\ uniform int uLightType[4];\ uniform vec3 uLightCol[4];\ uniform vec3 uLightDir[4];\ uniform vec3 uCameraPos;\ \ varying vec2 vTextureCoord;\ varying vec4 vDiffuseColor;\ varying vec4 vSpecularColor;\ varying lowp float vFogIntensity;\ \ vec3 addSpecularLight(vec3 srcColor, vec3 normal, vec3 direction, int lttype, vec3 ltdir, vec3 ltcol, float shine) {\ if(shine == 0.0){\ return srcColor;\ }\ vec3 h = normalize(ltdir + direction);\ float specular = pow(max(dot(h, -normal), 0.0), shine);\ return srcColor + ltcol * uMatSpecular * specular;\ }\ \ vec3 addDiffuseLight(vec3 srcColor, vec3 normal, int lttype, vec3 ltdir, vec3 ltcol) {\ float norm = max(dot(-normal, ltdir), 0.0);\ return norm*ltcol+srcColor;\ }\ \ void main(void) {\ mat4 finalMatrix = uWorldMatrix;\ if(uNBlend > 1){\ finalMatrix = uWorldMatrix*atWeight0[0] + uBlendMatrix[0]*atWeight0[1] + uBlendMatrix[1]*atWeight0[2];\ }\ if(uNBlend > 3){\ finalMatrix = finalMatrix + uBlendMatrix[2]*atWeight1[0] + uBlendMatrix[3]*atWeight1[1] + uBlendMatrix[4]*atWeight1[2];\ }\ vec3 vertNormal = normalize(mat3(finalMatrix[0].xyz, finalMatrix[1].xyz, finalMatrix[2].xyz)*atNormal);\ vec3 vertDir = normalize((finalMatrix * vec4(atVertex, 1.0)).xyz - uCameraPos);\ finalMatrix = uProjMatrix * uViewMatrix * finalMatrix;\ gl_Position = finalMatrix * vec4(atVertex, 1.0);\ vTextureCoord = atUV0*uTextureScale0 + uTextureMargin0;\ vec3 diffColor = uLightAmbient;\ vec3 specColor = vec3(0.0, 0.0, 0.0);\ if(uLightCount > 0){\ diffColor = addDiffuseLight(diffColor, vertNormal, uLightType[0], uLightDir[0], uLightCol[0]);\ specColor = addSpecularLight(specColor, vertNormal, vertDir, uLightType[0], uLightDir[0], uLightCol[0], uPower);\ }\ if(uLightCount > 1){\ diffColor = addDiffuseLight(diffColor, vertNormal, uLightType[1], uLightDir[1], uLightCol[1]);\ specColor = addSpecularLight(specColor, vertNormal, vertDir, uLightType[1], uLightDir[1], uLightCol[1], uPower);\ }\ if(uLightCount > 2){\ diffColor = addDiffuseLight(diffColor, vertNormal, uLightType[2], uLightDir[2], uLightCol[2]);\ specColor = addSpecularLight(specColor, vertNormal, vertDir, uLightType[2], uLightDir[2], uLightCol[2], uPower);\ }\ if(uLightCount > 3){\ diffColor = addDiffuseLight(diffColor, vertNormal, uLightType[3], uLightDir[3], uLightCol[3]);\ specColor = addSpecularLight(specColor, vertNormal, vertDir, uLightType[3], uLightDir[3], uLightCol[3], uPower);\ }\ \ vec4 matDiffuse;\ if(uEnableVColor == 1)\ matDiffuse = atVColor;\ else\ matDiffuse = uMatDiffuse;\ vDiffuseColor = vec4(matDiffuse.rgb*diffColor+uMatEmissive, matDiffuse.a);\ vSpecularColor = vec4(specColor, 0.0);\ vFogIntensity = clamp((length(gl_Position.xyz)-uFogStart)*uFogFactor, 0.0, 1.0);\ }\ '; this.shaderPrograms = null; this.currentShaderProgram = null; this.fsArray = null; this.vsArray = null; this.SHADER_FAIL = { SHADER_FAIL_OBJECT: 1 }; this.ALT_SHADER_TABLE = [ //selection, normal, discard, text fs/vs [null, null, null, null ], //selection [null, null, null, null ], //no lighting [null, [1,1], [1,2], null ], //diffuse [null, [2,1], [2,2], null ], //specular ]; }; MxeRender.def = { MAX_BONE: 6, MAX_LIGHT: 4, MAX_TEXTURE: 8, MAX_TEXTURE_UV: 3, MAX_SHADER_USER_ARRAY: 10, MAX_SHADER_RANDOM: 0x7fff, RM_DEFAULT: 0, RM_SELECTION: 1, }; MxeRender.prototype.compileShader = function(gl, stype, srcStr) { var gl = this.gl; var shader = gl.createShader(stype); gl.shaderSource(shader, srcStr); gl.compileShader(shader); var logstr = gl.getShaderInfoLog(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS) || logstr.length > 0) { MxeUtil.log(logstr); return this.SHADER_FAIL; } return shader; }; MxeRender.prototype.setBackground = function(cast) { var bgFrame = this.bgRenderFrame; if(cast === null){ bgFrame.setCast(null); return; } bgFrame.setCast(cast); //if(cast.castType === MxeCast.CT_BITMAP || cast.castType === MxeCast.CT_TEXTURE) bgFrame.cast.prepare(); }; MxeRender.prototype.setupShaderVariableLocations = function(shaderProgram) { var gl = this.gl; var i; var name; var num; shaderProgram.attributes = {}; shaderProgram.maxAttribute = -1; var attrNames = ["atVertex", "atNormal", "atWeight0", "atWeight1", "atVColor",]; var index; for(i in attrNames){ name = attrNames[i]; index = shaderProgram.attributes[name] = gl.getAttribLocation(shaderProgram, name); if(index > shaderProgram.maxAttribute) shaderProgram.maxAttribute = index; } shaderProgram.attributes.atUV = new Array(MxeRender.def.MAX_TEXTURE_UV); for(num=0; num<MxeRender.def.MAX_TEXTURE_UV; num++){ index = shaderProgram.attributes.atUV[num] = gl.getAttribLocation(shaderProgram, "atUV"+num); if(index > shaderProgram.maxAttribute) shaderProgram.maxAttribute = index; } ++shaderProgram.maxAttribute; shaderProgram.uniforms = {}; var uniNames = [ "uWorldMatrix", "uViewMatrix", "uProjMatrix", "uViewProjMatrix", "uWorldViewProjMatrix", "uNBlend", "uBlendMatrix", "uMatDiffuse", "uMatEmissive", "uMatSpecular", "uPower", "uFogColor", "uFogStart", "uFogEnd", "uFogFactor", "uTextColor", "uTextBgColor", "uLightCount", "uLightAmbient", "uLightType", "uLightCol", "uLightAtt0", "uLightAtt1", "uLightAtt2", "uLightRange", "uSpotExponent", "uSpotCutoff", //"uLightMatrix", "uLightDir", "uLightPos", "uCameraPos", "uUserFloatArray", "uUserIntArray", "uTime", "uRandom", "uEnableVColor", ]; for(i in uniNames){ name = uniNames[i]; shaderProgram.uniforms[name] = gl.getUniformLocation(shaderProgram, name); } shaderProgram.uniforms.uTexture = new Array(MxeRender.def.MAX_TEXTURE); for(num=0; num<MxeRender.def.MAX_TEXTURE; num++){ shaderProgram.uniforms.uTexture[num] = gl.getUniformLocation(shaderProgram, "uTexture" + num); } shaderProgram.uniforms.uBlendMode = new Array(MxeRender.def.MAX_TEXTURE); for(num=0; num<MxeRender.def.MAX_TEXTURE; num++){ shaderProgram.uniforms.uBlendMode[num] = gl.getUniformLocation(shaderProgram, "uBlendMode" + num); } shaderProgram.uniforms.uBlendValue = new Array(MxeRender.def.MAX_TEXTURE); for(num=0; num<MxeRender.def.MAX_TEXTURE; num++){ shaderProgram.uniforms.uBlendValue[num] = gl.getUniformLocation(shaderProgram, "uBlendValue" + num); } shaderProgram.uniforms.uTextureMargin = new Array(MxeRender.def.MAX_TEXTURE); for(num=0; num<MxeRender.def.MAX_TEXTURE; num++){ shaderProgram.uniforms.uTextureMargin[num] = gl.getUniformLocation(shaderProgram, "uTextureMargin" + num); } shaderProgram.uniforms.uTextureScale = new Array(MxeRender.def.MAX_TEXTURE); for(num=0; num<MxeRender.def.MAX_TEXTURE; num++){ shaderProgram.uniforms.uTextureScale[num] = gl.getUniformLocation(shaderProgram, "uTextureScale" + num); } shaderProgram.uniforms.uWrapMode = new Array(MxeRender.def.MAX_TEXTURE); for(num=0; num<MxeRender.def.MAX_TEXTURE; num++){ shaderProgram.uniforms.uWrapMode[num] = gl.getUniformLocation(shaderProgram, "uWrapMode" + num); } }; MxeRender.prototype.createShaderProgram = function(fsIndex, vsIndex) { var gl = this.gl; var fs = this.fsArray[fsIndex]; if(! fs) fs = this.fsArray[fsIndex] = this.compileShader(gl, gl.FRAGMENT_SHADER, this.FS_SRC[fsIndex]); if(fs === this.SHADER_FAIL) return this.SHADER_FAIL; var vs = this.vsArray[vsIndex]; if(! vs) vs = this.vsArray[vsIndex] = this.compileShader(gl, gl.VERTEX_SHADER, this.VS_SRC[vsIndex]); if(vs === this.SHADER_FAIL) return this.SHADER_FAIL; //link shader var shaderProgram = gl.createProgram(); this.shaderPrograms[vsIndex*this.FS_SRC.length+fsIndex] = shaderProgram; gl.attachShader(shaderProgram, vs); gl.attachShader(shaderProgram, fs); gl.linkProgram(shaderProgram); if (! gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { MxeUtil.log("Could not initialise shader("+fsIndex+","+vsIndex+").\n"); MxeUtil.log(gl.getProgramInfoLog(shaderProgram)); return this.SHADER_FAIL; } this.setupShaderVariableLocations(shaderProgram); return shaderProgram; }; MxeRender.prototype.initDefaultShaders = function() { this.fsArray = new Array(this.FS_SRC.length); this.vsArray = new Array(this.VS_SRC.length); this.shaderPrograms = new Array(this.FS_SRC.length*this.VS_SRC.length); if(! this.options.shaderBulkBuild) return; var gl = this.gl; var i, j; //create all shaders var FV_LINK_TABLE = [ //selection, normal, discard, text fs/vs [true , false, false, false ], //selection [false, true , true , true ], //no lighting [false, true , true , false ], //diffuse [false, true , true, false ], //specular ]; for(i=0; i<this.VS_SRC.length; i++){ for(j=0; j<this.FS_SRC.length; j++){ if(! FV_LINK_TABLE[i][j]) continue; this.shaderPrograms[i*this.FS_SRC.length+j] = this.createShaderProgram(j, i); } } }; MxeRender.prototype.setShaderProgram = function(shader) { var gl = this.gl; var i; if(this.currentShaderProgram !== null){ for(i=0; i<this.currentShaderProgram.maxAttribute; i++){ gl.disableVertexAttribArray(i); } } if(this.currentShaderProgram === shader) return; gl.useProgram(shader); this.currentShaderProgram = shader; }; MxeRender.prototype.requestShaderProgram = function(requestOptions) { var fsType; var vsType; if(requestOptions.renderMode === MxeRender.def.RM_SELECTION){ //selection shader fsType = vsType = 0; }else if(requestOptions.isText){ fsType = 3; vsType = 1; }else{ fsType = 1; if(requestOptions.alphaType & 1){ //HAS_TRANSPARENT fsType = 2; //transparent discard } vsType = 1; if(requestOptions.useLighting){ vsType = 2; if(requestOptions.useSpecular){ vsType = 3; } } } while(true) { var shader = this.shaderPrograms[vsType*this.FS_SRC.length+fsType]; if(! shader && ! this.options.shaderBulkBuild) shader = this.createShaderProgram(fsType, vsType); if(! shader || shader === this.SHADER_FAIL){ var altType = this.ALT_SHADER_TABLE[vsType][fsType]; if(altType !== null){ vsType = altType[0]; fsType = altType[1]; continue; }else{ throw new MxeException("invalid shader["+vsType+","+fsType+"]"); } } break; } return shader; }; MxeRender.prototype.createFrameBuffer = function() { var gl = this.gl; var canvas = this.player.canvas; this.frameBuffer = gl.createFramebuffer(); if(this.frameBuffer === null) return; //no context case this.frameBuffer.width = canvas.width; this.frameBuffer.height = canvas.height; gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer); this.renderDepthBuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderDepthBuffer); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, canvas.width, canvas.height); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.renderDepthBuffer); gl.bindRenderbuffer(gl.RENDERBUFFER, null); this.renderRGBBuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderRGBBuffer); gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA4, canvas.width, canvas.height); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, this.renderRGBBuffer); gl.bindRenderbuffer(gl.RENDERBUFFER, null); var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (status !== gl.FRAMEBUFFER_COMPLETE) { MxeUtil.log("Could not initialize frame buffer."); } gl.bindFramebuffer(gl.FRAMEBUFFER, null); }; MxeRender.prototype.deleteFrameBuffer = function() { var gl = this.gl; if(this.frameBuffer !== null){ gl.deleteFramebuffer(this.frameBuffer); this.frameBuffer = null; } if(this.renderDepthBuffer !== null){ gl.deleteRenderbuffer(this.renderDepthBuffer); this.renderDepthBuffer = null; } if(this.renderRGBBuffer !== null){ gl.deleteRenderbuffer(this.renderRGBBuffer); this.renderRGBBuffer = null; } }; MxeRender.prototype.updateViewport = function() { var gl = this.gl; var canvas = this.player.canvas; if(this.viewportWidth === canvas.width && this.viewportHeight === canvas.height) return; this.viewportWidth = canvas.width; this.viewportHeight = canvas.height; this.deleteFrameBuffer(); this.createFrameBuffer(); }; MxeRender.prototype.initGL = function() { //for GPU picking-- this.frameBuffer = null; this.renderDepthBuffer = null; this.renderRGBBuffer = null; //--for GPU picking var gl = null; var canvas = this.player.canvas; try { gl = this.gl = canvas.getContext("experimental-webgl", { antialias: this.options.enableAntialias }); } catch (e) { } if (! gl) gl = this.gl = null; if(gl === null){ MxeUtil.log("Could not initialise WebGL."); return false; } this.createFrameBuffer(); //set default gl.cullFace(gl.FRONT); this.initDefaultShaders(); this.render3D.initGL(gl); this.render2D.initGL(gl); return true; }; MxeRender.prototype.updateSelectionBuffer = function() { if(this.validSelectionBuffer) return; var gl = this.gl; gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer); this.drawScene(MxeRender.def.RM_SELECTION); gl.bindFramebuffer(gl.FRAMEBUFFER, null); this.validSelectionBuffer = true; }; MxeRender.prototype.prepare = function() { this.render3D.prepare(); this.render2D.prepare(); }; MxeRender.prototype.addEventListener = function(eventType, listener, userObj) { if(eventType === "ondrawbg"){ if(this.onDrawBGListeners === null){ this.onDrawBGListeners = new Array(); } this.onDrawBGListeners.push([listener, userObj]); return true; } if(eventType === "onexitdraw"){ if(this.onExitDrawListeners === null){ this.onExitDrawListeners = new Array(); } this.onExitDrawListeners.push([listener, userObj]); return true; } return false; }; MxeRender.prototype.renderPathEventHandler = function(listeners, renderMode) { if(listeners === null) return false; if(renderMode !== MxeRender.def.RM_DEFAULT) return false; var i; var func; var result = false; var e = this.renderEvent; e.score = this; for(i=0; i<listeners.length; i++){ func = listeners[i][0]; e.userObj = listeners[i][1]; e.gl = this.gl; result = func.apply(e.userObj, [e]) || result; } return result; }; MxeRender.prototype.drawBackground = function(renderMode, gl){ gl.depthMask(true); gl.disable(gl.SCISSOR_TEST); if(renderMode === MxeRender.def.RM_DEFAULT){ var bgColor; var bgAlpha; var cameraTrack = this.render3D.currentCameraTrack; if(cameraTrack !== null && cameraTrack.frame.getCast().fogEnable){ bgColor = cameraTrack.frame.getCast().fogColor; bgAlpha = this.player.contents.backgroundColor[3]; }else{ bgColor = this.player.contents.backgroundColor; bgAlpha = this.player.contents.backgroundColor[3]; } gl.clearColor(bgColor[0], bgColor[1], bgColor[2], bgAlpha); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); var bgFrame = this.bgRenderFrame; if(bgFrame.cast !== null){ var castScalable = bgFrame.cast.scalable; bgFrame.cast.scalable = true; //force scalable bgFrame.alpha = 1.0; bgFrame.visible = true; bgFrame.siz[0] = this.viewportWidth/bgFrame.cast.getWidth(); bgFrame.siz[1] = this.viewportHeight/bgFrame.cast.getHeight(); bgFrame.siz[2] = 1.0; bgFrame.pos[0] = 0.0; bgFrame.pos[1] = 0.0; bgFrame.pos[2] = 0.0; bgFrame.magFilter = gl.LINEAR; bgFrame.minFilter = gl.LINEAR; bgFrame.prepareRender(this); this.render2D.drawFrame(bgFrame, renderMode, 0); bgFrame.cast.scalable = castScalable; //restore } }else if(renderMode === MxeRender.def.RM_SELECTION){ gl.clearColor(1.0, 1.0, 1.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } } MxeRender.prototype.drawScene = function(renderMode) { var gl = this.gl; var doSkip = false; //set viewport gl.viewport(0, 0, this.viewportWidth, this.viewportHeight); doSkip = this.renderPathEventHandler(this.onDrawBGListeners, renderMode); if(! doSkip){ this.drawBackground(renderMode, gl); } doSkip = false; if(! doSkip){ var selectionOffset = 0; selectionOffset+= this.render2D.drawBackRenderList(renderMode, selectionOffset); if(this.render3D.currentCameraTrack === null){ //no camera }else{ selectionOffset+= this.render3D.drawRenderList(renderMode, selectionOffset); } selectionOffset+= this.render2D.drawFrontRenderList(renderMode, selectionOffset); } doSkip = this.renderPathEventHandler(this.onExitDrawListeners, renderMode); gl.flush(); }; MxeRender.prototype.getSelectionID = function(mouseX, mouseY) { var gl = this.gl; var stageH = this.viewportHeight; this.updateSelectionBuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer); var pix = new Uint8Array(4); gl.readPixels(mouseX, stageH-mouseY-1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pix); gl.bindFramebuffer(gl.FRAMEBUFFER, null); //MxeUtil.log(pix[3]+":"+pix[2]+":"+pix[1]+":"+pix[0]); /* //32bit case var selectionID = (pix[0]<<16) + (pix[1]<<8) + pix[2]; if(selectionID === 0xffffff){ */ //16bit case pix[0] = pix[0]>>4; pix[1] = pix[1]>>4; pix[2] = pix[2]>>4; pix[3] = pix[3]>>4; return (pix[3]<<12) + (pix[2]<<8) + (pix[1]<<4) + pix[0]; }; MxeRender.prototype.getRenderItemBySelectionID = function(selectionID) { if(selectionID === 0xffff){ //no object return null; } if(selectionID < this.render2D.backRenderCount) return this.render2D.backRenderList[selectionID]; selectionID-= this.render2D.backRenderCount; if(selectionID < this.render3D.renderCount) return this.render3D.renderList[selectionID]; selectionID-= this.render3D.renderCount; if(selectionID < this.render3D.alphaRenderCount) return this.render3D.alphaRenderList[selectionID]; selectionID-= this.render3D.alphaRenderCount; if(selectionID < this.render2D.frontRenderCount) return this.render2D.frontRenderList[selectionID]; //error MxeUtil.log("Illegal selection ID. ID=" + selectionID); return null; }; MxeRender.prototype.pickUp = function(x, y) { var renderItem = this.getRenderItemBySelectionID(this.getSelectionID(x, y)); if(renderItem === null){ //no object or error return null; } if(renderItem[0] === 0) return renderItem[2][0]; if(1 <= renderItem[0] && renderItem[0] <=3) return renderItem[1]; //CT_TEXTURE(billboard), CT_BITMAP(bitmap), CT_TEXT(text) if(renderItem[0] === 29) return renderItem[1]; //CT_PROCEDURAL //not support return null; }; MxeShaderRequestOptions = function() { this.renderMode = MxeRender.def.RM_DEFAULT; this.alphaType = 0; this.useLighting = false; this.useSpecular = false; this.isText = false; }; //CModel var MxeModel = function() { this.initialize.apply(this, arguments); }; MxeModel.prototype = Object.create(MxeCast.prototype); MxeModel.prototype.constructor = MxeModel; MxeModel.prototype.initialize = function(contents, index, label) { MxeCast.prototype.initialize.apply(this, arguments); this.castType = MxeCast.def.CT_MODEL; this.sectors = null; this.sectorsL = null; this.shaderUserFloatArray = new Float32Array(MxeRender.def.MAX_SHADER_USER_ARRAY); this.shaderUserIntArray = new Int32Array(MxeRender.def.MAX_SHADER_USER_ARRAY); }; MxeModel.prototype.initGL = function(gl) { if(this.sectors === null) return; for(var i=0; i<this.sectors.length; i++){ this.sectors[i].initGL(gl); } }; //CSector var MxeSector = function() { this.initialize.apply(this, arguments); }; MxeSector.prototype.initialize = function(model, index, label) { this.model = model; this.label = label; this.index = index; this.isSkin = false; //this.parents = null; this.material = null; this.vertexSrc = null; this.positionBuffer = null; this.normalBuffer = null; this.colorBuffer = null; this.uvBuffer = null; this.indexBuffer = null; this.indexLength = 0; this.indexOffset = 0; this.boneWeightBuffer = null; this.baseMatrix = null; this.sectorCenter = null; this.boxMin = null; this.boxMax = null; this.polygonNormals = null; //for getCrossPoint }; MxeSector.prototype.setVertices = function(vertexSrc) { this.vertexSrc = vertexSrc; }; MxeSector.prototype.initGL = function(gl) { if(this.vertexSrc === null) return; var vertLength = this.vertexSrc.position.length / 3; if(vertLength === 0) return; this.positionBuffer = gl.createBuffer(); if(this.positionBuffer !== null){ gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, this.vertexSrc.position, gl.STATIC_DRAW); this.positionBuffer.itemSize = 3; this.positionBuffer.numItems = vertLength; } this.normalBuffer = gl.createBuffer(); if(this.normalBuffer !== null){ gl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer); gl.bufferData(gl.ARRAY_BUFFER, this.vertexSrc.normal, gl.STATIC_DRAW); this.normalBuffer.itemSize = 3; this.normalBuffer.numItems = vertLength; } if(this.vertexSrc.texture != null){ //undefined ok this.uvBuffer = new Array(this.vertexSrc.texture.length); for(var i=0; i<this.vertexSrc.texture.length; i++){ if(this.vertexSrc.texture[i] == null){ this.uvBuffer[i] = null; continue; } this.uvBuffer[i] = gl.createBuffer(); if(this.uvBuffer[i] !== null){ gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer[i]); gl.bufferData(gl.ARRAY_BUFFER, this.vertexSrc.texture[i], gl.STATIC_DRAW); this.uvBuffer[i].itemSize = 2; this.uvBuffer[i].numItems = vertLength; } } } if(this.vertexSrc.weight != null){ //undefined ok this.boneWeightBuffer = gl.createBuffer(); if(this.boneWeightBuffer !== null){ gl.bindBuffer(gl.ARRAY_BUFFER, this.boneWeightBuffer); gl.bufferData(gl.ARRAY_BUFFER, this.vertexSrc.weight, gl.STATIC_DRAW); this.boneWeightBuffer.itemSize = this.vertexSrc.weight.length/vertLength; this.boneWeightBuffer.numItems = vertLength; } } if(this.vertexSrc.color != null){ this.colorBuffer = gl.createBuffer(); if(this.colorBuffer !== null){ gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, this.vertexSrc.color, gl.STATIC_DRAW); this.colorBuffer.itemSize = 4; this.colorBuffer.numItems = vertLength; } } this.indexBuffer = gl.createBuffer(); if(this.indexBuffer !== null){ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.vertexSrc.index, gl.STATIC_DRAW); this.indexBuffer.itemSize = 1; this.indexBuffer.numItems = this.vertexSrc.index.length; } }; MxeSector.prototype.prepareRender = function(render, frame) { for(var i=0; i<this.material.textureInfo.length; i++){ var textureInfo = this.material.textureInfo[i]; if(textureInfo === null) continue; var textureCast = textureInfo.cast; if(textureCast !== null){ textureCast.prepareRender(render, frame); } } if(this.material.shaderCast !== null){ this.material.shaderCast.prepareRender(render, frame); } }; MxeSector.prototype.calcPolygonNormals = function() { if(this.vertexSrc == null) return; if(this.vertexSrc.position === null || this.vertexSrc.position.length === 0) return; //ghost try{ MxeGeom.useTemporary(); var verts = this.vertexSrc.position; var polys = this.vertexSrc.index; var polyIdx = 0; var polyCount; var normIdx = 0; var isStripped = false; //TODO bool isStripped = (lpSector->mlpSectData->SectorOption & 0x01); // for stripped polygon if(isStripped){ polyCount = polys.length - 2; }else{ polyCount = polys.length/3; } this.polygonNormals = new Float32Array(polyCount*3); var p0, p1, p2; var polyVert0 = MxeGeom.vec3.getTemporary(); var polyVert1 = MxeGeom.vec3.getTemporary(); var polyVert2 = MxeGeom.vec3.getTemporary(); var polyNorm = MxeGeom.vec3.getTemporary(); var workVec0 = MxeGeom.vec3.getTemporary(); for(var i = 0; i < polyCount; i++, normIdx+=3){ //TODO 4poly if(isStripped && (i % 2)!==0){ p0 = polys[polyIdx+2]; p1 = polys[polyIdx+1]; p2 = polys[polyIdx+0]; } else{ p0 = polys[polyIdx+1]; p1 = polys[polyIdx+2]; p2 = polys[polyIdx+0]; } if (isStripped) polyIdx++; else polyIdx+= 3; //mIs4PolyOnly ? 4 : 3; if ((p0 === p1) || (p0 === p2) || (p1 === p2)) continue; polyVert0[0] = verts[p0*3]; polyVert0[1] = verts[p0*3+1]; polyVert0[2] = verts[p0*3+2]; polyVert1[0] = verts[p1*3]; polyVert1[1] = verts[p1*3+1]; polyVert1[2] = verts[p1*3+2]; polyVert2[0] = verts[p2*3]; polyVert2[1] = verts[p2*3+1]; polyVert2[2] = verts[p2*3+2]; vec3.cross(vec3.subtract(polyVert1, polyVert0, polyNorm), vec3.subtract(polyVert2, polyVert1, workVec0)); vec3.normalize(polyNorm); this.polygonNormals[normIdx] = polyNorm[0]; this.polygonNormals[normIdx+1] = polyNorm[1]; this.polygonNormals[normIdx+2] = polyNorm[2]; } } finally { MxeGeom.releaseTemporary(); } }; //CSector セクター情報の中で「テクスチャーグループ」設定により共有されるもの ≒ マテリアル情報 var MxeMaterial = function() { this.initialize.apply(this, arguments); }; MxeMaterial.def = { HAS_TRANSPARENT : 1, HAS_TRANSLUCENT : 2, }; MxeMaterial.prototype.initialize = function() { //public this.textureInfo = [null]; this.color = null; this.specularColor = null; this.emissionColor = null; this.shininess = 0.0; this.doubleSided = false; this.clippingValue = 1.0; this.depthTest = true; this.depthMask = true; this.useBlending = false; this.blendFactorSrc = 0; this.blendFactorDst = 0; this.blendFactorAlphaSrc = 0; this.blendFactorAlphaDst = 0; this.enableLighting = true; this.enableFog = true; this.shaderCast = null; //protected this.hasTransrucentVertex = false; //半透明頂点を持つかどうか。持つなら半透明として扱う。 }; //CAMERA var MxeCamera = function() { this.initialize.apply(this, arguments); }; MxeCamera.prototype = Object.create(MxeCast.prototype); MxeCamera.prototype.constructor = MxeCamera; MxeCamera.prototype.initialize = function(contents, index, label) { MxeCast.prototype.initialize.apply(this, arguments); this.castType = MxeCast.def.CT_CAMERA; //CAMERADATA-- //this.zoomFactor = 0.0; this.near = 0.0; // front clipping this.far = 0.0; // rear clipping this.fogEnable = false; this.fogColor = null; this.fogNear = 0.0; this.fogFar = 0.0; this.fogDensity = 0.0; //this.propChanged; // property changed by script //int Tag; //BOOL MaterialPropOff;// disable material property this.cameraAngle = 0.0; // Substitution of ZoomFactor V2.53 added //BOOL SkinClipOff; //--CAMERADATA this.fogFactor = 0.0; //for shader }; MxeCamera.prototype.prepareRender = function(render, frame) { if(this.fogEnable && this.fogNear < this.fogFar) this.fogFactor = 1.0/(this.fogFar - this.fogNear); else this.fogFactor = 0.0; }; //LIGHT var MxeLight = function() { this.initialize.apply(this, arguments); }; MxeLight.def = { TYPE_DIRECTIONAL: 0, TYPE_POINT: 1, TYPE_SPOT: 2, TYPE_AMBIENT: 3, }; MxeLight.prototype = Object.create(MxeCast.prototype); MxeLight.prototype.constructor = MxeLight; MxeLight.prototype.initialize = function(contents, index, label) { MxeCast.prototype.initialize.apply(this, arguments); this.castType = MxeCast.def.CT_MODEL; //LIGHTDATA-- this.type = 0; this.color = null; //this.dropOffType = 0; this.dropOffRate1 = 0.0; // SDK-B setting, 1'st term this.dropOffRate2 = 0.0; // SDK-A setting, 2'nd term this.dropOffRate3 = 0.0; // SDK-C setting, constant term this.distance = 0.0; this.cutOffAngle = 0.0; this.cutOffAnglePhi = 0.0; //--LIGHTDATA }; // var MxeCast2D = function() { this.initialize.apply(this, arguments); }; MxeCast2D.prototype = Object.create(MxeCast.prototype); MxeCast2D.prototype.constructor = MxeCast2D; MxeCast2D.prototype.initialize = function(contents, index, label) { MxeCast.prototype.initialize.apply(this, arguments); this.alphaType = 0; this.scalable = false; this.rotatable = false; this.alphaBlendable = false; this.magFilter = 0x2600; //GL_NEAREST this.minFilter = 0x2600; //GL_NEAREST this.behind3D = false; this.rotateCenter = null; this.valid = false; this.presetWidth = 0; this.presetHeight = 0; }; MxeCast2D.prototype.prepare = function() { }; MxeCast2D.prototype.getPrepared = function() { return false; }; MxeCast2D.prototype.getWidth = function() { return 0; }; MxeCast2D.prototype.getHeight = function() { return 0; }; MxeCast2D.prototype.invalidate = function() { this.valid = false; }; MxeCast2D.prototype.update = function(ctx, gl) { this.valid = true; }; // var MxeBillboardInfo = function() { this.initialize.apply(this, arguments); }; MxeBillboardInfo.prototype.initialize = function() { this.pos = null; this.siz = null; this.material = new MxeMaterial(); this.material.enableLighting = false; this.material.blendFactorSrc = 0x0302, //GL_SRC_ALPHA this.material.blendFactorDst = 0x0303, //GL_ONE_MINUS_SRC_ALPHA this.material.blendFactorAlphaSrc = 0x0302, //GL_SRC_ALPHA this.material.blendFactorAlphaDst = 0x0304, //GL_DST_ALPHA this.material.emissionColor = new Float32Array([0.0, 0.0, 0.0]); this.material.specularColor = new Float32Array([0.0, 0.0, 0.0]); var bbtexInfo; this.material.textureInfo[0] = bbtexInfo = new MxeSectorTextureInfo(); bbtexInfo.wrap_s = 0x812f; //GL_CLAMP_TO_EDGE bbtexInfo.wrap_t = 0x812f; //GL_CLAMP_TO_EDGE }; // var MxeBitmapBase = function() { this.initialize.apply(this, arguments); }; MxeBitmapBase.prototype = Object.create(MxeCast2D.prototype); MxeBitmapBase.prototype.constructor = MxeBitmapBase; MxeBitmapBase.prototype.initialize = function(contents, index, label) { MxeCast2D.prototype.initialize.apply(this, arguments); this.imageSrc = null; this.image = null; this.glTexture = null; this.prepareStatus = 0; //0:init 1:preparing 2:prepared -1:error this.loadingImage = null; //TEXBILLBOARDDATA-- this.billboardInfo = null; //--TEXBILLBOARDDATA }; MxeBitmapBase.prototype.getCurrentGL = function() { return this.contents.player.render.gl }; MxeBitmapBase.prototype.getPrepared = function() { return this.prepareStatus === 2; }; MxeBitmapBase.prototype.getWidth = function() { if(this.prepareStatus === 2) return this.image.width; return 0; }; MxeBitmapBase.prototype.getHeight = function() { if(this.prepareStatus === 2) return this.image.height; return 0; }; MxeBitmapBase.prototype.deleteImage = function(gl) { if(gl == null) gl = this.getCurrentGL(); this.prepareStatus = 0; if(this.glTexture) gl.deleteTexture(this.glTexture); // this.image = null; this.glTexture = null; }; MxeBitmapBase.prototype.cancelLoading = function() { if(this.loadingImage !== null){ if(this.prepareStatus === 1) this.prepareStatus = 0; this.loadingImage = null; return; } }; MxeBitmapBase.prototype.prepare = function() { if(this.prepareStatus !== 0){ return; } if(this.loadingImage !== null){ return; } if(this.imageSrc === null) return; this.loadImage(this.imageSrc); }; MxeBitmapBase.prototype.setImageEventListener = function(image) { var cast = this; image.addEventListener( "load", function() { if(image !== cast.loadingImage) return; cast.deleteImage(cast.getCurrentGL()); cast.createTexture(cast.getCurrentGL(), cast.loadingImage); cast.loadingImage = null; }, false); image.addEventListener( "error", function() { cast.prepareStatus = -1; cast.loadingImage = null; }, false); }; MxeBitmapBase.prototype.loadImage = function(src) { this.imageSrc = src; if(this.imageSrc === null) return; if(this.image !== null){ if(this.imageSrc === this.image.src) return; } this.cancelLoading(); if(this.prepareStatus === 0) this.prepareStatus = 1; var image = this.loadingImage = new Image(); //image.onload = this.getOnLoadListener(this, image); //image.onerror = this.getOnErrorListener(this); this.setImageEventListener(image); image.src = this.imageSrc; }; MxeBitmapBase.prototype.setImage = function(image) { if(image.src) this.imageSrc = image.src; else this.imageSrc = null; if(image.complete === false){ this.loadingImage = image; //image.onload = this.getOnLoadListener(this, image); //image.onerror = this.getOnErrorListener(this); this.setImageEventListener(image); }else{ this.deleteImage(this.getCurrentGL()); this.loadingImage = null; this.createTexture(this.getCurrentGL(), image); } }; MxeBitmapBase.prototype.getImage = function() { return this.image; }; MxeBitmapBase.prototype.setGLTexture = function(glTexture) { this.deleteImage(this.getCurrentGL()); this.glTexute = glTexture; }; MxeBitmapBase.prototype.getGLTexture = function() { return this.glTexture; }; MxeBitmapBase.prototype.createTexture = function(gl, image) { if(! gl) gl = this.getCurrentGL(); if(! gl){ this.glTexture = null; return; } this.glTexture = gl.createTexture(); this.image = image; this.prepareStatus = 2; this.textureWidth = 1; this.textureHeight = 1; while(this.textureWidth < image.width) this.textureWidth*= 2; while(this.textureHeight < image.height) this.textureHeight*= 2; //TODO gl error check gl.bindTexture(gl.TEXTURE_2D, this.glTexture); //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); if(this.textureWidth === image.width && this.textureHeight === image.height){ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.image); }else{ var textureArray = new Uint8Array(this.textureWidth*this.textureHeight*4); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureWidth, this.textureHeight, 0, gl.RGBA, gl.UNSIGNED_BYTE, textureArray); gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.image); } gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.magFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.minFilter); gl.bindTexture(gl.TEXTURE_2D, null); }; MxeBitmapBase.prototype.initGL = function(gl) { if(this.image !== null){ //do not deleteImage on this case(start, restore) this.createTexture(gl, this.image); } }; MxeBitmapBase.prototype.prepareRender = function(render, frame) { this.prepare(); }; //CBitmap var MxeBitmap = function() { this.initialize.apply(this, arguments); }; MxeBitmap.prototype = Object.create(MxeBitmapBase.prototype); MxeBitmap.prototype.constructor = MxeBitmap; MxeBitmap.prototype.initialize = function(contents, index, label) { MxeBitmapBase.prototype.initialize.apply(this, arguments); this.castType = MxeCast.def.CT_BITMAP; }; //CTexture var MxeTexture = function() { this.initialize.apply(this, arguments); }; MxeTexture.prototype = Object.create(MxeBitmapBase.prototype); MxeTexture.prototype.constructor = MxeTexture; MxeTexture.prototype.initialize = function(contents, index, label) { MxeBitmapBase.prototype.initialize.apply(this, arguments); this.castType = MxeCast.def.CT_TEXTURE; }; //TEXTUREINFO var MxeSectorTextureInfo = function() { this.initialize.apply(this, arguments); }; MxeSectorTextureInfo.prototype.initialize = function() { this.cast = null; // texture cast this.option = 0; // 0:normal, 1:movie, 2:bump this.mapType = 0; // TextureMap form this.blendValue = 1.0; this.blendMode = 0; // 0:modurate, 1:add, 2:sub this.wrap_s = 0x2901; //GL_REPEAT this.wrap_t = 0x2901; //GL_REPEAT //not implements this.repeat = new Float32Array([1.0, 1.0]); //xdiv, ydiv this.offset = new Float32Array([0.0, 0.0]); //xofs, yofs }; //MOVIE var MxeMovie = function() { this.initialize.apply(this, arguments); }; MxeMovie.prototype = Object.create(MxeBitmapBase.prototype); MxeMovie.prototype.constructor = MxeMovie; MxeMovie.prototype.initialize = function(contents, index, label) { MxeBitmapBase.prototype.initialize.apply(this, arguments); this.castType = MxeCast.def.CT_AVI; }; //SHADER var MxeShader = function() { this.initialize.apply(this, arguments); }; MxeShader.prototype = Object.create(MxeCast.prototype); MxeShader.prototype.constructor = MxeShader; MxeShader.prototype.initialize = function(contents, index, label) { MxeCast.prototype.initialize.apply(this, arguments); this.castType = MxeCast.def.CT_SHADER; this.fsSrc = null; this.vsSrc = null; this.program = null; this.error = 0; this.render = this.contents.player.render; this.userUniformValues = {}; }; MxeShader.prototype.initGL = function(gl) { this.program = null; this.error = 0; }; MxeShader.prototype.createShader = function(render) { var gl = render.gl; var fs = render.compileShader(gl, gl.FRAGMENT_SHADER, this.fsSrc); if(fs === render.SHADER_FAIL){ this.error = 1; var msg = "Could not initialise shader cast("+this.index+"). error="+this.error+"\n"; MxeUtil.log(msg); throw new MxeException("defaultshader", msg); return; } var vs = render.compileShader(gl, gl.VERTEX_SHADER, this.vsSrc); if(vs === render.SHADER_FAIL){ this.error = 2; var msg = "Could not initialise shader cast("+this.index+"). error="+this.error+"\n"; MxeUtil.log(msg); throw new MxeException("defaultshader", msg); return; } //link shader this.program = gl.createProgram(); gl.attachShader(this.program, vs); gl.attachShader(this.program, fs); gl.linkProgram(this.program); if (! gl.getProgramParameter(this.program, gl.LINK_STATUS)) { this.error = 3; var msg = "Could not initialise shader cast("+this.index+"). error="+this.error+"\n"+gl.getProgramInfoLog(this.program); MxeUtil.log(msg); throw new MxeException("defaultshader", msg); return; } render.setupShaderVariableLocations(this.program); } MxeShader.prototype.prepareRender = function(render, frame) { if(this.error !== 0) throw new MxeException("shadercast", "can't prepare shader"); if(! this.program && this.error === 0){ this.createShader(render); } }; MxeShader.prototype.commitUniformValues = function(gl){ for(var name in this.userUniformValues){ var location = this.program[name]; var value = this.userUniformValues[name]; if(location === undefined){ this.program[name] = location = gl.getUniformLocation(this.program, name); } if(location === null){ throw new MxeException("shadercast", "can't set uniform \""+name+"\""); } gl.uniform1f(location, value); } }; MxeShader.prototype.setUniformValue = function(name, value){ this.userUniformValues[name] = value; }; MxeShader.prototype.getUniformValue = function(name){ return this.userUniformValues[name]; }; //TEXT var MxeText = function() { this.initialize.apply(this, arguments); }; MxeText.prototype = Object.create(MxeBitmapBase.prototype); MxeText.prototype.constructor = MxeText; MxeText.def = { ALIGNMENT_LEFT : 3, ALIGNMENT_CENTER : 1, ALIGNMENT_RIGHT : 5, }; MxeText.prototype.initialize = function(contents, index, label) { MxeBitmapBase.prototype.initialize.apply(this, arguments); this.castType = MxeCast.def.CT_TEXT; //TEXTDATA-- //HFONT hFont; // font handle this.width = 0; // font width this.height = 0; // font height (total line) //this.itemHeight = 0; // one line text size this.fontHeightRatio = 1.25; this.color = null; // text color this.backgroundColor = null; // back color this.bgTransparent = true; // false:opaqu true:transparent //this.zpos; // text cast display priority(int) this.lineDistance = 0; // //int PropChanged; // property changed by script this.lines = null; //this.type = 0; //bit0 0:Normal/1:alfa bit2:Antialias, bit7:FixSize, bit8-15:font style, bit16,17 Cast Alignment, bit31:UNICODE this.alignment = null; //this.antialias = false; // use only for embeded engine //void* GeneralPointer; // use for GLLib, CELib //int ScriptTag; // script use only //TCHAR* TextPropertyBuf; this.lineWidthMax = 0; // font data this.fontSize = 0.0; //pt this.fontStyle = null; //[italic|bold] this.fontFamily = null; //--TEXTDATA this.alphaType = 2; //HAS_TRANSLUCENT(for antialias) this.alphaBlendable = true; }; MxeText.prototype.initGL = function(gl) { this.glTexture = null; this.valid = false; }; MxeText.prototype.deleteImage = function(gl) { }; MxeText.prototype.cancelLoading = function() { }; MxeText.prototype.prepare = function() { }; MxeText.prototype.loadImage = function(src) { }; MxeText.prototype.setImage = function(image) { }; MxeText.prototype.setGLTexture = function(glTexture) { }; MxeText.prototype.measureFontHeight = function(font, fontPxSize){ return fontPxSize * this.fontHeightRatio; }; MxeText.prototype.createTexture = function(gl) { var oldTexW = 0; var oldTexH = 0; if(this.glTexture !== null){ oldTexW = this.textureWidth; oldTexH = this.textureHeight; } this.textureWidth = 1; this.textureHeight = 1; while(this.textureWidth < this.image.width) this.textureWidth*= 2; while(this.textureHeight < this.image.height) this.textureHeight*= 2; if(this.textureWidth !== oldTexW || this.textureHeight !== oldTexH){ if(this.glTexture !== null){ gl.deleteTexture(this.glTexture); this.glTexture = null; } this.glTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, this.glTexture); var textureArray = new Uint8Array(this.textureWidth*this.textureHeight*4); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.textureWidth, this.textureHeight, 0, gl.RGBA, gl.UNSIGNED_BYTE, textureArray); }else{ gl.bindTexture(gl.TEXTURE_2D, this.glTexture); } gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.image); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.magFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.minFilter); gl.bindTexture(gl.TEXTURE_2D, null); }; MxeText.prototype.getPrepared = function() { return this.glTexture !== null; }; MxeText.prototype.getWidth = function() { if(! this.valid && ! this.update()) return 0; if(this.image !== null) return this.image.width; return 0; }; MxeText.prototype.getHeight = function() { if(! this.valid && ! this.update()) return 0; if(this.image !== null) return this.image.height; return 0; }; MxeText.prototype.update = function(ctx, gl) { if(this.valid) return true; if(this.lines === null || this.lines.length === 0){ this.valid = true; //this.width = 0; this.height = 0; return true; } if(! ctx) ctx = this.contents.player.render.render2D.getOffscreenContext(); if(! gl) gl = this.contents.player.render.gl; if(! ctx || ! gl) return false; var fontPxSize = this.fontSize*96.0/72.0; var font = ""; if(this.fontStyle != null) font = font + this.fontStyle; font = font + " " + fontPxSize + "px"; if(this.fontFamily != null) font = font + " " + this.fontFamily; ctx.font = font; var alignType = 0; switch(this.alignment){ case "center": alignType = 1; ctx.textAlign = "center"; break; case "right": alignType = 2; ctx.textAlign = "right"; break; case "left": alignType = 3; ctx.textAlign = "left"; break; default: alignType = 0; ctx.textAlign = "left"; break; } ctx.textBaseline = "top"; var i; var lineWidth; var metrics; var lineWidthTable; var itemHeight = this.measureFontHeight(font, fontPxSize); this.height = (itemHeight + this.lineDistance) * this.lines.length; if(alignType === 0){ lineWidthTable = new Float32Array(this.lines.length); this.lineWidthMax = 0; for(i=0; i<this.lines.length; i++){ metrics = ctx.measureText(this.lines[i]); lineWidth = metrics.width + 2; if(lineWidth > this.lineWidthMax) this.lineWidthMax = lineWidth; } lineWidthTable[i] = this.width = this.lineWidthMax; }else{ this.lineWidthMax = this.width; } this.width = Math.ceil(this.width); this.height = Math.ceil(this.height); if(ctx.canvas.width < this.width || ctx.canvas.height < this.height) throw new Mxe2DContextTooSmallException("", this.width, this.height); ctx.fillStyle = "#000000"; ctx.fillRect(0, 0, this.width, this.height); ctx.fillStyle = "#ffffff"; var lineDistanceSum = 0; var lineX = 0; for(i=0; i<this.lines.length; i++){ switch(alignType){ case 1: lineX = Math.floor(this.width / 2); break; case 2: lineX = this.width; break; } ctx.fillText(this.lines[i], lineX, Math.floor(itemHeight*i+lineDistanceSum)); lineDistanceSum+= this.lineDistance; } this.image = ctx.getImageData(0, 0, this.width, this.height); this.createTexture(gl); this.valid = true; return true; }; MxeText.prototype.prepareRender = function(render, frame) { try{ this.update(render.render2D.getOffscreenContext(), render.gl); }catch(e){ if(e.name === Mxe2DContextTooSmallException.prototype.name){ render.render2D.resizeOffscreenCanvas(e.requestWidth, e.requestHeight); this.update(render.render2D.getOffscreenContext(), render.gl); }else{ throw e; } } }; //PROCEDURAL var MxeProcedural = function() { this.initialize.apply(this, arguments); }; MxeProcedural.prototype = Object.create(MxeCast2D.prototype); MxeProcedural.prototype.constructor = MxeProcedural; MxeProcedural.prototype.initialize = function(contents, index, label) { MxeCast2D.prototype.initialize.apply(this, arguments); this.castType = MxeCast.def.CT_PROCEDURAL; //PROCEDURALDATA-- this.casts = null; //cast array this.colors = null; //color array this.intParams = null; //int array this.floatParams = null; //float array //this.presetWidth = 0; //-> MxeCast2D //this.presetHeight = 0; //-> MxeCast2D //--PROCEDURALDATA; this.viewClass = null; //MxeProceduralView class this.views = {}; //key is MxeFrame2D }; MxeProcedural.prototype.invalidate = function() { this.valid = false; }; MxeProcedural.prototype.getPrepared = function() { if(this.casts === null) return; for(var i=0; i<this.casts.length; i++){ if(this.casts[i] == null) continue; if(! this.casts[i].getPrepared()) return false; } return true; }; MxeProcedural.prototype.getWidth = function() { return this.presetWidth; }; MxeProcedural.prototype.getHeight = function() { return this.presetHeight; }; MxeProcedural.prototype.setViewClass = function(viewClass) { this.viewClass = viewClass; var keys = Object.keys(this.views); for(var i; i<keys.length; i++){ delete this.views[keys[i]]; } }; MxeProcedural.prototype.onDraw = function(render, frame, renderMode, selectionID) { if(! this.views[frame] && this.viewClass !== null){ this.views[frame] = new this.viewClass(this); } if(this.views[frame]){ this.views[frame].draw(render, frame, renderMode, selectionID); } }; MxeProcedural.prototype.prepareRender = function(render, frame) { if(this.casts === null) return; for(var i=0; i<this.casts.length; i++){ var cast = this.casts[i]; if(cast == null) continue; cast.prepareRender(render, frame); } if(frame){ var view = this.views[frame]; if(view) view.prepareRender(render, frame); } }; var MxeProceduralView = function() { this.initialize.apply(this, arguments); }; MxeProceduralView.prototype.initialize = function(procedural) { this.procedural = procedural; }; MxeProceduralView.prototype.draw = function(render, frame, renderMode, selectionID) { }; MxeProceduralView.prototype.prepareRender = function(render, frame) { }; var MxeScore = function() { this.initialize.apply(this, arguments); }; MxeScore.prototype.initialize = function(contents, index, label) { this.contents = contents; this.index = index; this.label = label; //this.parentScore = parentScore; 廃止 this.parentScore === this.selfTrack.score //SCORE-- //internal var int MaxTrack:int = 0; // total track this.maxFrameOfScore = 0; // max frame num of all track //internal var maxLoopFrame:int = 0; // max loop frame num this.tracks = null; //LPTrack // track object this.tracksL = null; //LPTrack // track object by label this.loops = null; //LPLoopFrame // loop data this.currentFrame = 0; // running frame num this.nextFrame = 0; // next frame num this.seekedFrame = -1; // keep seek frame //internal var MOTIONBLEND* LPMotionBlendInfo; // motion blend info //internal var frameChanged:Boolean = false; this.frameBreaked = false; // refered from script this.scoreStatus = 0; // bit0:Async(no use), bit1:UseFastSubScore this.frameLabelPos = null; // use by script LabelPosStr //--SCORE this.castType = MxeCast.def.CT_LINK; //for checkCast this.selfTrack = null; //this score on it this.addEventListenerFuncs = { "onenterframe": this.addOnEnterFrameListener, "onexitframe": this.addOnExitFrameListener, "onmousedown": this.addOnMouseDownListener, "onmouseup": this.addOnMouseUpListener, "onmousemove": this.addOnMouseMoveListener, }; this.onEnterFrameListeners = null; this.onExitFrameListeners = null; this.onMouseDownListeners = null; this.onMouseUpListeners = null; this.onMouseMoveListeners = null; }; MxeScore.def = { // Close.h // loop controll track ID LT_NONE: 0, // none LT_TOP : 1, // loop start LT_MID : 2, // in a loop LT_END : 3, // loop end LT_SNG : 4, // loop start and end (one frame loop) }; MxeScore.prototype.getTouchTag = function(id) { return this.player.getTouchTag(id); }; MxeScore.prototype.createEventFlagArray = function(frameNumbers){ if(! frameNumbers) return null; var lastItem = frameNumbers[frameNumbers.length-1]; var maxFrameNum; if(Array.isArray(lastItem)){ maxFrameNum = lastItem[1]; }else{ maxFrameNum = lastItem; } var flagArray = new Int8Array(maxFrameNum+1); for(var i in frameNumbers){ var item = frameNumbers[i]; if(Array.isArray(item)){ for(var j=item[0]; j<=item[1]; j++) flagArray[j] = 1; }else{ //number flagArray[item] = 1; } } return flagArray; }; MxeScore.prototype.addEventListener = function(eventType, listener, userObj, frameNumbers) { var func = this.addEventListenerFuncs[eventType]; if(func === undefined) return false; func.apply(this, [listener, userObj, frameNumbers]); return true; }; MxeScore.prototype.addOnEnterFrameListener = function(listener, userObj, frameNumbers) { if(this.onEnterFrameListeners === null){ this.onEnterFrameListeners = new Array(); } this.onEnterFrameListeners.push([listener, userObj, this.createEventFlagArray(frameNumbers)]); }; MxeScore.prototype.addOnExitFrameListener = function(listener, userObj, frameNumbers) { if(this.onExitFrameListeners === null){ this.onExitFrameListeners = new Array(); } this.onExitFrameListeners.push([listener, userObj, this.createEventFlagArray(frameNumbers)]); }; MxeScore.prototype.addOnMouseDownListener = function(listener, userObj, frameNumbers) { if(this.onMouseDownListeners === null){ this.onMouseDownListeners = new Array(); } this.onMouseDownListeners.push([listener, userObj, this.createEventFlagArray(frameNumbers)]); }; MxeScore.prototype.addOnMouseUpListener = function(listener, userObj, frameNumbers) { if(this.onMouseUpListeners === null){ this.onMouseUpListeners = new Array(); } this.onMouseUpListeners.push([listener, userObj, this.createEventFlagArray(frameNumbers)]); }; MxeScore.prototype.addOnMouseMoveListener = function(listener, userObj, frameNumbers) { if(this.onMouseMoveListeners === null){ this.onMouseMoveListeners = new Array(); } this.onMouseMoveListeners.push([listener, userObj, this.createEventFlagArray(frameNumbers)]); }; //TODO remove listener MxeScore.prototype.onEnterFrameHandler = function(e) { if(this.onEnterFrameListeners === null) return; var i; var func; var frameFlags; e.score = this; for(i=0; i<this.onEnterFrameListeners.length; i++){ frameFlags = this.onEnterFrameListeners[i][2]; if(frameFlags && (this.currentFrame >= frameFlags.length || ! frameFlags[this.currentFrame])) continue; func = this.onEnterFrameListeners[i][0]; e.userObj = this.onEnterFrameListeners[i][1]; func.apply(e.userObj, [e]); } }; MxeScore.prototype.onExitFrameHandler = function(e) { if(this.onExitFrameListeners === null) return; var i; var func; var frameFlags; e.score = this; for(i=0; i<this.onExitFrameListeners.length; i++){ frameFlags = this.onExitFrameListeners[i][2]; if(frameFlags && (this.currentFrame >= frameFlags.length || ! frameFlags[this.currentFrame])) continue; func = this.onExitFrameListeners[i][0]; e.userObj = this.onExitFrameListeners[i][1]; func.apply(e.userObj, [e]); } }; MxeScore.prototype.onMouseDownHandler = function(mouseDownEvent) { if(this.onMouseDownListeners === null) return; var i; var func; var frameFlags; mouseDownEvent.score = this; for(i=0; i<this.onMouseDownListeners.length; i++){ frameFlags = this.onMouseDownListeners[i][2]; if(frameFlags && (this.currentFrame >= frameFlags.length || ! frameFlags[this.currentFrame])) continue; func = this.onMouseDownListeners[i][0]; mouseDownEvent.userObj = this.onMouseDownListeners[i][1]; func.apply(mouseDownEvent.userObj, [mouseDownEvent]); } }; MxeScore.prototype.onMouseUpHandler = function(mouseUpEvent) { if(this.onMouseUpListeners === null) return; var i; var func; var frameFlags; mouseUpEvent.score = this; for(i=0; i<this.onMouseUpListeners.length; i++){ frameFlags = this.onMouseUpListeners[i][2]; if(frameFlags && (this.currentFrame >= frameFlags.length || ! frameFlags[this.currentFrame])) continue; func = this.onMouseUpListeners[i][0]; mouseUpEvent.userObj = this.onMouseUpListeners[i][1]; func.apply(mouseUpEvent.userObj, [mouseUpEvent]); }; }; MxeScore.prototype.onMouseMoveHandler = function(mouseMoveEvent) { if(this.onMouseMoveListeners === null) return; var i; var func; var frameFlags; mouseMoveEvent.score = this; for(i=0; i<this.onMouseMoveListeners.length; i++){ frameFlags = this.onMouseMoveListeners[i][2]; if(frameFlags && (this.currentFrame >= frameFlags.length || ! frameFlags[this.currentFrame])) continue; func = this.onMouseMoveListeners[i][0]; mouseMoveEvent.userObj = this.onMouseMoveListeners[i][1]; func.apply(mouseMoveEvent.userObj, [mouseMoveEvent]); } }; MxeScore.prototype.seekFrame = function(frameID) { var ftype = typeof(frameID); if (ftype === "number"){ this.seekedFrame = frameID; }else if(ftype === "string"){ this.seekFrameL(frameID); } }; MxeScore.prototype.seekFrameL = function(frameID) { this.seekedFrame = this.frameLabelPos[frameID]; }; MxeScore.prototype.breakLoop = function() { if(this.loops === null) return; var foundLoopEnd = false; var i; for(i=this.currentFrame; i<this.loops.length; i++){ switch (this.loops[i]){ case MxeScore.def.LT_END: case MxeScore.def.LT_SNG: foundLoopEnd = true; break; } if(foundLoopEnd) break; } if(foundLoopEnd){ this.seekedFrame = i+1; } }; MxeScore.prototype.updateFrameNumber = function() { var i; if(this.seekedFrame > -1){ this.currentFrame = this.seekedFrame; this.seekedFrame = -1; for(i=0; i<this.tracks.length; i++) this.tracks[i].onSeekFrameHandler(); }else{ this.currentFrame = this.nextFrame; } var cf = this.currentFrame; var maxFrame = this.maxFrameOfScore; var loops = this.loops; if ((loops !== null) && (maxFrame < loops.length)) maxFrame = loops.length; if (cf < maxFrame) this.nextFrame = cf + 1; // set default else this.nextFrame = cf; if (cf >= loops.length) return; if (loops === null) return; // some contents has no LPLoopFrame ! switch (loops[cf]){ case MxeScore.def.LT_END: while (loops[cf] !== MxeScore.def.LT_TOP) cf--; this.nextFrame = cf; break; case MxeScore.def.LT_SNG: this.nextFrame = cf; // self loop } }; MxeScore.prototype.makeFrame = function(frameNumber) { //CPlayer::MakeScore if(frameNumber < 0) this.updateFrameNumber(); for(var i=0; i<this.tracks.length; i++){ this.tracks[i].makeFrame(frameNumber); } }; MxeScore.prototype.prepareRender = function(render, resolveIK) { for(var i=0; i<this.tracks.length; i++){ var track = this.tracks[i]; track.prepareRender(render); if(track.castType === MxeCast.def.CT_LINK){ if(track.cast !== null){ track.cast.prepareRender(render, resolveIK); } } } //ik-- if(resolveIK){ for(var i=0; i<this.tracks.length; i++){ if(this.tracks[i].ikInfo) this.tracks[i].frame.resolveIK(); } } //--ik }; MxeScore.prototype.applyCamera = function(cameraMatrix) { for(var i=0; i<this.tracks.length; i++){ this.tracks[i].applyCamera(cameraMatrix); } }; MxeScore.prototype.setBlendAnimation = function(trackOffset, trackCount, frameCount, blendMode, rollFlag, continueFlag) { if(trackOffset < 0) trackOffset = 0; if(trackCount < 0) trackCount = this.tracks.length - trackOffset; for(var i=trackOffset; i<trackOffset+trackCount; i++){ this.tracks[i].setBlendAnimation(frameCount, blendMode, rollFlag, continueFlag); } }; MxeScore.prototype.cancelBlendAnimation = function(trackOffset, trackCount) { if(trackOffset < 0) trackOffset = 0; if(trackCount < 0) trackCount = this.tracks.length - trackOffset; for(var i=trackOffset; i<trackOffset+trackCount; i++){ this.tracks[i].cancelBlendAnimation(frameCount, blendMode, rollFlag, continueFlag); } }; var MxeTrack = function() { this.initialize.apply(this, arguments); }; MxeTrack.prototype.initialize = function(score, index, label) { this.score = score; this.index = index; this.label = label; this.tag = 0; this.scoreFrame = null; this.puppetFrame = null; this.blendAnimation = null; this.frame = null; this.renderList = null; //TRACK-- this.cast = null; this.castType = 0; this.parentTrack = null; this.maxFrame = 0; this.animationData = null; //LPElement; // T3DELEMENT, T2DELEMENT, .... this.puppet = false; //--TRACK this.addEventListenerFuncs = { "onclick": this.addOnClickListener, }; this.onClickListeners = null; }; MxeTrack.prototype.setPuppet = function(val) { }; MxeTrack.prototype.getPuppet = function() { return this.puppet; }; MxeTrack.prototype.addEventListener = function(eventType, listener, userObj, frameNumbers) { var func = this.addEventListenerFuncs[eventType]; if(func === undefined) return false; func.apply(this, [listener, userObj, frameNumbers]); return true; }; MxeTrack.prototype.addOnClickListener = function(listener, userObj, frameNumbers) { if(this.onClickListeners === null){ this.onClickListeners = new Array(); } this.onClickListeners.push([listener, userObj, this.score.createEventFlagArray(frameNumbers)]); this.score.contents.player.onClickListenerCount++; }; //TODO remove listener MxeTrack.prototype.onClickHandler = function(e) { //MxeUtil.log("track onclick x="+e.x+" y="+e.y+" track="+this.index+" sector="+e.sector.index); if(this.onClickListeners === null) return; var i; var func; var frameFlags; for(i=0; i<this.onClickListeners.length; i++){ frameFlags = this.onClickListeners[i][2]; if(frameFlags && (this.score.currentFrame >= frameFlags.length || ! frameFlags[this.score.currentFrame])) continue; func = this.onClickListeners[i][0]; e.userObj = this.onClickListeners[i][1]; e.track = this; //func.apply(e.userObj, [e]); } }; MxeTrack.prototype.makeFrame = function(frameNumber) { //if(frameNumber < 0) frameNumber = this.score.currentFrame; if(this.scoreFrame !== null){ if(this.blendAnimation != null){ this.scoreFrame.invalidate(); } this.scoreFrame.make(frameNumber); } }; MxeTrack.prototype.prepareRender = function(render) { //CStage::ModifyFrame() }; MxeTrack.prototype.applyCamera = function(cameraMatrix) { if(this.frame !== null) this.frame.applyCamera(cameraMatrix); }; MxeTrack.prototype.setBlendAnimation = function(frameCount, blendMode, rollFlag, continueFlag) { }; MxeTrack.prototype.cancelBlendAnimation = function(frameCount, blendMode, rollFlag, continueFlag) { this.blendAnimation = null; }; MxeTrack.prototype.onSeekFrameHandler = function() { if(this.blendAnimation !== null && ! this.blendAnimation.continueFlag && this.blendAnimation.frameNumber > 0){ this.blendAnimation = null; } }; MxeTrack.prototype.checkCastType = function(cast){ return (this.castType === cast.castType); }; var MxeBoneTrackInfo = function() { this.initialize.apply(this, arguments); }; MxeBoneTrackInfo.prototype.initialize = function(boneSector, modelTrack) { //BONEINFO-- this.boneSector = boneSector; this.modelTrack = modelTrack; //--BONEINFO }; var MxeTrack3D = function() { this.initialize.apply(this, arguments); }; MxeTrack3D.prototype = Object.create(MxeTrack.prototype); MxeTrack3D.prototype.constructor = MxeTrack3D; MxeTrack3D.prototype.initialize = function(score, index, label) { MxeTrack.prototype.initialize.apply(this, arguments); if(score) this.scoreFrame = new MxeFrame3D(this); this.frame = this.scoreFrame; this.renderList = null; //TRACK-- this.userMatrix = null; this.baseMatrix = null; //internal var MATRIX* LPIKBaseMatrix; //internal var MOTIONBLEND* LPMotionBlend; //internal var VECTOR CurMBPSaveVector[3];// MotionBlend, for preservation of puppet initial value and the final value. //internal var VECTOR CurMBPos; // MotionBlend position //internal var VECTOR CurMBRot; // MotionBlend rotation //internal var VECTOR CurMBSiz; // MotionBlend size //internal var BYTE* TexAnimGroupList; // each bit is texture0,1,2... //internal var int TexAnimGroupSize; //internal var int TexAnimAllTexMode; // each bit is texture0,1,2... bit31: 0=Track 1=Model this.rollType = 0; this.billboardType = 0; // 0:normal, 1:H only, 3:HV //internal var BYTE IsMotionBlendOn; //internal var BYTE IsMotionBlendContinue; //internal var RECT PictureFrame; //this.hasQuaternion = false; //--TRACK this.visibleData = null; this.boneInfo = null; //BONEINFO (MxeBoneTrackInfo) //ik-- this.ikInfo = null; this.constraint = 0; //--ik }; MxeTrack3D.prototype.prepareRender = function(render) { //CStage::ModifyFrame() if(this.frame !== null) this.frame.prepareRender(render); if(this.castType === MxeCast.def.CT_CAMERA && this.frame !== null && this.frame.worldVisible){ if(this.frame.cast !== null){ render.render3D.currentCameraTrack = this; } } if(this.castType === MxeCast.def.CT_LIGHT && this.frame !== null && this.frame.worldVisible){ if(this.frame.cast !== null) render.render3D.addLight(this); } if(this.frame !== null && this.frame.worldVisible && this.frame.renderList !== null) render.render3D.addRenderList(this.frame.renderList); }; MxeTrack3D.prototype.setPuppet = function(val) { if(this.puppet === val) return; this.puppet = val; if(this.puppet){ if(this.puppetFrame === null){ this.puppetFrame = new MxeFrame3D(this); this.puppetFrame.isPuppet = true; } this.frame = this.puppetFrame; }else{ //this.puppetFrame = null; this.frame = this.scoreFrame; } }; MxeTrack3D.prototype.makeFrame = function(frameNumber) { MxeTrack.prototype.makeFrame.apply(this, arguments); if(this.blendAnimation){ //TODO continueFlag this.blendAnimation.frameNumber++; if(this.blendAnimation.frameNumber < this.blendAnimation.frameCount){ this.frame.blend( this.blendAnimation.frame, 1.0-1.0/(this.blendAnimation.frameCount-this.blendAnimation.frameNumber), this.blendAnimation.blendMode, this.blendAnimation.rollFlag); vec3.set(this.frame.pos, this.blendAnimation.frame.pos); quat4.set(this.frame.rot, this.blendAnimation.frame.rot); vec3.set(this.frame.siz, this.blendAnimation.frame.siz); }else{ this.blendAnimation = null; } } }; MxeTrack3D.prototype.setBlendAnimation = function(frameCount_, blendMode_, rollFlag_, continueFlag_) { this.blendAnimation = { frameCount: frameCount_, frameNumber: 0, blendMode: blendMode_, rollFlag: rollFlag_, continueFlag: continueFlag_, frame: this.frame.duplicate(), }; }; MxeTrack3D.prototype.getBoneSector = function() { if(! this.boneInfo) return null; return this.boneInfo.boneSector; }; var MxeTrackBillboard = function() { this.initialize.apply(this, arguments); }; MxeTrackBillboard.prototype = Object.create(MxeTrack3D.prototype); MxeTrackBillboard.prototype.constructor = MxeTrackBillboard; MxeTrackBillboard.prototype.initialize = function(score, index, label) { MxeTrack3D.prototype.initialize.apply(this, arguments); this.workVector = vec3.create(); }; MxeTrackBillboard.prototype.applyCamera = function(cameraMatrix) { MxeTrack3D.prototype.applyCamera.apply(this, arguments); var billboardInfo = null; var cast = this.frame.getCast(); if(cast){ billboardInfo = cast.billboardInfo; } if(billboardInfo && this.frame.worldVisible){ var vm = this.frame.billboardMatrix; this.workVector[0] = -billboardInfo.pos[0]*billboardInfo.siz[0]*cast.getWidth()/2.0; this.workVector[1] = billboardInfo.pos[1]*billboardInfo.siz[1]*cast.getHeight()/2.0; this.workVector[2] = 0.0; mat4.translate(vm, this.workVector); vm[0]*= (billboardInfo.siz[0]*cast.getWidth()); vm[5]*= (billboardInfo.siz[1]*cast.getHeight()); } }; MxeTrackBillboard.prototype.checkCastType = function(cast){ if(cast.castType === MxeCast.def.CT_TEXTURE) return true; if(cast.castType === MxeCast.def.CT_BITMAP) return true; if(cast.castType === MxeCast.def.CT_PROCEDURAL) return true; if(cast.castType === MxeCast.def.CT_AVI) return true; if(cast.castType === MxeCast.def.CT_TEXT) return true; }; var MxeTrack2D = function() { this.initialize.apply(this, arguments); }; MxeTrack2D.prototype = Object.create(MxeTrack.prototype); MxeTrack2D.prototype.constructor = MxeTrack2D; MxeTrack2D.prototype.initialize = function(score, index, label) { MxeTrack.prototype.initialize.apply(this, arguments); this.scoreFrame = new MxeFrame2D(this) this.frame = this.scoreFrame; this.proceduralParams = null; }; MxeTrack2D.prototype.prepareRender = function(render) { //CStage::ModifyFrame() if(this.frame !== null) this.frame.prepareRender(render); if(this.frame !== null && this.frame.worldVisible && this.frame.renderList !== null && this.frame.cast !== null){ if(this.frame.cast.behind3D) render.render2D.addBackRenderList(this.frame.renderList); else render.render2D.addFrontRenderList(this.frame.renderList); } }; MxeTrack2D.prototype.setPuppet = function(val) { if(this.puppet === val) return; this.puppet = val; if(this.puppet){ this.puppetFrame = new MxeFrame2D(this); this.puppetFrame.isPuppet = true; this.puppetFrame.copyForPuppet(this.scoreFrame); this.frame = this.puppetFrame; }else{ this.puppetFrame = null; this.frame = this.scoreFrame; } }; MxeTrack2D.prototype.checkCastType = function(cast){ if(cast.castType === MxeCast.def.CT_TEXTURE) return true; if(cast.castType === MxeCast.def.CT_BITMAP) return true; if(cast.castType === MxeCast.def.CT_PROCEDURAL) return true; if(cast.castType === MxeCast.def.CT_AVI) return true; if(cast.castType === MxeCast.def.CT_TEXT) return true; }; var MxeTrackMaterial = function() { this.initialize.apply(this, arguments); }; MxeTrackMaterial.prototype = Object.create(MxeTrack3D.prototype); MxeTrackMaterial.prototype.constructor = MxeTrackMaterial; MxeTrackMaterial.prototype.initialize = function(score, index, label) { MxeTrack3D.prototype.initialize.apply(this, arguments); this.scoreFrame = new MxeFrameMaterial(this) this.frame = this.scoreFrame; //this.userMatrix = null; }; var MxeTrackUnknown = function() { this.initialize.apply(this, arguments); }; MxeTrackUnknown.prototype = Object.create(MxeTrack.prototype); MxeTrackUnknown.prototype.constructor = MxeTrackUnknown; MxeTrackUnknown.prototype.initialize = function(score, index, label) { MxeTrack.prototype.initialize.apply(this, arguments); }; var MxeFrame = function() { this.initialize.apply(this, arguments); }; MxeFrame.prototype.initialize = function(track) { this.track = track; this.visible = false; this.frameNum = -1; this.cast = null; this.worldVisible = false; this.isPuppet = false; }; MxeFrame.prototype.duplicate = function() { return null; } MxeFrame.prototype.make = function(frameNum) { }; MxeFrame.prototype.makeL = function(frameName) { var frameNum = this.track.score.frameLabelPos[frameName]; if(frameNum === undefined) return; this.make(frameNum); }; MxeFrame.prototype.invalidate = function(){ this.frameNum = -1; //"make" forcedly at next frame }; MxeFrame.prototype.prepareRender = function(render) { }; MxeFrame.prototype.applyCamera = function(cameraMatrix) { }; MxeFrame.prototype.checkCastType = function(cast){ if(this.track === null) return true; if(this.track.checkCastType(cast)) return true; throw new MxeException("setcast", "cast type error"); }; MxeFrame.prototype.setCast = function(cast) { this.checkCastType(cast); this.cast = cast; }; MxeFrame.prototype.getCast = function() { return this.cast; }; MxeFrame.prototype.blend = function(frame, p, blendMode, rollFlag) { }; var MxeFrame3D = function() { this.initialize.apply(this, arguments); }; MxeFrame3D.prototype = Object.create(MxeFrame.prototype); MxeFrame3D.prototype.constructor = MxeFrame3D; MxeFrame3D.prototype.initialize = function(track) { MxeFrame.prototype.initialize.apply(this, arguments); this.cast = track.cast; this.pos = vec3.create(); this.rot = quat4.create(); this.rot[3] = 1.0; this.siz = vec3.create(); this.siz[0] = this.siz[1] = this.siz[2] = 1.0; this.prevPosKey = -1; this.nextPosKey = -1; this.prevRotKey = -1; this.nextRotKey = -1; this.prevSizKey = -1; this.nextSizKey = -1; this.validWorldMatrix = false; this.worldMatrix = mat4.create(); //left handed this.skinMatrix = mat4.create(); //left handed //this.viewWorldMatrix = mat4.create(); //right handed //this.viewSkinMatrix = mat4.create(); //right handed this.billboardMatrix = null; this.worldSiz = vec3.create(); this.renderList = null; this.renderListValid = false; }; MxeFrame3D.prototype.duplicate = function() { var frame = new MxeFrame3D(this.track); frame.frameNum = this.frameNum; frame.setCast(this.cast); frame.renderList = this.renderList; frame.visible = this.visible; vec3.set(this.pos, frame.pos); quat4.set(this.rot, frame.rot); vec3.set(this.siz, frame.siz); return frame; } MxeFrame3D.prototype.isPosKey = function(frameData, n) { if(! frameData) return false; if(frameData[0] === null) return false; return true; }; MxeFrame3D.prototype.isRotKey = function(frameData, n) { if(! frameData) return false; if(frameData[1] === null) return false; return true; }; MxeFrame3D.prototype.isSizKey = function(frameData, n) { if(! frameData) return false; if(frameData[2] === null) return false; return true; }; MxeFrame3D.prototype.searchPosKey = function() { var animData = this.track.animationData; if(animData.length === 0){ this.nextPosKey = 0; this.prevPosKey = 0; return; } var n = this.frameNum; if(n >= animData.length) n = animData.length - 1; for(; n < animData.length; n++) if(this.isPosKey(animData[n], n)) break; this.nextPosKey = n; n = this.frameNum; for(; 0 <= n; n--) if(this.isPosKey(animData[n], n)) break; this.prevPosKey = n; }; MxeFrame3D.prototype.searchRotKey = function() { var animData = this.track.animationData; if(animData.length === 0){ this.nextRotKey = 0; this.prevRotKey = 0; return; } var n = this.frameNum; if(n >= animData.length) n = animData.length - 1; for(; n < animData.length; n++) if(this.isRotKey(animData[n], n)) break; this.nextRotKey = n; n = this.frameNum; for(; 0 <= n; n--) if(this.isRotKey(animData[n], n)) break; this.prevRotKey = n; }; MxeFrame3D.prototype.searchSizKey = function() { var animData = this.track.animationData; if(animData.length === 0){ this.nextSizKey = 0; this.prevSizKey = 0; return; } var n = this.frameNum; if(n >= animData.length) n = animData.length - 1; for(; n < animData.length; n++) if(this.isSizKey(animData[n], n)) break; this.nextSizKey = n; n = this.frameNum; for(; 0 <= n; n--) if(this.isSizKey(animData[n], n)) break; this.prevSizKey = n; }; MxeFrame3D.prototype.makeLinear = function() { if(this.track.animationData.length === 0){ //no key frames return; } var keyData0; var keyData1; var frameNum = this.frameNum; var p0; var p1; var diff; if(frameNum >= this.track.visibleData.length){ this.visible = false; frameNum = this.prevPosKey; }else{ this.visible = this.track.visibleData[frameNum]; } //Position if(frameNum === this.prevPosKey){ //key frame keyData0 = this.track.animationData[this.prevPosKey][0]; this.pos[0] = keyData0[0]; this.pos[1] = keyData0[1]; this.pos[2] = keyData0[2]; }else if(frameNum === this.nextPosKey){ //key frame keyData1 = this.track.animationData[this.nextPosKey][0]; this.pos[0] = keyData1[0]; this.pos[1] = keyData1[1]; this.pos[2] = keyData1[2]; }else{ //middle frame keyData0 = this.track.animationData[this.prevPosKey][0]; keyData1 = this.track.animationData[this.nextPosKey][0]; diff = (this.nextPosKey - this.prevPosKey)*1.0; p1 = (frameNum - this.prevPosKey)/diff; p0 = (this.nextPosKey - frameNum)/diff; this.pos[0] = keyData0[0]*p0 + keyData1[0]*p1; this.pos[1] = keyData0[1]*p0 + keyData1[1]*p1; this.pos[2] = keyData0[2]*p0 + keyData1[2]*p1; } //Rotation var isQuaternion = this.track.rollType === 7; if(frameNum === this.prevRotKey){ //key frame keyData0 = this.track.animationData[this.prevRotKey][1]; this.rot[0] = keyData0[0]; this.rot[1] = keyData0[1]; this.rot[2] = keyData0[2]; if(isQuaternion){ this.rot[3] = keyData0[3]; } }else if(frameNum === this.nextRotKey){ //key frame keyData1 = this.track.animationData[this.nextRotKey][1]; this.rot[0] = keyData1[0]; this.rot[1] = keyData1[1]; this.rot[2] = keyData1[2]; if(isQuaternion){ this.rot[3] = keyData1[3]; } }else{ //middle frame keyData0 = this.track.animationData[this.prevRotKey][1]; keyData1 = this.track.animationData[this.nextRotKey][1]; diff = (this.nextRotKey - this.prevRotKey)*1.0; p1 = (frameNum - this.prevRotKey)/diff; p0 = (this.nextRotKey - frameNum)/diff; if(isQuaternion){ //QuaternionSlerp MxeGeom.quat4.slerp(keyData0, keyData1, p1, this.rot); //quat4.normalize(this.rot); }else{ this.rot[0] = keyData0[0]*p0 + keyData1[0]*p1; this.rot[1] = keyData0[1]*p0 + keyData1[1]*p1; this.rot[2] = keyData0[2]*p0 + keyData1[2]*p1; } } //Scale if(frameNum === this.prevSizKey){ //key frame keyData0 = this.track.animationData[this.prevSizKey][2]; this.siz[0] = keyData0[0]; this.siz[1] = keyData0[1]; this.siz[2] = keyData0[2]; }else if(frameNum === this.nextSizKey){ //key frame keyData1 = this.track.animationData[this.nextSizKey][2]; this.siz[0] = keyData1[0]; this.siz[1] = keyData1[1]; this.siz[2] = keyData1[2]; }else{ //middle frame keyData0 = this.track.animationData[this.prevSizKey][2]; keyData1 = this.track.animationData[this.nextSizKey][2]; diff = (this.nextSizKey - this.prevSizKey)*1.0; p1 = (frameNum - this.prevSizKey)/diff; p0 = (this.nextSizKey - frameNum)/diff; this.siz[0] = keyData0[0]*p0 + keyData1[0]*p1; this.siz[1] = keyData0[1]*p0 + keyData1[1]*p1; this.siz[2] = keyData0[2]*p0 + keyData1[2]*p1; } }; MxeFrame3D.prototype.make = function(frameNum) { if(frameNum === -1) frameNum = this.track.score.currentFrame; if(! this.isPuppet && frameNum === this.frameNum) return; this.validWorldMatrix = false; this.frameNum = frameNum; this.cast = this.track.cast; var animLength = this.track.animationData.length; if(this.prevPosKey === -1) this.searchPosKey(); else if(frameNum < this.prevPosKey || (this.nextPosKey < frameNum && frameNum < animLength)) this.searchPosKey(); if(this.prevRotKey === -1) this.searchRotKey(); else if(frameNum < this.prevRotKey || (this.nextRotKey < frameNum && frameNum < animLength)) this.searchRotKey(); if(this.prevSizKey === -1) this.searchSizKey(); else if(frameNum < this.prevSizKey || (this.nextSizKey < frameNum && frameNum < animLength)) this.searchSizKey(); this.makeLinear(); //TODO easing //TODO spline }; MxeFrame3D.prototype.calcMatrix = function() { //CFrame::CulcFrame() try { MxeGeom.useTemporary(); //var rollType:uint = track.rollType; //var centerOffs; //:Vector3D = workV0; var sector; //:Sector; var parentTrack = this.track.parentTrack; var gm = this.worldMatrix; var tv = MxeGeom.vec3.getTemporary(); //var tm = mat4.create(); if(this.track.userMatrix !== null){ //gm = track.userMatrix.clone(); mat4.set(this.track.userMatrix, gm); //copy user matrix to world matrix this.worldSiz[0] = Math.sqrt(gm[0+0]*gm[0+0])+Math.sqrt(gm[0+1]*gm[0+1])+Math.sqrt(gm[0+2]*gm[0+2]); this.worldSiz[1] = Math.sqrt(gm[4+0]*gm[4+0])+Math.sqrt(gm[4+1]*gm[4+1])+Math.sqrt(gm[4+2]*gm[4+2]); this.worldSiz[2] = Math.sqrt(gm[8+0]*gm[8+0])+Math.sqrt(gm[8+1]*gm[8+1])+Math.sqrt(gm[8+2]*gm[8+2]); }else{ mat4.identity(gm); //SET TRANSLATION mat4.translate(gm, this.pos); //SET ROTATION //(注意)glMatrixの演算は、最後に演算したものが最初に適用されるマトリックスが生成される switch (this.track.rollType){ // rotate transration case 1: //XYZ mat4.rotateZ(gm, this.rot[2]); mat4.rotateY(gm, this.rot[1]); mat4.rotateX(gm, this.rot[0]); break; case 2: //XZY mat4.rotateY(gm, this.rot[1]); mat4.rotateZ(gm, this.rot[2]); mat4.rotateX(gm, this.rot[0]); break; case 3: //YXZ mat4.rotateZ(gm, this.rot[2]); mat4.rotateX(gm, this.rot[0]); mat4.rotateY(gm, this.rot[1]); break; case 4: //YZX mat4.rotateX(gm, this.rot[0]); mat4.rotateZ(gm, this.rot[2]); mat4.rotateY(gm, this.rot[1]); break; case 0: case 5: //ZXY //default mat4.rotateY(gm, this.rot[1]); mat4.rotateX(gm, this.rot[0]); mat4.rotateZ(gm, this.rot[2]); break; case 6: //ZYX mat4.rotateX(gm, this.rot[0]); mat4.rotateY(gm, this.rot[1]); mat4.rotateZ(gm, this.rot[2]); break; case 7: //Quaternion mat4.multiply(gm, mat4.inverse(quat4.toMat4(this.rot, MxeGeom.mat4.getTemporary())), gm); //mMatrix = MatrixMult( // MXMatrixRotationQuaternion(MXQUATERNION(lpTrack->Rot.x, lpTrack->Rot.y, lpTrack->Rot.z, lpTrack->Rot_W)), // mMatrix); break; } //SET SCALE tv[0] = this.siz[0]===0?1e-5:this.siz[0]; tv[1] = this.siz[1]===0?1e-5:this.siz[1]; tv[2] = this.siz[2]===0?1e-5:this.siz[2]; mat4.scale(gm, tv); this.worldSiz[0] = this.siz[0]; this.worldSiz[1] = this.siz[1]; this.worldSiz[2] = this.siz[2]; //SET PARENT MATRIX if(parentTrack !== null){ mat4.multiply(parentTrack.frame.worldMatrix, gm, gm); if (parentTrack.userMatrix === null){ // // if use user matrix then size is ignore var parentWorldSiz = parentTrack.frame.worldSiz; this.worldSiz[0] = this.worldSiz[0] * parentTrack.frame.worldSiz[0]; this.worldSiz[1] = this.worldSiz[1] * parentTrack.frame.worldSiz[1]; this.worldSiz[2] = this.worldSiz[2] * parentTrack.frame.worldSiz[2]; } } if (this.track.boneInfo !== null){ sector = this.track.getBoneSector(); mat4.inverse(sector.baseMatrix, this.skinMatrix); mat4.multiply(gm, this.skinMatrix, this.skinMatrix); mat4.translate(this.skinMatrix, [-sector.sectorCenter[0], -sector.sectorCenter[1], -sector.sectorCenter[2]]); } if(this.worldSiz[0] === 0 && this.worldSiz[1] === 0 && this.worldSiz[2] === 0) this.worldVisible = false; // no process in size 0. } this.validWorldMatrix = true; } finally { MxeGeom.releaseTemporary(); } }; MxeFrame3D.prototype.calcBlendRot = function(rot0, rot1, f0, f1, rollFlag) { var PI2 = Math.PI * 2.0; if(rollFlag){ if (rot0 > rot1) while (rot0 - rot1 > Math.PI) rot0 -= PI2; else while (rot1 - rot0 > Math.PI) rot1 -= PI2; return (rot0 * f0 + rot1 * f1) % PI2; } return rot0 * f0 + rot1 * f1; }; MxeFrame3D.prototype.blend = function(frame, p, blendMode, rollFlag) { var pinv = 1.0 - p; var isQuaternion = this.track.rollType === 7; this.pos[0] = this.pos[0]*pinv + frame.pos[0]*p; this.pos[1] = this.pos[1]*pinv + frame.pos[1]*p; this.pos[2] = this.pos[2]*pinv + frame.pos[2]*p; if(isQuaternion){ //QuaternionSlerp MxeGeom.quat4.slerp(this.rot, frame.rot, p, this.rot); }else{ this.rot[0] = this.calcBlendRot(this.rot[0], frame.rot[0], pinv, p, rollFlag); this.rot[1] = this.calcBlendRot(this.rot[1], frame.rot[1], pinv, p, rollFlag); this.rot[2] = this.calcBlendRot(this.rot[2], frame.rot[2], pinv, p, rollFlag); } this.siz[0] = this.siz[0]*pinv + frame.siz[0]*p; this.siz[1] = this.siz[1]*pinv + frame.siz[1]*p; this.siz[2] = this.siz[2]*pinv + frame.siz[2]*p; }; MxeFrame3D.prototype.getValidWorldMatrix = function() { if(! this.validWorldMatrix) return false; var parentTrack = this.track.parentTrack; if(parentTrack !== null){ this.validWorldMatrix = parentTrack.frame.getValidWorldMatrix(); } return this.validWorldMatrix; }; MxeFrame3D.prototype.getWorldMatrix = function() { if(this.getValidWorldMatrix()) return this.worldMatrix; var parentTrack = this.track.parentTrack; if(parentTrack !== null) parentTrack.frame.getWorldMatrix(); //for exec calcMatrix this.calcMatrix(); return this.worldMatrix; }; MxeFrame3D.prototype.localToWorld = function(localPos, worldPos) { return mat4.multiplyVec3(this.getWorldMatrix(), localPos, worldPos); }; MxeFrame3D.prototype.localToWorldVector = function(localVec, worldVec) { try { MxeGeom.useTemporary(); var m = mat4.set(this.getWorldMatrix(), MxeGeom.mat4.getTemporary()); m[12] = m[13] = m[14] = 0.0; mat4.multiplyVec3(m, localVec, worldVec); return vec3.normalize(worldVec); } finally { MxeGeom.releaseTemporary(); } }; MxeFrame3D.prototype.worldToLocal = function(worldPos, localPos) { try { MxeGeom.useTemporary(); return mat4.multiplyVec3(mat4.inverse(this.getWorldMatrix(), MxeGeom.mat4.getTemporary()), worldPos, localPos); } finally { MxeGeom.releaseTemporary(); } }; MxeFrame3D.prototype.worldToLocalVector = function(worldVec, localVec) { try { MxeGeom.useTemporary(); var m = mat4.set(this.getWorldMatrix(), MxeGeom.mat4.getTemporary()); m[12] = m[13] = m[14] = 0.0; mat4.multiplyVec3(mat4.inverse(m), worldVec, localVec); return vec3.normalize(localVec); } finally { MxeGeom.releaseTemporary(); } }; MxeFrame3D.prototype.getCrossPoint = function(pos, vec, backFlag, sectorOffset, sectorCount, result) { if(! result){ result = { crossed: false, position: vec3.create(), normal: vec3.create(), distance: 0.0, sector: null, }; }else{ result.crossed = false; } if(this.getCast() === null) return result; var sectors = this.getCast().sectors; if(sectors == null) return result; try { MxeGeom.useTemporary(); var localPos = MxeGeom.vec3.getTemporary(); this.worldToLocal(pos, localPos); var localVec = MxeGeom.vec3.getTemporary(); this.worldToLocalVector(vec, localVec); var localVecNega = MxeGeom.vec3.getTemporary(); vec3.negate(localVec, localVecNega); if (sectorOffset < 0) sectorOffset = 0; if (sectorCount < 0) sectorCount = sectors.length - sectorOffset; var touchBack = false; var polyCrossPoint = MxeGeom.vec3.getTemporary(); var polyDistance; var backPicked = false; var picked; var polyVert0 = MxeGeom.vec3.getTemporary(); var polyVert1 = MxeGeom.vec3.getTemporary(); var polyVert2 = MxeGeom.vec3.getTemporary(); var polyNorm = MxeGeom.vec3.getTemporary(); var polyNormNega = MxeGeom.vec3.getTemporary(); var polyCrossPoint = MxeGeom.quat4.getTemporary(); for(var i=sectorOffset; i<sectorOffset+sectorCount; i++) { var sector = sectors[i]; if(sector.vertexSrc === null) continue; if(sector.vertexSrc.position === null || sector.vertexSrc.position.length === 0) continue; //ghost if(sector.isSkin) continue;// do not check skin //if (lpFrame->mfFrameTypeID != ALL_MODEL) // only check base and bone // if (lpFrame->mfFrameTypeID != lpSector->msBoneSectorID) continue; var verts = sector.vertexSrc.position; var polys = sector.vertexSrc.index; var polyIdx = 0; var polyCount; var normIdx = 0; var isStripped = false; //TODO bool isStripped = (lpSector->mlpSectData->SectorOption & 0x01); // for stripped polygon if(isStripped){ polyCount = polys.length - 2; }else{ polyCount = polys.length/3; } if(sector.polygonNormals == null) sector.calcPolygonNormals(); for(var k = 0; k < polyCount; k++, normIdx+=3){ if(isStripped && (k % 2)!==0){ p0 = polys[polyIdx+2]; p1 = polys[polyIdx+1]; p2 = polys[polyIdx+0]; } else{ p0 = polys[polyIdx+1]; p1 = polys[polyIdx+2]; p2 = polys[polyIdx+0]; } if (isStripped) polyIdx++; else polyIdx+= 3; //mIs4PolyOnly ? 4 : 3; if ((p0 === p1) || (p0 === p2) || (p1 === p2)) continue; backPicked = false; polyVert0[0] = verts[p0*3]; polyVert0[1] = verts[p0*3+1]; polyVert0[2] = verts[p0*3+2]; polyVert1[0] = verts[p1*3]; polyVert1[1] = verts[p1*3+1]; polyVert1[2] = verts[p1*3+2]; polyVert2[0] = verts[p2*3]; polyVert2[1] = verts[p2*3+1]; polyVert2[2] = verts[p2*3+2]; polyNorm[0] = sector.polygonNormals[normIdx]; polyNorm[1] = sector.polygonNormals[normIdx+1]; polyNorm[2] = sector.polygonNormals[normIdx+2]; vec3.negate(polyNorm, polyNormNega); picked = MxeGeom.pick(polyVert0, polyVert1, polyVert2, polyNorm, localPos, localVec, polyCrossPoint); if (!picked) picked = MxeGeom.pick(polyVert0, polyVert1, polyVert2, polyNormNega, localPos, localVec, polyCrossPoint); // front reverse polygon if (!picked && backFlag){ backPicked = true; picked = MxeGeom.pick(polyVert0, polyVert1, polyVert2, polyNorm, localPos, localVecNega, polyCrossPoint); if (!picked) picked = MxeGeom.pick(polyVert0, polyVert1, polyVert2, polyNormNega, localPos, localVecNega, polyCrossPoint); // front reverse polygon } //TODO 4poly /* if (lpFrame->mflpModel->mIs4PolyOnly){ backPicked = false; if (!picked) picked = geomPick(lpVert[lpPoly[0]], lpVert[lpPoly[2]], lpVert[lpPoly[3]], *lpNorm, &crossPoint, &distance, startNorm, startPos); if (!picked) picked = geomPick(lpVert[lpPoly[0]], lpVert[lpPoly[2]], lpVert[lpPoly[3]], - *lpNorm, &crossPoint, &distance, startNorm, startPos); if (!picked && backFlag){ backPicked = true; picked = geomPick(lpVert[lpPoly[0]], lpVert[lpPoly[2]], lpVert[lpPoly[3]], *lpNorm, &crossPoint, &distance, - startNorm, startPos); if (!picked) picked = geomPick(lpVert[lpPoly[0]], lpVert[lpPoly[2]], lpVert[lpPoly[3]], - *lpNorm, &crossPoint, &distance, - startNorm, startPos); } lpPoly++; } */ if (!picked) continue; polyDistance = polyCrossPoint[3]; if (polyDistance < 0) polyDistance = - polyDistance; if(! result.crossed || result.distance > polyDistance){ result.crossed = true; result.distance = polyDistance; vec3.set(polyCrossPoint, result.position); // The collision point is copied for the inside of the polygon. vec3.set(polyNorm, result.normal); result.sector = sector; touchBack = backPicked; } } } if (result.crossed){ var m = mat4.set(this.getWorldMatrix(), MxeGeom.mat4.getTemporary()); m[12] = m[13] = m[14] = 0.0; mat4.multiplyVec3(m, vec3.subtract(result.position, localPos, localPos), localPos); result.distance = vec3.length(localPos); if (touchBack) result.distance = - result.distance; this.localToWorld(result.position, result.position); this.localToWorldVector(result.normal, result.normal); } return result; } finally { MxeGeom.releaseTemporary(); } }; MxeFrame3D.prototype.getMinimumDistance = function(pos, sectorOffset, sectorCount, result) { if(! result){ result = { status: -1, position: vec3.create(), normal: vec3.create(), distance: 0.0, sector: null, }; }else{ result.status = -1; } if(this.getCast() === null) return result; var sectors = this.getCast().sectors; if(sectors == null) return result; try { MxeGeom.useTemporary(); var localPos = MxeGeom.vec3.getTemporary(); this.worldToLocal(pos, localPos); if (sectorOffset < 0) sectorOffset = 0; if (sectorCount < 0) sectorCount = sectors.length - sectorOffset; //-- // A certain point and the beeline with the polygon of the model var stat; var i, j; var v0 = MxeGeom.vec3.getTemporary(); var v1 = MxeGeom.vec3.getTemporary(); var v2 = MxeGeom.vec3.getTemporary(); var v3 = MxeGeom.vec3.getTemporary(); var minPos = MxeGeom.quat4.getTemporary(); var ansP0, ansP1, ansP2, ansNormIdx; //for get answer normal for (i=sectorOffset; i<sectorOffset+sectorCount; i++){ // The second power table of the distance in the point and the each vertex is prepared in the start. var sector = sectors[i]; if(sector.vertexSrc === null) continue; if(sector.vertexSrc.position === null || sector.vertexSrc.position.length === 0) continue; //ghost if(sector.isSkin) continue;// do not check skin //if (lpFrame->mfFrameTypeID != ALL_MODEL) // only check base and bone // if (lpFrame->mfFrameTypeID != lpSector->msBoneSectorID) continue; var verts = sector.vertexSrc.position; var polys = sector.vertexSrc.index; var polyIdx = 0; var polyCount; var normIdx = 0; var isStripped = false; //TODO bool isStripped = (lpSector->mlpSectData->SectorOption & 0x01); // for stripped polygon if(isStripped){ polyCount = polys.length - 2; }else{ polyCount = polys.length/3; } var nvert = verts.length/3; var distanceTable = new Float32Array(nvert); for (j=0; j<nvert; j++){ v0[0] = verts[j*3]; v0[1] = verts[j*3+1]; v0[2] = verts[j*3+2]; distanceTable[j] = vec3.dot(vec3.subtract(v0, localPos), v0); //length^2 } // The minimal distance with each polygon var d0, d1, d2; var p0, p1, p2; for (j=0; j<polyCount; j++, normIdx+=3){ if(isStripped && (j % 2)!==0){ p0 = polys[polyIdx+2]; p1 = polys[polyIdx+1]; p2 = polys[polyIdx+0]; } else{ p0 = polys[polyIdx+1]; p1 = polys[polyIdx+2]; p2 = polys[polyIdx+0]; } if (isStripped) polyIdx++; else polyIdx+= 3; //mIs4PolyOnly ? 4 : 3; if ((p0 === p1) || (p0 === p2) || (p1 === p2)) continue; v0[0] = verts[p0*3]; v0[1] = verts[p0*3+1]; v0[2] = verts[p0*3+2]; d0 = distanceTable[p0]; v1[0] = verts[p1*3]; v1[1] = verts[p1*3+1]; v1[2] = verts[p1*3+2]; d1 = distanceTable[p1]; v2[0] = verts[p2*3]; v2[1] = verts[p2*3+1]; v2[2] = verts[p2*3+2]; d2 = distanceTable[p2]; stat = MxeGeom.getPolygonNearestPoint(localPos, v0, v1, v2, d0, d1, d2, minPos); if(stat < 0) continue; if (result.status < 0 || result.distance > minPos[3]){ result.distance = minPos[3]; vec3.set(minPos, result.position); //answerNorm = lpSector->mslpPolyNormal[j]; ansP0 = p0; ansP1 = p1; ansP2 = p2; ansNormIdx = normIdx; result.sector = sector; result.status = stat; } } } //-- if(result.status > -1){ if(result.sector.polygonNormals){ result.normal[0] = result.sector.polygonNormals[ansNormIdx*3]; result.normal[1] = result.sector.polygonNormals[ansNormIdx*3+1]; result.normal[2] = result.sector.polygonNormals[ansNormIdx*3+2]; }else{ var verts = result.sector.vertexSrc.position; v0[0] = verts[ansP0*3]; v0[1] = verts[ansP0*3+1]; v0[2] = verts[ansP0*3+2]; v1[0] = verts[ansP1*3]; v1[1] = verts[ansP1*3+1]; v1[2] = verts[ansP1*3+2]; v2[0] = verts[ansP2*3]; v2[1] = verts[ansP2*3+1]; v2[2] = verts[ansP2*3+2]; vec3.cross(vec3.subtract(v1, v0, result.normal), vec3.subtract(v2, v1, v3)); vec3.normalize(result.normal); //TODO check need this } var m = mat4.set(this.getWorldMatrix(), MxeGeom.mat4.getTemporary()); m[12] = m[13] = m[14] = 0.0; mat4.multiplyVec3(m, vec3.subtract(result.position, localPos, localPos), localPos); result.distance = vec3.length(localPos); this.localToWorld(result.position, result.position); this.localToWorldVector(result.normal, result.normal); } return result; } finally { MxeGeom.releaseTemporary(); } }; //ik-- MxeFrame3D.prototype.resolveIK = function() { var ik = this.track.ikInfo; if(! ik || ! ik.targetBone) return; if(this.track.rollType !== 7) //not quaternion return; try { MxeGeom.useTemporary(); var maxangle = ik.controlWeight * 4; var axis = MxeGeom.vec3.getTemporary(); var axisLen = 0.0; var ikbonePosW = MxeGeom.vec3.getTemporary(); ikbonePosW[0] = this.worldMatrix[12]; ikbonePosW[1] = this.worldMatrix[13]; ikbonePosW[2] = this.worldMatrix[14]; var ikbonePos = MxeGeom.vec3.getTemporary(); var ikboneVec = MxeGeom.vec3.getTemporary(); var ikboneLen = 0.0; var bonePos = MxeGeom.vec3.getTemporary(); var minLength = 0.1 * vec3.length(vec3.subtract(ik.targetBone.boneInfo.boneSector.sectorCenter, ik.targetBone.parentTrack.boneInfo.boneSector.sectorCenter, axis)); var targetFrame = ik.targetBone.frame; var targetPosW = MxeGeom.vec3.getTemporary(); var targetPos = MxeGeom.vec3.getTemporary(); var targetVec = MxeGeom.vec3.getTemporary(); var targetVecLen = 0.0; var sinTheta = 0.0; var theta = 0.0; var q = MxeGeom.quat4.getTemporary(); var boneFrame = null; var childBoneFrame = null; var c = 0.0; for (var n = 0; n < ik.iterations; n++) { targetPosW[0] = targetFrame.worldMatrix[12]; targetPosW[1] = targetFrame.worldMatrix[13]; targetPosW[2] = targetFrame.worldMatrix[14]; if (minLength > vec3.length(vec3.subtract(targetPosW, ikbonePosW, axis))) { break; } for (var i = 0; i < ik.childBones.length; i++) { boneFrame = ik.childBones[i].frame; //bonePos[0] = boneFrame.worldMatrix[12]; //bonePos[1] = boneFrame.worldMatrix[13]; //bonePos[2] = boneFrame.worldMatrix[14]; bonePos[0] = 0; bonePos[1] = 0; bonePos[2] = 0; if (i > 0){ targetPosW[0] = targetFrame.worldMatrix[12]; targetPosW[1] = targetFrame.worldMatrix[13]; targetPosW[2] = targetFrame.worldMatrix[14]; } boneFrame.worldToLocal(targetPosW, targetPos); boneFrame.worldToLocal(ikbonePosW, ikbonePos); targetVec = vec3.subtract(targetPos, bonePos, targetVec); targetVecLen = vec3.length(targetVec); if (targetVecLen < minLength) continue; ikboneVec = vec3.subtract(ikbonePos, bonePos, ikboneVec); ikboneVecLen = vec3.length(ikboneVec); if (ikboneVecLen < minLength) continue; axis = vec3.cross(targetVec, ikboneVec, axis); axisLen = vec3.length(axis); sinTheta = axisLen / ikboneVecLen / targetVecLen; if (sinTheta < 0.001) continue; theta = Math.asin(sinTheta); if (vec3.dot(targetVec, ikboneVec) < 0) { theta = 3.141592653589793 - theta; } if (theta > maxangle) theta = maxangle; quat4.set(vec3.scale(axis, Math.sin(theta / 2) / axisLen), q); q[3] = Math.cos(theta / 2); quat4.multiply(q, boneFrame.rot); switch(boneFrame.track.constraint){ case 1: //X only c = q[3]; quat4.set([-Math.sqrt(1 - c * c), 0, 0, c], q); break; case 2: //Y only c = q[3]; quat4.set([0, -Math.sqrt(1 - c * c), 0, c], q); break; case 4: //Z only c = q[3]; quat4.set([0, 0, -Math.sqrt(1 - c * c), c], q); break; default: } quat4.normalize(q); quat4.set(q, boneFrame.rot); for(var j=i; j>=0; j--){ childBoneFrame = ik.childBones[j].frame; childBoneFrame.calcMatrix(); } targetFrame.calcMatrix(); } } } finally { MxeGeom.releaseTemporary(); } }; //--ik MxeFrame3D.prototype.prepareRender = function(render) { //CStage::ModifyFrame() this.updateRenderList(); var parentTrack = this.track.parentTrack; var parentVisible = true; if(parentTrack !== null){ parentVisible = parentTrack.frame.worldVisible; } this.worldVisible = this.visible && parentVisible; //if(this.worldVisible) this.calcMatrix(); this.validWorldMatrix = true; if(this.worldVisible && this.renderList !== null){ var i; var item; var cast; for(i=0; i<this.renderList.length; i++){ item = this.renderList[i]; if(item[0] === 0){ //CT_MODEL item[1].prepareRender(render, this); }else if(item[0] === 1){ //CT_TEXTURE(billboard) cast = item[1].frame.getCast(); if(cast !== null) cast.prepareRender(render, this); } } } }; MxeFrame3D.prototype.calcBillboardMatrix = function(cameraMatrix, srcMatrix, dstMatrix) { try{ MxeGeom.useTemporary(); var selfY = Math.atan2(srcMatrix[10], srcMatrix[8]); var camDirY = Math.atan2(cameraMatrix[10], cameraMatrix[8]); var rotYMatrix = MxeGeom.mat4.getTemporary(); mat4.identity(rotYMatrix); mat4.multiply(srcMatrix, mat4.rotateY(rotYMatrix, camDirY - selfY), dstMatrix); mat4.multiply(cameraMatrix, dstMatrix, dstMatrix); } finally { MxeGeom.releaseTemporary(); } if(this.track.billboardType === 3){ //billboard HV dstMatrix[0] = this.worldSiz[0]; if (dstMatrix[0] < 0.0) dstMatrix[0] = - dstMatrix[0]; dstMatrix[5] = this.worldSiz[1]; if (dstMatrix[5] < 0.0) dstMatrix[5] = - dstMatrix[5]; dstMatrix[10] = -1.0; dstMatrix[1] = dstMatrix[2] = dstMatrix[3] = dstMatrix[4] = dstMatrix[6] = dstMatrix[7] = dstMatrix[8] = dstMatrix[9] = 0.0; } //MxeGeom.mat4.switchHand(dstMatrix); }; MxeFrame3D.prototype.applyCamera = function(cameraMatrix) { if(! this.worldVisible) return; if(this.track.billboardType > 0){ //billboard if(this.billboardMatrix === null) this.billboardMatrix = mat4.create(); this.calcBillboardMatrix(cameraMatrix, this.worldMatrix, this.billboardMatrix); } }; MxeFrame3D.prototype.setCast = function(cast) { this.checkCastType(cast); if(this.cast === cast) return; this.cast = cast; if(this.track.castType === 0){ //CT_MODEL this.renderListValid = false; } }; MxeFrame3D.prototype.updateRenderList = function() { if(this.renderListValid) return; if(this.renderList !== null && this.renderList !== this.track.renderList) this.renderList.length = 0; if(this.track.cast === this.cast){ this.renderList = this.track.renderList; }else{ if(this.track.castType === MxeCast.def.CT_MODEL){ var model = this.cast; if(model === null || model.sectors === null || model.sectors.length === 0){ this.renderList = null; }else{ this.renderList = new Array(model.sectors.length); var count = 0; var sector; for(var i=0; i<model.sectors.length; i++){ sector = model.sectors[i]; if(sector.indexBuffer === null) continue; //no poly this.renderList[count] = [0, model.sectors[i], [this.track]]; count++; } this.renderList.length = count; } }else{ this.renderList = this.trackRenderList; } } this.renderListValid = true; }; var MxeFrame2D = function() { this.initialize.apply(this, arguments); }; MxeFrame2D.prototype = Object.create(MxeFrame.prototype); MxeFrame2D.prototype.constructor = MxeFrame2D; MxeFrame2D.prototype.initialize = function(track) { MxeFrame.prototype.initialize.apply(this, arguments); if(track !== null){ this.cast = this.track.cast; } this.pos = new Float32Array([0.0,0.0,0.0]); this.siz = new Float32Array([1.0,1.0,0.0]); this.rot = 0.0; this.useBlending = false; this.enableTransparentDiscard = false; //subモードでの抜け色SDKとの互換性のためのフラグ this.alpha = 1.0; this.blendFactorSrc = 0x0302; //GL_SRC_ALPHA this.blendFactorDst = 0x0303; //GL_ONE_MINUS_SRC_ALPHA this.blendFactorAlphaSrc = 0x0302; //GL_SRC_ALPHA this.blendFactorAlphaDst = 0x0304; //GL_DST_ALPHA this.worldPos = vec3.create(); this.worldSiz = vec3.create(); //this.worldRot = 0.0; this.worldMatrix = mat4.create(); this.viewMatrix = mat4.create(); this.magFilter = 0x2600; //GL_NEAREST this.minFilter = 0x2600; //GL_NEAREST this.wrap_s = 0x812f; //GL_CLAMP_TO_EDGE this.wrap_t = 0x812f; //GL_CLAMP_TO_EDGE //TODO private this.parentMatrix = mat4.create(); this.rotOffset = vec3.create(); this.rotOffset[2] = 0.0; this.rotOffsetNega = vec3.create(); this.rotOffsetNega[2] = 0.0; //clipping this.clippingMode = 0; //0:disable 1:world 2:local this.clippingRect = new Float32Array(4); //[0]left [1]top [2]right [3]bottom (not include bottom-right) //procedural this.proceduralParams = null; //reference size(for puppet) this.referenceWidth = 0; this.referenceHeight = 0; this.renderList = null; }; MxeFrame2D.prototype.copyForProcedural = function(srcFrame) { this.track = srcFrame.track; this.visible = srcFrame.visible; vec3.set(srcFrame.pos, this.pos); vec3.set(srcFrame.siz, this.siz); this.rot = srcFrame.rot; this.useBlending = srcFrame.useBlending; this.alpha = srcFrame.alpha; this.blendFactorSrc = srcFrame.blendFactorSrc; this.blendFactorDst = srcFrame.blendFactorDst; this.blendFactorAlphaSrc = srcFrame.blendFactorAlphaSrc; this.blendFactorAlphaDst = srcFrame.blendFactorAlphaDst; this.magFilter = srcFrame.magFilter; this.minFilter = srcFrame.minFilter; this.wrap_s = srcFrame.wrap_s; this.wrap_t = srcFrame.wrap_t; this.clippingMode = srcFrame.clippingMode; this.clippingRect[0] = srcFrame.clippingRect[0]; this.clippingRect[1] = srcFrame.clippingRect[1]; this.clippingRect[2] = srcFrame.clippingRect[2]; this.clippingRect[3] = srcFrame.clippingRect[3]; } MxeFrame2D.prototype.copyForPuppet = function(scoreFrame) { this.visible = scoreFrame.visible; //vec3.set(scoreFrame.siz, this.siz); this.magFilter = scoreFrame.magFilter; this.minFilter = scoreFrame.minFilter; this.useBlending = scoreFrame.useBlending; this.alpha = scoreFrame.alpha; this.blendFactorSrc = scoreFrame.blendFactorSrc; this.blendFactorDst = scoreFrame.blendFactorDst; this.blendFactorAlphaSrc = scoreFrame.blendFactorAlphaSrc; this.blendFactorAlphaDst = scoreFrame.blendFactorAlphaDst; this.wrap_s = scoreFrame.wrap_s; this.wrap_t = scoreFrame.wrap_t; this.proceduralParams = new Array(scoreFrame.proceduralParams); }; MxeFrame2D.prototype.make = function(frameNum) { this.proceduralParams = this.track.proceduralParams; if(frameNum === -1) frameNum = this.track.score.currentFrame; //if(frameNum === this.frameNum) return; this.frameNum = frameNum; if(frameNum >= this.track.animationData.length){ this.visible = false; return; } var frameData = this.track.animationData[frameNum]; if(frameData == null){ this.visible = false; return; } this.cast = frameData[0]; this.pos[0] = frameData[1][0]; this.pos[1] = frameData[1][1]; this.pos[2] = 0.0; this.siz[0] = frameData[2][0]; this.siz[1] = frameData[2][1]; this.siz[2] = 0.0; this.rot = frameData[3]; this.enableTransparentDiscard = false; if(frameData.length < 4){ this.rot = 0.0; this.useBlending = false; this.blendFactorSrc = 0x0302; //GL_SRC_ALPHA this.blendFactorDst = 0x0303; //GL_ONE_MINUS_SRC_ALPHA this.blendFactorAlphaSrc = 0x0302; //GL_SRC_ALPHA this.blendFactorAlphaDst = 0x0304; //GL_DST_ALPHA this.alpha = 1.0; }else{ //has extension this.rot = frameData[3]; if((frameData[4] & 0x40) !== 0){ this.magFilter = 0x2601; //GL_LINEAR this.minFilter = 0x2601; //GL_LINEAR } var blendMode = 0; if((frameData[4] & 0x20) !== 0) blendMode = 2; //sub if((frameData[4] & 0x80) !== 0) blendMode = 1; //add if(blendMode == 0){ this.useBlending = false; this.blendFactorSrc = 0x0302; //GL_SRC_ALPHA this.blendFactorDst = 0x0303; //GL_ONE_MINUS_SRC_ALPHA this.blendFactorAlphaSrc = 0x0302; //GL_SRC_ALPHA this.blendFactorAlphaDst = 0x0304; //GL_DST_ALPHA }else if(blendMode == 1){ //add this.useBlending = true; this.blendFactorSrc = 0x0302; //GL_SRC_ALPHA this.blendFactorDst = 0x0001; //GL_ONE this.blendFactorAlphaSrc = 0x0302; //GL_SRC_ALPHA this.blendFactorAlphaDst = 0x0304; //GL_DST_ALPHA }else if(blendMode == 2){ //sub this.useBlending = true; this.enableTransparentDiscard = true; this.blendFactorSrc = 0x0303; //GL_ONE_MINUS_SRC_ALPHA this.blendFactorDst = 0x0301; //GL_ONE_MINUS_SRC_COLOR this.blendFactorAlphaSrc = 0x0302; //GL_SRC_ALPHA this.blendFactorAlphaDst = 0x0304; //GL_DST_ALPHA } this.alpha = frameData[5]; } if(this.cast !== null) this.visible = true; } //スケール1倍の時の幅 MxeFrame2D.prototype.getWidth1x = function() { return this.referenceWidth > 0 ? this.referenceWidth : this.cast.getWidth(); }; //スケール1倍の時の高さ MxeFrame2D.prototype.getHeight1x = function() { return this.referenceHeight > 0 ? this.referenceHeight : this.cast.getHeight(); }; MxeFrame2D.prototype.calcMatrix = function(viewportWidth, viewportHeight) { /* var xsiz = this.siz[0]/this.cast.image.width; var ysiz = this.siz[1]/this.cast.image.height; var frameWidth = this.siz[0]; var frameHeight = this.siz[1]; */ if(viewportWidth === 0.0 || viewportHeight === 0.0) return; //can't calc var xsiz = 1.0; var ysiz = 1.0; if(this.cast.scalable === true){ xsiz = this.siz[0]; ysiz = this.siz[1]; } var width1x = this.getWidth1x(); var height1x = this.getHeight1x(); var frameWidth = width1x * xsiz; var frameHeight = height1x * ysiz; var parentFrame = null; if(this.track !== null && this.track.parentTrack !== null){ parentFrame = this.track.parentTrack.frame; } if(this.cast.scalable === true && parentFrame !== null){ this.worldSiz[0] = xsiz * parentFrame.worldSiz[0]; this.worldSiz[1] = ysiz * parentFrame.worldSiz[1]; this.worldSiz[2] = 1.0; //this.worldRot = this.rot + parentFrame.worldRot; }else{ this.worldSiz[0] = xsiz; this.worldSiz[1] = ysiz; this.worldSiz[2] = 1.0; //this.worldRot = this.rot; } if(this.worldSiz[0] === 0.0 && this.worldSiz[1] === 0.0){ this.worldVisible = false; // no process in size 0. return; } this.worldPos[0] = Math.floor(this.pos[0]); this.worldPos[1] = Math.floor(this.pos[1]); this.worldPos[2] = 0.0; if(parentFrame !== null){ this.worldPos[0]-= parentFrame.getWidth1x()/2.0; this.worldPos[1]-= parentFrame.getHeight1x()/2.0; //get top-left mat4.identity(this.worldMatrix); this.worldMatrix[12] = this.worldPos[0]; this.worldMatrix[13] = this.worldPos[1]; MxeGeom.mat4.scale2D(parentFrame.worldMatrix, parentFrame.worldSiz, this.parentMatrix); MxeGeom.mat4.multiply2D(this.parentMatrix, this.worldMatrix, this.worldMatrix); //get floor error var errX = this.worldMatrix[12] - Math.floor(this.worldMatrix[12]); var errY = this.worldMatrix[13] - Math.floor(this.worldMatrix[13]); this.worldPos[0] = this.worldMatrix[12] - errX; this.worldPos[1] = this.worldMatrix[13] - errY; } //get center pos var dx = frameWidth/2.0; var dy = frameHeight/2.0; if(parentFrame !== null){ mat4.identity(this.worldMatrix); this.worldMatrix[12] = dx; this.worldMatrix[13] = dy; //if(this.cast.rotatable === true) mat4.set(parentFrame.worldMatrix, this.parentMatrix); //else // mat4.identity(this.parentMatrix); if(this.cast.scalable === true) MxeGeom.mat4.scale2D(this.parentMatrix, parentFrame.worldSiz); this.parentMatrix[12] = 0; this.parentMatrix[13] = 0; MxeGeom.mat4.multiply2D(this.parentMatrix, this.worldMatrix, this.worldMatrix); dx = this.worldMatrix[12]; dy = this.worldMatrix[13]; } this.worldPos[0]+= dx; this.worldPos[1]+= dy; //calc world matrix mat4.identity(this.worldMatrix); if(parentFrame !== null){ mat4.set(parentFrame.worldMatrix, this.worldMatrix); } this.worldMatrix[12] = this.worldPos[0]; this.worldMatrix[13] = this.worldPos[1]; if(this.cast.rotatable === true){ if(this.rot !== 0.0){ this.rotOffset[0] = this.cast.rotateCenter[0]*width1x*0.5*this.worldSiz[0]; this.rotOffset[1] = this.cast.rotateCenter[1]*height1x*0.5*this.worldSiz[1]; this.rotOffsetNega[0] = - this.rotOffset[0]; this.rotOffsetNega[1] = - this.rotOffset[1]; MxeGeom.mat4.translate2D(this.worldMatrix, this.rotOffset); MxeGeom.mat4.rotate2D(this.worldMatrix, this.rot); MxeGeom.mat4.translate2D(this.worldMatrix, this.rotOffsetNega); } } //calc view matrix mat4.identity(this.viewMatrix); MxeGeom.mat4.scale2D(this.viewMatrix, [1.0/viewportWidth, 1.0/viewportHeight, 1.0]); if(this.cast.rotatable === true) MxeGeom.mat4.multiply2D(this.viewMatrix, this.worldMatrix, this.viewMatrix); else MxeGeom.mat4.translate2D(this.viewMatrix, this.worldPos); MxeGeom.mat4.scale2D(this.viewMatrix, this.worldSiz); MxeGeom.mat4.scale2D(this.viewMatrix, [width1x, height1x, 1.0]); //to right handed this.viewMatrix[1] = -this.viewMatrix[1]; this.viewMatrix[4] = -this.viewMatrix[4]; this.viewMatrix[12] = 2.0*this.worldMatrix[12]/viewportWidth-1.0; this.viewMatrix[13] = 1.0-2.0*this.worldMatrix[13]/viewportHeight; }; MxeFrame2D.prototype.prepareRender = function(render) { if(this.renderList === null && this.track !== null) this.renderList = this.track.renderList; var parentTrack = this.track === null ? null :this.track.parentTrack; var parentVisible = true; if(parentTrack !== null){ parentVisible = parentTrack.frame.worldVisible; } this.worldVisible = this.visible && parentVisible; if(this.worldVisible && this.cast !== null) this.cast.prepareRender(render, this); if(this.cast === null)// || ! this.cast.getPrepared()) this.worldVisible = false; if(this.worldVisible){ this.calcMatrix(render.viewportWidth, render.viewportHeight); } } var MxeFrameMaterial = function() { this.initialize.apply(this, arguments); }; MxeFrameMaterial.prototype = Object.create(MxeFrame3D.prototype); MxeFrameMaterial.prototype.constructor = MxeFrameMaterial; MxeFrameMaterial.prototype.initialize = function(track) { MxeFrame3D.prototype.initialize.apply(this, arguments); }; MxeFrameMaterial.prototype.make = function(frameNum) { if(frameNum === -1) frameNum = this.track.score.currentFrame; //if(frameNum === this.frameNum) return; this.frameNum = frameNum; this.validWorldMatrix = false; this.visible = true; //TODO }; MxeFrameMaterial.prototype.calcMatrix = function() { var parentTrack = this.track.parentTrack; if(parentTrack === null){ mat4.identity(this.worldMatrix); mat4.identity(this.skinMatrix); this.worldSiz[0] = 1.0; this.worldSiz[1] = 1.0; this.worldSiz[2] = 1.0; }else{ mat4.set(parentTrack.frame.worldMatrix, this.worldMatrix); mat4.set(parentTrack.frame.skinMatrix, this.skinMatrix); vec3.set(parentTrack.frame.worldSiz, this.worldSiz); } this.validWorldMatrix = true; }; var MxeGeom = function() { }; MxeGeom.def = { MAX_FLOAT: 1e+30, }; MxeGeom.useTemporary = function() { MxeGeom.mat4.tempCtStack[++MxeGeom.mat4.tempCtStackIdx] = 0; MxeGeom.quat4.tempCtStack[++MxeGeom.quat4.tempCtStackIdx] = 0; MxeGeom.vec3.tempCtStack[++MxeGeom.vec3.tempCtStackIdx] = 0; }; MxeGeom.releaseTemporary = function() { MxeGeom.mat4.tempIdx-= MxeGeom.mat4.tempCtStack[MxeGeom.mat4.tempCtStackIdx--]; MxeGeom.quat4.tempIdx-= MxeGeom.quat4.tempCtStack[MxeGeom.quat4.tempCtStackIdx--]; MxeGeom.vec3.tempIdx-= MxeGeom.vec3.tempCtStack[MxeGeom.vec3.tempCtStackIdx--]; }; MxeGeom.mat4 = function() {}; MxeGeom.mat4.tempIdx = -1; MxeGeom.mat4.temps = []; MxeGeom.mat4.tempCtStackIdx = -1; MxeGeom.mat4.tempCtStack = []; MxeGeom.mat4.getTemporary = function() { this.tempIdx++; this.tempCtStack[this.tempCtStackIdx]++; if(this.tempIdx === this.temps.length){ this.temps.push(mat4.create()); } return this.temps[this.tempIdx]; }; MxeGeom.mat4.switchHand = function(m) { //right handed <--> left handed m[2] = - m[2]; m[6] = - m[6]; m[10] = - m[10]; m[14] = - m[14]; return m; }; MxeGeom.mat4.perspective = function(angle, aspectRatio, near, far, m) { var tanFov = Math.tan(angle*Math.PI/360.0); m[0] = 1.0/tanFov; m[5] = aspectRatio/ tanFov; //m[10] = far / (near - far); m[10] = -(far + near)/(far - near); m[11] = -1.0; //m[14] = m[10] * near; m[14] = -((2.0*far)*near)/(far - near); }; MxeGeom.mat4.multiply2D = function(mat, mat2, dest) { if(!dest) { dest = mat } var a00 = mat[0], a01 = mat[1], a03 = mat[3]; var a10 = mat[4], a11 = mat[5], a13 = mat[7]; var a30 = mat[12], a31 = mat[13], a33 = mat[15]; var b00 = mat2[0], b01 = mat2[1], b03 = mat2[3]; var b10 = mat2[4], b11 = mat2[5], b13 = mat2[7]; var b30 = mat2[12], b31 = mat2[13], b33 = mat2[15]; dest[0] = b00*a00 + b01*a10 + b03*a30; dest[1] = b00*a01 + b01*a11 + b03*a31; dest[3] = b00*a03 + b01*a13 + b03*a33; dest[4] = b10*a00 + b11*a10 + b13*a30; dest[5] = b10*a01 + b11*a11 + b13*a31; dest[7] = b10*a03 + b11*a13 + b13*a33; dest[12] = b30*a00 + b31*a10 + b33*a30; dest[13] = b30*a01 + b31*a11 + b33*a31; dest[15] = b30*a03 + b31*a13 + b33*a33; dest[2] = 0.0; dest[6] = 0.0; dest[8] = 0.0; dest[9] = 0.0; dest[10] = 1.0; dest[11] = 0.0; dest[14] = 0.0; return dest; }; MxeGeom.mat4.translate2D = function(mat, vec, dest) { var x = vec[0], y = vec[1]; if(!dest || mat == dest) { mat[12] = mat[0]*x + mat[4]*y + mat[12]; mat[13] = mat[1]*x + mat[5]*y + mat[13]; mat[15] = mat[3]*x + mat[7]*y + mat[15]; return mat; } var a00 = mat[0], a01 = mat[1], a03 = mat[3]; var a10 = mat[4], a11 = mat[5], a13 = mat[7]; dest[0] = a00; dest[1] = a01; dest[3] = a03; dest[4] = a10; dest[5] = a11; dest[7] = a13; dest[12] = a00*x + a10*y + mat[12]; dest[13] = a01*x + a11*y + mat[13]; dest[15] = a03*x + a13*y + mat[15]; dest[2] = 0.0; dest[6] = 0.0; dest[8] = 0.0; dest[9] = 0.0; dest[10] = 1.0; dest[11] = 0.0; dest[14] = 0.0; return dest; }; MxeGeom.mat4.scale2D = function(mat, vec, dest) { var x = vec[0], y = vec[1]; if(!dest || mat == dest) { mat[0] *= x; mat[1] *= x; mat[3] *= x; mat[4] *= y; mat[5] *= y; mat[7] *= y; return mat; } dest[0] = mat[0]*x; dest[1] = mat[1]*x; dest[3] = mat[3]*x; dest[4] = mat[4]*y; dest[5] = mat[5]*y; dest[7] = mat[7]*y; dest[12] = mat[12]; dest[13] = mat[13]; dest[15] = mat[15]; dest[2] = 0.0; dest[6] = 0.0; dest[8] = 0.0; dest[9] = 0.0; dest[10] = 1.0; dest[11] = 0.0; dest[14] = 0.0; return dest; }; MxeGeom.mat4.rotate2D = function(mat, angle, dest) { var s = Math.sin(angle); var c = Math.cos(angle); var a00 = mat[0], a01 = mat[1], a03 = mat[3]; var a10 = mat[4], a11 = mat[5], a13 = mat[7]; if(!dest) { dest = mat } else if(mat != dest) { dest[12] = mat[12]; dest[13] = mat[13]; dest[15] = mat[15]; } dest[0] = a00*c + a10*s; dest[1] = a01*c + a11*s; dest[3] = a03*c + a13*s; dest[4] = a00*-s + a10*c; dest[5] = a01*-s + a11*c; dest[7] = a03*-s + a13*c; dest[2] = 0.0; dest[6] = 0.0; dest[8] = 0.0; dest[9] = 0.0; dest[10] = 1.0; dest[11] = 0.0; dest[14] = 0.0; return dest; }; MxeGeom.quat4 = function() {}; MxeGeom.quat4.tempIdx = -1; MxeGeom.quat4.temps = []; MxeGeom.quat4.tempCtStackIdx = -1; MxeGeom.quat4.tempCtStack = []; MxeGeom.quat4.getTemporary = function() { this.tempIdx++; this.tempCtStack[this.tempCtStackIdx]++; if(this.tempIdx === this.temps.length){ this.temps.push(quat4.create()); } return this.temps[this.tempIdx]; }; MxeGeom.quat4.slerp = function(q0, q1, slerp, qdst){ var dot; var f0; var f1; var angle; qdst||(qdst=q0); dot = q0[0]*q1[0] + q0[1]*q1[1] + q0[2]*q1[2] + q0[3]*q1[3]; if(dot < 0.0){ dot = -dot; qdst[0] = -q1[0]; qdst[1] = -q1[1]; qdst[2] = -q1[2]; qdst[3] = -q1[3]; }else{ qdst[0] = q0[0]; qdst[1] = q0[1]; qdst[2] = q0[2]; qdst[3] = q0[3]; } if(dot >= 1.0){ qdst[0] = q0[0]; qdst[1] = q0[1]; qdst[2] = q0[2]; qdst[3] = q0[3]; }else{ if(dot < 0.999){ angle = Math.acos(dot); f0 = Math.sin(angle*(1.0-slerp))/Math.sin(angle); f1 = Math.sin(angle*slerp)/Math.sin(angle); }else{ // if the angle is small, use linear interpolation f0 = slerp; f1 = 1.0 - slerp; } qdst[0] = f0*q0[0] + f1*q1[0]; qdst[1] = f0*q0[1] + f1*q1[1]; qdst[2] = f0*q0[2] + f1*q1[2]; qdst[3] = f0*q0[3] + f1*q1[3]; } return qdst; }; MxeGeom.vec3 = function() {}; MxeGeom.vec3.tempIdx = -1; MxeGeom.vec3.temps = []; MxeGeom.vec3.tempCtStackIdx = -1; MxeGeom.vec3.tempCtStack = []; MxeGeom.vec3.getTemporary = function() { this.tempIdx++; this.tempCtStack[this.tempCtStackIdx]++; if(this.tempIdx === this.temps.length){ this.temps.push(vec3.create()); } return this.temps[this.tempIdx]; }; MxeGeom.pick = function(polyV0, polyV1, polyV2, polyNorm, pos, dir, crossPoint) { //crossPoint[3] is distance try{ MxeGeom.useTemporary(); var dist; // Official plane and intersection of line = Q+L* N・(V?Q)/N・L // Q: Starting point L: Line V:1 top N: Plane normal var dp = vec3.dot(polyNorm, dir); if (dp >= 0.0) return false; // 2010/07/01 if (dp < 0.002 && dp > - 0.002) return false; // Because the less influence of a minute polygon dist = vec3.dot(polyNorm, vec3.subtract(polyV0, pos, MxeGeom.vec3.getTemporary()))/dp; if (dist < 0.0) return false; crossPoint[0] = dir[0] * dist + pos[0]; crossPoint[1] = dir[1] * dist + pos[1]; crossPoint[2] = dir[2] * dist + pos[2]; crossPoint[3] = dist; vec3.subtract(polyV0, crossPoint); // Difference vector of intersection and the each polygon vertex vec3.subtract(polyV1, crossPoint); vec3.subtract(polyV2, crossPoint); var cp0 = MxeGeom.vec3.getTemporary(); var cp1 = MxeGeom.vec3.getTemporary(); vec3.cross(polyV0, polyV1, cp0); // The direction of angle that three difference vectors make vec3.cross(polyV1, polyV2, cp1); if (vec3.dot(cp0, cp1) <= 0.0) return false; // If it is 180 degrees or more, it is judged the outside of the polygon. vec3.cross(polyV2, polyV0, cp1); if (vec3.dot(cp0, cp1) <= 0.0) return false; return true; } finally { MxeGeom.releaseTemporary(); } }; MxeGeom.getPolygonNearestPoint = function(pos, v0, v1, v2, d0, d1, d2, nearestPoint) { //nearestPoint[3] is distance^2 if (d0 === 0.0){ vec3.set(v0, nearestPoint); nearestPoint[3] = 0.0; return 2; } if (d1 === 0.0){ vec3.set(v1, nearestPoint); nearestPoint[3] = 0.0; return 2; } if (d2 === 0.0){ vec3.set(v2, nearestPoint); nearestPoint[3] = 0.0; return 2; } try{ MxeGeom.useTemporary(); // It makes it to the vertex near v1 and v2 var tempV = MxeGeom.vec3.getTemporary(); var tempd; if (d0 < d1){ if (d1 < d2){ // d2 is max vec3.set(v2, tempV); vec3.set(v0, v2); vec3.set(tempV, v0); tempd = d2, d2 = d0, d0 = tempd; } else { // d1 is max vec3.set(v1, tempV); vec3.set(v0, v1); vec3.set(tempV, v0); tempd = d1, d1 = d0, d0 = tempd; } } else if (d0 < d2){ // d2 is max vec3.set(v2, tempV); vec3.set(v0, v2); vec3.set(tempV, v0); tempd = d2, d2 = d0, d0 = tempd; } var v1v2vec = MxeGeom.vec3.getTemporary(); vec3.subtract(v2, v1, v1v2vec); var v1spvec = MxeGeom.vec3.getTemporary(); vec3.subtract(pos, v1, v1spvec); var dotP1 = vec3.dot(v1v2vec, v1spvec); if (dotP1 < 0){ // It is a point near v1. var v1v0vec = MxeGeom.vec3.getTemporary(); vec3.subtract(v0, v1, v1v0vec); dotP1 = vec3.dot(v1v0vec, v1spvec); if (dotP1 < 0){ vec3.set(v1, nearestPoint); // It is a point nearest v1. nearestPoint[3] = d1; return 2; } // A straight line of the starting point, v0, and v1 intersections var mag = vec3.dot(v1v0vec, v1v0vec); //square length if (mag === 0.0){ nearestPoint[3] = MxeGeom.def.MAX_FLOAT; //MXMAXFLOAT return -1; } tempd = dotP1/mag; vec3.add(vec3.scale(v1v0vec, tempd, nearestPoint), v1); nearestPoint[3] = d1 - dotP1*tempd; return 1; // in line } var v2spvec = MxeGeom.vec3.getTemporary(); vec3.subtract(pos, v2, v2spvec); var dotP2 = - vec3.dot(v1v2vec, v2spvec); if (dotP2 < 0.0){ // It is a point near v2. var v2v0vec = MxeGeom.vec3.getTemporary(); vec3.subtract(v0, v2, v2v0vec); dotP2 = vec3.dot(v2v0vec, v2spvec); if (dotP2 < 0.0){ vec3.set(v2, nearestPoint); nearestPoint[3] = d2; return 2; } // A straight line of the starting point, v0, and v2 intersections var mag = vec3.dot(v2v0vec, v2v0vec); //square length if (mag === 0.0){ nearestPoint[3] = MxeGeom.def.MAX_FLOAT; //MXMAXFLOAT return -1; } tempd = dotP2/mag; vec3.add(vec3.scale(v2v0vec, tempd, nearestPoint), v2); nearestPoint[3] = d2 - dotP2*tempd; return 1; // in line } // A straight line of the starting point, v1, and v2 intersections var mag = vec3.dot(v1v2vec, v1v2vec); //square length if (mag === 0.0){ nearestPoint[3] = MxeGeom.def.MAX_FLOAT; //MXMAXFLOAT return -1; } tempd = dotP1/mag; vec3.add(vec3.scale(v1v2vec, tempd, tempV), v1); if (vec3.dot(vec3.subtract(v0, tempV, MxeGeom.vec3.getTemporary()), vec3.subtract(pos, tempV, MxeGeom.vec3.getTemporary())) < 0.0){ // In this case, it exists on the straight line of v1 and v2. vec3.set(tempV, nearestPoint); nearestPoint[3] = d1 - dotP1*tempd; return 1; // in line } // In this case, it exists from the starting point under the perpendicular. var norm = MxeGeom.vec3.getTemporary(); vec3.normalize(vec3.cross(v1v2vec, vec3.subtract(v0, v1, norm), norm)); var minD = vec3.dot(norm, pos) - vec3.dot(norm, v0); vec3.subtract(pos, vec3.scale(norm, minD, nearestPoint), nearestPoint); nearestPoint[3] = minD * minD; return 0; } finally { MxeGeom.releaseTemporary(); } }; var MxeEvent = function() { this.initialize.apply(this, arguments); }; MxeEvent.prototype.initialize = function(e) { this.type = null; this.orgEvent = e; this.userObj = null; }; var MxeUtil = function() { this.logLevel = 1; }; MxeUtil.detectSmartPhone = function (){ //MxeUtil.log("UA="+navigator.userAgent); if (navigator.userAgent.indexOf('iPhone') > 0 || navigator.userAgent.indexOf('iPod') > 0 || navigator.userAgent.indexOf('iPad') > 0 || navigator.userAgent.indexOf('Android') > 0 || navigator.userAgent.indexOf('Tizen') > 0) { return true; } return false; }; MxeUtil.log = function(msg, level){ if(! level) level = 1; if(this.logLevel < level) return; console.log(msg); }; var MxeException = function() { this.initialize.apply(this, arguments); }; MxeException.prototype.initialize = function(name, message) { if(! name) this.name = "unknown"; else this.name = name; this.message = message; }; MxeException.prototype.toString = function() { return "MxeException : " + this.name + " : " + this.message; }; var Mxe2DContextTooSmallException = function(){ this.initialize.apply(this, arguments); }; Mxe2DContextTooSmallException.prototype = Object.create(MxeException.prototype); Mxe2DContextTooSmallException.prototype.constructor = Mxe2DContextTooSmallException; Mxe2DContextTooSmallException.prototype.name = "2dcontexttoosmall"; Mxe2DContextTooSmallException.prototype.initialize = function(message, w, h) { this.message = message; this.requestWidth = w; this.requestHeight = h; }; var MxeTouchIDNormalizer = function(){ this.initialize.apply(this, arguments); }; MxeTouchIDNormalizer.prototype.initialize = function(player) { var idTable = {}; var usedTable = new Int8Array([0,0,0,0,0,0,0,0,]); var self = this; this.onTouchStart = function(e) { for(var i=0; i<e.changedTouches.length; i++){ var id = e.changedTouches[i].identifier; if(idTable[id] !== undefined) continue; //id already exists var regID=0; for(; regID<usedTable.length; regID++){ if(usedTable[regID] === 0) break; } if(regID >= usedTable.length){ var newUsedTable = new Int8Array(regID); newUsedTable.set(usedTable); //for(var j=0; j<usedTable.length; j++) newUsedTable[j] = usedTable[j]; usedTable = newUsedTable; //throw new MxeException("touchoverflow", "Touch overflow."); //return; } usedTable[regID] = 1; idTable[id] = regID; } }; this.onTouchEnd = function(e) { for(var i=0; i<e.changedTouches.length; i++){ var id = e.changedTouches[i].identifier; var regID = idTable[id]; if(regID !== undefined){ usedTable[regID] = 0; delete idTable[id]; } } }; this.normalize = function(id) { if(idTable[id] === undefined) return 0; return idTable[id]; }; };
import React from "react"; import "../ad_inventory/datecard.css" function DateCard() { var date = new Date(); var today = date.getDate() + " - " + (date.getMonth() + 1) + " - " + date.getFullYear(); const newTime = new Date().toLocaleTimeString(); return ( <div className="cardFloat"> <div className="card"> <h1>{today}</h1> <h3>{newTime}</h3> </div> </div> ); } export default DateCard
import { createStackNavigator } from 'react-navigation-stack'; import { createAppContainer } from 'react-navigation'; import React from 'react'; import { TouchableOpacity } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import GetStarted from '../screens/getStarted'; import PhoneInput from '../screens/phoneInput'; import TextVerification from '../screens/textVerification'; import NameInput from '../screens/nameInput'; import { Global } from '../styles/Global'; const screens = { GetStarted: { screen: GetStarted, navigationOptions: () => { return { headerShown: false, }; } }, PhoneInput: { screen: PhoneInput, navigationOptions: ({ navigation }) => { return { headerShown: true, title: 'Phone Number', headerStyle: Global.headerStyle, headerTitleStyle: Global.headerTitleStyle, headerLeft: () => ( <TouchableOpacity onPress={() => navigation.navigate('GetStarted')} style={{paddingLeft: 8}}> <Icon name='chevron-left' color='#FFF' size={32} /> </TouchableOpacity> ), } } }, TextVerification: { screen: TextVerification, navigationOptions: ({ navigation }) => { return { headerShown: true, title: 'Verification', headerStyle: Global.headerStyle, headerTitleStyle: Global.headerTitleStyle, headerLeft: () => ( <TouchableOpacity onPress={() => navigation.navigate('PhoneInput')} style={{paddingLeft: 8}}> <Icon name='chevron-left' color='#FFF' size={32} /> </TouchableOpacity> ), } } }, NameInput: { screen: NameInput, navigationOptions: ({ navigation }) => { return { headerShown: true, title: 'Name Input', headerStyle: Global.headerStyle, headerTitleStyle: Global.headerTitleStyle, gestureEnabled: false, headerLeft: () => ( null ) } } } }; const SignInStack = createStackNavigator(screens); export default createAppContainer(SignInStack);
import {BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import './App.css'; import Home from './Components/Home/Home'; import Login from './Components/Login/Login'; import Signup from "./Components/Signup/Signup"; import Navbar from './Components/NavBar/Navbar'; import Survey from "./Components/Survey/Survey"; import PageNotFount from './Components/PageNotFount'; import PrivateRoute from "./Components/PrivateRoute"; function App() { return ( <div className="App"> <Router> <Navbar /> <Switch> <PrivateRoute exact path="/"> <Home /> </PrivateRoute> <PrivateRoute exact path="/survey"> <Survey /> </PrivateRoute> <Route exact path="/signup"> <Signup /> </Route> <Route exact path="/login"> <Login /> </Route> <Route component={PageNotFount} /> </Switch> </Router> </div> ); } export default App;
// return date today const today = `${new Date().getFullYear()}-${new Date().getMonth()+1}-${new Date().getDate()}`; module.exports = { today }
const mongoose = require("mongoose"); const schema = new mongoose.Schema({ id: Number, title: String, content: String, author: String, datePosted: Date, image: String, }); module.exports = mongoose.model("Articles", schema, "Articles");
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const User = require("../User"); const DenneSchema = new Schema({ createdDate: { type: Date, default: Date.now, }, hotel: { type: mongoose.Schema.ObjectId, ref: "Hotel", required: true, }, isBooking: { type: Boolean, default: true, } }); // Pre Save Method DenneSchema.pre("save", async function (next) { if (!this.isModified("user")) { next(); } else { try { let userId = this.user; const user = await User.findById(userId); user.dennes.push(this.id); await user.save(); next(); } catch (err) { next(err); } } }); DenneSchema.post("remove", async function () { const user = await User.findById(this.user); user.dennes.splice(user.dennes.indexOf(this._id), 1); await user.save(); }); module.exports = mongoose.model("Denne", DenneSchema);
import React, { useState } from "react"; // Contains checkbox logic const Checkbox = ({ categories, handleFilters }) => { const [checked, setCheked] = useState([]); // Grab category id and put them // in an array so we can send it // to the backend to get all the // products based on category // accepts category id const handleToggle = (c) => () => { // Return the first index or -1 const currentCategoryId = checked.indexOf(c); // Grab a copy of the state const newCheckedCategoryId = [...checked]; // If currently checked was not already in checked state > push if (currentCategoryId === -1) { newCheckedCategoryId.push(c); // else pull, indicating the uncheck } else { newCheckedCategoryId.splice(currentCategoryId, 1); } console.log(newCheckedCategoryId); // Use the new updated checked category setCheked(newCheckedCategoryId); // Send the updated checked category to // the parent for processing via // handleFilters function handleFilters(newCheckedCategoryId); }; // Loop through categoires and // display them in a list with // a label and an input return categories.map((c, i) => ( <li key={i} className="list-unstyled"> <input // pass in category id onChange={handleToggle(c._id)} // c._id is used for displaying checked items // display tickmark only if the id // is present in the array value={checked.indexOf(c._id !== -1)} type="checkbox" className="form-check-input" /> <label className="form-check-label" style={{color:"white"}}>{c.name}</label> </li> )); }; export default Checkbox;
export function Minus(props) { return ( <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" {...props} > <defs> <style>{'.cls-1{fill-rule:evenodd}'}</style> </defs> <path className="cls-1" d="M.5 8.5v-1h15v1z" /> </svg> ); }
import React from "react"; import styled from "styled-components"; import SubscribeForm from "./SubscribeForm"; const HomeStyledHero = styled.div` height: calc(100vh - 70px); width: 100%; background-color: gray; background-image: url("https://live.staticflickr.com/65535/51162644248_86d25a4d61_b.jpg"); background-repeat: no-repeat; background-position: top; background-size: cover; display: flex; align-items: center; justify-content: flex-end; margin-bottom: 80px; @media (max-width: 750px) { margin-bottom: 0px; } `; const HeroForm = styled.div` height: 70%; max-height: 500px; width: 30%; margin-right: 200px; bottom: 100px; min-height: 350px; @media (max-width: 1250px) { width: 40%; } @media (max-width: 950px) { width: 50%; } @media (max-width: 750px) { width: 100%; height: 65%; margin-right: 0px; } @media (max-width: 450px) { width: 100%; height: 60%; margin-right: 0px; } `; const HomeHero = () => { return ( <HomeStyledHero> <HeroForm> <SubscribeForm /> </HeroForm> </HomeStyledHero> ); }; export default HomeHero;
import React from 'react' function SelectType (props) { let {allTypes, gameStatus, handleSelectType} = props return ( <div className="select-types"> <h4>请选择类型:</h4> { allTypes.map(matrixType => ( <button key={matrixType} onClick={() => handleSelectType(matrixType)} disabled={gameStatus === 'begin'} >{matrixType}X{matrixType}</button> )) } </div> ) } export default SelectType
import { Meteor } from 'meteor/meteor'; Meteor.methods({ createTask(title, desc, assigneeEmails) { check(desc, String); check(assigneeEmails, Array); check(title, String); try { Tasks.insert({ user_id: this.userId, title: title, description: desc, assignee_emails:assigneeEmails, created_at: new Date() }); // console.log(title, desc, assigneeEmails); } catch (err) { console.error(err.reason); return err; } } });
import React from "react"; import { observer, useObservable } from "mobx-react-lite"; const ReactMobx = observer(() => { const store = useObservable({ count: 1, addOne() { store.count++; }, subOne() { store.count--; } }); function addOneHandle() { store.addOne(); } function subOneHanlde() { store.subOne(); } return ( <div> <h1>Count: {store.count}</h1> <button onClick={addOneHandle}>Add One</button> <button onClick={subOneHanlde}>Sub One</button> </div> ); }); export default ReactMobx;
import React from 'react'; import ReactSelect from './ReactSelect'; class ActivityRow extends React.Component { constructor(props) { super(props); this.state = { activityList: [ { name: 'BREAK DOWN TIME', value: '1' }, { name: 'CHANGE OVER', value: '2' }, { name: 'COOLING TANK CLEANING', value: '3' }, { name: 'DOWN TIME', value: '4' }, { name: 'PRODUCTION', value: '5' }, { name: 'PROFILE CORRECTION', value: '6' }, { name: 'PROFILE PLATE CLEANING', value: '7' }, { name: 'SCREW/ADOPTER CLEANING', value: '8' }, { name: 'SET UP', value: '9' }, { name: 'SIZER FAIL', value: '10' }, { name: 'TRAINING', value: '11' } ] }; } handleChange = (e) => { this.props.onInputChange(e.target.name, e.target.value, this.props.rowIndex); // console.log(e.target.name); } render() { return ( <tr> <td><input name="from1" type="time" onChange={this.handleChange} /></td> <td><input name="to1" type="time" onChange={this.handleChange} /></td> <td>{<ReactSelect name="select1" options={this.state.activityList} value="9" />}</td> <td><input className="Uppercase" name="varAnly" type="text" onChange={this.handleChange} /></td> <td><input className="Uppercase" name="actTaken" type="text" onChange={this.handleChange} /></td> <td><input type="button" onClick={this.props.onClickPlus} value="Add" /> </td> <td><input type="button" onClick={this.props.onClickMinus} value="Remove" /> </td> </tr> ); } } class ActivityTable extends React.Component { constructor(props) { super(props); this.state = { activityNum: 1, activityRow: [<ActivityRow rowIndex={0} onInputChange={this.handleInputChange} onClickPlus={this.handleAddNewActClick} key={1} />], data: [{ from1: "", to1: "", select1: "", varAnly: "", actTaken: "" }] }; } handleInputChange = (name, value1, rwIndex) => { this.setState(prevState => { let newData = prevState.data newData[rwIndex][name] = value1; return { data: newData }; }); } componentDidUpdate = () => { console.log(this.state.data); } handleRemoveNewAct = () => { let removeAct = this.state.activityRow; removeAct.pop(); this.setState({ activityNum: this.state.activityNum - 1, activityRow: removeAct }); console.log("removed"); } handleAddNewActClick = () => { let newAct = this.state.activityRow; let newData = this.state.data; newAct.push(<ActivityRow rowIndex={newAct.length} onInputChange={this.handleInputChange} onClickPlus={this.handleAddNewActClick} onClickMinus={this.handleRemoveNewAct} key={this.state.activityNum + 1} />); newData.push({ from1: "", to1: "", select1: "", varAnly: "", actTaken: "" }); this.setState({ activityNum: this.state.activityNum + 1, activityRow: newAct, data: newData }); console.log("added"); } render() { return ( <div> <form> <table> <thead> <tr> <th>From</th> <th>To</th> <th>Activity</th> <th>Variance Analysis</th> <th>Action Taken</th> </tr> </thead> <tbody> {this.state.activityRow} <tr> <td> <input type="button" value="Submit" /> </td> </tr> </tbody> </table> </form> </div> ); } } class Activity extends React.Component { render() { return ( <div>{< ActivityTable />}</div> ); } } export default Activity;
WMS.module("Header", function(Header, WMS, Backbone, Marionette, $, _) { var API = { listHeaders: function() { Header.List.Controller.listHeaders(); } }; WMS.commands.setHandler('set:active:header', function(name) { Header.List.Controller.setActiveHeader(name); }); Header.on('start', function() { API.listHeaders(); WMS.getSession().on('change:authenticated', function() { API.listHeaders(); }); }); });
import React from "react"; import { shallow, mount } from "enzyme"; import Feedback from "./feedback"; describe("Renders feedback", () => { it("renders feedback shallowly", () => { shallow(<Feedback />); }); });
import React from 'react'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import StoryRouter from 'storybook-react-router'; import { DocsPage, DocsContainer } from '@storybook/addon-docs/blocks'; import AppHeader from './index'; import storeFs from '../../reducers'; const store = createStore(storeFs); const stories = storiesOf('AppHeader', module).addParameters({ title: 'AppHeader', component: AppHeader, docs: { container: DocsContainer, page: DocsPage, }, }); stories.addDecorator(StoryRouter()).addParameters({ foo: 1 }).add('顯示Tab', () => ( <Provider store={store}> <AppHeader currentActiveTab="html" handleTabClick={action('clicked')} isTabVisible isShareBtnVisible /> </Provider> )); stories.addDecorator(StoryRouter()).add('不顯示Tab', () => ( <Provider store={store}> <AppHeader currentActiveTab="html" handleTabClick={action('clicked')} isTabVisible={false} isShareBtnVisible /> </Provider> )); stories.addDecorator(StoryRouter()).add('不顯示分享按鈕', () => ( <Provider store={store}> <AppHeader currentActiveTab="html" handleTabClick={action('clicked')} isTabVisible={false} isShareBtnVisible={false} /> </Provider> ));