<commit_before>import Protocol from './protocol';
import Core from '../core';

function call_property(item, property){
  let prop = null;

  if(typeof item === "number" || typeof item === "symbol" || typeof item === "boolean" || typeof item === "string"){
    if(item[property] !== undefined){
      prop = property;
    }else if(item[Symbol.for(property)] !== undefined){
      prop = Symbol.for(property);
    }
  } else {
    if(property in item){
      prop = property;
    }else if(Symbol.for(property) in item){
      prop = Symbol.for(property);
    }
  }

  if(prop === null){
    throw new Error(`Property ${ property } not found in ${ item }`);
  }

  if(item[prop] instanceof Function){
    return item[prop]();
  }else{
    return item[prop];
  }
}

function is_generator(fun){
  return fun.constructor.name === "GeneratorFunction";
}

function* run(fun, args, context = null){
  if(fun.constructor.name === "GeneratorFunction"){
    return yield* fun.apply(context, args);
  }

  return yield fun.apply(context, args);
}

function apply(...args){
  if(args.length === 2){
    args[0].apply(null, args.slice(1));
  }else{
    args[0][args[1]].apply(null, args.slice(2));
  }
}

function contains(left, right){
  for(let x of right){
    if(Core.Patterns.match_or_default(left, x) != null){
      return true;
    }
  }

  return false;
}

function get_global(){
  if(typeof(self) !== "undefined"){
    return self;
  }else if(typeof(window) !== "undefined"){
    return window;
  }else if(typeof(global) !== "undefined"){
    return global;
  }

  throw new Error("No global state found");
}

function defstruct(defaults){
  return class {
    constructor(update = {}){
      let the_values = Object.assign(defaults, update);
      Object.assign(this, the_values);
    }

    static create(updates = {}){
      let x = new this(updates);
      return Object.freeze(x);
    }
  };
}

function defexception(defaults){
  return class extends Error {
    constructor(update = {}){
      let message = update.message || "";
      super(message);

      let the_values = Object.assign(defaults, update);
      Object.assign(this, the_values);

      this.name = this.constructor.name;
      this.message = message;
      this[Symbol.for("__exception__")] = true;
      Error.captureStackTrace(this, this.constructor.name);
    }

    static create(updates = {}){
      let x = new this(updates);
      return Object.freeze(x);
    }
  };
}

function defprotocol(spec){
  return new Protocol(spec);
}

function defimpl(protocol, type, impl){
  protocol.implementation(type, impl);
}

function get_object_keys(obj){
    return Object.keys(obj).concat(Object.getOwnPropertySymbols(obj));
}

function is_valid_character(codepoint){
  try{
    return String.fromCodePoint(codepoint) != null;
  }catch(e){
    return false;
  }
}

//https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_2_%E2%80%93_rewrite_the_DOMs_atob()_and_btoa()_using_JavaScript's_TypedArrays_and_UTF-8
function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}

function delete_property_from_map(map, property){
    let new_map = Object.assign(Object.create(map.constructor.prototype), map);
    delete new_map[property];

  return Object.freeze(new_map);
}

function class_to_obj(map){
    let new_map = Object.assign({}, map);
  return Object.freeze(new_map);
}

function add_property_to_map(map, property, value){
  let new_map = Object.assign({}, map);
  new_map[property] = value;
  return Object.freeze(new_map);
}

function update_map(map, property, value){
    if(property in get_object_keys(map)){
        return add_property_to_map(map, property, value);
    }

    throw "map does not have key";
}

function bnot(expr){
  return ~expr;
}

function band(left, right){
  return left & right;
}

function bor(left, right){
  return left | right;
}

function bsl(left, right){
  return left << right;
}

function bsr(left, right){
  return left >> right;
}

function bxor(left, right){
  return left ^ right;
}

function zip(list_of_lists){
  if(list_of_lists.length === 0){
    return Object.freeze([]);
  }

  let new_value = [];
  let smallest_length = list_of_lists[0];

  for(let x of list_of_lists){
    if(x.length < smallest_length){
      smallest_length = x.length;
    }
  }

  for(let i = 0; i < smallest_length; i++){
    let current_value = [];
    for(let j = 0; j < list_of_lists.length; j++){
      current_value.push(list_of_lists[j][i]);
    }

    new_value.push(new Core.Tuple(...current_value));
  }

  return Object.freeze(new_value);
}

function can_decode64(data) {
  try{
    atob(data);
    return true;
  }catch(e){
    return false;
  }
}

function remove_from_list(list, element){
    let found = false;

    return list.filter((elem) => {
        if(!found && elem === element){
            found = true;
            return false;
        }

        return true;
    });
}

function foldl(fun, acc, list){
    let acc1 = acc;

    for(const el of list){
        acc1 = fun(el, acc1);
    }

    return acc1;
}

function foldr(fun, acc, list){
    let acc1 = acc;

    for(let i = list.length - 1; i >= 0; i--){
        acc1 = fun(list[i], acc1);
    }

    return acc1;
}

function keyfind(key, n, tuplelist){

  for(let i = tuplelist.length - 1; i >= 0; i--){
    if(tuplelist[i].get(n) === key){
      return tuplelist[i];
    }
  }

  return false;
}

function keydelete(key, n, tuplelist){

    for(let i = tuplelist.length - 1; i >= 0; i--){
        if(tuplelist[i].get(n) === key){
            return tuplelist.concat([]).splice(i, 1);
        }
    }

    return tuplelist;
}

function keystore(key, n, list, newtuple){
    for(let i = list.length - 1; i >= 0; i--){
        if(list[i].get(n) === key){
            return list.concat([]).splice(i, 1, newtuple);
        }
    }

  return list.concat([]).push(newtuple);
}

function keymember(key, n, list){
  for(let i = list.length - 1; i >= 0; i--){
    if(list[i].get(n) === key){
      return true;
    }
  }

  return false;
}

function keytake(key, n, list){
  if(!keymember(key, n, list)){
    return false;
  }

  let tuple = keyfind(key, n, list);

  return new Tuple(tuple.get(n), tuple, keydelete(key, n, list));
}

function keyreplace(key, n, list, newtuple){

  for(let i = tuplelist.length - 1; i >= 0; i--){
    if(tuplelist[i].get(n) === key){
      return tuplelist.concat([]).splice(i, 1, newtuple);
    }
  }

  return tuplelist;
}

function reverse(list){
    return list.concat([]).reverse();
}

function maps_find(key, map){
    if(key in get_object_keys(map)){
        return new Core.Tuple(Symbol.for("ok"), map[key]);
    }else{
        return Symbol.for("error");
    }
}

function flatten(list, tail = []) {
  let new_list = [];

  for(let e of list){
    if(Array.isArray(e)){
      new_list = new_list.concat(flatten(e));
    }else{
      new_list.push(e);
    }
  }

  return Object.freeze(new_list.concat(tail));
}

function duplicate(n, elem){
  let list = [];

  for(let i = 0; i < n; i++){
    list.push(elem);
  }

  return Object.freeze(list);
}

function mapfoldl(fun, acc, list){
  let newlist = [];

  for(let x of list){
    let tup = fun(x, acc);
    newlist.push(tup.get(0));
    acc = tup.get(1);
  }

  return new Core.Tuple(Object.freeze(newlist), acc);
}

function filtermap(fun, list){
  let newlist = [];

  for(x of list){
    let result = fun(x);

    if(result === true){
      newlist.push(x);
    }else if(result instanceof Core.Tuple){
      newlist.push(result.get(1));
    }
  }

  return Object.freeze(newlist);
}

function maps_fold(fun, acc, map){
  let acc1 = acc;

  for(let k of get_object_keys(map)){
    acc1 = fun(k, map[k], acc1);
  }

  return acc1;
}

function maps_from_list(list){
  let m = {};

  for(x of list){
    m[x.get(0)] = x.get(1);
  }

  return Object.freeze(m);
}

export default {
  call_property,
  run,
  apply,
  contains,
  get_global,
  defstruct,
  defexception,
  defprotocol,
  defimpl,
  get_object_keys,
  is_valid_character,
  b64EncodeUnicode,
  delete_property_from_map,
  add_property_to_map,
  class_to_obj,
  can_decode64,
  bnot,
  band,
  bor,
  bsl,
  bsr,
  bxor,
  zip,
  foldl,
  foldr,
  remove_from_list,
  keydelete,
  keystore,
  keyfind,
  keytake,
  keyreplace,
  reverse,
  update_map,
  maps_find,
  flatten,
  duplicate,
  mapfoldl,
  filtermap,
  maps_fold,
  is_generator
};
<commit_msg>Removed is_generator function from javascript functions<commit_after>import Protocol from './protocol';
import Core from '../core';

function call_property(item, property){
  let prop = null;

  if(typeof item === "number" || typeof item === "symbol" || typeof item === "boolean" || typeof item === "string"){
    if(item[property] !== undefined){
      prop = property;
    }else if(item[Symbol.for(property)] !== undefined){
      prop = Symbol.for(property);
    }
  } else {
    if(property in item){
      prop = property;
    }else if(Symbol.for(property) in item){
      prop = Symbol.for(property);
    }
  }

  if(prop === null){
    throw new Error(`Property ${ property } not found in ${ item }`);
  }

  if(item[prop] instanceof Function){
    return item[prop]();
  }else{
    return item[prop];
  }
}

function apply(...args){
  if(args.length === 2){
    args[0].apply(null, args.slice(1));
  }else{
    args[0][args[1]].apply(null, args.slice(2));
  }
}

function contains(left, right){
  for(let x of right){
    if(Core.Patterns.match_or_default(left, x) != null){
      return true;
    }
  }

  return false;
}

function get_global(){
  if(typeof(self) !== "undefined"){
    return self;
  }else if(typeof(window) !== "undefined"){
    return window;
  }else if(typeof(global) !== "undefined"){
    return global;
  }

  throw new Error("No global state found");
}

function defstruct(defaults){
  return class {
    constructor(update = {}){
      let the_values = Object.assign(defaults, update);
      Object.assign(this, the_values);
    }

    static create(updates = {}){
      let x = new this(updates);
      return Object.freeze(x);
    }
  };
}

function defexception(defaults){
  return class extends Error {
    constructor(update = {}){
      let message = update.message || "";
      super(message);

      let the_values = Object.assign(defaults, update);
      Object.assign(this, the_values);

      this.name = this.constructor.name;
      this.message = message;
      this[Symbol.for("__exception__")] = true;
      Error.captureStackTrace(this, this.constructor.name);
    }

    static create(updates = {}){
      let x = new this(updates);
      return Object.freeze(x);
    }
  };
}

function defprotocol(spec){
  return new Protocol(spec);
}

function defimpl(protocol, type, impl){
  protocol.implementation(type, impl);
}

function get_object_keys(obj){
    return Object.keys(obj).concat(Object.getOwnPropertySymbols(obj));
}

function is_valid_character(codepoint){
  try{
    return String.fromCodePoint(codepoint) != null;
  }catch(e){
    return false;
  }
}

//https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_2_%E2%80%93_rewrite_the_DOMs_atob()_and_btoa()_using_JavaScript's_TypedArrays_and_UTF-8
function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}

function delete_property_from_map(map, property){
    let new_map = Object.assign(Object.create(map.constructor.prototype), map);
    delete new_map[property];

  return Object.freeze(new_map);
}

function class_to_obj(map){
    let new_map = Object.assign({}, map);
  return Object.freeze(new_map);
}

function add_property_to_map(map, property, value){
  let new_map = Object.assign({}, map);
  new_map[property] = value;
  return Object.freeze(new_map);
}

function update_map(map, property, value){
    if(property in get_object_keys(map)){
        return add_property_to_map(map, property, value);
    }

    throw "map does not have key";
}

function bnot(expr){
  return ~expr;
}

function band(left, right){
  return left & right;
}

function bor(left, right){
  return left | right;
}

function bsl(left, right){
  return left << right;
}

function bsr(left, right){
  return left >> right;
}

function bxor(left, right){
  return left ^ right;
}

function zip(list_of_lists){
  if(list_of_lists.length === 0){
    return Object.freeze([]);
  }

  let new_value = [];
  let smallest_length = list_of_lists[0];

  for(let x of list_of_lists){
    if(x.length < smallest_length){
      smallest_length = x.length;
    }
  }

  for(let i = 0; i < smallest_length; i++){
    let current_value = [];
    for(let j = 0; j < list_of_lists.length; j++){
      current_value.push(list_of_lists[j][i]);
    }

    new_value.push(new Core.Tuple(...current_value));
  }

  return Object.freeze(new_value);
}

function can_decode64(data) {
  try{
    atob(data);
    return true;
  }catch(e){
    return false;
  }
}

function remove_from_list(list, element){
    let found = false;

    return list.filter((elem) => {
        if(!found && elem === element){
            found = true;
            return false;
        }

        return true;
    });
}

function foldl(fun, acc, list){
    let acc1 = acc;

    for(const el of list){
        acc1 = fun(el, acc1);
    }

    return acc1;
}

function foldr(fun, acc, list){
    let acc1 = acc;

    for(let i = list.length - 1; i >= 0; i--){
        acc1 = fun(list[i], acc1);
    }

    return acc1;
}

function keyfind(key, n, tuplelist){

  for(let i = tuplelist.length - 1; i >= 0; i--){
    if(tuplelist[i].get(n) === key){
      return tuplelist[i];
    }
  }

  return false;
}

function keydelete(key, n, tuplelist){

    for(let i = tuplelist.length - 1; i >= 0; i--){
        if(tuplelist[i].get(n) === key){
            return tuplelist.concat([]).splice(i, 1);
        }
    }

    return tuplelist;
}

function keystore(key, n, list, newtuple){
    for(let i = list.length - 1; i >= 0; i--){
        if(list[i].get(n) === key){
            return list.concat([]).splice(i, 1, newtuple);
        }
    }

  return list.concat([]).push(newtuple);
}

function keymember(key, n, list){
  for(let i = list.length - 1; i >= 0; i--){
    if(list[i].get(n) === key){
      return true;
    }
  }

  return false;
}

function keytake(key, n, list){
  if(!keymember(key, n, list)){
    return false;
  }

  let tuple = keyfind(key, n, list);

  return new Tuple(tuple.get(n), tuple, keydelete(key, n, list));
}

function keyreplace(key, n, list, newtuple){

  for(let i = tuplelist.length - 1; i >= 0; i--){
    if(tuplelist[i].get(n) === key){
      return tuplelist.concat([]).splice(i, 1, newtuple);
    }
  }

  return tuplelist;
}

function reverse(list){
    return list.concat([]).reverse();
}

function maps_find(key, map){
    if(key in get_object_keys(map)){
        return new Core.Tuple(Symbol.for("ok"), map[key]);
    }else{
        return Symbol.for("error");
    }
}

function flatten(list, tail = []) {
  let new_list = [];

  for(let e of list){
    if(Array.isArray(e)){
      new_list = new_list.concat(flatten(e));
    }else{
      new_list.push(e);
    }
  }

  return Object.freeze(new_list.concat(tail));
}

function duplicate(n, elem){
  let list = [];

  for(let i = 0; i < n; i++){
    list.push(elem);
  }

  return Object.freeze(list);
}

function mapfoldl(fun, acc, list){
  let newlist = [];

  for(let x of list){
    let tup = fun(x, acc);
    newlist.push(tup.get(0));
    acc = tup.get(1);
  }

  return new Core.Tuple(Object.freeze(newlist), acc);
}

function filtermap(fun, list){
  let newlist = [];

  for(x of list){
    let result = fun(x);

    if(result === true){
      newlist.push(x);
    }else if(result instanceof Core.Tuple){
      newlist.push(result.get(1));
    }
  }

  return Object.freeze(newlist);
}

function maps_fold(fun, acc, map){
  let acc1 = acc;

  for(let k of get_object_keys(map)){
    acc1 = fun(k, map[k], acc1);
  }

  return acc1;
}

function maps_from_list(list){
  let m = {};

  for(x of list){
    m[x.get(0)] = x.get(1);
  }

  return Object.freeze(m);
}

export default {
  call_property,
  apply,
  contains,
  get_global,
  defstruct,
  defexception,
  defprotocol,
  defimpl,
  get_object_keys,
  is_valid_character,
  b64EncodeUnicode,
  delete_property_from_map,
  add_property_to_map,
  class_to_obj,
  can_decode64,
  bnot,
  band,
  bor,
  bsl,
  bsr,
  bxor,
  zip,
  foldl,
  foldr,
  remove_from_list,
  keydelete,
  keystore,
  keyfind,
  keytake,
  keyreplace,
  reverse,
  update_map,
  maps_find,
  flatten,
  duplicate,
  mapfoldl,
  filtermap,
  maps_fold
};
<|endoftext|>


<commit_before>/**
 * small demo node server that implements the EMU-webApp-websocket-protocol
 *
 * NOTE: on save no actions are performed (functions are just stubs)
 *
 * to run:
 *  > node nodeEmuProtocolWsServer.js
 *
 * author: Raphael Winkelmann
 */

'use strict';

// load deps
var fs = require('fs');
var os = require('os');
var filewalker = require('filewalker');

// allow to set vars from command line
if (process.argv.length === 2) {

  var portNr = 17890;
  var pathToDbRoot = '/Users/raphaelwinkelmann/Desktop/gersC/';
  var configName = 'gersC_DBconfig.json';
  // var pathToDbRoot = '../app/testData/newFormat/ae/';
  // var configName = 'ae_DBconfig.json';

} else if (process.argv.length === 3) {

  var portNr = process.argv[2];
  var pathToDbRoot = '../app/testData/newFormat/ae/';
  var configName = 'ae_DBconfig.json';

} else if (process.argv.length === 5) {

  var portNr = process.argv[2];
  var pathToDbRoot = process.argv[3];;
  var configName = process.argv[4];;

}

var dbConfig = {};
var ssffFilesMap = {};

// demo of user management
var doUserManagement = 'NO';
var userName = 'user1';
var userPwd = '1234'; // high security plain text password! This is for demo purposes only! Please store your passwords properly...

var WebSocketServer = require('ws').Server,
  wss = new WebSocketServer({
    port: portNr
  });

console.log('websocketserver running @: ws://' + os.hostname() + ':' + portNr);

wss.on('connection', function (ws) {

  console.log('INFO: client connected');

  ws.on('message', function (message) {
    // console.log('received: %s', message);
    var mJSO = JSON.parse(message);

    switch (mJSO.type) {
      // GETPROTOCOL method
    case 'GETPROTOCOL':
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'data': {
          'protocol': 'EMU-webApp-websocket-protocol',
          'version': '0.0.2'
        },
        'status': {
          'type': 'SUCCESS',
          'message': ''
        }
      }), undefined, 0);
      break;

      // GETDOUSERMANAGEMENT method
    case 'GETDOUSERMANAGEMENT':
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'data': doUserManagement,
        'status': {
          'type': 'SUCCESS',
          'message': ''
        }
      }), undefined, 0);
      break;

      // LOGONUSER method
    case 'LOGONUSER':

      if (mJSO.userName !== userName) {
        // handle wrong user name
        ws.send(JSON.stringify({
          'callbackID': mJSO.callbackID,
          'data': 'BADUSERNAME',
          'status': {
            'type': 'SUCCESS',
            'message': ''
          }
        }), undefined, 0);
      } else if (mJSO.pwd !== userPwd) {
        // handle wrong password
        ws.send(JSON.stringify({
          'callbackID': mJSO.callbackID,
          'data': 'BADPASSWORD',
          'status': {
            'type': 'SUCCESS',
            'message': ''
          }
        }), undefined, 0);
      } else {
        ws.send(JSON.stringify({
          'callbackID': mJSO.callbackID,
          'data': 'LOGGEDON',
          'status': {
            'type': 'SUCCESS',
            'message': ''
          }
        }), undefined, 0);
      }

      break;

      // GETGLOBALDBCONFIG method
    case 'GETGLOBALDBCONFIG':
      console.log('############## GETGLOBALDBCONFIG ####################')
      fs.readFile(pathToDbRoot + configName, 'utf8', function (err, data) {
        if (err) {
          console.log('Error: ' + err);
          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'status': {
              'type': 'ERROR',
              'message': err
            }
          }), undefined, 0);
          return;
        } else {
          dbConfig = JSON.parse(data);

          // figure out which SSFF files should be sent with each bundle
          // (could further reduce the files being sent by looking at the perspectives)
          for (var i = 0; i < dbConfig.ssffTrackDefinitions.length; i++) {
            if (ssffFilesMap[dbConfig.ssffTrackDefinitions[i].fileExtension] !== undefined) {
              ssffFilesMap[dbConfig.ssffTrackDefinitions[i].fileExtension] += 1;
            } else {
              ssffFilesMap[dbConfig.ssffTrackDefinitions[i].fileExtension] = 1;
            }
          }
          console.log(ssffFilesMap);

          // curUttList = dbConfig;
          // curStrippedUttList = stripUttList(dbConfig);

          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'data': dbConfig,
            'status': {
              'type': 'SUCCESS',
              'message': ''
            }
          }), undefined, 0);
          // ws.send(labelData);
        }
      });
      break;

      // GETBUNDLELIST method
      // file walks through DB to get all the bundles
    case 'GETBUNDLELIST':
      var bundleList = [];
      filewalker(pathToDbRoot)
        .on('dir', function (p) {

          var patt = new RegExp('^.+_ses+/.+_bndl$');
          // var patt = new RegExp('^SES[^/]+/[^/]+$');

          if (patt.test(p)) {
            var arr = p.split('/');
            var nArr = arr[arr.length - 1].split('_');
            var sArr = arr[0].split('_');
            sArr.pop();
            nArr.pop();
            bundleList.push({
              'name': nArr.join('_'),
              'session': sArr.join('_')
            });
          }
        }).on('error', function (err) {
          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'status': {
              'type': 'ERROR',
              'message': 'Error creating bundleList! Request type was: ' + mJSO.type + ' Error is: ' + err
            }
          }), undefined, 0);
        }).on('done', function () {
          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'data': bundleList,
            'status': {
              'type': 'SUCCESS',
              'message': ''
            }
          }), undefined, 0);
        }).walk();
      break;

      // GETBUNDLE method
    case 'GETBUNDLE':

      var bundle = {};
      bundle.ssffFiles = [];
      filewalker(pathToDbRoot)
        .on('dir', function () {}).on('file', function (p) {
          // var pattMedia = new RegExp('^SES[^/]+/' + mJSO.name + '/[^/]+' + dbConfig.mediafileExtension + '$');
          var pattMedia = new RegExp('^.+_ses+/' + mJSO.name + '_bndl' + '/[^/]+' + dbConfig.mediafileExtension + '$');

          // var pattAnnot = new RegExp('^SES[^/]+/' + mJSO.name + '/[^/]+' + 'json' + '$');
          var pattAnnot = new RegExp('^.+_ses+/' + mJSO.name + '_bndl' + '/[^/]+' + 'json' + '$');

          // read media file
          if (pattMedia.test(p)) {
            console.log(p);
            bundle.mediaFile = {};
            bundle.mediaFile.encoding = 'BASE64';
            bundle.mediaFile.filePath = p;
          }
          // read annotation file
          if (pattAnnot.test(p)) {
            bundle.annotation = {};
            bundle.annotation.filePath = p;
          }
          // read ssffTrackDefinitions

          // for (var i = 0; i < dbConfig.ssffTrackDefinitions.length; i++) {
          //   // var pattTrack = new RegExp('^SES[^/]+/' + mJSO.name + '/[^/]+' + dbConfig.ssffTrackDefinitions[i].fileExtension + '$');
          //   var pattTrack = new RegExp('^.+_ses+/' + mJSO.name + '_bndl' + '/[^/]+' + dbConfig.ssffTrackDefinitions[i].fileExtension + '$');
          //   if (pattTrack.test(p)) {
          //     bundle.ssffFiles.push({
          //       ssffTrackName: dbConfig.ssffTrackDefinitions[i].name,
          //       encoding: 'BASE64',
          //       filePath: p
          //     });
          //   }
          // }

        }).on('error', function (err) {
          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'status': {
              'type': 'ERROR',
              'message': 'Error getting bundle! Request type was: ' + mJSO.type + ' Error is: ' + err
            }
          }), undefined, 0);
        }).on('done', function () {
          console.log(mJSO)
          bundle.mediaFile.data = fs.readFileSync(pathToDbRoot + bundle.mediaFile.filePath, 'base64');
          delete bundle.mediaFile.filePath;

          bundle.annotation = JSON.parse(fs.readFileSync(pathToDbRoot + bundle.annotation.filePath, 'utf8'));
          delete bundle.annotation.filePath;
          for (var key in ssffFilesMap) {
              bundle.ssffFiles.push({
                fileExtension: key,
                encoding: 'BASE64',
                data: fs.readFileSync(pathToDbRoot + mJSO.session + '_ses/' + mJSO.name + '_bndl/' + mJSO.name + '.' + key, 'base64')
              });
          //   bundle.ssffFiles[i].data = fs.readFileSync(pathToDbRoot + bundle.ssffFiles[i].filePath, 'base64');
          //   delete bundle.ssffFiles[i].filePath;
          }

          console.log('##########################');
          console.log('done');
          // fs.writeFileSync('/Users/raphaelwinkelmann/Desktop/bundle.json', JSON.stringify(bundle, undefined, 0));
          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'data': bundle,
            'status': {
              'type': 'SUCCESS',
              'message': ''
            }
          }), undefined, 0);

        }).walk();
      break;

      // SAVEBUNDLE method
    case 'SAVEBUNDLE':
      console.log('### Pretending to save bundle:');
      console.log('\tname:', mJSO.data.annotation.name);
      console.log('\tsession:', mJSO.data.session);
      // console.log(mJSO.data.annotation);
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'status': {
          'type': 'SUCCESS',
          'message': 'Pst... I did not really do anything. Please do not tell anyone...'
        }
      }), undefined, 0);
      break;

      // DISCONNECTING method
    case 'DISCONNECTWARNING':
      console.log('preparing to disconnect...');
      // console.log(mJSO.data.annotation);
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'status': {
          'type': 'SUCCESS',
          'message': ''
        }
      }), undefined, 0);
      break;

      // GETDOEDITDBCONFIG method
    case 'GETDOEDITDBCONFIG':
      console.log('checking if editDBConfig is allowed...');
      // console.log(mJSO.data.annotation);
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'data': 'YES',
        'status': {
          'type': 'SUCCESS',
          'message': ''
        }
      }), undefined, 0);
      break;

      // GETDOEDITDBCONFIG method
    case 'EDITDBCONFIG':
      console.log('editing dbConfig...');
      // console.log(mJSO.data.annotation);
      // todo: edit dbconfig and return success or error
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'data': 'YES',
        'status': {
          'type': 'SUCCESS',
          'message': ''
        }
      }), undefined, 0);
      break;

    default:
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'status': {
          'type': 'ERROR',
          'message': 'Sent request type that is unknown to server! Request type was: ' + mJSO.type
        }
      }), undefined, 0);
    }

  });

  // display that client has disconnected
  ws.on('close', function () {
    console.log('INFO: client disconnected');
  });
});

/**
 *
 */
function sendBundle(ws, bundle) {
  console.log(bundle);
}<commit_msg>back to serving ae as default<commit_after>/**
 * small demo node server that implements the EMU-webApp-websocket-protocol
 *
 * NOTE: on save no actions are performed (functions are just stubs)
 *
 * to run:
 *  > node nodeEmuProtocolWsServer.js
 *
 * author: Raphael Winkelmann
 */

'use strict';

// load deps
var fs = require('fs');
var os = require('os');
var filewalker = require('filewalker');

// allow to set vars from command line
if (process.argv.length === 2) {

  var portNr = 17890;
  // var pathToDbRoot = '/Users/raphaelwinkelmann/Desktop/gersC/';
  // var configName = 'gersC_DBconfig.json';
  var pathToDbRoot = '../app/testData/newFormat/ae/';
  var configName = 'ae_DBconfig.json';

} else if (process.argv.length === 3) {

  var portNr = process.argv[2];
  var pathToDbRoot = '../app/testData/newFormat/ae/';
  var configName = 'ae_DBconfig.json';

} else if (process.argv.length === 5) {

  var portNr = process.argv[2];
  var pathToDbRoot = process.argv[3];;
  var configName = process.argv[4];;

}

var dbConfig = {};
var ssffFilesMap = {};

// demo of user management
var doUserManagement = 'NO';
var userName = 'user1';
var userPwd = '1234'; // high security plain text password! This is for demo purposes only! Please store your passwords properly...

var WebSocketServer = require('ws').Server,
  wss = new WebSocketServer({
    port: portNr
  });

console.log('websocketserver running @: ws://' + os.hostname() + ':' + portNr);

wss.on('connection', function (ws) {

  console.log('INFO: client connected');

  ws.on('message', function (message) {
    // console.log('received: %s', message);
    var mJSO = JSON.parse(message);

    switch (mJSO.type) {
      // GETPROTOCOL method
    case 'GETPROTOCOL':
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'data': {
          'protocol': 'EMU-webApp-websocket-protocol',
          'version': '0.0.2'
        },
        'status': {
          'type': 'SUCCESS',
          'message': ''
        }
      }), undefined, 0);
      break;

      // GETDOUSERMANAGEMENT method
    case 'GETDOUSERMANAGEMENT':
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'data': doUserManagement,
        'status': {
          'type': 'SUCCESS',
          'message': ''
        }
      }), undefined, 0);
      break;

      // LOGONUSER method
    case 'LOGONUSER':

      if (mJSO.userName !== userName) {
        // handle wrong user name
        ws.send(JSON.stringify({
          'callbackID': mJSO.callbackID,
          'data': 'BADUSERNAME',
          'status': {
            'type': 'SUCCESS',
            'message': ''
          }
        }), undefined, 0);
      } else if (mJSO.pwd !== userPwd) {
        // handle wrong password
        ws.send(JSON.stringify({
          'callbackID': mJSO.callbackID,
          'data': 'BADPASSWORD',
          'status': {
            'type': 'SUCCESS',
            'message': ''
          }
        }), undefined, 0);
      } else {
        ws.send(JSON.stringify({
          'callbackID': mJSO.callbackID,
          'data': 'LOGGEDON',
          'status': {
            'type': 'SUCCESS',
            'message': ''
          }
        }), undefined, 0);
      }

      break;

      // GETGLOBALDBCONFIG method
    case 'GETGLOBALDBCONFIG':
      console.log('############## GETGLOBALDBCONFIG ####################')
      fs.readFile(pathToDbRoot + configName, 'utf8', function (err, data) {
        if (err) {
          console.log('Error: ' + err);
          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'status': {
              'type': 'ERROR',
              'message': err
            }
          }), undefined, 0);
          return;
        } else {
          dbConfig = JSON.parse(data);

          // figure out which SSFF files should be sent with each bundle
          // (could further reduce the files being sent by looking at the perspectives)
          for (var i = 0; i < dbConfig.ssffTrackDefinitions.length; i++) {
            if (ssffFilesMap[dbConfig.ssffTrackDefinitions[i].fileExtension] !== undefined) {
              ssffFilesMap[dbConfig.ssffTrackDefinitions[i].fileExtension] += 1;
            } else {
              ssffFilesMap[dbConfig.ssffTrackDefinitions[i].fileExtension] = 1;
            }
          }
          console.log(ssffFilesMap);

          // curUttList = dbConfig;
          // curStrippedUttList = stripUttList(dbConfig);

          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'data': dbConfig,
            'status': {
              'type': 'SUCCESS',
              'message': ''
            }
          }), undefined, 0);
          // ws.send(labelData);
        }
      });
      break;

      // GETBUNDLELIST method
      // file walks through DB to get all the bundles
    case 'GETBUNDLELIST':
      var bundleList = [];
      filewalker(pathToDbRoot)
        .on('dir', function (p) {

          var patt = new RegExp('^.+_ses+/.+_bndl$');
          // var patt = new RegExp('^SES[^/]+/[^/]+$');

          if (patt.test(p)) {
            var arr = p.split('/');
            var nArr = arr[arr.length - 1].split('_');
            var sArr = arr[0].split('_');
            sArr.pop();
            nArr.pop();
            bundleList.push({
              'name': nArr.join('_'),
              'session': sArr.join('_')
            });
          }
        }).on('error', function (err) {
          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'status': {
              'type': 'ERROR',
              'message': 'Error creating bundleList! Request type was: ' + mJSO.type + ' Error is: ' + err
            }
          }), undefined, 0);
        }).on('done', function () {
          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'data': bundleList,
            'status': {
              'type': 'SUCCESS',
              'message': ''
            }
          }), undefined, 0);
        }).walk();
      break;

      // GETBUNDLE method
    case 'GETBUNDLE':

      var bundle = {};
      bundle.ssffFiles = [];
      filewalker(pathToDbRoot)
        .on('dir', function () {}).on('file', function (p) {
          // var pattMedia = new RegExp('^SES[^/]+/' + mJSO.name + '/[^/]+' + dbConfig.mediafileExtension + '$');
          var pattMedia = new RegExp('^.+_ses+/' + mJSO.name + '_bndl' + '/[^/]+' + dbConfig.mediafileExtension + '$');

          // var pattAnnot = new RegExp('^SES[^/]+/' + mJSO.name + '/[^/]+' + 'json' + '$');
          var pattAnnot = new RegExp('^.+_ses+/' + mJSO.name + '_bndl' + '/[^/]+' + 'json' + '$');

          // read media file
          if (pattMedia.test(p)) {
            console.log(p);
            bundle.mediaFile = {};
            bundle.mediaFile.encoding = 'BASE64';
            bundle.mediaFile.filePath = p;
          }
          // read annotation file
          if (pattAnnot.test(p)) {
            bundle.annotation = {};
            bundle.annotation.filePath = p;
          }
          // read ssffTrackDefinitions

          // for (var i = 0; i < dbConfig.ssffTrackDefinitions.length; i++) {
          //   // var pattTrack = new RegExp('^SES[^/]+/' + mJSO.name + '/[^/]+' + dbConfig.ssffTrackDefinitions[i].fileExtension + '$');
          //   var pattTrack = new RegExp('^.+_ses+/' + mJSO.name + '_bndl' + '/[^/]+' + dbConfig.ssffTrackDefinitions[i].fileExtension + '$');
          //   if (pattTrack.test(p)) {
          //     bundle.ssffFiles.push({
          //       ssffTrackName: dbConfig.ssffTrackDefinitions[i].name,
          //       encoding: 'BASE64',
          //       filePath: p
          //     });
          //   }
          // }

        }).on('error', function (err) {
          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'status': {
              'type': 'ERROR',
              'message': 'Error getting bundle! Request type was: ' + mJSO.type + ' Error is: ' + err
            }
          }), undefined, 0);
        }).on('done', function () {
          console.log(mJSO)
          bundle.mediaFile.data = fs.readFileSync(pathToDbRoot + bundle.mediaFile.filePath, 'base64');
          delete bundle.mediaFile.filePath;

          bundle.annotation = JSON.parse(fs.readFileSync(pathToDbRoot + bundle.annotation.filePath, 'utf8'));
          delete bundle.annotation.filePath;
          for (var key in ssffFilesMap) {
              bundle.ssffFiles.push({
                fileExtension: key,
                encoding: 'BASE64',
                data: fs.readFileSync(pathToDbRoot + mJSO.session + '_ses/' + mJSO.name + '_bndl/' + mJSO.name + '.' + key, 'base64')
              });
          //   bundle.ssffFiles[i].data = fs.readFileSync(pathToDbRoot + bundle.ssffFiles[i].filePath, 'base64');
          //   delete bundle.ssffFiles[i].filePath;
          }

          console.log('##########################');
          console.log('done');
          // fs.writeFileSync('/Users/raphaelwinkelmann/Desktop/bundle.json', JSON.stringify(bundle, undefined, 0));
          ws.send(JSON.stringify({
            'callbackID': mJSO.callbackID,
            'data': bundle,
            'status': {
              'type': 'SUCCESS',
              'message': ''
            }
          }), undefined, 0);

        }).walk();
      break;

      // SAVEBUNDLE method
    case 'SAVEBUNDLE':
      console.log('### Pretending to save bundle:');
      console.log('\tname:', mJSO.data.annotation.name);
      console.log('\tsession:', mJSO.data.session);
      // console.log(mJSO.data.annotation);
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'status': {
          'type': 'SUCCESS',
          'message': 'Pst... I did not really do anything. Please do not tell anyone...'
        }
      }), undefined, 0);
      break;

      // DISCONNECTING method
    case 'DISCONNECTWARNING':
      console.log('preparing to disconnect...');
      // console.log(mJSO.data.annotation);
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'status': {
          'type': 'SUCCESS',
          'message': ''
        }
      }), undefined, 0);
      break;

      // GETDOEDITDBCONFIG method
    case 'GETDOEDITDBCONFIG':
      console.log('checking if editDBConfig is allowed...');
      // console.log(mJSO.data.annotation);
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'data': 'YES',
        'status': {
          'type': 'SUCCESS',
          'message': ''
        }
      }), undefined, 0);
      break;

      // GETDOEDITDBCONFIG method
    case 'EDITDBCONFIG':
      console.log('editing dbConfig...');
      // console.log(mJSO.data.annotation);
      // todo: edit dbconfig and return success or error
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'data': 'YES',
        'status': {
          'type': 'SUCCESS',
          'message': ''
        }
      }), undefined, 0);
      break;

    default:
      ws.send(JSON.stringify({
        'callbackID': mJSO.callbackID,
        'status': {
          'type': 'ERROR',
          'message': 'Sent request type that is unknown to server! Request type was: ' + mJSO.type
        }
      }), undefined, 0);
    }

  });

  // display that client has disconnected
  ws.on('close', function () {
    console.log('INFO: client disconnected');
  });
});

/**
 *
 */
function sendBundle(ws, bundle) {
  console.log(bundle);
}<|endoftext|>


<commit_before>var Player = Character.extend({
    position: { x: 25, y: 155},

    ammoInClip: 0,
    ammoClipSize: 0,
    reloadTime: 0,
    fireTimeout: 0,
    hurtTimeout: 0,

    txBlaster: null,

    weaponBackfire: 0,
    isFiring: false,

    init: function() {
        this._super();

        this.txBody.src = 'assets/textures/steve.png';

        this.txCorpse = new Image();
        this.txCorpse.src = 'assets/textures/steve_dead.png';
        this.txCorpseSize = { w: 15, h: 20 };

        this.txBlaster = new Image();
        this.txBlaster.src = 'assets/textures/steve_blaster.png';

        this.size = { w: 15, h: 20 };
        this.ammoClipSize = 15;
        this.ammoInClip = this.ammoClipSize;
        this.hurtTimeout = 0;
        this.isFiring = false;

        this.syncHud();
    },

    reload: function() {
        if (this.reloadTime > 0) {
            return;
        }

        this.reloadTime = 30;
        this.ammoInClip = this.ammoClipSize;

        Sfx.reload();

        this.syncHud();
    },

    drawExtras: function(ctx) {
        if (this.isHurting) {
            return;
        }

        var offsetPos = {
            x: this.lastPosition.x - this.position.x,
            y: this.lastPosition.y - this.position.y
        };

        ctx.drawImage(this.txBlaster, 0, 0, this.size.w, this.size.h, offsetPos.x - this.weaponBackfire, offsetPos.y - this.weaponBackfire, this.size.w, this.size.h);
    },

    syncHud: function() {
        var $ammoCount = $('#hud .ammo-count');
        $ammoCount.text(this.ammoInClip);

        if (this.reloadTime > 0) {
            $ammoCount.addClass('reloading');
        } else {
            $ammoCount.removeClass('reloading');
        }
    },

    fire: function() {
        var projectile = new Projectile(this);
        projectile.position = {
            x: this.position.x + (this.facingEast ? 0 : 7),
            y: this.position.y + (this.size.h / 2) - 1
        };
        projectile.velocity = {
            x: this.facingEast ? 10 : -10,
            y: 0
        };

        this.ammoInClip--;

        Map.add(projectile);
        Sfx.fire();

        this.syncHud();

        this.knockBack(1, this.facingEast);

        this.weaponBackfire = this.facingEast ? 1 : -1;

        Camera.rumble(5, 2);

        this.isFiring = true;
    },

    hurt: function(source, damage) {
        if (this.hurtTimeout > 0) {
            damage = 0;
        }

        if (damage > 0) {
            this.hurtTimeout = 10;
            Camera.rumble(5, 3);
        }

        this._super(source, damage);
    },

    die: function() {
        this._super();

        $('#ded').show();
    },

    update: function() {
        if (this.dead) {
            if (Keyboard.wasKeyPressed(KeyEvent.DOM_VK_SPACE)) {
                // Restart game
                Renderer.loadMap(Map.id);
            }

            this._super();
            return;
        }

        /*** Input ***/
        if ((Keyboard.isKeyDown(KeyEvent.DOM_VK_LEFT) || Keyboard.isKeyDown(KeyEvent.DOM_VK_A)) && this.canMoveLeft) {
            if (!this.isFiring) {
                this.facingEast = false;
            }
            this.position.x -= this.movementSpeed;
        }

        if ((Keyboard.isKeyDown(KeyEvent.DOM_VK_RIGHT) || Keyboard.isKeyDown(KeyEvent.DOM_VK_D)) && this.canMoveRight) {
            if (!this.isFiring) {
                this.facingEast = true;
            }
            this.position.x += this.movementSpeed;
        }

        if (this.canJump && (Keyboard.wasKeyPressed(KeyEvent.DOM_VK_UP) || Keyboard.wasKeyPressed(KeyEvent.DOM_VK_W))) {
            this.jump();
        }

        var reloading = false;

        if (this.weaponBackfire > 0) {
            this.weaponBackfire--;
        } else if (this.weaponBackfire < 0) {
            this.weaponBackfire++;
        }

        if (this.reloadTime > 0) {
            // Reloading, one frame at a time
            this.reloadTime--;
            reloading = true;

            if (this.reloadTime == 0) {
                this.syncHud();
            }
        }

        if (this.fireTimeout > 0) {
            this.fireTimeout--;
        }

        var holdingFireButton = Keyboard.isKeyDown(KeyEvent.DOM_VK_SPACE);

        if (!reloading && this.fireTimeout == 0 && this.canFire) {
            if (Keyboard.wasKeyPressed(KeyEvent.DOM_VK_R)) {
                if (this.ammoInClip < this.ammoClipSize) {
                    this.reload();
                }
            } else if (holdingFireButton) {
                if (this.ammoInClip <= 0) {
                    this.reload();
                } else {
                    this.fire();
                    this.fireTimeout = 6;
                }
            }
        }

        this.isFiring = !!holdingFireButton;

        if (this.hurtTimeout > 0) {
            this.hurtTimeout--;
        }

        this._super();
    }

});<commit_msg>Player: Improve spawn position<commit_after>var Player = Character.extend({
    position: { x: 160, y: 160},

    ammoInClip: 0,
    ammoClipSize: 0,
    reloadTime: 0,
    fireTimeout: 0,
    hurtTimeout: 0,

    txBlaster: null,

    weaponBackfire: 0,
    isFiring: false,

    init: function() {
        this._super();

        this.txBody.src = 'assets/textures/steve.png';

        this.txCorpse = new Image();
        this.txCorpse.src = 'assets/textures/steve_dead.png';
        this.txCorpseSize = { w: 15, h: 20 };

        this.txBlaster = new Image();
        this.txBlaster.src = 'assets/textures/steve_blaster.png';

        this.size = { w: 15, h: 20 };
        this.ammoClipSize = 15;
        this.ammoInClip = this.ammoClipSize;
        this.hurtTimeout = 0;
        this.isFiring = false;

        this.syncHud();
    },

    reload: function() {
        if (this.reloadTime > 0) {
            return;
        }

        this.reloadTime = 30;
        this.ammoInClip = this.ammoClipSize;

        Sfx.reload();

        this.syncHud();
    },

    drawExtras: function(ctx) {
        if (this.isHurting) {
            return;
        }

        var offsetPos = {
            x: this.lastPosition.x - this.position.x,
            y: this.lastPosition.y - this.position.y
        };

        ctx.drawImage(this.txBlaster, 0, 0, this.size.w, this.size.h, offsetPos.x - this.weaponBackfire, offsetPos.y - this.weaponBackfire, this.size.w, this.size.h);
    },

    syncHud: function() {
        var $ammoCount = $('#hud .ammo-count');
        $ammoCount.text(this.ammoInClip);

        if (this.reloadTime > 0) {
            $ammoCount.addClass('reloading');
        } else {
            $ammoCount.removeClass('reloading');
        }
    },

    fire: function() {
        var projectile = new Projectile(this);
        projectile.position = {
            x: this.position.x + (this.facingEast ? 0 : 7),
            y: this.position.y + (this.size.h / 2) - 1
        };
        projectile.velocity = {
            x: this.facingEast ? 10 : -10,
            y: 0
        };

        this.ammoInClip--;

        Map.add(projectile);
        Sfx.fire();

        this.syncHud();

        this.knockBack(1, this.facingEast);

        this.weaponBackfire = this.facingEast ? 1 : -1;

        Camera.rumble(5, 2);

        this.isFiring = true;
    },

    hurt: function(source, damage) {
        if (this.hurtTimeout > 0) {
            damage = 0;
        }

        if (damage > 0) {
            this.hurtTimeout = 10;
            Camera.rumble(5, 3);
        }

        this._super(source, damage);
    },

    die: function() {
        this._super();

        $('#ded').show();
    },

    update: function() {
        if (this.dead) {
            if (Keyboard.wasKeyPressed(KeyEvent.DOM_VK_SPACE)) {
                // Restart game
                Renderer.loadMap(Map.id);
            }

            this._super();
            return;
        }

        /*** Input ***/
        if ((Keyboard.isKeyDown(KeyEvent.DOM_VK_LEFT) || Keyboard.isKeyDown(KeyEvent.DOM_VK_A)) && this.canMoveLeft) {
            if (!this.isFiring) {
                this.facingEast = false;
            }
            this.position.x -= this.movementSpeed;
        }

        if ((Keyboard.isKeyDown(KeyEvent.DOM_VK_RIGHT) || Keyboard.isKeyDown(KeyEvent.DOM_VK_D)) && this.canMoveRight) {
            if (!this.isFiring) {
                this.facingEast = true;
            }
            this.position.x += this.movementSpeed;
        }

        if (this.canJump && (Keyboard.wasKeyPressed(KeyEvent.DOM_VK_UP) || Keyboard.wasKeyPressed(KeyEvent.DOM_VK_W))) {
            this.jump();
        }

        var reloading = false;

        if (this.weaponBackfire > 0) {
            this.weaponBackfire--;
        } else if (this.weaponBackfire < 0) {
            this.weaponBackfire++;
        }

        if (this.reloadTime > 0) {
            // Reloading, one frame at a time
            this.reloadTime--;
            reloading = true;

            if (this.reloadTime == 0) {
                this.syncHud();
            }
        }

        if (this.fireTimeout > 0) {
            this.fireTimeout--;
        }

        var holdingFireButton = Keyboard.isKeyDown(KeyEvent.DOM_VK_SPACE);

        if (!reloading && this.fireTimeout == 0 && this.canFire) {
            if (Keyboard.wasKeyPressed(KeyEvent.DOM_VK_R)) {
                if (this.ammoInClip < this.ammoClipSize) {
                    this.reload();
                }
            } else if (holdingFireButton) {
                if (this.ammoInClip <= 0) {
                    this.reload();
                } else {
                    this.fire();
                    this.fireTimeout = 6;
                }
            }
        }

        this.isFiring = !!holdingFireButton;

        if (this.hurtTimeout > 0) {
            this.hurtTimeout--;
        }

        this._super();
    }

});<|endoftext|>


<commit_before>/*jslint browser:true*/
/*global App, Saga*/

/*

	<% _.each(users, function(user){ %>

		<%= user.id %> <%= user.first_name %> <%= user.last_name %>

	<% }); %>

*/

(function (asset) {
    "use strict";
    var div,
        debug = Saga.Debug,
        e = Saga.Dom.getById,
        u = Saga.Util,
        list = Saga.List("/albatros/sites/question_admin/site/data/qs.php"),
        addClicks = function () {
            e("btnLoadList").onclick = function () {
                list.load();
            };
            /*
            e("listContainer").innerHTML = asset.template({
                users: App.Model.users()
            });
            */
        },
        loadList = function () {
            list.checkbox(true, function (row) {

            });

            list.on("loaded", function () {
                Saga.Dom.elem("listContainer").innerHTML = list.template({
                    rows: list.data()
                });
                /*
                Saga.Dom.elem("listContainer").innerHTML = u.template(list.getTableTemplate(), {
                    rows: list.data()
                });
                */
            });
            list.load();
        },
        init = function (cb) {
            debug.log(asset.id + ".init()");
            div = e(asset.name);
            loadList();
            if(cb){ // ok this need more epic
                cb();
            }
            //addClicks();
        },
        simpleInit;

    Saga.Util.extend(asset.View, App.SimpleView(asset));

    simpleInit = asset.View.init;
    asset.View.init = function () {
        simpleInit();
        init();
    };
}(App.Assets.List));<commit_msg>Miguel Commit: za 10 mei 2014 01:45:22 CEST<commit_after>/*jslint browser:true*/
/*global App, Saga*/

(function (asset) {
    "use strict";
    var div,
        debug = Saga.Debug,
        e = Saga.Dom.getById,
        u = Saga.Util,
        list = Saga.List("/albatros/sites/question_admin/site/data/qs.php"),
        addClicks = function () {
            e("btnLoadList").onclick = function () {
                list.load();
            };
            /*
            e("listContainer").innerHTML = asset.template({
                users: App.Model.users()
            });
            */
        },
        loadList = function () {
            list.checkbox(true, function (row) {

            });

            list.on("loaded", function () {
                Saga.Dom.elem("listContainer").innerHTML = list.template({
                    rows: list.data()
                });
            });
            list.load();
        },
        init = function (cb) {
            debug.log(asset.id + ".init()");
            div = e(asset.name);
            loadList();
            if(cb){ // ok this need more epic
                cb();
            }
            //addClicks();
        },
        simpleInit;

    Saga.Util.extend(asset.View, App.SimpleView(asset));

    simpleInit = asset.View.init;
    asset.View.init = function () {
        simpleInit();
        init();
    };
}(App.Assets.List));<|endoftext|>


<commit_before>var util = require('util'),
  os = require('os'),
  PythonShell = require('python-shell'),
  exec = require('child_process').exec,
  bleno = require('bleno'),
  gpio = require("pi-gpio"),
  Descriptor = bleno.Descriptor,
  Characteristic = bleno.Characteristic,
  ShinySettings = require('./shiny');

var BatteryLevelCharacteristic = function() {
  BatteryLevelCharacteristic.super_.call(this, {
      uuid: '2A19',
      properties: ['read', 'write', 'notify'],
      descriptors: [
        new Descriptor({
            uuid: '2901',
            value: 'Battery level between 0 and 100 percent'
        }),
        new Descriptor({
            uuid: '2904',
            value: new Buffer([0x04, 0x01, 0x27, 0xAD, 0x01, 0x00, 0x00 ]) // maybe 12 0xC unsigned 8 bit
        })
      ]
  });
};

util.inherits(BatteryLevelCharacteristic, Characteristic);

BatteryLevelCharacteristic.prototype.onReadRequest = function(offset, callback) {

  console.log("in read");
  if (os.platform() === 'darwin') {
    exec('pmset -g batt', function (error, stdout, stderr) {

      var data = stdout.toString();
      // data - 'Now drawing from \'Battery Power\'\n -InternalBattery-0\t95%; discharging; 4:11 remaining\n'
      var percent = data.split('\t')[1].split(';')[0];
      console.log(percent);
      percent = parseInt(percent, 10);
      callback(this.RESULT_SUCCESS, new Buffer([percent]));

    });
  } else {
    // return hardcoded value
    console.log("reading...")
    callback(this.RESULT_SUCCESS, new Buffer([98]));

  }
};

BatteryLevelCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) {
  //console.log("in write");
  if (offset) {
    //console.log("in write - offset");
    callback(this.RESULT_ATTR_NOT_LONG);
  }
  //else if (data.length !== 1) {
   // console.log("data length !== 1");
    //console.log(JSON.stringify(data));
    //callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH);
  //}
  else {
    // console.log(JSON.stringify(data));
    // console.log('processing write request');
    // var receivedData = data.readUInt8(0);
    // console.log(typeof data);
    // console.log(data.toString('ascii'));

    // console.log(receivedData);
    // console.log(typeof receivedData);
        var command = data.toString('ascii');
    //console.log('command');
    console.log(command);

    if(command === "0"){
      console.log("stop");
      // print "Now stop"
      // GPIO.output(Motor1E,GPIO.LOW)

           gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }
    else if(command === "2"){
      console.log("command left");

           gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 1, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 1, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }else if(command === "1"){
      console.log("command right");

            gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 1, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 1, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });
    }
    else if(command === "4"){
      console.log("forward");

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 1, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 1, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }
    else if(command === "3"){
      console.log("back");

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 low");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 1, function() {
                    console.log("set pin 18 high");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 low");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 1, function() {
                                      console.log("set pin 15 high");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });

      });
    }
  }
  callback(this.RESULT_SUCCESS);
};

function setMotorDirection(direction) {
    console.log('Setting: ' + direction);

          var pin16 = 0;
          var pin18 = 0;
          var pin22 = 0;

          if(direction === 'forward'){
            pin16 = 1;
            pin18 = 0;
            pin22 = 1;
          }else if (direction == 'reverse'){
            pin16 = 1;
            pin18 = 0;
            pin22 = 1;
          }

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, pin16, function() {            // Set pin 16 high (1)
                console.log("set pin 16 " + pin16);
              //gpio.close(16);                        // Close pin 16
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, pin18, function() {            // Set pin 18 low (0)
                    console.log("set pin 18 " + pin18);
                  //gpio.close(18);                        // Close pin 18
                    gpio.open(22, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(22, pin22, function() {            // Set pin 22 high (1)
                              console.log("set pin 22 " + pin22);
                            //gpio.close(22);                        // Close pin 22
                          });
                        });
                });
              });
            });
          });
}

BatteryLevelCharacteristic.prototype.onNotify = function() {
  console.log('NotifyOnlyCharacteristic on notify');
};

module.exports = BatteryLevelCharacteristic;
<commit_msg>limit time for turning<commit_after>var util = require('util'),
  os = require('os'),
  PythonShell = require('python-shell'),
  exec = require('child_process').exec,
  bleno = require('bleno'),
  gpio = require("pi-gpio"),
  Descriptor = bleno.Descriptor,
  Characteristic = bleno.Characteristic,
  ShinySettings = require('./shiny');

var BatteryLevelCharacteristic = function() {
  BatteryLevelCharacteristic.super_.call(this, {
      uuid: '2A19',
      properties: ['read', 'write', 'notify'],
      descriptors: [
        new Descriptor({
            uuid: '2901',
            value: 'Battery level between 0 and 100 percent'
        }),
        new Descriptor({
            uuid: '2904',
            value: new Buffer([0x04, 0x01, 0x27, 0xAD, 0x01, 0x00, 0x00 ]) // maybe 12 0xC unsigned 8 bit
        })
      ]
  });
};

util.inherits(BatteryLevelCharacteristic, Characteristic);

BatteryLevelCharacteristic.prototype.onReadRequest = function(offset, callback) {

  console.log("in read");
  if (os.platform() === 'darwin') {
    exec('pmset -g batt', function (error, stdout, stderr) {

      var data = stdout.toString();
      // data - 'Now drawing from \'Battery Power\'\n -InternalBattery-0\t95%; discharging; 4:11 remaining\n'
      var percent = data.split('\t')[1].split(';')[0];
      console.log(percent);
      percent = parseInt(percent, 10);
      callback(this.RESULT_SUCCESS, new Buffer([percent]));

    });
  } else {
    // return hardcoded value
    console.log("reading...")
    callback(this.RESULT_SUCCESS, new Buffer([98]));

  }
};

BatteryLevelCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) {
  //console.log("in write");
  if (offset) {
    //console.log("in write - offset");
    callback(this.RESULT_ATTR_NOT_LONG);
  }
  //else if (data.length !== 1) {
   // console.log("data length !== 1");
    //console.log(JSON.stringify(data));
    //callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH);
  //}
  else {
    // console.log(JSON.stringify(data));
    // console.log('processing write request');
    // var receivedData = data.readUInt8(0);
    // console.log(typeof data);
    // console.log(data.toString('ascii'));

    // console.log(receivedData);
    // console.log(typeof receivedData);
        var command = data.toString('ascii');
    //console.log('command');
    console.log(command);

    if(command === "0"){
      console.log("stop");
      // print "Now stop"
      // GPIO.output(Motor1E,GPIO.LOW)

           gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }
    else if(command === "2"){
      console.log("command left");

           gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 1, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 1, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    setTimeout(stop(),500);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }else if(command === "1"){
      console.log("command right");

            gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 1, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 1, function() {
                                      console.log("set pin 15 low");
                                    setTimeout(stop(),500);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });
    }
    else if(command === "4"){
      console.log("forward");

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 1, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 1, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });

    }
    else if(command === "3"){
      console.log("back");

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 low");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 1, function() {
                    console.log("set pin 18 high");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 low");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 1, function() {
                                      console.log("set pin 15 high");

                                  stop();
                                  });
                                });
                          });
                        });
                });
              });
            });

      });
    }
  }
  callback(this.RESULT_SUCCESS);
};

function stop(){

           gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, 0, function() {
                console.log("set pin 16 high");
              //gpio.close(16);
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, 0, function() {
                    console.log("set pin 18 low");
                  //gpio.close(18);
                    gpio.open(13, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(13, 0, function() {
                              console.log("set pin 13 high");
                              gpio.open(15, "output", function(err) {
                                  if(err){
                                    console.log(err);
                                  }       // Open pin 22 for output
                                  gpio.write(15, 0, function() {
                                      console.log("set pin 15 low");
                                    //gpio.close(22);
                                  });
                                });
                          });
                        });
                });
              });
            });
          });
}

function setMotorDirection(direction) {
    console.log('Setting: ' + direction);

          var pin16 = 0;
          var pin18 = 0;
          var pin22 = 0;

          if(direction === 'forward'){
            pin16 = 1;
            pin18 = 0;
            pin22 = 1;
          }else if (direction == 'reverse'){
            pin16 = 1;
            pin18 = 0;
            pin22 = 1;
          }

          gpio.open(16, "output", function(err) {
            if(err){
              console.log(err);
            }       // Open pin 16 for output
            gpio.write(16, pin16, function() {            // Set pin 16 high (1)
                console.log("set pin 16 " + pin16);
              //gpio.close(16);                        // Close pin 16
              //18
              gpio.open(18, "output", function(err) {
                if(err){
                  console.log(err);
                }       // Open pin 18 for output
                gpio.write(18, pin18, function() {            // Set pin 18 low (0)
                    console.log("set pin 18 " + pin18);
                  //gpio.close(18);                        // Close pin 18
                    gpio.open(22, "output", function(err) {
                          if(err){
                            console.log(err);
                          }       // Open pin 22 for output
                          gpio.write(22, pin22, function() {            // Set pin 22 high (1)
                              console.log("set pin 22 " + pin22);
                            //gpio.close(22);                        // Close pin 22
                          });
                        });
                });
              });
            });
          });
}

BatteryLevelCharacteristic.prototype.onNotify = function() {
  console.log('NotifyOnlyCharacteristic on notify');
};

module.exports = BatteryLevelCharacteristic;
<|endoftext|>


<commit_before>VRtwglQuad = require('./VRtwglQuad.js');
twgl = require('../js-ext/twgl-full.js');

var vs = "attribute vec4 position;\n"+
"void main() {\n"+
"  gl_Position = position;\n"+
"}\n";

// equations - see: http://stackoverflow.com/a/1185413
var fsFull360180 = "precision mediump float;\n"+
"#define PI 3.141592653589793\n"+
"uniform vec2 resolution;\n"+
"uniform sampler2D textureSource;\n"+
"uniform mat4 transform;\n"+
"void main(void) {\n"+
"  //normalize uv so it is between 0 and 1\n"+
"  vec2 uv = gl_FragCoord.xy / resolution;\n"+
"  uv.y = (1. - uv.y);\n"+
"  //map uv.x 0..1 to -PI..PI and uv.y 0..1 to -PI/2..PI/2\n"+
"  float lat = 0.5*PI*(uv.y-0.5);\n"+
"  float lon = PI*(uv.x-0.5);\n"+
"  // map lat/lon to point on unit sphere\n"+
"  vec4 sphere_pnt = vec4(cos(lat) * cos(lon), cos(lat) * sin(lon), sin(lat), 1.);\n"+
"  // rotate point around origin via transform - pitch/yaw etc\n"+
"  sphere_pnt *= transform;\n"+
"  // now map point in sphere back to lat/lon coords\n"+
"  float R = length(sphere_pnt);\n"+
"  // map asin, which is -PI/2..PI/2 to 0..1\n"+
"  float finalLat = 0.5+asin(sphere_pnt.z/R)/(0.5*PI);\n"+
"  // map atan, which is -PI..PI to 0..1\n"+
"  float finalLon = 0.5+atan(sphere_pnt.y, sphere_pnt.x)/(PI);\n"+
"  gl_FragColor = texture2D(textureSource, vec2(finalLon, finalLat));\n"+
"}\n"

var fsWindowed = "precision mediump float;\n"+
"#define PI 3.141592653589793\n"+
"uniform vec2 resolution;\n"+
"uniform sampler2D textureSource;\n"+
"uniform mat4 transform;\n"+
"void main(void) {\n"+
"  //normalize uv so it is between 0 and 1\n"+
"  vec2 uv = gl_FragCoord.xy / resolution;\n"+
"  uv.y = (1. - uv.y);\n"+
"  vec2 sphX = vec2(.25,.25);\n"+
"  vec2 sphY = vec2(.75,.75);\n"+
"  vec2 sphYX = sphY-sphX;\n"+
"  vec2 testPt = (uv-sphX);\n"+
"  testPt= mod(testPt, 1.)/sphYX;\n"+
"  if (testPt.x<0. || testPt.x>1. || testPt.y<0. || testPt.y>1.){ discard; return;}\n"+
"  //map uv.x 0..1 to -PI..PI and uv.y 0..1 to -PI/2..PI/2\n"+
"  float lat = 0.5*PI*(uv.y-0.5);\n"+
"  float lon = PI*(uv.x-0.5);\n"+
"  // map lat/lon to point on unit sphere\n"+
"  vec4 sphere_pnt = vec4(cos(lat) * cos(lon), cos(lat) * sin(lon), sin(lat), 1.);\n"+
"  // rotate point around origin via transform - pitch/yaw etc\n"+
"  sphere_pnt *= transform;\n"+
"  // now map point in sphere back to lat/lon coords\n"+
"  float R = length(sphere_pnt);\n"+
"  // map asin, which is -PI/2..PI/2 to 0..1\n"+
"  float finalLat = 0.5+asin(sphere_pnt.z/R)/(0.5*PI);\n"+
"  // map atan, which is -PI..PI to 0..1\n"+
"  float finalLon = 0.5+atan(sphere_pnt.y, sphere_pnt.x)/(PI);\n"+
"  gl_FragColor = texture2D(textureSource, vec2(finalLon, finalLat));\n"+
"}\n"

VRtwglQuadStereoProjection = function() {
  var self = this;
  this.vrtwglQuad = null;
  this.uniforms = {
    resolution:[0,0],
    textureSource:null,
    transform:twgl.m4.identity()
  };

  this.init = function(element){
    this.vrtwglQuad = new VRtwglQuad();
    this.vrtwglQuad.init(element, vs, fsWindowed);
  }

  this.resize = function() {
    self.vrtwglQuad.resize();
  }

  this.render = function() {
    this.uniforms["resolution"] = [self.vrtwglQuad.canvas.clientWidth, self.vrtwglQuad.canvas.clientHeight];
    // var axisYaw = twgl.v3.create(0,1,0);
    // twgl.m4.axisRotate(this.uniforms.transform, axisYaw, 0.01, this.uniforms.transform);
    // var axisPitch = twgl.v3.create(0,0,1);
    // twgl.m4.axisRotate(this.uniforms.transform, axisPitch, 0.01, this.uniforms.transform);

    self.vrtwglQuad.setUniforms(this.uniforms);
    self.vrtwglQuad.render();
  }

  this.anim = function() {
    self.render();
    requestAnimationFrame(self.anim);
  }

  this.setupProjection = function (textureDescription) {
    var gl = self.vrtwglQuad.glContext;
    var tex = twgl.createTexture(gl, {
      min: gl.LINEAR,
      mag: gl.LINEAR,
      src: textureDescription.textureSource,
      crossOrigin: "", // either this or use twgl.setDefaults
    });

    this.uniforms["textureSource"] = tex;
  }

}

module.exports = VRtwglQuadStereoProjection;
<commit_msg>testing<commit_after>VRtwglQuad = require('./VRtwglQuad.js');
twgl = require('../js-ext/twgl-full.js');

var vs = "attribute vec4 position;\n"+
"void main() {\n"+
"  gl_Position = position;\n"+
"}\n";

var fsPassthrough = "precision mediump float;\n"+
"#define PI 3.141592653589793\n"+
"uniform vec2 resolution;\n"+
"uniform sampler2D textureSource;\n"+
"uniform mat4 transform;\n"+
"void main(void) {\n"+
"  //normalize uv so it is between 0 and 1\n"+
"  vec2 uv = gl_FragCoord.xy / resolution;\n"+
"  uv.y = (1. - uv.y);\n"+
"  gl_FragColor = texture2D(textureSource, vec2(uv.x, uv.y));\n"+
"}\n"

// equations - see: http://stackoverflow.com/a/1185413
var fsFull360180 = "precision mediump float;\n"+
"#define PI 3.141592653589793\n"+
"uniform vec2 resolution;\n"+
"uniform sampler2D textureSource;\n"+
"uniform mat4 transform;\n"+
"void main(void) {\n"+
"  //normalize uv so it is between 0 and 1\n"+
"  vec2 uv = gl_FragCoord.xy / resolution;\n"+
"  uv.y = (1. - uv.y);\n"+
"  vec2 rads = vec2(PI * 2. , PI);\n"+
//"  uv.y = .5+2.*(uv.y-0.5);\n"+
"  //map uv.x 0..1 to -PI..PI and uv.y 0..1 to -PI/2..PI/2\n"+
"  float lat = 0.5*PI*(uv.y-0.5);\n"+
"  float lon = PI*(uv.x-0.5);\n"+
"  // map lat/lon to point on unit sphere\n"+
"  vec4 sphere_pnt = vec4(cos(lat) * cos(lon), cos(lat) * sin(lon), sin(lat), 1.);\n"+
"  // rotate point around origin via transform - pitch/yaw etc\n"+
"  sphere_pnt *= transform;\n"+
"  // now map point in sphere back to lat/lon coords\n"+
"  float R = length(sphere_pnt);\n"+
"  sphere_pnt /= R;\n"+
"  // map asin, which is -PI/2..PI/2 to 0..1\n"+
"  float finalLat = 2.0*(asin(sphere_pnt.z) - PI*.5) + PI*.5;\n"+
"  // map atan, which is -PI..PI to 0..1\n"+
"  float finalLon = atan(sphere_pnt.y, sphere_pnt.x);\n"+
"  finalLon = mod(finalLon, 2.*PI);\n"+
"  vec2 final = vec2(lon, lat) / rads;\n"+
"  gl_FragColor = texture2D(textureSource, final);\n"+
"}\n"

// "  // map asin, which is -PI/2..PI/2 to 0..1\n"+
// "  float finalLat = 0.5+asin(sphere_pnt.z)/(0.5*PI);\n"+
// "  // map atan, which is -PI..PI to 0..1\n"+
// "  float finalLon = 0.5+atan(sphere_pnt.y, sphere_pnt.x)/(PI);\n"+

// "  float finalLat = 2.0*(acos(sphere_pnt.z - PI*.5) + PI*.5;\n"+
// "  float finalLon = atan(sphere_pnt.y, sphere_pnt.x);\n"+
// "  finalLon = mod(finalLon, 2.*PI);\n"+

var fsWindowed = "precision mediump float;\n"+
"#define PI 3.141592653589793\n"+
"uniform vec2 resolution;\n"+
"uniform sampler2D textureSource;\n"+
"uniform mat4 transform;\n"+
"void main(void) {\n"+
"  //normalize uv so it is between 0 and 1\n"+
"  vec2 uv = gl_FragCoord.xy / resolution;\n"+
"  uv.y = (1. - uv.y);\n"+
"  uv.y = .5+2.*(uv.y-0.5);\n"+
"  //map uv.x 0..1 to -PI..PI and uv.y 0..1 to -PI/2..PI/2\n"+
"  float lat = 0.5*PI*(uv.y-0.5);\n"+
"  float lon = PI*(uv.x-0.5);\n"+
"  // map lat/lon to point on unit sphere\n"+
"  vec4 sphere_pnt = vec4(cos(lat) * cos(lon), cos(lat) * sin(lon), sin(lat), 1.);\n"+
"  // rotate point around origin via transform - pitch/yaw etc\n"+
"  sphere_pnt *= transform;\n"+
"  // now map point in sphere back to lat/lon coords\n"+
"  float R = length(sphere_pnt);\n"+
"  // map asin, which is -PI/2..PI/2 to 0..1\n"+
"  float finalLat = 0.5+asin(sphere_pnt.z/R)/(0.5*PI);\n"+
"  // map atan, which is -PI..PI to 0..1\n"+
"  float finalLon = 0.5+atan(sphere_pnt.y, sphere_pnt.x)/(PI);\n"+
"  vec2 sphPt = vec2(finalLon, finalLat);\n"+
"  vec2 sphX = vec2(0.25,0.25);\n"+
"  vec2 sphY = vec2(0.75,0.75);\n"+
"  vec2 sphYX = sphY-sphX;\n"+
"  vec2 testPt = (sphPt-sphX);\n"+
"  testPt = mod(testPt, 1.)/sphYX;\n"+
"  if (testPt.x<0. || testPt.x>1. || testPt.y<0. || testPt.y>1.){ discard; return;}\n"+
"  gl_FragColor = texture2D(textureSource, vec2(finalLon, finalLat));\n"+
"}\n"

VRtwglQuadStereoProjection = function() {
  var self = this;
  this.vrtwglQuad = null;
  this.uniforms = {
    resolution:[0,0],
    textureSource:null,
    transform:twgl.m4.identity()
  };

  this.init = function(element){
    this.vrtwglQuad = new VRtwglQuad();
    this.vrtwglQuad.init(element, vs, fsFull360180);
    // var axisYaw = twgl.v3.create(0,1,0);
    // twgl.m4.axisRotate(this.uniforms.transform, axisYaw, Math.PI/2, this.uniforms.transform);
  }

  this.resize = function() {
    self.vrtwglQuad.resize();
  }

  this.render = function() {
    this.uniforms["resolution"] = [self.vrtwglQuad.canvas.clientWidth, self.vrtwglQuad.canvas.clientHeight];
    // var axisYaw = twgl.v3.create(0,1,0);
    // twgl.m4.axisRotate(this.uniforms.transform, axisYaw, 0.005, this.uniforms.transform);
    // var axisPitch = twgl.v3.create(0,0,1);
    // twgl.m4.axisRotate(this.uniforms.transform, axisPitch, 0.01, this.uniforms.transform);

    self.vrtwglQuad.setUniforms(this.uniforms);
    self.vrtwglQuad.render();
  }

  this.anim = function() {
    self.render();
    requestAnimationFrame(self.anim);
  }

  this.setupProjection = function (textureDescription) {
    var gl = self.vrtwglQuad.glContext;
    var tex = twgl.createTexture(gl, {
      min: gl.LINEAR,
      mag: gl.LINEAR,
      src: textureDescription.textureSource,
      crossOrigin: "", // either this or use twgl.setDefaults
    });

    this.uniforms["textureSource"] = tex;
  }

}

module.exports = VRtwglQuadStereoProjection;
<|endoftext|>


<commit_before>VRtwglQuad = require('./VRtwglQuad.js');
twgl = require('../js-ext/twgl-full.js');

var vs = "attribute vec4 position;\n"+
"void main() {\n"+
"  gl_Position = position;\n"+
"}\n";

// equations - see: http://stackoverflow.com/a/1185413
var fs = "precision mediump float;\n"+
"#define PI 3.141592653589793\n"+
"uniform vec2 resolution;\n"+
"uniform sampler2D textureSource;\n"+
"uniform mat4 transform;\n"+
"void main(void) {\n"+
"  //normalize uv so it is between 0 and 1\n"+
"  vec2 uv = gl_FragCoord.xy / resolution;\n"+
"  uv.y = (1. - uv.y);\n"+
//"  uv = 2.*uv;\n"+
"  float lat = uv.y;\n"+
"  float lon = uv.x;\n"+
"  vec4 sphere_pnt = vec4(cos(lat) * cos(lon), cos(lat) * sin(lon), sin(lat), 1.);\n"+
"  sphere_pnt *= transform;\n"+
"  float finalLat = asin(sphere_pnt.z);\n"+
"  float finalLon = atan(sphere_pnt.y, sphere_pnt.x);\n"+
"  gl_FragColor = texture2D(textureSource, vec2(finalLon, finalLat));\n"+
"}\n"

VRtwglQuadStereoProjection = function() {
  var self = this;
  this.vrtwglQuad = null;
  this.uniforms = {
    resolution:[0,0],
    textureSource:null,
    transform:twgl.m4.identity()
  };

  this.init = function(element){
    this.vrtwglQuad = new VRtwglQuad();
    this.vrtwglQuad.init(element, vs, fs);
    //twgl.m4.rotateZ(this.uniforms.transform, 0, this.uniforms.transform); // yaw
    //var axis = twgl.v3.create(0,1,0);
    //twgl.m4.axisRotate(this.uniforms.transform, axis, Math.PI/2, this.uniforms.transform);
  }

  this.resize = function() {
    self.vrtwglQuad.resize();
  }

  this.render = function() {
    this.uniforms["resolution"] = [self.vrtwglQuad.canvas.clientWidth, self.vrtwglQuad.canvas.clientHeight];
    //twgl.m4.rotateX(this.uniforms.transform, 0.01, this.uniforms.transform);

    self.vrtwglQuad.setUniforms(this.uniforms);
    self.vrtwglQuad.render();
  }

  this.anim = function() {
    self.render();
    requestAnimationFrame(self.anim);
  }

  this.setupProjection = function (textureDescription) {
    var gl = self.vrtwglQuad.glContext;
    var tex = twgl.createTexture(gl, {
      min: gl.LINEAR,
      mag: gl.LINEAR,
      src: textureDescription.textureSource,
      crossOrigin: "", // either this or use twgl.setDefaults
    });

    this.uniforms["textureSource"] = tex;
  }

}

module.exports = VRtwglQuadStereoProjection;
<commit_msg>next step: validate uv coords<commit_after>VRtwglQuad = require('./VRtwglQuad.js');
twgl = require('../js-ext/twgl-full.js');

var vs = "attribute vec4 position;\n"+
"void main() {\n"+
"  gl_Position = position;\n"+
"}\n";

// equations - see: http://stackoverflow.com/a/1185413
var fs = "precision mediump float;\n"+
"#define PI 3.141592653589793\n"+
"uniform vec2 resolution;\n"+
"uniform sampler2D textureSource;\n"+
"uniform mat4 transform;\n"+
"void main(void) {\n"+
"  //normalize uv so it is between 0 and 1\n"+
"  vec2 uv = gl_FragCoord.xy / resolution;\n"+
"  uv.y = (1. - uv.y);\n"+
//"  uv = 2.*uv;\n"+
"  float lat = uv.y;\n"+
"  float lon = uv.x;\n"+
"  vec4 sphere_pnt = vec4(cos(lat) * cos(lon), cos(lat) * sin(lon), sin(lat), 1.);\n"+
"  sphere_pnt *= transform;\n"+
//"  float R = length(sphere_pnt);\n"+
"  float finalLat = asin(sphere_pnt.z);\n"+
"  float finalLon = atan(sphere_pnt.y, sphere_pnt.x);\n"+
"  gl_FragColor = texture2D(textureSource, vec2(finalLon, finalLat));\n"+
"}\n"

VRtwglQuadStereoProjection = function() {
  var self = this;
  this.vrtwglQuad = null;
  this.uniforms = {
    resolution:[0,0],
    textureSource:null,
    transform:twgl.m4.identity()
  };

  this.init = function(element){
    this.vrtwglQuad = new VRtwglQuad();
    this.vrtwglQuad.init(element, vs, fs);
    //twgl.m4.rotateZ(this.uniforms.transform, 0, this.uniforms.transform); // yaw
    //var axis = twgl.v3.create(0,1,0);
    //twgl.m4.axisRotate(this.uniforms.transform, axis, Math.PI/2, this.uniforms.transform);
  }

  this.resize = function() {
    self.vrtwglQuad.resize();
  }

  this.render = function() {
    this.uniforms["resolution"] = [self.vrtwglQuad.canvas.clientWidth, self.vrtwglQuad.canvas.clientHeight];
    //twgl.m4.rotateX(this.uniforms.transform, 0.01, this.uniforms.transform);

    self.vrtwglQuad.setUniforms(this.uniforms);
    self.vrtwglQuad.render();
  }

  this.anim = function() {
    self.render();
    requestAnimationFrame(self.anim);
  }

  this.setupProjection = function (textureDescription) {
    var gl = self.vrtwglQuad.glContext;
    var tex = twgl.createTexture(gl, {
      min: gl.LINEAR,
      mag: gl.LINEAR,
      src: textureDescription.textureSource,
      crossOrigin: "", // either this or use twgl.setDefaults
    });

    this.uniforms["textureSource"] = tex;
  }

}

module.exports = VRtwglQuadStereoProjection;
<|endoftext|>