Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // www.multiplayerpiano.com
- // Multiplayer Piano Mod/Bot - PeriOS
- // version 1.4 (uploaded 2019/05/01)
- var version = "1.4";
- // Created by Peripheral Assassin (Poland)
- // Script contains upgraded version of script.js and my scripts and no songs.
- // Features:
- // -records songs (full automatically)
- // -plays these songs
- // -collects informations about users
- // -and more!
- // previous versions:
- // 1.0: http://pastebin.com/s1y0k9Li
- // 1.1: http://pastebin.com/HZeggFjw
- // How to install:
- // Block http://www.multiplayerpiano.com/script.js in your browser (in ad block plus click on the upper icon - settings - add your own filters - paste the link and click 'add' button and refresh MPP site),
- // Paste this script into console (F12)
- // Bugs? Send e-mail to me - [email protected]
- // No songs while you get back? Type \reload !
- // \itball command is disabled PERSISTENT.
- // To put clients in other rooms, just click on the room list.
- // IMPORTMIDI section is restricted for plain data. Use chooper100's MIDI importer and put generated files with upload buttom.
- //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- //new page handler
- /*
- var button = document.createElement("div");
- button.className = "ugly-button";
- button.id = "record-btn";
- button.innerText = "Record MP3";
- button.style.float = "right";
- document.getElementsByClassName("relative")[0].appendChild(button);
- var button = document.createElement("div");
- button.className = "ugly-button";
- button.id = "synth-btn";
- button.innerText = "Synth";
- button.style.float = "right";
- document.getElementsByClassName("relative")[0].appendChild(button);
- */
- //script.js modified
- // 钢琴
- $(function() {
- var test_mode = (window.location.hash && window.location.hash.match(/^(?:#.+)*#test(?:#.+)*$/i));
- var gSeeOwnCursor = (window.location.hash && window.location.hash.match(/^(?:#.+)*#seeowncursor(?:#.+)*$/i));
- var gMidiOutTest = (window.location.hash && window.location.hash.match(/^(?:#.+)*#midiout(?:#.+)*$/i)); // todo this is no longer needed
- if (!Array.prototype.indexOf) {
- Array.prototype.indexOf = function(elt /*, from*/) {
- var len = this.length >>> 0;
- var from = Number(arguments[1]) || 0;
- from = (from < 0) ? Math.ceil(from) : Math.floor(from);
- if (from < 0) from += len;
- for (; from < len; from++) {
- if (from in this && this[from] === elt) return from;
- }
- return -1;
- };
- }
- window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame
- || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame
- || function (cb) { setTimeout(cb, 1000 / 30); };
- var DEFAULT_VELOCITY = 0.5;
- var TIMING_TARGET = 1000;
- var localSound = true;
- // Utility
- ////////////////////////////////////////////////////////////////
- var Rect = function(x, y, w, h) {
- this.x = x;
- this.y = y;
- this.w = w;
- this.h = h;
- this.x2 = x + w;
- this.y2 = y + h;
- };
- Rect.prototype.contains = function(x, y) {
- return (x >= this.x && x <= this.x2 && y >= this.y && y <= this.y2);
- };
- // performing translation
- ////////////////////////////////////////////////////////////////
- var Translation = (function() {
- var strings = {
- "people are playing": {
- "pt": "pessoas estão jogando",
- "es": "personas están jugando",
- "ru": "человек играет",
- "fr": "personnes jouent",
- "ja": "人が遊んでいる",
- "de": "Leute spielen",
- "zh": "人在玩",
- "nl": "mensen spelen",
- "pl": "osób grają",
- "hu": "ember játszik"
- },
- "New Room...": {
- "pt": "Nova Sala ...",
- "es": "Nueva sala de...",
- "ru": "Новый номер...",
- "ja": "新しい部屋",
- "zh": "新房间",
- "nl": "nieuwe Kamer",
- "hu": "új szoba"
- },
- "room name": {
- "pt": "nome da sala",
- "es": "sala de nombre",
- "ru": "название комнаты",
- "fr": "nom de la chambre",
- "ja": "ルーム名",
- "de": "Raumnamen",
- "zh": "房间名称",
- "nl": "kamernaam",
- "pl": "nazwa pokój",
- "hu": "szoba neve"
- },
- "Visible (open to everyone)": {
- "pt": "Visível (aberto a todos)",
- "es": "Visible (abierto a todo el mundo)",
- "ru": "Visible (открытый для всех)",
- "fr": "Visible (ouvert à tous)",
- "ja": "目に見える(誰にでも開いている)",
- "de": "Sichtbar (offen für alle)",
- "zh": "可见(向所有人开放)",
- "nl": "Zichtbaar (open voor iedereen)",
- "pl": "Widoczne (otwarte dla wszystkich)",
- "hu": "Látható (nyitott mindenki számára)"
- },
- "Enable Chat": {
- "pt": "Ativar bate-papo",
- "es": "Habilitar chat",
- "ru": "Включить чат",
- "fr": "Activer discuter",
- "ja": "チャットを有効にする",
- "de": "aktivieren Sie chatten",
- "zh": "启用聊天",
- "nl": "Chat inschakelen",
- "pl": "Włącz czat",
- "hu": "a csevegést"
- },
- "Play Alone": {
- "pt": "Jogar Sozinho",
- "es": "Jugar Solo",
- "ru": "Играть в одиночку",
- "fr": "Jouez Seul",
- "ja": "一人でプレイ",
- "de": "Alleine Spielen",
- "zh": "独自玩耍",
- "nl": "Speel Alleen",
- "pl": "Zagraj sam",
- "hu": "Játssz egyedül"
- }
- // todo: it, tr, th, sv, ar, fi, nb, da, sv, he, cs, ko, ro, vi, id, nb, el, sk, bg, lt, sl, hr
- // todo: Connecting, Offline mode, input placeholder, Notifications
- };
- var setLanguage = function(lang) {
- language = lang
- };
- var getLanguage = function() {
- if(window.navigator && navigator.language && navigator.language.length >= 2) {
- return navigator.language.substr(0, 2).toLowerCase();
- } else {
- return "en";
- }
- };
- var get = function(text, lang) {
- if(typeof lang === "undefined") lang = language;
- var row = strings[text];
- if(row == undefined) return text;
- var string = row[lang];
- if(string == undefined) return text;
- return string;
- };
- var perform = function(lang) {
- if(typeof lang === "undefined") lang = language;
- $(".translate").each(function(i, ele) {
- var th = $(this);
- if(ele.tagName && ele.tagName.toLowerCase() == "input") {
- if(typeof ele.placeholder != "undefined") {
- th.attr("placeholder", get(th.attr("placeholder"), lang))
- }
- } else {
- th.text(get(th.text(), lang));
- }
- });
- };
- var language = getLanguage();
- return {
- setLanguage: setLanguage,
- getLanguage: getLanguage,
- get: get,
- perform: perform
- };
- })();
- Translation.perform();
- // AudioEngine classes
- ////////////////////////////////////////////////////////////////
- var AudioEngine = function() {
- };
- AudioEngine.prototype.init = function(cb) {
- this.volume = 0.6;
- this.sounds = {};
- this.paused = true;
- return this;
- };
- AudioEngine.prototype.load = function(id, url, cb) {
- };
- AudioEngine.prototype.play = function() {
- };
- AudioEngine.prototype.stop = function() {
- };
- AudioEngine.prototype.setVolume = function(vol) {
- this.volume = vol;
- };
- AudioEngine.prototype.resume = function() {
- this.paused = false;
- };
- AudioEngineWeb = function() {
- this.threshold = 1000;
- this.worker = new Worker("/workerTimer.js");
- var self = this;
- this.worker.onmessage = function(event)
- {
- if(event.data.args)
- if(event.data.args.action==0)
- {
- self.actualPlay(event.data.args.id, event.data.args.vol, event.data.args.time, event.data.args.part_id);
- }
- else
- {
- self.actualStop(event.data.args.id, event.data.args.time, event.data.args.part_id);
- }
- }
- };
- AudioEngineWeb.prototype = new AudioEngine();
- AudioEngineWeb.prototype.init = function(cb) {
- AudioEngine.prototype.init.call(this);
- this.context = new AudioContext();
- this.masterGain = this.context.createGain();
- this.masterGain.connect(this.context.destination);
- this.masterGain.gain.value = this.volume;
- this.limiterNode = this.context.createDynamicsCompressor();
- this.limiterNode.threshold.value = -10;
- this.limiterNode.knee.value = 0;
- this.limiterNode.ratio.value = 20;
- this.limiterNode.attack.value = 0;
- this.limiterNode.release.value = 0.1;
- this.limiterNode.connect(this.masterGain);
- // for synth mix
- this.pianoGain = this.context.createGain();
- this.pianoGain.gain.value = 0.5;
- this.pianoGain.connect(this.limiterNode);
- this.synthGain = this.context.createGain();
- this.synthGain.gain.value = 0.5;
- this.synthGain.connect(this.limiterNode);
- this.playings = {};
- if(cb) setTimeout(cb, 0);
- return this;
- };
- AudioEngineWeb.prototype.load = function(id, url, cb) {
- var audio = this;
- var req = new XMLHttpRequest();
- req.open("GET", url);
- req.responseType = "arraybuffer";
- req.addEventListener("readystatechange", function(evt) {
- if(req.readyState !== 4) return;
- try {
- audio.context.decodeAudioData(req.response, function(buffer) {
- audio.sounds[id] = buffer;
- if(cb) cb();
- });
- } catch(e) {
- /*throw new Error(e.message
- + " / id: " + id
- + " / url: " + url
- + " / status: " + req.status
- + " / ArrayBuffer: " + (req.response instanceof ArrayBuffer)
- + " / byteLength: " + (req.response && req.response.byteLength ? req.response.byteLength : "undefined"));*/
- new Notification({id: "audio-download-error", title: "Problem", text: "For some reason, an audio download failed with a status of " + req.status + ". ",
- target: "#piano", duration: 10000});
- }
- });
- req.send();
- };
- AudioEngineWeb.prototype.actualPlay = function(id, vol, time, part_id) { //the old play(), but with time insted of delay_ms.
- if(this.paused) return;
- if(!this.sounds.hasOwnProperty(id)) return;
- var source = this.context.createBufferSource();
- source.buffer = this.sounds[id];
- var gain = this.context.createGain();
- gain.gain.value = vol;
- source.connect(gain);
- gain.connect(this.pianoGain);
- source.start(time);
- // Patch from ste-art remedies stuttering under heavy load
- if(this.playings[id]) {
- var playing = this.playings[id];
- playing.gain.gain.setValueAtTime(playing.gain.gain.value, time);
- playing.gain.gain.linearRampToValueAtTime(0.0, time + 0.2);
- playing.source.stop(time + 0.21);
- if(enableSynth && playing.voice) {
- playing.voice.stop(time);
- }
- }
- this.playings[id] = {"source": source, "gain": gain, "part_id": part_id};
- if(enableSynth) {
- this.playings[id].voice = new synthVoice(id, time);
- }
- }
- AudioEngineWeb.prototype.play = function(id, vol, delay_ms, part_id)
- {
- if(!this.sounds.hasOwnProperty(id)) return;
- var time = this.context.currentTime + (delay_ms / 1000); //calculate time on note receive.
- var delay = delay_ms - this.threshold;
- if(delay<=0) this.actualPlay(id, vol, time, part_id);
- else {
- this.worker.postMessage({delay:delay,args:{action:0/*play*/,id:id, vol:vol, time:time, part_id:part_id}}); // but start scheduling right before play.
- }
- }
- AudioEngineWeb.prototype.actualStop = function(id, time, part_id) {
- if(this.playings.hasOwnProperty(id) && this.playings[id] && this.playings[id].part_id === part_id) {
- var gain = this.playings[id].gain.gain;
- gain.setValueAtTime(gain.value, time);
- gain.linearRampToValueAtTime(gain.value * 0.1, time + 0.16);
- gain.linearRampToValueAtTime(0.0, time + 0.4);
- this.playings[id].source.stop(time + 0.41);
- if(this.playings[id].voice) {
- this.playings[id].voice.stop(time);
- }
- this.playings[id] = null;
- }
- };
- AudioEngineWeb.prototype.stop = function(id, delay_ms, part_id) {
- var time = this.context.currentTime + (delay_ms / 1000);
- var delay = delay_ms - this.threshold;
- if(delay<=0) this.actualStop(id, time, part_id);
- else {
- this.worker.postMessage({delay:delay,args:{action:1/*stop*/, id:id, time:time, part_id:part_id}});
- }
- };
- AudioEngineWeb.prototype.setVolume = function(vol) {
- AudioEngine.prototype.setVolume.call(this, vol);
- this.masterGain.gain.value = this.volume;
- };
- AudioEngineWeb.prototype.resume = function() {
- this.paused = false;
- this.context.resume();
- };
- // Renderer classes
- ////////////////////////////////////////////////////////////////
- var Renderer = function() {
- };
- Renderer.prototype.init = function(piano) {
- this.piano = piano;
- this.resize();
- return this;
- };
- Renderer.prototype.resize = function(width, height) {
- if(typeof width == "undefined") width = $(this.piano.rootElement).width();
- if(typeof height == "undefined") height = Math.floor(width * 0.2);
- $(this.piano.rootElement).css({"height": height + "px", marginTop: Math.floor($(window).height() / 2 - height / 2) + "px"});
- this.width = width * window.devicePixelRatio;
- this.height = height * window.devicePixelRatio;
- };
- Renderer.prototype.visualize = function(key, color) {
- };
- var CanvasRenderer = function() {
- Renderer.call(this);
- };
- CanvasRenderer.prototype = new Renderer();
- CanvasRenderer.prototype.init = function(piano) {
- this.canvas = document.createElement("canvas");
- this.ctx = this.canvas.getContext("2d");
- piano.rootElement.appendChild(this.canvas);
- Renderer.prototype.init.call(this, piano); // calls resize()
- // create render loop
- var self = this;
- var render = function() {
- self.redraw();
- requestAnimationFrame(render);
- };
- requestAnimationFrame(render);
- // add event listeners
- var mouse_down = false;
- var last_key = null;
- $(piano.rootElement).mousedown(function(event) {
- mouse_down = true;
- //event.stopPropagation();
- event.preventDefault();
- var pos = CanvasRenderer.translateMouseEvent(event);
- var hit = self.getHit(pos.x, pos.y);
- if(hit) {
- press(hit.key.note, hit.v);
- last_key = hit.key;
- }
- });
- piano.rootElement.addEventListener("touchstart", function(event) {
- mouse_down = true;
- //event.stopPropagation();
- event.preventDefault();
- for(var i in event.changedTouches) {
- var pos = CanvasRenderer.translateMouseEvent(event.changedTouches[i]);
- var hit = self.getHit(pos.x, pos.y);
- if(hit) {
- press(hit.key.note, hit.v);
- last_key = hit.key;
- }
- }
- }, false);
- $(window).mouseup(function(event) {
- if(last_key) {
- release(last_key.note);
- }
- mouse_down = false;
- last_key = null;
- });
- /*$(piano.rootElement).mousemove(function(event) {
- if(!mouse_down) return;
- var pos = CanvasRenderer.translateMouseEvent(event);
- var hit = self.getHit(pos.x, pos.y);
- if(hit && hit.key != last_key) {
- press(hit.key.note, hit.v);
- last_key = hit.key;
- }
- });*/
- return this;
- };
- CanvasRenderer.prototype.resize = function(width, height) {
- Renderer.prototype.resize.call(this, width, height);
- if(this.width < 52 * 2) this.width = 52 * 2;
- if(this.height < this.width * 0.2) this.height = Math.floor(this.width * 0.2);
- this.canvas.width = this.width;
- this.canvas.height = this.height;
- this.canvas.style.width = this.width / window.devicePixelRatio + "px";
- this.canvas.style.height = this.height / window.devicePixelRatio + "px";
- // calculate key sizes
- this.whiteKeyWidth = Math.floor(this.width / 52);
- this.whiteKeyHeight = Math.floor(this.height * 0.9);
- this.blackKeyWidth = Math.floor(this.whiteKeyWidth * 0.75);
- this.blackKeyHeight = Math.floor(this.height * 0.5);
- this.blackKeyOffset = Math.floor(this.whiteKeyWidth - (this.blackKeyWidth / 2));
- this.keyMovement = Math.floor(this.whiteKeyHeight * 0.015);
- this.whiteBlipWidth = Math.floor(this.whiteKeyWidth * 0.7);
- this.whiteBlipHeight = Math.floor(this.whiteBlipWidth * 0.8);
- this.whiteBlipX = Math.floor((this.whiteKeyWidth - this.whiteBlipWidth) / 2);
- this.whiteBlipY = Math.floor(this.whiteKeyHeight - this.whiteBlipHeight * 1.2);
- this.blackBlipWidth = Math.floor(this.blackKeyWidth * 0.7);
- this.blackBlipHeight = Math.floor(this.blackBlipWidth * 0.8);
- this.blackBlipY = Math.floor(this.blackKeyHeight - this.blackBlipHeight * 1.2);
- this.blackBlipX = Math.floor((this.blackKeyWidth - this.blackBlipWidth) / 2);
- // prerender white key
- this.whiteKeyRender = document.createElement("canvas");
- this.whiteKeyRender.width = this.whiteKeyWidth;
- this.whiteKeyRender.height = this.height + 10;
- var ctx = this.whiteKeyRender.getContext("2d");
- if(ctx.createLinearGradient) {
- var gradient = ctx.createLinearGradient(0, 0, 0, this.whiteKeyHeight);
- gradient.addColorStop(0, "#eee");
- gradient.addColorStop(0.75, "#fff");
- gradient.addColorStop(1, "#dad4d4");
- ctx.fillStyle = gradient;
- } else {
- ctx.fillStyle = "#fff";
- }
- ctx.strokeStyle = "#000";
- ctx.lineJoin = "round";
- ctx.lineCap = "round";
- ctx.lineWidth = 10;
- ctx.strokeRect(ctx.lineWidth / 2, ctx.lineWidth / 2, this.whiteKeyWidth - ctx.lineWidth, this.whiteKeyHeight - ctx.lineWidth);
- ctx.lineWidth = 4;
- ctx.fillRect(ctx.lineWidth / 2, ctx.lineWidth / 2, this.whiteKeyWidth - ctx.lineWidth, this.whiteKeyHeight - ctx.lineWidth);
- // prerender black key
- this.blackKeyRender = document.createElement("canvas");
- this.blackKeyRender.width = this.blackKeyWidth + 10;
- this.blackKeyRender.height = this.blackKeyHeight + 10;
- var ctx = this.blackKeyRender.getContext("2d");
- if(ctx.createLinearGradient) {
- var gradient = ctx.createLinearGradient(0, 0, 0, this.blackKeyHeight);
- gradient.addColorStop(0, "#000");
- gradient.addColorStop(1, "#444");
- ctx.fillStyle = gradient;
- } else {
- ctx.fillStyle = "#000";
- }
- ctx.strokeStyle = "#222";
- ctx.lineJoin = "round";
- ctx.lineCap = "round";
- ctx.lineWidth = 8;
- ctx.strokeRect(ctx.lineWidth / 2, ctx.lineWidth / 2, this.blackKeyWidth - ctx.lineWidth, this.blackKeyHeight - ctx.lineWidth);
- ctx.lineWidth = 4;
- ctx.fillRect(ctx.lineWidth / 2, ctx.lineWidth / 2, this.blackKeyWidth - ctx.lineWidth, this.blackKeyHeight - ctx.lineWidth);
- // prerender shadows
- this.shadowRender = [];
- var y = -this.canvas.height * 2;
- for(var j = 0; j < 2; j++) {
- var canvas = document.createElement("canvas");
- this.shadowRender[j] = canvas;
- canvas.width = this.canvas.width;
- canvas.height = this.canvas.height;
- var ctx = canvas.getContext("2d");
- var sharp = j ? true : false;
- ctx.lineJoin = "round";
- ctx.lineCap = "round";
- ctx.lineWidth = 1;
- ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
- ctx.shadowBlur = this.keyMovement * 3;
- ctx.shadowOffsetY = -y + this.keyMovement;
- if(sharp) {
- ctx.shadowOffsetX = this.keyMovement;
- } else {
- ctx.shadowOffsetX = 0;
- ctx.shadowOffsetY = -y + this.keyMovement;
- }
- for(var i in this.piano.keys) {
- if(!this.piano.keys.hasOwnProperty(i)) continue;
- var key = this.piano.keys[i];
- if(key.sharp != sharp) continue;
- if(key.sharp) {
- ctx.fillRect(this.blackKeyOffset + this.whiteKeyWidth * key.spatial + ctx.lineWidth / 2,
- y + ctx.lineWidth / 2,
- this.blackKeyWidth - ctx.lineWidth, this.blackKeyHeight - ctx.lineWidth);
- } else {
- ctx.fillRect(this.whiteKeyWidth * key.spatial + ctx.lineWidth / 2,
- y + ctx.lineWidth / 2,
- this.whiteKeyWidth - ctx.lineWidth, this.whiteKeyHeight - ctx.lineWidth);
- }
- }
- }
- // update key rects
- for(var i in this.piano.keys) {
- if(!this.piano.keys.hasOwnProperty(i)) continue;
- var key = this.piano.keys[i];
- if(key.sharp) {
- key.rect = new Rect(this.blackKeyOffset + this.whiteKeyWidth * key.spatial, 0,
- this.blackKeyWidth, this.blackKeyHeight);
- } else {
- key.rect = new Rect(this.whiteKeyWidth * key.spatial, 0,
- this.whiteKeyWidth, this.whiteKeyHeight);
- }
- }
- };
- CanvasRenderer.prototype.visualize = function(key, color) {
- key.timePlayed = Date.now();
- key.blips.push({"time": key.timePlayed, "color": color});
- };
- CanvasRenderer.prototype.redraw = function() {
- var now = Date.now();
- var timeLoadedEnd = now - 1000;
- var timePlayedEnd = now - 100;
- var timeBlipEnd = now - 1000;
- this.ctx.save();
- this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
- // draw all keys
- for(var j = 0; j < 2; j++) {
- this.ctx.globalAlpha = 1.0;
- this.ctx.drawImage(this.shadowRender[j], 0, 0);
- var sharp = j ? true : false;
- for(var i in this.piano.keys) {
- if(!this.piano.keys.hasOwnProperty(i)) continue;
- var key = this.piano.keys[i];
- if(key.sharp != sharp) continue;
- if(!key.loaded) {
- this.ctx.globalAlpha = 0.2;
- } else if(key.timeLoaded > timeLoadedEnd) {
- this.ctx.globalAlpha = ((now - key.timeLoaded) / 1000) * 0.8 + 0.2;
- } else {
- this.ctx.globalAlpha = 1.0;
- }
- var y = 0;
- if(key.timePlayed > timePlayedEnd) {
- y = Math.floor(this.keyMovement - (((now - key.timePlayed) / 100) * this.keyMovement));
- }
- var x = Math.floor(key.sharp ? this.blackKeyOffset + this.whiteKeyWidth * key.spatial
- : this.whiteKeyWidth * key.spatial);
- var image = key.sharp ? this.blackKeyRender : this.whiteKeyRender;
- this.ctx.drawImage(image, x, y);
- // render blips
- if(key.blips.length) {
- var alpha = this.ctx.globalAlpha;
- var w, h;
- if(key.sharp) {
- x += this.blackBlipX;
- y = this.blackBlipY;
- w = this.blackBlipWidth;
- h = this.blackBlipHeight;
- } else {
- x += this.whiteBlipX;
- y = this.whiteBlipY;
- w = this.whiteBlipWidth;
- h = this.whiteBlipHeight;
- }
- for(var b = 0; b < key.blips.length; b++) {
- var blip = key.blips[b];
- if(blip.time > timeBlipEnd) {
- this.ctx.fillStyle = blip.color;
- this.ctx.globalAlpha = alpha - ((now - blip.time) / 1000);
- this.ctx.fillRect(x, y, w, h);
- } else {
- key.blips.splice(b, 1);
- --b;
- }
- y -= Math.floor(h * 1.1);
- }
- }
- }
- }
- this.ctx.restore();
- };
- CanvasRenderer.prototype.getHit = function(x, y) {
- for(var j = 0; j < 2; j++) {
- var sharp = j ? false : true; // black keys first
- for(var i in this.piano.keys) {
- if(!this.piano.keys.hasOwnProperty(i)) continue;
- var key = this.piano.keys[i];
- if(key.sharp != sharp) continue;
- if(key.rect.contains(x, y)) {
- var v = y / (key.sharp ? this.blackKeyHeight : this.whiteKeyHeight);
- v += 0.25;
- v *= DEFAULT_VELOCITY;
- if(v > 1.0) v = 1.0;
- return {"key": key, "v": v};
- }
- }
- }
- return null;
- };
- CanvasRenderer.isSupported = function() {
- var canvas = document.createElement("canvas");
- return !!(canvas.getContext && canvas.getContext("2d"));
- };
- CanvasRenderer.translateMouseEvent = function(evt) {
- var element = evt.target;
- var offx = 0;
- var offy = 0;
- do {
- if(!element) break; // wtf, wtf?
- offx += element.offsetLeft;
- offy += element.offsetTop;
- } while(element = element.offsetParent);
- return {
- x: (evt.pageX - offx) * window.devicePixelRatio,
- y: (evt.pageY - offy) * window.devicePixelRatio
- }
- };
- // Soundpack Stuff by electrashave ♥
- ////////////////////////////////////////////////////////////////
- function SoundSelector(piano) {
- this.initiated = false;
- this.keys = piano.keys;
- this.loading = {};
- this.notification;
- this.packs = [];
- this.piano = piano;
- this.soundSelection = localStorage.soundSelection || "MPP Classic";
- this.addPack({name: "MPP Classic", keys: Object.keys(this.piano.keys), ext: ".mp3", url: "/sounds/mppclassic/"});
- }
- SoundSelector.prototype.addPack = function(pack, load) {
- var self = this;
- self.loading[pack.url || pack] = true;
- function add(obj) {
- if (self.packs.indexOf(obj) != -1) return; //no adding packs twice D:<
- var html =document.createElement("li");
- html.classList = "pack";
- html.innerText = obj.name + " (" + obj.keys.length + " keys)";
- html.onclick = function() {
- self.loadPack(obj.name);
- self.notification.close();
- };
- obj.html = html;
- self.packs.push(obj);
- self.packs.sort(function(a, b) {
- if(a.name < b.name) return -1;
- if(a.name > b.name) return 1;
- return 0;
- });
- if (load) self.loadPack(obj.name);
- delete self.loading[obj.url];
- }
- if (typeof pack == "string") {
- $.getJSON(pack + "/info.json").done(function(json) {
- json.url = pack;
- add(json);
- });
- } else add(pack); //validate packs??
- };
- SoundSelector.prototype.addPacks = function(packs) {
- for (var i = 0; packs.length > i; i++) this.addPack(packs[i]);
- };
- SoundSelector.prototype.init = function() {
- var self = this;
- if (self.initialized) return console.warn("Sound selector already initialized!");
- if (!!Object.keys(self.loading).length) return setTimeout(function() {
- self.init();
- }, 250);
- $("#sound-btn").on("click", function() {
- if (document.getElementById("Notification-Sound-Selector") != null) return;
- var html = document.createElement("ul");
- $(html).append("<h1>Current Sound: " + self.soundSelection + "</h1>");
- for (var i = 0; self.packs.length > i; i++) {
- var pack = self.packs[i];
- if (pack.name == self.soundSelection) pack.html.classList = "pack enabled";
- else pack.html.classList = "pack";
- html.appendChild(pack.html);
- }
- self.notification = new Notification({title: "Sound Selector:", html: html, id: "Sound-Selector", duration: -1, target: "#sound-btn"});
- });
- self.initialized = true;
- self.loadPack(self.soundSelection, true);
- };
- SoundSelector.prototype.loadPack = function(pack, f) {
- for (var i = 0; this.packs.length > i; i++) {
- var p = this.packs[i];
- if (p.name == pack) {
- pack = p;
- break;
- }
- }
- if (typeof pack == "String") {
- console.warn("Sound pack does not exist! Loading default pack...");
- pack = this.packs[0];
- }
- if (pack.name == this.soundSelection && !f) return;
- if (pack.keys.length != Object.keys(this.piano.keys).length) {
- this.piano.keys = {};
- for (var i = 0; pack.keys.length > i; i++) this.piano.keys[pack.keys[i]] = this.keys[pack.keys[i]];
- this.piano.renderer.resize();
- }
- var self = this;
- for (var i in this.piano.keys) {
- if (!this.piano.keys.hasOwnProperty(i)) continue;
- (function() {
- var key = self.piano.keys[i];
- key.loaded = false;
- self.piano.audio.load(key.note, pack.url + key.note + pack.ext, function() {
- key.loaded = true;
- key.timeLoaded = Date.now();
- });
- })();
- }
- localStorage.soundSelection = pack.name;
- this.soundSelection = pack.name;
- };
- SoundSelector.prototype.removePack = function(name) {
- var found = false;
- for (var i = 0; this.packs.length > i; i++) {
- var pack = this.packs[i];
- if (pack.name == name) {
- this.packs.splice(i, 1);
- if (pack.name == this.soundSelection) this.loadPack(this.packs[0].name); //add mpp default if none?
- break;
- }
- }
- if (!found) console.warn("Sound pack not found!");
- };
- // Pianoctor
- ////////////////////////////////////////////////////////////////
- var PianoKey = function(note, octave) {
- this.note = note + octave;
- this.baseNote = note;
- this.octave = octave;
- this.sharp = note.indexOf("s") != -1;
- this.loaded = false;
- this.timeLoaded = 0;
- this.domElement = null;
- this.timePlayed = 0;
- this.blips = [];
- };
- var Piano = function(rootElement) {
- var piano = this;
- piano.rootElement = rootElement;
- piano.keys = {};
- var white_spatial = 0;
- var black_spatial = 0;
- var black_it = 0;
- var black_lut = [2, 1, 2, 1, 1];
- var addKey = function(note, octave) {
- var key = new PianoKey(note, octave);
- piano.keys[key.note] = key;
- if(key.sharp) {
- key.spatial = black_spatial;
- black_spatial += black_lut[black_it % 5];
- ++black_it;
- } else {
- key.spatial = white_spatial;
- ++white_spatial;
- }
- }
- if(test_mode) {
- addKey("c", 2);
- } else {
- addKey("a", -1);
- addKey("as", -1);
- addKey("b", -1);
- var notes = "c cs d ds e f fs g gs a as b".split(" ");
- for(var oct = 0; oct < 7; oct++) {
- for(var i in notes) {
- addKey(notes[i], oct);
- }
- }
- addKey("c", 7);
- }
- this.renderer = new CanvasRenderer().init(this);
- window.addEventListener("resize", function() {
- piano.renderer.resize();
- });
- window.AudioContext = window.AudioContext || window.webkitAudioContext || undefined;
- var audio_engine = AudioEngineWeb;
- this.audio = new audio_engine().init();
- };
- Piano.prototype.play = function(note, vol, participant, delay_ms,audio = true) {
- if(!this.keys.hasOwnProperty(note)) return;
- var key = this.keys[note];
- if(audio){
- if(key.loaded) this.audio.play(key.note, vol, delay_ms, participant.id);
- };
- if(typeof gMidiOutTest === "function") gMidiOutTest(key.note, vol * 100, delay_ms);
- var self = this;
- var jq_namediv = $(typeof participant == "undefined" ? null : participant.nameDiv);
- if(jq_namediv) {
- setTimeout(function() {
- self.renderer.visualize(key, typeof participant == "undefined" ? "yellow" : (participant.color || "#777"));
- jq_namediv.addClass("play");
- setTimeout(function() {
- jq_namediv.removeClass("play");
- }, 30);
- }, delay_ms);
- }
- };
- Piano.prototype.stop = function(note, participant, delay_ms) {
- if(!this.keys.hasOwnProperty(note)) return;
- var key = this.keys[note];
- if(key.loaded) this.audio.stop(key.note, delay_ms, participant.id);
- if(typeof gMidiOutTest === "function") gMidiOutTest(key.note, 0, delay_ms);
- };
- var gPiano = new Piano(document.getElementById("piano"));
- var gSoundSelector = new SoundSelector(gPiano);
- gSoundSelector.addPacks(["/sounds/Emotional_2.0/", "/sounds/Harp/", "/sounds/Music_Box/", "/sounds/Vintage_Upright/", "/sounds/Steinway_Grand/", "/sounds/Emotional/", "/sounds/Untitled/"]);
- gSoundSelector.init();
- gAutoSustain = true; //!(window.location.hash && window.location.hash.match(/^(?:#.+)*#sustain(?:#.+)*$/));
- var gSustain = false;
- volumeFactor = 0.5;
- gHeldNotes = {};gNHeld = 0;
- var gSustainedNotes = {};
- function press(id, vol,ns) {
- for(var y = 0;y<v;y++){//var vol = parseFloat(vol * Math.pow(volumeFactor,y)) || vol;
- setTimeout(function(){
- var ixd = id;
- if(!ixd){return false};
- if(!gClient.preventsPlaying()) {
- if(bluesMode)ixd = toBlues(ixd);
- var delay = 0;
- //console.log(y);
- for(var n = -octaveMode;n<=octaveMode;n++){
- var note = keys[keys.indexOf(ixd)+12*n];
- if(note){
- if(!ns)gHeldNotes[note] = true;
- gSustainedNotes[note] = true;
- gPiano.play(note, vol !== undefined ? vol : DEFAULT_VELOCITY, gClient.getOwnParticipant(), delay, localSound);
- gClient.startNote(note, vol);
- delay += octaveDelay;
- vq--;
- };
- };
- if(gClient.noteBuffer.length > 85){
- MPP.client.sendArray([{m: "n", t: gClient.noteBufferTime + gClient.serverTimeOffset, n: gClient.noteBuffer}]);
- gClient.noteBuffer = [];
- gClient.noteBufferTime = 0;
- console.log("packet oversize");
- };
- }else if(playing){
- clearTimeout(timeout);playing=0;
- MPP.chat.send("Play prevention detected. Automatically stopping the track.");
- }
- },y*d)};
- }
- function release(id,rep) {
- var id = id;
- if(bluesMode)id = toBlues(id);
- if(gHeldNotes[id]) {
- gHeldNotes[id] = false;
- if((gAutoSustain || gSustain) && !enableSynth) {
- gSustainedNotes[id] = true;
- } else {
- if(gNoteQuota.spend(1)) {
- gPiano.stop(id, gClient.getOwnParticipant(), 0);
- gClient.stopNote(id);
- gSustainedNotes[id] = false;
- }
- };
- }
- if(!rep && octaveMode == 1){release(keys[keys.indexOf(id)-12],true);release(keys[keys.indexOf(id)+12],true)}
- }
- function pressSustain() {
- gSustain = true;
- }
- function releaseSustain() {
- gSustain = false;
- if(!gAutoSustain) {
- for(var id in gSustainedNotes) {
- if(gSustainedNotes.hasOwnProperty(id) && gSustainedNotes[id] && !gHeldNotes[id]) {
- gSustainedNotes[id] = false;
- if(gNoteQuota.spend(1)) {
- gPiano.stop(id, gClient.getOwnParticipant(), 0);
- gClient.stopNote(id);
- }
- }
- }
- }
- }
- // internet science
- ////////////////////////////////////////////////////////////////
- var channel_id = decodeURIComponent(window.location.pathname);
- if(channel_id.substr(0, 1) == "/") channel_id = channel_id.substr(1);
- if(channel_id == "") channel_id = "lobby";
- var wssport = window.location.hostname == "www.multiplayerpiano.com" ? 443 : 8080;
- var gClient = new Client("ws://" + window.location.hostname + ":" + wssport);
- gClient.setChannel(channel_id);
- gClient.start();
- // Setting status
- (function() {
- gClient.on("status", function(status) {
- $("#status").text(status);
- });
- gClient.on("count", function(count) {
- if(count > 0) {
- $("#status").html('<span class="number">'+count+'</span> '+(count==1? 'person is' : 'people are')+' playing');
- document.title = "Piano (" + count + ")";
- } else {
- document.title = "Multiplayer Piano";
- }
- });
- })();
- // Handle changes to participants
- (function() {
- gClient.on("participant added", function(part) {
- part.displayX = 150;
- part.displayY = 50;
- // add nameDiv
- var div = document.createElement("div");
- div.className = "name";
- div.participantId = part.id;
- div.textContent = part.name || "";
- div.style.backgroundColor = part.color || "#777";
- if(gClient.participantId === part.id) {
- $(div).addClass("me");
- }
- if(gClient.channel && gClient.channel.crown && gClient.channel.crown.participantId === part.id) {
- $(div).addClass("owner");
- }
- if(gPianoMutes.indexOf(part._id) !== -1) {
- $(part.nameDiv).addClass("muted-notes");
- }
- if(gChatMutes.indexOf(part._id) !== -1) {
- $(part.nameDiv).addClass("muted-chat");
- }
- div.style.display = "none";
- part.nameDiv = $("#names")[0].appendChild(div);
- $(part.nameDiv).fadeIn(2000);
- // sort names
- var arr = $("#names .name");
- arr.sort(function(a, b) {
- a = a.style.backgroundColor; // todo: sort based on user id instead
- b = b.style.backgroundColor;
- if (a > b) return 1;
- else if (a < b) return -1;
- else return 0;
- });
- $("#names").html(arr);
- // add cursorDiv
- if(gClient.participantId !== part.id || gSeeOwnCursor) {
- var div = document.createElement("div");
- div.className = "cursor";
- div.style.display = "none";
- part.cursorDiv = $("#cursors")[0].appendChild(div);
- $(part.cursorDiv).fadeIn(2000);
- var div = document.createElement("div");
- div.className = "name";
- div.style.backgroundColor = part.color || "#777"
- div.textContent = part.name || "";
- part.cursorDiv.appendChild(div);
- } else {
- part.cursorDiv = undefined;
- }
- });
- gClient.on("participant removed", function(part) {
- // remove nameDiv
- var nd = $(part.nameDiv);
- var cd = $(part.cursorDiv);
- cd.fadeOut(2000);
- nd.fadeOut(2000, function() {
- nd.remove();
- cd.remove();
- part.nameDiv = undefined;
- part.cursorDiv = undefined;
- });
- });
- gClient.on("participant update", function(part) {
- var name = part.name || "";
- var color = part.color || "#777";
- part.nameDiv.style.backgroundColor = color;
- part.nameDiv.textContent = name;
- $(part.cursorDiv)
- .find(".name")
- .text(name)
- .css("background-color", color);
- });
- gClient.on("ch", function(msg) {
- for(var id in gClient.ppl) {
- if(gClient.ppl.hasOwnProperty(id)) {
- var part = gClient.ppl[id];
- if(part.id === gClient.participantId) {
- $(part.nameDiv).addClass("me");
- } else {
- $(part.nameDiv).removeClass("me");
- }
- if(msg.ch.crown && msg.ch.crown.participantId === part.id) {
- $(part.nameDiv).addClass("owner");
- $(part.cursorDiv).addClass("owner");
- } else {
- $(part.nameDiv).removeClass("owner");
- $(part.cursorDiv).removeClass("owner");
- }
- if(gPianoMutes.indexOf(part._id) !== -1) {
- $(part.nameDiv).addClass("muted-notes");
- } else {
- $(part.nameDiv).removeClass("muted-notes");
- }
- if(gChatMutes.indexOf(part._id) !== -1) {
- $(part.nameDiv).addClass("muted-chat");
- } else {
- $(part.nameDiv).removeClass("muted-chat");
- }
- }
- }
- });
- function updateCursor(msg) {
- const part = gClient.ppl[msg.id];
- if (part && part.cursorDiv) {
- part.cursorDiv.style.left = msg.x + "%";
- part.cursorDiv.style.top = msg.y + "%";
- }
- }
- gClient.on("m", updateCursor);
- gClient.on("participant added", updateCursor);
- })();
- // Handle changes to crown
- (function() {
- var jqcrown = $('<div id="crown"></div>').appendTo(document.body).hide();
- var jqcountdown = $('<span></span>').appendTo(jqcrown);
- var countdown_interval;
- jqcrown.click(function() {
- gClient.sendArray([{m: "chown", id: gClient.participantId}]);
- });
- gClient.on("ch", function(msg) {
- if(msg.ch.crown) {
- var crown = msg.ch.crown;
- if(!crown.participantId || !gClient.ppl[crown.participantId]) {
- var land_time = crown.time + 2000 - gClient.serverTimeOffset;
- var avail_time = crown.time + 15000 - gClient.serverTimeOffset;
- jqcountdown.text("");
- jqcrown.show();
- if(land_time - Date.now() <= 0) {
- jqcrown.css({"left": crown.endPos.x + "%", "top": crown.endPos.y + "%"});
- } else {
- jqcrown.css({"left": crown.startPos.x + "%", "top": crown.startPos.y + "%"});
- jqcrown.addClass("spin");
- jqcrown.animate({"left": crown.endPos.x + "%", "top": crown.endPos.y + "%"}, 2000, "linear", function() {
- jqcrown.removeClass("spin");
- });
- }
- clearInterval(countdown_interval);
- countdown_interval = setInterval(function() {
- var time = Date.now();
- if(time >= land_time) {
- var ms = avail_time - time;
- if(ms > 0) {
- jqcountdown.text(Math.ceil(ms / 1000) + "s");
- } else {
- jqcountdown.text("");
- clearInterval(countdown_interval);
- }
- }
- }, 1000);
- } else {
- jqcrown.hide();
- }
- } else {
- jqcrown.hide();
- }
- });
- gClient.on("disconnect", function() {
- jqcrown.fadeOut(2000);
- });
- })();
- // Playing notes
- gClient.on("n", function(msg) {
- var t = msg.t - gClient.serverTimeOffset + TIMING_TARGET - Date.now();
- var participant = gClient.findParticipantById(msg.p);
- if(gPianoMutes.indexOf(participant._id) !== -1)
- return;
- for(var i = 0; i < msg.n.length; i++) {
- var note = msg.n[i];
- var ms = t + (note.d || 0);
- if(ms < 0) {
- ms = 0;
- }
- else if(ms > 10000) continue;
- if(note.s) {
- gPiano.stop(note.n, participant, ms);
- } else {
- var vel = (typeof note.v !== "undefined")? parseFloat(note.v) : DEFAULT_VELOCITY;
- if(vel < 0) vel = 0; else if (vel > 1) vel = 1;
- gPiano.play(note.n, vel, participant, ms);
- if(enableSynth) {
- gPiano.stop(note.n, participant, ms + 1000);
- }
- }
- }
- });
- // Send cursor updates
- mx = 0;
- last_mx = -10;
- my = 0;
- last_my = -10;
- setInterval(function() {
- if(Math.abs(mx - last_mx) > 0.1 || Math.abs(my - last_my) > 0.1) {
- last_mx = mx;
- last_my = my;
- gClient.sendArray([{m: "m", x: mx, y: my}]);
- if(gSeeOwnCursor) {
- gClient.emit("m", { m: "m", id: gClient.participantId, x: mx, y: my });
- }
- var part = gClient.getOwnParticipant();
- if(part) {
- part.x = mx;
- part.y = my;
- }
- }
- }, 50);
- $(document).mousemove(function(event) {
- mx = ((event.pageX / $(window).width()) * 100).toFixed(2);
- my = ((event.pageY / $(window).height()) * 100).toFixed(2);
- });
- // Room settings button
- (function() {
- gClient.on("ch", function(msg) {
- if(gClient.isOwner()) {
- $("#room-settings-btn").show();
- } else {
- $("#room-settings-btn").hide();
- }
- });
- $("#room-settings-btn").click(function(evt) {
- if(gClient.channel && gClient.isOwner()) {
- var settings = gClient.channel.settings;
- openModal("#room-settings");
- setTimeout(function() {
- $("#room-settings .checkbox[name=visible]").prop("checked", settings.visible);
- $("#room-settings .checkbox[name=chat]").prop("checked", settings.chat);
- $("#room-settings .checkbox[name=crownsolo]").prop("checked", settings.crownsolo);
- $("#room-settings input[name=color]").val(settings.color);
- }, 100);
- }
- });
- $("#room-settings .submit").click(function() {
- var settings = {
- visible: $("#room-settings .checkbox[name=visible]").is(":checked"),
- chat: $("#room-settings .checkbox[name=chat]").is(":checked"),
- crownsolo: $("#room-settings .checkbox[name=crownsolo]").is(":checked"),
- color: $("#room-settings input[name=color]").val()
- };
- gClient.sendArray([{m: "chset", set: settings}]);
- closeModal();
- });
- $("#room-settings .drop-crown").click(function() {
- closeModal();
- if(confirm("This will drop the crown...!"))
- gClient.sendArray([{m: "chown"}]);
- });
- })();
- // Handle notifications
- gClient.on("notification", function(msg) {
- new Notification(msg);
- });
- // Don't foget spin
- gClient.on("ch", function(msg) {
- var chidlo = msg.ch._id.toLowerCase();
- if(chidlo === "spin" || chidlo.substr(-5) === "/spin") {
- $("#piano").addClass("spin");
- } else {
- $("#piano").removeClass("spin");
- }
- });
- /*function eb() {
- if(gClient.channel && gClient.channel._id.toLowerCase() === "test/fishing") {
- ebsprite.start(gClient);
- } else {
- ebsprite.stop();
- }
- }
- if(ebsprite) {
- gClient.on("ch", eb);
- eb();
- }*/
- // Crownsolo notice
- gClient.on("ch", function(msg) {
- if(msg.ch.settings.crownsolo) {
- if($("#crownsolo-notice").length == 0) {
- $('<div id="crownsolo-notice">').text('This room is set to "only the owner can play."').appendTo("body").fadeIn(1000);
- }
- } else {
- $("#crownsolo-notice").remove();
- }
- });
- gClient.on("disconnect", function() {
- $("#crownsolo-notice").remove();
- });
- // Background color
- (function() {
- var old_color1 = new Color("#3b5054");
- var old_color2 = new Color("#3b5054");
- function setColor(hex) {
- var color1 = new Color(hex);
- var color2 = new Color(hex);
- color2.add(-0x40, -0x40, -0x40);
- var bottom = document.getElementById("bottom");
- var duration = 500;
- var step = 0;
- var steps = 30;
- var step_ms = duration / steps;
- var difference = new Color(color1.r, color1.g, color1.b);
- difference.r -= old_color1.r;
- difference.g -= old_color1.g;
- difference.b -= old_color1.b;
- var inc = new Color(difference.r / steps, difference.g / steps, difference.b / steps);
- var iv;
- iv = setInterval(function() {
- old_color1.add(inc.r, inc.g, inc.b);
- old_color2.add(inc.r, inc.g, inc.b);
- document.body.style.background = "radial-gradient(ellipse at center, "+old_color1.toHexa()+" 0%,"+old_color2.toHexa()+" 100%)";
- bottom.style.background = old_color2.toHexa();
- if(++step >= steps) {
- clearInterval(iv);
- old_color1 = color1;
- old_color2 = color2;
- document.body.style.background = "radial-gradient(ellipse at center, "+color1.toHexa()+" 0%,"+color2.toHexa()+" 100%)";
- bottom.style.background = color2.toHexa();
- }
- }, step_ms);
- }
- setColor("#3b5054");
- gClient.on("ch", function(ch) {
- if(ch.ch.settings) {
- if(ch.ch.settings.color) {
- setColor(ch.ch.settings.color);
- } else {
- setColor("#3b5054");
- }
- }
- });
- })();
- var gPianoMutes = [];
- var gChatMutes = [];
- var volume_slider = document.getElementById("volume-slider");
- volume_slider.value = gPiano.audio.volume;
- $("#volume-label").text("Volume: " + Math.floor(gPiano.audio.volume * 100) + "%");
- volume_slider.addEventListener("input", function(evt) {
- var v = +volume_slider.value;
- gPiano.audio.setVolume(v);
- if (window.localStorage) localStorage.volume = v;
- $("#volume-label").text("Volume: " + Math.floor(v * 100) + "%");
- });
- var Note = function(note, octave) {
- this.note = note;
- this.octave = octave || 0;
- };
- var n = function(a, b) { return {note: new Note(a, b), held: false}; };
- key_binding = {
- 65: n("gs"),
- 90: n("a"),
- 83: n("as"),
- 88: n("b"),
- 67: n("c", 1),
- 70: n("cs", 1),
- 86: n("d", 1),
- 71: n("ds", 1),
- 66: n("e", 1),
- 78: n("f", 1),
- 74: n("fs", 1),
- 77: n("g", 1),
- 75: n("gs", 1),
- 188: n("a", 1),
- 76: n("as", 1),
- 190: n("b", 1),
- 191: n("c", 2),
- 222: n("cs", 2),
- 49: n("gs", 1),
- 81: n("a", 1),
- 50: n("as", 1),
- 87: n("b", 1),
- 69: n("c", 2),
- 52: n("cs", 2),
- 82: n("d", 2),
- 53: n("ds", 2),
- 84: n("e", 2),
- 89: n("f", 2),
- 55: n("fs", 2),
- 85: n("g", 2),
- 56: n("gs", 2),
- 73: n("a", 2),
- 57: n("as", 2),
- 79: n("b", 2),
- 80: n("c", 3),
- 189: n("cs", 3),
- 219: n("d", 3),
- 187: n("ds", 3),
- 221: n("e", 3),
- 220: n("f",3),
- 144: n("fs",3),
- 103: n("g",3),
- 111: n("gs",3),
- 104: n("a",3),
- 106: n("as",3),
- 105: n("b",3),
- 107: n("c",4),
- 173: n("cs", 3), // firefox why
- 61: n("ds", 3), // firefox why
- };
- capsLockKey = false;
- transpose_octave = 0;transpose_up = 0;transpose_down = 0;keys_down = "65 90 83 88 67 70 86 71 66 78 74 77 75 188 76 190 191 222".split(" ");octaveMode = 0;
- function handleKeyDown(evt) {
- //console.log(evt);
- var code = parseInt(evt.keyCode);
- if(key_binding[code] !== undefined) {
- var binding = key_binding[code];
- if(!binding.held) {
- binding.held = true;
- var note = binding.note;
- var octave = 1 + note.octave + transpose_octave;
- if(keys_down.indexOf(code.toString())!==-1)
- {octave+=transpose_down}else
- {octave+=transpose_up};
- if(evt.shiftKey) ++octave;
- else if(capsLockKey || evt.ctrlKey) --octave;
- note = note.note + octave;
- var vol = velocityFromMouseY();
- press(note, vol);
- }
- if(++gKeyboardSeq == 3) {
- gKnowsYouCanUseKeyboard = true;
- if(window.gKnowsYouCanUseKeyboardTimeout) clearTimeout(gKnowsYouCanUseKeyboardTimeout);
- if(localStorage) localStorage.knowsYouCanUseKeyboard = true;
- if(window.gKnowsYouCanUseKeyboardNotification) gKnowsYouCanUseKeyboardNotification.close();
- }
- evt.preventDefault();
- evt.stopPropagation();
- return false;
- } else if(code == 20) { // Caps Lock
- capsLockKey = true;
- evt.preventDefault();
- } else if(code === 0x20) { // Space Bar
- pressSustain();
- evt.preventDefault();
- } else if((code === 38) && transpose_up < 3) {
- ++transpose_up;
- } else if((code === 40) && transpose_up > -2) {
- --transpose_up;
- } else if((code === 39) && transpose_down < 3) {
- ++transpose_down;
- } else if((code === 37) && transpose_down > -2) {
- --transpose_down;
- } else if(code == 9) { // Tab (don't tab away from the piano)
- evt.preventDefault();
- } else if(code == 8) { // Backspace (don't navigate Back)
- gAutoSustain = !gAutoSustain;
- evt.preventDefault();
- }
- };
- function handleKeyUp(evt) {
- var code = parseInt(evt.keyCode);
- if(key_binding[code] !== undefined) {
- var binding = key_binding[code];
- if(binding.held) {
- binding.held = false;
- var note = binding.note;
- var octave = 1 + note.octave + transpose_octave;
- if(evt.shiftKey) ++octave;
- else if(capsLockKey || evt.ctrlKey) --octave;
- note = note.note + octave;
- release(note);
- }
- evt.preventDefault();
- evt.stopPropagation();
- return false;
- } else if(code == 20) { // Caps Lock
- capsLockKey = false;
- evt.preventDefault();
- } else if(code === 0x20) { // Space Bar
- releaseSustain();
- evt.preventDefault();
- }
- };
- function handleKeyPress(evt) {
- evt.preventDefault();
- evt.stopPropagation();
- if(evt.keyCode == 27 || evt.keyCode == 13) {
- //$("#chat input").focus();
- }
- return false;
- };
- var recapListener = function(evt) {
- captureKeyboard();
- };
- function captureKeyboard() {
- $("#piano").off("mousedown", recapListener);
- $("#piano").off("touchstart", recapListener);
- $(document).on("keydown", handleKeyDown );
- $(document).on("keyup", handleKeyUp);
- $(window).on("keypress", handleKeyPress );
- };
- function releaseKeyboard() {
- $(document).off("keydown", handleKeyDown );
- $(document).off("keyup", handleKeyUp);
- $(window).off("keypress", handleKeyPress );
- $("#piano").on("mousedown", recapListener);
- $("#piano").on("touchstart", recapListener);
- };
- captureKeyboard();
- velocityFromMouseY = function() {
- return 0.1 + (my / 100) * 0.6;
- };
- // NoteQuota
- var gNoteQuota = (function() {
- var last_rat = 0;
- var nqjq = $("#quota .value");
- setInterval(function() {
- gNoteQuota.tick();
- }, 2000);
- return new NoteQuota(function(points) {
- // update UI
- var rat = (points / this.max) * 100;
- if(rat <= last_rat)
- nqjq.stop(true, true).css("width", rat.toFixed(0) + "%");
- else
- nqjq.stop(true, true).animate({"width": rat.toFixed(0) + "%"}, 2000, "linear");
- last_rat = rat;
- });
- })();
- gClient.on("nq", function(nq_params) {
- gNoteQuota.setParams(nq_params);
- });
- gClient.on("disconnect", function() {
- gNoteQuota.setParams(NoteQuota.PARAMS_OFFLINE);
- });
- // click participant names
- (function() {
- var ele = document.getElementById("names");
- var touchhandler = function(e) {
- var target_jq = $(e.target);
- if(target_jq.hasClass("name")) {
- target_jq.addClass("play");
- if(e.target.participantId == gClient.participantId) {
- openModal("#rename", "input[name=name]");
- setTimeout(function() {
- $("#rename input[name=name]").val(gClient.ppl[gClient.participantId].name);
- $("#rename input[name=color]").val(gClient.ppl[gClient.participantId].color);
- }, 100);
- } else if(e.target.participantId) {
- var id = e.target.participantId;
- var part = gClient.ppl[id] || null;
- if(part) {
- participantMenu(part);
- e.stopPropagation();
- }
- }
- }
- };
- ele.addEventListener("mousedown", touchhandler);
- ele.addEventListener("touchstart", touchhandler);
- var releasehandler = function(e) {
- $("#names .name").removeClass("play");
- };
- document.body.addEventListener("mouseup", releasehandler);
- document.body.addEventListener("touchend", releasehandler);
- var removeParticipantMenus = function() {
- $(".participant-menu").remove();
- $(".participantSpotlight").hide();
- document.removeEventListener("mousedown", removeParticipantMenus);
- document.removeEventListener("touchstart", removeParticipantMenus);
- };
- var participantMenu = function(part) {
- if(!part) return;
- removeParticipantMenus();
- document.addEventListener("mousedown", removeParticipantMenus);
- document.addEventListener("touchstart", removeParticipantMenus);
- $("#" + part.id).find(".enemySpotlight").show();
- var menu = $('<div class="participant-menu"></div>');
- $("body").append(menu);
- // move menu to name position
- var jq_nd = $(part.nameDiv);
- var pos = jq_nd.position();
- menu.css({
- "top": pos.top + jq_nd.height() + 15,
- "left": pos.left + 6,
- "background": part.color || "black"
- });
- menu.on("mousedown touchstart", function(evt) {
- evt.stopPropagation();
- var target = $(evt.target);
- if(target.hasClass("menu-item")) {
- target.addClass("clicked");
- menu.fadeOut(200, function() {
- removeParticipantMenus();
- });
- }
- });
- // this spaces stuff out but also can be used for informational
- $('<div class="info"></div>').appendTo(menu).text(part._id);
- // add menu items
- if(gPianoMutes.indexOf(part._id) == -1) {
- $('<div class="menu-item">Mute Notes</div>').appendTo(menu)
- .on("mousedown touchstart", function(evt) {
- gPianoMutes.push(part._id);
- $(part.nameDiv).addClass("muted-notes");
- });
- } else {
- $('<div class="menu-item">Unmute Notes</div>').appendTo(menu)
- .on("mousedown touchstart", function(evt) {
- var i;
- while((i = gPianoMutes.indexOf(part._id)) != -1)
- gPianoMutes.splice(i, 1);
- $(part.nameDiv).removeClass("muted-notes");
- });
- }
- if(gChatMutes.indexOf(part._id) == -1) {
- $('<div class="menu-item">Mute Chat</div>').appendTo(menu)
- .on("mousedown touchstart", function(evt) {
- gChatMutes.push(part._id);
- $(part.nameDiv).addClass("muted-chat");
- });
- } else {
- $('<div class="menu-item">Unmute Chat</div>').appendTo(menu)
- .on("mousedown touchstart", function(evt) {
- var i;
- while((i = gChatMutes.indexOf(part._id)) != -1)
- gChatMutes.splice(i, 1);
- $(part.nameDiv).removeClass("muted-chat");
- });
- }
- if(!(gPianoMutes.indexOf(part._id) >= 0) || !(gChatMutes.indexOf(part._id) >= 0)) {
- $('<div class="menu-item">Mute Completely</div>').appendTo(menu)
- .on("mousedown touchstart", function(evt) {
- gPianoMutes.push(part._id);
- gChatMutes.push(part._id);
- $(part.nameDiv).addClass("muted-notes");
- $(part.nameDiv).addClass("muted-chat");
- });
- }
- if((gPianoMutes.indexOf(part._id) >= 0) || (gChatMutes.indexOf(part._id) >= 0)) {
- $('<div class="menu-item">Unmute Completely</div>').appendTo(menu)
- .on("mousedown touchstart", function(evt) {
- var i;
- while((i = gPianoMutes.indexOf(part._id)) != -1)
- gPianoMutes.splice(i, 1);
- while((i = gChatMutes.indexOf(part._id)) != -1)
- gChatMutes.splice(i, 1);
- $(part.nameDiv).removeClass("muted-notes");
- $(part.nameDiv).removeClass("muted-chat");
- });
- }
- if(gClient.isOwner()) {
- $('<div class="menu-item give-crown">Give Crown</div>').appendTo(menu)
- .on("mousedown touchstart", function(evt) {
- if(confirm("Give room ownership to "+part.name+"?"))
- gClient.sendArray([{m: "chown", id: part.id}]);
- });
- $('<div class="menu-item kickban">Kickban</div>').appendTo(menu)
- .on("mousedown touchstart", function(evt) {
- var minutes = prompt("How many minutes? (0-60)", "30");
- if(minutes === null) return;
- minutes = parseFloat(minutes) || 0;
- var ms = minutes * 60 * 1000;
- gClient.sendArray([{m: "kickban", _id: part._id, ms: ms}]);
- });
- }
- menu.fadeIn(100);
- };
- })();
- // Notification class
- ////////////////////////////////////////////////////////////////
- var Notification = function(par) {
- EventEmitter.call(this);
- var par = par || {};
- this.id = "Notification-" + (par.id || Math.random());
- this.title = par.title || "";
- this.text = par.text || "";
- this.html = par.html || "";
- this.target = $(par.target || "#piano");
- this.duration = par.duration || 30000;
- this["class"] = par["class"] || "classic";
- var self = this;
- var eles = $("#" + this.id);
- if(eles.length > 0) {
- eles.remove();
- }
- this.domElement = $('<div class="notification"><div class="notification-body"><div class="title"></div>' +
- '<div class="text"></div></div><div class="x">x</div></div>');
- this.domElement[0].id = this.id;
- this.domElement.addClass(this["class"]);
- this.domElement.find(".title").text(this.title);
- if(this.text.length > 0) {
- this.domElement.find(".text").text(this.text);
- } else if(this.html instanceof HTMLElement) {
- this.domElement.find(".text")[0].appendChild(this.html);
- } else if(this.html.length > 0) {
- this.domElement.find(".text").html(this.html);
- }
- document.body.appendChild(this.domElement.get(0));
- this.position();
- this.onresize = function() {
- self.position();
- };
- window.addEventListener("resize", this.onresize);
- this.domElement.find(".x").click(function() {
- self.close();
- });
- if(this.duration > 0) {
- setTimeout(function() {
- self.close();
- }, this.duration);
- }
- return this;
- }
- mixin(Notification.prototype, EventEmitter.prototype);
- Notification.prototype.constructor = Notification;
- Notification.prototype.position = function() {
- var pos = this.target.offset();
- var x = pos.left - (this.domElement.width() / 2) + (this.target.width() / 4);
- var y = pos.top - this.domElement.height() - 8;
- var width = this.domElement.width();
- if(x + width > $("body").width()) {
- x -= ((x + width) - $("body").width());
- }
- if(x < 0) x = 0;
- this.domElement.offset({left: x, top: y});
- };
- Notification.prototype.close = function() {
- var self = this;
- window.removeEventListener("resize", this.onresize);
- this.domElement.fadeOut(500, function() {
- self.domElement.remove();
- self.emit("close");
- });
- };
- // set variables from settings or set settings
- ////////////////////////////////////////////////////////////////
- var gKeyboardSeq = 0;
- var gKnowsYouCanUseKeyboard = false;
- if(localStorage && localStorage.knowsYouCanUseKeyboard) gKnowsYouCanUseKeyboard = true;
- if(!gKnowsYouCanUseKeyboard) {
- window.gKnowsYouCanUseKeyboardTimeout = setTimeout(function() {
- window.gKnowsYouCanUseKeyboardNotification = new Notification({title: "Did you know!?!",
- text: "You can play the piano with your keyboard, too. Try it!", target: "#piano", duration: 10000});
- }, 30000);
- }
- if(window.localStorage) {
- if(localStorage.volume) {
- volume_slider.value = localStorage.volume;
- gPiano.audio.setVolume(localStorage.volume);
- $("#volume-label").text("Volume: " + Math.floor(gPiano.audio.volume * 100) + "%");
- }
- else localStorage.volume = gPiano.audio.volume;
- window.gHasBeenHereBefore = (localStorage.gHasBeenHereBefore || false);
- if(gHasBeenHereBefore) {
- }
- localStorage.gHasBeenHereBefore = true;
- }
- // warn user about loud noises before starting sound (no autoplay)
- openModal("#sound-warning");
- var user_interact = function(evt) {
- document.removeEventListener("click", user_interact);
- closeModal();
- MPP.piano.audio.resume();
- }
- document.addEventListener("click", user_interact);
- // New room, change room
- ////////////////////////////////////////////////////////////////
- $("#room > .info").text("--");
- gClient.on("ch", function(msg) {
- var channel = msg.ch;
- var info = $("#room > .info");
- info.text(channel._id);
- if(channel.settings.lobby) info.addClass("lobby");
- else info.removeClass("lobby");
- if(!channel.settings.chat) info.addClass("no-chat");
- else info.removeClass("no-chat");
- if(channel.settings.crownsolo) info.addClass("crownsolo");
- else info.removeClass("crownsolo");
- if(!channel.settings.visible) info.addClass("not-visible");
- else info.removeClass("not-visible");
- });
- gClient.on("ls", function(ls) {
- for(var i in ls.u) {
- if(!ls.u.hasOwnProperty(i)) continue;
- var room = ls.u[i];
- var info = $("#room .info[roomname=\"" + (room._id + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0') + "\"]");
- if(info.length == 0) {
- info = $("<div class=\"info\"></div>");
- info.attr("roomname", room._id);
- $("#room .more").append(info);
- }
- info.text(room._id + " (" + room.count + ")");
- if(room.settings.lobby) info.addClass("lobby");
- else info.removeClass("lobby");
- if(!room.settings.chat) info.addClass("no-chat");
- else info.removeClass("no-chat");
- if(room.settings.crownsolo) info.addClass("crownsolo");
- else info.removeClass("crownsolo");
- if(!room.settings.visible) info.addClass("not-visible");
- else info.removeClass("not-visible");
- if(room.banned) info.addClass("banned");
- else info.removeClass("banned");
- }
- });
- $("#room").on("click", function(evt) {
- evt.stopPropagation();
- // clicks on a new room
- if($(evt.target).hasClass("info") && $(evt.target).parents(".more").length) {
- $("#room .more").fadeOut(250);
- var selected_name = $(evt.target).attr("roomname");
- if(typeof selected_name != "undefined") {
- changeRoom(selected_name, "right");
- }
- return false;
- }
- // clicks on "New Room..."
- else if($(evt.target).hasClass("new")) {
- openModal("#new-room", "input[name=name]");
- }
- // all other clicks
- var doc_click = function(evt) {
- if($(evt.target).is("#room .more")) return;
- $(document).off("mousedown", doc_click);
- $("#room .more").fadeOut(250);
- gClient.sendArray([{m: "-ls"}]);
- }
- $(document).on("mousedown", doc_click);
- $("#room .more .info").remove();
- $("#room .more").show();
- gClient.sendArray([{m: "+ls"}]);
- });
- $("#new-room-btn").on("click", function(evt) {
- evt.stopPropagation();
- openModal("#new-room", "input[name=name]");
- });
- $("#play-alone-btn").on("click", function(evt) {
- evt.stopPropagation();
- var room_name = "Room" + Math.floor(Math.random() * 1000000000000);
- changeRoom(room_name, "right", {"visible": false, "chat": true, "crownsolo": false});
- setTimeout(function() {
- new Notification({id: "share", title: "Playing alone", html: 'You are playing alone in a room by yourself, but you can always invite \
- friends by sending them the link.<br/><br/>\
- <a href="#" onclick="window.open(\'https://www.facebook.com/sharer/sharer.php?u=\'+encodeURIComponent(location.href),\'facebook-share-dialog\',\'width=626,height=436\');return false;">Share on Facebook</a><br/><br/>\
- <a href="http://twitter.com/home?status='+encodeURIComponent(location.href)+'" target="_blank">Tweet</a>', duration: 25000});
- }, 1000);
- });
- var gModal;
- function modalHandleEsc(evt) {
- if(evt.keyCode == 27) {
- closeModal();
- evt.preventDefault();
- evt.stopPropagation();
- }
- };
- function openModal(selector, focus) {
- if(chat) chat.blur();
- releaseKeyboard();
- $(document).on("keydown", modalHandleEsc);
- $("#modal #modals > *").hide();
- $("#modal").fadeIn(250);
- $(selector).show();
- setTimeout(function() {
- $(selector).find(focus).focus();
- }, 100);
- gModal = selector;
- };
- function closeModal() {
- $(document).off("keydown", modalHandleEsc);
- $("#modal").fadeOut(100);
- $("#modal #modals > *").hide();
- captureKeyboard();
- gModal = null;
- };
- var modal_bg = $("#modal .bg")[0];
- $(modal_bg).on("click", function(evt) {
- if(evt.target != modal_bg) return;
- closeModal();
- });
- (function() {
- function submit() {
- var name = $("#new-room .text[name=name]").val();
- var settings = {
- visible: $("#new-room .checkbox[name=visible]").is(":checked"),
- chat: true,
- crownsolo: false
- };
- $("#new-room .text[name=name]").val("");
- closeModal();
- changeRoom(name, "right", settings);
- setTimeout(function() {
- new Notification({id: "share", title: "Created a Room", html: 'You can invite friends to your room by sending them the link.<br/><br/>\
- <a href="#" onclick="window.open(\'https://www.facebook.com/sharer/sharer.php?u=\'+encodeURIComponent(location.href),\'facebook-share-dialog\',\'width=626,height=436\');return false;">Share on Facebook</a><br/><br/>\
- <a href="http://twitter.com/home?status='+encodeURIComponent(location.href)+'" target="_blank">Tweet</a>', duration: 25000});
- }, 1000);
- };
- $("#new-room .submit").click(function(evt) {
- submit();
- });
- $("#new-room .text[name=name]").keypress(function(evt) {
- if(evt.keyCode == 13) {
- submit();
- } else if(evt.keyCode == 27) {
- closeModal();
- } else {
- return;
- }
- evt.preventDefault();
- evt.stopPropagation();
- return false;
- });
- })();
- function changeRoom(name, direction, settings, push) {
- if(!settings) settings = {};
- if(!direction) direction = "right";
- if(typeof push == "undefined") push = true;
- var opposite = direction == "left" ? "right" : "left";
- if(name == "") name = "lobby";
- if(gClient.channel && gClient.channel._id === name) return;
- if(push) {
- var url = "/" + encodeURIComponent(name).replace("'", "%27");
- if(window.history && history.pushState) {
- history.pushState({"depth": gHistoryDepth += 1, "name": name}, "Piano > " + name, url);
- } else {
- window.location = url;
- return;
- }
- }
- gClient.setChannel(name, settings);
- var t = 0, d = 100;
- $("#piano").addClass("ease-out").addClass("slide-" + opposite);
- setTimeout(function() {
- $("#piano").removeClass("ease-out").removeClass("slide-" + opposite).addClass("slide-" + direction);
- }, t += d);
- setTimeout(function() {
- $("#piano").addClass("ease-in").removeClass("slide-" + direction);
- }, t += d);
- setTimeout(function() {
- $("#piano").removeClass("ease-in");
- }, t += d);
- };
- var gHistoryDepth = 0;
- $(window).on("popstate", function(evt) {
- var depth = evt.state ? evt.state.depth : 0;
- if(depth == gHistoryDepth) return; // <-- forgot why I did that though...
- var direction = depth <= gHistoryDepth ? "left" : "right";
- gHistoryDepth = depth;
- var name = decodeURIComponent(window.location.pathname);
- if(name.substr(0, 1) == "/") name = name.substr(1);
- changeRoom(name, direction, null, false);
- });
- // Rename
- ////////////////////////////////////////////////////////////////
- (function() {
- function submit() {
- var set = {
- name: $("#rename input[name=name]").val(),
- color: $("#rename input[name=color]").val()
- };
- //$("#rename .text[name=name]").val("");
- closeModal();
- gClient.sendArray([{m: "userset", set: set}]);
- };
- $("#rename .submit").click(function(evt) {
- submit();
- });
- $("#rename .text[name=name]").keypress(function(evt) {
- if(evt.keyCode == 13) {
- submit();
- } else if(evt.keyCode == 27) {
- closeModal();
- } else {
- return;
- }
- evt.preventDefault();
- evt.stopPropagation();
- return false;
- });
- })();
- // chatctor
- ////////////////////////////////////////////////////////////////
- msgBuffer = [];msgVirtualQuota = 3;mvq = setInterval(function(){if(msgVirtualQuota<3){msgVirtualQuota++}},2500);
- var chat = (function() {
- gClient.on("ch", function(msg) {
- if(msg.ch.settings.chat) {
- chat.show();
- } else {
- chat.hide();
- }
- });
- gClient.on("disconnect", function(msg) {
- chat.hide();
- });
- gClient.on("c", function(msg) {
- chat.clear();
- if(msg.c) {
- for(var i = 0; i < msg.c.length; i++) {
- chat.receive(msg.c[i]);
- }
- }
- });
- gClient.on("a", function(msg) {
- chat.receive(msg);
- });
- $("#chat input").on("focus", function(evt) {
- releaseKeyboard();
- $("#chat").addClass("chatting");
- chat.scrollToBottom();
- });
- /*$("#chat input").on("blur", function(evt) {
- captureKeyboard();
- $("#chat").removeClass("chatting");
- chat.scrollToBottom();
- });*/
- $(document).mousedown(function(evt) {
- if(!$("#chat").has(evt.target).length > 0) {
- chat.blur();
- }
- });
- document.addEventListener("touchstart", function(event) {
- for(var i in event.changedTouches) {
- var touch = event.changedTouches[i];
- if(!$("#chat").has(touch.target).length > 0) {
- chat.blur();
- }
- }
- });
- $(document).on("keydown", function(evt) {
- if($("#chat").hasClass("chatting")) {
- if(evt.keyCode == 27) {
- chat.blur();
- evt.preventDefault();
- evt.stopPropagation();
- } else if(evt.keyCode == 13) {
- $("#chat input").focus();
- }
- } else if(!gModal && (evt.keyCode == 27 || evt.keyCode == 13)) {
- $("#chat input").focus();
- }
- });
- $("#chat input").on("keydown", function(evt) {
- if(evt.keyCode == 13) {
- var message = $(this).val();
- if(message.length == 0) {
- setTimeout(function() {
- chat.blur();
- }, 100);
- } else if(message.length <= 512) {
- chat.send(message);
- $(this).val("");
- setTimeout(function() {
- chat.blur();
- }, 100);
- }
- evt.preventDefault();
- evt.stopPropagation();
- } else if(evt.keyCode == 27) {
- chat.blur();
- evt.preventDefault();
- evt.stopPropagation();
- } else if(evt.keyCode == 9) {
- evt.preventDefault();
- evt.stopPropagation();
- }
- });
- return {
- show: function() {
- $("#chat").fadeIn();
- },
- hide: function() {
- $("#chat").fadeOut();
- },
- clear: function() {
- $("#chat li").remove();
- },
- scrollToBottom: function() {
- var ele = $("#chat ul").get(0);
- ele.scrollTop = ele.scrollHeight;
- },
- blur: function() {
- if($("#chat").hasClass("chatting")) {
- $("#chat input").get(0).blur();
- $("#chat").removeClass("chatting");
- chat.scrollToBottom();
- captureKeyboard();
- }
- },
- send: function(message,b) {
- if(b){
- gClient.sendArray([{m:"a", message: message}]);
- }else{
- if(typeof message == 'string' && message.length<2048 && msgBuffer.length<16)
- if(message.length<512){var msg = message;var multi = -1;while((msg+';'+msgBuffer.slice(0,multi+1).join(';')).length<512 && multi+1<msgBuffer.length){multi++};
- if(multi==-1){msgBuffer.push(msg)}else{msgBuffer = msgBuffer.slice(multi);msgBuffer[0] = msgBuffer.slice(0,multi+1).reverse().join(';')+';'+msg}}
- else
- {var msg = message;while(msg.length>512){msgBuffer.push(msg.slice(0,500)+'...');msg = msg.slice(500)};msgBuffer.push(msg)}
- if(msgVirtualQuota>0 && message == undefined){gClient.sendArray([{m:"a", message: msgBuffer[0]}]);msgBuffer.shift();msgVirtualQuota--}
- if(msgBuffer.length>0 || message!==undefined){setTimeout(MPP.chat.send,250)};
- };
- },
- receive: function(msg) {
- if(gChatMutes.indexOf(msg.p._id) != -1) return;
- var li = $('<li><span class="name"/><span class="message"/>');
- li.find(".name").text(msg.p.name + ":");
- li.find(".message").text(msg.a);
- li.css("color", msg.p.color || "white");
- $("#chat ul").append(li);
- var eles = $("#chat ul li").get();
- for(var i = 1; i <= 50 && i <= eles.length; i++) {
- eles[eles.length - i].style.opacity = 1.0 - (i * 0.03);
- }
- if(eles.length > 50) {
- eles[0].style.display = "none";
- }
- if(eles.length > 256) {
- $(eles[0]).remove();
- }
- // scroll to bottom if not "chatting" or if not scrolled up
- if(!$("#chat").hasClass("chatting")) {
- chat.scrollToBottom();
- } else {
- var ele = $("#chat ul").get(0);
- if(ele.scrollTop > ele.scrollHeight - ele.offsetHeight - 50)
- chat.scrollToBottom();
- }
- }
- };
- })();
- // MIDI
- ////////////////////////////////////////////////////////////////
- var MIDI_TRANSPOSE = -12;
- var MIDI_KEY_NAMES = ["a-1", "as-1", "b-1"];
- var bare_notes = "c cs d ds e f fs g gs a as b".split(" ");
- for(var oct = 0; oct < 7; oct++) {
- for(var i in bare_notes) {
- MIDI_KEY_NAMES.push(bare_notes[i] + oct);
- }
- }
- MIDI_KEY_NAMES.push("c7");
- var devices_json;
- function sendDevices() {
- gClient.sendArray([{"m": "devices", "list": JSON.parse(devices_json)}]);
- }
- gClient.on("connect", sendDevices);
- (function() {
- if (navigator.requestMIDIAccess) {
- navigator.requestMIDIAccess().then(
- function(midi) {
- console.log(midi);
- function midimessagehandler(evt) {
- if(!evt.target.enabled) return;
- //console.log(evt);
- var channel = evt.data[0] & 0xf;
- var cmd = evt.data[0] >> 4;
- var note_number = evt.data[1];
- var vel = evt.data[2];
- //console.log(channel, cmd, note_number, vel);
- if(cmd == 8 || (cmd == 9 && vel == 0)) {
- // NOTE_OFF
- release(MIDI_KEY_NAMES[note_number - 9 + MIDI_TRANSPOSE]);
- } else if(cmd == 9) {
- // NOTE_ON
- press(MIDI_KEY_NAMES[note_number - 9 + MIDI_TRANSPOSE], vel / 100);
- } else if(cmd == 11) {
- // CONTROL_CHANGE
- if(!gAutoSustain) {
- if(note_number == 64) {
- if(vel > 0) {
- pressSustain();
- } else {
- releaseSustain();
- }
- }
- }
- }
- }
- function deviceInfo(dev) {
- return {
- type: dev.type,
- //id: dev.id,
- manufacturer: dev.manufacturer,
- name: dev.name,
- version: dev.version,
- //connection: dev.connection,
- //state: dev.state,
- enabled: dev.enabled
- };
- }
- function updateDevices() {
- var list = [];
- if(midi.inputs.size > 0) {
- var inputs = midi.inputs.values();
- for(var input_it = inputs.next(); input_it && !input_it.done; input_it = inputs.next()) {
- var input = input_it.value;
- list.push(deviceInfo(input));
- }
- }
- if(midi.outputs.size > 0) {
- var outputs = midi.outputs.values();
- for(var output_it = outputs.next(); output_it && !output_it.done; output_it = outputs.next()) {
- var output = output_it.value;
- list.push(deviceInfo(output));
- }
- }
- var new_json = JSON.stringify(list);
- if(new_json !== devices_json) {
- devices_json = new_json;
- sendDevices();
- }
- }
- function plug() {
- if(midi.inputs.size > 0) {
- var inputs = midi.inputs.values();
- for(var input_it = inputs.next(); input_it && !input_it.done; input_it = inputs.next()) {
- var input = input_it.value;
- //input.removeEventListener("midimessage", midimessagehandler);
- //input.addEventListener("midimessage", midimessagehandler);
- input.onmidimessage = midimessagehandler;
- if(input.enabled !== false) {
- input.enabled = true;
- localSound = false;
- MPP.chat.send("MIDI input detected. Local sound is off.")
- }
- console.log("input", input);
- }
- }
- if(midi.outputs.size > 0) {
- var outputs = midi.outputs.values();
- for(var output_it = outputs.next(); output_it && !output_it.done; output_it = outputs.next()) {
- var output = output_it.value;
- //output.enabled = false; // edit: don't touch
- console.log("output", output);
- }
- gMidiOutTest = function(note_name, vel, delay_ms) {
- var note_number = MIDI_KEY_NAMES.indexOf(note_name);
- if(note_number == -1) return;
- note_number = note_number + 9 - MIDI_TRANSPOSE;
- var outputs = midi.outputs.values();
- for(var output_it = outputs.next(); output_it && !output_it.done; output_it = outputs.next()) {
- var output = output_it.value;
- if(output.enabled) {
- output.send([0x90, note_number, vel], window.performance.now() + delay_ms);
- }
- }
- }
- }
- showConnections(false);
- updateDevices();
- }
- midi.addEventListener("statechange", function(evt) {
- if(evt instanceof MIDIConnectionEvent) {
- plug();
- }
- });
- plug();
- var connectionsNotification;
- function showConnections(sticky) {
- //if(document.getElementById("Notification-MIDI-Connections"))
- //sticky = 1; // todo: instead,
- var inputs_ul = document.createElement("ul");
- if(midi.inputs.size > 0) {
- var inputs = midi.inputs.values();
- for(var input_it = inputs.next(); input_it && !input_it.done; input_it = inputs.next()) {
- var input = input_it.value;
- var li = document.createElement("li");
- li.connectionId = input.id;
- li.classList.add("connection");
- if(input.enabled) li.classList.add("enabled");
- li.textContent = input.name;
- li.addEventListener("click", function(evt) {
- var inputs = midi.inputs.values();
- for(var input_it = inputs.next(); input_it && !input_it.done; input_it = inputs.next()) {
- var input = input_it.value;
- if(input.id === evt.target.connectionId) {
- input.enabled = !input.enabled;
- evt.target.classList.toggle("enabled");
- console.log("click", input);
- updateDevices();
- return;
- }
- }
- });
- inputs_ul.appendChild(li);
- }
- } else {
- inputs_ul.textContent = "(none)";
- }
- var outputs_ul = document.createElement("ul");
- if(midi.outputs.size > 0) {
- var outputs = midi.outputs.values();
- for(var output_it = outputs.next(); output_it && !output_it.done; output_it = outputs.next()) {
- var output = output_it.value;
- var li = document.createElement("li");
- li.connectionId = output.id;
- li.classList.add("connection");
- if(output.enabled) li.classList.add("enabled");
- li.textContent = output.name;
- li.addEventListener("click", function(evt) {
- var outputs = midi.outputs.values();
- for(var output_it = outputs.next(); output_it && !output_it.done; output_it = outputs.next()) {
- var output = output_it.value;
- if(output.id === evt.target.connectionId) {
- output.enabled = !output.enabled;
- evt.target.classList.toggle("enabled");
- console.log("click", output);
- updateDevices();
- return;
- }
- }
- });
- outputs_ul.appendChild(li);
- }
- } else {
- outputs_ul.textContent = "(none)";
- }
- var div = document.createElement("div");
- var h1 = document.createElement("h1");
- h1.textContent = "Inputs";
- div.appendChild(h1);
- div.appendChild(inputs_ul);
- h1 = document.createElement("h1");
- h1.textContent = "Outputs";
- div.appendChild(h1);
- div.appendChild(outputs_ul);
- connectionsNotification = new Notification({"id":"MIDI-Connections", "title":"MIDI Connections","duration":sticky?"-1":"4500","html":div,"target":"#midi-btn"});
- }
- document.getElementById("midi-btn").addEventListener("click", function(evt) {
- if(!document.getElementById("Notification-MIDI-Connections"))
- showConnections(true);
- else {
- connectionsNotification.close();
- }
- });
- },
- function(err){
- console.log(err);
- } );
- }
- })();
- // bug supply
- ////////////////////////////////////////////////////////////////
- window.onerror = function(message, url, line) {
- var url = url || "(no url)";
- var line = line || "(no line)";
- // errors in socket.io
- if(url.indexOf("socket.io.js") !== -1) {
- if(message.indexOf("INVALID_STATE_ERR") !== -1) return;
- if(message.indexOf("InvalidStateError") !== -1) return;
- if(message.indexOf("DOM Exception 11") !== -1) return;
- if(message.indexOf("Property 'open' of object #<c> is not a function") !== -1) return;
- if(message.indexOf("Cannot call method 'close' of undefined") !== -1) return;
- if(message.indexOf("Cannot call method 'close' of null") !== -1) return;
- if(message.indexOf("Cannot call method 'onClose' of null") !== -1) return;
- if(message.indexOf("Cannot call method 'payload' of null") !== -1) return;
- if(message.indexOf("Unable to get value of the property 'close'") !== -1) return;
- if(message.indexOf("NS_ERROR_NOT_CONNECTED") !== -1) return;
- if(message.indexOf("Unable to get property 'close' of undefined or null reference") !== -1) return;
- if(message.indexOf("Unable to get value of the property 'close': object is null or undefined") !== -1) return;
- if(message.indexOf("this.transport is null") !== -1) return;
- }
- // errors in soundmanager2
- if(url.indexOf("soundmanager2.js") !== -1) {
- // operation disabled in safe mode?
- if(message.indexOf("Could not complete the operation due to error c00d36ef") !== -1) return;
- if(message.indexOf("_s.o._setVolume is not a function") !== -1) return;
- }
- // errors in midibridge
- if(url.indexOf("midibridge") !== -1) {
- if(message.indexOf("Error calling method on NPObject") !== -1) return;
- }
- // too many failing extensions injected in my html
- if(url.indexOf(".js") !== url.length - 3) return;
- // extensions inject cross-domain embeds too
- if(url.toLowerCase().indexOf("multiplayerpiano.com") == -1) return;
- // errors in my code
- if(url.indexOf("script.js") !== -1) {
- if(message.indexOf("Object [object Object] has no method 'on'") !== -1) return;
- if(message.indexOf("Object [object Object] has no method 'off'") !== -1) return;
- if(message.indexOf("Property '$' of object [object Object] is not a function") !== -1) return;
- }
- var enc = "/bugreport/"
- + (message ? encodeURIComponent(message) : "") + "/"
- + (url ? encodeURIComponent(url) : "") + "/"
- + (line ? encodeURIComponent(line) : "");
- var img = new Image();
- img.src = enc;
- };
- // API
- window.MPP = {
- press: press,
- release: release,
- piano: gPiano,
- client: gClient,
- chat: chat,
- noteQuota: gNoteQuota,
- soundSelector: gSoundSelector
- };
- // record mp3
- (function() {
- var button = document.querySelector("#record-btn");
- var audio = MPP.piano.audio;
- var context = audio.context;
- var encoder_sample_rate = 44100;
- var encoder_kbps = 128;
- var encoder = null;
- var scriptProcessorNode = context.createScriptProcessor(4096, 2, 2);
- var recording = false;
- var recording_start_time = 0;
- var mp3_buffer = [];
- button.addEventListener("click", function(evt) {
- if(!recording) {
- // start recording
- mp3_buffer = [];
- encoder = new lamejs.Mp3Encoder(2, encoder_sample_rate, encoder_kbps);
- scriptProcessorNode.onaudioprocess = onAudioProcess;
- audio.masterGain.connect(scriptProcessorNode);
- scriptProcessorNode.connect(context.destination);
- recording_start_time = Date.now();
- recording = true;
- button.textContent = "Stop Recording";
- button.classList.add("stuck");
- new Notification({"id": "mp3", "title": "Recording MP3...", "html": "It's recording now. This could make things slow, maybe. Maybe give it a moment to settle before playing.<br><br>This feature is experimental.<br>Send complaints to <a href=\"mailto:[email protected]\">[email protected]</a>.", "duration": 10000});
- } else {
- // stop recording
- var mp3buf = encoder.flush();
- mp3_buffer.push(mp3buf);
- var blob = new Blob(mp3_buffer, {type: "audio/mp3"});
- var url = URL.createObjectURL(blob);
- scriptProcessorNode.onaudioprocess = null;
- audio.masterGain.disconnect(scriptProcessorNode);
- scriptProcessorNode.disconnect(context.destination);
- recording = false;
- button.textContent = "Record MP3";
- button.classList.remove("stuck");
- new Notification({"id": "mp3", "title": "MP3 recording finished", "html": "<a href=\""+url+"\" target=\"blank\">And here it is!</a> (open or save as)<br><br>This feature is experimental.<br>Send complaints to <a href=\"mailto:[email protected]\">[email protected]</a>.", "duration": 0});
- }
- });
- function onAudioProcess(evt) {
- var inputL = evt.inputBuffer.getChannelData(0);
- var inputR = evt.inputBuffer.getChannelData(1);
- var mp3buf = encoder.encodeBuffer(convert16(inputL), convert16(inputR));
- mp3_buffer.push(mp3buf);
- }
- function convert16(samples) {
- var len = samples.length;
- var result = new Int16Array(len);
- for(var i = 0; i < len; i++) {
- result[i] = 0x8000 * samples[i];
- }
- return(result);
- }
- })();
- // synth
- var enableSynth = false;
- var audio = gPiano.audio;
- var context = gPiano.audio.context;
- var synth_gain = context.createGain();
- synth_gain.gain.value = 0.05;
- synth_gain.connect(audio.synthGain);
- var osc_types = ["sine", "square", "sawtooth", "triangle"];
- var osc_type_index = 1;
- var osc1_type = "square";
- var osc1_attack = 0;
- var osc1_decay = 0.2;
- var osc1_sustain = 0.5;
- var osc1_release = 2.0;
- function synthVoice(note_name, time) {
- var note_number = MIDI_KEY_NAMES.indexOf(note_name);
- note_number = note_number + 9 - MIDI_TRANSPOSE;
- var freq = Math.pow(2, (note_number - 69) / 12) * 440.0;
- this.osc = context.createOscillator();
- this.osc.type = osc1_type;
- this.osc.frequency.value = freq;
- this.gain = context.createGain();
- this.gain.gain.value = 0;
- this.osc.connect(this.gain);
- this.gain.connect(synth_gain);
- this.osc.start(time);
- this.gain.gain.setValueAtTime(0, time);
- this.gain.gain.linearRampToValueAtTime(1, time + osc1_attack);
- this.gain.gain.linearRampToValueAtTime(osc1_sustain, time + osc1_attack + osc1_decay);
- }
- synthVoice.prototype.stop = function(time) {
- //this.gain.gain.setValueAtTime(osc1_sustain, time);
- this.gain.gain.linearRampToValueAtTime(0, time + osc1_release);
- this.osc.stop(time + osc1_release);
- };
- (function() {
- var button = document.getElementById("synth-btn");
- var notification;
- button.addEventListener("click", function() {
- if(notification) {
- notification.close();
- } else {
- showSynth();
- }
- });
- function showSynth() {
- var html = document.createElement("div");
- // on/off button
- (function() {
- var button = document.createElement("input");
- mixin(button, {type: "button", value: "ON/OFF", className: enableSynth ? "switched-on" : "switched-off"});
- button.addEventListener("click", function(evt) {
- enableSynth = !enableSynth;
- button.className = enableSynth ? "switched-on" : "switched-off";
- if(!enableSynth) {
- // stop all
- for(var i in audio.playings) {
- if(!audio.playings.hasOwnProperty(i)) continue;
- var playing = audio.playings[i];
- if(playing && playing.voice) {
- playing.voice.osc.stop();
- playing.voice = undefined;
- }
- }
- }
- });
- html.appendChild(button);
- })();
- // mix
- var knob = document.createElement("canvas");
- mixin(knob, {width: 32 * window.devicePixelRatio, height: 32 * window.devicePixelRatio, className: "knob"});
- html.appendChild(knob);
- knob = new Knob(knob, 0, 100, 0.1, 50, "mix", "%");
- knob.canvas.style.width = "32px";
- knob.canvas.style.height = "32px";
- knob.on("change", function(k) {
- var mix = k.value / 100;
- audio.pianoGain.gain.value = 1 - mix;
- audio.synthGain.gain.value = mix;
- });
- knob.emit("change", knob);
- // osc1 type
- (function() {
- osc1_type = osc_types[osc_type_index];
- var button = document.createElement("input");
- mixin(button, {type: "button", value: osc_types[osc_type_index]});
- button.addEventListener("click", function(evt) {
- if(++osc_type_index >= osc_types.length) osc_type_index = 0;
- osc1_type = osc_types[osc_type_index];
- button.value = osc1_type;
- });
- html.appendChild(button);
- })();
- // osc1 attack
- var knob = document.createElement("canvas");
- mixin(knob, {width: 32 * window.devicePixelRatio, height: 32 * window.devicePixelRatio, className: "knob"});
- html.appendChild(knob);
- knob = new Knob(knob, 0, 1, 0.001, osc1_attack, "osc1 attack", "s");
- knob.canvas.style.width = "32px";
- knob.canvas.style.height = "32px";
- knob.on("change", function(k) {
- osc1_attack = k.value;
- });
- knob.emit("change", knob);
- // osc1 decay
- var knob = document.createElement("canvas");
- mixin(knob, {width: 32 * window.devicePixelRatio, height: 32 * window.devicePixelRatio, className: "knob"});
- html.appendChild(knob);
- knob = new Knob(knob, 0, 2, 0.001, osc1_decay, "osc1 decay", "s");
- knob.canvas.style.width = "32px";
- knob.canvas.style.height = "32px";
- knob.on("change", function(k) {
- osc1_decay = k.value;
- });
- knob.emit("change", knob);
- var knob = document.createElement("canvas");
- mixin(knob, {width: 32 * window.devicePixelRatio, height: 32 * window.devicePixelRatio, className: "knob"});
- html.appendChild(knob);
- knob = new Knob(knob, 0, 1, 0.001, osc1_sustain, "osc1 sustain", "x");
- knob.canvas.style.width = "32px";
- knob.canvas.style.height = "32px";
- knob.on("change", function(k) {
- osc1_sustain = k.value;
- });
- knob.emit("change", knob);
- // osc1 release
- var knob = document.createElement("canvas");
- mixin(knob, {width: 32 * window.devicePixelRatio, height: 32 * window.devicePixelRatio, className: "knob"});
- html.appendChild(knob);
- knob = new Knob(knob, 0, 2, 0.001, osc1_release, "osc1 release", "s");
- knob.canvas.style.width = "32px";
- knob.canvas.style.height = "32px";
- knob.on("change", function(k) {
- osc1_release = k.value;
- });
- knob.emit("change", knob);
- var div = document.createElement("div");
- div.innerHTML = "<br><br><br><br><center>this space intentionally left blank</center><br><br><br><br>";
- html.appendChild(div);
- // notification
- notification = new Notification({title: "Synthesize", html: html, duration: -1, target: "#synth-btn"});
- notification.on("close", function() {
- var tip = document.getElementById("tooltip");
- if(tip) tip.parentNode.removeChild(tip);
- notification = null;
- });
- }
- })();
- });
- // misc
- ////////////////////////////////////////////////////////////////
- // analytics
- window.google_analytics_uacct = "UA-882009-7";
- var _gaq = _gaq || [];
- _gaq.push(['_setAccount', 'UA-882009-7']);
- _gaq.push(['_trackPageview']);
- _gaq.push(['_setAllowAnchor', true]);
- (function() {
- var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
- ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
- var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
- })();
- // twitter
- !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;
- js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
- // fb
- (function(d, s, id) {
- var js, fjs = d.getElementsByTagName(s)[0];
- if (d.getElementById(id)) return;
- js = d.createElement(s); js.id = id;
- js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.8";
- fjs.parentNode.insertBefore(js, fjs);
- }(document, 'script', 'facebook-jssdk'));
- // non-ad-free experience
- /*(function() {
- function adsOn() {
- if(window.localStorage) {
- var div = document.querySelector("#inclinations");
- div.innerHTML = "Ads:<br>ON / <a id=\"adsoff\" href=\"#\">OFF</a>";
- div.querySelector("#adsoff").addEventListener("click", adsOff);
- localStorage.ads = true;
- }
- // adsterra
- var script = document.createElement("script");
- script.src = "//pl132070.puhtml.com/68/7a/97/687a978dd26d579c788cb41e352f5a41.js";
- document.head.appendChild(script);
- }
- function adsOff() {
- if(window.localStorage) localStorage.ads = false;
- document.location.reload(true);
- }
- function noAds() {
- var div = document.querySelector("#inclinations");
- div.innerHTML = "Ads:<br><a id=\"adson\" href=\"#\">ON</a> / OFF";
- div.querySelector("#adson").addEventListener("click", adsOn);
- }
- if(window.localStorage) {
- if(localStorage.ads === undefined || localStorage.ads === "true")
- adsOn();
- else
- noAds();
- } else {
- adsOn();
- }
- })();*/
- //;p
- var hellos = [
- "Blaming about pain in my heart, but still going to live. ",
- "Found a paper with text 'I want to die'. Thrown out. ",
- "I haven't died yet. ",
- "Let's spam some notes. ",
- "Another day of music. ",
- "PeriOS runs his dirty thread and slowly reads his old HDD. ",
- "Why people like me? Because i like them. Sarcasm. ",
- "Why i can't add you to the whitelist? Maybe thats because you are black?. ",
- "I'm listening. ",
- "rag.self.describe(); ",
- "Did you try playing a song without pressing any keys? ",
- "PERIpheral Assassin: Opera Simulator is ready. ",
- "I don't know, how do i say 'Hello'. Bots like me cannot do that. ",
- "What's wrong in being a bot in a half? ",
- "Much pain but still time... ",
- "I'm black midi player, guys. ",
- "Do people think that is not an auto message thing? ",
- "Autism turned on. ",
- ];
- var noPerms = [
- "Hmm, i think this thing is not for you.",
- "Admin only.",
- "You don't have permission to do this.",
- "No, you are not on the admin list, sorry",
- "You practice executing command. I cannot do that.",
- "A special perm 'os.cmd.admin' is needed to perform this command.",
- "You have checked the access level indicator. It shows '0'.",
- "You are typing, the console says 'no'.",
- "No trollers allowed.",
- "Failed to execute this command on 'window'. The provided person is denied for doing that.",
- "Important: Command executed successfully. HOWEVER, only this text went out of this.",
- "Test for autism failed. No way. :<",
- ];
- function randomHello(){
- return hellos[Math.floor(Math.random() * hellos.length)];
- };
- function randomNoPerm(){
- return noPerms[Math.floor(Math.random() * noPerms.length)];
- }
- // FILE SYSTEM
- var code = "";
- var code2 = "";
- var metadata = {};
- var file = 'test.txt'
- var numberOfSongs = -1;
- var name = "";
- var dfg = ["dfg.dfg"];
- var songList = [];
- var ocp=[];
- var songcode = "";
- var sortL = 1;
- var curDfg;
- var non = 0;
- var bFsRequest = false;
- String.prototype.toNow = function(){
- let dfg = this.split(" ");
- let mons =
- {
- Jan: 1,
- Feb: 2,
- Mar: 3,
- Apr: 4,
- May: 5,
- Jun: 6,
- Jul: 7,
- Aug: 8,
- Sep: 9,
- Oct: 10,
- Nov: 11,
- Dec: 12,
- };
- let tm = dfg[4].split(":");
- return tm[2]/1+tm[1]*60+tm[0]*3600+dfg[2]*86400+(mons[dfg[1]]-1)*2678400+dfg[3]*32140800;
- }
- function findNaN(title)
- {
- if(songList.indexOf(title+".json")==-1)
- {
- return title;
- }
- else
- {
- var debug = 2;
- while(songList.indexOf(title+"("+debug+")"+".json")!==-1)
- {
- debug++;
- }
- return title+"("+debug+")";
- }
- }
- window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
- var errorHandler;var FileError = FileError;
- window.webkitStorageInfo.requestQuota(PERSISTENT, 1024*1024*1024, function(grantedBytes) {
- window.requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler);
- }, function(e) {
- console.log('Error', e);
- });
- if (FileError!==undefined){
- errorHandler = function(e) {
- var msg = '';
- switch (e.code) {
- case FileError.QUOTA_EXCEEDED_ERR:
- msg = 'QUOTA_EXCEEDED_ERR';
- break;
- case FileError.NOT_FOUND_ERR:
- msg = 'NOT_FOUND_ERR';
- break;
- case FileError.SECURITY_ERR:
- msg = 'SECURITY_ERR';
- break;
- case FileError.INVALID_MODIFICATION_ERR:
- msg = 'INVALID_MODIFICATION_ERR';
- break;
- case FileError.INVALID_STATE_ERR:
- msg = 'INVALID_STATE_ERR';
- break;
- default:
- msg = 'Unknown Error';
- break;
- };
- console.log('Error: ' + msg);bFsRequest = false;
- };}
- else
- {errorHandler=function(e){console.log(e);bFsRequest = false}}
- function onInitFs(fs) {
- if(sfile)
- fs.root.getFile(sfile, {}, function(fileEntry) {
- // Get a File object representing the file,
- // :P
- // then use FileReader to read its contents.
- fileEntry.getMetadata(function(mm){metadata = mm},function(a){throw("Failed to load metadata of propably invalid file. Please ignore this.")});
- fileEntry.file(function(file) {
- var reader = new FileReader();
- reader.onloadend = function(e) {code=this.result;if((typeof fonloadend == 'function') && (fixfile == sfile)){fonloadend(code)}};bFsRequest = false;
- reader.readAsText(file);
- }, errorHandler);
- }, fonerror);
- };
- function getFile(tofile,fsuccess,ferror){
- if(bFsRequest){setTimeout(function(){getFile(tofile,fsuccess,ferror)},1000)}else{
- bFsRequest = true;
- fonloadend = fsuccess;
- fonerror = ferror;
- fixfile = tofile;sfile = tofile;window.requestFileSystem(window.PERSISTENT, 1024*1024, onInitFs, errorHandler)
- }
- };
- function addTextToFile(file,text){getFile(file,function(base){var base = base+text;
- window.requestFileSystem(window.PERSISTENT, 1024*1024, function (fs) {
- fs.root.getFile(file+".txt", {create: false, exclusive: true}, function(fileEntry) {
- fileEntry.createWriter(function(fileWriter) {
- fileWriter.onwriteend = function(e) {
- console.log('Write completed.');
- };
- fileWriter.onerror = function(e) {
- console.log('Write failed: ' + e.toString());
- };
- // Create a new Blob and write it to log.txt.
- var blob = new Blob([base], {type: 'text/plain'});
- fileWriter.write(blob);
- }, errorHandler);
- }, errorHandler);
- }, errorHandler)})
- }
- function newFile(file,contents,bOverwrite){function onInitFs(fs) {
- fs.root.getFile(file+".json", {create: !bOverwrite, exclusive: true}, function(fileEntry) {
- fileEntry.createWriter(function(fileWriter) {
- fileWriter.onwriteend = function(e) {
- if(file!=="allParts" && subrealname!=="Anonymous")MPP.chat.send("Write completed: "+file+" Index: "+(songList.length-1));
- };
- fileWriter.onerror = function(e) {
- console.log('Write failed: ' + e);
- MPP.chat.send('Write failed: '+ e.toString());
- };
- // Create a new Blob and write it to log.txt.
- var blob = new Blob([contents], {type: 'text/plain'});
- fileWriter.write(blob);
- }, errorHandler);
- }, errorHandler);
- };
- window.requestFileSystem(window.PERSISTENT, 1024*1024, onInitFs, errorHandler)}
- function remove(file){
- window.requestFileSystem(window.PERSISTENT, 1024*1024, function(fs) {
- fs.root.getFile(file, {create: false}, function(fileEntry) {
- fileEntry.remove(function() {
- console.log('File removed.');
- }, errorHandler);
- }, errorHandler);
- }, errorHandler);
- }
- function addSong(title,contents){name = 'songs/'+findNaN(title);newFile(name,contents);name = findNaN(title)+".json";totalMetadata[name] = {modificationTime: Date()};numberOfSongs++;songList.push(name);setTimeout(function (){name="";{}},250);}
- function getSong(title){window.requestFileSystem(window.PERSISTENT, 1024*1024, function(fs) {
- fs.root.getDirectory('songs', {}, function(dirEntry) {
- dirEntry.getFile(title, {}, function(fileEntry) {
- // Get a File object representing the file,
- // then use FileReader to read its contents.
- fileEntry.file(function(file) {
- var reader = new FileReader();
- reader.onloadend = function(e) {
- songcode = this.result;
- if(songcode==""){remove('songs/'+title)}
- };
- reader.readAsText(file);
- }, errorHandler);
- }, errorHandler);
- }, errorHandler);
- }, errorHandler);};
- function newDir(name){
- window.requestFileSystem(window.PERSISTENT, 1024*1024, function(fs) {
- fs.root.getDirectory(name, {create: true}, function(dirEntry) {
- }, errorHandler);
- }, errorHandler);
- }
- function toArray(list) {
- return Array.prototype.slice.call(list || [], 0);
- };
- function rename(src, newName) {
- window.requestFileSystem(window.PERSISTENT, 1024*1024, function(fs) {
- fs.root.getDirectory('songs',{},function(dirEntry){
- dirEntry.getFile(src, {}, function(fileEntry) {
- fileEntry.moveTo(dirEntry, newName);
- }, errorHandler);
- }, errorHandler);
- }, errorHandler)};
- var totalSize = 0;
- var totalMetadata = [];
- function sortList()
- {
- try{
- supp = [];
- songList.forEach(function(s)
- {if(totalMetadata[s]!=undefined)supp.push({s: s,d: totalMetadata[s].modificationTime.toString()})
- });
- supp.sort(function(a,b){return a.d.toNow()-b.d.toNow()});
- songList = [];
- supp.forEach(function(s){songList.push(s.s)});
- dfg = songList;
- if(subrealname!=="Anonymous")MPP.chat.send(randomHello() + "Song list loaded.");
- }
- catch(err){throw err}
- };
- function getSongList(){
- MPP.chat.send("Loading song list...");
- window.requestFileSystem(window.PERSISTENT, 1024*1024, function(fs) {
- fs.root.getDirectory('songs/', {}, function(dirEntry) {
- dirEntry.getMetadata(function(m){window.dmetadata = m})
- var dirReader = dirEntry.createReader();
- entries = [];
- dfg = [];
- // Call the reader.readEntries() until no more results are returned.
- var readEntries = function() {
- dirReader.readEntries (function(results) {
- if (!results.length) {
- dfg = [];
- entries.forEach(function(a){dfg[dfg.length]=a.name});numberOfSongs=dfg.length;
- songList = dfg;
- totalSize= 0;totalMetadata = {};var tot = 0;
- songList.forEach(function(s)
- {
- dirEntry.getFile(s, {}, function(fileEntry)
- {
- fileEntry.getMetadata(function(m){totalMetadata[s]=m;totalSize+=m.size;tot++;
- if(tot==songList.length){sortList()}
- },function(e){MPP.chat.send("Failed to load song list. Error: "+e.code)});
- },errorHandler);
- });
- } else {
- entries = entries.concat(toArray(results));
- readEntries();
- }
- }, errorHandler);
- };
- readEntries(); // Start reading dirs.
- }, errorHandler);
- }, errorHandler);
- };
- // IMPORTMIDI (Deprecated. Use chooper100's MIDI importer and put generated files with upload buttom)
- var cursorUpdate = 0;
- var importStart = [];
- var importVolume = [];
- var importPitch = [];
- var importBars = [];
- var importVoice = [];
- var importDuration = [];
- var importIndexes = [];
- var keys = Object.keys(MPP.piano.keys);
- var dif = 0;
- var bar = 0;
- var items = "- 1 2 3 4 5 6 7 8 9 0 ,".split(" ");
- var shard = [];
- function fixCode()
- {
- shard=[];
- code.forEach(function(a){shard[shard.length]=a.replace(",",".")})
- }
- function applyMIDI(vc,min){
- a=[];
- b=[];
- c=[];
- r=[];
- var minv = 0;
- if(min!==undefined)
- {minv=min};
- dif = 0;
- var tempo = importBars[0];
- var tIdx = 0;
- for(var i=0;!(i>importStart.length);i++){
- if(tIdx < importBars.length && importIndexes[tIdx + 1] <= i){
- tIdx++;
- tempo = importBars[tIdx];
- };
- if(importStart[i]==importStart[0])
- {
- if(importStart[i-1]!==undefined)
- {dif=dif-4}
- }
- else {if((vc == undefined || (vc!==undefined && importVoice[i]!==undefined && vc == importVoice[i])) && minv<importVolume[i]){
- if(importStart[i-1]!==undefined && importStart[i-1]!==importStart[0]){
- dif=importStart[i]-dif}
- else
- {if(importStart[i-1]==importStart[0]){dif=importStart[i]-dif}}
- a[a.length]=keys[(importPitch[i]/1)-21];
- b[b.length]=Math.round(Math.round(importVolume[i])/10)/10;
- c[c.length]=Math.round((dif/1)*(60000/tempo));
- r[r.length]=Math.round((importDuration[i]/1)*(60000/tempo));
- dif=(importStart[i]/1)}
- }
- }
- }
- // LOCAL UPLOAD BUTTON (to import MIDIs):
- var code = "";
- var el = document.createElement("input");
- var rety = "";
- var wow = [];
- el.type="file";
- el.id="fileinput";
- el.className = "ugly-button";
- el.style="float:right";
- el.multiple=1;
- document.getElementsByClassName("relative")[0].appendChild(el);
- function readMultipleFiles(evt) {
- //Retrieve all the files from the FileList object
- var files = evt.target.files;
- if (files) {
- for (var i=0, f; f=files[i]; i++) {
- var r = new FileReader();
- r.onload = (function(f) {
- wow+=f;
- return function(e) {
- var contents = e.target.result;
- code = contents;
- switch(f.name)
- {
- case "Notes - Indexes.txt": {code = code.split("\n");fixCode();importIndexes=shard};break;
- case "Notes - Pitch.txt": {code = code.split("\n");fixCode();importPitch=shard};break;
- case "Notes - Voice.txt": {code = code.split("\n");fixCode();importVoice=shard};break;
- case "Notes - Volume.txt": {code = code.split("\n");fixCode();importVolume=shard};break;
- case "Notes - Start.txt": {code = code.split("\n");fixCode();importStart=shard};break;
- case "Notes - Duration.txt": {code = code.split("\n");fixCode();importDuration=shard};break;
- case "Bar Tempo.txt": {code = code.split("\n");fixCode();importBars=shard};break;
- default: {};break;
- }
- rety = f.name;
- };
- })(f);
- r.readAsText(f);
- }
- } else {
- alert("Failed to load files");
- }
- }
- document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
- // UNICODE FORMATTER (source: https://hastebin.com/raw/kayatuqane.js)
- var unicodeFormatter = document.createElement("script");
- unicodeFormatter.src = "https://hastebin.com/raw/kaytuquane.js";
- document.body.appendChild(unicodeFormatter);
- // MAIN PROGRAM (CMDS etc.)
- var a = ["a0","b0","c0"], b = [1,1,1],c = [1000,1000,1000],r = [2000,2000,100],octaveDelay = 0;
- echo = 1,blacklist = [],counter = 0,f = [0],g = [0],megaphone = 0,wn = [], snap = 0,nps=1, warn = 1, cfix = 1, participants = [],pre = [], songs = [], exp = 0, lvl = 1,sec = 1, songLength = 0;var i = 1,posSec= 0,partsRecorded = [],partsNotes = [],thrown = [],timeout,cursorUpdate = 1,minV=0,d=0,wBuffer=['',0],ball={},moderators = [],pitch = 0,recording = false,groups=[],mute = false,allParts = {},vq = 500;groups[0]=["7eb87a474bd1977306e5c4a6","7c40bfe02002be6db0abd862","5c8ec21836908314665b0066","3c3e04292084eee312694e26","f624cfc0b69ec74afe533efa"];
- var virtualQuota = setInterval(function(){if(vq<500)vq++},9);var vqEnabled = true;
- var subrealname = "PeriOS (PL)";
- var cping = "";
- var clientArray = [];
- var clientOnRooms = [];
- var loaded = 0;
- var tutorial = false
- var uploadVotes = 0;
- var prefix = "\\";
- var whiteKeys = [],blackKeys = [];for(var n in MPP.piano.keys){if(n.indexOf("s")!==-1){blackKeys[whiteKeys.length] = n}else{whiteKeys.push(n)}};
- var fluteMode = false;
- var displayPart = [];
- var defaultFollow = 1;
- var postHalting = false;
- var multiRoom = false;
- var privateNotes = false;
- var flute = function(){if(fluteMode){gNHeld = 0;for(var id in gHeldNotes){if(gHeldNotes[id] && (id in MPP.piano.keys)){MPP.press(id,velocityFromMouseY(),true);gNHeld++}};setTimeout(flute,10*(gNHeld !== 0 ? gNHeld: 2))}else{setTimeout(flute,1000);releaseAll()}}
- var packet = [];for(var n in MPP.piano.keys){packet.push({n: n,v: 0})};
- var chargeSpam = function(time,vel,note){for(var n in packet){if(note==undefined || (packet[n].n.indexOf(note)!=-1 && (packet[n].n.indexOf("s")==note.indexOf("s")))){packet[n].v = vel}else{packet[n].v = 0}};var t = time;window.toff = Date.now()+t;while(t>-4000){setTimeout(function(){MPP.client.sendArray([{m:"n",n: packet,t: window.toff}])},t);t-=1000};}
- var bluesMode = false; //blues module
- var bConv = {
- c: "c",
- cs: "cs",
- d: "d",
- ds: "f",
- e: "ds",
- f: "e",
- fs: "fs",
- g: "g",
- gs: "gs",
- a: "a",
- as: "b",
- b: "as",
- };
- function toBlues(id){
- if(id[1] == "s")
- return bConv[id.slice(0,2)] + id.slice(2);
- else
- return bConv[id[0]] + id.slice(1);
- };
- //rest
- function isValidate(num){
- if(clientArray[num].channel)
- {
- return clientArray[num].channel._id==clientOnRooms[num];
- }
- else
- {clientArray[num].setChannel(clientOnRooms[num]);return false}
- };
- function saveParts(){
- var sData = JSON.stringify(allParts)+" ".repeat(1000);if((loaded == 1) && !(rawPL>sData)){setTimeout(function(){newFile("allParts",sData,true)},1000);}
- };
- function getParts(){
- getFile("allParts.txt",function(partcode){var temp = allParts;
- allParts = JSON.parse(partcode);rawPL = partcode.length;
- var n = 0;
- for(var p in temp){addPart(temp[p])};uploadVotes = 0;groups = [];
- for(var p in allParts){n++;if(allParts[p].vu==1){uploadVotes++};
- if(allParts[p].g!==undefined){if(!groups[allParts[p].g]){groups[allParts[p].g]=[]}
- groups[allParts[p].g].push(allParts[p]._id);}
- if(allParts[p].f==0){blacklist.push(allParts[p].id)}};
- MPP.chat.send("Database loaded. ("+n+" users) ("+metadata.size+" bytes used.)");
- loaded = 1;
- },function(){newFile("allParts",JSON.stringify(allParts))})
- };
- /*function fixParts(){ TODO
- getFile("allParts.txt",function(partcode){var temp = allParts;
- var tStrings = partcode.slice(1,partcode.length-2).split(",");
- var errors = 0;
- for(var n = 0;n<tStrings.length;n++){
- var strcode = tStrings[n].replace("\":","\"]=").replace("\"","[\"")
- try{
- };
- };
- rawPL = partcode.length;
- for(var p in temp){addPart(temp[p])};
- MPP.chat.send("Database fixed. ("+n+" users) ("+metadata.size+" bytes used. Errors: "+errors+")");
- newFile("allParts",JSON.stringify(allParts))
- },function(){newFile("allParts",JSON.stringify(allParts))})
- };*/
- function addPart(part){
- if(allParts[part._id]==undefined)
- {allParts[part._id] = part;allParts[part._id].name = part.name;allParts[part._id].f = defaultFollow;allParts[part._id].a = 0;allParts[part._id].vu = 0;saveParts()}
- };
- function noteFilter(){
- var na = [];
- var nb = [];
- var nc = [];
- var tNotes = {};
- var nPrev = {};
- var ret = {removed: 0};
- for(var n = 0;n<a.length;n++){
- if(tNotes[a[n]]){
- if(tNotes[a[n]] < 1){
- tNotes[a[n]]++;
- }else{
- var ky = keys[keys.indexOf(a[n])+12];
- tNotes[ky] = (tNotes[ky] || 0) - 1;
- var ky = keys[keys.indexOf(a[n])-12];
- tNotes[ky] = (tNotes[ky] || 0) - 1;
- nPrev[a[n]] = -1;
- ret.removed+= 4;
- };
- }else{
- tNotes[a[n]] = 1;
- };
- if(c[n] > 0){
- for(var k in tNotes){
- if(tNotes[k]>0){
- for(var m = 0;m<tNotes[k];m++){
- na.push(k);
- nb.push(0.8);
- nc.push(0);
- };
- };
- };
- nc[nc.length-1] = c[n];
- tNotes = new Object(nPrev);
- nPrev = {};
- };
- };
- window.a = na;
- window.b = nb;
- window.c = nc;
- var time = 0;
- var needed = sec*1000;
- var j = 0;
- while(time<needed){
- time += c[j] || 0;
- j++;
- if(j>a.length)break;
- };
- i = j;
- clearTimeout(timeout);
- playing=0;
- playprecise();
- return ret;
- };
- function reloadclients(){
- if(multiroom)
- for(var c in clientArray){
- if(!clientArray[c].isConnected()){
- clientArray[c].connect()
- };
- if(clientArray[c].channel)if(clientArray[c].channel._id!==clientOnRooms[c]){
- clientArray[c].setChannel(clientOnRooms[c])
- };
- };
- };
- var iClients = setInterval(reloadclients,10000);
- function comRest(com){
- return com.slice(prefix.length).split(" ").slice(1).join(" ")
- };
- function gMessage(msg,p)
- {
- for(c in clientArray){clientArray[c].sendArray([{m: "a",message: p+" said: "+msg}])}
- }
- function privateMessage(msg,p) //separate Room and message with "|"
- {
- if(comRest(msg).indexOf("\\")==-1){
- var cmd = comRest(msg);
- var toroom = cmd.split("|")[0];
- var message = p+" said: "+cmd.split("|")[1];
- if(!(toroom in clientOnRooms)){
- clientOnRooms.forEach(function(room){
- if(room.indexOf(toroom)!==-1)clientArray[clientOnRooms.indexOf(room)].sendArray([{m: "a",message: message}]);
- })
- }else{
- clientArray[clientOnRooms.indexOf(toroom)].sendArray([{m: "a",message: message}])
- }
- }
- }
- function wyrownaj(rachunki)
- {
- if(j!==i)
- {
- j = 0;i=0;
- for(j = 0,j=0;pre[j].c-pre[0].c<sec*1000;j++,i++)
- {};
- i = j;
- setTimeout(wyrownaj,1000);
- }
- else
- {
- mute = false;
- }
- }
- var noteDivs = [];
- var brickParent = document.createElement("div");
- brickParent.style.position = "absolute";
- brickParent.style.marginTop = "-1000px";
- brickParent.id = "bp";
- document.body.appendChild(brickParent);
- function pushNoteDiv(n,d)
- {
- var note = document.createElement("div");
- note.style.position = "absolute";
- if(whiteKeys.indexOf(n)!==-1){
- note.style.backgroundColor = "green"}else{note.style.backgroundColor = "red"}
- note.style.width = "1.5%";
- note.style.height = "5%";
- note.style.marginLeft = (whiteKeys.indexOf(n)+blackKeys.indexOf(n)+2.7-(blackKeys.indexOf(n)!==-1)*0.5)*innerWidth/55.5+"px";
- note.id = "n"+((noteDivs.indexOf(undefined)+1 || noteDivs.length+1)-1);
- noteDivs[note.id.slice(1)/1] = {n: n,t: d,id: note.id};
- document.body.appendChild(note);
- }
- var noteTest = setInterval(function(){noteDivs.forEach(function(nt){if(nt!==undefined){var pos = (Date.now()-nt.t)/10-230;if(pos+230>0){var rmid = nt.id;while(document.getElementById(nt.id)!==null){document.body.removeChild(eval(rmid))};noteDivs[noteDivs.indexOf(nt)]=undefined}else{document.getElementById(nt.id).style.marginTop = pos+"px"}}})},25);
- function search(ssong)
- {var foundSongs=[],song = ssong.toLowerCase();
- if(songList!==undefined)
- {
- if((song/1).toString()=="NaN")
- {
- for(var i=0;!(i>songList.length-1);i++)
- {
- if(songList[i].toLowerCase().indexOf(song)!==-1)
- {foundSongs[foundSongs.length]=i}
- }
- }
- else
- {
- if(songList[song/1].split(".")[0].toString()!=="NaN")
- {foundSongs[foundSongs.length]=song/1}
- }
- };
- return foundSongs;
- };
- function getGroup(partid)
- {
- var g = -1;
- groups.forEach
- (function(group)
- {
- if(group.indexOf(partid)!==-1)
- {
- g = groups.indexOf(group);
- }
- }
- )
- return g;
- }
- function addtogroup(ser,index)
- {
- var current = [];
- for(var f=0;f<partsNotes.length;f++)
- {
- if(MPP.client.findParticipantById(partsRecorded[f]).name.indexOf(ser)!==-1)
- {
- current=MPP.client.findParticipantById(partsRecorded[f]);
- if(!groups[index]){groups[index]=[]}
- groups[index].push(current._id);
- addPart(current);
- allParts[current._id].g=index;
- }
- };
- }
- function spart(part,bobj,f,reg)
- {
- var found=[],current={};
- if(!bobj){displayPart = []};
- for(var g in allParts)
- {
- if(allParts[g].name!=undefined)
- if(fixName(allParts[g].name).toLowerCase().indexOf(part.toLowerCase())!==-1)
- {
- current=allParts[g];
- if(bobj && (f==undefined || f==current.f) && (reg==undefined || PC.isRegistered(current._id))){return current}else{displayPart.push(current)};found[found.length]=" "+current.name;
- }
- };
- if(!bobj)
- return found;
- }
- function getArgument(text,arg){
- return text.slice(prefix.length).split(" ")[arg - 1];
- };
- function waltime(input,time){var omg = input;var wtf = time;setTimeout(omg,wtf)};
- function releaseAll(){for(var n in gHeldNotes){gHeldNotes[n] = false}};
- function stun(){for(var fc = 0;sec*1000>pre[i].c && playing==1;i++)
- {
- if(!mute)
- {
- var hu = [pre[i]];
- hu[0].c-=(sec-1)*1000;
- hu.forEach(function(gb)
- {
- function pl()
- {
- var ix = keys.indexOf(gb.a);
- var n = keys[ix+pitch];
- if(!tutorial){if(postHalting){for(var m = ix - 1;m<ix+2;m++){if(gHeldNotes[keys[m]])MPP.release(keys[m])}};
- if(privateNotes){
- MPP.piano.play(n,gb.b*v,MPP.client.getOwnParticipant(),0);
- }else{
- ultrapress(n,gb.b*v);
- }
- }
- else
- {pushNoteDiv(n,Date.now()+3000)}
- if(gb.r){timeout=setTimeout(function()
- {
- MPP.release(n)
- },gb.r/(speed/100))}
- else
- {
- timeout=setTimeout(function()
- {
- MPP.release(n)
- },500/(speed/100))
- }
- }
- timeout=setTimeout(pl
- ,gb.c/(speed/100));
- })
- }
- };
- if(!(pre[i+1]))
- {
- playing = 0;releaseAll();
- setTimeout(function(){MPP.client.sendArray([{m: "userset",set: {name: realName}}])},2000)
- };
- if(playing==1)
- {
- sec++;
- if(!cursorUpdate)
- MPP.client.sendArray([{m: "m", x: 10+(sec/songLength)*0.8, y: 40 }]);
- timeout=setTimeout(stun,1000/(speed/100));
- /*if(nps>10000){minV=100-50/(nps/100);
- //for(var gh=0;nps>100 && gh<50;gh++)
- //{
- //nps=0;
- // thrown.forEach(function(n)
- // {
- // if(n.b>minV)
- // {
- // nps++
- // }
- // });
- // minV+=(100-minV)/1.5
- //}
- //}else
- //{
- // minV=0
- };*/
- if(sec%2 == 0)MPP.client.sendArray([{m: "userset", set: {name: realName+" ["+Math.floor((sec/(speed/100))/60)+":"+(sec/(speed/100)) % 60+"/"+Math.floor((songLength/(speed/100))/60)+":"+(songLength/(speed/100))%60+"]"}}])
- }
- else{
- setTimeout(function(){releaseAll()},1000) }};
- function playNote(){if(playing==1){MPP.press(pre[i].a,pre[i].b*v)}else{clearTimeout(playNote)};i++};
- function exportSong(a,b,c,r){var contents = "a = \"";a.forEach(function(a){contents+=a+" "});contents+="\".split(\" \");b=[";b.forEach(function(b){contents+=b+","});contents+="];c=[";c.forEach(function(c){contents+=c+","});contents+="];r=[";r.forEach(function(r){contents+=r+","});contents+="]";return contents };
- function playprecise(song){playing = 1;clearTimeout(timeout);pre = [];a.forEach(function(gb){pre[pre.length]=[];pre[pre.length-1].a=gb});var couter=0;b.forEach(function(gb){pre[couter].b=gb;couter++});var dely=0;couter=0;c.forEach(function(gb){dely+=gb;if(dely.toString()=="NaN"){dely=0};if(!(pre[couter])){pre[couter]=[]};pre[couter].c=dely;couter++});couter=0;r.forEach(function(gb){if(pre[couter]){pre[couter].r=gb;couter++}});songLength=Math.round(pre[pre.length-2].c/1000);
- if(songLength>0){nps = a.length/songLength;if(nps*(speed/100)*v>(100/(1+(MPP.client.channel._id=="RP Room")*9))){speed = 100;v = 1;if(MPP.client.channel._id=="RP Room"){MPP.chat.send("Setting too high for this room. Try another song.");return false};MPP.chat.send("Settings are too high. Reseting ...")};stun()}else{remove("songs/"+song);MPP.chat.send("Critical error: Song length must be positive.")}}
- function ultrapress(n,vl){if(snap==1){v = 10 - MPP.client.getOwnParticipant().y/10};var vol = vl/v; if(vol>vl){vol=1};
- if(vl<0){MPP.release(n)}else{if(vq>0 || !vqEnabled)
- for(var u = 0;u<1;u++)
- {
- MPP.press(n,vol);
- }
- }
- }
- function playnbn(notes){if(notes!==undefined)if(notes.forEach!==undefined)notes.forEach(function(note){if(!(note.s)){setTimeout(function(){MPP.press(keys[keys.indexOf(note.n)+pitch],note.v*v)},(note.d!==undefined)*note.d)}else{setTimeout(function(){MPP.release(note.n)},(note.d!==undefined)*note.d)}})}
- function ultrapresse(n,v){if(snap==1){v = 10 - MPP.client.getOwnParticipant().y/10}var vol = 1; if(vol>v){vol=1};for(var u = 0;u<v;u++){setTimeout(function(){MPP.press(n,vol)},u*d)}}
- function ultrapresso(n,v){if(snap==1){v = 10 - MPP.client.getOwnParticipant().y/10}var vol = 1; if(vol>v){vol=1};for(var u = 0;u<v;u++){setTimeout(function(){MPP.client.startNote(n,vol)},u*d)}}
- function repeat(){if(sec+1>songLength || sec == 0){MPP.chat.send(prefix+"play "+Math.round(Math.random()*songList.length).toString())};rep=setTimeout(repeat,5000)};
- function toHex(n){var o = "0123456789abcdef",n = n,d = 1,ret = "";while(d<n){d=d*16};d=d/16;while(d>0.9){var od = Math.floor(n/d);ret+=o[od];n= n - od*d;d = d/16};return ret};
- function char(c){var ch = toHex(c);while(ch.length<4){ch=0+ch};return eval("\""+"\\u"+ch+"\"")};
- function fixName(name){return name.formatUnicode()};
- window.safe =
- {
- eval: window.eval,
- };
- var preventOverflow = function(str,time)
- {
- var str0 = "function prevent(){if(Date.now()>"+time+"){throw 'Out of time to execute the srcipt.'}};";
- var str = str0+str;
- var preventer = ";prevent()}";
- var counter = str.length;
- var ind = str.lastIndexOf("}",counter);
- while(ind!=-1 && ind<=counter && counter>str0.length)
- {
- var arr = str.split("");
- arr[ind] = preventer;
- counter-=preventer.length;
- str = arr.join("");
- ind = str.lastIndexOf("}",counter);
- };
- return str
- };
- function convertToLUA(){
- var str = "1234567890abcdefghijklmnoprstuqvxyzABCDEFGHIJKLMNOPRSTUQVXYZ-=[]\;',./_+{}|:\"<>?`~!@#$%^&*() \n\\";
- var strOut = ""
- var timeSlice = 0
- for(var n = 0;n<a.length;n++){
- timeSlice = timeSlice + c[n];
- nIndex = keys.indexOf(a[n]) - 3;
- if(nIndex < 0)nIndex = 0;
- var ticks = Math.floor(timeSlice/25);
- timeSlice-=ticks * 25;
- while(ticks>96){strOut += "ęć";ticks-=96};
- strOut += (str[nIndex] || "\\") + (str[ticks] || "\\");
- };
- return strOut;
- };
- var ctsFailures = [];
- function convertToScratch(instrument,dTick,sStart,sEnd){
- var sStart = (sStart || 0) * 1000;
- var sEnd = (sEnd || Infinity) * 1000;
- var currentTime = 0;
- var strOut = "";
- var timeSlice = 0;
- var nTick = Infinity;
- var ins = instrument.toString() || "01";
- var min = 50;
- var prevTicks = 0;
- var prevNotes = [];
- var prevNotes1 = [];
- ctsFailures = [];
- for(var n in window.a)
- {
- if(window.c[n]>min && window.c[n]<nTick)
- nTick = window.c[n];
- };
- nTick = nTick.toString();
- strOut = "0".repeat(((3 - nTick.length) > 0) && (3 - nTick.length) || 0) + nTick.slice(0,3);
- strOut += "0".repeat(((2 - ins.length) > 0) && (2 - ins.length) || 0) + ins.slice(0,2);
- nTick = parseInt(nTick);
- for(var n = 0;n<a.length;n++){
- currentTime += c[n+1] || 0;
- if(currentTime > sEnd)break;
- if(currentTime >= sStart){
- timeSlice += (c[n+1] || 0);
- var nIdx = keys.indexOf(a[n]) - 3;
- if(nIdx < 0)nIdx = 0;
- var ticks = Math.floor(timeSlice/nTick);
- if(ticks > 99)ticks = 99;
- var noteLength = Math.floor((r[n] || (nTick * (dTick || 1)))/nTick);
- if(noteLength > 99)noteLength = 99;
- var vol = parseInt(b[n] * 9);
- if(ticks > 0){
- prevNotes = prevNotes.map(function(v,k){
- if((prevNotes1[k] == undefined) && (v > 0)){
- return v-1;
- }else{
- return v;
- };
- });
- prevNotes1 = [];
- };
- if((prevNotes[nIdx] == undefined || prevNotes[nIdx] < 1) && (prevNotes1[nIdx + 1] == undefined) && (prevNotes1[nIdx - 1] == undefined)){
- timeSlice -= ticks * nTick;
- if(ticks < 10)ticks = "0" + ticks;
- if(nIdx < 10)nIdx = "0" + nIdx;
- if(noteLength < 10)noteLength = "0" + noteLength;
- if(vol > 9)vol = 9;
- var addString = ""+nIdx + noteLength + vol + ticks;
- if(addString.length == 7)strOut += addString;
- else ctsFailures.push({total: addString.length,t: ticks,p: nIdx,l: noteLength,v: vol})
- };
- prevNotes[parseInt(nIdx)] = (prevNotes[parseInt(nIdx)] == undefined ? 1 : prevNotes[parseInt(nIdx)]+1);
- prevNotes1[parseInt(nIdx)] = true;
- }
- };
- var octaveList = [];
- var startl = strOut.length;
- var n = 5;
- while(n < strOut.length){
- var tck = parseInt(strOut.slice(n+5,n+7));
- var nidx = parseInt(strOut.slice(n,n+2));
- if(tck > 0){/*/ && strOut.length>0){
- for(var nt in Object.keys(octaveList)){
- var nt = parseInt(nt);
- if(octaveList[nt] !== undefined){
- if(octaveList[nt - 1] !== undefined){
- var nstr = strOut.slice(0,octaveList[nt]) + strOut.slice(octaveList[nt] + 7);
- //if(nstr.length < strOut.length){
- strOut = nstr;
- n -= 7;
- ctsFailures.push({n: nstr.length, o: strOut.length, t: 0, v: octaveList[nt]});
- //};
- }else if(octaveList[nt + 1] !== undefined){
- var nstr = strOut.slice(0,octaveList[nt]) + strOut.slice(octaveList[nt] + 7)
- //if(nstr.length < strOut.length){
- strOut = nstr;
- n -= 7;
- ctsFailures.push({n: nstr.length, o: strOut.length, t: 2, v: octaveList[nt]});
- //};
- };
- };
- };*/
- octaveList = [];
- }else{
- if(octaveList[nidx % 12] == undefined){
- octaveList[nidx % 12] = {n: n, p: nidx};
- }else{
- if(octaveList[nidx % 12].p < nidx){
- var nstr = strOut.slice(0,octaveList[nidx % 12].n) + strOut.slice(octaveList[nidx % 12].n + 7);
- //if(nstr.length < strOut.length){
- strOut = nstr;
- octaveList[nidx % 12] = {n: n, p: nidx};
- n -= 7;
- ctsFailures.push({n: nstr.length, o: strOut.length, t: 1});
- //};
- }else{
- var nstr = strOut.slice(0,n) + strOut.slice(n + 7);
- //if(nstr.length < strOut.length){
- strOut = nstr;
- n -= 7;
- ctsFailures.push({n: nstr.length, o: strOut.length, t: 1});
- //};
- }
- };
- }
- n += 7;
- //ctsFailures.push({t: tck, n: nidx});
- };
- return strOut;
- };
- function convertToODur(barSize){
- function Bar(tempo){
- this.tempo = tempo || 150;
- this.notes = [];
- return this;
- };
- function Note(pitch,time,length,volume,instrument){
- this.pitch = pitch;
- this.time = time;
- this.length = parseInt(length) || 1;
- this.volume = (volume || 100) / 100;
- this.instrument = instrument || 0;
- return this;
- };
- function Instrument(type){
- this.type = type || "square";
- return this;
- };
- var barSize = barSize || 32;
- var nTick = Infinity;
- for(var n in window.a)
- {
- if(window.c[n]>49 && window.c[n]<nTick)
- nTick = window.c[n];
- };
- var bars = [];
- var timeStamp = 0;
- var tempo = 60 * (1000 / nTick);
- for(var i = 0;i < a.length;i++){
- timeStamp += c[i];
- var time = Math.floor(timeStamp / nTick);
- var barId = Math.floor(time / barSize);
- if(barId < 1000){
- while(!bars[barId])bars.push(new Bar(tempo));
- bars[barId].notes.push(new Note(keys.indexOf(a[i]) + 33, time % barSize, Math.ceil((r[i] || 1) / nTick) || 1, b[i] * 100));
- };
- };
- var data = {
- bars: bars,
- cfg: {bl: barSize},
- instruments: [new Instrument],
- varsion: 0.1,
- };
- var blob = new Blob([JSON.stringify(data)], {type: 'text/JSON'});
- var url = window.URL.createObjectURL(blob);
- var anchor = document.createElement('a');
- anchor.href = url;
- anchor.target = '_blank';
- anchor.download = "data.JSON";
- anchor.click();
- };
- function addOp(id){
- if(!localStorage.ops)localStorage.ops = "{}";
- var obj = JSON.parse(localStorage.ops);
- obj[id] = true;
- localStorage.ops = JSON.stringify(obj);
- };
- function deOp(id){
- var obj = JSON.parse(localStorage.ops);
- obj[id] = false;
- localStorage.ops = JSON.stringify(obj);
- };
- function access(id){
- return JSON.parse(localStorage.ops)[id] || (id == MPP.client.getOwnParticipant()._id);
- };
- function wazne(yomom)
- {
- if (yomom.a.slice(0,prefix.length)==prefix && subrealname!=="Anonymous")
- {
- switch (yomom.a.slice(prefix.length).split(" ")[0].toLowerCase()) {
- case "stop": {if(playing==1){clearTimeout(timeout);playing=0}};break;
- case "bye": {if(yomom.p.id==MPP.client.getOwnParticipant().id){MPP.chat.hide()}else{MPP.chat.send(randomNoPerm())}};break;
- case "itball": {
- if(true){
- MPP.chat.send("This function is not enabled.");
- }else{
- var index = yomom.a.split(" ").slice(1).join(" ");
- var isindex = ball[index];
- if(isindex)
- {MPP.chat.send("ITball: "+isindex)}
- else
- {MPP.chat.send("Not found. Command ran out of access.")}
- };
- };break;
- case "pos":
- {
- mute = true;
- j = 0;i=0;
- var rd = comRest(yomom.a);
- if(!(isNaN(rd/1)) && rd!=="" && isFinite(rd/1))
- {
- for(j = 0,j=0;pre[j].c-pre[0].c<(rd/1)*1000;j++,i++)
- {};
- sec = rd/1; i = j;
- setTimeout(wyrownaj,1000);
- };
- MPP.chat.send("Time: "+Math.floor((sec/(speed/100))/60)+":"+(sec/(speed/100)) % 60+"/"+Math.floor((songLength/(speed/100))/60)+":"+(songLength/(speed/100))%60+"]")
- };break;
- case "echo": {if(echo==0){echo=1;MPP.chat.send("Comments on")}else{echo=0;MPP.chat.send("Comments off")} };break;
- case "octave": case "oct": {
- octaveMode=parseInt(getArgument(yomom.a,2) || (!octaveMode + 0));
- if(octaveMode>6)octaveMode = 6;
- if(octaveMode<0)octaveMode = 0;
- var out = "Octave mode off.";
- if(octaveMode == 1)
- out = "Octave mode on.";
- else if(octaveMode > 1)
- out = "Octaves played: "+octaveMode;
- MPP.chat.send(out);
- };break;
- case "octavedelay": {var arg = getArgument(yomom.a,2);if(arg!=="")octaveDelay = parseInt(arg);MPP.chat.send("Octave delay: "+octaveDelay)};break;
- case "megaphone": {if(megaphone==1){megaphone=0}else{megaphone=1} };break;
- case "gamemode":case "gm": {MPP.chat.send('Your gamemode has been updated.')};break;
- case "reload":{if(access(yomom.p._id)){getSongList()}else{MPP.chat.send(randomNoPerm())}};break;
- case "vf": {var arg = parseFloat(getArgument(yomom.a,2));if(arg && arg<=1 && arg>=0){volumeFriction = arg;MPP.chat.send("Volume friction: "+volumeFriction)}};break;
- case "msg":{if(yomom.a.indexOf("|")!=-1){privateMessage(yomom.a,yomom.p.name)}else{this.sendArray([{m: "a", message: "Please use \"|\" to separate room name and message."}])}};break;
- case "rooms":{MPP.client.sendArray([{m: "+ls"}]);MPP.chat.send("Waiting for response...")};break;
- case "ping":{MPP.chat.send("Play a note to check ping.");cping = yomom.p.id};break;
- case "tutorial":{};break;
- case "save":{if(access(yomom.p._id)){var s = yomom.a;for(var p = 0;p < partsNotes.length;p++){if(partsNotes[p].p == s){partsNotes[p].lastNote=0}}} else {MPP.chat.send(randomNoPerm())}};break;
- case "prefix":{var lprefix = comRest(yomom.a) || "";if(lprefix==""){MPP.chat.send("Prefix: "+prefix)}else{if(yomom.p.id==MPP.client.getOwnParticipant().id){prefix = lprefix;MPP.chat.send("Prefix set to: "+prefix)}else{MPP.chat.send(randomNoPerm())}}};break;
- case "songs":{MPP.chat.send("Song in database: "+dfg.length)};break;
- case "list":case "l":{var n = comRest(yomom.a)/1;if(n==""){n=1};if(!(isNaN(n))){if(n*10>dfg.length+9){MPP.chat.send("Not found.")}else{MPP.chat.send("Display page "+n+" of "+Math.ceil(dfg.length/10));var ls = [];for(var k = 0;k<10;k++){if(dfg.slice(n*10-10,n*10)[k] !== undefined)ls.push((n*10-10+k)+". "+dfg.slice(n*10-10,n*10)[k])};MPP.chat.send(ls.join(" #@# "))}}else{MPP.chat.send("Invalid page number")}};break;
- case "addtogroup":{if(access(yomom.p._id)){var toadd = comRest(yomom.a).split(" ");toadd[toadd.length-1]=undefined;toadd = getArgument(yomom.a,2);addtogroup(comRest(yomom.a),getArgument(yomom.a,yomom.a.split(" ").length))}};break;
- case "delay":case "d": {var rd = comRest(yomom.a);if(!(isNaN(rd/1)) && rd!=="" && isFinite(rd/1)){d = rd/1};MPP.chat.send('Note echo delay: '+d)};break;
- case "rplay": {var rp = comRest(yomom.a);if(rp/1<dfg.length){MPP.chat.send("Trying to read various file: "+dfg[rp/1]);try{play(dfg[rp/1])}catch(err){MPP.chat.send("Play error: "+err)}}};break;
- case "pitch":case "t": {var arg = comRest(yomom.a);if(!(isNaN(arg/1)) && Math.abs(arg/1)<96){pitch = arg/1};MPP.chat.send('Pitch: '+pitch)};break;
- case "userset": {if(access(yomom.p._id)){subrealname = comRest(yomom.a);MPP.client.sendArray([{m: "userset",set: {name: comRest(yomom.a)}}])}else{MPP.chat.send(randomNoPerm())}};break;
- case "addmod":
- {
- var part=comRest(yomom.a);
- var found="";
- var current={};
- for(var f=0;f<partsRecorded.length;f++)
- {
- if(partsNotes[f].p.indexOf(part)!==-1)
- {
- current=MPP.client.findParticipantById(partsRecorded[f]);
- if(moderators.indexOf(current.id)==-1)
- {
- moderators[moderators.length]=current.id
- }
- }
- }
- };
- break;
- case "localsound": {localSound = !localSound; MPP.chat.send("Local sound: " + (localSound ? "enabled" : "disabled"))};break;
- case "search":case "s": {var s = comRest(yomom.a);var found = search(s);if(found!=="" && found.length>1){MPP.chat.send("Found indexes: "+found.slice(0,100))}else{MPP.chat.send("Not found.")}};break;
- case "remove":case "rm": {if(access(yomom.p._id)){remove("songs/"+songList[comRest(yomom.a)])}else{MPP.chat.send(randomNoPerm())} };break;
- case "about": {MPP.chat.send("Peripheral_Assassin's independent recording and playing music bot. Version: "+version) };break;
- case "big": {
- var str = comRest(yomom.a);
- var str1 = "", str2 = "", str3 = "";
- for(var i = 0;i < str.length;i++){
- var l = lBlocks[str[i]];
- if(l)
- for(var j = 0;j < l.length;j += 3){
- str1 += l[j];
- str2 += l[j + 1];
- str3 += l[j + 2];
- };
- };
- MPP.chat.send(str1,true);
- MPP.chat.send(str2,true);
- MPP.chat.send(str3,true);
- };break;
- case "motd": {MPP.chat.send(motd)};break;
- case "multiroom": {if(access(yomom.p._id)){multiRoom = !multiRoom;MPP.chat.send("Multiroom mode turned "+(multiRoom && "on" || "off")+".")}else{MPP.chat.send(randomNoPerm())}};break;
- case "voteupload": {if(allParts[yomom.p._id].vu!==1){allParts[yomom.p._id].vu = 1;uploadVotes++;MPP.chat.send("You have voted for uploading my code. Total votes: "+uploadVotes)}else{MPP.chat.send("You already voted!")}};break;
- case "random":case "r": {var toplay = Math.round(Math.random()*dfg.length);i=0;sec=0;play(songList[toplay]);MPP.chat.send("Reading file. Index: "+toplay+" Song: "+songList[toplay])};break;
- case "globalsendchat":case "gsc":{if(comRest(yomom.a).indexOf("\\")==-1)gMessage(comRest(yomom.a),yomom.p.name)};break;
- case "setmotd": {if(access(yomom.p._id)){motd = comRest(yomom.a)}else{MPP.chat.send(randomNoPerm())}};break;
- case "rename": {
- if(access(yomom.p._id)){
- var index = parseInt(getArgument(yomom.a,2));
- var newName = comRest(yomom.a).split(" ").slice(1).join(" ");
- rename(songList[index],newName);
- songList[index] = newName;
- }else{
- MPP.chat.send(randomNoPerm());
- }
- };break;
- case "startrecord": {if(!recording){recording = true;wn = [];MPP.chat.send("Started recording notes. Type \\stoprecord to stop.") }else{MPP.chat.send("Already recording. Type \\stoprecord to stop.")}};break;
- case "stoprecord": {if(recording){recording = false;MPP.chat.send("Stopped recording. Type \\playrecord to play recorded notes. ("+wn.length+" packets received.)");counter = 0}};break;
- case "playrecord": {if(!playing){playing = 1;offset = wn[0].t;wnI = 0;function playwn(){if(playing==1){playnbn(wn[wnI].n);wnI++;setTimeout(playwn,wn[wnI+1].t-wn[wnI].t)}};playwn()}else{MPP.chat.send("Already playing. Please try later.")}};break;
- case "play":case "p":
- {
- var arg=comRest(yomom.a);
- if(arg!=="")
- {
- name = "";
- var song = arg.toLowerCase();
- songs=songList;
- var found=-1;
- if(songList!==undefined)
- {
- if((song/1).toString()=="NaN")
- {
- for(var i=0;!(i>songList.length-1);i++)
- {
- if(songList[i].toLowerCase().slice(songList[i].split(".").length+1).indexOf(song)!==-1)
- {found=i}
- }
- }
- else
- {
- if(songList[song/1] !== undefined)
- {found=song/1}
- }
- };
- if(found!==-1)
- {
- if(playing==1)
- {
- playing=0;
- clearTimeout(timeout)
- };
- MPP.chat.send("Reading file. Index: "+found+" Song: "+songList[found]);
- i=0;
- sec=0;
- play(songList[found])
- }
- else
- {
- MPP.chat.send("Not found.")
- }
- }
- else
- {
- playprecise()
- }
- };break;
- case "console": {if(access(yomom.p._id)){var err;try{var out = eval(comRest(yomom.a));MPP.chat.send("Console: "+((typeof out == "object") ? JSON.stringify(out) : out))} catch(err){MPP.chat.send(err.toString())}}else{MPP.chat.send(randomNoPerm())} };break;
- case "speed":case "tempo": {var rd = comRest(yomom.a);if(!(isNaN(rd/1)) && rd!=="" && isFinite(rd/1))if(rd>10){if(nps*rd/100*v<(100/(1+MPP.client.channel._id!=="RP Room"*9))){speed = rd }else{ speed = ((100/(1+MPP.client.channel._id!=="RP Room"*9))/(nps*v))*100}}else{speed=10};MPP.chat.send("Tempo: "+speed+"%")};break;
- case "dbsave":{if(access(yomom.p._id)){saveParts()}else{MPP.chat.send(randomNoPerm())}};break;
- case "dbload":{if(access(yomom.p._id)){getParts()}else{MPP.chat.send(randomNoPerm())}};break;
- case "posthalting": case "ph":{postHalting = !postHalting;MPP.chat.send("Posthalting "+((postHalting) && "enabled" || "disabled"))};break;
- case "suggestions":{};break;
- case "bin":{
- var code1 = secretChar;
- var code2 = secretChar;
- var isBin = true;
- var txt1 = comRest(yomom.a);
- var txt2 = txt1.split(" ");
- for(var i = 0;i < txt2.length;i++){
- var pr = parseInt(txt2[i],2);
- if(!isNaN(pr)){
- var cha = pr.toString(16);
- code2 += eval("'\\u" + "0".repeat(4 - cha.length) + cha + "'");
- }else{
- isBin = false;
- break;
- };
- };
- if(isBin){
- MPP.chat.send(code2);
- }else{
- for(var i = 0;i < txt1.length;i++){
- code1 += txt1.charCodeAt(i).toString(2) + " ";
- };
- MPP.chat.send(code1);
- }
- };break;
- case "hex":{
- var code1 = secretChar + "0x";
- var code2 = secretChar;
- var txt1 = comRest(yomom.a);
- var txt2 = comRest(yomom.a);
- var isHex = txt1.slice(0,2) == "0x";
- if(isHex){
- for(var i = 2;i < txt2.length;i += 4){
- var pr = txt2.slice(i,i + 4);
- if(!isNaN(pr)){
- code2 += eval("'\\u"+pr+"'");
- };
- };
- MPP.chat.send(code2);
- console.log(code2);
- }else{
- for(var i = 0;i < txt1.length;i++){
- var cha = txt1.charCodeAt(i).toString(16);
- code1 += "0".repeat(4 - cha.length) + cha;
- };
- MPP.chat.send(code1);
- console.log(code1);
- };
- };break;
- case "lenny":{MPP.chat.send("( ͡° ͜ʖ ͡°)")};break;
- case "op":{if(yomom.p.id==MPP.client.getOwnParticipant().id){var p = spart(getArgument(yomom.a,2),true);if(p){addOp(p._id);MPP.chat.send("Opped "+p.name+"; id: "+p._id)}else{MPP.chat.send("User not found.")}}else{MPP.chat.send(randomNoPerm())}};break;
- case "deop":{if(yomom.p.id==MPP.client.getOwnParticipant().id){var p = spart(getArgument(yomom.a,2),true);if(p){deOp(p._id);MPP.chat.send("Deopped "+p.name+"; id: "+p._id)}else{MPP.chat.send("User not found.")}}else{MPP.chat.send(randomNoPerm())}};break;
- case "takecrown":{if(access(yomom.p._id))MPP.client.sendArray([{m: "chown",p: yomom.p.id}])};break;
- case "vq":{vqEnabled = !vqEnabled;MPP.chat.send("Virtual quota "+(vqEnabled && "enabled." || "disabled."))};break;
- case "restart":case "rr": {v = 1;octaveMode = 0;speed = 100;pitch = 0;gAutoSustain = false;octaveDelay = 100;MPP.chat.send("Config reset.")};break;
- case "meow": {MPP.chat.send("I am only a bot. I cannot say 'MEOW'")};break;
- case "autorecord":case "autorec":{MPP.chat.send("Auto recording: " + ((rcEnabled = !rcEnabled) ? "enabled" : "disabled") ); localStorage.rcEnabled = rcEnabled};break;
- case "maxv":{for(var n in window.pre){window.pre[n].b = 1};MPP.chat.send("Volume maximized.")};break;
- case "gms":{var rooms = [];var n = clientArray.length;var nc = 0;var nr = 0;for(var cl in clientArray){if(clientArray[cl].isConnected())nc++;if(clientArray[cl].channel)if(clientArray[cl].channel._id==clientOnRooms[cl]){nr++;rooms.push(clientOnRooms[cl])}};MPP.chat.send("Multi room system state: "+nc+" connected, "+nr+" are on valid rooms. Rooms: "+rooms)};break;
- case "sustain": {gAutoSustain=!gAutoSustain;MPP.chat.send("Sustain: "+gAutoSustain)};break;
- case "magnet": {cursorUpdate=0;var part = MPP.client.findParticipantById(yomom.p._id);MPP.client.sendArray([{m: "m", x: part.x, y: part.y }])};break;
- case "unfollow": {var part=fixName(comRest(yomom.a));var found=[];var current=spart(part !== "" ? part: yomom.p.name.split("\u034f").join(""),true,1);
- if(current !==undefined)
- {found[found.length]=" "+current.name;allParts[current._id].f = 0;
- blacklist[blacklist.length]=current.id;}
- if(found.join().toString()!==""){MPP.chat.send("Unfollowing "+found+" ...")}else{MPP.chat.send("User not found.")}};break;
- case "follow":
- {
- var part=fixName(comRest(yomom.a)),found=[],current={};
- var current = spart(part !== "" ? part: yomom.p.name.split("\u034f").join(""),true,0);if(current!==undefined){
- if(blacklist.indexOf(current._id)!==-1)
- {
- found[found.length]=" "+current.name;
- blacklist[blacklist.indexOf(current.id)]=undefined;
- }
- allParts[current._id].f = 1;
- if(current.name!=="")
- {
- MPP.chat.send("Following "+found+" ...")
- }
- else
- {
- MPP.chat.send("User not found or user is already followed.")
- }
- }
- };break;
- case "whois": {var part=fixName(comRest(yomom.a));var n = 1;if(isNaN(part/1)){spart(part)}else{n=part/1};if(displayPart[0]!==undefined && n<displayPart.length+1){MPP.chat.send('Display participant '+n+' of '+displayPart.length);current = displayPart[n-1];MPP.chat.send("Name: "+current.name+" id: "+current.id+" color: "+current.color+ "( " + (new Color(current.color)).getName() + " ) _id: "+current._id+" x: "+current.x+" y: "+current.y)}else{MPP.chat.send("Not found.")}};break;
- case "whoami": {var current=yomom.p;MPP.chat.send("Name: "+current.name+" id: "+current.id+" color: "+current.color+ "( " + (new Color(current.color)).getName() + " ) _id: "+current._id+" x: "+current.x+" y: "+current.y)};break;
- case "help":case "?": {
- if (getArgument(yomom.a,2)==undefined){
- if(access(yomom.p._id))MPP.chat.send("Admin only: \\console, \\remove <song>, \\userset <name>, \\dbsave, \\dbload, \\save, \\rename, \\setmotd <motd>, \\remove, \\reload, \\takecrown".split("\\").join(prefix))
- ;
- setTimeout(function(){MPP.chat.send("Auto playing & NoTurns: \\play [song], \\sustain, \\volume [volume], \\stop, \\octave, \\octavedelay, \\speed [tempo], \\pitch, \\delay [note delay], \\pos [seconds], \\posthalting, \\list(l) \\vf \\restart(rr) \\autorec".split("\\").join(prefix)) },1000);
- setTimeout(function(){MPP.chat.send("Recording & hopping: \\startrecord, \\stoprecord, \\playrecord, \\follow [player], \\unfollow [player], \\ITball, \\megaphone".split("\\").join(prefix))
- MPP.chat.send("Other: \\help [command], \\motd, \\about, \\voteupload, \\press <notes> <volume>, \\echo, \\megaphone, \\whois [player], \\ping, \\magnet, \\gms, \\multiroom, \\globalsendchat, \\msg, \\big".split("\\").join(prefix))},2000);
- }
- else
- {
- switch((getArgument(yomom.a,2) || "").toLowerCase())
- {
- case "play": {MPP.chat.send(".\\play <song_number> Plays song.")}
- ;break;
- case "speed": {MPP.chat.send(".\\speed <speed> Sets the song playing speed. Optimal speed is 100.")}
- ;break;
- case "stop": {MPP.chat.send(".\\stop Just stops playing song or recording")};break;
- case "console": {MPP.chat.send(".\\console puts the commands into console")};break;
- case "itball": {MPP.chat.send(".\\ITball is a smart answering ball with auto-learning system")};break;
- case "megaphone": {MPP.chat.send(".\\megaphone Turns on or off repeating notes pressed on keyboard.")};break;
- case "record":{MPP.chat.send(".\\startrecord Starts, \\stoprecord stops recording the keyboard notes.")};break;
- case "about": {MPP.chat.send("Peripheral_Assassin's independent recording and playing music bot. Type \\help to see a list of commands")};break;
- case "echo": {MPP.chat.send(".\\echo Turns on or off notifications about players.")};break;
- case "motd": {MPP.chat.send(".\\motd shows message of the day.")};break;
- case "sustain": {MPP.chat.send("Turns auto sustain on and off")};break;
- case "maxv":{};break;
- case "suggestions": {};break;
- case "suggest": {};break; //TODO
- case "gms": {MPP.chat.send("Checks information about bots that are connected to other rooms.")};break;
- case "voteupload":{MPP.chat.send(".\\voteupload allows you to vote for uploading my code.")};break;
- case "pitch": {MPP.chat.send("Use \\pitch to set note offset while playing song or following notes.")};break;
- case "delay": {MPP.chat.send("Type \\delay <ms> to set time between playing multiple notes.")};break;
- case "follow": {MPP.chat.send("Type \\follow <nickname> to let me some information about you (notes)")};break;
- case "unfollow": {MPP.chat.send("Type \\unfollow <nickname> to do not let me some information about you (notes)")};break;
- case "volume": {MPP.chat.send(".\\volume <volume> Sets the song playing volume. Optimal volume is 1.")};break;
- case "press": {MPP.chat.send(".\\press <notes> <volume> Plays simple note on the keyboard. Examples: cs5 1,a4 5,b3 10,g6 69.")};break;
- default: {MPP.chat.send("No help for: "+JSON.stringify(getArgument(yomom.a,2)))};break;
- }
- }
- }
- ;break;
- case "volume":case "v": {var rd = comRest(yomom.a);if(rd!=="" && !(isNaN(rd/1)) && isFinite(rd/1)){if( rd=="mouseY"){snap = 1}else{
- if(nps){
- if(nps*(speed/100)*rd<(100/(1+MPP.client.channel._id!=="RP Room"*9))){v = getArgument(yomom.a,2);snap = 0}else{v = (100/(1+MPP.client.channel._id!=="RP Room"*9))/(nps*(speed/100))}
- }else{
- v = getArgument(yomom.a,2);
- }
- }
- };MPP.chat.send("Volume: "+v)};break;
- case "press": {
- if(getArgument(yomom.a,3)==""){
- MPP.chat.send("Too few arguments. Use: \\press <note> <volume>")
- }else{
- tv = cv;
- var len = yomom.a.split(" ").length;
- vo = parseInt(getArgument(yomom.a,len));
- cv = vo;
- if(vo<=100 && typeof vo == "number"){
- var n = yomom.a.split(" ").slice(1,len - 1);
- for(var u = 0;u<n.length+1;u++){
- MPP.press(n[u],1)
- };
- cv = tv
- }else{MPP.chat.send('Too high volume. Type a number from 0 to 100')} } };break;
- default: {MPP.chat.send("Unknown command. Type \\help for help")};break
- }
- }
- else
- {
- if(false && (wBuffer[2]>Date.now()-40000)&&(yomom.a.indexOf("\'")==-1)&&(wBuffer[1].indexOf("\"")==-1)&&(yomom.a.indexOf("\"")==-1)&&(wBuffer[1].indexOf("\'")==-1)&&(yomom.a.indexOf("\\")==-1)&&(yomom.a.toLowerCase().indexOf("itball")==-1)&&(wBuffer[1].indexOf("\\")==-1))
- {
- if(!(ball[yomom.a]) && !(yomom.a in ball)){ball[wBuffer[1]]=yomom.a;
- addTextToFile("ITball","\nball[\'"+JSON.stringify(wBuffer[1])+"\']=\'"+JSON.stringify(yomom.a)+"\';")};
- var n = 0,w1 = yomom.a.split(" "),w2 = wBuffer[1].split(" ");
- while((w1.length>n)&&(w2.length>n))
- {
- if(!(ball[w1[n]])){ball[w1[n]]=w2[n];
- addTextToFile("ITball","\nball[\'"+w2[n]+"\']=\'"+w1[n]+"\';")};
- n++;
- }
- }
- if(false &&(yomom.a.indexOf("\\")==-1)&&(yomom.a.toLowerCase().indexOf("itball")==-1))
- {wBuffer[1]=yomom.a;
- wBuffer[2]=Date.now();};
- }
- if(blacklist.indexOf(yomom.p.id)==-1)
- {
- if(partsRecorded.indexOf(yomom.p._id)==-1)
- {
- partsRecorded[partsRecorded.length]=yomom.p._id;
- partsNotes[partsNotes.length]=
- {
- lastNote:Date.now(),
- p:yomom.p.name,
- a:[],b:[],c:[],r:[]
- }
- };
- };
- for(var l = 0;l<partsRecorded.length-1;l++)
- {
- if(MPP.client.findParticipantById(partsRecorded[l])==MPP.client.offlineParticipant && partsRecorded[l].indexOf("GROUP")==-1)
- {
- partsRecorded[l] = undefined;
- partsNotes[l] = undefined;
- };
- partsRecorded = partsRecorded.filter(function(a){return a});
- partsNotes = partsNotes.filter(function(a){return a});
- };
- addPart(yomom.p);
- };
- flute();
- function vnum(n){
- return (typeof n == "number") && (Math.abs(n)<200)
- };
- var oMouse = {//mouse position troll
- x: 0,
- y: 0,
- nx: 0,
- ny: 0,
- t: 0,
- idle: 0,
- moveSpeed: 1,
- fIUpdate: function(){
- if(oMouse.t>0 && subrealname!=="Anonymous"){
- if(oMouse.x==0 && oMouse.y==0)console.log("wyzerowal");
- oMouse.x -= (oMouse.x - oMouse.nx) * (1/oMouse.t);
- oMouse.y -= (oMouse.y - oMouse.ny) * (1/oMouse.t);
- oMouse.t--;
- if(vnum(oMouse.x) && vnum(oMouse.y))
- {
- MPP.client.sendArray([{m: "m",x: oMouse.x,y: oMouse.y}]);
- MPP.client.participantUpdate({m: "m",x: oMouse.x,y: oMouse.y,id: MPP.client.getOwnParticipant().id});
- }
- /*else
- {
- console.log(oMouse.x+" "+oMouse.y);
- oMouse.x = 0;
- oMouse.y = 0;
- oMouse.nx = 0;
- oMouse.ny = 0;
- oMouse.t = 0;
- };
- */
- };
- },
- fUpdate: function(m){
- if(vnum(m.x) && vnum(m.y)){
- oMouse.nx = 100-m.x;
- oMouse.ny = 100-m.y;
- var a = oMouse.x-oMouse.nx;
- var b = oMouse.y-oMouse.ny;
- oMouse.t = Math.ceil(Math.sqrt((a*a)+(b*b))/oMouse.moveSpeed);
- if(oMouse.t<1)oMouse.t = 0;
- //console.log(oMouse.t);
- }
- },
- };
- //clearInterval(oMouse.fIUpdate);
- //oMouse.iUpdate = setInterval(oMouse.fIUpdate,50);
- //MPP.client._events.m.pop();
- //MPP.client.on("m",oMouse.fUpdate);
- var partCheck = setInterval(function(){
- partsRecorded.forEach(function(id){
- rec({p: id,n: [],t: 0})
- })
- },10000);
- MPP.client.on("participant removed", function(jomom) {if(echo==1)MPP.chat.send(jomom.name+" left the room")});
- MPP.client.on("participant added", function(jomom) {addPart(jomom);
- if(echo==1){MPP.chat.send("Welcome, "+jomom.name+". Type \\help to get my list of commands!")};if(allParts[jomom._id].f==0){blacklist.push(jomom.id)}});
- MPP.client.on("participant update", function(jomom){addPart(jomom);allParts[jomom._id].name = jomom.name})
- var rcEnabled = (localStorage.rcEnabled !== undefined ? localStorage.rcEnabled : true);
- function rec(jomom) {if(!rcEnabled)return false;
- if(jomom.p == cping){MPP.chat.send("Ping: "+(Date.now()-jomom.t)+" ms.");cping = ""};
- //if(allParts[jomom.p.id] && allParts[jomom.p.id].f == 0)return;
- if(true)//blacklist.indexOf(jomom.p)==-1)
- {
- if(partsRecorded.indexOf(jomom.p)==-1)
- {
- partsRecorded[partsRecorded.length]=jomom.p;
- partsNotes[partsNotes.length]=
- {
- lastNote:jomom.t,
- lastPlayed: Date.now(),
- p:MPP.client.findParticipantById(jomom.p).name,
- a:[],
- b:[],
- c:[],
- r:[]
- }
- };
- var delay = 0, delaykill = [0,0,0],lastd = 0,played = false, id = partsRecorded.indexOf(jomom.p), counterb = jomom.t-partsNotes[id].lastNote;
- if(counterb>10000 || (Date.now()-(partsNotes[id].lastPlayed || Date.now()) > 20000))
- {
- var wait=0;
- partsNotes.forEach(function(pn)
- {
- if(((jomom.t-pn.lastNote)>10000) || ((pn.lastPlayed || 0) + 20000 < Date.now()))
- {
- if(pn.a.length>250)
- {
- pn.c[0]=0;
- var songname = "";
- if(partsRecorded[partsNotes.indexOf(pn)].indexOf("GROUP")!==-1)
- {songname = partsRecorded[partsNotes.indexOf(pn)]}
- else
- {songname = fixName(MPP.client.findParticipantById(partsRecorded[partsNotes.indexOf(pn)]).name)}
- addSong("MPP - recording("+songname+")",exportSong(pn.a,pn.b,pn.c,pn.r));
- }
- pn.a=[];
- pn.b=[];
- pn.c=[];
- pn.r=[]
- }
- }
- )};
- var gr = getGroup(jomom.p)
- if(gr!==-1)
- {
- var renew = jomom;
- renew.p="GROUP"+gr;
- return rec(renew)
- }
- for(var d = 0;d<jomom.n.length;d++)
- {
- if(jomom.n[d].s==undefined)
- {
- played = true;
- partsNotes[id].b[partsNotes[id].b.length]=jomom.n[d].v;
- partsNotes[id].a[partsNotes[id].a.length]=jomom.n[d].n;
- if(d>0)
- {
- if(jomom.n[d].d!==undefined)
- {
- lastd = jomom.n[d].d;
- delaykill[delaykill.length]=jomom.n[d].d
- }
- else
- {
- delaykill[delaykill.length]=delaykill[delaykill.length-1]
- }
- }
- delay=delaykill[delaykill.length-1]-delaykill[delaykill.length-2];
- partsNotes[id].c[partsNotes[id].c.length]=Math.round(counterb+delay);
- counterb=0;
- if(partsNotes[id].b[partsNotes[id].b.length-1]==undefined)
- {
- partsNotes[id].b[partsNotes[id].b.length-1]=1
- };
- }
- else //defining length of notes (r)
- {
- var time = 0;
- for(var l = partsNotes[id].a.length-1;l>0;l--)
- {
- time+=partsNotes[id].c[l];
- if(partsNotes[id].a[l] == jomom.n[d].n)
- {
- partsNotes[id].r[l] = Math.round(time);
- l = 0;
- }
- }
- }
- if(played)
- {
- partsNotes[id].lastNote=jomom.t+lastd;
- partsNotes[id].lastPlayed = Date.now();
- }
- };
- };addPart(jomom.p)
- if(recording)
- wn.push(jomom)
- };
- var tClient = 0;
- motd = "This is the default message of the day.";
- MPP.client.on("n", rec);
- MPP.client.on("n", function(jomom) {if(megaphone==1 && blacklist.indexOf(jomom.p._id)==-1){if(MPP.client.noteBuffer.length>50 && warn == 1){MPP.chat.send("Note spam detected. Stopping...");megaphone=0}else{var delay = 0;var d = 0;playnbn(jomom.n,d,delay)}} })
- MPP.client.on("a", function(yomom) {wazne(yomom)});
- MPP.client.on("ls",function(ls){
- if(multiRoom){
- var rooms = "";for(var i in ls.u) {if(!ls.u.hasOwnProperty(i)) continue;if(clientOnRooms.indexOf(ls.u[i]._id)==-1){clientOnRooms.push(ls.u[i]._id);
- clientArray.push(new Client("ws:multiplayerpiano.com:443"));
- clientArray[clientArray.length-1].on("a",function(msg){
- if(this.channel._id!==MPP.client.channel._id){var pmsg = msg;pmsg.p.name="["+this.channel._id+"] "+pmsg.p.name;MPP.chat.receive(pmsg)
- if(msg.a[0]==prefix)
- switch(msg.a.slice(1).split(" ")[0].toLowerCase()){
- case "msg":{if(msg.a.indexOf("|")!=-1){privateMessage(msg.a,msg.p.name)}else{this.sendArray([{m: "a", message: "Please use "|" to separate room and message."}])}};break;
- case "globalsendchat":case "gsc":{if(comRest(msg.a).indexOf("\\")==-1)gMessage(comRest(msg.a),msg.p.name)};break;
- case "motd":{this.sendArray([{m: "a", message: motd}])};break
- case "help":{this.sendArray([{m: "a", message: "Local commands: \\msg <room>| <message>, \\globalsendchat, \\gsc <message>, \\help. See room "+MPP.client.channel._id+" to get full list of commands.".split("\\").join(prefix)}])};break;
- }
- }
- })
- clientArray[clientArray.length-1].on("participant added", function(jomom) {addPart(jomom);allParts[jomom._id].id = jomom.id;if(allParts[jomom._id].f==0 && blacklist.indexOf(jomom.id)==-1){blacklist.push(jomom._id)}});
- clientArray[clientArray.length-1].on("participant update", function(jomom){addPart(jomom);allParts[jomom._id].name = fixName(jomom.name)});
- clientArray[clientArray.length-1].chatsend = function(msg){this.sendArray([{m: "a", message: msg}]);
- }}
- for(var c in clientArray){if(clientArray[c].isConnected()){clientArray[c].stop()};};
- for(var c in clientArray){clientArray[c].setChannel(clientOnRooms[c]);clientArray[c].start();};
- MPP.client.sendArray([{m: "-ls"}]);
- clearTimeout(tClient);
- tClient = setTimeout(function(){var connected = 0,number = clientArray.length,valid = 0;for(var c in clientArray){if(clientArray[c].isConnected())connected++;if(clientArray[c].channel)if(clientArray[c].channel._id==clientOnRooms[c])valid++};MPP.chat.send("Reloading clients: "+number+" loaded, "+connected+" connected, "+valid+" valid.")},10000)
- }
- };
- });
- multiroom = false;
- var speed = 100;var playing = 0;var v = 1;var i = -1;function st() {if (i<a.length && playing == 1){if(cfix==1 && c[i]>10000){c[i]=10000}setTimeout(function () {if(v>1){ultrapress(a[i],b[i]*v)}else{MPP.press(a[i],b[i]*v)};i++;st();{}},c[i]/speed*100)}else {playing = 0}};
- function play(song){getSong(song);setTimeout(function(){if(songcode.length>50 || songcode!=="")
- {i=0;sec=0;setTimeout(function(){eval(songcode);playprecise(song)},1000)}
- else{remove("songs/"+song);MPP.chat.send("Critical error, file lost.");getSongList()}},500)
- }
- echo=0;
- var wait = 100;var dmg = 0;var rdmg = 0;
- function chordWow(){rdmg++;if(repeatkeys[rdmg]==undefined){rdmg=0;dmg++};if(dmg>6){dmg=0};MPP.press(repeatkeys[rdmg]+dmg);setTimeout(chordWow,wait)};
- function clearChat(ch){var cha = ch || "\u3164";MPP.client.sendArray([{m: "userset",set: {name: cha.repeat(32)}}]);for(var y = 0;y<4;y++){MPP.chat.send((cha.repeat(15) + "\u3164").repeat(32))}};
- code="";
- //file="ITball.txt";getFile();setTimeout(function(){eval(code)},2000);
- function putNote(n,v,d){}
- // pitch faller test: var test = setInterval(function(){pitch = Math.round(MPP.client.getOwnParticipant().x/2-25)},100);
- setTimeout(function(){getParts()},4000);
- setTimeout(function(){for(var p in MPP.client.ppl){if(allParts[MPP.client.ppl[p]._id].f==0){blacklist.push(MPP.client.ppl[p].id)}}},10000);
- flute();
- var foundBN = [];var best = {i: -1,n: "",s: -Infinity};
- function searchByNote(notes){foundBN = [];best = {i: -1,n: "",s: -Infinity};
- window.requestFileSystem(window.PERSISTENT, 1024*1024, function(fs) {
- fs.root.getDirectory('songs', {}, function(dirEntry) {
- dfg.forEach(function(f){
- dirEntry.getFile(f, {}, function(fileEntry) {
- // Get a File object representing the file,
- // then use FileReader to read its contents.
- fileEntry.file(function(file) {
- var reader = new FileReader();
- reader.onloadend = function(e) {
- eval(this.result);
- var index = 0;var score = 0;
- for(var n = 0;n<a.length-1;n++){if(keys.indexOf(notes[index+1])==-1){score+=100;break};var r = keys.indexOf(notes[index])-keys.indexOf(notes[index+1]);if(r==keys.indexOf(a[n])-keys.indexOf(a[n+1])){score+=20;index++}else{score-=1};};
- foundBN.push({i: songList.indexOf(f),n: f,s: score});
- if(foundBN.length==songList.length){foundBN = foundBN.sort(function(a,b){var bs =(a.s>b.s && a || b);if(bs.s>best.s){best = bs};return a.s>b.s});MPP.chat.send("Index: "+best.i+"; Song: "+best.n+"; Score: "+best.s)};
- };
- reader.readAsText(file);
- }, errorHandler);
- }, errorHandler);
- });
- }, errorHandler);
- }, errorHandler);};
- function loadingAnimation(nickLength){
- window.strla = "___________LOADING_PLEASE_WAIT";
- window.laidx = 0;
- window.lanl = nickLength;
- window.laintr = setInterval(function(){
- if(laidx < strla.length - lanl){
- subrealname = strla.slice(laidx,laidx + lanl + 1);
- laidx++;
- }else{
- subrealname = "\u29BF_RECORDER_\u29BF";
- setTimeout(function(){subrealname = "PeriOS (PL)"},10000);
- clearInterval(laintr);
- };
- },2000);
- };
- loadingAnimation(11);
- getSongList();
- var secretChar = "\u034f";
- var supernamechanger = setInterval(function(){var n = subrealname;for(var i = subrealname.length/2;i>0;i--){var sl = Math.ceil(Math.random()*subrealname.length);n = n.slice(0,sl)+secretChar+n.slice(sl)};realName = n;if(playing==0)MPP.client.sendArray([{m: "userset", set: {name: realName}}])},2500);
- var PC = {prefix: "&"},broenabled = false;
- var tbroadcast = setInterval(function(){if(broenabled)MPP.chat.send("[OS] "+broadcasts[Math.floor(Math.random()*(broadcasts.length))].join(""))},300000);
- window.broadcasts =
- [
- ["Type ",PC.prefix,"help to get pianocraft game commands!"],
- ["Type ",prefix,"help to get my bot commands!"],
- ["Get newest version of my bot here: http://pastebin.com/3HCZVRe4"],
- ["Added new command: "+prefix+"gms ! Use this to read information about my bots connected to other rooms."],
- ["If you don't want to record your songs, just type ",prefix,"unfollow to disable it."]
- ];
- String.prototype.formatUnicode = function(){
- let replaced = this;
- let chs = {
- f: ["F"],
- r: ["R"],
- o: ["O"],
- m: ["M"],
- };
- let reps = {};
- for(var c in chs){
- for (var trep in chs[c]){
- reps[chs[c][trep]] = c;
- };
- };
- //console.log(reps)
- for(var rep in reps){
- replaced = replaced.replace(eval("/"+rep+"/g"),reps[rep])
- };
- return replaced;
- };
- var lBlocks = {
- A: ["\u2597","\u2599","\u258c\u2005","\u2596","\u259f","\u2005\u2590"],
- B: [],
- };
- function getFairTimeOffset(){ //atlas module, i hope it'll be working
- var quota = 1; //nope
- var offset = 0;
- for(var i = 0;i < c.length;i++){
- quota += c[i] / 10;
- if(quota < 1){
- offset += 10;
- }else{
- quota--;
- }
- };
- return offset; //in ms
- };
- var dataB = {
- s: 0,
- e: 0,
- t: 0,
- idx: 0,
- it: 0,
- };
- function extractPack(){
- var now = Date.now();
- var pack = {m: "n",n: [],t: now};
- for(var i = 0;i < 88;i++){
- var id = dataB.idx;
- if(id == undefined)break;
- pack.n.push({n: a[id], v: b[id], d: (dataB.s - now)});
- dataB.s += c[id];
- dataB.idx++;
- };
- return pack;
- };
- function playWithOffset(ms){
- if(ms){
- dataB.s = Date.now() + ms;
- dataB.e = dataB.s + songLength * 1000;
- dataB.idx = 0;
- dataB.it = setInterval(function(){
- MPP.client.sendArray([extractPack()]);
- if(dataB.idx >= a.length - 1)clearInterval(dataB.it);
- },880);
- return dataB.it;
- };
- };
- /*
- var can = document.createElement("canvas");
- var ctx = can.getContext("2d");
- var longest = 0;
- var dchar = "_";
- var its = 16*16*16*16 - 1;
- for(var i = 0;i < its;i++){
- try{
- var hid = toHex(i);
- var char = eval("'\\u" + "0".repeat(4 - hid.length) + hid + "'");
- var len = ctx.measureText(eval("'\\u" + "0".repeat(4 - hid.length) + hid + "'"));
- if(len.width > longest){
- longest = len.width;
- dchar = char;
- };
- }catch(err){console.log(i)}
- };
- */
- function spamSong(){if(dataB.s >= dataB.e){var ms = getFairTimeOffset();return playWithOffset(ms)}};
- var display = 1;
- var spamPacks = []
- function G(n,d){return {n: n,v: 1,d: d || 0}};
- function H(d){var arr = [];for(var k in MPP.piano.keys){arr.push(new G(k,d))};return arr};
- function overPlay(d,dt){MPP.client.sendArray([{m: "n",n: new SNotes(d), t: dt || Date.now()}])};
- function testPack(delay){var arr = [];var d = 0;for(var k in MPP.piano.keys){arr.push(new G(k,d));d += delay};return arr};
- function S(s,d){spamPacks = [];display = d;
- for(var i = 0;i < s;i++){
- spamPacks.push(new H(i * 860));
- };spamPacks.forEach(function(a,b){setTimeout(function(){MPP.client.sendArray([{m:"n",n:a,t:Date.now()}])},(s - b) * 860)});
- setTimeout(function(){var sp = new H(0);for(var i = 0;i < 5;i++){MPP.client.sendArray([{m:"n",n:sp, t:Date.now()}])}},s * 860)};
Advertisement
Add Comment
Please, Sign In to add comment