diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6586752 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.nds +*.exe +mongoose.conf +Code/Engine/col.lua \ No newline at end of file diff --git a/Code/Audio/nitroAudio.js b/Code/Audio/nitroAudio.js new file mode 100644 index 0000000..44fe294 --- /dev/null +++ b/Code/Audio/nitroAudio.js @@ -0,0 +1,113 @@ +// +// nitroAudio.js +//-------------------- +// Provides an interface for playing nds music and sound effects. +// by RHY3756547 +// + +window.AudioContext = window.AudioContext || window.webkitAudioContext; + +window.nitroAudio = new (function() { + var t = this; + var ctx; + + t.sounds = []; + + t.tick = tick; + t.playSound = playSound; + t.kill = kill; + t.init = init; + t.instaKill = instaKill; + + t.sdat = null; + + function init(sdat) { + ctx = new AudioContext(); + t.ctx = ctx; + + var listener = ctx.listener; + listener.dopplerFactor = 1; + listener.speedOfSound = 100/1024; //343.3 + + SSEQWaveCache.init(sdat, ctx); + t.sdat = sdat; + } + + function tick() { + for (var i=0; i0) { + t.threads.splice(threadsToKill.pop(), 1); + } + + if (t.threads.length == 0 && ctx.currentTime > t.lastNoteEnd) t.dead = true; + } + + function startThread(pc) { + var thread = new SSEQThread(sseqHead.seq.data, pc, t); + t.threads.push(thread); + } + + function terminateThread(thread) { + threadsToKill.push(t.threads.indexOf(thread)); + } + + function setTempo(bpm) { + //sets tempo of threads and alters their wait times to adjust + t.bpm = bpm*t.bpmMultiplier; + } + + function loadBank(bn) { + t.bank = sdat.sections["$INFO"][2][bn]; + if (t.bank == null) {return;} + for (var i=0; i<4; i++) { + if (t.bank.waveArcs[i] != 0xFFFF) SSEQWaveCache.cacheWaveArc(t.bank.waveArcs[i]); + } + } + + function cutNoteShort(thread, note) { + try { //can throw exception if note has already ended. + if (note.ended) return; + var time = thread.calculateCurrentTime(); + var baseTime = (time == Infinity)?ctx.currentTime:time; + if (baseTime > note.noteEndsAt) return; + var releaseTime = note.relTime; + note.note.gain.cancelScheduledValues(baseTime); + note.note.gain.linearRampToValueAtTime(0, baseTime+releaseTime); //then release + note.src.stop(baseTime+releaseTime); + if (baseTime+releaseTime > t.lastNoteEnd) t.lastNoteEnd = baseTime+releaseTime; + } catch (e) {} + } + + function setTranspose(newT) { + t.transpose = newT; + for (var i=0; i>11)/1000; + source.playbackRate.exponentialRampToValueAtTime(targetFreq, baseTime+time); + } + } + + //sequence the note + + var atk = (thread.attack != null)?thread.attack:inst.attack; + var dec = (thread.decay != null)?thread.decay:inst.decay; + var sus = (thread.sustain != null)?thread.sustain:inst.sustainLvl; + var rel = (thread.release != null)?thread.release:inst.release; + + var attackTime = calculateRequiredAttackCycles(convertAttToRate(atk))*CYCLE_TIME;//(255/convertAttToRate(inst.attack))*0.016; //0.01; + var decayTime = (92544/convertFallToRate(dec))*(1-sus/0x7F)*CYCLE_TIME/2; + var releaseTime = (92544/convertFallToRate(rel))*(sus/0x7F)*CYCLE_TIME/2; + + if ((!thread.tie) || thread.lastNote == null) { + note.gain.value = 0.0; + note.gain.setValueAtTime(0.0, baseTime); //initially 0 + note.gain.linearRampToValueAtTime(velocity, baseTime+attackTime); //attack + note.gain.linearRampToValueAtTime(velocity*sus/0x7F, baseTime+attackTime+decayTime); //decay + + source.start(baseTime); + + source.onended = function(){ + note.ended = true; + source.disconnect(); + } + } + + if (realDur != Infinity) { + if (baseTime+attackTime+decayTime < baseTime+realDur) note.gain.linearRampToValueAtTime(velocity*sus/0x7F, baseTime+realDur); //sustain until + note.gain.linearRampToValueAtTime(0, baseTime+realDur+releaseTime); //then release + source.stop(baseTime+realDur+releaseTime); + + if (baseTime+realDur+releaseTime > t.lastNoteEnd) t.lastNoteEnd = baseTime+realDur+releaseTime; + } + + return {src: source, base: inst.freq, start:num, note: note, relTime: releaseTime, snd: snd, noteEndsAt:baseTime+realDur}; + } + + function calculateRequiredAttackCycles(att) { + var value = 92544; + var ticks = 0; + while (value > 0) { + value = Math.floor((att*value)/255); + ticks++ + } + return ticks; + } + + function convertAttToRate(attack) { + var table = [0x00, 0x01, 0x05, 0x0E, 0x1A, 0x26, 0x33, 0x3F, 0x49, 0x54, + 0x5C, 0x64, 0x6D, 0x74, 0x7B, 0x7F, 0x84, 0x89, 0x8F]; + if (attack & 0x80) return 0; + else if (attack >= 0x6F) return table[0x7F-attack]; + else return 0xFF-attack; + } + + function convertFallToRate(fall) { + if (fall&0x80) return 0; + else if (fall == 0x7F) return 0xFFFF; + else if (fall == 0x7E) return 0x3C00; + else if (fall < 0x32) return ((fall<<1)+1)&0xFFFF; + else return (0x1E00/(0x7E-fall))&0xFFFF; + } + + function noteToFreq(n) { + return Math.pow(2, (n-49)/12)*440; + } + + function getInst(inst, note) { + switch (inst.type) { + case 0: + return null; + case 1: + return inst; + case 2: + return inst.entries[Math.max(inst.lower, Math.min(inst.upper, note))-inst.lower]; + case 3: + for (var i=0; i 10000) { Instructions[0xFF](); console.error("audio thread locked up")}; + } + + if (t.wait == Infinity && t.lastNote != null && t.lastNote.note.ended) Instructions[0xFF](); + } + + function noteOn(num) { + if (num == 0) return; //NOP + var velocity = forcableValue(true); + var length = forcableValueFunc(false, readVariableLength); + if (length == 0) length = Infinity; + t.lastNote = player.playNote(t, velocity, length, num); + if (t.noteWait) t.wait += length; + } + + function ticksToMs(ticks) { + return (ticks/48)*(60000/player.bpm); + } + + function readVariableLength() { + var read = prog[pc++]; + var value = read&0x7F; + while (read & 0x80) { + var read = prog[pc++]; + value = (value<<7) | (read&0x7F); + } + return value; + + } + + function calculateCurrentTime() { + return player.baseAudioTime+ticksToMs(t.wait-player.remainder)/1000; + } + + var InstArgs = [ //starts at 0x80 + [readVariableLength], [readVariableLength], [], [], [], [], [], [], [], [], [], [], [], [], [], [], //0x80-0x8F + [], [], [], [read8, read24], [read24], [read24], [], [], [], [], [], [], [], [], [], [], //0x90-0x9F + [read8, readSpecial, read16, read16], [read8, readSpecial], [], [], [], [], [], [], [], [], [], [], [], [], [], [], + [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [read8, read8], [], [], //0xB0-0xBF + [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], [read8], + [read8], [read8], [read8], [read8], [read8], [read8], [read8], [], [], [], [], [], [], [], [], [], + [read16], [read16], [read16], [], [], [], [], [], [], [], [], [], [], [], [], [], + [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], + ] + + var Instructions = []; + + Instructions[0xFE] = function() { //track definition + player.trackAlloc = read16(); + } + + Instructions[0x93] = function() { //track definition + var trackID = prog[pc++]; + var newPC = prog[pc++]; + newPC |= prog[pc++]<<8; + newPC |= prog[pc++]<<16; + + var bit = 1<>7; + if (bank != 0) player.loadBank(bank); + } + + Instructions[0x94] = function() { //JUMP + var newPC = prog[pc++]; + newPC |= prog[pc++]<<8; + newPC |= prog[pc++]<<16; + pc = newPC; + } + + Instructions[0x95] = function() { //CALL + var newPC = prog[pc++]; + newPC |= prog[pc++]<<8; + newPC |= prog[pc++]<<16; + t.stack.push(pc); + pc = newPC; + } + + Instructions[0xFD] = function() { //RETURN + if (t.stack.length == 0) Instructions[0xFF](); + pc = t.stack.pop(); + } + + //LOGIC INSTRUCTIONS + + Instructions[0xA0] = function() { //random + force = true; //this command forces the input to the next command to be a generated random number + forceCommand = prog[pc++]; + if (forceCommand < 0x80 || (forceCommand >= 0xB0 && forceCommand <= 0xBD)) forceSpecial = prog[pc++]; + var min = reads16(); + var max = reads16(); + forceValue = Math.floor(Math.random()*(max-min+1))+min; + } + + Instructions[0xA1] = function() { //from var + force = true; //this command forces the input to the next command to be from a variable. use with caution probably! + forceCommand = prog[pc++]; + if (forceCommand < 0x80 || (forceCommand >= 0xB0 && forceCommand <= 0xBD)) forceSpecial = prog[pc++]; + forceValue = player.vars[prog[pc++]]; + } + + function varInst(inst){ + var varNum = forcableValue(true); + var arg = forcableValue(); + if (arg & 0x80) arg -= 256; + if (inst == 0xB4 && arg == 0) return; + varFunc[inst-0xB0](varNum, arg) + } + + var varFunc = [ //"=", "+=", "-=", "*=", "/=", "[Shift]", "[Rand]" + function(a, b) { player.vars[a] = b }, + function(a, b) { player.vars[a] += b }, + function(a, b) { player.vars[a] -= b }, + function(a, b) { player.vars[a] *= b }, + function(a, b) { player.vars[a] = Math.floor(player.vars[a]/b) }, + function(a, b) { + if (b < 0) player.vars[a] = player.vars[a]>>(-b); + else player.vars[a] = player.vars[a]<= b }, + function(a, b) { return player.vars[a] > b }, + function(a, b) { return player.vars[a] <= b }, + function(a, b) { return player.vars[a] < b }, + function(a, b) { return player.vars[a] != b }, + ] + + Instructions[0xB8] = boolInst; + Instructions[0xB9] = boolInst; + Instructions[0xBA] = boolInst; + Instructions[0xBB] = boolInst; + Instructions[0xBC] = boolInst; + Instructions[0xBD] = boolInst; + + Instructions[0xA2] = function() { //if# + if (!comparisonResult) { + //skip next + var inst = prog[pc++]; + if (inst < 0x80) { + read8(); + readVariableLength(); + } else { + var cmds = InstArgs[inst-0x80]; + var last = 0; + for (var i=0; i0); } //mono/poly + + Instructions[0xC8] = function() { t.tie = prog[pc++]; if (t.lastNote != null) player.cutNoteShort(t, t.lastNote); t.lastNote = null; } //tie + Instructions[0xC9] = function() { t.portaKey = prog[pc++]; } //portamento control + Instructions[0xCA] = function() { var value = forcableValue(); } //modulation depth + Instructions[0xCB] = function() { var value = forcableValue(); } //modulation speed + Instructions[0xCC] = function() { var value = prog[pc++]; } //modulation type + Instructions[0xCD] = function() { var value = prog[pc++]; } //modulation range + Instructions[0xCE] = function() { t.portaKey = (t.portaKey&0x7F)|((!prog[pc++])<<7); } //portamento on/off + Instructions[0xCF] = function() { t.portaTime = forcableValue(); } //portamento time + Instructions[0xD0] = function() { t.attack = forcableValue(); } //attack rate + Instructions[0xD1] = function() { t.decay = forcableValue(); } //decay rate + Instructions[0xD2] = function() { t.sustain = forcableValue(); } //sustain rate + Instructions[0xD3] = function() { t.release = forcableValue(); } //release rate + + Instructions[0xD4] = function() { t.loopTimes = forcableValue(); t.loopPtr = pc; } //loop start + Instructions[0xFC] = function() { if (t.loopTimes-- > 0) pc = t.loopPtr; } //loop end + + Instructions[0xD5] = function() { var value = forcableValue(); } //expression + Instructions[0xD6] = function() { var value = prog[pc++]; } //print variable + Instructions[0xE0] = function() { var value = prog[pc++]; value |= prog[pc++]<<8 } //modulation delay + + Instructions[0xE1] = function() { + var value = prog[pc++]; + value |= prog[pc++]<<8; + player.setTempo(value); + } //set BPM + + Instructions[0xE3] = function() { t.sweepPitch = forcableValueFunc(false, reads16); } //sweep pitch + + Instructions[0xFF] = function() { + if (t.lastNote != null) player.cutNoteShort(t, t.lastNote); + player.terminateThread(t); + t.dead = true; + } //end of track + + function read16() { + var value = prog[pc++]; + value |= prog[pc++]<<8; + return value; + } + + function reads16() { + var value = read16(); + if (value & 0x8000) value -= 0x10000; + return value; + } + + function read8() { + return prog[pc++]; + } + + function readSpecial(last) { + if (last < 0x80 || (last >= 0xB0 && last < 0xBD)) return prog[pc++]; + else return 0; + } + + function read24() { + var value = prog[pc++]; + value |= prog[pc++]<<8; + value |= prog[pc++]<<16; + return value; + } + + function forcableValueFunc(special, func) { + if (force) return special?forceSpecial:forceValue; + else return func(); + } + + function forcableValue(special) { + if (force) return special?forceSpecial:forceValue; + else return prog[pc++]; + } + + function setPan(value) { + t.pan = value; + if (value > 0) { + gainR.gain.value = 1; + gainL.gain.value = 1-value; + } else { + gainR.gain.value = 1+value; + gainL.gain.value = 1; + } + } + + function noteToFreq(n) { + return Math.pow(2, (n-49)/12)*440; + } +} \ No newline at end of file diff --git a/Code/Engine/cameras/cameraIngame.js b/Code/Engine/cameras/cameraIngame.js new file mode 100644 index 0000000..1592ace --- /dev/null +++ b/Code/Engine/cameras/cameraIngame.js @@ -0,0 +1,98 @@ +// +// cameraIngame.js +//-------------------- +// The ingame camera that follows the kart from behind. +// by RHY3756547 +// +// includes: main.js +// + +window.cameraIngame = function(kart) { + + var thisObj = this; + this.kart = kart; + this.getView = getView; + this.targetShadowPos = [0, 0, 0] + + var mat = mat4.create(); + + var camOffset = [0, 32, -48] + var lookAtOffset = [0, 16, 0] + + var camNormal = [0, 1, 0]; + var camAngle = 0; + var boostOff = 0; + + function getView(scene) { + var basis = buildBasis(); + var camPos = vec3.transformMat4([], camOffset, basis); + var lookAtPos = vec3.transformMat4([], lookAtOffset, basis); + + vec3.scale(camPos, camPos, 1/1024); + vec3.scale(lookAtPos, lookAtPos, 1/1024); + + var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]); + var kpos = vec3.clone(kart.pos); + if (kart.drifting && !kart.driftLanded && kart.ylock>0) kpos[1] -= kart.ylock; + mat4.translate(mat, mat, vec3.scale([], kpos, -1/1024)); + + //interpolate visual normal roughly to target + camNormal[0] += (kart.kartNormal[0]-camNormal[0])*0.075; + camNormal[1] += (kart.kartNormal[1]-camNormal[1])*0.075; + camNormal[2] += (kart.kartNormal[2]-camNormal[2])*0.075; + vec3.normalize(camNormal, camNormal); + + camAngle += dirDiff(kart.physicalDir+kart.driftOff/2, camAngle)*0.075; + camAngle = fixDir(camAngle); + + boostOff += (((kart.boostNorm+kart.boostMT > 0)?5:0) - boostOff)*0.075 + + var p = mat4.perspective(mat4.create(), ((70+boostOff)/180)*Math.PI, gl.viewportWidth / gl.viewportHeight, 0.01, 10000.0); + + var dist = 192; + this.targetShadowPos = vec3.add([], kart.pos, [Math.sin(kart.angle)*dist, 0, -Math.cos(kart.angle)*dist]) + + thisObj.view = {p:p, mv:mat}; + + return thisObj.view; + } + + function buildBasis() { + //order y, x, z + var basis = gramShmidt(camNormal, [Math.cos(camAngle), 0, Math.sin(camAngle)], [Math.sin(camAngle), 0, -Math.cos(camAngle)]); + var temp = basis[0]; + basis[0] = basis[1]; + basis[1] = temp; //todo: cleanup + return [ + basis[0][0], basis[0][1], basis[0][2], 0, + basis[1][0], basis[1][1], basis[1][2], 0, + basis[2][0], basis[2][1], basis[2][2], 0, + 0, 0, 0, 1 + ] + } + + function gramShmidt(v1, v2, v3) { + var u1 = v1; + var u2 = vec3.sub([0, 0, 0], v2, project(u1, v2)); + var u3 = vec3.sub([0, 0, 0], vec3.sub([0, 0, 0], v3, project(u1, v3)), project(u2, v3)); + return [vec3.normalize(u1, u1), vec3.normalize(u2, u2), vec3.normalize(u3, u3)] + } + + function project(u, v) { + return vec3.scale([], u, (vec3.dot(u, v)/vec3.dot(u, u))) + } + + function fixDir(dir) { + return posMod(dir, Math.PI*2); + } + + function dirDiff(dir1, dir2) { + var d = fixDir(dir1-dir2); + return (d>Math.PI)?(-2*Math.PI+d):d; + } + + function posMod(i, n) { + return (i % n + n) % n; + } + +} \ No newline at end of file diff --git a/Code/Engine/cameras/cameraIntro.js b/Code/Engine/cameras/cameraIntro.js new file mode 100644 index 0000000..7081423 --- /dev/null +++ b/Code/Engine/cameras/cameraIntro.js @@ -0,0 +1,118 @@ +// +// cameraIntro.js +//-------------------- +// Runs the intro camera for a scene. +// by RHY3756547 +// +// includes: main.js +// + +window.cameraIntro = function() { + + var thisObj = this; + this.kart = kart; + this.getView = getView; + this.targetShadowPos = [0, 0, 0] + + var mat = mat4.create(); + + var curCamNum = -1; + var curCam = null; + + var route = null; + var routePos = 0; + var routeSpeed = 0; + var routeProg = 0; + var duration = 0; + var pointInterp = 0; + + var normalFOV = 70; + var zoomLevel = 1; + + var viewW; + var viewH; + + function getView(scene, width, height) { + if (curCam == null) { + restartCam(scene); + } + viewW = width; + viewH = height; + + if (zoomLevel < curCam.zoomMark1) zoomLevel += curCam.zoomSpeedM1; + else if (zoomLevel > curCam.zoomMark2) zoomLevel += curCam.zoomSpeedM2; + else zoomLevel += curCam.zoomSpeed; + + if (zoomLevel > curCam.zoomEnd) zoomLevel = curCam.zoomEnd; + + if (duration-- < 0) { + var cams = scene.nkm.sections["CAME"].entries; + if (curCam.nextCam != -1) { + curCamNum = curCam.nextCam; + curCam = cams[curCamNum]; + zoomLevel = curCam.zoomStart; + + initCam(scene, curCam) + } else { + restartCam(scene); + } + } + + + thisObj.view = camFunc(scene, curCam); + } + + function restartCam(scene) { + var cams = scene.nkm.sections["CAME"].entries; + for (var i=0; i 1) { + routePos = (routePos+1)%route.length; + routeProg = 0; + recalcRouteSpeed(); + } + + pointInterp += (curCam.pointSpeed/100)/60; + if (pointInterp > 1) pointInterp = 1; + + var lookAtPos = vec3.lerp([], curCam.pos2, curCam.pos3, pointInterp) + + vec3.scale(camPos, camPos, 1/1024); + vec3.scale(lookAtPos, lookAtPos, 1/1024); + + var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]); + var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0); + + thisObj.targetShadowPos = lookAtPos; + + return {p:p, mv:mat} + } + + var initCam = function(scene, came) { + var routes = scene.paths; + route = routes[came.camRoute]; + routePos = 0; + routeProg = 0; + duration = came.duration; + recalcRouteSpeed(); + + } + +} \ No newline at end of file diff --git a/Code/Engine/cameras/cameraSpectator.js b/Code/Engine/cameras/cameraSpectator.js new file mode 100644 index 0000000..a89cf49 --- /dev/null +++ b/Code/Engine/cameras/cameraSpectator.js @@ -0,0 +1,216 @@ +// +// cameraSpectator.js +//-------------------- +// Spectates a specific kart. Requires NKM AREA and CAME to be set up correctly. +// by RHY3756547 +// +// includes: main.js +// + +window.cameraSpectator = function(kart) { + + var thisObj = this; + this.kart = kart; + this.getView = getView; + this.targetShadowPos = [0, 0, 0] + + var mat = mat4.create(); + + var curCamNum = -1; + var curCam = null; + + var route = null; + var routePos = 0; + var routeSpeed = 0; + var routeProg = 0; + + var relPos = []; + var posOff = []; + + var normalFOV = 70; + var zoomLevel = 1; + + var viewW; + var viewH; + + function getView(scene, width, height) { + viewW = width; + viewH = height; + + var cams = scene.nkm.sections["CAME"].entries; + var tArea = getNearestArea(scene.nkm.sections["AREA"].entries, kart.pos) + if (tArea.came != curCamNum) { + //restart camera. + curCamNum = tArea.came; + curCam = cams[curCamNum]; + zoomLevel = curCam.zoomStart; + + initCam[curCam.camType](scene, curCam) + } + + if (zoomLevel < curCam.zoomMark1) zoomLevel += curCam.zoomSpeedM1; + else if (zoomLevel > curCam.zoomMark2) zoomLevel += curCam.zoomSpeedM2; + else zoomLevel += curCam.zoomSpeed; + + if (zoomLevel > curCam.zoomEnd) zoomLevel = curCam.zoomEnd; + + thisObj.view = camFunc[curCam.camType](scene, curCam); + return thisObj.view; + } + + var camFunc = []; + + camFunc[1] = function(scene, came) { + var camPos = vec3.lerp([], route[routePos].pos, route[(routePos+1)%route.length].pos, routeProg); + routeProg += routeSpeed; + if (routeProg > 1) { + routePos = (routePos+1)%route.length; + routeProg = 0; + recalcRouteSpeed(); + } + + var lookAtPos = vec3.transformMat4([], [0, 4, 0], kart.mat); + + vec3.scale(camPos, camPos, 1/1024); + vec3.scale(lookAtPos, lookAtPos, 1/1024); + + var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]); + var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0); + + thisObj.targetShadowPos = kart.pos; + + return {p:p, mv:mat} + } + + camFunc[0] = function(scene, came) { //point cam + var camPos = vec3.clone(came.pos1); + + var lookAtPos = vec3.transformMat4([], [0, 4, 0], kart.mat); + + vec3.scale(camPos, camPos, 1/1024); + vec3.scale(lookAtPos, lookAtPos, 1/1024); + + var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]); + var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0); + + thisObj.targetShadowPos = kart.pos; + + return {p:p, mv:mat} + } + + camFunc[5] = function(scene, came) { //dash cam + var basis = kart.basis; + var camPos = vec3.transformMat4([], relPos, basis); + var lookAtPos = vec3.transformMat4([], [0, 0, 0], basis); + + vec3.scale(camPos, camPos, 1/1024); + vec3.scale(lookAtPos, lookAtPos, 1/1024); + + var mat = mat4.lookAt(mat4.create(), camPos, lookAtPos, [0, 1, 0]); + + var off = mat4.create(); + mat4.translate(off, off, [-came.pos3[0]/1024, came.pos3[1]/1024, -came.pos3[2]/1024]); + mat4.mul(mat, off, mat); + + var kpos = vec3.clone(kart.pos); + if (kart.drifting && !kart.driftLanded && kart.ylock>0) kpos[1] -= kart.ylock; + mat4.translate(mat, mat, vec3.scale([], kpos, -1/1024)); + + var p = mat4.perspective(mat4.create(), (zoomLevel*normalFOV/180)*Math.PI, viewW / viewH, 0.01, 10000.0); + + thisObj.targetShadowPos = kart.pos; + + return {p:p, mv:mat} + } + + camFunc[2] = camFunc[0]; + + var initCam = []; + + initCam[1] = function(scene, came) { + var routes = scene.paths; + route = routes[came.camRoute]; + routePos = 0; + routeProg = 0; + recalcRouteSpeed(); + + } + + initCam[2] = function(scene, came) { + } + + function recalcRouteSpeed() { + routeSpeed = (curCam.routeSpeed/100)/60; + //(curCam.routeSpeed/20)/vec3.dist(route[routePos].pos, route[(routePos+1)%route.length].pos); + } + + initCam[5] = function(scene, came) { + var mat = mat4.create(); + mat4.rotateY(mat, mat, (180-came.pos2[0])*(Math.PI/180)); + mat4.rotateX(mat, mat, -came.pos2[1]*(Math.PI/180)); + + + relPos = vec3.transformMat4([], [0, 0, -came.pos2[2]], mat); + /*var basis = kart.basis; + relPos = vec3.sub(relPos, came.pos1, kart.pos); + vec3.transformMat4(relPos, relPos, mat4.invert([], basis));*/ + } + + initCam[0] = initCam[2]; + + + function getNearestArea(areas, pos) { + var smallestDist = Infinity; + var closestArea = null; + for (var i=0; iMath.PI)?(-2*Math.PI+d):d; + } + + function posMod(i, n) { + return (i % n + n) % n; + } + +} \ No newline at end of file diff --git a/Code/Engine/collisionTypes.js b/Code/Engine/collisionTypes.js new file mode 100644 index 0000000..be9cd5e --- /dev/null +++ b/Code/Engine/collisionTypes.js @@ -0,0 +1,336 @@ +// +// collisionTypes.js +//-------------------- +// Includes enums for collision types. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/kcl.js +// + + +window.MKDS_COLSOUNDS = new function() { + this.DRIFT_ASPHALT = 84; + this.DRIFT_CONCRETE = 85; + this.DRIFT_EDGE = 86; //happens when you hit an edge while drifting? + this.DRIFT_DIRT = 87; + this.DRIFT_ROAD = 88; + this.DRIFT_STONE = 89; + this.DRIFT_SAND = 90; + this.DRIFT_ICE = 91; + this.DRIFT_GLASS = 92; + this.DRIFT_WATER = 93; + this.DRIFT_BOARD = 94; //boardwalk! + this.DRIFT_CARPET = 95; //like luigis mansion + this.DRIFT_METALGAUZE = 96; + this.DRIFT_PLASTIC = 97; + this.DRIFT_RAINBOW = 99; + this.DRIFT_MARSH = 100; //luigis mansion + + this.LAND_ASPHALT = 103; + this.LAND_SAND = 104; + this.LAND_DIRT = 105; + this.LAND_ICE = 106; + this.LAND_GRASS = 107; + this.LAND_SNOW = 108; + this.LAND_METALGAUZE = 109; + this.LAND_MARSH = 110; + this.LAND_WATER = 111; + this.LAND_WATERDEEP = 112; + this.LAND_CARPET = 113; + + this.DRIVE_DIRT = 114; + this.DRIVE_GRASS = 115; + this.DRIVE_WATER = 116; + this.DRIVE_STONE = 117; + this.DRIVE_SAND = 118; + this.DRIVE_MARSH = 119; + this.DRIVE_CARPET = 120; + + this.HIT_CAR = 128; + this.HIT_CONCRETE = 129; + this.HIT_FENCE = 130; + this.HIT_WOOD = 131; + this.HIT_TREE = 132; + this.HIT_BUSH = 133; + this.HIT_CLIFF = 134; + this.HIT_SIGN = 135; + this.HIT_ICE = 136; + this.HIT_SNOW = 137; + this.HIT_TABLE = 138; + this.HIT_BOUNCY = 139; + this.HIT_JELLY = 140; + this.HIT_METALGAUZE = 141; + this.HIT_METAL = 142; + + this.BRAKE = 143; + this.BRAKE_CONCRETE = 144; + this.BRAKE_DIRT = 145; + this.BRAKE_STONE = 146; + this.BRAKE_ICE = 147; + this.BRAKE_GLASS = 148; + this.BRAKE_WATER = 149; + this.BRAKE_BOARD = 150; //boardwalk + this.BRAKE_CARPET = 151; + this.BRAKE_METALGAUZE = 152; + this.BRAKE_PLASTIC = 153; + this.BRAKE_METAL = 154; + this.BRAKE_RAINBOW = 155; + this.BRAKE_MARSH = 156; + + this.BRAKE_BOOST = 158; + +} + +window.MKDS_COLTYPE = new (function(){ + this.ROAD = 0x00; + this.OFFROADMAIN = 0x01; + this.OFFROAD3 = 0x02; + this.OFFROAD2 = 0x03; + this.RAINBOWFALL = 0x04; + this.OFFROAD1 = 0x05; + this.SLIPPERY = 0x06; + this.BOOST = 0x07; + this.WALL = 0x08; + this.WALL2 = 0x09; + this.OOB = 0x0A; //voids out the player, returns to lakitu checkpoint. + this.FALL = 0x0B; //like out of bounds, but you fall through it. + this.JUMP_PAD = 0x0C; //jump pads on GBA levels + this.STICKY = 0x0D; //sets gravity to negative this plane's normal until the object hasn't collided for a few frames. + this.SMALLJUMP = 0x0E; //choco island 2's disaster ramps + this.CANNON = 0x0F; //activates cannon. basic effect id is the cannon to use. + this.UNKNOWN = 0x10; //it is a mystery... + this.FALLSWATER = 0x11; //points to falls object in nkm, gets motion parameters from there. + this.BOOST2 = 0x12; + this.LOOP = 0x13; //like sticky but with boost applied. see rainbow road ds + this.SOUNDROAD = 0x14; + this.RR_SPECIAL_WALL = 0x15; + + this.GROUP_ROAD = [ + this.ROAD, this.OFFROAD1, this.OFFROAD2, this.OFFROAD3, this.OFFROAD4, this.SLIPPERY, this.BOOST, + this.JUMP_PAD, this.STICKY, this.SMALLJUMP, this.FALLSWATER, this.BOOST2, this.LOOP, this.SOUNDROAD, + this.OOB, this.OFFROADMAIN + ] + + this.GROUP_SOLID = [ + this.ROAD, this.OFFROAD1, this.OFFROAD2, this.OFFROAD3, this.OFFROAD4, this.SLIPPERY, this.BOOST, + this.JUMP_PAD, this.STICKY, this.SMALLJUMP, this.FALLSWATER, this.BOOST2, this.LOOP, this.SOUNDROAD, + this.OOB, this.OFFROADMAIN, + + this.WALL, this.WALL2, this.RR_SPECIAL_WALL + ] + + this.GROUP_WALL = [ + this.WALL, this.WALL2, this.RR_SPECIAL_WALL + ] + + this.GROUP_BOOST = [ + this.BOOST, this.BOOST2, this.LOOP + ] + + this.PHYS_MAP = new Array(31); + this.PHYS_MAP[this.ROAD] = 0; + this.PHYS_MAP[this.OFFROAD3] = 2; + this.PHYS_MAP[this.OFFROAD2] = 3; + this.PHYS_MAP[this.OFFROAD1] = 4; + this.PHYS_MAP[this.OFFROADMAIN] = 5; + this.PHYS_MAP[this.SLIPPERY] = 6; + this.PHYS_MAP[this.BOOST] = 8; + this.PHYS_MAP[this.BOOST2] = 8; + this.PHYS_MAP[this.FALLSWATER] = 10; + this.PHYS_MAP[this.LOOP] = 11; + + //collision sound handlers + + var waterRoad = {drift: MKDS_COLSOUNDS.DRIFT_WATER, brake: MKDS_COLSOUNDS.BRAKE_WATER, land: MKDS_COLSOUNDS.LAND_WATER, drive: MKDS_COLSOUNDS.DRIVE_WATER}; + + this.SOUNDMAP = { + 0x00: //road + [ + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_STONE, brake: MKDS_COLSOUNDS.BRAKE_STONE, land: MKDS_COLSOUNDS.LAND_ASPHALT, drive: MKDS_COLSOUNDS.DRIVE_STONE}, + {drift: MKDS_COLSOUNDS.DRIFT_CONCRETE, brake: MKDS_COLSOUNDS.BRAKE_CONCRETE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_BOARD, brake: MKDS_COLSOUNDS.BRAKE_BOARD, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_SNOW}, //snow? + + {drift: MKDS_COLSOUNDS.DRIFT_METALGAUZE, brake: MKDS_COLSOUNDS.BRAKE_METALGAUZE, land: MKDS_COLSOUNDS.LAND_METALGAUZE}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + ], + + 0x01: //road 2 the roadening + [ + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_WATER, brake: MKDS_COLSOUNDS.BRAKE_WATER, land: MKDS_COLSOUNDS.LAND_WATERDEEP, drive: MKDS_COLSOUNDS.DRIVE_WATER}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_ASPHALT}, + {}, + {}, + {} + ], + + 0x02: //road 3 + [ + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND , land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + waterRoad, + + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_SNOW}, //snow + + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {}, + {}, + {}, + {} + ], + + 0x03: //road 4 + [ + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND , land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_DIRT, brake: MKDS_COLSOUNDS.BRAKE_DIRT, land: MKDS_COLSOUNDS.LAND_DIRT, drive: MKDS_COLSOUNDS.DRIVE_DIRT}, + + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_GRASS, drive: MKDS_COLSOUNDS.DRIVE_GRASS}, + + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_SNOW}, //snow + {}, + {} + ], + + 0x05: //road 5 + [ + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND , land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_DIRT, brake: MKDS_COLSOUNDS.BRAKE_DIRT, land: MKDS_COLSOUNDS.LAND_DIRT, drive: MKDS_COLSOUNDS.DRIVE_DIRT}, + + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_GRASS, drive: MKDS_COLSOUNDS.DRIVE_GRASS}, + + {drift: MKDS_COLSOUNDS.DRIFT_SAND, brake: MKDS_COLSOUNDS.BRAKE_SAND, land: MKDS_COLSOUNDS.LAND_SAND, drive: MKDS_COLSOUNDS.DRIVE_SAND}, + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land: MKDS_COLSOUNDS.LAND_GRASS, drive: MKDS_COLSOUNDS.DRIVE_GRASS}, + {}, + {}, + {} + ], + + 0x06: //slippery + [ + {drift: MKDS_COLSOUNDS.DRIFT_ICE, brake: MKDS_COLSOUNDS.BRAKE_ICE, land:MKDS_COLSOUNDS.LAND_ICE}, + {drift: MKDS_COLSOUNDS.DRIFT_MARSH, brake: MKDS_COLSOUNDS.BRAKE_MARSH, land:MKDS_COLSOUNDS.LAND_MARSH, drive: MKDS_COLSOUNDS.DRIVE_MARSH}, + {}, + {}, + {}, + {}, + {}, + {} + ], + + 0x07: //bo0st + [ + {drift: MKDS_COLSOUNDS.BRAKE_PLASTIC, brake: MKDS_COLSOUNDS.BRAKE_PLASTIC, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.BRAKE_PLASTIC, brake: MKDS_COLSOUNDS.BRAKE_PLASTIC, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {}, + {}, + {}, + {}, + {}, + {} + ], + + 0x08: //wall + [//placeholders + {hit: MKDS_COLSOUNDS.HIT_CONCRETE}, + {hit: MKDS_COLSOUNDS.HIT_CLIFF}, + {hit: MKDS_COLSOUNDS.HIT_SIGN}, //cliff + {hit: MKDS_COLSOUNDS.HIT_WOOD}, + {hit: MKDS_COLSOUNDS.HIT_BUSH}, + {}, + {hit: MKDS_COLSOUNDS.HIT_JELLY}, + {hit: MKDS_COLSOUNDS.HIT_ICE}, + ], + + 0x09: //wall 2 + [ + {hit: MKDS_COLSOUNDS.HIT_CONCRETE}, + {hit: MKDS_COLSOUNDS.HIT_STONE}, + {hit: MKDS_COLSOUNDS.HIT_METAL}, + {hit: MKDS_COLSOUNDS.HIT_WOOD}, + {hit: MKDS_COLSOUNDS.HIT_BUSH}, + {}, + {hit: MKDS_COLSOUNDS.HIT_JELLY}, + {hit: MKDS_COLSOUNDS.HIT_ICE}, + ], + + 0x10: //wall 3 + [ + {hit: MKDS_COLSOUNDS.HIT_CONCRETE}, + {}, + {}, + {}, + {}, + {}, + {}, + {}, + ], + + 0x15: //wall with sound effect + [ + {hit: MKDS_COLSOUNDS.HIT_CONCRETE}, + {hit: MKDS_COLSOUNDS.HIT_STONE}, + {hit: MKDS_COLSOUNDS.HIT_RAINBOW}, //only diff i think + {hit: MKDS_COLSOUNDS.HIT_WOOD}, + {hit: MKDS_COLSOUNDS.HIT_BUSH}, + {}, + {hit: MKDS_COLSOUNDS.HIT_JELLY}, + {hit: MKDS_COLSOUNDS.HIT_ICE}, + ], + + 0x11: [ //yoshi falls water + waterRoad, + waterRoad, + waterRoad, + waterRoad, + waterRoad, + waterRoad, + waterRoad, + waterRoad + ], + + 0x12: //boost + [ + {drift: MKDS_COLSOUNDS.BRAKE_PLASTIC, brake: MKDS_COLSOUNDS.BRAKE_PLASTIC, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {}, + {}, + {}, + {}, + {}, + {}, + {} + ], + + 0x13: //looping + [ + {drift: MKDS_COLSOUNDS.DRIFT_ASPHALT, brake: MKDS_COLSOUNDS.BRAKE, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {drift: MKDS_COLSOUNDS.DRIFT_RAINBOW, brake: MKDS_COLSOUNDS.BRAKE_RAINBOW, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {}, + {}, + {}, + {}, + {}, + {} + ], + + 0x14: //road with sfx + [ + {}, + {drift: MKDS_COLSOUNDS.DRIFT_CARPET, brake: MKDS_COLSOUNDS.BRAKE_CARPET, land:MKDS_COLSOUNDS.LAND_CARPET, drive: MKDS_COLSOUNDS.DRIVE_CARPET}, + {drift: MKDS_COLSOUNDS.DRIFT_RAINBOW, brake: MKDS_COLSOUNDS.BRAKE_RAINBOW, land:MKDS_COLSOUNDS.LAND_ASPHALT}, + {}, + {}, //stairs + {}, + {}, + {} + ] + } + +})() \ No newline at end of file diff --git a/Code/Engine/controls/controlDefault.js b/Code/Engine/controls/controlDefault.js new file mode 100644 index 0000000..9afc54d --- /dev/null +++ b/Code/Engine/controls/controlDefault.js @@ -0,0 +1,35 @@ +// +// controlDefault.js +//-------------------- +// Provides default (keyboard) controls for kart. In future there will be an AI controller and default will support gamepad. +// by RHY3756547 +// +// includes: main.js +// + +window.controlDefault = function() { + + var thisObj = this; + this.local = true; + var kart; + + this.setKart = function(k) { + kart = k; + thisObj.kart = k; + } + this.fetchInput = fetchInput; + + function fetchInput() { + return { + accel: keysArray[88], //x + decel: keysArray[90], //z + drift: keysArray[83], //s + item: keysArray[65], //a + + //-1 to 1, intensity. + turn: (keysArray[37]?-1:0)+(keysArray[39]?1:0), + airTurn: (keysArray[40]?-1:0)+(keysArray[38]?1:0) //air excitebike turn, doesn't really have much function + }; + } + +} \ No newline at end of file diff --git a/Code/Engine/controls/controlNetwork.js b/Code/Engine/controls/controlNetwork.js new file mode 100644 index 0000000..fa60bdc --- /dev/null +++ b/Code/Engine/controls/controlNetwork.js @@ -0,0 +1,41 @@ +// +// controlDefault.js +//-------------------- +// Provides default (keyboard) controls for kart. In future there will be an AI controller and default will support gamepad. +// by RHY3756547 +// +// includes: main.js +// + +window.controlNetwork = function() { + + var t = this; + var kart; + + this.local = false; + this.turn = 0; + this.airTurn = 0; + this.binput = 0; + + this.setKart = function(k) { + kart = k; + t.kart = k; + } + this.fetchInput = fetchInput; + + function fetchInput() { + //local controllers generally just return input and handle items - the network controller restores kart data from the stream sent from the server. Obviously this data needs to be verified by the server... + + return { + accel: t.binput&1, //x + decel: t.binput&2, //z + drift: t.binput&4, //s + item: false,//keysArray[65], //a + + //-1 to 1, intensity. + turn: t.turn,//(keysArray[37]?-1:0)+(keysArray[39]?1:0), + airTurn: t.airTurn//(keysArray[40]?-1:0)+(keysArray[38]?1:0) //air excitebike turn, doesn't really have much function + }; + } + +} \ No newline at end of file diff --git a/Code/Engine/controls/controlRaceCPU.js b/Code/Engine/controls/controlRaceCPU.js new file mode 100644 index 0000000..e43741b --- /dev/null +++ b/Code/Engine/controls/controlRaceCPU.js @@ -0,0 +1,141 @@ +// +// controlRaceCPU.js +//-------------------- +// Provides AI control for default races +// by RHY3756547 +// +// includes: main.js +// + +window.controlRaceCPU = function(nkm) { + + var thisObj = this; + var kart; + + this.setKart = function(k) { + kart = k; + thisObj.kart = k; + calcDestNorm(); + } + + this.fetchInput = fetchInput; + + var battleMode = (nkm.sections["EPAT"] == null); + + var paths, points; + if (battleMode) { //MEEPO!! + var paths = nkm.sections["MEPA"].entries; + var points = nkm.sections["MEPO"].entries; + } else { + var paths = nkm.sections["EPAT"].entries; + var points = nkm.sections["EPOI"].entries; + } + + var ePath = paths[0]; + var ePoiInd = ePath.startInd; + var ePoi = points[ePath.startInd]; + + var posOffset = [0, 0, 0]; + var destOff = [0, 0, 0]; + var offTrans = 0; + chooseNewOff(); + + var destNorm; + var destConst; + var destPoint; + + function fetchInput() { + //basically as a cpu, we're really dumb and need a constant supply of points to drive to. + //battle mode AI is a lot more complex, but since we're only going in one direction it can be kept simple. + + var accel = true; //currently always driving forward. should change for sharp turns and when we get stuck on a wall + //(drive in direction of wall? we may need to reverse, "if stuck for too long we can just call lakitu and the players won't even notice" - Nintendo) + + var dist = vec3.dot(destNorm, kart.pos) + destConst; + if (dist < ePoi.pointSize) advancePoint(); + + destPoint = vec3.add([], ePoi.pos, vec3.scale([], vec3.lerp([], posOffset, destOff, offTrans), ePoi.pointSize)); + var dirToPt = Math.atan2(destPoint[0]-kart.pos[0], kart.pos[2]-destPoint[2]); + + var diff = dirDiff(dirToPt, kart.physicalDir); + var turn = Math.min(Math.max(-1, (diff*3)), 1); + + offTrans += 1/240; + + if (offTrans >= 1) chooseNewOff(); + + return { + accel: accel, //x + decel: false, //z + drift: false, //s + item: false, //a + + //-1 to 1, intensity. + turn: turn, + airTurn: 0 //air excitebike turn, doesn't really have much function + }; + } + + function chooseNewOff() { + posOffset = destOff; + var ang = Math.random()*Math.PI*2; + var strength = Math.random(); + destOff = [Math.sin(ang)*strength, 0, Math.cos(ang)*strength]; + offTrans = 0; + } + + + function calcDestNorm() { + var norm = vec3.sub([], kart.pos, ePoi.pos); + vec3.normalize(norm, norm); + + destNorm = norm; + destConst = -vec3.dot(ePoi.pos, norm) + + } + + function advancePoint() { + if (++ePoiInd < ePath.startInd+ePath.pathLen) { + //next within this path + ePoi = points[ePoiInd]; + } else { + //advance to one of next possible paths + + if (battleMode) { + var pathInd = ((Math.random()>0.5 && ePath.source.length>0)?ePath.source:ePath.dest)[Math.floor(Math.random()*ePath.dest.length)]; + ePoiInd = pathInd; + ePoi = points[ePoiInd]; + recomputePath(); + } else { + var pathInd = ePath.dest[Math.floor(Math.random()*ePath.dest.length)]; + ePath = paths[pathInd]; + ePoi = points[ePath.startInd]; + ePoiInd = ePath.startInd; + } + } + calcDestNorm(); + } + + function recomputePath() { //use if point is set by anything but the path system, eg. respawn + for (var i=0; i= 0 && rel < paths[i].pathLen) { + ePath = paths[i]; + } + } + } + + function fixDir(dir) { + return posMod(dir, Math.PI*2); + } + + function dirDiff(dir1, dir2) { + var d = fixDir(dir1-dir2); + return (d>Math.PI)?(-2*Math.PI+d):d; + } + + function posMod(i, n) { + return (i % n + n) % n; + } + +} \ No newline at end of file diff --git a/Code/Engine/ingameRes.js b/Code/Engine/ingameRes.js new file mode 100644 index 0000000..1269aea --- /dev/null +++ b/Code/Engine/ingameRes.js @@ -0,0 +1,100 @@ +// +// ingameRes.js +//-------------------- +// Provides access to general ingame resources. +// by RHY3756547 +// + +window.IngameRes = function(rom) { + var r = this; + this.kartPhys = new kartphysicalparam(rom.getFile("/data/KartModelMenu/kartphysicalparam.bin")); + this.kartOff = new kartoffsetdata(rom.getFile("/data/KartModelMenu/kartoffsetdata.bin")); + this.MapObj = new narc(lz77.decompress(rom.getFile("/data/Main/MapObj.carc"))); //contains generic map obj, look in here when mapobj res is missing from course. (itembox etc) + this.MainRace = new narc(lz77.decompress(rom.getFile("/data/MainRace.carc"))); //contains item models. + this.MainEffect = new narc(lz77.decompress(rom.getFile("/data/MainEffect.carc"))); //contains particles. + this.Main2D = new narc(lz77.decompress(rom.getFile("/data/Main2D.carc"))); + + this.KartModelSub = new narc(lz77.decompress(rom.getFile("/data/KartModelSub.carc"))); //contains characters + animations + + this.Race = new narc(lz77.decompress(rom.getFile("/data/Scene/Race.carc"))); //contains lakitu, count, various graphics + this.RaceLoc = new narc(lz77.decompress(rom.getFile("/data/Scene/Race_us.carc"))); //contains lakitu lap signs, START, YOU WIN etc. some of these will be replaced by hi res graphics by default. + + this.MainFont = new nftr(r.Main2D.getFile("marioFont.NFTR")); + //debugger; + + this.getChar = getChar; + this.getKart = getKart; + + var itemNames = [ + "banana", "bomb", "gesso" /*squid*/, "kinoko" /*mushroom*/, "kinoko_p" /*queen shroom*/, "koura_g" /*green shell*/, "koura_r" /*red shell*/, "star", "teresa" /*boo*/, "thunder", + "koura_w" /*blue shell item rep*/, "f_box", "killer" /*bullet bill*/ + ] + + var charNames = [ + "mario", "donkey", "kinopio", "koopa", "peach", "wario", "yoshi", "luigi", "karon", "daisy", "waluigi", "robo", "heyho" + ] + + var charAbbrv = [ + "MR", "DK", "KO", "KP", "PC", "WR", "YS", "LG", "KA", "DS", "WL", "RB", "HH" + ] + + var tireName = ["kart_tire_L", "kart_tire_M", "kart_tire_S"]; + + var characters = []; + var karts = []; + + loadItems(); + loadTires(); + + function loadItems() { //loads physical representations of items + var t = {} + for (var i=0; i0 && newT t1) { //make sure t0 is smallest value + var temp = t1; + t1 = t0; + t0 = temp; + } + + if (!(t0>1 || t1<0)) { + //we will intersect this triangle's plane within this frame. + // + // Three things can happen for the earliest intersection: + // - sphere intersects plane of triangle (pt on plane projected from new position is inside triangle) + // - sphere intersects edge of triangle + // - sphere intersects point of triangle + + if (t0 < 0) { embedded = true; t0 = 0; } + if (t1 > 1) t1 = 1; + + var newT = t0; + + //sphere intersects plane of triangle + var pt = []; + if (embedded) { + vec3.sub(pt, pos, vec3.scale([], tri.Normal, dist)); + } else { + vec3.add(pt, pos, vec3.scale([], dir, newT)) + vec3.sub(pt, pt, tri.Normal); //project new position onto plane along normal + } + if (pointInTriangle(tri, pt, 0) && newT= 0 && edgePos <= 1) { + t = root; + colPlane = oTri; + colO = targ; + colPoint = vec3.add([], vert, vec3.scale(distLine, distLine, edgePos)); //result! + planeNormal = tri.Normal; + edge = true; + } + } + } + + } + } + } + + function getSmallestRoot(a, b, c, upperLimit) { + var det = (b*b) - 4*(a*c); + if (det<0) return null; //no result :'( + else { + det = Math.sqrt(det); + var root1 = ((-b)-det)/(2*a) + var root2 = ((-b)+det)/(2*a) + + if (root1 > root2) { //ensure root1 is smallest + var temp = root1; + root1 = root2; + root2 = temp; + } + + if (root1>0 && root10 && root2=-error && v>=-error && (u+v)<1+error); + } + + function getTriList(pos, diff, kclO) { //gets tris from kcl around a line. currently only fetches from middle point of line, but should include multiple samples for large differences in future. + var sample = vec3.add([], pos, vec3.scale([], diff, 0.5)) + return kclO.getPlanesAt(sample[0], sample[1], sample[2]); + } + +})(); \ No newline at end of file diff --git a/Code/Engine/mkdsConst.js b/Code/Engine/mkdsConst.js new file mode 100644 index 0000000..fe66624 --- /dev/null +++ b/Code/Engine/mkdsConst.js @@ -0,0 +1,113 @@ +// +// mkdsConst.js +//-------------------- +// Provides various game constants. +// by RHY3756547 +// + +window.MKDSCONST = new (function() { + + this.COURSEDIR = "/data/Course/"; + + this.COURSES = [ //in order of course id, nitro through retro + "cross_course", + "bank_course", + "beach_course", + "mansion_course", + + "desert_course", + "town_course", + "pinball_course", + "ridge_course", + + "snow_course", + "clock_course", + "mario_course", + "airship_course", + + "stadium_course", + "garden_course", + "koopa_course", + "rainbow_course", + + + "old_mario_sfc", + "old_momo_64", + "old_peach_agb", + "old_luigi_gc", + + "old_donut_sfc", + "old_frappe_64", + "old_koopa_agb", + "old_baby_gc", + + "old_noko_sfc", + "old_choco_64", + "old_luigi_agb", + "old_kinoko_gc", + + "old_choco_sfc", + "old_hyudoro_64", + "old_sky_agb", + "old_yoshi_gc", + + "mini_stage1", + "mini_stage2", + "mini_stage3", + "mini_stage4", + "mini_block_64", + "mini_dokan_gc" + + ] + + this.COURSE_MUSIC = [ + 74, + 16, + 15, + 21, + + 38, + 17, + 19, + 36, + + 37, + 39, + 74, + 18, + + 19, + 20, + 40, + 41, + + + 22, + 30, + 26, + 33, + + 24, + 31, + 27, + 34, + + 23, + 29, + 26, + 35, + + 25, + 32, + 28, + 33, + + 43, + 43, + 43, + 43, + 43, + 43 + ] + +})(); \ No newline at end of file diff --git a/Code/Engine/scenes/clientScene.js b/Code/Engine/scenes/clientScene.js new file mode 100644 index 0000000..3f46158 --- /dev/null +++ b/Code/Engine/scenes/clientScene.js @@ -0,0 +1,156 @@ +// +// clientScene.js +//-------------------- +// Manages the game state when connected to a server. Drives the course scene and track picker. +// by RHY3756547 +// + +window.clientScene = function(wsUrl, wsInstance, res) { + var res = res; //gameRes + var t = this; + + var WebSocket = window.WebSocket || window.MozWebSocket; + var ws = new WebSocket(wsUrl); + ws.binaryType = "arraybuffer"; + + t.ws = ws; + t.mode = -1; + t.activeScene = null; + t.myKart = null; + + ws.onopen = function() { + console.log("initial connection") + //first we need to establish connection to the instance. + var obj = { + t:"*", + i:wsInstance, + c:{ + name:"TestUser"+Math.round(Math.random()*10000), + char:Math.floor(Math.random()*12), + kart:Math.floor(Math.random()*0x24) + } + } + sendJSONMessage(obj); + }; + + ws.onmessage = function(evt) { + var d = evt.data; + if (typeof d != "string") { + //binary data + var view = new DataView(d); + var handler = binH[view.getUint8(0)]; + if (handler != null) handler(view); + } else { + //JSON string + var obj; + try { + obj = JSON.parse(d); + } catch (err) { + debugger; //packet recieved from server is bullshit + return; + } + var handler = wsH["$"+obj.t]; + if (handler != null) handler(obj); + } + } + + this.update = function() { + if (t.activeScene != null) t.activeScene.update(); + if (t.myKart != null) sendKartInfo(t.myKart); + } + + this.render = function() { + if (t.activeScene != null) sceneDrawer.drawTest(gl, t.activeScene, 0, 0, gl.viewportWidth, gl.viewportHeight) + } + + function abFromBlob(blob, callback) { + var fileReader = new FileReader(); + fileReader.onload = function() { + callback(this.result); + }; + fileReader.readAsArrayBuffer(blob); + } + + function sendKartInfo(kart) { + var dat = new ArrayBuffer(0x61); + var view = new DataView(dat); + view.setUint8(0, 32); + netKart.saveKart(view, 1, kart, kart.lastInput); + ws.send(dat); + } + + var wsH = {}; + wsH["$*"] = function(obj) { //initiate scene. + t.myKart = null; + if (obj.m == 1) { //race + t.mode = 1; + + var mainNarc, texNarc + if (obj.c.substr(0, 5) == "mkds/") { + var cnum = Number(obj.c.substr(5)); + var music = MKDSCONST.COURSE_MUSIC[cnum]; + var cDir = MKDSCONST.COURSEDIR+MKDSCONST.COURSES[cnum]; + var mainNarc = new narc(lz77.decompress(gameROM.getFile(cDir+".carc"))); + var texNarc = new narc(lz77.decompress(gameROM.getFile(cDir+"Tex.carc"))); + setUpCourse(mainNarc, texNarc, music, obj) + } + else throw "custom tracks are not implemented yet!" + } + } + + wsH["$+"] = function(obj) { //add kart. only used in debug circumstances. (people can't join normal gamemodes midgame) + console.log("kart added"); + if (t.mode != 1) return; + var kart = new Kart([0, -2000, 0], 0, 0, obj.k.kart, obj.k.char, new ((obj.p)?((window.prompt("press y for cpu controlled") == "y")?controlRaceCPU:controlDefault):controlNetwork)(t.activeScene.nkm, {}), t.activeScene); + t.activeScene.karts.push(kart); + } + + wsH["$-"] = function(obj) { //kart disconnect. + t.activeScene.karts[obj.k].active = false; + } + + var binH = []; + binH[32] = function(view) { + //if we are in a race, update kart positions in main scene. we should trust the server on this, however if anything goes wrong it will be caught earlier. + if (t.mode != 1) return; + + var n = view.getUint16(0x01, true); + var off = 0x03; + for (var i=0; i -1) { + musicRestartTimer++; + if (musicRestartTimer > musicRestart) { + scn.musicPlayer = nitroAudio.playSound(music, {volume:2, bpmMultiplier:(musicRestartType==0)?1.25:1}, null); + musicRestartTimer = -1; + } + } + + for (var i=0; i winPercent) continue; + finishTuple = finishPercents[i]; + } + + kart.controller = new controlRaceCPU(scn.nkm, {}); + kart.controller.setKart(kart); + + kart.anim.setAnim(winPercent>0.5?kart.charRes.LoseA:kart.charRes.winA); + kart.animMode = "raceEnd"; + + scn.camera = (new cameraSpectator(kart, scn)); + nitroAudio.playSound(finishTuple[1], {volume:2}, 0); + nitroAudio.playSound(finishTuple[2], {volume:2}, null); + nitroAudio.instaKill(scn.musicPlayer); + musicRestartTimer = 0; + musicRestart = 7.5*60; + musicRestartType = 1; + music = finishTuple[3]; + scn.entities.push(new Race3DUI(scn, "goal")); + } + else if (kart.lapNumber < 4) nitroAudio.playSound(65, {volume:2}, 0); + } + + if (kart.lapNumber == 4) finishers.push(kart); + } + + function startPosition(toAline, xspacing, yspacing, liney, angle, i) { + var horizN = i%toAline; + var vertN = Math.floor(i/toAline); + var staggered = (vertN%2); //second line moves 1/2 x spacing to the right + var relPos = [(horizN-(toAline/2)-0.25)*xspacing+staggered*0.5, 8, -(horizN*yspacing + vertN*liney)]; + var mat = mat4.rotateY([], mat4.create(), angle*(Math.PI/180)); + vec3.transformMat4(relPos, relPos, mat); + return relPos; + } + + function loadRes(res, id) { + var models = []; + + for (var i=0; i 0) { + //beeps for countdown + nitroAudio.playSound(39, {bpmMultiplier:16}, 0); + } + break; + case 2: + //show ui and play music at certain time after go + + if (mode.time == 1) { + scn.musicPlayer = nitroAudio.playSound(music, {volume:2}, null); + } + // + break; + } + } + + //win sting: 46 + //ok sting: 47 + //lose sting: 48 + //battle lose sting: 49 + //battle win sting: 50 + //ok sting??: 51 + //mission mode win sting: 52 + //mission mode win2 sting: 53 + //mission mode superwin sting: 54 + //boss win sting: 55 + //ok music: 56 + //lose music: 57 + //win music: 58 + //racelose : 61 + //ok music: 58 + //good time trials music: 59 + //ok time trials: 60 + + //final lap: 62 + + //full results win: 63 + //results draw: 64 + //full results lose: 65 + //gp results cutscene music: 66 + //gp results win music: 67 + //??? : 68 + //credits: 69-70 + // star: 73 + + scn.mode = mode; + } +} diff --git a/Code/Engine/scenes/sceneDrawer.js b/Code/Engine/scenes/sceneDrawer.js new file mode 100644 index 0000000..b010166 --- /dev/null +++ b/Code/Engine/scenes/sceneDrawer.js @@ -0,0 +1,132 @@ +// +// sceneDrawer.js +//-------------------- +// Provides functions to draw scenes in various ways. +// by RHY3756547 +// + +window.sceneDrawer = new function() { + var gl, shadowTarg; + + var shadowRes = 2048; + + this.init = function(gl) { + gl = gl; + shadowTarg = createRenderTarget(gl, shadowRes, shadowRes, true); + } + + this.drawWithShadow = function(gl, scn, x, y, width, height) { + if (scn.lastWidth != width || scn.lastHeight != height) { + scn.lastWidth = width; + scn.lastHeight = height; + scn.renderTarg = createRenderTarget(gl, width, height, true); + } + + var view = scn.camera.getView(scn, width, height); + var viewProj = mat4.mul(view.p, view.p, view.mv); + + var shadMat = scn.shadMat; + + if (scn.farShad == null) { + scn.farShad = createRenderTarget(gl, shadowRes*2, shadowRes*2, true); + gl.viewport(0, 0, shadowRes*2, shadowRes*2); + gl.bindFramebuffer(gl.FRAMEBUFFER, scn.farShad.fb); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(false, false, false, false); + scn.draw(gl, scn.farShadMat, true); + } + + gl.viewport(0, 0, shadowRes, shadowRes); + gl.bindFramebuffer(gl.FRAMEBUFFER, shadowTarg.fb); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(false, false, false, false); + scn.draw(gl, shadMat, true); + + gl.viewport(0, 0, width, height); + gl.bindFramebuffer(gl.FRAMEBUFFER, scn.renderTarg.fb); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(true, true, true, true); + scn.draw(gl, viewProj, false); + + scn.sndUpdate(view.mv); + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + gl.viewport(x, y, width, height); + shadowRender.drawShadowed(scn.renderTarg.color, scn.renderTarg.depth, shadowTarg.depth, scn.farShad.depth, viewProj, shadMat, scn.farShadMat) + } + + this.drawTest = function(gl, scn, x, y, width, height) { + + var view = scn.camera.view; //scn.camera.getView(scn, width, height); + + var viewProj = mat4.mul(mat4.create(), view.p, view.mv); + view = {p: viewProj, mv: view.mv}; + + var shadMat = scn.shadMat; + + nitroRender.unsetShadowMode(); + nitroRender.flagShadow = true; + nitroRender.updateBillboards(scn.lightMat); + + if (scn.farShad == null) { + scn.farShad = createRenderTarget(gl, shadowRes*2, shadowRes*2, true); + gl.viewport(0, 0, shadowRes*2, shadowRes*2); + gl.bindFramebuffer(gl.FRAMEBUFFER, scn.farShad.fb); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(false, false, false, false); + scn.draw(gl, scn.farShadMat, true); + } + + gl.viewport(0, 0, shadowRes, shadowRes); + gl.bindFramebuffer(gl.FRAMEBUFFER, shadowTarg.fb); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(false, false, false, false); + scn.draw(gl, shadMat, true); + + nitroRender.setShadowMode(shadowTarg.depth, scn.farShad.depth, shadMat, scn.farShadMat); + nitroRender.flagShadow = false; + + nitroRender.updateBillboards(view.mv); + gl.viewport(x, y, width, height); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + gl.colorMask(true, true, true, true); + scn.draw(gl, viewProj, false); + + scn.sndUpdate(view.mv); + + } + + function createRenderTarget(gl, xsize, ysize, depth) { + var depthTextureExt = gl.getExtension("WEBGL_depth_texture"); + if (!depthTextureExt) alert("depth texture not supported! we're DOOMED! jk we'll just have to add a fallback for people with potato gfx"); + + var colorTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, colorTexture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, xsize, ysize, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + var depthTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, depthTexture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, xsize, ysize, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null); + + var framebuffer = gl.createFramebuffer(); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorTexture, 0); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0); + + return { + color: colorTexture, + depth: depthTexture, + fb: framebuffer + } + } +} \ No newline at end of file diff --git a/Code/Engine/scenes/singleScene.js b/Code/Engine/scenes/singleScene.js new file mode 100644 index 0000000..8e23ed1 --- /dev/null +++ b/Code/Engine/scenes/singleScene.js @@ -0,0 +1,86 @@ +// +// singleScene.js +//-------------------- +// Drives the course scene when not connected to a server. Simulates responses expected from a server. +// by RHY3756547 +// + +window.singleScene = function(course, wsInstance, res) { + var res = res; //gameRes + var t = this; + + t.mode = -1; + t.activeScene = null; + t.myKart = null; + + var mchar = Math.floor(Math.random()*12); + var mkart = Math.floor(Math.random()*0x24); + + this.update = function() { + if (t.activeScene != null) { + t.activeScene.update(); + //simulate what a server would do + updateServer(); + } + } + + var advanceTimes = [3,4,-1,-1] + + function updateServer() { + var m = t.mode; + m.frameDiv++; + if (m.frameDiv == 60) { + m.frameDiv -= 60; + m.time++; + var timeAd = advanceTimes[m.id]; + if (timeAd != -1 && m.time >= timeAd) { + m.id++; + m.time = 0; + } + } + + t.activeScene.updateMode(JSON.parse(JSON.stringify(t.mode))); + } + + this.render = function() { + if (t.activeScene != null) sceneDrawer.drawTest(gl, t.activeScene, 0, 0, gl.viewportWidth, gl.viewportHeight) + } + + begin(course); + + function begin(course) { + var mainNarc, texNarc + if (course.substr(0, 5) == "mkds/") { + var cnum = Number(course.substr(5)); + var music = MKDSCONST.COURSE_MUSIC[cnum]; + var cDir = MKDSCONST.COURSEDIR+MKDSCONST.COURSES[cnum]; + var mainNarc = new narc(lz77.decompress(gameROM.getFile(cDir+".carc"))); + var texNarc = new narc(lz77.decompress(gameROM.getFile(cDir+"Tex.carc"))); + setUpCourse(mainNarc, texNarc, music) + } else throw "custom tracks are not implemented yet!" + } + + + function setUpCourse(mainNarc, texNarc, music) { + var chars = []; + chars.push({charN:mchar, kartN:mkart, controller:((window.prompt("press y for cpu controlled") == "y")?controlRaceCPU:controlDefault), raceCam:true, extraParams:[{k:"name", v:"single"}, {k:"active", v:true}]}); + + for (var i=0; i<7; i++) { + var tchar = Math.floor(Math.random()*12); + var tkart = Math.floor(Math.random()*0x24); + + chars.push({charN:tchar, kartN:tkart, controller:controlRaceCPU, raceCam:false, extraParams:[{k:"name", v:"no"}, {k:"active", v:true}]}); + } + + t.activeScene = new courseScene(mainNarc, texNarc, music, chars, {}, res); + + t.myKart = t.activeScene.karts[0]; + t.mode = { + id:0, + time:0, + frameDiv:0, + } + t.activeScene.updateMode(t.mode); + } + +} \ No newline at end of file diff --git a/Code/Engine/storage/fileStore.js b/Code/Engine/storage/fileStore.js new file mode 100644 index 0000000..dc737bf --- /dev/null +++ b/Code/Engine/storage/fileStore.js @@ -0,0 +1,83 @@ +window.fileStore = new (function(){ + var db; + var indexedDB; + + this.requestGameFiles = requestGameFiles; + + function requestGameFiles(callback) { + indexedDB = window.indexedDB + || window.webkitIndexedDB + || window.mozIndexedDB + || window.shimIndexedDB; + + var request = indexedDB.open("MKJS_DB", 1); + request.onerror = window.onerror; + + request.onsuccess = function(event) { + db = event.target.result; + loadGameFiles(callback); + } + + request.onupgradeneeded = function(event) { + db = event.target.result; + var objectStore = db.createObjectStore("files", { keyPath: "filename" }); + objectStore.transaction.oncomplete = function(event) { + loadGameFiles(callback); + } + } + } + + function loadGameFiles(callback) { + var transaction = db.transaction(["files"]); + var objectStore = transaction.objectStore("files"); + var request = objectStore.get("mkds.nds"); + request.onerror = function(event) { + alert("Fatal database error!"); + }; + request.onsuccess = function(event) { + if (request.result == null) downloadGame("Mario Kart DS.nds", callback); + else callback(request.result.data); + }; + } + + function downloadGame(url, callback) { + if (typeof url == "string") { + var xml = new XMLHttpRequest(); + xml.open("GET", url, true); + xml.responseType = "arraybuffer"; + xml.onload = function() { + storeGame(xml.response, callback); + } + xml.send(); + } else { + alert("You need to supply MKJS with a Mario Kart DS ROM to function. Click anywhere on the page to load a file.") + fileCallback = callback; + document.getElementById("fileIn").onchange = fileInChange; + waitForROM = true; + } + } + + function fileInChange(e) { + var bFile = e.target.files[0]; + var bReader = new FileReader(); + bReader.onload = function(e) { + waitForROM = false; //todo: verify + storeGame(e.target.result, fileCallback); + }; + bReader.readAsArrayBuffer(bFile); + } + + function storeGame(dat, callback) { + var transaction = db.transaction(["files"], "readwrite"); + var objectStore = transaction.objectStore("files"); + var request = objectStore.put({filename:"mkds.nds", data:dat}); + + request.onerror = function(event) { + alert("Failed to store game locally!"); + callback(dat); + }; + request.onsuccess = function(event) { + callback(dat); + }; + } +})(); \ No newline at end of file diff --git a/Code/Entities/bowserPlatforms.js b/Code/Entities/bowserPlatforms.js new file mode 100644 index 0000000..972f45d --- /dev/null +++ b/Code/Entities/bowserPlatforms.js @@ -0,0 +1,196 @@ +// +// bowserPlatforms.js +//-------------------- +// Provides platforms for Bowser's Castle +// by RHY3756547 +// +// includes: +// render stuff idk +// + +window.ObjRotaryRoom = function(obji, scene) { + var obji = obji; + var res = []; + + var t = this; + + t.collidable = true; + t.colMode = 0; + t.colRad = 512; + t.getCollision = getCollision; + t.moveWith = moveWith; + + t.pos = vec3.clone(obji.pos); + //t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + t.speed = (obji.setting1&0xFFFF)/8192; + t.angle = 0; + + var dirVel = 0; + + function update(scene) { + dirVel = t.speed; + t.angle += dirVel; + } + + function draw(view, pMatrix) { + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + mat4.rotateY(mat, mat, t.angle); + res.mdl[0].draw(mat, pMatrix); + } + + function requireRes() { //scene asks what resources to load + return {mdl:[{nsbmd:"rotary_room.nsbmd"}]}; + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + } + + function getCollision() { + var obj = {}; + var inf = res.mdl[0].getCollisionModel(0, 0); + obj.tris = inf.dat; + + var mat = mat4.translate([], mat4.create(), t.pos); + mat4.scale(mat, mat, vec3.mul([], [16*inf.scale, 16*inf.scale, 16*inf.scale], t.scale)); + mat4.rotateY(mat, mat, t.angle); + + obj.mat = mat; + return obj; + } + + function moveWith(obj) { //used for collidable objects that move. + var p = vec3.sub([], obj.pos, t.pos); + vec3.transformMat4(p, p, mat4.rotateY([], mat4.create(), dirVel)); + vec3.add(obj.pos, t.pos, p); + obj.physicalDir -= dirVel; + } + +} + +window.ObjRoutePlatform = function(obji, scene) { + var obji = obji; + var res = []; + var genCol; + + var t = this; + + t.collidable = true; + t.colMode = 0; + t.colRad = 512; + t.getCollision = getCollision; + t.moveWith = moveWith; + + t.pos = vec3.clone(obji.pos); + //t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + generateCol(); + + t.statDur = (obji.setting1&0xFFFF); + t.route = scene.paths[obji.routeID]; + t.routeSpeed = 1/6; + t.routePos = 0; + t.nextNode = t.route[t.routePos]; + t.prevPos = t.pos; + t.elapsedTime = 0; + + t.mode = 0; + + var movVel; + + //t.speed = (obji.setting1&0xFFFF)/8192; + + function update(scene) { + if (t.mode == 0) { + t.elapsedTime += t.routeSpeed; + movVel = vec3.sub([], t.nextNode.pos, t.prevPos); + //vec3.normalize(movVel, movVel); + vec3.scale(movVel, movVel, t.routeSpeed/t.nextNode.duration); + vec3.add(t.pos, t.pos, movVel); + if (t.elapsedTime >= t.nextNode.duration) { + t.elapsedTime = 0; + t.prevPos = t.nextNode.pos; + t.routePos = (t.routePos+1)%t.route.length; + t.nextNode = t.route[t.routePos]; + t.mode = 1; + } + } else { + t.elapsedTime += 1; + movVel = [0, 0, 0]; + if (t.elapsedTime > t.statDur) { + t.mode = 0; + t.elapsedTime = 0; + } + } + } + + function draw(view, pMatrix) { + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + res.mdl[0].draw(mat, pMatrix); + } + + function requireRes() { //scene asks what resources to load + return {mdl:[{nsbmd:"koopa_block.nsbmd"}]}; //25x, 11y + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + } + + function generateCol() { + genCol = {dat: [ + { + Vertex1: [25, 0, 11], + Vertex2: [25, 0, -11], + Vertex3: [-25, 0, -11], + Normal: [0, 1, 0] + }, + { + Vertex1: [-25, 0, -11], + Vertex2: [-25, 0, 11], + Vertex3: [25, 0, 11], + Normal: [0, 1, 0] + }, + ], scale: 1}; + } + + function getCollision() { + var obj = {}; + var inf = genCol;//res.mdl[0].getCollisionModel(0, 0); + obj.tris = inf.dat; + + var mat = mat4.translate([], mat4.create(), t.pos); + mat4.scale(mat, mat, vec3.mul([], [16*inf.scale, 16*inf.scale, 16*inf.scale], t.scale)); + + obj.mat = mat; + return obj; + } + + function moveWith(obj) { //used for collidable objects that move. + /*var p = vec3.sub([], obj.pos, t.pos); + vec3.transformMat4(p, p, mat4.rotateY([], mat4.create(), dirVel)); + vec3.add(obj.pos, t.pos, p); + obj.physicalDir -= dirVel;*/ + vec3.add(obj.pos, obj.pos, movVel); + } + +} \ No newline at end of file diff --git a/Code/Entities/decorations.js b/Code/Entities/decorations.js new file mode 100644 index 0000000..d4706f8 --- /dev/null +++ b/Code/Entities/decorations.js @@ -0,0 +1,273 @@ +// +// decorations.js +//-------------------- +// Provides decoration objects. +// by RHY3756547 +// +// includes: +// render stuff idk +// + +window.ObjDecor = function(obji, scene) { + var forceBill; + var obji = obji; + var res = []; + + var t = this; + + t.pos = vec3.clone(obji.pos); + t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + var mat = mat4.create(); + var frame = 0; + var anim = null; + var animFrame = 0; + var animMat = null; + + function draw(view, pMatrix) { + mat4.translate(mat, view, t.pos); + + if (t.angle[2] != 0) mat4.rotateZ(mat, mat, t.angle[2]*(Math.PI/180)); + if (t.angle[1] != 0) mat4.rotateY(mat, mat, t.angle[1]*(Math.PI/180)); + if (t.angle[0] != 0) mat4.rotateX(mat, mat, t.angle[0]*(Math.PI/180)); + + if (anim != null) { + animMat = anim.setFrame(0, 0, animFrame++); + } + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + res.mdl[0].draw(mat, pMatrix, animMat); + } + + function update() { + + } + + function requireRes() { //scene asks what resources to load + forceBill = true; + switch (obji.ID) { + case 0x012D: + return {mdl:[{nsbmd:"BeachTree1.nsbmd"}]}; //non solid + case 0x012E: + return {mdl:[{nsbmd:"BeachTree1.nsbmd"}]}; + case 0x012F: + return {mdl:[{nsbmd:"earthen_pipe1.nsbmd"}]}; //why is there an earthen pipe 2 + + case 0x0130: + return {mdl:[{nsbmd:"opa_tree1.nsbmd"}]}; + case 0x0131: + return {mdl:[{nsbmd:"OlgPipe1.nsbmd"}]}; + case 0x0132: + return {mdl:[{nsbmd:"OlgMush1.nsbmd"}]}; + case 0x0133: + return {mdl:[{nsbmd:"of6yoshi1.nsbmd"}]}; + case 0x0134: + return {mdl:[{nsbmd:"cow.nsbmd"}], other:[null, null, "cow.nsbtp"]}; //has animation, cow.nsbtp + case 0x0135: + forceBill = false; + return {mdl:[{nsbmd:"NsKiller1.nsbmd"}, {nsbmd:"NsKiller2.nsbmd"}, {nsbmd:"NsKiller2_s.nsbmd"}]}; //probably animates + case 0x0138: + return {mdl:[{nsbmd:"GardenTree1.nsbmd"}]}; + case 0x0139: + return {mdl:[{nsbmd:"kamome.nsbmd"}], other:[null, null, "kamone.nsbtp"]}; //animates using nsbtp, and uses route to move + + case 0x013A: + return {mdl:[{nsbmd:"CrossTree1.nsbmd"}]}; + + //0x013C is big cheep cheep + case 0x013C: + forceBill = false; + return {mdl:[{nsbmd:"bakubaku.nsbmd"}]}; + + //0x013D is spooky ghost + case 0x013D: + forceBill = false; + return {mdl:[{nsbmd:"teresa.nsbmd"}], other:[null, null, "teresa.nsbtp"]}; + + case 0x013E: + return {mdl:[{nsbmd:"Bank_Tree1.nsbmd"}]}; + case 0x013F: + return {mdl:[{nsbmd:"GardenTree1.nsbmd"}]}; //non solid + + case 0x0140: + return {mdl:[{nsbmd:"chandelier.nsbmd"}], other:[null, "chandelier.nsbca"]}; + case 0x0142: + return {mdl:[{nsbmd:"MarioTree3.nsbmd"}]}; + case 0x0145: + return {mdl:[{nsbmd:"TownTree1.nsbmd"}]}; + case 0x0146: + //solid + return {mdl:[{nsbmd:"Snow_Tree1.nsbmd"}]}; + case 0x0148: + return {mdl:[{nsbmd:"DeTree1.nsbmd"}]}; + case 0x0149: + return {mdl:[{nsbmd:"BankEgg1.nsbmd"}]}; + + case 0x014B: + return {mdl:[{nsbmd:"KinoHouse1.nsbmd"}]}; + case 0x014C: + return {mdl:[{nsbmd:"KinoHouse2.nsbmd"}]}; + case 0x014D: + return {mdl:[{nsbmd:"KinoMount1.nsbmd"}]}; + case 0x014E: + return {mdl:[{nsbmd:"KinoMount2.nsbmd"}]}; + + + case 0x014F: + return {mdl:[{nsbmd:"olaTree1c.nsbmd"}]}; + + case 0x0150: + return {mdl:[{nsbmd:"osaTree1c.nsbmd"}]}; + case 0x0151: + forceBill = false; + return {mdl:[{nsbmd:"picture1.nsbmd"}], other:[null, "picture1.nsbca"]}; + case 0x0152: + forceBill = false; + return {mdl:[{nsbmd:"picture2.nsbmd"}], other:[null, "picture2.nsbca"]}; + case 0x0153: + return {mdl:[{nsbmd:"om6Tree1.nsbmd"}]}; + + //0x0154 is rainbow road rotating star + case 0x0154: + forceBill = false; + return {mdl:[{nsbmd:"RainStar.nsbmd"}], other:["RainStar.nsbta"]}; + + case 0x0155: + return {mdl:[{nsbmd:"Of6Tree1.nsbmd"}]}; + case 0x0156: + return {mdl:[{nsbmd:"Of6Tree1.nsbmd"}]}; + case 0x0157: + return {mdl:[{nsbmd:"TownMonte.nsbmd"}], other:[null, null, "TownMonte.nsbtp"]}; //pianta! + + //debug pianta bridge + case 0x00CC: + forceBill = false; + return {mdl:[{nsbmd:"bridge.nsbmd"}], other:[null, "bridge.nsbca"]}; + //debug puddle + case 0x000D: + forceBill = false; + return {mdl:[{nsbmd:"puddle.nsbmd"}]}; + //debug airship + case 0x0158: + forceBill = false; + return {mdl:[{nsbmd:"airship.nsbmd"}]}; + + //need version for 3d objects? + + //DEBUG ENEMIES - remove here when implemented. + + case 0x0191: //goomba + return {mdl:[{nsbmd:"kuribo.nsbmd"}], other:[null, null, "kuribo.nsbtp"]}; //has nsbtp, route + case 0x0192: //rock + forceBill = false; + return {mdl:[{nsbmd:"rock.nsbmd"}, {nsbmd:"rock_shadow.nsbmd"}]}; //has route + case 0x0193: //thwomp + forceBill = false; + return {mdl:[{nsbmd:"dossun.nsbmd"}, {nsbmd:"dossun_shadow.nsbmd"}]}; //has route + case 0x0196: //chain chomp + forceBill = false; + return {mdl:[{nsbmd:"wanwan.nsbmd"}, {nsbmd:"wanwan_chain.nsbmd"}, {nsbmd:"wanwan_kui.nsbmd"}, {nsbmd:"rock_shadow.nsbmd"}]}; + case 0x0198: //bowser castle GBA fireball + return {mdl:[{nsbmd:"mkd_ef_bubble.nsbmd"}]}; + case 0x0199: //peach gardens monty + forceBill = false; + return {mdl:[{nsbmd:"choropu.nsbmd"}], other:[null, null, "choropu.nsbtp"]}; //has nsbtp + case 0x019B: //cheep cheep (bouncing) + return {mdl:[{nsbmd:"pukupuku.nsbmd"}], other:[null, null, "pukupuku.nsbtp"]}; //has nsbtp + case 0x019D: //snowman + return {mdl:[{nsbmd:"sman_top.nsbmd"}, {nsbmd:"sman_bottom.nsbmd"}]}; + case 0x019E: //trunk with bats + forceBill = false; + return {mdl:[{nsbmd:"kanoke_64.nsbmd"}, {nsbmd:"basabasa.nsbmd"}], other:[null, "kanoke_64.nsbca"]}; //basa has nsbtp + case 0x01A0: //bat + return {mdl:[{nsbmd:"basabasa.nsbmd"}], other:[null, null, "basabasa.nsbtp"]}; //has nsbtp + case 0x01A1: //as fortress cannon + forceBill = false; + return {mdl:[{nsbmd:"NsCannon1.nsbmd"}]}; + case 0x01A3: //mansion moving tree + forceBill = false; + return {mdl:[{nsbmd:"move_tree.nsbmd"}], other:[null, "move_tree.nsbca"]}; //has route + case 0x01A4: //flame + forceBill = false; + return {mdl:[{nsbmd:"mkd_ef_burner.nsbmd"}], other:["mkd_ef_burner.nsbta", null]}; + case 0x01A5: //chain chomp no base + forceBill = false; + return {mdl:[{nsbmd:"wanwan.nsbmd"}, {nsbmd:"wanwan_chain.nsbmd"}, {nsbmd:"rock_shadow.nsbmd"}]}; + + case 0x01A6: //plant + return {mdl:[{nsbmd:"ob_pakkun_sf.nsbmd"}], other:[null, null, "ob_pakkun_sf.nsbtp"]}; //has nsbtp + + case 0x01A7: //monty airship + forceBill = false; + return {mdl:[{nsbmd:"poo.nsbmd"}, {nsbmd:"cover.nsbmd"}, {nsbmd:"hole.nsbmd"}], other:[null, null, "poo.nsbtp"]}; //poo has nsbtp + + case 0x01A8: //bound + forceBill = false; + return {mdl:[{nsbmd:"bound.nsbmd"}], other:[null, null, "bound.nsbtp"]}; //has nsbtp + case 0x01A9: //flipper + forceBill = false; + return {mdl:[{nsbmd:"flipper.nsbmd"}], other:["flipper.nsbta", null, "flipper.nsbtp"]}; //has nsbtp + + case 0x01AA: //3d fire plant + forceBill = false; + //note... what exactly is PakkunZHead... + return {mdl:[{nsbmd:"PakkunMouth.nsbmd"}, {nsbmd:"PakkunBody.nsbmd"}, {nsbmd:"FireBall.nsbmd"}], other:[null, "PakkunMouth.nsbca"]}; + case 0x01AC: //crab + forceBill = false; + return {mdl:[{nsbmd:"crab.nsbmd"}, {nsbmd:"crab_hand.nsbmd"}], other:[null, null, "crab.nsbtp"]}; //both have nsbtp + + case 0x01AD: //desert hills sun + forceBill = false; + return {mdl:[{nsbmd:"sun.nsbmd"}, {nsbmd:"sun_LOD.nsbmd"}]/*, other:[null, "sun.nsbca"]*/}; //exesun animation does not load + + case 0x01B0: //routed iron ball + return {mdl:[{nsbmd:"IronBall.nsbmd"}]}; + case 0x01B1: //routed choco mountain rock + forceBill = false; + return {mdl:[{nsbmd:"rock2.nsbmd"}]}; + case 0x01B2: //sanbo... whatever that is (pokey?) routed + return {mdl:[{nsbmd:"sanbo_h.nsbmd"}, {nsbmd:"sanbo_b.nsbmd"}]}; + case 0x01B3: //iron ball + return {mdl:[{nsbmd:"IronBall.nsbmd"}]}; + + case 0x01B4: //cream + forceBill = false; + return {mdl:[{nsbmd:"cream.nsbmd"}, {nsbmd:"cream_effect.nsbmd"}]}; + case 0x01B5: //berry + forceBill = false; + return {mdl:[{nsbmd:"berry.nsbmd"}, {nsbmd:"cream_effect.nsbmd"}]}; + } + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + + if (forceBill) { + t.angle[1] = 0; + var bmd = r.mdl[0].bmd; + bmd.hasBillboards = true; + var models = bmd.modelData.objectData; + for (var i=0; i 0 && r.other[0] != null) { + res.mdl[0].loadTexAnim(r.other[0]); + } + if (r.other.length > 1 && r.other[1] != null) + anim = new nitroAnimator(r.mdl[0].bmd, r.other[1]); + } + } + +} \ No newline at end of file diff --git a/Code/Entities/itembox.js b/Code/Entities/itembox.js new file mode 100644 index 0000000..fc64640 --- /dev/null +++ b/Code/Entities/itembox.js @@ -0,0 +1,120 @@ +// +// itembox.js +//-------------------- +// Drives and animates itembox entity. +// by RHY3756547 +// + +window.ItemBox = function(obji, scene) { + var obji = obji; + var res = []; + + var t = this; + + var anim = 0; + var animFrame = 0; + var animMat; + var frames = 0; + + t.soundProps = {}; + t.pos = vec3.clone(obji.pos); + //t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.sndUpdate = sndUpdate; + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + t.mode = 0; + t.time = 0; + + var test = 0; + + + function update(scene) { + switch (t.mode) { + case 0: //alive + for (var i=0; i 30) { + t.mode = 2; + t.time = 0; + } + break; + case 2: //respawning + if (t.time++ > 30) { + t.mode = 0; + t.time = 0; + } + break; + } + + animMat = anim.setFrame(0, 0, animFrame); + animFrame = (animFrame+1)%frames; + } + + function draw(view, pMatrix, gl) { + if (t.mode == 0 || t.mode == 2) { + if (t.mode == 2) nitroRender.setColMult([1, 1, 1, t.time/30]); + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + //res.mdl[2].draw(mat, pMatrix); + + mat4.translate(mat, mat, [0, 1, 0]) + + gl.enable(gl.CULL_FACE); //box part + //gl.depthMask(false); + res.mdl[0].drawPoly(mat, pMatrix, 0, 1, animMat); + //gl.depthMask(true); + gl.disable(gl.CULL_FACE); + + //question mark part + gl.depthRange(0, 0.99); //hack to push question mark forward in z buffer, causes a few issues with far away boxes though + res.mdl[0].drawPoly(mat, pMatrix, 0, 0, animMat); + gl.depthRange(0, 1); + + if (t.mode == 2) nitroRender.setColMult([1, 1, 1, 1]); + } + } + + function sndUpdate(view) { + t.soundProps.pos = vec3.transformMat4([], t.pos, view); + if (t.soundProps.lastPos != null) t.soundProps.vel = vec3.sub([], t.soundProps.pos, t.soundProps.lastPos); + else t.soundProps.vel = [0, 0, 0]; + t.soundProps.lastPos = t.soundProps.pos; + + t.soundProps.refDistance = 192/1024; + t.soundProps.rolloffFactor = 1; + } + + function requireRes() { //scene asks what resources to load + return {mdl:[{nsbmd:"itembox.nsbmd"}, {nsbmd:"obj_shadow.nsbmd"}, {nsbmd:"itembox_hahen.nsbmd"}], other:["itembox.nsbca"]}; + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + anim = new nitroAnimator(r.mdl[0].bmd, r.other[0]); + frames = r.other[0].animData.objectData[0].frames; + animFrame = Math.floor(Math.random()*frames); + animMat = anim.setFrame(0, 0, animFrame); + } + +} \ No newline at end of file diff --git a/Code/Entities/kart.js b/Code/Entities/kart.js new file mode 100644 index 0000000..495d853 --- /dev/null +++ b/Code/Entities/kart.js @@ -0,0 +1,890 @@ +// +// kart.js +//-------------------- +// Entity type for karts. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/kcl.js +// + +window.Kart = function(pos, angle, speed, kartN, charN, controller, scene) { + var k = this; + var minimumMove = 0.05; + var MAXSPEED = 24; + var BOOSTTIME = 90; + + var kartSoundBase = 170; + + var COLBOUNCE_TIME = 20; + var COLBOUNCE_STRENGTH = 1; + + var params = scene.gameRes.kartPhys.karts[kartN]; + var offsets = scene.gameRes.kartOff.karts[kartN]; + + this.local = controller.local; + this.active = true; + this.preboost = true; + + this.soundProps = {}; + this.pos = pos; + this.angle = angle; + this.vel = vec3.create(); + this.weight = params.weight; + this.params = params; + this.kartBounce = kartBounce; + + this.speed = speed; + this.drifting = false; + this.driftMode = 0; //1 left, 2 right, 0 undecided + this.driftLanded = false; //if we haven't landed then apply a constant turn. + + //powerslide info: to advance to the next mode you need to hold the same button for 10 or more frames. Mode 0 starts facing drift direction, 1 is other way, 2 is returning (mini spark), 3 is other way, 4 is returning (turbo spark) + this.driftPSTick = 0; + this.driftPSMode = 0; + + this.kartTargetNormal = [0, 1, 0]; + this.kartNormal = [0, 1, 0]; + this.airTime = 0; + this.controller = controller; + + this.driftOff = 0; + this.physicalDir = angle; + this.mat = mat4.create(); + this.basis = mat4.create(); + this.ylock = 0; + + this.cannon = null; + + this.gravity = [0, -0.17, 0]; //100% confirmed by me messing around with the gravity value in mkds. for sticky surface and loop should modify to face plane until in air + + this.update = update; + this.sndUpdate = sndUpdate; + this.draw = draw; + + this.drawKart = drawKart; + this.drawWheels = drawWheels; + this.drawChar = drawChar; + + this.trackAttach = null; //a normal for the kart to attach to (loop) + this.boostMT = 0; + this.boostNorm = 0; + + this.kartColVel = vec3.create(); + this.kartColTimer = 0; + + var charRes = scene.gameRes.getChar(charN); + var kartRes = scene.gameRes.getKart(kartN); + var kartPolys = []; + + var kObj = kartRes.bmd.modelData.objectData[0]; + + for (var i=0; i= hitGroundAnim.length) groundAnim = -1; + } + + onGround = (k.airTime < 5); + + kartAnim = (kartAnim+1)%8; + var input = k.controller.fetchInput(); + k.lastInput = input; + + if (input.turn > 0.3) { + if (k.driveAnimF < 28) k.driveAnimF++; + } else if (input.turn < -0.3) { + if (k.driveAnimF > 0) k.driveAnimF--; + } else { + if (k.driveAnimF > 14) k.driveAnimF--; + else if (k.driveAnimF < 14) k.driveAnimF++; + } + + //update sounds + + var newSoundMode = soundMode; + if (input.accel) { + if (soundMode == 0 || soundMode == 6) newSoundMode = 2; + if (soundMode == 4) newSoundMode = 3; + } else { + if (soundMode != 0) { + if (soundMode == 2 || soundMode == 3) newSoundMode = 4; + if (newSoundMode == 4 && k.speed < 0.5) newSoundMode = 0; + } + } + + if (k.boostMT+k.boostNorm > 0) { + if (k.boostNorm == BOOSTTIME || k.boostMT == params.miniTurbo) { + if (sounds.boostSoundTrig) { + if (sounds.boost != null) nitroAudio.instaKill(sounds.boost); + sounds.boost = nitroAudio.playSound(160, {}, 0, k); + sounds.boost.gainN.gain.value = 2; + sounds.boostSoundTrig = false; + } + } else { + sounds.boostSoundTrig = true; + } + } else if (sounds.boost != null) { + nitroAudio.kill(sounds.boost); + sounds.boost = null; + } + + if (onGround && k.speed > 0.5) { + if (lastCollided != sounds.lastTerrain || lastBE != sounds.lastBE || sounds.drive == null) { + if (sounds.drive != null) nitroAudio.kill(sounds.drive); + if (lastColSounds.drive != null) { + sounds.drive = nitroAudio.playSound(lastColSounds.drive, {}, 0, k); + sounds.drive.gainN.gain.value = 2; + } + } + + if (k.drifting && k.driftLanded) { + if (lastCollided != sounds.lastTerrain || lastBE != sounds.lastBE || sounds.drift == null) { + if (sounds.drift != null) nitroAudio.kill(sounds.drift); + if (lastColSounds.drift != null) { + sounds.drift = nitroAudio.playSound(lastColSounds.drift, {}, 0, k); + } + } + } else if (sounds.drift != null) { nitroAudio.kill(sounds.drift); sounds.drift = null; } + + sounds.lastTerrain = lastCollided; + sounds.lastBE = lastBE; + } else { + if (sounds.drift != null) { nitroAudio.kill(sounds.drift); sounds.drift = null; } + if (sounds.drive != null) { nitroAudio.kill(sounds.drive); sounds.drive = null; } + } + + //end sound update + + if (k.preboost) { + + } else if (k.cannon != null) { //when cannon is active, we fly forward at max move speed until we get to the cannon point. + var c = scene.nkm.sections["KTPC"].entries[k.cannon]; + + var mat = mat4.create(); + mat4.rotateY(mat, mat, c.angle[1]*(Math.PI/180)); + mat4.rotateX(mat, mat, c.angle[0]*(-Math.PI/180)); + + var forward = [0, 0, 1]; + var up = [0, 1, 0]; + + k.vel = vec3.scale([], vec3.transformMat4(forward, forward, mat), MAXSPEED); + k.speed = MAXSPEED; + vec3.add(k.pos, k.pos, k.vel); + k.physicalDir = (180-c.angle[1])*(Math.PI/180); + k.angle = k.physicalDir; + k.kartTargetNormal = vec3.transformMat4(up, up, mat); + + var planeConst = -vec3.dot(c.pos, forward); + var cannonDist = vec3.dot(k.pos, forward) + planeConst; + if (cannonDist > 0) k.cannon = null; + } else { //default kart mode + + var groundEffect = 0; + if (lastCollided != -1) { + groundEffect = MKDS_COLTYPE.PHYS_MAP[lastCollided]; + if (groundEffect == null) groundEffect = 0; + } + + var effect = params.colParam[groundEffect]; + var top = params.topSpeed*effect.topSpeedMul; //if you let go of accel, drift ends anyway, so always accel in drift. + + var boosting = (k.boostNorm + k.boostMT)>0; + + if (boosting) { + var top2 + if (k.boostNorm>0){ + top2 = params.topSpeed*1.3; + k.boostNorm--; + } else { + top2 = params.topSpeed*((effect.topSpeedMul >= 1)?1.3:effect.topSpeedMul); + } + + if (k.boostMT>0) { + k.boostMT--; + } + + if (k.speed <= top2) { + k.speed += 1; + if (k.speed > top2) k.speed = top2; + } else { + k.speed *= 0.95; + } + } + + //kart controls + if (k.drifting) { + if ((onGround) && !(input.accel && input.drift && (k.speed > 2 || !k.driftLanded))) { + //end drift, execute miniturbo + k.drifting = false; + if (sounds.powerslide != null) { + nitroAudio.instaKill(sounds.powerslide); + sounds.powerslide = null; + } + if (k.driftPSMode == 3) { + k.boostMT = params.miniTurbo; + } + k.driftPSMode = 0; + k.driftPSTick = 0; + } + + if (k.driftMode == 0) { + if (input.turn > 0.30) { + k.driftMode = 2; + } else if (input.turn < -0.30) { + k.driftMode = 1; + } + } else { + if (k.driftLanded) { + var change = (((k.driftMode-1.5)*Math.PI/1.5)-k.driftOff)*0.05; + k.driftOff += change; + k.physicalDir -= change; + } + + //if we're above the initial y position, add a constant turn with a period of 180 frames. + if (!k.driftLanded && k.ylock>=0) { + k.physicalDir += (Math.PI*2/180)*(k.driftMode*2-3); + } + } + + if (onGround) { + if (!k.driftLanded) { + if (k.driftMode == 0) k.drifting = false; + else { + k.driftPSMode = 0; + k.driftPSTick = 0; + k.driftLanded = true; + } + } + if (k.drifting) { + + if (!boosting) { + if (k.speed <= top) { + k.speed += (k.speed/top > params.driftAccelSwitch)?params.driftAccel2:params.driftAccel1; + if (k.speed > top) k.speed = top; + } else { + k.speed *= 0.95; + } + } + + var turn = ((k.driftMode == 1)?(input.turn-1):(input.turn+1))/2; + + k.physicalDir += params.driftTurnRate*turn+((k.driftMode == 1)?-1:1)*(50/32768)*Math.PI; //what is this mystery number i hear you ask? well my friend, this is the turn rate for outward drift. + + //miniturbo code + if (input.turn != 0) { + var inward = ((input.turn>0) == k.driftMode-1); //if we're turning + + switch (k.driftPSMode) { + case 0: //dpad away from direction for 10 frames + if (!inward) k.driftPSTick++; + else if (k.driftPSTick > 9) { + k.driftPSMode++; + k.driftPSTick = 1; + + //play blue spark sound + var blue = nitroAudio.playSound(210, {}, 0, k); + blue.gainN.gain.value = 2; + + } else k.driftPSTick = 0; + break; + case 1: //dpad toward direction for 10 frames + if (inward) k.driftPSTick++; + else if (k.driftPSTick > 9) { + k.driftPSMode++; + k.driftPSTick = 1; + + } else k.driftPSTick = 0; + break; + case 2: //dpad away from direction for 10 frames + if (!inward) k.driftPSTick++; + else if (k.driftPSTick > 9) { + k.driftPSMode++; + k.driftPSTick = 1; + //play red sparks sound, full MT! + sounds.powerslide = nitroAudio.playSound(209, {}, 0, k); + sounds.powerslide.gainN.gain.value = 2; + } else k.driftPSTick = 0; + break; + case 3: //turbo charged + break; + } + } + } + } + } + + if (!k.drifting) { + if (onGround) { + var effect = params.colParam[groundEffect]; + if (!boosting) { + if (input.accel) { + if (k.speed <= top) { + k.speed += (k.speed/top > params.accelSwitch)?params.accel2:params.accel1; + if (k.speed > top) k.speed = top; + } else { + k.speed *= 0.95; + } + } else { + k.speed *= params.decel; + } + } + + if ((input.accel && k.speed >= 0) || (k.speed > 0.1)) { + k.physicalDir += params.turnRate*input.turn; + } else if ( k.speed < -0.1) { + k.physicalDir -= params.turnRate*input.turn; + } + + if (input.drift) { + ylvel = 1.25; + k.vel[1] += 1.25; + k.airTime = 4; + k.drifting = true; + k.driftLanded = false; + k.driftMode = 0; + k.ylock = 0; + + var boing = nitroAudio.playSound(207, {transpose: -4}, 0, k); + boing.gainN.gain.value = 2; + } + } else { + if (input.drift) { + ylvel = 0; + k.drifting = true; + k.driftLanded = false; + k.driftMode = 0; + k.ylock = -0.001; + } + } + } + + k.physicalDir = fixDir(k.physicalDir); + + if (k.driftOff != 0 && (!k.drifting || !k.driftLanded)) { + if (k.driftOff > 0) { + k.physicalDir += params.driftOffRestore; + k.driftOff -= params.driftOffRestore; + if (k.driftOff < 0) k.driftOff = 0; + } else { + k.physicalDir -= params.driftOffRestore; + k.driftOff += params.driftOffRestore; + if (k.driftOff > 0) k.driftOff = 0; + } + } + + checkKartCollision(scene); + + if (!onGround) { + this.kartTargetNormal = [0, 1, 0]; + vec3.add(k.vel, k.vel, k.gravity) + if (k.ylock >= 0) { + ylvel += k.gravity[1]; + k.ylock += ylvel; + } + + if (k.kartColTimer == COLBOUNCE_TIME) { + vec3.add(k.vel, k.vel, k.kartColVel); + } + } else { + k.angle += dirDiff(k.physicalDir, k.angle)*effect.handling/2; + k.angle = fixDir(k.physicalDir); + + k.vel[1] += k.gravity[1]; + k.vel = [Math.sin(k.angle)*k.speed, k.vel[1], -Math.cos(k.angle)*k.speed] + + if (k.kartColTimer > 0) { + vec3.add(k.vel, k.vel, vec3.scale([], k.kartColVel, k.kartColTimer/10)) + } + } + + if (k.kartColTimer > 0) k.kartColTimer--; + + wheelTurn += k.speed/16; + wheelTurn = fixDir(wheelTurn); + k.airTime++; + //end kart controls + + //move kart on moving platforms (no collision, will be corrected by next step) + if (stuckTo != null) { + if (stuckTo.moveWith != null) stuckTo.moveWith(k); + stuckTo = null; + } + + //move kart. + + + + var steps = 0; + var remainingT = 1; + var velSeg = vec3.clone(k.vel); + var posSeg = vec3.clone(k.pos); + var ignoreList = []; + while (steps++ < 10 && remainingT > 0.01) { + var result = lsc.sweepEllipse(posSeg, velSeg, scene, [params.colRadius, params.colRadius, params.colRadius], ignoreList); + if (result != null) { + colResponse(posSeg, velSeg, result, ignoreList) + remainingT -= result.t; + if (remainingT > 0.01) { + velSeg = vec3.scale(vec3.create(), k.vel, remainingT); + } + } else { + vec3.add(posSeg, posSeg, velSeg); + remainingT = 0; + } + } + k.pos = posSeg; + } + + //interpolate visual normal roughly to target + var rate = onGround?0.15:0.025; + k.kartNormal[0] += (k.kartTargetNormal[0]-k.kartNormal[0])*rate; + k.kartNormal[1] += (k.kartTargetNormal[1]-k.kartNormal[1])*rate; + k.kartNormal[2] += (k.kartTargetNormal[2]-k.kartNormal[2])*rate; + vec3.normalize(k.kartNormal, k.kartNormal); + + k.basis = buildBasis(); + + var mat = mat4.create(); + mat4.translate(mat, mat, k.pos); + k.mat = mat4.mul(mat, mat, k.basis); + + if (input.item) { + scene.items.addItem(0, scene.karts.indexOf(k), {}) + } + + updateKartSound(newSoundMode, input); + positionChanged(lastPos, k.pos); + } + + function genFutureChecks() { + //all future points that + var chosen = {} + var current = checkpoints[k.checkPointNumber]; + var expectedSection = current.nextSection; + futureChecks = []; + for (var i=k.checkPointNumber+1; i 0 && lineDot < vec2.sqrLen(lineCheck) && dot < 0 && dotOld >= 0) { + k.checkPointNumber = futureChecks[i]; + genFutureChecks(); + break; + } + } + + if (!k.passedKTP2 && forwardCrossedKTP(passLine, oldPos, pos)) k.passedKTP2 = true; + if (k.passedKTP2 && futureChecks.length == 0) { + //we can finish the lap + if (forwardCrossedKTP(startLine, oldPos, pos)) { + k.lapNumber++; + k.checkPointNumber = 0; + k.passedKTP2 = 0; + scene.lapAdvance(k); + } + } + } + + function forwardCrossedKTP(ktp, oldPos, pos) { + var distOld = vec2.sub([], [ktp.pos[0], ktp.pos[2]], [oldPos[0], oldPos[2]]); + var dist = vec2.sub([], [ktp.pos[0], ktp.pos[2]], [pos[0], pos[2]]); + + var ang = (ktp.angle[1]/180)*Math.PI; + + var sinus = Math.sin(ang); + var cosinus = Math.cos(ang); + + var dot = vec2.dot(dist, [sinus, cosinus]); + var dotOld = vec2.dot(distOld, [sinus, cosinus]); + + return (dot < 0 && dotOld >= 0); + } + + function checkKartCollision(scene) { //check collision with other karts. Really simple. + for (var i=0; i0 || ok.boostMT>0)?2:1)*((k.boostNorm>0 || k.boostMT>0)?0.5:1); + + //as well as side bounce also add velocity difference if other vel > mine. + + vec3.sub(k.kartColVel, k.pos, ok.pos); + k.kartColVel[1] = 0; + vec3.normalize(k.kartColVel, k.kartColVel); + vec3.scale(k.kartColVel, k.kartColVel, weightMul); + + if (vec3.length(k.vel) < vec3.length(ok.vel)) vec3.add(k.kartColVel, k.kartColVel, vec3.sub([], ok.vel, k.vel)); + + k.kartColVel[1] = 0; + } + + function fixDir(dir) { + return posMod(dir, Math.PI*2); + } + + function dirDiff(dir1, dir2) { + var d = fixDir(dir1-dir2); + return (d>Math.PI)?(-2*Math.PI+d):d; + } + + function posMod(i, n) { + return (i % n + n) % n; + } + + function updateKartSound(mode, input) { + var turn = (onGround && !k.drifting)?(1-Math.abs(input.turn)/11):1; + var transpose = (mode == 0)?0:(22*turn*k.speed/params.topSpeed); + + sounds.transpose += (transpose-sounds.transpose)/15; + if (mode != soundMode) { + soundMode = mode; + if (sounds.kart != null) nitroAudio.instaKill(sounds.kart); + sounds.kart = nitroAudio.playSound(kartSoundBase+soundMode, {transpose:sounds.transpose, volume:1}, 0, k); + //if (mode == 3) sounds.kart.gainN.gain.value = 0.5; + } else { + sounds.kart.seq.setTranspose(sounds.transpose); + } + } + + function buildBasis() { + //order y, x, z + var dir = k.physicalDir+k.driftOff+(Math.sin((COLBOUNCE_TIME-k.kartColTimer)/3)*(Math.PI/6)*(k.kartColTimer/COLBOUNCE_TIME)); + var basis = gramShmidt(k.kartNormal, [Math.cos(dir), 0, Math.sin(dir)], [Math.sin(dir), 0, -Math.cos(dir)]); + var temp = basis[0]; + basis[0] = basis[1]; + basis[1] = temp; //todo: cleanup + return [ + basis[0][0], basis[0][1], basis[0][2], 0, + basis[1][0], basis[1][1], basis[1][2], 0, + basis[2][0], basis[2][1], basis[2][2], 0, + 0, 0, 0, 1 + ] + + } + + function sndUpdate(view) { + k.soundProps.pos = vec3.transformMat4([], k.pos, view); + if (k.soundProps.lastPos != null) k.soundProps.vel = vec3.sub([], k.soundProps.pos, k.soundProps.lastPos); + else k.soundProps.vel = [0, 0, 0]; + k.soundProps.lastPos = k.soundProps.pos; + + k.soundProps.refDistance = 192/1024; + k.soundProps.rolloffFactor = 1; + + var calcVol = (k.soundProps.refDistance / (k.soundProps.refDistance + k.soundProps.rolloffFactor * (Math.sqrt(vec3.dot(k.soundProps.pos, k.soundProps.pos)) - k.soundProps.refDistance))); + } + + function gramShmidt(v1, v2, v3) { + var u1 = v1; + var u2 = vec3.sub([0, 0, 0], v2, project(u1, v2)); + var u3 = vec3.sub([0, 0, 0], vec3.sub([0, 0, 0], v3, project(u1, v3)), project(u2, v3)); + return [vec3.normalize(u1, u1), vec3.normalize(u2, u2), vec3.normalize(u3, u3)] + } + + function colSound(collision, effect) { + if (MKDS_COLTYPE.SOUNDMAP[collision] == null) return {}; + return MKDS_COLTYPE.SOUNDMAP[collision][effect] || {}; + } + + function project(u, v) { + return vec3.scale([], u, (vec3.dot(u, v)/vec3.dot(u, u))) + } + + function colResponse(pos, pvel, dat, ignoreList) { + + var plane = dat.plane; + var colType = (plane.CollisionType>>8)&31; + var colBE = (plane.CollisionType>>5)&7; + + lastCollided = colType; + lastBE = colBE; + lastColSounds = colSound(lastCollided, colBE); + + var n = vec3.normalize([], dat.normal); + var gravS = Math.sqrt(vec3.dot(k.gravity, k.gravity)); + var angle = Math.acos(vec3.dot(vec3.scale(vec3.create(), k.gravity, -1/gravS), n)); + var adjustPos = true; + + if (MKDS_COLTYPE.GROUP_WALL.indexOf(colType) != -1) { //wall + //sliding plane, except normal is transformed to be entirely on the xz plane (cannot ride on top of wall, treated as vertical) + var xz = Math.sqrt(n[0]*n[0]+n[2]*n[2]) + var adjN = [n[0]/xz, 0, n[2]/xz] + var proj = vec3.dot(k.vel, adjN); + + if (proj < -1) { + if (lastColSounds.hit != null) nitroAudio.playSound(lastColSounds.hit, {volume:1}, 0, k) + } + vec3.sub(k.vel, k.vel, vec3.scale(vec3.create(), adjN, proj)); + + //convert back to angle + speed to keep change to kart vel + + var v = k.vel; + k.speed = Math.sqrt(v[0]*v[0]+v[2]*v[2]); + k.angle = Math.atan2(v[0], -v[2]); + } else if (MKDS_COLTYPE.GROUP_ROAD.indexOf(colType) != -1) { + //sliding plane + if (MKDS_COLTYPE.GROUP_BOOST.indexOf(colType) != -1) { + k.boostNorm = BOOSTTIME; + } + + if (k.vel[1] > 0) k.vel[1] = 0; + var proj = vec3.dot(k.vel, n); + if (proj < -4 && k.vel[1] < -2) { proj -= 1.5; } + vec3.sub(k.vel, k.vel, vec3.scale(vec3.create(), n, proj)); + k.kartTargetNormal = dat.pNormal; + if (!onGround) { + console.log("ground: "+colType+", "+colBE); + groundAnim = 0; + if (lastColSounds.land != null) nitroAudio.playSound(lastColSounds.land, {volume:1}, 0, k) + } + k.airTime = 0; + stuckTo = dat.object; + } else if (colType == MKDS_COLTYPE.CANNON) { + //cannon!! + k.cannon = colBE; + } else { + adjustPos = false; + ignoreList.push(plane); + } + + //vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove)); //move away from plane slightly + + if (adjustPos) { //move back from plane slightly + //vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove)); + vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t)); + vec3.add(pos, vec3.scale([], n, params.colRadius+minimumMove), dat.colPoint); + /*if (dat.embedded) { + + } else { + var velMag = Math.sqrt(vec3.dot(pvel, pvel)); + if (velMag*dat.t > minimumMove) { + vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t-(minimumMove/velMag))); + } else { + //do not move, too close + } + }*/ + } else { + vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t)); + } + + } +} \ No newline at end of file diff --git a/Code/Entities/objDatabase.js b/Code/Entities/objDatabase.js new file mode 100644 index 0000000..3a6504a --- /dev/null +++ b/Code/Entities/objDatabase.js @@ -0,0 +1,119 @@ +// +// objDatabase.js +//-------------------- +// Links object IDs to specific entity types. Must be initialized after all js files are loaded! +// by RHY3756547 +// +// includes: +// entities/* +// + +window.objDatabase = new (function(){ + + this.init = function() { + this.idToType = []; + + var t = this.idToType; + t[0x0001] = ObjWater; + t[0x0003] = ObjWater; + t[0x0006] = ObjWater; + t[0x0008] = ObjSoundMaker; + t[0x0009] = ObjWater; + t[0x000C] = ObjWater; + + t[0x0065] = ItemBox; + + t[0x00CA] = ObjRoutePlatform; + t[0x00CB] = ObjGear; + t[0x00CE] = ObjGear; //test_cylinder, tick tock clock end + t[0x00D0] = ObjRotaryRoom; + t[0x00D1] = ObjGear; //rotary bridge + + t[0x012D] = ObjDecor; + t[0x012E] = ObjDecor; + t[0x012F] = ObjDecor; + + t[0x0130] = ObjDecor; + t[0x0131] = ObjDecor; + t[0x0132] = ObjDecor; + t[0x0133] = ObjDecor; + t[0x0134] = ObjDecor; + t[0x0135] = ObjDecor; + t[0x0138] = ObjDecor; + t[0x0139] = ObjDecor; + t[0x013C] = ObjDecor; //DEBUG: cheep cheep (routed) + t[0x013D] = ObjDecor; //DEBUG: ghost + + t[0x013A] = ObjDecor; //figure 8 tree + t[0x013C] = ObjDecor; + t[0x013F] = ObjDecor; + + t[0x0140] = ObjDecor; + t[0x0142] = ObjDecor; //more trees + t[0x0145] = ObjDecor; + t[0x0146] = ObjDecor; + t[0x0148] = ObjDecor; + t[0x0149] = ObjDecor; //yoshi falls egg + + t[0x014B] = ObjDecor; + t[0x014C] = ObjDecor; + t[0x014D] = ObjDecor; + t[0x014E] = ObjDecor; + t[0x014F] = ObjDecor; + + t[0x0150] = ObjDecor; + t[0x0151] = ObjDecor; + t[0x0152] = ObjDecor; + t[0x0153] = ObjDecor; + t[0x0154] = ObjDecor; //rainbow star + t[0x0155] = ObjDecor; + t[0x0156] = ObjDecor; + t[0x0157] = ObjDecor; + + t[0x019C] = ObjTruck; + t[0x019A] = ObjCar; + t[0x0195] = ObjBus; + + + t[0x00CC] = ObjDecor; //DEBUG: pianta bridge + t[0x000D] = ObjDecor; //DEBUG: puddle + + t[0x0158] = ObjDecor; //DEBUG: airship (routed) + + //DEBUG ENEMIES AS DECOR: switch as implemented: + + t[0x0191] = ObjDecor; + t[0x0192] = ObjDecor; + t[0x0193] = ObjDecor; + t[0x0196] = ObjDecor; + t[0x0198] = ObjDecor; + t[0x0199] = ObjDecor; + //truck + t[0x019B] = ObjDecor; + t[0x019D] = ObjDecor; + t[0x019E] = ObjDecor; + + t[0x01A0] = ObjDecor; + t[0x01A1] = ObjDecor; + t[0x01A3] = ObjDecor; + t[0x01A4] = ObjDecor; + t[0x01A5] = ObjDecor; + t[0x01A6] = ObjDecor; + t[0x01A7] = ObjDecor; + t[0x01A8] = ObjDecor; + t[0x01A9] = ObjDecor; + + t[0x01AA] = ObjDecor; + t[0x01AC] = ObjDecor; + t[0x01AD] = ObjDecor; + //rotating fireballs + + t[0x01B0] = ObjDecor; + t[0x01B1] = ObjDecor; + t[0x01B2] = ObjDecor; + t[0x01B3] = ObjDecor; + t[0x01B4] = ObjDecor; + t[0x01B5] = ObjDecor; + } + +})(); \ No newline at end of file diff --git a/Code/Entities/rotatingGear.js b/Code/Entities/rotatingGear.js new file mode 100644 index 0000000..2186d9b --- /dev/null +++ b/Code/Entities/rotatingGear.js @@ -0,0 +1,161 @@ +// +// rotatingGear.js +//-------------------- +// Provides rotating gear objects for tick tock clock +// by RHY3756547 +// +// includes: +// render stuff idk +// + +window.ObjGear = function(obji, scene) { + var obji = obji; + var res = []; + + var t = this; + + t.collidable = true; + t.colMode = 0; + t.colRad = 512; + t.getCollision = getCollision; + t.moveWith = moveWith; + + t.pos = vec3.clone(obji.pos); + //t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + t.speed = (obji.setting1&0xFFFF)/8192; + t.duration = obji.setting1>>16; + t.rampDur = obji.setting2&0xFFFF; + t.statDur = obji.setting2>>16; + t.wB1 = obji.setting3&0xFFFF; //ONE of these flips direction, the other makes the gear use the black model. Not sure which is which, but for tick tock clock there is no need to get this right. + t.wB2 = obji.setting3>>16; + + t.time = 0; + t.mode = 0; //0=rampup, 1=normal, 2=rampdown, 3=stationary + t.angle = 0; + t.dir = (t.wB1 == 0) + + var dirVel = 0; + + var prevMat; + var curMat; + setMat(); + prevMat = curMat; + + function setMat() { + prevMat = curMat; + var mat = mat4.create(); + mat4.translate(mat, mat, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + mat4.rotateY(mat, mat, obji.angle[1]*(Math.PI/180)); + mat4.rotateX(mat, mat, obji.angle[0]*(Math.PI/180)); + + mat4.rotateY(mat, mat, t.angle); + curMat = mat; + } + + function update(scene) { + t.time++; + switch (t.mode) { + case 0: + dirVel = t.speed*(t.time/t.rampDur)*((t.dir)?-1:1); + if (t.time > t.rampDur) { + t.time = 0; t.mode = 1; + } + break; + case 1: + dirVel = t.speed*((t.dir)?-1:1); + if (t.time > t.duration) { + t.time = 0; t.mode = 2; + } + break; + case 2: + dirVel = t.speed*(1-t.time/t.rampDur)*((t.dir)?-1:1); + if (t.time > t.rampDur) { + t.time = 0; t.mode = 3; t.dir = !t.dir; + } + break; + case 3: + dirVel = 0; + if (t.time > t.statDur) { + t.time = 0; t.mode = 0; + } + break; + } + t.angle += dirVel; + setMat(); + } + + function draw(view, pMatrix) { + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + mat4.rotateY(mat, mat, obji.angle[1]*(Math.PI/180)); + mat4.rotateX(mat, mat, obji.angle[0]*(Math.PI/180)); + + mat4.rotateY(mat, mat, t.angle); + + res.mdl[t.wB1].draw(mat, pMatrix); + } + + function requireRes() { //scene asks what resources to load + switch (obji.ID) { + case 0x00CB: + return {mdl:[{nsbmd:"gear_white.nsbmd"}, {nsbmd:"gear_black.nsbmd"}]}; + case 0x00CE: + return {mdl:[{nsbmd:"test_cylinder.nsbmd"}]}; + case 0x00D1: + t.colRad = 4096; + return {mdl:[{nsbmd:"rotary_bridge.nsbmd"}]}; + } + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + } + + function getCollision() { + var obj = {}; + var inf = res.mdl[0].getCollisionModel(0, 0); + obj.tris = inf.dat; + + var mat = mat4.translate([], mat4.create(), t.pos); + mat4.scale(mat, mat, vec3.mul([], [16*inf.scale, 16*inf.scale, 16*inf.scale], t.scale)); + + mat4.rotateY(mat, mat, obji.angle[1]*(Math.PI/180)); + mat4.rotateX(mat, mat, obji.angle[0]*(Math.PI/180)); + mat4.rotateY(mat, mat, t.angle); + + obj.mat = mat; + return obj; + } + + function moveWith(obj) { //used for collidable objects that move. + + //the most general way to move something with an object is to multiply its position by the inverse mv matrix of that object, and then the new mv matrix. + + vec3.transformMat4(obj.pos, obj.pos, mat4.invert([], prevMat)) + vec3.transformMat4(obj.pos, obj.pos, curMat) + + /*var p = vec3.sub([], obj.pos, t.pos); + + if (obji.ID == 0x00D1) { //todo: maybe something more general + vec3.transformMat4(p, p, mat4.rotateX([], mat4.create(), dirVel)); + vec3.add(obj.pos, t.pos, p); + } else { + vec3.transformMat4(p, p, mat4.rotateY([], mat4.create(), dirVel)); + vec3.add(obj.pos, t.pos, p); + obj.physicalDir -= dirVel; + }*/ + } + +} \ No newline at end of file diff --git a/Code/Entities/shell.js b/Code/Entities/shell.js new file mode 100644 index 0000000..9dc2238 --- /dev/null +++ b/Code/Entities/shell.js @@ -0,0 +1,118 @@ +// +// shell.js +//-------------------- +// Entity type for shells. (green) +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/kcl.js +// + +window.GreenShell = function(scene, owner, time, itemID, cliID, params) { + var t = this; + var minimumMove = 0.01; + + this.pos = vec3.transformMat4([], [0, (-owner.params.colRadius)+1, 16], owner.mat); + this.vel = vec3.create(); + this.gravity = [0, -0.17, 0]; //100% confirmed by me messing around with the gravity value in mkds + this.angle = owner.angle; + this.speed = 10; + this.yvel = 0; + + this.update = update; + this.draw = draw; + + function update(scene) { + t.vel = [Math.sin(t.angle)*t.speed, t.yvel, -Math.cos(t.angle)*t.speed] + vec3.add(t.vel, t.vel, t.gravity); + + //simple point move. + + var steps = 0; + var remainingT = 1; + var velSeg = vec3.clone(t.vel); + var posSeg = vec3.clone(t.pos); + var ignoreList = []; + while (steps++ < 10 && remainingT > 0.01) { + var result = lsc.raycast(posSeg, velSeg, scene.kcl, 0.05, ignoreList); + if (result != null) { + colResponse(posSeg, velSeg, result, ignoreList) + remainingT -= result.t; + if (remainingT > 0.01) { + velSeg = vec3.scale(vec3.create(), t.vel, remainingT); + } + } else { + vec3.add(posSeg, posSeg, velSeg); + remainingT = 0; + } + } + t.pos = posSeg; + + t.yvel = t.vel[1]; + } + + function draw(mvMatrix, pMatrix) { + var mat = mat4.translate(mat4.create(), mvMatrix, vec3.add(vec3.create(), t.pos, [0, 3, 0])); + + spritify(mat); + mat4.scale(mat, mat, [16, 16, 16]); + + scene.gameRes.items.koura_g.draw(mat, pMatrix); + } + + var spritify = function(mat, scale) { + var scale = (scale == null)?Math.sqrt(mat[0]*mat[0]+mat[1]*mat[1]+mat[2]*mat[2]):scale; + + mat[0]=scale; mat[1]=0; mat[2]=0; + mat[4]=0; mat[5]=scale; mat[6]=0; + mat[8]=0; mat[9]=0; mat[10]=scale; + } + + function colResponse(pos, pvel, dat, ignoreList) { + + var plane = dat.plane; + var colType = (plane.CollisionType>>8)&31; + vec3.add(pos, pos, vec3.scale(vec3.create(), pvel, dat.t)); + + var n = dat.normal; + vec3.normalize(n, n); + var gravS = Math.sqrt(vec3.dot(t.gravity, t.gravity)); + var angle = Math.acos(vec3.dot(vec3.scale(vec3.create(), t.gravity, -1/gravS), n)); + var adjustPos = true + + if (MKDS_COLTYPE.GROUP_WALL.indexOf(colType) != -1) { //wall + //shell reflection code - slide y vel across plane, bounce on xz + vec3.add(t.vel, vec3.scale(vec3.create(), n, -2*(vec3.dot(t.vel, n)/vec3.dot(n,n))), t.vel); + t.vel[1] = 0; + + var v = t.vel; + t.angle = Math.atan2(v[0], -v[2]); + + } else if (MKDS_COLTYPE.GROUP_ROAD.indexOf(colType) != -1) { + //sliding plane + var proj = vec3.dot(t.vel, n); + vec3.sub(t.vel, t.vel, vec3.scale(vec3.create(), n, proj)); + } else { + adjustPos = false; + ignoreList.push(plane); + } + + var rVelMag = Math.sqrt(vec3.dot(t.vel, t.vel)); + vec3.scale(t.vel, t.vel, t.speed/rVelMag); //force speed to shell speed for green shells. + + //vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove)); //move away from plane slightly + + if (adjustPos) { //move back from plane slightly + vec3.add(pos, pos, vec3.scale(vec3.create(), n, minimumMove)); + /* + var velMag = Math.sqrt(vec3.dot(pvel, pvel)); + if (velMag*dat.t > minimumMove) { + vec3.sub(pos, pos, vec3.scale(vec3.create(), pvel, minimumMove/velMag)); //move back slightly after moving + } else { + vec3.sub(pos, pos, vec3.scale(vec3.create(), pvel, dat.t)); //if we're already too close undo the movement. + } + */ + } + + } +} \ No newline at end of file diff --git a/Code/Entities/soundMaker.js b/Code/Entities/soundMaker.js new file mode 100644 index 0000000..5fac83a --- /dev/null +++ b/Code/Entities/soundMaker.js @@ -0,0 +1,77 @@ +// +// soundMaker.js +//-------------------- +// Provides env sound object, such as crowd for figure 8 +// by RHY3756547 +// + +//0008 + +window.ObjSoundMaker = function(obji, scene) { + var obji = obji; + + var t = this; + + t.pos = vec3.clone(obji.pos); + + t.soundProps = {}; + t.sndUpdate = sndUpdate; + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + + var mat = mat4.create(); + var frame = 0; + + var sound = null; + var sN = 0; + var threshold = 0.2; + var gain = 1; + switch (obji.ID) { + case 0x0008: + sN = 259; + gain = 2; + threshold = 0.2; + break; + } + + function draw(view, pMatrix) { + + } + + function update() { + } + + function sndUpdate(view) { + t.soundProps.pos = vec3.transformMat4([], t.pos, view); + t.soundProps.pos = [0, 0, Math.sqrt(vec3.dot(t.soundProps.pos, t.soundProps.pos))] + //if (t.soundProps.lastPos != null) t.soundProps.vel = vec3.sub([], t.soundProps.pos, t.soundProps.lastPos); + //else t.soundProps.vel = [0, 0, 0]; + //t.soundProps.lastPos = t.soundProps.pos; + + t.soundProps.refDistance = 1024/1024; + //t.soundProps.rolloffFactor = 1; + + var calcVol = (t.soundProps.refDistance / (t.soundProps.refDistance + t.soundProps.rolloffFactor * (t.soundProps.pos[2] - t.soundProps.refDistance))); + + if (calcVol>16)/100; + t.routePos = (obji.setting1&0xFFFF)%t.route.length; + t.nextNode = t.route[t.routePos]; + t.prevPos = t.pos; + t.elapsedTime = 0; + + var facingNormal = [0, 1, 0]; + var curNormal = [0, 1, 0]; + var floorNormal = [0, 1, 0]; + + function update(scene) { + //simple behaviour, just follow the path! piece of cake. + t.elapsedTime += t.routeSpeed; + t.pos = vec3.lerp([], t.prevPos, t.nextNode.pos, t.elapsedTime/t.nextNode.duration); + if (t.elapsedTime >= t.nextNode.duration) { + t.elapsedTime = 0; + t.prevPos = t.nextNode.pos; + t.routePos = (t.routePos+1)%t.route.length; + t.nextNode = t.route[t.routePos]; + } + + facingNormal = vec3.sub([], t.prevPos, t.nextNode.pos) + vec3.normalize(facingNormal, facingNormal); + + var rate = 0.025 + curNormal[0] += (facingNormal[0]-curNormal[0])*rate; + curNormal[1] += (facingNormal[1]-curNormal[1])*rate; + curNormal[2] += (facingNormal[2]-curNormal[2])*rate; + vec3.normalize(curNormal, curNormal); + + var spos = vec3.clone(t.pos); + spos[1] += 32; + var result = lsc.raycast(spos, [0, -100, 0], scene.kcl, 0.05, []); + if (result != null) { + floorNormal = result.normal; + } else { + floorNormal = [0,1,0]; + } + + } + + function draw(view, pMatrix) { + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + + mat4.mul(mat, mat, mat4.invert([], mat4.lookAt([], [0, 0, 0], curNormal, floorNormal))); + res.mdl[0].draw(mat, pMatrix); + } + + function requireRes() { //scene asks what resources to load + switch (obji.ID) { + case 0x019A: + return {mdl:[{nsbmd:"car_a.nsbmd"}]}; //one model, car + case 0x019C: + return {mdl:[{nsbmd:"truck_a.nsbmd"}]}; //one model, truck + case 0x0195: + return {mdl:[{nsbmd:"bus_a.nsbmd"}]}; //one model, bus + } + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + } +} + +window.ObjCar = ObjTruck; +window.ObjBus = ObjTruck; \ No newline at end of file diff --git a/Code/Entities/water.js b/Code/Entities/water.js new file mode 100644 index 0000000..523e917 --- /dev/null +++ b/Code/Entities/water.js @@ -0,0 +1,86 @@ +// +// water.js +//-------------------- +// Provides multiple types of traffic. +// by RHY3756547 +// +// includes: +// render stuff idk +// + +window.ObjWater = function(obji, scene) { + var obji = obji; + var res = []; + + var t = this; + + t.pos = vec3.clone(obji.pos); + //t.angle = vec3.clone(obji.angle); + t.scale = vec3.clone(obji.scale); + + t.requireRes = requireRes; + t.provideRes = provideRes; + t.update = update; + t.draw = draw; + var frame = 0; + + function draw(view, pMatrix) { + if (nitroRender.flagShadow) return; + var waterM = mat4.create(); + + gl.enable(gl.STENCIL_TEST); + gl.stencilMask(0xFF); + + gl.stencilFunc(gl.ALWAYS, 1, 0xFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE); //when depth test passes for water lower layer, pixel is already drawn, do not cover it with the white overlay (set stencil bit) + + var height = (t.pos[1])+6.144+Math.sin(frame/150)*12.288 //0.106 + + mat4.translate(waterM, view, [Math.sin(frame/180)*96, height-3.072, Math.cos(frame/146)*96]) + nitroRender.setAlpha(0x0A/31); + res.mdl[0].drawPoly(mat4.scale([], waterM, [16, 16, 16]), pMatrix, 0, 0); //water + + if (res.mdl[1] != null) { + mat4.translate(waterM, view, [-Math.sin((frame+30)/180)*96, height-3, Math.cos((frame+100)/146)*96]) + nitroRender.setAlpha(0x02/31); + res.mdl[1].draw(mat4.scale([], waterM, [16, 16, 16]), pMatrix); //water white detail part. stencil should do nothing here, since it's in the same position as the above. + } + + gl.stencilFunc(gl.EQUAL, 0, 0xFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + + if (!obji.ID == 9) { + mat4.translate(waterM, view, [0, height, 0]) + nitroRender.setAlpha(0x10/31); + res.mdl[0].drawPoly(mat4.scale([], waterM, [16, 16, 16]), pMatrix, 0, 1); //white shore wash part, water is stencil masked out + } + + gl.disable(gl.STENCIL_TEST); + + nitroRender.setAlpha(1); + } + + function update() { + frame = (frame+1)%197100; //it's a big number but yolo... we have the technology... + } + + function requireRes() { //scene asks what resources to load + switch (obji.ID) { + case 0x0001: + return {mdl:[{nsbmd:"beach_waterC.nsbmd"}, {nsbmd:"beach_waterA.nsbmd"}]}; + case 0x0003: + return {mdl:[{nsbmd:"town_waterC.nsbmd"}, {nsbmd:"town_waterA.nsbmd"}]}; + case 0x0006: + return {mdl:[{nsbmd:"yoshi_waterC.nsbmd"}]}; + case 0x0009: + return {mdl:[{nsbmd:"hyudoro_waterC.nsbmd"}, {nsbmd:"hyudoro_waterA.nsbmd"}]}; + case 0x000C: + return {mdl:[{nsbmd:"mini_stage3_waterC.nsbmd"}, {nsbmd:"mini_stage3_waterA.nsbmd"}]}; + } + } + + function provideRes(r) { + res = r; //...and gives them to us. :) + } + +} \ No newline at end of file diff --git a/Code/Formats/.subl29.tmp b/Code/Formats/.subl29.tmp new file mode 100644 index 0000000..a406902 --- /dev/null +++ b/Code/Formats/.subl29.tmp @@ -0,0 +1,158 @@ +// +// nsbtx.js +//-------------------- +// Reads NSBTX files (or TEX0 sections) and provides canvases containing decoded texture data. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// + +window.nsbtx = function(input, tex0, autogen) { + var texDataSize, texInfoOff, texOffset, compTexSize, compTexInfoOff, + compTexOffset, compTexInfoDataOff /*wtf*/, palSize, palInfoOff, + palOffset, mainOff + + var textureInfo, paletteInfo, palData, texData, colourBuffer + var thisObj = this; + + var bitDepths = [0, 8, 2, 4, 8, 2, 8, 16] + + if (input != null) { + load(input, tex0, autogen); + } + this.load = load; + this.readTexWithPal = readTexWithPal; + + this.scopeEval = function(code) {return eval(code)} //for debug purposes + + function load(input, tex0, autogen) { + var colourBuffer = new Uint32Array(4); + var view = new DataView(input); + var header = null; + var offset = 0; + if (!tex0) { //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BTX0") throw "NSBTX invalid. Expected BTX0, found "+header.stamp; + if (header.numSections > 1) throw "NSBTX invalid. Too many sections - should only have one."; + offset = header.sectionOffsets[0]; + } + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp; + var size = view.getUint32(offset+0x04, true); + var texDataSize = view.getUint16(offset+0x0C, true)<<8; + var texInfoOff = view.getUint16(offset+0x0E, true); + var texOffset = view.getUint16(offset+0x14, true); + + var compTexSize = view.getUint16(offset+0x1C, true)<<8; + var compTexInfoOff = view.getUint16(offset+0x1E, true); + var compTexOffset = view.getUint32(offset+0x24, true); + var compTexInfoDataOff = view.getUint32(offset+0x28, true); + + var palSize = view.getUint32(offset+0x30, true)<<3; + var palInfoOff = view.getUint32(offset+0x34, true); + var palOffset = view.getUint32(offset+0x38, true); + + //read palletes, then textures. + palData = input.slice(mainOff + palOffset, palSize); + texData = input.slice(mainOff + texOffset, texDataSize); + + paletteInfo = nitro.read3dInfo(view, palInfoOff, palInfoHandler); + textureInfo = nitro.read3dInfo(view, texInfoOff, texInfoHandler); + + /*if (f) { + console.log(textureInfo.objectData.length) + for (var i=0; i>((i%4)*2))&3) + if (i%4 == 3) databuf = texView.readUint8(++off); + } else if (bitDepths == 4) { + if (i%2 == 0) { + col = readPalColour(palView, palOff, databuf&15) + } else { + col = readPalColour(palView, palOff, databuf>>4) + databuf = texView.readUint8(++off); + } + } else if (bitDepths == 8) { + col = readPalColour(palView, palOff, texView.readUint8(off)) + off += 1; + } else if (bitDepths == 16) { + col = readPalColour(palView, palOff, texView.readUint16(off, true)) + off += 2; + } + data.data.set(col, i*4); + } + return canvas; + } + + function readPalColour(view, palOff, ind) { + var col = palView.getUint16(palOff+ind*2, true); + colourBuffer[0] = Math.round(((col&31)/31)*255) + colourBuffer[1] = Math.round((((col>>5)&31)/31)*255) + colourBuffer[2] = Math.round((((col>>10)&31)/31)*255) + colourBuffer[3] = Math.round((col>>15)*255) + } + + function palInfoHandler(view, offset) { + var palOffset = view.getUint16(offset, true)<<3; + var unknown = view.getUint16(offset+2, true); + return { + palOffset: palOffset, + nextoff: offset+4 + } + } + + function texInfoHandler(view, offset) { + var texOffset = view.getUint16(offset, true)<<3; + var flags = view.getUint16(offset+2, true); + var width2 = view.getUint8(offset+4, true); + var unknown = view.getUint8(offset+5, true); + var height2 = view.getUint8(offset+6, true); + var unknown2 = view.getUint8(offset+7, true); + return { + texOffset: texOffset, + pal: (flags>>13), + format: ((flags>>10)&7), + height: ((flags>>7)&7)<<3, + width: ((flags>>4)&7)<<3, + + nextoff: offset+8 + } + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/Code/Formats/.subl509.tmp b/Code/Formats/.subl509.tmp new file mode 100644 index 0000000..a92148c --- /dev/null +++ b/Code/Formats/.subl509.tmp @@ -0,0 +1,158 @@ +// +// nsbtx.js +//-------------------- +// Reads NSBTX files (or TEX0 sections) and provides canvases containing decoded texture data. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// + +window.nsbtx = function(input, tex0, autogen) { + var texDataSize, texInfoOff, texOffset, compTexSize, compTexInfoOff, + compTexOffset, compTexInfoDataOff /*wtf*/, palSize, palInfoOff, + palOffset, mainOff + + var textureInfo, paletteInfo, palData, texData, colourBuffer + var thisObj = this; + + var bitDepths = [0, 8, 2, 4, 8, 2, 8, 16] + + if (input != null) { + load(input, tex0, autogen); + } + this.load = load; + this.readTexWithPal = readTexWithPal; + + this.scopeEval = function(code) {return eval(code)} //for debug purposes + + function load(input, tex0, autogen) { + var colourBuffer = new Uint32Array(4); + var view = new DataView(input); + var header = null; + var offset = 0; + if (!tex0) { //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BTX0") throw "NSBTX invalid. Expected BTX0, found "+header.stamp; + if (header.numSections > 1) throw "NSBTX invalid. Too many sections - should only have one."; + offset = header.sectionOffsets[0]; + } + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp; + var size = view.getUint32(offset+0x04, true); + var texDataSize = view.getUint16(offset+0x0C, true)<<8; + var texInfoOff = view.getUint16(offset+0x0E, true); + var texOffset = view.getUint16(offset+0x14, true); + + var compTexSize = view.getUint16(offset+0x1C, true)<<8; + var compTexInfoOff = view.getUint16(offset+0x1E, true); + var compTexOffset = view.getUint32(offset+0x24, true); + var compTexInfoDataOff = view.getUint32(offset+0x28, true); + + var palSize = view.getUint32(offset+0x30, true)<<3; + var palInfoOff = view.getUint32(offset+0x34, true); + var palOffset = view.getUint32(offset+0x38, true); + + //read palletes, then textures. + palData = input.slice(mainOff + palOffset, palSize); + texData = input.slice(mainOff + texOffset, texDataSize); + + paletteInfo = nitro.read3dInfo(view, palInfoOff, palInfoHandler); + textureInfo = nitro.read3dInfo(view, texInfoOff, texInfoHandler); + + if (autogen) { + console.log(textureInfo.objectData.length) + for (var i=0; i>((i%4)*2))&3) + if (i%4 == 3) databuf = texView.readUint8(++off); + } else if (bitDepths == 4) { + if (i%2 == 0) { + col = readPalColour(palView, palOff, databuf&15) + } else { + col = readPalColour(palView, palOff, databuf>>4) + databuf = texView.readUint8(++off); + } + } else if (bitDepths == 8) { + col = readPalColour(palView, palOff, texView.readUint8(off)) + off += 1; + } else if (bitDepths == 16) { + col = readPalColour(palView, palOff, texView.readUint16(off, true)) + off += 2; + } + data.data.set(col, i*4); + } + return canvas; + } + + function readPalColour(view, palOff, ind) { + var col = palView.getUint16(palOff+ind*2, true); + colourBuffer[0] = Math.round(((col&31)/31)*255) + colourBuffer[1] = Math.round((((col>>5)&31)/31)*255) + colourBuffer[2] = Math.round((((col>>10)&31)/31)*255) + colourBuffer[3] = Math.round((col>>15)*255) + } + + function palInfoHandler(view, offset) { + var palOffset = view.getUint16(offset, true)<<3; + var unknown = view.getUint16(offset+2, true); + return { + palOffset: palOffset, + nextoff: offset+4 + } + } + + function texInfoHandler(view, offset) { + var texOffset = view.getUint16(offset, true)<<3; + var flags = view.getUint16(offset+2, true); + var width2 = view.getUint8(offset+4, true); + var unknown = view.getUint8(offset+5, true); + var height2 = view.getUint8(offset+6, true); + var unknown2 = view.getUint8(offset+7, true); + return { + texOffset: texOffset, + pal: (flags>>13), + format: ((flags>>10)&7), + height: ((flags>>7)&7)<<3, + width: ((flags>>4)&7)<<3, + + nextoff: offset+8 + } + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/Code/Formats/.sublaf1.tmp b/Code/Formats/.sublaf1.tmp new file mode 100644 index 0000000..0969e34 --- /dev/null +++ b/Code/Formats/.sublaf1.tmp @@ -0,0 +1,158 @@ +// +// nsbtx.js +//-------------------- +// Reads NSBTX files (or TEX0 sections) and provides canvases containing decoded texture data. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// + +window.nsbtx = function(input, tex0, autogen) { + var texDataSize, texInfoOff, texOffset, compTexSize, compTexInfoOff, + compTexOffset, compTexInfoDataOff /*wtf*/, palSize, palInfoOff, + palOffset, mainOff + + var textureInfo, paletteInfo, palData, texData, colourBuffer + var thisObj = this; + + var bitDepths = [0, 8, 2, 4, 8, 2, 8, 16] + + if (input != null) { + load(input, tex0, autogen); + } + this.load = load; + this.readTexWithPal = readTexWithPal; + + this.scopeEval = function(code) {return eval(code)} //for debug purposes + + function load(input, tex0, autogen) { + var colourBuffer = new Uint32Array(4); + var view = new DataView(input); + var header = null; + var offset = 0; + if (!tex0) { //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BTX0") throw "NSBTX invalid. Expected BTX0, found "+header.stamp; + if (header.numSections > 1) throw "NSBTX invalid. Too many sections - should only have one."; + offset = header.sectionOffsets[0]; + } + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp; + var size = view.getUint32(offset+0x04, true); + var texDataSize = view.getUint16(offset+0x0C, true)<<8; + var texInfoOff = view.getUint16(offset+0x0E, true); + var texOffset = view.getUint16(offset+0x14, true); + + var compTexSize = view.getUint16(offset+0x1C, true)<<8; + var compTexInfoOff = view.getUint16(offset+0x1E, true); + var compTexOffset = view.getUint32(offset+0x24, true); + var compTexInfoDataOff = view.getUint32(offset+0x28, true); + + var palSize = view.getUint32(offset+0x30, true)<<3; + var palInfoOff = view.getUint32(offset+0x34, true); + var palOffset = view.getUint32(offset+0x38, true); + + //read palletes, then textures. + palData = input.slice(mainOff + palOffset, palSize); + texData = input.slice(mainOff + texOffset, texDataSize); + + paletteInfo = nitro.read3dInfo(view, palInfoOff, palInfoHandler); + textureInfo = nitro.read3dInfo(view, texInfoOff, texInfoHandler); + + if (false) { + console.log(textureInfo.objectData.length) + for (var i=0; i>((i%4)*2))&3) + if (i%4 == 3) databuf = texView.readUint8(++off); + } else if (bitDepths == 4) { + if (i%2 == 0) { + col = readPalColour(palView, palOff, databuf&15) + } else { + col = readPalColour(palView, palOff, databuf>>4) + databuf = texView.readUint8(++off); + } + } else if (bitDepths == 8) { + col = readPalColour(palView, palOff, texView.readUint8(off)) + off += 1; + } else if (bitDepths == 16) { + col = readPalColour(palView, palOff, texView.readUint16(off, true)) + off += 2; + } + data.data.set(col, i*4); + } + return canvas; + } + + function readPalColour(view, palOff, ind) { + var col = palView.getUint16(palOff+ind*2, true); + colourBuffer[0] = Math.round(((col&31)/31)*255) + colourBuffer[1] = Math.round((((col>>5)&31)/31)*255) + colourBuffer[2] = Math.round((((col>>10)&31)/31)*255) + colourBuffer[3] = Math.round((col>>15)*255) + } + + function palInfoHandler(view, offset) { + var palOffset = view.getUint16(offset, true)<<3; + var unknown = view.getUint16(offset+2, true); + return { + palOffset: palOffset, + nextoff: offset+4 + } + } + + function texInfoHandler(view, offset) { + var texOffset = view.getUint16(offset, true)<<3; + var flags = view.getUint16(offset+2, true); + var width2 = view.getUint8(offset+4, true); + var unknown = view.getUint8(offset+5, true); + var height2 = view.getUint8(offset+6, true); + var unknown2 = view.getUint8(offset+7, true); + return { + texOffset: texOffset, + pal: (flags>>13), + format: ((flags>>10)&7), + height: ((flags>>7)&7)<<3, + width: ((flags>>4)&7)<<3, + + nextoff: offset+8 + } + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/Code/Formats/Net/netKart.js b/Code/Formats/Net/netKart.js new file mode 100644 index 0000000..6e50af1 --- /dev/null +++ b/Code/Formats/Net/netKart.js @@ -0,0 +1,113 @@ +// +// netKart.js +//-------------------- +// Singleton for serializing and restoring kart data. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /entities/kart.js +// + +window.netKart = new function() { + var animNames = ["drive", "win", "lose", "spin"] + this.saveKart = saveKart; + this.restoreKart = restoreKart; + + function saveKart(view, off, k, input) { // requires 0x60 bytes of space from the offset location + saveVec3(view, off, k.pos); + saveVec3(view, off+0xC, k.vel); + view.setFloat32(off+0x18, k.angle, true); + view.setFloat32(off+0x1C, k.physicalDir, true); + view.setFloat32(off+0x20, k.driftOff, true); + if (k.cannon != null) view.setUint16(off+0x24, k.cannon, true); + else view.setUint16(off+0x24, 0xFFFF, true); + + view.setUint16(off+0x26, k.airTime, true); + view.setUint16(off+0x28, k.lastCollided, true); + + view.setUint8(off+0x2A, k.boostMT); + view.setUint8(off+0x2B, k.boostNorm); + + view.setUint16(off+0x2C, k.stuckTo, true); + view.setUint8(off+0x2E, k.wheelTurn); + + saveVec3(view, off+0x30, k.kartColVel); + view.setUint8(off+0x3C, k.kartColTimer); + + saveVec3(view, off+0x3D, k.kartTargetNormal); + saveVec3(view, off+0x49, k.trackAttach); + + var driftFlags = ((k.drifting)?1:0)|(k.driftMode<<1)|((k.driftLanded)?8:0); + view.setUint8(off+0x55, driftFlags); + + view.setUint8(off+0x56, animNames.indexOf(k.animMode)); + + var binput = ((input.accel)?1:0)|((input.decel)?2:0)|((input.drift)?4:0); + view.setUint8(off+0x57, binput); + + view.setFloat32(off+0x58, input.turn, true); + view.setFloat32(off+0x5C, input.airTurn, true); + } + + function restoreKart(view, off, k) { // we use the same endianness format as the ds to avoid confusion. + try { + k.pos = readVec3(view, off, k.pos); + k.vel = readVec3(view, off+0xC, k.vel); + k.angle = view.getFloat32(off+0x18, true); + k.physicalDir = view.getFloat32(off+0x1C, true); + k.driftOff = view.getFloat32(off+0x20, true); + k.cannon = view.getUint16(off+0x24, true); + if (k.cannon == 0xFFFF) k.cannon = null; + + k.airTime = view.getUint16(off+0x26, true); + k.lastCollided = view.getUint16(off+0x28, true); + + k.boostMT = view.getUint8(off+0x2A); + k.boostNorm = view.getUint8(off+0x2B); + + k.stuckTo = view.getUint16(off+0x2C, true); + k.wheelTurn = view.getUint8(off+0x2E); + + k.kartColVel = readVec3(view, off+0x30, k.kartColVel); + k.kartColTimer = view.getUint8(off+0x3C); + + k.kartTargetNormal = readVec3(view, off+0x3D, k.kartTargetNormal); + k.trackAttach = readVec3(view, off+0x49, k.trackAttach); + + var driftFlags = view.getUint8(off+0x55); + + k.drifting = driftFlags&1; + k.driftMode = (driftFlags>>1)&3; + k.driftLanded = driftFlags&8; + + k.animMode = animNames[view.getUint8(off+0x56)]; + + k.controller.binput = view.getUint8(off+0x57); + + k.controller.turn = view.getFloat32(off+0x58, true); + k.controller.airTurn = view.getFloat32(off+0x5C, true); + + } catch (err) { + console.err("Kart restore failure:"+err.message); + //failed to restore kart data. may wish to disconnect on this, but it's probably better to not react. + } + } + + function saveVec3(view, off, vec) { + var vec = vec; + if (vec == null) vec = [NaN, NaN, NaN]; + view.setFloat32(off, vec[0], true); + view.setFloat32(off+4, vec[1], true); + view.setFloat32(off+8, vec[2], true); + } + + function readVec3(view, off, vec) { + var first = view.getFloat32(off, true); + if (isNaN(first)) return null; + vec = vec3.create(); + vec[0] = first; + vec[1] = view.getFloat32(off+4, true); + vec[2] = view.getFloat32(off+8, true); + return vec; + } +} \ No newline at end of file diff --git a/Code/Formats/kartoffsetdata.js b/Code/Formats/kartoffsetdata.js new file mode 100644 index 0000000..8fb0516 --- /dev/null +++ b/Code/Formats/kartoffsetdata.js @@ -0,0 +1,71 @@ +// +// kartoffsetdata.js +//-------------------- +// Provides functionality to read mario kart ds kart wheel and character model offsets. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// + +window.kartoffsetdata = function(input) { + + var thisObj = this; + + if (input != null) { + load(input); + } + this.load = load; + + function load(input) { + var view = new DataView(input); + var off = 0; + var karts = [] + for (var i=0; i<37; i++) { + var obj = {}; + obj.name = readString(view, off, 0x10); + off += 0x10; + obj.frontTireSize = view.getInt32(off, true)/4096; + off += 4; + + var wheels = []; + for (var j=0; j<4; j++) { + var pos = vec3.create(); + pos[0] = view.getInt32(off, true)/4096; + pos[1] = view.getInt32(off+4, true)/4096; + pos[2] = view.getInt32(off+8, true)/4096; + off += 12; + wheels.push(pos); + } + + var chars = []; + for (var j=0; j<13; j++) { + var pos = vec3.create(); + pos[0] = view.getInt32(off, true)/4096; + pos[1] = view.getInt32(off+4, true)/4096; + console.log("charPos: "+pos[1]); + pos[2] = view.getInt32(off+8, true)/4096; + off += 12; + chars.push(pos); + } + + obj.wheels = wheels; + obj.chars = chars; + + karts.push(obj); + } + thisObj.karts = karts; + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } + + function readString(view, offset, length) { + var str = ""; + for (var i=0; i maxx) maxx=vert[0]; + if (vert[2] < minz) minz=vert[2]; + if (vert[2] > maxz) maxz=vert[2]; + } + + console.log("minx: "+minx+" maxx: "+maxx+" minz: "+minz+" maxz: "+maxz) + + //var sfx = canvas.width/(maxx-minx); + //var sfy = canvas.height/(maxz-minz); + //offx = -((minx+maxx)/2); + //offz = -((minz+maxz)/2); + //sf = Math.min(sfx, sfy)*0.8; + octree = [] + + var rootNodes = ((~xMask >> coordShift) + 1) * ((~yMask >> coordShift) + 1) * ((~zMask >> coordShift) + 1); + + for (var i=0; i> coordShift) + 1); x++) { + for (var z=0; z<((~zMask >> coordShift) + 1); z++) { + ctx.strokeRect(topLeftVec[0]+size*x, topLeftVec[2]+size*z, size, size); + } + } + } + + function testDrawPlanes(planes) { + for (var i=1; i0 || (y&yMask)>0 || (z&zMask)>0) return []; //no collision + + var index = (x>>coordShift)|((y>>coordShift)<>coordShift)<>shift)&1)|(((y>>shift)&1)<<1)|(((z>>shift)&1)<<2); + return traverseOctree(node.items[index], x, y, z, shift-1); + } + + function decodeCube(baseoff, off, view) { + var data = view.getUint32(off, end); + var off2 = baseoff+(data&0x7FFFFFFF); + if (off2 >= view.byteLength) { + return { + leaf: true, + tris: [], + realTris: [] + } + } + if (data&0x80000000) { //is a leaf. + off2 += 2; + var tris = []; + var realTris = []; + while (true) { + var read = view.getUint16(off2, end); + if (read == 0) break; //zero terminated + tris.push(read); + realTris.push(planes[read]); + trisMapped += 1; + off2 += 2; + } + return { + leaf: true, + tris: tris, + realTris: realTris + } + } else { //contains 8 more cubes + var cubes = []; + var boff = off2; + for (var i=0; i<8; i++) { + cubes.push(decodeCube(boff, off2, view)); + off2 += 4; + } + return { + leaf: false, + items: cubes + } + } + } + + function Plane(view, offset) { + this.Len = readBigDec(view, offset, mkwiiMode); + this.Vertex1 = readVert(view.getUint16(offset+0x4, end), view); + this.Normal = readNormal(view.getUint16(offset+0x6, end), view); + this.NormalA = readNormal(view.getUint16(offset+0x8, end), view); + this.NormalB = readNormal(view.getUint16(offset+0xA, end), view); + this.NormalC = readNormal(view.getUint16(offset+0xC, end), view); + this.CollisionType = view.getUint16(offset+0xE, end); + + var crossA = vec3.cross(vec3.create(), this.NormalA, this.Normal); + var crossB = vec3.cross(vec3.create(), this.NormalB, this.Normal); + + this.Vertex2 = vec3.scaleAndAdd(vec3.create(), this.Vertex1, crossB, (this.Len/vec3.dot(crossB, this.NormalC))); + this.Vertex3 = vec3.scaleAndAdd(vec3.create(), this.Vertex1, crossA, (this.Len/vec3.dot(crossA, this.NormalC))); + } + + function readVert(num, view) { + var vec = vec3.create(); + var loc = vertexOffset+num*0xC; + vec[0] = readBigDec(view, loc, mkwiiMode); + vec[1] = readBigDec(view, loc+0x4, mkwiiMode); + vec[2] = readBigDec(view, loc+0x8, mkwiiMode); + return vec; + } + + function readNormal(num, view) { + var mkwii = mkwiiMode; + var vec = vec3.create(); + if (mkwii) { + var loc = normalOffset+num*0xC; + vec[0] = view.getFloat32(loc); + vec[1] = view.getFloat32(loc+0x4); + vec[2] = view.getFloat32(loc+0x8); + } else { + var loc = normalOffset+num*0x6; + vec[0] = view.getInt16(loc, end)/4096; //fixed point + vec[1] = view.getInt16(loc+0x2, end)/4096; + vec[2] = view.getInt16(loc+0x4, end)/4096; + } + return vec; + } +} \ No newline at end of file diff --git a/Code/Formats/lz77.js b/Code/Formats/lz77.js new file mode 100644 index 0000000..b6e5861 --- /dev/null +++ b/Code/Formats/lz77.js @@ -0,0 +1,41 @@ +// +// lz77.js +//-------------------- +// Reads and decompresses lz77 (mode 0x10 only) files. In future may be able to recompress. +// by RHY3756547 +// + +window.lz77 = new (function() { + this.decompress = function(buffer) { + var view = new DataView(buffer); + var compType = view.getUint8(0); + var size = view.getUint32(0, true)>>8; + + var targ = new ArrayBuffer(size); + var targA = new Uint8Array(targ); + + var off = 4; + var dOff = 0; + var eof = buffer.byteLength; + while (off=0; j--) { + if (off>=eof) break; + if ((flag>>j)&1) { //1=compressed, 2=raw byte + var dat = view.getUint16(off); + off += 2; + var cOff = (dOff-(dat&4095))-1; + var len = (dat>>12)+3; + + for (var k=0; k>5)&31, (dat>>10)&31]; + return col; + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } + + if (input != null) { + if (typeof input == "string") { + var xml = new XMLHttpRequest(); + xml.responseType = "arraybuffer"; + xml.open("GET", input, true); + xml.onload = function() { + load(xml.response); + } + xml.send(); + } else { + load(input, mkwii); + } + } + +} \ No newline at end of file diff --git a/Code/Formats/nsbca.js b/Code/Formats/nsbca.js new file mode 100644 index 0000000..3174932 --- /dev/null +++ b/Code/Formats/nsbca.js @@ -0,0 +1,246 @@ +// +// nsbca.js +//-------------------- +// Reads NSBCA files (bone animations) for use in combination with an NSBMD (model) file +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// + +// most investigation done by florian for the mkds course modifier. +// I've tried to keep things much simpler than they were in his code. + +window.nsbca = function(input) { + + var mainOff; + var animData; + var speeds = [1.0, 0.5, 1/3]; + var mainObj = this; + + if (input != null) { + load(input); + } + this.load = load; + + function load(input) { + var view = new DataView(input); + var header = null; + var offset = 0; + var tex; + + //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BCA0") throw "NSBCA invalid. Expected BCA0, found "+header.stamp; + if (header.numSections > 1) throw "NSBCA invalid. Too many sections - should have 1 maximum."; + offset = header.sectionOffsets[0]; + //end nitro + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "JNT0") throw "NSBCA invalid. Expected JNT0, found "+stamp; + + animData = nitro.read3dInfo(view, mainOff+8, animInfoHandler); + mainObj.animData = animData; + } + + function animInfoHandler(view, off, base) { + var offset = mainOff + view.getUint32(off, true); + var obj = {nextoff: off + 4} + readAnim(view, offset, obj); + return obj; + } + + function readAnim(view, off, obj) { + obj.baseOff = off; + obj.stamp = readChar(view, off+0x0)+readChar(view, off+0x2)+readChar(view, off+0x3); + obj.frames = view.getUint16(off+0x4, true); + obj.numObj = view.getUint16(off+0x6, true); + obj.unknown = view.getUint32(off+0x8, true); //NOTE: this may be a flag. used later to specify extra frames if not = 3 + obj.off1 = view.getUint32(off+0xC, true); + obj.off2 = view.getUint32(off+0x10, true); //offset to rotation data + off += 0x14; + var transforms = []; + for (var i=0; i>1) & 1)) { //T: translation + var translate = [[], [], []]; //store translations in x,y,z arrays + var tlExtra = []; + + for (var i=0; i<3; i++) { //iterate over x y z (for translation) + var f = (flag>>(3+i))&1; + if (f) { //one value + translate[i].push(view.getInt32(off, true)/4096); + off += 4; + } else { //credit to florian for cracking this. + var inf = {}; + inf.startFrame = view.getUint16(off, true) + var dat = view.getUint16(off+2, true) + inf.endFrame = dat&0x0FFF; + inf.halfSize = ((dat>>12)&3); + inf.speed = speeds[((dat>>14)&3)]; + inf.off = view.getUint32(off+4, true); + + var extra = (obj.unknown != 3)?0:(obj.frames-inf.endFrame); + var length = Math.floor((obj.frames+extra)*inf.speed); + var w = (inf.halfSize)?2:4; + + var off2 = obj.baseOff+inf.off; + for (var j=0; j>6) & 1)) { //R: rotation, which is both fun and exciting. + + var rotate = []; + var rotExtra; + + var f = (flag>>8)&1; + if (f) { //one value + rotate.push(readRotation(view, off, obj)); + off += 4; + } else { //credit to florian for cracking this. + var inf = {}; + inf.startFrame = view.getUint16(off, true) + var dat = view.getUint16(off+2, true) //low 12 bits are end frame, high 4 are size flag and speed + inf.endFrame = dat&0x0FFF; + inf.halfSize = ((dat>>12)&3); //not used by rotation? + inf.speed = speeds[((dat>>14)&3)]; + inf.off = view.getUint32(off+4, true); + var extra = (obj.unknown != 3)?0:(obj.frames-inf.endFrame); + //florian's rotate code seems to ignore this extra value. I'll need more examples of nsbca to test this more thoroughly. + var length = Math.floor((obj.frames+extra)*inf.speed); + + var off2 = obj.baseOff+inf.off; + try { + for (var j=0; j>9) & 1)) { //S: scale + var scale = [[], [], []]; //store scales in x,y,z arrays + var scExtra = []; + + for (var i=0; i<3; i++) { //iterate over x y z (for scale) + var f = (flag>>(11+i))&1; + if (f) { //one value + scale[i].push({ + s1: view.getInt32(off, true)/4096, + s2: view.getInt32(off, true)/4096 + }); + off += 8; + } else { //credit to florian for cracking this. + var inf = {}; + inf.startFrame = view.getUint16(off, true) + var dat = view.getUint16(off+2, true) + inf.endFrame = dat&0x0FFF; + inf.halfSize = ((dat>>12)&3); + inf.speed = speeds[((dat>>14)&3)]; + inf.off = view.getUint32(off+4, true); + + var extra = (obj.unknown != 3)?0:(obj.frames-inf.endFrame); + var length = Math.ceil((obj.frames+extra)*inf.speed); + var w = ((inf.halfSize)?2:4); + + var off2 = obj.baseOff+inf.off; + for (var j=0; j>15); + + if (mode) { //rotation is pivot + var off2 = obj.baseOff+obj.off1+ind*6; //jump to rotation data + return { + pivot: true, + param: view.getUint16(off2, true), + a: view.getInt16(off2+2, true)/4096, + b: view.getInt16(off2+4, true)/4096 + }; + } else { + var off2 = obj.baseOff+obj.off2+ind*10; //jump to rotation data + var d1 = view.getInt16(off2, true); + var d2 = view.getInt16(off2+2, true); + var d3 = view.getInt16(off2+4, true); + var d4 = view.getInt16(off2+6, true); + var d5 = view.getInt16(off2+8, true); + + var i6 = ((d5&7)<<12) | ((d1&7)<<9) | ((d2&7)<<6) | ((d3&7)<<3) | ((d4&7)); + if (i6&4096) i6 = (-8192)+i6; + + var v1 = [d1>>3, d2>>3, d3>>3] + var v2 = [d4>>3, d5>>3, i6] + + vec3.scale(v1, v1, 1/4096); + vec3.scale(v2, v2, 1/4096); + var v3 = vec3.cross([], v1, v2) + + var mat = [ + v1[0], v1[1], v1[2], + v2[0], v2[1], v2[2], + v3[0], v3[1], v3[2] + ] + + return { + pivot: false, + mat: mat + }; + } + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/Code/Formats/nsbmd.js b/Code/Formats/nsbmd.js new file mode 100644 index 0000000..b266e85 --- /dev/null +++ b/Code/Formats/nsbmd.js @@ -0,0 +1,411 @@ +// +// nsbmd.js +//-------------------- +// Reads NSBMD models and any texture data within them. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// /formats/nsbtx.js +// + +window.nsbmd = function(input) { + + var mainOff, modelData, texPalOff, materials; + var mainObj = this; + + if (input != null) { + load(input); + } + this.load = load; + + + function load(input) { + mainObj.hasBillboards = false; + var view = new DataView(input); + var header = null; + var offset = 0; + var tex; + + //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BMD0") throw "NSBMD invalid. Expected BMD0, found "+header.stamp; + if (header.numSections > 2) throw "NSBMD invalid. Too many sections - should have 2 maximum."; + if (header.numSections == 2) tex = new nsbtx(input.slice(header.sectionOffsets[1]), true, true); + offset = header.sectionOffsets[0]; + //end nitro + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "MDL0") throw "NSBMD invalid. Expected MDL0, found "+stamp; + + mainObj.tex = tex; + + modelData = nitro.read3dInfo(view, mainOff+8, modelInfoHandler); + mainObj.modelData = modelData; + } + + function modelInfoHandler(view, offset) { + var mdlOff = view.getUint32(offset, true); + + var off = mainOff+mdlOff; + var obj = readModelData(view, off); + obj.nextoff = offset+4; + + return obj; + } + + function readModelData(view, offset) { + var head = {} + head.blockSize = view.getUint32(offset, true); + head.bonesOffset = offset+view.getUint32(offset+4, true); + head.materialsOffset = offset+view.getUint32(offset+8, true); + head.polyStartOffset = offset+view.getUint32(offset+0xC, true); + head.polyEndOffset = offset+view.getUint32(offset+0x10, true); + + head.numObjects = view.getUint8(offset+0x17); + head.numMaterials = view.getUint8(offset+0x18); + head.numPolys = view.getUint8(offset+0x19); + head.maxStack = view.getUint8(offset+0x1A); + + head.scale = view.getInt32(offset+0x1C, true)/4096; + + head.numVerts = view.getUint16(offset+0x24, true); + head.numSurfaces = view.getUint16(offset+0x26, true); + head.numTriangles = view.getUint16(offset+0x28, true); + head.numQuads = view.getUint16(offset+0x2A, true); + + head.bboxX = view.getInt16(offset+0x2C, true)/4096; + head.bboxY = view.getInt16(offset+0x2E, true)/4096; + head.bboxZ = view.getInt16(offset+0x30, true)/4096; + head.bboxWidth = view.getInt16(offset+0x32, true)/4096; + head.bboxHeight = view.getInt16(offset+0x34, true)/4096; + head.bboxDepth = view.getInt16(offset+0x36, true)/4096; + //head.runtimeData = view.getUint64(offset+0x38, true); + texPalOff = head.materialsOffset; //leak into local scope so it can be used by tex and pal bindings + + var objects = nitro.read3dInfo(view, offset+0x40, objInfoHandler); + var polys = nitro.read3dInfo(view, head.polyStartOffset, polyInfoHandler); + + materials = nitro.read3dInfo(view, head.materialsOffset+4, matInfoHandler); + + var tex = nitro.read3dInfo(view, head.materialsOffset+view.getUint16(head.materialsOffset, true), texInfoHandler); + var palt = nitro.read3dInfo(view, head.materialsOffset+view.getUint16(head.materialsOffset+2, true), palInfoHandler); + + var commands = parseBones(head.bonesOffset, view, polys, materials, objects, head.maxStack); + + return {head: head, objects: objects, polys: polys, materials: materials, tex:tex, palt:palt, commands:commands} + } + + function parseBones(offset, view, polys, materials, objects, maxStack) { + var last; + var commands = []; + + var freeStack = maxStack; + var forceID=null; + var lastMat = null; + + while (offset 10) debugger; + break; + case 3: //stack id for poly (wit) + forceID = view.getUint8(offset++); + console.log("stackid is "+forceID); + case 0: + break; + case 5: + //i don't... what?? + //holy shp! + var poly = view.getUint8(offset++); + polys.objectData[poly].stackID = (stackID == null)?(commands[commands.length-1].forceID):forceID; + polys.objectData[poly].mat = lastMat; + + break; + case 7: + //sets object to be billboard + var obj = view.getUint8(offset++); + objects.objectData[obj].billboardMode = 1; + mainObj.hasBillboards = true; + break; + case 8: + //sets object to be billboard around only y axis. (xz remain unchanged) + var obj = view.getUint8(offset++); + objects.objectData[obj].billboardMode = 2; + mainObj.hasBillboards = true; + break; + case 0x0b: + break; //begin, not quite sure what of. doesn't seem to change anything + case 0x2b: + break; //end + default: + console.log("bone transform unknown: "+last); + break; + } + } + //if (window.throwWhatever) debugger; + return commands; + } + + function matInfoHandler(view, off, base) { + var offset = texPalOff + view.getUint32(off, true); + + var rel = 0; + /*while (rel < 40) { + var flags = view.getUint16(offset+rel, true); + if ((flags&15)==15) console.log("rel at "+rel); + rel += 2; + }*/ + + var polyAttrib = view.getUint16(offset+12, true); + console.log(polyAttrib); + + var flags = view.getUint16(offset+22, true); //other info in here is specular data etc. + + //scale starts at 44; + + var mat; + offset += 44; + switch ((flags>>14) & 0x03) { //texture scaling mode + case 0: + mat = mat3.create(); //no scale + break; + case 1: + mat = mat3.create(); + mat3.scale(mat, mat, [view.getInt32(offset, true)/4096, view.getInt32(offset+4, true)/4096]); + //mat3.translate(mat, mat, [-anim.translateS[(texFrame>>anim.frameStep.translateS)%anim.translateS.length], anim.translateT[(texFrame>>anim.frameStep.translateT)%anim.translateT.length]]) //for some mystery reason I need to negate the S translation + + break; + case 2: + case 3: + mat = mat3.create(); //custom tex mat + alert("custom"); + for (var i=0; i<16; i++) { + mat[i] = view.getInt32(offset, true)/4096; + offset += 4; + } + } + + var cullMode = ((polyAttrib>>6)&3); + + var alpha = ((polyAttrib>>16)&31)/31; + if (alpha == 0) alpha = 1; + + return { + height: 8 << ((flags>>7)&7), + width: 8 << ((flags>>4)&7), + repeatX: flags&1, + repeatY: (flags>>1)&1, + flipX: (flags>>2)&1, + flipY: (flags>>3)&1, + texMat: mat, + alpha: alpha, + cullMode: cullMode, + nextoff: off + 4 + } + } + + function texInfoHandler(view, off, base, ind) { + var oDat = texPalOff+view.getUint16(off, true); //contains offset to array of materials to bind to + var num = view.getUint8(off+2, true); + var mats = []; + for (var i=0; i>4)&15; + neg = (flag>>8)&15; + A = view.getInt16(offset+0x4, true)/4096; + B = view.getInt16(offset+0x6, true)/4096; + + pivot[mode] = (neg&1)?-1:1; + var horiz = mode%3; + var vert = Math.floor(mode/3) + var left = (horiz==0)?1:0; var top = ((vert==0)?1:0)*3; + var right = (horiz==2)?1:2; var btm = ((vert==2)?1:2)*3; + pivot[left+top] = A; + pivot[right+top] = B; + pivot[left+btm] = (neg&2)?-B:B; + pivot[right+btm] = (neg&4)?-A:A; + + offset += 4; + } else { + pivot = mat3.create() + } + var scale = vec3.create(); + if (!(flag&4)) { + scale[0] = view.getInt32(offset+0x4, true)/4096; + scale[1] = view.getInt32(offset+0x8, true)/4096; + scale[2] = view.getInt32(offset+0xC, true)/4096; + offset += 0xC; + } else { + scale[0] = 1; + scale[1] = 1; + scale[2] = 1; + } + if ((!(flag&8)) && (!(flag&2))) { //rotate matrix, replaces pivot + pivot[0] = rotTerm1; + pivot[1] = view.getInt16(offset+0x4, true)/4096; + pivot[2] = view.getInt16(offset+0x6, true)/4096; + pivot[3] = view.getInt16(offset+0x8, true)/4096; + pivot[4] = view.getInt16(offset+0xA, true)/4096; + pivot[5] = view.getInt16(offset+0xC, true)/4096; + pivot[6] = view.getInt16(offset+0xE, true)/4096; + pivot[7] = view.getInt16(offset+0x10, true)/4096; + pivot[8] = view.getInt16(offset+0x12, true)/4096; + offset += 16; + } + var mat = mat4.create(); + mat4.translate(mat, mat, translate); + mat4.multiply(mat, mat, mat4FromMat3(pivot)); + mat4.scale(mat, mat, scale); + return { + translate: translate, + pivot: pivot, + + pA: A, + pB: B, + pMode: mode, + pNeg: neg, + + scale: scale, + flag: flag, + mat: mat, + billboardMode: 0, + nextoff: off + 4 + } + } + + function mat4FromMat3(mat) { + dest = mat4.create(); + + dest[0] = mat[0]; + dest[1] = mat[1]; + dest[2] = mat[2]; + dest[3] = 0; + + dest[4] = mat[3]; + dest[5] = mat[4]; + dest[6] = mat[5]; + dest[7] = 0; + + dest[8] = mat[6]; + dest[9] = mat[7]; + dest[10] = mat[8]; + dest[11] = 0; + + dest[12] = 0; + dest[13] = 0; + dest[14] = 0; + dest[15] = 1; + + return dest; + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/Code/Formats/nsbta.js b/Code/Formats/nsbta.js new file mode 100644 index 0000000..d9ab0e0 --- /dev/null +++ b/Code/Formats/nsbta.js @@ -0,0 +1,142 @@ +// +// nsbta.js +//-------------------- +// Reads NSBTA files (texture uv animation via uv transform matrices within a polygon) for use in combination with an NSBMD (model) file +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js +// + +// man oh man if only there were some documentation on this that weren't shoddily written code in mkds course modifier +// well i guess we can find out how the format works +// together :') + +window.nsbta = function(input) { + + var mainOff; + var animData; + var mainObj = this; + var prop = [ + "scaleS", + "scaleT", + "rotation", + "translateS", + "translateT" + ] + + if (input != null) { + load(input); + } + this.load = load; + + + function load(input) { + var view = new DataView(input); + var header = null; + var offset = 0; + var tex; + + //nitro 3d header + header = nitro.readHeader(view); + if (header.stamp != "BTA0") throw "NSBTA invalid. Expected BTA0, found "+header.stamp; + if (header.numSections > 1) throw "NSBTA invalid. Too many sections - should have 1 maximum."; + offset = header.sectionOffsets[0]; + //end nitro + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "SRT0") throw "NSBTA invalid. Expected SRT0, found "+stamp; + + animData = nitro.read3dInfo(view, mainOff+8, animInfoHandler); + mainObj.animData = animData; + } + + function animInfoHandler(view, offset) { + var animOff = view.getUint32(offset, true); + + var off = mainOff+animOff; + var obj = readAnimData(view, off); + obj.nextoff = offset+4; + + return obj; + } + + function readAnimData(view, offset) { + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); //should be M_AT, where _ is a 0 character + var unknown1 = view.getUint16(offset+4, true); + var unknown2 = view.getUint8(offset+6, false); + var unknown3 = view.getUint8(offset+7, false); + var data = nitro.read3dInfo(view, offset+8, matInfoHandler); + return {data: data, nextoff: data.nextoff}; + } + + function matInfoHandler(view, offset, base) { + // there doesn't seem to be any documentation on this so I'm going to take the first step and maybe explain a few things here: + // each material has 5 sets of 16 bit values of the following type: + // + // frames: determines the number of frames worth of transforms of this type are stored + // flags: if >4096 then multiple frames are used instead of inline data. not much else is known + // offset/data: depending on previous flag, either points to an array of data or provides the data for the sole frame. relative to base of this 3dinfoobject + // data2: used for rotation matrix (second value) + // + // order is as follows: + // scaleS, scaleT, rotation, translateS, translateT (all values are signed fixed point 1.3.12) + // + // note: rotation external data has two 16 bit integers instead of one per frame. + // + // also!! rotation matrices work as follows: + // + // | B A | + // | -A B | + // + // kind of like nsbmd pivot + + var obj = {} + obj.flags = []; //for debug + obj.frames = []; + obj.frameStep = {}; + + for (var i=0; i<5; i++) { + + obj[prop[i]] = []; + var frames = view.getUint16(offset, true); + var flags = view.getUint16(offset+2, true); + var value = view.getUint16(offset+4, true); + var data2 = view.getInt16(offset+6, true)/4096; + + //flags research so far: + //bit 13 (8196) - set if inline single frame data, unset if multiple frame data at offset + //bit 14-15 - framestep, aka what to shift frame counters by (eg for half framerate this would be 1, frame>>1, essentially dividing the frame speed by 2.) + + obj.frameStep[prop[i]] = (flags>>14); + obj.flags[i] = flags; + obj.frames[i] = frames; + + if (flags & 8192) { + if (value & 32768) value = 65536-value; //convert to int + obj[prop[i]].push(value/4096); + if (i == 2) obj[prop[i]].push(data2); + } else { //data is found at offset + frames = frames>>obj.frameStep[prop[i]]; + //frames -= 1; + var off = base + value-8; + for (var j=0; j 1) throw "NSBTP invalid. Too many sections - should have 1 maximum."; + offset = header.sectionOffsets[0]; + //end nitro + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "PAT0") throw "NSBTP invalid. Expected PAT0, found "+stamp; + + animData = nitro.read3dInfo(view, mainOff+8, animInfoHandler); + debugger; + mainObj.animData = animData; + } + + function animInfoHandler(view, offset) { + var animOff = view.getUint32(offset, true); + + var off = mainOff+animOff; + var obj = readAnimData(view, off); + obj.nextoff = offset+4; + + return obj; + } + + function readAnimData(view, offset) { + matOff = offset; + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); //should be M_PT, where _ is a 0 character + + offset += 4; + //b400 0303 4400 7400 - countdown (3..2..1.. then start is another model, duration 180 frames, 3 frames of anim) + //1400 0404 4800 8800 - kuribo (4 frames, shorter animation duration) + //1e00 0202 4000 6000 - pinball stage (2 frames) + //0200 0202 4000 6000 - fish, cow and crab (duration and total 2 frames, unusually short animation) + //0d00 0404 5000 9000 - bat (duration 13, 6 frames, uneven pacing) + + //16bit duration (60fps frames, total) + //8bit tex start + //8bit pal start + //16bit unknown (flags? kuribo repeats by playing backwards) + //16bit unknown + + //example data, for 3 mat 3 pal data + //var tinfo = texInfoHandler(view, offset+4); + //8 bytes here? looks like texinfo + + var duration = view.getUint16(offset, true); + var tframes = view.getUint8(offset+2); + var pframes = view.getUint8(offset+3); + var unknown = view.getUint16(offset+4, true); + var unknown2 = view.getUint16(offset+6, true); + + //...then another nitro + var data = nitro.read3dInfo(view, offset+8, matInfoHandler); + + return {data: data, nextoff: data.nextoff, tframes:tframes, pframes:pframes, unknown:unknown, unknown2:unknown2, duration:duration}; + } + + function matInfoHandler(view, offset, base) { + var obj = {} + obj.frames = []; + + // in here... + // 16bit frames + // 16bit maybe material number (probably? mostly 0) to replace + // 16bit unknown (flags? 0x4400 count, 0x1101 waluigi, 0x3303 goomba, 0x0010 fish) + // 16bit offset from M_PT (always 0x38) + + //at offset (frame of these) + // 16bit happenAt + // 8bit tex + // 8bit pal + + //then (frame of these) + // 16char texname + //then (frame of these) + // 16char palname + + var frames = view.getUint16(offset, true); + obj.matinfo = view.getUint16(offset+2, true); + obj.flags = view.getUint16(offset+4, true); + var offset2 = view.getUint16(offset+6, true); + offset += 8; + obj.nextoff = offset; + + offset = matOff + offset2; + //info and timing for each frame + for (var i=0; i 1) throw "NSBTX invalid. Too many sections - should only have one."; + offset = header.sectionOffsets[0]; + } + + mainOff = offset; + + var stamp = readChar(view, offset+0x0)+readChar(view, offset+0x1)+readChar(view, offset+0x2)+readChar(view, offset+0x3); + if (stamp != "TEX0") throw "NSBTX invalid. Expected TEX0, found "+stamp; + var size = view.getUint32(offset+0x04, true); + texDataSize = view.getUint16(offset+0x0C, true)<<3; + texInfoOff = view.getUint16(offset+0x0E, true); + texOffset = view.getUint16(offset+0x14, true); + + compTexSize = view.getUint16(offset+0x1C, true)<<3; + compTexInfoOff = view.getUint16(offset+0x1E, true); + compTexOffset = view.getUint32(offset+0x24, true); + compTexInfoDataOff = view.getUint32(offset+0x28, true); + + palSize = view.getUint32(offset+0x30, true)<<3; + palInfoOff = view.getUint32(offset+0x34, true); + palOffset = view.getUint32(offset+0x38, true); + + //read palletes, then textures. + var po = mainOff + palOffset; + palData = input.slice(po, po+palSize); + + var to = mainOff + texOffset; + texData = input.slice(to, to+texDataSize); + + var co = mainOff + compTexOffset; + compData = input.slice(co, co+compTexSize); //pixel information for compression. 2bpp, 16 pixels, so per 4x4 block takes up 4 bytes + + var cio = mainOff + compTexInfoDataOff; + compInfoData = input.slice(cio, cio+compTexSize/2); //each 4x4 block has a 16bit information uint. 2 bytes per block, thus half the size of above. + + + paletteInfo = nitro.read3dInfo(view, mainOff + palInfoOff, palInfoHandler); + textureInfo = nitro.read3dInfo(view, mainOff + texInfoOff, texInfoHandler); + + thisObj.paletteInfo = paletteInfo; + thisObj.textureInfo = textureInfo; + } + + function readTexWithPal(textureId, palId) { + var tex = textureInfo.objectData[textureId]; + var pal = paletteInfo.objectData[palId]; + + var format = tex.format; + var trans = tex.pal0trans; + + if (format == 5) return readCompressedTex(tex, pal); //compressed 4x4 texture, different processing entirely + + var off = tex.texOffset; + var palView = new DataView(palData); + var texView = new DataView(texData); + var palOff = pal.palOffset; + + var canvas = document.createElement("canvas"); + canvas.width = tex.width; + canvas.height = tex.height; + var ctx = canvas.getContext("2d"); + var img = ctx.getImageData(0, 0, tex.width, tex.height); + + var total = tex.width*tex.height; + var databuf; + for (var i=0; i>5)*(255/7); + + } else if (format == 2) { //2 bit pal + if (i%4 == 0) databuf = texView.getUint8(off++); + col = readPalColour(palView, palOff, (databuf>>((i%4)*2))&3, trans) + + } else if (format == 3) { //4 bit pal + if (i%2 == 0) { + databuf = texView.getUint8(off++); + col = readPalColour(palView, palOff, databuf&15, trans) + } else { + col = readPalColour(palView, palOff, databuf>>4, trans) + } + + } else if (format == 4) { //8 bit pal + col = readPalColour(palView, palOff, texView.getUint8(off++), trans) + + } else if (format == 6) { //A5I3 encoding. 5 bits alpha 3 bits pal index + var dat = texView.getUint8(off++) + col = readPalColour(palView, palOff, dat&7, trans); + col[3] = (dat>>3)*(255/31); + + } else if (format == 7) { //raw color data + col = texView.getUint16(off, true); + colourBuffer[0] = Math.round(((col&31)/31)*255) + colourBuffer[1] = Math.round((((col>>5)&31)/31)*255) + colourBuffer[2] = Math.round((((col>>10)&31)/31)*255) + colourBuffer[3] = Math.round((col>>15)*255); + col = colourBuffer; + off += 2; + + } else { + console.log("texture format is none, ignoring") + return canvas; + } + img.data.set(col, i*4); + } + ctx.putImageData(img, 0, 0) + return canvas; + } + + function readCompressedTex(tex, pal) { //format 5, 4x4 texels. I'll keep this well documented so it's easy to understand. + var off = tex.texOffset; + var texView = new DataView(compData); //real texture data - 32 bits per 4x4 block (one byte per 4px horizontal line, each descending 1px) + var compView = new DataView(compInfoData); //view into compression info - informs of pallete and parameters. + var palView = new DataView(palData); //view into the texture pallete + var compOff = off/2; //info is 2 bytes per block, so the offset is half that of the tex offset. + var palOff = pal.palOffset; + var transColor = new Uint8Array([0, 0, 0, 0]); //transparent black + + var canvas = document.createElement("canvas"); + canvas.width = tex.width; + canvas.height = tex.height; + var ctx = canvas.getContext("2d"); + var img = ctx.getImageData(0, 0, tex.width, tex.height); + + var w = tex.width>>2; //iterate over blocks, block w and h is /4. + var h = tex.height>>2; + + for (var y=0; y> 14) & 3); + + var finalPo = palOff+addr*4; + var imgoff = x*4+(y*w*16); + for (var iy=0; iy<4; iy++) { + var dat = texView.getUint8(off++); + for (var ix=0; ix<4; ix++) { //iterate over horiz lines + var part = (dat>>(ix*2))&3; + var col; + + switch (mode) { + case 0: //value 3 is transparent, otherwise pal colour + if (part == 3) col = transColor; + else col = readPalColour(palView, finalPo, part); + break; + case 1: //average mode - colour 2 is average of 1st two, 3 is transparent. 0&1 are normal. + if (part == 3) col = transColor; + else if (part == 2) col = readFractionalPal(palView, finalPo, 0.5); + else col = readPalColour(palView, finalPo, part); + break; + case 2: //pal colour + col = readPalColour(palView, finalPo, part); + break; + case 3: //5/8 3/8 mode - colour 2 is 5/8 of col0 plus 3/8 of col1, 3 is 3/8 of col0 plus 5/8 of col1. 0&1 are normal. + if (part == 3) col = readFractionalPal(palView, finalPo, 3/8); + else if (part == 2) col = readFractionalPal(palView, finalPo, 5/8); + else col = readPalColour(palView, finalPo, part); + break; + } + + img.data.set(col, (imgoff++)*4) + } + imgoff += tex.width-4; + } + compOff += 2; //align off to next block + } + } + + ctx.putImageData(img, 0, 0) + return canvas; + } + + function readPalColour(view, palOff, ind, pal0trans) { + var col = view.getUint16(palOff+ind*2, true); + var f = 255/31; + colourBuffer[0] = Math.round((col&31)*f) + colourBuffer[1] = Math.round(((col>>5)&31)*f) + colourBuffer[2] = Math.round(((col>>10)&31)*f) + colourBuffer[3] = (pal0trans && ind == 0)?0:255; + return colourBuffer; + } + + function readFractionalPal(view, palOff, i) { + var col = view.getUint16(palOff, true); + var col2 = view.getUint16(palOff+2, true); + var ni = 1-i; + var f = 255/31; + colourBuffer[0] = Math.round((col&31)*f*i + (col2&31)*f*ni) + colourBuffer[1] = Math.round(((col>>5)&31)*f*i + ((col2>>5)&31)*f*ni) + colourBuffer[2] = Math.round(((col>>10)&31)*f*i + ((col2>>10)&31)*f*ni) + colourBuffer[3] = 255; + return colourBuffer; + } + + function palInfoHandler(view, offset) { + var palOffset = view.getUint16(offset, true)<<3; + var unknown = view.getUint16(offset+2, true); + return { + palOffset: palOffset, + unknown: unknown, + nextoff: offset+4 + } + } + + function texInfoHandler(view, offset) { + var texOffset = view.getUint16(offset, true)<<3; + var flags = view.getUint16(offset+2, true); + var width2 = view.getUint8(offset+4, true); + var unknown = view.getUint8(offset+5, true); + var height2 = view.getUint8(offset+6, true); + var unknown2 = view.getUint8(offset+7, true); + return { + texOffset: texOffset, + pal0trans: (flags>>13)&1, //two top flags are texture matrix modes. not sure if it really matters (except for nsbta animation maybe, but 0 = no transform and things that have tex animations are set to 0 anyways). + format: ((flags>>10)&7), + height: 8 << ((flags>>7)&7), + width: 8 << ((flags>>4)&7), + repeatX: flags&1, + repeatY: (flags>>1)&1, + flipX: (flags>>2)&1, + flipY: (flags>>3)&1, + + unkWidth: width2, + unk1: unknown, + unkHeight: height2, + unk2: unknown2, + + nextoff: offset+8 + } + } + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } +} \ No newline at end of file diff --git a/Code/Formats/sbnk.js b/Code/Formats/sbnk.js new file mode 100644 index 0000000..70737a2 --- /dev/null +++ b/Code/Formats/sbnk.js @@ -0,0 +1,102 @@ +// +// sbnk.js +//-------------------- +// Reads sbnk files. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// + +window.sbnk = function(input, dataView) { + var t = this; + this.load = load; + + function load(input, dataView) { + var view = (dataView)?input:(new DataView(input)); + var header = null; + var offset = 0; + + var stamp = readChar(view, 0x0)+readChar(view, 0x1)+readChar(view, 0x2)+readChar(view, 0x3); + if (stamp != "SBNK") throw "SWAV invalid. Expected SWAV, found "+stamp; + offset += 16; + var data = readChar(view, offset)+readChar(view, offset+1)+readChar(view, offset+2)+readChar(view, offset+3); + if (data != "DATA") throw "SWAV invalid, expected DATA, found "+data; + offset += 8; + + offset += 32; //skip reserved + + var numInst = view.getUint32(offset, true); + t.instruments = []; + offset += 4; + for (var i=0; i-1; i--) { //reverse order so we can process files into js objects + var off = (view.getUint32(0x10+i*8, true)); + var size = (view.getUint32(0x14+i*8, true)); + if (size != 0) readSection(view, off); + } + + } + + function readSection(view, off) { + var stamp = "$"+readChar(view, off)+readChar(view, off+1)+readChar(view, off+2)+readChar(view, off+3); + if (sectionFunc[stamp] != null) t.sections[stamp] = sectionFunc[stamp](view, off+8); + else console.error("Invalid section in SDAT! No handler for section type "+stamp.substr(1, 4)); + } + + var sectionFunc = {} + + sectionFunc["$SYMB"] = function(view, off) { + + } + + sectionFunc["$INFO"] = function(view, off) { + var obj = []; + for (var i=0; i<8; i++) { + var relOff = off+view.getUint32(off+i*4, true)-8; + + var count = view.getUint32(relOff, true); + obj[i] = []; + relOff += 4; + var last = null; + for (var j=0; j 96000) return ctx.createBuffer(1, 1, 44000); //give up and return an empty buffer + } + } + + var indChanges = [-1, -1, -1, -1, 2, 4, 6, 8]; + var ADPCMTable = [ + 0x0007,0x0008,0x0009,0x000A,0x000B,0x000C,0x000D,0x000E,0x0010,0x0011,0x0013,0x0015, + 0x0017,0x0019,0x001C,0x001F,0x0022,0x0025,0x0029,0x002D,0x0032,0x0037,0x003C,0x0042, + 0x0049,0x0050,0x0058,0x0061,0x006B,0x0076,0x0082,0x008F,0x009D,0x00AD,0x00BE,0x00D1, + 0x00E6,0x00FD,0x0117,0x0133,0x0151,0x0173,0x0198,0x01C1,0x01EE,0x0220,0x0256,0x0292, + 0x02D4,0x031C,0x036C,0x03C3,0x0424,0x048E,0x0502,0x0583,0x0610,0x06AB,0x0756,0x0812, + 0x08E0,0x09C3,0x0ABD,0x0BD0,0x0CFF,0x0E4C,0x0FBA,0x114C,0x1307,0x14EE,0x1706,0x1954, + 0x1BDC,0x1EA5,0x21B6,0x2515,0x28CA,0x2CDF,0x315B,0x364B,0x3BB9,0x41B2,0x4844,0x4F7E, + 0x5771,0x602F,0x69CE,0x7462,0x7FFF + ]; //thanks no$gba docs + + function decodeADPCM(view, off) { + var pcm = view.getUint16(off, true); //initial pcm + var ind = view.getUint8(off+2); //initial index + off += 4; + + var size = t.bytesize-4; + var out = new Float32Array((size*2)); + var write = 0; + //out[write++] = pcm/0x7FFF; + + for (var i=0; i>(j*4))&15; + + var diff = Math.floor(((nibble&7)*2+1)*ADPCMTable[ind]/8); + if (nibble&8) pcm = Math.max(pcm-diff, -0x7FFF); + else pcm = Math.min(pcm+diff, 0x7FFF); + out[write++] = pcm/0x7FFF; + + ind = Math.min(88, Math.max(0, ind + indChanges[nibble&7])); + } + } + return out; + } + + + function readChar(view, offset) { + return String.fromCharCode(view.getUint8(offset)); + } + + if (input != null) { + load(input, hasHead, dataView); + } +} \ No newline at end of file diff --git a/Code/IndexedDBShim.min.js b/Code/IndexedDBShim.min.js new file mode 100644 index 0000000..29a317e --- /dev/null +++ b/Code/IndexedDBShim.min.js @@ -0,0 +1,3 @@ +/*! IndexedDBShim - v0.1.2 - 2014-06-14 */ +"use strict";var idbModules={},cleanInterface=!1;(function(){var e={test:!0};if(Object.defineProperty)try{Object.defineProperty(e,"test",{enumerable:!1}),e.test&&(cleanInterface=!0)}catch(t){}})(),function(e){function t(e,t,n,o){n.target=t,"function"==typeof t[e]&&t[e].apply(t,[n]),"function"==typeof o&&o()}function n(t,n,o){var r=new DOMException.prototype.constructor(0,n);throw r.name=t,r.message=n,e.DEBUG&&(console.log(t,n,o,r),console.trace&&console.trace()),r}var o=function(){this.length=0,this._items=[],cleanInterface&&Object.defineProperty(this,"_items",{enumerable:!1})};if(o.prototype={contains:function(e){return-1!==this._items.indexOf(e)},item:function(e){return this._items[e]},indexOf:function(e){return this._items.indexOf(e)},push:function(e){this._items.push(e),this.length+=1;for(var t=0;this._items.length>t;t++)this[t]=this._items[t]},splice:function(){this._items.splice.apply(this._items,arguments),this.length=this._items.length;for(var e in this)e===parseInt(e,10)+""&&delete this[e];for(e=0;this._items.length>e;e++)this[e]=this._items[e]}},cleanInterface)for(var r in{indexOf:!1,push:!1,splice:!1})Object.defineProperty(o.prototype,r,{enumerable:!1});e.util={throwDOMException:n,callback:t,quote:function(e){return"'"+e+"'"},StringList:o}}(idbModules),function(idbModules){var Sca=function(){return{decycle:function(object,callback){function checkForCompletion(){0===queuedObjects.length&&returnCallback(derezObj)}function readBlobAsDataURL(e,t){var n=new FileReader;n.onloadend=function(e){var n=e.target.result,o="blob";updateEncodedBlob(n,t,o)},n.readAsDataURL(e)}function updateEncodedBlob(dataURL,path,blobtype){var encoded=queuedObjects.indexOf(path);path=path.replace("$","derezObj"),eval(path+'.$enc="'+dataURL+'"'),eval(path+'.$type="'+blobtype+'"'),queuedObjects.splice(encoded,1),checkForCompletion()}function derez(e,t){var n,o,r;if(!("object"!=typeof e||null===e||e instanceof Boolean||e instanceof Date||e instanceof Number||e instanceof RegExp||e instanceof Blob||e instanceof String)){for(n=0;objects.length>n;n+=1)if(objects[n]===e)return{$ref:paths[n]};if(objects.push(e),paths.push(t),"[object Array]"===Object.prototype.toString.apply(e))for(r=[],n=0;e.length>n;n+=1)r[n]=derez(e[n],t+"["+n+"]");else{r={};for(o in e)Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=derez(e[o],t+"["+JSON.stringify(o)+"]"))}return r}return e instanceof Blob?(queuedObjects.push(t),readBlobAsDataURL(e,t)):e instanceof Boolean?e={$type:"bool",$enc:""+e}:e instanceof Date?e={$type:"date",$enc:e.getTime()}:e instanceof Number?e={$type:"num",$enc:""+e}:e instanceof RegExp&&(e={$type:"regex",$enc:""+e}),e}var objects=[],paths=[],queuedObjects=[],returnCallback=callback,derezObj=derez(object,"$");checkForCompletion()},retrocycle:function retrocycle($){function dataURLToBlob(e){var t,n,o,r=";base64,";if(-1===e.indexOf(r))return n=e.split(","),t=n[0].split(":")[1],o=n[1],new Blob([o],{type:t});n=e.split(r),t=n[0].split(":")[1],o=window.atob(n[1]);for(var i=o.length,a=new Uint8Array(i),s=0;i>s;++s)a[s]=o.charCodeAt(s);return new Blob([a.buffer],{type:t})}function rez(value){var i,item,name,path;if(value&&"object"==typeof value)if("[object Array]"===Object.prototype.toString.apply(value))for(i=0;value.length>i;i+=1)item=value[i],item&&"object"==typeof item&&(path=item.$ref,value[i]="string"==typeof path&&px.test(path)?eval(path):rez(item));else if(void 0!==value.$type)switch(value.$type){case"blob":case"file":value=dataURLToBlob(value.$enc);break;case"bool":value=Boolean("true"===value.$enc);break;case"date":value=new Date(value.$enc);break;case"num":value=Number(value.$enc);break;case"regex":value=eval(value.$enc)}else for(name in value)"object"==typeof value[name]&&(item=value[name],item&&(path=item.$ref,value[name]="string"==typeof path&&px.test(path)?eval(path):rez(item)));return value}var px=/^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/;return rez($),$},encode:function(e,t){function n(e){t(JSON.stringify(e))}this.decycle(e,n)},decode:function(e){return this.retrocycle(JSON.parse(e))}}}();idbModules.Sca=Sca}(idbModules),function(e){var t=["","number","string","boolean","object","undefined"],n=function(){return{encode:function(e){return t.indexOf(typeof e)+"-"+JSON.stringify(e)},decode:function(e){return e===void 0?void 0:JSON.parse(e.substring(2))}}},o={number:n("number"),"boolean":n(),object:n(),string:{encode:function(e){return t.indexOf("string")+"-"+e},decode:function(e){return""+e.substring(2)}},undefined:{encode:function(){return t.indexOf("undefined")+"-undefined"},decode:function(){return void 0}}},r=function(){return{encode:function(e){return o[typeof e].encode(e)},decode:function(e){return o[t[e.substring(0,1)]].decode(e)}}}();e.Key=r}(idbModules),function(e){var t=function(e,t){return{type:e,debug:t,bubbles:!1,cancelable:!1,eventPhase:0,timeStamp:new Date}};e.Event=t}(idbModules),function(e){var t=function(){this.onsuccess=this.onerror=this.result=this.error=this.source=this.transaction=null,this.readyState="pending"},n=function(){this.onblocked=this.onupgradeneeded=null};n.prototype=t,e.IDBRequest=t,e.IDBOpenRequest=n}(idbModules),function(e,t){var n=function(e,t,n,o){this.lower=e,this.upper=t,this.lowerOpen=n,this.upperOpen=o};n.only=function(e){return new n(e,e,!1,!1)},n.lowerBound=function(e,o){return new n(e,t,o,t)},n.upperBound=function(e){return new n(t,e,t,open)},n.bound=function(e,t,o,r){return new n(e,t,o,r)},e.IDBKeyRange=n}(idbModules),function(e,t){function n(n,o,r,i,a,s){this.__range=n,this.source=this.__idbObjectStore=r,this.__req=i,this.key=t,this.direction=o,this.__keyColumnName=a,this.__valueColumnName=s,this.__valueDecoder="value"===s?e.Sca:e.Key,this.source.transaction.__active||e.util.throwDOMException("TransactionInactiveError - The transaction this IDBObjectStore belongs to is not active."),this.__offset=-1,this.__lastKeyContinued=t,this["continue"]()}n.prototype.__find=function(n,o,r,i,a){a=a||1;var s=this,c=["SELECT * FROM ",e.util.quote(s.__idbObjectStore.name)],u=[];c.push("WHERE ",s.__keyColumnName," NOT NULL"),s.__range&&(s.__range.lower||s.__range.upper)&&(c.push("AND"),s.__range.lower&&(c.push(s.__keyColumnName+(s.__range.lowerOpen?" >":" >= ")+" ?"),u.push(e.Key.encode(s.__range.lower))),s.__range.lower&&s.__range.upper&&c.push("AND"),s.__range.upper&&(c.push(s.__keyColumnName+(s.__range.upperOpen?" < ":" <= ")+" ?"),u.push(e.Key.encode(s.__range.upper)))),n!==t&&(s.__lastKeyContinued=n,s.__offset=0),s.__lastKeyContinued!==t&&(c.push("AND "+s.__keyColumnName+" >= ?"),u.push(e.Key.encode(s.__lastKeyContinued))),c.push("ORDER BY ",s.__keyColumnName),c.push("LIMIT "+a+" OFFSET "+s.__offset),e.DEBUG&&console.log(c.join(" "),u),s.__prefetchedData=null,o.executeSql(c.join(" "),u,function(n,o){o.rows.length>1?(s.__prefetchedData=o.rows,s.__prefetchedIndex=0,e.DEBUG&&console.log("Preloaded "+s.__prefetchedData.length+" records for cursor"),s.__decode(o.rows.item(0),r)):1===o.rows.length?s.__decode(o.rows.item(0),r):(e.DEBUG&&console.log("Reached end of cursors"),r(t,t))},function(t,n){e.DEBUG&&console.log("Could not execute Cursor.continue"),i(n)})},n.prototype.__decode=function(t,n){var o=e.Key.decode(t[this.__keyColumnName]),r=this.__valueDecoder.decode(t[this.__valueColumnName]),i=e.Key.decode(t.key);n(o,r,i)},n.prototype["continue"]=function(n){var o=e.cursorPreloadPackSize||100,r=this;this.__idbObjectStore.transaction.__addToTransactionQueue(function(e,i,a,s){r.__offset++;var c=function(e,n,o){r.key=e,r.value=n,r.primaryKey=o,a(r.key!==t?r:t,r.__req)};return r.__prefetchedData&&(r.__prefetchedIndex++,r.__prefetchedIndex=n&&e.util.throwDOMException("Type Error - Count is invalid - 0 or negative",n);var o=this;this.__idbObjectStore.transaction.__addToTransactionQueue(function(e,r,i,a){o.__offset+=n,o.__find(t,e,function(e,n){o.key=e,o.value=n,i(o.key!==t?o:t,o.__req)},a)})},n.prototype.update=function(n){var o=this,r=this.__idbObjectStore.transaction.__createRequest(function(){});return e.Sca.encode(n,function(n){o.__idbObjectStore.transaction.__pushToQueue(r,function(r,i,a,s){o.__find(t,r,function(t,i,c){var u="UPDATE "+e.util.quote(o.__idbObjectStore.name)+" SET value = ? WHERE key = ?";e.DEBUG&&console.log(u,n,t,c),r.executeSql(u,[n,e.Key.encode(c)],function(e,n){1===n.rowsAffected?a(t):s("No rows with key found"+t)},function(e,t){s(t)})},s)})}),r},n.prototype["delete"]=function(){var n=this;return this.__idbObjectStore.transaction.__addToTransactionQueue(function(o,r,i,a){n.__find(t,o,function(r,s,c){var u="DELETE FROM "+e.util.quote(n.__idbObjectStore.name)+" WHERE key = ?";e.DEBUG&&console.log(u,r,c),o.executeSql(u,[e.Key.encode(c)],function(e,o){1===o.rowsAffected?(n.__offset--,i(t)):a("No rows with key found"+r)},function(e,t){a(t)})},a)})},e.IDBCursor=n}(idbModules),function(idbModules,undefined){function IDBIndex(e,t){this.indexName=this.name=e,this.__idbObjectStore=this.objectStore=this.source=t;var n=t.__storeProps&&t.__storeProps.indexList;n&&(n=JSON.parse(n)),this.keyPath=n&&n[e]&&n[e].keyPath||e,["multiEntry","unique"].forEach(function(t){this[t]=!!(n&&n[e]&&n[e].optionalParams&&n[e].optionalParams[t])},this)}IDBIndex.prototype.__createIndex=function(indexName,keyPath,optionalParameters){var me=this,transaction=me.__idbObjectStore.transaction;transaction.__addToTransactionQueue(function(tx,args,success,failure){me.__idbObjectStore.__getStoreProps(tx,function(){function error(){idbModules.util.throwDOMException(0,"Could not create new index",arguments)}2!==transaction.mode&&idbModules.util.throwDOMException(0,"Invalid State error, not a version transaction",me.transaction);var idxList=JSON.parse(me.__idbObjectStore.__storeProps.indexList);idxList[indexName]!==undefined&&idbModules.util.throwDOMException(0,"Index already exists on store",idxList);var columnName=indexName;idxList[indexName]={columnName:columnName,keyPath:keyPath,optionalParams:optionalParameters},me.__idbObjectStore.__storeProps.indexList=JSON.stringify(idxList);var sql=["ALTER TABLE",idbModules.util.quote(me.__idbObjectStore.name),"ADD",columnName,"BLOB"].join(" ");idbModules.DEBUG&&console.log(sql),tx.executeSql(sql,[],function(tx,data){tx.executeSql("SELECT * FROM "+idbModules.util.quote(me.__idbObjectStore.name),[],function(tx,data){(function initIndexForRow(i){if(data.rows.length>i)try{var value=idbModules.Sca.decode(data.rows.item(i).value),indexKey=eval("value['"+keyPath+"']");tx.executeSql("UPDATE "+idbModules.util.quote(me.__idbObjectStore.name)+" set "+columnName+" = ? where key = ?",[idbModules.Key.encode(indexKey),data.rows.item(i).key],function(){initIndexForRow(i+1)},error)}catch(e){initIndexForRow(i+1)}else idbModules.DEBUG&&console.log("Updating the indexes in table",me.__idbObjectStore.__storeProps),tx.executeSql("UPDATE __sys__ set indexList = ? where name = ?",[me.__idbObjectStore.__storeProps.indexList,me.__idbObjectStore.name],function(){me.__idbObjectStore.__setReadyState("createIndex",!0),success(me)},error)})(0)},error)},error)},"createObjectStore")})},IDBIndex.prototype.openCursor=function(e,t){var n=new idbModules.IDBRequest;return new idbModules.IDBCursor(e,t,this.source,n,this.indexName,"value"),n},IDBIndex.prototype.openKeyCursor=function(e,t){var n=new idbModules.IDBRequest;return new idbModules.IDBCursor(e,t,this.source,n,this.indexName,"key"),n},IDBIndex.prototype.__fetchIndexData=function(e,t){var n=this;return n.__idbObjectStore.transaction.__addToTransactionQueue(function(o,r,i,a){var s=["SELECT * FROM ",idbModules.util.quote(n.__idbObjectStore.name)," WHERE",n.indexName,"NOT NULL"],c=[];e!==undefined&&(s.push("AND",n.indexName," = ?"),c.push(idbModules.Key.encode(e))),idbModules.DEBUG&&console.log("Trying to fetch data for Index",s.join(" "),c),o.executeSql(s.join(" "),c,function(e,n){var o;o="count"===t?n.rows.length:0===n.rows.length?undefined:"key"===t?idbModules.Key.decode(n.rows.item(0).key):idbModules.Sca.decode(n.rows.item(0).value),i(o)},a)})},IDBIndex.prototype.get=function(e){return this.__fetchIndexData(e,"value")},IDBIndex.prototype.getKey=function(e){return this.__fetchIndexData(e,"key")},IDBIndex.prototype.count=function(e){return this.__fetchIndexData(e,"count")},idbModules.IDBIndex=IDBIndex}(idbModules),function(idbModules){var IDBObjectStore=function(e,t,n){this.name=e,this.transaction=t,this.__ready={},this.__setReadyState("createObjectStore",n===void 0?!0:n),this.indexNames=new idbModules.util.StringList};IDBObjectStore.prototype.__setReadyState=function(e,t){this.__ready[e]=t},IDBObjectStore.prototype.__waitForReady=function(e,t){var n=!0;if(t!==void 0)n=this.__ready[t]===void 0?!0:this.__ready[t];else for(var o in this.__ready)this.__ready[o]||(n=!1);if(n)e();else{idbModules.DEBUG&&console.log("Waiting for to be ready",t);var r=this;window.setTimeout(function(){r.__waitForReady(e,t)},100)}},IDBObjectStore.prototype.__getStoreProps=function(e,t,n){var o=this;this.__waitForReady(function(){o.__storeProps?(idbModules.DEBUG&&console.log("Store properties - cached",o.__storeProps),t(o.__storeProps)):e.executeSql("SELECT * FROM __sys__ where name = ?",[o.name],function(e,n){1!==n.rows.length?t():(o.__storeProps={name:n.rows.item(0).name,indexList:n.rows.item(0).indexList,autoInc:n.rows.item(0).autoInc,keyPath:n.rows.item(0).keyPath},idbModules.DEBUG&&console.log("Store properties",o.__storeProps),t(o.__storeProps))},function(){t()})},n)},IDBObjectStore.prototype.__deriveKey=function(tx,value,key,callback){function getNextAutoIncKey(){tx.executeSql("SELECT * FROM sqlite_sequence where name like ?",[me.name],function(e,t){1!==t.rows.length?callback(0):callback(t.rows.item(0).seq)},function(e,t){idbModules.util.throwDOMException(0,"Data Error - Could not get the auto increment value for key",t)})}var me=this;me.__getStoreProps(tx,function(props){if(props||idbModules.util.throwDOMException(0,"Data Error - Could not locate defination for this table",props),props.keyPath)if(key!==void 0&&idbModules.util.throwDOMException(0,"Data Error - The object store uses in-line keys and the key parameter was provided",props),value)try{var primaryKey=eval("value['"+props.keyPath+"']");primaryKey?callback(primaryKey):"true"===props.autoInc?getNextAutoIncKey():idbModules.util.throwDOMException(0,"Data Error - Could not eval key from keyPath")}catch(e){idbModules.util.throwDOMException(0,"Data Error - Could not eval key from keyPath",e)}else idbModules.util.throwDOMException(0,"Data Error - KeyPath was specified, but value was not");else key!==void 0?callback(key):"false"===props.autoInc?idbModules.util.throwDOMException(0,"Data Error - The object store uses out-of-line keys and has no key generator and the key parameter was not provided. ",props):getNextAutoIncKey()})},IDBObjectStore.prototype.__insertData=function(tx,encoded,value,primaryKey,success,error){var paramMap={};primaryKey!==void 0&&(paramMap.key=idbModules.Key.encode(primaryKey));var indexes=JSON.parse(this.__storeProps.indexList);for(var key in indexes)try{paramMap[indexes[key].columnName]=idbModules.Key.encode(eval("value['"+indexes[key].keyPath+"']"))}catch(e){error(e)}var sqlStart=["INSERT INTO ",idbModules.util.quote(this.name),"("],sqlEnd=[" VALUES ("],sqlValues=[];for(key in paramMap)sqlStart.push(key+","),sqlEnd.push("?,"),sqlValues.push(paramMap[key]);sqlStart.push("value )"),sqlEnd.push("?)"),sqlValues.push(encoded);var sql=sqlStart.join(" ")+sqlEnd.join(" ");idbModules.DEBUG&&console.log("SQL for adding",sql,sqlValues),tx.executeSql(sql,sqlValues,function(){success(primaryKey)},function(e,t){error(t)})},IDBObjectStore.prototype.add=function(e,t){var n=this,o=n.transaction.__createRequest(function(){});return idbModules.Sca.encode(e,function(r){n.transaction.__pushToQueue(o,function(o,i,a,s){n.__deriveKey(o,e,t,function(t){n.__insertData(o,r,e,t,a,s)})})}),o},IDBObjectStore.prototype.put=function(e,t){var n=this,o=n.transaction.__createRequest(function(){});return idbModules.Sca.encode(e,function(r){n.transaction.__pushToQueue(o,function(o,i,a,s){n.__deriveKey(o,e,t,function(t){var i="DELETE FROM "+idbModules.util.quote(n.name)+" where key = ?";o.executeSql(i,[idbModules.Key.encode(t)],function(o,i){idbModules.DEBUG&&console.log("Did the row with the",t,"exist? ",i.rowsAffected),n.__insertData(o,r,e,t,a,s)},function(e,t){s(t)})})})}),o},IDBObjectStore.prototype.get=function(e){var t=this;return t.transaction.__addToTransactionQueue(function(n,o,r,i){t.__waitForReady(function(){var o=idbModules.Key.encode(e);idbModules.DEBUG&&console.log("Fetching",t.name,o),n.executeSql("SELECT * FROM "+idbModules.util.quote(t.name)+" where key = ?",[o],function(e,t){idbModules.DEBUG&&console.log("Fetched data",t);try{if(0===t.rows.length)return r();r(idbModules.Sca.decode(t.rows.item(0).value))}catch(n){idbModules.DEBUG&&console.log(n),r(void 0)}},function(e,t){i(t)})})})},IDBObjectStore.prototype["delete"]=function(e){var t=this;return t.transaction.__addToTransactionQueue(function(n,o,r,i){t.__waitForReady(function(){var o=idbModules.Key.encode(e);idbModules.DEBUG&&console.log("Fetching",t.name,o),n.executeSql("DELETE FROM "+idbModules.util.quote(t.name)+" where key = ?",[o],function(e,t){idbModules.DEBUG&&console.log("Deleted from database",t.rowsAffected),r()},function(e,t){i(t)})})})},IDBObjectStore.prototype.clear=function(){var e=this;return e.transaction.__addToTransactionQueue(function(t,n,o,r){e.__waitForReady(function(){t.executeSql("DELETE FROM "+idbModules.util.quote(e.name),[],function(e,t){idbModules.DEBUG&&console.log("Cleared all records from database",t.rowsAffected),o()},function(e,t){r(t)})})})},IDBObjectStore.prototype.count=function(e){var t=this;return t.transaction.__addToTransactionQueue(function(n,o,r,i){t.__waitForReady(function(){var o="SELECT * FROM "+idbModules.util.quote(t.name)+(e!==void 0?" WHERE key = ?":""),a=[];e!==void 0&&a.push(idbModules.Key.encode(e)),n.executeSql(o,a,function(e,t){r(t.rows.length)},function(e,t){i(t)})})})},IDBObjectStore.prototype.openCursor=function(e,t){var n=new idbModules.IDBRequest;return new idbModules.IDBCursor(e,t,this,n,"key","value"),n},IDBObjectStore.prototype.index=function(e){var t=new idbModules.IDBIndex(e,this);return t},IDBObjectStore.prototype.createIndex=function(e,t,n){var o=this;n=n||{},o.__setReadyState("createIndex",!1);var r=new idbModules.IDBIndex(e,o);return o.__waitForReady(function(){r.__createIndex(e,t,n)},"createObjectStore"),o.indexNames.push(e),r},IDBObjectStore.prototype.deleteIndex=function(e){var t=new idbModules.IDBIndex(e,this,!1);return t.__deleteIndex(e),t},idbModules.IDBObjectStore=IDBObjectStore}(idbModules),function(e){var t=0,n=1,o=2,r=function(o,r,i){if("number"==typeof r)this.mode=r,2!==r&&e.DEBUG&&console.log("Mode should be a string, but was specified as ",r);else if("string"==typeof r)switch(r){case"readwrite":this.mode=n;break;case"readonly":this.mode=t;break;default:this.mode=t}this.storeNames="string"==typeof o?[o]:o;for(var a=0;this.storeNames.length>a;a++)i.objectStoreNames.contains(this.storeNames[a])||e.util.throwDOMException(0,"The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.",this.storeNames[a]);this.__active=!0,this.__running=!1,this.__requests=[],this.__aborted=!1,this.db=i,this.error=null,this.onabort=this.onerror=this.oncomplete=null};r.prototype.__executeRequests=function(){if(this.__running&&this.mode!==o)return e.DEBUG&&console.log("Looks like the request set is already running",this.mode),void 0;this.__running=!0;var t=this;window.setTimeout(function(){2===t.mode||t.__active||e.util.throwDOMException(0,"A request was placed against a transaction which is currently not active, or which is finished",t.__active),t.db.__db.transaction(function(n){function o(t,n){n&&(a.req=n),a.req.readyState="done",a.req.result=t,delete a.req.error;var o=e.Event("success");e.util.callback("onsuccess",a.req,o),s++,i()}function r(){a.req.readyState="done",a.req.error="DOMError";var t=e.Event("error",arguments);e.util.callback("onerror",a.req,t),s++,i()}function i(){return s>=t.__requests.length?(t.__active=!1,t.__requests=[],void 0):(a=t.__requests[s],a.op(n,a.args,o,r),void 0)}t.__tx=n;var a=null,s=0;try{i()}catch(c){e.DEBUG&&console.log("An exception occured in transaction",arguments),"function"==typeof t.onerror&&t.onerror()}},function(){e.DEBUG&&console.log("An error in transaction",arguments),"function"==typeof t.onerror&&t.onerror()},function(){e.DEBUG&&console.log("Transaction completed",arguments),"function"==typeof t.oncomplete&&t.oncomplete()})},1)},r.prototype.__addToTransactionQueue=function(t,n){this.__active||this.mode===o||e.util.throwDOMException(0,"A request was placed against a transaction which is currently not active, or which is finished.",this.__mode);var r=this.__createRequest();return this.__pushToQueue(r,t,n),r},r.prototype.__createRequest=function(){var t=new e.IDBRequest;return t.source=this.db,t.transaction=this,t},r.prototype.__pushToQueue=function(e,t,n){this.__requests.push({op:t,args:n,req:e}),this.__executeRequests()},r.prototype.objectStore=function(t){return new e.IDBObjectStore(t,this)},r.prototype.abort=function(){!this.__active&&e.util.throwDOMException(0,"A request was placed against a transaction which is currently not active, or which is finished",this.__active)},r.prototype.READ_ONLY=0,r.prototype.READ_WRITE=1,r.prototype.VERSION_CHANGE=2,e.IDBTransaction=r}(idbModules),function(e){var t=function(t,n,o,r){this.__db=t,this.version=o,this.__storeProperties=r,this.objectStoreNames=new e.util.StringList;for(var i=0;r.rows.length>i;i++)this.objectStoreNames.push(r.rows.item(i).name);this.name=n,this.onabort=this.onerror=this.onversionchange=null};t.prototype.createObjectStore=function(t,n){var o=this;n=n||{},n.keyPath=n.keyPath||null;var r=new e.IDBObjectStore(t,o.__versionTransaction,!1),i=o.__versionTransaction;return i.__addToTransactionQueue(function(i,a,s){function c(){e.util.throwDOMException(0,"Could not create new object store",arguments)}o.__versionTransaction||e.util.throwDOMException(0,"Invalid State error",o.transaction);var u=["CREATE TABLE",e.util.quote(t),"(key BLOB",n.autoIncrement?", inc INTEGER PRIMARY KEY AUTOINCREMENT":"PRIMARY KEY",", value BLOB)"].join(" ");e.DEBUG&&console.log(u),i.executeSql(u,[],function(e){e.executeSql("INSERT INTO __sys__ VALUES (?,?,?,?)",[t,n.keyPath,n.autoIncrement?!0:!1,"{}"],function(){r.__setReadyState("createObjectStore",!0),s(r)},c)},c)}),o.objectStoreNames.push(t),r},t.prototype.deleteObjectStore=function(t){var n=function(){e.util.throwDOMException(0,"Could not delete ObjectStore",arguments)},o=this;!o.objectStoreNames.contains(t)&&n("Object Store does not exist"),o.objectStoreNames.splice(o.objectStoreNames.indexOf(t),1);var r=o.__versionTransaction;r.__addToTransactionQueue(function(){o.__versionTransaction||e.util.throwDOMException(0,"Invalid State error",o.transaction),o.__db.transaction(function(o){o.executeSql("SELECT * FROM __sys__ where name = ?",[t],function(o,r){r.rows.length>0&&o.executeSql("DROP TABLE "+e.util.quote(t),[],function(){o.executeSql("DELETE FROM __sys__ WHERE name = ?",[t],function(){},n)},n)})})})},t.prototype.close=function(){},t.prototype.transaction=function(t,n){var o=new e.IDBTransaction(t,n||1,this);return o},e.IDBDatabase=t}(idbModules),function(e){var t=4194304;if(window.openDatabase){var n=window.openDatabase("__sysdb__",1,"System Database",t);n.transaction(function(t){t.executeSql("SELECT * FROM dbVersions",[],function(){},function(){n.transaction(function(t){t.executeSql("CREATE TABLE IF NOT EXISTS dbVersions (name VARCHAR(255), version INT);",[],function(){},function(){e.util.throwDOMException("Could not create table __sysdb__ to save DB versions")})})})},function(){e.DEBUG&&console.log("Error in sysdb transaction - when selecting from dbVersions",arguments)});var o={open:function(o,r){function i(){if(!c){var t=e.Event("error",arguments);s.readyState="done",s.error="DOMError",e.util.callback("onerror",s,t),c=!0}}function a(a){var c=window.openDatabase(o,1,o,t);s.readyState="done",r===void 0&&(r=a||1),(0>=r||a>r)&&e.util.throwDOMException(0,"An attempt was made to open a database using a lower version than the existing version.",r),c.transaction(function(t){t.executeSql("CREATE TABLE IF NOT EXISTS __sys__ (name VARCHAR(255), keyPath VARCHAR(255), autoInc BOOLEAN, indexList BLOB)",[],function(){t.executeSql("SELECT * FROM __sys__",[],function(t,u){var d=e.Event("success");s.source=s.result=new e.IDBDatabase(c,o,r,u),r>a?n.transaction(function(t){t.executeSql("UPDATE dbVersions set version = ? where name = ?",[r,o],function(){var t=e.Event("upgradeneeded");t.oldVersion=a,t.newVersion=r,s.transaction=s.result.__versionTransaction=new e.IDBTransaction([],2,s.source),e.util.callback("onupgradeneeded",s,t,function(){var t=e.Event("success");e.util.callback("onsuccess",s,t)})},i)},i):e.util.callback("onsuccess",s,d)},i)},i)},i)}var s=new e.IDBOpenRequest,c=!1;return n.transaction(function(e){e.executeSql("SELECT * FROM dbVersions where name = ?",[o],function(e,t){0===t.rows.length?e.executeSql("INSERT INTO dbVersions VALUES (?,?)",[o,r||1],function(){a(0)},i):a(t.rows.item(0).version)},i)},i),s},deleteDatabase:function(o){function r(t){if(!s){a.readyState="done",a.error="DOMError";var n=e.Event("error");n.message=t,n.debug=arguments,e.util.callback("onerror",a,n),s=!0}}function i(){n.transaction(function(t){t.executeSql("DELETE FROM dbVersions where name = ? ",[o],function(){a.result=void 0;var t=e.Event("success");t.newVersion=null,t.oldVersion=c,e.util.callback("onsuccess",a,t)},r)},r)}var a=new e.IDBOpenRequest,s=!1,c=null;return n.transaction(function(n){n.executeSql("SELECT * FROM dbVersions where name = ?",[o],function(n,s){if(0===s.rows.length){a.result=void 0;var u=e.Event("success");return u.newVersion=null,u.oldVersion=c,e.util.callback("onsuccess",a,u),void 0}c=s.rows.item(0).version;var d=window.openDatabase(o,1,o,t);d.transaction(function(t){t.executeSql("SELECT * FROM __sys__",[],function(t,n){var o=n.rows;(function a(n){n>=o.length?t.executeSql("DROP TABLE __sys__",[],function(){i()},r):t.executeSql("DROP TABLE "+e.util.quote(o.item(n).name),[],function(){a(n+1)},function(){a(n+1)})})(0)},function(){i()})},r)})},r),a},cmp:function(t,n){return e.Key.encode(t)>e.Key.encode(n)?1:t===n?0:-1}};e.shimIndexedDB=o}}(idbModules),function(e,t){e.openDatabase!==void 0&&(e.shimIndexedDB=t.shimIndexedDB,e.shimIndexedDB&&(e.shimIndexedDB.__useShim=function(){e.indexedDB=t.shimIndexedDB,e.IDBDatabase=t.IDBDatabase,e.IDBTransaction=t.IDBTransaction,e.IDBCursor=t.IDBCursor,e.IDBKeyRange=t.IDBKeyRange,e.indexedDB!==t.shimIndexedDB&&Object.defineProperty&&Object.defineProperty(e,"indexedDB",{value:t.shimIndexedDB})},e.shimIndexedDB.__debug=function(e){t.DEBUG=e})),"indexedDB"in e||(e.indexedDB=e.indexedDB||e.webkitIndexedDB||e.mozIndexedDB||e.oIndexedDB||e.msIndexedDB);var n=!1;if((navigator.userAgent.match(/Android 2/)||navigator.userAgent.match(/Android 3/)||navigator.userAgent.match(/Android 4\.[0-3]/))&&(navigator.userAgent.match(/Chrome/)||(n=!0)),void 0!==e.indexedDB&&!n||void 0===e.openDatabase){e.IDBDatabase=e.IDBDatabase||e.webkitIDBDatabase,e.IDBTransaction=e.IDBTransaction||e.webkitIDBTransaction,e.IDBCursor=e.IDBCursor||e.webkitIDBCursor,e.IDBKeyRange=e.IDBKeyRange||e.webkitIDBKeyRange,e.IDBTransaction||(e.IDBTransaction={});try{e.IDBTransaction.READ_ONLY=e.IDBTransaction.READ_ONLY||"readonly",e.IDBTransaction.READ_WRITE=e.IDBTransaction.READ_WRITE||"readwrite"}catch(o){}}else e.shimIndexedDB.__useShim()}(window,idbModules); +//@ sourceMappingURL=http://nparashuram.com/IndexedDBShim/dist/IndexedDBShim.min.map \ No newline at end of file diff --git a/Code/Particles/itemboxShard.js b/Code/Particles/itemboxShard.js new file mode 100644 index 0000000..e3e4af9 --- /dev/null +++ b/Code/Particles/itemboxShard.js @@ -0,0 +1,39 @@ +// +// itemboxShard.js +//-------------------- +// by RHY3756547 +// + +window.ItemShard = function(scene, targ, model) { + var t = this; + t.update = update; + t.draw = draw; + + t.time = 0; + t.pos = vec3.clone(targ.pos); + t.vel = vec3.add([], targ.vel, [(Math.random()-0.5)*5, Math.random()*7, (Math.random()-0.5)*5]); + t.dirVel = [(Math.random()-0.5), (Math.random()-0.5), (Math.random()-0.5)]; + t.dir = [Math.random()*2*Math.PI, Math.random()*2*Math.PI, Math.random()*2*Math.PI]; + t.scale = Math.random()+0.5; + t.scale = [t.scale, t.scale, t.scale]; + + function update(scene) { + vec3.add(t.pos, t.pos, t.vel); + vec3.add(t.vel, t.vel, [0, -0.17, 0]); + vec3.add(t.dir, t.dir, t.dirVel); + + if (t.time++ > 30) scene.removeParticle(t); + } + + function draw(view, pMatrix, gl) { + var mat = mat4.translate(mat4.create(), view, t.pos); + + mat4.rotateZ(mat, mat, t.dir[2]); + mat4.rotateY(mat, mat, t.dir[1]); + mat4.rotateX(mat, mat, t.dir[0]); + + mat4.scale(mat, mat, vec3.scale([], t.scale, 16)); + model.draw(mat, pMatrix); + } + +} \ No newline at end of file diff --git a/Code/Render/nitroAnimator.js b/Code/Render/nitroAnimator.js new file mode 100644 index 0000000..63c743a --- /dev/null +++ b/Code/Render/nitroAnimator.js @@ -0,0 +1,244 @@ +// +// nitroAnimator.js +//-------------------- +// Runs nsbca animations and provides matrix stacks that can be used with nitroRender to draw them. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/* +// + +window.nitroAnimator = function(bmd, bca) { + var t = this; + t.bmd = bmd; + t.bca = bca; + var bmd = bmd; + var bca = bca; + t.setFrame = setFrame; + t.setAnim = setAnim; + t.getLength = getLength; + + var matBufEmpty = new Float32Array(31*16); + var workingMat = mat4.create(); + + var temp = mat4.create(); + var off=0; + var objMats = []; + for (var i=0; i<31; i++) { + matBufEmpty.set(temp, off); + objMats.push(mat4.create()); + off += 16; + } + + var matBuf = new Float32Array(31*16); + var matStack = {built: true, dat: matBuf}; + + function setAnim(b) { + bca = b; + t.bca = b; + } + + function getLength(anim) { + return bca.animData.objectData[anim].frames; + } + + function setFrame(anim, modelind, frame) { + + var b = bca.animData.objectData[anim]; + + var fLow = Math.floor(frame); + var fHigh = Math.ceil(frame); + var iterp = frame%1; + + var model = bmd.modelData.objectData[modelind]; + var fallback = model.objects.objectData; + + for (var i=0; i>4)&15; + var A = rot.a; + var B = rot.b; + + pivot[mode] = (neg&1)?-1:1; + var horiz = mode%3; + var vert = Math.floor(mode/3) + var left = (horiz==0)?1:0; var top = ((vert==0)?1:0)*3; + var right = (horiz==2)?1:2; var btm = ((vert==2)?1:2)*3; + pivot[left+top] = A; + pivot[right+top] = B; + pivot[left+btm] = (neg&2)?-B:B; + pivot[right+btm] = (neg&4)?-A:A; + return pivot; + } else { + return rot.mat; + } + } + + function lerpMat3(m1, m2, p) { //this is probably a dumb idea, but it's not the worst thing i've come up with... + var q = 1-p; + + return [ + m1[0]*q+m2[0]*p, m1[1]*q+m2[1]*p, m1[2]*q+m2[2]*p, + m1[3]*q+m2[3]*p, m1[4]*q+m2[4]*p, m1[5]*q+m2[5]*p, + m1[6]*q+m2[6]*p, m1[7]*q+m2[7]*p, m1[8]*q+m2[8]*p, + ] + } +} \ No newline at end of file diff --git a/Code/Render/nitroRender.js b/Code/Render/nitroRender.js new file mode 100644 index 0000000..16c0c6f --- /dev/null +++ b/Code/Render/nitroRender.js @@ -0,0 +1,741 @@ +// +// nitroRender.js +//-------------------- +// Provides an interface with which NSBMD models can be drawn to a fst canvas. +// by RHY3756547 +// +// includes: gl-matrix.js (glMatrix 2.0) +// /formats/nitro.js --passive requirement from other nitro formats +// /formats/nsbmd.js +// /formats/nsbta.js +// /formats/nsbtx.js +// + +window.nitroRender = new function() { + var gl, frag, vert, nitroShader; + var cVec, color, texCoord, norm; + var vecMode, vecPos, vecNorm, vecTx, vecCol, vecNum, vecMat, curMat; + var texWidth, texHeight, alphaMul = 1; + + this.cullModes = []; + + this.billboardID = 0; //incrememts every time billboards need to be updated. cycles &0xFFFFFF to avoid issues + this.lastMatStack = null; //used to check if we need to send the matStack again. will be used with a versioning system in future. + + this.last = {}; //obj: the last vertex buffers drawn + + var optimiseTriangles = true; //improves draw performance by >10x on most models. + + var modelBuffer; + var shaders = []; + + this.renderDispList = renderDispList; + this.setAlpha = setAlpha; + this.getViewWidth = getViewWidth; + this.getViewHeight = getViewHeight; + + this.flagShadow = false; + + var parameters = { + 0: 0, + 0x10:1, 0x11:0, 0x12:1, 0x13:1, 0x14:1, 0x15:0, 0x16:16, 0x17:12, 0x18:16, 0x19:12, 0x1A:9, 0x1B:3, 0x1C:3, //matrix commands + 0x20:1, 0x21:1, 0x22:1, 0x23:2, 0x24:1, 0x25:1, 0x26:1, 0x27:1, 0x28:1, 0x29:1, 0x2A:1, 0x2B:1, //vertex commands + 0x30:1, 0x31:1, 0x32:1, 0x33:1, 0x34:32, //material param + 0x40:1, 0x41:0, //begin or end vertices + 0x50:1, //swap buffers + 0x60:1, //viewport + 0x70:3, 0x71:2, 0x72:1 //tests + } + + var instructions = {}; + + instructions[0x14] = function(view, off) { //restore to matrix, used constantly for bone transforms + curMat = view.getUint8(off); + } + + instructions[0x20] = function(view, off) { //color + var dat = view.getUint16(off,true); + color[0] = (dat&31)/31; + color[1] = ((dat>>5)&31)/31; + color[2] = ((dat>>10)&31)/31; + } + + instructions[0x21] = function(view, off) { //normal + var dat = view.getUint32(off, true); + norm[0] = tenBitSign(dat); + norm[1] = tenBitSign(dat>>10); + norm[2] = tenBitSign(dat>>20); + } + + instructions[0x22] = function(view, off) { //texcoord + texCoord[0] = (view.getInt16(off, true)/16)/texWidth; + texCoord[1] = (view.getInt16(off+2, true)/16)/texHeight; + } + + instructions[0x23] = function(view, off) { //xyz 16 bit + cVec[0] = view.getInt16(off, true)/4096; + cVec[1] = view.getInt16(off+2, true)/4096; + cVec[2] = view.getInt16(off+4, true)/4096; + pushVector(); + } + + instructions[0x24] = function(view, off) { //xyz 10 bit + var dat = view.getUint32(off, true); + cVec[0] = tenBitSign(dat); + cVec[1] = tenBitSign(dat>>10); + cVec[2] = tenBitSign(dat>>20); + pushVector(); + } + + instructions[0x25] = function(view, off) { //xy 16 bit + cVec[0] = view.getInt16(off, true)/4096; + cVec[1] = view.getInt16(off+2, true)/4096; + pushVector(); + } + + + instructions[0x26] = function(view, off) { //xz 16 bit + cVec[0] = view.getInt16(off, true)/4096; + cVec[2] = view.getInt16(off+2, true)/4096; + pushVector(); + } + + + instructions[0x27] = function(view, off) { //yz 16 bit + cVec[1] = view.getInt16(off, true)/4096; + cVec[2] = view.getInt16(off+2, true)/4096; + pushVector(); + } + + instructions[0x28] = function(view, off) { //xyz 10 bit relative + var dat = view.getUint32(off, true); + cVec[0] += relativeSign(dat); + cVec[1] += relativeSign(dat>>10); + cVec[2] += relativeSign(dat>>20); + pushVector(); + } + + instructions[0x40] = function(view, off) { //begin vtx + var dat = view.getUint32(off, true); + vecMode = dat; + + if (!optimiseTriangles) { + vecPos = []; + vecNorm = []; + vecTx = []; + vecCol = []; + vecMat = []; + } + vecNum = 0; + } + + instructions[0x41] = function(view, off) { //end vtx + if (!optimiseTriangles) pushStrip(); + } + + function setAlpha(alpha) { //for fading specific things out or whatever + alphaMul = alpha; + } + + function getViewWidth(){ + return gl.viewportWidth; + } + + function getViewHeight() { + return gl.viewportHeight; + } + + function pushStrip() { //push the last group of triangles to the buffer. Should do this on matrix change... details fourthcoming + var modes = (optimiseTriangles)?[gl.TRIANGLES, gl.TRIANGLES, gl.TRIANGLES, gl.TRIANGLES]:[gl.TRIANGLES, gl.TRIANGLES, gl.TRIANGLE_STRIP, gl.TRIANGLE_STRIP]; + var pos = gl.createBuffer(); + var col = gl.createBuffer(); + var tx = gl.createBuffer(); + var mat = gl.createBuffer(); + var norm = gl.createBuffer(); + + var posArray = new Float32Array(vecPos); + + gl.bindBuffer(gl.ARRAY_BUFFER, pos); + gl.bufferData(gl.ARRAY_BUFFER, posArray, gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, tx); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecTx), gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, col); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecCol), gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, mat); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecMat), gl.STATIC_DRAW); + + gl.bindBuffer(gl.ARRAY_BUFFER, norm); + gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vecNorm), gl.STATIC_DRAW); + + modelBuffer.strips.push({ + posArray: posArray, + vPos: pos, + vTx: tx, + vCol: col, + vMat: mat, + vNorm: norm, + verts: vecPos.length/3, + mode: modes[vecMode] + }) + } + + function pushVector() { + if (vecMode == 1 && vecNum%4 == 3) { //quads - special case + vecPos = vecPos.concat(vecPos.slice(vecPos.length-9, vecPos.length-6)).concat(vecPos.slice(vecPos.length-3)); + vecNorm = vecNorm.concat(vecNorm.slice(vecNorm.length-9, vecNorm.length-6)).concat(vecNorm.slice(vecNorm.length-3)); + vecTx = vecTx.concat(vecTx.slice(vecTx.length-6, vecTx.length-4)).concat(vecTx.slice(vecTx.length-2)); + vecCol = vecCol.concat(vecCol.slice(vecCol.length-12, vecCol.length-8)).concat(vecCol.slice(vecCol.length-4)); + vecMat = vecMat.concat(vecMat.slice(vecMat.length-3, vecMat.length-2)).concat(vecMat.slice(vecMat.length-1)); + } + + if (optimiseTriangles && (vecMode > 1) && (vecNum > 2)) { //convert tri strips to individual triangles so we get one buffer per polygon + vecPos = vecPos.concat(vecPos.slice(vecPos.length-6)); + vecNorm = vecNorm.concat(vecNorm.slice(vecNorm.length-6)); + vecTx = vecTx.concat(vecTx.slice(vecTx.length-4)); + vecCol = vecCol.concat(vecCol.slice(vecCol.length-8)); + vecMat = vecMat.concat(vecMat.slice(vecMat.length-2)); + } + + vecNum++; + + vecPos = vecPos.concat(cVec); + vecTx = vecTx.concat(texCoord); + vecCol = vecCol.concat(color); + vecNorm = vecNorm.concat(norm); + vecMat.push(curMat); + + } + + function tenBitSign(val) { + val &= 1023; + if (val & 512) return (val-1024)/64; + else return val/64; + } + function relativeSign(val) { + val &= 1023; + if (val & 512) return (val-1024)/4096; + else return val/4096; + } + + this.init = function(ctx) { + gl = ctx; + this.gl = gl; + + shaders = nitroShaders.compileShaders(gl); + + this.nitroShader = shaders[0]; + this.cullModes = [gl.FRONT_AND_BACK, gl.FRONT, gl.BACK]; + } + + this.prepareShader = function() { + //prepares the shader so no redundant calls have to be made. Should be called upon every program change. + gl.enable(gl.BLEND); + gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); + this.last = {}; + gl.activeTexture(gl.TEXTURE0); + gl.uniform1i(this.nitroShader.samplerUniform, 0); + } + + this.setShadowMode = function(sTex, fsTex, sMat, fsMat) { + this.nitroShader = shaders[1]; + var shader = shaders[1]; + gl.useProgram(shader); + + gl.uniformMatrix4fv(shader.shadowMatUniform, false, sMat); + gl.uniformMatrix4fv(shader.farShadowMatUniform, false, fsMat); + + gl.uniform1f(shader.shadOffUniform, 0.00005+((mobile)?0.0005:0)); + gl.uniform1f(shader.farShadOffUniform, 0.0005); + + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, sTex); + gl.uniform1i(shader.lightSamplerUniform, 1); + + gl.activeTexture(gl.TEXTURE2); + gl.bindTexture(gl.TEXTURE_2D, fsTex); + gl.uniform1i(shader.farLightSamplerUniform, 2); + + this.setColMult([1, 1, 1, 1]); + this.prepareShader(); + } + + this.unsetShadowMode = function() { + this.nitroShader = shaders[0]; + gl.useProgram(this.nitroShader); + + this.setColMult([1, 1, 1, 1]); + this.prepareShader(); + } + + this.setColMult = function(color) { + gl.useProgram(this.nitroShader); + gl.uniform4fv(this.nitroShader.colMultUniform, color); + } + + this.updateBillboards = function(view) { + this.billboardID = (this.billboardID+1)%0xFFFFFF; + + var nv = mat4.clone(view); + nv[12] = 0; + nv[13] = 0; + nv[14] = 0; //nullify translation + var nv2 = mat4.clone(nv); + this.billboardMat = mat4.invert(nv, nv); + nv2[4] = 0; + nv2[5] = 1; //do not invert y axis view + nv2[6] = 0; + this.yBillboardMat = mat4.invert(nv2, nv2); + } + + function renderDispList(disp, tex, startStack) { //renders the display list to a form of vertex buffer. The idea is that NSBTA and NSBCA can still be applied to the buffer at little performance cost. (rather than recompiling the model) + modelBuffer = { + strips: [] + /* strip entry format: + vPos: glBuffer, + vTx: glBuffer, + vCol: glBuffer, + verts: int count of vertices, + mode: (eg. gl.TRIANGLES, gl.TRIANGLESTRIP) + mat: transformation matrix to apply. unused atm as matrix functions are unimplemented + */ + } //the nitroModel will store this and use it for rendering instead of the display list in future. + + curMat = startStack; //start on root bone + var shader = nitroRender.nitroShader; + var gl = nitroRender.gl; + var off=0; + var view = new DataView(disp); + + texWidth = tex.width; + texHeight = tex.height; + + cVec = [0,0,0]; + norm = [0,1,0]; + texCoord = [0,0]; + color = [1,1,1,alphaMul]; //todo: polygon attributes + + vecMode = 0; + vecNum = 0; + vecPos = []; + vecNorm = []; + vecTx = []; + vecCol = []; + vecMat = []; + + while (off < disp.byteLength) { + var ioff = off; + off += 4; + for (var i=0; i<4; i++) { + var inst = view.getUint8(ioff++); + if (instructions[inst] != null) { + instructions[inst](view, off); + } else { + if (inst != 0) alert("invalid instruction 0x"+(inst.toString(16))); + } + var temp = parameters[inst]; + off += (temp == null)?0:temp*4; + } + } + + if (optimiseTriangles) pushStrip(); + + return modelBuffer; + } + +}; + +function nitroModel(bmd, btx, remap) { + var bmd = bmd; + this.bmd = bmd; + var thisObj = this; + var loadedTex; + var texCanvas; + var tex; + var texAnim; + var texFrame; + var modelBuffers; + var collisionModel = []; + var matBufEmpty = new Float32Array(31*16); + + var temp = mat4.create(); + var off=0; + for (var i=0; i<31; i++) { + matBufEmpty.set(temp, off); + off += 16; + } + temp = null; + + var texMap = { tex:{}, pal:{} }; + //var matStack; + this.draw = draw; + this.drawPoly = externDrawPoly; + this.drawModel = externDrawModel; + this.getCollisionModel = getCollisionModel; + + modelBuffers = [] + this.modelBuffers = modelBuffers; + var matBuf = []; + for (var i=0; i>anim.frameStep.scaleS)%anim.scaleS.length], anim.scaleT[(texFrame>>anim.frameStep.scaleT)%anim.scaleT.length]]); + mat3.translate(mat, mat, [-anim.translateS[(texFrame>>anim.frameStep.translateS)%anim.translateS.length], anim.translateT[(texFrame>>anim.frameStep.translateT)%anim.translateT.length]]) //for some mystery reason I need to negate the S translation + gl.uniformMatrix3fv(shader.texMatrixUniform, false, mat); + } else { + gl.uniformMatrix3fv(shader.texMatrixUniform, false, material.texMat); + } + + } else gl.uniformMatrix3fv(shader.texMatrixUniform, false, material.texMat); + + if (modelBuffers[modelind][polyind] == null) modelBuffers[modelind][polyind] = nitroRender.renderDispList(poly.disp, tex[poly.mat], (poly.stackID == null)?model.lastStackID:poly.stackID); + drawModelBuffer(modelBuffers[modelind][polyind], gl, shader); + } + +function generateMatrixStack(model, targ) { //this generates a matrix stack with the default bones. use nitroAnimator to pass custom matrix stacks using nsbca animations. + var matrices = []; + + var objs = model.objects.objectData; + var cmds = model.commands; + var curMat = mat4.create(); + var lastStackID = 0; + + for (var i=0; i1.0 || lightDist.y>1.0) {\n\ + if (texture2D(farLightDSampler, fLightDist.xy).r+farShadOff < fLightDist.z) {\n\ + gl_FragColor = gl_FragColor*vec4(0.5, 0.5, 0.7, 1);\n\ + }\n\ + } else {\n\ + if (texture2D(lightDSampler, lightDist.xy).r+shadOff < lightDist.z) {\n\ + gl_FragColor = gl_FragColor*vec4(0.5, 0.5, 0.7, 1);\n\ + }\n\ + }\n", + + extra: "" + } + + var baseConf = { + frag: this.defaultFrag, vert: this.defaultVert, + uniforms: [ + ["pMatrixUniform", "uPMatrix"], + ["matStackUniform", "matStack"], + ["mvMatrixUniform", "uMVMatrix"], + ["texMatrixUniform", "texMatrix"], + ["samplerUniform", "uSampler"], + ["colMultUniform", "colMult"], + ], + attributes: [ + ["vertexPositionAttribute", "aVertexPosition"], + ["textureCoordAttribute", "aTextureCoord"], + ["colorAttribute", "aColor"], + ["matAttribute", "matrixID"], + ["normAttribute", "aNormal"] + ] + }; + + var config = []; + + var fragParts = [ + dFrag, + lightFrag, + sdFrag + ] + + var shadUnif = [ + ["shadowMatUniform", "shadowMat"], + ["farShadowMatUniform", "farShadowMat"], + + ["shadOffUniform", "shadOff"], + ["farShadOffUniform", "farShadOff"], + + ["lightSamplerUniform", "lightDSampler"], + ["farLightSamplerUniform", "farLightDSampler"] + ] + + config[0] = baseConf; + + config[1] = {frag: this.shadFrag, vert: this.shadVert, uniforms: baseConf.uniforms.slice(0), attributes: baseConf.attributes.slice(0)}; + config[1].uniforms = config[1].uniforms.concat(shadUnif); + + function makeShader(source, base, id) { //makes shaders using flags + + } + + function combineGLSL(shaderParts) { + var out = ""; + + for (var i=0; i length) { + scene.removeEntity(t); + } + } +} \ No newline at end of file diff --git a/Code/UI/uiPlace.js b/Code/UI/uiPlace.js new file mode 100644 index 0000000..fa78509 --- /dev/null +++ b/Code/UI/uiPlace.js @@ -0,0 +1,105 @@ +// +// !! all UI objects assume you have forced positive y as down! +// + +window.uiPlace = function(gl) { + + var WHITE = [1, 1, 1, 1]; + + var frontBuf = { + pos: gl.createBuffer(), + col: gl.createBuffer(), + tx: gl.createBuffer() + } + + var backBuf = { + pos: gl.createBuffer(), + col: gl.createBuffer(), + tx: gl.createBuffer() + } + + var backActive = false; + + function setPlace(num) { + if (nun < 10) { + + } else { + var tens = Math.floor(num/10)%10; + var suffix = (tens == 1)?3:(Math.min(3, (num-1)%10)); + } + } + + function genVertRect(targ, dx, dy, dwidth, dheight, sx, sy, swidth, sheight, z, cornerColours) { //y is down positive. we adjust texture coords to fit this. + var cornerColours = cornerColours + if (cornerColours == null) cornerColours = [WHITE, WHITE, WHITE, WHITE]; + + var vpos = targ.vpos; + var vcol = targ.vcol; + var vtx = targ.vtx; + + // tri 1 + // + // 1 2 + // --------- + // | / + // | / + // | / + // |/ + // + // 3 + // + + vpos.push(dx); + vpos.push(dy); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[0]); + vtx.push(sx); + vtx.push(1-sy); + + vpos.push(dx+dwidth); + vpos.push(dy); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[1]); + vtx.push(sx+swidth); + vtx.push(1-sy); + + vpos.push(dx); + vpos.push(dy+dheight); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[2]); + vtx.push(sx); + vtx.push(1-(sy+sheight)); + + //tri 2 + // + // 1 + // /| + // / | + // / | + // / | + // --------- 3 + // 2 + + vpos.push(dx+dwidth); + vpos.push(dy); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[1]); + vtx.push(sx+swidth); + vtx.push(1-sy); + + vpos.push(dx); + vpos.push(dy+dheight); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[2]); + vtx.push(sx); + vtx.push(1-(sy+sheight)); + + vpos.push(dx+dwidth); + vpos.push(dy+dheight); + vpos.push(z); + vcol = vcol.concat(vcol, cornerColours[2]); + vtx.push(sx+swidth); + vtx.push(1-(sy+sheight)); + + } +} \ No newline at end of file diff --git a/Code/glMatrix/gl-matrix-min.js b/Code/glMatrix/gl-matrix-min.js new file mode 100644 index 0000000..973d11c --- /dev/null +++ b/Code/glMatrix/gl-matrix-min.js @@ -0,0 +1,28 @@ +/** + * @fileoverview gl-matrix - High performance matrix and vector operations + * @author Brandon Jones + * @author Colin MacKenzie IV + * @version 2.2.1 + */ +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +(function(e){"use strict";var t={};typeof exports=="undefined"?typeof define=="function"&&typeof define.amd=="object"&&define.amd?(t.exports={},define(function(){return t.exports})):t.exports=typeof window!="undefined"?window:e:t.exports=exports,function(e){if(!t)var t=1e-6;if(!n)var n=typeof Float32Array!="undefined"?Float32Array:Array;if(!r)var r=Math.random;var i={};i.setMatrixArrayType=function(e){n=e},typeof e!="undefined"&&(e.glMatrix=i);var s=Math.PI/180;i.toRadian=function(e){return e*s};var o={};o.create=function(){var e=new n(2);return e[0]=0,e[1]=0,e},o.clone=function(e){var t=new n(2);return t[0]=e[0],t[1]=e[1],t},o.fromValues=function(e,t){var r=new n(2);return r[0]=e,r[1]=t,r},o.copy=function(e,t){return e[0]=t[0],e[1]=t[1],e},o.set=function(e,t,n){return e[0]=t,e[1]=n,e},o.add=function(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e},o.subtract=function(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e},o.sub=o.subtract,o.multiply=function(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e},o.mul=o.multiply,o.divide=function(e,t,n){return e[0]=t[0]/n[0],e[1]=t[1]/n[1],e},o.div=o.divide,o.min=function(e,t,n){return e[0]=Math.min(t[0],n[0]),e[1]=Math.min(t[1],n[1]),e},o.max=function(e,t,n){return e[0]=Math.max(t[0],n[0]),e[1]=Math.max(t[1],n[1]),e},o.scale=function(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e},o.scaleAndAdd=function(e,t,n,r){return e[0]=t[0]+n[0]*r,e[1]=t[1]+n[1]*r,e},o.distance=function(e,t){var n=t[0]-e[0],r=t[1]-e[1];return Math.sqrt(n*n+r*r)},o.dist=o.distance,o.squaredDistance=function(e,t){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r},o.sqrDist=o.squaredDistance,o.length=function(e){var t=e[0],n=e[1];return Math.sqrt(t*t+n*n)},o.len=o.length,o.squaredLength=function(e){var t=e[0],n=e[1];return t*t+n*n},o.sqrLen=o.squaredLength,o.negate=function(e,t){return e[0]=-t[0],e[1]=-t[1],e},o.normalize=function(e,t){var n=t[0],r=t[1],i=n*n+r*r;return i>0&&(i=1/Math.sqrt(i),e[0]=t[0]*i,e[1]=t[1]*i),e},o.dot=function(e,t){return e[0]*t[0]+e[1]*t[1]},o.cross=function(e,t,n){var r=t[0]*n[1]-t[1]*n[0];return e[0]=e[1]=0,e[2]=r,e},o.lerp=function(e,t,n,r){var i=t[0],s=t[1];return e[0]=i+r*(n[0]-i),e[1]=s+r*(n[1]-s),e},o.random=function(e,t){t=t||1;var n=r()*2*Math.PI;return e[0]=Math.cos(n)*t,e[1]=Math.sin(n)*t,e},o.transformMat2=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[2]*i,e[1]=n[1]*r+n[3]*i,e},o.transformMat2d=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[2]*i+n[4],e[1]=n[1]*r+n[3]*i+n[5],e},o.transformMat3=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[3]*i+n[6],e[1]=n[1]*r+n[4]*i+n[7],e},o.transformMat4=function(e,t,n){var r=t[0],i=t[1];return e[0]=n[0]*r+n[4]*i+n[12],e[1]=n[1]*r+n[5]*i+n[13],e},o.forEach=function(){var e=o.create();return function(t,n,r,i,s,o){var u,a;n||(n=2),r||(r=0),i?a=Math.min(i*n+r,t.length):a=t.length;for(u=r;u0&&(s=1/Math.sqrt(s),e[0]=t[0]*s,e[1]=t[1]*s,e[2]=t[2]*s),e},u.dot=function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]},u.cross=function(e,t,n){var r=t[0],i=t[1],s=t[2],o=n[0],u=n[1],a=n[2];return e[0]=i*a-s*u,e[1]=s*o-r*a,e[2]=r*u-i*o,e},u.lerp=function(e,t,n,r){var i=t[0],s=t[1],o=t[2];return e[0]=i+r*(n[0]-i),e[1]=s+r*(n[1]-s),e[2]=o+r*(n[2]-o),e},u.random=function(e,t){t=t||1;var n=r()*2*Math.PI,i=r()*2-1,s=Math.sqrt(1-i*i)*t;return e[0]=Math.cos(n)*s,e[1]=Math.sin(n)*s,e[2]=i*t,e},u.transformMat4=function(e,t,n){var r=t[0],i=t[1],s=t[2];return e[0]=n[0]*r+n[4]*i+n[8]*s+n[12],e[1]=n[1]*r+n[5]*i+n[9]*s+n[13],e[2]=n[2]*r+n[6]*i+n[10]*s+n[14],e},u.transformMat3=function(e,t,n){var r=t[0],i=t[1],s=t[2];return e[0]=r*n[0]+i*n[3]+s*n[6],e[1]=r*n[1]+i*n[4]+s*n[7],e[2]=r*n[2]+i*n[5]+s*n[8],e},u.transformQuat=function(e,t,n){var r=t[0],i=t[1],s=t[2],o=n[0],u=n[1],a=n[2],f=n[3],l=f*r+u*s-a*i,c=f*i+a*r-o*s,h=f*s+o*i-u*r,p=-o*r-u*i-a*s;return e[0]=l*f+p*-o+c*-a-h*-u,e[1]=c*f+p*-u+h*-o-l*-a,e[2]=h*f+p*-a+l*-u-c*-o,e},u.rotateX=function(e,t,n,r){var i=[],s=[];return i[0]=t[0]-n[0],i[1]=t[1]-n[1],i[2]=t[2]-n[2],s[0]=i[0],s[1]=i[1]*Math.cos(r)-i[2]*Math.sin(r),s[2]=i[1]*Math.sin(r)+i[2]*Math.cos(r),e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=s[2]+n[2],e},u.rotateY=function(e,t,n,r){var i=[],s=[];return i[0]=t[0]-n[0],i[1]=t[1]-n[1],i[2]=t[2]-n[2],s[0]=i[2]*Math.sin(r)+i[0]*Math.cos(r),s[1]=i[1],s[2]=i[2]*Math.cos(r)-i[0]*Math.sin(r),e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=s[2]+n[2],e},u.rotateZ=function(e,t,n,r){var i=[],s=[];return i[0]=t[0]-n[0],i[1]=t[1]-n[1],i[2]=t[2]-n[2],s[0]=i[0]*Math.cos(r)-i[1]*Math.sin(r),s[1]=i[0]*Math.sin(r)+i[1]*Math.cos(r),s[2]=i[2],e[0]=s[0]+n[0],e[1]=s[1]+n[1],e[2]=s[2]+n[2],e},u.forEach=function(){var e=u.create();return function(t,n,r,i,s,o){var u,a;n||(n=3),r||(r=0),i?a=Math.min(i*n+r,t.length):a=t.length;for(u=r;u0&&(o=1/Math.sqrt(o),e[0]=t[0]*o,e[1]=t[1]*o,e[2]=t[2]*o,e[3]=t[3]*o),e},a.dot=function(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]},a.lerp=function(e,t,n,r){var i=t[0],s=t[1],o=t[2],u=t[3];return e[0]=i+r*(n[0]-i),e[1]=s+r*(n[1]-s),e[2]=o+r*(n[2]-o),e[3]=u+r*(n[3]-u),e},a.random=function(e,t){return t=t||1,e[0]=r(),e[1]=r(),e[2]=r(),e[3]=r(),a.normalize(e,e),a.scale(e,e,t),e},a.transformMat4=function(e,t,n){var r=t[0],i=t[1],s=t[2],o=t[3];return e[0]=n[0]*r+n[4]*i+n[8]*s+n[12]*o,e[1]=n[1]*r+n[5]*i+n[9]*s+n[13]*o,e[2]=n[2]*r+n[6]*i+n[10]*s+n[14]*o,e[3]=n[3]*r+n[7]*i+n[11]*s+n[15]*o,e},a.transformQuat=function(e,t,n){var r=t[0],i=t[1],s=t[2],o=n[0],u=n[1],a=n[2],f=n[3],l=f*r+u*s-a*i,c=f*i+a*r-o*s,h=f*s+o*i-u*r,p=-o*r-u*i-a*s;return e[0]=l*f+p*-o+c*-a-h*-u,e[1]=c*f+p*-u+h*-o-l*-a,e[2]=h*f+p*-a+l*-u-c*-o,e},a.forEach=function(){var e=a.create();return function(t,n,r,i,s,o){var u,a;n||(n=4),r||(r=0),i?a=Math.min(i*n+r,t.length):a=t.length;for(u=r;u.999999?(r[0]=0,r[1]=0,r[2]=0,r[3]=1,r):(u.cross(e,i,s),r[0]=e[0],r[1]=e[1],r[2]=e[2],r[3]=1+o,p.normalize(r,r))}}(),p.setAxes=function(){var e=c.create();return function(t,n,r,i){return e[0]=r[0],e[3]=r[1],e[6]=r[2],e[1]=i[0],e[4]=i[1],e[7]=i[2],e[2]=-n[0],e[5]=-n[1],e[8]=-n[2],p.normalize(t,p.fromMat3(t,e))}}(),p.clone=a.clone,p.fromValues=a.fromValues,p.copy=a.copy,p.set=a.set,p.identity=function(e){return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},p.setAxisAngle=function(e,t,n){n*=.5;var r=Math.sin(n);return e[0]=r*t[0],e[1]=r*t[1],e[2]=r*t[2],e[3]=Math.cos(n),e},p.add=a.add,p.multiply=function(e,t,n){var r=t[0],i=t[1],s=t[2],o=t[3],u=n[0],a=n[1],f=n[2],l=n[3];return e[0]=r*l+o*u+i*f-s*a,e[1]=i*l+o*a+s*u-r*f,e[2]=s*l+o*f+r*a-i*u,e[3]=o*l-r*u-i*a-s*f,e},p.mul=p.multiply,p.scale=a.scale,p.rotateX=function(e,t,n){n*=.5;var r=t[0],i=t[1],s=t[2],o=t[3],u=Math.sin(n),a=Math.cos(n);return e[0]=r*a+o*u,e[1]=i*a+s*u,e[2]=s*a-i*u,e[3]=o*a-r*u,e},p.rotateY=function(e,t,n){n*=.5;var r=t[0],i=t[1],s=t[2],o=t[3],u=Math.sin(n),a=Math.cos(n);return e[0]=r*a-s*u,e[1]=i*a+o*u,e[2]=s*a+r*u,e[3]=o*a-i*u,e},p.rotateZ=function(e,t,n){n*=.5;var r=t[0],i=t[1],s=t[2],o=t[3],u=Math.sin(n),a=Math.cos(n);return e[0]=r*a+i*u,e[1]=i*a-r*u,e[2]=s*a+o*u,e[3]=o*a-s*u,e},p.calculateW=function(e,t){var n=t[0],r=t[1],i=t[2];return e[0]=n,e[1]=r,e[2]=i,e[3]=-Math.sqrt(Math.abs(1-n*n-r*r-i*i)),e},p.dot=a.dot,p.lerp=a.lerp,p.slerp=function(e,t,n,r){var i=t[0],s=t[1],o=t[2],u=t[3],a=n[0],f=n[1],l=n[2],c=n[3],h,p,d,v,m;return p=i*a+s*f+o*l+u*c,p<0&&(p=-p,a=-a,f=-f,l=-l,c=-c),1-p>1e-6?(h=Math.acos(p),d=Math.sin(h),v=Math.sin((1-r)*h)/d,m=Math.sin(r*h)/d):(v=1-r,m=r),e[0]=v*i+m*a,e[1]=v*s+m*f,e[2]=v*o+m*l,e[3]=v*u+m*c,e},p.invert=function(e,t){var n=t[0],r=t[1],i=t[2],s=t[3],o=n*n+r*r+i*i+s*s,u=o?1/o:0;return e[0]=-n*u,e[1]=-r*u,e[2]=-i*u,e[3]=s*u,e},p.conjugate=function(e,t){return e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e[3]=t[3],e},p.length=a.length,p.len=p.length,p.squaredLength=a.squaredLength,p.sqrLen=p.squaredLength,p.normalize=a.normalize,p.fromMat3=function(e,t){var n=t[0]+t[4]+t[8],r;if(n>0)r=Math.sqrt(n+1),e[3]=.5*r,r=.5/r,e[0]=(t[7]-t[5])*r,e[1]=(t[2]-t[6])*r,e[2]=(t[3]-t[1])*r;else{var i=0;t[4]>t[0]&&(i=1),t[8]>t[i*3+i]&&(i=2);var s=(i+1)%3,o=(i+2)%3;r=Math.sqrt(t[i*3+i]-t[s*3+s]-t[o*3+o]+1),e[i]=.5*r,r=.5/r,e[3]=(t[o*3+s]-t[s*3+o])*r,e[s]=(t[s*3+i]+t[i*3+s])*r,e[o]=(t[o*3+i]+t[i*3+o])*r}return e},p.str=function(e){return"quat("+e[0]+", "+e[1]+", "+e[2]+", "+e[3]+")"},typeof e!="undefined"&&(e.quat=p)}(t.exports)})(this); diff --git a/Code/glMatrix/gl-matrix.js b/Code/glMatrix/gl-matrix.js new file mode 100644 index 0000000..9316004 --- /dev/null +++ b/Code/glMatrix/gl-matrix.js @@ -0,0 +1,4292 @@ +/** + * @fileoverview gl-matrix - High performance matrix and vector operations + * @author Brandon Jones + * @author Colin MacKenzie IV + * @version 2.2.2 + */ + +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + + +(function(_global) { + "use strict"; + + var shim = {}; + if (typeof(exports) === 'undefined') { + if(typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + shim.exports = {}; + define(function() { + return shim.exports; + }); + } else { + // gl-matrix lives in a browser, define its namespaces in global + shim.exports = typeof(window) !== 'undefined' ? window : _global; + } + } + else { + // gl-matrix lives in commonjs, define its namespaces in exports + shim.exports = exports; + } + + (function(exports) { + /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + + +if(!GLMAT_EPSILON) { + var GLMAT_EPSILON = 0.000001; +} + +if(!GLMAT_ARRAY_TYPE) { + var GLMAT_ARRAY_TYPE = (typeof Float32Array !== 'undefined') ? Float32Array : Array; +} + +if(!GLMAT_RANDOM) { + var GLMAT_RANDOM = Math.random; +} + +/** + * @class Common utilities + * @name glMatrix + */ +var glMatrix = {}; + +/** + * Sets the type of array used when creating new vectors and matrices + * + * @param {Type} type Array type, such as Float32Array or Array + */ +glMatrix.setMatrixArrayType = function(type) { + GLMAT_ARRAY_TYPE = type; +} + +if(typeof(exports) !== 'undefined') { + exports.glMatrix = glMatrix; +} + +var degree = Math.PI / 180; + +/** +* Convert Degree To Radian +* +* @param {Number} Angle in Degrees +*/ +glMatrix.toRadian = function(a){ + return a * degree; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 2 Dimensional Vector + * @name vec2 + */ + +var vec2 = {}; + +/** + * Creates a new, empty vec2 + * + * @returns {vec2} a new 2D vector + */ +vec2.create = function() { + var out = new GLMAT_ARRAY_TYPE(2); + out[0] = 0; + out[1] = 0; + return out; +}; + +/** + * Creates a new vec2 initialized with values from an existing vector + * + * @param {vec2} a vector to clone + * @returns {vec2} a new 2D vector + */ +vec2.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(2); + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Creates a new vec2 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} a new 2D vector + */ +vec2.fromValues = function(x, y) { + var out = new GLMAT_ARRAY_TYPE(2); + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Copy the values from one vec2 to another + * + * @param {vec2} out the receiving vector + * @param {vec2} a the source vector + * @returns {vec2} out + */ +vec2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + return out; +}; + +/** + * Set the components of a vec2 to the given values + * + * @param {vec2} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @returns {vec2} out + */ +vec2.set = function(out, x, y) { + out[0] = x; + out[1] = y; + return out; +}; + +/** + * Adds two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + return out; +}; + +/** + * Subtracts vector b from vector a + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + return out; +}; + +/** + * Alias for {@link vec2.subtract} + * @function + */ +vec2.sub = vec2.subtract; + +/** + * Multiplies two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + return out; +}; + +/** + * Alias for {@link vec2.multiply} + * @function + */ +vec2.mul = vec2.multiply; + +/** + * Divides two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + return out; +}; + +/** + * Alias for {@link vec2.divide} + * @function + */ +vec2.div = vec2.divide; + +/** + * Returns the minimum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.min = function(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + return out; +}; + +/** + * Returns the maximum of two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec2} out + */ +vec2.max = function(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + return out; +}; + +/** + * Scales a vec2 by a scalar number + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec2} out + */ +vec2.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + return out; +}; + +/** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec2} out + */ +vec2.scaleAndAdd = function(out, a, b, scale) { + out[0] = a[0] + (b[0] * scale); + out[1] = a[1] + (b[1] * scale); + return out; +}; + +/** + * Calculates the euclidian distance between two vec2's + * + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {Number} distance between a and b + */ +vec2.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for {@link vec2.distance} + * @function + */ +vec2.dist = vec2.distance; + +/** + * Calculates the squared euclidian distance between two vec2's + * + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {Number} squared distance between a and b + */ +vec2.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1]; + return x*x + y*y; +}; + +/** + * Alias for {@link vec2.squaredDistance} + * @function + */ +vec2.sqrDist = vec2.squaredDistance; + +/** + * Calculates the length of a vec2 + * + * @param {vec2} a vector to calculate length of + * @returns {Number} length of a + */ +vec2.length = function (a) { + var x = a[0], + y = a[1]; + return Math.sqrt(x*x + y*y); +}; + +/** + * Alias for {@link vec2.length} + * @function + */ +vec2.len = vec2.length; + +/** + * Calculates the squared length of a vec2 + * + * @param {vec2} a vector to calculate squared length of + * @returns {Number} squared length of a + */ +vec2.squaredLength = function (a) { + var x = a[0], + y = a[1]; + return x*x + y*y; +}; + +/** + * Alias for {@link vec2.squaredLength} + * @function + */ +vec2.sqrLen = vec2.squaredLength; + +/** + * Negates the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to negate + * @returns {vec2} out + */ +vec2.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + return out; +}; + +/** + * Returns the inverse of the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to invert + * @returns {vec2} out + */ +vec2.inverse = function(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + return out; +}; + +/** + * Normalize a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to normalize + * @returns {vec2} out + */ +vec2.normalize = function(out, a) { + var x = a[0], + y = a[1]; + var len = x*x + y*y; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec2's + * + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {Number} dot product of a and b + */ +vec2.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1]; +}; + +/** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param {vec3} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @returns {vec3} out + */ +vec2.cross = function(out, a, b) { + var z = a[0] * b[1] - a[1] * b[0]; + out[0] = out[1] = 0; + out[2] = z; + return out; +}; + +/** + * Performs a linear interpolation between two vec2's + * + * @param {vec2} out the receiving vector + * @param {vec2} a the first operand + * @param {vec2} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {vec2} out + */ +vec2.lerp = function (out, a, b, t) { + var ax = a[0], + ay = a[1]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + return out; +}; + +/** + * Generates a random vector with the given scale + * + * @param {vec2} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec2} out + */ +vec2.random = function (out, scale) { + scale = scale || 1.0; + var r = GLMAT_RANDOM() * 2.0 * Math.PI; + out[0] = Math.cos(r) * scale; + out[1] = Math.sin(r) * scale; + return out; +}; + +/** + * Transforms the vec2 with a mat2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat2} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat2 = function(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[2] * y; + out[1] = m[1] * x + m[3] * y; + return out; +}; + +/** + * Transforms the vec2 with a mat2d + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat2d} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat2d = function(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[2] * y + m[4]; + out[1] = m[1] * x + m[3] * y + m[5]; + return out; +}; + +/** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat3} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat3 = function(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[3] * y + m[6]; + out[1] = m[1] * x + m[4] * y + m[7]; + return out; +}; + +/** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param {vec2} out the receiving vector + * @param {vec2} a the vector to transform + * @param {mat4} m matrix to transform with + * @returns {vec2} out + */ +vec2.transformMat4 = function(out, a, m) { + var x = a[0], + y = a[1]; + out[0] = m[0] * x + m[4] * y + m[12]; + out[1] = m[1] * x + m[5] * y + m[13]; + return out; +}; + +/** + * Perform some operation over an array of vec2s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ +vec2.forEach = (function() { + var vec = vec2.create(); + + return function(a, stride, offset, count, fn, arg) { + var i, l; + if(!stride) { + stride = 2; + } + + if(!offset) { + offset = 0; + } + + if(count) { + l = Math.min((count * stride) + offset, a.length); + } else { + l = a.length; + } + + for(i = offset; i < l; i += stride) { + vec[0] = a[i]; vec[1] = a[i+1]; + fn(vec, vec, arg); + a[i] = vec[0]; a[i+1] = vec[1]; + } + + return a; + }; +})(); + +/** + * Returns a string representation of a vector + * + * @param {vec2} vec vector to represent as a string + * @returns {String} string representation of the vector + */ +vec2.str = function (a) { + return 'vec2(' + a[0] + ', ' + a[1] + ')'; +}; + +if(typeof(exports) !== 'undefined') { + exports.vec2 = vec2; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 3 Dimensional Vector + * @name vec3 + */ + +var vec3 = {}; + +/** + * Creates a new, empty vec3 + * + * @returns {vec3} a new 3D vector + */ +vec3.create = function() { + var out = new GLMAT_ARRAY_TYPE(3); + out[0] = 0; + out[1] = 0; + out[2] = 0; + return out; +}; + +/** + * Creates a new vec3 initialized with values from an existing vector + * + * @param {vec3} a vector to clone + * @returns {vec3} a new 3D vector + */ +vec3.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(3); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; +}; + +/** + * Creates a new vec3 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} a new 3D vector + */ +vec3.fromValues = function(x, y, z) { + var out = new GLMAT_ARRAY_TYPE(3); + out[0] = x; + out[1] = y; + out[2] = z; + return out; +}; + +/** + * Copy the values from one vec3 to another + * + * @param {vec3} out the receiving vector + * @param {vec3} a the source vector + * @returns {vec3} out + */ +vec3.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + return out; +}; + +/** + * Set the components of a vec3 to the given values + * + * @param {vec3} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @returns {vec3} out + */ +vec3.set = function(out, x, y, z) { + out[0] = x; + out[1] = y; + out[2] = z; + return out; +}; + +/** + * Adds two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + return out; +}; + +/** + * Subtracts vector b from vector a + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + return out; +}; + +/** + * Alias for {@link vec3.subtract} + * @function + */ +vec3.sub = vec3.subtract; + +/** + * Multiplies two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + return out; +}; + +/** + * Alias for {@link vec3.multiply} + * @function + */ +vec3.mul = vec3.multiply; + +/** + * Divides two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + return out; +}; + +/** + * Alias for {@link vec3.divide} + * @function + */ +vec3.div = vec3.divide; + +/** + * Returns the minimum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.min = function(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + return out; +}; + +/** + * Returns the maximum of two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.max = function(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + return out; +}; + +/** + * Scales a vec3 by a scalar number + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec3} out + */ +vec3.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + return out; +}; + +/** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec3} out + */ +vec3.scaleAndAdd = function(out, a, b, scale) { + out[0] = a[0] + (b[0] * scale); + out[1] = a[1] + (b[1] * scale); + out[2] = a[2] + (b[2] * scale); + return out; +}; + +/** + * Calculates the euclidian distance between two vec3's + * + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {Number} distance between a and b + */ +vec3.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1], + z = b[2] - a[2]; + return Math.sqrt(x*x + y*y + z*z); +}; + +/** + * Alias for {@link vec3.distance} + * @function + */ +vec3.dist = vec3.distance; + +/** + * Calculates the squared euclidian distance between two vec3's + * + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {Number} squared distance between a and b + */ +vec3.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1], + z = b[2] - a[2]; + return x*x + y*y + z*z; +}; + +/** + * Alias for {@link vec3.squaredDistance} + * @function + */ +vec3.sqrDist = vec3.squaredDistance; + +/** + * Calculates the length of a vec3 + * + * @param {vec3} a vector to calculate length of + * @returns {Number} length of a + */ +vec3.length = function (a) { + var x = a[0], + y = a[1], + z = a[2]; + return Math.sqrt(x*x + y*y + z*z); +}; + +/** + * Alias for {@link vec3.length} + * @function + */ +vec3.len = vec3.length; + +/** + * Calculates the squared length of a vec3 + * + * @param {vec3} a vector to calculate squared length of + * @returns {Number} squared length of a + */ +vec3.squaredLength = function (a) { + var x = a[0], + y = a[1], + z = a[2]; + return x*x + y*y + z*z; +}; + +/** + * Alias for {@link vec3.squaredLength} + * @function + */ +vec3.sqrLen = vec3.squaredLength; + +/** + * Negates the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to negate + * @returns {vec3} out + */ +vec3.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + return out; +}; + +/** + * Returns the inverse of the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to invert + * @returns {vec3} out + */ +vec3.inverse = function(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + out[2] = 1.0 / a[2]; + return out; +}; + +/** + * Normalize a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to normalize + * @returns {vec3} out + */ +vec3.normalize = function(out, a) { + var x = a[0], + y = a[1], + z = a[2]; + var len = x*x + y*y + z*z; + if (len > 0) { + //TODO: evaluate use of glm_invsqrt here? + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + out[2] = a[2] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec3's + * + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {Number} dot product of a and b + */ +vec3.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +}; + +/** + * Computes the cross product of two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @returns {vec3} out + */ +vec3.cross = function(out, a, b) { + var ax = a[0], ay = a[1], az = a[2], + bx = b[0], by = b[1], bz = b[2]; + + out[0] = ay * bz - az * by; + out[1] = az * bx - ax * bz; + out[2] = ax * by - ay * bx; + return out; +}; + +/** + * Performs a linear interpolation between two vec3's + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {vec3} out + */ +vec3.lerp = function (out, a, b, t) { + var ax = a[0], + ay = a[1], + az = a[2]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + return out; +}; + +/** + * Generates a random vector with the given scale + * + * @param {vec3} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec3} out + */ +vec3.random = function (out, scale) { + scale = scale || 1.0; + + var r = GLMAT_RANDOM() * 2.0 * Math.PI; + var z = (GLMAT_RANDOM() * 2.0) - 1.0; + var zScale = Math.sqrt(1.0-z*z) * scale; + + out[0] = Math.cos(r) * zScale; + out[1] = Math.sin(r) * zScale; + out[2] = z * scale; + return out; +}; + +/** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to transform + * @param {mat4} m matrix to transform with + * @returns {vec3} out + */ +vec3.transformMat4 = function(out, a, m) { + var x = a[0], y = a[1], z = a[2], + w = m[3] * x + m[7] * y + m[11] * z + m[15]; + w = w || 1.0; + out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w; + out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w; + out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w; + return out; +}; + +/** + * Transforms the vec3 with a mat3. + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to transform + * @param {mat4} m the 3x3 matrix to transform with + * @returns {vec3} out + */ +vec3.transformMat3 = function(out, a, m) { + var x = a[0], y = a[1], z = a[2]; + out[0] = x * m[0] + y * m[3] + z * m[6]; + out[1] = x * m[1] + y * m[4] + z * m[7]; + out[2] = x * m[2] + y * m[5] + z * m[8]; + return out; +}; + +/** + * Transforms the vec3 with a quat + * + * @param {vec3} out the receiving vector + * @param {vec3} a the vector to transform + * @param {quat} q quaternion to transform with + * @returns {vec3} out + */ +vec3.transformQuat = function(out, a, q) { + // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations + + var x = a[0], y = a[1], z = a[2], + qx = q[0], qy = q[1], qz = q[2], qw = q[3], + + // calculate quat * vec + ix = qw * x + qy * z - qz * y, + iy = qw * y + qz * x - qx * z, + iz = qw * z + qx * y - qy * x, + iw = -qx * x - qy * y - qz * z; + + // calculate result * inverse quat + out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; + out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; + out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; + return out; +}; + +/** + * Rotate a 3D vector around the x-axis + * @param {vec3} out The receiving vec3 + * @param {vec3} a The vec3 point to rotate + * @param {vec3} b The origin of the rotation + * @param {Number} c The angle of rotation + * @returns {vec3} out + */ +vec3.rotateX = function(out, a, b, c){ + var p = [], r=[]; + //Translate point to the origin + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; + + //perform rotation + r[0] = p[0]; + r[1] = p[1]*Math.cos(c) - p[2]*Math.sin(c); + r[2] = p[1]*Math.sin(c) + p[2]*Math.cos(c); + + //translate to correct position + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + + return out; +}; + +/** + * Rotate a 3D vector around the y-axis + * @param {vec3} out The receiving vec3 + * @param {vec3} a The vec3 point to rotate + * @param {vec3} b The origin of the rotation + * @param {Number} c The angle of rotation + * @returns {vec3} out + */ +vec3.rotateY = function(out, a, b, c){ + var p = [], r=[]; + //Translate point to the origin + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; + + //perform rotation + r[0] = p[2]*Math.sin(c) + p[0]*Math.cos(c); + r[1] = p[1]; + r[2] = p[2]*Math.cos(c) - p[0]*Math.sin(c); + + //translate to correct position + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + + return out; +}; + +/** + * Rotate a 3D vector around the z-axis + * @param {vec3} out The receiving vec3 + * @param {vec3} a The vec3 point to rotate + * @param {vec3} b The origin of the rotation + * @param {Number} c The angle of rotation + * @returns {vec3} out + */ +vec3.rotateZ = function(out, a, b, c){ + var p = [], r=[]; + //Translate point to the origin + p[0] = a[0] - b[0]; + p[1] = a[1] - b[1]; + p[2] = a[2] - b[2]; + + //perform rotation + r[0] = p[0]*Math.cos(c) - p[1]*Math.sin(c); + r[1] = p[0]*Math.sin(c) + p[1]*Math.cos(c); + r[2] = p[2]; + + //translate to correct position + out[0] = r[0] + b[0]; + out[1] = r[1] + b[1]; + out[2] = r[2] + b[2]; + + return out; +}; + +/** + * Perform some operation over an array of vec3s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ +vec3.forEach = (function() { + var vec = vec3.create(); + + return function(a, stride, offset, count, fn, arg) { + var i, l; + if(!stride) { + stride = 3; + } + + if(!offset) { + offset = 0; + } + + if(count) { + l = Math.min((count * stride) + offset, a.length); + } else { + l = a.length; + } + + for(i = offset; i < l; i += stride) { + vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2]; + fn(vec, vec, arg); + a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2]; + } + + return a; + }; +})(); + +/** + * Returns a string representation of a vector + * + * @param {vec3} vec vector to represent as a string + * @returns {String} string representation of the vector + */ +vec3.str = function (a) { + return 'vec3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')'; +}; + +if(typeof(exports) !== 'undefined') { + exports.vec3 = vec3; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 4 Dimensional Vector + * @name vec4 + */ + +var vec4 = {}; + +/** + * Creates a new, empty vec4 + * + * @returns {vec4} a new 4D vector + */ +vec4.create = function() { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 0; + return out; +}; + +/** + * Creates a new vec4 initialized with values from an existing vector + * + * @param {vec4} a vector to clone + * @returns {vec4} a new 4D vector + */ +vec4.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +}; + +/** + * Creates a new vec4 initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} a new 4D vector + */ +vec4.fromValues = function(x, y, z, w) { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; +}; + +/** + * Copy the values from one vec4 to another + * + * @param {vec4} out the receiving vector + * @param {vec4} a the source vector + * @returns {vec4} out + */ +vec4.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +}; + +/** + * Set the components of a vec4 to the given values + * + * @param {vec4} out the receiving vector + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {vec4} out + */ +vec4.set = function(out, x, y, z, w) { + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = w; + return out; +}; + +/** + * Adds two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.add = function(out, a, b) { + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; + out[3] = a[3] + b[3]; + return out; +}; + +/** + * Subtracts vector b from vector a + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.subtract = function(out, a, b) { + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; + out[3] = a[3] - b[3]; + return out; +}; + +/** + * Alias for {@link vec4.subtract} + * @function + */ +vec4.sub = vec4.subtract; + +/** + * Multiplies two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.multiply = function(out, a, b) { + out[0] = a[0] * b[0]; + out[1] = a[1] * b[1]; + out[2] = a[2] * b[2]; + out[3] = a[3] * b[3]; + return out; +}; + +/** + * Alias for {@link vec4.multiply} + * @function + */ +vec4.mul = vec4.multiply; + +/** + * Divides two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.divide = function(out, a, b) { + out[0] = a[0] / b[0]; + out[1] = a[1] / b[1]; + out[2] = a[2] / b[2]; + out[3] = a[3] / b[3]; + return out; +}; + +/** + * Alias for {@link vec4.divide} + * @function + */ +vec4.div = vec4.divide; + +/** + * Returns the minimum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.min = function(out, a, b) { + out[0] = Math.min(a[0], b[0]); + out[1] = Math.min(a[1], b[1]); + out[2] = Math.min(a[2], b[2]); + out[3] = Math.min(a[3], b[3]); + return out; +}; + +/** + * Returns the maximum of two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {vec4} out + */ +vec4.max = function(out, a, b) { + out[0] = Math.max(a[0], b[0]); + out[1] = Math.max(a[1], b[1]); + out[2] = Math.max(a[2], b[2]); + out[3] = Math.max(a[3], b[3]); + return out; +}; + +/** + * Scales a vec4 by a scalar number + * + * @param {vec4} out the receiving vector + * @param {vec4} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {vec4} out + */ +vec4.scale = function(out, a, b) { + out[0] = a[0] * b; + out[1] = a[1] * b; + out[2] = a[2] * b; + out[3] = a[3] * b; + return out; +}; + +/** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @param {Number} scale the amount to scale b by before adding + * @returns {vec4} out + */ +vec4.scaleAndAdd = function(out, a, b, scale) { + out[0] = a[0] + (b[0] * scale); + out[1] = a[1] + (b[1] * scale); + out[2] = a[2] + (b[2] * scale); + out[3] = a[3] + (b[3] * scale); + return out; +}; + +/** + * Calculates the euclidian distance between two vec4's + * + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {Number} distance between a and b + */ +vec4.distance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1], + z = b[2] - a[2], + w = b[3] - a[3]; + return Math.sqrt(x*x + y*y + z*z + w*w); +}; + +/** + * Alias for {@link vec4.distance} + * @function + */ +vec4.dist = vec4.distance; + +/** + * Calculates the squared euclidian distance between two vec4's + * + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {Number} squared distance between a and b + */ +vec4.squaredDistance = function(a, b) { + var x = b[0] - a[0], + y = b[1] - a[1], + z = b[2] - a[2], + w = b[3] - a[3]; + return x*x + y*y + z*z + w*w; +}; + +/** + * Alias for {@link vec4.squaredDistance} + * @function + */ +vec4.sqrDist = vec4.squaredDistance; + +/** + * Calculates the length of a vec4 + * + * @param {vec4} a vector to calculate length of + * @returns {Number} length of a + */ +vec4.length = function (a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + return Math.sqrt(x*x + y*y + z*z + w*w); +}; + +/** + * Alias for {@link vec4.length} + * @function + */ +vec4.len = vec4.length; + +/** + * Calculates the squared length of a vec4 + * + * @param {vec4} a vector to calculate squared length of + * @returns {Number} squared length of a + */ +vec4.squaredLength = function (a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + return x*x + y*y + z*z + w*w; +}; + +/** + * Alias for {@link vec4.squaredLength} + * @function + */ +vec4.sqrLen = vec4.squaredLength; + +/** + * Negates the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to negate + * @returns {vec4} out + */ +vec4.negate = function(out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = -a[3]; + return out; +}; + +/** + * Returns the inverse of the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to invert + * @returns {vec4} out + */ +vec4.inverse = function(out, a) { + out[0] = 1.0 / a[0]; + out[1] = 1.0 / a[1]; + out[2] = 1.0 / a[2]; + out[3] = 1.0 / a[3]; + return out; +}; + +/** + * Normalize a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to normalize + * @returns {vec4} out + */ +vec4.normalize = function(out, a) { + var x = a[0], + y = a[1], + z = a[2], + w = a[3]; + var len = x*x + y*y + z*z + w*w; + if (len > 0) { + len = 1 / Math.sqrt(len); + out[0] = a[0] * len; + out[1] = a[1] * len; + out[2] = a[2] * len; + out[3] = a[3] * len; + } + return out; +}; + +/** + * Calculates the dot product of two vec4's + * + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @returns {Number} dot product of a and b + */ +vec4.dot = function (a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; +}; + +/** + * Performs a linear interpolation between two vec4's + * + * @param {vec4} out the receiving vector + * @param {vec4} a the first operand + * @param {vec4} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {vec4} out + */ +vec4.lerp = function (out, a, b, t) { + var ax = a[0], + ay = a[1], + az = a[2], + aw = a[3]; + out[0] = ax + t * (b[0] - ax); + out[1] = ay + t * (b[1] - ay); + out[2] = az + t * (b[2] - az); + out[3] = aw + t * (b[3] - aw); + return out; +}; + +/** + * Generates a random vector with the given scale + * + * @param {vec4} out the receiving vector + * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns {vec4} out + */ +vec4.random = function (out, scale) { + scale = scale || 1.0; + + //TODO: This is a pretty awful way of doing this. Find something better. + out[0] = GLMAT_RANDOM(); + out[1] = GLMAT_RANDOM(); + out[2] = GLMAT_RANDOM(); + out[3] = GLMAT_RANDOM(); + vec4.normalize(out, out); + vec4.scale(out, out, scale); + return out; +}; + +/** + * Transforms the vec4 with a mat4. + * + * @param {vec4} out the receiving vector + * @param {vec4} a the vector to transform + * @param {mat4} m matrix to transform with + * @returns {vec4} out + */ +vec4.transformMat4 = function(out, a, m) { + var x = a[0], y = a[1], z = a[2], w = a[3]; + out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; + out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; + out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; + out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; + return out; +}; + +/** + * Transforms the vec4 with a quat + * + * @param {vec4} out the receiving vector + * @param {vec4} a the vector to transform + * @param {quat} q quaternion to transform with + * @returns {vec4} out + */ +vec4.transformQuat = function(out, a, q) { + var x = a[0], y = a[1], z = a[2], + qx = q[0], qy = q[1], qz = q[2], qw = q[3], + + // calculate quat * vec + ix = qw * x + qy * z - qz * y, + iy = qw * y + qz * x - qx * z, + iz = qw * z + qx * y - qy * x, + iw = -qx * x - qy * y - qz * z; + + // calculate result * inverse quat + out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy; + out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz; + out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx; + return out; +}; + +/** + * Perform some operation over an array of vec4s. + * + * @param {Array} a the array of vectors to iterate over + * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param {Number} offset Number of elements to skip at the beginning of the array + * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array + * @param {Function} fn Function to call for each vector in the array + * @param {Object} [arg] additional argument to pass to fn + * @returns {Array} a + * @function + */ +vec4.forEach = (function() { + var vec = vec4.create(); + + return function(a, stride, offset, count, fn, arg) { + var i, l; + if(!stride) { + stride = 4; + } + + if(!offset) { + offset = 0; + } + + if(count) { + l = Math.min((count * stride) + offset, a.length); + } else { + l = a.length; + } + + for(i = offset; i < l; i += stride) { + vec[0] = a[i]; vec[1] = a[i+1]; vec[2] = a[i+2]; vec[3] = a[i+3]; + fn(vec, vec, arg); + a[i] = vec[0]; a[i+1] = vec[1]; a[i+2] = vec[2]; a[i+3] = vec[3]; + } + + return a; + }; +})(); + +/** + * Returns a string representation of a vector + * + * @param {vec4} vec vector to represent as a string + * @returns {String} string representation of the vector + */ +vec4.str = function (a) { + return 'vec4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')'; +}; + +if(typeof(exports) !== 'undefined') { + exports.vec4 = vec4; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 2x2 Matrix + * @name mat2 + */ + +var mat2 = {}; + +/** + * Creates a new identity mat2 + * + * @returns {mat2} a new 2x2 matrix + */ +mat2.create = function() { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +}; + +/** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param {mat2} a matrix to clone + * @returns {mat2} a new 2x2 matrix + */ +mat2.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +}; + +/** + * Copy the values from one mat2 to another + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + return out; +}; + +/** + * Set a mat2 to the identity matrix + * + * @param {mat2} out the receiving matrix + * @returns {mat2} out + */ +mat2.identity = function(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +}; + +/** + * Transpose the values of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.transpose = function(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a1 = a[1]; + out[1] = a[2]; + out[2] = a1; + } else { + out[0] = a[0]; + out[1] = a[2]; + out[2] = a[1]; + out[3] = a[3]; + } + + return out; +}; + +/** + * Inverts a mat2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.invert = function(out, a) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], + + // Calculate the determinant + det = a0 * a3 - a2 * a1; + + if (!det) { + return null; + } + det = 1.0 / det; + + out[0] = a3 * det; + out[1] = -a1 * det; + out[2] = -a2 * det; + out[3] = a0 * det; + + return out; +}; + +/** + * Calculates the adjugate of a mat2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the source matrix + * @returns {mat2} out + */ +mat2.adjoint = function(out, a) { + // Caching this value is nessecary if out == a + var a0 = a[0]; + out[0] = a[3]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a0; + + return out; +}; + +/** + * Calculates the determinant of a mat2 + * + * @param {mat2} a the source matrix + * @returns {Number} determinant of a + */ +mat2.determinant = function (a) { + return a[0] * a[3] - a[2] * a[1]; +}; + +/** + * Multiplies two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ +mat2.multiply = function (out, a, b) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3]; + var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; + out[0] = a0 * b0 + a2 * b1; + out[1] = a1 * b0 + a3 * b1; + out[2] = a0 * b2 + a2 * b3; + out[3] = a1 * b2 + a3 * b3; + return out; +}; + +/** + * Alias for {@link mat2.multiply} + * @function + */ +mat2.mul = mat2.multiply; + +/** + * Rotates a mat2 by the given angle + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ +mat2.rotate = function (out, a, rad) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], + s = Math.sin(rad), + c = Math.cos(rad); + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; + out[2] = a0 * -s + a2 * c; + out[3] = a1 * -s + a3 * c; + return out; +}; + +/** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to rotate + * @param {vec2} v the vec2 to scale the matrix by + * @returns {mat2} out + **/ +mat2.scale = function(out, a, v) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], + v0 = v[0], v1 = v[1]; + out[0] = a0 * v0; + out[1] = a1 * v0; + out[2] = a2 * v1; + out[3] = a3 * v1; + return out; +}; + +/** + * Returns a string representation of a mat2 + * + * @param {mat2} mat matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat2.str = function (a) { + return 'mat2(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')'; +}; + +/** + * Returns Frobenius norm of a mat2 + * + * @param {mat2} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat2.frob = function (a) { + return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2))) +}; + +/** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param {mat2} L the lower triangular matrix + * @param {mat2} D the diagonal matrix + * @param {mat2} U the upper triangular matrix + * @param {mat2} a the input matrix to factorize + */ + +mat2.LDU = function (L, D, U, a) { + L[2] = a[2]/a[0]; + U[0] = a[0]; + U[1] = a[1]; + U[3] = a[3] - L[2] * U[1]; + return [L, D, U]; +}; + +if(typeof(exports) !== 'undefined') { + exports.mat2 = mat2; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 2x3 Matrix + * @name mat2d + * + * @description + * A mat2d contains six elements defined as: + *
+ * [a, c, tx,
+ *  b, d, ty]
+ * 
+ * This is a short form for the 3x3 matrix: + *
+ * [a, c, tx,
+ *  b, d, ty,
+ *  0, 0, 1]
+ * 
+ * The last row is ignored so the array is shorter and operations are faster. + */ + +var mat2d = {}; + +/** + * Creates a new identity mat2d + * + * @returns {mat2d} a new 2x3 matrix + */ +mat2d.create = function() { + var out = new GLMAT_ARRAY_TYPE(6); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = 0; + out[5] = 0; + return out; +}; + +/** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param {mat2d} a matrix to clone + * @returns {mat2d} a new 2x3 matrix + */ +mat2d.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(6); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + return out; +}; + +/** + * Copy the values from one mat2d to another + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the source matrix + * @returns {mat2d} out + */ +mat2d.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + return out; +}; + +/** + * Set a mat2d to the identity matrix + * + * @param {mat2d} out the receiving matrix + * @returns {mat2d} out + */ +mat2d.identity = function(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 1; + out[4] = 0; + out[5] = 0; + return out; +}; + +/** + * Inverts a mat2d + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the source matrix + * @returns {mat2d} out + */ +mat2d.invert = function(out, a) { + var aa = a[0], ab = a[1], ac = a[2], ad = a[3], + atx = a[4], aty = a[5]; + + var det = aa * ad - ab * ac; + if(!det){ + return null; + } + det = 1.0 / det; + + out[0] = ad * det; + out[1] = -ab * det; + out[2] = -ac * det; + out[3] = aa * det; + out[4] = (ac * aty - ad * atx) * det; + out[5] = (ab * atx - aa * aty) * det; + return out; +}; + +/** + * Calculates the determinant of a mat2d + * + * @param {mat2d} a the source matrix + * @returns {Number} determinant of a + */ +mat2d.determinant = function (a) { + return a[0] * a[3] - a[1] * a[2]; +}; + +/** + * Multiplies two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ +mat2d.multiply = function (out, a, b) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], + b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5]; + out[0] = a0 * b0 + a2 * b1; + out[1] = a1 * b0 + a3 * b1; + out[2] = a0 * b2 + a2 * b3; + out[3] = a1 * b2 + a3 * b3; + out[4] = a0 * b4 + a2 * b5 + a4; + out[5] = a1 * b4 + a3 * b5 + a5; + return out; +}; + +/** + * Alias for {@link mat2d.multiply} + * @function + */ +mat2d.mul = mat2d.multiply; + + +/** + * Rotates a mat2d by the given angle + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ +mat2d.rotate = function (out, a, rad) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], + s = Math.sin(rad), + c = Math.cos(rad); + out[0] = a0 * c + a2 * s; + out[1] = a1 * c + a3 * s; + out[2] = a0 * -s + a2 * c; + out[3] = a1 * -s + a3 * c; + out[4] = a4; + out[5] = a5; + return out; +}; + +/** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to translate + * @param {vec2} v the vec2 to scale the matrix by + * @returns {mat2d} out + **/ +mat2d.scale = function(out, a, v) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], + v0 = v[0], v1 = v[1]; + out[0] = a0 * v0; + out[1] = a1 * v0; + out[2] = a2 * v1; + out[3] = a3 * v1; + out[4] = a4; + out[5] = a5; + return out; +}; + +/** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to translate + * @param {vec2} v the vec2 to translate the matrix by + * @returns {mat2d} out + **/ +mat2d.translate = function(out, a, v) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], + v0 = v[0], v1 = v[1]; + out[0] = a0; + out[1] = a1; + out[2] = a2; + out[3] = a3; + out[4] = a0 * v0 + a2 * v1 + a4; + out[5] = a1 * v0 + a3 * v1 + a5; + return out; +}; + +/** + * Returns a string representation of a mat2d + * + * @param {mat2d} a matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat2d.str = function (a) { + return 'mat2d(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + + a[3] + ', ' + a[4] + ', ' + a[5] + ')'; +}; + +/** + * Returns Frobenius norm of a mat2d + * + * @param {mat2d} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat2d.frob = function (a) { + return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + 1)) +}; + +if(typeof(exports) !== 'undefined') { + exports.mat2d = mat2d; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 3x3 Matrix + * @name mat3 + */ + +var mat3 = {}; + +/** + * Creates a new identity mat3 + * + * @returns {mat3} a new 3x3 matrix + */ +mat3.create = function() { + var out = new GLMAT_ARRAY_TYPE(9); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +}; + +/** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {mat4} a the source 4x4 matrix + * @returns {mat3} out + */ +mat3.fromMat4 = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[4]; + out[4] = a[5]; + out[5] = a[6]; + out[6] = a[8]; + out[7] = a[9]; + out[8] = a[10]; + return out; +}; + +/** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param {mat3} a matrix to clone + * @returns {mat3} a new 3x3 matrix + */ +mat3.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(9); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +}; + +/** + * Copy the values from one mat3 to another + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +}; + +/** + * Set a mat3 to the identity matrix + * + * @param {mat3} out the receiving matrix + * @returns {mat3} out + */ +mat3.identity = function(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 1; + out[5] = 0; + out[6] = 0; + out[7] = 0; + out[8] = 1; + return out; +}; + +/** + * Transpose the values of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.transpose = function(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], a02 = a[2], a12 = a[5]; + out[1] = a[3]; + out[2] = a[6]; + out[3] = a01; + out[5] = a[7]; + out[6] = a02; + out[7] = a12; + } else { + out[0] = a[0]; + out[1] = a[3]; + out[2] = a[6]; + out[3] = a[1]; + out[4] = a[4]; + out[5] = a[7]; + out[6] = a[2]; + out[7] = a[5]; + out[8] = a[8]; + } + + return out; +}; + +/** + * Inverts a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.invert = function(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8], + + b01 = a22 * a11 - a12 * a21, + b11 = -a22 * a10 + a12 * a20, + b21 = a21 * a10 - a11 * a20, + + // Calculate the determinant + det = a00 * b01 + a01 * b11 + a02 * b21; + + if (!det) { + return null; + } + det = 1.0 / det; + + out[0] = b01 * det; + out[1] = (-a22 * a01 + a02 * a21) * det; + out[2] = (a12 * a01 - a02 * a11) * det; + out[3] = b11 * det; + out[4] = (a22 * a00 - a02 * a20) * det; + out[5] = (-a12 * a00 + a02 * a10) * det; + out[6] = b21 * det; + out[7] = (-a21 * a00 + a01 * a20) * det; + out[8] = (a11 * a00 - a01 * a10) * det; + return out; +}; + +/** + * Calculates the adjugate of a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the source matrix + * @returns {mat3} out + */ +mat3.adjoint = function(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8]; + + out[0] = (a11 * a22 - a12 * a21); + out[1] = (a02 * a21 - a01 * a22); + out[2] = (a01 * a12 - a02 * a11); + out[3] = (a12 * a20 - a10 * a22); + out[4] = (a00 * a22 - a02 * a20); + out[5] = (a02 * a10 - a00 * a12); + out[6] = (a10 * a21 - a11 * a20); + out[7] = (a01 * a20 - a00 * a21); + out[8] = (a00 * a11 - a01 * a10); + return out; +}; + +/** + * Calculates the determinant of a mat3 + * + * @param {mat3} a the source matrix + * @returns {Number} determinant of a + */ +mat3.determinant = function (a) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8]; + + return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); +}; + +/** + * Multiplies two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ +mat3.multiply = function (out, a, b) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8], + + b00 = b[0], b01 = b[1], b02 = b[2], + b10 = b[3], b11 = b[4], b12 = b[5], + b20 = b[6], b21 = b[7], b22 = b[8]; + + out[0] = b00 * a00 + b01 * a10 + b02 * a20; + out[1] = b00 * a01 + b01 * a11 + b02 * a21; + out[2] = b00 * a02 + b01 * a12 + b02 * a22; + + out[3] = b10 * a00 + b11 * a10 + b12 * a20; + out[4] = b10 * a01 + b11 * a11 + b12 * a21; + out[5] = b10 * a02 + b11 * a12 + b12 * a22; + + out[6] = b20 * a00 + b21 * a10 + b22 * a20; + out[7] = b20 * a01 + b21 * a11 + b22 * a21; + out[8] = b20 * a02 + b21 * a12 + b22 * a22; + return out; +}; + +/** + * Alias for {@link mat3.multiply} + * @function + */ +mat3.mul = mat3.multiply; + +/** + * Translate a mat3 by the given vector + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to translate + * @param {vec2} v vector to translate by + * @returns {mat3} out + */ +mat3.translate = function(out, a, v) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8], + x = v[0], y = v[1]; + + out[0] = a00; + out[1] = a01; + out[2] = a02; + + out[3] = a10; + out[4] = a11; + out[5] = a12; + + out[6] = x * a00 + y * a10 + a20; + out[7] = x * a01 + y * a11 + a21; + out[8] = x * a02 + y * a12 + a22; + return out; +}; + +/** + * Rotates a mat3 by the given angle + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ +mat3.rotate = function (out, a, rad) { + var a00 = a[0], a01 = a[1], a02 = a[2], + a10 = a[3], a11 = a[4], a12 = a[5], + a20 = a[6], a21 = a[7], a22 = a[8], + + s = Math.sin(rad), + c = Math.cos(rad); + + out[0] = c * a00 + s * a10; + out[1] = c * a01 + s * a11; + out[2] = c * a02 + s * a12; + + out[3] = c * a10 - s * a00; + out[4] = c * a11 - s * a01; + out[5] = c * a12 - s * a02; + + out[6] = a20; + out[7] = a21; + out[8] = a22; + return out; +}; + +/** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to rotate + * @param {vec2} v the vec2 to scale the matrix by + * @returns {mat3} out + **/ +mat3.scale = function(out, a, v) { + var x = v[0], y = v[1]; + + out[0] = x * a[0]; + out[1] = x * a[1]; + out[2] = x * a[2]; + + out[3] = y * a[3]; + out[4] = y * a[4]; + out[5] = y * a[5]; + + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + return out; +}; + +/** + * Copies the values from a mat2d into a mat3 + * + * @param {mat3} out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns {mat3} out + **/ +mat3.fromMat2d = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = 0; + + out[3] = a[2]; + out[4] = a[3]; + out[5] = 0; + + out[6] = a[4]; + out[7] = a[5]; + out[8] = 1; + return out; +}; + +/** +* Calculates a 3x3 matrix from the given quaternion +* +* @param {mat3} out mat3 receiving operation result +* @param {quat} q Quaternion to create matrix from +* +* @returns {mat3} out +*/ +mat3.fromQuat = function (out, q) { + var x = q[0], y = q[1], z = q[2], w = q[3], + x2 = x + x, + y2 = y + y, + z2 = z + z, + + xx = x * x2, + yx = y * x2, + yy = y * y2, + zx = z * x2, + zy = z * y2, + zz = z * z2, + wx = w * x2, + wy = w * y2, + wz = w * z2; + + out[0] = 1 - yy - zz; + out[3] = yx - wz; + out[6] = zx + wy; + + out[1] = yx + wz; + out[4] = 1 - xx - zz; + out[7] = zy - wx; + + out[2] = zx - wy; + out[5] = zy + wx; + out[8] = 1 - xx - yy; + + return out; +}; + +/** +* Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix +* +* @param {mat3} out mat3 receiving operation result +* @param {mat4} a Mat4 to derive the normal matrix from +* +* @returns {mat3} out +*/ +mat3.normalFromMat4 = function (out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], + + b00 = a00 * a11 - a01 * a10, + b01 = a00 * a12 - a02 * a10, + b02 = a00 * a13 - a03 * a10, + b03 = a01 * a12 - a02 * a11, + b04 = a01 * a13 - a03 * a11, + b05 = a02 * a13 - a03 * a12, + b06 = a20 * a31 - a21 * a30, + b07 = a20 * a32 - a22 * a30, + b08 = a20 * a33 - a23 * a30, + b09 = a21 * a32 - a22 * a31, + b10 = a21 * a33 - a23 * a31, + b11 = a22 * a33 - a23 * a32, + + // Calculate the determinant + det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + det = 1.0 / det; + + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + + out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + + out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + + return out; +}; + +/** + * Returns a string representation of a mat3 + * + * @param {mat3} mat matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat3.str = function (a) { + return 'mat3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + + a[6] + ', ' + a[7] + ', ' + a[8] + ')'; +}; + +/** + * Returns Frobenius norm of a mat3 + * + * @param {mat3} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat3.frob = function (a) { + return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + Math.pow(a[6], 2) + Math.pow(a[7], 2) + Math.pow(a[8], 2))) +}; + + +if(typeof(exports) !== 'undefined') { + exports.mat3 = mat3; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class 4x4 Matrix + * @name mat4 + */ + +var mat4 = {}; + +/** + * Creates a new identity mat4 + * + * @returns {mat4} a new 4x4 matrix + */ +mat4.create = function() { + var out = new GLMAT_ARRAY_TYPE(16); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +}; + +/** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param {mat4} a matrix to clone + * @returns {mat4} a new 4x4 matrix + */ +mat4.clone = function(a) { + var out = new GLMAT_ARRAY_TYPE(16); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +}; + +/** + * Copy the values from one mat4 to another + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.copy = function(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +}; + +/** + * Set a mat4 to the identity matrix + * + * @param {mat4} out the receiving matrix + * @returns {mat4} out + */ +mat4.identity = function(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +}; + +/** + * Transpose the values of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.transpose = function(out, a) { + // If we are transposing ourselves we can skip a few steps but have to cache some values + if (out === a) { + var a01 = a[1], a02 = a[2], a03 = a[3], + a12 = a[6], a13 = a[7], + a23 = a[11]; + + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a01; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a02; + out[9] = a12; + out[11] = a[14]; + out[12] = a03; + out[13] = a13; + out[14] = a23; + } else { + out[0] = a[0]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a[1]; + out[5] = a[5]; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a[2]; + out[9] = a[6]; + out[10] = a[10]; + out[11] = a[14]; + out[12] = a[3]; + out[13] = a[7]; + out[14] = a[11]; + out[15] = a[15]; + } + + return out; +}; + +/** + * Inverts a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.invert = function(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], + + b00 = a00 * a11 - a01 * a10, + b01 = a00 * a12 - a02 * a10, + b02 = a00 * a13 - a03 * a10, + b03 = a01 * a12 - a02 * a11, + b04 = a01 * a13 - a03 * a11, + b05 = a02 * a13 - a03 * a12, + b06 = a20 * a31 - a21 * a30, + b07 = a20 * a32 - a22 * a30, + b08 = a20 * a33 - a23 * a30, + b09 = a21 * a32 - a22 * a31, + b10 = a21 * a33 - a23 * a31, + b11 = a22 * a33 - a23 * a32, + + // Calculate the determinant + det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) { + return null; + } + det = 1.0 / det; + + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + + return out; +}; + +/** + * Calculates the adjugate of a mat4 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the source matrix + * @returns {mat4} out + */ +mat4.adjoint = function(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; + + out[0] = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22)); + out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); + out[2] = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12)); + out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); + out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); + out[5] = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22)); + out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); + out[7] = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12)); + out[8] = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21)); + out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); + out[10] = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11)); + out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); + out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); + out[13] = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21)); + out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); + out[15] = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11)); + return out; +}; + +/** + * Calculates the determinant of a mat4 + * + * @param {mat4} a the source matrix + * @returns {Number} determinant of a + */ +mat4.determinant = function (a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], + + b00 = a00 * a11 - a01 * a10, + b01 = a00 * a12 - a02 * a10, + b02 = a00 * a13 - a03 * a10, + b03 = a01 * a12 - a02 * a11, + b04 = a01 * a13 - a03 * a11, + b05 = a02 * a13 - a03 * a12, + b06 = a20 * a31 - a21 * a30, + b07 = a20 * a32 - a22 * a30, + b08 = a20 * a33 - a23 * a30, + b09 = a21 * a32 - a22 * a31, + b10 = a21 * a33 - a23 * a31, + b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; +}; + +/** + * Multiplies two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ +mat4.multiply = function (out, a, b) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], + a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], + a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], + a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; + + // Cache only the current line of the second matrix + var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; + out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + + b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; + out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + + b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; + out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + + b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; + out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30; + out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31; + out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32; + out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; + return out; +}; + +/** + * Alias for {@link mat4.multiply} + * @function + */ +mat4.mul = mat4.multiply; + +/** + * Translate a mat4 by the given vector + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to translate + * @param {vec3} v vector to translate by + * @returns {mat4} out + */ +mat4.translate = function (out, a, v) { + var x = v[0], y = v[1], z = v[2], + a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23; + + if (a === out) { + out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + } else { + a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; + a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; + a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; + + out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03; + out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13; + out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23; + + out[12] = a00 * x + a10 * y + a20 * z + a[12]; + out[13] = a01 * x + a11 * y + a21 * z + a[13]; + out[14] = a02 * x + a12 * y + a22 * z + a[14]; + out[15] = a03 * x + a13 * y + a23 * z + a[15]; + } + + return out; +}; + +/** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {vec3} v the vec3 to scale the matrix by + * @returns {mat4} out + **/ +mat4.scale = function(out, a, v) { + var x = v[0], y = v[1], z = v[2]; + + out[0] = a[0] * x; + out[1] = a[1] * x; + out[2] = a[2] * x; + out[3] = a[3] * x; + out[4] = a[4] * y; + out[5] = a[5] * y; + out[6] = a[6] * y; + out[7] = a[7] * y; + out[8] = a[8] * z; + out[9] = a[9] * z; + out[10] = a[10] * z; + out[11] = a[11] * z; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +}; + +/** + * Rotates a mat4 by the given angle + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out + */ +mat4.rotate = function (out, a, rad, axis) { + var x = axis[0], y = axis[1], z = axis[2], + len = Math.sqrt(x * x + y * y + z * z), + s, c, t, + a00, a01, a02, a03, + a10, a11, a12, a13, + a20, a21, a22, a23, + b00, b01, b02, + b10, b11, b12, + b20, b21, b22; + + if (Math.abs(len) < GLMAT_EPSILON) { return null; } + + len = 1 / len; + x *= len; + y *= len; + z *= len; + + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; + + a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; + a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; + a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; + + // Construct the elements of the rotation matrix + b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s; + b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s; + b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c; + + // Perform rotation-specific matrix multiplication + out[0] = a00 * b00 + a10 * b01 + a20 * b02; + out[1] = a01 * b00 + a11 * b01 + a21 * b02; + out[2] = a02 * b00 + a12 * b01 + a22 * b02; + out[3] = a03 * b00 + a13 * b01 + a23 * b02; + out[4] = a00 * b10 + a10 * b11 + a20 * b12; + out[5] = a01 * b10 + a11 * b11 + a21 * b12; + out[6] = a02 * b10 + a12 * b11 + a22 * b12; + out[7] = a03 * b10 + a13 * b11 + a23 * b12; + out[8] = a00 * b20 + a10 * b21 + a20 * b22; + out[9] = a01 * b20 + a11 * b21 + a21 * b22; + out[10] = a02 * b20 + a12 * b21 + a22 * b22; + out[11] = a03 * b20 + a13 * b21 + a23 * b22; + + if (a !== out) { // If the source and destination differ, copy the unchanged last row + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + return out; +}; + +/** + * Rotates a matrix by the given angle around the X axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.rotateX = function (out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7], + a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + + if (a !== out) { // If the source and destination differ, copy the unchanged rows + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + + // Perform axis-specific matrix multiplication + out[4] = a10 * c + a20 * s; + out[5] = a11 * c + a21 * s; + out[6] = a12 * c + a22 * s; + out[7] = a13 * c + a23 * s; + out[8] = a20 * c - a10 * s; + out[9] = a21 * c - a11 * s; + out[10] = a22 * c - a12 * s; + out[11] = a23 * c - a13 * s; + return out; +}; + +/** + * Rotates a matrix by the given angle around the Y axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.rotateY = function (out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3], + a20 = a[8], + a21 = a[9], + a22 = a[10], + a23 = a[11]; + + if (a !== out) { // If the source and destination differ, copy the unchanged rows + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + + // Perform axis-specific matrix multiplication + out[0] = a00 * c - a20 * s; + out[1] = a01 * c - a21 * s; + out[2] = a02 * c - a22 * s; + out[3] = a03 * c - a23 * s; + out[8] = a00 * s + a20 * c; + out[9] = a01 * s + a21 * c; + out[10] = a02 * s + a22 * c; + out[11] = a03 * s + a23 * c; + return out; +}; + +/** + * Rotates a matrix by the given angle around the Z axis + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to rotate + * @param {Number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ +mat4.rotateZ = function (out, a, rad) { + var s = Math.sin(rad), + c = Math.cos(rad), + a00 = a[0], + a01 = a[1], + a02 = a[2], + a03 = a[3], + a10 = a[4], + a11 = a[5], + a12 = a[6], + a13 = a[7]; + + if (a !== out) { // If the source and destination differ, copy the unchanged last row + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + + // Perform axis-specific matrix multiplication + out[0] = a00 * c + a10 * s; + out[1] = a01 * c + a11 * s; + out[2] = a02 * c + a12 * s; + out[3] = a03 * c + a13 * s; + out[4] = a10 * c - a00 * s; + out[5] = a11 * c - a01 * s; + out[6] = a12 * c - a02 * s; + out[7] = a13 * c - a03 * s; + return out; +}; + +/** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat4} q Rotation quaternion + * @param {vec3} v Translation vector + * @returns {mat4} out + */ +mat4.fromRotationTranslation = function (out, q, v) { + // Quaternion math + var x = q[0], y = q[1], z = q[2], w = q[3], + x2 = x + x, + y2 = y + y, + z2 = z + z, + + xx = x * x2, + xy = x * y2, + xz = x * z2, + yy = y * y2, + yz = y * z2, + zz = z * z2, + wx = w * x2, + wy = w * y2, + wz = w * z2; + + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + + return out; +}; + +mat4.fromQuat = function (out, q) { + var x = q[0], y = q[1], z = q[2], w = q[3], + x2 = x + x, + y2 = y + y, + z2 = z + z, + + xx = x * x2, + yx = y * x2, + yy = y * y2, + zx = z * x2, + zy = z * y2, + zz = z * z2, + wx = w * x2, + wy = w * y2, + wz = w * z2; + + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; + + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; + + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; + + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + + return out; +}; + +/** + * Generates a frustum matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Number} left Left bound of the frustum + * @param {Number} right Right bound of the frustum + * @param {Number} bottom Bottom bound of the frustum + * @param {Number} top Top bound of the frustum + * @param {Number} near Near bound of the frustum + * @param {Number} far Far bound of the frustum + * @returns {mat4} out + */ +mat4.frustum = function (out, left, right, bottom, top, near, far) { + var rl = 1 / (right - left), + tb = 1 / (top - bottom), + nf = 1 / (near - far); + out[0] = (near * 2) * rl; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = (near * 2) * tb; + out[6] = 0; + out[7] = 0; + out[8] = (right + left) * rl; + out[9] = (top + bottom) * tb; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = (far * near * 2) * nf; + out[15] = 0; + return out; +}; + +/** + * Generates a perspective projection matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} fovy Vertical field of view in radians + * @param {number} aspect Aspect ratio. typically viewport width/height + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ +mat4.perspective = function (out, fovy, aspect, near, far) { + var f = 1.0 / Math.tan(fovy / 2), + nf = 1 / (near - far); + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = (2 * far * near) * nf; + out[15] = 0; + return out; +}; + +/** + * Generates a orthogonal projection matrix with the given bounds + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {number} left Left bound of the frustum + * @param {number} right Right bound of the frustum + * @param {number} bottom Bottom bound of the frustum + * @param {number} top Top bound of the frustum + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ +mat4.ortho = function (out, left, right, bottom, top, near, far) { + var lr = 1 / (left - right), + bt = 1 / (bottom - top), + nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 2 * nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = (far + near) * nf; + out[15] = 1; + return out; +}; + +/** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {vec3} eye Position of the viewer + * @param {vec3} center Point the viewer is looking at + * @param {vec3} up vec3 pointing up + * @returns {mat4} out + */ +mat4.lookAt = function (out, eye, center, up) { + var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, + eyex = eye[0], + eyey = eye[1], + eyez = eye[2], + upx = up[0], + upy = up[1], + upz = up[2], + centerx = center[0], + centery = center[1], + centerz = center[2]; + + if (Math.abs(eyex - centerx) < GLMAT_EPSILON && + Math.abs(eyey - centery) < GLMAT_EPSILON && + Math.abs(eyez - centerz) < GLMAT_EPSILON) { + return mat4.identity(out); + } + + z0 = eyex - centerx; + z1 = eyey - centery; + z2 = eyez - centerz; + + len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + z0 *= len; + z1 *= len; + z2 *= len; + + x0 = upy * z2 - upz * z1; + x1 = upz * z0 - upx * z2; + x2 = upx * z1 - upy * z0; + len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + if (!len) { + x0 = 0; + x1 = 0; + x2 = 0; + } else { + len = 1 / len; + x0 *= len; + x1 *= len; + x2 *= len; + } + + y0 = z1 * x2 - z2 * x1; + y1 = z2 * x0 - z0 * x2; + y2 = z0 * x1 - z1 * x0; + + len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + if (!len) { + y0 = 0; + y1 = 0; + y2 = 0; + } else { + len = 1 / len; + y0 *= len; + y1 *= len; + y2 *= len; + } + + out[0] = x0; + out[1] = y0; + out[2] = z0; + out[3] = 0; + out[4] = x1; + out[5] = y1; + out[6] = z1; + out[7] = 0; + out[8] = x2; + out[9] = y2; + out[10] = z2; + out[11] = 0; + out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); + out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); + out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); + out[15] = 1; + + return out; +}; + +/** + * Returns a string representation of a mat4 + * + * @param {mat4} mat matrix to represent as a string + * @returns {String} string representation of the matrix + */ +mat4.str = function (a) { + return 'mat4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' + + a[8] + ', ' + a[9] + ', ' + a[10] + ', ' + a[11] + ', ' + + a[12] + ', ' + a[13] + ', ' + a[14] + ', ' + a[15] + ')'; +}; + +/** + * Returns Frobenius norm of a mat4 + * + * @param {mat4} a the matrix to calculate Frobenius norm of + * @returns {Number} Frobenius norm + */ +mat4.frob = function (a) { + return(Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + Math.pow(a[6], 2) + Math.pow(a[7], 2) + Math.pow(a[8], 2) + Math.pow(a[9], 2) + Math.pow(a[10], 2) + Math.pow(a[11], 2) + Math.pow(a[12], 2) + Math.pow(a[13], 2) + Math.pow(a[14], 2) + Math.pow(a[15], 2) )) +}; + + +if(typeof(exports) !== 'undefined') { + exports.mat4 = mat4; +} +; +/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + +/** + * @class Quaternion + * @name quat + */ + +var quat = {}; + +/** + * Creates a new identity quat + * + * @returns {quat} a new quaternion + */ +quat.create = function() { + var out = new GLMAT_ARRAY_TYPE(4); + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +}; + +/** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {vec3} a the initial vector + * @param {vec3} b the destination vector + * @returns {quat} out + */ +quat.rotationTo = (function() { + var tmpvec3 = vec3.create(); + var xUnitVec3 = vec3.fromValues(1,0,0); + var yUnitVec3 = vec3.fromValues(0,1,0); + + return function(out, a, b) { + var dot = vec3.dot(a, b); + if (dot < -0.999999) { + vec3.cross(tmpvec3, xUnitVec3, a); + if (vec3.length(tmpvec3) < 0.000001) + vec3.cross(tmpvec3, yUnitVec3, a); + vec3.normalize(tmpvec3, tmpvec3); + quat.setAxisAngle(out, tmpvec3, Math.PI); + return out; + } else if (dot > 0.999999) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; + } else { + vec3.cross(tmpvec3, a, b); + out[0] = tmpvec3[0]; + out[1] = tmpvec3[1]; + out[2] = tmpvec3[2]; + out[3] = 1 + dot; + return quat.normalize(out, out); + } + }; +})(); + +/** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ +quat.setAxes = (function() { + var matr = mat3.create(); + + return function(out, view, right, up) { + matr[0] = right[0]; + matr[3] = right[1]; + matr[6] = right[2]; + + matr[1] = up[0]; + matr[4] = up[1]; + matr[7] = up[2]; + + matr[2] = -view[0]; + matr[5] = -view[1]; + matr[8] = -view[2]; + + return quat.normalize(out, quat.fromMat3(out, matr)); + }; +})(); + +/** + * Creates a new quat initialized with values from an existing quaternion + * + * @param {quat} a quaternion to clone + * @returns {quat} a new quaternion + * @function + */ +quat.clone = vec4.clone; + +/** + * Creates a new quat initialized with the given values + * + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} a new quaternion + * @function + */ +quat.fromValues = vec4.fromValues; + +/** + * Copy the values from one quat to another + * + * @param {quat} out the receiving quaternion + * @param {quat} a the source quaternion + * @returns {quat} out + * @function + */ +quat.copy = vec4.copy; + +/** + * Set the components of a quat to the given values + * + * @param {quat} out the receiving quaternion + * @param {Number} x X component + * @param {Number} y Y component + * @param {Number} z Z component + * @param {Number} w W component + * @returns {quat} out + * @function + */ +quat.set = vec4.set; + +/** + * Set a quat to the identity quaternion + * + * @param {quat} out the receiving quaternion + * @returns {quat} out + */ +quat.identity = function(out) { + out[0] = 0; + out[1] = 0; + out[2] = 0; + out[3] = 1; + return out; +}; + +/** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param {quat} out the receiving quaternion + * @param {vec3} axis the axis around which to rotate + * @param {Number} rad the angle in radians + * @returns {quat} out + **/ +quat.setAxisAngle = function(out, axis, rad) { + rad = rad * 0.5; + var s = Math.sin(rad); + out[0] = s * axis[0]; + out[1] = s * axis[1]; + out[2] = s * axis[2]; + out[3] = Math.cos(rad); + return out; +}; + +/** + * Adds two quat's + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @returns {quat} out + * @function + */ +quat.add = vec4.add; + +/** + * Multiplies two quat's + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @returns {quat} out + */ +quat.multiply = function(out, a, b) { + var ax = a[0], ay = a[1], az = a[2], aw = a[3], + bx = b[0], by = b[1], bz = b[2], bw = b[3]; + + out[0] = ax * bw + aw * bx + ay * bz - az * by; + out[1] = ay * bw + aw * by + az * bx - ax * bz; + out[2] = az * bw + aw * bz + ax * by - ay * bx; + out[3] = aw * bw - ax * bx - ay * by - az * bz; + return out; +}; + +/** + * Alias for {@link quat.multiply} + * @function + */ +quat.mul = quat.multiply; + +/** + * Scales a quat by a scalar number + * + * @param {quat} out the receiving vector + * @param {quat} a the vector to scale + * @param {Number} b amount to scale the vector by + * @returns {quat} out + * @function + */ +quat.scale = vec4.scale; + +/** + * Rotates a quaternion by the given angle about the X axis + * + * @param {quat} out quat receiving operation result + * @param {quat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ +quat.rotateX = function (out, a, rad) { + rad *= 0.5; + + var ax = a[0], ay = a[1], az = a[2], aw = a[3], + bx = Math.sin(rad), bw = Math.cos(rad); + + out[0] = ax * bw + aw * bx; + out[1] = ay * bw + az * bx; + out[2] = az * bw - ay * bx; + out[3] = aw * bw - ax * bx; + return out; +}; + +/** + * Rotates a quaternion by the given angle about the Y axis + * + * @param {quat} out quat receiving operation result + * @param {quat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ +quat.rotateY = function (out, a, rad) { + rad *= 0.5; + + var ax = a[0], ay = a[1], az = a[2], aw = a[3], + by = Math.sin(rad), bw = Math.cos(rad); + + out[0] = ax * bw - az * by; + out[1] = ay * bw + aw * by; + out[2] = az * bw + ax * by; + out[3] = aw * bw - ay * by; + return out; +}; + +/** + * Rotates a quaternion by the given angle about the Z axis + * + * @param {quat} out quat receiving operation result + * @param {quat} a quat to rotate + * @param {number} rad angle (in radians) to rotate + * @returns {quat} out + */ +quat.rotateZ = function (out, a, rad) { + rad *= 0.5; + + var ax = a[0], ay = a[1], az = a[2], aw = a[3], + bz = Math.sin(rad), bw = Math.cos(rad); + + out[0] = ax * bw + ay * bz; + out[1] = ay * bw - ax * bz; + out[2] = az * bw + aw * bz; + out[3] = aw * bw - az * bz; + return out; +}; + +/** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param {quat} out the receiving quaternion + * @param {quat} a quat to calculate W component of + * @returns {quat} out + */ +quat.calculateW = function (out, a) { + var x = a[0], y = a[1], z = a[2]; + + out[0] = x; + out[1] = y; + out[2] = z; + out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z)); + return out; +}; + +/** + * Calculates the dot product of two quat's + * + * @param {quat} a the first operand + * @param {quat} b the second operand + * @returns {Number} dot product of a and b + * @function + */ +quat.dot = vec4.dot; + +/** + * Performs a linear interpolation between two quat's + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {quat} out + * @function + */ +quat.lerp = vec4.lerp; + +/** + * Performs a spherical linear interpolation between two quat + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {Number} t interpolation amount between the two inputs + * @returns {quat} out + */ +quat.slerp = function (out, a, b, t) { + // benchmarks: + // http://jsperf.com/quaternion-slerp-implementations + + var ax = a[0], ay = a[1], az = a[2], aw = a[3], + bx = b[0], by = b[1], bz = b[2], bw = b[3]; + + var omega, cosom, sinom, scale0, scale1; + + // calc cosine + cosom = ax * bx + ay * by + az * bz + aw * bw; + // adjust signs (if necessary) + if ( cosom < 0.0 ) { + cosom = -cosom; + bx = - bx; + by = - by; + bz = - bz; + bw = - bw; + } + // calculate coefficients + if ( (1.0 - cosom) > 0.000001 ) { + // standard case (slerp) + omega = Math.acos(cosom); + sinom = Math.sin(omega); + scale0 = Math.sin((1.0 - t) * omega) / sinom; + scale1 = Math.sin(t * omega) / sinom; + } else { + // "from" and "to" quaternions are very close + // ... so we can do a linear interpolation + scale0 = 1.0 - t; + scale1 = t; + } + // calculate final values + out[0] = scale0 * ax + scale1 * bx; + out[1] = scale0 * ay + scale1 * by; + out[2] = scale0 * az + scale1 * bz; + out[3] = scale0 * aw + scale1 * bw; + + return out; +}; + +/** + * Calculates the inverse of a quat + * + * @param {quat} out the receiving quaternion + * @param {quat} a quat to calculate inverse of + * @returns {quat} out + */ +quat.invert = function(out, a) { + var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], + dot = a0*a0 + a1*a1 + a2*a2 + a3*a3, + invDot = dot ? 1.0/dot : 0; + + // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 + + out[0] = -a0*invDot; + out[1] = -a1*invDot; + out[2] = -a2*invDot; + out[3] = a3*invDot; + return out; +}; + +/** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param {quat} out the receiving quaternion + * @param {quat} a quat to calculate conjugate of + * @returns {quat} out + */ +quat.conjugate = function (out, a) { + out[0] = -a[0]; + out[1] = -a[1]; + out[2] = -a[2]; + out[3] = a[3]; + return out; +}; + +/** + * Calculates the length of a quat + * + * @param {quat} a vector to calculate length of + * @returns {Number} length of a + * @function + */ +quat.length = vec4.length; + +/** + * Alias for {@link quat.length} + * @function + */ +quat.len = quat.length; + +/** + * Calculates the squared length of a quat + * + * @param {quat} a vector to calculate squared length of + * @returns {Number} squared length of a + * @function + */ +quat.squaredLength = vec4.squaredLength; + +/** + * Alias for {@link quat.squaredLength} + * @function + */ +quat.sqrLen = quat.squaredLength; + +/** + * Normalize a quat + * + * @param {quat} out the receiving quaternion + * @param {quat} a quaternion to normalize + * @returns {quat} out + * @function + */ +quat.normalize = vec4.normalize; + +/** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param {quat} out the receiving quaternion + * @param {mat3} m rotation matrix + * @returns {quat} out + * @function + */ +quat.fromMat3 = function(out, m) { + // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes + // article "Quaternion Calculus and Fast Animation". + var fTrace = m[0] + m[4] + m[8]; + var fRoot; + + if ( fTrace > 0.0 ) { + // |w| > 1/2, may as well choose w > 1/2 + fRoot = Math.sqrt(fTrace + 1.0); // 2w + out[3] = 0.5 * fRoot; + fRoot = 0.5/fRoot; // 1/(4w) + out[0] = (m[5]-m[7])*fRoot; + out[1] = (m[6]-m[2])*fRoot; + out[2] = (m[1]-m[3])*fRoot; + } else { + // |w| <= 1/2 + var i = 0; + if ( m[4] > m[0] ) + i = 1; + if ( m[8] > m[i*3+i] ) + i = 2; + var j = (i+1)%3; + var k = (i+2)%3; + + fRoot = Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k] + 1.0); + out[i] = 0.5 * fRoot; + fRoot = 0.5 / fRoot; + out[3] = (m[j*3+k] - m[k*3+j]) * fRoot; + out[j] = (m[j*3+i] + m[i*3+j]) * fRoot; + out[k] = (m[k*3+i] + m[i*3+k]) * fRoot; + } + + return out; +}; + +/** + * Returns a string representation of a quatenion + * + * @param {quat} vec vector to represent as a string + * @returns {String} string representation of the vector + */ +quat.str = function (a) { + return 'quat(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ')'; +}; + +if(typeof(exports) !== 'undefined') { + exports.quat = quat; +} +; + + + + + + + + + + + + + + })(shim.exports); +})(this); diff --git a/Resource/placeAtlas.png b/Resource/placeAtlas.png new file mode 100644 index 0000000..d845b87 Binary files /dev/null and b/Resource/placeAtlas.png differ diff --git a/Server/config.json b/Server/config.json new file mode 100644 index 0000000..ac916b4 --- /dev/null +++ b/Server/config.json @@ -0,0 +1,52 @@ +{ + "port": 8081, + "instances": 1, + "defaultInstance": { + "mapRotation": [ + "mkdsDefault" + ], + "mapMode": "random", + "itemConfig": [ + { + "item": 0, + "cfg": {} + }, + { + "item": 1, + "cfg": {} + }, + { + "item": 2, + "cfg": {} + } + ], + "itemChance": [ + { + "placement": 0.25, + "choices": [ + { + "item": 0, + "chance": 0.5 + }, + { + "item": 1, + "chance": 0.75 + }, + { + "item": 2, + "chance": 1 + } + ] + }, + { + "placement": 1, + "choices": [ + { + "item": 2, + "chance": 1 + } + ] + } + ] + } +} \ No newline at end of file diff --git a/Server/modules/mkjsInstance Notes.js b/Server/modules/mkjsInstance Notes.js new file mode 100644 index 0000000..e0f8531 --- /dev/null +++ b/Server/modules/mkjsInstance Notes.js @@ -0,0 +1,41 @@ +// instances are basically individual game servers; it is possible to run more than one on the same server. +// the connection to the instance should be the first thing the client sends to the websocket server. the client is then bound to this instance for the duration of the connecton. +// +// normally a race packet exchange goes like this: +// +// C -> S: join instance. submit (kartInitFormat) (as obj.c) minus flags. +// S -> C: send back instance state, type "*". includes mode m (0 = choose course, 1 = race), data d. +// +// data d for race is in format {c:(courseName), k:(kartInitFormat[]), r:(tickRate in 1/60 tick duration increments), i:(itemConfig), p:(your kart, or -1 if in spectator mode)} + +// kartInitFormat: { +// name: (username), +// char: (characterID), //physical character id. +// kart: (kartID), //physical kart id. +// kModel: (kartModelID, undefined normally. if non zero use model sent by server) +// cModel: (charModelID, same as above) +// customKParam: (same format as kartoffsetdata entry. note that custom characters always use the same offset. may be undefined.) +// flags: (info on player, eg if player is an admin, mod, on mobile etc.) +// active: boolean //karts are never deleted - they are just set as inactive after disconnect. the karts list is only completely refreshed on course change or restart. +// } +// +// repeatedly: +// C -> S: send kart data every tick. positions and checkpoint numbers +// S -> C: send array of updated kart data to back to client +// +// item request: +// C -> S: request item packet (hit itembox), type "ri" +// S -> C: return which item to select. type "si", sent to all clients so they know what you have. +// C -> S: when the user is ready to use their item, they will create the item and send a message to the server to create it on all sides. this is of type "ci", and includes the tick the item was fired on. +// S -> C (all others): type "ci" is mirrored to all other clients, server verifies that client has right to send that item first +// ---the item is now on all clients at the correct place--- +// C -> S: when a client gets hit with an item, they send a packet of type "~i" with reason "h" for hit. "~i" is "change item". items that destroy themselves do not need to send this - +// they will annihilate automatically on all clients at the same tick if karts do not interfere. +// +// S -> C: when a spectator connects to a game in progress, they will be sent all item packets in order in an array with type "pi" (packed items). +// +// win: +// C -> S: completed all laps and finished course. type "w", includes finish tick. +// S -> C (all other): "w" mirrored to clients. +// C (all other) -> S: "wa" (win acknowledge) - ping back to server to confirm win. we wait until all clients agree or the timeout on the clients occurs (usually 2s) +// this is to settle win conflicts. \ No newline at end of file diff --git a/Server/modules/mkjsInstance.js b/Server/modules/mkjsInstance.js new file mode 100644 index 0000000..4b2c572 --- /dev/null +++ b/Server/modules/mkjsInstance.js @@ -0,0 +1,169 @@ +function mkjsInstance(config, instanceConfig, wss) { + var userID = 0; + var sockets = []; + var kartInf = []; + var relkDat = []; + var t = this; + + var upInt = setInterval(update, 16.667); + + function update() { + + //generate and send kart dat packet + if (relkDat.length != 0) { + var d = new ArrayBuffer(3+relkDat.length*0x62); + var arr = new Uint8Array(d); + var view = new DataView(d); + arr[0] = 32; + view.setUint16(1, relkDat.length, true); + var off = 3; + for (var i=0; i + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/Server/node_modules/safe-buffer/browser.js b/Server/node_modules/safe-buffer/browser.js new file mode 100644 index 0000000..0bd1202 --- /dev/null +++ b/Server/node_modules/safe-buffer/browser.js @@ -0,0 +1 @@ +module.exports = require('buffer') diff --git a/Server/node_modules/safe-buffer/index.js b/Server/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..74a7358 --- /dev/null +++ b/Server/node_modules/safe-buffer/index.js @@ -0,0 +1,58 @@ +var buffer = require('buffer') + +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + Object.keys(buffer).forEach(function (prop) { + exports[prop] = buffer[prop] + }) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +Object.keys(Buffer).forEach(function (prop) { + SafeBuffer[prop] = Buffer[prop] +}) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/Server/node_modules/safe-buffer/package.json b/Server/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..90d7908 --- /dev/null +++ b/Server/node_modules/safe-buffer/package.json @@ -0,0 +1,103 @@ +{ + "_args": [ + [ + { + "raw": "safe-buffer@~5.0.1", + "scope": null, + "escapedName": "safe-buffer", + "name": "safe-buffer", + "rawSpec": "~5.0.1", + "spec": ">=5.0.1 <5.1.0", + "type": "range" + }, + "D:\\Programs\\Dropbox\\Public\\mkds\\Server\\node_modules\\ws" + ] + ], + "_from": "safe-buffer@>=5.0.1 <5.1.0", + "_id": "safe-buffer@5.0.1", + "_inCache": true, + "_location": "/safe-buffer", + "_nodeVersion": "4.4.5", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/safe-buffer-5.0.1.tgz_1464588482081_0.8112505874596536" + }, + "_npmUser": { + "name": "feross", + "email": "feross@feross.org" + }, + "_npmVersion": "2.15.5", + "_phantomChildren": {}, + "_requested": { + "raw": "safe-buffer@~5.0.1", + "scope": null, + "escapedName": "safe-buffer", + "name": "safe-buffer", + "rawSpec": "~5.0.1", + "spec": ">=5.0.1 <5.1.0", + "type": "range" + }, + "_requiredBy": [ + "/ws" + ], + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.0.1.tgz", + "_shasum": "d263ca54696cd8a306b5ca6551e92de57918fbe7", + "_shrinkwrap": null, + "_spec": "safe-buffer@~5.0.1", + "_where": "D:\\Programs\\Dropbox\\Public\\mkds\\Server\\node_modules\\ws", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "browser": "./browser.js", + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "dependencies": {}, + "description": "Safer Node.js Buffer API", + "devDependencies": { + "standard": "^7.0.0", + "tape": "^4.0.0", + "zuul": "^3.0.0" + }, + "directories": {}, + "dist": { + "shasum": "d263ca54696cd8a306b5ca6551e92de57918fbe7", + "tarball": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.0.1.tgz" + }, + "gitHead": "1e371a367da962afae2bebc527b50271c739d28c", + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "maintainers": [ + { + "name": "feross", + "email": "feross@feross.org" + }, + { + "name": "mafintosh", + "email": "mathiasbuus@gmail.com" + } + ], + "name": "safe-buffer", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "version": "5.0.1" +} diff --git a/Server/node_modules/safe-buffer/test.js b/Server/node_modules/safe-buffer/test.js new file mode 100644 index 0000000..7da8ad7 --- /dev/null +++ b/Server/node_modules/safe-buffer/test.js @@ -0,0 +1,99 @@ +var test = require('tape') +var SafeBuffer = require('./').Buffer + +test('new SafeBuffer(value) works just like Buffer', function (t) { + t.deepEqual(new SafeBuffer('hey'), new Buffer('hey')) + t.deepEqual(new SafeBuffer('hey', 'utf8'), new Buffer('hey', 'utf8')) + t.deepEqual(new SafeBuffer('686579', 'hex'), new Buffer('686579', 'hex')) + t.deepEqual(new SafeBuffer([1, 2, 3]), new Buffer([1, 2, 3])) + t.deepEqual(new SafeBuffer(new Uint8Array([1, 2, 3])), new Buffer(new Uint8Array([1, 2, 3]))) + + t.equal(typeof SafeBuffer.isBuffer, 'function') + t.equal(SafeBuffer.isBuffer(new SafeBuffer('hey')), true) + t.equal(Buffer.isBuffer(new SafeBuffer('hey')), true) + t.notOk(SafeBuffer.isBuffer({})) + + t.end() +}) + +test('SafeBuffer.from(value) converts to a Buffer', function (t) { + t.deepEqual(SafeBuffer.from('hey'), new Buffer('hey')) + t.deepEqual(SafeBuffer.from('hey', 'utf8'), new Buffer('hey', 'utf8')) + t.deepEqual(SafeBuffer.from('686579', 'hex'), new Buffer('686579', 'hex')) + t.deepEqual(SafeBuffer.from([1, 2, 3]), new Buffer([1, 2, 3])) + t.deepEqual(SafeBuffer.from(new Uint8Array([1, 2, 3])), new Buffer(new Uint8Array([1, 2, 3]))) + + t.end() +}) + +test('SafeBuffer.alloc(number) returns zeroed-out memory', function (t) { + for (var i = 0; i < 10; i++) { + var expected1 = new Buffer(1000) + expected1.fill(0) + t.deepEqual(SafeBuffer.alloc(1000), expected1) + + var expected2 = new Buffer(1000 * 1000) + expected2.fill(0) + t.deepEqual(SafeBuffer.alloc(1000 * 1000), expected2) + } + t.end() +}) + +test('SafeBuffer.allocUnsafe(number)', function (t) { + var buf = SafeBuffer.allocUnsafe(100) // unitialized memory + t.equal(buf.length, 100) + t.equal(SafeBuffer.isBuffer(buf), true) + t.equal(Buffer.isBuffer(buf), true) + t.end() +}) + +test('SafeBuffer.from() throws with number types', function (t) { + t.plan(5) + t.throws(function () { + SafeBuffer.from(0) + }) + t.throws(function () { + SafeBuffer.from(-1) + }) + t.throws(function () { + SafeBuffer.from(NaN) + }) + t.throws(function () { + SafeBuffer.from(Infinity) + }) + t.throws(function () { + SafeBuffer.from(99) + }) +}) + +test('SafeBuffer.allocUnsafe() throws with non-number types', function (t) { + t.plan(4) + t.throws(function () { + SafeBuffer.allocUnsafe('hey') + }) + t.throws(function () { + SafeBuffer.allocUnsafe('hey', 'utf8') + }) + t.throws(function () { + SafeBuffer.allocUnsafe([1, 2, 3]) + }) + t.throws(function () { + SafeBuffer.allocUnsafe({}) + }) +}) + +test('SafeBuffer.alloc() throws with non-number types', function (t) { + t.plan(4) + t.throws(function () { + SafeBuffer.alloc('hey') + }) + t.throws(function () { + SafeBuffer.alloc('hey', 'utf8') + }) + t.throws(function () { + SafeBuffer.alloc([1, 2, 3]) + }) + t.throws(function () { + SafeBuffer.alloc({}) + }) +}) diff --git a/Server/node_modules/ultron/LICENSE b/Server/node_modules/ultron/LICENSE new file mode 100644 index 0000000..6dc9316 --- /dev/null +++ b/Server/node_modules/ultron/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Unshift.io, Arnout Kazemier, the Contributors. + +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. + diff --git a/Server/node_modules/ultron/index.js b/Server/node_modules/ultron/index.js new file mode 100644 index 0000000..9e0677a --- /dev/null +++ b/Server/node_modules/ultron/index.js @@ -0,0 +1,138 @@ +'use strict'; + +var has = Object.prototype.hasOwnProperty; + +/** + * An auto incrementing id which we can use to create "unique" Ultron instances + * so we can track the event emitters that are added through the Ultron + * interface. + * + * @type {Number} + * @private + */ +var id = 0; + +/** + * Ultron is high-intelligence robot. It gathers intelligence so it can start improving + * upon his rudimentary design. It will learn from your EventEmitting patterns + * and exterminate them. + * + * @constructor + * @param {EventEmitter} ee EventEmitter instance we need to wrap. + * @api public + */ +function Ultron(ee) { + if (!(this instanceof Ultron)) return new Ultron(ee); + + this.id = id++; + this.ee = ee; +} + +/** + * Register a new EventListener for the given event. + * + * @param {String} event Name of the event. + * @param {Functon} fn Callback function. + * @param {Mixed} context The context of the function. + * @returns {Ultron} + * @api public + */ +Ultron.prototype.on = function on(event, fn, context) { + fn.__ultron = this.id; + this.ee.on(event, fn, context); + + return this; +}; +/** + * Add an EventListener that's only called once. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} context The context of the function. + * @returns {Ultron} + * @api public + */ +Ultron.prototype.once = function once(event, fn, context) { + fn.__ultron = this.id; + this.ee.once(event, fn, context); + + return this; +}; + +/** + * Remove the listeners we assigned for the given event. + * + * @returns {Ultron} + * @api public + */ +Ultron.prototype.remove = function remove() { + var args = arguments + , ee = this.ee + , event; + + // + // When no event names are provided we assume that we need to clear all the + // events that were assigned through us. + // + if (args.length === 1 && 'string' === typeof args[0]) { + args = args[0].split(/[, ]+/); + } else if (!args.length) { + if (ee.eventNames) { + args = ee.eventNames(); + } else if (ee._events) { + args = []; + + for (event in ee._events) { + if (has.call(ee._events, event)) args.push(event); + } + + if (Object.getOwnPropertySymbols) { + args = args.concat(Object.getOwnPropertySymbols(ee._events)); + } + } + } + + for (var i = 0; i < args.length; i++) { + var listeners = ee.listeners(args[i]); + + for (var j = 0; j < listeners.length; j++) { + event = listeners[j]; + + // + // Once listeners have a `listener` property that stores the real listener + // in the EventEmitter that ships with Node.js. + // + if (event.listener) { + if (event.listener.__ultron !== this.id) continue; + delete event.listener.__ultron; + } else { + if (event.__ultron !== this.id) continue; + delete event.__ultron; + } + + ee.removeListener(args[i], event); + } + } + + return this; +}; + +/** + * Destroy the Ultron instance, remove all listeners and release all references. + * + * @returns {Boolean} + * @api public + */ +Ultron.prototype.destroy = function destroy() { + if (!this.ee) return false; + + this.remove(); + this.ee = null; + + return true; +}; + +// +// Expose the module. +// +module.exports = Ultron; diff --git a/Server/node_modules/ultron/package.json b/Server/node_modules/ultron/package.json new file mode 100644 index 0000000..45bef13 --- /dev/null +++ b/Server/node_modules/ultron/package.json @@ -0,0 +1,112 @@ +{ + "_args": [ + [ + { + "raw": "ultron@~1.1.0", + "scope": null, + "escapedName": "ultron", + "name": "ultron", + "rawSpec": "~1.1.0", + "spec": ">=1.1.0 <1.2.0", + "type": "range" + }, + "D:\\Programs\\Dropbox\\Public\\mkds\\Server\\node_modules\\ws" + ] + ], + "_from": "ultron@>=1.1.0 <1.2.0", + "_id": "ultron@1.1.0", + "_inCache": true, + "_location": "/ultron", + "_nodeVersion": "6.2.1", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/ultron-1.1.0.tgz_1483969751660_0.8877595944795758" + }, + "_npmUser": { + "name": "3rdeden", + "email": "npm@3rd-Eden.com" + }, + "_npmVersion": "3.9.3", + "_phantomChildren": {}, + "_requested": { + "raw": "ultron@~1.1.0", + "scope": null, + "escapedName": "ultron", + "name": "ultron", + "rawSpec": "~1.1.0", + "spec": ">=1.1.0 <1.2.0", + "type": "range" + }, + "_requiredBy": [ + "/ws" + ], + "_resolved": "https://registry.npmjs.org/ultron/-/ultron-1.1.0.tgz", + "_shasum": "b07a2e6a541a815fc6a34ccd4533baec307ca864", + "_shrinkwrap": null, + "_spec": "ultron@~1.1.0", + "_where": "D:\\Programs\\Dropbox\\Public\\mkds\\Server\\node_modules\\ws", + "author": { + "name": "Arnout Kazemier" + }, + "bugs": { + "url": "https://github.com/unshiftio/ultron/issues" + }, + "dependencies": {}, + "description": "Ultron is high-intelligence robot. It gathers intel so it can start improving upon his rudimentary design", + "devDependencies": { + "assume": "1.4.x", + "eventemitter3": "2.0.x", + "istanbul": "0.4.x", + "mocha": "~3.2.0", + "pre-commit": "~1.2.0" + }, + "directories": {}, + "dist": { + "shasum": "b07a2e6a541a815fc6a34ccd4533baec307ca864", + "tarball": "https://registry.npmjs.org/ultron/-/ultron-1.1.0.tgz" + }, + "gitHead": "6eb97b74402978aebda4a9d497cb6243ec80c9f1", + "homepage": "https://github.com/unshiftio/ultron", + "keywords": [ + "Ultron", + "robot", + "gather", + "intelligence", + "event", + "events", + "eventemitter", + "emitter", + "cleanup" + ], + "license": "MIT", + "main": "index.js", + "maintainers": [ + { + "name": "unshift", + "email": "npm@unshift.io" + }, + { + "name": "v1", + "email": "info@3rd-Eden.com" + }, + { + "name": "3rdeden", + "email": "npm@3rd-Eden.com" + } + ], + "name": "ultron", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+https://github.com/unshiftio/ultron.git" + }, + "scripts": { + "100%": "istanbul check-coverage --statements 100 --functions 100 --lines 100 --branches 100", + "coverage": "istanbul cover _mocha -- test.js", + "test": "mocha test.js", + "test-travis": "istanbul cover _mocha --report lcovonly -- test.js", + "watch": "mocha --watch test.js" + }, + "version": "1.1.0" +} diff --git a/Server/node_modules/ws/LICENSE b/Server/node_modules/ws/LICENSE new file mode 100644 index 0000000..a145cd1 --- /dev/null +++ b/Server/node_modules/ws/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2011 Einar Otto Stangvik + +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. diff --git a/Server/node_modules/ws/README.md b/Server/node_modules/ws/README.md new file mode 100644 index 0000000..714f1a8 --- /dev/null +++ b/Server/node_modules/ws/README.md @@ -0,0 +1,259 @@ +# ws: a Node.js WebSocket library + +[![Version npm](https://img.shields.io/npm/v/ws.svg)](https://www.npmjs.com/package/ws) +[![Linux Build](https://img.shields.io/travis/websockets/ws/master.svg)](https://travis-ci.org/websockets/ws) +[![Windows Build](https://ci.appveyor.com/api/projects/status/github/websockets/ws?branch=master&svg=true)](https://ci.appveyor.com/project/lpinca/ws) +[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg)](https://coveralls.io/r/websockets/ws?branch=master) + +`ws` is a simple to use, blazing fast, and thoroughly tested WebSocket client +and server implementation. + +Passes the quite extensive Autobahn test suite. See http://websockets.github.io/ws/ +for the full reports. + +## Protocol support + +* **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) +* **HyBi drafts 13-17** (Current default, alternatively option `protocolVersion: 13`) + +## Installing + +``` +npm install --save ws +``` + +### Opt-in for performance + +There are 2 optional modules that can be installed along side with the `ws` +module. These modules are binary addons which improve certain operations, but as +they are binary addons they require compilation which can fail if no c++ +compiler is installed on the host system. + +- `npm install --save bufferutil`: Improves internal buffer operations which + allows for faster processing of masked WebSocket frames and general buffer + operations. +- `npm install --save utf-8-validate`: The specification requires validation of + invalid UTF-8 chars, some of these validations could not be done in JavaScript + hence the need for a binary addon. In most cases you will already be + validating the input that you receive for security purposes leading to double + validation. But if you want to be 100% spec-conforming and have fast + validation of UTF-8 then this module is a must. + +## API Docs + +See [`/doc/ws.md`](https://github.com/websockets/ws/blob/master/doc/ws.md) +for Node.js-like docs for the ws classes. + +## WebSocket compression + +`ws` supports the [permessage-deflate extension][permessage-deflate] extension +which enables the client and server to negotiate a compression algorithm and +its parameters, and then selectively apply it to the data payloads of each +WebSocket message. + +The extension is enabled by default but adds a significant overhead in terms of +performance and memory comsumption. We suggest to use WebSocket compression +only if it is really needed. + +To disable the extension you can set the `perMessageDeflate` option to `false`. +On the server: + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ + perMessageDeflate: false, + port: 8080 +}); +``` + +On the client: + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('ws://www.host.com/path', { + perMessageDeflate: false +}); +``` + +## Usage examples + +### Sending and receiving text data + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('open', function open() { + ws.send('something'); +}); + +ws.on('message', function incoming(data, flags) { + // flags.binary will be set if a binary data is received. + // flags.masked will be set if the data was masked. +}); +``` + +### Sending binary data + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('open', function open() { + const array = new Float32Array(5); + + for (var i = 0; i < array.length; ++i) { + array[i] = i / 2; + } + + ws.send(array); +}); +``` + +### Server example + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('message', function incoming(message) { + console.log('received: %s', message); + }); + + ws.send('something'); +}); +``` + +### Broadcast example + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ port: 8080 }); + +// Broadcast to all. +wss.broadcast = function broadcast(data) { + wss.clients.forEach(function each(client) { + if (client.readyState === WebSocket.OPEN) { + client.send(data); + } + }); +}; + +wss.on('connection', function connection(ws) { + ws.on('message', function incoming(data) { + // Broadcast to everyone else. + wss.clients.forEach(function each(client) { + if (client !== ws && client.readyState === WebSocket.OPEN) { + client.send(data); + } + }); + }); +}); +``` + +### ExpressJS example + +```js +const express = require('express'); +const http = require('http'); +const url = require('url'); +const WebSocket = require('ws'); + +const app = express(); + +app.use(function (req, res) { + res.send({ msg: "hello" }); +}); + +const server = http.createServer(app); +const wss = new WebSocket.Server({ server }); + +wss.on('connection', function connection(ws) { + const location = url.parse(ws.upgradeReq.url, true); + // You might use location.query.access_token to authenticate or share sessions + // or ws.upgradeReq.headers.cookie (see http://stackoverflow.com/a/16395220/151312) + + ws.on('message', function incoming(message) { + console.log('received: %s', message); + }); + + ws.send('something'); +}); + +server.listen(8080, function listening() { + console.log('Listening on %d', server.address().port); +}); +``` + +### echo.websocket.org demo + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('wss://echo.websocket.org/', { + origin: 'https://websocket.org' +}); + +ws.on('open', function open() { + console.log('connected'); + ws.send(Date.now()); +}); + +ws.on('close', function close() { + console.log('disconnected'); +}); + +ws.on('message', function incoming(data, flags) { + console.log(`Roundtrip time: ${Date.now() - data} ms`, flags); + + setTimeout(function timeout() { + ws.send(Date.now()); + }, 500); +}); +``` + +### Other examples + +For a full example with a browser client communicating with a ws server, see the +examples folder. + +Otherwise, see the test cases. + +## Error handling best practices + +```js +// If the WebSocket is closed before the following send is attempted +ws.send('something'); + +// Errors (both immediate and async write errors) can be detected in an optional +// callback. The callback is also the only way of being notified that data has +// actually been sent. +ws.send('something', function ack(error) { + // If error is not defined, the send has been completed, otherwise the error + // object will indicate what failed. +}); + +// Immediate errors can also be handled with `try...catch`, but **note** that +// since sends are inherently asynchronous, socket write failures will *not* be +// captured when this technique is used. +try { ws.send('something'); } +catch (e) { /* handle error */ } +``` + +## Changelog + +We're using the GitHub [`releases`](https://github.com/websockets/ws/releases) +for changelog entries. + +## License + +[MIT](LICENSE) + +[permessage-deflate]: https://tools.ietf.org/html/rfc7692 diff --git a/Server/node_modules/ws/SECURITY.md b/Server/node_modules/ws/SECURITY.md new file mode 100644 index 0000000..fd8e07b --- /dev/null +++ b/Server/node_modules/ws/SECURITY.md @@ -0,0 +1,33 @@ +# Security Guidelines + +Please contact us directly at **security@3rd-Eden.com** for any bug that might +impact the security of this project. Please prefix the subject of your email +with `[security]` in lowercase and square brackets. Our email filters will +automatically prevent these messages from being moved to our spam box. + +You will receive an acknowledgement of your report within **24 hours**. + +All emails that do not include security vulnerabilities will be removed and +blocked instantly. + +## Exceptions + +If you do not receive an acknowledgement within the said time frame please give +us the benefit of the doubt as it's possible that we haven't seen it yet. In +this case please send us a message **without details** using one of the +following methods: + +- Contact the lead developers of this project on their personal e-mails. You + can find the e-mails in the git logs, for example using the following command: + `git --no-pager show -s --format='%an <%ae>' ` where `` is the + SHA1 of their latest commit in the project. +- Create a GitHub issue stating contact details and the severity of the issue. + +Once we have acknowledged receipt of your report and confirmed the bug +ourselves we will work with you to fix the vulnerability and publicly acknowledge +your responsible disclosure, if you wish. In addition to that we will report +all vulnerabilities to the [Node Security Project](https://nodesecurity.io/). + +## History + +04 Jan 2016: [Buffer vulnerablity](https://github.com/websockets/ws/releases/tag/1.0.1) diff --git a/Server/node_modules/ws/index.js b/Server/node_modules/ws/index.js new file mode 100644 index 0000000..489e169 --- /dev/null +++ b/Server/node_modules/ws/index.js @@ -0,0 +1,15 @@ +/*! + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik + * MIT Licensed + */ + +'use strict'; + +const WebSocket = require('./lib/WebSocket'); + +WebSocket.Server = require('./lib/WebSocketServer'); +WebSocket.Receiver = require('./lib/Receiver'); +WebSocket.Sender = require('./lib/Sender'); + +module.exports = WebSocket; diff --git a/Server/node_modules/ws/lib/BufferUtil.js b/Server/node_modules/ws/lib/BufferUtil.js new file mode 100644 index 0000000..6a35e8f --- /dev/null +++ b/Server/node_modules/ws/lib/BufferUtil.js @@ -0,0 +1,71 @@ +/*! + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik + * MIT Licensed + */ + +'use strict'; + +const safeBuffer = require('safe-buffer'); + +const Buffer = safeBuffer.Buffer; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +const concat = (list, totalLength) => { + const target = Buffer.allocUnsafe(totalLength); + var offset = 0; + + for (var i = 0; i < list.length; i++) { + const buf = list[i]; + buf.copy(target, offset); + offset += buf.length; + } + + return target; +}; + +try { + const bufferUtil = require('bufferutil'); + + module.exports = Object.assign({ concat }, bufferUtil.BufferUtil || bufferUtil); +} catch (e) /* istanbul ignore next */ { + /** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ + const mask = (source, mask, output, offset, length) => { + for (var i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } + }; + + /** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ + const unmask = (buffer, mask) => { + // Required until https://github.com/nodejs/node/issues/9006 is resolved. + const length = buffer.length; + for (var i = 0; i < length; i++) { + buffer[i] ^= mask[i & 3]; + } + }; + + module.exports = { concat, mask, unmask }; +} diff --git a/Server/node_modules/ws/lib/Constants.js b/Server/node_modules/ws/lib/Constants.js new file mode 100644 index 0000000..3904414 --- /dev/null +++ b/Server/node_modules/ws/lib/Constants.js @@ -0,0 +1,10 @@ +'use strict'; + +const safeBuffer = require('safe-buffer'); + +const Buffer = safeBuffer.Buffer; + +exports.BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments']; +exports.GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; +exports.EMPTY_BUFFER = Buffer.alloc(0); +exports.NOOP = () => {}; diff --git a/Server/node_modules/ws/lib/ErrorCodes.js b/Server/node_modules/ws/lib/ErrorCodes.js new file mode 100644 index 0000000..f515571 --- /dev/null +++ b/Server/node_modules/ws/lib/ErrorCodes.js @@ -0,0 +1,28 @@ +/*! + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik + * MIT Licensed + */ + +'use strict'; + +module.exports = { + isValidErrorCode: function (code) { + return (code >= 1000 && code <= 1013 && code !== 1004 && code !== 1005 && code !== 1006) || + (code >= 3000 && code <= 4999); + }, + 1000: 'normal', + 1001: 'going away', + 1002: 'protocol error', + 1003: 'unsupported data', + 1004: 'reserved', + 1005: 'reserved for extensions', + 1006: 'reserved for extensions', + 1007: 'inconsistent or invalid data', + 1008: 'policy violation', + 1009: 'message too big', + 1010: 'extension handshake missing', + 1011: 'an unexpected condition prevented the request from being fulfilled', + 1012: 'service restart', + 1013: 'try again later' +}; diff --git a/Server/node_modules/ws/lib/EventTarget.js b/Server/node_modules/ws/lib/EventTarget.js new file mode 100644 index 0000000..e30b1b3 --- /dev/null +++ b/Server/node_modules/ws/lib/EventTarget.js @@ -0,0 +1,155 @@ +'use strict'; + +/** + * Class representing an event. + * + * @private + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @param {Object} target A reference to the target to which the event was dispatched + */ + constructor (type, target) { + this.target = target; + this.type = type; + } +} + +/** + * Class representing a message event. + * + * @extends Event + * @private + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data + * @param {Boolean} isBinary Specifies if `data` is binary + * @param {WebSocket} target A reference to the target to which the event was dispatched + */ + constructor (data, isBinary, target) { + super('message', target); + + this.binary = isBinary; // non-standard. + this.data = data; + } +} + +/** + * Class representing a close event. + * + * @extends Event + * @private + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {Number} code The status code explaining why the connection is being closed + * @param {String} reason A human-readable string explaining why the connection is closing + * @param {WebSocket} target A reference to the target to which the event was dispatched + */ + constructor (code, reason, target) { + super('close', target); + + this.wasClean = code === undefined || code === 1000; + this.reason = reason; + this.target = target; + this.type = 'close'; + this.code = code; + } +} + +/** + * Class representing an open event. + * + * @extends Event + * @private + */ +class OpenEvent extends Event { + /** + * Create a new `OpenEvent`. + * + * @param {WebSocket} target A reference to the target to which the event was dispatched + */ + constructor (target) { + super('open', target); + } +} + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} method A string representing the event type to listen for + * @param {Function} listener The listener to add + * @public + */ + addEventListener (method, listener) { + if (typeof listener !== 'function') return; + + function onMessage (data, flags) { + listener.call(this, new MessageEvent(data, !!flags.binary, this)); + } + + function onClose (code, message) { + listener.call(this, new CloseEvent(code, message, this)); + } + + function onError (event) { + event.type = 'error'; + event.target = this; + listener.call(this, event); + } + + function onOpen () { + listener.call(this, new OpenEvent(this)); + } + + if (method === 'message') { + onMessage._listener = listener; + this.on(method, onMessage); + } else if (method === 'close') { + onClose._listener = listener; + this.on(method, onClose); + } else if (method === 'error') { + onError._listener = listener; + this.on(method, onError); + } else if (method === 'open') { + onOpen._listener = listener; + this.on(method, onOpen); + } else { + this.on(method, listener); + } + }, + + /** + * Remove an event listener. + * + * @param {String} method A string representing the event type to remove + * @param {Function} listener The listener to remove + * @public + */ + removeEventListener (method, listener) { + const listeners = this.listeners(method); + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i] === listener || listeners[i]._listener === listener) { + this.removeListener(method, listeners[i]); + } + } + } +}; + +module.exports = EventTarget; diff --git a/Server/node_modules/ws/lib/Extensions.js b/Server/node_modules/ws/lib/Extensions.js new file mode 100644 index 0000000..a91910e --- /dev/null +++ b/Server/node_modules/ws/lib/Extensions.js @@ -0,0 +1,67 @@ +'use strict'; + +/** + * Parse the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} value field value of the header + * @return {Object} The parsed object + * @public + */ +const parse = (value) => { + value = value || ''; + + const extensions = {}; + + value.split(',').forEach((v) => { + const params = v.split(';'); + const token = params.shift().trim(); + const paramsList = extensions[token] = extensions[token] || []; + const parsedParams = {}; + + params.forEach((param) => { + const parts = param.trim().split('='); + const key = parts[0]; + var value = parts[1]; + + if (value === undefined) { + value = true; + } else { + // unquote value + if (value[0] === '"') { + value = value.slice(1); + } + if (value[value.length - 1] === '"') { + value = value.slice(0, value.length - 1); + } + } + (parsedParams[key] = parsedParams[key] || []).push(value); + }); + + paramsList.push(parsedParams); + }); + + return extensions; +}; + +/** + * Serialize a parsed `Sec-WebSocket-Extensions` header to a string. + * + * @param {Object} value The object to format + * @return {String} A string representing the given value + * @public + */ +const format = (value) => { + return Object.keys(value).map((token) => { + var paramsList = value[token]; + if (!Array.isArray(paramsList)) paramsList = [paramsList]; + return paramsList.map((params) => { + return [token].concat(Object.keys(params).map((k) => { + var p = params[k]; + if (!Array.isArray(p)) p = [p]; + return p.map((v) => v === true ? k : `${k}=${v}`).join('; '); + })).join('; '); + }).join(', '); + }).join(', '); +}; + +module.exports = { format, parse }; diff --git a/Server/node_modules/ws/lib/PerMessageDeflate.js b/Server/node_modules/ws/lib/PerMessageDeflate.js new file mode 100644 index 0000000..c1a1d3c --- /dev/null +++ b/Server/node_modules/ws/lib/PerMessageDeflate.js @@ -0,0 +1,384 @@ +'use strict'; + +const safeBuffer = require('safe-buffer'); +const zlib = require('zlib'); + +const bufferUtil = require('./BufferUtil'); + +const Buffer = safeBuffer.Buffer; + +const AVAILABLE_WINDOW_BITS = [8, 9, 10, 11, 12, 13, 14, 15]; +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const EMPTY_BLOCK = Buffer.from([0x00]); +const DEFAULT_WINDOW_BITS = 15; +const DEFAULT_MEM_LEVEL = 8; + +/** + * Per-message Deflate implementation. + */ +class PerMessageDeflate { + constructor (options, isServer, maxPayload) { + this._options = options || {}; + this._isServer = !!isServer; + this._inflate = null; + this._deflate = null; + this.params = null; + this._maxPayload = maxPayload || 0; + this.threshold = this._options.threshold === undefined ? 1024 : this._options.threshold; + } + + static get extensionName () { + return 'permessage-deflate'; + } + + /** + * Create extension parameters offer. + * + * @return {Object} Extension parameters + * @public + */ + offer () { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept extension offer. + * + * @param {Array} paramsList Extension parameters + * @return {Object} Accepted configuration + * @public + */ + accept (paramsList) { + paramsList = this.normalizeParams(paramsList); + + var params; + if (this._isServer) { + params = this.acceptAsServer(paramsList); + } else { + params = this.acceptAsClient(paramsList); + } + + this.params = params; + return params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup () { + if (this._inflate) { + if (this._inflate.writeInProgress) { + this._inflate.pendingClose = true; + } else { + this._inflate.close(); + this._inflate = null; + } + } + if (this._deflate) { + if (this._deflate.writeInProgress) { + this._deflate.pendingClose = true; + } else { + this._deflate.close(); + this._deflate = null; + } + } + } + + /** + * Accept extension offer from client. + * + * @param {Array} paramsList Extension parameters + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer (paramsList) { + const accepted = {}; + const result = paramsList.some((params) => { + if (( + this._options.serverNoContextTakeover === false && + params.server_no_context_takeover + ) || ( + this._options.serverMaxWindowBits === false && + params.server_max_window_bits + ) || ( + typeof this._options.serverMaxWindowBits === 'number' && + typeof params.server_max_window_bits === 'number' && + this._options.serverMaxWindowBits > params.server_max_window_bits + ) || ( + typeof this._options.clientMaxWindowBits === 'number' && + !params.client_max_window_bits + )) { + return; + } + + if ( + this._options.serverNoContextTakeover || + params.server_no_context_takeover + ) { + accepted.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if ( + this._options.clientNoContextTakeover !== false && + params.client_no_context_takeover + ) { + accepted.client_no_context_takeover = true; + } + if (typeof this._options.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = this._options.serverMaxWindowBits; + } else if (typeof params.server_max_window_bits === 'number') { + accepted.server_max_window_bits = params.server_max_window_bits; + } + if (typeof this._options.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = this._options.clientMaxWindowBits; + } else if ( + this._options.clientMaxWindowBits !== false && + typeof params.client_max_window_bits === 'number' + ) { + accepted.client_max_window_bits = params.client_max_window_bits; + } + return true; + }); + + if (!result) throw new Error(`Doesn't support the offered configuration`); + + return accepted; + } + + /** + * Accept extension response from server. + * + * @param {Array} paramsList Extension parameters + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient (paramsList) { + const params = paramsList[0]; + + if (this._options.clientNoContextTakeover != null) { + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Invalid value for "client_no_context_takeover"'); + } + } + if (this._options.clientMaxWindowBits != null) { + if ( + this._options.clientMaxWindowBits === false && + params.client_max_window_bits + ) { + throw new Error('Invalid value for "client_max_window_bits"'); + } + if ( + typeof this._options.clientMaxWindowBits === 'number' && ( + !params.client_max_window_bits || + params.client_max_window_bits > this._options.clientMaxWindowBits + )) { + throw new Error('Invalid value for "client_max_window_bits"'); + } + } + + return params; + } + + /** + * Normalize extensions parameters. + * + * @param {Array} paramsList Extension parameters + * @return {Array} Normalized extensions parameters + * @private + */ + normalizeParams (paramsList) { + return paramsList.map((params) => { + Object.keys(params).forEach((key) => { + var value = params[key]; + if (value.length > 1) { + throw new Error(`Multiple extension parameters for ${key}`); + } + + value = value[0]; + + switch (key) { + case 'server_no_context_takeover': + case 'client_no_context_takeover': + if (value !== true) { + throw new Error(`invalid extension parameter value for ${key} (${value})`); + } + params[key] = true; + break; + case 'server_max_window_bits': + case 'client_max_window_bits': + if (typeof value === 'string') { + value = parseInt(value, 10); + if (!~AVAILABLE_WINDOW_BITS.indexOf(value)) { + throw new Error(`invalid extension parameter value for ${key} (${value})`); + } + } + if (!this._isServer && value === true) { + throw new Error(`Missing extension parameter value for ${key}`); + } + params[key] = value; + break; + default: + throw new Error(`Not defined extension parameter (${key})`); + } + }); + return params; + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress (data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const maxWindowBits = this.params[`${endpoint}_max_window_bits`]; + this._inflate = zlib.createInflateRaw({ + windowBits: typeof maxWindowBits === 'number' ? maxWindowBits : DEFAULT_WINDOW_BITS + }); + } + this._inflate.writeInProgress = true; + + var totalLength = 0; + const buffers = []; + var err; + + const onData = (data) => { + totalLength += data.length; + if (this._maxPayload < 1 || totalLength <= this._maxPayload) { + return buffers.push(data); + } + + err = new Error('max payload size exceeded'); + err.closeCode = 1009; + this._inflate.reset(); + }; + + const onError = (err) => { + cleanup(); + callback(err); + }; + + const cleanup = () => { + if (!this._inflate) return; + + this._inflate.removeListener('error', onError); + this._inflate.removeListener('data', onData); + this._inflate.writeInProgress = false; + + if ( + (fin && this.params[`${endpoint}_no_context_takeover`]) || + this._inflate.pendingClose + ) { + this._inflate.close(); + this._inflate = null; + } + }; + + this._inflate.on('error', onError).on('data', onData); + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + cleanup(); + if (err) callback(err); + else callback(null, bufferUtil.concat(buffers, totalLength)); + }); + } + + /** + * Compress data. + * + * @param {Buffer} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress (data, fin, callback) { + if (!data || data.length === 0) { + process.nextTick(callback, null, EMPTY_BLOCK); + return; + } + + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const maxWindowBits = this.params[`${endpoint}_max_window_bits`]; + this._deflate = zlib.createDeflateRaw({ + flush: zlib.Z_SYNC_FLUSH, + windowBits: typeof maxWindowBits === 'number' ? maxWindowBits : DEFAULT_WINDOW_BITS, + memLevel: this._options.memLevel || DEFAULT_MEM_LEVEL + }); + } + this._deflate.writeInProgress = true; + + var totalLength = 0; + const buffers = []; + + const onData = (data) => { + totalLength += data.length; + buffers.push(data); + }; + + const onError = (err) => { + cleanup(); + callback(err); + }; + + const cleanup = () => { + if (!this._deflate) return; + + this._deflate.removeListener('error', onError); + this._deflate.removeListener('data', onData); + this._deflate.writeInProgress = false; + + if ( + (fin && this.params[`${endpoint}_no_context_takeover`]) || + this._deflate.pendingClose + ) { + this._deflate.close(); + this._deflate = null; + } + }; + + this._deflate.on('error', onError).on('data', onData); + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + cleanup(); + var data = bufferUtil.concat(buffers, totalLength); + if (fin) data = data.slice(0, data.length - 4); + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; diff --git a/Server/node_modules/ws/lib/Receiver.js b/Server/node_modules/ws/lib/Receiver.js new file mode 100644 index 0000000..6c1a10e --- /dev/null +++ b/Server/node_modules/ws/lib/Receiver.js @@ -0,0 +1,555 @@ +/*! + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik + * MIT Licensed + */ + +'use strict'; + +const safeBuffer = require('safe-buffer'); + +const PerMessageDeflate = require('./PerMessageDeflate'); +const isValidUTF8 = require('./Validation'); +const bufferUtil = require('./BufferUtil'); +const ErrorCodes = require('./ErrorCodes'); +const constants = require('./Constants'); + +const Buffer = safeBuffer.Buffer; + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; + +/** + * HyBi Receiver implementation. + */ +class Receiver { + /** + * Creates a Receiver instance. + * + * @param {Object} extensions An object containing the negotiated extensions + * @param {Number} maxPayload The maximum allowed message length + * @param {String} binaryType The type for binary data + */ + constructor (extensions, maxPayload, binaryType) { + this.binaryType = binaryType || constants.BINARY_TYPES[0]; + this.extensions = extensions || {}; + this.maxPayload = maxPayload | 0; + + this.bufferedBytes = 0; + this.buffers = []; + + this.compressed = false; + this.payloadLength = 0; + this.fragmented = 0; + this.masked = false; + this.fin = false; + this.mask = null; + this.opcode = 0; + + this.totalPayloadLength = 0; + this.messageLength = 0; + this.fragments = []; + + this.cleanupCallback = null; + this.hadError = false; + this.dead = false; + this.loop = false; + + this.onmessage = null; + this.onclose = null; + this.onerror = null; + this.onping = null; + this.onpong = null; + + this.state = GET_INFO; + } + + /** + * Consumes bytes from the available buffered data. + * + * @param {Number} bytes The number of bytes to consume + * @return {Buffer} Consumed bytes + * @private + */ + readBuffer (bytes) { + var offset = 0; + var dst; + var l; + + this.bufferedBytes -= bytes; + + if (bytes === this.buffers[0].length) return this.buffers.shift(); + + if (bytes < this.buffers[0].length) { + dst = this.buffers[0].slice(0, bytes); + this.buffers[0] = this.buffers[0].slice(bytes); + return dst; + } + + dst = Buffer.allocUnsafe(bytes); + + while (bytes > 0) { + l = this.buffers[0].length; + + if (bytes >= l) { + this.buffers[0].copy(dst, offset); + offset += l; + this.buffers.shift(); + } else { + this.buffers[0].copy(dst, offset, 0, bytes); + this.buffers[0] = this.buffers[0].slice(bytes); + } + + bytes -= l; + } + + return dst; + } + + /** + * Checks if the number of buffered bytes is bigger or equal than `n` and + * calls `cleanup` if necessary. + * + * @param {Number} n The number of bytes to check against + * @return {Boolean} `true` if `bufferedBytes >= n`, else `false` + * @private + */ + hasBufferedBytes (n) { + if (this.bufferedBytes >= n) return true; + + this.loop = false; + if (this.dead) this.cleanup(this.cleanupCallback); + return false; + } + + /** + * Adds new data to the parser. + * + * @public + */ + add (data) { + if (this.dead) return; + + this.bufferedBytes += data.length; + this.buffers.push(data); + this.startLoop(); + } + + /** + * Starts the parsing loop. + * + * @private + */ + startLoop () { + this.loop = true; + + while (this.loop) { + switch (this.state) { + case GET_INFO: + this.getInfo(); + break; + case GET_PAYLOAD_LENGTH_16: + this.getPayloadLength16(); + break; + case GET_PAYLOAD_LENGTH_64: + this.getPayloadLength64(); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + this.getData(); + break; + default: // `INFLATING` + this.loop = false; + } + } + } + + /** + * Reads the first two bytes of a frame. + * + * @private + */ + getInfo () { + if (!this.hasBufferedBytes(2)) return; + + const buf = this.readBuffer(2); + + if ((buf[0] & 0x30) !== 0x00) { + this.error(new Error('RSV2 and RSV3 must be clear'), 1002); + return; + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this.extensions[PerMessageDeflate.extensionName]) { + this.error(new Error('RSV1 must be clear'), 1002); + return; + } + + this.fin = (buf[0] & 0x80) === 0x80; + this.opcode = buf[0] & 0x0f; + this.payloadLength = buf[1] & 0x7f; + + if (this.opcode === 0x00) { + if (compressed) { + this.error(new Error('RSV1 must be clear'), 1002); + return; + } + + if (!this.fragmented) { + this.error(new Error(`invalid opcode: ${this.opcode}`), 1002); + return; + } else { + this.opcode = this.fragmented; + } + } else if (this.opcode === 0x01 || this.opcode === 0x02) { + if (this.fragmented) { + this.error(new Error(`invalid opcode: ${this.opcode}`), 1002); + return; + } + + this.compressed = compressed; + } else if (this.opcode > 0x07 && this.opcode < 0x0b) { + if (!this.fin) { + this.error(new Error('FIN must be set'), 1002); + return; + } + + if (compressed) { + this.error(new Error('RSV1 must be clear'), 1002); + return; + } + + if (this.payloadLength > 0x7d) { + this.error(new Error('invalid payload length'), 1002); + return; + } + } else { + this.error(new Error(`invalid opcode: ${this.opcode}`), 1002); + return; + } + + if (!this.fin && !this.fragmented) this.fragmented = this.opcode; + + this.masked = (buf[1] & 0x80) === 0x80; + + if (this.payloadLength === 126) this.state = GET_PAYLOAD_LENGTH_16; + else if (this.payloadLength === 127) this.state = GET_PAYLOAD_LENGTH_64; + else this.haveLength(); + } + + /** + * Gets extended payload length (7+16). + * + * @private + */ + getPayloadLength16 () { + if (!this.hasBufferedBytes(2)) return; + + this.payloadLength = this.readBuffer(2).readUInt16BE(0, true); + this.haveLength(); + } + + /** + * Gets extended payload length (7+64). + * + * @private + */ + getPayloadLength64 () { + if (!this.hasBufferedBytes(8)) return; + + const buf = this.readBuffer(8); + const num = buf.readUInt32BE(0, true); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + this.error(new Error('max payload size exceeded'), 1009); + return; + } + + this.payloadLength = (num * Math.pow(2, 32)) + buf.readUInt32BE(4, true); + this.haveLength(); + } + + /** + * Payload length has been read. + * + * @private + */ + haveLength () { + if (this.opcode < 0x08 && this.maxPayloadExceeded(this.payloadLength)) { + return; + } + + if (this.masked) this.state = GET_MASK; + else this.state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask () { + if (!this.hasBufferedBytes(4)) return; + + this.mask = this.readBuffer(4); + this.state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @private + */ + getData () { + var data = constants.EMPTY_BUFFER; + + if (this.payloadLength) { + if (!this.hasBufferedBytes(this.payloadLength)) return; + + data = this.readBuffer(this.payloadLength); + if (this.masked) bufferUtil.unmask(data, this.mask); + } + + if (this.opcode > 0x07) { + this.controlMessage(data); + } else if (this.compressed) { + this.state = INFLATING; + this.decompress(data); + } else if (this.pushFragment(data)) { + this.dataMessage(); + } + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @private + */ + decompress (data) { + const extension = this.extensions[PerMessageDeflate.extensionName]; + + extension.decompress(data, this.fin, (err, buf) => { + if (err) { + this.error(err, err.closeCode === 1009 ? 1009 : 1007); + return; + } + + if (this.pushFragment(buf)) this.dataMessage(); + this.startLoop(); + }); + } + + /** + * Handles a data message. + * + * @private + */ + dataMessage () { + if (this.fin) { + const messageLength = this.messageLength; + const fragments = this.fragments; + + this.totalPayloadLength = 0; + this.messageLength = 0; + this.fragmented = 0; + this.fragments = []; + + if (this.opcode === 2) { + var data; + + if (this.binaryType === 'nodebuffer') { + data = toBuffer(fragments, messageLength); + } else if (this.binaryType === 'arraybuffer') { + data = toArrayBuffer(toBuffer(fragments, messageLength)); + } else { + data = fragments; + } + + this.onmessage(data, { masked: this.masked, binary: true }); + } else { + const buf = toBuffer(fragments, messageLength); + + if (!isValidUTF8(buf)) { + this.error(new Error('invalid utf8 sequence'), 1007); + return; + } + + this.onmessage(buf.toString(), { masked: this.masked }); + } + } + + this.state = GET_INFO; + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @private + */ + controlMessage (data) { + if (this.opcode === 0x08) { + if (data.length === 0) { + this.onclose(1000, '', { masked: this.masked }); + this.loop = false; + this.cleanup(this.cleanupCallback); + } else if (data.length === 1) { + this.error(new Error('invalid payload length'), 1002); + } else { + const code = data.readUInt16BE(0, true); + + if (!ErrorCodes.isValidErrorCode(code)) { + this.error(new Error(`invalid status code: ${code}`), 1002); + return; + } + + const buf = data.slice(2); + + if (!isValidUTF8(buf)) { + this.error(new Error('invalid utf8 sequence'), 1007); + return; + } + + this.onclose(code, buf.toString(), { masked: this.masked }); + this.loop = false; + this.cleanup(this.cleanupCallback); + } + + return; + } + + const flags = { masked: this.masked, binary: true }; + + if (this.opcode === 0x09) this.onping(data, flags); + else this.onpong(data, flags); + + this.state = GET_INFO; + } + + /** + * Handles an error. + * + * @param {Error} err The error + * @param {Number} code Close code + * @private + */ + error (err, code) { + this.onerror(err, code); + this.hadError = true; + this.loop = false; + this.cleanup(this.cleanupCallback); + } + + /** + * Checks payload size, disconnects socket when it exceeds `maxPayload`. + * + * @param {Number} length Payload length + * @private + */ + maxPayloadExceeded (length) { + if (length === 0 || this.maxPayload < 1) return false; + + const fullLength = this.totalPayloadLength + length; + + if (fullLength <= this.maxPayload) { + this.totalPayloadLength = fullLength; + return false; + } + + this.error(new Error('max payload size exceeded'), 1009); + return true; + } + + /** + * Appends a fragment in the fragments array after checking that the sum of + * fragment lengths does not exceed `maxPayload`. + * + * @param {Buffer} fragment The fragment to add + * @return {Boolean} `true` if `maxPayload` is not exceeded, else `false` + * @private + */ + pushFragment (fragment) { + if (fragment.length === 0) return true; + + const totalLength = this.messageLength + fragment.length; + + if (this.maxPayload < 1 || totalLength <= this.maxPayload) { + this.messageLength = totalLength; + this.fragments.push(fragment); + return true; + } + + this.error(new Error('max payload size exceeded'), 1009); + return false; + } + + /** + * Releases resources used by the receiver. + * + * @param {Function} cb Callback + * @public + */ + cleanup (cb) { + this.dead = true; + + if (!this.hadError && (this.loop || this.state === INFLATING)) { + this.cleanupCallback = cb; + } else { + this.extensions = null; + this.fragments = null; + this.buffers = null; + this.mask = null; + + this.cleanupCallback = null; + this.onmessage = null; + this.onclose = null; + this.onerror = null; + this.onping = null; + this.onpong = null; + + if (cb) cb(); + } + } +} + +module.exports = Receiver; + +/** + * Makes a buffer from a list of fragments. + * + * @param {Buffer[]} fragments The list of fragments composing the message + * @param {Number} messageLength The length of the message + * @return {Buffer} + * @private + */ +function toBuffer (fragments, messageLength) { + if (fragments.length === 1) return fragments[0]; + if (fragments.length > 1) return bufferUtil.concat(fragments, messageLength); + return constants.EMPTY_BUFFER; +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} The buffer to convert + * @return {ArrayBuffer} Converted buffer + */ +function toArrayBuffer (buf) { + if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); +} diff --git a/Server/node_modules/ws/lib/Sender.js b/Server/node_modules/ws/lib/Sender.js new file mode 100644 index 0000000..b33bfd4 --- /dev/null +++ b/Server/node_modules/ws/lib/Sender.js @@ -0,0 +1,404 @@ +/*! + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik + * MIT Licensed + */ + +'use strict'; + +const safeBuffer = require('safe-buffer'); +const crypto = require('crypto'); + +const PerMessageDeflate = require('./PerMessageDeflate'); +const bufferUtil = require('./BufferUtil'); +const ErrorCodes = require('./ErrorCodes'); + +const Buffer = safeBuffer.Buffer; + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {net.Socket} socket The connection socket + * @param {Object} extensions An object containing the negotiated extensions + */ + constructor (socket, extensions) { + this.perMessageDeflate = (extensions || {})[PerMessageDeflate.extensionName]; + this._socket = socket; + + this.firstFragment = true; + this.compress = false; + + this.bufferedBytes = 0; + this.deflating = false; + this.queue = []; + + this.onerror = null; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {Buffer} data The data to frame + * @param {Object} options Options object + * @param {Number} options.opcode The opcode + * @param {Boolean} options.readOnly Specifies whether `data` can be modified + * @param {Boolean} options.fin Specifies whether or not to set the FIN bit + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit + * @return {Buffer[]} The framed data as a list of `Buffer` instances + * @public + */ + static frame (data, options) { + const merge = data.length < 1024 || (options.mask && options.readOnly); + var offset = options.mask ? 6 : 2; + var payloadLength = data.length; + + if (data.length >= 65536) { + offset += 8; + payloadLength = 127; + } else if (data.length > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? data.length + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + if (payloadLength === 126) { + target.writeUInt16BE(data.length, 2, true); + } else if (payloadLength === 127) { + target.writeUInt32BE(0, 2, true); + target.writeUInt32BE(data.length, 6, true); + } + + if (!options.mask) { + target[1] = payloadLength; + if (merge) { + data.copy(target, offset); + return [target]; + } + + return [target, data]; + } + + const mask = crypto.randomBytes(4); + + target[1] = payloadLength | 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (merge) { + bufferUtil.mask(data, mask, target, offset, data.length); + return [target]; + } + + bufferUtil.mask(data, mask, data, 0, data.length); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {(Number|undefined)} code The status code component of the body + * @param {String} data The message component of the body + * @param {Boolean} mask Specifies whether or not to mask the message + * @param {Function} cb Callback + * @public + */ + close (code, data, mask, cb) { + if (code !== undefined && (typeof code !== 'number' || !ErrorCodes.isValidErrorCode(code))) { + throw new Error('first argument must be a valid error code number'); + } + + const buf = Buffer.allocUnsafe(2 + (data ? Buffer.byteLength(data) : 0)); + + buf.writeUInt16BE(code || 1000, 0, true); + if (buf.length > 2) buf.write(data, 2); + + if (this.deflating) { + this.enqueue([this.doClose, buf, mask, cb]); + } else { + this.doClose(buf, mask, cb); + } + } + + /** + * Frames and sends a close message. + * + * @param {Buffer} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Function} cb Callback + * @private + */ + doClose (data, mask, cb) { + this.sendFrame(Sender.frame(data, { + readOnly: false, + opcode: 0x08, + rsv1: false, + fin: true, + mask + }), cb); + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @public + */ + ping (data, mask) { + var readOnly = true; + + if (!Buffer.isBuffer(data)) { + if (data instanceof ArrayBuffer) { + data = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + data = viewToBuffer(data); + } else { + data = Buffer.from(data); + readOnly = false; + } + } + + if (this.deflating) { + this.enqueue([this.doPing, data, mask, readOnly]); + } else { + this.doPing(data, mask, readOnly); + } + } + + /** + * Frames and sends a ping message. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Boolean} readOnly Specifies whether `data` can be modified + * @private + */ + doPing (data, mask, readOnly) { + this.sendFrame(Sender.frame(data, { + opcode: 0x09, + rsv1: false, + fin: true, + readOnly, + mask + })); + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @public + */ + pong (data, mask) { + var readOnly = true; + + if (!Buffer.isBuffer(data)) { + if (data instanceof ArrayBuffer) { + data = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + data = viewToBuffer(data); + } else { + data = Buffer.from(data); + readOnly = false; + } + } + + if (this.deflating) { + this.enqueue([this.doPong, data, mask, readOnly]); + } else { + this.doPong(data, mask, readOnly); + } + } + + /** + * Frames and sends a pong message. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Boolean} readOnly Specifies whether `data` can be modified + * @private + */ + doPong (data, mask, readOnly) { + this.sendFrame(Sender.frame(data, { + opcode: 0x0a, + rsv1: false, + fin: true, + readOnly, + mask + })); + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} options.compress Specifies whether or not to compress `data` + * @param {Boolean} options.binary Specifies whether `data` is binary or text + * @param {Boolean} options.fin Specifies whether the fragment is the last one + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Function} cb Callback + * @public + */ + send (data, options, cb) { + var opcode = options.binary ? 2 : 1; + var rsv1 = options.compress; + var readOnly = true; + + if (!Buffer.isBuffer(data)) { + if (data instanceof ArrayBuffer) { + data = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + data = viewToBuffer(data); + } else { + data = Buffer.from(data); + readOnly = false; + } + } + + if (this.firstFragment) { + this.firstFragment = false; + if (rsv1 && this.perMessageDeflate) { + rsv1 = data.length >= this.perMessageDeflate.threshold; + } + this.compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this.firstFragment = true; + + if (this.perMessageDeflate) { + const opts = { + compress: this.compress, + mask: options.mask, + fin: options.fin, + readOnly, + opcode, + rsv1 + }; + + if (this.deflating) { + this.enqueue([this.dispatch, data, opts, cb]); + } else { + this.dispatch(data, opts, cb); + } + } else { + this.sendFrame(Sender.frame(data, { + mask: options.mask, + fin: options.fin, + rsv1: false, + readOnly, + opcode + }), cb); + } + } + + /** + * Dispatches a data message. + * + * @param {Buffer} data The message to send + * @param {Object} options Options object + * @param {Number} options.opcode The opcode + * @param {Boolean} options.readOnly Specifies whether `data` can be modified + * @param {Boolean} options.fin Specifies whether or not to set the FIN bit + * @param {Boolean} options.compress Specifies whether or not to compress `data` + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit + * @param {Function} cb Callback + * @private + */ + dispatch (data, options, cb) { + if (!options.compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + this.deflating = true; + this.perMessageDeflate.compress(data, options.fin, (err, buf) => { + if (err) { + if (cb) cb(err); + else this.onerror(err); + return; + } + + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.deflating = false; + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue () { + while (!this.deflating && this.queue.length) { + const params = this.queue.shift(); + + this.bufferedBytes -= params[1].length; + params[0].apply(this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue (params) { + this.bufferedBytes += params[1].length; + this.queue.push(params); + } + + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} cb Callback + * @private + */ + sendFrame (list, cb) { + if (list.length === 2) { + this._socket.write(list[0]); + this._socket.write(list[1], cb); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; + +/** + * Converts an `ArrayBuffer` view into a buffer. + * + * @param {(DataView|TypedArray)} view The view to convert + * @return {Buffer} Converted view + * @private + */ +function viewToBuffer (view) { + const buf = Buffer.from(view.buffer); + + if (view.byteLength !== view.buffer.byteLength) { + return buf.slice(view.byteOffset, view.byteOffset + view.byteLength); + } + + return buf; +} diff --git a/Server/node_modules/ws/lib/Validation.js b/Server/node_modules/ws/lib/Validation.js new file mode 100644 index 0000000..fcb170f --- /dev/null +++ b/Server/node_modules/ws/lib/Validation.js @@ -0,0 +1,17 @@ +/*! + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik + * MIT Licensed + */ + +'use strict'; + +try { + const isValidUTF8 = require('utf-8-validate'); + + module.exports = typeof isValidUTF8 === 'object' + ? isValidUTF8.Validation.isValidUTF8 // utf-8-validate@<3.0.0 + : isValidUTF8; +} catch (e) /* istanbul ignore next */ { + module.exports = () => true; +} diff --git a/Server/node_modules/ws/lib/WebSocket.js b/Server/node_modules/ws/lib/WebSocket.js new file mode 100644 index 0000000..21a9f10 --- /dev/null +++ b/Server/node_modules/ws/lib/WebSocket.js @@ -0,0 +1,704 @@ +/*! + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik + * MIT Licensed + */ + +'use strict'; + +const EventEmitter = require('events'); +const crypto = require('crypto'); +const Ultron = require('ultron'); +const https = require('https'); +const http = require('http'); +const url = require('url'); + +const PerMessageDeflate = require('./PerMessageDeflate'); +const EventTarget = require('./EventTarget'); +const Extensions = require('./Extensions'); +const constants = require('./Constants'); +const Receiver = require('./Receiver'); +const Sender = require('./Sender'); + +const protocolVersions = [8, 13]; +const closeTimeout = 30 * 1000; // Allow 30 seconds to terminate the connection cleanly. + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {String} address The URL to which to connect + * @param {(String|String[])} protocols The subprotocols + * @param {Object} options Connection options + */ + constructor (address, protocols, options) { + super(); + + if (!protocols) { + protocols = []; + } else if (typeof protocols === 'string') { + protocols = [protocols]; + } else if (!Array.isArray(protocols)) { + options = protocols; + protocols = []; + } + + this.readyState = WebSocket.CONNECTING; + this.bytesReceived = 0; + this.extensions = {}; + this.protocol = ''; + + this._binaryType = constants.BINARY_TYPES[0]; + this._finalize = this.finalize.bind(this); + this._finalizeCalled = false; + this._closeMessage = null; + this._closeTimer = null; + this._closeCode = null; + this._receiver = null; + this._sender = null; + this._socket = null; + this._ultron = null; + + if (Array.isArray(address)) { + initAsServerClient.call(this, address[0], address[1], address[2], options); + } else { + initAsClient.call(this, address, protocols, options); + } + } + + get CONNECTING () { return WebSocket.CONNECTING; } + get CLOSING () { return WebSocket.CLOSING; } + get CLOSED () { return WebSocket.CLOSED; } + get OPEN () { return WebSocket.OPEN; } + + /** + * @type {Number} + */ + get bufferedAmount () { + var amount = 0; + + if (this._socket) { + amount = this._socket.bufferSize + this._sender.bufferedBytes; + } + return amount; + } + + /** + * This deviates from the WHATWG interface since ws doesn't support the required + * default "blob" type (instead we define a custom "nodebuffer" type). + * + * @type {String} + */ + get binaryType () { + return this._binaryType; + } + + set binaryType (type) { + if (constants.BINARY_TYPES.indexOf(type) < 0) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver.binaryType = type; + } + + /** + * Set up the socket and the internal resources. + * + * @param {net.Socket} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @private + */ + setSocket (socket, head) { + socket.setTimeout(0); + socket.setNoDelay(); + + this._receiver = new Receiver(this.extensions, this.maxPayload, this.binaryType); + this._sender = new Sender(socket, this.extensions); + this._ultron = new Ultron(socket); + this._socket = socket; + + // socket cleanup handlers + this._ultron.on('close', this._finalize); + this._ultron.on('error', this._finalize); + this._ultron.on('end', this._finalize); + + // ensure that the head is added to the receiver + if (head && head.length > 0) { + socket.unshift(head); + head = null; + } + + // subsequent packets are pushed to the receiver + this._ultron.on('data', (data) => { + this.bytesReceived += data.length; + this._receiver.add(data); + }); + + // receiver event handlers + this._receiver.onmessage = (data, flags) => this.emit('message', data, flags); + this._receiver.onping = (data, flags) => { + this.pong(data, !this._isServer, true); + this.emit('ping', data, flags); + }; + this._receiver.onpong = (data, flags) => this.emit('pong', data, flags); + this._receiver.onclose = (code, reason) => { + this._closeMessage = reason; + this._closeCode = code; + this.close(code, reason); + }; + this._receiver.onerror = (error, code) => { + // close the connection when the receiver reports a HyBi error code + this.close(code, ''); + this.emit('error', error); + }; + + // sender event handlers + this._sender.onerror = (error) => { + this.close(1002, ''); + this.emit('error', error); + }; + + this.readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Clean up and release internal resources. + * + * @param {(Boolean|Error)} Indicates whether or not an error occurred + * @private + */ + finalize (error) { + if (this._finalizeCalled) return; + + this.readyState = WebSocket.CLOSING; + this._finalizeCalled = true; + + clearTimeout(this._closeTimer); + this._closeTimer = null; + + // + // If the connection was closed abnormally (with an error), or if the close + // control frame was malformed or not received then the close code must be + // 1006. + // + if (error) this._closeCode = 1006; + + if (this._socket) { + this._ultron.destroy(); + this._socket.on('error', function onerror () { + this.destroy(); + }); + + if (!error) this._socket.end(); + else this._socket.destroy(); + + this._socket = null; + this._ultron = null; + } + + if (this._sender) { + this._sender = this._sender.onerror = null; + } + + if (this._receiver) { + this._receiver.cleanup(() => this.emitClose()); + this._receiver = null; + } else { + this.emitClose(); + } + } + + /** + * Emit the `close` event. + * + * @private + */ + emitClose () { + this.readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode || 1006, this._closeMessage || ''); + + if (this.extensions[PerMessageDeflate.extensionName]) { + this.extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this.extensions = null; + + this.removeAllListeners(); + this.on('error', constants.NOOP); // Catch all errors after this. + } + + /** + * Pause the socket stream. + * + * @public + */ + pause () { + if (this.readyState !== WebSocket.OPEN) throw new Error('not opened'); + + this._socket.pause(); + } + + /** + * Resume the socket stream + * + * @public + */ + resume () { + if (this.readyState !== WebSocket.OPEN) throw new Error('not opened'); + + this._socket.resume(); + } + + /** + * Start a closing handshake. + * + * @param {Number} code Status code explaining why the connection is closing + * @param {String} data A string explaining why the connection is closing + * @public + */ + close (code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + if (this._req && !this._req.aborted) { + this._req.abort(); + this.emit('error', new Error('closed before the connection is established')); + this.finalize(true); + } + return; + } + + if (this.readyState === WebSocket.CLOSING) { + if (this._closeCode && this._socket) this._socket.end(); + return; + } + + this.readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + if (err) this.emit('error', err); + + if (this._socket) { + if (this._closeCode) this._socket.end(); + // + // Ensure that the connection is cleaned up even when the closing + // handshake fails. + // + clearTimeout(this._closeTimer); + this._closeTimer = setTimeout(this._finalize, closeTimeout, true); + } + }); + } + + /** + * Send a ping message. + * + * @param {*} data The message to send + * @param {Boolean} mask Indicates whether or not to mask `data` + * @param {Boolean} failSilently Indicates whether or not to throw if `readyState` isn't `OPEN` + * @public + */ + ping (data, mask, failSilently) { + if (this.readyState !== WebSocket.OPEN) { + if (failSilently) return; + throw new Error('not opened'); + } + + if (typeof data === 'number') data = data.toString(); + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || constants.EMPTY_BUFFER, mask); + } + + /** + * Send a pong message. + * + * @param {*} data The message to send + * @param {Boolean} mask Indicates whether or not to mask `data` + * @param {Boolean} failSilently Indicates whether or not to throw if `readyState` isn't `OPEN` + * @public + */ + pong (data, mask, failSilently) { + if (this.readyState !== WebSocket.OPEN) { + if (failSilently) return; + throw new Error('not opened'); + } + + if (typeof data === 'number') data = data.toString(); + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || constants.EMPTY_BUFFER, mask); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} options.compress Specifies whether or not to compress `data` + * @param {Boolean} options.binary Specifies whether `data` is binary or text + * @param {Boolean} options.fin Specifies whether the fragment is the last one + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Function} cb Callback which is executed when data is written out + * @public + */ + send (data, options, cb) { + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (this.readyState !== WebSocket.OPEN) { + if (cb) cb(new Error('not opened')); + else throw new Error('not opened'); + return; + } + + if (typeof data === 'number') data = data.toString(); + + const opts = Object.assign({ + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true + }, options); + + if (!this.extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || constants.EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate () { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + if (this._req && !this._req.aborted) { + this._req.abort(); + this.emit('error', new Error('closed before the connection is established')); + this.finalize(true); + } + return; + } + + this.finalize(true); + } +} + +WebSocket.CONNECTING = 0; +WebSocket.OPEN = 1; +WebSocket.CLOSING = 2; +WebSocket.CLOSED = 3; + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + /** + * Return the listener of the event. + * + * @return {(Function|undefined)} The event listener or `undefined` + * @public + */ + get () { + const listeners = this.listeners(method); + for (var i = 0; i < listeners.length; i++) { + if (listeners[i]._listener) return listeners[i]._listener; + } + }, + /** + * Add a listener for the event. + * + * @param {Function} listener The listener to add + * @public + */ + set (listener) { + const listeners = this.listeners(method); + for (var i = 0; i < listeners.length; i++) { + // + // Remove only the listeners added via `addEventListener`. + // + if (listeners[i]._listener) this.removeListener(method, listeners[i]); + } + this.addEventListener(method, listener); + } + }); +}); + +WebSocket.prototype.addEventListener = EventTarget.addEventListener; +WebSocket.prototype.removeEventListener = EventTarget.removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket server client. + * + * @param {http.IncomingMessage} req The request object + * @param {net.Socket} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options WebSocket attributes + * @param {Number} options.protocolVersion The WebSocket protocol version + * @param {Object} options.extensions The negotiated extensions + * @param {Number} options.maxPayload The maximum allowed message size + * @param {String} options.protocol The chosen subprotocol + * @private + */ +function initAsServerClient (req, socket, head, options) { + this.protocolVersion = options.protocolVersion; + this.extensions = options.extensions; + this.maxPayload = options.maxPayload; + this.protocol = options.protocol; + + this.upgradeReq = req; + this._isServer = true; + + this.setSocket(socket, head); +} + +/** + * Initialize a WebSocket client. + * + * @param {String} address The URL to which to connect + * @param {String[]} protocols The list of subprotocols + * @param {Object} options Connection options + * @param {String} options.protocol Value of the `Sec-WebSocket-Protocol` header + * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate + * @param {String} options.localAddress Local interface to bind for network connections + * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` header + * @param {Object} options.headers An object containing request headers + * @param {String} options.origin Value of the `Origin` or `Sec-WebSocket-Origin` header + * @param {http.Agent} options.agent Use the specified Agent + * @param {String} options.host Value of the `Host` header + * @param {Number} options.family IP address family to use during hostname lookup (4 or 6). + * @param {Function} options.checkServerIdentity A function to validate the server hostname + * @param {Boolean} options.rejectUnauthorized Verify or not the server certificate + * @param {String} options.passphrase The passphrase for the private key or pfx + * @param {String} options.ciphers The ciphers to use or exclude + * @param {(String|String[]|Buffer|Buffer[])} options.cert The certificate key + * @param {(String|String[]|Buffer|Buffer[])} options.key The private key + * @param {(String|Buffer)} options.pfx The private key, certificate, and CA certs + * @param {(String|String[]|Buffer|Buffer[])} options.ca Trusted certificates + * @private + */ +function initAsClient (address, protocols, options) { + options = Object.assign({ + protocolVersion: protocolVersions[1], + protocol: protocols.join(','), + perMessageDeflate: true, + localAddress: null, + headers: null, + family: null, + origin: null, + agent: null, + host: null, + + // + // SSL options. + // + checkServerIdentity: null, + rejectUnauthorized: null, + passphrase: null, + ciphers: null, + cert: null, + key: null, + pfx: null, + ca: null + }, options); + + if (protocolVersions.indexOf(options.protocolVersion) === -1) { + throw new Error( + `unsupported protocol version: ${options.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + this.protocolVersion = options.protocolVersion; + this._isServer = false; + this.url = address; + + const serverUrl = url.parse(address); + const isUnixSocket = serverUrl.protocol === 'ws+unix:'; + + if (!serverUrl.host && (!isUnixSocket || !serverUrl.path)) { + throw new Error('invalid url'); + } + + const isSecure = serverUrl.protocol === 'wss:' || serverUrl.protocol === 'https:'; + const key = crypto.randomBytes(16).toString('base64'); + const httpObj = isSecure ? https : http; + + // + // Prepare extensions. + // + const extensionsOffer = {}; + var perMessageDeflate; + + if (options.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + options.perMessageDeflate !== true ? options.perMessageDeflate : {}, + false + ); + extensionsOffer[PerMessageDeflate.extensionName] = perMessageDeflate.offer(); + } + + const requestOptions = { + port: serverUrl.port || (isSecure ? 443 : 80), + host: serverUrl.hostname, + path: '/', + headers: { + 'Sec-WebSocket-Version': options.protocolVersion, + 'Sec-WebSocket-Key': key, + 'Connection': 'Upgrade', + 'Upgrade': 'websocket' + } + }; + + if (options.headers) Object.assign(requestOptions.headers, options.headers); + if (Object.keys(extensionsOffer).length) { + requestOptions.headers['Sec-WebSocket-Extensions'] = Extensions.format(extensionsOffer); + } + if (options.protocol) { + requestOptions.headers['Sec-WebSocket-Protocol'] = options.protocol; + } + if (options.origin) { + if (options.protocolVersion < 13) { + requestOptions.headers['Sec-WebSocket-Origin'] = options.origin; + } else { + requestOptions.headers.Origin = options.origin; + } + } + if (options.host) requestOptions.headers.Host = options.host; + if (serverUrl.auth) requestOptions.auth = serverUrl.auth; + + if (options.localAddress) requestOptions.localAddress = options.localAddress; + if (options.family) requestOptions.family = options.family; + + if (isUnixSocket) { + const parts = serverUrl.path.split(':'); + + requestOptions.socketPath = parts[0]; + requestOptions.path = parts[1]; + } else if (serverUrl.path) { + // + // Make sure that path starts with `/`. + // + if (serverUrl.path.charAt(0) !== '/') { + requestOptions.path = `/${serverUrl.path}`; + } else { + requestOptions.path = serverUrl.path; + } + } + + var agent = options.agent; + + // + // A custom agent is required for these options. + // + if ( + options.rejectUnauthorized != null || + options.checkServerIdentity || + options.passphrase || + options.ciphers || + options.cert || + options.key || + options.pfx || + options.ca + ) { + if (options.passphrase) requestOptions.passphrase = options.passphrase; + if (options.ciphers) requestOptions.ciphers = options.ciphers; + if (options.cert) requestOptions.cert = options.cert; + if (options.key) requestOptions.key = options.key; + if (options.pfx) requestOptions.pfx = options.pfx; + if (options.ca) requestOptions.ca = options.ca; + if (options.checkServerIdentity) { + requestOptions.checkServerIdentity = options.checkServerIdentity; + } + if (options.rejectUnauthorized != null) { + requestOptions.rejectUnauthorized = options.rejectUnauthorized; + } + + if (!agent) agent = new httpObj.Agent(requestOptions); + } + + if (agent) requestOptions.agent = agent; + + this._req = httpObj.get(requestOptions); + + this._req.on('error', (error) => { + if (this._req.aborted) return; + + this._req = null; + this.emit('error', error); + this.finalize(true); + }); + + this._req.on('response', (res) => { + if (!this.emit('unexpected-response', this._req, res)) { + this._req.abort(); + this.emit('error', new Error(`unexpected server response (${res.statusCode})`)); + this.finalize(true); + } + }); + + this._req.on('upgrade', (res, socket, head) => { + this._req = null; + + const digest = crypto.createHash('sha1') + .update(key + constants.GUID, 'binary') + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + socket.destroy(); + this.emit('error', new Error('invalid server key')); + return this.finalize(true); + } + + const serverProt = res.headers['sec-websocket-protocol']; + const protList = (options.protocol || '').split(/, */); + var protError; + + if (!options.protocol && serverProt) { + protError = 'server sent a subprotocol even though none requested'; + } else if (options.protocol && !serverProt) { + protError = 'server sent no subprotocol even though requested'; + } else if (serverProt && protList.indexOf(serverProt) === -1) { + protError = 'server responded with an invalid protocol'; + } + + if (protError) { + socket.destroy(); + this.emit('error', new Error(protError)); + return this.finalize(true); + } + + if (serverProt) this.protocol = serverProt; + + const serverExtensions = Extensions.parse(res.headers['sec-websocket-extensions']); + + if (perMessageDeflate && serverExtensions[PerMessageDeflate.extensionName]) { + try { + perMessageDeflate.accept(serverExtensions[PerMessageDeflate.extensionName]); + } catch (err) { + socket.destroy(); + this.emit('error', new Error('invalid extension parameter')); + return this.finalize(true); + } + + this.extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + + this.setSocket(socket, head); + }); +} diff --git a/Server/node_modules/ws/lib/WebSocketServer.js b/Server/node_modules/ws/lib/WebSocketServer.js new file mode 100644 index 0000000..e78efc1 --- /dev/null +++ b/Server/node_modules/ws/lib/WebSocketServer.js @@ -0,0 +1,336 @@ +/*! + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik + * MIT Licensed + */ + +'use strict'; + +const safeBuffer = require('safe-buffer'); +const EventEmitter = require('events'); +const crypto = require('crypto'); +const Ultron = require('ultron'); +const http = require('http'); +const url = require('url'); + +const PerMessageDeflate = require('./PerMessageDeflate'); +const Extensions = require('./Extensions'); +const constants = require('./Constants'); +const WebSocket = require('./WebSocket'); + +const Buffer = safeBuffer.Buffer; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {String} options.host The hostname where to bind the server + * @param {Number} options.port The port where to bind the server + * @param {http.Server} options.server A pre-created HTTP/S server to use + * @param {Function} options.verifyClient An hook to reject connections + * @param {Function} options.handleProtocols An hook to handle protocols + * @param {String} options.path Accept only connections matching this path + * @param {Boolean} options.noServer Enable no server mode + * @param {Boolean} options.clientTracking Specifies whether or not to track clients + * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate + * @param {Number} options.maxPayload The maximum allowed message size + * @param {Function} callback A listener for the `listening` event + */ + constructor (options, callback) { + super(); + + options = Object.assign({ + maxPayload: 100 * 1024 * 1024, + perMessageDeflate: true, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null + }, options); + + if (options.port == null && !options.server && !options.noServer) { + throw new TypeError('missing or invalid options'); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.allowHalfOpen = false; + this._server.listen(options.port, options.host, options.backlog, callback); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + this._ultron = new Ultron(this._server); + this._ultron.on('listening', () => this.emit('listening')); + this._ultron.on('error', (err) => this.emit('error', err)); + this._ultron.on('upgrade', (req, socket, head) => { + this.handleUpgrade(req, socket, head, (client) => { + this.emit(`connection${req.url}`, client); + this.emit('connection', client); + }); + }); + } + + if (options.clientTracking) this.clients = new Set(); + this.options = options; + this.path = options.path; + } + + /** + * Close the server. + * + * @param {Function} cb Callback + * @public + */ + close (cb) { + // + // Terminate all associated clients. + // + if (this.clients) { + for (const client of this.clients) client.terminate(); + } + + const server = this._server; + + if (server) { + this._ultron.destroy(); + this._ultron = this._server = null; + + // + // Close the http server if it was internally created. + // + if (this.options.port != null) return server.close(cb); + } + + if (cb) cb(); + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle (req) { + if (this.options.path && url.parse(req.url).pathname !== this.options.path) { + return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {net.Socket} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade (req, socket, head, cb) { + socket.on('error', socketError); + + const version = +req.headers['sec-websocket-version']; + + if ( + req.method !== 'GET' || req.headers.upgrade.toLowerCase() !== 'websocket' || + !req.headers['sec-websocket-key'] || (version !== 8 && version !== 13) || + !this.shouldHandle(req) + ) { + return abortConnection(socket, 400); + } + + var protocol = (req.headers['sec-websocket-protocol'] || '').split(/, */); + + // + // Optionally call external protocol selection handler. + // + if (this.options.handleProtocols) { + protocol = this.options.handleProtocols(protocol); + if (protocol === false) return abortConnection(socket, 401); + } else { + protocol = protocol[0]; + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.connection.authorized || req.connection.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message) => { + if (!verified) return abortConnection(socket, code || 401, message); + + this.completeUpgrade(protocol, version, req, socket, head, cb); + }); + return; + } else if (!this.options.verifyClient(info)) { + return abortConnection(socket, 401); + } + } + + this.completeUpgrade(protocol, version, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {String} protocol The chosen subprotocol + * @param {Number} version The WebSocket protocol version + * @param {http.IncomingMessage} req The request object + * @param {net.Socket} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @private + */ + completeUpgrade (protocol, version, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + const key = crypto.createHash('sha1') + .update(req.headers['sec-websocket-key'] + constants.GUID, 'binary') + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${key}` + ]; + + if (protocol) headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + + const offer = Extensions.parse(req.headers['sec-websocket-extensions']); + var extensions; + + try { + extensions = acceptExtensions(this.options, offer); + } catch (err) { + return abortConnection(socket, 400); + } + + const props = Object.keys(extensions); + + if (props.length) { + const serverExtensions = props.reduce((obj, key) => { + obj[key] = [extensions[key].params]; + return obj; + }, {}); + + headers.push(`Sec-WebSocket-Extensions: ${Extensions.format(serverExtensions)}`); + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers); + + socket.write(headers.concat('', '').join('\r\n')); + + const client = new WebSocket([req, socket, head], { + maxPayload: this.options.maxPayload, + protocolVersion: version, + extensions, + protocol + }); + + if (this.clients) { + this.clients.add(client); + client.on('close', () => this.clients.delete(client)); + } + + socket.removeListener('error', socketError); + cb(client); + } +} + +module.exports = WebSocketServer; + +/** + * Handle premature socket errors. + * + * @private + */ +function socketError () { + this.destroy(); +} + +/** + * Accept WebSocket extensions. + * + * @param {Object} options The `WebSocketServer` configuration options + * @param {Object} offer The parsed value of the `sec-websocket-extensions` header + * @return {Object} Accepted extensions + * @private + */ +function acceptExtensions (options, offer) { + const pmd = options.perMessageDeflate; + const extensions = {}; + + if (pmd && offer[PerMessageDeflate.extensionName]) { + const perMessageDeflate = new PerMessageDeflate( + pmd !== true ? pmd : {}, + true, + options.maxPayload + ); + + perMessageDeflate.accept(offer[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + + return extensions; +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {net.Socket} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @private + */ +function abortConnection (socket, code, message) { + if (socket.writable) { + message = message || http.STATUS_CODES[code]; + socket.write( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + 'Connection: close\r\n' + + 'Content-type: text/html\r\n' + + `Content-Length: ${Buffer.byteLength(message)}\r\n` + + '\r\n' + + message + ); + } + + socket.removeListener('error', socketError); + socket.destroy(); +} diff --git a/Server/node_modules/ws/package.json b/Server/node_modules/ws/package.json new file mode 100644 index 0000000..4540a63 --- /dev/null +++ b/Server/node_modules/ws/package.json @@ -0,0 +1,122 @@ +{ + "_args": [ + [ + { + "raw": "ws", + "scope": null, + "escapedName": "ws", + "name": "ws", + "rawSpec": "", + "spec": "latest", + "type": "tag" + }, + "D:\\Programs\\Dropbox\\Public\\mkds\\Server" + ] + ], + "_from": "ws@latest", + "_id": "ws@2.2.3", + "_inCache": true, + "_location": "/ws", + "_nodeVersion": "7.8.0", + "_npmOperationalInternal": { + "host": "packages-12-west.internal.npmjs.com", + "tmp": "tmp/ws-2.2.3.tgz_1491214217857_0.5180311135482043" + }, + "_npmUser": { + "name": "lpinca", + "email": "luigipinca@gmail.com" + }, + "_npmVersion": "4.2.0", + "_phantomChildren": {}, + "_requested": { + "raw": "ws", + "scope": null, + "escapedName": "ws", + "name": "ws", + "rawSpec": "", + "spec": "latest", + "type": "tag" + }, + "_requiredBy": [ + "#USER" + ], + "_resolved": "https://registry.npmjs.org/ws/-/ws-2.2.3.tgz", + "_shasum": "f36c9719a56dff813f455af912a2078145bbd940", + "_shrinkwrap": null, + "_spec": "ws", + "_where": "D:\\Programs\\Dropbox\\Public\\mkds\\Server", + "author": { + "name": "Einar Otto Stangvik", + "email": "einaros@gmail.com", + "url": "http://2x.io" + }, + "bugs": { + "url": "https://github.com/websockets/ws/issues" + }, + "dependencies": { + "safe-buffer": "~5.0.1", + "ultron": "~1.1.0" + }, + "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", + "devDependencies": { + "benchmark": "~2.1.2", + "bufferutil": "~3.0.0", + "eslint": "~3.19.0", + "eslint-config-standard": "~8.0.0-beta.1", + "eslint-plugin-import": "~2.2.0", + "eslint-plugin-node": "~4.2.0", + "eslint-plugin-promise": "~3.5.0", + "eslint-plugin-standard": "~2.1.0", + "mocha": "~3.2.0", + "nyc": "~10.2.0", + "utf-8-validate": "~3.0.0" + }, + "directories": {}, + "dist": { + "shasum": "f36c9719a56dff813f455af912a2078145bbd940", + "tarball": "https://registry.npmjs.org/ws/-/ws-2.2.3.tgz" + }, + "gitHead": "212c7aab04a5f23d89111c1722371211efa2dd89", + "homepage": "https://github.com/websockets/ws#readme", + "keywords": [ + "HyBi", + "Push", + "RFC-6455", + "WebSocket", + "WebSockets", + "real-time" + ], + "license": "MIT", + "main": "index.js", + "maintainers": [ + { + "name": "3rdeden", + "email": "npm@3rd-Eden.com" + }, + { + "name": "einaros", + "email": "einaros@gmail.com" + }, + { + "name": "lpinca", + "email": "luigipinca@gmail.com" + }, + { + "name": "v1", + "email": "npm@3rd-Eden.com" + } + ], + "name": "ws", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git://github.com/websockets/ws.git" + }, + "scripts": { + "integration": "eslint . && mocha test/*.integration.js", + "lint": "eslint .", + "test": "eslint . && nyc --reporter=html --reporter=text mocha test/*.test.js" + }, + "version": "2.2.3" +} diff --git a/Server/run.bat b/Server/run.bat new file mode 100644 index 0000000..9c4dee9 --- /dev/null +++ b/Server/run.bat @@ -0,0 +1 @@ +node server.js \ No newline at end of file diff --git a/Server/run.sh b/Server/run.sh new file mode 100644 index 0000000..317e61e --- /dev/null +++ b/Server/run.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +# just boots the server. nothing fancy right now. +nodejs server.js \ No newline at end of file diff --git a/Server/server.js b/Server/server.js new file mode 100644 index 0000000..d31222a --- /dev/null +++ b/Server/server.js @@ -0,0 +1,116 @@ +// +// MKJS Dedicated server main file. +// + +// Default config: +var defaultCfg = { + port:8080, + instances:1, + + defaultInstance: { + mapRotation: [ + "mkdsDefault" //auto includes all default maps. if you want to specify specific maps you will need to remove this and add "mkds/tracknum" for each default track you want to include. + //custom tracks are read from the "maps/" folder. + ], + mapMode: "random", + + itemConfig: [ + //specifies item number and default params + //eg triple green will have settings to choose how many shells you start with. + {item:0, cfg:{}}, + {item:1, cfg:{}}, + {item:2, cfg:{}}, + ], + itemChance: [ + //specifies brackets where certain items have a specific chance of appearing. + //should be in order of near first place first. + { + placement: 0.25, //if 8 players, players 1 and 2 will get this chance distribution. + choices: [ + //the random selector generates a number between 0 and 1. if it is less than an item's "chance", that item will be selected. If not we try the next one. + //real % chance per item is (item.chance - last.chance)*100 + {item:0, chance:0.5}, + {item:1, chance:0.75}, + {item:2, chance:1} + ] + }, + + { + placement: 1, + choices: [ + {item:2, chance:1} + ] + }, + ] + } +} +// -- + +process.title = "MKJS Dedicated Server"; + +console.log("Initializing server..."); +try { + var ws = require('ws'), + http = require('http'), + fs = require('fs'), + inst = require('./modules/mkjsInstance.js'); +} catch (err) { + console.error("FATAL ERROR - could not load modules. Ensure you have ws for websockets."); + process.exit(1); +} +console.log("Modules Ready!"); + +try { + var config = JSON.parse(fs.readFileSync('config.json', 'ascii')); +} catch (err) { + if (err.errno == 34) { + console.error("No config file. Writing default config."); + fs.writeFileSync('config.json', JSON.stringify(defaultCfg, null, "\t"), 'ascii') + var config = JSON.parse(fs.readFileSync('config.json', 'ascii')); + } else { + console.error("FATAL ERROR - could not load config. Check that the syntax is correct."); + process.exit(1); + } +} + +var wss = new ws.Server({port: config.port}); + +var instances = []; + +for (var i=0; i + + + + + + + + + + + + + +Current SSEQ: 0 + + \ No newline at end of file diff --git a/audioSFX.html b/audioSFX.html new file mode 100644 index 0000000..288d7f1 --- /dev/null +++ b/audioSFX.html @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + +Current SSEQ: 0 + + \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..3faa682 --- /dev/null +++ b/index.html @@ -0,0 +1 @@ + \ No newline at end of file