diff options
| author | Jules Laplace <jules@okfoc.us> | 2014-06-03 16:24:10 -0400 |
|---|---|---|
| committer | Jules Laplace <jules@okfoc.us> | 2014-06-03 16:24:28 -0400 |
| commit | 607f69c67a5b4dc72d2754192e3cdf67d0ad11d0 (patch) | |
| tree | 6556e7922c5bedb274bb1650e5dd100643a7895d /client/assets/javascripts/mx | |
| parent | d31259291d807c851de4396921e0c26b6dd8dce2 (diff) | |
partitioning client and serveR
Diffstat (limited to 'client/assets/javascripts/mx')
18 files changed, 2911 insertions, 0 deletions
diff --git a/client/assets/javascripts/mx/extensions/mx.movements.js b/client/assets/javascripts/mx/extensions/mx.movements.js new file mode 100644 index 0000000..074ca9a --- /dev/null +++ b/client/assets/javascripts/mx/extensions/mx.movements.js @@ -0,0 +1,285 @@ + + +MX.Movements = function (cam, viewHeight) { + + var moveForward, + moveLeft, + moveBackward, + moveRight, + moveUp, + moveDown, + turnLeft, + turnRight, + turnUp, + turnDown, + jumping = false, + creeping = false, + locked = false, + gravity = false, + rotationX_min = PI/-2, + rotationX_max = PI/2 + + var v = 12, + vr = Math.PI * 0.012, + jumpV = 23, + vx = vy = vz = 0, + creepFactor = 0.3 + + var DEFAULT_SCALE = scale = 1.0 + + var pos = { x: 0, y: 0, z: 0, rotationX: 0, rotationY: 0 } + + return { + + init: function () { + + document.addEventListener('keydown', function (e) { + // console.log(e.keyCode) + if (locked) return; + switch ( e.keyCode ) { + + case 16: // shift + creeping = true + break + + case 38: // up + case 87: // w + moveForward = true + break + + case 37: // left + case 65: // a + moveLeft = true + break + + case 40: // down + case 83: // s + moveBackward = true + break + + case 39: // right + case 68: // d + moveRight = true + break + + case 81: // q + turnLeft = true + break + + case 69: // e + turnRight = true + break + + case 82: // r + turnUp = true + break + + case 70: // f + turnDown = true + break + + case 32: // space + if (gravity) { + jumping = true + vy = abs(vy) + jumpV * scale + if (e.shiftKey) { + vy *= -1 + } + } + else { + if (e.shiftKey) { + moveDown = true + } + else { + moveUp = true + } + } + break + + case 27: // esc + map.toggle() + break + } + }) + + document.addEventListener('keyup', function (e) { + if (locked) return; + switch ( e.keyCode ) { + + case 16: // shift + creeping = false + break + + case 38: // up + case 87: // w + moveForward = false + break + + case 37: // left + case 65: // a + moveLeft = false + break + + case 40: // down + case 83: // s + moveBackward = false + break + + case 39: // right + case 68: // d + moveRight = false + break + + case 81: // q + turnLeft = false + break + + case 69: // e + turnRight = false + break + + case 82: // r + turnUp = false + break + + case 70: // f + turnDown = false + break + + case 32: // space + moveUp = moveDown = false + break + + case 48: // 0 + cam.rotationX = 0 + cam.rotationY = 0 + cam.x = 0 + cam.y = viewHeight + cam.z = 0 + break + } + }) + + var mouseX, mouseY, dx, dy, rotX, rotY, dragging = false + document.addEventListener('mousedown', function (e) { + if (locked) return; + mouseX = e.pageX + mouseY = e.pageY + rotX = cam.rotationX + rotY = cam.rotationY + dragging = true + }) + + document.addEventListener('mousemove', function (e) { + if (locked || ! dragging || app.dragging) return + var dx = (e.pageX - mouseX) / window.innerWidth * Math.PI/3 + var dy = (e.pageY - mouseY) / window.innerHeight * Math.PI/3 + cam.rotationY = rotY + dx + cam.rotationX = clamp( rotX - dy, rotationX_min, rotationX_max ) + }) + + document.addEventListener('mouseup', function (e) { + app.dragging = dragging = false + }) + + window.addEventListener('blur', reset) + window.addEventListener('focus', reset) + function reset(){ + moveForward = moveLeft = moveBackward = moveRight = moveUp = moveDown = turnLeft = turnRight = jumping = dragging = creeping = false + } + + }, + + update: function () { + + if (locked) return; + + var ry = cam.rotationY + var s = creeping ? scale * creepFactor : scale + var vrrrr = creeping ? vr * creepFactor * 5 : vr + var moving = moveForward || moveBackward || moveRight || moveLeft || moveUp || moveDown || turnLeft || turnRight || turnUp || turnDown + vx = vz = 0 + + pos.x = cam.x + pos.z = cam.z + + if (moving) { + + if (moveForward) { + vx += v * Math.cos(ry + Math.PI / 2) * s + vz += v * Math.sin(ry + Math.PI / 2) * s + } + if (moveBackward) { + vx -= v * Math.cos(ry + Math.PI / 2) * s + vz -= v * Math.sin(ry + Math.PI / 2) * s + } + if (moveLeft) { + vx -= v * Math.cos(ry) * s + vz -= v * Math.sin(ry) * s + } + if (moveRight) { + vx += v * Math.cos(ry) * s + vz += v * Math.sin(ry) * s + } + if (moveUp) { + pos.y += v * scale + } + if (moveDown) { + pos.y -= v * scale + } + + if (turnUp) { + cam.rotationX = clamp( cam.rotationX - vrrrr*s, rotationX_min, rotationX_max) + } + if (turnDown) { + cam.rotationX = clamp( cam.rotationX + vrrrr*s, rotationX_min, rotationX_max) + } + if (turnLeft) { + cam.rotationY += vrrrr*s + } + if (turnRight) { + cam.rotationY -= vrrrr*s + } + + pos.x += vx + pos.z += vz + } + + if (gravity) { + vy -= 1 * scale + + pos.y += vy + + if (vy) { + moving = true + } + if (pos.y <= viewHeight) { + pos.y = viewHeight + vy = 0 + jumping = false + vz = vz || 1 + } + + var ceiling = (Rooms.mover.room ? Rooms.mover.room.height : 5000) + + if (pos.y >= ceiling) { + vy = 0 + pos.y = ceiling + vz = vz || 1 + } + } + + if (moving) { + app.tube("move", pos) + } + }, + + lock: function(){ locked = true }, + unlock: function(){ locked = false }, + scale: function(n){ if (n) scale = n; return scale }, + resetScale: function(n){ scale = DEFAULT_SCALE }, + gravity: function(g){ return typeof g == "boolean" ? gravity = g : gravity }, + velocity: function(n){ v = clamp(n, 1, 50) }, + jumpVelocity: function(n){ jumpV = clamp(n, 1, 50) }, + } +} diff --git a/client/assets/javascripts/mx/extensions/mx.rotationControl.js b/client/assets/javascripts/mx/extensions/mx.rotationControl.js new file mode 100644 index 0000000..9adb627 --- /dev/null +++ b/client/assets/javascripts/mx/extensions/mx.rotationControl.js @@ -0,0 +1,265 @@ +// Usage: +// +// var control = new MX.RotationControl() +// control.init( object{MX.Object3D} [, listener{HTMLElement}] ) +// +// In animation loop: +// +// control.update() +// +// The above code will register handler functions on `listener` +// and will be updating `object`s rotationX and rotationY +// If no `listener` is provided, will default to `object`s el. + +MX.RotationControl = function () { + + var object, + locked = false + + var down = false, + active = false, + lastX, + lastY + + var pointerLockPrefix = + 'pointerLockElement' in document ? '' : + 'mozPointerLockElement' in document ? 'moz' : + 'webkitPointerLockElement' in document ? 'webkit' : null, + hasPointerLock = !(pointerLockPrefix === null) + pointerLockEnabled = false + + var pub = { + + sensitivity : .5, + ease : 10, + drag : true, + + inverseX : false, + inverseY : false, + + disableX : false, + disableY : false, + + rotationX : 0, + rotationY : 0, + + upperBoundX : undefined, + lowerBoundX : undefined, + + upperBoundY : undefined, + lowerBoundY : undefined, + + usePreset: function (name) { + var ops = presets[name] + if (ops) { + if (currentPreset && presets[currentPreset].teardown) { + presets[currentPreset].teardown() + } + for (var op in ops) { + if (op !== 'setup' && op !== 'teardown') { + pub[op] = ops[op] + } + } + if (op.setup) ops.setup() + } + } + } + + var currentPreset + var presets = { + firstPerson: { + drag: false, + ease: 2, + sensitivity: .18, + inverseX: true, + inverseY: true, + upperBoundX: MX.rotationUnit === 'deg' ? 90 : Math.PI / 2, + lowerBoundX: MX.rotationUnit === 'deg' ? -90 : -Math.PI / 2 + }, + skybox: { + sensitivity: .18, + inverseX: true, + inverseY: true, + upperBoundX: MX.rotationUnit === 'deg' ? 90 : Math.PI / 2, + lowerBoundX: MX.rotationUnit === 'deg' ? -90 : -Math.PI / 2 + } + } + + function init (obj, lis) { + if (active) return + + object = obj + pub.rotationX = object.rotationX + pub.rotationY = object.rotationY + + if (lis instanceof HTMLElement) { + listener = lis + } else if (lis instanceof MX.Object3D) { + listener = lis.el + } else { + listener = window.document + } + + listener.addEventListener('mousedown', onDown) + listener.addEventListener('mousemove', onMove) + listener.addEventListener('mouseup', onUp) + listener.addEventListener('touchstart', onDown) + listener.addEventListener('touchmove', onMove) + listener.addEventListener('touchend', onUp) + + active = true + } + + function changeObject (obj) { + object = obj + pub.rotationX = object.rotationX + pub.rotationY = object.rotationY + } + + function changeListener (lis) { + remove() + active = false + init(object, lis) + if (pointerLockEnabled) { + initPointerLock() + } + } + + function remove () { + if (!active) return + listener.removeEventListener('mousedown', onDown) + listener.removeEventListener('mousemove', onMove) + listener.removeEventListener('mouseup', onUp) + listener.removeEventListener('touchstart', onDown) + listener.removeEventListener('touchmove', onMove) + listener.removeEventListener('touchend', onUp) + + if (hasPointerLock) { + document.removeEventListener(pointerLockPrefix + 'pointerlockchange', onPointerLockChange) + document.removeEventListener('mousemove', onPointerLockMove) + document.body[pointerLockPrefix + (pointerLockPrefix ? 'E' : 'e') + 'xitPointerLock']() + } + active = false + } + + function onDown (e) { + e = normalizeEvent(e) + if (!e) return + down = true + lastX = e.pageX + lastY = e.pageY + } + + function onMove (e) { + if (e.type = 'touchmove') { + e.preventDefault() + } + if (pub.drag && !down) return + e = normalizeEvent(e) + if (!e) return + lastX = lastX || e.pageX + lastY = lastY || e.pageY + var dx = e.pageX - lastX, + dy = e.pageY - lastY + lastX = e.pageX + lastY = e.pageY + updateTarget(dx, dy) + } + + function onUp () { + down = false + } + + function initPointerLock () { + + if (pointerLockEnabled) return + + document.addEventListener(pointerLockPrefix + 'pointerlockchange', onPointerLockChange) + document.addEventListener('mousemove', onPointerLockMove) + + document.body[pointerLockPrefix + (pointerLockPrefix ? 'R' : 'r') + 'equestPointerLock']() + } + + function onPointerLockChange () { + var el = document.body + if (document[pointerLockPrefix + (pointerLockPrefix ? 'P' : 'p') + 'ointerLockElement'] === el) { + pointerLockEnabled = true + } else { + pointerLockEnabled = false + } + } + + function onPointerLockMove (e) { + if (!pointerLockEnabled) return + var dx = e[pointerLockPrefix + (pointerLockPrefix ? 'M' : 'm') + 'ovementX'], + dy = e[pointerLockPrefix + (pointerLockPrefix ? 'M' : 'm') + 'ovementY'] + updateTarget(dx, dy) + } + + function normalizeEvent (e) { + if (e.touches) { + return e.touches.length > 1 ? false : e.touches[0] + } else { + return e + } + } + + function updateTarget (dx, dy) { + if (pub.inverseX) dx = -dx + if (pub.inverseY) dy = -dy + if (MX.rotationUnit !== 'deg') { + dx = MX.toRad(dx) + dy = MX.toRad(dy) + } + + if (!pub.disableX) { + pub.rotationX -= dy * pub.sensitivity + if (pub.upperBoundX) pub.rotationX = Math.min(pub.rotationX, pub.upperBoundX) + if (pub.lowerBoundX) pub.rotationX = Math.max(pub.rotationX, pub.lowerBoundX) + } + + if (!pub.disableY) { + pub.rotationY += dx * pub.sensitivity + if (pub.upperBoundY) pub.rotationY = Math.min(pub.rotationY, pub.upperBoundY) + if (pub.lowerBoundY) pub.rotationY = Math.max(pub.rotationY, pub.lowerBoundY) + } + } + + function update () { + if (!object || locked) return + var dx = pub.rotationX - object.rotationX, + dy = pub.rotationY - object.rotationY + if (Math.abs(dx) < 0.0001) { + object.rotationX = pub.rotationX + } else { + object.rotationX += dx / pub.ease + } + if (Math.abs(dy) < 0.0001) { + object.rotationY = pub.rotationY + } else { + object.rotationY += dy / pub.ease + } + } + + function lock () { + locked = true + } + + function unlock () { + pub.rotationX = object.rotationX + pub.rotationY = object.rotationY + locked = false + } + + pub.init = init + pub.remove = remove + pub.update = update + pub.lock = lock + pub.unlock = unlock + pub.initPointerLock = initPointerLock + pub.changeObject = changeObject + pub.changeListener = changeListener + + return pub + +}
\ No newline at end of file diff --git a/client/assets/javascripts/mx/extensions/mx.scene.js b/client/assets/javascripts/mx/extensions/mx.scene.js new file mode 100644 index 0000000..8f11fb0 --- /dev/null +++ b/client/assets/javascripts/mx/extensions/mx.scene.js @@ -0,0 +1,165 @@ +// NOTE +// +// This is not a fully functional 3d scene as you might expect. +// The camera can only do pitch (rotationX) and yaw (rotationY), but no roll (rotationZ) +// because I haven't implemented alternative euler orders or quaternions. +// +// For serious 3D scenes with more functionalities you should use +// THREE.js with CSS3D Renderer. + +MX.Camera = MX.Object3D.extend({ + + init: function(){ + this.el = null + this.type = "Camera" + }, + + move: function(s){ + for (var i in s) { + this[i] = s[i] + } + }, + + toString: function(){ + var params = "x y z rotationX rotationY".split(" ") + return this.__toString(params, "scene.camera.move") + }, + + getCameraEuler: function (target) { + var dx = target.x - this.x, + dy = target.y - this.y, + dz = target.z - this.z + r = {} + r.y = Math.atan2(-dx, dz) + r.x = Math.atan2(-dy, Math.sqrt(dx*dx + dz*dz)) + r.z = 0 + if (MX.rotationUnit === 'deg') { + r.x = MX.toDeg(r.x) + r.y = MX.toDeg(r.y) + } + return r + } + +}) + +MX.Scene = (function () { + + var add = MX.Object3D.prototype.add, + remove = MX.Object3D.prototype.remove + + function Scene () { + + this.el = document.createElement('div') + this.el.classList.add('mx-scene') + + var s = this.el.style + + s[MX.transformProp] = 'preserve-3d' + + s.webkitPerspectiveOrigin = '50% 50%' + s.mozPerspectiveOrigin = '50% 50%' + s.perspectiveOrigin = '50% 50%' + + s.webkitUserSelect = 'none' + s.mozUserSelect = 'none' + s.userSelect = 'none' + + s.overflow = 'hidden' + + this.inner = new MX.Object3D().addTo(this.el) + this.inner.el.style.width = '0' + this.inner.el.style.height = '0' + + var self = this + var width, height, perspective + + Object.defineProperty(this, 'width', { + get: function () { + return width + }, + set: function (val) { + width = val + self.el.style.width = val + 'px' + } + }) + + Object.defineProperty(this, 'height', { + get: function () { + return height + }, + set: function (val) { + height = val + self.el.style.height = val + 'px' + } + }) + + Object.defineProperty(this, 'perspective', { + get: function () { + return perspective + }, + set: function (val) { + perspective = val + self.el.style[MX.perspectiveProp] = val + 'px' + self.inner.z = -val - self.camera.z + self.inner.rotationOrigin.z = -val + } + }) + + var cam = this.camera = new MX.Camera() + + this.inner.rotationOrigin = { x:0, y:0, z:0 } + + this.perspective = 0 + } + + Scene.prototype = { + + constructor: Scene, + + add: function () { + add.apply(this.inner, arguments) + return this + }, + + remove: function () { + remove.apply(this.inner, arguments) + return this + }, + + addTo: function (target) { + if (typeof target === 'string') { + target = document.querySelector(target) + } + if (target instanceof HTMLElement && target.appendChild) { + target.appendChild(this.el) + } else { + console.warn('You can only add a Scene to an HTML element.') + } + return this + }, + + update: function () { + // update inner based on camera + + var i = this.inner, + c = this.camera + + c.update() + + i.z = -this.perspective - c.z + i.x = -c.x + i.y = -c.y + + i.rotationX = -c.rotationX + i.rotationY = -c.rotationY + //i.rotationZ = -c.rotationZ + + i.update() + return this + }, + + } + + return Scene + +})()
\ No newline at end of file diff --git a/client/assets/javascripts/mx/extensions/mx.scrubber.js b/client/assets/javascripts/mx/extensions/mx.scrubber.js new file mode 100644 index 0000000..54612f2 --- /dev/null +++ b/client/assets/javascripts/mx/extensions/mx.scrubber.js @@ -0,0 +1,191 @@ +/* + Use the scrollwheel to tween between different points and orientations + + scrubber = new MX.Scrubber(cam, [ + { + position: [0, viewHeight, -1000], + rotation: [0, 0] + }, + { + position: [0, 1000, 1000], + rotation: [0, Math.PI] + }, + { + position: [0, viewHeight, -1000], + rotation: [0, 2*Math.PI] + }, + { + position: [0, viewHeight, -2000], + rotation: [0, 0] + } + ]) + + // in your animate function: + scrubber.update() + +*/ + +MX.Scrubber = function (obj, points) { + + obj = obj || {} + points = points || {} + + var reversible = true, loop = false; + + var total = points.length * 100, + distance = 0 + destination = 0, + last_index = -1, + last_name = null, + locked = false, + point_count = points.length + (loop+0) + + var avg_speed = scroll_avg_speed = 5, + click_avg_speed = 20, + webkit_ratio = 0.02 + + if (points[0].position) { + points.forEach(function(p){ + p.x = p.position[0] + p.y = p.position[1] + p.z = p.position[2] + p.rotationX = p.rotation[0] + p.rotationY = p.rotation[1] + }) + } + + document.addEventListener('touchstart', next, false); + document.addEventListener('mousedown', next, false); + document.addEventListener('mousewheel', onDocumentMouseWheel, false); + document.addEventListener('DOMMouseScroll', onDocumentMouseWheel, false); + function onDocumentMouseWheel (e) { + + if (locked) return + + var delta = 0; + + // WebKit + if ( event.wheelDeltaY ) { + delta -= event.wheelDeltaY * webkit_ratio + } + // Opera / Explorer 9 + else if ( event.wheelDelta ) { + delta -= event.wheelDelta * webkit_ratio + } + // Firefox + else if ( event.detail ) { + delta += event.detail * 2 + } + if (! reversible && delta < 0) return; + + if (destination < total-100 || delta < 0) { + e.preventDefault() + } + else { + return + } + + destination += delta + + avg_speed = scroll_avg_speed + } + + function add_point(point){ + if (point.type == "Camera") { + point = { + position: [ point.x, point.y, point.z ], + rotation: [ point.rotationX, point.rotationY ], + callback: noop + } + } + points.push(point) + total = points.length * 100 + } + + function reset(){ + distance = destination = 0 + last_index = -1 + last_name = null + } + + function next(){ + destination = ~~(destination/100) * 100 + destination += 100 + avg_speed = click_avg_speed + } + + function update(){ + if (locked) return + + if (destination > total-100) destination = total-100 + + distance = avg(distance, destination, avg_speed) + var ratio = distance / total + + if (! loop) { + if (ratio < 0) { + destination = 0 + ratio = 0 + } + else if (ratio > 1) { + destination = total + ratio = 1 + } + } + + var diff = ratio * point_count + var step = (distance % 100) / 100 + var src = ~~clamp(diff, 0, point_count-1) + var halfway = ~~clamp(diff + 0.5, 0, point_count-1) + var dest = ~~clamp(diff + 1, 0, point_count-1) + + if (halfway != last_index) { + last_index = halfway + if (points[last_index].name != last_name) { + last_name = points[last_index].name + } + $("#info .active").removeClass("active") + $("#info div[data-name='" + last_name + "']").addClass("active") + points[halfway].callback && points[halfway].callback() + } + + var ry0 = points[src].rotationY + var ry1 = points[dest].rotationY + if (abs(ry0 - ry1) == TWO_PI) { + ry0 = ry1 + } + + obj.x = lerp(step, points[src].x, points[dest].x) + obj.y = lerp(step, points[src].y, points[dest].y) + obj.z = lerp(step, points[src].z, points[dest].z) + obj.rotationX = lerp(step, points[src].rotationX, points[dest].rotationX) + obj.rotationY = lerp(step, ry0, ry1) + if (obj.rotationY > PI) { obj.rotationY -= TWO_PI } + } + + var scrubber = { + init: function(){ + app && app.movements && app.movements.lock() + }, + lock: function(){ + app && app.movements && app.movements.unlock() + locked = true + }, + unlock: function(){ + app && app.movements && app.movements.lock() + locked = false + }, + step: function(n){ + distance = destination = n * 100 + }, + add_point: add_point, + reset: reset, + next: next, + update: update, + + obj: obj, + points: points + } + + return scrubber; +} diff --git a/client/assets/javascripts/mx/mx.js b/client/assets/javascripts/mx/mx.js new file mode 100644 index 0000000..df9abe7 --- /dev/null +++ b/client/assets/javascripts/mx/mx.js @@ -0,0 +1,583 @@ +/** + * Copyright (C) 2013 by Evan You + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +var MX = MX || (function (undefined) { + + var MX = { + version: '0.1.0', + prefix: undefined, + rotationUnit: 'rad' + } + + var floatPrecision = 5 + + // ======================================================================== + // Setup & Compatibility + // ======================================================================== + + var transformProp, + transitionProp, + transformOriginProp, + transformStyleProp, + perspectiveProp, + transitionEndEvent + + var positionAtCenter = true, // whether to auto center objects + centeringCSS // styles to inject for center positioning + + document.addEventListener('DOMContentLoaded', setup) + + function setup () { + + // sniff prefix + + var s = document.body.style + + MX.prefix = + 'webkitTransform' in s ? 'webkit' : + 'mozTransform' in s ? 'moz' : + 'msTransform' in s ? 'ms' : '' + + transformProp = MX.transformProp = addPrefix('transform') + transitionProp = MX.transitionProp = addPrefix('transition') + transformOriginProp = MX.transformOriginProp = addPrefix('transformOrigin') + transformStyleProp = MX.transformStyleProp = addPrefix('transformStyle') + perspectiveProp = MX.perspectiveProp = addPrefix('perspective') + transitionEndEvent = MX.transitionEndEvent = MX.prefix === 'webkit' ? 'webkitTransitionEnd' : 'transitionend' + + // shiv rAF + + var vendors = ['webkit', 'moz', 'ms'] + for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { + window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'] + window.cancelAnimationFrame = + window[vendors[x]+'CancelAnimationFrame'] || + window[vendors[x]+'CancelRequestAnimationFrame'] + } + + // inject centering css + + centeringCSS = document.createElement('style') + centeringCSS.type = 'text/css' + centeringCSS.innerHTML = + '.mx-object3d {' + + 'position: absolute;' + + 'top: 50%;' + + 'left: 50%;}' + injectCenteringCSS() + + window.scrollTo(0,0) + } + + function injectCenteringCSS () { + document.head.appendChild(centeringCSS) + } + + function removeCenteringCSS () { + document.head.removeChild(centeringCSS) + } + + // ======================================================================== + // Utils + // ======================================================================== + + function toDeg (rad) { + return rad / Math.PI * 180 + } + + function toRad (deg) { + return deg / 180 * Math.PI + } + + function buildRotationTranslation (obj) { + + // used when rotationOrigin is set + + var origin = obj.rotationOrigin + if (!origin) { + return + } else { + var dx = origin.x - obj.x, + dy = -(origin.y - obj.y), + dz = -(origin.z - obj.z) + return { + before: 'translate3d(' + dx.toFixed(floatPrecision) +'px,' + dy.toFixed(floatPrecision) + 'px,' + dz.toFixed(floatPrecision) + 'px) ', + after: 'translate3d(' + (-dx).toFixed(floatPrecision) + 'px,' + (-dy).toFixed(floatPrecision) + 'px,' + (-dz).toFixed(floatPrecision) + 'px) ' + } + } + } + + function addPrefix (string) { + if (MX.prefix) { + string = MX.prefix + string.charAt(0).toUpperCase() + string.slice(1) + } + return string + } + + // ======================================================================== + // Base Object3D + // ======================================================================== + + function Object3D (el) { + + this.setupDomElement(el) + this.setCSSTransformStyle('preserve-3d') + this.el.classList.add('mx-object3d') + + this.parent = undefined + this.children = [] + this.updateChildren = true + + this.inverseLookAt = false + + this.persisted = true + + this.reset() + +// this.quaternion = new MX.Quaternion () +// this.quaternion._euler = this + + var width, height, + self = this + + Object.defineProperty(this, 'width', { + get: function () { + return width + || parseInt(self.el.style.width, 10) + || 0 + }, + set: function (val) { + width = val + this.el.style.width = width + 'px' + } + }) + + Object.defineProperty(this, 'height', { + get: function () { + return height + || parseInt(self.el.style.height, 10) + || 0 + }, + set: function (val) { + height = val + this.el.style.height = height + 'px' + } + }) + } + + Object3D.prototype = { + + constructor: Object3D, + + reset: function () { + this.x = this.__x = 0 + this.y = this.__y = 0 + this.z = this.__z = 0 + this.rotationX = this.__rotationX = 0 + this.rotationY = this.__rotationY = 0 + this.rotationZ = this.__rotationZ = 0 + this.scaleX = this.__scaleX = 1 + this.scaleY = this.__scaleY = 1 + this.scaleZ = this.__scaleZ = 1 + this.scale = this.__scale = 1 + this.perspective = this.__perspective = 0 + this.rotationOrigin = undefined + this.followTarget = undefined +// this.quaternion = new MX.Quaternion() + this.dirty = true + this.update() + }, + + setupDomElement: function (el) { + this.el = undefined + if (el instanceof HTMLElement) { + this.el = el + } else if (typeof el === 'string') { + var tag = el.match(/^[^.#\s]*/)[1], + id = el.match(/#[^.#\s]*/), + classes = el.match(/\.[^.#\s]*/g) + this.el = document.createElement(tag || 'div') + if (id) { + this.el.id = id[0].slice(1) + } + if (classes) { + var i = classes.length + while (i--) { + this.el.classList.add(classes[i].slice(1)) + } + } + } else { + this.el = document.createElement('div') + } + }, + + update: function () { + + if (this.updateChildren) { + var i = this.children.length + while (i--) { + this.children[i].update() + } + } + + if (this.followTarget) { + this.lookAt(this.followTarget, false) + } + + if (this.scaleX !== this.__scaleX || + this.scaleY !== this.__scaleY || + this.scaleZ !== this.__scaleZ) { + this.__scaleX = this.scaleX + this.__scaleY = this.scaleY + this.__scaleZ = this.scaleZ + this.dirty = true + } + + if (this.scale !== this.__scale) { + this.scaleX = + this.scaleY = + this.scaleZ = + this.__scaleX = + this.__scaleY = + this.__scaleZ = + this.__scale = + this.scale + this.dirty = true + } + + if (this.rotationX !== this.__rotationX || + this.rotationY !== this.__rotationY || + this.rotationZ !== this.__rotationZ) { + this.__rotationX = this.rotationX + this.__rotationY = this.rotationY + this.__rotationZ = this.rotationZ + this.dirty = true + } + + if (this.x !== this.__x || + this.y !== this.__y || + this.z !== this.__z) { + this.__x = this.x + this.__y = this.y + this.__z = this.z + this.dirty = true + } + + if (this.perspective !== this.__perspective) { + this.__perspective = this.perspective + this.dirty = true + } + + if (this.dirty && this.el) { + + var rotationTranslation = buildRotationTranslation(this), + rotation = 'rotateX(' + this.rotationX.toFixed(floatPrecision) + MX.rotationUnit + ') ' + + 'rotateY(' + this.rotationY.toFixed(floatPrecision) + MX.rotationUnit + ') ' + + 'rotateZ(' + this.rotationZ.toFixed(floatPrecision) + MX.rotationUnit + ') ' + + var transformString = + (MX.positionAtCenter ? 'translate3d(-50%, -50%, 0) ' : '') + + (this.perspective ? 'perspective(' + this.perspective + 'px) ' : '') + + 'translate3d(' + + this.x.toFixed(floatPrecision || 0) + 'px,' + + (-this.y).toFixed(floatPrecision) + 'px,' + + (-this.z).toFixed(floatPrecision) + 'px) ' + + 'scale3d(' + + this.scaleX.toFixed(floatPrecision) + ',' + + this.scaleY.toFixed(floatPrecision) + ',' + + this.scaleZ.toFixed(floatPrecision) + ') ' + + if (rotationTranslation) { + transformString += rotationTranslation.before + + rotation + + rotationTranslation.after + + } else { + transformString += rotation + } + + this.el.style[transformProp] = transformString + this.dirty = false + } + + return this + + }, + + // taken from three.js + setFromQuaternion: function ( q, order, update ) { + // q is assumed to be normalized + + // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m + + var sqx = q.x * q.x; + var sqy = q.y * q.y; + var sqz = q.z * q.z; + var sqw = q.w * q.w; + + this.rotationX = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) ); + this.rotationY = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ), -1, 1 ) ); + this.rotationZ = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) ); + }, + + lookAt: function (target, update) { + var r = this.getLookAtEuler(target) + this.setRotation(r) + if (update !== false) this.update() + return this + }, + + getLookAtEuler: function (target) { + // euler order XYZ + var r = {}, + dx = target.x - this.x, + dy = target.y - this.y, + dz = target.z - this.z + if (this.inverseLookAt) { + dx = -dx + dy = -dy + dz = -dz + } + if (dz === 0) dz = 0.001 + r.x = -Math.atan2(dy, dz) + var flip = dz > 0 ? 1 : -1 + r.y = flip * Math.atan2(dx * Math.cos(r.x), dz * -flip) + r.z = Math.atan2(Math.cos(r.x), Math.sin(r.x) * Math.sin(r.y)) - Math.PI / 2 + if (MX.rotationUnit === 'deg') { + r.x = toDeg(r.x) + r.y = toDeg(r.y) + r.z = toDeg(r.z) + } + return r + }, + + add: function () { + if (!this.el) return + var parent = this + Array.prototype.forEach.call(arguments, function (child) { + if (!child instanceof Object3D) return + parent.el.appendChild(child.el) + if (!parent.children) parent.children = [] + parent.children.push(child) + child.parent = parent + }) + return this + }, + + remove: function () { + var parent = this + Array.prototype.forEach.call(arguments, function (child) { + var index = parent.children.indexOf(child) + if (index !== -1) { + parent.children.splice(index, 1) + parent.el.removeChild(child.el) + child.parent = undefined + } + }) + return this + }, + + addTo: function (target) { + if (typeof target === 'string') { + target = document.querySelector(target) + } + if (target instanceof HTMLElement && target.appendChild) { + target.appendChild(this.el) + } else if (target instanceof Object3D || target instanceof Scene) { + target.add(this) + } + return this + }, + + removeElement: function () { + if (this.el.parentNode) { + this.el.parentNode.removeChild(this.el) + } + }, + + setPosition: function (tar) { + this.x = (tar.x || tar.x === 0) ? tar.x : this.x + this.y = (tar.y || tar.y === 0) ? tar.y : this.y + this.z = (tar.z || tar.z === 0) ? tar.z : this.z + }, + + setRotation: function (tar) { + this.rotationX = (tar.x || tar.x === 0) ? tar.x : this.rotationX + this.rotationY = (tar.y || tar.y === 0) ? tar.y : this.rotationY + this.rotationZ = (tar.z || tar.z === 0) ? tar.z : this.rotationZ + }, + + setScale: function (tar) { + this.scaleX = (tar.x || tar.x === 0) ? tar.x : this.scaleX + this.scaleY = (tar.y || tar.y === 0) ? tar.y : this.scaleY + this.scaleZ = (tar.z || tar.z === 0) ? tar.z : this.scaleZ + }, + + setCSSTransformOrigin: function (origin) { + this.el && (this.el.style[transformOriginProp] = origin) + return this + }, + + setCSSTransformStyle: function (style) { + this.el && (this.el.style[transformStyleProp] = style) + return this + }, + + setCSSTransition: function (trans) { + this.el && (this.el.style[transitionProp] = trans) + return this + }, + + setCSSPerspective: function (pers) { + this.el && (this.el.style[perspectiveProp] = pers) + return this + }, + + onTransitionEnd: function (callback) { + this.cancelTransitionEnd() + var el = this.el + el.addEventListener(transitionEndEvent, onEnd) + function onEnd () { + el.removeEventListener(transitionEndEvent, onEnd) + callback() + } + }, + + cancelTransitionEnd: function () { + this.el.removeEventListener(transitionEndEvent) + }, + + toString: function(params){ + params = params || "id width height depth x y z rotationX rotationY rotationZ scale".split(" ") + return this.__toString(params) + }, + + __toString: function(params, func){ + this.id = this.id || guid() + var list = [], + obj = {}, + type = this.type || "Object3d", + name = type.toLowerCase(), + val, + param + for (var i in params) { + param = params[i] + val = this[param] + if (val === 0 && ! func) continue; + if (typeof val == "number") { + if (param.indexOf("rotation") != -1) { + obj[param] = Number(val.toFixed(3)) + } + else { + obj[param] = ~~val + } + } + else { + obj[param] = val + } + } + + return (func || "var " + name + " = new MX." + type ) + "(" + + JSON.stringify(obj, undefined, 2) + + ")\n" + (func ? "" : "scene.add(" + name + ")") + }, + + contains: function(x,y,z){ + var containsX = false, + containsY = false, + containsZ = false + + if (x === null) { + containsX = true + } + else { + containsX = abs(this.x - x) <= this.width/2 + } + + if (y === null) { + containsY = true + } + else { + containsY = abs(this.y - y) <= this.height/2 + } + + if (z === null) { + containsZ = true + } + else { + containsZ = abs(this.z - z) <= this.depth/2 + } + + return (containsX && containsY && containsZ) + } + + } + + // ======================================================================== + // Inheritance + // ======================================================================== + + Object3D.extend = extend.bind(Object3D) + + function extend (props) { + var Super = this + var ExtendedObject3D = function () { + Super.call(this) + props.init && props.init.apply(this, arguments) + } + ExtendedObject3D.prototype = Object.create(Super.prototype) + for (var prop in props) { + if (props.hasOwnProperty(prop) && prop !== 'init') { + ExtendedObject3D.prototype[prop] = props[prop] + } + } + ExtendedObject3D.extend = extend.bind(ExtendedObject3D) + return ExtendedObject3D + } + + // ======================================================================== + // Expose API + // ======================================================================== + + MX.Object3D = Object3D + MX.toRad = toRad + MX.toDeg = toDeg + + // center positioning getter setter + Object.defineProperty(MX, 'positionAtCenter', { + get: function () { + return positionAtCenter + }, + set: function (val) { + if (typeof val !== 'boolean') return + positionAtCenter = val + if (positionAtCenter) { + injectCenteringCSS() + } else { + removeCenteringCSS() + } + } + }) + + return MX + +})()
\ No newline at end of file diff --git a/client/assets/javascripts/mx/mx.min.js b/client/assets/javascripts/mx/mx.min.js new file mode 100644 index 0000000..b0f0cdd --- /dev/null +++ b/client/assets/javascripts/mx/mx.min.js @@ -0,0 +1 @@ +var MX=MX||function(undefined){var MX={prefix:undefined,rotationUnit:"rad"};var floatPrecision=5;var transformProp,transitionProp,transformOriginProp,transformStyleProp,perspectiveProp;var positionAtCenter=true,centeringCSS;document.addEventListener("DOMContentLoaded",setup);function setup(){var s=document.body.style;MX.prefix="webkitTransform"in s?"webkit":"mozTransform"in s?"moz":"msTransform"in s?"ms":"";transformProp=MX.transformProp=addPrefix("transform");transitionProp=MX.transitionProp=addPrefix("transition");transformOriginProp=MX.transformOriginProp=addPrefix("transformOrigin");transformStyleProp=MX.transformStyleProp=addPrefix("transformStyle");perspectiveProp=MX.perspectiveProp=addPrefix("perspective");var vendors=["webkit","moz","ms"];for(var x=0;x<vendors.length&&!window.requestAnimationFrame;++x){window.requestAnimationFrame=window[vendors[x]+"RequestAnimationFrame"];window.cancelAnimationFrame=window[vendors[x]+"CancelAnimationFrame"]||window[vendors[x]+"CancelRequestAnimationFrame"]}centeringCSS=document.createElement("style");centeringCSS.type="text/css";centeringCSS.innerHTML=".mx-object3d {"+"position: absolute;"+"top: 50%;"+"left: 50%;}";injectCenteringCSS()}function injectCenteringCSS(){document.head.appendChild(centeringCSS)}function removeCenteringCSS(){document.head.removeChild(centeringCSS)}function toDeg(rad){return rad/Math.PI*180}function toRad(deg){return deg/180*Math.PI}function buildRotationTranslation(obj){var origin=obj.rotationOrigin;if(!origin){return}else{var dx=origin.x-obj.x,dy=-(origin.y-obj.y),dz=-(origin.z-obj.z);return{before:"translate3d("+dx+"px,"+dy+"px,"+dz+"px) ",after:"translate3d("+-dx+"px,"+-dy+"px,"+-dz+"px) "}}}function addPrefix(string){if(MX.prefix){string=MX.prefix+string.charAt(0).toUpperCase()+string.slice(1)}return string}function Object3D(el){this.setupDomElement(el);this.setCSSTransformStyle("preserve-3d");this.el.classList.add("mx-object3d");this.parent=undefined;this.children=[];this.updateChildren=true;this.inverseLookAt=false;this.reset();var width,height,self=this;Object.defineProperty(this,"width",{get:function(){return width||parseInt(self.el.style.width,10)||0},set:function(val){width=val;this.el.style.width=width+"px"}});Object.defineProperty(this,"height",{get:function(){return height||parseInt(self.el.style.height,10)||0},set:function(val){height=val;this.el.style.height=height+"px"}})}Object3D.prototype={constructor:Object3D,reset:function(){this.x=this.__x=0;this.y=this.__y=0;this.z=this.__z=0;this.rotationX=this.__rotationX=0;this.rotationY=this.__rotationY=0;this.rotationZ=this.__rotationZ=0;this.scaleX=this.__scaleX=1;this.scaleY=this.__scaleY=1;this.scaleZ=this.__scaleZ=1;this.scale=this.__scale=1;this.rotationOrigin=undefined;this.followTarget=undefined;this.dirty=true;this.update()},setupDomElement:function(el){this.el=undefined;if(el instanceof HTMLElement){this.el=el}else if(typeof el==="string"){var tag=el.match(/^[^.#\s]*/)[1],id=el.match(/#[^.#\s]*/),classes=el.match(/\.[^.#\s]*/g);this.el=document.createElement(tag||"div");if(id){this.el.id=id[0].slice(1)}if(classes){var i=classes.length;while(i--){this.el.classList.add(classes[i].slice(1))}}}else{this.el=document.createElement("div")}},update:function(){if(this.updateChildren){var i=this.children.length;while(i--){this.children[i].update()}}if(this.followTarget){this.lookAt(this.followTarget,false)}if(this.scaleX!==this.__scaleX||this.scaleY!==this.__scaleY||this.scaleZ!==this.__scaleZ){this.__scaleX=this.scaleX;this.__scaleY=this.scaleY;this.__scaleZ=this.scaleZ;this.dirty=true}if(this.scale!==this.__scale){this.scaleX=this.scaleY=this.scaleZ=this.__scaleX=this.__scaleY=this.__scaleZ=this.__scale=this.scale;this.dirty=true}if(this.rotationX!==this.__rotationX||this.rotationY!==this.__rotationY||this.rotationZ!==this.__rotationZ){this.__rotationX=this.rotationX;this.__rotationY=this.rotationY;this.__rotationZ=this.rotationZ;this.dirty=true}if(this.x!==this.__x||this.y!==this.__y||this.z!==this.__z){this.__x=this.x;this.__y=this.y;this.__z=this.z;this.dirty=true}if(this.dirty&&this.el){var rotationTranslation=buildRotationTranslation(this),rotation="rotateX("+this.rotationX.toFixed(floatPrecision)+MX.rotationUnit+") "+"rotateY("+this.rotationY.toFixed(floatPrecision)+MX.rotationUnit+") "+"rotateZ("+this.rotationZ.toFixed(floatPrecision)+MX.rotationUnit+") ";var transformString=(MX.positionAtCenter?"translate3d(-50%, -50%, 0) ":"")+"translate3d("+this.x.toFixed(floatPrecision)+"px,"+(-this.y).toFixed(floatPrecision)+"px,"+(-this.z).toFixed(floatPrecision)+"px) "+"scale3d("+this.scaleX.toFixed(floatPrecision)+","+this.scaleY.toFixed(floatPrecision)+","+this.scaleZ.toFixed(floatPrecision)+") ";if(rotationTranslation){transformString+=rotationTranslation.before+rotation+rotationTranslation.after}else{transformString+=rotation}this.el.style[transformProp]=transformString;this.dirty=false}return this},lookAt:function(target,update){var r=this.getLookAtEuler(target);this.setRotation(r);if(update!==false)this.update();return this},getLookAtEuler:function(target){var r={},dx=target.x-this.x,dy=target.y-this.y,dz=target.z-this.z;if(this.inverseLookAt){dx=-dx;dy=-dy;dz=-dz}if(dz===0)dz=.001;r.x=-Math.atan2(dy,dz);var flip=dz>0?1:-1;r.y=flip*Math.atan2(dx*Math.cos(r.x),dz*-flip);r.z=Math.atan2(Math.cos(r.x),Math.sin(r.x)*Math.sin(r.y))-Math.PI/2;if(MX.rotationUnit==="deg"){r.x=toDeg(r.x);r.y=toDeg(r.y);r.z=toDeg(r.z)}return r},add:function(){if(!this.el)return;var parent=this;Array.prototype.forEach.call(arguments,function(child){if(!child instanceof Object3D)return;parent.el.appendChild(child.el);if(!parent.children)parent.children=[];parent.children.push(child);child.parent=parent});return this},remove:function(){var parent=this;Array.prototype.forEach.call(arguments,function(child){var index=parent.children.indexOf(child);if(index!==-1){parent.children.splice(index,1);child.parent=undefined}});return this},addTo:function(target){if(typeof target==="string"){target=document.querySelector(target)}if(target instanceof HTMLElement&&target.appendChild){target.appendChild(this.el)}else if(target instanceof Object3D||target instanceof Scene){target.add(this)}return this},removeElement:function(){if(this.el.parentNode){this.el.parentNode.removeChild(this.el)}},setPosition:function(tar){this.x=tar.x||tar.x===0?tar.x:this.x;this.y=tar.y||tar.y===0?tar.y:this.y;this.z=tar.z||tar.z===0?tar.z:this.z},setRotation:function(tar){this.rotationX=tar.x||tar.x===0?tar.x:this.rotationX;this.rotationY=tar.y||tar.y===0?tar.y:this.rotationY;this.rotationZ=tar.z||tar.z===0?tar.z:this.rotationZ},setScale:function(tar){this.scaleX=tar.x||tar.x===0?tar.x:this.scaleX;this.scaleY=tar.y||tar.y===0?tar.y:this.scaleY;this.scaleZ=tar.z||tar.z===0?tar.z:this.scaleZ},setCSSTransformOrigin:function(origin){this.el&&(this.el.style[transformOriginProp]=addPrefix(origin));return this},setCSSTransformStyle:function(style){this.el&&(this.el.style[transformStyleProp]=addPrefix(style));return this},setCSSTransition:function(trans){this.el&&(this.el.style[transitionProp]=addPrefix(trans));return this},setCSSPerspective:function(pers){this.el&&(this.el.style[perspectiveProp]=addPrefix(pers));return this}};Object3D.extend=extend.bind(Object3D);function extend(props){var Super=this;var ExtendedObject3D=function(){Super.call(this);props.init&&props.init.apply(this,arguments)};ExtendedObject3D.prototype=Object.create(Super.prototype);for(var prop in props){if(props.hasOwnProperty(prop)&&prop!=="init"){ExtendedObject3D.prototype[prop]=props[prop]}}ExtendedObject3D.extend=extend.bind(ExtendedObject3D);return ExtendedObject3D}MX.Object3D=Object3D;MX.toRad=toRad;MX.toDeg=toDeg;Object.defineProperty(MX,"positionAtCenter",{get:function(){return positionAtCenter},set:function(val){if(typeof val!=="boolean")return;positionAtCenter=val;if(positionAtCenter){injectCenteringCSS()}else{removeCenteringCSS()}}});return MX}();
\ No newline at end of file diff --git a/client/assets/javascripts/mx/mx.minimap.js b/client/assets/javascripts/mx/mx.minimap.js new file mode 100644 index 0000000..252305c --- /dev/null +++ b/client/assets/javascripts/mx/mx.minimap.js @@ -0,0 +1,211 @@ +MX.Minimap = function () { + var canvas = document.createElement("canvas") + var ctx = canvas.getContext("2d") + var w = canvas.width = 200 + var h = canvas.height = 200 + + var gridSpace; + var zoom = 2.7 + + var gridStroke = '#ddd' + var boxFill = '#fff' + var boxStroke = '#000' + var playerColor = '#888' + + var xmin, xmax, ymin, ymax, xpos, ypos, scale, side; + + this.update = function(){ + this.draw() + } + + this.bounds = function(){ + gridSpace = Math.pow(10, ~~(zoom-0.5)+0.5) + side = Math.pow(10, zoom+1) + scale = w / side + xpos = -cam.x + ypos = cam.z + + xmin = side/-2 - xpos + xmax = side/2 - xpos + ymin = side/-2 - ypos + ymax = side/2 - ypos + } + + this.draw = function(){ + ctx.clearRect(0,0,w,h) + + ctx.fillStyle = "#fff" + ctx.fillRect(0,0,w,h) + this.bounds() + this.grid() + this.boxes() + this.player() + } + + this.grid = function(){ + ctx.strokeStyle = gridStroke + ctx.lineWidth = 1 + ctx.fillStyle = "transparent" + + var xmod = xmin-(xmin % gridSpace) + var ymod = ymin-(ymin % gridSpace) + + for (var x = xmin; x < xmax+gridSpace; x += gridSpace) { + var xline = (x-xmod) * scale + line(xline, 0, xline, h) + } + for (var y = ymin; y < ymax+gridSpace; y += gridSpace) { + var yline = (y-ymod) * scale + line(0, yline, w, yline) + } + + function line(x0,y0,x1,y1) { + ctx.beginPath() + ctx.moveTo(x0, y0) + ctx.lineTo(x1, y1) + ctx.stroke() + } + } + this.player = function(){ + ctx.save() + + ctx.translate(~~(w/2),~~(h/2)); + ctx.rotate(-cam.rotationY) + + var radius = 5 + + ctx.fillStyle = playerColor; + + ctx.beginPath(); + ctx.arc(0, 0, radius, 0, 2*Math.PI, false); + ctx.fill(); + + ctx.beginPath(); + ctx.moveTo(0,0) + ctx.lineTo(-radius,0) + ctx.lineTo(0,radius*3) + ctx.lineTo(radius,0) + ctx.moveTo(0,0) + ctx.fill() + + ctx.fillStyle = "transparent" + ctx.restore() + } + + this.boxes = function(){ + + ctx.save() + ctx.translate(~~(w/2),~~(h/2)); + ctx.lineWidth = 0.5 + var tx = ((-xpos) * scale), + ty = ((-ypos) * scale); + ctx.translate(tx, ty) + + scene.inner.children.forEach(function(obj){ + if (obj.type == "BoxDimensions") { + + ctx.save() + ctx.fillStyle = obj.color + ctx.strokeStyle = obj.borderColor + + var obj_scale = (obj.scale || 1) * scale + + var tx = ~~((obj.x) * obj_scale), + ty = ~~((obj.z) * obj_scale); + ctx.translate(-tx, ty) + ctx.rotate(-obj.rotationY) + + var ww = ~~(obj.width/2 * obj_scale) + var hh = ~~(obj.depth/2 * obj_scale) + ctx.beginPath(); + ctx.moveTo(ww, hh) + + ctx.lineTo(ww, -hh) + ctx.lineTo(-ww, -hh) + ctx.lineTo(-ww, hh) + ctx.closePath() + ctx.fill() + ctx.stroke() + ctx.restore() + } + if (obj.type == "Image") { + + ctx.save() + ctx.strokeStyle = "#444" + + var obj_scale = (obj.scale || 1) * scale + + var tx = ~~((obj.x) * obj_scale), + ty = ~~((obj.z) * obj_scale); + ctx.translate(-tx, ty) + ctx.rotate(-obj.rotationY) + + var ww = ~~(obj.width/2 * obj_scale) + ctx.beginPath(); + ctx.moveTo(ww, 0) + ctx.lineTo(-ww, 0) + ctx.closePath() + ctx.stroke() + ctx.restore() + } + }) + ctx.restore() + } + + var dragging = false, mx = 0, my = 0, mdx = 0, mdy = 0, cx, cy; + canvas.addEventListener("mousedown", function(e){ + e.stopPropagation() + var rect = canvas.getBoundingClientRect() + dragging = true; + mx = e.pageX - rect.left + my = e.pageY - rect.top + mdx = (mx - w/2) / scale + mdy = (my - h/2) / scale + cx = cam.x // -= mdx + cy = cam.z // += mdy + + minimap.update() + }) + document.addEventListener("mousemove", function(e){ + if (dragging) { + e.stopPropagation() + var rect = canvas.getBoundingClientRect() + var mnx = e.pageX - rect.left + var mny = e.pageY - rect.top + mdx = (mnx - mx) / scale + mdy = (mny - my) / scale + + cam.x = cx + mdx + cam.z = cy - mdy + minimap.update() + } + }) + document.addEventListener("mouseup", function(e){ + dragging = false; + }) + + canvas.addEventListener( 'mousewheel', onDocumentMouseWheel, false ); + canvas.addEventListener( 'DOMMouseScroll', onDocumentMouseWheel, false); + function onDocumentMouseWheel (e) { + e.preventDefault() + e.stopPropagation() + // WebKit + if ( event.wheelDeltaY ) { + zoom -= event.wheelDeltaY * 0.0003; + } + // Opera / Explorer 9 + else if ( event.wheelDelta ) { + zoom -= event.wheelDelta * 0.0003; + } + // Firefox + else if ( event.detail ) { + zoom += event.detail * 0.01; + } + minimap.update() + } + + this.draw() + document.querySelector("#minimap .el").appendChild(canvas) + + return this; +}
\ No newline at end of file diff --git a/client/assets/javascripts/mx/mx.quaternion.js b/client/assets/javascripts/mx/mx.quaternion.js new file mode 100644 index 0000000..783f887 --- /dev/null +++ b/client/assets/javascripts/mx/mx.quaternion.js @@ -0,0 +1,414 @@ +/** + * quaternion taken from three.js + * @author mikael emtinger / http://gomo.se/ + * @author alteredq / http://alteredqualia.com/ + * @author WestLangley / http://github.com/WestLangley + * @author bhouston / http://exocortex.com + */ + +MX.Quaternion = function ( x, y, z, w ) { + + this._x = x || 0; + this._y = y || 0; + this._z = z || 0; + this._w = ( w !== undefined ) ? w : 1; + +}; + +MX.Quaternion.prototype = { + + constructor: MX.Quaternion, + + _x: 0,_y: 0, _z: 0, _w: 0, + + _euler: undefined, + + _updateEuler: function ( callback ) { + + if ( this._euler !== undefined ) { + + this._euler.setFromQuaternion( this, undefined, false ); + + } + + }, + + get x () { + + return this._x; + + }, + + set x ( value ) { + + this._x = value; + this._updateEuler(); + + }, + + get y () { + + return this._y; + + }, + + set y ( value ) { + + this._y = value; + this._updateEuler(); + + }, + + get z () { + + return this._z; + + }, + + set z ( value ) { + + this._z = value; + this._updateEuler(); + + }, + + get w () { + + return this._w; + + }, + + set w ( value ) { + + this._w = value; + this._updateEuler(); + + }, + + set: function ( x, y, z, w ) { + + this._x = x; + this._y = y; + this._z = z; + this._w = w; + + this._updateEuler(); + + return this; + + }, + + copy: function ( quaternion ) { + + this._x = quaternion._x; + this._y = quaternion._y; + this._z = quaternion._z; + this._w = quaternion._w; + + this._updateEuler(); + + return this; + + }, + + setFromEuler: function ( euler, update ) { + + if ( euler instanceof MX.Euler === false ) { + throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' ); + } + + // http://www.mathworks.com/matlabcentral/fileexchange/ + // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ + // content/SpinCalc.m + + var c1 = Math.cos( euler._x / 2 ); + var c2 = Math.cos( euler._y / 2 ); + var c3 = Math.cos( euler._z / 2 ); + var s1 = Math.sin( euler._x / 2 ); + var s2 = Math.sin( euler._y / 2 ); + var s3 = Math.sin( euler._z / 2 ); + + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + + if ( update !== false ) this._updateEuler(); + + return this; + + }, + + setFromAxisAngle: function ( axis, angle ) { + + // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm + // axis have to be normalized + + var halfAngle = angle / 2, s = Math.sin( halfAngle ); + + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos( halfAngle ); + + this._updateEuler(); + + return this; + + }, + + setFromRotationMatrix: function ( m ) { + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm + + // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) + + var te = m.elements, + + m11 = te[0], m12 = te[4], m13 = te[8], + m21 = te[1], m22 = te[5], m23 = te[9], + m31 = te[2], m32 = te[6], m33 = te[10], + + trace = m11 + m22 + m33, + s; + + if ( trace > 0 ) { + + s = 0.5 / Math.sqrt( trace + 1.0 ); + + this._w = 0.25 / s; + this._x = ( m32 - m23 ) * s; + this._y = ( m13 - m31 ) * s; + this._z = ( m21 - m12 ) * s; + + } else if ( m11 > m22 && m11 > m33 ) { + + s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); + + this._w = (m32 - m23 ) / s; + this._x = 0.25 * s; + this._y = (m12 + m21 ) / s; + this._z = (m13 + m31 ) / s; + + } else if ( m22 > m33 ) { + + s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); + + this._w = (m13 - m31 ) / s; + this._x = (m12 + m21 ) / s; + this._y = 0.25 * s; + this._z = (m23 + m32 ) / s; + + } else { + + s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); + + this._w = ( m21 - m12 ) / s; + this._x = ( m13 + m31 ) / s; + this._y = ( m23 + m32 ) / s; + this._z = 0.25 * s; + + } + + this._updateEuler(); + + return this; + + }, + + inverse: function () { + + this.conjugate().normalize(); + + return this; + + }, + + conjugate: function () { + + this._x *= -1; + this._y *= -1; + this._z *= -1; + + this._updateEuler(); + + return this; + + }, + + lengthSq: function () { + + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + + }, + + length: function () { + + return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); + + }, + + normalize: function () { + + var l = this.length(); + + if ( l === 0 ) { + + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + + } else { + + l = 1 / l; + + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; + + } + + return this; + + }, + + multiply: function ( q, p ) { + + if ( p !== undefined ) { + + console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); + return this.multiplyQuaternions( q, p ); + + } + + return this.multiplyQuaternions( this, q ); + + }, + + multiplyQuaternions: function ( a, b ) { + + // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm + + var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; + var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; + + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + + this._updateEuler(); + + return this; + + }, + + multiplyVector3: function ( vector ) { + + console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); + return vector.applyQuaternion( this ); + + }, + + slerp: function ( qb, t ) { + + var x = this._x, y = this._y, z = this._z, w = this._w; + + // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ + + var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + + if ( cosHalfTheta < 0 ) { + + this._w = -qb._w; + this._x = -qb._x; + this._y = -qb._y; + this._z = -qb._z; + + cosHalfTheta = -cosHalfTheta; + + } else { + + this.copy( qb ); + + } + + if ( cosHalfTheta >= 1.0 ) { + + this._w = w; + this._x = x; + this._y = y; + this._z = z; + + return this; + + } + + var halfTheta = Math.acos( cosHalfTheta ); + var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta ); + + if ( Math.abs( sinHalfTheta ) < 0.001 ) { + + this._w = 0.5 * ( w + this._w ); + this._x = 0.5 * ( x + this._x ); + this._y = 0.5 * ( y + this._y ); + this._z = 0.5 * ( z + this._z ); + + return this; + + } + + var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, + ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; + + this._w = ( w * ratioA + this._w * ratioB ); + this._x = ( x * ratioA + this._x * ratioB ); + this._y = ( y * ratioA + this._y * ratioB ); + this._z = ( z * ratioA + this._z * ratioB ); + + this._updateEuler(); + + return this; + + }, + + equals: function ( quaternion ) { + + return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); + + }, + + fromArray: function ( array ) { + + this._x = array[ 0 ]; + this._y = array[ 1 ]; + this._z = array[ 2 ]; + this._w = array[ 3 ]; + + this._updateEuler(); + + return this; + + }, + + toArray: function () { + + return [ this._x, this._y, this._z, this._w ]; + + }, + + clone: function () { + + return new MX.Quaternion( this._x, this._y, this._z, this._w ); + + } + +}; + +MX.Quaternion.slerp = function ( qa, qb, qm, t ) { + + return qm.copy( qa ).slerp( qb, t ); + +} diff --git a/client/assets/javascripts/mx/primitives/mx.box.js b/client/assets/javascripts/mx/primitives/mx.box.js new file mode 100644 index 0000000..dfe3f5e --- /dev/null +++ b/client/assets/javascripts/mx/primitives/mx.box.js @@ -0,0 +1,62 @@ +MX.Box = MX.Object3D.extend({ + + // this will be called within the contructor + init: function (size, color, borderColor) { + + this.type = "Box" + + size = size || 100 + color = color || 'rgba(0, 255, 122, .1)' + borderColor = borderColor || '#0f3' + + // an Object3D's associated DOM node is the "el" property + this.el.classList.add('box') + + var angle = MX.rotationUnit === 'deg' ? 90 : (Math.PI / 2) + + var top = this.top = new MX.Object3D('.face') + top.rotationX = angle + top.y = size / 2 + + var bottom = this.bottom = new MX.Object3D('.face') + bottom.rotationX = -angle + bottom.y = -size / 2 + + var left = this.left = new MX.Object3D('.face') + left.rotationY = -angle + left.x = -size / 2 + + var right = this.right = new MX.Object3D('.face') + right.rotationY = angle + right.x = size / 2 + + var front = this.front = new MX.Object3D('.face') + front.z = -size / 2 + + var back = this.back = new MX.Object3D('.face') + back.rotationY = angle * 2 + back.z = size / 2 + + // adding children, must also be instances of Object3D + this.add(top, bottom, left, right, front, back) + + this.children.forEach(function (face) { + face.width = size - 2 + face.height = size - 2 + face.el.style.backgroundColor = color + face.el.style.border = '1px solid ' + borderColor + }) + + // this applies the updated CSS style + // required for any change to take effect + // when a parent object's update() is called + // all its children will be updated as well + this.update() + + // if this object's children won't move by themselves + this.updateChildren = false + } + + // other properties will be mixed into the prototype of the new constructor + +})
\ No newline at end of file diff --git a/client/assets/javascripts/mx/primitives/mx.boxDimensions.js b/client/assets/javascripts/mx/primitives/mx.boxDimensions.js new file mode 100644 index 0000000..f3edb13 --- /dev/null +++ b/client/assets/javascripts/mx/primitives/mx.boxDimensions.js @@ -0,0 +1,154 @@ +MX.BoxDimensions = MX.Object3D.extend({ + + // this will be called within the contructor + init: function (opt) { + + var base = this + + this.type = "BoxDimensions" + + var id = this.id = opt.id || guid() + this.x = opt.x || 0 + this.y = opt.y || 0 + this.z = opt.z || 0 + // this.scale = opt.scale || 1 + var scale = opt.scale || 1 + this.rotationX = opt.rotationX || 0 + this.rotationY = opt.rotationY || 0 + this.rotationZ = opt.rotationZ || 0 + var width = this.width = opt.width || 100 + var height = this.height = opt.height || 100 + var depth = this.depth = opt.depth || 100 + var color = this.color = opt.color || 'rgba(0, 255, 122, .1)' + var backgroundImage = this.backgroundImage = opt.backgroundImage; + var borderColor = this.borderColor = opt.borderColor || '#0f3' + var borderWidth = this.borderWidth = typeof opt.borderWidth !== 'undefined' ? opt.borderWidth : 3; + var borderRadius = this.borderRadius = typeof opt.borderRadius !== 'undefined' ? opt.borderRadius : undefined; + var sides = this.sides = opt.sides || "top bottom left right front back" + var className = this.className = opt.className || null + + // an Object3D's associated DOM node is the "el" property + this.el.classList.add('box') + + var angle = MX.rotationUnit === 'deg' ? 90 : (Math.PI / 2) + + this.top = this.bottom = this.left = this.right = this.front = this.back = null + if (-1 != sides.indexOf("top")) { + var top = this.top = new MX.Object3D('.face.top') + top.rotationX = angle + top.width = width + top.height = depth + top.y = height * scale + top.scale = scale + this.add(top) + } + if (-1 != sides.indexOf("bottom")) { + var bottom = this.bottom = new MX.Object3D('.face.bottom') + bottom.rotationX = -angle + bottom.width = width + bottom.height = depth + bottom.y = 0 + bottom.scale = scale + this.add(bottom) + } + if (-1 != sides.indexOf("left")) { + var left = this.left = new MX.Object3D('.face.left') + left.rotationY = -angle + left.width = depth + left.height = height + left.x = -width/2 * scale + left.y = height/2 * scale + left.scale = scale + this.add(left) + } + if (-1 != sides.indexOf("right")) { + var right = this.right = new MX.Object3D('.face.right') + right.rotationY = angle + right.width = depth + right.height = height + right.x = width/2 * scale + right.y = height/2 * scale + right.scale = scale + this.add(right) + } + if (-1 != sides.indexOf("front")) { + var front = this.front = new MX.Object3D('.face.front') + front.width = width + front.height = height + front.z = -depth/2 * scale + front.y = height/2 * scale + front.scale = scale + this.add(front) + } + if (-1 != sides.indexOf("back")) { + var back = this.back = new MX.Object3D('.face.back') + back.width = width + back.height = height + back.rotationY = angle * 2 + back.z = depth/2 * scale + back.y = height/2 * scale + back.scale = scale + this.add(back) + } + + this.children.forEach(function (face) { + if (borderRadius) { + face.el.style.borderRadius = borderRadius + "px" + } + if (className) { + face.el.classList.add(className) + } + else { + if (backgroundImage) { + face.el.style.backgroundImage = "url(" + backgroundImage + ")" + } + else if (color) { + face.el.style.backgroundColor = color + } + if (borderWidth) { + face.el.style.border = borderWidth + 'px solid ' + borderColor + } + } + }) + + // bottom.el.style.border = "0" + + // this applies the updated CSS style + // required for any change to take effect + // when a parent object's update() is called + // all its children will be updated as well + this.update() + + // if this object's children won't move by themselves + this.updateChildren = true + + this.setWidth = function(w){ + base.width = top.width = bottom.width = front.width = back.width = w + left.x = -w/2 + right.x = w/2 + base.dirty = true + } + this.setHeight = function(h){ + base.height = left.height = right.height = front.height = back.height = h + bottom.y = 0 + left.y = right.y = front.y = back.y = h/2 + top.y = h + base.dirty = true + } + this.setDepth = function(d){ + base.depth = top.height = bottom.height = left.width = right.width = d + front.z = -d/2 + back.z = d/2 + base.dirty = true + } + + }, + + toString: function(){ + var params = "id width height depth x y z rotationX rotationY scale color borderColor borderWidth backgroundImage borderRadius sides".split(" ") + return this.__toString(params) + }, + + // other properties will be mixed into the prototype of the new constructor + +})
\ No newline at end of file diff --git a/client/assets/javascripts/mx/primitives/mx.coords.js b/client/assets/javascripts/mx/primitives/mx.coords.js new file mode 100644 index 0000000..80b148c --- /dev/null +++ b/client/assets/javascripts/mx/primitives/mx.coords.js @@ -0,0 +1,61 @@ +MX.Coords = (function () { + + var colors = { + x: '#f33', + y: '#3f3', + z: '#66f' + } + + var Axis = MX.Object3D.extend({ + init: function (axis, size) { + + var label = document.createElement('span') + label.textContent = axis.toUpperCase() + label.style.position = 'absolute' + label.style.right = '0px' + label.style.bottom = '3px' + label.style.fontSize = Math.round(size / 10) + 'px' + this.el.appendChild(label) + + var faceA = new MX.Object3D(), + faceB = new MX.Object3D() + faceA.rotationX = 90 + this.add(faceA, faceB) + + this.el.style.color = + faceA.el.style.backgroundColor = + faceB.el.style.backgroundColor = colors[axis] + + this.width = + faceA.width = + faceB.width = size + + this.height = + faceA.height = + faceB.height = Math.round(size / 100) + + var angle = MX.rotationUnit === 'deg' ? 90 : (Math.PI / 2) + + if (axis === 'y') { + this.rotationZ = -angle + } else if (axis === 'z') { + this.rotationY = angle + } + } + }) + + var Coords = MX.Object3D.extend({ + init: function (size) { + size = size || 100 + var x = new Axis('x', size), + y = new Axis('y', size), + z = new Axis('z', size) + this.add(x, y, z) + this.update() + this.updateChildren = false + } + }) + + return Coords + +})()
\ No newline at end of file diff --git a/client/assets/javascripts/mx/primitives/mx.cutout.js b/client/assets/javascripts/mx/primitives/mx.cutout.js new file mode 100644 index 0000000..9d9043f --- /dev/null +++ b/client/assets/javascripts/mx/primitives/mx.cutout.js @@ -0,0 +1,66 @@ +MX.Cutout = MX.Object3D.extend({ + init: function (ops) { + + this.type = "Cutout" + + var layer = this + layer.width = 0 + layer.height = 0 + + if (ops.src) this.loadTexture(ops) + + if (ops.texture) { + } + else if (ops.classname) { + layer.el.classList.add(ops.classname) + } + else { + } + layer.el.style.backgroundRepeat = 'no-repeat' + + this.dirty = true + this.updateChildren = true + this.update() + }, + + loadTexture: function(ops){ + var layer = this + var image = new Image() + var pattern = ops.pattern + var texture = ops.texture + + image.onload = function(){ + var canvas = document.createElement("canvas") + var ctx = canvas.getContext('2d') + + layer.width = canvas.width = image.naturalWidth + layer.height = canvas.height = image.naturalHeight + + ctx.drawImage(image, 0, 0, canvas.width, canvas.height) + ctx.globalCompositeOperation = "source-in" + + if (texture) { + ctx.fillStyle = ctx.createPattern(texture, 'repeat') + ctx.fillRect(0, 0, canvas.width, canvas.height) + } + if (pattern) { + ctx.fillStyle = ctx.createPattern(pattern, 'repeat') + ctx.fillRect(0, 0, canvas.width, canvas.height) + } + + layer.scale = ops.scale || 1 + layer.x = ops.x || 0 + layer.y = (ops.y || 0) + layer.height/2 + 1 + layer.z = ops.z || 0 + layer.rotationX = ops.rotationX || 0 + layer.rotationY = ops.rotationY || 0 + layer.el.appendChild(canvas) + + layer.el.classList.add('image') + ops.className && layer.el.classList.add(ops.className) + layer.dirty = true + layer.update() + } + image.src = ops.src; + } +}) diff --git a/client/assets/javascripts/mx/primitives/mx.face.js b/client/assets/javascripts/mx/primitives/mx.face.js new file mode 100644 index 0000000..ac47ab4 --- /dev/null +++ b/client/assets/javascripts/mx/primitives/mx.face.js @@ -0,0 +1,41 @@ +MX.Face = MX.Object3D.extend({ + + // this will be called within the contructor + init: function (size, color, borderColor) { + + size = size || 100 + color = color || 'rgba(0, 255, 122, .1)' + borderColor = borderColor || '#0f3' + + // an Object3D's associated DOM node is the "el" property + this.el.classList.add('face') + + var angle = MX.rotationUnit === 'deg' ? 90 : (Math.PI / 2) + + var top = this.top = new MX.Object3D('.face') + top.rotationX = angle + top.y = size / 2 + + // adding children, must also be instances of Object3D + this.add(top) + + this.children.forEach(function (face) { + face.width = size - 2 + face.height = size - 2 + face.el.style.backgroundColor = color + face.el.style.border = '1px solid ' + borderColor + }) + + // this applies the updated CSS style + // required for any change to take effect + // when a parent object's update() is called + // all its children will be updated as well + this.update() + + // if this object's children won't move by themselves + this.updateChildren = false + } + + // other properties will be mixed into the prototype of the new constructor + +}) diff --git a/client/assets/javascripts/mx/primitives/mx.image.js b/client/assets/javascripts/mx/primitives/mx.image.js new file mode 100644 index 0000000..d1e292d --- /dev/null +++ b/client/assets/javascripts/mx/primitives/mx.image.js @@ -0,0 +1,69 @@ +MX.Image = MX.Object3D.extend({ + init: function (ops) { + + this.type = "Image" + + var layer = this + layer.width = 0 + layer.height = 0 + layer.x = ops.x || 0 + layer.y = ops.y || 0 + layer.z = ops.z || 0 + layer.backface = ops.backface || false + + if (layer.backface) { + layer.el.classList.add("backface-visible") + } + + if (ops.src) { + this.loadTexture(ops) + } + + if (ops.className) { + layer.el.classList.add(ops.className) + } + layer.el.style.backgroundRepeat = 'no-repeat' + + this.dirty = true + this.updateChildren = true + this.update() + }, + + loadTexture: function(ops){ + var layer = this + layer.ops = defaults(ops, layer.ops) + var image = new Image() + image.onload = function(){ + layer.scale = layer.ops.scale || 1 + layer.width = image.naturalWidth + layer.height = image.naturalHeight + layer.x = layer.ops.x || 0 + layer.y = (layer.ops.y || 0) + layer.scale * layer.height/2 + 1 + layer.z = layer.ops.z || 0 + layer.rotationX = layer.ops.rotationX || 0 + layer.rotationY = layer.ops.rotationY || 0 + layer.rotationZ = layer.ops.rotationZ || 0 + layer.el.style.backgroundImage = "url(" + image.src + ")" + layer.el.classList.add('image') + layer.dirty = true + layer.update() + } + image.src = ops.src; + }, + + move: function(ops){ + var layer = this + layer.ops = defaults(ops, layer.ops) + for (var i in ops) { + layer[i] = ops[i] + } + layer.dirty = true + layer.update() + }, + + toString: function(){ + var params = "id src width height depth x y z rotationX rotationY rotationZ scale".split(" ") + return this.__toString(params) + }, + +}) diff --git a/client/assets/javascripts/mx/primitives/mx.scaleBox.js b/client/assets/javascripts/mx/primitives/mx.scaleBox.js new file mode 100644 index 0000000..77f45e9 --- /dev/null +++ b/client/assets/javascripts/mx/primitives/mx.scaleBox.js @@ -0,0 +1,140 @@ +MX.ScaleBox = MX.Object3D.extend({ + + // this will be called within the contructor + init: function (opt) { + + var base = this + + this.type = "ScaleBox" + + var id = this.id = opt.id || guid() + this.x = opt.x || 0 + this.y = opt.y || 0 + this.z = opt.z || 0 + this.rotationX = opt.rotationX || 0 + this.rotationY = opt.rotationY || 0 + this.rotationZ = opt.rotationZ || 0 + var scale = this.scale = opt.scale || 1 + var width = this.width = scale * (opt.width || 100) + var height = this.height = scale * (opt.height || 100) + var depth = this.depth = scale * (opt.depth || 100) + var color = this.color = opt.color || 'rgba(0, 255, 122, .1)' + var sides = this.sides = opt.sides || "top bottom left right front back" + + // an Object3D's associated DOM node is the "el" property + this.el.classList.add('box') + + var angle = MX.rotationUnit === 'deg' ? 90 : (Math.PI / 2) + + var top = this.top = new MX.Object3D('.face.top') + top.rotationX = angle + top.width = 1 + top.height = 1 + top.scaleX = width + top.scaleY = 1 + top.scaleZ = depth + top.y = height + + var bottom = this.bottom = new MX.Object3D('.face.bottom') + bottom.rotationX = -angle + bottom.width = 1 + bottom.height = 1 + bottom.scaleX = width + bottom.scaleY = 1 + bottom.scaleZ = depth + bottom.y = 0 + + var left = this.left = new MX.Object3D('.face.left') + left.rotationY = -angle + left.width = 1 + left.height = 1 + left.scaleX = 1 + left.scaleY = height + left.scaleZ = depth + left.x = -width/2 + left.y = height/2 + + var right = this.right = new MX.Object3D('.face.right') + right.rotationY = angle + right.width = 1 + right.height = 1 + right.scaleX = 1 + right.scaleY = height + right.scaleZ = depth + right.x = width/2 + right.y = height/2 + + var front = this.front = new MX.Object3D('.face.front') + front.width = 1 + front.height = 1 + front.scaleX = width + front.scaleY = height + front.scaleZ = 1 + front.z = -depth/2 + front.y = height/2 + + var back = this.back = new MX.Object3D('.face.back') + back.width = 1 + back.height = 1 + back.scaleX = width + back.scaleY = height + back.scaleZ = 1 + back.rotationY = angle * 2 + back.z = depth/2 + back.y = height/2 + + // adding children, must also be instances of Object3D + if (-1 != sides.indexOf("top")) this.add(top) + if (-1 != sides.indexOf("bottom")) this.add(bottom) + if (-1 != sides.indexOf("left")) this.add(left) + if (-1 != sides.indexOf("right")) this.add(right) + if (-1 != sides.indexOf("front")) this.add(front) + if (-1 != sides.indexOf("back")) this.add(back) + + this.children.forEach(function (face) { + face.el.style.backgroundColor = color + }) + + // this applies the updated CSS style + // required for any change to take effect + // when a parent object's update() is called + // all its children will be updated as well + this.update() + + // if this object's children won't move by themselves + this.updateChildren = true + + this.setWidth = function(w){ + base.width = top.width = bottom.width = front.width = back.width = w + left.x = -w/2 + right.x = w/2 + base.dirty = true + } + this.setHeight = function(h){ + base.height = left.height = right.height = front.height = back.height = h + bottom.y = 0 + left.y = right.y = front.y = back.y = h/2 + top.y = h + base.dirty = true + } + this.setDepth = function(d){ + base.depth = top.height = bottom.height = left.width = right.width = d + front.z = -d/2 + back.z = d/2 + base.dirty = true + } + + }, + + toString: function(){ + var params = "id width height depth x y z rotationX rotationY color sides".split(" ") + return this.__toString(params) + }, + + clone: function(){ + return new MX[this.type] (this) + } + + // other properties will be mixed into the prototype of the new constructor + +}) diff --git a/client/assets/javascripts/mx/primitives/mx.tableau.js b/client/assets/javascripts/mx/primitives/mx.tableau.js new file mode 100644 index 0000000..514e206 --- /dev/null +++ b/client/assets/javascripts/mx/primitives/mx.tableau.js @@ -0,0 +1,48 @@ + + +var Tableau = function(){ + this.extend = extend.bind(Tableau) + + function extend (props) { + var Super = this + var ExtendedTableau = function () { + Super.call(this) + props.init && props.init.apply(this, arguments) + } + ExtendedTableau.prototype = Object.create(Tableau.prototype) + for (var prop in props) { + if (props.hasOwnProperty(prop) && prop !== 'init') { + ExtendedTableau.prototype[prop] = props[prop] + } + } + ExtendedTableau.extend = extend.bind(ExtendedTableau) + return ExtendedTableau + } +} + +Tableau.prototype.init = function(opt){} +Tableau.prototype.animate = function(t){} +Tableau.prototype.show = function(){} +Tableau.prototype.hide = function(){} + +MX.Tableau = new Tableau() +MX.Tableaux = {} + +/* + +MX.Tableaux.Foo = MX.Tableau.extend({ + // this will be called within the contructor + init: function (opt) { + }, + + show: function(){ + }, + + hide: function(){ + }, + + animate: function() { + } +}) + +*/ diff --git a/client/assets/javascripts/mx/primitives/mx.text.js b/client/assets/javascripts/mx/primitives/mx.text.js new file mode 100644 index 0000000..0c278a9 --- /dev/null +++ b/client/assets/javascripts/mx/primitives/mx.text.js @@ -0,0 +1,34 @@ +MX.Text = MX.Object3D.extend({ + init: function (ops) { + + this.type = "Text" + + var layer = new MX.Object3D('text') + layer.width = ops.width || 100 + layer.height = ops.height || 50 + layer.x = ops.x || 0 + layer.y = ops.y || 0 + layer.z = ops.z || 0 + layer.scale = ops.scale || 1 + layer.el.innerHTML = ops.value || "" + if (ops.id) layer.el.id = ops.id; + if (ops.background) layer.el.style.background = ops.background; + if (ops.color) layer.el.style.color = ops.color; + if (ops.fontSize) layer.el.style.fontSize = ops.fontSize + "px"; + + this.add(layer) + + this.children.forEach(function (c, i) { + if (ops.classname) { + c.el.classList.add(ops.classname) + } + else { + } + c.el.style.backgroundRepeat = 'no-repeat' + }) + + this.dirty = true + this.updateChildren = true + this.update() + } +}) diff --git a/client/assets/javascripts/mx/primitives/mx.texturedBox.js b/client/assets/javascripts/mx/primitives/mx.texturedBox.js new file mode 100644 index 0000000..daec2d8 --- /dev/null +++ b/client/assets/javascripts/mx/primitives/mx.texturedBox.js @@ -0,0 +1,121 @@ +// Creates a box using a given texture image. +// Uses a texture image like this: +// +// ---------- ---------- +// | | | +// | top | bottom | +// | | | +// ---------- ---------- ---------- ---------- +// | | | | | +// | left | front | right | back | +// | | | | | +// ---------- ---------- ---------- ---------- +// +// See `examples/images/skins/` for some minecraft skin examples. + +// Options: +// +// - {number} `width` +// - {number} `height` +// - {number} `depth` +// - {string} `texture` path to texture image +// - {string} `classname` class to be added to dom element + +MX.TexturedBox = MX.Object3D.extend({ + + init: function (ops) { + + this.type = "TexturedBox" + + if (!ops.width || !ops.height || !ops.depth || (!ops.texture && !ops.classname)) { + console.warn('TextureBox: missing arguments') + return + } + + // faces + var angle = MX.rotationUnit === 'deg' ? 90 : (Math.PI / 2), + offsetX = ops.offset ? (ops.offset.x || 0) : 0, + offsetY = ops.offset ? (ops.offset.y || 0) : 0, + overlap = ops.overlap ? ops.overlap : 0 + var multiTexture = typeof ops.texture == "object"; + + var top = this.top = new MX.Object3D() + top.width = ops.width + top.height = ops.depth + top.rotationX = angle + top.y = ops.height / 2 - overlap + if (!multiTexture) + top.el.style.backgroundPosition = + (-(offsetX + ops.depth) + 'px ') + + (-offsetY + 'px') + + var bottom = this.bottom = new MX.Object3D() + bottom.width = ops.width + bottom.height = ops.depth + bottom.rotationX = -angle + bottom.y = -ops.height / 2 + overlap + if (!multiTexture) + bottom.el.style.backgroundPosition = + (-(offsetX + ops.depth + ops.width) + 'px ') + + (-offsetY + 'px') + + var left = this.left = new MX.Object3D() + left.width = ops.depth + left.height = ops.height + left.rotationY = -angle + left.x = -ops.width / 2 + overlap + if (!multiTexture) + left.el.style.backgroundPosition = + (-offsetX + 'px ') + + (-(offsetY + ops.depth) + 'px') + + var right = this.right = new MX.Object3D() + right.width = ops.depth + right.height = ops.height + right.rotationY = angle + right.x = ops.width / 2 - overlap + if (!multiTexture) + right.el.style.backgroundPosition = + (-(offsetX + ops.depth + ops.width) + 'px ') + + (-(offsetY + ops.depth) + 'px') + + var front = this.front = new MX.Object3D() + front.width = ops.width + front.height = ops.height + front.z = -ops.depth / 2 + overlap + if (!multiTexture) + front.el.style.backgroundPosition = + (-(offsetX + ops.depth) + 'px ') + + (-(offsetY + ops.depth) + 'px') + + var back = this.back = new MX.Object3D() + back.width = ops.width + back.height = ops.height + back.rotationY = angle * 2 + back.z = ops.depth / 2 - overlap + if (!multiTexture) + back.el.style.backgroundPosition = + (-(offsetX + ops.depth * 2 + ops.width) + 'px ') + + (-(offsetY + ops.depth) + 'px') + + this.add(top, bottom, left, right, front, back) + + this.children.forEach(function (c,i) { + if (multiTexture) { + c.el.style.backgroundImage = 'url(' + ops.texture[i] + ')' + } + else if (ops.texture) { + c.el.style.backgroundImage = 'url(' + ops.texture + ')' + } + if (ops.classname) { + c.el.classList.add(ops.classname) + } + c.el.style.backgroundRepeat = 'no-repeat' + }) + + this.update() + this.updateChildren = false + + } + +}) |
