diff --git a/hydra-server/public/bundle.js b/hydra-server/public/bundle.js
new file mode 100644
index 0000000..f463c86
--- /dev/null
+++ b/hydra-server/public/bundle.js
@@ -0,0 +1,119057 @@
+(function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o {
+ sketches.saveSketch(code)
+ }
+ editor.shareSketch = menu.shareSketch.bind(menu)
+ // if a sketch was found based on the URL parameters, dont show intro window
+ if(sketchFromURL) {
+ menu.closeModal()
+ } else {
+ menu.openModal()
+ }
+ })
+ menu.sketches = sketches
+
+ // define extra functions (eventually should be added to hydra-synth?)
+
+ // hush clears what you see on the screen
+ window.hush = () => {
+ solid().out()
+ solid().out(o1)
+ solid().out(o2)
+ solid().out(o3)
+ render(o0)
+ }
+
+
+ pb.init(hydra.captureStream, {
+ server: window.location.origin,
+ room: 'iclc'
+ })
+
+ var engine = loop(function(dt) {
+ hydra.tick(dt)
+ }).start()
+
+}
+
+window.onload = init
+
+},{"./src/editor.js":2,"./src/gallery.js":4,"./src/menu.js":5,"./src/p5-wrapper.js":6,"./src/pb-live.js":7,"hydra-synth":61,"raf-loop":91}],2:[function(require,module,exports){
+/* eslint-disable no-eval */
+var CodeMirror = require('codemirror/lib/codemirror')
+require('codemirror/mode/javascript/javascript')
+require('codemirror/addon/hint/javascript-hint')
+require('codemirror/addon/hint/show-hint')
+require('codemirror/addon/selection/mark-selection')
+
+var isShowing = true
+
+var EditorClass = function () {
+ var self = this
+
+ this.cm = CodeMirror.fromTextArea(document.getElementById('code'), {
+ theme: 'tomorrow-night-eighties',
+ value: 'hello',
+ mode: {name: 'javascript', globalVars: true},
+ lineWrapping: true,
+ styleSelectedText: true,
+ extraKeys: {
+ 'Shift-Ctrl-Enter': function (instance) {
+ self.evalAll((code, error) => {
+ console.log('evaluated', code, error)
+ // if(!error){
+ // self.saveSketch(code)
+ // }
+ })
+ },
+ 'Shift-Ctrl-G': function (instance) {
+ self.shareSketch()
+ },
+ 'Shift-Ctrl-H': function (instance) {
+ var l = document.getElementsByClassName('CodeMirror-scroll')[0]
+ var m = document.getElementById('modal-header')
+ if (isShowing) {
+ l.style.opacity = 0
+ self.logElement.style.opacity = 0
+ m.style.opacity = 0
+ isShowing = false
+ } else {
+ l.style.opacity= 1
+ m.style.opacity = 1
+ self.logElement.style.opacity = 1
+ isShowing = true
+ }
+ },
+ 'Ctrl-Enter': function (instance) {
+ var c = instance.getCursor()
+ var s = instance.getLine(c.line)
+ self.eval(s)
+ },
+ 'Shift-Ctrl-W': function (instance) {
+
+ },
+ 'Shift-Ctrl-S': function (instance) {
+ screencap()
+ },
+ 'Alt-Enter': (instance) => {
+ var text = self.selectCurrentBlock(instance)
+ console.log('text', text)
+ self.eval(text.text)
+ }
+ }
+ })
+
+ this.cm.markText({line: 0, ch: 0}, {line: 6, ch: 42}, {className: 'styled-background'})
+ this.cm.refresh()
+ this.logElement = document.createElement('div')
+ this.logElement.className = "console cm-s-tomorrow-night-eighties"
+ document.body.appendChild(this.logElement)
+ this.log("hi")
+
+
+ // TO DO: add show code param
+ let searchParams = new URLSearchParams(window.location.search)
+ let showCode = searchParams.get('show-code')
+
+ if(showCode == "false") {
+ console.log("not showing code")
+ var l = document.getElementsByClassName('CodeMirror-scroll')[0]
+ l.style.display = 'none'
+ self.logElement.style.display = 'none'
+ isShowing = false
+ }
+ //}
+}
+
+EditorClass.prototype.clear = function () {
+ this.cm.setValue('\n \n // Type some code on a new line (such as "osc().out()"), and press CTRL+shift+enter')
+}
+
+EditorClass.prototype.saveSketch = function(code) {
+ console.log('no function for save sketch has been implemented')
+}
+
+EditorClass.prototype.shareSketch = function(code) {
+ console.log('no function for share sketch has been implemented')
+}
+
+// EditorClass.prototype.saveExample = function(code) {
+// console.log('no function for save example has been implemented')
+// }
+
+EditorClass.prototype.evalAll = function (callback) {
+ this.eval(this.cm.getValue(), function (code, error){
+ if(callback) callback(code, error)
+ })
+}
+
+EditorClass.prototype.eval = function (arg, callback) {
+ var self = this
+ var jsString = arg
+ var isError = false
+ try {
+ eval(jsString)
+ self.log(jsString)
+ } catch (e) {
+ isError = true
+ // console.log("logging", e.message)
+ self.log(e.message, "log-error")
+ //console.log('ERROR', JSON.stringify(e))
+ }
+// console.log('callback is', callback)
+ if(callback) callback(jsString, isError)
+
+}
+
+EditorClass.prototype.log = function(msg, className = "") {
+ this.logElement.innerHTML =` >> ${msg} `
+}
+
+EditorClass.prototype.selectCurrentBlock = function (editor) { // thanks to graham wakefield + gibber
+ var pos = editor.getCursor()
+ var startline = pos.line
+ var endline = pos.line
+ while (startline > 0 && editor.getLine(startline) !== '') {
+ startline--
+ }
+ while (endline < editor.lineCount() && editor.getLine(endline) !== '') {
+ endline++
+ }
+ var pos1 = {
+ line: startline,
+ ch: 0
+ }
+ var pos2 = {
+ line: endline,
+ ch: 0
+ }
+ var str = editor.getRange(pos1, pos2)
+ return {
+ start: pos1,
+ end: pos2,
+ text: str
+ }
+}
+
+module.exports = EditorClass
+
+},{"codemirror/addon/hint/javascript-hint":18,"codemirror/addon/hint/show-hint":19,"codemirror/addon/selection/mark-selection":20,"codemirror/lib/codemirror":21,"codemirror/mode/javascript/javascript":22}],3:[function(require,module,exports){
+module.exports=[
+ {
+ "sketch_id": "example_0",
+ "code":"JTJGJTJGJTIwYnklMjBTZWJhc3RpYW4lMjBBdmlsYSUwQSUyRiUyRiUyMGh0dHAlM0ElMkYlMkZ3d3cuc2ViYXN0aWFuLWF2aWxhLmNvbSUyRiUwQSUwQWEuc2hvdygpJTBBJTJGJTJGU09VTkQlMEElMEFhLnNldFNjYWxlJTIwKDEwJTIwJTIwKSUwQWEuc2V0QmlucyUyMCg2KSUwQSUyRiUyRiUwQWEuc2V0dGluZ3MlNUIwJTVELmN1dG9mZiUyMCUzRCUyMDElMEFhLnNldHRpbmdzJTVCMSU1RC5jdXRvZmYlMjAlM0QlMjAyJTBBYS5zZXR0aW5ncyU1QjIlNUQuY3V0b2ZmJTIwJTNEJTIwNCUwQWEuc2V0dGluZ3MlNUIzJTVELmN1dG9mZiUyMCUzRCUyMDYlMEFhLnNldHRpbmdzJTVCNCU1RC5jdXRvZmYlMjAlM0QlMjA4JTBBYS5zZXR0aW5ncyU1QjUlNUQuY3V0b2ZmJTIwJTNEJTIwOSUwQSUwQXNoYXBlKDMpLnNjYWxlKCgpJTNEJTNFJTIwYS5mZnQlNUI0JTVEKjIlMjAlMkIxKS5rYWxlaWQoMiklMEEuYWRkKG9zYygxMikuY29sb3JhbWEoMSkuY29sb3IoMiUyQzMlMkM0KSklMEEuYmxlbmQobzApLmNvbG9yKDAlMkMxJTJDMSklMEEuYmxlbmQobzApLnJvdGF0ZSgoKSUzRCUzRSUyMGEuZmZ0JTVCMSU1RCowLjElMjAtMC4yKSUwQS5zY3JvbGxZKC0wLjMyJTJDLTAuMiklMEEuYWRkKHNoYXBlKDcpLmNvbG9yKDIlMkMxJTJDMC41KS5yZXBlYXQoLTMlMkMzKS5hZGQoc2hhcGUoMikuc2NhbGUoMSkua2FsZWlkKDUpLmNvbG9yKDAlMkMxJTJDMC41KSkuc2Nyb2xsWSgoKSUzRCUzRSUyMGEuZmZ0JTVCMCU1RCowLjclMjAtMC4xJTJDLTAuMDIpKS5zY2FsZSgoKSUzRCUzRSUyMGEuZmZ0JTVCMiU1RCowLjIlMjAtMSklMEElMkYlMkYuc2NhbGUoKCklM0QlM0UlMjBhLmZmdCU1QjMlNUQqMiUyMC0xKSUwQS5zY3JvbGxZKC0yMSUyQy0wLjIpJTBBLnJvdGF0ZSgtMC4xJTJDKCklM0QlM0UlMjBhLmZmdCU1QjMlNUQqMC4wMiUyMC0wLjEpJTBBLm91dChvMCk="
+},{
+ "sketch_id": "example_1",
+ "code":"JTJGJTJGJTIwYnklMjBTZWJhc3RpYW4lMjBBdmlsYSUwQSUyRiUyRiUyMGh0dHAlM0ElMkYlMkZ3d3cuc2ViYXN0aWFuLWF2aWxhLmNvbSUyRiUwQSUwQWEuc2hvdygpJTBBJTJGJTJGU09VTkQlMEElMEFhLnNldFNjYWxlJTIwKDEwJTIwJTIwKSUwQWEuc2V0QmlucyUyMCg2KSUwQSUyRiUyRiUwQWEuc2V0dGluZ3MlNUIwJTVELmN1dG9mZiUyMCUzRCUyMDElMEFhLnNldHRpbmdzJTVCMSU1RC5jdXRvZmYlMjAlM0QlMjAyJTBBYS5zZXR0aW5ncyU1QjIlNUQuY3V0b2ZmJTIwJTNEJTIwNCUwQWEuc2V0dGluZ3MlNUIzJTVELmN1dG9mZiUyMCUzRCUyMDYlMEFhLnNldHRpbmdzJTVCNCU1RC5jdXRvZmYlMjAlM0QlMjA4JTBBYS5zZXR0aW5ncyU1QjUlNUQuY3V0b2ZmJTIwJTNEJTIwOSUwQSUwQSUwQSUwQW9zYygzMjIpLmNvbG9yKDAlMkMwJTJDMCklMEEuYWRkKHNoYXBlKDIpLmNvbG9yKDIlMkMyJTJDMikuc2NhbGUoMC4wMDYpLnJvdGF0ZSgwLjAwMDAwMSkpJTBBLm1vZHVsYXRlKG5vaXNlKCgpJTNEJTNFJTIwYS5mZnQlNUIxJTVEKjEwJTIwJTJCMC4wMSkuc2NhbGUoNSUyQzAuMSkpJTBBLnNjYWxlKDEuMiUyQzElMkMzKSUwQSUyRiUyRi5zY2FsZSgoKSUzRCUzRSUyMGEuZmZ0JTVCMyU1RCowLjElMjAtMiklMEElMkYlMkYucmVwZWF0KDElMkM1KSUwQSUyRiUyRi5yb3RhdGUoMSUyQygpJTNEJTNFJTIwYS5mZnQlNUIzJTVEKjElMjAlMkIwLjAxKSUwQS5vdXQobzAp"
+},{
+ "sketch_id": "example_2",
+ "code":"JTJGJTJGJTIwYnklMjBTZWJhc3RpYW4lMjBBdmlsYSUwQSUyRiUyRiUyMGh0dHAlM0ElMkYlMkZ3d3cuc2ViYXN0aWFuLWF2aWxhLmNvbSUyRiUwQSUwQSUyRiUyRiUwQSUwQWEuc2V0U2NhbGUlMjAoMTAlMjAlMjApJTBBYS5zZXRCaW5zJTIwKDYpJTBBJTJGJTJGJTBBYS5zZXR0aW5ncyU1QjAlNUQuY3V0b2ZmJTIwJTNEJTIwMSUwQWEuc2V0dGluZ3MlNUIxJTVELmN1dG9mZiUyMCUzRCUyMDIlMEFhLnNldHRpbmdzJTVCMiU1RC5jdXRvZmYlMjAlM0QlMjA0JTBBYS5zZXR0aW5ncyU1QjMlNUQuY3V0b2ZmJTIwJTNEJTIwNiUwQWEuc2V0dGluZ3MlNUI0JTVELmN1dG9mZiUyMCUzRCUyMDglMEFhLnNldHRpbmdzJTVCNSU1RC5jdXRvZmYlMjAlM0QlMjA5JTBBJTBBJTBBc2hhcGUoNCkuc2NhbGUoKCklM0QlM0UlMjBhLmZmdCU1QjQlNUQqMiUyMCUyQjEpJTBBLmJsZW5kKG8wKS5hZGQoc2hhcGUoMykuY29sb3IoMCUyQzAlMkMwLjcpKSUwQS5ibGVuZChvMCkuY29sb3IoMSUyQzElMkMxKSUwQS5ibGVuZChvMCkucm90YXRlKCgpJTNEJTNFJTIwYS5mZnQlNUIxJTVEKjAuMSUyMC0wLjIpJTBBLnNjcm9sbFkoLTAuMzIlMkMtMC4yKSUwQS5hZGQoc2hhcGUoMjApLmNvbG9yKDIlMkMwJTJDMCkuc2Nyb2xsWSgoKSUzRCUzRSUyMGEuZmZ0JTVCMCU1RCowLjclMjAtMC4xJTJDLTAuMDIpKS5zY2FsZSgoKSUzRCUzRSUyMGEuZmZ0JTVCMiU1RCowLjclMjAtMC44KSUwQS5zY2FsZSgoKSUzRCUzRSUyMGEuZmZ0JTVCMyU1RCoyJTIwLTEpJTBBLm1vZHVsYXRlKG8wJTJDKCklM0QlM0UlMjBhLmZmdCU1QjIlNUQqMC4xJTIwLTAuMiklMEEucm90YXRlKC0wLjElMkMoKSUzRCUzRSUyMGEuZmZ0JTVCMyU1RCowLjclMjAtMC4xKSUwQS5vdXQobzAp"
+},{
+ "sketch_id": "example_3",
+ "code":"JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTBBb3NjKDIwJTJDJTIwMC4wMyUyQyUyMDEuNykua2FsZWlkKCkubXVsdChvc2MoMjAlMkMlMjAwLjAwMSUyQyUyMDApLnJvdGF0ZSgxLjU4KSkuYmxlbmQobzAlMkMlMjAwLjk0KS5tb2R1bGF0ZVNjYWxlKG9zYygxMCUyQyUyMDApJTJDLTAuMDMpLnNjYWxlKDAuOCUyQyUyMCgpJTIwJTNEJTNFJTIwKDEuMDUlMjAlMkIlMjAwLjElMjAqJTIwTWF0aC5zaW4oMC4wNSp0aW1lKSkpLm91dChvMCk="
+},{
+ "sketch_id": "example_4",
+ "code":"JTJGJTJGJTIwYnklMjBOZWxzb24lMjBWZXJhJTBBJTJGJTJGJTIwdHdpdHRlciUzQSUyMCU0MG5lbF9zb25vbG9naWElMEElMEFvc2MoOCUyQy0wLjUlMkMlMjAxKS5jb2xvcigtMS41JTJDJTIwLTEuNSUyQyUyMC0xLjUpLmJsZW5kKG8wKS5yb3RhdGUoLTAuNSUyQyUyMC0wLjUpLm1vZHVsYXRlKHNoYXBlKDQpLnJvdGF0ZSgwLjUlMkMlMjAwLjUpLnNjYWxlKDIpLnJlcGVhdFgoMiUyQyUyMDIpLm1vZHVsYXRlKG8wJTJDJTIwKCklMjAlM0QlM0UlMjBtb3VzZS54JTIwKiUyMDAuMDAwNSkucmVwZWF0WSgyJTJDJTIwMikpLm91dChvMCklMEElMEElMEElMEElMEElMEE="
+},{
+ "sketch_id": "example_5",
+ "code":"JTJGJTJGJTIwYnklMjBEJUMzJUE5Ym9yYSUyMEZhbGxlaXJvcyUyMEdvbnphbGVzJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZ3d3cuZ29uemFsZXNkZWJvcmEuY29tJTJGJTBBJTBBYS5zaG93KCklMEElMEFhLmhpZGUoKSUwQSUwQWEuc2hvdygpJTBBJTIwJTIwb3NjKDEwKSUwQSUyMCUyMC5hZGQobm9pc2UoOSUyQyUyMDUpKSUwQSUyMCUyMC5yZXBlYXQoNSklMEElMjAlMjAlMjAlMjAuY29sb3IoJTBBJTIwJTIwJTIwJTIwJTIwJTIwKCklMjAlM0QlM0UlMjAlN0IlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjBpZihhLmZmdCU1QjAlNUQlMjAlM0UlMjAwLjQpJTIwcmV0dXJuJTIwMC4xJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwZWxzZSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMHJldHVybiUyMDAuNiUwQSUyMCUyMCUyMCUyMCUyMCUyMCU3RCUyQyUwQSUyMCUyMCUyMCUyMCUyMCUyMDAuMiUyQyUyMDAuNiUyQyUyMDAuNCUwQSUyMCUyMCUyMCUyMCklMEElMjAlMjAlMjAlMjAlMjAuY29sb3JhbWEoMC43JTJDJTIwMC41KSUwQSUyMCUyMCUyMCUyMC5vdXQoKSUwQSUwQSUyMCUyMCUyMCUyMCUwQSUwQWEuc2V0U21vb3RoKDAuMyklMEElMEFhLnNldEN1dG9mZig2KSUwQSUwQWEuc2V0U2NhbGUoMyklMEElMEFhLnNldEJpbnMoNiklMEElMEFhLnNldHRpbmdzJTVCMCU1RC5jdXRvZmYlMjAlM0QlMjAyJTBBJTBBYS5zZXR0aW5ncyU1QjAlNUQuc2NhbGUlMjAlM0QlMjA0"
+},{
+ "sketch_id": "example_6",
+ "code":"JTJGJTJGJTIwYnklMjBEJUMzJUE5Ym9yYSUyMEZhbGxlaXJvcyUyMEdvbnphbGVzJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZ3d3cuZ29uemFsZXNkZWJvcmEuY29tJTJGJTBBJTBBb3NjKDUpLmFkZChub2lzZSg1JTJDJTIwMikpLmNvbG9yKDAlMkMlMjAwJTJDJTIwMykuY29sb3JhbWEoMC40KS5vdXQoKSUwQSUwQSUwQSUwQQ=="
+},{
+ "sketch_id": "example_7",
+ "code":"JTJGJTJGJTIwYnklMjBSb2RyaWdvJTIwVmVsYXNjbyUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGeWVjdG8uZ2l0aHViLmlvJTJGJTBBJTBBb3NjKDMlMkMlMjAwLjIlMkMlMjAwKS5jb2xvcigyJTJDJTIwMC43JTJDJTIwMSkubW9kdWxhdGUobzElMkMlMjAwLjgpLmRpZmYobzEpLm91dChvMCklMEFvc2MoKCklMjAlM0QlM0UlMjAoYS5mZnQlNUIwJTVEKjM5KSUyQyUyMDAuMiUyQyUyMDApLmNvbG9yKDAlMkMlMjAxJTJDJTIwMikucm90YXRlKDEuNTcpLm91dChvMSklMEFvc2MoMzAlMkMlMjAwLjIlMkMlMjAwKS5vdXQobzIp"
+},{
+ "sketch_id": "example_8",
+ "code":"JTJGJTJGJTIwYnklMjBSb2RyaWdvJTIwVmVsYXNjbyUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGeWVjdG8uZ2l0aHViLmlvJTJGJTBBJTBBb3NjKDEwNyUyQyUyMDAlMkMlMjAwLjcpLmNvbG9yKDElMkMlMjAwJTJDJTIwMSkucm90YXRlKDAlMkMlMjAtMC4wOCkubW9kdWxhdGVSb3RhdGUobzElMkMlMjAwLjQpLm91dChvMCklMEFvc2MoMzMpLnJvdGF0ZSgyJTJDJTIwMC44KS5tb2R1bGF0ZVJvdGF0ZShvMCUyQyUyMCgpJTIwJTNEJTNFJTIwKGEuZmZ0JTVCMCU1RCoyKSkub3V0KG8xKSUwQQ=="
+},{
+ "sketch_id": "example_9",
+ "code":"JTJGJTJGJTIwYnklMjBSb2RyaWdvJTIwVmVsYXNjbyUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGeWVjdG8uZ2l0aHViLmlvJTJGJTBBJTBBb3NjKDE4JTJDJTIwMC4xJTJDJTIwMCkuY29sb3IoMiUyQyUyMDAuMSUyQyUyMDIpJTBBLm11bHQob3NjKDIwJTJDJTIwMC4wMSUyQyUyMDApKS5yZXBlYXQoMiUyQyUyMDIwKS5yb3RhdGUoMC41KS5tb2R1bGF0ZShvMSklMEEuc2NhbGUoMSUyQyUyMCgpJTIwJTNEJTNFJTIwJTIwKGEuZmZ0JTVCMCU1RCowLjklMjAlMkIlMjAyKSkuZGlmZihvMSkub3V0KG8wKSUwQW9zYygyMCUyQyUyMDAuMiUyQyUyMDApLmNvbG9yKDIlMkMlMjAwLjclMkMlMjAwLjEpLm11bHQob3NjKDQwKSkubW9kdWxhdGVSb3RhdGUobzAlMkMlMjAwLjIpJTBBLnJvdGF0ZSgwLjIpLm91dChvMSk="
+},{
+ "sketch_id": "example_10",
+ "code":"JTJGJTJGJTIwYnklMjBaYWNoJTIwS3JhbGwlMEElMkYlMkYlMjBodHRwJTNBJTJGJTJGemFjaGtyYWxsLm9ubGluZSUyRiUwQSUwQW9zYyglMjAyMTUlMkMlMjAwLjElMkMlMjAyJTIwKSUwQS5tb2R1bGF0ZSglMEElMjAlMjBvc2MoJTIwMiUyQyUyMC0wLjMlMkMlMjAxMDAlMjApJTBBJTIwJTIwLnJvdGF0ZSgxNSklMEEpJTBBLm11bHQoJTBBJTIwJTIwb3NjKCUyMDIxNSUyQyUyMC0wLjElMkMlMjAyKSUwQSUyMCUyMC5waXhlbGF0ZSglMjA1MCUyQyUyMDUwJTIwKSUwQSklMEEuY29sb3IoJTIwMC45JTJDJTIwMC4wJTJDJTIwMC45JTIwKSUwQS5tb2R1bGF0ZSglMEElMjAlMjBvc2MoJTIwNiUyQyUyMC0wLjElMjApJTBBJTIwJTIwLnJvdGF0ZSglMjA5JTIwKSUwQSklMEEuYWRkKCUwQSUyMCUyMG9zYyglMjAxMCUyQyUyMC0wLjklMkMlMjA5MDAlMjApJTBBJTIwJTIwLmNvbG9yKDElMkMwJTJDMSklMEEpJTBBLm11bHQoJTBBJTIwJTIwc2hhcGUoOTAwJTJDJTIwMC4yJTJDJTIwMSklMEElMjAlMjAubHVtYSgpJTBBJTIwJTIwLnJlcGVhdFgoMiklMEElMjAlMjAucmVwZWF0WSgyKSUwQSUyMCUyMC5jb2xvcmFtYSgxMCklMEEpJTBBLm1vZHVsYXRlKCUwQSUyMCUyMG9zYyglMjA5JTJDJTIwLTAuMyUyQyUyMDkwMCUyMCklMEElMjAlMjAucm90YXRlKCUyMDYlMjApJTBBKSUwQS5hZGQoJTBBJTIwJTIwb3NjKDQlMkMlMjAxJTJDJTIwOTApJTBBJTIwJTIwLmNvbG9yKDAuMiUyQzAlMkMxKSUwQSklMEEub3V0KCklMEE="
+},{
+ "sketch_id": "example_11",
+ "code": "JTJGJTJGJTIwYnklMjBaYWNoJTIwS3JhbGwlMEElMkYlMkYlMjBodHRwJTNBJTJGJTJGemFjaGtyYWxsLm9ubGluZSUyRiUwQSUwQW9zYygxMCUyQyUyMDAuOSUyQyUyMDMwMCklMEEuY29sb3IoMC45JTJDJTIwMC43JTJDJTIwMC44KSUwQS5kaWZmKCUwQSUyMCUyMG9zYyg0NSUyQyUyMDAuMyUyQyUyMDEwMCklMEElMjAlMjAuY29sb3IoMC45JTJDJTIwMC45JTJDJTIwMC45KSUwQSUyMCUyMC5yb3RhdGUoMC4xOCklMEElMjAlMjAucGl4ZWxhdGUoMTIpJTBBJTIwJTIwLmthbGVpZCgpJTBBKSUwQS5zY3JvbGxYKDEwKSUwQS5jb2xvcmFtYSgpJTBBLmx1bWEoKSUwQS5yZXBlYXRYKDQpJTBBLnJlcGVhdFkoNCklMEEubW9kdWxhdGUoJTBBJTIwJTIwb3NjKDElMkMlMjAtMC45JTJDJTIwMzAwKSUwQSklMEEuc2NhbGUoMiklMEEub3V0KCklMEE="
+},{
+ "sketch_id": "example_13",
+ "code":"JTJGJTJGJTIwYWNpZCUyMGJ1cyUyMHNlYXQlMEElMkYlMkYlMjBieSUyMFdpbGwlMjBIdW1waHJleXMlMEElMkYlMkYlMjBodHRwcyUzQSUyRiUyRmdpdGh1Yi5jb20lMkZUaGVXaXNweSUwQSUwQW9zYygxMDUpLmNvbG9yKDAuNSUyQzAuMSUyQzAuOCkucm90YXRlKDAuMTElMkMlMjAwLjEpLm1vZHVsYXRlKG9zYygxMCkucm90YXRlKDAuMykuYWRkKG8wJTJDJTIwMC4xKSkuYWRkKG9zYygyMCUyQzAuMDElMkMxKS5jb2xvcigwJTJDMC44JTJDMSkpLm91dChvMCklMEFvc2MoNTAlMkMwLjA1JTJDJTIwMC43KS5jb2xvcigxJTJDMC43JTJDMC41KS5kaWZmKG8wKS5tb2R1bGF0ZShvMSUyQzAuMDUpLm91dChvMSklMEFyZW5kZXIobzEp"
+},
+{
+ "sketch_id": "example_14",
+ "code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwJTQwX29qYWNrXyUwQSUwQW9zYygyMCUyQyUyMDAuMDElMkMlMjAxLjEpJTBBJTA5LmthbGVpZCg1KSUwQSUwOS5jb2xvcigyLjgzJTJDMC45MSUyQzAuMzkpJTBBJTA5LnJvdGF0ZSgwJTJDJTIwMC4xKSUwQSUwOS5tb2R1bGF0ZShvMCUyQyUyMCgpJTIwJTNEJTNFJTIwbW91c2UueCUyMColMjAwLjAwMDMpJTBBJTA5LnNjYWxlKDEuMDEpJTBBJTIwJTIwJTA5Lm91dChvMCk="
+},
+{
+ "sketch_id": "example_15",
+ "code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZvamFjay5naXRodWIuaW8lMEElMEFvc2MoMTAwJTJDJTIwMC4wMSUyQyUyMDEuNCklMEElMDkucm90YXRlKDAlMkMlMjAwLjEpJTBBJTA5Lm11bHQob3NjKDEwJTJDJTIwMC4xKS5tb2R1bGF0ZShvc2MoMTApLnJvdGF0ZSgwJTJDJTIwLTAuMSklMkMlMjAxKSklMEElMDkuY29sb3IoMi44MyUyQzAuOTElMkMwLjM5KSUwQSUyMCUyMC5vdXQobzAp"
+},
+{
+ "sketch_id": "example_16",
+ "code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZvamFjay5naXRodWIuaW8lMEElMEFvc2MoNCUyQyUyMDAuMSUyQyUyMDAuOCkuY29sb3IoMS4wNCUyQzAlMkMlMjAtMS4xKS5yb3RhdGUoMC4zMCUyQyUyMDAuMSkucGl4ZWxhdGUoMiUyQyUyMDIwKS5tb2R1bGF0ZShub2lzZSgyLjUpJTJDJTIwKCklMjAlM0QlM0UlMjAxLjUlMjAqJTIwTWF0aC5zaW4oMC4wOCUyMColMjB0aW1lKSkub3V0KG8wKQ=="
+},
+{
+ "sketch_id": "example_17",
+ "code": "JTJGJTJGJTIwbW9pcmUlMEElMkYlMkYlMjBieSUyME9saXZpYSUyMEphY2slMEElMkYlMkYlMjB0d2l0dGVyJTNBJTIwJTQwX29qYWNrXyUwQSUwQXBhdHRlcm4lMjAlM0QlMjAoKSUyMCUzRCUzRSUyMG9zYygyMDAlMkMlMjAwKS5rYWxlaWQoMjAwKS5zY2FsZSgxJTJDJTIwMC40KSUwQSUyRiUyRiUwQXBhdHRlcm4oKSUwQSUyMCUyMC5zY3JvbGxYKDAuMSUyQyUyMDAuMDEpJTBBJTIwJTIwLm11bHQocGF0dGVybigpKSUwQSUyMCUyMC5vdXQoKQ=="
+},
+{
+ "sketch_id": "example_18",
+ "code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZvamFjay5naXRodWIuaW8lMEElMEFvc2MoNiUyQyUyMDAlMkMlMjAwLjgpJTBBJTIwJTIwLmNvbG9yKDEuMTQlMkMlMjAwLjYlMkMuODApJTBBJTIwJTIwLnJvdGF0ZSgwLjkyJTJDJTIwMC4zKSUwQSUyMCUyMC5waXhlbGF0ZSgyMCUyQyUyMDEwKSUwQSUyMCUyMC5tdWx0KG9zYyg0MCUyQyUyMDAuMDMpLnRocmVzaCgwLjQpLnJvdGF0ZSgwJTJDJTIwLTAuMDIpKSUwQSUyMCUyMC5tb2R1bGF0ZVJvdGF0ZShvc2MoMjAlMkMlMjAwKS50aHJlc2goMC4zJTJDJTIwMC42KSUyQyUyMCgpJTIwJTNEJTNFJTIwMC4xJTIwJTJCJTIwbW91c2UueCUyMColMjAwLjAwMiklMEElMjAlMjAub3V0KG8wKQ=="
+}
+]
+
+},{}],4:[function(require,module,exports){
+const request = require('superagent')
+const examples = require('./examples.json')
+const sketches = []
+
+
+class Gallery {
+ constructor (callback) {
+ this.sketches = []
+ this.examples = []
+ this.current = null
+ this.code = null
+ this.exampleIndex = null
+
+ // request.get('/sketches').end((err, res) => {
+ // console.log('got sketches', res.text, err)
+ // if(err) {
+ // console.log('err getting sketches', err)
+ // } else {
+ // this.sketches = JSON.parse(res.text)
+ // }
+
+ this.examples = examples
+ this.setSketchFromURL(callback)
+ // callback(this.code, this.foundSketch)
+ // })
+ }
+
+ clear() {
+ this.current = null
+ this.code = null
+ this.exampleIndex = null
+ let newurl = window.location.protocol + '//' + window.location.host + window.location.pathname
+ window.history.pushState({ path: newurl }, '', newurl)
+ this.url = newurl
+ }
+
+ setSketchFromURL(callback) {
+ let searchParams = new URLSearchParams(window.location.search)
+ let base64Code = searchParams.get('code')
+ if(!base64Code) base64Code = searchParams.get('id') // backwards compatibility with earlier form of naming. id is now called code
+ let sketch_id = searchParams.get('sketch_id')
+ let code = ''
+ console.log("id", sketch_id, "code", base64Code)
+
+ // boolean to determine whether a sketch was found based on the URL, either through looking through the database or rendering the code
+ this.foundSketch = false
+ // if contains a sketch id, set sketch from id
+ if(sketch_id) {
+ //var sketch = this.getSketchById(sketch_id)
+ request
+ .get('/sketchById')
+ .query({sketch_id: sketch_id})
+ .end((err, res) => {
+ console.log('got sketches', res.text, err)
+ if(err) {
+ console.log('err getting sketches', err)
+ this.setSketchFromCode(base64Code, callback)
+ } else {
+ this.sketches = JSON.parse(res.text)
+ if(this.sketches.length > 0) {
+ this.setSketch(this.sketches[0])
+ //this.code = this.decodeBase64(this.sketches[0].code)
+ this.foundSketch = true
+ callback(this.code, this.foundSketch)
+ } else {
+ this.setSketchFromCode(base64Code, callback)
+ }
+ }
+ })
+ } else {
+ this.setSketchFromCode(base64Code, callback)
+ }
+ //
+ //
+ // // console.log('found ', sketch)
+ // // if(sketch) {
+ // // this.setSketch(sketch)
+ // // this.foundSketch = true0
+ // // } else if (base64Code){
+ // // this.code = this.decodeBase64(base64Code)
+ // // this.foundSketch = true
+ // // } else {
+ // // console.log('id not found', sketch_id)
+ // // this.setRandomSketch()
+ // // }
+ //
+ // // // backwards combaitbility with earlier shareable URLS
+ // } else {
+ //
+ // if (base64Code) {
+ // this.code = this.decodeBase64(base64Code)
+ // this.foundSketch = true
+ // } else {
+ // this.setRandomSketch()
+ // }
+ // }
+ }
+
+ setSketchFromCode(base64Code, callback){
+ if (base64Code) {
+ this.code = this.decodeBase64(base64Code)
+ this.foundSketch = true
+ } else {
+ this.setRandomSketch()
+ }
+ callback(this.code, this.foundSketch)
+ }
+
+ saveImage() {
+
+ }
+
+ setToURL(params){
+ // console.log(base64)
+ console.log('params', params)
+
+ // keep code in url for backwards compatibility / compatibility between local and public versions
+ var url_params = `sketch_id=${params.sketch_id}&code=${params.code}`
+ // } else {
+ // url_params = params.map( (param, index) => `${param.label}=${param.value}`).join('&')
+ // }
+ console.log('url params', url_params)
+ let newurl = window.location.protocol + '//' +
+ window.location.host + window.location.pathname + '?' + url_params
+ window.history.pushState({ path: newurl }, '', newurl)
+ this.url = newurl
+ }
+
+ encodeBase64(text) {
+ return btoa(encodeURIComponent(text))
+ }
+ decodeBase64(base64Code) {
+ return decodeURIComponent(atob(base64Code))
+ }
+
+ setSketch(sketch) {
+ this.code = this.decodeBase64(sketch.code)
+ this.current = sketch
+ // this.setToURL('sketch_id', sketch._id)
+ // let params = Object.keys(sketch).map( (key) => {
+ // return {label: key, value: sketch[key]}
+ // })
+ this.setToURL(sketch)
+ }
+
+ setRandomSketch() {
+ // if there are sketches, set code from sketch, otherwise generate random
+ console.log("examples length", this.examples)
+ if(this.examples.length > 0) {
+ let rand = Math.floor(Math.random() * this.examples.length)
+ while (rand === this.exampleIndex) {
+ rand = Math.floor(Math.random() * this.examples.length)
+ }
+ this.exampleIndex = rand
+ console.log('example is', this.examples[rand])
+ this.setSketch(this.examples[rand])
+ } else {
+ var startString = 'osc(' + 2 + Math.floor(Math.pow(10, Math.random() * 2)) + ')'
+ startString += '.color(' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2)+ ')'
+ startString += '.rotate(' + Math.random().toFixed(2) + ')'
+ startString += '.out(o0)'
+ this.code = startString
+ }
+ }
+
+ // shares via twitter
+ shareSketch(code, hydra, name) {
+ this.saveSketch(code, () => {
+ console.log("URL is", this.url, 'sketch is', this.current)
+ hydra.getScreenImage((img) => {
+ request
+ .post('/image')
+ .attach('previewImage', img)
+ .query({
+ url: this.url,
+ sketch_id: this.current.sketch_id,
+ name: name
+ })
+ // .send({
+ // code: base64
+ // })
+ // .query(query)
+ .end((err, res) => {
+ if(err) {
+ console.log('error postingimage', err)
+ } else {
+ console.log('image response', res.text)
+ // self.setToURL([ { label: 'sketch_id', value: res.text}, {label: 'code', value: base64} ])
+
+ }
+ })
+ // var oReq = new XMLHttpRequest();
+ // oReq.open("POST", "https://localhost:8000/image", true);
+ // oReq.onload = function (oEvent) {
+ // // Uploaded.
+ // console.log("uploaded", oEvent)
+ // };
+ // oReq.send(img);
+ // console.log('got image', img)
+ })
+ })
+ }
+
+ saveSketch(code, callback) {
+ let self = this
+ //console.log('saving in gallery', code)
+ let base64 = this.encodeBase64(code)
+ // console.log('code is', base64)
+
+ let query = {
+ code: base64,
+ parent: this.current ? this.current.sketch_id : null
+ }
+
+ console.log('saving in gallery', query)
+ request
+ .post('/sketch')
+ // .send({
+ // code: base64
+ // })
+ .query(query)
+ .end((err, res) => {
+ if(err) {
+ console.log('error posting sketch', err)
+ if(callback) callback(err)
+ } else {
+ console.log('response', res.text)
+ // self.setToURL([ { label: 'sketch_id', value: res.text}, {label: 'code', value: base64} ])
+ self.setSketch({
+ sketch_id: res.text,
+ code: base64
+ })
+ if(callback) callback(null)
+ }
+ })
+ }
+
+ getSketchById(id) {
+ console.log('looking for', id)
+ var sketch = this.sketches.filter((sketch) => sketch.sketch_id === id)
+ return sketch[0]
+ }
+}
+
+module.exports = Gallery
+
+},{"./examples.json":3,"superagent":133}],5:[function(require,module,exports){
+
+
+
+class Menu {
+ constructor (obj) {
+ this.sketches = obj.sketches
+ this.editor = obj.editor
+ this.hydra = obj.hydra
+
+ // variables related to popup window
+ this.closeButton = document.getElementById("close-icon")
+ this.clearButton = document.getElementById("clear-icon")
+ this.shareButton = document.getElementById("share-icon")
+ this.shuffleButton = document.getElementById("shuffle-icon")
+ this.editorText = document.getElementsByClassName('CodeMirror-scroll')[0]
+
+ this.shuffleButton.onclick = this.shuffleSketches.bind(this)
+ this.shareButton.onclick = this.shareSketch.bind(this)
+ this.clearButton.onclick = this.clearAll.bind(this)
+ this.closeButton.onclick = () => {
+ if(!this.isClosed) {
+ this.closeModal()
+ } else {
+ this.openModal()
+ }
+ }
+
+ this.isClosed = false
+ this.closeModal()
+ }
+
+ shuffleSketches() {
+ this.clearAll()
+ this.sketches.setRandomSketch()
+ this.editor.cm.setValue(this.sketches.code)
+ this.editor.evalAll()
+ }
+
+ shareSketch() {
+ this.editor.evalAll((code, error) => {
+ console.log('evaluated', code, error)
+ if(!error){
+ this.showConfirmation( (name) => {
+ this.sketches.shareSketch(code, this.hydra, name)
+ }, () => this.hideConfirmation() )
+ }
+ })
+ }
+
+ showConfirmation(successCallback, terminateCallback) {
+ var c = prompt("Pressing OK will share this sketch to \nhttps://twitter.com/hydra_patterns.\n\nInclude your name or twitter handle (optional):")
+ console.log('confirm value', c)
+ if (c !== null) {
+ successCallback(c)
+ } else {
+ terminateCallback()
+ }
+ }
+
+ hideConfirmation() {
+
+ }
+
+ clearAll() {
+ hush()
+ this.sketches.clear()
+ this.editor.clear()
+ //@todo: add clear/reset function to hydra
+ }
+
+ closeModal () {
+ document.getElementById("info-container").className = "hidden"
+ this.closeButton.className = "fas fa-question-circle icon"
+ this.shareButton.classList.remove('hidden')
+ this.clearButton.classList.remove('hidden')
+ this.editorText.style.opacity = 1
+ this.isClosed = true
+ }
+
+ openModal () {
+ document.getElementById("info-container").className = ""
+ this.closeButton.className = "fas fa-times icon"
+ this.shareButton.classList.add('hidden')
+ this.clearButton.classList.add('hidden')
+ this.editorText.style.opacity = 0.0
+ this.isClosed = false
+ }
+
+}
+
+module.exports = Menu
+
+},{}],6:[function(require,module,exports){
+//'use babel'
+
+const p5lib = require('p5')
+require('p5/lib/addons/p5.dom')
+
+class P5 extends p5lib{
+ constructor ({
+ width = window.innerWidth,
+ height = window.innerHeight,
+ mode = 'P2D'
+ } = {}) {
+ //console.log('createing canvas', width, height, window.innerWidth, window.innerHeight)
+ super(( p ) => {
+ p.setup = () => { p.createCanvas(width, height, p[mode]) }
+ // p.setup = () => { p.createCanvas() }
+ p.draw = () => { }
+ }, 'hydra-ui')
+ this.width = width
+ this.height = height
+ this.mode = mode
+ this.canvas.style.position = "absolute"
+ this.canvas.style.top = "0px"
+ this.canvas.style.left = "0px"
+ this.canvas.style.zIndex = -1
+ // console.log('p5', this)
+ // return this.p5
+ }
+
+ show() {
+ this.canvas.style.zIndex = -1
+ }
+
+ hide() {
+ this.canvas.style.zIndex = -10
+ }
+
+ // p5 clear function not covering canvas
+ clear() {
+ this.drawingContext.clearRect(0, 0, this.canvas.width, this.canvas.height)
+ }
+}
+
+module.exports = P5
+
+},{"p5":85,"p5/lib/addons/p5.dom":84}],7:[function(require,module,exports){
+/* globals sessionStorage */
+// Extends rtc-patch-bay to include support for nicknames and persistent session storage
+
+var PatchBay = require('./rtc-patch-bay.js')
+//var PatchBay = require('./../../../../rtc-patch-bay')
+var inherits = require('inherits')
+
+var PBLive = function () {
+ this.session = {}
+
+ // lookup tables for converting id to nickname
+ this.nickFromId = {}
+ this.idFromNick = {}
+
+ this.loadFromStorage()
+}
+// inherits from PatchBay module
+inherits(PBLive, PatchBay)
+
+PBLive.prototype.init = function (stream, opts) {
+ this.settings = {
+ server: opts.server || 'https://patch-bay.glitch.me/',
+ room: opts.room || 'patch-bay',
+ stream: stream
+ }
+
+ this.makeGlobal = opts.makeGlobal || true
+ this.setPageTitle = opts.setTitle || true
+
+ if (this.session.id) this.settings.id = this.session.id
+
+ PatchBay.call(this, this.settings)
+
+ if (this.makeGlobal) window.pb = this
+
+ this.on('ready', () => {
+ // console.log("ID:", this._userData.uuid, this.session.id)
+ if (!this.nick) {
+ if (this.session.nick) {
+ this.setName(this.session.nick)
+ } else {
+ this.session.id = this.id
+ this.setName(this.session.id)
+ }
+ }
+ console.log('connected to server ' + this.settings.server + ' with name ' + this.settings.id)
+ })
+ // received a broadcast
+ this.on('broadcast', this._processBroadcast.bind(this))
+ this.on('new peer', this.handleNewPeer.bind(this))
+
+ window.onbeforeunload = () => {
+ this.session.id = window.pb.id
+ this.session.nick = this.nick
+ sessionStorage.setItem('pb', JSON.stringify(this.session))
+ }
+
+ var self = this
+ this.on('stream', function (id, stream) {
+ console.log('got stream!', id, stream)
+ const video = document.createElement('video')
+ video.src = window.URL.createObjectURL(stream)
+ video.addEventListener('loadedmetadata', () => {
+ // console.log("loaded meta22")
+ video.play()
+ self.video = video
+ self.emit('got video', self.nickFromId[id], video)
+ })
+ })
+}
+
+PBLive.prototype.loadFromStorage = function () {
+ if (sessionStorage.getItem('pb') !== null) {
+ this.session = JSON.parse(sessionStorage.getItem('pb'))
+ }
+}
+
+PBLive.prototype.initSource = function (nick, callback) {
+ this.initConnectionFromId(this.idFromNick[nick], callback)
+// this.peers[this.idFromNick[nick]].streamCallback = callback
+}
+
+// default nickname is just peer id.
+// to do: save nickname information between sessions
+PBLive.prototype.handleNewPeer = function (peer) {
+ // console.log("new peer", peer)
+ this.nickFromId[peer] = peer
+ this.idFromNick[peer] = peer
+ // console.log("THIS IS THE PEER", peer)
+ // to do: only send to new peer, not to all
+ if (this.nick) {
+ this.broadcast({
+ type: 'update-nick',
+ id: this.id,
+ nick: this.nick
+ })
+ }
+}
+
+PBLive.prototype.list = function () {
+ var l = Object.keys(this.idFromNick)
+ console.log(l)
+ return Object.keys(this.idFromNick)
+}
+
+// choose an identifying name
+PBLive.prototype.setName = function (nick) {
+ this.broadcast({
+ type: 'update-nick',
+ id: this.id,
+ nick: nick,
+ previous: this.nick
+ })
+ this.nick = nick
+ if (this.setPageTitle) document.title = nick
+}
+
+PBLive.prototype._processBroadcast = function (data) {
+ if (data.type === 'update-nick') {
+ if (data.previous !== data.nick) {
+ delete this.idFromNick[this.nickFromId[data.id]]
+ this.nickFromId[data.id] = data.nick
+ this.idFromNick[data.nick] = data.id
+ if (data.previous) {
+ console.log(data.previous + ' changed to ' + data.nick)
+ } else {
+ console.log('connected to ' + data.nick)
+ }
+ }
+ }
+}
+// PBExtended.prototype.
+module.exports = PBLive
+
+},{"./rtc-patch-bay.js":8,"inherits":78}],8:[function(require,module,exports){
+// Module for handling connections to multiple peers.
+
+
+var io = require('socket.io-client')
+var SimplePeer = require('simple-peer')
+var extend = Object.assign
+var events = require('events').EventEmitter
+var inherits = require('inherits')
+const shortid = require('shortid')
+
+var PatchBay = function (options) {
+// connect to websocket signalling server. To DO: error validation
+ this.signaller = io(options.server)
+
+ //assign unique id to this peer, or use id passed in
+
+ this.id = options.id || shortid.generate()
+
+ this.stream = options.stream || null
+
+ //options to be sent to simple peer
+ this._peerOptions = options.peerOptions || {}
+ this._room = options.room
+
+
+ this.settings = {
+ shareMediaWhenRequested: true,
+ shareMediaWhenInitiating: false,
+ requestMediaWhenInitiating: true,
+ autoconnect: false
+ }
+
+ //object containing ALL peers in room
+ this.peers = {}
+
+ //object containing peers connected via webrtc
+ this.rtcPeers = {}
+
+ // Handle events from signalling server
+ this.signaller.on('ready', this._readyForSignalling.bind(this))
+// this.signaller.on('peers', )
+// this.signaller.on('signal', this._handleSignal.bind(this))
+ this.signaller.on('message', this._handleMessage.bind(this))
+ // Received message via websockets to all peers in room
+ this.signaller.on('broadcast', this._receivedBroadcast.bind(this))
+
+ // emit 'join' event to signalling server
+ this.signaller.emit('join', this._room, {uuid: this.id})
+
+ this.signaller.on('new peer', this._newPeer.bind(this))
+}
+// inherits from events module in order to trigger events
+inherits(PatchBay, events)
+
+// send data to all connected peers via data channels
+PatchBay.prototype.sendToAll = function (data) {
+ Object.keys(this.rtcPeers).forEach(function (id) {
+ this.rtcPeers[id].send(data)
+ }, this)
+}
+
+// sends to peer specified b
+PatchBay.prototype.sendToPeer = function (peerId, data) {
+ if (peerId in this.rtcPeers) {
+ this.rtcPeers[peerId].send(data)
+ }
+}
+
+PatchBay.prototype.reinitAll = function(){
+ Object.keys(this.rtcPeers).forEach(function (id) {
+ this.reinitPeer(id)
+ }.bind(this))
+// this._connectToPeers.bind(this)
+}
+
+PatchBay.prototype.initRtcPeer = function(id, opts) {
+ this.emit('new peer', {id: id})
+ var newOptions = opts
+ console.log()
+ if(this.iceServers) {
+ opts['config'] = {
+ iceServers: this.iceServers
+ }
+ }
+
+ if(opts.initiator === true) {
+ if (this.stream != null) {
+ if(this.settings.shareMediaWhenInitiating === true){
+ newOptions.stream = this.stream
+ }
+ }
+ if(this.settings.requestMediaWhenInitiating === true){
+ newOptions.offerConstraints = {
+ offerToReceiveVideo: true,
+ offerToReceiveAudio: true
+ }
+ }
+ } else {
+ if(this.settings.shareMediaWhenRequested === true){
+ if (this.stream != null) {
+ newOptions.stream = this.stream
+ }
+ }
+ }
+ var options = extend(this._peerOptions, newOptions)
+console.log("OPTIONS", options)
+ this.rtcPeers[id] = new SimplePeer(options)
+ this._attachPeerEvents(this.rtcPeers[id], id)
+}
+
+PatchBay.prototype.reinitRtcConnection = function(id, opts){
+ // Because renegotiation is not implemeneted in SimplePeer, reinitiate connection when configuration has changed
+ this.rtcPeers[id]._destroy(null, function(e){
+ this.initRtcPeer(id, {
+ stream: this.stream,
+ initiator: true
+ })
+ }.bind(this))
+}
+// //new peer connected to signalling server
+PatchBay.prototype._newPeer = function (peer){
+ // this.connectedIds.push(peer)
+
+
+ // Configuration for specified peer.
+ // Individual configuration controls whether will receive media from
+ // and/or send media to a specific peer.
+
+ this.peers[peer] = {
+ rtcPeer: null
+ }
+
+ this.emit('new peer', peer)
+ // this.emit('updated peer list', this.connectedIds)
+}
+// // Once the new peer receives a list of connected peers from the server,
+// // creates new simple peer object for each connected peer.
+PatchBay.prototype._readyForSignalling = function ({ peers, servers }) {
+// console.log("received peer list", _t, this.peers)
+
+ peers.forEach((peer) => {
+ this._newPeer(peer)
+ })
+
+ // if received ice and turn server information from signalling server, use in establishing
+ if(servers) {
+ this.iceServers = servers
+ }
+// this.peers = peers
+ this.emit('ready')
+}
+
+// Init connection to RECEIVE video
+PatchBay.prototype.initConnectionFromId = function(id, callback){
+// console.log("initianing connection")
+ if(id in this.rtcPeers){
+ console.log("Already connected to..", id, this.rtcPeers)
+ //if this peer was originally only sending a stream (not receiving), recreate connecting but this time two-way
+ if(this.rtcPeers[id].initiator===false){
+ this.reinitRtcConnection(id)
+ } else {
+ //already connected, do nothing
+
+ }
+ } else {
+ this.initRtcPeer(id, {
+ initiator: true
+ })
+ }
+}
+
+
+// receive signal from signalling server, forward to simple-peer
+PatchBay.prototype._handleMessage = function (data) {
+ // if there is currently no peer object for a peer id, that peer is initiating a new connection.
+
+ if (data.type === 'signal'){
+ this._handleSignal(data)
+ } else {
+ this.emit('message', data)
+ }
+}
+// receive signal from signalling server, forward to simple-peer
+PatchBay.prototype._handleSignal = function (data) {
+ // if there is currently no peer object for a peer id, that peer is initiating a new connection.
+ if (!this.rtcPeers[data.id]) {
+ // this.emit('new peer', data)
+ // var options = extend({stream: this.stream}, this._peerOptions)
+ // this.rtcPeers[data.id] = new SimplePeer(options)
+ // this._attachPeerEvents(this.rtcPeers[data.id], data.id)
+
+ this.initRtcPeer(data.id, {initiator: false})
+ }
+ this.rtcPeers[data.id].signal(data.message)
+}
+// sendToAll send through rtc connections, whereas broadcast
+// send through the signalling server. Useful in cases where
+// not all peers are connected via webrtc with other peers
+PatchBay.prototype._receivedBroadcast = function(data) {
+ //console.log("RECEIVED BROADCAST", data)
+ this.emit('broadcast', data)
+}
+
+//sends via signalling server
+PatchBay.prototype.broadcast = function (data) {
+ this.signaller.emit('broadcast', data)
+}
+// handle events for each connected peer
+PatchBay.prototype._attachPeerEvents = function (p, _id) {
+ p.on('signal', function (id, signal) {
+ // console.log('signal', id, signal)
+ // console.log("peer signal sending over sockets", id, signal)
+ // this.signaller.emit('signal', {id: id, signal: signal})
+ this.signaller.emit('message', {id: id, message: signal, type: 'signal'})
+ }.bind(this, _id))
+
+ p.on('stream', function (id, stream) {
+ this.rtcPeers[id].stream = stream
+ // console.log('E: stream', id, stream)
+ // console.log("received a stream", stream)
+ this.emit('stream', id, stream)
+ }.bind(this, _id))
+
+ p.on('connect', function (id) {
+ // console.log("connected to ", id)
+ this.emit('connect', id)
+ }.bind(this, _id))
+
+ p.on('data', function (id, data) {
+// console.log('data', id)
+ this.emit('data', {id: id, data: JSON.parse(data)})
+ }.bind(this, _id))
+
+ p.on('close', function (id) {
+ //console.log('CLOSED')
+ delete (this.rtcPeers[id])
+ this.emit('close', id)
+ }.bind(this, _id))
+
+ p.on('error', function(e){
+ console.log("simple peer error", e)
+ })
+}
+
+PatchBay.prototype._destroy = function () {
+ Object.values(this.rtcPeers).forEach( function (peer) {
+ peer.destroy()
+ })
+ this.signaller.close()
+}
+
+
+module.exports = PatchBay
+
+},{"events":16,"inherits":78,"shortid":108,"simple-peer":118,"socket.io-client":122}],9:[function(require,module,exports){
+module.exports = after
+
+function after(count, callback, err_cb) {
+ var bail = false
+ err_cb = err_cb || noop
+ proxy.count = count
+
+ return (count === 0) ? callback() : proxy
+
+ function proxy(err, result) {
+ if (proxy.count <= 0) {
+ throw new Error('after called too many times')
+ }
+ --proxy.count
+
+ // after first error, rest are passed to err_cb
+ if (err) {
+ bail = true
+ callback(err)
+ // future error callbacks will go to error handler
+ callback = err_cb
+ } else if (proxy.count === 0 && !bail) {
+ callback(null, result)
+ }
+ }
+}
+
+function noop() {}
+
+},{}],10:[function(require,module,exports){
+/**
+ * An abstraction for slicing an arraybuffer even when
+ * ArrayBuffer.prototype.slice is not supported
+ *
+ * @api public
+ */
+
+module.exports = function(arraybuffer, start, end) {
+ var bytes = arraybuffer.byteLength;
+ start = start || 0;
+ end = end || bytes;
+
+ if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
+
+ if (start < 0) { start += bytes; }
+ if (end < 0) { end += bytes; }
+ if (end > bytes) { end = bytes; }
+
+ if (start >= bytes || start >= end || bytes === 0) {
+ return new ArrayBuffer(0);
+ }
+
+ var abv = new Uint8Array(arraybuffer);
+ var result = new Uint8Array(end - start);
+ for (var i = start, ii = 0; i < end; i++, ii++) {
+ result[ii] = abv[i];
+ }
+ return result.buffer;
+};
+
+},{}],11:[function(require,module,exports){
+
+/**
+ * Expose `Backoff`.
+ */
+
+module.exports = Backoff;
+
+/**
+ * Initialize backoff timer with `opts`.
+ *
+ * - `min` initial timeout in milliseconds [100]
+ * - `max` max timeout [10000]
+ * - `jitter` [0]
+ * - `factor` [2]
+ *
+ * @param {Object} opts
+ * @api public
+ */
+
+function Backoff(opts) {
+ opts = opts || {};
+ this.ms = opts.min || 100;
+ this.max = opts.max || 10000;
+ this.factor = opts.factor || 2;
+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
+ this.attempts = 0;
+}
+
+/**
+ * Return the backoff duration.
+ *
+ * @return {Number}
+ * @api public
+ */
+
+Backoff.prototype.duration = function(){
+ var ms = this.ms * Math.pow(this.factor, this.attempts++);
+ if (this.jitter) {
+ var rand = Math.random();
+ var deviation = Math.floor(rand * this.jitter * ms);
+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
+ }
+ return Math.min(ms, this.max) | 0;
+};
+
+/**
+ * Reset the number of attempts.
+ *
+ * @api public
+ */
+
+Backoff.prototype.reset = function(){
+ this.attempts = 0;
+};
+
+/**
+ * Set the minimum duration
+ *
+ * @api public
+ */
+
+Backoff.prototype.setMin = function(min){
+ this.ms = min;
+};
+
+/**
+ * Set the maximum duration
+ *
+ * @api public
+ */
+
+Backoff.prototype.setMax = function(max){
+ this.max = max;
+};
+
+/**
+ * Set the jitter
+ *
+ * @api public
+ */
+
+Backoff.prototype.setJitter = function(jitter){
+ this.jitter = jitter;
+};
+
+
+},{}],12:[function(require,module,exports){
+/*
+ * base64-arraybuffer
+ * https://github.com/niklasvh/base64-arraybuffer
+ *
+ * Copyright (c) 2012 Niklas von Hertzen
+ * Licensed under the MIT license.
+ */
+(function(){
+ "use strict";
+
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+ // Use a lookup table to find the index.
+ var lookup = new Uint8Array(256);
+ for (var i = 0; i < chars.length; i++) {
+ lookup[chars.charCodeAt(i)] = i;
+ }
+
+ exports.encode = function(arraybuffer) {
+ var bytes = new Uint8Array(arraybuffer),
+ i, len = bytes.length, base64 = "";
+
+ for (i = 0; i < len; i+=3) {
+ base64 += chars[bytes[i] >> 2];
+ base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
+ base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
+ base64 += chars[bytes[i + 2] & 63];
+ }
+
+ if ((len % 3) === 2) {
+ base64 = base64.substring(0, base64.length - 1) + "=";
+ } else if (len % 3 === 1) {
+ base64 = base64.substring(0, base64.length - 2) + "==";
+ }
+
+ return base64;
+ };
+
+ exports.decode = function(base64) {
+ var bufferLength = base64.length * 0.75,
+ len = base64.length, i, p = 0,
+ encoded1, encoded2, encoded3, encoded4;
+
+ if (base64[base64.length - 1] === "=") {
+ bufferLength--;
+ if (base64[base64.length - 2] === "=") {
+ bufferLength--;
+ }
+ }
+
+ var arraybuffer = new ArrayBuffer(bufferLength),
+ bytes = new Uint8Array(arraybuffer);
+
+ for (i = 0; i < len; i+=4) {
+ encoded1 = lookup[base64.charCodeAt(i)];
+ encoded2 = lookup[base64.charCodeAt(i+1)];
+ encoded3 = lookup[base64.charCodeAt(i+2)];
+ encoded4 = lookup[base64.charCodeAt(i+3)];
+
+ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
+ bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
+ bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
+ }
+
+ return arraybuffer;
+ };
+})();
+
+},{}],13:[function(require,module,exports){
+'use strict'
+
+exports.byteLength = byteLength
+exports.toByteArray = toByteArray
+exports.fromByteArray = fromByteArray
+
+var lookup = []
+var revLookup = []
+var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
+
+var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
+for (var i = 0, len = code.length; i < len; ++i) {
+ lookup[i] = code[i]
+ revLookup[code.charCodeAt(i)] = i
+}
+
+// Support decoding URL-safe base64 strings, as Node.js does.
+// See: https://en.wikipedia.org/wiki/Base64#URL_applications
+revLookup['-'.charCodeAt(0)] = 62
+revLookup['_'.charCodeAt(0)] = 63
+
+function placeHoldersCount (b64) {
+ var len = b64.length
+ if (len % 4 > 0) {
+ throw new Error('Invalid string. Length must be a multiple of 4')
+ }
+
+ // the number of equal signs (place holders)
+ // if there are two placeholders, than the two characters before it
+ // represent one byte
+ // if there is only one, then the three characters before it represent 2 bytes
+ // this is just a cheap hack to not do indexOf twice
+ return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
+}
+
+function byteLength (b64) {
+ // base64 is 4/3 + up to two characters of the original data
+ return (b64.length * 3 / 4) - placeHoldersCount(b64)
+}
+
+function toByteArray (b64) {
+ var i, l, tmp, placeHolders, arr
+ var len = b64.length
+ placeHolders = placeHoldersCount(b64)
+
+ arr = new Arr((len * 3 / 4) - placeHolders)
+
+ // if there are placeholders, only get up to the last complete 4 chars
+ l = placeHolders > 0 ? len - 4 : len
+
+ var L = 0
+
+ for (i = 0; i < l; i += 4) {
+ tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
+ arr[L++] = (tmp >> 16) & 0xFF
+ arr[L++] = (tmp >> 8) & 0xFF
+ arr[L++] = tmp & 0xFF
+ }
+
+ if (placeHolders === 2) {
+ tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
+ arr[L++] = tmp & 0xFF
+ } else if (placeHolders === 1) {
+ tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
+ arr[L++] = (tmp >> 8) & 0xFF
+ arr[L++] = tmp & 0xFF
+ }
+
+ return arr
+}
+
+function tripletToBase64 (num) {
+ return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
+}
+
+function encodeChunk (uint8, start, end) {
+ var tmp
+ var output = []
+ for (var i = start; i < end; i += 3) {
+ tmp = ((uint8[i] << 16) & 0xFF0000) + ((uint8[i + 1] << 8) & 0xFF00) + (uint8[i + 2] & 0xFF)
+ output.push(tripletToBase64(tmp))
+ }
+ return output.join('')
+}
+
+function fromByteArray (uint8) {
+ var tmp
+ var len = uint8.length
+ var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
+ var output = ''
+ var parts = []
+ var maxChunkLength = 16383 // must be multiple of 3
+
+ // go through the array every three bytes, we'll deal with trailing stuff later
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
+ parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
+ }
+
+ // pad the end with zeros, but make sure to not forget the extra bytes
+ if (extraBytes === 1) {
+ tmp = uint8[len - 1]
+ output += lookup[tmp >> 2]
+ output += lookup[(tmp << 4) & 0x3F]
+ output += '=='
+ } else if (extraBytes === 2) {
+ tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
+ output += lookup[tmp >> 10]
+ output += lookup[(tmp >> 4) & 0x3F]
+ output += lookup[(tmp << 2) & 0x3F]
+ output += '='
+ }
+
+ parts.push(output)
+
+ return parts.join('')
+}
+
+},{}],14:[function(require,module,exports){
+(function (global){
+/**
+ * Create a blob builder even when vendor prefixes exist
+ */
+
+var BlobBuilder = global.BlobBuilder
+ || global.WebKitBlobBuilder
+ || global.MSBlobBuilder
+ || global.MozBlobBuilder;
+
+/**
+ * Check if Blob constructor is supported
+ */
+
+var blobSupported = (function() {
+ try {
+ var a = new Blob(['hi']);
+ return a.size === 2;
+ } catch(e) {
+ return false;
+ }
+})();
+
+/**
+ * Check if Blob constructor supports ArrayBufferViews
+ * Fails in Safari 6, so we need to map to ArrayBuffers there.
+ */
+
+var blobSupportsArrayBufferView = blobSupported && (function() {
+ try {
+ var b = new Blob([new Uint8Array([1,2])]);
+ return b.size === 2;
+ } catch(e) {
+ return false;
+ }
+})();
+
+/**
+ * Check if BlobBuilder is supported
+ */
+
+var blobBuilderSupported = BlobBuilder
+ && BlobBuilder.prototype.append
+ && BlobBuilder.prototype.getBlob;
+
+/**
+ * Helper function that maps ArrayBufferViews to ArrayBuffers
+ * Used by BlobBuilder constructor and old browsers that didn't
+ * support it in the Blob constructor.
+ */
+
+function mapArrayBufferViews(ary) {
+ for (var i = 0; i < ary.length; i++) {
+ var chunk = ary[i];
+ if (chunk.buffer instanceof ArrayBuffer) {
+ var buf = chunk.buffer;
+
+ // if this is a subarray, make a copy so we only
+ // include the subarray region from the underlying buffer
+ if (chunk.byteLength !== buf.byteLength) {
+ var copy = new Uint8Array(chunk.byteLength);
+ copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
+ buf = copy.buffer;
+ }
+
+ ary[i] = buf;
+ }
+ }
+}
+
+function BlobBuilderConstructor(ary, options) {
+ options = options || {};
+
+ var bb = new BlobBuilder();
+ mapArrayBufferViews(ary);
+
+ for (var i = 0; i < ary.length; i++) {
+ bb.append(ary[i]);
+ }
+
+ return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
+};
+
+function BlobConstructor(ary, options) {
+ mapArrayBufferViews(ary);
+ return new Blob(ary, options || {});
+};
+
+module.exports = (function() {
+ if (blobSupported) {
+ return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
+ } else if (blobBuilderSupported) {
+ return BlobBuilderConstructor;
+ } else {
+ return undefined;
+ }
+})();
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],15:[function(require,module,exports){
+
+},{}],16:[function(require,module,exports){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var objectCreate = Object.create || objectCreatePolyfill
+var objectKeys = Object.keys || objectKeysPolyfill
+var bind = Function.prototype.bind || functionBindPolyfill
+
+function EventEmitter() {
+ if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
+ this._events = objectCreate(null);
+ this._eventsCount = 0;
+ }
+
+ this._maxListeners = this._maxListeners || undefined;
+}
+module.exports = EventEmitter;
+
+// Backwards-compat with node 0.10.x
+EventEmitter.EventEmitter = EventEmitter;
+
+EventEmitter.prototype._events = undefined;
+EventEmitter.prototype._maxListeners = undefined;
+
+// By default EventEmitters will print a warning if more than 10 listeners are
+// added to it. This is a useful default which helps finding memory leaks.
+var defaultMaxListeners = 10;
+
+var hasDefineProperty;
+try {
+ var o = {};
+ if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
+ hasDefineProperty = o.x === 0;
+} catch (err) { hasDefineProperty = false }
+if (hasDefineProperty) {
+ Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
+ enumerable: true,
+ get: function() {
+ return defaultMaxListeners;
+ },
+ set: function(arg) {
+ // check whether the input is a positive number (whose value is zero or
+ // greater and not a NaN).
+ if (typeof arg !== 'number' || arg < 0 || arg !== arg)
+ throw new TypeError('"defaultMaxListeners" must be a positive number');
+ defaultMaxListeners = arg;
+ }
+ });
+} else {
+ EventEmitter.defaultMaxListeners = defaultMaxListeners;
+}
+
+// Obviously not all Emitters should be limited to 10. This function allows
+// that to be increased. Set to zero for unlimited.
+EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
+ if (typeof n !== 'number' || n < 0 || isNaN(n))
+ throw new TypeError('"n" argument must be a positive number');
+ this._maxListeners = n;
+ return this;
+};
+
+function $getMaxListeners(that) {
+ if (that._maxListeners === undefined)
+ return EventEmitter.defaultMaxListeners;
+ return that._maxListeners;
+}
+
+EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
+ return $getMaxListeners(this);
+};
+
+// These standalone emit* functions are used to optimize calling of event
+// handlers for fast cases because emit() itself often has a variable number of
+// arguments and can be deoptimized because of that. These functions always have
+// the same number of arguments and thus do not get deoptimized, so the code
+// inside them can execute faster.
+function emitNone(handler, isFn, self) {
+ if (isFn)
+ handler.call(self);
+ else {
+ var len = handler.length;
+ var listeners = arrayClone(handler, len);
+ for (var i = 0; i < len; ++i)
+ listeners[i].call(self);
+ }
+}
+function emitOne(handler, isFn, self, arg1) {
+ if (isFn)
+ handler.call(self, arg1);
+ else {
+ var len = handler.length;
+ var listeners = arrayClone(handler, len);
+ for (var i = 0; i < len; ++i)
+ listeners[i].call(self, arg1);
+ }
+}
+function emitTwo(handler, isFn, self, arg1, arg2) {
+ if (isFn)
+ handler.call(self, arg1, arg2);
+ else {
+ var len = handler.length;
+ var listeners = arrayClone(handler, len);
+ for (var i = 0; i < len; ++i)
+ listeners[i].call(self, arg1, arg2);
+ }
+}
+function emitThree(handler, isFn, self, arg1, arg2, arg3) {
+ if (isFn)
+ handler.call(self, arg1, arg2, arg3);
+ else {
+ var len = handler.length;
+ var listeners = arrayClone(handler, len);
+ for (var i = 0; i < len; ++i)
+ listeners[i].call(self, arg1, arg2, arg3);
+ }
+}
+
+function emitMany(handler, isFn, self, args) {
+ if (isFn)
+ handler.apply(self, args);
+ else {
+ var len = handler.length;
+ var listeners = arrayClone(handler, len);
+ for (var i = 0; i < len; ++i)
+ listeners[i].apply(self, args);
+ }
+}
+
+EventEmitter.prototype.emit = function emit(type) {
+ var er, handler, len, args, i, events;
+ var doError = (type === 'error');
+
+ events = this._events;
+ if (events)
+ doError = (doError && events.error == null);
+ else if (!doError)
+ return false;
+
+ // If there is no 'error' event listener then throw.
+ if (doError) {
+ if (arguments.length > 1)
+ er = arguments[1];
+ if (er instanceof Error) {
+ throw er; // Unhandled 'error' event
+ } else {
+ // At least give some kind of context to the user
+ var err = new Error('Unhandled "error" event. (' + er + ')');
+ err.context = er;
+ throw err;
+ }
+ return false;
+ }
+
+ handler = events[type];
+
+ if (!handler)
+ return false;
+
+ var isFn = typeof handler === 'function';
+ len = arguments.length;
+ switch (len) {
+ // fast cases
+ case 1:
+ emitNone(handler, isFn, this);
+ break;
+ case 2:
+ emitOne(handler, isFn, this, arguments[1]);
+ break;
+ case 3:
+ emitTwo(handler, isFn, this, arguments[1], arguments[2]);
+ break;
+ case 4:
+ emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
+ break;
+ // slower
+ default:
+ args = new Array(len - 1);
+ for (i = 1; i < len; i++)
+ args[i - 1] = arguments[i];
+ emitMany(handler, isFn, this, args);
+ }
+
+ return true;
+};
+
+function _addListener(target, type, listener, prepend) {
+ var m;
+ var events;
+ var existing;
+
+ if (typeof listener !== 'function')
+ throw new TypeError('"listener" argument must be a function');
+
+ events = target._events;
+ if (!events) {
+ events = target._events = objectCreate(null);
+ target._eventsCount = 0;
+ } else {
+ // To avoid recursion in the case that type === "newListener"! Before
+ // adding it to the listeners, first emit "newListener".
+ if (events.newListener) {
+ target.emit('newListener', type,
+ listener.listener ? listener.listener : listener);
+
+ // Re-assign `events` because a newListener handler could have caused the
+ // this._events to be assigned to a new object
+ events = target._events;
+ }
+ existing = events[type];
+ }
+
+ if (!existing) {
+ // Optimize the case of one listener. Don't need the extra array object.
+ existing = events[type] = listener;
+ ++target._eventsCount;
+ } else {
+ if (typeof existing === 'function') {
+ // Adding the second element, need to change to array.
+ existing = events[type] =
+ prepend ? [listener, existing] : [existing, listener];
+ } else {
+ // If we've already got an array, just append.
+ if (prepend) {
+ existing.unshift(listener);
+ } else {
+ existing.push(listener);
+ }
+ }
+
+ // Check for listener leak
+ if (!existing.warned) {
+ m = $getMaxListeners(target);
+ if (m && m > 0 && existing.length > m) {
+ existing.warned = true;
+ var w = new Error('Possible EventEmitter memory leak detected. ' +
+ existing.length + ' "' + String(type) + '" listeners ' +
+ 'added. Use emitter.setMaxListeners() to ' +
+ 'increase limit.');
+ w.name = 'MaxListenersExceededWarning';
+ w.emitter = target;
+ w.type = type;
+ w.count = existing.length;
+ if (typeof console === 'object' && console.warn) {
+ console.warn('%s: %s', w.name, w.message);
+ }
+ }
+ }
+ }
+
+ return target;
+}
+
+EventEmitter.prototype.addListener = function addListener(type, listener) {
+ return _addListener(this, type, listener, false);
+};
+
+EventEmitter.prototype.on = EventEmitter.prototype.addListener;
+
+EventEmitter.prototype.prependListener =
+ function prependListener(type, listener) {
+ return _addListener(this, type, listener, true);
+ };
+
+function onceWrapper() {
+ if (!this.fired) {
+ this.target.removeListener(this.type, this.wrapFn);
+ this.fired = true;
+ switch (arguments.length) {
+ case 0:
+ return this.listener.call(this.target);
+ case 1:
+ return this.listener.call(this.target, arguments[0]);
+ case 2:
+ return this.listener.call(this.target, arguments[0], arguments[1]);
+ case 3:
+ return this.listener.call(this.target, arguments[0], arguments[1],
+ arguments[2]);
+ default:
+ var args = new Array(arguments.length);
+ for (var i = 0; i < args.length; ++i)
+ args[i] = arguments[i];
+ this.listener.apply(this.target, args);
+ }
+ }
+}
+
+function _onceWrap(target, type, listener) {
+ var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
+ var wrapped = bind.call(onceWrapper, state);
+ wrapped.listener = listener;
+ state.wrapFn = wrapped;
+ return wrapped;
+}
+
+EventEmitter.prototype.once = function once(type, listener) {
+ if (typeof listener !== 'function')
+ throw new TypeError('"listener" argument must be a function');
+ this.on(type, _onceWrap(this, type, listener));
+ return this;
+};
+
+EventEmitter.prototype.prependOnceListener =
+ function prependOnceListener(type, listener) {
+ if (typeof listener !== 'function')
+ throw new TypeError('"listener" argument must be a function');
+ this.prependListener(type, _onceWrap(this, type, listener));
+ return this;
+ };
+
+// Emits a 'removeListener' event if and only if the listener was removed.
+EventEmitter.prototype.removeListener =
+ function removeListener(type, listener) {
+ var list, events, position, i, originalListener;
+
+ if (typeof listener !== 'function')
+ throw new TypeError('"listener" argument must be a function');
+
+ events = this._events;
+ if (!events)
+ return this;
+
+ list = events[type];
+ if (!list)
+ return this;
+
+ if (list === listener || list.listener === listener) {
+ if (--this._eventsCount === 0)
+ this._events = objectCreate(null);
+ else {
+ delete events[type];
+ if (events.removeListener)
+ this.emit('removeListener', type, list.listener || listener);
+ }
+ } else if (typeof list !== 'function') {
+ position = -1;
+
+ for (i = list.length - 1; i >= 0; i--) {
+ if (list[i] === listener || list[i].listener === listener) {
+ originalListener = list[i].listener;
+ position = i;
+ break;
+ }
+ }
+
+ if (position < 0)
+ return this;
+
+ if (position === 0)
+ list.shift();
+ else
+ spliceOne(list, position);
+
+ if (list.length === 1)
+ events[type] = list[0];
+
+ if (events.removeListener)
+ this.emit('removeListener', type, originalListener || listener);
+ }
+
+ return this;
+ };
+
+EventEmitter.prototype.removeAllListeners =
+ function removeAllListeners(type) {
+ var listeners, events, i;
+
+ events = this._events;
+ if (!events)
+ return this;
+
+ // not listening for removeListener, no need to emit
+ if (!events.removeListener) {
+ if (arguments.length === 0) {
+ this._events = objectCreate(null);
+ this._eventsCount = 0;
+ } else if (events[type]) {
+ if (--this._eventsCount === 0)
+ this._events = objectCreate(null);
+ else
+ delete events[type];
+ }
+ return this;
+ }
+
+ // emit removeListener for all listeners on all events
+ if (arguments.length === 0) {
+ var keys = objectKeys(events);
+ var key;
+ for (i = 0; i < keys.length; ++i) {
+ key = keys[i];
+ if (key === 'removeListener') continue;
+ this.removeAllListeners(key);
+ }
+ this.removeAllListeners('removeListener');
+ this._events = objectCreate(null);
+ this._eventsCount = 0;
+ return this;
+ }
+
+ listeners = events[type];
+
+ if (typeof listeners === 'function') {
+ this.removeListener(type, listeners);
+ } else if (listeners) {
+ // LIFO order
+ for (i = listeners.length - 1; i >= 0; i--) {
+ this.removeListener(type, listeners[i]);
+ }
+ }
+
+ return this;
+ };
+
+function _listeners(target, type, unwrap) {
+ var events = target._events;
+
+ if (!events)
+ return [];
+
+ var evlistener = events[type];
+ if (!evlistener)
+ return [];
+
+ if (typeof evlistener === 'function')
+ return unwrap ? [evlistener.listener || evlistener] : [evlistener];
+
+ return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
+}
+
+EventEmitter.prototype.listeners = function listeners(type) {
+ return _listeners(this, type, true);
+};
+
+EventEmitter.prototype.rawListeners = function rawListeners(type) {
+ return _listeners(this, type, false);
+};
+
+EventEmitter.listenerCount = function(emitter, type) {
+ if (typeof emitter.listenerCount === 'function') {
+ return emitter.listenerCount(type);
+ } else {
+ return listenerCount.call(emitter, type);
+ }
+};
+
+EventEmitter.prototype.listenerCount = listenerCount;
+function listenerCount(type) {
+ var events = this._events;
+
+ if (events) {
+ var evlistener = events[type];
+
+ if (typeof evlistener === 'function') {
+ return 1;
+ } else if (evlistener) {
+ return evlistener.length;
+ }
+ }
+
+ return 0;
+}
+
+EventEmitter.prototype.eventNames = function eventNames() {
+ return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
+};
+
+// About 1.5x faster than the two-arg version of Array#splice().
+function spliceOne(list, index) {
+ for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
+ list[i] = list[k];
+ list.pop();
+}
+
+function arrayClone(arr, n) {
+ var copy = new Array(n);
+ for (var i = 0; i < n; ++i)
+ copy[i] = arr[i];
+ return copy;
+}
+
+function unwrapListeners(arr) {
+ var ret = new Array(arr.length);
+ for (var i = 0; i < ret.length; ++i) {
+ ret[i] = arr[i].listener || arr[i];
+ }
+ return ret;
+}
+
+function objectCreatePolyfill(proto) {
+ var F = function() {};
+ F.prototype = proto;
+ return new F;
+}
+function objectKeysPolyfill(obj) {
+ var keys = [];
+ for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
+ keys.push(k);
+ }
+ return k;
+}
+function functionBindPolyfill(context) {
+ var fn = this;
+ return function () {
+ return fn.apply(context, arguments);
+ };
+}
+
+},{}],17:[function(require,module,exports){
+/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
+/* eslint-disable no-proto */
+
+'use strict'
+
+var base64 = require('base64-js')
+var ieee754 = require('ieee754')
+
+exports.Buffer = Buffer
+exports.SlowBuffer = SlowBuffer
+exports.INSPECT_MAX_BYTES = 50
+
+var K_MAX_LENGTH = 0x7fffffff
+exports.kMaxLength = K_MAX_LENGTH
+
+/**
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
+ * === true Use Uint8Array implementation (fastest)
+ * === false Print warning and recommend using `buffer` v4.x which has an Object
+ * implementation (most compatible, even IE6)
+ *
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
+ * Opera 11.6+, iOS 4.2+.
+ *
+ * We report that the browser does not support typed arrays if the are not subclassable
+ * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
+ * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
+ * for __proto__ and has a buggy typed array implementation.
+ */
+Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
+
+if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
+ typeof console.error === 'function') {
+ console.error(
+ 'This browser lacks typed array (Uint8Array) support which is required by ' +
+ '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
+ )
+}
+
+function typedArraySupport () {
+ // Can typed array instances can be augmented?
+ try {
+ var arr = new Uint8Array(1)
+ arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
+ return arr.foo() === 42
+ } catch (e) {
+ return false
+ }
+}
+
+Object.defineProperty(Buffer.prototype, 'parent', {
+ get: function () {
+ if (!(this instanceof Buffer)) {
+ return undefined
+ }
+ return this.buffer
+ }
+})
+
+Object.defineProperty(Buffer.prototype, 'offset', {
+ get: function () {
+ if (!(this instanceof Buffer)) {
+ return undefined
+ }
+ return this.byteOffset
+ }
+})
+
+function createBuffer (length) {
+ if (length > K_MAX_LENGTH) {
+ throw new RangeError('Invalid typed array length')
+ }
+ // Return an augmented `Uint8Array` instance
+ var buf = new Uint8Array(length)
+ buf.__proto__ = Buffer.prototype
+ return buf
+}
+
+/**
+ * The Buffer constructor returns instances of `Uint8Array` that have their
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
+ * returns a single octet.
+ *
+ * The `Uint8Array` prototype remains unmodified.
+ */
+
+function Buffer (arg, encodingOrOffset, length) {
+ // Common case.
+ if (typeof arg === 'number') {
+ if (typeof encodingOrOffset === 'string') {
+ throw new Error(
+ 'If encoding is specified then the first argument must be a string'
+ )
+ }
+ return allocUnsafe(arg)
+ }
+ return from(arg, encodingOrOffset, length)
+}
+
+// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
+if (typeof Symbol !== 'undefined' && Symbol.species &&
+ Buffer[Symbol.species] === Buffer) {
+ Object.defineProperty(Buffer, Symbol.species, {
+ value: null,
+ configurable: true,
+ enumerable: false,
+ writable: false
+ })
+}
+
+Buffer.poolSize = 8192 // not used by this implementation
+
+function from (value, encodingOrOffset, length) {
+ if (typeof value === 'number') {
+ throw new TypeError('"value" argument must not be a number')
+ }
+
+ if (isArrayBuffer(value) || (value && isArrayBuffer(value.buffer))) {
+ return fromArrayBuffer(value, encodingOrOffset, length)
+ }
+
+ if (typeof value === 'string') {
+ return fromString(value, encodingOrOffset)
+ }
+
+ return fromObject(value)
+}
+
+/**
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
+ * if value is a number.
+ * Buffer.from(str[, encoding])
+ * Buffer.from(array)
+ * Buffer.from(buffer)
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
+ **/
+Buffer.from = function (value, encodingOrOffset, length) {
+ return from(value, encodingOrOffset, length)
+}
+
+// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
+// https://github.com/feross/buffer/pull/148
+Buffer.prototype.__proto__ = Uint8Array.prototype
+Buffer.__proto__ = Uint8Array
+
+function assertSize (size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('"size" argument must be of type number')
+ } else if (size < 0) {
+ throw new RangeError('"size" argument must not be negative')
+ }
+}
+
+function alloc (size, fill, encoding) {
+ assertSize(size)
+ if (size <= 0) {
+ return createBuffer(size)
+ }
+ if (fill !== undefined) {
+ // Only pay attention to encoding if it's a string. This
+ // prevents accidentally sending in a number that would
+ // be interpretted as a start offset.
+ return typeof encoding === 'string'
+ ? createBuffer(size).fill(fill, encoding)
+ : createBuffer(size).fill(fill)
+ }
+ return createBuffer(size)
+}
+
+/**
+ * Creates a new filled Buffer instance.
+ * alloc(size[, fill[, encoding]])
+ **/
+Buffer.alloc = function (size, fill, encoding) {
+ return alloc(size, fill, encoding)
+}
+
+function allocUnsafe (size) {
+ assertSize(size)
+ return createBuffer(size < 0 ? 0 : checked(size) | 0)
+}
+
+/**
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
+ * */
+Buffer.allocUnsafe = function (size) {
+ return allocUnsafe(size)
+}
+/**
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
+ */
+Buffer.allocUnsafeSlow = function (size) {
+ return allocUnsafe(size)
+}
+
+function fromString (string, encoding) {
+ if (typeof encoding !== 'string' || encoding === '') {
+ encoding = 'utf8'
+ }
+
+ if (!Buffer.isEncoding(encoding)) {
+ throw new TypeError('Unknown encoding: ' + encoding)
+ }
+
+ var length = byteLength(string, encoding) | 0
+ var buf = createBuffer(length)
+
+ var actual = buf.write(string, encoding)
+
+ if (actual !== length) {
+ // Writing a hex string, for example, that contains invalid characters will
+ // cause everything after the first invalid character to be ignored. (e.g.
+ // 'abxxcd' will be treated as 'ab')
+ buf = buf.slice(0, actual)
+ }
+
+ return buf
+}
+
+function fromArrayLike (array) {
+ var length = array.length < 0 ? 0 : checked(array.length) | 0
+ var buf = createBuffer(length)
+ for (var i = 0; i < length; i += 1) {
+ buf[i] = array[i] & 255
+ }
+ return buf
+}
+
+function fromArrayBuffer (array, byteOffset, length) {
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
+ throw new RangeError('"offset" is outside of buffer bounds')
+ }
+
+ if (array.byteLength < byteOffset + (length || 0)) {
+ throw new RangeError('"length" is outside of buffer bounds')
+ }
+
+ var buf
+ if (byteOffset === undefined && length === undefined) {
+ buf = new Uint8Array(array)
+ } else if (length === undefined) {
+ buf = new Uint8Array(array, byteOffset)
+ } else {
+ buf = new Uint8Array(array, byteOffset, length)
+ }
+
+ // Return an augmented `Uint8Array` instance
+ buf.__proto__ = Buffer.prototype
+ return buf
+}
+
+function fromObject (obj) {
+ if (Buffer.isBuffer(obj)) {
+ var len = checked(obj.length) | 0
+ var buf = createBuffer(len)
+
+ if (buf.length === 0) {
+ return buf
+ }
+
+ obj.copy(buf, 0, 0, len)
+ return buf
+ }
+
+ if (obj) {
+ if (ArrayBuffer.isView(obj) || 'length' in obj) {
+ if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
+ return createBuffer(0)
+ }
+ return fromArrayLike(obj)
+ }
+
+ if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
+ return fromArrayLike(obj.data)
+ }
+ }
+
+ throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.')
+}
+
+function checked (length) {
+ // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
+ // length is NaN (which is otherwise coerced to zero.)
+ if (length >= K_MAX_LENGTH) {
+ throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
+ 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
+ }
+ return length | 0
+}
+
+function SlowBuffer (length) {
+ if (+length != length) { // eslint-disable-line eqeqeq
+ length = 0
+ }
+ return Buffer.alloc(+length)
+}
+
+Buffer.isBuffer = function isBuffer (b) {
+ return b != null && b._isBuffer === true
+}
+
+Buffer.compare = function compare (a, b) {
+ if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
+ throw new TypeError('Arguments must be Buffers')
+ }
+
+ if (a === b) return 0
+
+ var x = a.length
+ var y = b.length
+
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
+ if (a[i] !== b[i]) {
+ x = a[i]
+ y = b[i]
+ break
+ }
+ }
+
+ if (x < y) return -1
+ if (y < x) return 1
+ return 0
+}
+
+Buffer.isEncoding = function isEncoding (encoding) {
+ switch (String(encoding).toLowerCase()) {
+ case 'hex':
+ case 'utf8':
+ case 'utf-8':
+ case 'ascii':
+ case 'latin1':
+ case 'binary':
+ case 'base64':
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return true
+ default:
+ return false
+ }
+}
+
+Buffer.concat = function concat (list, length) {
+ if (!Array.isArray(list)) {
+ throw new TypeError('"list" argument must be an Array of Buffers')
+ }
+
+ if (list.length === 0) {
+ return Buffer.alloc(0)
+ }
+
+ var i
+ if (length === undefined) {
+ length = 0
+ for (i = 0; i < list.length; ++i) {
+ length += list[i].length
+ }
+ }
+
+ var buffer = Buffer.allocUnsafe(length)
+ var pos = 0
+ for (i = 0; i < list.length; ++i) {
+ var buf = list[i]
+ if (ArrayBuffer.isView(buf)) {
+ buf = Buffer.from(buf)
+ }
+ if (!Buffer.isBuffer(buf)) {
+ throw new TypeError('"list" argument must be an Array of Buffers')
+ }
+ buf.copy(buffer, pos)
+ pos += buf.length
+ }
+ return buffer
+}
+
+function byteLength (string, encoding) {
+ if (Buffer.isBuffer(string)) {
+ return string.length
+ }
+ if (ArrayBuffer.isView(string) || isArrayBuffer(string)) {
+ return string.byteLength
+ }
+ if (typeof string !== 'string') {
+ string = '' + string
+ }
+
+ var len = string.length
+ if (len === 0) return 0
+
+ // Use a for loop to avoid recursion
+ var loweredCase = false
+ for (;;) {
+ switch (encoding) {
+ case 'ascii':
+ case 'latin1':
+ case 'binary':
+ return len
+ case 'utf8':
+ case 'utf-8':
+ case undefined:
+ return utf8ToBytes(string).length
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return len * 2
+ case 'hex':
+ return len >>> 1
+ case 'base64':
+ return base64ToBytes(string).length
+ default:
+ if (loweredCase) return utf8ToBytes(string).length // assume utf8
+ encoding = ('' + encoding).toLowerCase()
+ loweredCase = true
+ }
+ }
+}
+Buffer.byteLength = byteLength
+
+function slowToString (encoding, start, end) {
+ var loweredCase = false
+
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
+ // property of a typed array.
+
+ // This behaves neither like String nor Uint8Array in that we set start/end
+ // to their upper/lower bounds if the value passed is out of range.
+ // undefined is handled specially as per ECMA-262 6th Edition,
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
+ if (start === undefined || start < 0) {
+ start = 0
+ }
+ // Return early if start > this.length. Done here to prevent potential uint32
+ // coercion fail below.
+ if (start > this.length) {
+ return ''
+ }
+
+ if (end === undefined || end > this.length) {
+ end = this.length
+ }
+
+ if (end <= 0) {
+ return ''
+ }
+
+ // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
+ end >>>= 0
+ start >>>= 0
+
+ if (end <= start) {
+ return ''
+ }
+
+ if (!encoding) encoding = 'utf8'
+
+ while (true) {
+ switch (encoding) {
+ case 'hex':
+ return hexSlice(this, start, end)
+
+ case 'utf8':
+ case 'utf-8':
+ return utf8Slice(this, start, end)
+
+ case 'ascii':
+ return asciiSlice(this, start, end)
+
+ case 'latin1':
+ case 'binary':
+ return latin1Slice(this, start, end)
+
+ case 'base64':
+ return base64Slice(this, start, end)
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return utf16leSlice(this, start, end)
+
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
+ encoding = (encoding + '').toLowerCase()
+ loweredCase = true
+ }
+ }
+}
+
+// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
+// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
+// reliably in a browserify context because there could be multiple different
+// copies of the 'buffer' package in use. This method works even for Buffer
+// instances that were created from another copy of the `buffer` package.
+// See: https://github.com/feross/buffer/issues/154
+Buffer.prototype._isBuffer = true
+
+function swap (b, n, m) {
+ var i = b[n]
+ b[n] = b[m]
+ b[m] = i
+}
+
+Buffer.prototype.swap16 = function swap16 () {
+ var len = this.length
+ if (len % 2 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 16-bits')
+ }
+ for (var i = 0; i < len; i += 2) {
+ swap(this, i, i + 1)
+ }
+ return this
+}
+
+Buffer.prototype.swap32 = function swap32 () {
+ var len = this.length
+ if (len % 4 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 32-bits')
+ }
+ for (var i = 0; i < len; i += 4) {
+ swap(this, i, i + 3)
+ swap(this, i + 1, i + 2)
+ }
+ return this
+}
+
+Buffer.prototype.swap64 = function swap64 () {
+ var len = this.length
+ if (len % 8 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 64-bits')
+ }
+ for (var i = 0; i < len; i += 8) {
+ swap(this, i, i + 7)
+ swap(this, i + 1, i + 6)
+ swap(this, i + 2, i + 5)
+ swap(this, i + 3, i + 4)
+ }
+ return this
+}
+
+Buffer.prototype.toString = function toString () {
+ var length = this.length
+ if (length === 0) return ''
+ if (arguments.length === 0) return utf8Slice(this, 0, length)
+ return slowToString.apply(this, arguments)
+}
+
+Buffer.prototype.toLocaleString = Buffer.prototype.toString
+
+Buffer.prototype.equals = function equals (b) {
+ if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
+ if (this === b) return true
+ return Buffer.compare(this, b) === 0
+}
+
+Buffer.prototype.inspect = function inspect () {
+ var str = ''
+ var max = exports.INSPECT_MAX_BYTES
+ if (this.length > 0) {
+ str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
+ if (this.length > max) str += ' ... '
+ }
+ return ''
+}
+
+Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
+ if (!Buffer.isBuffer(target)) {
+ throw new TypeError('Argument must be a Buffer')
+ }
+
+ if (start === undefined) {
+ start = 0
+ }
+ if (end === undefined) {
+ end = target ? target.length : 0
+ }
+ if (thisStart === undefined) {
+ thisStart = 0
+ }
+ if (thisEnd === undefined) {
+ thisEnd = this.length
+ }
+
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
+ throw new RangeError('out of range index')
+ }
+
+ if (thisStart >= thisEnd && start >= end) {
+ return 0
+ }
+ if (thisStart >= thisEnd) {
+ return -1
+ }
+ if (start >= end) {
+ return 1
+ }
+
+ start >>>= 0
+ end >>>= 0
+ thisStart >>>= 0
+ thisEnd >>>= 0
+
+ if (this === target) return 0
+
+ var x = thisEnd - thisStart
+ var y = end - start
+ var len = Math.min(x, y)
+
+ var thisCopy = this.slice(thisStart, thisEnd)
+ var targetCopy = target.slice(start, end)
+
+ for (var i = 0; i < len; ++i) {
+ if (thisCopy[i] !== targetCopy[i]) {
+ x = thisCopy[i]
+ y = targetCopy[i]
+ break
+ }
+ }
+
+ if (x < y) return -1
+ if (y < x) return 1
+ return 0
+}
+
+// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
+// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
+//
+// Arguments:
+// - buffer - a Buffer to search
+// - val - a string, Buffer, or number
+// - byteOffset - an index into `buffer`; will be clamped to an int32
+// - encoding - an optional encoding, relevant is val is a string
+// - dir - true for indexOf, false for lastIndexOf
+function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
+ // Empty buffer means no match
+ if (buffer.length === 0) return -1
+
+ // Normalize byteOffset
+ if (typeof byteOffset === 'string') {
+ encoding = byteOffset
+ byteOffset = 0
+ } else if (byteOffset > 0x7fffffff) {
+ byteOffset = 0x7fffffff
+ } else if (byteOffset < -0x80000000) {
+ byteOffset = -0x80000000
+ }
+ byteOffset = +byteOffset // Coerce to Number.
+ if (numberIsNaN(byteOffset)) {
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
+ byteOffset = dir ? 0 : (buffer.length - 1)
+ }
+
+ // Normalize byteOffset: negative offsets start from the end of the buffer
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset
+ if (byteOffset >= buffer.length) {
+ if (dir) return -1
+ else byteOffset = buffer.length - 1
+ } else if (byteOffset < 0) {
+ if (dir) byteOffset = 0
+ else return -1
+ }
+
+ // Normalize val
+ if (typeof val === 'string') {
+ val = Buffer.from(val, encoding)
+ }
+
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
+ if (Buffer.isBuffer(val)) {
+ // Special case: looking for empty string/buffer always fails
+ if (val.length === 0) {
+ return -1
+ }
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
+ } else if (typeof val === 'number') {
+ val = val & 0xFF // Search for a byte value [0-255]
+ if (typeof Uint8Array.prototype.indexOf === 'function') {
+ if (dir) {
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
+ } else {
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
+ }
+ }
+ return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
+ }
+
+ throw new TypeError('val must be string, number or Buffer')
+}
+
+function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
+ var indexSize = 1
+ var arrLength = arr.length
+ var valLength = val.length
+
+ if (encoding !== undefined) {
+ encoding = String(encoding).toLowerCase()
+ if (encoding === 'ucs2' || encoding === 'ucs-2' ||
+ encoding === 'utf16le' || encoding === 'utf-16le') {
+ if (arr.length < 2 || val.length < 2) {
+ return -1
+ }
+ indexSize = 2
+ arrLength /= 2
+ valLength /= 2
+ byteOffset /= 2
+ }
+ }
+
+ function read (buf, i) {
+ if (indexSize === 1) {
+ return buf[i]
+ } else {
+ return buf.readUInt16BE(i * indexSize)
+ }
+ }
+
+ var i
+ if (dir) {
+ var foundIndex = -1
+ for (i = byteOffset; i < arrLength; i++) {
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
+ if (foundIndex === -1) foundIndex = i
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
+ } else {
+ if (foundIndex !== -1) i -= i - foundIndex
+ foundIndex = -1
+ }
+ }
+ } else {
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
+ for (i = byteOffset; i >= 0; i--) {
+ var found = true
+ for (var j = 0; j < valLength; j++) {
+ if (read(arr, i + j) !== read(val, j)) {
+ found = false
+ break
+ }
+ }
+ if (found) return i
+ }
+ }
+
+ return -1
+}
+
+Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
+ return this.indexOf(val, byteOffset, encoding) !== -1
+}
+
+Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
+}
+
+Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
+}
+
+function hexWrite (buf, string, offset, length) {
+ offset = Number(offset) || 0
+ var remaining = buf.length - offset
+ if (!length) {
+ length = remaining
+ } else {
+ length = Number(length)
+ if (length > remaining) {
+ length = remaining
+ }
+ }
+
+ var strLen = string.length
+
+ if (length > strLen / 2) {
+ length = strLen / 2
+ }
+ for (var i = 0; i < length; ++i) {
+ var parsed = parseInt(string.substr(i * 2, 2), 16)
+ if (numberIsNaN(parsed)) return i
+ buf[offset + i] = parsed
+ }
+ return i
+}
+
+function utf8Write (buf, string, offset, length) {
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
+}
+
+function asciiWrite (buf, string, offset, length) {
+ return blitBuffer(asciiToBytes(string), buf, offset, length)
+}
+
+function latin1Write (buf, string, offset, length) {
+ return asciiWrite(buf, string, offset, length)
+}
+
+function base64Write (buf, string, offset, length) {
+ return blitBuffer(base64ToBytes(string), buf, offset, length)
+}
+
+function ucs2Write (buf, string, offset, length) {
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
+}
+
+Buffer.prototype.write = function write (string, offset, length, encoding) {
+ // Buffer#write(string)
+ if (offset === undefined) {
+ encoding = 'utf8'
+ length = this.length
+ offset = 0
+ // Buffer#write(string, encoding)
+ } else if (length === undefined && typeof offset === 'string') {
+ encoding = offset
+ length = this.length
+ offset = 0
+ // Buffer#write(string, offset[, length][, encoding])
+ } else if (isFinite(offset)) {
+ offset = offset >>> 0
+ if (isFinite(length)) {
+ length = length >>> 0
+ if (encoding === undefined) encoding = 'utf8'
+ } else {
+ encoding = length
+ length = undefined
+ }
+ } else {
+ throw new Error(
+ 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
+ )
+ }
+
+ var remaining = this.length - offset
+ if (length === undefined || length > remaining) length = remaining
+
+ if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
+ throw new RangeError('Attempt to write outside buffer bounds')
+ }
+
+ if (!encoding) encoding = 'utf8'
+
+ var loweredCase = false
+ for (;;) {
+ switch (encoding) {
+ case 'hex':
+ return hexWrite(this, string, offset, length)
+
+ case 'utf8':
+ case 'utf-8':
+ return utf8Write(this, string, offset, length)
+
+ case 'ascii':
+ return asciiWrite(this, string, offset, length)
+
+ case 'latin1':
+ case 'binary':
+ return latin1Write(this, string, offset, length)
+
+ case 'base64':
+ // Warning: maxLength not taken into account in base64Write
+ return base64Write(this, string, offset, length)
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return ucs2Write(this, string, offset, length)
+
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
+ encoding = ('' + encoding).toLowerCase()
+ loweredCase = true
+ }
+ }
+}
+
+Buffer.prototype.toJSON = function toJSON () {
+ return {
+ type: 'Buffer',
+ data: Array.prototype.slice.call(this._arr || this, 0)
+ }
+}
+
+function base64Slice (buf, start, end) {
+ if (start === 0 && end === buf.length) {
+ return base64.fromByteArray(buf)
+ } else {
+ return base64.fromByteArray(buf.slice(start, end))
+ }
+}
+
+function utf8Slice (buf, start, end) {
+ end = Math.min(buf.length, end)
+ var res = []
+
+ var i = start
+ while (i < end) {
+ var firstByte = buf[i]
+ var codePoint = null
+ var bytesPerSequence = (firstByte > 0xEF) ? 4
+ : (firstByte > 0xDF) ? 3
+ : (firstByte > 0xBF) ? 2
+ : 1
+
+ if (i + bytesPerSequence <= end) {
+ var secondByte, thirdByte, fourthByte, tempCodePoint
+
+ switch (bytesPerSequence) {
+ case 1:
+ if (firstByte < 0x80) {
+ codePoint = firstByte
+ }
+ break
+ case 2:
+ secondByte = buf[i + 1]
+ if ((secondByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
+ if (tempCodePoint > 0x7F) {
+ codePoint = tempCodePoint
+ }
+ }
+ break
+ case 3:
+ secondByte = buf[i + 1]
+ thirdByte = buf[i + 2]
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
+ if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
+ codePoint = tempCodePoint
+ }
+ }
+ break
+ case 4:
+ secondByte = buf[i + 1]
+ thirdByte = buf[i + 2]
+ fourthByte = buf[i + 3]
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
+ if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
+ codePoint = tempCodePoint
+ }
+ }
+ }
+ }
+
+ if (codePoint === null) {
+ // we did not generate a valid codePoint so insert a
+ // replacement char (U+FFFD) and advance only 1 byte
+ codePoint = 0xFFFD
+ bytesPerSequence = 1
+ } else if (codePoint > 0xFFFF) {
+ // encode to utf16 (surrogate pair dance)
+ codePoint -= 0x10000
+ res.push(codePoint >>> 10 & 0x3FF | 0xD800)
+ codePoint = 0xDC00 | codePoint & 0x3FF
+ }
+
+ res.push(codePoint)
+ i += bytesPerSequence
+ }
+
+ return decodeCodePointsArray(res)
+}
+
+// Based on http://stackoverflow.com/a/22747272/680742, the browser with
+// the lowest limit is Chrome, with 0x10000 args.
+// We go 1 magnitude less, for safety
+var MAX_ARGUMENTS_LENGTH = 0x1000
+
+function decodeCodePointsArray (codePoints) {
+ var len = codePoints.length
+ if (len <= MAX_ARGUMENTS_LENGTH) {
+ return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
+ }
+
+ // Decode in chunks to avoid "call stack size exceeded".
+ var res = ''
+ var i = 0
+ while (i < len) {
+ res += String.fromCharCode.apply(
+ String,
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
+ )
+ }
+ return res
+}
+
+function asciiSlice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
+
+ for (var i = start; i < end; ++i) {
+ ret += String.fromCharCode(buf[i] & 0x7F)
+ }
+ return ret
+}
+
+function latin1Slice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
+
+ for (var i = start; i < end; ++i) {
+ ret += String.fromCharCode(buf[i])
+ }
+ return ret
+}
+
+function hexSlice (buf, start, end) {
+ var len = buf.length
+
+ if (!start || start < 0) start = 0
+ if (!end || end < 0 || end > len) end = len
+
+ var out = ''
+ for (var i = start; i < end; ++i) {
+ out += toHex(buf[i])
+ }
+ return out
+}
+
+function utf16leSlice (buf, start, end) {
+ var bytes = buf.slice(start, end)
+ var res = ''
+ for (var i = 0; i < bytes.length; i += 2) {
+ res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
+ }
+ return res
+}
+
+Buffer.prototype.slice = function slice (start, end) {
+ var len = this.length
+ start = ~~start
+ end = end === undefined ? len : ~~end
+
+ if (start < 0) {
+ start += len
+ if (start < 0) start = 0
+ } else if (start > len) {
+ start = len
+ }
+
+ if (end < 0) {
+ end += len
+ if (end < 0) end = 0
+ } else if (end > len) {
+ end = len
+ }
+
+ if (end < start) end = start
+
+ var newBuf = this.subarray(start, end)
+ // Return an augmented `Uint8Array` instance
+ newBuf.__proto__ = Buffer.prototype
+ return newBuf
+}
+
+/*
+ * Need to make sure that buffer isn't trying to write out of bounds.
+ */
+function checkOffset (offset, ext, length) {
+ if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
+}
+
+Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
+ }
+
+ return val
+}
+
+Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) {
+ checkOffset(offset, byteLength, this.length)
+ }
+
+ var val = this[offset + --byteLength]
+ var mul = 1
+ while (byteLength > 0 && (mul *= 0x100)) {
+ val += this[offset + --byteLength] * mul
+ }
+
+ return val
+}
+
+Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ return this[offset]
+}
+
+Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return this[offset] | (this[offset + 1] << 8)
+}
+
+Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return (this[offset] << 8) | this[offset + 1]
+}
+
+Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return ((this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16)) +
+ (this[offset + 3] * 0x1000000)
+}
+
+Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return (this[offset] * 0x1000000) +
+ ((this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ this[offset + 3])
+}
+
+Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
+ }
+ mul *= 0x80
+
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+ return val
+}
+
+Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var i = byteLength
+ var mul = 1
+ var val = this[offset + --i]
+ while (i > 0 && (mul *= 0x100)) {
+ val += this[offset + --i] * mul
+ }
+ mul *= 0x80
+
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+ return val
+}
+
+Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ if (!(this[offset] & 0x80)) return (this[offset])
+ return ((0xff - this[offset] + 1) * -1)
+}
+
+Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ var val = this[offset] | (this[offset + 1] << 8)
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
+}
+
+Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ var val = this[offset + 1] | (this[offset] << 8)
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
+}
+
+Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return (this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16) |
+ (this[offset + 3] << 24)
+}
+
+Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return (this[offset] << 24) |
+ (this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ (this[offset + 3])
+}
+
+Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
+ return ieee754.read(this, offset, true, 23, 4)
+}
+
+Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
+ return ieee754.read(this, offset, false, 23, 4)
+}
+
+Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 8, this.length)
+ return ieee754.read(this, offset, true, 52, 8)
+}
+
+Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 8, this.length)
+ return ieee754.read(this, offset, false, 52, 8)
+}
+
+function checkInt (buf, value, offset, ext, max, min) {
+ if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
+}
+
+Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
+ }
+
+ var mul = 1
+ var i = 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
+ }
+
+ var i = byteLength - 1
+ var mul = 1
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
+ this[offset] = (value & 0xff)
+ return offset + 1
+}
+
+Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ return offset + 2
+}
+
+Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
+ this[offset] = (value >>> 8)
+ this[offset + 1] = (value & 0xff)
+ return offset + 2
+}
+
+Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+ this[offset + 3] = (value >>> 24)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 1] = (value >>> 8)
+ this[offset] = (value & 0xff)
+ return offset + 4
+}
+
+Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = (value & 0xff)
+ return offset + 4
+}
+
+Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) {
+ var limit = Math.pow(2, (8 * byteLength) - 1)
+
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
+ }
+
+ var i = 0
+ var mul = 1
+ var sub = 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
+ sub = 1
+ }
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) {
+ var limit = Math.pow(2, (8 * byteLength) - 1)
+
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
+ }
+
+ var i = byteLength - 1
+ var mul = 1
+ var sub = 0
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
+ sub = 1
+ }
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
+ if (value < 0) value = 0xff + value + 1
+ this[offset] = (value & 0xff)
+ return offset + 1
+}
+
+Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ return offset + 2
+}
+
+Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ this[offset] = (value >>> 8)
+ this[offset + 1] = (value & 0xff)
+ return offset + 2
+}
+
+Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 3] = (value >>> 24)
+ return offset + 4
+}
+
+Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ if (value < 0) value = 0xffffffff + value + 1
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = (value & 0xff)
+ return offset + 4
+}
+
+function checkIEEE754 (buf, value, offset, ext, max, min) {
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
+ if (offset < 0) throw new RangeError('Index out of range')
+}
+
+function writeFloat (buf, value, offset, littleEndian, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
+ }
+ ieee754.write(buf, value, offset, littleEndian, 23, 4)
+ return offset + 4
+}
+
+Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, false, noAssert)
+}
+
+function writeDouble (buf, value, offset, littleEndian, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
+ }
+ ieee754.write(buf, value, offset, littleEndian, 52, 8)
+ return offset + 8
+}
+
+Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, false, noAssert)
+}
+
+// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+Buffer.prototype.copy = function copy (target, targetStart, start, end) {
+ if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
+ if (!start) start = 0
+ if (!end && end !== 0) end = this.length
+ if (targetStart >= target.length) targetStart = target.length
+ if (!targetStart) targetStart = 0
+ if (end > 0 && end < start) end = start
+
+ // Copy 0 bytes; we're done
+ if (end === start) return 0
+ if (target.length === 0 || this.length === 0) return 0
+
+ // Fatal error conditions
+ if (targetStart < 0) {
+ throw new RangeError('targetStart out of bounds')
+ }
+ if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
+ if (end < 0) throw new RangeError('sourceEnd out of bounds')
+
+ // Are we oob?
+ if (end > this.length) end = this.length
+ if (target.length - targetStart < end - start) {
+ end = target.length - targetStart + start
+ }
+
+ var len = end - start
+
+ if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
+ // Use built-in when available, missing from IE11
+ this.copyWithin(targetStart, start, end)
+ } else if (this === target && start < targetStart && targetStart < end) {
+ // descending copy from end
+ for (var i = len - 1; i >= 0; --i) {
+ target[i + targetStart] = this[i + start]
+ }
+ } else {
+ Uint8Array.prototype.set.call(
+ target,
+ this.subarray(start, end),
+ targetStart
+ )
+ }
+
+ return len
+}
+
+// Usage:
+// buffer.fill(number[, offset[, end]])
+// buffer.fill(buffer[, offset[, end]])
+// buffer.fill(string[, offset[, end]][, encoding])
+Buffer.prototype.fill = function fill (val, start, end, encoding) {
+ // Handle string cases:
+ if (typeof val === 'string') {
+ if (typeof start === 'string') {
+ encoding = start
+ start = 0
+ end = this.length
+ } else if (typeof end === 'string') {
+ encoding = end
+ end = this.length
+ }
+ if (encoding !== undefined && typeof encoding !== 'string') {
+ throw new TypeError('encoding must be a string')
+ }
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
+ throw new TypeError('Unknown encoding: ' + encoding)
+ }
+ if (val.length === 1) {
+ var code = val.charCodeAt(0)
+ if ((encoding === 'utf8' && code < 128) ||
+ encoding === 'latin1') {
+ // Fast path: If `val` fits into a single byte, use that numeric value.
+ val = code
+ }
+ }
+ } else if (typeof val === 'number') {
+ val = val & 255
+ }
+
+ // Invalid ranges are not set to a default, so can range check early.
+ if (start < 0 || this.length < start || this.length < end) {
+ throw new RangeError('Out of range index')
+ }
+
+ if (end <= start) {
+ return this
+ }
+
+ start = start >>> 0
+ end = end === undefined ? this.length : end >>> 0
+
+ if (!val) val = 0
+
+ var i
+ if (typeof val === 'number') {
+ for (i = start; i < end; ++i) {
+ this[i] = val
+ }
+ } else {
+ var bytes = Buffer.isBuffer(val)
+ ? val
+ : new Buffer(val, encoding)
+ var len = bytes.length
+ if (len === 0) {
+ throw new TypeError('The value "' + val +
+ '" is invalid for argument "value"')
+ }
+ for (i = 0; i < end - start; ++i) {
+ this[i + start] = bytes[i % len]
+ }
+ }
+
+ return this
+}
+
+// HELPER FUNCTIONS
+// ================
+
+var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
+
+function base64clean (str) {
+ // Node takes equal signs as end of the Base64 encoding
+ str = str.split('=')[0]
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
+ str = str.trim().replace(INVALID_BASE64_RE, '')
+ // Node converts strings with length < 2 to ''
+ if (str.length < 2) return ''
+ // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
+ while (str.length % 4 !== 0) {
+ str = str + '='
+ }
+ return str
+}
+
+function toHex (n) {
+ if (n < 16) return '0' + n.toString(16)
+ return n.toString(16)
+}
+
+function utf8ToBytes (string, units) {
+ units = units || Infinity
+ var codePoint
+ var length = string.length
+ var leadSurrogate = null
+ var bytes = []
+
+ for (var i = 0; i < length; ++i) {
+ codePoint = string.charCodeAt(i)
+
+ // is surrogate component
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
+ // last char was a lead
+ if (!leadSurrogate) {
+ // no lead yet
+ if (codePoint > 0xDBFF) {
+ // unexpected trail
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
+ } else if (i + 1 === length) {
+ // unpaired lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
+ }
+
+ // valid lead
+ leadSurrogate = codePoint
+
+ continue
+ }
+
+ // 2 leads in a row
+ if (codePoint < 0xDC00) {
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ leadSurrogate = codePoint
+ continue
+ }
+
+ // valid surrogate pair
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
+ } else if (leadSurrogate) {
+ // valid bmp char, but last char was a lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ }
+
+ leadSurrogate = null
+
+ // encode utf8
+ if (codePoint < 0x80) {
+ if ((units -= 1) < 0) break
+ bytes.push(codePoint)
+ } else if (codePoint < 0x800) {
+ if ((units -= 2) < 0) break
+ bytes.push(
+ codePoint >> 0x6 | 0xC0,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x10000) {
+ if ((units -= 3) < 0) break
+ bytes.push(
+ codePoint >> 0xC | 0xE0,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x110000) {
+ if ((units -= 4) < 0) break
+ bytes.push(
+ codePoint >> 0x12 | 0xF0,
+ codePoint >> 0xC & 0x3F | 0x80,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else {
+ throw new Error('Invalid code point')
+ }
+ }
+
+ return bytes
+}
+
+function asciiToBytes (str) {
+ var byteArray = []
+ for (var i = 0; i < str.length; ++i) {
+ // Node's code seems to be doing this and not & 0x7F..
+ byteArray.push(str.charCodeAt(i) & 0xFF)
+ }
+ return byteArray
+}
+
+function utf16leToBytes (str, units) {
+ var c, hi, lo
+ var byteArray = []
+ for (var i = 0; i < str.length; ++i) {
+ if ((units -= 2) < 0) break
+
+ c = str.charCodeAt(i)
+ hi = c >> 8
+ lo = c % 256
+ byteArray.push(lo)
+ byteArray.push(hi)
+ }
+
+ return byteArray
+}
+
+function base64ToBytes (str) {
+ return base64.toByteArray(base64clean(str))
+}
+
+function blitBuffer (src, dst, offset, length) {
+ for (var i = 0; i < length; ++i) {
+ if ((i + offset >= dst.length) || (i >= src.length)) break
+ dst[i + offset] = src[i]
+ }
+ return i
+}
+
+// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
+// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
+function isArrayBuffer (obj) {
+ return obj instanceof ArrayBuffer ||
+ (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
+ typeof obj.byteLength === 'number')
+}
+
+function numberIsNaN (obj) {
+ return obj !== obj // eslint-disable-line no-self-compare
+}
+
+},{"base64-js":13,"ieee754":76}],18:[function(require,module,exports){
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ var Pos = CodeMirror.Pos;
+
+ function forEach(arr, f) {
+ for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
+ }
+
+ function arrayContains(arr, item) {
+ if (!Array.prototype.indexOf) {
+ var i = arr.length;
+ while (i--) {
+ if (arr[i] === item) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return arr.indexOf(item) != -1;
+ }
+
+ function scriptHint(editor, keywords, getToken, options) {
+ // Find the token at the cursor
+ var cur = editor.getCursor(), token = getToken(editor, cur);
+ if (/\b(?:string|comment)\b/.test(token.type)) return;
+ var innerMode = CodeMirror.innerMode(editor.getMode(), token.state);
+ if (innerMode.mode.helperType === "json") return;
+ token.state = innerMode.state;
+
+ // If it's not a 'word-style' token, ignore the token.
+ if (!/^[\w$_]*$/.test(token.string)) {
+ token = {start: cur.ch, end: cur.ch, string: "", state: token.state,
+ type: token.string == "." ? "property" : null};
+ } else if (token.end > cur.ch) {
+ token.end = cur.ch;
+ token.string = token.string.slice(0, cur.ch - token.start);
+ }
+
+ var tprop = token;
+ // If it is a property, find out what it is a property of.
+ while (tprop.type == "property") {
+ tprop = getToken(editor, Pos(cur.line, tprop.start));
+ if (tprop.string != ".") return;
+ tprop = getToken(editor, Pos(cur.line, tprop.start));
+ if (!context) var context = [];
+ context.push(tprop);
+ }
+ return {list: getCompletions(token, context, keywords, options),
+ from: Pos(cur.line, token.start),
+ to: Pos(cur.line, token.end)};
+ }
+
+ function javascriptHint(editor, options) {
+ return scriptHint(editor, javascriptKeywords,
+ function (e, cur) {return e.getTokenAt(cur);},
+ options);
+ };
+ CodeMirror.registerHelper("hint", "javascript", javascriptHint);
+
+ function getCoffeeScriptToken(editor, cur) {
+ // This getToken, it is for coffeescript, imitates the behavior of
+ // getTokenAt method in javascript.js, that is, returning "property"
+ // type and treat "." as indepenent token.
+ var token = editor.getTokenAt(cur);
+ if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') {
+ token.end = token.start;
+ token.string = '.';
+ token.type = "property";
+ }
+ else if (/^\.[\w$_]*$/.test(token.string)) {
+ token.type = "property";
+ token.start++;
+ token.string = token.string.replace(/\./, '');
+ }
+ return token;
+ }
+
+ function coffeescriptHint(editor, options) {
+ return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options);
+ }
+ CodeMirror.registerHelper("hint", "coffeescript", coffeescriptHint);
+
+ var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " +
+ "toUpperCase toLowerCase split concat match replace search").split(" ");
+ var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " +
+ "lastIndexOf every some filter forEach map reduce reduceRight ").split(" ");
+ var funcProps = "prototype apply call bind".split(" ");
+ var javascriptKeywords = ("break case catch class const continue debugger default delete do else export extends false finally for function " +
+ "if in import instanceof new null return super switch this throw true try typeof var void while with yield").split(" ");
+ var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
+ "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");
+
+ function forAllProps(obj, callback) {
+ if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {
+ for (var name in obj) callback(name)
+ } else {
+ for (var o = obj; o; o = Object.getPrototypeOf(o))
+ Object.getOwnPropertyNames(o).forEach(callback)
+ }
+ }
+
+ function getCompletions(token, context, keywords, options) {
+ var found = [], start = token.string, global = options && options.globalScope || window;
+ function maybeAdd(str) {
+ if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str);
+ }
+ function gatherCompletions(obj) {
+ if (typeof obj == "string") forEach(stringProps, maybeAdd);
+ else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
+ else if (obj instanceof Function) forEach(funcProps, maybeAdd);
+ forAllProps(obj, maybeAdd)
+ }
+
+ if (context && context.length) {
+ // If this is a property, see if it belongs to some object we can
+ // find in the current environment.
+ var obj = context.pop(), base;
+ if (obj.type && obj.type.indexOf("variable") === 0) {
+ if (options && options.additionalContext)
+ base = options.additionalContext[obj.string];
+ if (!options || options.useGlobalScope !== false)
+ base = base || global[obj.string];
+ } else if (obj.type == "string") {
+ base = "";
+ } else if (obj.type == "atom") {
+ base = 1;
+ } else if (obj.type == "function") {
+ if (global.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') &&
+ (typeof global.jQuery == 'function'))
+ base = global.jQuery();
+ else if (global._ != null && (obj.string == '_') && (typeof global._ == 'function'))
+ base = global._();
+ }
+ while (base != null && context.length)
+ base = base[context.pop().string];
+ if (base != null) gatherCompletions(base);
+ } else {
+ // If not, just look in the global object and any local scope
+ // (reading into JS mode internals to get at the local and global variables)
+ for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name);
+ for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name);
+ if (!options || options.useGlobalScope !== false)
+ gatherCompletions(global);
+ forEach(keywords, maybeAdd);
+ }
+ return found;
+ }
+});
+
+},{"../../lib/codemirror":21}],19:[function(require,module,exports){
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var HINT_ELEMENT_CLASS = "CodeMirror-hint";
+ var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";
+
+ // This is the old interface, kept around for now to stay
+ // backwards-compatible.
+ CodeMirror.showHint = function(cm, getHints, options) {
+ if (!getHints) return cm.showHint(options);
+ if (options && options.async) getHints.async = true;
+ var newOpts = {hint: getHints};
+ if (options) for (var prop in options) newOpts[prop] = options[prop];
+ return cm.showHint(newOpts);
+ };
+
+ CodeMirror.defineExtension("showHint", function(options) {
+ options = parseOptions(this, this.getCursor("start"), options);
+ var selections = this.listSelections()
+ if (selections.length > 1) return;
+ // By default, don't allow completion when something is selected.
+ // A hint function can have a `supportsSelection` property to
+ // indicate that it can handle selections.
+ if (this.somethingSelected()) {
+ if (!options.hint.supportsSelection) return;
+ // Don't try with cross-line selections
+ for (var i = 0; i < selections.length; i++)
+ if (selections[i].head.line != selections[i].anchor.line) return;
+ }
+
+ if (this.state.completionActive) this.state.completionActive.close();
+ var completion = this.state.completionActive = new Completion(this, options);
+ if (!completion.options.hint) return;
+
+ CodeMirror.signal(this, "startCompletion", this);
+ completion.update(true);
+ });
+
+ function Completion(cm, options) {
+ this.cm = cm;
+ this.options = options;
+ this.widget = null;
+ this.debounce = 0;
+ this.tick = 0;
+ this.startPos = this.cm.getCursor("start");
+ this.startLen = this.cm.getLine(this.startPos.line).length - this.cm.getSelection().length;
+
+ var self = this;
+ cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
+ }
+
+ var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
+ return setTimeout(fn, 1000/60);
+ };
+ var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
+
+ Completion.prototype = {
+ close: function() {
+ if (!this.active()) return;
+ this.cm.state.completionActive = null;
+ this.tick = null;
+ this.cm.off("cursorActivity", this.activityFunc);
+
+ if (this.widget && this.data) CodeMirror.signal(this.data, "close");
+ if (this.widget) this.widget.close();
+ CodeMirror.signal(this.cm, "endCompletion", this.cm);
+ },
+
+ active: function() {
+ return this.cm.state.completionActive == this;
+ },
+
+ pick: function(data, i) {
+ var completion = data.list[i];
+ if (completion.hint) completion.hint(this.cm, data, completion);
+ else this.cm.replaceRange(getText(completion), completion.from || data.from,
+ completion.to || data.to, "complete");
+ CodeMirror.signal(data, "pick", completion);
+ this.close();
+ },
+
+ cursorActivity: function() {
+ if (this.debounce) {
+ cancelAnimationFrame(this.debounce);
+ this.debounce = 0;
+ }
+
+ var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
+ if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
+ pos.ch < this.startPos.ch || this.cm.somethingSelected() ||
+ (pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
+ this.close();
+ } else {
+ var self = this;
+ this.debounce = requestAnimationFrame(function() {self.update();});
+ if (this.widget) this.widget.disable();
+ }
+ },
+
+ update: function(first) {
+ if (this.tick == null) return
+ var self = this, myTick = ++this.tick
+ fetchHints(this.options.hint, this.cm, this.options, function(data) {
+ if (self.tick == myTick) self.finishUpdate(data, first)
+ })
+ },
+
+ finishUpdate: function(data, first) {
+ if (this.data) CodeMirror.signal(this.data, "update");
+
+ var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
+ if (this.widget) this.widget.close();
+
+ this.data = data;
+
+ if (data && data.list.length) {
+ if (picked && data.list.length == 1) {
+ this.pick(data, 0);
+ } else {
+ this.widget = new Widget(this, data);
+ CodeMirror.signal(data, "shown");
+ }
+ }
+ }
+ };
+
+ function parseOptions(cm, pos, options) {
+ var editor = cm.options.hintOptions;
+ var out = {};
+ for (var prop in defaultOptions) out[prop] = defaultOptions[prop];
+ if (editor) for (var prop in editor)
+ if (editor[prop] !== undefined) out[prop] = editor[prop];
+ if (options) for (var prop in options)
+ if (options[prop] !== undefined) out[prop] = options[prop];
+ if (out.hint.resolve) out.hint = out.hint.resolve(cm, pos)
+ return out;
+ }
+
+ function getText(completion) {
+ if (typeof completion == "string") return completion;
+ else return completion.text;
+ }
+
+ function buildKeyMap(completion, handle) {
+ var baseMap = {
+ Up: function() {handle.moveFocus(-1);},
+ Down: function() {handle.moveFocus(1);},
+ PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
+ PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
+ Home: function() {handle.setFocus(0);},
+ End: function() {handle.setFocus(handle.length - 1);},
+ Enter: handle.pick,
+ Tab: handle.pick,
+ Esc: handle.close
+ };
+ var custom = completion.options.customKeys;
+ var ourMap = custom ? {} : baseMap;
+ function addBinding(key, val) {
+ var bound;
+ if (typeof val != "string")
+ bound = function(cm) { return val(cm, handle); };
+ // This mechanism is deprecated
+ else if (baseMap.hasOwnProperty(val))
+ bound = baseMap[val];
+ else
+ bound = val;
+ ourMap[key] = bound;
+ }
+ if (custom)
+ for (var key in custom) if (custom.hasOwnProperty(key))
+ addBinding(key, custom[key]);
+ var extra = completion.options.extraKeys;
+ if (extra)
+ for (var key in extra) if (extra.hasOwnProperty(key))
+ addBinding(key, extra[key]);
+ return ourMap;
+ }
+
+ function getHintElement(hintsElement, el) {
+ while (el && el != hintsElement) {
+ if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
+ el = el.parentNode;
+ }
+ }
+
+ function Widget(completion, data) {
+ this.completion = completion;
+ this.data = data;
+ this.picked = false;
+ var widget = this, cm = completion.cm;
+
+ var hints = this.hints = document.createElement("ul");
+ hints.className = "CodeMirror-hints";
+ this.selectedHint = data.selectedHint || 0;
+
+ var completions = data.list;
+ for (var i = 0; i < completions.length; ++i) {
+ var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
+ var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
+ if (cur.className != null) className = cur.className + " " + className;
+ elt.className = className;
+ if (cur.render) cur.render(elt, data, cur);
+ else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
+ elt.hintId = i;
+ }
+
+ var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
+ var left = pos.left, top = pos.bottom, below = true;
+ hints.style.left = left + "px";
+ hints.style.top = top + "px";
+ // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
+ var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
+ var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
+ (completion.options.container || document.body).appendChild(hints);
+ var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
+ var scrolls = hints.scrollHeight > hints.clientHeight + 1
+ var startScroll = cm.getScrollInfo();
+
+ if (overlapY > 0) {
+ var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
+ if (curTop - height > 0) { // Fits above cursor
+ hints.style.top = (top = pos.top - height) + "px";
+ below = false;
+ } else if (height > winH) {
+ hints.style.height = (winH - 5) + "px";
+ hints.style.top = (top = pos.bottom - box.top) + "px";
+ var cursor = cm.getCursor();
+ if (data.from.ch != cursor.ch) {
+ pos = cm.cursorCoords(cursor);
+ hints.style.left = (left = pos.left) + "px";
+ box = hints.getBoundingClientRect();
+ }
+ }
+ }
+ var overlapX = box.right - winW;
+ if (overlapX > 0) {
+ if (box.right - box.left > winW) {
+ hints.style.width = (winW - 5) + "px";
+ overlapX -= (box.right - box.left) - winW;
+ }
+ hints.style.left = (left = pos.left - overlapX) + "px";
+ }
+ if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
+ node.style.paddingRight = cm.display.nativeBarWidth + "px"
+
+ cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
+ moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
+ setFocus: function(n) { widget.changeActive(n); },
+ menuSize: function() { return widget.screenAmount(); },
+ length: completions.length,
+ close: function() { completion.close(); },
+ pick: function() { widget.pick(); },
+ data: data
+ }));
+
+ if (completion.options.closeOnUnfocus) {
+ var closingOnBlur;
+ cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
+ cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
+ }
+
+ cm.on("scroll", this.onScroll = function() {
+ var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
+ var newTop = top + startScroll.top - curScroll.top;
+ var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
+ if (!below) point += hints.offsetHeight;
+ if (point <= editor.top || point >= editor.bottom) return completion.close();
+ hints.style.top = newTop + "px";
+ hints.style.left = (left + startScroll.left - curScroll.left) + "px";
+ });
+
+ CodeMirror.on(hints, "dblclick", function(e) {
+ var t = getHintElement(hints, e.target || e.srcElement);
+ if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
+ });
+
+ CodeMirror.on(hints, "click", function(e) {
+ var t = getHintElement(hints, e.target || e.srcElement);
+ if (t && t.hintId != null) {
+ widget.changeActive(t.hintId);
+ if (completion.options.completeOnSingleClick) widget.pick();
+ }
+ });
+
+ CodeMirror.on(hints, "mousedown", function() {
+ setTimeout(function(){cm.focus();}, 20);
+ });
+
+ CodeMirror.signal(data, "select", completions[this.selectedHint], hints.childNodes[this.selectedHint]);
+ return true;
+ }
+
+ Widget.prototype = {
+ close: function() {
+ if (this.completion.widget != this) return;
+ this.completion.widget = null;
+ this.hints.parentNode.removeChild(this.hints);
+ this.completion.cm.removeKeyMap(this.keyMap);
+
+ var cm = this.completion.cm;
+ if (this.completion.options.closeOnUnfocus) {
+ cm.off("blur", this.onBlur);
+ cm.off("focus", this.onFocus);
+ }
+ cm.off("scroll", this.onScroll);
+ },
+
+ disable: function() {
+ this.completion.cm.removeKeyMap(this.keyMap);
+ var widget = this;
+ this.keyMap = {Enter: function() { widget.picked = true; }};
+ this.completion.cm.addKeyMap(this.keyMap);
+ },
+
+ pick: function() {
+ this.completion.pick(this.data, this.selectedHint);
+ },
+
+ changeActive: function(i, avoidWrap) {
+ if (i >= this.data.list.length)
+ i = avoidWrap ? this.data.list.length - 1 : 0;
+ else if (i < 0)
+ i = avoidWrap ? 0 : this.data.list.length - 1;
+ if (this.selectedHint == i) return;
+ var node = this.hints.childNodes[this.selectedHint];
+ node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
+ node = this.hints.childNodes[this.selectedHint = i];
+ node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
+ if (node.offsetTop < this.hints.scrollTop)
+ this.hints.scrollTop = node.offsetTop - 3;
+ else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
+ this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
+ CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
+ },
+
+ screenAmount: function() {
+ return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
+ }
+ };
+
+ function applicableHelpers(cm, helpers) {
+ if (!cm.somethingSelected()) return helpers
+ var result = []
+ for (var i = 0; i < helpers.length; i++)
+ if (helpers[i].supportsSelection) result.push(helpers[i])
+ return result
+ }
+
+ function fetchHints(hint, cm, options, callback) {
+ if (hint.async) {
+ hint(cm, callback, options)
+ } else {
+ var result = hint(cm, options)
+ if (result && result.then) result.then(callback)
+ else callback(result)
+ }
+ }
+
+ function resolveAutoHints(cm, pos) {
+ var helpers = cm.getHelpers(pos, "hint"), words
+ if (helpers.length) {
+ var resolved = function(cm, callback, options) {
+ var app = applicableHelpers(cm, helpers);
+ function run(i) {
+ if (i == app.length) return callback(null)
+ fetchHints(app[i], cm, options, function(result) {
+ if (result && result.list.length > 0) callback(result)
+ else run(i + 1)
+ })
+ }
+ run(0)
+ }
+ resolved.async = true
+ resolved.supportsSelection = true
+ return resolved
+ } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
+ return function(cm) { return CodeMirror.hint.fromList(cm, {words: words}) }
+ } else if (CodeMirror.hint.anyword) {
+ return function(cm, options) { return CodeMirror.hint.anyword(cm, options) }
+ } else {
+ return function() {}
+ }
+ }
+
+ CodeMirror.registerHelper("hint", "auto", {
+ resolve: resolveAutoHints
+ });
+
+ CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
+ var cur = cm.getCursor(), token = cm.getTokenAt(cur)
+ var term, from = CodeMirror.Pos(cur.line, token.start), to = cur
+ if (token.start < cur.ch && /\w/.test(token.string.charAt(cur.ch - token.start - 1))) {
+ term = token.string.substr(0, cur.ch - token.start)
+ } else {
+ term = ""
+ from = cur
+ }
+ var found = [];
+ for (var i = 0; i < options.words.length; i++) {
+ var word = options.words[i];
+ if (word.slice(0, term.length) == term)
+ found.push(word);
+ }
+
+ if (found.length) return {list: found, from: from, to: to};
+ });
+
+ CodeMirror.commands.autocomplete = CodeMirror.showHint;
+
+ var defaultOptions = {
+ hint: CodeMirror.hint.auto,
+ completeSingle: true,
+ alignWithWord: true,
+ closeCharacters: /[\s()\[\]{};:>,]/,
+ closeOnUnfocus: true,
+ completeOnSingleClick: true,
+ container: null,
+ customKeys: null,
+ extraKeys: null
+ };
+
+ CodeMirror.defineOption("hintOptions", null);
+});
+
+},{"../../lib/codemirror":21}],20:[function(require,module,exports){
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// Because sometimes you need to mark the selected *text*.
+//
+// Adds an option 'styleSelectedText' which, when enabled, gives
+// selected text the CSS class given as option value, or
+// "CodeMirror-selectedtext" when the value is not a string.
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
+ var prev = old && old != CodeMirror.Init;
+ if (val && !prev) {
+ cm.state.markedSelection = [];
+ cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
+ reset(cm);
+ cm.on("cursorActivity", onCursorActivity);
+ cm.on("change", onChange);
+ } else if (!val && prev) {
+ cm.off("cursorActivity", onCursorActivity);
+ cm.off("change", onChange);
+ clear(cm);
+ cm.state.markedSelection = cm.state.markedSelectionStyle = null;
+ }
+ });
+
+ function onCursorActivity(cm) {
+ if (cm.state.markedSelection)
+ cm.operation(function() { update(cm); });
+ }
+
+ function onChange(cm) {
+ if (cm.state.markedSelection && cm.state.markedSelection.length)
+ cm.operation(function() { clear(cm); });
+ }
+
+ var CHUNK_SIZE = 8;
+ var Pos = CodeMirror.Pos;
+ var cmp = CodeMirror.cmpPos;
+
+ function coverRange(cm, from, to, addAt) {
+ if (cmp(from, to) == 0) return;
+ var array = cm.state.markedSelection;
+ var cls = cm.state.markedSelectionStyle;
+ for (var line = from.line;;) {
+ var start = line == from.line ? from : Pos(line, 0);
+ var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
+ var end = atEnd ? to : Pos(endLine, 0);
+ var mark = cm.markText(start, end, {className: cls});
+ if (addAt == null) array.push(mark);
+ else array.splice(addAt++, 0, mark);
+ if (atEnd) break;
+ line = endLine;
+ }
+ }
+
+ function clear(cm) {
+ var array = cm.state.markedSelection;
+ for (var i = 0; i < array.length; ++i) array[i].clear();
+ array.length = 0;
+ }
+
+ function reset(cm) {
+ clear(cm);
+ var ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++)
+ coverRange(cm, ranges[i].from(), ranges[i].to());
+ }
+
+ function update(cm) {
+ if (!cm.somethingSelected()) return clear(cm);
+ if (cm.listSelections().length > 1) return reset(cm);
+
+ var from = cm.getCursor("start"), to = cm.getCursor("end");
+
+ var array = cm.state.markedSelection;
+ if (!array.length) return coverRange(cm, from, to);
+
+ var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
+ if (!coverStart || !coverEnd || to.line - from.line <= CHUNK_SIZE ||
+ cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
+ return reset(cm);
+
+ while (cmp(from, coverStart.from) > 0) {
+ array.shift().clear();
+ coverStart = array[0].find();
+ }
+ if (cmp(from, coverStart.from) < 0) {
+ if (coverStart.to.line - from.line < CHUNK_SIZE) {
+ array.shift().clear();
+ coverRange(cm, from, coverStart.to, 0);
+ } else {
+ coverRange(cm, from, coverStart.from, 0);
+ }
+ }
+
+ while (cmp(to, coverEnd.to) < 0) {
+ array.pop().clear();
+ coverEnd = array[array.length - 1].find();
+ }
+ if (cmp(to, coverEnd.to) > 0) {
+ if (to.line - coverEnd.from.line < CHUNK_SIZE) {
+ array.pop().clear();
+ coverRange(cm, coverEnd.from, to);
+ } else {
+ coverRange(cm, coverEnd.to, to);
+ }
+ }
+ }
+});
+
+},{"../../lib/codemirror":21}],21:[function(require,module,exports){
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+// This is CodeMirror (http://codemirror.net), a code editor
+// implemented in JavaScript on top of the browser's DOM.
+//
+// You can find some technical background for some of the code below
+// at http://marijnhaverbeke.nl/blog/#cm-internals .
+
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global.CodeMirror = factory());
+}(this, (function () { 'use strict';
+
+// Kludges for bugs and behavior differences that can't be feature
+// detected are enabled based on userAgent etc sniffing.
+var userAgent = navigator.userAgent;
+var platform = navigator.platform;
+
+var gecko = /gecko\/\d/i.test(userAgent);
+var ie_upto10 = /MSIE \d/.test(userAgent);
+var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
+var edge = /Edge\/(\d+)/.exec(userAgent);
+var ie = ie_upto10 || ie_11up || edge;
+var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
+var webkit = !edge && /WebKit\//.test(userAgent);
+var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
+var chrome = !edge && /Chrome\//.test(userAgent);
+var presto = /Opera\//.test(userAgent);
+var safari = /Apple Computer/.test(navigator.vendor);
+var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
+var phantom = /PhantomJS/.test(userAgent);
+
+var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
+var android = /Android/.test(userAgent);
+// This is woefully incomplete. Suggestions for alternative methods welcome.
+var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
+var mac = ios || /Mac/.test(platform);
+var chromeOS = /\bCrOS\b/.test(userAgent);
+var windows = /win/i.test(platform);
+
+var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
+if (presto_version) { presto_version = Number(presto_version[1]); }
+if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
+// Some browsers use the wrong event properties to signal cmd/ctrl on OS X
+var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
+var captureRightClick = gecko || (ie && ie_version >= 9);
+
+function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
+
+var rmClass = function(node, cls) {
+ var current = node.className;
+ var match = classTest(cls).exec(current);
+ if (match) {
+ var after = current.slice(match.index + match[0].length);
+ node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
+ }
+};
+
+function removeChildren(e) {
+ for (var count = e.childNodes.length; count > 0; --count)
+ { e.removeChild(e.firstChild); }
+ return e
+}
+
+function removeChildrenAndAdd(parent, e) {
+ return removeChildren(parent).appendChild(e)
+}
+
+function elt(tag, content, className, style) {
+ var e = document.createElement(tag);
+ if (className) { e.className = className; }
+ if (style) { e.style.cssText = style; }
+ if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
+ else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
+ return e
+}
+// wrapper for elt, which removes the elt from the accessibility tree
+function eltP(tag, content, className, style) {
+ var e = elt(tag, content, className, style);
+ e.setAttribute("role", "presentation");
+ return e
+}
+
+var range;
+if (document.createRange) { range = function(node, start, end, endNode) {
+ var r = document.createRange();
+ r.setEnd(endNode || node, end);
+ r.setStart(node, start);
+ return r
+}; }
+else { range = function(node, start, end) {
+ var r = document.body.createTextRange();
+ try { r.moveToElementText(node.parentNode); }
+ catch(e) { return r }
+ r.collapse(true);
+ r.moveEnd("character", end);
+ r.moveStart("character", start);
+ return r
+}; }
+
+function contains(parent, child) {
+ if (child.nodeType == 3) // Android browser always returns false when child is a textnode
+ { child = child.parentNode; }
+ if (parent.contains)
+ { return parent.contains(child) }
+ do {
+ if (child.nodeType == 11) { child = child.host; }
+ if (child == parent) { return true }
+ } while (child = child.parentNode)
+}
+
+function activeElt() {
+ // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
+ // IE < 10 will throw when accessed while the page is loading or in an iframe.
+ // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
+ var activeElement;
+ try {
+ activeElement = document.activeElement;
+ } catch(e) {
+ activeElement = document.body || null;
+ }
+ while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
+ { activeElement = activeElement.shadowRoot.activeElement; }
+ return activeElement
+}
+
+function addClass(node, cls) {
+ var current = node.className;
+ if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
+}
+function joinClasses(a, b) {
+ var as = a.split(" ");
+ for (var i = 0; i < as.length; i++)
+ { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
+ return b
+}
+
+var selectInput = function(node) { node.select(); };
+if (ios) // Mobile Safari apparently has a bug where select() is broken.
+ { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
+else if (ie) // Suppress mysterious IE10 errors
+ { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
+
+function bind(f) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function(){return f.apply(null, args)}
+}
+
+function copyObj(obj, target, overwrite) {
+ if (!target) { target = {}; }
+ for (var prop in obj)
+ { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
+ { target[prop] = obj[prop]; } }
+ return target
+}
+
+// Counts the column offset in a string, taking tabs into account.
+// Used mostly to find indentation.
+function countColumn(string, end, tabSize, startIndex, startValue) {
+ if (end == null) {
+ end = string.search(/[^\s\u00a0]/);
+ if (end == -1) { end = string.length; }
+ }
+ for (var i = startIndex || 0, n = startValue || 0;;) {
+ var nextTab = string.indexOf("\t", i);
+ if (nextTab < 0 || nextTab >= end)
+ { return n + (end - i) }
+ n += nextTab - i;
+ n += tabSize - (n % tabSize);
+ i = nextTab + 1;
+ }
+}
+
+var Delayed = function() {this.id = null;};
+Delayed.prototype.set = function (ms, f) {
+ clearTimeout(this.id);
+ this.id = setTimeout(f, ms);
+};
+
+function indexOf(array, elt) {
+ for (var i = 0; i < array.length; ++i)
+ { if (array[i] == elt) { return i } }
+ return -1
+}
+
+// Number of pixels added to scroller and sizer to hide scrollbar
+var scrollerGap = 30;
+
+// Returned or thrown by various protocols to signal 'I'm not
+// handling this'.
+var Pass = {toString: function(){return "CodeMirror.Pass"}};
+
+// Reused option objects for setSelection & friends
+var sel_dontScroll = {scroll: false};
+var sel_mouse = {origin: "*mouse"};
+var sel_move = {origin: "+move"};
+
+// The inverse of countColumn -- find the offset that corresponds to
+// a particular column.
+function findColumn(string, goal, tabSize) {
+ for (var pos = 0, col = 0;;) {
+ var nextTab = string.indexOf("\t", pos);
+ if (nextTab == -1) { nextTab = string.length; }
+ var skipped = nextTab - pos;
+ if (nextTab == string.length || col + skipped >= goal)
+ { return pos + Math.min(skipped, goal - col) }
+ col += nextTab - pos;
+ col += tabSize - (col % tabSize);
+ pos = nextTab + 1;
+ if (col >= goal) { return pos }
+ }
+}
+
+var spaceStrs = [""];
+function spaceStr(n) {
+ while (spaceStrs.length <= n)
+ { spaceStrs.push(lst(spaceStrs) + " "); }
+ return spaceStrs[n]
+}
+
+function lst(arr) { return arr[arr.length-1] }
+
+function map(array, f) {
+ var out = [];
+ for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
+ return out
+}
+
+function insertSorted(array, value, score) {
+ var pos = 0, priority = score(value);
+ while (pos < array.length && score(array[pos]) <= priority) { pos++; }
+ array.splice(pos, 0, value);
+}
+
+function nothing() {}
+
+function createObj(base, props) {
+ var inst;
+ if (Object.create) {
+ inst = Object.create(base);
+ } else {
+ nothing.prototype = base;
+ inst = new nothing();
+ }
+ if (props) { copyObj(props, inst); }
+ return inst
+}
+
+var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
+function isWordCharBasic(ch) {
+ return /\w/.test(ch) || ch > "\x80" &&
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
+}
+function isWordChar(ch, helper) {
+ if (!helper) { return isWordCharBasic(ch) }
+ if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
+ return helper.test(ch)
+}
+
+function isEmpty(obj) {
+ for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
+ return true
+}
+
+// Extending unicode characters. A series of a non-extending char +
+// any number of extending chars is treated as a single unit as far
+// as editing and measuring is concerned. This is not fully correct,
+// since some scripts/fonts/browsers also treat other configurations
+// of code points as a group.
+var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;
+function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
+
+// Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
+function skipExtendingChars(str, pos, dir) {
+ while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
+ return pos
+}
+
+// Returns the value from the range [`from`; `to`] that satisfies
+// `pred` and is closest to `from`. Assumes that at least `to`
+// satisfies `pred`. Supports `from` being greater than `to`.
+function findFirst(pred, from, to) {
+ // At any point we are certain `to` satisfies `pred`, don't know
+ // whether `from` does.
+ var dir = from > to ? -1 : 1;
+ for (;;) {
+ if (from == to) { return from }
+ var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
+ if (mid == from) { return pred(mid) ? from : to }
+ if (pred(mid)) { to = mid; }
+ else { from = mid + dir; }
+ }
+}
+
+// The display handles the DOM integration, both for input reading
+// and content drawing. It holds references to DOM nodes and
+// display-related state.
+
+function Display(place, doc, input) {
+ var d = this;
+ this.input = input;
+
+ // Covers bottom-right square when both scrollbars are present.
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
+ d.scrollbarFiller.setAttribute("cm-not-content", "true");
+ // Covers bottom of gutter when coverGutterNextToScrollbar is on
+ // and h scrollbar is present.
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
+ d.gutterFiller.setAttribute("cm-not-content", "true");
+ // Will contain the actual code, positioned to cover the viewport.
+ d.lineDiv = eltP("div", null, "CodeMirror-code");
+ // Elements are added to these to represent selection and cursors.
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
+ d.cursorDiv = elt("div", null, "CodeMirror-cursors");
+ // A visibility: hidden element used to find the size of things.
+ d.measure = elt("div", null, "CodeMirror-measure");
+ // When lines outside of the viewport are measured, they are drawn in this.
+ d.lineMeasure = elt("div", null, "CodeMirror-measure");
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
+ d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
+ null, "position: relative; outline: none");
+ var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
+ // Moved around its parent to cover visible view.
+ d.mover = elt("div", [lines], null, "position: relative");
+ // Set to the height of the document, allowing scrolling.
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
+ d.sizerWidth = null;
+ // Behavior of elts with overflow: auto and padding is
+ // inconsistent across browsers. This is used to ensure the
+ // scrollable area is big enough.
+ d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
+ // Will contain the gutters, if any.
+ d.gutters = elt("div", null, "CodeMirror-gutters");
+ d.lineGutter = null;
+ // Actual scrollable element.
+ d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
+ d.scroller.setAttribute("tabIndex", "-1");
+ // The element in which the editor lives.
+ d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
+
+ // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
+ if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
+ if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
+
+ if (place) {
+ if (place.appendChild) { place.appendChild(d.wrapper); }
+ else { place(d.wrapper); }
+ }
+
+ // Current rendered range (may be bigger than the view window).
+ d.viewFrom = d.viewTo = doc.first;
+ d.reportedViewFrom = d.reportedViewTo = doc.first;
+ // Information about the rendered lines.
+ d.view = [];
+ d.renderedView = null;
+ // Holds info about a single rendered line when it was rendered
+ // for measurement, while not in view.
+ d.externalMeasured = null;
+ // Empty space (in pixels) above the view
+ d.viewOffset = 0;
+ d.lastWrapHeight = d.lastWrapWidth = 0;
+ d.updateLineNumbers = null;
+
+ d.nativeBarWidth = d.barHeight = d.barWidth = 0;
+ d.scrollbarsClipped = false;
+
+ // Used to only resize the line number gutter when necessary (when
+ // the amount of lines crosses a boundary that makes its width change)
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
+ // Set to true when a non-horizontal-scrolling line widget is
+ // added. As an optimization, line widget aligning is skipped when
+ // this is false.
+ d.alignWidgets = false;
+
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
+
+ // Tracks the maximum line length so that the horizontal scrollbar
+ // can be kept static when scrolling.
+ d.maxLine = null;
+ d.maxLineLength = 0;
+ d.maxLineChanged = false;
+
+ // Used for measuring wheel scrolling granularity
+ d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
+
+ // True when shift is held down.
+ d.shift = false;
+
+ // Used to track whether anything happened since the context menu
+ // was opened.
+ d.selForContextMenu = null;
+
+ d.activeTouch = null;
+
+ input.init(d);
+}
+
+// Find the line object corresponding to the given line number.
+function getLine(doc, n) {
+ n -= doc.first;
+ if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
+ var chunk = doc;
+ while (!chunk.lines) {
+ for (var i = 0;; ++i) {
+ var child = chunk.children[i], sz = child.chunkSize();
+ if (n < sz) { chunk = child; break }
+ n -= sz;
+ }
+ }
+ return chunk.lines[n]
+}
+
+// Get the part of a document between two positions, as an array of
+// strings.
+function getBetween(doc, start, end) {
+ var out = [], n = start.line;
+ doc.iter(start.line, end.line + 1, function (line) {
+ var text = line.text;
+ if (n == end.line) { text = text.slice(0, end.ch); }
+ if (n == start.line) { text = text.slice(start.ch); }
+ out.push(text);
+ ++n;
+ });
+ return out
+}
+// Get the lines between from and to, as array of strings.
+function getLines(doc, from, to) {
+ var out = [];
+ doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
+ return out
+}
+
+// Update the height of a line, propagating the height change
+// upwards to parent nodes.
+function updateLineHeight(line, height) {
+ var diff = height - line.height;
+ if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
+}
+
+// Given a line object, find its line number by walking up through
+// its parent links.
+function lineNo(line) {
+ if (line.parent == null) { return null }
+ var cur = line.parent, no = indexOf(cur.lines, line);
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
+ for (var i = 0;; ++i) {
+ if (chunk.children[i] == cur) { break }
+ no += chunk.children[i].chunkSize();
+ }
+ }
+ return no + cur.first
+}
+
+// Find the line at the given vertical position, using the height
+// information in the document tree.
+function lineAtHeight(chunk, h) {
+ var n = chunk.first;
+ outer: do {
+ for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
+ var child = chunk.children[i$1], ch = child.height;
+ if (h < ch) { chunk = child; continue outer }
+ h -= ch;
+ n += child.chunkSize();
+ }
+ return n
+ } while (!chunk.lines)
+ var i = 0;
+ for (; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i], lh = line.height;
+ if (h < lh) { break }
+ h -= lh;
+ }
+ return n + i
+}
+
+function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
+
+function lineNumberFor(options, i) {
+ return String(options.lineNumberFormatter(i + options.firstLineNumber))
+}
+
+// A Pos instance represents a position within the text.
+function Pos(line, ch, sticky) {
+ if ( sticky === void 0 ) sticky = null;
+
+ if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
+ this.line = line;
+ this.ch = ch;
+ this.sticky = sticky;
+}
+
+// Compare two positions, return 0 if they are the same, a negative
+// number when a is less, and a positive number otherwise.
+function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
+
+function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
+
+function copyPos(x) {return Pos(x.line, x.ch)}
+function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
+function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
+
+// Most of the external API clips given positions to make sure they
+// actually exist within the document.
+function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
+function clipPos(doc, pos) {
+ if (pos.line < doc.first) { return Pos(doc.first, 0) }
+ var last = doc.first + doc.size - 1;
+ if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
+ return clipToLen(pos, getLine(doc, pos.line).text.length)
+}
+function clipToLen(pos, linelen) {
+ var ch = pos.ch;
+ if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
+ else if (ch < 0) { return Pos(pos.line, 0) }
+ else { return pos }
+}
+function clipPosArray(doc, array) {
+ var out = [];
+ for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
+ return out
+}
+
+// Optimize some code when these features are not used.
+var sawReadOnlySpans = false;
+var sawCollapsedSpans = false;
+
+function seeReadOnlySpans() {
+ sawReadOnlySpans = true;
+}
+
+function seeCollapsedSpans() {
+ sawCollapsedSpans = true;
+}
+
+// TEXTMARKER SPANS
+
+function MarkedSpan(marker, from, to) {
+ this.marker = marker;
+ this.from = from; this.to = to;
+}
+
+// Search an array of spans for a span matching the given marker.
+function getMarkedSpanFor(spans, marker) {
+ if (spans) { for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if (span.marker == marker) { return span }
+ } }
+}
+// Remove a span from an array, returning undefined if no spans are
+// left (we don't store arrays for lines without spans).
+function removeMarkedSpan(spans, span) {
+ var r;
+ for (var i = 0; i < spans.length; ++i)
+ { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
+ return r
+}
+// Add a span to a line.
+function addMarkedSpan(line, span) {
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
+ span.marker.attachLine(line);
+}
+
+// Used for the algorithm that adjusts markers for a change in the
+// document. These functions cut an array of spans at a given
+// character position, returning an array of remaining chunks (or
+// undefined if nothing remains).
+function markedSpansBefore(old, startCh, isInsert) {
+ var nw;
+ if (old) { for (var i = 0; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
+ if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
+ }
+ } }
+ return nw
+}
+function markedSpansAfter(old, endCh, isInsert) {
+ var nw;
+ if (old) { for (var i = 0; i < old.length; ++i) {
+ var span = old[i], marker = span.marker;
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
+ if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
+ span.to == null ? null : span.to - endCh));
+ }
+ } }
+ return nw
+}
+
+// Given a change object, compute the new set of marker spans that
+// cover the line in which the change took place. Removes spans
+// entirely within the change, reconnects spans belonging to the
+// same marker that appear on both sides of the change, and cuts off
+// spans partially within the change. Returns an array of span
+// arrays with one element for each line in (after) the change.
+function stretchSpansOverChange(doc, change) {
+ if (change.full) { return null }
+ var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
+ var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
+ if (!oldFirst && !oldLast) { return null }
+
+ var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
+ // Get the spans that 'stick out' on both sides
+ var first = markedSpansBefore(oldFirst, startCh, isInsert);
+ var last = markedSpansAfter(oldLast, endCh, isInsert);
+
+ // Next, merge those two ends
+ var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
+ if (first) {
+ // Fix up .to properties of first
+ for (var i = 0; i < first.length; ++i) {
+ var span = first[i];
+ if (span.to == null) {
+ var found = getMarkedSpanFor(last, span.marker);
+ if (!found) { span.to = startCh; }
+ else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
+ }
+ }
+ }
+ if (last) {
+ // Fix up .from in last (or move them into first in case of sameLine)
+ for (var i$1 = 0; i$1 < last.length; ++i$1) {
+ var span$1 = last[i$1];
+ if (span$1.to != null) { span$1.to += offset; }
+ if (span$1.from == null) {
+ var found$1 = getMarkedSpanFor(first, span$1.marker);
+ if (!found$1) {
+ span$1.from = offset;
+ if (sameLine) { (first || (first = [])).push(span$1); }
+ }
+ } else {
+ span$1.from += offset;
+ if (sameLine) { (first || (first = [])).push(span$1); }
+ }
+ }
+ }
+ // Make sure we didn't create any zero-length spans
+ if (first) { first = clearEmptySpans(first); }
+ if (last && last != first) { last = clearEmptySpans(last); }
+
+ var newMarkers = [first];
+ if (!sameLine) {
+ // Fill gap with whole-line-spans
+ var gap = change.text.length - 2, gapMarkers;
+ if (gap > 0 && first)
+ { for (var i$2 = 0; i$2 < first.length; ++i$2)
+ { if (first[i$2].to == null)
+ { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
+ for (var i$3 = 0; i$3 < gap; ++i$3)
+ { newMarkers.push(gapMarkers); }
+ newMarkers.push(last);
+ }
+ return newMarkers
+}
+
+// Remove spans that are empty and don't have a clearWhenEmpty
+// option of false.
+function clearEmptySpans(spans) {
+ for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
+ { spans.splice(i--, 1); }
+ }
+ if (!spans.length) { return null }
+ return spans
+}
+
+// Used to 'clip' out readOnly ranges when making a change.
+function removeReadOnlyRanges(doc, from, to) {
+ var markers = null;
+ doc.iter(from.line, to.line + 1, function (line) {
+ if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
+ var mark = line.markedSpans[i].marker;
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
+ { (markers || (markers = [])).push(mark); }
+ } }
+ });
+ if (!markers) { return null }
+ var parts = [{from: from, to: to}];
+ for (var i = 0; i < markers.length; ++i) {
+ var mk = markers[i], m = mk.find(0);
+ for (var j = 0; j < parts.length; ++j) {
+ var p = parts[j];
+ if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
+ var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
+ if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
+ { newParts.push({from: p.from, to: m.from}); }
+ if (dto > 0 || !mk.inclusiveRight && !dto)
+ { newParts.push({from: m.to, to: p.to}); }
+ parts.splice.apply(parts, newParts);
+ j += newParts.length - 3;
+ }
+ }
+ return parts
+}
+
+// Connect or disconnect spans from a line.
+function detachMarkedSpans(line) {
+ var spans = line.markedSpans;
+ if (!spans) { return }
+ for (var i = 0; i < spans.length; ++i)
+ { spans[i].marker.detachLine(line); }
+ line.markedSpans = null;
+}
+function attachMarkedSpans(line, spans) {
+ if (!spans) { return }
+ for (var i = 0; i < spans.length; ++i)
+ { spans[i].marker.attachLine(line); }
+ line.markedSpans = spans;
+}
+
+// Helpers used when computing which overlapping collapsed span
+// counts as the larger one.
+function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
+function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
+
+// Returns a number indicating which of two overlapping collapsed
+// spans is larger (and thus includes the other). Falls back to
+// comparing ids when the spans cover exactly the same range.
+function compareCollapsedMarkers(a, b) {
+ var lenDiff = a.lines.length - b.lines.length;
+ if (lenDiff != 0) { return lenDiff }
+ var aPos = a.find(), bPos = b.find();
+ var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
+ if (fromCmp) { return -fromCmp }
+ var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
+ if (toCmp) { return toCmp }
+ return b.id - a.id
+}
+
+// Find out whether a line ends or starts in a collapsed span. If
+// so, return the marker for that span.
+function collapsedSpanAtSide(line, start) {
+ var sps = sawCollapsedSpans && line.markedSpans, found;
+ if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0))
+ { found = sp.marker; }
+ } }
+ return found
+}
+function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
+function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
+
+// Test whether there exists a collapsed span that partially
+// overlaps (covers the start or end, but not both) of a new span.
+// Such overlap is not allowed.
+function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
+ var line = getLine(doc, lineNo$$1);
+ var sps = sawCollapsedSpans && line.markedSpans;
+ if (sps) { for (var i = 0; i < sps.length; ++i) {
+ var sp = sps[i];
+ if (!sp.marker.collapsed) { continue }
+ var found = sp.marker.find(0);
+ var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
+ var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
+ if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
+ if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
+ fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
+ { return true }
+ } }
+}
+
+// A visual line is a line as drawn on the screen. Folding, for
+// example, can cause multiple logical lines to appear on the same
+// visual line. This finds the start of the visual line that the
+// given line is part of (usually that is the line itself).
+function visualLine(line) {
+ var merged;
+ while (merged = collapsedSpanAtStart(line))
+ { line = merged.find(-1, true).line; }
+ return line
+}
+
+function visualLineEnd(line) {
+ var merged;
+ while (merged = collapsedSpanAtEnd(line))
+ { line = merged.find(1, true).line; }
+ return line
+}
+
+// Returns an array of logical lines that continue the visual line
+// started by the argument, or undefined if there are no such lines.
+function visualLineContinued(line) {
+ var merged, lines;
+ while (merged = collapsedSpanAtEnd(line)) {
+ line = merged.find(1, true).line
+ ;(lines || (lines = [])).push(line);
+ }
+ return lines
+}
+
+// Get the line number of the start of the visual line that the
+// given line number is part of.
+function visualLineNo(doc, lineN) {
+ var line = getLine(doc, lineN), vis = visualLine(line);
+ if (line == vis) { return lineN }
+ return lineNo(vis)
+}
+
+// Get the line number of the start of the next visual line after
+// the given line.
+function visualLineEndNo(doc, lineN) {
+ if (lineN > doc.lastLine()) { return lineN }
+ var line = getLine(doc, lineN), merged;
+ if (!lineIsHidden(doc, line)) { return lineN }
+ while (merged = collapsedSpanAtEnd(line))
+ { line = merged.find(1, true).line; }
+ return lineNo(line) + 1
+}
+
+// Compute whether a line is hidden. Lines count as hidden when they
+// are part of a visual line that starts with another line, or when
+// they are entirely covered by collapsed, non-widget span.
+function lineIsHidden(doc, line) {
+ var sps = sawCollapsedSpans && line.markedSpans;
+ if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
+ sp = sps[i];
+ if (!sp.marker.collapsed) { continue }
+ if (sp.from == null) { return true }
+ if (sp.marker.widgetNode) { continue }
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
+ { return true }
+ } }
+}
+function lineIsHiddenInner(doc, line, span) {
+ if (span.to == null) {
+ var end = span.marker.find(1, true);
+ return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
+ }
+ if (span.marker.inclusiveRight && span.to == line.text.length)
+ { return true }
+ for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
+ sp = line.markedSpans[i];
+ if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
+ (sp.to == null || sp.to != span.from) &&
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
+ lineIsHiddenInner(doc, line, sp)) { return true }
+ }
+}
+
+// Find the height above the given line.
+function heightAtLine(lineObj) {
+ lineObj = visualLine(lineObj);
+
+ var h = 0, chunk = lineObj.parent;
+ for (var i = 0; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i];
+ if (line == lineObj) { break }
+ else { h += line.height; }
+ }
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
+ for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
+ var cur = p.children[i$1];
+ if (cur == chunk) { break }
+ else { h += cur.height; }
+ }
+ }
+ return h
+}
+
+// Compute the character length of a line, taking into account
+// collapsed ranges (see markText) that might hide parts, and join
+// other lines onto it.
+function lineLength(line) {
+ if (line.height == 0) { return 0 }
+ var len = line.text.length, merged, cur = line;
+ while (merged = collapsedSpanAtStart(cur)) {
+ var found = merged.find(0, true);
+ cur = found.from.line;
+ len += found.from.ch - found.to.ch;
+ }
+ cur = line;
+ while (merged = collapsedSpanAtEnd(cur)) {
+ var found$1 = merged.find(0, true);
+ len -= cur.text.length - found$1.from.ch;
+ cur = found$1.to.line;
+ len += cur.text.length - found$1.to.ch;
+ }
+ return len
+}
+
+// Find the longest line in the document.
+function findMaxLine(cm) {
+ var d = cm.display, doc = cm.doc;
+ d.maxLine = getLine(doc, doc.first);
+ d.maxLineLength = lineLength(d.maxLine);
+ d.maxLineChanged = true;
+ doc.iter(function (line) {
+ var len = lineLength(line);
+ if (len > d.maxLineLength) {
+ d.maxLineLength = len;
+ d.maxLine = line;
+ }
+ });
+}
+
+// BIDI HELPERS
+
+function iterateBidiSections(order, from, to, f) {
+ if (!order) { return f(from, to, "ltr", 0) }
+ var found = false;
+ for (var i = 0; i < order.length; ++i) {
+ var part = order[i];
+ if (part.from < to && part.to > from || from == to && part.to == from) {
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
+ found = true;
+ }
+ }
+ if (!found) { f(from, to, "ltr"); }
+}
+
+var bidiOther = null;
+function getBidiPartAt(order, ch, sticky) {
+ var found;
+ bidiOther = null;
+ for (var i = 0; i < order.length; ++i) {
+ var cur = order[i];
+ if (cur.from < ch && cur.to > ch) { return i }
+ if (cur.to == ch) {
+ if (cur.from != cur.to && sticky == "before") { found = i; }
+ else { bidiOther = i; }
+ }
+ if (cur.from == ch) {
+ if (cur.from != cur.to && sticky != "before") { found = i; }
+ else { bidiOther = i; }
+ }
+ }
+ return found != null ? found : bidiOther
+}
+
+// Bidirectional ordering algorithm
+// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
+// that this (partially) implements.
+
+// One-char codes used for character types:
+// L (L): Left-to-Right
+// R (R): Right-to-Left
+// r (AL): Right-to-Left Arabic
+// 1 (EN): European Number
+// + (ES): European Number Separator
+// % (ET): European Number Terminator
+// n (AN): Arabic Number
+// , (CS): Common Number Separator
+// m (NSM): Non-Spacing Mark
+// b (BN): Boundary Neutral
+// s (B): Paragraph Separator
+// t (S): Segment Separator
+// w (WS): Whitespace
+// N (ON): Other Neutrals
+
+// Returns null if characters are ordered as they appear
+// (left-to-right), or an array of sections ({from, to, level}
+// objects) in the order in which they occur visually.
+var bidiOrdering = (function() {
+ // Character types for codepoints 0 to 0xff
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
+ // Character types for codepoints 0x600 to 0x6f9
+ var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
+ function charType(code) {
+ if (code <= 0xf7) { return lowTypes.charAt(code) }
+ else if (0x590 <= code && code <= 0x5f4) { return "R" }
+ else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
+ else if (0x6ee <= code && code <= 0x8ac) { return "r" }
+ else if (0x2000 <= code && code <= 0x200b) { return "w" }
+ else if (code == 0x200c) { return "b" }
+ else { return "L" }
+ }
+
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
+
+ function BidiSpan(level, from, to) {
+ this.level = level;
+ this.from = from; this.to = to;
+ }
+
+ return function(str, direction) {
+ var outerType = direction == "ltr" ? "L" : "R";
+
+ if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
+ var len = str.length, types = [];
+ for (var i = 0; i < len; ++i)
+ { types.push(charType(str.charCodeAt(i))); }
+
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
+ // change the type of the NSM to the type of the previous
+ // character. If the NSM is at the start of the level run, it will
+ // get the type of sor.
+ for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
+ var type = types[i$1];
+ if (type == "m") { types[i$1] = prev; }
+ else { prev = type; }
+ }
+
+ // W2. Search backwards from each instance of a European number
+ // until the first strong type (R, L, AL, or sor) is found. If an
+ // AL is found, change the type of the European number to Arabic
+ // number.
+ // W3. Change all ALs to R.
+ for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
+ var type$1 = types[i$2];
+ if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
+ else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
+ }
+
+ // W4. A single European separator between two European numbers
+ // changes to a European number. A single common separator between
+ // two numbers of the same type changes to that type.
+ for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
+ var type$2 = types[i$3];
+ if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
+ else if (type$2 == "," && prev$1 == types[i$3+1] &&
+ (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
+ prev$1 = type$2;
+ }
+
+ // W5. A sequence of European terminators adjacent to European
+ // numbers changes to all European numbers.
+ // W6. Otherwise, separators and terminators change to Other
+ // Neutral.
+ for (var i$4 = 0; i$4 < len; ++i$4) {
+ var type$3 = types[i$4];
+ if (type$3 == ",") { types[i$4] = "N"; }
+ else if (type$3 == "%") {
+ var end = (void 0);
+ for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
+ var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
+ for (var j = i$4; j < end; ++j) { types[j] = replace; }
+ i$4 = end - 1;
+ }
+ }
+
+ // W7. Search backwards from each instance of a European number
+ // until the first strong type (R, L, or sor) is found. If an L is
+ // found, then change the type of the European number to L.
+ for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
+ var type$4 = types[i$5];
+ if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
+ else if (isStrong.test(type$4)) { cur$1 = type$4; }
+ }
+
+ // N1. A sequence of neutrals takes the direction of the
+ // surrounding strong text if the text on both sides has the same
+ // direction. European and Arabic numbers act as if they were R in
+ // terms of their influence on neutrals. Start-of-level-run (sor)
+ // and end-of-level-run (eor) are used at level run boundaries.
+ // N2. Any remaining neutrals take the embedding direction.
+ for (var i$6 = 0; i$6 < len; ++i$6) {
+ if (isNeutral.test(types[i$6])) {
+ var end$1 = (void 0);
+ for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
+ var before = (i$6 ? types[i$6-1] : outerType) == "L";
+ var after = (end$1 < len ? types[end$1] : outerType) == "L";
+ var replace$1 = before == after ? (before ? "L" : "R") : outerType;
+ for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
+ i$6 = end$1 - 1;
+ }
+ }
+
+ // Here we depart from the documented algorithm, in order to avoid
+ // building up an actual levels array. Since there are only three
+ // levels (0, 1, 2) in an implementation that doesn't take
+ // explicit embedding into account, we can build up the order on
+ // the fly, without following the level-based algorithm.
+ var order = [], m;
+ for (var i$7 = 0; i$7 < len;) {
+ if (countsAsLeft.test(types[i$7])) {
+ var start = i$7;
+ for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
+ order.push(new BidiSpan(0, start, i$7));
+ } else {
+ var pos = i$7, at = order.length;
+ for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
+ for (var j$2 = pos; j$2 < i$7;) {
+ if (countsAsNum.test(types[j$2])) {
+ if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
+ var nstart = j$2;
+ for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
+ order.splice(at, 0, new BidiSpan(2, nstart, j$2));
+ pos = j$2;
+ } else { ++j$2; }
+ }
+ if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
+ }
+ }
+ if (direction == "ltr") {
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
+ order[0].from = m[0].length;
+ order.unshift(new BidiSpan(0, 0, m[0].length));
+ }
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
+ lst(order).to -= m[0].length;
+ order.push(new BidiSpan(0, len - m[0].length, len));
+ }
+ }
+
+ return direction == "rtl" ? order.reverse() : order
+ }
+})();
+
+// Get the bidi ordering for the given line (and cache it). Returns
+// false for lines that are fully left-to-right, and an array of
+// BidiSpan objects otherwise.
+function getOrder(line, direction) {
+ var order = line.order;
+ if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
+ return order
+}
+
+// EVENT HANDLING
+
+// Lightweight event framework. on/off also work on DOM nodes,
+// registering native DOM handlers.
+
+var noHandlers = [];
+
+var on = function(emitter, type, f) {
+ if (emitter.addEventListener) {
+ emitter.addEventListener(type, f, false);
+ } else if (emitter.attachEvent) {
+ emitter.attachEvent("on" + type, f);
+ } else {
+ var map$$1 = emitter._handlers || (emitter._handlers = {});
+ map$$1[type] = (map$$1[type] || noHandlers).concat(f);
+ }
+};
+
+function getHandlers(emitter, type) {
+ return emitter._handlers && emitter._handlers[type] || noHandlers
+}
+
+function off(emitter, type, f) {
+ if (emitter.removeEventListener) {
+ emitter.removeEventListener(type, f, false);
+ } else if (emitter.detachEvent) {
+ emitter.detachEvent("on" + type, f);
+ } else {
+ var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
+ if (arr) {
+ var index = indexOf(arr, f);
+ if (index > -1)
+ { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
+ }
+ }
+}
+
+function signal(emitter, type /*, values...*/) {
+ var handlers = getHandlers(emitter, type);
+ if (!handlers.length) { return }
+ var args = Array.prototype.slice.call(arguments, 2);
+ for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
+}
+
+// The DOM events that CodeMirror handles can be overridden by
+// registering a (non-DOM) handler on the editor for the event name,
+// and preventDefault-ing the event in that handler.
+function signalDOMEvent(cm, e, override) {
+ if (typeof e == "string")
+ { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
+ signal(cm, override || e.type, cm, e);
+ return e_defaultPrevented(e) || e.codemirrorIgnore
+}
+
+function signalCursorActivity(cm) {
+ var arr = cm._handlers && cm._handlers.cursorActivity;
+ if (!arr) { return }
+ var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
+ for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
+ { set.push(arr[i]); } }
+}
+
+function hasHandler(emitter, type) {
+ return getHandlers(emitter, type).length > 0
+}
+
+// Add on and off methods to a constructor's prototype, to make
+// registering events on such objects more convenient.
+function eventMixin(ctor) {
+ ctor.prototype.on = function(type, f) {on(this, type, f);};
+ ctor.prototype.off = function(type, f) {off(this, type, f);};
+}
+
+// Due to the fact that we still support jurassic IE versions, some
+// compatibility wrappers are needed.
+
+function e_preventDefault(e) {
+ if (e.preventDefault) { e.preventDefault(); }
+ else { e.returnValue = false; }
+}
+function e_stopPropagation(e) {
+ if (e.stopPropagation) { e.stopPropagation(); }
+ else { e.cancelBubble = true; }
+}
+function e_defaultPrevented(e) {
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
+}
+function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
+
+function e_target(e) {return e.target || e.srcElement}
+function e_button(e) {
+ var b = e.which;
+ if (b == null) {
+ if (e.button & 1) { b = 1; }
+ else if (e.button & 2) { b = 3; }
+ else if (e.button & 4) { b = 2; }
+ }
+ if (mac && e.ctrlKey && b == 1) { b = 3; }
+ return b
+}
+
+// Detect drag-and-drop
+var dragAndDrop = function() {
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
+ // couldn't get it to work yet.
+ if (ie && ie_version < 9) { return false }
+ var div = elt('div');
+ return "draggable" in div || "dragDrop" in div
+}();
+
+var zwspSupported;
+function zeroWidthElement(measure) {
+ if (zwspSupported == null) {
+ var test = elt("span", "\u200b");
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
+ if (measure.firstChild.offsetHeight != 0)
+ { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
+ }
+ var node = zwspSupported ? elt("span", "\u200b") :
+ elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
+ node.setAttribute("cm-text", "");
+ return node
+}
+
+// Feature-detect IE's crummy client rect reporting for bidi text
+var badBidiRects;
+function hasBadBidiRects(measure) {
+ if (badBidiRects != null) { return badBidiRects }
+ var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
+ var r0 = range(txt, 0, 1).getBoundingClientRect();
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
+ removeChildren(measure);
+ if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
+ return badBidiRects = (r1.right - r0.right < 3)
+}
+
+// See if "".split is the broken IE version, if so, provide an
+// alternative way to split lines.
+var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
+ var pos = 0, result = [], l = string.length;
+ while (pos <= l) {
+ var nl = string.indexOf("\n", pos);
+ if (nl == -1) { nl = string.length; }
+ var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
+ var rt = line.indexOf("\r");
+ if (rt != -1) {
+ result.push(line.slice(0, rt));
+ pos += rt + 1;
+ } else {
+ result.push(line);
+ pos = nl + 1;
+ }
+ }
+ return result
+} : function (string) { return string.split(/\r\n?|\n/); };
+
+var hasSelection = window.getSelection ? function (te) {
+ try { return te.selectionStart != te.selectionEnd }
+ catch(e) { return false }
+} : function (te) {
+ var range$$1;
+ try {range$$1 = te.ownerDocument.selection.createRange();}
+ catch(e) {}
+ if (!range$$1 || range$$1.parentElement() != te) { return false }
+ return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
+};
+
+var hasCopyEvent = (function () {
+ var e = elt("div");
+ if ("oncopy" in e) { return true }
+ e.setAttribute("oncopy", "return;");
+ return typeof e.oncopy == "function"
+})();
+
+var badZoomedRects = null;
+function hasBadZoomedRects(measure) {
+ if (badZoomedRects != null) { return badZoomedRects }
+ var node = removeChildrenAndAdd(measure, elt("span", "x"));
+ var normal = node.getBoundingClientRect();
+ var fromRange = range(node, 0, 1).getBoundingClientRect();
+ return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
+}
+
+// Known modes, by name and by MIME
+var modes = {};
+var mimeModes = {};
+
+// Extra arguments are stored as the mode's dependencies, which is
+// used by (legacy) mechanisms like loadmode.js to automatically
+// load a mode. (Preferred mechanism is the require/define calls.)
+function defineMode(name, mode) {
+ if (arguments.length > 2)
+ { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
+ modes[name] = mode;
+}
+
+function defineMIME(mime, spec) {
+ mimeModes[mime] = spec;
+}
+
+// Given a MIME type, a {name, ...options} config object, or a name
+// string, return a mode config object.
+function resolveMode(spec) {
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
+ spec = mimeModes[spec];
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
+ var found = mimeModes[spec.name];
+ if (typeof found == "string") { found = {name: found}; }
+ spec = createObj(found, spec);
+ spec.name = found.name;
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
+ return resolveMode("application/xml")
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
+ return resolveMode("application/json")
+ }
+ if (typeof spec == "string") { return {name: spec} }
+ else { return spec || {name: "null"} }
+}
+
+// Given a mode spec (anything that resolveMode accepts), find and
+// initialize an actual mode object.
+function getMode(options, spec) {
+ spec = resolveMode(spec);
+ var mfactory = modes[spec.name];
+ if (!mfactory) { return getMode(options, "text/plain") }
+ var modeObj = mfactory(options, spec);
+ if (modeExtensions.hasOwnProperty(spec.name)) {
+ var exts = modeExtensions[spec.name];
+ for (var prop in exts) {
+ if (!exts.hasOwnProperty(prop)) { continue }
+ if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
+ modeObj[prop] = exts[prop];
+ }
+ }
+ modeObj.name = spec.name;
+ if (spec.helperType) { modeObj.helperType = spec.helperType; }
+ if (spec.modeProps) { for (var prop$1 in spec.modeProps)
+ { modeObj[prop$1] = spec.modeProps[prop$1]; } }
+
+ return modeObj
+}
+
+// This can be used to attach properties to mode objects from
+// outside the actual mode definition.
+var modeExtensions = {};
+function extendMode(mode, properties) {
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
+ copyObj(properties, exts);
+}
+
+function copyState(mode, state) {
+ if (state === true) { return state }
+ if (mode.copyState) { return mode.copyState(state) }
+ var nstate = {};
+ for (var n in state) {
+ var val = state[n];
+ if (val instanceof Array) { val = val.concat([]); }
+ nstate[n] = val;
+ }
+ return nstate
+}
+
+// Given a mode and a state (for that mode), find the inner mode and
+// state at the position that the state refers to.
+function innerMode(mode, state) {
+ var info;
+ while (mode.innerMode) {
+ info = mode.innerMode(state);
+ if (!info || info.mode == mode) { break }
+ state = info.state;
+ mode = info.mode;
+ }
+ return info || {mode: mode, state: state}
+}
+
+function startState(mode, a1, a2) {
+ return mode.startState ? mode.startState(a1, a2) : true
+}
+
+// STRING STREAM
+
+// Fed to the mode parsers, provides helper functions to make
+// parsers more succinct.
+
+var StringStream = function(string, tabSize, lineOracle) {
+ this.pos = this.start = 0;
+ this.string = string;
+ this.tabSize = tabSize || 8;
+ this.lastColumnPos = this.lastColumnValue = 0;
+ this.lineStart = 0;
+ this.lineOracle = lineOracle;
+};
+
+StringStream.prototype.eol = function () {return this.pos >= this.string.length};
+StringStream.prototype.sol = function () {return this.pos == this.lineStart};
+StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
+StringStream.prototype.next = function () {
+ if (this.pos < this.string.length)
+ { return this.string.charAt(this.pos++) }
+};
+StringStream.prototype.eat = function (match) {
+ var ch = this.string.charAt(this.pos);
+ var ok;
+ if (typeof match == "string") { ok = ch == match; }
+ else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
+ if (ok) {++this.pos; return ch}
+};
+StringStream.prototype.eatWhile = function (match) {
+ var start = this.pos;
+ while (this.eat(match)){}
+ return this.pos > start
+};
+StringStream.prototype.eatSpace = function () {
+ var this$1 = this;
+
+ var start = this.pos;
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
+ return this.pos > start
+};
+StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
+StringStream.prototype.skipTo = function (ch) {
+ var found = this.string.indexOf(ch, this.pos);
+ if (found > -1) {this.pos = found; return true}
+};
+StringStream.prototype.backUp = function (n) {this.pos -= n;};
+StringStream.prototype.column = function () {
+ if (this.lastColumnPos < this.start) {
+ this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
+ this.lastColumnPos = this.start;
+ }
+ return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
+};
+StringStream.prototype.indentation = function () {
+ return countColumn(this.string, null, this.tabSize) -
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
+};
+StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
+ if (typeof pattern == "string") {
+ var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
+ var substr = this.string.substr(this.pos, pattern.length);
+ if (cased(substr) == cased(pattern)) {
+ if (consume !== false) { this.pos += pattern.length; }
+ return true
+ }
+ } else {
+ var match = this.string.slice(this.pos).match(pattern);
+ if (match && match.index > 0) { return null }
+ if (match && consume !== false) { this.pos += match[0].length; }
+ return match
+ }
+};
+StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
+StringStream.prototype.hideFirstChars = function (n, inner) {
+ this.lineStart += n;
+ try { return inner() }
+ finally { this.lineStart -= n; }
+};
+StringStream.prototype.lookAhead = function (n) {
+ var oracle = this.lineOracle;
+ return oracle && oracle.lookAhead(n)
+};
+StringStream.prototype.baseToken = function () {
+ var oracle = this.lineOracle;
+ return oracle && oracle.baseToken(this.pos)
+};
+
+var SavedContext = function(state, lookAhead) {
+ this.state = state;
+ this.lookAhead = lookAhead;
+};
+
+var Context = function(doc, state, line, lookAhead) {
+ this.state = state;
+ this.doc = doc;
+ this.line = line;
+ this.maxLookAhead = lookAhead || 0;
+ this.baseTokens = null;
+ this.baseTokenPos = 1;
+};
+
+Context.prototype.lookAhead = function (n) {
+ var line = this.doc.getLine(this.line + n);
+ if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
+ return line
+};
+
+Context.prototype.baseToken = function (n) {
+ var this$1 = this;
+
+ if (!this.baseTokens) { return null }
+ while (this.baseTokens[this.baseTokenPos] <= n)
+ { this$1.baseTokenPos += 2; }
+ var type = this.baseTokens[this.baseTokenPos + 1];
+ return {type: type && type.replace(/( |^)overlay .*/, ""),
+ size: this.baseTokens[this.baseTokenPos] - n}
+};
+
+Context.prototype.nextLine = function () {
+ this.line++;
+ if (this.maxLookAhead > 0) { this.maxLookAhead--; }
+};
+
+Context.fromSaved = function (doc, saved, line) {
+ if (saved instanceof SavedContext)
+ { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
+ else
+ { return new Context(doc, copyState(doc.mode, saved), line) }
+};
+
+Context.prototype.save = function (copy) {
+ var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
+ return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
+};
+
+
+// Compute a style array (an array starting with a mode generation
+// -- for invalidation -- followed by pairs of end positions and
+// style strings), which is used to highlight the tokens on the
+// line.
+function highlightLine(cm, line, context, forceToEnd) {
+ // A styles array always starts with a number identifying the
+ // mode/overlays that it is based on (for easy invalidation).
+ var st = [cm.state.modeGen], lineClasses = {};
+ // Compute the base array of styles
+ runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
+ lineClasses, forceToEnd);
+ var state = context.state;
+
+ // Run overlays, adjust style array.
+ var loop = function ( o ) {
+ context.baseTokens = st;
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
+ context.state = true;
+ runMode(cm, line.text, overlay.mode, context, function (end, style) {
+ var start = i;
+ // Ensure there's a token end at the current position, and that i points at it
+ while (at < end) {
+ var i_end = st[i];
+ if (i_end > end)
+ { st.splice(i, 1, end, st[i+1], i_end); }
+ i += 2;
+ at = Math.min(end, i_end);
+ }
+ if (!style) { return }
+ if (overlay.opaque) {
+ st.splice(start, i - start, end, "overlay " + style);
+ i = start + 2;
+ } else {
+ for (; start < i; start += 2) {
+ var cur = st[start+1];
+ st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
+ }
+ }
+ }, lineClasses);
+ context.state = state;
+ context.baseTokens = null;
+ context.baseTokenPos = 1;
+ };
+
+ for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
+
+ return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
+}
+
+function getLineStyles(cm, line, updateFrontier) {
+ if (!line.styles || line.styles[0] != cm.state.modeGen) {
+ var context = getContextBefore(cm, lineNo(line));
+ var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
+ var result = highlightLine(cm, line, context);
+ if (resetState) { context.state = resetState; }
+ line.stateAfter = context.save(!resetState);
+ line.styles = result.styles;
+ if (result.classes) { line.styleClasses = result.classes; }
+ else if (line.styleClasses) { line.styleClasses = null; }
+ if (updateFrontier === cm.doc.highlightFrontier)
+ { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
+ }
+ return line.styles
+}
+
+function getContextBefore(cm, n, precise) {
+ var doc = cm.doc, display = cm.display;
+ if (!doc.mode.startState) { return new Context(doc, true, n) }
+ var start = findStartLine(cm, n, precise);
+ var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
+ var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
+
+ doc.iter(start, n, function (line) {
+ processLine(cm, line.text, context);
+ var pos = context.line;
+ line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
+ context.nextLine();
+ });
+ if (precise) { doc.modeFrontier = context.line; }
+ return context
+}
+
+// Lightweight form of highlight -- proceed over this line and
+// update state, but don't save a style array. Used for lines that
+// aren't currently visible.
+function processLine(cm, text, context, startAt) {
+ var mode = cm.doc.mode;
+ var stream = new StringStream(text, cm.options.tabSize, context);
+ stream.start = stream.pos = startAt || 0;
+ if (text == "") { callBlankLine(mode, context.state); }
+ while (!stream.eol()) {
+ readToken(mode, stream, context.state);
+ stream.start = stream.pos;
+ }
+}
+
+function callBlankLine(mode, state) {
+ if (mode.blankLine) { return mode.blankLine(state) }
+ if (!mode.innerMode) { return }
+ var inner = innerMode(mode, state);
+ if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
+}
+
+function readToken(mode, stream, state, inner) {
+ for (var i = 0; i < 10; i++) {
+ if (inner) { inner[0] = innerMode(mode, state).mode; }
+ var style = mode.token(stream, state);
+ if (stream.pos > stream.start) { return style }
+ }
+ throw new Error("Mode " + mode.name + " failed to advance stream.")
+}
+
+var Token = function(stream, type, state) {
+ this.start = stream.start; this.end = stream.pos;
+ this.string = stream.current();
+ this.type = type || null;
+ this.state = state;
+};
+
+// Utility for getTokenAt and getLineTokens
+function takeToken(cm, pos, precise, asArray) {
+ var doc = cm.doc, mode = doc.mode, style;
+ pos = clipPos(doc, pos);
+ var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
+ var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
+ if (asArray) { tokens = []; }
+ while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
+ stream.start = stream.pos;
+ style = readToken(mode, stream, context.state);
+ if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
+ }
+ return asArray ? tokens : new Token(stream, style, context.state)
+}
+
+function extractLineClasses(type, output) {
+ if (type) { for (;;) {
+ var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
+ if (!lineClass) { break }
+ type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
+ var prop = lineClass[1] ? "bgClass" : "textClass";
+ if (output[prop] == null)
+ { output[prop] = lineClass[2]; }
+ else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
+ { output[prop] += " " + lineClass[2]; }
+ } }
+ return type
+}
+
+// Run the given mode's parser over a line, calling f for each token.
+function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
+ var flattenSpans = mode.flattenSpans;
+ if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
+ var curStart = 0, curStyle = null;
+ var stream = new StringStream(text, cm.options.tabSize, context), style;
+ var inner = cm.options.addModeClass && [null];
+ if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
+ while (!stream.eol()) {
+ if (stream.pos > cm.options.maxHighlightLength) {
+ flattenSpans = false;
+ if (forceToEnd) { processLine(cm, text, context, stream.pos); }
+ stream.pos = text.length;
+ style = null;
+ } else {
+ style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
+ }
+ if (inner) {
+ var mName = inner[0].name;
+ if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
+ }
+ if (!flattenSpans || curStyle != style) {
+ while (curStart < stream.start) {
+ curStart = Math.min(stream.start, curStart + 5000);
+ f(curStart, curStyle);
+ }
+ curStyle = style;
+ }
+ stream.start = stream.pos;
+ }
+ while (curStart < stream.pos) {
+ // Webkit seems to refuse to render text nodes longer than 57444
+ // characters, and returns inaccurate measurements in nodes
+ // starting around 5000 chars.
+ var pos = Math.min(stream.pos, curStart + 5000);
+ f(pos, curStyle);
+ curStart = pos;
+ }
+}
+
+// Finds the line to start with when starting a parse. Tries to
+// find a line with a stateAfter, so that it can start with a
+// valid state. If that fails, it returns the line with the
+// smallest indentation, which tends to need the least context to
+// parse correctly.
+function findStartLine(cm, n, precise) {
+ var minindent, minline, doc = cm.doc;
+ var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
+ for (var search = n; search > lim; --search) {
+ if (search <= doc.first) { return doc.first }
+ var line = getLine(doc, search - 1), after = line.stateAfter;
+ if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
+ { return search }
+ var indented = countColumn(line.text, null, cm.options.tabSize);
+ if (minline == null || minindent > indented) {
+ minline = search - 1;
+ minindent = indented;
+ }
+ }
+ return minline
+}
+
+function retreatFrontier(doc, n) {
+ doc.modeFrontier = Math.min(doc.modeFrontier, n);
+ if (doc.highlightFrontier < n - 10) { return }
+ var start = doc.first;
+ for (var line = n - 1; line > start; line--) {
+ var saved = getLine(doc, line).stateAfter;
+ // change is on 3
+ // state on line 1 looked ahead 2 -- so saw 3
+ // test 1 + 2 < 3 should cover this
+ if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
+ start = line + 1;
+ break
+ }
+ }
+ doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
+}
+
+// LINE DATA STRUCTURE
+
+// Line objects. These hold state related to a line, including
+// highlighting info (the styles array).
+var Line = function(text, markedSpans, estimateHeight) {
+ this.text = text;
+ attachMarkedSpans(this, markedSpans);
+ this.height = estimateHeight ? estimateHeight(this) : 1;
+};
+
+Line.prototype.lineNo = function () { return lineNo(this) };
+eventMixin(Line);
+
+// Change the content (text, markers) of a line. Automatically
+// invalidates cached information and tries to re-estimate the
+// line's height.
+function updateLine(line, text, markedSpans, estimateHeight) {
+ line.text = text;
+ if (line.stateAfter) { line.stateAfter = null; }
+ if (line.styles) { line.styles = null; }
+ if (line.order != null) { line.order = null; }
+ detachMarkedSpans(line);
+ attachMarkedSpans(line, markedSpans);
+ var estHeight = estimateHeight ? estimateHeight(line) : 1;
+ if (estHeight != line.height) { updateLineHeight(line, estHeight); }
+}
+
+// Detach a line from the document tree and its markers.
+function cleanUpLine(line) {
+ line.parent = null;
+ detachMarkedSpans(line);
+}
+
+// Convert a style as returned by a mode (either null, or a string
+// containing one or more styles) to a CSS style. This is cached,
+// and also looks for line-wide styles.
+var styleToClassCache = {};
+var styleToClassCacheWithMode = {};
+function interpretTokenStyle(style, options) {
+ if (!style || /^\s*$/.test(style)) { return null }
+ var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
+ return cache[style] ||
+ (cache[style] = style.replace(/\S+/g, "cm-$&"))
+}
+
+// Render the DOM representation of the text of a line. Also builds
+// up a 'line map', which points at the DOM nodes that represent
+// specific stretches of text, and is used by the measuring code.
+// The returned object contains the DOM node, this map, and
+// information about line-wide styles that were set by the mode.
+function buildLineContent(cm, lineView) {
+ // The padding-right forces the element to have a 'border', which
+ // is needed on Webkit to be able to get line-level bounding
+ // rectangles for it (in measureChar).
+ var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
+ var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
+ col: 0, pos: 0, cm: cm,
+ trailingSpace: false,
+ splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
+ lineView.measure = {};
+
+ // Iterate over the logical lines that make up this visual line.
+ for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
+ var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
+ builder.pos = 0;
+ builder.addToken = buildToken;
+ // Optionally wire in some hacks into the token-rendering
+ // algorithm, to deal with browser quirks.
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
+ { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
+ builder.map = [];
+ var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
+ insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
+ if (line.styleClasses) {
+ if (line.styleClasses.bgClass)
+ { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
+ if (line.styleClasses.textClass)
+ { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
+ }
+
+ // Ensure at least a single node is present, for measuring.
+ if (builder.map.length == 0)
+ { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
+
+ // Store the map and a cache object for the current logical line
+ if (i == 0) {
+ lineView.measure.map = builder.map;
+ lineView.measure.cache = {};
+ } else {
+ (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
+ ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
+ }
+ }
+
+ // See issue #2901
+ if (webkit) {
+ var last = builder.content.lastChild;
+ if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
+ { builder.content.className = "cm-tab-wrap-hack"; }
+ }
+
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
+ if (builder.pre.className)
+ { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
+
+ return builder
+}
+
+function defaultSpecialCharPlaceholder(ch) {
+ var token = elt("span", "\u2022", "cm-invalidchar");
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
+ token.setAttribute("aria-label", token.title);
+ return token
+}
+
+// Build up the DOM representation for a single token, and add it to
+// the line map. Takes care to render special characters separately.
+function buildToken(builder, text, style, startStyle, endStyle, title, css) {
+ if (!text) { return }
+ var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
+ var special = builder.cm.state.specialChars, mustWrap = false;
+ var content;
+ if (!special.test(text)) {
+ builder.col += text.length;
+ content = document.createTextNode(displayText);
+ builder.map.push(builder.pos, builder.pos + text.length, content);
+ if (ie && ie_version < 9) { mustWrap = true; }
+ builder.pos += text.length;
+ } else {
+ content = document.createDocumentFragment();
+ var pos = 0;
+ while (true) {
+ special.lastIndex = pos;
+ var m = special.exec(text);
+ var skipped = m ? m.index - pos : text.length - pos;
+ if (skipped) {
+ var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
+ if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
+ else { content.appendChild(txt); }
+ builder.map.push(builder.pos, builder.pos + skipped, txt);
+ builder.col += skipped;
+ builder.pos += skipped;
+ }
+ if (!m) { break }
+ pos += skipped + 1;
+ var txt$1 = (void 0);
+ if (m[0] == "\t") {
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
+ txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
+ txt$1.setAttribute("role", "presentation");
+ txt$1.setAttribute("cm-text", "\t");
+ builder.col += tabWidth;
+ } else if (m[0] == "\r" || m[0] == "\n") {
+ txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
+ txt$1.setAttribute("cm-text", m[0]);
+ builder.col += 1;
+ } else {
+ txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
+ txt$1.setAttribute("cm-text", m[0]);
+ if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
+ else { content.appendChild(txt$1); }
+ builder.col += 1;
+ }
+ builder.map.push(builder.pos, builder.pos + 1, txt$1);
+ builder.pos++;
+ }
+ }
+ builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
+ if (style || startStyle || endStyle || mustWrap || css) {
+ var fullStyle = style || "";
+ if (startStyle) { fullStyle += startStyle; }
+ if (endStyle) { fullStyle += endStyle; }
+ var token = elt("span", [content], fullStyle, css);
+ if (title) { token.title = title; }
+ return builder.content.appendChild(token)
+ }
+ builder.content.appendChild(content);
+}
+
+function splitSpaces(text, trailingBefore) {
+ if (text.length > 1 && !/ /.test(text)) { return text }
+ var spaceBefore = trailingBefore, result = "";
+ for (var i = 0; i < text.length; i++) {
+ var ch = text.charAt(i);
+ if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
+ { ch = "\u00a0"; }
+ result += ch;
+ spaceBefore = ch == " ";
+ }
+ return result
+}
+
+// Work around nonsense dimensions being reported for stretches of
+// right-to-left text.
+function buildTokenBadBidi(inner, order) {
+ return function (builder, text, style, startStyle, endStyle, title, css) {
+ style = style ? style + " cm-force-border" : "cm-force-border";
+ var start = builder.pos, end = start + text.length;
+ for (;;) {
+ // Find the part that overlaps with the start of this text
+ var part = (void 0);
+ for (var i = 0; i < order.length; i++) {
+ part = order[i];
+ if (part.to > start && part.from <= start) { break }
+ }
+ if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
+ startStyle = null;
+ text = text.slice(part.to - start);
+ start = part.to;
+ }
+ }
+}
+
+function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
+ var widget = !ignoreWidget && marker.widgetNode;
+ if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
+ if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
+ if (!widget)
+ { widget = builder.content.appendChild(document.createElement("span")); }
+ widget.setAttribute("cm-marker", marker.id);
+ }
+ if (widget) {
+ builder.cm.display.input.setUneditable(widget);
+ builder.content.appendChild(widget);
+ }
+ builder.pos += size;
+ builder.trailingSpace = false;
+}
+
+// Outputs a number of spans to make up a line, taking highlighting
+// and marked text into account.
+function insertLineContent(line, builder, styles) {
+ var spans = line.markedSpans, allText = line.text, at = 0;
+ if (!spans) {
+ for (var i$1 = 1; i$1 < styles.length; i$1+=2)
+ { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
+ return
+ }
+
+ var len = allText.length, pos = 0, i = 1, text = "", style, css;
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
+ for (;;) {
+ if (nextChange == pos) { // Update current marker set
+ spanStyle = spanEndStyle = spanStartStyle = title = css = "";
+ collapsed = null; nextChange = Infinity;
+ var foundBookmarks = [], endStyles = (void 0);
+ for (var j = 0; j < spans.length; ++j) {
+ var sp = spans[j], m = sp.marker;
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
+ foundBookmarks.push(m);
+ } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
+ if (sp.to != null && sp.to != pos && nextChange > sp.to) {
+ nextChange = sp.to;
+ spanEndStyle = "";
+ }
+ if (m.className) { spanStyle += " " + m.className; }
+ if (m.css) { css = (css ? css + ";" : "") + m.css; }
+ if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
+ if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
+ if (m.title && !title) { title = m.title; }
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
+ { collapsed = sp; }
+ } else if (sp.from > pos && nextChange > sp.from) {
+ nextChange = sp.from;
+ }
+ }
+ if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
+ { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
+
+ if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
+ { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
+ if (collapsed && (collapsed.from || 0) == pos) {
+ buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
+ collapsed.marker, collapsed.from == null);
+ if (collapsed.to == null) { return }
+ if (collapsed.to == pos) { collapsed = false; }
+ }
+ }
+ if (pos >= len) { break }
+
+ var upto = Math.min(len, nextChange);
+ while (true) {
+ if (text) {
+ var end = pos + text.length;
+ if (!collapsed) {
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
+ builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
+ }
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
+ pos = end;
+ spanStartStyle = "";
+ }
+ text = allText.slice(at, at = styles[i++]);
+ style = interpretTokenStyle(styles[i++], builder.cm.options);
+ }
+ }
+}
+
+
+// These objects are used to represent the visible (currently drawn)
+// part of the document. A LineView may correspond to multiple
+// logical lines, if those are connected by collapsed ranges.
+function LineView(doc, line, lineN) {
+ // The starting line
+ this.line = line;
+ // Continuing lines, if any
+ this.rest = visualLineContinued(line);
+ // Number of logical lines in this visual line
+ this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
+ this.node = this.text = null;
+ this.hidden = lineIsHidden(doc, line);
+}
+
+// Create a range of LineView objects for the given lines.
+function buildViewArray(cm, from, to) {
+ var array = [], nextPos;
+ for (var pos = from; pos < to; pos = nextPos) {
+ var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
+ nextPos = pos + view.size;
+ array.push(view);
+ }
+ return array
+}
+
+var operationGroup = null;
+
+function pushOperation(op) {
+ if (operationGroup) {
+ operationGroup.ops.push(op);
+ } else {
+ op.ownsGroup = operationGroup = {
+ ops: [op],
+ delayedCallbacks: []
+ };
+ }
+}
+
+function fireCallbacksForOps(group) {
+ // Calls delayed callbacks and cursorActivity handlers until no
+ // new ones appear
+ var callbacks = group.delayedCallbacks, i = 0;
+ do {
+ for (; i < callbacks.length; i++)
+ { callbacks[i].call(null); }
+ for (var j = 0; j < group.ops.length; j++) {
+ var op = group.ops[j];
+ if (op.cursorActivityHandlers)
+ { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
+ { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
+ }
+ } while (i < callbacks.length)
+}
+
+function finishOperation(op, endCb) {
+ var group = op.ownsGroup;
+ if (!group) { return }
+
+ try { fireCallbacksForOps(group); }
+ finally {
+ operationGroup = null;
+ endCb(group);
+ }
+}
+
+var orphanDelayedCallbacks = null;
+
+// Often, we want to signal events at a point where we are in the
+// middle of some work, but don't want the handler to start calling
+// other methods on the editor, which might be in an inconsistent
+// state or simply not expect any other events to happen.
+// signalLater looks whether there are any handlers, and schedules
+// them to be executed when the last operation ends, or, if no
+// operation is active, when a timeout fires.
+function signalLater(emitter, type /*, values...*/) {
+ var arr = getHandlers(emitter, type);
+ if (!arr.length) { return }
+ var args = Array.prototype.slice.call(arguments, 2), list;
+ if (operationGroup) {
+ list = operationGroup.delayedCallbacks;
+ } else if (orphanDelayedCallbacks) {
+ list = orphanDelayedCallbacks;
+ } else {
+ list = orphanDelayedCallbacks = [];
+ setTimeout(fireOrphanDelayed, 0);
+ }
+ var loop = function ( i ) {
+ list.push(function () { return arr[i].apply(null, args); });
+ };
+
+ for (var i = 0; i < arr.length; ++i)
+ loop( i );
+}
+
+function fireOrphanDelayed() {
+ var delayed = orphanDelayedCallbacks;
+ orphanDelayedCallbacks = null;
+ for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
+}
+
+// When an aspect of a line changes, a string is added to
+// lineView.changes. This updates the relevant part of the line's
+// DOM structure.
+function updateLineForChanges(cm, lineView, lineN, dims) {
+ for (var j = 0; j < lineView.changes.length; j++) {
+ var type = lineView.changes[j];
+ if (type == "text") { updateLineText(cm, lineView); }
+ else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
+ else if (type == "class") { updateLineClasses(cm, lineView); }
+ else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
+ }
+ lineView.changes = null;
+}
+
+// Lines with gutter elements, widgets or a background class need to
+// be wrapped, and have the extra elements added to the wrapper div
+function ensureLineWrapped(lineView) {
+ if (lineView.node == lineView.text) {
+ lineView.node = elt("div", null, null, "position: relative");
+ if (lineView.text.parentNode)
+ { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
+ lineView.node.appendChild(lineView.text);
+ if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
+ }
+ return lineView.node
+}
+
+function updateLineBackground(cm, lineView) {
+ var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
+ if (cls) { cls += " CodeMirror-linebackground"; }
+ if (lineView.background) {
+ if (cls) { lineView.background.className = cls; }
+ else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
+ } else if (cls) {
+ var wrap = ensureLineWrapped(lineView);
+ lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
+ cm.display.input.setUneditable(lineView.background);
+ }
+}
+
+// Wrapper around buildLineContent which will reuse the structure
+// in display.externalMeasured when possible.
+function getLineContent(cm, lineView) {
+ var ext = cm.display.externalMeasured;
+ if (ext && ext.line == lineView.line) {
+ cm.display.externalMeasured = null;
+ lineView.measure = ext.measure;
+ return ext.built
+ }
+ return buildLineContent(cm, lineView)
+}
+
+// Redraw the line's text. Interacts with the background and text
+// classes because the mode may output tokens that influence these
+// classes.
+function updateLineText(cm, lineView) {
+ var cls = lineView.text.className;
+ var built = getLineContent(cm, lineView);
+ if (lineView.text == lineView.node) { lineView.node = built.pre; }
+ lineView.text.parentNode.replaceChild(built.pre, lineView.text);
+ lineView.text = built.pre;
+ if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
+ lineView.bgClass = built.bgClass;
+ lineView.textClass = built.textClass;
+ updateLineClasses(cm, lineView);
+ } else if (cls) {
+ lineView.text.className = cls;
+ }
+}
+
+function updateLineClasses(cm, lineView) {
+ updateLineBackground(cm, lineView);
+ if (lineView.line.wrapClass)
+ { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
+ else if (lineView.node != lineView.text)
+ { lineView.node.className = ""; }
+ var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
+ lineView.text.className = textClass || "";
+}
+
+function updateLineGutter(cm, lineView, lineN, dims) {
+ if (lineView.gutter) {
+ lineView.node.removeChild(lineView.gutter);
+ lineView.gutter = null;
+ }
+ if (lineView.gutterBackground) {
+ lineView.node.removeChild(lineView.gutterBackground);
+ lineView.gutterBackground = null;
+ }
+ if (lineView.line.gutterClass) {
+ var wrap = ensureLineWrapped(lineView);
+ lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
+ ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
+ cm.display.input.setUneditable(lineView.gutterBackground);
+ wrap.insertBefore(lineView.gutterBackground, lineView.text);
+ }
+ var markers = lineView.line.gutterMarkers;
+ if (cm.options.lineNumbers || markers) {
+ var wrap$1 = ensureLineWrapped(lineView);
+ var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
+ cm.display.input.setUneditable(gutterWrap);
+ wrap$1.insertBefore(gutterWrap, lineView.text);
+ if (lineView.line.gutterClass)
+ { gutterWrap.className += " " + lineView.line.gutterClass; }
+ if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
+ { lineView.lineNumber = gutterWrap.appendChild(
+ elt("div", lineNumberFor(cm.options, lineN),
+ "CodeMirror-linenumber CodeMirror-gutter-elt",
+ ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
+ if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
+ var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
+ if (found)
+ { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
+ ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
+ } }
+ }
+}
+
+function updateLineWidgets(cm, lineView, dims) {
+ if (lineView.alignable) { lineView.alignable = null; }
+ for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
+ next = node.nextSibling;
+ if (node.className == "CodeMirror-linewidget")
+ { lineView.node.removeChild(node); }
+ }
+ insertLineWidgets(cm, lineView, dims);
+}
+
+// Build a line's DOM representation from scratch
+function buildLineElement(cm, lineView, lineN, dims) {
+ var built = getLineContent(cm, lineView);
+ lineView.text = lineView.node = built.pre;
+ if (built.bgClass) { lineView.bgClass = built.bgClass; }
+ if (built.textClass) { lineView.textClass = built.textClass; }
+
+ updateLineClasses(cm, lineView);
+ updateLineGutter(cm, lineView, lineN, dims);
+ insertLineWidgets(cm, lineView, dims);
+ return lineView.node
+}
+
+// A lineView may contain multiple logical lines (when merged by
+// collapsed spans). The widgets for all of them need to be drawn.
+function insertLineWidgets(cm, lineView, dims) {
+ insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
+ if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
+ { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
+}
+
+function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
+ if (!line.widgets) { return }
+ var wrap = ensureLineWrapped(lineView);
+ for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
+ var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
+ if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
+ positionLineWidget(widget, node, lineView, dims);
+ cm.display.input.setUneditable(node);
+ if (allowAbove && widget.above)
+ { wrap.insertBefore(node, lineView.gutter || lineView.text); }
+ else
+ { wrap.appendChild(node); }
+ signalLater(widget, "redraw");
+ }
+}
+
+function positionLineWidget(widget, node, lineView, dims) {
+ if (widget.noHScroll) {
+ (lineView.alignable || (lineView.alignable = [])).push(node);
+ var width = dims.wrapperWidth;
+ node.style.left = dims.fixedPos + "px";
+ if (!widget.coverGutter) {
+ width -= dims.gutterTotalWidth;
+ node.style.paddingLeft = dims.gutterTotalWidth + "px";
+ }
+ node.style.width = width + "px";
+ }
+ if (widget.coverGutter) {
+ node.style.zIndex = 5;
+ node.style.position = "relative";
+ if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
+ }
+}
+
+function widgetHeight(widget) {
+ if (widget.height != null) { return widget.height }
+ var cm = widget.doc.cm;
+ if (!cm) { return 0 }
+ if (!contains(document.body, widget.node)) {
+ var parentStyle = "position: relative;";
+ if (widget.coverGutter)
+ { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
+ if (widget.noHScroll)
+ { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
+ removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
+ }
+ return widget.height = widget.node.parentNode.offsetHeight
+}
+
+// Return true when the given mouse event happened in a widget
+function eventInWidget(display, e) {
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
+ if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
+ (n.parentNode == display.sizer && n != display.mover))
+ { return true }
+ }
+}
+
+// POSITION MEASUREMENT
+
+function paddingTop(display) {return display.lineSpace.offsetTop}
+function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
+function paddingH(display) {
+ if (display.cachedPaddingH) { return display.cachedPaddingH }
+ var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
+ var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
+ var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
+ if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
+ return data
+}
+
+function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
+function displayWidth(cm) {
+ return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
+}
+function displayHeight(cm) {
+ return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
+}
+
+// Ensure the lineView.wrapping.heights array is populated. This is
+// an array of bottom offsets for the lines that make up a drawn
+// line. When lineWrapping is on, there might be more than one
+// height.
+function ensureLineHeights(cm, lineView, rect) {
+ var wrapping = cm.options.lineWrapping;
+ var curWidth = wrapping && displayWidth(cm);
+ if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
+ var heights = lineView.measure.heights = [];
+ if (wrapping) {
+ lineView.measure.width = curWidth;
+ var rects = lineView.text.firstChild.getClientRects();
+ for (var i = 0; i < rects.length - 1; i++) {
+ var cur = rects[i], next = rects[i + 1];
+ if (Math.abs(cur.bottom - next.bottom) > 2)
+ { heights.push((cur.bottom + next.top) / 2 - rect.top); }
+ }
+ }
+ heights.push(rect.bottom - rect.top);
+ }
+}
+
+// Find a line map (mapping character offsets to text nodes) and a
+// measurement cache for the given line number. (A line view might
+// contain multiple lines when collapsed ranges are present.)
+function mapFromLineView(lineView, line, lineN) {
+ if (lineView.line == line)
+ { return {map: lineView.measure.map, cache: lineView.measure.cache} }
+ for (var i = 0; i < lineView.rest.length; i++)
+ { if (lineView.rest[i] == line)
+ { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
+ for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
+ { if (lineNo(lineView.rest[i$1]) > lineN)
+ { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
+}
+
+// Render a line into the hidden node display.externalMeasured. Used
+// when measurement is needed for a line that's not in the viewport.
+function updateExternalMeasurement(cm, line) {
+ line = visualLine(line);
+ var lineN = lineNo(line);
+ var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
+ view.lineN = lineN;
+ var built = view.built = buildLineContent(cm, view);
+ view.text = built.pre;
+ removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
+ return view
+}
+
+// Get a {top, bottom, left, right} box (in line-local coordinates)
+// for a given character.
+function measureChar(cm, line, ch, bias) {
+ return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
+}
+
+// Find a line view that corresponds to the given line number.
+function findViewForLine(cm, lineN) {
+ if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
+ { return cm.display.view[findViewIndex(cm, lineN)] }
+ var ext = cm.display.externalMeasured;
+ if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
+ { return ext }
+}
+
+// Measurement can be split in two steps, the set-up work that
+// applies to the whole line, and the measurement of the actual
+// character. Functions like coordsChar, that need to do a lot of
+// measurements in a row, can thus ensure that the set-up work is
+// only done once.
+function prepareMeasureForLine(cm, line) {
+ var lineN = lineNo(line);
+ var view = findViewForLine(cm, lineN);
+ if (view && !view.text) {
+ view = null;
+ } else if (view && view.changes) {
+ updateLineForChanges(cm, view, lineN, getDimensions(cm));
+ cm.curOp.forceUpdate = true;
+ }
+ if (!view)
+ { view = updateExternalMeasurement(cm, line); }
+
+ var info = mapFromLineView(view, line, lineN);
+ return {
+ line: line, view: view, rect: null,
+ map: info.map, cache: info.cache, before: info.before,
+ hasHeights: false
+ }
+}
+
+// Given a prepared measurement object, measures the position of an
+// actual character (or fetches it from the cache).
+function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
+ if (prepared.before) { ch = -1; }
+ var key = ch + (bias || ""), found;
+ if (prepared.cache.hasOwnProperty(key)) {
+ found = prepared.cache[key];
+ } else {
+ if (!prepared.rect)
+ { prepared.rect = prepared.view.text.getBoundingClientRect(); }
+ if (!prepared.hasHeights) {
+ ensureLineHeights(cm, prepared.view, prepared.rect);
+ prepared.hasHeights = true;
+ }
+ found = measureCharInner(cm, prepared, ch, bias);
+ if (!found.bogus) { prepared.cache[key] = found; }
+ }
+ return {left: found.left, right: found.right,
+ top: varHeight ? found.rtop : found.top,
+ bottom: varHeight ? found.rbottom : found.bottom}
+}
+
+var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
+
+function nodeAndOffsetInLineMap(map$$1, ch, bias) {
+ var node, start, end, collapse, mStart, mEnd;
+ // First, search the line map for the text node corresponding to,
+ // or closest to, the target character.
+ for (var i = 0; i < map$$1.length; i += 3) {
+ mStart = map$$1[i];
+ mEnd = map$$1[i + 1];
+ if (ch < mStart) {
+ start = 0; end = 1;
+ collapse = "left";
+ } else if (ch < mEnd) {
+ start = ch - mStart;
+ end = start + 1;
+ } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
+ end = mEnd - mStart;
+ start = end - 1;
+ if (ch >= mEnd) { collapse = "right"; }
+ }
+ if (start != null) {
+ node = map$$1[i + 2];
+ if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
+ { collapse = bias; }
+ if (bias == "left" && start == 0)
+ { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
+ node = map$$1[(i -= 3) + 2];
+ collapse = "left";
+ } }
+ if (bias == "right" && start == mEnd - mStart)
+ { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
+ node = map$$1[(i += 3) + 2];
+ collapse = "right";
+ } }
+ break
+ }
+ }
+ return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
+}
+
+function getUsefulRect(rects, bias) {
+ var rect = nullRect;
+ if (bias == "left") { for (var i = 0; i < rects.length; i++) {
+ if ((rect = rects[i]).left != rect.right) { break }
+ } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
+ if ((rect = rects[i$1]).left != rect.right) { break }
+ } }
+ return rect
+}
+
+function measureCharInner(cm, prepared, ch, bias) {
+ var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
+ var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
+
+ var rect;
+ if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
+ for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
+ while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
+ while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
+ if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
+ { rect = node.parentNode.getBoundingClientRect(); }
+ else
+ { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
+ if (rect.left || rect.right || start == 0) { break }
+ end = start;
+ start = start - 1;
+ collapse = "right";
+ }
+ if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
+ } else { // If it is a widget, simply get the box for the whole widget.
+ if (start > 0) { collapse = bias = "right"; }
+ var rects;
+ if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
+ { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
+ else
+ { rect = node.getBoundingClientRect(); }
+ }
+ if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
+ var rSpan = node.parentNode.getClientRects()[0];
+ if (rSpan)
+ { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
+ else
+ { rect = nullRect; }
+ }
+
+ var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
+ var mid = (rtop + rbot) / 2;
+ var heights = prepared.view.measure.heights;
+ var i = 0;
+ for (; i < heights.length - 1; i++)
+ { if (mid < heights[i]) { break } }
+ var top = i ? heights[i - 1] : 0, bot = heights[i];
+ var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
+ right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
+ top: top, bottom: bot};
+ if (!rect.left && !rect.right) { result.bogus = true; }
+ if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
+
+ return result
+}
+
+// Work around problem with bounding client rects on ranges being
+// returned incorrectly when zoomed on IE10 and below.
+function maybeUpdateRectForZooming(measure, rect) {
+ if (!window.screen || screen.logicalXDPI == null ||
+ screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
+ { return rect }
+ var scaleX = screen.logicalXDPI / screen.deviceXDPI;
+ var scaleY = screen.logicalYDPI / screen.deviceYDPI;
+ return {left: rect.left * scaleX, right: rect.right * scaleX,
+ top: rect.top * scaleY, bottom: rect.bottom * scaleY}
+}
+
+function clearLineMeasurementCacheFor(lineView) {
+ if (lineView.measure) {
+ lineView.measure.cache = {};
+ lineView.measure.heights = null;
+ if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
+ { lineView.measure.caches[i] = {}; } }
+ }
+}
+
+function clearLineMeasurementCache(cm) {
+ cm.display.externalMeasure = null;
+ removeChildren(cm.display.lineMeasure);
+ for (var i = 0; i < cm.display.view.length; i++)
+ { clearLineMeasurementCacheFor(cm.display.view[i]); }
+}
+
+function clearCaches(cm) {
+ clearLineMeasurementCache(cm);
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
+ if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
+ cm.display.lineNumChars = null;
+}
+
+function pageScrollX() {
+ // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
+ // which causes page_Offset and bounding client rects to use
+ // different reference viewports and invalidate our calculations.
+ if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
+ return window.pageXOffset || (document.documentElement || document.body).scrollLeft
+}
+function pageScrollY() {
+ if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
+ return window.pageYOffset || (document.documentElement || document.body).scrollTop
+}
+
+function widgetTopHeight(lineObj) {
+ var height = 0;
+ if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
+ { height += widgetHeight(lineObj.widgets[i]); } } }
+ return height
+}
+
+// Converts a {top, bottom, left, right} box from line-local
+// coordinates into another coordinate system. Context may be one of
+// "line", "div" (display.lineDiv), "local"./null (editor), "window",
+// or "page".
+function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
+ if (!includeWidgets) {
+ var height = widgetTopHeight(lineObj);
+ rect.top += height; rect.bottom += height;
+ }
+ if (context == "line") { return rect }
+ if (!context) { context = "local"; }
+ var yOff = heightAtLine(lineObj);
+ if (context == "local") { yOff += paddingTop(cm.display); }
+ else { yOff -= cm.display.viewOffset; }
+ if (context == "page" || context == "window") {
+ var lOff = cm.display.lineSpace.getBoundingClientRect();
+ yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
+ var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
+ rect.left += xOff; rect.right += xOff;
+ }
+ rect.top += yOff; rect.bottom += yOff;
+ return rect
+}
+
+// Coverts a box from "div" coords to another coordinate system.
+// Context may be "window", "page", "div", or "local"./null.
+function fromCoordSystem(cm, coords, context) {
+ if (context == "div") { return coords }
+ var left = coords.left, top = coords.top;
+ // First move into "page" coordinate system
+ if (context == "page") {
+ left -= pageScrollX();
+ top -= pageScrollY();
+ } else if (context == "local" || !context) {
+ var localBox = cm.display.sizer.getBoundingClientRect();
+ left += localBox.left;
+ top += localBox.top;
+ }
+
+ var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
+ return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
+}
+
+function charCoords(cm, pos, context, lineObj, bias) {
+ if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
+}
+
+// Returns a box for a given cursor position, which may have an
+// 'other' property containing the position of the secondary cursor
+// on a bidi boundary.
+// A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
+// and after `char - 1` in writing order of `char - 1`
+// A cursor Pos(line, char, "after") is on the same visual line as `char`
+// and before `char` in writing order of `char`
+// Examples (upper-case letters are RTL, lower-case are LTR):
+// Pos(0, 1, ...)
+// before after
+// ab a|b a|b
+// aB a|B aB|
+// Ab |Ab A|b
+// AB B|A B|A
+// Every position after the last character on a line is considered to stick
+// to the last character on the line.
+function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
+ lineObj = lineObj || getLine(cm.doc, pos.line);
+ if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
+ function get(ch, right) {
+ var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
+ if (right) { m.left = m.right; } else { m.right = m.left; }
+ return intoCoordSystem(cm, lineObj, m, context)
+ }
+ var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
+ if (ch >= lineObj.text.length) {
+ ch = lineObj.text.length;
+ sticky = "before";
+ } else if (ch <= 0) {
+ ch = 0;
+ sticky = "after";
+ }
+ if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
+
+ function getBidi(ch, partPos, invert) {
+ var part = order[partPos], right = part.level == 1;
+ return get(invert ? ch - 1 : ch, right != invert)
+ }
+ var partPos = getBidiPartAt(order, ch, sticky);
+ var other = bidiOther;
+ var val = getBidi(ch, partPos, sticky == "before");
+ if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
+ return val
+}
+
+// Used to cheaply estimate the coordinates for a position. Used for
+// intermediate scroll updates.
+function estimateCoords(cm, pos) {
+ var left = 0;
+ pos = clipPos(cm.doc, pos);
+ if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
+ var lineObj = getLine(cm.doc, pos.line);
+ var top = heightAtLine(lineObj) + paddingTop(cm.display);
+ return {left: left, right: left, top: top, bottom: top + lineObj.height}
+}
+
+// Positions returned by coordsChar contain some extra information.
+// xRel is the relative x position of the input coordinates compared
+// to the found position (so xRel > 0 means the coordinates are to
+// the right of the character position, for example). When outside
+// is true, that means the coordinates lie outside the line's
+// vertical range.
+function PosWithInfo(line, ch, sticky, outside, xRel) {
+ var pos = Pos(line, ch, sticky);
+ pos.xRel = xRel;
+ if (outside) { pos.outside = true; }
+ return pos
+}
+
+// Compute the character position closest to the given coordinates.
+// Input must be lineSpace-local ("div" coordinate system).
+function coordsChar(cm, x, y) {
+ var doc = cm.doc;
+ y += cm.display.viewOffset;
+ if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
+ var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
+ if (lineN > last)
+ { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
+ if (x < 0) { x = 0; }
+
+ var lineObj = getLine(doc, lineN);
+ for (;;) {
+ var found = coordsCharInner(cm, lineObj, lineN, x, y);
+ var merged = collapsedSpanAtEnd(lineObj);
+ var mergedPos = merged && merged.find(0, true);
+ if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
+ { lineN = lineNo(lineObj = mergedPos.to.line); }
+ else
+ { return found }
+ }
+}
+
+function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
+ y -= widgetTopHeight(lineObj);
+ var end = lineObj.text.length;
+ var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
+ end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
+ return {begin: begin, end: end}
+}
+
+function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
+ if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
+ var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
+ return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
+}
+
+// Returns true if the given side of a box is after the given
+// coordinates, in top-to-bottom, left-to-right order.
+function boxIsAfter(box, x, y, left) {
+ return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
+}
+
+function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
+ // Move y into line-local coordinate space
+ y -= heightAtLine(lineObj);
+ var preparedMeasure = prepareMeasureForLine(cm, lineObj);
+ // When directly calling `measureCharPrepared`, we have to adjust
+ // for the widgets at this line.
+ var widgetHeight$$1 = widgetTopHeight(lineObj);
+ var begin = 0, end = lineObj.text.length, ltr = true;
+
+ var order = getOrder(lineObj, cm.doc.direction);
+ // If the line isn't plain left-to-right text, first figure out
+ // which bidi section the coordinates fall into.
+ if (order) {
+ var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
+ (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
+ ltr = part.level != 1;
+ // The awkward -1 offsets are needed because findFirst (called
+ // on these below) will treat its first bound as inclusive,
+ // second as exclusive, but we want to actually address the
+ // characters in the part's range
+ begin = ltr ? part.from : part.to - 1;
+ end = ltr ? part.to : part.from - 1;
+ }
+
+ // A binary search to find the first character whose bounding box
+ // starts after the coordinates. If we run across any whose box wrap
+ // the coordinates, store that.
+ var chAround = null, boxAround = null;
+ var ch = findFirst(function (ch) {
+ var box = measureCharPrepared(cm, preparedMeasure, ch);
+ box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
+ if (!boxIsAfter(box, x, y, false)) { return false }
+ if (box.top <= y && box.left <= x) {
+ chAround = ch;
+ boxAround = box;
+ }
+ return true
+ }, begin, end);
+
+ var baseX, sticky, outside = false;
+ // If a box around the coordinates was found, use that
+ if (boxAround) {
+ // Distinguish coordinates nearer to the left or right side of the box
+ var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
+ ch = chAround + (atStart ? 0 : 1);
+ sticky = atStart ? "after" : "before";
+ baseX = atLeft ? boxAround.left : boxAround.right;
+ } else {
+ // (Adjust for extended bound, if necessary.)
+ if (!ltr && (ch == end || ch == begin)) { ch++; }
+ // To determine which side to associate with, get the box to the
+ // left of the character and compare it's vertical position to the
+ // coordinates
+ sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
+ (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
+ "after" : "before";
+ // Now get accurate coordinates for this place, in order to get a
+ // base X position
+ var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
+ baseX = coords.left;
+ outside = y < coords.top || y >= coords.bottom;
+ }
+
+ ch = skipExtendingChars(lineObj.text, ch, 1);
+ return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
+}
+
+function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
+ // Bidi parts are sorted left-to-right, and in a non-line-wrapping
+ // situation, we can take this ordering to correspond to the visual
+ // ordering. This finds the first part whose end is after the given
+ // coordinates.
+ var index = findFirst(function (i) {
+ var part = order[i], ltr = part.level != 1;
+ return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
+ "line", lineObj, preparedMeasure), x, y, true)
+ }, 0, order.length - 1);
+ var part = order[index];
+ // If this isn't the first part, the part's start is also after
+ // the coordinates, and the coordinates aren't on the same line as
+ // that start, move one part back.
+ if (index > 0) {
+ var ltr = part.level != 1;
+ var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
+ "line", lineObj, preparedMeasure);
+ if (boxIsAfter(start, x, y, true) && start.top > y)
+ { part = order[index - 1]; }
+ }
+ return part
+}
+
+function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
+ // In a wrapped line, rtl text on wrapping boundaries can do things
+ // that don't correspond to the ordering in our `order` array at
+ // all, so a binary search doesn't work, and we want to return a
+ // part that only spans one line so that the binary search in
+ // coordsCharInner is safe. As such, we first find the extent of the
+ // wrapped line, and then do a flat search in which we discard any
+ // spans that aren't on the line.
+ var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
+ var begin = ref.begin;
+ var end = ref.end;
+ if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
+ var part = null, closestDist = null;
+ for (var i = 0; i < order.length; i++) {
+ var p = order[i];
+ if (p.from >= end || p.to <= begin) { continue }
+ var ltr = p.level != 1;
+ var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
+ // Weigh against spans ending before this, so that they are only
+ // picked if nothing ends after
+ var dist = endX < x ? x - endX + 1e9 : endX - x;
+ if (!part || closestDist > dist) {
+ part = p;
+ closestDist = dist;
+ }
+ }
+ if (!part) { part = order[order.length - 1]; }
+ // Clip the part to the wrapped line.
+ if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
+ if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
+ return part
+}
+
+var measureText;
+// Compute the default text height.
+function textHeight(display) {
+ if (display.cachedTextHeight != null) { return display.cachedTextHeight }
+ if (measureText == null) {
+ measureText = elt("pre");
+ // Measure a bunch of lines, for browsers that compute
+ // fractional heights.
+ for (var i = 0; i < 49; ++i) {
+ measureText.appendChild(document.createTextNode("x"));
+ measureText.appendChild(elt("br"));
+ }
+ measureText.appendChild(document.createTextNode("x"));
+ }
+ removeChildrenAndAdd(display.measure, measureText);
+ var height = measureText.offsetHeight / 50;
+ if (height > 3) { display.cachedTextHeight = height; }
+ removeChildren(display.measure);
+ return height || 1
+}
+
+// Compute the default character width.
+function charWidth(display) {
+ if (display.cachedCharWidth != null) { return display.cachedCharWidth }
+ var anchor = elt("span", "xxxxxxxxxx");
+ var pre = elt("pre", [anchor]);
+ removeChildrenAndAdd(display.measure, pre);
+ var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
+ if (width > 2) { display.cachedCharWidth = width; }
+ return width || 10
+}
+
+// Do a bulk-read of the DOM positions and sizes needed to draw the
+// view, so that we don't interleave reading and writing to the DOM.
+function getDimensions(cm) {
+ var d = cm.display, left = {}, width = {};
+ var gutterLeft = d.gutters.clientLeft;
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
+ left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
+ width[cm.options.gutters[i]] = n.clientWidth;
+ }
+ return {fixedPos: compensateForHScroll(d),
+ gutterTotalWidth: d.gutters.offsetWidth,
+ gutterLeft: left,
+ gutterWidth: width,
+ wrapperWidth: d.wrapper.clientWidth}
+}
+
+// Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
+// but using getBoundingClientRect to get a sub-pixel-accurate
+// result.
+function compensateForHScroll(display) {
+ return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
+}
+
+// Returns a function that estimates the height of a line, to use as
+// first approximation until the line becomes visible (and is thus
+// properly measurable).
+function estimateHeight(cm) {
+ var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
+ var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
+ return function (line) {
+ if (lineIsHidden(cm.doc, line)) { return 0 }
+
+ var widgetsHeight = 0;
+ if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
+ if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
+ } }
+
+ if (wrapping)
+ { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
+ else
+ { return widgetsHeight + th }
+ }
+}
+
+function estimateLineHeights(cm) {
+ var doc = cm.doc, est = estimateHeight(cm);
+ doc.iter(function (line) {
+ var estHeight = est(line);
+ if (estHeight != line.height) { updateLineHeight(line, estHeight); }
+ });
+}
+
+// Given a mouse event, find the corresponding position. If liberal
+// is false, it checks whether a gutter or scrollbar was clicked,
+// and returns null if it was. forRect is used by rectangular
+// selections, and tries to estimate a character position even for
+// coordinates beyond the right of the text.
+function posFromMouse(cm, e, liberal, forRect) {
+ var display = cm.display;
+ if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
+
+ var x, y, space = display.lineSpace.getBoundingClientRect();
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
+ try { x = e.clientX - space.left; y = e.clientY - space.top; }
+ catch (e) { return null }
+ var coords = coordsChar(cm, x, y), line;
+ if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
+ var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
+ coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
+ }
+ return coords
+}
+
+// Find the view element corresponding to a given line. Return null
+// when the line isn't visible.
+function findViewIndex(cm, n) {
+ if (n >= cm.display.viewTo) { return null }
+ n -= cm.display.viewFrom;
+ if (n < 0) { return null }
+ var view = cm.display.view;
+ for (var i = 0; i < view.length; i++) {
+ n -= view[i].size;
+ if (n < 0) { return i }
+ }
+}
+
+function updateSelection(cm) {
+ cm.display.input.showSelection(cm.display.input.prepareSelection());
+}
+
+function prepareSelection(cm, primary) {
+ if ( primary === void 0 ) primary = true;
+
+ var doc = cm.doc, result = {};
+ var curFragment = result.cursors = document.createDocumentFragment();
+ var selFragment = result.selection = document.createDocumentFragment();
+
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ if (!primary && i == doc.sel.primIndex) { continue }
+ var range$$1 = doc.sel.ranges[i];
+ if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
+ var collapsed = range$$1.empty();
+ if (collapsed || cm.options.showCursorWhenSelecting)
+ { drawSelectionCursor(cm, range$$1.head, curFragment); }
+ if (!collapsed)
+ { drawSelectionRange(cm, range$$1, selFragment); }
+ }
+ return result
+}
+
+// Draws a cursor for the given range
+function drawSelectionCursor(cm, head, output) {
+ var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
+
+ var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
+ cursor.style.left = pos.left + "px";
+ cursor.style.top = pos.top + "px";
+ cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
+
+ if (pos.other) {
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
+ var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
+ otherCursor.style.display = "";
+ otherCursor.style.left = pos.other.left + "px";
+ otherCursor.style.top = pos.other.top + "px";
+ otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
+ }
+}
+
+function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
+
+// Draws the given range as a highlighted selection
+function drawSelectionRange(cm, range$$1, output) {
+ var display = cm.display, doc = cm.doc;
+ var fragment = document.createDocumentFragment();
+ var padding = paddingH(cm.display), leftSide = padding.left;
+ var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
+ var docLTR = doc.direction == "ltr";
+
+ function add(left, top, width, bottom) {
+ if (top < 0) { top = 0; }
+ top = Math.round(top);
+ bottom = Math.round(bottom);
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")));
+ }
+
+ function drawForLine(line, fromArg, toArg) {
+ var lineObj = getLine(doc, line);
+ var lineLen = lineObj.text.length;
+ var start, end;
+ function coords(ch, bias) {
+ return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
+ }
+
+ function wrapX(pos, dir, side) {
+ var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
+ var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
+ var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
+ return coords(ch, prop)[prop]
+ }
+
+ var order = getOrder(lineObj, doc.direction);
+ iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
+ var ltr = dir == "ltr";
+ var fromPos = coords(from, ltr ? "left" : "right");
+ var toPos = coords(to - 1, ltr ? "right" : "left");
+
+ var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
+ var first = i == 0, last = !order || i == order.length - 1;
+ if (toPos.top - fromPos.top <= 3) { // Single line
+ var openLeft = (docLTR ? openStart : openEnd) && first;
+ var openRight = (docLTR ? openEnd : openStart) && last;
+ var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
+ var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
+ add(left, fromPos.top, right - left, fromPos.bottom);
+ } else { // Multiple lines
+ var topLeft, topRight, botLeft, botRight;
+ if (ltr) {
+ topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
+ topRight = docLTR ? rightSide : wrapX(from, dir, "before");
+ botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
+ botRight = docLTR && openEnd && last ? rightSide : toPos.right;
+ } else {
+ topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
+ topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
+ botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
+ botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
+ }
+ add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
+ if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
+ add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
+ }
+
+ if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
+ if (cmpCoords(toPos, start) < 0) { start = toPos; }
+ if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
+ if (cmpCoords(toPos, end) < 0) { end = toPos; }
+ });
+ return {start: start, end: end}
+ }
+
+ var sFrom = range$$1.from(), sTo = range$$1.to();
+ if (sFrom.line == sTo.line) {
+ drawForLine(sFrom.line, sFrom.ch, sTo.ch);
+ } else {
+ var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
+ var singleVLine = visualLine(fromLine) == visualLine(toLine);
+ var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
+ var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
+ if (singleVLine) {
+ if (leftEnd.top < rightStart.top - 2) {
+ add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
+ add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
+ } else {
+ add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
+ }
+ }
+ if (leftEnd.bottom < rightStart.top)
+ { add(leftSide, leftEnd.bottom, null, rightStart.top); }
+ }
+
+ output.appendChild(fragment);
+}
+
+// Cursor-blinking
+function restartBlink(cm) {
+ if (!cm.state.focused) { return }
+ var display = cm.display;
+ clearInterval(display.blinker);
+ var on = true;
+ display.cursorDiv.style.visibility = "";
+ if (cm.options.cursorBlinkRate > 0)
+ { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
+ cm.options.cursorBlinkRate); }
+ else if (cm.options.cursorBlinkRate < 0)
+ { display.cursorDiv.style.visibility = "hidden"; }
+}
+
+function ensureFocus(cm) {
+ if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
+}
+
+function delayBlurEvent(cm) {
+ cm.state.delayingBlurEvent = true;
+ setTimeout(function () { if (cm.state.delayingBlurEvent) {
+ cm.state.delayingBlurEvent = false;
+ onBlur(cm);
+ } }, 100);
+}
+
+function onFocus(cm, e) {
+ if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
+
+ if (cm.options.readOnly == "nocursor") { return }
+ if (!cm.state.focused) {
+ signal(cm, "focus", cm, e);
+ cm.state.focused = true;
+ addClass(cm.display.wrapper, "CodeMirror-focused");
+ // This test prevents this from firing when a context
+ // menu is closed (since the input reset would kill the
+ // select-all detection hack)
+ if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
+ cm.display.input.reset();
+ if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
+ }
+ cm.display.input.receivedFocus();
+ }
+ restartBlink(cm);
+}
+function onBlur(cm, e) {
+ if (cm.state.delayingBlurEvent) { return }
+
+ if (cm.state.focused) {
+ signal(cm, "blur", cm, e);
+ cm.state.focused = false;
+ rmClass(cm.display.wrapper, "CodeMirror-focused");
+ }
+ clearInterval(cm.display.blinker);
+ setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
+}
+
+// Read the actual heights of the rendered lines, and update their
+// stored heights to match.
+function updateHeightsInViewport(cm) {
+ var display = cm.display;
+ var prevBottom = display.lineDiv.offsetTop;
+ for (var i = 0; i < display.view.length; i++) {
+ var cur = display.view[i], height = (void 0);
+ if (cur.hidden) { continue }
+ if (ie && ie_version < 8) {
+ var bot = cur.node.offsetTop + cur.node.offsetHeight;
+ height = bot - prevBottom;
+ prevBottom = bot;
+ } else {
+ var box = cur.node.getBoundingClientRect();
+ height = box.bottom - box.top;
+ }
+ var diff = cur.line.height - height;
+ if (height < 2) { height = textHeight(display); }
+ if (diff > .005 || diff < -.005) {
+ updateLineHeight(cur.line, height);
+ updateWidgetHeight(cur.line);
+ if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
+ { updateWidgetHeight(cur.rest[j]); } }
+ }
+ }
+}
+
+// Read and store the height of line widgets associated with the
+// given line.
+function updateWidgetHeight(line) {
+ if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
+ var w = line.widgets[i], parent = w.node.parentNode;
+ if (parent) { w.height = parent.offsetHeight; }
+ } }
+}
+
+// Compute the lines that are visible in a given viewport (defaults
+// the the current scroll position). viewport may contain top,
+// height, and ensure (see op.scrollToPos) properties.
+function visibleLines(display, doc, viewport) {
+ var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
+ top = Math.floor(top - paddingTop(display));
+ var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
+
+ var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
+ // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
+ // forces those lines into the viewport (if possible).
+ if (viewport && viewport.ensure) {
+ var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
+ if (ensureFrom < from) {
+ from = ensureFrom;
+ to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
+ } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
+ from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
+ to = ensureTo;
+ }
+ }
+ return {from: from, to: Math.max(to, from + 1)}
+}
+
+// Re-align line numbers and gutter marks to compensate for
+// horizontal scrolling.
+function alignHorizontally(cm) {
+ var display = cm.display, view = display.view;
+ if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
+ var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
+ var gutterW = display.gutters.offsetWidth, left = comp + "px";
+ for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
+ if (cm.options.fixedGutter) {
+ if (view[i].gutter)
+ { view[i].gutter.style.left = left; }
+ if (view[i].gutterBackground)
+ { view[i].gutterBackground.style.left = left; }
+ }
+ var align = view[i].alignable;
+ if (align) { for (var j = 0; j < align.length; j++)
+ { align[j].style.left = left; } }
+ } }
+ if (cm.options.fixedGutter)
+ { display.gutters.style.left = (comp + gutterW) + "px"; }
+}
+
+// Used to ensure that the line number gutter is still the right
+// size for the current document size. Returns true when an update
+// is needed.
+function maybeUpdateLineNumberWidth(cm) {
+ if (!cm.options.lineNumbers) { return false }
+ var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
+ if (last.length != display.lineNumChars) {
+ var test = display.measure.appendChild(elt("div", [elt("div", last)],
+ "CodeMirror-linenumber CodeMirror-gutter-elt"));
+ var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
+ display.lineGutter.style.width = "";
+ display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
+ display.lineGutter.style.width = display.lineNumWidth + "px";
+ updateGutterSpace(cm);
+ return true
+ }
+ return false
+}
+
+// SCROLLING THINGS INTO VIEW
+
+// If an editor sits on the top or bottom of the window, partially
+// scrolled out of view, this ensures that the cursor is visible.
+function maybeScrollWindow(cm, rect) {
+ if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
+
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
+ if (rect.top + box.top < 0) { doScroll = true; }
+ else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
+ if (doScroll != null && !phantom) {
+ var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
+ cm.display.lineSpace.appendChild(scrollNode);
+ scrollNode.scrollIntoView(doScroll);
+ cm.display.lineSpace.removeChild(scrollNode);
+ }
+}
+
+// Scroll a given position into view (immediately), verifying that
+// it actually became visible (as line heights are accurately
+// measured, the position of something may 'drift' during drawing).
+function scrollPosIntoView(cm, pos, end, margin) {
+ if (margin == null) { margin = 0; }
+ var rect;
+ if (!cm.options.lineWrapping && pos == end) {
+ // Set pos and end to the cursor positions around the character pos sticks to
+ // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
+ // If pos == Pos(_, 0, "before"), pos and end are unchanged
+ pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
+ end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
+ }
+ for (var limit = 0; limit < 5; limit++) {
+ var changed = false;
+ var coords = cursorCoords(cm, pos);
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
+ rect = {left: Math.min(coords.left, endCoords.left),
+ top: Math.min(coords.top, endCoords.top) - margin,
+ right: Math.max(coords.left, endCoords.left),
+ bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
+ var scrollPos = calculateScrollPos(cm, rect);
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
+ if (scrollPos.scrollTop != null) {
+ updateScrollTop(cm, scrollPos.scrollTop);
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
+ }
+ if (scrollPos.scrollLeft != null) {
+ setScrollLeft(cm, scrollPos.scrollLeft);
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
+ }
+ if (!changed) { break }
+ }
+ return rect
+}
+
+// Scroll a given set of coordinates into view (immediately).
+function scrollIntoView(cm, rect) {
+ var scrollPos = calculateScrollPos(cm, rect);
+ if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
+ if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
+}
+
+// Calculate a new scroll position needed to scroll the given
+// rectangle into view. Returns an object with scrollTop and
+// scrollLeft properties. When these are undefined, the
+// vertical/horizontal position does not need to be adjusted.
+function calculateScrollPos(cm, rect) {
+ var display = cm.display, snapMargin = textHeight(cm.display);
+ if (rect.top < 0) { rect.top = 0; }
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
+ var screen = displayHeight(cm), result = {};
+ if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
+ var docBottom = cm.doc.height + paddingVert(display);
+ var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
+ if (rect.top < screentop) {
+ result.scrollTop = atTop ? 0 : rect.top;
+ } else if (rect.bottom > screentop + screen) {
+ var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
+ if (newTop != screentop) { result.scrollTop = newTop; }
+ }
+
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
+ var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
+ var tooWide = rect.right - rect.left > screenw;
+ if (tooWide) { rect.right = rect.left + screenw; }
+ if (rect.left < 10)
+ { result.scrollLeft = 0; }
+ else if (rect.left < screenleft)
+ { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
+ else if (rect.right > screenw + screenleft - 3)
+ { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
+ return result
+}
+
+// Store a relative adjustment to the scroll position in the current
+// operation (to be applied when the operation finishes).
+function addToScrollTop(cm, top) {
+ if (top == null) { return }
+ resolveScrollToPos(cm);
+ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
+}
+
+// Make sure that at the end of the operation the current cursor is
+// shown.
+function ensureCursorVisible(cm) {
+ resolveScrollToPos(cm);
+ var cur = cm.getCursor();
+ cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
+}
+
+function scrollToCoords(cm, x, y) {
+ if (x != null || y != null) { resolveScrollToPos(cm); }
+ if (x != null) { cm.curOp.scrollLeft = x; }
+ if (y != null) { cm.curOp.scrollTop = y; }
+}
+
+function scrollToRange(cm, range$$1) {
+ resolveScrollToPos(cm);
+ cm.curOp.scrollToPos = range$$1;
+}
+
+// When an operation has its scrollToPos property set, and another
+// scroll action is applied before the end of the operation, this
+// 'simulates' scrolling that position into view in a cheap way, so
+// that the effect of intermediate scroll commands is not ignored.
+function resolveScrollToPos(cm) {
+ var range$$1 = cm.curOp.scrollToPos;
+ if (range$$1) {
+ cm.curOp.scrollToPos = null;
+ var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
+ scrollToCoordsRange(cm, from, to, range$$1.margin);
+ }
+}
+
+function scrollToCoordsRange(cm, from, to, margin) {
+ var sPos = calculateScrollPos(cm, {
+ left: Math.min(from.left, to.left),
+ top: Math.min(from.top, to.top) - margin,
+ right: Math.max(from.right, to.right),
+ bottom: Math.max(from.bottom, to.bottom) + margin
+ });
+ scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
+}
+
+// Sync the scrollable area and scrollbars, ensure the viewport
+// covers the visible area.
+function updateScrollTop(cm, val) {
+ if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
+ if (!gecko) { updateDisplaySimple(cm, {top: val}); }
+ setScrollTop(cm, val, true);
+ if (gecko) { updateDisplaySimple(cm); }
+ startWorker(cm, 100);
+}
+
+function setScrollTop(cm, val, forceScroll) {
+ val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
+ if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
+ cm.doc.scrollTop = val;
+ cm.display.scrollbars.setScrollTop(val);
+ if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
+}
+
+// Sync scroller and scrollbar, ensure the gutter elements are
+// aligned.
+function setScrollLeft(cm, val, isScroller, forceScroll) {
+ val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
+ if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
+ cm.doc.scrollLeft = val;
+ alignHorizontally(cm);
+ if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
+ cm.display.scrollbars.setScrollLeft(val);
+}
+
+// SCROLLBARS
+
+// Prepare DOM reads needed to update the scrollbars. Done in one
+// shot to minimize update/measure roundtrips.
+function measureForScrollbars(cm) {
+ var d = cm.display, gutterW = d.gutters.offsetWidth;
+ var docH = Math.round(cm.doc.height + paddingVert(cm.display));
+ return {
+ clientHeight: d.scroller.clientHeight,
+ viewHeight: d.wrapper.clientHeight,
+ scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
+ viewWidth: d.wrapper.clientWidth,
+ barLeft: cm.options.fixedGutter ? gutterW : 0,
+ docHeight: docH,
+ scrollHeight: docH + scrollGap(cm) + d.barHeight,
+ nativeBarWidth: d.nativeBarWidth,
+ gutterWidth: gutterW
+ }
+}
+
+var NativeScrollbars = function(place, scroll, cm) {
+ this.cm = cm;
+ var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
+ var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
+ place(vert); place(horiz);
+
+ on(vert, "scroll", function () {
+ if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
+ });
+ on(horiz, "scroll", function () {
+ if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
+ });
+
+ this.checkedZeroWidth = false;
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
+ if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
+};
+
+NativeScrollbars.prototype.update = function (measure) {
+ var needsH = measure.scrollWidth > measure.clientWidth + 1;
+ var needsV = measure.scrollHeight > measure.clientHeight + 1;
+ var sWidth = measure.nativeBarWidth;
+
+ if (needsV) {
+ this.vert.style.display = "block";
+ this.vert.style.bottom = needsH ? sWidth + "px" : "0";
+ var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
+ // A bug in IE8 can cause this value to be negative, so guard it.
+ this.vert.firstChild.style.height =
+ Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
+ } else {
+ this.vert.style.display = "";
+ this.vert.firstChild.style.height = "0";
+ }
+
+ if (needsH) {
+ this.horiz.style.display = "block";
+ this.horiz.style.right = needsV ? sWidth + "px" : "0";
+ this.horiz.style.left = measure.barLeft + "px";
+ var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
+ this.horiz.firstChild.style.width =
+ Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
+ } else {
+ this.horiz.style.display = "";
+ this.horiz.firstChild.style.width = "0";
+ }
+
+ if (!this.checkedZeroWidth && measure.clientHeight > 0) {
+ if (sWidth == 0) { this.zeroWidthHack(); }
+ this.checkedZeroWidth = true;
+ }
+
+ return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
+};
+
+NativeScrollbars.prototype.setScrollLeft = function (pos) {
+ if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
+ if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
+};
+
+NativeScrollbars.prototype.setScrollTop = function (pos) {
+ if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
+ if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
+};
+
+NativeScrollbars.prototype.zeroWidthHack = function () {
+ var w = mac && !mac_geMountainLion ? "12px" : "18px";
+ this.horiz.style.height = this.vert.style.width = w;
+ this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
+ this.disableHoriz = new Delayed;
+ this.disableVert = new Delayed;
+};
+
+NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
+ bar.style.pointerEvents = "auto";
+ function maybeDisable() {
+ // To find out whether the scrollbar is still visible, we
+ // check whether the element under the pixel in the bottom
+ // right corner of the scrollbar box is the scrollbar box
+ // itself (when the bar is still visible) or its filler child
+ // (when the bar is hidden). If it is still visible, we keep
+ // it enabled, if it's hidden, we disable pointer events.
+ var box = bar.getBoundingClientRect();
+ var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
+ : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
+ if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
+ else { delay.set(1000, maybeDisable); }
+ }
+ delay.set(1000, maybeDisable);
+};
+
+NativeScrollbars.prototype.clear = function () {
+ var parent = this.horiz.parentNode;
+ parent.removeChild(this.horiz);
+ parent.removeChild(this.vert);
+};
+
+var NullScrollbars = function () {};
+
+NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
+NullScrollbars.prototype.setScrollLeft = function () {};
+NullScrollbars.prototype.setScrollTop = function () {};
+NullScrollbars.prototype.clear = function () {};
+
+function updateScrollbars(cm, measure) {
+ if (!measure) { measure = measureForScrollbars(cm); }
+ var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
+ updateScrollbarsInner(cm, measure);
+ for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
+ if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
+ { updateHeightsInViewport(cm); }
+ updateScrollbarsInner(cm, measureForScrollbars(cm));
+ startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
+ }
+}
+
+// Re-synchronize the fake scrollbars with the actual size of the
+// content.
+function updateScrollbarsInner(cm, measure) {
+ var d = cm.display;
+ var sizes = d.scrollbars.update(measure);
+
+ d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
+ d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
+ d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
+
+ if (sizes.right && sizes.bottom) {
+ d.scrollbarFiller.style.display = "block";
+ d.scrollbarFiller.style.height = sizes.bottom + "px";
+ d.scrollbarFiller.style.width = sizes.right + "px";
+ } else { d.scrollbarFiller.style.display = ""; }
+ if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
+ d.gutterFiller.style.display = "block";
+ d.gutterFiller.style.height = sizes.bottom + "px";
+ d.gutterFiller.style.width = measure.gutterWidth + "px";
+ } else { d.gutterFiller.style.display = ""; }
+}
+
+var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
+
+function initScrollbars(cm) {
+ if (cm.display.scrollbars) {
+ cm.display.scrollbars.clear();
+ if (cm.display.scrollbars.addClass)
+ { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
+ }
+
+ cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
+ cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
+ // Prevent clicks in the scrollbars from killing focus
+ on(node, "mousedown", function () {
+ if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
+ });
+ node.setAttribute("cm-not-content", "true");
+ }, function (pos, axis) {
+ if (axis == "horizontal") { setScrollLeft(cm, pos); }
+ else { updateScrollTop(cm, pos); }
+ }, cm);
+ if (cm.display.scrollbars.addClass)
+ { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
+}
+
+// Operations are used to wrap a series of changes to the editor
+// state in such a way that each change won't have to update the
+// cursor and display (which would be awkward, slow, and
+// error-prone). Instead, display updates are batched and then all
+// combined and executed at once.
+
+var nextOpId = 0;
+// Start a new operation.
+function startOperation(cm) {
+ cm.curOp = {
+ cm: cm,
+ viewChanged: false, // Flag that indicates that lines might need to be redrawn
+ startHeight: cm.doc.height, // Used to detect need to update scrollbar
+ forceUpdate: false, // Used to force a redraw
+ updateInput: null, // Whether to reset the input textarea
+ typing: false, // Whether this reset should be careful to leave existing text (for compositing)
+ changeObjs: null, // Accumulated changes, for firing change events
+ cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
+ cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
+ selectionChanged: false, // Whether the selection needs to be redrawn
+ updateMaxLine: false, // Set when the widest line needs to be determined anew
+ scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
+ scrollToPos: null, // Used to scroll to a specific position
+ focus: false,
+ id: ++nextOpId // Unique ID
+ };
+ pushOperation(cm.curOp);
+}
+
+// Finish an operation, updating the display and signalling delayed events
+function endOperation(cm) {
+ var op = cm.curOp;
+ finishOperation(op, function (group) {
+ for (var i = 0; i < group.ops.length; i++)
+ { group.ops[i].cm.curOp = null; }
+ endOperations(group);
+ });
+}
+
+// The DOM updates done when an operation finishes are batched so
+// that the minimum number of relayouts are required.
+function endOperations(group) {
+ var ops = group.ops;
+ for (var i = 0; i < ops.length; i++) // Read DOM
+ { endOperation_R1(ops[i]); }
+ for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
+ { endOperation_W1(ops[i$1]); }
+ for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
+ { endOperation_R2(ops[i$2]); }
+ for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
+ { endOperation_W2(ops[i$3]); }
+ for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
+ { endOperation_finish(ops[i$4]); }
+}
+
+function endOperation_R1(op) {
+ var cm = op.cm, display = cm.display;
+ maybeClipScrollbars(cm);
+ if (op.updateMaxLine) { findMaxLine(cm); }
+
+ op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
+ op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
+ op.scrollToPos.to.line >= display.viewTo) ||
+ display.maxLineChanged && cm.options.lineWrapping;
+ op.update = op.mustUpdate &&
+ new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
+}
+
+function endOperation_W1(op) {
+ op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
+}
+
+function endOperation_R2(op) {
+ var cm = op.cm, display = cm.display;
+ if (op.updatedDisplay) { updateHeightsInViewport(cm); }
+
+ op.barMeasure = measureForScrollbars(cm);
+
+ // If the max line changed since it was last measured, measure it,
+ // and ensure the document's width matches it.
+ // updateDisplay_W2 will use these properties to do the actual resizing
+ if (display.maxLineChanged && !cm.options.lineWrapping) {
+ op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
+ cm.display.sizerWidth = op.adjustWidthTo;
+ op.barMeasure.scrollWidth =
+ Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
+ op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
+ }
+
+ if (op.updatedDisplay || op.selectionChanged)
+ { op.preparedSelection = display.input.prepareSelection(); }
+}
+
+function endOperation_W2(op) {
+ var cm = op.cm;
+
+ if (op.adjustWidthTo != null) {
+ cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
+ if (op.maxScrollLeft < cm.doc.scrollLeft)
+ { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
+ cm.display.maxLineChanged = false;
+ }
+
+ var takeFocus = op.focus && op.focus == activeElt();
+ if (op.preparedSelection)
+ { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
+ if (op.updatedDisplay || op.startHeight != cm.doc.height)
+ { updateScrollbars(cm, op.barMeasure); }
+ if (op.updatedDisplay)
+ { setDocumentHeight(cm, op.barMeasure); }
+
+ if (op.selectionChanged) { restartBlink(cm); }
+
+ if (cm.state.focused && op.updateInput)
+ { cm.display.input.reset(op.typing); }
+ if (takeFocus) { ensureFocus(op.cm); }
+}
+
+function endOperation_finish(op) {
+ var cm = op.cm, display = cm.display, doc = cm.doc;
+
+ if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
+
+ // Abort mouse wheel delta measurement, when scrolling explicitly
+ if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
+ { display.wheelStartX = display.wheelStartY = null; }
+
+ // Propagate the scroll position to the actual DOM scroller
+ if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
+
+ if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
+ // If we need to scroll a specific position into view, do so.
+ if (op.scrollToPos) {
+ var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
+ clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
+ maybeScrollWindow(cm, rect);
+ }
+
+ // Fire events for markers that are hidden/unidden by editing or
+ // undoing
+ var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
+ if (hidden) { for (var i = 0; i < hidden.length; ++i)
+ { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
+ if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
+ { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
+
+ if (display.wrapper.offsetHeight)
+ { doc.scrollTop = cm.display.scroller.scrollTop; }
+
+ // Fire change events, and delayed event handlers
+ if (op.changeObjs)
+ { signal(cm, "changes", cm, op.changeObjs); }
+ if (op.update)
+ { op.update.finish(); }
+}
+
+// Run the given function in an operation
+function runInOp(cm, f) {
+ if (cm.curOp) { return f() }
+ startOperation(cm);
+ try { return f() }
+ finally { endOperation(cm); }
+}
+// Wraps a function in an operation. Returns the wrapped function.
+function operation(cm, f) {
+ return function() {
+ if (cm.curOp) { return f.apply(cm, arguments) }
+ startOperation(cm);
+ try { return f.apply(cm, arguments) }
+ finally { endOperation(cm); }
+ }
+}
+// Used to add methods to editor and doc instances, wrapping them in
+// operations.
+function methodOp(f) {
+ return function() {
+ if (this.curOp) { return f.apply(this, arguments) }
+ startOperation(this);
+ try { return f.apply(this, arguments) }
+ finally { endOperation(this); }
+ }
+}
+function docMethodOp(f) {
+ return function() {
+ var cm = this.cm;
+ if (!cm || cm.curOp) { return f.apply(this, arguments) }
+ startOperation(cm);
+ try { return f.apply(this, arguments) }
+ finally { endOperation(cm); }
+ }
+}
+
+// Updates the display.view data structure for a given change to the
+// document. From and to are in pre-change coordinates. Lendiff is
+// the amount of lines added or subtracted by the change. This is
+// used for changes that span multiple lines, or change the way
+// lines are divided into visual lines. regLineChange (below)
+// registers single-line changes.
+function regChange(cm, from, to, lendiff) {
+ if (from == null) { from = cm.doc.first; }
+ if (to == null) { to = cm.doc.first + cm.doc.size; }
+ if (!lendiff) { lendiff = 0; }
+
+ var display = cm.display;
+ if (lendiff && to < display.viewTo &&
+ (display.updateLineNumbers == null || display.updateLineNumbers > from))
+ { display.updateLineNumbers = from; }
+
+ cm.curOp.viewChanged = true;
+
+ if (from >= display.viewTo) { // Change after
+ if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
+ { resetView(cm); }
+ } else if (to <= display.viewFrom) { // Change before
+ if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
+ resetView(cm);
+ } else {
+ display.viewFrom += lendiff;
+ display.viewTo += lendiff;
+ }
+ } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
+ resetView(cm);
+ } else if (from <= display.viewFrom) { // Top overlap
+ var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
+ if (cut) {
+ display.view = display.view.slice(cut.index);
+ display.viewFrom = cut.lineN;
+ display.viewTo += lendiff;
+ } else {
+ resetView(cm);
+ }
+ } else if (to >= display.viewTo) { // Bottom overlap
+ var cut$1 = viewCuttingPoint(cm, from, from, -1);
+ if (cut$1) {
+ display.view = display.view.slice(0, cut$1.index);
+ display.viewTo = cut$1.lineN;
+ } else {
+ resetView(cm);
+ }
+ } else { // Gap in the middle
+ var cutTop = viewCuttingPoint(cm, from, from, -1);
+ var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
+ if (cutTop && cutBot) {
+ display.view = display.view.slice(0, cutTop.index)
+ .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
+ .concat(display.view.slice(cutBot.index));
+ display.viewTo += lendiff;
+ } else {
+ resetView(cm);
+ }
+ }
+
+ var ext = display.externalMeasured;
+ if (ext) {
+ if (to < ext.lineN)
+ { ext.lineN += lendiff; }
+ else if (from < ext.lineN + ext.size)
+ { display.externalMeasured = null; }
+ }
+}
+
+// Register a change to a single line. Type must be one of "text",
+// "gutter", "class", "widget"
+function regLineChange(cm, line, type) {
+ cm.curOp.viewChanged = true;
+ var display = cm.display, ext = cm.display.externalMeasured;
+ if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
+ { display.externalMeasured = null; }
+
+ if (line < display.viewFrom || line >= display.viewTo) { return }
+ var lineView = display.view[findViewIndex(cm, line)];
+ if (lineView.node == null) { return }
+ var arr = lineView.changes || (lineView.changes = []);
+ if (indexOf(arr, type) == -1) { arr.push(type); }
+}
+
+// Clear the view.
+function resetView(cm) {
+ cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
+ cm.display.view = [];
+ cm.display.viewOffset = 0;
+}
+
+function viewCuttingPoint(cm, oldN, newN, dir) {
+ var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
+ if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
+ { return {index: index, lineN: newN} }
+ var n = cm.display.viewFrom;
+ for (var i = 0; i < index; i++)
+ { n += view[i].size; }
+ if (n != oldN) {
+ if (dir > 0) {
+ if (index == view.length - 1) { return null }
+ diff = (n + view[index].size) - oldN;
+ index++;
+ } else {
+ diff = n - oldN;
+ }
+ oldN += diff; newN += diff;
+ }
+ while (visualLineNo(cm.doc, newN) != newN) {
+ if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
+ newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
+ index += dir;
+ }
+ return {index: index, lineN: newN}
+}
+
+// Force the view to cover a given range, adding empty view element
+// or clipping off existing ones as needed.
+function adjustView(cm, from, to) {
+ var display = cm.display, view = display.view;
+ if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
+ display.view = buildViewArray(cm, from, to);
+ display.viewFrom = from;
+ } else {
+ if (display.viewFrom > from)
+ { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
+ else if (display.viewFrom < from)
+ { display.view = display.view.slice(findViewIndex(cm, from)); }
+ display.viewFrom = from;
+ if (display.viewTo < to)
+ { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
+ else if (display.viewTo > to)
+ { display.view = display.view.slice(0, findViewIndex(cm, to)); }
+ }
+ display.viewTo = to;
+}
+
+// Count the number of lines in the view whose DOM representation is
+// out of date (or nonexistent).
+function countDirtyView(cm) {
+ var view = cm.display.view, dirty = 0;
+ for (var i = 0; i < view.length; i++) {
+ var lineView = view[i];
+ if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
+ }
+ return dirty
+}
+
+// HIGHLIGHT WORKER
+
+function startWorker(cm, time) {
+ if (cm.doc.highlightFrontier < cm.display.viewTo)
+ { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
+}
+
+function highlightWorker(cm) {
+ var doc = cm.doc;
+ if (doc.highlightFrontier >= cm.display.viewTo) { return }
+ var end = +new Date + cm.options.workTime;
+ var context = getContextBefore(cm, doc.highlightFrontier);
+ var changedLines = [];
+
+ doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
+ if (context.line >= cm.display.viewFrom) { // Visible
+ var oldStyles = line.styles;
+ var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
+ var highlighted = highlightLine(cm, line, context, true);
+ if (resetState) { context.state = resetState; }
+ line.styles = highlighted.styles;
+ var oldCls = line.styleClasses, newCls = highlighted.classes;
+ if (newCls) { line.styleClasses = newCls; }
+ else if (oldCls) { line.styleClasses = null; }
+ var ischange = !oldStyles || oldStyles.length != line.styles.length ||
+ oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
+ if (ischange) { changedLines.push(context.line); }
+ line.stateAfter = context.save();
+ context.nextLine();
+ } else {
+ if (line.text.length <= cm.options.maxHighlightLength)
+ { processLine(cm, line.text, context); }
+ line.stateAfter = context.line % 5 == 0 ? context.save() : null;
+ context.nextLine();
+ }
+ if (+new Date > end) {
+ startWorker(cm, cm.options.workDelay);
+ return true
+ }
+ });
+ doc.highlightFrontier = context.line;
+ doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
+ if (changedLines.length) { runInOp(cm, function () {
+ for (var i = 0; i < changedLines.length; i++)
+ { regLineChange(cm, changedLines[i], "text"); }
+ }); }
+}
+
+// DISPLAY DRAWING
+
+var DisplayUpdate = function(cm, viewport, force) {
+ var display = cm.display;
+
+ this.viewport = viewport;
+ // Store some values that we'll need later (but don't want to force a relayout for)
+ this.visible = visibleLines(display, cm.doc, viewport);
+ this.editorIsHidden = !display.wrapper.offsetWidth;
+ this.wrapperHeight = display.wrapper.clientHeight;
+ this.wrapperWidth = display.wrapper.clientWidth;
+ this.oldDisplayWidth = displayWidth(cm);
+ this.force = force;
+ this.dims = getDimensions(cm);
+ this.events = [];
+};
+
+DisplayUpdate.prototype.signal = function (emitter, type) {
+ if (hasHandler(emitter, type))
+ { this.events.push(arguments); }
+};
+DisplayUpdate.prototype.finish = function () {
+ var this$1 = this;
+
+ for (var i = 0; i < this.events.length; i++)
+ { signal.apply(null, this$1.events[i]); }
+};
+
+function maybeClipScrollbars(cm) {
+ var display = cm.display;
+ if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
+ display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
+ display.heightForcer.style.height = scrollGap(cm) + "px";
+ display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
+ display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
+ display.scrollbarsClipped = true;
+ }
+}
+
+function selectionSnapshot(cm) {
+ if (cm.hasFocus()) { return null }
+ var active = activeElt();
+ if (!active || !contains(cm.display.lineDiv, active)) { return null }
+ var result = {activeElt: active};
+ if (window.getSelection) {
+ var sel = window.getSelection();
+ if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
+ result.anchorNode = sel.anchorNode;
+ result.anchorOffset = sel.anchorOffset;
+ result.focusNode = sel.focusNode;
+ result.focusOffset = sel.focusOffset;
+ }
+ }
+ return result
+}
+
+function restoreSelection(snapshot) {
+ if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
+ snapshot.activeElt.focus();
+ if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
+ var sel = window.getSelection(), range$$1 = document.createRange();
+ range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
+ range$$1.collapse(false);
+ sel.removeAllRanges();
+ sel.addRange(range$$1);
+ sel.extend(snapshot.focusNode, snapshot.focusOffset);
+ }
+}
+
+// Does the actual updating of the line display. Bails out
+// (returning false) when there is nothing to be done and forced is
+// false.
+function updateDisplayIfNeeded(cm, update) {
+ var display = cm.display, doc = cm.doc;
+
+ if (update.editorIsHidden) {
+ resetView(cm);
+ return false
+ }
+
+ // Bail out if the visible area is already rendered and nothing changed.
+ if (!update.force &&
+ update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
+ display.renderedView == display.view && countDirtyView(cm) == 0)
+ { return false }
+
+ if (maybeUpdateLineNumberWidth(cm)) {
+ resetView(cm);
+ update.dims = getDimensions(cm);
+ }
+
+ // Compute a suitable new viewport (from & to)
+ var end = doc.first + doc.size;
+ var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
+ var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
+ if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
+ if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
+ if (sawCollapsedSpans) {
+ from = visualLineNo(cm.doc, from);
+ to = visualLineEndNo(cm.doc, to);
+ }
+
+ var different = from != display.viewFrom || to != display.viewTo ||
+ display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
+ adjustView(cm, from, to);
+
+ display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
+ // Position the mover div to align with the current scroll position
+ cm.display.mover.style.top = display.viewOffset + "px";
+
+ var toUpdate = countDirtyView(cm);
+ if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
+ { return false }
+
+ // For big changes, we hide the enclosing element during the
+ // update, since that speeds up the operations on most browsers.
+ var selSnapshot = selectionSnapshot(cm);
+ if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
+ patchDisplay(cm, display.updateLineNumbers, update.dims);
+ if (toUpdate > 4) { display.lineDiv.style.display = ""; }
+ display.renderedView = display.view;
+ // There might have been a widget with a focused element that got
+ // hidden or updated, if so re-focus it.
+ restoreSelection(selSnapshot);
+
+ // Prevent selection and cursors from interfering with the scroll
+ // width and height.
+ removeChildren(display.cursorDiv);
+ removeChildren(display.selectionDiv);
+ display.gutters.style.height = display.sizer.style.minHeight = 0;
+
+ if (different) {
+ display.lastWrapHeight = update.wrapperHeight;
+ display.lastWrapWidth = update.wrapperWidth;
+ startWorker(cm, 400);
+ }
+
+ display.updateLineNumbers = null;
+
+ return true
+}
+
+function postUpdateDisplay(cm, update) {
+ var viewport = update.viewport;
+
+ for (var first = true;; first = false) {
+ if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
+ // Clip forced viewport to actual scrollable area.
+ if (viewport && viewport.top != null)
+ { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
+ // Updated line heights might result in the drawn area not
+ // actually covering the viewport. Keep looping until it does.
+ update.visible = visibleLines(cm.display, cm.doc, viewport);
+ if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
+ { break }
+ }
+ if (!updateDisplayIfNeeded(cm, update)) { break }
+ updateHeightsInViewport(cm);
+ var barMeasure = measureForScrollbars(cm);
+ updateSelection(cm);
+ updateScrollbars(cm, barMeasure);
+ setDocumentHeight(cm, barMeasure);
+ update.force = false;
+ }
+
+ update.signal(cm, "update", cm);
+ if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
+ update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
+ cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
+ }
+}
+
+function updateDisplaySimple(cm, viewport) {
+ var update = new DisplayUpdate(cm, viewport);
+ if (updateDisplayIfNeeded(cm, update)) {
+ updateHeightsInViewport(cm);
+ postUpdateDisplay(cm, update);
+ var barMeasure = measureForScrollbars(cm);
+ updateSelection(cm);
+ updateScrollbars(cm, barMeasure);
+ setDocumentHeight(cm, barMeasure);
+ update.finish();
+ }
+}
+
+// Sync the actual display DOM structure with display.view, removing
+// nodes for lines that are no longer in view, and creating the ones
+// that are not there yet, and updating the ones that are out of
+// date.
+function patchDisplay(cm, updateNumbersFrom, dims) {
+ var display = cm.display, lineNumbers = cm.options.lineNumbers;
+ var container = display.lineDiv, cur = container.firstChild;
+
+ function rm(node) {
+ var next = node.nextSibling;
+ // Works around a throw-scroll bug in OS X Webkit
+ if (webkit && mac && cm.display.currentWheelTarget == node)
+ { node.style.display = "none"; }
+ else
+ { node.parentNode.removeChild(node); }
+ return next
+ }
+
+ var view = display.view, lineN = display.viewFrom;
+ // Loop over the elements in the view, syncing cur (the DOM nodes
+ // in display.lineDiv) with the view as we go.
+ for (var i = 0; i < view.length; i++) {
+ var lineView = view[i];
+ if (lineView.hidden) {
+ } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
+ var node = buildLineElement(cm, lineView, lineN, dims);
+ container.insertBefore(node, cur);
+ } else { // Already drawn
+ while (cur != lineView.node) { cur = rm(cur); }
+ var updateNumber = lineNumbers && updateNumbersFrom != null &&
+ updateNumbersFrom <= lineN && lineView.lineNumber;
+ if (lineView.changes) {
+ if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
+ updateLineForChanges(cm, lineView, lineN, dims);
+ }
+ if (updateNumber) {
+ removeChildren(lineView.lineNumber);
+ lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
+ }
+ cur = lineView.node.nextSibling;
+ }
+ lineN += lineView.size;
+ }
+ while (cur) { cur = rm(cur); }
+}
+
+function updateGutterSpace(cm) {
+ var width = cm.display.gutters.offsetWidth;
+ cm.display.sizer.style.marginLeft = width + "px";
+}
+
+function setDocumentHeight(cm, measure) {
+ cm.display.sizer.style.minHeight = measure.docHeight + "px";
+ cm.display.heightForcer.style.top = measure.docHeight + "px";
+ cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
+}
+
+// Rebuild the gutter elements, ensure the margin to the left of the
+// code matches their width.
+function updateGutters(cm) {
+ var gutters = cm.display.gutters, specs = cm.options.gutters;
+ removeChildren(gutters);
+ var i = 0;
+ for (; i < specs.length; ++i) {
+ var gutterClass = specs[i];
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
+ if (gutterClass == "CodeMirror-linenumbers") {
+ cm.display.lineGutter = gElt;
+ gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
+ }
+ }
+ gutters.style.display = i ? "" : "none";
+ updateGutterSpace(cm);
+}
+
+// Make sure the gutters options contains the element
+// "CodeMirror-linenumbers" when the lineNumbers option is true.
+function setGuttersForLineNumbers(options) {
+ var found = indexOf(options.gutters, "CodeMirror-linenumbers");
+ if (found == -1 && options.lineNumbers) {
+ options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
+ } else if (found > -1 && !options.lineNumbers) {
+ options.gutters = options.gutters.slice(0);
+ options.gutters.splice(found, 1);
+ }
+}
+
+// Since the delta values reported on mouse wheel events are
+// unstandardized between browsers and even browser versions, and
+// generally horribly unpredictable, this code starts by measuring
+// the scroll effect that the first few mouse wheel events have,
+// and, from that, detects the way it can convert deltas to pixel
+// offsets afterwards.
+//
+// The reason we want to know the amount a wheel event will scroll
+// is that it gives us a chance to update the display before the
+// actual scrolling happens, reducing flickering.
+
+var wheelSamples = 0;
+var wheelPixelsPerUnit = null;
+// Fill in a browser-detected starting value on browsers where we
+// know one. These don't have to be accurate -- the result of them
+// being wrong would just be a slight flicker on the first wheel
+// scroll (if it is large enough).
+if (ie) { wheelPixelsPerUnit = -.53; }
+else if (gecko) { wheelPixelsPerUnit = 15; }
+else if (chrome) { wheelPixelsPerUnit = -.7; }
+else if (safari) { wheelPixelsPerUnit = -1/3; }
+
+function wheelEventDelta(e) {
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
+ else if (dy == null) { dy = e.wheelDelta; }
+ return {x: dx, y: dy}
+}
+function wheelEventPixels(e) {
+ var delta = wheelEventDelta(e);
+ delta.x *= wheelPixelsPerUnit;
+ delta.y *= wheelPixelsPerUnit;
+ return delta
+}
+
+function onScrollWheel(cm, e) {
+ var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
+
+ var display = cm.display, scroll = display.scroller;
+ // Quit if there's nothing to scroll here
+ var canScrollX = scroll.scrollWidth > scroll.clientWidth;
+ var canScrollY = scroll.scrollHeight > scroll.clientHeight;
+ if (!(dx && canScrollX || dy && canScrollY)) { return }
+
+ // Webkit browsers on OS X abort momentum scrolls when the target
+ // of the scroll event is removed from the scrollable element.
+ // This hack (see related code in patchDisplay) makes sure the
+ // element is kept around.
+ if (dy && mac && webkit) {
+ outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
+ for (var i = 0; i < view.length; i++) {
+ if (view[i].node == cur) {
+ cm.display.currentWheelTarget = cur;
+ break outer
+ }
+ }
+ }
+ }
+
+ // On some browsers, horizontal scrolling will cause redraws to
+ // happen before the gutter has been realigned, causing it to
+ // wriggle around in a most unseemly way. When we have an
+ // estimated pixels/delta value, we just handle horizontal
+ // scrolling entirely here. It'll be slightly off from native, but
+ // better than glitching out.
+ if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
+ if (dy && canScrollY)
+ { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
+ setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
+ // Only prevent default scrolling if vertical scrolling is
+ // actually possible. Otherwise, it causes vertical scroll
+ // jitter on OSX trackpads when deltaX is small and deltaY
+ // is large (issue #3579)
+ if (!dy || (dy && canScrollY))
+ { e_preventDefault(e); }
+ display.wheelStartX = null; // Abort measurement, if in progress
+ return
+ }
+
+ // 'Project' the visible viewport to cover the area that is being
+ // scrolled into view (if we know enough to estimate it).
+ if (dy && wheelPixelsPerUnit != null) {
+ var pixels = dy * wheelPixelsPerUnit;
+ var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
+ if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
+ else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
+ updateDisplaySimple(cm, {top: top, bottom: bot});
+ }
+
+ if (wheelSamples < 20) {
+ if (display.wheelStartX == null) {
+ display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
+ display.wheelDX = dx; display.wheelDY = dy;
+ setTimeout(function () {
+ if (display.wheelStartX == null) { return }
+ var movedX = scroll.scrollLeft - display.wheelStartX;
+ var movedY = scroll.scrollTop - display.wheelStartY;
+ var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
+ (movedX && display.wheelDX && movedX / display.wheelDX);
+ display.wheelStartX = display.wheelStartY = null;
+ if (!sample) { return }
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
+ ++wheelSamples;
+ }, 200);
+ } else {
+ display.wheelDX += dx; display.wheelDY += dy;
+ }
+ }
+}
+
+// Selection objects are immutable. A new one is created every time
+// the selection changes. A selection is one or more non-overlapping
+// (and non-touching) ranges, sorted, and an integer that indicates
+// which one is the primary selection (the one that's scrolled into
+// view, that getCursor returns, etc).
+var Selection = function(ranges, primIndex) {
+ this.ranges = ranges;
+ this.primIndex = primIndex;
+};
+
+Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
+
+Selection.prototype.equals = function (other) {
+ var this$1 = this;
+
+ if (other == this) { return true }
+ if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
+ for (var i = 0; i < this.ranges.length; i++) {
+ var here = this$1.ranges[i], there = other.ranges[i];
+ if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
+ }
+ return true
+};
+
+Selection.prototype.deepCopy = function () {
+ var this$1 = this;
+
+ var out = [];
+ for (var i = 0; i < this.ranges.length; i++)
+ { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
+ return new Selection(out, this.primIndex)
+};
+
+Selection.prototype.somethingSelected = function () {
+ var this$1 = this;
+
+ for (var i = 0; i < this.ranges.length; i++)
+ { if (!this$1.ranges[i].empty()) { return true } }
+ return false
+};
+
+Selection.prototype.contains = function (pos, end) {
+ var this$1 = this;
+
+ if (!end) { end = pos; }
+ for (var i = 0; i < this.ranges.length; i++) {
+ var range = this$1.ranges[i];
+ if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
+ { return i }
+ }
+ return -1
+};
+
+var Range = function(anchor, head) {
+ this.anchor = anchor; this.head = head;
+};
+
+Range.prototype.from = function () { return minPos(this.anchor, this.head) };
+Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
+Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
+
+// Take an unsorted, potentially overlapping set of ranges, and
+// build a selection out of it. 'Consumes' ranges array (modifying
+// it).
+function normalizeSelection(ranges, primIndex) {
+ var prim = ranges[primIndex];
+ ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
+ primIndex = indexOf(ranges, prim);
+ for (var i = 1; i < ranges.length; i++) {
+ var cur = ranges[i], prev = ranges[i - 1];
+ if (cmp(prev.to(), cur.from()) >= 0) {
+ var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
+ var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
+ if (i <= primIndex) { --primIndex; }
+ ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
+ }
+ }
+ return new Selection(ranges, primIndex)
+}
+
+function simpleSelection(anchor, head) {
+ return new Selection([new Range(anchor, head || anchor)], 0)
+}
+
+// Compute the position of the end of a change (its 'to' property
+// refers to the pre-change end).
+function changeEnd(change) {
+ if (!change.text) { return change.to }
+ return Pos(change.from.line + change.text.length - 1,
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
+}
+
+// Adjust a position to refer to the post-change position of the
+// same text, or the end of the change if the change covers it.
+function adjustForChange(pos, change) {
+ if (cmp(pos, change.from) < 0) { return pos }
+ if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
+
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
+ if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
+ return Pos(line, ch)
+}
+
+function computeSelAfterChange(doc, change) {
+ var out = [];
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ var range = doc.sel.ranges[i];
+ out.push(new Range(adjustForChange(range.anchor, change),
+ adjustForChange(range.head, change)));
+ }
+ return normalizeSelection(out, doc.sel.primIndex)
+}
+
+function offsetPos(pos, old, nw) {
+ if (pos.line == old.line)
+ { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
+ else
+ { return Pos(nw.line + (pos.line - old.line), pos.ch) }
+}
+
+// Used by replaceSelections to allow moving the selection to the
+// start or around the replaced test. Hint may be "start" or "around".
+function computeReplacedSel(doc, changes, hint) {
+ var out = [];
+ var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
+ for (var i = 0; i < changes.length; i++) {
+ var change = changes[i];
+ var from = offsetPos(change.from, oldPrev, newPrev);
+ var to = offsetPos(changeEnd(change), oldPrev, newPrev);
+ oldPrev = change.to;
+ newPrev = to;
+ if (hint == "around") {
+ var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
+ out[i] = new Range(inv ? to : from, inv ? from : to);
+ } else {
+ out[i] = new Range(from, from);
+ }
+ }
+ return new Selection(out, doc.sel.primIndex)
+}
+
+// Used to get the editor into a consistent state again when options change.
+
+function loadMode(cm) {
+ cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
+ resetModeState(cm);
+}
+
+function resetModeState(cm) {
+ cm.doc.iter(function (line) {
+ if (line.stateAfter) { line.stateAfter = null; }
+ if (line.styles) { line.styles = null; }
+ });
+ cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
+ startWorker(cm, 100);
+ cm.state.modeGen++;
+ if (cm.curOp) { regChange(cm); }
+}
+
+// DOCUMENT DATA STRUCTURE
+
+// By default, updates that start and end at the beginning of a line
+// are treated specially, in order to make the association of line
+// widgets and marker elements with the text behave more intuitive.
+function isWholeLineUpdate(doc, change) {
+ return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
+ (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
+}
+
+// Perform a change on the document data structure.
+function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
+ function spansFor(n) {return markedSpans ? markedSpans[n] : null}
+ function update(line, text, spans) {
+ updateLine(line, text, spans, estimateHeight$$1);
+ signalLater(line, "change", line, change);
+ }
+ function linesFor(start, end) {
+ var result = [];
+ for (var i = start; i < end; ++i)
+ { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
+ return result
+ }
+
+ var from = change.from, to = change.to, text = change.text;
+ var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
+ var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
+
+ // Adjust the line structure
+ if (change.full) {
+ doc.insert(0, linesFor(0, text.length));
+ doc.remove(text.length, doc.size - text.length);
+ } else if (isWholeLineUpdate(doc, change)) {
+ // This is a whole-line replace. Treated specially to make
+ // sure line objects move the way they are supposed to.
+ var added = linesFor(0, text.length - 1);
+ update(lastLine, lastLine.text, lastSpans);
+ if (nlines) { doc.remove(from.line, nlines); }
+ if (added.length) { doc.insert(from.line, added); }
+ } else if (firstLine == lastLine) {
+ if (text.length == 1) {
+ update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
+ } else {
+ var added$1 = linesFor(1, text.length - 1);
+ added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+ doc.insert(from.line + 1, added$1);
+ }
+ } else if (text.length == 1) {
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
+ doc.remove(from.line + 1, nlines);
+ } else {
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
+ update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
+ var added$2 = linesFor(1, text.length - 1);
+ if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
+ doc.insert(from.line + 1, added$2);
+ }
+
+ signalLater(doc, "change", doc, change);
+}
+
+// Call f for all linked documents.
+function linkedDocs(doc, f, sharedHistOnly) {
+ function propagate(doc, skip, sharedHist) {
+ if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
+ var rel = doc.linked[i];
+ if (rel.doc == skip) { continue }
+ var shared = sharedHist && rel.sharedHist;
+ if (sharedHistOnly && !shared) { continue }
+ f(rel.doc, shared);
+ propagate(rel.doc, doc, shared);
+ } }
+ }
+ propagate(doc, null, true);
+}
+
+// Attach a document to an editor.
+function attachDoc(cm, doc) {
+ if (doc.cm) { throw new Error("This document is already in use.") }
+ cm.doc = doc;
+ doc.cm = cm;
+ estimateLineHeights(cm);
+ loadMode(cm);
+ setDirectionClass(cm);
+ if (!cm.options.lineWrapping) { findMaxLine(cm); }
+ cm.options.mode = doc.modeOption;
+ regChange(cm);
+}
+
+function setDirectionClass(cm) {
+ (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
+}
+
+function directionChanged(cm) {
+ runInOp(cm, function () {
+ setDirectionClass(cm);
+ regChange(cm);
+ });
+}
+
+function History(startGen) {
+ // Arrays of change events and selections. Doing something adds an
+ // event to done and clears undo. Undoing moves events from done
+ // to undone, redoing moves them in the other direction.
+ this.done = []; this.undone = [];
+ this.undoDepth = Infinity;
+ // Used to track when changes can be merged into a single undo
+ // event
+ this.lastModTime = this.lastSelTime = 0;
+ this.lastOp = this.lastSelOp = null;
+ this.lastOrigin = this.lastSelOrigin = null;
+ // Used by the isClean() method
+ this.generation = this.maxGeneration = startGen || 1;
+}
+
+// Create a history change event from an updateDoc-style change
+// object.
+function historyChangeFromChange(doc, change) {
+ var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
+ attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
+ linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
+ return histChange
+}
+
+// Pop all selection events off the end of a history array. Stop at
+// a change event.
+function clearSelectionEvents(array) {
+ while (array.length) {
+ var last = lst(array);
+ if (last.ranges) { array.pop(); }
+ else { break }
+ }
+}
+
+// Find the top change event in the history. Pop off selection
+// events that are in the way.
+function lastChangeEvent(hist, force) {
+ if (force) {
+ clearSelectionEvents(hist.done);
+ return lst(hist.done)
+ } else if (hist.done.length && !lst(hist.done).ranges) {
+ return lst(hist.done)
+ } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
+ hist.done.pop();
+ return lst(hist.done)
+ }
+}
+
+// Register a change in the history. Merges changes that are within
+// a single operation, or are close together with an origin that
+// allows merging (starting with "+") into a single event.
+function addChangeToHistory(doc, change, selAfter, opId) {
+ var hist = doc.history;
+ hist.undone.length = 0;
+ var time = +new Date, cur;
+ var last;
+
+ if ((hist.lastOp == opId ||
+ hist.lastOrigin == change.origin && change.origin &&
+ ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
+ change.origin.charAt(0) == "*")) &&
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
+ // Merge this change into the last event
+ last = lst(cur.changes);
+ if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
+ // Optimized case for simple insertion -- don't want to add
+ // new changesets for every character typed
+ last.to = changeEnd(change);
+ } else {
+ // Add new sub-event
+ cur.changes.push(historyChangeFromChange(doc, change));
+ }
+ } else {
+ // Can not be merged, start a new event.
+ var before = lst(hist.done);
+ if (!before || !before.ranges)
+ { pushSelectionToHistory(doc.sel, hist.done); }
+ cur = {changes: [historyChangeFromChange(doc, change)],
+ generation: hist.generation};
+ hist.done.push(cur);
+ while (hist.done.length > hist.undoDepth) {
+ hist.done.shift();
+ if (!hist.done[0].ranges) { hist.done.shift(); }
+ }
+ }
+ hist.done.push(selAfter);
+ hist.generation = ++hist.maxGeneration;
+ hist.lastModTime = hist.lastSelTime = time;
+ hist.lastOp = hist.lastSelOp = opId;
+ hist.lastOrigin = hist.lastSelOrigin = change.origin;
+
+ if (!last) { signal(doc, "historyAdded"); }
+}
+
+function selectionEventCanBeMerged(doc, origin, prev, sel) {
+ var ch = origin.charAt(0);
+ return ch == "*" ||
+ ch == "+" &&
+ prev.ranges.length == sel.ranges.length &&
+ prev.somethingSelected() == sel.somethingSelected() &&
+ new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
+}
+
+// Called whenever the selection changes, sets the new selection as
+// the pending selection in the history, and pushes the old pending
+// selection into the 'done' array when it was significantly
+// different (in number of selected ranges, emptiness, or time).
+function addSelectionToHistory(doc, sel, opId, options) {
+ var hist = doc.history, origin = options && options.origin;
+
+ // A new event is started when the previous origin does not match
+ // the current, or the origins don't allow matching. Origins
+ // starting with * are always merged, those starting with + are
+ // merged when similar and close together in time.
+ if (opId == hist.lastSelOp ||
+ (origin && hist.lastSelOrigin == origin &&
+ (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
+ selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
+ { hist.done[hist.done.length - 1] = sel; }
+ else
+ { pushSelectionToHistory(sel, hist.done); }
+
+ hist.lastSelTime = +new Date;
+ hist.lastSelOrigin = origin;
+ hist.lastSelOp = opId;
+ if (options && options.clearRedo !== false)
+ { clearSelectionEvents(hist.undone); }
+}
+
+function pushSelectionToHistory(sel, dest) {
+ var top = lst(dest);
+ if (!(top && top.ranges && top.equals(sel)))
+ { dest.push(sel); }
+}
+
+// Used to store marked span information in the history.
+function attachLocalSpans(doc, change, from, to) {
+ var existing = change["spans_" + doc.id], n = 0;
+ doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
+ if (line.markedSpans)
+ { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
+ ++n;
+ });
+}
+
+// When un/re-doing restores text containing marked spans, those
+// that have been explicitly cleared should not be restored.
+function removeClearedSpans(spans) {
+ if (!spans) { return null }
+ var out;
+ for (var i = 0; i < spans.length; ++i) {
+ if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
+ else if (out) { out.push(spans[i]); }
+ }
+ return !out ? spans : out.length ? out : null
+}
+
+// Retrieve and filter the old marked spans stored in a change event.
+function getOldSpans(doc, change) {
+ var found = change["spans_" + doc.id];
+ if (!found) { return null }
+ var nw = [];
+ for (var i = 0; i < change.text.length; ++i)
+ { nw.push(removeClearedSpans(found[i])); }
+ return nw
+}
+
+// Used for un/re-doing changes from the history. Combines the
+// result of computing the existing spans with the set of spans that
+// existed in the history (so that deleting around a span and then
+// undoing brings back the span).
+function mergeOldSpans(doc, change) {
+ var old = getOldSpans(doc, change);
+ var stretched = stretchSpansOverChange(doc, change);
+ if (!old) { return stretched }
+ if (!stretched) { return old }
+
+ for (var i = 0; i < old.length; ++i) {
+ var oldCur = old[i], stretchCur = stretched[i];
+ if (oldCur && stretchCur) {
+ spans: for (var j = 0; j < stretchCur.length; ++j) {
+ var span = stretchCur[j];
+ for (var k = 0; k < oldCur.length; ++k)
+ { if (oldCur[k].marker == span.marker) { continue spans } }
+ oldCur.push(span);
+ }
+ } else if (stretchCur) {
+ old[i] = stretchCur;
+ }
+ }
+ return old
+}
+
+// Used both to provide a JSON-safe object in .getHistory, and, when
+// detaching a document, to split the history in two
+function copyHistoryArray(events, newGroup, instantiateSel) {
+ var copy = [];
+ for (var i = 0; i < events.length; ++i) {
+ var event = events[i];
+ if (event.ranges) {
+ copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
+ continue
+ }
+ var changes = event.changes, newChanges = [];
+ copy.push({changes: newChanges});
+ for (var j = 0; j < changes.length; ++j) {
+ var change = changes[j], m = (void 0);
+ newChanges.push({from: change.from, to: change.to, text: change.text});
+ if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
+ if (indexOf(newGroup, Number(m[1])) > -1) {
+ lst(newChanges)[prop] = change[prop];
+ delete change[prop];
+ }
+ } } }
+ }
+ }
+ return copy
+}
+
+// The 'scroll' parameter given to many of these indicated whether
+// the new cursor position should be scrolled into view after
+// modifying the selection.
+
+// If shift is held or the extend flag is set, extends a range to
+// include a given position (and optionally a second position).
+// Otherwise, simply returns the range between the given positions.
+// Used for cursor motion and such.
+function extendRange(range, head, other, extend) {
+ if (extend) {
+ var anchor = range.anchor;
+ if (other) {
+ var posBefore = cmp(head, anchor) < 0;
+ if (posBefore != (cmp(other, anchor) < 0)) {
+ anchor = head;
+ head = other;
+ } else if (posBefore != (cmp(head, other) < 0)) {
+ head = other;
+ }
+ }
+ return new Range(anchor, head)
+ } else {
+ return new Range(other || head, head)
+ }
+}
+
+// Extend the primary selection range, discard the rest.
+function extendSelection(doc, head, other, options, extend) {
+ if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
+ setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
+}
+
+// Extend all selections (pos is an array of selections with length
+// equal the number of selections)
+function extendSelections(doc, heads, options) {
+ var out = [];
+ var extend = doc.cm && (doc.cm.display.shift || doc.extend);
+ for (var i = 0; i < doc.sel.ranges.length; i++)
+ { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
+ var newSel = normalizeSelection(out, doc.sel.primIndex);
+ setSelection(doc, newSel, options);
+}
+
+// Updates a single range in the selection.
+function replaceOneSelection(doc, i, range, options) {
+ var ranges = doc.sel.ranges.slice(0);
+ ranges[i] = range;
+ setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
+}
+
+// Reset the selection to a single range.
+function setSimpleSelection(doc, anchor, head, options) {
+ setSelection(doc, simpleSelection(anchor, head), options);
+}
+
+// Give beforeSelectionChange handlers a change to influence a
+// selection update.
+function filterSelectionChange(doc, sel, options) {
+ var obj = {
+ ranges: sel.ranges,
+ update: function(ranges) {
+ var this$1 = this;
+
+ this.ranges = [];
+ for (var i = 0; i < ranges.length; i++)
+ { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
+ clipPos(doc, ranges[i].head)); }
+ },
+ origin: options && options.origin
+ };
+ signal(doc, "beforeSelectionChange", doc, obj);
+ if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
+ if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
+ else { return sel }
+}
+
+function setSelectionReplaceHistory(doc, sel, options) {
+ var done = doc.history.done, last = lst(done);
+ if (last && last.ranges) {
+ done[done.length - 1] = sel;
+ setSelectionNoUndo(doc, sel, options);
+ } else {
+ setSelection(doc, sel, options);
+ }
+}
+
+// Set a new selection.
+function setSelection(doc, sel, options) {
+ setSelectionNoUndo(doc, sel, options);
+ addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
+}
+
+function setSelectionNoUndo(doc, sel, options) {
+ if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
+ { sel = filterSelectionChange(doc, sel, options); }
+
+ var bias = options && options.bias ||
+ (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
+ setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
+
+ if (!(options && options.scroll === false) && doc.cm)
+ { ensureCursorVisible(doc.cm); }
+}
+
+function setSelectionInner(doc, sel) {
+ if (sel.equals(doc.sel)) { return }
+
+ doc.sel = sel;
+
+ if (doc.cm) {
+ doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
+ signalCursorActivity(doc.cm);
+ }
+ signalLater(doc, "cursorActivity", doc);
+}
+
+// Verify that the selection does not partially select any atomic
+// marked ranges.
+function reCheckSelection(doc) {
+ setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
+}
+
+// Return a selection that does not partially select any atomic
+// ranges.
+function skipAtomicInSelection(doc, sel, bias, mayClear) {
+ var out;
+ for (var i = 0; i < sel.ranges.length; i++) {
+ var range = sel.ranges[i];
+ var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
+ var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
+ var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
+ if (out || newAnchor != range.anchor || newHead != range.head) {
+ if (!out) { out = sel.ranges.slice(0, i); }
+ out[i] = new Range(newAnchor, newHead);
+ }
+ }
+ return out ? normalizeSelection(out, sel.primIndex) : sel
+}
+
+function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
+ var line = getLine(doc, pos.line);
+ if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
+ var sp = line.markedSpans[i], m = sp.marker;
+ if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
+ (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
+ if (mayClear) {
+ signal(m, "beforeCursorEnter");
+ if (m.explicitlyCleared) {
+ if (!line.markedSpans) { break }
+ else {--i; continue}
+ }
+ }
+ if (!m.atomic) { continue }
+
+ if (oldPos) {
+ var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
+ if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
+ { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
+ if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
+ { return skipAtomicInner(doc, near, pos, dir, mayClear) }
+ }
+
+ var far = m.find(dir < 0 ? -1 : 1);
+ if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
+ { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
+ return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
+ }
+ } }
+ return pos
+}
+
+// Ensure a given position is not inside an atomic range.
+function skipAtomic(doc, pos, oldPos, bias, mayClear) {
+ var dir = bias || 1;
+ var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
+ skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
+ if (!found) {
+ doc.cantEdit = true;
+ return Pos(doc.first, 0)
+ }
+ return found
+}
+
+function movePos(doc, pos, dir, line) {
+ if (dir < 0 && pos.ch == 0) {
+ if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
+ else { return null }
+ } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
+ if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
+ else { return null }
+ } else {
+ return new Pos(pos.line, pos.ch + dir)
+ }
+}
+
+function selectAll(cm) {
+ cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
+}
+
+// UPDATING
+
+// Allow "beforeChange" event handlers to influence a change
+function filterChange(doc, change, update) {
+ var obj = {
+ canceled: false,
+ from: change.from,
+ to: change.to,
+ text: change.text,
+ origin: change.origin,
+ cancel: function () { return obj.canceled = true; }
+ };
+ if (update) { obj.update = function (from, to, text, origin) {
+ if (from) { obj.from = clipPos(doc, from); }
+ if (to) { obj.to = clipPos(doc, to); }
+ if (text) { obj.text = text; }
+ if (origin !== undefined) { obj.origin = origin; }
+ }; }
+ signal(doc, "beforeChange", doc, obj);
+ if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
+
+ if (obj.canceled) { return null }
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
+}
+
+// Apply a change to a document, and add it to the document's
+// history, and propagating it to all linked documents.
+function makeChange(doc, change, ignoreReadOnly) {
+ if (doc.cm) {
+ if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
+ if (doc.cm.state.suppressEdits) { return }
+ }
+
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
+ change = filterChange(doc, change, true);
+ if (!change) { return }
+ }
+
+ // Possibly split or suppress the update based on the presence
+ // of read-only spans in its range.
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
+ if (split) {
+ for (var i = split.length - 1; i >= 0; --i)
+ { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
+ } else {
+ makeChangeInner(doc, change);
+ }
+}
+
+function makeChangeInner(doc, change) {
+ if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
+ var selAfter = computeSelAfterChange(doc, change);
+ addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
+
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
+ var rebased = [];
+
+ linkedDocs(doc, function (doc, sharedHist) {
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+ rebaseHist(doc.history, change);
+ rebased.push(doc.history);
+ }
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
+ });
+}
+
+// Revert a change stored in a document's history.
+function makeChangeFromHistory(doc, type, allowSelectionOnly) {
+ var suppress = doc.cm && doc.cm.state.suppressEdits;
+ if (suppress && !allowSelectionOnly) { return }
+
+ var hist = doc.history, event, selAfter = doc.sel;
+ var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
+
+ // Verify that there is a useable event (so that ctrl-z won't
+ // needlessly clear selection events)
+ var i = 0;
+ for (; i < source.length; i++) {
+ event = source[i];
+ if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
+ { break }
+ }
+ if (i == source.length) { return }
+ hist.lastOrigin = hist.lastSelOrigin = null;
+
+ for (;;) {
+ event = source.pop();
+ if (event.ranges) {
+ pushSelectionToHistory(event, dest);
+ if (allowSelectionOnly && !event.equals(doc.sel)) {
+ setSelection(doc, event, {clearRedo: false});
+ return
+ }
+ selAfter = event;
+ } else if (suppress) {
+ source.push(event);
+ return
+ } else { break }
+ }
+
+ // Build up a reverse change object to add to the opposite history
+ // stack (redo when undoing, and vice versa).
+ var antiChanges = [];
+ pushSelectionToHistory(selAfter, dest);
+ dest.push({changes: antiChanges, generation: hist.generation});
+ hist.generation = event.generation || ++hist.maxGeneration;
+
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
+
+ var loop = function ( i ) {
+ var change = event.changes[i];
+ change.origin = type;
+ if (filter && !filterChange(doc, change, false)) {
+ source.length = 0;
+ return {}
+ }
+
+ antiChanges.push(historyChangeFromChange(doc, change));
+
+ var after = i ? computeSelAfterChange(doc, change) : lst(source);
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
+ if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
+ var rebased = [];
+
+ // Propagate to the linked documents
+ linkedDocs(doc, function (doc, sharedHist) {
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
+ rebaseHist(doc.history, change);
+ rebased.push(doc.history);
+ }
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
+ });
+ };
+
+ for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
+ var returned = loop( i$1 );
+
+ if ( returned ) return returned.v;
+ }
+}
+
+// Sub-views need their line numbers shifted when text is added
+// above or below them in the parent document.
+function shiftDoc(doc, distance) {
+ if (distance == 0) { return }
+ doc.first += distance;
+ doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
+ Pos(range.anchor.line + distance, range.anchor.ch),
+ Pos(range.head.line + distance, range.head.ch)
+ ); }), doc.sel.primIndex);
+ if (doc.cm) {
+ regChange(doc.cm, doc.first, doc.first - distance, distance);
+ for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
+ { regLineChange(doc.cm, l, "gutter"); }
+ }
+}
+
+// More lower-level change function, handling only a single document
+// (not linked ones).
+function makeChangeSingleDoc(doc, change, selAfter, spans) {
+ if (doc.cm && !doc.cm.curOp)
+ { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
+
+ if (change.to.line < doc.first) {
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
+ return
+ }
+ if (change.from.line > doc.lastLine()) { return }
+
+ // Clip the change to the size of this doc
+ if (change.from.line < doc.first) {
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
+ shiftDoc(doc, shift);
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
+ text: [lst(change.text)], origin: change.origin};
+ }
+ var last = doc.lastLine();
+ if (change.to.line > last) {
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
+ text: [change.text[0]], origin: change.origin};
+ }
+
+ change.removed = getBetween(doc, change.from, change.to);
+
+ if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
+ if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
+ else { updateDoc(doc, change, spans); }
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
+}
+
+// Handle the interaction of a change to a document with the editor
+// that this document is part of.
+function makeChangeSingleDocInEditor(cm, change, spans) {
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
+
+ var recomputeMaxLength = false, checkWidthStart = from.line;
+ if (!cm.options.lineWrapping) {
+ checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
+ doc.iter(checkWidthStart, to.line + 1, function (line) {
+ if (line == display.maxLine) {
+ recomputeMaxLength = true;
+ return true
+ }
+ });
+ }
+
+ if (doc.sel.contains(change.from, change.to) > -1)
+ { signalCursorActivity(cm); }
+
+ updateDoc(doc, change, spans, estimateHeight(cm));
+
+ if (!cm.options.lineWrapping) {
+ doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
+ var len = lineLength(line);
+ if (len > display.maxLineLength) {
+ display.maxLine = line;
+ display.maxLineLength = len;
+ display.maxLineChanged = true;
+ recomputeMaxLength = false;
+ }
+ });
+ if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
+ }
+
+ retreatFrontier(doc, from.line);
+ startWorker(cm, 400);
+
+ var lendiff = change.text.length - (to.line - from.line) - 1;
+ // Remember that these lines changed, for updating the display
+ if (change.full)
+ { regChange(cm); }
+ else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
+ { regLineChange(cm, from.line, "text"); }
+ else
+ { regChange(cm, from.line, to.line + 1, lendiff); }
+
+ var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
+ if (changeHandler || changesHandler) {
+ var obj = {
+ from: from, to: to,
+ text: change.text,
+ removed: change.removed,
+ origin: change.origin
+ };
+ if (changeHandler) { signalLater(cm, "change", cm, obj); }
+ if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
+ }
+ cm.display.selForContextMenu = null;
+}
+
+function replaceRange(doc, code, from, to, origin) {
+ if (!to) { to = from; }
+ if (cmp(to, from) < 0) { var assign;
+ (assign = [to, from], from = assign[0], to = assign[1]); }
+ if (typeof code == "string") { code = doc.splitLines(code); }
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
+}
+
+// Rebasing/resetting history to deal with externally-sourced changes
+
+function rebaseHistSelSingle(pos, from, to, diff) {
+ if (to < pos.line) {
+ pos.line += diff;
+ } else if (from < pos.line) {
+ pos.line = from;
+ pos.ch = 0;
+ }
+}
+
+// Tries to rebase an array of history events given a change in the
+// document. If the change touches the same lines as the event, the
+// event, and everything 'behind' it, is discarded. If the change is
+// before the event, the event's positions are updated. Uses a
+// copy-on-write scheme for the positions, to avoid having to
+// reallocate them all on every rebase, but also avoid problems with
+// shared position objects being unsafely updated.
+function rebaseHistArray(array, from, to, diff) {
+ for (var i = 0; i < array.length; ++i) {
+ var sub = array[i], ok = true;
+ if (sub.ranges) {
+ if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
+ for (var j = 0; j < sub.ranges.length; j++) {
+ rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
+ rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
+ }
+ continue
+ }
+ for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
+ var cur = sub.changes[j$1];
+ if (to < cur.from.line) {
+ cur.from = Pos(cur.from.line + diff, cur.from.ch);
+ cur.to = Pos(cur.to.line + diff, cur.to.ch);
+ } else if (from <= cur.to.line) {
+ ok = false;
+ break
+ }
+ }
+ if (!ok) {
+ array.splice(0, i + 1);
+ i = 0;
+ }
+ }
+}
+
+function rebaseHist(hist, change) {
+ var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
+ rebaseHistArray(hist.done, from, to, diff);
+ rebaseHistArray(hist.undone, from, to, diff);
+}
+
+// Utility for applying a change to a line by handle or number,
+// returning the number and optionally registering the line as
+// changed.
+function changeLine(doc, handle, changeType, op) {
+ var no = handle, line = handle;
+ if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
+ else { no = lineNo(handle); }
+ if (no == null) { return null }
+ if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
+ return line
+}
+
+// The document is represented as a BTree consisting of leaves, with
+// chunk of lines in them, and branches, with up to ten leaves or
+// other branch nodes below them. The top node is always a branch
+// node, and is the document object itself (meaning it has
+// additional methods and properties).
+//
+// All nodes have parent links. The tree is used both to go from
+// line numbers to line objects, and to go from objects to numbers.
+// It also indexes by height, and is used to convert between height
+// and line object, and to find the total height of the document.
+//
+// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
+
+function LeafChunk(lines) {
+ var this$1 = this;
+
+ this.lines = lines;
+ this.parent = null;
+ var height = 0;
+ for (var i = 0; i < lines.length; ++i) {
+ lines[i].parent = this$1;
+ height += lines[i].height;
+ }
+ this.height = height;
+}
+
+LeafChunk.prototype = {
+ chunkSize: function() { return this.lines.length },
+
+ // Remove the n lines at offset 'at'.
+ removeInner: function(at, n) {
+ var this$1 = this;
+
+ for (var i = at, e = at + n; i < e; ++i) {
+ var line = this$1.lines[i];
+ this$1.height -= line.height;
+ cleanUpLine(line);
+ signalLater(line, "delete");
+ }
+ this.lines.splice(at, n);
+ },
+
+ // Helper used to collapse a small branch into a single leaf.
+ collapse: function(lines) {
+ lines.push.apply(lines, this.lines);
+ },
+
+ // Insert the given array of lines at offset 'at', count them as
+ // having the given height.
+ insertInner: function(at, lines, height) {
+ var this$1 = this;
+
+ this.height += height;
+ this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
+ for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
+ },
+
+ // Used to iterate over a part of the tree.
+ iterN: function(at, n, op) {
+ var this$1 = this;
+
+ for (var e = at + n; at < e; ++at)
+ { if (op(this$1.lines[at])) { return true } }
+ }
+};
+
+function BranchChunk(children) {
+ var this$1 = this;
+
+ this.children = children;
+ var size = 0, height = 0;
+ for (var i = 0; i < children.length; ++i) {
+ var ch = children[i];
+ size += ch.chunkSize(); height += ch.height;
+ ch.parent = this$1;
+ }
+ this.size = size;
+ this.height = height;
+ this.parent = null;
+}
+
+BranchChunk.prototype = {
+ chunkSize: function() { return this.size },
+
+ removeInner: function(at, n) {
+ var this$1 = this;
+
+ this.size -= n;
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this$1.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
+ child.removeInner(at, rm);
+ this$1.height -= oldHeight - child.height;
+ if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
+ if ((n -= rm) == 0) { break }
+ at = 0;
+ } else { at -= sz; }
+ }
+ // If the result is smaller than 25 lines, ensure that it is a
+ // single leaf node.
+ if (this.size - n < 25 &&
+ (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
+ var lines = [];
+ this.collapse(lines);
+ this.children = [new LeafChunk(lines)];
+ this.children[0].parent = this;
+ }
+ },
+
+ collapse: function(lines) {
+ var this$1 = this;
+
+ for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
+ },
+
+ insertInner: function(at, lines, height) {
+ var this$1 = this;
+
+ this.size += lines.length;
+ this.height += height;
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this$1.children[i], sz = child.chunkSize();
+ if (at <= sz) {
+ child.insertInner(at, lines, height);
+ if (child.lines && child.lines.length > 50) {
+ // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
+ // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
+ var remaining = child.lines.length % 25 + 25;
+ for (var pos = remaining; pos < child.lines.length;) {
+ var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
+ child.height -= leaf.height;
+ this$1.children.splice(++i, 0, leaf);
+ leaf.parent = this$1;
+ }
+ child.lines = child.lines.slice(0, remaining);
+ this$1.maybeSpill();
+ }
+ break
+ }
+ at -= sz;
+ }
+ },
+
+ // When a node has grown, check whether it should be split.
+ maybeSpill: function() {
+ if (this.children.length <= 10) { return }
+ var me = this;
+ do {
+ var spilled = me.children.splice(me.children.length - 5, 5);
+ var sibling = new BranchChunk(spilled);
+ if (!me.parent) { // Become the parent node
+ var copy = new BranchChunk(me.children);
+ copy.parent = me;
+ me.children = [copy, sibling];
+ me = copy;
+ } else {
+ me.size -= sibling.size;
+ me.height -= sibling.height;
+ var myIndex = indexOf(me.parent.children, me);
+ me.parent.children.splice(myIndex + 1, 0, sibling);
+ }
+ sibling.parent = me.parent;
+ } while (me.children.length > 10)
+ me.parent.maybeSpill();
+ },
+
+ iterN: function(at, n, op) {
+ var this$1 = this;
+
+ for (var i = 0; i < this.children.length; ++i) {
+ var child = this$1.children[i], sz = child.chunkSize();
+ if (at < sz) {
+ var used = Math.min(n, sz - at);
+ if (child.iterN(at, used, op)) { return true }
+ if ((n -= used) == 0) { break }
+ at = 0;
+ } else { at -= sz; }
+ }
+ }
+};
+
+// Line widgets are block elements displayed above or below a line.
+
+var LineWidget = function(doc, node, options) {
+ var this$1 = this;
+
+ if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
+ { this$1[opt] = options[opt]; } } }
+ this.doc = doc;
+ this.node = node;
+};
+
+LineWidget.prototype.clear = function () {
+ var this$1 = this;
+
+ var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
+ if (no == null || !ws) { return }
+ for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
+ if (!ws.length) { line.widgets = null; }
+ var height = widgetHeight(this);
+ updateLineHeight(line, Math.max(0, line.height - height));
+ if (cm) {
+ runInOp(cm, function () {
+ adjustScrollWhenAboveVisible(cm, line, -height);
+ regLineChange(cm, no, "widget");
+ });
+ signalLater(cm, "lineWidgetCleared", cm, this, no);
+ }
+};
+
+LineWidget.prototype.changed = function () {
+ var this$1 = this;
+
+ var oldH = this.height, cm = this.doc.cm, line = this.line;
+ this.height = null;
+ var diff = widgetHeight(this) - oldH;
+ if (!diff) { return }
+ updateLineHeight(line, line.height + diff);
+ if (cm) {
+ runInOp(cm, function () {
+ cm.curOp.forceUpdate = true;
+ adjustScrollWhenAboveVisible(cm, line, diff);
+ signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
+ });
+ }
+};
+eventMixin(LineWidget);
+
+function adjustScrollWhenAboveVisible(cm, line, diff) {
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
+ { addToScrollTop(cm, diff); }
+}
+
+function addLineWidget(doc, handle, node, options) {
+ var widget = new LineWidget(doc, node, options);
+ var cm = doc.cm;
+ if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
+ changeLine(doc, handle, "widget", function (line) {
+ var widgets = line.widgets || (line.widgets = []);
+ if (widget.insertAt == null) { widgets.push(widget); }
+ else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
+ widget.line = line;
+ if (cm && !lineIsHidden(doc, line)) {
+ var aboveVisible = heightAtLine(line) < doc.scrollTop;
+ updateLineHeight(line, line.height + widgetHeight(widget));
+ if (aboveVisible) { addToScrollTop(cm, widget.height); }
+ cm.curOp.forceUpdate = true;
+ }
+ return true
+ });
+ if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
+ return widget
+}
+
+// TEXTMARKERS
+
+// Created with markText and setBookmark methods. A TextMarker is a
+// handle that can be used to clear or find a marked position in the
+// document. Line objects hold arrays (markedSpans) containing
+// {from, to, marker} object pointing to such marker objects, and
+// indicating that such a marker is present on that line. Multiple
+// lines may point to the same marker when it spans across lines.
+// The spans will have null for their from/to properties when the
+// marker continues beyond the start/end of the line. Markers have
+// links back to the lines they currently touch.
+
+// Collapsed markers have unique ids, in order to be able to order
+// them, which is needed for uniquely determining an outer marker
+// when they overlap (they may nest, but not partially overlap).
+var nextMarkerId = 0;
+
+var TextMarker = function(doc, type) {
+ this.lines = [];
+ this.type = type;
+ this.doc = doc;
+ this.id = ++nextMarkerId;
+};
+
+// Clear the marker.
+TextMarker.prototype.clear = function () {
+ var this$1 = this;
+
+ if (this.explicitlyCleared) { return }
+ var cm = this.doc.cm, withOp = cm && !cm.curOp;
+ if (withOp) { startOperation(cm); }
+ if (hasHandler(this, "clear")) {
+ var found = this.find();
+ if (found) { signalLater(this, "clear", found.from, found.to); }
+ }
+ var min = null, max = null;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this$1.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this$1);
+ if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
+ else if (cm) {
+ if (span.to != null) { max = lineNo(line); }
+ if (span.from != null) { min = lineNo(line); }
+ }
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
+ if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
+ { updateLineHeight(line, textHeight(cm.display)); }
+ }
+ if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
+ var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
+ if (len > cm.display.maxLineLength) {
+ cm.display.maxLine = visual;
+ cm.display.maxLineLength = len;
+ cm.display.maxLineChanged = true;
+ }
+ } }
+
+ if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
+ this.lines.length = 0;
+ this.explicitlyCleared = true;
+ if (this.atomic && this.doc.cantEdit) {
+ this.doc.cantEdit = false;
+ if (cm) { reCheckSelection(cm.doc); }
+ }
+ if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
+ if (withOp) { endOperation(cm); }
+ if (this.parent) { this.parent.clear(); }
+};
+
+// Find the position of the marker in the document. Returns a {from,
+// to} object by default. Side can be passed to get a specific side
+// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
+// Pos objects returned contain a line object, rather than a line
+// number (used to prevent looking up the same line twice).
+TextMarker.prototype.find = function (side, lineObj) {
+ var this$1 = this;
+
+ if (side == null && this.type == "bookmark") { side = 1; }
+ var from, to;
+ for (var i = 0; i < this.lines.length; ++i) {
+ var line = this$1.lines[i];
+ var span = getMarkedSpanFor(line.markedSpans, this$1);
+ if (span.from != null) {
+ from = Pos(lineObj ? line : lineNo(line), span.from);
+ if (side == -1) { return from }
+ }
+ if (span.to != null) {
+ to = Pos(lineObj ? line : lineNo(line), span.to);
+ if (side == 1) { return to }
+ }
+ }
+ return from && {from: from, to: to}
+};
+
+// Signals that the marker's widget changed, and surrounding layout
+// should be recomputed.
+TextMarker.prototype.changed = function () {
+ var this$1 = this;
+
+ var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
+ if (!pos || !cm) { return }
+ runInOp(cm, function () {
+ var line = pos.line, lineN = lineNo(pos.line);
+ var view = findViewForLine(cm, lineN);
+ if (view) {
+ clearLineMeasurementCacheFor(view);
+ cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
+ }
+ cm.curOp.updateMaxLine = true;
+ if (!lineIsHidden(widget.doc, line) && widget.height != null) {
+ var oldHeight = widget.height;
+ widget.height = null;
+ var dHeight = widgetHeight(widget) - oldHeight;
+ if (dHeight)
+ { updateLineHeight(line, line.height + dHeight); }
+ }
+ signalLater(cm, "markerChanged", cm, this$1);
+ });
+};
+
+TextMarker.prototype.attachLine = function (line) {
+ if (!this.lines.length && this.doc.cm) {
+ var op = this.doc.cm.curOp;
+ if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
+ { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
+ }
+ this.lines.push(line);
+};
+
+TextMarker.prototype.detachLine = function (line) {
+ this.lines.splice(indexOf(this.lines, line), 1);
+ if (!this.lines.length && this.doc.cm) {
+ var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
+ }
+};
+eventMixin(TextMarker);
+
+// Create a marker, wire it up to the right lines, and
+function markText(doc, from, to, options, type) {
+ // Shared markers (across linked documents) are handled separately
+ // (markTextShared will call out to this again, once per
+ // document).
+ if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
+ // Ensure we are in an operation.
+ if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
+
+ var marker = new TextMarker(doc, type), diff = cmp(from, to);
+ if (options) { copyObj(options, marker, false); }
+ // Don't connect empty markers unless clearWhenEmpty is false
+ if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
+ { return marker }
+ if (marker.replacedWith) {
+ // Showing up as a widget implies collapsed (widget replaces text)
+ marker.collapsed = true;
+ marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
+ if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
+ if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
+ }
+ if (marker.collapsed) {
+ if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
+ from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
+ { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
+ seeCollapsedSpans();
+ }
+
+ if (marker.addToHistory)
+ { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
+
+ var curLine = from.line, cm = doc.cm, updateMaxLine;
+ doc.iter(curLine, to.line + 1, function (line) {
+ if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
+ { updateMaxLine = true; }
+ if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
+ addMarkedSpan(line, new MarkedSpan(marker,
+ curLine == from.line ? from.ch : null,
+ curLine == to.line ? to.ch : null));
+ ++curLine;
+ });
+ // lineIsHidden depends on the presence of the spans, so needs a second pass
+ if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
+ if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
+ }); }
+
+ if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
+
+ if (marker.readOnly) {
+ seeReadOnlySpans();
+ if (doc.history.done.length || doc.history.undone.length)
+ { doc.clearHistory(); }
+ }
+ if (marker.collapsed) {
+ marker.id = ++nextMarkerId;
+ marker.atomic = true;
+ }
+ if (cm) {
+ // Sync editor state
+ if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
+ if (marker.collapsed)
+ { regChange(cm, from.line, to.line + 1); }
+ else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
+ { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
+ if (marker.atomic) { reCheckSelection(cm.doc); }
+ signalLater(cm, "markerAdded", cm, marker);
+ }
+ return marker
+}
+
+// SHARED TEXTMARKERS
+
+// A shared marker spans multiple linked documents. It is
+// implemented as a meta-marker-object controlling multiple normal
+// markers.
+var SharedTextMarker = function(markers, primary) {
+ var this$1 = this;
+
+ this.markers = markers;
+ this.primary = primary;
+ for (var i = 0; i < markers.length; ++i)
+ { markers[i].parent = this$1; }
+};
+
+SharedTextMarker.prototype.clear = function () {
+ var this$1 = this;
+
+ if (this.explicitlyCleared) { return }
+ this.explicitlyCleared = true;
+ for (var i = 0; i < this.markers.length; ++i)
+ { this$1.markers[i].clear(); }
+ signalLater(this, "clear");
+};
+
+SharedTextMarker.prototype.find = function (side, lineObj) {
+ return this.primary.find(side, lineObj)
+};
+eventMixin(SharedTextMarker);
+
+function markTextShared(doc, from, to, options, type) {
+ options = copyObj(options);
+ options.shared = false;
+ var markers = [markText(doc, from, to, options, type)], primary = markers[0];
+ var widget = options.widgetNode;
+ linkedDocs(doc, function (doc) {
+ if (widget) { options.widgetNode = widget.cloneNode(true); }
+ markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
+ for (var i = 0; i < doc.linked.length; ++i)
+ { if (doc.linked[i].isParent) { return } }
+ primary = lst(markers);
+ });
+ return new SharedTextMarker(markers, primary)
+}
+
+function findSharedMarkers(doc) {
+ return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
+}
+
+function copySharedMarkers(doc, markers) {
+ for (var i = 0; i < markers.length; i++) {
+ var marker = markers[i], pos = marker.find();
+ var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
+ if (cmp(mFrom, mTo)) {
+ var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
+ marker.markers.push(subMark);
+ subMark.parent = marker;
+ }
+ }
+}
+
+function detachSharedMarkers(markers) {
+ var loop = function ( i ) {
+ var marker = markers[i], linked = [marker.primary.doc];
+ linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
+ for (var j = 0; j < marker.markers.length; j++) {
+ var subMarker = marker.markers[j];
+ if (indexOf(linked, subMarker.doc) == -1) {
+ subMarker.parent = null;
+ marker.markers.splice(j--, 1);
+ }
+ }
+ };
+
+ for (var i = 0; i < markers.length; i++) loop( i );
+}
+
+var nextDocId = 0;
+var Doc = function(text, mode, firstLine, lineSep, direction) {
+ if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
+ if (firstLine == null) { firstLine = 0; }
+
+ BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
+ this.first = firstLine;
+ this.scrollTop = this.scrollLeft = 0;
+ this.cantEdit = false;
+ this.cleanGeneration = 1;
+ this.modeFrontier = this.highlightFrontier = firstLine;
+ var start = Pos(firstLine, 0);
+ this.sel = simpleSelection(start);
+ this.history = new History(null);
+ this.id = ++nextDocId;
+ this.modeOption = mode;
+ this.lineSep = lineSep;
+ this.direction = (direction == "rtl") ? "rtl" : "ltr";
+ this.extend = false;
+
+ if (typeof text == "string") { text = this.splitLines(text); }
+ updateDoc(this, {from: start, to: start, text: text});
+ setSelection(this, simpleSelection(start), sel_dontScroll);
+};
+
+Doc.prototype = createObj(BranchChunk.prototype, {
+ constructor: Doc,
+ // Iterate over the document. Supports two forms -- with only one
+ // argument, it calls that for each line in the document. With
+ // three, it iterates over the range given by the first two (with
+ // the second being non-inclusive).
+ iter: function(from, to, op) {
+ if (op) { this.iterN(from - this.first, to - from, op); }
+ else { this.iterN(this.first, this.first + this.size, from); }
+ },
+
+ // Non-public interface for adding and removing lines.
+ insert: function(at, lines) {
+ var height = 0;
+ for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
+ this.insertInner(at - this.first, lines, height);
+ },
+ remove: function(at, n) { this.removeInner(at - this.first, n); },
+
+ // From here, the methods are part of the public interface. Most
+ // are also available from CodeMirror (editor) instances.
+
+ getValue: function(lineSep) {
+ var lines = getLines(this, this.first, this.first + this.size);
+ if (lineSep === false) { return lines }
+ return lines.join(lineSep || this.lineSeparator())
+ },
+ setValue: docMethodOp(function(code) {
+ var top = Pos(this.first, 0), last = this.first + this.size - 1;
+ makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
+ text: this.splitLines(code), origin: "setValue", full: true}, true);
+ if (this.cm) { scrollToCoords(this.cm, 0, 0); }
+ setSelection(this, simpleSelection(top), sel_dontScroll);
+ }),
+ replaceRange: function(code, from, to, origin) {
+ from = clipPos(this, from);
+ to = to ? clipPos(this, to) : from;
+ replaceRange(this, code, from, to, origin);
+ },
+ getRange: function(from, to, lineSep) {
+ var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
+ if (lineSep === false) { return lines }
+ return lines.join(lineSep || this.lineSeparator())
+ },
+
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
+
+ getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
+ getLineNumber: function(line) {return lineNo(line)},
+
+ getLineHandleVisualStart: function(line) {
+ if (typeof line == "number") { line = getLine(this, line); }
+ return visualLine(line)
+ },
+
+ lineCount: function() {return this.size},
+ firstLine: function() {return this.first},
+ lastLine: function() {return this.first + this.size - 1},
+
+ clipPos: function(pos) {return clipPos(this, pos)},
+
+ getCursor: function(start) {
+ var range$$1 = this.sel.primary(), pos;
+ if (start == null || start == "head") { pos = range$$1.head; }
+ else if (start == "anchor") { pos = range$$1.anchor; }
+ else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
+ else { pos = range$$1.from(); }
+ return pos
+ },
+ listSelections: function() { return this.sel.ranges },
+ somethingSelected: function() {return this.sel.somethingSelected()},
+
+ setCursor: docMethodOp(function(line, ch, options) {
+ setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
+ }),
+ setSelection: docMethodOp(function(anchor, head, options) {
+ setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
+ }),
+ extendSelection: docMethodOp(function(head, other, options) {
+ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
+ }),
+ extendSelections: docMethodOp(function(heads, options) {
+ extendSelections(this, clipPosArray(this, heads), options);
+ }),
+ extendSelectionsBy: docMethodOp(function(f, options) {
+ var heads = map(this.sel.ranges, f);
+ extendSelections(this, clipPosArray(this, heads), options);
+ }),
+ setSelections: docMethodOp(function(ranges, primary, options) {
+ var this$1 = this;
+
+ if (!ranges.length) { return }
+ var out = [];
+ for (var i = 0; i < ranges.length; i++)
+ { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
+ clipPos(this$1, ranges[i].head)); }
+ if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
+ setSelection(this, normalizeSelection(out, primary), options);
+ }),
+ addSelection: docMethodOp(function(anchor, head, options) {
+ var ranges = this.sel.ranges.slice(0);
+ ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
+ setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
+ }),
+
+ getSelection: function(lineSep) {
+ var this$1 = this;
+
+ var ranges = this.sel.ranges, lines;
+ for (var i = 0; i < ranges.length; i++) {
+ var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
+ lines = lines ? lines.concat(sel) : sel;
+ }
+ if (lineSep === false) { return lines }
+ else { return lines.join(lineSep || this.lineSeparator()) }
+ },
+ getSelections: function(lineSep) {
+ var this$1 = this;
+
+ var parts = [], ranges = this.sel.ranges;
+ for (var i = 0; i < ranges.length; i++) {
+ var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
+ if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
+ parts[i] = sel;
+ }
+ return parts
+ },
+ replaceSelection: function(code, collapse, origin) {
+ var dup = [];
+ for (var i = 0; i < this.sel.ranges.length; i++)
+ { dup[i] = code; }
+ this.replaceSelections(dup, collapse, origin || "+input");
+ },
+ replaceSelections: docMethodOp(function(code, collapse, origin) {
+ var this$1 = this;
+
+ var changes = [], sel = this.sel;
+ for (var i = 0; i < sel.ranges.length; i++) {
+ var range$$1 = sel.ranges[i];
+ changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
+ }
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
+ for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
+ { makeChange(this$1, changes[i$1]); }
+ if (newSel) { setSelectionReplaceHistory(this, newSel); }
+ else if (this.cm) { ensureCursorVisible(this.cm); }
+ }),
+ undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
+ redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
+ undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
+ redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
+
+ setExtending: function(val) {this.extend = val;},
+ getExtending: function() {return this.extend},
+
+ historySize: function() {
+ var hist = this.history, done = 0, undone = 0;
+ for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
+ for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
+ return {undo: done, redo: undone}
+ },
+ clearHistory: function() {this.history = new History(this.history.maxGeneration);},
+
+ markClean: function() {
+ this.cleanGeneration = this.changeGeneration(true);
+ },
+ changeGeneration: function(forceSplit) {
+ if (forceSplit)
+ { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
+ return this.history.generation
+ },
+ isClean: function (gen) {
+ return this.history.generation == (gen || this.cleanGeneration)
+ },
+
+ getHistory: function() {
+ return {done: copyHistoryArray(this.history.done),
+ undone: copyHistoryArray(this.history.undone)}
+ },
+ setHistory: function(histData) {
+ var hist = this.history = new History(this.history.maxGeneration);
+ hist.done = copyHistoryArray(histData.done.slice(0), null, true);
+ hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
+ },
+
+ setGutterMarker: docMethodOp(function(line, gutterID, value) {
+ return changeLine(this, line, "gutter", function (line) {
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
+ markers[gutterID] = value;
+ if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
+ return true
+ })
+ }),
+
+ clearGutter: docMethodOp(function(gutterID) {
+ var this$1 = this;
+
+ this.iter(function (line) {
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
+ changeLine(this$1, line, "gutter", function () {
+ line.gutterMarkers[gutterID] = null;
+ if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
+ return true
+ });
+ }
+ });
+ }),
+
+ lineInfo: function(line) {
+ var n;
+ if (typeof line == "number") {
+ if (!isLine(this, line)) { return null }
+ n = line;
+ line = getLine(this, line);
+ if (!line) { return null }
+ } else {
+ n = lineNo(line);
+ if (n == null) { return null }
+ }
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
+ widgets: line.widgets}
+ },
+
+ addLineClass: docMethodOp(function(handle, where, cls) {
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
+ var prop = where == "text" ? "textClass"
+ : where == "background" ? "bgClass"
+ : where == "gutter" ? "gutterClass" : "wrapClass";
+ if (!line[prop]) { line[prop] = cls; }
+ else if (classTest(cls).test(line[prop])) { return false }
+ else { line[prop] += " " + cls; }
+ return true
+ })
+ }),
+ removeLineClass: docMethodOp(function(handle, where, cls) {
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
+ var prop = where == "text" ? "textClass"
+ : where == "background" ? "bgClass"
+ : where == "gutter" ? "gutterClass" : "wrapClass";
+ var cur = line[prop];
+ if (!cur) { return false }
+ else if (cls == null) { line[prop] = null; }
+ else {
+ var found = cur.match(classTest(cls));
+ if (!found) { return false }
+ var end = found.index + found[0].length;
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
+ }
+ return true
+ })
+ }),
+
+ addLineWidget: docMethodOp(function(handle, node, options) {
+ return addLineWidget(this, handle, node, options)
+ }),
+ removeLineWidget: function(widget) { widget.clear(); },
+
+ markText: function(from, to, options) {
+ return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
+ },
+ setBookmark: function(pos, options) {
+ var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
+ insertLeft: options && options.insertLeft,
+ clearWhenEmpty: false, shared: options && options.shared,
+ handleMouseEvents: options && options.handleMouseEvents};
+ pos = clipPos(this, pos);
+ return markText(this, pos, pos, realOpts, "bookmark")
+ },
+ findMarksAt: function(pos) {
+ pos = clipPos(this, pos);
+ var markers = [], spans = getLine(this, pos.line).markedSpans;
+ if (spans) { for (var i = 0; i < spans.length; ++i) {
+ var span = spans[i];
+ if ((span.from == null || span.from <= pos.ch) &&
+ (span.to == null || span.to >= pos.ch))
+ { markers.push(span.marker.parent || span.marker); }
+ } }
+ return markers
+ },
+ findMarks: function(from, to, filter) {
+ from = clipPos(this, from); to = clipPos(this, to);
+ var found = [], lineNo$$1 = from.line;
+ this.iter(from.line, to.line + 1, function (line) {
+ var spans = line.markedSpans;
+ if (spans) { for (var i = 0; i < spans.length; i++) {
+ var span = spans[i];
+ if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
+ span.from == null && lineNo$$1 != from.line ||
+ span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
+ (!filter || filter(span.marker)))
+ { found.push(span.marker.parent || span.marker); }
+ } }
+ ++lineNo$$1;
+ });
+ return found
+ },
+ getAllMarks: function() {
+ var markers = [];
+ this.iter(function (line) {
+ var sps = line.markedSpans;
+ if (sps) { for (var i = 0; i < sps.length; ++i)
+ { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
+ });
+ return markers
+ },
+
+ posFromIndex: function(off) {
+ var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
+ this.iter(function (line) {
+ var sz = line.text.length + sepSize;
+ if (sz > off) { ch = off; return true }
+ off -= sz;
+ ++lineNo$$1;
+ });
+ return clipPos(this, Pos(lineNo$$1, ch))
+ },
+ indexFromPos: function (coords) {
+ coords = clipPos(this, coords);
+ var index = coords.ch;
+ if (coords.line < this.first || coords.ch < 0) { return 0 }
+ var sepSize = this.lineSeparator().length;
+ this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
+ index += line.text.length + sepSize;
+ });
+ return index
+ },
+
+ copy: function(copyHistory) {
+ var doc = new Doc(getLines(this, this.first, this.first + this.size),
+ this.modeOption, this.first, this.lineSep, this.direction);
+ doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
+ doc.sel = this.sel;
+ doc.extend = false;
+ if (copyHistory) {
+ doc.history.undoDepth = this.history.undoDepth;
+ doc.setHistory(this.getHistory());
+ }
+ return doc
+ },
+
+ linkedDoc: function(options) {
+ if (!options) { options = {}; }
+ var from = this.first, to = this.first + this.size;
+ if (options.from != null && options.from > from) { from = options.from; }
+ if (options.to != null && options.to < to) { to = options.to; }
+ var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
+ if (options.sharedHist) { copy.history = this.history
+ ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
+ copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
+ copySharedMarkers(copy, findSharedMarkers(this));
+ return copy
+ },
+ unlinkDoc: function(other) {
+ var this$1 = this;
+
+ if (other instanceof CodeMirror$1) { other = other.doc; }
+ if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
+ var link = this$1.linked[i];
+ if (link.doc != other) { continue }
+ this$1.linked.splice(i, 1);
+ other.unlinkDoc(this$1);
+ detachSharedMarkers(findSharedMarkers(this$1));
+ break
+ } }
+ // If the histories were shared, split them again
+ if (other.history == this.history) {
+ var splitIds = [other.id];
+ linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
+ other.history = new History(null);
+ other.history.done = copyHistoryArray(this.history.done, splitIds);
+ other.history.undone = copyHistoryArray(this.history.undone, splitIds);
+ }
+ },
+ iterLinkedDocs: function(f) {linkedDocs(this, f);},
+
+ getMode: function() {return this.mode},
+ getEditor: function() {return this.cm},
+
+ splitLines: function(str) {
+ if (this.lineSep) { return str.split(this.lineSep) }
+ return splitLinesAuto(str)
+ },
+ lineSeparator: function() { return this.lineSep || "\n" },
+
+ setDirection: docMethodOp(function (dir) {
+ if (dir != "rtl") { dir = "ltr"; }
+ if (dir == this.direction) { return }
+ this.direction = dir;
+ this.iter(function (line) { return line.order = null; });
+ if (this.cm) { directionChanged(this.cm); }
+ })
+});
+
+// Public alias.
+Doc.prototype.eachLine = Doc.prototype.iter;
+
+// Kludge to work around strange IE behavior where it'll sometimes
+// re-fire a series of drag-related events right after the drop (#1551)
+var lastDrop = 0;
+
+function onDrop(e) {
+ var cm = this;
+ clearDragCursor(cm);
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
+ { return }
+ e_preventDefault(e);
+ if (ie) { lastDrop = +new Date; }
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
+ if (!pos || cm.isReadOnly()) { return }
+ // Might be a file drop, in which case we simply extract the text
+ // and insert it.
+ if (files && files.length && window.FileReader && window.File) {
+ var n = files.length, text = Array(n), read = 0;
+ var loadFile = function (file, i) {
+ if (cm.options.allowDropFileTypes &&
+ indexOf(cm.options.allowDropFileTypes, file.type) == -1)
+ { return }
+
+ var reader = new FileReader;
+ reader.onload = operation(cm, function () {
+ var content = reader.result;
+ if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
+ text[i] = content;
+ if (++read == n) {
+ pos = clipPos(cm.doc, pos);
+ var change = {from: pos, to: pos,
+ text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
+ origin: "paste"};
+ makeChange(cm.doc, change);
+ setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
+ }
+ });
+ reader.readAsText(file);
+ };
+ for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
+ } else { // Normal drop
+ // Don't do a replace if the drop happened inside of the selected text.
+ if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
+ cm.state.draggingText(e);
+ // Ensure the editor is re-focused
+ setTimeout(function () { return cm.display.input.focus(); }, 20);
+ return
+ }
+ try {
+ var text$1 = e.dataTransfer.getData("Text");
+ if (text$1) {
+ var selected;
+ if (cm.state.draggingText && !cm.state.draggingText.copy)
+ { selected = cm.listSelections(); }
+ setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
+ if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
+ { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
+ cm.replaceSelection(text$1, "around", "paste");
+ cm.display.input.focus();
+ }
+ }
+ catch(e){}
+ }
+}
+
+function onDragStart(cm, e) {
+ if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
+
+ e.dataTransfer.setData("Text", cm.getSelection());
+ e.dataTransfer.effectAllowed = "copyMove";
+
+ // Use dummy image instead of default browsers image.
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
+ if (e.dataTransfer.setDragImage && !safari) {
+ var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
+ img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
+ if (presto) {
+ img.width = img.height = 1;
+ cm.display.wrapper.appendChild(img);
+ // Force a relayout, or Opera won't use our image for some obscure reason
+ img._top = img.offsetTop;
+ }
+ e.dataTransfer.setDragImage(img, 0, 0);
+ if (presto) { img.parentNode.removeChild(img); }
+ }
+}
+
+function onDragOver(cm, e) {
+ var pos = posFromMouse(cm, e);
+ if (!pos) { return }
+ var frag = document.createDocumentFragment();
+ drawSelectionCursor(cm, pos, frag);
+ if (!cm.display.dragCursor) {
+ cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
+ cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
+ }
+ removeChildrenAndAdd(cm.display.dragCursor, frag);
+}
+
+function clearDragCursor(cm) {
+ if (cm.display.dragCursor) {
+ cm.display.lineSpace.removeChild(cm.display.dragCursor);
+ cm.display.dragCursor = null;
+ }
+}
+
+// These must be handled carefully, because naively registering a
+// handler for each editor will cause the editors to never be
+// garbage collected.
+
+function forEachCodeMirror(f) {
+ if (!document.getElementsByClassName) { return }
+ var byClass = document.getElementsByClassName("CodeMirror");
+ for (var i = 0; i < byClass.length; i++) {
+ var cm = byClass[i].CodeMirror;
+ if (cm) { f(cm); }
+ }
+}
+
+var globalsRegistered = false;
+function ensureGlobalHandlers() {
+ if (globalsRegistered) { return }
+ registerGlobalHandlers();
+ globalsRegistered = true;
+}
+function registerGlobalHandlers() {
+ // When the window resizes, we need to refresh active editors.
+ var resizeTimer;
+ on(window, "resize", function () {
+ if (resizeTimer == null) { resizeTimer = setTimeout(function () {
+ resizeTimer = null;
+ forEachCodeMirror(onResize);
+ }, 100); }
+ });
+ // When the window loses focus, we want to show the editor as blurred
+ on(window, "blur", function () { return forEachCodeMirror(onBlur); });
+}
+// Called when the window resizes
+function onResize(cm) {
+ var d = cm.display;
+ if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
+ { return }
+ // Might be a text scaling operation, clear size caches.
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
+ d.scrollbarsClipped = false;
+ cm.setSize();
+}
+
+var keyNames = {
+ 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
+ 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
+ 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 145: "ScrollLock",
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
+ 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
+};
+
+// Number keys
+for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
+// Alphabetic keys
+for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
+// Function keys
+for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
+
+var keyMap = {};
+
+keyMap.basic = {
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
+ "Tab": "defaultTab", "Shift-Tab": "indentAuto",
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
+ "Esc": "singleSelection"
+};
+// Note that the save and find-related commands aren't defined by
+// default. User code or addons can define them. Unknown commands
+// are simply ignored.
+keyMap.pcDefault = {
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
+ "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
+ "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
+ "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
+ "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
+ fallthrough: "basic"
+};
+// Very basic readline/emacs-style bindings, which are standard on Mac.
+keyMap.emacsy = {
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
+ "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
+ "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
+ "Ctrl-O": "openLine"
+};
+keyMap.macDefault = {
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
+ "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
+ "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
+ fallthrough: ["basic", "emacsy"]
+};
+keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
+
+// KEYMAP DISPATCH
+
+function normalizeKeyName(name) {
+ var parts = name.split(/-(?!$)/);
+ name = parts[parts.length - 1];
+ var alt, ctrl, shift, cmd;
+ for (var i = 0; i < parts.length - 1; i++) {
+ var mod = parts[i];
+ if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
+ else if (/^a(lt)?$/i.test(mod)) { alt = true; }
+ else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
+ else if (/^s(hift)?$/i.test(mod)) { shift = true; }
+ else { throw new Error("Unrecognized modifier name: " + mod) }
+ }
+ if (alt) { name = "Alt-" + name; }
+ if (ctrl) { name = "Ctrl-" + name; }
+ if (cmd) { name = "Cmd-" + name; }
+ if (shift) { name = "Shift-" + name; }
+ return name
+}
+
+// This is a kludge to keep keymaps mostly working as raw objects
+// (backwards compatibility) while at the same time support features
+// like normalization and multi-stroke key bindings. It compiles a
+// new normalized keymap, and then updates the old object to reflect
+// this.
+function normalizeKeyMap(keymap) {
+ var copy = {};
+ for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
+ var value = keymap[keyname];
+ if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
+ if (value == "...") { delete keymap[keyname]; continue }
+
+ var keys = map(keyname.split(" "), normalizeKeyName);
+ for (var i = 0; i < keys.length; i++) {
+ var val = (void 0), name = (void 0);
+ if (i == keys.length - 1) {
+ name = keys.join(" ");
+ val = value;
+ } else {
+ name = keys.slice(0, i + 1).join(" ");
+ val = "...";
+ }
+ var prev = copy[name];
+ if (!prev) { copy[name] = val; }
+ else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
+ }
+ delete keymap[keyname];
+ } }
+ for (var prop in copy) { keymap[prop] = copy[prop]; }
+ return keymap
+}
+
+function lookupKey(key, map$$1, handle, context) {
+ map$$1 = getKeyMap(map$$1);
+ var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
+ if (found === false) { return "nothing" }
+ if (found === "...") { return "multi" }
+ if (found != null && handle(found)) { return "handled" }
+
+ if (map$$1.fallthrough) {
+ if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
+ { return lookupKey(key, map$$1.fallthrough, handle, context) }
+ for (var i = 0; i < map$$1.fallthrough.length; i++) {
+ var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
+ if (result) { return result }
+ }
+ }
+}
+
+// Modifier key presses don't count as 'real' key presses for the
+// purpose of keymap fallthrough.
+function isModifierKey(value) {
+ var name = typeof value == "string" ? value : keyNames[value.keyCode];
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
+}
+
+function addModifierNames(name, event, noShift) {
+ var base = name;
+ if (event.altKey && base != "Alt") { name = "Alt-" + name; }
+ if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
+ if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
+ if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
+ return name
+}
+
+// Look up the name of a key as indicated by an event object.
+function keyName(event, noShift) {
+ if (presto && event.keyCode == 34 && event["char"]) { return false }
+ var name = keyNames[event.keyCode];
+ if (name == null || event.altGraphKey) { return false }
+ // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
+ // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
+ if (event.keyCode == 3 && event.code) { name = event.code; }
+ return addModifierNames(name, event, noShift)
+}
+
+function getKeyMap(val) {
+ return typeof val == "string" ? keyMap[val] : val
+}
+
+// Helper for deleting text near the selection(s), used to implement
+// backspace, delete, and similar functionality.
+function deleteNearSelection(cm, compute) {
+ var ranges = cm.doc.sel.ranges, kill = [];
+ // Build up a set of ranges to kill first, merging overlapping
+ // ranges.
+ for (var i = 0; i < ranges.length; i++) {
+ var toKill = compute(ranges[i]);
+ while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
+ var replaced = kill.pop();
+ if (cmp(replaced.from, toKill.from) < 0) {
+ toKill.from = replaced.from;
+ break
+ }
+ }
+ kill.push(toKill);
+ }
+ // Next, remove those actual ranges.
+ runInOp(cm, function () {
+ for (var i = kill.length - 1; i >= 0; i--)
+ { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
+ ensureCursorVisible(cm);
+ });
+}
+
+function moveCharLogically(line, ch, dir) {
+ var target = skipExtendingChars(line.text, ch + dir, dir);
+ return target < 0 || target > line.text.length ? null : target
+}
+
+function moveLogically(line, start, dir) {
+ var ch = moveCharLogically(line, start.ch, dir);
+ return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
+}
+
+function endOfLine(visually, cm, lineObj, lineNo, dir) {
+ if (visually) {
+ var order = getOrder(lineObj, cm.doc.direction);
+ if (order) {
+ var part = dir < 0 ? lst(order) : order[0];
+ var moveInStorageOrder = (dir < 0) == (part.level == 1);
+ var sticky = moveInStorageOrder ? "after" : "before";
+ var ch;
+ // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
+ // it could be that the last bidi part is not on the last visual line,
+ // since visual lines contain content order-consecutive chunks.
+ // Thus, in rtl, we are looking for the first (content-order) character
+ // in the rtl chunk that is on the last line (that is, the same line
+ // as the last (content-order) character).
+ if (part.level > 0 || cm.doc.direction == "rtl") {
+ var prep = prepareMeasureForLine(cm, lineObj);
+ ch = dir < 0 ? lineObj.text.length - 1 : 0;
+ var targetTop = measureCharPrepared(cm, prep, ch).top;
+ ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
+ if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
+ } else { ch = dir < 0 ? part.to : part.from; }
+ return new Pos(lineNo, ch, sticky)
+ }
+ }
+ return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
+}
+
+function moveVisually(cm, line, start, dir) {
+ var bidi = getOrder(line, cm.doc.direction);
+ if (!bidi) { return moveLogically(line, start, dir) }
+ if (start.ch >= line.text.length) {
+ start.ch = line.text.length;
+ start.sticky = "before";
+ } else if (start.ch <= 0) {
+ start.ch = 0;
+ start.sticky = "after";
+ }
+ var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
+ if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
+ // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
+ // nothing interesting happens.
+ return moveLogically(line, start, dir)
+ }
+
+ var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
+ var prep;
+ var getWrappedLineExtent = function (ch) {
+ if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
+ prep = prep || prepareMeasureForLine(cm, line);
+ return wrappedLineExtentChar(cm, line, prep, ch)
+ };
+ var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
+
+ if (cm.doc.direction == "rtl" || part.level == 1) {
+ var moveInStorageOrder = (part.level == 1) == (dir < 0);
+ var ch = mv(start, moveInStorageOrder ? 1 : -1);
+ if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
+ // Case 2: We move within an rtl part or in an rtl editor on the same visual line
+ var sticky = moveInStorageOrder ? "before" : "after";
+ return new Pos(start.line, ch, sticky)
+ }
+ }
+
+ // Case 3: Could not move within this bidi part in this visual line, so leave
+ // the current bidi part
+
+ var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
+ var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
+ ? new Pos(start.line, mv(ch, 1), "before")
+ : new Pos(start.line, ch, "after"); };
+
+ for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
+ var part = bidi[partPos];
+ var moveInStorageOrder = (dir > 0) == (part.level != 1);
+ var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
+ if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
+ ch = moveInStorageOrder ? part.from : mv(part.to, -1);
+ if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
+ }
+ };
+
+ // Case 3a: Look for other bidi parts on the same visual line
+ var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
+ if (res) { return res }
+
+ // Case 3b: Look for other bidi parts on the next visual line
+ var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
+ if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
+ res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
+ if (res) { return res }
+ }
+
+ // Case 4: Nowhere to move
+ return null
+}
+
+// Commands are parameter-less actions that can be performed on an
+// editor, mostly used for keybindings.
+var commands = {
+ selectAll: selectAll,
+ singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
+ killLine: function (cm) { return deleteNearSelection(cm, function (range) {
+ if (range.empty()) {
+ var len = getLine(cm.doc, range.head.line).text.length;
+ if (range.head.ch == len && range.head.line < cm.lastLine())
+ { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
+ else
+ { return {from: range.head, to: Pos(range.head.line, len)} }
+ } else {
+ return {from: range.from(), to: range.to()}
+ }
+ }); },
+ deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
+ from: Pos(range.from().line, 0),
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
+ }); }); },
+ delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
+ from: Pos(range.from().line, 0), to: range.from()
+ }); }); },
+ delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ var leftPos = cm.coordsChar({left: 0, top: top}, "div");
+ return {from: leftPos, to: range.from()}
+ }); },
+ delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
+ return {from: range.from(), to: rightPos }
+ }); },
+ undo: function (cm) { return cm.undo(); },
+ redo: function (cm) { return cm.redo(); },
+ undoSelection: function (cm) { return cm.undoSelection(); },
+ redoSelection: function (cm) { return cm.redoSelection(); },
+ goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
+ goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
+ goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
+ {origin: "+move", bias: 1}
+ ); },
+ goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
+ {origin: "+move", bias: 1}
+ ); },
+ goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
+ {origin: "+move", bias: -1}
+ ); },
+ goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
+ }, sel_move); },
+ goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: 0, top: top}, "div")
+ }, sel_move); },
+ goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ var pos = cm.coordsChar({left: 0, top: top}, "div");
+ if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
+ return pos
+ }, sel_move); },
+ goLineUp: function (cm) { return cm.moveV(-1, "line"); },
+ goLineDown: function (cm) { return cm.moveV(1, "line"); },
+ goPageUp: function (cm) { return cm.moveV(-1, "page"); },
+ goPageDown: function (cm) { return cm.moveV(1, "page"); },
+ goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
+ goCharRight: function (cm) { return cm.moveH(1, "char"); },
+ goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
+ goColumnRight: function (cm) { return cm.moveH(1, "column"); },
+ goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
+ goGroupRight: function (cm) { return cm.moveH(1, "group"); },
+ goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
+ goWordRight: function (cm) { return cm.moveH(1, "word"); },
+ delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
+ delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
+ delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
+ delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
+ delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
+ delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
+ indentAuto: function (cm) { return cm.indentSelection("smart"); },
+ indentMore: function (cm) { return cm.indentSelection("add"); },
+ indentLess: function (cm) { return cm.indentSelection("subtract"); },
+ insertTab: function (cm) { return cm.replaceSelection("\t"); },
+ insertSoftTab: function (cm) {
+ var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
+ for (var i = 0; i < ranges.length; i++) {
+ var pos = ranges[i].from();
+ var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
+ spaces.push(spaceStr(tabSize - col % tabSize));
+ }
+ cm.replaceSelections(spaces);
+ },
+ defaultTab: function (cm) {
+ if (cm.somethingSelected()) { cm.indentSelection("add"); }
+ else { cm.execCommand("insertTab"); }
+ },
+ // Swap the two chars left and right of each selection's head.
+ // Move cursor behind the two swapped characters afterwards.
+ //
+ // Doesn't consider line feeds a character.
+ // Doesn't scan more than one line above to find a character.
+ // Doesn't do anything on an empty line.
+ // Doesn't do anything with non-empty selections.
+ transposeChars: function (cm) { return runInOp(cm, function () {
+ var ranges = cm.listSelections(), newSel = [];
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) { continue }
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
+ if (line) {
+ if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
+ if (cur.ch > 0) {
+ cur = new Pos(cur.line, cur.ch + 1);
+ cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
+ Pos(cur.line, cur.ch - 2), cur, "+transpose");
+ } else if (cur.line > cm.doc.first) {
+ var prev = getLine(cm.doc, cur.line - 1).text;
+ if (prev) {
+ cur = new Pos(cur.line, 1);
+ cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
+ prev.charAt(prev.length - 1),
+ Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
+ }
+ }
+ }
+ newSel.push(new Range(cur, cur));
+ }
+ cm.setSelections(newSel);
+ }); },
+ newlineAndIndent: function (cm) { return runInOp(cm, function () {
+ var sels = cm.listSelections();
+ for (var i = sels.length - 1; i >= 0; i--)
+ { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
+ sels = cm.listSelections();
+ for (var i$1 = 0; i$1 < sels.length; i$1++)
+ { cm.indentLine(sels[i$1].from().line, null, true); }
+ ensureCursorVisible(cm);
+ }); },
+ openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
+ toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
+};
+
+
+function lineStart(cm, lineN) {
+ var line = getLine(cm.doc, lineN);
+ var visual = visualLine(line);
+ if (visual != line) { lineN = lineNo(visual); }
+ return endOfLine(true, cm, visual, lineN, 1)
+}
+function lineEnd(cm, lineN) {
+ var line = getLine(cm.doc, lineN);
+ var visual = visualLineEnd(line);
+ if (visual != line) { lineN = lineNo(visual); }
+ return endOfLine(true, cm, line, lineN, -1)
+}
+function lineStartSmart(cm, pos) {
+ var start = lineStart(cm, pos.line);
+ var line = getLine(cm.doc, start.line);
+ var order = getOrder(line, cm.doc.direction);
+ if (!order || order[0].level == 0) {
+ var firstNonWS = Math.max(0, line.text.search(/\S/));
+ var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
+ return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
+ }
+ return start
+}
+
+// Run a handler that was bound to a key.
+function doHandleBinding(cm, bound, dropShift) {
+ if (typeof bound == "string") {
+ bound = commands[bound];
+ if (!bound) { return false }
+ }
+ // Ensure previous input has been read, so that the handler sees a
+ // consistent view of the document
+ cm.display.input.ensurePolled();
+ var prevShift = cm.display.shift, done = false;
+ try {
+ if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
+ if (dropShift) { cm.display.shift = false; }
+ done = bound(cm) != Pass;
+ } finally {
+ cm.display.shift = prevShift;
+ cm.state.suppressEdits = false;
+ }
+ return done
+}
+
+function lookupKeyForEditor(cm, name, handle) {
+ for (var i = 0; i < cm.state.keyMaps.length; i++) {
+ var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
+ if (result) { return result }
+ }
+ return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
+ || lookupKey(name, cm.options.keyMap, handle, cm)
+}
+
+// Note that, despite the name, this function is also used to check
+// for bound mouse clicks.
+
+var stopSeq = new Delayed;
+
+function dispatchKey(cm, name, e, handle) {
+ var seq = cm.state.keySeq;
+ if (seq) {
+ if (isModifierKey(name)) { return "handled" }
+ if (/\'$/.test(name))
+ { cm.state.keySeq = null; }
+ else
+ { stopSeq.set(50, function () {
+ if (cm.state.keySeq == seq) {
+ cm.state.keySeq = null;
+ cm.display.input.reset();
+ }
+ }); }
+ if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
+ }
+ return dispatchKeyInner(cm, name, e, handle)
+}
+
+function dispatchKeyInner(cm, name, e, handle) {
+ var result = lookupKeyForEditor(cm, name, handle);
+
+ if (result == "multi")
+ { cm.state.keySeq = name; }
+ if (result == "handled")
+ { signalLater(cm, "keyHandled", cm, name, e); }
+
+ if (result == "handled" || result == "multi") {
+ e_preventDefault(e);
+ restartBlink(cm);
+ }
+
+ return !!result
+}
+
+// Handle a key from the keydown event.
+function handleKeyBinding(cm, e) {
+ var name = keyName(e, true);
+ if (!name) { return false }
+
+ if (e.shiftKey && !cm.state.keySeq) {
+ // First try to resolve full name (including 'Shift-'). Failing
+ // that, see if there is a cursor-motion command (starting with
+ // 'go') bound to the keyname without 'Shift-'.
+ return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
+ || dispatchKey(cm, name, e, function (b) {
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
+ { return doHandleBinding(cm, b) }
+ })
+ } else {
+ return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
+ }
+}
+
+// Handle a key from the keypress event
+function handleCharBinding(cm, e, ch) {
+ return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
+}
+
+var lastStoppedKey = null;
+function onKeyDown(e) {
+ var cm = this;
+ cm.curOp.focus = activeElt();
+ if (signalDOMEvent(cm, e)) { return }
+ // IE does strange things with escape.
+ if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
+ var code = e.keyCode;
+ cm.display.shift = code == 16 || e.shiftKey;
+ var handled = handleKeyBinding(cm, e);
+ if (presto) {
+ lastStoppedKey = handled ? code : null;
+ // Opera has no cut event... we try to at least catch the key combo
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
+ { cm.replaceSelection("", null, "cut"); }
+ }
+
+ // Turn mouse into crosshair when Alt is held on Mac.
+ if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
+ { showCrossHair(cm); }
+}
+
+function showCrossHair(cm) {
+ var lineDiv = cm.display.lineDiv;
+ addClass(lineDiv, "CodeMirror-crosshair");
+
+ function up(e) {
+ if (e.keyCode == 18 || !e.altKey) {
+ rmClass(lineDiv, "CodeMirror-crosshair");
+ off(document, "keyup", up);
+ off(document, "mouseover", up);
+ }
+ }
+ on(document, "keyup", up);
+ on(document, "mouseover", up);
+}
+
+function onKeyUp(e) {
+ if (e.keyCode == 16) { this.doc.sel.shift = false; }
+ signalDOMEvent(this, e);
+}
+
+function onKeyPress(e) {
+ var cm = this;
+ if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
+ var keyCode = e.keyCode, charCode = e.charCode;
+ if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
+ if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
+ // Some browsers fire keypress events for backspace
+ if (ch == "\x08") { return }
+ if (handleCharBinding(cm, e, ch)) { return }
+ cm.display.input.onKeyPress(e);
+}
+
+var DOUBLECLICK_DELAY = 400;
+
+var PastClick = function(time, pos, button) {
+ this.time = time;
+ this.pos = pos;
+ this.button = button;
+};
+
+PastClick.prototype.compare = function (time, pos, button) {
+ return this.time + DOUBLECLICK_DELAY > time &&
+ cmp(pos, this.pos) == 0 && button == this.button
+};
+
+var lastClick;
+var lastDoubleClick;
+function clickRepeat(pos, button) {
+ var now = +new Date;
+ if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
+ lastClick = lastDoubleClick = null;
+ return "triple"
+ } else if (lastClick && lastClick.compare(now, pos, button)) {
+ lastDoubleClick = new PastClick(now, pos, button);
+ lastClick = null;
+ return "double"
+ } else {
+ lastClick = new PastClick(now, pos, button);
+ lastDoubleClick = null;
+ return "single"
+ }
+}
+
+// A mouse down can be a single click, double click, triple click,
+// start of selection drag, start of text drag, new cursor
+// (ctrl-click), rectangle drag (alt-drag), or xwin
+// middle-click-paste. Or it might be a click on something we should
+// not interfere with, such as a scrollbar or widget.
+function onMouseDown(e) {
+ var cm = this, display = cm.display;
+ if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
+ display.input.ensurePolled();
+ display.shift = e.shiftKey;
+
+ if (eventInWidget(display, e)) {
+ if (!webkit) {
+ // Briefly turn off draggability, to allow widgets to do
+ // normal dragging things.
+ display.scroller.draggable = false;
+ setTimeout(function () { return display.scroller.draggable = true; }, 100);
+ }
+ return
+ }
+ if (clickInGutter(cm, e)) { return }
+ var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
+ window.focus();
+
+ // #3261: make sure, that we're not starting a second selection
+ if (button == 1 && cm.state.selectingText)
+ { cm.state.selectingText(e); }
+
+ if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
+
+ if (button == 1) {
+ if (pos) { leftButtonDown(cm, pos, repeat, e); }
+ else if (e_target(e) == display.scroller) { e_preventDefault(e); }
+ } else if (button == 2) {
+ if (pos) { extendSelection(cm.doc, pos); }
+ setTimeout(function () { return display.input.focus(); }, 20);
+ } else if (button == 3) {
+ if (captureRightClick) { onContextMenu(cm, e); }
+ else { delayBlurEvent(cm); }
+ }
+}
+
+function handleMappedButton(cm, button, pos, repeat, event) {
+ var name = "Click";
+ if (repeat == "double") { name = "Double" + name; }
+ else if (repeat == "triple") { name = "Triple" + name; }
+ name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
+
+ return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
+ if (typeof bound == "string") { bound = commands[bound]; }
+ if (!bound) { return false }
+ var done = false;
+ try {
+ if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
+ done = bound(cm, pos) != Pass;
+ } finally {
+ cm.state.suppressEdits = false;
+ }
+ return done
+ })
+}
+
+function configureMouse(cm, repeat, event) {
+ var option = cm.getOption("configureMouse");
+ var value = option ? option(cm, repeat, event) : {};
+ if (value.unit == null) {
+ var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
+ value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
+ }
+ if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
+ if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
+ if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
+ return value
+}
+
+function leftButtonDown(cm, pos, repeat, event) {
+ if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
+ else { cm.curOp.focus = activeElt(); }
+
+ var behavior = configureMouse(cm, repeat, event);
+
+ var sel = cm.doc.sel, contained;
+ if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
+ repeat == "single" && (contained = sel.contains(pos)) > -1 &&
+ (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
+ (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
+ { leftButtonStartDrag(cm, event, pos, behavior); }
+ else
+ { leftButtonSelect(cm, event, pos, behavior); }
+}
+
+// Start a text drag. When it ends, see if any dragging actually
+// happen, and treat as a click if it didn't.
+function leftButtonStartDrag(cm, event, pos, behavior) {
+ var display = cm.display, moved = false;
+ var dragEnd = operation(cm, function (e) {
+ if (webkit) { display.scroller.draggable = false; }
+ cm.state.draggingText = false;
+ off(display.wrapper.ownerDocument, "mouseup", dragEnd);
+ off(display.wrapper.ownerDocument, "mousemove", mouseMove);
+ off(display.scroller, "dragstart", dragStart);
+ off(display.scroller, "drop", dragEnd);
+ if (!moved) {
+ e_preventDefault(e);
+ if (!behavior.addNew)
+ { extendSelection(cm.doc, pos, null, null, behavior.extend); }
+ // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
+ if (webkit || ie && ie_version == 9)
+ { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); }
+ else
+ { display.input.focus(); }
+ }
+ });
+ var mouseMove = function(e2) {
+ moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
+ };
+ var dragStart = function () { return moved = true; };
+ // Let the drag handler handle this.
+ if (webkit) { display.scroller.draggable = true; }
+ cm.state.draggingText = dragEnd;
+ dragEnd.copy = !behavior.moveOnDrag;
+ // IE's approach to draggable
+ if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
+ on(display.wrapper.ownerDocument, "mouseup", dragEnd);
+ on(display.wrapper.ownerDocument, "mousemove", mouseMove);
+ on(display.scroller, "dragstart", dragStart);
+ on(display.scroller, "drop", dragEnd);
+
+ delayBlurEvent(cm);
+ setTimeout(function () { return display.input.focus(); }, 20);
+}
+
+function rangeForUnit(cm, pos, unit) {
+ if (unit == "char") { return new Range(pos, pos) }
+ if (unit == "word") { return cm.findWordAt(pos) }
+ if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
+ var result = unit(cm, pos);
+ return new Range(result.from, result.to)
+}
+
+// Normal selection, as opposed to text dragging.
+function leftButtonSelect(cm, event, start, behavior) {
+ var display = cm.display, doc = cm.doc;
+ e_preventDefault(event);
+
+ var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
+ if (behavior.addNew && !behavior.extend) {
+ ourIndex = doc.sel.contains(start);
+ if (ourIndex > -1)
+ { ourRange = ranges[ourIndex]; }
+ else
+ { ourRange = new Range(start, start); }
+ } else {
+ ourRange = doc.sel.primary();
+ ourIndex = doc.sel.primIndex;
+ }
+
+ if (behavior.unit == "rectangle") {
+ if (!behavior.addNew) { ourRange = new Range(start, start); }
+ start = posFromMouse(cm, event, true, true);
+ ourIndex = -1;
+ } else {
+ var range$$1 = rangeForUnit(cm, start, behavior.unit);
+ if (behavior.extend)
+ { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
+ else
+ { ourRange = range$$1; }
+ }
+
+ if (!behavior.addNew) {
+ ourIndex = 0;
+ setSelection(doc, new Selection([ourRange], 0), sel_mouse);
+ startSel = doc.sel;
+ } else if (ourIndex == -1) {
+ ourIndex = ranges.length;
+ setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
+ {scroll: false, origin: "*mouse"});
+ } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
+ setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
+ {scroll: false, origin: "*mouse"});
+ startSel = doc.sel;
+ } else {
+ replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
+ }
+
+ var lastPos = start;
+ function extendTo(pos) {
+ if (cmp(lastPos, pos) == 0) { return }
+ lastPos = pos;
+
+ if (behavior.unit == "rectangle") {
+ var ranges = [], tabSize = cm.options.tabSize;
+ var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
+ var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
+ var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
+ for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
+ line <= end; line++) {
+ var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
+ if (left == right)
+ { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
+ else if (text.length > leftPos)
+ { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
+ }
+ if (!ranges.length) { ranges.push(new Range(start, start)); }
+ setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
+ {origin: "*mouse", scroll: false});
+ cm.scrollIntoView(pos);
+ } else {
+ var oldRange = ourRange;
+ var range$$1 = rangeForUnit(cm, pos, behavior.unit);
+ var anchor = oldRange.anchor, head;
+ if (cmp(range$$1.anchor, anchor) > 0) {
+ head = range$$1.head;
+ anchor = minPos(oldRange.from(), range$$1.anchor);
+ } else {
+ head = range$$1.anchor;
+ anchor = maxPos(oldRange.to(), range$$1.head);
+ }
+ var ranges$1 = startSel.ranges.slice(0);
+ ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
+ setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse);
+ }
+ }
+
+ var editorSize = display.wrapper.getBoundingClientRect();
+ // Used to ensure timeout re-tries don't fire when another extend
+ // happened in the meantime (clearTimeout isn't reliable -- at
+ // least on Chrome, the timeouts still happen even when cleared,
+ // if the clear happens after their scheduled firing time).
+ var counter = 0;
+
+ function extend(e) {
+ var curCount = ++counter;
+ var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
+ if (!cur) { return }
+ if (cmp(cur, lastPos) != 0) {
+ cm.curOp.focus = activeElt();
+ extendTo(cur);
+ var visible = visibleLines(display, doc);
+ if (cur.line >= visible.to || cur.line < visible.from)
+ { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
+ } else {
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
+ if (outside) { setTimeout(operation(cm, function () {
+ if (counter != curCount) { return }
+ display.scroller.scrollTop += outside;
+ extend(e);
+ }), 50); }
+ }
+ }
+
+ function done(e) {
+ cm.state.selectingText = false;
+ counter = Infinity;
+ e_preventDefault(e);
+ display.input.focus();
+ off(display.wrapper.ownerDocument, "mousemove", move);
+ off(display.wrapper.ownerDocument, "mouseup", up);
+ doc.history.lastSelOrigin = null;
+ }
+
+ var move = operation(cm, function (e) {
+ if (!e_button(e)) { done(e); }
+ else { extend(e); }
+ });
+ var up = operation(cm, done);
+ cm.state.selectingText = up;
+ on(display.wrapper.ownerDocument, "mousemove", move);
+ on(display.wrapper.ownerDocument, "mouseup", up);
+}
+
+// Used when mouse-selecting to adjust the anchor to the proper side
+// of a bidi jump depending on the visual position of the head.
+function bidiSimplify(cm, range$$1) {
+ var anchor = range$$1.anchor;
+ var head = range$$1.head;
+ var anchorLine = getLine(cm.doc, anchor.line);
+ if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
+ var order = getOrder(anchorLine);
+ if (!order) { return range$$1 }
+ var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
+ if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
+ var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
+ if (boundary == 0 || boundary == order.length) { return range$$1 }
+
+ // Compute the relative visual position of the head compared to the
+ // anchor (<0 is to the left, >0 to the right)
+ var leftSide;
+ if (head.line != anchor.line) {
+ leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
+ } else {
+ var headIndex = getBidiPartAt(order, head.ch, head.sticky);
+ var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
+ if (headIndex == boundary - 1 || headIndex == boundary)
+ { leftSide = dir < 0; }
+ else
+ { leftSide = dir > 0; }
+ }
+
+ var usePart = order[boundary + (leftSide ? -1 : 0)];
+ var from = leftSide == (usePart.level == 1);
+ var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
+ return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
+}
+
+
+// Determines whether an event happened in the gutter, and fires the
+// handlers for the corresponding event.
+function gutterEvent(cm, e, type, prevent) {
+ var mX, mY;
+ if (e.touches) {
+ mX = e.touches[0].clientX;
+ mY = e.touches[0].clientY;
+ } else {
+ try { mX = e.clientX; mY = e.clientY; }
+ catch(e) { return false }
+ }
+ if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
+ if (prevent) { e_preventDefault(e); }
+
+ var display = cm.display;
+ var lineBox = display.lineDiv.getBoundingClientRect();
+
+ if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
+ mY -= lineBox.top - display.viewOffset;
+
+ for (var i = 0; i < cm.options.gutters.length; ++i) {
+ var g = display.gutters.childNodes[i];
+ if (g && g.getBoundingClientRect().right >= mX) {
+ var line = lineAtHeight(cm.doc, mY);
+ var gutter = cm.options.gutters[i];
+ signal(cm, type, cm, line, gutter, e);
+ return e_defaultPrevented(e)
+ }
+ }
+}
+
+function clickInGutter(cm, e) {
+ return gutterEvent(cm, e, "gutterClick", true)
+}
+
+// CONTEXT MENU HANDLING
+
+// To make the context menu work, we need to briefly unhide the
+// textarea (making it as unobtrusive as possible) to let the
+// right-click take effect on it.
+function onContextMenu(cm, e) {
+ if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
+ if (signalDOMEvent(cm, e, "contextmenu")) { return }
+ cm.display.input.onContextMenu(e);
+}
+
+function contextMenuInGutter(cm, e) {
+ if (!hasHandler(cm, "gutterContextMenu")) { return false }
+ return gutterEvent(cm, e, "gutterContextMenu", false)
+}
+
+function themeChanged(cm) {
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
+ clearCaches(cm);
+}
+
+var Init = {toString: function(){return "CodeMirror.Init"}};
+
+var defaults = {};
+var optionHandlers = {};
+
+function defineOptions(CodeMirror) {
+ var optionHandlers = CodeMirror.optionHandlers;
+
+ function option(name, deflt, handle, notOnInit) {
+ CodeMirror.defaults[name] = deflt;
+ if (handle) { optionHandlers[name] =
+ notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
+ }
+
+ CodeMirror.defineOption = option;
+
+ // Passed to option handlers when there is no old value.
+ CodeMirror.Init = Init;
+
+ // These two are, on init, called from the constructor because they
+ // have to be initialized before the editor can start at all.
+ option("value", "", function (cm, val) { return cm.setValue(val); }, true);
+ option("mode", null, function (cm, val) {
+ cm.doc.modeOption = val;
+ loadMode(cm);
+ }, true);
+
+ option("indentUnit", 2, loadMode, true);
+ option("indentWithTabs", false);
+ option("smartIndent", true);
+ option("tabSize", 4, function (cm) {
+ resetModeState(cm);
+ clearCaches(cm);
+ regChange(cm);
+ }, true);
+
+ option("lineSeparator", null, function (cm, val) {
+ cm.doc.lineSep = val;
+ if (!val) { return }
+ var newBreaks = [], lineNo = cm.doc.first;
+ cm.doc.iter(function (line) {
+ for (var pos = 0;;) {
+ var found = line.text.indexOf(val, pos);
+ if (found == -1) { break }
+ pos = found + val.length;
+ newBreaks.push(Pos(lineNo, found));
+ }
+ lineNo++;
+ });
+ for (var i = newBreaks.length - 1; i >= 0; i--)
+ { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
+ });
+ option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
+ cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
+ if (old != Init) { cm.refresh(); }
+ });
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
+ option("electricChars", true);
+ option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
+ throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
+ }, true);
+ option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
+ option("rtlMoveVisually", !windows);
+ option("wholeLineUpdateBefore", true);
+
+ option("theme", "default", function (cm) {
+ themeChanged(cm);
+ guttersChanged(cm);
+ }, true);
+ option("keyMap", "default", function (cm, val, old) {
+ var next = getKeyMap(val);
+ var prev = old != Init && getKeyMap(old);
+ if (prev && prev.detach) { prev.detach(cm, next); }
+ if (next.attach) { next.attach(cm, prev || null); }
+ });
+ option("extraKeys", null);
+ option("configureMouse", null);
+
+ option("lineWrapping", false, wrappingChanged, true);
+ option("gutters", [], function (cm) {
+ setGuttersForLineNumbers(cm.options);
+ guttersChanged(cm);
+ }, true);
+ option("fixedGutter", true, function (cm, val) {
+ cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
+ cm.refresh();
+ }, true);
+ option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
+ option("scrollbarStyle", "native", function (cm) {
+ initScrollbars(cm);
+ updateScrollbars(cm);
+ cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
+ cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
+ }, true);
+ option("lineNumbers", false, function (cm) {
+ setGuttersForLineNumbers(cm.options);
+ guttersChanged(cm);
+ }, true);
+ option("firstLineNumber", 1, guttersChanged, true);
+ option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
+ option("showCursorWhenSelecting", false, updateSelection, true);
+
+ option("resetSelectionOnContextMenu", true);
+ option("lineWiseCopyCut", true);
+ option("pasteLinesPerSelection", true);
+
+ option("readOnly", false, function (cm, val) {
+ if (val == "nocursor") {
+ onBlur(cm);
+ cm.display.input.blur();
+ }
+ cm.display.input.readOnlyChanged(val);
+ });
+ option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
+ option("dragDrop", true, dragDropChanged);
+ option("allowDropFileTypes", null);
+
+ option("cursorBlinkRate", 530);
+ option("cursorScrollMargin", 0);
+ option("cursorHeight", 1, updateSelection, true);
+ option("singleCursorHeightPerLine", true, updateSelection, true);
+ option("workTime", 100);
+ option("workDelay", 100);
+ option("flattenSpans", true, resetModeState, true);
+ option("addModeClass", false, resetModeState, true);
+ option("pollInterval", 100);
+ option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
+ option("historyEventDelay", 1250);
+ option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
+ option("maxHighlightLength", 10000, resetModeState, true);
+ option("moveInputWithCursor", true, function (cm, val) {
+ if (!val) { cm.display.input.resetPosition(); }
+ });
+
+ option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
+ option("autofocus", null);
+ option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
+}
+
+function guttersChanged(cm) {
+ updateGutters(cm);
+ regChange(cm);
+ alignHorizontally(cm);
+}
+
+function dragDropChanged(cm, value, old) {
+ var wasOn = old && old != Init;
+ if (!value != !wasOn) {
+ var funcs = cm.display.dragFunctions;
+ var toggle = value ? on : off;
+ toggle(cm.display.scroller, "dragstart", funcs.start);
+ toggle(cm.display.scroller, "dragenter", funcs.enter);
+ toggle(cm.display.scroller, "dragover", funcs.over);
+ toggle(cm.display.scroller, "dragleave", funcs.leave);
+ toggle(cm.display.scroller, "drop", funcs.drop);
+ }
+}
+
+function wrappingChanged(cm) {
+ if (cm.options.lineWrapping) {
+ addClass(cm.display.wrapper, "CodeMirror-wrap");
+ cm.display.sizer.style.minWidth = "";
+ cm.display.sizerWidth = null;
+ } else {
+ rmClass(cm.display.wrapper, "CodeMirror-wrap");
+ findMaxLine(cm);
+ }
+ estimateLineHeights(cm);
+ regChange(cm);
+ clearCaches(cm);
+ setTimeout(function () { return updateScrollbars(cm); }, 100);
+}
+
+// A CodeMirror instance represents an editor. This is the object
+// that user code is usually dealing with.
+
+function CodeMirror$1(place, options) {
+ var this$1 = this;
+
+ if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }
+
+ this.options = options = options ? copyObj(options) : {};
+ // Determine effective options based on given values and defaults.
+ copyObj(defaults, options, false);
+ setGuttersForLineNumbers(options);
+
+ var doc = options.value;
+ if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
+ this.doc = doc;
+
+ var input = new CodeMirror$1.inputStyles[options.inputStyle](this);
+ var display = this.display = new Display(place, doc, input);
+ display.wrapper.CodeMirror = this;
+ updateGutters(this);
+ themeChanged(this);
+ if (options.lineWrapping)
+ { this.display.wrapper.className += " CodeMirror-wrap"; }
+ initScrollbars(this);
+
+ this.state = {
+ keyMaps: [], // stores maps added by addKeyMap
+ overlays: [], // highlighting overlays, as added by addOverlay
+ modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
+ overwrite: false,
+ delayingBlurEvent: false,
+ focused: false,
+ suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
+ pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
+ selectingText: false,
+ draggingText: false,
+ highlight: new Delayed(), // stores highlight worker timeout
+ keySeq: null, // Unfinished key sequence
+ specialChars: null
+ };
+
+ if (options.autofocus && !mobile) { display.input.focus(); }
+
+ // Override magic textarea content restore that IE sometimes does
+ // on our hidden textarea on reload
+ if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
+
+ registerEventHandlers(this);
+ ensureGlobalHandlers();
+
+ startOperation(this);
+ this.curOp.forceUpdate = true;
+ attachDoc(this, doc);
+
+ if ((options.autofocus && !mobile) || this.hasFocus())
+ { setTimeout(bind(onFocus, this), 20); }
+ else
+ { onBlur(this); }
+
+ for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
+ { optionHandlers[opt](this$1, options[opt], Init); } }
+ maybeUpdateLineNumberWidth(this);
+ if (options.finishInit) { options.finishInit(this); }
+ for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
+ endOperation(this);
+ // Suppress optimizelegibility in Webkit, since it breaks text
+ // measuring on line wrapping boundaries.
+ if (webkit && options.lineWrapping &&
+ getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
+ { display.lineDiv.style.textRendering = "auto"; }
+}
+
+// The default configuration options.
+CodeMirror$1.defaults = defaults;
+// Functions to run when options are changed.
+CodeMirror$1.optionHandlers = optionHandlers;
+
+// Attach the necessary event handlers when initializing the editor
+function registerEventHandlers(cm) {
+ var d = cm.display;
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
+ // Older IE's will not fire a second mousedown for a double click
+ if (ie && ie_version < 11)
+ { on(d.scroller, "dblclick", operation(cm, function (e) {
+ if (signalDOMEvent(cm, e)) { return }
+ var pos = posFromMouse(cm, e);
+ if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
+ e_preventDefault(e);
+ var word = cm.findWordAt(pos);
+ extendSelection(cm.doc, word.anchor, word.head);
+ })); }
+ else
+ { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
+ // Some browsers fire contextmenu *after* opening the menu, at
+ // which point we can't mess with it anymore. Context menu is
+ // handled in onMouseDown for these browsers.
+ if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); }
+
+ // Used to suppress mouse event handling when a touch happens
+ var touchFinished, prevTouch = {end: 0};
+ function finishTouch() {
+ if (d.activeTouch) {
+ touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
+ prevTouch = d.activeTouch;
+ prevTouch.end = +new Date;
+ }
+ }
+ function isMouseLikeTouchEvent(e) {
+ if (e.touches.length != 1) { return false }
+ var touch = e.touches[0];
+ return touch.radiusX <= 1 && touch.radiusY <= 1
+ }
+ function farAway(touch, other) {
+ if (other.left == null) { return true }
+ var dx = other.left - touch.left, dy = other.top - touch.top;
+ return dx * dx + dy * dy > 20 * 20
+ }
+ on(d.scroller, "touchstart", function (e) {
+ if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
+ d.input.ensurePolled();
+ clearTimeout(touchFinished);
+ var now = +new Date;
+ d.activeTouch = {start: now, moved: false,
+ prev: now - prevTouch.end <= 300 ? prevTouch : null};
+ if (e.touches.length == 1) {
+ d.activeTouch.left = e.touches[0].pageX;
+ d.activeTouch.top = e.touches[0].pageY;
+ }
+ }
+ });
+ on(d.scroller, "touchmove", function () {
+ if (d.activeTouch) { d.activeTouch.moved = true; }
+ });
+ on(d.scroller, "touchend", function (e) {
+ var touch = d.activeTouch;
+ if (touch && !eventInWidget(d, e) && touch.left != null &&
+ !touch.moved && new Date - touch.start < 300) {
+ var pos = cm.coordsChar(d.activeTouch, "page"), range;
+ if (!touch.prev || farAway(touch, touch.prev)) // Single tap
+ { range = new Range(pos, pos); }
+ else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
+ { range = cm.findWordAt(pos); }
+ else // Triple tap
+ { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
+ cm.setSelection(range.anchor, range.head);
+ cm.focus();
+ e_preventDefault(e);
+ }
+ finishTouch();
+ });
+ on(d.scroller, "touchcancel", finishTouch);
+
+ // Sync scrolling between fake scrollbars and real scrollable
+ // area, ensure viewport is updated when scrolling.
+ on(d.scroller, "scroll", function () {
+ if (d.scroller.clientHeight) {
+ updateScrollTop(cm, d.scroller.scrollTop);
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
+ signal(cm, "scroll", cm);
+ }
+ });
+
+ // Listen to wheel events in order to try and update the viewport on time.
+ on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
+ on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
+
+ // Prevent wrapper from ever scrolling
+ on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
+
+ d.dragFunctions = {
+ enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
+ over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
+ start: function (e) { return onDragStart(cm, e); },
+ drop: operation(cm, onDrop),
+ leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
+ };
+
+ var inp = d.input.getField();
+ on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
+ on(inp, "keydown", operation(cm, onKeyDown));
+ on(inp, "keypress", operation(cm, onKeyPress));
+ on(inp, "focus", function (e) { return onFocus(cm, e); });
+ on(inp, "blur", function (e) { return onBlur(cm, e); });
+}
+
+var initHooks = [];
+CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); };
+
+// Indent the given line. The how parameter can be "smart",
+// "add"/null, "subtract", or "prev". When aggressive is false
+// (typically set to true for forced single-line indents), empty
+// lines are not indented, and places where the mode returns Pass
+// are left alone.
+function indentLine(cm, n, how, aggressive) {
+ var doc = cm.doc, state;
+ if (how == null) { how = "add"; }
+ if (how == "smart") {
+ // Fall back to "prev" when the mode doesn't have an indentation
+ // method.
+ if (!doc.mode.indent) { how = "prev"; }
+ else { state = getContextBefore(cm, n).state; }
+ }
+
+ var tabSize = cm.options.tabSize;
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
+ if (line.stateAfter) { line.stateAfter = null; }
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
+ if (!aggressive && !/\S/.test(line.text)) {
+ indentation = 0;
+ how = "not";
+ } else if (how == "smart") {
+ indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
+ if (indentation == Pass || indentation > 150) {
+ if (!aggressive) { return }
+ how = "prev";
+ }
+ }
+ if (how == "prev") {
+ if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
+ else { indentation = 0; }
+ } else if (how == "add") {
+ indentation = curSpace + cm.options.indentUnit;
+ } else if (how == "subtract") {
+ indentation = curSpace - cm.options.indentUnit;
+ } else if (typeof how == "number") {
+ indentation = curSpace + how;
+ }
+ indentation = Math.max(0, indentation);
+
+ var indentString = "", pos = 0;
+ if (cm.options.indentWithTabs)
+ { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
+ if (pos < indentation) { indentString += spaceStr(indentation - pos); }
+
+ if (indentString != curSpaceString) {
+ replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
+ line.stateAfter = null;
+ return true
+ } else {
+ // Ensure that, if the cursor was in the whitespace at the start
+ // of the line, it is moved to the end of that space.
+ for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
+ var range = doc.sel.ranges[i$1];
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
+ var pos$1 = Pos(n, curSpaceString.length);
+ replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
+ break
+ }
+ }
+ }
+}
+
+// This will be set to a {lineWise: bool, text: [string]} object, so
+// that, when pasting, we know what kind of selections the copied
+// text was made out of.
+var lastCopied = null;
+
+function setLastCopied(newLastCopied) {
+ lastCopied = newLastCopied;
+}
+
+function applyTextInput(cm, inserted, deleted, sel, origin) {
+ var doc = cm.doc;
+ cm.display.shift = false;
+ if (!sel) { sel = doc.sel; }
+
+ var paste = cm.state.pasteIncoming || origin == "paste";
+ var textLines = splitLinesAuto(inserted), multiPaste = null;
+ // When pasting N lines into N selections, insert one line per selection
+ if (paste && sel.ranges.length > 1) {
+ if (lastCopied && lastCopied.text.join("\n") == inserted) {
+ if (sel.ranges.length % lastCopied.text.length == 0) {
+ multiPaste = [];
+ for (var i = 0; i < lastCopied.text.length; i++)
+ { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
+ }
+ } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
+ multiPaste = map(textLines, function (l) { return [l]; });
+ }
+ }
+
+ var updateInput;
+ // Normal behavior is to insert the new text into every selection
+ for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
+ var range$$1 = sel.ranges[i$1];
+ var from = range$$1.from(), to = range$$1.to();
+ if (range$$1.empty()) {
+ if (deleted && deleted > 0) // Handle deletion
+ { from = Pos(from.line, from.ch - deleted); }
+ else if (cm.state.overwrite && !paste) // Handle overwrite
+ { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
+ else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
+ { from = to = Pos(from.line, 0); }
+ }
+ updateInput = cm.curOp.updateInput;
+ var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
+ origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
+ makeChange(cm.doc, changeEvent);
+ signalLater(cm, "inputRead", cm, changeEvent);
+ }
+ if (inserted && !paste)
+ { triggerElectric(cm, inserted); }
+
+ ensureCursorVisible(cm);
+ cm.curOp.updateInput = updateInput;
+ cm.curOp.typing = true;
+ cm.state.pasteIncoming = cm.state.cutIncoming = false;
+}
+
+function handlePaste(e, cm) {
+ var pasted = e.clipboardData && e.clipboardData.getData("Text");
+ if (pasted) {
+ e.preventDefault();
+ if (!cm.isReadOnly() && !cm.options.disableInput)
+ { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
+ return true
+ }
+}
+
+function triggerElectric(cm, inserted) {
+ // When an 'electric' character is inserted, immediately trigger a reindent
+ if (!cm.options.electricChars || !cm.options.smartIndent) { return }
+ var sel = cm.doc.sel;
+
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
+ var range$$1 = sel.ranges[i];
+ if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
+ var mode = cm.getModeAt(range$$1.head);
+ var indented = false;
+ if (mode.electricChars) {
+ for (var j = 0; j < mode.electricChars.length; j++)
+ { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
+ indented = indentLine(cm, range$$1.head.line, "smart");
+ break
+ } }
+ } else if (mode.electricInput) {
+ if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
+ { indented = indentLine(cm, range$$1.head.line, "smart"); }
+ }
+ if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
+ }
+}
+
+function copyableRanges(cm) {
+ var text = [], ranges = [];
+ for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
+ var line = cm.doc.sel.ranges[i].head.line;
+ var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
+ ranges.push(lineRange);
+ text.push(cm.getRange(lineRange.anchor, lineRange.head));
+ }
+ return {text: text, ranges: ranges}
+}
+
+function disableBrowserMagic(field, spellcheck) {
+ field.setAttribute("autocorrect", "off");
+ field.setAttribute("autocapitalize", "off");
+ field.setAttribute("spellcheck", !!spellcheck);
+}
+
+function hiddenTextarea() {
+ var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
+ var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
+ // The textarea is kept positioned near the cursor to prevent the
+ // fact that it'll be scrolled into view on input from scrolling
+ // our fake cursor out of view. On webkit, when wrap=off, paste is
+ // very slow. So make the area wide instead.
+ if (webkit) { te.style.width = "1000px"; }
+ else { te.setAttribute("wrap", "off"); }
+ // If border: 0; -- iOS fails to open keyboard (issue #1287)
+ if (ios) { te.style.border = "1px solid black"; }
+ disableBrowserMagic(te);
+ return div
+}
+
+// The publicly visible API. Note that methodOp(f) means
+// 'wrap f in an operation, performed on its `this` parameter'.
+
+// This is not the complete set of editor methods. Most of the
+// methods defined on the Doc type are also injected into
+// CodeMirror.prototype, for backwards compatibility and
+// convenience.
+
+var addEditorMethods = function(CodeMirror) {
+ var optionHandlers = CodeMirror.optionHandlers;
+
+ var helpers = CodeMirror.helpers = {};
+
+ CodeMirror.prototype = {
+ constructor: CodeMirror,
+ focus: function(){window.focus(); this.display.input.focus();},
+
+ setOption: function(option, value) {
+ var options = this.options, old = options[option];
+ if (options[option] == value && option != "mode") { return }
+ options[option] = value;
+ if (optionHandlers.hasOwnProperty(option))
+ { operation(this, optionHandlers[option])(this, value, old); }
+ signal(this, "optionChange", this, option);
+ },
+
+ getOption: function(option) {return this.options[option]},
+ getDoc: function() {return this.doc},
+
+ addKeyMap: function(map$$1, bottom) {
+ this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
+ },
+ removeKeyMap: function(map$$1) {
+ var maps = this.state.keyMaps;
+ for (var i = 0; i < maps.length; ++i)
+ { if (maps[i] == map$$1 || maps[i].name == map$$1) {
+ maps.splice(i, 1);
+ return true
+ } }
+ },
+
+ addOverlay: methodOp(function(spec, options) {
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
+ if (mode.startState) { throw new Error("Overlays may not be stateful.") }
+ insertSorted(this.state.overlays,
+ {mode: mode, modeSpec: spec, opaque: options && options.opaque,
+ priority: (options && options.priority) || 0},
+ function (overlay) { return overlay.priority; });
+ this.state.modeGen++;
+ regChange(this);
+ }),
+ removeOverlay: methodOp(function(spec) {
+ var this$1 = this;
+
+ var overlays = this.state.overlays;
+ for (var i = 0; i < overlays.length; ++i) {
+ var cur = overlays[i].modeSpec;
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
+ overlays.splice(i, 1);
+ this$1.state.modeGen++;
+ regChange(this$1);
+ return
+ }
+ }
+ }),
+
+ indentLine: methodOp(function(n, dir, aggressive) {
+ if (typeof dir != "string" && typeof dir != "number") {
+ if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
+ else { dir = dir ? "add" : "subtract"; }
+ }
+ if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
+ }),
+ indentSelection: methodOp(function(how) {
+ var this$1 = this;
+
+ var ranges = this.doc.sel.ranges, end = -1;
+ for (var i = 0; i < ranges.length; i++) {
+ var range$$1 = ranges[i];
+ if (!range$$1.empty()) {
+ var from = range$$1.from(), to = range$$1.to();
+ var start = Math.max(end, from.line);
+ end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
+ for (var j = start; j < end; ++j)
+ { indentLine(this$1, j, how); }
+ var newRanges = this$1.doc.sel.ranges;
+ if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
+ { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
+ } else if (range$$1.head.line > end) {
+ indentLine(this$1, range$$1.head.line, how, true);
+ end = range$$1.head.line;
+ if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
+ }
+ }
+ }),
+
+ // Fetch the parser token for a given character. Useful for hacks
+ // that want to inspect the mode state (say, for completion).
+ getTokenAt: function(pos, precise) {
+ return takeToken(this, pos, precise)
+ },
+
+ getLineTokens: function(line, precise) {
+ return takeToken(this, Pos(line), precise, true)
+ },
+
+ getTokenTypeAt: function(pos) {
+ pos = clipPos(this.doc, pos);
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
+ var type;
+ if (ch == 0) { type = styles[2]; }
+ else { for (;;) {
+ var mid = (before + after) >> 1;
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
+ else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
+ else { type = styles[mid * 2 + 2]; break }
+ } }
+ var cut = type ? type.indexOf("overlay ") : -1;
+ return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
+ },
+
+ getModeAt: function(pos) {
+ var mode = this.doc.mode;
+ if (!mode.innerMode) { return mode }
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
+ },
+
+ getHelper: function(pos, type) {
+ return this.getHelpers(pos, type)[0]
+ },
+
+ getHelpers: function(pos, type) {
+ var this$1 = this;
+
+ var found = [];
+ if (!helpers.hasOwnProperty(type)) { return found }
+ var help = helpers[type], mode = this.getModeAt(pos);
+ if (typeof mode[type] == "string") {
+ if (help[mode[type]]) { found.push(help[mode[type]]); }
+ } else if (mode[type]) {
+ for (var i = 0; i < mode[type].length; i++) {
+ var val = help[mode[type][i]];
+ if (val) { found.push(val); }
+ }
+ } else if (mode.helperType && help[mode.helperType]) {
+ found.push(help[mode.helperType]);
+ } else if (help[mode.name]) {
+ found.push(help[mode.name]);
+ }
+ for (var i$1 = 0; i$1 < help._global.length; i$1++) {
+ var cur = help._global[i$1];
+ if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
+ { found.push(cur.val); }
+ }
+ return found
+ },
+
+ getStateAfter: function(line, precise) {
+ var doc = this.doc;
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
+ return getContextBefore(this, line + 1, precise).state
+ },
+
+ cursorCoords: function(start, mode) {
+ var pos, range$$1 = this.doc.sel.primary();
+ if (start == null) { pos = range$$1.head; }
+ else if (typeof start == "object") { pos = clipPos(this.doc, start); }
+ else { pos = start ? range$$1.from() : range$$1.to(); }
+ return cursorCoords(this, pos, mode || "page")
+ },
+
+ charCoords: function(pos, mode) {
+ return charCoords(this, clipPos(this.doc, pos), mode || "page")
+ },
+
+ coordsChar: function(coords, mode) {
+ coords = fromCoordSystem(this, coords, mode || "page");
+ return coordsChar(this, coords.left, coords.top)
+ },
+
+ lineAtHeight: function(height, mode) {
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
+ return lineAtHeight(this.doc, height + this.display.viewOffset)
+ },
+ heightAtLine: function(line, mode, includeWidgets) {
+ var end = false, lineObj;
+ if (typeof line == "number") {
+ var last = this.doc.first + this.doc.size - 1;
+ if (line < this.doc.first) { line = this.doc.first; }
+ else if (line > last) { line = last; end = true; }
+ lineObj = getLine(this.doc, line);
+ } else {
+ lineObj = line;
+ }
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
+ (end ? this.doc.height - heightAtLine(lineObj) : 0)
+ },
+
+ defaultTextHeight: function() { return textHeight(this.display) },
+ defaultCharWidth: function() { return charWidth(this.display) },
+
+ getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
+
+ addWidget: function(pos, node, scroll, vert, horiz) {
+ var display = this.display;
+ pos = cursorCoords(this, clipPos(this.doc, pos));
+ var top = pos.bottom, left = pos.left;
+ node.style.position = "absolute";
+ node.setAttribute("cm-ignore-events", "true");
+ this.display.input.setUneditable(node);
+ display.sizer.appendChild(node);
+ if (vert == "over") {
+ top = pos.top;
+ } else if (vert == "above" || vert == "near") {
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
+ { top = pos.top - node.offsetHeight; }
+ else if (pos.bottom + node.offsetHeight <= vspace)
+ { top = pos.bottom; }
+ if (left + node.offsetWidth > hspace)
+ { left = hspace - node.offsetWidth; }
+ }
+ node.style.top = top + "px";
+ node.style.left = node.style.right = "";
+ if (horiz == "right") {
+ left = display.sizer.clientWidth - node.offsetWidth;
+ node.style.right = "0px";
+ } else {
+ if (horiz == "left") { left = 0; }
+ else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
+ node.style.left = left + "px";
+ }
+ if (scroll)
+ { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
+ },
+
+ triggerOnKeyDown: methodOp(onKeyDown),
+ triggerOnKeyPress: methodOp(onKeyPress),
+ triggerOnKeyUp: onKeyUp,
+ triggerOnMouseDown: methodOp(onMouseDown),
+
+ execCommand: function(cmd) {
+ if (commands.hasOwnProperty(cmd))
+ { return commands[cmd].call(null, this) }
+ },
+
+ triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
+
+ findPosH: function(from, amount, unit, visually) {
+ var this$1 = this;
+
+ var dir = 1;
+ if (amount < 0) { dir = -1; amount = -amount; }
+ var cur = clipPos(this.doc, from);
+ for (var i = 0; i < amount; ++i) {
+ cur = findPosH(this$1.doc, cur, dir, unit, visually);
+ if (cur.hitSide) { break }
+ }
+ return cur
+ },
+
+ moveH: methodOp(function(dir, unit) {
+ var this$1 = this;
+
+ this.extendSelectionsBy(function (range$$1) {
+ if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
+ { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
+ else
+ { return dir < 0 ? range$$1.from() : range$$1.to() }
+ }, sel_move);
+ }),
+
+ deleteH: methodOp(function(dir, unit) {
+ var sel = this.doc.sel, doc = this.doc;
+ if (sel.somethingSelected())
+ { doc.replaceSelection("", null, "+delete"); }
+ else
+ { deleteNearSelection(this, function (range$$1) {
+ var other = findPosH(doc, range$$1.head, dir, unit, false);
+ return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
+ }); }
+ }),
+
+ findPosV: function(from, amount, unit, goalColumn) {
+ var this$1 = this;
+
+ var dir = 1, x = goalColumn;
+ if (amount < 0) { dir = -1; amount = -amount; }
+ var cur = clipPos(this.doc, from);
+ for (var i = 0; i < amount; ++i) {
+ var coords = cursorCoords(this$1, cur, "div");
+ if (x == null) { x = coords.left; }
+ else { coords.left = x; }
+ cur = findPosV(this$1, coords, dir, unit);
+ if (cur.hitSide) { break }
+ }
+ return cur
+ },
+
+ moveV: methodOp(function(dir, unit) {
+ var this$1 = this;
+
+ var doc = this.doc, goals = [];
+ var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
+ doc.extendSelectionsBy(function (range$$1) {
+ if (collapse)
+ { return dir < 0 ? range$$1.from() : range$$1.to() }
+ var headPos = cursorCoords(this$1, range$$1.head, "div");
+ if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
+ goals.push(headPos.left);
+ var pos = findPosV(this$1, headPos, dir, unit);
+ if (unit == "page" && range$$1 == doc.sel.primary())
+ { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
+ return pos
+ }, sel_move);
+ if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
+ { doc.sel.ranges[i].goalColumn = goals[i]; } }
+ }),
+
+ // Find the word at the given position (as returned by coordsChar).
+ findWordAt: function(pos) {
+ var doc = this.doc, line = getLine(doc, pos.line).text;
+ var start = pos.ch, end = pos.ch;
+ if (line) {
+ var helper = this.getHelper(pos, "wordChars");
+ if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
+ var startChar = line.charAt(start);
+ var check = isWordChar(startChar, helper)
+ ? function (ch) { return isWordChar(ch, helper); }
+ : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
+ : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
+ while (start > 0 && check(line.charAt(start - 1))) { --start; }
+ while (end < line.length && check(line.charAt(end))) { ++end; }
+ }
+ return new Range(Pos(pos.line, start), Pos(pos.line, end))
+ },
+
+ toggleOverwrite: function(value) {
+ if (value != null && value == this.state.overwrite) { return }
+ if (this.state.overwrite = !this.state.overwrite)
+ { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
+ else
+ { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
+
+ signal(this, "overwriteToggle", this, this.state.overwrite);
+ },
+ hasFocus: function() { return this.display.input.getField() == activeElt() },
+ isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
+
+ scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
+ getScrollInfo: function() {
+ var scroller = this.display.scroller;
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
+ height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
+ width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
+ clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
+ },
+
+ scrollIntoView: methodOp(function(range$$1, margin) {
+ if (range$$1 == null) {
+ range$$1 = {from: this.doc.sel.primary().head, to: null};
+ if (margin == null) { margin = this.options.cursorScrollMargin; }
+ } else if (typeof range$$1 == "number") {
+ range$$1 = {from: Pos(range$$1, 0), to: null};
+ } else if (range$$1.from == null) {
+ range$$1 = {from: range$$1, to: null};
+ }
+ if (!range$$1.to) { range$$1.to = range$$1.from; }
+ range$$1.margin = margin || 0;
+
+ if (range$$1.from.line != null) {
+ scrollToRange(this, range$$1);
+ } else {
+ scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
+ }
+ }),
+
+ setSize: methodOp(function(width, height) {
+ var this$1 = this;
+
+ var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
+ if (width != null) { this.display.wrapper.style.width = interpret(width); }
+ if (height != null) { this.display.wrapper.style.height = interpret(height); }
+ if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
+ var lineNo$$1 = this.display.viewFrom;
+ this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
+ if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
+ { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
+ ++lineNo$$1;
+ });
+ this.curOp.forceUpdate = true;
+ signal(this, "refresh", this);
+ }),
+
+ operation: function(f){return runInOp(this, f)},
+ startOperation: function(){return startOperation(this)},
+ endOperation: function(){return endOperation(this)},
+
+ refresh: methodOp(function() {
+ var oldHeight = this.display.cachedTextHeight;
+ regChange(this);
+ this.curOp.forceUpdate = true;
+ clearCaches(this);
+ scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
+ updateGutterSpace(this);
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
+ { estimateLineHeights(this); }
+ signal(this, "refresh", this);
+ }),
+
+ swapDoc: methodOp(function(doc) {
+ var old = this.doc;
+ old.cm = null;
+ attachDoc(this, doc);
+ clearCaches(this);
+ this.display.input.reset();
+ scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
+ this.curOp.forceScroll = true;
+ signalLater(this, "swapDoc", this, old);
+ return old
+ }),
+
+ getInputField: function(){return this.display.input.getField()},
+ getWrapperElement: function(){return this.display.wrapper},
+ getScrollerElement: function(){return this.display.scroller},
+ getGutterElement: function(){return this.display.gutters}
+ };
+ eventMixin(CodeMirror);
+
+ CodeMirror.registerHelper = function(type, name, value) {
+ if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
+ helpers[type][name] = value;
+ };
+ CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
+ CodeMirror.registerHelper(type, name, value);
+ helpers[type]._global.push({pred: predicate, val: value});
+ };
+};
+
+// Used for horizontal relative motion. Dir is -1 or 1 (left or
+// right), unit can be "char", "column" (like char, but doesn't
+// cross line boundaries), "word" (across next word), or "group" (to
+// the start of next group of word or non-word-non-whitespace
+// chars). The visually param controls whether, in right-to-left
+// text, direction 1 means to move towards the next index in the
+// string, or towards the character to the right of the current
+// position. The resulting position will have a hitSide=true
+// property if it reached the end of the document.
+function findPosH(doc, pos, dir, unit, visually) {
+ var oldPos = pos;
+ var origDir = dir;
+ var lineObj = getLine(doc, pos.line);
+ function findNextLine() {
+ var l = pos.line + dir;
+ if (l < doc.first || l >= doc.first + doc.size) { return false }
+ pos = new Pos(l, pos.ch, pos.sticky);
+ return lineObj = getLine(doc, l)
+ }
+ function moveOnce(boundToLine) {
+ var next;
+ if (visually) {
+ next = moveVisually(doc.cm, lineObj, pos, dir);
+ } else {
+ next = moveLogically(lineObj, pos, dir);
+ }
+ if (next == null) {
+ if (!boundToLine && findNextLine())
+ { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
+ else
+ { return false }
+ } else {
+ pos = next;
+ }
+ return true
+ }
+
+ if (unit == "char") {
+ moveOnce();
+ } else if (unit == "column") {
+ moveOnce(true);
+ } else if (unit == "word" || unit == "group") {
+ var sawType = null, group = unit == "group";
+ var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
+ for (var first = true;; first = false) {
+ if (dir < 0 && !moveOnce(!first)) { break }
+ var cur = lineObj.text.charAt(pos.ch) || "\n";
+ var type = isWordChar(cur, helper) ? "w"
+ : group && cur == "\n" ? "n"
+ : !group || /\s/.test(cur) ? null
+ : "p";
+ if (group && !first && !type) { type = "s"; }
+ if (sawType && sawType != type) {
+ if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
+ break
+ }
+
+ if (type) { sawType = type; }
+ if (dir > 0 && !moveOnce(!first)) { break }
+ }
+ }
+ var result = skipAtomic(doc, pos, oldPos, origDir, true);
+ if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
+ return result
+}
+
+// For relative vertical movement. Dir may be -1 or 1. Unit can be
+// "page" or "line". The resulting position will have a hitSide=true
+// property if it reached the end of the document.
+function findPosV(cm, pos, dir, unit) {
+ var doc = cm.doc, x = pos.left, y;
+ if (unit == "page") {
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
+ var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
+ y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
+
+ } else if (unit == "line") {
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
+ }
+ var target;
+ for (;;) {
+ target = coordsChar(cm, x, y);
+ if (!target.outside) { break }
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
+ y += dir * 5;
+ }
+ return target
+}
+
+// CONTENTEDITABLE INPUT STYLE
+
+var ContentEditableInput = function(cm) {
+ this.cm = cm;
+ this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
+ this.polling = new Delayed();
+ this.composing = null;
+ this.gracePeriod = false;
+ this.readDOMTimeout = null;
+};
+
+ContentEditableInput.prototype.init = function (display) {
+ var this$1 = this;
+
+ var input = this, cm = input.cm;
+ var div = input.div = display.lineDiv;
+ disableBrowserMagic(div, cm.options.spellcheck);
+
+ on(div, "paste", function (e) {
+ if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
+ // IE doesn't fire input events, so we schedule a read for the pasted content in this way
+ if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
+ });
+
+ on(div, "compositionstart", function (e) {
+ this$1.composing = {data: e.data, done: false};
+ });
+ on(div, "compositionupdate", function (e) {
+ if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
+ });
+ on(div, "compositionend", function (e) {
+ if (this$1.composing) {
+ if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
+ this$1.composing.done = true;
+ }
+ });
+
+ on(div, "touchstart", function () { return input.forceCompositionEnd(); });
+
+ on(div, "input", function () {
+ if (!this$1.composing) { this$1.readFromDOMSoon(); }
+ });
+
+ function onCopyCut(e) {
+ if (signalDOMEvent(cm, e)) { return }
+ if (cm.somethingSelected()) {
+ setLastCopied({lineWise: false, text: cm.getSelections()});
+ if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
+ } else if (!cm.options.lineWiseCopyCut) {
+ return
+ } else {
+ var ranges = copyableRanges(cm);
+ setLastCopied({lineWise: true, text: ranges.text});
+ if (e.type == "cut") {
+ cm.operation(function () {
+ cm.setSelections(ranges.ranges, 0, sel_dontScroll);
+ cm.replaceSelection("", null, "cut");
+ });
+ }
+ }
+ if (e.clipboardData) {
+ e.clipboardData.clearData();
+ var content = lastCopied.text.join("\n");
+ // iOS exposes the clipboard API, but seems to discard content inserted into it
+ e.clipboardData.setData("Text", content);
+ if (e.clipboardData.getData("Text") == content) {
+ e.preventDefault();
+ return
+ }
+ }
+ // Old-fashioned briefly-focus-a-textarea hack
+ var kludge = hiddenTextarea(), te = kludge.firstChild;
+ cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
+ te.value = lastCopied.text.join("\n");
+ var hadFocus = document.activeElement;
+ selectInput(te);
+ setTimeout(function () {
+ cm.display.lineSpace.removeChild(kludge);
+ hadFocus.focus();
+ if (hadFocus == div) { input.showPrimarySelection(); }
+ }, 50);
+ }
+ on(div, "copy", onCopyCut);
+ on(div, "cut", onCopyCut);
+};
+
+ContentEditableInput.prototype.prepareSelection = function () {
+ var result = prepareSelection(this.cm, false);
+ result.focus = this.cm.state.focused;
+ return result
+};
+
+ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
+ if (!info || !this.cm.display.view.length) { return }
+ if (info.focus || takeFocus) { this.showPrimarySelection(); }
+ this.showMultipleSelections(info);
+};
+
+ContentEditableInput.prototype.showPrimarySelection = function () {
+ var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
+ var from = prim.from(), to = prim.to();
+
+ if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
+ sel.removeAllRanges();
+ return
+ }
+
+ var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
+ var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
+ if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
+ cmp(minPos(curAnchor, curFocus), from) == 0 &&
+ cmp(maxPos(curAnchor, curFocus), to) == 0)
+ { return }
+
+ var view = cm.display.view;
+ var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
+ {node: view[0].measure.map[2], offset: 0};
+ var end = to.line < cm.display.viewTo && posToDOM(cm, to);
+ if (!end) {
+ var measure = view[view.length - 1].measure;
+ var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
+ end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
+ }
+
+ if (!start || !end) {
+ sel.removeAllRanges();
+ return
+ }
+
+ var old = sel.rangeCount && sel.getRangeAt(0), rng;
+ try { rng = range(start.node, start.offset, end.offset, end.node); }
+ catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
+ if (rng) {
+ if (!gecko && cm.state.focused) {
+ sel.collapse(start.node, start.offset);
+ if (!rng.collapsed) {
+ sel.removeAllRanges();
+ sel.addRange(rng);
+ }
+ } else {
+ sel.removeAllRanges();
+ sel.addRange(rng);
+ }
+ if (old && sel.anchorNode == null) { sel.addRange(old); }
+ else if (gecko) { this.startGracePeriod(); }
+ }
+ this.rememberSelection();
+};
+
+ContentEditableInput.prototype.startGracePeriod = function () {
+ var this$1 = this;
+
+ clearTimeout(this.gracePeriod);
+ this.gracePeriod = setTimeout(function () {
+ this$1.gracePeriod = false;
+ if (this$1.selectionChanged())
+ { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
+ }, 20);
+};
+
+ContentEditableInput.prototype.showMultipleSelections = function (info) {
+ removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
+ removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
+};
+
+ContentEditableInput.prototype.rememberSelection = function () {
+ var sel = window.getSelection();
+ this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
+ this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
+};
+
+ContentEditableInput.prototype.selectionInEditor = function () {
+ var sel = window.getSelection();
+ if (!sel.rangeCount) { return false }
+ var node = sel.getRangeAt(0).commonAncestorContainer;
+ return contains(this.div, node)
+};
+
+ContentEditableInput.prototype.focus = function () {
+ if (this.cm.options.readOnly != "nocursor") {
+ if (!this.selectionInEditor())
+ { this.showSelection(this.prepareSelection(), true); }
+ this.div.focus();
+ }
+};
+ContentEditableInput.prototype.blur = function () { this.div.blur(); };
+ContentEditableInput.prototype.getField = function () { return this.div };
+
+ContentEditableInput.prototype.supportsTouch = function () { return true };
+
+ContentEditableInput.prototype.receivedFocus = function () {
+ var input = this;
+ if (this.selectionInEditor())
+ { this.pollSelection(); }
+ else
+ { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
+
+ function poll() {
+ if (input.cm.state.focused) {
+ input.pollSelection();
+ input.polling.set(input.cm.options.pollInterval, poll);
+ }
+ }
+ this.polling.set(this.cm.options.pollInterval, poll);
+};
+
+ContentEditableInput.prototype.selectionChanged = function () {
+ var sel = window.getSelection();
+ return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
+ sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
+};
+
+ContentEditableInput.prototype.pollSelection = function () {
+ if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
+ var sel = window.getSelection(), cm = this.cm;
+ // On Android Chrome (version 56, at least), backspacing into an
+ // uneditable block element will put the cursor in that element,
+ // and then, because it's not editable, hide the virtual keyboard.
+ // Because Android doesn't allow us to actually detect backspace
+ // presses in a sane way, this code checks for when that happens
+ // and simulates a backspace press in this case.
+ if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
+ this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
+ this.blur();
+ this.focus();
+ return
+ }
+ if (this.composing) { return }
+ this.rememberSelection();
+ var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
+ var head = domToPos(cm, sel.focusNode, sel.focusOffset);
+ if (anchor && head) { runInOp(cm, function () {
+ setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
+ if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
+ }); }
+};
+
+ContentEditableInput.prototype.pollContent = function () {
+ if (this.readDOMTimeout != null) {
+ clearTimeout(this.readDOMTimeout);
+ this.readDOMTimeout = null;
+ }
+
+ var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
+ var from = sel.from(), to = sel.to();
+ if (from.ch == 0 && from.line > cm.firstLine())
+ { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
+ if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
+ { to = Pos(to.line + 1, 0); }
+ if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
+
+ var fromIndex, fromLine, fromNode;
+ if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
+ fromLine = lineNo(display.view[0].line);
+ fromNode = display.view[0].node;
+ } else {
+ fromLine = lineNo(display.view[fromIndex].line);
+ fromNode = display.view[fromIndex - 1].node.nextSibling;
+ }
+ var toIndex = findViewIndex(cm, to.line);
+ var toLine, toNode;
+ if (toIndex == display.view.length - 1) {
+ toLine = display.viewTo - 1;
+ toNode = display.lineDiv.lastChild;
+ } else {
+ toLine = lineNo(display.view[toIndex + 1].line) - 1;
+ toNode = display.view[toIndex + 1].node.previousSibling;
+ }
+
+ if (!fromNode) { return false }
+ var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
+ var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
+ while (newText.length > 1 && oldText.length > 1) {
+ if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
+ else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
+ else { break }
+ }
+
+ var cutFront = 0, cutEnd = 0;
+ var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
+ while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
+ { ++cutFront; }
+ var newBot = lst(newText), oldBot = lst(oldText);
+ var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
+ oldBot.length - (oldText.length == 1 ? cutFront : 0));
+ while (cutEnd < maxCutEnd &&
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
+ { ++cutEnd; }
+ // Try to move start of change to start of selection if ambiguous
+ if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
+ while (cutFront && cutFront > from.ch &&
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
+ cutFront--;
+ cutEnd++;
+ }
+ }
+
+ newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
+ newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
+
+ var chFrom = Pos(fromLine, cutFront);
+ var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
+ if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
+ replaceRange(cm.doc, newText, chFrom, chTo, "+input");
+ return true
+ }
+};
+
+ContentEditableInput.prototype.ensurePolled = function () {
+ this.forceCompositionEnd();
+};
+ContentEditableInput.prototype.reset = function () {
+ this.forceCompositionEnd();
+};
+ContentEditableInput.prototype.forceCompositionEnd = function () {
+ if (!this.composing) { return }
+ clearTimeout(this.readDOMTimeout);
+ this.composing = null;
+ this.updateFromDOM();
+ this.div.blur();
+ this.div.focus();
+};
+ContentEditableInput.prototype.readFromDOMSoon = function () {
+ var this$1 = this;
+
+ if (this.readDOMTimeout != null) { return }
+ this.readDOMTimeout = setTimeout(function () {
+ this$1.readDOMTimeout = null;
+ if (this$1.composing) {
+ if (this$1.composing.done) { this$1.composing = null; }
+ else { return }
+ }
+ this$1.updateFromDOM();
+ }, 80);
+};
+
+ContentEditableInput.prototype.updateFromDOM = function () {
+ var this$1 = this;
+
+ if (this.cm.isReadOnly() || !this.pollContent())
+ { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
+};
+
+ContentEditableInput.prototype.setUneditable = function (node) {
+ node.contentEditable = "false";
+};
+
+ContentEditableInput.prototype.onKeyPress = function (e) {
+ if (e.charCode == 0) { return }
+ e.preventDefault();
+ if (!this.cm.isReadOnly())
+ { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
+};
+
+ContentEditableInput.prototype.readOnlyChanged = function (val) {
+ this.div.contentEditable = String(val != "nocursor");
+};
+
+ContentEditableInput.prototype.onContextMenu = function () {};
+ContentEditableInput.prototype.resetPosition = function () {};
+
+ContentEditableInput.prototype.needsContentAttribute = true;
+
+function posToDOM(cm, pos) {
+ var view = findViewForLine(cm, pos.line);
+ if (!view || view.hidden) { return null }
+ var line = getLine(cm.doc, pos.line);
+ var info = mapFromLineView(view, line, pos.line);
+
+ var order = getOrder(line, cm.doc.direction), side = "left";
+ if (order) {
+ var partPos = getBidiPartAt(order, pos.ch);
+ side = partPos % 2 ? "right" : "left";
+ }
+ var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
+ result.offset = result.collapse == "right" ? result.end : result.start;
+ return result
+}
+
+function isInGutter(node) {
+ for (var scan = node; scan; scan = scan.parentNode)
+ { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
+ return false
+}
+
+function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
+
+function domTextBetween(cm, from, to, fromLine, toLine) {
+ var text = "", closing = false, lineSep = cm.doc.lineSeparator();
+ function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
+ function close() {
+ if (closing) {
+ text += lineSep;
+ closing = false;
+ }
+ }
+ function addText(str) {
+ if (str) {
+ close();
+ text += str;
+ }
+ }
+ function walk(node) {
+ if (node.nodeType == 1) {
+ var cmText = node.getAttribute("cm-text");
+ if (cmText != null) {
+ addText(cmText || node.textContent.replace(/\u200b/g, ""));
+ return
+ }
+ var markerID = node.getAttribute("cm-marker"), range$$1;
+ if (markerID) {
+ var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
+ if (found.length && (range$$1 = found[0].find(0)))
+ { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
+ return
+ }
+ if (node.getAttribute("contenteditable") == "false") { return }
+ var isBlock = /^(pre|div|p)$/i.test(node.nodeName);
+ if (isBlock) { close(); }
+ for (var i = 0; i < node.childNodes.length; i++)
+ { walk(node.childNodes[i]); }
+ if (isBlock) { closing = true; }
+ } else if (node.nodeType == 3) {
+ addText(node.nodeValue);
+ }
+ }
+ for (;;) {
+ walk(from);
+ if (from == to) { break }
+ from = from.nextSibling;
+ }
+ return text
+}
+
+function domToPos(cm, node, offset) {
+ var lineNode;
+ if (node == cm.display.lineDiv) {
+ lineNode = cm.display.lineDiv.childNodes[offset];
+ if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
+ node = null; offset = 0;
+ } else {
+ for (lineNode = node;; lineNode = lineNode.parentNode) {
+ if (!lineNode || lineNode == cm.display.lineDiv) { return null }
+ if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
+ }
+ }
+ for (var i = 0; i < cm.display.view.length; i++) {
+ var lineView = cm.display.view[i];
+ if (lineView.node == lineNode)
+ { return locateNodeInLineView(lineView, node, offset) }
+ }
+}
+
+function locateNodeInLineView(lineView, node, offset) {
+ var wrapper = lineView.text.firstChild, bad = false;
+ if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
+ if (node == wrapper) {
+ bad = true;
+ node = wrapper.childNodes[offset];
+ offset = 0;
+ if (!node) {
+ var line = lineView.rest ? lst(lineView.rest) : lineView.line;
+ return badPos(Pos(lineNo(line), line.text.length), bad)
+ }
+ }
+
+ var textNode = node.nodeType == 3 ? node : null, topNode = node;
+ if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
+ textNode = node.firstChild;
+ if (offset) { offset = textNode.nodeValue.length; }
+ }
+ while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
+ var measure = lineView.measure, maps = measure.maps;
+
+ function find(textNode, topNode, offset) {
+ for (var i = -1; i < (maps ? maps.length : 0); i++) {
+ var map$$1 = i < 0 ? measure.map : maps[i];
+ for (var j = 0; j < map$$1.length; j += 3) {
+ var curNode = map$$1[j + 2];
+ if (curNode == textNode || curNode == topNode) {
+ var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
+ var ch = map$$1[j] + offset;
+ if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
+ return Pos(line, ch)
+ }
+ }
+ }
+ }
+ var found = find(textNode, topNode, offset);
+ if (found) { return badPos(found, bad) }
+
+ // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
+ for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
+ found = find(after, after.firstChild, 0);
+ if (found)
+ { return badPos(Pos(found.line, found.ch - dist), bad) }
+ else
+ { dist += after.textContent.length; }
+ }
+ for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
+ found = find(before, before.firstChild, -1);
+ if (found)
+ { return badPos(Pos(found.line, found.ch + dist$1), bad) }
+ else
+ { dist$1 += before.textContent.length; }
+ }
+}
+
+// TEXTAREA INPUT STYLE
+
+var TextareaInput = function(cm) {
+ this.cm = cm;
+ // See input.poll and input.reset
+ this.prevInput = "";
+
+ // Flag that indicates whether we expect input to appear real soon
+ // now (after some event like 'keypress' or 'input') and are
+ // polling intensively.
+ this.pollingFast = false;
+ // Self-resetting timeout for the poller
+ this.polling = new Delayed();
+ // Used to work around IE issue with selection being forgotten when focus moves away from textarea
+ this.hasSelection = false;
+ this.composing = null;
+};
+
+TextareaInput.prototype.init = function (display) {
+ var this$1 = this;
+
+ var input = this, cm = this.cm;
+ this.createField(display);
+ var te = this.textarea;
+
+ display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
+
+ // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
+ if (ios) { te.style.width = "0px"; }
+
+ on(te, "input", function () {
+ if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
+ input.poll();
+ });
+
+ on(te, "paste", function (e) {
+ if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
+
+ cm.state.pasteIncoming = true;
+ input.fastPoll();
+ });
+
+ function prepareCopyCut(e) {
+ if (signalDOMEvent(cm, e)) { return }
+ if (cm.somethingSelected()) {
+ setLastCopied({lineWise: false, text: cm.getSelections()});
+ } else if (!cm.options.lineWiseCopyCut) {
+ return
+ } else {
+ var ranges = copyableRanges(cm);
+ setLastCopied({lineWise: true, text: ranges.text});
+ if (e.type == "cut") {
+ cm.setSelections(ranges.ranges, null, sel_dontScroll);
+ } else {
+ input.prevInput = "";
+ te.value = ranges.text.join("\n");
+ selectInput(te);
+ }
+ }
+ if (e.type == "cut") { cm.state.cutIncoming = true; }
+ }
+ on(te, "cut", prepareCopyCut);
+ on(te, "copy", prepareCopyCut);
+
+ on(display.scroller, "paste", function (e) {
+ if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
+ cm.state.pasteIncoming = true;
+ input.focus();
+ });
+
+ // Prevent normal selection in the editor (we handle our own)
+ on(display.lineSpace, "selectstart", function (e) {
+ if (!eventInWidget(display, e)) { e_preventDefault(e); }
+ });
+
+ on(te, "compositionstart", function () {
+ var start = cm.getCursor("from");
+ if (input.composing) { input.composing.range.clear(); }
+ input.composing = {
+ start: start,
+ range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
+ };
+ });
+ on(te, "compositionend", function () {
+ if (input.composing) {
+ input.poll();
+ input.composing.range.clear();
+ input.composing = null;
+ }
+ });
+};
+
+TextareaInput.prototype.createField = function (_display) {
+ // Wraps and hides input textarea
+ this.wrapper = hiddenTextarea();
+ // The semihidden textarea that is focused when the editor is
+ // focused, and receives input.
+ this.textarea = this.wrapper.firstChild;
+};
+
+TextareaInput.prototype.prepareSelection = function () {
+ // Redraw the selection and/or cursor
+ var cm = this.cm, display = cm.display, doc = cm.doc;
+ var result = prepareSelection(cm);
+
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
+ if (cm.options.moveInputWithCursor) {
+ var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
+ var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
+ result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
+ headPos.top + lineOff.top - wrapOff.top));
+ result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
+ headPos.left + lineOff.left - wrapOff.left));
+ }
+
+ return result
+};
+
+TextareaInput.prototype.showSelection = function (drawn) {
+ var cm = this.cm, display = cm.display;
+ removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
+ removeChildrenAndAdd(display.selectionDiv, drawn.selection);
+ if (drawn.teTop != null) {
+ this.wrapper.style.top = drawn.teTop + "px";
+ this.wrapper.style.left = drawn.teLeft + "px";
+ }
+};
+
+// Reset the input to correspond to the selection (or to be empty,
+// when not typing and nothing is selected)
+TextareaInput.prototype.reset = function (typing) {
+ if (this.contextMenuPending || this.composing) { return }
+ var cm = this.cm;
+ if (cm.somethingSelected()) {
+ this.prevInput = "";
+ var content = cm.getSelection();
+ this.textarea.value = content;
+ if (cm.state.focused) { selectInput(this.textarea); }
+ if (ie && ie_version >= 9) { this.hasSelection = content; }
+ } else if (!typing) {
+ this.prevInput = this.textarea.value = "";
+ if (ie && ie_version >= 9) { this.hasSelection = null; }
+ }
+};
+
+TextareaInput.prototype.getField = function () { return this.textarea };
+
+TextareaInput.prototype.supportsTouch = function () { return false };
+
+TextareaInput.prototype.focus = function () {
+ if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
+ try { this.textarea.focus(); }
+ catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
+ }
+};
+
+TextareaInput.prototype.blur = function () { this.textarea.blur(); };
+
+TextareaInput.prototype.resetPosition = function () {
+ this.wrapper.style.top = this.wrapper.style.left = 0;
+};
+
+TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
+
+// Poll for input changes, using the normal rate of polling. This
+// runs as long as the editor is focused.
+TextareaInput.prototype.slowPoll = function () {
+ var this$1 = this;
+
+ if (this.pollingFast) { return }
+ this.polling.set(this.cm.options.pollInterval, function () {
+ this$1.poll();
+ if (this$1.cm.state.focused) { this$1.slowPoll(); }
+ });
+};
+
+// When an event has just come in that is likely to add or change
+// something in the input textarea, we poll faster, to ensure that
+// the change appears on the screen quickly.
+TextareaInput.prototype.fastPoll = function () {
+ var missed = false, input = this;
+ input.pollingFast = true;
+ function p() {
+ var changed = input.poll();
+ if (!changed && !missed) {missed = true; input.polling.set(60, p);}
+ else {input.pollingFast = false; input.slowPoll();}
+ }
+ input.polling.set(20, p);
+};
+
+// Read input from the textarea, and update the document to match.
+// When something is selected, it is present in the textarea, and
+// selected (unless it is huge, in which case a placeholder is
+// used). When nothing is selected, the cursor sits after previously
+// seen text (can be empty), which is stored in prevInput (we must
+// not reset the textarea when typing, because that breaks IME).
+TextareaInput.prototype.poll = function () {
+ var this$1 = this;
+
+ var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
+ // Since this is called a *lot*, try to bail out as cheaply as
+ // possible when it is clear that nothing happened. hasSelection
+ // will be the case when there is a lot of text in the textarea,
+ // in which case reading its value would be expensive.
+ if (this.contextMenuPending || !cm.state.focused ||
+ (hasSelection(input) && !prevInput && !this.composing) ||
+ cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
+ { return false }
+
+ var text = input.value;
+ // If nothing changed, bail.
+ if (text == prevInput && !cm.somethingSelected()) { return false }
+ // Work around nonsensical selection resetting in IE9/10, and
+ // inexplicable appearance of private area unicode characters on
+ // some key combos in Mac (#2689).
+ if (ie && ie_version >= 9 && this.hasSelection === text ||
+ mac && /[\uf700-\uf7ff]/.test(text)) {
+ cm.display.input.reset();
+ return false
+ }
+
+ if (cm.doc.sel == cm.display.selForContextMenu) {
+ var first = text.charCodeAt(0);
+ if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
+ if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
+ }
+ // Find the part of the input that is actually new
+ var same = 0, l = Math.min(prevInput.length, text.length);
+ while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
+
+ runInOp(cm, function () {
+ applyTextInput(cm, text.slice(same), prevInput.length - same,
+ null, this$1.composing ? "*compose" : null);
+
+ // Don't leave long text in the textarea, since it makes further polling slow
+ if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
+ else { this$1.prevInput = text; }
+
+ if (this$1.composing) {
+ this$1.composing.range.clear();
+ this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
+ {className: "CodeMirror-composing"});
+ }
+ });
+ return true
+};
+
+TextareaInput.prototype.ensurePolled = function () {
+ if (this.pollingFast && this.poll()) { this.pollingFast = false; }
+};
+
+TextareaInput.prototype.onKeyPress = function () {
+ if (ie && ie_version >= 9) { this.hasSelection = null; }
+ this.fastPoll();
+};
+
+TextareaInput.prototype.onContextMenu = function (e) {
+ var input = this, cm = input.cm, display = cm.display, te = input.textarea;
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
+ if (!pos || presto) { return } // Opera is difficult.
+
+ // Reset the current text selection only if the click is done outside of the selection
+ // and 'resetSelectionOnContextMenu' option is true.
+ var reset = cm.options.resetSelectionOnContextMenu;
+ if (reset && cm.doc.sel.contains(pos) == -1)
+ { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
+
+ var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
+ input.wrapper.style.cssText = "position: absolute";
+ var wrapperBox = input.wrapper.getBoundingClientRect();
+ te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
+ var oldScrollY;
+ if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
+ display.input.focus();
+ if (webkit) { window.scrollTo(null, oldScrollY); }
+ display.input.reset();
+ // Adds "Select all" to context menu in FF
+ if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
+ input.contextMenuPending = true;
+ display.selForContextMenu = cm.doc.sel;
+ clearTimeout(display.detectingSelectAll);
+
+ // Select-all will be greyed out if there's nothing to select, so
+ // this adds a zero-width space so that we can later check whether
+ // it got selected.
+ function prepareSelectAllHack() {
+ if (te.selectionStart != null) {
+ var selected = cm.somethingSelected();
+ var extval = "\u200b" + (selected ? te.value : "");
+ te.value = "\u21da"; // Used to catch context-menu undo
+ te.value = extval;
+ input.prevInput = selected ? "" : "\u200b";
+ te.selectionStart = 1; te.selectionEnd = extval.length;
+ // Re-set this, in case some other handler touched the
+ // selection in the meantime.
+ display.selForContextMenu = cm.doc.sel;
+ }
+ }
+ function rehide() {
+ input.contextMenuPending = false;
+ input.wrapper.style.cssText = oldWrapperCSS;
+ te.style.cssText = oldCSS;
+ if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
+
+ // Try to detect the user choosing select-all
+ if (te.selectionStart != null) {
+ if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
+ var i = 0, poll = function () {
+ if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
+ te.selectionEnd > 0 && input.prevInput == "\u200b") {
+ operation(cm, selectAll)(cm);
+ } else if (i++ < 10) {
+ display.detectingSelectAll = setTimeout(poll, 500);
+ } else {
+ display.selForContextMenu = null;
+ display.input.reset();
+ }
+ };
+ display.detectingSelectAll = setTimeout(poll, 200);
+ }
+ }
+
+ if (ie && ie_version >= 9) { prepareSelectAllHack(); }
+ if (captureRightClick) {
+ e_stop(e);
+ var mouseup = function () {
+ off(window, "mouseup", mouseup);
+ setTimeout(rehide, 20);
+ };
+ on(window, "mouseup", mouseup);
+ } else {
+ setTimeout(rehide, 50);
+ }
+};
+
+TextareaInput.prototype.readOnlyChanged = function (val) {
+ if (!val) { this.reset(); }
+ this.textarea.disabled = val == "nocursor";
+};
+
+TextareaInput.prototype.setUneditable = function () {};
+
+TextareaInput.prototype.needsContentAttribute = false;
+
+function fromTextArea(textarea, options) {
+ options = options ? copyObj(options) : {};
+ options.value = textarea.value;
+ if (!options.tabindex && textarea.tabIndex)
+ { options.tabindex = textarea.tabIndex; }
+ if (!options.placeholder && textarea.placeholder)
+ { options.placeholder = textarea.placeholder; }
+ // Set autofocus to true if this textarea is focused, or if it has
+ // autofocus and no other element is focused.
+ if (options.autofocus == null) {
+ var hasFocus = activeElt();
+ options.autofocus = hasFocus == textarea ||
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
+ }
+
+ function save() {textarea.value = cm.getValue();}
+
+ var realSubmit;
+ if (textarea.form) {
+ on(textarea.form, "submit", save);
+ // Deplorable hack to make the submit method do the right thing.
+ if (!options.leaveSubmitMethodAlone) {
+ var form = textarea.form;
+ realSubmit = form.submit;
+ try {
+ var wrappedSubmit = form.submit = function () {
+ save();
+ form.submit = realSubmit;
+ form.submit();
+ form.submit = wrappedSubmit;
+ };
+ } catch(e) {}
+ }
+ }
+
+ options.finishInit = function (cm) {
+ cm.save = save;
+ cm.getTextArea = function () { return textarea; };
+ cm.toTextArea = function () {
+ cm.toTextArea = isNaN; // Prevent this from being ran twice
+ save();
+ textarea.parentNode.removeChild(cm.getWrapperElement());
+ textarea.style.display = "";
+ if (textarea.form) {
+ off(textarea.form, "submit", save);
+ if (typeof textarea.form.submit == "function")
+ { textarea.form.submit = realSubmit; }
+ }
+ };
+ };
+
+ textarea.style.display = "none";
+ var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
+ options);
+ return cm
+}
+
+function addLegacyProps(CodeMirror) {
+ CodeMirror.off = off;
+ CodeMirror.on = on;
+ CodeMirror.wheelEventPixels = wheelEventPixels;
+ CodeMirror.Doc = Doc;
+ CodeMirror.splitLines = splitLinesAuto;
+ CodeMirror.countColumn = countColumn;
+ CodeMirror.findColumn = findColumn;
+ CodeMirror.isWordChar = isWordCharBasic;
+ CodeMirror.Pass = Pass;
+ CodeMirror.signal = signal;
+ CodeMirror.Line = Line;
+ CodeMirror.changeEnd = changeEnd;
+ CodeMirror.scrollbarModel = scrollbarModel;
+ CodeMirror.Pos = Pos;
+ CodeMirror.cmpPos = cmp;
+ CodeMirror.modes = modes;
+ CodeMirror.mimeModes = mimeModes;
+ CodeMirror.resolveMode = resolveMode;
+ CodeMirror.getMode = getMode;
+ CodeMirror.modeExtensions = modeExtensions;
+ CodeMirror.extendMode = extendMode;
+ CodeMirror.copyState = copyState;
+ CodeMirror.startState = startState;
+ CodeMirror.innerMode = innerMode;
+ CodeMirror.commands = commands;
+ CodeMirror.keyMap = keyMap;
+ CodeMirror.keyName = keyName;
+ CodeMirror.isModifierKey = isModifierKey;
+ CodeMirror.lookupKey = lookupKey;
+ CodeMirror.normalizeKeyMap = normalizeKeyMap;
+ CodeMirror.StringStream = StringStream;
+ CodeMirror.SharedTextMarker = SharedTextMarker;
+ CodeMirror.TextMarker = TextMarker;
+ CodeMirror.LineWidget = LineWidget;
+ CodeMirror.e_preventDefault = e_preventDefault;
+ CodeMirror.e_stopPropagation = e_stopPropagation;
+ CodeMirror.e_stop = e_stop;
+ CodeMirror.addClass = addClass;
+ CodeMirror.contains = contains;
+ CodeMirror.rmClass = rmClass;
+ CodeMirror.keyNames = keyNames;
+}
+
+// EDITOR CONSTRUCTOR
+
+defineOptions(CodeMirror$1);
+
+addEditorMethods(CodeMirror$1);
+
+// Set up methods on CodeMirror's prototype to redirect to the editor's document.
+var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
+for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
+ { CodeMirror$1.prototype[prop] = (function(method) {
+ return function() {return method.apply(this.doc, arguments)}
+ })(Doc.prototype[prop]); } }
+
+eventMixin(Doc);
+
+// INPUT HANDLING
+
+CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
+
+// MODE DEFINITION AND QUERYING
+
+// Extra arguments are stored as the mode's dependencies, which is
+// used by (legacy) mechanisms like loadmode.js to automatically
+// load a mode. (Preferred mechanism is the require/define calls.)
+CodeMirror$1.defineMode = function(name/*, mode, …*/) {
+ if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; }
+ defineMode.apply(this, arguments);
+};
+
+CodeMirror$1.defineMIME = defineMIME;
+
+// Minimal default mode.
+CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
+CodeMirror$1.defineMIME("text/plain", "null");
+
+// EXTENSIONS
+
+CodeMirror$1.defineExtension = function (name, func) {
+ CodeMirror$1.prototype[name] = func;
+};
+CodeMirror$1.defineDocExtension = function (name, func) {
+ Doc.prototype[name] = func;
+};
+
+CodeMirror$1.fromTextArea = fromTextArea;
+
+addLegacyProps(CodeMirror$1);
+
+CodeMirror$1.version = "5.36.0";
+
+return CodeMirror$1;
+
+})));
+
+},{}],22:[function(require,module,exports){
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.defineMode("javascript", function(config, parserConfig) {
+ var indentUnit = config.indentUnit;
+ var statementIndent = parserConfig.statementIndent;
+ var jsonldMode = parserConfig.jsonld;
+ var jsonMode = parserConfig.json || jsonldMode;
+ var isTS = parserConfig.typescript;
+ var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
+
+ // Tokenizer
+
+ var keywords = function(){
+ function kw(type) {return {type: type, style: "keyword"};}
+ var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d");
+ var operator = kw("operator"), atom = {type: "atom", style: "atom"};
+
+ return {
+ "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
+ "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C,
+ "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"),
+ "function": kw("function"), "catch": kw("catch"),
+ "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
+ "in": operator, "typeof": operator, "instanceof": operator,
+ "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
+ "this": kw("this"), "class": kw("class"), "super": kw("atom"),
+ "yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
+ "await": C
+ };
+ }();
+
+ var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
+ var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
+
+ function readRegexp(stream) {
+ var escaped = false, next, inSet = false;
+ while ((next = stream.next()) != null) {
+ if (!escaped) {
+ if (next == "/" && !inSet) return;
+ if (next == "[") inSet = true;
+ else if (inSet && next == "]") inSet = false;
+ }
+ escaped = !escaped && next == "\\";
+ }
+ }
+
+ // Used as scratch variables to communicate multiple values without
+ // consing up tons of objects.
+ var type, content;
+ function ret(tp, style, cont) {
+ type = tp; content = cont;
+ return style;
+ }
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (ch == '"' || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
+ return ret("number", "number");
+ } else if (ch == "." && stream.match("..")) {
+ return ret("spread", "meta");
+ } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+ return ret(ch);
+ } else if (ch == "=" && stream.eat(">")) {
+ return ret("=>", "operator");
+ } else if (ch == "0" && stream.eat(/x/i)) {
+ stream.eatWhile(/[\da-f]/i);
+ return ret("number", "number");
+ } else if (ch == "0" && stream.eat(/o/i)) {
+ stream.eatWhile(/[0-7]/i);
+ return ret("number", "number");
+ } else if (ch == "0" && stream.eat(/b/i)) {
+ stream.eatWhile(/[01]/i);
+ return ret("number", "number");
+ } else if (/\d/.test(ch)) {
+ stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
+ return ret("number", "number");
+ } else if (ch == "/") {
+ if (stream.eat("*")) {
+ state.tokenize = tokenComment;
+ return tokenComment(stream, state);
+ } else if (stream.eat("/")) {
+ stream.skipToEnd();
+ return ret("comment", "comment");
+ } else if (expressionAllowed(stream, state, 1)) {
+ readRegexp(stream);
+ stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
+ return ret("regexp", "string-2");
+ } else {
+ stream.eat("=");
+ return ret("operator", "operator", stream.current());
+ }
+ } else if (ch == "`") {
+ state.tokenize = tokenQuasi;
+ return tokenQuasi(stream, state);
+ } else if (ch == "#") {
+ stream.skipToEnd();
+ return ret("error", "error");
+ } else if (isOperatorChar.test(ch)) {
+ if (ch != ">" || !state.lexical || state.lexical.type != ">") {
+ if (stream.eat("=")) {
+ if (ch == "!" || ch == "=") stream.eat("=")
+ } else if (/[<>*+\-]/.test(ch)) {
+ stream.eat(ch)
+ if (ch == ">") stream.eat(ch)
+ }
+ }
+ return ret("operator", "operator", stream.current());
+ } else if (wordRE.test(ch)) {
+ stream.eatWhile(wordRE);
+ var word = stream.current()
+ if (state.lastType != ".") {
+ if (keywords.propertyIsEnumerable(word)) {
+ var kw = keywords[word]
+ return ret(kw.type, kw.style, word)
+ }
+ if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\(\w]/, false))
+ return ret("async", "keyword", word)
+ }
+ return ret("variable", "variable", word)
+ }
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next;
+ if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
+ state.tokenize = tokenBase;
+ return ret("jsonld-keyword", "meta");
+ }
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) break;
+ escaped = !escaped && next == "\\";
+ }
+ if (!escaped) state.tokenize = tokenBase;
+ return ret("string", "string");
+ };
+ }
+
+ function tokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == "/" && maybeEnd) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return ret("comment", "comment");
+ }
+
+ function tokenQuasi(stream, state) {
+ var escaped = false, next;
+ while ((next = stream.next()) != null) {
+ if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ escaped = !escaped && next == "\\";
+ }
+ return ret("quasi", "string-2", stream.current());
+ }
+
+ var brackets = "([{}])";
+ // This is a crude lookahead trick to try and notice that we're
+ // parsing the argument patterns for a fat-arrow function before we
+ // actually hit the arrow token. It only works if the arrow is on
+ // the same line as the arguments and there's no strange noise
+ // (comments) in between. Fallback is to only notice when we hit the
+ // arrow, and not declare the arguments as locals for the arrow
+ // body.
+ function findFatArrow(stream, state) {
+ if (state.fatArrowAt) state.fatArrowAt = null;
+ var arrow = stream.string.indexOf("=>", stream.start);
+ if (arrow < 0) return;
+
+ if (isTS) { // Try to skip TypeScript return type declarations after the arguments
+ var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
+ if (m) arrow = m.index
+ }
+
+ var depth = 0, sawSomething = false;
+ for (var pos = arrow - 1; pos >= 0; --pos) {
+ var ch = stream.string.charAt(pos);
+ var bracket = brackets.indexOf(ch);
+ if (bracket >= 0 && bracket < 3) {
+ if (!depth) { ++pos; break; }
+ if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
+ } else if (bracket >= 3 && bracket < 6) {
+ ++depth;
+ } else if (wordRE.test(ch)) {
+ sawSomething = true;
+ } else if (/["'\/]/.test(ch)) {
+ return;
+ } else if (sawSomething && !depth) {
+ ++pos;
+ break;
+ }
+ }
+ if (sawSomething && !depth) state.fatArrowAt = pos;
+ }
+
+ // Parser
+
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
+
+ function JSLexical(indented, column, type, align, prev, info) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.prev = prev;
+ this.info = info;
+ if (align != null) this.align = align;
+ }
+
+ function inScope(state, varname) {
+ for (var v = state.localVars; v; v = v.next)
+ if (v.name == varname) return true;
+ for (var cx = state.context; cx; cx = cx.prev) {
+ for (var v = cx.vars; v; v = v.next)
+ if (v.name == varname) return true;
+ }
+ }
+
+ function parseJS(state, style, type, content, stream) {
+ var cc = state.cc;
+ // Communicate our context to the combinators.
+ // (Less wasteful than consing up a hundred closures on every call.)
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
+
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = true;
+
+ while(true) {
+ var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
+ if (combinator(type, content)) {
+ while(cc.length && cc[cc.length - 1].lex)
+ cc.pop()();
+ if (cx.marked) return cx.marked;
+ if (type == "variable" && inScope(state, content)) return "variable-2";
+ return style;
+ }
+ }
+ }
+
+ // Combinator utils
+
+ var cx = {state: null, column: null, marked: null, cc: null};
+ function pass() {
+ for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
+ }
+ function cont() {
+ pass.apply(null, arguments);
+ return true;
+ }
+ function register(varname) {
+ function inList(list) {
+ for (var v = list; v; v = v.next)
+ if (v.name == varname) return true;
+ return false;
+ }
+ var state = cx.state;
+ cx.marked = "def";
+ if (state.context) {
+ if (inList(state.localVars)) return;
+ state.localVars = {name: varname, next: state.localVars};
+ } else {
+ if (inList(state.globalVars)) return;
+ if (parserConfig.globalVars)
+ state.globalVars = {name: varname, next: state.globalVars};
+ }
+ }
+
+ function isModifier(name) {
+ return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
+ }
+
+ // Combinators
+
+ var defaultVars = {name: "this", next: {name: "arguments"}};
+ function pushcontext() {
+ cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
+ cx.state.localVars = defaultVars;
+ }
+ function popcontext() {
+ cx.state.localVars = cx.state.context.vars;
+ cx.state.context = cx.state.context.prev;
+ }
+ function pushlex(type, info) {
+ var result = function() {
+ var state = cx.state, indent = state.indented;
+ if (state.lexical.type == "stat") indent = state.lexical.indented;
+ else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
+ indent = outer.indented;
+ state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
+ };
+ result.lex = true;
+ return result;
+ }
+ function poplex() {
+ var state = cx.state;
+ if (state.lexical.prev) {
+ if (state.lexical.type == ")")
+ state.indented = state.lexical.indented;
+ state.lexical = state.lexical.prev;
+ }
+ }
+ poplex.lex = true;
+
+ function expect(wanted) {
+ function exp(type) {
+ if (type == wanted) return cont();
+ else if (wanted == ";") return pass();
+ else return cont(exp);
+ };
+ return exp;
+ }
+
+ function statement(type, value) {
+ if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
+ if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
+ if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
+ if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
+ if (type == "debugger") return cont(expect(";"));
+ if (type == "{") return cont(pushlex("}"), block, poplex);
+ if (type == ";") return cont();
+ if (type == "if") {
+ if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
+ cx.state.cc.pop()();
+ return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
+ }
+ if (type == "function") return cont(functiondef);
+ if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
+ if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), className, poplex); }
+ if (type == "variable") {
+ if (isTS && value == "declare") {
+ cx.marked = "keyword"
+ return cont(statement)
+ } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
+ cx.marked = "keyword"
+ if (value == "enum") return cont(enumdef);
+ else if (value == "type") return cont(typeexpr, expect("operator"), typeexpr, expect(";"));
+ else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
+ } else if (isTS && value == "namespace") {
+ cx.marked = "keyword"
+ return cont(pushlex("form"), expression, block, poplex)
+ } else {
+ return cont(pushlex("stat"), maybelabel);
+ }
+ }
+ if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"),
+ block, poplex, poplex);
+ if (type == "case") return cont(expression, expect(":"));
+ if (type == "default") return cont(expect(":"));
+ if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
+ statement, poplex, popcontext);
+ if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
+ if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
+ if (type == "async") return cont(statement)
+ if (value == "@") return cont(expression, statement)
+ return pass(pushlex("stat"), expression, expect(";"), poplex);
+ }
+ function expression(type, value) {
+ return expressionInner(type, value, false);
+ }
+ function expressionNoComma(type, value) {
+ return expressionInner(type, value, true);
+ }
+ function parenExpr(type) {
+ if (type != "(") return pass()
+ return cont(pushlex(")"), expression, expect(")"), poplex)
+ }
+ function expressionInner(type, value, noComma) {
+ if (cx.state.fatArrowAt == cx.stream.start) {
+ var body = noComma ? arrowBodyNoComma : arrowBody;
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
+ else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
+ }
+
+ var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
+ if (type == "function") return cont(functiondef, maybeop);
+ if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); }
+ if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
+ if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
+ if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
+ if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
+ if (type == "{") return contCommasep(objprop, "}", null, maybeop);
+ if (type == "quasi") return pass(quasi, maybeop);
+ if (type == "new") return cont(maybeTarget(noComma));
+ if (type == "import") return cont(expression);
+ return cont();
+ }
+ function maybeexpression(type) {
+ if (type.match(/[;\}\)\],]/)) return pass();
+ return pass(expression);
+ }
+
+ function maybeoperatorComma(type, value) {
+ if (type == ",") return cont(expression);
+ return maybeoperatorNoComma(type, value, false);
+ }
+ function maybeoperatorNoComma(type, value, noComma) {
+ var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
+ var expr = noComma == false ? expression : expressionNoComma;
+ if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
+ if (type == "operator") {
+ if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
+ if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false))
+ return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
+ if (value == "?") return cont(expression, expect(":"), expr);
+ return cont(expr);
+ }
+ if (type == "quasi") { return pass(quasi, me); }
+ if (type == ";") return;
+ if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
+ if (type == ".") return cont(property, me);
+ if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
+ if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
+ if (type == "regexp") {
+ cx.state.lastType = cx.marked = "operator"
+ cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
+ return cont(expr)
+ }
+ }
+ function quasi(type, value) {
+ if (type != "quasi") return pass();
+ if (value.slice(value.length - 2) != "${") return cont(quasi);
+ return cont(expression, continueQuasi);
+ }
+ function continueQuasi(type) {
+ if (type == "}") {
+ cx.marked = "string-2";
+ cx.state.tokenize = tokenQuasi;
+ return cont(quasi);
+ }
+ }
+ function arrowBody(type) {
+ findFatArrow(cx.stream, cx.state);
+ return pass(type == "{" ? statement : expression);
+ }
+ function arrowBodyNoComma(type) {
+ findFatArrow(cx.stream, cx.state);
+ return pass(type == "{" ? statement : expressionNoComma);
+ }
+ function maybeTarget(noComma) {
+ return function(type) {
+ if (type == ".") return cont(noComma ? targetNoComma : target);
+ else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
+ else return pass(noComma ? expressionNoComma : expression);
+ };
+ }
+ function target(_, value) {
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
+ }
+ function targetNoComma(_, value) {
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
+ }
+ function maybelabel(type) {
+ if (type == ":") return cont(poplex, statement);
+ return pass(maybeoperatorComma, expect(";"), poplex);
+ }
+ function property(type) {
+ if (type == "variable") {cx.marked = "property"; return cont();}
+ }
+ function objprop(type, value) {
+ if (type == "async") {
+ cx.marked = "property";
+ return cont(objprop);
+ } else if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property";
+ if (value == "get" || value == "set") return cont(getterSetter);
+ var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
+ if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
+ cx.state.fatArrowAt = cx.stream.pos + m[0].length
+ return cont(afterprop);
+ } else if (type == "number" || type == "string") {
+ cx.marked = jsonldMode ? "property" : (cx.style + " property");
+ return cont(afterprop);
+ } else if (type == "jsonld-keyword") {
+ return cont(afterprop);
+ } else if (isTS && isModifier(value)) {
+ cx.marked = "keyword"
+ return cont(objprop)
+ } else if (type == "[") {
+ return cont(expression, maybetype, expect("]"), afterprop);
+ } else if (type == "spread") {
+ return cont(expressionNoComma, afterprop);
+ } else if (value == "*") {
+ cx.marked = "keyword";
+ return cont(objprop);
+ } else if (type == ":") {
+ return pass(afterprop)
+ }
+ }
+ function getterSetter(type) {
+ if (type != "variable") return pass(afterprop);
+ cx.marked = "property";
+ return cont(functiondef);
+ }
+ function afterprop(type) {
+ if (type == ":") return cont(expressionNoComma);
+ if (type == "(") return pass(functiondef);
+ }
+ function commasep(what, end, sep) {
+ function proceed(type, value) {
+ if (sep ? sep.indexOf(type) > -1 : type == ",") {
+ var lex = cx.state.lexical;
+ if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
+ return cont(function(type, value) {
+ if (type == end || value == end) return pass()
+ return pass(what)
+ }, proceed);
+ }
+ if (type == end || value == end) return cont();
+ return cont(expect(end));
+ }
+ return function(type, value) {
+ if (type == end || value == end) return cont();
+ return pass(what, proceed);
+ };
+ }
+ function contCommasep(what, end, info) {
+ for (var i = 3; i < arguments.length; i++)
+ cx.cc.push(arguments[i]);
+ return cont(pushlex(end, info), commasep(what, end), poplex);
+ }
+ function block(type) {
+ if (type == "}") return cont();
+ return pass(statement, block);
+ }
+ function maybetype(type, value) {
+ if (isTS) {
+ if (type == ":") return cont(typeexpr);
+ if (value == "?") return cont(maybetype);
+ }
+ }
+ function mayberettype(type) {
+ if (isTS && type == ":") {
+ if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr)
+ else return cont(typeexpr)
+ }
+ }
+ function isKW(_, value) {
+ if (value == "is") {
+ cx.marked = "keyword"
+ return cont()
+ }
+ }
+ function typeexpr(type, value) {
+ if (value == "keyof" || value == "typeof") {
+ cx.marked = "keyword"
+ return cont(value == "keyof" ? typeexpr : expression)
+ }
+ if (type == "variable" || value == "void") {
+ cx.marked = "type"
+ return cont(afterType)
+ }
+ if (type == "string" || type == "number" || type == "atom") return cont(afterType);
+ if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
+ if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType)
+ if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType)
+ }
+ function maybeReturnType(type) {
+ if (type == "=>") return cont(typeexpr)
+ }
+ function typeprop(type, value) {
+ if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property"
+ return cont(typeprop)
+ } else if (value == "?") {
+ return cont(typeprop)
+ } else if (type == ":") {
+ return cont(typeexpr)
+ } else if (type == "[") {
+ return cont(expression, maybetype, expect("]"), typeprop)
+ }
+ }
+ function typearg(type) {
+ if (type == "variable") return cont(typearg)
+ else if (type == ":") return cont(typeexpr)
+ }
+ function afterType(type, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
+ if (value == "|" || type == "." || value == "&") return cont(typeexpr)
+ if (type == "[") return cont(expect("]"), afterType)
+ if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
+ }
+ function maybeTypeArgs(_, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
+ }
+ function typeparam() {
+ return pass(typeexpr, maybeTypeDefault)
+ }
+ function maybeTypeDefault(_, value) {
+ if (value == "=") return cont(typeexpr)
+ }
+ function vardef(_, value) {
+ if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)}
+ return pass(pattern, maybetype, maybeAssign, vardefCont);
+ }
+ function pattern(type, value) {
+ if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) }
+ if (type == "variable") { register(value); return cont(); }
+ if (type == "spread") return cont(pattern);
+ if (type == "[") return contCommasep(pattern, "]");
+ if (type == "{") return contCommasep(proppattern, "}");
+ }
+ function proppattern(type, value) {
+ if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
+ register(value);
+ return cont(maybeAssign);
+ }
+ if (type == "variable") cx.marked = "property";
+ if (type == "spread") return cont(pattern);
+ if (type == "}") return pass();
+ return cont(expect(":"), pattern, maybeAssign);
+ }
+ function maybeAssign(_type, value) {
+ if (value == "=") return cont(expressionNoComma);
+ }
+ function vardefCont(type) {
+ if (type == ",") return cont(vardef);
+ }
+ function maybeelse(type, value) {
+ if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
+ }
+ function forspec(type, value) {
+ if (value == "await") return cont(forspec);
+ if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
+ }
+ function forspec1(type) {
+ if (type == "var") return cont(vardef, expect(";"), forspec2);
+ if (type == ";") return cont(forspec2);
+ if (type == "variable") return cont(formaybeinof);
+ return pass(expression, expect(";"), forspec2);
+ }
+ function formaybeinof(_type, value) {
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
+ return cont(maybeoperatorComma, forspec2);
+ }
+ function forspec2(type, value) {
+ if (type == ";") return cont(forspec3);
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
+ return pass(expression, expect(";"), forspec3);
+ }
+ function forspec3(type) {
+ if (type != ")") cont(expression);
+ }
+ function functiondef(type, value) {
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
+ if (type == "variable") {register(value); return cont(functiondef);}
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
+ if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef)
+ }
+ function funarg(type, value) {
+ if (value == "@") cont(expression, funarg)
+ if (type == "spread") return cont(funarg);
+ if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); }
+ return pass(pattern, maybetype, maybeAssign);
+ }
+ function classExpression(type, value) {
+ // Class expressions may have an optional name.
+ if (type == "variable") return className(type, value);
+ return classNameAfter(type, value);
+ }
+ function className(type, value) {
+ if (type == "variable") {register(value); return cont(classNameAfter);}
+ }
+ function classNameAfter(type, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter)
+ if (value == "extends" || value == "implements" || (isTS && type == ",")) {
+ if (value == "implements") cx.marked = "keyword";
+ return cont(isTS ? typeexpr : expression, classNameAfter);
+ }
+ if (type == "{") return cont(pushlex("}"), classBody, poplex);
+ }
+ function classBody(type, value) {
+ if (type == "async" ||
+ (type == "variable" &&
+ (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) &&
+ cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) {
+ cx.marked = "keyword";
+ return cont(classBody);
+ }
+ if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property";
+ return cont(isTS ? classfield : functiondef, classBody);
+ }
+ if (type == "[")
+ return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody)
+ if (value == "*") {
+ cx.marked = "keyword";
+ return cont(classBody);
+ }
+ if (type == ";") return cont(classBody);
+ if (type == "}") return cont();
+ if (value == "@") return cont(expression, classBody)
+ }
+ function classfield(type, value) {
+ if (value == "?") return cont(classfield)
+ if (type == ":") return cont(typeexpr, maybeAssign)
+ if (value == "=") return cont(expressionNoComma)
+ return pass(functiondef)
+ }
+ function afterExport(type, value) {
+ if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
+ if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
+ if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
+ return pass(statement);
+ }
+ function exportField(type, value) {
+ if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
+ if (type == "variable") return pass(expressionNoComma, exportField);
+ }
+ function afterImport(type) {
+ if (type == "string") return cont();
+ if (type == "(") return pass(expression);
+ return pass(importSpec, maybeMoreImports, maybeFrom);
+ }
+ function importSpec(type, value) {
+ if (type == "{") return contCommasep(importSpec, "}");
+ if (type == "variable") register(value);
+ if (value == "*") cx.marked = "keyword";
+ return cont(maybeAs);
+ }
+ function maybeMoreImports(type) {
+ if (type == ",") return cont(importSpec, maybeMoreImports)
+ }
+ function maybeAs(_type, value) {
+ if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
+ }
+ function maybeFrom(_type, value) {
+ if (value == "from") { cx.marked = "keyword"; return cont(expression); }
+ }
+ function arrayLiteral(type) {
+ if (type == "]") return cont();
+ return pass(commasep(expressionNoComma, "]"));
+ }
+ function enumdef() {
+ return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex)
+ }
+ function enummember() {
+ return pass(pattern, maybeAssign);
+ }
+
+ function isContinuedStatement(state, textAfter) {
+ return state.lastType == "operator" || state.lastType == "," ||
+ isOperatorChar.test(textAfter.charAt(0)) ||
+ /[,.]/.test(textAfter.charAt(0));
+ }
+
+ function expressionAllowed(stream, state, backUp) {
+ return state.tokenize == tokenBase &&
+ /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
+ (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
+ }
+
+ // Interface
+
+ return {
+ startState: function(basecolumn) {
+ var state = {
+ tokenize: tokenBase,
+ lastType: "sof",
+ cc: [],
+ lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
+ localVars: parserConfig.localVars,
+ context: parserConfig.localVars && {vars: parserConfig.localVars},
+ indented: basecolumn || 0
+ };
+ if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
+ state.globalVars = parserConfig.globalVars;
+ return state;
+ },
+
+ token: function(stream, state) {
+ if (stream.sol()) {
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = false;
+ state.indented = stream.indentation();
+ findFatArrow(stream, state);
+ }
+ if (state.tokenize != tokenComment && stream.eatSpace()) return null;
+ var style = state.tokenize(stream, state);
+ if (type == "comment") return style;
+ state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
+ return parseJS(state, style, type, content, stream);
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize == tokenComment) return CodeMirror.Pass;
+ if (state.tokenize != tokenBase) return 0;
+ var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
+ // Kludge to prevent 'maybelse' from blocking lexical scope pops
+ if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
+ var c = state.cc[i];
+ if (c == poplex) lexical = lexical.prev;
+ else if (c != maybeelse) break;
+ }
+ while ((lexical.type == "stat" || lexical.type == "form") &&
+ (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
+ (top == maybeoperatorComma || top == maybeoperatorNoComma) &&
+ !/^[,\.=+\-*:?[\(]/.test(textAfter))))
+ lexical = lexical.prev;
+ if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
+ lexical = lexical.prev;
+ var type = lexical.type, closing = firstChar == type;
+
+ if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
+ else if (type == "form" && firstChar == "{") return lexical.indented;
+ else if (type == "form") return lexical.indented + indentUnit;
+ else if (type == "stat")
+ return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
+ else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
+ return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
+ else if (lexical.align) return lexical.column + (closing ? 0 : 1);
+ else return lexical.indented + (closing ? 0 : indentUnit);
+ },
+
+ electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
+ blockCommentStart: jsonMode ? null : "/*",
+ blockCommentEnd: jsonMode ? null : "*/",
+ blockCommentContinue: jsonMode ? null : " * ",
+ lineComment: jsonMode ? null : "//",
+ fold: "brace",
+ closeBrackets: "()[]{}''\"\"``",
+
+ helperType: jsonMode ? "json" : "javascript",
+ jsonldMode: jsonldMode,
+ jsonMode: jsonMode,
+
+ expressionAllowed: expressionAllowed,
+
+ skipExpression: function(state) {
+ var top = state.cc[state.cc.length - 1]
+ if (top == expression || top == expressionNoComma) state.cc.pop()
+ }
+ };
+});
+
+CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
+
+CodeMirror.defineMIME("text/javascript", "javascript");
+CodeMirror.defineMIME("text/ecmascript", "javascript");
+CodeMirror.defineMIME("application/javascript", "javascript");
+CodeMirror.defineMIME("application/x-javascript", "javascript");
+CodeMirror.defineMIME("application/ecmascript", "javascript");
+CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
+CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
+CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
+CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
+CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
+
+});
+
+},{"../../lib/codemirror":21}],23:[function(require,module,exports){
+/**
+ * Slice reference.
+ */
+
+var slice = [].slice;
+
+/**
+ * Bind `obj` to `fn`.
+ *
+ * @param {Object} obj
+ * @param {Function|String} fn or string
+ * @return {Function}
+ * @api public
+ */
+
+module.exports = function(obj, fn){
+ if ('string' == typeof fn) fn = obj[fn];
+ if ('function' != typeof fn) throw new Error('bind() requires a function');
+ var args = slice.call(arguments, 2);
+ return function(){
+ return fn.apply(obj, args.concat(slice.call(arguments)));
+ }
+};
+
+},{}],24:[function(require,module,exports){
+
+/**
+ * Expose `Emitter`.
+ */
+
+if (typeof module !== 'undefined') {
+ module.exports = Emitter;
+}
+
+/**
+ * Initialize a new `Emitter`.
+ *
+ * @api public
+ */
+
+function Emitter(obj) {
+ if (obj) return mixin(obj);
+};
+
+/**
+ * Mixin the emitter properties.
+ *
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
+
+function mixin(obj) {
+ for (var key in Emitter.prototype) {
+ obj[key] = Emitter.prototype[key];
+ }
+ return obj;
+}
+
+/**
+ * Listen on the given `event` with `fn`.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.on =
+Emitter.prototype.addEventListener = function(event, fn){
+ this._callbacks = this._callbacks || {};
+ (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
+ .push(fn);
+ return this;
+};
+
+/**
+ * Adds an `event` listener that will be invoked a single
+ * time then automatically removed.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.once = function(event, fn){
+ function on() {
+ this.off(event, on);
+ fn.apply(this, arguments);
+ }
+
+ on.fn = fn;
+ this.on(event, on);
+ return this;
+};
+
+/**
+ * Remove the given callback for `event` or all
+ * registered callbacks.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.off =
+Emitter.prototype.removeListener =
+Emitter.prototype.removeAllListeners =
+Emitter.prototype.removeEventListener = function(event, fn){
+ this._callbacks = this._callbacks || {};
+
+ // all
+ if (0 == arguments.length) {
+ this._callbacks = {};
+ return this;
+ }
+
+ // specific event
+ var callbacks = this._callbacks['$' + event];
+ if (!callbacks) return this;
+
+ // remove all handlers
+ if (1 == arguments.length) {
+ delete this._callbacks['$' + event];
+ return this;
+ }
+
+ // remove specific handler
+ var cb;
+ for (var i = 0; i < callbacks.length; i++) {
+ cb = callbacks[i];
+ if (cb === fn || cb.fn === fn) {
+ callbacks.splice(i, 1);
+ break;
+ }
+ }
+ return this;
+};
+
+/**
+ * Emit `event` with the given args.
+ *
+ * @param {String} event
+ * @param {Mixed} ...
+ * @return {Emitter}
+ */
+
+Emitter.prototype.emit = function(event){
+ this._callbacks = this._callbacks || {};
+ var args = [].slice.call(arguments, 1)
+ , callbacks = this._callbacks['$' + event];
+
+ if (callbacks) {
+ callbacks = callbacks.slice(0);
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
+ callbacks[i].apply(this, args);
+ }
+ }
+
+ return this;
+};
+
+/**
+ * Return array of callbacks for `event`.
+ *
+ * @param {String} event
+ * @return {Array}
+ * @api public
+ */
+
+Emitter.prototype.listeners = function(event){
+ this._callbacks = this._callbacks || {};
+ return this._callbacks['$' + event] || [];
+};
+
+/**
+ * Check if this emitter has `event` handlers.
+ *
+ * @param {String} event
+ * @return {Boolean}
+ * @api public
+ */
+
+Emitter.prototype.hasListeners = function(event){
+ return !! this.listeners(event).length;
+};
+
+},{}],25:[function(require,module,exports){
+
+module.exports = function(a, b){
+ var fn = function(){};
+ fn.prototype = b.prototype;
+ a.prototype = new fn;
+ a.prototype.constructor = a;
+};
+},{}],26:[function(require,module,exports){
+(function (Buffer){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+// NOTE: These type checking functions intentionally don't use `instanceof`
+// because it is fragile and can be easily faked with `Object.create()`.
+
+function isArray(arg) {
+ if (Array.isArray) {
+ return Array.isArray(arg);
+ }
+ return objectToString(arg) === '[object Array]';
+}
+exports.isArray = isArray;
+
+function isBoolean(arg) {
+ return typeof arg === 'boolean';
+}
+exports.isBoolean = isBoolean;
+
+function isNull(arg) {
+ return arg === null;
+}
+exports.isNull = isNull;
+
+function isNullOrUndefined(arg) {
+ return arg == null;
+}
+exports.isNullOrUndefined = isNullOrUndefined;
+
+function isNumber(arg) {
+ return typeof arg === 'number';
+}
+exports.isNumber = isNumber;
+
+function isString(arg) {
+ return typeof arg === 'string';
+}
+exports.isString = isString;
+
+function isSymbol(arg) {
+ return typeof arg === 'symbol';
+}
+exports.isSymbol = isSymbol;
+
+function isUndefined(arg) {
+ return arg === void 0;
+}
+exports.isUndefined = isUndefined;
+
+function isRegExp(re) {
+ return objectToString(re) === '[object RegExp]';
+}
+exports.isRegExp = isRegExp;
+
+function isObject(arg) {
+ return typeof arg === 'object' && arg !== null;
+}
+exports.isObject = isObject;
+
+function isDate(d) {
+ return objectToString(d) === '[object Date]';
+}
+exports.isDate = isDate;
+
+function isError(e) {
+ return (objectToString(e) === '[object Error]' || e instanceof Error);
+}
+exports.isError = isError;
+
+function isFunction(arg) {
+ return typeof arg === 'function';
+}
+exports.isFunction = isFunction;
+
+function isPrimitive(arg) {
+ return arg === null ||
+ typeof arg === 'boolean' ||
+ typeof arg === 'number' ||
+ typeof arg === 'string' ||
+ typeof arg === 'symbol' || // ES6 symbol
+ typeof arg === 'undefined';
+}
+exports.isPrimitive = isPrimitive;
+
+exports.isBuffer = Buffer.isBuffer;
+
+function objectToString(o) {
+ return Object.prototype.toString.call(o);
+}
+
+}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
+},{"../../is-buffer/index.js":79}],27:[function(require,module,exports){
+/**
+ * Helpers.
+ */
+
+var s = 1000;
+var m = s * 60;
+var h = m * 60;
+var d = h * 24;
+var y = d * 365.25;
+
+/**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ * - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} [options]
+ * @throws {Error} throw an error if val is not a non-empty string or a number
+ * @return {String|Number}
+ * @api public
+ */
+
+module.exports = function(val, options) {
+ options = options || {};
+ var type = typeof val;
+ if (type === 'string' && val.length > 0) {
+ return parse(val);
+ } else if (type === 'number' && isNaN(val) === false) {
+ return options.long ? fmtLong(val) : fmtShort(val);
+ }
+ throw new Error(
+ 'val is not a non-empty string or a valid number. val=' +
+ JSON.stringify(val)
+ );
+};
+
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+function parse(str) {
+ str = String(str);
+ if (str.length > 100) {
+ return;
+ }
+ var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
+ str
+ );
+ if (!match) {
+ return;
+ }
+ var n = parseFloat(match[1]);
+ var type = (match[2] || 'ms').toLowerCase();
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'yrs':
+ case 'yr':
+ case 'y':
+ return n * y;
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * d;
+ case 'hours':
+ case 'hour':
+ case 'hrs':
+ case 'hr':
+ case 'h':
+ return n * h;
+ case 'minutes':
+ case 'minute':
+ case 'mins':
+ case 'min':
+ case 'm':
+ return n * m;
+ case 'seconds':
+ case 'second':
+ case 'secs':
+ case 'sec':
+ case 's':
+ return n * s;
+ case 'milliseconds':
+ case 'millisecond':
+ case 'msecs':
+ case 'msec':
+ case 'ms':
+ return n;
+ default:
+ return undefined;
+ }
+}
+
+/**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function fmtShort(ms) {
+ if (ms >= d) {
+ return Math.round(ms / d) + 'd';
+ }
+ if (ms >= h) {
+ return Math.round(ms / h) + 'h';
+ }
+ if (ms >= m) {
+ return Math.round(ms / m) + 'm';
+ }
+ if (ms >= s) {
+ return Math.round(ms / s) + 's';
+ }
+ return ms + 'ms';
+}
+
+/**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function fmtLong(ms) {
+ return plural(ms, d, 'day') ||
+ plural(ms, h, 'hour') ||
+ plural(ms, m, 'minute') ||
+ plural(ms, s, 'second') ||
+ ms + ' ms';
+}
+
+/**
+ * Pluralization helper.
+ */
+
+function plural(ms, n, name) {
+ if (ms < n) {
+ return;
+ }
+ if (ms < n * 1.5) {
+ return Math.floor(ms / n) + ' ' + name;
+ }
+ return Math.ceil(ms / n) + ' ' + name + 's';
+}
+
+},{}],28:[function(require,module,exports){
+(function (process){
+/**
+ * This is the web browser implementation of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
+
+exports = module.exports = require('./debug');
+exports.log = log;
+exports.formatArgs = formatArgs;
+exports.save = save;
+exports.load = load;
+exports.useColors = useColors;
+exports.storage = 'undefined' != typeof chrome
+ && 'undefined' != typeof chrome.storage
+ ? chrome.storage.local
+ : localstorage();
+
+/**
+ * Colors.
+ */
+
+exports.colors = [
+ 'lightseagreen',
+ 'forestgreen',
+ 'goldenrod',
+ 'dodgerblue',
+ 'darkorchid',
+ 'crimson'
+];
+
+/**
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
+ * and the Firebug extension (any Firefox version) are known
+ * to support "%c" CSS customizations.
+ *
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
+ */
+
+function useColors() {
+ // NB: In an Electron preload script, document will be defined but not fully
+ // initialized. Since we know we're in Chrome, we'll just detect this case
+ // explicitly
+ if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
+ return true;
+ }
+
+ // is webkit? http://stackoverflow.com/a/16459606/376773
+ // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
+ return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
+ // is firebug? http://stackoverflow.com/a/398120/376773
+ (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
+ // is firefox >= v31?
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
+ // double check webkit in userAgent just in case we are in a worker
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
+}
+
+/**
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
+ */
+
+exports.formatters.j = function(v) {
+ try {
+ return JSON.stringify(v);
+ } catch (err) {
+ return '[UnexpectedJSONParseError]: ' + err.message;
+ }
+};
+
+
+/**
+ * Colorize log arguments if enabled.
+ *
+ * @api public
+ */
+
+function formatArgs(args) {
+ var useColors = this.useColors;
+
+ args[0] = (useColors ? '%c' : '')
+ + this.namespace
+ + (useColors ? ' %c' : ' ')
+ + args[0]
+ + (useColors ? '%c ' : ' ')
+ + '+' + exports.humanize(this.diff);
+
+ if (!useColors) return;
+
+ var c = 'color: ' + this.color;
+ args.splice(1, 0, c, 'color: inherit')
+
+ // the final "%c" is somewhat tricky, because there could be other
+ // arguments passed either before or after the %c, so we need to
+ // figure out the correct index to insert the CSS into
+ var index = 0;
+ var lastC = 0;
+ args[0].replace(/%[a-zA-Z%]/g, function(match) {
+ if ('%%' === match) return;
+ index++;
+ if ('%c' === match) {
+ // we only are interested in the *last* %c
+ // (the user may have provided their own)
+ lastC = index;
+ }
+ });
+
+ args.splice(lastC, 0, c);
+}
+
+/**
+ * Invokes `console.log()` when available.
+ * No-op when `console.log` is not a "function".
+ *
+ * @api public
+ */
+
+function log() {
+ // this hackery is required for IE8/9, where
+ // the `console.log` function doesn't have 'apply'
+ return 'object' === typeof console
+ && console.log
+ && Function.prototype.apply.call(console.log, console, arguments);
+}
+
+/**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+
+function save(namespaces) {
+ try {
+ if (null == namespaces) {
+ exports.storage.removeItem('debug');
+ } else {
+ exports.storage.debug = namespaces;
+ }
+ } catch(e) {}
+}
+
+/**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+
+function load() {
+ var r;
+ try {
+ r = exports.storage.debug;
+ } catch(e) {}
+
+ // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
+ if (!r && typeof process !== 'undefined' && 'env' in process) {
+ r = process.env.DEBUG;
+ }
+
+ return r;
+}
+
+/**
+ * Enable namespaces listed in `localStorage.debug` initially.
+ */
+
+exports.enable(load());
+
+/**
+ * Localstorage attempts to return the localstorage.
+ *
+ * This is necessary because safari throws
+ * when a user disables cookies/localstorage
+ * and you attempt to access it.
+ *
+ * @return {LocalStorage}
+ * @api private
+ */
+
+function localstorage() {
+ try {
+ return window.localStorage;
+ } catch (e) {}
+}
+
+}).call(this,require('_process'))
+},{"./debug":29,"_process":90}],29:[function(require,module,exports){
+
+/**
+ * This is the common logic for both the Node.js and web browser
+ * implementations of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
+
+exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
+exports.coerce = coerce;
+exports.disable = disable;
+exports.enable = enable;
+exports.enabled = enabled;
+exports.humanize = require('ms');
+
+/**
+ * The currently active debug mode names, and names to skip.
+ */
+
+exports.names = [];
+exports.skips = [];
+
+/**
+ * Map of special "%n" handling functions, for the debug "format" argument.
+ *
+ * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
+ */
+
+exports.formatters = {};
+
+/**
+ * Previous log timestamp.
+ */
+
+var prevTime;
+
+/**
+ * Select a color.
+ * @param {String} namespace
+ * @return {Number}
+ * @api private
+ */
+
+function selectColor(namespace) {
+ var hash = 0, i;
+
+ for (i in namespace) {
+ hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
+ hash |= 0; // Convert to 32bit integer
+ }
+
+ return exports.colors[Math.abs(hash) % exports.colors.length];
+}
+
+/**
+ * Create a debugger with the given `namespace`.
+ *
+ * @param {String} namespace
+ * @return {Function}
+ * @api public
+ */
+
+function createDebug(namespace) {
+
+ function debug() {
+ // disabled?
+ if (!debug.enabled) return;
+
+ var self = debug;
+
+ // set `diff` timestamp
+ var curr = +new Date();
+ var ms = curr - (prevTime || curr);
+ self.diff = ms;
+ self.prev = prevTime;
+ self.curr = curr;
+ prevTime = curr;
+
+ // turn the `arguments` into a proper Array
+ var args = new Array(arguments.length);
+ for (var i = 0; i < args.length; i++) {
+ args[i] = arguments[i];
+ }
+
+ args[0] = exports.coerce(args[0]);
+
+ if ('string' !== typeof args[0]) {
+ // anything else let's inspect with %O
+ args.unshift('%O');
+ }
+
+ // apply any `formatters` transformations
+ var index = 0;
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
+ // if we encounter an escaped % then don't increase the array index
+ if (match === '%%') return match;
+ index++;
+ var formatter = exports.formatters[format];
+ if ('function' === typeof formatter) {
+ var val = args[index];
+ match = formatter.call(self, val);
+
+ // now we need to remove `args[index]` since it's inlined in the `format`
+ args.splice(index, 1);
+ index--;
+ }
+ return match;
+ });
+
+ // apply env-specific formatting (colors, etc.)
+ exports.formatArgs.call(self, args);
+
+ var logFn = debug.log || exports.log || console.log.bind(console);
+ logFn.apply(self, args);
+ }
+
+ debug.namespace = namespace;
+ debug.enabled = exports.enabled(namespace);
+ debug.useColors = exports.useColors();
+ debug.color = selectColor(namespace);
+
+ // env-specific initialization logic for debug instances
+ if ('function' === typeof exports.init) {
+ exports.init(debug);
+ }
+
+ return debug;
+}
+
+/**
+ * Enables a debug mode by namespaces. This can include modes
+ * separated by a colon and wildcards.
+ *
+ * @param {String} namespaces
+ * @api public
+ */
+
+function enable(namespaces) {
+ exports.save(namespaces);
+
+ exports.names = [];
+ exports.skips = [];
+
+ var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
+ var len = split.length;
+
+ for (var i = 0; i < len; i++) {
+ if (!split[i]) continue; // ignore empty strings
+ namespaces = split[i].replace(/\*/g, '.*?');
+ if (namespaces[0] === '-') {
+ exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
+ } else {
+ exports.names.push(new RegExp('^' + namespaces + '$'));
+ }
+ }
+}
+
+/**
+ * Disable debug output.
+ *
+ * @api public
+ */
+
+function disable() {
+ exports.enable('');
+}
+
+/**
+ * Returns true if the given mode name is enabled, false otherwise.
+ *
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
+ */
+
+function enabled(name) {
+ var i, len;
+ for (i = 0, len = exports.skips.length; i < len; i++) {
+ if (exports.skips[i].test(name)) {
+ return false;
+ }
+ }
+ for (i = 0, len = exports.names.length; i < len; i++) {
+ if (exports.names[i].test(name)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Coerce `val`.
+ *
+ * @param {Mixed} val
+ * @return {Mixed}
+ * @api private
+ */
+
+function coerce(val) {
+ if (val instanceof Error) return val.stack || val.message;
+ return val;
+}
+
+},{"ms":27}],30:[function(require,module,exports){
+
+module.exports = require('./socket');
+
+/**
+ * Exports parser
+ *
+ * @api public
+ *
+ */
+module.exports.parser = require('engine.io-parser');
+
+},{"./socket":31,"engine.io-parser":42}],31:[function(require,module,exports){
+(function (global){
+/**
+ * Module dependencies.
+ */
+
+var transports = require('./transports/index');
+var Emitter = require('component-emitter');
+var debug = require('debug')('engine.io-client:socket');
+var index = require('indexof');
+var parser = require('engine.io-parser');
+var parseuri = require('parseuri');
+var parseqs = require('parseqs');
+
+/**
+ * Module exports.
+ */
+
+module.exports = Socket;
+
+/**
+ * Socket constructor.
+ *
+ * @param {String|Object} uri or options
+ * @param {Object} options
+ * @api public
+ */
+
+function Socket (uri, opts) {
+ if (!(this instanceof Socket)) return new Socket(uri, opts);
+
+ opts = opts || {};
+
+ if (uri && 'object' === typeof uri) {
+ opts = uri;
+ uri = null;
+ }
+
+ if (uri) {
+ uri = parseuri(uri);
+ opts.hostname = uri.host;
+ opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
+ opts.port = uri.port;
+ if (uri.query) opts.query = uri.query;
+ } else if (opts.host) {
+ opts.hostname = parseuri(opts.host).host;
+ }
+
+ this.secure = null != opts.secure ? opts.secure
+ : (global.location && 'https:' === location.protocol);
+
+ if (opts.hostname && !opts.port) {
+ // if no port is specified manually, use the protocol default
+ opts.port = this.secure ? '443' : '80';
+ }
+
+ this.agent = opts.agent || false;
+ this.hostname = opts.hostname ||
+ (global.location ? location.hostname : 'localhost');
+ this.port = opts.port || (global.location && location.port
+ ? location.port
+ : (this.secure ? 443 : 80));
+ this.query = opts.query || {};
+ if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
+ this.upgrade = false !== opts.upgrade;
+ this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
+ this.forceJSONP = !!opts.forceJSONP;
+ this.jsonp = false !== opts.jsonp;
+ this.forceBase64 = !!opts.forceBase64;
+ this.enablesXDR = !!opts.enablesXDR;
+ this.timestampParam = opts.timestampParam || 't';
+ this.timestampRequests = opts.timestampRequests;
+ this.transports = opts.transports || ['polling', 'websocket'];
+ this.transportOptions = opts.transportOptions || {};
+ this.readyState = '';
+ this.writeBuffer = [];
+ this.prevBufferLen = 0;
+ this.policyPort = opts.policyPort || 843;
+ this.rememberUpgrade = opts.rememberUpgrade || false;
+ this.binaryType = null;
+ this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
+ this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
+
+ if (true === this.perMessageDeflate) this.perMessageDeflate = {};
+ if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
+ this.perMessageDeflate.threshold = 1024;
+ }
+
+ // SSL options for Node.js client
+ this.pfx = opts.pfx || null;
+ this.key = opts.key || null;
+ this.passphrase = opts.passphrase || null;
+ this.cert = opts.cert || null;
+ this.ca = opts.ca || null;
+ this.ciphers = opts.ciphers || null;
+ this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized;
+ this.forceNode = !!opts.forceNode;
+
+ // other options for Node.js client
+ var freeGlobal = typeof global === 'object' && global;
+ if (freeGlobal.global === freeGlobal) {
+ if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
+ this.extraHeaders = opts.extraHeaders;
+ }
+
+ if (opts.localAddress) {
+ this.localAddress = opts.localAddress;
+ }
+ }
+
+ // set on handshake
+ this.id = null;
+ this.upgrades = null;
+ this.pingInterval = null;
+ this.pingTimeout = null;
+
+ // set on heartbeat
+ this.pingIntervalTimer = null;
+ this.pingTimeoutTimer = null;
+
+ this.open();
+}
+
+Socket.priorWebsocketSuccess = false;
+
+/**
+ * Mix in `Emitter`.
+ */
+
+Emitter(Socket.prototype);
+
+/**
+ * Protocol version.
+ *
+ * @api public
+ */
+
+Socket.protocol = parser.protocol; // this is an int
+
+/**
+ * Expose deps for legacy compatibility
+ * and standalone browser access.
+ */
+
+Socket.Socket = Socket;
+Socket.Transport = require('./transport');
+Socket.transports = require('./transports/index');
+Socket.parser = require('engine.io-parser');
+
+/**
+ * Creates transport of the given type.
+ *
+ * @param {String} transport name
+ * @return {Transport}
+ * @api private
+ */
+
+Socket.prototype.createTransport = function (name) {
+ debug('creating transport "%s"', name);
+ var query = clone(this.query);
+
+ // append engine.io protocol identifier
+ query.EIO = parser.protocol;
+
+ // transport name
+ query.transport = name;
+
+ // per-transport options
+ var options = this.transportOptions[name] || {};
+
+ // session id if we already have one
+ if (this.id) query.sid = this.id;
+
+ var transport = new transports[name]({
+ query: query,
+ socket: this,
+ agent: options.agent || this.agent,
+ hostname: options.hostname || this.hostname,
+ port: options.port || this.port,
+ secure: options.secure || this.secure,
+ path: options.path || this.path,
+ forceJSONP: options.forceJSONP || this.forceJSONP,
+ jsonp: options.jsonp || this.jsonp,
+ forceBase64: options.forceBase64 || this.forceBase64,
+ enablesXDR: options.enablesXDR || this.enablesXDR,
+ timestampRequests: options.timestampRequests || this.timestampRequests,
+ timestampParam: options.timestampParam || this.timestampParam,
+ policyPort: options.policyPort || this.policyPort,
+ pfx: options.pfx || this.pfx,
+ key: options.key || this.key,
+ passphrase: options.passphrase || this.passphrase,
+ cert: options.cert || this.cert,
+ ca: options.ca || this.ca,
+ ciphers: options.ciphers || this.ciphers,
+ rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized,
+ perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate,
+ extraHeaders: options.extraHeaders || this.extraHeaders,
+ forceNode: options.forceNode || this.forceNode,
+ localAddress: options.localAddress || this.localAddress,
+ requestTimeout: options.requestTimeout || this.requestTimeout,
+ protocols: options.protocols || void (0)
+ });
+
+ return transport;
+};
+
+function clone (obj) {
+ var o = {};
+ for (var i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ o[i] = obj[i];
+ }
+ }
+ return o;
+}
+
+/**
+ * Initializes transport to use and starts probe.
+ *
+ * @api private
+ */
+Socket.prototype.open = function () {
+ var transport;
+ if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
+ transport = 'websocket';
+ } else if (0 === this.transports.length) {
+ // Emit error on next tick so it can be listened to
+ var self = this;
+ setTimeout(function () {
+ self.emit('error', 'No transports available');
+ }, 0);
+ return;
+ } else {
+ transport = this.transports[0];
+ }
+ this.readyState = 'opening';
+
+ // Retry with the next transport if the transport is disabled (jsonp: false)
+ try {
+ transport = this.createTransport(transport);
+ } catch (e) {
+ this.transports.shift();
+ this.open();
+ return;
+ }
+
+ transport.open();
+ this.setTransport(transport);
+};
+
+/**
+ * Sets the current transport. Disables the existing one (if any).
+ *
+ * @api private
+ */
+
+Socket.prototype.setTransport = function (transport) {
+ debug('setting transport %s', transport.name);
+ var self = this;
+
+ if (this.transport) {
+ debug('clearing existing transport %s', this.transport.name);
+ this.transport.removeAllListeners();
+ }
+
+ // set up transport
+ this.transport = transport;
+
+ // set up transport listeners
+ transport
+ .on('drain', function () {
+ self.onDrain();
+ })
+ .on('packet', function (packet) {
+ self.onPacket(packet);
+ })
+ .on('error', function (e) {
+ self.onError(e);
+ })
+ .on('close', function () {
+ self.onClose('transport close');
+ });
+};
+
+/**
+ * Probes a transport.
+ *
+ * @param {String} transport name
+ * @api private
+ */
+
+Socket.prototype.probe = function (name) {
+ debug('probing transport "%s"', name);
+ var transport = this.createTransport(name, { probe: 1 });
+ var failed = false;
+ var self = this;
+
+ Socket.priorWebsocketSuccess = false;
+
+ function onTransportOpen () {
+ if (self.onlyBinaryUpgrades) {
+ var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
+ failed = failed || upgradeLosesBinary;
+ }
+ if (failed) return;
+
+ debug('probe transport "%s" opened', name);
+ transport.send([{ type: 'ping', data: 'probe' }]);
+ transport.once('packet', function (msg) {
+ if (failed) return;
+ if ('pong' === msg.type && 'probe' === msg.data) {
+ debug('probe transport "%s" pong', name);
+ self.upgrading = true;
+ self.emit('upgrading', transport);
+ if (!transport) return;
+ Socket.priorWebsocketSuccess = 'websocket' === transport.name;
+
+ debug('pausing current transport "%s"', self.transport.name);
+ self.transport.pause(function () {
+ if (failed) return;
+ if ('closed' === self.readyState) return;
+ debug('changing transport and sending upgrade packet');
+
+ cleanup();
+
+ self.setTransport(transport);
+ transport.send([{ type: 'upgrade' }]);
+ self.emit('upgrade', transport);
+ transport = null;
+ self.upgrading = false;
+ self.flush();
+ });
+ } else {
+ debug('probe transport "%s" failed', name);
+ var err = new Error('probe error');
+ err.transport = transport.name;
+ self.emit('upgradeError', err);
+ }
+ });
+ }
+
+ function freezeTransport () {
+ if (failed) return;
+
+ // Any callback called by transport should be ignored since now
+ failed = true;
+
+ cleanup();
+
+ transport.close();
+ transport = null;
+ }
+
+ // Handle any error that happens while probing
+ function onerror (err) {
+ var error = new Error('probe error: ' + err);
+ error.transport = transport.name;
+
+ freezeTransport();
+
+ debug('probe transport "%s" failed because of error: %s', name, err);
+
+ self.emit('upgradeError', error);
+ }
+
+ function onTransportClose () {
+ onerror('transport closed');
+ }
+
+ // When the socket is closed while we're probing
+ function onclose () {
+ onerror('socket closed');
+ }
+
+ // When the socket is upgraded while we're probing
+ function onupgrade (to) {
+ if (transport && to.name !== transport.name) {
+ debug('"%s" works - aborting "%s"', to.name, transport.name);
+ freezeTransport();
+ }
+ }
+
+ // Remove all listeners on the transport and on self
+ function cleanup () {
+ transport.removeListener('open', onTransportOpen);
+ transport.removeListener('error', onerror);
+ transport.removeListener('close', onTransportClose);
+ self.removeListener('close', onclose);
+ self.removeListener('upgrading', onupgrade);
+ }
+
+ transport.once('open', onTransportOpen);
+ transport.once('error', onerror);
+ transport.once('close', onTransportClose);
+
+ this.once('close', onclose);
+ this.once('upgrading', onupgrade);
+
+ transport.open();
+};
+
+/**
+ * Called when connection is deemed open.
+ *
+ * @api public
+ */
+
+Socket.prototype.onOpen = function () {
+ debug('socket open');
+ this.readyState = 'open';
+ Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
+ this.emit('open');
+ this.flush();
+
+ // we check for `readyState` in case an `open`
+ // listener already closed the socket
+ if ('open' === this.readyState && this.upgrade && this.transport.pause) {
+ debug('starting upgrade probes');
+ for (var i = 0, l = this.upgrades.length; i < l; i++) {
+ this.probe(this.upgrades[i]);
+ }
+ }
+};
+
+/**
+ * Handles a packet.
+ *
+ * @api private
+ */
+
+Socket.prototype.onPacket = function (packet) {
+ if ('opening' === this.readyState || 'open' === this.readyState ||
+ 'closing' === this.readyState) {
+ debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
+
+ this.emit('packet', packet);
+
+ // Socket is live - any packet counts
+ this.emit('heartbeat');
+
+ switch (packet.type) {
+ case 'open':
+ this.onHandshake(JSON.parse(packet.data));
+ break;
+
+ case 'pong':
+ this.setPing();
+ this.emit('pong');
+ break;
+
+ case 'error':
+ var err = new Error('server error');
+ err.code = packet.data;
+ this.onError(err);
+ break;
+
+ case 'message':
+ this.emit('data', packet.data);
+ this.emit('message', packet.data);
+ break;
+ }
+ } else {
+ debug('packet received with socket readyState "%s"', this.readyState);
+ }
+};
+
+/**
+ * Called upon handshake completion.
+ *
+ * @param {Object} handshake obj
+ * @api private
+ */
+
+Socket.prototype.onHandshake = function (data) {
+ this.emit('handshake', data);
+ this.id = data.sid;
+ this.transport.query.sid = data.sid;
+ this.upgrades = this.filterUpgrades(data.upgrades);
+ this.pingInterval = data.pingInterval;
+ this.pingTimeout = data.pingTimeout;
+ this.onOpen();
+ // In case open handler closes socket
+ if ('closed' === this.readyState) return;
+ this.setPing();
+
+ // Prolong liveness of socket on heartbeat
+ this.removeListener('heartbeat', this.onHeartbeat);
+ this.on('heartbeat', this.onHeartbeat);
+};
+
+/**
+ * Resets ping timeout.
+ *
+ * @api private
+ */
+
+Socket.prototype.onHeartbeat = function (timeout) {
+ clearTimeout(this.pingTimeoutTimer);
+ var self = this;
+ self.pingTimeoutTimer = setTimeout(function () {
+ if ('closed' === self.readyState) return;
+ self.onClose('ping timeout');
+ }, timeout || (self.pingInterval + self.pingTimeout));
+};
+
+/**
+ * Pings server every `this.pingInterval` and expects response
+ * within `this.pingTimeout` or closes connection.
+ *
+ * @api private
+ */
+
+Socket.prototype.setPing = function () {
+ var self = this;
+ clearTimeout(self.pingIntervalTimer);
+ self.pingIntervalTimer = setTimeout(function () {
+ debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
+ self.ping();
+ self.onHeartbeat(self.pingTimeout);
+ }, self.pingInterval);
+};
+
+/**
+* Sends a ping packet.
+*
+* @api private
+*/
+
+Socket.prototype.ping = function () {
+ var self = this;
+ this.sendPacket('ping', function () {
+ self.emit('ping');
+ });
+};
+
+/**
+ * Called on `drain` event
+ *
+ * @api private
+ */
+
+Socket.prototype.onDrain = function () {
+ this.writeBuffer.splice(0, this.prevBufferLen);
+
+ // setting prevBufferLen = 0 is very important
+ // for example, when upgrading, upgrade packet is sent over,
+ // and a nonzero prevBufferLen could cause problems on `drain`
+ this.prevBufferLen = 0;
+
+ if (0 === this.writeBuffer.length) {
+ this.emit('drain');
+ } else {
+ this.flush();
+ }
+};
+
+/**
+ * Flush write buffers.
+ *
+ * @api private
+ */
+
+Socket.prototype.flush = function () {
+ if ('closed' !== this.readyState && this.transport.writable &&
+ !this.upgrading && this.writeBuffer.length) {
+ debug('flushing %d packets in socket', this.writeBuffer.length);
+ this.transport.send(this.writeBuffer);
+ // keep track of current length of writeBuffer
+ // splice writeBuffer and callbackBuffer on `drain`
+ this.prevBufferLen = this.writeBuffer.length;
+ this.emit('flush');
+ }
+};
+
+/**
+ * Sends a message.
+ *
+ * @param {String} message.
+ * @param {Function} callback function.
+ * @param {Object} options.
+ * @return {Socket} for chaining.
+ * @api public
+ */
+
+Socket.prototype.write =
+Socket.prototype.send = function (msg, options, fn) {
+ this.sendPacket('message', msg, options, fn);
+ return this;
+};
+
+/**
+ * Sends a packet.
+ *
+ * @param {String} packet type.
+ * @param {String} data.
+ * @param {Object} options.
+ * @param {Function} callback function.
+ * @api private
+ */
+
+Socket.prototype.sendPacket = function (type, data, options, fn) {
+ if ('function' === typeof data) {
+ fn = data;
+ data = undefined;
+ }
+
+ if ('function' === typeof options) {
+ fn = options;
+ options = null;
+ }
+
+ if ('closing' === this.readyState || 'closed' === this.readyState) {
+ return;
+ }
+
+ options = options || {};
+ options.compress = false !== options.compress;
+
+ var packet = {
+ type: type,
+ data: data,
+ options: options
+ };
+ this.emit('packetCreate', packet);
+ this.writeBuffer.push(packet);
+ if (fn) this.once('flush', fn);
+ this.flush();
+};
+
+/**
+ * Closes the connection.
+ *
+ * @api private
+ */
+
+Socket.prototype.close = function () {
+ if ('opening' === this.readyState || 'open' === this.readyState) {
+ this.readyState = 'closing';
+
+ var self = this;
+
+ if (this.writeBuffer.length) {
+ this.once('drain', function () {
+ if (this.upgrading) {
+ waitForUpgrade();
+ } else {
+ close();
+ }
+ });
+ } else if (this.upgrading) {
+ waitForUpgrade();
+ } else {
+ close();
+ }
+ }
+
+ function close () {
+ self.onClose('forced close');
+ debug('socket closing - telling transport to close');
+ self.transport.close();
+ }
+
+ function cleanupAndClose () {
+ self.removeListener('upgrade', cleanupAndClose);
+ self.removeListener('upgradeError', cleanupAndClose);
+ close();
+ }
+
+ function waitForUpgrade () {
+ // wait for upgrade to finish since we can't send packets while pausing a transport
+ self.once('upgrade', cleanupAndClose);
+ self.once('upgradeError', cleanupAndClose);
+ }
+
+ return this;
+};
+
+/**
+ * Called upon transport error
+ *
+ * @api private
+ */
+
+Socket.prototype.onError = function (err) {
+ debug('socket error %j', err);
+ Socket.priorWebsocketSuccess = false;
+ this.emit('error', err);
+ this.onClose('transport error', err);
+};
+
+/**
+ * Called upon transport close.
+ *
+ * @api private
+ */
+
+Socket.prototype.onClose = function (reason, desc) {
+ if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
+ debug('socket close with reason: "%s"', reason);
+ var self = this;
+
+ // clear timers
+ clearTimeout(this.pingIntervalTimer);
+ clearTimeout(this.pingTimeoutTimer);
+
+ // stop event from firing again for transport
+ this.transport.removeAllListeners('close');
+
+ // ensure transport won't stay open
+ this.transport.close();
+
+ // ignore further transport communication
+ this.transport.removeAllListeners();
+
+ // set ready state
+ this.readyState = 'closed';
+
+ // clear session id
+ this.id = null;
+
+ // emit close event
+ this.emit('close', reason, desc);
+
+ // clean buffers after, so users can still
+ // grab the buffers on `close` event
+ self.writeBuffer = [];
+ self.prevBufferLen = 0;
+ }
+};
+
+/**
+ * Filters upgrades, returning only those matching client transports.
+ *
+ * @param {Array} server upgrades
+ * @api private
+ *
+ */
+
+Socket.prototype.filterUpgrades = function (upgrades) {
+ var filteredUpgrades = [];
+ for (var i = 0, j = upgrades.length; i < j; i++) {
+ if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
+ }
+ return filteredUpgrades;
+};
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./transport":32,"./transports/index":33,"component-emitter":24,"debug":39,"engine.io-parser":42,"indexof":77,"parseqs":86,"parseuri":87}],32:[function(require,module,exports){
+/**
+ * Module dependencies.
+ */
+
+var parser = require('engine.io-parser');
+var Emitter = require('component-emitter');
+
+/**
+ * Module exports.
+ */
+
+module.exports = Transport;
+
+/**
+ * Transport abstract constructor.
+ *
+ * @param {Object} options.
+ * @api private
+ */
+
+function Transport (opts) {
+ this.path = opts.path;
+ this.hostname = opts.hostname;
+ this.port = opts.port;
+ this.secure = opts.secure;
+ this.query = opts.query;
+ this.timestampParam = opts.timestampParam;
+ this.timestampRequests = opts.timestampRequests;
+ this.readyState = '';
+ this.agent = opts.agent || false;
+ this.socket = opts.socket;
+ this.enablesXDR = opts.enablesXDR;
+
+ // SSL options for Node.js client
+ this.pfx = opts.pfx;
+ this.key = opts.key;
+ this.passphrase = opts.passphrase;
+ this.cert = opts.cert;
+ this.ca = opts.ca;
+ this.ciphers = opts.ciphers;
+ this.rejectUnauthorized = opts.rejectUnauthorized;
+ this.forceNode = opts.forceNode;
+
+ // other options for Node.js client
+ this.extraHeaders = opts.extraHeaders;
+ this.localAddress = opts.localAddress;
+}
+
+/**
+ * Mix in `Emitter`.
+ */
+
+Emitter(Transport.prototype);
+
+/**
+ * Emits an error.
+ *
+ * @param {String} str
+ * @return {Transport} for chaining
+ * @api public
+ */
+
+Transport.prototype.onError = function (msg, desc) {
+ var err = new Error(msg);
+ err.type = 'TransportError';
+ err.description = desc;
+ this.emit('error', err);
+ return this;
+};
+
+/**
+ * Opens the transport.
+ *
+ * @api public
+ */
+
+Transport.prototype.open = function () {
+ if ('closed' === this.readyState || '' === this.readyState) {
+ this.readyState = 'opening';
+ this.doOpen();
+ }
+
+ return this;
+};
+
+/**
+ * Closes the transport.
+ *
+ * @api private
+ */
+
+Transport.prototype.close = function () {
+ if ('opening' === this.readyState || 'open' === this.readyState) {
+ this.doClose();
+ this.onClose();
+ }
+
+ return this;
+};
+
+/**
+ * Sends multiple packets.
+ *
+ * @param {Array} packets
+ * @api private
+ */
+
+Transport.prototype.send = function (packets) {
+ if ('open' === this.readyState) {
+ this.write(packets);
+ } else {
+ throw new Error('Transport not open');
+ }
+};
+
+/**
+ * Called upon open
+ *
+ * @api private
+ */
+
+Transport.prototype.onOpen = function () {
+ this.readyState = 'open';
+ this.writable = true;
+ this.emit('open');
+};
+
+/**
+ * Called with data.
+ *
+ * @param {String} data
+ * @api private
+ */
+
+Transport.prototype.onData = function (data) {
+ var packet = parser.decodePacket(data, this.socket.binaryType);
+ this.onPacket(packet);
+};
+
+/**
+ * Called with a decoded packet.
+ */
+
+Transport.prototype.onPacket = function (packet) {
+ this.emit('packet', packet);
+};
+
+/**
+ * Called upon close.
+ *
+ * @api private
+ */
+
+Transport.prototype.onClose = function () {
+ this.readyState = 'closed';
+ this.emit('close');
+};
+
+},{"component-emitter":24,"engine.io-parser":42}],33:[function(require,module,exports){
+(function (global){
+/**
+ * Module dependencies
+ */
+
+var XMLHttpRequest = require('xmlhttprequest-ssl');
+var XHR = require('./polling-xhr');
+var JSONP = require('./polling-jsonp');
+var websocket = require('./websocket');
+
+/**
+ * Export transports.
+ */
+
+exports.polling = polling;
+exports.websocket = websocket;
+
+/**
+ * Polling transport polymorphic constructor.
+ * Decides on xhr vs jsonp based on feature detection.
+ *
+ * @api private
+ */
+
+function polling (opts) {
+ var xhr;
+ var xd = false;
+ var xs = false;
+ var jsonp = false !== opts.jsonp;
+
+ if (global.location) {
+ var isSSL = 'https:' === location.protocol;
+ var port = location.port;
+
+ // some user agents have empty `location.port`
+ if (!port) {
+ port = isSSL ? 443 : 80;
+ }
+
+ xd = opts.hostname !== location.hostname || port !== opts.port;
+ xs = opts.secure !== isSSL;
+ }
+
+ opts.xdomain = xd;
+ opts.xscheme = xs;
+ xhr = new XMLHttpRequest(opts);
+
+ if ('open' in xhr && !opts.forceJSONP) {
+ return new XHR(opts);
+ } else {
+ if (!jsonp) throw new Error('JSONP disabled');
+ return new JSONP(opts);
+ }
+}
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./polling-jsonp":34,"./polling-xhr":35,"./websocket":37,"xmlhttprequest-ssl":38}],34:[function(require,module,exports){
+(function (global){
+
+/**
+ * Module requirements.
+ */
+
+var Polling = require('./polling');
+var inherit = require('component-inherit');
+
+/**
+ * Module exports.
+ */
+
+module.exports = JSONPPolling;
+
+/**
+ * Cached regular expressions.
+ */
+
+var rNewline = /\n/g;
+var rEscapedNewline = /\\n/g;
+
+/**
+ * Global JSONP callbacks.
+ */
+
+var callbacks;
+
+/**
+ * Noop.
+ */
+
+function empty () { }
+
+/**
+ * JSONP Polling constructor.
+ *
+ * @param {Object} opts.
+ * @api public
+ */
+
+function JSONPPolling (opts) {
+ Polling.call(this, opts);
+
+ this.query = this.query || {};
+
+ // define global callbacks array if not present
+ // we do this here (lazily) to avoid unneeded global pollution
+ if (!callbacks) {
+ // we need to consider multiple engines in the same page
+ if (!global.___eio) global.___eio = [];
+ callbacks = global.___eio;
+ }
+
+ // callback identifier
+ this.index = callbacks.length;
+
+ // add callback to jsonp global
+ var self = this;
+ callbacks.push(function (msg) {
+ self.onData(msg);
+ });
+
+ // append to query string
+ this.query.j = this.index;
+
+ // prevent spurious errors from being emitted when the window is unloaded
+ if (global.document && global.addEventListener) {
+ global.addEventListener('beforeunload', function () {
+ if (self.script) self.script.onerror = empty;
+ }, false);
+ }
+}
+
+/**
+ * Inherits from Polling.
+ */
+
+inherit(JSONPPolling, Polling);
+
+/*
+ * JSONP only supports binary as base64 encoded strings
+ */
+
+JSONPPolling.prototype.supportsBinary = false;
+
+/**
+ * Closes the socket.
+ *
+ * @api private
+ */
+
+JSONPPolling.prototype.doClose = function () {
+ if (this.script) {
+ this.script.parentNode.removeChild(this.script);
+ this.script = null;
+ }
+
+ if (this.form) {
+ this.form.parentNode.removeChild(this.form);
+ this.form = null;
+ this.iframe = null;
+ }
+
+ Polling.prototype.doClose.call(this);
+};
+
+/**
+ * Starts a poll cycle.
+ *
+ * @api private
+ */
+
+JSONPPolling.prototype.doPoll = function () {
+ var self = this;
+ var script = document.createElement('script');
+
+ if (this.script) {
+ this.script.parentNode.removeChild(this.script);
+ this.script = null;
+ }
+
+ script.async = true;
+ script.src = this.uri();
+ script.onerror = function (e) {
+ self.onError('jsonp poll error', e);
+ };
+
+ var insertAt = document.getElementsByTagName('script')[0];
+ if (insertAt) {
+ insertAt.parentNode.insertBefore(script, insertAt);
+ } else {
+ (document.head || document.body).appendChild(script);
+ }
+ this.script = script;
+
+ var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);
+
+ if (isUAgecko) {
+ setTimeout(function () {
+ var iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ document.body.removeChild(iframe);
+ }, 100);
+ }
+};
+
+/**
+ * Writes with a hidden iframe.
+ *
+ * @param {String} data to send
+ * @param {Function} called upon flush.
+ * @api private
+ */
+
+JSONPPolling.prototype.doWrite = function (data, fn) {
+ var self = this;
+
+ if (!this.form) {
+ var form = document.createElement('form');
+ var area = document.createElement('textarea');
+ var id = this.iframeId = 'eio_iframe_' + this.index;
+ var iframe;
+
+ form.className = 'socketio';
+ form.style.position = 'absolute';
+ form.style.top = '-1000px';
+ form.style.left = '-1000px';
+ form.target = id;
+ form.method = 'POST';
+ form.setAttribute('accept-charset', 'utf-8');
+ area.name = 'd';
+ form.appendChild(area);
+ document.body.appendChild(form);
+
+ this.form = form;
+ this.area = area;
+ }
+
+ this.form.action = this.uri();
+
+ function complete () {
+ initIframe();
+ fn();
+ }
+
+ function initIframe () {
+ if (self.iframe) {
+ try {
+ self.form.removeChild(self.iframe);
+ } catch (e) {
+ self.onError('jsonp polling iframe removal error', e);
+ }
+ }
+
+ try {
+ // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
+ var html = '
+ * There is a set of creation methods, DOM manipulation methods, and
+ * an extended p5.Element that supports a range of HTML elements. See the
+ *
+ * beyond the canvas tutorial for a full overview of how this addon works.
+ *
+ *
Methods and properties shown in black are part of the p5.js core, items in
+ * blue are part of the p5.dom library. You will need to include an extra file
+ * in order to access the blue functions. See the
+ * using a library
+ * section for information on how to include this library. p5.dom comes with
+ * p5 complete or you can download the single file
+ *
+ * here.
+ * Creates a new HTML5 <video> element that contains the audio/video
+ * feed from a webcam. The element is separate from the canvas and is
+ * displayed by default. The element can be hidden using .hide(). The feed
+ * can be drawn onto the canvas using image().
+ * More specific properties of the feed can be passing in a Constraints object.
+ * See the
+ * W3C
+ * spec for possible properties. Note that not all of these are supported
+ * by all browsers.
+ * Security note: A new browser security specification requires that getUserMedia,
+ * which is behind createCapture(), only works when you're running the code locally,
+ * or on HTTPS. Learn more here
+ * and here.
+ *
+ * @method createCapture
+ * @param {String|Constant|Object} type type of capture, either VIDEO or
+ * AUDIO if none specified, default both,
+ * or a Constraints object
+ * @param {Function} callback function to be called once
+ * stream has loaded
+ * @return {Object|p5.Element} capture video p5.Element
+ * @example
+ * Each color stores the color mode and level maxes that applied at the\ntime of its construction. These are used to interpret the input arguments\n(at construction and later for that instance of color) and to format the\noutput e.g. when saturation() is requested.\nInternally we store an array representing the ideal RGBA values in floating\npoint form, normalized from 0 to 1. From this we calculate the closest\nscreen color (RGBA levels from 0 to 255) and expose this to the renderer.
\nWe also cache normalized, floating point components of the color in various\nrepresentations as they are calculated. This is done to prevent repeating a\nconversion that has already been performed.
\n"
+ },
+ "Setting": {
+ "name": "Setting",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Color",
+ "namespace": "",
+ "file": "src/color/setting.js",
+ "line": 1,
+ "requires": [
+ "core",
+ "constants"
+ ]
+ },
+ "Shape": {
+ "name": "Shape",
+ "submodules": {
+ "2D Primitives": 1,
+ "Curves": 1,
+ "Vertex": 1,
+ "3D Models": 1,
+ "3D Primitives": 1
+ },
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {}
+ },
+ "2D Primitives": {
+ "name": "2D Primitives",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Shape",
+ "namespace": "",
+ "file": "src/core/2d_primitives.js",
+ "line": 1,
+ "requires": [
+ "core",
+ "constants"
+ ]
+ },
+ "Attributes": {
+ "name": "Attributes",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Typography",
+ "namespace": "",
+ "file": "src/core/attributes.js",
+ "line": 1,
+ "requires": [
+ "core",
+ "constants"
+ ]
+ },
+ "Constants": {
+ "name": "Constants",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {},
+ "module": "Constants",
+ "file": "src/core/constants.js",
+ "line": 1
+ },
+ "Structure": {
+ "name": "Structure",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {},
+ "module": "IO",
+ "file": "src/core/core.js",
+ "line": 1,
+ "requires": [
+ "constants"
+ ]
+ },
+ "Curves": {
+ "name": "Curves",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Shape",
+ "namespace": "",
+ "file": "src/core/curves.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "Environment": {
+ "name": "Environment",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {},
+ "module": "Environment",
+ "file": "src/core/environment.js",
+ "line": 1,
+ "requires": [
+ "core",
+ "constants"
+ ]
+ },
+ "DOM": {
+ "name": "DOM",
+ "submodules": {},
+ "elements": {},
+ "classes": {
+ "p5.Element": 1
+ },
+ "fors": {
+ "p5.Element": 1
+ },
+ "namespaces": {},
+ "module": "DOM",
+ "file": "src/core/p5.Element.js",
+ "line": 11,
+ "description": "Base class for all elements added to a sketch, including canvas,\ngraphics buffers, and other HTML elements. Methods in blue are\nincluded in the core functionality, methods in brown are added\nwith the p5.dom\nlibrary.\nIt is not called directly, but p5.Element\nobjects are created by calling createCanvas, createGraphics,\nor in the p5.dom library, createDiv, createImg, createInput, etc.
\n"
+ },
+ "Rendering": {
+ "name": "Rendering",
+ "submodules": {
+ "undefined": 1
+ },
+ "elements": {},
+ "classes": {
+ "p5.RendererGL": 1,
+ "p5.Graphics": 1,
+ "p5.Renderer": 1
+ },
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {},
+ "module": "Rendering",
+ "file": "src/webgl/p5.RendererGL.js",
+ "line": 439,
+ "description": "Thin wrapper around a renderer, to be used for creating a\ngraphics buffer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. The fields and methods for this class are\nextensive, but mirror the normal drawing API for p5.
\n"
+ },
+ "Transform": {
+ "name": "Transform",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {},
+ "module": "Transform",
+ "file": "src/core/transform.js",
+ "line": 1,
+ "requires": [
+ "core",
+ "constants"
+ ]
+ },
+ "Vertex": {
+ "name": "Vertex",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Shape",
+ "namespace": "",
+ "file": "src/core/vertex.js",
+ "line": 1,
+ "requires": [
+ "core",
+ "constants"
+ ]
+ },
+ "Data": {
+ "name": "Data",
+ "submodules": {
+ "Dictionary": 1,
+ "Array Functions": 1,
+ "String Functions": 1
+ },
+ "elements": {},
+ "classes": {
+ "p5.TypedDict": 1,
+ "p5.StringDict": 1,
+ "p5.NumberDict": 1
+ },
+ "fors": {
+ "p5.TypedDict": 1,
+ "p5": 1
+ },
+ "namespaces": {},
+ "file": "src/data/p5.TypedDict.js",
+ "line": 407
+ },
+ "Dictionary": {
+ "name": "Dictionary",
+ "submodules": {},
+ "elements": {},
+ "classes": {
+ "p5.TypedDict": 1,
+ "p5.StringDict": 1,
+ "p5.NumberDict": 1
+ },
+ "fors": {
+ "p5.TypedDict": 1,
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Data",
+ "namespace": "",
+ "file": "src/data/p5.TypedDict.js",
+ "line": 407,
+ "requires": [
+ "core\n\nThis module defines the p5 methods for the p5 Dictionary classes\nthese classes StringDict and NumberDict are for storing and working\nwith key",
+ "value pairs"
+ ],
+ "description": "Base class for all p5.Dictionary types. More specifically\n typed Dictionary objects inherit from this
\n"
+ },
+ "Events": {
+ "name": "Events",
+ "submodules": {
+ "Acceleration": 1,
+ "Keyboard": 1,
+ "Mouse": 1,
+ "Touch": 1
+ },
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {}
+ },
+ "Acceleration": {
+ "name": "Acceleration",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Events",
+ "namespace": "",
+ "file": "src/events/acceleration.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "Keyboard": {
+ "name": "Keyboard",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Events",
+ "namespace": "",
+ "file": "src/events/keyboard.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "Mouse": {
+ "name": "Mouse",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Events",
+ "namespace": "",
+ "file": "src/events/mouse.js",
+ "line": 1,
+ "requires": [
+ "core",
+ "constants"
+ ]
+ },
+ "Touch": {
+ "name": "Touch",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Events",
+ "namespace": "",
+ "file": "src/events/touch.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "Image": {
+ "name": "Image",
+ "submodules": {
+ "Pixels": 1
+ },
+ "elements": {},
+ "classes": {
+ "p5.Image": 1
+ },
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {},
+ "module": "Image",
+ "file": "src/image/p5.Image.js",
+ "line": 23,
+ "requires": [
+ "core"
+ ],
+ "description": "Creates a new p5.Image. A p5.Image is a canvas backed representation of an\nimage.\n
\np5 can display .gif, .jpg and .png images. Images may be displayed\nin 2D and 3D space. Before an image is used, it must be loaded with the\nloadImage() function. The p5.Image class contains fields for the width and\nheight of the image, as well as an array called pixels[] that contains the\nvalues for every pixel in the image.\n
\nThe methods described below allow easy access to the image's pixels and\nalpha channel and simplify the process of compositing.\n
\nBefore using the pixels[] array, be sure to use the loadPixels() method on\nthe image to make sure that the pixel data is properly loaded.
\n"
+ },
+ "Loading & Displaying": {
+ "name": "Loading & Displaying",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Typography",
+ "namespace": "",
+ "file": "src/image/loading_displaying.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "Pixels": {
+ "name": "Pixels",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Image",
+ "namespace": "",
+ "file": "src/image/pixels.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "IO": {
+ "name": "IO",
+ "submodules": {
+ "Structure": 1,
+ "Input": 1,
+ "Output": 1,
+ "Table": 1,
+ "XML": 1,
+ "Time & Date": 1
+ },
+ "elements": {},
+ "classes": {
+ "p5": 1,
+ "p5.PrintWriter": 1,
+ "p5.Table": 1,
+ "p5.TableRow": 1,
+ "p5.XML": 1
+ },
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {},
+ "file": "src/io/p5.XML.js",
+ "line": 11
+ },
+ "Input": {
+ "name": "Input",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "IO",
+ "namespace": "",
+ "file": "src/io/files.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "Output": {
+ "name": "Output",
+ "submodules": {},
+ "elements": {},
+ "classes": {
+ "p5": 1,
+ "p5.PrintWriter": 1
+ },
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "IO",
+ "namespace": "",
+ "file": "src/io/files.js",
+ "line": 1169,
+ "description": "This is the p5 instance constructor.
\nA p5 instance holds all the properties and methods related to\na p5 sketch. It expects an incoming sketch closure and it can also\ntake an optional node parameter for attaching the generated p5 canvas\nto a node. The sketch closure takes the newly created p5 instance as\nits sole argument and may optionally set preload(), setup(), and/or\ndraw() properties on it for running a sketch.
\nA p5 sketch can run in "global" or "instance" mode:\n"global" - all properties and methods are attached to the window\n"instance" - all properties and methods are bound to this p5 object
\n"
+ },
+ "Table": {
+ "name": "Table",
+ "submodules": {},
+ "elements": {},
+ "classes": {
+ "p5.Table": 1,
+ "p5.TableRow": 1
+ },
+ "fors": {},
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "IO",
+ "namespace": "",
+ "file": "src/io/p5.TableRow.js",
+ "line": 11,
+ "requires": [
+ "core"
+ ],
+ "description": "Table objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file.
\n"
+ },
+ "XML": {
+ "name": "XML",
+ "submodules": {},
+ "elements": {},
+ "classes": {
+ "p5.XML": 1
+ },
+ "fors": {},
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "IO",
+ "namespace": "",
+ "file": "src/io/p5.XML.js",
+ "line": 11,
+ "requires": [
+ "core"
+ ],
+ "description": "XML is a representation of an XML object, able to parse XML code. Use\nloadXML() to load external XML files and create XML objects.
\n"
+ },
+ "Math": {
+ "name": "Math",
+ "submodules": {
+ "Calculation": 1,
+ "Noise": 1,
+ "Random": 1,
+ "Trigonometry": 1
+ },
+ "elements": {},
+ "classes": {
+ "p5.Vector": 1
+ },
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {},
+ "module": "Math",
+ "file": "src/math/p5.Vector.js",
+ "line": 12,
+ "requires": [
+ "core"
+ ],
+ "description": "A class to describe a two or three dimensional vector, specifically\na Euclidean (also known as geometric) vector. A vector is an entity\nthat has both magnitude and direction. The datatype, however, stores\nthe components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude\nand direction can be accessed via the methods mag() and heading().\n
\nIn many of the p5.js examples, you will see p5.Vector used to describe a\nposition, velocity, or acceleration. For example, if you consider a rectangle\nmoving across the screen, at any given instant it has a position (a vector\nthat points from the origin to its location), a velocity (the rate at which\nthe object's position changes per time unit, expressed as a vector), and\nacceleration (the rate at which the object's velocity changes per time\nunit, expressed as a vector).\n
\nSince vectors represent groupings of values, we cannot simply use\ntraditional addition/multiplication/etc. Instead, we'll need to do some\n"vector" math, which is made easy by the methods inside the p5.Vector class.
\n"
+ },
+ "Calculation": {
+ "name": "Calculation",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Math",
+ "namespace": "",
+ "file": "src/math/calculation.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "Noise": {
+ "name": "Noise",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Math",
+ "namespace": "",
+ "file": "src/math/noise.js",
+ "line": 14,
+ "requires": [
+ "core"
+ ]
+ },
+ "Random": {
+ "name": "Random",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Math",
+ "namespace": "",
+ "file": "src/math/random.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "Trigonometry": {
+ "name": "Trigonometry",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Math",
+ "namespace": "",
+ "file": "src/math/trigonometry.js",
+ "line": 1,
+ "requires": [
+ "core",
+ "constants"
+ ]
+ },
+ "Typography": {
+ "name": "Typography",
+ "submodules": {
+ "Attributes": 1,
+ "Loading & Displaying": 1,
+ "Font": 1
+ },
+ "elements": {},
+ "classes": {
+ "p5.Font": 1
+ },
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {},
+ "file": "src/typography/p5.Font.js",
+ "line": 21
+ },
+ "Font": {
+ "name": "Font",
+ "submodules": {},
+ "elements": {},
+ "classes": {
+ "p5.Font": 1
+ },
+ "fors": {},
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Typography",
+ "namespace": "",
+ "file": "src/typography/p5.Font.js",
+ "line": 21,
+ "description": "This module defines the p5.Font class and functions for\ndrawing text to the display canvas.
\n",
+ "requires": [
+ "core",
+ "constants"
+ ]
+ },
+ "Array Functions": {
+ "name": "Array Functions",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Data",
+ "namespace": "",
+ "file": "src/utilities/array_functions.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "String Functions": {
+ "name": "String Functions",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Data",
+ "namespace": "",
+ "file": "src/utilities/string_functions.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "Time & Date": {
+ "name": "Time & Date",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "IO",
+ "namespace": "",
+ "file": "src/utilities/time_date.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "Lights, Camera": {
+ "name": "Lights, Camera",
+ "submodules": {
+ "Camera": 1,
+ "Lights": 1,
+ "Material": 1,
+ "Shaders": 1
+ },
+ "elements": {},
+ "classes": {
+ "p5.Geometry": 1,
+ "p5.Matrix": 1,
+ "p5.Shader": 1,
+ "p5.Texture": 1
+ },
+ "fors": {
+ "p5": 1
+ },
+ "namespaces": {},
+ "file": "src/webgl/p5.Texture.js",
+ "line": 13
+ },
+ "Camera": {
+ "name": "Camera",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Lights, Camera",
+ "namespace": "",
+ "file": "src/webgl/camera.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "Lights": {
+ "name": "Lights",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Lights, Camera",
+ "namespace": "",
+ "file": "src/webgl/light.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ]
+ },
+ "3D Models": {
+ "name": "3D Models",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Shape",
+ "namespace": "",
+ "file": "src/webgl/loading.js",
+ "line": 1,
+ "requires": [
+ "core",
+ "p5.Geometry"
+ ]
+ },
+ "Material": {
+ "name": "Material",
+ "submodules": {},
+ "elements": {},
+ "classes": {
+ "p5.Texture": 1
+ },
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Lights, Camera",
+ "namespace": "",
+ "file": "src/webgl/p5.Texture.js",
+ "line": 13,
+ "requires": [
+ "core"
+ ],
+ "description": "This module defines the p5.Texture class
\n"
+ },
+ "Shaders": {
+ "name": "Shaders",
+ "submodules": {},
+ "elements": {},
+ "classes": {
+ "p5.Shader": 1
+ },
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Lights, Camera",
+ "namespace": "",
+ "file": "src/webgl/p5.Shader.js",
+ "line": 13,
+ "description": "This module defines the p5.Shader class
\n",
+ "requires": [
+ "core"
+ ]
+ },
+ "3D Primitives": {
+ "name": "3D Primitives",
+ "submodules": {},
+ "elements": {},
+ "classes": {},
+ "fors": {
+ "p5": 1
+ },
+ "is_submodule": 1,
+ "namespaces": {},
+ "module": "Shape",
+ "namespace": "",
+ "file": "src/webgl/primitives.js",
+ "line": 1,
+ "requires": [
+ "core",
+ "p5.Geometry"
+ ]
+ },
+ "p5.dom": {
+ "name": "p5.dom",
+ "submodules": {},
+ "elements": {},
+ "classes": {
+ "p5.dom": 1,
+ "p5.MediaElement": 1,
+ "p5.File": 1
+ },
+ "fors": {
+ "p5.dom": 1,
+ "p5.Element": 1
+ },
+ "namespaces": {},
+ "module": "p5.dom",
+ "file": "lib/addons/p5.dom.js",
+ "line": 2885,
+ "description": "The web is much more than just canvas and p5.dom makes it easy to interact\nwith other HTML5 objects, including text, hyperlink, image, input, video,\naudio, and webcam.
\nThere is a set of creation methods, DOM manipulation methods, and\nan extended p5.Element that supports a range of HTML elements. See the\n\nbeyond the canvas tutorial for a full overview of how this addon works.
\nMethods and properties shown in black are part of the p5.js core, items in\nblue are part of the p5.dom library. You will need to include an extra file\nin order to access the blue functions. See the\nusing a library\nsection for information on how to include this library. p5.dom comes with\np5 complete or you can download the single file\n\nhere.
\nSee tutorial: beyond the canvas\nfor more info on how to use this libary.
\n",
+ "tag": "main",
+ "itemtype": "main"
+ },
+ "p5.sound": {
+ "name": "p5.sound",
+ "submodules": {},
+ "elements": {},
+ "classes": {
+ "p5.sound": 1,
+ "p5.SoundFile": 1,
+ "p5.Amplitude": 1,
+ "p5.FFT": 1,
+ "p5.Signal": 1,
+ "p5.Oscillator": 1,
+ "p5.SinOsc": 1,
+ "p5.TriOsc": 1,
+ "p5.SawOsc": 1,
+ "p5.SqrOsc": 1,
+ "p5.Env": 1,
+ "p5.Pulse": 1,
+ "p5.Noise": 1,
+ "p5.AudioIn": 1,
+ "p5.Effect": 1,
+ "p5.Filter": 1,
+ "p5.LowPass": 1,
+ "p5.HighPass": 1,
+ "p5.BandPass": 1,
+ "p5.EQ": 1,
+ "p5.Panner3D": 1,
+ "p5.Delay": 1,
+ "p5.Reverb": 1,
+ "p5.Convolver": 1,
+ "p5.Phrase": 1,
+ "p5.Part": 1,
+ "p5.Score": 1,
+ "p5.SoundLoop": 1,
+ "p5.Compressor": 1,
+ "p5.SoundRecorder": 1,
+ "p5.PeakDetect": 1,
+ "p5.Gain": 1,
+ "p5.AudioVoice": 1,
+ "p5.MonoSynth": 1,
+ "p5.PolySynth": 1,
+ "p5.Distortion": 1
+ },
+ "fors": {
+ "p5.sound": 1,
+ "p5": 1
+ },
+ "namespaces": {},
+ "module": "p5.sound",
+ "file": "lib/addons/p5.sound.js",
+ "line": 12243,
+ "description": "p5.sound extends p5 with Web Audio functionality including audio input,\nplayback, analysis and synthesis.\n
\np5.SoundFile: Load and play sound files.
\np5.Amplitude: Get the current volume of a sound.
\np5.AudioIn: Get sound from an input source, typically\n a computer microphone.
\np5.FFT: Analyze the frequency of sound. Returns\n results from the frequency spectrum or time domain (waveform).
\np5.Oscillator: Generate Sine,\n Triangle, Square and Sawtooth waveforms. Base class of\n p5.Noise and p5.Pulse.\n
\np5.Env: An Envelope is a series\n of fades over time. Often used to control an object's\n output gain level as an "ADSR Envelope" (Attack, Decay,\n Sustain, Release). Can also modulate other parameters.
\np5.Delay: A delay effect with\n parameters for feedback, delayTime, and lowpass filter.
\np5.Filter: Filter the frequency range of a\n sound.\n
\np5.Reverb: Add reverb to a sound by specifying\n duration and decay.
\np5.Convolver: Extends\np5.Reverb to simulate the sound of real\n physical spaces through convolution.
\np5.SoundRecorder: Record sound for playback\n / save the .wav file.\np5.Phrase, p5.Part and\np5.Score: Compose musical sequences.\n
\np5.sound is on GitHub.\nDownload the latest version\nhere.
\n",
+ "tag": "main",
+ "itemtype": "main"
+ }
+ },
+ "classes": {
+ "p5": {
+ "name": "p5",
+ "shortname": "p5",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "IO",
+ "submodule": "Output",
+ "namespace": "",
+ "file": "src/core/core.js",
+ "line": 15,
+ "description": "This is the p5 instance constructor.
\nA p5 instance holds all the properties and methods related to\na p5 sketch. It expects an incoming sketch closure and it can also\ntake an optional node parameter for attaching the generated p5 canvas\nto a node. The sketch closure takes the newly created p5 instance as\nits sole argument and may optionally set preload(), setup(), and/or\ndraw() properties on it for running a sketch.
\nA p5 sketch can run in "global" or "instance" mode:\n"global" - all properties and methods are attached to the window\n"instance" - all properties and methods are bound to this p5 object
\n",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "sketch",
+ "description": "a closure that can set optional preload(),\n setup(), and/or draw() properties on the\n given p5 instance
\n",
+ "type": "Function"
+ },
+ {
+ "name": "node",
+ "description": "element to attach canvas to, if a\n boolean is passed in use it as sync
\n",
+ "type": "HTMLElement|Boolean",
+ "optional": true
+ },
+ {
+ "name": "sync",
+ "description": "start synchronously (optional)
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "a p5 instance",
+ "type": "P5"
+ }
+ },
+ "p5.Color": {
+ "name": "p5.Color",
+ "shortname": "p5.Color",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "Color",
+ "submodule": "Creating & Reading",
+ "namespace": "",
+ "file": "src/color/p5.Color.js",
+ "line": 16,
+ "description": "Each color stores the color mode and level maxes that applied at the\ntime of its construction. These are used to interpret the input arguments\n(at construction and later for that instance of color) and to format the\noutput e.g. when saturation() is requested.
\nInternally we store an array representing the ideal RGBA values in floating\npoint form, normalized from 0 to 1. From this we calculate the closest\nscreen color (RGBA levels from 0 to 255) and expose this to the renderer.
\nWe also cache normalized, floating point components of the color in various\nrepresentations as they are calculated. This is done to prevent repeating a\nconversion that has already been performed.
\n"
+ },
+ "p5.Element": {
+ "name": "p5.Element",
+ "shortname": "p5.Element",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "DOM",
+ "submodule": "DOM",
+ "namespace": "",
+ "file": "src/core/p5.Element.js",
+ "line": 11,
+ "description": "Base class for all elements added to a sketch, including canvas,\ngraphics buffers, and other HTML elements. Methods in blue are\nincluded in the core functionality, methods in brown are added\nwith the p5.dom\nlibrary.\nIt is not called directly, but p5.Element\nobjects are created by calling createCanvas, createGraphics,\nor in the p5.dom library, createDiv, createImg, createInput, etc.
\n",
+ "params": [
+ {
+ "name": "elt",
+ "description": "DOM node that is wrapped
\n",
+ "type": "String"
+ },
+ {
+ "name": "pInst",
+ "description": "pointer to p5 instance
\n",
+ "type": "P5",
+ "optional": true
+ }
+ ]
+ },
+ "p5.Graphics": {
+ "name": "p5.Graphics",
+ "shortname": "p5.Graphics",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "Rendering",
+ "submodule": "Rendering",
+ "namespace": "",
+ "file": "src/core/p5.Graphics.js",
+ "line": 12,
+ "description": "Thin wrapper around a renderer, to be used for creating a\ngraphics buffer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. The fields and methods for this class are\nextensive, but mirror the normal drawing API for p5.
\n",
+ "extends": "p5.Element",
+ "params": [
+ {
+ "name": "w",
+ "description": "width
\n",
+ "type": "Number"
+ },
+ {
+ "name": "h",
+ "description": "height
\n",
+ "type": "Number"
+ },
+ {
+ "name": "renderer",
+ "description": "the renderer to use, either P2D or WEBGL
\n",
+ "type": "Constant"
+ },
+ {
+ "name": "pInst",
+ "description": "pointer to p5 instance
\n",
+ "type": "P5",
+ "optional": true
+ }
+ ]
+ },
+ "p5.Renderer": {
+ "name": "p5.Renderer",
+ "shortname": "p5.Renderer",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "Rendering",
+ "submodule": "Rendering",
+ "namespace": "",
+ "file": "src/core/p5.Renderer.js",
+ "line": 12,
+ "description": "Main graphics and rendering context, as well as the base API\nimplementation for p5.js "core". To be used as the superclass for\nRenderer2D and Renderer3D classes, respecitvely.
\n",
+ "is_constructor": 1,
+ "extends": "p5.Element",
+ "params": [
+ {
+ "name": "elt",
+ "description": "DOM node that is wrapped
\n",
+ "type": "String"
+ },
+ {
+ "name": "pInst",
+ "description": "pointer to p5 instance
\n",
+ "type": "P5",
+ "optional": true
+ },
+ {
+ "name": "isMainCanvas",
+ "description": "whether we're using it as main canvas
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ]
+ },
+ "p5.TypedDict": {
+ "name": "p5.TypedDict",
+ "shortname": "p5.TypedDict",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "Data",
+ "submodule": "Dictionary",
+ "namespace": "",
+ "file": "src/data/p5.TypedDict.js",
+ "line": 78,
+ "description": "Base class for all p5.Dictionary types. More specifically\n typed Dictionary objects inherit from this
\n"
+ },
+ "p5.StringDict": {
+ "name": "p5.StringDict",
+ "shortname": "p5.StringDict",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "Data",
+ "submodule": "Dictionary",
+ "namespace": "",
+ "file": "src/data/p5.TypedDict.js",
+ "line": 387,
+ "description": "A Dictionary class for Strings.
\n",
+ "extends": "p5.TypedDict"
+ },
+ "p5.NumberDict": {
+ "name": "p5.NumberDict",
+ "shortname": "p5.NumberDict",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "Data",
+ "submodule": "Dictionary",
+ "namespace": "",
+ "file": "src/data/p5.TypedDict.js",
+ "line": 407,
+ "description": "A simple Dictionary class for Numbers.
\n",
+ "extends": "p5.TypedDict"
+ },
+ "p5.Image": {
+ "name": "p5.Image",
+ "shortname": "p5.Image",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "Image",
+ "submodule": "Image",
+ "namespace": "",
+ "file": "src/image/p5.Image.js",
+ "line": 23,
+ "description": "Creates a new p5.Image. A p5.Image is a canvas backed representation of an\nimage.\n
\np5 can display .gif, .jpg and .png images. Images may be displayed\nin 2D and 3D space. Before an image is used, it must be loaded with the\nloadImage() function. The p5.Image class contains fields for the width and\nheight of the image, as well as an array called pixels[] that contains the\nvalues for every pixel in the image.\n
\nThe methods described below allow easy access to the image's pixels and\nalpha channel and simplify the process of compositing.\n
\nBefore using the pixels[] array, be sure to use the loadPixels() method on\nthe image to make sure that the pixel data is properly loaded.
\n",
+ "example": [
+ "\n\nfunction setup() {\n var img = createImage(100, 100); // same as new p5.Image(100, 100);\n img.loadPixels();\n createCanvas(100, 100);\n background(0);\n\n // helper for writing color to array\n function writeColor(image, x, y, red, green, blue, alpha) {\n var index = (x + y * width) * 4;\n image.pixels[index] = red;\n image.pixels[index + 1] = green;\n image.pixels[index + 2] = blue;\n image.pixels[index + 3] = alpha;\n }\n\n var x, y;\n // fill with random colors\n for (y = 0; y < img.height; y++) {\n for (x = 0; x < img.width; x++) {\n var red = random(255);\n var green = random(255);\n var blue = random(255);\n var alpha = 255;\n writeColor(img, x, y, red, green, blue, alpha);\n }\n }\n\n // draw a red line\n y = 0;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 255, 0, 0, 255);\n }\n\n // draw a green line\n y = img.height - 1;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 0, 255, 0, 255);\n }\n\n img.updatePixels();\n image(img, 0, 0);\n}\n
"
+ ],
+ "params": [
+ {
+ "name": "width",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "height",
+ "description": "",
+ "type": "Number"
+ }
+ ]
+ },
+ "p5.PrintWriter": {
+ "name": "p5.PrintWriter",
+ "shortname": "p5.PrintWriter",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "IO",
+ "submodule": "Output",
+ "namespace": "",
+ "file": "src/io/files.js",
+ "line": 1169,
+ "params": [
+ {
+ "name": "filename",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "extension",
+ "description": "",
+ "type": "String",
+ "optional": true
+ }
+ ]
+ },
+ "p5.Table": {
+ "name": "p5.Table",
+ "shortname": "p5.Table",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "IO",
+ "submodule": "Table",
+ "namespace": "",
+ "file": "src/io/p5.Table.js",
+ "line": 35,
+ "description": "Table objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file.
\n",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "rows",
+ "description": "An array of p5.TableRow objects
\n",
+ "type": "p5.TableRow[]",
+ "optional": true
+ }
+ ]
+ },
+ "p5.TableRow": {
+ "name": "p5.TableRow",
+ "shortname": "p5.TableRow",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "IO",
+ "submodule": "Table",
+ "namespace": "",
+ "file": "src/io/p5.TableRow.js",
+ "line": 11,
+ "description": "A TableRow object represents a single row of data values,\nstored in columns, from a table.
\nA Table Row contains both an ordered array, and an unordered\nJSON object.
\n",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "str",
+ "description": "optional: populate the row with a\n string of values, separated by the\n separator
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "separator",
+ "description": "comma separated values (csv) by default
\n",
+ "type": "String",
+ "optional": true
+ }
+ ]
+ },
+ "p5.XML": {
+ "name": "p5.XML",
+ "shortname": "p5.XML",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "IO",
+ "submodule": "XML",
+ "namespace": "",
+ "file": "src/io/p5.XML.js",
+ "line": 11,
+ "description": "XML is a representation of an XML object, able to parse XML code. Use\nloadXML() to load external XML files and create XML objects.
\n",
+ "is_constructor": 1,
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var children = xml.getChildren('animal');\n\n for (var i = 0; i < children.length; i++) {\n var id = children[i].getNum('id');\n var coloring = children[i].getString('species');\n var name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
"
+ ],
+ "alt": "no image displayed"
+ },
+ "p5.Vector": {
+ "name": "p5.Vector",
+ "shortname": "p5.Vector",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "Math",
+ "submodule": "Math",
+ "namespace": "",
+ "file": "src/math/p5.Vector.js",
+ "line": 12,
+ "description": "A class to describe a two or three dimensional vector, specifically\na Euclidean (also known as geometric) vector. A vector is an entity\nthat has both magnitude and direction. The datatype, however, stores\nthe components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude\nand direction can be accessed via the methods mag() and heading().\n
\nIn many of the p5.js examples, you will see p5.Vector used to describe a\nposition, velocity, or acceleration. For example, if you consider a rectangle\nmoving across the screen, at any given instant it has a position (a vector\nthat points from the origin to its location), a velocity (the rate at which\nthe object's position changes per time unit, expressed as a vector), and\nacceleration (the rate at which the object's velocity changes per time\nunit, expressed as a vector).\n
\nSince vectors represent groupings of values, we cannot simply use\ntraditional addition/multiplication/etc. Instead, we'll need to do some\n"vector" math, which is made easy by the methods inside the p5.Vector class.
\n",
+ "params": [
+ {
+ "name": "x",
+ "description": "x component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "y",
+ "description": "y component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "z",
+ "description": "z component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\n\nvar v1 = createVector(40, 50);\nvar v2 = createVector(40, 50);\n\nellipse(v1.x, v1.y, 50, 50);\nellipse(v2.x, v2.y, 50, 50);\nv1.add(v2);\nellipse(v1.x, v1.y, 50, 50);\n\n
"
+ ],
+ "alt": "2 white ellipses. One center-left the other bottom right and off canvas"
+ },
+ "p5.Font": {
+ "name": "p5.Font",
+ "shortname": "p5.Font",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "Typography",
+ "submodule": "Font",
+ "namespace": "",
+ "file": "src/typography/p5.Font.js",
+ "line": 21,
+ "description": "Base class for font handling
\n",
+ "params": [
+ {
+ "name": "pInst",
+ "description": "pointer to p5 instance
\n",
+ "type": "P5",
+ "optional": true
+ }
+ ]
+ },
+ "p5.Geometry": {
+ "name": "p5.Geometry",
+ "shortname": "p5.Geometry",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "Lights, Camera",
+ "namespace": "",
+ "file": "src/webgl/p5.Geometry.js",
+ "line": 6,
+ "description": "p5 Geometry class
\n",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "vertData",
+ "description": "callback function or Object\n containing routine(s) for vertex data generation
\n",
+ "type": "Function | Object"
+ },
+ {
+ "name": "detailX",
+ "description": "number of vertices on horizontal surface
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "detailY",
+ "description": "number of vertices on horizontal surface
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "callback",
+ "description": "function to call upon object instantiation.
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ]
+ },
+ "p5.Shader": {
+ "name": "p5.Shader",
+ "shortname": "p5.Shader",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "Lights, Camera",
+ "submodule": "Shaders",
+ "namespace": "",
+ "file": "src/webgl/p5.Shader.js",
+ "line": 13,
+ "description": "Shader class for WEBGL Mode
\n",
+ "params": [
+ {
+ "name": "renderer",
+ "description": "an instance of p5.RendererGL that\nwill provide the GL context for this new p5.Shader
\n",
+ "type": "p5.RendererGL"
+ },
+ {
+ "name": "vertSrc",
+ "description": "source code for the vertex shader (as a string)
\n",
+ "type": "String"
+ },
+ {
+ "name": "fragSrc",
+ "description": "source code for the fragment shader (as a string)
\n",
+ "type": "String"
+ }
+ ]
+ },
+ "p5.dom": {
+ "name": "p5.dom",
+ "shortname": "p5.dom",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.dom",
+ "submodule": "p5.dom",
+ "namespace": ""
+ },
+ "p5.MediaElement": {
+ "name": "p5.MediaElement",
+ "shortname": "p5.MediaElement",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.dom",
+ "submodule": "p5.dom",
+ "namespace": "",
+ "file": "lib/addons/p5.dom.js",
+ "line": 1829,
+ "description": "Extends p5.Element to handle audio and video. In addition to the methods\nof p5.Element, it also contains methods for controlling media. It is not\ncalled directly, but p5.MediaElements are created by calling createVideo,\ncreateAudio, and createCapture.
\n",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "elt",
+ "description": "DOM node that is wrapped
\n",
+ "type": "String"
+ }
+ ]
+ },
+ "p5.File": {
+ "name": "p5.File",
+ "shortname": "p5.File",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.dom",
+ "submodule": "p5.dom",
+ "namespace": "",
+ "file": "lib/addons/p5.dom.js",
+ "line": 2885,
+ "description": "Base class for a file\nUsing this for createFileInput
\n",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "file",
+ "description": "File that is wrapped
\n",
+ "type": "File"
+ }
+ ]
+ },
+ "p5.sound": {
+ "name": "p5.sound",
+ "shortname": "p5.sound",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": ""
+ },
+ "p5.SoundFile": {
+ "name": "p5.SoundFile",
+ "shortname": "p5.SoundFile",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 740,
+ "description": "SoundFile object with a path to a file.
\n\nThe p5.SoundFile may not be available immediately because\nit loads the file information asynchronously.
\n\nTo do something with the sound as soon as it loads\npass the name of a function as the second parameter.
\n\nOnly one file path is required. However, audio file formats\n(i.e. mp3, ogg, wav and m4a/aac) are not supported by all\nweb browsers. If you want to ensure compatability, instead of a single\nfile path, you may include an Array of filepaths, and the browser will\nchoose a format that works.
",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "path",
+ "description": "path to a sound file (String). Optionally,\n you may include multiple file formats in\n an array. Alternately, accepts an object\n from the HTML5 File API, or a p5.File.
\n",
+ "type": "String|Array"
+ },
+ {
+ "name": "successCallback",
+ "description": "Name of a function to call once file loads
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "Name of a function to call if file fails to\n load. This function will receive an error or\n XMLHttpRequest object with information\n about what went wrong.
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "whileLoadingCallback",
+ "description": "Name of a function to call while file\n is loading. That function will\n receive progress of the request to\n load the sound file\n (between 0 and 1) as its first\n parameter. This progress\n does not account for the additional\n time needed to decode the audio data.
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\n\nfunction preload() {\n soundFormats('mp3', 'ogg');\n mySound = loadSound('assets/doorbell.mp3');\n}\n\nfunction setup() {\n mySound.setVolume(0.1);\n mySound.play();\n}\n\n
"
+ ]
+ },
+ "p5.Amplitude": {
+ "name": "p5.Amplitude",
+ "shortname": "p5.Amplitude",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 2154,
+ "description": "Amplitude measures volume between 0.0 and 1.0.\nListens to all p5sound by default, or use setInput()\nto listen to a specific sound source. Accepts an optional\nsmoothing value, which defaults to 0.
\n",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "smoothing",
+ "description": "between 0.0 and .999 to smooth\n amplitude readings (defaults to 0)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nvar sound, amplitude, cnv;\n\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\nfunction setup() {\n cnv = createCanvas(100,100);\n amplitude = new p5.Amplitude();\n\n // start / stop the sound when canvas is clicked\n cnv.mouseClicked(function() {\n if (sound.isPlaying() ){\n sound.stop();\n } else {\n sound.play();\n }\n });\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\n\n
"
+ ]
+ },
+ "p5.FFT": {
+ "name": "p5.FFT",
+ "shortname": "p5.FFT",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 2426,
+ "description": "FFT (Fast Fourier Transform) is an analysis algorithm that\nisolates individual\n\naudio frequencies within a waveform.
\n\nOnce instantiated, a p5.FFT object can return an array based on\ntwo types of analyses:
• FFT.waveform() computes\namplitude values along the time domain. The array indices correspond\nto samples across a brief moment in time. Each value represents\namplitude of the waveform at that sample of time.
\n• FFT.analyze() computes amplitude values along the\nfrequency domain. The array indices correspond to frequencies (i.e.\npitches), from the lowest to the highest that humans can hear. Each\nvalue represents amplitude at that slice of the frequency spectrum.\nUse with getEnergy() to measure amplitude at specific\nfrequencies, or within a range of frequencies.
\n\nFFT analyzes a very short snapshot of sound called a sample\nbuffer. It returns an array of amplitude measurements, referred\nto as bins. The array is 1024 bins long by default.\nYou can change the bin array length, but it must be a power of 2\nbetween 16 and 1024 in order for the FFT algorithm to function\ncorrectly. The actual size of the FFT buffer is twice the\nnumber of bins, so given a standard sample rate, the buffer is\n2048/44100 seconds long.
",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "smoothing",
+ "description": "Smooth results of Freq Spectrum.\n 0.0 < smoothing < 1.0.\n Defaults to 0.8.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "bins",
+ "description": "Length of resulting array.\n Must be a power of two between\n 16 and 1024. Defaults to 1024.
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nfunction preload(){\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup(){\n var cnv = createCanvas(100,100);\n cnv.mouseClicked(togglePlay);\n fft = new p5.FFT();\n sound.amp(0.2);\n}\n\nfunction draw(){\n background(0);\n\n var spectrum = fft.analyze();\n noStroke();\n fill(0,255,0); // spectrum is green\n for (var i = 0; i< spectrum.length; i++){\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h )\n }\n\n var waveform = fft.waveform();\n noFill();\n beginShape();\n stroke(255,0,0); // waveform is red\n strokeWeight(1);\n for (var i = 0; i< waveform.length; i++){\n var x = map(i, 0, waveform.length, 0, width);\n var y = map( waveform[i], -1, 1, 0, height);\n vertex(x,y);\n }\n endShape();\n\n text('click to play/pause', 4, 10);\n}\n\n// fade sound if mouse is over canvas\nfunction togglePlay() {\n if (sound.isPlaying()) {\n sound.pause();\n } else {\n sound.loop();\n }\n}\n
"
+ ]
+ },
+ "p5.Signal": {
+ "name": "p5.Signal",
+ "shortname": "p5.Signal",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 4828,
+ "description": "p5.Signal is a constant audio-rate signal used by p5.Oscillator\nand p5.Envelope for modulation math.
\n\nThis is necessary because Web Audio is processed on a seprate clock.\nFor example, the p5 draw loop runs about 60 times per second. But\nthe audio clock must process samples 44100 times per second. If we\nwant to add a value to each of those samples, we can't do it in the\ndraw loop, but we can do it by adding a constant-rate audio signal.</p.\n\n
This class mostly functions behind the scenes in p5.sound, and returns\na Tone.Signal from the Tone.js library by Yotam Mann.\nIf you want to work directly with audio signals for modular\nsynthesis, check out\ntone.js.
",
+ "is_constructor": 1,
+ "return": {
+ "description": "A Signal object from the Tone.js library",
+ "type": "Tone.Signal"
+ },
+ "example": [
+ "\n\nfunction setup() {\n carrier = new p5.Oscillator('sine');\n carrier.amp(1); // set amplitude\n carrier.freq(220); // set frequency\n carrier.start(); // start oscillating\n\n modulator = new p5.Oscillator('sawtooth');\n modulator.disconnect();\n modulator.amp(1);\n modulator.freq(4);\n modulator.start();\n\n // Modulator's default amplitude range is -1 to 1.\n // Multiply it by -200, so the range is -200 to 200\n // then add 220 so the range is 20 to 420\n carrier.freq( modulator.mult(-200).add(220) );\n}\n
"
+ ]
+ },
+ "p5.Oscillator": {
+ "name": "p5.Oscillator",
+ "shortname": "p5.Oscillator",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 4974,
+ "description": "Creates a signal that oscillates between -1.0 and 1.0.\nBy default, the oscillation takes the form of a sinusoidal\nshape ('sine'). Additional types include 'triangle',\n'sawtooth' and 'square'. The frequency defaults to\n440 oscillations per second (440Hz, equal to the pitch of an\n'A' note).
\n\nSet the type of oscillation with setType(), or by instantiating a\nspecific oscillator: p5.SinOsc, p5.TriOsc, p5.SqrOsc, or p5.SawOsc.\n
",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "freq",
+ "description": "frequency defaults to 440Hz
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "type",
+ "description": "type of oscillator. Options:\n 'sine' (default), 'triangle',\n 'sawtooth', 'square'
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nvar osc;\nvar playing = false;\n\nfunction setup() {\n backgroundColor = color(255,0,255);\n textAlign(CENTER);\n\n osc = new p5.Oscillator();\n osc.setType('sine');\n osc.freq(240);\n osc.amp(0);\n osc.start();\n}\n\nfunction draw() {\n background(backgroundColor)\n text('click to play', width/2, height/2);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {\n if (!playing) {\n // ramp amplitude to 0.5 over 0.05 seconds\n osc.amp(0.5, 0.05);\n playing = true;\n backgroundColor = color(0,255,255);\n } else {\n // ramp amplitude to 0 over 0.5 seconds\n osc.amp(0, 0.5);\n playing = false;\n backgroundColor = color(255,0,255);\n }\n }\n}\n
"
+ ]
+ },
+ "p5.SinOsc": {
+ "name": "p5.SinOsc",
+ "shortname": "p5.SinOsc",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 5409,
+ "description": "Constructor: new p5.SinOsc().\nThis creates a Sine Wave Oscillator and is\nequivalent to new p5.Oscillator('sine')\n or creating a p5.Oscillator and then calling\nits method setType('sine').\nSee p5.Oscillator for methods.
\n",
+ "is_constructor": 1,
+ "extends": "p5.Oscillator",
+ "params": [
+ {
+ "name": "freq",
+ "description": "Set the frequency
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ]
+ },
+ "p5.TriOsc": {
+ "name": "p5.TriOsc",
+ "shortname": "p5.TriOsc",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 5426,
+ "description": "Constructor: new p5.TriOsc().\nThis creates a Triangle Wave Oscillator and is\nequivalent to new p5.Oscillator('triangle')\n or creating a p5.Oscillator and then calling\nits method setType('triangle').\nSee p5.Oscillator for methods.
\n",
+ "is_constructor": 1,
+ "extends": "p5.Oscillator",
+ "params": [
+ {
+ "name": "freq",
+ "description": "Set the frequency
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ]
+ },
+ "p5.SawOsc": {
+ "name": "p5.SawOsc",
+ "shortname": "p5.SawOsc",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 5443,
+ "description": "Constructor: new p5.SawOsc().\nThis creates a SawTooth Wave Oscillator and is\nequivalent to new p5.Oscillator('sawtooth')\n or creating a p5.Oscillator and then calling\nits method setType('sawtooth').\nSee p5.Oscillator for methods.
\n",
+ "is_constructor": 1,
+ "extends": "p5.Oscillator",
+ "params": [
+ {
+ "name": "freq",
+ "description": "Set the frequency
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ]
+ },
+ "p5.SqrOsc": {
+ "name": "p5.SqrOsc",
+ "shortname": "p5.SqrOsc",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 5460,
+ "description": "Constructor: new p5.SqrOsc().\nThis creates a Square Wave Oscillator and is\nequivalent to new p5.Oscillator('square')\n or creating a p5.Oscillator and then calling\nits method setType('square').\nSee p5.Oscillator for methods.
\n",
+ "is_constructor": 1,
+ "extends": "p5.Oscillator",
+ "params": [
+ {
+ "name": "freq",
+ "description": "Set the frequency
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ]
+ },
+ "p5.Env": {
+ "name": "p5.Env",
+ "shortname": "p5.Env",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 5917,
+ "description": "Envelopes are pre-defined amplitude distribution over time.\nTypically, envelopes are used to control the output volume\nof an object, a series of fades referred to as Attack, Decay,\nSustain and Release (\nADSR\n). Envelopes can also control other Web Audio Parameters—for example, a p5.Env can\ncontrol an Oscillator's frequency like this: osc.freq(env).
\nUse setRange to change the attack/release level.\nUse setADSR to change attackTime, decayTime, sustainPercent and releaseTime.
\nUse the play method to play the entire envelope,\nthe ramp method for a pingable trigger,\nor triggerAttack/\ntriggerRelease to trigger noteOn/noteOff.
",
+ "is_constructor": 1,
+ "example": [
+ "\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n
"
+ ]
+ },
+ "p5.Pulse": {
+ "name": "p5.Pulse",
+ "shortname": "p5.Pulse",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 6709,
+ "description": "Creates a Pulse object, an oscillator that implements\nPulse Width Modulation.\nThe pulse is created with two oscillators.\nAccepts a parameter for frequency, and to set the\nwidth between the pulses. See \np5.Oscillator for a full list of methods.
\n",
+ "extends": "p5.Oscillator",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "freq",
+ "description": "Frequency in oscillations per second (Hz)
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "w",
+ "description": "Width between the pulses (0 to 1.0,\n defaults to 0)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nvar pulse;\nfunction setup() {\n background(0);\n\n // Create and start the pulse wave oscillator\n pulse = new p5.Pulse();\n pulse.amp(0.5);\n pulse.freq(220);\n pulse.start();\n}\n\nfunction draw() {\n var w = map(mouseX, 0, width, 0, 1);\n w = constrain(w, 0, 1);\n pulse.width(w)\n}\n
"
+ ]
+ },
+ "p5.Noise": {
+ "name": "p5.Noise",
+ "shortname": "p5.Noise",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 6886,
+ "description": "Noise is a type of oscillator that generates a buffer with random values.
\n",
+ "extends": "p5.Oscillator",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "type",
+ "description": "Type of noise can be 'white' (default),\n 'brown' or 'pink'.
\n",
+ "type": "String"
+ }
+ ]
+ },
+ "p5.AudioIn": {
+ "name": "p5.AudioIn",
+ "shortname": "p5.AudioIn",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 7075,
+ "description": "Get audio from an input, i.e. your computer's microphone.
\n\nTurn the mic on/off with the start() and stop() methods. When the mic\nis on, its volume can be measured with getLevel or by connecting an\nFFT object.
\n\nIf you want to hear the AudioIn, use the .connect() method.\nAudioIn does not connect to p5.sound output by default to prevent\nfeedback.
\n\nNote: This uses the getUserMedia/\nStream API, which is not supported by certain browsers. Access in Chrome browser\nis limited to localhost and https, but access over http may be limited.
",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "errorCallback",
+ "description": "A function to call if there is an error\n accessing the AudioIn. For example,\n Safari and iOS devices do not\n currently allow microphone access.
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nvar mic;\nfunction setup(){\n mic = new p5.AudioIn()\n mic.start();\n}\nfunction draw(){\n background(0);\n micLevel = mic.getLevel();\n ellipse(width/2, constrain(height-micLevel*height*5, 0, height), 10, 10);\n}\n
"
+ ]
+ },
+ "p5.Effect": {
+ "name": "p5.Effect",
+ "shortname": "p5.Effect",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 7970,
+ "description": "Effect is a base class for audio effects in p5.
\nThis module handles the nodes and methods that are\ncommon and useful for current and future effects.
\nThis class is extended by p5.Distortion,\np5.Compressor,\np5.Delay,\np5.Filter,\np5.Reverb.
\n",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "ac",
+ "description": "Reference to the audio context of the p5 object
\n",
+ "type": "Object",
+ "optional": true
+ },
+ {
+ "name": "input",
+ "description": "Gain Node effect wrapper
\n",
+ "type": "AudioNode",
+ "optional": true
+ },
+ {
+ "name": "output",
+ "description": "Gain Node effect wrapper
\n",
+ "type": "AudioNode",
+ "optional": true
+ },
+ {
+ "name": "_drywet",
+ "description": "Tone.JS CrossFade node (defaults to value: 1)
\n",
+ "type": "Object",
+ "optional": true
+ },
+ {
+ "name": "wet",
+ "description": "Effects that extend this class should connect\n to the wet signal to this gain node, so that dry and wet\n signals are mixed properly.
\n",
+ "type": "AudioNode",
+ "optional": true
+ }
+ ]
+ },
+ "p5.Filter": {
+ "name": "p5.Filter",
+ "shortname": "p5.Filter",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 8102,
+ "description": "A p5.Filter uses a Web Audio Biquad Filter to filter\nthe frequency response of an input source. Subclasses\ninclude:
\n\np5.LowPass:\nAllows frequencies below the cutoff frequency to pass through,\nand attenuates frequencies above the cutoff.
\np5.HighPass:\nThe opposite of a lowpass filter.
\np5.BandPass:\nAllows a range of frequencies to pass through and attenuates\nthe frequencies below and above this frequency range.
\n
\nThe .res() method controls either width of the\nbandpass, or resonance of the low/highpass cutoff frequency.
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n",
+ "extends": "p5.Effect",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "type",
+ "description": "'lowpass' (default), 'highpass', 'bandpass'
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nvar fft, noise, filter;\n\nfunction setup() {\n fill(255, 40, 255);\n\n filter = new p5.BandPass();\n\n noise = new p5.Noise();\n // disconnect unfiltered noise,\n // and connect to filter\n noise.disconnect();\n noise.connect(filter);\n noise.start();\n\n fft = new p5.FFT();\n}\n\nfunction draw() {\n background(30);\n\n // set the BandPass frequency based on mouseX\n var freq = map(mouseX, 0, width, 20, 10000);\n filter.freq(freq);\n // give the filter a narrow band (lower res = wider bandpass)\n filter.res(50);\n\n // draw filtered spectrum\n var spectrum = fft.analyze();\n noStroke();\n for (var i = 0; i < spectrum.length; i++) {\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width/spectrum.length, h);\n }\n\n isMouseOverCanvas();\n}\n\nfunction isMouseOverCanvas() {\n var mX = mouseX, mY = mouseY;\n if (mX > 0 && mX < width && mY < height && mY > 0) {\n noise.amp(0.5, 0.2);\n } else {\n noise.amp(0, 0.2);\n }\n}\n
"
+ ]
+ },
+ "p5.LowPass": {
+ "name": "p5.LowPass",
+ "shortname": "p5.LowPass",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 8332,
+ "description": "Constructor: new p5.LowPass() Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('lowpass').\nSee p5.Filter for methods.
\n",
+ "is_constructor": 1,
+ "extends": "p5.Filter"
+ },
+ "p5.HighPass": {
+ "name": "p5.HighPass",
+ "shortname": "p5.HighPass",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 8346,
+ "description": "Constructor: new p5.HighPass() Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('highpass').\nSee p5.Filter for methods.
\n",
+ "is_constructor": 1,
+ "extends": "p5.Filter"
+ },
+ "p5.BandPass": {
+ "name": "p5.BandPass",
+ "shortname": "p5.BandPass",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 8360,
+ "description": "Constructor: new p5.BandPass() Filter.\nThis is the same as creating a p5.Filter and then calling\nits method setType('bandpass').\nSee p5.Filter for methods.
\n",
+ "is_constructor": 1,
+ "extends": "p5.Filter"
+ },
+ "p5.EQ": {
+ "name": "p5.EQ",
+ "shortname": "p5.EQ",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 8429,
+ "description": "p5.EQ is an audio effect that performs the function of a multiband\naudio equalizer. Equalization is used to adjust the balance of\nfrequency compoenents of an audio signal. This process is commonly used\nin sound production and recording to change the waveform before it reaches\na sound output device. EQ can also be used as an audio effect to create\ninteresting distortions by filtering out parts of the spectrum. p5.EQ is\nbuilt using a chain of Web Audio Biquad Filter Nodes and can be\ninstantiated with 3 or 8 bands. Bands can be added or removed from\nthe EQ by directly modifying p5.EQ.bands (the array that stores filters).
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n",
+ "is_constructor": 1,
+ "extends": "p5.Effect",
+ "params": [
+ {
+ "name": "_eqsize",
+ "description": "Constructor will accept 3 or 8, defaults to 3
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "p5.EQ object",
+ "type": "Object"
+ },
+ "example": [
+ "\n\nvar eq;\nvar band_names;\nvar band_index;\n\nvar soundFile, play;\n\nfunction preload() {\n soundFormats('mp3', 'ogg');\n soundFile = loadSound('assets/beat');\n}\n\nfunction setup() {\n eq = new p5.EQ(3);\n soundFile.disconnect();\n eq.process(soundFile);\n\n band_names = ['lows','mids','highs'];\n band_index = 0;\n play = false;\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(30);\n noStroke();\n fill(255);\n text('click to kill',50,25);\n\n fill(255, 40, 255);\n textSize(26);\n text(band_names[band_index],50,55);\n\n fill(255);\n textSize(9);\n text('space = play/pause',50,80);\n}\n\n//If mouse is over canvas, cycle to the next band and kill the frequency\nfunction mouseClicked() {\n for (var i = 0; i < eq.bands.length; i++) {\n eq.bands[i].gain(0);\n }\n eq.bands[band_index].gain(-40);\n if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {\n band_index === 2 ? band_index = 0 : band_index++;\n }\n}\n\n//use space bar to trigger play / pause\nfunction keyPressed() {\n if (key===' ') {\n play = !play\n play ? soundFile.loop() : soundFile.pause();\n }\n}\n
"
+ ]
+ },
+ "p5.Panner3D": {
+ "name": "p5.Panner3D",
+ "shortname": "p5.Panner3D",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 8619,
+ "description": "Panner3D is based on the \nWeb Audio Spatial Panner Node.\nThis panner is a spatial processing node that allows audio to be positioned\nand oriented in 3D space.
\nThe position is relative to an \nAudio Context Listener, which can be accessed\nby p5.soundOut.audiocontext.listener
\n",
+ "is_constructor": 1
+ },
+ "p5.Delay": {
+ "name": "p5.Delay",
+ "shortname": "p5.Delay",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 9068,
+ "description": "Delay is an echo effect. It processes an existing sound source,\nand outputs a delayed version of that sound. The p5.Delay can\nproduce different effects depending on the delayTime, feedback,\nfilter, and type. In the example below, a feedback of 0.5 (the\ndefaul value) will produce a looping delay that decreases in\nvolume by 50% each repeat. A filter will cut out the high\nfrequencies so that the delay does not sound as piercing as the\noriginal source.
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n",
+ "extends": "p5.Effect",
+ "is_constructor": 1,
+ "example": [
+ "\n\nvar noise, env, delay;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n noise = new p5.Noise('brown');\n noise.amp(0);\n noise.start();\n\n delay = new p5.Delay();\n\n // delay.process() accepts 4 parameters:\n // source, delayTime, feedback, filter frequency\n // play with these numbers!!\n delay.process(noise, .12, .7, 2300);\n\n // play the noise with an envelope,\n // a series of fades ( time / value pairs )\n env = new p5.Env(.01, 0.2, .2, .1);\n}\n\n// mouseClick triggers envelope\nfunction mouseClicked() {\n // is mouse over canvas?\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n env.play(noise);\n }\n}\n
"
+ ]
+ },
+ "p5.Reverb": {
+ "name": "p5.Reverb",
+ "shortname": "p5.Reverb",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 9345,
+ "description": "Reverb adds depth to a sound through a large number of decaying\nechoes. It creates the perception that sound is occurring in a\nphysical space. The p5.Reverb has paramters for Time (how long does the\nreverb last) and decayRate (how much the sound decays with each echo)\nthat can be set with the .set() or .process() methods. The p5.Convolver\nextends p5.Reverb allowing you to recreate the sound of actual physical\nspaces through convolution.
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n",
+ "extends": "p5.Effect",
+ "is_constructor": 1,
+ "example": [
+ "\n\nvar soundFile, reverb;\nfunction preload() {\n soundFile = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n reverb = new p5.Reverb();\n soundFile.disconnect(); // so we'll only hear reverb...\n\n // connect soundFile to reverb, process w/\n // 3 second reverbTime, decayRate of 2%\n reverb.process(soundFile, 3, 2);\n soundFile.play();\n}\n
"
+ ]
+ },
+ "p5.Convolver": {
+ "name": "p5.Convolver",
+ "shortname": "p5.Convolver",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 9505,
+ "description": "p5.Convolver extends p5.Reverb. It can emulate the sound of real\nphysical spaces through a process called \nconvolution.
\n\nConvolution multiplies any audio input by an "impulse response"\nto simulate the dispersion of sound over time. The impulse response is\ngenerated from an audio file that you provide. One way to\ngenerate an impulse response is to pop a balloon in a reverberant space\nand record the echo. Convolution can also be used to experiment with\nsound.
\n\nUse the method createConvolution(path) to instantiate a\np5.Convolver with a path to your impulse response audio file.
",
+ "extends": "p5.Effect",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "path",
+ "description": "path to a sound file
\n",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "function to call when loading succeeds
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "function to call if loading fails.\n This function will receive an error or\n XMLHttpRequest object with information\n about what went wrong.
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nvar cVerb, sound;\nfunction preload() {\n // We have both MP3 and OGG versions of all sound assets\n soundFormats('ogg', 'mp3');\n\n // Try replacing 'bx-spring' with other soundfiles like\n // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'\n cVerb = createConvolver('assets/bx-spring.mp3');\n\n // Try replacing 'Damscray_DancingTiger' with\n // 'beat', 'doorbell', lucky_dragons'\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\n
"
+ ]
+ },
+ "p5.Phrase": {
+ "name": "p5.Phrase",
+ "shortname": "p5.Phrase",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 10057,
+ "description": "A phrase is a pattern of musical events over time, i.e.\na series of notes and rests.
\n\nPhrases must be added to a p5.Part for playback, and\neach part can play multiple phrases at the same time.\nFor example, one Phrase might be a kick drum, another\ncould be a snare, and another could be the bassline.
\n\nThe first parameter is a name so that the phrase can be\nmodified or deleted later. The callback is a a function that\nthis phrase will call at every step—for example it might be\ncalled playNote(value){}. The array determines\nwhich value is passed into the callback at each step of the\nphrase. It can be numbers, an object with multiple numbers,\nor a zero (0) indicates a rest so the callback won't be called).
",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "name",
+ "description": "Name so that you can access the Phrase.
\n",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "The name of a function that this phrase\n will call. Typically it will play a sound,\n and accept two parameters: a time at which\n to play the sound (in seconds from now),\n and a value from the sequence array. The\n time should be passed into the play() or\n start() method to ensure precision.
\n",
+ "type": "Function"
+ },
+ {
+ "name": "sequence",
+ "description": "Array of values to pass into the callback\n at each step of the phrase.
\n",
+ "type": "Array"
+ }
+ ],
+ "example": [
+ "\n\nvar mySound, myPhrase, myPart;\nvar pattern = [1,0,0,2,0,2,0,0];\nvar msg = 'click to play';\n\nfunction preload() {\n mySound = loadSound('assets/beatbox.mp3');\n}\n\nfunction setup() {\n noStroke();\n fill(255);\n textAlign(CENTER);\n masterVolume(0.1);\n\n myPhrase = new p5.Phrase('bbox', makeSound, pattern);\n myPart = new p5.Part();\n myPart.addPhrase(myPhrase);\n myPart.setBPM(60);\n}\n\nfunction draw() {\n background(0);\n text(msg, width/2, height/2);\n}\n\nfunction makeSound(time, playbackRate) {\n mySound.rate(playbackRate);\n mySound.play(time);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n myPart.start();\n msg = 'playing pattern';\n }\n}\n\n
"
+ ]
+ },
+ "p5.Part": {
+ "name": "p5.Part",
+ "shortname": "p5.Part",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 10142,
+ "description": "A p5.Part plays back one or more p5.Phrases. Instantiate a part\nwith steps and tatums. By default, each step represents 1/16th note.
\n\nSee p5.Phrase for more about musical timing.
",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "steps",
+ "description": "Steps in the part
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "tatums",
+ "description": "Divisions of a beat (default is 1/16, a quarter note)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nvar box, drum, myPart;\nvar boxPat = [1,0,0,2,0,2,0,0];\nvar drumPat = [0,1,1,0,2,0,1,0];\nvar msg = 'click to play';\n\nfunction preload() {\n box = loadSound('assets/beatbox.mp3');\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n noStroke();\n fill(255);\n textAlign(CENTER);\n masterVolume(0.1);\n\n var boxPhrase = new p5.Phrase('box', playBox, boxPat);\n var drumPhrase = new p5.Phrase('drum', playDrum, drumPat);\n myPart = new p5.Part();\n myPart.addPhrase(boxPhrase);\n myPart.addPhrase(drumPhrase);\n myPart.setBPM(60);\n masterVolume(0.1);\n}\n\nfunction draw() {\n background(0);\n text(msg, width/2, height/2);\n}\n\nfunction playBox(time, playbackRate) {\n box.rate(playbackRate);\n box.play(time);\n}\n\nfunction playDrum(time, playbackRate) {\n drum.rate(playbackRate);\n drum.play(time);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n myPart.start();\n msg = 'playing part';\n }\n}\n
"
+ ]
+ },
+ "p5.Score": {
+ "name": "p5.Score",
+ "shortname": "p5.Score",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 10396,
+ "description": "A Score consists of a series of Parts. The parts will\nbe played back in order. For example, you could have an\nA part, a B part, and a C part, and play them back in this order\nnew p5.Score(a, a, b, a, c)
\n",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "parts",
+ "description": "One or multiple parts, to be played in sequence.
\n",
+ "type": "p5.Part",
+ "optional": true,
+ "multiple": true
+ }
+ ]
+ },
+ "p5.SoundLoop": {
+ "name": "p5.SoundLoop",
+ "shortname": "p5.SoundLoop",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 10527,
+ "description": "SoundLoop
\n",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "callback",
+ "description": "this function will be called on each iteration of theloop
\n",
+ "type": "Function"
+ },
+ {
+ "name": "interval",
+ "description": "amount of time or beats for each iteration of the loop\n defaults to 1
\n",
+ "type": "Number|String",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nvar click;\nvar looper1;\n\nfunction preload() {\n click = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n //the looper's callback is passed the timeFromNow\n //this value should be used as a reference point from\n //which to schedule sounds\n looper1 = new p5.SoundLoop(function(timeFromNow){\n click.play(timeFromNow);\n background(255 * (looper1.iterations % 2));\n }, 2);\n\n //stop after 10 iteratios;\n looper1.maxIterations = 10;\n //start the loop\n looper1.start();\n}\n
"
+ ]
+ },
+ "p5.Compressor": {
+ "name": "p5.Compressor",
+ "shortname": "p5.Compressor",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 10786,
+ "description": "Compressor is an audio effect class that performs dynamics compression\non an audio input source. This is a very commonly used technique in music\nand sound production. Compression creates an overall louder, richer,\nand fuller sound by lowering the volume of louds and raising that of softs.\nCompression can be used to avoid clipping (sound distortion due to\npeaks in volume) and is especially useful when many sounds are played\nat once. Compression can be used on indivudal sound sources in addition\nto the master output.
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n",
+ "is_constructor": 1,
+ "extends": "p5.Effect"
+ },
+ "p5.SoundRecorder": {
+ "name": "p5.SoundRecorder",
+ "shortname": "p5.SoundRecorder",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 10994,
+ "description": "Record sounds for playback and/or to save as a .wav file.\nThe p5.SoundRecorder records all sound output from your sketch,\nor can be assigned a specific source with setInput().
\nThe record() method accepts a p5.SoundFile as a parameter.\nWhen playback is stopped (either after the given amount of time,\nor with the stop() method), the p5.SoundRecorder will send its\nrecording to that p5.SoundFile for playback.
",
+ "is_constructor": 1,
+ "example": [
+ "\n\nvar mic, recorder, soundFile;\nvar state = 0;\n\nfunction setup() {\n background(200);\n // create an audio in\n mic = new p5.AudioIn();\n\n // prompts user to enable their browser mic\n mic.start();\n\n // create a sound recorder\n recorder = new p5.SoundRecorder();\n\n // connect the mic to the recorder\n recorder.setInput(mic);\n\n // this sound file will be used to\n // playback & save the recording\n soundFile = new p5.SoundFile();\n\n text('keyPress to record', 20, 20);\n}\n\nfunction keyPressed() {\n // make sure user enabled the mic\n if (state === 0 && mic.enabled) {\n\n // record to our p5.SoundFile\n recorder.record(soundFile);\n\n background(255,0,0);\n text('Recording!', 20, 20);\n state++;\n }\n else if (state === 1) {\n background(0,255,0);\n\n // stop recorder and\n // send result to soundFile\n recorder.stop();\n\n text('Stopped', 20, 20);\n state++;\n }\n\n else if (state === 2) {\n soundFile.play(); // play the result!\n save(soundFile, 'mySound.wav');\n state++;\n }\n}\n
"
+ ]
+ },
+ "p5.PeakDetect": {
+ "name": "p5.PeakDetect",
+ "shortname": "p5.PeakDetect",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 11283,
+ "description": "PeakDetect works in conjunction with p5.FFT to\nlook for onsets in some or all of the frequency spectrum.\n
\n\nTo use p5.PeakDetect, call update in the draw loop\nand pass in a p5.FFT object.\n
\n\nYou can listen for a specific part of the frequency spectrum by\nsetting the range between freq1 and freq2.\n
\n\nthreshold is the threshold for detecting a peak,\nscaled between 0 and 1. It is logarithmic, so 0.1 is half as loud\nas 1.0.
\n\n\nThe update method is meant to be run in the draw loop, and\nframes determines how many loops must pass before\nanother peak can be detected.\nFor example, if the frameRate() = 60, you could detect the beat of a\n120 beat-per-minute song with this equation:\n framesPerPeak = 60 / (estimatedBPM / 60 );\n
\n\n\nBased on example contribtued by @b2renger, and a simple beat detection\nexplanation by a\nhref="http://www.airtightinteractive.com/2013/10/making-audio-reactive-visuals/"\ntarget="_blank"Felix Turner.\n
",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "freq1",
+ "description": "lowFrequency - defaults to 20Hz
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "freq2",
+ "description": "highFrequency - defaults to 20000 Hz
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "threshold",
+ "description": "Threshold for detecting a beat between 0 and 1\n scaled logarithmically where 0.1 is 1/2 the loudness\n of 1.0. Defaults to 0.35.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "framesPerPeak",
+ "description": "Defaults to 20.
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\n\nvar cnv, soundFile, fft, peakDetect;\nvar ellipseWidth = 10;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n\n soundFile = loadSound('assets/beat.mp3');\n\n // p5.PeakDetect requires a p5.FFT\n fft = new p5.FFT();\n peakDetect = new p5.PeakDetect();\n\n}\n\nfunction draw() {\n background(0);\n text('click to play/pause', width/2, height/2);\n\n // peakDetect accepts an fft post-analysis\n fft.analyze();\n peakDetect.update(fft);\n\n if ( peakDetect.isDetected ) {\n ellipseWidth = 50;\n } else {\n ellipseWidth *= 0.95;\n }\n\n ellipse(width/2, height/2, ellipseWidth, ellipseWidth);\n}\n\n// toggle play/stop when canvas is clicked\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n if (soundFile.isPlaying() ) {\n soundFile.stop();\n } else {\n soundFile.play();\n }\n }\n}\n
"
+ ]
+ },
+ "p5.Gain": {
+ "name": "p5.Gain",
+ "shortname": "p5.Gain",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 11503,
+ "description": "A gain node is usefull to set the relative volume of sound.\nIt's typically used to build mixers.
\n",
+ "is_constructor": 1,
+ "example": [
+ "\n\n\n // load two soundfile and crossfade beetween them\n var sound1,sound2;\n var gain1, gain2, gain3;\n\n function preload(){\n soundFormats('ogg', 'mp3');\n sound1 = loadSound('../_files/Damscray_01');\n sound2 = loadSound('../_files/beat.mp3');\n }\n\n function setup() {\n createCanvas(400,200);\n\n // create a 'master' gain to which we will connect both soundfiles\n gain3 = new p5.Gain();\n gain3.connect();\n\n // setup first sound for playing\n sound1.rate(1);\n sound1.loop();\n sound1.disconnect(); // diconnect from p5 output\n\n gain1 = new p5.Gain(); // setup a gain node\n gain1.setInput(sound1); // connect the first sound to its input\n gain1.connect(gain3); // connect its output to the 'master'\n\n sound2.rate(1);\n sound2.disconnect();\n sound2.loop();\n\n gain2 = new p5.Gain();\n gain2.setInput(sound2);\n gain2.connect(gain3);\n\n }\n\n function draw(){\n background(180);\n\n // calculate the horizontal distance beetween the mouse and the right of the screen\n var d = dist(mouseX,0,width,0);\n\n // map the horizontal position of the mouse to values useable for volume control of sound1\n var vol1 = map(mouseX,0,width,0,1);\n var vol2 = 1-vol1; // when sound1 is loud, sound2 is quiet and vice versa\n\n gain1.amp(vol1,0.5,0);\n gain2.amp(vol2,0.5,0);\n\n // map the vertical position of the mouse to values useable for 'master volume control'\n var vol3 = map(mouseY,0,height,0,1);\n gain3.amp(vol3,0.5,0);\n }\n
\n"
+ ]
+ },
+ "p5.AudioVoice": {
+ "name": "p5.AudioVoice",
+ "shortname": "p5.AudioVoice",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 11638,
+ "description": "Base class for monophonic synthesizers. Any extensions of this class\nshould follow the API and implement the methods below in order to\nremain compatible with p5.PolySynth();
\n",
+ "is_constructor": 1
+ },
+ "p5.MonoSynth": {
+ "name": "p5.MonoSynth",
+ "shortname": "p5.MonoSynth",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 11711,
+ "description": "An MonoSynth is used as a single voice for sound synthesis.\nThis is a class to be used in conjonction with the PolySynth\nclass. Custom synthetisers should be built inheriting from\nthis class.
\n",
+ "is_constructor": 1,
+ "example": [
+ "\n\nvar monosynth;\nvar x;\n\nfunction setup() {\n monosynth = new p5.MonoSynth();\n monosynth.loadPreset('simpleBass');\n monosynth.play(45,1,x=0,1);\n monosynth.play(49,1,x+=1,0.25);\n monosynth.play(50,1,x+=0.25,0.25);\n monosynth.play(49,1,x+=0.5,0.25);\n monosynth.play(50,1,x+=0.25,0.25);\n}\n
"
+ ]
+ },
+ "p5.PolySynth": {
+ "name": "p5.PolySynth",
+ "shortname": "p5.PolySynth",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 11943,
+ "description": "An AudioVoice is used as a single voice for sound synthesis.\nThe PolySynth class holds an array of AudioVoice, and deals\nwith voices allocations, with setting notes to be played, and\nparameters to be set.
\n",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "synthVoice",
+ "description": "A monophonic synth voice inheriting\n the AudioVoice class. Defaults to p5.MonoSynth
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "polyValue",
+ "description": "Number of voices, defaults to 8;
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nvar polysynth;\nfunction setup() {\n polysynth = new p5.PolySynth();\n polysynth.play(53,1,0,3);\n polysynth.play(60,1,0,2.9);\n polysynth.play(69,1,0,3);\n polysynth.play(71,1,0,3);\n polysynth.play(74,1,0,3);\n}\n
\n"
+ ]
+ },
+ "p5.Distortion": {
+ "name": "p5.Distortion",
+ "shortname": "p5.Distortion",
+ "classitems": [],
+ "plugins": [],
+ "extensions": [],
+ "plugin_for": [],
+ "extension_for": [],
+ "module": "p5.sound",
+ "submodule": "p5.sound",
+ "namespace": "",
+ "file": "lib/addons/p5.sound.js",
+ "line": 12243,
+ "description": "A Distortion effect created with a Waveshaper Node,\nwith an approach adapted from\nKevin Ennis
\nThis class extends p5.Effect.\nMethods amp(), chain(),\ndrywet(), connect(), and\ndisconnect() are available.
\n",
+ "extends": "p5.Effect",
+ "is_constructor": 1,
+ "params": [
+ {
+ "name": "amount",
+ "description": "Unbounded distortion amount.\n Normal values range from 0-1.
\n",
+ "type": "Number",
+ "optional": true,
+ "optdefault": "0.25"
+ },
+ {
+ "name": "oversample",
+ "description": "'none', '2x', or '4x'.
\n",
+ "type": "String",
+ "optional": true,
+ "optdefault": "'none'"
+ }
+ ]
+ }
+ },
+ "elements": {},
+ "classitems": [
+ {
+ "file": "src/color/color_conversion.js",
+ "line": 10,
+ "description": "Conversions adapted from http://www.easyrgb.com/en/math.php.
\nIn these functions, hue is always in the range [0,1); all other components\nare in the range [0,1]. 'Brightness' and 'value' are used interchangeably.
\n",
+ "class": "p5",
+ "module": "Conversion",
+ "submodule": "Color Conversion"
+ },
+ {
+ "file": "src/color/color_conversion.js",
+ "line": 20,
+ "description": "Convert an HSBA array to HSLA.
\n",
+ "class": "p5",
+ "module": "Conversion",
+ "submodule": "Color Conversion"
+ },
+ {
+ "file": "src/color/color_conversion.js",
+ "line": 46,
+ "description": "Convert an HSBA array to RGBA.
\n",
+ "class": "p5",
+ "module": "Conversion",
+ "submodule": "Color Conversion"
+ },
+ {
+ "file": "src/color/color_conversion.js",
+ "line": 101,
+ "description": "Convert an HSLA array to HSBA.
\n",
+ "class": "p5",
+ "module": "Conversion",
+ "submodule": "Color Conversion"
+ },
+ {
+ "file": "src/color/color_conversion.js",
+ "line": 124,
+ "description": "Convert an HSLA array to RGBA.
\nWe need to change basis from HSLA to something that can be more easily be\nprojected onto RGBA. We will choose hue and brightness as our first two\ncomponents, and pick a convenient third one ('zest') so that we don't need\nto calculate formal HSBA saturation.
\n",
+ "class": "p5",
+ "module": "Conversion",
+ "submodule": "Color Conversion"
+ },
+ {
+ "file": "src/color/color_conversion.js",
+ "line": 188,
+ "description": "Convert an RGBA array to HSBA.
\n",
+ "class": "p5",
+ "module": "Conversion",
+ "submodule": "Color Conversion"
+ },
+ {
+ "file": "src/color/color_conversion.js",
+ "line": 227,
+ "description": "Convert an RGBA array to HSLA.
\n",
+ "class": "p5",
+ "module": "Conversion",
+ "submodule": "Color Conversion"
+ },
+ {
+ "file": "src/color/creating_reading.js",
+ "line": 16,
+ "description": "Extracts the alpha value from a color or pixel array.
\n",
+ "itemtype": "method",
+ "name": "alpha",
+ "params": [
+ {
+ "name": "color",
+ "description": "p5.Color object, color components,\n or CSS color
\n",
+ "type": "p5.Color|Number[]|String"
+ }
+ ],
+ "return": {
+ "description": "the alpha value",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nnoStroke();\nvar c = color(0, 126, 255, 102);\nfill(c);\nrect(15, 15, 35, 70);\nvar value = alpha(c); // Sets 'value' to 102\nfill(value);\nrect(50, 15, 35, 70);\n\n
"
+ ],
+ "alt": "Left half of canvas light blue and right half light charcoal grey.\nLeft half of canvas light purple and right half a royal blue.\nLeft half of canvas salmon pink and the right half white.\nYellow rect in middle right of canvas, with 55 pixel width and height.\nYellow ellipse in top left canvas, black ellipse in bottom right,both 80x80.\nBright fuschia rect in middle of canvas, 60 pixel width and height.\nTwo bright green rects on opposite sides of the canvas, both 45x80.\nFour blue rects in each corner of the canvas, each are 35x35.\nBright sea green rect on left and darker rect on right of canvas, both 45x80.\nDark green rect on left and light green rect on right of canvas, both 45x80.\nDark blue rect on left and light teal rect on right of canvas, both 45x80.\nblue rect on left and green on right, both with black outlines & 35x60.\nsalmon pink rect on left and black on right, both 35x60.\n4 rects, tan, brown, brownish purple and purple, with white outlines & 20x60.\nlight pastel green rect on left and dark grey rect on right, both 35x60.\nyellow rect on left and red rect on right, both with black outlines & 35x60.\ngrey canvas\ndeep pink rect on left and grey rect on right, both 35x60.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/creating_reading.js",
+ "line": 61,
+ "description": "Extracts the blue value from a color or pixel array.
\n",
+ "itemtype": "method",
+ "name": "blue",
+ "params": [
+ {
+ "name": "color",
+ "description": "p5.Color object, color components,\n or CSS color
\n",
+ "type": "p5.Color|Number[]|String"
+ }
+ ],
+ "return": {
+ "description": "the blue value",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar c = color(175, 100, 220); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nvar blueValue = blue(c); // Get blue in 'c'\nprint(blueValue); // Prints \"220.0\"\nfill(0, 0, blueValue); // Use 'blueValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
"
+ ],
+ "alt": "Left half of canvas light purple and right half a royal blue.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/creating_reading.js",
+ "line": 91,
+ "description": "Extracts the HSB brightness value from a color or pixel array.
\n",
+ "itemtype": "method",
+ "name": "brightness",
+ "params": [
+ {
+ "name": "color",
+ "description": "p5.Color object, color components,\n or CSS color
\n",
+ "type": "p5.Color|Number[]|String"
+ }
+ ],
+ "return": {
+ "description": "the brightness value",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = brightness(c); // Sets 'value' to 255\nfill(value);\nrect(50, 20, 35, 60);\n\n
"
+ ],
+ "alt": "Left half of canvas salmon pink and the right half white.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/creating_reading.js",
+ "line": 121,
+ "description": "Creates colors for storing in variables of the color datatype. The\nparameters are interpreted as RGB or HSB values depending on the\ncurrent colorMode(). The default mode is RGB values from 0 to 255\nand, therefore, the function call color(255, 204, 0) will return a\nbright yellow color.\n
\nNote that if only one value is provided to color(), it will be interpreted\nas a grayscale value. Add a second value, and it will be used for alpha\ntransparency. When three values are specified, they are interpreted as\neither RGB or HSB values. Adding a fourth value applies alpha\ntransparency.\n
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.
\n",
+ "itemtype": "method",
+ "name": "color",
+ "return": {
+ "description": "resulting color",
+ "type": "p5.Color"
+ },
+ "example": [
+ "\n\n\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nrect(30, 20, 55, 55); // Draw rectangle\n\n
\n\n\n\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nellipse(25, 25, 80, 80); // Draw left circle\n\n// Using only one value with color()\n// generates a grayscale value.\nc = color(65); // Update 'c' with grayscale value\nfill(c); // Use updated 'c' as fill color\nellipse(75, 75, 80, 80); // Draw right circle\n\n
\n\n\n\n// Named SVG & CSS colors may be used,\nvar c = color('magenta');\nfill(c); // Use 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nrect(20, 20, 60, 60); // Draw rectangle\n\n
\n\n\n\n// as can hex color codes:\nnoStroke(); // Don't draw a stroke around shapes\nvar c = color('#0f0');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('#00ff00');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n\n
\n\n\n\n// RGB and RGBA color strings are also supported:\n// these all set to the same color (solid blue)\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('rgb(0,0,255)');\nfill(c); // Use 'c' as fill color\nrect(10, 10, 35, 35); // Draw rectangle\n\nc = color('rgb(0%, 0%, 100%)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 35, 35); // Draw rectangle\n\nc = color('rgba(0, 0, 255, 1)');\nfill(c); // Use updated 'c' as fill color\nrect(10, 55, 35, 35); // Draw rectangle\n\nc = color('rgba(0%, 0%, 100%, 1)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 55, 35, 35); // Draw rectangle\n\n
\n\n\n\n// HSL color is also supported and can be specified\n// by value\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('hsl(160, 100%, 50%)');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('hsla(160, 100%, 50%, 0.5)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n\n
\n\n\n\n// HSB color is also supported and can be specified\n// by value\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('hsb(160, 100%, 50%)');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('hsba(160, 100%, 50%, 0.5)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n\n
\n\n\n\nvar c; // Declare color 'c'\nnoStroke(); // Don't draw a stroke around shapes\n\n// If no colorMode is specified, then the\n// default of RGB with scale of 0-255 is used.\nc = color(50, 55, 100); // Create a color for 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(0, 10, 45, 80); // Draw left rect\n\ncolorMode(HSB, 100); // Use HSB with scale of 0-100\nc = color(50, 55, 100); // Update 'c' with new color\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw right rect\n\n
"
+ ],
+ "alt": "Yellow rect in middle right of canvas, with 55 pixel width and height.\nYellow ellipse in top left of canvas, black ellipse in bottom right,both 80x80.\nBright fuschia rect in middle of canvas, 60 pixel width and height.\nTwo bright green rects on opposite sides of the canvas, both 45x80.\nFour blue rects in each corner of the canvas, each are 35x35.\nBright sea green rect on left and darker rect on right of canvas, both 45x80.\nDark green rect on left and lighter green rect on right of canvas, both 45x80.\nDark blue rect on left and light teal rect on right of canvas, both 45x80.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Creating & Reading",
+ "overloads": [
+ {
+ "line": 121,
+ "params": [
+ {
+ "name": "gray",
+ "description": "number specifying value between white\n and black.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "alpha",
+ "description": "alpha value relative to current color range\n (default is 0-255)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "resulting color",
+ "type": "p5.Color"
+ }
+ },
+ {
+ "line": 280,
+ "params": [
+ {
+ "name": "v1",
+ "description": "red or hue value relative to\n the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "green or saturation value\n relative to the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v3",
+ "description": "blue or brightness value\n relative to the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "alpha",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.Color"
+ }
+ },
+ {
+ "line": 292,
+ "params": [
+ {
+ "name": "value",
+ "description": "a color string
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.Color"
+ }
+ },
+ {
+ "line": 297,
+ "params": [
+ {
+ "name": "values",
+ "description": "an array containing the red,green,blue &\n and alpha components of the color
\n",
+ "type": "Number[]"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.Color"
+ }
+ },
+ {
+ "line": 303,
+ "params": [
+ {
+ "name": "color",
+ "description": "",
+ "type": "p5.Color"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.Color"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/color/creating_reading.js",
+ "line": 319,
+ "description": "Extracts the green value from a color or pixel array.
\n",
+ "itemtype": "method",
+ "name": "green",
+ "params": [
+ {
+ "name": "color",
+ "description": "p5.Color object, color components,\n or CSS color
\n",
+ "type": "p5.Color|Number[]|String"
+ }
+ ],
+ "return": {
+ "description": "the green value",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar c = color(20, 75, 200); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nvar greenValue = green(c); // Get green in 'c'\nprint(greenValue); // Print \"75.0\"\nfill(0, greenValue, 0); // Use 'greenValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
"
+ ],
+ "alt": "blue rect on left and green on right, both with black outlines & 35x60.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/creating_reading.js",
+ "line": 350,
+ "description": "Extracts the hue value from a color or pixel array.
\nHue exists in both HSB and HSL. This function will return the\nHSB-normalized hue when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL-normalized hue otherwise. (The values will only be different if the\nmaximum hue setting for each system is different.)
\n",
+ "itemtype": "method",
+ "name": "hue",
+ "params": [
+ {
+ "name": "color",
+ "description": "p5.Color object, color components,\n or CSS color
\n",
+ "type": "p5.Color|Number[]|String"
+ }
+ ],
+ "return": {
+ "description": "the hue",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = hue(c); // Sets 'value' to \"0\"\nfill(value);\nrect(50, 20, 35, 60);\n\n
"
+ ],
+ "alt": "salmon pink rect on left and black on right, both 35x60.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/creating_reading.js",
+ "line": 387,
+ "description": "Blends two colors to find a third color somewhere between them. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first color, 0.1 is very near the first color, 0.5 is halfway\nin between, etc. An amount below 0 will be treated as 0. Likewise, amounts\nabove 1 will be capped at 1. This is different from the behavior of lerp(),\nbut necessary because otherwise numbers outside the range will produce\nstrange and unexpected colors.\n
\nThe way that colours are interpolated depends on the current color mode.
\n",
+ "itemtype": "method",
+ "name": "lerpColor",
+ "params": [
+ {
+ "name": "c1",
+ "description": "interpolate from this color
\n",
+ "type": "p5.Color"
+ },
+ {
+ "name": "c2",
+ "description": "interpolate to this color
\n",
+ "type": "p5.Color"
+ },
+ {
+ "name": "amt",
+ "description": "number between 0 and 1
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "interpolated color",
+ "type": "p5.Color"
+ },
+ "example": [
+ "\n\n\ncolorMode(RGB);\nstroke(255);\nbackground(51);\nvar from = color(218, 165, 32);\nvar to = color(72, 61, 139);\ncolorMode(RGB); // Try changing to HSB.\nvar interA = lerpColor(from, to, 0.33);\nvar interB = lerpColor(from, to, 0.66);\nfill(from);\nrect(10, 20, 20, 60);\nfill(interA);\nrect(30, 20, 20, 60);\nfill(interB);\nrect(50, 20, 20, 60);\nfill(to);\nrect(70, 20, 20, 60);\n\n
"
+ ],
+ "alt": "4 rects one tan, brown, brownish purple, purple, with white outlines & 20x60",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/creating_reading.js",
+ "line": 484,
+ "description": "Extracts the HSL lightness value from a color or pixel array.
\n",
+ "itemtype": "method",
+ "name": "lightness",
+ "params": [
+ {
+ "name": "color",
+ "description": "p5.Color object, color components,\n or CSS color
\n",
+ "type": "p5.Color|Number[]|String"
+ }
+ ],
+ "return": {
+ "description": "the lightness",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nnoStroke();\ncolorMode(HSL);\nvar c = color(156, 100, 50, 1);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = lightness(c); // Sets 'value' to 50\nfill(value);\nrect(50, 20, 35, 60);\n\n
"
+ ],
+ "alt": "light pastel green rect on left and dark grey rect on right, both 35x60.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/creating_reading.js",
+ "line": 514,
+ "description": "Extracts the red value from a color or pixel array.
\n",
+ "itemtype": "method",
+ "name": "red",
+ "params": [
+ {
+ "name": "color",
+ "description": "p5.Color object, color components,\n or CSS color
\n",
+ "type": "p5.Color|Number[]|String"
+ }
+ ],
+ "return": {
+ "description": "the red value",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nvar redValue = red(c); // Get red in 'c'\nprint(redValue); // Print \"255.0\"\nfill(redValue, 0, 0); // Use 'redValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n\n
\n\n\n\ncolorMode(RGB, 255);\nvar c = color(127, 255, 0);\ncolorMode(RGB, 1);\nvar myColor = red(c);\nprint(myColor);\n\n
"
+ ],
+ "alt": "yellow rect on left and red rect on right, both with black outlines and 35x60.\ngrey canvas",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/creating_reading.js",
+ "line": 554,
+ "description": "Extracts the saturation value from a color or pixel array.
\nSaturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL saturation otherwise.
\n",
+ "itemtype": "method",
+ "name": "saturation",
+ "params": [
+ {
+ "name": "color",
+ "description": "p5.Color object, color components,\n or CSS color
\n",
+ "type": "p5.Color|Number[]|String"
+ }
+ ],
+ "return": {
+ "description": "the saturation value",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = saturation(c); // Sets 'value' to 126\nfill(value);\nrect(50, 20, 35, 60);\n\n
"
+ ],
+ "alt": "deep pink rect on left and grey rect on right, both 35x60.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/p5.Color.js",
+ "line": 52,
+ "description": "This function returns the color formatted as a string. This can be useful\nfor debugging, or for using p5.js with other libraries.
\n",
+ "itemtype": "method",
+ "name": "toString",
+ "params": [
+ {
+ "name": "format",
+ "description": "How the color string will be formatted.\nLeaving this empty formats the string as rgba(r, g, b, a).\n'#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes.\n'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode.\n'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels.\n'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages.
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "the formatted string",
+ "type": "String"
+ },
+ "example": [
+ "\n\n\nvar myColor;\nfunction setup() {\n createCanvas(200, 200);\n stroke(255);\n myColor = color(100, 100, 250);\n fill(myColor);\n}\n\nfunction draw() {\n text(myColor.toString(), 10, 10);\n text(myColor.toString('#rrggbb'), 10, 95);\n text(myColor.toString('rgba%'), 10, 180);\n}\n\n
"
+ ],
+ "alt": "canvas with text representation of color",
+ "class": "p5.Color",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/p5.Color.js",
+ "line": 247,
+ "itemtype": "method",
+ "name": "setRed",
+ "params": [
+ {
+ "name": "red",
+ "description": "the new red value
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\n\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setRed(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n
"
+ ],
+ "alt": "canvas with gradually changing background color",
+ "class": "p5.Color",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/p5.Color.js",
+ "line": 274,
+ "itemtype": "method",
+ "name": "setGreen",
+ "params": [
+ {
+ "name": "green",
+ "description": "the new green value
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\n\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n
"
+ ],
+ "alt": "canvas with gradually changing background color",
+ "class": "p5.Color",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/p5.Color.js",
+ "line": 301,
+ "itemtype": "method",
+ "name": "setBlue",
+ "params": [
+ {
+ "name": "blue",
+ "description": "the new blue value
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\n\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n\n
"
+ ],
+ "alt": "canvas with gradually changing background color",
+ "class": "p5.Color",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/p5.Color.js",
+ "line": 328,
+ "itemtype": "method",
+ "name": "setAlpha",
+ "params": [
+ {
+ "name": "alpha",
+ "description": "the new alpha value
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\n\nvar squareColor;\n\nfunction setup() {\n ellipseMode(CORNERS);\n strokeWeight(4);\n squareColor = color(100, 50, 150);\n}\n\nfunction draw() {\n background(255);\n\n noFill();\n stroke(0);\n ellipse(10, 10, width - 10, height - 10);\n\n squareColor.setAlpha(128 + 128 * sin(millis() / 1000));\n fill(squareColor);\n noStroke();\n rect(13, 13, width - 26, height - 26);\n}\n\n
"
+ ],
+ "alt": "circle behind a square with gradually changing opacity",
+ "class": "p5.Color",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/p5.Color.js",
+ "line": 406,
+ "description": "Hue is the same in HSB and HSL, but the maximum value may be different.\nThis function will return the HSB-normalized saturation when supplied with\nan HSB color object, but will default to the HSL-normalized saturation\notherwise.
\n",
+ "class": "p5.Color",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/p5.Color.js",
+ "line": 437,
+ "description": "Saturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object, but will default\nto the HSL saturation otherwise.
\n",
+ "class": "p5.Color",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/p5.Color.js",
+ "line": 456,
+ "description": "CSS named colors.
\n",
+ "class": "p5.Color",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/p5.Color.js",
+ "line": 609,
+ "description": "These regular expressions are used to build up the patterns for matching\nviable CSS color strings: fragmenting the regexes in this way increases the\nlegibility and comprehensibility of the code.
\nNote that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency.
\n",
+ "class": "p5.Color",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/p5.Color.js",
+ "line": 622,
+ "description": "Full color string patterns. The capture groups are necessary.
\n",
+ "class": "p5.Color",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/p5.Color.js",
+ "line": 976,
+ "description": "For HSB and HSL, interpret the gray level as a brightness/lightness\nvalue (they are equivalent when chroma is zero). For RGB, normalize the\ngray level according to the blue maximum.
\n",
+ "class": "p5.Color",
+ "module": "Color",
+ "submodule": "Creating & Reading"
+ },
+ {
+ "file": "src/color/setting.js",
+ "line": 15,
+ "description": "The background() function sets the color used for the background of the\np5.js canvas. The default background is light gray. This function is\ntypically used within draw() to clear the display window at the beginning\nof each frame, but it can be used inside setup() to set the background on\nthe first frame of animation or if the background need only be set once.\n
\nThe color is either specified in terms of the RGB, HSB, or HSL color\ndepending on the current colorMode. (The default color space is RGB, with\neach value in the range from 0 to 255). The alpha range by default is also 0 to 255.\n
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color strings\nand all named color strings are supported. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.\n
\nA p5.Color object can also be provided to set the background color.\n
\nA p5.Image can also be provided to set the background image.
\n",
+ "itemtype": "method",
+ "name": "background",
+ "chainable": 1,
+ "example": [
+ "\n\n\n// Grayscale integer value\nbackground(51);\n\n
\n\n\n\n// R, G & B integer values\nbackground(255, 204, 0);\n\n
\n\n\n\n// H, S & B integer values\ncolorMode(HSB);\nbackground(255, 204, 100);\n\n
\n\n\n\n// Named SVG/CSS color string\nbackground('red');\n\n
\n\n\n\n// three-digit hexadecimal RGB notation\nbackground('#fae');\n\n
\n\n\n\n// six-digit hexadecimal RGB notation\nbackground('#222222');\n\n
\n\n\n\n// integer RGB notation\nbackground('rgb(0,255,0)');\n\n
\n\n\n\n// integer RGBA notation\nbackground('rgba(0,255,0, 0.25)');\n\n
\n\n\n\n// percentage RGB notation\nbackground('rgb(100%,0%,10%)');\n\n
\n\n\n\n// percentage RGBA notation\nbackground('rgba(100%,0%,100%,0.5)');\n\n
\n\n\n\n// p5 Color object\nbackground(color(0, 0, 255));\n\n
"
+ ],
+ "alt": "canvas with darkest charcoal grey background.\ncanvas with yellow background.\ncanvas with royal blue background.\ncanvas with red background.\ncanvas with pink background.\ncanvas with black background.\ncanvas with bright green background.\ncanvas with soft green background.\ncanvas with red background.\ncanvas with light purple background.\ncanvas with blue background.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Setting",
+ "overloads": [
+ {
+ "line": 15,
+ "params": [
+ {
+ "name": "color",
+ "description": "any value created by the color() function
\n",
+ "type": "p5.Color"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 131,
+ "params": [
+ {
+ "name": "colorstring",
+ "description": "color string, possible formats include: integer\n rgb() or rgba(), percentage rgb() or rgba(),\n 3-digit hex, 6-digit hex
\n",
+ "type": "String"
+ },
+ {
+ "name": "a",
+ "description": "opacity of the background relative to current\n color range (default is 0-255)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 141,
+ "params": [
+ {
+ "name": "gray",
+ "description": "specifies a value between white and black
\n",
+ "type": "Number"
+ },
+ {
+ "name": "a",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 148,
+ "params": [
+ {
+ "name": "v1",
+ "description": "red or hue value (depending on the current color\n mode)
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "green or saturation value (depending on the current\n color mode)
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v3",
+ "description": "blue or brightness value (depending on the current\n color mode)
\n",
+ "type": "Number"
+ },
+ {
+ "name": "a",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 160,
+ "params": [
+ {
+ "name": "values",
+ "description": "an array containing the red,green,blue &\n and alpha components of the color
\n",
+ "type": "Number[]"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 167,
+ "params": [
+ {
+ "name": "image",
+ "description": "image created with loadImage() or createImage(),\n to set as background\n (must be same size as the sketch window)
\n",
+ "type": "p5.Image"
+ },
+ {
+ "name": "a",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/color/setting.js",
+ "line": 185,
+ "description": "Clears the pixels within a buffer. This function only works on p5.Canvas\nobjects created with the createCanvas() function; it won't work with the\nmain display window. Unlike the main graphics context, pixels in\nadditional graphics areas created with createGraphics() can be entirely\nor partially transparent. This function clears everything to make all of\nthe pixels 100% transparent.
\n",
+ "itemtype": "method",
+ "name": "clear",
+ "chainable": 1,
+ "example": [
+ "\n\n\n// Clear the screen on mouse press.\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n ellipse(mouseX, mouseY, 20, 20);\n}\n\nfunction mousePressed() {\n clear();\n}\n\n
"
+ ],
+ "alt": "20x20 white ellipses are continually drawn at mouse x and y coordinates.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Setting"
+ },
+ {
+ "file": "src/color/setting.js",
+ "line": 223,
+ "description": "colorMode() changes the way p5.js interprets color data. By default, the\nparameters for fill(), stroke(), background(), and color() are defined by\nvalues between 0 and 255 using the RGB color model. This is equivalent to\nsetting colorMode(RGB, 255). Setting colorMode(HSB) lets you use the HSB\nsystem instead. By default, this is colorMode(HSB, 360, 100, 100, 1). You\ncan also use HSL.\n
\nNote: existing color objects remember the mode that they were created in,\nso you can change modes as you like without affecting their appearance.
\n",
+ "itemtype": "method",
+ "name": "colorMode",
+ "chainable": 1,
+ "example": [
+ "\n\n\nnoStroke();\ncolorMode(RGB, 100);\nfor (var i = 0; i < 100; i++) {\n for (var j = 0; j < 100; j++) {\n stroke(i, j, 0);\n point(i, j);\n }\n}\n\n
\n\n\n\nnoStroke();\ncolorMode(HSB, 100);\nfor (var i = 0; i < 100; i++) {\n for (var j = 0; j < 100; j++) {\n stroke(i, j, 100);\n point(i, j);\n }\n}\n\n
\n\n\n\ncolorMode(RGB, 255);\nvar c = color(127, 255, 0);\n\ncolorMode(RGB, 1);\nvar myColor = c._getRed();\ntext(myColor, 10, 10, 80, 80);\n\n
\n\n\n\nnoFill();\ncolorMode(RGB, 255, 255, 255, 1);\nbackground(255);\n\nstrokeWeight(4);\nstroke(255, 0, 10, 0.3);\nellipse(40, 40, 50, 50);\nellipse(50, 50, 40, 40);\n\n
"
+ ],
+ "alt": "Green to red gradient from bottom L to top R. shading originates from top left.\nRainbow gradient from left to right. Brightness increasing to white at top.\nunknown image.\n50x50 ellipse at middle L & 40x40 ellipse at center. Transluscent pink outlines.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Setting",
+ "overloads": [
+ {
+ "line": 223,
+ "params": [
+ {
+ "name": "mode",
+ "description": "either RGB, HSB or HSL, corresponding to\n Red/Green/Blue and Hue/Saturation/Brightness\n (or Lightness)
\n",
+ "type": "Constant"
+ },
+ {
+ "name": "max",
+ "description": "range for all values
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 300,
+ "params": [
+ {
+ "name": "mode",
+ "description": "",
+ "type": "Constant"
+ },
+ {
+ "name": "max1",
+ "description": "range for the red or hue depending on the\n current color mode
\n",
+ "type": "Number"
+ },
+ {
+ "name": "max2",
+ "description": "range for the green or saturation depending\n on the current color mode
\n",
+ "type": "Number"
+ },
+ {
+ "name": "max3",
+ "description": "range for the blue or brightness/lighntess\n depending on the current color mode
\n",
+ "type": "Number"
+ },
+ {
+ "name": "maxA",
+ "description": "range for the alpha
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/color/setting.js",
+ "line": 344,
+ "description": "Sets the color used to fill shapes. For example, if you run\nfill(204, 102, 0), all subsequent shapes will be filled with orange. This\ncolor is either specified in terms of the RGB or HSB color depending on\nthe current colorMode(). (The default color space is RGB, with each value\nin the range from 0 to 255). The alpha range by default is also 0 to 255.\n
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color strings\nand all named color strings are supported. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.\n
\nA p5 Color object can also be provided to set the fill color.
\n",
+ "itemtype": "method",
+ "name": "fill",
+ "chainable": 1,
+ "example": [
+ "\n\n\n// Grayscale integer value\nfill(51);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// R, G & B integer values\nfill(255, 204, 0);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// H, S & B integer values\ncolorMode(HSB);\nfill(255, 204, 100);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// Named SVG/CSS color string\nfill('red');\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// three-digit hexadecimal RGB notation\nfill('#fae');\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// six-digit hexadecimal RGB notation\nfill('#222222');\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// integer RGB notation\nfill('rgb(0,255,0)');\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// integer RGBA notation\nfill('rgba(0,255,0, 0.25)');\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// percentage RGB notation\nfill('rgb(100%,0%,10%)');\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// percentage RGBA notation\nfill('rgba(100%,0%,100%,0.5)');\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// p5 Color object\nfill(color(0, 0, 255));\nrect(20, 20, 60, 60);\n\n
"
+ ],
+ "alt": "60x60 dark charcoal grey rect with black outline in center of canvas.\n60x60 yellow rect with black outline in center of canvas.\n60x60 royal blue rect with black outline in center of canvas.\n60x60 red rect with black outline in center of canvas.\n60x60 pink rect with black outline in center of canvas.\n60x60 black rect with black outline in center of canvas.\n60x60 light green rect with black outline in center of canvas.\n60x60 soft green rect with black outline in center of canvas.\n60x60 red rect with black outline in center of canvas.\n60x60 dark fushcia rect with black outline in center of canvas.\n60x60 blue rect with black outline in center of canvas.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Setting",
+ "overloads": [
+ {
+ "line": 344,
+ "params": [
+ {
+ "name": "v1",
+ "description": "red or hue value relative to\n the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "green or saturation value\n relative to the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v3",
+ "description": "blue or brightness value\n relative to the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "alpha",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 469,
+ "params": [
+ {
+ "name": "value",
+ "description": "a color string
\n",
+ "type": "String"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 475,
+ "params": [
+ {
+ "name": "gray",
+ "description": "a gray value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "alpha",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 482,
+ "params": [
+ {
+ "name": "values",
+ "description": "an array containing the red,green,blue &\n and alpha components of the color
\n",
+ "type": "Number[]"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 489,
+ "params": [
+ {
+ "name": "color",
+ "description": "the fill color
\n",
+ "type": "p5.Color"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/color/setting.js",
+ "line": 501,
+ "description": "Disables filling geometry. If both noStroke() and noFill() are called,\nnothing will be drawn to the screen.
\n",
+ "itemtype": "method",
+ "name": "noFill",
+ "chainable": 1,
+ "example": [
+ "\n\n\nrect(15, 10, 55, 55);\nnoFill();\nrect(20, 20, 60, 60);\n\n
\n\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n noFill();\n stroke(100, 100, 240);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(45, 45, 45);\n}\n\n
"
+ ],
+ "alt": "white rect top middle and noFill rect center. Both 60x60 with black outlines.\nblack canvas with purple cube wireframe spinning",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Setting"
+ },
+ {
+ "file": "src/color/setting.js",
+ "line": 542,
+ "description": "Disables drawing the stroke (outline). If both noStroke() and noFill()\nare called, nothing will be drawn to the screen.
\n",
+ "itemtype": "method",
+ "name": "noStroke",
+ "chainable": 1,
+ "example": [
+ "\n\n\nnoStroke();\nrect(20, 20, 60, 60);\n\n
\n\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n noStroke();\n fill(240, 150, 150);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(45, 45, 45);\n}\n\n
"
+ ],
+ "alt": "60x60 white rect at center. no outline.\nblack canvas with pink cube spinning",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Setting"
+ },
+ {
+ "file": "src/color/setting.js",
+ "line": 582,
+ "description": "Sets the color used to draw lines and borders around shapes. This color\nis either specified in terms of the RGB or HSB color depending on the\ncurrent colorMode() (the default color space is RGB, with each value in\nthe range from 0 to 255). The alpha range by default is also 0 to 255.\n
\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.\n
\nA p5 Color object can also be provided to set the stroke color.
\n",
+ "itemtype": "method",
+ "name": "stroke",
+ "chainable": 1,
+ "example": [
+ "\n\n\n// Grayscale integer value\nstrokeWeight(4);\nstroke(51);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// R, G & B integer values\nstroke(255, 204, 0);\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// H, S & B integer values\ncolorMode(HSB);\nstrokeWeight(4);\nstroke(255, 204, 100);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// Named SVG/CSS color string\nstroke('red');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// three-digit hexadecimal RGB notation\nstroke('#fae');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// six-digit hexadecimal RGB notation\nstroke('#222222');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// integer RGB notation\nstroke('rgb(0,255,0)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// integer RGBA notation\nstroke('rgba(0,255,0,0.25)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// percentage RGB notation\nstroke('rgb(100%,0%,10%)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// percentage RGBA notation\nstroke('rgba(100%,0%,100%,0.5)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
\n\n\n\n// p5 Color object\nstroke(color(0, 0, 255));\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n\n
"
+ ],
+ "alt": "60x60 white rect at center. Dark charcoal grey outline.\n60x60 white rect at center. Yellow outline.\n60x60 white rect at center. Royal blue outline.\n60x60 white rect at center. Red outline.\n60x60 white rect at center. Pink outline.\n60x60 white rect at center. Black outline.\n60x60 white rect at center. Bright green outline.\n60x60 white rect at center. Soft green outline.\n60x60 white rect at center. Red outline.\n60x60 white rect at center. Dark fushcia outline.\n60x60 white rect at center. Blue outline.",
+ "class": "p5",
+ "module": "Color",
+ "submodule": "Setting",
+ "overloads": [
+ {
+ "line": 582,
+ "params": [
+ {
+ "name": "v1",
+ "description": "red or hue value relative to\n the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "green or saturation value\n relative to the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v3",
+ "description": "blue or brightness value\n relative to the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "alpha",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 721,
+ "params": [
+ {
+ "name": "value",
+ "description": "a color string
\n",
+ "type": "String"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 727,
+ "params": [
+ {
+ "name": "gray",
+ "description": "a gray value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "alpha",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 734,
+ "params": [
+ {
+ "name": "values",
+ "description": "an array containing the red,green,blue &\n and alpha components of the color
\n",
+ "type": "Number[]"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 741,
+ "params": [
+ {
+ "name": "color",
+ "description": "the stroke color
\n",
+ "type": "p5.Color"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/core/2d_primitives.js",
+ "line": 16,
+ "description": "Draw an arc to the screen. If called with only x, y, w, h, start, and\nstop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc\nwill be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The\norigin may be changed with the ellipseMode() function.
\nNote that drawing a full circle (ex: 0 to TWO_PI) will appear blank\nbecause 0 and TWO_PI are the same position on the unit circle. The\nbest way to handle this is by using the ellipse() function instead\nto create a closed ellipse, and to use the arc() function\nonly to draw parts of an ellipse.
\n",
+ "itemtype": "method",
+ "name": "arc",
+ "params": [
+ {
+ "name": "x",
+ "description": "x-coordinate of the arc's ellipse
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "y-coordinate of the arc's ellipse
\n",
+ "type": "Number"
+ },
+ {
+ "name": "w",
+ "description": "width of the arc's ellipse by default
\n",
+ "type": "Number"
+ },
+ {
+ "name": "h",
+ "description": "height of the arc's ellipse by default
\n",
+ "type": "Number"
+ },
+ {
+ "name": "start",
+ "description": "angle to start the arc, specified in radians
\n",
+ "type": "Number"
+ },
+ {
+ "name": "stop",
+ "description": "angle to stop the arc, specified in radians
\n",
+ "type": "Number"
+ },
+ {
+ "name": "mode",
+ "description": "optional parameter to determine the way of drawing\n the arc. either CHORD, PIE or OPEN
\n",
+ "type": "Constant",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\narc(50, 55, 50, 50, 0, HALF_PI);\nnoFill();\narc(50, 55, 60, 60, HALF_PI, PI);\narc(50, 55, 70, 70, PI, PI + QUARTER_PI);\narc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI);\n\n
\n\n\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI);\n\n
\n\n\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN);\n\n
\n\n\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD);\n\n
\n\n\n\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE);\n\n
"
+ ],
+ "alt": "shattered outline of an ellipse with a quarter of a white circle bottom-right.\nwhite ellipse with top right quarter missing.\nwhite ellipse with black outline with top right missing.\nwhite ellipse with top right missing with black outline around shape.\nwhite ellipse with top right quarter missing with black outline around the shape.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "2D Primitives"
+ },
+ {
+ "file": "src/core/2d_primitives.js",
+ "line": 133,
+ "description": "Draws an ellipse (oval) to the screen. An ellipse with equal width and\nheight is a circle. By default, the first two parameters set the location,\nand the third and fourth parameters set the shape's width and height. If\nno height is specified, the value of width is used for both the width and\nheight. If a negative height or width is specified, the absolute value is taken.\nThe origin may be changed with the ellipseMode() function.
\n",
+ "itemtype": "method",
+ "name": "ellipse",
+ "chainable": 1,
+ "example": [
+ "\n\n\nellipse(56, 46, 55, 55);\n\n
"
+ ],
+ "alt": "white ellipse with black outline in middle-right of canvas that is 55x55.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "2D Primitives",
+ "overloads": [
+ {
+ "line": 133,
+ "params": [
+ {
+ "name": "x",
+ "description": "x-coordinate of the ellipse.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "y-coordinate of the ellipse.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "w",
+ "description": "width of the ellipse.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "h",
+ "description": "height of the ellipse.
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 158,
+ "params": [
+ {
+ "name": "x",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "w",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "h",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "detail",
+ "description": "number of radial sectors to draw
\n",
+ "type": "Integer"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/core/2d_primitives.js",
+ "line": 188,
+ "description": "Draws a line (a direct path between two points) to the screen. The version\nof line() with four parameters draws the line in 2D. To color a line, use\nthe stroke() function. A line cannot be filled, therefore the fill()\nfunction will not affect the color of a line. 2D lines are drawn with a\nwidth of one pixel by default, but this can be changed with the\nstrokeWeight() function.
\n",
+ "itemtype": "method",
+ "name": "line",
+ "chainable": 1,
+ "example": [
+ "\n\n\nline(30, 20, 85, 75);\n\n
\n\n\n\nline(30, 20, 85, 20);\nstroke(126);\nline(85, 20, 85, 75);\nstroke(255);\nline(85, 75, 30, 75);\n\n
"
+ ],
+ "alt": "line 78 pixels long running from mid-top to bottom-right of canvas.\n3 lines of various stroke sizes. Form top, bottom and right sides of a square.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "2D Primitives",
+ "overloads": [
+ {
+ "line": 188,
+ "params": [
+ {
+ "name": "x1",
+ "description": "the x-coordinate of the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y1",
+ "description": "the y-coordinate of the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "the x-coordinate of the second point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "the y-coordinate of the second point
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 224,
+ "params": [
+ {
+ "name": "x1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z1",
+ "description": "the z-coordinate of the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z2",
+ "description": "the z-coordinate of the second point
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/core/2d_primitives.js",
+ "line": 244,
+ "description": "Draws a point, a coordinate in space at the dimension of one pixel.\nThe first parameter is the horizontal value for the point, the second\nvalue is the vertical value for the point. The color of the point is\ndetermined by the current stroke.
\n",
+ "itemtype": "method",
+ "name": "point",
+ "params": [
+ {
+ "name": "x",
+ "description": "the x-coordinate
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "the y-coordinate
\n",
+ "type": "Number"
+ },
+ {
+ "name": "z",
+ "description": "the z-coordinate (for WEBGL mode)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\npoint(30, 20);\npoint(85, 20);\npoint(85, 75);\npoint(30, 75);\n\n
"
+ ],
+ "alt": "4 points centered in the middle-right of the canvas.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "2D Primitives"
+ },
+ {
+ "file": "src/core/2d_primitives.js",
+ "line": 279,
+ "description": "Draw a quad. A quad is a quadrilateral, a four sided polygon. It is\nsimilar to a rectangle, but the angles between its edges are not\nconstrained to ninety degrees. The first pair of parameters (x1,y1)\nsets the first vertex and the subsequent pairs should proceed\nclockwise or counter-clockwise around the defined shape.
\n",
+ "itemtype": "method",
+ "name": "quad",
+ "chainable": 1,
+ "example": [
+ "\n\n\nquad(38, 31, 86, 20, 69, 63, 30, 76);\n\n
"
+ ],
+ "alt": "irregular white quadrilateral shape with black outline mid-right of canvas.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "2D Primitives",
+ "overloads": [
+ {
+ "line": 279,
+ "params": [
+ {
+ "name": "x1",
+ "description": "the x-coordinate of the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y1",
+ "description": "the y-coordinate of the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "the x-coordinate of the second point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "the y-coordinate of the second point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x3",
+ "description": "the x-coordinate of the third point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y3",
+ "description": "the y-coordinate of the third point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x4",
+ "description": "the x-coordinate of the fourth point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y4",
+ "description": "the y-coordinate of the fourth point
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 307,
+ "params": [
+ {
+ "name": "x1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "x3",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y3",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z3",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "x4",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y4",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z4",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/core/2d_primitives.js",
+ "line": 333,
+ "description": "Draws a rectangle to the screen. A rectangle is a four-sided shape with\nevery angle at ninety degrees. By default, the first two parameters set\nthe location of the upper-left corner, the third sets the width, and the\nfourth sets the height. The way these parameters are interpreted, however,\nmay be changed with the rectMode() function.\n
\nThe fifth, sixth, seventh and eighth parameters, if specified,\ndetermine corner radius for the top-right, top-left, lower-right and\nlower-left corners, respectively. An omitted corner radius parameter is set\nto the value of the previously specified radius value in the parameter list.
\n",
+ "itemtype": "method",
+ "name": "rect",
+ "chainable": 1,
+ "example": [
+ "\n\n\n// Draw a rectangle at location (30, 20) with a width and height of 55.\nrect(30, 20, 55, 55);\n\n
\n\n\n\n// Draw a rectangle with rounded corners, each having a radius of 20.\nrect(30, 20, 55, 55, 20);\n\n
\n\n\n\n// Draw a rectangle with rounded corners having the following radii:\n// top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.\nrect(30, 20, 55, 55, 20, 15, 10, 5);\n\n
"
+ ],
+ "alt": "55x55 white rect with black outline in mid-right of canvas.\n55x55 white rect with black outline and rounded edges in mid-right of canvas.\n55x55 white rect with black outline and rounded edges of different radii.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "2D Primitives",
+ "overloads": [
+ {
+ "line": 333,
+ "params": [
+ {
+ "name": "x",
+ "description": "x-coordinate of the rectangle.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "y-coordinate of the rectangle.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "w",
+ "description": "width of the rectangle.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "h",
+ "description": "height of the rectangle.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "tl",
+ "description": "optional radius of top-left corner.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "tr",
+ "description": "optional radius of top-right corner.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "br",
+ "description": "optional radius of bottom-right corner.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "bl",
+ "description": "optional radius of bottom-left corner.
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 383,
+ "params": [
+ {
+ "name": "x",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "w",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "h",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "detailX",
+ "description": "number of segments in the x-direction
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "detailY",
+ "description": "number of segments in the y-direction
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/core/2d_primitives.js",
+ "line": 416,
+ "description": "A triangle is a plane created by connecting three points. The first two\narguments specify the first point, the middle two arguments specify the\nsecond point, and the last two arguments specify the third point.
\n",
+ "itemtype": "method",
+ "name": "triangle",
+ "params": [
+ {
+ "name": "x1",
+ "description": "x-coordinate of the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y1",
+ "description": "y-coordinate of the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "x-coordinate of the second point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "y-coordinate of the second point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x3",
+ "description": "x-coordinate of the third point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y3",
+ "description": "y-coordinate of the third point
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\ntriangle(30, 75, 58, 20, 86, 75);\n\n
"
+ ],
+ "alt": "white triangle with black outline in mid-right of canvas.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "2D Primitives"
+ },
+ {
+ "file": "src/core/attributes.js",
+ "line": 14,
+ "description": "Modifies the location from which ellipses are drawn by changing the way\nin which parameters given to ellipse() are interpreted.\n
\nThe default mode is ellipseMode(CENTER), which interprets the first two\nparameters of ellipse() as the shape's center point, while the third and\nfourth parameters are its width and height.\n
\nellipseMode(RADIUS) also uses the first two parameters of ellipse() as\nthe shape's center point, but uses the third and fourth parameters to\nspecify half of the shapes's width and height.\n
\nellipseMode(CORNER) interprets the first two parameters of ellipse() as\nthe upper-left corner of the shape, while the third and fourth parameters\nare its width and height.\n
\nellipseMode(CORNERS) interprets the first two parameters of ellipse() as\nthe location of one corner of the ellipse's bounding box, and the third\nand fourth parameters as the location of the opposite corner.\n
\nThe parameter must be written in ALL CAPS because Javascript is a\ncase-sensitive language.
\n",
+ "itemtype": "method",
+ "name": "ellipseMode",
+ "params": [
+ {
+ "name": "mode",
+ "description": "either CENTER, RADIUS, CORNER, or CORNERS
\n",
+ "type": "Constant"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nellipseMode(RADIUS); // Set ellipseMode to RADIUS\nfill(255); // Set fill to white\nellipse(50, 50, 30, 30); // Draw white ellipse using RADIUS mode\n\nellipseMode(CENTER); // Set ellipseMode to CENTER\nfill(100); // Set fill to gray\nellipse(50, 50, 30, 30); // Draw gray ellipse using CENTER mode\n\n
\n\n\n\nellipseMode(CORNER); // Set ellipseMode is CORNER\nfill(255); // Set fill to white\nellipse(25, 25, 50, 50); // Draw white ellipse using CORNER mode\n\nellipseMode(CORNERS); // Set ellipseMode to CORNERS\nfill(100); // Set fill to gray\nellipse(25, 25, 50, 50); // Draw gray ellipse using CORNERS mode\n\n
"
+ ],
+ "alt": "60x60 white ellipse and 30x30 grey ellipse with black outlines at center.\n60x60 white ellipse @center and 30x30 grey ellipse top-right, black outlines.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Attributes"
+ },
+ {
+ "file": "src/core/attributes.js",
+ "line": 83,
+ "description": "Draws all geometry with jagged (aliased) edges. Note that smooth() is\nactive by default, so it is necessary to call noSmooth() to disable\nsmoothing of geometry, images, and fonts.
\n",
+ "itemtype": "method",
+ "name": "noSmooth",
+ "chainable": 1,
+ "example": [
+ "\n\n\nbackground(0);\nnoStroke();\nsmooth();\nellipse(30, 48, 36, 36);\nnoSmooth();\nellipse(70, 48, 36, 36);\n\n
"
+ ],
+ "alt": "2 pixelated 36x36 white ellipses to left & right of center, black background",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Attributes"
+ },
+ {
+ "file": "src/core/attributes.js",
+ "line": 111,
+ "description": "Modifies the location from which rectangles are drawn by changing the way\nin which parameters given to rect() are interpreted.\n
\nThe default mode is rectMode(CORNER), which interprets the first two\nparameters of rect() as the upper-left corner of the shape, while the\nthird and fourth parameters are its width and height.\n
\nrectMode(CORNERS) interprets the first two parameters of rect() as the\nlocation of one corner, and the third and fourth parameters as the\nlocation of the opposite corner.\n
\nrectMode(CENTER) interprets the first two parameters of rect() as the\nshape's center point, while the third and fourth parameters are its\nwidth and height.\n
\nrectMode(RADIUS) also uses the first two parameters of rect() as the\nshape's center point, but uses the third and fourth parameters to specify\nhalf of the shapes's width and height.\n
\nThe parameter must be written in ALL CAPS because Javascript is a\ncase-sensitive language.
\n",
+ "itemtype": "method",
+ "name": "rectMode",
+ "params": [
+ {
+ "name": "mode",
+ "description": "either CORNER, CORNERS, CENTER, or RADIUS
\n",
+ "type": "Constant"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nrectMode(CORNER); // Default rectMode is CORNER\nfill(255); // Set fill to white\nrect(25, 25, 50, 50); // Draw white rect using CORNER mode\n\nrectMode(CORNERS); // Set rectMode to CORNERS\nfill(100); // Set fill to gray\nrect(25, 25, 50, 50); // Draw gray rect using CORNERS mode\n\n
\n\n\n\nrectMode(RADIUS); // Set rectMode to RADIUS\nfill(255); // Set fill to white\nrect(50, 50, 30, 30); // Draw white rect using RADIUS mode\n\nrectMode(CENTER); // Set rectMode to CENTER\nfill(100); // Set fill to gray\nrect(50, 50, 30, 30); // Draw gray rect using CENTER mode\n\n
"
+ ],
+ "alt": "50x50 white rect at center and 25x25 grey rect in the top left of the other.\n50x50 white rect at center and 25x25 grey rect in the center of the other.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Attributes"
+ },
+ {
+ "file": "src/core/attributes.js",
+ "line": 180,
+ "description": "Draws all geometry with smooth (anti-aliased) edges. smooth() will also\nimprove image quality of resized images. Note that smooth() is active by\ndefault; noSmooth() can be used to disable smoothing of geometry,\nimages, and fonts.
\n",
+ "itemtype": "method",
+ "name": "smooth",
+ "chainable": 1,
+ "example": [
+ "\n\n\nbackground(0);\nnoStroke();\nsmooth();\nellipse(30, 48, 36, 36);\nnoSmooth();\nellipse(70, 48, 36, 36);\n\n
"
+ ],
+ "alt": "2 pixelated 36x36 white ellipses one left one right of center. On black.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Attributes"
+ },
+ {
+ "file": "src/core/attributes.js",
+ "line": 209,
+ "description": "Sets the style for rendering line endings. These ends are either squared,\nextended, or rounded, each of which specified with the corresponding\nparameters: SQUARE, PROJECT, and ROUND. The default cap is ROUND.
\n",
+ "itemtype": "method",
+ "name": "strokeCap",
+ "params": [
+ {
+ "name": "cap",
+ "description": "either SQUARE, PROJECT, or ROUND
\n",
+ "type": "Constant"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nstrokeWeight(12.0);\nstrokeCap(ROUND);\nline(20, 30, 80, 30);\nstrokeCap(SQUARE);\nline(20, 50, 80, 50);\nstrokeCap(PROJECT);\nline(20, 70, 80, 70);\n\n
"
+ ],
+ "alt": "3 lines. Top line: rounded ends, mid: squared, bottom:longer squared ends.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Attributes"
+ },
+ {
+ "file": "src/core/attributes.js",
+ "line": 246,
+ "description": "Sets the style of the joints which connect line segments. These joints\nare either mitered, beveled, or rounded and specified with the\ncorresponding parameters MITER, BEVEL, and ROUND. The default joint is\nMITER.
\n",
+ "itemtype": "method",
+ "name": "strokeJoin",
+ "params": [
+ {
+ "name": "join",
+ "description": "either MITER, BEVEL, ROUND
\n",
+ "type": "Constant"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(MITER);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n\n
\n\n\n\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(BEVEL);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n\n
\n\n\n\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(ROUND);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n\n
"
+ ],
+ "alt": "Right-facing arrowhead shape with pointed tip in center of canvas.\nRight-facing arrowhead shape with flat tip in center of canvas.\nRight-facing arrowhead shape with rounded tip in center of canvas.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Attributes"
+ },
+ {
+ "file": "src/core/attributes.js",
+ "line": 313,
+ "description": "Sets the width of the stroke used for lines, points, and the border\naround shapes. All widths are set in units of pixels.
\n",
+ "itemtype": "method",
+ "name": "strokeWeight",
+ "params": [
+ {
+ "name": "weight",
+ "description": "the weight (in pixels) of the stroke
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nstrokeWeight(1); // Default\nline(20, 20, 80, 20);\nstrokeWeight(4); // Thicker\nline(20, 40, 80, 40);\nstrokeWeight(10); // Beastly\nline(20, 70, 80, 70);\n\n
"
+ ],
+ "alt": "3 horizontal black lines. Top line: thin, mid: medium, bottom:thick.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Attributes"
+ },
+ {
+ "file": "src/core/canvas.js",
+ "line": 1,
+ "requires": [
+ "constants"
+ ],
+ "class": "p5",
+ "module": "Shape"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 13,
+ "itemtype": "property",
+ "name": "P2D",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 18,
+ "itemtype": "property",
+ "name": "WEBGL",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 34,
+ "description": "HALF_PI is a mathematical constant with the value\n1.57079632679489661923. It is half the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos().
\n",
+ "itemtype": "property",
+ "name": "HALF_PI",
+ "type": "Number",
+ "final": 1,
+ "example": [
+ "\n\narc(50, 50, 80, 80, 0, HALF_PI);\n
"
+ ],
+ "alt": "80x80 white quarter-circle with curve toward bottom right of canvas.",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 53,
+ "description": "PI is a mathematical constant with the value\n3.14159265358979323846. It is the ratio of the circumference\nof a circle to its diameter. It is useful in combination with\nthe trigonometric functions sin() and cos().
\n",
+ "itemtype": "property",
+ "name": "PI",
+ "type": "Number",
+ "final": 1,
+ "example": [
+ "\n\narc(50, 50, 80, 80, 0, PI);\n
"
+ ],
+ "alt": "white half-circle with curve toward bottom of canvas.",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 72,
+ "description": "QUARTER_PI is a mathematical constant with the value 0.7853982.\nIt is one quarter the ratio of the circumference of a circle to\nits diameter. It is useful in combination with the trigonometric\nfunctions sin() and cos().
\n",
+ "itemtype": "property",
+ "name": "QUARTER_PI",
+ "type": "Number",
+ "final": 1,
+ "example": [
+ "\n\narc(50, 50, 80, 80, 0, QUARTER_PI);\n
"
+ ],
+ "alt": "white eighth-circle rotated about 40 degrees with curve bottom right canvas.",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 91,
+ "description": "TAU is an alias for TWO_PI, a mathematical constant with the\nvalue 6.28318530717958647693. It is twice the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos().
\n",
+ "itemtype": "property",
+ "name": "TAU",
+ "type": "Number",
+ "final": 1,
+ "example": [
+ "\n\narc(50, 50, 80, 80, 0, TAU);\n
"
+ ],
+ "alt": "80x80 white ellipse shape in center of canvas.",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 110,
+ "description": "TWO_PI is a mathematical constant with the value\n6.28318530717958647693. It is twice the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions sin() and cos().
\n",
+ "itemtype": "property",
+ "name": "TWO_PI",
+ "type": "Number",
+ "final": 1,
+ "example": [
+ "\n\narc(50, 50, 80, 80, 0, TWO_PI);\n
"
+ ],
+ "alt": "80x80 white ellipse shape in center of canvas.",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 129,
+ "description": "Constant to be used with angleMode() function, to set the mode which\np5.js interprates and calculates angles (either DEGREES or RADIANS).
\n",
+ "itemtype": "property",
+ "name": "DEGREES",
+ "type": "String",
+ "final": 1,
+ "example": [
+ "\n\nfunction setup() {\n angleMode(DEGREES);\n}\n
"
+ ],
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 143,
+ "description": "Constant to be used with angleMode() function, to set the mode which\np5.js interprates and calculates angles (either RADIANS or DEGREES).
\n",
+ "itemtype": "property",
+ "name": "RADIANS",
+ "type": "String",
+ "final": 1,
+ "example": [
+ "\n\nfunction setup() {\n angleMode(RADIANS);\n}\n
"
+ ],
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 161,
+ "itemtype": "property",
+ "name": "CORNER",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 166,
+ "itemtype": "property",
+ "name": "CORNERS",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 171,
+ "itemtype": "property",
+ "name": "RADIUS",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 176,
+ "itemtype": "property",
+ "name": "RIGHT",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 181,
+ "itemtype": "property",
+ "name": "LEFT",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 186,
+ "itemtype": "property",
+ "name": "CENTER",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 191,
+ "itemtype": "property",
+ "name": "TOP",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 196,
+ "itemtype": "property",
+ "name": "BOTTOM",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 201,
+ "itemtype": "property",
+ "name": "BASELINE",
+ "type": "String",
+ "final": 1,
+ "default": "alphabetic",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 207,
+ "itemtype": "property",
+ "name": "POINTS",
+ "type": "Number",
+ "final": 1,
+ "default": "0x0000",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 213,
+ "itemtype": "property",
+ "name": "LINES",
+ "type": "Number",
+ "final": 1,
+ "default": "0x0001",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 219,
+ "itemtype": "property",
+ "name": "LINE_STRIP",
+ "type": "Number",
+ "final": 1,
+ "default": "0x0003",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 225,
+ "itemtype": "property",
+ "name": "LINE_LOOP",
+ "type": "Number",
+ "final": 1,
+ "default": "0x0002",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 231,
+ "itemtype": "property",
+ "name": "TRIANGLES",
+ "type": "Number",
+ "final": 1,
+ "default": "0x0004",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 237,
+ "itemtype": "property",
+ "name": "TRIANGLE_FAN",
+ "type": "Number",
+ "final": 1,
+ "default": "0x0006",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 243,
+ "itemtype": "property",
+ "name": "TRIANGLE_STRIP",
+ "type": "Number",
+ "final": 1,
+ "default": "0x0005",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 249,
+ "itemtype": "property",
+ "name": "QUADS",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 254,
+ "itemtype": "property",
+ "name": "QUAD_STRIP",
+ "type": "String",
+ "final": 1,
+ "default": "quad_strip",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 260,
+ "itemtype": "property",
+ "name": "CLOSE",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 265,
+ "itemtype": "property",
+ "name": "OPEN",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 270,
+ "itemtype": "property",
+ "name": "CHORD",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 275,
+ "itemtype": "property",
+ "name": "PIE",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 280,
+ "itemtype": "property",
+ "name": "PROJECT",
+ "type": "String",
+ "final": 1,
+ "default": "square",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 286,
+ "itemtype": "property",
+ "name": "SQUARE",
+ "type": "String",
+ "final": 1,
+ "default": "butt",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 292,
+ "itemtype": "property",
+ "name": "ROUND",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 297,
+ "itemtype": "property",
+ "name": "BEVEL",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 302,
+ "itemtype": "property",
+ "name": "MITER",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 309,
+ "itemtype": "property",
+ "name": "RGB",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 314,
+ "itemtype": "property",
+ "name": "HSB",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 319,
+ "itemtype": "property",
+ "name": "HSL",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 345,
+ "itemtype": "property",
+ "name": "BLEND",
+ "type": "String",
+ "final": 1,
+ "default": "source-over",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 351,
+ "itemtype": "property",
+ "name": "ADD",
+ "type": "String",
+ "final": 1,
+ "default": "lighter",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 359,
+ "itemtype": "property",
+ "name": "DARKEST",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 364,
+ "itemtype": "property",
+ "name": "LIGHTEST",
+ "type": "String",
+ "final": 1,
+ "default": "lighten",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 370,
+ "itemtype": "property",
+ "name": "DIFFERENCE",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 375,
+ "itemtype": "property",
+ "name": "EXCLUSION",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 380,
+ "itemtype": "property",
+ "name": "MULTIPLY",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 385,
+ "itemtype": "property",
+ "name": "SCREEN",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 390,
+ "itemtype": "property",
+ "name": "REPLACE",
+ "type": "String",
+ "final": 1,
+ "default": "copy",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 396,
+ "itemtype": "property",
+ "name": "OVERLAY",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 401,
+ "itemtype": "property",
+ "name": "HARD_LIGHT",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 406,
+ "itemtype": "property",
+ "name": "SOFT_LIGHT",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 411,
+ "itemtype": "property",
+ "name": "DODGE",
+ "type": "String",
+ "final": 1,
+ "default": "color-dodge",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 417,
+ "itemtype": "property",
+ "name": "BURN",
+ "type": "String",
+ "final": 1,
+ "default": "color-burn",
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 425,
+ "itemtype": "property",
+ "name": "THRESHOLD",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 430,
+ "itemtype": "property",
+ "name": "GRAY",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 435,
+ "itemtype": "property",
+ "name": "OPAQUE",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 440,
+ "itemtype": "property",
+ "name": "INVERT",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 445,
+ "itemtype": "property",
+ "name": "POSTERIZE",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 450,
+ "itemtype": "property",
+ "name": "DILATE",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 455,
+ "itemtype": "property",
+ "name": "ERODE",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 460,
+ "itemtype": "property",
+ "name": "BLUR",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 467,
+ "itemtype": "property",
+ "name": "NORMAL",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 472,
+ "itemtype": "property",
+ "name": "ITALIC",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 477,
+ "itemtype": "property",
+ "name": "BOLD",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 501,
+ "itemtype": "property",
+ "name": "LANDSCAPE",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/constants.js",
+ "line": 506,
+ "itemtype": "property",
+ "name": "PORTRAIT",
+ "type": "String",
+ "final": 1,
+ "class": "p5",
+ "module": "Constants",
+ "submodule": "Constants"
+ },
+ {
+ "file": "src/core/core.js",
+ "line": 49,
+ "description": "Called directly before setup(), the preload() function is used to handle\nasynchronous loading of external files in a blocking way. If a preload \nfunction is defined, setup() will wait until any load calls within have\nfinished. Nothing besides load calls (loadImage, loadJSON, loadFont,\nloadStrings, etc.) should be inside preload function. If asynchronous\nloading is preferred, the load methods can instead be called in setup()\nor anywhere else with the use of a callback parameter.\n
\nBy default the text "loading..." will be displayed. To make your own\nloading page, include an HTML element with id "p5_loading" in your\npage. More information here.
\n",
+ "itemtype": "method",
+ "name": "preload",
+ "example": [
+ "\n\nvar img;\nvar c;\nfunction preload() {\n // preload() runs once\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n // setup() waits until preload() is done\n img.loadPixels();\n // get color of middle pixel\n c = img.get(img.width / 2, img.height / 2);\n}\n\nfunction draw() {\n background(c);\n image(img, 25, 25, 50, 50);\n}\n
"
+ ],
+ "alt": "nothing displayed",
+ "class": "p5",
+ "module": "Structure",
+ "submodule": "Structure"
+ },
+ {
+ "file": "src/core/core.js",
+ "line": 90,
+ "description": "The setup() function is called once when the program starts. It's used to\ndefine initial environment properties such as screen size and background\ncolor and to load media such as images and fonts as the program starts.\nThere can only be one setup() function for each program and it shouldn't\nbe called again after its initial execution.\n
\nNote: Variables declared within setup() are not accessible within other\nfunctions, including draw().
\n",
+ "itemtype": "method",
+ "name": "setup",
+ "example": [
+ "\n\nvar a = 0;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(102);\n}\n\nfunction draw() {\n rect(a++ % width, 10, 2, 80);\n}\n
"
+ ],
+ "alt": "nothing displayed",
+ "class": "p5",
+ "module": "Structure",
+ "submodule": "Structure"
+ },
+ {
+ "file": "src/core/core.js",
+ "line": 121,
+ "description": "Called directly after setup(), the draw() function continuously executes\nthe lines of code contained inside its block until the program is stopped\nor noLoop() is called. Note if noLoop() is called in setup(), draw() will\nstill be executed once before stopping. draw() is called automatically and\nshould never be called explicitly.\n
\nIt should always be controlled with noLoop(), redraw() and loop(). After\nnoLoop() stops the code in draw() from executing, redraw() causes the\ncode inside draw() to execute once, and loop() will cause the code\ninside draw() to resume executing continuously.\n
\nThe number of times draw() executes in each second may be controlled with\nthe frameRate() function.\n
\nThere can only be one draw() function for each sketch, and draw() must\nexist if you want the code to run continuously, or to process events such\nas mousePressed(). Sometimes, you might have an empty call to draw() in\nyour program, as shown in the above example.\n
\nIt is important to note that the drawing coordinate system will be reset\nat the beginning of each draw() call. If any transformations are performed\nwithin draw() (ex: scale, rotate, translate), their effects will be\nundone at the beginning of draw(), so transformations will not accumulate\nover time. On the other hand, styling applied (ex: fill, stroke, etc) will\nremain in effect.
\n",
+ "itemtype": "method",
+ "name": "draw",
+ "example": [
+ "\n\nvar yPos = 0;\nfunction setup() {\n // setup() runs once\n frameRate(30);\n}\nfunction draw() {\n // draw() loops forever, until stopped\n background(204);\n yPos = yPos - 1;\n if (yPos < 0) {\n yPos = height;\n }\n line(0, yPos, width, yPos);\n}\n
"
+ ],
+ "alt": "nothing displayed",
+ "class": "p5",
+ "module": "Structure",
+ "submodule": "Structure"
+ },
+ {
+ "file": "src/core/core.js",
+ "line": 407,
+ "description": "Removes the entire p5 sketch. This will remove the canvas and any\nelements created by p5.js. It will also stop the draw loop and unbind\nany properties or methods from the window global scope. It will\nleave a variable p5 in case you wanted to create a new p5 sketch.\nIf you like, you can set p5 = null to erase it. While all functions and\nvariables and objects created by the p5 library will be removed, any\nother global variables created by your code will remain.
\n",
+ "itemtype": "method",
+ "name": "remove",
+ "example": [
+ "\n\nfunction draw() {\n ellipse(50, 50, 10, 10);\n}\n\nfunction mousePressed() {\n remove(); // remove whole sketch on mouse press\n}\n
"
+ ],
+ "alt": "nothing displayed",
+ "class": "p5",
+ "module": "Structure",
+ "submodule": "Structure"
+ },
+ {
+ "file": "src/core/curves.js",
+ "line": 13,
+ "description": "Draws a cubic Bezier curve on the screen. These curves are defined by a\nseries of anchor and control points. The first two parameters specify\nthe first anchor point and the last two parameters specify the other\nanchor point, which become the first and last points on the curve. The\nmiddle parameters specify the two control points which define the shape\nof the curve. Approximately speaking, control points "pull" the curve\ntowards them.
Bezier curves were developed by French\nautomotive engineer Pierre Bezier, and are commonly used in computer\ngraphics to define gently sloping curves. See also curve().
\n",
+ "itemtype": "method",
+ "name": "bezier",
+ "chainable": 1,
+ "example": [
+ "\n\n\nnoFill();\nstroke(255, 102, 0);\nline(85, 20, 10, 10);\nline(90, 90, 15, 80);\nstroke(0, 0, 0);\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\n\n
\n\n\n\nbackground(0, 0, 0);\nnoFill();\nstroke(255);\nbezier(250, 250, 0, 100, 100, 0, 100, 0, 0, 0, 100, 0);\n\n
"
+ ],
+ "alt": "stretched black s-shape in center with orange lines extending from end points.\nstretched black s-shape with 10 5x5 white ellipses along the shape.\nstretched black s-shape with 7 5x5 ellipses and orange lines along the shape.\nstretched black s-shape with 17 small orange lines extending from under shape.\nhorseshoe shape with orange ends facing left and black curved center.\nhorseshoe shape with orange ends facing left and black curved center.\nLine shaped like right-facing arrow,points move with mouse-x and warp shape.\nhorizontal line that hooks downward on the right and 13 5x5 ellipses along it.\nright curving line mid-right of canvas with 7 short lines radiating from it.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Curves",
+ "overloads": [
+ {
+ "line": 13,
+ "params": [
+ {
+ "name": "x1",
+ "description": "x-coordinate for the first anchor point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y1",
+ "description": "y-coordinate for the first anchor point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "x-coordinate for the first control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "y-coordinate for the first control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x3",
+ "description": "x-coordinate for the second control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y3",
+ "description": "y-coordinate for the second control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x4",
+ "description": "x-coordinate for the second anchor point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y4",
+ "description": "y-coordinate for the second anchor point
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 66,
+ "params": [
+ {
+ "name": "x1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z1",
+ "description": "z-coordinate for the first anchor point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z2",
+ "description": "z-coordinate for the first control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x3",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y3",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z3",
+ "description": "z-coordinate for the second control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x4",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y4",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z4",
+ "description": "z-coordinate for the second anchor point
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/core/curves.js",
+ "line": 92,
+ "description": "Sets the resolution at which Beziers display.
\nThe default value is 20.
\nThis function is only useful when using the WEBGL renderer\nas the default canvas renderer does not use this information.
\n",
+ "itemtype": "method",
+ "name": "bezierDetail",
+ "params": [
+ {
+ "name": "detail",
+ "description": "resolution of the curves
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n\n bezierDetail(5);\n}\n\nfunction draw() {\n background(200);\n\n // prettier-ignore\n bezier(-40, -40, 0,\n 90, -40, 0,\n -90, 40, 0,\n 40, 40, 0);\n}\n\n
"
+ ],
+ "alt": "stretched black s-shape with a low level of bezier detail",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Curves"
+ },
+ {
+ "file": "src/core/curves.js",
+ "line": 135,
+ "description": "Evaluates the Bezier at position t for points a, b, c, d.\nThe parameters a and d are the first and last points\non the curve, and b and c are the control points.\nThe final parameter t varies between 0 and 1.\nThis can be done once with the x coordinates and a second time\nwith the y coordinates to get the location of a bezier curve at t.
\n",
+ "itemtype": "method",
+ "name": "bezierPoint",
+ "params": [
+ {
+ "name": "a",
+ "description": "coordinate of first point on the curve
\n",
+ "type": "Number"
+ },
+ {
+ "name": "b",
+ "description": "coordinate of first control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "c",
+ "description": "coordinate of second control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "d",
+ "description": "coordinate of second point on the curve
\n",
+ "type": "Number"
+ },
+ {
+ "name": "t",
+ "description": "value between 0 and 1
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the value of the Bezier at position t",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nnoFill();\nvar x1 = 85,\n x2 = 10,\n x3 = 90,\n x4 = 15;\nvar y1 = 20,\n y2 = 10,\n y3 = 90,\n y4 = 80;\nbezier(x1, y1, x2, y2, x3, y3, x4, y4);\nfill(255);\nvar steps = 10;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = bezierPoint(x1, x2, x3, x4, t);\n var y = bezierPoint(y1, y2, y3, y4, t);\n ellipse(x, y, 5, 5);\n}\n\n
"
+ ],
+ "alt": "stretched black s-shape with 17 small orange lines extending from under shape.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Curves"
+ },
+ {
+ "file": "src/core/curves.js",
+ "line": 190,
+ "description": "Evaluates the tangent to the Bezier at position t for points a, b, c, d.\nThe parameters a and d are the first and last points\non the curve, and b and c are the control points.\nThe final parameter t varies between 0 and 1.
\n",
+ "itemtype": "method",
+ "name": "bezierTangent",
+ "params": [
+ {
+ "name": "a",
+ "description": "coordinate of first point on the curve
\n",
+ "type": "Number"
+ },
+ {
+ "name": "b",
+ "description": "coordinate of first control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "c",
+ "description": "coordinate of second control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "d",
+ "description": "coordinate of second point on the curve
\n",
+ "type": "Number"
+ },
+ {
+ "name": "t",
+ "description": "value between 0 and 1
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the tangent at position t",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nvar steps = 6;\nfill(255);\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n // Get the location of the point\n var x = bezierPoint(85, 10, 90, 15, t);\n var y = bezierPoint(20, 10, 90, 80, t);\n // Get the tangent points\n var tx = bezierTangent(85, 10, 90, 15, t);\n var ty = bezierTangent(20, 10, 90, 80, t);\n // Calculate an angle from the tangent points\n var a = atan2(ty, tx);\n a += PI;\n stroke(255, 102, 0);\n line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);\n // The following line of code makes a line\n // inverse of the above line\n //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);\n stroke(0);\n ellipse(x, y, 5, 5);\n}\n\n
\n\n\n\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nstroke(255, 102, 0);\nvar steps = 16;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = bezierPoint(85, 10, 90, 15, t);\n var y = bezierPoint(20, 10, 90, 80, t);\n var tx = bezierTangent(85, 10, 90, 15, t);\n var ty = bezierTangent(20, 10, 90, 80, t);\n var a = atan2(ty, tx);\n a -= HALF_PI;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n\n
"
+ ],
+ "alt": "s-shaped line with 17 short orange lines extending from underside of shape",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Curves"
+ },
+ {
+ "file": "src/core/curves.js",
+ "line": 269,
+ "description": "Draws a curved line on the screen between two points, given as the\nmiddle four parameters. The first two parameters are a control point, as\nif the curve came from this point even though it's not drawn. The last\ntwo parameters similarly describe the other control point.
\nLonger curves can be created by putting a series of curve() functions\ntogether or using curveVertex(). An additional function called\ncurveTightness() provides control for the visual quality of the curve.\nThe curve() function is an implementation of Catmull-Rom splines.
\n",
+ "itemtype": "method",
+ "name": "curve",
+ "chainable": 1,
+ "example": [
+ "\n\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\nstroke(0);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nstroke(255, 102, 0);\ncurve(73, 24, 73, 61, 15, 65, 15, 65);\n\n
\n\n\n// Define the curve points as JavaScript objects\nvar p1 = { x: 5, y: 26 },\n p2 = { x: 73, y: 24 };\nvar p3 = { x: 73, y: 61 },\n p4 = { x: 15, y: 65 };\nnoFill();\nstroke(255, 102, 0);\ncurve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);\nstroke(0);\ncurve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);\nstroke(255, 102, 0);\ncurve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y);\n\n
\n\n\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0);\nstroke(0);\ncurve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0);\nstroke(255, 102, 0);\ncurve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0);\n\n
"
+ ],
+ "alt": "horseshoe shape with orange ends facing left and black curved center.\nhorseshoe shape with orange ends facing left and black curved center.\ncurving black and orange lines.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Curves",
+ "overloads": [
+ {
+ "line": 269,
+ "params": [
+ {
+ "name": "x1",
+ "description": "x-coordinate for the beginning control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y1",
+ "description": "y-coordinate for the beginning control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "x-coordinate for the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "y-coordinate for the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x3",
+ "description": "x-coordinate for the second point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y3",
+ "description": "y-coordinate for the second point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x4",
+ "description": "x-coordinate for the ending control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y4",
+ "description": "y-coordinate for the ending control point
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 334,
+ "params": [
+ {
+ "name": "x1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z1",
+ "description": "z-coordinate for the beginning control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z2",
+ "description": "z-coordinate for the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x3",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y3",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z3",
+ "description": "z-coordinate for the second point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x4",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y4",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z4",
+ "description": "z-coordinate for the ending control point
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/core/curves.js",
+ "line": 360,
+ "description": "Sets the resolution at which curves display.
\nThe default value is 20.
\nThis function is only useful when using the WEBGL renderer\nas the default canvas renderer does not use this\ninformation.
\n",
+ "itemtype": "method",
+ "name": "curveDetail",
+ "params": [
+ {
+ "name": "resolution",
+ "description": "of the curves
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n curveDetail(5);\n}\nfunction draw() {\n background(200);\n\n // prettier-ignore\n curve( 250, 600, 0,\n -30, 40, 0,\n 30, 30, 0,\n -250, 600, 0);\n}\n\n
"
+ ],
+ "alt": "white arch shape with a low level of curve detail.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Curves"
+ },
+ {
+ "file": "src/core/curves.js",
+ "line": 402,
+ "description": "Modifies the quality of forms created with curve() and curveVertex().\nThe parameter tightness determines how the curve fits to the vertex\npoints. The value 0.0 is the default value for tightness (this value\ndefines the curves to be Catmull-Rom splines) and the value 1.0 connects\nall the points with straight lines. Values within the range -5.0 and 5.0\nwill deform the curves but will leave them recognizable and as values\nincrease in magnitude, they will continue to deform.
\n",
+ "itemtype": "method",
+ "name": "curveTightness",
+ "params": [
+ {
+ "name": "amount",
+ "description": "of deformation from the original vertices
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\n// Move the mouse left and right to see the curve change\n\nfunction setup() {\n createCanvas(100, 100);\n noFill();\n}\n\nfunction draw() {\n background(204);\n var t = map(mouseX, 0, width, -5, 5);\n curveTightness(t);\n beginShape();\n curveVertex(10, 26);\n curveVertex(10, 26);\n curveVertex(83, 24);\n curveVertex(83, 61);\n curveVertex(25, 65);\n curveVertex(25, 65);\n endShape();\n}\n\n
"
+ ],
+ "alt": "Line shaped like right-facing arrow,points move with mouse-x and warp shape.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Curves"
+ },
+ {
+ "file": "src/core/curves.js",
+ "line": 448,
+ "description": "Evaluates the curve at position t for points a, b, c, d.\nThe parameter t varies between 0 and 1, a and d are points\non the curve, and b and c are the control points.\nThis can be done once with the x coordinates and a second time\nwith the y coordinates to get the location of a curve at t.
\n",
+ "itemtype": "method",
+ "name": "curvePoint",
+ "params": [
+ {
+ "name": "a",
+ "description": "coordinate of first point on the curve
\n",
+ "type": "Number"
+ },
+ {
+ "name": "b",
+ "description": "coordinate of first control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "c",
+ "description": "coordinate of second control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "d",
+ "description": "coordinate of second point on the curve
\n",
+ "type": "Number"
+ },
+ {
+ "name": "t",
+ "description": "value between 0 and 1
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "bezier value at position t",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nnoFill();\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nfill(255);\nellipseMode(CENTER);\nvar steps = 6;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = curvePoint(5, 5, 73, 73, t);\n var y = curvePoint(26, 26, 24, 61, t);\n ellipse(x, y, 5, 5);\n x = curvePoint(5, 73, 73, 15, t);\n y = curvePoint(26, 24, 61, 65, t);\n ellipse(x, y, 5, 5);\n}\n\n
\n\nline hooking down to right-bottom with 13 5x5 white ellipse points"
+ ],
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Curves"
+ },
+ {
+ "file": "src/core/curves.js",
+ "line": 497,
+ "description": "Evaluates the tangent to the curve at position t for points a, b, c, d.\nThe parameter t varies between 0 and 1, a and d are points on the curve,\nand b and c are the control points.
\n",
+ "itemtype": "method",
+ "name": "curveTangent",
+ "params": [
+ {
+ "name": "a",
+ "description": "coordinate of first point on the curve
\n",
+ "type": "Number"
+ },
+ {
+ "name": "b",
+ "description": "coordinate of first control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "c",
+ "description": "coordinate of second control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "d",
+ "description": "coordinate of second point on the curve
\n",
+ "type": "Number"
+ },
+ {
+ "name": "t",
+ "description": "value between 0 and 1
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the tangent at position t",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nnoFill();\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nvar steps = 6;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = curvePoint(5, 73, 73, 15, t);\n var y = curvePoint(26, 24, 61, 65, t);\n //ellipse(x, y, 5, 5);\n var tx = curveTangent(5, 73, 73, 15, t);\n var ty = curveTangent(26, 24, 61, 65, t);\n var a = atan2(ty, tx);\n a -= PI / 2.0;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n\n
"
+ ],
+ "alt": "right curving line mid-right of canvas with 7 short lines radiating from it.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Curves"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 22,
+ "description": "The print() function writes to the console area of your browser.\nThis function is often helpful for looking at the data a program is\nproducing. This function creates a new line of text for each call to\nthe function. Individual elements can be\nseparated with quotes ("") and joined with the addition operator (+).
\n",
+ "itemtype": "method",
+ "name": "print",
+ "params": [
+ {
+ "name": "contents",
+ "description": "any combination of Number, String, Object, Boolean,\n Array to print
\n",
+ "type": "Any"
+ }
+ ],
+ "example": [
+ "\n\nvar x = 10;\nprint('The value of x is ' + x);\n// prints \"The value of x is 10\"\n
"
+ ],
+ "alt": "default grey canvas",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 49,
+ "description": "The system variable frameCount contains the number of frames that have\nbeen displayed since the program started. Inside setup() the value is 0,\nafter the first iteration of draw it is 1, etc.
\n",
+ "itemtype": "property",
+ "name": "frameCount",
+ "type": "Integer",
+ "readonly": "",
+ "example": [
+ "\n \nfunction setup() {\n frameRate(30);\n textSize(20);\n textSize(30);\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(200);\n text(frameCount, width / 2, height / 2);\n}\n
"
+ ],
+ "alt": "numbers rapidly counting upward with frame count set to 30.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 77,
+ "description": "Confirms if the window a p5.js program is in is "focused," meaning that\nthe sketch will accept mouse or keyboard input. This variable is\n"true" if the window is focused and "false" if not.
\n",
+ "itemtype": "property",
+ "name": "focused",
+ "type": "Boolean",
+ "readonly": "",
+ "example": [
+ "\n\n// To demonstrate, put two windows side by side.\n// Click on the window that the p5 sketch isn't in!\nfunction draw() {\n background(200);\n noStroke();\n fill(0, 200, 0);\n ellipse(25, 25, 50, 50);\n\n if (!focused) {\n // or \"if (focused === false)\"\n stroke(200, 0, 0);\n line(0, 0, 100, 100);\n line(100, 0, 0, 100);\n }\n}\n
"
+ ],
+ "alt": "green 50x50 ellipse at top left. Red X covers canvas when page focus changes",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 109,
+ "description": "Sets the cursor to a predefined symbol or an image, or makes it visible\nif already hidden. If you are trying to set an image as the cursor, the\nrecommended size is 16x16 or 32x32 pixels. It is not possible to load an\nimage as the cursor if you are exporting your program for the Web, and not\nall MODES work with all browsers. The values for parameters x and y must\nbe less than the dimensions of the image.
\n",
+ "itemtype": "method",
+ "name": "cursor",
+ "params": [
+ {
+ "name": "type",
+ "description": "either ARROW, CROSS, HAND, MOVE, TEXT, or\n WAIT, or path for image
\n",
+ "type": "String|Constant"
+ },
+ {
+ "name": "x",
+ "description": "the horizontal active spot of the cursor
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "y",
+ "description": "the vertical active spot of the cursor
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\n// Move the mouse left and right across the image\n// to see the cursor change from a cross to a hand\nfunction draw() {\n line(width / 2, 0, width / 2, height);\n if (mouseX < 50) {\n cursor(CROSS);\n } else {\n cursor(HAND);\n }\n}\n
"
+ ],
+ "alt": "horizontal line divides canvas. cursor on left is a cross, right is hand.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 170,
+ "description": "Specifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within setup() is\nrecommended. The default rate is 60 frames per second. This is the same as\nsetFrameRate(val).\n
\nCalling frameRate() with no arguments returns the current framerate. The\ndraw function must run at least once before it will return a value. This\nis the same as getFrameRate().\n
\nCalling frameRate() with arguments that are not of the type numbers\nor are non positive also returns current framerate.
\n",
+ "itemtype": "method",
+ "name": "frameRate",
+ "chainable": 1,
+ "example": [
+ "\n\n\nvar rectX = 0;\nvar fr = 30; //starting FPS\nvar clr;\n\nfunction setup() {\n background(200);\n frameRate(fr); // Attempt to refresh at starting FPS\n clr = color(255, 0, 0);\n}\n\nfunction draw() {\n background(200);\n rectX = rectX += 1; // Move Rectangle\n\n if (rectX >= width) {\n // If you go off screen.\n if (fr === 30) {\n clr = color(0, 0, 255);\n fr = 10;\n frameRate(fr); // make frameRate 10 FPS\n } else {\n clr = color(255, 0, 0);\n fr = 30;\n frameRate(fr); // make frameRate 30 FPS\n }\n rectX = 0;\n }\n fill(clr);\n rect(rectX, 40, 20, 20);\n}\n
"
+ ],
+ "alt": "blue rect moves left to right, followed by red rect moving faster. Loops.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment",
+ "overloads": [
+ {
+ "line": 170,
+ "params": [
+ {
+ "name": "fps",
+ "description": "number of frames to be displayed every second
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 228,
+ "params": [],
+ "return": {
+ "description": "current frameRate",
+ "type": "Number"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 268,
+ "description": "Hides the cursor from view.
\n",
+ "itemtype": "method",
+ "name": "noCursor",
+ "example": [
+ "\n\nfunction setup() {\n noCursor();\n}\n\nfunction draw() {\n background(200);\n ellipse(mouseX, mouseY, 10, 10);\n}\n
"
+ ],
+ "alt": "cursor becomes 10x 10 white ellipse the moves with mouse x and y.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 293,
+ "description": "System variable that stores the width of the entire screen display. This\nis used to run a full-screen program on any display size.
\n",
+ "itemtype": "property",
+ "name": "displayWidth",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\ncreateCanvas(displayWidth, displayHeight);\n
"
+ ],
+ "alt": "cursor becomes 10x 10 white ellipse the moves with mouse x and y.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 310,
+ "description": "System variable that stores the height of the entire screen display. This\nis used to run a full-screen program on any display size.
\n",
+ "itemtype": "property",
+ "name": "displayHeight",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\ncreateCanvas(displayWidth, displayHeight);\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 327,
+ "description": "System variable that stores the width of the inner window, it maps to\nwindow.innerWidth.
\n",
+ "itemtype": "property",
+ "name": "windowWidth",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\ncreateCanvas(windowWidth, windowHeight);\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 343,
+ "description": "System variable that stores the height of the inner window, it maps to\nwindow.innerHeight.
\n",
+ "itemtype": "property",
+ "name": "windowHeight",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\ncreateCanvas(windowWidth, windowHeight);\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 359,
+ "description": "The windowResized() function is called once every time the browser window\nis resized. This is a good place to resize the canvas or do any other\nadjustments to accommodate the new window size.
\n",
+ "itemtype": "method",
+ "name": "windowResized",
+ "example": [
+ "\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n}\n\nfunction draw() {\n background(0, 100, 200);\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 413,
+ "description": "System variable that stores the width of the drawing canvas. This value\nis set by the first parameter of the createCanvas() function.\nFor example, the function call createCanvas(320, 240) sets the width\nvariable to the value 320. The value of width defaults to 100 if\ncreateCanvas() is not used in a program.
\n",
+ "itemtype": "property",
+ "name": "width",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 425,
+ "description": "System variable that stores the height of the drawing canvas. This value\nis set by the second parameter of the createCanvas() function. For\nexample, the function call createCanvas(320, 240) sets the height\nvariable to the value 240. The value of height defaults to 100 if\ncreateCanvas() is not used in a program.
\n",
+ "itemtype": "property",
+ "name": "height",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 437,
+ "description": "If argument is given, sets the sketch to fullscreen or not based on the\nvalue of the argument. If no argument is given, returns the current\nfullscreen state. Note that due to browser restrictions this can only\nbe called on user input, for example, on mouse press like the example\nbelow.
\n",
+ "itemtype": "method",
+ "name": "fullscreen",
+ "params": [
+ {
+ "name": "val",
+ "description": "whether the sketch should be in fullscreen mode\nor not
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "current fullscreen state",
+ "type": "Boolean"
+ },
+ "example": [
+ "\n\n\n// Clicking in the box toggles fullscreen on and off.\nfunction setup() {\n background(200);\n}\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n var fs = fullscreen();\n fullscreen(!fs);\n }\n}\n\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 488,
+ "description": "Sets the pixel scaling for high pixel density displays. By default\npixel density is set to match display density, call pixelDensity(1)\nto turn this off. Calling pixelDensity() with no arguments returns\nthe current pixel density of the sketch.
\n",
+ "itemtype": "method",
+ "name": "pixelDensity",
+ "params": [
+ {
+ "name": "val",
+ "description": "whether or how much the sketch should scale
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "current pixel density of the sketch",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n\n
\n\n\nfunction setup() {\n pixelDensity(3.0);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n\n
"
+ ],
+ "alt": "fuzzy 50x50 white ellipse with black outline in center of canvas.\nsharp 50x50 white ellipse with black outline in center of canvas.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 534,
+ "description": "Returns the pixel density of the current display the sketch is running on.
\n",
+ "itemtype": "method",
+ "name": "displayDensity",
+ "return": {
+ "description": "current pixel density of the display",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n var density = displayDensity();\n pixelDensity(density);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n\n
"
+ ],
+ "alt": "50x50 white ellipse with black outline in center of canvas.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 591,
+ "description": "Gets the current URL.
\n",
+ "itemtype": "method",
+ "name": "getURL",
+ "return": {
+ "description": "url",
+ "type": "String"
+ },
+ "example": [
+ "\n\n\nvar url;\nvar x = 100;\n\nfunction setup() {\n fill(0);\n noStroke();\n url = getURL();\n}\n\nfunction draw() {\n background(200);\n text(url, x, height / 2);\n x--;\n}\n\n
"
+ ],
+ "alt": "current url (http://p5js.org/reference/#/p5/getURL) moves right to left.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 622,
+ "description": "Gets the current URL path as an array.
\n",
+ "itemtype": "method",
+ "name": "getURLPath",
+ "return": {
+ "description": "path components",
+ "type": "String[]"
+ },
+ "example": [
+ "\n\nfunction setup() {\n var urlPath = getURLPath();\n for (var i = 0; i < urlPath.length; i++) {\n text(urlPath[i], 10, i * 20 + 20);\n }\n}\n
"
+ ],
+ "alt": "no display",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/environment.js",
+ "line": 645,
+ "description": "Gets the current URL params as an Object.
\n",
+ "itemtype": "method",
+ "name": "getURLParams",
+ "return": {
+ "description": "URL params",
+ "type": "Object"
+ },
+ "example": [
+ "\n\n\n// Example: http://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n var params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n}\n\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5",
+ "module": "Environment",
+ "submodule": "Environment"
+ },
+ {
+ "file": "src/core/error_helpers.js",
+ "line": 1,
+ "requires": [
+ "core"
+ ],
+ "class": "p5",
+ "module": "Environment"
+ },
+ {
+ "file": "src/core/error_helpers.js",
+ "line": 405,
+ "description": "Validates parameters\nparam {String} func the name of the function\nparam {Array} args user input arguments
\nexample:\n var a;\n ellipse(10,10,a,5);\nconsole ouput:\n "It looks like ellipse received an empty variable in spot #2."
\nexample:\n ellipse(10,"foo",5,5);\nconsole output:\n "ellipse was expecting a number for parameter #1,\n received "foo" instead."
\n",
+ "class": "p5",
+ "module": "Environment"
+ },
+ {
+ "file": "src/core/error_helpers.js",
+ "line": 457,
+ "description": "Prints out all the colors in the color pallete with white text.\nFor color blindness testing.
\n",
+ "class": "p5",
+ "module": "Environment"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 26,
+ "description": "Underlying HTML element. All normal HTML methods can be called on this.
\n",
+ "example": [
+ "\n\n\ncreateCanvas(300, 500);\nbackground(0, 0, 0, 0);\nvar input = createInput();\ninput.position(20, 225);\nvar inputElem = new p5.Element(input.elt);\ninputElem.style('width:450px;');\ninputElem.value('some string');\n\n
"
+ ],
+ "itemtype": "property",
+ "name": "elt",
+ "readonly": "",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 51,
+ "description": "Attaches the element to the parent specified. A way of setting\n the container for the element. Accepts either a string ID, DOM\n node, or p5.Element. If no arguments given, parent node is returned.\n For more ways to position the canvas, see the\n \n positioning the canvas wiki page.
\n",
+ "itemtype": "method",
+ "name": "parent",
+ "chainable": 1,
+ "example": [
+ "\n \n // in the html file:\n // <div id=\"myContainer\"></div>\n// in the js file:\n var cnv = createCanvas(100, 100);\n cnv.parent('myContainer');\n
\n \n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div1.parent(div0); // use p5.Element\n
\n \n var div0 = createDiv('this is the parent');\n div0.id('apples');\n var div1 = createDiv('this is the child');\n div1.parent('apples'); // use id\n
\n \n var elt = document.getElementById('myParentDiv');\n var div1 = createDiv('this is the child');\n div1.parent(elt); // use element from page\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM",
+ "overloads": [
+ {
+ "line": 51,
+ "params": [
+ {
+ "name": "parent",
+ "description": "the ID, DOM node, or p5.Element\n of desired parent element
\n",
+ "type": "String|p5.Element|Object"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 94,
+ "params": [],
+ "return": {
+ "description": "",
+ "type": "p5.Element"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 116,
+ "description": "Sets the ID of the element. If no ID argument is passed in, it instead\n returns the current ID of the element.
\n",
+ "itemtype": "method",
+ "name": "id",
+ "chainable": 1,
+ "example": [
+ "\n \n function setup() {\n var cnv = createCanvas(100, 100);\n // Assigns a CSS selector ID to\n // the canvas element.\n cnv.id('mycanvas');\n }\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM",
+ "overloads": [
+ {
+ "line": 116,
+ "params": [
+ {
+ "name": "id",
+ "description": "ID of the element
\n",
+ "type": "String"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 138,
+ "params": [],
+ "return": {
+ "description": "the id of the element",
+ "type": "String"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 153,
+ "description": "Adds given class to the element. If no class argument is passed in, it\n instead returns a string containing the current class(es) of the element.
\n",
+ "itemtype": "method",
+ "name": "class",
+ "chainable": 1,
+ "example": [
+ "\n \n function setup() {\n var cnv = createCanvas(100, 100);\n // Assigns a CSS selector class 'small'\n // to the canvas element.\n cnv.class('small');\n }\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM",
+ "overloads": [
+ {
+ "line": 153,
+ "params": [
+ {
+ "name": "class",
+ "description": "class to add
\n",
+ "type": "String"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 175,
+ "params": [],
+ "return": {
+ "description": "the class of the element",
+ "type": "String"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 188,
+ "description": "The .mousePressed() function is called once after every time a\nmouse button is pressed over the element. This can be used to\nattach element specific event listeners.
\n",
+ "itemtype": "method",
+ "name": "mousePressed",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when mouse is\n pressed over the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mousePressed(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any click anywhere\nfunction mousePressed() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 238,
+ "description": "The .doubleClicked() function is called once after every time a\nmouse button is pressed twice over the element. This can be used to\nattach element and action specific event listeners.
\n",
+ "itemtype": "method",
+ "name": "doubleClicked",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when mouse is\n double clicked over the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.Element"
+ },
+ "example": [
+ "\n\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.doubleClicked(changeGray); // attach listener for\n // canvas double click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any double click anywhere\nfunction doubleClicked() {\n d = d + 10;\n}\n\n// this function fires only when cnv is double clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 287,
+ "description": "The .mouseWheel() function is called once after every time a\nmouse wheel is scrolled over the element. This can be used to\nattach element specific event listeners.\n
\nThe function accepts a callback function as argument which will be executed\nwhen the wheel event is triggered on the element, the callback function is\npassed one argument event. The event.deltaY property returns negative\nvalues if the mouse wheel is rotated up or away from the user and positive\nin the other direction. The event.deltaX does the same as event.deltaY\nexcept it reads the horizontal wheel scroll of the mouse wheel.\n
\nOn OS X with "natural" scrolling enabled, the event.deltaY values are\nreversed.
\n",
+ "itemtype": "method",
+ "name": "mouseWheel",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when mouse is\n scrolled over the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseWheel(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with mousewheel movement\n// anywhere on screen\nfunction mouseWheel() {\n g = g + 10;\n}\n\n// this function fires with mousewheel movement\n// over canvas only\nfunction changeSize(event) {\n if (event.deltaY > 0) {\n d = d + 10;\n } else {\n d = d - 10;\n }\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 353,
+ "description": "The .mouseReleased() function is called once after every time a\nmouse button is released over the element. This can be used to\nattach element specific event listeners.
\n",
+ "itemtype": "method",
+ "name": "mouseReleased",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when mouse is\n released over the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseReleased(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// released\nfunction mouseReleased() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// released while on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 406,
+ "description": "The .mouseClicked() function is called once after a mouse button is\npressed and released over the element. This can be used to\nattach element specific event listeners.
\n",
+ "itemtype": "method",
+ "name": "mouseClicked",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when mouse is\n clicked over the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nvar cnv;\nvar d;\nvar g;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseClicked(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// clicked anywhere\nfunction mouseClicked() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// clicked on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 460,
+ "description": "The .mouseMoved() function is called once every time a\nmouse moves over the element. This can be used to attach an\nelement specific event listener.
\n",
+ "itemtype": "method",
+ "name": "mouseMoved",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when a mouse moves\n over the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nvar cnv;\nvar d = 30;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseMoved(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n fill(200);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires when mouse moves anywhere on\n// page\nfunction mouseMoved() {\n g = g + 5;\n if (g > 255) {\n g = 0;\n }\n}\n\n// this function fires when mouse moves over canvas\nfunction changeSize() {\n d = d + 2;\n if (d > 100) {\n d = 0;\n }\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 519,
+ "description": "The .mouseOver() function is called once after every time a\nmouse moves onto the element. This can be used to attach an\nelement specific event listener.
\n",
+ "itemtype": "method",
+ "name": "mouseOver",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when a mouse moves\n onto the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nvar cnv;\nvar d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOver(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 562,
+ "description": "The .changed() function is called when the value of an\nelement changes.\nThis can be used to attach an element specific event listener.
\n",
+ "itemtype": "method",
+ "name": "changed",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when the value of\n an element changes.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nvar sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n var item = sel.value();\n background(200);\n text(\"it's a \" + item + '!', 50, 50);\n}\n
\n\nvar checkbox;\nvar cnv;\n\nfunction setup() {\n checkbox = createCheckbox(' fill');\n checkbox.changed(changeFill);\n cnv = createCanvas(100, 100);\n cnv.position(0, 30);\n noFill();\n}\n\nfunction draw() {\n background(200);\n ellipse(50, 50, 50, 50);\n}\n\nfunction changeFill() {\n if (checkbox.checked()) {\n fill(0);\n } else {\n noFill();\n }\n}\n
"
+ ],
+ "alt": "dropdown: pear, kiwi, grape. When selected text \"its a\" + selection shown.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 629,
+ "description": "The .input() function is called when any user input is\ndetected with an element. The input event is often used\nto detect keystrokes in a input element, or changes on a\nslider element. This can be used to attach an element specific\nevent listener.
\n",
+ "itemtype": "method",
+ "name": "input",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when any user input is\n detected within the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n// Open your console to see the output\nfunction setup() {\n var inp = createInput('');\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent() {\n console.log('you are typing: ', this.value());\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 664,
+ "description": "The .mouseOut() function is called once after every time a\nmouse moves off the element. This can be used to attach an\nelement specific event listener.
\n",
+ "itemtype": "method",
+ "name": "mouseOut",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when a mouse\n moves off of an element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nvar cnv;\nvar d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOut(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 706,
+ "description": "The .touchStarted() function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners.
\n",
+ "itemtype": "method",
+ "name": "touchStarted",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when a touch\n starts over the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchStarted(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchStarted() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 755,
+ "description": "The .touchMoved() function is called once after every time a touch move is\nregistered. This can be used to attach element specific event listeners.
\n",
+ "itemtype": "method",
+ "name": "touchMoved",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when a touch moves over\n the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nvar cnv;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchMoved(changeGray); // attach listener for\n // canvas click only\n g = 100;\n}\n\nfunction draw() {\n background(g);\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 796,
+ "description": "The .touchEnded() function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners.
\n",
+ "itemtype": "method",
+ "name": "touchEnded",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when a touch ends\n over the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchEnded(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchEnded() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n
"
+ ],
+ "alt": "no display.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 846,
+ "description": "The .dragOver() function is called once after every time a\nfile is dragged over the element. This can be used to attach an\nelement specific event listener.
\n",
+ "itemtype": "method",
+ "name": "dragOver",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when a file is\n dragged over the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n// To test this sketch, simply drag a\n// file over the canvas\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragOver(dragOverCallback);\n}\n\n// This function will be called whenever\n// a file is dragged over the canvas\nfunction dragOverCallback() {\n background(240);\n text('Dragged over', width / 2, height / 2);\n}\n
"
+ ],
+ "alt": "nothing displayed",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 884,
+ "description": "The .dragLeave() function is called once after every time a\ndragged file leaves the element area. This can be used to attach an\nelement specific event listener.
\n",
+ "itemtype": "method",
+ "name": "dragLeave",
+ "params": [
+ {
+ "name": "fxn",
+ "description": "function to be fired when a file is\n dragged off the element.\n if false is passed instead, the previously\n firing function will no longer fire.
\n",
+ "type": "Function|Boolean"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n// To test this sketch, simply drag a file\n// over and then out of the canvas area\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragLeave(dragLeaveCallback);\n}\n\n// This function will be called whenever\n// a file is dragged out of the canvas\nfunction dragLeaveCallback() {\n background(240);\n text('Dragged off', width / 2, height / 2);\n}\n
"
+ ],
+ "alt": "nothing displayed",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 922,
+ "description": "The .drop() function is called for each file dropped on the element.\nIt requires a callback that is passed a p5.File object. You can\noptionally pass two callbacks, the first one (required) is triggered\nfor each file dropped when the file is loaded. The second (optional)\nis triggered just once when a file (or files) are dropped.
\n",
+ "itemtype": "method",
+ "name": "drop",
+ "params": [
+ {
+ "name": "callback",
+ "description": "callback triggered when files are dropped.
\n",
+ "type": "Function"
+ },
+ {
+ "name": "fxn",
+ "description": "callback to receive loaded file.
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop image', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction gotFile(file) {\n var img = createImg(file.data).hide();\n // Draw the image onto the canvas\n image(img, 0, 0, width, height);\n}\n
"
+ ],
+ "alt": "Canvas turns into whatever image is dragged/dropped onto it.",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Element.js",
+ "line": 1057,
+ "description": "Helper fxn for sharing pixel methods
\n",
+ "class": "p5.Element",
+ "module": "DOM",
+ "submodule": "DOM"
+ },
+ {
+ "file": "src/core/p5.Graphics.js",
+ "line": 65,
+ "description": "Removes a Graphics object from the page and frees any resources\nassociated with it.
\n",
+ "itemtype": "method",
+ "name": "remove",
+ "example": [
+ "\n\nvar bg;\nfunction setup() {\n bg = createCanvas(100, 100);\n bg.background(0);\n image(bg, 0, 0);\n bg.remove();\n}\n
\n\n\nvar bg;\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n stroke(255);\n fill(0);\n\n // create and draw the background image\n bg = createGraphics(100, 100);\n bg.background(200);\n bg.ellipse(50, 50, 80, 80);\n}\nfunction draw() {\n var t = millis() / 1000;\n // draw the background\n if (bg) {\n image(bg, frameCount % 100, 0);\n image(bg, frameCount % 100 - 100, 0);\n }\n // draw the foreground\n var p = p5.Vector.fromAngle(t, 35).add(50, 50);\n ellipse(p.x, p.y, 30);\n}\nfunction mouseClicked() {\n // remove the background\n if (bg) {\n bg.remove();\n bg = null;\n }\n}\n
"
+ ],
+ "alt": "no image\na multi-colored circle moving back and forth over a scrolling background.",
+ "class": "p5.Graphics",
+ "module": "Rendering",
+ "submodule": "Rendering"
+ },
+ {
+ "file": "src/core/p5.Renderer.js",
+ "line": 113,
+ "description": "Resize our canvas element.
\n",
+ "class": "p5.Renderer",
+ "module": "Rendering",
+ "submodule": "Rendering"
+ },
+ {
+ "file": "src/core/p5.Renderer.js",
+ "line": 182,
+ "description": "Helper fxn to check font type (system or otf)
\n",
+ "class": "p5.Renderer",
+ "module": "Rendering",
+ "submodule": "Rendering"
+ },
+ {
+ "file": "src/core/p5.Renderer.js",
+ "line": 235,
+ "description": "Helper fxn to measure ascent and descent.\nAdapted from http://stackoverflow.com/a/25355178
\n",
+ "class": "p5.Renderer",
+ "module": "Rendering",
+ "submodule": "Rendering"
+ },
+ {
+ "file": "src/core/p5.Renderer2D.js",
+ "line": 10,
+ "description": "p5.Renderer2D\nThe 2D graphics canvas renderer class.\nextends p5.Renderer
\n",
+ "class": "p5",
+ "module": "Rendering"
+ },
+ {
+ "file": "src/core/p5.Renderer2D.js",
+ "line": 395,
+ "description": "Generate a cubic Bezier representing an arc on the unit circle of total\nangle size radians, beginning start radians above the x-axis. Up to\nfour of these curves are combined to make a full arc.
\nSee www.joecridge.me/bezier.pdf for an explanation of the method.
\n",
+ "class": "p5",
+ "module": "Rendering"
+ },
+ {
+ "file": "src/core/rendering.js",
+ "line": 17,
+ "description": "Creates a canvas element in the document, and sets the dimensions of it\nin pixels. This method should be called only once at the start of setup.\nCalling createCanvas more than once in a sketch will result in very\nunpredictable behavior. If you want more than one drawing canvas\nyou could use createGraphics (hidden by default but it can be shown).\n
\nThe system variables width and height are set by the parameters passed\nto this function. If createCanvas() is not used, the window will be\ngiven a default size of 100x100 pixels.\n
\nFor more ways to position the canvas, see the\n\npositioning the canvas wiki page.
\n",
+ "itemtype": "method",
+ "name": "createCanvas",
+ "params": [
+ {
+ "name": "w",
+ "description": "width of the canvas
\n",
+ "type": "Number"
+ },
+ {
+ "name": "h",
+ "description": "height of the canvas
\n",
+ "type": "Number"
+ },
+ {
+ "name": "renderer",
+ "description": "either P2D or WEBGL
\n",
+ "type": "Constant",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.Renderer"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n createCanvas(100, 50);\n background(153);\n line(0, 0, width, height);\n}\n\n
"
+ ],
+ "alt": "Black line extending from top-left of canvas to bottom right.",
+ "class": "p5",
+ "module": "Rendering",
+ "submodule": "Rendering"
+ },
+ {
+ "file": "src/core/rendering.js",
+ "line": 119,
+ "description": "Resizes the canvas to given width and height. The canvas will be cleared\nand draw will be called immediately, allowing the sketch to re-render itself\nin the resized canvas.
\n",
+ "itemtype": "method",
+ "name": "resizeCanvas",
+ "params": [
+ {
+ "name": "w",
+ "description": "width of the canvas
\n",
+ "type": "Number"
+ },
+ {
+ "name": "h",
+ "description": "height of the canvas
\n",
+ "type": "Number"
+ },
+ {
+ "name": "noRedraw",
+ "description": "don't redraw the canvas immediately
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n}\n\nfunction draw() {\n background(0, 100, 200);\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n
"
+ ],
+ "alt": "No image displayed.",
+ "class": "p5",
+ "module": "Rendering",
+ "submodule": "Rendering"
+ },
+ {
+ "file": "src/core/rendering.js",
+ "line": 172,
+ "description": "Removes the default canvas for a p5 sketch that doesn't\nrequire a canvas
\n",
+ "itemtype": "method",
+ "name": "noCanvas",
+ "example": [
+ "\n\n\nfunction setup() {\n noCanvas();\n}\n\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5",
+ "module": "Rendering",
+ "submodule": "Rendering"
+ },
+ {
+ "file": "src/core/rendering.js",
+ "line": 195,
+ "description": "Creates and returns a new p5.Renderer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels.
\n",
+ "itemtype": "method",
+ "name": "createGraphics",
+ "params": [
+ {
+ "name": "w",
+ "description": "width of the offscreen graphics buffer
\n",
+ "type": "Number"
+ },
+ {
+ "name": "h",
+ "description": "height of the offscreen graphics buffer
\n",
+ "type": "Number"
+ },
+ {
+ "name": "renderer",
+ "description": "either P2D or WEBGL\nundefined defaults to p2d
\n",
+ "type": "Constant",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "offscreen graphics buffer",
+ "type": "p5.Graphics"
+ },
+ "example": [
+ "\n\n\nvar pg;\nfunction setup() {\n createCanvas(100, 100);\n pg = createGraphics(100, 100);\n}\nfunction draw() {\n background(200);\n pg.background(100);\n pg.noStroke();\n pg.ellipse(pg.width / 2, pg.height / 2, 50, 50);\n image(pg, 50, 50);\n image(pg, 0, 0, 50, 50);\n}\n\n
"
+ ],
+ "alt": "4 grey squares alternating light and dark grey. White quarter circle mid-left.",
+ "class": "p5",
+ "module": "Rendering",
+ "submodule": "Rendering"
+ },
+ {
+ "file": "src/core/rendering.js",
+ "line": 234,
+ "description": "Blends the pixels in the display window according to the defined mode.\nThere is a choice of the following modes to blend the source pixels (A)\nwith the ones of pixels already in the display window (B):
\n\nBLEND - linear interpolation of colours: C =\nA*factor + B. This is the default blending mode. \nADD - sum of A and B \nDARKEST - only the darkest colour succeeds: C =\nmin(A*factor, B). \nLIGHTEST - only the lightest colour succeeds: C =\nmax(A*factor, B). \nDIFFERENCE - subtract colors from underlying image. \nEXCLUSION - similar to DIFFERENCE, but less\nextreme. \nMULTIPLY - multiply the colors, result will always be\ndarker. \nSCREEN - opposite multiply, uses inverse values of the\ncolors. \nREPLACE - the pixels entirely replace the others and\ndon't utilize alpha (transparency) values. \nOVERLAY - mix of MULTIPLY and SCREEN\n. Multiplies dark values, and screens light values. \nHARD_LIGHT - SCREEN when greater than 50%\ngray, MULTIPLY when lower. \nSOFT_LIGHT - mix of DARKEST and\nLIGHTEST. Works like OVERLAY, but not as harsh.\n \nDODGE - lightens light tones and increases contrast,\nignores darks. \nBURN - darker areas are applied, increasing contrast,\nignores lights. \n
",
+ "itemtype": "method",
+ "name": "blendMode",
+ "params": [
+ {
+ "name": "mode",
+ "description": "blend mode to set for canvas.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL
\n",
+ "type": "Constant"
+ }
+ ],
+ "example": [
+ "\n\n\nblendMode(LIGHTEST);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n\n
\n\n\nblendMode(MULTIPLY);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n\n
"
+ ],
+ "alt": "translucent image thick red & blue diagonal rounded lines intersecting center\nThick red & blue diagonal rounded lines intersecting center. dark at overlap",
+ "class": "p5",
+ "module": "Rendering",
+ "submodule": "Rendering"
+ },
+ {
+ "file": "src/core/shim.js",
+ "line": 70,
+ "description": "shim for Uint8ClampedArray.slice\n(allows arrayCopy to work with pixels[])\nwith thanks to http://halfpapstudios.com/blog/tag/html5-canvas/\nEnumerable set to false to protect for...in from\nUint8ClampedArray.prototype pollution.
\n",
+ "class": "p5",
+ "module": "Rendering"
+ },
+ {
+ "file": "src/core/structure.js",
+ "line": 15,
+ "description": "Stops p5.js from continuously executing the code within draw().\nIf loop() is called, the code in draw() begins to run continuously again.\nIf using noLoop() in setup(), it should be the last line inside the block.\n
\nWhen noLoop() is used, it's not possible to manipulate or access the\nscreen inside event handling functions such as mousePressed() or\nkeyPressed(). Instead, use those functions to call redraw() or loop(),\nwhich will run draw(), which can update the screen properly. This means\nthat when noLoop() has been called, no drawing can happen, and functions\nlike saveFrame() or loadPixels() may not be used.\n
\nNote that if the sketch is resized, redraw() will be called to update\nthe sketch, even after noLoop() has been specified. Otherwise, the sketch\nwould enter an odd state until loop() was called.
\n",
+ "itemtype": "method",
+ "name": "noLoop",
+ "example": [
+ "\n\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n noLoop();\n}\n\nfunction draw() {\n line(10, 10, 90, 90);\n}\n
\n\n\nvar x = 0;\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n noLoop();\n}\n\nfunction mouseReleased() {\n loop();\n}\n
"
+ ],
+ "alt": "113 pixel long line extending from top-left to bottom right of canvas.\nhorizontal line moves slowly from left. Loops but stops on mouse press.",
+ "class": "p5",
+ "module": "Structure",
+ "submodule": "Structure"
+ },
+ {
+ "file": "src/core/structure.js",
+ "line": 77,
+ "description": "By default, p5.js loops through draw() continuously, executing the code\nwithin it. However, the draw() loop may be stopped by calling noLoop().\nIn that case, the draw() loop can be resumed with loop().
\n",
+ "itemtype": "method",
+ "name": "loop",
+ "example": [
+ "\n\nvar x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n loop();\n}\n\nfunction mouseReleased() {\n noLoop();\n}\n
"
+ ],
+ "alt": "horizontal line moves slowly from left. Loops but stops on mouse press.",
+ "class": "p5",
+ "module": "Structure",
+ "submodule": "Structure"
+ },
+ {
+ "file": "src/core/structure.js",
+ "line": 132,
+ "description": "The push() function saves the current drawing style settings and\ntransformations, while pop() restores these settings. Note that these\nfunctions are always used together. They allow you to change the style\nand transformation settings and later return to what you had. When a new\nstate is started with push(), it builds on the current style and transform\ninformation. The push() and pop() functions can be embedded to provide\nmore control. (See the second example for a demonstration.)\n
\npush() stores information related to the current transformation state\nand style settings controlled by the following functions: fill(),\nstroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),\nimageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(),\ntextFont(), textMode(), textSize(), textLeading().
\n",
+ "itemtype": "method",
+ "name": "push",
+ "example": [
+ "\n\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\ntranslate(50, 0);\nellipse(0, 50, 33, 33); // Middle circle\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n
\n\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(33, 50, 33, 33); // Left-middle circle\n\npush(); // Start another new drawing state\nstroke(0, 102, 153);\nellipse(66, 50, 33, 33); // Right-middle circle\npop(); // Restore previous state\n\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n
"
+ ],
+ "alt": "Gold ellipse + thick black outline @center 2 white ellipses on left and right.\n2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.",
+ "class": "p5",
+ "module": "Structure",
+ "submodule": "Structure"
+ },
+ {
+ "file": "src/core/structure.js",
+ "line": 197,
+ "description": "The push() function saves the current drawing style settings and\ntransformations, while pop() restores these settings. Note that these\nfunctions are always used together. They allow you to change the style\nand transformation settings and later return to what you had. When a new\nstate is started with push(), it builds on the current style and transform\ninformation. The push() and pop() functions can be embedded to provide\nmore control. (See the second example for a demonstration.)\n
\npush() stores information related to the current transformation state\nand style settings controlled by the following functions: fill(),\nstroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),\nimageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(),\ntextFont(), textMode(), textSize(), textLeading().
\n",
+ "itemtype": "method",
+ "name": "pop",
+ "example": [
+ "\n\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\ntranslate(50, 0);\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(0, 50, 33, 33); // Middle circle\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n
\n\n\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(33, 50, 33, 33); // Left-middle circle\n\npush(); // Start another new drawing state\nstroke(0, 102, 153);\nellipse(66, 50, 33, 33); // Right-middle circle\npop(); // Restore previous state\n\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n\n
"
+ ],
+ "alt": "Gold ellipse + thick black outline @center 2 white ellipses on left and right.\n2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.",
+ "class": "p5",
+ "module": "Structure",
+ "submodule": "Structure"
+ },
+ {
+ "file": "src/core/structure.js",
+ "line": 271,
+ "description": "Executes the code within draw() one time. This functions allows the\n program to update the display window only when necessary, for example\n when an event registered by mousePressed() or keyPressed() occurs.\n
\n In structuring a program, it only makes sense to call redraw() within\n events such as mousePressed(). This is because redraw() does not run\n draw() immediately (it only sets a flag that indicates an update is\n needed).\n
\n The redraw() function does not work properly when called inside draw().\n To enable/disable animations, use loop() and noLoop().\n
\n In addition you can set the number of redraws per method call. Just\n add an integer as single parameter for the number of redraws.
\n",
+ "itemtype": "method",
+ "name": "redraw",
+ "params": [
+ {
+ "name": "n",
+ "description": "Redraw for n-times. The default value is 1.
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n \n var x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n x += 1;\n redraw();\n }\n
\n\n var x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n x += 1;\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n redraw(5);\n }\n
"
+ ],
+ "alt": "black line on far left of canvas\n black line on far left of canvas",
+ "class": "p5",
+ "module": "Structure",
+ "submodule": "Structure"
+ },
+ {
+ "file": "src/core/transform.js",
+ "line": 13,
+ "description": "Multiplies the current matrix by the one specified through the parameters.\nThis is a powerful operation that can perform the equivalent of translate,\nscale, shear and rotate all at once. You can learn more about transformation\nmatrices on \nWikipedia.
\nThe naming of the arguments here follows the naming of the \nWHATWG specification and corresponds to a\ntransformation matrix of the\nform:
\n\n
\n
\n",
+ "itemtype": "method",
+ "name": "applyMatrix",
+ "params": [
+ {
+ "name": "a",
+ "description": "numbers which define the 2x3 matrix to be multiplied
\n",
+ "type": "Number"
+ },
+ {
+ "name": "b",
+ "description": "numbers which define the 2x3 matrix to be multiplied
\n",
+ "type": "Number"
+ },
+ {
+ "name": "c",
+ "description": "numbers which define the 2x3 matrix to be multiplied
\n",
+ "type": "Number"
+ },
+ {
+ "name": "d",
+ "description": "numbers which define the 2x3 matrix to be multiplied
\n",
+ "type": "Number"
+ },
+ {
+ "name": "e",
+ "description": "numbers which define the 2x3 matrix to be multiplied
\n",
+ "type": "Number"
+ },
+ {
+ "name": "f",
+ "description": "numbers which define the 2x3 matrix to be multiplied
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n // Equivalent to translate(x, y);\n applyMatrix(1, 0, 0, 1, 40 + step, 50);\n rect(0, 0, 50, 50);\n}\n\n
\n\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n translate(50, 50);\n // Equivalent to scale(x, y);\n applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
\n\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, 0, TWO_PI);\n var cos_a = cos(angle);\n var sin_a = sin(angle);\n background(200);\n translate(50, 50);\n // Equivalent to rotate(angle);\n applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
\n\n\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, -PI / 4, PI / 4);\n background(200);\n translate(50, 50);\n // equivalent to shearX(angle);\n var shear_factor = 1 / tan(PI / 2 - angle);\n applyMatrix(1, 0, shear_factor, 1, 0, 0);\n rect(0, 0, 50, 50);\n}\n\n
"
+ ],
+ "alt": "A rectangle translating to the right\nA rectangle shrinking to the center\nA rectangle rotating clockwise about the center\nA rectangle shearing",
+ "class": "p5",
+ "module": "Transform",
+ "submodule": "Transform"
+ },
+ {
+ "file": "src/core/transform.js",
+ "line": 135,
+ "description": "Replaces the current matrix with the identity matrix.
\n",
+ "itemtype": "method",
+ "name": "resetMatrix",
+ "chainable": 1,
+ "example": [
+ "\n\n\ntranslate(50, 50);\napplyMatrix(0.5, 0.5, -0.5, 0.5, 0, 0);\nrect(0, 0, 20, 20);\n// Note that the translate is also reset.\nresetMatrix();\nrect(0, 0, 20, 20);\n\n
"
+ ],
+ "alt": "A rotated retangle in the center with another at the top left corner",
+ "class": "p5",
+ "module": "Transform",
+ "submodule": "Transform"
+ },
+ {
+ "file": "src/core/transform.js",
+ "line": 161,
+ "description": "Rotates a shape the amount specified by the angle parameter. This\nfunction accounts for angleMode, so angles can be entered in either\nRADIANS or DEGREES.\n
\nObjects are always rotated around their relative position to the\norigin and positive numbers rotate objects in a clockwise direction.\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nrotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI).\nAll tranformations are reset when draw() begins again.\n
\nTechnically, rotate() multiplies the current transformation matrix\nby a rotation matrix. This function can be further controlled by\nthe push() and pop().
\n",
+ "itemtype": "method",
+ "name": "rotate",
+ "params": [
+ {
+ "name": "angle",
+ "description": "the angle of rotation, specified in radians\n or degrees, depending on current angleMode
\n",
+ "type": "Number"
+ },
+ {
+ "name": "axis",
+ "description": "(in 3d) the axis to rotate around
\n",
+ "type": "p5.Vector|Number[]",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\ntranslate(width / 2, height / 2);\nrotate(PI / 3.0);\nrect(-26, -26, 52, 52);\n\n
"
+ ],
+ "alt": "white 52x52 rect with black outline at center rotated counter 45 degrees",
+ "class": "p5",
+ "module": "Transform",
+ "submodule": "Transform"
+ },
+ {
+ "file": "src/core/transform.js",
+ "line": 201,
+ "description": "Rotates around X axis.
\n",
+ "itemtype": "method",
+ "name": "rotateX",
+ "params": [
+ {
+ "name": "angle",
+ "description": "the angle of rotation, specified in radians\n or degrees, depending on current angleMode
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateX(millis() / 1000);\n box();\n}\n\n
"
+ ],
+ "alt": "3d box rotating around the x axis.",
+ "class": "p5",
+ "module": "Transform",
+ "submodule": "Transform"
+ },
+ {
+ "file": "src/core/transform.js",
+ "line": 231,
+ "description": "Rotates around Y axis.
\n",
+ "itemtype": "method",
+ "name": "rotateY",
+ "params": [
+ {
+ "name": "angle",
+ "description": "the angle of rotation, specified in radians\n or degrees, depending on current angleMode
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateY(millis() / 1000);\n box();\n}\n\n
"
+ ],
+ "alt": "3d box rotating around the y axis.",
+ "class": "p5",
+ "module": "Transform",
+ "submodule": "Transform"
+ },
+ {
+ "file": "src/core/transform.js",
+ "line": 261,
+ "description": "Rotates around Z axis. Webgl mode only.
\n",
+ "itemtype": "method",
+ "name": "rotateZ",
+ "params": [
+ {
+ "name": "angle",
+ "description": "the angle of rotation, specified in radians\n or degrees, depending on current angleMode
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateZ(millis() / 1000);\n box();\n}\n\n
"
+ ],
+ "alt": "3d box rotating around the z axis.",
+ "class": "p5",
+ "module": "Transform",
+ "submodule": "Transform"
+ },
+ {
+ "file": "src/core/transform.js",
+ "line": 291,
+ "description": "Increases or decreases the size of a shape by expanding and contracting\nvertices. Objects always scale from their relative origin to the\ncoordinate system. Scale values are specified as decimal percentages.\nFor example, the function call scale(2.0) increases the dimension of a\nshape by 200%.\n
\nTransformations apply to everything that happens after and subsequent\ncalls to the function multiply the effect. For example, calling scale(2.0)\nand then scale(1.5) is the same as scale(3.0). If scale() is called\nwithin draw(), the transformation is reset when the loop begins again.\n
\nUsing this function with the z parameter is only available in WEBGL mode.\nThis function can be further controlled with push() and pop().
\n",
+ "itemtype": "method",
+ "name": "scale",
+ "chainable": 1,
+ "example": [
+ "\n\n\ntranslate(width / 2, height / 2);\nrotate(PI / 3.0);\nrect(-26, -26, 52, 52);\n\n
\n\n\n\nrect(30, 20, 50, 50);\nscale(0.5, 1.3);\nrect(30, 20, 50, 50);\n\n
"
+ ],
+ "alt": "white 52x52 rect with black outline at center rotated counter 45 degrees\n2 white rects with black outline- 1 50x50 at center. other 25x65 bottom left",
+ "class": "p5",
+ "module": "Transform",
+ "submodule": "Transform",
+ "overloads": [
+ {
+ "line": 291,
+ "params": [
+ {
+ "name": "s",
+ "description": "percent to scale the object, or percentage to\n scale the object in the x-axis if multiple arguments\n are given
\n",
+ "type": "Number|p5.Vector|Number[]"
+ },
+ {
+ "name": "y",
+ "description": "percent to scale the object in the y-axis
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "z",
+ "description": "percent to scale the object in the z-axis (webgl only)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 336,
+ "params": [
+ {
+ "name": "scales",
+ "description": "per-axis percents to scale the object
\n",
+ "type": "p5.Vector|Number[]"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/core/transform.js",
+ "line": 366,
+ "description": "Shears a shape around the x-axis the amount specified by the angle\nparameter. Angles should be specified in the current angleMode.\nObjects are always sheared around their relative position to the origin\nand positive numbers shear objects in a clockwise direction.\n
\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearX(PI/2) and then shearX(PI/2) is the same as shearX(PI).\nIf shearX() is called within the draw(), the transformation is reset when\nthe loop begins again.\n
\nTechnically, shearX() multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\npush() and pop() functions.
\n",
+ "itemtype": "method",
+ "name": "shearX",
+ "params": [
+ {
+ "name": "angle",
+ "description": "angle of shear specified in radians or degrees,\n depending on current angleMode
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\ntranslate(width / 4, height / 4);\nshearX(PI / 4.0);\nrect(0, 0, 30, 30);\n\n
"
+ ],
+ "alt": "white irregular quadrilateral with black outline at top middle.",
+ "class": "p5",
+ "module": "Transform",
+ "submodule": "Transform"
+ },
+ {
+ "file": "src/core/transform.js",
+ "line": 405,
+ "description": "Shears a shape around the y-axis the amount specified by the angle\nparameter. Angles should be specified in the current angleMode. Objects\nare always sheared around their relative position to the origin and\npositive numbers shear objects in a clockwise direction.\n
\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If\nshearY() is called within the draw(), the transformation is reset when\nthe loop begins again.\n
\nTechnically, shearY() multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\npush() and pop() functions.
\n",
+ "itemtype": "method",
+ "name": "shearY",
+ "params": [
+ {
+ "name": "angle",
+ "description": "angle of shear specified in radians or degrees,\n depending on current angleMode
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\ntranslate(width / 4, height / 4);\nshearY(PI / 4.0);\nrect(0, 0, 30, 30);\n\n
"
+ ],
+ "alt": "white irregular quadrilateral with black outline at middle bottom.",
+ "class": "p5",
+ "module": "Transform",
+ "submodule": "Transform"
+ },
+ {
+ "file": "src/core/transform.js",
+ "line": 444,
+ "description": "Specifies an amount to displace objects within the display window.\nThe x parameter specifies left/right translation, the y parameter\nspecifies up/down translation.\n
\nTransformations are cumulative and apply to everything that happens after\nand subsequent calls to the function accumulates the effect. For example,\ncalling translate(50, 0) and then translate(20, 0) is the same as\ntranslate(70, 0). If translate() is called within draw(), the\ntransformation is reset when the loop begins again. This function can be\nfurther controlled by using push() and pop().
\n",
+ "itemtype": "method",
+ "name": "translate",
+ "chainable": 1,
+ "example": [
+ "\n\n\ntranslate(30, 20);\nrect(0, 0, 55, 55);\n\n
\n\n\n\nrect(0, 0, 55, 55); // Draw rect at original 0,0\ntranslate(30, 20);\nrect(0, 0, 55, 55); // Draw rect at new 0,0\ntranslate(14, 14);\nrect(0, 0, 55, 55); // Draw rect at new 0,0\n\n
\n\n\n\n\nfunction draw() {\n background(200);\n rectMode(CENTER);\n translate(width / 2, height / 2);\n translate(p5.Vector.fromAngle(millis() / 1000, 40));\n rect(0, 0, 20, 20);\n}\n\n
"
+ ],
+ "alt": "white 55x55 rect with black outline at center right.\n3 white 55x55 rects with black outlines at top-l, center-r and bottom-r.\na 20x20 white rect moving in a circle around the canvas",
+ "class": "p5",
+ "module": "Transform",
+ "submodule": "Transform",
+ "overloads": [
+ {
+ "line": 444,
+ "params": [
+ {
+ "name": "x",
+ "description": "left/right translation
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "up/down translation
\n",
+ "type": "Number"
+ },
+ {
+ "name": "z",
+ "description": "forward/backward translation (webgl only)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 498,
+ "params": [
+ {
+ "name": "vector",
+ "description": "the vector to translate by
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/core/vertex.js",
+ "line": 22,
+ "description": "Use the beginContour() and endContour() functions to create negative\nshapes within shapes such as the center of the letter 'O'. beginContour()\nbegins recording vertices for the shape and endContour() stops recording.\nThe vertices that define a negative shape must "wind" in the opposite\ndirection from the exterior shape. First draw vertices for the exterior\nclockwise order, then for internal shapes, draw vertices\nshape in counter-clockwise.\n
\nThese functions can only be used within a beginShape()/endShape() pair and\ntransformations such as translate(), rotate(), and scale() do not work\nwithin a beginContour()/endContour() pair. It is also not possible to use\nother shapes, such as ellipse() or rect() within.
\n",
+ "itemtype": "method",
+ "name": "beginContour",
+ "chainable": 1,
+ "example": [
+ "\n\n\ntranslate(50, 50);\nstroke(255, 0, 0);\nbeginShape();\n// Exterior part of shape, clockwise winding\nvertex(-40, -40);\nvertex(40, -40);\nvertex(40, 40);\nvertex(-40, 40);\n// Interior part of shape, counter-clockwise winding\nbeginContour();\nvertex(-20, -20);\nvertex(-20, 20);\nvertex(20, 20);\nvertex(20, -20);\nendContour();\nendShape(CLOSE);\n\n
"
+ ],
+ "alt": "white rect and smaller grey rect with red outlines in center of canvas.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Vertex"
+ },
+ {
+ "file": "src/core/vertex.js",
+ "line": 70,
+ "description": "Using the beginShape() and endShape() functions allow creating more\ncomplex forms. beginShape() begins recording vertices for a shape and\nendShape() stops recording. The value of the kind parameter tells it which\ntypes of shapes to create from the provided vertices. With no mode\nspecified, the shape can be any irregular polygon.\n
\nThe parameters available for beginShape() are POINTS, LINES, TRIANGLES,\nTRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. After calling the\nbeginShape() function, a series of vertex() commands must follow. To stop\ndrawing the shape, call endShape(). Each shape will be outlined with the\ncurrent stroke color and filled with the fill color.\n
\nTransformations such as translate(), rotate(), and scale() do not work\nwithin beginShape(). It is also not possible to use other shapes, such as\nellipse() or rect() within beginShape().
\n",
+ "itemtype": "method",
+ "name": "beginShape",
+ "params": [
+ {
+ "name": "kind",
+ "description": "either POINTS, LINES, TRIANGLES, TRIANGLE_FAN\n TRIANGLE_STRIP, QUADS, or QUAD_STRIP
\n",
+ "type": "Constant",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n\n
\n\n\n\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n
\n\n\n\nbeginShape(LINES);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n
\n\n\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n
\n\n\n\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n\n
\n\n\n\nbeginShape(TRIANGLES);\nvertex(30, 75);\nvertex(40, 20);\nvertex(50, 75);\nvertex(60, 20);\nvertex(70, 75);\nvertex(80, 20);\nendShape();\n\n
\n\n\n\nbeginShape(TRIANGLE_STRIP);\nvertex(30, 75);\nvertex(40, 20);\nvertex(50, 75);\nvertex(60, 20);\nvertex(70, 75);\nvertex(80, 20);\nvertex(90, 75);\nendShape();\n\n
\n\n\n\nbeginShape(TRIANGLE_FAN);\nvertex(57.5, 50);\nvertex(57.5, 15);\nvertex(92, 50);\nvertex(57.5, 85);\nvertex(22, 50);\nvertex(57.5, 15);\nendShape();\n\n
\n\n\n\nbeginShape(QUADS);\nvertex(30, 20);\nvertex(30, 75);\nvertex(50, 75);\nvertex(50, 20);\nvertex(65, 20);\nvertex(65, 75);\nvertex(85, 75);\nvertex(85, 20);\nendShape();\n\n
\n\n\n\nbeginShape(QUAD_STRIP);\nvertex(30, 20);\nvertex(30, 75);\nvertex(50, 20);\nvertex(50, 75);\nvertex(65, 20);\nvertex(65, 75);\nvertex(85, 20);\nvertex(85, 75);\nendShape();\n\n
\n\n\n\nbeginShape();\nvertex(20, 20);\nvertex(40, 20);\nvertex(40, 40);\nvertex(60, 40);\nvertex(60, 60);\nvertex(20, 60);\nendShape(CLOSE);\n\n
"
+ ],
+ "alt": "white square-shape with black outline in middle-right of canvas.\n4 black points in a square shape in middle-right of canvas.\n2 horizontal black lines. In the top-right and bottom-right of canvas.\n3 line shape with horizontal on top, vertical in middle and horizontal bottom.\nsquare line shape in middle-right of canvas.\n2 white triangle shapes mid-right canvas. left one pointing up and right down.\n5 horizontal interlocking and alternating white triangles in mid-right canvas.\n4 interlocking white triangles in 45 degree rotated square-shape.\n2 white rectangle shapes in mid-right canvas. Both 20x55.\n3 side-by-side white rectangles center rect is smaller in mid-right canvas.\nThick white l-shape with black outline mid-top-left of canvas.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Vertex"
+ },
+ {
+ "file": "src/core/vertex.js",
+ "line": 270,
+ "description": "Specifies vertex coordinates for Bezier curves. Each call to\nbezierVertex() defines the position of two control points and\none anchor point of a Bezier curve, adding a new segment to a\nline or shape.\n
\nThe first time bezierVertex() is used within a\nbeginShape() call, it must be prefaced with a call to vertex()\nto set the first anchor point. This function must be used between\nbeginShape() and endShape() and only when there is no MODE\nparameter specified to beginShape().
\n",
+ "itemtype": "method",
+ "name": "bezierVertex",
+ "params": [
+ {
+ "name": "x2",
+ "description": "x-coordinate for the first control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "y-coordinate for the first control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x3",
+ "description": "x-coordinate for the second control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y3",
+ "description": "y-coordinate for the second control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x4",
+ "description": "x-coordinate for the anchor point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y4",
+ "description": "y-coordinate for the anchor point
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nstrokeWeight(5);\npoint(30, 20);\npoint(80, 20);\npoint(80, 75);\npoint(30, 75);\n\nstrokeWeight(1);\nnoFill();\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 20, 80, 75, 30, 75);\nendShape();\n\n
\n\n\n\nstrokeWeight(5);\npoint(30, 20);\npoint(80, 20);\npoint(80, 75);\npoint(30, 75);\n\nstroke(244, 122, 158);\npoint(50, 80);\npoint(60, 25);\npoint(30, 20);\n\nstroke(0);\nstrokeWeight(1);\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 20, 80, 75, 30, 75);\nbezierVertex(50, 80, 60, 25, 30, 20);\nendShape();\n\n
"
+ ],
+ "alt": "crescent-shaped line in middle of canvas. Points facing left.\nwhite crescent shape in middle of canvas. Points facing left.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Vertex"
+ },
+ {
+ "file": "src/core/vertex.js",
+ "line": 356,
+ "description": "Specifies vertex coordinates for curves. This function may only\nbe used between beginShape() and endShape() and only when there\nis no MODE parameter specified to beginShape().\n
\nThe first and last points in a series of curveVertex() lines will be used to\nguide the beginning and end of a the curve. A minimum of four\npoints is required to draw a tiny curve between the second and\nthird points. Adding a fifth point with curveVertex() will draw\nthe curve between the second, third, and fourth points. The\ncurveVertex() function is an implementation of Catmull-Rom\nsplines.
\n",
+ "itemtype": "method",
+ "name": "curveVertex",
+ "params": [
+ {
+ "name": "x",
+ "description": "x-coordinate of the vertex
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "y-coordinate of the vertex
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nstrokeWeight(5);\npoint(84, 91);\npoint(68, 19);\npoint(21, 17);\npoint(32, 91);\nstrokeWeight(1);\n\nnoFill();\nbeginShape();\ncurveVertex(84, 91);\ncurveVertex(84, 91);\ncurveVertex(68, 19);\ncurveVertex(21, 17);\ncurveVertex(32, 91);\ncurveVertex(32, 91);\nendShape();\n\n
"
+ ],
+ "alt": "Upside-down u-shape line, mid canvas. left point extends beyond canvas view.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Vertex"
+ },
+ {
+ "file": "src/core/vertex.js",
+ "line": 407,
+ "description": "Use the beginContour() and endContour() functions to create negative\nshapes within shapes such as the center of the letter 'O'. beginContour()\nbegins recording vertices for the shape and endContour() stops recording.\nThe vertices that define a negative shape must "wind" in the opposite\ndirection from the exterior shape. First draw vertices for the exterior\nclockwise order, then for internal shapes, draw vertices\nshape in counter-clockwise.\n
\nThese functions can only be used within a beginShape()/endShape() pair and\ntransformations such as translate(), rotate(), and scale() do not work\nwithin a beginContour()/endContour() pair. It is also not possible to use\nother shapes, such as ellipse() or rect() within.
\n",
+ "itemtype": "method",
+ "name": "endContour",
+ "chainable": 1,
+ "example": [
+ "\n\n\ntranslate(50, 50);\nstroke(255, 0, 0);\nbeginShape();\n// Exterior part of shape, clockwise winding\nvertex(-40, -40);\nvertex(40, -40);\nvertex(40, 40);\nvertex(-40, 40);\n// Interior part of shape, counter-clockwise winding\nbeginContour();\nvertex(-20, -20);\nvertex(-20, 20);\nvertex(20, 20);\nvertex(20, -20);\nendContour();\nendShape(CLOSE);\n\n
"
+ ],
+ "alt": "white rect and smaller grey rect with red outlines in center of canvas.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Vertex"
+ },
+ {
+ "file": "src/core/vertex.js",
+ "line": 467,
+ "description": "The endShape() function is the companion to beginShape() and may only be\ncalled after beginShape(). When endshape() is called, all of image data\ndefined since the previous call to beginShape() is written into the image\nbuffer. The constant CLOSE as the value for the MODE parameter to close\nthe shape (to connect the beginning and the end).
\n",
+ "itemtype": "method",
+ "name": "endShape",
+ "params": [
+ {
+ "name": "mode",
+ "description": "use CLOSE to close the shape
\n",
+ "type": "Constant",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nnoFill();\n\nbeginShape();\nvertex(20, 20);\nvertex(45, 20);\nvertex(45, 80);\nendShape(CLOSE);\n\nbeginShape();\nvertex(50, 20);\nvertex(75, 20);\nvertex(75, 80);\nendShape();\n\n
"
+ ],
+ "alt": "Triangle line shape with smallest interior angle on bottom and upside-down L.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Vertex"
+ },
+ {
+ "file": "src/core/vertex.js",
+ "line": 553,
+ "description": "Specifies vertex coordinates for quadratic Bezier curves. Each call to\nquadraticVertex() defines the position of one control points and one\nanchor point of a Bezier curve, adding a new segment to a line or shape.\nThe first time quadraticVertex() is used within a beginShape() call, it\nmust be prefaced with a call to vertex() to set the first anchor point.\nThis function must be used between beginShape() and endShape() and only\nwhen there is no MODE parameter specified to beginShape().
\n",
+ "itemtype": "method",
+ "name": "quadraticVertex",
+ "params": [
+ {
+ "name": "cx",
+ "description": "x-coordinate for the control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "cy",
+ "description": "y-coordinate for the control point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x3",
+ "description": "x-coordinate for the anchor point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y3",
+ "description": "y-coordinate for the anchor point
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nstrokeWeight(5);\npoint(20, 20);\npoint(80, 20);\npoint(50, 50);\n\nnoFill();\nstrokeWeight(1);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nendShape();\n\n
\n\n\n\nstrokeWeight(5);\npoint(20, 20);\npoint(80, 20);\npoint(50, 50);\n\npoint(20, 80);\npoint(80, 80);\npoint(80, 60);\n\nnoFill();\nstrokeWeight(1);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nquadraticVertex(20, 80, 80, 80);\nvertex(80, 60);\nendShape();\n\n
"
+ ],
+ "alt": "arched-shaped black line with 4 pixel thick stroke weight.\nbackwards s-shaped black line with 4 pixel thick stroke weight.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Vertex"
+ },
+ {
+ "file": "src/core/vertex.js",
+ "line": 645,
+ "description": "All shapes are constructed by connecting a series of vertices. vertex()\nis used to specify the vertex coordinates for points, lines, triangles,\nquads, and polygons. It is used exclusively within the beginShape() and\nendShape() functions.
\n",
+ "itemtype": "method",
+ "name": "vertex",
+ "chainable": 1,
+ "example": [
+ "\n\n\nstrokeWeight(3);\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n\n
"
+ ],
+ "alt": "8 points making 4 lines",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "Vertex",
+ "overloads": [
+ {
+ "line": 645,
+ "params": [
+ {
+ "name": "x",
+ "description": "x-coordinate of the vertex
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "y-coordinate of the vertex
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 732,
+ "params": [
+ {
+ "name": "x",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z",
+ "description": "z-coordinate of the vertex
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "u",
+ "description": "the vertex's texture u-coordinate
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "v",
+ "description": "the vertex's texture v-coordinate
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 16,
+ "description": "Creates a new instance of p5.StringDict using the key, value pair\n or object you provide.
\n",
+ "itemtype": "method",
+ "name": "createStringDict",
+ "return": {
+ "description": "",
+ "type": "p5.StringDict"
+ },
+ "example": [
+ "\n \n \n function setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n }\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Dictionary",
+ "overloads": [
+ {
+ "line": 16,
+ "params": [
+ {
+ "name": "key",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "value",
+ "description": "",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.StringDict"
+ }
+ },
+ {
+ "line": 36,
+ "params": [
+ {
+ "name": "object",
+ "description": "object
\n",
+ "type": "Object"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.StringDict"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 47,
+ "description": "Creates a new instance of p5.NumberDict using the key, value pair\n or object you provide.
\n",
+ "itemtype": "method",
+ "name": "createNumberDict",
+ "return": {
+ "description": "",
+ "type": "p5.NumberDict"
+ },
+ "example": [
+ "\n \n \n function setup() {\n var myDictionary = createNumberDict(100, 42);\n print(myDictionary.hasKey(100)); // logs true to console\n }\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Dictionary",
+ "overloads": [
+ {
+ "line": 47,
+ "params": [
+ {
+ "name": "key",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "value",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.NumberDict"
+ }
+ },
+ {
+ "line": 67,
+ "params": [
+ {
+ "name": "object",
+ "description": "object
\n",
+ "type": "Object"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.NumberDict"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 97,
+ "description": "Returns the number of key-value pairs currently in Dictionary object
\n",
+ "itemtype": "method",
+ "name": "size",
+ "return": {
+ "description": "the number of key-value pairs in Dictionary object",
+ "type": "Integer"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createNumberDict(1, 10);\n myDictionary.create(2, 20);\n myDictionary.create(3, 30);\n print(myDictionary.size()); // value of amt is 3\n}\n
\n"
+ ],
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 119,
+ "description": "Returns true if key exists in Dictionary\notherwise returns false
\n",
+ "itemtype": "method",
+ "name": "hasKey",
+ "params": [
+ {
+ "name": "key",
+ "description": "that you want to access
\n",
+ "type": "Number|String"
+ }
+ ],
+ "return": {
+ "description": "whether that key exists in Dictionary",
+ "type": "Boolean"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n}\n
\n"
+ ],
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 142,
+ "description": "Returns value stored at supplied key.
\n",
+ "itemtype": "method",
+ "name": "get",
+ "params": [
+ {
+ "name": "key",
+ "description": "that you want to access
\n",
+ "type": "Number|String"
+ }
+ ],
+ "return": {
+ "description": "the value stored at that key",
+ "type": "Number|String"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n var myValue = myDictionary.get('p5');\n print(myValue === 'js'); // logs true to console\n}\n
\n"
+ ],
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 169,
+ "description": "Changes the value of key if in it already exists in\nin the Dictionary otherwise makes a new key-value pair
\n",
+ "itemtype": "method",
+ "name": "set",
+ "params": [
+ {
+ "name": "key",
+ "description": "",
+ "type": "Number|String"
+ },
+ {
+ "name": "value",
+ "description": "",
+ "type": "Number|String"
+ }
+ ],
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.set('p5', 'JS');\n myDictionary.print();\n // above logs \"key: p5 - value: JS\" to console\n}\n
\n"
+ ],
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 198,
+ "description": "private helper function to handle the user passing objects in\nduring construction or calls to create()
\n",
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 209,
+ "description": "Creates a key-value pair in the Dictionary
\n",
+ "itemtype": "method",
+ "name": "create",
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n
"
+ ],
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary",
+ "overloads": [
+ {
+ "line": 209,
+ "params": [
+ {
+ "name": "key",
+ "description": "",
+ "type": "Number|String"
+ },
+ {
+ "name": "value",
+ "description": "",
+ "type": "Number|String"
+ }
+ ]
+ },
+ {
+ "line": 227,
+ "params": [
+ {
+ "name": "obj",
+ "description": "key/value pair
\n",
+ "type": "Object"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 245,
+ "description": "Empties Dictionary of all key-value pairs
\n",
+ "itemtype": "method",
+ "name": "clear",
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // prints 'true'\n myDictionary.clear();\n print(myDictionary.hasKey('p5')); // prints 'false'\n}\n\n
"
+ ],
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 265,
+ "description": "Removes a key-value pair in the Dictionary
\n",
+ "itemtype": "method",
+ "name": "remove",
+ "params": [
+ {
+ "name": "key",
+ "description": "for the pair to remove
\n",
+ "type": "Number|String"
+ }
+ ],
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n myDictionary.remove('p5');\n myDictionary.print();\n // above logs \"key: happy value: coding\" to console\n}\n
\n"
+ ],
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 295,
+ "description": "Logs the list of items currently in the Dictionary to the console
\n",
+ "itemtype": "method",
+ "name": "print",
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n\n
"
+ ],
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 319,
+ "description": "Converts the Dictionary into a CSV file for local\nstorage.
\n",
+ "itemtype": "method",
+ "name": "saveTable",
+ "example": [
+ "\n\n\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveTable('beatles');\n });\n\n
"
+ ],
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 352,
+ "description": "Converts the Dictionary into a JSON file for local\nstorage.
\n",
+ "itemtype": "method",
+ "name": "saveJSON",
+ "example": [
+ "\n\n\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveJSON('beatles');\n });\n\n
"
+ ],
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 378,
+ "description": "private helper function to ensure that the user passed in valid\nvalues for the Dictionary type
\n",
+ "class": "p5.TypedDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 423,
+ "description": "private helper function to ensure that the user passed in valid\nvalues for the Dictionary type
\n",
+ "class": "p5.NumberDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 432,
+ "description": "Add to a value stored at a certain key\nThe sum is stored in that location in the Dictionary.
\n",
+ "itemtype": "method",
+ "name": "add",
+ "params": [
+ {
+ "name": "Key",
+ "description": "for value you wish to add to
\n",
+ "type": "Number"
+ },
+ {
+ "name": "Amount",
+ "description": "to add to the value
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 5);\n myDictionary.add(2, 2);\n console.log(myDictionary.get(2)); // logs 7 to console.\n}\n
\n\n"
+ ],
+ "class": "p5.NumberDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 460,
+ "description": "Subtract from a value stored at a certain key\nThe difference is stored in that location in the Dictionary.
\n",
+ "itemtype": "method",
+ "name": "sub",
+ "params": [
+ {
+ "name": "Key",
+ "description": "for value you wish to subtract from
\n",
+ "type": "Number"
+ },
+ {
+ "name": "Amount",
+ "description": "to subtract from the value
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 5);\n myDictionary.sub(2, 2);\n console.log(myDictionary.get(2)); // logs 3 to console.\n}\n
\n\n"
+ ],
+ "class": "p5.NumberDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 484,
+ "description": "Multiply a value stored at a certain key\nThe product is stored in that location in the Dictionary.
\n",
+ "itemtype": "method",
+ "name": "mult",
+ "params": [
+ {
+ "name": "Key",
+ "description": "for value you wish to multiply
\n",
+ "type": "Number"
+ },
+ {
+ "name": "Amount",
+ "description": "to multiply the value by
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 4);\n myDictionary.mult(2, 2);\n console.log(myDictionary.get(2)); // logs 8 to console.\n}\n
\n\n"
+ ],
+ "class": "p5.NumberDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 512,
+ "description": "Divide a value stored at a certain key\nThe quotient is stored in that location in the Dictionary.
\n",
+ "itemtype": "method",
+ "name": "div",
+ "params": [
+ {
+ "name": "Key",
+ "description": "for value you wish to divide
\n",
+ "type": "Number"
+ },
+ {
+ "name": "Amount",
+ "description": "to divide the value by
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createNumberDict(2, 8);\n myDictionary.div(2, 2);\n console.log(myDictionary.get(2)); // logs 4 to console.\n}\n
\n\n"
+ ],
+ "class": "p5.NumberDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 540,
+ "description": "private helper function for finding lowest or highest value\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'
\n",
+ "class": "p5.NumberDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 563,
+ "description": "Return the lowest value.
\n",
+ "itemtype": "method",
+ "name": "minValue",
+ "return": {
+ "description": "",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n var lowestValue = myDictionary.minValue(); // value is -10\n print(lowestValue);\n}\n
\n"
+ ],
+ "class": "p5.NumberDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 584,
+ "description": "Return the highest value.
\n",
+ "itemtype": "method",
+ "name": "maxValue",
+ "return": {
+ "description": "",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n var highestValue = myDictionary.maxValue(); // value is 3\n print(highestValue);\n}\n
\n"
+ ],
+ "class": "p5.NumberDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 605,
+ "description": "private helper function for finding lowest or highest key\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'
\n",
+ "class": "p5.NumberDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 628,
+ "description": "Return the lowest key.
\n",
+ "itemtype": "method",
+ "name": "minKey",
+ "return": {
+ "description": "",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n var lowestKey = myDictionary.minKey(); // value is 1.2\n print(lowestKey);\n}\n
\n"
+ ],
+ "class": "p5.NumberDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/data/p5.TypedDict.js",
+ "line": 649,
+ "description": "Return the highest key.
\n",
+ "itemtype": "method",
+ "name": "maxKey",
+ "return": {
+ "description": "",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n var highestKey = myDictionary.maxKey(); // value is 4\n print(highestKey);\n}\n
\n"
+ ],
+ "class": "p5.NumberDict",
+ "module": "Data",
+ "submodule": "Dictionary"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 12,
+ "description": "The system variable deviceOrientation always contains the orientation of\nthe device. The value of this variable will either be set 'landscape'\nor 'portrait'. If no data is available it will be set to 'undefined'.\neither LANDSCAPE or PORTRAIT.
\n",
+ "itemtype": "property",
+ "name": "deviceOrientation",
+ "type": "Constant",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 23,
+ "description": "The system variable accelerationX always contains the acceleration of the\ndevice along the x axis. Value is represented as meters per second squared.
\n",
+ "itemtype": "property",
+ "name": "accelerationX",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 32,
+ "description": "The system variable accelerationY always contains the acceleration of the\ndevice along the y axis. Value is represented as meters per second squared.
\n",
+ "itemtype": "property",
+ "name": "accelerationY",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 41,
+ "description": "The system variable accelerationZ always contains the acceleration of the\ndevice along the z axis. Value is represented as meters per second squared.
\n",
+ "itemtype": "property",
+ "name": "accelerationZ",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 50,
+ "description": "The system variable pAccelerationX always contains the acceleration of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n",
+ "itemtype": "property",
+ "name": "pAccelerationX",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 60,
+ "description": "The system variable pAccelerationY always contains the acceleration of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n",
+ "itemtype": "property",
+ "name": "pAccelerationY",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 70,
+ "description": "The system variable pAccelerationZ always contains the acceleration of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as meters per second squared.
\n",
+ "itemtype": "property",
+ "name": "pAccelerationZ",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 91,
+ "description": "The system variable rotationX always contains the rotation of the\ndevice along the x axis. Value is represented as 0 to +/-180 degrees.\n
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n",
+ "example": [
+ "\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
"
+ ],
+ "itemtype": "property",
+ "name": "rotationX",
+ "type": "Number",
+ "readonly": "",
+ "alt": "red horizontal line right, green vertical line bottom. black background.",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 125,
+ "description": "The system variable rotationY always contains the rotation of the\ndevice along the y axis. Value is represented as 0 to +/-90 degrees.\n
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n",
+ "example": [
+ "\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
"
+ ],
+ "itemtype": "property",
+ "name": "rotationY",
+ "type": "Number",
+ "readonly": "",
+ "alt": "red horizontal line right, green vertical line bottom. black background.",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 158,
+ "description": "The system variable rotationZ always contains the rotation of the\ndevice along the z axis. Value is represented as 0 to 359 degrees.\n
\nUnlike rotationX and rotationY, this variable is available for devices\nwith a built-in compass only.\n
\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.
\n",
+ "example": [
+ "\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n\n
"
+ ],
+ "itemtype": "property",
+ "name": "rotationZ",
+ "type": "Number",
+ "readonly": "",
+ "alt": "red horizontal line right, green vertical line bottom. black background.",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 194,
+ "description": "The system variable pRotationX always contains the rotation of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as 0 to +/-180 degrees.\n
\npRotationX can also be used with rotationX to determine the rotate\ndirection of the device along the X-axis.
\n",
+ "example": [
+ "\n\n\n// A simple if statement looking at whether\n// rotationX - pRotationX < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nvar rX = rotationX + 180;\nvar pRX = pRotationX + 180;\n\nif ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {\n rotateDirection = 'clockwise';\n} else if (rX - pRX < 0 || rX - pRX > 270) {\n rotateDirection = 'counter-clockwise';\n}\n\nprint(rotateDirection);\n\n
"
+ ],
+ "alt": "no image to display.",
+ "itemtype": "property",
+ "name": "pRotationX",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 239,
+ "description": "The system variable pRotationY always contains the rotation of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as 0 to +/-90 degrees.\n
\npRotationY can also be used with rotationY to determine the rotate\ndirection of the device along the Y-axis.
\n",
+ "example": [
+ "\n\n\n// A simple if statement looking at whether\n// rotationY - pRotationY < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nvar rY = rotationY + 180;\nvar pRY = pRotationY + 180;\n\nif ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {\n rotateDirection = 'clockwise';\n} else if (rY - pRY < 0 || rY - pRY > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n\n
"
+ ],
+ "alt": "no image to display.",
+ "itemtype": "property",
+ "name": "pRotationY",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 283,
+ "description": "The system variable pRotationZ always contains the rotation of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as 0 to 359 degrees.\n
\npRotationZ can also be used with rotationZ to determine the rotate\ndirection of the device along the Z-axis.
\n",
+ "example": [
+ "\n\n\n// A simple if statement looking at whether\n// rotationZ - pRotationZ < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\nif (\n (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||\n rotationZ - pRotationZ < -270\n) {\n rotateDirection = 'clockwise';\n} else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n\n
"
+ ],
+ "alt": "no image to display.",
+ "itemtype": "property",
+ "name": "pRotationZ",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 341,
+ "itemtype": "property",
+ "name": "turnAxis",
+ "type": "String",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 350,
+ "description": "The setMoveThreshold() function is used to set the movement threshold for\nthe deviceMoved() function. The default threshold is set to 0.5.
\n",
+ "itemtype": "method",
+ "name": "setMoveThreshold",
+ "params": [
+ {
+ "name": "value",
+ "description": "The threshold value
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 362,
+ "description": "The setShakeThreshold() function is used to set the movement threshold for\nthe deviceShaken() function. The default threshold is set to 30.
\n",
+ "itemtype": "method",
+ "name": "setShakeThreshold",
+ "params": [
+ {
+ "name": "value",
+ "description": "The threshold value
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 374,
+ "description": "The deviceMoved() function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to\n0.5.
\n",
+ "itemtype": "method",
+ "name": "deviceMoved",
+ "example": [
+ "\n\n\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
"
+ ],
+ "alt": "50x50 black rect in center of canvas. turns white on mobile when device moves",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 405,
+ "description": "The deviceTurned() function is called when the device rotates by\nmore than 90 degrees continuously.\n
\nThe axis that triggers the deviceTurned() method is stored in the turnAxis\nvariable. The deviceTurned() method can be locked to trigger on any axis:\nX, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'.
\n",
+ "itemtype": "method",
+ "name": "deviceTurned",
+ "example": [
+ "\n\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees\n// to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n}\n\n
\n\n\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n\n
"
+ ],
+ "alt": "50x50 black rect in center of canvas. turns white on mobile when device turns\n50x50 black rect in center of canvas. turns white on mobile when x-axis turns",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/acceleration.js",
+ "line": 464,
+ "description": "The deviceShaken() function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.
\n",
+ "itemtype": "method",
+ "name": "deviceShaken",
+ "example": [
+ "\n\n\n// Run this example on a mobile device\n// Shake the device to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceShaken() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
"
+ ],
+ "alt": "50x50 black rect in center of canvas. turns white on mobile when device shakes",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Acceleration"
+ },
+ {
+ "file": "src/events/keyboard.js",
+ "line": 18,
+ "description": "The boolean system variable keyIsPressed is true if any key is pressed\nand false if no keys are pressed.
\n",
+ "itemtype": "property",
+ "name": "keyIsPressed",
+ "type": "Boolean",
+ "readonly": "",
+ "example": [
+ "\n\n\nfunction draw() {\n if (keyIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n rect(25, 25, 50, 50);\n}\n\n
"
+ ],
+ "alt": "50x50 white rect that turns black on keypress.",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Keyboard"
+ },
+ {
+ "file": "src/events/keyboard.js",
+ "line": 45,
+ "description": "The system variable key always contains the value of the most recent\nkey on the keyboard that was typed. To get the proper capitalization, it\nis best to use it within keyTyped(). For non-ASCII keys, use the keyCode\nvariable.
\n",
+ "itemtype": "property",
+ "name": "key",
+ "type": "String",
+ "readonly": "",
+ "example": [
+ "\n\n// Click any key to display it!\n// (Not Guaranteed to be Case Sensitive)\nfunction setup() {\n fill(245, 123, 158);\n textSize(50);\n}\n\nfunction draw() {\n background(200);\n text(key, 33, 65); // Display last key pressed.\n}\n
"
+ ],
+ "alt": "canvas displays any key value that is pressed in pink font.",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Keyboard"
+ },
+ {
+ "file": "src/events/keyboard.js",
+ "line": 74,
+ "description": "The variable keyCode is used to detect special keys such as BACKSPACE,\nDELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW,\nDOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\nYou can also check for custom keys by looking up the keyCode of any key\non a site like this: keycode.info.
\n",
+ "itemtype": "property",
+ "name": "keyCode",
+ "type": "Integer",
+ "readonly": "",
+ "example": [
+ "\n\nvar fillVal = 126;\nfunction draw() {\n fill(fillVal);\n rect(25, 25, 50, 50);\n}\n\nfunction keyPressed() {\n if (keyCode === UP_ARROW) {\n fillVal = 255;\n } else if (keyCode === DOWN_ARROW) {\n fillVal = 0;\n }\n return false; // prevent default\n}\n
"
+ ],
+ "alt": "Grey rect center. turns white when up arrow pressed and black when down",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Keyboard"
+ },
+ {
+ "file": "src/events/keyboard.js",
+ "line": 107,
+ "description": "The keyPressed() function is called once every time a key is pressed. The\nkeyCode for the key that was pressed is stored in the keyCode variable.\n
\nFor non-ASCII keys, use the keyCode variable. You can check if the keyCode\nequals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,\nOPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\n
\nFor ASCII keys that was pressed is stored in the key variable. However, it\ndoes not distinguish between uppercase and lowercase. For this reason, it\nis recommended to use keyTyped() to read the key variable, in which the\ncase of the variable will be distinguished.\n
\nBecause of how operating systems handle key repeats, holding down a key\nmay cause multiple calls to keyTyped() (and keyReleased() as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.
\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
\n",
+ "itemtype": "method",
+ "name": "keyPressed",
+ "example": [
+ "\n\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n}\n\n
\n\n\nfunction keyPressed() {\n // Do something\n return false; // prevent any default behaviour\n}\n\n
"
+ ],
+ "alt": "black rect center. turns white when key pressed and black when released\nblack rect center. turns white when left arrow pressed and black when right.",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Keyboard"
+ },
+ {
+ "file": "src/events/keyboard.js",
+ "line": 198,
+ "description": "The keyReleased() function is called once every time a key is released.\nSee key and keyCode for more information.
\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
\n",
+ "itemtype": "method",
+ "name": "keyReleased",
+ "example": [
+ "\n\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n return false; // prevent any default behavior\n}\n\n
"
+ ],
+ "alt": "black rect center. turns white when key pressed and black when pressed again",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Keyboard"
+ },
+ {
+ "file": "src/events/keyboard.js",
+ "line": 254,
+ "description": "The keyTyped() function is called once every time a key is pressed, but\naction keys such as Ctrl, Shift, and Alt are ignored. The most recent\nkey pressed will be stored in the key variable.\n
\nBecause of how operating systems handle key repeats, holding down a key\nwill cause multiple calls to keyTyped() (and keyReleased() as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.
\nBrowsers may have different default behaviors attached to various key\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.
\n",
+ "itemtype": "method",
+ "name": "keyTyped",
+ "example": [
+ "\n\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyTyped() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // uncomment to prevent any default behavior\n // return false;\n}\n\n
"
+ ],
+ "alt": "black rect center. turns white when 'a' key typed and black when 'b' pressed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Keyboard"
+ },
+ {
+ "file": "src/events/keyboard.js",
+ "line": 308,
+ "description": "The onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released.
\n",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Keyboard"
+ },
+ {
+ "file": "src/events/keyboard.js",
+ "line": 318,
+ "description": "The keyIsDown() function checks if the key is currently down, i.e. pressed.\nIt can be used if you have an object that moves, and you want several keys\nto be able to affect its behaviour simultaneously, such as moving a\nsprite diagonally. You can put in any number representing the keyCode of\nthe key, or use any of the variable keyCode names listed\nhere.
\n",
+ "itemtype": "method",
+ "name": "keyIsDown",
+ "params": [
+ {
+ "name": "code",
+ "description": "The key to check for.
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "whether key is down or not",
+ "type": "Boolean"
+ },
+ "example": [
+ "\n\nvar x = 100;\nvar y = 100;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n if (keyIsDown(LEFT_ARROW)) {\n x -= 5;\n }\n\n if (keyIsDown(RIGHT_ARROW)) {\n x += 5;\n }\n\n if (keyIsDown(UP_ARROW)) {\n y -= 5;\n }\n\n if (keyIsDown(DOWN_ARROW)) {\n y += 5;\n }\n\n clear();\n fill(255, 0, 0);\n ellipse(x, y, 50, 50);\n}\n
"
+ ],
+ "alt": "50x50 red ellipse moves left, right, up and down with arrow presses.",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Keyboard"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 22,
+ "description": "The system variable mouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the canvas. If touch is\nused instead of mouse input, mouseX will hold the x value of the most\nrecent touch point.
\n",
+ "itemtype": "property",
+ "name": "mouseX",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\n\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(mouseX, 0, mouseX, 100);\n}\n\n
"
+ ],
+ "alt": "horizontal black line moves left and right with mouse x-position",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 48,
+ "description": "The system variable mouseY always contains the current vertical position\nof the mouse, relative to (0, 0) of the canvas. If touch is\nused instead of mouse input, mouseY will hold the y value of the most\nrecent touch point.
\n",
+ "itemtype": "property",
+ "name": "mouseY",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\n\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(0, mouseY, 100, mouseY);\n}\n\n
"
+ ],
+ "alt": "vertical black line moves up and down with mouse y-position",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 74,
+ "description": "The system variable pmouseX always contains the horizontal position of\nthe mouse or finger in the frame previous to the current frame, relative to\n(0, 0) of the canvas.
\n",
+ "itemtype": "property",
+ "name": "pmouseX",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\n\n// Move the mouse across the canvas to leave a trail\nfunction setup() {\n //slow down the frameRate to make it more visible\n frameRate(10);\n}\n\nfunction draw() {\n background(244, 248, 252);\n line(mouseX, mouseY, pmouseX, pmouseY);\n print(pmouseX + ' -> ' + mouseX);\n}\n\n
"
+ ],
+ "alt": "line trail is created from cursor movements. faster movement make longer line.",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 105,
+ "description": "The system variable pmouseY always contains the vertical position of the\nmouse or finger in the frame previous to the current frame, relative to\n(0, 0) of the canvas.
\n",
+ "itemtype": "property",
+ "name": "pmouseY",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n //draw a square only if the mouse is not moving\n if (mouseY === pmouseY && mouseX === pmouseX) {\n rect(20, 20, 60, 60);\n }\n\n print(pmouseY + ' -> ' + mouseY);\n}\n\n
"
+ ],
+ "alt": "60x60 black rect center, fuschia background. rect flickers on mouse movement",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 135,
+ "description": "The system variable winMouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the window.
\n",
+ "itemtype": "property",
+ "name": "winMouseX",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the horizontal mouse position\n //rela tive to the window\n myCanvas.position(winMouseX + 1, windowHeight / 2);\n\n //the y of the square is relative to the canvas\n rect(20, mouseY, 60, 60);\n}\n\n
"
+ ],
+ "alt": "60x60 black rect y moves with mouse y and fuschia canvas moves with mouse x",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 172,
+ "description": "The system variable winMouseY always contains the current vertical\nposition of the mouse, relative to (0, 0) of the window.
\n",
+ "itemtype": "property",
+ "name": "winMouseY",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the vertical mouse position\n //rel ative to the window\n myCanvas.position(windowWidth / 2, winMouseY + 1);\n\n //the x of the square is relative to the canvas\n rect(mouseX, 20, 60, 60);\n}\n\n
"
+ ],
+ "alt": "60x60 black rect x moves with mouse x and fuschia canvas y moves with mouse y",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 209,
+ "description": "The system variable pwinMouseX always contains the horizontal position\nof the mouse in the frame previous to the current frame, relative to\n(0, 0) of the window.
\n",
+ "itemtype": "property",
+ "name": "pwinMouseX",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current x position is the horizontal mouse speed\n var speed = abs(winMouseX - pwinMouseX);\n //change the size of the circle\n //according to the horizontal speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n\n
"
+ ],
+ "alt": "fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 249,
+ "description": "The system variable pwinMouseY always contains the vertical position of\nthe mouse in the frame previous to the current frame, relative to (0, 0)\nof the window.
\n",
+ "itemtype": "property",
+ "name": "pwinMouseY",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\n\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current y position is the vertical mouse speed\n var speed = abs(winMouseY - pwinMouseY);\n //change the size of the circle\n //according to the vertical speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n\n
"
+ ],
+ "alt": "fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 290,
+ "description": "Processing automatically tracks if the mouse button is pressed and which\nbutton is pressed. The value of the system variable mouseButton is either\nLEFT, RIGHT, or CENTER depending on which button was pressed last.\nWarning: different browsers may track mouseButton differently.
\n",
+ "itemtype": "property",
+ "name": "mouseButton",
+ "type": "Constant",
+ "readonly": "",
+ "example": [
+ "\n\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed) {\n if (mouseButton === LEFT) {\n ellipse(50, 50, 50, 50);\n }\n if (mouseButton === RIGHT) {\n rect(25, 25, 50, 50);\n }\n if (mouseButton === CENTER) {\n triangle(23, 75, 50, 20, 78, 75);\n }\n }\n\n print(mouseButton);\n}\n\n
"
+ ],
+ "alt": "50x50 black ellipse appears on center of fuschia canvas on mouse click/press.",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 329,
+ "description": "The boolean system variable mouseIsPressed is true if the mouse is pressed\nand false if not.
\n",
+ "itemtype": "property",
+ "name": "mouseIsPressed",
+ "type": "Boolean",
+ "readonly": "",
+ "example": [
+ "\n\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed) {\n ellipse(50, 50, 50, 50);\n } else {\n rect(25, 25, 50, 50);\n }\n\n print(mouseIsPressed);\n}\n\n
"
+ ],
+ "alt": "black 50x50 rect becomes ellipse with mouse click/press. fuschia background.",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 418,
+ "description": "The mouseMoved() function is called every time the mouse moves and a mouse\nbutton is not pressed.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
\n",
+ "itemtype": "method",
+ "name": "mouseMoved",
+ "example": [
+ "\n\n\n// Move the mouse across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n\n\nfunction mouseMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
"
+ ],
+ "alt": "black 50x50 rect becomes lighter with mouse movements until white then resets\nno image displayed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 462,
+ "description": "The mouseDragged() function is called once every time the mouse moves and\na mouse button is pressed. If no mouseDragged() function is defined, the\ntouchMoved() function will be called instead if it is defined.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
\n",
+ "itemtype": "method",
+ "name": "mouseDragged",
+ "example": [
+ "\n\n\n// Drag the mouse across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseDragged() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n\n\nfunction mouseDragged() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
"
+ ],
+ "alt": "black 50x50 rect turns lighter with mouse click and drag until white, resets\nno image displayed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 532,
+ "description": "The mousePressed() function is called once after every time a mouse button\nis pressed. The mouseButton variable (see the related reference entry)\ncan be used to determine which button has been pressed. If no\nmousePressed() function is defined, the touchStarted() function will be\ncalled instead if it is defined.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
\n",
+ "itemtype": "method",
+ "name": "mousePressed",
+ "example": [
+ "\n\n\n// Click within the image to change\n// the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mousePressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n\n\nfunction mousePressed() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
"
+ ],
+ "alt": "black 50x50 rect turns white with mouse click/press.\nno image displayed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 598,
+ "description": "The mouseReleased() function is called every time a mouse button is\nreleased. If no mouseReleased() function is defined, the touchEnded()\nfunction will be called instead if it is defined.
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
\n",
+ "itemtype": "method",
+ "name": "mouseReleased",
+ "example": [
+ "\n\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n\n\nfunction mouseReleased() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
"
+ ],
+ "alt": "black 50x50 rect turns white with mouse click/press.\nno image displayed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 665,
+ "description": "The mouseClicked() function is called once after a mouse button has been\npressed and then released.
\nBrowsers handle clicks differently, so this function is only guaranteed to be\nrun when the left mouse button is clicked. To handle other mouse buttons\nbeing pressed or released, see mousePressed() or mouseReleased().
\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add "return false" to the end of the method.
\n",
+ "itemtype": "method",
+ "name": "mouseClicked",
+ "example": [
+ "\n\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction mouseClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n\n\nfunction mouseClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
"
+ ],
+ "alt": "black 50x50 rect turns white with mouse click/press.\nno image displayed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 724,
+ "description": "The doubleClicked() function is executed every time a event\nlistener has detected a dblclick event which is a part of the\nDOM L3 specification. The doubleClicked event is fired when a\npointing device button (usually a mouse's primary button)\nis clicked twice on a single element. For more info on the\ndblclick event refer to mozilla's documentation here:\nhttps://developer.mozilla.org/en-US/docs/Web/Events/dblclick
\n",
+ "itemtype": "method",
+ "name": "doubleClicked",
+ "example": [
+ "\n\n\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been double clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction doubleClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n\n\nfunction doubleClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
"
+ ],
+ "alt": "black 50x50 rect turns white with mouse doubleClick/press.\nno image displayed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/mouse.js",
+ "line": 782,
+ "description": "The function mouseWheel() is executed every time a vertical mouse wheel\nevent is detected either triggered by an actual mouse wheel or by a\ntouchpad.
\nThe event.delta property returns the amount the mouse wheel\nhave scrolled. The values can be positive or negative depending on the\nscroll direction (on OS X with "natural" scrolling enabled, the signs\nare inverted).
\nBrowsers may have different default behaviors attached to various\nmouse events. To prevent any default behavior for this event, add\n"return false" to the end of the method.
\nDue to the current support of the "wheel" event on Safari, the function\nmay only work as expected if "return false" is included while using Safari.
\n",
+ "itemtype": "method",
+ "name": "mouseWheel",
+ "example": [
+ "\n\n\nvar pos = 25;\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n rect(25, pos, 50, 50);\n}\n\nfunction mouseWheel(event) {\n print(event.delta);\n //move the square according to the vertical scroll amount\n pos += event.delta;\n //uncomment to block page scrolling\n //return false;\n}\n\n
"
+ ],
+ "alt": "black 50x50 rect moves up and down with vertical scroll. fuschia background",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Mouse"
+ },
+ {
+ "file": "src/events/touch.js",
+ "line": 12,
+ "description": "The system variable touches[] contains an array of the positions of all\ncurrent touch points, relative to (0, 0) of the canvas, and IDs identifying a\nunique touch as it moves. Each element in the array is an object with x, y,\nand id properties.
\nThe touches[] array is not supported on Safari and IE on touch-based\ndesktops (laptops).
\n",
+ "itemtype": "property",
+ "name": "touches",
+ "type": "Object[]",
+ "readonly": "",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Touch"
+ },
+ {
+ "file": "src/events/touch.js",
+ "line": 57,
+ "description": "The touchStarted() function is called once after every time a touch is\nregistered. If no touchStarted() function is defined, the mousePressed()\nfunction will be called instead if it is defined.
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.
\n",
+ "itemtype": "method",
+ "name": "touchStarted",
+ "example": [
+ "\n\n\n// Touch within the image to change\n// the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchStarted() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n\n\nfunction touchStarted() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
"
+ ],
+ "alt": "50x50 black rect turns white with touch event.\nno image displayed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Touch"
+ },
+ {
+ "file": "src/events/touch.js",
+ "line": 120,
+ "description": "The touchMoved() function is called every time a touch move is registered.\nIf no touchMoved() function is defined, the mouseDragged() function will\nbe called instead if it is defined.
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.
\n",
+ "itemtype": "method",
+ "name": "touchMoved",
+ "example": [
+ "\n\n\n// Move your finger across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n\n
\n\n\n\nfunction touchMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
"
+ ],
+ "alt": "50x50 black rect turns lighter with touch until white. resets\nno image displayed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Touch"
+ },
+ {
+ "file": "src/events/touch.js",
+ "line": 182,
+ "description": "The touchEnded() function is called every time a touch ends. If no\ntouchEnded() function is defined, the mouseReleased() function will be\ncalled instead if it is defined.
\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add "return false"\nto the end of the method.
\n",
+ "itemtype": "method",
+ "name": "touchEnded",
+ "example": [
+ "\n\n\n// Release touch within the image to\n// change the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchEnded() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n\n
\n\n\n\nfunction touchEnded() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n\n
"
+ ],
+ "alt": "50x50 black rect turns white with touch.\nno image displayed",
+ "class": "p5",
+ "module": "Events",
+ "submodule": "Touch"
+ },
+ {
+ "file": "src/image/filters.js",
+ "line": 3,
+ "description": "This module defines the filters for use with image buffers.
\nThis module is basically a collection of functions stored in an object\nas opposed to modules. The functions are destructive, modifying\nthe passed in canvas rather than creating a copy.
\nGenerally speaking users of this module will use the Filters.apply method\non a canvas to create an effect.
\nA number of functions are borrowed/adapted from\nhttp://www.html5rocks.com/en/tutorials/canvas/imagefilters/\nor the java processing implementation.
\n",
+ "class": "p5",
+ "module": "Events"
+ },
+ {
+ "file": "src/image/image.js",
+ "line": 8,
+ "description": "This module defines the p5 methods for the p5.Image class\nfor drawing images to the main display canvas.
\n",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/image.js",
+ "line": 18,
+ "description": "Creates a new p5.Image (the datatype for storing images). This provides a\nfresh buffer of pixels to play with. Set the size of the buffer with the\nwidth and height parameters.\n
\n.pixels gives access to an array containing the values for all the pixels\nin the display window.\nThese values are numbers. This array is the size (including an appropriate\nfactor for the pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. See .pixels for\nmore info. It may also be simpler to use set() or get().\n
\nBefore accessing the pixels of an image, the data must loaded with the\nloadPixels() function. After the array data has been modified, the\nupdatePixels() function must be run to update the changes.
\n",
+ "itemtype": "method",
+ "name": "createImage",
+ "params": [
+ {
+ "name": "width",
+ "description": "width in pixels
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "height",
+ "description": "height in pixels
\n",
+ "type": "Integer"
+ }
+ ],
+ "return": {
+ "description": "the p5.Image object",
+ "type": "p5.Image"
+ },
+ "example": [
+ "\n\n\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
\n\n\n\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n\n
\n\n\n\nvar pink = color(255, 102, 204);\nvar img = createImage(66, 66);\nimg.loadPixels();\nvar d = pixelDensity();\nvar halfImage = 4 * (width * d) * (height / 2 * d);\nfor (var i = 0; i < halfImage; i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
"
+ ],
+ "alt": "66x66 dark turquoise rect in center of canvas.\n2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas\nno image displayed",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/image.js",
+ "line": 98,
+ "description": "Save the current canvas as an image. In Safari, this will open the\nimage in the window and the user must provide their own\nfilename on save-as. Other browsers will either save the\nfile immediately, or prompt the user with a dialogue window.
\n",
+ "itemtype": "method",
+ "name": "saveCanvas",
+ "example": [
+ "\n \n function setup() {\n var c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas(c, 'myCanvas', 'jpg');\n }\n
\n \n // note that this example has the same result as above\n // if no canvas is specified, defaults to main canvas\n function setup() {\n var c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas('myCanvas', 'jpg');\n\n // all of the following are valid\n saveCanvas(c, 'myCanvas', 'jpg');\n saveCanvas(c, 'myCanvas.jpg');\n saveCanvas(c, 'myCanvas');\n saveCanvas(c);\n saveCanvas('myCanvas', 'png');\n saveCanvas('myCanvas');\n saveCanvas();\n }\n
"
+ ],
+ "alt": "no image displayed\n no image displayed\n no image displayed",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Image",
+ "overloads": [
+ {
+ "line": 98,
+ "params": [
+ {
+ "name": "selectedCanvas",
+ "description": "a variable\n representing a specific html5 canvas (optional)
\n",
+ "type": "p5.Element|HTMLCanvasElement"
+ },
+ {
+ "name": "filename",
+ "description": "",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "extension",
+ "description": "'jpg' or 'png'
\n",
+ "type": "String",
+ "optional": true
+ }
+ ]
+ },
+ {
+ "line": 142,
+ "params": [
+ {
+ "name": "filename",
+ "description": "",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "extension",
+ "description": "",
+ "type": "String",
+ "optional": true
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/image/image.js",
+ "line": 193,
+ "description": "Capture a sequence of frames that can be used to create a movie.\nAccepts a callback. For example, you may wish to send the frames\nto a server where they can be stored or converted into a movie.\nIf no callback is provided, the browser will pop up save dialogues in an\nattempt to download all of the images that have just been created. With the\ncallback provided the image data isn't saved by default but instead passed\nas an argument to the callback function as an array of objects, with the\nsize of array equal to the total number of frames.
\nNote that saveFrames() will only save the first 15 frames of an animation.\nTo export longer animations, you might look into a library like\nccapture.js.
\n",
+ "itemtype": "method",
+ "name": "saveFrames",
+ "params": [
+ {
+ "name": "filename",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "extension",
+ "description": "'jpg' or 'png'
\n",
+ "type": "String"
+ },
+ {
+ "name": "duration",
+ "description": "Duration in seconds to save the frames for.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "framerate",
+ "description": "Framerate to save the frames in.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "callback",
+ "description": "A callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData - an\n image/octet-stream, filename and extension.
\n",
+ "type": "Function(Array)",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\n function draw() {\n background(mouseX);\n }\n\n function mousePressed() {\n saveFrames('out', 'png', 1, 25, function(data) {\n print(data);\n });\n }\n
"
+ ],
+ "alt": "canvas background goes from light to dark with mouse x.",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/loading_displaying.js",
+ "line": 17,
+ "description": "Loads an image from a path and creates a p5.Image from it.\n
\nThe image may not be immediately available for rendering\nIf you want to ensure that the image is ready before doing\nanything with it, place the loadImage() call in preload().\nYou may also supply a callback function to handle the image when it's ready.\n
\nThe path to the image should be relative to the HTML file\nthat links in your sketch. Loading an image from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.
\n",
+ "itemtype": "method",
+ "name": "loadImage",
+ "params": [
+ {
+ "name": "path",
+ "description": "Path of the image to be loaded
\n",
+ "type": "String"
+ },
+ {
+ "name": "successCallback",
+ "description": "Function to be called once\n the image is loaded. Will be passed the\n p5.Image.
\n",
+ "type": "function(p5.Image)",
+ "optional": true
+ },
+ {
+ "name": "failureCallback",
+ "description": "called with event error if\n the image fails to load.
\n",
+ "type": "Function(Event)",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "the p5.Image object",
+ "type": "p5.Image"
+ },
+ "example": [
+ "\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n}\n\n
\n\n\nfunction setup() {\n // here we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', function(img) {\n image(img, 0, 0);\n });\n}\n\n
"
+ ],
+ "alt": "image of the underside of a white umbrella and grided ceililng above\nimage of the underside of a white umbrella and grided ceililng above",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Loading & Displaying"
+ },
+ {
+ "file": "src/image/loading_displaying.js",
+ "line": 125,
+ "description": "Draw an image to the p5.js canvas.
\nThis function can be used with different numbers of parameters. The\nsimplest use requires only three parameters: img, x, and y—where (x, y) is\nthe position of the image. Two more parameters can optionally be added to\nspecify the width and height of the image.
\nThis function can also be used with all eight Number parameters. To\ndifferentiate between all these parameters, p5.js uses the language of\n"destination rectangle" (which corresponds to "dx", "dy", etc.) and "source\nimage" (which corresponds to "sx", "sy", etc.) below. Specifying the\n"source image" dimensions can be useful when you want to display a\nsubsection of the source image instead of the whole thing. Here's a diagram\nto explain further:\n
\n",
+ "itemtype": "method",
+ "name": "image",
+ "example": [
+ "\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height\n image(img, 0, 0);\n}\n\n
\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n background(50);\n // Top-left corner of the img is at (10, 10)\n // Width and height are 50 x 50\n image(img, 10, 10, 50, 50);\n}\n\n
\n\n\nfunction setup() {\n // Here, we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', function(img) {\n image(img, 0, 0);\n });\n}\n\n
\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/gradient.png');\n}\nfunction setup() {\n // 1. Background image\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height, 100 x 100\n image(img, 0, 0);\n // 2. Top right image\n // Top-left corner of destination rectangle is at (50, 0)\n // Destination rectangle width and height are 40 x 20\n // The next parameters are relative to the source image:\n // - Starting at position (50, 50) on the source image, capture a 50 x 50\n // subsection\n // - Draw this subsection to fill the dimensions of the destination rectangle\n image(img, 50, 0, 40, 20, 50, 50, 50, 50);\n}\n\n
"
+ ],
+ "alt": "image of the underside of a white umbrella and gridded ceiling above\nimage of the underside of a white umbrella and gridded ceiling above",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Loading & Displaying",
+ "overloads": [
+ {
+ "line": 125,
+ "params": [
+ {
+ "name": "img",
+ "description": "the image to display
\n",
+ "type": "p5.Image|p5.Element"
+ },
+ {
+ "name": "x",
+ "description": "the x-coordinate of the top-left corner of the image
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "the y-coordinate of the top-left corner of the image
\n",
+ "type": "Number"
+ },
+ {
+ "name": "width",
+ "description": "the width to draw the image
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "height",
+ "description": "the height to draw the image
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ]
+ },
+ {
+ "line": 213,
+ "params": [
+ {
+ "name": "img",
+ "description": "",
+ "type": "p5.Image|p5.Element"
+ },
+ {
+ "name": "dx",
+ "description": "the x-coordinate of the destination\n rectangle in which to draw the source image
\n",
+ "type": "Number"
+ },
+ {
+ "name": "dy",
+ "description": "the y-coordinate of the destination\n rectangle in which to draw the source image
\n",
+ "type": "Number"
+ },
+ {
+ "name": "dWidth",
+ "description": "the width of the destination rectangle
\n",
+ "type": "Number"
+ },
+ {
+ "name": "dHeight",
+ "description": "the height of the destination rectangle
\n",
+ "type": "Number"
+ },
+ {
+ "name": "sx",
+ "description": "the x-coordinate of the subsection of the source\nimage to draw into the destination rectangle
\n",
+ "type": "Number"
+ },
+ {
+ "name": "sy",
+ "description": "the y-coordinate of the subsection of the source\nimage to draw into the destination rectangle
\n",
+ "type": "Number"
+ },
+ {
+ "name": "sWidth",
+ "description": "the width of the subsection of the\n source image to draw into the destination\n rectangle
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "sHeight",
+ "description": "the height of the subsection of the\n source image to draw into the destination rectangle
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/image/loading_displaying.js",
+ "line": 296,
+ "description": "Sets the fill value for displaying images. Images can be tinted to\nspecified colors or made transparent by including an alpha value.\n
\nTo apply transparency to an image without affecting its color, use\nwhite as the tint color and specify an alpha value. For instance,\ntint(255, 128) will make an image 50% transparent (assuming the default\nalpha range of 0-255, which can be changed with colorMode()).\n
\nThe value for the gray parameter must be less than or equal to the current\nmaximum value as specified by colorMode(). The default maximum value is\n255.
\n",
+ "itemtype": "method",
+ "name": "tint",
+ "example": [
+ "\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204); // Tint blue\n image(img, 50, 0);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204, 126); // Tint blue and set transparency\n image(img, 50, 0);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(255, 126); // Apply transparency without changing color\n image(img, 50, 0);\n}\n\n
"
+ ],
+ "alt": "2 side by side images of umbrella and ceiling, one image with blue tint\nImages of umbrella and ceiling, one half of image with blue tint\n2 side by side images of umbrella and ceiling, one image translucent",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Loading & Displaying",
+ "overloads": [
+ {
+ "line": 296,
+ "params": [
+ {
+ "name": "v1",
+ "description": "red or hue value relative to\n the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "green or saturation value\n relative to the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v3",
+ "description": "blue or brightness value\n relative to the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "alpha",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ]
+ },
+ {
+ "line": 369,
+ "params": [
+ {
+ "name": "value",
+ "description": "a color string
\n",
+ "type": "String"
+ }
+ ]
+ },
+ {
+ "line": 374,
+ "params": [
+ {
+ "name": "gray",
+ "description": "a gray value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "alpha",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ]
+ },
+ {
+ "line": 380,
+ "params": [
+ {
+ "name": "values",
+ "description": "an array containing the red,green,blue &\n and alpha components of the color
\n",
+ "type": "Number[]"
+ }
+ ]
+ },
+ {
+ "line": 386,
+ "params": [
+ {
+ "name": "color",
+ "description": "the tint color
\n",
+ "type": "p5.Color"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/image/loading_displaying.js",
+ "line": 396,
+ "description": "Removes the current fill value for displaying images and reverts to\ndisplaying images with their original hues.
\n",
+ "itemtype": "method",
+ "name": "noTint",
+ "example": [
+ "\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n tint(0, 153, 204); // Tint blue\n image(img, 0, 0);\n noTint(); // Disable tint\n image(img, 50, 0);\n}\n\n
"
+ ],
+ "alt": "2 side by side images of bricks, left image with blue tint",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Loading & Displaying"
+ },
+ {
+ "file": "src/image/loading_displaying.js",
+ "line": 462,
+ "description": "Set image mode. Modifies the location from which images are drawn by\nchanging the way in which parameters given to image() are interpreted.\nThe default mode is imageMode(CORNER), which interprets the second and\nthird parameters of image() as the upper-left corner of the image. If\ntwo additional parameters are specified, they are used to set the image's\nwidth and height.\n
\nimageMode(CORNERS) interprets the second and third parameters of image()\nas the location of one corner, and the fourth and fifth parameters as the\nopposite corner.\n
\nimageMode(CENTER) interprets the second and third parameters of image()\nas the image's center point. If two additional parameters are specified,\nthey are used to set the image's width and height.
\n",
+ "itemtype": "method",
+ "name": "imageMode",
+ "params": [
+ {
+ "name": "mode",
+ "description": "either CORNER, CORNERS, or CENTER
\n",
+ "type": "Constant"
+ }
+ ],
+ "example": [
+ "\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNER);\n image(img, 10, 10, 50, 50);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNERS);\n image(img, 10, 10, 90, 40);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CENTER);\n image(img, 50, 50, 80, 80);\n}\n\n
"
+ ],
+ "alt": "small square image of bricks\nhorizontal rectangle image of bricks\nlarge square image of bricks",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Loading & Displaying"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 9,
+ "description": "This module defines the p5.Image class and P5 methods for\ndrawing images to the main display canvas.
\n",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 90,
+ "description": "Image width.
\n",
+ "itemtype": "property",
+ "name": "width",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (var i = 0; i < img.width; i++) {\n var c = img.get(i, img.height / 2);\n stroke(c);\n line(i, height / 2, i, height);\n }\n}\n
"
+ ],
+ "alt": "rocky mountains in top and horizontal lines in corresponding colors in bottom.",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 117,
+ "description": "Image height.
\n",
+ "itemtype": "property",
+ "name": "height",
+ "type": "Number",
+ "readonly": "",
+ "example": [
+ "\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (var i = 0; i < img.height; i++) {\n var c = img.get(img.width / 2, i);\n stroke(c);\n line(0, i, width / 2, i);\n }\n}\n
"
+ ],
+ "alt": "rocky mountains on right and vertical lines in corresponding colors on left.",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 151,
+ "description": "Array containing the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh denisty displays may have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. With\npixelDensity = 2, there will be 160,000. The first four values\n(indices 0-3) in the array will be the R, G, B, A values of the pixel at\n(0, 0). The second four values (indices 4-7) will contain the R, G, B, A\nvalues of the pixel at (1, 0). More generally, to set values for a pixel\nat (x, y):
\nvar d = pixelDensity();\nfor (var i = 0; i < d; i++) {\n for (var j = 0; j < d; j++) {\n // loop over\n idx = 4 * ((y * d + j) * width * d + (x * d + i));\n pixels[idx] = r;\n pixels[idx+1] = g;\n pixels[idx+2] = b;\n pixels[idx+3] = a;\n }\n}\n
\n
\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.
\n",
+ "itemtype": "property",
+ "name": "pixels",
+ "type": "Number[]",
+ "example": [
+ "\n\n\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
\n\n\nvar pink = color(255, 102, 204);\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < 4 * (width * height / 2); i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n\n
"
+ ],
+ "alt": "66x66 turquoise rect in center of canvas\n66x66 pink rect in center of canvas",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 221,
+ "description": "Helper fxn for sharing pixel methods
\n",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 230,
+ "description": "Loads the pixels data for this image into the [pixels] attribute.
\n",
+ "itemtype": "method",
+ "name": "loadPixels",
+ "example": [
+ "\n\nvar myImage;\nvar halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * width * height / 2;\n for (var i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0);\n}\n
"
+ ],
+ "alt": "2 images of rocky mountains vertically stacked",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 266,
+ "description": "Updates the backing canvas for this image with the contents of\nthe [pixels] array.
\n",
+ "itemtype": "method",
+ "name": "updatePixels",
+ "example": [
+ "\n\nvar myImage;\nvar halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * width * height / 2;\n for (var i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0);\n}\n
"
+ ],
+ "alt": "2 images of rocky mountains vertically stacked",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image",
+ "overloads": [
+ {
+ "line": 266,
+ "params": [
+ {
+ "name": "x",
+ "description": "x-offset of the target update area for the\n underlying canvas
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "y",
+ "description": "y-offset of the target update area for the\n underlying canvas
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "w",
+ "description": "height of the target update area for the\n underlying canvas
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "h",
+ "description": "height of the target update area for the\n underlying canvas
\n",
+ "type": "Integer"
+ }
+ ]
+ },
+ {
+ "line": 306,
+ "params": []
+ }
+ ]
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 314,
+ "description": "Get a region of pixels from an image.
\nIf no params are passed, those whole image is returned,\nif x and y are the only params passed a single pixel is extracted\nif all params are passed a rectangle region is extracted and a p5.Image\nis returned.
\nReturns undefined if the region is outside the bounds of the image
\n",
+ "itemtype": "method",
+ "name": "get",
+ "params": [
+ {
+ "name": "x",
+ "description": "x-coordinate of the pixel
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "y",
+ "description": "y-coordinate of the pixel
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "w",
+ "description": "width
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "h",
+ "description": "height
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "color of pixel at x,y in array format\n [R, G, B, A] or p5.Image",
+ "type": "Number[]|Color|p5.Image"
+ },
+ "example": [
+ "\n\nvar myImage;\nvar c;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(myImage);\n noStroke();\n c = myImage.get(60, 90);\n fill(c);\n rect(25, 25, 50, 50);\n}\n\n//get() returns color here\n
"
+ ],
+ "alt": "image of rocky mountains with 50x50 green rect in front",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 359,
+ "description": "Set the color of a single pixel or write an image into\nthis p5.Image.
\nNote that for a large number of pixels this will\nbe slower than directly manipulating the pixels array\nand then calling updatePixels().
\n",
+ "itemtype": "method",
+ "name": "set",
+ "params": [
+ {
+ "name": "x",
+ "description": "x-coordinate of the pixel
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "y-coordinate of the pixel
\n",
+ "type": "Number"
+ },
+ {
+ "name": "a",
+ "description": "grayscale value | pixel array |\n a p5.Color | image to copy
\n",
+ "type": "Number|Number[]|Object"
+ }
+ ],
+ "example": [
+ "\n\n\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n\n
"
+ ],
+ "alt": "2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 397,
+ "description": "Resize the image to a new width and height. To make the image scale\nproportionally, use 0 as the value for the wide or high parameter.\nFor instance, to make the width of an image 150 pixels, and change\nthe height using the same proportion, use resize(150, 0).
\n",
+ "itemtype": "method",
+ "name": "resize",
+ "params": [
+ {
+ "name": "width",
+ "description": "the resized image width
\n",
+ "type": "Number"
+ },
+ {
+ "name": "height",
+ "description": "the resized image height
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\nvar img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(img, 0, 0);\n}\n\nfunction mousePressed() {\n img.resize(50, 100);\n}\n
"
+ ],
+ "alt": "image of rocky mountains. zoomed in",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 481,
+ "description": "Copies a region of pixels from one image to another. If no\nsrcImage is specified this is used as the source. If the source\nand destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.
\n",
+ "itemtype": "method",
+ "name": "copy",
+ "example": [
+ "\n\nvar photo;\nvar bricks;\nvar x;\nvar y;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n x = bricks.width / 2;\n y = bricks.height / 2;\n photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);\n image(photo, 0, 0);\n}\n
"
+ ],
+ "alt": "image of rocky mountains and smaller image on top of bricks at top left",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image",
+ "overloads": [
+ {
+ "line": 481,
+ "params": [
+ {
+ "name": "srcImage",
+ "description": "source image
\n",
+ "type": "p5.Image|p5.Element"
+ },
+ {
+ "name": "sx",
+ "description": "X coordinate of the source's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sy",
+ "description": "Y coordinate of the source's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sw",
+ "description": "source image width
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sh",
+ "description": "source image height
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dx",
+ "description": "X coordinate of the destination's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dy",
+ "description": "Y coordinate of the destination's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dw",
+ "description": "destination image width
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dh",
+ "description": "destination image height
\n",
+ "type": "Integer"
+ }
+ ]
+ },
+ {
+ "line": 522,
+ "params": [
+ {
+ "name": "sx",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sy",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sw",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sh",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dx",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dy",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dw",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dh",
+ "description": "",
+ "type": "Integer"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 561,
+ "description": "Masks part of an image from displaying by loading another\nimage and using it's alpha channel as an alpha channel for\nthis image.
\n",
+ "itemtype": "method",
+ "name": "mask",
+ "params": [
+ {
+ "name": "srcImage",
+ "description": "source image
\n",
+ "type": "p5.Image"
+ }
+ ],
+ "example": [
+ "\n\nvar photo, maskImage;\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n maskImage = loadImage('assets/mask2.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n photo.mask(maskImage);\n image(photo, 0, 0);\n}\n
"
+ ],
+ "alt": "image of rocky mountains with white at right\n\n\nhttp://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 624,
+ "description": "Applies an image filter to a p5.Image
\n",
+ "itemtype": "method",
+ "name": "filter",
+ "params": [
+ {
+ "name": "filterType",
+ "description": "either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter
\n",
+ "type": "Constant"
+ },
+ {
+ "name": "filterParam",
+ "description": "an optional parameter unique\n to each filter, see above
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\nvar photo1;\nvar photo2;\n\nfunction preload() {\n photo1 = loadImage('assets/rockies.jpg');\n photo2 = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n photo2.filter('gray');\n image(photo1, 0, 0);\n image(photo2, width / 2, 0);\n}\n
"
+ ],
+ "alt": "2 images of rocky mountains left one in color, right in black and white",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 660,
+ "description": "Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation.
\n",
+ "itemtype": "method",
+ "name": "blend",
+ "example": [
+ "\n\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\n\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
\n\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n
"
+ ],
+ "alt": "image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image",
+ "overloads": [
+ {
+ "line": 660,
+ "params": [
+ {
+ "name": "srcImage",
+ "description": "source image
\n",
+ "type": "p5.Image"
+ },
+ {
+ "name": "sx",
+ "description": "X coordinate of the source's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sy",
+ "description": "Y coordinate of the source's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sw",
+ "description": "source image width
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sh",
+ "description": "source image height
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dx",
+ "description": "X coordinate of the destination's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dy",
+ "description": "Y coordinate of the destination's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dw",
+ "description": "destination image width
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dh",
+ "description": "destination image height
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "blendMode",
+ "description": "the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
\nAvailable blend modes are: normal | multiply | screen | overlay |\n darken | lighten | color-dodge | color-burn | hard-light |\n soft-light | difference | exclusion | hue | saturation |\n color | luminosity
\nhttp://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
\n",
+ "type": "Constant"
+ }
+ ]
+ },
+ {
+ "line": 739,
+ "params": [
+ {
+ "name": "sx",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sy",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sw",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sh",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dx",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dy",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dw",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dh",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "blendMode",
+ "description": "",
+ "type": "Constant"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/image/p5.Image.js",
+ "line": 782,
+ "description": "Saves the image to a file and force the browser to download it.\nAccepts two strings for filename and file extension\nSupports png (default) and jpg.
\n",
+ "itemtype": "method",
+ "name": "save",
+ "params": [
+ {
+ "name": "filename",
+ "description": "give your file a name
\n",
+ "type": "String"
+ },
+ {
+ "name": "extension",
+ "description": "'png' or 'jpg'
\n",
+ "type": "String"
+ }
+ ],
+ "example": [
+ "\n\nvar photo;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(photo, 0, 0);\n}\n\nfunction keyTyped() {\n if (key === 's') {\n photo.save('photo', 'png');\n }\n}\n
"
+ ],
+ "alt": "image of rocky mountains.",
+ "class": "p5.Image",
+ "module": "Image",
+ "submodule": "Image"
+ },
+ {
+ "file": "src/image/pixels.js",
+ "line": 14,
+ "description": "Uint8ClampedArray\ncontaining the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh density displays will have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. On a\nretina display, there will be 160,000.\n
\nThe first four values (indices 0-3) in the array will be the R, G, B, A\nvalues of the pixel at (0, 0). The second four values (indices 4-7) will\ncontain the R, G, B, A values of the pixel at (1, 0). More generally, to\nset values for a pixel at (x, y):
\nvar d = pixelDensity();\nfor (var i = 0; i < d; i++) {\n for (var j = 0; j < d; j++) {\n // loop over\n idx = 4 * ((y * d + j) * width * d + (x * d + i));\n pixels[idx] = r;\n pixels[idx+1] = g;\n pixels[idx+2] = b;\n pixels[idx+3] = a;\n }\n}\n
\nWhile the above method is complex, it is flexible enough to work with\nany pixelDensity. Note that set() will automatically take care of\nsetting all the appropriate values in pixels[] for a given (x, y) at\nany pixelDensity, but the performance may not be as fast when lots of\nmodifications are made to the pixel array.\n
\nBefore accessing this array, the data must loaded with the loadPixels()\nfunction. After the array data has been modified, the updatePixels()\nfunction must be run to update the changes.\n
\nNote that this is not a standard javascript array. This means that\nstandard javascript functions such as slice() or\narrayCopy() do not\nwork.
",
+ "itemtype": "property",
+ "name": "pixels",
+ "type": "Number[]",
+ "example": [
+ "\n\n\nvar pink = color(255, 102, 204);\nloadPixels();\nvar d = pixelDensity();\nvar halfImage = 4 * (width * d) * (height / 2 * d);\nfor (var i = 0; i < halfImage; i += 4) {\n pixels[i] = red(pink);\n pixels[i + 1] = green(pink);\n pixels[i + 2] = blue(pink);\n pixels[i + 3] = alpha(pink);\n}\nupdatePixels();\n\n
"
+ ],
+ "alt": "top half of canvas pink, bottom grey",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Pixels"
+ },
+ {
+ "file": "src/image/pixels.js",
+ "line": 83,
+ "description": "Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation.
\n",
+ "itemtype": "method",
+ "name": "blend",
+ "example": [
+ "\n\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n}\n
\n\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n}\n
\n\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n}\n
"
+ ],
+ "alt": "image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Pixels",
+ "overloads": [
+ {
+ "line": 83,
+ "params": [
+ {
+ "name": "srcImage",
+ "description": "source image
\n",
+ "type": "p5.Image"
+ },
+ {
+ "name": "sx",
+ "description": "X coordinate of the source's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sy",
+ "description": "Y coordinate of the source's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sw",
+ "description": "source image width
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sh",
+ "description": "source image height
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dx",
+ "description": "X coordinate of the destination's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dy",
+ "description": "Y coordinate of the destination's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dw",
+ "description": "destination image width
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dh",
+ "description": "destination image height
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "blendMode",
+ "description": "the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
\n",
+ "type": "Constant"
+ }
+ ]
+ },
+ {
+ "line": 156,
+ "params": [
+ {
+ "name": "sx",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sy",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sw",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sh",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dx",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dy",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dw",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dh",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "blendMode",
+ "description": "",
+ "type": "Constant"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/image/pixels.js",
+ "line": 177,
+ "description": "Copies a region of the canvas to another region of the canvas\nand copies a region of pixels from an image used as the srcImg parameter\ninto the canvas srcImage is specified this is used as the source. If\nthe source and destination regions aren't the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.
\n",
+ "itemtype": "method",
+ "name": "copy",
+ "example": [
+ "\n\nvar img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(img);\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n stroke(255);\n noFill();\n // Rectangle shows area being copied\n rect(7, 22, 10, 10);\n}\n
"
+ ],
+ "alt": "image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Pixels",
+ "overloads": [
+ {
+ "line": 177,
+ "params": [
+ {
+ "name": "srcImage",
+ "description": "source image
\n",
+ "type": "p5.Image|p5.Element"
+ },
+ {
+ "name": "sx",
+ "description": "X coordinate of the source's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sy",
+ "description": "Y coordinate of the source's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sw",
+ "description": "source image width
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "sh",
+ "description": "source image height
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dx",
+ "description": "X coordinate of the destination's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dy",
+ "description": "Y coordinate of the destination's upper left corner
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dw",
+ "description": "destination image width
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dh",
+ "description": "destination image height
\n",
+ "type": "Integer"
+ }
+ ]
+ },
+ {
+ "line": 220,
+ "params": [
+ {
+ "name": "sx",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sy",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sw",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "sh",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dx",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dy",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dw",
+ "description": "",
+ "type": "Integer"
+ },
+ {
+ "name": "dh",
+ "description": "",
+ "type": "Integer"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/image/pixels.js",
+ "line": 236,
+ "description": "Applies a filter to the canvas.\n
\nThe presets options are:\n
\nTHRESHOLD\nConverts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.\n
\nGRAY\nConverts any colors in the image to grayscale equivalents. No parameter\nis used.\n
\nOPAQUE\nSets the alpha channel to entirely opaque. No parameter is used.\n
\nINVERT\nSets each pixel to its inverse value. No parameter is used.\n
\nPOSTERIZE\nLimits each channel of the image to the number of colors specified as the\nparameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.\n
\nBLUR\nExecutes a Gaussian blur with the level parameter specifying the extent\nof the blurring. If no parameter is used, the blur is equivalent to\nGaussian blur of radius 1. Larger values increase the blur.\n
\nERODE\nReduces the light areas. No parameter is used.\n
\nDILATE\nIncreases the light areas. No parameter is used.
\n",
+ "itemtype": "method",
+ "name": "filter",
+ "params": [
+ {
+ "name": "filterType",
+ "description": "either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter
\n",
+ "type": "Constant"
+ },
+ {
+ "name": "filterParam",
+ "description": "an optional parameter unique\n to each filter, see above
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(THRESHOLD);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(GRAY);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(OPAQUE);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(INVERT);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(POSTERIZE, 3);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(DILATE);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(BLUR, 3);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(ERODE);\n}\n\n
"
+ ],
+ "alt": "black and white image of a brick wall.\ngreyscale image of a brickwall\nimage of a brickwall\njade colored image of a brickwall\nred and pink image of a brickwall\nimage of a brickwall\nblurry image of a brickwall\nimage of a brickwall\nimage of a brickwall with less detail",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Pixels"
+ },
+ {
+ "file": "src/image/pixels.js",
+ "line": 415,
+ "description": "Returns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If no parameters are specified, the entire image is returned.\nUse the x and y parameters to get the value of one pixel. Get a section of\nthe display window by specifying additional w and h parameters. When\ngetting an image, the x and y parameters define the coordinates for the\nupper-left corner of the image, regardless of the current imageMode().\n
\nIf the pixel requested is outside of the image window, [0,0,0,255] is\nreturned. To get the numbers scaled according to the current color ranges\nand taking into account colorMode, use getColor instead of get.\n
\nGetting the color of a single pixel with get(x, y) is easy, but not as fast\nas grabbing the data directly from pixels[]. The equivalent statement to\nget(x, y) using pixels[] with pixel density d is\n\nvar x, y, d; // set these to the coordinates\nvar off = (y width + x) d * 4;\nvar components = [\n pixels[off],\n pixels[off + 1],\n pixels[off + 2],\n pixels[off + 3]\n];\nprint(components);\n\n
\nSee the reference for pixels[] for more information.
\n",
+ "itemtype": "method",
+ "name": "get",
+ "params": [
+ {
+ "name": "x",
+ "description": "x-coordinate of the pixel
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "y",
+ "description": "y-coordinate of the pixel
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "w",
+ "description": "width
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "h",
+ "description": "height
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "values of pixel at x,y in array format\n [R, G, B, A] or p5.Image",
+ "type": "Number[]|p5.Image"
+ },
+ "example": [
+ "\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n var c = get();\n image(c, width / 2, 0);\n}\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n var c = get(50, 90);\n fill(c);\n noStroke();\n rect(25, 25, 50, 50);\n}\n\n
"
+ ],
+ "alt": "2 images of the rocky mountains, side-by-side\nImage of the rocky mountains with 50x50 green rect in center of canvas",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Pixels"
+ },
+ {
+ "file": "src/image/pixels.js",
+ "line": 491,
+ "description": "Loads the pixel data for the display window into the pixels[] array. This\nfunction must always be called before reading from or writing to pixels[].\nNote that only changes made with set() or direct manipulation of pixels[]\nwill occur.
\n",
+ "itemtype": "method",
+ "name": "loadPixels",
+ "example": [
+ "\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0);\n var d = pixelDensity();\n var halfImage = 4 * (img.width * d) * (img.height * d / 2);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n\n
"
+ ],
+ "alt": "two images of the rocky mountains. one on top, one on bottom of canvas.",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Pixels"
+ },
+ {
+ "file": "src/image/pixels.js",
+ "line": 528,
+ "description": "Changes the color of any pixel, or writes an image directly to the\ndisplay window.
\nThe x and y parameters specify the pixel to change and the c parameter\nspecifies the color value. This can be a p5.Color object, or [R, G, B, A]\npixel array. It can also be a single grayscale value.\nWhen setting an image, the x and y parameters define the coordinates for\nthe upper-left corner of the image, regardless of the current imageMode().\n
\n\nAfter using set(), you must call updatePixels() for your changes to appear.\nThis should be called once all pixels have been set, and must be called before\ncalling .get() or drawing the image.\n
\nSetting the color of a single pixel with set(x, y) is easy, but not as\nfast as putting the data directly into pixels[]. Setting the pixels[]\nvalues directly may be complicated when working with a retina display,\nbut will perform better when lots of pixels need to be set directly on\nevery loop.
\nSee the reference for pixels[] for more information.
",
+ "itemtype": "method",
+ "name": "set",
+ "params": [
+ {
+ "name": "x",
+ "description": "x-coordinate of the pixel
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "y-coordinate of the pixel
\n",
+ "type": "Number"
+ },
+ {
+ "name": "c",
+ "description": "insert a grayscale value | a pixel array |\n a p5.Color object | a p5.Image to copy
\n",
+ "type": "Number|Number[]|Object"
+ }
+ ],
+ "example": [
+ "\n\n\nvar black = color(0);\nset(30, 20, black);\nset(85, 20, black);\nset(85, 75, black);\nset(30, 75, black);\nupdatePixels();\n\n
\n\n\n\nfor (var i = 30; i < width - 15; i++) {\n for (var j = 20; j < height - 25; j++) {\n var c = color(204 - j, 153 - i, 0);\n set(i, j, c);\n }\n}\nupdatePixels();\n\n
\n\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n set(0, 0, img);\n updatePixels();\n line(0, 0, width, height);\n line(0, height, width, 0);\n}\n\n
"
+ ],
+ "alt": "4 black points in the shape of a square middle-right of canvas.\nsquare with orangey-brown gradient lightening at bottom right.\nimage of the rocky mountains. with lines like an 'x' through the center.",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Pixels"
+ },
+ {
+ "file": "src/image/pixels.js",
+ "line": 602,
+ "description": "Updates the display window with the data in the pixels[] array.\nUse in conjunction with loadPixels(). If you're only reading pixels from\nthe array, there's no need to call updatePixels() — updating is only\nnecessary to apply changes. updatePixels() should be called anytime the\npixels array is manipulated or set() is called, and only changes made with\nset() or direct changes to pixels[] will occur.
\n",
+ "itemtype": "method",
+ "name": "updatePixels",
+ "params": [
+ {
+ "name": "x",
+ "description": "x-coordinate of the upper-left corner of region\n to update
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "y",
+ "description": "y-coordinate of the upper-left corner of region\n to update
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "w",
+ "description": "width of region to update
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "h",
+ "description": "height of region to update
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\n\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0);\n var d = pixelDensity();\n var halfImage = 4 * (img.width * d) * (img.height * d / 2);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n\n
"
+ ],
+ "alt": "two images of the rocky mountains. one on top, one on bottom of canvas.",
+ "class": "p5",
+ "module": "Image",
+ "submodule": "Pixels"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 19,
+ "description": "Loads a JSON file from a file or a URL, and returns an Object.\nNote that even if the JSON file contains an Array, an Object will be\nreturned with index numbers as keys.
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. JSONP is supported via a polyfill and you\ncan pass in as the second argument an object with definitions of the json\ncallback following the syntax specified here.
\n",
+ "itemtype": "method",
+ "name": "loadJSON",
+ "return": {
+ "description": "JSON data",
+ "type": "Object|Array"
+ },
+ "example": [
+ "\n\nCalling loadJSON() inside preload() guarantees to complete the\noperation before setup() and draw() are called.
\n\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nvar earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n var url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n earthquakes = loadJSON(url);\n}\n\nfunction setup() {\n noLoop();\n}\n\nfunction draw() {\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
\n\n\nOutside of preload(), you may supply a callback function to handle the\nobject:
\n\nfunction setup() {\n noLoop();\n var url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n loadJSON(url, drawEarthquake);\n}\n\nfunction draw() {\n background(200);\n}\n\nfunction drawEarthquake(earthquakes) {\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n
"
+ ],
+ "alt": "50x50 ellipse that changes from black to white depending on the current humidity\n50x50 ellipse that changes from black to white depending on the current humidity",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Input",
+ "overloads": [
+ {
+ "line": 19,
+ "params": [
+ {
+ "name": "path",
+ "description": "name of the file or url to load
\n",
+ "type": "String"
+ },
+ {
+ "name": "jsonpOptions",
+ "description": "options object for jsonp related settings
\n",
+ "type": "Object",
+ "optional": true
+ },
+ {
+ "name": "datatype",
+ "description": ""json" or "jsonp"
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "callback",
+ "description": "function to be executed after\n loadJSON() completes, data is passed\n in as first argument
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "JSON data",
+ "type": "Object|Array"
+ }
+ },
+ {
+ "line": 104,
+ "params": [
+ {
+ "name": "path",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "datatype",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Object|Array"
+ }
+ },
+ {
+ "line": 112,
+ "params": [
+ {
+ "name": "path",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "",
+ "type": "Function"
+ },
+ {
+ "name": "errorCallback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Object|Array"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 170,
+ "description": "Reads the contents of a file and creates a String array of its individual\nlines. If the name of the file is used as the parameter, as in the above\nexample, the file must be located in the sketch directory/folder.\n
\nAlternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.\n
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed.
\n",
+ "itemtype": "method",
+ "name": "loadStrings",
+ "params": [
+ {
+ "name": "filename",
+ "description": "name of the file or url to load
\n",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "function to be executed after loadStrings()\n completes, Array is passed in as first\n argument
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Array of Strings",
+ "type": "String[]"
+ },
+ "example": [
+ "\n\nCalling loadStrings() inside preload() guarantees to complete the\noperation before setup() and draw() are called.
\n\n\nvar result;\nfunction preload() {\n result = loadStrings('assets/test.txt');\n}\n\nfunction setup() {\n background(200);\n var ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n
\n\nOutside of preload(), you may supply a callback function to handle the\nobject:
\n\n\nfunction setup() {\n loadStrings('assets/test.txt', pickString);\n}\n\nfunction pickString(result) {\n background(200);\n var ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n
"
+ ],
+ "alt": "randomly generated text from a file, for example \"i smell like butter\"\nrandomly generated text from a file, for example \"i have three feet\"",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Input"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 271,
+ "description": "Reads the contents of a file or URL and creates a p5.Table object with\nits values. If a file is specified, it must be located in the sketch's\n"data" folder. The filename parameter can also be a URL to a file found\nonline. By default, the file is assumed to be comma-separated (in CSV\nformat). Table only looks for a header row if the 'header' option is\nincluded.
\n\nPossible options include:\n
\n- csv - parse the table as comma-separated values
\n- tsv - parse the table as tab-separated values
\n- header - this table has a header (title) row
\n
\n\n\nWhen passing in multiple options, pass them in as separate parameters,\nseperated by commas. For example:\n
\n\nloadTable('my_csv_file.csv', 'csv', 'header');\n\n
\n\n All files loaded and saved use UTF-8 encoding.
\n\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadTable() inside preload()\nguarantees to complete the operation before setup() and draw() are called.\n
Outside of preload(), you may supply a callback function to handle the\nobject:
\n",
+ "itemtype": "method",
+ "name": "loadTable",
+ "return": {
+ "description": "Table object containing data",
+ "type": "Object"
+ },
+ "example": [
+ "\n\n\n// Given the following CSV file called \"mammals.csv\"\n// located in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n //the file can be remote\n //table = loadTable(\"http://p5js.org/reference/assets/mammals.csv\",\n // \"csv\", \"header\");\n}\n\nfunction setup() {\n //count the columns\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n\n print(table.getColumn('name'));\n //[\"Goat\", \"Leopard\", \"Zebra\"]\n\n //cycle through the table\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++) {\n print(table.getString(r, c));\n }\n}\n\n
"
+ ],
+ "alt": "randomly generated text from a file, for example \"i smell like butter\"\nrandomly generated text from a file, for example \"i have three feet\"",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Input",
+ "overloads": [
+ {
+ "line": 271,
+ "params": [
+ {
+ "name": "filename",
+ "description": "name of the file or URL to load
\n",
+ "type": "String"
+ },
+ {
+ "name": "options",
+ "description": ""header" "csv" "tsv"
\n",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "function to be executed after\n loadTable() completes. On success, the\n Table object is passed in as the\n first argument.
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Table object containing data",
+ "type": "Object"
+ }
+ },
+ {
+ "line": 360,
+ "params": [
+ {
+ "name": "filename",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Object"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 603,
+ "description": "Reads the contents of a file and creates an XML object with its values.\nIf the name of the file is used as the parameter, as in the above example,\nthe file must be located in the sketch directory/folder.
\nAlternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.
\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling loadXML() inside preload()\nguarantees to complete the operation before setup() and draw() are called.
\nOutside of preload(), you may supply a callback function to handle the\nobject.
\n",
+ "itemtype": "method",
+ "name": "loadXML",
+ "params": [
+ {
+ "name": "filename",
+ "description": "name of the file or URL to load
\n",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "function to be executed after loadXML()\n completes, XML object is passed in as\n first argument
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "XML object containing data",
+ "type": "Object"
+ },
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var children = xml.getChildren('animal');\n\n for (var i = 0; i < children.length; i++) {\n var id = children[i].getNum('id');\n var coloring = children[i].getString('species');\n var name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Input"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 704,
+ "itemtype": "method",
+ "name": "loadBytes",
+ "params": [
+ {
+ "name": "file",
+ "description": "name of the file or URL to load
\n",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "function to be executed after loadBytes()\n completes
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "function to be executed if there\n is an error
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "an object whose 'bytes' property will be the loaded buffer",
+ "type": "Object"
+ },
+ "example": [
+ "\n\nvar data;\n\nfunction preload() {\n data = loadBytes('assets/mammals.xml');\n}\n\nfunction setup() {\n for (var i = 0; i < 5; i++) {\n console.log(data.bytes[i].toString(16));\n }\n}\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Input"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 754,
+ "description": "Method for executing an HTTP GET request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'GET'). The 'binary' datatype will return\na Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer\nwhich can be used to initialize typed arrays (such as Uint8Array).
\n",
+ "itemtype": "method",
+ "name": "httpGet",
+ "example": [
+ "\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nvar earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n var url =\n 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n httpGet(url, 'jsonp', false, function(response) {\n // when the HTTP request completes, populate the variable that holds the\n // earthquake data used in the visualization.\n earthquakes = response;\n });\n}\n\nfunction draw() {\n if (!earthquakes) {\n // Wait until the earthquake data has loaded before drawing.\n return;\n }\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n noLoop();\n}\n
"
+ ],
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Input",
+ "overloads": [
+ {
+ "line": 754,
+ "params": [
+ {
+ "name": "path",
+ "description": "name of the file or url to load
\n",
+ "type": "String"
+ },
+ {
+ "name": "datatype",
+ "description": ""json", "jsonp", "binary", "arrayBuffer",\n "xml", or "text"
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "data",
+ "description": "param data passed sent with request
\n",
+ "type": "Object|Boolean",
+ "optional": true
+ },
+ {
+ "name": "callback",
+ "description": "function to be executed after\n httpGet() completes, data is passed in\n as first argument
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ]
+ },
+ {
+ "line": 805,
+ "params": [
+ {
+ "name": "path",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "data",
+ "description": "",
+ "type": "Object|Boolean"
+ },
+ {
+ "name": "callback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ }
+ ]
+ },
+ {
+ "line": 812,
+ "params": [
+ {
+ "name": "path",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "",
+ "type": "Function"
+ },
+ {
+ "name": "errorCallback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 826,
+ "description": "Method for executing an HTTP POST request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling httpDo(path, 'POST').
\n",
+ "itemtype": "method",
+ "name": "httpPost",
+ "example": [
+ "\n\n\n// Examples use jsonplaceholder.typicode.com for a Mock Data API\n\nvar url = 'https://jsonplaceholder.typicode.com/posts';\nvar postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n var r = random(255);\n var g = random(255);\n var b = random(255);\n\n httpPost(url, 'json', postData, function(result) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n ellipse(mouseX, mouseY, 200, 200);\n text(result.body, mouseX, mouseY);\n });\n}\n\n
\n\n\n\nvar url = 'https://invalidURL'; // A bad URL that will cause errors\nvar postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n var r = random(255);\n var g = random(255);\n var b = random(255);\n\n httpPost(\n url,\n 'json',\n postData,\n function(result) {\n // ... won't be called\n },\n function(error) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n text(error.toString(), mouseX, mouseY);\n }\n );\n}\n
\n"
+ ],
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Input",
+ "overloads": [
+ {
+ "line": 826,
+ "params": [
+ {
+ "name": "path",
+ "description": "name of the file or url to load
\n",
+ "type": "String"
+ },
+ {
+ "name": "datatype",
+ "description": ""json", "jsonp", "xml", or "text".\n If omitted, httpPost() will guess.
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "data",
+ "description": "param data passed sent with request
\n",
+ "type": "Object|Boolean",
+ "optional": true
+ },
+ {
+ "name": "callback",
+ "description": "function to be executed after\n httpPost() completes, data is passed in\n as first argument
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ]
+ },
+ {
+ "line": 905,
+ "params": [
+ {
+ "name": "path",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "data",
+ "description": "",
+ "type": "Object|Boolean"
+ },
+ {
+ "name": "callback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ }
+ ]
+ },
+ {
+ "line": 912,
+ "params": [
+ {
+ "name": "path",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "",
+ "type": "Function"
+ },
+ {
+ "name": "errorCallback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 926,
+ "description": "Method for executing an HTTP request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text.
\nFor more advanced use, you may also pass in the path as the first argument\nand a object as the second argument, the signature follows the one specified\nin the Fetch API specification.
\n",
+ "itemtype": "method",
+ "name": "httpDo",
+ "example": [
+ "\n\n\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\n\n// displays an animation of all USGS earthquakes\nvar earthquakes;\nvar eqFeatureIndex = 0;\n\nfunction preload() {\n var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';\n httpDo(\n url,\n {\n method: 'GET',\n // Other Request options, like special headers for apis\n headers: { authorization: 'Bearer secretKey' }\n },\n function(res) {\n earthquakes = res;\n }\n );\n}\n\nfunction draw() {\n // wait until the data is loaded\n if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {\n return;\n }\n clear();\n\n var feature = earthquakes.features[eqFeatureIndex];\n var mag = feature.properties.mag;\n var rad = mag / 11 * ((width + height) / 2);\n fill(255, 0, 0, 100);\n ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);\n\n if (eqFeatureIndex >= earthquakes.features.length) {\n eqFeatureIndex = 0;\n } else {\n eqFeatureIndex += 1;\n }\n}\n\n
"
+ ],
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Input",
+ "overloads": [
+ {
+ "line": 926,
+ "params": [
+ {
+ "name": "path",
+ "description": "name of the file or url to load
\n",
+ "type": "String"
+ },
+ {
+ "name": "method",
+ "description": "either "GET", "POST", or "PUT",\n defaults to "GET"
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "datatype",
+ "description": ""json", "jsonp", "xml", or "text"
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "data",
+ "description": "param data passed sent with request
\n",
+ "type": "Object",
+ "optional": true
+ },
+ {
+ "name": "callback",
+ "description": "function to be executed after\n httpGet() completes, data is passed in\n as first argument
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "function to be executed if\n there is an error, response is passed\n in as first argument
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ]
+ },
+ {
+ "line": 994,
+ "params": [
+ {
+ "name": "path",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "options",
+ "description": "Request object options as documented in the\n "fetch" API\nreference
\n",
+ "type": "Object"
+ },
+ {
+ "name": "callback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "",
+ "type": "Function",
+ "optional": true
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 1130,
+ "itemtype": "method",
+ "name": "createWriter",
+ "params": [
+ {
+ "name": "name",
+ "description": "name of the file to be created
\n",
+ "type": "String"
+ },
+ {
+ "name": "extension",
+ "description": "",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.PrintWriter"
+ },
+ "example": [
+ "\n\n\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n var writer = createWriter('squares.txt');\n for (var i = 0; i < 10; i++) {\n writer.print(i * i);\n }\n writer.close();\n writer.clear();\n });\n\n
"
+ ],
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Output"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 1179,
+ "description": "Writes data to the PrintWriter stream
\n",
+ "itemtype": "method",
+ "name": "write",
+ "params": [
+ {
+ "name": "data",
+ "description": "all data to be written by the PrintWriter
\n",
+ "type": "Array"
+ }
+ ],
+ "example": [
+ "\n\n\n// creates a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// write 'Hello world!'' to the file\nwriter.write(['Hello world!']);\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n\n\n// creates a file called 'newFile2.txt'\nvar writer = createWriter('newFile2.txt');\n// write 'apples,bananas,123' to the file\nwriter.write(['apples', 'bananas', 123]);\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n\n\n// creates a file called 'newFile3.txt'\nvar writer = createWriter('newFile3.txt');\n// write 'My name is: Teddy' to the file\nwriter.write('My name is:');\nwriter.write(' Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n\n
"
+ ],
+ "class": "p5.PrintWriter",
+ "module": "IO",
+ "submodule": "Output"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 1219,
+ "description": "Writes data to the PrintWriter stream, and adds a new line at the end
\n",
+ "itemtype": "method",
+ "name": "print",
+ "params": [
+ {
+ "name": "data",
+ "description": "all data to be printed by the PrintWriter
\n",
+ "type": "Array"
+ }
+ ],
+ "example": [
+ "\n\n\n// creates a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// creates a file containing\n// My name is:\n// Teddy\nwriter.print('My name is:');\nwriter.print('Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n\n\nvar writer;\n\nfunction setup() {\n createCanvas(400, 400);\n // create a PrintWriter\n writer = createWriter('newFile.txt');\n}\n\nfunction draw() {\n // print all mouseX and mouseY coordinates to the stream\n writer.print([mouseX, mouseY]);\n}\n\nfunction mouseClicked() {\n // close the PrintWriter and save the file\n writer.close();\n}\n\n
"
+ ],
+ "class": "p5.PrintWriter",
+ "module": "IO",
+ "submodule": "Output"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 1262,
+ "description": "Clears the data already written to the PrintWriter object
\n",
+ "itemtype": "method",
+ "name": "clear",
+ "example": [
+ "\n\n// create writer object\nvar writer = createWriter('newFile.txt');\nwriter.write(['clear me']);\n// clear writer object here\nwriter.clear();\n// close writer\nwriter.close();\n
\n"
+ ],
+ "class": "p5.PrintWriter",
+ "module": "IO",
+ "submodule": "Output"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 1280,
+ "description": "Closes the PrintWriter
\n",
+ "itemtype": "method",
+ "name": "close",
+ "example": [
+ "\n\n\n// create a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// close the PrintWriter and save the file\nwriter.close();\n\n
\n\n\n// create a file called 'newFile2.txt'\nvar writer = createWriter('newFile2.txt');\n// write some data to the file\nwriter.write([100, 101, 102]);\n// close the PrintWriter and save the file\nwriter.close();\n\n
"
+ ],
+ "class": "p5.PrintWriter",
+ "module": "IO",
+ "submodule": "Output"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 1329,
+ "description": "Save an image, text, json, csv, wav, or html. Prompts download to\nthe client's computer. Note that it is not recommended to call save()\nwithin draw if it's looping, as the save() function will open a new save\ndialog every frame.
\nThe default behavior is to save the canvas as an image. You can\noptionally specify a filename.\nFor example:
\n \n save();\n save('myCanvas.jpg'); // save a specific canvas with a filename\n
\n\nAlternately, the first parameter can be a pointer to a canvas\np5.Element, an Array of Strings,\nan Array of JSON, a JSON object, a p5.Table, a p5.Image, or a\np5.SoundFile (requires p5.sound). The second parameter is a filename\n(including extension). The third parameter is for options specific\nto this type of object. This method will save a file that fits the\ngiven paramaters. For example:
\n\n \n // Saves canvas as an image\n save('myCanvas.jpg');\n\n // Saves pImage as a png image\n var img = createImage(10, 10);\n save(img, 'my.png');\n\n // Saves canvas as an image\n var cnv = createCanvas(100, 100);\n save(cnv, 'myCanvas.jpg');\n\n // Saves p5.Renderer object as an image\n var gb = createGraphics(100, 100);\n save(gb, 'myGraphics.jpg');\n\n var myTable = new p5.Table();\n\n // Saves table as html file\n save(myTable, 'myTable.html');\n\n // Comma Separated Values\n save(myTable, 'myTable.csv');\n\n // Tab Separated Values\n save(myTable, 'myTable.tsv');\n\n var myJSON = { a: 1, b: true };\n\n // Saves pretty JSON\n save(myJSON, 'my.json');\n\n // Optimizes JSON filesize\n save(myJSON, 'my.json', true);\n\n // Saves array of strings to a text file with line breaks after each item\n var arrayOfStrings = ['a', 'b'];\n save(arrayOfStrings, 'my.txt');\n
",
+ "itemtype": "method",
+ "name": "save",
+ "params": [
+ {
+ "name": "objectOrFilename",
+ "description": "If filename is provided, will\n save canvas as an image with\n either png or jpg extension\n depending on the filename.\n If object is provided, will\n save depending on the object\n and filename (see examples\n above).
\n",
+ "type": "Object|String",
+ "optional": true
+ },
+ {
+ "name": "filename",
+ "description": "If an object is provided as the first\n parameter, then the second parameter\n indicates the filename,\n and should include an appropriate\n file extension (see examples above).
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "options",
+ "description": "Additional options depend on\n filetype. For example, when saving JSON,\n true indicates that the\n output will be optimized for filesize,\n rather than readability.
\n",
+ "type": "Boolean|String",
+ "optional": true
+ }
+ ],
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Output"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 1457,
+ "description": "Writes the contents of an Array or a JSON object to a .json file.\nThe file saving process and location of the saved file will\nvary between web browsers.
\n",
+ "itemtype": "method",
+ "name": "saveJSON",
+ "params": [
+ {
+ "name": "json",
+ "description": "",
+ "type": "Array|Object"
+ },
+ {
+ "name": "filename",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "optimize",
+ "description": "If true, removes line breaks\n and spaces from the output\n file to optimize filesize\n (but not readability).
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n \n var json = {}; // new JSON Object\n\n json.id = 0;\n json.species = 'Panthera leo';\n json.name = 'Lion';\n\n createButton('save')\n .position(10, 10)\n .mousePressed(function() {\n saveJSON(json, 'lion.json');\n });\n\n // saves the following to a file called \"lion.json\":\n // {\n // \"id\": 0,\n // \"species\": \"Panthera leo\",\n // \"name\": \"Lion\"\n // }\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Output"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 1509,
+ "description": "Writes an array of Strings to a text file, one line per String.\nThe file saving process and location of the saved file will\nvary between web browsers.
\n",
+ "itemtype": "method",
+ "name": "saveStrings",
+ "params": [
+ {
+ "name": "list",
+ "description": "string array to be written
\n",
+ "type": "String[]"
+ },
+ {
+ "name": "filename",
+ "description": "filename for output
\n",
+ "type": "String"
+ },
+ {
+ "name": "extension",
+ "description": "the filename's extension
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n \n var words = 'apple bear cat dog';\n\n // .split() outputs an Array\n var list = split(words, ' ');\n\n createButton('save')\n .position(10, 10)\n .mousePressed(function() {\n saveStrings(list, 'nouns.txt');\n });\n\n // Saves the following to a file called 'nouns.txt':\n //\n // apple\n // bear\n // cat\n // dog\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Output"
+ },
+ {
+ "file": "src/io/files.js",
+ "line": 1571,
+ "description": "Writes the contents of a Table object to a file. Defaults to a\ntext file with comma-separated-values ('csv') but can also\nuse tab separation ('tsv'), or generate an HTML table ('html').\nThe file saving process and location of the saved file will\nvary between web browsers.
\n",
+ "itemtype": "method",
+ "name": "saveTable",
+ "params": [
+ {
+ "name": "Table",
+ "description": "the Table object to save to a file
\n",
+ "type": "p5.Table"
+ },
+ {
+ "name": "filename",
+ "description": "the filename to which the Table should be saved
\n",
+ "type": "String"
+ },
+ {
+ "name": "options",
+ "description": "can be one of "tsv", "csv", or "html"
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n\n var table;\n\n function setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n var newRow = table.addRow();\n newRow.setNum('id', table.getRowCount() - 1);\n newRow.setString('species', 'Panthera leo');\n newRow.setString('name', 'Lion');\n\n // To save, un-comment next line then click 'run'\n // saveTable(table, 'new.csv');\n }\n\n // Saves the following to a file called 'new.csv':\n // id,species,name\n // 0,Panthera leo,Lion\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Output"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 11,
+ "description": "Table Options
\nGeneric class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.
\nCSV files are\n\ncomma separated values, often with the data in quotes. TSV\nfiles use tabs as separators, and usually don't bother with the\nquotes.
\nFile names should end with .csv if they're comma separated.
\nA rough "spec" for CSV can be found\nhere.
\nTo load files, use the loadTable method.
\nTo save tables to your computer, use the save method\n or the saveTable method.
\n\nPossible options include:
\n\n- csv - parse the table as comma-separated values\n
- tsv - parse the table as tab-separated values\n
- header - this table has a header (title) row\n
",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 45,
+ "itemtype": "property",
+ "name": "columns",
+ "type": "String[]",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 50,
+ "itemtype": "property",
+ "name": "rows",
+ "type": "p5.TableRow[]",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 56,
+ "description": "Use addRow() to add a new row of data to a p5.Table object. By default,\nan empty row is created. Typically, you would store a reference to\nthe new row in a TableRow object (see newRow in the example above),\nand then set individual values using set().
\nIf a p5.TableRow object is included as a parameter, then that row is\nduplicated and added to the table.
\n",
+ "itemtype": "method",
+ "name": "addRow",
+ "params": [
+ {
+ "name": "row",
+ "description": "row to be added to the table
\n",
+ "type": "p5.TableRow",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add a row\n var newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 119,
+ "description": "Removes a row from the table object.
\n",
+ "itemtype": "method",
+ "name": "removeRow",
+ "params": [
+ {
+ "name": "id",
+ "description": "ID number of the row to remove
\n",
+ "type": "Integer"
+ }
+ ],
+ "example": [
+ "\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //remove the first row\n table.removeRow(0);\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 167,
+ "description": "Returns a reference to the specified p5.TableRow. The reference\ncan then be used to get and set values of the selected row.
\n",
+ "itemtype": "method",
+ "name": "getRow",
+ "params": [
+ {
+ "name": "rowID",
+ "description": "ID number of the row to get
\n",
+ "type": "Integer"
+ }
+ ],
+ "return": {
+ "description": "p5.TableRow object",
+ "type": "p5.TableRow"
+ },
+ "example": [
+ "\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n var row = table.getRow(1);\n //print it column by column\n //note: a row is an object, not an array\n for (var c = 0; c < table.getColumnCount(); c++) {\n print(row.getString(c));\n }\n}\n\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 213,
+ "description": "Gets all rows from the table. Returns an array of p5.TableRows.
\n",
+ "itemtype": "method",
+ "name": "getRows",
+ "return": {
+ "description": "Array of p5.TableRows",
+ "type": "p5.TableRow[]"
+ },
+ "example": [
+ "\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n\n //warning: rows is an array of objects\n for (var r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n for (r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 262,
+ "description": "Finds the first row in the Table that contains the value\nprovided, and returns a reference to that row. Even if\nmultiple rows are possible matches, only the first matching\nrow is returned. The column to search may be specified by\neither its ID or title.
\n",
+ "itemtype": "method",
+ "name": "findRow",
+ "params": [
+ {
+ "name": "value",
+ "description": "The value to match
\n",
+ "type": "String"
+ },
+ {
+ "name": "column",
+ "description": "ID number or title of the\n column to search
\n",
+ "type": "Integer|String"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.TableRow"
+ },
+ "example": [
+ "\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //find the animal named zebra\n var row = table.findRow('Zebra', 'name');\n //find the corresponding species\n print(row.getString('species'));\n }\n \n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 327,
+ "description": "Finds the rows in the Table that contain the value\nprovided, and returns references to those rows. Returns an\nArray, so for must be used to iterate through all the rows,\nas shown in the example above. The column to search may be\nspecified by either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "findRows",
+ "params": [
+ {
+ "name": "value",
+ "description": "The value to match
\n",
+ "type": "String"
+ },
+ {
+ "name": "column",
+ "description": "ID number or title of the\n column to search
\n",
+ "type": "Integer|String"
+ }
+ ],
+ "return": {
+ "description": "An Array of TableRow objects",
+ "type": "p5.TableRow[]"
+ },
+ "example": [
+ "\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add another goat\n var newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Scape Goat');\n newRow.setString('name', 'Goat');\n\n //find the rows containing animals named Goat\n var rows = table.findRows('Goat', 'name');\n print(rows.length + ' Goats found');\n }\n \n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 396,
+ "description": "Finds the first row in the Table that matches the regular\nexpression provided, and returns a reference to that row.\nEven if multiple rows are possible matches, only the first\nmatching row is returned. The column to search may be\nspecified by either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "matchRow",
+ "params": [
+ {
+ "name": "regexp",
+ "description": "The regular expression to match
\n",
+ "type": "String|RegExp"
+ },
+ {
+ "name": "column",
+ "description": "The column ID (number) or\n title (string)
\n",
+ "type": "String|Integer"
+ }
+ ],
+ "return": {
+ "description": "TableRow object",
+ "type": "p5.TableRow"
+ },
+ "example": [
+ "\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //Search using specified regex on a given column, return TableRow object\n var mammal = table.matchRow(new RegExp('ant'), 1);\n print(mammal.getString(1));\n //Output \"Panthera pardus\"\n}\n\n
\n"
+ ],
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 455,
+ "description": "Finds the rows in the Table that match the regular expression provided,\nand returns references to those rows. Returns an array, so for must be\nused to iterate through all the rows, as shown in the example. The\ncolumn to search may be specified by either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "matchRows",
+ "params": [
+ {
+ "name": "regexp",
+ "description": "The regular expression to match
\n",
+ "type": "String"
+ },
+ {
+ "name": "column",
+ "description": "The column ID (number) or\n title (string)
\n",
+ "type": "String|Integer",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "An Array of TableRow objects",
+ "type": "p5.TableRow[]"
+ },
+ "example": [
+ "\n\n\nvar table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', 'Lion');\n newRow.setString('type', 'Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', 'Snake');\n newRow.setString('type', 'Reptile');\n\n newRow = table.addRow();\n newRow.setString('name', 'Mosquito');\n newRow.setString('type', 'Insect');\n\n newRow = table.addRow();\n newRow.setString('name', 'Lizard');\n newRow.setString('type', 'Reptile');\n\n var rows = table.matchRows('R.*', 'type');\n for (var i = 0; i < rows.length; i++) {\n print(rows[i].getString('name') + ': ' + rows[i].getString('type'));\n }\n}\n// Sketch prints:\n// Snake: Reptile\n// Lizard: Reptile\n\n
"
+ ],
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 522,
+ "description": "Retrieves all values in the specified column, and returns them\nas an array. The column may be specified by either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "getColumn",
+ "params": [
+ {
+ "name": "column",
+ "description": "String or Number of the column to return
\n",
+ "type": "String|Number"
+ }
+ ],
+ "return": {
+ "description": "Array of column values",
+ "type": "Array"
+ },
+ "example": [
+ "\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //getColumn returns an array that can be printed directly\n print(table.getColumn('species'));\n //outputs [\"Capra hircus\", \"Panthera pardus\", \"Equus zebra\"]\n }\n \n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 575,
+ "description": "Removes all rows from a Table. While all rows are removed,\ncolumns and column titles are maintained.
\n",
+ "itemtype": "method",
+ "name": "clearRows",
+ "example": [
+ "\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.clearRows();\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n }\n \n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 617,
+ "description": "Use addColumn() to add a new column to a Table object.\nTypically, you will want to specify a title, so the column\nmay be easily referenced later by name. (If no title is\nspecified, the new column's title will be null.)
\n",
+ "itemtype": "method",
+ "name": "addColumn",
+ "params": [
+ {
+ "name": "title",
+ "description": "title of the given column
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.addColumn('carnivore');\n table.set(0, 'carnivore', 'no');\n table.set(1, 'carnivore', 'yes');\n table.set(2, 'carnivore', 'no');\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n \n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 668,
+ "description": "Returns the total number of columns in a Table.
\n",
+ "itemtype": "method",
+ "name": "getColumnCount",
+ "return": {
+ "description": "Number of columns in this table",
+ "type": "Integer"
+ },
+ "example": [
+ "\n \n \n // given the cvs file \"blobs.csv\" in /assets directory\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n var table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n var numOfColumn = table.getColumnCount();\n text('There are ' + numOfColumn + ' columns in the table.', 100, 50);\n }\n \n
"
+ ],
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 704,
+ "description": "Returns the total number of rows in a Table.
\n",
+ "itemtype": "method",
+ "name": "getRowCount",
+ "return": {
+ "description": "Number of rows in this table",
+ "type": "Integer"
+ },
+ "example": [
+ "\n \n \n // given the cvs file \"blobs.csv\" in /assets directory\n //\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n var table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);\n }\n \n
"
+ ],
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 740,
+ "description": "Removes any of the specified characters (or "tokens").
\n\nIf no column is specified, then the values in all columns and\nrows are processed. A specific column may be referenced by\neither its ID or title.
",
+ "itemtype": "method",
+ "name": "removeTokens",
+ "params": [
+ {
+ "name": "chars",
+ "description": "String listing characters to be removed
\n",
+ "type": "String"
+ },
+ {
+ "name": "column",
+ "description": "Column ID (number)\n or name (string)
\n",
+ "type": "String|Integer",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n \n function setup() {\n var table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', ' $Lion ,');\n newRow.setString('type', ',,,Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', '$Snake ');\n newRow.setString('type', ',,,Reptile');\n\n table.removeTokens(',$ ');\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
"
+ ],
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 814,
+ "description": "Trims leading and trailing whitespace, such as spaces and tabs,\nfrom String table values. If no column is specified, then the\nvalues in all columns and rows are trimmed. A specific column\nmay be referenced by either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "trim",
+ "params": [
+ {
+ "name": "column",
+ "description": "Column ID (number)\n or name (string)
\n",
+ "type": "String|Integer",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n \n function setup() {\n var table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', ' Lion ,');\n newRow.setString('type', ' Mammal ');\n\n newRow = table.addRow();\n newRow.setString('name', ' Snake ');\n newRow.setString('type', ' Reptile ');\n\n table.trim();\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n
"
+ ],
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 878,
+ "description": "Use removeColumn() to remove an existing column from a Table\nobject. The column to be removed may be identified by either\nits title (a String) or its index value (an int).\nremoveColumn(0) would remove the first column, removeColumn(1)\nwould remove the second column, and so on.
\n",
+ "itemtype": "method",
+ "name": "removeColumn",
+ "params": [
+ {
+ "name": "column",
+ "description": "columnName (string) or ID (number)
\n",
+ "type": "String|Integer"
+ }
+ ],
+ "example": [
+ "\n \n \n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.removeColumn('id');\n print(table.getColumnCount());\n }\n \n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 944,
+ "description": "Stores a value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "set",
+ "params": [
+ {
+ "name": "row",
+ "description": "row ID
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "column",
+ "description": "column ID (Number)\n or title (String)
\n",
+ "type": "String|Integer"
+ },
+ {
+ "name": "value",
+ "description": "value to assign
\n",
+ "type": "String|Number"
+ }
+ ],
+ "example": [
+ "\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.set(0, 'species', 'Canis Lupus');\n table.set(0, 'name', 'Wolf');\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 994,
+ "description": "Stores a Float value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "setNum",
+ "params": [
+ {
+ "name": "row",
+ "description": "row ID
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "column",
+ "description": "column ID (Number)\n or title (String)
\n",
+ "type": "String|Integer"
+ },
+ {
+ "name": "value",
+ "description": "value to assign
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.setNum(1, 'id', 1);\n\n print(table.getColumn(0));\n //[\"0\", 1, \"2\"]\n}\n\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 1040,
+ "description": "Stores a String value in the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "setString",
+ "params": [
+ {
+ "name": "row",
+ "description": "row ID
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "column",
+ "description": "column ID (Number)\n or title (String)
\n",
+ "type": "String|Integer"
+ },
+ {
+ "name": "value",
+ "description": "value to assign
\n",
+ "type": "String"
+ }
+ ],
+ "example": [
+ "\n\n// Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //add a row\n var newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n print(table.getArray());\n}\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 1085,
+ "description": "Retrieves a value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n",
+ "itemtype": "method",
+ "name": "get",
+ "params": [
+ {
+ "name": "row",
+ "description": "row ID
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "column",
+ "description": "columnName (string) or\n ID (number)
\n",
+ "type": "String|Integer"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "String|Number"
+ },
+ "example": [
+ "\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.get(0, 1));\n //Capra hircus\n print(table.get(0, 'species'));\n //Capra hircus\n}\n\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 1132,
+ "description": "Retrieves a Float value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n",
+ "itemtype": "method",
+ "name": "getNum",
+ "params": [
+ {
+ "name": "row",
+ "description": "row ID
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "column",
+ "description": "columnName (string) or\n ID (number)
\n",
+ "type": "String|Integer"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n}\n\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 1177,
+ "description": "Retrieves a String value from the Table's specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.
\n",
+ "itemtype": "method",
+ "name": "getString",
+ "params": [
+ {
+ "name": "row",
+ "description": "row ID
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "column",
+ "description": "columnName (string) or\n ID (number)
\n",
+ "type": "String|Integer"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "String"
+ },
+ "example": [
+ "\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getString(0, 0)); // 0\n print(table.getString(0, 1)); // Capra hircus\n print(table.getString(0, 2)); // Goat\n print(table.getString(1, 0)); // 1\n print(table.getString(1, 1)); // Panthera pardus\n print(table.getString(1, 2)); // Leopard\n print(table.getString(2, 0)); // 2\n print(table.getString(2, 1)); // Equus zebra\n print(table.getString(2, 2)); // Zebra\n}\n\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 1230,
+ "description": "Retrieves all table data and returns as an object. If a column name is\npassed in, each row object will be stored with that attribute as its\ntitle.
\n",
+ "itemtype": "method",
+ "name": "getObject",
+ "params": [
+ {
+ "name": "headerColumn",
+ "description": "Name of the column which should be used to\n title each row object (optional)
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Object"
+ },
+ "example": [
+ "\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n var tableObject = table.getObject();\n\n print(tableObject);\n //outputs an object\n}\n\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.Table.js",
+ "line": 1294,
+ "description": "Retrieves all table data and returns it as a multidimensional array.
\n",
+ "itemtype": "method",
+ "name": "getArray",
+ "return": {
+ "description": "",
+ "type": "Array"
+ },
+ "example": [
+ "\n\n\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leoperd\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n var tableArray = table.getArray();\n for (var i = 0; i < tableArray.length; i++) {\n print(tableArray[i]);\n }\n}\n\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.Table",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.TableRow.js",
+ "line": 42,
+ "description": "Stores a value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "set",
+ "params": [
+ {
+ "name": "column",
+ "description": "Column ID (Number)\n or Title (String)
\n",
+ "type": "String|Integer"
+ },
+ {
+ "name": "value",
+ "description": "The value to be stored
\n",
+ "type": "String|Number"
+ }
+ ],
+ "example": [
+ "\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n print(table.getArray());\n }\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.TableRow",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.TableRow.js",
+ "line": 104,
+ "description": "Stores a Float value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "setNum",
+ "params": [
+ {
+ "name": "column",
+ "description": "Column ID (Number)\n or Title (String)
\n",
+ "type": "String|Integer"
+ },
+ {
+ "name": "value",
+ "description": "The value to be stored\n as a Float
\n",
+ "type": "Number|String"
+ }
+ ],
+ "example": [
+ "\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n rows[r].setNum('id', r + 10);\n }\n\n print(table.getArray());\n }\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.TableRow",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.TableRow.js",
+ "line": 148,
+ "description": "Stores a String value in the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "setString",
+ "params": [
+ {
+ "name": "column",
+ "description": "Column ID (Number)\n or Title (String)
\n",
+ "type": "String|Integer"
+ },
+ {
+ "name": "value",
+ "description": "The value to be stored\n as a String
\n",
+ "type": "String|Number|Boolean|Object"
+ }
+ ],
+ "example": [
+ "\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n var name = rows[r].getString('name');\n rows[r].setString('name', 'A ' + name + ' named George');\n }\n\n print(table.getArray());\n }\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.TableRow",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.TableRow.js",
+ "line": 193,
+ "description": "Retrieves a value from the TableRow's specified column.\nThe column may be specified by either its ID or title.
\n",
+ "itemtype": "method",
+ "name": "get",
+ "params": [
+ {
+ "name": "column",
+ "description": "columnName (string) or\n ID (number)
\n",
+ "type": "String|Integer"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "String|Number"
+ },
+ "example": [
+ "\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var names = [];\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n names.push(rows[r].get('name'));\n }\n\n print(names);\n }\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.TableRow",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.TableRow.js",
+ "line": 241,
+ "description": "Retrieves a Float value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n",
+ "itemtype": "method",
+ "name": "getNum",
+ "params": [
+ {
+ "name": "column",
+ "description": "columnName (string) or\n ID (number)
\n",
+ "type": "String|Integer"
+ }
+ ],
+ "return": {
+ "description": "Float Floating point number",
+ "type": "Number"
+ },
+ "example": [
+ "\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n var minId = Infinity;\n var maxId = -Infinity;\n for (var r = 0; r < rows.length; r++) {\n var id = rows[r].getNum('id');\n minId = min(minId, id);\n maxId = min(maxId, id);\n }\n print('minimum id = ' + minId + ', maximum id = ' + maxId);\n }\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.TableRow",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.TableRow.js",
+ "line": 297,
+ "description": "Retrieves an String value from the TableRow's specified\ncolumn. The column may be specified by either its ID or\ntitle.
\n",
+ "itemtype": "method",
+ "name": "getString",
+ "params": [
+ {
+ "name": "column",
+ "description": "columnName (string) or\n ID (number)
\n",
+ "type": "String|Integer"
+ }
+ ],
+ "return": {
+ "description": "String",
+ "type": "String"
+ },
+ "example": [
+ "\n \n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n var longest = '';\n for (var r = 0; r < rows.length; r++) {\n var species = rows[r].getString('species');\n if (longest.length < species.length) {\n longest = species;\n }\n }\n\n print('longest: ' + longest);\n }\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5.TableRow",
+ "module": "IO",
+ "submodule": "Table"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 64,
+ "description": "Gets a copy of the element's parent. Returns the parent as another\np5.XML object.
\n",
+ "itemtype": "method",
+ "name": "getParent",
+ "return": {
+ "description": "element parent",
+ "type": "p5.XML"
+ },
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var children = xml.getChildren('animal');\n var parent = children[1].getParent();\n print(parent.getName());\n}\n\n// Sketch prints:\n// mammals\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 102,
+ "description": "Gets the element's full name, which is returned as a String.
\n",
+ "itemtype": "method",
+ "name": "getName",
+ "return": {
+ "description": "the name of the node",
+ "type": "String"
+ },
+ "example": [
+ "<animal\n \n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n var xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n print(xml.getName());\n }\n\n // Sketch prints:\n // mammals\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 137,
+ "description": "Sets the element's name, which is specified as a String.
\n",
+ "itemtype": "method",
+ "name": "setName",
+ "params": [
+ {
+ "name": "the",
+ "description": "new name of the node
\n",
+ "type": "String"
+ }
+ ],
+ "example": [
+ "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.getName());\n xml.setName('fish');\n print(xml.getName());\n}\n\n// Sketch prints:\n// mammals\n// fish\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 175,
+ "description": "Checks whether or not the element has any children, and returns the result\nas a boolean.
\n",
+ "itemtype": "method",
+ "name": "hasChildren",
+ "return": {
+ "description": "",
+ "type": "Boolean"
+ },
+ "example": [
+ "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.hasChildren());\n}\n\n// Sketch prints:\n// true\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 211,
+ "description": "Get the names of all of the element's children, and returns the names as an\narray of Strings. This is the same as looping through and calling getName()\non each child element individually.
\n",
+ "itemtype": "method",
+ "name": "listChildren",
+ "return": {
+ "description": "names of the children of the element",
+ "type": "String[]"
+ },
+ "example": [
+ "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.listChildren());\n}\n\n// Sketch prints:\n// [\"animal\", \"animal\", \"animal\"]\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 250,
+ "description": "Returns all of the element's children as an array of p5.XML objects. When\nthe name parameter is specified, then it will return all children that match\nthat name.
\n",
+ "itemtype": "method",
+ "name": "getChildren",
+ "params": [
+ {
+ "name": "name",
+ "description": "element name
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "children of the element",
+ "type": "p5.XML[]"
+ },
+ "example": [
+ "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var animals = xml.getChildren('animal');\n\n for (var i = 0; i < animals.length; i++) {\n print(animals[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 300,
+ "description": "Returns the first of the element's children that matches the name parameter\nor the child of the given index.It returns undefined if no matching\nchild is found.
\n",
+ "itemtype": "method",
+ "name": "getChild",
+ "params": [
+ {
+ "name": "name",
+ "description": "element name or index
\n",
+ "type": "String|Integer"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.XML"
+ },
+ "example": [
+ "<animal\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var secondChild = xml.getChild(1);\n print(secondChild.getContent());\n}\n\n// Sketch prints:\n// \"Leopard\"\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 361,
+ "description": "Appends a new child to the element. The child can be specified with\neither a String, which will be used as the new tag's name, or as a\nreference to an existing p5.XML object.\nA reference to the newly created child is returned as an p5.XML object.
\n",
+ "itemtype": "method",
+ "name": "addChild",
+ "params": [
+ {
+ "name": "node",
+ "description": "a p5.XML Object which will be the child to be added
\n",
+ "type": "p5.XML"
+ }
+ ],
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var child = new p5.XML();\n child.setAttribute('id', '3');\n child.setAttribute('species', 'Ornithorhynchus anatinus');\n child.setContent('Platypus');\n xml.addChild(child);\n\n var animals = xml.getChildren('animal');\n print(animals[animals.length - 1].getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 412,
+ "description": "Removes the element specified by name or index.
\n",
+ "itemtype": "method",
+ "name": "removeChild",
+ "params": [
+ {
+ "name": "name",
+ "description": "element name or index
\n",
+ "type": "String|Integer"
+ }
+ ],
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild('animal');\n var children = xml.getChildren();\n for (var i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Leopard\"\n// \"Zebra\"\n
\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild(1);\n var children = xml.getChildren();\n for (var i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Zebra\"\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 484,
+ "description": "Counts the specified element's number of attributes, returned as an Number.
\n",
+ "itemtype": "method",
+ "name": "getAttributeCount",
+ "return": {
+ "description": "",
+ "type": "Integer"
+ },
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getAttributeCount());\n}\n\n// Sketch prints:\n// 2\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 520,
+ "description": "Gets all of the specified element's attributes, and returns them as an\narray of Strings.
\n",
+ "itemtype": "method",
+ "name": "listAttributes",
+ "return": {
+ "description": "an array of strings containing the names of attributes",
+ "type": "String[]"
+ },
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.listAttributes());\n}\n\n// Sketch prints:\n// [\"id\", \"species\"]\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 557,
+ "description": "Checks whether or not an element has the specified attribute.
\n",
+ "itemtype": "method",
+ "name": "hasAttribute",
+ "params": [
+ {
+ "name": "the",
+ "description": "attribute to be checked
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "true if attribute found else false",
+ "type": "Boolean"
+ },
+ "example": [
+ "\n \n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // \n // <mammals>\n // <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n // <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n // <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n // </mammals>\n\n var xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.hasAttribute('species'));\n print(firstChild.hasAttribute('color'));\n }\n\n // Sketch prints:\n // true\n // false\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 596,
+ "description": "Returns an attribute value of the element as an Number. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, the value 0 is returned.
\n",
+ "itemtype": "method",
+ "name": "getNum",
+ "params": [
+ {
+ "name": "name",
+ "description": "the non-null full name of the attribute
\n",
+ "type": "String"
+ },
+ {
+ "name": "defaultValue",
+ "description": "the default value of the attribute
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getNum('id'));\n}\n\n// Sketch prints:\n// 0\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 637,
+ "description": "Returns an attribute value of the element as an String. If the defaultValue\nparameter is specified and the attribute doesn't exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn't\nexist, null is returned.
\n",
+ "itemtype": "method",
+ "name": "getString",
+ "params": [
+ {
+ "name": "name",
+ "description": "the non-null full name of the attribute
\n",
+ "type": "String"
+ },
+ {
+ "name": "defaultValue",
+ "description": "the default value of the attribute
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "String"
+ },
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 678,
+ "description": "Sets the content of an element's attribute. The first parameter specifies\nthe attribute name, while the second specifies the new content.
\n",
+ "itemtype": "method",
+ "name": "setAttribute",
+ "params": [
+ {
+ "name": "name",
+ "description": "the full name of the attribute
\n",
+ "type": "String"
+ },
+ {
+ "name": "value",
+ "description": "the value of the attribute
\n",
+ "type": "Number|String|Boolean"
+ }
+ ],
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n firstChild.setAttribute('species', 'Jamides zebra');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n// \"Jamides zebra\"\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 721,
+ "description": "Returns the content of an element. If there is no such content,\ndefaultValue is returned if specified, otherwise null is returned.
\n",
+ "itemtype": "method",
+ "name": "getContent",
+ "params": [
+ {
+ "name": "defaultValue",
+ "description": "value returned if no content is found
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "String"
+ },
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 759,
+ "description": "Sets the element's content.
\n",
+ "itemtype": "method",
+ "name": "setContent",
+ "params": [
+ {
+ "name": "text",
+ "description": "the new content
\n",
+ "type": "String"
+ }
+ ],
+ "example": [
+ "\n\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// \n// <mammals>\n// <animal id=\"0\" species=\"Capra hircus\">Goat</animal>\n// <animal id=\"1\" species=\"Panthera pardus\">Leopard</animal>\n// <animal id=\"2\" species=\"Equus zebra\">Zebra</animal>\n// </mammals>\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n firstChild.setContent('Mountain Goat');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Mountain Goat\"\n
"
+ ],
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 801,
+ "description": "This method is called while the parsing of XML (when loadXML() is\ncalled). The difference between this method and the setContent()\nmethod defined later is that this one is used to set the content\nwhen the node in question has more nodes under it and so on and\nnot directly text content. While in the other one is used when\nthe node in question directly has text inside it.
\n",
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/io/p5.XML.js",
+ "line": 818,
+ "description": "This method is called while the parsing of XML (when loadXML() is\ncalled). The XML node is passed and its attributes are stored in the\np5.XML's attribute Object.
\n",
+ "class": "p5.XML",
+ "module": "IO",
+ "submodule": "XML"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 12,
+ "description": "Calculates the absolute value (magnitude) of a number. Maps to Math.abs().\nThe absolute value of a number is always positive.
\n",
+ "itemtype": "method",
+ "name": "abs",
+ "params": [
+ {
+ "name": "n",
+ "description": "number to compute
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "absolute value of given number",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction setup() {\n var x = -3;\n var y = abs(x);\n\n print(x); // -3\n print(y); // 3\n}\n
"
+ ],
+ "alt": "no image displayed",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 36,
+ "description": "Calculates the closest int value that is greater than or equal to the\nvalue of the parameter. Maps to Math.ceil(). For example, ceil(9.03)\nreturns the value 10.
\n",
+ "itemtype": "method",
+ "name": "ceil",
+ "params": [
+ {
+ "name": "n",
+ "description": "number to round up
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "rounded up number",
+ "type": "Integer"
+ },
+ "example": [
+ "\n\nfunction draw() {\n background(200);\n // map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n //Get the ceiling of the mapped number.\n var bx = ceil(map(mouseX, 0, 100, 0, 5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
"
+ ],
+ "alt": "2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 76,
+ "description": "Constrains a value between a minimum and maximum value.
\n",
+ "itemtype": "method",
+ "name": "constrain",
+ "params": [
+ {
+ "name": "n",
+ "description": "number to constrain
\n",
+ "type": "Number"
+ },
+ {
+ "name": "low",
+ "description": "minimum limit
\n",
+ "type": "Number"
+ },
+ {
+ "name": "high",
+ "description": "maximum limit
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "constrained number",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction draw() {\n background(200);\n\n var leftWall = 25;\n var rightWall = 75;\n\n // xm is just the mouseX, while\n // xc is the mouseX, but constrained\n // between the leftWall and rightWall!\n var xm = mouseX;\n var xc = constrain(mouseX, leftWall, rightWall);\n\n // Draw the walls.\n stroke(150);\n line(leftWall, 0, leftWall, height);\n line(rightWall, 0, rightWall, height);\n\n // Draw xm and xc as circles.\n noStroke();\n fill(150);\n ellipse(xm, 33, 9, 9); // Not Constrained\n fill(0);\n ellipse(xc, 66, 9, 9); // Constrained\n}\n
"
+ ],
+ "alt": "2 vertical lines. 2 ellipses move with mouse X 1 does not move passed lines",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 121,
+ "description": "Calculates the distance between two points.
\n",
+ "itemtype": "method",
+ "name": "dist",
+ "return": {
+ "description": "distance between the two points",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n// Move your mouse inside the canvas to see the\n// change in distance between two points!\nfunction draw() {\n background(200);\n fill(0);\n\n var x1 = 10;\n var y1 = 90;\n var x2 = mouseX;\n var y2 = mouseY;\n\n line(x1, y1, x2, y2);\n ellipse(x1, y1, 7, 7);\n ellipse(x2, y2, 7, 7);\n\n // d is the length of the line\n // the distance from point 1 to point 2.\n var d = int(dist(x1, y1, x2, y2));\n\n // Let's write d along the line we are drawing!\n push();\n translate((x1 + x2) / 2, (y1 + y2) / 2);\n rotate(atan2(y2 - y1, x2 - x1));\n text(nfc(d, 1), 0, -5);\n pop();\n // Fancy!\n}\n
"
+ ],
+ "alt": "2 ellipses joined by line. 1 ellipse moves with mouse X&Y. Distance displayed.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation",
+ "overloads": [
+ {
+ "line": 121,
+ "params": [
+ {
+ "name": "x1",
+ "description": "x-coordinate of the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y1",
+ "description": "y-coordinate of the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "x-coordinate of the second point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "y-coordinate of the second point
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "distance between the two points",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 165,
+ "params": [
+ {
+ "name": "x1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z1",
+ "description": "z-coordinate of the first point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z2",
+ "description": "z-coordinate of the second point
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "distance between the two points",
+ "type": "Number"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 190,
+ "description": "Returns Euler's number e (2.71828...) raised to the power of the n\nparameter. Maps to Math.exp().
\n",
+ "itemtype": "method",
+ "name": "exp",
+ "params": [
+ {
+ "name": "n",
+ "description": "exponent to raise
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "e^n",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction draw() {\n background(200);\n\n // Compute the exp() function with a value between 0 and 2\n var xValue = map(mouseX, 0, width, 0, 2);\n var yValue = exp(xValue);\n\n var y = map(yValue, 0, 8, height, 0);\n\n var legend = 'exp (' + nfc(xValue, 3) + ')\\n= ' + nf(yValue, 1, 4);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n\n // Draw the exp(x) curve,\n // over the domain of x from 0 to 2\n noFill();\n stroke(0);\n beginShape();\n for (var x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, 2);\n yValue = exp(xValue);\n y = map(yValue, 0, 8, height, 0);\n vertex(x, y);\n }\n\n endShape();\n line(0, 0, 0, height);\n line(0, height - 1, width, height - 1);\n}\n
"
+ ],
+ "alt": "ellipse moves along a curve with mouse x. e^n displayed.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 240,
+ "description": "Calculates the closest int value that is less than or equal to the\nvalue of the parameter. Maps to Math.floor().
\n",
+ "itemtype": "method",
+ "name": "floor",
+ "params": [
+ {
+ "name": "n",
+ "description": "number to round down
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "rounded down number",
+ "type": "Integer"
+ },
+ "example": [
+ "\n\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n //Get the floor of the mapped number.\n var bx = floor(map(mouseX, 0, 100, 0, 5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
"
+ ],
+ "alt": "2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 279,
+ "description": "Calculates a number between two numbers at a specific increment. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first point, 0.1 is very near the first point, 0.5 is\nhalf-way in between, etc. The lerp function is convenient for creating\nmotion along a straight path and for drawing dotted lines.
\n",
+ "itemtype": "method",
+ "name": "lerp",
+ "params": [
+ {
+ "name": "start",
+ "description": "first value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "stop",
+ "description": "second value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "amt",
+ "description": "number between 0.0 and 1.0
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "lerped value",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction setup() {\n background(200);\n var a = 20;\n var b = 80;\n var c = lerp(a, b, 0.2);\n var d = lerp(a, b, 0.5);\n var e = lerp(a, b, 0.8);\n\n var y = 50;\n\n strokeWeight(5);\n stroke(0); // Draw the original points in black\n point(a, y);\n point(b, y);\n\n stroke(100); // Draw the lerp points in gray\n point(c, y);\n point(d, y);\n point(e, y);\n}\n
"
+ ],
+ "alt": "5 points horizontally staggered mid-canvas. mid 3 are grey, outer black",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 324,
+ "description": "Calculates the natural logarithm (the base-e logarithm) of a number. This\nfunction expects the n parameter to be a value greater than 0.0. Maps to\nMath.log().
\n",
+ "itemtype": "method",
+ "name": "log",
+ "params": [
+ {
+ "name": "n",
+ "description": "number greater than 0
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "natural logarithm of n",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction draw() {\n background(200);\n var maxX = 2.8;\n var maxY = 1.5;\n\n // Compute the natural log of a value between 0 and maxX\n var xValue = map(mouseX, 0, width, 0, maxX);\n if (xValue > 0) {\n // Cannot take the log of a negative number.\n var yValue = log(xValue);\n var y = map(yValue, -maxY, maxY, height, 0);\n\n // Display the calculation occurring.\n var legend = 'log(' + nf(xValue, 1, 2) + ')\\n= ' + nf(yValue, 1, 3);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n }\n\n // Draw the log(x) curve,\n // over the domain of x from 0 to maxX\n noFill();\n stroke(0);\n beginShape();\n for (var x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, maxX);\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n vertex(x, y);\n }\n endShape();\n line(0, 0, 0, height);\n line(0, height / 2, width, height / 2);\n}\n
"
+ ],
+ "alt": "ellipse moves along a curve with mouse x. natural logarithm of n displayed.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 379,
+ "description": "Calculates the magnitude (or length) of a vector. A vector is a direction\nin space commonly used in computer graphics and linear algebra. Because it\nhas no "start" position, the magnitude of a vector can be thought of as\nthe distance from the coordinate 0,0 to its x,y value. Therefore, mag() is\na shortcut for writing dist(0, 0, x, y).
\n",
+ "itemtype": "method",
+ "name": "mag",
+ "params": [
+ {
+ "name": "a",
+ "description": "first value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "b",
+ "description": "second value
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "magnitude of vector from (0,0) to (a,b)",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction setup() {\n var x1 = 20;\n var x2 = 80;\n var y1 = 30;\n var y2 = 70;\n\n line(0, 0, x1, y1);\n print(mag(x1, y1)); // Prints \"36.05551275463989\"\n line(0, 0, x2, y1);\n print(mag(x2, y1)); // Prints \"85.44003745317531\"\n line(0, 0, x1, y2);\n print(mag(x1, y2)); // Prints \"72.80109889280519\"\n line(0, 0, x2, y2);\n print(mag(x2, y2)); // Prints \"106.3014581273465\"\n}\n
"
+ ],
+ "alt": "4 lines of different length radiate from top left of canvas.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 418,
+ "description": "Re-maps a number from one range to another.\n
\nIn the first example above, the number 25 is converted from a value in the\nrange of 0 to 100 into a value that ranges from the left edge of the\nwindow (0) to the right edge (width).
\n",
+ "itemtype": "method",
+ "name": "map",
+ "params": [
+ {
+ "name": "value",
+ "description": "the incoming value to be converted
\n",
+ "type": "Number"
+ },
+ {
+ "name": "start1",
+ "description": "lower bound of the value's current range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "stop1",
+ "description": "upper bound of the value's current range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "start2",
+ "description": "lower bound of the value's target range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "stop2",
+ "description": "upper bound of the value's target range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "withinBounds",
+ "description": "constrain the value to the newly mapped range
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "remapped number",
+ "type": "Number"
+ },
+ "example": [
+ "\n \nvar value = 25;\nvar m = map(value, 0, 100, 0, width);\nellipse(m, 50, 10, 10);\n
\n\n \nfunction setup() {\n noStroke();\n}\n\nfunction draw() {\n background(204);\n var x1 = map(mouseX, 0, width, 25, 75);\n ellipse(x1, 25, 25, 25);\n //This ellipse is constrained to the 0-100 range\n //after setting withinBounds to true\n var x2 = map(mouseX, 0, width, 0, 100, true);\n ellipse(x2, 75, 25, 25);\n}\n
"
+ ],
+ "alt": "10 by 10 white ellipse with in mid left canvas\n2 25 by 25 white ellipses move with mouse x. Bottom has more range from X",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 474,
+ "description": "Determines the largest value in a sequence of numbers, and then returns\nthat value. max() accepts any number of Number parameters, or an Array\nof any length.
\n",
+ "itemtype": "method",
+ "name": "max",
+ "return": {
+ "description": "maximum Number",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how max() works!\n var numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n var spacing = 15;\n var elemsY = 25;\n for (var i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n var maxX = 33;\n var maxY = 80;\n // Draw the Maximum value in the array.\n textSize(32);\n text(max(numArray), maxX, maxY);\n}\n
"
+ ],
+ "alt": "Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 9",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation",
+ "overloads": [
+ {
+ "line": 474,
+ "params": [
+ {
+ "name": "n0",
+ "description": "Number to compare
\n",
+ "type": "Number"
+ },
+ {
+ "name": "n1",
+ "description": "Number to compare
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "maximum Number",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 510,
+ "params": [
+ {
+ "name": "nums",
+ "description": "Numbers to compare
\n",
+ "type": "Number[]"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Number"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 524,
+ "description": "Determines the smallest value in a sequence of numbers, and then returns\nthat value. min() accepts any number of Number parameters, or an Array\nof any length.
\n",
+ "itemtype": "method",
+ "name": "min",
+ "return": {
+ "description": "minimum Number",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how min() works!\n var numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n var spacing = 15;\n var elemsY = 25;\n for (var i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n var maxX = 33;\n var maxY = 80;\n // Draw the Minimum value in the array.\n textSize(32);\n text(min(numArray), maxX, maxY);\n}\n
"
+ ],
+ "alt": "Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 1",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation",
+ "overloads": [
+ {
+ "line": 524,
+ "params": [
+ {
+ "name": "n0",
+ "description": "Number to compare
\n",
+ "type": "Number"
+ },
+ {
+ "name": "n1",
+ "description": "Number to compare
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "minimum Number",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 560,
+ "params": [
+ {
+ "name": "nums",
+ "description": "Numbers to compare
\n",
+ "type": "Number[]"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Number"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 574,
+ "description": "Normalizes a number from another range into a value between 0 and 1.\nIdentical to map(value, low, high, 0, 1).\nNumbers outside of the range are not clamped to 0 and 1, because\nout-of-range values are often intentional and useful. (See the second\nexample above.)
\n",
+ "itemtype": "method",
+ "name": "norm",
+ "params": [
+ {
+ "name": "value",
+ "description": "incoming value to be normalized
\n",
+ "type": "Number"
+ },
+ {
+ "name": "start",
+ "description": "lower bound of the value's current range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "stop",
+ "description": "upper bound of the value's current range
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "normalized number",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction draw() {\n background(200);\n var currentNum = mouseX;\n var lowerBound = 0;\n var upperBound = width; //100;\n var normalized = norm(currentNum, lowerBound, upperBound);\n var lineY = 70;\n line(0, lineY, width, lineY);\n //Draw an ellipse mapped to the non-normalized value.\n noStroke();\n fill(50);\n var s = 7; // ellipse size\n ellipse(currentNum, lineY, s, s);\n\n // Draw the guide\n var guideY = lineY + 15;\n text('0', 0, guideY);\n textAlign(RIGHT);\n text('100', width, guideY);\n\n // Draw the normalized value\n textAlign(LEFT);\n fill(0);\n textSize(32);\n var normalY = 40;\n var normalX = 20;\n text(normalized, normalX, normalY);\n}\n
"
+ ],
+ "alt": "ellipse moves with mouse. 0 shown left & 100 right and updating values center",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 627,
+ "description": "Facilitates exponential expressions. The pow() function is an efficient\nway of multiplying numbers by themselves (or their reciprocals) in large\nquantities. For example, pow(3, 5) is equivalent to the expression\n33333 and pow(3, -5) is equivalent to 1 / 33333. Maps to\nMath.pow().
\n",
+ "itemtype": "method",
+ "name": "pow",
+ "params": [
+ {
+ "name": "n",
+ "description": "base of the exponential expression
\n",
+ "type": "Number"
+ },
+ {
+ "name": "e",
+ "description": "power by which to raise the base
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "n^e",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction setup() {\n //Exponentially increase the size of an ellipse.\n var eSize = 3; // Original Size\n var eLoc = 10; // Original Location\n\n ellipse(eLoc, eLoc, eSize, eSize);\n\n ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));\n\n ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));\n\n ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));\n}\n
"
+ ],
+ "alt": "small to large ellipses radiating from top left of canvas",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 661,
+ "description": "Calculates the integer closest to the n parameter. For example,\nround(133.8) returns the value 134. Maps to Math.round().
\n",
+ "itemtype": "method",
+ "name": "round",
+ "params": [
+ {
+ "name": "n",
+ "description": "number to round
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "rounded number",
+ "type": "Integer"
+ },
+ "example": [
+ "\n\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n // Round the mapped number.\n var bx = round(map(mouseX, 0, 100, 0, 5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n
"
+ ],
+ "alt": "horizontal center line squared values displayed on top and regular on bottom.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 700,
+ "description": "Squares a number (multiplies a number by itself). The result is always a\npositive number, as multiplying two negative numbers always yields a\npositive result. For example, -1 * -1 = 1.
\n",
+ "itemtype": "method",
+ "name": "sq",
+ "params": [
+ {
+ "name": "n",
+ "description": "number to square
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "squared number",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction draw() {\n background(200);\n var eSize = 7;\n var x1 = map(mouseX, 0, width, 0, 10);\n var y1 = 80;\n var x2 = sq(x1);\n var y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n var spacing = 15;\n noStroke();\n fill(0);\n text('x = ' + x1, 0, y1 + spacing);\n text('sq(x) = ' + x2, 0, y2 + spacing);\n}\n
"
+ ],
+ "alt": "horizontal center line squared values displayed on top and regular on bottom.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/calculation.js",
+ "line": 747,
+ "description": "Calculates the square root of a number. The square root of a number is\nalways positive, even though there may be a valid negative root. The\nsquare root s of number a is such that s*s = a. It is the opposite of\nsquaring. Maps to Math.sqrt().
\n",
+ "itemtype": "method",
+ "name": "sqrt",
+ "params": [
+ {
+ "name": "n",
+ "description": "non-negative number to square root
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "square root of number",
+ "type": "Number"
+ },
+ "example": [
+ "\n\nfunction draw() {\n background(200);\n var eSize = 7;\n var x1 = mouseX;\n var y1 = 80;\n var x2 = sqrt(x1);\n var y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n noStroke();\n fill(0);\n var spacing = 15;\n text('x = ' + x1, 0, y1 + spacing);\n text('sqrt(x) = ' + x2, 0, y2 + spacing);\n}\n
"
+ ],
+ "alt": "horizontal center line squareroot values displayed on top and regular on bottom.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Calculation"
+ },
+ {
+ "file": "src/math/math.js",
+ "line": 12,
+ "description": "Creates a new p5.Vector (the datatype for storing vectors). This provides a\ntwo or three dimensional vector, specifically a Euclidean (also known as\ngeometric) vector. A vector is an entity that has both magnitude and\ndirection.
\n",
+ "itemtype": "method",
+ "name": "createVector",
+ "params": [
+ {
+ "name": "x",
+ "description": "x component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "y",
+ "description": "y component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "z",
+ "description": "z component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.Vector"
+ },
+ "example": [
+ "\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255, 102, 204);\n}\n\nfunction draw() {\n background(255);\n pointLight(color(255), createVector(sin(millis() / 1000) * 20, -40, -10));\n scale(0.75);\n sphere();\n}\n
"
+ ],
+ "alt": "a purple sphere lit by a point light oscillating horizontally",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/noise.js",
+ "line": 40,
+ "description": "Returns the Perlin noise value at specified coordinates. Perlin noise is\na random sequence generator producing a more natural ordered, harmonic\nsuccession of numbers compared to the standard random() function.\nIt was invented by Ken Perlin in the 1980s and been used since in\ngraphical applications to produce procedural textures, natural motion,\nshapes, terrains etc.
The main difference to the\nrandom() function is that Perlin noise is defined in an infinite\nn-dimensional space where each pair of coordinates corresponds to a\nfixed semi-random value (fixed only for the lifespan of the program; see\nthe noiseSeed() function). p5.js can compute 1D, 2D and 3D noise,\ndepending on the number of coordinates given. The resulting value will\nalways be between 0.0 and 1.0. The noise value can be animated by moving\nthrough the noise space as demonstrated in the example above. The 2nd\nand 3rd dimension can also be interpreted as time.
The actual\nnoise is structured similar to an audio signal, in respect to the\nfunction's use of frequencies. Similar to the concept of harmonics in\nphysics, perlin noise is computed over several octaves which are added\ntogether for the final result.
Another way to adjust the\ncharacter of the resulting sequence is the scale of the input\ncoordinates. As the function works within an infinite space the value of\nthe coordinates doesn't matter as such, only the distance between\nsuccessive coordinates does (eg. when using noise() within a\nloop). As a general rule the smaller the difference between coordinates,\nthe smoother the resulting noise sequence will be. Steps of 0.005-0.03\nwork best for most applications, but this will differ depending on use.
\n",
+ "itemtype": "method",
+ "name": "noise",
+ "params": [
+ {
+ "name": "x",
+ "description": "x-coordinate in noise space
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "y-coordinate in noise space
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "z",
+ "description": "z-coordinate in noise space
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Perlin noise value (between 0 and 1) at specified\n coordinates",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar xoff = 0.0;\n\nfunction draw() {\n background(204);\n xoff = xoff + 0.01;\n var n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n\n
\n\nvar noiseScale=0.02;\n\nfunction draw() {\n background(0);\n for (var x=0; x < width; x++) {\n var noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);\n stroke(noiseVal*255);\n line(x, mouseY+noiseVal*80, x, height);\n }\n}\n\n
"
+ ],
+ "alt": "vertical line moves left to right with updating noise values.\nhorizontal wave pattern effected by mouse x-position & updating noise values.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Noise"
+ },
+ {
+ "file": "src/math/noise.js",
+ "line": 187,
+ "description": "Adjusts the character and level of detail produced by the Perlin noise\n function. Similar to harmonics in physics, noise is computed over\n several octaves. Lower octaves contribute more to the output signal and\n as such define the overall intensity of the noise, whereas higher octaves\n create finer grained details in the noise sequence.\n
\n By default, noise is computed over 4 octaves with each octave contributing\n exactly half than its predecessor, starting at 50% strength for the 1st\n octave. This falloff amount can be changed by adding an additional function\n parameter. Eg. a falloff factor of 0.75 means each octave will now have\n 75% impact (25% less) of the previous lower octave. Any value between\n 0.0 and 1.0 is valid, however note that values greater than 0.5 might\n result in greater than 1.0 values returned by noise().\n
\n By changing these parameters, the signal created by the noise()\n function can be adapted to fit very specific needs and characteristics.
\n",
+ "itemtype": "method",
+ "name": "noiseDetail",
+ "params": [
+ {
+ "name": "lod",
+ "description": "number of octaves to be used by the noise
\n",
+ "type": "Number"
+ },
+ {
+ "name": "falloff",
+ "description": "falloff factor for each octave
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n \n \n var noiseVal;\n var noiseScale = 0.02;\nfunction setup() {\n createCanvas(100, 100);\n }\nfunction draw() {\n background(0);\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width / 2; x++) {\n noiseDetail(2, 0.2);\n noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);\n stroke(noiseVal * 255);\n point(x, y);\n noiseDetail(8, 0.65);\n noiseVal = noise(\n (mouseX + x + width / 2) * noiseScale,\n (mouseY + y) * noiseScale\n );\n stroke(noiseVal * 255);\n point(x + width / 2, y);\n }\n }\n }\n \n
"
+ ],
+ "alt": "2 vertical grey smokey patterns affected my mouse x-position and noise.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Noise"
+ },
+ {
+ "file": "src/math/noise.js",
+ "line": 253,
+ "description": "Sets the seed value for noise(). By default, noise()\nproduces different results each time the program is run. Set the\nvalue parameter to a constant to return the same pseudo-random\nnumbers each time the software is run.
\n",
+ "itemtype": "method",
+ "name": "noiseSeed",
+ "params": [
+ {
+ "name": "seed",
+ "description": "the seed value
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\nvar xoff = 0.0;\n\nfunction setup() {\n noiseSeed(99);\n stroke(0, 10);\n}\n\nfunction draw() {\n xoff = xoff + .01;\n var n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n\n
"
+ ],
+ "alt": "vertical grey lines drawing in pattern affected by noise.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Noise"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 67,
+ "description": "The x component of the vector
\n",
+ "itemtype": "property",
+ "name": "x",
+ "type": "Number",
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 72,
+ "description": "The y component of the vector
\n",
+ "itemtype": "property",
+ "name": "y",
+ "type": "Number",
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 77,
+ "description": "The z component of the vector
\n",
+ "itemtype": "property",
+ "name": "z",
+ "type": "Number",
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 84,
+ "description": "Returns a string representation of a vector v by calling String(v)\nor v.toString(). This method is useful for logging vectors in the\nconsole.
\n",
+ "itemtype": "method",
+ "name": "toString",
+ "return": {
+ "description": "",
+ "type": "String"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n var v = createVector(20, 30);\n print(String(v)); // prints \"p5.Vector Object : [20, 30, 0]\"\n}\n\n
\n\n\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text(v1.toString(), 10, 25, 90, 75);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 134,
+ "description": "Sets the x, y, and z component of the vector using two or three separate\nvariables, the data from a p5.Vector, or the values from a float array.
\n",
+ "itemtype": "method",
+ "name": "set",
+ "chainable": 1,
+ "example": [
+ "\n\n\nfunction setup() {\n var v = createVector(1, 2, 3);\n v.set(4, 5, 6); // Sets vector to [4, 5, 6]\n\n var v1 = createVector(0, 0, 0);\n var arr = [1, 2, 3];\n v1.set(arr); // Sets vector to [1, 2, 3]\n}\n\n
\n\n\n\nvar v0, v1;\nfunction setup() {\n createCanvas(100, 100);\n\n v0 = createVector(0, 0);\n v1 = createVector(50, 50);\n}\n\nfunction draw() {\n background(240);\n\n drawArrow(v0, v1, 'black');\n v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1));\n\n noStroke();\n text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math",
+ "overloads": [
+ {
+ "line": 134,
+ "params": [
+ {
+ "name": "x",
+ "description": "the x component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "y",
+ "description": "the y component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "z",
+ "description": "the z component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 193,
+ "params": [
+ {
+ "name": "value",
+ "description": "the vector to set
\n",
+ "type": "p5.Vector|Number[]"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 217,
+ "description": "Gets a copy of the vector, returns a p5.Vector object.
\n",
+ "itemtype": "method",
+ "name": "copy",
+ "return": {
+ "description": "the copy of the p5.Vector object",
+ "type": "p5.Vector"
+ },
+ "example": [
+ "\n\n\nvar v1 = createVector(1, 2, 3);\nvar v2 = v1.copy();\nprint(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z);\n// Prints \"true\"\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 240,
+ "description": "Adds x, y, and z components to a vector, adds one vector to another, or\nadds two independent vectors together. The version of the method that adds\ntwo vectors together is a static method and returns a p5.Vector, the others\nacts directly on the vector. See the examples for more context.
\n",
+ "itemtype": "method",
+ "name": "add",
+ "chainable": 1,
+ "example": [
+ "\n\n\nvar v = createVector(1, 2, 3);\nv.add(4, 5, 6);\n// v's components are set to [5, 7, 9]\n\n
\n\n\n\n// Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(2, 3, 4);\n\nvar v3 = p5.Vector.add(v1, v2);\n// v3 has components [3, 5, 7]\nprint(v3);\n\n
\n\n\n\n// red vector + blue vector = purple vector\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(-30, 20);\n drawArrow(v1, v2, 'blue');\n\n var v3 = p5.Vector.add(v1, v2);\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math",
+ "overloads": [
+ {
+ "line": 240,
+ "params": [
+ {
+ "name": "x",
+ "description": "the x component of the vector to be added
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "the y component of the vector to be added
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "z",
+ "description": "the z component of the vector to be added
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 306,
+ "params": [
+ {
+ "name": "value",
+ "description": "the vector to add
\n",
+ "type": "p5.Vector|Number[]"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 1556,
+ "params": [
+ {
+ "name": "v1",
+ "description": "a p5.Vector to add
\n",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "v2",
+ "description": "a p5.Vector to add
\n",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "target",
+ "description": "the vector to receive the result
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "static": 1
+ },
+ {
+ "line": 1563,
+ "params": [
+ {
+ "name": "v1",
+ "description": "",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "v2",
+ "description": "",
+ "type": "p5.Vector"
+ }
+ ],
+ "static": 1,
+ "return": {
+ "description": "the resulting p5.Vector",
+ "type": "p5.Vector"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 330,
+ "description": "Subtracts x, y, and z components from a vector, subtracts one vector from\nanother, or subtracts two independent vectors. The version of the method\nthat subtracts two vectors is a static method and returns a p5.Vector, the\nother acts directly on the vector. See the examples for more context.
\n",
+ "itemtype": "method",
+ "name": "sub",
+ "chainable": 1,
+ "example": [
+ "\n\n\nvar v = createVector(4, 5, 6);\nv.sub(1, 1, 1);\n// v's components are set to [3, 4, 5]\n\n
\n\n\n\n// Static method\nvar v1 = createVector(2, 3, 4);\nvar v2 = createVector(1, 2, 3);\n\nvar v3 = p5.Vector.sub(v1, v2);\n// v3 has components [1, 1, 1]\nprint(v3);\n\n
\n\n\n\n// red vector - blue vector = purple vector\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n var v3 = p5.Vector.sub(v1, v2);\n drawArrow(v2, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math",
+ "overloads": [
+ {
+ "line": 330,
+ "params": [
+ {
+ "name": "x",
+ "description": "the x component of the vector to subtract
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "the y component of the vector to subtract
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "z",
+ "description": "the z component of the vector to subtract
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 396,
+ "params": [
+ {
+ "name": "value",
+ "description": "the vector to subtract
\n",
+ "type": "p5.Vector|Number[]"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 1586,
+ "params": [
+ {
+ "name": "v1",
+ "description": "a p5.Vector to subtract from
\n",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "v2",
+ "description": "a p5.Vector to subtract
\n",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "target",
+ "description": "if undefined a new vector will be created
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "static": 1
+ },
+ {
+ "line": 1593,
+ "params": [
+ {
+ "name": "v1",
+ "description": "",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "v2",
+ "description": "",
+ "type": "p5.Vector"
+ }
+ ],
+ "static": 1,
+ "return": {
+ "description": "the resulting p5.Vector",
+ "type": "p5.Vector"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 420,
+ "description": "Multiply the vector by a scalar. The static version of this method\ncreates a new p5.Vector while the non static version acts on the vector\ndirectly. See the examples for more context.
\n",
+ "itemtype": "method",
+ "name": "mult",
+ "chainable": 1,
+ "example": [
+ "\n\n\nvar v = createVector(1, 2, 3);\nv.mult(2);\n// v's components are set to [2, 4, 6]\n\n
\n\n\n\n// Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = p5.Vector.mult(v1, 2);\n// v2 has components [2, 4, 6]\nprint(v2);\n\n
\n\n\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(25, -25);\n drawArrow(v0, v1, 'red');\n\n var num = map(mouseX, 0, width, -2, 2, true);\n var v2 = p5.Vector.mult(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('multiplied by ' + num.toFixed(2), 5, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math",
+ "overloads": [
+ {
+ "line": 420,
+ "params": [
+ {
+ "name": "n",
+ "description": "the number to multiply with the vector
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 1614,
+ "params": [
+ {
+ "name": "v",
+ "description": "the vector to multiply
\n",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "n",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "target",
+ "description": "if undefined a new vector will be created
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "static": 1
+ },
+ {
+ "line": 1621,
+ "params": [
+ {
+ "name": "v",
+ "description": "",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "n",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "static": 1,
+ "return": {
+ "description": "the resulting new p5.Vector",
+ "type": "p5.Vector"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 495,
+ "description": "Divide the vector by a scalar. The static version of this method creates a\nnew p5.Vector while the non static version acts on the vector directly.\nSee the examples for more context.
\n",
+ "itemtype": "method",
+ "name": "div",
+ "chainable": 1,
+ "example": [
+ "\n\n\nvar v = createVector(6, 4, 2);\nv.div(2); //v's components are set to [3, 2, 1]\n\n
\n\n\n\n// Static method\nvar v1 = createVector(6, 4, 2);\nvar v2 = p5.Vector.div(v1, 2);\n// v2 has components [3, 2, 1]\nprint(v2);\n\n
\n\n\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 100);\n var v1 = createVector(50, -50);\n drawArrow(v0, v1, 'red');\n\n var num = map(mouseX, 0, width, 10, 0.5, true);\n var v2 = p5.Vector.div(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('divided by ' + num.toFixed(2), 10, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math",
+ "overloads": [
+ {
+ "line": 495,
+ "params": [
+ {
+ "name": "n",
+ "description": "the number to divide the vector by
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 1641,
+ "params": [
+ {
+ "name": "v",
+ "description": "the vector to divide
\n",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "n",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "target",
+ "description": "if undefined a new vector will be created
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "static": 1
+ },
+ {
+ "line": 1648,
+ "params": [
+ {
+ "name": "v",
+ "description": "",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "n",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "static": 1,
+ "return": {
+ "description": "the resulting new p5.Vector",
+ "type": "p5.Vector"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 573,
+ "description": "Calculates the magnitude (length) of the vector and returns the result as\na float (this is simply the equation sqrt(xx + yy + z*z).)
\n",
+ "itemtype": "method",
+ "name": "mag",
+ "return": {
+ "description": "magnitude of the vector",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length: ' + v1.mag().toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
\n\n\nvar v = createVector(20.0, 30.0, 40.0);\nvar m = v.mag();\nprint(m); // Prints \"53.85164807134504\"\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math",
+ "overloads": [
+ {
+ "line": 573,
+ "params": [],
+ "return": {
+ "description": "magnitude of the vector",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 1738,
+ "params": [
+ {
+ "name": "vecT",
+ "description": "the vector to return the magnitude of
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "static": 1,
+ "return": {
+ "description": "the magnitude of vecT",
+ "type": "Number"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 621,
+ "description": "Calculates the squared magnitude of the vector and returns the result\nas a float (this is simply the equation (xx + yy + z*z).)\nFaster if the real length is not required in the\ncase of comparing vectors, etc.
\n",
+ "itemtype": "method",
+ "name": "magSq",
+ "return": {
+ "description": "squared magnitude of the vector",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\n// Static method\nvar v1 = createVector(6, 4, 2);\nprint(v1.magSq()); // Prints \"56\"\n\n
\n\n\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 675,
+ "description": "Calculates the dot product of two vectors. The version of the method\nthat computes the dot product of two independent vectors is a static\nmethod. See the examples for more context.
\n",
+ "itemtype": "method",
+ "name": "dot",
+ "return": {
+ "description": "the dot product",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(2, 3, 4);\n\nprint(v1.dot(v2)); // Prints \"20\"\n\n
\n\n\n\n//Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(3, 2, 1);\nprint(p5.Vector.dot(v1, v2)); // Prints \"10\"\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math",
+ "overloads": [
+ {
+ "line": 675,
+ "params": [
+ {
+ "name": "x",
+ "description": "x component of the vector
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "y component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "z",
+ "description": "z component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "the dot product",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 706,
+ "params": [
+ {
+ "name": "value",
+ "description": "value component of the vector or a p5.Vector
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 1668,
+ "params": [
+ {
+ "name": "v1",
+ "description": "the first p5.Vector
\n",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "v2",
+ "description": "the second p5.Vector
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "static": 1,
+ "return": {
+ "description": "the dot product",
+ "type": "Number"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 718,
+ "description": "Calculates and returns a vector composed of the cross product between\ntwo vectors. Both the static and non static methods return a new p5.Vector.\nSee the examples for more context.
\n",
+ "itemtype": "method",
+ "name": "cross",
+ "return": {
+ "description": "p5.Vector composed of cross product",
+ "type": "p5.Vector"
+ },
+ "example": [
+ "\n\n\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(1, 2, 3);\n\nv1.cross(v2); // v's components are [0, 0, 0]\n\n
\n\n\n\n// Static method\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar crossProduct = p5.Vector.cross(v1, v2);\n// crossProduct has components [0, 0, 1]\nprint(crossProduct);\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math",
+ "overloads": [
+ {
+ "line": 718,
+ "params": [
+ {
+ "name": "v",
+ "description": "p5.Vector to be crossed
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "return": {
+ "description": "p5.Vector composed of cross product",
+ "type": "p5.Vector"
+ }
+ },
+ {
+ "line": 1682,
+ "params": [
+ {
+ "name": "v1",
+ "description": "the first p5.Vector
\n",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "v2",
+ "description": "the second p5.Vector
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "static": 1,
+ "return": {
+ "description": "the cross product",
+ "type": "Number"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 759,
+ "description": "Calculates the Euclidean distance between two points (considering a\npoint as a vector object).
\n",
+ "itemtype": "method",
+ "name": "dist",
+ "return": {
+ "description": "the distance",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar distance = v1.dist(v2); // distance is 1.4142...\nprint(distance);\n\n
\n\n\n\n// Static method\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar distance = p5.Vector.dist(v1, v2);\n// distance is 1.4142...\nprint(distance);\n\n
\n\n\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n\n var v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math",
+ "overloads": [
+ {
+ "line": 759,
+ "params": [
+ {
+ "name": "v",
+ "description": "the x, y, and z coordinates of a p5.Vector
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "return": {
+ "description": "the distance",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 1697,
+ "params": [
+ {
+ "name": "v1",
+ "description": "the first p5.Vector
\n",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "v2",
+ "description": "the second p5.Vector
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "static": 1,
+ "return": {
+ "description": "the distance",
+ "type": "Number"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 830,
+ "description": "Normalize the vector to length 1 (make it a unit vector).
\n",
+ "itemtype": "method",
+ "name": "normalize",
+ "return": {
+ "description": "normalized p5.Vector",
+ "type": "p5.Vector"
+ },
+ "example": [
+ "\n\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.normalize();\n// v's components are set to\n// [0.4454354, 0.8908708, 0.089087084]\n\n
\n\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n v1.normalize();\n drawArrow(v0, v1.mult(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 886,
+ "description": "Limit the magnitude of this vector to the value used for the max\nparameter.
\n",
+ "itemtype": "method",
+ "name": "limit",
+ "params": [
+ {
+ "name": "max",
+ "description": "the maximum magnitude for the vector
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.limit(5);\n// v's components are set to\n// [2.2271771, 4.4543543, 0.4454354]\n\n
\n\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n drawArrow(v0, v1.limit(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 944,
+ "description": "Set the magnitude of this vector to the value used for the len\nparameter.
\n",
+ "itemtype": "method",
+ "name": "setMag",
+ "params": [
+ {
+ "name": "len",
+ "description": "the new length for this vector
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.setMag(10);\n// v's components are set to [6.0, 8.0, 0.0]\n\n
\n\n\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(50, 50);\n\n drawArrow(v0, v1, 'red');\n\n var length = map(mouseX, 0, width, 0, 141, true);\n v1.setMag(length);\n drawArrow(v0, v1, 'blue');\n\n noStroke();\n text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1000,
+ "description": "Calculate the angle of rotation for this vector (only 2D vectors)
\n",
+ "itemtype": "method",
+ "name": "heading",
+ "return": {
+ "description": "the angle of rotation",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n var v1 = createVector(30, 50);\n print(v1.heading()); // 1.0303768265243125\n\n v1 = createVector(40, 50);\n print(v1.heading()); // 0.8960553845713439\n\n v1 = createVector(30, 70);\n print(v1.heading()); // 1.1659045405098132\n}\n\n
\n\n\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'black');\n\n var myHeading = v1.heading();\n noStroke();\n text(\n 'vector heading: ' +\n myHeading.toFixed(2) +\n ' radians or ' +\n degrees(myHeading).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1069,
+ "description": "Rotate the vector by an angle (only 2D vectors), magnitude remains the\nsame
\n",
+ "itemtype": "method",
+ "name": "rotate",
+ "params": [
+ {
+ "name": "angle",
+ "description": "the angle of rotation
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n\n\nvar v = createVector(10.0, 20.0);\n// v has components [10.0, 20.0, 0.0]\nv.rotate(HALF_PI);\n// v's components are set to [-20.0, 9.999999, 0.0]\n\n
\n\n\n\nvar angle = 0;\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(50, 0);\n\n drawArrow(v0, v1.rotate(angle), 'black');\n angle += 0.01;\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1125,
+ "description": "Calculates and returns the angle (in radians) between two vectors.
\n",
+ "itemtype": "method",
+ "name": "angleBetween",
+ "params": [
+ {
+ "name": "the",
+ "description": "x, y, and z components of a p5.Vector
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "return": {
+ "description": "the angle between (in radians)",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar angle = v1.angleBetween(v2);\n// angle is PI/2\nprint(angle);\n\n
\n\n\n\nfunction draw() {\n background(240);\n var v0 = createVector(50, 50);\n\n var v1 = createVector(50, 0);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX - 50, mouseY - 50);\n drawArrow(v0, v2, 'blue');\n\n var angleBetween = v1.angleBetween(v2);\n noStroke();\n text(\n 'angle between: ' +\n angleBetween.toFixed(2) +\n ' radians or ' +\n degrees(angleBetween).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1198,
+ "description": "Linear interpolate the vector to another vector
\n",
+ "itemtype": "method",
+ "name": "lerp",
+ "chainable": 1,
+ "example": [
+ "\n\n\nvar v = createVector(1, 1, 0);\n\nv.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]\n\n
\n\n\n\nvar v1 = createVector(0, 0, 0);\nvar v2 = createVector(100, 100, 0);\n\nvar v3 = p5.Vector.lerp(v1, v2, 0.5);\n// v3 has components [50,50,0]\nprint(v3);\n\n
\n\n\n\nvar step = 0.01;\nvar amount = 0;\n\nfunction draw() {\n background(240);\n var v0 = createVector(0, 0);\n\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(90, 90);\n drawArrow(v0, v2, 'blue');\n\n if (amount > 1 || amount < 0) {\n step *= -1;\n }\n amount += step;\n var v3 = p5.Vector.lerp(v1, v2, amount);\n\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math",
+ "overloads": [
+ {
+ "line": 1198,
+ "params": [
+ {
+ "name": "x",
+ "description": "the x component
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "the y component
\n",
+ "type": "Number"
+ },
+ {
+ "name": "z",
+ "description": "the z component
\n",
+ "type": "Number"
+ },
+ {
+ "name": "amt",
+ "description": "the amount of interpolation; some value between 0.0\n (old vector) and 1.0 (new vector). 0.9 is very near\n the new vector. 0.5 is halfway in between.
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 1271,
+ "params": [
+ {
+ "name": "v",
+ "description": "the p5.Vector to lerp to
\n",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "amt",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 1712,
+ "params": [
+ {
+ "name": "v1",
+ "description": "",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "v2",
+ "description": "",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "amt",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "target",
+ "description": "if undefined a new vector will be created
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "static": 1
+ },
+ {
+ "line": 1720,
+ "params": [
+ {
+ "name": "v1",
+ "description": "",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "v2",
+ "description": "",
+ "type": "p5.Vector"
+ },
+ {
+ "name": "amt",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "static": 1,
+ "return": {
+ "description": "the lerped value",
+ "type": "Number"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1287,
+ "description": "Return a representation of this vector as a float array. This is only\nfor temporary use. If used in any other fashion, the contents should be\ncopied by using the p5.Vector.copy() method to copy into your own\narray.
\n",
+ "itemtype": "method",
+ "name": "array",
+ "return": {
+ "description": "an Array with the 3 values",
+ "type": "Number[]"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n var v = createVector(20, 30);\n print(v.array()); // Prints : Array [20, 30, 0]\n}\n\n
\n\n\n\nvar v = createVector(10.0, 20.0, 30.0);\nvar f = v.array();\nprint(f[0]); // Prints \"10.0\"\nprint(f[1]); // Prints \"20.0\"\nprint(f[2]); // Prints \"30.0\"\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1319,
+ "description": "Equality check against a p5.Vector
\n",
+ "itemtype": "method",
+ "name": "equals",
+ "return": {
+ "description": "whether the vectors are equals",
+ "type": "Boolean"
+ },
+ "example": [
+ "\n\n\nvar v1 = createVector(5, 10, 20);\nvar v2 = createVector(5, 10, 20);\nvar v3 = createVector(13, 10, 19);\n\nprint(v1.equals(v2.x, v2.y, v2.z)); // true\nprint(v1.equals(v3.x, v3.y, v3.z)); // false\n\n
\n\n\n\nvar v1 = createVector(10.0, 20.0, 30.0);\nvar v2 = createVector(10.0, 20.0, 30.0);\nvar v3 = createVector(0.0, 0.0, 0.0);\nprint(v1.equals(v2)); // true\nprint(v1.equals(v3)); // false\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math",
+ "overloads": [
+ {
+ "line": 1319,
+ "params": [
+ {
+ "name": "x",
+ "description": "the x component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "y",
+ "description": "the y component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "z",
+ "description": "the z component of the vector
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "whether the vectors are equals",
+ "type": "Boolean"
+ }
+ },
+ {
+ "line": 1349,
+ "params": [
+ {
+ "name": "value",
+ "description": "the vector to compare
\n",
+ "type": "p5.Vector|Array"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Boolean"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1374,
+ "description": "Make a new 2D vector from an angle
\n",
+ "itemtype": "method",
+ "name": "fromAngle",
+ "static": 1,
+ "params": [
+ {
+ "name": "angle",
+ "description": "the desired angle, in radians
\n",
+ "type": "Number"
+ },
+ {
+ "name": "length",
+ "description": "the length of the new vector (defaults to 1)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "the new p5.Vector object",
+ "type": "p5.Vector"
+ },
+ "example": [
+ "\n\n\nfunction draw() {\n background(200);\n\n // Create a variable, proportional to the mouseX,\n // varying from 0-360, to represent an angle in degrees.\n angleMode(DEGREES);\n var myDegrees = map(mouseX, 0, width, 0, 360);\n\n // Display that variable in an onscreen text.\n // (Note the nfc() function to truncate additional decimal places,\n // and the \"\\xB0\" character for the degree symbol.)\n var readout = 'angle = ' + nfc(myDegrees, 1) + '\\xB0';\n noStroke();\n fill(0);\n text(readout, 5, 15);\n\n // Create a p5.Vector using the fromAngle function,\n // and extract its x and y components.\n var v = p5.Vector.fromAngle(radians(myDegrees), 30);\n var vx = v.x;\n var vy = v.y;\n\n push();\n translate(width / 2, height / 2);\n noFill();\n stroke(150);\n line(0, 0, 30, 0);\n stroke(0);\n line(0, 0, vx, vy);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1426,
+ "description": "Make a new 3D vector from a pair of ISO spherical angles
\n",
+ "itemtype": "method",
+ "name": "fromAngles",
+ "static": 1,
+ "params": [
+ {
+ "name": "theta",
+ "description": "the polar angle, in radians (zero is up)
\n",
+ "type": "Number"
+ },
+ {
+ "name": "phi",
+ "description": "the azimuthal angle, in radians\n (zero is out of the screen)
\n",
+ "type": "Number"
+ },
+ {
+ "name": "length",
+ "description": "the length of the new vector (defaults to 1)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "the new p5.Vector object",
+ "type": "p5.Vector"
+ },
+ "example": [
+ "\n\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n fill(255);\n noStroke();\n}\nfunction draw() {\n background(255);\n\n var t = millis() / 1000;\n\n // add three point lights\n pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));\n pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));\n pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));\n\n sphere(35);\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1475,
+ "description": "Make a new 2D unit vector from a random angle
\n",
+ "itemtype": "method",
+ "name": "random2D",
+ "static": 1,
+ "return": {
+ "description": "the new p5.Vector object",
+ "type": "p5.Vector"
+ },
+ "example": [
+ "\n\n\nvar v = p5.Vector.random2D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.0] or\n// [-0.4695841, -0.14366731, 0.0] or\n// [0.6091097, -0.22805278, 0.0]\nprint(v);\n\n
\n\n\n\nfunction setup() {\n frameRate(1);\n}\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = p5.Vector.random2D();\n drawArrow(v0, v1.mult(50), 'black');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1528,
+ "description": "Make a new random 3D unit vector.
\n",
+ "itemtype": "method",
+ "name": "random3D",
+ "static": 1,
+ "return": {
+ "description": "the new p5.Vector object",
+ "type": "p5.Vector"
+ },
+ "example": [
+ "\n\n\nvar v = p5.Vector.random3D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.599168] or\n// [-0.4695841, -0.14366731, -0.8711202] or\n// [0.6091097, -0.22805278, -0.7595902]\nprint(v);\n\n
"
+ ],
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1611,
+ "description": "Multiplies a vector by a scalar and returns a new vector.
\n",
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1638,
+ "description": "Divides a vector by a scalar and returns a new vector.
\n",
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1665,
+ "description": "Calculates the dot product of two vectors.
\n",
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1679,
+ "description": "Calculates the cross product of two vectors.
\n",
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1693,
+ "description": "Calculates the Euclidean distance between two points (considering a\npoint as a vector object).
\n",
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/p5.Vector.js",
+ "line": 1708,
+ "description": "Linear interpolate a vector to another vector and return the result as a\nnew vector.
\n",
+ "class": "p5.Vector",
+ "module": "Math",
+ "submodule": "Math"
+ },
+ {
+ "file": "src/math/random.js",
+ "line": 48,
+ "description": "Sets the seed value for random().
\nBy default, random() produces different results each time the program\nis run. Set the seed parameter to a constant to return the same\npseudo-random numbers each time the software is run.
\n",
+ "itemtype": "method",
+ "name": "randomSeed",
+ "params": [
+ {
+ "name": "seed",
+ "description": "the seed value
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n\n\nrandomSeed(99);\nfor (var i = 0; i < 100; i++) {\n var r = random(0, 255);\n stroke(r);\n line(i, 0, i, 100);\n}\n\n
"
+ ],
+ "alt": "many vertical lines drawn in white, black or grey.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Random"
+ },
+ {
+ "file": "src/math/random.js",
+ "line": 79,
+ "description": "Return a random floating-point number.
\nTakes either 0, 1 or 2 arguments.
\nIf no argument is given, returns a random number from 0\nup to (but not including) 1.
\nIf one argument is given and it is a number, returns a random number from 0\nup to (but not including) the number.
\nIf one argument is given and it is an array, returns a random element from\nthat array.
\nIf two arguments are given, returns a random number from the\nfirst argument up to (but not including) the second argument.
\n",
+ "itemtype": "method",
+ "name": "random",
+ "return": {
+ "description": "the random number",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nfor (var i = 0; i < 100; i++) {\n var r = random(50);\n stroke(r * 5);\n line(50, i, 50 + r, i);\n}\n\n
\n\n\nfor (var i = 0; i < 100; i++) {\n var r = random(-50, 50);\n line(50, i, 50 + r, i);\n}\n\n
\n\n\n// Get a random element from an array using the random(Array) syntax\nvar words = ['apple', 'bear', 'cat', 'dog'];\nvar word = random(words); // select random word\ntext(word, 10, 50); // draw the word\n\n
"
+ ],
+ "alt": "100 horizontal lines from center canvas to right. size+fill change each time\n100 horizontal lines from center of canvas. height & side change each render\nword displayed at random. Either apple, bear, cat, or dog",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Random",
+ "overloads": [
+ {
+ "line": 79,
+ "params": [
+ {
+ "name": "min",
+ "description": "the lower bound (inclusive)
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "max",
+ "description": "the upper bound (exclusive)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "the random number",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 133,
+ "params": [
+ {
+ "name": "choices",
+ "description": "the array to choose from
\n",
+ "type": "Array"
+ }
+ ],
+ "return": {
+ "description": "the random element from the array",
+ "type": "*"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/math/random.js",
+ "line": 166,
+ "description": "Returns a random number fitting a Gaussian, or\n normal, distribution. There is theoretically no minimum or maximum\n value that randomGaussian() might return. Rather, there is\n just a very low probability that values far from the mean will be\n returned; and a higher probability that numbers near the mean will\n be returned.\n
\n Takes either 0, 1 or 2 arguments.
\n If no args, returns a mean of 0 and standard deviation of 1.
\n If one arg, that arg is the mean (standard deviation is 1).
\n If two args, first is mean, second is standard deviation.
\n",
+ "itemtype": "method",
+ "name": "randomGaussian",
+ "params": [
+ {
+ "name": "mean",
+ "description": "the mean
\n",
+ "type": "Number"
+ },
+ {
+ "name": "sd",
+ "description": "the standard deviation
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the random number",
+ "type": "Number"
+ },
+ "example": [
+ "\n \n \n for (var y = 0; y < 100; y++) {\n var x = randomGaussian(50, 15);\n line(50, y, x, y);\n }\n \n
\n \n \n var distribution = new Array(360);\nfunction setup() {\n createCanvas(100, 100);\n for (var i = 0; i < distribution.length; i++) {\n distribution[i] = floor(randomGaussian(0, 15));\n }\n }\nfunction draw() {\n background(204);\n translate(width / 2, width / 2);\n for (var i = 0; i < distribution.length; i++) {\n rotate(TWO_PI / distribution.length);\n stroke(0);\n var dist = abs(distribution[i]);\n line(0, 0, dist, 0);\n }\n }\n \n
"
+ ],
+ "alt": "100 horizontal lines from center of canvas. height & side change each render\n black lines radiate from center of canvas. size determined each render",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Random"
+ },
+ {
+ "file": "src/math/trigonometry.js",
+ "line": 20,
+ "description": "The inverse of cos(), returns the arc cosine of a value. This function\nexpects the values in the range of -1 to 1 and values are returned in\nthe range 0 to PI (3.1415927).
\n",
+ "itemtype": "method",
+ "name": "acos",
+ "params": [
+ {
+ "name": "value",
+ "description": "the value whose arc cosine is to be returned
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the arc cosine of the given value",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar a = PI;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: \"3.1415927 : -1.0 : 3.1415927\"\nprint(a + ' : ' + c + ' : ' + ac);\n\n
\n\n\n\nvar a = PI + PI / 4.0;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: \"3.926991 : -0.70710665 : 2.3561943\"\nprint(a + ' : ' + c + ' : ' + ac);\n\n
"
+ ],
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Trigonometry"
+ },
+ {
+ "file": "src/math/trigonometry.js",
+ "line": 54,
+ "description": "The inverse of sin(), returns the arc sine of a value. This function\nexpects the values in the range of -1 to 1 and values are returned\nin the range -PI/2 to PI/2.
\n",
+ "itemtype": "method",
+ "name": "asin",
+ "params": [
+ {
+ "name": "value",
+ "description": "the value whose arc sine is to be returned
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the arc sine of the given value",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar a = PI + PI / 3;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: \"1.0471976 : 0.86602545 : 1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n\n
\n\n\n\nvar a = PI + PI / 3.0;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: \"4.1887903 : -0.86602545 : -1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n\n
\n"
+ ],
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Trigonometry"
+ },
+ {
+ "file": "src/math/trigonometry.js",
+ "line": 89,
+ "description": "The inverse of tan(), returns the arc tangent of a value. This function\nexpects the values in the range of -Infinity to Infinity (exclusive) and\nvalues are returned in the range -PI/2 to PI/2.
\n",
+ "itemtype": "method",
+ "name": "atan",
+ "params": [
+ {
+ "name": "value",
+ "description": "the value whose arc tangent is to be returned
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the arc tangent of the given value",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar a = PI + PI / 3;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: \"1.0471976 : 1.7320509 : 1.0471976\"\nprint(a + ' : ' + t + ' : ' + at);\n\n
\n\n\n\nvar a = PI + PI / 3.0;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: \"4.1887903 : 1.7320513 : 1.0471977\"\nprint(a + ' : ' + t + ' : ' + at);\n\n
\n"
+ ],
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Trigonometry"
+ },
+ {
+ "file": "src/math/trigonometry.js",
+ "line": 124,
+ "description": "Calculates the angle (in radians) from a specified point to the coordinate\norigin as measured from the positive x-axis. Values are returned as a\nfloat in the range from PI to -PI. The atan2() function is most often used\nfor orienting geometry to the position of the cursor.\n
\nNote: The y-coordinate of the point is the first parameter, and the\nx-coordinate is the second parameter, due the the structure of calculating\nthe tangent.
\n",
+ "itemtype": "method",
+ "name": "atan2",
+ "params": [
+ {
+ "name": "y",
+ "description": "y-coordinate of the point
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x",
+ "description": "x-coordinate of the point
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the arc tangent of the given point",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nfunction draw() {\n background(204);\n translate(width / 2, height / 2);\n var a = atan2(mouseY - height / 2, mouseX - width / 2);\n rotate(a);\n rect(-30, -5, 60, 10);\n}\n\n
"
+ ],
+ "alt": "60 by 10 rect at center of canvas rotates with mouse movements",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Trigonometry"
+ },
+ {
+ "file": "src/math/trigonometry.js",
+ "line": 160,
+ "description": "Calculates the cosine of an angle. This function takes into account the\ncurrent angleMode. Values are returned in the range -1 to 1.
\n",
+ "itemtype": "method",
+ "name": "cos",
+ "params": [
+ {
+ "name": "angle",
+ "description": "the angle
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the cosine of the angle",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar a = 0.0;\nvar inc = TWO_PI / 25.0;\nfor (var i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);\n a = a + inc;\n}\n\n
"
+ ],
+ "alt": "vertical black lines form wave patterns, extend-down on left and right side",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Trigonometry"
+ },
+ {
+ "file": "src/math/trigonometry.js",
+ "line": 188,
+ "description": "Calculates the sine of an angle. This function takes into account the\ncurrent angleMode. Values are returned in the range -1 to 1.
\n",
+ "itemtype": "method",
+ "name": "sin",
+ "params": [
+ {
+ "name": "angle",
+ "description": "the angle
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the sine of the angle",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n\nvar a = 0.0;\nvar inc = TWO_PI / 25.0;\nfor (var i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);\n a = a + inc;\n}\n\n
"
+ ],
+ "alt": "vertical black lines extend down and up from center to form wave pattern",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Trigonometry"
+ },
+ {
+ "file": "src/math/trigonometry.js",
+ "line": 216,
+ "description": "Calculates the tangent of an angle. This function takes into account\nthe current angleMode. Values are returned in the range -1 to 1.
\n",
+ "itemtype": "method",
+ "name": "tan",
+ "params": [
+ {
+ "name": "angle",
+ "description": "the angle
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the tangent of the angle",
+ "type": "Number"
+ },
+ "example": [
+ "\n\n
\nvar a = 0.0;\nvar inc = TWO_PI / 50.0;\nfor (var i = 0; i < 100; i = i + 2) {\n line(i, 50, i, 50 + tan(a) * 2.0);\n a = a + inc;\n}\n"
+ ],
+ "alt": "vertical black lines end down and up from center to form spike pattern",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Trigonometry"
+ },
+ {
+ "file": "src/math/trigonometry.js",
+ "line": 244,
+ "description": "
Converts a radian measurement to its corresponding value in degrees.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964. This function does not take into account the\ncurrent angleMode.
\n",
+ "itemtype": "method",
+ "name": "degrees",
+ "params": [
+ {
+ "name": "radians",
+ "description": "
the radians value to convert to degrees
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the converted angle",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\n\nvar rad = PI / 4;\nvar deg = degrees(rad);\nprint(rad + ' radians is ' + deg + ' degrees');\n// Prints: 0.7853981633974483 radians is 45 degrees\n\n
\n"
+ ],
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Trigonometry"
+ },
+ {
+ "file": "src/math/trigonometry.js",
+ "line": 271,
+ "description": "
Converts a degree measurement to its corresponding value in radians.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964. This function does not take into account the\ncurrent angleMode.
\n",
+ "itemtype": "method",
+ "name": "radians",
+ "params": [
+ {
+ "name": "degrees",
+ "description": "
the degree value to convert to radians
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "the converted angle",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\n\nvar deg = 45.0;\nvar rad = radians(deg);\nprint(deg + ' degrees is ' + rad + ' radians');\n// Prints: 45 degrees is 0.7853981633974483 radians\n\n
"
+ ],
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Trigonometry"
+ },
+ {
+ "file": "src/math/trigonometry.js",
+ "line": 296,
+ "description": "
Sets the current mode of p5 to given mode. Default mode is RADIANS.
\n",
+ "itemtype": "method",
+ "name": "angleMode",
+ "params": [
+ {
+ "name": "mode",
+ "description": "
either RADIANS or DEGREES
\n",
+ "type": "Constant"
+ }
+ ],
+ "example": [
+ "\n
\n\nfunction draw() {\n background(204);\n angleMode(DEGREES); // Change the mode to DEGREES\n var a = atan2(mouseY - height / 2, mouseX - width / 2);\n translate(width / 2, height / 2);\n push();\n rotate(a);\n rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees\n pop();\n angleMode(RADIANS); // Change the mode to RADIANS\n rotate(a); // var a stays the same\n rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians\n}\n\n
"
+ ],
+ "alt": "40 by 10 rect in center rotates with mouse moves. 20 by 10 rect moves faster.",
+ "class": "p5",
+ "module": "Math",
+ "submodule": "Trigonometry"
+ },
+ {
+ "file": "src/typography/attributes.js",
+ "line": 13,
+ "description": "
Sets the current alignment for drawing text. Accepts two\narguments: horizAlign (LEFT, CENTER, or RIGHT) and\nvertAlign (TOP, BOTTOM, CENTER, or BASELINE).
\n
The horizAlign parameter is in reference to the x value\nof the text() function, while the vertAlign parameter is\nin reference to the y value.
\n
So if you write textAlign(LEFT), you are aligning the left\nedge of your text to the x value you give in text(). If you\nwrite textAlign(RIGHT, TOP), you are aligning the right edge\nof your text to the x value and the top of edge of the text\nto the y value.
\n",
+ "itemtype": "method",
+ "name": "textAlign",
+ "chainable": 1,
+ "example": [
+ "\n
\n\ntextSize(16);\ntextAlign(RIGHT);\ntext('ABCD', 50, 30);\ntextAlign(CENTER);\ntext('EFGH', 50, 50);\ntextAlign(LEFT);\ntext('IJKL', 50, 70);\n\n
"
+ ],
+ "alt": "Letters ABCD displayed at top right, EFGH at center and IJKL at bottom left.",
+ "class": "p5",
+ "module": "Typography",
+ "submodule": "Attributes",
+ "overloads": [
+ {
+ "line": 13,
+ "params": [
+ {
+ "name": "horizAlign",
+ "description": "
horizontal alignment, either LEFT,\n CENTER, or RIGHT
\n",
+ "type": "Constant"
+ },
+ {
+ "name": "vertAlign",
+ "description": "
vertical alignment, either TOP,\n BOTTOM, CENTER, or BASELINE
\n",
+ "type": "Constant",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 51,
+ "params": [],
+ "return": {
+ "description": "",
+ "type": "Object"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/typography/attributes.js",
+ "line": 60,
+ "description": "
Sets/gets the spacing, in pixels, between lines of text. This\nsetting will be used in all subsequent calls to the text() function.
\n",
+ "itemtype": "method",
+ "name": "textLeading",
+ "chainable": 1,
+ "example": [
+ "\n
\n\n// Text to display. The \"\\n\" is a \"new line\" character\nvar lines = 'L1\\nL2\\nL3';\ntextSize(12);\n\ntextLeading(10); // Set leading to 10\ntext(lines, 10, 25);\n\ntextLeading(20); // Set leading to 20\ntext(lines, 40, 25);\n\ntextLeading(30); // Set leading to 30\ntext(lines, 70, 25);\n\n
"
+ ],
+ "alt": "set L1 L2 & L3 displayed vertically 3 times. spacing increases for each set",
+ "class": "p5",
+ "module": "Typography",
+ "submodule": "Attributes",
+ "overloads": [
+ {
+ "line": 60,
+ "params": [
+ {
+ "name": "leading",
+ "description": "
the size in pixels for spacing between lines
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 89,
+ "params": [],
+ "return": {
+ "description": "",
+ "type": "Number"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/typography/attributes.js",
+ "line": 98,
+ "description": "
Sets/gets the current font size. This size will be used in all subsequent\ncalls to the text() function. Font size is measured in pixels.
\n",
+ "itemtype": "method",
+ "name": "textSize",
+ "chainable": 1,
+ "example": [
+ "\n
\n\ntextSize(12);\ntext('Font Size 12', 10, 30);\ntextSize(14);\ntext('Font Size 14', 10, 60);\ntextSize(16);\ntext('Font Size 16', 10, 90);\n\n
"
+ ],
+ "alt": "Font Size 12 displayed small, Font Size 14 medium & Font Size 16 large",
+ "class": "p5",
+ "module": "Typography",
+ "submodule": "Attributes",
+ "overloads": [
+ {
+ "line": 98,
+ "params": [
+ {
+ "name": "theSize",
+ "description": "
the size of the letters in units of pixels
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 121,
+ "params": [],
+ "return": {
+ "description": "",
+ "type": "Number"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/typography/attributes.js",
+ "line": 130,
+ "description": "
Sets/gets the style of the text for system fonts to NORMAL, ITALIC, or BOLD.\nNote: this may be is overridden by CSS styling. For non-system fonts\n(opentype, truetype, etc.) please load styled fonts instead.
\n",
+ "itemtype": "method",
+ "name": "textStyle",
+ "chainable": 1,
+ "example": [
+ "\n
\n\nstrokeWeight(0);\ntextSize(12);\ntextStyle(NORMAL);\ntext('Font Style Normal', 10, 30);\ntextStyle(ITALIC);\ntext('Font Style Italic', 10, 60);\ntextStyle(BOLD);\ntext('Font Style Bold', 10, 90);\n\n
"
+ ],
+ "alt": "words Font Style Normal displayed normally, Italic in italic and bold in bold",
+ "class": "p5",
+ "module": "Typography",
+ "submodule": "Attributes",
+ "overloads": [
+ {
+ "line": 130,
+ "params": [
+ {
+ "name": "theStyle",
+ "description": "
styling for text, either NORMAL,\n ITALIC, or BOLD
\n",
+ "type": "Constant"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 156,
+ "params": [],
+ "return": {
+ "description": "",
+ "type": "String"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/typography/attributes.js",
+ "line": 165,
+ "description": "
Calculates and returns the width of any character or text string.
\n",
+ "itemtype": "method",
+ "name": "textWidth",
+ "params": [
+ {
+ "name": "theText",
+ "description": "
the String of characters to measure
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\n\ntextSize(28);\n\nvar aChar = 'P';\nvar cWidth = textWidth(aChar);\ntext(aChar, 0, 40);\nline(cWidth, 0, cWidth, 50);\n\nvar aString = 'p5.js';\nvar sWidth = textWidth(aString);\ntext(aString, 0, 85);\nline(sWidth, 50, sWidth, 100);\n\n
"
+ ],
+ "alt": "Letter P and p5.js are displayed with vertical lines at end. P is wide",
+ "class": "p5",
+ "module": "Typography",
+ "submodule": "Attributes"
+ },
+ {
+ "file": "src/typography/attributes.js",
+ "line": 200,
+ "description": "
Returns the ascent of the current font at its current size. The ascent\nrepresents the distance, in pixels, of the tallest character above\nthe baseline.
\n",
+ "itemtype": "method",
+ "name": "textAscent",
+ "return": {
+ "description": "",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\n\nvar base = height * 0.75;\nvar scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nvar asc = textAscent() * scalar; // Calc ascent\nline(0, base - asc, width, base - asc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\nasc = textAscent() * scalar; // Recalc ascent\nline(40, base - asc, width, base - asc);\ntext('dp', 40, base); // Draw text on baseline\n\n
"
+ ],
+ "class": "p5",
+ "module": "Typography",
+ "submodule": "Attributes"
+ },
+ {
+ "file": "src/typography/attributes.js",
+ "line": 229,
+ "description": "
Returns the descent of the current font at its current size. The descent\nrepresents the distance, in pixels, of the character with the longest\ndescender below the baseline.
\n",
+ "itemtype": "method",
+ "name": "textDescent",
+ "return": {
+ "description": "",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\n\nvar base = height * 0.75;\nvar scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nvar desc = textDescent() * scalar; // Calc ascent\nline(0, base + desc, width, base + desc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\ndesc = textDescent() * scalar; // Recalc ascent\nline(40, base + desc, width, base + desc);\ntext('dp', 40, base); // Draw text on baseline\n\n
"
+ ],
+ "class": "p5",
+ "module": "Typography",
+ "submodule": "Attributes"
+ },
+ {
+ "file": "src/typography/attributes.js",
+ "line": 258,
+ "description": "
Helper function to measure ascent and descent.
\n",
+ "class": "p5",
+ "module": "Typography",
+ "submodule": "Attributes"
+ },
+ {
+ "file": "src/typography/loading_displaying.js",
+ "line": 16,
+ "description": "
Loads an opentype font file (.otf, .ttf) from a file or a URL,\nand returns a PFont Object. This method is asynchronous,\nmeaning it may not finish before the next line in your sketch\nis executed.\n
\nThe path to the font should be relative to the HTML file\nthat links in your sketch. Loading an from a URL or other\nremote location may be blocked due to your browser's built-in\nsecurity.
\n",
+ "itemtype": "method",
+ "name": "loadFont",
+ "params": [
+ {
+ "name": "path",
+ "description": "
name of the file or url to load
\n",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "
function to be executed after\n loadFont() completes
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "onError",
+ "description": "
function to be executed if\n an error occurs
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "p5.Font object",
+ "type": "p5.Font"
+ },
+ "example": [
+ "\n\n
Calling loadFont() inside preload() guarantees that the load\noperation will have completed before setup() and draw() are called.
\n\n
\nvar myFont;\nfunction preload() {\n myFont = loadFont('assets/AvenirNextLTPro-Demi.otf');\n}\n\nfunction setup() {\n fill('#ED225D');\n textFont(myFont);\n textSize(36);\n text('p5*js', 10, 50);\n}\n
\n\nOutside of preload(), you may supply a callback function to handle the\nobject:\n\n
\nfunction setup() {\n loadFont('assets/AvenirNextLTPro-Demi.otf', drawText);\n}\n\nfunction drawText(font) {\n fill('#ED225D');\n textFont(font, 36);\n text('p5*js', 10, 50);\n}\n
\n\n
You can also use the string name of the font to style other HTML\nelements.
\n\n
\nfunction preload() {\n loadFont('assets/Avenir.otf');\n}\n\nfunction setup() {\n var myDiv = createDiv('hello there');\n myDiv.style('font-family', 'Avenir');\n}\n
"
+ ],
+ "alt": "p5*js in p5's theme dark pink\np5*js in p5's theme dark pink",
+ "class": "p5",
+ "module": "Typography",
+ "submodule": "Loading & Displaying"
+ },
+ {
+ "file": "src/typography/loading_displaying.js",
+ "line": 143,
+ "description": "
Draws text to the screen. Displays the information specified in the first\nparameter on the screen in the position specified by the additional\nparameters. A default font will be used unless a font is set with the\ntextFont() function and a default size will be used unless a font is set\nwith textSize(). Change the color of the text with the fill() function.\nChange the outline of the text with the stroke() and strokeWeight()\nfunctions.\n
\nThe text displays in relation to the textAlign() function, which gives the\noption to draw to the left, right, and center of the coordinates.\n
\nThe x2 and y2 parameters define a rectangular area to display within and\nmay only be used with string data. When these parameters are specified,\nthey are interpreted based on the current rectMode() setting. Text that\ndoes not fit completely within the rectangle specified will not be drawn\nto the screen.
\n",
+ "itemtype": "method",
+ "name": "text",
+ "params": [
+ {
+ "name": "str",
+ "description": "
the alphanumeric\n symbols to be displayed
\n",
+ "type": "String|Object|Array|Number|Boolean"
+ },
+ {
+ "name": "x",
+ "description": "
x-coordinate of text
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "
y-coordinate of text
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x2",
+ "description": "
by default, the width of the text box,\n see rectMode() for more info
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "y2",
+ "description": "
by default, the height of the text box,\n see rectMode() for more info
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\ntextSize(32);\ntext('word', 10, 30);\nfill(0, 102, 153);\ntext('word', 10, 60);\nfill(0, 102, 153, 51);\ntext('word', 10, 90);\n\n
\n
\n\nvar s = 'The quick brown fox jumped over the lazy dog.';\nfill(50);\ntext(s, 10, 10, 70, 80); // Text wraps within text box\n\n
"
+ ],
+ "alt": "'word' displayed 3 times going from black, blue to translucent blue\nThe quick brown fox jumped over the lazy dog.",
+ "class": "p5",
+ "module": "Typography",
+ "submodule": "Loading & Displaying"
+ },
+ {
+ "file": "src/typography/loading_displaying.js",
+ "line": 202,
+ "description": "
Sets the current font that will be drawn with the text() function.
\n",
+ "itemtype": "method",
+ "name": "textFont",
+ "return": {
+ "description": "the current font",
+ "type": "Object"
+ },
+ "example": [
+ "\n
\n\nfill(0);\ntextSize(12);\ntextFont('Georgia');\ntext('Georgia', 12, 30);\ntextFont('Helvetica');\ntext('Helvetica', 12, 60);\n\n
\n
\n\nvar fontRegular, fontItalic, fontBold;\nfunction preload() {\n fontRegular = loadFont('assets/Regular.otf');\n fontItalic = loadFont('assets/Italic.ttf');\n fontBold = loadFont('assets/Bold.ttf');\n}\nfunction setup() {\n background(210);\n fill(0)\n .strokeWeight(0)\n .textSize(10);\n textFont(fontRegular);\n text('Font Style Normal', 10, 30);\n textFont(fontItalic);\n text('Font Style Italic', 10, 50);\n textFont(fontBold);\n text('Font Style Bold', 10, 70);\n}\n\n
"
+ ],
+ "alt": "words Font Style Normal displayed normally, Italic in italic and bold in bold",
+ "class": "p5",
+ "module": "Typography",
+ "submodule": "Loading & Displaying",
+ "overloads": [
+ {
+ "line": 202,
+ "params": [],
+ "return": {
+ "description": "the current font",
+ "type": "Object"
+ }
+ },
+ {
+ "line": 245,
+ "params": [
+ {
+ "name": "font",
+ "description": "
a font loaded via loadFont(), or a String\nrepresenting a web safe font (a font\nthat is generally available across all systems)
\n",
+ "type": "Object|String"
+ },
+ {
+ "name": "size",
+ "description": "
the font size to use
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/typography/p5.Font.js",
+ "line": 31,
+ "description": "
Underlying opentype font implementation
\n",
+ "itemtype": "property",
+ "name": "font",
+ "class": "p5.Font",
+ "module": "Typography",
+ "submodule": "Font"
+ },
+ {
+ "file": "src/typography/p5.Font.js",
+ "line": 43,
+ "description": "
Returns a tight bounding box for the given text string using this\nfont (currently only supports single lines)
\n",
+ "itemtype": "method",
+ "name": "textBounds",
+ "params": [
+ {
+ "name": "line",
+ "description": "
a line of text
\n",
+ "type": "String"
+ },
+ {
+ "name": "x",
+ "description": "
x-position
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "
y-position
\n",
+ "type": "Number"
+ },
+ {
+ "name": "fontSize",
+ "description": "
font size to use (optional)
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "options",
+ "description": "
opentype options (optional)
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "a rectangle object with properties: x, y, w, h",
+ "type": "Object"
+ },
+ "example": [
+ "\n
\n\nvar font;\nvar textString = 'Lorem ipsum dolor sit amet.';\nfunction preload() {\n font = loadFont('./assets/Regular.otf');\n}\nfunction setup() {\n background(210);\n\n var bbox = font.textBounds(textString, 10, 30, 12);\n fill(255);\n stroke(0);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n fill(0);\n noStroke();\n\n textFont(font);\n textSize(12);\n text(textString, 10, 30);\n}\n\n
"
+ ],
+ "alt": "words Lorem ipsum dol go off canvas and contained by white bounding box",
+ "class": "p5.Font",
+ "module": "Typography",
+ "submodule": "Font"
+ },
+ {
+ "file": "src/typography/p5.Font.js",
+ "line": 158,
+ "description": "
Computes an array of points following the path for specified text
\n",
+ "itemtype": "method",
+ "name": "textToPoints",
+ "params": [
+ {
+ "name": "txt",
+ "description": "
a line of text
\n",
+ "type": "String"
+ },
+ {
+ "name": "x",
+ "description": "
x-position
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "
y-position
\n",
+ "type": "Number"
+ },
+ {
+ "name": "fontSize",
+ "description": "
font size to use (optional)
\n",
+ "type": "Number"
+ },
+ {
+ "name": "options",
+ "description": "
an (optional) object that can contain:
\n
sampleFactor - the ratio of path-length to number of samples\n(default=.25); higher values yield more points and are therefore\nmore precise
\n
simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "an array of points, each with x, y, alpha (the path angle)",
+ "type": "Array"
+ },
+ "example": [
+ "\n
\n\nvar font;\nfunction preload() {\n font = loadFont('./assets/Avenir.otf');\n}\n\nvar points;\nvar bounds;\nfunction setup() {\n createCanvas(100, 100);\n stroke(0);\n fill(255, 104, 204);\n\n points = font.textToPoints('p5', 0, 0, 10, {\n sampleFactor: 5,\n simplifyThreshold: 0\n });\n bounds = font.textBounds(' p5 ', 0, 0, 10);\n}\n\nfunction draw() {\n background(255);\n beginShape();\n translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h);\n for (var i = 0; i < points.length; i++) {\n var p = points[i];\n vertex(\n p.x * width / bounds.w +\n sin(20 * p.y / bounds.h + millis() / 1000) * width / 30,\n p.y * height / bounds.h\n );\n }\n endShape(CLOSE);\n}\n\n
\n"
+ ],
+ "class": "p5.Font",
+ "module": "Typography",
+ "submodule": "Font"
+ },
+ {
+ "file": "src/utilities/array_functions.js",
+ "line": 12,
+ "description": "
Adds a value to the end of an array. Extends the length of\nthe array by one. Maps to Array.push().
\n",
+ "itemtype": "method",
+ "name": "append",
+ "deprecated": true,
+ "deprecationMessage": "Use
array.push(value) instead.",
+ "params": [
+ {
+ "name": "array",
+ "description": "
Array to append
\n",
+ "type": "Array"
+ },
+ {
+ "name": "value",
+ "description": "
to be added to the Array
\n",
+ "type": "Any"
+ }
+ ],
+ "example": [
+ "\n
\nfunction setup() {\n var myArray = ['Mango', 'Apple', 'Papaya'];\n print(myArray); // ['Mango', 'Apple', 'Papaya']\n\n append(myArray, 'Peach');\n print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']\n}\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Array Functions"
+ },
+ {
+ "file": "src/utilities/array_functions.js",
+ "line": 36,
+ "description": "
Copies an array (or part of an array) to another array. The src array is\ncopied to the dst array, beginning at the position specified by\nsrcPosition and into the position specified by dstPosition. The number of\nelements to copy is determined by length. Note that copying values\noverwrites existing values in the destination array. To append values\ninstead of overwriting them, use concat().\n
\nThe simplified version with only two arguments, arrayCopy(src, dst),\ncopies an entire array to another of the same size. It is equivalent to\narrayCopy(src, 0, dst, 0, src.length).\n
\nUsing this function is far more efficient for copying array data than\niterating through a for() loop and copying each element individually.
\n",
+ "itemtype": "method",
+ "name": "arrayCopy",
+ "deprecated": true,
+ "example": [
+ "\n
\nvar src = ['A', 'B', 'C'];\nvar dst = [1, 2, 3];\nvar srcPosition = 1;\nvar dstPosition = 0;\nvar length = 2;\n\nprint(src); // ['A', 'B', 'C']\nprint(dst); // [ 1 , 2 , 3 ]\n\narrayCopy(src, srcPosition, dst, dstPosition, length);\nprint(dst); // ['B', 'C', 3]\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Array Functions",
+ "overloads": [
+ {
+ "line": 36,
+ "params": [
+ {
+ "name": "src",
+ "description": "
the source Array
\n",
+ "type": "Array"
+ },
+ {
+ "name": "srcPosition",
+ "description": "
starting position in the source Array
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "dst",
+ "description": "
the destination Array
\n",
+ "type": "Array"
+ },
+ {
+ "name": "dstPosition",
+ "description": "
starting position in the destination Array
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "length",
+ "description": "
number of Array elements to be copied
\n",
+ "type": "Integer"
+ }
+ ]
+ },
+ {
+ "line": 74,
+ "params": [
+ {
+ "name": "src",
+ "description": "",
+ "type": "Array"
+ },
+ {
+ "name": "dst",
+ "description": "",
+ "type": "Array"
+ },
+ {
+ "name": "length",
+ "description": "",
+ "type": "Integer",
+ "optional": true
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/array_functions.js",
+ "line": 113,
+ "description": "
Concatenates two arrays, maps to Array.concat(). Does not modify the\ninput arrays.
\n",
+ "itemtype": "method",
+ "name": "concat",
+ "deprecated": true,
+ "deprecationMessage": "Use
arr1.concat(arr2) instead.",
+ "params": [
+ {
+ "name": "a",
+ "description": "
first Array to concatenate
\n",
+ "type": "Array"
+ },
+ {
+ "name": "b",
+ "description": "
second Array to concatenate
\n",
+ "type": "Array"
+ }
+ ],
+ "return": {
+ "description": "concatenated array",
+ "type": "Array"
+ },
+ "example": [
+ "\n
\nfunction setup() {\n var arr1 = ['A', 'B', 'C'];\n var arr2 = [1, 2, 3];\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1,2,3]\n\n var arr3 = concat(arr1, arr2);\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1, 2, 3]\n print(arr3); // ['A','B','C', 1, 2, 3]\n}\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Array Functions"
+ },
+ {
+ "file": "src/utilities/array_functions.js",
+ "line": 144,
+ "description": "
Reverses the order of an array, maps to Array.reverse()
\n",
+ "itemtype": "method",
+ "name": "reverse",
+ "deprecated": true,
+ "deprecationMessage": "Use
array.reverse() instead.",
+ "params": [
+ {
+ "name": "list",
+ "description": "
Array to reverse
\n",
+ "type": "Array"
+ }
+ ],
+ "example": [
+ "\n
\nfunction setup() {\n var myArray = ['A', 'B', 'C'];\n print(myArray); // ['A','B','C']\n\n reverse(myArray);\n print(myArray); // ['C','B','A']\n}\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Array Functions"
+ },
+ {
+ "file": "src/utilities/array_functions.js",
+ "line": 165,
+ "description": "
Decreases an array by one element and returns the shortened array,\nmaps to Array.pop().
\n",
+ "itemtype": "method",
+ "name": "shorten",
+ "deprecated": true,
+ "deprecationMessage": "Use
array.pop() instead.",
+ "params": [
+ {
+ "name": "list",
+ "description": "
Array to shorten
\n",
+ "type": "Array"
+ }
+ ],
+ "return": {
+ "description": "shortened Array",
+ "type": "Array"
+ },
+ "example": [
+ "\n
\nfunction setup() {\n var myArray = ['A', 'B', 'C'];\n print(myArray); // ['A', 'B', 'C']\n var newArray = shorten(myArray);\n print(myArray); // ['A','B','C']\n print(newArray); // ['A','B']\n}\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Array Functions"
+ },
+ {
+ "file": "src/utilities/array_functions.js",
+ "line": 189,
+ "description": "
Randomizes the order of the elements of an array. Implements\n\nFisher-Yates Shuffle Algorithm.
\n",
+ "itemtype": "method",
+ "name": "shuffle",
+ "deprecated": true,
+ "deprecationMessage": "See
shuffling an array with JS instead.",
+ "params": [
+ {
+ "name": "array",
+ "description": "
Array to shuffle
\n",
+ "type": "Array"
+ },
+ {
+ "name": "bool",
+ "description": "
modify passed array
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "shuffled Array",
+ "type": "Array"
+ },
+ "example": [
+ "\n
\nfunction setup() {\n var regularArr = ['ABC', 'def', createVector(), TAU, Math.E];\n print(regularArr);\n shuffle(regularArr, true); // force modifications to passed array\n print(regularArr);\n\n // By default shuffle() returns a shuffled cloned array:\n var newArr = shuffle(regularArr);\n print(regularArr);\n print(newArr);\n}\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Array Functions"
+ },
+ {
+ "file": "src/utilities/array_functions.js",
+ "line": 232,
+ "description": "
Sorts an array of numbers from smallest to largest, or puts an array of\nwords in alphabetical order. The original array is not modified; a\nre-ordered array is returned. The count parameter states the number of\nelements to sort. For example, if there are 12 elements in an array and\ncount is set to 5, only the first 5 elements in the array will be sorted.
\n",
+ "itemtype": "method",
+ "name": "sort",
+ "deprecated": true,
+ "deprecationMessage": "Use
array.sort() instead.",
+ "params": [
+ {
+ "name": "list",
+ "description": "
Array to sort
\n",
+ "type": "Array"
+ },
+ {
+ "name": "count",
+ "description": "
number of elements to sort, starting from 0
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n
\nfunction setup() {\n var words = ['banana', 'apple', 'pear', 'lime'];\n print(words); // ['banana', 'apple', 'pear', 'lime']\n var count = 4; // length of array\n\n words = sort(words, count);\n print(words); // ['apple', 'banana', 'lime', 'pear']\n}\n
\n
\nfunction setup() {\n var numbers = [2, 6, 1, 5, 14, 9, 8, 12];\n print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12]\n var count = 5; // Less than the length of the array\n\n numbers = sort(numbers, count);\n print(numbers); // [1,2,5,6,14,9,8,12]\n}\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Array Functions"
+ },
+ {
+ "file": "src/utilities/array_functions.js",
+ "line": 279,
+ "description": "
Inserts a value or an array of values into an existing array. The first\nparameter specifies the initial array to be modified, and the second\nparameter defines the data to be inserted. The third parameter is an index\nvalue which specifies the array position from which to insert data.\n(Remember that array index numbering starts at zero, so the first position\nis 0, the second position is 1, and so on.)
\n",
+ "itemtype": "method",
+ "name": "splice",
+ "deprecated": true,
+ "deprecationMessage": "Use
array.splice() instead.",
+ "params": [
+ {
+ "name": "list",
+ "description": "
Array to splice into
\n",
+ "type": "Array"
+ },
+ {
+ "name": "value",
+ "description": "
value to be spliced in
\n",
+ "type": "Any"
+ },
+ {
+ "name": "position",
+ "description": "
in the array from which to insert data
\n",
+ "type": "Integer"
+ }
+ ],
+ "example": [
+ "\n
\nfunction setup() {\n var myArray = [0, 1, 2, 3, 4];\n var insArray = ['A', 'B', 'C'];\n print(myArray); // [0, 1, 2, 3, 4]\n print(insArray); // ['A','B','C']\n\n splice(myArray, insArray, 3);\n print(myArray); // [0,1,2,'A','B','C',3,4]\n}\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Array Functions"
+ },
+ {
+ "file": "src/utilities/array_functions.js",
+ "line": 313,
+ "description": "
Extracts an array of elements from an existing array. The list parameter\ndefines the array from which the elements will be copied, and the start\nand count parameters specify which elements to extract. If no count is\ngiven, elements will be extracted from the start to the end of the array.\nWhen specifying the start, remember that the first array element is 0.\nThis function does not change the source array.
\n",
+ "itemtype": "method",
+ "name": "subset",
+ "deprecated": true,
+ "deprecationMessage": "Use
array.slice() instead.",
+ "params": [
+ {
+ "name": "list",
+ "description": "
Array to extract from
\n",
+ "type": "Array"
+ },
+ {
+ "name": "start",
+ "description": "
position to begin
\n",
+ "type": "Integer"
+ },
+ {
+ "name": "count",
+ "description": "
number of values to extract
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Array of extracted elements",
+ "type": "Array"
+ },
+ "example": [
+ "\n
\nfunction setup() {\n var myArray = [1, 2, 3, 4, 5];\n print(myArray); // [1, 2, 3, 4, 5]\n\n var sub1 = subset(myArray, 0, 3);\n var sub2 = subset(myArray, 2, 2);\n print(sub1); // [1,2,3]\n print(sub2); // [3,4]\n}\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Array Functions"
+ },
+ {
+ "file": "src/utilities/conversion.js",
+ "line": 12,
+ "description": "
Converts a string to its floating point representation. The contents of a\nstring must resemble a number, or NaN (not a number) will be returned.\nFor example, float("1234.56") evaluates to 1234.56, but float("giraffe")\nwill return NaN.
\n
When an array of values is passed in, then an array of floats of the same\nlength is returned.
\n",
+ "itemtype": "method",
+ "name": "float",
+ "params": [
+ {
+ "name": "str",
+ "description": "
float string to parse
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "floating point representation of string",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\nvar str = '20';\nvar diameter = float(str);\nellipse(width / 2, height / 2, diameter, diameter);\n
"
+ ],
+ "alt": "20 by 20 white ellipse in the center of the canvas",
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Conversion"
+ },
+ {
+ "file": "src/utilities/conversion.js",
+ "line": 42,
+ "description": "
Converts a boolean, string, or float to its integer representation.\nWhen an array of values is passed in, then an int array of the same length\nis returned.
\n",
+ "itemtype": "method",
+ "name": "int",
+ "return": {
+ "description": "integer representation of value",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\nprint(int('10')); // 10\nprint(int(10.31)); // 10\nprint(int(-10)); // -10\nprint(int(true)); // 1\nprint(int(false)); // 0\nprint(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Conversion",
+ "overloads": [
+ {
+ "line": 42,
+ "params": [
+ {
+ "name": "n",
+ "description": "
value to parse
\n",
+ "type": "String|Boolean|Number"
+ },
+ {
+ "name": "radix",
+ "description": "
the radix to convert to (default: 10)
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "integer representation of value",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 62,
+ "params": [
+ {
+ "name": "ns",
+ "description": "
values to parse
\n",
+ "type": "Array"
+ }
+ ],
+ "return": {
+ "description": "integer representation of values",
+ "type": "Number[]"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/conversion.js",
+ "line": 82,
+ "description": "
Converts a boolean, string or number to its string representation.\nWhen an array of values is passed in, then an array of strings of the same\nlength is returned.
\n",
+ "itemtype": "method",
+ "name": "str",
+ "params": [
+ {
+ "name": "n",
+ "description": "
value to parse
\n",
+ "type": "String|Boolean|Number|Array"
+ }
+ ],
+ "return": {
+ "description": "string representation of value",
+ "type": "String"
+ },
+ "example": [
+ "\n
\nprint(str('10')); // \"10\"\nprint(str(10.31)); // \"10.31\"\nprint(str(-10)); // \"-10\"\nprint(str(true)); // \"true\"\nprint(str(false)); // \"false\"\nprint(str([true, '10.3', 9.8])); // [ \"true\", \"10.3\", \"9.8\" ]\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Conversion"
+ },
+ {
+ "file": "src/utilities/conversion.js",
+ "line": 108,
+ "description": "
Converts a number or string to its boolean representation.\nFor a number, any non-zero value (positive or negative) evaluates to true,\nwhile zero evaluates to false. For a string, the value "true" evaluates to\ntrue, while any other value evaluates to false. When an array of number or\nstring values is passed in, then a array of booleans of the same length is\nreturned.
\n",
+ "itemtype": "method",
+ "name": "boolean",
+ "params": [
+ {
+ "name": "n",
+ "description": "
value to parse
\n",
+ "type": "String|Boolean|Number|Array"
+ }
+ ],
+ "return": {
+ "description": "boolean representation of value",
+ "type": "Boolean"
+ },
+ "example": [
+ "\n
\nprint(boolean(0)); // false\nprint(boolean(1)); // true\nprint(boolean('true')); // true\nprint(boolean('abcd')); // false\nprint(boolean([0, 12, 'true'])); // [false, true, false]\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Conversion"
+ },
+ {
+ "file": "src/utilities/conversion.js",
+ "line": 140,
+ "description": "
Converts a number, string representation of a number, or boolean to its byte\nrepresentation. A byte can be only a whole number between -128 and 127, so\nwhen a value outside of this range is converted, it wraps around to the\ncorresponding byte representation. When an array of number, string or boolean\nvalues is passed in, then an array of bytes the same length is returned.
\n",
+ "itemtype": "method",
+ "name": "byte",
+ "return": {
+ "description": "byte representation of value",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\nprint(byte(127)); // 127\nprint(byte(128)); // -128\nprint(byte(23.4)); // 23\nprint(byte('23.4')); // 23\nprint(byte('hello')); // NaN\nprint(byte(true)); // 1\nprint(byte([0, 255, '100'])); // [0, -1, 100]\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Conversion",
+ "overloads": [
+ {
+ "line": 140,
+ "params": [
+ {
+ "name": "n",
+ "description": "
value to parse
\n",
+ "type": "String|Boolean|Number"
+ }
+ ],
+ "return": {
+ "description": "byte representation of value",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 162,
+ "params": [
+ {
+ "name": "ns",
+ "description": "
values to parse
\n",
+ "type": "Array"
+ }
+ ],
+ "return": {
+ "description": "array of byte representation of values",
+ "type": "Number[]"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/conversion.js",
+ "line": 176,
+ "description": "
Converts a number or string to its corresponding single-character\nstring representation. If a string parameter is provided, it is first\nparsed as an integer and then translated into a single-character string.\nWhen an array of number or string values is passed in, then an array of\nsingle-character strings of the same length is returned.
\n",
+ "itemtype": "method",
+ "name": "char",
+ "return": {
+ "description": "string representation of value",
+ "type": "String"
+ },
+ "example": [
+ "\n
\nprint(char(65)); // \"A\"\nprint(char('65')); // \"A\"\nprint(char([65, 66, 67])); // [ \"A\", \"B\", \"C\" ]\nprint(join(char([65, 66, 67]), '')); // \"ABC\"\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Conversion",
+ "overloads": [
+ {
+ "line": 176,
+ "params": [
+ {
+ "name": "n",
+ "description": "
value to parse
\n",
+ "type": "String|Number"
+ }
+ ],
+ "return": {
+ "description": "string representation of value",
+ "type": "String"
+ }
+ },
+ {
+ "line": 195,
+ "params": [
+ {
+ "name": "ns",
+ "description": "
values to parse
\n",
+ "type": "Array"
+ }
+ ],
+ "return": {
+ "description": "array of string representation of values",
+ "type": "String[]"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/conversion.js",
+ "line": 210,
+ "description": "
Converts a single-character string to its corresponding integer\nrepresentation. When an array of single-character string values is passed\nin, then an array of integers of the same length is returned.
\n",
+ "itemtype": "method",
+ "name": "unchar",
+ "return": {
+ "description": "integer representation of value",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\nprint(unchar('A')); // 65\nprint(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ]\nprint(unchar(split('ABC', ''))); // [ 65, 66, 67 ]\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Conversion",
+ "overloads": [
+ {
+ "line": 210,
+ "params": [
+ {
+ "name": "n",
+ "description": "
value to parse
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "integer representation of value",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 226,
+ "params": [
+ {
+ "name": "ns",
+ "description": "
values to parse
\n",
+ "type": "Array"
+ }
+ ],
+ "return": {
+ "description": "integer representation of values",
+ "type": "Number[]"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/conversion.js",
+ "line": 239,
+ "description": "
Converts a number to a string in its equivalent hexadecimal notation. If a\nsecond parameter is passed, it is used to set the number of characters to\ngenerate in the hexadecimal notation. When an array is passed in, an\narray of strings in hexadecimal notation of the same length is returned.
\n",
+ "itemtype": "method",
+ "name": "hex",
+ "return": {
+ "description": "hexadecimal string representation of value",
+ "type": "String"
+ },
+ "example": [
+ "\n
\nprint(hex(255)); // \"000000FF\"\nprint(hex(255, 6)); // \"0000FF\"\nprint(hex([0, 127, 255], 6)); // [ \"000000\", \"00007F\", \"0000FF\" ]\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Conversion",
+ "overloads": [
+ {
+ "line": 239,
+ "params": [
+ {
+ "name": "n",
+ "description": "
value to parse
\n",
+ "type": "Number"
+ },
+ {
+ "name": "digits",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "hexadecimal string representation of value",
+ "type": "String"
+ }
+ },
+ {
+ "line": 257,
+ "params": [
+ {
+ "name": "ns",
+ "description": "
array of values to parse
\n",
+ "type": "Number[]"
+ },
+ {
+ "name": "digits",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "hexadecimal string representation of values",
+ "type": "String[]"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/conversion.js",
+ "line": 286,
+ "description": "
Converts a string representation of a hexadecimal number to its equivalent\ninteger value. When an array of strings in hexadecimal notation is passed\nin, an array of integers of the same length is returned.
\n",
+ "itemtype": "method",
+ "name": "unhex",
+ "return": {
+ "description": "integer representation of hexadecimal value",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\nprint(unhex('A')); // 10\nprint(unhex('FF')); // 255\nprint(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ]\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "Conversion",
+ "overloads": [
+ {
+ "line": 286,
+ "params": [
+ {
+ "name": "n",
+ "description": "
value to parse
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "integer representation of hexadecimal value",
+ "type": "Number"
+ }
+ },
+ {
+ "line": 302,
+ "params": [
+ {
+ "name": "ns",
+ "description": "
values to parse
\n",
+ "type": "Array"
+ }
+ ],
+ "return": {
+ "description": "integer representations of hexadecimal value",
+ "type": "Number[]"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/string_functions.js",
+ "line": 15,
+ "description": "
Combines an array of Strings into one String, each separated by the\ncharacter(s) used for the separator parameter. To join arrays of ints or\nfloats, it's necessary to first convert them to Strings using nf() or\nnfs().
\n",
+ "itemtype": "method",
+ "name": "join",
+ "params": [
+ {
+ "name": "list",
+ "description": "
array of Strings to be joined
\n",
+ "type": "Array"
+ },
+ {
+ "name": "separator",
+ "description": "
String to be placed between each item
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "joined String",
+ "type": "String"
+ },
+ "example": [
+ "\n
\n\nvar array = ['Hello', 'world!'];\nvar separator = ' ';\nvar message = join(array, separator);\ntext(message, 5, 50);\n\n
"
+ ],
+ "alt": "\"hello world!\" displayed middle left of canvas.",
+ "class": "p5",
+ "module": "Data",
+ "submodule": "String Functions"
+ },
+ {
+ "file": "src/utilities/string_functions.js",
+ "line": 44,
+ "description": "
This function is used to apply a regular expression to a piece of text,\nand return matching groups (elements found inside parentheses) as a\nString array. If there are no matches, a null value will be returned.\nIf no groups are specified in the regular expression, but the sequence\nmatches, an array of length 1 (with the matched text as the first element\nof the array) will be returned.\n
\nTo use the function, first check to see if the result is null. If the\nresult is null, then the sequence did not match at all. If the sequence\ndid match, an array is returned.\n
\nIf there are groups (specified by sets of parentheses) in the regular\nexpression, then the contents of each will be returned in the array.\nElement [0] of a regular expression match returns the entire matching\nstring, and the match groups start at element [1] (the first group is [1],\nthe second [2], and so on).
\n",
+ "itemtype": "method",
+ "name": "match",
+ "params": [
+ {
+ "name": "str",
+ "description": "
the String to be searched
\n",
+ "type": "String"
+ },
+ {
+ "name": "regexp",
+ "description": "
the regexp to be used for matching
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "Array of Strings found",
+ "type": "String[]"
+ },
+ "example": [
+ "\n
\n\nvar string = 'Hello p5js*!';\nvar regexp = 'p5js\\\\*';\nvar m = match(string, regexp);\ntext(m, 5, 50);\n\n
"
+ ],
+ "alt": "\"p5js*\" displayed middle left of canvas.",
+ "class": "p5",
+ "module": "Data",
+ "submodule": "String Functions"
+ },
+ {
+ "file": "src/utilities/string_functions.js",
+ "line": 85,
+ "description": "
This function is used to apply a regular expression to a piece of text,\nand return a list of matching groups (elements found inside parentheses)\nas a two-dimensional String array. If there are no matches, a null value\nwill be returned. If no groups are specified in the regular expression,\nbut the sequence matches, a two dimensional array is still returned, but\nthe second dimension is only of length one.\n
\nTo use the function, first check to see if the result is null. If the\nresult is null, then the sequence did not match at all. If the sequence\ndid match, a 2D array is returned.\n
\nIf there are groups (specified by sets of parentheses) in the regular\nexpression, then the contents of each will be returned in the array.\nAssuming a loop with counter variable i, element [i][0] of a regular\nexpression match returns the entire matching string, and the match groups\nstart at element [i][1] (the first group is [i][1], the second [i][2],\nand so on).
\n",
+ "itemtype": "method",
+ "name": "matchAll",
+ "params": [
+ {
+ "name": "str",
+ "description": "
the String to be searched
\n",
+ "type": "String"
+ },
+ {
+ "name": "regexp",
+ "description": "
the regexp to be used for matching
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "2d Array of Strings found",
+ "type": "String[]"
+ },
+ "example": [
+ "\n
\n\nvar string = 'Hello p5js*! Hello world!';\nvar regexp = 'Hello';\nmatchAll(string, regexp);\n\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "String Functions"
+ },
+ {
+ "file": "src/utilities/string_functions.js",
+ "line": 132,
+ "description": "
Utility function for formatting numbers into strings. There are two\nversions: one for formatting floats, and one for formatting ints.\nThe values for the digits, left, and right parameters should always\nbe positive integers.
\n",
+ "itemtype": "method",
+ "name": "nf",
+ "return": {
+ "description": "formatted String",
+ "type": "String"
+ },
+ "example": [
+ "\n
\n\nfunction setup() {\n background(200);\n var num = 112.53106115;\n\n noStroke();\n fill(0);\n textSize(14);\n // Draw formatted numbers\n text(nf(num, 5, 2), 10, 20);\n\n text(nf(num, 4, 3), 10, 55);\n\n text(nf(num, 3, 6), 10, 85);\n\n // Draw dividing lines\n stroke(120);\n line(0, 30, width, 30);\n line(0, 65, width, 65);\n}\n\n
"
+ ],
+ "alt": "\"0011253\" top left, \"0112.531\" mid left, \"112.531061\" bottom left canvas",
+ "class": "p5",
+ "module": "Data",
+ "submodule": "String Functions",
+ "overloads": [
+ {
+ "line": 132,
+ "params": [
+ {
+ "name": "num",
+ "description": "
the Number to format
\n",
+ "type": "Number|String"
+ },
+ {
+ "name": "left",
+ "description": "
number of digits to the left of the\n decimal point
\n",
+ "type": "Integer|String",
+ "optional": true
+ },
+ {
+ "name": "right",
+ "description": "
number of digits to the right of the\n decimal point
\n",
+ "type": "Integer|String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "formatted String",
+ "type": "String"
+ }
+ },
+ {
+ "line": 174,
+ "params": [
+ {
+ "name": "nums",
+ "description": "
the Numbers to format
\n",
+ "type": "Array"
+ },
+ {
+ "name": "left",
+ "description": "",
+ "type": "Integer|String",
+ "optional": true
+ },
+ {
+ "name": "right",
+ "description": "",
+ "type": "Integer|String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "formatted Strings",
+ "type": "String[]"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/string_functions.js",
+ "line": 237,
+ "description": "
Utility function for formatting numbers into strings and placing\nappropriate commas to mark units of 1000. There are two versions: one\nfor formatting ints, and one for formatting an array of ints. The value\nfor the right parameter should always be a positive integer.
\n",
+ "itemtype": "method",
+ "name": "nfc",
+ "return": {
+ "description": "formatted String",
+ "type": "String"
+ },
+ "example": [
+ "\n
\n\nfunction setup() {\n background(200);\n var num = 11253106.115;\n var numArr = [1, 1, 2];\n\n noStroke();\n fill(0);\n textSize(12);\n\n // Draw formatted numbers\n text(nfc(num, 4), 10, 30);\n text(nfc(numArr, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n\n
"
+ ],
+ "alt": "\"11,253,106.115\" top middle and \"1.00,1.00,2.00\" displayed bottom mid",
+ "class": "p5",
+ "module": "Data",
+ "submodule": "String Functions",
+ "overloads": [
+ {
+ "line": 237,
+ "params": [
+ {
+ "name": "num",
+ "description": "
the Number to format
\n",
+ "type": "Number|String"
+ },
+ {
+ "name": "right",
+ "description": "
number of digits to the right of the\n decimal point
\n",
+ "type": "Integer|String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "formatted String",
+ "type": "String"
+ }
+ },
+ {
+ "line": 275,
+ "params": [
+ {
+ "name": "nums",
+ "description": "
the Numbers to format
\n",
+ "type": "Array"
+ },
+ {
+ "name": "right",
+ "description": "",
+ "type": "Integer|String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "formatted Strings",
+ "type": "String[]"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/string_functions.js",
+ "line": 313,
+ "description": "
Utility function for formatting numbers into strings. Similar to nf() but\nputs a "+" in front of positive numbers and a "-" in front of negative\nnumbers. There are two versions: one for formatting floats, and one for\nformatting ints. The values for left, and right parameters\nshould always be positive integers.
\n",
+ "itemtype": "method",
+ "name": "nfp",
+ "return": {
+ "description": "formatted String",
+ "type": "String"
+ },
+ "example": [
+ "\n
\n\nfunction setup() {\n background(200);\n var num1 = 11253106.115;\n var num2 = -11253106.115;\n\n noStroke();\n fill(0);\n textSize(12);\n\n // Draw formatted numbers\n text(nfp(num1, 4, 2), 10, 30);\n text(nfp(num2, 4, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n\n
"
+ ],
+ "alt": "\"+11253106.11\" top middle and \"-11253106.11\" displayed bottom middle",
+ "class": "p5",
+ "module": "Data",
+ "submodule": "String Functions",
+ "overloads": [
+ {
+ "line": 313,
+ "params": [
+ {
+ "name": "num",
+ "description": "
the Number to format
\n",
+ "type": "Number"
+ },
+ {
+ "name": "left",
+ "description": "
number of digits to the left of the decimal\n point
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "right",
+ "description": "
number of digits to the right of the\n decimal point
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "formatted String",
+ "type": "String"
+ }
+ },
+ {
+ "line": 354,
+ "params": [
+ {
+ "name": "nums",
+ "description": "
the Numbers to format
\n",
+ "type": "Number[]"
+ },
+ {
+ "name": "left",
+ "description": "",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "right",
+ "description": "",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "formatted Strings",
+ "type": "String[]"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/string_functions.js",
+ "line": 375,
+ "description": "
Utility function for formatting numbers into strings. Similar to nf() but\nputs a " " (space) in front of positive numbers and a "-" in front of\nnegative numbers. There are two versions: one for formatting floats, and\none for formatting ints. The values for the digits, left, and right\nparameters should always be positive integers.
\n",
+ "itemtype": "method",
+ "name": "nfs",
+ "return": {
+ "description": "formatted String",
+ "type": "String"
+ },
+ "example": [
+ "\n
\n\nfunction setup() {\n background(200);\n var num1 = 11253106.115;\n var num2 = -11253106.115;\n\n noStroke();\n fill(0);\n textSize(12);\n // Draw formatted numbers\n text(nfs(num1, 4, 2), 10, 30);\n\n text(nfs(num2, 4, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n\n
"
+ ],
+ "alt": "\"11253106.11\" top middle and \"-11253106.11\" displayed bottom middle",
+ "class": "p5",
+ "module": "Data",
+ "submodule": "String Functions",
+ "overloads": [
+ {
+ "line": 375,
+ "params": [
+ {
+ "name": "num",
+ "description": "
the Number to format
\n",
+ "type": "Number"
+ },
+ {
+ "name": "left",
+ "description": "
number of digits to the left of the decimal\n point
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "right",
+ "description": "
number of digits to the right of the\n decimal point
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "formatted String",
+ "type": "String"
+ }
+ },
+ {
+ "line": 416,
+ "params": [
+ {
+ "name": "nums",
+ "description": "
the Numbers to format
\n",
+ "type": "Array"
+ },
+ {
+ "name": "left",
+ "description": "",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "right",
+ "description": "",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "formatted Strings",
+ "type": "String[]"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/string_functions.js",
+ "line": 437,
+ "description": "
The split() function maps to String.split(), it breaks a String into\npieces using a character or string as the delimiter. The delim parameter\nspecifies the character or characters that mark the boundaries between\neach piece. A String[] array is returned that contains each of the pieces.
\n
The splitTokens() function works in a similar fashion, except that it\nsplits using a range of characters instead of a specific character or\nsequence.
\n",
+ "itemtype": "method",
+ "name": "split",
+ "params": [
+ {
+ "name": "value",
+ "description": "
the String to be split
\n",
+ "type": "String"
+ },
+ {
+ "name": "delim",
+ "description": "
the String used to separate the data
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "Array of Strings",
+ "type": "String[]"
+ },
+ "example": [
+ "\n
\n\nvar names = 'Pat,Xio,Alex';\nvar splitString = split(names, ',');\ntext(splitString[0], 5, 30);\ntext(splitString[1], 5, 50);\ntext(splitString[2], 5, 70);\n\n
"
+ ],
+ "alt": "\"pat\" top left, \"Xio\" mid left and \"Alex\" displayed bottom left",
+ "class": "p5",
+ "module": "Data",
+ "submodule": "String Functions"
+ },
+ {
+ "file": "src/utilities/string_functions.js",
+ "line": 471,
+ "description": "
The splitTokens() function splits a String at one or many character\ndelimiters or "tokens." The delim parameter specifies the character or\ncharacters to be used as a boundary.\n
\nIf no delim characters are specified, any whitespace character is used to\nsplit. Whitespace characters include tab (\\t), line feed (\\n), carriage\nreturn (\\r), form feed (\\f), and space.
\n",
+ "itemtype": "method",
+ "name": "splitTokens",
+ "params": [
+ {
+ "name": "value",
+ "description": "
the String to be split
\n",
+ "type": "String"
+ },
+ {
+ "name": "delim",
+ "description": "
list of individual Strings that will be used as\n separators
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Array of Strings",
+ "type": "String[]"
+ },
+ "example": [
+ "\n
\n\nfunction setup() {\n var myStr = 'Mango, Banana, Lime';\n var myStrArr = splitTokens(myStr, ',');\n\n print(myStrArr); // prints : [\"Mango\",\" Banana\",\" Lime\"]\n}\n\n
"
+ ],
+ "class": "p5",
+ "module": "Data",
+ "submodule": "String Functions"
+ },
+ {
+ "file": "src/utilities/string_functions.js",
+ "line": 526,
+ "description": "
Removes whitespace characters from the beginning and end of a String. In\naddition to standard whitespace characters such as space, carriage return,\nand tab, this function also removes the Unicode "nbsp" character.
\n",
+ "itemtype": "method",
+ "name": "trim",
+ "return": {
+ "description": "a trimmed String",
+ "type": "String"
+ },
+ "example": [
+ "\n
\n\nvar string = trim(' No new lines\\n ');\ntext(string + ' here', 2, 50);\n\n
"
+ ],
+ "alt": "\"No new lines here\" displayed center canvas",
+ "class": "p5",
+ "module": "Data",
+ "submodule": "String Functions",
+ "overloads": [
+ {
+ "line": 526,
+ "params": [
+ {
+ "name": "str",
+ "description": "
a String to be trimmed
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "a trimmed String",
+ "type": "String"
+ }
+ },
+ {
+ "line": 546,
+ "params": [
+ {
+ "name": "strs",
+ "description": "
an Array of Strings to be trimmed
\n",
+ "type": "Array"
+ }
+ ],
+ "return": {
+ "description": "an Array of trimmed Strings",
+ "type": "String[]"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/utilities/time_date.js",
+ "line": 12,
+ "description": "
p5.js communicates with the clock on your computer. The day() function\nreturns the current day as a value from 1 - 31.
\n",
+ "itemtype": "method",
+ "name": "day",
+ "return": {
+ "description": "the current day",
+ "type": "Integer"
+ },
+ "example": [
+ "\n
\n\nvar d = day();\ntext('Current day: \\n' + d, 5, 50);\n\n
"
+ ],
+ "alt": "Current day is displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Time & Date"
+ },
+ {
+ "file": "src/utilities/time_date.js",
+ "line": 34,
+ "description": "
p5.js communicates with the clock on your computer. The hour() function\nreturns the current hour as a value from 0 - 23.
\n",
+ "itemtype": "method",
+ "name": "hour",
+ "return": {
+ "description": "the current hour",
+ "type": "Integer"
+ },
+ "example": [
+ "\n
\n\nvar h = hour();\ntext('Current hour:\\n' + h, 5, 50);\n\n
"
+ ],
+ "alt": "Current hour is displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Time & Date"
+ },
+ {
+ "file": "src/utilities/time_date.js",
+ "line": 56,
+ "description": "
p5.js communicates with the clock on your computer. The minute() function\nreturns the current minute as a value from 0 - 59.
\n",
+ "itemtype": "method",
+ "name": "minute",
+ "return": {
+ "description": "the current minute",
+ "type": "Integer"
+ },
+ "example": [
+ "\n
\n\nvar m = minute();\ntext('Current minute: \\n' + m, 5, 50);\n\n
"
+ ],
+ "alt": "Current minute is displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Time & Date"
+ },
+ {
+ "file": "src/utilities/time_date.js",
+ "line": 78,
+ "description": "
Returns the number of milliseconds (thousandths of a second) since\nstarting the program. This information is often used for timing events and\nanimation sequences.
\n",
+ "itemtype": "method",
+ "name": "millis",
+ "return": {
+ "description": "the number of milliseconds since starting the program",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\n\nvar millisecond = millis();\ntext('Milliseconds \\nrunning: \\n' + millisecond, 5, 40);\n\n
"
+ ],
+ "alt": "number of milliseconds since program has started displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Time & Date"
+ },
+ {
+ "file": "src/utilities/time_date.js",
+ "line": 101,
+ "description": "
p5.js communicates with the clock on your computer. The month() function\nreturns the current month as a value from 1 - 12.
\n",
+ "itemtype": "method",
+ "name": "month",
+ "return": {
+ "description": "the current month",
+ "type": "Integer"
+ },
+ "example": [
+ "\n
\n\nvar m = month();\ntext('Current month: \\n' + m, 5, 50);\n\n
"
+ ],
+ "alt": "Current month is displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Time & Date"
+ },
+ {
+ "file": "src/utilities/time_date.js",
+ "line": 123,
+ "description": "
p5.js communicates with the clock on your computer. The second() function\nreturns the current second as a value from 0 - 59.
\n",
+ "itemtype": "method",
+ "name": "second",
+ "return": {
+ "description": "the current second",
+ "type": "Integer"
+ },
+ "example": [
+ "\n
\n\nvar s = second();\ntext('Current second: \\n' + s, 5, 50);\n\n
"
+ ],
+ "alt": "Current second is displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Time & Date"
+ },
+ {
+ "file": "src/utilities/time_date.js",
+ "line": 145,
+ "description": "
p5.js communicates with the clock on your computer. The year() function\nreturns the current year as an integer (2014, 2015, 2016, etc).
\n",
+ "itemtype": "method",
+ "name": "year",
+ "return": {
+ "description": "the current year",
+ "type": "Integer"
+ },
+ "example": [
+ "\n
\n\nvar y = year();\ntext('Current year: \\n' + y, 5, 50);\n\n
"
+ ],
+ "alt": "Current year is displayed",
+ "class": "p5",
+ "module": "IO",
+ "submodule": "Time & Date"
+ },
+ {
+ "file": "src/webgl/camera.js",
+ "line": 12,
+ "description": "
Sets camera position for a 3D sketch. The function behaves similarly\ngluLookAt, except that it replaces the existing modelview matrix instead\nof applying any transformations calculated here on top of the existing\nmodel view.\nWhen called with no arguments, this function\nsets a default camera equivalent to calling\ncamera(0, 0, (height/2.0) / tan(PI*30.0 / 180.0), 0, 0, 0, 0, 1, 0);
\n",
+ "itemtype": "method",
+ "name": "camera",
+ "params": [
+ {
+ "name": "x",
+ "description": "
camera position value on x axis
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "y",
+ "description": "
camera position value on y axis
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "z",
+ "description": "
camera position value on z axis
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "centerX",
+ "description": "
x coordinate representing center of the sketch
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "centerY",
+ "description": "
y coordinate representing center of the sketch
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "centerZ",
+ "description": "
z coordinate representing center of the sketch
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "upX",
+ "description": "
x component of direction 'up' from camera
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "upY",
+ "description": "
y component of direction 'up' from camera
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "upZ",
+ "description": "
z component of direction 'up' from camera
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n //move the camera away from the plane by a sin wave\n camera(0, 0, sin(frameCount * 0.01) * 100, 0, 0, 0, 0, 1, 0);\n plane(120, 120);\n}\n\n
"
+ ],
+ "alt": "blue square shrinks in size grows to fill canvas. disappears then loops.",
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Camera"
+ },
+ {
+ "file": "src/webgl/camera.js",
+ "line": 161,
+ "description": "
Sets perspective camera. When called with no arguments, the defaults\nprovided are equivalent to\nperspective(PI/3.0, width/height, cameraZ/10.0, cameraZ10.0)\nwhere cameraZ is ((height/2.0) / tan(PI60.0/360.0));
\n",
+ "itemtype": "method",
+ "name": "perspective",
+ "params": [
+ {
+ "name": "fovy",
+ "description": "
camera frustum vertical field of view,\n from bottom to top of view, in angleMode units
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "aspect",
+ "description": "
camera frustum aspect ratio
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "near",
+ "description": "
frustum near plane length
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "far",
+ "description": "
frustum far plane length
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\n//drag mouse to toggle the world!\n//you will see there's a vanish point\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n var fov = 60 / 180 * PI;\n var cameraZ = height / 2.0 / tan(fov / 2.0);\n perspective(60 / 180 * PI, width / height, cameraZ * 0.1, cameraZ * 10);\n}\nfunction draw() {\n background(200);\n orbitControl();\n for (var i = -1; i < 2; i++) {\n for (var j = -2; j < 3; j++) {\n push();\n translate(i * 160, 0, j * 160);\n box(40, 40, 40);\n pop();\n }\n }\n}\n\n
"
+ ],
+ "alt": "colored 3d boxes toggleable with mouse position",
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Camera"
+ },
+ {
+ "file": "src/webgl/camera.js",
+ "line": 243,
+ "description": "
Setup ortho camera
\n",
+ "itemtype": "method",
+ "name": "ortho",
+ "params": [
+ {
+ "name": "left",
+ "description": "
camera frustum left plane
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "right",
+ "description": "
camera frustum right plane
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "bottom",
+ "description": "
camera frustum bottom plane
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "top",
+ "description": "
camera frustum top plane
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "near",
+ "description": "
camera frustum near plane
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "far",
+ "description": "
camera frustum far plane
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\n//drag mouse to toggle the world!\n//there's no vanish point\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n ortho(-width / 2, width / 2, height / 2, -height / 2, 0, 500);\n}\nfunction draw() {\n background(200);\n orbitControl();\n strokeWeight(0.1);\n for (var i = -1; i < 2; i++) {\n for (var j = -2; j < 3; j++) {\n push();\n translate(i * 160, 0, j * 160);\n box(40, 40, 40);\n pop();\n }\n }\n}\n\n
"
+ ],
+ "alt": "3 3d boxes, reveal several more boxes on 3d plane when mouse used to toggle",
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Camera"
+ },
+ {
+ "file": "src/webgl/interaction.js",
+ "line": 5,
+ "itemtype": "method",
+ "name": "orbitControl",
+ "chainable": 1,
+ "example": [
+ "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(50);\n // Orbit control allows the camera to orbit around a target.\n orbitControl();\n box(30, 50);\n}\n\n
"
+ ],
+ "alt": "Camera orbits around box when mouse is hold-clicked & then moved.",
+ "class": "p5",
+ "module": "Lights, Camera"
+ },
+ {
+ "file": "src/webgl/light.js",
+ "line": 12,
+ "description": "
Creates an ambient light with a color
\n",
+ "itemtype": "method",
+ "name": "ambientLight",
+ "chainable": 1,
+ "example": [
+ "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(150);\n ambientMaterial(250);\n noStroke();\n sphere(25);\n}\n\n
"
+ ],
+ "alt": "evenly distributed light across a sphere",
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Lights",
+ "overloads": [
+ {
+ "line": 12,
+ "params": [
+ {
+ "name": "v1",
+ "description": "
red or hue value relative to\n the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "
green or saturation value\n relative to the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v3",
+ "description": "
blue or brightness value\n relative to the current color range
\n",
+ "type": "Number"
+ },
+ {
+ "name": "alpha",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 46,
+ "params": [
+ {
+ "name": "value",
+ "description": "
a color string
\n",
+ "type": "String"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 52,
+ "params": [
+ {
+ "name": "gray",
+ "description": "
a gray value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "alpha",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 59,
+ "params": [
+ {
+ "name": "values",
+ "description": "
an array containing the red,green,blue &\n and alpha components of the color
\n",
+ "type": "Number[]"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 66,
+ "params": [
+ {
+ "name": "color",
+ "description": "
the ambient light color
\n",
+ "type": "p5.Color"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/webgl/light.js",
+ "line": 101,
+ "description": "
Creates a directional light with a color and a direction
\n",
+ "itemtype": "method",
+ "name": "directionalLight",
+ "chainable": 1,
+ "example": [
+ "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light direction\n var dirX = (mouseX / width - 0.5) * 2;\n var dirY = (mouseY / height - 0.5) * 2;\n directionalLight(250, 250, 250, -dirX, -dirY, 0.25);\n ambientMaterial(250);\n noStroke();\n sphere(25);\n}\n\n
"
+ ],
+ "alt": "light source on canvas changeable with mouse position",
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Lights",
+ "overloads": [
+ {
+ "line": 101,
+ "params": [
+ {
+ "name": "v1",
+ "description": "
red or hue value (depending on the current\ncolor mode),
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "
green or saturation value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v3",
+ "description": "
blue or brightness value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "position",
+ "description": "
the direction of the light
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 134,
+ "params": [
+ {
+ "name": "color",
+ "description": "
color Array, CSS color string,\n or p5.Color value
\n",
+ "type": "Number[]|String|p5.Color"
+ },
+ {
+ "name": "x",
+ "description": "
x axis direction
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "
y axis direction
\n",
+ "type": "Number"
+ },
+ {
+ "name": "z",
+ "description": "
z axis direction
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 144,
+ "params": [
+ {
+ "name": "color",
+ "description": "",
+ "type": "Number[]|String|p5.Color"
+ },
+ {
+ "name": "position",
+ "description": "",
+ "type": "p5.Vector"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 151,
+ "params": [
+ {
+ "name": "v1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "v3",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "x",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/webgl/light.js",
+ "line": 207,
+ "description": "
Creates a point light with a color and a light position
\n",
+ "itemtype": "method",
+ "name": "pointLight",
+ "chainable": 1,
+ "example": [
+ "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light position\n var locX = mouseX - width / 2;\n var locY = mouseY - height / 2;\n // to set the light position,\n // think of the world's coordinate as:\n // -width/2,-height/2 -------- width/2,-height/2\n // | |\n // | 0,0 |\n // | |\n // -width/2,height/2--------width/2,height/2\n pointLight(250, 250, 250, locX, locY, 50);\n ambientMaterial(250);\n noStroke();\n sphere(25);\n}\n\n
"
+ ],
+ "alt": "spot light on canvas changes position with mouse",
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Lights",
+ "overloads": [
+ {
+ "line": 207,
+ "params": [
+ {
+ "name": "v1",
+ "description": "
red or hue value (depending on the current\ncolor mode),
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "
green or saturation value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v3",
+ "description": "
blue or brightness value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "x",
+ "description": "
x axis position
\n",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "
y axis position
\n",
+ "type": "Number"
+ },
+ {
+ "name": "z",
+ "description": "
z axis position
\n",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 249,
+ "params": [
+ {
+ "name": "v1",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "v3",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "position",
+ "description": "
the position of the light
\n",
+ "type": "p5.Vector"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 258,
+ "params": [
+ {
+ "name": "color",
+ "description": "
color Array, CSS color string,\nor p5.Color value
\n",
+ "type": "Number[]|String|p5.Color"
+ },
+ {
+ "name": "x",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "y",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "z",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 268,
+ "params": [
+ {
+ "name": "color",
+ "description": "",
+ "type": "Number[]|String|p5.Color"
+ },
+ {
+ "name": "position",
+ "description": "",
+ "type": "p5.Vector"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/webgl/loading.js",
+ "line": 14,
+ "description": "
Load a 3d model from an OBJ file.\n
\nOne of the limitations of the OBJ format is that it doesn't have a built-in\nsense of scale. This means that models exported from different programs might\nbe very different sizes. If your model isn't displaying, try calling\nloadModel() with the normalized parameter set to true. This will resize the\nmodel to a scale appropriate for p5. You can also make additional changes to\nthe final size of your model with the scale() function.
\n",
+ "itemtype": "method",
+ "name": "loadModel",
+ "return": {
+ "description": "the p5.Geometry object",
+ "type": "p5.Geometry"
+ },
+ "example": [
+ "\n
\n\n//draw a spinning teapot\nvar teapot;\n\nfunction preload() {\n teapot = loadModel('assets/teapot.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(teapot);\n}\n\n
"
+ ],
+ "alt": "Vertically rotating 3-d teapot with red, green and blue gradient.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "3D Models",
+ "overloads": [
+ {
+ "line": 14,
+ "params": [
+ {
+ "name": "path",
+ "description": "
Path of the model to be loaded
\n",
+ "type": "String"
+ },
+ {
+ "name": "normalize",
+ "description": "
If true, scale the model to a\n standardized size when loading
\n",
+ "type": "Boolean"
+ },
+ {
+ "name": "successCallback",
+ "description": "
Function to be called\n once the model is loaded. Will be passed\n the 3D model object.
\n",
+ "type": "function(p5.Geometry)",
+ "optional": true
+ },
+ {
+ "name": "failureCallback",
+ "description": "
called with event error if\n the image fails to load.
\n",
+ "type": "Function(Event)",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "the p5.Geometry object",
+ "type": "p5.Geometry"
+ }
+ },
+ {
+ "line": 61,
+ "params": [
+ {
+ "name": "path",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "successCallback",
+ "description": "",
+ "type": "function(p5.Geometry)",
+ "optional": true
+ },
+ {
+ "name": "failureCallback",
+ "description": "",
+ "type": "Function(Event)",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "the p5.Geometry object",
+ "type": "p5.Geometry"
+ }
+ }
+ ]
+ },
+ {
+ "file": "src/webgl/loading.js",
+ "line": 106,
+ "description": "
Parse OBJ lines into model. For reference, this is what a simple model of a\nsquare might look like:
\n
v -0.5 -0.5 0.5\nv -0.5 -0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 0.5 0.5
\n
f 4 3 2 1
\n",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "3D Models"
+ },
+ {
+ "file": "src/webgl/loading.js",
+ "line": 215,
+ "description": "
Render a 3d model to the screen.
\n",
+ "itemtype": "method",
+ "name": "model",
+ "params": [
+ {
+ "name": "model",
+ "description": "
Loaded 3d model to be rendered
\n",
+ "type": "p5.Geometry"
+ }
+ ],
+ "example": [
+ "\n
\n\n//draw a spinning teapot\nvar teapot;\n\nfunction preload() {\n teapot = loadModel('assets/teapot.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(teapot);\n}\n\n
"
+ ],
+ "alt": "Vertically rotating 3-d teapot with red, green and blue gradient.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "3D Models"
+ },
+ {
+ "file": "src/webgl/material.js",
+ "line": 14,
+ "description": "
Loads a custom shader from the provided vertex and fragment\nshader paths. The shader files are loaded asynchronously in the\nbackground, so this method should be used in preload().
\n
For now, there are three main types of shaders. p5 will automatically\nsupply appropriate vertices, normals, colors, and lighting attributes\nif the parameters defined in the shader match the names.
\n",
+ "itemtype": "method",
+ "name": "loadShader",
+ "params": [
+ {
+ "name": "vertFilename",
+ "description": "
path to file containing vertex shader\nsource code
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "fragFilename",
+ "description": "
path to file containing fragment shader\nsource code
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "a shader object created from the provided\nvertex and fragment shader files.",
+ "type": "p5.Shader"
+ },
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Material"
+ },
+ {
+ "file": "src/webgl/material.js",
+ "line": 57,
+ "itemtype": "method",
+ "name": "createShader",
+ "params": [
+ {
+ "name": "vertSrc",
+ "description": "
source code for the vertex shader
\n",
+ "type": "String"
+ },
+ {
+ "name": "fragSrc",
+ "description": "
source code for the fragment shader
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "a shader object created from the provided\nvertex and fragment shaders.",
+ "type": "p5.Shader"
+ },
+ "example": [
+ "\n
\n\n// the 'varying's are shared between both vertex & fragment shaders\nvar varying = 'precision highp float; varying vec2 vPos;';\n\n// the vertex shader is called for each vertex\nvar vs =\n varying +\n 'attribute vec3 aPosition;' +\n 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }';\n\n// the fragment shader is called for each pixel\nvar fs =\n varying +\n 'uniform vec2 p;' +\n 'uniform float r;' +\n 'const int I = 500;' +\n 'void main() {' +\n ' vec2 c = p + vPos * r, z = c;' +\n ' float n = 0.0;' +\n ' for (int i = I; i > 0; i --) {' +\n ' if(z.x*z.x+z.y*z.y > 4.0) {' +\n ' n = float(i)/float(I);' +\n ' break;' +\n ' }' +\n ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' +\n ' }' +\n ' gl_FragColor = vec4(0.5-cos(n*17.0)/2.0,0.5-cos(n*13.0)/2.0,0.5-cos(n*23.0)/2.0,1.0);' +\n '}';\n\nvar mandel;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // create and initialize the shader\n mandel = createShader(vs, fs);\n shader(mandel);\n noStroke();\n\n // 'p' is the center point of the Mandelbrot image\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n // 'r' is the size of the image in Mandelbrot-space\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n\n
"
+ ],
+ "alt": "zooming Mandelbrot set. a colorful, infinitely detailed fractal.",
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Material"
+ },
+ {
+ "file": "src/webgl/material.js",
+ "line": 125,
+ "description": "
The shader() function lets the user provide a custom shader\nto fill in shapes in WEBGL mode. Users can create their\nown shaders by loading vertex and fragment shaders with\nloadShader().
\n",
+ "itemtype": "method",
+ "name": "shader",
+ "chainable": 1,
+ "params": [
+ {
+ "name": "s",
+ "description": "
the desired p5.Shader to use for rendering\nshapes.
\n",
+ "type": "p5.Shader",
+ "optional": true
+ }
+ ],
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Material"
+ },
+ {
+ "file": "src/webgl/material.js",
+ "line": 150,
+ "description": "
Normal material for geometry. You can view all\npossible materials in this\nexample.
\n",
+ "itemtype": "method",
+ "name": "normalMaterial",
+ "chainable": 1,
+ "example": [
+ "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n normalMaterial();\n sphere(50);\n}\n\n
"
+ ],
+ "alt": "Red, green and blue gradient.",
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Material"
+ },
+ {
+ "file": "src/webgl/material.js",
+ "line": 185,
+ "description": "
Texture for geometry. You can view other possible materials in this\nexample.
\n",
+ "itemtype": "method",
+ "name": "texture",
+ "params": [
+ {
+ "name": "tex",
+ "description": "
2-dimensional graphics\n to render as texture
\n",
+ "type": "p5.Image|p5.MediaElement|p5.Graphics"
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n //pass image as texture\n texture(img);\n box(200, 200, 200);\n}\n\n
\n\n
\n\nvar pg;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n pg = createGraphics(200, 200);\n pg.textSize(100);\n}\n\nfunction draw() {\n background(0);\n pg.background(255);\n pg.text('hello!', 0, 100);\n //pass image as texture\n texture(pg);\n plane(200);\n}\n\n
\n\n
\n\nvar vid;\nfunction preload() {\n vid = createVideo('assets/fingers.mov');\n vid.hide();\n vid.loop();\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n //pass video frame as texture\n texture(vid);\n plane(200);\n}\n\n
"
+ ],
+ "alt": "Rotating view of many images umbrella and grid roof on a 3d plane\nblack canvas\nblack canvas",
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Material"
+ },
+ {
+ "file": "src/webgl/material.js",
+ "line": 275,
+ "description": "
Ambient material for geometry with a given color. You can view all\npossible materials in this\nexample.
\n",
+ "itemtype": "method",
+ "name": "ambientMaterial",
+ "chainable": 1,
+ "example": [
+ "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(100);\n pointLight(250, 250, 250, 100, 100, 0);\n ambientMaterial(250);\n sphere(50);\n}\n\n
"
+ ],
+ "alt": "radiating light source from top right of canvas",
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Material",
+ "overloads": [
+ {
+ "line": 275,
+ "params": [
+ {
+ "name": "v1",
+ "description": "
gray value, red or hue value\n (depending on the current color mode),
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "
green or saturation value
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "v3",
+ "description": "
blue or brightness value
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "a",
+ "description": "
opacity
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 306,
+ "params": [
+ {
+ "name": "color",
+ "description": "
color, color Array, or CSS color string
\n",
+ "type": "Number[]|String|p5.Color"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/webgl/material.js",
+ "line": 324,
+ "description": "
Specular material for geometry with a given color. You can view all\npossible materials in this\nexample.
\n",
+ "itemtype": "method",
+ "name": "specularMaterial",
+ "chainable": 1,
+ "example": [
+ "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(100);\n pointLight(250, 250, 250, 100, 100, 0);\n specularMaterial(250);\n sphere(50);\n}\n\n
"
+ ],
+ "alt": "diffused radiating light source from top right of canvas",
+ "class": "p5",
+ "module": "Lights, Camera",
+ "submodule": "Material",
+ "overloads": [
+ {
+ "line": 324,
+ "params": [
+ {
+ "name": "v1",
+ "description": "
gray value, red or hue value\n (depending on the current color mode),
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "
green or saturation value
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "v3",
+ "description": "
blue or brightness value
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "a",
+ "description": "
opacity
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "chainable": 1
+ },
+ {
+ "line": 355,
+ "params": [
+ {
+ "name": "color",
+ "description": "
color Array, or CSS color string
\n",
+ "type": "Number[]|String|p5.Color"
+ }
+ ],
+ "chainable": 1
+ }
+ ]
+ },
+ {
+ "file": "src/webgl/p5.Geometry.js",
+ "line": 52,
+ "itemtype": "method",
+ "name": "computeFaces",
+ "chainable": 1,
+ "class": "p5.Geometry",
+ "module": "Lights, Camera"
+ },
+ {
+ "file": "src/webgl/p5.Geometry.js",
+ "line": 94,
+ "description": "
computes smooth normals per vertex as an average of each\nface.
\n",
+ "itemtype": "method",
+ "name": "computeNormals",
+ "chainable": 1,
+ "class": "p5.Geometry",
+ "module": "Lights, Camera"
+ },
+ {
+ "file": "src/webgl/p5.Geometry.js",
+ "line": 133,
+ "description": "
Averages the vertex normals. Used in curved\nsurfaces
\n",
+ "itemtype": "method",
+ "name": "averageNormals",
+ "chainable": 1,
+ "class": "p5.Geometry",
+ "module": "Lights, Camera"
+ },
+ {
+ "file": "src/webgl/p5.Geometry.js",
+ "line": 154,
+ "description": "
Averages pole normals. Used in spherical primitives
\n",
+ "itemtype": "method",
+ "name": "averagePoleNormals",
+ "chainable": 1,
+ "class": "p5.Geometry",
+ "module": "Lights, Camera"
+ },
+ {
+ "file": "src/webgl/p5.Geometry.js",
+ "line": 247,
+ "description": "
Modifies all vertices to be centered within the range -100 to 100.
\n",
+ "itemtype": "method",
+ "name": "normalize",
+ "chainable": 1,
+ "class": "p5.Geometry",
+ "module": "Lights, Camera"
+ },
+ {
+ "file": "src/webgl/p5.RendererGL.js",
+ "line": 197,
+ "description": "
Set attributes for the WebGL Drawing context.\nThis is a way of adjusting ways that the WebGL\nrenderer works to fine-tune the display and performance.\nThis should be put in setup().\nThe available attributes are:\n
\nalpha - indicates if the canvas contains an alpha buffer\ndefault is true\n
\ndepth - indicates whether the drawing buffer has a depth buffer\nof at least 16 bits - default is true\n
\nstencil - indicates whether the drawing buffer has a stencil buffer\nof at least 8 bits\n
\nantialias - indicates whether or not to perform anti-aliasing\ndefault is false\n
\npremultipliedAlpha - indicates that the page compositor will assume\nthe drawing buffer contains colors with pre-multiplied alpha\ndefault is false\n
\npreserveDrawingBuffer - if true the buffers will not be cleared and\nand will preserve their values until cleared or overwritten by author\n(note that p5 clears automatically on draw loop)\ndefault is true\n
\nperPixelLighting - if true, per-pixel lighting will be used in the\nlighting shader.\ndefault is false\n
\n",
+ "itemtype": "method",
+ "name": "setAttributes",
+ "example": [
+ "\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n\n
\n
\nNow with the antialias attribute set to true.\n
\n
\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n\n
\n\n
\n\n// press the mouse button to enable perPixelLighting\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255);\n}\n\nvar lights = [\n { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },\n { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },\n { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },\n { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },\n { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },\n { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }\n];\n\nfunction draw() {\n var t = millis() / 1000 + 1000;\n background(0);\n directionalLight(color('#222'), 1, 1, 1);\n\n for (var i = 0; i < lights.length; i++) {\n var light = lights[i];\n pointLight(\n color(light.c),\n p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)\n );\n }\n\n specularMaterial(255);\n sphere(width * 0.1);\n\n rotateX(t * 0.77);\n rotateY(t * 0.83);\n rotateZ(t * 0.91);\n torus(width * 0.3, width * 0.07, 30, 10);\n}\n\nfunction mousePressed() {\n setAttributes('perPixelLighting', true);\n noStroke();\n fill(255);\n}\nfunction mouseReleased() {\n setAttributes('perPixelLighting', false);\n noStroke();\n fill(255);\n}\n\n
"
+ ],
+ "alt": "a rotating cube with smoother edges",
+ "class": "p5",
+ "module": "Rendering",
+ "submodule": "Rendering",
+ "overloads": [
+ {
+ "line": 197,
+ "params": [
+ {
+ "name": "key",
+ "description": "
Name of attribute
\n",
+ "type": "String"
+ },
+ {
+ "name": "value",
+ "description": "
New value of named attribute
\n",
+ "type": "Boolean"
+ }
+ ]
+ },
+ {
+ "line": 330,
+ "params": [
+ {
+ "name": "obj",
+ "description": "
object with key-value pairs
\n",
+ "type": "Object"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "file": "src/webgl/p5.Shader.js",
+ "line": 270,
+ "description": "
Wrapper around gl.uniform functions.\nAs we store uniform info in the shader we can use that\nto do type checking on the supplied data and call\nthe appropriate function.
\n",
+ "itemtype": "method",
+ "name": "setUniform",
+ "chainable": 1,
+ "params": [
+ {
+ "name": "uniformName",
+ "description": "
the name of the uniform in the\nshader program
\n",
+ "type": "String"
+ },
+ {
+ "name": "data",
+ "description": "
the data to be associated\nwith that uniform; type varies (could be a single numerical value, array,\nmatrix, or texture / sampler reference)
\n",
+ "type": "Object|Number|Boolean|Number[]"
+ }
+ ],
+ "class": "p5.Shader",
+ "module": "Lights, Camera",
+ "submodule": "Shaders"
+ },
+ {
+ "file": "src/webgl/primitives.js",
+ "line": 14,
+ "description": "
Draw a plane with given a width and height
\n",
+ "itemtype": "method",
+ "name": "plane",
+ "params": [
+ {
+ "name": "width",
+ "description": "
width of the plane
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "height",
+ "description": "
height of the plane
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "detailX",
+ "description": "
Optional number of triangle\n subdivisions in x-dimension
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "detailY",
+ "description": "
Optional number of triangle\n subdivisions in y-dimension
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\n//draw a plane with width 50 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n plane(50, 50);\n}\n\n
"
+ ],
+ "alt": "Nothing displayed on canvas\nRotating interior view of a box with sides that change color.\n3d red and green gradient.\nRotating interior view of a cylinder with sides that change color.\nRotating view of a cylinder with sides that change color.\n3d red and green gradient.\nrotating view of a multi-colored cylinder with concave sides.",
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "3D Primitives"
+ },
+ {
+ "file": "src/webgl/primitives.js",
+ "line": 96,
+ "description": "
Draw a box with given width, height and depth
\n",
+ "itemtype": "method",
+ "name": "box",
+ "params": [
+ {
+ "name": "width",
+ "description": "
width of the box
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "Height",
+ "description": "
height of the box
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "depth",
+ "description": "
depth of the box
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "detailX",
+ "description": "
Optional number of triangle\n subdivisions in x-dimension
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "detailY",
+ "description": "
Optional number of triangle\n subdivisions in y-dimension
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\n//draw a spinning box with width, height and depth 200\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(50);\n}\n\n
"
+ ],
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "3D Primitives"
+ },
+ {
+ "file": "src/webgl/primitives.js",
+ "line": 213,
+ "description": "
Draw a sphere with given radius
\n",
+ "itemtype": "method",
+ "name": "sphere",
+ "params": [
+ {
+ "name": "radius",
+ "description": "
radius of circle
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "detailX",
+ "description": "
number of segments,\n the more segments the smoother geometry\n default is 24
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "detailY",
+ "description": "
number of segments,\n the more segments the smoother geometry\n default is 16
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\n// draw a sphere with radius 200\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n sphere(40);\n}\n\n
"
+ ],
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "3D Primitives"
+ },
+ {
+ "file": "src/webgl/primitives.js",
+ "line": 391,
+ "description": "
Draw a cylinder with given radius and height
\n",
+ "itemtype": "method",
+ "name": "cylinder",
+ "params": [
+ {
+ "name": "radius",
+ "description": "
radius of the surface
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "height",
+ "description": "
height of the cylinder
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "detailX",
+ "description": "
number of segments,\n the more segments the smoother geometry\n default is 24
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "detailY",
+ "description": "
number of segments in y-dimension,\n the more segments the smoother geometry\n default is 1
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "bottomCap",
+ "description": "
whether to draw the bottom of the cylinder
\n",
+ "type": "Boolean",
+ "optional": true
+ },
+ {
+ "name": "topCap",
+ "description": "
whether to draw the top of the cylinder
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\n//draw a spinning cylinder with radius 20 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cylinder(20, 50);\n}\n\n
"
+ ],
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "3D Primitives"
+ },
+ {
+ "file": "src/webgl/primitives.js",
+ "line": 482,
+ "description": "
Draw a cone with given radius and height
\n",
+ "itemtype": "method",
+ "name": "cone",
+ "params": [
+ {
+ "name": "radius",
+ "description": "
radius of the bottom surface
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "height",
+ "description": "
height of the cone
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "detailX",
+ "description": "
number of segments,\n the more segments the smoother geometry\n default is 24
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "detailY",
+ "description": "
number of segments,\n the more segments the smoother geometry\n default is 1
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "cap",
+ "description": "
whether to draw the base of the cone
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\n//draw a spinning cone with radius 40 and height 70\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cone(40, 70);\n}\n\n
"
+ ],
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "3D Primitives"
+ },
+ {
+ "file": "src/webgl/primitives.js",
+ "line": 553,
+ "description": "
Draw an ellipsoid with given radius
\n",
+ "itemtype": "method",
+ "name": "ellipsoid",
+ "params": [
+ {
+ "name": "radiusx",
+ "description": "
xradius of circle
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "radiusy",
+ "description": "
yradius of circle
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "radiusz",
+ "description": "
zradius of circle
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "detailX",
+ "description": "
number of segments,\n the more segments the smoother geometry\n default is 24. Avoid detail number above\n 150, it may crash the browser.
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "detailY",
+ "description": "
number of segments,\n the more segments the smoother geometry\n default is 16. Avoid detail number above\n 150, it may crash the browser.
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\n// draw an ellipsoid with radius 20, 30 and 40.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n ellipsoid(20, 30, 40);\n}\n\n
"
+ ],
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "3D Primitives"
+ },
+ {
+ "file": "src/webgl/primitives.js",
+ "line": 643,
+ "description": "
Draw a torus with given radius and tube radius
\n",
+ "itemtype": "method",
+ "name": "torus",
+ "params": [
+ {
+ "name": "radius",
+ "description": "
radius of the whole ring
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "tubeRadius",
+ "description": "
radius of the tube
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "detailX",
+ "description": "
number of segments in x-dimension,\n the more segments the smoother geometry\n default is 24
\n",
+ "type": "Integer",
+ "optional": true
+ },
+ {
+ "name": "detailY",
+ "description": "
number of segments in y-dimension,\n the more segments the smoother geometry\n default is 16
\n",
+ "type": "Integer",
+ "optional": true
+ }
+ ],
+ "chainable": 1,
+ "example": [
+ "\n
\n\n//draw a spinning torus with radius 200 and tube radius 60\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n torus(50, 15);\n}\n\n
"
+ ],
+ "class": "p5",
+ "module": "Shape",
+ "submodule": "3D Primitives"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 40,
+ "description": "
Searches the page for an element with the given ID, class, or tag name (using the '#' or '.'\nprefixes to specify an ID or class respectively, and none for a tag) and returns it as\na p5.Element. If a class or tag name is given with more than 1 element,\nonly the first element will be returned.\nThe DOM node itself can be accessed with .elt.\nReturns null if none found. You can also specify a container to search within.
\n",
+ "itemtype": "method",
+ "name": "select",
+ "params": [
+ {
+ "name": "name",
+ "description": "
id, class, or tag name of element to search for
\n",
+ "type": "String"
+ },
+ {
+ "name": "container",
+ "description": "
id, p5.Element, or\n HTML element to search within
\n",
+ "type": "String|p5.Element|HTMLElement",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "p5.Element containing node found",
+ "type": "Object|p5.Element|null"
+ },
+ "example": [
+ "\n
\nfunction setup() {\n createCanvas(100, 100);\n //translates canvas 50px down\n select('canvas').position(100, 100);\n}\n
\n
\n// these are all valid calls to select()\nvar a = select('#moo');\nvar b = select('#blah', '#myContainer');\nvar c, e;\nif (b) {\n c = select('#foo', b);\n}\nvar d = document.getElementById('beep');\nif (d) {\n e = select('p', d);\n}\n[a, b, c, d, e]; // unused\n
\n"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 107,
+ "description": "
Searches the page for elements with the given class or tag name (using the '.' prefix\nto specify a class and no prefix for a tag) and returns them as p5.Elements\nin an array.\nThe DOM node itself can be accessed with .elt.\nReturns an empty array if none found.\nYou can also specify a container to search within.
\n",
+ "itemtype": "method",
+ "name": "selectAll",
+ "params": [
+ {
+ "name": "name",
+ "description": "
class or tag name of elements to search for
\n",
+ "type": "String"
+ },
+ {
+ "name": "container",
+ "description": "
id, p5.Element, or HTML element to search within
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Array of p5.Elements containing nodes found",
+ "type": "Array"
+ },
+ "example": [
+ "\n
\nfunction setup() {\n createButton('btn');\n createButton('2nd btn');\n createButton('3rd btn');\n var buttons = selectAll('button');\n\n for (var i = 0; i < buttons.length; i++) {\n buttons[i].size(100, 100);\n }\n}\n
\n
\n// these are all valid calls to selectAll()\nvar a = selectAll('.moo');\na = selectAll('div');\na = selectAll('button', '#myContainer');\n\nvar d = select('#container');\na = selectAll('p', d);\n\nvar f = document.getElementById('beep');\na = select('.blah', f);\n\na; // unused\n
\n"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 168,
+ "description": "
Helper function for select and selectAll
\n",
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 184,
+ "description": "
Helper function for getElement and getElements.
\n",
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 218,
+ "description": "
Removes all elements created by p5, except any canvas / graphics\nelements created by createCanvas or createGraphics.\nEvent handlers are removed, and element is removed from the DOM.
\n",
+ "itemtype": "method",
+ "name": "removeElements",
+ "example": [
+ "\n
\nfunction setup() {\n createCanvas(100, 100);\n createDiv('this is some text');\n createP('this is a paragraph');\n}\nfunction mousePressed() {\n removeElements(); // this will remove the div and p, not canvas\n}\n
\n"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 245,
+ "description": "
Helpers for create methods.
\n",
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 256,
+ "description": "
Creates a <div></div> element in the DOM with given inner HTML.\nAppends to the container node if one is specified, otherwise\nappends to body.
\n",
+ "itemtype": "method",
+ "name": "createDiv",
+ "params": [
+ {
+ "name": "html",
+ "description": "
inner HTML for element created
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created node",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\ncreateDiv('this is some text');\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 270,
+ "description": "
Creates a <p></p> element in the DOM with given inner HTML. Used\nfor paragraph length text.\nAppends to the container node if one is specified, otherwise\nappends to body.
\n",
+ "itemtype": "method",
+ "name": "createP",
+ "params": [
+ {
+ "name": "html",
+ "description": "
inner HTML for element created
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created node",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\ncreateP('this is some text');\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 285,
+ "description": "
Creates a <span></span> element in the DOM with given inner HTML.\nAppends to the container node if one is specified, otherwise\nappends to body.
\n",
+ "itemtype": "method",
+ "name": "createSpan",
+ "params": [
+ {
+ "name": "html",
+ "description": "
inner HTML for element created
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created node",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\ncreateSpan('this is some text');\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 308,
+ "description": "
Creates an <img> element in the DOM with given src and\nalternate text.\nAppends to the container node if one is specified, otherwise\nappends to body.
\n",
+ "itemtype": "method",
+ "name": "createImg",
+ "params": [
+ {
+ "name": "src",
+ "description": "
src path or url for image
\n",
+ "type": "String"
+ },
+ {
+ "name": "alt",
+ "description": "
alternate text to be used if image does not load
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "successCallback",
+ "description": "
callback to be called once image data is loaded
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created node",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\ncreateImg('http://p5js.org/img/asterisk-01.png');\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 351,
+ "description": "
Creates an <a></a> element in the DOM for including a hyperlink.\nAppends to the container node if one is specified, otherwise\nappends to body.
\n",
+ "itemtype": "method",
+ "name": "createA",
+ "params": [
+ {
+ "name": "href",
+ "description": "
url of page to link to
\n",
+ "type": "String"
+ },
+ {
+ "name": "html",
+ "description": "
inner html of link element to display
\n",
+ "type": "String"
+ },
+ {
+ "name": "target",
+ "description": "
target where new link should open,\n could be _blank, _self, _parent, _top.
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created node",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\ncreateA('http://p5js.org/', 'this is a link');\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 376,
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 378,
+ "description": "
Creates a slider <input></input> element in the DOM.\nUse .size() to set the display length of the slider.\nAppends to the container node if one is specified, otherwise\nappends to body.
\n",
+ "itemtype": "method",
+ "name": "createSlider",
+ "params": [
+ {
+ "name": "min",
+ "description": "
minimum value of the slider
\n",
+ "type": "Number"
+ },
+ {
+ "name": "max",
+ "description": "
maximum value of the slider
\n",
+ "type": "Number"
+ },
+ {
+ "name": "value",
+ "description": "
default value of the slider
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "step",
+ "description": "
step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created node",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\nvar slider;\nfunction setup() {\n slider = createSlider(0, 255, 100);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n var val = slider.value();\n background(val);\n}\n
\n\n
\nvar slider;\nfunction setup() {\n colorMode(HSB);\n slider = createSlider(0, 360, 60, 40);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n var val = slider.value();\n background(val, 100, 100, 1);\n}\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 435,
+ "description": "
Creates a <button></button> element in the DOM.\nUse .size() to set the display size of the button.\nUse .mousePressed() to specify behavior on press.\nAppends to the container node if one is specified, otherwise\nappends to body.
\n",
+ "itemtype": "method",
+ "name": "createButton",
+ "params": [
+ {
+ "name": "label",
+ "description": "
label displayed on the button
\n",
+ "type": "String"
+ },
+ {
+ "name": "value",
+ "description": "
value of the button
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created node",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\nvar button;\nfunction setup() {\n createCanvas(100, 100);\n background(0);\n button = createButton('click me');\n button.position(19, 19);\n button.mousePressed(changeBG);\n}\n\nfunction changeBG() {\n var val = random(255);\n background(val);\n}\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 471,
+ "description": "
Creates a checkbox <input></input> element in the DOM.\nCalling .checked() on a checkbox returns if it is checked or not
\n",
+ "itemtype": "method",
+ "name": "createCheckbox",
+ "params": [
+ {
+ "name": "label",
+ "description": "
label displayed after checkbox
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "value",
+ "description": "
value of the checkbox; checked is true, unchecked is false
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created node",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\nvar checkbox;\n\nfunction setup() {\n checkbox = createCheckbox('label', false);\n checkbox.changed(myCheckedEvent);\n}\n\nfunction myCheckedEvent() {\n if (this.checked()) {\n console.log('Checking!');\n } else {\n console.log('Unchecking!');\n }\n}\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 539,
+ "description": "
Creates a dropdown menu <select></select> element in the DOM.\nIt also helps to assign select-box methods to p5.Element when selecting existing select box
\n",
+ "itemtype": "method",
+ "name": "createSelect",
+ "return": {
+ "description": "",
+ "type": "p5.Element"
+ },
+ "example": [
+ "\n
\nvar sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n var item = sel.value();\n background(200);\n text('it is a' + item + '!', 50, 50);\n}\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom",
+ "overloads": [
+ {
+ "line": 539,
+ "params": [
+ {
+ "name": "multiple",
+ "description": "
true if dropdown should support multiple selections
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.Element"
+ }
+ },
+ {
+ "line": 567,
+ "params": [
+ {
+ "name": "existing",
+ "description": "
DOM select element
\n",
+ "type": "Object"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.Element"
+ }
+ }
+ ]
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 643,
+ "description": "
Creates a radio button <input></input> element in the DOM.\nThe .option() method can be used to set options for the radio after it is\ncreated. The .value() method will return the currently selected option.
\n",
+ "itemtype": "method",
+ "name": "createRadio",
+ "params": [
+ {
+ "name": "divId",
+ "description": "
the id and name of the created div and input field respectively
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created node",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\nvar radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option('black');\n radio.option('white');\n radio.option('gray');\n radio.style('width', '60px');\n textAlign(CENTER);\n fill(255, 0, 0);\n}\n\nfunction draw() {\n var val = radio.value();\n background(val);\n text(val, width / 2, height / 2);\n}\n
\n
\nvar radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option('apple', 1);\n radio.option('bread', 2);\n radio.option('juice', 3);\n radio.style('width', '60px');\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(200);\n var val = radio.value();\n if (val) {\n text('item cost is $' + val, width / 2, height / 2);\n }\n}\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 781,
+ "description": "
Creates an <input></input> element in the DOM for text input.\nUse .size() to set the display length of the box.\nAppends to the container node if one is specified, otherwise\nappends to body.
\n",
+ "itemtype": "method",
+ "name": "createInput",
+ "params": [
+ {
+ "name": "value",
+ "description": "
default value of the input box
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "type",
+ "description": "
type of text, ie text, password etc. Defaults to text
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created node",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\nfunction setup() {\n var inp = createInput('');\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent() {\n console.log('you are typing: ', this.value());\n}\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 811,
+ "description": "
Creates an <input></input> element in the DOM of type 'file'.\nThis allows users to select local files for use in a sketch.
\n",
+ "itemtype": "method",
+ "name": "createFileInput",
+ "params": [
+ {
+ "name": "callback",
+ "description": "
callback function for when a file loaded
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "multiple",
+ "description": "
optional to allow multiple files selected
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created DOM element",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\nvar input;\nvar img;\n\nfunction setup() {\n input = createFileInput(handleFile);\n input.position(0, 0);\n}\n\nfunction draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction handleFile(file) {\n print(file);\n if (file.type === 'image') {\n img = createImg(file.data);\n img.hide();\n }\n}"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 897,
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 934,
+ "description": "
Creates an HTML5 <video> element in the DOM for simple playback\nof audio/video. Shown by default, can be hidden with .hide()\nand drawn into canvas using video(). Appends to the container\nnode if one is specified, otherwise appends to body. The first parameter\ncan be either a single string path to a video file, or an array of string\npaths to different formats of the same video. This is useful for ensuring\nthat your video can play across different browsers, as each supports\ndifferent formats. See this\npage for further information about supported formats.
\n",
+ "itemtype": "method",
+ "name": "createVideo",
+ "params": [
+ {
+ "name": "src",
+ "description": "
path to a video file, or array of paths for\n supporting different browsers
\n",
+ "type": "String|Array"
+ },
+ {
+ "name": "callback",
+ "description": "
callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to video p5.Element",
+ "type": "p5.MediaElement|p5.Element"
+ },
+ "example": [
+ "\n
\nvar vid;\nfunction setup() {\n vid = createVideo(['small.mp4', 'small.ogv', 'small.webm'], vidLoad);\n}\n\n// This function is called when the video loads\nfunction vidLoad() {\n vid.play();\n}\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 973,
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 975,
+ "description": "
Creates a hidden HTML5 <audio> element in the DOM for simple audio\nplayback. Appends to the container node if one is specified,\notherwise appends to body. The first parameter\ncan be either a single string path to a audio file, or an array of string\npaths to different formats of the same audio. This is useful for ensuring\nthat your audio can play across different browsers, as each supports\ndifferent formats. See this\npage for further information about supported formats.
\n",
+ "itemtype": "method",
+ "name": "createAudio",
+ "params": [
+ {
+ "name": "src",
+ "description": "
path to an audio file, or array of paths\n for supporting different browsers
\n",
+ "type": "String|String[]",
+ "optional": true
+ },
+ {
+ "name": "callback",
+ "description": "
callback function to be called upon\n 'canplaythrough' event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to audio p5.Element /**",
+ "type": "p5.MediaElement|p5.Element"
+ },
+ "example": [
+ "\n
\nvar ele;\nfunction setup() {\n ele = createAudio('assets/beat.mp3');\n\n // here we set the element to autoplay\n // The element will play as soon\n // as it is able to do so.\n ele.autoplay(true);\n}\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1013,
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1048,
+ "description": "
Creates a new HTML5 <video> element that contains the audio/video\nfeed from a webcam. The element is separate from the canvas and is\ndisplayed by default. The element can be hidden using .hide(). The feed\ncan be drawn onto the canvas using image().
\n
More specific properties of the feed can be passing in a Constraints object.\nSee the\n W3C\nspec for possible properties. Note that not all of these are supported\nby all browsers.
\n
Security note: A new browser security specification requires that getUserMedia,\nwhich is behind createCapture(), only works when you're running the code locally,\nor on HTTPS. Learn more here\nand here.
",
+ "itemtype": "method",
+ "name": "createCapture",
+ "params": [
+ {
+ "name": "type",
+ "description": "
type of capture, either VIDEO or\n AUDIO if none specified, default both,\n or a Constraints object
\n",
+ "type": "String|Constant|Object"
+ },
+ {
+ "name": "callback",
+ "description": "
function to be called once\n stream has loaded
\n",
+ "type": "Function"
+ }
+ ],
+ "return": {
+ "description": "capture video p5.Element",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\nvar capture;\n\nfunction setup() {\n createCanvas(480, 480);\n capture = createCapture(VIDEO);\n capture.hide();\n}\n\nfunction draw() {\n image(capture, 0, 0, width, width * capture.height / capture.width);\n filter(INVERT);\n}\n
\n
\nfunction setup() {\n createCanvas(480, 120);\n var constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [{ maxFrameRate: 10 }]\n },\n audio: true\n };\n createCapture(constraints, function(stream) {\n console.log(stream);\n });\n}\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1167,
+ "description": "
Creates element with given tag in the DOM with given content.\nAppends to the container node if one is specified, otherwise\nappends to body.
\n",
+ "itemtype": "method",
+ "name": "createElement",
+ "params": [
+ {
+ "name": "tag",
+ "description": "
tag for the new element
\n",
+ "type": "String"
+ },
+ {
+ "name": "content",
+ "description": "
html content to be inserted into the element
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element holding created node",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\ncreateElement('h2', 'im an h2 p5.element!');\n
"
+ ],
+ "class": "p5.dom",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1193,
+ "description": "
Adds specified class to the element.
\n",
+ "itemtype": "method",
+ "name": "addClass",
+ "params": [
+ {
+ "name": "class",
+ "description": "
name of class to add
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\n var div = createDiv('div');\n div.addClass('myClass');\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1220,
+ "description": "
Removes specified class from the element.
\n",
+ "itemtype": "method",
+ "name": "removeClass",
+ "params": [
+ {
+ "name": "class",
+ "description": "
name of class to remove
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "* @example\n
\n // In this example, a class is set when the div is created\n // and removed when mouse is pressed. This could link up\n // with a CSS style rule to toggle style properties.\nvar div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('myClass');\n }\nfunction mousePressed() {\n div.removeClass('myClass');\n }\n
",
+ "type": "Object|p5.Element"
+ },
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1251,
+ "description": "
Attaches the element as a child to the parent specified.\n Accepts either a string ID, DOM node, or p5.Element.\n If no argument is specified, an array of children DOM nodes is returned.
\n",
+ "itemtype": "method",
+ "name": "child",
+ "params": [
+ {
+ "name": "child",
+ "description": "
the ID, DOM node, or p5.Element\n to add to the current element
\n",
+ "type": "String|Object|p5.Element",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.Element"
+ },
+ "example": [
+ "\n
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div0.child(div1); // use p5.Element\n
\n
\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div1.id('apples');\n div0.child('apples'); // use id\n
\n
\n var div0 = createDiv('this is the parent');\n var elt = document.getElementById('myChildDiv');\n div0.child(elt); // use element from page\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1295,
+ "description": "
Centers a p5 Element either vertically, horizontally,\nor both, relative to its parent or according to\nthe body if the Element has no parent. If no argument is passed\nthe Element is aligned both vertically and horizontally.
\n",
+ "itemtype": "method",
+ "name": "center",
+ "params": [
+ {
+ "name": "align",
+ "description": "
passing 'vertical', 'horizontal' aligns element accordingly
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "pointer to p5.Element",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\nfunction setup() {\n var div = createDiv('').size(10, 10);\n div.style('background-color', 'orange');\n div.center();\n}\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1348,
+ "description": "
If an argument is given, sets the inner HTML of the element,\n replacing any existing html. If true is included as a second\n argument, html is appended instead of replacing existing html.\n If no arguments are given, returns\n the inner HTML of the element.
\n",
+ "itemtype": "method",
+ "name": "html",
+ "params": [
+ {
+ "name": "html",
+ "description": "
the HTML to be placed inside the element
\n",
+ "type": "String",
+ "optional": true
+ },
+ {
+ "name": "append",
+ "description": "
whether to append HTML to existing
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element|String"
+ },
+ "example": [
+ "\n
\n var div = createDiv('').size(100, 100);\n div.html('hi');\n
\n
\n var div = createDiv('Hello ').size(100, 100);\n div.html('World', true);\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1383,
+ "description": "
Sets the position of the element relative to (0, 0) of the\n window. Essentially, sets position:absolute and left and top\n properties of style. If no arguments given returns the x and y position\n of the element in an object.
\n",
+ "itemtype": "method",
+ "name": "position",
+ "params": [
+ {
+ "name": "x",
+ "description": "
x-position relative to upper left of window
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "y",
+ "description": "
y-position relative to upper left of window
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\n function setup() {\n var cnv = createCanvas(100, 100);\n // positions canvas 50px to the right and 100px\n // below upper left corner of the window\n cnv.position(50, 100);\n }\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1473,
+ "description": "
Sets the given style (css) property (1st arg) of the element with the\ngiven value (2nd arg). If a single argument is given, .style()\nreturns the value of the given property; however, if the single argument\nis given in css syntax ('text-align:center'), .style() sets the css\nappropriatly. .style() also handles 2d and 3d css transforms. If\nthe 1st arg is 'rotate', 'translate', or 'position', the following arguments\naccept Numbers as values. ('translate', 10, 100, 50);
\n",
+ "itemtype": "method",
+ "name": "style",
+ "params": [
+ {
+ "name": "property",
+ "description": "
property to be set
\n",
+ "type": "String"
+ },
+ {
+ "name": "value",
+ "description": "
value to assign to property (only String|Number for rotate/translate)
\n",
+ "type": "String|Number|p5.Color",
+ "optional": true
+ },
+ {
+ "name": "value2",
+ "description": "
position can take a 2nd value
\n",
+ "type": "String|Number|p5.Color",
+ "optional": true
+ },
+ {
+ "name": "value3",
+ "description": "
translate can take a 2nd & 3rd value
\n",
+ "type": "String|Number|p5.Color",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "value of property, if no value is specified\nor p5.Element",
+ "type": "String|Object|p5.Element"
+ },
+ "example": [
+ "\n
\nvar myDiv = createDiv('I like pandas.');\nmyDiv.style('font-size', '18px');\nmyDiv.style('color', '#ff0000');\n
\n
\nvar col = color(25, 23, 200, 50);\nvar button = createButton('button');\nbutton.style('background-color', col);\nbutton.position(10, 10);\n
\n
\nvar myDiv = createDiv('I like lizards.');\nmyDiv.style('position', 20, 20);\nmyDiv.style('rotate', 45);\n
\n
\nvar myDiv;\nfunction setup() {\n background(200);\n myDiv = createDiv('I like gray.');\n myDiv.position(20, 20);\n}\n\nfunction draw() {\n myDiv.style('font-size', mouseX + 'px');\n}\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1570,
+ "description": "
Adds a new attribute or changes the value of an existing attribute\n on the specified element. If no value is specified, returns the\n value of the given attribute, or null if attribute is not set.
\n",
+ "itemtype": "method",
+ "name": "attribute",
+ "params": [
+ {
+ "name": "attr",
+ "description": "
attribute to set
\n",
+ "type": "String"
+ },
+ {
+ "name": "value",
+ "description": "
value to assign to attribute
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "value of attribute, if no value is\n specified or p5.Element",
+ "type": "String|Object|p5.Element"
+ },
+ "example": [
+ "\n
\n var myDiv = createDiv('I like pandas.');\n myDiv.attribute('align', 'center');\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1610,
+ "description": "
Removes an attribute on the specified element.
\n",
+ "itemtype": "method",
+ "name": "removeAttribute",
+ "params": [
+ {
+ "name": "attr",
+ "description": "
attribute to remove
\n",
+ "type": "String"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\n var button;\n var checkbox;\nfunction setup() {\n checkbox = createCheckbox('enable', true);\n checkbox.changed(enableButton);\n button = createButton('button');\n button.position(10, 10);\n }\nfunction enableButton() {\n if (this.checked()) {\n // Re-enable the button\n button.removeAttribute('disabled');\n } else {\n // Disable the button\n button.attribute('disabled', '');\n }\n }\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1655,
+ "description": "
Either returns the value of the element if no arguments\ngiven, or sets the value of the element.
\n",
+ "itemtype": "method",
+ "name": "value",
+ "params": [
+ {
+ "name": "value",
+ "description": "",
+ "type": "String|Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "value of element if no value is specified or p5.Element",
+ "type": "String|Object|p5.Element"
+ },
+ "example": [
+ "\n
\n// gets the value\nvar inp;\nfunction setup() {\n inp = createInput('');\n}\n\nfunction mousePressed() {\n print(inp.value());\n}\n
\n
\n// sets the value\nvar inp;\nfunction setup() {\n inp = createInput('myValue');\n}\n\nfunction mousePressed() {\n inp.value('myValue');\n}\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1697,
+ "description": "
Shows the current element. Essentially, setting display:block for the style.
\n",
+ "itemtype": "method",
+ "name": "show",
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\n var div = createDiv('div');\n div.style('display', 'none');\n div.show(); // turns display to block\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1715,
+ "description": "
Hides the current element. Essentially, setting display:none for the style.
\n",
+ "itemtype": "method",
+ "name": "hide",
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\nvar div = createDiv('this is a div');\ndiv.hide();\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1731,
+ "description": "
Sets the width and height of the element. AUTO can be used to\n only adjust one dimension. If no arguments given returns the width and height\n of the element in an object.
\n",
+ "itemtype": "method",
+ "name": "size",
+ "params": [
+ {
+ "name": "w",
+ "description": "
width of the element, either AUTO, or a number
\n",
+ "type": "Number|Constant",
+ "optional": true
+ },
+ {
+ "name": "h",
+ "description": "
height of the element, either AUTO, or a number
\n",
+ "type": "Number|Constant",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\n var div = createDiv('this is a div');\n div.size(100, 100);\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1805,
+ "description": "
Removes the element and deregisters all listeners.
\n",
+ "itemtype": "method",
+ "name": "remove",
+ "example": [
+ "\n
\nvar myDiv = createDiv('this is some text');\nmyDiv.remove();\n
"
+ ],
+ "class": "p5.Element",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1851,
+ "description": "
Path to the media element source.
\n",
+ "itemtype": "property",
+ "name": "src",
+ "return": {
+ "description": "src",
+ "type": "String"
+ },
+ "example": [
+ "\n
\nvar ele;\n\nfunction setup() {\n background(250);\n\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/beat.mp3');\n\n //We'll set up our example so that\n //when you click on the text,\n //an alert box displays the MediaElement's\n //src field.\n textAlign(CENTER);\n text('Click Me!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n //Show our p5.MediaElement's src field\n alert(ele.src);\n }\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1917,
+ "description": "
Play an HTML5 media element.
\n",
+ "itemtype": "method",
+ "name": "play",
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\nvar ele;\n\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/beat.mp3');\n\n background(250);\n textAlign(CENTER);\n text('Click to Play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n //Here we call the play() function on\n //the p5.MediaElement we created above.\n //This will start the audio sample.\n ele.play();\n\n background(200);\n text('You clicked Play!', width / 2, height / 2);\n }\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 1970,
+ "description": "
Stops an HTML5 media element (sets current time to zero).
\n",
+ "itemtype": "method",
+ "name": "stop",
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\n//This example both starts\n//and stops a sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\n\n//while our audio is playing,\n//this will be set to true\nvar sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n //if the sample is currently playing\n //calling the stop() function on\n //our p5.MediaElement will stop\n //it and reset its current\n //time to 0 (i.e. it will start\n //at the beginning the next time\n //you play it)\n ele.stop();\n\n sampleIsPlaying = false;\n text('Click to play!', width / 2, height / 2);\n } else {\n //loop our sound element until we\n //call ele.stop() on it.\n ele.loop();\n\n sampleIsPlaying = true;\n text('Click to stop!', width / 2, height / 2);\n }\n }\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2034,
+ "description": "
Pauses an HTML5 media element.
\n",
+ "itemtype": "method",
+ "name": "pause",
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\n//This example both starts\n//and pauses a sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\n\n//while our audio is playing,\n//this will be set to true\nvar sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n //Calling pause() on our\n //p5.MediaElement will stop it\n //playing, but when we call the\n //loop() or play() functions\n //the sample will start from\n //where we paused it.\n ele.pause();\n\n sampleIsPlaying = false;\n text('Click to resume!', width / 2, height / 2);\n } else {\n //loop our sound element until we\n //call ele.pause() on it.\n ele.loop();\n\n sampleIsPlaying = true;\n text('Click to pause!', width / 2, height / 2);\n }\n }\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2096,
+ "description": "
Set 'loop' to true for an HTML5 media element, and starts playing.
\n",
+ "itemtype": "method",
+ "name": "loop",
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\n//Clicking the canvas will loop\n//the audio sample until the user\n//clicks again to stop it\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\n\n//while our audio is playing,\n//this will be set to true\nvar sampleIsLooping = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to loop!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (!sampleIsLooping) {\n //loop our sound element until we\n //call ele.stop() on it.\n ele.loop();\n\n sampleIsLooping = true;\n text('Click to stop!', width / 2, height / 2);\n } else {\n ele.stop();\n\n sampleIsLooping = false;\n text('Click to loop!', width / 2, height / 2);\n }\n }\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2152,
+ "description": "
Set 'loop' to false for an HTML5 media element. Element will stop\nwhen it reaches the end.
\n",
+ "itemtype": "method",
+ "name": "noLoop",
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "example": [
+ "\n
\n//This example both starts\n//and stops loop of sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\n//while our audio is playing,\n//this will be set to true\nvar sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n ele.noLoop();\n text('No more Loops!', width / 2, height / 2);\n } else {\n ele.loop();\n sampleIsPlaying = true;\n text('Click to stop looping!', width / 2, height / 2);\n }\n }\n}\n
\n"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2204,
+ "description": "
Set HTML5 media element to autoplay or not.
\n",
+ "itemtype": "method",
+ "name": "autoplay",
+ "params": [
+ {
+ "name": "autoplay",
+ "description": "
whether the element should autoplay
\n",
+ "type": "Boolean"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Object|p5.Element"
+ },
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2216,
+ "description": "
Sets volume for this HTML5 media element. If no argument is given,\nreturns the current volume.
\n",
+ "params": [
+ {
+ "name": "val",
+ "description": "
volume between 0.0 and 1.0
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "current volume or p5.MediaElement",
+ "type": "Number|p5.MediaElement"
+ },
+ "itemtype": "method",
+ "name": "volume",
+ "example": [
+ "\n
\nvar ele;\nfunction setup() {\n // p5.MediaElement objects are usually created\n // by calling the createAudio(), createVideo(),\n // and createCapture() functions.\n // In this example we create\n // a new p5.MediaElement via createAudio().\n ele = createAudio('assets/lucky_dragons.mp3');\n background(250);\n textAlign(CENTER);\n text('Click to Play!', width / 2, height / 2);\n}\nfunction mouseClicked() {\n // Here we call the volume() function\n // on the sound element to set its volume\n // Volume must be between 0.0 and 1.0\n ele.volume(0.2);\n ele.play();\n background(200);\n text('You clicked Play!', width / 2, height / 2);\n}\n
\n
\nvar audio;\nvar counter = 0;\n\nfunction loaded() {\n audio.play();\n}\n\nfunction setup() {\n audio = createAudio('assets/lucky_dragons.mp3', loaded);\n textAlign(CENTER);\n}\n\nfunction draw() {\n if (counter === 0) {\n background(0, 255, 0);\n text('volume(0.9)', width / 2, height / 2);\n } else if (counter === 1) {\n background(255, 255, 0);\n text('volume(0.5)', width / 2, height / 2);\n } else if (counter === 2) {\n background(255, 0, 0);\n text('volume(0.1)', width / 2, height / 2);\n }\n}\n\nfunction mousePressed() {\n counter++;\n if (counter === 0) {\n audio.volume(0.9);\n } else if (counter === 1) {\n audio.volume(0.5);\n } else if (counter === 2) {\n audio.volume(0.1);\n } else {\n counter = 0;\n audio.volume(0.9);\n }\n}\n\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2298,
+ "description": "
If no arguments are given, returns the current playback speed of the\nelement. The speed parameter sets the speed where 2.0 will play the\nelement twice as fast, 0.5 will play at half the speed, and -1 will play\nthe element in normal speed in reverse.(Note that not all browsers support\nbackward playback and even if they do, playback might not be smooth.)
\n",
+ "itemtype": "method",
+ "name": "speed",
+ "params": [
+ {
+ "name": "speed",
+ "description": "
speed multiplier for element playback
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "current playback speed or p5.MediaElement",
+ "type": "Number|Object|p5.MediaElement"
+ },
+ "example": [
+ "\n
\n//Clicking the canvas will loop\n//the audio sample until the user\n//clicks again to stop it\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\nvar button;\n\nfunction setup() {\n createCanvas(710, 400);\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n ele.loop();\n background(200);\n\n button = createButton('2x speed');\n button.position(100, 68);\n button.mousePressed(twice_speed);\n\n button = createButton('half speed');\n button.position(200, 68);\n button.mousePressed(half_speed);\n\n button = createButton('reverse play');\n button.position(300, 68);\n button.mousePressed(reverse_speed);\n\n button = createButton('STOP');\n button.position(400, 68);\n button.mousePressed(stop_song);\n\n button = createButton('PLAY!');\n button.position(500, 68);\n button.mousePressed(play_speed);\n}\n\nfunction twice_speed() {\n ele.speed(2);\n}\n\nfunction half_speed() {\n ele.speed(0.5);\n}\n\nfunction reverse_speed() {\n ele.speed(-1);\n}\n\nfunction stop_song() {\n ele.stop();\n}\n\nfunction play_speed() {\n ele.play();\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2377,
+ "description": "
If no arguments are given, returns the current time of the element.\nIf an argument is given the current time of the element is set to it.
\n",
+ "itemtype": "method",
+ "name": "time",
+ "params": [
+ {
+ "name": "time",
+ "description": "
time to jump to (in seconds)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "current time (in seconds)\n or p5.MediaElement",
+ "type": "Number|Object|p5.MediaElement"
+ },
+ "example": [
+ "\n
\nvar ele;\nvar beginning = true;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/lucky_dragons.mp3');\n background(250);\n textAlign(CENTER);\n text('start at beginning', width / 2, height / 2);\n}\n\n// this function fires with click anywhere\nfunction mousePressed() {\n if (beginning === true) {\n // here we start the sound at the beginning\n // time(0) is not necessary here\n // as this produces the same result as\n // play()\n ele.play().time(0);\n background(200);\n text('jump 2 sec in', width / 2, height / 2);\n beginning = false;\n } else {\n // here we jump 2 seconds into the sound\n ele.play().time(2);\n background(250);\n text('start at beginning', width / 2, height / 2);\n beginning = true;\n }\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2432,
+ "description": "
Returns the duration of the HTML5 media element.
\n",
+ "itemtype": "method",
+ "name": "duration",
+ "return": {
+ "description": "duration",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\nvar ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/doorbell.mp3');\n background(250);\n textAlign(CENTER);\n text('Click to know the duration!', 10, 25, 70, 80);\n}\nfunction mouseClicked() {\n ele.play();\n background(200);\n //ele.duration dislpays the duration\n text(ele.duration() + ' seconds', width / 2, height / 2);\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2550,
+ "description": "
Schedule an event to be called when the audio or video\nelement reaches the end. If the element is looping,\nthis will not be called. The element is passed in\nas the argument to the onended callback.
\n",
+ "itemtype": "method",
+ "name": "onended",
+ "params": [
+ {
+ "name": "callback",
+ "description": "
function to call when the\n soundfile has ended. The\n media element will be passed\n in as the argument to the\n callback.
\n",
+ "type": "Function"
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "Object|p5.MediaElement"
+ },
+ "example": [
+ "\n
\nfunction setup() {\n var audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n audioEl.onended(sayDone);\n}\n\nfunction sayDone(elt) {\n alert('done playing ' + elt.src);\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2581,
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2583,
+ "description": "
Send the audio output of this element to a specified audioNode or\np5.sound object. If no element is provided, connects to p5's master\noutput. That connection is established when this method is first called.\nAll connections are removed by the .disconnect() method.
\n
This method is meant to be used with the p5.sound.js addon library.
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "audioNode",
+ "description": "
AudioNode from the Web Audio API,\nor an object from the p5.sound library
\n",
+ "type": "AudioNode|Object"
+ }
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2632,
+ "description": "
Disconnect all Web Audio routing, including to master output.\nThis is useful if you want to re-route the output through\naudio effects, for example.
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2647,
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2649,
+ "description": "
Show the default MediaElement controls, as determined by the web browser.
\n",
+ "itemtype": "method",
+ "name": "showControls",
+ "example": [
+ "\n
\nvar ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio()\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to Show Controls!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n ele.showControls();\n background(200);\n text('Controls Shown', width / 2, height / 2);\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2680,
+ "description": "
Hide the default mediaElement controls.
\n",
+ "itemtype": "method",
+ "name": "hideControls",
+ "example": [
+ "\n
\nvar ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio()\n ele = createAudio('assets/lucky_dragons.mp3');\n ele.showControls();\n background(200);\n textAlign(CENTER);\n text('Click to hide Controls!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n ele.hideControls();\n background(200);\n text('Controls hidden', width / 2, height / 2);\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2709,
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2720,
+ "description": "
Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.
\n
Accepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.
\n
Time will be passed as the first parameter to the callback function,\nand param will be the second parameter.
\n",
+ "itemtype": "method",
+ "name": "addCue",
+ "params": [
+ {
+ "name": "time",
+ "description": "
Time in seconds, relative to this media\n element's playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "callback",
+ "description": "
Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.
\n",
+ "type": "Function"
+ },
+ {
+ "name": "value",
+ "description": "
An object to be passed as the\n second parameter to the\n callback function.
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "id ID of this cue,\n useful for removeCue(id)",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\nfunction setup() {\n background(255, 255, 255);\n\n var audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n\n // schedule three calls to changeBackground\n audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n audioEl.addCue(5.0, changeBackground, color(255, 255, 0));\n}\n\nfunction changeBackground(val) {\n background(val);\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2782,
+ "description": "
Remove a callback based on its ID. The ID is returned by the\naddCue method.
\n",
+ "itemtype": "method",
+ "name": "removeCue",
+ "params": [
+ {
+ "name": "id",
+ "description": "
ID of the cue, as returned by addCue
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n
\nvar audioEl, id1, id2;\nfunction setup() {\n background(255, 255, 255);\n audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n // schedule five calls to changeBackground\n id1 = audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n id2 = audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n text('Click to remove first and last Cue!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n audioEl.removeCue(id1);\n audioEl.removeCue(id2);\n}\nfunction changeBackground(val) {\n background(val);\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2824,
+ "description": "
Remove all of the callbacks that had originally been scheduled\nvia the addCue method.
\n",
+ "itemtype": "method",
+ "name": "clearCues",
+ "params": [
+ {
+ "name": "id",
+ "description": "
ID of the cue, as returned by addCue
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n
\nvar audioEl;\nfunction setup() {\n background(255, 255, 255);\n audioEl = createAudio('assets/beat.mp3');\n //Show the default MediaElement controls, as determined by the web browser\n audioEl.showControls();\n // schedule calls to changeBackground\n background(200);\n text('Click to change Cue!', 10, 25, 70, 80);\n audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n}\nfunction mousePressed() {\n // here we clear the scheduled callbacks\n audioEl.clearCues();\n // then we add some more callbacks\n audioEl.addCue(1, changeBackground, color(2, 2, 2));\n audioEl.addCue(3, changeBackground, color(255, 255, 0));\n}\nfunction changeBackground(val) {\n background(val);\n}\n
"
+ ],
+ "class": "p5.MediaElement",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2894,
+ "description": "
Underlying File object. All normal File methods can be called on this.
\n",
+ "itemtype": "property",
+ "name": "file",
+ "class": "p5.File",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2906,
+ "description": "
File type (image, text, etc.)
\n",
+ "itemtype": "property",
+ "name": "type",
+ "class": "p5.File",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2912,
+ "description": "
File subtype (usually the file extension jpg, png, xml, etc.)
\n",
+ "itemtype": "property",
+ "name": "subtype",
+ "class": "p5.File",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2918,
+ "description": "
File name
\n",
+ "itemtype": "property",
+ "name": "name",
+ "class": "p5.File",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2924,
+ "description": "
File size
\n",
+ "itemtype": "property",
+ "name": "size",
+ "class": "p5.File",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.dom.js",
+ "line": 2931,
+ "description": "
URL string containing image data.
\n",
+ "itemtype": "property",
+ "name": "data",
+ "class": "p5.File",
+ "module": "p5.dom",
+ "submodule": "p5.dom"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 46,
+ "description": "
p5.sound\nhttps://p5js.org/reference/#/libraries/p5.sound
\n
From the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors
\n
MIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE
\n
Some of the many audio libraries & resources that inspire p5.sound:
\n
\n",
+ "class": "p5.sound",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 212,
+ "description": "
Returns the Audio Context for this sketch. Useful for users\nwho would like to dig deeper into the Web Audio API\n.
",
+ "itemtype": "method",
+ "name": "getAudioContext",
+ "return": {
+ "description": "AudioContext for this sketch",
+ "type": "Object"
+ },
+ "class": "p5.sound",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 226,
+ "description": "
Determine which filetypes are supported (inspired by buzz.js)\nThe audio element (el) will only be used to test browser support for various audio formats
\n",
+ "class": "p5.sound",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 296,
+ "description": "
Master contains AudioContext and the master sound output.
\n",
+ "class": "p5.sound",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 329,
+ "description": "
Returns a number representing the master amplitude (volume) for sound\nin this sketch.
\n",
+ "itemtype": "method",
+ "name": "getMasterVolume",
+ "return": {
+ "description": "Master amplitude (volume) for sound in this sketch.\n Should be between 0.0 (silence) and 1.0.",
+ "type": "Number"
+ },
+ "class": "p5.sound",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 340,
+ "description": "
Scale the output of all sound in this sketch
\nScaled between 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a
rampTime parameter. For more\ncomplex fades, see the Env class.\n\nAlternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.\n\n
How This Works: When you load the p5.sound module, it\ncreates a single instance of p5sound. All sound objects in this\nmodule output to p5sound before reaching your computer's output.\nSo if you change the amplitude of p5sound, it impacts all of the\nsound in this module.
\n\n
If no value is provided, returns a Web Audio API Gain Node
",
+ "itemtype": "method",
+ "name": "masterVolume",
+ "params": [
+ {
+ "name": "volume",
+ "description": "
Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator
\n",
+ "type": "Number|Object"
+ },
+ {
+ "name": "rampTime",
+ "description": "
Fade for t seconds
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
Schedule this event to happen at\n t seconds in the future
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.sound",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 382,
+ "description": "
p5.soundOut is the p5.sound master output. It sends output to\nthe destination of this window's web audio context. It contains\nWeb Audio API nodes including a dyanmicsCompressor (.limiter),\nand Gain Nodes for .input and .output.
\n",
+ "itemtype": "property",
+ "name": "soundOut",
+ "type": "Object",
+ "class": "p5.sound",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 407,
+ "class": "p5",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 410,
+ "description": "
Returns a number representing the sample rate, in samples per second,\nof all sound objects in this audio context. It is determined by the\nsampling rate of your operating system's sound card, and it is not\ncurrently possile to change.\nIt is often 44100, or twice the range of human hearing.
\n",
+ "itemtype": "method",
+ "name": "sampleRate",
+ "return": {
+ "description": "samplerate samples per second",
+ "type": "Number"
+ },
+ "class": "p5",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 423,
+ "description": "
Returns the closest MIDI note value for\na given frequency.
\n",
+ "itemtype": "method",
+ "name": "freqToMidi",
+ "params": [
+ {
+ "name": "frequency",
+ "description": "
A freqeuncy, for example, the "A"\n above Middle C is 440Hz
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "MIDI note value",
+ "type": "Number"
+ },
+ "class": "p5",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 437,
+ "description": "
Returns the frequency value of a MIDI note value.\nGeneral MIDI treats notes as integers where middle C\nis 60, C# is 61, D is 62 etc. Useful for generating\nmusical frequencies with oscillators.
\n",
+ "itemtype": "method",
+ "name": "midiToFreq",
+ "params": [
+ {
+ "name": "midiNote",
+ "description": "
The number of a MIDI note
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "Frequency value of the given MIDI note",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\nvar notes = [60, 64, 67, 72];\nvar i = 0;\n\nfunction setup() {\n osc = new p5.Oscillator('Triangle');\n osc.start();\n frameRate(1);\n}\n\nfunction draw() {\n var freq = midiToFreq(notes[i]);\n osc.freq(freq);\n i++;\n if (i >= notes.length){\n i = 0;\n }\n}\n
"
+ ],
+ "class": "p5",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 470,
+ "description": "
List the SoundFile formats that you will include. LoadSound\nwill search your directory for these extensions, and will pick\na format that is compatable with the client's web browser.\nHere is a free online file\nconverter.
\n",
+ "itemtype": "method",
+ "name": "soundFormats",
+ "params": [
+ {
+ "name": "formats",
+ "description": "
i.e. 'mp3', 'wav', 'ogg'
\n",
+ "type": "String",
+ "optional": true,
+ "multiple": true
+ }
+ ],
+ "example": [
+ "\n
\nfunction preload() {\n // set the global sound formats\n soundFormats('mp3', 'ogg');\n\n // load either beatbox.mp3, or .ogg, depending on browser\n mySound = loadSound('assets/beatbox.mp3');\n}\n\nfunction setup() {\n mySound.play();\n}\n
"
+ ],
+ "class": "p5",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 583,
+ "description": "
Used by Osc and Env to chain signal math
\n",
+ "class": "p5",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 855,
+ "description": "
loadSound() returns a new p5.SoundFile from a specified\npath. If called during preload(), the p5.SoundFile will be ready\nto play in time for setup() and draw(). If called outside of\npreload, the p5.SoundFile will not be ready immediately, so\nloadSound accepts a callback as the second parameter. Using a\n\nlocal server is recommended when loading external files.
\n",
+ "itemtype": "method",
+ "name": "loadSound",
+ "params": [
+ {
+ "name": "path",
+ "description": "
Path to the sound file, or an array with\n paths to soundfiles in multiple formats\n i.e. ['sound.ogg', 'sound.mp3'].\n Alternately, accepts an object: either\n from the HTML5 File API, or a p5.File.
\n",
+ "type": "String|Array"
+ },
+ {
+ "name": "successCallback",
+ "description": "
Name of a function to call once file loads
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "
Name of a function to call if there is\n an error loading the file.
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "whileLoading",
+ "description": "
Name of a function to call while file is loading.\n This function will receive the percentage loaded\n so far, from 0.0 to 1.0.
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Returns a p5.SoundFile",
+ "type": "SoundFile"
+ },
+ "example": [
+ "\n
\nfunction preload() {\n mySound = loadSound('assets/doorbell.mp3');\n}\n\nfunction setup() {\n mySound.setVolume(0.1);\n mySound.play();\n}\n
"
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 995,
+ "description": "
Returns true if the sound file finished loading successfully.
\n",
+ "itemtype": "method",
+ "name": "isLoaded",
+ "return": {
+ "description": "",
+ "type": "Boolean"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1008,
+ "description": "
Play the p5.SoundFile
\n",
+ "itemtype": "method",
+ "name": "play",
+ "params": [
+ {
+ "name": "startTime",
+ "description": "
(optional) schedule playback to start (in seconds from now).
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "rate",
+ "description": "
(optional) playback rate
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "amp",
+ "description": "
(optional) amplitude (volume)\n of playback
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "cueStart",
+ "description": "
(optional) cue start time in seconds
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "duration",
+ "description": "
(optional) duration of playback in seconds
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1109,
+ "description": "
p5.SoundFile has two play modes: restart and\nsustain. Play Mode determines what happens to a\np5.SoundFile if it is triggered while in the middle of playback.\nIn sustain mode, playback will continue simultaneous to the\nnew playback. In restart mode, play() will stop playback\nand start over. With untilDone, a sound will play only if it's\nnot already playing. Sustain is the default mode.
\n",
+ "itemtype": "method",
+ "name": "playMode",
+ "params": [
+ {
+ "name": "str",
+ "description": "
'restart' or 'sustain' or 'untilDone'
\n",
+ "type": "String"
+ }
+ ],
+ "example": [
+ "\n
\nfunction setup(){\n mySound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\nfunction mouseClicked() {\n mySound.playMode('sustain');\n mySound.play();\n}\nfunction keyPressed() {\n mySound.playMode('restart');\n mySound.play();\n}\n\n
"
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1152,
+ "description": "
Pauses a file that is currently playing. If the file is not\nplaying, then nothing will happen.
\n
After pausing, .play() will resume from the paused\nposition.\nIf p5.SoundFile had been set to loop before it was paused,\nit will continue to loop after it is unpaused with .play().
\n",
+ "itemtype": "method",
+ "name": "pause",
+ "params": [
+ {
+ "name": "startTime",
+ "description": "
(optional) schedule event to occur\n seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n
\nvar soundFile;\n\nfunction preload() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/Damscray_02.mp3');\n}\nfunction setup() {\n background(0, 255, 0);\n soundFile.setVolume(0.1);\n soundFile.loop();\n}\nfunction keyTyped() {\n if (key == 'p') {\n soundFile.pause();\n background(255, 0, 0);\n }\n}\n\nfunction keyReleased() {\n if (key == 'p') {\n soundFile.play();\n background(0, 255, 0);\n }\n}\n\n
"
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1208,
+ "description": "
Loop the p5.SoundFile. Accepts optional parameters to set the\nplayback rate, playback volume, loopStart, loopEnd.
\n",
+ "itemtype": "method",
+ "name": "loop",
+ "params": [
+ {
+ "name": "startTime",
+ "description": "
(optional) schedule event to occur\n seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "rate",
+ "description": "
(optional) playback rate
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "amp",
+ "description": "
(optional) playback volume
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "cueLoopStart",
+ "description": "
(optional) startTime in seconds
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "duration",
+ "description": "
(optional) loop duration in seconds
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1224,
+ "description": "
Set a p5.SoundFile's looping flag to true or false. If the sound\nis currently playing, this change will take effect when it\nreaches the end of the current playback.
\n",
+ "itemtype": "method",
+ "name": "setLoop",
+ "params": [
+ {
+ "name": "Boolean",
+ "description": "
set looping to true or false
\n",
+ "type": "Boolean"
+ }
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1245,
+ "description": "
Returns 'true' if a p5.SoundFile is currently looping and playing, 'false' if not.
\n",
+ "itemtype": "method",
+ "name": "isLooping",
+ "return": {
+ "description": "",
+ "type": "Boolean"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1260,
+ "description": "
Returns true if a p5.SoundFile is playing, false if not (i.e.\npaused or stopped).
\n",
+ "itemtype": "method",
+ "name": "isPlaying",
+ "return": {
+ "description": "",
+ "type": "Boolean"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1270,
+ "description": "
Returns true if a p5.SoundFile is paused, false if not (i.e.\nplaying or stopped).
\n",
+ "itemtype": "method",
+ "name": "isPaused",
+ "return": {
+ "description": "",
+ "type": "Boolean"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1280,
+ "description": "
Stop soundfile playback.
\n",
+ "itemtype": "method",
+ "name": "stop",
+ "params": [
+ {
+ "name": "startTime",
+ "description": "
(optional) schedule event to occur\n in seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1326,
+ "description": "
Multiply the output volume (amplitude) of a sound file\nbetween 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a rampTime parameter. For more\ncomplex fades, see the Env class.
\n
Alternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.
\n",
+ "itemtype": "method",
+ "name": "setVolume",
+ "params": [
+ {
+ "name": "volume",
+ "description": "
Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator
\n",
+ "type": "Number|Object"
+ },
+ {
+ "name": "rampTime",
+ "description": "
Fade for t seconds
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
Schedule this event to happen at\n t seconds in the future
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1367,
+ "description": "
Set the stereo panning of a p5.sound object to\na floating point number between -1.0 (left) and 1.0 (right).\nDefault is 0.0 (center).
\n",
+ "itemtype": "method",
+ "name": "pan",
+ "params": [
+ {
+ "name": "panValue",
+ "description": "
Set the stereo panner
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
schedule this event to happen\n seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n
\n\n var ball = {};\n var soundFile;\n\n function setup() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/beatbox.mp3');\n }\n\n function draw() {\n background(0);\n ball.x = constrain(mouseX, 0, width);\n ellipse(ball.x, height/2, 20, 20)\n }\n\n function mousePressed(){\n // map the ball's x location to a panning degree\n // between -1.0 (left) and 1.0 (right)\n var panning = map(ball.x, 0., width,-1.0, 1.0);\n soundFile.pan(panning);\n soundFile.play();\n }\n
"
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1406,
+ "description": "
Returns the current stereo pan position (-1.0 to 1.0)
\n",
+ "itemtype": "method",
+ "name": "getPan",
+ "return": {
+ "description": "Returns the stereo pan setting of the Oscillator\n as a number between -1.0 (left) and 1.0 (right).\n 0.0 is center and default.",
+ "type": "Number"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1417,
+ "description": "
Set the playback rate of a sound file. Will change the speed and the pitch.\nValues less than zero will reverse the audio buffer.
\n",
+ "itemtype": "method",
+ "name": "rate",
+ "params": [
+ {
+ "name": "playbackRate",
+ "description": "
Set the playback rate. 1.0 is normal,\n .5 is half-speed, 2.0 is twice as fast.\n Values less than zero play backwards.
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n
\nvar song;\n\nfunction preload() {\n song = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n song.loop();\n}\n\nfunction draw() {\n background(200);\n\n // Set the rate to a range between 0.1 and 4\n // Changing the rate also alters the pitch\n var speed = map(mouseY, 0.1, height, 0, 2);\n speed = constrain(speed, 0.01, 4);\n song.rate(speed);\n\n // Draw a circle to show what is going on\n stroke(0);\n fill(51, 100);\n ellipse(mouseX, 100, 48, 48);\n}\n\n \n
\n"
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1490,
+ "description": "
Returns the duration of a sound file in seconds.
\n",
+ "itemtype": "method",
+ "name": "duration",
+ "return": {
+ "description": "The duration of the soundFile in seconds.",
+ "type": "Number"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1504,
+ "description": "
Return the current position of the p5.SoundFile playhead, in seconds.\nTime is relative to the normal buffer direction, so if reverseBuffer\nhas been called, currentTime will count backwards.
\n",
+ "itemtype": "method",
+ "name": "currentTime",
+ "return": {
+ "description": "currentTime of the soundFile in seconds.",
+ "type": "Number"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1515,
+ "description": "
Move the playhead of the song to a position, in seconds. Start timing\nand playback duration. If none are given, will reset the file to play\nentire duration from start to finish.
\n",
+ "itemtype": "method",
+ "name": "jump",
+ "params": [
+ {
+ "name": "cueTime",
+ "description": "
cueTime of the soundFile in seconds.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "duration",
+ "description": "
duration in seconds.
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1538,
+ "description": "
Return the number of channels in a sound file.\nFor example, Mono = 1, Stereo = 2.
\n",
+ "itemtype": "method",
+ "name": "channels",
+ "return": {
+ "description": "[channels]",
+ "type": "Number"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1548,
+ "description": "
Return the sample rate of the sound file.
\n",
+ "itemtype": "method",
+ "name": "sampleRate",
+ "return": {
+ "description": "[sampleRate]",
+ "type": "Number"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1557,
+ "description": "
Return the number of samples in a sound file.\nEqual to sampleRate * duration.
\n",
+ "itemtype": "method",
+ "name": "frames",
+ "return": {
+ "description": "[sampleCount]",
+ "type": "Number"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1567,
+ "description": "
Returns an array of amplitude peaks in a p5.SoundFile that can be\nused to draw a static waveform. Scans through the p5.SoundFile's\naudio buffer to find the greatest amplitudes. Accepts one\nparameter, 'length', which determines size of the array.\nLarger arrays result in more precise waveform visualizations.
\n
Inspired by Wavesurfer.js.
\n",
+ "itemtype": "method",
+ "name": "getPeaks",
+ "params": [
+ {
+ "name": "length",
+ "description": "
length is the size of the returned array.\n Larger length results in more precision.\n Defaults to 5*width of the browser window.
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Array of peaks.",
+ "type": "Float32Array"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1619,
+ "description": "
Reverses the p5.SoundFile's buffer source.\nPlayback must be handled separately (see example).
\n",
+ "itemtype": "method",
+ "name": "reverseBuffer",
+ "example": [
+ "\n
\nvar drum;\n\nfunction preload() {\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n drum.reverseBuffer();\n drum.play();\n}\n\n \n
"
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1659,
+ "description": "
Schedule an event to be called when the soundfile\nreaches the end of a buffer. If the soundfile is\nplaying through once, this will be called when it\nends. If it is looping, it will be called when\nstop is called.
\n",
+ "itemtype": "method",
+ "name": "onended",
+ "params": [
+ {
+ "name": "callback",
+ "description": "
function to call when the\n soundfile has ended.
\n",
+ "type": "Function"
+ }
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1712,
+ "description": "
Connects the output of a p5sound object to input of another\np5.sound object. For example, you may connect a p5.SoundFile to an\nFFT or an Effect. If no parameter is given, it will connect to\nthe master output. Most p5sound objects connect to the master\noutput when they are created.
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "object",
+ "description": "
Audio object that accepts an input
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1733,
+ "description": "
Disconnects the output of this p5sound object.
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1741,
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1746,
+ "description": "
Reset the source for this SoundFile to a\nnew path (URL).
\n",
+ "itemtype": "method",
+ "name": "setPath",
+ "params": [
+ {
+ "name": "path",
+ "description": "
path to audio file
\n",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "
Callback
\n",
+ "type": "Function"
+ }
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1759,
+ "description": "
Replace the current Audio Buffer with a new Buffer.
\n",
+ "itemtype": "method",
+ "name": "setBuffer",
+ "params": [
+ {
+ "name": "buf",
+ "description": "
Array of Float32 Array(s). 2 Float32 Arrays\n will create a stereo source. 1 will create\n a mono source.
\n",
+ "type": "Array"
+ }
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 1831,
+ "description": "
processPeaks returns an array of timestamps where it thinks there is a beat.
\n
This is an asynchronous function that processes the soundfile in an offline audio context,\nand sends the results to your callback function.
\n
The process involves running the soundfile through a lowpass filter, and finding all of the\npeaks above the initial threshold. If the total number of peaks are below the minimum number of peaks,\nit decreases the threshold and re-runs the analysis until either minPeaks or minThreshold are reached.
\n",
+ "itemtype": "method",
+ "name": "processPeaks",
+ "params": [
+ {
+ "name": "callback",
+ "description": "
a function to call once this data is returned
\n",
+ "type": "Function"
+ },
+ {
+ "name": "initThreshold",
+ "description": "
initial threshold defaults to 0.9
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "minThreshold",
+ "description": "
minimum threshold defaults to 0.22
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "minPeaks",
+ "description": "
minimum number of peaks defaults to 200
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Array of timestamped peaks",
+ "type": "Array"
+ },
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2022,
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2031,
+ "description": "
Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.
\n
Accepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.
\n
Time will be passed as the first parameter to the callback function,\nand param will be the second parameter.
\n",
+ "itemtype": "method",
+ "name": "addCue",
+ "params": [
+ {
+ "name": "time",
+ "description": "
Time in seconds, relative to this media\n element's playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.
\n",
+ "type": "Number"
+ },
+ {
+ "name": "callback",
+ "description": "
Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.
\n",
+ "type": "Function"
+ },
+ {
+ "name": "value",
+ "description": "
An object to be passed as the\n second parameter to the\n callback function.
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "id ID of this cue,\n useful for removeCue(id)",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n mySound = loadSound('assets/beat.mp3');\n\n // schedule calls to changeText\n mySound.addCue(0.50, changeText, \"hello\" );\n mySound.addCue(1.00, changeText, \"p5\" );\n mySound.addCue(1.50, changeText, \"what\" );\n mySound.addCue(2.00, changeText, \"do\" );\n mySound.addCue(2.50, changeText, \"you\" );\n mySound.addCue(3.00, changeText, \"want\" );\n mySound.addCue(4.00, changeText, \"to\" );\n mySound.addCue(5.00, changeText, \"make\" );\n mySound.addCue(6.00, changeText, \"?\" );\n}\n\nfunction changeText(val) {\n background(0);\n text(val, width/2, height/2);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n if (mySound.isPlaying() ) {\n mySound.stop();\n } else {\n mySound.play();\n }\n }\n}\n
"
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2106,
+ "description": "
Remove a callback based on its ID. The ID is returned by the\naddCue method.
\n",
+ "itemtype": "method",
+ "name": "removeCue",
+ "params": [
+ {
+ "name": "id",
+ "description": "
ID of the cue, as returned by addCue
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2124,
+ "description": "
Remove all of the callbacks that had originally been scheduled\nvia the addCue method.
\n",
+ "itemtype": "method",
+ "name": "clearCues",
+ "class": "p5.SoundFile",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2232,
+ "description": "
Connects to the p5sound instance (master output) by default.\nOptionally, you can pass in a specific source (i.e. a soundfile).
\n",
+ "itemtype": "method",
+ "name": "setInput",
+ "params": [
+ {
+ "name": "snd",
+ "description": "
set the sound source\n (optional, defaults to\n master output)
\n",
+ "type": "SoundObject|undefined",
+ "optional": true
+ },
+ {
+ "name": "smoothing",
+ "description": "
a range between 0.0 and 1.0\n to smooth amplitude readings
\n",
+ "type": "Number|undefined",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n
\nfunction preload(){\n sound1 = loadSound('assets/beat.mp3');\n sound2 = loadSound('assets/drum.mp3');\n}\nfunction setup(){\n amplitude = new p5.Amplitude();\n sound1.play();\n sound2.play();\n amplitude.setInput(sound2);\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\nfunction mouseClicked(){\n sound1.stop();\n sound2.stop();\n}\n
"
+ ],
+ "class": "p5.Amplitude",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2337,
+ "description": "
Returns a single Amplitude reading at the moment it is called.\nFor continuous readings, run in the draw loop.
\n",
+ "itemtype": "method",
+ "name": "getLevel",
+ "params": [
+ {
+ "name": "channel",
+ "description": "
Optionally return only channel 0 (left) or 1 (right)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Amplitude as a number between 0.0 and 1.0",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\nfunction setup() {\n amplitude = new p5.Amplitude();\n sound.play();\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\nfunction mouseClicked(){\n sound.stop();\n}\n
"
+ ],
+ "class": "p5.Amplitude",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2378,
+ "description": "
Determines whether the results of Amplitude.process() will be\nNormalized. To normalize, Amplitude finds the difference the\nloudest reading it has processed and the maximum amplitude of\n1.0. Amplitude adds this difference to all values to produce\nresults that will reliably map between 0.0 and 1.0. However,\nif a louder moment occurs, the amount that Normalize adds to\nall the values will change. Accepts an optional boolean parameter\n(true or false). Normalizing is off by default.
\n",
+ "itemtype": "method",
+ "name": "toggleNormalize",
+ "params": [
+ {
+ "name": "boolean",
+ "description": "
set normalize to true (1) or false (0)
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "class": "p5.Amplitude",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2398,
+ "description": "
Smooth Amplitude analysis by averaging with the last analysis\nframe. Off by default.
\n",
+ "itemtype": "method",
+ "name": "smooth",
+ "params": [
+ {
+ "name": "set",
+ "description": "
smoothing from 0.0 <= 1
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.Amplitude",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2567,
+ "description": "
Set the input source for the FFT analysis. If no source is\nprovided, FFT will analyze all sound in the sketch.
\n",
+ "itemtype": "method",
+ "name": "setInput",
+ "params": [
+ {
+ "name": "source",
+ "description": "
p5.sound object (or web audio API source node)
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2586,
+ "description": "
Returns an array of amplitude values (between -1.0 and +1.0) that represent\na snapshot of amplitude readings in a single buffer. Length will be\nequal to bins (defaults to 1024). Can be used to draw the waveform\nof a sound.
\n",
+ "itemtype": "method",
+ "name": "waveform",
+ "params": [
+ {
+ "name": "bins",
+ "description": "
Must be a power of two between\n 16 and 1024. Defaults to 1024.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "precision",
+ "description": "
If any value is provided, will return results\n in a Float32 Array which is more precise\n than a regular array.
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Array Array of amplitude values (-1 to 1)\n over time. Array length = bins.",
+ "type": "Array"
+ },
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2629,
+ "description": "
Returns an array of amplitude values (between 0 and 255)\nacross the frequency spectrum. Length is equal to FFT bins\n(1024 by default). The array indices correspond to frequencies\n(i.e. pitches), from the lowest to the highest that humans can\nhear. Each value represents amplitude at that slice of the\nfrequency spectrum. Must be called prior to using\ngetEnergy().
\n",
+ "itemtype": "method",
+ "name": "analyze",
+ "params": [
+ {
+ "name": "bins",
+ "description": "
Must be a power of two between\n 16 and 1024. Defaults to 1024.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "scale",
+ "description": "
If "dB," returns decibel\n float measurements between\n -140 and 0 (max).\n Otherwise returns integers from 0-255.
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "spectrum Array of energy (amplitude/volume)\n values across the frequency spectrum.\n Lowest energy (silence) = 0, highest\n possible is 255.",
+ "type": "Array"
+ },
+ "example": [
+ "\n
\nvar osc;\nvar fft;\n\nfunction setup(){\n createCanvas(100,100);\n osc = new p5.Oscillator();\n osc.amp(0);\n osc.start();\n fft = new p5.FFT();\n}\n\nfunction draw(){\n background(0);\n\n var freq = map(mouseX, 0, 800, 20, 15000);\n freq = constrain(freq, 1, 20000);\n osc.freq(freq);\n\n var spectrum = fft.analyze();\n noStroke();\n fill(0,255,0); // spectrum is green\n for (var i = 0; i< spectrum.length; i++){\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h );\n }\n\n stroke(255);\n text('Freq: ' + round(freq)+'Hz', 10, 10);\n\n isMouseOverCanvas();\n}\n\n// only play sound when mouse is over canvas\nfunction isMouseOverCanvas() {\n var mX = mouseX, mY = mouseY;\n if (mX > 0 && mX < width && mY < height && mY > 0) {\n osc.amp(0.5, 0.2);\n } else {\n osc.amp(0, 0.2);\n }\n}\n
\n\n"
+ ],
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2721,
+ "description": "
Returns the amount of energy (volume) at a specific\n\nfrequency, or the average amount of energy between two\nfrequencies. Accepts Number(s) corresponding\nto frequency (in Hz), or a String corresponding to predefined\nfrequency ranges ("bass", "lowMid", "mid", "highMid", "treble").\nReturns a range between 0 (no energy/volume at that frequency) and\n255 (maximum energy).\nNOTE: analyze() must be called prior to getEnergy(). Analyze()\ntells the FFT to analyze frequency data, and getEnergy() uses\nthe results determine the value at a specific frequency or\nrange of frequencies.
\n",
+ "itemtype": "method",
+ "name": "getEnergy",
+ "params": [
+ {
+ "name": "frequency1",
+ "description": "
Will return a value representing\n energy at this frequency. Alternately,\n the strings "bass", "lowMid" "mid",\n "highMid", and "treble" will return\n predefined frequency ranges.
\n",
+ "type": "Number|String"
+ },
+ {
+ "name": "frequency2",
+ "description": "
If a second frequency is given,\n will return average amount of\n energy that exists between the\n two frequencies.
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Energy Energy (volume/amplitude) from\n 0 and 255.",
+ "type": "Number"
+ },
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2803,
+ "description": "
Returns the\n\nspectral centroid of the input signal.\nNOTE: analyze() must be called prior to getCentroid(). Analyze()\ntells the FFT to analyze frequency data, and getCentroid() uses\nthe results determine the spectral centroid.
\n",
+ "itemtype": "method",
+ "name": "getCentroid",
+ "return": {
+ "description": "Spectral Centroid Frequency Frequency of the spectral centroid in Hz.",
+ "type": "Number"
+ },
+ "example": [
+ "\n
\n\n\nfunction setup(){\ncnv = createCanvas(800,400);\nsound = new p5.AudioIn();\nsound.start();\nfft = new p5.FFT();\nsound.connect(fft);\n}\n\n\nfunction draw(){\n\nvar centroidplot = 0.0;\nvar spectralCentroid = 0;\n\n\nbackground(0);\nstroke(0,255,0);\nvar spectrum = fft.analyze();\nfill(0,255,0); // spectrum is green\n\n//draw the spectrum\n\nfor (var i = 0; i< spectrum.length; i++){\n var x = map(log(i), 0, log(spectrum.length), 0, width);\n var h = map(spectrum[i], 0, 255, 0, height);\n var rectangle_width = (log(i+1)-log(i))*(width/log(spectrum.length));\n rect(x, height, rectangle_width, -h )\n}\n\nvar nyquist = 22050;\n\n// get the centroid\nspectralCentroid = fft.getCentroid();\n\n// the mean_freq_index calculation is for the display.\nvar mean_freq_index = spectralCentroid/(nyquist/spectrum.length);\n\ncentroidplot = map(log(mean_freq_index), 0, log(spectrum.length), 0, width);\n\n\nstroke(255,0,0); // the line showing where the centroid is will be red\n\nrect(centroidplot, 0, width / spectrum.length, height)\nnoStroke();\nfill(255,255,255); // text is white\ntextSize(40);\ntext(\"centroid: \"+round(spectralCentroid)+\" Hz\", 10, 40);\n}\n
"
+ ],
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2884,
+ "description": "
Smooth FFT analysis by averaging with the last analysis frame.
\n",
+ "itemtype": "method",
+ "name": "smooth",
+ "params": [
+ {
+ "name": "smoothing",
+ "description": "
0.0 < smoothing < 1.0.\n Defaults to 0.8.
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2904,
+ "description": "
Returns an array of average amplitude values for a given number\nof frequency bands split equally. N defaults to 16.\nNOTE: analyze() must be called prior to linAverages(). Analyze()\ntells the FFT to analyze frequency data, and linAverages() uses\nthe results to group them into a smaller set of averages.
\n",
+ "itemtype": "method",
+ "name": "linAverages",
+ "params": [
+ {
+ "name": "N",
+ "description": "
Number of returned frequency groups
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "linearAverages Array of average amplitude values for each group",
+ "type": "Array"
+ },
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2934,
+ "description": "
Returns an array of average amplitude values of the spectrum, for a given\nset of \nOctave Bands\nNOTE: analyze() must be called prior to logAverages(). Analyze()\ntells the FFT to analyze frequency data, and logAverages() uses\nthe results to group them into a smaller set of averages.
\n",
+ "itemtype": "method",
+ "name": "logAverages",
+ "params": [
+ {
+ "name": "octaveBands",
+ "description": "
Array of Octave Bands objects for grouping
\n",
+ "type": "Array"
+ }
+ ],
+ "return": {
+ "description": "logAverages Array of average amplitude values for each group",
+ "type": "Array"
+ },
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 2964,
+ "description": "
Calculates and Returns the 1/N\nOctave Bands\nN defaults to 3 and minimum central frequency to 15.625Hz.\n(1/3 Octave Bands ~= 31 Frequency Bands)\nSetting fCtr0 to a central value of a higher octave will ignore the lower bands\nand produce less frequency groups.
\n",
+ "itemtype": "method",
+ "name": "getOctaveBands",
+ "params": [
+ {
+ "name": "N",
+ "description": "
Specifies the 1/N type of generated octave bands
\n",
+ "type": "Number"
+ },
+ {
+ "name": "fCtr0",
+ "description": "
Minimum central frequency for the lowest band
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "octaveBands Array of octave band objects with their bounds",
+ "type": "Array"
+ },
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 3022,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 3399,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 3420,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 3479,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 3797,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 3969,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4127,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4168,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4238,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4426,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4483,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4651,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4699,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4730,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4751,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4771,
+ "class": "p5.FFT",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4873,
+ "description": "
Fade to value, for smooth transitions
\n",
+ "itemtype": "method",
+ "name": "fade",
+ "params": [
+ {
+ "name": "value",
+ "description": "
Value to set this signal
\n",
+ "type": "Number"
+ },
+ {
+ "name": "secondsFromNow",
+ "description": "
Length of fade, in seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Signal",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4884,
+ "description": "
Connect a p5.sound object or Web Audio node to this\np5.Signal so that its amplitude values can be scaled.
\n",
+ "itemtype": "method",
+ "name": "setInput",
+ "params": [
+ {
+ "name": "input",
+ "description": "",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.Signal",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4898,
+ "description": "
Add a constant value to this audio signal,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalAdd.
\n",
+ "itemtype": "method",
+ "name": "add",
+ "params": [
+ {
+ "name": "number",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "object",
+ "type": "p5.Signal"
+ },
+ "class": "p5.Signal",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4917,
+ "description": "
Multiply this signal by a constant value,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalMult.
\n",
+ "itemtype": "method",
+ "name": "mult",
+ "params": [
+ {
+ "name": "number",
+ "description": "
to multiply
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "object",
+ "type": "p5.Signal"
+ },
+ "class": "p5.Signal",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 4936,
+ "description": "
Scale this signal value to a given range,\nand return the result as an audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalScale.
\n",
+ "itemtype": "method",
+ "name": "scale",
+ "params": [
+ {
+ "name": "number",
+ "description": "
to multiply
\n",
+ "type": "Number"
+ },
+ {
+ "name": "inMin",
+ "description": "
input range minumum
\n",
+ "type": "Number"
+ },
+ {
+ "name": "inMax",
+ "description": "
input range maximum
\n",
+ "type": "Number"
+ },
+ {
+ "name": "outMin",
+ "description": "
input range minumum
\n",
+ "type": "Number"
+ },
+ {
+ "name": "outMax",
+ "description": "
input range maximum
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "object",
+ "type": "p5.Signal"
+ },
+ "class": "p5.Signal",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5070,
+ "description": "
Start an oscillator. Accepts an optional parameter to\ndetermine how long (in seconds from now) until the\noscillator starts.
\n",
+ "itemtype": "method",
+ "name": "start",
+ "params": [
+ {
+ "name": "time",
+ "description": "
startTime in seconds from now.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "frequency",
+ "description": "
frequency in Hz.
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5110,
+ "description": "
Stop an oscillator. Accepts an optional parameter\nto determine how long (in seconds from now) until the\noscillator stops.
\n",
+ "itemtype": "method",
+ "name": "stop",
+ "params": [
+ {
+ "name": "secondsFromNow",
+ "description": "
Time, in seconds from now.
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5126,
+ "description": "
Set the amplitude between 0 and 1.0. Or, pass in an object\nsuch as an oscillator to modulate amplitude with an audio signal.
\n",
+ "itemtype": "method",
+ "name": "amp",
+ "params": [
+ {
+ "name": "vol",
+ "description": "
between 0 and 1.0\n or a modulating signal/oscillator
\n",
+ "type": "Number|Object"
+ },
+ {
+ "name": "rampTime",
+ "description": "
create a fade that lasts rampTime
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
schedule this event to happen\n seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "gain If no value is provided,\n returns the Web Audio API\n AudioParam that controls\n this oscillator's\n gain/amplitude/volume)",
+ "type": "AudioParam"
+ },
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5161,
+ "description": "
Set frequency of an oscillator to a value. Or, pass in an object\nsuch as an oscillator to modulate the frequency with an audio signal.
\n",
+ "itemtype": "method",
+ "name": "freq",
+ "params": [
+ {
+ "name": "Frequency",
+ "description": "
Frequency in Hz\n or modulating signal/oscillator
\n",
+ "type": "Number|Object"
+ },
+ {
+ "name": "rampTime",
+ "description": "
Ramp time (in seconds)
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
Schedule this event to happen\n at x seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Frequency If no value is provided,\n returns the Web Audio API\n AudioParam that controls\n this oscillator's frequency",
+ "type": "AudioParam"
+ },
+ "example": [
+ "\n
\nvar osc = new p5.Oscillator(300);\nosc.start();\nosc.freq(40, 10);\n
"
+ ],
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5220,
+ "description": "
Set type to 'sine', 'triangle', 'sawtooth' or 'square'.
\n",
+ "itemtype": "method",
+ "name": "setType",
+ "params": [
+ {
+ "name": "type",
+ "description": "
'sine', 'triangle', 'sawtooth' or 'square'.
\n",
+ "type": "String"
+ }
+ ],
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5232,
+ "description": "
Connect to a p5.sound / Web Audio object.
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "unit",
+ "description": "
A p5.sound or Web Audio object
\n",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5249,
+ "description": "
Disconnect all outputs
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5260,
+ "description": "
Pan between Left (-1) and Right (1)
\n",
+ "itemtype": "method",
+ "name": "pan",
+ "params": [
+ {
+ "name": "panning",
+ "description": "
Number between -1 and 1
\n",
+ "type": "Number"
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
schedule this event to happen\n seconds from now
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5292,
+ "description": "
Set the phase of an oscillator between 0.0 and 1.0.\nIn this implementation, phase is a delay time\nbased on the oscillator's current frequency.
\n",
+ "itemtype": "method",
+ "name": "phase",
+ "params": [
+ {
+ "name": "phase",
+ "description": "
float between 0.0 and 1.0
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5346,
+ "description": "
Add a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method again\nwill override the initial add() with a new value.
\n",
+ "itemtype": "method",
+ "name": "add",
+ "params": [
+ {
+ "name": "number",
+ "description": "
Constant number to add
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "Oscillator Returns this oscillator\n with scaled output",
+ "type": "p5.Oscillator"
+ },
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5363,
+ "description": "
Multiply the p5.Oscillator's output amplitude\nby a fixed value (i.e. turn it up!). Calling this method\nagain will override the initial mult() with a new value.
\n",
+ "itemtype": "method",
+ "name": "mult",
+ "params": [
+ {
+ "name": "number",
+ "description": "
Constant number to multiply
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "Oscillator Returns this oscillator\n with multiplied output",
+ "type": "p5.Oscillator"
+ },
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5379,
+ "description": "
Scale this oscillator's amplitude values to a given\nrange, and return the oscillator. Calling this method\nagain will override the initial scale() with new values.
\n",
+ "itemtype": "method",
+ "name": "scale",
+ "params": [
+ {
+ "name": "inMin",
+ "description": "
input range minumum
\n",
+ "type": "Number"
+ },
+ {
+ "name": "inMax",
+ "description": "
input range maximum
\n",
+ "type": "Number"
+ },
+ {
+ "name": "outMin",
+ "description": "
input range minumum
\n",
+ "type": "Number"
+ },
+ {
+ "name": "outMax",
+ "description": "
input range maximum
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "Oscillator Returns this oscillator\n with scaled output",
+ "type": "p5.Oscillator"
+ },
+ "class": "p5.Oscillator",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5478,
+ "class": "p5.SqrOsc",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5681,
+ "class": "p5.SqrOsc",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5970,
+ "description": "
Time until envelope reaches attackLevel
\n",
+ "itemtype": "property",
+ "name": "attackTime",
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5975,
+ "description": "
Level once attack is complete.
\n",
+ "itemtype": "property",
+ "name": "attackLevel",
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5980,
+ "description": "
Time until envelope reaches decayLevel.
\n",
+ "itemtype": "property",
+ "name": "decayTime",
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5985,
+ "description": "
Level after decay. The envelope will sustain here until it is released.
\n",
+ "itemtype": "property",
+ "name": "decayLevel",
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5990,
+ "description": "
Duration of the release portion of the envelope.
\n",
+ "itemtype": "property",
+ "name": "releaseTime",
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 5995,
+ "description": "
Level at the end of the release.
\n",
+ "itemtype": "property",
+ "name": "releaseLevel",
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6031,
+ "description": "
Reset the envelope with a series of time/value pairs.
\n",
+ "itemtype": "method",
+ "name": "set",
+ "params": [
+ {
+ "name": "attackTime",
+ "description": "
Time (in seconds) before level\n reaches attackLevel
\n",
+ "type": "Number"
+ },
+ {
+ "name": "attackLevel",
+ "description": "
Typically an amplitude between\n 0.0 and 1.0
\n",
+ "type": "Number"
+ },
+ {
+ "name": "decayTime",
+ "description": "
Time
\n",
+ "type": "Number"
+ },
+ {
+ "name": "decayLevel",
+ "description": "
Amplitude (In a standard ADSR envelope,\n decayLevel = sustainLevel)
\n",
+ "type": "Number"
+ },
+ {
+ "name": "releaseTime",
+ "description": "
Release Time (in seconds)
\n",
+ "type": "Number"
+ },
+ {
+ "name": "releaseLevel",
+ "description": "
Amplitude
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n
\nvar t1 = 0.1; // attack time in seconds\nvar l1 = 0.7; // attack level 0.0 to 1.0\nvar t2 = 0.3; // decay time in seconds\nvar l2 = 0.1; // decay level 0.0 to 1.0\nvar t3 = 0.2; // sustain time in seconds\nvar l3 = 0.2; // sustain level 0.0 to 1.0\n// release level defaults to zero\n\nvar env;\nvar triOsc;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env(t1, l1, t2, l2, t3, l3);\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env); // give the env control of the triOsc's amp\n triOsc.start();\n}\n\n// mouseClick triggers envelope if over canvas\nfunction mouseClicked() {\n // is mouse over canvas?\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n env.play(triOsc);\n }\n}\n
\n"
+ ],
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6090,
+ "description": "
Set values like a traditional\n\nADSR envelope\n.
\n",
+ "itemtype": "method",
+ "name": "setADSR",
+ "params": [
+ {
+ "name": "attackTime",
+ "description": "
Time (in seconds before envelope\n reaches Attack Level
\n",
+ "type": "Number"
+ },
+ {
+ "name": "decayTime",
+ "description": "
Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "susRatio",
+ "description": "
Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "releaseTime",
+ "description": "
Time in seconds from now (defaults to 0)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n
"
+ ],
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6155,
+ "description": "
Set max (attackLevel) and min (releaseLevel) of envelope.
\n",
+ "itemtype": "method",
+ "name": "setRange",
+ "params": [
+ {
+ "name": "aLevel",
+ "description": "
attack level (defaults to 1)
\n",
+ "type": "Number"
+ },
+ {
+ "name": "rLevel",
+ "description": "
release level (defaults to 0)
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n
"
+ ],
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6234,
+ "description": "
Assign a parameter to be controlled by this envelope.\nIf a p5.Sound object is given, then the p5.Env will control its\noutput gain. If multiple inputs are provided, the env will\ncontrol all of them.
\n",
+ "itemtype": "method",
+ "name": "setInput",
+ "params": [
+ {
+ "name": "inputs",
+ "description": "
A p5.sound object or\n Web Audio Param.
\n",
+ "type": "Object",
+ "optional": true,
+ "multiple": true
+ }
+ ],
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6249,
+ "description": "
Set whether the envelope ramp is linear (default) or exponential.\nExponential ramps can be useful because we perceive amplitude\nand frequency logarithmically.
\n",
+ "itemtype": "method",
+ "name": "setExp",
+ "params": [
+ {
+ "name": "isExp",
+ "description": "
true is exponential, false is linear
\n",
+ "type": "Boolean"
+ }
+ ],
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6267,
+ "description": "
Play tells the envelope to start acting on a given input.\nIf the input is a p5.sound object (i.e. AudioIn, Oscillator,\nSoundFile), then Env will control its output volume.\nEnvelopes can also be used to control any \nWeb Audio Audio Param.
\n",
+ "itemtype": "method",
+ "name": "play",
+ "params": [
+ {
+ "name": "unit",
+ "description": "
A p5.sound object or\n Web Audio Param.
\n",
+ "type": "Object"
+ },
+ {
+ "name": "startTime",
+ "description": "
time from now (in seconds) at which to play
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "sustainTime",
+ "description": "
time to sustain before releasing the envelope
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n
\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n // trigger env on triOsc, 0 seconds from now\n // After decay, sustain for 0.2 seconds before release\n env.play(triOsc, 0, 0.2);\n}\n
"
+ ],
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6328,
+ "description": "
Trigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go. Input can be\nany p5.sound object, or a \nWeb Audio Param.
\n",
+ "itemtype": "method",
+ "name": "triggerAttack",
+ "params": [
+ {
+ "name": "unit",
+ "description": "
p5.sound Object or Web Audio Param
\n",
+ "type": "Object"
+ },
+ {
+ "name": "secondsFromNow",
+ "description": "
time from now (in seconds)
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n
\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.3;\nvar susPercent = 0.4;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack(){\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\n
"
+ ],
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6435,
+ "description": "
Trigger the Release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n",
+ "itemtype": "method",
+ "name": "triggerRelease",
+ "params": [
+ {
+ "name": "unit",
+ "description": "
p5.sound Object or Web Audio Param
\n",
+ "type": "Object"
+ },
+ {
+ "name": "secondsFromNow",
+ "description": "
time to trigger the release
\n",
+ "type": "Number"
+ }
+ ],
+ "example": [
+ "\n
\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.3;\nvar susPercent = 0.4;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack(){\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\n
"
+ ],
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6532,
+ "description": "
Exponentially ramp to a value using the first two\nvalues from setADSR(attackTime, decayTime)\nas \ntime constants for simple exponential ramps.\nIf the value is higher than current value, it uses attackTime,\nwhile a decrease uses decayTime.
\n",
+ "itemtype": "method",
+ "name": "ramp",
+ "params": [
+ {
+ "name": "unit",
+ "description": "
p5.sound Object or Web Audio Param
\n",
+ "type": "Object"
+ },
+ {
+ "name": "secondsFromNow",
+ "description": "
When to trigger the ramp
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v",
+ "description": "
Target value
\n",
+ "type": "Number"
+ },
+ {
+ "name": "v2",
+ "description": "
Second target value (optional)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n
\nvar env, osc, amp, cnv;\n\nvar attackTime = 0.001;\nvar decayTime = 0.2;\nvar attackLevel = 1;\nvar decayLevel = 0;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n fill(0,255,0);\n noStroke();\n\n env = new p5.Env();\n env.setADSR(attackTime, decayTime);\n\n osc = new p5.Oscillator();\n osc.amp(env);\n osc.start();\n\n amp = new p5.Amplitude();\n\n cnv.mousePressed(triggerRamp);\n}\n\nfunction triggerRamp() {\n env.ramp(osc, 0, attackLevel, decayLevel);\n}\n\nfunction draw() {\n background(20,20,20);\n text('click me', 10, 20);\n var h = map(amp.getLevel(), 0, 0.4, 0, height);;\n\n rect(0, height, width, -h);\n}\n
"
+ ],
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6637,
+ "description": "
Add a value to the p5.Oscillator's output amplitude,\nand return the oscillator. Calling this method\nagain will override the initial add() with new values.
\n",
+ "itemtype": "method",
+ "name": "add",
+ "params": [
+ {
+ "name": "number",
+ "description": "
Constant number to add
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "Envelope Returns this envelope\n with scaled output",
+ "type": "p5.Env"
+ },
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6653,
+ "description": "
Multiply the p5.Env's output amplitude\nby a fixed value. Calling this method\nagain will override the initial mult() with new values.
\n",
+ "itemtype": "method",
+ "name": "mult",
+ "params": [
+ {
+ "name": "number",
+ "description": "
Constant number to multiply
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "Envelope Returns this envelope\n with scaled output",
+ "type": "p5.Env"
+ },
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6669,
+ "description": "
Scale this envelope's amplitude values to a given\nrange, and return the envelope. Calling this method\nagain will override the initial scale() with new values.
\n",
+ "itemtype": "method",
+ "name": "scale",
+ "params": [
+ {
+ "name": "inMin",
+ "description": "
input range minumum
\n",
+ "type": "Number"
+ },
+ {
+ "name": "inMax",
+ "description": "
input range maximum
\n",
+ "type": "Number"
+ },
+ {
+ "name": "outMin",
+ "description": "
input range minumum
\n",
+ "type": "Number"
+ },
+ {
+ "name": "outMax",
+ "description": "
input range maximum
\n",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "Envelope Returns this envelope\n with scaled output",
+ "type": "p5.Env"
+ },
+ "class": "p5.Env",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6773,
+ "description": "
Set the width of a Pulse object (an oscillator that implements\nPulse Width Modulation).
\n",
+ "itemtype": "method",
+ "name": "width",
+ "params": [
+ {
+ "name": "width",
+ "description": "
Width between the pulses (0 to 1.0,\n defaults to 0)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Pulse",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6958,
+ "description": "
Set type of noise to 'white', 'pink' or 'brown'.\nWhite is the default.
\n",
+ "itemtype": "method",
+ "name": "setType",
+ "params": [
+ {
+ "name": "type",
+ "description": "
'white', 'pink' or 'brown'
\n",
+ "type": "String",
+ "optional": true
+ }
+ ],
+ "class": "p5.Noise",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 6988,
+ "description": "
Start the noise
\n",
+ "itemtype": "method",
+ "name": "start",
+ "class": "p5.Noise",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7005,
+ "description": "
Stop the noise.
\n",
+ "itemtype": "method",
+ "name": "stop",
+ "class": "p5.Noise",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7017,
+ "description": "
Pan the noise.
\n",
+ "itemtype": "method",
+ "name": "pan",
+ "params": [
+ {
+ "name": "panning",
+ "description": "
Number between -1 (left)\n and 1 (right)
\n",
+ "type": "Number"
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
schedule this event to happen\n seconds from now
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.Noise",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7026,
+ "description": "
Set the amplitude of the noise between 0 and 1.0. Or,\nmodulate amplitude with an audio signal such as an oscillator.
\n",
+ "itemtype": "method",
+ "name": "amp",
+ "params": [
+ {
+ "name": "volume",
+ "description": "
amplitude between 0 and 1.0\n or modulating signal/oscillator
\n",
+ "type": "Number|Object"
+ },
+ {
+ "name": "rampTime",
+ "description": "
create a fade that lasts rampTime
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
schedule this event to happen\n seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Noise",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7037,
+ "description": "
Send output to a p5.sound or web audio object
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "unit",
+ "description": "",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.Noise",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7043,
+ "description": "
Disconnect all output.
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.Noise",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7117,
+ "description": "
Client must allow browser to access their microphone / audioin source.\nDefault: false. Will become true when the client enables acces.
\n",
+ "itemtype": "property",
+ "name": "enabled",
+ "type": "Boolean",
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7133,
+ "description": "
Start processing audio input. This enables the use of other\nAudioIn methods like getLevel(). Note that by default, AudioIn\nis not connected to p5.sound's output. So you won't hear\nanything unless you use the connect() method.
\n
Certain browsers limit access to the user's microphone. For example,\nChrome only allows access from localhost and over https. For this reason,\nyou may want to include an errorCallback—a function that is called in case\nthe browser won't provide mic access.
\n",
+ "itemtype": "method",
+ "name": "start",
+ "params": [
+ {
+ "name": "successCallback",
+ "description": "
Name of a function to call on\n success.
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "
Name of a function to call if\n there was an error. For example,\n some browsers do not support\n getUserMedia.
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7186,
+ "description": "
Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel().\nIf re-starting, the user may be prompted for permission access.
\n",
+ "itemtype": "method",
+ "name": "stop",
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7202,
+ "description": "
Connect to an audio unit. If no parameter is provided, will\nconnect to the master output (i.e. your speakers).
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "unit",
+ "description": "
An object that accepts audio input,\n such as an FFT
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7223,
+ "description": "
Disconnect the AudioIn from all audio units. For example, if\nconnect() had been called, disconnect() will stop sending\nsignal to your speakers.
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7235,
+ "description": "
Read the Amplitude (volume level) of an AudioIn. The AudioIn\nclass contains its own instance of the Amplitude class to help\nmake it easy to get a microphone's volume level. Accepts an\noptional smoothing value (0.0 < 1.0). NOTE: AudioIn must\n.start() before using .getLevel().
\n",
+ "itemtype": "method",
+ "name": "getLevel",
+ "params": [
+ {
+ "name": "smoothing",
+ "description": "
Smoothing is 0.0 by default.\n Smooths values based on previous values.
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Volume level (between 0.0 and 1.0)",
+ "type": "Number"
+ },
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7253,
+ "description": "
Set amplitude (volume) of a mic input between 0 and 1.0.
\n",
+ "itemtype": "method",
+ "name": "amp",
+ "params": [
+ {
+ "name": "vol",
+ "description": "
between 0 and 1.0
\n",
+ "type": "Number"
+ },
+ {
+ "name": "time",
+ "description": "
ramp time (optional)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7272,
+ "description": "
Returns a list of available input sources. This is a wrapper\nfor <a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n "https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"
\n
\nand it returns a Promise.
\n
\n",
+ "itemtype": "method",
+ "name": "getSources",
+ "params": [
+ {
+ "name": "successCallback",
+ "description": "
This callback function handles the sources when they\n have been enumerated. The callback function\n receives the deviceList array as its only argument
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "
This optional callback receives the error\n message as its argument.
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "Returns a Promise that can be used in place of the callbacks, similar\n to the enumerateDevices() method",
+ "type": "Object"
+ },
+ "example": [
+ "\n
\n var audiograb;\n\n function setup(){\n //new audioIn\n audioGrab = new p5.AudioIn();\n\n audioGrab.getSources(function(deviceList) {\n //print out the array of available sources\n console.log(deviceList);\n //set the source to the first item in the deviceList array\n audioGrab.setSource(0);\n });\n }\n
"
+ ],
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7323,
+ "description": "
Set the input source. Accepts a number representing a\nposition in the array returned by getSources().\nThis is only available in browsers that support\n<a title="MediaDevices.enumerateDevices() - Web APIs | MDN" target="_blank" href=\n"https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices"
\n
\nnavigator.mediaDevices.enumerateDevices().
\n
\n",
+ "itemtype": "method",
+ "name": "setSource",
+ "params": [
+ {
+ "name": "num",
+ "description": "
position of input source in the array
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7363,
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7379,
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7403,
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7429,
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7451,
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7473,
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7519,
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7550,
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7568,
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7905,
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 7927,
+ "class": "p5.AudioIn",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8003,
+ "description": "
In classes that extend\np5.Effect, connect effect nodes\nto the wet parameter
\n",
+ "class": "p5.Effect",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8016,
+ "description": "
Set the output volume of the filter.
\n",
+ "itemtype": "method",
+ "name": "amp",
+ "params": [
+ {
+ "name": "vol",
+ "description": "
amplitude between 0 and 1.0
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "rampTime",
+ "description": "
create a fade that lasts until rampTime
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "tFromNow",
+ "description": "
schedule this event to happen in tFromNow seconds
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Effect",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8033,
+ "description": "
Link effects together in a chain\nExample usage: filter.chain(reverb, delay, panner);\nMay be used with an open-ended number of arguments
\n",
+ "itemtype": "method",
+ "name": "chain",
+ "params": [
+ {
+ "name": "arguments",
+ "description": "
Chain together multiple sound objects
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "class": "p5.Effect",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8050,
+ "description": "
Adjust the dry/wet value.
\n",
+ "itemtype": "method",
+ "name": "drywet",
+ "params": [
+ {
+ "name": "fade",
+ "description": "
The desired drywet value (0 - 1.0)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Effect",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8062,
+ "description": "
Send output to a p5.js-sound, Web Audio Node, or use signal to\ncontrol an AudioParam
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "unit",
+ "description": "",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.Effect",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8073,
+ "description": "
Disconnect all output.
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.Effect",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8181,
+ "description": "
The p5.Filter is built with a\n\nWeb Audio BiquadFilter Node.
\n",
+ "itemtype": "property",
+ "name": "biquadFilter",
+ "type": "DelayNode",
+ "class": "p5.Filter",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8199,
+ "description": "
Filter an audio signal according to a set\nof filter parameters.
\n",
+ "itemtype": "method",
+ "name": "process",
+ "params": [
+ {
+ "name": "Signal",
+ "description": "
An object that outputs audio
\n",
+ "type": "Object"
+ },
+ {
+ "name": "freq",
+ "description": "
Frequency in Hz, from 10 to 22050
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "res",
+ "description": "
Resonance/Width of the filter frequency\n from 0.001 to 1000
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Filter",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8213,
+ "description": "
Set the frequency and the resonance of the filter.
\n",
+ "itemtype": "method",
+ "name": "set",
+ "params": [
+ {
+ "name": "freq",
+ "description": "
Frequency in Hz, from 10 to 22050
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "res",
+ "description": "
Resonance (Q) from 0.001 to 1000
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
schedule this event to happen\n seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Filter",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8230,
+ "description": "
Set the filter frequency, in Hz, from 10 to 22050 (the range of\nhuman hearing, although in reality most people hear in a narrower\nrange).
\n",
+ "itemtype": "method",
+ "name": "freq",
+ "params": [
+ {
+ "name": "freq",
+ "description": "
Filter Frequency
\n",
+ "type": "Number"
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
schedule this event to happen\n seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "value Returns the current frequency value",
+ "type": "Number"
+ },
+ "class": "p5.Filter",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8255,
+ "description": "
Controls either width of a bandpass frequency,\nor the resonance of a low/highpass cutoff frequency.
\n",
+ "itemtype": "method",
+ "name": "res",
+ "params": [
+ {
+ "name": "res",
+ "description": "
Resonance/Width of filter freq\n from 0.001 to 1000
\n",
+ "type": "Number"
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
schedule this event to happen\n seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "value Returns the current res value",
+ "type": "Number"
+ },
+ "class": "p5.Filter",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8277,
+ "description": "
Controls the gain attribute of a Biquad Filter.\nThis is distinctly different from .amp() which is inherited from p5.Effect\n.amp() controls the volume via the output gain node\np5.Filter.gain() controls the gain parameter of a Biquad Filter node.
\n",
+ "itemtype": "method",
+ "name": "gain",
+ "params": [
+ {
+ "name": "gain",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "Returns the current or updated gain value",
+ "type": "Number"
+ },
+ "class": "p5.Filter",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8298,
+ "description": "
Toggle function. Switches between the specified type and allpass
\n",
+ "itemtype": "method",
+ "name": "toggle",
+ "return": {
+ "description": "[Toggle value]",
+ "type": "Boolean"
+ },
+ "class": "p5.Filter",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8313,
+ "description": "
Set the type of a p5.Filter. Possible types include:\n"lowpass" (default), "highpass", "bandpass",\n"lowshelf", "highshelf", "peaking", "notch",\n"allpass".
\n",
+ "itemtype": "method",
+ "name": "setType",
+ "params": [
+ {
+ "name": "t",
+ "description": "",
+ "type": "String"
+ }
+ ],
+ "class": "p5.Filter",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8516,
+ "description": "
The p5.EQ is built with abstracted p5.Filter objects.\nTo modify any bands, use methods of the \np5.Filter API, especially gain and freq.\nBands are stored in an array, with indices 0 - 3, or 0 - 7
\n",
+ "itemtype": "property",
+ "name": "bands",
+ "type": "Array",
+ "class": "p5.EQ",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8551,
+ "description": "
Process an input by connecting it to the EQ
\n",
+ "itemtype": "method",
+ "name": "process",
+ "params": [
+ {
+ "name": "src",
+ "description": "
Audio source
\n",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.EQ",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8637,
+ "description": "
\nWeb Audio Spatial Panner Node
\n
Properties include
\n
\n",
+ "itemtype": "property",
+ "name": "panner",
+ "type": "AudioNode",
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8660,
+ "description": "
Connect an audio sorce
\n",
+ "itemtype": "method",
+ "name": "process",
+ "params": [
+ {
+ "name": "src",
+ "description": "
Input source
\n",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8669,
+ "description": "
Set the X,Y,Z position of the Panner
\n",
+ "itemtype": "method",
+ "name": "set",
+ "params": [
+ {
+ "name": "xVal",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "yVal",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "zVal",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "time",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "Updated x, y, z values as an array",
+ "type": "Array"
+ },
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8688,
+ "description": "
Getter and setter methods for position coordinates
\n",
+ "itemtype": "method",
+ "name": "positionX",
+ "return": {
+ "description": "updated coordinate value",
+ "type": "Number"
+ },
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8693,
+ "description": "
Getter and setter methods for position coordinates
\n",
+ "itemtype": "method",
+ "name": "positionY",
+ "return": {
+ "description": "updated coordinate value",
+ "type": "Number"
+ },
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8698,
+ "description": "
Getter and setter methods for position coordinates
\n",
+ "itemtype": "method",
+ "name": "positionZ",
+ "return": {
+ "description": "updated coordinate value",
+ "type": "Number"
+ },
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8736,
+ "description": "
Set the X,Y,Z position of the Panner
\n",
+ "itemtype": "method",
+ "name": "orient",
+ "params": [
+ {
+ "name": "xVal",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "yVal",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "zVal",
+ "description": "",
+ "type": "Number"
+ },
+ {
+ "name": "time",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "Updated x, y, z values as an array",
+ "type": "Array"
+ },
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8755,
+ "description": "
Getter and setter methods for orient coordinates
\n",
+ "itemtype": "method",
+ "name": "orientX",
+ "return": {
+ "description": "updated coordinate value",
+ "type": "Number"
+ },
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8760,
+ "description": "
Getter and setter methods for orient coordinates
\n",
+ "itemtype": "method",
+ "name": "orientY",
+ "return": {
+ "description": "updated coordinate value",
+ "type": "Number"
+ },
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8765,
+ "description": "
Getter and setter methods for orient coordinates
\n",
+ "itemtype": "method",
+ "name": "orientZ",
+ "return": {
+ "description": "updated coordinate value",
+ "type": "Number"
+ },
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8803,
+ "description": "
Set the rolloff factor and max distance
\n",
+ "itemtype": "method",
+ "name": "setFalloff",
+ "params": [
+ {
+ "name": "maxDistance",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "rolloffFactor",
+ "description": "",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8813,
+ "description": "
Maxium distance between the source and the listener
\n",
+ "itemtype": "method",
+ "name": "maxDist",
+ "params": [
+ {
+ "name": "maxDistance",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "updated value",
+ "type": "Number"
+ },
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 8825,
+ "description": "
How quickly the volume is reduced as the source moves away from the listener
\n",
+ "itemtype": "method",
+ "name": "rollof",
+ "params": [
+ {
+ "name": "rolloffFactor",
+ "description": "",
+ "type": "Number"
+ }
+ ],
+ "return": {
+ "description": "updated value",
+ "type": "Number"
+ },
+ "class": "p5.Panner3D",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9128,
+ "description": "
The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.
\n",
+ "itemtype": "property",
+ "name": "leftDelay",
+ "type": "DelayNode",
+ "class": "p5.Delay",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9136,
+ "description": "
The p5.Delay is built with two\n\nWeb Audio Delay Nodes, one for each stereo channel.
\n",
+ "itemtype": "property",
+ "name": "rightDelay",
+ "type": "DelayNode",
+ "class": "p5.Delay",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9168,
+ "description": "
Add delay to an audio signal according to a set\nof delay parameters.
\n",
+ "itemtype": "method",
+ "name": "process",
+ "params": [
+ {
+ "name": "Signal",
+ "description": "
An object that outputs audio
\n",
+ "type": "Object"
+ },
+ {
+ "name": "delayTime",
+ "description": "
Time (in seconds) of the delay/echo.\n Some browsers limit delayTime to\n 1 second.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "feedback",
+ "description": "
sends the delay back through itself\n in a loop that decreases in volume\n each time.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "lowPass",
+ "description": "
Cutoff frequency. Only frequencies\n below the lowPass will be part of the\n delay.
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Delay",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9203,
+ "description": "
Set the delay (echo) time, in seconds. Usually this value will be\na floating point number between 0.0 and 1.0.
\n",
+ "itemtype": "method",
+ "name": "delayTime",
+ "params": [
+ {
+ "name": "delayTime",
+ "description": "
Time (in seconds) of the delay
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.Delay",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9222,
+ "description": "
Feedback occurs when Delay sends its signal back through its input\nin a loop. The feedback amount determines how much signal to send each\ntime through the loop. A feedback greater than 1.0 is not desirable because\nit will increase the overall output each time through the loop,\ncreating an infinite feedback loop. The default value is 0.5
\n",
+ "itemtype": "method",
+ "name": "feedback",
+ "params": [
+ {
+ "name": "feedback",
+ "description": "
0.0 to 1.0, or an object such as an\n Oscillator that can be used to\n modulate this param
\n",
+ "type": "Number|Object"
+ }
+ ],
+ "return": {
+ "description": "Feedback value",
+ "type": "Number"
+ },
+ "class": "p5.Delay",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9250,
+ "description": "
Set a lowpass filter frequency for the delay. A lowpass filter\nwill cut off any frequencies higher than the filter frequency.
\n",
+ "itemtype": "method",
+ "name": "filter",
+ "params": [
+ {
+ "name": "cutoffFreq",
+ "description": "
A lowpass filter will cut off any\n frequencies higher than the filter frequency.
\n",
+ "type": "Number|Object"
+ },
+ {
+ "name": "res",
+ "description": "
Resonance of the filter frequency\n cutoff, or an object (i.e. a p5.Oscillator)\n that can be used to modulate this parameter.\n High numbers (i.e. 15) will produce a resonance,\n low numbers (i.e. .2) will produce a slope.
\n",
+ "type": "Number|Object"
+ }
+ ],
+ "class": "p5.Delay",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9267,
+ "description": "
Choose a preset type of delay. 'pingPong' bounces the signal\nfrom the left to the right channel to produce a stereo effect.\nAny other parameter will revert to the default delay setting.
\n",
+ "itemtype": "method",
+ "name": "setType",
+ "params": [
+ {
+ "name": "type",
+ "description": "
'pingPong' (1) or 'default' (0)
\n",
+ "type": "String|Number"
+ }
+ ],
+ "class": "p5.Delay",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9300,
+ "description": "
Set the output level of the delay effect.
\n",
+ "itemtype": "method",
+ "name": "amp",
+ "params": [
+ {
+ "name": "volume",
+ "description": "
amplitude between 0 and 1.0
\n",
+ "type": "Number"
+ },
+ {
+ "name": "rampTime",
+ "description": "
create a fade that lasts rampTime
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
schedule this event to happen\n seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Delay",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9309,
+ "description": "
Send output to a p5.sound or web audio object
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "unit",
+ "description": "",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.Delay",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9315,
+ "description": "
Disconnect all output.
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.Delay",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9394,
+ "description": "
Connect a source to the reverb, and assign reverb parameters.
\n",
+ "itemtype": "method",
+ "name": "process",
+ "params": [
+ {
+ "name": "src",
+ "description": "
p5.sound / Web Audio object with a sound\n output.
\n",
+ "type": "Object"
+ },
+ {
+ "name": "seconds",
+ "description": "
Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "decayRate",
+ "description": "
Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "reverse",
+ "description": "
Play the reverb backwards or forwards.
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "class": "p5.Reverb",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9423,
+ "description": "
Set the reverb settings. Similar to .process(), but without\nassigning a new input.
\n",
+ "itemtype": "method",
+ "name": "set",
+ "params": [
+ {
+ "name": "seconds",
+ "description": "
Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "decayRate",
+ "description": "
Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "reverse",
+ "description": "
Play the reverb backwards or forwards.
\n",
+ "type": "Boolean",
+ "optional": true
+ }
+ ],
+ "class": "p5.Reverb",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9451,
+ "description": "
Set the output level of the reverb effect.
\n",
+ "itemtype": "method",
+ "name": "amp",
+ "params": [
+ {
+ "name": "volume",
+ "description": "
amplitude between 0 and 1.0
\n",
+ "type": "Number"
+ },
+ {
+ "name": "rampTime",
+ "description": "
create a fade that lasts rampTime
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
schedule this event to happen\n seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Reverb",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9460,
+ "description": "
Send output to a p5.sound or web audio object
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "unit",
+ "description": "",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.Reverb",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9466,
+ "description": "
Disconnect all output.
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.Reverb",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9560,
+ "description": "
Internally, the p5.Convolver uses the a\n\nWeb Audio Convolver Node.
\n",
+ "itemtype": "property",
+ "name": "convolverNod",
+ "type": "ConvolverNode",
+ "class": "p5.Convolver",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9585,
+ "description": "
Create a p5.Convolver. Accepts a path to a soundfile\nthat will be used to generate an impulse response.
\n",
+ "itemtype": "method",
+ "name": "createConvolver",
+ "params": [
+ {
+ "name": "path",
+ "description": "
path to a sound file
\n",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "
function to call if loading is successful.\n The object will be passed in as the argument\n to the callback function.
\n",
+ "type": "Function",
+ "optional": true
+ },
+ {
+ "name": "errorCallback",
+ "description": "
function to call if loading is not successful.\n A custom error will be passed in as the argument\n to the callback function.
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "",
+ "type": "p5.Convolver"
+ },
+ "example": [
+ "\n
\nvar cVerb, sound;\nfunction preload() {\n // We have both MP3 and OGG versions of all sound assets\n soundFormats('ogg', 'mp3');\n\n // Try replacing 'bx-spring' with other soundfiles like\n // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'\n cVerb = createConvolver('assets/bx-spring.mp3');\n\n // Try replacing 'Damscray_DancingTiger' with\n // 'beat', 'doorbell', lucky_dragons'\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\n
"
+ ],
+ "class": "p5.Convolver",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9701,
+ "description": "
Connect a source to the reverb, and assign reverb parameters.
\n",
+ "itemtype": "method",
+ "name": "process",
+ "params": [
+ {
+ "name": "src",
+ "description": "
p5.sound / Web Audio object with a sound\n output.
\n",
+ "type": "Object"
+ }
+ ],
+ "example": [
+ "\n
\nvar cVerb, sound;\nfunction preload() {\n soundFormats('ogg', 'mp3');\n\n cVerb = createConvolver('assets/concrete-tunnel.mp3');\n\n sound = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with (i.e. connect to) cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\n
"
+ ],
+ "class": "p5.Convolver",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9733,
+ "description": "
If you load multiple impulse files using the .addImpulse method,\nthey will be stored as Objects in this Array. Toggle between them\nwith the toggleImpulse(id) method.
\n",
+ "itemtype": "property",
+ "name": "impulses",
+ "type": "Array",
+ "class": "p5.Convolver",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9741,
+ "description": "
Load and assign a new Impulse Response to the p5.Convolver.\nThe impulse is added to the .impulses array. Previous\nimpulses can be accessed with the .toggleImpulse(id)\nmethod.
\n",
+ "itemtype": "method",
+ "name": "addImpulse",
+ "params": [
+ {
+ "name": "path",
+ "description": "
path to a sound file
\n",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "
function (optional)
\n",
+ "type": "Function"
+ },
+ {
+ "name": "errorCallback",
+ "description": "
function (optional)
\n",
+ "type": "Function"
+ }
+ ],
+ "class": "p5.Convolver",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9759,
+ "description": "
Similar to .addImpulse, except that the .impulses\nArray is reset to save memory. A new .impulses\narray is created with this impulse as the only item.
\n",
+ "itemtype": "method",
+ "name": "resetImpulse",
+ "params": [
+ {
+ "name": "path",
+ "description": "
path to a sound file
\n",
+ "type": "String"
+ },
+ {
+ "name": "callback",
+ "description": "
function (optional)
\n",
+ "type": "Function"
+ },
+ {
+ "name": "errorCallback",
+ "description": "
function (optional)
\n",
+ "type": "Function"
+ }
+ ],
+ "class": "p5.Convolver",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9777,
+ "description": "
If you have used .addImpulse() to add multiple impulses\nto a p5.Convolver, then you can use this method to toggle between\nthe items in the .impulses Array. Accepts a parameter\nto identify which impulse you wish to use, identified either by its\noriginal filename (String) or by its position in the .impulses\n Array (Number).
\nYou can access the objects in the .impulses Array directly. Each\nObject has two attributes: an .audioBuffer (type:\nWeb Audio \nAudioBuffer) and a .name, a String that corresponds\nwith the original filename.
\n",
+ "itemtype": "method",
+ "name": "toggleImpulse",
+ "params": [
+ {
+ "name": "id",
+ "description": "
Identify the impulse by its original filename\n (String), or by its position in the\n .impulses Array (Number).
\n",
+ "type": "String|Number"
+ }
+ ],
+ "class": "p5.Convolver",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9821,
+ "class": "p5.Convolver",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 9846,
+ "class": "p5.Convolver",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10041,
+ "description": "
Set the global tempo, in beats per minute, for all\np5.Parts. This method will impact all active p5.Parts.
\n",
+ "itemtype": "method",
+ "name": "setBPM",
+ "params": [
+ {
+ "name": "BPM",
+ "description": "
Beats Per Minute
\n",
+ "type": "Number"
+ },
+ {
+ "name": "rampTime",
+ "description": "
Seconds from now
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.Convolver",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10131,
+ "description": "
Array of values to pass into the callback\nat each step of the phrase. Depending on the callback\nfunction's requirements, these values may be numbers,\nstrings, or an object with multiple parameters.\nZero (0) indicates a rest.
\n",
+ "itemtype": "property",
+ "name": "sequence",
+ "type": "Array",
+ "class": "p5.Phrase",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10219,
+ "description": "
Set the tempo of this part, in Beats Per Minute.
\n",
+ "itemtype": "method",
+ "name": "setBPM",
+ "params": [
+ {
+ "name": "BPM",
+ "description": "
Beats Per Minute
\n",
+ "type": "Number"
+ },
+ {
+ "name": "rampTime",
+ "description": "
Seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10229,
+ "description": "
Returns the Beats Per Minute of this currently part.
\n",
+ "itemtype": "method",
+ "name": "getBPM",
+ "return": {
+ "description": "",
+ "type": "Number"
+ },
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10238,
+ "description": "
Start playback of this part. It will play\nthrough all of its phrases at a speed\ndetermined by setBPM.
\n",
+ "itemtype": "method",
+ "name": "start",
+ "params": [
+ {
+ "name": "time",
+ "description": "
seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10254,
+ "description": "
Loop playback of this part. It will begin\nlooping through all of its phrases at a speed\ndetermined by setBPM.
\n",
+ "itemtype": "method",
+ "name": "loop",
+ "params": [
+ {
+ "name": "time",
+ "description": "
seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10271,
+ "description": "
Tell the part to stop looping.
\n",
+ "itemtype": "method",
+ "name": "noLoop",
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10283,
+ "description": "
Stop the part and cue it to step 0.
\n",
+ "itemtype": "method",
+ "name": "stop",
+ "params": [
+ {
+ "name": "time",
+ "description": "
seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10293,
+ "description": "
Pause the part. Playback will resume\nfrom the current step.
\n",
+ "itemtype": "method",
+ "name": "pause",
+ "params": [
+ {
+ "name": "time",
+ "description": "
seconds from now
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10305,
+ "description": "
Add a p5.Phrase to this Part.
\n",
+ "itemtype": "method",
+ "name": "addPhrase",
+ "params": [
+ {
+ "name": "phrase",
+ "description": "
reference to a p5.Phrase
\n",
+ "type": "p5.Phrase"
+ }
+ ],
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10326,
+ "description": "
Remove a phrase from this part, based on the name it was\ngiven when it was created.
\n",
+ "itemtype": "method",
+ "name": "removePhrase",
+ "params": [
+ {
+ "name": "phraseName",
+ "description": "",
+ "type": "String"
+ }
+ ],
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10340,
+ "description": "
Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.
\n",
+ "itemtype": "method",
+ "name": "getPhrase",
+ "params": [
+ {
+ "name": "phraseName",
+ "description": "",
+ "type": "String"
+ }
+ ],
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10354,
+ "description": "
Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.
\n",
+ "itemtype": "method",
+ "name": "replaceSequence",
+ "params": [
+ {
+ "name": "phraseName",
+ "description": "",
+ "type": "String"
+ },
+ {
+ "name": "sequence",
+ "description": "
Array of values to pass into the callback\n at each step of the phrase.
\n",
+ "type": "Array"
+ }
+ ],
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10382,
+ "description": "
Fire a callback function at every step.
\n",
+ "itemtype": "method",
+ "name": "onStep",
+ "params": [
+ {
+ "name": "callback",
+ "description": "
The name of the callback\n you want to fire\n on every beat/tatum.
\n",
+ "type": "Function"
+ }
+ ],
+ "class": "p5.Part",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10435,
+ "description": "
Start playback of the score.
\n",
+ "itemtype": "method",
+ "name": "start",
+ "class": "p5.Score",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10444,
+ "description": "
Stop playback of the score.
\n",
+ "itemtype": "method",
+ "name": "stop",
+ "class": "p5.Score",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10454,
+ "description": "
Pause playback of the score.
\n",
+ "itemtype": "method",
+ "name": "pause",
+ "class": "p5.Score",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10462,
+ "description": "
Loop playback of the score.
\n",
+ "itemtype": "method",
+ "name": "loop",
+ "class": "p5.Score",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10471,
+ "description": "
Stop looping playback of the score. If it\nis currently playing, this will go into effect\nafter the current round of playback completes.
\n",
+ "itemtype": "method",
+ "name": "noLoop",
+ "class": "p5.Score",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10496,
+ "description": "
Set the tempo for all parts in the score
\n",
+ "itemtype": "method",
+ "name": "setBPM",
+ "params": [
+ {
+ "name": "BPM",
+ "description": "
Beats Per Minute
\n",
+ "type": "Number"
+ },
+ {
+ "name": "rampTime",
+ "description": "
Seconds from now
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.Score",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10564,
+ "description": "
musicalTimeMode uses Tone.Time convention\ntrue if string, false if number
\n",
+ "itemtype": "property",
+ "name": "musicalTimeMode",
+ "type": "Boolean",
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10571,
+ "description": "
musicalTimeMode variables\nmodify these only when the interval is specified in musicalTime format as a string
\n",
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10578,
+ "description": "
Set a limit to the number of loops to play. defaults to Infinity
\n",
+ "itemtype": "property",
+ "name": "maxIterations",
+ "type": "Number",
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10587,
+ "description": "
Do not initiate the callback if timeFromNow is < 0\nThis ususually occurs for a few milliseconds when the page\nis not fully loaded
\n
The callback should only be called until maxIterations is reached
\n",
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10601,
+ "description": "
Start the loop
\n",
+ "itemtype": "method",
+ "name": "start",
+ "params": [
+ {
+ "name": "timeFromNow",
+ "description": "
schedule a starting time
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10614,
+ "description": "
Stop the loop
\n",
+ "itemtype": "method",
+ "name": "stop",
+ "params": [
+ {
+ "name": "timeFromNow",
+ "description": "
schedule a stopping time
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10627,
+ "description": "
Pause the loop
\n",
+ "itemtype": "method",
+ "name": "pause",
+ "params": [
+ {
+ "name": "timeFromNow",
+ "description": "
schedule a pausing time
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10639,
+ "description": "
Synchronize loops. Use this method to start two more more loops in synchronization\nor to start a loop in synchronization with a loop that is already playing\nThis method will schedule the implicit loop in sync with the explicit master loop\ni.e. loopToStart.syncedStart(loopToSyncWith)
\n",
+ "itemtype": "method",
+ "name": "syncedStart",
+ "params": [
+ {
+ "name": "otherLoop",
+ "description": "
a p5.SoundLoop to sync with
\n",
+ "type": "Object"
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
Start the loops in sync after timeFromNow seconds
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10720,
+ "description": "
Getters and Setters, setting any paramter will result in a change in the clock's\nfrequency, that will be reflected after the next callback\nbeats per minute (defaults to 60)
\n",
+ "itemtype": "property",
+ "name": "bpm",
+ "type": "Number",
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10738,
+ "description": "
number of quarter notes in a measure (defaults to 4)
\n",
+ "itemtype": "property",
+ "name": "timeSignature",
+ "type": "Number",
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10754,
+ "description": "
length of the loops interval
\n",
+ "itemtype": "property",
+ "name": "interval",
+ "type": "Number|String",
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10768,
+ "description": "
how many times the callback has been called so far
\n",
+ "itemtype": "property",
+ "name": "iterations",
+ "type": "Number",
+ "readonly": "",
+ "class": "p5.SoundLoop",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10809,
+ "description": "
The p5.Compressor is built with a Web Audio Dynamics Compressor Node\n
\n",
+ "itemtype": "property",
+ "name": "compressor",
+ "type": "AudioNode",
+ "class": "p5.Compressor",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10820,
+ "description": "
Performs the same function as .connect, but also accepts\noptional parameters to set compressor's audioParams
\n",
+ "itemtype": "method",
+ "name": "process",
+ "params": [
+ {
+ "name": "src",
+ "description": "
Sound source to be connected
\n",
+ "type": "Object"
+ },
+ {
+ "name": "attack",
+ "description": "
The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "knee",
+ "description": "
A decibel value representing the range above the\n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "ratio",
+ "description": "
The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "threshold",
+ "description": "
The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "release",
+ "description": "
The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Compressor",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10843,
+ "description": "
Set the paramters of a compressor.
\n",
+ "itemtype": "method",
+ "name": "set",
+ "params": [
+ {
+ "name": "attack",
+ "description": "
The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1
\n",
+ "type": "Number"
+ },
+ {
+ "name": "knee",
+ "description": "
A decibel value representing the range above the\n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40
\n",
+ "type": "Number"
+ },
+ {
+ "name": "ratio",
+ "description": "
The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20
\n",
+ "type": "Number"
+ },
+ {
+ "name": "threshold",
+ "description": "
The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0
\n",
+ "type": "Number"
+ },
+ {
+ "name": "release",
+ "description": "
The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1
\n",
+ "type": "Number"
+ }
+ ],
+ "class": "p5.Compressor",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10875,
+ "description": "
Get current attack or set value w/ time ramp
\n",
+ "itemtype": "method",
+ "name": "attack",
+ "params": [
+ {
+ "name": "attack",
+ "description": "
Attack is the amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "time",
+ "description": "
Assign time value to schedule the change in value
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Compressor",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10895,
+ "description": "
Get current knee or set value w/ time ramp
\n",
+ "itemtype": "method",
+ "name": "knee",
+ "params": [
+ {
+ "name": "knee",
+ "description": "
A decibel value representing the range above the\n threshold where the curve smoothly transitions to the "ratio" portion.\n default = 30, range 0 - 40
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "time",
+ "description": "
Assign time value to schedule the change in value
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Compressor",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10915,
+ "description": "
Get current ratio or set value w/ time ramp
\n",
+ "itemtype": "method",
+ "name": "ratio",
+ "params": [
+ {
+ "name": "ratio",
+ "description": "
The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "time",
+ "description": "
Assign time value to schedule the change in value
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Compressor",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10934,
+ "description": "
Get current threshold or set value w/ time ramp
\n",
+ "itemtype": "method",
+ "name": "threshold",
+ "params": [
+ {
+ "name": "threshold",
+ "description": "
The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0
\n",
+ "type": "Number"
+ },
+ {
+ "name": "time",
+ "description": "
Assign time value to schedule the change in value
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Compressor",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10953,
+ "description": "
Get current release or set value w/ time ramp
\n",
+ "itemtype": "method",
+ "name": "release",
+ "params": [
+ {
+ "name": "release",
+ "description": "
The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1
\n",
+ "type": "Number"
+ },
+ {
+ "name": "time",
+ "description": "
Assign time value to schedule the change in value
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Compressor",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 10973,
+ "description": "
Return the current reduction value
\n",
+ "itemtype": "method",
+ "name": "reduction",
+ "return": {
+ "description": "Value of the amount of gain reduction that is applied to the signal",
+ "type": "Number"
+ },
+ "class": "p5.Compressor",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11085,
+ "description": "
Connect a specific device to the p5.SoundRecorder.\nIf no parameter is given, p5.SoundRecorer will record\nall audible p5.sound from your sketch.
\n",
+ "itemtype": "method",
+ "name": "setInput",
+ "params": [
+ {
+ "name": "unit",
+ "description": "
p5.sound object or a web audio unit\n that outputs sound
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "class": "p5.SoundRecorder",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11106,
+ "description": "
Start recording. To access the recording, provide\na p5.SoundFile as the first parameter. The p5.SoundRecorder\nwill send its recording to that p5.SoundFile for playback once\nrecording is complete. Optional parameters include duration\n(in seconds) of the recording, and a callback function that\nwill be called once the complete recording has been\ntransfered to the p5.SoundFile.
\n",
+ "itemtype": "method",
+ "name": "record",
+ "params": [
+ {
+ "name": "soundFile",
+ "description": "
p5.SoundFile
\n",
+ "type": "p5.SoundFile"
+ },
+ {
+ "name": "duration",
+ "description": "
Time (in seconds)
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "callback",
+ "description": "
The name of a function that will be\n called once the recording completes
\n",
+ "type": "Function",
+ "optional": true
+ }
+ ],
+ "class": "p5.SoundRecorder",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11139,
+ "description": "
Stop the recording. Once the recording is stopped,\nthe results will be sent to the p5.SoundFile that\nwas given on .record(), and if a callback function\nwas provided on record, that function will be called.
\n",
+ "itemtype": "method",
+ "name": "stop",
+ "class": "p5.SoundRecorder",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11212,
+ "description": "
Save a p5.SoundFile as a .wav audio file.
\n",
+ "itemtype": "method",
+ "name": "saveSound",
+ "params": [
+ {
+ "name": "soundFile",
+ "description": "
p5.SoundFile that you wish to save
\n",
+ "type": "p5.SoundFile"
+ },
+ {
+ "name": "name",
+ "description": "
name of the resulting .wav file.
\n",
+ "type": "String"
+ }
+ ],
+ "class": "p5.SoundRecorder",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11388,
+ "description": "
isDetected is set to true when a peak is detected.
\n",
+ "itemtype": "attribute",
+ "name": "isDetected",
+ "type": "Boolean",
+ "default": "false",
+ "class": "p5.PeakDetect",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11401,
+ "description": "
The update method is run in the draw loop.
\n
Accepts an FFT object. You must call .analyze()\non the FFT object prior to updating the peakDetect\nbecause it relies on a completed FFT analysis.
\n",
+ "itemtype": "method",
+ "name": "update",
+ "params": [
+ {
+ "name": "fftObject",
+ "description": "
A p5.FFT object
\n",
+ "type": "p5.FFT"
+ }
+ ],
+ "class": "p5.PeakDetect",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11432,
+ "description": "
onPeak accepts two arguments: a function to call when\na peak is detected. The value of the peak,\nbetween 0.0 and 1.0, is passed to the callback.
\n",
+ "itemtype": "method",
+ "name": "onPeak",
+ "params": [
+ {
+ "name": "callback",
+ "description": "
Name of a function that will\n be called when a peak is\n detected.
\n",
+ "type": "Function"
+ },
+ {
+ "name": "val",
+ "description": "
Optional value to pass\n into the function when\n a peak is detected.
\n",
+ "type": "Object",
+ "optional": true
+ }
+ ],
+ "example": [
+ "\n
\nvar cnv, soundFile, fft, peakDetect;\nvar ellipseWidth = 0;\n\nfunction setup() {\n cnv = createCanvas(100,100);\n textAlign(CENTER);\n\n soundFile = loadSound('assets/beat.mp3');\n fft = new p5.FFT();\n peakDetect = new p5.PeakDetect();\n\n setupSound();\n\n // when a beat is detected, call triggerBeat()\n peakDetect.onPeak(triggerBeat);\n}\n\nfunction draw() {\n background(0);\n fill(255);\n text('click to play', width/2, height/2);\n\n fft.analyze();\n peakDetect.update(fft);\n\n ellipseWidth *= 0.95;\n ellipse(width/2, height/2, ellipseWidth, ellipseWidth);\n}\n\n// this function is called by peakDetect.onPeak\nfunction triggerBeat() {\n ellipseWidth = 50;\n}\n\n// mouseclick starts/stops sound\nfunction setupSound() {\n cnv.mouseClicked( function() {\n if (soundFile.isPlaying() ) {\n soundFile.stop();\n } else {\n soundFile.play();\n }\n });\n}\n
"
+ ],
+ "class": "p5.PeakDetect",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11578,
+ "description": "
Connect a source to the gain node.
\n",
+ "itemtype": "method",
+ "name": "setInput",
+ "params": [
+ {
+ "name": "src",
+ "description": "
p5.sound / Web Audio object with a sound\n output.
\n",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.Gain",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11588,
+ "description": "
Send output to a p5.sound or web audio object
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "unit",
+ "description": "",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.Gain",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11598,
+ "description": "
Disconnect all output.
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.Gain",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11606,
+ "description": "
Set the output level of the gain node.
\n",
+ "itemtype": "method",
+ "name": "amp",
+ "params": [
+ {
+ "name": "volume",
+ "description": "
amplitude between 0 and 1.0
\n",
+ "type": "Number"
+ },
+ {
+ "name": "rampTime",
+ "description": "
create a fade that lasts rampTime
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "timeFromNow",
+ "description": "
schedule this event to happen\n seconds from now
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.Gain",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11684,
+ "description": "
Connect to p5 objects or Web Audio Nodes
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "unit",
+ "description": "",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.AudioVoice",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11693,
+ "description": "
Disconnect from soundOut
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.AudioVoice",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11761,
+ "description": "
Play tells the MonoSynth to start playing a note. This method schedules\nthe calling of .triggerAttack and .triggerRelease.
\n",
+ "itemtype": "method",
+ "name": "play",
+ "params": [
+ {
+ "name": "note",
+ "description": "
the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format ("C4", "Eb3"...etc")\n See \n Tone. Defaults to 440 hz.
\n",
+ "type": "String | Number"
+ },
+ {
+ "name": "velocity",
+ "description": "
velocity of the note to play (ranging from 0 to 1)
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "secondsFromNow",
+ "description": "
time from now (in seconds) at which to play
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "sustainTime",
+ "description": "
time to sustain before releasing the envelope
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11783,
+ "description": "
Trigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.
\n",
+ "params": [
+ {
+ "name": "note",
+ "description": "
the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format ("C4", "Eb3"...etc")\n See \n Tone. Defaults to 440 hz
\n",
+ "type": "String | Number"
+ },
+ {
+ "name": "velocity",
+ "description": "
velocity of the note to play (ranging from 0 to 1)
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "secondsFromNow",
+ "description": "
time from now (in seconds) at which to play
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "itemtype": "method",
+ "name": "triggerAttack",
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11806,
+ "description": "
Trigger the release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n",
+ "params": [
+ {
+ "name": "secondsFromNow",
+ "description": "
time to trigger the release
\n",
+ "type": "Number"
+ }
+ ],
+ "itemtype": "method",
+ "name": "triggerRelease",
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11819,
+ "description": "
Set values like a traditional\n\nADSR envelope\n.
\n",
+ "itemtype": "method",
+ "name": "setADSR",
+ "params": [
+ {
+ "name": "attackTime",
+ "description": "
Time (in seconds before envelope\n reaches Attack Level
\n",
+ "type": "Number"
+ },
+ {
+ "name": "decayTime",
+ "description": "
Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "susRatio",
+ "description": "
Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "releaseTime",
+ "description": "
Time in seconds from now (defaults to 0)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11843,
+ "description": "
Getters and Setters
\n",
+ "itemtype": "property",
+ "name": "attack",
+ "type": "Number",
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11847,
+ "itemtype": "property",
+ "name": "decay",
+ "type": "Number",
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11850,
+ "itemtype": "property",
+ "name": "sustain",
+ "type": "Number",
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11853,
+ "itemtype": "property",
+ "name": "release",
+ "type": "Number",
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11890,
+ "description": "
MonoSynth amp
\n",
+ "itemtype": "method",
+ "name": "amp",
+ "params": [
+ {
+ "name": "vol",
+ "description": "
desired volume
\n",
+ "type": "Number"
+ },
+ {
+ "name": "rampTime",
+ "description": "
Time to reach new volume
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "return": {
+ "description": "new volume value",
+ "type": "Number"
+ },
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11904,
+ "description": "
Connect to a p5.sound / Web Audio object.
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "unit",
+ "description": "
A p5.sound or Web Audio object
\n",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11914,
+ "description": "
Disconnect all outputs
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11922,
+ "description": "
Get rid of the MonoSynth and free up its resources / memory.
\n",
+ "itemtype": "method",
+ "name": "dispose",
+ "class": "p5.MonoSynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11974,
+ "description": "
An object that holds information about which notes have been played and\nwhich notes are currently being played. New notes are added as keys\non the fly. While a note has been attacked, but not released, the value of the\nkey is the audiovoice which is generating that note. When notes are released,\nthe value of the key becomes undefined.
\n",
+ "itemtype": "property",
+ "name": "notes",
+ "class": "p5.PolySynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11986,
+ "description": "
A PolySynth must have at least 1 voice, defaults to 8
\n",
+ "itemtype": "property",
+ "name": "polyvalue",
+ "class": "p5.PolySynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 11991,
+ "description": "
Monosynth that generates the sound for each note that is triggered. The\np5.PolySynth defaults to using the p5.MonoSynth as its voice.
\n",
+ "itemtype": "property",
+ "name": "AudioVoice",
+ "class": "p5.PolySynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12022,
+ "description": "
Play a note by triggering noteAttack and noteRelease with sustain time
\n",
+ "itemtype": "method",
+ "name": "play",
+ "params": [
+ {
+ "name": "note",
+ "description": "
midi note to play (ranging from 0 to 127 - 60 being a middle C)
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "velocity",
+ "description": "
velocity of the note to play (ranging from 0 to 1)
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "secondsFromNow",
+ "description": "
time from now (in seconds) at which to play
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "sustainTime",
+ "description": "
time to sustain before releasing the envelope
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.PolySynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12036,
+ "description": "
noteADSR sets the envelope for a specific note that has just been triggered.\nUsing this method modifies the envelope of whichever audiovoice is being used\nto play the desired note. The envelope should be reset before noteRelease is called\nin order to prevent the modified envelope from being used on other notes.
\n",
+ "itemtype": "method",
+ "name": "noteADSR",
+ "params": [
+ {
+ "name": "note",
+ "description": "
Midi note on which ADSR should be set.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "attackTime",
+ "description": "
Time (in seconds before envelope\n reaches Attack Level
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "decayTime",
+ "description": "
Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "susRatio",
+ "description": "
Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "releaseTime",
+ "description": "
Time in seconds from now (defaults to 0)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.PolySynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12064,
+ "description": "
Set the PolySynths global envelope. This method modifies the envelopes of each\nmonosynth so that all notes are played with this envelope.
\n",
+ "itemtype": "method",
+ "name": "setADSR",
+ "params": [
+ {
+ "name": "note",
+ "description": "
Midi note on which ADSR should be set.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "attackTime",
+ "description": "
Time (in seconds before envelope\n reaches Attack Level
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "decayTime",
+ "description": "
Time (in seconds) before envelope\n reaches Decay/Sustain Level
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "susRatio",
+ "description": "
Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using setRange),\n then decayLevel would increase proportionally, to become 0.5.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "releaseTime",
+ "description": "
Time in seconds from now (defaults to 0)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.PolySynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12089,
+ "description": "
Trigger the Attack, and Decay portion of a MonoSynth.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.
\n",
+ "itemtype": "method",
+ "name": "noteAttack",
+ "params": [
+ {
+ "name": "note",
+ "description": "
midi note on which attack should be triggered.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "velocity",
+ "description": "
velocity of the note to play (ranging from 0 to 1)/
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "secondsFromNow",
+ "description": "
time from now (in seconds)
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.PolySynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12162,
+ "description": "
Trigger the Release of an AudioVoice note. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.
\n",
+ "itemtype": "method",
+ "name": "noteRelease",
+ "params": [
+ {
+ "name": "note",
+ "description": "
midi note on which attack should be triggered.
\n",
+ "type": "Number",
+ "optional": true
+ },
+ {
+ "name": "secondsFromNow",
+ "description": "
time to trigger the release
\n",
+ "type": "Number",
+ "optional": true
+ }
+ ],
+ "class": "p5.PolySynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12192,
+ "description": "
Connect to a p5.sound / Web Audio object.
\n",
+ "itemtype": "method",
+ "name": "connect",
+ "params": [
+ {
+ "name": "unit",
+ "description": "
A p5.sound or Web Audio object
\n",
+ "type": "Object"
+ }
+ ],
+ "class": "p5.PolySynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12202,
+ "description": "
Disconnect all outputs
\n",
+ "itemtype": "method",
+ "name": "disconnect",
+ "class": "p5.PolySynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12210,
+ "description": "
Get rid of the MonoSynth and free up its resources / memory.
\n",
+ "itemtype": "method",
+ "name": "dispose",
+ "class": "p5.PolySynth",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12276,
+ "description": "
The p5.Distortion is built with a\n\nWeb Audio WaveShaper Node.
\n",
+ "itemtype": "property",
+ "name": "WaveShaperNode",
+ "type": "AudioNode",
+ "class": "p5.Distortion",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12291,
+ "description": "
Process a sound source, optionally specify amount and oversample values.
\n",
+ "itemtype": "method",
+ "name": "process",
+ "params": [
+ {
+ "name": "amount",
+ "description": "
Unbounded distortion amount.\n Normal values range from 0-1.
\n",
+ "type": "Number",
+ "optional": true,
+ "optdefault": "0.25"
+ },
+ {
+ "name": "oversample",
+ "description": "
'none', '2x', or '4x'.
\n",
+ "type": "String",
+ "optional": true,
+ "optdefault": "'none'"
+ }
+ ],
+ "class": "p5.Distortion",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12303,
+ "description": "
Set the amount and oversample of the waveshaper distortion.
\n",
+ "itemtype": "method",
+ "name": "set",
+ "params": [
+ {
+ "name": "amount",
+ "description": "
Unbounded distortion amount.\n Normal values range from 0-1.
\n",
+ "type": "Number",
+ "optional": true,
+ "optdefault": "0.25"
+ },
+ {
+ "name": "oversample",
+ "description": "
'none', '2x', or '4x'.
\n",
+ "type": "String",
+ "optional": true,
+ "optdefault": "'none'"
+ }
+ ],
+ "class": "p5.Distortion",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12321,
+ "description": "
Return the distortion amount, typically between 0-1.
\n",
+ "itemtype": "method",
+ "name": "getAmount",
+ "return": {
+ "description": "Unbounded distortion amount.\n Normal values range from 0-1.",
+ "type": "Number"
+ },
+ "class": "p5.Distortion",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ },
+ {
+ "file": "lib/addons/p5.sound.js",
+ "line": 12331,
+ "description": "
Return the oversampling.
\n",
+ "itemtype": "method",
+ "name": "getOversample",
+ "return": {
+ "description": "Oversample can either be 'none', '2x', or '4x'.",
+ "type": "String"
+ },
+ "class": "p5.Distortion",
+ "module": "p5.sound",
+ "submodule": "p5.sound"
+ }
+ ],
+ "warnings": [
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/creating_reading.js:16"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/creating_reading.js:61"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/creating_reading.js:91"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/creating_reading.js:121"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/creating_reading.js:319"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/creating_reading.js:350"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/creating_reading.js:387"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/creating_reading.js:484"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/creating_reading.js:514"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/creating_reading.js:554"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/p5.Color.js:52"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/p5.Color.js:247"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/p5.Color.js:274"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/p5.Color.js:301"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/p5.Color.js:328"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/p5.Color.js:759"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/setting.js:15"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/setting.js:185"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/setting.js:223"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/setting.js:344"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/setting.js:501"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/setting.js:542"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/color/setting.js:582"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/2d_primitives.js:16"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/2d_primitives.js:133"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/2d_primitives.js:188"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/2d_primitives.js:244"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/2d_primitives.js:279"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/2d_primitives.js:333"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/2d_primitives.js:416"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/attributes.js:14"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/attributes.js:83"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/attributes.js:111"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/attributes.js:180"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/attributes.js:209"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/attributes.js:246"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/attributes.js:313"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/constants.js:34"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/constants.js:53"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/constants.js:72"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/constants.js:91"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/constants.js:110"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/core.js:49"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/core.js:90"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/core.js:121"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/core.js:407"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/curves.js:13"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/curves.js:92"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/curves.js:135"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/curves.js:190"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/curves.js:269"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/curves.js:360"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/curves.js:402"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/curves.js:497"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:22"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:49"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:77"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:109"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:170"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:268"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:293"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:310"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:327"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:343"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:359"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:437"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " src/core/environment.js:488"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:488"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " src/core/environment.js:534"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:534"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:591"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:622"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/environment.js:645"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:51"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:116"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:153"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:188"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:238"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:287"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:353"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:406"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:460"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:519"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:562"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:629"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:664"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:706"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:755"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:796"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:846"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:884"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Element.js:922"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/p5.Graphics.js:65"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/rendering.js:17"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/rendering.js:119"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/rendering.js:172"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/rendering.js:195"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/rendering.js:234"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/structure.js:15"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/structure.js:77"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/structure.js:132"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/structure.js:197"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/structure.js:271"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/transform.js:13"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/transform.js:135"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/transform.js:161"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/transform.js:201"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/transform.js:231"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/transform.js:261"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/transform.js:291"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/transform.js:366"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/transform.js:405"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/transform.js:444"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/vertex.js:22"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/vertex.js:70"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/vertex.js:270"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/vertex.js:356"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/vertex.js:407"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/vertex.js:467"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/vertex.js:553"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/vertex.js:645"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/vertex.js:645"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/vertex.js:645"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/core/vertex.js:645"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/acceleration.js:91"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/acceleration.js:125"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/acceleration.js:158"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/acceleration.js:194"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/acceleration.js:239"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/acceleration.js:283"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/acceleration.js:374"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/acceleration.js:405"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/acceleration.js:464"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/keyboard.js:18"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/keyboard.js:45"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/keyboard.js:74"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/keyboard.js:107"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/keyboard.js:198"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/keyboard.js:254"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/keyboard.js:318"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:22"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:48"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:74"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:105"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:135"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:172"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:209"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:249"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:290"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:329"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:418"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:462"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:532"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:598"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:665"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:724"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/mouse.js:782"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/touch.js:57"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/touch.js:120"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/events/touch.js:182"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/image.js:18"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/image.js:98"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/image.js:193"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/loading_displaying.js:17"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " src/image/loading_displaying.js:108"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/loading_displaying.js:125"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/loading_displaying.js:296"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/loading_displaying.js:396"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/loading_displaying.js:462"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:90"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:117"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:151"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:230"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:266"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:314"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:359"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:397"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:481"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:561"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:624"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:660"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/p5.Image.js:782"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/pixels.js:14"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/pixels.js:83"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/pixels.js:177"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/pixels.js:236"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/pixels.js:415"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/pixels.js:491"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/pixels.js:528"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/image/pixels.js:602"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/files.js:19"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/files.js:170"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/files.js:271"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/files.js:603"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " src/io/files.js:704"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/files.js:704"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/files.js:1457"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/files.js:1509"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/files.js:1571"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:56"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:119"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:167"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:213"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:262"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:327"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:522"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:575"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:617"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:878"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:944"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:994"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:1040"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:1085"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:1132"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:1177"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:1230"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.Table.js:1294"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.TableRow.js:42"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.TableRow.js:104"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.TableRow.js:148"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.TableRow.js:193"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.TableRow.js:241"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.TableRow.js:297"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/io/p5.XML.js:11"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:12"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:36"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:76"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:121"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:190"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:240"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:279"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:324"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:379"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:418"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:474"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:524"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:574"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:627"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:661"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:700"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/calculation.js:747"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/math.js:12"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/noise.js:40"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/noise.js:187"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/noise.js:253"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/p5.Vector.js:12"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/random.js:48"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/random.js:79"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/random.js:166"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/trigonometry.js:124"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/trigonometry.js:160"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/trigonometry.js:188"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/trigonometry.js:216"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/math/trigonometry.js:296"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " src/math/trigonometry.js:332"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " src/math/trigonometry.js:347"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " src/math/trigonometry.js:362"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/typography/attributes.js:13"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/typography/attributes.js:60"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/typography/attributes.js:98"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/typography/attributes.js:130"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/typography/attributes.js:165"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/typography/loading_displaying.js:16"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/typography/loading_displaying.js:143"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/typography/loading_displaying.js:202"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/typography/p5.Font.js:43"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/conversion.js:12"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/string_functions.js:15"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/string_functions.js:44"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/string_functions.js:132"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/string_functions.js:237"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/string_functions.js:313"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/string_functions.js:375"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/string_functions.js:437"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/string_functions.js:526"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/time_date.js:12"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/time_date.js:34"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/time_date.js:56"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/time_date.js:78"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/time_date.js:101"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/time_date.js:123"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/utilities/time_date.js:145"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/camera.js:12"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/camera.js:161"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/camera.js:243"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/interaction.js:5"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/light.js:12"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/light.js:101"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/light.js:207"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/loading.js:14"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/loading.js:215"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " src/webgl/material.js:57"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/material.js:57"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/material.js:150"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/material.js:185"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/material.js:275"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/material.js:324"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/p5.RendererGL.js:197"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/p5.RendererGL.js:439"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/p5.RendererGL.js:486"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/p5.RendererGL.js:526"
+ },
+ {
+ "message": "unknown tag: alt",
+ "line": " src/webgl/primitives.js:14"
+ },
+ {
+ "message": "replacing incorrect tag: params with param",
+ "line": " lib/addons/p5.sound.js:1567"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " lib/addons/p5.sound.js:1567"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " lib/addons/p5.sound.js:7272"
+ },
+ {
+ "message": "replacing incorrect tag: returns with return",
+ "line": " lib/addons/p5.sound.js:9222"
+ },
+ {
+ "message": "Missing item type\nConversions adapted from
.\n\nIn these functions, hue is always in the range [0,1); all other components\nare in the range [0,1]. 'Brightness' and 'value' are used interchangeably.",
+ "line": " src/color/color_conversion.js:10"
+ },
+ {
+ "message": "Missing item type\nConvert an HSBA array to HSLA.",
+ "line": " src/color/color_conversion.js:20"
+ },
+ {
+ "message": "Missing item type\nConvert an HSBA array to RGBA.",
+ "line": " src/color/color_conversion.js:46"
+ },
+ {
+ "message": "Missing item type\nConvert an HSLA array to HSBA.",
+ "line": " src/color/color_conversion.js:101"
+ },
+ {
+ "message": "Missing item type\nConvert an HSLA array to RGBA.\n\nWe need to change basis from HSLA to something that can be more easily be\nprojected onto RGBA. We will choose hue and brightness as our first two\ncomponents, and pick a convenient third one ('zest') so that we don't need\nto calculate formal HSBA saturation.",
+ "line": " src/color/color_conversion.js:124"
+ },
+ {
+ "message": "Missing item type\nConvert an RGBA array to HSBA.",
+ "line": " src/color/color_conversion.js:188"
+ },
+ {
+ "message": "Missing item type\nConvert an RGBA array to HSLA.",
+ "line": " src/color/color_conversion.js:227"
+ },
+ {
+ "message": "Missing item type\nHue is the same in HSB and HSL, but the maximum value may be different.\nThis function will return the HSB-normalized saturation when supplied with\nan HSB color object, but will default to the HSL-normalized saturation\notherwise.",
+ "line": " src/color/p5.Color.js:406"
+ },
+ {
+ "message": "Missing item type\nSaturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object, but will default\nto the HSL saturation otherwise.",
+ "line": " src/color/p5.Color.js:437"
+ },
+ {
+ "message": "Missing item type\nCSS named colors.",
+ "line": " src/color/p5.Color.js:456"
+ },
+ {
+ "message": "Missing item type\nThese regular expressions are used to build up the patterns for matching\nviable CSS color strings: fragmenting the regexes in this way increases the\nlegibility and comprehensibility of the code.\n\nNote that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency.",
+ "line": " src/color/p5.Color.js:609"
+ },
+ {
+ "message": "Missing item type\nFull color string patterns. The capture groups are necessary.",
+ "line": " src/color/p5.Color.js:622"
+ },
+ {
+ "message": "Missing item type\nFor a number of different inputs, returns a color formatted as [r, g, b, a]\narrays, with each component normalized between 0 and 1.",
+ "line": " src/color/p5.Color.js:759"
+ },
+ {
+ "message": "Missing item type\nFor HSB and HSL, interpret the gray level as a brightness/lightness\nvalue (they are equivalent when chroma is zero). For RGB, normalize the\ngray level according to the blue maximum.",
+ "line": " src/color/p5.Color.js:976"
+ },
+ {
+ "message": "Missing item type",
+ "line": " src/core/canvas.js:1"
+ },
+ {
+ "message": "Missing item type\nReturns the current framerate.",
+ "line": " src/core/environment.js:242"
+ },
+ {
+ "message": "Missing item type\nSpecifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within setup() is\nrecommended. The default rate is 60 frames per second.\n\nCalling frameRate() with no arguments returns the current framerate.",
+ "line": " src/core/environment.js:252"
+ },
+ {
+ "message": "Missing item type",
+ "line": " src/core/error_helpers.js:1"
+ },
+ {
+ "message": "Missing item type\nPrints out a fancy, colorful message to the console log",
+ "line": " src/core/error_helpers.js:65"
+ },
+ {
+ "message": "Missing item type\nValidates parameters\nparam {String} func the name of the function\nparam {Array} args user input arguments\n\nexample:\n var a;\n ellipse(10,10,a,5);\nconsole ouput:\n \"It looks like ellipse received an empty variable in spot #2.\"\n\nexample:\n ellipse(10,\"foo\",5,5);\nconsole output:\n \"ellipse was expecting a number for parameter #1,\n received \"foo\" instead.\"",
+ "line": " src/core/error_helpers.js:405"
+ },
+ {
+ "message": "Missing item type\nPrints out all the colors in the color pallete with white text.\nFor color blindness testing.",
+ "line": " src/core/error_helpers.js:457"
+ },
+ {
+ "message": "Missing item type\n_globalInit\n\nTODO: ???\nif sketch is on window\nassume \"global\" mode\nand instantiate p5 automatically\notherwise do nothing",
+ "line": " src/core/init.js:5"
+ },
+ {
+ "message": "Missing item type\nHelper fxn for sharing pixel methods",
+ "line": " src/core/p5.Element.js:1057"
+ },
+ {
+ "message": "Missing item type\nResize our canvas element.",
+ "line": " src/core/p5.Renderer.js:113"
+ },
+ {
+ "message": "Missing item type\nHelper fxn to check font type (system or otf)",
+ "line": " src/core/p5.Renderer.js:182"
+ },
+ {
+ "message": "Missing item type\nHelper fxn to measure ascent and descent.\nAdapted from http://stackoverflow.com/a/25355178",
+ "line": " src/core/p5.Renderer.js:235"
+ },
+ {
+ "message": "Missing item type\np5.Renderer2D\nThe 2D graphics canvas renderer class.\nextends p5.Renderer",
+ "line": " src/core/p5.Renderer2D.js:10"
+ },
+ {
+ "message": "Missing item type\nGenerate a cubic Bezier representing an arc on the unit circle of total\nangle `size` radians, beginning `start` radians above the x-axis. Up to\nfour of these curves are combined to make a full arc.\n\nSee www.joecridge.me/bezier.pdf for an explanation of the method.",
+ "line": " src/core/p5.Renderer2D.js:395"
+ },
+ {
+ "message": "Missing item type\nshim for Uint8ClampedArray.slice\n(allows arrayCopy to work with pixels[])\nwith thanks to http://halfpapstudios.com/blog/tag/html5-canvas/\nEnumerable set to false to protect for...in from\nUint8ClampedArray.prototype pollution.",
+ "line": " src/core/shim.js:70"
+ },
+ {
+ "message": "Missing item type\nprivate helper function to handle the user passing objects in\nduring construction or calls to create()",
+ "line": " src/data/p5.TypedDict.js:198"
+ },
+ {
+ "message": "Missing item type\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type",
+ "line": " src/data/p5.TypedDict.js:378"
+ },
+ {
+ "message": "Missing item type\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type",
+ "line": " src/data/p5.TypedDict.js:423"
+ },
+ {
+ "message": "Missing item type\nprivate helper function for finding lowest or highest value\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'",
+ "line": " src/data/p5.TypedDict.js:540"
+ },
+ {
+ "message": "Missing item type\nprivate helper function for finding lowest or highest key\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'",
+ "line": " src/data/p5.TypedDict.js:605"
+ },
+ {
+ "message": "Missing item type\n_updatePAccelerations updates the pAcceleration values",
+ "line": " src/events/acceleration.js:80"
+ },
+ {
+ "message": "Missing item type\nHolds the key codes of currently pressed keys.",
+ "line": " src/events/keyboard.js:12"
+ },
+ {
+ "message": "Missing item type\nThe onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released.",
+ "line": " src/events/keyboard.js:308"
+ },
+ {
+ "message": "Missing item type\nThe checkDownKeys function returns a boolean true if any keys pressed\nand a false if no keys are currently pressed.\n\nHelps avoid instances where a multiple keys are pressed simultaneously and\nreleasing a single key will then switch the\nkeyIsPressed property to true.",
+ "line": " src/events/keyboard.js:370"
+ },
+ {
+ "message": "Missing item type\nThis module defines the filters for use with image buffers.\n\nThis module is basically a collection of functions stored in an object\nas opposed to modules. The functions are destructive, modifying\nthe passed in canvas rather than creating a copy.\n\nGenerally speaking users of this module will use the Filters.apply method\non a canvas to create an effect.\n\nA number of functions are borrowed/adapted from\nhttp://www.html5rocks.com/en/tutorials/canvas/imagefilters/\nor the java processing implementation.",
+ "line": " src/image/filters.js:3"
+ },
+ {
+ "message": "Missing item type\nReturns the pixel buffer for a canvas",
+ "line": " src/image/filters.js:26"
+ },
+ {
+ "message": "Missing item type\nReturns a 32 bit number containing ARGB data at ith pixel in the\n1D array containing pixels data.",
+ "line": " src/image/filters.js:46"
+ },
+ {
+ "message": "Missing item type\nModifies pixels RGBA values to values contained in the data object.",
+ "line": " src/image/filters.js:67"
+ },
+ {
+ "message": "Missing item type\nReturns the ImageData object for a canvas\nhttps://developer.mozilla.org/en-US/docs/Web/API/ImageData",
+ "line": " src/image/filters.js:87"
+ },
+ {
+ "message": "Missing item type\nReturns a blank ImageData object.",
+ "line": " src/image/filters.js:107"
+ },
+ {
+ "message": "Missing item type\nApplys a filter function to a canvas.\n\nThe difference between this and the actual filter functions defined below\nis that the filter functions generally modify the pixel buffer but do\nnot actually put that data back to the canvas (where it would actually\nupdate what is visible). By contrast this method does make the changes\nactually visible in the canvas.\n\nThe apply method is the method that callers of this module would generally\nuse. It has been separated from the actual filters to support an advanced\nuse case of creating a filter chain that executes without actually updating\nthe canvas in between everystep.",
+ "line": " src/image/filters.js:122"
+ },
+ {
+ "message": "Missing item type\nConverts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.\n\nBorrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/",
+ "line": " src/image/filters.js:159"
+ },
+ {
+ "message": "Missing item type\nConverts any colors in the image to grayscale equivalents.\nNo parameter is used.\n\nBorrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/",
+ "line": " src/image/filters.js:193"
+ },
+ {
+ "message": "Missing item type\nSets the alpha channel to entirely opaque. No parameter is used.",
+ "line": " src/image/filters.js:216"
+ },
+ {
+ "message": "Missing item type\nSets each pixel to its inverse value. No parameter is used.",
+ "line": " src/image/filters.js:232"
+ },
+ {
+ "message": "Missing item type\nLimits each channel of the image to the number of colors specified as\nthe parameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.\n\nAdapted from java based processing implementation",
+ "line": " src/image/filters.js:247"
+ },
+ {
+ "message": "Missing item type\nreduces the bright areas in an image",
+ "line": " src/image/filters.js:279"
+ },
+ {
+ "message": "Missing item type\nincreases the bright areas in an image",
+ "line": " src/image/filters.js:367"
+ },
+ {
+ "message": "Missing item type\nThis module defines the p5 methods for the p5.Image class\nfor drawing images to the main display canvas.",
+ "line": " src/image/image.js:8"
+ },
+ {
+ "message": "Missing item type\nValidates clipping params. Per drawImage spec sWidth and sHight cannot be\nnegative or greater than image intrinsic width and height",
+ "line": " src/image/loading_displaying.js:108"
+ },
+ {
+ "message": "Missing item type\nApply the current tint color to the input image, return the resulting\ncanvas.",
+ "line": " src/image/loading_displaying.js:425"
+ },
+ {
+ "message": "Missing item type\nThis module defines the p5.Image class and P5 methods for\ndrawing images to the main display canvas.",
+ "line": " src/image/p5.Image.js:9"
+ },
+ {
+ "message": "Missing item type\nHelper fxn for sharing pixel methods",
+ "line": " src/image/p5.Image.js:221"
+ },
+ {
+ "message": "Missing item type\nGenerate a blob of file data as a url to prepare for download.\nAccepts an array of data, a filename, and an extension (optional).\nThis is a private function because it does not do any formatting,\nbut it is used by saveStrings, saveJSON, saveTable etc.",
+ "line": " src/io/files.js:1697"
+ },
+ {
+ "message": "Missing item type\nReturns a file extension, or another string\nif the provided parameter has no extension.",
+ "line": " src/io/files.js:1766"
+ },
+ {
+ "message": "Missing item type\nReturns true if the browser is Safari, false if not.\nSafari makes trouble for downloading files.",
+ "line": " src/io/files.js:1799"
+ },
+ {
+ "message": "Missing item type\nHelper function, a callback for download that deletes\nan invisible anchor element from the DOM once the file\nhas been automatically downloaded.",
+ "line": " src/io/files.js:1811"
+ },
+ {
+ "message": "Missing item type\nTable Options\nGeneric class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.
\nCSV files are\n\ncomma separated values, often with the data in quotes. TSV\nfiles use tabs as separators, and usually don't bother with the\nquotes.
\nFile names should end with .csv if they're comma separated.
\nA rough \"spec\" for CSV can be found\nhere.
\nTo load files, use the loadTable method.
\nTo save tables to your computer, use the save method\n or the saveTable method.
\n\nPossible options include:\n\n- csv - parse the table as comma-separated values\n
- tsv - parse the table as tab-separated values\n
- header - this table has a header (title) row\n
",
+ "line": " src/io/p5.Table.js:11"
+ },
+ {
+ "message": "Missing item type\nThis method is called while the parsing of XML (when loadXML() is\ncalled). The difference between this method and the setContent()\nmethod defined later is that this one is used to set the content\nwhen the node in question has more nodes under it and so on and\nnot directly text content. While in the other one is used when\nthe node in question directly has text inside it.",
+ "line": " src/io/p5.XML.js:801"
+ },
+ {
+ "message": "Missing item type\nThis method is called while the parsing of XML (when loadXML() is\ncalled). The XML node is passed and its attributes are stored in the\np5.XML's attribute Object.",
+ "line": " src/io/p5.XML.js:818"
+ },
+ {
+ "message": "Missing item type\nMultiplies a vector by a scalar and returns a new vector.",
+ "line": " src/math/p5.Vector.js:1611"
+ },
+ {
+ "message": "Missing item type\nDivides a vector by a scalar and returns a new vector.",
+ "line": " src/math/p5.Vector.js:1638"
+ },
+ {
+ "message": "Missing item type\nCalculates the dot product of two vectors.",
+ "line": " src/math/p5.Vector.js:1665"
+ },
+ {
+ "message": "Missing item type\nCalculates the cross product of two vectors.",
+ "line": " src/math/p5.Vector.js:1679"
+ },
+ {
+ "message": "Missing item type\nCalculates the Euclidean distance between two points (considering a\npoint as a vector object).",
+ "line": " src/math/p5.Vector.js:1693"
+ },
+ {
+ "message": "Missing item type\nLinear interpolate a vector to another vector and return the result as a\nnew vector.",
+ "line": " src/math/p5.Vector.js:1708"
+ },
+ {
+ "message": "Missing item type\nHelper function to measure ascent and descent.",
+ "line": " src/typography/attributes.js:258"
+ },
+ {
+ "message": "Missing item type\nReturns the set of opentype glyphs for the supplied string.\n\nNote that there is not a strict one-to-one mapping between characters\nand glyphs, so the list of returned glyphs can be larger or smaller\n than the length of the given string.",
+ "line": " src/typography/p5.Font.js:257"
+ },
+ {
+ "message": "Missing item type\nReturns an opentype path for the supplied string and position.",
+ "line": " src/typography/p5.Font.js:272"
+ },
+ {
+ "message": "Missing item type\nParse OBJ lines into model. For reference, this is what a simple model of a\nsquare might look like:\n\nv -0.5 -0.5 0.5\nv -0.5 -0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 0.5 0.5\n\nf 4 3 2 1",
+ "line": " src/webgl/loading.js:106"
+ },
+ {
+ "message": "Missing item type",
+ "line": " src/webgl/material.js:373"
+ },
+ {
+ "message": "Missing item type\nCreate a 2D array for establishing stroke connections",
+ "line": " src/webgl/p5.Geometry.js:192"
+ },
+ {
+ "message": "Missing item type\nCreate 4 vertices for each stroke line, two at the beginning position\nand two at the end position. These vertices are displaced relative to\nthat line's normal on the GPU",
+ "line": " src/webgl/p5.Geometry.js:213"
+ },
+ {
+ "message": "Missing item type",
+ "line": " src/webgl/p5.Matrix.js:1"
+ },
+ {
+ "message": "Missing item type\nPRIVATE",
+ "line": " src/webgl/p5.Matrix.js:673"
+ },
+ {
+ "message": "Missing item type\nWelcome to RendererGL Immediate Mode.\nImmediate mode is used for drawing custom shapes\nfrom a set of vertices. Immediate Mode is activated\nwhen you call beginShape() & de-activated when you call endShape().\nImmediate mode is a style of programming borrowed\nfrom OpenGL's (now-deprecated) immediate mode.\nIt differs from p5.js' default, Retained Mode, which caches\ngeometries and buffers on the CPU to reduce the number of webgl\ndraw calls. Retained mode is more efficient & performative,\nhowever, Immediate Mode is useful for sketching quick\ngeometric ideas.",
+ "line": " src/webgl/p5.RendererGL.Immediate.js:1"
+ },
+ {
+ "message": "Missing item type\nEnd shape drawing and render vertices to screen.",
+ "line": " src/webgl/p5.RendererGL.Immediate.js:106"
+ },
+ {
+ "message": "Missing item type\ninitializes buffer defaults. runs each time a new geometry is\nregistered",
+ "line": " src/webgl/p5.RendererGL.Retained.js:8"
+ },
+ {
+ "message": "Missing item type\ncreateBuffers description",
+ "line": " src/webgl/p5.RendererGL.Retained.js:47"
+ },
+ {
+ "message": "Missing item type\nDraws buffers given a geometry key ID",
+ "line": " src/webgl/p5.RendererGL.Retained.js:191"
+ },
+ {
+ "message": "Missing item type\nmodel view, projection, & normal\nmatrices",
+ "line": " src/webgl/p5.RendererGL.js:77"
+ },
+ {
+ "message": "Missing item type\n[background description]",
+ "line": " src/webgl/p5.RendererGL.js:417"
+ },
+ {
+ "message": "Missing item type\n[resize description]",
+ "line": " src/webgl/p5.RendererGL.js:654"
+ },
+ {
+ "message": "Missing item type\nclears color and depth buffers\nwith r,g,b,a",
+ "line": " src/webgl/p5.RendererGL.js:684"
+ },
+ {
+ "message": "Missing item type\n[translate description]",
+ "line": " src/webgl/p5.RendererGL.js:702"
+ },
+ {
+ "message": "Missing item type\nScales the Model View Matrix by a vector",
+ "line": " src/webgl/p5.RendererGL.js:721"
+ },
+ {
+ "message": "Missing item type\nturn a two dimensional array into one dimensional array",
+ "line": " src/webgl/p5.RendererGL.js:1001"
+ },
+ {
+ "message": "Missing item type\nturn a p5.Vector Array into a one dimensional number array",
+ "line": " src/webgl/p5.RendererGL.js:1038"
+ },
+ {
+ "message": "Missing item type\nensures that p5 is using a 3d renderer. throws an error if not.",
+ "line": " src/webgl/p5.RendererGL.js:1054"
+ },
+ {
+ "message": "Missing item type",
+ "line": " src/webgl/primitives.js:257"
+ },
+ {
+ "message": "Missing item type\nDraw a line given two points",
+ "line": " src/webgl/primitives.js:1037"
+ },
+ {
+ "message": "Missing item type\nHelper function for select and selectAll",
+ "line": " lib/addons/p5.dom.js:168"
+ },
+ {
+ "message": "Missing item type\nHelper function for getElement and getElements.",
+ "line": " lib/addons/p5.dom.js:184"
+ },
+ {
+ "message": "Missing item type\nHelpers for create methods.",
+ "line": " lib/addons/p5.dom.js:245"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.dom.js:376"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.dom.js:897"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.dom.js:973"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.dom.js:1013"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.dom.js:2581"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.dom.js:2647"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.dom.js:2709"
+ },
+ {
+ "message": "Missing item type\np5.sound\nhttps://p5js.org/reference/#/libraries/p5.sound\n\nFrom the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors\n\nMIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE\n\nSome of the many audio libraries & resources that inspire p5.sound:\n - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js\n - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/\n - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0\n - wavesurfer.js https://github.com/katspaugh/wavesurfer.js\n - Web Audio Components by Jordan Santell https://github.com/web-audio-components\n - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound\n\n Web Audio API: http://w3.org/TR/webaudio/",
+ "line": " lib/addons/p5.sound.js:46"
+ },
+ {
+ "message": "Missing item type\nDetermine which filetypes are supported (inspired by buzz.js)\nThe audio element (el) will only be used to test browser support for various audio formats",
+ "line": " lib/addons/p5.sound.js:226"
+ },
+ {
+ "message": "Missing item type\nMaster contains AudioContext and the master sound output.",
+ "line": " lib/addons/p5.sound.js:296"
+ },
+ {
+ "message": "Missing item type\na silent connection to the DesinationNode\nwhich will ensure that anything connected to it\nwill not be garbage collected",
+ "line": " lib/addons/p5.sound.js:391"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:407"
+ },
+ {
+ "message": "Missing item type\nUsed by Osc and Env to chain signal math",
+ "line": " lib/addons/p5.sound.js:583"
+ },
+ {
+ "message": "Missing item type\nThis is a helper function that the p5.SoundFile calls to load\nitself. Accepts a callback (the name of another function)\nas an optional parameter.",
+ "line": " lib/addons/p5.sound.js:903"
+ },
+ {
+ "message": "Missing item type\nStop playback on all of this soundfile's sources.",
+ "line": " lib/addons/p5.sound.js:1304"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:1741"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:2022"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:3022"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:3399"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:3420"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:3479"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:3797"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:3969"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:4127"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:4168"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:4238"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:4426"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:4483"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:4651"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:4699"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:4730"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:4751"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:4771"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:5478"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:5681"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:7363"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:7379"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:7403"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:7429"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:7451"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:7473"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:7519"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:7550"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:7568"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:7905"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:7927"
+ },
+ {
+ "message": "Missing item type\nThe p5.Effect class is built\n using Tone.js CrossFade",
+ "line": " lib/addons/p5.sound.js:7997"
+ },
+ {
+ "message": "Missing item type\nIn classes that extend\np5.Effect, connect effect nodes\nto the wet parameter",
+ "line": " lib/addons/p5.sound.js:8003"
+ },
+ {
+ "message": "Missing item type\nEQFilter extends p5.Filter with constraints\nnecessary for the p5.EQ",
+ "line": " lib/addons/p5.sound.js:8381"
+ },
+ {
+ "message": "Missing item type\nInspired by Simple Reverb by Jordan Santell\nhttps://github.com/web-audio-components/simple-reverb/blob/master/index.js\n\nUtility function for building an impulse response\nbased on the module parameters.",
+ "line": " lib/addons/p5.sound.js:9471"
+ },
+ {
+ "message": "Missing item type\nPrivate method to load a buffer as an Impulse Response,\nassign it to the convolverNode, and add to the Array of .impulses.",
+ "line": " lib/addons/p5.sound.js:9635"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:9821"
+ },
+ {
+ "message": "Missing item type",
+ "line": " lib/addons/p5.sound.js:9846"
+ },
+ {
+ "message": "Missing item type\nmusicalTimeMode variables\nmodify these only when the interval is specified in musicalTime format as a string",
+ "line": " lib/addons/p5.sound.js:10571"
+ },
+ {
+ "message": "Missing item type\nDo not initiate the callback if timeFromNow is < 0\nThis ususually occurs for a few milliseconds when the page\nis not fully loaded\n\nThe callback should only be called until maxIterations is reached",
+ "line": " lib/addons/p5.sound.js:10587"
+ },
+ {
+ "message": "Missing item type\ncallback invoked when the recording is over",
+ "line": " lib/addons/p5.sound.js:11072"
+ },
+ {
+ "message": "Missing item type\ninternal method called on audio process",
+ "line": " lib/addons/p5.sound.js:11158"
+ },
+ {
+ "message": "Missing item type\nPrivate method to ensure accurate values of this._voicesInUse\nAny time a new value is scheduled, it is necessary to increment all subsequent\nscheduledValues after attack, and decrement all subsequent\nscheduledValues after release",
+ "line": " lib/addons/p5.sound.js:12142"
+ },
+ {
+ "message": "Missing item type\np5.sound\nhttps://p5js.org/reference/#/libraries/p5.sound\n\nFrom the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors\n\nMIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE\n\nSome of the many audio libraries & resources that inspire p5.sound:\n - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js\n - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/\n - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0\n - wavesurfer.js https://github.com/katspaugh/wavesurfer.js\n - Web Audio Components by Jordan Santell https://github.com/web-audio-components\n - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound\n\n Web Audio API: http://w3.org/TR/webaudio/",
+ "line": " lib/addons/p5.sound.min.js:3"
+ }
+ ],
+ "consts": {
+ "RGB": [
+ "p5.colorMode"
+ ],
+ "HSB": [
+ "p5.colorMode"
+ ],
+ "HSL": [
+ "p5.colorMode"
+ ],
+ "CHORD": [
+ "p5.arc"
+ ],
+ "PIE": [
+ "p5.arc"
+ ],
+ "OPEN": [
+ "p5.arc"
+ ],
+ "CENTER": [
+ "p5.ellipseMode",
+ "p5.rectMode",
+ "p5.imageMode",
+ "p5.textAlign"
+ ],
+ "RADIUS": [
+ "p5.ellipseMode",
+ "p5.rectMode"
+ ],
+ "CORNER": [
+ "p5.ellipseMode",
+ "p5.rectMode",
+ "p5.imageMode"
+ ],
+ "CORNERS": [
+ "p5.ellipseMode",
+ "p5.rectMode",
+ "p5.imageMode"
+ ],
+ "SQUARE": [
+ "p5.strokeCap"
+ ],
+ "PROJECT": [
+ "p5.strokeCap"
+ ],
+ "ROUND": [
+ "p5.strokeCap",
+ "p5.strokeJoin"
+ ],
+ "MITER": [
+ "p5.strokeJoin"
+ ],
+ "BEVEL": [
+ "p5.strokeJoin"
+ ],
+ "ARROW": [
+ "p5.cursor"
+ ],
+ "CROSS": [
+ "p5.cursor"
+ ],
+ "HAND": [
+ "p5.cursor"
+ ],
+ "MOVE": [
+ "p5.cursor"
+ ],
+ "TEXT": [
+ "p5.cursor"
+ ],
+ "WAIT": [
+ "p5.cursor"
+ ],
+ "P2D": [
+ "p5.createCanvas",
+ "p5.createGraphics"
+ ],
+ "WEBGL": [
+ "p5.createCanvas",
+ "p5.createGraphics"
+ ],
+ "BLEND": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "DARKEST": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "LIGHTEST": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "DIFFERENCE": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "MULTIPLY": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "EXCLUSION": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "SCREEN": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "REPLACE": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "OVERLAY": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "HARD_LIGHT": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "SOFT_LIGHT": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "DODGE": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "BURN": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "ADD": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend"
+ ],
+ "NORMAL": [
+ "p5.blendMode",
+ "p5.Image.blend",
+ "p5.blend",
+ "p5.textStyle"
+ ],
+ "POINTS": [
+ "p5.beginShape"
+ ],
+ "LINES": [
+ "p5.beginShape"
+ ],
+ "TRIANGLES": [
+ "p5.beginShape"
+ ],
+ "TRIANGLE_FAN": [
+ "p5.beginShape"
+ ],
+ "TRIANGLE_STRIP": [
+ "p5.beginShape"
+ ],
+ "QUADS": [
+ "p5.beginShape"
+ ],
+ "QUAD_STRIP": [
+ "p5.beginShape"
+ ],
+ "CLOSE": [
+ "p5.endShape"
+ ],
+ "THRESHOLD": [
+ "p5.Image.filter",
+ "p5.filter"
+ ],
+ "GRAY": [
+ "p5.Image.filter",
+ "p5.filter"
+ ],
+ "OPAQUE": [
+ "p5.Image.filter",
+ "p5.filter"
+ ],
+ "INVERT": [
+ "p5.Image.filter",
+ "p5.filter"
+ ],
+ "POSTERIZE": [
+ "p5.Image.filter",
+ "p5.filter"
+ ],
+ "BLUR": [
+ "p5.Image.filter",
+ "p5.filter"
+ ],
+ "ERODE": [
+ "p5.Image.filter",
+ "p5.filter"
+ ],
+ "DILATE": [
+ "p5.Image.filter",
+ "p5.filter"
+ ],
+ "RADIANS": [
+ "p5.angleMode"
+ ],
+ "DEGREES": [
+ "p5.angleMode"
+ ],
+ "LEFT": [
+ "p5.textAlign"
+ ],
+ "RIGHT": [
+ "p5.textAlign"
+ ],
+ "TOP": [
+ "p5.textAlign"
+ ],
+ "BOTTOM": [
+ "p5.textAlign"
+ ],
+ "BASELINE": [
+ "p5.textAlign"
+ ],
+ "ITALIC": [
+ "p5.textStyle"
+ ],
+ "BOLD": [
+ "p5.textStyle"
+ ],
+ "VIDEO": [
+ "p5.dom.createCapture"
+ ],
+ "AUDIO": [
+ "p5.dom.createCapture"
+ ],
+ "AUTO": [
+ "p5.Element.size"
+ ]
+ }
+}
+},{}],2:[function(_dereq_,module,exports){
+var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
+
+;(function (exports) {
+ 'use strict';
+
+ var Arr = (typeof Uint8Array !== 'undefined')
+ ? Uint8Array
+ : Array
+
+ var PLUS = '+'.charCodeAt(0)
+ var SLASH = '/'.charCodeAt(0)
+ var NUMBER = '0'.charCodeAt(0)
+ var LOWER = 'a'.charCodeAt(0)
+ var UPPER = 'A'.charCodeAt(0)
+ var PLUS_URL_SAFE = '-'.charCodeAt(0)
+ var SLASH_URL_SAFE = '_'.charCodeAt(0)
+
+ function decode (elt) {
+ var code = elt.charCodeAt(0)
+ if (code === PLUS ||
+ code === PLUS_URL_SAFE)
+ return 62 // '+'
+ if (code === SLASH ||
+ code === SLASH_URL_SAFE)
+ return 63 // '/'
+ if (code < NUMBER)
+ return -1 //no match
+ if (code < NUMBER + 10)
+ return code - NUMBER + 26 + 26
+ if (code < UPPER + 26)
+ return code - UPPER
+ if (code < LOWER + 26)
+ return code - LOWER + 26
+ }
+
+ function b64ToByteArray (b64) {
+ var i, j, l, tmp, placeHolders, arr
+
+ if (b64.length % 4 > 0) {
+ throw new Error('Invalid string. Length must be a multiple of 4')
+ }
+
+ // the number of equal signs (place holders)
+ // if there are two placeholders, than the two characters before it
+ // represent one byte
+ // if there is only one, then the three characters before it represent 2 bytes
+ // this is just a cheap hack to not do indexOf twice
+ var len = b64.length
+ placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
+
+ // base64 is 4/3 + up to two characters of the original data
+ arr = new Arr(b64.length * 3 / 4 - placeHolders)
+
+ // if there are placeholders, only get up to the last complete 4 chars
+ l = placeHolders > 0 ? b64.length - 4 : b64.length
+
+ var L = 0
+
+ function push (v) {
+ arr[L++] = v
+ }
+
+ for (i = 0, j = 0; i < l; i += 4, j += 3) {
+ tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
+ push((tmp & 0xFF0000) >> 16)
+ push((tmp & 0xFF00) >> 8)
+ push(tmp & 0xFF)
+ }
+
+ if (placeHolders === 2) {
+ tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
+ push(tmp & 0xFF)
+ } else if (placeHolders === 1) {
+ tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
+ push((tmp >> 8) & 0xFF)
+ push(tmp & 0xFF)
+ }
+
+ return arr
+ }
+
+ function uint8ToBase64 (uint8) {
+ var i,
+ extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
+ output = "",
+ temp, length
+
+ function encode (num) {
+ return lookup.charAt(num)
+ }
+
+ function tripletToBase64 (num) {
+ return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
+ }
+
+ // go through the array every three bytes, we'll deal with trailing stuff later
+ for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
+ temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
+ output += tripletToBase64(temp)
+ }
+
+ // pad the end with zeros, but make sure to not forget the extra bytes
+ switch (extraBytes) {
+ case 1:
+ temp = uint8[uint8.length - 1]
+ output += encode(temp >> 2)
+ output += encode((temp << 4) & 0x3F)
+ output += '=='
+ break
+ case 2:
+ temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
+ output += encode(temp >> 10)
+ output += encode((temp >> 4) & 0x3F)
+ output += encode((temp << 2) & 0x3F)
+ output += '='
+ break
+ }
+
+ return output
+ }
+
+ exports.toByteArray = b64ToByteArray
+ exports.fromByteArray = uint8ToBase64
+}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
+
+},{}],3:[function(_dereq_,module,exports){
+
+},{}],4:[function(_dereq_,module,exports){
+(function (global){
+/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
+/* eslint-disable no-proto */
+
+'use strict'
+
+var base64 = _dereq_('base64-js')
+var ieee754 = _dereq_('ieee754')
+var isArray = _dereq_('isarray')
+
+exports.Buffer = Buffer
+exports.SlowBuffer = SlowBuffer
+exports.INSPECT_MAX_BYTES = 50
+Buffer.poolSize = 8192 // not used by this implementation
+
+var rootParent = {}
+
+/**
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
+ * === true Use Uint8Array implementation (fastest)
+ * === false Use Object implementation (most compatible, even IE6)
+ *
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
+ * Opera 11.6+, iOS 4.2+.
+ *
+ * Due to various browser bugs, sometimes the Object implementation will be used even
+ * when the browser supports typed arrays.
+ *
+ * Note:
+ *
+ * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
+ * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
+ *
+ * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
+ * on objects.
+ *
+ * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
+ *
+ * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
+ * incorrect length in some situations.
+
+ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
+ * get the Object implementation, which is slower but behaves correctly.
+ */
+Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
+ ? global.TYPED_ARRAY_SUPPORT
+ : typedArraySupport()
+
+function typedArraySupport () {
+ function Bar () {}
+ try {
+ var arr = new Uint8Array(1)
+ arr.foo = function () { return 42 }
+ arr.constructor = Bar
+ return arr.foo() === 42 && // typed array instances can be augmented
+ arr.constructor === Bar && // constructor can be set
+ typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
+ arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
+ } catch (e) {
+ return false
+ }
+}
+
+function kMaxLength () {
+ return Buffer.TYPED_ARRAY_SUPPORT
+ ? 0x7fffffff
+ : 0x3fffffff
+}
+
+/**
+ * Class: Buffer
+ * =============
+ *
+ * The Buffer constructor returns instances of `Uint8Array` that are augmented
+ * with function properties for all the node `Buffer` API functions. We use
+ * `Uint8Array` so that square bracket notation works as expected -- it returns
+ * a single octet.
+ *
+ * By augmenting the instances, we can avoid modifying the `Uint8Array`
+ * prototype.
+ */
+function Buffer (arg) {
+ if (!(this instanceof Buffer)) {
+ // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
+ if (arguments.length > 1) return new Buffer(arg, arguments[1])
+ return new Buffer(arg)
+ }
+
+ if (!Buffer.TYPED_ARRAY_SUPPORT) {
+ this.length = 0
+ this.parent = undefined
+ }
+
+ // Common case.
+ if (typeof arg === 'number') {
+ return fromNumber(this, arg)
+ }
+
+ // Slightly less common case.
+ if (typeof arg === 'string') {
+ return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
+ }
+
+ // Unusual.
+ return fromObject(this, arg)
+}
+
+function fromNumber (that, length) {
+ that = allocate(that, length < 0 ? 0 : checked(length) | 0)
+ if (!Buffer.TYPED_ARRAY_SUPPORT) {
+ for (var i = 0; i < length; i++) {
+ that[i] = 0
+ }
+ }
+ return that
+}
+
+function fromString (that, string, encoding) {
+ if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
+
+ // Assumption: byteLength() return value is always < kMaxLength.
+ var length = byteLength(string, encoding) | 0
+ that = allocate(that, length)
+
+ that.write(string, encoding)
+ return that
+}
+
+function fromObject (that, object) {
+ if (Buffer.isBuffer(object)) return fromBuffer(that, object)
+
+ if (isArray(object)) return fromArray(that, object)
+
+ if (object == null) {
+ throw new TypeError('must start with number, buffer, array or string')
+ }
+
+ if (typeof ArrayBuffer !== 'undefined') {
+ if (object.buffer instanceof ArrayBuffer) {
+ return fromTypedArray(that, object)
+ }
+ if (object instanceof ArrayBuffer) {
+ return fromArrayBuffer(that, object)
+ }
+ }
+
+ if (object.length) return fromArrayLike(that, object)
+
+ return fromJsonObject(that, object)
+}
+
+function fromBuffer (that, buffer) {
+ var length = checked(buffer.length) | 0
+ that = allocate(that, length)
+ buffer.copy(that, 0, 0, length)
+ return that
+}
+
+function fromArray (that, array) {
+ var length = checked(array.length) | 0
+ that = allocate(that, length)
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255
+ }
+ return that
+}
+
+// Duplicate of fromArray() to keep fromArray() monomorphic.
+function fromTypedArray (that, array) {
+ var length = checked(array.length) | 0
+ that = allocate(that, length)
+ // Truncating the elements is probably not what people expect from typed
+ // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
+ // of the old Buffer constructor.
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255
+ }
+ return that
+}
+
+function fromArrayBuffer (that, array) {
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ array.byteLength
+ that = Buffer._augment(new Uint8Array(array))
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ that = fromTypedArray(that, new Uint8Array(array))
+ }
+ return that
+}
+
+function fromArrayLike (that, array) {
+ var length = checked(array.length) | 0
+ that = allocate(that, length)
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255
+ }
+ return that
+}
+
+// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
+// Returns a zero-length buffer for inputs that don't conform to the spec.
+function fromJsonObject (that, object) {
+ var array
+ var length = 0
+
+ if (object.type === 'Buffer' && isArray(object.data)) {
+ array = object.data
+ length = checked(array.length) | 0
+ }
+ that = allocate(that, length)
+
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255
+ }
+ return that
+}
+
+if (Buffer.TYPED_ARRAY_SUPPORT) {
+ Buffer.prototype.__proto__ = Uint8Array.prototype
+ Buffer.__proto__ = Uint8Array
+} else {
+ // pre-set for values that may exist in the future
+ Buffer.prototype.length = undefined
+ Buffer.prototype.parent = undefined
+}
+
+function allocate (that, length) {
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ that = Buffer._augment(new Uint8Array(length))
+ that.__proto__ = Buffer.prototype
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ that.length = length
+ that._isBuffer = true
+ }
+
+ var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
+ if (fromPool) that.parent = rootParent
+
+ return that
+}
+
+function checked (length) {
+ // Note: cannot use `length < kMaxLength` here because that fails when
+ // length is NaN (which is otherwise coerced to zero.)
+ if (length >= kMaxLength()) {
+ throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
+ 'size: 0x' + kMaxLength().toString(16) + ' bytes')
+ }
+ return length | 0
+}
+
+function SlowBuffer (subject, encoding) {
+ if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
+
+ var buf = new Buffer(subject, encoding)
+ delete buf.parent
+ return buf
+}
+
+Buffer.isBuffer = function isBuffer (b) {
+ return !!(b != null && b._isBuffer)
+}
+
+Buffer.compare = function compare (a, b) {
+ if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
+ throw new TypeError('Arguments must be Buffers')
+ }
+
+ if (a === b) return 0
+
+ var x = a.length
+ var y = b.length
+
+ var i = 0
+ var len = Math.min(x, y)
+ while (i < len) {
+ if (a[i] !== b[i]) break
+
+ ++i
+ }
+
+ if (i !== len) {
+ x = a[i]
+ y = b[i]
+ }
+
+ if (x < y) return -1
+ if (y < x) return 1
+ return 0
+}
+
+Buffer.isEncoding = function isEncoding (encoding) {
+ switch (String(encoding).toLowerCase()) {
+ case 'hex':
+ case 'utf8':
+ case 'utf-8':
+ case 'ascii':
+ case 'binary':
+ case 'base64':
+ case 'raw':
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return true
+ default:
+ return false
+ }
+}
+
+Buffer.concat = function concat (list, length) {
+ if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
+
+ if (list.length === 0) {
+ return new Buffer(0)
+ }
+
+ var i
+ if (length === undefined) {
+ length = 0
+ for (i = 0; i < list.length; i++) {
+ length += list[i].length
+ }
+ }
+
+ var buf = new Buffer(length)
+ var pos = 0
+ for (i = 0; i < list.length; i++) {
+ var item = list[i]
+ item.copy(buf, pos)
+ pos += item.length
+ }
+ return buf
+}
+
+function byteLength (string, encoding) {
+ if (typeof string !== 'string') string = '' + string
+
+ var len = string.length
+ if (len === 0) return 0
+
+ // Use a for loop to avoid recursion
+ var loweredCase = false
+ for (;;) {
+ switch (encoding) {
+ case 'ascii':
+ case 'binary':
+ // Deprecated
+ case 'raw':
+ case 'raws':
+ return len
+ case 'utf8':
+ case 'utf-8':
+ return utf8ToBytes(string).length
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return len * 2
+ case 'hex':
+ return len >>> 1
+ case 'base64':
+ return base64ToBytes(string).length
+ default:
+ if (loweredCase) return utf8ToBytes(string).length // assume utf8
+ encoding = ('' + encoding).toLowerCase()
+ loweredCase = true
+ }
+ }
+}
+Buffer.byteLength = byteLength
+
+function slowToString (encoding, start, end) {
+ var loweredCase = false
+
+ start = start | 0
+ end = end === undefined || end === Infinity ? this.length : end | 0
+
+ if (!encoding) encoding = 'utf8'
+ if (start < 0) start = 0
+ if (end > this.length) end = this.length
+ if (end <= start) return ''
+
+ while (true) {
+ switch (encoding) {
+ case 'hex':
+ return hexSlice(this, start, end)
+
+ case 'utf8':
+ case 'utf-8':
+ return utf8Slice(this, start, end)
+
+ case 'ascii':
+ return asciiSlice(this, start, end)
+
+ case 'binary':
+ return binarySlice(this, start, end)
+
+ case 'base64':
+ return base64Slice(this, start, end)
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return utf16leSlice(this, start, end)
+
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
+ encoding = (encoding + '').toLowerCase()
+ loweredCase = true
+ }
+ }
+}
+
+Buffer.prototype.toString = function toString () {
+ var length = this.length | 0
+ if (length === 0) return ''
+ if (arguments.length === 0) return utf8Slice(this, 0, length)
+ return slowToString.apply(this, arguments)
+}
+
+Buffer.prototype.equals = function equals (b) {
+ if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
+ if (this === b) return true
+ return Buffer.compare(this, b) === 0
+}
+
+Buffer.prototype.inspect = function inspect () {
+ var str = ''
+ var max = exports.INSPECT_MAX_BYTES
+ if (this.length > 0) {
+ str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
+ if (this.length > max) str += ' ... '
+ }
+ return ''
+}
+
+Buffer.prototype.compare = function compare (b) {
+ if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
+ if (this === b) return 0
+ return Buffer.compare(this, b)
+}
+
+Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
+ if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
+ else if (byteOffset < -0x80000000) byteOffset = -0x80000000
+ byteOffset >>= 0
+
+ if (this.length === 0) return -1
+ if (byteOffset >= this.length) return -1
+
+ // Negative offsets start from the end of the buffer
+ if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
+
+ if (typeof val === 'string') {
+ if (val.length === 0) return -1 // special case: looking for empty string always fails
+ return String.prototype.indexOf.call(this, val, byteOffset)
+ }
+ if (Buffer.isBuffer(val)) {
+ return arrayIndexOf(this, val, byteOffset)
+ }
+ if (typeof val === 'number') {
+ if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
+ return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
+ }
+ return arrayIndexOf(this, [ val ], byteOffset)
+ }
+
+ function arrayIndexOf (arr, val, byteOffset) {
+ var foundIndex = -1
+ for (var i = 0; byteOffset + i < arr.length; i++) {
+ if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
+ if (foundIndex === -1) foundIndex = i
+ if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
+ } else {
+ foundIndex = -1
+ }
+ }
+ return -1
+ }
+
+ throw new TypeError('val must be string, number or Buffer')
+}
+
+// `get` is deprecated
+Buffer.prototype.get = function get (offset) {
+ console.log('.get() is deprecated. Access using array indexes instead.')
+ return this.readUInt8(offset)
+}
+
+// `set` is deprecated
+Buffer.prototype.set = function set (v, offset) {
+ console.log('.set() is deprecated. Access using array indexes instead.')
+ return this.writeUInt8(v, offset)
+}
+
+function hexWrite (buf, string, offset, length) {
+ offset = Number(offset) || 0
+ var remaining = buf.length - offset
+ if (!length) {
+ length = remaining
+ } else {
+ length = Number(length)
+ if (length > remaining) {
+ length = remaining
+ }
+ }
+
+ // must be an even number of digits
+ var strLen = string.length
+ if (strLen % 2 !== 0) throw new Error('Invalid hex string')
+
+ if (length > strLen / 2) {
+ length = strLen / 2
+ }
+ for (var i = 0; i < length; i++) {
+ var parsed = parseInt(string.substr(i * 2, 2), 16)
+ if (isNaN(parsed)) throw new Error('Invalid hex string')
+ buf[offset + i] = parsed
+ }
+ return i
+}
+
+function utf8Write (buf, string, offset, length) {
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
+}
+
+function asciiWrite (buf, string, offset, length) {
+ return blitBuffer(asciiToBytes(string), buf, offset, length)
+}
+
+function binaryWrite (buf, string, offset, length) {
+ return asciiWrite(buf, string, offset, length)
+}
+
+function base64Write (buf, string, offset, length) {
+ return blitBuffer(base64ToBytes(string), buf, offset, length)
+}
+
+function ucs2Write (buf, string, offset, length) {
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
+}
+
+Buffer.prototype.write = function write (string, offset, length, encoding) {
+ // Buffer#write(string)
+ if (offset === undefined) {
+ encoding = 'utf8'
+ length = this.length
+ offset = 0
+ // Buffer#write(string, encoding)
+ } else if (length === undefined && typeof offset === 'string') {
+ encoding = offset
+ length = this.length
+ offset = 0
+ // Buffer#write(string, offset[, length][, encoding])
+ } else if (isFinite(offset)) {
+ offset = offset | 0
+ if (isFinite(length)) {
+ length = length | 0
+ if (encoding === undefined) encoding = 'utf8'
+ } else {
+ encoding = length
+ length = undefined
+ }
+ // legacy write(string, encoding, offset, length) - remove in v0.13
+ } else {
+ var swap = encoding
+ encoding = offset
+ offset = length | 0
+ length = swap
+ }
+
+ var remaining = this.length - offset
+ if (length === undefined || length > remaining) length = remaining
+
+ if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
+ throw new RangeError('attempt to write outside buffer bounds')
+ }
+
+ if (!encoding) encoding = 'utf8'
+
+ var loweredCase = false
+ for (;;) {
+ switch (encoding) {
+ case 'hex':
+ return hexWrite(this, string, offset, length)
+
+ case 'utf8':
+ case 'utf-8':
+ return utf8Write(this, string, offset, length)
+
+ case 'ascii':
+ return asciiWrite(this, string, offset, length)
+
+ case 'binary':
+ return binaryWrite(this, string, offset, length)
+
+ case 'base64':
+ // Warning: maxLength not taken into account in base64Write
+ return base64Write(this, string, offset, length)
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return ucs2Write(this, string, offset, length)
+
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
+ encoding = ('' + encoding).toLowerCase()
+ loweredCase = true
+ }
+ }
+}
+
+Buffer.prototype.toJSON = function toJSON () {
+ return {
+ type: 'Buffer',
+ data: Array.prototype.slice.call(this._arr || this, 0)
+ }
+}
+
+function base64Slice (buf, start, end) {
+ if (start === 0 && end === buf.length) {
+ return base64.fromByteArray(buf)
+ } else {
+ return base64.fromByteArray(buf.slice(start, end))
+ }
+}
+
+function utf8Slice (buf, start, end) {
+ end = Math.min(buf.length, end)
+ var res = []
+
+ var i = start
+ while (i < end) {
+ var firstByte = buf[i]
+ var codePoint = null
+ var bytesPerSequence = (firstByte > 0xEF) ? 4
+ : (firstByte > 0xDF) ? 3
+ : (firstByte > 0xBF) ? 2
+ : 1
+
+ if (i + bytesPerSequence <= end) {
+ var secondByte, thirdByte, fourthByte, tempCodePoint
+
+ switch (bytesPerSequence) {
+ case 1:
+ if (firstByte < 0x80) {
+ codePoint = firstByte
+ }
+ break
+ case 2:
+ secondByte = buf[i + 1]
+ if ((secondByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
+ if (tempCodePoint > 0x7F) {
+ codePoint = tempCodePoint
+ }
+ }
+ break
+ case 3:
+ secondByte = buf[i + 1]
+ thirdByte = buf[i + 2]
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
+ if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
+ codePoint = tempCodePoint
+ }
+ }
+ break
+ case 4:
+ secondByte = buf[i + 1]
+ thirdByte = buf[i + 2]
+ fourthByte = buf[i + 3]
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
+ if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
+ codePoint = tempCodePoint
+ }
+ }
+ }
+ }
+
+ if (codePoint === null) {
+ // we did not generate a valid codePoint so insert a
+ // replacement char (U+FFFD) and advance only 1 byte
+ codePoint = 0xFFFD
+ bytesPerSequence = 1
+ } else if (codePoint > 0xFFFF) {
+ // encode to utf16 (surrogate pair dance)
+ codePoint -= 0x10000
+ res.push(codePoint >>> 10 & 0x3FF | 0xD800)
+ codePoint = 0xDC00 | codePoint & 0x3FF
+ }
+
+ res.push(codePoint)
+ i += bytesPerSequence
+ }
+
+ return decodeCodePointsArray(res)
+}
+
+// Based on http://stackoverflow.com/a/22747272/680742, the browser with
+// the lowest limit is Chrome, with 0x10000 args.
+// We go 1 magnitude less, for safety
+var MAX_ARGUMENTS_LENGTH = 0x1000
+
+function decodeCodePointsArray (codePoints) {
+ var len = codePoints.length
+ if (len <= MAX_ARGUMENTS_LENGTH) {
+ return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
+ }
+
+ // Decode in chunks to avoid "call stack size exceeded".
+ var res = ''
+ var i = 0
+ while (i < len) {
+ res += String.fromCharCode.apply(
+ String,
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
+ )
+ }
+ return res
+}
+
+function asciiSlice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
+
+ for (var i = start; i < end; i++) {
+ ret += String.fromCharCode(buf[i] & 0x7F)
+ }
+ return ret
+}
+
+function binarySlice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
+
+ for (var i = start; i < end; i++) {
+ ret += String.fromCharCode(buf[i])
+ }
+ return ret
+}
+
+function hexSlice (buf, start, end) {
+ var len = buf.length
+
+ if (!start || start < 0) start = 0
+ if (!end || end < 0 || end > len) end = len
+
+ var out = ''
+ for (var i = start; i < end; i++) {
+ out += toHex(buf[i])
+ }
+ return out
+}
+
+function utf16leSlice (buf, start, end) {
+ var bytes = buf.slice(start, end)
+ var res = ''
+ for (var i = 0; i < bytes.length; i += 2) {
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
+ }
+ return res
+}
+
+Buffer.prototype.slice = function slice (start, end) {
+ var len = this.length
+ start = ~~start
+ end = end === undefined ? len : ~~end
+
+ if (start < 0) {
+ start += len
+ if (start < 0) start = 0
+ } else if (start > len) {
+ start = len
+ }
+
+ if (end < 0) {
+ end += len
+ if (end < 0) end = 0
+ } else if (end > len) {
+ end = len
+ }
+
+ if (end < start) end = start
+
+ var newBuf
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ newBuf = Buffer._augment(this.subarray(start, end))
+ } else {
+ var sliceLen = end - start
+ newBuf = new Buffer(sliceLen, undefined)
+ for (var i = 0; i < sliceLen; i++) {
+ newBuf[i] = this[i + start]
+ }
+ }
+
+ if (newBuf.length) newBuf.parent = this.parent || this
+
+ return newBuf
+}
+
+/*
+ * Need to make sure that buffer isn't trying to write out of bounds.
+ */
+function checkOffset (offset, ext, length) {
+ if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
+}
+
+Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
+ }
+
+ return val
+}
+
+Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) {
+ checkOffset(offset, byteLength, this.length)
+ }
+
+ var val = this[offset + --byteLength]
+ var mul = 1
+ while (byteLength > 0 && (mul *= 0x100)) {
+ val += this[offset + --byteLength] * mul
+ }
+
+ return val
+}
+
+Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ return this[offset]
+}
+
+Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return this[offset] | (this[offset + 1] << 8)
+}
+
+Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return (this[offset] << 8) | this[offset + 1]
+}
+
+Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return ((this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16)) +
+ (this[offset + 3] * 0x1000000)
+}
+
+Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return (this[offset] * 0x1000000) +
+ ((this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ this[offset + 3])
+}
+
+Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
+ }
+ mul *= 0x80
+
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+ return val
+}
+
+Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var i = byteLength
+ var mul = 1
+ var val = this[offset + --i]
+ while (i > 0 && (mul *= 0x100)) {
+ val += this[offset + --i] * mul
+ }
+ mul *= 0x80
+
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+ return val
+}
+
+Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ if (!(this[offset] & 0x80)) return (this[offset])
+ return ((0xff - this[offset] + 1) * -1)
+}
+
+Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ var val = this[offset] | (this[offset + 1] << 8)
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
+}
+
+Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ var val = this[offset + 1] | (this[offset] << 8)
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
+}
+
+Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return (this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16) |
+ (this[offset + 3] << 24)
+}
+
+Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return (this[offset] << 24) |
+ (this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ (this[offset + 3])
+}
+
+Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+ return ieee754.read(this, offset, true, 23, 4)
+}
+
+Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+ return ieee754.read(this, offset, false, 23, 4)
+}
+
+Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 8, this.length)
+ return ieee754.read(this, offset, true, 52, 8)
+}
+
+Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 8, this.length)
+ return ieee754.read(this, offset, false, 52, 8)
+}
+
+function checkInt (buf, value, offset, ext, max, min) {
+ if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
+ if (value > max || value < min) throw new RangeError('value is out of bounds')
+ if (offset + ext > buf.length) throw new RangeError('index out of range')
+}
+
+Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
+
+ var mul = 1
+ var i = 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
+
+ var i = byteLength - 1
+ var mul = 1
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
+ this[offset] = (value & 0xff)
+ return offset + 1
+}
+
+function objectWriteUInt16 (buf, value, offset, littleEndian) {
+ if (value < 0) value = 0xffff + value + 1
+ for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
+ buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
+ (littleEndian ? i : 1 - i) * 8
+ }
+}
+
+Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ } else {
+ objectWriteUInt16(this, value, offset, true)
+ }
+ return offset + 2
+}
+
+Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 8)
+ this[offset + 1] = (value & 0xff)
+ } else {
+ objectWriteUInt16(this, value, offset, false)
+ }
+ return offset + 2
+}
+
+function objectWriteUInt32 (buf, value, offset, littleEndian) {
+ if (value < 0) value = 0xffffffff + value + 1
+ for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
+ buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
+ }
+}
+
+Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset + 3] = (value >>> 24)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 1] = (value >>> 8)
+ this[offset] = (value & 0xff)
+ } else {
+ objectWriteUInt32(this, value, offset, true)
+ }
+ return offset + 4
+}
+
+Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = (value & 0xff)
+ } else {
+ objectWriteUInt32(this, value, offset, false)
+ }
+ return offset + 4
+}
+
+Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) {
+ var limit = Math.pow(2, 8 * byteLength - 1)
+
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
+ }
+
+ var i = 0
+ var mul = 1
+ var sub = value < 0 ? 1 : 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) {
+ var limit = Math.pow(2, 8 * byteLength - 1)
+
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
+ }
+
+ var i = byteLength - 1
+ var mul = 1
+ var sub = value < 0 ? 1 : 0
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
+ if (value < 0) value = 0xff + value + 1
+ this[offset] = (value & 0xff)
+ return offset + 1
+}
+
+Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ } else {
+ objectWriteUInt16(this, value, offset, true)
+ }
+ return offset + 2
+}
+
+Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 8)
+ this[offset + 1] = (value & 0xff)
+ } else {
+ objectWriteUInt16(this, value, offset, false)
+ }
+ return offset + 2
+}
+
+Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 3] = (value >>> 24)
+ } else {
+ objectWriteUInt32(this, value, offset, true)
+ }
+ return offset + 4
+}
+
+Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ if (value < 0) value = 0xffffffff + value + 1
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = (value & 0xff)
+ } else {
+ objectWriteUInt32(this, value, offset, false)
+ }
+ return offset + 4
+}
+
+function checkIEEE754 (buf, value, offset, ext, max, min) {
+ if (value > max || value < min) throw new RangeError('value is out of bounds')
+ if (offset + ext > buf.length) throw new RangeError('index out of range')
+ if (offset < 0) throw new RangeError('index out of range')
+}
+
+function writeFloat (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
+ }
+ ieee754.write(buf, value, offset, littleEndian, 23, 4)
+ return offset + 4
+}
+
+Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, false, noAssert)
+}
+
+function writeDouble (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
+ }
+ ieee754.write(buf, value, offset, littleEndian, 52, 8)
+ return offset + 8
+}
+
+Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, false, noAssert)
+}
+
+// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+Buffer.prototype.copy = function copy (target, targetStart, start, end) {
+ if (!start) start = 0
+ if (!end && end !== 0) end = this.length
+ if (targetStart >= target.length) targetStart = target.length
+ if (!targetStart) targetStart = 0
+ if (end > 0 && end < start) end = start
+
+ // Copy 0 bytes; we're done
+ if (end === start) return 0
+ if (target.length === 0 || this.length === 0) return 0
+
+ // Fatal error conditions
+ if (targetStart < 0) {
+ throw new RangeError('targetStart out of bounds')
+ }
+ if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
+ if (end < 0) throw new RangeError('sourceEnd out of bounds')
+
+ // Are we oob?
+ if (end > this.length) end = this.length
+ if (target.length - targetStart < end - start) {
+ end = target.length - targetStart + start
+ }
+
+ var len = end - start
+ var i
+
+ if (this === target && start < targetStart && targetStart < end) {
+ // descending copy from end
+ for (i = len - 1; i >= 0; i--) {
+ target[i + targetStart] = this[i + start]
+ }
+ } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
+ // ascending copy from start
+ for (i = 0; i < len; i++) {
+ target[i + targetStart] = this[i + start]
+ }
+ } else {
+ target._set(this.subarray(start, start + len), targetStart)
+ }
+
+ return len
+}
+
+// fill(value, start=0, end=buffer.length)
+Buffer.prototype.fill = function fill (value, start, end) {
+ if (!value) value = 0
+ if (!start) start = 0
+ if (!end) end = this.length
+
+ if (end < start) throw new RangeError('end < start')
+
+ // Fill 0 bytes; we're done
+ if (end === start) return
+ if (this.length === 0) return
+
+ if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
+ if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
+
+ var i
+ if (typeof value === 'number') {
+ for (i = start; i < end; i++) {
+ this[i] = value
+ }
+ } else {
+ var bytes = utf8ToBytes(value.toString())
+ var len = bytes.length
+ for (i = start; i < end; i++) {
+ this[i] = bytes[i % len]
+ }
+ }
+
+ return this
+}
+
+/**
+ * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
+ * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
+ */
+Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
+ if (typeof Uint8Array !== 'undefined') {
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ return (new Buffer(this)).buffer
+ } else {
+ var buf = new Uint8Array(this.length)
+ for (var i = 0, len = buf.length; i < len; i += 1) {
+ buf[i] = this[i]
+ }
+ return buf.buffer
+ }
+ } else {
+ throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
+ }
+}
+
+// HELPER FUNCTIONS
+// ================
+
+var BP = Buffer.prototype
+
+/**
+ * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
+ */
+Buffer._augment = function _augment (arr) {
+ arr.constructor = Buffer
+ arr._isBuffer = true
+
+ // save reference to original Uint8Array set method before overwriting
+ arr._set = arr.set
+
+ // deprecated
+ arr.get = BP.get
+ arr.set = BP.set
+
+ arr.write = BP.write
+ arr.toString = BP.toString
+ arr.toLocaleString = BP.toString
+ arr.toJSON = BP.toJSON
+ arr.equals = BP.equals
+ arr.compare = BP.compare
+ arr.indexOf = BP.indexOf
+ arr.copy = BP.copy
+ arr.slice = BP.slice
+ arr.readUIntLE = BP.readUIntLE
+ arr.readUIntBE = BP.readUIntBE
+ arr.readUInt8 = BP.readUInt8
+ arr.readUInt16LE = BP.readUInt16LE
+ arr.readUInt16BE = BP.readUInt16BE
+ arr.readUInt32LE = BP.readUInt32LE
+ arr.readUInt32BE = BP.readUInt32BE
+ arr.readIntLE = BP.readIntLE
+ arr.readIntBE = BP.readIntBE
+ arr.readInt8 = BP.readInt8
+ arr.readInt16LE = BP.readInt16LE
+ arr.readInt16BE = BP.readInt16BE
+ arr.readInt32LE = BP.readInt32LE
+ arr.readInt32BE = BP.readInt32BE
+ arr.readFloatLE = BP.readFloatLE
+ arr.readFloatBE = BP.readFloatBE
+ arr.readDoubleLE = BP.readDoubleLE
+ arr.readDoubleBE = BP.readDoubleBE
+ arr.writeUInt8 = BP.writeUInt8
+ arr.writeUIntLE = BP.writeUIntLE
+ arr.writeUIntBE = BP.writeUIntBE
+ arr.writeUInt16LE = BP.writeUInt16LE
+ arr.writeUInt16BE = BP.writeUInt16BE
+ arr.writeUInt32LE = BP.writeUInt32LE
+ arr.writeUInt32BE = BP.writeUInt32BE
+ arr.writeIntLE = BP.writeIntLE
+ arr.writeIntBE = BP.writeIntBE
+ arr.writeInt8 = BP.writeInt8
+ arr.writeInt16LE = BP.writeInt16LE
+ arr.writeInt16BE = BP.writeInt16BE
+ arr.writeInt32LE = BP.writeInt32LE
+ arr.writeInt32BE = BP.writeInt32BE
+ arr.writeFloatLE = BP.writeFloatLE
+ arr.writeFloatBE = BP.writeFloatBE
+ arr.writeDoubleLE = BP.writeDoubleLE
+ arr.writeDoubleBE = BP.writeDoubleBE
+ arr.fill = BP.fill
+ arr.inspect = BP.inspect
+ arr.toArrayBuffer = BP.toArrayBuffer
+
+ return arr
+}
+
+var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
+
+function base64clean (str) {
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
+ str = stringtrim(str).replace(INVALID_BASE64_RE, '')
+ // Node converts strings with length < 2 to ''
+ if (str.length < 2) return ''
+ // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
+ while (str.length % 4 !== 0) {
+ str = str + '='
+ }
+ return str
+}
+
+function stringtrim (str) {
+ if (str.trim) return str.trim()
+ return str.replace(/^\s+|\s+$/g, '')
+}
+
+function toHex (n) {
+ if (n < 16) return '0' + n.toString(16)
+ return n.toString(16)
+}
+
+function utf8ToBytes (string, units) {
+ units = units || Infinity
+ var codePoint
+ var length = string.length
+ var leadSurrogate = null
+ var bytes = []
+
+ for (var i = 0; i < length; i++) {
+ codePoint = string.charCodeAt(i)
+
+ // is surrogate component
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
+ // last char was a lead
+ if (!leadSurrogate) {
+ // no lead yet
+ if (codePoint > 0xDBFF) {
+ // unexpected trail
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
+ } else if (i + 1 === length) {
+ // unpaired lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
+ }
+
+ // valid lead
+ leadSurrogate = codePoint
+
+ continue
+ }
+
+ // 2 leads in a row
+ if (codePoint < 0xDC00) {
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ leadSurrogate = codePoint
+ continue
+ }
+
+ // valid surrogate pair
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
+ } else if (leadSurrogate) {
+ // valid bmp char, but last char was a lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ }
+
+ leadSurrogate = null
+
+ // encode utf8
+ if (codePoint < 0x80) {
+ if ((units -= 1) < 0) break
+ bytes.push(codePoint)
+ } else if (codePoint < 0x800) {
+ if ((units -= 2) < 0) break
+ bytes.push(
+ codePoint >> 0x6 | 0xC0,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x10000) {
+ if ((units -= 3) < 0) break
+ bytes.push(
+ codePoint >> 0xC | 0xE0,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x110000) {
+ if ((units -= 4) < 0) break
+ bytes.push(
+ codePoint >> 0x12 | 0xF0,
+ codePoint >> 0xC & 0x3F | 0x80,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else {
+ throw new Error('Invalid code point')
+ }
+ }
+
+ return bytes
+}
+
+function asciiToBytes (str) {
+ var byteArray = []
+ for (var i = 0; i < str.length; i++) {
+ // Node's code seems to be doing this and not & 0x7F..
+ byteArray.push(str.charCodeAt(i) & 0xFF)
+ }
+ return byteArray
+}
+
+function utf16leToBytes (str, units) {
+ var c, hi, lo
+ var byteArray = []
+ for (var i = 0; i < str.length; i++) {
+ if ((units -= 2) < 0) break
+
+ c = str.charCodeAt(i)
+ hi = c >> 8
+ lo = c % 256
+ byteArray.push(lo)
+ byteArray.push(hi)
+ }
+
+ return byteArray
+}
+
+function base64ToBytes (str) {
+ return base64.toByteArray(base64clean(str))
+}
+
+function blitBuffer (src, dst, offset, length) {
+ for (var i = 0; i < length; i++) {
+ if ((i + offset >= dst.length) || (i >= src.length)) break
+ dst[i + offset] = src[i]
+ }
+ return i
+}
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"base64-js":2,"ieee754":8,"isarray":9}],5:[function(_dereq_,module,exports){
+(function (process,global){
+/*!
+ * @overview es6-promise - a tiny implementation of Promises/A+.
+ * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
+ * @license Licensed under MIT license
+ * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
+ * @version 4.1.1
+ */
+
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global.ES6Promise = factory());
+}(this, (function () { 'use strict';
+
+function objectOrFunction(x) {
+ var type = typeof x;
+ return x !== null && (type === 'object' || type === 'function');
+}
+
+function isFunction(x) {
+ return typeof x === 'function';
+}
+
+var _isArray = undefined;
+if (Array.isArray) {
+ _isArray = Array.isArray;
+} else {
+ _isArray = function (x) {
+ return Object.prototype.toString.call(x) === '[object Array]';
+ };
+}
+
+var isArray = _isArray;
+
+var len = 0;
+var vertxNext = undefined;
+var customSchedulerFn = undefined;
+
+var asap = function asap(callback, arg) {
+ queue[len] = callback;
+ queue[len + 1] = arg;
+ len += 2;
+ if (len === 2) {
+ // If len is 2, that means that we need to schedule an async flush.
+ // If additional callbacks are queued before the queue is flushed, they
+ // will be processed by this flush that we are scheduling.
+ if (customSchedulerFn) {
+ customSchedulerFn(flush);
+ } else {
+ scheduleFlush();
+ }
+ }
+};
+
+function setScheduler(scheduleFn) {
+ customSchedulerFn = scheduleFn;
+}
+
+function setAsap(asapFn) {
+ asap = asapFn;
+}
+
+var browserWindow = typeof window !== 'undefined' ? window : undefined;
+var browserGlobal = browserWindow || {};
+var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
+var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
+
+// test for web worker but not in IE10
+var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
+
+// node
+function useNextTick() {
+ // node version 0.10.x displays a deprecation warning when nextTick is used recursively
+ // see https://github.com/cujojs/when/issues/410 for details
+ return function () {
+ return process.nextTick(flush);
+ };
+}
+
+// vertx
+function useVertxTimer() {
+ if (typeof vertxNext !== 'undefined') {
+ return function () {
+ vertxNext(flush);
+ };
+ }
+
+ return useSetTimeout();
+}
+
+function useMutationObserver() {
+ var iterations = 0;
+ var observer = new BrowserMutationObserver(flush);
+ var node = document.createTextNode('');
+ observer.observe(node, { characterData: true });
+
+ return function () {
+ node.data = iterations = ++iterations % 2;
+ };
+}
+
+// web worker
+function useMessageChannel() {
+ var channel = new MessageChannel();
+ channel.port1.onmessage = flush;
+ return function () {
+ return channel.port2.postMessage(0);
+ };
+}
+
+function useSetTimeout() {
+ // Store setTimeout reference so es6-promise will be unaffected by
+ // other code modifying setTimeout (like sinon.useFakeTimers())
+ var globalSetTimeout = setTimeout;
+ return function () {
+ return globalSetTimeout(flush, 1);
+ };
+}
+
+var queue = new Array(1000);
+function flush() {
+ for (var i = 0; i < len; i += 2) {
+ var callback = queue[i];
+ var arg = queue[i + 1];
+
+ callback(arg);
+
+ queue[i] = undefined;
+ queue[i + 1] = undefined;
+ }
+
+ len = 0;
+}
+
+function attemptVertx() {
+ try {
+ var r = _dereq_;
+ var vertx = r('vertx');
+ vertxNext = vertx.runOnLoop || vertx.runOnContext;
+ return useVertxTimer();
+ } catch (e) {
+ return useSetTimeout();
+ }
+}
+
+var scheduleFlush = undefined;
+// Decide what async method to use to triggering processing of queued callbacks:
+if (isNode) {
+ scheduleFlush = useNextTick();
+} else if (BrowserMutationObserver) {
+ scheduleFlush = useMutationObserver();
+} else if (isWorker) {
+ scheduleFlush = useMessageChannel();
+} else if (browserWindow === undefined && typeof _dereq_ === 'function') {
+ scheduleFlush = attemptVertx();
+} else {
+ scheduleFlush = useSetTimeout();
+}
+
+function then(onFulfillment, onRejection) {
+ var _arguments = arguments;
+
+ var parent = this;
+
+ var child = new this.constructor(noop);
+
+ if (child[PROMISE_ID] === undefined) {
+ makePromise(child);
+ }
+
+ var _state = parent._state;
+
+ if (_state) {
+ (function () {
+ var callback = _arguments[_state - 1];
+ asap(function () {
+ return invokeCallback(_state, child, callback, parent._result);
+ });
+ })();
+ } else {
+ subscribe(parent, child, onFulfillment, onRejection);
+ }
+
+ return child;
+}
+
+/**
+ `Promise.resolve` returns a promise that will become resolved with the
+ passed `value`. It is shorthand for the following:
+
+ ```javascript
+ let promise = new Promise(function(resolve, reject){
+ resolve(1);
+ });
+
+ promise.then(function(value){
+ // value === 1
+ });
+ ```
+
+ Instead of writing the above, your code now simply becomes the following:
+
+ ```javascript
+ let promise = Promise.resolve(1);
+
+ promise.then(function(value){
+ // value === 1
+ });
+ ```
+
+ @method resolve
+ @static
+ @param {Any} value value that the returned promise will be resolved with
+ Useful for tooling.
+ @return {Promise} a promise that will become fulfilled with the given
+ `value`
+*/
+function resolve$1(object) {
+ /*jshint validthis:true */
+ var Constructor = this;
+
+ if (object && typeof object === 'object' && object.constructor === Constructor) {
+ return object;
+ }
+
+ var promise = new Constructor(noop);
+ resolve(promise, object);
+ return promise;
+}
+
+var PROMISE_ID = Math.random().toString(36).substring(16);
+
+function noop() {}
+
+var PENDING = void 0;
+var FULFILLED = 1;
+var REJECTED = 2;
+
+var GET_THEN_ERROR = new ErrorObject();
+
+function selfFulfillment() {
+ return new TypeError("You cannot resolve a promise with itself");
+}
+
+function cannotReturnOwn() {
+ return new TypeError('A promises callback cannot return that same promise.');
+}
+
+function getThen(promise) {
+ try {
+ return promise.then;
+ } catch (error) {
+ GET_THEN_ERROR.error = error;
+ return GET_THEN_ERROR;
+ }
+}
+
+function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
+ try {
+ then$$1.call(value, fulfillmentHandler, rejectionHandler);
+ } catch (e) {
+ return e;
+ }
+}
+
+function handleForeignThenable(promise, thenable, then$$1) {
+ asap(function (promise) {
+ var sealed = false;
+ var error = tryThen(then$$1, thenable, function (value) {
+ if (sealed) {
+ return;
+ }
+ sealed = true;
+ if (thenable !== value) {
+ resolve(promise, value);
+ } else {
+ fulfill(promise, value);
+ }
+ }, function (reason) {
+ if (sealed) {
+ return;
+ }
+ sealed = true;
+
+ reject(promise, reason);
+ }, 'Settle: ' + (promise._label || ' unknown promise'));
+
+ if (!sealed && error) {
+ sealed = true;
+ reject(promise, error);
+ }
+ }, promise);
+}
+
+function handleOwnThenable(promise, thenable) {
+ if (thenable._state === FULFILLED) {
+ fulfill(promise, thenable._result);
+ } else if (thenable._state === REJECTED) {
+ reject(promise, thenable._result);
+ } else {
+ subscribe(thenable, undefined, function (value) {
+ return resolve(promise, value);
+ }, function (reason) {
+ return reject(promise, reason);
+ });
+ }
+}
+
+function handleMaybeThenable(promise, maybeThenable, then$$1) {
+ if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
+ handleOwnThenable(promise, maybeThenable);
+ } else {
+ if (then$$1 === GET_THEN_ERROR) {
+ reject(promise, GET_THEN_ERROR.error);
+ GET_THEN_ERROR.error = null;
+ } else if (then$$1 === undefined) {
+ fulfill(promise, maybeThenable);
+ } else if (isFunction(then$$1)) {
+ handleForeignThenable(promise, maybeThenable, then$$1);
+ } else {
+ fulfill(promise, maybeThenable);
+ }
+ }
+}
+
+function resolve(promise, value) {
+ if (promise === value) {
+ reject(promise, selfFulfillment());
+ } else if (objectOrFunction(value)) {
+ handleMaybeThenable(promise, value, getThen(value));
+ } else {
+ fulfill(promise, value);
+ }
+}
+
+function publishRejection(promise) {
+ if (promise._onerror) {
+ promise._onerror(promise._result);
+ }
+
+ publish(promise);
+}
+
+function fulfill(promise, value) {
+ if (promise._state !== PENDING) {
+ return;
+ }
+
+ promise._result = value;
+ promise._state = FULFILLED;
+
+ if (promise._subscribers.length !== 0) {
+ asap(publish, promise);
+ }
+}
+
+function reject(promise, reason) {
+ if (promise._state !== PENDING) {
+ return;
+ }
+ promise._state = REJECTED;
+ promise._result = reason;
+
+ asap(publishRejection, promise);
+}
+
+function subscribe(parent, child, onFulfillment, onRejection) {
+ var _subscribers = parent._subscribers;
+ var length = _subscribers.length;
+
+ parent._onerror = null;
+
+ _subscribers[length] = child;
+ _subscribers[length + FULFILLED] = onFulfillment;
+ _subscribers[length + REJECTED] = onRejection;
+
+ if (length === 0 && parent._state) {
+ asap(publish, parent);
+ }
+}
+
+function publish(promise) {
+ var subscribers = promise._subscribers;
+ var settled = promise._state;
+
+ if (subscribers.length === 0) {
+ return;
+ }
+
+ var child = undefined,
+ callback = undefined,
+ detail = promise._result;
+
+ for (var i = 0; i < subscribers.length; i += 3) {
+ child = subscribers[i];
+ callback = subscribers[i + settled];
+
+ if (child) {
+ invokeCallback(settled, child, callback, detail);
+ } else {
+ callback(detail);
+ }
+ }
+
+ promise._subscribers.length = 0;
+}
+
+function ErrorObject() {
+ this.error = null;
+}
+
+var TRY_CATCH_ERROR = new ErrorObject();
+
+function tryCatch(callback, detail) {
+ try {
+ return callback(detail);
+ } catch (e) {
+ TRY_CATCH_ERROR.error = e;
+ return TRY_CATCH_ERROR;
+ }
+}
+
+function invokeCallback(settled, promise, callback, detail) {
+ var hasCallback = isFunction(callback),
+ value = undefined,
+ error = undefined,
+ succeeded = undefined,
+ failed = undefined;
+
+ if (hasCallback) {
+ value = tryCatch(callback, detail);
+
+ if (value === TRY_CATCH_ERROR) {
+ failed = true;
+ error = value.error;
+ value.error = null;
+ } else {
+ succeeded = true;
+ }
+
+ if (promise === value) {
+ reject(promise, cannotReturnOwn());
+ return;
+ }
+ } else {
+ value = detail;
+ succeeded = true;
+ }
+
+ if (promise._state !== PENDING) {
+ // noop
+ } else if (hasCallback && succeeded) {
+ resolve(promise, value);
+ } else if (failed) {
+ reject(promise, error);
+ } else if (settled === FULFILLED) {
+ fulfill(promise, value);
+ } else if (settled === REJECTED) {
+ reject(promise, value);
+ }
+}
+
+function initializePromise(promise, resolver) {
+ try {
+ resolver(function resolvePromise(value) {
+ resolve(promise, value);
+ }, function rejectPromise(reason) {
+ reject(promise, reason);
+ });
+ } catch (e) {
+ reject(promise, e);
+ }
+}
+
+var id = 0;
+function nextId() {
+ return id++;
+}
+
+function makePromise(promise) {
+ promise[PROMISE_ID] = id++;
+ promise._state = undefined;
+ promise._result = undefined;
+ promise._subscribers = [];
+}
+
+function Enumerator$1(Constructor, input) {
+ this._instanceConstructor = Constructor;
+ this.promise = new Constructor(noop);
+
+ if (!this.promise[PROMISE_ID]) {
+ makePromise(this.promise);
+ }
+
+ if (isArray(input)) {
+ this.length = input.length;
+ this._remaining = input.length;
+
+ this._result = new Array(this.length);
+
+ if (this.length === 0) {
+ fulfill(this.promise, this._result);
+ } else {
+ this.length = this.length || 0;
+ this._enumerate(input);
+ if (this._remaining === 0) {
+ fulfill(this.promise, this._result);
+ }
+ }
+ } else {
+ reject(this.promise, validationError());
+ }
+}
+
+function validationError() {
+ return new Error('Array Methods must be provided an Array');
+}
+
+Enumerator$1.prototype._enumerate = function (input) {
+ for (var i = 0; this._state === PENDING && i < input.length; i++) {
+ this._eachEntry(input[i], i);
+ }
+};
+
+Enumerator$1.prototype._eachEntry = function (entry, i) {
+ var c = this._instanceConstructor;
+ var resolve$$1 = c.resolve;
+
+ if (resolve$$1 === resolve$1) {
+ var _then = getThen(entry);
+
+ if (_then === then && entry._state !== PENDING) {
+ this._settledAt(entry._state, i, entry._result);
+ } else if (typeof _then !== 'function') {
+ this._remaining--;
+ this._result[i] = entry;
+ } else if (c === Promise$2) {
+ var promise = new c(noop);
+ handleMaybeThenable(promise, entry, _then);
+ this._willSettleAt(promise, i);
+ } else {
+ this._willSettleAt(new c(function (resolve$$1) {
+ return resolve$$1(entry);
+ }), i);
+ }
+ } else {
+ this._willSettleAt(resolve$$1(entry), i);
+ }
+};
+
+Enumerator$1.prototype._settledAt = function (state, i, value) {
+ var promise = this.promise;
+
+ if (promise._state === PENDING) {
+ this._remaining--;
+
+ if (state === REJECTED) {
+ reject(promise, value);
+ } else {
+ this._result[i] = value;
+ }
+ }
+
+ if (this._remaining === 0) {
+ fulfill(promise, this._result);
+ }
+};
+
+Enumerator$1.prototype._willSettleAt = function (promise, i) {
+ var enumerator = this;
+
+ subscribe(promise, undefined, function (value) {
+ return enumerator._settledAt(FULFILLED, i, value);
+ }, function (reason) {
+ return enumerator._settledAt(REJECTED, i, reason);
+ });
+};
+
+/**
+ `Promise.all` accepts an array of promises, and returns a new promise which
+ is fulfilled with an array of fulfillment values for the passed promises, or
+ rejected with the reason of the first passed promise to be rejected. It casts all
+ elements of the passed iterable to promises as it runs this algorithm.
+
+ Example:
+
+ ```javascript
+ let promise1 = resolve(1);
+ let promise2 = resolve(2);
+ let promise3 = resolve(3);
+ let promises = [ promise1, promise2, promise3 ];
+
+ Promise.all(promises).then(function(array){
+ // The array here would be [ 1, 2, 3 ];
+ });
+ ```
+
+ If any of the `promises` given to `all` are rejected, the first promise
+ that is rejected will be given as an argument to the returned promises's
+ rejection handler. For example:
+
+ Example:
+
+ ```javascript
+ let promise1 = resolve(1);
+ let promise2 = reject(new Error("2"));
+ let promise3 = reject(new Error("3"));
+ let promises = [ promise1, promise2, promise3 ];
+
+ Promise.all(promises).then(function(array){
+ // Code here never runs because there are rejected promises!
+ }, function(error) {
+ // error.message === "2"
+ });
+ ```
+
+ @method all
+ @static
+ @param {Array} entries array of promises
+ @param {String} label optional string for labeling the promise.
+ Useful for tooling.
+ @return {Promise} promise that is fulfilled when all `promises` have been
+ fulfilled, or rejected if any of them become rejected.
+ @static
+*/
+function all$1(entries) {
+ return new Enumerator$1(this, entries).promise;
+}
+
+/**
+ `Promise.race` returns a new promise which is settled in the same way as the
+ first passed promise to settle.
+
+ Example:
+
+ ```javascript
+ let promise1 = new Promise(function(resolve, reject){
+ setTimeout(function(){
+ resolve('promise 1');
+ }, 200);
+ });
+
+ let promise2 = new Promise(function(resolve, reject){
+ setTimeout(function(){
+ resolve('promise 2');
+ }, 100);
+ });
+
+ Promise.race([promise1, promise2]).then(function(result){
+ // result === 'promise 2' because it was resolved before promise1
+ // was resolved.
+ });
+ ```
+
+ `Promise.race` is deterministic in that only the state of the first
+ settled promise matters. For example, even if other promises given to the
+ `promises` array argument are resolved, but the first settled promise has
+ become rejected before the other promises became fulfilled, the returned
+ promise will become rejected:
+
+ ```javascript
+ let promise1 = new Promise(function(resolve, reject){
+ setTimeout(function(){
+ resolve('promise 1');
+ }, 200);
+ });
+
+ let promise2 = new Promise(function(resolve, reject){
+ setTimeout(function(){
+ reject(new Error('promise 2'));
+ }, 100);
+ });
+
+ Promise.race([promise1, promise2]).then(function(result){
+ // Code here never runs
+ }, function(reason){
+ // reason.message === 'promise 2' because promise 2 became rejected before
+ // promise 1 became fulfilled
+ });
+ ```
+
+ An example real-world use case is implementing timeouts:
+
+ ```javascript
+ Promise.race([ajax('foo.json'), timeout(5000)])
+ ```
+
+ @method race
+ @static
+ @param {Array} promises array of promises to observe
+ Useful for tooling.
+ @return {Promise} a promise which settles in the same way as the first passed
+ promise to settle.
+*/
+function race$1(entries) {
+ /*jshint validthis:true */
+ var Constructor = this;
+
+ if (!isArray(entries)) {
+ return new Constructor(function (_, reject) {
+ return reject(new TypeError('You must pass an array to race.'));
+ });
+ } else {
+ return new Constructor(function (resolve, reject) {
+ var length = entries.length;
+ for (var i = 0; i < length; i++) {
+ Constructor.resolve(entries[i]).then(resolve, reject);
+ }
+ });
+ }
+}
+
+/**
+ `Promise.reject` returns a promise rejected with the passed `reason`.
+ It is shorthand for the following:
+
+ ```javascript
+ let promise = new Promise(function(resolve, reject){
+ reject(new Error('WHOOPS'));
+ });
+
+ promise.then(function(value){
+ // Code here doesn't run because the promise is rejected!
+ }, function(reason){
+ // reason.message === 'WHOOPS'
+ });
+ ```
+
+ Instead of writing the above, your code now simply becomes the following:
+
+ ```javascript
+ let promise = Promise.reject(new Error('WHOOPS'));
+
+ promise.then(function(value){
+ // Code here doesn't run because the promise is rejected!
+ }, function(reason){
+ // reason.message === 'WHOOPS'
+ });
+ ```
+
+ @method reject
+ @static
+ @param {Any} reason value that the returned promise will be rejected with.
+ Useful for tooling.
+ @return {Promise} a promise rejected with the given `reason`.
+*/
+function reject$1(reason) {
+ /*jshint validthis:true */
+ var Constructor = this;
+ var promise = new Constructor(noop);
+ reject(promise, reason);
+ return promise;
+}
+
+function needsResolver() {
+ throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
+}
+
+function needsNew() {
+ throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
+}
+
+/**
+ Promise objects represent the eventual result of an asynchronous operation. The
+ primary way of interacting with a promise is through its `then` method, which
+ registers callbacks to receive either a promise's eventual value or the reason
+ why the promise cannot be fulfilled.
+
+ Terminology
+ -----------
+
+ - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
+ - `thenable` is an object or function that defines a `then` method.
+ - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
+ - `exception` is a value that is thrown using the throw statement.
+ - `reason` is a value that indicates why a promise was rejected.
+ - `settled` the final resting state of a promise, fulfilled or rejected.
+
+ A promise can be in one of three states: pending, fulfilled, or rejected.
+
+ Promises that are fulfilled have a fulfillment value and are in the fulfilled
+ state. Promises that are rejected have a rejection reason and are in the
+ rejected state. A fulfillment value is never a thenable.
+
+ Promises can also be said to *resolve* a value. If this value is also a
+ promise, then the original promise's settled state will match the value's
+ settled state. So a promise that *resolves* a promise that rejects will
+ itself reject, and a promise that *resolves* a promise that fulfills will
+ itself fulfill.
+
+
+ Basic Usage:
+ ------------
+
+ ```js
+ let promise = new Promise(function(resolve, reject) {
+ // on success
+ resolve(value);
+
+ // on failure
+ reject(reason);
+ });
+
+ promise.then(function(value) {
+ // on fulfillment
+ }, function(reason) {
+ // on rejection
+ });
+ ```
+
+ Advanced Usage:
+ ---------------
+
+ Promises shine when abstracting away asynchronous interactions such as
+ `XMLHttpRequest`s.
+
+ ```js
+ function getJSON(url) {
+ return new Promise(function(resolve, reject){
+ let xhr = new XMLHttpRequest();
+
+ xhr.open('GET', url);
+ xhr.onreadystatechange = handler;
+ xhr.responseType = 'json';
+ xhr.setRequestHeader('Accept', 'application/json');
+ xhr.send();
+
+ function handler() {
+ if (this.readyState === this.DONE) {
+ if (this.status === 200) {
+ resolve(this.response);
+ } else {
+ reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
+ }
+ }
+ };
+ });
+ }
+
+ getJSON('/posts.json').then(function(json) {
+ // on fulfillment
+ }, function(reason) {
+ // on rejection
+ });
+ ```
+
+ Unlike callbacks, promises are great composable primitives.
+
+ ```js
+ Promise.all([
+ getJSON('/posts'),
+ getJSON('/comments')
+ ]).then(function(values){
+ values[0] // => postsJSON
+ values[1] // => commentsJSON
+
+ return values;
+ });
+ ```
+
+ @class Promise
+ @param {function} resolver
+ Useful for tooling.
+ @constructor
+*/
+function Promise$2(resolver) {
+ this[PROMISE_ID] = nextId();
+ this._result = this._state = undefined;
+ this._subscribers = [];
+
+ if (noop !== resolver) {
+ typeof resolver !== 'function' && needsResolver();
+ this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
+ }
+}
+
+Promise$2.all = all$1;
+Promise$2.race = race$1;
+Promise$2.resolve = resolve$1;
+Promise$2.reject = reject$1;
+Promise$2._setScheduler = setScheduler;
+Promise$2._setAsap = setAsap;
+Promise$2._asap = asap;
+
+Promise$2.prototype = {
+ constructor: Promise$2,
+
+ /**
+ The primary way of interacting with a promise is through its `then` method,
+ which registers callbacks to receive either a promise's eventual value or the
+ reason why the promise cannot be fulfilled.
+
+ ```js
+ findUser().then(function(user){
+ // user is available
+ }, function(reason){
+ // user is unavailable, and you are given the reason why
+ });
+ ```
+
+ Chaining
+ --------
+
+ The return value of `then` is itself a promise. This second, 'downstream'
+ promise is resolved with the return value of the first promise's fulfillment
+ or rejection handler, or rejected if the handler throws an exception.
+
+ ```js
+ findUser().then(function (user) {
+ return user.name;
+ }, function (reason) {
+ return 'default name';
+ }).then(function (userName) {
+ // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
+ // will be `'default name'`
+ });
+
+ findUser().then(function (user) {
+ throw new Error('Found user, but still unhappy');
+ }, function (reason) {
+ throw new Error('`findUser` rejected and we're unhappy');
+ }).then(function (value) {
+ // never reached
+ }, function (reason) {
+ // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
+ // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
+ });
+ ```
+ If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
+
+ ```js
+ findUser().then(function (user) {
+ throw new PedagogicalException('Upstream error');
+ }).then(function (value) {
+ // never reached
+ }).then(function (value) {
+ // never reached
+ }, function (reason) {
+ // The `PedgagocialException` is propagated all the way down to here
+ });
+ ```
+
+ Assimilation
+ ------------
+
+ Sometimes the value you want to propagate to a downstream promise can only be
+ retrieved asynchronously. This can be achieved by returning a promise in the
+ fulfillment or rejection handler. The downstream promise will then be pending
+ until the returned promise is settled. This is called *assimilation*.
+
+ ```js
+ findUser().then(function (user) {
+ return findCommentsByAuthor(user);
+ }).then(function (comments) {
+ // The user's comments are now available
+ });
+ ```
+
+ If the assimliated promise rejects, then the downstream promise will also reject.
+
+ ```js
+ findUser().then(function (user) {
+ return findCommentsByAuthor(user);
+ }).then(function (comments) {
+ // If `findCommentsByAuthor` fulfills, we'll have the value here
+ }, function (reason) {
+ // If `findCommentsByAuthor` rejects, we'll have the reason here
+ });
+ ```
+
+ Simple Example
+ --------------
+
+ Synchronous Example
+
+ ```javascript
+ let result;
+
+ try {
+ result = findResult();
+ // success
+ } catch(reason) {
+ // failure
+ }
+ ```
+
+ Errback Example
+
+ ```js
+ findResult(function(result, err){
+ if (err) {
+ // failure
+ } else {
+ // success
+ }
+ });
+ ```
+
+ Promise Example;
+
+ ```javascript
+ findResult().then(function(result){
+ // success
+ }, function(reason){
+ // failure
+ });
+ ```
+
+ Advanced Example
+ --------------
+
+ Synchronous Example
+
+ ```javascript
+ let author, books;
+
+ try {
+ author = findAuthor();
+ books = findBooksByAuthor(author);
+ // success
+ } catch(reason) {
+ // failure
+ }
+ ```
+
+ Errback Example
+
+ ```js
+
+ function foundBooks(books) {
+
+ }
+
+ function failure(reason) {
+
+ }
+
+ findAuthor(function(author, err){
+ if (err) {
+ failure(err);
+ // failure
+ } else {
+ try {
+ findBoooksByAuthor(author, function(books, err) {
+ if (err) {
+ failure(err);
+ } else {
+ try {
+ foundBooks(books);
+ } catch(reason) {
+ failure(reason);
+ }
+ }
+ });
+ } catch(error) {
+ failure(err);
+ }
+ // success
+ }
+ });
+ ```
+
+ Promise Example;
+
+ ```javascript
+ findAuthor().
+ then(findBooksByAuthor).
+ then(function(books){
+ // found books
+ }).catch(function(reason){
+ // something went wrong
+ });
+ ```
+
+ @method then
+ @param {Function} onFulfilled
+ @param {Function} onRejected
+ Useful for tooling.
+ @return {Promise}
+ */
+ then: then,
+
+ /**
+ `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
+ as the catch block of a try/catch statement.
+
+ ```js
+ function findAuthor(){
+ throw new Error('couldn't find that author');
+ }
+
+ // synchronous
+ try {
+ findAuthor();
+ } catch(reason) {
+ // something went wrong
+ }
+
+ // async with promises
+ findAuthor().catch(function(reason){
+ // something went wrong
+ });
+ ```
+
+ @method catch
+ @param {Function} onRejection
+ Useful for tooling.
+ @return {Promise}
+ */
+ 'catch': function _catch(onRejection) {
+ return this.then(null, onRejection);
+ }
+};
+
+/*global self*/
+function polyfill$1() {
+ var local = undefined;
+
+ if (typeof global !== 'undefined') {
+ local = global;
+ } else if (typeof self !== 'undefined') {
+ local = self;
+ } else {
+ try {
+ local = Function('return this')();
+ } catch (e) {
+ throw new Error('polyfill failed because global object is unavailable in this environment');
+ }
+ }
+
+ var P = local.Promise;
+
+ if (P) {
+ var promiseToString = null;
+ try {
+ promiseToString = Object.prototype.toString.call(P.resolve());
+ } catch (e) {
+ // silently ignored
+ }
+
+ if (promiseToString === '[object Promise]' && !P.cast) {
+ return;
+ }
+ }
+
+ local.Promise = Promise$2;
+}
+
+// Strange compat..
+Promise$2.polyfill = polyfill$1;
+Promise$2.Promise = Promise$2;
+
+return Promise$2;
+
+})));
+
+
+
+}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"_process":11}],6:[function(_dereq_,module,exports){
+(function (global, factory) {
+ if (typeof define === 'function' && define.amd) {
+ define(['exports', 'module'], factory);
+ } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
+ factory(exports, module);
+ } else {
+ var mod = {
+ exports: {}
+ };
+ factory(mod.exports, mod);
+ global.fetchJsonp = mod.exports;
+ }
+})(this, function (exports, module) {
+ 'use strict';
+
+ var defaultOptions = {
+ timeout: 5000,
+ jsonpCallback: 'callback',
+ jsonpCallbackFunction: null
+ };
+
+ function generateCallbackFunction() {
+ return 'jsonp_' + Date.now() + '_' + Math.ceil(Math.random() * 100000);
+ }
+
+ function clearFunction(functionName) {
+ // IE8 throws an exception when you try to delete a property on window
+ // http://stackoverflow.com/a/1824228/751089
+ try {
+ delete window[functionName];
+ } catch (e) {
+ window[functionName] = undefined;
+ }
+ }
+
+ function removeScript(scriptId) {
+ var script = document.getElementById(scriptId);
+ if (script) {
+ document.getElementsByTagName('head')[0].removeChild(script);
+ }
+ }
+
+ function fetchJsonp(_url) {
+ var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
+
+ // to avoid param reassign
+ var url = _url;
+ var timeout = options.timeout || defaultOptions.timeout;
+ var jsonpCallback = options.jsonpCallback || defaultOptions.jsonpCallback;
+
+ var timeoutId = undefined;
+
+ return new Promise(function (resolve, reject) {
+ var callbackFunction = options.jsonpCallbackFunction || generateCallbackFunction();
+ var scriptId = jsonpCallback + '_' + callbackFunction;
+
+ window[callbackFunction] = function (response) {
+ resolve({
+ ok: true,
+ // keep consistent with fetch API
+ json: function json() {
+ return Promise.resolve(response);
+ }
+ });
+
+ if (timeoutId) clearTimeout(timeoutId);
+
+ removeScript(scriptId);
+
+ clearFunction(callbackFunction);
+ };
+
+ // Check if the user set their own params, and if not add a ? to start a list of params
+ url += url.indexOf('?') === -1 ? '?' : '&';
+
+ var jsonpScript = document.createElement('script');
+ jsonpScript.setAttribute('src', '' + url + jsonpCallback + '=' + callbackFunction);
+ if (options.charset) {
+ jsonpScript.setAttribute('charset', options.charset);
+ }
+ jsonpScript.id = scriptId;
+ document.getElementsByTagName('head')[0].appendChild(jsonpScript);
+
+ timeoutId = setTimeout(function () {
+ reject(new Error('JSONP request to ' + _url + ' timed out'));
+
+ clearFunction(callbackFunction);
+ removeScript(scriptId);
+ window[callbackFunction] = function () {
+ clearFunction(callbackFunction);
+ };
+ }, timeout);
+
+ // Caught if got 404/500
+ jsonpScript.onerror = function () {
+ reject(new Error('JSONP request to ' + _url + ' failed'));
+
+ clearFunction(callbackFunction);
+ removeScript(scriptId);
+ if (timeoutId) clearTimeout(timeoutId);
+ };
+ });
+ }
+
+ // export as global function
+ /*
+ let local;
+ if (typeof global !== 'undefined') {
+ local = global;
+ } else if (typeof self !== 'undefined') {
+ local = self;
+ } else {
+ try {
+ local = Function('return this')();
+ } catch (e) {
+ throw new Error('polyfill failed because global object is unavailable in this environment');
+ }
+ }
+ local.fetchJsonp = fetchJsonp;
+ */
+
+ module.exports = fetchJsonp;
+});
+},{}],7:[function(_dereq_,module,exports){
+/* FileSaver.js
+ * A saveAs() FileSaver implementation.
+ * 1.3.2
+ * 2016-06-16 18:25:19
+ *
+ * By Eli Grey, http://eligrey.com
+ * License: MIT
+ * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
+ */
+
+/*global self */
+/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
+
+/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
+
+var saveAs = saveAs || (function(view) {
+ "use strict";
+ // IE <10 is explicitly unsupported
+ if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
+ return;
+ }
+ var
+ doc = view.document
+ // only get URL when necessary in case Blob.js hasn't overridden it yet
+ , get_URL = function() {
+ return view.URL || view.webkitURL || view;
+ }
+ , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
+ , can_use_save_link = "download" in save_link
+ , click = function(node) {
+ var event = new MouseEvent("click");
+ node.dispatchEvent(event);
+ }
+ , is_safari = /constructor/i.test(view.HTMLElement) || view.safari
+ , is_chrome_ios =/CriOS\/[\d]+/.test(navigator.userAgent)
+ , throw_outside = function(ex) {
+ (view.setImmediate || view.setTimeout)(function() {
+ throw ex;
+ }, 0);
+ }
+ , force_saveable_type = "application/octet-stream"
+ // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
+ , arbitrary_revoke_timeout = 1000 * 40 // in ms
+ , revoke = function(file) {
+ var revoker = function() {
+ if (typeof file === "string") { // file is an object URL
+ get_URL().revokeObjectURL(file);
+ } else { // file is a File
+ file.remove();
+ }
+ };
+ setTimeout(revoker, arbitrary_revoke_timeout);
+ }
+ , dispatch = function(filesaver, event_types, event) {
+ event_types = [].concat(event_types);
+ var i = event_types.length;
+ while (i--) {
+ var listener = filesaver["on" + event_types[i]];
+ if (typeof listener === "function") {
+ try {
+ listener.call(filesaver, event || filesaver);
+ } catch (ex) {
+ throw_outside(ex);
+ }
+ }
+ }
+ }
+ , auto_bom = function(blob) {
+ // prepend BOM for UTF-8 XML and text/* types (including HTML)
+ // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
+ if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
+ return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
+ }
+ return blob;
+ }
+ , FileSaver = function(blob, name, no_auto_bom) {
+ if (!no_auto_bom) {
+ blob = auto_bom(blob);
+ }
+ // First try a.download, then web filesystem, then object URLs
+ var
+ filesaver = this
+ , type = blob.type
+ , force = type === force_saveable_type
+ , object_url
+ , dispatch_all = function() {
+ dispatch(filesaver, "writestart progress write writeend".split(" "));
+ }
+ // on any filesys errors revert to saving with object URLs
+ , fs_error = function() {
+ if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
+ // Safari doesn't allow downloading of blob urls
+ var reader = new FileReader();
+ reader.onloadend = function() {
+ var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
+ var popup = view.open(url, '_blank');
+ if(!popup) view.location.href = url;
+ url=undefined; // release reference before dispatching
+ filesaver.readyState = filesaver.DONE;
+ dispatch_all();
+ };
+ reader.readAsDataURL(blob);
+ filesaver.readyState = filesaver.INIT;
+ return;
+ }
+ // don't create more object URLs than needed
+ if (!object_url) {
+ object_url = get_URL().createObjectURL(blob);
+ }
+ if (force) {
+ view.location.href = object_url;
+ } else {
+ var opened = view.open(object_url, "_blank");
+ if (!opened) {
+ // Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
+ view.location.href = object_url;
+ }
+ }
+ filesaver.readyState = filesaver.DONE;
+ dispatch_all();
+ revoke(object_url);
+ }
+ ;
+ filesaver.readyState = filesaver.INIT;
+
+ if (can_use_save_link) {
+ object_url = get_URL().createObjectURL(blob);
+ setTimeout(function() {
+ save_link.href = object_url;
+ save_link.download = name;
+ click(save_link);
+ dispatch_all();
+ revoke(object_url);
+ filesaver.readyState = filesaver.DONE;
+ });
+ return;
+ }
+
+ fs_error();
+ }
+ , FS_proto = FileSaver.prototype
+ , saveAs = function(blob, name, no_auto_bom) {
+ return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
+ }
+ ;
+ // IE 10+ (native saveAs)
+ if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
+ return function(blob, name, no_auto_bom) {
+ name = name || blob.name || "download";
+
+ if (!no_auto_bom) {
+ blob = auto_bom(blob);
+ }
+ return navigator.msSaveOrOpenBlob(blob, name);
+ };
+ }
+
+ FS_proto.abort = function(){};
+ FS_proto.readyState = FS_proto.INIT = 0;
+ FS_proto.WRITING = 1;
+ FS_proto.DONE = 2;
+
+ FS_proto.error =
+ FS_proto.onwritestart =
+ FS_proto.onprogress =
+ FS_proto.onwrite =
+ FS_proto.onabort =
+ FS_proto.onerror =
+ FS_proto.onwriteend =
+ null;
+
+ return saveAs;
+}(
+ typeof self !== "undefined" && self
+ || typeof window !== "undefined" && window
+ || this.content
+));
+// `self` is undefined in Firefox for Android content script context
+// while `this` is nsIContentFrameMessageManager
+// with an attribute `content` that corresponds to the window
+
+if (typeof module !== "undefined" && module.exports) {
+ module.exports.saveAs = saveAs;
+} else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
+ define("FileSaver.js", function() {
+ return saveAs;
+ });
+}
+
+},{}],8:[function(_dereq_,module,exports){
+exports.read = function (buffer, offset, isLE, mLen, nBytes) {
+ var e, m
+ var eLen = nBytes * 8 - mLen - 1
+ var eMax = (1 << eLen) - 1
+ var eBias = eMax >> 1
+ var nBits = -7
+ var i = isLE ? (nBytes - 1) : 0
+ var d = isLE ? -1 : 1
+ var s = buffer[offset + i]
+
+ i += d
+
+ e = s & ((1 << (-nBits)) - 1)
+ s >>= (-nBits)
+ nBits += eLen
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+
+ m = e & ((1 << (-nBits)) - 1)
+ e >>= (-nBits)
+ nBits += mLen
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+
+ if (e === 0) {
+ e = 1 - eBias
+ } else if (e === eMax) {
+ return m ? NaN : ((s ? -1 : 1) * Infinity)
+ } else {
+ m = m + Math.pow(2, mLen)
+ e = e - eBias
+ }
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
+}
+
+exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
+ var e, m, c
+ var eLen = nBytes * 8 - mLen - 1
+ var eMax = (1 << eLen) - 1
+ var eBias = eMax >> 1
+ var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
+ var i = isLE ? 0 : (nBytes - 1)
+ var d = isLE ? 1 : -1
+ var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
+
+ value = Math.abs(value)
+
+ if (isNaN(value) || value === Infinity) {
+ m = isNaN(value) ? 1 : 0
+ e = eMax
+ } else {
+ e = Math.floor(Math.log(value) / Math.LN2)
+ if (value * (c = Math.pow(2, -e)) < 1) {
+ e--
+ c *= 2
+ }
+ if (e + eBias >= 1) {
+ value += rt / c
+ } else {
+ value += rt * Math.pow(2, 1 - eBias)
+ }
+ if (value * c >= 2) {
+ e++
+ c /= 2
+ }
+
+ if (e + eBias >= eMax) {
+ m = 0
+ e = eMax
+ } else if (e + eBias >= 1) {
+ m = (value * c - 1) * Math.pow(2, mLen)
+ e = e + eBias
+ } else {
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
+ e = 0
+ }
+ }
+
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
+
+ e = (e << mLen) | m
+ eLen += mLen
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
+
+ buffer[offset + i - d] |= s * 128
+}
+
+},{}],9:[function(_dereq_,module,exports){
+var toString = {}.toString;
+
+module.exports = Array.isArray || function (arr) {
+ return toString.call(arr) == '[object Array]';
+};
+
+},{}],10:[function(_dereq_,module,exports){
+(function (Buffer){
+/**
+ * https://opentype.js.org v0.7.3 | (c) Frederik De Bleser and other contributors | MIT License | Uses tiny-inflate by Devon Govett
+ */
+
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
+ (factory((global.opentype = global.opentype || {})));
+}(this, (function (exports) { 'use strict';
+
+var TINF_OK = 0;
+var TINF_DATA_ERROR = -3;
+
+function Tree() {
+ this.table = new Uint16Array(16); /* table of code length counts */
+ this.trans = new Uint16Array(288); /* code -> symbol translation table */
+}
+
+function Data(source, dest) {
+ this.source = source;
+ this.sourceIndex = 0;
+ this.tag = 0;
+ this.bitcount = 0;
+
+ this.dest = dest;
+ this.destLen = 0;
+
+ this.ltree = new Tree(); /* dynamic length/symbol tree */
+ this.dtree = new Tree(); /* dynamic distance tree */
+}
+
+/* --------------------------------------------------- *
+ * -- uninitialized global data (static structures) -- *
+ * --------------------------------------------------- */
+
+var sltree = new Tree();
+var sdtree = new Tree();
+
+/* extra bits and base tables for length codes */
+var length_bits = new Uint8Array(30);
+var length_base = new Uint16Array(30);
+
+/* extra bits and base tables for distance codes */
+var dist_bits = new Uint8Array(30);
+var dist_base = new Uint16Array(30);
+
+/* special ordering of code length codes */
+var clcidx = new Uint8Array([
+ 16, 17, 18, 0, 8, 7, 9, 6,
+ 10, 5, 11, 4, 12, 3, 13, 2,
+ 14, 1, 15
+]);
+
+/* used by tinf_decode_trees, avoids allocations every call */
+var code_tree = new Tree();
+var lengths = new Uint8Array(288 + 32);
+
+/* ----------------------- *
+ * -- utility functions -- *
+ * ----------------------- */
+
+/* build extra bits and base tables */
+function tinf_build_bits_base(bits, base, delta, first) {
+ var i, sum;
+
+ /* build bits table */
+ for (i = 0; i < delta; ++i) { bits[i] = 0; }
+ for (i = 0; i < 30 - delta; ++i) { bits[i + delta] = i / delta | 0; }
+
+ /* build base table */
+ for (sum = first, i = 0; i < 30; ++i) {
+ base[i] = sum;
+ sum += 1 << bits[i];
+ }
+}
+
+/* build the fixed huffman trees */
+function tinf_build_fixed_trees(lt, dt) {
+ var i;
+
+ /* build fixed length tree */
+ for (i = 0; i < 7; ++i) { lt.table[i] = 0; }
+
+ lt.table[7] = 24;
+ lt.table[8] = 152;
+ lt.table[9] = 112;
+
+ for (i = 0; i < 24; ++i) { lt.trans[i] = 256 + i; }
+ for (i = 0; i < 144; ++i) { lt.trans[24 + i] = i; }
+ for (i = 0; i < 8; ++i) { lt.trans[24 + 144 + i] = 280 + i; }
+ for (i = 0; i < 112; ++i) { lt.trans[24 + 144 + 8 + i] = 144 + i; }
+
+ /* build fixed distance tree */
+ for (i = 0; i < 5; ++i) { dt.table[i] = 0; }
+
+ dt.table[5] = 32;
+
+ for (i = 0; i < 32; ++i) { dt.trans[i] = i; }
+}
+
+/* given an array of code lengths, build a tree */
+var offs = new Uint16Array(16);
+
+function tinf_build_tree(t, lengths, off, num) {
+ var i, sum;
+
+ /* clear code length count table */
+ for (i = 0; i < 16; ++i) { t.table[i] = 0; }
+
+ /* scan symbol lengths, and sum code length counts */
+ for (i = 0; i < num; ++i) { t.table[lengths[off + i]]++; }
+
+ t.table[0] = 0;
+
+ /* compute offset table for distribution sort */
+ for (sum = 0, i = 0; i < 16; ++i) {
+ offs[i] = sum;
+ sum += t.table[i];
+ }
+
+ /* create code->symbol translation table (symbols sorted by code) */
+ for (i = 0; i < num; ++i) {
+ if (lengths[off + i]) { t.trans[offs[lengths[off + i]]++] = i; }
+ }
+}
+
+/* ---------------------- *
+ * -- decode functions -- *
+ * ---------------------- */
+
+/* get one bit from source stream */
+function tinf_getbit(d) {
+ /* check if tag is empty */
+ if (!d.bitcount--) {
+ /* load next tag */
+ d.tag = d.source[d.sourceIndex++];
+ d.bitcount = 7;
+ }
+
+ /* shift bit out of tag */
+ var bit = d.tag & 1;
+ d.tag >>>= 1;
+
+ return bit;
+}
+
+/* read a num bit value from a stream and add base */
+function tinf_read_bits(d, num, base) {
+ if (!num)
+ { return base; }
+
+ while (d.bitcount < 24) {
+ d.tag |= d.source[d.sourceIndex++] << d.bitcount;
+ d.bitcount += 8;
+ }
+
+ var val = d.tag & (0xffff >>> (16 - num));
+ d.tag >>>= num;
+ d.bitcount -= num;
+ return val + base;
+}
+
+/* given a data stream and a tree, decode a symbol */
+function tinf_decode_symbol(d, t) {
+ while (d.bitcount < 24) {
+ d.tag |= d.source[d.sourceIndex++] << d.bitcount;
+ d.bitcount += 8;
+ }
+
+ var sum = 0, cur = 0, len = 0;
+ var tag = d.tag;
+
+ /* get more bits while code value is above sum */
+ do {
+ cur = 2 * cur + (tag & 1);
+ tag >>>= 1;
+ ++len;
+
+ sum += t.table[len];
+ cur -= t.table[len];
+ } while (cur >= 0);
+
+ d.tag = tag;
+ d.bitcount -= len;
+
+ return t.trans[sum + cur];
+}
+
+/* given a data stream, decode dynamic trees from it */
+function tinf_decode_trees(d, lt, dt) {
+ var hlit, hdist, hclen;
+ var i, num, length;
+
+ /* get 5 bits HLIT (257-286) */
+ hlit = tinf_read_bits(d, 5, 257);
+
+ /* get 5 bits HDIST (1-32) */
+ hdist = tinf_read_bits(d, 5, 1);
+
+ /* get 4 bits HCLEN (4-19) */
+ hclen = tinf_read_bits(d, 4, 4);
+
+ for (i = 0; i < 19; ++i) { lengths[i] = 0; }
+
+ /* read code lengths for code length alphabet */
+ for (i = 0; i < hclen; ++i) {
+ /* get 3 bits code length (0-7) */
+ var clen = tinf_read_bits(d, 3, 0);
+ lengths[clcidx[i]] = clen;
+ }
+
+ /* build code length tree */
+ tinf_build_tree(code_tree, lengths, 0, 19);
+
+ /* decode code lengths for the dynamic trees */
+ for (num = 0; num < hlit + hdist;) {
+ var sym = tinf_decode_symbol(d, code_tree);
+
+ switch (sym) {
+ case 16:
+ /* copy previous code length 3-6 times (read 2 bits) */
+ var prev = lengths[num - 1];
+ for (length = tinf_read_bits(d, 2, 3); length; --length) {
+ lengths[num++] = prev;
+ }
+ break;
+ case 17:
+ /* repeat code length 0 for 3-10 times (read 3 bits) */
+ for (length = tinf_read_bits(d, 3, 3); length; --length) {
+ lengths[num++] = 0;
+ }
+ break;
+ case 18:
+ /* repeat code length 0 for 11-138 times (read 7 bits) */
+ for (length = tinf_read_bits(d, 7, 11); length; --length) {
+ lengths[num++] = 0;
+ }
+ break;
+ default:
+ /* values 0-15 represent the actual code lengths */
+ lengths[num++] = sym;
+ break;
+ }
+ }
+
+ /* build dynamic trees */
+ tinf_build_tree(lt, lengths, 0, hlit);
+ tinf_build_tree(dt, lengths, hlit, hdist);
+}
+
+/* ----------------------------- *
+ * -- block inflate functions -- *
+ * ----------------------------- */
+
+/* given a stream and two trees, inflate a block of data */
+function tinf_inflate_block_data(d, lt, dt) {
+ while (1) {
+ var sym = tinf_decode_symbol(d, lt);
+
+ /* check for end of block */
+ if (sym === 256) {
+ return TINF_OK;
+ }
+
+ if (sym < 256) {
+ d.dest[d.destLen++] = sym;
+ } else {
+ var length, dist, offs;
+ var i;
+
+ sym -= 257;
+
+ /* possibly get more bits from length code */
+ length = tinf_read_bits(d, length_bits[sym], length_base[sym]);
+
+ dist = tinf_decode_symbol(d, dt);
+
+ /* possibly get more bits from distance code */
+ offs = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]);
+
+ /* copy match */
+ for (i = offs; i < offs + length; ++i) {
+ d.dest[d.destLen++] = d.dest[i];
+ }
+ }
+ }
+}
+
+/* inflate an uncompressed block of data */
+function tinf_inflate_uncompressed_block(d) {
+ var length, invlength;
+ var i;
+
+ /* unread from bitbuffer */
+ while (d.bitcount > 8) {
+ d.sourceIndex--;
+ d.bitcount -= 8;
+ }
+
+ /* get length */
+ length = d.source[d.sourceIndex + 1];
+ length = 256 * length + d.source[d.sourceIndex];
+
+ /* get one's complement of length */
+ invlength = d.source[d.sourceIndex + 3];
+ invlength = 256 * invlength + d.source[d.sourceIndex + 2];
+
+ /* check length */
+ if (length !== (~invlength & 0x0000ffff))
+ { return TINF_DATA_ERROR; }
+
+ d.sourceIndex += 4;
+
+ /* copy block */
+ for (i = length; i; --i)
+ { d.dest[d.destLen++] = d.source[d.sourceIndex++]; }
+
+ /* make sure we start next block on a byte boundary */
+ d.bitcount = 0;
+
+ return TINF_OK;
+}
+
+/* inflate stream from source to dest */
+function tinf_uncompress(source, dest) {
+ var d = new Data(source, dest);
+ var bfinal, btype, res;
+
+ do {
+ /* read final block flag */
+ bfinal = tinf_getbit(d);
+
+ /* read block type (2 bits) */
+ btype = tinf_read_bits(d, 2, 0);
+
+ /* decompress block */
+ switch (btype) {
+ case 0:
+ /* decompress uncompressed block */
+ res = tinf_inflate_uncompressed_block(d);
+ break;
+ case 1:
+ /* decompress block with fixed huffman trees */
+ res = tinf_inflate_block_data(d, sltree, sdtree);
+ break;
+ case 2:
+ /* decompress block with dynamic huffman trees */
+ tinf_decode_trees(d, d.ltree, d.dtree);
+ res = tinf_inflate_block_data(d, d.ltree, d.dtree);
+ break;
+ default:
+ res = TINF_DATA_ERROR;
+ }
+
+ if (res !== TINF_OK)
+ { throw new Error('Data error'); }
+
+ } while (!bfinal);
+
+ if (d.destLen < d.dest.length) {
+ if (typeof d.dest.slice === 'function')
+ { return d.dest.slice(0, d.destLen); }
+ else
+ { return d.dest.subarray(0, d.destLen); }
+ }
+
+ return d.dest;
+}
+
+/* -------------------- *
+ * -- initialization -- *
+ * -------------------- */
+
+/* build fixed huffman trees */
+tinf_build_fixed_trees(sltree, sdtree);
+
+/* build extra bits and base tables */
+tinf_build_bits_base(length_bits, length_base, 4, 3);
+tinf_build_bits_base(dist_bits, dist_base, 2, 1);
+
+/* fix a special case */
+length_bits[28] = 0;
+length_base[28] = 258;
+
+var index = tinf_uncompress;
+
+// The Bounding Box object
+
+function derive(v0, v1, v2, v3, t) {
+ return Math.pow(1 - t, 3) * v0 +
+ 3 * Math.pow(1 - t, 2) * t * v1 +
+ 3 * (1 - t) * Math.pow(t, 2) * v2 +
+ Math.pow(t, 3) * v3;
+}
+/**
+ * A bounding box is an enclosing box that describes the smallest measure within which all the points lie.
+ * It is used to calculate the bounding box of a glyph or text path.
+ *
+ * On initialization, x1/y1/x2/y2 will be NaN. Check if the bounding box is empty using `isEmpty()`.
+ *
+ * @exports opentype.BoundingBox
+ * @class
+ * @constructor
+ */
+function BoundingBox() {
+ this.x1 = Number.NaN;
+ this.y1 = Number.NaN;
+ this.x2 = Number.NaN;
+ this.y2 = Number.NaN;
+}
+
+/**
+ * Returns true if the bounding box is empty, that is, no points have been added to the box yet.
+ */
+BoundingBox.prototype.isEmpty = function() {
+ return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2);
+};
+
+/**
+ * Add the point to the bounding box.
+ * The x1/y1/x2/y2 coordinates of the bounding box will now encompass the given point.
+ * @param {number} x - The X coordinate of the point.
+ * @param {number} y - The Y coordinate of the point.
+ */
+BoundingBox.prototype.addPoint = function(x, y) {
+ if (typeof x === 'number') {
+ if (isNaN(this.x1) || isNaN(this.x2)) {
+ this.x1 = x;
+ this.x2 = x;
+ }
+ if (x < this.x1) {
+ this.x1 = x;
+ }
+ if (x > this.x2) {
+ this.x2 = x;
+ }
+ }
+ if (typeof y === 'number') {
+ if (isNaN(this.y1) || isNaN(this.y2)) {
+ this.y1 = y;
+ this.y2 = y;
+ }
+ if (y < this.y1) {
+ this.y1 = y;
+ }
+ if (y > this.y2) {
+ this.y2 = y;
+ }
+ }
+};
+
+/**
+ * Add a X coordinate to the bounding box.
+ * This extends the bounding box to include the X coordinate.
+ * This function is used internally inside of addBezier.
+ * @param {number} x - The X coordinate of the point.
+ */
+BoundingBox.prototype.addX = function(x) {
+ this.addPoint(x, null);
+};
+
+/**
+ * Add a Y coordinate to the bounding box.
+ * This extends the bounding box to include the Y coordinate.
+ * This function is used internally inside of addBezier.
+ * @param {number} y - The Y coordinate of the point.
+ */
+BoundingBox.prototype.addY = function(y) {
+ this.addPoint(null, y);
+};
+
+/**
+ * Add a Bézier curve to the bounding box.
+ * This extends the bounding box to include the entire Bézier.
+ * @param {number} x0 - The starting X coordinate.
+ * @param {number} y0 - The starting Y coordinate.
+ * @param {number} x1 - The X coordinate of the first control point.
+ * @param {number} y1 - The Y coordinate of the first control point.
+ * @param {number} x2 - The X coordinate of the second control point.
+ * @param {number} y2 - The Y coordinate of the second control point.
+ * @param {number} x - The ending X coordinate.
+ * @param {number} y - The ending Y coordinate.
+ */
+BoundingBox.prototype.addBezier = function(x0, y0, x1, y1, x2, y2, x, y) {
+ var this$1 = this;
+
+ // This code is based on http://nishiohirokazu.blogspot.com/2009/06/how-to-calculate-bezier-curves-bounding.html
+ // and https://github.com/icons8/svg-path-bounding-box
+
+ var p0 = [x0, y0];
+ var p1 = [x1, y1];
+ var p2 = [x2, y2];
+ var p3 = [x, y];
+
+ this.addPoint(x0, y0);
+ this.addPoint(x, y);
+
+ for (var i = 0; i <= 1; i++) {
+ var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
+ var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
+ var c = 3 * p1[i] - 3 * p0[i];
+
+ if (a === 0) {
+ if (b === 0) { continue; }
+ var t = -c / b;
+ if (0 < t && t < 1) {
+ if (i === 0) { this$1.addX(derive(p0[i], p1[i], p2[i], p3[i], t)); }
+ if (i === 1) { this$1.addY(derive(p0[i], p1[i], p2[i], p3[i], t)); }
+ }
+ continue;
+ }
+
+ var b2ac = Math.pow(b, 2) - 4 * c * a;
+ if (b2ac < 0) { continue; }
+ var t1 = (-b + Math.sqrt(b2ac)) / (2 * a);
+ if (0 < t1 && t1 < 1) {
+ if (i === 0) { this$1.addX(derive(p0[i], p1[i], p2[i], p3[i], t1)); }
+ if (i === 1) { this$1.addY(derive(p0[i], p1[i], p2[i], p3[i], t1)); }
+ }
+ var t2 = (-b - Math.sqrt(b2ac)) / (2 * a);
+ if (0 < t2 && t2 < 1) {
+ if (i === 0) { this$1.addX(derive(p0[i], p1[i], p2[i], p3[i], t2)); }
+ if (i === 1) { this$1.addY(derive(p0[i], p1[i], p2[i], p3[i], t2)); }
+ }
+ }
+};
+
+/**
+ * Add a quadratic curve to the bounding box.
+ * This extends the bounding box to include the entire quadratic curve.
+ * @param {number} x0 - The starting X coordinate.
+ * @param {number} y0 - The starting Y coordinate.
+ * @param {number} x1 - The X coordinate of the control point.
+ * @param {number} y1 - The Y coordinate of the control point.
+ * @param {number} x - The ending X coordinate.
+ * @param {number} y - The ending Y coordinate.
+ */
+BoundingBox.prototype.addQuad = function(x0, y0, x1, y1, x, y) {
+ var cp1x = x0 + 2 / 3 * (x1 - x0);
+ var cp1y = y0 + 2 / 3 * (y1 - y0);
+ var cp2x = cp1x + 1 / 3 * (x - x0);
+ var cp2y = cp1y + 1 / 3 * (y - y0);
+ this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y);
+};
+
+// Geometric objects
+
+/**
+ * A bézier path containing a set of path commands similar to a SVG path.
+ * Paths can be drawn on a context using `draw`.
+ * @exports opentype.Path
+ * @class
+ * @constructor
+ */
+function Path() {
+ this.commands = [];
+ this.fill = 'black';
+ this.stroke = null;
+ this.strokeWidth = 1;
+}
+
+/**
+ * @param {number} x
+ * @param {number} y
+ */
+Path.prototype.moveTo = function(x, y) {
+ this.commands.push({
+ type: 'M',
+ x: x,
+ y: y
+ });
+};
+
+/**
+ * @param {number} x
+ * @param {number} y
+ */
+Path.prototype.lineTo = function(x, y) {
+ this.commands.push({
+ type: 'L',
+ x: x,
+ y: y
+ });
+};
+
+/**
+ * Draws cubic curve
+ * @function
+ * curveTo
+ * @memberof opentype.Path.prototype
+ * @param {number} x1 - x of control 1
+ * @param {number} y1 - y of control 1
+ * @param {number} x2 - x of control 2
+ * @param {number} y2 - y of control 2
+ * @param {number} x - x of path point
+ * @param {number} y - y of path point
+ */
+
+/**
+ * Draws cubic curve
+ * @function
+ * bezierCurveTo
+ * @memberof opentype.Path.prototype
+ * @param {number} x1 - x of control 1
+ * @param {number} y1 - y of control 1
+ * @param {number} x2 - x of control 2
+ * @param {number} y2 - y of control 2
+ * @param {number} x - x of path point
+ * @param {number} y - y of path point
+ * @see curveTo
+ */
+Path.prototype.curveTo = Path.prototype.bezierCurveTo = function(x1, y1, x2, y2, x, y) {
+ this.commands.push({
+ type: 'C',
+ x1: x1,
+ y1: y1,
+ x2: x2,
+ y2: y2,
+ x: x,
+ y: y
+ });
+};
+
+/**
+ * Draws quadratic curve
+ * @function
+ * quadraticCurveTo
+ * @memberof opentype.Path.prototype
+ * @param {number} x1 - x of control
+ * @param {number} y1 - y of control
+ * @param {number} x - x of path point
+ * @param {number} y - y of path point
+ */
+
+/**
+ * Draws quadratic curve
+ * @function
+ * quadTo
+ * @memberof opentype.Path.prototype
+ * @param {number} x1 - x of control
+ * @param {number} y1 - y of control
+ * @param {number} x - x of path point
+ * @param {number} y - y of path point
+ */
+Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function(x1, y1, x, y) {
+ this.commands.push({
+ type: 'Q',
+ x1: x1,
+ y1: y1,
+ x: x,
+ y: y
+ });
+};
+
+/**
+ * Closes the path
+ * @function closePath
+ * @memberof opentype.Path.prototype
+ */
+
+/**
+ * Close the path
+ * @function close
+ * @memberof opentype.Path.prototype
+ */
+Path.prototype.close = Path.prototype.closePath = function() {
+ this.commands.push({
+ type: 'Z'
+ });
+};
+
+/**
+ * Add the given path or list of commands to the commands of this path.
+ * @param {Array} pathOrCommands - another opentype.Path, an opentype.BoundingBox, or an array of commands.
+ */
+Path.prototype.extend = function(pathOrCommands) {
+ if (pathOrCommands.commands) {
+ pathOrCommands = pathOrCommands.commands;
+ } else if (pathOrCommands instanceof BoundingBox) {
+ var box = pathOrCommands;
+ this.moveTo(box.x1, box.y1);
+ this.lineTo(box.x2, box.y1);
+ this.lineTo(box.x2, box.y2);
+ this.lineTo(box.x1, box.y2);
+ this.close();
+ return;
+ }
+
+ Array.prototype.push.apply(this.commands, pathOrCommands);
+};
+
+/**
+ * Calculate the bounding box of the path.
+ * @returns {opentype.BoundingBox}
+ */
+Path.prototype.getBoundingBox = function() {
+ var this$1 = this;
+
+ var box = new BoundingBox();
+
+ var startX = 0;
+ var startY = 0;
+ var prevX = 0;
+ var prevY = 0;
+ for (var i = 0; i < this.commands.length; i++) {
+ var cmd = this$1.commands[i];
+ switch (cmd.type) {
+ case 'M':
+ box.addPoint(cmd.x, cmd.y);
+ startX = prevX = cmd.x;
+ startY = prevY = cmd.y;
+ break;
+ case 'L':
+ box.addPoint(cmd.x, cmd.y);
+ prevX = cmd.x;
+ prevY = cmd.y;
+ break;
+ case 'Q':
+ box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y);
+ prevX = cmd.x;
+ prevY = cmd.y;
+ break;
+ case 'C':
+ box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
+ prevX = cmd.x;
+ prevY = cmd.y;
+ break;
+ case 'Z':
+ prevX = startX;
+ prevY = startY;
+ break;
+ default:
+ throw new Error('Unexpected path command ' + cmd.type);
+ }
+ }
+ if (box.isEmpty()) {
+ box.addPoint(0, 0);
+ }
+ return box;
+};
+
+/**
+ * Draw the path to a 2D context.
+ * @param {CanvasRenderingContext2D} ctx - A 2D drawing context.
+ */
+Path.prototype.draw = function(ctx) {
+ var this$1 = this;
+
+ ctx.beginPath();
+ for (var i = 0; i < this.commands.length; i += 1) {
+ var cmd = this$1.commands[i];
+ if (cmd.type === 'M') {
+ ctx.moveTo(cmd.x, cmd.y);
+ } else if (cmd.type === 'L') {
+ ctx.lineTo(cmd.x, cmd.y);
+ } else if (cmd.type === 'C') {
+ ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
+ } else if (cmd.type === 'Q') {
+ ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y);
+ } else if (cmd.type === 'Z') {
+ ctx.closePath();
+ }
+ }
+
+ if (this.fill) {
+ ctx.fillStyle = this.fill;
+ ctx.fill();
+ }
+
+ if (this.stroke) {
+ ctx.strokeStyle = this.stroke;
+ ctx.lineWidth = this.strokeWidth;
+ ctx.stroke();
+ }
+};
+
+/**
+ * Convert the Path to a string of path data instructions
+ * See http://www.w3.org/TR/SVG/paths.html#PathData
+ * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values
+ * @return {string}
+ */
+Path.prototype.toPathData = function(decimalPlaces) {
+ var this$1 = this;
+
+ decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2;
+
+ function floatToString(v) {
+ if (Math.round(v) === v) {
+ return '' + Math.round(v);
+ } else {
+ return v.toFixed(decimalPlaces);
+ }
+ }
+
+ function packValues() {
+ var arguments$1 = arguments;
+
+ var s = '';
+ for (var i = 0; i < arguments.length; i += 1) {
+ var v = arguments$1[i];
+ if (v >= 0 && i > 0) {
+ s += ' ';
+ }
+
+ s += floatToString(v);
+ }
+
+ return s;
+ }
+
+ var d = '';
+ for (var i = 0; i < this.commands.length; i += 1) {
+ var cmd = this$1.commands[i];
+ if (cmd.type === 'M') {
+ d += 'M' + packValues(cmd.x, cmd.y);
+ } else if (cmd.type === 'L') {
+ d += 'L' + packValues(cmd.x, cmd.y);
+ } else if (cmd.type === 'C') {
+ d += 'C' + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
+ } else if (cmd.type === 'Q') {
+ d += 'Q' + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y);
+ } else if (cmd.type === 'Z') {
+ d += 'Z';
+ }
+ }
+
+ return d;
+};
+
+/**
+ * Convert the path to an SVG element, as a string.
+ * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values
+ * @return {string}
+ */
+Path.prototype.toSVG = function(decimalPlaces) {
+ var svg = '';
+ return svg;
+};
+
+/**
+ * Convert the path to a DOM element.
+ * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values
+ * @return {SVGPathElement}
+ */
+Path.prototype.toDOMElement = function(decimalPlaces) {
+ var temporaryPath = this.toPathData(decimalPlaces);
+ var newPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
+
+ newPath.setAttribute('d', temporaryPath);
+
+ return newPath;
+};
+
+// Run-time checking of preconditions.
+
+function fail(message) {
+ throw new Error(message);
+}
+
+// Precondition function that checks if the given predicate is true.
+// If not, it will throw an error.
+function argument(predicate, message) {
+ if (!predicate) {
+ fail(message);
+ }
+}
+
+var check = { fail: fail, argument: argument, assert: argument };
+
+// Data types used in the OpenType font file.
+// All OpenType fonts use Motorola-style byte ordering (Big Endian)
+
+var LIMIT16 = 32768; // The limit at which a 16-bit number switches signs == 2^15
+var LIMIT32 = 2147483648; // The limit at which a 32-bit number switches signs == 2 ^ 31
+
+/**
+ * @exports opentype.decode
+ * @class
+ */
+var decode = {};
+/**
+ * @exports opentype.encode
+ * @class
+ */
+var encode = {};
+/**
+ * @exports opentype.sizeOf
+ * @class
+ */
+var sizeOf = {};
+
+// Return a function that always returns the same value.
+function constant(v) {
+ return function() {
+ return v;
+ };
+}
+
+// OpenType data types //////////////////////////////////////////////////////
+
+/**
+ * Convert an 8-bit unsigned integer to a list of 1 byte.
+ * @param {number}
+ * @returns {Array}
+ */
+encode.BYTE = function(v) {
+ check.argument(v >= 0 && v <= 255, 'Byte value should be between 0 and 255.');
+ return [v];
+};
+/**
+ * @constant
+ * @type {number}
+ */
+sizeOf.BYTE = constant(1);
+
+/**
+ * Convert a 8-bit signed integer to a list of 1 byte.
+ * @param {string}
+ * @returns {Array}
+ */
+encode.CHAR = function(v) {
+ return [v.charCodeAt(0)];
+};
+
+/**
+ * @constant
+ * @type {number}
+ */
+sizeOf.CHAR = constant(1);
+
+/**
+ * Convert an ASCII string to a list of bytes.
+ * @param {string}
+ * @returns {Array}
+ */
+encode.CHARARRAY = function(v) {
+ var b = [];
+ for (var i = 0; i < v.length; i += 1) {
+ b[i] = v.charCodeAt(i);
+ }
+
+ return b;
+};
+
+/**
+ * @param {Array}
+ * @returns {number}
+ */
+sizeOf.CHARARRAY = function(v) {
+ return v.length;
+};
+
+/**
+ * Convert a 16-bit unsigned integer to a list of 2 bytes.
+ * @param {number}
+ * @returns {Array}
+ */
+encode.USHORT = function(v) {
+ return [(v >> 8) & 0xFF, v & 0xFF];
+};
+
+/**
+ * @constant
+ * @type {number}
+ */
+sizeOf.USHORT = constant(2);
+
+/**
+ * Convert a 16-bit signed integer to a list of 2 bytes.
+ * @param {number}
+ * @returns {Array}
+ */
+encode.SHORT = function(v) {
+ // Two's complement
+ if (v >= LIMIT16) {
+ v = -(2 * LIMIT16 - v);
+ }
+
+ return [(v >> 8) & 0xFF, v & 0xFF];
+};
+
+/**
+ * @constant
+ * @type {number}
+ */
+sizeOf.SHORT = constant(2);
+
+/**
+ * Convert a 24-bit unsigned integer to a list of 3 bytes.
+ * @param {number}
+ * @returns {Array}
+ */
+encode.UINT24 = function(v) {
+ return [(v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
+};
+
+/**
+ * @constant
+ * @type {number}
+ */
+sizeOf.UINT24 = constant(3);
+
+/**
+ * Convert a 32-bit unsigned integer to a list of 4 bytes.
+ * @param {number}
+ * @returns {Array}
+ */
+encode.ULONG = function(v) {
+ return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
+};
+
+/**
+ * @constant
+ * @type {number}
+ */
+sizeOf.ULONG = constant(4);
+
+/**
+ * Convert a 32-bit unsigned integer to a list of 4 bytes.
+ * @param {number}
+ * @returns {Array}
+ */
+encode.LONG = function(v) {
+ // Two's complement
+ if (v >= LIMIT32) {
+ v = -(2 * LIMIT32 - v);
+ }
+
+ return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
+};
+
+/**
+ * @constant
+ * @type {number}
+ */
+sizeOf.LONG = constant(4);
+
+encode.FIXED = encode.ULONG;
+sizeOf.FIXED = sizeOf.ULONG;
+
+encode.FWORD = encode.SHORT;
+sizeOf.FWORD = sizeOf.SHORT;
+
+encode.UFWORD = encode.USHORT;
+sizeOf.UFWORD = sizeOf.USHORT;
+
+/**
+ * Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp.
+ * @param {number}
+ * @returns {Array}
+ */
+encode.LONGDATETIME = function(v) {
+ return [0, 0, 0, 0, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
+};
+
+/**
+ * @constant
+ * @type {number}
+ */
+sizeOf.LONGDATETIME = constant(8);
+
+/**
+ * Convert a 4-char tag to a list of 4 bytes.
+ * @param {string}
+ * @returns {Array}
+ */
+encode.TAG = function(v) {
+ check.argument(v.length === 4, 'Tag should be exactly 4 ASCII characters.');
+ return [v.charCodeAt(0),
+ v.charCodeAt(1),
+ v.charCodeAt(2),
+ v.charCodeAt(3)];
+};
+
+/**
+ * @constant
+ * @type {number}
+ */
+sizeOf.TAG = constant(4);
+
+// CFF data types ///////////////////////////////////////////////////////////
+
+encode.Card8 = encode.BYTE;
+sizeOf.Card8 = sizeOf.BYTE;
+
+encode.Card16 = encode.USHORT;
+sizeOf.Card16 = sizeOf.USHORT;
+
+encode.OffSize = encode.BYTE;
+sizeOf.OffSize = sizeOf.BYTE;
+
+encode.SID = encode.USHORT;
+sizeOf.SID = sizeOf.USHORT;
+
+// Convert a numeric operand or charstring number to a variable-size list of bytes.
+/**
+ * Convert a numeric operand or charstring number to a variable-size list of bytes.
+ * @param {number}
+ * @returns {Array}
+ */
+encode.NUMBER = function(v) {
+ if (v >= -107 && v <= 107) {
+ return [v + 139];
+ } else if (v >= 108 && v <= 1131) {
+ v = v - 108;
+ return [(v >> 8) + 247, v & 0xFF];
+ } else if (v >= -1131 && v <= -108) {
+ v = -v - 108;
+ return [(v >> 8) + 251, v & 0xFF];
+ } else if (v >= -32768 && v <= 32767) {
+ return encode.NUMBER16(v);
+ } else {
+ return encode.NUMBER32(v);
+ }
+};
+
+/**
+ * @param {number}
+ * @returns {number}
+ */
+sizeOf.NUMBER = function(v) {
+ return encode.NUMBER(v).length;
+};
+
+/**
+ * Convert a signed number between -32768 and +32767 to a three-byte value.
+ * This ensures we always use three bytes, but is not the most compact format.
+ * @param {number}
+ * @returns {Array}
+ */
+encode.NUMBER16 = function(v) {
+ return [28, (v >> 8) & 0xFF, v & 0xFF];
+};
+
+/**
+ * @constant
+ * @type {number}
+ */
+sizeOf.NUMBER16 = constant(3);
+
+/**
+ * Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value.
+ * This is useful if you want to be sure you always use four bytes,
+ * at the expense of wasting a few bytes for smaller numbers.
+ * @param {number}
+ * @returns {Array}
+ */
+encode.NUMBER32 = function(v) {
+ return [29, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
+};
+
+/**
+ * @constant
+ * @type {number}
+ */
+sizeOf.NUMBER32 = constant(5);
+
+/**
+ * @param {number}
+ * @returns {Array}
+ */
+encode.REAL = function(v) {
+ var value = v.toString();
+
+ // Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7)
+ // This code converts it back to a number without the epsilon.
+ var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
+ if (m) {
+ var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
+ value = (Math.round(v * epsilon) / epsilon).toString();
+ }
+
+ var nibbles = '';
+ for (var i = 0, ii = value.length; i < ii; i += 1) {
+ var c = value[i];
+ if (c === 'e') {
+ nibbles += value[++i] === '-' ? 'c' : 'b';
+ } else if (c === '.') {
+ nibbles += 'a';
+ } else if (c === '-') {
+ nibbles += 'e';
+ } else {
+ nibbles += c;
+ }
+ }
+
+ nibbles += (nibbles.length & 1) ? 'f' : 'ff';
+ var out = [30];
+ for (var i$1 = 0, ii$1 = nibbles.length; i$1 < ii$1; i$1 += 2) {
+ out.push(parseInt(nibbles.substr(i$1, 2), 16));
+ }
+
+ return out;
+};
+
+/**
+ * @param {number}
+ * @returns {number}
+ */
+sizeOf.REAL = function(v) {
+ return encode.REAL(v).length;
+};
+
+encode.NAME = encode.CHARARRAY;
+sizeOf.NAME = sizeOf.CHARARRAY;
+
+encode.STRING = encode.CHARARRAY;
+sizeOf.STRING = sizeOf.CHARARRAY;
+
+/**
+ * @param {DataView} data
+ * @param {number} offset
+ * @param {number} numBytes
+ * @returns {string}
+ */
+decode.UTF8 = function(data, offset, numBytes) {
+ var codePoints = [];
+ var numChars = numBytes;
+ for (var j = 0; j < numChars; j++, offset += 1) {
+ codePoints[j] = data.getUint8(offset);
+ }
+
+ return String.fromCharCode.apply(null, codePoints);
+};
+
+/**
+ * @param {DataView} data
+ * @param {number} offset
+ * @param {number} numBytes
+ * @returns {string}
+ */
+decode.UTF16 = function(data, offset, numBytes) {
+ var codePoints = [];
+ var numChars = numBytes / 2;
+ for (var j = 0; j < numChars; j++, offset += 2) {
+ codePoints[j] = data.getUint16(offset);
+ }
+
+ return String.fromCharCode.apply(null, codePoints);
+};
+
+/**
+ * Convert a JavaScript string to UTF16-BE.
+ * @param {string}
+ * @returns {Array}
+ */
+encode.UTF16 = function(v) {
+ var b = [];
+ for (var i = 0; i < v.length; i += 1) {
+ var codepoint = v.charCodeAt(i);
+ b[b.length] = (codepoint >> 8) & 0xFF;
+ b[b.length] = codepoint & 0xFF;
+ }
+
+ return b;
+};
+
+/**
+ * @param {string}
+ * @returns {number}
+ */
+sizeOf.UTF16 = function(v) {
+ return v.length * 2;
+};
+
+// Data for converting old eight-bit Macintosh encodings to Unicode.
+// This representation is optimized for decoding; encoding is slower
+// and needs more memory. The assumption is that all opentype.js users
+// want to open fonts, but saving a font will be comparatively rare
+// so it can be more expensive. Keyed by IANA character set name.
+//
+// Python script for generating these strings:
+//
+// s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)])
+// print(s.encode('utf-8'))
+/**
+ * @private
+ */
+var eightBitMacEncodings = {
+ 'x-mac-croatian': // Python: 'mac_croatian'
+ 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' +
+ '¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ',
+ 'x-mac-cyrillic': // Python: 'mac_cyrillic'
+ 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' +
+ 'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю',
+ 'x-mac-gaelic': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT
+ 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' +
+ 'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ',
+ 'x-mac-greek': // Python: 'mac_greek'
+ 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' +
+ 'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ\u00AD',
+ 'x-mac-icelandic': // Python: 'mac_iceland'
+ 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
+ '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
+ 'x-mac-inuit': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT
+ 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' +
+ 'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł',
+ 'x-mac-ce': // Python: 'mac_latin2'
+ 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' +
+ 'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ',
+ macintosh: // Python: 'mac_roman'
+ 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
+ '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
+ 'x-mac-romanian': // Python: 'mac_romanian'
+ 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' +
+ '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
+ 'x-mac-turkish': // Python: 'mac_turkish'
+ 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
+ '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ'
+};
+
+/**
+ * Decodes an old-style Macintosh string. Returns either a Unicode JavaScript
+ * string, or 'undefined' if the encoding is unsupported. For example, we do
+ * not support Chinese, Japanese or Korean because these would need large
+ * mapping tables.
+ * @param {DataView} dataView
+ * @param {number} offset
+ * @param {number} dataLength
+ * @param {string} encoding
+ * @returns {string}
+ */
+decode.MACSTRING = function(dataView, offset, dataLength, encoding) {
+ var table = eightBitMacEncodings[encoding];
+ if (table === undefined) {
+ return undefined;
+ }
+
+ var result = '';
+ for (var i = 0; i < dataLength; i++) {
+ var c = dataView.getUint8(offset + i);
+ // In all eight-bit Mac encodings, the characters 0x00..0x7F are
+ // mapped to U+0000..U+007F; we only need to look up the others.
+ if (c <= 0x7F) {
+ result += String.fromCharCode(c);
+ } else {
+ result += table[c & 0x7F];
+ }
+ }
+
+ return result;
+};
+
+// Helper function for encode.MACSTRING. Returns a dictionary for mapping
+// Unicode character codes to their 8-bit MacOS equivalent. This table
+// is not exactly a super cheap data structure, but we do not care because
+// encoding Macintosh strings is only rarely needed in typical applications.
+var macEncodingTableCache = typeof WeakMap === 'function' && new WeakMap();
+var macEncodingCacheKeys;
+var getMacEncodingTable = function (encoding) {
+ // Since we use encoding as a cache key for WeakMap, it has to be
+ // a String object and not a literal. And at least on NodeJS 2.10.1,
+ // WeakMap requires that the same String instance is passed for cache hits.
+ if (!macEncodingCacheKeys) {
+ macEncodingCacheKeys = {};
+ for (var e in eightBitMacEncodings) {
+ /*jshint -W053 */ // Suppress "Do not use String as a constructor."
+ macEncodingCacheKeys[e] = new String(e);
+ }
+ }
+
+ var cacheKey = macEncodingCacheKeys[encoding];
+ if (cacheKey === undefined) {
+ return undefined;
+ }
+
+ // We can't do "if (cache.has(key)) {return cache.get(key)}" here:
+ // since garbage collection may run at any time, it could also kick in
+ // between the calls to cache.has() and cache.get(). In that case,
+ // we would return 'undefined' even though we do support the encoding.
+ if (macEncodingTableCache) {
+ var cachedTable = macEncodingTableCache.get(cacheKey);
+ if (cachedTable !== undefined) {
+ return cachedTable;
+ }
+ }
+
+ var decodingTable = eightBitMacEncodings[encoding];
+ if (decodingTable === undefined) {
+ return undefined;
+ }
+
+ var encodingTable = {};
+ for (var i = 0; i < decodingTable.length; i++) {
+ encodingTable[decodingTable.charCodeAt(i)] = i + 0x80;
+ }
+
+ if (macEncodingTableCache) {
+ macEncodingTableCache.set(cacheKey, encodingTable);
+ }
+
+ return encodingTable;
+};
+
+/**
+ * Encodes an old-style Macintosh string. Returns a byte array upon success.
+ * If the requested encoding is unsupported, or if the input string contains
+ * a character that cannot be expressed in the encoding, the function returns
+ * 'undefined'.
+ * @param {string} str
+ * @param {string} encoding
+ * @returns {Array}
+ */
+encode.MACSTRING = function(str, encoding) {
+ var table = getMacEncodingTable(encoding);
+ if (table === undefined) {
+ return undefined;
+ }
+
+ var result = [];
+ for (var i = 0; i < str.length; i++) {
+ var c = str.charCodeAt(i);
+
+ // In all eight-bit Mac encodings, the characters 0x00..0x7F are
+ // mapped to U+0000..U+007F; we only need to look up the others.
+ if (c >= 0x80) {
+ c = table[c];
+ if (c === undefined) {
+ // str contains a Unicode character that cannot be encoded
+ // in the requested encoding.
+ return undefined;
+ }
+ }
+ result[i] = c;
+ // result.push(c);
+ }
+
+ return result;
+};
+
+/**
+ * @param {string} str
+ * @param {string} encoding
+ * @returns {number}
+ */
+sizeOf.MACSTRING = function(str, encoding) {
+ var b = encode.MACSTRING(str, encoding);
+ if (b !== undefined) {
+ return b.length;
+ } else {
+ return 0;
+ }
+};
+
+// Helper for encode.VARDELTAS
+function isByteEncodable(value) {
+ return value >= -128 && value <= 127;
+}
+
+// Helper for encode.VARDELTAS
+function encodeVarDeltaRunAsZeroes(deltas, pos, result) {
+ var runLength = 0;
+ var numDeltas = deltas.length;
+ while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) {
+ ++pos;
+ ++runLength;
+ }
+ result.push(0x80 | (runLength - 1));
+ return pos;
+}
+
+// Helper for encode.VARDELTAS
+function encodeVarDeltaRunAsBytes(deltas, offset, result) {
+ var runLength = 0;
+ var numDeltas = deltas.length;
+ var pos = offset;
+ while (pos < numDeltas && runLength < 64) {
+ var value = deltas[pos];
+ if (!isByteEncodable(value)) {
+ break;
+ }
+
+ // Within a byte-encoded run of deltas, a single zero is best
+ // stored literally as 0x00 value. However, if we have two or
+ // more zeroes in a sequence, it is better to start a new run.
+ // Fore example, the sequence of deltas [15, 15, 0, 15, 15]
+ // becomes 6 bytes (04 0F 0F 00 0F 0F) when storing the zero
+ // within the current run, but 7 bytes (01 0F 0F 80 01 0F 0F)
+ // when starting a new run.
+ if (value === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) {
+ break;
+ }
+
+ ++pos;
+ ++runLength;
+ }
+ result.push(runLength - 1);
+ for (var i = offset; i < pos; ++i) {
+ result.push((deltas[i] + 256) & 0xff);
+ }
+ return pos;
+}
+
+// Helper for encode.VARDELTAS
+function encodeVarDeltaRunAsWords(deltas, offset, result) {
+ var runLength = 0;
+ var numDeltas = deltas.length;
+ var pos = offset;
+ while (pos < numDeltas && runLength < 64) {
+ var value = deltas[pos];
+
+ // Within a word-encoded run of deltas, it is easiest to start
+ // a new run (with a different encoding) whenever we encounter
+ // a zero value. For example, the sequence [0x6666, 0, 0x7777]
+ // needs 7 bytes when storing the zero inside the current run
+ // (42 66 66 00 00 77 77), and equally 7 bytes when starting a
+ // new run (40 66 66 80 40 77 77).
+ if (value === 0) {
+ break;
+ }
+
+ // Within a word-encoded run of deltas, a single value in the
+ // range (-128..127) should be encoded within the current run
+ // because it is more compact. For example, the sequence
+ // [0x6666, 2, 0x7777] becomes 7 bytes when storing the value
+ // literally (42 66 66 00 02 77 77), but 8 bytes when starting
+ // a new run (40 66 66 00 02 40 77 77).
+ if (isByteEncodable(value) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) {
+ break;
+ }
+
+ ++pos;
+ ++runLength;
+ }
+ result.push(0x40 | (runLength - 1));
+ for (var i = offset; i < pos; ++i) {
+ var val = deltas[i];
+ result.push(((val + 0x10000) >> 8) & 0xff, (val + 0x100) & 0xff);
+ }
+ return pos;
+}
+
+/**
+ * Encode a list of variation adjustment deltas.
+ *
+ * Variation adjustment deltas are used in ‘gvar’ and ‘cvar’ tables.
+ * They indicate how points (in ‘gvar’) or values (in ‘cvar’) get adjusted
+ * when generating instances of variation fonts.
+ *
+ * @see https://www.microsoft.com/typography/otspec/gvar.htm
+ * @see https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html
+ * @param {Array}
+ * @return {Array}
+ */
+encode.VARDELTAS = function(deltas) {
+ var pos = 0;
+ var result = [];
+ while (pos < deltas.length) {
+ var value = deltas[pos];
+ if (value === 0) {
+ pos = encodeVarDeltaRunAsZeroes(deltas, pos, result);
+ } else if (value >= -128 && value <= 127) {
+ pos = encodeVarDeltaRunAsBytes(deltas, pos, result);
+ } else {
+ pos = encodeVarDeltaRunAsWords(deltas, pos, result);
+ }
+ }
+ return result;
+};
+
+// Convert a list of values to a CFF INDEX structure.
+// The values should be objects containing name / type / value.
+/**
+ * @param {Array} l
+ * @returns {Array}
+ */
+encode.INDEX = function(l) {
+ //var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data,
+ // i, v;
+ // Because we have to know which data type to use to encode the offsets,
+ // we have to go through the values twice: once to encode the data and
+ // calculate the offsets, then again to encode the offsets using the fitting data type.
+ var offset = 1; // First offset is always 1.
+ var offsets = [offset];
+ var data = [];
+ for (var i = 0; i < l.length; i += 1) {
+ var v = encode.OBJECT(l[i]);
+ Array.prototype.push.apply(data, v);
+ offset += v.length;
+ offsets.push(offset);
+ }
+
+ if (data.length === 0) {
+ return [0, 0];
+ }
+
+ var encodedOffsets = [];
+ var offSize = (1 + Math.floor(Math.log(offset) / Math.log(2)) / 8) | 0;
+ var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize];
+ for (var i$1 = 0; i$1 < offsets.length; i$1 += 1) {
+ var encodedOffset = offsetEncoder(offsets[i$1]);
+ Array.prototype.push.apply(encodedOffsets, encodedOffset);
+ }
+
+ return Array.prototype.concat(encode.Card16(l.length),
+ encode.OffSize(offSize),
+ encodedOffsets,
+ data);
+};
+
+/**
+ * @param {Array}
+ * @returns {number}
+ */
+sizeOf.INDEX = function(v) {
+ return encode.INDEX(v).length;
+};
+
+/**
+ * Convert an object to a CFF DICT structure.
+ * The keys should be numeric.
+ * The values should be objects containing name / type / value.
+ * @param {Object} m
+ * @returns {Array}
+ */
+encode.DICT = function(m) {
+ var d = [];
+ var keys = Object.keys(m);
+ var length = keys.length;
+
+ for (var i = 0; i < length; i += 1) {
+ // Object.keys() return string keys, but our keys are always numeric.
+ var k = parseInt(keys[i], 0);
+ var v = m[k];
+ // Value comes before the key.
+ d = d.concat(encode.OPERAND(v.value, v.type));
+ d = d.concat(encode.OPERATOR(k));
+ }
+
+ return d;
+};
+
+/**
+ * @param {Object}
+ * @returns {number}
+ */
+sizeOf.DICT = function(m) {
+ return encode.DICT(m).length;
+};
+
+/**
+ * @param {number}
+ * @returns {Array}
+ */
+encode.OPERATOR = function(v) {
+ if (v < 1200) {
+ return [v];
+ } else {
+ return [12, v - 1200];
+ }
+};
+
+/**
+ * @param {Array} v
+ * @param {string}
+ * @returns {Array}
+ */
+encode.OPERAND = function(v, type) {
+ var d = [];
+ if (Array.isArray(type)) {
+ for (var i = 0; i < type.length; i += 1) {
+ check.argument(v.length === type.length, 'Not enough arguments given for type' + type);
+ d = d.concat(encode.OPERAND(v[i], type[i]));
+ }
+ } else {
+ if (type === 'SID') {
+ d = d.concat(encode.NUMBER(v));
+ } else if (type === 'offset') {
+ // We make it easy for ourselves and always encode offsets as
+ // 4 bytes. This makes offset calculation for the top dict easier.
+ d = d.concat(encode.NUMBER32(v));
+ } else if (type === 'number') {
+ d = d.concat(encode.NUMBER(v));
+ } else if (type === 'real') {
+ d = d.concat(encode.REAL(v));
+ } else {
+ throw new Error('Unknown operand type ' + type);
+ // FIXME Add support for booleans
+ }
+ }
+
+ return d;
+};
+
+encode.OP = encode.BYTE;
+sizeOf.OP = sizeOf.BYTE;
+
+// memoize charstring encoding using WeakMap if available
+var wmm = typeof WeakMap === 'function' && new WeakMap();
+
+/**
+ * Convert a list of CharString operations to bytes.
+ * @param {Array}
+ * @returns {Array}
+ */
+encode.CHARSTRING = function(ops) {
+ // See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))".
+ if (wmm) {
+ var cachedValue = wmm.get(ops);
+ if (cachedValue !== undefined) {
+ return cachedValue;
+ }
+ }
+
+ var d = [];
+ var length = ops.length;
+
+ for (var i = 0; i < length; i += 1) {
+ var op = ops[i];
+ d = d.concat(encode[op.type](op.value));
+ }
+
+ if (wmm) {
+ wmm.set(ops, d);
+ }
+
+ return d;
+};
+
+/**
+ * @param {Array}
+ * @returns {number}
+ */
+sizeOf.CHARSTRING = function(ops) {
+ return encode.CHARSTRING(ops).length;
+};
+
+// Utility functions ////////////////////////////////////////////////////////
+
+/**
+ * Convert an object containing name / type / value to bytes.
+ * @param {Object}
+ * @returns {Array}
+ */
+encode.OBJECT = function(v) {
+ var encodingFunction = encode[v.type];
+ check.argument(encodingFunction !== undefined, 'No encoding function for type ' + v.type);
+ return encodingFunction(v.value);
+};
+
+/**
+ * @param {Object}
+ * @returns {number}
+ */
+sizeOf.OBJECT = function(v) {
+ var sizeOfFunction = sizeOf[v.type];
+ check.argument(sizeOfFunction !== undefined, 'No sizeOf function for type ' + v.type);
+ return sizeOfFunction(v.value);
+};
+
+/**
+ * Convert a table object to bytes.
+ * A table contains a list of fields containing the metadata (name, type and default value).
+ * The table itself has the field values set as attributes.
+ * @param {opentype.Table}
+ * @returns {Array}
+ */
+encode.TABLE = function(table) {
+ var d = [];
+ var length = table.fields.length;
+ var subtables = [];
+ var subtableOffsets = [];
+
+ for (var i = 0; i < length; i += 1) {
+ var field = table.fields[i];
+ var encodingFunction = encode[field.type];
+ check.argument(encodingFunction !== undefined, 'No encoding function for field type ' + field.type + ' (' + field.name + ')');
+ var value = table[field.name];
+ if (value === undefined) {
+ value = field.value;
+ }
+
+ var bytes = encodingFunction(value);
+
+ if (field.type === 'TABLE') {
+ subtableOffsets.push(d.length);
+ d = d.concat([0, 0]);
+ subtables.push(bytes);
+ } else {
+ d = d.concat(bytes);
+ }
+ }
+
+ for (var i$1 = 0; i$1 < subtables.length; i$1 += 1) {
+ var o = subtableOffsets[i$1];
+ var offset = d.length;
+ check.argument(offset < 65536, 'Table ' + table.tableName + ' too big.');
+ d[o] = offset >> 8;
+ d[o + 1] = offset & 0xff;
+ d = d.concat(subtables[i$1]);
+ }
+
+ return d;
+};
+
+/**
+ * @param {opentype.Table}
+ * @returns {number}
+ */
+sizeOf.TABLE = function(table) {
+ var numBytes = 0;
+ var length = table.fields.length;
+
+ for (var i = 0; i < length; i += 1) {
+ var field = table.fields[i];
+ var sizeOfFunction = sizeOf[field.type];
+ check.argument(sizeOfFunction !== undefined, 'No sizeOf function for field type ' + field.type + ' (' + field.name + ')');
+ var value = table[field.name];
+ if (value === undefined) {
+ value = field.value;
+ }
+
+ numBytes += sizeOfFunction(value);
+
+ // Subtables take 2 more bytes for offsets.
+ if (field.type === 'TABLE') {
+ numBytes += 2;
+ }
+ }
+
+ return numBytes;
+};
+
+encode.RECORD = encode.TABLE;
+sizeOf.RECORD = sizeOf.TABLE;
+
+// Merge in a list of bytes.
+encode.LITERAL = function(v) {
+ return v;
+};
+
+sizeOf.LITERAL = function(v) {
+ return v.length;
+};
+
+// Table metadata
+
+/**
+ * @exports opentype.Table
+ * @class
+ * @param {string} tableName
+ * @param {Array} fields
+ * @param {Object} options
+ * @constructor
+ */
+function Table(tableName, fields, options) {
+ var this$1 = this;
+
+ for (var i = 0; i < fields.length; i += 1) {
+ var field = fields[i];
+ this$1[field.name] = field.value;
+ }
+
+ this.tableName = tableName;
+ this.fields = fields;
+ if (options) {
+ var optionKeys = Object.keys(options);
+ for (var i$1 = 0; i$1 < optionKeys.length; i$1 += 1) {
+ var k = optionKeys[i$1];
+ var v = options[k];
+ if (this$1[k] !== undefined) {
+ this$1[k] = v;
+ }
+ }
+ }
+}
+
+/**
+ * Encodes the table and returns an array of bytes
+ * @return {Array}
+ */
+Table.prototype.encode = function() {
+ return encode.TABLE(this);
+};
+
+/**
+ * Get the size of the table.
+ * @return {number}
+ */
+Table.prototype.sizeOf = function() {
+ return sizeOf.TABLE(this);
+};
+
+/**
+ * @private
+ */
+function ushortList(itemName, list, count) {
+ if (count === undefined) {
+ count = list.length;
+ }
+ var fields = new Array(list.length + 1);
+ fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count};
+ for (var i = 0; i < list.length; i++) {
+ fields[i + 1] = {name: itemName + i, type: 'USHORT', value: list[i]};
+ }
+ return fields;
+}
+
+/**
+ * @private
+ */
+function tableList(itemName, records, itemCallback) {
+ var count = records.length;
+ var fields = new Array(count + 1);
+ fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count};
+ for (var i = 0; i < count; i++) {
+ fields[i + 1] = {name: itemName + i, type: 'TABLE', value: itemCallback(records[i], i)};
+ }
+ return fields;
+}
+
+/**
+ * @private
+ */
+function recordList(itemName, records, itemCallback) {
+ var count = records.length;
+ var fields = [];
+ fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count};
+ for (var i = 0; i < count; i++) {
+ fields = fields.concat(itemCallback(records[i], i));
+ }
+ return fields;
+}
+
+// Common Layout Tables
+
+/**
+ * @exports opentype.Coverage
+ * @class
+ * @param {opentype.Table}
+ * @constructor
+ * @extends opentype.Table
+ */
+function Coverage(coverageTable) {
+ if (coverageTable.format === 1) {
+ Table.call(this, 'coverageTable',
+ [{name: 'coverageFormat', type: 'USHORT', value: 1}]
+ .concat(ushortList('glyph', coverageTable.glyphs))
+ );
+ } else {
+ check.assert(false, 'Can\'t create coverage table format 2 yet.');
+ }
+}
+Coverage.prototype = Object.create(Table.prototype);
+Coverage.prototype.constructor = Coverage;
+
+function ScriptList(scriptListTable) {
+ Table.call(this, 'scriptListTable',
+ recordList('scriptRecord', scriptListTable, function(scriptRecord, i) {
+ var script = scriptRecord.script;
+ var defaultLangSys = script.defaultLangSys;
+ check.assert(!!defaultLangSys, 'Unable to write GSUB: script ' + scriptRecord.tag + ' has no default language system.');
+ return [
+ {name: 'scriptTag' + i, type: 'TAG', value: scriptRecord.tag},
+ {name: 'script' + i, type: 'TABLE', value: new Table('scriptTable', [
+ {name: 'defaultLangSys', type: 'TABLE', value: new Table('defaultLangSys', [
+ {name: 'lookupOrder', type: 'USHORT', value: 0},
+ {name: 'reqFeatureIndex', type: 'USHORT', value: defaultLangSys.reqFeatureIndex}]
+ .concat(ushortList('featureIndex', defaultLangSys.featureIndexes)))}
+ ].concat(recordList('langSys', script.langSysRecords, function(langSysRecord, i) {
+ var langSys = langSysRecord.langSys;
+ return [
+ {name: 'langSysTag' + i, type: 'TAG', value: langSysRecord.tag},
+ {name: 'langSys' + i, type: 'TABLE', value: new Table('langSys', [
+ {name: 'lookupOrder', type: 'USHORT', value: 0},
+ {name: 'reqFeatureIndex', type: 'USHORT', value: langSys.reqFeatureIndex}
+ ].concat(ushortList('featureIndex', langSys.featureIndexes)))}
+ ];
+ })))}
+ ];
+ })
+ );
+}
+ScriptList.prototype = Object.create(Table.prototype);
+ScriptList.prototype.constructor = ScriptList;
+
+/**
+ * @exports opentype.FeatureList
+ * @class
+ * @param {opentype.Table}
+ * @constructor
+ * @extends opentype.Table
+ */
+function FeatureList(featureListTable) {
+ Table.call(this, 'featureListTable',
+ recordList('featureRecord', featureListTable, function(featureRecord, i) {
+ var feature = featureRecord.feature;
+ return [
+ {name: 'featureTag' + i, type: 'TAG', value: featureRecord.tag},
+ {name: 'feature' + i, type: 'TABLE', value: new Table('featureTable', [
+ {name: 'featureParams', type: 'USHORT', value: feature.featureParams} ].concat(ushortList('lookupListIndex', feature.lookupListIndexes)))}
+ ];
+ })
+ );
+}
+FeatureList.prototype = Object.create(Table.prototype);
+FeatureList.prototype.constructor = FeatureList;
+
+/**
+ * @exports opentype.LookupList
+ * @class
+ * @param {opentype.Table}
+ * @param {Object}
+ * @constructor
+ * @extends opentype.Table
+ */
+function LookupList(lookupListTable, subtableMakers) {
+ Table.call(this, 'lookupListTable', tableList('lookup', lookupListTable, function(lookupTable) {
+ var subtableCallback = subtableMakers[lookupTable.lookupType];
+ check.assert(!!subtableCallback, 'Unable to write GSUB lookup type ' + lookupTable.lookupType + ' tables.');
+ return new Table('lookupTable', [
+ {name: 'lookupType', type: 'USHORT', value: lookupTable.lookupType},
+ {name: 'lookupFlag', type: 'USHORT', value: lookupTable.lookupFlag}
+ ].concat(tableList('subtable', lookupTable.subtables, subtableCallback)));
+ }));
+}
+LookupList.prototype = Object.create(Table.prototype);
+LookupList.prototype.constructor = LookupList;
+
+// Record = same as Table, but inlined (a Table has an offset and its data is further in the stream)
+// Don't use offsets inside Records (probable bug), only in Tables.
+var table = {
+ Table: Table,
+ Record: Table,
+ Coverage: Coverage,
+ ScriptList: ScriptList,
+ FeatureList: FeatureList,
+ LookupList: LookupList,
+ ushortList: ushortList,
+ tableList: tableList,
+ recordList: recordList,
+};
+
+// Parsing utility functions
+
+// Retrieve an unsigned byte from the DataView.
+function getByte(dataView, offset) {
+ return dataView.getUint8(offset);
+}
+
+// Retrieve an unsigned 16-bit short from the DataView.
+// The value is stored in big endian.
+function getUShort(dataView, offset) {
+ return dataView.getUint16(offset, false);
+}
+
+// Retrieve a signed 16-bit short from the DataView.
+// The value is stored in big endian.
+function getShort(dataView, offset) {
+ return dataView.getInt16(offset, false);
+}
+
+// Retrieve an unsigned 32-bit long from the DataView.
+// The value is stored in big endian.
+function getULong(dataView, offset) {
+ return dataView.getUint32(offset, false);
+}
+
+// Retrieve a 32-bit signed fixed-point number (16.16) from the DataView.
+// The value is stored in big endian.
+function getFixed(dataView, offset) {
+ var decimal = dataView.getInt16(offset, false);
+ var fraction = dataView.getUint16(offset + 2, false);
+ return decimal + fraction / 65535;
+}
+
+// Retrieve a 4-character tag from the DataView.
+// Tags are used to identify tables.
+function getTag(dataView, offset) {
+ var tag = '';
+ for (var i = offset; i < offset + 4; i += 1) {
+ tag += String.fromCharCode(dataView.getInt8(i));
+ }
+
+ return tag;
+}
+
+// Retrieve an offset from the DataView.
+// Offsets are 1 to 4 bytes in length, depending on the offSize argument.
+function getOffset(dataView, offset, offSize) {
+ var v = 0;
+ for (var i = 0; i < offSize; i += 1) {
+ v <<= 8;
+ v += dataView.getUint8(offset + i);
+ }
+
+ return v;
+}
+
+// Retrieve a number of bytes from start offset to the end offset from the DataView.
+function getBytes(dataView, startOffset, endOffset) {
+ var bytes = [];
+ for (var i = startOffset; i < endOffset; i += 1) {
+ bytes.push(dataView.getUint8(i));
+ }
+
+ return bytes;
+}
+
+// Convert the list of bytes to a string.
+function bytesToString(bytes) {
+ var s = '';
+ for (var i = 0; i < bytes.length; i += 1) {
+ s += String.fromCharCode(bytes[i]);
+ }
+
+ return s;
+}
+
+var typeOffsets = {
+ byte: 1,
+ uShort: 2,
+ short: 2,
+ uLong: 4,
+ fixed: 4,
+ longDateTime: 8,
+ tag: 4
+};
+
+// A stateful parser that changes the offset whenever a value is retrieved.
+// The data is a DataView.
+function Parser(data, offset) {
+ this.data = data;
+ this.offset = offset;
+ this.relativeOffset = 0;
+}
+
+Parser.prototype.parseByte = function() {
+ var v = this.data.getUint8(this.offset + this.relativeOffset);
+ this.relativeOffset += 1;
+ return v;
+};
+
+Parser.prototype.parseChar = function() {
+ var v = this.data.getInt8(this.offset + this.relativeOffset);
+ this.relativeOffset += 1;
+ return v;
+};
+
+Parser.prototype.parseCard8 = Parser.prototype.parseByte;
+
+Parser.prototype.parseUShort = function() {
+ var v = this.data.getUint16(this.offset + this.relativeOffset);
+ this.relativeOffset += 2;
+ return v;
+};
+
+Parser.prototype.parseCard16 = Parser.prototype.parseUShort;
+Parser.prototype.parseSID = Parser.prototype.parseUShort;
+Parser.prototype.parseOffset16 = Parser.prototype.parseUShort;
+
+Parser.prototype.parseShort = function() {
+ var v = this.data.getInt16(this.offset + this.relativeOffset);
+ this.relativeOffset += 2;
+ return v;
+};
+
+Parser.prototype.parseF2Dot14 = function() {
+ var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384;
+ this.relativeOffset += 2;
+ return v;
+};
+
+Parser.prototype.parseULong = function() {
+ var v = getULong(this.data, this.offset + this.relativeOffset);
+ this.relativeOffset += 4;
+ return v;
+};
+
+Parser.prototype.parseFixed = function() {
+ var v = getFixed(this.data, this.offset + this.relativeOffset);
+ this.relativeOffset += 4;
+ return v;
+};
+
+Parser.prototype.parseString = function(length) {
+ var dataView = this.data;
+ var offset = this.offset + this.relativeOffset;
+ var string = '';
+ this.relativeOffset += length;
+ for (var i = 0; i < length; i++) {
+ string += String.fromCharCode(dataView.getUint8(offset + i));
+ }
+
+ return string;
+};
+
+Parser.prototype.parseTag = function() {
+ return this.parseString(4);
+};
+
+// LONGDATETIME is a 64-bit integer.
+// JavaScript and unix timestamps traditionally use 32 bits, so we
+// only take the last 32 bits.
+// + Since until 2038 those bits will be filled by zeros we can ignore them.
+Parser.prototype.parseLongDateTime = function() {
+ var v = getULong(this.data, this.offset + this.relativeOffset + 4);
+ // Subtract seconds between 01/01/1904 and 01/01/1970
+ // to convert Apple Mac timestamp to Standard Unix timestamp
+ v -= 2082844800;
+ this.relativeOffset += 8;
+ return v;
+};
+
+Parser.prototype.parseVersion = function() {
+ var major = getUShort(this.data, this.offset + this.relativeOffset);
+
+ // How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1
+ // This returns the correct number if minor = 0xN000 where N is 0-9
+ var minor = getUShort(this.data, this.offset + this.relativeOffset + 2);
+ this.relativeOffset += 4;
+ return major + minor / 0x1000 / 10;
+};
+
+Parser.prototype.skip = function(type, amount) {
+ if (amount === undefined) {
+ amount = 1;
+ }
+
+ this.relativeOffset += typeOffsets[type] * amount;
+};
+
+///// Parsing lists and records ///////////////////////////////
+
+// Parse a list of 16 bit unsigned integers. The length of the list can be read on the stream
+// or provided as an argument.
+Parser.prototype.parseOffset16List =
+Parser.prototype.parseUShortList = function(count) {
+ if (count === undefined) { count = this.parseUShort(); }
+ var offsets = new Array(count);
+ var dataView = this.data;
+ var offset = this.offset + this.relativeOffset;
+ for (var i = 0; i < count; i++) {
+ offsets[i] = dataView.getUint16(offset);
+ offset += 2;
+ }
+
+ this.relativeOffset += count * 2;
+ return offsets;
+};
+
+// Parses a list of 16 bit signed integers.
+Parser.prototype.parseShortList = function(count) {
+ var list = new Array(count);
+ var dataView = this.data;
+ var offset = this.offset + this.relativeOffset;
+ for (var i = 0; i < count; i++) {
+ list[i] = dataView.getInt16(offset);
+ offset += 2;
+ }
+
+ this.relativeOffset += count * 2;
+ return list;
+};
+
+// Parses a list of bytes.
+Parser.prototype.parseByteList = function(count) {
+ var list = new Array(count);
+ var dataView = this.data;
+ var offset = this.offset + this.relativeOffset;
+ for (var i = 0; i < count; i++) {
+ list[i] = dataView.getUint8(offset++);
+ }
+
+ this.relativeOffset += count;
+ return list;
+};
+
+/**
+ * Parse a list of items.
+ * Record count is optional, if omitted it is read from the stream.
+ * itemCallback is one of the Parser methods.
+ */
+Parser.prototype.parseList = function(count, itemCallback) {
+ var this$1 = this;
+
+ if (!itemCallback) {
+ itemCallback = count;
+ count = this.parseUShort();
+ }
+ var list = new Array(count);
+ for (var i = 0; i < count; i++) {
+ list[i] = itemCallback.call(this$1);
+ }
+ return list;
+};
+
+/**
+ * Parse a list of records.
+ * Record count is optional, if omitted it is read from the stream.
+ * Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }
+ */
+Parser.prototype.parseRecordList = function(count, recordDescription) {
+ var this$1 = this;
+
+ // If the count argument is absent, read it in the stream.
+ if (!recordDescription) {
+ recordDescription = count;
+ count = this.parseUShort();
+ }
+ var records = new Array(count);
+ var fields = Object.keys(recordDescription);
+ for (var i = 0; i < count; i++) {
+ var rec = {};
+ for (var j = 0; j < fields.length; j++) {
+ var fieldName = fields[j];
+ var fieldType = recordDescription[fieldName];
+ rec[fieldName] = fieldType.call(this$1);
+ }
+ records[i] = rec;
+ }
+ return records;
+};
+
+// Parse a data structure into an object
+// Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }
+Parser.prototype.parseStruct = function(description) {
+ var this$1 = this;
+
+ if (typeof description === 'function') {
+ return description.call(this);
+ } else {
+ var fields = Object.keys(description);
+ var struct = {};
+ for (var j = 0; j < fields.length; j++) {
+ var fieldName = fields[j];
+ var fieldType = description[fieldName];
+ struct[fieldName] = fieldType.call(this$1);
+ }
+ return struct;
+ }
+};
+
+Parser.prototype.parsePointer = function(description) {
+ var structOffset = this.parseOffset16();
+ if (structOffset > 0) { // NULL offset => return undefined
+ return new Parser(this.data, this.offset + structOffset).parseStruct(description);
+ }
+ return undefined;
+};
+
+/**
+ * Parse a list of offsets to lists of 16-bit integers,
+ * or a list of offsets to lists of offsets to any kind of items.
+ * If itemCallback is not provided, a list of list of UShort is assumed.
+ * If provided, itemCallback is called on each item and must parse the item.
+ * See examples in tables/gsub.js
+ */
+Parser.prototype.parseListOfLists = function(itemCallback) {
+ var this$1 = this;
+
+ var offsets = this.parseOffset16List();
+ var count = offsets.length;
+ var relativeOffset = this.relativeOffset;
+ var list = new Array(count);
+ for (var i = 0; i < count; i++) {
+ var start = offsets[i];
+ if (start === 0) { // NULL offset
+ list[i] = undefined; // Add i as owned property to list. Convenient with assert.
+ continue;
+ }
+ this$1.relativeOffset = start;
+ if (itemCallback) {
+ var subOffsets = this$1.parseOffset16List();
+ var subList = new Array(subOffsets.length);
+ for (var j = 0; j < subOffsets.length; j++) {
+ this$1.relativeOffset = start + subOffsets[j];
+ subList[j] = itemCallback.call(this$1);
+ }
+ list[i] = subList;
+ } else {
+ list[i] = this$1.parseUShortList();
+ }
+ }
+ this.relativeOffset = relativeOffset;
+ return list;
+};
+
+///// Complex tables parsing //////////////////////////////////
+
+// Parse a coverage table in a GSUB, GPOS or GDEF table.
+// https://www.microsoft.com/typography/OTSPEC/chapter2.htm
+// parser.offset must point to the start of the table containing the coverage.
+Parser.prototype.parseCoverage = function() {
+ var this$1 = this;
+
+ var startOffset = this.offset + this.relativeOffset;
+ var format = this.parseUShort();
+ var count = this.parseUShort();
+ if (format === 1) {
+ return {
+ format: 1,
+ glyphs: this.parseUShortList(count)
+ };
+ } else if (format === 2) {
+ var ranges = new Array(count);
+ for (var i = 0; i < count; i++) {
+ ranges[i] = {
+ start: this$1.parseUShort(),
+ end: this$1.parseUShort(),
+ index: this$1.parseUShort()
+ };
+ }
+ return {
+ format: 2,
+ ranges: ranges
+ };
+ }
+ throw new Error('0x' + startOffset.toString(16) + ': Coverage format must be 1 or 2.');
+};
+
+// Parse a Class Definition Table in a GSUB, GPOS or GDEF table.
+// https://www.microsoft.com/typography/OTSPEC/chapter2.htm
+Parser.prototype.parseClassDef = function() {
+ var startOffset = this.offset + this.relativeOffset;
+ var format = this.parseUShort();
+ if (format === 1) {
+ return {
+ format: 1,
+ startGlyph: this.parseUShort(),
+ classes: this.parseUShortList()
+ };
+ } else if (format === 2) {
+ return {
+ format: 2,
+ ranges: this.parseRecordList({
+ start: Parser.uShort,
+ end: Parser.uShort,
+ classId: Parser.uShort
+ })
+ };
+ }
+ throw new Error('0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.');
+};
+
+///// Static methods ///////////////////////////////////
+// These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance.
+
+Parser.list = function(count, itemCallback) {
+ return function() {
+ return this.parseList(count, itemCallback);
+ };
+};
+
+Parser.recordList = function(count, recordDescription) {
+ return function() {
+ return this.parseRecordList(count, recordDescription);
+ };
+};
+
+Parser.pointer = function(description) {
+ return function() {
+ return this.parsePointer(description);
+ };
+};
+
+Parser.tag = Parser.prototype.parseTag;
+Parser.byte = Parser.prototype.parseByte;
+Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort;
+Parser.uShortList = Parser.prototype.parseUShortList;
+Parser.struct = Parser.prototype.parseStruct;
+Parser.coverage = Parser.prototype.parseCoverage;
+Parser.classDef = Parser.prototype.parseClassDef;
+
+///// Script, Feature, Lookup lists ///////////////////////////////////////////////
+// https://www.microsoft.com/typography/OTSPEC/chapter2.htm
+
+var langSysTable = {
+ reserved: Parser.uShort,
+ reqFeatureIndex: Parser.uShort,
+ featureIndexes: Parser.uShortList
+};
+
+Parser.prototype.parseScriptList = function() {
+ return this.parsePointer(Parser.recordList({
+ tag: Parser.tag,
+ script: Parser.pointer({
+ defaultLangSys: Parser.pointer(langSysTable),
+ langSysRecords: Parser.recordList({
+ tag: Parser.tag,
+ langSys: Parser.pointer(langSysTable)
+ })
+ })
+ }));
+};
+
+Parser.prototype.parseFeatureList = function() {
+ return this.parsePointer(Parser.recordList({
+ tag: Parser.tag,
+ feature: Parser.pointer({
+ featureParams: Parser.offset16,
+ lookupListIndexes: Parser.uShortList
+ })
+ }));
+};
+
+Parser.prototype.parseLookupList = function(lookupTableParsers) {
+ return this.parsePointer(Parser.list(Parser.pointer(function() {
+ var lookupType = this.parseUShort();
+ check.argument(1 <= lookupType && lookupType <= 8, 'GSUB lookup type ' + lookupType + ' unknown.');
+ var lookupFlag = this.parseUShort();
+ var useMarkFilteringSet = lookupFlag & 0x10;
+ return {
+ lookupType: lookupType,
+ lookupFlag: lookupFlag,
+ subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])),
+ markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined
+ };
+ })));
+};
+
+var parse = {
+ getByte: getByte,
+ getCard8: getByte,
+ getUShort: getUShort,
+ getCard16: getUShort,
+ getShort: getShort,
+ getULong: getULong,
+ getFixed: getFixed,
+ getTag: getTag,
+ getOffset: getOffset,
+ getBytes: getBytes,
+ bytesToString: bytesToString,
+ Parser: Parser,
+};
+
+// The `cmap` table stores the mappings from characters to glyphs.
+// https://www.microsoft.com/typography/OTSPEC/cmap.htm
+
+function parseCmapTableFormat12(cmap, p) {
+ //Skip reserved.
+ p.parseUShort();
+
+ // Length in bytes of the sub-tables.
+ cmap.length = p.parseULong();
+ cmap.language = p.parseULong();
+
+ var groupCount;
+ cmap.groupCount = groupCount = p.parseULong();
+ cmap.glyphIndexMap = {};
+
+ for (var i = 0; i < groupCount; i += 1) {
+ var startCharCode = p.parseULong();
+ var endCharCode = p.parseULong();
+ var startGlyphId = p.parseULong();
+
+ for (var c = startCharCode; c <= endCharCode; c += 1) {
+ cmap.glyphIndexMap[c] = startGlyphId;
+ startGlyphId++;
+ }
+ }
+}
+
+function parseCmapTableFormat4(cmap, p, data, start, offset) {
+ // Length in bytes of the sub-tables.
+ cmap.length = p.parseUShort();
+ cmap.language = p.parseUShort();
+
+ // segCount is stored x 2.
+ var segCount;
+ cmap.segCount = segCount = p.parseUShort() >> 1;
+
+ // Skip searchRange, entrySelector, rangeShift.
+ p.skip('uShort', 3);
+
+ // The "unrolled" mapping from character codes to glyph indices.
+ cmap.glyphIndexMap = {};
+ var endCountParser = new parse.Parser(data, start + offset + 14);
+ var startCountParser = new parse.Parser(data, start + offset + 16 + segCount * 2);
+ var idDeltaParser = new parse.Parser(data, start + offset + 16 + segCount * 4);
+ var idRangeOffsetParser = new parse.Parser(data, start + offset + 16 + segCount * 6);
+ var glyphIndexOffset = start + offset + 16 + segCount * 8;
+ for (var i = 0; i < segCount - 1; i += 1) {
+ var glyphIndex = (void 0);
+ var endCount = endCountParser.parseUShort();
+ var startCount = startCountParser.parseUShort();
+ var idDelta = idDeltaParser.parseShort();
+ var idRangeOffset = idRangeOffsetParser.parseUShort();
+ for (var c = startCount; c <= endCount; c += 1) {
+ if (idRangeOffset !== 0) {
+ // The idRangeOffset is relative to the current position in the idRangeOffset array.
+ // Take the current offset in the idRangeOffset array.
+ glyphIndexOffset = (idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2);
+
+ // Add the value of the idRangeOffset, which will move us into the glyphIndex array.
+ glyphIndexOffset += idRangeOffset;
+
+ // Then add the character index of the current segment, multiplied by 2 for USHORTs.
+ glyphIndexOffset += (c - startCount) * 2;
+ glyphIndex = parse.getUShort(data, glyphIndexOffset);
+ if (glyphIndex !== 0) {
+ glyphIndex = (glyphIndex + idDelta) & 0xFFFF;
+ }
+ } else {
+ glyphIndex = (c + idDelta) & 0xFFFF;
+ }
+
+ cmap.glyphIndexMap[c] = glyphIndex;
+ }
+ }
+}
+
+// Parse the `cmap` table. This table stores the mappings from characters to glyphs.
+// There are many available formats, but we only support the Windows format 4 and 12.
+// This function returns a `CmapEncoding` object or null if no supported format could be found.
+function parseCmapTable(data, start) {
+ var cmap = {};
+ cmap.version = parse.getUShort(data, start);
+ check.argument(cmap.version === 0, 'cmap table version should be 0.');
+
+ // The cmap table can contain many sub-tables, each with their own format.
+ // We're only interested in a "platform 3" table. This is a Windows format.
+ cmap.numTables = parse.getUShort(data, start + 2);
+ var offset = -1;
+ for (var i = cmap.numTables - 1; i >= 0; i -= 1) {
+ var platformId = parse.getUShort(data, start + 4 + (i * 8));
+ var encodingId = parse.getUShort(data, start + 4 + (i * 8) + 2);
+ if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10)) {
+ offset = parse.getULong(data, start + 4 + (i * 8) + 4);
+ break;
+ }
+ }
+
+ if (offset === -1) {
+ // There is no cmap table in the font that we support.
+ throw new Error('No valid cmap sub-tables found.');
+ }
+
+ var p = new parse.Parser(data, start + offset);
+ cmap.format = p.parseUShort();
+
+ if (cmap.format === 12) {
+ parseCmapTableFormat12(cmap, p);
+ } else if (cmap.format === 4) {
+ parseCmapTableFormat4(cmap, p, data, start, offset);
+ } else {
+ throw new Error('Only format 4 and 12 cmap tables are supported (found format ' + cmap.format + ').');
+ }
+
+ return cmap;
+}
+
+function addSegment(t, code, glyphIndex) {
+ t.segments.push({
+ end: code,
+ start: code,
+ delta: -(code - glyphIndex),
+ offset: 0
+ });
+}
+
+function addTerminatorSegment(t) {
+ t.segments.push({
+ end: 0xFFFF,
+ start: 0xFFFF,
+ delta: 1,
+ offset: 0
+ });
+}
+
+function makeCmapTable(glyphs) {
+ var t = new table.Table('cmap', [
+ {name: 'version', type: 'USHORT', value: 0},
+ {name: 'numTables', type: 'USHORT', value: 1},
+ {name: 'platformID', type: 'USHORT', value: 3},
+ {name: 'encodingID', type: 'USHORT', value: 1},
+ {name: 'offset', type: 'ULONG', value: 12},
+ {name: 'format', type: 'USHORT', value: 4},
+ {name: 'length', type: 'USHORT', value: 0},
+ {name: 'language', type: 'USHORT', value: 0},
+ {name: 'segCountX2', type: 'USHORT', value: 0},
+ {name: 'searchRange', type: 'USHORT', value: 0},
+ {name: 'entrySelector', type: 'USHORT', value: 0},
+ {name: 'rangeShift', type: 'USHORT', value: 0}
+ ]);
+
+ t.segments = [];
+ for (var i = 0; i < glyphs.length; i += 1) {
+ var glyph = glyphs.get(i);
+ for (var j = 0; j < glyph.unicodes.length; j += 1) {
+ addSegment(t, glyph.unicodes[j], i);
+ }
+
+ t.segments = t.segments.sort(function(a, b) {
+ return a.start - b.start;
+ });
+ }
+
+ addTerminatorSegment(t);
+
+ var segCount;
+ segCount = t.segments.length;
+ t.segCountX2 = segCount * 2;
+ t.searchRange = Math.pow(2, Math.floor(Math.log(segCount) / Math.log(2))) * 2;
+ t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2);
+ t.rangeShift = t.segCountX2 - t.searchRange;
+
+ // Set up parallel segment arrays.
+ var endCounts = [];
+ var startCounts = [];
+ var idDeltas = [];
+ var idRangeOffsets = [];
+ var glyphIds = [];
+
+ for (var i$1 = 0; i$1 < segCount; i$1 += 1) {
+ var segment = t.segments[i$1];
+ endCounts = endCounts.concat({name: 'end_' + i$1, type: 'USHORT', value: segment.end});
+ startCounts = startCounts.concat({name: 'start_' + i$1, type: 'USHORT', value: segment.start});
+ idDeltas = idDeltas.concat({name: 'idDelta_' + i$1, type: 'SHORT', value: segment.delta});
+ idRangeOffsets = idRangeOffsets.concat({name: 'idRangeOffset_' + i$1, type: 'USHORT', value: segment.offset});
+ if (segment.glyphId !== undefined) {
+ glyphIds = glyphIds.concat({name: 'glyph_' + i$1, type: 'USHORT', value: segment.glyphId});
+ }
+ }
+
+ t.fields = t.fields.concat(endCounts);
+ t.fields.push({name: 'reservedPad', type: 'USHORT', value: 0});
+ t.fields = t.fields.concat(startCounts);
+ t.fields = t.fields.concat(idDeltas);
+ t.fields = t.fields.concat(idRangeOffsets);
+ t.fields = t.fields.concat(glyphIds);
+
+ t.length = 14 + // Subtable header
+ endCounts.length * 2 +
+ 2 + // reservedPad
+ startCounts.length * 2 +
+ idDeltas.length * 2 +
+ idRangeOffsets.length * 2 +
+ glyphIds.length * 2;
+
+ return t;
+}
+
+var cmap = { parse: parseCmapTable, make: makeCmapTable };
+
+// Glyph encoding
+
+var cffStandardStrings = [
+ '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright',
+ 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two',
+ 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater',
+ 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
+ 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
+ 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
+ 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling',
+ 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft',
+ 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph',
+ 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand',
+ 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring',
+ 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE',
+ 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu',
+ 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn',
+ 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright',
+ 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex',
+ 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex',
+ 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute',
+ 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute',
+ 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute',
+ 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave',
+ 'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior',
+ 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff', 'onedotenleader',
+ 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
+ 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior',
+ 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
+ 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl',
+ 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall',
+ 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall',
+ 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
+ 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall',
+ 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
+ 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall',
+ 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
+ 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
+ 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior',
+ 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
+ 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall',
+ 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
+ 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall',
+ 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
+ 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000',
+ '001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'];
+
+var cffStandardEncoding = [
+ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
+ '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright',
+ 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two',
+ 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater',
+ 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
+ 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
+ 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
+ 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', '', '', '', '', '', '', '',
+ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
+ 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle',
+ 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger',
+ 'daggerdbl', 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright',
+ 'guillemotright', 'ellipsis', 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', 'tilde',
+ 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla', '', 'hungarumlaut', 'ogonek', 'caron',
+ 'emdash', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '', '',
+ '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae', '', '', '', 'dotlessi', '', '',
+ 'lslash', 'oslash', 'oe', 'germandbls'];
+
+var cffExpertEncoding = [
+ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
+ '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior',
+ 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader',
+ 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle',
+ 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon',
+ 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior',
+ 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior',
+ 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl',
+ 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall',
+ 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall',
+ 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
+ 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '',
+ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
+ 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall',
+ 'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior',
+ '', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters',
+ 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '',
+ '', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
+ 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior',
+ 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
+ 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall',
+ 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
+ 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
+ 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall',
+ 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
+ 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall'];
+
+var standardNames = [
+ '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
+ 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash',
+ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
+ 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
+ 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
+ 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
+ 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
+ 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave',
+ 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
+ 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis',
+ 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section',
+ 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal',
+ 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation',
+ 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown',
+ 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright',
+ 'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft',
+ 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction',
+ 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase',
+ 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute',
+ 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex',
+ 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut',
+ 'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth',
+ 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior',
+ 'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla',
+ 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat'];
+
+/**
+ * This is the encoding used for fonts created from scratch.
+ * It loops through all glyphs and finds the appropriate unicode value.
+ * Since it's linear time, other encodings will be faster.
+ * @exports opentype.DefaultEncoding
+ * @class
+ * @constructor
+ * @param {opentype.Font}
+ */
+function DefaultEncoding(font) {
+ this.font = font;
+}
+
+DefaultEncoding.prototype.charToGlyphIndex = function(c) {
+ var code = c.charCodeAt(0);
+ var glyphs = this.font.glyphs;
+ if (glyphs) {
+ for (var i = 0; i < glyphs.length; i += 1) {
+ var glyph = glyphs.get(i);
+ for (var j = 0; j < glyph.unicodes.length; j += 1) {
+ if (glyph.unicodes[j] === code) {
+ return i;
+ }
+ }
+ }
+ }
+ return null;
+};
+
+/**
+ * @exports opentype.CmapEncoding
+ * @class
+ * @constructor
+ * @param {Object} cmap - a object with the cmap encoded data
+ */
+function CmapEncoding(cmap) {
+ this.cmap = cmap;
+}
+
+/**
+ * @param {string} c - the character
+ * @return {number} The glyph index.
+ */
+CmapEncoding.prototype.charToGlyphIndex = function(c) {
+ return this.cmap.glyphIndexMap[c.charCodeAt(0)] || 0;
+};
+
+/**
+ * @exports opentype.CffEncoding
+ * @class
+ * @constructor
+ * @param {string} encoding - The encoding
+ * @param {Array} charset - The character set.
+ */
+function CffEncoding(encoding, charset) {
+ this.encoding = encoding;
+ this.charset = charset;
+}
+
+/**
+ * @param {string} s - The character
+ * @return {number} The index.
+ */
+CffEncoding.prototype.charToGlyphIndex = function(s) {
+ var code = s.charCodeAt(0);
+ var charName = this.encoding[code];
+ return this.charset.indexOf(charName);
+};
+
+/**
+ * @exports opentype.GlyphNames
+ * @class
+ * @constructor
+ * @param {Object} post
+ */
+function GlyphNames(post) {
+ var this$1 = this;
+
+ switch (post.version) {
+ case 1:
+ this.names = standardNames.slice();
+ break;
+ case 2:
+ this.names = new Array(post.numberOfGlyphs);
+ for (var i = 0; i < post.numberOfGlyphs; i++) {
+ if (post.glyphNameIndex[i] < standardNames.length) {
+ this$1.names[i] = standardNames[post.glyphNameIndex[i]];
+ } else {
+ this$1.names[i] = post.names[post.glyphNameIndex[i] - standardNames.length];
+ }
+ }
+
+ break;
+ case 2.5:
+ this.names = new Array(post.numberOfGlyphs);
+ for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) {
+ this$1.names[i$1] = standardNames[i$1 + post.glyphNameIndex[i$1]];
+ }
+
+ break;
+ case 3:
+ this.names = [];
+ break;
+ default:
+ this.names = [];
+ break;
+ }
+}
+
+/**
+ * Gets the index of a glyph by name.
+ * @param {string} name - The glyph name
+ * @return {number} The index
+ */
+GlyphNames.prototype.nameToGlyphIndex = function(name) {
+ return this.names.indexOf(name);
+};
+
+/**
+ * @param {number} gid
+ * @return {string}
+ */
+GlyphNames.prototype.glyphIndexToName = function(gid) {
+ return this.names[gid];
+};
+
+/**
+ * @alias opentype.addGlyphNames
+ * @param {opentype.Font}
+ */
+function addGlyphNames(font) {
+ var glyph;
+ var glyphIndexMap = font.tables.cmap.glyphIndexMap;
+ var charCodes = Object.keys(glyphIndexMap);
+
+ for (var i = 0; i < charCodes.length; i += 1) {
+ var c = charCodes[i];
+ var glyphIndex = glyphIndexMap[c];
+ glyph = font.glyphs.get(glyphIndex);
+ glyph.addUnicode(parseInt(c));
+ }
+
+ for (var i$1 = 0; i$1 < font.glyphs.length; i$1 += 1) {
+ glyph = font.glyphs.get(i$1);
+ if (font.cffEncoding) {
+ if (font.isCIDFont) {
+ glyph.name = 'gid' + i$1;
+ } else {
+ glyph.name = font.cffEncoding.charset[i$1];
+ }
+ } else if (font.glyphNames.names) {
+ glyph.name = font.glyphNames.glyphIndexToName(i$1);
+ }
+ }
+}
+
+// Drawing utility functions.
+
+// Draw a line on the given context from point `x1,y1` to point `x2,y2`.
+function line(ctx, x1, y1, x2, y2) {
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.stroke();
+}
+
+var draw = { line: line };
+
+// The `glyf` table describes the glyphs in TrueType outline format.
+// http://www.microsoft.com/typography/otspec/glyf.htm
+
+// Parse the coordinate data for a glyph.
+function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) {
+ var v;
+ if ((flag & shortVectorBitMask) > 0) {
+ // The coordinate is 1 byte long.
+ v = p.parseByte();
+ // The `same` bit is re-used for short values to signify the sign of the value.
+ if ((flag & sameBitMask) === 0) {
+ v = -v;
+ }
+
+ v = previousValue + v;
+ } else {
+ // The coordinate is 2 bytes long.
+ // If the `same` bit is set, the coordinate is the same as the previous coordinate.
+ if ((flag & sameBitMask) > 0) {
+ v = previousValue;
+ } else {
+ // Parse the coordinate as a signed 16-bit delta value.
+ v = previousValue + p.parseShort();
+ }
+ }
+
+ return v;
+}
+
+// Parse a TrueType glyph.
+function parseGlyph(glyph, data, start) {
+ var p = new parse.Parser(data, start);
+ glyph.numberOfContours = p.parseShort();
+ glyph._xMin = p.parseShort();
+ glyph._yMin = p.parseShort();
+ glyph._xMax = p.parseShort();
+ glyph._yMax = p.parseShort();
+ var flags;
+ var flag;
+
+ if (glyph.numberOfContours > 0) {
+ // This glyph is not a composite.
+ var endPointIndices = glyph.endPointIndices = [];
+ for (var i = 0; i < glyph.numberOfContours; i += 1) {
+ endPointIndices.push(p.parseUShort());
+ }
+
+ glyph.instructionLength = p.parseUShort();
+ glyph.instructions = [];
+ for (var i$1 = 0; i$1 < glyph.instructionLength; i$1 += 1) {
+ glyph.instructions.push(p.parseByte());
+ }
+
+ var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1;
+ flags = [];
+ for (var i$2 = 0; i$2 < numberOfCoordinates; i$2 += 1) {
+ flag = p.parseByte();
+ flags.push(flag);
+ // If bit 3 is set, we repeat this flag n times, where n is the next byte.
+ if ((flag & 8) > 0) {
+ var repeatCount = p.parseByte();
+ for (var j = 0; j < repeatCount; j += 1) {
+ flags.push(flag);
+ i$2 += 1;
+ }
+ }
+ }
+
+ check.argument(flags.length === numberOfCoordinates, 'Bad flags.');
+
+ if (endPointIndices.length > 0) {
+ var points = [];
+ var point;
+ // X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0.
+ if (numberOfCoordinates > 0) {
+ for (var i$3 = 0; i$3 < numberOfCoordinates; i$3 += 1) {
+ flag = flags[i$3];
+ point = {};
+ point.onCurve = !!(flag & 1);
+ point.lastPointOfContour = endPointIndices.indexOf(i$3) >= 0;
+ points.push(point);
+ }
+
+ var px = 0;
+ for (var i$4 = 0; i$4 < numberOfCoordinates; i$4 += 1) {
+ flag = flags[i$4];
+ point = points[i$4];
+ point.x = parseGlyphCoordinate(p, flag, px, 2, 16);
+ px = point.x;
+ }
+
+ var py = 0;
+ for (var i$5 = 0; i$5 < numberOfCoordinates; i$5 += 1) {
+ flag = flags[i$5];
+ point = points[i$5];
+ point.y = parseGlyphCoordinate(p, flag, py, 4, 32);
+ py = point.y;
+ }
+ }
+
+ glyph.points = points;
+ } else {
+ glyph.points = [];
+ }
+ } else if (glyph.numberOfContours === 0) {
+ glyph.points = [];
+ } else {
+ glyph.isComposite = true;
+ glyph.points = [];
+ glyph.components = [];
+ var moreComponents = true;
+ while (moreComponents) {
+ flags = p.parseUShort();
+ var component = {
+ glyphIndex: p.parseUShort(),
+ xScale: 1,
+ scale01: 0,
+ scale10: 0,
+ yScale: 1,
+ dx: 0,
+ dy: 0
+ };
+ if ((flags & 1) > 0) {
+ // The arguments are words
+ if ((flags & 2) > 0) {
+ // values are offset
+ component.dx = p.parseShort();
+ component.dy = p.parseShort();
+ } else {
+ // values are matched points
+ component.matchedPoints = [p.parseUShort(), p.parseUShort()];
+ }
+
+ } else {
+ // The arguments are bytes
+ if ((flags & 2) > 0) {
+ // values are offset
+ component.dx = p.parseChar();
+ component.dy = p.parseChar();
+ } else {
+ // values are matched points
+ component.matchedPoints = [p.parseByte(), p.parseByte()];
+ }
+ }
+
+ if ((flags & 8) > 0) {
+ // We have a scale
+ component.xScale = component.yScale = p.parseF2Dot14();
+ } else if ((flags & 64) > 0) {
+ // We have an X / Y scale
+ component.xScale = p.parseF2Dot14();
+ component.yScale = p.parseF2Dot14();
+ } else if ((flags & 128) > 0) {
+ // We have a 2x2 transformation
+ component.xScale = p.parseF2Dot14();
+ component.scale01 = p.parseF2Dot14();
+ component.scale10 = p.parseF2Dot14();
+ component.yScale = p.parseF2Dot14();
+ }
+
+ glyph.components.push(component);
+ moreComponents = !!(flags & 32);
+ }
+ if (flags & 0x100) {
+ // We have instructions
+ glyph.instructionLength = p.parseUShort();
+ glyph.instructions = [];
+ for (var i$6 = 0; i$6 < glyph.instructionLength; i$6 += 1) {
+ glyph.instructions.push(p.parseByte());
+ }
+ }
+ }
+}
+
+// Transform an array of points and return a new array.
+function transformPoints(points, transform) {
+ var newPoints = [];
+ for (var i = 0; i < points.length; i += 1) {
+ var pt = points[i];
+ var newPt = {
+ x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx,
+ y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy,
+ onCurve: pt.onCurve,
+ lastPointOfContour: pt.lastPointOfContour
+ };
+ newPoints.push(newPt);
+ }
+
+ return newPoints;
+}
+
+function getContours(points) {
+ var contours = [];
+ var currentContour = [];
+ for (var i = 0; i < points.length; i += 1) {
+ var pt = points[i];
+ currentContour.push(pt);
+ if (pt.lastPointOfContour) {
+ contours.push(currentContour);
+ currentContour = [];
+ }
+ }
+
+ check.argument(currentContour.length === 0, 'There are still points left in the current contour.');
+ return contours;
+}
+
+// Convert the TrueType glyph outline to a Path.
+function getPath(points) {
+ var p = new Path();
+ if (!points) {
+ return p;
+ }
+
+ var contours = getContours(points);
+
+ for (var contourIndex = 0; contourIndex < contours.length; ++contourIndex) {
+ var contour = contours[contourIndex];
+
+ var prev = null;
+ var curr = contour[contour.length - 1];
+ var next = contour[0];
+
+ if (curr.onCurve) {
+ p.moveTo(curr.x, curr.y);
+ } else {
+ if (next.onCurve) {
+ p.moveTo(next.x, next.y);
+ } else {
+ // If both first and last points are off-curve, start at their middle.
+ var start = {x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5};
+ p.moveTo(start.x, start.y);
+ }
+ }
+
+ for (var i = 0; i < contour.length; ++i) {
+ prev = curr;
+ curr = next;
+ next = contour[(i + 1) % contour.length];
+
+ if (curr.onCurve) {
+ // This is a straight line.
+ p.lineTo(curr.x, curr.y);
+ } else {
+ var prev2 = prev;
+ var next2 = next;
+
+ if (!prev.onCurve) {
+ prev2 = { x: (curr.x + prev.x) * 0.5, y: (curr.y + prev.y) * 0.5 };
+ p.lineTo(prev2.x, prev2.y);
+ }
+
+ if (!next.onCurve) {
+ next2 = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 };
+ }
+
+ p.lineTo(prev2.x, prev2.y);
+ p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y);
+ }
+ }
+
+ p.closePath();
+ }
+ return p;
+}
+
+function buildPath(glyphs, glyph) {
+ if (glyph.isComposite) {
+ for (var j = 0; j < glyph.components.length; j += 1) {
+ var component = glyph.components[j];
+ var componentGlyph = glyphs.get(component.glyphIndex);
+ // Force the ttfGlyphLoader to parse the glyph.
+ componentGlyph.getPath();
+ if (componentGlyph.points) {
+ var transformedPoints = (void 0);
+ if (component.matchedPoints === undefined) {
+ // component positioned by offset
+ transformedPoints = transformPoints(componentGlyph.points, component);
+ } else {
+ // component positioned by matched points
+ if ((component.matchedPoints[0] > glyph.points.length - 1) ||
+ (component.matchedPoints[1] > componentGlyph.points.length - 1)) {
+ throw Error('Matched points out of range in ' + glyph.name);
+ }
+ var firstPt = glyph.points[component.matchedPoints[0]];
+ var secondPt = componentGlyph.points[component.matchedPoints[1]];
+ var transform = {
+ xScale: component.xScale, scale01: component.scale01,
+ scale10: component.scale10, yScale: component.yScale,
+ dx: 0, dy: 0
+ };
+ secondPt = transformPoints([secondPt], transform)[0];
+ transform.dx = firstPt.x - secondPt.x;
+ transform.dy = firstPt.y - secondPt.y;
+ transformedPoints = transformPoints(componentGlyph.points, transform);
+ }
+ glyph.points = glyph.points.concat(transformedPoints);
+ }
+ }
+ }
+
+ return getPath(glyph.points);
+}
+
+// Parse all the glyphs according to the offsets from the `loca` table.
+function parseGlyfTable(data, start, loca, font) {
+ var glyphs = new glyphset.GlyphSet(font);
+
+ // The last element of the loca table is invalid.
+ for (var i = 0; i < loca.length - 1; i += 1) {
+ var offset = loca[i];
+ var nextOffset = loca[i + 1];
+ if (offset !== nextOffset) {
+ glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath));
+ } else {
+ glyphs.push(i, glyphset.glyphLoader(font, i));
+ }
+ }
+
+ return glyphs;
+}
+
+var glyf = { getPath: getPath, parse: parseGlyfTable };
+
+// The Glyph object
+
+function getPathDefinition(glyph, path) {
+ var _path = path || {commands: []};
+ return {
+ configurable: true,
+
+ get: function() {
+ if (typeof _path === 'function') {
+ _path = _path();
+ }
+
+ return _path;
+ },
+
+ set: function(p) {
+ _path = p;
+ }
+ };
+}
+/**
+ * @typedef GlyphOptions
+ * @type Object
+ * @property {string} [name] - The glyph name
+ * @property {number} [unicode]
+ * @property {Array} [unicodes]
+ * @property {number} [xMin]
+ * @property {number} [yMin]
+ * @property {number} [xMax]
+ * @property {number} [yMax]
+ * @property {number} [advanceWidth]
+ */
+
+// A Glyph is an individual mark that often corresponds to a character.
+// Some glyphs, such as ligatures, are a combination of many characters.
+// Glyphs are the basic building blocks of a font.
+//
+// The `Glyph` class contains utility methods for drawing the path and its points.
+/**
+ * @exports opentype.Glyph
+ * @class
+ * @param {GlyphOptions}
+ * @constructor
+ */
+function Glyph(options) {
+ // By putting all the code on a prototype function (which is only declared once)
+ // we reduce the memory requirements for larger fonts by some 2%
+ this.bindConstructorValues(options);
+}
+
+/**
+ * @param {GlyphOptions}
+ */
+Glyph.prototype.bindConstructorValues = function(options) {
+ this.index = options.index || 0;
+
+ // These three values cannot be deferred for memory optimization:
+ this.name = options.name || null;
+ this.unicode = options.unicode || undefined;
+ this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : [];
+
+ // But by binding these values only when necessary, we reduce can
+ // the memory requirements by almost 3% for larger fonts.
+ if (options.xMin) {
+ this.xMin = options.xMin;
+ }
+
+ if (options.yMin) {
+ this.yMin = options.yMin;
+ }
+
+ if (options.xMax) {
+ this.xMax = options.xMax;
+ }
+
+ if (options.yMax) {
+ this.yMax = options.yMax;
+ }
+
+ if (options.advanceWidth) {
+ this.advanceWidth = options.advanceWidth;
+ }
+
+ // The path for a glyph is the most memory intensive, and is bound as a value
+ // with a getter/setter to ensure we actually do path parsing only once the
+ // path is actually needed by anything.
+ Object.defineProperty(this, 'path', getPathDefinition(this, options.path));
+};
+
+/**
+ * @param {number}
+ */
+Glyph.prototype.addUnicode = function(unicode) {
+ if (this.unicodes.length === 0) {
+ this.unicode = unicode;
+ }
+
+ this.unicodes.push(unicode);
+};
+
+/**
+ * Calculate the minimum bounding box for this glyph.
+ * @return {opentype.BoundingBox}
+ */
+Glyph.prototype.getBoundingBox = function() {
+ return this.path.getBoundingBox();
+};
+
+/**
+ * Convert the glyph to a Path we can draw on a drawing context.
+ * @param {number} [x=0] - Horizontal position of the beginning of the text.
+ * @param {number} [y=0] - Vertical position of the *baseline* of the text.
+ * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
+ * @param {Object=} options - xScale, yScale to stretch the glyph.
+ * @param {opentype.Font} if hinting is to be used, the font
+ * @return {opentype.Path}
+ */
+Glyph.prototype.getPath = function(x, y, fontSize, options, font) {
+ x = x !== undefined ? x : 0;
+ y = y !== undefined ? y : 0;
+ fontSize = fontSize !== undefined ? fontSize : 72;
+ var commands;
+ var hPoints;
+ if (!options) { options = { }; }
+ var xScale = options.xScale;
+ var yScale = options.yScale;
+
+ if (options.hinting && font && font.hinting) {
+ // in case of hinting, the hinting engine takes care
+ // of scaling the points (not the path) before hinting.
+ hPoints = this.path && font.hinting.exec(this, fontSize);
+ // in case the hinting engine failed hPoints is undefined
+ // and thus reverts to plain rending
+ }
+
+ if (hPoints) {
+ commands = glyf.getPath(hPoints).commands;
+ x = Math.round(x);
+ y = Math.round(y);
+ // TODO in case of hinting xyScaling is not yet supported
+ xScale = yScale = 1;
+ } else {
+ commands = this.path.commands;
+ var scale = 1 / this.path.unitsPerEm * fontSize;
+ if (xScale === undefined) { xScale = scale; }
+ if (yScale === undefined) { yScale = scale; }
+ }
+
+ var p = new Path();
+ for (var i = 0; i < commands.length; i += 1) {
+ var cmd = commands[i];
+ if (cmd.type === 'M') {
+ p.moveTo(x + (cmd.x * xScale), y + (-cmd.y * yScale));
+ } else if (cmd.type === 'L') {
+ p.lineTo(x + (cmd.x * xScale), y + (-cmd.y * yScale));
+ } else if (cmd.type === 'Q') {
+ p.quadraticCurveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale),
+ x + (cmd.x * xScale), y + (-cmd.y * yScale));
+ } else if (cmd.type === 'C') {
+ p.curveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale),
+ x + (cmd.x2 * xScale), y + (-cmd.y2 * yScale),
+ x + (cmd.x * xScale), y + (-cmd.y * yScale));
+ } else if (cmd.type === 'Z') {
+ p.closePath();
+ }
+ }
+
+ return p;
+};
+
+/**
+ * Split the glyph into contours.
+ * This function is here for backwards compatibility, and to
+ * provide raw access to the TrueType glyph outlines.
+ * @return {Array}
+ */
+Glyph.prototype.getContours = function() {
+ var this$1 = this;
+
+ if (this.points === undefined) {
+ return [];
+ }
+
+ var contours = [];
+ var currentContour = [];
+ for (var i = 0; i < this.points.length; i += 1) {
+ var pt = this$1.points[i];
+ currentContour.push(pt);
+ if (pt.lastPointOfContour) {
+ contours.push(currentContour);
+ currentContour = [];
+ }
+ }
+
+ check.argument(currentContour.length === 0, 'There are still points left in the current contour.');
+ return contours;
+};
+
+/**
+ * Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph.
+ * @return {Object}
+ */
+Glyph.prototype.getMetrics = function() {
+ var commands = this.path.commands;
+ var xCoords = [];
+ var yCoords = [];
+ for (var i = 0; i < commands.length; i += 1) {
+ var cmd = commands[i];
+ if (cmd.type !== 'Z') {
+ xCoords.push(cmd.x);
+ yCoords.push(cmd.y);
+ }
+
+ if (cmd.type === 'Q' || cmd.type === 'C') {
+ xCoords.push(cmd.x1);
+ yCoords.push(cmd.y1);
+ }
+
+ if (cmd.type === 'C') {
+ xCoords.push(cmd.x2);
+ yCoords.push(cmd.y2);
+ }
+ }
+
+ var metrics = {
+ xMin: Math.min.apply(null, xCoords),
+ yMin: Math.min.apply(null, yCoords),
+ xMax: Math.max.apply(null, xCoords),
+ yMax: Math.max.apply(null, yCoords),
+ leftSideBearing: this.leftSideBearing
+ };
+
+ if (!isFinite(metrics.xMin)) {
+ metrics.xMin = 0;
+ }
+
+ if (!isFinite(metrics.xMax)) {
+ metrics.xMax = this.advanceWidth;
+ }
+
+ if (!isFinite(metrics.yMin)) {
+ metrics.yMin = 0;
+ }
+
+ if (!isFinite(metrics.yMax)) {
+ metrics.yMax = 0;
+ }
+
+ metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin);
+ return metrics;
+};
+
+/**
+ * Draw the glyph on the given context.
+ * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
+ * @param {number} [x=0] - Horizontal position of the beginning of the text.
+ * @param {number} [y=0] - Vertical position of the *baseline* of the text.
+ * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
+ * @param {Object=} options - xScale, yScale to stretch the glyph.
+ */
+Glyph.prototype.draw = function(ctx, x, y, fontSize, options) {
+ this.getPath(x, y, fontSize, options).draw(ctx);
+};
+
+/**
+ * Draw the points of the glyph.
+ * On-curve points will be drawn in blue, off-curve points will be drawn in red.
+ * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
+ * @param {number} [x=0] - Horizontal position of the beginning of the text.
+ * @param {number} [y=0] - Vertical position of the *baseline* of the text.
+ * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
+ */
+Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) {
+ function drawCircles(l, x, y, scale) {
+ var PI_SQ = Math.PI * 2;
+ ctx.beginPath();
+ for (var j = 0; j < l.length; j += 1) {
+ ctx.moveTo(x + (l[j].x * scale), y + (l[j].y * scale));
+ ctx.arc(x + (l[j].x * scale), y + (l[j].y * scale), 2, 0, PI_SQ, false);
+ }
+
+ ctx.closePath();
+ ctx.fill();
+ }
+
+ x = x !== undefined ? x : 0;
+ y = y !== undefined ? y : 0;
+ fontSize = fontSize !== undefined ? fontSize : 24;
+ var scale = 1 / this.path.unitsPerEm * fontSize;
+
+ var blueCircles = [];
+ var redCircles = [];
+ var path = this.path;
+ for (var i = 0; i < path.commands.length; i += 1) {
+ var cmd = path.commands[i];
+ if (cmd.x !== undefined) {
+ blueCircles.push({x: cmd.x, y: -cmd.y});
+ }
+
+ if (cmd.x1 !== undefined) {
+ redCircles.push({x: cmd.x1, y: -cmd.y1});
+ }
+
+ if (cmd.x2 !== undefined) {
+ redCircles.push({x: cmd.x2, y: -cmd.y2});
+ }
+ }
+
+ ctx.fillStyle = 'blue';
+ drawCircles(blueCircles, x, y, scale);
+ ctx.fillStyle = 'red';
+ drawCircles(redCircles, x, y, scale);
+};
+
+/**
+ * Draw lines indicating important font measurements.
+ * Black lines indicate the origin of the coordinate system (point 0,0).
+ * Blue lines indicate the glyph bounding box.
+ * Green line indicates the advance width of the glyph.
+ * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
+ * @param {number} [x=0] - Horizontal position of the beginning of the text.
+ * @param {number} [y=0] - Vertical position of the *baseline* of the text.
+ * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
+ */
+Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) {
+ var scale;
+ x = x !== undefined ? x : 0;
+ y = y !== undefined ? y : 0;
+ fontSize = fontSize !== undefined ? fontSize : 24;
+ scale = 1 / this.path.unitsPerEm * fontSize;
+ ctx.lineWidth = 1;
+
+ // Draw the origin
+ ctx.strokeStyle = 'black';
+ draw.line(ctx, x, -10000, x, 10000);
+ draw.line(ctx, -10000, y, 10000, y);
+
+ // This code is here due to memory optimization: by not using
+ // defaults in the constructor, we save a notable amount of memory.
+ var xMin = this.xMin || 0;
+ var yMin = this.yMin || 0;
+ var xMax = this.xMax || 0;
+ var yMax = this.yMax || 0;
+ var advanceWidth = this.advanceWidth || 0;
+
+ // Draw the glyph box
+ ctx.strokeStyle = 'blue';
+ draw.line(ctx, x + (xMin * scale), -10000, x + (xMin * scale), 10000);
+ draw.line(ctx, x + (xMax * scale), -10000, x + (xMax * scale), 10000);
+ draw.line(ctx, -10000, y + (-yMin * scale), 10000, y + (-yMin * scale));
+ draw.line(ctx, -10000, y + (-yMax * scale), 10000, y + (-yMax * scale));
+
+ // Draw the advance width
+ ctx.strokeStyle = 'green';
+ draw.line(ctx, x + (advanceWidth * scale), -10000, x + (advanceWidth * scale), 10000);
+};
+
+// The GlyphSet object
+
+// Define a property on the glyph that depends on the path being loaded.
+function defineDependentProperty(glyph, externalName, internalName) {
+ Object.defineProperty(glyph, externalName, {
+ get: function() {
+ // Request the path property to make sure the path is loaded.
+ glyph.path; // jshint ignore:line
+ return glyph[internalName];
+ },
+ set: function(newValue) {
+ glyph[internalName] = newValue;
+ },
+ enumerable: true,
+ configurable: true
+ });
+}
+
+/**
+ * A GlyphSet represents all glyphs available in the font, but modelled using
+ * a deferred glyph loader, for retrieving glyphs only once they are absolutely
+ * necessary, to keep the memory footprint down.
+ * @exports opentype.GlyphSet
+ * @class
+ * @param {opentype.Font}
+ * @param {Array}
+ */
+function GlyphSet(font, glyphs) {
+ var this$1 = this;
+
+ this.font = font;
+ this.glyphs = {};
+ if (Array.isArray(glyphs)) {
+ for (var i = 0; i < glyphs.length; i++) {
+ this$1.glyphs[i] = glyphs[i];
+ }
+ }
+
+ this.length = (glyphs && glyphs.length) || 0;
+}
+
+/**
+ * @param {number} index
+ * @return {opentype.Glyph}
+ */
+GlyphSet.prototype.get = function(index) {
+ if (typeof this.glyphs[index] === 'function') {
+ this.glyphs[index] = this.glyphs[index]();
+ }
+
+ return this.glyphs[index];
+};
+
+/**
+ * @param {number} index
+ * @param {Object}
+ */
+GlyphSet.prototype.push = function(index, loader) {
+ this.glyphs[index] = loader;
+ this.length++;
+};
+
+/**
+ * @alias opentype.glyphLoader
+ * @param {opentype.Font} font
+ * @param {number} index
+ * @return {opentype.Glyph}
+ */
+function glyphLoader(font, index) {
+ return new Glyph({index: index, font: font});
+}
+
+/**
+ * Generate a stub glyph that can be filled with all metadata *except*
+ * the "points" and "path" properties, which must be loaded only once
+ * the glyph's path is actually requested for text shaping.
+ * @alias opentype.ttfGlyphLoader
+ * @param {opentype.Font} font
+ * @param {number} index
+ * @param {Function} parseGlyph
+ * @param {Object} data
+ * @param {number} position
+ * @param {Function} buildPath
+ * @return {opentype.Glyph}
+ */
+function ttfGlyphLoader(font, index, parseGlyph, data, position, buildPath) {
+ return function() {
+ var glyph = new Glyph({index: index, font: font});
+
+ glyph.path = function() {
+ parseGlyph(glyph, data, position);
+ var path = buildPath(font.glyphs, glyph);
+ path.unitsPerEm = font.unitsPerEm;
+ return path;
+ };
+
+ defineDependentProperty(glyph, 'xMin', '_xMin');
+ defineDependentProperty(glyph, 'xMax', '_xMax');
+ defineDependentProperty(glyph, 'yMin', '_yMin');
+ defineDependentProperty(glyph, 'yMax', '_yMax');
+
+ return glyph;
+ };
+}
+/**
+ * @alias opentype.cffGlyphLoader
+ * @param {opentype.Font} font
+ * @param {number} index
+ * @param {Function} parseCFFCharstring
+ * @param {string} charstring
+ * @return {opentype.Glyph}
+ */
+function cffGlyphLoader(font, index, parseCFFCharstring, charstring) {
+ return function() {
+ var glyph = new Glyph({index: index, font: font});
+
+ glyph.path = function() {
+ var path = parseCFFCharstring(font, glyph, charstring);
+ path.unitsPerEm = font.unitsPerEm;
+ return path;
+ };
+
+ return glyph;
+ };
+}
+
+var glyphset = { GlyphSet: GlyphSet, glyphLoader: glyphLoader, ttfGlyphLoader: ttfGlyphLoader, cffGlyphLoader: cffGlyphLoader };
+
+// The `CFF` table contains the glyph outlines in PostScript format.
+// https://www.microsoft.com/typography/OTSPEC/cff.htm
+// http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/cff.pdf
+// http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/type2.pdf
+
+// Custom equals function that can also check lists.
+function equals(a, b) {
+ if (a === b) {
+ return true;
+ } else if (Array.isArray(a) && Array.isArray(b)) {
+ if (a.length !== b.length) {
+ return false;
+ }
+
+ for (var i = 0; i < a.length; i += 1) {
+ if (!equals(a[i], b[i])) {
+ return false;
+ }
+ }
+
+ return true;
+ } else {
+ return false;
+ }
+}
+
+// Subroutines are encoded using the negative half of the number space.
+// See type 2 chapter 4.7 "Subroutine operators".
+function calcCFFSubroutineBias(subrs) {
+ var bias;
+ if (subrs.length < 1240) {
+ bias = 107;
+ } else if (subrs.length < 33900) {
+ bias = 1131;
+ } else {
+ bias = 32768;
+ }
+
+ return bias;
+}
+
+// Parse a `CFF` INDEX array.
+// An index array consists of a list of offsets, then a list of objects at those offsets.
+function parseCFFIndex(data, start, conversionFn) {
+ var offsets = [];
+ var objects = [];
+ var count = parse.getCard16(data, start);
+ var objectOffset;
+ var endOffset;
+ if (count !== 0) {
+ var offsetSize = parse.getByte(data, start + 2);
+ objectOffset = start + ((count + 1) * offsetSize) + 2;
+ var pos = start + 3;
+ for (var i = 0; i < count + 1; i += 1) {
+ offsets.push(parse.getOffset(data, pos, offsetSize));
+ pos += offsetSize;
+ }
+
+ // The total size of the index array is 4 header bytes + the value of the last offset.
+ endOffset = objectOffset + offsets[count];
+ } else {
+ endOffset = start + 2;
+ }
+
+ for (var i$1 = 0; i$1 < offsets.length - 1; i$1 += 1) {
+ var value = parse.getBytes(data, objectOffset + offsets[i$1], objectOffset + offsets[i$1 + 1]);
+ if (conversionFn) {
+ value = conversionFn(value);
+ }
+
+ objects.push(value);
+ }
+
+ return {objects: objects, startOffset: start, endOffset: endOffset};
+}
+
+// Parse a `CFF` DICT real value.
+function parseFloatOperand(parser) {
+ var s = '';
+ var eof = 15;
+ var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'E', 'E-', null, '-'];
+ while (true) {
+ var b = parser.parseByte();
+ var n1 = b >> 4;
+ var n2 = b & 15;
+
+ if (n1 === eof) {
+ break;
+ }
+
+ s += lookup[n1];
+
+ if (n2 === eof) {
+ break;
+ }
+
+ s += lookup[n2];
+ }
+
+ return parseFloat(s);
+}
+
+// Parse a `CFF` DICT operand.
+function parseOperand(parser, b0) {
+ var b1;
+ var b2;
+ var b3;
+ var b4;
+ if (b0 === 28) {
+ b1 = parser.parseByte();
+ b2 = parser.parseByte();
+ return b1 << 8 | b2;
+ }
+
+ if (b0 === 29) {
+ b1 = parser.parseByte();
+ b2 = parser.parseByte();
+ b3 = parser.parseByte();
+ b4 = parser.parseByte();
+ return b1 << 24 | b2 << 16 | b3 << 8 | b4;
+ }
+
+ if (b0 === 30) {
+ return parseFloatOperand(parser);
+ }
+
+ if (b0 >= 32 && b0 <= 246) {
+ return b0 - 139;
+ }
+
+ if (b0 >= 247 && b0 <= 250) {
+ b1 = parser.parseByte();
+ return (b0 - 247) * 256 + b1 + 108;
+ }
+
+ if (b0 >= 251 && b0 <= 254) {
+ b1 = parser.parseByte();
+ return -(b0 - 251) * 256 - b1 - 108;
+ }
+
+ throw new Error('Invalid b0 ' + b0);
+}
+
+// Convert the entries returned by `parseDict` to a proper dictionary.
+// If a value is a list of one, it is unpacked.
+function entriesToObject(entries) {
+ var o = {};
+ for (var i = 0; i < entries.length; i += 1) {
+ var key = entries[i][0];
+ var values = entries[i][1];
+ var value = (void 0);
+ if (values.length === 1) {
+ value = values[0];
+ } else {
+ value = values;
+ }
+
+ if (o.hasOwnProperty(key) && !isNaN(o[key])) {
+ throw new Error('Object ' + o + ' already has key ' + key);
+ }
+
+ o[key] = value;
+ }
+
+ return o;
+}
+
+// Parse a `CFF` DICT object.
+// A dictionary contains key-value pairs in a compact tokenized format.
+function parseCFFDict(data, start, size) {
+ start = start !== undefined ? start : 0;
+ var parser = new parse.Parser(data, start);
+ var entries = [];
+ var operands = [];
+ size = size !== undefined ? size : data.length;
+
+ while (parser.relativeOffset < size) {
+ var op = parser.parseByte();
+
+ // The first byte for each dict item distinguishes between operator (key) and operand (value).
+ // Values <= 21 are operators.
+ if (op <= 21) {
+ // Two-byte operators have an initial escape byte of 12.
+ if (op === 12) {
+ op = 1200 + parser.parseByte();
+ }
+
+ entries.push([op, operands]);
+ operands = [];
+ } else {
+ // Since the operands (values) come before the operators (keys), we store all operands in a list
+ // until we encounter an operator.
+ operands.push(parseOperand(parser, op));
+ }
+ }
+
+ return entriesToObject(entries);
+}
+
+// Given a String Index (SID), return the value of the string.
+// Strings below index 392 are standard CFF strings and are not encoded in the font.
+function getCFFString(strings, index) {
+ if (index <= 390) {
+ index = cffStandardStrings[index];
+ } else {
+ index = strings[index - 391];
+ }
+
+ return index;
+}
+
+// Interpret a dictionary and return a new dictionary with readable keys and values for missing entries.
+// This function takes `meta` which is a list of objects containing `operand`, `name` and `default`.
+function interpretDict(dict, meta, strings) {
+ var newDict = {};
+ var value;
+
+ // Because we also want to include missing values, we start out from the meta list
+ // and lookup values in the dict.
+ for (var i = 0; i < meta.length; i += 1) {
+ var m = meta[i];
+
+ if (Array.isArray(m.type)) {
+ var values = [];
+ values.length = m.type.length;
+ for (var j = 0; j < m.type.length; j++) {
+ value = dict[m.op] !== undefined ? dict[m.op][j] : undefined;
+ if (value === undefined) {
+ value = m.value !== undefined && m.value[j] !== undefined ? m.value[j] : null;
+ }
+ if (m.type[j] === 'SID') {
+ value = getCFFString(strings, value);
+ }
+ values[j] = value;
+ }
+ newDict[m.name] = values;
+ } else {
+ value = dict[m.op];
+ if (value === undefined) {
+ value = m.value !== undefined ? m.value : null;
+ }
+
+ if (m.type === 'SID') {
+ value = getCFFString(strings, value);
+ }
+ newDict[m.name] = value;
+ }
+ }
+
+ return newDict;
+}
+
+// Parse the CFF header.
+function parseCFFHeader(data, start) {
+ var header = {};
+ header.formatMajor = parse.getCard8(data, start);
+ header.formatMinor = parse.getCard8(data, start + 1);
+ header.size = parse.getCard8(data, start + 2);
+ header.offsetSize = parse.getCard8(data, start + 3);
+ header.startOffset = start;
+ header.endOffset = start + 4;
+ return header;
+}
+
+var TOP_DICT_META = [
+ {name: 'version', op: 0, type: 'SID'},
+ {name: 'notice', op: 1, type: 'SID'},
+ {name: 'copyright', op: 1200, type: 'SID'},
+ {name: 'fullName', op: 2, type: 'SID'},
+ {name: 'familyName', op: 3, type: 'SID'},
+ {name: 'weight', op: 4, type: 'SID'},
+ {name: 'isFixedPitch', op: 1201, type: 'number', value: 0},
+ {name: 'italicAngle', op: 1202, type: 'number', value: 0},
+ {name: 'underlinePosition', op: 1203, type: 'number', value: -100},
+ {name: 'underlineThickness', op: 1204, type: 'number', value: 50},
+ {name: 'paintType', op: 1205, type: 'number', value: 0},
+ {name: 'charstringType', op: 1206, type: 'number', value: 2},
+ {
+ name: 'fontMatrix',
+ op: 1207,
+ type: ['real', 'real', 'real', 'real', 'real', 'real'],
+ value: [0.001, 0, 0, 0.001, 0, 0]
+ },
+ {name: 'uniqueId', op: 13, type: 'number'},
+ {name: 'fontBBox', op: 5, type: ['number', 'number', 'number', 'number'], value: [0, 0, 0, 0]},
+ {name: 'strokeWidth', op: 1208, type: 'number', value: 0},
+ {name: 'xuid', op: 14, type: [], value: null},
+ {name: 'charset', op: 15, type: 'offset', value: 0},
+ {name: 'encoding', op: 16, type: 'offset', value: 0},
+ {name: 'charStrings', op: 17, type: 'offset', value: 0},
+ {name: 'private', op: 18, type: ['number', 'offset'], value: [0, 0]},
+ {name: 'ros', op: 1230, type: ['SID', 'SID', 'number']},
+ {name: 'cidFontVersion', op: 1231, type: 'number', value: 0},
+ {name: 'cidFontRevision', op: 1232, type: 'number', value: 0},
+ {name: 'cidFontType', op: 1233, type: 'number', value: 0},
+ {name: 'cidCount', op: 1234, type: 'number', value: 8720},
+ {name: 'uidBase', op: 1235, type: 'number'},
+ {name: 'fdArray', op: 1236, type: 'offset'},
+ {name: 'fdSelect', op: 1237, type: 'offset'},
+ {name: 'fontName', op: 1238, type: 'SID'}
+];
+
+var PRIVATE_DICT_META = [
+ {name: 'subrs', op: 19, type: 'offset', value: 0},
+ {name: 'defaultWidthX', op: 20, type: 'number', value: 0},
+ {name: 'nominalWidthX', op: 21, type: 'number', value: 0}
+];
+
+// Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary.
+// The top dictionary contains the essential metadata for the font, together with the private dictionary.
+function parseCFFTopDict(data, strings) {
+ var dict = parseCFFDict(data, 0, data.byteLength);
+ return interpretDict(dict, TOP_DICT_META, strings);
+}
+
+// Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need.
+function parseCFFPrivateDict(data, start, size, strings) {
+ var dict = parseCFFDict(data, start, size);
+ return interpretDict(dict, PRIVATE_DICT_META, strings);
+}
+
+// Returns a list of "Top DICT"s found using an INDEX list.
+// Used to read both the usual high-level Top DICTs and also the FDArray
+// discovered inside CID-keyed fonts. When a Top DICT has a reference to
+// a Private DICT that is read and saved into the Top DICT.
+//
+// In addition to the expected/optional values as outlined in TOP_DICT_META
+// the following values might be saved into the Top DICT.
+//
+// _subrs [] array of local CFF subroutines from Private DICT
+// _subrsBias bias value computed from number of subroutines
+// (see calcCFFSubroutineBias() and parseCFFCharstring())
+// _defaultWidthX default widths for CFF characters
+// _nominalWidthX bias added to width embedded within glyph description
+//
+// _privateDict saved copy of parsed Private DICT from Top DICT
+function gatherCFFTopDicts(data, start, cffIndex, strings) {
+ var topDictArray = [];
+ for (var iTopDict = 0; iTopDict < cffIndex.length; iTopDict += 1) {
+ var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer);
+ var topDict = parseCFFTopDict(topDictData, strings);
+ topDict._subrs = [];
+ topDict._subrsBias = 0;
+ var privateSize = topDict.private[0];
+ var privateOffset = topDict.private[1];
+ if (privateSize !== 0 && privateOffset !== 0) {
+ var privateDict = parseCFFPrivateDict(data, privateOffset + start, privateSize, strings);
+ topDict._defaultWidthX = privateDict.defaultWidthX;
+ topDict._nominalWidthX = privateDict.nominalWidthX;
+ if (privateDict.subrs !== 0) {
+ var subrOffset = privateOffset + privateDict.subrs;
+ var subrIndex = parseCFFIndex(data, subrOffset + start);
+ topDict._subrs = subrIndex.objects;
+ topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs);
+ }
+ topDict._privateDict = privateDict;
+ }
+ topDictArray.push(topDict);
+ }
+ return topDictArray;
+}
+
+// Parse the CFF charset table, which contains internal names for all the glyphs.
+// This function will return a list of glyph names.
+// See Adobe TN #5176 chapter 13, "Charsets".
+function parseCFFCharset(data, start, nGlyphs, strings) {
+ var sid;
+ var count;
+ var parser = new parse.Parser(data, start);
+
+ // The .notdef glyph is not included, so subtract 1.
+ nGlyphs -= 1;
+ var charset = ['.notdef'];
+
+ var format = parser.parseCard8();
+ if (format === 0) {
+ for (var i = 0; i < nGlyphs; i += 1) {
+ sid = parser.parseSID();
+ charset.push(getCFFString(strings, sid));
+ }
+ } else if (format === 1) {
+ while (charset.length <= nGlyphs) {
+ sid = parser.parseSID();
+ count = parser.parseCard8();
+ for (var i$1 = 0; i$1 <= count; i$1 += 1) {
+ charset.push(getCFFString(strings, sid));
+ sid += 1;
+ }
+ }
+ } else if (format === 2) {
+ while (charset.length <= nGlyphs) {
+ sid = parser.parseSID();
+ count = parser.parseCard16();
+ for (var i$2 = 0; i$2 <= count; i$2 += 1) {
+ charset.push(getCFFString(strings, sid));
+ sid += 1;
+ }
+ }
+ } else {
+ throw new Error('Unknown charset format ' + format);
+ }
+
+ return charset;
+}
+
+// Parse the CFF encoding data. Only one encoding can be specified per font.
+// See Adobe TN #5176 chapter 12, "Encodings".
+function parseCFFEncoding(data, start, charset) {
+ var code;
+ var enc = {};
+ var parser = new parse.Parser(data, start);
+ var format = parser.parseCard8();
+ if (format === 0) {
+ var nCodes = parser.parseCard8();
+ for (var i = 0; i < nCodes; i += 1) {
+ code = parser.parseCard8();
+ enc[code] = i;
+ }
+ } else if (format === 1) {
+ var nRanges = parser.parseCard8();
+ code = 1;
+ for (var i$1 = 0; i$1 < nRanges; i$1 += 1) {
+ var first = parser.parseCard8();
+ var nLeft = parser.parseCard8();
+ for (var j = first; j <= first + nLeft; j += 1) {
+ enc[j] = code;
+ code += 1;
+ }
+ }
+ } else {
+ throw new Error('Unknown encoding format ' + format);
+ }
+
+ return new CffEncoding(enc, charset);
+}
+
+// Take in charstring code and return a Glyph object.
+// The encoding is described in the Type 2 Charstring Format
+// https://www.microsoft.com/typography/OTSPEC/charstr2.htm
+function parseCFFCharstring(font, glyph, code) {
+ var c1x;
+ var c1y;
+ var c2x;
+ var c2y;
+ var p = new Path();
+ var stack = [];
+ var nStems = 0;
+ var haveWidth = false;
+ var open = false;
+ var x = 0;
+ var y = 0;
+ var subrs;
+ var subrsBias;
+ var defaultWidthX;
+ var nominalWidthX;
+ if (font.isCIDFont) {
+ var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index];
+ var fdDict = font.tables.cff.topDict._fdArray[fdIndex];
+ subrs = fdDict._subrs;
+ subrsBias = fdDict._subrsBias;
+ defaultWidthX = fdDict._defaultWidthX;
+ nominalWidthX = fdDict._nominalWidthX;
+ } else {
+ subrs = font.tables.cff.topDict._subrs;
+ subrsBias = font.tables.cff.topDict._subrsBias;
+ defaultWidthX = font.tables.cff.topDict._defaultWidthX;
+ nominalWidthX = font.tables.cff.topDict._nominalWidthX;
+ }
+ var width = defaultWidthX;
+
+ function newContour(x, y) {
+ if (open) {
+ p.closePath();
+ }
+
+ p.moveTo(x, y);
+ open = true;
+ }
+
+ function parseStems() {
+ var hasWidthArg;
+
+ // The number of stem operators on the stack is always even.
+ // If the value is uneven, that means a width is specified.
+ hasWidthArg = stack.length % 2 !== 0;
+ if (hasWidthArg && !haveWidth) {
+ width = stack.shift() + nominalWidthX;
+ }
+
+ nStems += stack.length >> 1;
+ stack.length = 0;
+ haveWidth = true;
+ }
+
+ function parse$$1(code) {
+ var b1;
+ var b2;
+ var b3;
+ var b4;
+ var codeIndex;
+ var subrCode;
+ var jpx;
+ var jpy;
+ var c3x;
+ var c3y;
+ var c4x;
+ var c4y;
+
+ var i = 0;
+ while (i < code.length) {
+ var v = code[i];
+ i += 1;
+ switch (v) {
+ case 1: // hstem
+ parseStems();
+ break;
+ case 3: // vstem
+ parseStems();
+ break;
+ case 4: // vmoveto
+ if (stack.length > 1 && !haveWidth) {
+ width = stack.shift() + nominalWidthX;
+ haveWidth = true;
+ }
+
+ y += stack.pop();
+ newContour(x, y);
+ break;
+ case 5: // rlineto
+ while (stack.length > 0) {
+ x += stack.shift();
+ y += stack.shift();
+ p.lineTo(x, y);
+ }
+
+ break;
+ case 6: // hlineto
+ while (stack.length > 0) {
+ x += stack.shift();
+ p.lineTo(x, y);
+ if (stack.length === 0) {
+ break;
+ }
+
+ y += stack.shift();
+ p.lineTo(x, y);
+ }
+
+ break;
+ case 7: // vlineto
+ while (stack.length > 0) {
+ y += stack.shift();
+ p.lineTo(x, y);
+ if (stack.length === 0) {
+ break;
+ }
+
+ x += stack.shift();
+ p.lineTo(x, y);
+ }
+
+ break;
+ case 8: // rrcurveto
+ while (stack.length > 0) {
+ c1x = x + stack.shift();
+ c1y = y + stack.shift();
+ c2x = c1x + stack.shift();
+ c2y = c1y + stack.shift();
+ x = c2x + stack.shift();
+ y = c2y + stack.shift();
+ p.curveTo(c1x, c1y, c2x, c2y, x, y);
+ }
+
+ break;
+ case 10: // callsubr
+ codeIndex = stack.pop() + subrsBias;
+ subrCode = subrs[codeIndex];
+ if (subrCode) {
+ parse$$1(subrCode);
+ }
+
+ break;
+ case 11: // return
+ return;
+ case 12: // flex operators
+ v = code[i];
+ i += 1;
+ switch (v) {
+ case 35: // flex
+ // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |-
+ c1x = x + stack.shift(); // dx1
+ c1y = y + stack.shift(); // dy1
+ c2x = c1x + stack.shift(); // dx2
+ c2y = c1y + stack.shift(); // dy2
+ jpx = c2x + stack.shift(); // dx3
+ jpy = c2y + stack.shift(); // dy3
+ c3x = jpx + stack.shift(); // dx4
+ c3y = jpy + stack.shift(); // dy4
+ c4x = c3x + stack.shift(); // dx5
+ c4y = c3y + stack.shift(); // dy5
+ x = c4x + stack.shift(); // dx6
+ y = c4y + stack.shift(); // dy6
+ stack.shift(); // flex depth
+ p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
+ p.curveTo(c3x, c3y, c4x, c4y, x, y);
+ break;
+ case 34: // hflex
+ // |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |-
+ c1x = x + stack.shift(); // dx1
+ c1y = y; // dy1
+ c2x = c1x + stack.shift(); // dx2
+ c2y = c1y + stack.shift(); // dy2
+ jpx = c2x + stack.shift(); // dx3
+ jpy = c2y; // dy3
+ c3x = jpx + stack.shift(); // dx4
+ c3y = c2y; // dy4
+ c4x = c3x + stack.shift(); // dx5
+ c4y = y; // dy5
+ x = c4x + stack.shift(); // dx6
+ p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
+ p.curveTo(c3x, c3y, c4x, c4y, x, y);
+ break;
+ case 36: // hflex1
+ // |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |-
+ c1x = x + stack.shift(); // dx1
+ c1y = y + stack.shift(); // dy1
+ c2x = c1x + stack.shift(); // dx2
+ c2y = c1y + stack.shift(); // dy2
+ jpx = c2x + stack.shift(); // dx3
+ jpy = c2y; // dy3
+ c3x = jpx + stack.shift(); // dx4
+ c3y = c2y; // dy4
+ c4x = c3x + stack.shift(); // dx5
+ c4y = c3y + stack.shift(); // dy5
+ x = c4x + stack.shift(); // dx6
+ p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
+ p.curveTo(c3x, c3y, c4x, c4y, x, y);
+ break;
+ case 37: // flex1
+ // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |-
+ c1x = x + stack.shift(); // dx1
+ c1y = y + stack.shift(); // dy1
+ c2x = c1x + stack.shift(); // dx2
+ c2y = c1y + stack.shift(); // dy2
+ jpx = c2x + stack.shift(); // dx3
+ jpy = c2y + stack.shift(); // dy3
+ c3x = jpx + stack.shift(); // dx4
+ c3y = jpy + stack.shift(); // dy4
+ c4x = c3x + stack.shift(); // dx5
+ c4y = c3y + stack.shift(); // dy5
+ if (Math.abs(c4x - x) > Math.abs(c4y - y)) {
+ x = c4x + stack.shift();
+ } else {
+ y = c4y + stack.shift();
+ }
+
+ p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
+ p.curveTo(c3x, c3y, c4x, c4y, x, y);
+ break;
+ default:
+ console.log('Glyph ' + glyph.index + ': unknown operator ' + 1200 + v);
+ stack.length = 0;
+ }
+ break;
+ case 14: // endchar
+ if (stack.length > 0 && !haveWidth) {
+ width = stack.shift() + nominalWidthX;
+ haveWidth = true;
+ }
+
+ if (open) {
+ p.closePath();
+ open = false;
+ }
+
+ break;
+ case 18: // hstemhm
+ parseStems();
+ break;
+ case 19: // hintmask
+ case 20: // cntrmask
+ parseStems();
+ i += (nStems + 7) >> 3;
+ break;
+ case 21: // rmoveto
+ if (stack.length > 2 && !haveWidth) {
+ width = stack.shift() + nominalWidthX;
+ haveWidth = true;
+ }
+
+ y += stack.pop();
+ x += stack.pop();
+ newContour(x, y);
+ break;
+ case 22: // hmoveto
+ if (stack.length > 1 && !haveWidth) {
+ width = stack.shift() + nominalWidthX;
+ haveWidth = true;
+ }
+
+ x += stack.pop();
+ newContour(x, y);
+ break;
+ case 23: // vstemhm
+ parseStems();
+ break;
+ case 24: // rcurveline
+ while (stack.length > 2) {
+ c1x = x + stack.shift();
+ c1y = y + stack.shift();
+ c2x = c1x + stack.shift();
+ c2y = c1y + stack.shift();
+ x = c2x + stack.shift();
+ y = c2y + stack.shift();
+ p.curveTo(c1x, c1y, c2x, c2y, x, y);
+ }
+
+ x += stack.shift();
+ y += stack.shift();
+ p.lineTo(x, y);
+ break;
+ case 25: // rlinecurve
+ while (stack.length > 6) {
+ x += stack.shift();
+ y += stack.shift();
+ p.lineTo(x, y);
+ }
+
+ c1x = x + stack.shift();
+ c1y = y + stack.shift();
+ c2x = c1x + stack.shift();
+ c2y = c1y + stack.shift();
+ x = c2x + stack.shift();
+ y = c2y + stack.shift();
+ p.curveTo(c1x, c1y, c2x, c2y, x, y);
+ break;
+ case 26: // vvcurveto
+ if (stack.length % 2) {
+ x += stack.shift();
+ }
+
+ while (stack.length > 0) {
+ c1x = x;
+ c1y = y + stack.shift();
+ c2x = c1x + stack.shift();
+ c2y = c1y + stack.shift();
+ x = c2x;
+ y = c2y + stack.shift();
+ p.curveTo(c1x, c1y, c2x, c2y, x, y);
+ }
+
+ break;
+ case 27: // hhcurveto
+ if (stack.length % 2) {
+ y += stack.shift();
+ }
+
+ while (stack.length > 0) {
+ c1x = x + stack.shift();
+ c1y = y;
+ c2x = c1x + stack.shift();
+ c2y = c1y + stack.shift();
+ x = c2x + stack.shift();
+ y = c2y;
+ p.curveTo(c1x, c1y, c2x, c2y, x, y);
+ }
+
+ break;
+ case 28: // shortint
+ b1 = code[i];
+ b2 = code[i + 1];
+ stack.push(((b1 << 24) | (b2 << 16)) >> 16);
+ i += 2;
+ break;
+ case 29: // callgsubr
+ codeIndex = stack.pop() + font.gsubrsBias;
+ subrCode = font.gsubrs[codeIndex];
+ if (subrCode) {
+ parse$$1(subrCode);
+ }
+
+ break;
+ case 30: // vhcurveto
+ while (stack.length > 0) {
+ c1x = x;
+ c1y = y + stack.shift();
+ c2x = c1x + stack.shift();
+ c2y = c1y + stack.shift();
+ x = c2x + stack.shift();
+ y = c2y + (stack.length === 1 ? stack.shift() : 0);
+ p.curveTo(c1x, c1y, c2x, c2y, x, y);
+ if (stack.length === 0) {
+ break;
+ }
+
+ c1x = x + stack.shift();
+ c1y = y;
+ c2x = c1x + stack.shift();
+ c2y = c1y + stack.shift();
+ y = c2y + stack.shift();
+ x = c2x + (stack.length === 1 ? stack.shift() : 0);
+ p.curveTo(c1x, c1y, c2x, c2y, x, y);
+ }
+
+ break;
+ case 31: // hvcurveto
+ while (stack.length > 0) {
+ c1x = x + stack.shift();
+ c1y = y;
+ c2x = c1x + stack.shift();
+ c2y = c1y + stack.shift();
+ y = c2y + stack.shift();
+ x = c2x + (stack.length === 1 ? stack.shift() : 0);
+ p.curveTo(c1x, c1y, c2x, c2y, x, y);
+ if (stack.length === 0) {
+ break;
+ }
+
+ c1x = x;
+ c1y = y + stack.shift();
+ c2x = c1x + stack.shift();
+ c2y = c1y + stack.shift();
+ x = c2x + stack.shift();
+ y = c2y + (stack.length === 1 ? stack.shift() : 0);
+ p.curveTo(c1x, c1y, c2x, c2y, x, y);
+ }
+
+ break;
+ default:
+ if (v < 32) {
+ console.log('Glyph ' + glyph.index + ': unknown operator ' + v);
+ } else if (v < 247) {
+ stack.push(v - 139);
+ } else if (v < 251) {
+ b1 = code[i];
+ i += 1;
+ stack.push((v - 247) * 256 + b1 + 108);
+ } else if (v < 255) {
+ b1 = code[i];
+ i += 1;
+ stack.push(-(v - 251) * 256 - b1 - 108);
+ } else {
+ b1 = code[i];
+ b2 = code[i + 1];
+ b3 = code[i + 2];
+ b4 = code[i + 3];
+ i += 4;
+ stack.push(((b1 << 24) | (b2 << 16) | (b3 << 8) | b4) / 65536);
+ }
+ }
+ }
+ }
+
+ parse$$1(code);
+
+ glyph.advanceWidth = width;
+ return p;
+}
+
+function parseCFFFDSelect(data, start, nGlyphs, fdArrayCount) {
+ var fdSelect = [];
+ var fdIndex;
+ var parser = new parse.Parser(data, start);
+ var format = parser.parseCard8();
+ if (format === 0) {
+ // Simple list of nGlyphs elements
+ for (var iGid = 0; iGid < nGlyphs; iGid++) {
+ fdIndex = parser.parseCard8();
+ if (fdIndex >= fdArrayCount) {
+ throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')');
+ }
+ fdSelect.push(fdIndex);
+ }
+ } else if (format === 3) {
+ // Ranges
+ var nRanges = parser.parseCard16();
+ var first = parser.parseCard16();
+ if (first !== 0) {
+ throw new Error('CFF Table CID Font FDSelect format 3 range has bad initial GID ' + first);
+ }
+ var next;
+ for (var iRange = 0; iRange < nRanges; iRange++) {
+ fdIndex = parser.parseCard8();
+ next = parser.parseCard16();
+ if (fdIndex >= fdArrayCount) {
+ throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')');
+ }
+ if (next > nGlyphs) {
+ throw new Error('CFF Table CID Font FDSelect format 3 range has bad GID ' + next);
+ }
+ for (; first < next; first++) {
+ fdSelect.push(fdIndex);
+ }
+ first = next;
+ }
+ if (next !== nGlyphs) {
+ throw new Error('CFF Table CID Font FDSelect format 3 range has bad final GID ' + next);
+ }
+ } else {
+ throw new Error('CFF Table CID Font FDSelect table has unsupported format ' + format);
+ }
+ return fdSelect;
+}
+
+// Parse the `CFF` table, which contains the glyph outlines in PostScript format.
+function parseCFFTable(data, start, font) {
+ font.tables.cff = {};
+ var header = parseCFFHeader(data, start);
+ var nameIndex = parseCFFIndex(data, header.endOffset, parse.bytesToString);
+ var topDictIndex = parseCFFIndex(data, nameIndex.endOffset);
+ var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse.bytesToString);
+ var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset);
+ font.gsubrs = globalSubrIndex.objects;
+ font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs);
+
+ var topDictArray = gatherCFFTopDicts(data, start, topDictIndex.objects, stringIndex.objects);
+ if (topDictArray.length !== 1) {
+ throw new Error('CFF table has too many fonts in \'FontSet\' - count of fonts NameIndex.length = ' + topDictArray.length);
+ }
+
+ var topDict = topDictArray[0];
+ font.tables.cff.topDict = topDict;
+
+ if (topDict._privateDict) {
+ font.defaultWidthX = topDict._privateDict.defaultWidthX;
+ font.nominalWidthX = topDict._privateDict.nominalWidthX;
+ }
+
+ if (topDict.ros[0] !== undefined && topDict.ros[1] !== undefined) {
+ font.isCIDFont = true;
+ }
+
+ if (font.isCIDFont) {
+ var fdArrayOffset = topDict.fdArray;
+ var fdSelectOffset = topDict.fdSelect;
+ if (fdArrayOffset === 0 || fdSelectOffset === 0) {
+ throw new Error('Font is marked as a CID font, but FDArray and/or FDSelect information is missing');
+ }
+ fdArrayOffset += start;
+ var fdArrayIndex = parseCFFIndex(data, fdArrayOffset);
+ var fdArray = gatherCFFTopDicts(data, start, fdArrayIndex.objects, stringIndex.objects);
+ topDict._fdArray = fdArray;
+ fdSelectOffset += start;
+ topDict._fdSelect = parseCFFFDSelect(data, fdSelectOffset, font.numGlyphs, fdArray.length);
+ }
+
+ var privateDictOffset = start + topDict.private[1];
+ var privateDict = parseCFFPrivateDict(data, privateDictOffset, topDict.private[0], stringIndex.objects);
+ font.defaultWidthX = privateDict.defaultWidthX;
+ font.nominalWidthX = privateDict.nominalWidthX;
+
+ if (privateDict.subrs !== 0) {
+ var subrOffset = privateDictOffset + privateDict.subrs;
+ var subrIndex = parseCFFIndex(data, subrOffset);
+ font.subrs = subrIndex.objects;
+ font.subrsBias = calcCFFSubroutineBias(font.subrs);
+ } else {
+ font.subrs = [];
+ font.subrsBias = 0;
+ }
+
+ // Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset.
+ var charStringsIndex = parseCFFIndex(data, start + topDict.charStrings);
+ font.nGlyphs = charStringsIndex.objects.length;
+
+ var charset = parseCFFCharset(data, start + topDict.charset, font.nGlyphs, stringIndex.objects);
+ if (topDict.encoding === 0) { // Standard encoding
+ font.cffEncoding = new CffEncoding(cffStandardEncoding, charset);
+ } else if (topDict.encoding === 1) { // Expert encoding
+ font.cffEncoding = new CffEncoding(cffExpertEncoding, charset);
+ } else {
+ font.cffEncoding = parseCFFEncoding(data, start + topDict.encoding, charset);
+ }
+
+ // Prefer the CMAP encoding to the CFF encoding.
+ font.encoding = font.encoding || font.cffEncoding;
+
+ font.glyphs = new glyphset.GlyphSet(font);
+ for (var i = 0; i < font.nGlyphs; i += 1) {
+ var charString = charStringsIndex.objects[i];
+ font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString));
+ }
+}
+
+// Convert a string to a String ID (SID).
+// The list of strings is modified in place.
+function encodeString(s, strings) {
+ var sid;
+
+ // Is the string in the CFF standard strings?
+ var i = cffStandardStrings.indexOf(s);
+ if (i >= 0) {
+ sid = i;
+ }
+
+ // Is the string already in the string index?
+ i = strings.indexOf(s);
+ if (i >= 0) {
+ sid = i + cffStandardStrings.length;
+ } else {
+ sid = cffStandardStrings.length + strings.length;
+ strings.push(s);
+ }
+
+ return sid;
+}
+
+function makeHeader() {
+ return new table.Record('Header', [
+ {name: 'major', type: 'Card8', value: 1},
+ {name: 'minor', type: 'Card8', value: 0},
+ {name: 'hdrSize', type: 'Card8', value: 4},
+ {name: 'major', type: 'Card8', value: 1}
+ ]);
+}
+
+function makeNameIndex(fontNames) {
+ var t = new table.Record('Name INDEX', [
+ {name: 'names', type: 'INDEX', value: []}
+ ]);
+ t.names = [];
+ for (var i = 0; i < fontNames.length; i += 1) {
+ t.names.push({name: 'name_' + i, type: 'NAME', value: fontNames[i]});
+ }
+
+ return t;
+}
+
+// Given a dictionary's metadata, create a DICT structure.
+function makeDict(meta, attrs, strings) {
+ var m = {};
+ for (var i = 0; i < meta.length; i += 1) {
+ var entry = meta[i];
+ var value = attrs[entry.name];
+ if (value !== undefined && !equals(value, entry.value)) {
+ if (entry.type === 'SID') {
+ value = encodeString(value, strings);
+ }
+
+ m[entry.op] = {name: entry.name, type: entry.type, value: value};
+ }
+ }
+
+ return m;
+}
+
+// The Top DICT houses the global font attributes.
+function makeTopDict(attrs, strings) {
+ var t = new table.Record('Top DICT', [
+ {name: 'dict', type: 'DICT', value: {}}
+ ]);
+ t.dict = makeDict(TOP_DICT_META, attrs, strings);
+ return t;
+}
+
+function makeTopDictIndex(topDict) {
+ var t = new table.Record('Top DICT INDEX', [
+ {name: 'topDicts', type: 'INDEX', value: []}
+ ]);
+ t.topDicts = [{name: 'topDict_0', type: 'TABLE', value: topDict}];
+ return t;
+}
+
+function makeStringIndex(strings) {
+ var t = new table.Record('String INDEX', [
+ {name: 'strings', type: 'INDEX', value: []}
+ ]);
+ t.strings = [];
+ for (var i = 0; i < strings.length; i += 1) {
+ t.strings.push({name: 'string_' + i, type: 'STRING', value: strings[i]});
+ }
+
+ return t;
+}
+
+function makeGlobalSubrIndex() {
+ // Currently we don't use subroutines.
+ return new table.Record('Global Subr INDEX', [
+ {name: 'subrs', type: 'INDEX', value: []}
+ ]);
+}
+
+function makeCharsets(glyphNames, strings) {
+ var t = new table.Record('Charsets', [
+ {name: 'format', type: 'Card8', value: 0}
+ ]);
+ for (var i = 0; i < glyphNames.length; i += 1) {
+ var glyphName = glyphNames[i];
+ var glyphSID = encodeString(glyphName, strings);
+ t.fields.push({name: 'glyph_' + i, type: 'SID', value: glyphSID});
+ }
+
+ return t;
+}
+
+function glyphToOps(glyph) {
+ var ops = [];
+ var path = glyph.path;
+ ops.push({name: 'width', type: 'NUMBER', value: glyph.advanceWidth});
+ var x = 0;
+ var y = 0;
+ for (var i = 0; i < path.commands.length; i += 1) {
+ var dx = (void 0);
+ var dy = (void 0);
+ var cmd = path.commands[i];
+ if (cmd.type === 'Q') {
+ // CFF only supports bézier curves, so convert the quad to a bézier.
+ var _13 = 1 / 3;
+ var _23 = 2 / 3;
+
+ // We're going to create a new command so we don't change the original path.
+ cmd = {
+ type: 'C',
+ x: cmd.x,
+ y: cmd.y,
+ x1: _13 * x + _23 * cmd.x1,
+ y1: _13 * y + _23 * cmd.y1,
+ x2: _13 * cmd.x + _23 * cmd.x1,
+ y2: _13 * cmd.y + _23 * cmd.y1
+ };
+ }
+
+ if (cmd.type === 'M') {
+ dx = Math.round(cmd.x - x);
+ dy = Math.round(cmd.y - y);
+ ops.push({name: 'dx', type: 'NUMBER', value: dx});
+ ops.push({name: 'dy', type: 'NUMBER', value: dy});
+ ops.push({name: 'rmoveto', type: 'OP', value: 21});
+ x = Math.round(cmd.x);
+ y = Math.round(cmd.y);
+ } else if (cmd.type === 'L') {
+ dx = Math.round(cmd.x - x);
+ dy = Math.round(cmd.y - y);
+ ops.push({name: 'dx', type: 'NUMBER', value: dx});
+ ops.push({name: 'dy', type: 'NUMBER', value: dy});
+ ops.push({name: 'rlineto', type: 'OP', value: 5});
+ x = Math.round(cmd.x);
+ y = Math.round(cmd.y);
+ } else if (cmd.type === 'C') {
+ var dx1 = Math.round(cmd.x1 - x);
+ var dy1 = Math.round(cmd.y1 - y);
+ var dx2 = Math.round(cmd.x2 - cmd.x1);
+ var dy2 = Math.round(cmd.y2 - cmd.y1);
+ dx = Math.round(cmd.x - cmd.x2);
+ dy = Math.round(cmd.y - cmd.y2);
+ ops.push({name: 'dx1', type: 'NUMBER', value: dx1});
+ ops.push({name: 'dy1', type: 'NUMBER', value: dy1});
+ ops.push({name: 'dx2', type: 'NUMBER', value: dx2});
+ ops.push({name: 'dy2', type: 'NUMBER', value: dy2});
+ ops.push({name: 'dx', type: 'NUMBER', value: dx});
+ ops.push({name: 'dy', type: 'NUMBER', value: dy});
+ ops.push({name: 'rrcurveto', type: 'OP', value: 8});
+ x = Math.round(cmd.x);
+ y = Math.round(cmd.y);
+ }
+
+ // Contours are closed automatically.
+ }
+
+ ops.push({name: 'endchar', type: 'OP', value: 14});
+ return ops;
+}
+
+function makeCharStringsIndex(glyphs) {
+ var t = new table.Record('CharStrings INDEX', [
+ {name: 'charStrings', type: 'INDEX', value: []}
+ ]);
+
+ for (var i = 0; i < glyphs.length; i += 1) {
+ var glyph = glyphs.get(i);
+ var ops = glyphToOps(glyph);
+ t.charStrings.push({name: glyph.name, type: 'CHARSTRING', value: ops});
+ }
+
+ return t;
+}
+
+function makePrivateDict(attrs, strings) {
+ var t = new table.Record('Private DICT', [
+ {name: 'dict', type: 'DICT', value: {}}
+ ]);
+ t.dict = makeDict(PRIVATE_DICT_META, attrs, strings);
+ return t;
+}
+
+function makeCFFTable(glyphs, options) {
+ var t = new table.Table('CFF ', [
+ {name: 'header', type: 'RECORD'},
+ {name: 'nameIndex', type: 'RECORD'},
+ {name: 'topDictIndex', type: 'RECORD'},
+ {name: 'stringIndex', type: 'RECORD'},
+ {name: 'globalSubrIndex', type: 'RECORD'},
+ {name: 'charsets', type: 'RECORD'},
+ {name: 'charStringsIndex', type: 'RECORD'},
+ {name: 'privateDict', type: 'RECORD'}
+ ]);
+
+ var fontScale = 1 / options.unitsPerEm;
+ // We use non-zero values for the offsets so that the DICT encodes them.
+ // This is important because the size of the Top DICT plays a role in offset calculation,
+ // and the size shouldn't change after we've written correct offsets.
+ var attrs = {
+ version: options.version,
+ fullName: options.fullName,
+ familyName: options.familyName,
+ weight: options.weightName,
+ fontBBox: options.fontBBox || [0, 0, 0, 0],
+ fontMatrix: [fontScale, 0, 0, fontScale, 0, 0],
+ charset: 999,
+ encoding: 0,
+ charStrings: 999,
+ private: [0, 999]
+ };
+
+ var privateAttrs = {};
+
+ var glyphNames = [];
+ var glyph;
+
+ // Skip first glyph (.notdef)
+ for (var i = 1; i < glyphs.length; i += 1) {
+ glyph = glyphs.get(i);
+ glyphNames.push(glyph.name);
+ }
+
+ var strings = [];
+
+ t.header = makeHeader();
+ t.nameIndex = makeNameIndex([options.postScriptName]);
+ var topDict = makeTopDict(attrs, strings);
+ t.topDictIndex = makeTopDictIndex(topDict);
+ t.globalSubrIndex = makeGlobalSubrIndex();
+ t.charsets = makeCharsets(glyphNames, strings);
+ t.charStringsIndex = makeCharStringsIndex(glyphs);
+ t.privateDict = makePrivateDict(privateAttrs, strings);
+
+ // Needs to come at the end, to encode all custom strings used in the font.
+ t.stringIndex = makeStringIndex(strings);
+
+ var startOffset = t.header.sizeOf() +
+ t.nameIndex.sizeOf() +
+ t.topDictIndex.sizeOf() +
+ t.stringIndex.sizeOf() +
+ t.globalSubrIndex.sizeOf();
+ attrs.charset = startOffset;
+
+ // We use the CFF standard encoding; proper encoding will be handled in cmap.
+ attrs.encoding = 0;
+ attrs.charStrings = attrs.charset + t.charsets.sizeOf();
+ attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf();
+
+ // Recreate the Top DICT INDEX with the correct offsets.
+ topDict = makeTopDict(attrs, strings);
+ t.topDictIndex = makeTopDictIndex(topDict);
+
+ return t;
+}
+
+var cff = { parse: parseCFFTable, make: makeCFFTable };
+
+// The `head` table contains global information about the font.
+// https://www.microsoft.com/typography/OTSPEC/head.htm
+
+// Parse the header `head` table
+function parseHeadTable(data, start) {
+ var head = {};
+ var p = new parse.Parser(data, start);
+ head.version = p.parseVersion();
+ head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000;
+ head.checkSumAdjustment = p.parseULong();
+ head.magicNumber = p.parseULong();
+ check.argument(head.magicNumber === 0x5F0F3CF5, 'Font header has wrong magic number.');
+ head.flags = p.parseUShort();
+ head.unitsPerEm = p.parseUShort();
+ head.created = p.parseLongDateTime();
+ head.modified = p.parseLongDateTime();
+ head.xMin = p.parseShort();
+ head.yMin = p.parseShort();
+ head.xMax = p.parseShort();
+ head.yMax = p.parseShort();
+ head.macStyle = p.parseUShort();
+ head.lowestRecPPEM = p.parseUShort();
+ head.fontDirectionHint = p.parseShort();
+ head.indexToLocFormat = p.parseShort();
+ head.glyphDataFormat = p.parseShort();
+ return head;
+}
+
+function makeHeadTable(options) {
+ // Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970
+ var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800;
+ var createdTimestamp = timestamp;
+
+ if (options.createdTimestamp) {
+ createdTimestamp = options.createdTimestamp + 2082844800;
+ }
+
+ return new table.Table('head', [
+ {name: 'version', type: 'FIXED', value: 0x00010000},
+ {name: 'fontRevision', type: 'FIXED', value: 0x00010000},
+ {name: 'checkSumAdjustment', type: 'ULONG', value: 0},
+ {name: 'magicNumber', type: 'ULONG', value: 0x5F0F3CF5},
+ {name: 'flags', type: 'USHORT', value: 0},
+ {name: 'unitsPerEm', type: 'USHORT', value: 1000},
+ {name: 'created', type: 'LONGDATETIME', value: createdTimestamp},
+ {name: 'modified', type: 'LONGDATETIME', value: timestamp},
+ {name: 'xMin', type: 'SHORT', value: 0},
+ {name: 'yMin', type: 'SHORT', value: 0},
+ {name: 'xMax', type: 'SHORT', value: 0},
+ {name: 'yMax', type: 'SHORT', value: 0},
+ {name: 'macStyle', type: 'USHORT', value: 0},
+ {name: 'lowestRecPPEM', type: 'USHORT', value: 0},
+ {name: 'fontDirectionHint', type: 'SHORT', value: 2},
+ {name: 'indexToLocFormat', type: 'SHORT', value: 0},
+ {name: 'glyphDataFormat', type: 'SHORT', value: 0}
+ ], options);
+}
+
+var head = { parse: parseHeadTable, make: makeHeadTable };
+
+// The `hhea` table contains information for horizontal layout.
+// https://www.microsoft.com/typography/OTSPEC/hhea.htm
+
+// Parse the horizontal header `hhea` table
+function parseHheaTable(data, start) {
+ var hhea = {};
+ var p = new parse.Parser(data, start);
+ hhea.version = p.parseVersion();
+ hhea.ascender = p.parseShort();
+ hhea.descender = p.parseShort();
+ hhea.lineGap = p.parseShort();
+ hhea.advanceWidthMax = p.parseUShort();
+ hhea.minLeftSideBearing = p.parseShort();
+ hhea.minRightSideBearing = p.parseShort();
+ hhea.xMaxExtent = p.parseShort();
+ hhea.caretSlopeRise = p.parseShort();
+ hhea.caretSlopeRun = p.parseShort();
+ hhea.caretOffset = p.parseShort();
+ p.relativeOffset += 8;
+ hhea.metricDataFormat = p.parseShort();
+ hhea.numberOfHMetrics = p.parseUShort();
+ return hhea;
+}
+
+function makeHheaTable(options) {
+ return new table.Table('hhea', [
+ {name: 'version', type: 'FIXED', value: 0x00010000},
+ {name: 'ascender', type: 'FWORD', value: 0},
+ {name: 'descender', type: 'FWORD', value: 0},
+ {name: 'lineGap', type: 'FWORD', value: 0},
+ {name: 'advanceWidthMax', type: 'UFWORD', value: 0},
+ {name: 'minLeftSideBearing', type: 'FWORD', value: 0},
+ {name: 'minRightSideBearing', type: 'FWORD', value: 0},
+ {name: 'xMaxExtent', type: 'FWORD', value: 0},
+ {name: 'caretSlopeRise', type: 'SHORT', value: 1},
+ {name: 'caretSlopeRun', type: 'SHORT', value: 0},
+ {name: 'caretOffset', type: 'SHORT', value: 0},
+ {name: 'reserved1', type: 'SHORT', value: 0},
+ {name: 'reserved2', type: 'SHORT', value: 0},
+ {name: 'reserved3', type: 'SHORT', value: 0},
+ {name: 'reserved4', type: 'SHORT', value: 0},
+ {name: 'metricDataFormat', type: 'SHORT', value: 0},
+ {name: 'numberOfHMetrics', type: 'USHORT', value: 0}
+ ], options);
+}
+
+var hhea = { parse: parseHheaTable, make: makeHheaTable };
+
+// The `hmtx` table contains the horizontal metrics for all glyphs.
+// https://www.microsoft.com/typography/OTSPEC/hmtx.htm
+
+// Parse the `hmtx` table, which contains the horizontal metrics for all glyphs.
+// This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph.
+function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) {
+ var advanceWidth;
+ var leftSideBearing;
+ var p = new parse.Parser(data, start);
+ for (var i = 0; i < numGlyphs; i += 1) {
+ // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs.
+ if (i < numMetrics) {
+ advanceWidth = p.parseUShort();
+ leftSideBearing = p.parseShort();
+ }
+
+ var glyph = glyphs.get(i);
+ glyph.advanceWidth = advanceWidth;
+ glyph.leftSideBearing = leftSideBearing;
+ }
+}
+
+function makeHmtxTable(glyphs) {
+ var t = new table.Table('hmtx', []);
+ for (var i = 0; i < glyphs.length; i += 1) {
+ var glyph = glyphs.get(i);
+ var advanceWidth = glyph.advanceWidth || 0;
+ var leftSideBearing = glyph.leftSideBearing || 0;
+ t.fields.push({name: 'advanceWidth_' + i, type: 'USHORT', value: advanceWidth});
+ t.fields.push({name: 'leftSideBearing_' + i, type: 'SHORT', value: leftSideBearing});
+ }
+
+ return t;
+}
+
+var hmtx = { parse: parseHmtxTable, make: makeHmtxTable };
+
+// The `ltag` table stores IETF BCP-47 language tags. It allows supporting
+// languages for which TrueType does not assign a numeric code.
+// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ltag.html
+// http://www.w3.org/International/articles/language-tags/
+// http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
+
+function makeLtagTable(tags) {
+ var result = new table.Table('ltag', [
+ {name: 'version', type: 'ULONG', value: 1},
+ {name: 'flags', type: 'ULONG', value: 0},
+ {name: 'numTags', type: 'ULONG', value: tags.length}
+ ]);
+
+ var stringPool = '';
+ var stringPoolOffset = 12 + tags.length * 4;
+ for (var i = 0; i < tags.length; ++i) {
+ var pos = stringPool.indexOf(tags[i]);
+ if (pos < 0) {
+ pos = stringPool.length;
+ stringPool += tags[i];
+ }
+
+ result.fields.push({name: 'offset ' + i, type: 'USHORT', value: stringPoolOffset + pos});
+ result.fields.push({name: 'length ' + i, type: 'USHORT', value: tags[i].length});
+ }
+
+ result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool});
+ return result;
+}
+
+function parseLtagTable(data, start) {
+ var p = new parse.Parser(data, start);
+ var tableVersion = p.parseULong();
+ check.argument(tableVersion === 1, 'Unsupported ltag table version.');
+ // The 'ltag' specification does not define any flags; skip the field.
+ p.skip('uLong', 1);
+ var numTags = p.parseULong();
+
+ var tags = [];
+ for (var i = 0; i < numTags; i++) {
+ var tag = '';
+ var offset = start + p.parseUShort();
+ var length = p.parseUShort();
+ for (var j = offset; j < offset + length; ++j) {
+ tag += String.fromCharCode(data.getInt8(j));
+ }
+
+ tags.push(tag);
+ }
+
+ return tags;
+}
+
+var ltag = { make: makeLtagTable, parse: parseLtagTable };
+
+// The `maxp` table establishes the memory requirements for the font.
+// We need it just to get the number of glyphs in the font.
+// https://www.microsoft.com/typography/OTSPEC/maxp.htm
+
+// Parse the maximum profile `maxp` table.
+function parseMaxpTable(data, start) {
+ var maxp = {};
+ var p = new parse.Parser(data, start);
+ maxp.version = p.parseVersion();
+ maxp.numGlyphs = p.parseUShort();
+ if (maxp.version === 1.0) {
+ maxp.maxPoints = p.parseUShort();
+ maxp.maxContours = p.parseUShort();
+ maxp.maxCompositePoints = p.parseUShort();
+ maxp.maxCompositeContours = p.parseUShort();
+ maxp.maxZones = p.parseUShort();
+ maxp.maxTwilightPoints = p.parseUShort();
+ maxp.maxStorage = p.parseUShort();
+ maxp.maxFunctionDefs = p.parseUShort();
+ maxp.maxInstructionDefs = p.parseUShort();
+ maxp.maxStackElements = p.parseUShort();
+ maxp.maxSizeOfInstructions = p.parseUShort();
+ maxp.maxComponentElements = p.parseUShort();
+ maxp.maxComponentDepth = p.parseUShort();
+ }
+
+ return maxp;
+}
+
+function makeMaxpTable(numGlyphs) {
+ return new table.Table('maxp', [
+ {name: 'version', type: 'FIXED', value: 0x00005000},
+ {name: 'numGlyphs', type: 'USHORT', value: numGlyphs}
+ ]);
+}
+
+var maxp = { parse: parseMaxpTable, make: makeMaxpTable };
+
+// The `name` naming table.
+// https://www.microsoft.com/typography/OTSPEC/name.htm
+
+// NameIDs for the name table.
+var nameTableNames = [
+ 'copyright', // 0
+ 'fontFamily', // 1
+ 'fontSubfamily', // 2
+ 'uniqueID', // 3
+ 'fullName', // 4
+ 'version', // 5
+ 'postScriptName', // 6
+ 'trademark', // 7
+ 'manufacturer', // 8
+ 'designer', // 9
+ 'description', // 10
+ 'manufacturerURL', // 11
+ 'designerURL', // 12
+ 'license', // 13
+ 'licenseURL', // 14
+ 'reserved', // 15
+ 'preferredFamily', // 16
+ 'preferredSubfamily', // 17
+ 'compatibleFullName', // 18
+ 'sampleText', // 19
+ 'postScriptFindFontName', // 20
+ 'wwsFamily', // 21
+ 'wwsSubfamily' // 22
+];
+
+var macLanguages = {
+ 0: 'en',
+ 1: 'fr',
+ 2: 'de',
+ 3: 'it',
+ 4: 'nl',
+ 5: 'sv',
+ 6: 'es',
+ 7: 'da',
+ 8: 'pt',
+ 9: 'no',
+ 10: 'he',
+ 11: 'ja',
+ 12: 'ar',
+ 13: 'fi',
+ 14: 'el',
+ 15: 'is',
+ 16: 'mt',
+ 17: 'tr',
+ 18: 'hr',
+ 19: 'zh-Hant',
+ 20: 'ur',
+ 21: 'hi',
+ 22: 'th',
+ 23: 'ko',
+ 24: 'lt',
+ 25: 'pl',
+ 26: 'hu',
+ 27: 'es',
+ 28: 'lv',
+ 29: 'se',
+ 30: 'fo',
+ 31: 'fa',
+ 32: 'ru',
+ 33: 'zh',
+ 34: 'nl-BE',
+ 35: 'ga',
+ 36: 'sq',
+ 37: 'ro',
+ 38: 'cz',
+ 39: 'sk',
+ 40: 'si',
+ 41: 'yi',
+ 42: 'sr',
+ 43: 'mk',
+ 44: 'bg',
+ 45: 'uk',
+ 46: 'be',
+ 47: 'uz',
+ 48: 'kk',
+ 49: 'az-Cyrl',
+ 50: 'az-Arab',
+ 51: 'hy',
+ 52: 'ka',
+ 53: 'mo',
+ 54: 'ky',
+ 55: 'tg',
+ 56: 'tk',
+ 57: 'mn-CN',
+ 58: 'mn',
+ 59: 'ps',
+ 60: 'ks',
+ 61: 'ku',
+ 62: 'sd',
+ 63: 'bo',
+ 64: 'ne',
+ 65: 'sa',
+ 66: 'mr',
+ 67: 'bn',
+ 68: 'as',
+ 69: 'gu',
+ 70: 'pa',
+ 71: 'or',
+ 72: 'ml',
+ 73: 'kn',
+ 74: 'ta',
+ 75: 'te',
+ 76: 'si',
+ 77: 'my',
+ 78: 'km',
+ 79: 'lo',
+ 80: 'vi',
+ 81: 'id',
+ 82: 'tl',
+ 83: 'ms',
+ 84: 'ms-Arab',
+ 85: 'am',
+ 86: 'ti',
+ 87: 'om',
+ 88: 'so',
+ 89: 'sw',
+ 90: 'rw',
+ 91: 'rn',
+ 92: 'ny',
+ 93: 'mg',
+ 94: 'eo',
+ 128: 'cy',
+ 129: 'eu',
+ 130: 'ca',
+ 131: 'la',
+ 132: 'qu',
+ 133: 'gn',
+ 134: 'ay',
+ 135: 'tt',
+ 136: 'ug',
+ 137: 'dz',
+ 138: 'jv',
+ 139: 'su',
+ 140: 'gl',
+ 141: 'af',
+ 142: 'br',
+ 143: 'iu',
+ 144: 'gd',
+ 145: 'gv',
+ 146: 'ga',
+ 147: 'to',
+ 148: 'el-polyton',
+ 149: 'kl',
+ 150: 'az',
+ 151: 'nn'
+};
+
+// MacOS language ID → MacOS script ID
+//
+// Note that the script ID is not sufficient to determine what encoding
+// to use in TrueType files. For some languages, MacOS used a modification
+// of a mainstream script. For example, an Icelandic name would be stored
+// with smRoman in the TrueType naming table, but the actual encoding
+// is a special Icelandic version of the normal Macintosh Roman encoding.
+// As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal
+// Syllables but MacOS had run out of available script codes, so this was
+// done as a (pretty radical) "modification" of Ethiopic.
+//
+// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt
+var macLanguageToScript = {
+ 0: 0, // langEnglish → smRoman
+ 1: 0, // langFrench → smRoman
+ 2: 0, // langGerman → smRoman
+ 3: 0, // langItalian → smRoman
+ 4: 0, // langDutch → smRoman
+ 5: 0, // langSwedish → smRoman
+ 6: 0, // langSpanish → smRoman
+ 7: 0, // langDanish → smRoman
+ 8: 0, // langPortuguese → smRoman
+ 9: 0, // langNorwegian → smRoman
+ 10: 5, // langHebrew → smHebrew
+ 11: 1, // langJapanese → smJapanese
+ 12: 4, // langArabic → smArabic
+ 13: 0, // langFinnish → smRoman
+ 14: 6, // langGreek → smGreek
+ 15: 0, // langIcelandic → smRoman (modified)
+ 16: 0, // langMaltese → smRoman
+ 17: 0, // langTurkish → smRoman (modified)
+ 18: 0, // langCroatian → smRoman (modified)
+ 19: 2, // langTradChinese → smTradChinese
+ 20: 4, // langUrdu → smArabic
+ 21: 9, // langHindi → smDevanagari
+ 22: 21, // langThai → smThai
+ 23: 3, // langKorean → smKorean
+ 24: 29, // langLithuanian → smCentralEuroRoman
+ 25: 29, // langPolish → smCentralEuroRoman
+ 26: 29, // langHungarian → smCentralEuroRoman
+ 27: 29, // langEstonian → smCentralEuroRoman
+ 28: 29, // langLatvian → smCentralEuroRoman
+ 29: 0, // langSami → smRoman
+ 30: 0, // langFaroese → smRoman (modified)
+ 31: 4, // langFarsi → smArabic (modified)
+ 32: 7, // langRussian → smCyrillic
+ 33: 25, // langSimpChinese → smSimpChinese
+ 34: 0, // langFlemish → smRoman
+ 35: 0, // langIrishGaelic → smRoman (modified)
+ 36: 0, // langAlbanian → smRoman
+ 37: 0, // langRomanian → smRoman (modified)
+ 38: 29, // langCzech → smCentralEuroRoman
+ 39: 29, // langSlovak → smCentralEuroRoman
+ 40: 0, // langSlovenian → smRoman (modified)
+ 41: 5, // langYiddish → smHebrew
+ 42: 7, // langSerbian → smCyrillic
+ 43: 7, // langMacedonian → smCyrillic
+ 44: 7, // langBulgarian → smCyrillic
+ 45: 7, // langUkrainian → smCyrillic (modified)
+ 46: 7, // langByelorussian → smCyrillic
+ 47: 7, // langUzbek → smCyrillic
+ 48: 7, // langKazakh → smCyrillic
+ 49: 7, // langAzerbaijani → smCyrillic
+ 50: 4, // langAzerbaijanAr → smArabic
+ 51: 24, // langArmenian → smArmenian
+ 52: 23, // langGeorgian → smGeorgian
+ 53: 7, // langMoldavian → smCyrillic
+ 54: 7, // langKirghiz → smCyrillic
+ 55: 7, // langTajiki → smCyrillic
+ 56: 7, // langTurkmen → smCyrillic
+ 57: 27, // langMongolian → smMongolian
+ 58: 7, // langMongolianCyr → smCyrillic
+ 59: 4, // langPashto → smArabic
+ 60: 4, // langKurdish → smArabic
+ 61: 4, // langKashmiri → smArabic
+ 62: 4, // langSindhi → smArabic
+ 63: 26, // langTibetan → smTibetan
+ 64: 9, // langNepali → smDevanagari
+ 65: 9, // langSanskrit → smDevanagari
+ 66: 9, // langMarathi → smDevanagari
+ 67: 13, // langBengali → smBengali
+ 68: 13, // langAssamese → smBengali
+ 69: 11, // langGujarati → smGujarati
+ 70: 10, // langPunjabi → smGurmukhi
+ 71: 12, // langOriya → smOriya
+ 72: 17, // langMalayalam → smMalayalam
+ 73: 16, // langKannada → smKannada
+ 74: 14, // langTamil → smTamil
+ 75: 15, // langTelugu → smTelugu
+ 76: 18, // langSinhalese → smSinhalese
+ 77: 19, // langBurmese → smBurmese
+ 78: 20, // langKhmer → smKhmer
+ 79: 22, // langLao → smLao
+ 80: 30, // langVietnamese → smVietnamese
+ 81: 0, // langIndonesian → smRoman
+ 82: 0, // langTagalog → smRoman
+ 83: 0, // langMalayRoman → smRoman
+ 84: 4, // langMalayArabic → smArabic
+ 85: 28, // langAmharic → smEthiopic
+ 86: 28, // langTigrinya → smEthiopic
+ 87: 28, // langOromo → smEthiopic
+ 88: 0, // langSomali → smRoman
+ 89: 0, // langSwahili → smRoman
+ 90: 0, // langKinyarwanda → smRoman
+ 91: 0, // langRundi → smRoman
+ 92: 0, // langNyanja → smRoman
+ 93: 0, // langMalagasy → smRoman
+ 94: 0, // langEsperanto → smRoman
+ 128: 0, // langWelsh → smRoman (modified)
+ 129: 0, // langBasque → smRoman
+ 130: 0, // langCatalan → smRoman
+ 131: 0, // langLatin → smRoman
+ 132: 0, // langQuechua → smRoman
+ 133: 0, // langGuarani → smRoman
+ 134: 0, // langAymara → smRoman
+ 135: 7, // langTatar → smCyrillic
+ 136: 4, // langUighur → smArabic
+ 137: 26, // langDzongkha → smTibetan
+ 138: 0, // langJavaneseRom → smRoman
+ 139: 0, // langSundaneseRom → smRoman
+ 140: 0, // langGalician → smRoman
+ 141: 0, // langAfrikaans → smRoman
+ 142: 0, // langBreton → smRoman (modified)
+ 143: 28, // langInuktitut → smEthiopic (modified)
+ 144: 0, // langScottishGaelic → smRoman (modified)
+ 145: 0, // langManxGaelic → smRoman (modified)
+ 146: 0, // langIrishGaelicScript → smRoman (modified)
+ 147: 0, // langTongan → smRoman
+ 148: 6, // langGreekAncient → smRoman
+ 149: 0, // langGreenlandic → smRoman
+ 150: 0, // langAzerbaijanRoman → smRoman
+ 151: 0 // langNynorsk → smRoman
+};
+
+// While Microsoft indicates a region/country for all its language
+// IDs, we omit the region code if it's equal to the "most likely
+// region subtag" according to Unicode CLDR. For scripts, we omit
+// the subtag if it is equal to the Suppress-Script entry in the
+// IANA language subtag registry for IETF BCP 47.
+//
+// For example, Microsoft states that its language code 0x041A is
+// Croatian in Croatia. We transform this to the BCP 47 language code 'hr'
+// and not 'hr-HR' because Croatia is the default country for Croatian,
+// according to Unicode CLDR. As another example, Microsoft states
+// that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform
+// this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script
+// for the Croatian language, according to IANA.
+//
+// http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html
+// http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
+var windowsLanguages = {
+ 0x0436: 'af',
+ 0x041C: 'sq',
+ 0x0484: 'gsw',
+ 0x045E: 'am',
+ 0x1401: 'ar-DZ',
+ 0x3C01: 'ar-BH',
+ 0x0C01: 'ar',
+ 0x0801: 'ar-IQ',
+ 0x2C01: 'ar-JO',
+ 0x3401: 'ar-KW',
+ 0x3001: 'ar-LB',
+ 0x1001: 'ar-LY',
+ 0x1801: 'ary',
+ 0x2001: 'ar-OM',
+ 0x4001: 'ar-QA',
+ 0x0401: 'ar-SA',
+ 0x2801: 'ar-SY',
+ 0x1C01: 'aeb',
+ 0x3801: 'ar-AE',
+ 0x2401: 'ar-YE',
+ 0x042B: 'hy',
+ 0x044D: 'as',
+ 0x082C: 'az-Cyrl',
+ 0x042C: 'az',
+ 0x046D: 'ba',
+ 0x042D: 'eu',
+ 0x0423: 'be',
+ 0x0845: 'bn',
+ 0x0445: 'bn-IN',
+ 0x201A: 'bs-Cyrl',
+ 0x141A: 'bs',
+ 0x047E: 'br',
+ 0x0402: 'bg',
+ 0x0403: 'ca',
+ 0x0C04: 'zh-HK',
+ 0x1404: 'zh-MO',
+ 0x0804: 'zh',
+ 0x1004: 'zh-SG',
+ 0x0404: 'zh-TW',
+ 0x0483: 'co',
+ 0x041A: 'hr',
+ 0x101A: 'hr-BA',
+ 0x0405: 'cs',
+ 0x0406: 'da',
+ 0x048C: 'prs',
+ 0x0465: 'dv',
+ 0x0813: 'nl-BE',
+ 0x0413: 'nl',
+ 0x0C09: 'en-AU',
+ 0x2809: 'en-BZ',
+ 0x1009: 'en-CA',
+ 0x2409: 'en-029',
+ 0x4009: 'en-IN',
+ 0x1809: 'en-IE',
+ 0x2009: 'en-JM',
+ 0x4409: 'en-MY',
+ 0x1409: 'en-NZ',
+ 0x3409: 'en-PH',
+ 0x4809: 'en-SG',
+ 0x1C09: 'en-ZA',
+ 0x2C09: 'en-TT',
+ 0x0809: 'en-GB',
+ 0x0409: 'en',
+ 0x3009: 'en-ZW',
+ 0x0425: 'et',
+ 0x0438: 'fo',
+ 0x0464: 'fil',
+ 0x040B: 'fi',
+ 0x080C: 'fr-BE',
+ 0x0C0C: 'fr-CA',
+ 0x040C: 'fr',
+ 0x140C: 'fr-LU',
+ 0x180C: 'fr-MC',
+ 0x100C: 'fr-CH',
+ 0x0462: 'fy',
+ 0x0456: 'gl',
+ 0x0437: 'ka',
+ 0x0C07: 'de-AT',
+ 0x0407: 'de',
+ 0x1407: 'de-LI',
+ 0x1007: 'de-LU',
+ 0x0807: 'de-CH',
+ 0x0408: 'el',
+ 0x046F: 'kl',
+ 0x0447: 'gu',
+ 0x0468: 'ha',
+ 0x040D: 'he',
+ 0x0439: 'hi',
+ 0x040E: 'hu',
+ 0x040F: 'is',
+ 0x0470: 'ig',
+ 0x0421: 'id',
+ 0x045D: 'iu',
+ 0x085D: 'iu-Latn',
+ 0x083C: 'ga',
+ 0x0434: 'xh',
+ 0x0435: 'zu',
+ 0x0410: 'it',
+ 0x0810: 'it-CH',
+ 0x0411: 'ja',
+ 0x044B: 'kn',
+ 0x043F: 'kk',
+ 0x0453: 'km',
+ 0x0486: 'quc',
+ 0x0487: 'rw',
+ 0x0441: 'sw',
+ 0x0457: 'kok',
+ 0x0412: 'ko',
+ 0x0440: 'ky',
+ 0x0454: 'lo',
+ 0x0426: 'lv',
+ 0x0427: 'lt',
+ 0x082E: 'dsb',
+ 0x046E: 'lb',
+ 0x042F: 'mk',
+ 0x083E: 'ms-BN',
+ 0x043E: 'ms',
+ 0x044C: 'ml',
+ 0x043A: 'mt',
+ 0x0481: 'mi',
+ 0x047A: 'arn',
+ 0x044E: 'mr',
+ 0x047C: 'moh',
+ 0x0450: 'mn',
+ 0x0850: 'mn-CN',
+ 0x0461: 'ne',
+ 0x0414: 'nb',
+ 0x0814: 'nn',
+ 0x0482: 'oc',
+ 0x0448: 'or',
+ 0x0463: 'ps',
+ 0x0415: 'pl',
+ 0x0416: 'pt',
+ 0x0816: 'pt-PT',
+ 0x0446: 'pa',
+ 0x046B: 'qu-BO',
+ 0x086B: 'qu-EC',
+ 0x0C6B: 'qu',
+ 0x0418: 'ro',
+ 0x0417: 'rm',
+ 0x0419: 'ru',
+ 0x243B: 'smn',
+ 0x103B: 'smj-NO',
+ 0x143B: 'smj',
+ 0x0C3B: 'se-FI',
+ 0x043B: 'se',
+ 0x083B: 'se-SE',
+ 0x203B: 'sms',
+ 0x183B: 'sma-NO',
+ 0x1C3B: 'sms',
+ 0x044F: 'sa',
+ 0x1C1A: 'sr-Cyrl-BA',
+ 0x0C1A: 'sr',
+ 0x181A: 'sr-Latn-BA',
+ 0x081A: 'sr-Latn',
+ 0x046C: 'nso',
+ 0x0432: 'tn',
+ 0x045B: 'si',
+ 0x041B: 'sk',
+ 0x0424: 'sl',
+ 0x2C0A: 'es-AR',
+ 0x400A: 'es-BO',
+ 0x340A: 'es-CL',
+ 0x240A: 'es-CO',
+ 0x140A: 'es-CR',
+ 0x1C0A: 'es-DO',
+ 0x300A: 'es-EC',
+ 0x440A: 'es-SV',
+ 0x100A: 'es-GT',
+ 0x480A: 'es-HN',
+ 0x080A: 'es-MX',
+ 0x4C0A: 'es-NI',
+ 0x180A: 'es-PA',
+ 0x3C0A: 'es-PY',
+ 0x280A: 'es-PE',
+ 0x500A: 'es-PR',
+
+ // Microsoft has defined two different language codes for
+ // “Spanish with modern sorting” and “Spanish with traditional
+ // sorting”. This makes sense for collation APIs, and it would be
+ // possible to express this in BCP 47 language tags via Unicode
+ // extensions (eg., es-u-co-trad is Spanish with traditional
+ // sorting). However, for storing names in fonts, the distinction
+ // does not make sense, so we give “es” in both cases.
+ 0x0C0A: 'es',
+ 0x040A: 'es',
+
+ 0x540A: 'es-US',
+ 0x380A: 'es-UY',
+ 0x200A: 'es-VE',
+ 0x081D: 'sv-FI',
+ 0x041D: 'sv',
+ 0x045A: 'syr',
+ 0x0428: 'tg',
+ 0x085F: 'tzm',
+ 0x0449: 'ta',
+ 0x0444: 'tt',
+ 0x044A: 'te',
+ 0x041E: 'th',
+ 0x0451: 'bo',
+ 0x041F: 'tr',
+ 0x0442: 'tk',
+ 0x0480: 'ug',
+ 0x0422: 'uk',
+ 0x042E: 'hsb',
+ 0x0420: 'ur',
+ 0x0843: 'uz-Cyrl',
+ 0x0443: 'uz',
+ 0x042A: 'vi',
+ 0x0452: 'cy',
+ 0x0488: 'wo',
+ 0x0485: 'sah',
+ 0x0478: 'ii',
+ 0x046A: 'yo'
+};
+
+// Returns a IETF BCP 47 language code, for example 'zh-Hant'
+// for 'Chinese in the traditional script'.
+function getLanguageCode(platformID, languageID, ltag) {
+ switch (platformID) {
+ case 0: // Unicode
+ if (languageID === 0xFFFF) {
+ return 'und';
+ } else if (ltag) {
+ return ltag[languageID];
+ }
+
+ break;
+
+ case 1: // Macintosh
+ return macLanguages[languageID];
+
+ case 3: // Windows
+ return windowsLanguages[languageID];
+ }
+
+ return undefined;
+}
+
+var utf16 = 'utf-16';
+
+// MacOS script ID → encoding. This table stores the default case,
+// which can be overridden by macLanguageEncodings.
+var macScriptEncodings = {
+ 0: 'macintosh', // smRoman
+ 1: 'x-mac-japanese', // smJapanese
+ 2: 'x-mac-chinesetrad', // smTradChinese
+ 3: 'x-mac-korean', // smKorean
+ 6: 'x-mac-greek', // smGreek
+ 7: 'x-mac-cyrillic', // smCyrillic
+ 9: 'x-mac-devanagai', // smDevanagari
+ 10: 'x-mac-gurmukhi', // smGurmukhi
+ 11: 'x-mac-gujarati', // smGujarati
+ 12: 'x-mac-oriya', // smOriya
+ 13: 'x-mac-bengali', // smBengali
+ 14: 'x-mac-tamil', // smTamil
+ 15: 'x-mac-telugu', // smTelugu
+ 16: 'x-mac-kannada', // smKannada
+ 17: 'x-mac-malayalam', // smMalayalam
+ 18: 'x-mac-sinhalese', // smSinhalese
+ 19: 'x-mac-burmese', // smBurmese
+ 20: 'x-mac-khmer', // smKhmer
+ 21: 'x-mac-thai', // smThai
+ 22: 'x-mac-lao', // smLao
+ 23: 'x-mac-georgian', // smGeorgian
+ 24: 'x-mac-armenian', // smArmenian
+ 25: 'x-mac-chinesesimp', // smSimpChinese
+ 26: 'x-mac-tibetan', // smTibetan
+ 27: 'x-mac-mongolian', // smMongolian
+ 28: 'x-mac-ethiopic', // smEthiopic
+ 29: 'x-mac-ce', // smCentralEuroRoman
+ 30: 'x-mac-vietnamese', // smVietnamese
+ 31: 'x-mac-extarabic' // smExtArabic
+};
+
+// MacOS language ID → encoding. This table stores the exceptional
+// cases, which override macScriptEncodings. For writing MacOS naming
+// tables, we need to emit a MacOS script ID. Therefore, we cannot
+// merge macScriptEncodings into macLanguageEncodings.
+//
+// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt
+var macLanguageEncodings = {
+ 15: 'x-mac-icelandic', // langIcelandic
+ 17: 'x-mac-turkish', // langTurkish
+ 18: 'x-mac-croatian', // langCroatian
+ 24: 'x-mac-ce', // langLithuanian
+ 25: 'x-mac-ce', // langPolish
+ 26: 'x-mac-ce', // langHungarian
+ 27: 'x-mac-ce', // langEstonian
+ 28: 'x-mac-ce', // langLatvian
+ 30: 'x-mac-icelandic', // langFaroese
+ 37: 'x-mac-romanian', // langRomanian
+ 38: 'x-mac-ce', // langCzech
+ 39: 'x-mac-ce', // langSlovak
+ 40: 'x-mac-ce', // langSlovenian
+ 143: 'x-mac-inuit', // langInuktitut
+ 146: 'x-mac-gaelic' // langIrishGaelicScript
+};
+
+function getEncoding(platformID, encodingID, languageID) {
+ switch (platformID) {
+ case 0: // Unicode
+ return utf16;
+
+ case 1: // Apple Macintosh
+ return macLanguageEncodings[languageID] || macScriptEncodings[encodingID];
+
+ case 3: // Microsoft Windows
+ if (encodingID === 1 || encodingID === 10) {
+ return utf16;
+ }
+
+ break;
+ }
+
+ return undefined;
+}
+
+// Parse the naming `name` table.
+// FIXME: Format 1 additional fields are not supported yet.
+// ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904'].
+function parseNameTable(data, start, ltag) {
+ var name = {};
+ var p = new parse.Parser(data, start);
+ var format = p.parseUShort();
+ var count = p.parseUShort();
+ var stringOffset = p.offset + p.parseUShort();
+ for (var i = 0; i < count; i++) {
+ var platformID = p.parseUShort();
+ var encodingID = p.parseUShort();
+ var languageID = p.parseUShort();
+ var nameID = p.parseUShort();
+ var property = nameTableNames[nameID] || nameID;
+ var byteLength = p.parseUShort();
+ var offset = p.parseUShort();
+ var language = getLanguageCode(platformID, languageID, ltag);
+ var encoding = getEncoding(platformID, encodingID, languageID);
+ if (encoding !== undefined && language !== undefined) {
+ var text = (void 0);
+ if (encoding === utf16) {
+ text = decode.UTF16(data, stringOffset + offset, byteLength);
+ } else {
+ text = decode.MACSTRING(data, stringOffset + offset, byteLength, encoding);
+ }
+
+ if (text) {
+ var translations = name[property];
+ if (translations === undefined) {
+ translations = name[property] = {};
+ }
+
+ translations[language] = text;
+ }
+ }
+ }
+
+ var langTagCount = 0;
+ if (format === 1) {
+ // FIXME: Also handle Microsoft's 'name' table 1.
+ langTagCount = p.parseUShort();
+ }
+
+ return name;
+}
+
+// {23: 'foo'} → {'foo': 23}
+// ['bar', 'baz'] → {'bar': 0, 'baz': 1}
+function reverseDict(dict) {
+ var result = {};
+ for (var key in dict) {
+ result[dict[key]] = parseInt(key);
+ }
+
+ return result;
+}
+
+function makeNameRecord(platformID, encodingID, languageID, nameID, length, offset) {
+ return new table.Record('NameRecord', [
+ {name: 'platformID', type: 'USHORT', value: platformID},
+ {name: 'encodingID', type: 'USHORT', value: encodingID},
+ {name: 'languageID', type: 'USHORT', value: languageID},
+ {name: 'nameID', type: 'USHORT', value: nameID},
+ {name: 'length', type: 'USHORT', value: length},
+ {name: 'offset', type: 'USHORT', value: offset}
+ ]);
+}
+
+// Finds the position of needle in haystack, or -1 if not there.
+// Like String.indexOf(), but for arrays.
+function findSubArray(needle, haystack) {
+ var needleLength = needle.length;
+ var limit = haystack.length - needleLength + 1;
+
+ loop:
+ for (var pos = 0; pos < limit; pos++) {
+ for (; pos < limit; pos++) {
+ for (var k = 0; k < needleLength; k++) {
+ if (haystack[pos + k] !== needle[k]) {
+ continue loop;
+ }
+ }
+
+ return pos;
+ }
+ }
+
+ return -1;
+}
+
+function addStringToPool(s, pool) {
+ var offset = findSubArray(s, pool);
+ if (offset < 0) {
+ offset = pool.length;
+ var i = 0;
+ var len = s.length;
+ for (; i < len; ++i) {
+ pool.push(s[i]);
+ }
+
+ }
+
+ return offset;
+}
+
+function makeNameTable(names, ltag) {
+ var nameID;
+ var nameIDs = [];
+
+ var namesWithNumericKeys = {};
+ var nameTableIds = reverseDict(nameTableNames);
+ for (var key in names) {
+ var id = nameTableIds[key];
+ if (id === undefined) {
+ id = key;
+ }
+
+ nameID = parseInt(id);
+
+ if (isNaN(nameID)) {
+ throw new Error('Name table entry "' + key + '" does not exist, see nameTableNames for complete list.');
+ }
+
+ namesWithNumericKeys[nameID] = names[key];
+ nameIDs.push(nameID);
+ }
+
+ var macLanguageIds = reverseDict(macLanguages);
+ var windowsLanguageIds = reverseDict(windowsLanguages);
+
+ var nameRecords = [];
+ var stringPool = [];
+
+ for (var i = 0; i < nameIDs.length; i++) {
+ nameID = nameIDs[i];
+ var translations = namesWithNumericKeys[nameID];
+ for (var lang in translations) {
+ var text = translations[lang];
+
+ // For MacOS, we try to emit the name in the form that was introduced
+ // in the initial version of the TrueType spec (in the late 1980s).
+ // However, this can fail for various reasons: the requested BCP 47
+ // language code might not have an old-style Mac equivalent;
+ // we might not have a codec for the needed character encoding;
+ // or the name might contain characters that cannot be expressed
+ // in the old-style Macintosh encoding. In case of failure, we emit
+ // the name in a more modern fashion (Unicode encoding with BCP 47
+ // language tags) that is recognized by MacOS 10.5, released in 2009.
+ // If fonts were only read by operating systems, we could simply
+ // emit all names in the modern form; this would be much easier.
+ // However, there are many applications and libraries that read
+ // 'name' tables directly, and these will usually only recognize
+ // the ancient form (silently skipping the unrecognized names).
+ var macPlatform = 1; // Macintosh
+ var macLanguage = macLanguageIds[lang];
+ var macScript = macLanguageToScript[macLanguage];
+ var macEncoding = getEncoding(macPlatform, macScript, macLanguage);
+ var macName = encode.MACSTRING(text, macEncoding);
+ if (macName === undefined) {
+ macPlatform = 0; // Unicode
+ macLanguage = ltag.indexOf(lang);
+ if (macLanguage < 0) {
+ macLanguage = ltag.length;
+ ltag.push(lang);
+ }
+
+ macScript = 4; // Unicode 2.0 and later
+ macName = encode.UTF16(text);
+ }
+
+ var macNameOffset = addStringToPool(macName, stringPool);
+ nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage,
+ nameID, macName.length, macNameOffset));
+
+ var winLanguage = windowsLanguageIds[lang];
+ if (winLanguage !== undefined) {
+ var winName = encode.UTF16(text);
+ var winNameOffset = addStringToPool(winName, stringPool);
+ nameRecords.push(makeNameRecord(3, 1, winLanguage,
+ nameID, winName.length, winNameOffset));
+ }
+ }
+ }
+
+ nameRecords.sort(function(a, b) {
+ return ((a.platformID - b.platformID) ||
+ (a.encodingID - b.encodingID) ||
+ (a.languageID - b.languageID) ||
+ (a.nameID - b.nameID));
+ });
+
+ var t = new table.Table('name', [
+ {name: 'format', type: 'USHORT', value: 0},
+ {name: 'count', type: 'USHORT', value: nameRecords.length},
+ {name: 'stringOffset', type: 'USHORT', value: 6 + nameRecords.length * 12}
+ ]);
+
+ for (var r = 0; r < nameRecords.length; r++) {
+ t.fields.push({name: 'record_' + r, type: 'RECORD', value: nameRecords[r]});
+ }
+
+ t.fields.push({name: 'strings', type: 'LITERAL', value: stringPool});
+ return t;
+}
+
+var _name = { parse: parseNameTable, make: makeNameTable };
+
+// The `OS/2` table contains metrics required in OpenType fonts.
+// https://www.microsoft.com/typography/OTSPEC/os2.htm
+
+var unicodeRanges = [
+ {begin: 0x0000, end: 0x007F}, // Basic Latin
+ {begin: 0x0080, end: 0x00FF}, // Latin-1 Supplement
+ {begin: 0x0100, end: 0x017F}, // Latin Extended-A
+ {begin: 0x0180, end: 0x024F}, // Latin Extended-B
+ {begin: 0x0250, end: 0x02AF}, // IPA Extensions
+ {begin: 0x02B0, end: 0x02FF}, // Spacing Modifier Letters
+ {begin: 0x0300, end: 0x036F}, // Combining Diacritical Marks
+ {begin: 0x0370, end: 0x03FF}, // Greek and Coptic
+ {begin: 0x2C80, end: 0x2CFF}, // Coptic
+ {begin: 0x0400, end: 0x04FF}, // Cyrillic
+ {begin: 0x0530, end: 0x058F}, // Armenian
+ {begin: 0x0590, end: 0x05FF}, // Hebrew
+ {begin: 0xA500, end: 0xA63F}, // Vai
+ {begin: 0x0600, end: 0x06FF}, // Arabic
+ {begin: 0x07C0, end: 0x07FF}, // NKo
+ {begin: 0x0900, end: 0x097F}, // Devanagari
+ {begin: 0x0980, end: 0x09FF}, // Bengali
+ {begin: 0x0A00, end: 0x0A7F}, // Gurmukhi
+ {begin: 0x0A80, end: 0x0AFF}, // Gujarati
+ {begin: 0x0B00, end: 0x0B7F}, // Oriya
+ {begin: 0x0B80, end: 0x0BFF}, // Tamil
+ {begin: 0x0C00, end: 0x0C7F}, // Telugu
+ {begin: 0x0C80, end: 0x0CFF}, // Kannada
+ {begin: 0x0D00, end: 0x0D7F}, // Malayalam
+ {begin: 0x0E00, end: 0x0E7F}, // Thai
+ {begin: 0x0E80, end: 0x0EFF}, // Lao
+ {begin: 0x10A0, end: 0x10FF}, // Georgian
+ {begin: 0x1B00, end: 0x1B7F}, // Balinese
+ {begin: 0x1100, end: 0x11FF}, // Hangul Jamo
+ {begin: 0x1E00, end: 0x1EFF}, // Latin Extended Additional
+ {begin: 0x1F00, end: 0x1FFF}, // Greek Extended
+ {begin: 0x2000, end: 0x206F}, // General Punctuation
+ {begin: 0x2070, end: 0x209F}, // Superscripts And Subscripts
+ {begin: 0x20A0, end: 0x20CF}, // Currency Symbol
+ {begin: 0x20D0, end: 0x20FF}, // Combining Diacritical Marks For Symbols
+ {begin: 0x2100, end: 0x214F}, // Letterlike Symbols
+ {begin: 0x2150, end: 0x218F}, // Number Forms
+ {begin: 0x2190, end: 0x21FF}, // Arrows
+ {begin: 0x2200, end: 0x22FF}, // Mathematical Operators
+ {begin: 0x2300, end: 0x23FF}, // Miscellaneous Technical
+ {begin: 0x2400, end: 0x243F}, // Control Pictures
+ {begin: 0x2440, end: 0x245F}, // Optical Character Recognition
+ {begin: 0x2460, end: 0x24FF}, // Enclosed Alphanumerics
+ {begin: 0x2500, end: 0x257F}, // Box Drawing
+ {begin: 0x2580, end: 0x259F}, // Block Elements
+ {begin: 0x25A0, end: 0x25FF}, // Geometric Shapes
+ {begin: 0x2600, end: 0x26FF}, // Miscellaneous Symbols
+ {begin: 0x2700, end: 0x27BF}, // Dingbats
+ {begin: 0x3000, end: 0x303F}, // CJK Symbols And Punctuation
+ {begin: 0x3040, end: 0x309F}, // Hiragana
+ {begin: 0x30A0, end: 0x30FF}, // Katakana
+ {begin: 0x3100, end: 0x312F}, // Bopomofo
+ {begin: 0x3130, end: 0x318F}, // Hangul Compatibility Jamo
+ {begin: 0xA840, end: 0xA87F}, // Phags-pa
+ {begin: 0x3200, end: 0x32FF}, // Enclosed CJK Letters And Months
+ {begin: 0x3300, end: 0x33FF}, // CJK Compatibility
+ {begin: 0xAC00, end: 0xD7AF}, // Hangul Syllables
+ {begin: 0xD800, end: 0xDFFF}, // Non-Plane 0 *
+ {begin: 0x10900, end: 0x1091F}, // Phoenicia
+ {begin: 0x4E00, end: 0x9FFF}, // CJK Unified Ideographs
+ {begin: 0xE000, end: 0xF8FF}, // Private Use Area (plane 0)
+ {begin: 0x31C0, end: 0x31EF}, // CJK Strokes
+ {begin: 0xFB00, end: 0xFB4F}, // Alphabetic Presentation Forms
+ {begin: 0xFB50, end: 0xFDFF}, // Arabic Presentation Forms-A
+ {begin: 0xFE20, end: 0xFE2F}, // Combining Half Marks
+ {begin: 0xFE10, end: 0xFE1F}, // Vertical Forms
+ {begin: 0xFE50, end: 0xFE6F}, // Small Form Variants
+ {begin: 0xFE70, end: 0xFEFF}, // Arabic Presentation Forms-B
+ {begin: 0xFF00, end: 0xFFEF}, // Halfwidth And Fullwidth Forms
+ {begin: 0xFFF0, end: 0xFFFF}, // Specials
+ {begin: 0x0F00, end: 0x0FFF}, // Tibetan
+ {begin: 0x0700, end: 0x074F}, // Syriac
+ {begin: 0x0780, end: 0x07BF}, // Thaana
+ {begin: 0x0D80, end: 0x0DFF}, // Sinhala
+ {begin: 0x1000, end: 0x109F}, // Myanmar
+ {begin: 0x1200, end: 0x137F}, // Ethiopic
+ {begin: 0x13A0, end: 0x13FF}, // Cherokee
+ {begin: 0x1400, end: 0x167F}, // Unified Canadian Aboriginal Syllabics
+ {begin: 0x1680, end: 0x169F}, // Ogham
+ {begin: 0x16A0, end: 0x16FF}, // Runic
+ {begin: 0x1780, end: 0x17FF}, // Khmer
+ {begin: 0x1800, end: 0x18AF}, // Mongolian
+ {begin: 0x2800, end: 0x28FF}, // Braille Patterns
+ {begin: 0xA000, end: 0xA48F}, // Yi Syllables
+ {begin: 0x1700, end: 0x171F}, // Tagalog
+ {begin: 0x10300, end: 0x1032F}, // Old Italic
+ {begin: 0x10330, end: 0x1034F}, // Gothic
+ {begin: 0x10400, end: 0x1044F}, // Deseret
+ {begin: 0x1D000, end: 0x1D0FF}, // Byzantine Musical Symbols
+ {begin: 0x1D400, end: 0x1D7FF}, // Mathematical Alphanumeric Symbols
+ {begin: 0xFF000, end: 0xFFFFD}, // Private Use (plane 15)
+ {begin: 0xFE00, end: 0xFE0F}, // Variation Selectors
+ {begin: 0xE0000, end: 0xE007F}, // Tags
+ {begin: 0x1900, end: 0x194F}, // Limbu
+ {begin: 0x1950, end: 0x197F}, // Tai Le
+ {begin: 0x1980, end: 0x19DF}, // New Tai Lue
+ {begin: 0x1A00, end: 0x1A1F}, // Buginese
+ {begin: 0x2C00, end: 0x2C5F}, // Glagolitic
+ {begin: 0x2D30, end: 0x2D7F}, // Tifinagh
+ {begin: 0x4DC0, end: 0x4DFF}, // Yijing Hexagram Symbols
+ {begin: 0xA800, end: 0xA82F}, // Syloti Nagri
+ {begin: 0x10000, end: 0x1007F}, // Linear B Syllabary
+ {begin: 0x10140, end: 0x1018F}, // Ancient Greek Numbers
+ {begin: 0x10380, end: 0x1039F}, // Ugaritic
+ {begin: 0x103A0, end: 0x103DF}, // Old Persian
+ {begin: 0x10450, end: 0x1047F}, // Shavian
+ {begin: 0x10480, end: 0x104AF}, // Osmanya
+ {begin: 0x10800, end: 0x1083F}, // Cypriot Syllabary
+ {begin: 0x10A00, end: 0x10A5F}, // Kharoshthi
+ {begin: 0x1D300, end: 0x1D35F}, // Tai Xuan Jing Symbols
+ {begin: 0x12000, end: 0x123FF}, // Cuneiform
+ {begin: 0x1D360, end: 0x1D37F}, // Counting Rod Numerals
+ {begin: 0x1B80, end: 0x1BBF}, // Sundanese
+ {begin: 0x1C00, end: 0x1C4F}, // Lepcha
+ {begin: 0x1C50, end: 0x1C7F}, // Ol Chiki
+ {begin: 0xA880, end: 0xA8DF}, // Saurashtra
+ {begin: 0xA900, end: 0xA92F}, // Kayah Li
+ {begin: 0xA930, end: 0xA95F}, // Rejang
+ {begin: 0xAA00, end: 0xAA5F}, // Cham
+ {begin: 0x10190, end: 0x101CF}, // Ancient Symbols
+ {begin: 0x101D0, end: 0x101FF}, // Phaistos Disc
+ {begin: 0x102A0, end: 0x102DF}, // Carian
+ {begin: 0x1F030, end: 0x1F09F} // Domino Tiles
+];
+
+function getUnicodeRange(unicode) {
+ for (var i = 0; i < unicodeRanges.length; i += 1) {
+ var range = unicodeRanges[i];
+ if (unicode >= range.begin && unicode < range.end) {
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+// Parse the OS/2 and Windows metrics `OS/2` table
+function parseOS2Table(data, start) {
+ var os2 = {};
+ var p = new parse.Parser(data, start);
+ os2.version = p.parseUShort();
+ os2.xAvgCharWidth = p.parseShort();
+ os2.usWeightClass = p.parseUShort();
+ os2.usWidthClass = p.parseUShort();
+ os2.fsType = p.parseUShort();
+ os2.ySubscriptXSize = p.parseShort();
+ os2.ySubscriptYSize = p.parseShort();
+ os2.ySubscriptXOffset = p.parseShort();
+ os2.ySubscriptYOffset = p.parseShort();
+ os2.ySuperscriptXSize = p.parseShort();
+ os2.ySuperscriptYSize = p.parseShort();
+ os2.ySuperscriptXOffset = p.parseShort();
+ os2.ySuperscriptYOffset = p.parseShort();
+ os2.yStrikeoutSize = p.parseShort();
+ os2.yStrikeoutPosition = p.parseShort();
+ os2.sFamilyClass = p.parseShort();
+ os2.panose = [];
+ for (var i = 0; i < 10; i++) {
+ os2.panose[i] = p.parseByte();
+ }
+
+ os2.ulUnicodeRange1 = p.parseULong();
+ os2.ulUnicodeRange2 = p.parseULong();
+ os2.ulUnicodeRange3 = p.parseULong();
+ os2.ulUnicodeRange4 = p.parseULong();
+ os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte());
+ os2.fsSelection = p.parseUShort();
+ os2.usFirstCharIndex = p.parseUShort();
+ os2.usLastCharIndex = p.parseUShort();
+ os2.sTypoAscender = p.parseShort();
+ os2.sTypoDescender = p.parseShort();
+ os2.sTypoLineGap = p.parseShort();
+ os2.usWinAscent = p.parseUShort();
+ os2.usWinDescent = p.parseUShort();
+ if (os2.version >= 1) {
+ os2.ulCodePageRange1 = p.parseULong();
+ os2.ulCodePageRange2 = p.parseULong();
+ }
+
+ if (os2.version >= 2) {
+ os2.sxHeight = p.parseShort();
+ os2.sCapHeight = p.parseShort();
+ os2.usDefaultChar = p.parseUShort();
+ os2.usBreakChar = p.parseUShort();
+ os2.usMaxContent = p.parseUShort();
+ }
+
+ return os2;
+}
+
+function makeOS2Table(options) {
+ return new table.Table('OS/2', [
+ {name: 'version', type: 'USHORT', value: 0x0003},
+ {name: 'xAvgCharWidth', type: 'SHORT', value: 0},
+ {name: 'usWeightClass', type: 'USHORT', value: 0},
+ {name: 'usWidthClass', type: 'USHORT', value: 0},
+ {name: 'fsType', type: 'USHORT', value: 0},
+ {name: 'ySubscriptXSize', type: 'SHORT', value: 650},
+ {name: 'ySubscriptYSize', type: 'SHORT', value: 699},
+ {name: 'ySubscriptXOffset', type: 'SHORT', value: 0},
+ {name: 'ySubscriptYOffset', type: 'SHORT', value: 140},
+ {name: 'ySuperscriptXSize', type: 'SHORT', value: 650},
+ {name: 'ySuperscriptYSize', type: 'SHORT', value: 699},
+ {name: 'ySuperscriptXOffset', type: 'SHORT', value: 0},
+ {name: 'ySuperscriptYOffset', type: 'SHORT', value: 479},
+ {name: 'yStrikeoutSize', type: 'SHORT', value: 49},
+ {name: 'yStrikeoutPosition', type: 'SHORT', value: 258},
+ {name: 'sFamilyClass', type: 'SHORT', value: 0},
+ {name: 'bFamilyType', type: 'BYTE', value: 0},
+ {name: 'bSerifStyle', type: 'BYTE', value: 0},
+ {name: 'bWeight', type: 'BYTE', value: 0},
+ {name: 'bProportion', type: 'BYTE', value: 0},
+ {name: 'bContrast', type: 'BYTE', value: 0},
+ {name: 'bStrokeVariation', type: 'BYTE', value: 0},
+ {name: 'bArmStyle', type: 'BYTE', value: 0},
+ {name: 'bLetterform', type: 'BYTE', value: 0},
+ {name: 'bMidline', type: 'BYTE', value: 0},
+ {name: 'bXHeight', type: 'BYTE', value: 0},
+ {name: 'ulUnicodeRange1', type: 'ULONG', value: 0},
+ {name: 'ulUnicodeRange2', type: 'ULONG', value: 0},
+ {name: 'ulUnicodeRange3', type: 'ULONG', value: 0},
+ {name: 'ulUnicodeRange4', type: 'ULONG', value: 0},
+ {name: 'achVendID', type: 'CHARARRAY', value: 'XXXX'},
+ {name: 'fsSelection', type: 'USHORT', value: 0},
+ {name: 'usFirstCharIndex', type: 'USHORT', value: 0},
+ {name: 'usLastCharIndex', type: 'USHORT', value: 0},
+ {name: 'sTypoAscender', type: 'SHORT', value: 0},
+ {name: 'sTypoDescender', type: 'SHORT', value: 0},
+ {name: 'sTypoLineGap', type: 'SHORT', value: 0},
+ {name: 'usWinAscent', type: 'USHORT', value: 0},
+ {name: 'usWinDescent', type: 'USHORT', value: 0},
+ {name: 'ulCodePageRange1', type: 'ULONG', value: 0},
+ {name: 'ulCodePageRange2', type: 'ULONG', value: 0},
+ {name: 'sxHeight', type: 'SHORT', value: 0},
+ {name: 'sCapHeight', type: 'SHORT', value: 0},
+ {name: 'usDefaultChar', type: 'USHORT', value: 0},
+ {name: 'usBreakChar', type: 'USHORT', value: 0},
+ {name: 'usMaxContext', type: 'USHORT', value: 0}
+ ], options);
+}
+
+var os2 = { parse: parseOS2Table, make: makeOS2Table, unicodeRanges: unicodeRanges, getUnicodeRange: getUnicodeRange };
+
+// The `post` table stores additional PostScript information, such as glyph names.
+// https://www.microsoft.com/typography/OTSPEC/post.htm
+
+// Parse the PostScript `post` table
+function parsePostTable(data, start) {
+ var post = {};
+ var p = new parse.Parser(data, start);
+ post.version = p.parseVersion();
+ post.italicAngle = p.parseFixed();
+ post.underlinePosition = p.parseShort();
+ post.underlineThickness = p.parseShort();
+ post.isFixedPitch = p.parseULong();
+ post.minMemType42 = p.parseULong();
+ post.maxMemType42 = p.parseULong();
+ post.minMemType1 = p.parseULong();
+ post.maxMemType1 = p.parseULong();
+ switch (post.version) {
+ case 1:
+ post.names = standardNames.slice();
+ break;
+ case 2:
+ post.numberOfGlyphs = p.parseUShort();
+ post.glyphNameIndex = new Array(post.numberOfGlyphs);
+ for (var i = 0; i < post.numberOfGlyphs; i++) {
+ post.glyphNameIndex[i] = p.parseUShort();
+ }
+
+ post.names = [];
+ for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) {
+ if (post.glyphNameIndex[i$1] >= standardNames.length) {
+ var nameLength = p.parseChar();
+ post.names.push(p.parseString(nameLength));
+ }
+ }
+
+ break;
+ case 2.5:
+ post.numberOfGlyphs = p.parseUShort();
+ post.offset = new Array(post.numberOfGlyphs);
+ for (var i$2 = 0; i$2 < post.numberOfGlyphs; i$2++) {
+ post.offset[i$2] = p.parseChar();
+ }
+
+ break;
+ }
+ return post;
+}
+
+function makePostTable() {
+ return new table.Table('post', [
+ {name: 'version', type: 'FIXED', value: 0x00030000},
+ {name: 'italicAngle', type: 'FIXED', value: 0},
+ {name: 'underlinePosition', type: 'FWORD', value: 0},
+ {name: 'underlineThickness', type: 'FWORD', value: 0},
+ {name: 'isFixedPitch', type: 'ULONG', value: 0},
+ {name: 'minMemType42', type: 'ULONG', value: 0},
+ {name: 'maxMemType42', type: 'ULONG', value: 0},
+ {name: 'minMemType1', type: 'ULONG', value: 0},
+ {name: 'maxMemType1', type: 'ULONG', value: 0}
+ ]);
+}
+
+var post = { parse: parsePostTable, make: makePostTable };
+
+// The `GSUB` table contains ligatures, among other things.
+// https://www.microsoft.com/typography/OTSPEC/gsub.htm
+
+var subtableParsers = new Array(9); // subtableParsers[0] is unused
+
+// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS
+subtableParsers[1] = function parseLookup1() {
+ var start = this.offset + this.relativeOffset;
+ var substFormat = this.parseUShort();
+ if (substFormat === 1) {
+ return {
+ substFormat: 1,
+ coverage: this.parsePointer(Parser.coverage),
+ deltaGlyphId: this.parseUShort()
+ };
+ } else if (substFormat === 2) {
+ return {
+ substFormat: 2,
+ coverage: this.parsePointer(Parser.coverage),
+ substitute: this.parseOffset16List()
+ };
+ }
+ check.assert(false, '0x' + start.toString(16) + ': lookup type 1 format must be 1 or 2.');
+};
+
+// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS
+subtableParsers[2] = function parseLookup2() {
+ var substFormat = this.parseUShort();
+ check.argument(substFormat === 1, 'GSUB Multiple Substitution Subtable identifier-format must be 1');
+ return {
+ substFormat: substFormat,
+ coverage: this.parsePointer(Parser.coverage),
+ sequences: this.parseListOfLists()
+ };
+};
+
+// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS
+subtableParsers[3] = function parseLookup3() {
+ var substFormat = this.parseUShort();
+ check.argument(substFormat === 1, 'GSUB Alternate Substitution Subtable identifier-format must be 1');
+ return {
+ substFormat: substFormat,
+ coverage: this.parsePointer(Parser.coverage),
+ alternateSets: this.parseListOfLists()
+ };
+};
+
+// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS
+subtableParsers[4] = function parseLookup4() {
+ var substFormat = this.parseUShort();
+ check.argument(substFormat === 1, 'GSUB ligature table identifier-format must be 1');
+ return {
+ substFormat: substFormat,
+ coverage: this.parsePointer(Parser.coverage),
+ ligatureSets: this.parseListOfLists(function() {
+ return {
+ ligGlyph: this.parseUShort(),
+ components: this.parseUShortList(this.parseUShort() - 1)
+ };
+ })
+ };
+};
+
+var lookupRecordDesc = {
+ sequenceIndex: Parser.uShort,
+ lookupListIndex: Parser.uShort
+};
+
+// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF
+subtableParsers[5] = function parseLookup5() {
+ var start = this.offset + this.relativeOffset;
+ var substFormat = this.parseUShort();
+
+ if (substFormat === 1) {
+ return {
+ substFormat: substFormat,
+ coverage: this.parsePointer(Parser.coverage),
+ ruleSets: this.parseListOfLists(function() {
+ var glyphCount = this.parseUShort();
+ var substCount = this.parseUShort();
+ return {
+ input: this.parseUShortList(glyphCount - 1),
+ lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
+ };
+ })
+ };
+ } else if (substFormat === 2) {
+ return {
+ substFormat: substFormat,
+ coverage: this.parsePointer(Parser.coverage),
+ classDef: this.parsePointer(Parser.classDef),
+ classSets: this.parseListOfLists(function() {
+ var glyphCount = this.parseUShort();
+ var substCount = this.parseUShort();
+ return {
+ classes: this.parseUShortList(glyphCount - 1),
+ lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
+ };
+ })
+ };
+ } else if (substFormat === 3) {
+ var glyphCount = this.parseUShort();
+ var substCount = this.parseUShort();
+ return {
+ substFormat: substFormat,
+ coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)),
+ lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
+ };
+ }
+ check.assert(false, '0x' + start.toString(16) + ': lookup type 5 format must be 1, 2 or 3.');
+};
+
+// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC
+subtableParsers[6] = function parseLookup6() {
+ var start = this.offset + this.relativeOffset;
+ var substFormat = this.parseUShort();
+ if (substFormat === 1) {
+ return {
+ substFormat: 1,
+ coverage: this.parsePointer(Parser.coverage),
+ chainRuleSets: this.parseListOfLists(function() {
+ return {
+ backtrack: this.parseUShortList(),
+ input: this.parseUShortList(this.parseShort() - 1),
+ lookahead: this.parseUShortList(),
+ lookupRecords: this.parseRecordList(lookupRecordDesc)
+ };
+ })
+ };
+ } else if (substFormat === 2) {
+ return {
+ substFormat: 2,
+ coverage: this.parsePointer(Parser.coverage),
+ backtrackClassDef: this.parsePointer(Parser.classDef),
+ inputClassDef: this.parsePointer(Parser.classDef),
+ lookaheadClassDef: this.parsePointer(Parser.classDef),
+ chainClassSet: this.parseListOfLists(function() {
+ return {
+ backtrack: this.parseUShortList(),
+ input: this.parseUShortList(this.parseShort() - 1),
+ lookahead: this.parseUShortList(),
+ lookupRecords: this.parseRecordList(lookupRecordDesc)
+ };
+ })
+ };
+ } else if (substFormat === 3) {
+ return {
+ substFormat: 3,
+ backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)),
+ inputCoverage: this.parseList(Parser.pointer(Parser.coverage)),
+ lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)),
+ lookupRecords: this.parseRecordList(lookupRecordDesc)
+ };
+ }
+ check.assert(false, '0x' + start.toString(16) + ': lookup type 6 format must be 1, 2 or 3.');
+};
+
+// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES
+subtableParsers[7] = function parseLookup7() {
+ // Extension Substitution subtable
+ var substFormat = this.parseUShort();
+ check.argument(substFormat === 1, 'GSUB Extension Substitution subtable identifier-format must be 1');
+ var extensionLookupType = this.parseUShort();
+ var extensionParser = new Parser(this.data, this.offset + this.parseULong());
+ return {
+ substFormat: 1,
+ lookupType: extensionLookupType,
+ extension: subtableParsers[extensionLookupType].call(extensionParser)
+ };
+};
+
+// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS
+subtableParsers[8] = function parseLookup8() {
+ var substFormat = this.parseUShort();
+ check.argument(substFormat === 1, 'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1');
+ return {
+ substFormat: substFormat,
+ coverage: this.parsePointer(Parser.coverage),
+ backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)),
+ lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)),
+ substitutes: this.parseUShortList()
+ };
+};
+
+// https://www.microsoft.com/typography/OTSPEC/gsub.htm
+function parseGsubTable(data, start) {
+ start = start || 0;
+ var p = new Parser(data, start);
+ var tableVersion = p.parseVersion();
+ check.argument(tableVersion === 1, 'Unsupported GSUB table version.');
+ return {
+ version: tableVersion,
+ scripts: p.parseScriptList(),
+ features: p.parseFeatureList(),
+ lookups: p.parseLookupList(subtableParsers)
+ };
+}
+
+// GSUB Writing //////////////////////////////////////////////
+var subtableMakers = new Array(9);
+
+subtableMakers[1] = function makeLookup1(subtable) {
+ if (subtable.substFormat === 1) {
+ return new table.Table('substitutionTable', [
+ {name: 'substFormat', type: 'USHORT', value: 1},
+ {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)},
+ {name: 'deltaGlyphID', type: 'USHORT', value: subtable.deltaGlyphId}
+ ]);
+ } else {
+ return new table.Table('substitutionTable', [
+ {name: 'substFormat', type: 'USHORT', value: 2},
+ {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}
+ ].concat(table.ushortList('substitute', subtable.substitute)));
+ }
+ check.fail('Lookup type 1 substFormat must be 1 or 2.');
+};
+
+subtableMakers[3] = function makeLookup3(subtable) {
+ check.assert(subtable.substFormat === 1, 'Lookup type 3 substFormat must be 1.');
+ return new table.Table('substitutionTable', [
+ {name: 'substFormat', type: 'USHORT', value: 1},
+ {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}
+ ].concat(table.tableList('altSet', subtable.alternateSets, function(alternateSet) {
+ return new table.Table('alternateSetTable', table.ushortList('alternate', alternateSet));
+ })));
+};
+
+subtableMakers[4] = function makeLookup4(subtable) {
+ check.assert(subtable.substFormat === 1, 'Lookup type 4 substFormat must be 1.');
+ return new table.Table('substitutionTable', [
+ {name: 'substFormat', type: 'USHORT', value: 1},
+ {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}
+ ].concat(table.tableList('ligSet', subtable.ligatureSets, function(ligatureSet) {
+ return new table.Table('ligatureSetTable', table.tableList('ligature', ligatureSet, function(ligature) {
+ return new table.Table('ligatureTable',
+ [{name: 'ligGlyph', type: 'USHORT', value: ligature.ligGlyph}]
+ .concat(table.ushortList('component', ligature.components, ligature.components.length + 1))
+ );
+ }));
+ })));
+};
+
+function makeGsubTable(gsub) {
+ return new table.Table('GSUB', [
+ {name: 'version', type: 'ULONG', value: 0x10000},
+ {name: 'scripts', type: 'TABLE', value: new table.ScriptList(gsub.scripts)},
+ {name: 'features', type: 'TABLE', value: new table.FeatureList(gsub.features)},
+ {name: 'lookups', type: 'TABLE', value: new table.LookupList(gsub.lookups, subtableMakers)}
+ ]);
+}
+
+var gsub = { parse: parseGsubTable, make: makeGsubTable };
+
+// The `GPOS` table contains kerning pairs, among other things.
+// https://www.microsoft.com/typography/OTSPEC/gpos.htm
+
+// Parse the metadata `meta` table.
+// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html
+function parseMetaTable(data, start) {
+ var p = new parse.Parser(data, start);
+ var tableVersion = p.parseULong();
+ check.argument(tableVersion === 1, 'Unsupported META table version.');
+ p.parseULong(); // flags - currently unused and set to 0
+ p.parseULong(); // tableOffset
+ var numDataMaps = p.parseULong();
+
+ var tags = {};
+ for (var i = 0; i < numDataMaps; i++) {
+ var tag = p.parseTag();
+ var dataOffset = p.parseULong();
+ var dataLength = p.parseULong();
+ var text = decode.UTF8(data, start + dataOffset, dataLength);
+
+ tags[tag] = text;
+ }
+ return tags;
+}
+
+function makeMetaTable(tags) {
+ var numTags = Object.keys(tags).length;
+ var stringPool = '';
+ var stringPoolOffset = 16 + numTags * 12;
+
+ var result = new table.Table('meta', [
+ {name: 'version', type: 'ULONG', value: 1},
+ {name: 'flags', type: 'ULONG', value: 0},
+ {name: 'offset', type: 'ULONG', value: stringPoolOffset},
+ {name: 'numTags', type: 'ULONG', value: numTags}
+ ]);
+
+ for (var tag in tags) {
+ var pos = stringPool.length;
+ stringPool += tags[tag];
+
+ result.fields.push({name: 'tag ' + tag, type: 'TAG', value: tag});
+ result.fields.push({name: 'offset ' + tag, type: 'ULONG', value: stringPoolOffset + pos});
+ result.fields.push({name: 'length ' + tag, type: 'ULONG', value: tags[tag].length});
+ }
+
+ result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool});
+
+ return result;
+}
+
+var meta = { parse: parseMetaTable, make: makeMetaTable };
+
+// The `sfnt` wrapper provides organization for the tables in the font.
+// It is the top-level data structure in a font.
+// https://www.microsoft.com/typography/OTSPEC/otff.htm
+// Recommendations for creating OpenType Fonts:
+// http://www.microsoft.com/typography/otspec140/recom.htm
+
+function log2(v) {
+ return Math.log(v) / Math.log(2) | 0;
+}
+
+function computeCheckSum(bytes) {
+ while (bytes.length % 4 !== 0) {
+ bytes.push(0);
+ }
+
+ var sum = 0;
+ for (var i = 0; i < bytes.length; i += 4) {
+ sum += (bytes[i] << 24) +
+ (bytes[i + 1] << 16) +
+ (bytes[i + 2] << 8) +
+ (bytes[i + 3]);
+ }
+
+ sum %= Math.pow(2, 32);
+ return sum;
+}
+
+function makeTableRecord(tag, checkSum, offset, length) {
+ return new table.Record('Table Record', [
+ {name: 'tag', type: 'TAG', value: tag !== undefined ? tag : ''},
+ {name: 'checkSum', type: 'ULONG', value: checkSum !== undefined ? checkSum : 0},
+ {name: 'offset', type: 'ULONG', value: offset !== undefined ? offset : 0},
+ {name: 'length', type: 'ULONG', value: length !== undefined ? length : 0}
+ ]);
+}
+
+function makeSfntTable(tables) {
+ var sfnt = new table.Table('sfnt', [
+ {name: 'version', type: 'TAG', value: 'OTTO'},
+ {name: 'numTables', type: 'USHORT', value: 0},
+ {name: 'searchRange', type: 'USHORT', value: 0},
+ {name: 'entrySelector', type: 'USHORT', value: 0},
+ {name: 'rangeShift', type: 'USHORT', value: 0}
+ ]);
+ sfnt.tables = tables;
+ sfnt.numTables = tables.length;
+ var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables));
+ sfnt.searchRange = 16 * highestPowerOf2;
+ sfnt.entrySelector = log2(highestPowerOf2);
+ sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange;
+
+ var recordFields = [];
+ var tableFields = [];
+
+ var offset = sfnt.sizeOf() + (makeTableRecord().sizeOf() * sfnt.numTables);
+ while (offset % 4 !== 0) {
+ offset += 1;
+ tableFields.push({name: 'padding', type: 'BYTE', value: 0});
+ }
+
+ for (var i = 0; i < tables.length; i += 1) {
+ var t = tables[i];
+ check.argument(t.tableName.length === 4, 'Table name' + t.tableName + ' is invalid.');
+ var tableLength = t.sizeOf();
+ var tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength);
+ recordFields.push({name: tableRecord.tag + ' Table Record', type: 'RECORD', value: tableRecord});
+ tableFields.push({name: t.tableName + ' table', type: 'RECORD', value: t});
+ offset += tableLength;
+ check.argument(!isNaN(offset), 'Something went wrong calculating the offset.');
+ while (offset % 4 !== 0) {
+ offset += 1;
+ tableFields.push({name: 'padding', type: 'BYTE', value: 0});
+ }
+ }
+
+ // Table records need to be sorted alphabetically.
+ recordFields.sort(function(r1, r2) {
+ if (r1.value.tag > r2.value.tag) {
+ return 1;
+ } else {
+ return -1;
+ }
+ });
+
+ sfnt.fields = sfnt.fields.concat(recordFields);
+ sfnt.fields = sfnt.fields.concat(tableFields);
+ return sfnt;
+}
+
+// Get the metrics for a character. If the string has more than one character
+// this function returns metrics for the first available character.
+// You can provide optional fallback metrics if no characters are available.
+function metricsForChar(font, chars, notFoundMetrics) {
+ for (var i = 0; i < chars.length; i += 1) {
+ var glyphIndex = font.charToGlyphIndex(chars[i]);
+ if (glyphIndex > 0) {
+ var glyph = font.glyphs.get(glyphIndex);
+ return glyph.getMetrics();
+ }
+ }
+
+ return notFoundMetrics;
+}
+
+function average(vs) {
+ var sum = 0;
+ for (var i = 0; i < vs.length; i += 1) {
+ sum += vs[i];
+ }
+
+ return sum / vs.length;
+}
+
+// Convert the font object to a SFNT data structure.
+// This structure contains all the necessary tables and metadata to create a binary OTF file.
+function fontToSfntTable(font) {
+ var xMins = [];
+ var yMins = [];
+ var xMaxs = [];
+ var yMaxs = [];
+ var advanceWidths = [];
+ var leftSideBearings = [];
+ var rightSideBearings = [];
+ var firstCharIndex;
+ var lastCharIndex = 0;
+ var ulUnicodeRange1 = 0;
+ var ulUnicodeRange2 = 0;
+ var ulUnicodeRange3 = 0;
+ var ulUnicodeRange4 = 0;
+
+ for (var i = 0; i < font.glyphs.length; i += 1) {
+ var glyph = font.glyphs.get(i);
+ var unicode = glyph.unicode | 0;
+
+ if (isNaN(glyph.advanceWidth)) {
+ throw new Error('Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.');
+ }
+
+ if (firstCharIndex > unicode || firstCharIndex === undefined) {
+ // ignore .notdef char
+ if (unicode > 0) {
+ firstCharIndex = unicode;
+ }
+ }
+
+ if (lastCharIndex < unicode) {
+ lastCharIndex = unicode;
+ }
+
+ var position = os2.getUnicodeRange(unicode);
+ if (position < 32) {
+ ulUnicodeRange1 |= 1 << position;
+ } else if (position < 64) {
+ ulUnicodeRange2 |= 1 << position - 32;
+ } else if (position < 96) {
+ ulUnicodeRange3 |= 1 << position - 64;
+ } else if (position < 123) {
+ ulUnicodeRange4 |= 1 << position - 96;
+ } else {
+ throw new Error('Unicode ranges bits > 123 are reserved for internal usage');
+ }
+ // Skip non-important characters.
+ if (glyph.name === '.notdef') { continue; }
+ var metrics = glyph.getMetrics();
+ xMins.push(metrics.xMin);
+ yMins.push(metrics.yMin);
+ xMaxs.push(metrics.xMax);
+ yMaxs.push(metrics.yMax);
+ leftSideBearings.push(metrics.leftSideBearing);
+ rightSideBearings.push(metrics.rightSideBearing);
+ advanceWidths.push(glyph.advanceWidth);
+ }
+
+ var globals = {
+ xMin: Math.min.apply(null, xMins),
+ yMin: Math.min.apply(null, yMins),
+ xMax: Math.max.apply(null, xMaxs),
+ yMax: Math.max.apply(null, yMaxs),
+ advanceWidthMax: Math.max.apply(null, advanceWidths),
+ advanceWidthAvg: average(advanceWidths),
+ minLeftSideBearing: Math.min.apply(null, leftSideBearings),
+ maxLeftSideBearing: Math.max.apply(null, leftSideBearings),
+ minRightSideBearing: Math.min.apply(null, rightSideBearings)
+ };
+ globals.ascender = font.ascender;
+ globals.descender = font.descender;
+
+ var headTable = head.make({
+ flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0)
+ unitsPerEm: font.unitsPerEm,
+ xMin: globals.xMin,
+ yMin: globals.yMin,
+ xMax: globals.xMax,
+ yMax: globals.yMax,
+ lowestRecPPEM: 3,
+ createdTimestamp: font.createdTimestamp
+ });
+
+ var hheaTable = hhea.make({
+ ascender: globals.ascender,
+ descender: globals.descender,
+ advanceWidthMax: globals.advanceWidthMax,
+ minLeftSideBearing: globals.minLeftSideBearing,
+ minRightSideBearing: globals.minRightSideBearing,
+ xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin),
+ numberOfHMetrics: font.glyphs.length
+ });
+
+ var maxpTable = maxp.make(font.glyphs.length);
+
+ var os2Table = os2.make({
+ xAvgCharWidth: Math.round(globals.advanceWidthAvg),
+ usWeightClass: font.tables.os2.usWeightClass,
+ usWidthClass: font.tables.os2.usWidthClass,
+ usFirstCharIndex: firstCharIndex,
+ usLastCharIndex: lastCharIndex,
+ ulUnicodeRange1: ulUnicodeRange1,
+ ulUnicodeRange2: ulUnicodeRange2,
+ ulUnicodeRange3: ulUnicodeRange3,
+ ulUnicodeRange4: ulUnicodeRange4,
+ fsSelection: font.tables.os2.fsSelection, // REGULAR
+ // See http://typophile.com/node/13081 for more info on vertical metrics.
+ // We get metrics for typical characters (such as "x" for xHeight).
+ // We provide some fallback characters if characters are unavailable: their
+ // ordering was chosen experimentally.
+ sTypoAscender: globals.ascender,
+ sTypoDescender: globals.descender,
+ sTypoLineGap: 0,
+ usWinAscent: globals.yMax,
+ usWinDescent: Math.abs(globals.yMin),
+ ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now
+ sxHeight: metricsForChar(font, 'xyvw', {yMax: Math.round(globals.ascender / 2)}).yMax,
+ sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals).yMax,
+ usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available.
+ usBreakChar: font.hasChar(' ') ? 32 : 0 // Use space as the break character, if available.
+ });
+
+ var hmtxTable = hmtx.make(font.glyphs);
+ var cmapTable = cmap.make(font.glyphs);
+
+ var englishFamilyName = font.getEnglishName('fontFamily');
+ var englishStyleName = font.getEnglishName('fontSubfamily');
+ var englishFullName = englishFamilyName + ' ' + englishStyleName;
+ var postScriptName = font.getEnglishName('postScriptName');
+ if (!postScriptName) {
+ postScriptName = englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName;
+ }
+
+ var names = {};
+ for (var n in font.names) {
+ names[n] = font.names[n];
+ }
+
+ if (!names.uniqueID) {
+ names.uniqueID = {en: font.getEnglishName('manufacturer') + ':' + englishFullName};
+ }
+
+ if (!names.postScriptName) {
+ names.postScriptName = {en: postScriptName};
+ }
+
+ if (!names.preferredFamily) {
+ names.preferredFamily = font.names.fontFamily;
+ }
+
+ if (!names.preferredSubfamily) {
+ names.preferredSubfamily = font.names.fontSubfamily;
+ }
+
+ var languageTags = [];
+ var nameTable = _name.make(names, languageTags);
+ var ltagTable = (languageTags.length > 0 ? ltag.make(languageTags) : undefined);
+
+ var postTable = post.make();
+ var cffTable = cff.make(font.glyphs, {
+ version: font.getEnglishName('version'),
+ fullName: englishFullName,
+ familyName: englishFamilyName,
+ weightName: englishStyleName,
+ postScriptName: postScriptName,
+ unitsPerEm: font.unitsPerEm,
+ fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax]
+ });
+
+ var metaTable = (font.metas && Object.keys(font.metas).length > 0) ? meta.make(font.metas) : undefined;
+
+ // The order does not matter because makeSfntTable() will sort them.
+ var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable];
+ if (ltagTable) {
+ tables.push(ltagTable);
+ }
+ // Optional tables
+ if (font.tables.gsub) {
+ tables.push(gsub.make(font.tables.gsub));
+ }
+ if (metaTable) {
+ tables.push(metaTable);
+ }
+
+ var sfntTable = makeSfntTable(tables);
+
+ // Compute the font's checkSum and store it in head.checkSumAdjustment.
+ var bytes = sfntTable.encode();
+ var checkSum = computeCheckSum(bytes);
+ var tableFields = sfntTable.fields;
+ var checkSumAdjusted = false;
+ for (var i$1 = 0; i$1 < tableFields.length; i$1 += 1) {
+ if (tableFields[i$1].name === 'head table') {
+ tableFields[i$1].value.checkSumAdjustment = 0xB1B0AFBA - checkSum;
+ checkSumAdjusted = true;
+ break;
+ }
+ }
+
+ if (!checkSumAdjusted) {
+ throw new Error('Could not find head table with checkSum to adjust.');
+ }
+
+ return sfntTable;
+}
+
+var sfnt = { make: makeSfntTable, fontToTable: fontToSfntTable, computeCheckSum: computeCheckSum };
+
+// The Layout object is the prototype of Substitution objects, and provides
+// utility methods to manipulate common layout tables (GPOS, GSUB, GDEF...)
+
+function searchTag(arr, tag) {
+ /* jshint bitwise: false */
+ var imin = 0;
+ var imax = arr.length - 1;
+ while (imin <= imax) {
+ var imid = (imin + imax) >>> 1;
+ var val = arr[imid].tag;
+ if (val === tag) {
+ return imid;
+ } else if (val < tag) {
+ imin = imid + 1;
+ } else { imax = imid - 1; }
+ }
+ // Not found: return -1-insertion point
+ return -imin - 1;
+}
+
+function binSearch(arr, value) {
+ /* jshint bitwise: false */
+ var imin = 0;
+ var imax = arr.length - 1;
+ while (imin <= imax) {
+ var imid = (imin + imax) >>> 1;
+ var val = arr[imid];
+ if (val === value) {
+ return imid;
+ } else if (val < value) {
+ imin = imid + 1;
+ } else { imax = imid - 1; }
+ }
+ // Not found: return -1-insertion point
+ return -imin - 1;
+}
+
+/**
+ * @exports opentype.Layout
+ * @class
+ */
+function Layout(font, tableName) {
+ this.font = font;
+ this.tableName = tableName;
+}
+
+Layout.prototype = {
+
+ /**
+ * Binary search an object by "tag" property
+ * @instance
+ * @function searchTag
+ * @memberof opentype.Layout
+ * @param {Array} arr
+ * @param {string} tag
+ * @return {number}
+ */
+ searchTag: searchTag,
+
+ /**
+ * Binary search in a list of numbers
+ * @instance
+ * @function binSearch
+ * @memberof opentype.Layout
+ * @param {Array} arr
+ * @param {number} value
+ * @return {number}
+ */
+ binSearch: binSearch,
+
+ /**
+ * Get or create the Layout table (GSUB, GPOS etc).
+ * @param {boolean} create - Whether to create a new one.
+ * @return {Object} The GSUB or GPOS table.
+ */
+ getTable: function(create) {
+ var layout = this.font.tables[this.tableName];
+ if (!layout && create) {
+ layout = this.font.tables[this.tableName] = this.createDefaultTable();
+ }
+ return layout;
+ },
+
+ /**
+ * Returns all scripts in the substitution table.
+ * @instance
+ * @return {Array}
+ */
+ getScriptNames: function() {
+ var layout = this.getTable();
+ if (!layout) { return []; }
+ return layout.scripts.map(function(script) {
+ return script.tag;
+ });
+ },
+
+ /**
+ * Returns the best bet for a script name.
+ * Returns 'DFLT' if it exists.
+ * If not, returns 'latn' if it exists.
+ * If neither exist, returns undefined.
+ */
+ getDefaultScriptName: function() {
+ var layout = this.getTable();
+ if (!layout) { return; }
+ var hasLatn = false;
+ for (var i = 0; i < layout.scripts.length; i++) {
+ var name = layout.scripts[i].tag;
+ if (name === 'DFLT') { return name; }
+ if (name === 'latn') { hasLatn = true; }
+ }
+ if (hasLatn) { return 'latn'; }
+ },
+
+ /**
+ * Returns all LangSysRecords in the given script.
+ * @instance
+ * @param {string} [script='DFLT']
+ * @param {boolean} create - forces the creation of this script table if it doesn't exist.
+ * @return {Object} An object with tag and script properties.
+ */
+ getScriptTable: function(script, create) {
+ var layout = this.getTable(create);
+ if (layout) {
+ script = script || 'DFLT';
+ var scripts = layout.scripts;
+ var pos = searchTag(layout.scripts, script);
+ if (pos >= 0) {
+ return scripts[pos].script;
+ } else if (create) {
+ var scr = {
+ tag: script,
+ script: {
+ defaultLangSys: {reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: []},
+ langSysRecords: []
+ }
+ };
+ scripts.splice(-1 - pos, 0, scr);
+ return scr.script;
+ }
+ }
+ },
+
+ /**
+ * Returns a language system table
+ * @instance
+ * @param {string} [script='DFLT']
+ * @param {string} [language='dlft']
+ * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist.
+ * @return {Object}
+ */
+ getLangSysTable: function(script, language, create) {
+ var scriptTable = this.getScriptTable(script, create);
+ if (scriptTable) {
+ if (!language || language === 'dflt' || language === 'DFLT') {
+ return scriptTable.defaultLangSys;
+ }
+ var pos = searchTag(scriptTable.langSysRecords, language);
+ if (pos >= 0) {
+ return scriptTable.langSysRecords[pos].langSys;
+ } else if (create) {
+ var langSysRecord = {
+ tag: language,
+ langSys: {reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: []}
+ };
+ scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord);
+ return langSysRecord.langSys;
+ }
+ }
+ },
+
+ /**
+ * Get a specific feature table.
+ * @instance
+ * @param {string} [script='DFLT']
+ * @param {string} [language='dlft']
+ * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm
+ * @param {boolean} create - forces the creation of the feature table if it doesn't exist.
+ * @return {Object}
+ */
+ getFeatureTable: function(script, language, feature, create) {
+ var langSysTable = this.getLangSysTable(script, language, create);
+ if (langSysTable) {
+ var featureRecord;
+ var featIndexes = langSysTable.featureIndexes;
+ var allFeatures = this.font.tables[this.tableName].features;
+ // The FeatureIndex array of indices is in arbitrary order,
+ // even if allFeatures is sorted alphabetically by feature tag.
+ for (var i = 0; i < featIndexes.length; i++) {
+ featureRecord = allFeatures[featIndexes[i]];
+ if (featureRecord.tag === feature) {
+ return featureRecord.feature;
+ }
+ }
+ if (create) {
+ var index = allFeatures.length;
+ // Automatic ordering of features would require to shift feature indexes in the script list.
+ check.assert(index === 0 || feature >= allFeatures[index - 1].tag, 'Features must be added in alphabetical order.');
+ featureRecord = {
+ tag: feature,
+ feature: { params: 0, lookupListIndexes: [] }
+ };
+ allFeatures.push(featureRecord);
+ featIndexes.push(index);
+ return featureRecord.feature;
+ }
+ }
+ },
+
+ /**
+ * Get the lookup tables of a given type for a script/language/feature.
+ * @instance
+ * @param {string} [script='DFLT']
+ * @param {string} [language='dlft']
+ * @param {string} feature - 4-letter feature code
+ * @param {number} lookupType - 1 to 8
+ * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables.
+ * @return {Object[]}
+ */
+ getLookupTables: function(script, language, feature, lookupType, create) {
+ var featureTable = this.getFeatureTable(script, language, feature, create);
+ var tables = [];
+ if (featureTable) {
+ var lookupTable;
+ var lookupListIndexes = featureTable.lookupListIndexes;
+ var allLookups = this.font.tables[this.tableName].lookups;
+ // lookupListIndexes are in no particular order, so use naive search.
+ for (var i = 0; i < lookupListIndexes.length; i++) {
+ lookupTable = allLookups[lookupListIndexes[i]];
+ if (lookupTable.lookupType === lookupType) {
+ tables.push(lookupTable);
+ }
+ }
+ if (tables.length === 0 && create) {
+ lookupTable = {
+ lookupType: lookupType,
+ lookupFlag: 0,
+ subtables: [],
+ markFilteringSet: undefined
+ };
+ var index = allLookups.length;
+ allLookups.push(lookupTable);
+ lookupListIndexes.push(index);
+ return [lookupTable];
+ }
+ }
+ return tables;
+ },
+
+ /**
+ * Returns the list of glyph indexes of a coverage table.
+ * Format 1: the list is stored raw
+ * Format 2: compact list as range records.
+ * @instance
+ * @param {Object} coverageTable
+ * @return {Array}
+ */
+ expandCoverage: function(coverageTable) {
+ if (coverageTable.format === 1) {
+ return coverageTable.glyphs;
+ } else {
+ var glyphs = [];
+ var ranges = coverageTable.ranges;
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i];
+ var start = range.start;
+ var end = range.end;
+ for (var j = start; j <= end; j++) {
+ glyphs.push(j);
+ }
+ }
+ return glyphs;
+ }
+ }
+
+};
+
+// The Substitution object provides utility methods to manipulate
+// the GSUB substitution table.
+
+/**
+ * @exports opentype.Substitution
+ * @class
+ * @extends opentype.Layout
+ * @param {opentype.Font}
+ * @constructor
+ */
+function Substitution(font) {
+ Layout.call(this, font, 'gsub');
+}
+
+// Check if 2 arrays of primitives are equal.
+function arraysEqual(ar1, ar2) {
+ var n = ar1.length;
+ if (n !== ar2.length) { return false; }
+ for (var i = 0; i < n; i++) {
+ if (ar1[i] !== ar2[i]) { return false; }
+ }
+ return true;
+}
+
+// Find the first subtable of a lookup table in a particular format.
+function getSubstFormat(lookupTable, format, defaultSubtable) {
+ var subtables = lookupTable.subtables;
+ for (var i = 0; i < subtables.length; i++) {
+ var subtable = subtables[i];
+ if (subtable.substFormat === format) {
+ return subtable;
+ }
+ }
+ if (defaultSubtable) {
+ subtables.push(defaultSubtable);
+ return defaultSubtable;
+ }
+ return undefined;
+}
+
+Substitution.prototype = Layout.prototype;
+
+/**
+ * Create a default GSUB table.
+ * @return {Object} gsub - The GSUB table.
+ */
+Substitution.prototype.createDefaultTable = function() {
+ // Generate a default empty GSUB table with just a DFLT script and dflt lang sys.
+ return {
+ version: 1,
+ scripts: [{
+ tag: 'DFLT',
+ script: {
+ defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] },
+ langSysRecords: []
+ }
+ }],
+ features: [],
+ lookups: []
+ };
+};
+
+/**
+ * List all single substitutions (lookup type 1) for a given script, language, and feature.
+ * @param {string} [script='DFLT']
+ * @param {string} [language='dflt']
+ * @param {string} feature - 4-character feature name ('aalt', 'salt', 'ss01'...)
+ * @return {Array} substitutions - The list of substitutions.
+ */
+Substitution.prototype.getSingle = function(feature, script, language) {
+ var this$1 = this;
+
+ var substitutions = [];
+ var lookupTables = this.getLookupTables(script, language, feature, 1);
+ for (var idx = 0; idx < lookupTables.length; idx++) {
+ var subtables = lookupTables[idx].subtables;
+ for (var i = 0; i < subtables.length; i++) {
+ var subtable = subtables[i];
+ var glyphs = this$1.expandCoverage(subtable.coverage);
+ var j = (void 0);
+ if (subtable.substFormat === 1) {
+ var delta = subtable.deltaGlyphId;
+ for (j = 0; j < glyphs.length; j++) {
+ var glyph = glyphs[j];
+ substitutions.push({ sub: glyph, by: glyph + delta });
+ }
+ } else {
+ var substitute = subtable.substitute;
+ for (j = 0; j < glyphs.length; j++) {
+ substitutions.push({ sub: glyphs[j], by: substitute[j] });
+ }
+ }
+ }
+ }
+ return substitutions;
+};
+
+/**
+ * List all alternates (lookup type 3) for a given script, language, and feature.
+ * @param {string} [script='DFLT']
+ * @param {string} [language='dflt']
+ * @param {string} feature - 4-character feature name ('aalt', 'salt'...)
+ * @return {Array} alternates - The list of alternates
+ */
+Substitution.prototype.getAlternates = function(feature, script, language) {
+ var this$1 = this;
+
+ var alternates = [];
+ var lookupTables = this.getLookupTables(script, language, feature, 3);
+ for (var idx = 0; idx < lookupTables.length; idx++) {
+ var subtables = lookupTables[idx].subtables;
+ for (var i = 0; i < subtables.length; i++) {
+ var subtable = subtables[i];
+ var glyphs = this$1.expandCoverage(subtable.coverage);
+ var alternateSets = subtable.alternateSets;
+ for (var j = 0; j < glyphs.length; j++) {
+ alternates.push({ sub: glyphs[j], by: alternateSets[j] });
+ }
+ }
+ }
+ return alternates;
+};
+
+/**
+ * List all ligatures (lookup type 4) for a given script, language, and feature.
+ * The result is an array of ligature objects like { sub: [ids], by: id }
+ * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
+ * @param {string} [script='DFLT']
+ * @param {string} [language='dflt']
+ * @return {Array} ligatures - The list of ligatures.
+ */
+Substitution.prototype.getLigatures = function(feature, script, language) {
+ var this$1 = this;
+
+ var ligatures = [];
+ var lookupTables = this.getLookupTables(script, language, feature, 4);
+ for (var idx = 0; idx < lookupTables.length; idx++) {
+ var subtables = lookupTables[idx].subtables;
+ for (var i = 0; i < subtables.length; i++) {
+ var subtable = subtables[i];
+ var glyphs = this$1.expandCoverage(subtable.coverage);
+ var ligatureSets = subtable.ligatureSets;
+ for (var j = 0; j < glyphs.length; j++) {
+ var startGlyph = glyphs[j];
+ var ligSet = ligatureSets[j];
+ for (var k = 0; k < ligSet.length; k++) {
+ var lig = ligSet[k];
+ ligatures.push({
+ sub: [startGlyph].concat(lig.components),
+ by: lig.ligGlyph
+ });
+ }
+ }
+ }
+ }
+ return ligatures;
+};
+
+/**
+ * Add or modify a single substitution (lookup type 1)
+ * Format 2, more flexible, is always used.
+ * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
+ * @param {Object} substitution - { sub: id, delta: number } for format 1 or { sub: id, by: id } for format 2.
+ * @param {string} [script='DFLT']
+ * @param {string} [language='dflt']
+ */
+Substitution.prototype.addSingle = function(feature, substitution, script, language) {
+ var lookupTable = this.getLookupTables(script, language, feature, 1, true)[0];
+ var subtable = getSubstFormat(lookupTable, 2, { // lookup type 1 subtable, format 2, coverage format 1
+ substFormat: 2,
+ coverage: {format: 1, glyphs: []},
+ substitute: []
+ });
+ check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format);
+ var coverageGlyph = substitution.sub;
+ var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
+ if (pos < 0) {
+ pos = -1 - pos;
+ subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
+ subtable.substitute.splice(pos, 0, 0);
+ }
+ subtable.substitute[pos] = substitution.by;
+};
+
+/**
+ * Add or modify an alternate substitution (lookup type 1)
+ * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
+ * @param {Object} substitution - { sub: id, by: [ids] }
+ * @param {string} [script='DFLT']
+ * @param {string} [language='dflt']
+ */
+Substitution.prototype.addAlternate = function(feature, substitution, script, language) {
+ var lookupTable = this.getLookupTables(script, language, feature, 3, true)[0];
+ var subtable = getSubstFormat(lookupTable, 1, { // lookup type 3 subtable, format 1, coverage format 1
+ substFormat: 1,
+ coverage: {format: 1, glyphs: []},
+ alternateSets: []
+ });
+ check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format);
+ var coverageGlyph = substitution.sub;
+ var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
+ if (pos < 0) {
+ pos = -1 - pos;
+ subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
+ subtable.alternateSets.splice(pos, 0, 0);
+ }
+ subtable.alternateSets[pos] = substitution.by;
+};
+
+/**
+ * Add a ligature (lookup type 4)
+ * Ligatures with more components must be stored ahead of those with fewer components in order to be found
+ * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
+ * @param {Object} ligature - { sub: [ids], by: id }
+ * @param {string} [script='DFLT']
+ * @param {string} [language='dflt']
+ */
+Substitution.prototype.addLigature = function(feature, ligature, script, language) {
+ var lookupTable = this.getLookupTables(script, language, feature, 4, true)[0];
+ var subtable = lookupTable.subtables[0];
+ if (!subtable) {
+ subtable = { // lookup type 4 subtable, format 1, coverage format 1
+ substFormat: 1,
+ coverage: { format: 1, glyphs: [] },
+ ligatureSets: []
+ };
+ lookupTable.subtables[0] = subtable;
+ }
+ check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format);
+ var coverageGlyph = ligature.sub[0];
+ var ligComponents = ligature.sub.slice(1);
+ var ligatureTable = {
+ ligGlyph: ligature.by,
+ components: ligComponents
+ };
+ var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
+ if (pos >= 0) {
+ // ligatureSet already exists
+ var ligatureSet = subtable.ligatureSets[pos];
+ for (var i = 0; i < ligatureSet.length; i++) {
+ // If ligature already exists, return.
+ if (arraysEqual(ligatureSet[i].components, ligComponents)) {
+ return;
+ }
+ }
+ // ligature does not exist: add it.
+ ligatureSet.push(ligatureTable);
+ } else {
+ // Create a new ligatureSet and add coverage for the first glyph.
+ pos = -1 - pos;
+ subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
+ subtable.ligatureSets.splice(pos, 0, [ligatureTable]);
+ }
+};
+
+/**
+ * List all feature data for a given script and language.
+ * @param {string} feature - 4-letter feature name
+ * @param {string} [script='DFLT']
+ * @param {string} [language='dflt']
+ * @return {Array} substitutions - The list of substitutions.
+ */
+Substitution.prototype.getFeature = function(feature, script, language) {
+ if (/ss\d\d/.test(feature)) { // ss01 - ss20
+ return this.getSingle(feature, script, language);
+ }
+ switch (feature) {
+ case 'aalt':
+ case 'salt':
+ return this.getSingle(feature, script, language)
+ .concat(this.getAlternates(feature, script, language));
+ case 'dlig':
+ case 'liga':
+ case 'rlig': return this.getLigatures(feature, script, language);
+ }
+ return undefined;
+};
+
+/**
+ * Add a substitution to a feature for a given script and language.
+ * @param {string} feature - 4-letter feature name
+ * @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] })
+ * @param {string} [script='DFLT']
+ * @param {string} [language='dflt']
+ */
+Substitution.prototype.add = function(feature, sub, script, language) {
+ if (/ss\d\d/.test(feature)) { // ss01 - ss20
+ return this.addSingle(feature, sub, script, language);
+ }
+ switch (feature) {
+ case 'aalt':
+ case 'salt':
+ if (typeof sub.by === 'number') {
+ return this.addSingle(feature, sub, script, language);
+ }
+ return this.addAlternate(feature, sub, script, language);
+ case 'dlig':
+ case 'liga':
+ case 'rlig':
+ return this.addLigature(feature, sub, script, language);
+ }
+ return undefined;
+};
+
+function isBrowser() {
+ return typeof window !== 'undefined';
+}
+
+function nodeBufferToArrayBuffer(buffer) {
+ var ab = new ArrayBuffer(buffer.length);
+ var view = new Uint8Array(ab);
+ for (var i = 0; i < buffer.length; ++i) {
+ view[i] = buffer[i];
+ }
+
+ return ab;
+}
+
+function arrayBufferToNodeBuffer(ab) {
+ var buffer = new Buffer(ab.byteLength);
+ var view = new Uint8Array(ab);
+ for (var i = 0; i < buffer.length; ++i) {
+ buffer[i] = view[i];
+ }
+
+ return buffer;
+}
+
+function checkArgument(expression, message) {
+ if (!expression) {
+ throw message;
+ }
+}
+
+/* A TrueType font hinting interpreter.
+*
+* (c) 2017 Axel Kittenberger
+*
+* This interpreter has been implemented according to this documentation:
+* https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html
+*
+* According to the documentation F24DOT6 values are used for pixels.
+* That means calculation is 1/64 pixel accurate and uses integer operations.
+* However, Javascript has floating point operations by default and only
+* those are available. One could make a case to simulate the 1/64 accuracy
+* exactly by truncating after every division operation
+* (for example with << 0) to get pixel exactly results as other TrueType
+* implementations. It may make sense since some fonts are pixel optimized
+* by hand using DELTAP instructions. The current implementation doesn't
+* and rather uses full floating point precision.
+*
+* xScale, yScale and rotation is currently ignored.
+*
+* A few non-trivial instructions are missing as I didn't encounter yet
+* a font that used them to test a possible implementation.
+*
+* Some fonts seem to use undocumented features regarding the twilight zone.
+* Only some of them are implemented as they were encountered.
+*
+* The exports.DEBUG statements are removed on the minified distribution file.
+*/
+var instructionTable;
+var exec;
+var execGlyph;
+var execComponent;
+
+/*
+* Creates a hinting object.
+*
+* There ought to be exactly one
+* for each truetype font that is used for hinting.
+*/
+function Hinting(font) {
+ // the font this hinting object is for
+ this.font = font;
+
+ // cached states
+ this._fpgmState =
+ this._prepState =
+ undefined;
+
+ // errorState
+ // 0 ... all okay
+ // 1 ... had an error in a glyf,
+ // continue working but stop spamming
+ // the console
+ // 2 ... error at prep, stop hinting at this ppem
+ // 3 ... error at fpeg, stop hinting for this font at all
+ this._errorState = 0;
+}
+
+/*
+* Not rounding.
+*/
+function roundOff(v) {
+ return v;
+}
+
+/*
+* Rounding to grid.
+*/
+function roundToGrid(v) {
+ //Rounding in TT is supposed to "symmetrical around zero"
+ return Math.sign(v) * Math.round(Math.abs(v));
+}
+
+/*
+* Rounding to double grid.
+*/
+function roundToDoubleGrid(v) {
+ return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2;
+}
+
+/*
+* Rounding to half grid.
+*/
+function roundToHalfGrid(v) {
+ return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5);
+}
+
+/*
+* Rounding to up to grid.
+*/
+function roundUpToGrid(v) {
+ return Math.sign(v) * Math.ceil(Math.abs(v));
+}
+
+/*
+* Rounding to down to grid.
+*/
+function roundDownToGrid(v) {
+ return Math.sign(v) * Math.floor(Math.abs(v));
+}
+
+/*
+* Super rounding.
+*/
+var roundSuper = function (v) {
+ var period = this.srPeriod;
+ var phase = this.srPhase;
+ var threshold = this.srThreshold;
+ var sign = 1;
+
+ if (v < 0) {
+ v = -v;
+ sign = -1;
+ }
+
+ v += threshold - phase;
+
+ v = Math.trunc(v / period) * period;
+
+ v += phase;
+
+ // according to http://xgridfit.sourceforge.net/round.html
+ if (sign > 0 && v < 0) { return phase; }
+ if (sign < 0 && v > 0) { return -phase; }
+
+ return v * sign;
+};
+
+/*
+* Unit vector of x-axis.
+*/
+var xUnitVector = {
+ x: 1,
+
+ y: 0,
+
+ axis: 'x',
+
+ // Gets the projected distance between two points.
+ // o1/o2 ... if true, respective original position is used.
+ distance: function (p1, p2, o1, o2) {
+ return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x);
+ },
+
+ // Moves point p so the moved position has the same relative
+ // position to the moved positions of rp1 and rp2 than the
+ // original positions had.
+ //
+ // See APPENDIX on INTERPOLATE at the bottom of this file.
+ interpolate: function (p, rp1, rp2, pv) {
+ var do1;
+ var do2;
+ var doa1;
+ var doa2;
+ var dm1;
+ var dm2;
+ var dt;
+
+ if (!pv || pv === this) {
+ do1 = p.xo - rp1.xo;
+ do2 = p.xo - rp2.xo;
+ dm1 = rp1.x - rp1.xo;
+ dm2 = rp2.x - rp2.xo;
+ doa1 = Math.abs(do1);
+ doa2 = Math.abs(do2);
+ dt = doa1 + doa2;
+
+ if (dt === 0) {
+ p.x = p.xo + (dm1 + dm2) / 2;
+ return;
+ }
+
+ p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt;
+ return;
+ }
+
+ do1 = pv.distance(p, rp1, true, true);
+ do2 = pv.distance(p, rp2, true, true);
+ dm1 = pv.distance(rp1, rp1, false, true);
+ dm2 = pv.distance(rp2, rp2, false, true);
+ doa1 = Math.abs(do1);
+ doa2 = Math.abs(do2);
+ dt = doa1 + doa2;
+
+ if (dt === 0) {
+ xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
+ return;
+ }
+
+ xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
+ },
+
+ // Slope of line normal to this
+ normalSlope: Number.NEGATIVE_INFINITY,
+
+ // Sets the point 'p' relative to point 'rp'
+ // by the distance 'd'.
+ //
+ // See APPENDIX on SETRELATIVE at the bottom of this file.
+ //
+ // p ... point to set
+ // rp ... reference point
+ // d ... distance on projection vector
+ // pv ... projection vector (undefined = this)
+ // org ... if true, uses the original position of rp as reference.
+ setRelative: function (p, rp, d, pv, org) {
+ if (!pv || pv === this) {
+ p.x = (org ? rp.xo : rp.x) + d;
+ return;
+ }
+
+ var rpx = org ? rp.xo : rp.x;
+ var rpy = org ? rp.yo : rp.y;
+ var rpdx = rpx + d * pv.x;
+ var rpdy = rpy + d * pv.y;
+
+ p.x = rpdx + (p.y - rpdy) / pv.normalSlope;
+ },
+
+ // Slope of vector line.
+ slope: 0,
+
+ // Touches the point p.
+ touch: function (p) {
+ p.xTouched = true;
+ },
+
+ // Tests if a point p is touched.
+ touched: function (p) {
+ return p.xTouched;
+ },
+
+ // Untouches the point p.
+ untouch: function (p) {
+ p.xTouched = false;
+ }
+};
+
+/*
+* Unit vector of y-axis.
+*/
+var yUnitVector = {
+ x: 0,
+
+ y: 1,
+
+ axis: 'y',
+
+ // Gets the projected distance between two points.
+ // o1/o2 ... if true, respective original position is used.
+ distance: function (p1, p2, o1, o2) {
+ return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y);
+ },
+
+ // Moves point p so the moved position has the same relative
+ // position to the moved positions of rp1 and rp2 than the
+ // original positions had.
+ //
+ // See APPENDIX on INTERPOLATE at the bottom of this file.
+ interpolate: function (p, rp1, rp2, pv) {
+ var do1;
+ var do2;
+ var doa1;
+ var doa2;
+ var dm1;
+ var dm2;
+ var dt;
+
+ if (!pv || pv === this) {
+ do1 = p.yo - rp1.yo;
+ do2 = p.yo - rp2.yo;
+ dm1 = rp1.y - rp1.yo;
+ dm2 = rp2.y - rp2.yo;
+ doa1 = Math.abs(do1);
+ doa2 = Math.abs(do2);
+ dt = doa1 + doa2;
+
+ if (dt === 0) {
+ p.y = p.yo + (dm1 + dm2) / 2;
+ return;
+ }
+
+ p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt;
+ return;
+ }
+
+ do1 = pv.distance(p, rp1, true, true);
+ do2 = pv.distance(p, rp2, true, true);
+ dm1 = pv.distance(rp1, rp1, false, true);
+ dm2 = pv.distance(rp2, rp2, false, true);
+ doa1 = Math.abs(do1);
+ doa2 = Math.abs(do2);
+ dt = doa1 + doa2;
+
+ if (dt === 0) {
+ yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
+ return;
+ }
+
+ yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
+ },
+
+ // Slope of line normal to this.
+ normalSlope: 0,
+
+ // Sets the point 'p' relative to point 'rp'
+ // by the distance 'd'
+ //
+ // See APPENDIX on SETRELATIVE at the bottom of this file.
+ //
+ // p ... point to set
+ // rp ... reference point
+ // d ... distance on projection vector
+ // pv ... projection vector (undefined = this)
+ // org ... if true, uses the original position of rp as reference.
+ setRelative: function (p, rp, d, pv, org) {
+ if (!pv || pv === this) {
+ p.y = (org ? rp.yo : rp.y) + d;
+ return;
+ }
+
+ var rpx = org ? rp.xo : rp.x;
+ var rpy = org ? rp.yo : rp.y;
+ var rpdx = rpx + d * pv.x;
+ var rpdy = rpy + d * pv.y;
+
+ p.y = rpdy + pv.normalSlope * (p.x - rpdx);
+ },
+
+ // Slope of vector line.
+ slope: Number.POSITIVE_INFINITY,
+
+ // Touches the point p.
+ touch: function (p) {
+ p.yTouched = true;
+ },
+
+ // Tests if a point p is touched.
+ touched: function (p) {
+ return p.yTouched;
+ },
+
+ // Untouches the point p.
+ untouch: function (p) {
+ p.yTouched = false;
+ }
+};
+
+Object.freeze(xUnitVector);
+Object.freeze(yUnitVector);
+
+/*
+* Creates a unit vector that is not x- or y-axis.
+*/
+function UnitVector(x, y) {
+ this.x = x;
+ this.y = y;
+ this.axis = undefined;
+ this.slope = y / x;
+ this.normalSlope = -x / y;
+ Object.freeze(this);
+}
+
+/*
+* Gets the projected distance between two points.
+* o1/o2 ... if true, respective original position is used.
+*/
+UnitVector.prototype.distance = function(p1, p2, o1, o2) {
+ return (
+ this.x * xUnitVector.distance(p1, p2, o1, o2) +
+ this.y * yUnitVector.distance(p1, p2, o1, o2)
+ );
+};
+
+/*
+* Moves point p so the moved position has the same relative
+* position to the moved positions of rp1 and rp2 than the
+* original positions had.
+*
+* See APPENDIX on INTERPOLATE at the bottom of this file.
+*/
+UnitVector.prototype.interpolate = function(p, rp1, rp2, pv) {
+ var dm1;
+ var dm2;
+ var do1;
+ var do2;
+ var doa1;
+ var doa2;
+ var dt;
+
+ do1 = pv.distance(p, rp1, true, true);
+ do2 = pv.distance(p, rp2, true, true);
+ dm1 = pv.distance(rp1, rp1, false, true);
+ dm2 = pv.distance(rp2, rp2, false, true);
+ doa1 = Math.abs(do1);
+ doa2 = Math.abs(do2);
+ dt = doa1 + doa2;
+
+ if (dt === 0) {
+ this.setRelative(p, p, (dm1 + dm2) / 2, pv, true);
+ return;
+ }
+
+ this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true);
+};
+
+/*
+* Sets the point 'p' relative to point 'rp'
+* by the distance 'd'
+*
+* See APPENDIX on SETRELATIVE at the bottom of this file.
+*
+* p ... point to set
+* rp ... reference point
+* d ... distance on projection vector
+* pv ... projection vector (undefined = this)
+* org ... if true, uses the original position of rp as reference.
+*/
+UnitVector.prototype.setRelative = function(p, rp, d, pv, org) {
+ pv = pv || this;
+
+ var rpx = org ? rp.xo : rp.x;
+ var rpy = org ? rp.yo : rp.y;
+ var rpdx = rpx + d * pv.x;
+ var rpdy = rpy + d * pv.y;
+
+ var pvns = pv.normalSlope;
+ var fvs = this.slope;
+
+ var px = p.x;
+ var py = p.y;
+
+ p.x = (fvs * px - pvns * rpdx + rpdy - py) / (fvs - pvns);
+ p.y = fvs * (p.x - px) + py;
+};
+
+/*
+* Touches the point p.
+*/
+UnitVector.prototype.touch = function(p) {
+ p.xTouched = true;
+ p.yTouched = true;
+};
+
+/*
+* Returns a unit vector with x/y coordinates.
+*/
+function getUnitVector(x, y) {
+ var d = Math.sqrt(x * x + y * y);
+
+ x /= d;
+ y /= d;
+
+ if (x === 1 && y === 0) { return xUnitVector; }
+ else if (x === 0 && y === 1) { return yUnitVector; }
+ else { return new UnitVector(x, y); }
+}
+
+/*
+* Creates a point in the hinting engine.
+*/
+function HPoint(
+ x,
+ y,
+ lastPointOfContour,
+ onCurve
+) {
+ this.x = this.xo = Math.round(x * 64) / 64; // hinted x value and original x-value
+ this.y = this.yo = Math.round(y * 64) / 64; // hinted y value and original y-value
+
+ this.lastPointOfContour = lastPointOfContour;
+ this.onCurve = onCurve;
+ this.prevPointOnContour = undefined;
+ this.nextPointOnContour = undefined;
+ this.xTouched = false;
+ this.yTouched = false;
+
+ Object.preventExtensions(this);
+}
+
+/*
+* Returns the next touched point on the contour.
+*
+* v ... unit vector to test touch axis.
+*/
+HPoint.prototype.nextTouched = function(v) {
+ var p = this.nextPointOnContour;
+
+ while (!v.touched(p) && p !== this) { p = p.nextPointOnContour; }
+
+ return p;
+};
+
+/*
+* Returns the previous touched point on the contour
+*
+* v ... unit vector to test touch axis.
+*/
+HPoint.prototype.prevTouched = function(v) {
+ var p = this.prevPointOnContour;
+
+ while (!v.touched(p) && p !== this) { p = p.prevPointOnContour; }
+
+ return p;
+};
+
+/*
+* The zero point.
+*/
+var HPZero = Object.freeze(new HPoint(0, 0));
+
+/*
+* The default state of the interpreter.
+*
+* Note: Freezing the defaultState and then deriving from it
+* makes the V8 Javascript engine going awkward,
+* so this is avoided, albeit the defaultState shouldn't
+* ever change.
+*/
+var defaultState = {
+ cvCutIn: 17 / 16, // control value cut in
+ deltaBase: 9,
+ deltaShift: 0.125,
+ loop: 1, // loops some instructions
+ minDis: 1, // minimum distance
+ autoFlip: true
+};
+
+/*
+* The current state of the interpreter.
+*
+* env ... 'fpgm' or 'prep' or 'glyf'
+* prog ... the program
+*/
+function State(env, prog) {
+ this.env = env;
+ this.stack = [];
+ this.prog = prog;
+
+ switch (env) {
+ case 'glyf' :
+ this.zp0 = this.zp1 = this.zp2 = 1;
+ this.rp0 = this.rp1 = this.rp2 = 0;
+ /* fall through */
+ case 'prep' :
+ this.fv = this.pv = this.dpv = xUnitVector;
+ this.round = roundToGrid;
+ }
+}
+
+/*
+* Executes a glyph program.
+*
+* This does the hinting for each glyph.
+*
+* Returns an array of moved points.
+*
+* glyph: the glyph to hint
+* ppem: the size the glyph is rendered for
+*/
+Hinting.prototype.exec = function(glyph, ppem) {
+ if (typeof ppem !== 'number') {
+ throw new Error('Point size is not a number!');
+ }
+
+ // Received a fatal error, don't do any hinting anymore.
+ if (this._errorState > 2) { return; }
+
+ var font = this.font;
+ var prepState = this._prepState;
+
+ if (!prepState || prepState.ppem !== ppem) {
+ var fpgmState = this._fpgmState;
+
+ if (!fpgmState) {
+ // Executes the fpgm state.
+ // This is used by fonts to define functions.
+ State.prototype = defaultState;
+
+ fpgmState =
+ this._fpgmState =
+ new State('fpgm', font.tables.fpgm);
+
+ fpgmState.funcs = [ ];
+ fpgmState.font = font;
+
+ if (exports.DEBUG) {
+ console.log('---EXEC FPGM---');
+ fpgmState.step = -1;
+ }
+
+ try {
+ exec(fpgmState);
+ } catch (e) {
+ console.log('Hinting error in FPGM:' + e);
+ this._errorState = 3;
+ return;
+ }
+ }
+
+ // Executes the prep program for this ppem setting.
+ // This is used by fonts to set cvt values
+ // depending on to be rendered font size.
+
+ State.prototype = fpgmState;
+ prepState =
+ this._prepState =
+ new State('prep', font.tables.prep);
+
+ prepState.ppem = ppem;
+
+ // Creates a copy of the cvt table
+ // and scales it to the current ppem setting.
+ var oCvt = font.tables.cvt;
+ if (oCvt) {
+ var cvt = prepState.cvt = new Array(oCvt.length);
+ var scale = ppem / font.unitsPerEm;
+ for (var c = 0; c < oCvt.length; c++) {
+ cvt[c] = oCvt[c] * scale;
+ }
+ } else {
+ prepState.cvt = [];
+ }
+
+ if (exports.DEBUG) {
+ console.log('---EXEC PREP---');
+ prepState.step = -1;
+ }
+
+ try {
+ exec(prepState);
+ } catch (e) {
+ if (this._errorState < 2) {
+ console.log('Hinting error in PREP:' + e);
+ }
+ this._errorState = 2;
+ }
+ }
+
+ if (this._errorState > 1) { return; }
+
+ try {
+ return execGlyph(glyph, prepState);
+ } catch (e) {
+ if (this._errorState < 1) {
+ console.log('Hinting error:' + e);
+ console.log('Note: further hinting errors are silenced');
+ }
+ this._errorState = 1;
+ return undefined;
+ }
+};
+
+/*
+* Executes the hinting program for a glyph.
+*/
+execGlyph = function(glyph, prepState) {
+ // original point positions
+ var xScale = prepState.ppem / prepState.font.unitsPerEm;
+ var yScale = xScale;
+ var components = glyph.components;
+ var contours;
+ var gZone;
+ var state;
+
+ State.prototype = prepState;
+ if (!components) {
+ state = new State('glyf', glyph.instructions);
+ if (exports.DEBUG) {
+ console.log('---EXEC GLYPH---');
+ state.step = -1;
+ }
+ execComponent(glyph, state, xScale, yScale);
+ gZone = state.gZone;
+ } else {
+ var font = prepState.font;
+ gZone = [];
+ contours = [];
+ for (var i = 0; i < components.length; i++) {
+ var c = components[i];
+ var cg = font.glyphs.get(c.glyphIndex);
+
+ state = new State('glyf', cg.instructions);
+
+ if (exports.DEBUG) {
+ console.log('---EXEC COMP ' + i + '---');
+ state.step = -1;
+ }
+
+ execComponent(cg, state, xScale, yScale);
+ // appends the computed points to the result array
+ // post processes the component points
+ var dx = Math.round(c.dx * xScale);
+ var dy = Math.round(c.dy * yScale);
+ var gz = state.gZone;
+ var cc = state.contours;
+ for (var pi = 0; pi < gz.length; pi++) {
+ var p = gz[pi];
+ p.xTouched = p.yTouched = false;
+ p.xo = p.x = p.x + dx;
+ p.yo = p.y = p.y + dy;
+ }
+
+ var gLen = gZone.length;
+ gZone.push.apply(gZone, gz);
+ for (var j = 0; j < cc.length; j++) {
+ contours.push(cc[j] + gLen);
+ }
+ }
+
+ if (glyph.instructions && !state.inhibitGridFit) {
+ // the composite has instructions on its own
+ state = new State('glyf', glyph.instructions);
+
+ state.gZone = state.z0 = state.z1 = state.z2 = gZone;
+
+ state.contours = contours;
+
+ // note: HPZero cannot be used here, since
+ // the point might be modified
+ gZone.push(
+ new HPoint(0, 0),
+ new HPoint(Math.round(glyph.advanceWidth * xScale), 0)
+ );
+
+ if (exports.DEBUG) {
+ console.log('---EXEC COMPOSITE---');
+ state.step = -1;
+ }
+
+ exec(state);
+
+ gZone.length -= 2;
+ }
+ }
+
+ return gZone;
+};
+
+/*
+* Executes the hinting program for a component of a multi-component glyph
+* or of the glyph itself by a non-component glyph.
+*/
+execComponent = function(glyph, state, xScale, yScale)
+{
+ var points = glyph.points || [];
+ var pLen = points.length;
+ var gZone = state.gZone = state.z0 = state.z1 = state.z2 = [];
+ var contours = state.contours = [];
+
+ // Scales the original points and
+ // makes copies for the hinted points.
+ var cp; // current point
+ for (var i = 0; i < pLen; i++) {
+ cp = points[i];
+
+ gZone[i] = new HPoint(
+ cp.x * xScale,
+ cp.y * yScale,
+ cp.lastPointOfContour,
+ cp.onCurve
+ );
+ }
+
+ // Chain links the contours.
+ var sp; // start point
+ var np; // next point
+
+ for (var i$1 = 0; i$1 < pLen; i$1++) {
+ cp = gZone[i$1];
+
+ if (!sp) {
+ sp = cp;
+ contours.push(i$1);
+ }
+
+ if (cp.lastPointOfContour) {
+ cp.nextPointOnContour = sp;
+ sp.prevPointOnContour = cp;
+ sp = undefined;
+ } else {
+ np = gZone[i$1 + 1];
+ cp.nextPointOnContour = np;
+ np.prevPointOnContour = cp;
+ }
+ }
+
+ if (state.inhibitGridFit) { return; }
+
+ gZone.push(
+ new HPoint(0, 0),
+ new HPoint(Math.round(glyph.advanceWidth * xScale), 0)
+ );
+
+ exec(state);
+
+ // Removes the extra points.
+ gZone.length -= 2;
+
+ if (exports.DEBUG) {
+ console.log('FINISHED GLYPH', state.stack);
+ for (var i$2 = 0; i$2 < pLen; i$2++) {
+ console.log(i$2, gZone[i$2].x, gZone[i$2].y);
+ }
+ }
+};
+
+/*
+* Executes the program loaded in state.
+*/
+exec = function(state) {
+ var prog = state.prog;
+
+ if (!prog) { return; }
+
+ var pLen = prog.length;
+ var ins;
+
+ for (state.ip = 0; state.ip < pLen; state.ip++) {
+ if (exports.DEBUG) { state.step++; }
+ ins = instructionTable[prog[state.ip]];
+
+ if (!ins) {
+ throw new Error(
+ 'unknown instruction: 0x' +
+ Number(prog[state.ip]).toString(16)
+ );
+ }
+
+ ins(state);
+
+ // very extensive debugging for each step
+ /*
+ if (exports.DEBUG) {
+ var da;
+ if (state.gZone) {
+ da = [];
+ for (let i = 0; i < state.gZone.length; i++)
+ {
+ da.push(i + ' ' +
+ state.gZone[i].x * 64 + ' ' +
+ state.gZone[i].y * 64 + ' ' +
+ (state.gZone[i].xTouched ? 'x' : '') +
+ (state.gZone[i].yTouched ? 'y' : '')
+ );
+ }
+ console.log('GZ', da);
+ }
+
+ if (state.tZone) {
+ da = [];
+ for (let i = 0; i < state.tZone.length; i++) {
+ da.push(i + ' ' +
+ state.tZone[i].x * 64 + ' ' +
+ state.tZone[i].y * 64 + ' ' +
+ (state.tZone[i].xTouched ? 'x' : '') +
+ (state.tZone[i].yTouched ? 'y' : '')
+ );
+ }
+ console.log('TZ', da);
+ }
+
+ if (state.stack.length > 10) {
+ console.log(
+ state.stack.length,
+ '...', state.stack.slice(state.stack.length - 10)
+ );
+ } else {
+ console.log(state.stack.length, state.stack);
+ }
+ }
+ */
+ }
+};
+
+/*
+* Initializes the twilight zone.
+*
+* This is only done if a SZPx instruction
+* refers to the twilight zone.
+*/
+function initTZone(state)
+{
+ var tZone = state.tZone = new Array(state.gZone.length);
+
+ // no idea if this is actually correct...
+ for (var i = 0; i < tZone.length; i++)
+ {
+ tZone[i] = new HPoint(0, 0);
+ }
+}
+
+/*
+* Skips the instruction pointer ahead over an IF/ELSE block.
+* handleElse .. if true breaks on matching ELSE
+*/
+function skip(state, handleElse)
+{
+ var prog = state.prog;
+ var ip = state.ip;
+ var nesting = 1;
+ var ins;
+
+ do {
+ ins = prog[++ip];
+ if (ins === 0x58) // IF
+ { nesting++; }
+ else if (ins === 0x59) // EIF
+ { nesting--; }
+ else if (ins === 0x40) // NPUSHB
+ { ip += prog[ip + 1] + 1; }
+ else if (ins === 0x41) // NPUSHW
+ { ip += 2 * prog[ip + 1] + 1; }
+ else if (ins >= 0xB0 && ins <= 0xB7) // PUSHB
+ { ip += ins - 0xB0 + 1; }
+ else if (ins >= 0xB8 && ins <= 0xBF) // PUSHW
+ { ip += (ins - 0xB8 + 1) * 2; }
+ else if (handleElse && nesting === 1 && ins === 0x1B) // ELSE
+ { break; }
+ } while (nesting > 0);
+
+ state.ip = ip;
+}
+
+/*----------------------------------------------------------*
+* And then a lot of instructions... *
+*----------------------------------------------------------*/
+
+// SVTCA[a] Set freedom and projection Vectors To Coordinate Axis
+// 0x00-0x01
+function SVTCA(v, state) {
+ if (exports.DEBUG) { console.log(state.step, 'SVTCA[' + v.axis + ']'); }
+
+ state.fv = state.pv = state.dpv = v;
+}
+
+// SPVTCA[a] Set Projection Vector to Coordinate Axis
+// 0x02-0x03
+function SPVTCA(v, state) {
+ if (exports.DEBUG) { console.log(state.step, 'SPVTCA[' + v.axis + ']'); }
+
+ state.pv = state.dpv = v;
+}
+
+// SFVTCA[a] Set Freedom Vector to Coordinate Axis
+// 0x04-0x05
+function SFVTCA(v, state) {
+ if (exports.DEBUG) { console.log(state.step, 'SFVTCA[' + v.axis + ']'); }
+
+ state.fv = v;
+}
+
+// SPVTL[a] Set Projection Vector To Line
+// 0x06-0x07
+function SPVTL(a, state) {
+ var stack = state.stack;
+ var p2i = stack.pop();
+ var p1i = stack.pop();
+ var p2 = state.z2[p2i];
+ var p1 = state.z1[p1i];
+
+ if (exports.DEBUG) { console.log('SPVTL[' + a + ']', p2i, p1i); }
+
+ var dx;
+ var dy;
+
+ if (!a) {
+ dx = p1.x - p2.x;
+ dy = p1.y - p2.y;
+ } else {
+ dx = p2.y - p1.y;
+ dy = p1.x - p2.x;
+ }
+
+ state.pv = state.dpv = getUnitVector(dx, dy);
+}
+
+// SFVTL[a] Set Freedom Vector To Line
+// 0x08-0x09
+function SFVTL(a, state) {
+ var stack = state.stack;
+ var p2i = stack.pop();
+ var p1i = stack.pop();
+ var p2 = state.z2[p2i];
+ var p1 = state.z1[p1i];
+
+ if (exports.DEBUG) { console.log('SFVTL[' + a + ']', p2i, p1i); }
+
+ var dx;
+ var dy;
+
+ if (!a) {
+ dx = p1.x - p2.x;
+ dy = p1.y - p2.y;
+ } else {
+ dx = p2.y - p1.y;
+ dy = p1.x - p2.x;
+ }
+
+ state.fv = getUnitVector(dx, dy);
+}
+
+// SPVFS[] Set Projection Vector From Stack
+// 0x0A
+function SPVFS(state) {
+ var stack = state.stack;
+ var y = stack.pop();
+ var x = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SPVFS[]', y, x); }
+
+ state.pv = state.dpv = getUnitVector(x, y);
+}
+
+// SFVFS[] Set Freedom Vector From Stack
+// 0x0B
+function SFVFS(state) {
+ var stack = state.stack;
+ var y = stack.pop();
+ var x = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SPVFS[]', y, x); }
+
+ state.fv = getUnitVector(x, y);
+}
+
+// GPV[] Get Projection Vector
+// 0x0C
+function GPV(state) {
+ var stack = state.stack;
+ var pv = state.pv;
+
+ if (exports.DEBUG) { console.log(state.step, 'GPV[]'); }
+
+ stack.push(pv.x * 0x4000);
+ stack.push(pv.y * 0x4000);
+}
+
+// GFV[] Get Freedom Vector
+// 0x0C
+function GFV(state) {
+ var stack = state.stack;
+ var fv = state.fv;
+
+ if (exports.DEBUG) { console.log(state.step, 'GFV[]'); }
+
+ stack.push(fv.x * 0x4000);
+ stack.push(fv.y * 0x4000);
+}
+
+// SFVTPV[] Set Freedom Vector To Projection Vector
+// 0x0E
+function SFVTPV(state) {
+ state.fv = state.pv;
+
+ if (exports.DEBUG) { console.log(state.step, 'SFVTPV[]'); }
+}
+
+// ISECT[] moves point p to the InterSECTion of two lines
+// 0x0F
+function ISECT(state)
+{
+ var stack = state.stack;
+ var pa0i = stack.pop();
+ var pa1i = stack.pop();
+ var pb0i = stack.pop();
+ var pb1i = stack.pop();
+ var pi = stack.pop();
+ var z0 = state.z0;
+ var z1 = state.z1;
+ var pa0 = z0[pa0i];
+ var pa1 = z0[pa1i];
+ var pb0 = z1[pb0i];
+ var pb1 = z1[pb1i];
+ var p = state.z2[pi];
+
+ if (exports.DEBUG) { console.log('ISECT[], ', pa0i, pa1i, pb0i, pb1i, pi); }
+
+ // math from
+ // en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line
+
+ var x1 = pa0.x;
+ var y1 = pa0.y;
+ var x2 = pa1.x;
+ var y2 = pa1.y;
+ var x3 = pb0.x;
+ var y3 = pb0.y;
+ var x4 = pb1.x;
+ var y4 = pb1.y;
+
+ var div = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
+ var f1 = x1 * y2 - y1 * x2;
+ var f2 = x3 * y4 - y3 * x4;
+
+ p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div;
+ p.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div;
+}
+
+// SRP0[] Set Reference Point 0
+// 0x10
+function SRP0(state) {
+ state.rp0 = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SRP0[]', state.rp0); }
+}
+
+// SRP1[] Set Reference Point 1
+// 0x11
+function SRP1(state) {
+ state.rp1 = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SRP1[]', state.rp1); }
+}
+
+// SRP1[] Set Reference Point 2
+// 0x12
+function SRP2(state) {
+ state.rp2 = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SRP2[]', state.rp2); }
+}
+
+// SZP0[] Set Zone Pointer 0
+// 0x13
+function SZP0(state) {
+ var n = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SZP0[]', n); }
+
+ state.zp0 = n;
+
+ switch (n) {
+ case 0:
+ if (!state.tZone) { initTZone(state); }
+ state.z0 = state.tZone;
+ break;
+ case 1 :
+ state.z0 = state.gZone;
+ break;
+ default :
+ throw new Error('Invalid zone pointer');
+ }
+}
+
+// SZP1[] Set Zone Pointer 1
+// 0x14
+function SZP1(state) {
+ var n = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SZP1[]', n); }
+
+ state.zp1 = n;
+
+ switch (n) {
+ case 0:
+ if (!state.tZone) { initTZone(state); }
+ state.z1 = state.tZone;
+ break;
+ case 1 :
+ state.z1 = state.gZone;
+ break;
+ default :
+ throw new Error('Invalid zone pointer');
+ }
+}
+
+// SZP2[] Set Zone Pointer 2
+// 0x15
+function SZP2(state) {
+ var n = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SZP2[]', n); }
+
+ state.zp2 = n;
+
+ switch (n) {
+ case 0:
+ if (!state.tZone) { initTZone(state); }
+ state.z2 = state.tZone;
+ break;
+ case 1 :
+ state.z2 = state.gZone;
+ break;
+ default :
+ throw new Error('Invalid zone pointer');
+ }
+}
+
+// SZPS[] Set Zone PointerS
+// 0x16
+function SZPS(state) {
+ var n = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SZPS[]', n); }
+
+ state.zp0 = state.zp1 = state.zp2 = n;
+
+ switch (n) {
+ case 0:
+ if (!state.tZone) { initTZone(state); }
+ state.z0 = state.z1 = state.z2 = state.tZone;
+ break;
+ case 1 :
+ state.z0 = state.z1 = state.z2 = state.gZone;
+ break;
+ default :
+ throw new Error('Invalid zone pointer');
+ }
+}
+
+// SLOOP[] Set LOOP variable
+// 0x17
+function SLOOP(state) {
+ state.loop = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SLOOP[]', state.loop); }
+}
+
+// RTG[] Round To Grid
+// 0x18
+function RTG(state) {
+ if (exports.DEBUG) { console.log(state.step, 'RTG[]'); }
+
+ state.round = roundToGrid;
+}
+
+// RTHG[] Round To Half Grid
+// 0x19
+function RTHG(state) {
+ if (exports.DEBUG) { console.log(state.step, 'RTHG[]'); }
+
+ state.round = roundToHalfGrid;
+}
+
+// SMD[] Set Minimum Distance
+// 0x1A
+function SMD(state) {
+ var d = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SMD[]', d); }
+
+ state.minDis = d / 0x40;
+}
+
+// ELSE[] ELSE clause
+// 0x1B
+function ELSE(state) {
+ // This instruction has been reached by executing a then branch
+ // so it just skips ahead until matching EIF.
+ //
+ // In case the IF was negative the IF[] instruction already
+ // skipped forward over the ELSE[]
+
+ if (exports.DEBUG) { console.log(state.step, 'ELSE[]'); }
+
+ skip(state, false);
+}
+
+// JMPR[] JuMP Relative
+// 0x1C
+function JMPR(state) {
+ var o = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'JMPR[]', o); }
+
+ // A jump by 1 would do nothing.
+ state.ip += o - 1;
+}
+
+// SCVTCI[] Set Control Value Table Cut-In
+// 0x1D
+function SCVTCI(state) {
+ var n = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SCVTCI[]', n); }
+
+ state.cvCutIn = n / 0x40;
+}
+
+// DUP[] DUPlicate top stack element
+// 0x20
+function DUP(state) {
+ var stack = state.stack;
+
+ if (exports.DEBUG) { console.log(state.step, 'DUP[]'); }
+
+ stack.push(stack[stack.length - 1]);
+}
+
+// POP[] POP top stack element
+// 0x21
+function POP(state) {
+ if (exports.DEBUG) { console.log(state.step, 'POP[]'); }
+
+ state.stack.pop();
+}
+
+// CLEAR[] CLEAR the stack
+// 0x22
+function CLEAR(state) {
+ if (exports.DEBUG) { console.log(state.step, 'CLEAR[]'); }
+
+ state.stack.length = 0;
+}
+
+// SWAP[] SWAP the top two elements on the stack
+// 0x23
+function SWAP(state) {
+ var stack = state.stack;
+
+ var a = stack.pop();
+ var b = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SWAP[]'); }
+
+ stack.push(a);
+ stack.push(b);
+}
+
+// DEPTH[] DEPTH of the stack
+// 0x24
+function DEPTH(state) {
+ var stack = state.stack;
+
+ if (exports.DEBUG) { console.log(state.step, 'DEPTH[]'); }
+
+ stack.push(stack.length);
+}
+
+// LOOPCALL[] LOOPCALL function
+// 0x2A
+function LOOPCALL(state) {
+ var stack = state.stack;
+ var fn = stack.pop();
+ var c = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'LOOPCALL[]', fn, c); }
+
+ // saves callers program
+ var cip = state.ip;
+ var cprog = state.prog;
+
+ state.prog = state.funcs[fn];
+
+ // executes the function
+ for (var i = 0; i < c; i++) {
+ exec(state);
+
+ if (exports.DEBUG) { console.log(
+ ++state.step,
+ i + 1 < c ? 'next loopcall' : 'done loopcall',
+ i
+ ); }
+ }
+
+ // restores the callers program
+ state.ip = cip;
+ state.prog = cprog;
+}
+
+// CALL[] CALL function
+// 0x2B
+function CALL(state) {
+ var fn = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'CALL[]', fn); }
+
+ // saves callers program
+ var cip = state.ip;
+ var cprog = state.prog;
+
+ state.prog = state.funcs[fn];
+
+ // executes the function
+ exec(state);
+
+ // restores the callers program
+ state.ip = cip;
+ state.prog = cprog;
+
+ if (exports.DEBUG) { console.log(++state.step, 'returning from', fn); }
+}
+
+// CINDEX[] Copy the INDEXed element to the top of the stack
+// 0x25
+function CINDEX(state) {
+ var stack = state.stack;
+ var k = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'CINDEX[]', k); }
+
+ // In case of k == 1, it copies the last element after popping
+ // thus stack.length - k.
+ stack.push(stack[stack.length - k]);
+}
+
+// MINDEX[] Move the INDEXed element to the top of the stack
+// 0x26
+function MINDEX(state) {
+ var stack = state.stack;
+ var k = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'MINDEX[]', k); }
+
+ stack.push(stack.splice(stack.length - k, 1)[0]);
+}
+
+// FDEF[] Function DEFinition
+// 0x2C
+function FDEF(state) {
+ if (state.env !== 'fpgm') { throw new Error('FDEF not allowed here'); }
+ var stack = state.stack;
+ var prog = state.prog;
+ var ip = state.ip;
+
+ var fn = stack.pop();
+ var ipBegin = ip;
+
+ if (exports.DEBUG) { console.log(state.step, 'FDEF[]', fn); }
+
+ while (prog[++ip] !== 0x2D){ }
+
+ state.ip = ip;
+ state.funcs[fn] = prog.slice(ipBegin + 1, ip);
+}
+
+// MDAP[a] Move Direct Absolute Point
+// 0x2E-0x2F
+function MDAP(round, state) {
+ var pi = state.stack.pop();
+ var p = state.z0[pi];
+ var fv = state.fv;
+ var pv = state.pv;
+
+ if (exports.DEBUG) { console.log(state.step, 'MDAP[' + round + ']', pi); }
+
+ var d = pv.distance(p, HPZero);
+
+ if (round) { d = state.round(d); }
+
+ fv.setRelative(p, HPZero, d, pv);
+ fv.touch(p);
+
+ state.rp0 = state.rp1 = pi;
+}
+
+// IUP[a] Interpolate Untouched Points through the outline
+// 0x30
+function IUP(v, state) {
+ var z2 = state.z2;
+ var pLen = z2.length - 2;
+ var cp;
+ var pp;
+ var np;
+
+ if (exports.DEBUG) { console.log(state.step, 'IUP[' + v.axis + ']'); }
+
+ for (var i = 0; i < pLen; i++) {
+ cp = z2[i]; // current point
+
+ // if this point has been touched go on
+ if (v.touched(cp)) { continue; }
+
+ pp = cp.prevTouched(v);
+
+ // no point on the contour has been touched?
+ if (pp === cp) { continue; }
+
+ np = cp.nextTouched(v);
+
+ if (pp === np) {
+ // only one point on the contour has been touched
+ // so simply moves the point like that
+
+ v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true);
+ }
+
+ v.interpolate(cp, pp, np, v);
+ }
+}
+
+// SHP[] SHift Point using reference point
+// 0x32-0x33
+function SHP(a, state) {
+ var stack = state.stack;
+ var rpi = a ? state.rp1 : state.rp2;
+ var rp = (a ? state.z0 : state.z1)[rpi];
+ var fv = state.fv;
+ var pv = state.pv;
+ var loop = state.loop;
+ var z2 = state.z2;
+
+ while (loop--)
+ {
+ var pi = stack.pop();
+ var p = z2[pi];
+
+ var d = pv.distance(rp, rp, false, true);
+ fv.setRelative(p, p, d, pv);
+ fv.touch(p);
+
+ if (exports.DEBUG) {
+ console.log(
+ state.step,
+ (state.loop > 1 ?
+ 'loop ' + (state.loop - loop) + ': ' :
+ ''
+ ) +
+ 'SHP[' + (a ? 'rp1' : 'rp2') + ']', pi
+ );
+ }
+ }
+
+ state.loop = 1;
+}
+
+// SHC[] SHift Contour using reference point
+// 0x36-0x37
+function SHC(a, state) {
+ var stack = state.stack;
+ var rpi = a ? state.rp1 : state.rp2;
+ var rp = (a ? state.z0 : state.z1)[rpi];
+ var fv = state.fv;
+ var pv = state.pv;
+ var ci = stack.pop();
+ var sp = state.z2[state.contours[ci]];
+ var p = sp;
+
+ if (exports.DEBUG) { console.log(state.step, 'SHC[' + a + ']', ci); }
+
+ var d = pv.distance(rp, rp, false, true);
+
+ do {
+ if (p !== rp) { fv.setRelative(p, p, d, pv); }
+ p = p.nextPointOnContour;
+ } while (p !== sp);
+}
+
+// SHZ[] SHift Zone using reference point
+// 0x36-0x37
+function SHZ(a, state) {
+ var stack = state.stack;
+ var rpi = a ? state.rp1 : state.rp2;
+ var rp = (a ? state.z0 : state.z1)[rpi];
+ var fv = state.fv;
+ var pv = state.pv;
+
+ var e = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SHZ[' + a + ']', e); }
+
+ var z;
+ switch (e) {
+ case 0 : z = state.tZone; break;
+ case 1 : z = state.gZone; break;
+ default : throw new Error('Invalid zone');
+ }
+
+ var p;
+ var d = pv.distance(rp, rp, false, true);
+ var pLen = z.length - 2;
+ for (var i = 0; i < pLen; i++)
+ {
+ p = z[i];
+ if (p !== rp) { fv.setRelative(p, p, d, pv); }
+ }
+}
+
+// SHPIX[] SHift point by a PIXel amount
+// 0x38
+function SHPIX(state) {
+ var stack = state.stack;
+ var loop = state.loop;
+ var fv = state.fv;
+ var d = stack.pop() / 0x40;
+ var z2 = state.z2;
+
+ while (loop--) {
+ var pi = stack.pop();
+ var p = z2[pi];
+
+ if (exports.DEBUG) {
+ console.log(
+ state.step,
+ (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') +
+ 'SHPIX[]', pi, d
+ );
+ }
+
+ fv.setRelative(p, p, d);
+ fv.touch(p);
+ }
+
+ state.loop = 1;
+}
+
+// IP[] Interpolate Point
+// 0x39
+function IP(state) {
+ var stack = state.stack;
+ var rp1i = state.rp1;
+ var rp2i = state.rp2;
+ var loop = state.loop;
+ var rp1 = state.z0[rp1i];
+ var rp2 = state.z1[rp2i];
+ var fv = state.fv;
+ var pv = state.dpv;
+ var z2 = state.z2;
+
+ while (loop--) {
+ var pi = stack.pop();
+ var p = z2[pi];
+
+ if (exports.DEBUG) {
+ console.log(
+ state.step,
+ (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') +
+ 'IP[]', pi, rp1i, '<->', rp2i
+ );
+ }
+
+ fv.interpolate(p, rp1, rp2, pv);
+
+ fv.touch(p);
+ }
+
+ state.loop = 1;
+}
+
+// MSIRP[a] Move Stack Indirect Relative Point
+// 0x3A-0x3B
+function MSIRP(a, state) {
+ var stack = state.stack;
+ var d = stack.pop() / 64;
+ var pi = stack.pop();
+ var p = state.z1[pi];
+ var rp0 = state.z0[state.rp0];
+ var fv = state.fv;
+ var pv = state.pv;
+
+ fv.setRelative(p, rp0, d, pv);
+ fv.touch(p);
+
+ if (exports.DEBUG) { console.log(state.step, 'MSIRP[' + a + ']', d, pi); }
+
+ state.rp1 = state.rp0;
+ state.rp2 = pi;
+ if (a) { state.rp0 = pi; }
+}
+
+// ALIGNRP[] Align to reference point.
+// 0x3C
+function ALIGNRP(state) {
+ var stack = state.stack;
+ var rp0i = state.rp0;
+ var rp0 = state.z0[rp0i];
+ var loop = state.loop;
+ var fv = state.fv;
+ var pv = state.pv;
+ var z1 = state.z1;
+
+ while (loop--) {
+ var pi = stack.pop();
+ var p = z1[pi];
+
+ if (exports.DEBUG) {
+ console.log(
+ state.step,
+ (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') +
+ 'ALIGNRP[]', pi
+ );
+ }
+
+ fv.setRelative(p, rp0, 0, pv);
+ fv.touch(p);
+ }
+
+ state.loop = 1;
+}
+
+// RTG[] Round To Double Grid
+// 0x3D
+function RTDG(state) {
+ if (exports.DEBUG) { console.log(state.step, 'RTDG[]'); }
+
+ state.round = roundToDoubleGrid;
+}
+
+// MIAP[a] Move Indirect Absolute Point
+// 0x3E-0x3F
+function MIAP(round, state) {
+ var stack = state.stack;
+ var n = stack.pop();
+ var pi = stack.pop();
+ var p = state.z0[pi];
+ var fv = state.fv;
+ var pv = state.pv;
+ var cv = state.cvt[n];
+
+ // TODO cvtcutin should be considered here
+ if (round) { cv = state.round(cv); }
+
+ if (exports.DEBUG) {
+ console.log(
+ state.step,
+ 'MIAP[' + round + ']',
+ n, '(', cv, ')', pi
+ );
+ }
+
+ fv.setRelative(p, HPZero, cv, pv);
+
+ if (state.zp0 === 0) {
+ p.xo = p.x;
+ p.yo = p.y;
+ }
+
+ fv.touch(p);
+
+ state.rp0 = state.rp1 = pi;
+}
+
+// NPUSB[] PUSH N Bytes
+// 0x40
+function NPUSHB(state) {
+ var prog = state.prog;
+ var ip = state.ip;
+ var stack = state.stack;
+
+ var n = prog[++ip];
+
+ if (exports.DEBUG) { console.log(state.step, 'NPUSHB[]', n); }
+
+ for (var i = 0; i < n; i++) { stack.push(prog[++ip]); }
+
+ state.ip = ip;
+}
+
+// NPUSHW[] PUSH N Words
+// 0x41
+function NPUSHW(state) {
+ var ip = state.ip;
+ var prog = state.prog;
+ var stack = state.stack;
+ var n = prog[++ip];
+
+ if (exports.DEBUG) { console.log(state.step, 'NPUSHW[]', n); }
+
+ for (var i = 0; i < n; i++) {
+ var w = (prog[++ip] << 8) | prog[++ip];
+ if (w & 0x8000) { w = -((w ^ 0xffff) + 1); }
+ stack.push(w);
+ }
+
+ state.ip = ip;
+}
+
+// WS[] Write Store
+// 0x42
+function WS(state) {
+ var stack = state.stack;
+ var store = state.store;
+
+ if (!store) { store = state.store = []; }
+
+ var v = stack.pop();
+ var l = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'WS', v, l); }
+
+ store[l] = v;
+}
+
+// RS[] Read Store
+// 0x43
+function RS(state) {
+ var stack = state.stack;
+ var store = state.store;
+
+ var l = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'RS', l); }
+
+ var v = (store && store[l]) || 0;
+
+ stack.push(v);
+}
+
+// WCVTP[] Write Control Value Table in Pixel units
+// 0x44
+function WCVTP(state) {
+ var stack = state.stack;
+
+ var v = stack.pop();
+ var l = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'WCVTP', v, l); }
+
+ state.cvt[l] = v / 0x40;
+}
+
+// RCVT[] Read Control Value Table entry
+// 0x45
+function RCVT(state) {
+ var stack = state.stack;
+ var cvte = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'RCVT', cvte); }
+
+ stack.push(state.cvt[cvte] * 0x40);
+}
+
+// GC[] Get Coordinate projected onto the projection vector
+// 0x46-0x47
+function GC(a, state) {
+ var stack = state.stack;
+ var pi = stack.pop();
+ var p = state.z2[pi];
+
+ if (exports.DEBUG) { console.log(state.step, 'GC[' + a + ']', pi); }
+
+ stack.push(state.dpv.distance(p, HPZero, a, false) * 0x40);
+}
+
+// MD[a] Measure Distance
+// 0x49-0x4A
+function MD(a, state) {
+ var stack = state.stack;
+ var pi2 = stack.pop();
+ var pi1 = stack.pop();
+ var p2 = state.z1[pi2];
+ var p1 = state.z0[pi1];
+ var d = state.dpv.distance(p1, p2, a, a);
+
+ if (exports.DEBUG) { console.log(state.step, 'MD[' + a + ']', pi2, pi1, '->', d); }
+
+ state.stack.push(Math.round(d * 64));
+}
+
+// MPPEM[] Measure Pixels Per EM
+// 0x4B
+function MPPEM(state) {
+ if (exports.DEBUG) { console.log(state.step, 'MPPEM[]'); }
+ state.stack.push(state.ppem);
+}
+
+// FLIPON[] set the auto FLIP Boolean to ON
+// 0x4D
+function FLIPON(state) {
+ if (exports.DEBUG) { console.log(state.step, 'FLIPON[]'); }
+ state.autoFlip = true;
+}
+
+// LT[] Less Than
+// 0x50
+function LT(state) {
+ var stack = state.stack;
+ var e2 = stack.pop();
+ var e1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'LT[]', e2, e1); }
+
+ stack.push(e1 < e2 ? 1 : 0);
+}
+
+// LTEQ[] Less Than or EQual
+// 0x53
+function LTEQ(state) {
+ var stack = state.stack;
+ var e2 = stack.pop();
+ var e1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'LTEQ[]', e2, e1); }
+
+ stack.push(e1 <= e2 ? 1 : 0);
+}
+
+// GTEQ[] Greater Than
+// 0x52
+function GT(state) {
+ var stack = state.stack;
+ var e2 = stack.pop();
+ var e1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'GT[]', e2, e1); }
+
+ stack.push(e1 > e2 ? 1 : 0);
+}
+
+// GTEQ[] Greater Than or EQual
+// 0x53
+function GTEQ(state) {
+ var stack = state.stack;
+ var e2 = stack.pop();
+ var e1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'GTEQ[]', e2, e1); }
+
+ stack.push(e1 >= e2 ? 1 : 0);
+}
+
+// EQ[] EQual
+// 0x54
+function EQ(state) {
+ var stack = state.stack;
+ var e2 = stack.pop();
+ var e1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'EQ[]', e2, e1); }
+
+ stack.push(e2 === e1 ? 1 : 0);
+}
+
+// NEQ[] Not EQual
+// 0x55
+function NEQ(state) {
+ var stack = state.stack;
+ var e2 = stack.pop();
+ var e1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'NEQ[]', e2, e1); }
+
+ stack.push(e2 !== e1 ? 1 : 0);
+}
+
+// ODD[] ODD
+// 0x56
+function ODD(state) {
+ var stack = state.stack;
+ var n = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'ODD[]', n); }
+
+ stack.push(Math.trunc(n) % 2 ? 1 : 0);
+}
+
+// EVEN[] EVEN
+// 0x57
+function EVEN(state) {
+ var stack = state.stack;
+ var n = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'EVEN[]', n); }
+
+ stack.push(Math.trunc(n) % 2 ? 0 : 1);
+}
+
+// IF[] IF test
+// 0x58
+function IF(state) {
+ var test = state.stack.pop();
+ var ins;
+
+ if (exports.DEBUG) { console.log(state.step, 'IF[]', test); }
+
+ // if test is true it just continues
+ // if not the ip is skipped until matching ELSE or EIF
+ if (!test) {
+ skip(state, true);
+
+ if (exports.DEBUG) { console.log(state.step, ins === 0x1B ? 'ELSE[]' : 'EIF[]'); }
+ }
+}
+
+// EIF[] End IF
+// 0x59
+function EIF(state) {
+ // this can be reached normally when
+ // executing an else branch.
+ // -> just ignore it
+
+ if (exports.DEBUG) { console.log(state.step, 'EIF[]'); }
+}
+
+// AND[] logical AND
+// 0x5A
+function AND(state) {
+ var stack = state.stack;
+ var e2 = stack.pop();
+ var e1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'AND[]', e2, e1); }
+
+ stack.push(e2 && e1 ? 1 : 0);
+}
+
+// OR[] logical OR
+// 0x5B
+function OR(state) {
+ var stack = state.stack;
+ var e2 = stack.pop();
+ var e1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'OR[]', e2, e1); }
+
+ stack.push(e2 || e1 ? 1 : 0);
+}
+
+// NOT[] logical NOT
+// 0x5C
+function NOT(state) {
+ var stack = state.stack;
+ var e = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'NOT[]', e); }
+
+ stack.push(e ? 0 : 1);
+}
+
+// DELTAP1[] DELTA exception P1
+// DELTAP2[] DELTA exception P2
+// DELTAP3[] DELTA exception P3
+// 0x5D, 0x71, 0x72
+function DELTAP123(b, state) {
+ var stack = state.stack;
+ var n = stack.pop();
+ var fv = state.fv;
+ var pv = state.pv;
+ var ppem = state.ppem;
+ var base = state.deltaBase + (b - 1) * 16;
+ var ds = state.deltaShift;
+ var z0 = state.z0;
+
+ if (exports.DEBUG) { console.log(state.step, 'DELTAP[' + b + ']', n, stack); }
+
+ for (var i = 0; i < n; i++)
+ {
+ var pi = stack.pop();
+ var arg = stack.pop();
+ var appem = base + ((arg & 0xF0) >> 4);
+ if (appem !== ppem) { continue; }
+
+ var mag = (arg & 0x0F) - 8;
+ if (mag >= 0) { mag++; }
+ if (exports.DEBUG) { console.log(state.step, 'DELTAPFIX', pi, 'by', mag * ds); }
+
+ var p = z0[pi];
+ fv.setRelative(p, p, mag * ds, pv);
+ }
+}
+
+// SDB[] Set Delta Base in the graphics state
+// 0x5E
+function SDB(state) {
+ var stack = state.stack;
+ var n = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SDB[]', n); }
+
+ state.deltaBase = n;
+}
+
+// SDS[] Set Delta Shift in the graphics state
+// 0x5F
+function SDS(state) {
+ var stack = state.stack;
+ var n = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SDS[]', n); }
+
+ state.deltaShift = Math.pow(0.5, n);
+}
+
+// ADD[] ADD
+// 0x60
+function ADD(state) {
+ var stack = state.stack;
+ var n2 = stack.pop();
+ var n1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'ADD[]', n2, n1); }
+
+ stack.push(n1 + n2);
+}
+
+// SUB[] SUB
+// 0x61
+function SUB(state) {
+ var stack = state.stack;
+ var n2 = stack.pop();
+ var n1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SUB[]', n2, n1); }
+
+ stack.push(n1 - n2);
+}
+
+// DIV[] DIV
+// 0x62
+function DIV(state) {
+ var stack = state.stack;
+ var n2 = stack.pop();
+ var n1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'DIV[]', n2, n1); }
+
+ stack.push(n1 * 64 / n2);
+}
+
+// MUL[] MUL
+// 0x63
+function MUL(state) {
+ var stack = state.stack;
+ var n2 = stack.pop();
+ var n1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'MUL[]', n2, n1); }
+
+ stack.push(n1 * n2 / 64);
+}
+
+// ABS[] ABSolute value
+// 0x64
+function ABS(state) {
+ var stack = state.stack;
+ var n = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'ABS[]', n); }
+
+ stack.push(Math.abs(n));
+}
+
+// NEG[] NEGate
+// 0x65
+function NEG(state) {
+ var stack = state.stack;
+ var n = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'NEG[]', n); }
+
+ stack.push(-n);
+}
+
+// FLOOR[] FLOOR
+// 0x66
+function FLOOR(state) {
+ var stack = state.stack;
+ var n = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'FLOOR[]', n); }
+
+ stack.push(Math.floor(n / 0x40) * 0x40);
+}
+
+// CEILING[] CEILING
+// 0x67
+function CEILING(state) {
+ var stack = state.stack;
+ var n = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'CEILING[]', n); }
+
+ stack.push(Math.ceil(n / 0x40) * 0x40);
+}
+
+// ROUND[ab] ROUND value
+// 0x68-0x6B
+function ROUND(dt, state) {
+ var stack = state.stack;
+ var n = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'ROUND[]'); }
+
+ stack.push(state.round(n / 0x40) * 0x40);
+}
+
+// WCVTF[] Write Control Value Table in Funits
+// 0x70
+function WCVTF(state) {
+ var stack = state.stack;
+ var v = stack.pop();
+ var l = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'WCVTF[]', v, l); }
+
+ state.cvt[l] = v * state.ppem / state.font.unitsPerEm;
+}
+
+// DELTAC1[] DELTA exception C1
+// DELTAC2[] DELTA exception C2
+// DELTAC3[] DELTA exception C3
+// 0x73, 0x74, 0x75
+function DELTAC123(b, state) {
+ var stack = state.stack;
+ var n = stack.pop();
+ var ppem = state.ppem;
+ var base = state.deltaBase + (b - 1) * 16;
+ var ds = state.deltaShift;
+
+ if (exports.DEBUG) { console.log(state.step, 'DELTAC[' + b + ']', n, stack); }
+
+ for (var i = 0; i < n; i++) {
+ var c = stack.pop();
+ var arg = stack.pop();
+ var appem = base + ((arg & 0xF0) >> 4);
+ if (appem !== ppem) { continue; }
+
+ var mag = (arg & 0x0F) - 8;
+ if (mag >= 0) { mag++; }
+
+ var delta = mag * ds;
+
+ if (exports.DEBUG) { console.log(state.step, 'DELTACFIX', c, 'by', delta); }
+
+ state.cvt[c] += delta;
+ }
+}
+
+// SROUND[] Super ROUND
+// 0x76
+function SROUND(state) {
+ var n = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'SROUND[]', n); }
+
+ state.round = roundSuper;
+
+ var period;
+
+ switch (n & 0xC0) {
+ case 0x00:
+ period = 0.5;
+ break;
+ case 0x40:
+ period = 1;
+ break;
+ case 0x80:
+ period = 2;
+ break;
+ default:
+ throw new Error('invalid SROUND value');
+ }
+
+ state.srPeriod = period;
+
+ switch (n & 0x30) {
+ case 0x00:
+ state.srPhase = 0;
+ break;
+ case 0x10:
+ state.srPhase = 0.25 * period;
+ break;
+ case 0x20:
+ state.srPhase = 0.5 * period;
+ break;
+ case 0x30:
+ state.srPhase = 0.75 * period;
+ break;
+ default: throw new Error('invalid SROUND value');
+ }
+
+ n &= 0x0F;
+
+ if (n === 0) { state.srThreshold = 0; }
+ else { state.srThreshold = (n / 8 - 0.5) * period; }
+}
+
+// S45ROUND[] Super ROUND 45 degrees
+// 0x77
+function S45ROUND(state) {
+ var n = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'S45ROUND[]', n); }
+
+ state.round = roundSuper;
+
+ var period;
+
+ switch (n & 0xC0) {
+ case 0x00:
+ period = Math.sqrt(2) / 2;
+ break;
+ case 0x40:
+ period = Math.sqrt(2);
+ break;
+ case 0x80:
+ period = 2 * Math.sqrt(2);
+ break;
+ default:
+ throw new Error('invalid S45ROUND value');
+ }
+
+ state.srPeriod = period;
+
+ switch (n & 0x30) {
+ case 0x00:
+ state.srPhase = 0;
+ break;
+ case 0x10:
+ state.srPhase = 0.25 * period;
+ break;
+ case 0x20:
+ state.srPhase = 0.5 * period;
+ break;
+ case 0x30:
+ state.srPhase = 0.75 * period;
+ break;
+ default:
+ throw new Error('invalid S45ROUND value');
+ }
+
+ n &= 0x0F;
+
+ if (n === 0) { state.srThreshold = 0; }
+ else { state.srThreshold = (n / 8 - 0.5) * period; }
+}
+
+// ROFF[] Round Off
+// 0x7A
+function ROFF(state) {
+ if (exports.DEBUG) { console.log(state.step, 'ROFF[]'); }
+
+ state.round = roundOff;
+}
+
+// RUTG[] Round Up To Grid
+// 0x7C
+function RUTG(state) {
+ if (exports.DEBUG) { console.log(state.step, 'RUTG[]'); }
+
+ state.round = roundUpToGrid;
+}
+
+// RDTG[] Round Down To Grid
+// 0x7D
+function RDTG(state) {
+ if (exports.DEBUG) { console.log(state.step, 'RDTG[]'); }
+
+ state.round = roundDownToGrid;
+}
+
+// SCANCTRL[] SCAN conversion ConTRoL
+// 0x85
+function SCANCTRL(state) {
+ var n = state.stack.pop();
+
+ // ignored by opentype.js
+
+ if (exports.DEBUG) { console.log(state.step, 'SCANCTRL[]', n); }
+}
+
+// SDPVTL[a] Set Dual Projection Vector To Line
+// 0x86-0x87
+function SDPVTL(a, state) {
+ var stack = state.stack;
+ var p2i = stack.pop();
+ var p1i = stack.pop();
+ var p2 = state.z2[p2i];
+ var p1 = state.z1[p1i];
+
+ if (exports.DEBUG) { console.log('SDPVTL[' + a + ']', p2i, p1i); }
+
+ var dx;
+ var dy;
+
+ if (!a) {
+ dx = p1.x - p2.x;
+ dy = p1.y - p2.y;
+ } else {
+ dx = p2.y - p1.y;
+ dy = p1.x - p2.x;
+ }
+
+ state.dpv = getUnitVector(dx, dy);
+}
+
+// GETINFO[] GET INFOrmation
+// 0x88
+function GETINFO(state) {
+ var stack = state.stack;
+ var sel = stack.pop();
+ var r = 0;
+
+ if (exports.DEBUG) { console.log(state.step, 'GETINFO[]', sel); }
+
+ // v35 as in no subpixel hinting
+ if (sel & 0x01) { r = 35; }
+
+ // TODO rotation and stretch currently not supported
+ // and thus those GETINFO are always 0.
+
+ // opentype.js is always gray scaling
+ if (sel & 0x20) { r |= 0x1000; }
+
+ stack.push(r);
+}
+
+// ROLL[] ROLL the top three stack elements
+// 0x8A
+function ROLL(state) {
+ var stack = state.stack;
+ var a = stack.pop();
+ var b = stack.pop();
+ var c = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'ROLL[]'); }
+
+ stack.push(b);
+ stack.push(a);
+ stack.push(c);
+}
+
+// MAX[] MAXimum of top two stack elements
+// 0x8B
+function MAX(state) {
+ var stack = state.stack;
+ var e2 = stack.pop();
+ var e1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'MAX[]', e2, e1); }
+
+ stack.push(Math.max(e1, e2));
+}
+
+// MIN[] MINimum of top two stack elements
+// 0x8C
+function MIN(state) {
+ var stack = state.stack;
+ var e2 = stack.pop();
+ var e1 = stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'MIN[]', e2, e1); }
+
+ stack.push(Math.min(e1, e2));
+}
+
+// SCANTYPE[] SCANTYPE
+// 0x8D
+function SCANTYPE(state) {
+ var n = state.stack.pop();
+ // ignored by opentype.js
+ if (exports.DEBUG) { console.log(state.step, 'SCANTYPE[]', n); }
+}
+
+// INSTCTRL[] INSTCTRL
+// 0x8D
+function INSTCTRL(state) {
+ var s = state.stack.pop();
+ var v = state.stack.pop();
+
+ if (exports.DEBUG) { console.log(state.step, 'INSTCTRL[]', s, v); }
+
+ switch (s) {
+ case 1 : state.inhibitGridFit = !!v; return;
+ case 2 : state.ignoreCvt = !!v; return;
+ default: throw new Error('invalid INSTCTRL[] selector');
+ }
+}
+
+// PUSHB[abc] PUSH Bytes
+// 0xB0-0xB7
+function PUSHB(n, state) {
+ var stack = state.stack;
+ var prog = state.prog;
+ var ip = state.ip;
+
+ if (exports.DEBUG) { console.log(state.step, 'PUSHB[' + n + ']'); }
+
+ for (var i = 0; i < n; i++) { stack.push(prog[++ip]); }
+
+ state.ip = ip;
+}
+
+// PUSHW[abc] PUSH Words
+// 0xB8-0xBF
+function PUSHW(n, state) {
+ var ip = state.ip;
+ var prog = state.prog;
+ var stack = state.stack;
+
+ if (exports.DEBUG) { console.log(state.ip, 'PUSHW[' + n + ']'); }
+
+ for (var i = 0; i < n; i++) {
+ var w = (prog[++ip] << 8) | prog[++ip];
+ if (w & 0x8000) { w = -((w ^ 0xffff) + 1); }
+ stack.push(w);
+ }
+
+ state.ip = ip;
+}
+
+// MDRP[abcde] Move Direct Relative Point
+// 0xD0-0xEF
+// (if indirect is 0)
+//
+// and
+//
+// MIRP[abcde] Move Indirect Relative Point
+// 0xE0-0xFF
+// (if indirect is 1)
+
+function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) {
+ var stack = state.stack;
+ var cvte = indirect && stack.pop();
+ var pi = stack.pop();
+ var rp0i = state.rp0;
+ var rp = state.z0[rp0i];
+ var p = state.z1[pi];
+
+ var md = state.minDis;
+ var fv = state.fv;
+ var pv = state.dpv;
+ var od; // original distance
+ var d; // moving distance
+ var sign; // sign of distance
+ var cv;
+
+ d = od = pv.distance(p, rp, true, true);
+ sign = d >= 0 ? 1 : -1; // Math.sign would be 0 in case of 0
+
+ // TODO consider autoFlip
+ d = Math.abs(d);
+
+ if (indirect) {
+ cv = state.cvt[cvte];
+
+ if (ro && Math.abs(d - cv) < state.cvCutIn) { d = cv; }
+ }
+
+ if (keepD && d < md) { d = md; }
+
+ if (ro) { d = state.round(d); }
+
+ fv.setRelative(p, rp, sign * d, pv);
+ fv.touch(p);
+
+ if (exports.DEBUG) {
+ console.log(
+ state.step,
+ (indirect ? 'MIRP[' : 'MDRP[') +
+ (setRp0 ? 'M' : 'm') +
+ (keepD ? '>' : '_') +
+ (ro ? 'R' : '_') +
+ (dt === 0 ? 'Gr' : (dt === 1 ? 'Bl' : (dt === 2 ? 'Wh' : ''))) +
+ ']',
+ indirect ?
+ cvte + '(' + state.cvt[cvte] + ',' + cv + ')' :
+ '',
+ pi,
+ '(d =', od, '->', sign * d, ')'
+ );
+ }
+
+ state.rp1 = state.rp0;
+ state.rp2 = pi;
+ if (setRp0) { state.rp0 = pi; }
+}
+
+/*
+* The instruction table.
+*/
+instructionTable = [
+ /* 0x00 */ SVTCA.bind(undefined, yUnitVector),
+ /* 0x01 */ SVTCA.bind(undefined, xUnitVector),
+ /* 0x02 */ SPVTCA.bind(undefined, yUnitVector),
+ /* 0x03 */ SPVTCA.bind(undefined, xUnitVector),
+ /* 0x04 */ SFVTCA.bind(undefined, yUnitVector),
+ /* 0x05 */ SFVTCA.bind(undefined, xUnitVector),
+ /* 0x06 */ SPVTL.bind(undefined, 0),
+ /* 0x07 */ SPVTL.bind(undefined, 1),
+ /* 0x08 */ SFVTL.bind(undefined, 0),
+ /* 0x09 */ SFVTL.bind(undefined, 1),
+ /* 0x0A */ SPVFS,
+ /* 0x0B */ SFVFS,
+ /* 0x0C */ GPV,
+ /* 0x0D */ GFV,
+ /* 0x0E */ SFVTPV,
+ /* 0x0F */ ISECT,
+ /* 0x10 */ SRP0,
+ /* 0x11 */ SRP1,
+ /* 0x12 */ SRP2,
+ /* 0x13 */ SZP0,
+ /* 0x14 */ SZP1,
+ /* 0x15 */ SZP2,
+ /* 0x16 */ SZPS,
+ /* 0x17 */ SLOOP,
+ /* 0x18 */ RTG,
+ /* 0x19 */ RTHG,
+ /* 0x1A */ SMD,
+ /* 0x1B */ ELSE,
+ /* 0x1C */ JMPR,
+ /* 0x1D */ SCVTCI,
+ /* 0x1E */ undefined, // TODO SSWCI
+ /* 0x1F */ undefined, // TODO SSW
+ /* 0x20 */ DUP,
+ /* 0x21 */ POP,
+ /* 0x22 */ CLEAR,
+ /* 0x23 */ SWAP,
+ /* 0x24 */ DEPTH,
+ /* 0x25 */ CINDEX,
+ /* 0x26 */ MINDEX,
+ /* 0x27 */ undefined, // TODO ALIGNPTS
+ /* 0x28 */ undefined,
+ /* 0x29 */ undefined, // TODO UTP
+ /* 0x2A */ LOOPCALL,
+ /* 0x2B */ CALL,
+ /* 0x2C */ FDEF,
+ /* 0x2D */ undefined, // ENDF (eaten by FDEF)
+ /* 0x2E */ MDAP.bind(undefined, 0),
+ /* 0x2F */ MDAP.bind(undefined, 1),
+ /* 0x30 */ IUP.bind(undefined, yUnitVector),
+ /* 0x31 */ IUP.bind(undefined, xUnitVector),
+ /* 0x32 */ SHP.bind(undefined, 0),
+ /* 0x33 */ SHP.bind(undefined, 1),
+ /* 0x34 */ SHC.bind(undefined, 0),
+ /* 0x35 */ SHC.bind(undefined, 1),
+ /* 0x36 */ SHZ.bind(undefined, 0),
+ /* 0x37 */ SHZ.bind(undefined, 1),
+ /* 0x38 */ SHPIX,
+ /* 0x39 */ IP,
+ /* 0x3A */ MSIRP.bind(undefined, 0),
+ /* 0x3B */ MSIRP.bind(undefined, 1),
+ /* 0x3C */ ALIGNRP,
+ /* 0x3D */ RTDG,
+ /* 0x3E */ MIAP.bind(undefined, 0),
+ /* 0x3F */ MIAP.bind(undefined, 1),
+ /* 0x40 */ NPUSHB,
+ /* 0x41 */ NPUSHW,
+ /* 0x42 */ WS,
+ /* 0x43 */ RS,
+ /* 0x44 */ WCVTP,
+ /* 0x45 */ RCVT,
+ /* 0x46 */ GC.bind(undefined, 0),
+ /* 0x47 */ GC.bind(undefined, 1),
+ /* 0x48 */ undefined, // TODO SCFS
+ /* 0x49 */ MD.bind(undefined, 0),
+ /* 0x4A */ MD.bind(undefined, 1),
+ /* 0x4B */ MPPEM,
+ /* 0x4C */ undefined, // TODO MPS
+ /* 0x4D */ FLIPON,
+ /* 0x4E */ undefined, // TODO FLIPOFF
+ /* 0x4F */ undefined, // TODO DEBUG
+ /* 0x50 */ LT,
+ /* 0x51 */ LTEQ,
+ /* 0x52 */ GT,
+ /* 0x53 */ GTEQ,
+ /* 0x54 */ EQ,
+ /* 0x55 */ NEQ,
+ /* 0x56 */ ODD,
+ /* 0x57 */ EVEN,
+ /* 0x58 */ IF,
+ /* 0x59 */ EIF,
+ /* 0x5A */ AND,
+ /* 0x5B */ OR,
+ /* 0x5C */ NOT,
+ /* 0x5D */ DELTAP123.bind(undefined, 1),
+ /* 0x5E */ SDB,
+ /* 0x5F */ SDS,
+ /* 0x60 */ ADD,
+ /* 0x61 */ SUB,
+ /* 0x62 */ DIV,
+ /* 0x63 */ MUL,
+ /* 0x64 */ ABS,
+ /* 0x65 */ NEG,
+ /* 0x66 */ FLOOR,
+ /* 0x67 */ CEILING,
+ /* 0x68 */ ROUND.bind(undefined, 0),
+ /* 0x69 */ ROUND.bind(undefined, 1),
+ /* 0x6A */ ROUND.bind(undefined, 2),
+ /* 0x6B */ ROUND.bind(undefined, 3),
+ /* 0x6C */ undefined, // TODO NROUND[ab]
+ /* 0x6D */ undefined, // TODO NROUND[ab]
+ /* 0x6E */ undefined, // TODO NROUND[ab]
+ /* 0x6F */ undefined, // TODO NROUND[ab]
+ /* 0x70 */ WCVTF,
+ /* 0x71 */ DELTAP123.bind(undefined, 2),
+ /* 0x72 */ DELTAP123.bind(undefined, 3),
+ /* 0x73 */ DELTAC123.bind(undefined, 1),
+ /* 0x74 */ DELTAC123.bind(undefined, 2),
+ /* 0x75 */ DELTAC123.bind(undefined, 3),
+ /* 0x76 */ SROUND,
+ /* 0x77 */ S45ROUND,
+ /* 0x78 */ undefined, // TODO JROT[]
+ /* 0x79 */ undefined, // TODO JROF[]
+ /* 0x7A */ ROFF,
+ /* 0x7B */ undefined,
+ /* 0x7C */ RUTG,
+ /* 0x7D */ RDTG,
+ /* 0x7E */ POP, // actually SANGW, supposed to do only a pop though
+ /* 0x7F */ POP, // actually AA, supposed to do only a pop though
+ /* 0x80 */ undefined, // TODO FLIPPT
+ /* 0x81 */ undefined, // TODO FLIPRGON
+ /* 0x82 */ undefined, // TODO FLIPRGOFF
+ /* 0x83 */ undefined,
+ /* 0x84 */ undefined,
+ /* 0x85 */ SCANCTRL,
+ /* 0x86 */ SDPVTL.bind(undefined, 0),
+ /* 0x87 */ SDPVTL.bind(undefined, 1),
+ /* 0x88 */ GETINFO,
+ /* 0x89 */ undefined, // TODO IDEF
+ /* 0x8A */ ROLL,
+ /* 0x8B */ MAX,
+ /* 0x8C */ MIN,
+ /* 0x8D */ SCANTYPE,
+ /* 0x8E */ INSTCTRL,
+ /* 0x8F */ undefined,
+ /* 0x90 */ undefined,
+ /* 0x91 */ undefined,
+ /* 0x92 */ undefined,
+ /* 0x93 */ undefined,
+ /* 0x94 */ undefined,
+ /* 0x95 */ undefined,
+ /* 0x96 */ undefined,
+ /* 0x97 */ undefined,
+ /* 0x98 */ undefined,
+ /* 0x99 */ undefined,
+ /* 0x9A */ undefined,
+ /* 0x9B */ undefined,
+ /* 0x9C */ undefined,
+ /* 0x9D */ undefined,
+ /* 0x9E */ undefined,
+ /* 0x9F */ undefined,
+ /* 0xA0 */ undefined,
+ /* 0xA1 */ undefined,
+ /* 0xA2 */ undefined,
+ /* 0xA3 */ undefined,
+ /* 0xA4 */ undefined,
+ /* 0xA5 */ undefined,
+ /* 0xA6 */ undefined,
+ /* 0xA7 */ undefined,
+ /* 0xA8 */ undefined,
+ /* 0xA9 */ undefined,
+ /* 0xAA */ undefined,
+ /* 0xAB */ undefined,
+ /* 0xAC */ undefined,
+ /* 0xAD */ undefined,
+ /* 0xAE */ undefined,
+ /* 0xAF */ undefined,
+ /* 0xB0 */ PUSHB.bind(undefined, 1),
+ /* 0xB1 */ PUSHB.bind(undefined, 2),
+ /* 0xB2 */ PUSHB.bind(undefined, 3),
+ /* 0xB3 */ PUSHB.bind(undefined, 4),
+ /* 0xB4 */ PUSHB.bind(undefined, 5),
+ /* 0xB5 */ PUSHB.bind(undefined, 6),
+ /* 0xB6 */ PUSHB.bind(undefined, 7),
+ /* 0xB7 */ PUSHB.bind(undefined, 8),
+ /* 0xB8 */ PUSHW.bind(undefined, 1),
+ /* 0xB9 */ PUSHW.bind(undefined, 2),
+ /* 0xBA */ PUSHW.bind(undefined, 3),
+ /* 0xBB */ PUSHW.bind(undefined, 4),
+ /* 0xBC */ PUSHW.bind(undefined, 5),
+ /* 0xBD */ PUSHW.bind(undefined, 6),
+ /* 0xBE */ PUSHW.bind(undefined, 7),
+ /* 0xBF */ PUSHW.bind(undefined, 8),
+ /* 0xC0 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 0),
+ /* 0xC1 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 1),
+ /* 0xC2 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 2),
+ /* 0xC3 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 3),
+ /* 0xC4 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 0),
+ /* 0xC5 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 1),
+ /* 0xC6 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 2),
+ /* 0xC7 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 3),
+ /* 0xC8 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 0),
+ /* 0xC9 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 1),
+ /* 0xCA */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 2),
+ /* 0xCB */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 3),
+ /* 0xCC */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 0),
+ /* 0xCD */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 1),
+ /* 0xCE */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 2),
+ /* 0xCF */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 3),
+ /* 0xD0 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 0),
+ /* 0xD1 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 1),
+ /* 0xD2 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 2),
+ /* 0xD3 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 3),
+ /* 0xD4 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 0),
+ /* 0xD5 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 1),
+ /* 0xD6 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 2),
+ /* 0xD7 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 3),
+ /* 0xD8 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 0),
+ /* 0xD9 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 1),
+ /* 0xDA */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 2),
+ /* 0xDB */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 3),
+ /* 0xDC */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 0),
+ /* 0xDD */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 1),
+ /* 0xDE */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 2),
+ /* 0xDF */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 3),
+ /* 0xE0 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 0),
+ /* 0xE1 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 1),
+ /* 0xE2 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 2),
+ /* 0xE3 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 3),
+ /* 0xE4 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 0),
+ /* 0xE5 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 1),
+ /* 0xE6 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 2),
+ /* 0xE7 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 3),
+ /* 0xE8 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 0),
+ /* 0xE9 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 1),
+ /* 0xEA */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 2),
+ /* 0xEB */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 3),
+ /* 0xEC */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 0),
+ /* 0xED */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 1),
+ /* 0xEE */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 2),
+ /* 0xEF */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 3),
+ /* 0xF0 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 0),
+ /* 0xF1 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 1),
+ /* 0xF2 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 2),
+ /* 0xF3 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 3),
+ /* 0xF4 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 0),
+ /* 0xF5 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 1),
+ /* 0xF6 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 2),
+ /* 0xF7 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 3),
+ /* 0xF8 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 0),
+ /* 0xF9 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 1),
+ /* 0xFA */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 2),
+ /* 0xFB */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 3),
+ /* 0xFC */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 0),
+ /* 0xFD */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 1),
+ /* 0xFE */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 2),
+ /* 0xFF */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 3)
+];
+
+
+
+/*****************************
+ Mathematical Considerations
+******************************
+
+fv ... refers to freedom vector
+pv ... refers to projection vector
+rp ... refers to reference point
+p ... refers to to point being operated on
+d ... refers to distance
+
+SETRELATIVE:
+============
+
+case freedom vector == x-axis:
+------------------------------
+
+ (pv)
+ .-'
+ rpd .-'
+ .-*
+ d .-'90°'
+ .-' '
+ .-' '
+ *-' ' b
+ rp '
+ '
+ '
+ p *----------*-------------- (fv)
+ pm
+
+ rpdx = rpx + d * pv.x
+ rpdy = rpy + d * pv.y
+
+ equation of line b
+
+ y - rpdy = pvns * (x- rpdx)
+
+ y = p.y
+
+ x = rpdx + ( p.y - rpdy ) / pvns
+
+
+case freedom vector == y-axis:
+------------------------------
+
+ * pm
+ |\
+ | \
+ | \
+ | \
+ | \
+ | \
+ | \
+ | \
+ | \
+ | \ b
+ | \
+ | \
+ | \ .-' (pv)
+ | 90° \.-'
+ | .-'* rpd
+ | .-'
+ * *-' d
+ p rp
+
+ rpdx = rpx + d * pv.x
+ rpdy = rpy + d * pv.y
+
+ equation of line b:
+ pvns ... normal slope to pv
+
+ y - rpdy = pvns * (x - rpdx)
+
+ x = p.x
+
+ y = rpdy + pvns * (p.x - rpdx)
+
+
+
+generic case:
+-------------
+
+
+ .'(fv)
+ .'
+ .* pm
+ .' !
+ .' .
+ .' !
+ .' . b
+ .' !
+ * .
+ p !
+ 90° . ... (pv)
+ ...-*-'''
+ ...---''' rpd
+ ...---''' d
+ *--'''
+ rp
+
+ rpdx = rpx + d * pv.x
+ rpdy = rpy + d * pv.y
+
+ equation of line b:
+ pvns... normal slope to pv
+
+ y - rpdy = pvns * (x - rpdx)
+
+ equation of freedom vector line:
+ fvs ... slope of freedom vector (=fy/fx)
+
+ y - py = fvs * (x - px)
+
+
+ on pm both equations are true for same x/y
+
+ y - rpdy = pvns * (x - rpdx)
+
+ y - py = fvs * (x - px)
+
+ form to y and set equal:
+
+ pvns * (x - rpdx) + rpdy = fvs * (x - px) + py
+
+ expand:
+
+ pvns * x - pvns * rpdx + rpdy = fvs * x - fvs * px + py
+
+ switch:
+
+ fvs * x - fvs * px + py = pvns * x - pvns * rpdx + rpdy
+
+ solve for x:
+
+ fvs * x - pvns * x = fvs * px - pvns * rpdx - py + rpdy
+
+
+
+ fvs * px - pvns * rpdx + rpdy - py
+ x = -----------------------------------
+ fvs - pvns
+
+ and:
+
+ y = fvs * (x - px) + py
+
+
+
+INTERPOLATE:
+============
+
+Examples of point interpolation.
+
+The weight of the movement of the reference point gets bigger
+the further the other reference point is away, thus the safest
+option (that is avoiding 0/0 divisions) is to weight the
+original distance of the other point by the sum of both distances.
+
+If the sum of both distances is 0, then move the point by the
+arithmetic average of the movement of both reference points.
+
+
+
+
+ (+6)
+ rp1o *---->*rp1
+ . . (+12)
+ . . rp2o *---------->* rp2
+ . . . .
+ . . . .
+ . 10 20 . .
+ |.........|...................| .
+ . . .
+ . . (+8) .
+ po *------>*p .
+ . . .
+ . 12 . 24 .
+ |...........|.......................|
+ 36
+
+
+-------
+
+
+
+ (+10)
+ rp1o *-------->*rp1
+ . . (-10)
+ . . rp2 *<---------* rpo2
+ . . . .
+ . . . .
+ . 10 . 30 . .
+ |.........|.............................|
+ . .
+ . (+5) .
+ po *--->* p .
+ . . .
+ . . 20 .
+ |....|..............|
+ 5 15
+
+
+-------
+
+
+ (+10)
+ rp1o *-------->*rp1
+ . .
+ . .
+ rp2o *-------->*rp2
+
+
+ (+10)
+ po *-------->* p
+
+-------
+
+
+ (+10)
+ rp1o *-------->*rp1
+ . .
+ . .(+30)
+ rp2o *---------------------------->*rp2
+
+
+ (+25)
+ po *----------------------->* p
+
+
+
+vim: set ts=4 sw=4 expandtab:
+*****/
+
+// The Font object
+
+/**
+ * @typedef FontOptions
+ * @type Object
+ * @property {Boolean} empty - whether to create a new empty font
+ * @property {string} familyName
+ * @property {string} styleName
+ * @property {string=} fullName
+ * @property {string=} postScriptName
+ * @property {string=} designer
+ * @property {string=} designerURL
+ * @property {string=} manufacturer
+ * @property {string=} manufacturerURL
+ * @property {string=} license
+ * @property {string=} licenseURL
+ * @property {string=} version
+ * @property {string=} description
+ * @property {string=} copyright
+ * @property {string=} trademark
+ * @property {Number} unitsPerEm
+ * @property {Number} ascender
+ * @property {Number} descender
+ * @property {Number} createdTimestamp
+ * @property {string=} weightClass
+ * @property {string=} widthClass
+ * @property {string=} fsSelection
+ */
+
+/**
+ * A Font represents a loaded OpenType font file.
+ * It contains a set of glyphs and methods to draw text on a drawing context,
+ * or to get a path representing the text.
+ * @exports opentype.Font
+ * @class
+ * @param {FontOptions}
+ * @constructor
+ */
+function Font(options) {
+ options = options || {};
+
+ if (!options.empty) {
+ // Check that we've provided the minimum set of names.
+ checkArgument(options.familyName, 'When creating a new Font object, familyName is required.');
+ checkArgument(options.styleName, 'When creating a new Font object, styleName is required.');
+ checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.');
+ checkArgument(options.ascender, 'When creating a new Font object, ascender is required.');
+ checkArgument(options.descender, 'When creating a new Font object, descender is required.');
+ checkArgument(options.descender < 0, 'Descender should be negative (e.g. -512).');
+
+ // OS X will complain if the names are empty, so we put a single space everywhere by default.
+ this.names = {
+ fontFamily: {en: options.familyName || ' '},
+ fontSubfamily: {en: options.styleName || ' '},
+ fullName: {en: options.fullName || options.familyName + ' ' + options.styleName},
+ postScriptName: {en: options.postScriptName || options.familyName + options.styleName},
+ designer: {en: options.designer || ' '},
+ designerURL: {en: options.designerURL || ' '},
+ manufacturer: {en: options.manufacturer || ' '},
+ manufacturerURL: {en: options.manufacturerURL || ' '},
+ license: {en: options.license || ' '},
+ licenseURL: {en: options.licenseURL || ' '},
+ version: {en: options.version || 'Version 0.1'},
+ description: {en: options.description || ' '},
+ copyright: {en: options.copyright || ' '},
+ trademark: {en: options.trademark || ' '}
+ };
+ this.unitsPerEm = options.unitsPerEm || 1000;
+ this.ascender = options.ascender;
+ this.descender = options.descender;
+ this.createdTimestamp = options.createdTimestamp;
+ this.tables = { os2: {
+ usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM,
+ usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM,
+ fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR
+ } };
+ }
+
+ this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported.
+ this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []);
+ this.encoding = new DefaultEncoding(this);
+ this.substitution = new Substitution(this);
+ this.tables = this.tables || {};
+
+ Object.defineProperty(this, 'hinting', {
+ get: function() {
+ if (this._hinting) { return this._hinting; }
+ if (this.outlinesFormat === 'truetype') {
+ return (this._hinting = new Hinting(this));
+ }
+ }
+ });
+}
+
+/**
+ * Check if the font has a glyph for the given character.
+ * @param {string}
+ * @return {Boolean}
+ */
+Font.prototype.hasChar = function(c) {
+ return this.encoding.charToGlyphIndex(c) !== null;
+};
+
+/**
+ * Convert the given character to a single glyph index.
+ * Note that this function assumes that there is a one-to-one mapping between
+ * the given character and a glyph; for complex scripts this might not be the case.
+ * @param {string}
+ * @return {Number}
+ */
+Font.prototype.charToGlyphIndex = function(s) {
+ return this.encoding.charToGlyphIndex(s);
+};
+
+/**
+ * Convert the given character to a single Glyph object.
+ * Note that this function assumes that there is a one-to-one mapping between
+ * the given character and a glyph; for complex scripts this might not be the case.
+ * @param {string}
+ * @return {opentype.Glyph}
+ */
+Font.prototype.charToGlyph = function(c) {
+ var glyphIndex = this.charToGlyphIndex(c);
+ var glyph = this.glyphs.get(glyphIndex);
+ if (!glyph) {
+ // .notdef
+ glyph = this.glyphs.get(0);
+ }
+
+ return glyph;
+};
+
+/**
+ * Convert the given text to a list of Glyph objects.
+ * Note that there is no strict one-to-one mapping between characters and
+ * glyphs, so the list of returned glyphs can be larger or smaller than the
+ * length of the given string.
+ * @param {string}
+ * @param {GlyphRenderOptions} [options]
+ * @return {opentype.Glyph[]}
+ */
+Font.prototype.stringToGlyphs = function(s, options) {
+ var this$1 = this;
+
+ options = options || this.defaultRenderOptions;
+ // Get glyph indexes
+ var indexes = [];
+ for (var i = 0; i < s.length; i += 1) {
+ var c = s[i];
+ indexes.push(this$1.charToGlyphIndex(c));
+ }
+ var length = indexes.length;
+
+ // Apply substitutions on glyph indexes
+ if (options.features) {
+ var script = options.script || this.substitution.getDefaultScriptName();
+ var manyToOne = [];
+ if (options.features.liga) { manyToOne = manyToOne.concat(this.substitution.getFeature('liga', script, options.language)); }
+ if (options.features.rlig) { manyToOne = manyToOne.concat(this.substitution.getFeature('rlig', script, options.language)); }
+ for (var i$1 = 0; i$1 < length; i$1 += 1) {
+ for (var j = 0; j < manyToOne.length; j++) {
+ var ligature = manyToOne[j];
+ var components = ligature.sub;
+ var compCount = components.length;
+ var k = 0;
+ while (k < compCount && components[k] === indexes[i$1 + k]) { k++; }
+ if (k === compCount) {
+ indexes.splice(i$1, compCount, ligature.by);
+ length = length - compCount + 1;
+ }
+ }
+ }
+ }
+
+ // convert glyph indexes to glyph objects
+ var glyphs = new Array(length);
+ var notdef = this.glyphs.get(0);
+ for (var i$2 = 0; i$2 < length; i$2 += 1) {
+ glyphs[i$2] = this$1.glyphs.get(indexes[i$2]) || notdef;
+ }
+ return glyphs;
+};
+
+/**
+ * @param {string}
+ * @return {Number}
+ */
+Font.prototype.nameToGlyphIndex = function(name) {
+ return this.glyphNames.nameToGlyphIndex(name);
+};
+
+/**
+ * @param {string}
+ * @return {opentype.Glyph}
+ */
+Font.prototype.nameToGlyph = function(name) {
+ var glyphIndex = this.nameToGlyphIndex(name);
+ var glyph = this.glyphs.get(glyphIndex);
+ if (!glyph) {
+ // .notdef
+ glyph = this.glyphs.get(0);
+ }
+
+ return glyph;
+};
+
+/**
+ * @param {Number}
+ * @return {String}
+ */
+Font.prototype.glyphIndexToName = function(gid) {
+ if (!this.glyphNames.glyphIndexToName) {
+ return '';
+ }
+
+ return this.glyphNames.glyphIndexToName(gid);
+};
+
+/**
+ * Retrieve the value of the kerning pair between the left glyph (or its index)
+ * and the right glyph (or its index). If no kerning pair is found, return 0.
+ * The kerning value gets added to the advance width when calculating the spacing
+ * between glyphs.
+ * @param {opentype.Glyph} leftGlyph
+ * @param {opentype.Glyph} rightGlyph
+ * @return {Number}
+ */
+Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) {
+ leftGlyph = leftGlyph.index || leftGlyph;
+ rightGlyph = rightGlyph.index || rightGlyph;
+ var gposKerning = this.getGposKerningValue;
+ return gposKerning ? gposKerning(leftGlyph, rightGlyph) :
+ (this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0);
+};
+
+/**
+ * @typedef GlyphRenderOptions
+ * @type Object
+ * @property {string} [script] - script used to determine which features to apply. By default, 'DFLT' or 'latn' is used.
+ * See https://www.microsoft.com/typography/otspec/scripttags.htm
+ * @property {string} [language='dflt'] - language system used to determine which features to apply.
+ * See https://www.microsoft.com/typography/developers/opentype/languagetags.aspx
+ * @property {boolean} [kerning=true] - whether to include kerning values
+ * @property {object} [features] - OpenType Layout feature tags. Used to enable or disable the features of the given script/language system.
+ * See https://www.microsoft.com/typography/otspec/featuretags.htm
+ */
+Font.prototype.defaultRenderOptions = {
+ kerning: true,
+ features: {
+ liga: true,
+ rlig: true
+ }
+};
+
+/**
+ * Helper function that invokes the given callback for each glyph in the given text.
+ * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text
+ * @param {string} text - The text to apply.
+ * @param {number} [x=0] - Horizontal position of the beginning of the text.
+ * @param {number} [y=0] - Vertical position of the *baseline* of the text.
+ * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
+ * @param {GlyphRenderOptions=} options
+ * @param {Function} callback
+ */
+Font.prototype.forEachGlyph = function(text, x, y, fontSize, options, callback) {
+ var this$1 = this;
+
+ x = x !== undefined ? x : 0;
+ y = y !== undefined ? y : 0;
+ fontSize = fontSize !== undefined ? fontSize : 72;
+ options = options || this.defaultRenderOptions;
+ var fontScale = 1 / this.unitsPerEm * fontSize;
+ var glyphs = this.stringToGlyphs(text, options);
+ for (var i = 0; i < glyphs.length; i += 1) {
+ var glyph = glyphs[i];
+ callback.call(this$1, glyph, x, y, fontSize, options);
+ if (glyph.advanceWidth) {
+ x += glyph.advanceWidth * fontScale;
+ }
+
+ if (options.kerning && i < glyphs.length - 1) {
+ var kerningValue = this$1.getKerningValue(glyph, glyphs[i + 1]);
+ x += kerningValue * fontScale;
+ }
+
+ if (options.letterSpacing) {
+ x += options.letterSpacing * fontSize;
+ } else if (options.tracking) {
+ x += (options.tracking / 1000) * fontSize;
+ }
+ }
+ return x;
+};
+
+/**
+ * Create a Path object that represents the given text.
+ * @param {string} text - The text to create.
+ * @param {number} [x=0] - Horizontal position of the beginning of the text.
+ * @param {number} [y=0] - Vertical position of the *baseline* of the text.
+ * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
+ * @param {GlyphRenderOptions=} options
+ * @return {opentype.Path}
+ */
+Font.prototype.getPath = function(text, x, y, fontSize, options) {
+ var fullPath = new Path();
+ this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
+ var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this);
+ fullPath.extend(glyphPath);
+ });
+ return fullPath;
+};
+
+/**
+ * Create an array of Path objects that represent the glyphs of a given text.
+ * @param {string} text - The text to create.
+ * @param {number} [x=0] - Horizontal position of the beginning of the text.
+ * @param {number} [y=0] - Vertical position of the *baseline* of the text.
+ * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
+ * @param {GlyphRenderOptions=} options
+ * @return {opentype.Path[]}
+ */
+Font.prototype.getPaths = function(text, x, y, fontSize, options) {
+ var glyphPaths = [];
+ this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
+ var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this);
+ glyphPaths.push(glyphPath);
+ });
+
+ return glyphPaths;
+};
+
+/**
+ * Returns the advance width of a text.
+ *
+ * This is something different than Path.getBoundingBox() as for example a
+ * suffixed whitespace increases the advanceWidth but not the bounding box
+ * or an overhanging letter like a calligraphic 'f' might have a quite larger
+ * bounding box than its advance width.
+ *
+ * This corresponds to canvas2dContext.measureText(text).width
+ *
+ * @param {string} text - The text to create.
+ * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
+ * @param {GlyphRenderOptions=} options
+ * @return advance width
+ */
+Font.prototype.getAdvanceWidth = function(text, fontSize, options) {
+ return this.forEachGlyph(text, 0, 0, fontSize, options, function() {});
+};
+
+/**
+ * Draw the text on the given drawing context.
+ * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
+ * @param {string} text - The text to create.
+ * @param {number} [x=0] - Horizontal position of the beginning of the text.
+ * @param {number} [y=0] - Vertical position of the *baseline* of the text.
+ * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
+ * @param {GlyphRenderOptions=} options
+ */
+Font.prototype.draw = function(ctx, text, x, y, fontSize, options) {
+ this.getPath(text, x, y, fontSize, options).draw(ctx);
+};
+
+/**
+ * Draw the points of all glyphs in the text.
+ * On-curve points will be drawn in blue, off-curve points will be drawn in red.
+ * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
+ * @param {string} text - The text to create.
+ * @param {number} [x=0] - Horizontal position of the beginning of the text.
+ * @param {number} [y=0] - Vertical position of the *baseline* of the text.
+ * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
+ * @param {GlyphRenderOptions=} options
+ */
+Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) {
+ this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
+ glyph.drawPoints(ctx, gX, gY, gFontSize);
+ });
+};
+
+/**
+ * Draw lines indicating important font measurements for all glyphs in the text.
+ * Black lines indicate the origin of the coordinate system (point 0,0).
+ * Blue lines indicate the glyph bounding box.
+ * Green line indicates the advance width of the glyph.
+ * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
+ * @param {string} text - The text to create.
+ * @param {number} [x=0] - Horizontal position of the beginning of the text.
+ * @param {number} [y=0] - Vertical position of the *baseline* of the text.
+ * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
+ * @param {GlyphRenderOptions=} options
+ */
+Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) {
+ this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
+ glyph.drawMetrics(ctx, gX, gY, gFontSize);
+ });
+};
+
+/**
+ * @param {string}
+ * @return {string}
+ */
+Font.prototype.getEnglishName = function(name) {
+ var translations = this.names[name];
+ if (translations) {
+ return translations.en;
+ }
+};
+
+/**
+ * Validate
+ */
+Font.prototype.validate = function() {
+ var warnings = [];
+ var _this = this;
+
+ function assert(predicate, message) {
+ if (!predicate) {
+ warnings.push(message);
+ }
+ }
+
+ function assertNamePresent(name) {
+ var englishName = _this.getEnglishName(name);
+ assert(englishName && englishName.trim().length > 0,
+ 'No English ' + name + ' specified.');
+ }
+
+ // Identification information
+ assertNamePresent('fontFamily');
+ assertNamePresent('weightName');
+ assertNamePresent('manufacturer');
+ assertNamePresent('copyright');
+ assertNamePresent('version');
+
+ // Dimension information
+ assert(this.unitsPerEm > 0, 'No unitsPerEm specified.');
+};
+
+/**
+ * Convert the font object to a SFNT data structure.
+ * This structure contains all the necessary tables and metadata to create a binary OTF file.
+ * @return {opentype.Table}
+ */
+Font.prototype.toTables = function() {
+ return sfnt.fontToTable(this);
+};
+/**
+ * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.
+ */
+Font.prototype.toBuffer = function() {
+ console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.');
+ return this.toArrayBuffer();
+};
+/**
+ * Converts a `opentype.Font` into an `ArrayBuffer`
+ * @return {ArrayBuffer}
+ */
+Font.prototype.toArrayBuffer = function() {
+ var sfntTable = this.toTables();
+ var bytes = sfntTable.encode();
+ var buffer = new ArrayBuffer(bytes.length);
+ var intArray = new Uint8Array(buffer);
+ for (var i = 0; i < bytes.length; i++) {
+ intArray[i] = bytes[i];
+ }
+
+ return buffer;
+};
+
+/**
+ * Initiate a download of the OpenType font.
+ */
+Font.prototype.download = function(fileName) {
+ var familyName = this.getEnglishName('fontFamily');
+ var styleName = this.getEnglishName('fontSubfamily');
+ fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf';
+ var arrayBuffer = this.toArrayBuffer();
+
+ if (isBrowser()) {
+ window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
+ window.requestFileSystem(window.TEMPORARY, arrayBuffer.byteLength, function(fs) {
+ fs.root.getFile(fileName, {create: true}, function(fileEntry) {
+ fileEntry.createWriter(function(writer) {
+ var dataView = new DataView(arrayBuffer);
+ var blob = new Blob([dataView], {type: 'font/opentype'});
+ writer.write(blob);
+
+ writer.addEventListener('writeend', function() {
+ // Navigating to the file will download it.
+ location.href = fileEntry.toURL();
+ }, false);
+ });
+ });
+ },
+ function(err) {
+ throw new Error(err.name + ': ' + err.message);
+ });
+ } else {
+ var fs = _dereq_('fs');
+ var buffer = arrayBufferToNodeBuffer(arrayBuffer);
+ fs.writeFileSync(fileName, buffer);
+ }
+};
+/**
+ * @private
+ */
+Font.prototype.fsSelectionValues = {
+ ITALIC: 0x001, //1
+ UNDERSCORE: 0x002, //2
+ NEGATIVE: 0x004, //4
+ OUTLINED: 0x008, //8
+ STRIKEOUT: 0x010, //16
+ BOLD: 0x020, //32
+ REGULAR: 0x040, //64
+ USER_TYPO_METRICS: 0x080, //128
+ WWS: 0x100, //256
+ OBLIQUE: 0x200 //512
+};
+
+/**
+ * @private
+ */
+Font.prototype.usWidthClasses = {
+ ULTRA_CONDENSED: 1,
+ EXTRA_CONDENSED: 2,
+ CONDENSED: 3,
+ SEMI_CONDENSED: 4,
+ MEDIUM: 5,
+ SEMI_EXPANDED: 6,
+ EXPANDED: 7,
+ EXTRA_EXPANDED: 8,
+ ULTRA_EXPANDED: 9
+};
+
+/**
+ * @private
+ */
+Font.prototype.usWeightClasses = {
+ THIN: 100,
+ EXTRA_LIGHT: 200,
+ LIGHT: 300,
+ NORMAL: 400,
+ MEDIUM: 500,
+ SEMI_BOLD: 600,
+ BOLD: 700,
+ EXTRA_BOLD: 800,
+ BLACK: 900
+};
+
+// The `fvar` table stores font variation axes and instances.
+// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html
+
+function addName(name, names) {
+ var nameString = JSON.stringify(name);
+ var nameID = 256;
+ for (var nameKey in names) {
+ var n = parseInt(nameKey);
+ if (!n || n < 256) {
+ continue;
+ }
+
+ if (JSON.stringify(names[nameKey]) === nameString) {
+ return n;
+ }
+
+ if (nameID <= n) {
+ nameID = n + 1;
+ }
+ }
+
+ names[nameID] = name;
+ return nameID;
+}
+
+function makeFvarAxis(n, axis, names) {
+ var nameID = addName(axis.name, names);
+ return [
+ {name: 'tag_' + n, type: 'TAG', value: axis.tag},
+ {name: 'minValue_' + n, type: 'FIXED', value: axis.minValue << 16},
+ {name: 'defaultValue_' + n, type: 'FIXED', value: axis.defaultValue << 16},
+ {name: 'maxValue_' + n, type: 'FIXED', value: axis.maxValue << 16},
+ {name: 'flags_' + n, type: 'USHORT', value: 0},
+ {name: 'nameID_' + n, type: 'USHORT', value: nameID}
+ ];
+}
+
+function parseFvarAxis(data, start, names) {
+ var axis = {};
+ var p = new parse.Parser(data, start);
+ axis.tag = p.parseTag();
+ axis.minValue = p.parseFixed();
+ axis.defaultValue = p.parseFixed();
+ axis.maxValue = p.parseFixed();
+ p.skip('uShort', 1); // reserved for flags; no values defined
+ axis.name = names[p.parseUShort()] || {};
+ return axis;
+}
+
+function makeFvarInstance(n, inst, axes, names) {
+ var nameID = addName(inst.name, names);
+ var fields = [
+ {name: 'nameID_' + n, type: 'USHORT', value: nameID},
+ {name: 'flags_' + n, type: 'USHORT', value: 0}
+ ];
+
+ for (var i = 0; i < axes.length; ++i) {
+ var axisTag = axes[i].tag;
+ fields.push({
+ name: 'axis_' + n + ' ' + axisTag,
+ type: 'FIXED',
+ value: inst.coordinates[axisTag] << 16
+ });
+ }
+
+ return fields;
+}
+
+function parseFvarInstance(data, start, axes, names) {
+ var inst = {};
+ var p = new parse.Parser(data, start);
+ inst.name = names[p.parseUShort()] || {};
+ p.skip('uShort', 1); // reserved for flags; no values defined
+
+ inst.coordinates = {};
+ for (var i = 0; i < axes.length; ++i) {
+ inst.coordinates[axes[i].tag] = p.parseFixed();
+ }
+
+ return inst;
+}
+
+function makeFvarTable(fvar, names) {
+ var result = new table.Table('fvar', [
+ {name: 'version', type: 'ULONG', value: 0x10000},
+ {name: 'offsetToData', type: 'USHORT', value: 0},
+ {name: 'countSizePairs', type: 'USHORT', value: 2},
+ {name: 'axisCount', type: 'USHORT', value: fvar.axes.length},
+ {name: 'axisSize', type: 'USHORT', value: 20},
+ {name: 'instanceCount', type: 'USHORT', value: fvar.instances.length},
+ {name: 'instanceSize', type: 'USHORT', value: 4 + fvar.axes.length * 4}
+ ]);
+ result.offsetToData = result.sizeOf();
+
+ for (var i = 0; i < fvar.axes.length; i++) {
+ result.fields = result.fields.concat(makeFvarAxis(i, fvar.axes[i], names));
+ }
+
+ for (var j = 0; j < fvar.instances.length; j++) {
+ result.fields = result.fields.concat(makeFvarInstance(j, fvar.instances[j], fvar.axes, names));
+ }
+
+ return result;
+}
+
+function parseFvarTable(data, start, names) {
+ var p = new parse.Parser(data, start);
+ var tableVersion = p.parseULong();
+ check.argument(tableVersion === 0x00010000, 'Unsupported fvar table version.');
+ var offsetToData = p.parseOffset16();
+ // Skip countSizePairs.
+ p.skip('uShort', 1);
+ var axisCount = p.parseUShort();
+ var axisSize = p.parseUShort();
+ var instanceCount = p.parseUShort();
+ var instanceSize = p.parseUShort();
+
+ var axes = [];
+ for (var i = 0; i < axisCount; i++) {
+ axes.push(parseFvarAxis(data, start + offsetToData + i * axisSize, names));
+ }
+
+ var instances = [];
+ var instanceStart = start + offsetToData + axisCount * axisSize;
+ for (var j = 0; j < instanceCount; j++) {
+ instances.push(parseFvarInstance(data, instanceStart + j * instanceSize, axes, names));
+ }
+
+ return {axes: axes, instances: instances};
+}
+
+var fvar = { make: makeFvarTable, parse: parseFvarTable };
+
+// The `GPOS` table contains kerning pairs, among other things.
+// https://www.microsoft.com/typography/OTSPEC/gpos.htm
+
+// Parse ScriptList and FeatureList tables of GPOS, GSUB, GDEF, BASE, JSTF tables.
+// These lists are unused by now, this function is just the basis for a real parsing.
+function parseTaggedListTable(data, start) {
+ var p = new parse.Parser(data, start);
+ var n = p.parseUShort();
+ var list = [];
+ for (var i = 0; i < n; i++) {
+ list[p.parseTag()] = { offset: p.parseUShort() };
+ }
+
+ return list;
+}
+
+// Parse a coverage table in a GSUB, GPOS or GDEF table.
+// Format 1 is a simple list of glyph ids,
+// Format 2 is a list of ranges. It is expanded in a list of glyphs, maybe not the best idea.
+function parseCoverageTable(data, start) {
+ var p = new parse.Parser(data, start);
+ var format = p.parseUShort();
+ var count = p.parseUShort();
+ if (format === 1) {
+ return p.parseUShortList(count);
+ } else if (format === 2) {
+ var coverage = [];
+ for (; count--;) {
+ var begin = p.parseUShort();
+ var end = p.parseUShort();
+ var index = p.parseUShort();
+ for (var i = begin; i <= end; i++) {
+ coverage[index++] = i;
+ }
+ }
+
+ return coverage;
+ }
+}
+
+// Parse a Class Definition Table in a GSUB, GPOS or GDEF table.
+// Returns a function that gets a class value from a glyph ID.
+function parseClassDefTable(data, start) {
+ var p = new parse.Parser(data, start);
+ var format = p.parseUShort();
+ if (format === 1) {
+ // Format 1 specifies a range of consecutive glyph indices, one class per glyph ID.
+ var startGlyph = p.parseUShort();
+ var glyphCount = p.parseUShort();
+ var classes = p.parseUShortList(glyphCount);
+ return function(glyphID) {
+ return classes[glyphID - startGlyph] || 0;
+ };
+ } else if (format === 2) {
+ // Format 2 defines multiple groups of glyph indices that belong to the same class.
+ var rangeCount = p.parseUShort();
+ var startGlyphs = [];
+ var endGlyphs = [];
+ var classValues = [];
+ for (var i = 0; i < rangeCount; i++) {
+ startGlyphs[i] = p.parseUShort();
+ endGlyphs[i] = p.parseUShort();
+ classValues[i] = p.parseUShort();
+ }
+
+ return function(glyphID) {
+ var l = 0;
+ var r = startGlyphs.length - 1;
+ while (l < r) {
+ var c = (l + r + 1) >> 1;
+ if (glyphID < startGlyphs[c]) {
+ r = c - 1;
+ } else {
+ l = c;
+ }
+ }
+
+ if (startGlyphs[l] <= glyphID && glyphID <= endGlyphs[l]) {
+ return classValues[l] || 0;
+ }
+
+ return 0;
+ };
+ }
+}
+
+// Parse a pair adjustment positioning subtable, format 1 or format 2
+// The subtable is returned in the form of a lookup function.
+function parsePairPosSubTable(data, start) {
+ var p = new parse.Parser(data, start);
+ // This part is common to format 1 and format 2 subtables
+ var format = p.parseUShort();
+ var coverageOffset = p.parseUShort();
+ var coverage = parseCoverageTable(data, start + coverageOffset);
+ // valueFormat 4: XAdvance only, 1: XPlacement only, 0: no ValueRecord for second glyph
+ // Only valueFormat1=4 and valueFormat2=0 is supported.
+ var valueFormat1 = p.parseUShort();
+ var valueFormat2 = p.parseUShort();
+ var value1;
+ var value2;
+ if (valueFormat1 !== 4 || valueFormat2 !== 0) { return; }
+ var sharedPairSets = {};
+ if (format === 1) {
+ // Pair Positioning Adjustment: Format 1
+ var pairSetCount = p.parseUShort();
+ var pairSet = [];
+ // Array of offsets to PairSet tables-from beginning of PairPos subtable-ordered by Coverage Index
+ var pairSetOffsets = p.parseOffset16List(pairSetCount);
+ for (var firstGlyph = 0; firstGlyph < pairSetCount; firstGlyph++) {
+ var pairSetOffset = pairSetOffsets[firstGlyph];
+ var sharedPairSet = sharedPairSets[pairSetOffset];
+ if (!sharedPairSet) {
+ // Parse a pairset table in a pair adjustment subtable format 1
+ sharedPairSet = {};
+ p.relativeOffset = pairSetOffset;
+ var pairValueCount = p.parseUShort();
+ for (; pairValueCount--;) {
+ var secondGlyph = p.parseUShort();
+ if (valueFormat1) { value1 = p.parseShort(); }
+ if (valueFormat2) { value2 = p.parseShort(); }
+ // We only support valueFormat1 = 4 and valueFormat2 = 0,
+ // so value1 is the XAdvance and value2 is empty.
+ sharedPairSet[secondGlyph] = value1;
+ }
+ }
+
+ pairSet[coverage[firstGlyph]] = sharedPairSet;
+ }
+
+ return function(leftGlyph, rightGlyph) {
+ var pairs = pairSet[leftGlyph];
+ if (pairs) { return pairs[rightGlyph]; }
+ };
+ } else if (format === 2) {
+ // Pair Positioning Adjustment: Format 2
+ var classDef1Offset = p.parseUShort();
+ var classDef2Offset = p.parseUShort();
+ var class1Count = p.parseUShort();
+ var class2Count = p.parseUShort();
+ var getClass1 = parseClassDefTable(data, start + classDef1Offset);
+ var getClass2 = parseClassDefTable(data, start + classDef2Offset);
+
+ // Parse kerning values by class pair.
+ var kerningMatrix = [];
+ for (var i = 0; i < class1Count; i++) {
+ var kerningRow = kerningMatrix[i] = [];
+ for (var j = 0; j < class2Count; j++) {
+ if (valueFormat1) { value1 = p.parseShort(); }
+ if (valueFormat2) { value2 = p.parseShort(); }
+ // We only support valueFormat1 = 4 and valueFormat2 = 0,
+ // so value1 is the XAdvance and value2 is empty.
+ kerningRow[j] = value1;
+ }
+ }
+
+ // Convert coverage list to a hash
+ var covered = {};
+ for (var i$1 = 0; i$1 < coverage.length; i$1++) {
+ covered[coverage[i$1]] = 1;
+ }
+
+ // Get the kerning value for a specific glyph pair.
+ return function(leftGlyph, rightGlyph) {
+ if (!covered[leftGlyph]) { return; }
+ var class1 = getClass1(leftGlyph);
+ var class2 = getClass2(rightGlyph);
+ var kerningRow = kerningMatrix[class1];
+
+ if (kerningRow) {
+ return kerningRow[class2];
+ }
+ };
+ }
+}
+
+// Parse a LookupTable (present in of GPOS, GSUB, GDEF, BASE, JSTF tables).
+function parseLookupTable(data, start) {
+ var p = new parse.Parser(data, start);
+ var lookupType = p.parseUShort();
+ var lookupFlag = p.parseUShort();
+ var useMarkFilteringSet = lookupFlag & 0x10;
+ var subTableCount = p.parseUShort();
+ var subTableOffsets = p.parseOffset16List(subTableCount);
+ var table = {
+ lookupType: lookupType,
+ lookupFlag: lookupFlag,
+ markFilteringSet: useMarkFilteringSet ? p.parseUShort() : -1
+ };
+ // LookupType 2, Pair adjustment
+ if (lookupType === 2) {
+ var subtables = [];
+ for (var i = 0; i < subTableCount; i++) {
+ var pairPosSubTable = parsePairPosSubTable(data, start + subTableOffsets[i]);
+ if (pairPosSubTable) { subtables.push(pairPosSubTable); }
+ }
+ // Return a function which finds the kerning values in the subtables.
+ table.getKerningValue = function(leftGlyph, rightGlyph) {
+ for (var i = subtables.length; i--;) {
+ var value = subtables[i](leftGlyph, rightGlyph);
+ if (value !== undefined) { return value; }
+ }
+
+ return 0;
+ };
+ }
+
+ return table;
+}
+
+// Parse the `GPOS` table which contains, among other things, kerning pairs.
+// https://www.microsoft.com/typography/OTSPEC/gpos.htm
+function parseGposTable(data, start, font) {
+ var p = new parse.Parser(data, start);
+ var tableVersion = p.parseFixed();
+ check.argument(tableVersion === 1, 'Unsupported GPOS table version.');
+
+ // ScriptList and FeatureList - ignored for now
+ parseTaggedListTable(data, start + p.parseUShort());
+ // 'kern' is the feature we are looking for.
+ parseTaggedListTable(data, start + p.parseUShort());
+
+ // LookupList
+ var lookupListOffset = p.parseUShort();
+ p.relativeOffset = lookupListOffset;
+ var lookupCount = p.parseUShort();
+ var lookupTableOffsets = p.parseOffset16List(lookupCount);
+ var lookupListAbsoluteOffset = start + lookupListOffset;
+ for (var i = 0; i < lookupCount; i++) {
+ var table = parseLookupTable(data, lookupListAbsoluteOffset + lookupTableOffsets[i]);
+ if (table.lookupType === 2 && !font.getGposKerningValue) { font.getGposKerningValue = table.getKerningValue; }
+ }
+}
+
+var gpos = { parse: parseGposTable };
+
+// The `kern` table contains kerning pairs.
+// Note that some fonts use the GPOS OpenType layout table to specify kerning.
+// https://www.microsoft.com/typography/OTSPEC/kern.htm
+
+function parseWindowsKernTable(p) {
+ var pairs = {};
+ // Skip nTables.
+ p.skip('uShort');
+ var subtableVersion = p.parseUShort();
+ check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.');
+ // Skip subtableLength, subtableCoverage
+ p.skip('uShort', 2);
+ var nPairs = p.parseUShort();
+ // Skip searchRange, entrySelector, rangeShift.
+ p.skip('uShort', 3);
+ for (var i = 0; i < nPairs; i += 1) {
+ var leftIndex = p.parseUShort();
+ var rightIndex = p.parseUShort();
+ var value = p.parseShort();
+ pairs[leftIndex + ',' + rightIndex] = value;
+ }
+ return pairs;
+}
+
+function parseMacKernTable(p) {
+ var pairs = {};
+ // The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits.
+ // Skip the rest.
+ p.skip('uShort');
+ var nTables = p.parseULong();
+ //check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').');
+ if (nTables > 1) {
+ console.warn('Only the first kern subtable is supported.');
+ }
+ p.skip('uLong');
+ var coverage = p.parseUShort();
+ var subtableVersion = coverage & 0xFF;
+ p.skip('uShort');
+ if (subtableVersion === 0) {
+ var nPairs = p.parseUShort();
+ // Skip searchRange, entrySelector, rangeShift.
+ p.skip('uShort', 3);
+ for (var i = 0; i < nPairs; i += 1) {
+ var leftIndex = p.parseUShort();
+ var rightIndex = p.parseUShort();
+ var value = p.parseShort();
+ pairs[leftIndex + ',' + rightIndex] = value;
+ }
+ }
+ return pairs;
+}
+
+// Parse the `kern` table which contains kerning pairs.
+function parseKernTable(data, start) {
+ var p = new parse.Parser(data, start);
+ var tableVersion = p.parseUShort();
+ if (tableVersion === 0) {
+ return parseWindowsKernTable(p);
+ } else if (tableVersion === 1) {
+ return parseMacKernTable(p);
+ } else {
+ throw new Error('Unsupported kern table version (' + tableVersion + ').');
+ }
+}
+
+var kern = { parse: parseKernTable };
+
+// The `loca` table stores the offsets to the locations of the glyphs in the font.
+// https://www.microsoft.com/typography/OTSPEC/loca.htm
+
+// Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font,
+// relative to the beginning of the glyphData table.
+// The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs)
+// The loca table has two versions: a short version where offsets are stored as uShorts, and a long
+// version where offsets are stored as uLongs. The `head` table specifies which version to use
+// (under indexToLocFormat).
+function parseLocaTable(data, start, numGlyphs, shortVersion) {
+ var p = new parse.Parser(data, start);
+ var parseFn = shortVersion ? p.parseUShort : p.parseULong;
+ // There is an extra entry after the last index element to compute the length of the last glyph.
+ // That's why we use numGlyphs + 1.
+ var glyphOffsets = [];
+ for (var i = 0; i < numGlyphs + 1; i += 1) {
+ var glyphOffset = parseFn.call(p);
+ if (shortVersion) {
+ // The short table version stores the actual offset divided by 2.
+ glyphOffset *= 2;
+ }
+
+ glyphOffsets.push(glyphOffset);
+ }
+
+ return glyphOffsets;
+}
+
+var loca = { parse: parseLocaTable };
+
+// opentype.js
+// https://github.com/nodebox/opentype.js
+// (c) 2015 Frederik De Bleser
+// opentype.js may be freely distributed under the MIT license.
+
+/* global DataView, Uint8Array, XMLHttpRequest */
+
+/**
+ * The opentype library.
+ * @namespace opentype
+ */
+
+// File loaders /////////////////////////////////////////////////////////
+/**
+ * Loads a font from a file. The callback throws an error message as the first parameter if it fails
+ * and the font as an ArrayBuffer in the second parameter if it succeeds.
+ * @param {string} path - The path of the file
+ * @param {Function} callback - The function to call when the font load completes
+ */
+function loadFromFile(path, callback) {
+ var fs = _dereq_('fs');
+ fs.readFile(path, function(err, buffer) {
+ if (err) {
+ return callback(err.message);
+ }
+
+ callback(null, nodeBufferToArrayBuffer(buffer));
+ });
+}
+/**
+ * Loads a font from a URL. The callback throws an error message as the first parameter if it fails
+ * and the font as an ArrayBuffer in the second parameter if it succeeds.
+ * @param {string} url - The URL of the font file.
+ * @param {Function} callback - The function to call when the font load completes
+ */
+function loadFromUrl(url, callback) {
+ var request = new XMLHttpRequest();
+ request.open('get', url, true);
+ request.responseType = 'arraybuffer';
+ request.onload = function() {
+ if (request.status !== 200) {
+ return callback('Font could not be loaded: ' + request.statusText);
+ }
+
+ return callback(null, request.response);
+ };
+
+ request.onerror = function () {
+ callback('Font could not be loaded');
+ };
+
+ request.send();
+}
+
+// Table Directory Entries //////////////////////////////////////////////
+/**
+ * Parses OpenType table entries.
+ * @param {DataView}
+ * @param {Number}
+ * @return {Object[]}
+ */
+function parseOpenTypeTableEntries(data, numTables) {
+ var tableEntries = [];
+ var p = 12;
+ for (var i = 0; i < numTables; i += 1) {
+ var tag = parse.getTag(data, p);
+ var checksum = parse.getULong(data, p + 4);
+ var offset = parse.getULong(data, p + 8);
+ var length = parse.getULong(data, p + 12);
+ tableEntries.push({tag: tag, checksum: checksum, offset: offset, length: length, compression: false});
+ p += 16;
+ }
+
+ return tableEntries;
+}
+
+/**
+ * Parses WOFF table entries.
+ * @param {DataView}
+ * @param {Number}
+ * @return {Object[]}
+ */
+function parseWOFFTableEntries(data, numTables) {
+ var tableEntries = [];
+ var p = 44; // offset to the first table directory entry.
+ for (var i = 0; i < numTables; i += 1) {
+ var tag = parse.getTag(data, p);
+ var offset = parse.getULong(data, p + 4);
+ var compLength = parse.getULong(data, p + 8);
+ var origLength = parse.getULong(data, p + 12);
+ var compression = (void 0);
+ if (compLength < origLength) {
+ compression = 'WOFF';
+ } else {
+ compression = false;
+ }
+
+ tableEntries.push({tag: tag, offset: offset, compression: compression,
+ compressedLength: compLength, length: origLength});
+ p += 20;
+ }
+
+ return tableEntries;
+}
+
+/**
+ * @typedef TableData
+ * @type Object
+ * @property {DataView} data - The DataView
+ * @property {number} offset - The data offset.
+ */
+
+/**
+ * @param {DataView}
+ * @param {Object}
+ * @return {TableData}
+ */
+function uncompressTable(data, tableEntry) {
+ if (tableEntry.compression === 'WOFF') {
+ var inBuffer = new Uint8Array(data.buffer, tableEntry.offset + 2, tableEntry.compressedLength - 2);
+ var outBuffer = new Uint8Array(tableEntry.length);
+ index(inBuffer, outBuffer);
+ if (outBuffer.byteLength !== tableEntry.length) {
+ throw new Error('Decompression error: ' + tableEntry.tag + ' decompressed length doesn\'t match recorded length');
+ }
+
+ var view = new DataView(outBuffer.buffer, 0);
+ return {data: view, offset: 0};
+ } else {
+ return {data: data, offset: tableEntry.offset};
+ }
+}
+
+// Public API ///////////////////////////////////////////////////////////
+
+/**
+ * Parse the OpenType file data (as an ArrayBuffer) and return a Font object.
+ * Throws an error if the font could not be parsed.
+ * @param {ArrayBuffer}
+ * @return {opentype.Font}
+ */
+function parseBuffer(buffer) {
+ var indexToLocFormat;
+ var ltagTable;
+
+ // Since the constructor can also be called to create new fonts from scratch, we indicate this
+ // should be an empty font that we'll fill with our own data.
+ var font = new Font({empty: true});
+
+ // OpenType fonts use big endian byte ordering.
+ // We can't rely on typed array view types, because they operate with the endianness of the host computer.
+ // Instead we use DataViews where we can specify endianness.
+ var data = new DataView(buffer, 0);
+ var numTables;
+ var tableEntries = [];
+ var signature = parse.getTag(data, 0);
+ if (signature === String.fromCharCode(0, 1, 0, 0) || signature === 'true' || signature === 'typ1') {
+ font.outlinesFormat = 'truetype';
+ numTables = parse.getUShort(data, 4);
+ tableEntries = parseOpenTypeTableEntries(data, numTables);
+ } else if (signature === 'OTTO') {
+ font.outlinesFormat = 'cff';
+ numTables = parse.getUShort(data, 4);
+ tableEntries = parseOpenTypeTableEntries(data, numTables);
+ } else if (signature === 'wOFF') {
+ var flavor = parse.getTag(data, 4);
+ if (flavor === String.fromCharCode(0, 1, 0, 0)) {
+ font.outlinesFormat = 'truetype';
+ } else if (flavor === 'OTTO') {
+ font.outlinesFormat = 'cff';
+ } else {
+ throw new Error('Unsupported OpenType flavor ' + signature);
+ }
+
+ numTables = parse.getUShort(data, 12);
+ tableEntries = parseWOFFTableEntries(data, numTables);
+ } else {
+ throw new Error('Unsupported OpenType signature ' + signature);
+ }
+
+ var cffTableEntry;
+ var fvarTableEntry;
+ var glyfTableEntry;
+ var gposTableEntry;
+ var gsubTableEntry;
+ var hmtxTableEntry;
+ var kernTableEntry;
+ var locaTableEntry;
+ var nameTableEntry;
+ var metaTableEntry;
+ var p;
+
+ for (var i = 0; i < numTables; i += 1) {
+ var tableEntry = tableEntries[i];
+ var table = (void 0);
+ switch (tableEntry.tag) {
+ case 'cmap':
+ table = uncompressTable(data, tableEntry);
+ font.tables.cmap = cmap.parse(table.data, table.offset);
+ font.encoding = new CmapEncoding(font.tables.cmap);
+ break;
+ case 'cvt ' :
+ table = uncompressTable(data, tableEntry);
+ p = new parse.Parser(table.data, table.offset);
+ font.tables.cvt = p.parseShortList(tableEntry.length / 2);
+ break;
+ case 'fvar':
+ fvarTableEntry = tableEntry;
+ break;
+ case 'fpgm' :
+ table = uncompressTable(data, tableEntry);
+ p = new parse.Parser(table.data, table.offset);
+ font.tables.fpgm = p.parseByteList(tableEntry.length);
+ break;
+ case 'head':
+ table = uncompressTable(data, tableEntry);
+ font.tables.head = head.parse(table.data, table.offset);
+ font.unitsPerEm = font.tables.head.unitsPerEm;
+ indexToLocFormat = font.tables.head.indexToLocFormat;
+ break;
+ case 'hhea':
+ table = uncompressTable(data, tableEntry);
+ font.tables.hhea = hhea.parse(table.data, table.offset);
+ font.ascender = font.tables.hhea.ascender;
+ font.descender = font.tables.hhea.descender;
+ font.numberOfHMetrics = font.tables.hhea.numberOfHMetrics;
+ break;
+ case 'hmtx':
+ hmtxTableEntry = tableEntry;
+ break;
+ case 'ltag':
+ table = uncompressTable(data, tableEntry);
+ ltagTable = ltag.parse(table.data, table.offset);
+ break;
+ case 'maxp':
+ table = uncompressTable(data, tableEntry);
+ font.tables.maxp = maxp.parse(table.data, table.offset);
+ font.numGlyphs = font.tables.maxp.numGlyphs;
+ break;
+ case 'name':
+ nameTableEntry = tableEntry;
+ break;
+ case 'OS/2':
+ table = uncompressTable(data, tableEntry);
+ font.tables.os2 = os2.parse(table.data, table.offset);
+ break;
+ case 'post':
+ table = uncompressTable(data, tableEntry);
+ font.tables.post = post.parse(table.data, table.offset);
+ font.glyphNames = new GlyphNames(font.tables.post);
+ break;
+ case 'prep' :
+ table = uncompressTable(data, tableEntry);
+ p = new parse.Parser(table.data, table.offset);
+ font.tables.prep = p.parseByteList(tableEntry.length);
+ break;
+ case 'glyf':
+ glyfTableEntry = tableEntry;
+ break;
+ case 'loca':
+ locaTableEntry = tableEntry;
+ break;
+ case 'CFF ':
+ cffTableEntry = tableEntry;
+ break;
+ case 'kern':
+ kernTableEntry = tableEntry;
+ break;
+ case 'GPOS':
+ gposTableEntry = tableEntry;
+ break;
+ case 'GSUB':
+ gsubTableEntry = tableEntry;
+ break;
+ case 'meta':
+ metaTableEntry = tableEntry;
+ break;
+ }
+ }
+
+ var nameTable = uncompressTable(data, nameTableEntry);
+ font.tables.name = _name.parse(nameTable.data, nameTable.offset, ltagTable);
+ font.names = font.tables.name;
+
+ if (glyfTableEntry && locaTableEntry) {
+ var shortVersion = indexToLocFormat === 0;
+ var locaTable = uncompressTable(data, locaTableEntry);
+ var locaOffsets = loca.parse(locaTable.data, locaTable.offset, font.numGlyphs, shortVersion);
+ var glyfTable = uncompressTable(data, glyfTableEntry);
+ font.glyphs = glyf.parse(glyfTable.data, glyfTable.offset, locaOffsets, font);
+ } else if (cffTableEntry) {
+ var cffTable = uncompressTable(data, cffTableEntry);
+ cff.parse(cffTable.data, cffTable.offset, font);
+ } else {
+ throw new Error('Font doesn\'t contain TrueType or CFF outlines.');
+ }
+
+ var hmtxTable = uncompressTable(data, hmtxTableEntry);
+ hmtx.parse(hmtxTable.data, hmtxTable.offset, font.numberOfHMetrics, font.numGlyphs, font.glyphs);
+ addGlyphNames(font);
+
+ if (kernTableEntry) {
+ var kernTable = uncompressTable(data, kernTableEntry);
+ font.kerningPairs = kern.parse(kernTable.data, kernTable.offset);
+ } else {
+ font.kerningPairs = {};
+ }
+
+ if (gposTableEntry) {
+ var gposTable = uncompressTable(data, gposTableEntry);
+ gpos.parse(gposTable.data, gposTable.offset, font);
+ }
+
+ if (gsubTableEntry) {
+ var gsubTable = uncompressTable(data, gsubTableEntry);
+ font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset);
+ }
+
+ if (fvarTableEntry) {
+ var fvarTable = uncompressTable(data, fvarTableEntry);
+ font.tables.fvar = fvar.parse(fvarTable.data, fvarTable.offset, font.names);
+ }
+
+ if (metaTableEntry) {
+ var metaTable = uncompressTable(data, metaTableEntry);
+ font.tables.meta = meta.parse(metaTable.data, metaTable.offset);
+ font.metas = font.tables.meta;
+ }
+
+ return font;
+}
+
+/**
+ * Asynchronously load the font from a URL or a filesystem. When done, call the callback
+ * with two arguments `(err, font)`. The `err` will be null on success,
+ * the `font` is a Font object.
+ * We use the node.js callback convention so that
+ * opentype.js can integrate with frameworks like async.js.
+ * @alias opentype.load
+ * @param {string} url - The URL of the font to load.
+ * @param {Function} callback - The callback.
+ */
+function load(url, callback) {
+ var isNode$$1 = typeof window === 'undefined';
+ var loadFn = isNode$$1 ? loadFromFile : loadFromUrl;
+ loadFn(url, function(err, arrayBuffer) {
+ if (err) {
+ return callback(err);
+ }
+ var font;
+ try {
+ font = parseBuffer(arrayBuffer);
+ } catch (e) {
+ return callback(e, null);
+ }
+ return callback(null, font);
+ });
+}
+
+/**
+ * Synchronously load the font from a URL or file.
+ * When done, returns the font object or throws an error.
+ * @alias opentype.loadSync
+ * @param {string} url - The URL of the font to load.
+ * @return {opentype.Font}
+ */
+function loadSync(url) {
+ var fs = _dereq_('fs');
+ var buffer = fs.readFileSync(url);
+ return parseBuffer(nodeBufferToArrayBuffer(buffer));
+}
+
+exports.Font = Font;
+exports.Glyph = Glyph;
+exports.Path = Path;
+exports.BoundingBox = BoundingBox;
+exports._parse = parse;
+exports.parse = parseBuffer;
+exports.load = load;
+exports.loadSync = loadSync;
+
+Object.defineProperty(exports, '__esModule', { value: true });
+
+})));
+
+
+}).call(this,_dereq_("buffer").Buffer)
+},{"buffer":4,"fs":3}],11:[function(_dereq_,module,exports){
+// shim for using process in browser
+var process = module.exports = {};
+
+// cached from whatever global is present so that test runners that stub it
+// don't break things. But we need to wrap it in a try catch in case it is
+// wrapped in strict mode code which doesn't define any globals. It's inside a
+// function because try/catches deoptimize in certain engines.
+
+var cachedSetTimeout;
+var cachedClearTimeout;
+
+function defaultSetTimout() {
+ throw new Error('setTimeout has not been defined');
+}
+function defaultClearTimeout () {
+ throw new Error('clearTimeout has not been defined');
+}
+(function () {
+ try {
+ if (typeof setTimeout === 'function') {
+ cachedSetTimeout = setTimeout;
+ } else {
+ cachedSetTimeout = defaultSetTimout;
+ }
+ } catch (e) {
+ cachedSetTimeout = defaultSetTimout;
+ }
+ try {
+ if (typeof clearTimeout === 'function') {
+ cachedClearTimeout = clearTimeout;
+ } else {
+ cachedClearTimeout = defaultClearTimeout;
+ }
+ } catch (e) {
+ cachedClearTimeout = defaultClearTimeout;
+ }
+} ())
+function runTimeout(fun) {
+ if (cachedSetTimeout === setTimeout) {
+ //normal enviroments in sane situations
+ return setTimeout(fun, 0);
+ }
+ // if setTimeout wasn't available but was latter defined
+ if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
+ cachedSetTimeout = setTimeout;
+ return setTimeout(fun, 0);
+ }
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedSetTimeout(fun, 0);
+ } catch(e){
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedSetTimeout.call(null, fun, 0);
+ } catch(e){
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
+ return cachedSetTimeout.call(this, fun, 0);
+ }
+ }
+
+
+}
+function runClearTimeout(marker) {
+ if (cachedClearTimeout === clearTimeout) {
+ //normal enviroments in sane situations
+ return clearTimeout(marker);
+ }
+ // if clearTimeout wasn't available but was latter defined
+ if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
+ cachedClearTimeout = clearTimeout;
+ return clearTimeout(marker);
+ }
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedClearTimeout(marker);
+ } catch (e){
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedClearTimeout.call(null, marker);
+ } catch (e){
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
+ // Some versions of I.E. have different rules for clearTimeout vs setTimeout
+ return cachedClearTimeout.call(this, marker);
+ }
+ }
+
+
+
+}
+var queue = [];
+var draining = false;
+var currentQueue;
+var queueIndex = -1;
+
+function cleanUpNextTick() {
+ if (!draining || !currentQueue) {
+ return;
+ }
+ draining = false;
+ if (currentQueue.length) {
+ queue = currentQueue.concat(queue);
+ } else {
+ queueIndex = -1;
+ }
+ if (queue.length) {
+ drainQueue();
+ }
+}
+
+function drainQueue() {
+ if (draining) {
+ return;
+ }
+ var timeout = runTimeout(cleanUpNextTick);
+ draining = true;
+
+ var len = queue.length;
+ while(len) {
+ currentQueue = queue;
+ queue = [];
+ while (++queueIndex < len) {
+ if (currentQueue) {
+ currentQueue[queueIndex].run();
+ }
+ }
+ queueIndex = -1;
+ len = queue.length;
+ }
+ currentQueue = null;
+ draining = false;
+ runClearTimeout(timeout);
+}
+
+process.nextTick = function (fun) {
+ var args = new Array(arguments.length - 1);
+ if (arguments.length > 1) {
+ for (var i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+ }
+ queue.push(new Item(fun, args));
+ if (queue.length === 1 && !draining) {
+ runTimeout(drainQueue);
+ }
+};
+
+// v8 likes predictible objects
+function Item(fun, array) {
+ this.fun = fun;
+ this.array = array;
+}
+Item.prototype.run = function () {
+ this.fun.apply(null, this.array);
+};
+process.title = 'browser';
+process.browser = true;
+process.env = {};
+process.argv = [];
+process.version = ''; // empty string to avoid regexp issues
+process.versions = {};
+
+function noop() {}
+
+process.on = noop;
+process.addListener = noop;
+process.once = noop;
+process.off = noop;
+process.removeListener = noop;
+process.removeAllListeners = noop;
+process.emit = noop;
+process.prependListener = noop;
+process.prependOnceListener = noop;
+
+process.listeners = function (name) { return [] }
+
+process.binding = function (name) {
+ throw new Error('process.binding is not supported');
+};
+
+process.cwd = function () { return '/' };
+process.chdir = function (dir) {
+ throw new Error('process.chdir is not supported');
+};
+process.umask = function() { return 0; };
+
+},{}],12:[function(_dereq_,module,exports){
+(function(self) {
+ 'use strict';
+
+ if (self.fetch) {
+ return
+ }
+
+ var support = {
+ searchParams: 'URLSearchParams' in self,
+ iterable: 'Symbol' in self && 'iterator' in Symbol,
+ blob: 'FileReader' in self && 'Blob' in self && (function() {
+ try {
+ new Blob()
+ return true
+ } catch(e) {
+ return false
+ }
+ })(),
+ formData: 'FormData' in self,
+ arrayBuffer: 'ArrayBuffer' in self
+ }
+
+ if (support.arrayBuffer) {
+ var viewClasses = [
+ '[object Int8Array]',
+ '[object Uint8Array]',
+ '[object Uint8ClampedArray]',
+ '[object Int16Array]',
+ '[object Uint16Array]',
+ '[object Int32Array]',
+ '[object Uint32Array]',
+ '[object Float32Array]',
+ '[object Float64Array]'
+ ]
+
+ var isDataView = function(obj) {
+ return obj && DataView.prototype.isPrototypeOf(obj)
+ }
+
+ var isArrayBufferView = ArrayBuffer.isView || function(obj) {
+ return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
+ }
+ }
+
+ function normalizeName(name) {
+ if (typeof name !== 'string') {
+ name = String(name)
+ }
+ if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
+ throw new TypeError('Invalid character in header field name')
+ }
+ return name.toLowerCase()
+ }
+
+ function normalizeValue(value) {
+ if (typeof value !== 'string') {
+ value = String(value)
+ }
+ return value
+ }
+
+ // Build a destructive iterator for the value list
+ function iteratorFor(items) {
+ var iterator = {
+ next: function() {
+ var value = items.shift()
+ return {done: value === undefined, value: value}
+ }
+ }
+
+ if (support.iterable) {
+ iterator[Symbol.iterator] = function() {
+ return iterator
+ }
+ }
+
+ return iterator
+ }
+
+ function Headers(headers) {
+ this.map = {}
+
+ if (headers instanceof Headers) {
+ headers.forEach(function(value, name) {
+ this.append(name, value)
+ }, this)
+ } else if (Array.isArray(headers)) {
+ headers.forEach(function(header) {
+ this.append(header[0], header[1])
+ }, this)
+ } else if (headers) {
+ Object.getOwnPropertyNames(headers).forEach(function(name) {
+ this.append(name, headers[name])
+ }, this)
+ }
+ }
+
+ Headers.prototype.append = function(name, value) {
+ name = normalizeName(name)
+ value = normalizeValue(value)
+ var oldValue = this.map[name]
+ this.map[name] = oldValue ? oldValue+','+value : value
+ }
+
+ Headers.prototype['delete'] = function(name) {
+ delete this.map[normalizeName(name)]
+ }
+
+ Headers.prototype.get = function(name) {
+ name = normalizeName(name)
+ return this.has(name) ? this.map[name] : null
+ }
+
+ Headers.prototype.has = function(name) {
+ return this.map.hasOwnProperty(normalizeName(name))
+ }
+
+ Headers.prototype.set = function(name, value) {
+ this.map[normalizeName(name)] = normalizeValue(value)
+ }
+
+ Headers.prototype.forEach = function(callback, thisArg) {
+ for (var name in this.map) {
+ if (this.map.hasOwnProperty(name)) {
+ callback.call(thisArg, this.map[name], name, this)
+ }
+ }
+ }
+
+ Headers.prototype.keys = function() {
+ var items = []
+ this.forEach(function(value, name) { items.push(name) })
+ return iteratorFor(items)
+ }
+
+ Headers.prototype.values = function() {
+ var items = []
+ this.forEach(function(value) { items.push(value) })
+ return iteratorFor(items)
+ }
+
+ Headers.prototype.entries = function() {
+ var items = []
+ this.forEach(function(value, name) { items.push([name, value]) })
+ return iteratorFor(items)
+ }
+
+ if (support.iterable) {
+ Headers.prototype[Symbol.iterator] = Headers.prototype.entries
+ }
+
+ function consumed(body) {
+ if (body.bodyUsed) {
+ return Promise.reject(new TypeError('Already read'))
+ }
+ body.bodyUsed = true
+ }
+
+ function fileReaderReady(reader) {
+ return new Promise(function(resolve, reject) {
+ reader.onload = function() {
+ resolve(reader.result)
+ }
+ reader.onerror = function() {
+ reject(reader.error)
+ }
+ })
+ }
+
+ function readBlobAsArrayBuffer(blob) {
+ var reader = new FileReader()
+ var promise = fileReaderReady(reader)
+ reader.readAsArrayBuffer(blob)
+ return promise
+ }
+
+ function readBlobAsText(blob) {
+ var reader = new FileReader()
+ var promise = fileReaderReady(reader)
+ reader.readAsText(blob)
+ return promise
+ }
+
+ function readArrayBufferAsText(buf) {
+ var view = new Uint8Array(buf)
+ var chars = new Array(view.length)
+
+ for (var i = 0; i < view.length; i++) {
+ chars[i] = String.fromCharCode(view[i])
+ }
+ return chars.join('')
+ }
+
+ function bufferClone(buf) {
+ if (buf.slice) {
+ return buf.slice(0)
+ } else {
+ var view = new Uint8Array(buf.byteLength)
+ view.set(new Uint8Array(buf))
+ return view.buffer
+ }
+ }
+
+ function Body() {
+ this.bodyUsed = false
+
+ this._initBody = function(body) {
+ this._bodyInit = body
+ if (!body) {
+ this._bodyText = ''
+ } else if (typeof body === 'string') {
+ this._bodyText = body
+ } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
+ this._bodyBlob = body
+ } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
+ this._bodyFormData = body
+ } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
+ this._bodyText = body.toString()
+ } else if (support.arrayBuffer && support.blob && isDataView(body)) {
+ this._bodyArrayBuffer = bufferClone(body.buffer)
+ // IE 10-11 can't handle a DataView body.
+ this._bodyInit = new Blob([this._bodyArrayBuffer])
+ } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
+ this._bodyArrayBuffer = bufferClone(body)
+ } else {
+ throw new Error('unsupported BodyInit type')
+ }
+
+ if (!this.headers.get('content-type')) {
+ if (typeof body === 'string') {
+ this.headers.set('content-type', 'text/plain;charset=UTF-8')
+ } else if (this._bodyBlob && this._bodyBlob.type) {
+ this.headers.set('content-type', this._bodyBlob.type)
+ } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
+ this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')
+ }
+ }
+ }
+
+ if (support.blob) {
+ this.blob = function() {
+ var rejected = consumed(this)
+ if (rejected) {
+ return rejected
+ }
+
+ if (this._bodyBlob) {
+ return Promise.resolve(this._bodyBlob)
+ } else if (this._bodyArrayBuffer) {
+ return Promise.resolve(new Blob([this._bodyArrayBuffer]))
+ } else if (this._bodyFormData) {
+ throw new Error('could not read FormData body as blob')
+ } else {
+ return Promise.resolve(new Blob([this._bodyText]))
+ }
+ }
+
+ this.arrayBuffer = function() {
+ if (this._bodyArrayBuffer) {
+ return consumed(this) || Promise.resolve(this._bodyArrayBuffer)
+ } else {
+ return this.blob().then(readBlobAsArrayBuffer)
+ }
+ }
+ }
+
+ this.text = function() {
+ var rejected = consumed(this)
+ if (rejected) {
+ return rejected
+ }
+
+ if (this._bodyBlob) {
+ return readBlobAsText(this._bodyBlob)
+ } else if (this._bodyArrayBuffer) {
+ return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
+ } else if (this._bodyFormData) {
+ throw new Error('could not read FormData body as text')
+ } else {
+ return Promise.resolve(this._bodyText)
+ }
+ }
+
+ if (support.formData) {
+ this.formData = function() {
+ return this.text().then(decode)
+ }
+ }
+
+ this.json = function() {
+ return this.text().then(JSON.parse)
+ }
+
+ return this
+ }
+
+ // HTTP methods whose capitalization should be normalized
+ var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']
+
+ function normalizeMethod(method) {
+ var upcased = method.toUpperCase()
+ return (methods.indexOf(upcased) > -1) ? upcased : method
+ }
+
+ function Request(input, options) {
+ options = options || {}
+ var body = options.body
+
+ if (input instanceof Request) {
+ if (input.bodyUsed) {
+ throw new TypeError('Already read')
+ }
+ this.url = input.url
+ this.credentials = input.credentials
+ if (!options.headers) {
+ this.headers = new Headers(input.headers)
+ }
+ this.method = input.method
+ this.mode = input.mode
+ if (!body && input._bodyInit != null) {
+ body = input._bodyInit
+ input.bodyUsed = true
+ }
+ } else {
+ this.url = String(input)
+ }
+
+ this.credentials = options.credentials || this.credentials || 'omit'
+ if (options.headers || !this.headers) {
+ this.headers = new Headers(options.headers)
+ }
+ this.method = normalizeMethod(options.method || this.method || 'GET')
+ this.mode = options.mode || this.mode || null
+ this.referrer = null
+
+ if ((this.method === 'GET' || this.method === 'HEAD') && body) {
+ throw new TypeError('Body not allowed for GET or HEAD requests')
+ }
+ this._initBody(body)
+ }
+
+ Request.prototype.clone = function() {
+ return new Request(this, { body: this._bodyInit })
+ }
+
+ function decode(body) {
+ var form = new FormData()
+ body.trim().split('&').forEach(function(bytes) {
+ if (bytes) {
+ var split = bytes.split('=')
+ var name = split.shift().replace(/\+/g, ' ')
+ var value = split.join('=').replace(/\+/g, ' ')
+ form.append(decodeURIComponent(name), decodeURIComponent(value))
+ }
+ })
+ return form
+ }
+
+ function parseHeaders(rawHeaders) {
+ var headers = new Headers()
+ rawHeaders.split(/\r?\n/).forEach(function(line) {
+ var parts = line.split(':')
+ var key = parts.shift().trim()
+ if (key) {
+ var value = parts.join(':').trim()
+ headers.append(key, value)
+ }
+ })
+ return headers
+ }
+
+ Body.call(Request.prototype)
+
+ function Response(bodyInit, options) {
+ if (!options) {
+ options = {}
+ }
+
+ this.type = 'default'
+ this.status = 'status' in options ? options.status : 200
+ this.ok = this.status >= 200 && this.status < 300
+ this.statusText = 'statusText' in options ? options.statusText : 'OK'
+ this.headers = new Headers(options.headers)
+ this.url = options.url || ''
+ this._initBody(bodyInit)
+ }
+
+ Body.call(Response.prototype)
+
+ Response.prototype.clone = function() {
+ return new Response(this._bodyInit, {
+ status: this.status,
+ statusText: this.statusText,
+ headers: new Headers(this.headers),
+ url: this.url
+ })
+ }
+
+ Response.error = function() {
+ var response = new Response(null, {status: 0, statusText: ''})
+ response.type = 'error'
+ return response
+ }
+
+ var redirectStatuses = [301, 302, 303, 307, 308]
+
+ Response.redirect = function(url, status) {
+ if (redirectStatuses.indexOf(status) === -1) {
+ throw new RangeError('Invalid status code')
+ }
+
+ return new Response(null, {status: status, headers: {location: url}})
+ }
+
+ self.Headers = Headers
+ self.Request = Request
+ self.Response = Response
+
+ self.fetch = function(input, init) {
+ return new Promise(function(resolve, reject) {
+ var request = new Request(input, init)
+ var xhr = new XMLHttpRequest()
+
+ xhr.onload = function() {
+ var options = {
+ status: xhr.status,
+ statusText: xhr.statusText,
+ headers: parseHeaders(xhr.getAllResponseHeaders() || '')
+ }
+ options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')
+ var body = 'response' in xhr ? xhr.response : xhr.responseText
+ resolve(new Response(body, options))
+ }
+
+ xhr.onerror = function() {
+ reject(new TypeError('Network request failed'))
+ }
+
+ xhr.ontimeout = function() {
+ reject(new TypeError('Network request failed'))
+ }
+
+ xhr.open(request.method, request.url, true)
+
+ if (request.credentials === 'include') {
+ xhr.withCredentials = true
+ }
+
+ if ('responseType' in xhr && support.blob) {
+ xhr.responseType = 'blob'
+ }
+
+ request.headers.forEach(function(value, name) {
+ xhr.setRequestHeader(name, value)
+ })
+
+ xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
+ })
+ }
+ self.fetch.polyfill = true
+})(typeof self !== 'undefined' ? self : this);
+
+},{}],13:[function(_dereq_,module,exports){
+'use strict';
+
+var p5 = _dereq_('./core/core');
+_dereq_('./color/p5.Color');
+_dereq_('./core/p5.Element');
+_dereq_('./typography/p5.Font');
+_dereq_('./core/p5.Graphics');
+_dereq_('./core/p5.Renderer2D');
+
+_dereq_('./image/p5.Image');
+_dereq_('./math/p5.Vector');
+_dereq_('./io/p5.TableRow');
+_dereq_('./io/p5.Table');
+_dereq_('./io/p5.XML');
+
+_dereq_('./color/creating_reading');
+_dereq_('./color/setting');
+_dereq_('./core/constants');
+_dereq_('./utilities/conversion');
+_dereq_('./utilities/array_functions');
+_dereq_('./utilities/string_functions');
+_dereq_('./core/environment');
+_dereq_('./image/image');
+_dereq_('./image/loading_displaying');
+_dereq_('./image/pixels');
+_dereq_('./io/files');
+_dereq_('./events/keyboard');
+_dereq_('./events/acceleration'); //john
+_dereq_('./events/mouse');
+_dereq_('./utilities/time_date');
+_dereq_('./events/touch');
+_dereq_('./math/math');
+_dereq_('./math/calculation');
+_dereq_('./math/random');
+_dereq_('./math/noise');
+_dereq_('./math/trigonometry');
+_dereq_('./core/rendering');
+_dereq_('./core/2d_primitives');
+
+_dereq_('./core/attributes');
+_dereq_('./core/curves');
+_dereq_('./core/vertex');
+_dereq_('./core/structure');
+_dereq_('./core/transform');
+_dereq_('./typography/attributes');
+_dereq_('./typography/loading_displaying');
+
+_dereq_('./data/p5.TypedDict');
+
+_dereq_('./webgl/p5.RendererGL');
+_dereq_('./webgl/p5.Geometry');
+_dereq_('./webgl/p5.RendererGL.Retained');
+_dereq_('./webgl/p5.RendererGL.Immediate');
+_dereq_('./webgl/primitives');
+_dereq_('./webgl/loading');
+_dereq_('./webgl/p5.Matrix');
+_dereq_('./webgl/material');
+_dereq_('./webgl/light');
+_dereq_('./webgl/p5.Shader');
+_dereq_('./webgl/camera');
+_dereq_('./webgl/interaction');
+
+_dereq_('./core/init.js');
+
+module.exports = p5;
+
+},{"./color/creating_reading":15,"./color/p5.Color":16,"./color/setting":17,"./core/2d_primitives":18,"./core/attributes":19,"./core/constants":21,"./core/core":22,"./core/curves":23,"./core/environment":24,"./core/init.js":26,"./core/p5.Element":27,"./core/p5.Graphics":28,"./core/p5.Renderer2D":30,"./core/rendering":31,"./core/structure":33,"./core/transform":34,"./core/vertex":35,"./data/p5.TypedDict":36,"./events/acceleration":37,"./events/keyboard":38,"./events/mouse":39,"./events/touch":40,"./image/image":42,"./image/loading_displaying":43,"./image/p5.Image":44,"./image/pixels":45,"./io/files":46,"./io/p5.Table":47,"./io/p5.TableRow":48,"./io/p5.XML":49,"./math/calculation":50,"./math/math":51,"./math/noise":52,"./math/p5.Vector":53,"./math/random":54,"./math/trigonometry":55,"./typography/attributes":56,"./typography/loading_displaying":57,"./typography/p5.Font":58,"./utilities/array_functions":59,"./utilities/conversion":60,"./utilities/string_functions":61,"./utilities/time_date":62,"./webgl/camera":63,"./webgl/interaction":64,"./webgl/light":65,"./webgl/loading":66,"./webgl/material":67,"./webgl/p5.Geometry":68,"./webgl/p5.Matrix":69,"./webgl/p5.RendererGL":72,"./webgl/p5.RendererGL.Immediate":70,"./webgl/p5.RendererGL.Retained":71,"./webgl/p5.Shader":73,"./webgl/primitives":75}],14:[function(_dereq_,module,exports){
+/**
+ * @module Conversion
+ * @submodule Color Conversion
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+/**
+ * Conversions adapted from .
+ *
+ * In these functions, hue is always in the range [0,1); all other components
+ * are in the range [0,1]. 'Brightness' and 'value' are used interchangeably.
+ */
+
+var p5 = _dereq_('../core/core');
+p5.ColorConversion = {};
+
+/**
+ * Convert an HSBA array to HSLA.
+ */
+p5.ColorConversion._hsbaToHSLA = function(hsba) {
+ var hue = hsba[0];
+ var sat = hsba[1];
+ var val = hsba[2];
+
+ // Calculate lightness.
+ var li = (2 - sat) * val / 2;
+
+ // Convert saturation.
+ if (li !== 0) {
+ if (li === 1) {
+ sat = 0;
+ } else if (li < 0.5) {
+ sat = sat / (2 - sat);
+ } else {
+ sat = sat * val / (2 - li * 2);
+ }
+ }
+
+ // Hue and alpha stay the same.
+ return [hue, sat, li, hsba[3]];
+};
+
+/**
+ * Convert an HSBA array to RGBA.
+ */
+p5.ColorConversion._hsbaToRGBA = function(hsba) {
+ var hue = hsba[0] * 6; // We will split hue into 6 sectors.
+ var sat = hsba[1];
+ var val = hsba[2];
+
+ var RGBA = [];
+
+ if (sat === 0) {
+ RGBA = [val, val, val, hsba[3]]; // Return early if grayscale.
+ } else {
+ var sector = Math.floor(hue);
+ var tint1 = val * (1 - sat);
+ var tint2 = val * (1 - sat * (hue - sector));
+ var tint3 = val * (1 - sat * (1 + sector - hue));
+ var red, green, blue;
+ if (sector === 1) {
+ // Yellow to green.
+ red = tint2;
+ green = val;
+ blue = tint1;
+ } else if (sector === 2) {
+ // Green to cyan.
+ red = tint1;
+ green = val;
+ blue = tint3;
+ } else if (sector === 3) {
+ // Cyan to blue.
+ red = tint1;
+ green = tint2;
+ blue = val;
+ } else if (sector === 4) {
+ // Blue to magenta.
+ red = tint3;
+ green = tint1;
+ blue = val;
+ } else if (sector === 5) {
+ // Magenta to red.
+ red = val;
+ green = tint1;
+ blue = tint2;
+ } else {
+ // Red to yellow (sector could be 0 or 6).
+ red = val;
+ green = tint3;
+ blue = tint1;
+ }
+ RGBA = [red, green, blue, hsba[3]];
+ }
+
+ return RGBA;
+};
+
+/**
+ * Convert an HSLA array to HSBA.
+ */
+p5.ColorConversion._hslaToHSBA = function(hsla) {
+ var hue = hsla[0];
+ var sat = hsla[1];
+ var li = hsla[2];
+
+ // Calculate brightness.
+ var val;
+ if (li < 0.5) {
+ val = (1 + sat) * li;
+ } else {
+ val = li + sat - li * sat;
+ }
+
+ // Convert saturation.
+ sat = 2 * (val - li) / val;
+
+ // Hue and alpha stay the same.
+ return [hue, sat, val, hsla[3]];
+};
+
+/**
+ * Convert an HSLA array to RGBA.
+ *
+ * We need to change basis from HSLA to something that can be more easily be
+ * projected onto RGBA. We will choose hue and brightness as our first two
+ * components, and pick a convenient third one ('zest') so that we don't need
+ * to calculate formal HSBA saturation.
+ */
+p5.ColorConversion._hslaToRGBA = function(hsla) {
+ var hue = hsla[0] * 6; // We will split hue into 6 sectors.
+ var sat = hsla[1];
+ var li = hsla[2];
+
+ var RGBA = [];
+
+ if (sat === 0) {
+ RGBA = [li, li, li, hsla[3]]; // Return early if grayscale.
+ } else {
+ // Calculate brightness.
+ var val;
+ if (li < 0.5) {
+ val = (1 + sat) * li;
+ } else {
+ val = li + sat - li * sat;
+ }
+
+ // Define zest.
+ var zest = 2 * li - val;
+
+ // Implement projection (project onto green by default).
+ var hzvToRGB = function(hue, zest, val) {
+ if (hue < 0) {
+ // Hue must wrap to allow projection onto red and blue.
+ hue += 6;
+ } else if (hue >= 6) {
+ hue -= 6;
+ }
+ if (hue < 1) {
+ // Red to yellow (increasing green).
+ return zest + (val - zest) * hue;
+ } else if (hue < 3) {
+ // Yellow to cyan (greatest green).
+ return val;
+ } else if (hue < 4) {
+ // Cyan to blue (decreasing green).
+ return zest + (val - zest) * (4 - hue);
+ } else {
+ // Blue to red (least green).
+ return zest;
+ }
+ };
+
+ // Perform projections, offsetting hue as necessary.
+ RGBA = [
+ hzvToRGB(hue + 2, zest, val),
+ hzvToRGB(hue, zest, val),
+ hzvToRGB(hue - 2, zest, val),
+ hsla[3]
+ ];
+ }
+
+ return RGBA;
+};
+
+/**
+ * Convert an RGBA array to HSBA.
+ */
+p5.ColorConversion._rgbaToHSBA = function(rgba) {
+ var red = rgba[0];
+ var green = rgba[1];
+ var blue = rgba[2];
+
+ var val = Math.max(red, green, blue);
+ var chroma = val - Math.min(red, green, blue);
+
+ var hue, sat;
+ if (chroma === 0) {
+ // Return early if grayscale.
+ hue = 0;
+ sat = 0;
+ } else {
+ sat = chroma / val;
+ if (red === val) {
+ // Magenta to yellow.
+ hue = (green - blue) / chroma;
+ } else if (green === val) {
+ // Yellow to cyan.
+ hue = 2 + (blue - red) / chroma;
+ } else if (blue === val) {
+ // Cyan to magenta.
+ hue = 4 + (red - green) / chroma;
+ }
+ if (hue < 0) {
+ // Confine hue to the interval [0, 1).
+ hue += 6;
+ } else if (hue >= 6) {
+ hue -= 6;
+ }
+ }
+
+ return [hue / 6, sat, val, rgba[3]];
+};
+
+/**
+ * Convert an RGBA array to HSLA.
+ */
+p5.ColorConversion._rgbaToHSLA = function(rgba) {
+ var red = rgba[0];
+ var green = rgba[1];
+ var blue = rgba[2];
+
+ var val = Math.max(red, green, blue);
+ var min = Math.min(red, green, blue);
+ var li = val + min; // We will halve this later.
+ var chroma = val - min;
+
+ var hue, sat;
+ if (chroma === 0) {
+ // Return early if grayscale.
+ hue = 0;
+ sat = 0;
+ } else {
+ if (li < 1) {
+ sat = chroma / li;
+ } else {
+ sat = chroma / (2 - li);
+ }
+ if (red === val) {
+ // Magenta to yellow.
+ hue = (green - blue) / chroma;
+ } else if (green === val) {
+ // Yellow to cyan.
+ hue = 2 + (blue - red) / chroma;
+ } else if (blue === val) {
+ // Cyan to magenta.
+ hue = 4 + (red - green) / chroma;
+ }
+ if (hue < 0) {
+ // Confine hue to the interval [0, 1).
+ hue += 6;
+ } else if (hue >= 6) {
+ hue -= 6;
+ }
+ }
+
+ return [hue / 6, sat, li / 2, rgba[3]];
+};
+
+module.exports = p5.ColorConversion;
+
+},{"../core/core":22}],15:[function(_dereq_,module,exports){
+/**
+ * @module Color
+ * @submodule Creating & Reading
+ * @for p5
+ * @requires core
+ * @requires constants
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+var constants = _dereq_('../core/constants');
+_dereq_('./p5.Color');
+_dereq_('../core/error_helpers');
+
+/**
+ * Extracts the alpha value from a color or pixel array.
+ *
+ * @method alpha
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the alpha value
+ * @example
+ *
+ *
+ * noStroke();
+ * var c = color(0, 126, 255, 102);
+ * fill(c);
+ * rect(15, 15, 35, 70);
+ * var value = alpha(c); // Sets 'value' to 102
+ * fill(value);
+ * rect(50, 15, 35, 70);
+ *
+ *
+ *
+ * @alt
+ * Left half of canvas light blue and right half light charcoal grey.
+ * Left half of canvas light purple and right half a royal blue.
+ * Left half of canvas salmon pink and the right half white.
+ * Yellow rect in middle right of canvas, with 55 pixel width and height.
+ * Yellow ellipse in top left canvas, black ellipse in bottom right,both 80x80.
+ * Bright fuschia rect in middle of canvas, 60 pixel width and height.
+ * Two bright green rects on opposite sides of the canvas, both 45x80.
+ * Four blue rects in each corner of the canvas, each are 35x35.
+ * Bright sea green rect on left and darker rect on right of canvas, both 45x80.
+ * Dark green rect on left and light green rect on right of canvas, both 45x80.
+ * Dark blue rect on left and light teal rect on right of canvas, both 45x80.
+ * blue rect on left and green on right, both with black outlines & 35x60.
+ * salmon pink rect on left and black on right, both 35x60.
+ * 4 rects, tan, brown, brownish purple and purple, with white outlines & 20x60.
+ * light pastel green rect on left and dark grey rect on right, both 35x60.
+ * yellow rect on left and red rect on right, both with black outlines & 35x60.
+ * grey canvas
+ * deep pink rect on left and grey rect on right, both 35x60.
+ */
+p5.prototype.alpha = function(c) {
+ p5._validateParameters('alpha', arguments);
+ return this.color(c)._getAlpha();
+};
+
+/**
+ * Extracts the blue value from a color or pixel array.
+ *
+ * @method blue
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the blue value
+ * @example
+ *
+ *
+ * var c = color(175, 100, 220); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ *
+ * var blueValue = blue(c); // Get blue in 'c'
+ * print(blueValue); // Prints "220.0"
+ * fill(0, 0, blueValue); // Use 'blueValue' in new fill
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ *
+ *
+ *
+ * @alt
+ * Left half of canvas light purple and right half a royal blue.
+ *
+ */
+p5.prototype.blue = function(c) {
+ p5._validateParameters('blue', arguments);
+ return this.color(c)._getBlue();
+};
+
+/**
+ * Extracts the HSB brightness value from a color or pixel array.
+ *
+ * @method brightness
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the brightness value
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * var c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * var value = brightness(c); // Sets 'value' to 255
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ *
+ * @alt
+ * Left half of canvas salmon pink and the right half white.
+ *
+ */
+p5.prototype.brightness = function(c) {
+ p5._validateParameters('brightness', arguments);
+ return this.color(c)._getBrightness();
+};
+
+/**
+ * Creates colors for storing in variables of the color datatype. The
+ * parameters are interpreted as RGB or HSB values depending on the
+ * current colorMode(). The default mode is RGB values from 0 to 255
+ * and, therefore, the function call color(255, 204, 0) will return a
+ * bright yellow color.
+ *
+ * Note that if only one value is provided to color(), it will be interpreted
+ * as a grayscale value. Add a second value, and it will be used for alpha
+ * transparency. When three values are specified, they are interpreted as
+ * either RGB or HSB values. Adding a fourth value applies alpha
+ * transparency.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color
+ * strings and all named color strings are supported. In this case, an alpha
+ * number value as a second argument is not supported, the RGBA form should be
+ * used.
+ *
+ * @method color
+ * @param {Number} gray number specifying value between white
+ * and black.
+ * @param {Number} [alpha] alpha value relative to current color range
+ * (default is 0-255)
+ * @return {p5.Color} resulting color
+ *
+ * @example
+ *
+ *
+ * var c = color(255, 204, 0); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * noStroke(); // Don't draw a stroke around shapes
+ * rect(30, 20, 55, 55); // Draw rectangle
+ *
+ *
+ *
+ *
+ *
+ * var c = color(255, 204, 0); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * noStroke(); // Don't draw a stroke around shapes
+ * ellipse(25, 25, 80, 80); // Draw left circle
+ *
+ * // Using only one value with color()
+ * // generates a grayscale value.
+ * c = color(65); // Update 'c' with grayscale value
+ * fill(c); // Use updated 'c' as fill color
+ * ellipse(75, 75, 80, 80); // Draw right circle
+ *
+ *
+ *
+ *
+ *
+ * // Named SVG & CSS colors may be used,
+ * var c = color('magenta');
+ * fill(c); // Use 'c' as fill color
+ * noStroke(); // Don't draw a stroke around shapes
+ * rect(20, 20, 60, 60); // Draw rectangle
+ *
+ *
+ *
+ *
+ *
+ * // as can hex color codes:
+ * noStroke(); // Don't draw a stroke around shapes
+ * var c = color('#0f0');
+ * fill(c); // Use 'c' as fill color
+ * rect(0, 10, 45, 80); // Draw rectangle
+ *
+ * c = color('#00ff00');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 10, 45, 80); // Draw rectangle
+ *
+ *
+ *
+ *
+ *
+ * // RGB and RGBA color strings are also supported:
+ * // these all set to the same color (solid blue)
+ * var c;
+ * noStroke(); // Don't draw a stroke around shapes
+ * c = color('rgb(0,0,255)');
+ * fill(c); // Use 'c' as fill color
+ * rect(10, 10, 35, 35); // Draw rectangle
+ *
+ * c = color('rgb(0%, 0%, 100%)');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 10, 35, 35); // Draw rectangle
+ *
+ * c = color('rgba(0, 0, 255, 1)');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(10, 55, 35, 35); // Draw rectangle
+ *
+ * c = color('rgba(0%, 0%, 100%, 1)');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 55, 35, 35); // Draw rectangle
+ *
+ *
+ *
+ *
+ *
+ * // HSL color is also supported and can be specified
+ * // by value
+ * var c;
+ * noStroke(); // Don't draw a stroke around shapes
+ * c = color('hsl(160, 100%, 50%)');
+ * fill(c); // Use 'c' as fill color
+ * rect(0, 10, 45, 80); // Draw rectangle
+ *
+ * c = color('hsla(160, 100%, 50%, 0.5)');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 10, 45, 80); // Draw rectangle
+ *
+ *
+ *
+ *
+ *
+ * // HSB color is also supported and can be specified
+ * // by value
+ * var c;
+ * noStroke(); // Don't draw a stroke around shapes
+ * c = color('hsb(160, 100%, 50%)');
+ * fill(c); // Use 'c' as fill color
+ * rect(0, 10, 45, 80); // Draw rectangle
+ *
+ * c = color('hsba(160, 100%, 50%, 0.5)');
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 10, 45, 80); // Draw rectangle
+ *
+ *
+ *
+ *
+ *
+ * var c; // Declare color 'c'
+ * noStroke(); // Don't draw a stroke around shapes
+ *
+ * // If no colorMode is specified, then the
+ * // default of RGB with scale of 0-255 is used.
+ * c = color(50, 55, 100); // Create a color for 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(0, 10, 45, 80); // Draw left rect
+ *
+ * colorMode(HSB, 100); // Use HSB with scale of 0-100
+ * c = color(50, 55, 100); // Update 'c' with new color
+ * fill(c); // Use updated 'c' as fill color
+ * rect(55, 10, 45, 80); // Draw right rect
+ *
+ *
+ *
+ * @alt
+ * Yellow rect in middle right of canvas, with 55 pixel width and height.
+ * Yellow ellipse in top left of canvas, black ellipse in bottom right,both 80x80.
+ * Bright fuschia rect in middle of canvas, 60 pixel width and height.
+ * Two bright green rects on opposite sides of the canvas, both 45x80.
+ * Four blue rects in each corner of the canvas, each are 35x35.
+ * Bright sea green rect on left and darker rect on right of canvas, both 45x80.
+ * Dark green rect on left and lighter green rect on right of canvas, both 45x80.
+ * Dark blue rect on left and light teal rect on right of canvas, both 45x80.
+ *
+ */
+/**
+ * @method color
+ * @param {Number} v1 red or hue value relative to
+ * the current color range
+ * @param {Number} v2 green or saturation value
+ * relative to the current color range
+ * @param {Number} v3 blue or brightness value
+ * relative to the current color range
+ * @param {Number} [alpha]
+ * @return {p5.Color}
+ */
+
+/**
+ * @method color
+ * @param {String} value a color string
+ * @return {p5.Color}
+ */
+/**
+ * @method color
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and alpha components of the color
+ * @return {p5.Color}
+ */
+/**
+ * @method color
+ * @param {p5.Color} color
+ * @return {p5.Color}
+ */
+
+p5.prototype.color = function() {
+ p5._validateParameters('color', arguments);
+ if (arguments[0] instanceof p5.Color) {
+ return arguments[0]; // Do nothing if argument is already a color object.
+ }
+
+ var args = arguments[0] instanceof Array ? arguments[0] : arguments;
+ return new p5.Color(this, args);
+};
+
+/**
+ * Extracts the green value from a color or pixel array.
+ *
+ * @method green
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the green value
+ * @example
+ *
+ *
+ * var c = color(20, 75, 200); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ *
+ * var greenValue = green(c); // Get green in 'c'
+ * print(greenValue); // Print "75.0"
+ * fill(0, greenValue, 0); // Use 'greenValue' in new fill
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ *
+ *
+ *
+ * @alt
+ * blue rect on left and green on right, both with black outlines & 35x60.
+ *
+ */
+
+p5.prototype.green = function(c) {
+ p5._validateParameters('green', arguments);
+ return this.color(c)._getGreen();
+};
+
+/**
+ * Extracts the hue value from a color or pixel array.
+ *
+ * Hue exists in both HSB and HSL. This function will return the
+ * HSB-normalized hue when supplied with an HSB color object (or when supplied
+ * with a pixel array while the color mode is HSB), but will default to the
+ * HSL-normalized hue otherwise. (The values will only be different if the
+ * maximum hue setting for each system is different.)
+ *
+ * @method hue
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the hue
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * var c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * var value = hue(c); // Sets 'value' to "0"
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ *
+ * @alt
+ * salmon pink rect on left and black on right, both 35x60.
+ *
+ */
+
+p5.prototype.hue = function(c) {
+ p5._validateParameters('hue', arguments);
+ return this.color(c)._getHue();
+};
+
+/**
+ * Blends two colors to find a third color somewhere between them. The amt
+ * parameter is the amount to interpolate between the two values where 0.0
+ * equal to the first color, 0.1 is very near the first color, 0.5 is halfway
+ * in between, etc. An amount below 0 will be treated as 0. Likewise, amounts
+ * above 1 will be capped at 1. This is different from the behavior of lerp(),
+ * but necessary because otherwise numbers outside the range will produce
+ * strange and unexpected colors.
+ *
+ * The way that colours are interpolated depends on the current color mode.
+ *
+ * @method lerpColor
+ * @param {p5.Color} c1 interpolate from this color
+ * @param {p5.Color} c2 interpolate to this color
+ * @param {Number} amt number between 0 and 1
+ * @return {p5.Color} interpolated color
+ * @example
+ *
+ *
+ * colorMode(RGB);
+ * stroke(255);
+ * background(51);
+ * var from = color(218, 165, 32);
+ * var to = color(72, 61, 139);
+ * colorMode(RGB); // Try changing to HSB.
+ * var interA = lerpColor(from, to, 0.33);
+ * var interB = lerpColor(from, to, 0.66);
+ * fill(from);
+ * rect(10, 20, 20, 60);
+ * fill(interA);
+ * rect(30, 20, 20, 60);
+ * fill(interB);
+ * rect(50, 20, 20, 60);
+ * fill(to);
+ * rect(70, 20, 20, 60);
+ *
+ *
+ *
+ * @alt
+ * 4 rects one tan, brown, brownish purple, purple, with white outlines & 20x60
+ *
+ */
+
+p5.prototype.lerpColor = function(c1, c2, amt) {
+ p5._validateParameters('lerpColor', arguments);
+ var mode = this._colorMode;
+ var maxes = this._colorMaxes;
+ var l0, l1, l2, l3;
+ var fromArray, toArray;
+
+ if (mode === constants.RGB) {
+ fromArray = c1.levels.map(function(level) {
+ return level / 255;
+ });
+ toArray = c2.levels.map(function(level) {
+ return level / 255;
+ });
+ } else if (mode === constants.HSB) {
+ c1._getBrightness(); // Cache hsba so it definitely exists.
+ c2._getBrightness();
+ fromArray = c1.hsba;
+ toArray = c2.hsba;
+ } else if (mode === constants.HSL) {
+ c1._getLightness(); // Cache hsla so it definitely exists.
+ c2._getLightness();
+ fromArray = c1.hsla;
+ toArray = c2.hsla;
+ } else {
+ throw new Error(mode + 'cannot be used for interpolation.');
+ }
+
+ // Prevent extrapolation.
+ amt = Math.max(Math.min(amt, 1), 0);
+
+ // Define lerp here itself if user isn't using math module.
+ // Maintains the definition as found in math/calculation.js
+ if (typeof this.lerp === 'undefined') {
+ this.lerp = function(start, stop, amt) {
+ return amt * (stop - start) + start;
+ };
+ }
+
+ // Perform interpolation.
+ l0 = this.lerp(fromArray[0], toArray[0], amt);
+ l1 = this.lerp(fromArray[1], toArray[1], amt);
+ l2 = this.lerp(fromArray[2], toArray[2], amt);
+ l3 = this.lerp(fromArray[3], toArray[3], amt);
+
+ // Scale components.
+ l0 *= maxes[mode][0];
+ l1 *= maxes[mode][1];
+ l2 *= maxes[mode][2];
+ l3 *= maxes[mode][3];
+
+ return this.color(l0, l1, l2, l3);
+};
+
+/**
+ * Extracts the HSL lightness value from a color or pixel array.
+ *
+ * @method lightness
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the lightness
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSL);
+ * var c = color(156, 100, 50, 1);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * var value = lightness(c); // Sets 'value' to 50
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ *
+ * @alt
+ * light pastel green rect on left and dark grey rect on right, both 35x60.
+ *
+ */
+p5.prototype.lightness = function(c) {
+ p5._validateParameters('lightness', arguments);
+ return this.color(c)._getLightness();
+};
+
+/**
+ * Extracts the red value from a color or pixel array.
+ *
+ * @method red
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the red value
+ * @example
+ *
+ *
+ * var c = color(255, 204, 0); // Define color 'c'
+ * fill(c); // Use color variable 'c' as fill color
+ * rect(15, 20, 35, 60); // Draw left rectangle
+ *
+ * var redValue = red(c); // Get red in 'c'
+ * print(redValue); // Print "255.0"
+ * fill(redValue, 0, 0); // Use 'redValue' in new fill
+ * rect(50, 20, 35, 60); // Draw right rectangle
+ *
+ *
+ *
+ *
+ *
+ * colorMode(RGB, 255);
+ * var c = color(127, 255, 0);
+ * colorMode(RGB, 1);
+ * var myColor = red(c);
+ * print(myColor);
+ *
+ *
+ *
+ * @alt
+ * yellow rect on left and red rect on right, both with black outlines and 35x60.
+ * grey canvas
+ */
+p5.prototype.red = function(c) {
+ p5._validateParameters('red', arguments);
+ return this.color(c)._getRed();
+};
+
+/**
+ * Extracts the saturation value from a color or pixel array.
+ *
+ * Saturation is scaled differently in HSB and HSL. This function will return
+ * the HSB saturation when supplied with an HSB color object (or when supplied
+ * with a pixel array while the color mode is HSB), but will default to the
+ * HSL saturation otherwise.
+ *
+ * @method saturation
+ * @param {p5.Color|Number[]|String} color p5.Color object, color components,
+ * or CSS color
+ * @return {Number} the saturation value
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 255);
+ * var c = color(0, 126, 255);
+ * fill(c);
+ * rect(15, 20, 35, 60);
+ * var value = saturation(c); // Sets 'value' to 126
+ * fill(value);
+ * rect(50, 20, 35, 60);
+ *
+ *
+ *
+ * @alt
+ *deep pink rect on left and grey rect on right, both 35x60.
+ *
+ */
+
+p5.prototype.saturation = function(c) {
+ p5._validateParameters('saturation', arguments);
+ return this.color(c)._getSaturation();
+};
+
+module.exports = p5;
+
+},{"../core/constants":21,"../core/core":22,"../core/error_helpers":25,"./p5.Color":16}],16:[function(_dereq_,module,exports){
+/**
+ * @module Color
+ * @submodule Creating & Reading
+ * @for p5
+ * @requires core
+ * @requires constants
+ * @requires color_conversion
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+var constants = _dereq_('../core/constants');
+var color_conversion = _dereq_('./color_conversion');
+
+/**
+ * Each color stores the color mode and level maxes that applied at the
+ * time of its construction. These are used to interpret the input arguments
+ * (at construction and later for that instance of color) and to format the
+ * output e.g. when saturation() is requested.
+ *
+ * Internally we store an array representing the ideal RGBA values in floating
+ * point form, normalized from 0 to 1. From this we calculate the closest
+ * screen color (RGBA levels from 0 to 255) and expose this to the renderer.
+ *
+ * We also cache normalized, floating point components of the color in various
+ * representations as they are calculated. This is done to prevent repeating a
+ * conversion that has already been performed.
+ *
+ * @class p5.Color
+ */
+p5.Color = function(pInst, vals) {
+ // Record color mode and maxes at time of construction.
+ this._storeModeAndMaxes(pInst._colorMode, pInst._colorMaxes);
+
+ // Calculate normalized RGBA values.
+ if (
+ this.mode !== constants.RGB &&
+ this.mode !== constants.HSL &&
+ this.mode !== constants.HSB
+ ) {
+ throw new Error(this.mode + ' is an invalid colorMode.');
+ } else {
+ this._array = p5.Color._parseInputs.apply(this, vals);
+ }
+
+ // Expose closest screen color.
+ this._calculateLevels();
+ return this;
+};
+
+/**
+ * This function returns the color formatted as a string. This can be useful
+ * for debugging, or for using p5.js with other libraries.
+ * @method toString
+ * @param {String} [format] How the color string will be formatted.
+ * Leaving this empty formats the string as rgba(r, g, b, a).
+ * '#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes.
+ * 'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode.
+ * 'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels.
+ * 'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages.
+ * @return {String} the formatted string
+ * @example
+ *
+ *
+ * var myColor;
+ * function setup() {
+ * createCanvas(200, 200);
+ * stroke(255);
+ * myColor = color(100, 100, 250);
+ * fill(myColor);
+ * }
+ *
+ * function draw() {
+ * text(myColor.toString(), 10, 10);
+ * text(myColor.toString('#rrggbb'), 10, 95);
+ * text(myColor.toString('rgba%'), 10, 180);
+ * }
+ *
+ *
+ *
+ * @alt
+ * canvas with text representation of color
+ */
+p5.Color.prototype.toString = function(format) {
+ if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array);
+ if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array);
+
+ var a = this.levels;
+ var f = this._array;
+ var alpha = f[3]; // String representation uses normalized alpha
+
+ switch (format) {
+ case '#rrggbb':
+ return '#'.concat(
+ a[0] < 16 ? '0'.concat(a[0].toString(16)) : a[0].toString(16),
+ a[1] < 16 ? '0'.concat(a[1].toString(16)) : a[1].toString(16),
+ a[2] < 16 ? '0'.concat(a[2].toString(16)) : a[2].toString(16)
+ );
+
+ case '#rrggbbaa':
+ return '#'.concat(
+ a[0] < 16 ? '0'.concat(a[0].toString(16)) : a[0].toString(16),
+ a[1] < 16 ? '0'.concat(a[1].toString(16)) : a[1].toString(16),
+ a[2] < 16 ? '0'.concat(a[2].toString(16)) : a[2].toString(16),
+ a[3] < 16 ? '0'.concat(a[2].toString(16)) : a[3].toString(16)
+ );
+
+ case '#rgb':
+ return '#'.concat(
+ Math.round(f[0] * 15).toString(16),
+ Math.round(f[1] * 15).toString(16),
+ Math.round(f[2] * 15).toString(16)
+ );
+
+ case '#rgba':
+ return '#'.concat(
+ Math.round(f[0] * 15).toString(16),
+ Math.round(f[1] * 15).toString(16),
+ Math.round(f[2] * 15).toString(16),
+ Math.round(f[3] * 15).toString(16)
+ );
+
+ case 'rgb':
+ return 'rgb('.concat(a[0], ', ', a[1], ', ', a[2], ')');
+
+ case 'rgb%':
+ return 'rgb('.concat(
+ (100 * f[0]).toPrecision(3),
+ '%, ',
+ (100 * f[1]).toPrecision(3),
+ '%, ',
+ (100 * f[2]).toPrecision(3),
+ '%)'
+ );
+
+ case 'rgba%':
+ return 'rgba('.concat(
+ (100 * f[0]).toPrecision(3),
+ '%, ',
+ (100 * f[1]).toPrecision(3),
+ '%, ',
+ (100 * f[2]).toPrecision(3),
+ '%, ',
+ (100 * f[3]).toPrecision(3),
+ '%)'
+ );
+
+ case 'hsb':
+ case 'hsv':
+ return 'hsb('.concat(
+ this.hsba[0] * this.maxes[constants.HSB][0],
+ ', ',
+ this.hsba[1] * this.maxes[constants.HSB][1],
+ ', ',
+ this.hsba[2] * this.maxes[constants.HSB][2],
+ ')'
+ );
+
+ case 'hsb%':
+ case 'hsv%':
+ return 'hsb('.concat(
+ (100 * this.hsba[0]).toPrecision(3),
+ '%, ',
+ (100 * this.hsba[1]).toPrecision(3),
+ '%, ',
+ (100 * this.hsba[2]).toPrecision(3),
+ '%)'
+ );
+
+ case 'hsba':
+ case 'hsva':
+ return 'hsba('.concat(
+ this.hsba[0] * this.maxes[constants.HSB][0],
+ ', ',
+ this.hsba[1] * this.maxes[constants.HSB][1],
+ ', ',
+ this.hsba[2] * this.maxes[constants.HSB][2],
+ ', ',
+ alpha,
+ ')'
+ );
+
+ case 'hsba%':
+ case 'hsva%':
+ return 'hsba('.concat(
+ (100 * this.hsba[0]).toPrecision(3),
+ '%, ',
+ (100 * this.hsba[1]).toPrecision(3),
+ '%, ',
+ (100 * this.hsba[2]).toPrecision(3),
+ '%, ',
+ (100 * alpha).toPrecision(3),
+ '%)'
+ );
+
+ case 'hsl':
+ return 'hsl('.concat(
+ this.hsla[0] * this.maxes[constants.HSL][0],
+ ', ',
+ this.hsla[1] * this.maxes[constants.HSL][1],
+ ', ',
+ this.hsla[2] * this.maxes[constants.HSL][2],
+ ')'
+ );
+
+ case 'hsl%':
+ return 'hsl('.concat(
+ (100 * this.hsla[0]).toPrecision(3),
+ '%, ',
+ (100 * this.hsla[1]).toPrecision(3),
+ '%, ',
+ (100 * this.hsla[2]).toPrecision(3),
+ '%)'
+ );
+
+ case 'hsla':
+ return 'hsla('.concat(
+ this.hsla[0] * this.maxes[constants.HSL][0],
+ ', ',
+ this.hsla[1] * this.maxes[constants.HSL][1],
+ ', ',
+ this.hsla[2] * this.maxes[constants.HSL][2],
+ ', ',
+ alpha,
+ ')'
+ );
+
+ case 'hsla%':
+ return 'hsl('.concat(
+ (100 * this.hsla[0]).toPrecision(3),
+ '%, ',
+ (100 * this.hsla[1]).toPrecision(3),
+ '%, ',
+ (100 * this.hsla[2]).toPrecision(3),
+ '%, ',
+ (100 * alpha).toPrecision(3),
+ '%)'
+ );
+
+ case 'rgba':
+ default:
+ return 'rgba(' + a[0] + ',' + a[1] + ',' + a[2] + ',' + alpha + ')';
+ }
+};
+
+/**
+ * @method setRed
+ * @param {Number} red the new red value
+ * @example
+ *
+ *
+ * var backgroundColor;
+ *
+ * function setup() {
+ * backgroundColor = color(100, 50, 150);
+ * }
+ *
+ * function draw() {
+ * backgroundColor.setRed(128 + 128 * sin(millis() / 1000));
+ * background(backgroundColor);
+ * }
+ *
+ *
+ *
+ * @alt
+ * canvas with gradually changing background color
+ */
+p5.Color.prototype.setRed = function(new_red) {
+ this._array[0] = new_red / this.maxes[constants.RGB][0];
+ this._calculateLevels();
+};
+
+/**
+ * @method setGreen
+ * @param {Number} green the new green value
+ * @example
+ *
+ *
+ * var backgroundColor;
+ *
+ * function setup() {
+ * backgroundColor = color(100, 50, 150);
+ * }
+ *
+ * function draw() {
+ * backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));
+ * background(backgroundColor);
+ * }
+ *
+ *
+ *
+ * @alt
+ * canvas with gradually changing background color
+ **/
+p5.Color.prototype.setGreen = function(new_green) {
+ this._array[1] = new_green / this.maxes[constants.RGB][1];
+ this._calculateLevels();
+};
+
+/**
+ * @method setBlue
+ * @param {Number} blue the new blue value
+ * @example
+ *
+ *
+ * var backgroundColor;
+ *
+ * function setup() {
+ * backgroundColor = color(100, 50, 150);
+ * }
+ *
+ * function draw() {
+ * backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));
+ * background(backgroundColor);
+ * }
+ *
+ *
+ *
+ * @alt
+ * canvas with gradually changing background color
+ **/
+p5.Color.prototype.setBlue = function(new_blue) {
+ this._array[2] = new_blue / this.maxes[constants.RGB][2];
+ this._calculateLevels();
+};
+
+/**
+ * @method setAlpha
+ * @param {Number} alpha the new alpha value
+ * @example
+ *
+ *
+ * var squareColor;
+ *
+ * function setup() {
+ * ellipseMode(CORNERS);
+ * strokeWeight(4);
+ * squareColor = color(100, 50, 150);
+ * }
+ *
+ * function draw() {
+ * background(255);
+ *
+ * noFill();
+ * stroke(0);
+ * ellipse(10, 10, width - 10, height - 10);
+ *
+ * squareColor.setAlpha(128 + 128 * sin(millis() / 1000));
+ * fill(squareColor);
+ * noStroke();
+ * rect(13, 13, width - 26, height - 26);
+ * }
+ *
+ *
+ *
+ * @alt
+ * circle behind a square with gradually changing opacity
+ **/
+p5.Color.prototype.setAlpha = function(new_alpha) {
+ this._array[3] = new_alpha / this.maxes[this.mode][3];
+ this._calculateLevels();
+};
+
+// calculates and stores the closest screen levels
+p5.Color.prototype._calculateLevels = function() {
+ this.levels = this._array.map(function(level) {
+ return Math.round(level * 255);
+ });
+};
+
+p5.Color.prototype._getAlpha = function() {
+ return this._array[3] * this.maxes[this.mode][3];
+};
+
+// stores the color mode and maxes in this instance of Color
+// for later use (by _parseInputs())
+p5.Color.prototype._storeModeAndMaxes = function(new_mode, new_maxes) {
+ this.mode = new_mode;
+ this.maxes = new_maxes;
+};
+
+p5.Color.prototype._getMode = function() {
+ return this.mode;
+};
+
+p5.Color.prototype._getMaxes = function() {
+ return this.maxes;
+};
+
+p5.Color.prototype._getBlue = function() {
+ return this._array[2] * this.maxes[constants.RGB][2];
+};
+
+p5.Color.prototype._getBrightness = function() {
+ if (!this.hsba) {
+ this.hsba = color_conversion._rgbaToHSBA(this._array);
+ }
+ return this.hsba[2] * this.maxes[constants.HSB][2];
+};
+
+p5.Color.prototype._getGreen = function() {
+ return this._array[1] * this.maxes[constants.RGB][1];
+};
+
+/**
+ * Hue is the same in HSB and HSL, but the maximum value may be different.
+ * This function will return the HSB-normalized saturation when supplied with
+ * an HSB color object, but will default to the HSL-normalized saturation
+ * otherwise.
+ */
+p5.Color.prototype._getHue = function() {
+ if (this.mode === constants.HSB) {
+ if (!this.hsba) {
+ this.hsba = color_conversion._rgbaToHSBA(this._array);
+ }
+ return this.hsba[0] * this.maxes[constants.HSB][0];
+ } else {
+ if (!this.hsla) {
+ this.hsla = color_conversion._rgbaToHSLA(this._array);
+ }
+ return this.hsla[0] * this.maxes[constants.HSL][0];
+ }
+};
+
+p5.Color.prototype._getLightness = function() {
+ if (!this.hsla) {
+ this.hsla = color_conversion._rgbaToHSLA(this._array);
+ }
+ return this.hsla[2] * this.maxes[constants.HSL][2];
+};
+
+p5.Color.prototype._getRed = function() {
+ return this._array[0] * this.maxes[constants.RGB][0];
+};
+
+/**
+ * Saturation is scaled differently in HSB and HSL. This function will return
+ * the HSB saturation when supplied with an HSB color object, but will default
+ * to the HSL saturation otherwise.
+ */
+p5.Color.prototype._getSaturation = function() {
+ if (this.mode === constants.HSB) {
+ if (!this.hsba) {
+ this.hsba = color_conversion._rgbaToHSBA(this._array);
+ }
+ return this.hsba[1] * this.maxes[constants.HSB][1];
+ } else {
+ if (!this.hsla) {
+ this.hsla = color_conversion._rgbaToHSLA(this._array);
+ }
+ return this.hsla[1] * this.maxes[constants.HSL][1];
+ }
+};
+
+/**
+ * CSS named colors.
+ */
+var namedColors = {
+ aliceblue: '#f0f8ff',
+ antiquewhite: '#faebd7',
+ aqua: '#00ffff',
+ aquamarine: '#7fffd4',
+ azure: '#f0ffff',
+ beige: '#f5f5dc',
+ bisque: '#ffe4c4',
+ black: '#000000',
+ blanchedalmond: '#ffebcd',
+ blue: '#0000ff',
+ blueviolet: '#8a2be2',
+ brown: '#a52a2a',
+ burlywood: '#deb887',
+ cadetblue: '#5f9ea0',
+ chartreuse: '#7fff00',
+ chocolate: '#d2691e',
+ coral: '#ff7f50',
+ cornflowerblue: '#6495ed',
+ cornsilk: '#fff8dc',
+ crimson: '#dc143c',
+ cyan: '#00ffff',
+ darkblue: '#00008b',
+ darkcyan: '#008b8b',
+ darkgoldenrod: '#b8860b',
+ darkgray: '#a9a9a9',
+ darkgreen: '#006400',
+ darkgrey: '#a9a9a9',
+ darkkhaki: '#bdb76b',
+ darkmagenta: '#8b008b',
+ darkolivegreen: '#556b2f',
+ darkorange: '#ff8c00',
+ darkorchid: '#9932cc',
+ darkred: '#8b0000',
+ darksalmon: '#e9967a',
+ darkseagreen: '#8fbc8f',
+ darkslateblue: '#483d8b',
+ darkslategray: '#2f4f4f',
+ darkslategrey: '#2f4f4f',
+ darkturquoise: '#00ced1',
+ darkviolet: '#9400d3',
+ deeppink: '#ff1493',
+ deepskyblue: '#00bfff',
+ dimgray: '#696969',
+ dimgrey: '#696969',
+ dodgerblue: '#1e90ff',
+ firebrick: '#b22222',
+ floralwhite: '#fffaf0',
+ forestgreen: '#228b22',
+ fuchsia: '#ff00ff',
+ gainsboro: '#dcdcdc',
+ ghostwhite: '#f8f8ff',
+ gold: '#ffd700',
+ goldenrod: '#daa520',
+ gray: '#808080',
+ green: '#008000',
+ greenyellow: '#adff2f',
+ grey: '#808080',
+ honeydew: '#f0fff0',
+ hotpink: '#ff69b4',
+ indianred: '#cd5c5c',
+ indigo: '#4b0082',
+ ivory: '#fffff0',
+ khaki: '#f0e68c',
+ lavender: '#e6e6fa',
+ lavenderblush: '#fff0f5',
+ lawngreen: '#7cfc00',
+ lemonchiffon: '#fffacd',
+ lightblue: '#add8e6',
+ lightcoral: '#f08080',
+ lightcyan: '#e0ffff',
+ lightgoldenrodyellow: '#fafad2',
+ lightgray: '#d3d3d3',
+ lightgreen: '#90ee90',
+ lightgrey: '#d3d3d3',
+ lightpink: '#ffb6c1',
+ lightsalmon: '#ffa07a',
+ lightseagreen: '#20b2aa',
+ lightskyblue: '#87cefa',
+ lightslategray: '#778899',
+ lightslategrey: '#778899',
+ lightsteelblue: '#b0c4de',
+ lightyellow: '#ffffe0',
+ lime: '#00ff00',
+ limegreen: '#32cd32',
+ linen: '#faf0e6',
+ magenta: '#ff00ff',
+ maroon: '#800000',
+ mediumaquamarine: '#66cdaa',
+ mediumblue: '#0000cd',
+ mediumorchid: '#ba55d3',
+ mediumpurple: '#9370db',
+ mediumseagreen: '#3cb371',
+ mediumslateblue: '#7b68ee',
+ mediumspringgreen: '#00fa9a',
+ mediumturquoise: '#48d1cc',
+ mediumvioletred: '#c71585',
+ midnightblue: '#191970',
+ mintcream: '#f5fffa',
+ mistyrose: '#ffe4e1',
+ moccasin: '#ffe4b5',
+ navajowhite: '#ffdead',
+ navy: '#000080',
+ oldlace: '#fdf5e6',
+ olive: '#808000',
+ olivedrab: '#6b8e23',
+ orange: '#ffa500',
+ orangered: '#ff4500',
+ orchid: '#da70d6',
+ palegoldenrod: '#eee8aa',
+ palegreen: '#98fb98',
+ paleturquoise: '#afeeee',
+ palevioletred: '#db7093',
+ papayawhip: '#ffefd5',
+ peachpuff: '#ffdab9',
+ peru: '#cd853f',
+ pink: '#ffc0cb',
+ plum: '#dda0dd',
+ powderblue: '#b0e0e6',
+ purple: '#800080',
+ red: '#ff0000',
+ rosybrown: '#bc8f8f',
+ royalblue: '#4169e1',
+ saddlebrown: '#8b4513',
+ salmon: '#fa8072',
+ sandybrown: '#f4a460',
+ seagreen: '#2e8b57',
+ seashell: '#fff5ee',
+ sienna: '#a0522d',
+ silver: '#c0c0c0',
+ skyblue: '#87ceeb',
+ slateblue: '#6a5acd',
+ slategray: '#708090',
+ slategrey: '#708090',
+ snow: '#fffafa',
+ springgreen: '#00ff7f',
+ steelblue: '#4682b4',
+ tan: '#d2b48c',
+ teal: '#008080',
+ thistle: '#d8bfd8',
+ tomato: '#ff6347',
+ turquoise: '#40e0d0',
+ violet: '#ee82ee',
+ wheat: '#f5deb3',
+ white: '#ffffff',
+ whitesmoke: '#f5f5f5',
+ yellow: '#ffff00',
+ yellowgreen: '#9acd32'
+};
+
+/**
+ * These regular expressions are used to build up the patterns for matching
+ * viable CSS color strings: fragmenting the regexes in this way increases the
+ * legibility and comprehensibility of the code.
+ *
+ * Note that RGB values of .9 are not parsed by IE, but are supported here for
+ * color string consistency.
+ */
+var WHITESPACE = /\s*/; // Match zero or more whitespace characters.
+var INTEGER = /(\d{1,3})/; // Match integers: 79, 255, etc.
+var DECIMAL = /((?:\d+(?:\.\d+)?)|(?:\.\d+))/; // Match 129.6, 79, .9, etc.
+var PERCENT = new RegExp(DECIMAL.source + '%'); // Match 12.9%, 79%, .9%, etc.
+
+/**
+ * Full color string patterns. The capture groups are necessary.
+ */
+var colorPatterns = {
+ // Match colors in format #XXX, e.g. #416.
+ HEX3: /^#([a-f0-9])([a-f0-9])([a-f0-9])$/i,
+
+ // Match colors in format #XXXX, e.g. #5123.
+ HEX4: /^#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])$/i,
+
+ // Match colors in format #XXXXXX, e.g. #b4d455.
+ HEX6: /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i,
+
+ // Match colors in format #XXXXXXXX, e.g. #b4d45535.
+ HEX8: /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i,
+
+ // Match colors in format rgb(R, G, B), e.g. rgb(255, 0, 128).
+ RGB: new RegExp(
+ [
+ '^rgb\\(',
+ INTEGER.source,
+ ',',
+ INTEGER.source,
+ ',',
+ INTEGER.source,
+ '\\)$'
+ ].join(WHITESPACE.source),
+ 'i'
+ ),
+
+ // Match colors in format rgb(R%, G%, B%), e.g. rgb(100%, 0%, 28.9%).
+ RGB_PERCENT: new RegExp(
+ [
+ '^rgb\\(',
+ PERCENT.source,
+ ',',
+ PERCENT.source,
+ ',',
+ PERCENT.source,
+ '\\)$'
+ ].join(WHITESPACE.source),
+ 'i'
+ ),
+
+ // Match colors in format rgb(R, G, B, A), e.g. rgb(255, 0, 128, 0.25).
+ RGBA: new RegExp(
+ [
+ '^rgba\\(',
+ INTEGER.source,
+ ',',
+ INTEGER.source,
+ ',',
+ INTEGER.source,
+ ',',
+ DECIMAL.source,
+ '\\)$'
+ ].join(WHITESPACE.source),
+ 'i'
+ ),
+
+ // Match colors in format rgb(R%, G%, B%, A), e.g. rgb(100%, 0%, 28.9%, 0.5).
+ RGBA_PERCENT: new RegExp(
+ [
+ '^rgba\\(',
+ PERCENT.source,
+ ',',
+ PERCENT.source,
+ ',',
+ PERCENT.source,
+ ',',
+ DECIMAL.source,
+ '\\)$'
+ ].join(WHITESPACE.source),
+ 'i'
+ ),
+
+ // Match colors in format hsla(H, S%, L%), e.g. hsl(100, 40%, 28.9%).
+ HSL: new RegExp(
+ [
+ '^hsl\\(',
+ INTEGER.source,
+ ',',
+ PERCENT.source,
+ ',',
+ PERCENT.source,
+ '\\)$'
+ ].join(WHITESPACE.source),
+ 'i'
+ ),
+
+ // Match colors in format hsla(H, S%, L%, A), e.g. hsla(100, 40%, 28.9%, 0.5).
+ HSLA: new RegExp(
+ [
+ '^hsla\\(',
+ INTEGER.source,
+ ',',
+ PERCENT.source,
+ ',',
+ PERCENT.source,
+ ',',
+ DECIMAL.source,
+ '\\)$'
+ ].join(WHITESPACE.source),
+ 'i'
+ ),
+
+ // Match colors in format hsb(H, S%, B%), e.g. hsb(100, 40%, 28.9%).
+ HSB: new RegExp(
+ [
+ '^hsb\\(',
+ INTEGER.source,
+ ',',
+ PERCENT.source,
+ ',',
+ PERCENT.source,
+ '\\)$'
+ ].join(WHITESPACE.source),
+ 'i'
+ ),
+
+ // Match colors in format hsba(H, S%, B%, A), e.g. hsba(100, 40%, 28.9%, 0.5).
+ HSBA: new RegExp(
+ [
+ '^hsba\\(',
+ INTEGER.source,
+ ',',
+ PERCENT.source,
+ ',',
+ PERCENT.source,
+ ',',
+ DECIMAL.source,
+ '\\)$'
+ ].join(WHITESPACE.source),
+ 'i'
+ )
+};
+
+/**
+ * For a number of different inputs, returns a color formatted as [r, g, b, a]
+ * arrays, with each component normalized between 0 and 1.
+ *
+ * @private
+ * @param {Array} [...args] An 'array-like' object that represents a list of
+ * arguments
+ * @return {Number[]} a color formatted as [r, g, b, a]
+ * Example:
+ * input ==> output
+ * g ==> [g, g, g, 255]
+ * g,a ==> [g, g, g, a]
+ * r, g, b ==> [r, g, b, 255]
+ * r, g, b, a ==> [r, g, b, a]
+ * [g] ==> [g, g, g, 255]
+ * [g, a] ==> [g, g, g, a]
+ * [r, g, b] ==> [r, g, b, 255]
+ * [r, g, b, a] ==> [r, g, b, a]
+ * @example
+ *
+ *
+ * // todo
+ *
+ *
+ *
+ * @alt
+ * //todo
+ *
+ */
+p5.Color._parseInputs = function(r, g, b, a) {
+ var numArgs = arguments.length;
+ var mode = this.mode;
+ var maxes = this.maxes;
+ var results = [];
+
+ if (numArgs >= 3) {
+ // Argument is a list of component values.
+
+ results[0] = r / maxes[mode][0];
+ results[1] = g / maxes[mode][1];
+ results[2] = b / maxes[mode][2];
+
+ // Alpha may be undefined, so default it to 100%.
+ if (typeof a === 'number') {
+ results[3] = a / maxes[mode][3];
+ } else {
+ results[3] = 1;
+ }
+
+ // Constrain components to the range [0,1].
+ results = results.map(function(value) {
+ return Math.max(Math.min(value, 1), 0);
+ });
+
+ // Convert to RGBA and return.
+ if (mode === constants.HSL) {
+ return color_conversion._hslaToRGBA(results);
+ } else if (mode === constants.HSB) {
+ return color_conversion._hsbaToRGBA(results);
+ } else {
+ return results;
+ }
+ } else if (numArgs === 1 && typeof r === 'string') {
+ var str = r.trim().toLowerCase();
+
+ // Return if string is a named colour.
+ if (namedColors[str]) {
+ return p5.Color._parseInputs.call(this, namedColors[str]);
+ }
+
+ // Try RGBA pattern matching.
+ if (colorPatterns.HEX3.test(str)) {
+ // #rgb
+ results = colorPatterns.HEX3.exec(str)
+ .slice(1)
+ .map(function(color) {
+ return parseInt(color + color, 16) / 255;
+ });
+ results[3] = 1;
+ return results;
+ } else if (colorPatterns.HEX6.test(str)) {
+ // #rrggbb
+ results = colorPatterns.HEX6.exec(str)
+ .slice(1)
+ .map(function(color) {
+ return parseInt(color, 16) / 255;
+ });
+ results[3] = 1;
+ return results;
+ } else if (colorPatterns.HEX4.test(str)) {
+ // #rgba
+ results = colorPatterns.HEX4.exec(str)
+ .slice(1)
+ .map(function(color) {
+ return parseInt(color + color, 16) / 255;
+ });
+ return results;
+ } else if (colorPatterns.HEX8.test(str)) {
+ // #rrggbbaa
+ results = colorPatterns.HEX8.exec(str)
+ .slice(1)
+ .map(function(color) {
+ return parseInt(color, 16) / 255;
+ });
+ return results;
+ } else if (colorPatterns.RGB.test(str)) {
+ // rgb(R,G,B)
+ results = colorPatterns.RGB.exec(str)
+ .slice(1)
+ .map(function(color) {
+ return color / 255;
+ });
+ results[3] = 1;
+ return results;
+ } else if (colorPatterns.RGB_PERCENT.test(str)) {
+ // rgb(R%,G%,B%)
+ results = colorPatterns.RGB_PERCENT.exec(str)
+ .slice(1)
+ .map(function(color) {
+ return parseFloat(color) / 100;
+ });
+ results[3] = 1;
+ return results;
+ } else if (colorPatterns.RGBA.test(str)) {
+ // rgba(R,G,B,A)
+ results = colorPatterns.RGBA.exec(str)
+ .slice(1)
+ .map(function(color, idx) {
+ if (idx === 3) {
+ return parseFloat(color);
+ }
+ return color / 255;
+ });
+ return results;
+ } else if (colorPatterns.RGBA_PERCENT.test(str)) {
+ // rgba(R%,G%,B%,A%)
+ results = colorPatterns.RGBA_PERCENT.exec(str)
+ .slice(1)
+ .map(function(color, idx) {
+ if (idx === 3) {
+ return parseFloat(color);
+ }
+ return parseFloat(color) / 100;
+ });
+ return results;
+ }
+
+ // Try HSLA pattern matching.
+ if (colorPatterns.HSL.test(str)) {
+ // hsl(H,S,L)
+ results = colorPatterns.HSL.exec(str)
+ .slice(1)
+ .map(function(color, idx) {
+ if (idx === 0) {
+ return parseInt(color, 10) / 360;
+ }
+ return parseInt(color, 10) / 100;
+ });
+ results[3] = 1;
+ } else if (colorPatterns.HSLA.test(str)) {
+ // hsla(H,S,L,A)
+ results = colorPatterns.HSLA.exec(str)
+ .slice(1)
+ .map(function(color, idx) {
+ if (idx === 0) {
+ return parseInt(color, 10) / 360;
+ } else if (idx === 3) {
+ return parseFloat(color);
+ }
+ return parseInt(color, 10) / 100;
+ });
+ }
+ results = results.map(function(value) {
+ return Math.max(Math.min(value, 1), 0);
+ });
+ if (results.length) {
+ return color_conversion._hslaToRGBA(results);
+ }
+
+ // Try HSBA pattern matching.
+ if (colorPatterns.HSB.test(str)) {
+ // hsb(H,S,B)
+ results = colorPatterns.HSB.exec(str)
+ .slice(1)
+ .map(function(color, idx) {
+ if (idx === 0) {
+ return parseInt(color, 10) / 360;
+ }
+ return parseInt(color, 10) / 100;
+ });
+ results[3] = 1;
+ } else if (colorPatterns.HSBA.test(str)) {
+ // hsba(H,S,B,A)
+ results = colorPatterns.HSBA.exec(str)
+ .slice(1)
+ .map(function(color, idx) {
+ if (idx === 0) {
+ return parseInt(color, 10) / 360;
+ } else if (idx === 3) {
+ return parseFloat(color);
+ }
+ return parseInt(color, 10) / 100;
+ });
+ }
+ results = results.map(function(value) {
+ return Math.max(Math.min(value, 1), 0);
+ });
+
+ if (results.length) {
+ return color_conversion._hsbaToRGBA(results);
+ }
+
+ // Input did not match any CSS color pattern: default to white.
+ results = [1, 1, 1, 1];
+ } else if ((numArgs === 1 || numArgs === 2) && typeof r === 'number') {
+ // 'Grayscale' mode.
+
+ /**
+ * For HSB and HSL, interpret the gray level as a brightness/lightness
+ * value (they are equivalent when chroma is zero). For RGB, normalize the
+ * gray level according to the blue maximum.
+ */
+ results[0] = r / maxes[mode][2];
+ results[1] = r / maxes[mode][2];
+ results[2] = r / maxes[mode][2];
+
+ // Alpha may be undefined, so default it to 100%.
+ if (typeof g === 'number') {
+ results[3] = g / maxes[mode][3];
+ } else {
+ results[3] = 1;
+ }
+
+ // Constrain components to the range [0,1].
+ results = results.map(function(value) {
+ return Math.max(Math.min(value, 1), 0);
+ });
+ } else {
+ throw new Error(arguments + 'is not a valid color representation.');
+ }
+
+ return results;
+};
+
+module.exports = p5.Color;
+
+},{"../core/constants":21,"../core/core":22,"./color_conversion":14}],17:[function(_dereq_,module,exports){
+/**
+ * @module Color
+ * @submodule Setting
+ * @for p5
+ * @requires core
+ * @requires constants
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+var constants = _dereq_('../core/constants');
+_dereq_('./p5.Color');
+
+/**
+ * The background() function sets the color used for the background of the
+ * p5.js canvas. The default background is light gray. This function is
+ * typically used within draw() to clear the display window at the beginning
+ * of each frame, but it can be used inside setup() to set the background on
+ * the first frame of animation or if the background need only be set once.
+ *
+ * The color is either specified in terms of the RGB, HSB, or HSL color
+ * depending on the current colorMode. (The default color space is RGB, with
+ * each value in the range from 0 to 255). The alpha range by default is also 0 to 255.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color strings
+ * and all named color strings are supported. In this case, an alpha number
+ * value as a second argument is not supported, the RGBA form should be used.
+ *
+ * A p5.Color object can also be provided to set the background color.
+ *
+ * A p5.Image can also be provided to set the background image.
+ *
+ * @method background
+ * @param {p5.Color} color any value created by the color() function
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * // Grayscale integer value
+ * background(51);
+ *
+ *
+ *
+ *
+ *
+ * // R, G & B integer values
+ * background(255, 204, 0);
+ *
+ *
+ *
+ *
+ *
+ * // H, S & B integer values
+ * colorMode(HSB);
+ * background(255, 204, 100);
+ *
+ *
+ *
+ *
+ *
+ * // Named SVG/CSS color string
+ * background('red');
+ *
+ *
+ *
+ *
+ *
+ * // three-digit hexadecimal RGB notation
+ * background('#fae');
+ *
+ *
+ *
+ *
+ *
+ * // six-digit hexadecimal RGB notation
+ * background('#222222');
+ *
+ *
+ *
+ *
+ *
+ * // integer RGB notation
+ * background('rgb(0,255,0)');
+ *
+ *
+ *
+ *
+ *
+ * // integer RGBA notation
+ * background('rgba(0,255,0, 0.25)');
+ *
+ *
+ *
+ *
+ *
+ * // percentage RGB notation
+ * background('rgb(100%,0%,10%)');
+ *
+ *
+ *
+ *
+ *
+ * // percentage RGBA notation
+ * background('rgba(100%,0%,100%,0.5)');
+ *
+ *
+ *
+ *
+ *
+ * // p5 Color object
+ * background(color(0, 0, 255));
+ *
+ *
+ *
+ * @alt
+ * canvas with darkest charcoal grey background.
+ * canvas with yellow background.
+ * canvas with royal blue background.
+ * canvas with red background.
+ * canvas with pink background.
+ * canvas with black background.
+ * canvas with bright green background.
+ * canvas with soft green background.
+ * canvas with red background.
+ * canvas with light purple background.
+ * canvas with blue background.
+ */
+
+/**
+ * @method background
+ * @param {String} colorstring color string, possible formats include: integer
+ * rgb() or rgba(), percentage rgb() or rgba(),
+ * 3-digit hex, 6-digit hex
+ * @param {Number} [a] opacity of the background relative to current
+ * color range (default is 0-255)
+ * @chainable
+ */
+
+/**
+ * @method background
+ * @param {Number} gray specifies a value between white and black
+ * @param {Number} [a]
+ * @chainable
+ */
+
+/**
+ * @method background
+ * @param {Number} v1 red or hue value (depending on the current color
+ * mode)
+ * @param {Number} v2 green or saturation value (depending on the current
+ * color mode)
+ * @param {Number} v3 blue or brightness value (depending on the current
+ * color mode)
+ * @param {Number} [a]
+ * @chainable
+ */
+
+/**
+ * @method background
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and alpha components of the color
+ * @chainable
+ */
+
+/**
+ * @method background
+ * @param {p5.Image} image image created with loadImage() or createImage(),
+ * to set as background
+ * (must be same size as the sketch window)
+ * @param {Number} [a]
+ * @chainable
+ */
+
+p5.prototype.background = function() {
+ if (arguments[0] instanceof p5.Image) {
+ this.image(arguments[0], 0, 0, this.width, this.height);
+ } else {
+ this._renderer.background.apply(this._renderer, arguments);
+ }
+ return this;
+};
+
+/**
+ * Clears the pixels within a buffer. This function only works on p5.Canvas
+ * objects created with the createCanvas() function; it won't work with the
+ * main display window. Unlike the main graphics context, pixels in
+ * additional graphics areas created with createGraphics() can be entirely
+ * or partially transparent. This function clears everything to make all of
+ * the pixels 100% transparent.
+ *
+ * @method clear
+ * @chainable
+ * @example
+ *
+ *
+ * // Clear the screen on mouse press.
+ * function setup() {
+ * createCanvas(100, 100);
+ * }
+ *
+ * function draw() {
+ * ellipse(mouseX, mouseY, 20, 20);
+ * }
+ *
+ * function mousePressed() {
+ * clear();
+ * }
+ *
+ *
+ *
+ * @alt
+ * 20x20 white ellipses are continually drawn at mouse x and y coordinates.
+ *
+ */
+
+p5.prototype.clear = function() {
+ this._renderer.clear();
+ return this;
+};
+
+/**
+ * colorMode() changes the way p5.js interprets color data. By default, the
+ * parameters for fill(), stroke(), background(), and color() are defined by
+ * values between 0 and 255 using the RGB color model. This is equivalent to
+ * setting colorMode(RGB, 255). Setting colorMode(HSB) lets you use the HSB
+ * system instead. By default, this is colorMode(HSB, 360, 100, 100, 1). You
+ * can also use HSL.
+ *
+ * Note: existing color objects remember the mode that they were created in,
+ * so you can change modes as you like without affecting their appearance.
+ *
+ *
+ * @method colorMode
+ * @param {Constant} mode either RGB, HSB or HSL, corresponding to
+ * Red/Green/Blue and Hue/Saturation/Brightness
+ * (or Lightness)
+ * @param {Number} [max] range for all values
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * noStroke();
+ * colorMode(RGB, 100);
+ * for (var i = 0; i < 100; i++) {
+ * for (var j = 0; j < 100; j++) {
+ * stroke(i, j, 0);
+ * point(i, j);
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * noStroke();
+ * colorMode(HSB, 100);
+ * for (var i = 0; i < 100; i++) {
+ * for (var j = 0; j < 100; j++) {
+ * stroke(i, j, 100);
+ * point(i, j);
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * colorMode(RGB, 255);
+ * var c = color(127, 255, 0);
+ *
+ * colorMode(RGB, 1);
+ * var myColor = c._getRed();
+ * text(myColor, 10, 10, 80, 80);
+ *
+ *
+ *
+ *
+ *
+ * noFill();
+ * colorMode(RGB, 255, 255, 255, 1);
+ * background(255);
+ *
+ * strokeWeight(4);
+ * stroke(255, 0, 10, 0.3);
+ * ellipse(40, 40, 50, 50);
+ * ellipse(50, 50, 40, 40);
+ *
+ *
+ *
+ * @alt
+ *Green to red gradient from bottom L to top R. shading originates from top left.
+ *Rainbow gradient from left to right. Brightness increasing to white at top.
+ *unknown image.
+ *50x50 ellipse at middle L & 40x40 ellipse at center. Transluscent pink outlines.
+ *
+ */
+/**
+ * @method colorMode
+ * @param {Constant} mode
+ * @param {Number} max1 range for the red or hue depending on the
+ * current color mode
+ * @param {Number} max2 range for the green or saturation depending
+ * on the current color mode
+ * @param {Number} max3 range for the blue or brightness/lighntess
+ * depending on the current color mode
+ * @param {Number} [maxA] range for the alpha
+ * @chainable
+ */
+p5.prototype.colorMode = function(mode, max1, max2, max3, maxA) {
+ p5._validateParameters('colorMode', arguments);
+ if (
+ mode === constants.RGB ||
+ mode === constants.HSB ||
+ mode === constants.HSL
+ ) {
+ // Set color mode.
+ this._colorMode = mode;
+
+ // Set color maxes.
+ var maxes = this._colorMaxes[mode];
+ if (arguments.length === 2) {
+ maxes[0] = max1; // Red
+ maxes[1] = max1; // Green
+ maxes[2] = max1; // Blue
+ maxes[3] = max1; // Alpha
+ } else if (arguments.length === 4) {
+ maxes[0] = max1; // Red
+ maxes[1] = max2; // Green
+ maxes[2] = max3; // Blue
+ } else if (arguments.length === 5) {
+ maxes[0] = max1; // Red
+ maxes[1] = max2; // Green
+ maxes[2] = max3; // Blue
+ maxes[3] = maxA; // Alpha
+ }
+ }
+
+ return this;
+};
+
+/**
+ * Sets the color used to fill shapes. For example, if you run
+ * fill(204, 102, 0), all subsequent shapes will be filled with orange. This
+ * color is either specified in terms of the RGB or HSB color depending on
+ * the current colorMode(). (The default color space is RGB, with each value
+ * in the range from 0 to 255). The alpha range by default is also 0 to 255.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color strings
+ * and all named color strings are supported. In this case, an alpha number
+ * value as a second argument is not supported, the RGBA form should be used.
+ *
+ * A p5 Color object can also be provided to set the fill color.
+ *
+ * @method fill
+ * @param {Number} v1 red or hue value relative to
+ * the current color range
+ * @param {Number} v2 green or saturation value
+ * relative to the current color range
+ * @param {Number} v3 blue or brightness value
+ * relative to the current color range
+ * @param {Number} [alpha]
+ * @chainable
+ * @example
+ *
+ *
+ * // Grayscale integer value
+ * fill(51);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // R, G & B integer values
+ * fill(255, 204, 0);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // H, S & B integer values
+ * colorMode(HSB);
+ * fill(255, 204, 100);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // Named SVG/CSS color string
+ * fill('red');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // three-digit hexadecimal RGB notation
+ * fill('#fae');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // six-digit hexadecimal RGB notation
+ * fill('#222222');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // integer RGB notation
+ * fill('rgb(0,255,0)');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // integer RGBA notation
+ * fill('rgba(0,255,0, 0.25)');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // percentage RGB notation
+ * fill('rgb(100%,0%,10%)');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // percentage RGBA notation
+ * fill('rgba(100%,0%,100%,0.5)');
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // p5 Color object
+ * fill(color(0, 0, 255));
+ * rect(20, 20, 60, 60);
+ *
+ *
+ * @alt
+ * 60x60 dark charcoal grey rect with black outline in center of canvas.
+ * 60x60 yellow rect with black outline in center of canvas.
+ * 60x60 royal blue rect with black outline in center of canvas.
+ * 60x60 red rect with black outline in center of canvas.
+ * 60x60 pink rect with black outline in center of canvas.
+ * 60x60 black rect with black outline in center of canvas.
+ * 60x60 light green rect with black outline in center of canvas.
+ * 60x60 soft green rect with black outline in center of canvas.
+ * 60x60 red rect with black outline in center of canvas.
+ * 60x60 dark fushcia rect with black outline in center of canvas.
+ * 60x60 blue rect with black outline in center of canvas.
+ */
+
+/**
+ * @method fill
+ * @param {String} value a color string
+ * @chainable
+ */
+
+/**
+ * @method fill
+ * @param {Number} gray a gray value
+ * @param {Number} [alpha]
+ * @chainable
+ */
+
+/**
+ * @method fill
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and alpha components of the color
+ * @chainable
+ */
+
+/**
+ * @method fill
+ * @param {p5.Color} color the fill color
+ * @chainable
+ */
+p5.prototype.fill = function() {
+ this._renderer._setProperty('_fillSet', true);
+ this._renderer._setProperty('_doFill', true);
+ this._renderer.fill.apply(this._renderer, arguments);
+ return this;
+};
+
+/**
+ * Disables filling geometry. If both noStroke() and noFill() are called,
+ * nothing will be drawn to the screen.
+ *
+ * @method noFill
+ * @chainable
+ * @example
+ *
+ *
+ * rect(15, 10, 55, 55);
+ * noFill();
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * noFill();
+ * stroke(100, 100, 240);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * box(45, 45, 45);
+ * }
+ *
+ *
+ *
+ * @alt
+ * white rect top middle and noFill rect center. Both 60x60 with black outlines.
+ * black canvas with purple cube wireframe spinning
+ */
+p5.prototype.noFill = function() {
+ this._renderer._setProperty('_doFill', false);
+ return this;
+};
+
+/**
+ * Disables drawing the stroke (outline). If both noStroke() and noFill()
+ * are called, nothing will be drawn to the screen.
+ *
+ * @method noStroke
+ * @chainable
+ * @example
+ *
+ *
+ * noStroke();
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * noStroke();
+ * fill(240, 150, 150);
+ * rotateX(frameCount * 0.01);
+ * rotateY(frameCount * 0.01);
+ * box(45, 45, 45);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60x60 white rect at center. no outline.
+ * black canvas with pink cube spinning
+ */
+p5.prototype.noStroke = function() {
+ this._renderer._setProperty('_doStroke', false);
+ return this;
+};
+
+/**
+ * Sets the color used to draw lines and borders around shapes. This color
+ * is either specified in terms of the RGB or HSB color depending on the
+ * current colorMode() (the default color space is RGB, with each value in
+ * the range from 0 to 255). The alpha range by default is also 0 to 255.
+ *
+ * If a single string argument is provided, RGB, RGBA and Hex CSS color
+ * strings and all named color strings are supported. In this case, an alpha
+ * number value as a second argument is not supported, the RGBA form should be
+ * used.
+ *
+ * A p5 Color object can also be provided to set the stroke color.
+ *
+ *
+ * @method stroke
+ * @param {Number} v1 red or hue value relative to
+ * the current color range
+ * @param {Number} v2 green or saturation value
+ * relative to the current color range
+ * @param {Number} v3 blue or brightness value
+ * relative to the current color range
+ * @param {Number} [alpha]
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * // Grayscale integer value
+ * strokeWeight(4);
+ * stroke(51);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // R, G & B integer values
+ * stroke(255, 204, 0);
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // H, S & B integer values
+ * colorMode(HSB);
+ * strokeWeight(4);
+ * stroke(255, 204, 100);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // Named SVG/CSS color string
+ * stroke('red');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // three-digit hexadecimal RGB notation
+ * stroke('#fae');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // six-digit hexadecimal RGB notation
+ * stroke('#222222');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // integer RGB notation
+ * stroke('rgb(0,255,0)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // integer RGBA notation
+ * stroke('rgba(0,255,0,0.25)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // percentage RGB notation
+ * stroke('rgb(100%,0%,10%)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // percentage RGBA notation
+ * stroke('rgba(100%,0%,100%,0.5)');
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ *
+ *
+ * // p5 Color object
+ * stroke(color(0, 0, 255));
+ * strokeWeight(4);
+ * rect(20, 20, 60, 60);
+ *
+ *
+ *
+ * @alt
+ * 60x60 white rect at center. Dark charcoal grey outline.
+ * 60x60 white rect at center. Yellow outline.
+ * 60x60 white rect at center. Royal blue outline.
+ * 60x60 white rect at center. Red outline.
+ * 60x60 white rect at center. Pink outline.
+ * 60x60 white rect at center. Black outline.
+ * 60x60 white rect at center. Bright green outline.
+ * 60x60 white rect at center. Soft green outline.
+ * 60x60 white rect at center. Red outline.
+ * 60x60 white rect at center. Dark fushcia outline.
+ * 60x60 white rect at center. Blue outline.
+ */
+
+/**
+ * @method stroke
+ * @param {String} value a color string
+ * @chainable
+ */
+
+/**
+ * @method stroke
+ * @param {Number} gray a gray value
+ * @param {Number} [alpha]
+ * @chainable
+ */
+
+/**
+ * @method stroke
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and alpha components of the color
+ * @chainable
+ */
+
+/**
+ * @method stroke
+ * @param {p5.Color} color the stroke color
+ * @chainable
+ */
+
+p5.prototype.stroke = function() {
+ this._renderer._setProperty('_strokeSet', true);
+ this._renderer._setProperty('_doStroke', true);
+ this._renderer.stroke.apply(this._renderer, arguments);
+ return this;
+};
+
+module.exports = p5;
+
+},{"../core/constants":21,"../core/core":22,"./p5.Color":16}],18:[function(_dereq_,module,exports){
+/**
+ * @module Shape
+ * @submodule 2D Primitives
+ * @for p5
+ * @requires core
+ * @requires constants
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+var constants = _dereq_('./constants');
+var canvas = _dereq_('./canvas');
+_dereq_('./error_helpers');
+
+/**
+ * Draw an arc to the screen. If called with only x, y, w, h, start, and
+ * stop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc
+ * will be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The
+ * origin may be changed with the ellipseMode() function.
+ * Note that drawing a full circle (ex: 0 to TWO_PI) will appear blank
+ * because 0 and TWO_PI are the same position on the unit circle. The
+ * best way to handle this is by using the ellipse() function instead
+ * to create a closed ellipse, and to use the arc() function
+ * only to draw parts of an ellipse.
+ *
+ * @method arc
+ * @param {Number} x x-coordinate of the arc's ellipse
+ * @param {Number} y y-coordinate of the arc's ellipse
+ * @param {Number} w width of the arc's ellipse by default
+ * @param {Number} h height of the arc's ellipse by default
+ * @param {Number} start angle to start the arc, specified in radians
+ * @param {Number} stop angle to stop the arc, specified in radians
+ * @param {Constant} [mode] optional parameter to determine the way of drawing
+ * the arc. either CHORD, PIE or OPEN
+ * @chainable
+ * @example
+ *
+ *
+ * arc(50, 55, 50, 50, 0, HALF_PI);
+ * noFill();
+ * arc(50, 55, 60, 60, HALF_PI, PI);
+ * arc(50, 55, 70, 70, PI, PI + QUARTER_PI);
+ * arc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI);
+ *
+ *
+ *
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI);
+ *
+ *
+ *
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN);
+ *
+ *
+ *
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD);
+ *
+ *
+ *
+ *
+ *
+ * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE);
+ *
+ *
+ *
+ * @alt
+ *shattered outline of an ellipse with a quarter of a white circle bottom-right.
+ *white ellipse with top right quarter missing.
+ *white ellipse with black outline with top right missing.
+ *white ellipse with top right missing with black outline around shape.
+ *white ellipse with top right quarter missing with black outline around the shape.
+ *
+ */
+p5.prototype.arc = function(x, y, w, h, start, stop, mode) {
+ p5._validateParameters('arc', arguments);
+ if (!this._renderer._doStroke && !this._renderer._doFill) {
+ return this;
+ }
+
+ start = this._toRadians(start);
+ stop = this._toRadians(stop);
+
+ // Make all angles positive...
+ while (start < 0) {
+ start += constants.TWO_PI;
+ }
+ while (stop < 0) {
+ stop += constants.TWO_PI;
+ }
+ // ...and confine them to the interval [0,TWO_PI).
+ start %= constants.TWO_PI;
+ stop %= constants.TWO_PI;
+
+ // account for full circle
+ if (stop === start) {
+ stop += constants.TWO_PI;
+ }
+
+ // Adjust angles to counter linear scaling.
+ if (start <= constants.HALF_PI) {
+ start = Math.atan(w / h * Math.tan(start));
+ } else if (start > constants.HALF_PI && start <= 3 * constants.HALF_PI) {
+ start = Math.atan(w / h * Math.tan(start)) + constants.PI;
+ } else {
+ start = Math.atan(w / h * Math.tan(start)) + constants.TWO_PI;
+ }
+ if (stop <= constants.HALF_PI) {
+ stop = Math.atan(w / h * Math.tan(stop));
+ } else if (stop > constants.HALF_PI && stop <= 3 * constants.HALF_PI) {
+ stop = Math.atan(w / h * Math.tan(stop)) + constants.PI;
+ } else {
+ stop = Math.atan(w / h * Math.tan(stop)) + constants.TWO_PI;
+ }
+
+ // Exceed the interval if necessary in order to preserve the size and
+ // orientation of the arc.
+ if (start > stop) {
+ stop += constants.TWO_PI;
+ }
+ // p5 supports negative width and heights for ellipses
+ w = Math.abs(w);
+ h = Math.abs(h);
+ this._renderer.arc(x, y, w, h, start, stop, mode);
+ return this;
+};
+
+/**
+ * Draws an ellipse (oval) to the screen. An ellipse with equal width and
+ * height is a circle. By default, the first two parameters set the location,
+ * and the third and fourth parameters set the shape's width and height. If
+ * no height is specified, the value of width is used for both the width and
+ * height. If a negative height or width is specified, the absolute value is taken.
+ * The origin may be changed with the ellipseMode() function.
+ *
+ * @method ellipse
+ * @param {Number} x x-coordinate of the ellipse.
+ * @param {Number} y y-coordinate of the ellipse.
+ * @param {Number} w width of the ellipse.
+ * @param {Number} [h] height of the ellipse.
+ * @chainable
+ * @example
+ *
+ *
+ * ellipse(56, 46, 55, 55);
+ *
+ *
+ *
+ * @alt
+ *white ellipse with black outline in middle-right of canvas that is 55x55.
+ *
+ */
+/**
+ * @method ellipse
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} w
+ * @param {Number} h
+ * @param {Integer} detail number of radial sectors to draw
+ */
+p5.prototype.ellipse = function(x, y, w, h, detailX) {
+ p5._validateParameters('ellipse', arguments);
+
+ // p5 supports negative width and heights for rects
+ if (w < 0) {
+ w = Math.abs(w);
+ }
+
+ if (typeof h === 'undefined') {
+ // Duplicate 3rd argument if only 3 given.
+ h = w;
+ } else if (h < 0) {
+ h = Math.abs(h);
+ }
+
+ if (this._renderer._doStroke || this._renderer._doFill) {
+ var vals = canvas.modeAdjust(x, y, w, h, this._renderer._ellipseMode);
+ this._renderer.ellipse([vals.x, vals.y, vals.w, vals.h, detailX]);
+ }
+
+ return this;
+};
+/**
+ * Draws a line (a direct path between two points) to the screen. The version
+ * of line() with four parameters draws the line in 2D. To color a line, use
+ * the stroke() function. A line cannot be filled, therefore the fill()
+ * function will not affect the color of a line. 2D lines are drawn with a
+ * width of one pixel by default, but this can be changed with the
+ * strokeWeight() function.
+ *
+ * @method line
+ * @param {Number} x1 the x-coordinate of the first point
+ * @param {Number} y1 the y-coordinate of the first point
+ * @param {Number} x2 the x-coordinate of the second point
+ * @param {Number} y2 the y-coordinate of the second point
+ * @chainable
+ * @example
+ *
+ *
+ * line(30, 20, 85, 75);
+ *
+ *
+ *
+ *
+ *
+ * line(30, 20, 85, 20);
+ * stroke(126);
+ * line(85, 20, 85, 75);
+ * stroke(255);
+ * line(85, 75, 30, 75);
+ *
+ *
+ *
+ * @alt
+ *line 78 pixels long running from mid-top to bottom-right of canvas.
+ *3 lines of various stroke sizes. Form top, bottom and right sides of a square.
+ *
+ */
+/**
+ * @method line
+ * @param {Number} x1
+ * @param {Number} y1
+ * @param {Number} z1 the z-coordinate of the first point
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 the z-coordinate of the second point
+ * @chainable
+ */
+p5.prototype.line = function() {
+ p5._validateParameters('line', arguments);
+
+ if (this._renderer._doStroke) {
+ this._renderer.line.apply(this._renderer, arguments);
+ }
+
+ return this;
+};
+
+/**
+ * Draws a point, a coordinate in space at the dimension of one pixel.
+ * The first parameter is the horizontal value for the point, the second
+ * value is the vertical value for the point. The color of the point is
+ * determined by the current stroke.
+ *
+ * @method point
+ * @param {Number} x the x-coordinate
+ * @param {Number} y the y-coordinate
+ * @param {Number} [z] the z-coordinate (for WEBGL mode)
+ * @chainable
+ * @example
+ *
+ *
+ * point(30, 20);
+ * point(85, 20);
+ * point(85, 75);
+ * point(30, 75);
+ *
+ *
+ *
+ * @alt
+ *4 points centered in the middle-right of the canvas.
+ *
+ */
+p5.prototype.point = function() {
+ p5._validateParameters('point', arguments);
+
+ if (this._renderer._doStroke) {
+ this._renderer.point.apply(this._renderer, arguments);
+ }
+
+ return this;
+};
+
+/**
+ * Draw a quad. A quad is a quadrilateral, a four sided polygon. It is
+ * similar to a rectangle, but the angles between its edges are not
+ * constrained to ninety degrees. The first pair of parameters (x1,y1)
+ * sets the first vertex and the subsequent pairs should proceed
+ * clockwise or counter-clockwise around the defined shape.
+ *
+ * @method quad
+ * @param {Number} x1 the x-coordinate of the first point
+ * @param {Number} y1 the y-coordinate of the first point
+ * @param {Number} x2 the x-coordinate of the second point
+ * @param {Number} y2 the y-coordinate of the second point
+ * @param {Number} x3 the x-coordinate of the third point
+ * @param {Number} y3 the y-coordinate of the third point
+ * @param {Number} x4 the x-coordinate of the fourth point
+ * @param {Number} y4 the y-coordinate of the fourth point
+ * @chainable
+ * @example
+ *
+ *
+ * quad(38, 31, 86, 20, 69, 63, 30, 76);
+ *
+ *
+ *
+ * @alt
+ *irregular white quadrilateral shape with black outline mid-right of canvas.
+ *
+ */
+/**
+ * @method quad
+ * @param {Number} x1
+ * @param {Number} y1
+ * @param {Number} z1
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2
+ * @param {Number} x3
+ * @param {Number} y3
+ * @param {Number} z3
+ * @param {Number} x4
+ * @param {Number} y4
+ * @param {Number} z4
+ * @chainable
+ */
+p5.prototype.quad = function() {
+ p5._validateParameters('quad', arguments);
+
+ if (this._renderer._doStroke || this._renderer._doFill) {
+ this._renderer.quad.apply(this._renderer, arguments);
+ }
+
+ return this;
+};
+
+/**
+ * Draws a rectangle to the screen. A rectangle is a four-sided shape with
+ * every angle at ninety degrees. By default, the first two parameters set
+ * the location of the upper-left corner, the third sets the width, and the
+ * fourth sets the height. The way these parameters are interpreted, however,
+ * may be changed with the rectMode() function.
+ *
+ * The fifth, sixth, seventh and eighth parameters, if specified,
+ * determine corner radius for the top-right, top-left, lower-right and
+ * lower-left corners, respectively. An omitted corner radius parameter is set
+ * to the value of the previously specified radius value in the parameter list.
+ *
+ * @method rect
+ * @param {Number} x x-coordinate of the rectangle.
+ * @param {Number} y y-coordinate of the rectangle.
+ * @param {Number} w width of the rectangle.
+ * @param {Number} h height of the rectangle.
+ * @param {Number} [tl] optional radius of top-left corner.
+ * @param {Number} [tr] optional radius of top-right corner.
+ * @param {Number} [br] optional radius of bottom-right corner.
+ * @param {Number} [bl] optional radius of bottom-left corner.
+ * @chainable
+ * @example
+ *
+ *
+ * // Draw a rectangle at location (30, 20) with a width and height of 55.
+ * rect(30, 20, 55, 55);
+ *
+ *
+ *
+ *
+ *
+ * // Draw a rectangle with rounded corners, each having a radius of 20.
+ * rect(30, 20, 55, 55, 20);
+ *
+ *
+ *
+ *
+ *
+ * // Draw a rectangle with rounded corners having the following radii:
+ * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.
+ * rect(30, 20, 55, 55, 20, 15, 10, 5);
+ *
+ *
+ *
+ * @alt
+ * 55x55 white rect with black outline in mid-right of canvas.
+ * 55x55 white rect with black outline and rounded edges in mid-right of canvas.
+ * 55x55 white rect with black outline and rounded edges of different radii.
+ */
+/**
+ * @method rect
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} w
+ * @param {Number} h
+ * @param {Integer} [detailX] number of segments in the x-direction
+ * @param {Integer} [detailY] number of segments in the y-direction
+ * @chainable
+ */
+p5.prototype.rect = function() {
+ p5._validateParameters('rect', arguments);
+
+ if (this._renderer._doStroke || this._renderer._doFill) {
+ var vals = canvas.modeAdjust(
+ arguments[0],
+ arguments[1],
+ arguments[2],
+ arguments[3],
+ this._renderer._rectMode
+ );
+ var args = [vals.x, vals.y, vals.w, vals.h];
+ // append the additional arguments (either cornder radii, or
+ // segment details) to the argument list
+ for (var i = 4; i < arguments.length; i++) {
+ args[i] = arguments[i];
+ }
+ this._renderer.rect(args);
+ }
+
+ return this;
+};
+
+/**
+ * A triangle is a plane created by connecting three points. The first two
+ * arguments specify the first point, the middle two arguments specify the
+ * second point, and the last two arguments specify the third point.
+ *
+ * @method triangle
+ * @param {Number} x1 x-coordinate of the first point
+ * @param {Number} y1 y-coordinate of the first point
+ * @param {Number} x2 x-coordinate of the second point
+ * @param {Number} y2 y-coordinate of the second point
+ * @param {Number} x3 x-coordinate of the third point
+ * @param {Number} y3 y-coordinate of the third point
+ * @chainable
+ * @example
+ *
+ *
+ * triangle(30, 75, 58, 20, 86, 75);
+ *
+ *
+ *
+ *@alt
+ * white triangle with black outline in mid-right of canvas.
+ *
+ */
+p5.prototype.triangle = function() {
+ p5._validateParameters('triangle', arguments);
+
+ if (this._renderer._doStroke || this._renderer._doFill) {
+ this._renderer.triangle(arguments);
+ }
+
+ return this;
+};
+
+module.exports = p5;
+
+},{"./canvas":20,"./constants":21,"./core":22,"./error_helpers":25}],19:[function(_dereq_,module,exports){
+/**
+ * @module Shape
+ * @submodule Attributes
+ * @for p5
+ * @requires core
+ * @requires constants
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+var constants = _dereq_('./constants');
+
+/**
+ * Modifies the location from which ellipses are drawn by changing the way
+ * in which parameters given to ellipse() are interpreted.
+ *
+ * The default mode is ellipseMode(CENTER), which interprets the first two
+ * parameters of ellipse() as the shape's center point, while the third and
+ * fourth parameters are its width and height.
+ *
+ * ellipseMode(RADIUS) also uses the first two parameters of ellipse() as
+ * the shape's center point, but uses the third and fourth parameters to
+ * specify half of the shapes's width and height.
+ *
+ * ellipseMode(CORNER) interprets the first two parameters of ellipse() as
+ * the upper-left corner of the shape, while the third and fourth parameters
+ * are its width and height.
+ *
+ * ellipseMode(CORNERS) interprets the first two parameters of ellipse() as
+ * the location of one corner of the ellipse's bounding box, and the third
+ * and fourth parameters as the location of the opposite corner.
+ *
+ * The parameter must be written in ALL CAPS because Javascript is a
+ * case-sensitive language.
+ *
+ * @method ellipseMode
+ * @param {Constant} mode either CENTER, RADIUS, CORNER, or CORNERS
+ * @chainable
+ * @example
+ *
+ *
+ * ellipseMode(RADIUS); // Set ellipseMode to RADIUS
+ * fill(255); // Set fill to white
+ * ellipse(50, 50, 30, 30); // Draw white ellipse using RADIUS mode
+ *
+ * ellipseMode(CENTER); // Set ellipseMode to CENTER
+ * fill(100); // Set fill to gray
+ * ellipse(50, 50, 30, 30); // Draw gray ellipse using CENTER mode
+ *
+ *
+ *
+ *
+ *
+ * ellipseMode(CORNER); // Set ellipseMode is CORNER
+ * fill(255); // Set fill to white
+ * ellipse(25, 25, 50, 50); // Draw white ellipse using CORNER mode
+ *
+ * ellipseMode(CORNERS); // Set ellipseMode to CORNERS
+ * fill(100); // Set fill to gray
+ * ellipse(25, 25, 50, 50); // Draw gray ellipse using CORNERS mode
+ *
+ *
+ *
+ * @alt
+ * 60x60 white ellipse and 30x30 grey ellipse with black outlines at center.
+ * 60x60 white ellipse @center and 30x30 grey ellipse top-right, black outlines.
+ *
+ */
+p5.prototype.ellipseMode = function(m) {
+ p5._validateParameters('ellipseMode', arguments);
+ if (
+ m === constants.CORNER ||
+ m === constants.CORNERS ||
+ m === constants.RADIUS ||
+ m === constants.CENTER
+ ) {
+ this._renderer._ellipseMode = m;
+ }
+ return this;
+};
+
+/**
+ * Draws all geometry with jagged (aliased) edges. Note that smooth() is
+ * active by default, so it is necessary to call noSmooth() to disable
+ * smoothing of geometry, images, and fonts.
+ *
+ * @method noSmooth
+ * @chainable
+ * @example
+ *
+ *
+ * background(0);
+ * noStroke();
+ * smooth();
+ * ellipse(30, 48, 36, 36);
+ * noSmooth();
+ * ellipse(70, 48, 36, 36);
+ *
+ *
+ *
+ * @alt
+ * 2 pixelated 36x36 white ellipses to left & right of center, black background
+ *
+ */
+p5.prototype.noSmooth = function() {
+ this._renderer.noSmooth();
+ return this;
+};
+
+/**
+ * Modifies the location from which rectangles are drawn by changing the way
+ * in which parameters given to rect() are interpreted.
+ *
+ * The default mode is rectMode(CORNER), which interprets the first two
+ * parameters of rect() as the upper-left corner of the shape, while the
+ * third and fourth parameters are its width and height.
+ *
+ * rectMode(CORNERS) interprets the first two parameters of rect() as the
+ * location of one corner, and the third and fourth parameters as the
+ * location of the opposite corner.
+ *
+ * rectMode(CENTER) interprets the first two parameters of rect() as the
+ * shape's center point, while the third and fourth parameters are its
+ * width and height.
+ *
+ * rectMode(RADIUS) also uses the first two parameters of rect() as the
+ * shape's center point, but uses the third and fourth parameters to specify
+ * half of the shapes's width and height.
+ *
+ * The parameter must be written in ALL CAPS because Javascript is a
+ * case-sensitive language.
+ *
+ * @method rectMode
+ * @param {Constant} mode either CORNER, CORNERS, CENTER, or RADIUS
+ * @chainable
+ * @example
+ *
+ *
+ * rectMode(CORNER); // Default rectMode is CORNER
+ * fill(255); // Set fill to white
+ * rect(25, 25, 50, 50); // Draw white rect using CORNER mode
+ *
+ * rectMode(CORNERS); // Set rectMode to CORNERS
+ * fill(100); // Set fill to gray
+ * rect(25, 25, 50, 50); // Draw gray rect using CORNERS mode
+ *
+ *
+ *
+ *
+ *
+ * rectMode(RADIUS); // Set rectMode to RADIUS
+ * fill(255); // Set fill to white
+ * rect(50, 50, 30, 30); // Draw white rect using RADIUS mode
+ *
+ * rectMode(CENTER); // Set rectMode to CENTER
+ * fill(100); // Set fill to gray
+ * rect(50, 50, 30, 30); // Draw gray rect using CENTER mode
+ *
+ *
+ *
+ * @alt
+ * 50x50 white rect at center and 25x25 grey rect in the top left of the other.
+ * 50x50 white rect at center and 25x25 grey rect in the center of the other.
+ *
+ */
+p5.prototype.rectMode = function(m) {
+ p5._validateParameters('rectMode', arguments);
+ if (
+ m === constants.CORNER ||
+ m === constants.CORNERS ||
+ m === constants.RADIUS ||
+ m === constants.CENTER
+ ) {
+ this._renderer._rectMode = m;
+ }
+ return this;
+};
+
+/**
+ * Draws all geometry with smooth (anti-aliased) edges. smooth() will also
+ * improve image quality of resized images. Note that smooth() is active by
+ * default; noSmooth() can be used to disable smoothing of geometry,
+ * images, and fonts.
+ *
+ * @method smooth
+ * @chainable
+ * @example
+ *
+ *
+ * background(0);
+ * noStroke();
+ * smooth();
+ * ellipse(30, 48, 36, 36);
+ * noSmooth();
+ * ellipse(70, 48, 36, 36);
+ *
+ *
+ *
+ * @alt
+ * 2 pixelated 36x36 white ellipses one left one right of center. On black.
+ *
+ */
+p5.prototype.smooth = function() {
+ this._renderer.smooth();
+ return this;
+};
+
+/**
+ * Sets the style for rendering line endings. These ends are either squared,
+ * extended, or rounded, each of which specified with the corresponding
+ * parameters: SQUARE, PROJECT, and ROUND. The default cap is ROUND.
+ *
+ * @method strokeCap
+ * @param {Constant} cap either SQUARE, PROJECT, or ROUND
+ * @chainable
+ * @example
+ *
+ *
+ * strokeWeight(12.0);
+ * strokeCap(ROUND);
+ * line(20, 30, 80, 30);
+ * strokeCap(SQUARE);
+ * line(20, 50, 80, 50);
+ * strokeCap(PROJECT);
+ * line(20, 70, 80, 70);
+ *
+ *
+ *
+ * @alt
+ * 3 lines. Top line: rounded ends, mid: squared, bottom:longer squared ends.
+ *
+ */
+p5.prototype.strokeCap = function(cap) {
+ p5._validateParameters('strokeCap', arguments);
+ if (
+ cap === constants.ROUND ||
+ cap === constants.SQUARE ||
+ cap === constants.PROJECT
+ ) {
+ this._renderer.strokeCap(cap);
+ }
+ return this;
+};
+
+/**
+ * Sets the style of the joints which connect line segments. These joints
+ * are either mitered, beveled, or rounded and specified with the
+ * corresponding parameters MITER, BEVEL, and ROUND. The default joint is
+ * MITER.
+ *
+ * @method strokeJoin
+ * @param {Constant} join either MITER, BEVEL, ROUND
+ * @chainable
+ * @example
+ *
+ *
+ * noFill();
+ * strokeWeight(10.0);
+ * strokeJoin(MITER);
+ * beginShape();
+ * vertex(35, 20);
+ * vertex(65, 50);
+ * vertex(35, 80);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * noFill();
+ * strokeWeight(10.0);
+ * strokeJoin(BEVEL);
+ * beginShape();
+ * vertex(35, 20);
+ * vertex(65, 50);
+ * vertex(35, 80);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * noFill();
+ * strokeWeight(10.0);
+ * strokeJoin(ROUND);
+ * beginShape();
+ * vertex(35, 20);
+ * vertex(65, 50);
+ * vertex(35, 80);
+ * endShape();
+ *
+ *
+ *
+ * @alt
+ * Right-facing arrowhead shape with pointed tip in center of canvas.
+ * Right-facing arrowhead shape with flat tip in center of canvas.
+ * Right-facing arrowhead shape with rounded tip in center of canvas.
+ *
+ */
+p5.prototype.strokeJoin = function(join) {
+ p5._validateParameters('strokeJoin', arguments);
+ if (
+ join === constants.ROUND ||
+ join === constants.BEVEL ||
+ join === constants.MITER
+ ) {
+ this._renderer.strokeJoin(join);
+ }
+ return this;
+};
+
+/**
+ * Sets the width of the stroke used for lines, points, and the border
+ * around shapes. All widths are set in units of pixels.
+ *
+ * @method strokeWeight
+ * @param {Number} weight the weight (in pixels) of the stroke
+ * @chainable
+ * @example
+ *
+ *
+ * strokeWeight(1); // Default
+ * line(20, 20, 80, 20);
+ * strokeWeight(4); // Thicker
+ * line(20, 40, 80, 40);
+ * strokeWeight(10); // Beastly
+ * line(20, 70, 80, 70);
+ *
+ *
+ *
+ * @alt
+ * 3 horizontal black lines. Top line: thin, mid: medium, bottom:thick.
+ *
+ */
+p5.prototype.strokeWeight = function(w) {
+ p5._validateParameters('strokeWeight', arguments);
+ this._renderer.strokeWeight(w);
+ return this;
+};
+
+module.exports = p5;
+
+},{"./constants":21,"./core":22}],20:[function(_dereq_,module,exports){
+/**
+ * @requires constants
+ */
+
+'use strict';
+
+var constants = _dereq_('./constants');
+
+module.exports = {
+ modeAdjust: function(a, b, c, d, mode) {
+ if (mode === constants.CORNER) {
+ return { x: a, y: b, w: c, h: d };
+ } else if (mode === constants.CORNERS) {
+ return { x: a, y: b, w: c - a, h: d - b };
+ } else if (mode === constants.RADIUS) {
+ return { x: a - c, y: b - d, w: 2 * c, h: 2 * d };
+ } else if (mode === constants.CENTER) {
+ return { x: a - c * 0.5, y: b - d * 0.5, w: c, h: d };
+ }
+ },
+
+ arcModeAdjust: function(a, b, c, d, mode) {
+ if (mode === constants.CORNER) {
+ return { x: a + c * 0.5, y: b + d * 0.5, w: c, h: d };
+ } else if (mode === constants.CORNERS) {
+ return { x: a, y: b, w: c + a, h: d + b };
+ } else if (mode === constants.RADIUS) {
+ return { x: a, y: b, w: 2 * c, h: 2 * d };
+ } else if (mode === constants.CENTER) {
+ return { x: a, y: b, w: c, h: d };
+ }
+ }
+};
+
+},{"./constants":21}],21:[function(_dereq_,module,exports){
+/**
+ * @module Constants
+ * @submodule Constants
+ * @for p5
+ */
+
+'use strict';
+
+var PI = Math.PI;
+
+module.exports = {
+ // GRAPHICS RENDERER
+ /**
+ * @property {String} P2D
+ * @final
+ */
+ P2D: 'p2d',
+ /**
+ * @property {String} WEBGL
+ * @final
+ */
+ WEBGL: 'webgl',
+
+ // ENVIRONMENT
+ ARROW: 'default',
+ CROSS: 'crosshair',
+ HAND: 'pointer',
+ MOVE: 'move',
+ TEXT: 'text',
+ WAIT: 'wait',
+
+ // TRIGONOMETRY
+
+ /**
+ * HALF_PI is a mathematical constant with the value
+ * 1.57079632679489661923. It is half the ratio of the
+ * circumference of a circle to its diameter. It is useful in
+ * combination with the trigonometric functions sin() and cos().
+ *
+ * @property {Number} HALF_PI
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, HALF_PI);
+ *
+ *
+ * @alt
+ * 80x80 white quarter-circle with curve toward bottom right of canvas.
+ *
+ */
+ HALF_PI: PI / 2,
+ /**
+ * PI is a mathematical constant with the value
+ * 3.14159265358979323846. It is the ratio of the circumference
+ * of a circle to its diameter. It is useful in combination with
+ * the trigonometric functions sin() and cos().
+ *
+ * @property {Number} PI
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, PI);
+ *
+ *
+ * @alt
+ * white half-circle with curve toward bottom of canvas.
+ *
+ */
+ PI: PI,
+ /**
+ * QUARTER_PI is a mathematical constant with the value 0.7853982.
+ * It is one quarter the ratio of the circumference of a circle to
+ * its diameter. It is useful in combination with the trigonometric
+ * functions sin() and cos().
+ *
+ * @property {Number} QUARTER_PI
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, QUARTER_PI);
+ *
+ *
+ * @alt
+ * white eighth-circle rotated about 40 degrees with curve bottom right canvas.
+ *
+ */
+ QUARTER_PI: PI / 4,
+ /**
+ * TAU is an alias for TWO_PI, a mathematical constant with the
+ * value 6.28318530717958647693. It is twice the ratio of the
+ * circumference of a circle to its diameter. It is useful in
+ * combination with the trigonometric functions sin() and cos().
+ *
+ * @property {Number} TAU
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, TAU);
+ *
+ *
+ * @alt
+ * 80x80 white ellipse shape in center of canvas.
+ *
+ */
+ TAU: PI * 2,
+ /**
+ * TWO_PI is a mathematical constant with the value
+ * 6.28318530717958647693. It is twice the ratio of the
+ * circumference of a circle to its diameter. It is useful in
+ * combination with the trigonometric functions sin() and cos().
+ *
+ * @property {Number} TWO_PI
+ * @final
+ *
+ * @example
+ *
+ * arc(50, 50, 80, 80, 0, TWO_PI);
+ *
+ *
+ * @alt
+ * 80x80 white ellipse shape in center of canvas.
+ *
+ */
+ TWO_PI: PI * 2,
+ /**
+ * Constant to be used with angleMode() function, to set the mode which
+ * p5.js interprates and calculates angles (either DEGREES or RADIANS).
+ * @property {String} DEGREES
+ * @final
+ *
+ * @example
+ *
+ * function setup() {
+ * angleMode(DEGREES);
+ * }
+ *
+ */
+ DEGREES: 'degrees',
+ /**
+ * Constant to be used with angleMode() function, to set the mode which
+ * p5.js interprates and calculates angles (either RADIANS or DEGREES).
+ * @property {String} RADIANS
+ * @final
+ *
+ * @example
+ *
+ * function setup() {
+ * angleMode(RADIANS);
+ * }
+ *
+ */
+ RADIANS: 'radians',
+ DEG_TO_RAD: PI / 180.0,
+ RAD_TO_DEG: 180.0 / PI,
+
+ // SHAPE
+ /**
+ * @property {String} CORNER
+ * @final
+ */
+ CORNER: 'corner',
+ /**
+ * @property {String} CORNERS
+ * @final
+ */
+ CORNERS: 'corners',
+ /**
+ * @property {String} RADIUS
+ * @final
+ */
+ RADIUS: 'radius',
+ /**
+ * @property {String} RIGHT
+ * @final
+ */
+ RIGHT: 'right',
+ /**
+ * @property {String} LEFT
+ * @final
+ */
+ LEFT: 'left',
+ /**
+ * @property {String} CENTER
+ * @final
+ */
+ CENTER: 'center',
+ /**
+ * @property {String} TOP
+ * @final
+ */
+ TOP: 'top',
+ /**
+ * @property {String} BOTTOM
+ * @final
+ */
+ BOTTOM: 'bottom',
+ /**
+ * @property {String} BASELINE
+ * @final
+ * @default alphabetic
+ */
+ BASELINE: 'alphabetic',
+ /**
+ * @property {Number} POINTS
+ * @final
+ * @default 0x0000
+ */
+ POINTS: 0x0000,
+ /**
+ * @property {Number} LINES
+ * @final
+ * @default 0x0001
+ */
+ LINES: 0x0001,
+ /**
+ * @property {Number} LINE_STRIP
+ * @final
+ * @default 0x0003
+ */
+ LINE_STRIP: 0x0003,
+ /**
+ * @property {Number} LINE_LOOP
+ * @final
+ * @default 0x0002
+ */
+ LINE_LOOP: 0x0002,
+ /**
+ * @property {Number} TRIANGLES
+ * @final
+ * @default 0x0004
+ */
+ TRIANGLES: 0x0004,
+ /**
+ * @property {Number} TRIANGLE_FAN
+ * @final
+ * @default 0x0006
+ */
+ TRIANGLE_FAN: 0x0006,
+ /**
+ * @property {Number} TRIANGLE_STRIP
+ * @final
+ * @default 0x0005
+ */
+ TRIANGLE_STRIP: 0x0005,
+ /**
+ * @property {String} QUADS
+ * @final
+ */
+ QUADS: 'quads',
+ /**
+ * @property {String} QUAD_STRIP
+ * @final
+ * @default quad_strip
+ */
+ QUAD_STRIP: 'quad_strip',
+ /**
+ * @property {String} CLOSE
+ * @final
+ */
+ CLOSE: 'close',
+ /**
+ * @property {String} OPEN
+ * @final
+ */
+ OPEN: 'open',
+ /**
+ * @property {String} CHORD
+ * @final
+ */
+ CHORD: 'chord',
+ /**
+ * @property {String} PIE
+ * @final
+ */
+ PIE: 'pie',
+ /**
+ * @property {String} PROJECT
+ * @final
+ * @default square
+ */
+ PROJECT: 'square', // PEND: careful this is counterintuitive
+ /**
+ * @property {String} SQUARE
+ * @final
+ * @default butt
+ */
+ SQUARE: 'butt',
+ /**
+ * @property {String} ROUND
+ * @final
+ */
+ ROUND: 'round',
+ /**
+ * @property {String} BEVEL
+ * @final
+ */
+ BEVEL: 'bevel',
+ /**
+ * @property {String} MITER
+ * @final
+ */
+ MITER: 'miter',
+
+ // COLOR
+ /**
+ * @property {String} RGB
+ * @final
+ */
+ RGB: 'rgb',
+ /**
+ * @property {String} HSB
+ * @final
+ */
+ HSB: 'hsb',
+ /**
+ * @property {String} HSL
+ * @final
+ */
+ HSL: 'hsl',
+
+ // DOM EXTENSION
+ AUTO: 'auto',
+
+ // INPUT
+ ALT: 18,
+ BACKSPACE: 8,
+ CONTROL: 17,
+ DELETE: 46,
+ DOWN_ARROW: 40,
+ ENTER: 13,
+ ESCAPE: 27,
+ LEFT_ARROW: 37,
+ OPTION: 18,
+ RETURN: 13,
+ RIGHT_ARROW: 39,
+ SHIFT: 16,
+ TAB: 9,
+ UP_ARROW: 38,
+
+ // RENDERING
+ /**
+ * @property {String} BLEND
+ * @final
+ * @default source-over
+ */
+ BLEND: 'source-over',
+ /**
+ * @property {String} ADD
+ * @final
+ * @default lighter
+ */
+ ADD: 'lighter',
+ //ADD: 'add', //
+ //SUBTRACT: 'subtract', //
+ /**
+ * @property {String} DARKEST
+ * @final
+ */
+ DARKEST: 'darken',
+ /**
+ * @property {String} LIGHTEST
+ * @final
+ * @default lighten
+ */
+ LIGHTEST: 'lighten',
+ /**
+ * @property {String} DIFFERENCE
+ * @final
+ */
+ DIFFERENCE: 'difference',
+ /**
+ * @property {String} EXCLUSION
+ * @final
+ */
+ EXCLUSION: 'exclusion',
+ /**
+ * @property {String} MULTIPLY
+ * @final
+ */
+ MULTIPLY: 'multiply',
+ /**
+ * @property {String} SCREEN
+ * @final
+ */
+ SCREEN: 'screen',
+ /**
+ * @property {String} REPLACE
+ * @final
+ * @default copy
+ */
+ REPLACE: 'copy',
+ /**
+ * @property {String} OVERLAY
+ * @final
+ */
+ OVERLAY: 'overlay',
+ /**
+ * @property {String} HARD_LIGHT
+ * @final
+ */
+ HARD_LIGHT: 'hard-light',
+ /**
+ * @property {String} SOFT_LIGHT
+ * @final
+ */
+ SOFT_LIGHT: 'soft-light',
+ /**
+ * @property {String} DODGE
+ * @final
+ * @default color-dodge
+ */
+ DODGE: 'color-dodge',
+ /**
+ * @property {String} BURN
+ * @final
+ * @default color-burn
+ */
+ BURN: 'color-burn',
+
+ // FILTERS
+ /**
+ * @property {String} THRESHOLD
+ * @final
+ */
+ THRESHOLD: 'threshold',
+ /**
+ * @property {String} GRAY
+ * @final
+ */
+ GRAY: 'gray',
+ /**
+ * @property {String} OPAQUE
+ * @final
+ */
+ OPAQUE: 'opaque',
+ /**
+ * @property {String} INVERT
+ * @final
+ */
+ INVERT: 'invert',
+ /**
+ * @property {String} POSTERIZE
+ * @final
+ */
+ POSTERIZE: 'posterize',
+ /**
+ * @property {String} DILATE
+ * @final
+ */
+ DILATE: 'dilate',
+ /**
+ * @property {String} ERODE
+ * @final
+ */
+ ERODE: 'erode',
+ /**
+ * @property {String} BLUR
+ * @final
+ */
+ BLUR: 'blur',
+
+ // TYPOGRAPHY
+ /**
+ * @property {String} NORMAL
+ * @final
+ */
+ NORMAL: 'normal',
+ /**
+ * @property {String} ITALIC
+ * @final
+ */
+ ITALIC: 'italic',
+ /**
+ * @property {String} BOLD
+ * @final
+ */
+ BOLD: 'bold',
+
+ // TYPOGRAPHY-INTERNAL
+ _DEFAULT_TEXT_FILL: '#000000',
+ _DEFAULT_LEADMULT: 1.25,
+ _CTX_MIDDLE: 'middle',
+
+ // VERTICES
+ LINEAR: 'linear',
+ QUADRATIC: 'quadratic',
+ BEZIER: 'bezier',
+ CURVE: 'curve',
+
+ // WEBGL DRAWMODES
+ STROKE: 'stroke',
+ FILL: 'fill',
+ TEXTURE: 'texture',
+ IMMEDIATE: 'immediate',
+
+ // DEVICE-ORIENTATION
+ /**
+ * @property {String} LANDSCAPE
+ * @final
+ */
+ LANDSCAPE: 'landscape',
+ /**
+ * @property {String} PORTRAIT
+ * @final
+ */
+ PORTRAIT: 'portrait',
+
+ // DEFAULTS
+ _DEFAULT_STROKE: '#000000',
+ _DEFAULT_FILL: '#FFFFFF'
+};
+
+},{}],22:[function(_dereq_,module,exports){
+/**
+ * @module Structure
+ * @submodule Structure
+ * @for p5
+ * @requires constants
+ */
+
+'use strict';
+
+_dereq_('./shim');
+
+// Core needs the PVariables object
+var constants = _dereq_('./constants');
+
+/**
+ * This is the p5 instance constructor.
+ *
+ * A p5 instance holds all the properties and methods related to
+ * a p5 sketch. It expects an incoming sketch closure and it can also
+ * take an optional node parameter for attaching the generated p5 canvas
+ * to a node. The sketch closure takes the newly created p5 instance as
+ * its sole argument and may optionally set preload(), setup(), and/or
+ * draw() properties on it for running a sketch.
+ *
+ * A p5 sketch can run in "global" or "instance" mode:
+ * "global" - all properties and methods are attached to the window
+ * "instance" - all properties and methods are bound to this p5 object
+ *
+ * @class p5
+ * @constructor
+ * @param {function} sketch a closure that can set optional preload(),
+ * setup(), and/or draw() properties on the
+ * given p5 instance
+ * @param {HTMLElement|Boolean} [node] element to attach canvas to, if a
+ * boolean is passed in use it as sync
+ * @param {Boolean} [sync] start synchronously (optional)
+ * @return {p5} a p5 instance
+ */
+var p5 = function(sketch, node, sync) {
+ if (typeof node === 'boolean' && typeof sync === 'undefined') {
+ sync = node;
+ node = undefined;
+ }
+
+ //////////////////////////////////////////////
+ // PUBLIC p5 PROPERTIES AND METHODS
+ //////////////////////////////////////////////
+
+ /**
+ * Called directly before setup(), the preload() function is used to handle
+ * asynchronous loading of external files in a blocking way. If a preload
+ * function is defined, setup() will wait until any load calls within have
+ * finished. Nothing besides load calls (loadImage, loadJSON, loadFont,
+ * loadStrings, etc.) should be inside preload function. If asynchronous
+ * loading is preferred, the load methods can instead be called in setup()
+ * or anywhere else with the use of a callback parameter.
+ *
+ * By default the text "loading..." will be displayed. To make your own
+ * loading page, include an HTML element with id "p5_loading" in your
+ * page. More information here.
+ *
+ * @method preload
+ * @example
+ *
+ * var img;
+ * var c;
+ * function preload() {
+ // preload() runs once
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ *
+ * function setup() {
+ // setup() waits until preload() is done
+ * img.loadPixels();
+ * // get color of middle pixel
+ * c = img.get(img.width / 2, img.height / 2);
+ * }
+ *
+ * function draw() {
+ * background(c);
+ * image(img, 25, 25, 50, 50);
+ * }
+ *
+ *
+ * @alt
+ * nothing displayed
+ *
+ */
+
+ /**
+ * The setup() function is called once when the program starts. It's used to
+ * define initial environment properties such as screen size and background
+ * color and to load media such as images and fonts as the program starts.
+ * There can only be one setup() function for each program and it shouldn't
+ * be called again after its initial execution.
+ *
+ * Note: Variables declared within setup() are not accessible within other
+ * functions, including draw().
+ *
+ * @method setup
+ * @example
+ *
+ * var a = 0;
+ *
+ * function setup() {
+ * background(0);
+ * noStroke();
+ * fill(102);
+ * }
+ *
+ * function draw() {
+ * rect(a++ % width, 10, 2, 80);
+ * }
+ *
+ *
+ * @alt
+ * nothing displayed
+ *
+ */
+
+ /**
+ * Called directly after setup(), the draw() function continuously executes
+ * the lines of code contained inside its block until the program is stopped
+ * or noLoop() is called. Note if noLoop() is called in setup(), draw() will
+ * still be executed once before stopping. draw() is called automatically and
+ * should never be called explicitly.
+ *
+ * It should always be controlled with noLoop(), redraw() and loop(). After
+ * noLoop() stops the code in draw() from executing, redraw() causes the
+ * code inside draw() to execute once, and loop() will cause the code
+ * inside draw() to resume executing continuously.
+ *
+ * The number of times draw() executes in each second may be controlled with
+ * the frameRate() function.
+ *
+ * There can only be one draw() function for each sketch, and draw() must
+ * exist if you want the code to run continuously, or to process events such
+ * as mousePressed(). Sometimes, you might have an empty call to draw() in
+ * your program, as shown in the above example.
+ *
+ * It is important to note that the drawing coordinate system will be reset
+ * at the beginning of each draw() call. If any transformations are performed
+ * within draw() (ex: scale, rotate, translate), their effects will be
+ * undone at the beginning of draw(), so transformations will not accumulate
+ * over time. On the other hand, styling applied (ex: fill, stroke, etc) will
+ * remain in effect.
+ *
+ * @method draw
+ * @example
+ *
+ * var yPos = 0;
+ * function setup() {
+ // setup() runs once
+ * frameRate(30);
+ * }
+ * function draw() {
+ // draw() loops forever, until stopped
+ * background(204);
+ * yPos = yPos - 1;
+ * if (yPos < 0) {
+ * yPos = height;
+ * }
+ * line(0, yPos, width, yPos);
+ * }
+ *
+ *
+ * @alt
+ * nothing displayed
+ *
+ */
+
+ //////////////////////////////////////////////
+ // PRIVATE p5 PROPERTIES AND METHODS
+ //////////////////////////////////////////////
+
+ this._setupDone = false;
+ // for handling hidpi
+ this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1;
+ this._userNode = node;
+ this._curElement = null;
+ this._elements = [];
+ this._requestAnimId = 0;
+ this._preloadCount = 0;
+ this._isGlobal = false;
+ this._loop = true;
+ this._initializeInstanceVariables();
+ this._defaultCanvasSize = {
+ width: 100,
+ height: 100
+ };
+ this._events = {
+ // keep track of user-events for unregistering later
+ mousemove: null,
+ mousedown: null,
+ mouseup: null,
+ dragend: null,
+ dragover: null,
+ click: null,
+ dblclick: null,
+ mouseover: null,
+ mouseout: null,
+ keydown: null,
+ keyup: null,
+ keypress: null,
+ touchstart: null,
+ touchmove: null,
+ touchend: null,
+ resize: null,
+ blur: null
+ };
+
+ this._events.wheel = null;
+ this._loadingScreenId = 'p5_loading';
+
+ // Allows methods to be registered on an instance that
+ // are instance-specific.
+ this._registeredMethods = {};
+ var methods = Object.getOwnPropertyNames(p5.prototype._registeredMethods);
+ for (var i = 0; i < methods.length; i++) {
+ var prop = methods[i];
+ this._registeredMethods[prop] = p5.prototype._registeredMethods[
+ prop
+ ].slice();
+ }
+
+ if (window.DeviceOrientationEvent) {
+ this._events.deviceorientation = null;
+ }
+ if (window.DeviceMotionEvent && !window._isNodeWebkit) {
+ this._events.devicemotion = null;
+ }
+
+ this._start = function() {
+ // Find node if id given
+ if (this._userNode) {
+ if (typeof this._userNode === 'string') {
+ this._userNode = document.getElementById(this._userNode);
+ }
+ }
+
+ var userPreload = this.preload || window.preload; // look for "preload"
+ if (userPreload) {
+ // Setup loading screen
+ // Set loading screen into dom if not present
+ // Otherwise displays and removes user provided loading screen
+ var loadingScreen = document.getElementById(this._loadingScreenId);
+ if (!loadingScreen) {
+ loadingScreen = document.createElement('div');
+ loadingScreen.innerHTML = 'Loading...';
+ loadingScreen.style.position = 'absolute';
+ loadingScreen.id = this._loadingScreenId;
+ var node = this._userNode || document.body;
+ node.appendChild(loadingScreen);
+ }
+ // var methods = this._preloadMethods;
+ for (var method in this._preloadMethods) {
+ // default to p5 if no object defined
+ this._preloadMethods[method] = this._preloadMethods[method] || p5;
+ var obj = this._preloadMethods[method];
+ //it's p5, check if it's global or instance
+ if (obj === p5.prototype || obj === p5) {
+ if (this._isGlobal) {
+ window[method] = this._wrapPreload(this, method);
+ }
+ obj = this;
+ }
+ this._registeredPreloadMethods[method] = obj[method];
+ obj[method] = this._wrapPreload(obj, method);
+ }
+
+ userPreload();
+ this._runIfPreloadsAreDone();
+ } else {
+ this._setup();
+ this._runFrames();
+ this._draw();
+ }
+ }.bind(this);
+
+ this._runIfPreloadsAreDone = function() {
+ var context = this._isGlobal ? window : this;
+ if (context._preloadCount === 0) {
+ var loadingScreen = document.getElementById(context._loadingScreenId);
+ if (loadingScreen) {
+ loadingScreen.parentNode.removeChild(loadingScreen);
+ }
+ context._setup();
+ context._runFrames();
+ context._draw();
+ }
+ };
+
+ this._decrementPreload = function() {
+ var context = this._isGlobal ? window : this;
+ if (typeof context.preload === 'function') {
+ context._setProperty('_preloadCount', context._preloadCount - 1);
+ context._runIfPreloadsAreDone();
+ }
+ };
+
+ this._wrapPreload = function(obj, fnName) {
+ return function() {
+ //increment counter
+ this._incrementPreload();
+ //call original function
+ return this._registeredPreloadMethods[fnName].apply(obj, arguments);
+ }.bind(this);
+ };
+
+ this._incrementPreload = function() {
+ var context = this._isGlobal ? window : this;
+ context._setProperty('_preloadCount', context._preloadCount + 1);
+ };
+
+ this._setup = function() {
+ // Always create a default canvas.
+ // Later on if the user calls createCanvas, this default one
+ // will be replaced
+ this.createCanvas(
+ this._defaultCanvasSize.width,
+ this._defaultCanvasSize.height,
+ 'p2d'
+ );
+
+ // return preload functions to their normal vals if switched by preload
+ var context = this._isGlobal ? window : this;
+ if (typeof context.preload === 'function') {
+ for (var f in this._preloadMethods) {
+ context[f] = this._preloadMethods[f][f];
+ if (context[f] && this) {
+ context[f] = context[f].bind(this);
+ }
+ }
+ }
+
+ // Short-circuit on this, in case someone used the library in "global"
+ // mode earlier
+ if (typeof context.setup === 'function') {
+ context.setup();
+ }
+
+ // unhide any hidden canvases that were created
+ var canvases = document.getElementsByTagName('canvas');
+ for (var i = 0; i < canvases.length; i++) {
+ var k = canvases[i];
+ if (k.dataset.hidden === 'true') {
+ k.style.visibility = '';
+ delete k.dataset.hidden;
+ }
+ }
+ this._setupDone = true;
+ }.bind(this);
+
+ this._draw = function() {
+ var now = window.performance.now();
+ var time_since_last = now - this._lastFrameTime;
+ var target_time_between_frames = 1000 / this._targetFrameRate;
+
+ // only draw if we really need to; don't overextend the browser.
+ // draw if we're within 5ms of when our next frame should paint
+ // (this will prevent us from giving up opportunities to draw
+ // again when it's really about time for us to do so). fixes an
+ // issue where the frameRate is too low if our refresh loop isn't
+ // in sync with the browser. note that we have to draw once even
+ // if looping is off, so we bypass the time delay if that
+ // is the case.
+ var epsilon = 5;
+ if (
+ !this._loop ||
+ time_since_last >= target_time_between_frames - epsilon
+ ) {
+ //mandatory update values(matrixs and stack)
+
+ this.redraw();
+ this._frameRate = 1000.0 / (now - this._lastFrameTime);
+ this._lastFrameTime = now;
+
+ // If the user is actually using mouse module, then update
+ // coordinates, otherwise skip. We can test this by simply
+ // checking if any of the mouse functions are available or not.
+ // NOTE : This reflects only in complete build or modular build.
+ if (typeof this._updateMouseCoords !== 'undefined') {
+ this._updateMouseCoords();
+ }
+ }
+
+ // get notified the next time the browser gives us
+ // an opportunity to draw.
+ if (this._loop) {
+ this._requestAnimId = window.requestAnimationFrame(this._draw);
+ }
+ }.bind(this);
+
+ this._runFrames = function() {
+ if (this._updateInterval) {
+ clearInterval(this._updateInterval);
+ }
+ }.bind(this);
+
+ this._setProperty = function(prop, value) {
+ this[prop] = value;
+ if (this._isGlobal) {
+ window[prop] = value;
+ }
+ }.bind(this);
+
+ /**
+ * Removes the entire p5 sketch. This will remove the canvas and any
+ * elements created by p5.js. It will also stop the draw loop and unbind
+ * any properties or methods from the window global scope. It will
+ * leave a variable p5 in case you wanted to create a new p5 sketch.
+ * If you like, you can set p5 = null to erase it. While all functions and
+ * variables and objects created by the p5 library will be removed, any
+ * other global variables created by your code will remain.
+ *
+ * @method remove
+ * @example
+ *
+ * function draw() {
+ * ellipse(50, 50, 10, 10);
+ * }
+ *
+ * function mousePressed() {
+ * remove(); // remove whole sketch on mouse press
+ * }
+ *
+ *
+ * @alt
+ * nothing displayed
+ *
+ */
+ this.remove = function() {
+ var loadingScreen = document.getElementById(this._loadingScreenId);
+ if (loadingScreen) {
+ loadingScreen.parentNode.removeChild(loadingScreen);
+ // Add 1 to preload counter to prevent the sketch ever executing setup()
+ this._incrementPreload();
+ }
+ if (this._curElement) {
+ // stop draw
+ this._loop = false;
+ if (this._requestAnimId) {
+ window.cancelAnimationFrame(this._requestAnimId);
+ }
+
+ // unregister events sketch-wide
+ for (var ev in this._events) {
+ window.removeEventListener(ev, this._events[ev]);
+ }
+
+ // remove DOM elements created by p5, and listeners
+ for (var i = 0; i < this._elements.length; i++) {
+ var e = this._elements[i];
+ if (e.elt.parentNode) {
+ e.elt.parentNode.removeChild(e.elt);
+ }
+ for (var elt_ev in e._events) {
+ e.elt.removeEventListener(elt_ev, e._events[elt_ev]);
+ }
+ }
+
+ // call any registered remove functions
+ var self = this;
+ this._registeredMethods.remove.forEach(function(f) {
+ if (typeof f !== 'undefined') {
+ f.call(self);
+ }
+ });
+ }
+ // remove window bound properties and methods
+ if (this._isGlobal) {
+ for (var p in p5.prototype) {
+ try {
+ delete window[p];
+ } catch (x) {
+ window[p] = undefined;
+ }
+ }
+ for (var p2 in this) {
+ if (this.hasOwnProperty(p2)) {
+ try {
+ delete window[p2];
+ } catch (x) {
+ window[p2] = undefined;
+ }
+ }
+ }
+ p5.instance = null;
+ }
+ }.bind(this);
+
+ // call any registered init functions
+ this._registeredMethods.init.forEach(function(f) {
+ if (typeof f !== 'undefined') {
+ f.call(this);
+ }
+ }, this);
+
+ var friendlyBindGlobal = this._createFriendlyGlobalFunctionBinder();
+
+ // If the user has created a global setup or draw function,
+ // assume "global" mode and make everything global (i.e. on the window)
+ if (!sketch) {
+ this._isGlobal = true;
+ p5.instance = this;
+ // Loop through methods on the prototype and attach them to the window
+ for (var p in p5.prototype) {
+ if (typeof p5.prototype[p] === 'function') {
+ var ev = p.substring(2);
+ if (!this._events.hasOwnProperty(ev)) {
+ if (Math.hasOwnProperty(p) && Math[p] === p5.prototype[p]) {
+ // Multiple p5 methods are just native Math functions. These can be
+ // called without any binding.
+ friendlyBindGlobal(p, p5.prototype[p]);
+ } else {
+ friendlyBindGlobal(p, p5.prototype[p].bind(this));
+ }
+ }
+ } else {
+ friendlyBindGlobal(p, p5.prototype[p]);
+ }
+ }
+ // Attach its properties to the window
+ for (var p2 in this) {
+ if (this.hasOwnProperty(p2)) {
+ friendlyBindGlobal(p2, this[p2]);
+ }
+ }
+ } else {
+ // Else, the user has passed in a sketch closure that may set
+ // user-provided 'setup', 'draw', etc. properties on this instance of p5
+ sketch(this);
+ }
+
+ // Bind events to window (not using container div bc key events don't work)
+
+ for (var e in this._events) {
+ var f = this['_on' + e];
+ if (f) {
+ var m = f.bind(this);
+ window.addEventListener(e, m, { passive: false });
+ this._events[e] = m;
+ }
+ }
+
+ var focusHandler = function() {
+ this._setProperty('focused', true);
+ }.bind(this);
+ var blurHandler = function() {
+ this._setProperty('focused', false);
+ }.bind(this);
+ window.addEventListener('focus', focusHandler);
+ window.addEventListener('blur', blurHandler);
+ this.registerMethod('remove', function() {
+ window.removeEventListener('focus', focusHandler);
+ window.removeEventListener('blur', blurHandler);
+ });
+
+ if (sync) {
+ this._start();
+ } else {
+ if (document.readyState === 'complete') {
+ this._start();
+ } else {
+ window.addEventListener('load', this._start.bind(this), false);
+ }
+ }
+};
+
+p5.prototype._initializeInstanceVariables = function() {
+ this._styles = [];
+
+ this._bezierDetail = 20;
+ this._curveDetail = 20;
+
+ this._colorMode = constants.RGB;
+ this._colorMaxes = {
+ rgb: [255, 255, 255, 255],
+ hsb: [360, 100, 100, 1],
+ hsl: [360, 100, 100, 1]
+ };
+};
+
+// This is a pointer to our global mode p5 instance, if we're in
+// global mode.
+p5.instance = null;
+
+// Allows for the friendly error system to be turned off when creating a sketch,
+// which can give a significant boost to performance when needed.
+p5.disableFriendlyErrors = false;
+
+// attach constants to p5 prototype
+for (var k in constants) {
+ p5.prototype[k] = constants[k];
+}
+
+// functions that cause preload to wait
+// more can be added by using registerPreloadMethod(func)
+p5.prototype._preloadMethods = {
+ loadJSON: p5.prototype,
+ loadImage: p5.prototype,
+ loadStrings: p5.prototype,
+ loadXML: p5.prototype,
+ loadBytes: p5.prototype,
+ loadShape: p5.prototype,
+ loadTable: p5.prototype,
+ loadFont: p5.prototype,
+ loadModel: p5.prototype,
+ loadShader: p5.prototype
+};
+
+p5.prototype._registeredMethods = { init: [], pre: [], post: [], remove: [] };
+
+p5.prototype._registeredPreloadMethods = {};
+
+p5.prototype.registerPreloadMethod = function(fnString, obj) {
+ // obj = obj || p5.prototype;
+ if (!p5.prototype._preloadMethods.hasOwnProperty(fnString)) {
+ p5.prototype._preloadMethods[fnString] = obj;
+ }
+};
+
+p5.prototype.registerMethod = function(name, m) {
+ var target = this || p5.prototype;
+ if (!target._registeredMethods.hasOwnProperty(name)) {
+ target._registeredMethods[name] = [];
+ }
+ target._registeredMethods[name].push(m);
+};
+
+p5.prototype._createFriendlyGlobalFunctionBinder = function(options) {
+ options = options || {};
+
+ var globalObject = options.globalObject || window;
+ var log = options.log || console.log.bind(console);
+ var propsToForciblyOverwrite = {
+ // p5.print actually always overwrites an existing global function,
+ // albeit one that is very unlikely to be used:
+ //
+ // https://developer.mozilla.org/en-US/docs/Web/API/Window/print
+ print: true
+ };
+
+ return function(prop, value) {
+ if (
+ !p5.disableFriendlyErrors &&
+ typeof IS_MINIFIED === 'undefined' &&
+ typeof value === 'function' &&
+ !(prop in p5.prototype._preloadMethods)
+ ) {
+ try {
+ // Because p5 has so many common function names, it's likely
+ // that users may accidentally overwrite global p5 functions with
+ // their own variables. Let's allow this but log a warning to
+ // help users who may be doing this unintentionally.
+ //
+ // For more information, see:
+ //
+ // https://github.com/processing/p5.js/issues/1317
+
+ if (prop in globalObject && !(prop in propsToForciblyOverwrite)) {
+ throw new Error('global "' + prop + '" already exists');
+ }
+
+ // It's possible that this might throw an error because there
+ // are a lot of edge-cases in which `Object.defineProperty` might
+ // not succeed; since this functionality is only intended to
+ // help beginners anyways, we'll just catch such an exception
+ // if it occurs, and fall back to legacy behavior.
+ Object.defineProperty(globalObject, prop, {
+ configurable: true,
+ enumerable: true,
+ get: function() {
+ return value;
+ },
+ set: function(newValue) {
+ Object.defineProperty(globalObject, prop, {
+ configurable: true,
+ enumerable: true,
+ value: newValue,
+ writable: true
+ });
+ log(
+ 'You just changed the value of "' +
+ prop +
+ '", which was ' +
+ "a p5 function. This could cause problems later if you're " +
+ 'not careful.'
+ );
+ }
+ });
+ } catch (e) {
+ log(
+ 'p5 had problems creating the global function "' +
+ prop +
+ '", ' +
+ 'possibly because your code is already using that name as ' +
+ 'a variable. You may want to rename your variable to something ' +
+ 'else.'
+ );
+ globalObject[prop] = value;
+ }
+ } else {
+ globalObject[prop] = value;
+ }
+ };
+};
+
+module.exports = p5;
+
+},{"./constants":21,"./shim":32}],23:[function(_dereq_,module,exports){
+/**
+ * @module Shape
+ * @submodule Curves
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+_dereq_('./error_helpers');
+
+/**
+ * Draws a cubic Bezier curve on the screen. These curves are defined by a
+ * series of anchor and control points. The first two parameters specify
+ * the first anchor point and the last two parameters specify the other
+ * anchor point, which become the first and last points on the curve. The
+ * middle parameters specify the two control points which define the shape
+ * of the curve. Approximately speaking, control points "pull" the curve
+ * towards them.
Bezier curves were developed by French
+ * automotive engineer Pierre Bezier, and are commonly used in computer
+ * graphics to define gently sloping curves. See also curve().
+ *
+ * @method bezier
+ * @param {Number} x1 x-coordinate for the first anchor point
+ * @param {Number} y1 y-coordinate for the first anchor point
+ * @param {Number} x2 x-coordinate for the first control point
+ * @param {Number} y2 y-coordinate for the first control point
+ * @param {Number} x3 x-coordinate for the second control point
+ * @param {Number} y3 y-coordinate for the second control point
+ * @param {Number} x4 x-coordinate for the second anchor point
+ * @param {Number} y4 y-coordinate for the second anchor point
+ * @chainable
+ * @example
+ *
+ *
+ * noFill();
+ * stroke(255, 102, 0);
+ * line(85, 20, 10, 10);
+ * line(90, 90, 15, 80);
+ * stroke(0, 0, 0);
+ * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+ *
+ *
+ *
+ *
+ *
+ * background(0, 0, 0);
+ * noFill();
+ * stroke(255);
+ * bezier(250, 250, 0, 100, 100, 0, 100, 0, 0, 0, 100, 0);
+ *
+ *
+ *
+ * @alt
+ * stretched black s-shape in center with orange lines extending from end points.
+ * stretched black s-shape with 10 5x5 white ellipses along the shape.
+ * stretched black s-shape with 7 5x5 ellipses and orange lines along the shape.
+ * stretched black s-shape with 17 small orange lines extending from under shape.
+ * horseshoe shape with orange ends facing left and black curved center.
+ * horseshoe shape with orange ends facing left and black curved center.
+ * Line shaped like right-facing arrow,points move with mouse-x and warp shape.
+ * horizontal line that hooks downward on the right and 13 5x5 ellipses along it.
+ * right curving line mid-right of canvas with 7 short lines radiating from it.
+ */
+/**
+ * @method bezier
+ * @param {Number} x1
+ * @param {Number} y1
+ * @param {Number} z1 z-coordinate for the first anchor point
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 z-coordinate for the first control point
+ * @param {Number} x3
+ * @param {Number} y3
+ * @param {Number} z3 z-coordinate for the second control point
+ * @param {Number} x4
+ * @param {Number} y4
+ * @param {Number} z4 z-coordinate for the second anchor point
+ * @chainable
+ */
+p5.prototype.bezier = function() {
+ p5._validateParameters('bezier', arguments);
+
+ if (this._renderer._doStroke || this._renderer._doFill) {
+ this._renderer.bezier.apply(this._renderer, arguments);
+ }
+
+ return this;
+};
+
+/**
+ * Sets the resolution at which Beziers display.
+ *
+ * The default value is 20.
+ *
+ * This function is only useful when using the WEBGL renderer
+ * as the default canvas renderer does not use this information.
+ *
+ * @method bezierDetail
+ * @param {Number} detail resolution of the curves
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noFill();
+ *
+ * bezierDetail(5);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // prettier-ignore
+ * bezier(-40, -40, 0,
+ * 90, -40, 0,
+ * -90, 40, 0,
+ * 40, 40, 0);
+ * }
+ *
+ *
+ *
+ * @alt
+ * stretched black s-shape with a low level of bezier detail
+ *
+ */
+p5.prototype.bezierDetail = function(d) {
+ p5._validateParameters('bezierDetail', arguments);
+ this._bezierDetail = d;
+ return this;
+};
+
+/**
+ * Evaluates the Bezier at position t for points a, b, c, d.
+ * The parameters a and d are the first and last points
+ * on the curve, and b and c are the control points.
+ * The final parameter t varies between 0 and 1.
+ * This can be done once with the x coordinates and a second time
+ * with the y coordinates to get the location of a bezier curve at t.
+ *
+ * @method bezierPoint
+ * @param {Number} a coordinate of first point on the curve
+ * @param {Number} b coordinate of first control point
+ * @param {Number} c coordinate of second control point
+ * @param {Number} d coordinate of second point on the curve
+ * @param {Number} t value between 0 and 1
+ * @return {Number} the value of the Bezier at position t
+ * @example
+ *
+ *
+ * noFill();
+ * var x1 = 85,
+ x2 = 10,
+ x3 = 90,
+ x4 = 15;
+ * var y1 = 20,
+ y2 = 10,
+ y3 = 90,
+ y4 = 80;
+ * bezier(x1, y1, x2, y2, x3, y3, x4, y4);
+ * fill(255);
+ * var steps = 10;
+ * for (var i = 0; i <= steps; i++) {
+ * var t = i / steps;
+ * var x = bezierPoint(x1, x2, x3, x4, t);
+ * var y = bezierPoint(y1, y2, y3, y4, t);
+ * ellipse(x, y, 5, 5);
+ * }
+ *
+ *
+ *
+ * @alt
+ * stretched black s-shape with 17 small orange lines extending from under shape.
+ *
+ */
+p5.prototype.bezierPoint = function(a, b, c, d, t) {
+ p5._validateParameters('bezierPoint', arguments);
+
+ var adjustedT = 1 - t;
+ return (
+ Math.pow(adjustedT, 3) * a +
+ 3 * Math.pow(adjustedT, 2) * t * b +
+ 3 * adjustedT * Math.pow(t, 2) * c +
+ Math.pow(t, 3) * d
+ );
+};
+
+/**
+ * Evaluates the tangent to the Bezier at position t for points a, b, c, d.
+ * The parameters a and d are the first and last points
+ * on the curve, and b and c are the control points.
+ * The final parameter t varies between 0 and 1.
+ *
+ * @method bezierTangent
+ * @param {Number} a coordinate of first point on the curve
+ * @param {Number} b coordinate of first control point
+ * @param {Number} c coordinate of second control point
+ * @param {Number} d coordinate of second point on the curve
+ * @param {Number} t value between 0 and 1
+ * @return {Number} the tangent at position t
+ * @example
+ *
+ *
+ * noFill();
+ * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+ * var steps = 6;
+ * fill(255);
+ * for (var i = 0; i <= steps; i++) {
+ * var t = i / steps;
+ * // Get the location of the point
+ * var x = bezierPoint(85, 10, 90, 15, t);
+ * var y = bezierPoint(20, 10, 90, 80, t);
+ * // Get the tangent points
+ * var tx = bezierTangent(85, 10, 90, 15, t);
+ * var ty = bezierTangent(20, 10, 90, 80, t);
+ * // Calculate an angle from the tangent points
+ * var a = atan2(ty, tx);
+ * a += PI;
+ * stroke(255, 102, 0);
+ * line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);
+ * // The following line of code makes a line
+ * // inverse of the above line
+ * //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);
+ * stroke(0);
+ * ellipse(x, y, 5, 5);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * noFill();
+ * bezier(85, 20, 10, 10, 90, 90, 15, 80);
+ * stroke(255, 102, 0);
+ * var steps = 16;
+ * for (var i = 0; i <= steps; i++) {
+ * var t = i / steps;
+ * var x = bezierPoint(85, 10, 90, 15, t);
+ * var y = bezierPoint(20, 10, 90, 80, t);
+ * var tx = bezierTangent(85, 10, 90, 15, t);
+ * var ty = bezierTangent(20, 10, 90, 80, t);
+ * var a = atan2(ty, tx);
+ * a -= HALF_PI;
+ * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);
+ * }
+ *
+ *
+ *
+ * @alt
+ * s-shaped line with 17 short orange lines extending from underside of shape
+ *
+ */
+p5.prototype.bezierTangent = function(a, b, c, d, t) {
+ p5._validateParameters('bezierTangent', arguments);
+
+ var adjustedT = 1 - t;
+ return (
+ 3 * d * Math.pow(t, 2) -
+ 3 * c * Math.pow(t, 2) +
+ 6 * c * adjustedT * t -
+ 6 * b * adjustedT * t +
+ 3 * b * Math.pow(adjustedT, 2) -
+ 3 * a * Math.pow(adjustedT, 2)
+ );
+};
+
+/**
+ * Draws a curved line on the screen between two points, given as the
+ * middle four parameters. The first two parameters are a control point, as
+ * if the curve came from this point even though it's not drawn. The last
+ * two parameters similarly describe the other control point.
+ * Longer curves can be created by putting a series of curve() functions
+ * together or using curveVertex(). An additional function called
+ * curveTightness() provides control for the visual quality of the curve.
+ * The curve() function is an implementation of Catmull-Rom splines.
+ *
+ * @method curve
+ * @param {Number} x1 x-coordinate for the beginning control point
+ * @param {Number} y1 y-coordinate for the beginning control point
+ * @param {Number} x2 x-coordinate for the first point
+ * @param {Number} y2 y-coordinate for the first point
+ * @param {Number} x3 x-coordinate for the second point
+ * @param {Number} y3 y-coordinate for the second point
+ * @param {Number} x4 x-coordinate for the ending control point
+ * @param {Number} y4 y-coordinate for the ending control point
+ * @chainable
+ * @example
+ *
+ *
+ * noFill();
+ * stroke(255, 102, 0);
+ * curve(5, 26, 5, 26, 73, 24, 73, 61);
+ * stroke(0);
+ * curve(5, 26, 73, 24, 73, 61, 15, 65);
+ * stroke(255, 102, 0);
+ * curve(73, 24, 73, 61, 15, 65, 15, 65);
+ *
+ *
+ *
+ *
+ * // Define the curve points as JavaScript objects
+ * var p1 = { x: 5, y: 26 },
+ p2 = { x: 73, y: 24 };
+ * var p3 = { x: 73, y: 61 },
+ p4 = { x: 15, y: 65 };
+ * noFill();
+ * stroke(255, 102, 0);
+ * curve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
+ * stroke(0);
+ * curve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);
+ * stroke(255, 102, 0);
+ * curve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y);
+ *
+ *
+ *
+ *
+ * noFill();
+ * stroke(255, 102, 0);
+ * curve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0);
+ * stroke(0);
+ * curve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0);
+ * stroke(255, 102, 0);
+ * curve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0);
+ *
+ *
+ *
+ * @alt
+ * horseshoe shape with orange ends facing left and black curved center.
+ * horseshoe shape with orange ends facing left and black curved center.
+ * curving black and orange lines.
+ */
+/**
+ * @method curve
+ * @param {Number} x1
+ * @param {Number} y1
+ * @param {Number} z1 z-coordinate for the beginning control point
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 z-coordinate for the first point
+ * @param {Number} x3
+ * @param {Number} y3
+ * @param {Number} z3 z-coordinate for the second point
+ * @param {Number} x4
+ * @param {Number} y4
+ * @param {Number} z4 z-coordinate for the ending control point
+ * @chainable
+ */
+p5.prototype.curve = function() {
+ p5._validateParameters('curve', arguments);
+
+ if (this._renderer._doStroke) {
+ this._renderer.curve.apply(this._renderer, arguments);
+ }
+
+ return this;
+};
+
+/**
+ * Sets the resolution at which curves display.
+ *
+ * The default value is 20.
+ *
+ * This function is only useful when using the WEBGL renderer
+ * as the default canvas renderer does not use this
+ * information.
+ *
+ * @method curveDetail
+ * @param {Number} resolution of the curves
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ *
+ * curveDetail(5);
+ * }
+ * function draw() {
+ * background(200);
+ *
+ * // prettier-ignore
+ * curve( 250, 600, 0,
+ * -30, 40, 0,
+ * 30, 30, 0,
+ * -250, 600, 0);
+ * }
+ *
+ *
+ *
+ * @alt
+ * white arch shape with a low level of curve detail.
+ *
+ */
+p5.prototype.curveDetail = function(d) {
+ p5._validateParameters('curveDetail', arguments);
+ this._curveDetail = d;
+ return this;
+};
+
+/**
+ * Modifies the quality of forms created with curve() and curveVertex().
+ * The parameter tightness determines how the curve fits to the vertex
+ * points. The value 0.0 is the default value for tightness (this value
+ * defines the curves to be Catmull-Rom splines) and the value 1.0 connects
+ * all the points with straight lines. Values within the range -5.0 and 5.0
+ * will deform the curves but will leave them recognizable and as values
+ * increase in magnitude, they will continue to deform.
+ *
+ * @method curveTightness
+ * @param {Number} amount of deformation from the original vertices
+ * @chainable
+ * @example
+ *
+ *
+ * // Move the mouse left and right to see the curve change
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * noFill();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * var t = map(mouseX, 0, width, -5, 5);
+ * curveTightness(t);
+ * beginShape();
+ * curveVertex(10, 26);
+ * curveVertex(10, 26);
+ * curveVertex(83, 24);
+ * curveVertex(83, 61);
+ * curveVertex(25, 65);
+ * curveVertex(25, 65);
+ * endShape();
+ * }
+ *
+ *
+ *
+ * @alt
+ * Line shaped like right-facing arrow,points move with mouse-x and warp shape.
+ */
+p5.prototype.curveTightness = function(t) {
+ p5._validateParameters('curveTightness', arguments);
+ this._renderer._curveTightness = t;
+};
+
+/**
+ * Evaluates the curve at position t for points a, b, c, d.
+ * The parameter t varies between 0 and 1, a and d are points
+ * on the curve, and b and c are the control points.
+ * This can be done once with the x coordinates and a second time
+ * with the y coordinates to get the location of a curve at t.
+ *
+ * @method curvePoint
+ * @param {Number} a coordinate of first point on the curve
+ * @param {Number} b coordinate of first control point
+ * @param {Number} c coordinate of second control point
+ * @param {Number} d coordinate of second point on the curve
+ * @param {Number} t value between 0 and 1
+ * @return {Number} bezier value at position t
+ * @example
+ *
+ *
+ * noFill();
+ * curve(5, 26, 5, 26, 73, 24, 73, 61);
+ * curve(5, 26, 73, 24, 73, 61, 15, 65);
+ * fill(255);
+ * ellipseMode(CENTER);
+ * var steps = 6;
+ * for (var i = 0; i <= steps; i++) {
+ * var t = i / steps;
+ * var x = curvePoint(5, 5, 73, 73, t);
+ * var y = curvePoint(26, 26, 24, 61, t);
+ * ellipse(x, y, 5, 5);
+ * x = curvePoint(5, 73, 73, 15, t);
+ * y = curvePoint(26, 24, 61, 65, t);
+ * ellipse(x, y, 5, 5);
+ * }
+ *
+ *
+ *
+ *line hooking down to right-bottom with 13 5x5 white ellipse points
+ */
+p5.prototype.curvePoint = function(a, b, c, d, t) {
+ p5._validateParameters('curvePoint', arguments);
+
+ var t3 = t * t * t,
+ t2 = t * t,
+ f1 = -0.5 * t3 + t2 - 0.5 * t,
+ f2 = 1.5 * t3 - 2.5 * t2 + 1.0,
+ f3 = -1.5 * t3 + 2.0 * t2 + 0.5 * t,
+ f4 = 0.5 * t3 - 0.5 * t2;
+ return a * f1 + b * f2 + c * f3 + d * f4;
+};
+
+/**
+ * Evaluates the tangent to the curve at position t for points a, b, c, d.
+ * The parameter t varies between 0 and 1, a and d are points on the curve,
+ * and b and c are the control points.
+ *
+ * @method curveTangent
+ * @param {Number} a coordinate of first point on the curve
+ * @param {Number} b coordinate of first control point
+ * @param {Number} c coordinate of second control point
+ * @param {Number} d coordinate of second point on the curve
+ * @param {Number} t value between 0 and 1
+ * @return {Number} the tangent at position t
+ * @example
+ *
+ *
+ * noFill();
+ * curve(5, 26, 73, 24, 73, 61, 15, 65);
+ * var steps = 6;
+ * for (var i = 0; i <= steps; i++) {
+ * var t = i / steps;
+ * var x = curvePoint(5, 73, 73, 15, t);
+ * var y = curvePoint(26, 24, 61, 65, t);
+ * //ellipse(x, y, 5, 5);
+ * var tx = curveTangent(5, 73, 73, 15, t);
+ * var ty = curveTangent(26, 24, 61, 65, t);
+ * var a = atan2(ty, tx);
+ * a -= PI / 2.0;
+ * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);
+ * }
+ *
+ *
+ *
+ * @alt
+ *right curving line mid-right of canvas with 7 short lines radiating from it.
+ */
+p5.prototype.curveTangent = function(a, b, c, d, t) {
+ p5._validateParameters('curveTangent', arguments);
+
+ var t2 = t * t,
+ f1 = -3 * t2 / 2 + 2 * t - 0.5,
+ f2 = 9 * t2 / 2 - 5 * t,
+ f3 = -9 * t2 / 2 + 4 * t + 0.5,
+ f4 = 3 * t2 / 2 - t;
+ return a * f1 + b * f2 + c * f3 + d * f4;
+};
+
+module.exports = p5;
+
+},{"./core":22,"./error_helpers":25}],24:[function(_dereq_,module,exports){
+/**
+ * @module Environment
+ * @submodule Environment
+ * @for p5
+ * @requires core
+ * @requires constants
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+var C = _dereq_('./constants');
+
+var standardCursors = [C.ARROW, C.CROSS, C.HAND, C.MOVE, C.TEXT, C.WAIT];
+
+p5.prototype._frameRate = 0;
+p5.prototype._lastFrameTime = window.performance.now();
+p5.prototype._targetFrameRate = 60;
+
+var _windowPrint = window.print;
+
+/**
+ * The print() function writes to the console area of your browser.
+ * This function is often helpful for looking at the data a program is
+ * producing. This function creates a new line of text for each call to
+ * the function. Individual elements can be
+ * separated with quotes ("") and joined with the addition operator (+).
+ *
+ * @method print
+ * @param {Any} contents any combination of Number, String, Object, Boolean,
+ * Array to print
+ * @example
+ *
+ * var x = 10;
+ * print('The value of x is ' + x);
+ * // prints "The value of x is 10"
+ *
+ * @alt
+ * default grey canvas
+ */
+p5.prototype.print = function() {
+ if (!arguments.length) {
+ _windowPrint();
+ } else {
+ console.log.apply(console, arguments);
+ }
+};
+
+/**
+ * The system variable frameCount contains the number of frames that have
+ * been displayed since the program started. Inside setup() the value is 0,
+ * after the first iteration of draw it is 1, etc.
+ *
+ * @property {Integer} frameCount
+ * @readOnly
+ * @example
+ *
+ * function setup() {
+ * frameRate(30);
+ * textSize(20);
+ * textSize(30);
+ * textAlign(CENTER);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * text(frameCount, width / 2, height / 2);
+ * }
+
+ *
+ * @alt
+ * numbers rapidly counting upward with frame count set to 30.
+ *
+ */
+p5.prototype.frameCount = 0;
+
+/**
+ * Confirms if the window a p5.js program is in is "focused," meaning that
+ * the sketch will accept mouse or keyboard input. This variable is
+ * "true" if the window is focused and "false" if not.
+ *
+ * @property {Boolean} focused
+ * @readOnly
+ * @example
+ *
+ * // To demonstrate, put two windows side by side.
+ * // Click on the window that the p5 sketch isn't in!
+ * function draw() {
+ * background(200);
+ * noStroke();
+ * fill(0, 200, 0);
+ * ellipse(25, 25, 50, 50);
+ *
+ * if (!focused) {
+ // or "if (focused === false)"
+ * stroke(200, 0, 0);
+ * line(0, 0, 100, 100);
+ * line(100, 0, 0, 100);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * green 50x50 ellipse at top left. Red X covers canvas when page focus changes
+ *
+ */
+p5.prototype.focused = document.hasFocus();
+
+/**
+ * Sets the cursor to a predefined symbol or an image, or makes it visible
+ * if already hidden. If you are trying to set an image as the cursor, the
+ * recommended size is 16x16 or 32x32 pixels. It is not possible to load an
+ * image as the cursor if you are exporting your program for the Web, and not
+ * all MODES work with all browsers. The values for parameters x and y must
+ * be less than the dimensions of the image.
+ *
+ * @method cursor
+ * @param {String|Constant} type either ARROW, CROSS, HAND, MOVE, TEXT, or
+ * WAIT, or path for image
+ * @param {Number} [x] the horizontal active spot of the cursor
+ * @param {Number} [y] the vertical active spot of the cursor
+ * @example
+ *
+ * // Move the mouse left and right across the image
+ * // to see the cursor change from a cross to a hand
+ * function draw() {
+ * line(width / 2, 0, width / 2, height);
+ * if (mouseX < 50) {
+ * cursor(CROSS);
+ * } else {
+ * cursor(HAND);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * horizontal line divides canvas. cursor on left is a cross, right is hand.
+ *
+ */
+p5.prototype.cursor = function(type, x, y) {
+ var cursor = 'auto';
+ var canvas = this._curElement.elt;
+ if (standardCursors.indexOf(type) > -1) {
+ // Standard css cursor
+ cursor = type;
+ } else if (typeof type === 'string') {
+ var coords = '';
+ if (x && y && (typeof x === 'number' && typeof y === 'number')) {
+ // Note that x and y values must be unit-less positive integers < 32
+ // https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
+ coords = x + ' ' + y;
+ }
+ if (
+ type.substring(0, 7) === 'http://' ||
+ type.substring(0, 8) === 'https://'
+ ) {
+ // Image (absolute url)
+ cursor = 'url(' + type + ') ' + coords + ', auto';
+ } else if (/\.(cur|jpg|jpeg|gif|png|CUR|JPG|JPEG|GIF|PNG)$/.test(type)) {
+ // Image file (relative path) - Separated for performance reasons
+ cursor = 'url(' + type + ') ' + coords + ', auto';
+ } else {
+ // Any valid string for the css cursor property
+ cursor = type;
+ }
+ }
+ canvas.style.cursor = cursor;
+};
+
+/**
+ * Specifies the number of frames to be displayed every second. For example,
+ * the function call frameRate(30) will attempt to refresh 30 times a second.
+ * If the processor is not fast enough to maintain the specified rate, the
+ * frame rate will not be achieved. Setting the frame rate within setup() is
+ * recommended. The default rate is 60 frames per second. This is the same as
+ * setFrameRate(val).
+ *
+ * Calling frameRate() with no arguments returns the current framerate. The
+ * draw function must run at least once before it will return a value. This
+ * is the same as getFrameRate().
+ *
+ * Calling frameRate() with arguments that are not of the type numbers
+ * or are non positive also returns current framerate.
+ *
+ * @method frameRate
+ * @param {Number} fps number of frames to be displayed every second
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * var rectX = 0;
+ * var fr = 30; //starting FPS
+ * var clr;
+ *
+ * function setup() {
+ * background(200);
+ * frameRate(fr); // Attempt to refresh at starting FPS
+ * clr = color(255, 0, 0);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rectX = rectX += 1; // Move Rectangle
+ *
+ * if (rectX >= width) {
+ // If you go off screen.
+ * if (fr === 30) {
+ * clr = color(0, 0, 255);
+ * fr = 10;
+ * frameRate(fr); // make frameRate 10 FPS
+ * } else {
+ * clr = color(255, 0, 0);
+ * fr = 30;
+ * frameRate(fr); // make frameRate 30 FPS
+ * }
+ * rectX = 0;
+ * }
+ * fill(clr);
+ * rect(rectX, 40, 20, 20);
+ * }
+ *
+ *
+ * @alt
+ * blue rect moves left to right, followed by red rect moving faster. Loops.
+ *
+ */
+/**
+ * @method frameRate
+ * @return {Number} current frameRate
+ */
+p5.prototype.frameRate = function(fps) {
+ p5._validateParameters('frameRate', arguments);
+ if (typeof fps !== 'number' || fps < 0) {
+ return this._frameRate;
+ } else {
+ this._setProperty('_targetFrameRate', fps);
+ this._runFrames();
+ return this;
+ }
+};
+/**
+ * Returns the current framerate.
+ *
+ * @private
+ * @return {Number} current frameRate
+ */
+p5.prototype.getFrameRate = function() {
+ return this.frameRate();
+};
+
+/**
+ * Specifies the number of frames to be displayed every second. For example,
+ * the function call frameRate(30) will attempt to refresh 30 times a second.
+ * If the processor is not fast enough to maintain the specified rate, the
+ * frame rate will not be achieved. Setting the frame rate within setup() is
+ * recommended. The default rate is 60 frames per second.
+ *
+ * Calling frameRate() with no arguments returns the current framerate.
+ *
+ * @private
+ * @param {Number} [fps] number of frames to be displayed every second
+ */
+p5.prototype.setFrameRate = function(fps) {
+ return this.frameRate(fps);
+};
+
+/**
+ * Hides the cursor from view.
+ *
+ * @method noCursor
+ * @example
+ *
+ * function setup() {
+ * noCursor();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * ellipse(mouseX, mouseY, 10, 10);
+ * }
+ *
+ *
+ *
+ * @alt
+ * cursor becomes 10x 10 white ellipse the moves with mouse x and y.
+ *
+ */
+p5.prototype.noCursor = function() {
+ this._curElement.elt.style.cursor = 'none';
+};
+
+/**
+ * System variable that stores the width of the entire screen display. This
+ * is used to run a full-screen program on any display size.
+ *
+ * @property {Number} displayWidth
+ * @readOnly
+ * @example
+ *
+ * createCanvas(displayWidth, displayHeight);
+ *
+ *
+ * @alt
+ * cursor becomes 10x 10 white ellipse the moves with mouse x and y.
+ *
+ */
+p5.prototype.displayWidth = screen.width;
+
+/**
+ * System variable that stores the height of the entire screen display. This
+ * is used to run a full-screen program on any display size.
+ *
+ * @property {Number} displayHeight
+ * @readOnly
+ * @example
+ *
+ * createCanvas(displayWidth, displayHeight);
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.prototype.displayHeight = screen.height;
+
+/**
+ * System variable that stores the width of the inner window, it maps to
+ * window.innerWidth.
+ *
+ * @property {Number} windowWidth
+ * @readOnly
+ * @example
+ *
+ * createCanvas(windowWidth, windowHeight);
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.prototype.windowWidth = getWindowWidth();
+/**
+ * System variable that stores the height of the inner window, it maps to
+ * window.innerHeight.
+ *
+ * @property {Number} windowHeight
+ * @readOnly
+ * @example
+ *
+ * createCanvas(windowWidth, windowHeight);
+ *
+ *@alt
+ * no display.
+ *
+ */
+p5.prototype.windowHeight = getWindowHeight();
+
+/**
+ * The windowResized() function is called once every time the browser window
+ * is resized. This is a good place to resize the canvas or do any other
+ * adjustments to accommodate the new window size.
+ *
+ * @method windowResized
+ * @example
+ *
+ * function setup() {
+ * createCanvas(windowWidth, windowHeight);
+ * }
+ *
+ * function draw() {
+ * background(0, 100, 200);
+ * }
+ *
+ * function windowResized() {
+ * resizeCanvas(windowWidth, windowHeight);
+ * }
+ *
+ * @alt
+ * no display.
+ */
+p5.prototype._onresize = function(e) {
+ this._setProperty('windowWidth', getWindowWidth());
+ this._setProperty('windowHeight', getWindowHeight());
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ if (typeof context.windowResized === 'function') {
+ executeDefault = context.windowResized(e);
+ if (executeDefault !== undefined && !executeDefault) {
+ e.preventDefault();
+ }
+ }
+};
+
+function getWindowWidth() {
+ return (
+ window.innerWidth ||
+ (document.documentElement && document.documentElement.clientWidth) ||
+ (document.body && document.body.clientWidth) ||
+ 0
+ );
+}
+
+function getWindowHeight() {
+ return (
+ window.innerHeight ||
+ (document.documentElement && document.documentElement.clientHeight) ||
+ (document.body && document.body.clientHeight) ||
+ 0
+ );
+}
+
+/**
+ * System variable that stores the width of the drawing canvas. This value
+ * is set by the first parameter of the createCanvas() function.
+ * For example, the function call createCanvas(320, 240) sets the width
+ * variable to the value 320. The value of width defaults to 100 if
+ * createCanvas() is not used in a program.
+ *
+ * @property {Number} width
+ * @readOnly
+ */
+p5.prototype.width = 0;
+
+/**
+ * System variable that stores the height of the drawing canvas. This value
+ * is set by the second parameter of the createCanvas() function. For
+ * example, the function call createCanvas(320, 240) sets the height
+ * variable to the value 240. The value of height defaults to 100 if
+ * createCanvas() is not used in a program.
+ *
+ * @property {Number} height
+ * @readOnly
+ */
+p5.prototype.height = 0;
+
+/**
+ * If argument is given, sets the sketch to fullscreen or not based on the
+ * value of the argument. If no argument is given, returns the current
+ * fullscreen state. Note that due to browser restrictions this can only
+ * be called on user input, for example, on mouse press like the example
+ * below.
+ *
+ * @method fullscreen
+ * @param {Boolean} [val] whether the sketch should be in fullscreen mode
+ * or not
+ * @return {Boolean} current fullscreen state
+ * @example
+ *
+ *
+ * // Clicking in the box toggles fullscreen on and off.
+ * function setup() {
+ * background(200);
+ * }
+ * function mousePressed() {
+ * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {
+ * var fs = fullscreen();
+ * fullscreen(!fs);
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.prototype.fullscreen = function(val) {
+ p5._validateParameters('fullscreen', arguments);
+ // no arguments, return fullscreen or not
+ if (typeof val === 'undefined') {
+ return (
+ document.fullscreenElement ||
+ document.webkitFullscreenElement ||
+ document.mozFullScreenElement ||
+ document.msFullscreenElement
+ );
+ } else {
+ // otherwise set to fullscreen or not
+ if (val) {
+ launchFullscreen(document.documentElement);
+ } else {
+ exitFullscreen();
+ }
+ }
+};
+
+/**
+ * Sets the pixel scaling for high pixel density displays. By default
+ * pixel density is set to match display density, call pixelDensity(1)
+ * to turn this off. Calling pixelDensity() with no arguments returns
+ * the current pixel density of the sketch.
+ *
+ *
+ * @method pixelDensity
+ * @param {Number} [val] whether or how much the sketch should scale
+ * @returns {Number} current pixel density of the sketch
+ * @example
+ *
+ *
+ * function setup() {
+ * pixelDensity(1);
+ * createCanvas(100, 100);
+ * background(200);
+ * ellipse(width / 2, height / 2, 50, 50);
+ * }
+ *
+ *
+ *
+ *
+ * function setup() {
+ * pixelDensity(3.0);
+ * createCanvas(100, 100);
+ * background(200);
+ * ellipse(width / 2, height / 2, 50, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * fuzzy 50x50 white ellipse with black outline in center of canvas.
+ * sharp 50x50 white ellipse with black outline in center of canvas.
+ */
+p5.prototype.pixelDensity = function(val) {
+ p5._validateParameters('pixelDensity', arguments);
+ if (typeof val === 'number') {
+ this._pixelDensity = val;
+ } else {
+ return this._pixelDensity;
+ }
+ this.resizeCanvas(this.width, this.height, true);
+};
+
+/**
+ * Returns the pixel density of the current display the sketch is running on.
+ *
+ * @method displayDensity
+ * @returns {Number} current pixel density of the display
+ * @example
+ *
+ *
+ * function setup() {
+ * var density = displayDensity();
+ * pixelDensity(density);
+ * createCanvas(100, 100);
+ * background(200);
+ * ellipse(width / 2, height / 2, 50, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 white ellipse with black outline in center of canvas.
+ */
+p5.prototype.displayDensity = function() {
+ return window.devicePixelRatio;
+};
+
+function launchFullscreen(element) {
+ var enabled =
+ document.fullscreenEnabled ||
+ document.webkitFullscreenEnabled ||
+ document.mozFullScreenEnabled ||
+ document.msFullscreenEnabled;
+ if (!enabled) {
+ throw new Error('Fullscreen not enabled in this browser.');
+ }
+ if (element.requestFullscreen) {
+ element.requestFullscreen();
+ } else if (element.mozRequestFullScreen) {
+ element.mozRequestFullScreen();
+ } else if (element.webkitRequestFullscreen) {
+ element.webkitRequestFullscreen();
+ } else if (element.msRequestFullscreen) {
+ element.msRequestFullscreen();
+ }
+}
+
+function exitFullscreen() {
+ if (document.exitFullscreen) {
+ document.exitFullscreen();
+ } else if (document.mozCancelFullScreen) {
+ document.mozCancelFullScreen();
+ } else if (document.webkitExitFullscreen) {
+ document.webkitExitFullscreen();
+ } else if (document.msExitFullscreen) {
+ document.msExitFullscreen();
+ }
+}
+
+/**
+ * Gets the current URL.
+ * @method getURL
+ * @return {String} url
+ * @example
+ *
+ *
+ * var url;
+ * var x = 100;
+ *
+ * function setup() {
+ * fill(0);
+ * noStroke();
+ * url = getURL();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * text(url, x, height / 2);
+ * x--;
+ * }
+ *
+ *
+ *
+ * @alt
+ * current url (http://p5js.org/reference/#/p5/getURL) moves right to left.
+ *
+ */
+p5.prototype.getURL = function() {
+ return location.href;
+};
+/**
+ * Gets the current URL path as an array.
+ * @method getURLPath
+ * @return {String[]} path components
+ * @example
+ *
+ * function setup() {
+ * var urlPath = getURLPath();
+ * for (var i = 0; i < urlPath.length; i++) {
+ * text(urlPath[i], 10, i * 20 + 20);
+ * }
+ * }
+ *
+ *
+ * @alt
+ *no display
+ *
+ */
+p5.prototype.getURLPath = function() {
+ return location.pathname.split('/').filter(function(v) {
+ return v !== '';
+ });
+};
+/**
+ * Gets the current URL params as an Object.
+ * @method getURLParams
+ * @return {Object} URL params
+ * @example
+ *
+ *
+ * // Example: http://p5js.org?year=2014&month=May&day=15
+ *
+ * function setup() {
+ * var params = getURLParams();
+ * text(params.day, 10, 20);
+ * text(params.month, 10, 40);
+ * text(params.year, 10, 60);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.prototype.getURLParams = function() {
+ var re = /[?&]([^&=]+)(?:[&=])([^&=]+)/gim;
+ var m;
+ var v = {};
+ while ((m = re.exec(location.search)) != null) {
+ if (m.index === re.lastIndex) {
+ re.lastIndex++;
+ }
+ v[m[1]] = m[2];
+ }
+ return v;
+};
+
+module.exports = p5;
+
+},{"./constants":21,"./core":22}],25:[function(_dereq_,module,exports){
+/**
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+var constants = _dereq_('./constants');
+
+if (typeof IS_MINIFIED !== 'undefined') {
+ p5._validateParameters = p5._friendlyFileLoadError = function() {};
+} else {
+ var doFriendlyWelcome = false; // TEMP until we get it all working LM
+ // for parameter validation
+ var dataDoc = _dereq_('../../docs/reference/data.json');
+ var arrDoc = JSON.parse(JSON.stringify(dataDoc));
+
+ // -- Borrowed from jQuery 1.11.3 --
+ var class2type = {};
+ var toString = class2type.toString;
+ var names = [
+ 'Boolean',
+ 'Number',
+ 'String',
+ 'Function',
+ 'Array',
+ 'Date',
+ 'RegExp',
+ 'Object',
+ 'Error'
+ ];
+ for (var n = 0; n < names.length; n++) {
+ class2type['[object ' + names[n] + ']'] = names[n].toLowerCase();
+ }
+ var getType = function(obj) {
+ if (obj == null) {
+ return obj + '';
+ }
+ return typeof obj === 'object' || typeof obj === 'function'
+ ? class2type[toString.call(obj)] || 'object'
+ : typeof obj;
+ };
+
+ // -- End borrow --
+
+ var friendlyWelcome = function() {
+ // p5.js brand - magenta: #ED225D
+ //var astrixBgColor = 'transparent';
+ //var astrixTxtColor = '#ED225D';
+ //var welcomeBgColor = '#ED225D';
+ //var welcomeTextColor = 'white';
+ console.log(
+ ' _ \n' +
+ ' /\\| |/\\ \n' +
+ " \\ ` ' / \n" +
+ ' / , . \\ \n' +
+ ' \\/|_|\\/ ' +
+ '\n\n> p5.js says: Welcome! ' +
+ 'This is your friendly debugger. ' +
+ 'To turn me off switch to using “p5.min.js”.'
+ );
+ };
+
+ /**
+ * Prints out a fancy, colorful message to the console log
+ *
+ * @private
+ * @param {String} message the words to be said
+ * @param {String} func the name of the function to link
+ * @param {Number|String} color CSS color string or error type
+ *
+ * @return console logs
+ */
+ // Wrong number of params, undefined param, wrong type
+ var FILE_LOAD = 3;
+ var ERR_PARAMS = 3;
+ // p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta
+ // See testColors below for all the color codes and names
+ var typeColors = ['#2D7BB6', '#EE9900', '#4DB200', '#C83C00'];
+ var report = function(message, func, color) {
+ if (doFriendlyWelcome) {
+ friendlyWelcome();
+ doFriendlyWelcome = false;
+ }
+ if ('undefined' === getType(color)) {
+ color = '#B40033'; // dark magenta
+ } else if (getType(color) === 'number') {
+ // Type to color
+ color = typeColors[color];
+ }
+ if (func.substring(0, 4) === 'load') {
+ console.log(
+ '> p5.js says: ' +
+ message +
+ '[https://github.com/processing/p5.js/wiki/Local-server]'
+ );
+ } else {
+ console.log(
+ '> p5.js says: ' +
+ message +
+ ' [http://p5js.org/reference/#p5/' +
+ func +
+ ']'
+ );
+ }
+ };
+
+ var errorCases = {
+ '0': {
+ fileType: 'image',
+ method: 'loadImage',
+ message: ' hosting the image online,'
+ },
+ '1': {
+ fileType: 'XML file',
+ method: 'loadXML'
+ },
+ '2': {
+ fileType: 'table file',
+ method: 'loadTable'
+ },
+ '3': {
+ fileType: 'text file',
+ method: 'loadStrings'
+ },
+ '4': {
+ fileType: 'font',
+ method: 'loadFont',
+ message: ' hosting the font online,'
+ }
+ };
+ p5._friendlyFileLoadError = function(errorType, filePath) {
+ var errorInfo = errorCases[errorType];
+ var message =
+ 'It looks like there was a problem' +
+ ' loading your ' +
+ errorInfo.fileType +
+ '.' +
+ ' Try checking if the file path [' +
+ filePath +
+ '] is correct,' +
+ (errorInfo.message || '') +
+ ' or running a local server.';
+ report(message, errorInfo.method, FILE_LOAD);
+ };
+
+ var docCache = {};
+ var builtinTypes = [
+ 'number',
+ 'string',
+ 'boolean',
+ 'constant',
+ 'function',
+ 'any',
+ 'integer'
+ ];
+
+ // validateParameters() helper functions:
+ // lookupParamDoc() for querying data.json
+ var lookupParamDoc = function(func) {
+ var queryResult = arrDoc.classitems.filter(function(x) {
+ return x.name === func;
+ });
+ // different JSON structure for funct with multi-format
+ var overloads = [];
+ if (queryResult[0].hasOwnProperty('overloads')) {
+ for (var i = 0; i < queryResult[0].overloads.length; i++) {
+ overloads.push(queryResult[0].overloads[i].params);
+ }
+ } else {
+ overloads.push(queryResult[0].params || []);
+ }
+
+ var mapConstants = {};
+ var maxParams = 0;
+ overloads.forEach(function(formats) {
+ if (maxParams < formats.length) {
+ maxParams = formats.length;
+ }
+ formats.forEach(function(format) {
+ format.types = format.type.split('|').map(function ct(type) {
+ // array
+ if (type.substr(type.length - 2, 2) === '[]') {
+ return {
+ name: type,
+ array: ct(type.substr(0, type.length - 2))
+ };
+ }
+
+ var lowerType = type.toLowerCase();
+
+ // contant
+ if (lowerType === 'constant') {
+ var constant;
+ if (mapConstants.hasOwnProperty(format.name)) {
+ constant = mapConstants[format.name];
+ } else {
+ // parse possible constant values from description
+ var myRe = /either\s+(?:[A-Z0-9_]+\s*,?\s*(?:or)?\s*)+/g;
+ var values = {};
+ var names = [];
+
+ constant = mapConstants[format.name] = {
+ values: values,
+ names: names
+ };
+
+ var myArray = myRe.exec(format.description);
+ if (func === 'endShape' && format.name === 'mode') {
+ values[constants.CLOSE] = true;
+ names.push('CLOSE');
+ } else {
+ var match = myArray[0];
+ var reConst = /[A-Z0-9_]+/g;
+ var matchConst;
+ while ((matchConst = reConst.exec(match)) !== null) {
+ var name = matchConst[0];
+ if (constants.hasOwnProperty(name)) {
+ values[constants[name]] = true;
+ names.push(name);
+ }
+ }
+ }
+ }
+ return {
+ name: type,
+ builtin: lowerType,
+ names: constant.names,
+ values: constant.values
+ };
+ }
+
+ // function
+ if (lowerType.substr(0, 'function'.length) === 'function') {
+ lowerType = 'function';
+ }
+ // builtin
+ if (builtinTypes.indexOf(lowerType) >= 0) {
+ return { name: type, builtin: lowerType };
+ }
+
+ // find type's prototype
+ var t = window;
+ var typeParts = type.split('.');
+
+ // special-case 'p5' since it may be non-global
+ if (typeParts[0] === 'p5') {
+ t = p5;
+ typeParts.shift();
+ }
+
+ typeParts.forEach(function(p) {
+ t = t && t[p];
+ });
+ if (t) {
+ return { name: type, prototype: t };
+ }
+
+ return { name: type, type: lowerType };
+ });
+ });
+ });
+ return {
+ overloads: overloads,
+ maxParams: maxParams
+ };
+ };
+
+ var testParamType = function(param, type) {
+ var isArray = param instanceof Array;
+ if (type.array && isArray) {
+ for (var i = 0; i < param.length; i++) {
+ if (!testParamType(param[i], type.array)) {
+ return false;
+ }
+ }
+ return true;
+ } else if (type.prototype) {
+ return param instanceof type.prototype;
+ } else if (type.builtin) {
+ switch (type.builtin) {
+ case 'number':
+ return typeof param === 'number' || (!!param && !isNaN(param));
+ case 'integer':
+ return (
+ (typeof param === 'number' || (!!param && !isNaN(param))) &&
+ Number(param) === Math.floor(param)
+ );
+ case 'boolean':
+ case 'any':
+ return true;
+ case 'array':
+ return isArray;
+ case 'string':
+ return typeof param === 'number' || typeof param === 'string';
+ case 'constant':
+ return type.values.hasOwnProperty(param);
+ case 'function':
+ return param instanceof Function;
+ }
+ }
+
+ return typeof param === type.t;
+ };
+
+ // testType() for non-object type parameter validation
+ // Returns true if PASS, false if FAIL
+ var testParamTypes = function(param, types) {
+ for (var i = 0; i < types.length; i++) {
+ if (testParamType(param, types[i])) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ var testParamFormat = function(args, formats) {
+ var errorArray = [];
+ for (var p = 0; p < formats.length; p++) {
+ var arg = args[p];
+ var format = formats[p];
+ var argType = typeof arg;
+ if ('undefined' === argType || null === arg) {
+ if (format.optional !== true) {
+ errorArray.push({
+ type: 'EMPTY_VAR',
+ position: p,
+ format: format
+ });
+ }
+ } else if (!testParamTypes(arg, format.types)) {
+ errorArray.push({
+ type: 'WRONG_TYPE',
+ position: p,
+ format: format,
+ arg: arg
+ });
+ }
+ }
+ return errorArray;
+ };
+
+ // function for generating console.log() msg
+ p5._friendlyParamError = function(errorObj, func) {
+ var message;
+
+ function formatType() {
+ var format = errorObj.format;
+ return format.types
+ .map(function(type) {
+ return type.names ? type.names.join('|') : type.name;
+ })
+ .join('|');
+ }
+
+ switch (errorObj.type) {
+ case 'EMPTY_VAR':
+ message =
+ func +
+ '() was expecting ' +
+ formatType() +
+ ' for parameter #' +
+ errorObj.position +
+ ' (zero-based index), received an empty variable instead.' +
+ ' If not intentional, this is often a problem with scope:' +
+ ' [https://p5js.org/examples/data-variable-scope.html]';
+ break;
+ case 'WRONG_TYPE':
+ var arg = errorObj.arg;
+ var argType = arg instanceof Array ? 'array' : arg.name || typeof arg;
+ message =
+ func +
+ '() was expecting ' +
+ formatType() +
+ ' for parameter #' +
+ errorObj.position +
+ ' (zero-based index), received ' +
+ argType +
+ ' instead';
+ break;
+ case 'WRONG_ARGUMENT_COUNT':
+ message =
+ func +
+ '() was expecting ' +
+ errorObj.maxParams +
+ ' arguments, but received ' +
+ errorObj.argCount;
+ break;
+ }
+
+ if (message) {
+ try {
+ var re = /Function\.validateParameters.*[\r\n].*[\r\n].*\(([^)]*)/;
+ var location = re.exec(new Error().stack)[1];
+ if (location) {
+ message += ' at ' + location;
+ }
+ } catch (err) {}
+
+ report(message + '.', func, ERR_PARAMS);
+ }
+ };
+
+ /**
+ * Validates parameters
+ * param {String} func the name of the function
+ * param {Array} args user input arguments
+ *
+ * example:
+ * var a;
+ * ellipse(10,10,a,5);
+ * console ouput:
+ * "It looks like ellipse received an empty variable in spot #2."
+ *
+ * example:
+ * ellipse(10,"foo",5,5);
+ * console output:
+ * "ellipse was expecting a number for parameter #1,
+ * received "foo" instead."
+ */
+ p5._validateParameters = function validateParameters(func, args) {
+ if (p5.disableFriendlyErrors) {
+ return; // skip FES
+ }
+
+ var docs = docCache[func] || (docCache[func] = lookupParamDoc(func));
+ var errorArray = [];
+ var minErrCount = 999999;
+ var overloads = docs.overloads;
+ for (var i = 0; i < overloads.length; i++) {
+ var arrError = testParamFormat(args, overloads[i]);
+ // see if this is the format with min number of err
+ if (minErrCount > arrError.length) {
+ minErrCount = arrError.length;
+ errorArray = arrError;
+ }
+ if (arrError.length === 0) {
+ break; // no error
+ }
+ }
+
+ if (!errorArray.length && args.length > docs.maxParams) {
+ errorArray.push({
+ type: 'WRONG_ARGUMENT_COUNT',
+ argCount: args.length,
+ maxParams: docs.maxParams
+ });
+ }
+
+ // generate err msg
+ for (var n = 0; n < errorArray.length; n++) {
+ p5._friendlyParamError(errorArray[n], func);
+ }
+ };
+
+ /**
+ * Prints out all the colors in the color pallete with white text.
+ * For color blindness testing.
+ */
+ /* function testColors() {
+ var str = 'A box of biscuits, a box of mixed biscuits and a biscuit mixer';
+ report(str, 'print', '#ED225D'); // p5.js magenta
+ report(str, 'print', '#2D7BB6'); // p5.js blue
+ report(str, 'print', '#EE9900'); // p5.js orange
+ report(str, 'print', '#A67F59'); // p5.js light brown
+ report(str, 'print', '#704F21'); // p5.js gold
+ report(str, 'print', '#1CC581'); // auto cyan
+ report(str, 'print', '#FF6625'); // auto orange
+ report(str, 'print', '#79EB22'); // auto green
+ report(str, 'print', '#B40033'); // p5.js darkened magenta
+ report(str, 'print', '#084B7F'); // p5.js darkened blue
+ report(str, 'print', '#945F00'); // p5.js darkened orange
+ report(str, 'print', '#6B441D'); // p5.js darkened brown
+ report(str, 'print', '#2E1B00'); // p5.js darkened gold
+ report(str, 'print', '#008851'); // auto dark cyan
+ report(str, 'print', '#C83C00'); // auto dark orange
+ report(str, 'print', '#4DB200'); // auto dark green
+ } */
+
+ p5.prototype._validateParameters = p5.validateParameters;
+}
+
+// This is a lazily-defined list of p5 symbols that may be
+// misused by beginners at top-level code, outside of setup/draw. We'd like
+// to detect these errors and help the user by suggesting they move them
+// into setup/draw.
+//
+// For more details, see https://github.com/processing/p5.js/issues/1121.
+var misusedAtTopLevelCode = null;
+var FAQ_URL =
+ 'https://github.com/processing/p5.js/wiki/' +
+ 'Frequently-Asked-Questions' +
+ '#why-cant-i-assign-variables-using-p5-functions-and-' +
+ 'variables-before-setup';
+
+var defineMisusedAtTopLevelCode = function() {
+ var uniqueNamesFound = {};
+
+ var getSymbols = function(obj) {
+ return Object.getOwnPropertyNames(obj)
+ .filter(function(name) {
+ if (name[0] === '_') {
+ return false;
+ }
+ if (name in uniqueNamesFound) {
+ return false;
+ }
+
+ uniqueNamesFound[name] = true;
+
+ return true;
+ })
+ .map(function(name) {
+ var type;
+
+ if (typeof obj[name] === 'function') {
+ type = 'function';
+ } else if (name === name.toUpperCase()) {
+ type = 'constant';
+ } else {
+ type = 'variable';
+ }
+
+ return { name: name, type: type };
+ });
+ };
+
+ misusedAtTopLevelCode = [].concat(
+ getSymbols(p5.prototype),
+ // At present, p5 only adds its constants to p5.prototype during
+ // construction, which may not have happened at the time a
+ // ReferenceError is thrown, so we'll manually add them to our list.
+ getSymbols(_dereq_('./constants'))
+ );
+
+ // This will ultimately ensure that we report the most specific error
+ // possible to the user, e.g. advising them about HALF_PI instead of PI
+ // when their code misuses the former.
+ misusedAtTopLevelCode.sort(function(a, b) {
+ return b.name.length - a.name.length;
+ });
+};
+
+var helpForMisusedAtTopLevelCode = function(e, log) {
+ if (!log) {
+ log = console.log.bind(console);
+ }
+
+ if (!misusedAtTopLevelCode) {
+ defineMisusedAtTopLevelCode();
+ }
+
+ // If we find that we're logging lots of false positives, we can
+ // uncomment the following code to avoid displaying anything if the
+ // user's code isn't likely to be using p5's global mode. (Note that
+ // setup/draw are more likely to be defined due to JS function hoisting.)
+ //
+ //if (!('setup' in window || 'draw' in window)) {
+ // return;
+ //}
+
+ misusedAtTopLevelCode.some(function(symbol) {
+ // Note that while just checking for the occurrence of the
+ // symbol name in the error message could result in false positives,
+ // a more rigorous test is difficult because different browsers
+ // log different messages, and the format of those messages may
+ // change over time.
+ //
+ // For example, if the user uses 'PI' in their code, it may result
+ // in any one of the following messages:
+ //
+ // * 'PI' is undefined (Microsoft Edge)
+ // * ReferenceError: PI is undefined (Firefox)
+ // * Uncaught ReferenceError: PI is not defined (Chrome)
+
+ if (e.message && e.message.match('\\W?' + symbol.name + '\\W') !== null) {
+ log(
+ "Did you just try to use p5.js's " +
+ symbol.name +
+ (symbol.type === 'function' ? '() ' : ' ') +
+ symbol.type +
+ '? If so, you may want to ' +
+ "move it into your sketch's setup() function.\n\n" +
+ 'For more details, see: ' +
+ FAQ_URL
+ );
+ return true;
+ }
+ });
+};
+
+// Exposing this primarily for unit testing.
+p5.prototype._helpForMisusedAtTopLevelCode = helpForMisusedAtTopLevelCode;
+
+if (document.readyState !== 'complete') {
+ window.addEventListener('error', helpForMisusedAtTopLevelCode, false);
+
+ // Our job is only to catch ReferenceErrors that are thrown when
+ // global (non-instance mode) p5 APIs are used at the top-level
+ // scope of a file, so we'll unbind our error listener now to make
+ // sure we don't log false positives later.
+ window.addEventListener('load', function() {
+ window.removeEventListener('error', helpForMisusedAtTopLevelCode, false);
+ });
+}
+
+module.exports = p5;
+
+},{"../../docs/reference/data.json":1,"./constants":21,"./core":22}],26:[function(_dereq_,module,exports){
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+/**
+ * _globalInit
+ *
+ * TODO: ???
+ * if sketch is on window
+ * assume "global" mode
+ * and instantiate p5 automatically
+ * otherwise do nothing
+ *
+ * @private
+ * @return {Undefined}
+ */
+var _globalInit = function() {
+ if (!window.PHANTOMJS && !window.mocha) {
+ // If there is a setup or draw function on the window
+ // then instantiate p5 in "global" mode
+ if (
+ ((window.setup && typeof window.setup === 'function') ||
+ (window.draw && typeof window.draw === 'function')) &&
+ !p5.instance
+ ) {
+ new p5();
+ }
+ }
+};
+
+// TODO: ???
+if (document.readyState === 'complete') {
+ _globalInit();
+} else {
+ window.addEventListener('load', _globalInit, false);
+}
+
+},{"../core/core":22}],27:[function(_dereq_,module,exports){
+/**
+ * @module DOM
+ * @submodule DOM
+ * @for p5.Element
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+
+/**
+ * Base class for all elements added to a sketch, including canvas,
+ * graphics buffers, and other HTML elements. Methods in blue are
+ * included in the core functionality, methods in brown are added
+ * with the p5.dom
+ * library.
+ * It is not called directly, but p5.Element
+ * objects are created by calling createCanvas, createGraphics,
+ * or in the p5.dom library, createDiv, createImg, createInput, etc.
+ *
+ * @class p5.Element
+ * @param {String} elt DOM node that is wrapped
+ * @param {p5} [pInst] pointer to p5 instance
+ */
+p5.Element = function(elt, pInst) {
+ /**
+ * Underlying HTML element. All normal HTML methods can be called on this.
+ * @example
+ *
+ *
+ * createCanvas(300, 500);
+ * background(0, 0, 0, 0);
+ * var input = createInput();
+ * input.position(20, 225);
+ * var inputElem = new p5.Element(input.elt);
+ * inputElem.style('width:450px;');
+ * inputElem.value('some string');
+ *
+ *
+ *
+ * @property elt
+ * @readOnly
+ */
+ this.elt = elt;
+ this._pInst = pInst;
+ this._events = {};
+ this.width = this.elt.offsetWidth;
+ this.height = this.elt.offsetHeight;
+};
+
+/**
+ *
+ * Attaches the element to the parent specified. A way of setting
+ * the container for the element. Accepts either a string ID, DOM
+ * node, or p5.Element. If no arguments given, parent node is returned.
+ * For more ways to position the canvas, see the
+ *
+ * positioning the canvas wiki page.
+ *
+ * @method parent
+ * @param {String|p5.Element|Object} parent the ID, DOM node, or p5.Element
+ * of desired parent element
+ * @chainable
+ *
+ * @example
+ *
+ * // in the html file:
+ * // <div id="myContainer"></div>
+ *
+ * // in the js file:
+ * var cnv = createCanvas(100, 100);
+ * cnv.parent('myContainer');
+ *
+ *
+ * var div0 = createDiv('this is the parent');
+ * var div1 = createDiv('this is the child');
+ * div1.parent(div0); // use p5.Element
+ *
+ *
+ * var div0 = createDiv('this is the parent');
+ * div0.id('apples');
+ * var div1 = createDiv('this is the child');
+ * div1.parent('apples'); // use id
+ *
+ *
+ * var elt = document.getElementById('myParentDiv');
+ * var div1 = createDiv('this is the child');
+ * div1.parent(elt); // use element from page
+ *
+ *
+ * @alt
+ * no display.
+ */
+/**
+ * @method parent
+ * @return {p5.Element}
+ *
+ */
+p5.Element.prototype.parent = function(p) {
+ if (typeof p === 'undefined') {
+ return this.elt.parentNode;
+ }
+
+ if (typeof p === 'string') {
+ if (p[0] === '#') {
+ p = p.substring(1);
+ }
+ p = document.getElementById(p);
+ } else if (p instanceof p5.Element) {
+ p = p.elt;
+ }
+ p.appendChild(this.elt);
+ return this;
+};
+
+/**
+ *
+ * Sets the ID of the element. If no ID argument is passed in, it instead
+ * returns the current ID of the element.
+ *
+ * @method id
+ * @param {String} id ID of the element
+ * @chainable
+ *
+ * @example
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ * // Assigns a CSS selector ID to
+ * // the canvas element.
+ * cnv.id('mycanvas');
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+/**
+ * @method id
+ * @return {String} the id of the element
+ */
+p5.Element.prototype.id = function(id) {
+ if (typeof id === 'undefined') {
+ return this.elt.id;
+ }
+
+ this.elt.id = id;
+ this.width = this.elt.offsetWidth;
+ this.height = this.elt.offsetHeight;
+ return this;
+};
+
+/**
+ *
+ * Adds given class to the element. If no class argument is passed in, it
+ * instead returns a string containing the current class(es) of the element.
+ *
+ * @method class
+ * @param {String} class class to add
+ * @chainable
+ *
+ * @example
+ *
+ * function setup() {
+ * var cnv = createCanvas(100, 100);
+ * // Assigns a CSS selector class 'small'
+ * // to the canvas element.
+ * cnv.class('small');
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ */
+/**
+ * @method class
+ * @return {String} the class of the element
+ */
+p5.Element.prototype.class = function(c) {
+ if (typeof c === 'undefined') {
+ return this.elt.className;
+ }
+
+ this.elt.className = c;
+ return this;
+};
+
+/**
+ * The .mousePressed() function is called once after every time a
+ * mouse button is pressed over the element. This can be used to
+ * attach element specific event listeners.
+ *
+ * @method mousePressed
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * pressed over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * var cnv;
+ * var d;
+ * var g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mousePressed(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any click anywhere
+ * function mousePressed() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.mousePressed = function(fxn) {
+ adjustListener('mousedown', fxn, this);
+ adjustListener('touchstart', fxn, this);
+ return this;
+};
+
+/**
+ * The .doubleClicked() function is called once after every time a
+ * mouse button is pressed twice over the element. This can be used to
+ * attach element and action specific event listeners.
+ *
+ * @method doubleClicked
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * double clicked over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @return {p5.Element}
+ * @example
+ *
+ * var cnv;
+ * var d;
+ * var g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.doubleClicked(changeGray); // attach listener for
+ * // canvas double click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any double click anywhere
+ * function doubleClicked() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is double clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.doubleClicked = function(fxn) {
+ adjustListener('dblclick', fxn, this);
+ return this;
+};
+
+/**
+ * The .mouseWheel() function is called once after every time a
+ * mouse wheel is scrolled over the element. This can be used to
+ * attach element specific event listeners.
+ *
+ * The function accepts a callback function as argument which will be executed
+ * when the `wheel` event is triggered on the element, the callback function is
+ * passed one argument `event`. The `event.deltaY` property returns negative
+ * values if the mouse wheel is rotated up or away from the user and positive
+ * in the other direction. The `event.deltaX` does the same as `event.deltaY`
+ * except it reads the horizontal wheel scroll of the mouse wheel.
+ *
+ * On OS X with "natural" scrolling enabled, the `event.deltaY` values are
+ * reversed.
+ *
+ * @method mouseWheel
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * scrolled over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * var cnv;
+ * var d;
+ * var g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseWheel(changeSize); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with mousewheel movement
+ * // anywhere on screen
+ * function mouseWheel() {
+ * g = g + 10;
+ * }
+ *
+ * // this function fires with mousewheel movement
+ * // over canvas only
+ * function changeSize(event) {
+ * if (event.deltaY > 0) {
+ * d = d + 10;
+ * } else {
+ * d = d - 10;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.mouseWheel = function(fxn) {
+ adjustListener('wheel', fxn, this);
+ return this;
+};
+
+/**
+ * The .mouseReleased() function is called once after every time a
+ * mouse button is released over the element. This can be used to
+ * attach element specific event listeners.
+ *
+ * @method mouseReleased
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * released over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * var cnv;
+ * var d;
+ * var g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseReleased(changeGray); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // released
+ * function mouseReleased() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // released while on canvas
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.mouseReleased = function(fxn) {
+ adjustListener('mouseup', fxn, this);
+ adjustListener('touchend', fxn, this);
+ return this;
+};
+
+/**
+ * The .mouseClicked() function is called once after a mouse button is
+ * pressed and released over the element. This can be used to
+ * attach element specific event listeners.
+ *
+ * @method mouseClicked
+ * @param {Function|Boolean} fxn function to be fired when mouse is
+ * clicked over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ *
+ * var cnv;
+ * var d;
+ * var g;
+ *
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseClicked(changeGray); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // clicked anywhere
+ * function mouseClicked() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires after the mouse has been
+ * // clicked on canvas
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.mouseClicked = function(fxn) {
+ adjustListener('click', fxn, this);
+ return this;
+};
+
+/**
+ * The .mouseMoved() function is called once every time a
+ * mouse moves over the element. This can be used to attach an
+ * element specific event listener.
+ *
+ * @method mouseMoved
+ * @param {Function|Boolean} fxn function to be fired when a mouse moves
+ * over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * var cnv;
+ * var d = 30;
+ * var g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseMoved(changeSize); // attach listener for
+ * // activity on canvas only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * fill(200);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires when mouse moves anywhere on
+ * // page
+ * function mouseMoved() {
+ * g = g + 5;
+ * if (g > 255) {
+ * g = 0;
+ * }
+ * }
+ *
+ * // this function fires when mouse moves over canvas
+ * function changeSize() {
+ * d = d + 2;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.mouseMoved = function(fxn) {
+ adjustListener('mousemove', fxn, this);
+ adjustListener('touchmove', fxn, this);
+ return this;
+};
+
+/**
+ * The .mouseOver() function is called once after every time a
+ * mouse moves onto the element. This can be used to attach an
+ * element specific event listener.
+ *
+ * @method mouseOver
+ * @param {Function|Boolean} fxn function to be fired when a mouse moves
+ * onto the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * var cnv;
+ * var d;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseOver(changeGray);
+ * d = 10;
+ * }
+ *
+ * function draw() {
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * function changeGray() {
+ * d = d + 10;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.mouseOver = function(fxn) {
+ adjustListener('mouseover', fxn, this);
+ return this;
+};
+
+/**
+ * The .changed() function is called when the value of an
+ * element changes.
+ * This can be used to attach an element specific event listener.
+ *
+ * @method changed
+ * @param {Function|Boolean} fxn function to be fired when the value of
+ * an element changes.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * var sel;
+ *
+ * function setup() {
+ * textAlign(CENTER);
+ * background(200);
+ * sel = createSelect();
+ * sel.position(10, 10);
+ * sel.option('pear');
+ * sel.option('kiwi');
+ * sel.option('grape');
+ * sel.changed(mySelectEvent);
+ * }
+ *
+ * function mySelectEvent() {
+ * var item = sel.value();
+ * background(200);
+ * text("it's a " + item + '!', 50, 50);
+ * }
+ *
+ *
+ * var checkbox;
+ * var cnv;
+ *
+ * function setup() {
+ * checkbox = createCheckbox(' fill');
+ * checkbox.changed(changeFill);
+ * cnv = createCanvas(100, 100);
+ * cnv.position(0, 30);
+ * noFill();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * ellipse(50, 50, 50, 50);
+ * }
+ *
+ * function changeFill() {
+ * if (checkbox.checked()) {
+ * fill(0);
+ * } else {
+ * noFill();
+ * }
+ * }
+ *
+ *
+ * @alt
+ * dropdown: pear, kiwi, grape. When selected text "its a" + selection shown.
+ *
+ */
+p5.Element.prototype.changed = function(fxn) {
+ adjustListener('change', fxn, this);
+ return this;
+};
+
+/**
+ * The .input() function is called when any user input is
+ * detected with an element. The input event is often used
+ * to detect keystrokes in a input element, or changes on a
+ * slider element. This can be used to attach an element specific
+ * event listener.
+ *
+ * @method input
+ * @param {Function|Boolean} fxn function to be fired when any user input is
+ * detected within the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * // Open your console to see the output
+ * function setup() {
+ * var inp = createInput('');
+ * inp.input(myInputEvent);
+ * }
+ *
+ * function myInputEvent() {
+ * console.log('you are typing: ', this.value());
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.input = function(fxn) {
+ adjustListener('input', fxn, this);
+ return this;
+};
+
+/**
+ * The .mouseOut() function is called once after every time a
+ * mouse moves off the element. This can be used to attach an
+ * element specific event listener.
+ *
+ * @method mouseOut
+ * @param {Function|Boolean} fxn function to be fired when a mouse
+ * moves off of an element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * var cnv;
+ * var d;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.mouseOut(changeGray);
+ * d = 10;
+ * }
+ *
+ * function draw() {
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * function changeGray() {
+ * d = d + 10;
+ * if (d > 100) {
+ * d = 0;
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.mouseOut = function(fxn) {
+ adjustListener('mouseout', fxn, this);
+ return this;
+};
+
+/**
+ * The .touchStarted() function is called once after every time a touch is
+ * registered. This can be used to attach element specific event listeners.
+ *
+ * @method touchStarted
+ * @param {Function|Boolean} fxn function to be fired when a touch
+ * starts over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * var cnv;
+ * var d;
+ * var g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchStarted(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any touch anywhere
+ * function touchStarted() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.touchStarted = function(fxn) {
+ adjustListener('touchstart', fxn, this);
+ adjustListener('mousedown', fxn, this);
+ return this;
+};
+
+/**
+ * The .touchMoved() function is called once after every time a touch move is
+ * registered. This can be used to attach element specific event listeners.
+ *
+ * @method touchMoved
+ * @param {Function|Boolean} fxn function to be fired when a touch moves over
+ * the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * var cnv;
+ * var g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchMoved(changeGray); // attach listener for
+ * // canvas click only
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.touchMoved = function(fxn) {
+ adjustListener('touchmove', fxn, this);
+ adjustListener('mousemove', fxn, this);
+ return this;
+};
+
+/**
+ * The .touchEnded() function is called once after every time a touch is
+ * registered. This can be used to attach element specific event listeners.
+ *
+ * @method touchEnded
+ * @param {Function|Boolean} fxn function to be fired when a touch ends
+ * over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * var cnv;
+ * var d;
+ * var g;
+ * function setup() {
+ * cnv = createCanvas(100, 100);
+ * cnv.touchEnded(changeGray); // attach listener for
+ * // canvas click only
+ * d = 10;
+ * g = 100;
+ * }
+ *
+ * function draw() {
+ * background(g);
+ * ellipse(width / 2, height / 2, d, d);
+ * }
+ *
+ * // this function fires with any touch anywhere
+ * function touchEnded() {
+ * d = d + 10;
+ * }
+ *
+ * // this function fires only when cnv is clicked
+ * function changeGray() {
+ * g = random(0, 255);
+ * }
+ *
+ *
+ *
+ * @alt
+ * no display.
+ *
+ */
+p5.Element.prototype.touchEnded = function(fxn) {
+ adjustListener('touchend', fxn, this);
+ adjustListener('mouseup', fxn, this);
+ return this;
+};
+
+/**
+ * The .dragOver() function is called once after every time a
+ * file is dragged over the element. This can be used to attach an
+ * element specific event listener.
+ *
+ * @method dragOver
+ * @param {Function|Boolean} fxn function to be fired when a file is
+ * dragged over the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * // To test this sketch, simply drag a
+ * // file over the canvas
+ * function setup() {
+ * var c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('Drag file', width / 2, height / 2);
+ * c.dragOver(dragOverCallback);
+ * }
+ *
+ * // This function will be called whenever
+ * // a file is dragged over the canvas
+ * function dragOverCallback() {
+ * background(240);
+ * text('Dragged over', width / 2, height / 2);
+ * }
+ *
+ * @alt
+ * nothing displayed
+ */
+p5.Element.prototype.dragOver = function(fxn) {
+ adjustListener('dragover', fxn, this);
+ return this;
+};
+
+/**
+ * The .dragLeave() function is called once after every time a
+ * dragged file leaves the element area. This can be used to attach an
+ * element specific event listener.
+ *
+ * @method dragLeave
+ * @param {Function|Boolean} fxn function to be fired when a file is
+ * dragged off the element.
+ * if `false` is passed instead, the previously
+ * firing function will no longer fire.
+ * @chainable
+ * @example
+ *
+ * // To test this sketch, simply drag a file
+ * // over and then out of the canvas area
+ * function setup() {
+ * var c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('Drag file', width / 2, height / 2);
+ * c.dragLeave(dragLeaveCallback);
+ * }
+ *
+ * // This function will be called whenever
+ * // a file is dragged out of the canvas
+ * function dragLeaveCallback() {
+ * background(240);
+ * text('Dragged off', width / 2, height / 2);
+ * }
+ *
+ * @alt
+ * nothing displayed
+ */
+p5.Element.prototype.dragLeave = function(fxn) {
+ adjustListener('dragleave', fxn, this);
+ return this;
+};
+
+/**
+ * The .drop() function is called for each file dropped on the element.
+ * It requires a callback that is passed a p5.File object. You can
+ * optionally pass two callbacks, the first one (required) is triggered
+ * for each file dropped when the file is loaded. The second (optional)
+ * is triggered just once when a file (or files) are dropped.
+ *
+ * @method drop
+ * @param {Function} callback callback triggered when files are dropped.
+ * @param {Function} [fxn] callback to receive loaded file.
+ * @chainable
+ * @example
+ *
+ * function setup() {
+ * var c = createCanvas(100, 100);
+ * background(200);
+ * textAlign(CENTER);
+ * text('drop image', width / 2, height / 2);
+ * c.drop(gotFile);
+ * }
+ *
+ * function gotFile(file) {
+ * var img = createImg(file.data).hide();
+ * // Draw the image onto the canvas
+ * image(img, 0, 0, width, height);
+ * }
+ *
+ *
+ * @alt
+ * Canvas turns into whatever image is dragged/dropped onto it.
+ *
+ */
+p5.Element.prototype.drop = function(callback, fxn) {
+ // Make a file loader callback and trigger user's callback
+ function makeLoader(theFile) {
+ // Making a p5.File object
+ var p5file = new p5.File(theFile);
+ return function(e) {
+ p5file.data = e.target.result;
+ callback(p5file);
+ };
+ }
+
+ // Is the file stuff supported?
+ if (window.File && window.FileReader && window.FileList && window.Blob) {
+ // If you want to be able to drop you've got to turn off
+ // a lot of default behavior
+ attachListener(
+ 'dragover',
+ function(evt) {
+ evt.stopPropagation();
+ evt.preventDefault();
+ },
+ this
+ );
+
+ // If this is a drag area we need to turn off the default behavior
+ attachListener(
+ 'dragleave',
+ function(evt) {
+ evt.stopPropagation();
+ evt.preventDefault();
+ },
+ this
+ );
+
+ // If just one argument it's the callback for the files
+ if (typeof fxn !== 'undefined') {
+ attachListener('drop', fxn, this);
+ }
+
+ // Deal with the files
+ attachListener(
+ 'drop',
+ function(evt) {
+ evt.stopPropagation();
+ evt.preventDefault();
+
+ // A FileList
+ var files = evt.dataTransfer.files;
+
+ // Load each one and trigger the callback
+ for (var i = 0; i < files.length; i++) {
+ var f = files[i];
+ var reader = new FileReader();
+ reader.onload = makeLoader(f);
+
+ // Text or data?
+ // This should likely be improved
+ if (f.type.indexOf('text') > -1) {
+ reader.readAsText(f);
+ } else {
+ reader.readAsDataURL(f);
+ }
+ }
+ },
+ this
+ );
+ } else {
+ console.log('The File APIs are not fully supported in this browser.');
+ }
+
+ return this;
+};
+
+// General handler for event attaching and detaching
+function adjustListener(ev, fxn, ctx) {
+ if (fxn === false) {
+ detachListener(ev, ctx);
+ } else {
+ attachListener(ev, fxn, ctx);
+ }
+ return this;
+}
+
+function attachListener(ev, fxn, ctx) {
+ // LM removing, not sure why we had this?
+ // var _this = ctx;
+ // var f = function (e) { fxn(e, _this); };
+
+ // detach the old listener if there was one
+ if (ctx._events[ev]) {
+ detachListener(ev, ctx);
+ }
+ var f = fxn.bind(ctx);
+ ctx.elt.addEventListener(ev, f, false);
+ ctx._events[ev] = f;
+}
+
+function detachListener(ev, ctx) {
+ var f = ctx._events[ev];
+ ctx.elt.removeEventListener(ev, f, false);
+ ctx._events[ev] = null;
+}
+
+/**
+ * Helper fxn for sharing pixel methods
+ *
+ */
+p5.Element.prototype._setProperty = function(prop, value) {
+ this[prop] = value;
+};
+
+module.exports = p5.Element;
+
+},{"./core":22}],28:[function(_dereq_,module,exports){
+/**
+ * @module Rendering
+ * @submodule Rendering
+ * @for p5
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+var constants = _dereq_('./constants');
+
+/**
+ * Thin wrapper around a renderer, to be used for creating a
+ * graphics buffer object. Use this class if you need
+ * to draw into an off-screen graphics buffer. The two parameters define the
+ * width and height in pixels. The fields and methods for this class are
+ * extensive, but mirror the normal drawing API for p5.
+ *
+ * @class p5.Graphics
+ * @extends p5.Element
+ * @param {Number} w width
+ * @param {Number} h height
+ * @param {Constant} renderer the renderer to use, either P2D or WEBGL
+ * @param {p5} [pInst] pointer to p5 instance
+ */
+p5.Graphics = function(w, h, renderer, pInst) {
+ var r = renderer || constants.P2D;
+
+ this.canvas = document.createElement('canvas');
+ var node = pInst._userNode || document.body;
+ node.appendChild(this.canvas);
+
+ p5.Element.call(this, this.canvas, pInst, false);
+
+ // bind methods and props of p5 to the new object
+ for (var p in p5.prototype) {
+ if (!this[p]) {
+ if (typeof p5.prototype[p] === 'function') {
+ this[p] = p5.prototype[p].bind(this);
+ } else {
+ this[p] = p5.prototype[p];
+ }
+ }
+ }
+
+ p5.prototype._initializeInstanceVariables.apply(this);
+ this.width = w;
+ this.height = h;
+ this._pixelDensity = pInst._pixelDensity;
+
+ if (r === constants.WEBGL) {
+ this._renderer = new p5.RendererGL(this.canvas, this, false);
+ } else {
+ this._renderer = new p5.Renderer2D(this.canvas, this, false);
+ }
+ pInst._elements.push(this);
+
+ this._renderer.resize(w, h);
+ this._renderer._applyDefaults();
+ return this;
+};
+
+p5.Graphics.prototype = Object.create(p5.Element.prototype);
+
+/**
+ * Removes a Graphics object from the page and frees any resources
+ * associated with it.
+ *
+ * @method remove
+ *
+ * @example
+ *
+ * var bg;
+ * function setup() {
+ * bg = createCanvas(100, 100);
+ * bg.background(0);
+ * image(bg, 0, 0);
+ * bg.remove();
+ * }
+ *
+ *
+ *
+ * var bg;
+ * function setup() {
+ * pixelDensity(1);
+ * createCanvas(100, 100);
+ * stroke(255);
+ * fill(0);
+ *
+ * // create and draw the background image
+ * bg = createGraphics(100, 100);
+ * bg.background(200);
+ * bg.ellipse(50, 50, 80, 80);
+ * }
+ * function draw() {
+ * var t = millis() / 1000;
+ * // draw the background
+ * if (bg) {
+ * image(bg, frameCount % 100, 0);
+ * image(bg, frameCount % 100 - 100, 0);
+ * }
+ * // draw the foreground
+ * var p = p5.Vector.fromAngle(t, 35).add(50, 50);
+ * ellipse(p.x, p.y, 30);
+ * }
+ * function mouseClicked() {
+ * // remove the background
+ * if (bg) {
+ * bg.remove();
+ * bg = null;
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no image
+ * a multi-colored circle moving back and forth over a scrolling background.
+ *
+ */
+p5.Graphics.prototype.remove = function() {
+ if (this.elt.parentNode) {
+ this.elt.parentNode.removeChild(this.elt);
+ }
+ var idx = this._pInst._elements.indexOf(this);
+ if (idx !== -1) {
+ this._pInst._elements.splice(idx, 1);
+ }
+ for (var elt_ev in this._events) {
+ this.elt.removeEventListener(elt_ev, this._events[elt_ev]);
+ }
+};
+
+module.exports = p5.Graphics;
+
+},{"./constants":21,"./core":22}],29:[function(_dereq_,module,exports){
+/**
+ * @module Rendering
+ * @submodule Rendering
+ * @for p5
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+var constants = _dereq_('../core/constants');
+
+/**
+ * Main graphics and rendering context, as well as the base API
+ * implementation for p5.js "core". To be used as the superclass for
+ * Renderer2D and Renderer3D classes, respecitvely.
+ *
+ * @class p5.Renderer
+ * @constructor
+ * @extends p5.Element
+ * @param {String} elt DOM node that is wrapped
+ * @param {p5} [pInst] pointer to p5 instance
+ * @param {Boolean} [isMainCanvas] whether we're using it as main canvas
+ */
+p5.Renderer = function(elt, pInst, isMainCanvas) {
+ p5.Element.call(this, elt, pInst);
+ this.canvas = elt;
+ this._pInst = pInst;
+ if (isMainCanvas) {
+ this._isMainCanvas = true;
+ // for pixel method sharing with pimage
+ this._pInst._setProperty('_curElement', this);
+ this._pInst._setProperty('canvas', this.canvas);
+ this._pInst._setProperty('width', this.width);
+ this._pInst._setProperty('height', this.height);
+ } else {
+ // hide if offscreen buffer by default
+ this.canvas.style.display = 'none';
+ this._styles = []; // non-main elt styles stored in p5.Renderer
+ }
+
+ this._textSize = 12;
+ this._textLeading = 15;
+ this._textFont = 'sans-serif';
+ this._textStyle = constants.NORMAL;
+ this._textAscent = null;
+ this._textDescent = null;
+
+ this._rectMode = constants.CORNER;
+ this._ellipseMode = constants.CENTER;
+ this._curveTightness = 0;
+ this._imageMode = constants.CORNER;
+
+ this._tint = null;
+ this._doStroke = true;
+ this._doFill = true;
+ this._strokeSet = false;
+ this._fillSet = false;
+};
+
+p5.Renderer.prototype = Object.create(p5.Element.prototype);
+
+// the renderer should return a 'style' object that it wishes to
+// store on the push stack.
+p5.Renderer.prototype.push = function() {
+ return {
+ properties: {
+ _doStroke: this._doStroke,
+ _strokeSet: this._strokeSet,
+ _doFill: this._doFill,
+ _fillSet: this._fillSet,
+ _tint: this._tint,
+ _imageMode: this._imageMode,
+ _rectMode: this._rectMode,
+ _ellipseMode: this._ellipseMode,
+ _textFont: this._textFont,
+ _textLeading: this._textLeading,
+ _textSize: this._textSize,
+ _textStyle: this._textStyle
+ }
+ };
+};
+
+// this is implementation of Object.assign() which is unavailable in
+// IE11 and (non-Chrome) Android browsers.
+// The assign() method is used to copy the values of all enumerable
+// own properties from one or more source objects to a target object.
+// It will return the target object.
+function assign(to, firstSource) {
+ for (var i = 1; i < arguments.length; i++) {
+ var nextSource = arguments[i];
+ if (nextSource === undefined || nextSource === null) {
+ continue;
+ }
+
+ for (var nextKey in nextSource)
+ if (nextSource.hasOwnProperty(nextKey)) {
+ to[nextKey] = nextSource[nextKey];
+ }
+ }
+ return to;
+}
+
+// a pop() operation is in progress
+// the renderer is passed the 'style' object that it returned
+// from its push() method.
+p5.Renderer.prototype.pop = function(style) {
+ if (style.properties) {
+ // copy the style properties back into the renderer
+ assign(this, style.properties);
+ }
+};
+
+/**
+ * Resize our canvas element.
+ */
+p5.Renderer.prototype.resize = function(w, h) {
+ this.width = w;
+ this.height = h;
+ this.elt.width = w * this._pInst._pixelDensity;
+ this.elt.height = h * this._pInst._pixelDensity;
+ this.elt.style.width = w + 'px';
+ this.elt.style.height = h + 'px';
+ if (this._isMainCanvas) {
+ this._pInst._setProperty('width', this.width);
+ this._pInst._setProperty('height', this.height);
+ }
+};
+
+p5.Renderer.prototype.textLeading = function(l) {
+ if (typeof l === 'number') {
+ this._setProperty('_textLeading', l);
+ return this;
+ }
+
+ return this._textLeading;
+};
+
+p5.Renderer.prototype.textSize = function(s) {
+ if (typeof s === 'number') {
+ this._setProperty('_textSize', s);
+ this._setProperty('_textLeading', s * constants._DEFAULT_LEADMULT);
+ return this._applyTextProperties();
+ }
+
+ return this._textSize;
+};
+
+p5.Renderer.prototype.textStyle = function(s) {
+ if (s) {
+ if (
+ s === constants.NORMAL ||
+ s === constants.ITALIC ||
+ s === constants.BOLD
+ ) {
+ this._setProperty('_textStyle', s);
+ }
+
+ return this._applyTextProperties();
+ }
+
+ return this._textStyle;
+};
+
+p5.Renderer.prototype.textAscent = function() {
+ if (this._textAscent === null) {
+ this._updateTextMetrics();
+ }
+ return this._textAscent;
+};
+
+p5.Renderer.prototype.textDescent = function() {
+ if (this._textDescent === null) {
+ this._updateTextMetrics();
+ }
+ return this._textDescent;
+};
+
+p5.Renderer.prototype._applyDefaults = function() {
+ return this;
+};
+
+/**
+ * Helper fxn to check font type (system or otf)
+ */
+p5.Renderer.prototype._isOpenType = function(f) {
+ f = f || this._textFont;
+ return typeof f === 'object' && f.font && f.font.supported;
+};
+
+p5.Renderer.prototype._updateTextMetrics = function() {
+ if (this._isOpenType()) {
+ this._setProperty('_textAscent', this._textFont._textAscent());
+ this._setProperty('_textDescent', this._textFont._textDescent());
+ return this;
+ }
+
+ // Adapted from http://stackoverflow.com/a/25355178
+ var text = document.createElement('span');
+ text.style.fontFamily = this._textFont;
+ text.style.fontSize = this._textSize + 'px';
+ text.innerHTML = 'ABCjgq|';
+
+ var block = document.createElement('div');
+ block.style.display = 'inline-block';
+ block.style.width = '1px';
+ block.style.height = '0px';
+
+ var container = document.createElement('div');
+ container.appendChild(text);
+ container.appendChild(block);
+
+ container.style.height = '0px';
+ container.style.overflow = 'hidden';
+ document.body.appendChild(container);
+
+ block.style.verticalAlign = 'baseline';
+ var blockOffset = calculateOffset(block);
+ var textOffset = calculateOffset(text);
+ var ascent = blockOffset[1] - textOffset[1];
+
+ block.style.verticalAlign = 'bottom';
+ blockOffset = calculateOffset(block);
+ textOffset = calculateOffset(text);
+ var height = blockOffset[1] - textOffset[1];
+ var descent = height - ascent;
+
+ document.body.removeChild(container);
+
+ this._setProperty('_textAscent', ascent);
+ this._setProperty('_textDescent', descent);
+
+ return this;
+};
+
+/**
+ * Helper fxn to measure ascent and descent.
+ * Adapted from http://stackoverflow.com/a/25355178
+ */
+function calculateOffset(object) {
+ var currentLeft = 0,
+ currentTop = 0;
+ if (object.offsetParent) {
+ do {
+ currentLeft += object.offsetLeft;
+ currentTop += object.offsetTop;
+ } while ((object = object.offsetParent));
+ } else {
+ currentLeft += object.offsetLeft;
+ currentTop += object.offsetTop;
+ }
+ return [currentLeft, currentTop];
+}
+
+module.exports = p5.Renderer;
+
+},{"../core/constants":21,"./core":22}],30:[function(_dereq_,module,exports){
+'use strict';
+
+var p5 = _dereq_('./core');
+var canvas = _dereq_('./canvas');
+var constants = _dereq_('./constants');
+var filters = _dereq_('../image/filters');
+
+_dereq_('./p5.Renderer');
+
+/**
+ * p5.Renderer2D
+ * The 2D graphics canvas renderer class.
+ * extends p5.Renderer
+ */
+var styleEmpty = 'rgba(0,0,0,0)';
+// var alphaThreshold = 0.00125; // minimum visible
+
+p5.Renderer2D = function(elt, pInst, isMainCanvas) {
+ p5.Renderer.call(this, elt, pInst, isMainCanvas);
+ this.drawingContext = this.canvas.getContext('2d');
+ this._pInst._setProperty('drawingContext', this.drawingContext);
+ return this;
+};
+
+p5.Renderer2D.prototype = Object.create(p5.Renderer.prototype);
+
+p5.Renderer2D.prototype._applyDefaults = function() {
+ this._cachedFillStyle = this._cachedStrokeStyle = undefined;
+ this._setFill(constants._DEFAULT_FILL);
+ this._setStroke(constants._DEFAULT_STROKE);
+ this.drawingContext.lineCap = constants.ROUND;
+ this.drawingContext.font = 'normal 12px sans-serif';
+};
+
+p5.Renderer2D.prototype.resize = function(w, h) {
+ p5.Renderer.prototype.resize.call(this, w, h);
+ this.drawingContext.scale(
+ this._pInst._pixelDensity,
+ this._pInst._pixelDensity
+ );
+};
+
+//////////////////////////////////////////////
+// COLOR | Setting
+//////////////////////////////////////////////
+
+p5.Renderer2D.prototype.background = function() {
+ this.drawingContext.save();
+ this.drawingContext.setTransform(1, 0, 0, 1, 0, 0);
+ this.drawingContext.scale(
+ this._pInst._pixelDensity,
+ this._pInst._pixelDensity
+ );
+
+ if (arguments[0] instanceof p5.Image) {
+ this._pInst.image(arguments[0], 0, 0, this.width, this.height);
+ } else {
+ var curFill = this._getFill();
+ // create background rect
+ var color = this._pInst.color.apply(this._pInst, arguments);
+ var newFill = color.toString();
+ this._setFill(newFill);
+ this.drawingContext.fillRect(0, 0, this.width, this.height);
+ // reset fill
+ this._setFill(curFill);
+ }
+ this.drawingContext.restore();
+};
+
+p5.Renderer2D.prototype.clear = function() {
+ this.drawingContext.save();
+ this.drawingContext.setTransform(1, 0, 0, 1, 0, 0);
+ this.drawingContext.clearRect(0, 0, this.width, this.height);
+ this.drawingContext.restore();
+};
+
+p5.Renderer2D.prototype.fill = function() {
+ var color = this._pInst.color.apply(this._pInst, arguments);
+ this._setFill(color.toString());
+};
+
+p5.Renderer2D.prototype.stroke = function() {
+ var color = this._pInst.color.apply(this._pInst, arguments);
+ this._setStroke(color.toString());
+};
+
+//////////////////////////////////////////////
+// IMAGE | Loading & Displaying
+//////////////////////////////////////////////
+
+p5.Renderer2D.prototype.image = function(
+ img,
+ sx,
+ sy,
+ sWidth,
+ sHeight,
+ dx,
+ dy,
+ dWidth,
+ dHeight
+) {
+ var cnv;
+ try {
+ if (this._tint) {
+ if (p5.MediaElement && img instanceof p5.MediaElement) {
+ img.loadPixels();
+ }
+ if (img.canvas) {
+ cnv = this._getTintedImageCanvas(img);
+ }
+ }
+ if (!cnv) {
+ cnv = img.canvas || img.elt;
+ }
+ this.drawingContext.drawImage(
+ cnv,
+ sx,
+ sy,
+ sWidth,
+ sHeight,
+ dx,
+ dy,
+ dWidth,
+ dHeight
+ );
+ } catch (e) {
+ if (e.name !== 'NS_ERROR_NOT_AVAILABLE') {
+ throw e;
+ }
+ }
+};
+
+p5.Renderer2D.prototype._getTintedImageCanvas = function(img) {
+ if (!img.canvas) {
+ return img;
+ }
+ var pixels = filters._toPixels(img.canvas);
+ var tmpCanvas = document.createElement('canvas');
+ tmpCanvas.width = img.canvas.width;
+ tmpCanvas.height = img.canvas.height;
+ var tmpCtx = tmpCanvas.getContext('2d');
+ var id = tmpCtx.createImageData(img.canvas.width, img.canvas.height);
+ var newPixels = id.data;
+ for (var i = 0; i < pixels.length; i += 4) {
+ var r = pixels[i];
+ var g = pixels[i + 1];
+ var b = pixels[i + 2];
+ var a = pixels[i + 3];
+ newPixels[i] = r * this._tint[0] / 255;
+ newPixels[i + 1] = g * this._tint[1] / 255;
+ newPixels[i + 2] = b * this._tint[2] / 255;
+ newPixels[i + 3] = a * this._tint[3] / 255;
+ }
+ tmpCtx.putImageData(id, 0, 0);
+ return tmpCanvas;
+};
+
+//////////////////////////////////////////////
+// IMAGE | Pixels
+//////////////////////////////////////////////
+
+p5.Renderer2D.prototype.blendMode = function(mode) {
+ this.drawingContext.globalCompositeOperation = mode;
+};
+p5.Renderer2D.prototype.blend = function() {
+ var currBlend = this.drawingContext.globalCompositeOperation;
+ var blendMode = arguments[arguments.length - 1];
+
+ var copyArgs = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
+
+ this.drawingContext.globalCompositeOperation = blendMode;
+ if (this._pInst) {
+ this._pInst.copy.apply(this._pInst, copyArgs);
+ } else {
+ this.copy.apply(this, copyArgs);
+ }
+ this.drawingContext.globalCompositeOperation = currBlend;
+};
+
+p5.Renderer2D.prototype.copy = function() {
+ var srcImage, sx, sy, sw, sh, dx, dy, dw, dh;
+ if (arguments.length === 9) {
+ srcImage = arguments[0];
+ sx = arguments[1];
+ sy = arguments[2];
+ sw = arguments[3];
+ sh = arguments[4];
+ dx = arguments[5];
+ dy = arguments[6];
+ dw = arguments[7];
+ dh = arguments[8];
+ } else if (arguments.length === 8) {
+ srcImage = this._pInst;
+ sx = arguments[0];
+ sy = arguments[1];
+ sw = arguments[2];
+ sh = arguments[3];
+ dx = arguments[4];
+ dy = arguments[5];
+ dw = arguments[6];
+ dh = arguments[7];
+ } else {
+ throw new Error('Signature not supported');
+ }
+ p5.Renderer2D._copyHelper(this, srcImage, sx, sy, sw, sh, dx, dy, dw, dh);
+};
+
+p5.Renderer2D._copyHelper = function(
+ dstImage,
+ srcImage,
+ sx,
+ sy,
+ sw,
+ sh,
+ dx,
+ dy,
+ dw,
+ dh
+) {
+ srcImage.loadPixels();
+ var s = srcImage.canvas.width / srcImage.width;
+ dstImage.drawingContext.drawImage(
+ srcImage.canvas,
+ s * sx,
+ s * sy,
+ s * sw,
+ s * sh,
+ dx,
+ dy,
+ dw,
+ dh
+ );
+};
+
+p5.Renderer2D.prototype.get = function(x, y, w, h) {
+ if (
+ x === undefined &&
+ y === undefined &&
+ w === undefined &&
+ h === undefined
+ ) {
+ x = 0;
+ y = 0;
+ w = this.width;
+ h = this.height;
+ } else if (w === undefined && h === undefined) {
+ w = 1;
+ h = 1;
+ }
+
+ // if the section does not overlap the canvas
+ if (x + w < 0 || y + h < 0 || x > this.width || y > this.height) {
+ return [0, 0, 0, 255];
+ }
+
+ var ctx = this._pInst || this;
+ ctx.loadPixels();
+
+ var pd = ctx._pixelDensity;
+
+ // round down to get integer numbers
+ x = Math.floor(x);
+ y = Math.floor(y);
+ w = Math.floor(w);
+ h = Math.floor(h);
+
+ var sx = x * pd;
+ var sy = y * pd;
+ if (w === 1 && h === 1 && !(this instanceof p5.RendererGL)) {
+ var imageData = this.drawingContext.getImageData(sx, sy, 1, 1).data;
+ //imageData = [0,0,0,0];
+ return [imageData[0], imageData[1], imageData[2], imageData[3]];
+ } else {
+ //auto constrain the width and height to
+ //dimensions of the source image
+ var dw = Math.min(w, ctx.width);
+ var dh = Math.min(h, ctx.height);
+ var sw = dw * pd;
+ var sh = dh * pd;
+
+ var region = new p5.Image(dw, dh);
+ region.canvas
+ .getContext('2d')
+ .drawImage(this.canvas, sx, sy, sw, sh, 0, 0, dw, dh);
+
+ return region;
+ }
+};
+
+p5.Renderer2D.prototype.loadPixels = function() {
+ var ctx = this._pInst || this; // if called by p5.Image
+ var pd = ctx._pixelDensity;
+ var w = this.width * pd;
+ var h = this.height * pd;
+ var imageData = this.drawingContext.getImageData(0, 0, w, h);
+ // @todo this should actually set pixels per object, so diff buffers can
+ // have diff pixel arrays.
+ ctx._setProperty('imageData', imageData);
+ ctx._setProperty('pixels', imageData.data);
+};
+
+p5.Renderer2D.prototype.set = function(x, y, imgOrCol) {
+ // round down to get integer numbers
+ x = Math.floor(x);
+ y = Math.floor(y);
+ var ctx = this._pInst || this;
+ if (imgOrCol instanceof p5.Image) {
+ this.drawingContext.save();
+ this.drawingContext.setTransform(1, 0, 0, 1, 0, 0);
+ this.drawingContext.scale(ctx._pixelDensity, ctx._pixelDensity);
+ this.drawingContext.drawImage(imgOrCol.canvas, x, y);
+ this.loadPixels.call(ctx);
+ this.drawingContext.restore();
+ } else {
+ var r = 0,
+ g = 0,
+ b = 0,
+ a = 0;
+ var idx =
+ 4 *
+ (y * ctx._pixelDensity * (this.width * ctx._pixelDensity) +
+ x * ctx._pixelDensity);
+ if (!ctx.imageData) {
+ ctx.loadPixels.call(ctx);
+ }
+ if (typeof imgOrCol === 'number') {
+ if (idx < ctx.pixels.length) {
+ r = imgOrCol;
+ g = imgOrCol;
+ b = imgOrCol;
+ a = 255;
+ //this.updatePixels.call(this);
+ }
+ } else if (imgOrCol instanceof Array) {
+ if (imgOrCol.length < 4) {
+ throw new Error('pixel array must be of the form [R, G, B, A]');
+ }
+ if (idx < ctx.pixels.length) {
+ r = imgOrCol[0];
+ g = imgOrCol[1];
+ b = imgOrCol[2];
+ a = imgOrCol[3];
+ //this.updatePixels.call(this);
+ }
+ } else if (imgOrCol instanceof p5.Color) {
+ if (idx < ctx.pixels.length) {
+ r = imgOrCol.levels[0];
+ g = imgOrCol.levels[1];
+ b = imgOrCol.levels[2];
+ a = imgOrCol.levels[3];
+ //this.updatePixels.call(this);
+ }
+ }
+ // loop over pixelDensity * pixelDensity
+ for (var i = 0; i < ctx._pixelDensity; i++) {
+ for (var j = 0; j < ctx._pixelDensity; j++) {
+ // loop over
+ idx =
+ 4 *
+ ((y * ctx._pixelDensity + j) * this.width * ctx._pixelDensity +
+ (x * ctx._pixelDensity + i));
+ ctx.pixels[idx] = r;
+ ctx.pixels[idx + 1] = g;
+ ctx.pixels[idx + 2] = b;
+ ctx.pixels[idx + 3] = a;
+ }
+ }
+ }
+};
+
+p5.Renderer2D.prototype.updatePixels = function(x, y, w, h) {
+ var ctx = this._pInst || this;
+ var pd = ctx._pixelDensity;
+ if (
+ x === undefined &&
+ y === undefined &&
+ w === undefined &&
+ h === undefined
+ ) {
+ x = 0;
+ y = 0;
+ w = this.width;
+ h = this.height;
+ }
+ w *= pd;
+ h *= pd;
+
+ this.drawingContext.putImageData(ctx.imageData, x, y, 0, 0, w, h);
+};
+
+//////////////////////////////////////////////
+// SHAPE | 2D Primitives
+//////////////////////////////////////////////
+
+/**
+ * Generate a cubic Bezier representing an arc on the unit circle of total
+ * angle `size` radians, beginning `start` radians above the x-axis. Up to
+ * four of these curves are combined to make a full arc.
+ *
+ * See www.joecridge.me/bezier.pdf for an explanation of the method.
+ */
+p5.Renderer2D.prototype._acuteArcToBezier = function _acuteArcToBezier(
+ start,
+ size
+) {
+ // Evauate constants.
+ var alpha = size / 2.0,
+ cos_alpha = Math.cos(alpha),
+ sin_alpha = Math.sin(alpha),
+ cot_alpha = 1.0 / Math.tan(alpha),
+ phi = start + alpha, // This is how far the arc needs to be rotated.
+ cos_phi = Math.cos(phi),
+ sin_phi = Math.sin(phi),
+ lambda = (4.0 - cos_alpha) / 3.0,
+ mu = sin_alpha + (cos_alpha - lambda) * cot_alpha;
+
+ // Return rotated waypoints.
+ return {
+ ax: Math.cos(start),
+ ay: Math.sin(start),
+ bx: lambda * cos_phi + mu * sin_phi,
+ by: lambda * sin_phi - mu * cos_phi,
+ cx: lambda * cos_phi - mu * sin_phi,
+ cy: lambda * sin_phi + mu * cos_phi,
+ dx: Math.cos(start + size),
+ dy: Math.sin(start + size)
+ };
+};
+
+p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) {
+ var ctx = this.drawingContext;
+ var vals = canvas.arcModeAdjust(x, y, w, h, this._ellipseMode);
+ var rx = vals.w / 2.0;
+ var ry = vals.h / 2.0;
+ var epsilon = 0.00001; // Smallest visible angle on displays up to 4K.
+ var arcToDraw = 0;
+ var curves = [];
+
+ // Create curves
+ while (stop - start > epsilon) {
+ arcToDraw = Math.min(stop - start, constants.HALF_PI);
+ curves.push(this._acuteArcToBezier(start, arcToDraw));
+ start += arcToDraw;
+ }
+
+ // Fill curves
+ if (this._doFill) {
+ ctx.beginPath();
+ curves.forEach(function(curve, index) {
+ if (index === 0) {
+ ctx.moveTo(vals.x + curve.ax * rx, vals.y + curve.ay * ry);
+ }
+ // prettier-ignore
+ ctx.bezierCurveTo(vals.x + curve.bx * rx, vals.y + curve.by * ry,
+ vals.x + curve.cx * rx, vals.y + curve.cy * ry,
+ vals.x + curve.dx * rx, vals.y + curve.dy * ry);
+ });
+ if (mode === constants.PIE || mode == null) {
+ ctx.lineTo(vals.x, vals.y);
+ }
+ ctx.closePath();
+ ctx.fill();
+ }
+
+ // Stroke curves
+ if (this._doStroke) {
+ ctx.beginPath();
+ curves.forEach(function(curve, index) {
+ if (index === 0) {
+ ctx.moveTo(vals.x + curve.ax * rx, vals.y + curve.ay * ry);
+ }
+ // prettier-ignore
+ ctx.bezierCurveTo(vals.x + curve.bx * rx, vals.y + curve.by * ry,
+ vals.x + curve.cx * rx, vals.y + curve.cy * ry,
+ vals.x + curve.dx * rx, vals.y + curve.dy * ry);
+ });
+ if (mode === constants.PIE) {
+ ctx.lineTo(vals.x, vals.y);
+ ctx.closePath();
+ } else if (mode === constants.CHORD) {
+ ctx.closePath();
+ }
+ ctx.stroke();
+ }
+ return this;
+};
+
+p5.Renderer2D.prototype.ellipse = function(args) {
+ var ctx = this.drawingContext;
+ var doFill = this._doFill,
+ doStroke = this._doStroke;
+ var x = args[0],
+ y = args[1],
+ w = args[2],
+ h = args[3];
+ if (doFill && !doStroke) {
+ if (this._getFill() === styleEmpty) {
+ return this;
+ }
+ } else if (!doFill && doStroke) {
+ if (this._getStroke() === styleEmpty) {
+ return this;
+ }
+ }
+ var kappa = 0.5522847498,
+ ox = w / 2 * kappa, // control point offset horizontal
+ oy = h / 2 * kappa, // control point offset vertical
+ xe = x + w, // x-end
+ ye = y + h, // y-end
+ xm = x + w / 2, // x-middle
+ ym = y + h / 2; // y-middle
+ ctx.beginPath();
+ ctx.moveTo(x, ym);
+ ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
+ ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
+ ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
+ ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
+ ctx.closePath();
+ if (doFill) {
+ ctx.fill();
+ }
+ if (doStroke) {
+ ctx.stroke();
+ }
+};
+
+p5.Renderer2D.prototype.line = function(x1, y1, x2, y2) {
+ var ctx = this.drawingContext;
+ if (!this._doStroke) {
+ return this;
+ } else if (this._getStroke() === styleEmpty) {
+ return this;
+ }
+ // Translate the line by (0.5, 0.5) to draw it crisp
+ if (ctx.lineWidth % 2 === 1) {
+ ctx.translate(0.5, 0.5);
+ }
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.stroke();
+ if (ctx.lineWidth % 2 === 1) {
+ ctx.translate(-0.5, -0.5);
+ }
+ return this;
+};
+
+p5.Renderer2D.prototype.point = function(x, y) {
+ var ctx = this.drawingContext;
+ if (!this._doStroke) {
+ return this;
+ } else if (this._getStroke() === styleEmpty) {
+ return this;
+ }
+ var s = this._getStroke();
+ var f = this._getFill();
+ x = Math.round(x);
+ y = Math.round(y);
+ // swapping fill color to stroke and back after for correct point rendering
+ this._setFill(s);
+ if (ctx.lineWidth > 1) {
+ ctx.beginPath();
+ ctx.arc(x, y, ctx.lineWidth / 2, 0, constants.TWO_PI, false);
+ ctx.fill();
+ } else {
+ ctx.fillRect(x, y, 1, 1);
+ }
+ this._setFill(f);
+};
+
+p5.Renderer2D.prototype.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) {
+ var ctx = this.drawingContext;
+ var doFill = this._doFill,
+ doStroke = this._doStroke;
+ if (doFill && !doStroke) {
+ if (this._getFill() === styleEmpty) {
+ return this;
+ }
+ } else if (!doFill && doStroke) {
+ if (this._getStroke() === styleEmpty) {
+ return this;
+ }
+ }
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.lineTo(x3, y3);
+ ctx.lineTo(x4, y4);
+ ctx.closePath();
+ if (doFill) {
+ ctx.fill();
+ }
+ if (doStroke) {
+ ctx.stroke();
+ }
+ return this;
+};
+
+p5.Renderer2D.prototype.rect = function(args) {
+ var x = args[0],
+ y = args[1],
+ w = args[2],
+ h = args[3],
+ tl = args[4],
+ tr = args[5],
+ br = args[6],
+ bl = args[7];
+ var ctx = this.drawingContext;
+ var doFill = this._doFill,
+ doStroke = this._doStroke;
+ if (doFill && !doStroke) {
+ if (this._getFill() === styleEmpty) {
+ return this;
+ }
+ } else if (!doFill && doStroke) {
+ if (this._getStroke() === styleEmpty) {
+ return this;
+ }
+ }
+ // Translate the line by (0.5, 0.5) to draw a crisp rectangle border
+ if (this._doStroke && ctx.lineWidth % 2 === 1) {
+ ctx.translate(0.5, 0.5);
+ }
+ ctx.beginPath();
+
+ if (typeof tl === 'undefined') {
+ // No rounded corners
+ ctx.rect(x, y, w, h);
+ } else {
+ // At least one rounded corner
+ // Set defaults when not specified
+ if (typeof tr === 'undefined') {
+ tr = tl;
+ }
+ if (typeof br === 'undefined') {
+ br = tr;
+ }
+ if (typeof bl === 'undefined') {
+ bl = br;
+ }
+
+ var hw = w / 2;
+ var hh = h / 2;
+
+ // Clip radii
+ if (w < 2 * tl) {
+ tl = hw;
+ }
+ if (h < 2 * tl) {
+ tl = hh;
+ }
+ if (w < 2 * tr) {
+ tr = hw;
+ }
+ if (h < 2 * tr) {
+ tr = hh;
+ }
+ if (w < 2 * br) {
+ br = hw;
+ }
+ if (h < 2 * br) {
+ br = hh;
+ }
+ if (w < 2 * bl) {
+ bl = hw;
+ }
+ if (h < 2 * bl) {
+ bl = hh;
+ }
+
+ // Draw shape
+ ctx.beginPath();
+ ctx.moveTo(x + tl, y);
+ ctx.arcTo(x + w, y, x + w, y + h, tr);
+ ctx.arcTo(x + w, y + h, x, y + h, br);
+ ctx.arcTo(x, y + h, x, y, bl);
+ ctx.arcTo(x, y, x + w, y, tl);
+ ctx.closePath();
+ }
+ if (this._doFill) {
+ ctx.fill();
+ }
+ if (this._doStroke) {
+ ctx.stroke();
+ }
+ if (this._doStroke && ctx.lineWidth % 2 === 1) {
+ ctx.translate(-0.5, -0.5);
+ }
+ return this;
+};
+
+p5.Renderer2D.prototype.triangle = function(args) {
+ var ctx = this.drawingContext;
+ var doFill = this._doFill,
+ doStroke = this._doStroke;
+ var x1 = args[0],
+ y1 = args[1];
+ var x2 = args[2],
+ y2 = args[3];
+ var x3 = args[4],
+ y3 = args[5];
+ if (doFill && !doStroke) {
+ if (this._getFill() === styleEmpty) {
+ return this;
+ }
+ } else if (!doFill && doStroke) {
+ if (this._getStroke() === styleEmpty) {
+ return this;
+ }
+ }
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.lineTo(x3, y3);
+ ctx.closePath();
+ if (doFill) {
+ ctx.fill();
+ }
+ if (doStroke) {
+ ctx.stroke();
+ }
+};
+
+p5.Renderer2D.prototype.endShape = function(
+ mode,
+ vertices,
+ isCurve,
+ isBezier,
+ isQuadratic,
+ isContour,
+ shapeKind
+) {
+ if (vertices.length === 0) {
+ return this;
+ }
+ if (!this._doStroke && !this._doFill) {
+ return this;
+ }
+ var closeShape = mode === constants.CLOSE;
+ var v;
+ if (closeShape && !isContour) {
+ vertices.push(vertices[0]);
+ }
+ var i, j;
+ var numVerts = vertices.length;
+ if (isCurve && (shapeKind === constants.POLYGON || shapeKind === null)) {
+ if (numVerts > 3) {
+ var b = [],
+ s = 1 - this._curveTightness;
+ this.drawingContext.beginPath();
+ this.drawingContext.moveTo(vertices[1][0], vertices[1][1]);
+ for (i = 1; i + 2 < numVerts; i++) {
+ v = vertices[i];
+ b[0] = [v[0], v[1]];
+ b[1] = [
+ v[0] + (s * vertices[i + 1][0] - s * vertices[i - 1][0]) / 6,
+ v[1] + (s * vertices[i + 1][1] - s * vertices[i - 1][1]) / 6
+ ];
+ b[2] = [
+ vertices[i + 1][0] +
+ (s * vertices[i][0] - s * vertices[i + 2][0]) / 6,
+ vertices[i + 1][1] + (s * vertices[i][1] - s * vertices[i + 2][1]) / 6
+ ];
+ b[3] = [vertices[i + 1][0], vertices[i + 1][1]];
+ this.drawingContext.bezierCurveTo(
+ b[1][0],
+ b[1][1],
+ b[2][0],
+ b[2][1],
+ b[3][0],
+ b[3][1]
+ );
+ }
+ if (closeShape) {
+ this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]);
+ }
+ this._doFillStrokeClose();
+ }
+ } else if (
+ isBezier &&
+ (shapeKind === constants.POLYGON || shapeKind === null)
+ ) {
+ this.drawingContext.beginPath();
+ for (i = 0; i < numVerts; i++) {
+ if (vertices[i].isVert) {
+ if (vertices[i].moveTo) {
+ this.drawingContext.moveTo(vertices[i][0], vertices[i][1]);
+ } else {
+ this.drawingContext.lineTo(vertices[i][0], vertices[i][1]);
+ }
+ } else {
+ this.drawingContext.bezierCurveTo(
+ vertices[i][0],
+ vertices[i][1],
+ vertices[i][2],
+ vertices[i][3],
+ vertices[i][4],
+ vertices[i][5]
+ );
+ }
+ }
+ this._doFillStrokeClose();
+ } else if (
+ isQuadratic &&
+ (shapeKind === constants.POLYGON || shapeKind === null)
+ ) {
+ this.drawingContext.beginPath();
+ for (i = 0; i < numVerts; i++) {
+ if (vertices[i].isVert) {
+ if (vertices[i].moveTo) {
+ this.drawingContext.moveTo([0], vertices[i][1]);
+ } else {
+ this.drawingContext.lineTo(vertices[i][0], vertices[i][1]);
+ }
+ } else {
+ this.drawingContext.quadraticCurveTo(
+ vertices[i][0],
+ vertices[i][1],
+ vertices[i][2],
+ vertices[i][3]
+ );
+ }
+ }
+ this._doFillStrokeClose();
+ } else {
+ if (shapeKind === constants.POINTS) {
+ for (i = 0; i < numVerts; i++) {
+ v = vertices[i];
+ if (this._doStroke) {
+ this._pInst.stroke(v[6]);
+ }
+ this._pInst.point(v[0], v[1]);
+ }
+ } else if (shapeKind === constants.LINES) {
+ for (i = 0; i + 1 < numVerts; i += 2) {
+ v = vertices[i];
+ if (this._doStroke) {
+ this._pInst.stroke(vertices[i + 1][6]);
+ }
+ this._pInst.line(v[0], v[1], vertices[i + 1][0], vertices[i + 1][1]);
+ }
+ } else if (shapeKind === constants.TRIANGLES) {
+ for (i = 0; i + 2 < numVerts; i += 3) {
+ v = vertices[i];
+ this.drawingContext.beginPath();
+ this.drawingContext.moveTo(v[0], v[1]);
+ this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]);
+ this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]);
+ this.drawingContext.lineTo(v[0], v[1]);
+ if (this._doFill) {
+ this._pInst.fill(vertices[i + 2][5]);
+ this.drawingContext.fill();
+ }
+ if (this._doStroke) {
+ this._pInst.stroke(vertices[i + 2][6]);
+ this.drawingContext.stroke();
+ }
+ this.drawingContext.closePath();
+ }
+ } else if (shapeKind === constants.TRIANGLE_STRIP) {
+ for (i = 0; i + 1 < numVerts; i++) {
+ v = vertices[i];
+ this.drawingContext.beginPath();
+ this.drawingContext.moveTo(vertices[i + 1][0], vertices[i + 1][1]);
+ this.drawingContext.lineTo(v[0], v[1]);
+ if (this._doStroke) {
+ this._pInst.stroke(vertices[i + 1][6]);
+ }
+ if (this._doFill) {
+ this._pInst.fill(vertices[i + 1][5]);
+ }
+ if (i + 2 < numVerts) {
+ this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]);
+ if (this._doStroke) {
+ this._pInst.stroke(vertices[i + 2][6]);
+ }
+ if (this._doFill) {
+ this._pInst.fill(vertices[i + 2][5]);
+ }
+ }
+ this._doFillStrokeClose();
+ }
+ } else if (shapeKind === constants.TRIANGLE_FAN) {
+ if (numVerts > 2) {
+ // For performance reasons, try to batch as many of the
+ // fill and stroke calls as possible.
+ this.drawingContext.beginPath();
+ for (i = 2; i < numVerts; i++) {
+ v = vertices[i];
+ this.drawingContext.moveTo(vertices[0][0], vertices[0][1]);
+ this.drawingContext.lineTo(vertices[i - 1][0], vertices[i - 1][1]);
+ this.drawingContext.lineTo(v[0], v[1]);
+ this.drawingContext.lineTo(vertices[0][0], vertices[0][1]);
+ // If the next colour is going to be different, stroke / fill now
+ if (i < numVerts - 1) {
+ if (
+ (this._doFill && v[5] !== vertices[i + 1][5]) ||
+ (this._doStroke && v[6] !== vertices[i + 1][6])
+ ) {
+ if (this._doFill) {
+ this._pInst.fill(v[5]);
+ this.drawingContext.fill();
+ this._pInst.fill(vertices[i + 1][5]);
+ }
+ if (this._doStroke) {
+ this._pInst.stroke(v[6]);
+ this.drawingContext.stroke();
+ this._pInst.stroke(vertices[i + 1][6]);
+ }
+ this.drawingContext.closePath();
+ this.drawingContext.beginPath(); // Begin the next one
+ }
+ }
+ }
+ this._doFillStrokeClose();
+ }
+ } else if (shapeKind === constants.QUADS) {
+ for (i = 0; i + 3 < numVerts; i += 4) {
+ v = vertices[i];
+ this.drawingContext.beginPath();
+ this.drawingContext.moveTo(v[0], v[1]);
+ for (j = 1; j < 4; j++) {
+ this.drawingContext.lineTo(vertices[i + j][0], vertices[i + j][1]);
+ }
+ this.drawingContext.lineTo(v[0], v[1]);
+ if (this._doFill) {
+ this._pInst.fill(vertices[i + 3][5]);
+ }
+ if (this._doStroke) {
+ this._pInst.stroke(vertices[i + 3][6]);
+ }
+ this._doFillStrokeClose();
+ }
+ } else if (shapeKind === constants.QUAD_STRIP) {
+ if (numVerts > 3) {
+ for (i = 0; i + 1 < numVerts; i += 2) {
+ v = vertices[i];
+ this.drawingContext.beginPath();
+ if (i + 3 < numVerts) {
+ this.drawingContext.moveTo(vertices[i + 2][0], vertices[i + 2][1]);
+ this.drawingContext.lineTo(v[0], v[1]);
+ this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]);
+ this.drawingContext.lineTo(vertices[i + 3][0], vertices[i + 3][1]);
+ if (this._doFill) {
+ this._pInst.fill(vertices[i + 3][5]);
+ }
+ if (this._doStroke) {
+ this._pInst.stroke(vertices[i + 3][6]);
+ }
+ } else {
+ this.drawingContext.moveTo(v[0], v[1]);
+ this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]);
+ }
+ this._doFillStrokeClose();
+ }
+ }
+ } else {
+ this.drawingContext.beginPath();
+ this.drawingContext.moveTo(vertices[0][0], vertices[0][1]);
+ for (i = 1; i < numVerts; i++) {
+ v = vertices[i];
+ if (v.isVert) {
+ if (v.moveTo) {
+ this.drawingContext.moveTo(v[0], v[1]);
+ } else {
+ this.drawingContext.lineTo(v[0], v[1]);
+ }
+ }
+ }
+ this._doFillStrokeClose();
+ }
+ }
+ isCurve = false;
+ isBezier = false;
+ isQuadratic = false;
+ isContour = false;
+ if (closeShape) {
+ vertices.pop();
+ }
+ return this;
+};
+//////////////////////////////////////////////
+// SHAPE | Attributes
+//////////////////////////////////////////////
+
+p5.Renderer2D.prototype.noSmooth = function() {
+ if ('imageSmoothingEnabled' in this.drawingContext) {
+ this.drawingContext.imageSmoothingEnabled = false;
+ }
+ return this;
+};
+
+p5.Renderer2D.prototype.smooth = function() {
+ if ('imageSmoothingEnabled' in this.drawingContext) {
+ this.drawingContext.imageSmoothingEnabled = true;
+ }
+ return this;
+};
+
+p5.Renderer2D.prototype.strokeCap = function(cap) {
+ if (
+ cap === constants.ROUND ||
+ cap === constants.SQUARE ||
+ cap === constants.PROJECT
+ ) {
+ this.drawingContext.lineCap = cap;
+ }
+ return this;
+};
+
+p5.Renderer2D.prototype.strokeJoin = function(join) {
+ if (
+ join === constants.ROUND ||
+ join === constants.BEVEL ||
+ join === constants.MITER
+ ) {
+ this.drawingContext.lineJoin = join;
+ }
+ return this;
+};
+
+p5.Renderer2D.prototype.strokeWeight = function(w) {
+ if (typeof w === 'undefined' || w === 0) {
+ // hack because lineWidth 0 doesn't work
+ this.drawingContext.lineWidth = 0.0001;
+ } else {
+ this.drawingContext.lineWidth = w;
+ }
+ return this;
+};
+
+p5.Renderer2D.prototype._getFill = function() {
+ if (!this._cachedFillStyle) {
+ this._cachedFillStyle = this.drawingContext.fillStyle;
+ }
+ return this._cachedFillStyle;
+};
+
+p5.Renderer2D.prototype._setFill = function(fillStyle) {
+ if (fillStyle !== this._cachedFillStyle) {
+ this.drawingContext.fillStyle = fillStyle;
+ this._cachedFillStyle = fillStyle;
+ }
+};
+
+p5.Renderer2D.prototype._getStroke = function() {
+ if (!this._cachedStrokeStyle) {
+ this._cachedStrokeStyle = this.drawingContext.strokeStyle;
+ }
+ return this._cachedStrokeStyle;
+};
+
+p5.Renderer2D.prototype._setStroke = function(strokeStyle) {
+ if (strokeStyle !== this._cachedStrokeStyle) {
+ this.drawingContext.strokeStyle = strokeStyle;
+ this._cachedStrokeStyle = strokeStyle;
+ }
+};
+
+//////////////////////////////////////////////
+// SHAPE | Curves
+//////////////////////////////////////////////
+p5.Renderer2D.prototype.bezier = function(x1, y1, x2, y2, x3, y3, x4, y4) {
+ this._pInst.beginShape();
+ this._pInst.vertex(x1, y1);
+ this._pInst.bezierVertex(x2, y2, x3, y3, x4, y4);
+ this._pInst.endShape();
+ return this;
+};
+
+p5.Renderer2D.prototype.curve = function(x1, y1, x2, y2, x3, y3, x4, y4) {
+ this._pInst.beginShape();
+ this._pInst.curveVertex(x1, y1);
+ this._pInst.curveVertex(x2, y2);
+ this._pInst.curveVertex(x3, y3);
+ this._pInst.curveVertex(x4, y4);
+ this._pInst.endShape();
+ return this;
+};
+
+//////////////////////////////////////////////
+// SHAPE | Vertex
+//////////////////////////////////////////////
+
+p5.Renderer2D.prototype._doFillStrokeClose = function() {
+ if (this._doFill) {
+ this.drawingContext.fill();
+ }
+ if (this._doStroke) {
+ this.drawingContext.stroke();
+ }
+ this.drawingContext.closePath();
+};
+
+//////////////////////////////////////////////
+// TRANSFORM
+//////////////////////////////////////////////
+
+p5.Renderer2D.prototype.applyMatrix = function(a, b, c, d, e, f) {
+ this.drawingContext.transform(a, b, c, d, e, f);
+};
+
+p5.Renderer2D.prototype.resetMatrix = function() {
+ this.drawingContext.setTransform(1, 0, 0, 1, 0, 0);
+ this.drawingContext.scale(
+ this._pInst._pixelDensity,
+ this._pInst._pixelDensity
+ );
+ return this;
+};
+
+p5.Renderer2D.prototype.rotate = function(rad) {
+ this.drawingContext.rotate(rad);
+};
+
+p5.Renderer2D.prototype.scale = function(x, y) {
+ this.drawingContext.scale(x, y);
+ return this;
+};
+
+p5.Renderer2D.prototype.shearX = function(rad) {
+ this.drawingContext.transform(1, 0, Math.tan(rad), 1, 0, 0);
+ return this;
+};
+
+p5.Renderer2D.prototype.shearY = function(rad) {
+ this.drawingContext.transform(1, Math.tan(rad), 0, 1, 0, 0);
+ return this;
+};
+
+p5.Renderer2D.prototype.translate = function(x, y) {
+ // support passing a vector as the 1st parameter
+ if (x instanceof p5.Vector) {
+ y = x.y;
+ x = x.x;
+ }
+ this.drawingContext.translate(x, y);
+ return this;
+};
+
+//////////////////////////////////////////////
+// TYPOGRAPHY
+//
+//////////////////////////////////////////////
+
+p5.Renderer2D.prototype.text = function(str, x, y, maxWidth, maxHeight) {
+ var p = this._pInst,
+ cars,
+ n,
+ ii,
+ jj,
+ line,
+ testLine,
+ testWidth,
+ words,
+ totalHeight,
+ baselineHacked,
+ finalMaxHeight = Number.MAX_VALUE;
+
+ // baselineHacked: (HACK)
+ // A temporary fix to conform to Processing's implementation
+ // of BASELINE vertical alignment in a bounding box
+
+ if (!(this._doFill || this._doStroke)) {
+ return;
+ }
+
+ if (typeof str === 'undefined') {
+ return;
+ } else if (typeof str !== 'string') {
+ str = str.toString();
+ }
+
+ str = str.replace(/(\t)/g, ' ');
+ cars = str.split('\n');
+
+ if (typeof maxWidth !== 'undefined') {
+ totalHeight = 0;
+ for (ii = 0; ii < cars.length; ii++) {
+ line = '';
+ words = cars[ii].split(' ');
+ for (n = 0; n < words.length; n++) {
+ testLine = line + words[n] + ' ';
+ testWidth = this.textWidth(testLine);
+ if (testWidth > maxWidth) {
+ line = words[n] + ' ';
+ totalHeight += p.textLeading();
+ } else {
+ line = testLine;
+ }
+ }
+ }
+
+ if (this._rectMode === constants.CENTER) {
+ x -= maxWidth / 2;
+ y -= maxHeight / 2;
+ }
+
+ switch (this.drawingContext.textAlign) {
+ case constants.CENTER:
+ x += maxWidth / 2;
+ break;
+ case constants.RIGHT:
+ x += maxWidth;
+ break;
+ }
+
+ if (typeof maxHeight !== 'undefined') {
+ switch (this.drawingContext.textBaseline) {
+ case constants.BOTTOM:
+ y += maxHeight - totalHeight;
+ break;
+ case constants._CTX_MIDDLE: // CENTER?
+ y += (maxHeight - totalHeight) / 2;
+ break;
+ case constants.BASELINE:
+ baselineHacked = true;
+ this.drawingContext.textBaseline = constants.TOP;
+ break;
+ }
+
+ // remember the max-allowed y-position for any line (fix to #928)
+ finalMaxHeight = y + maxHeight - p.textAscent();
+ }
+
+ for (ii = 0; ii < cars.length; ii++) {
+ line = '';
+ words = cars[ii].split(' ');
+ for (n = 0; n < words.length; n++) {
+ testLine = line + words[n] + ' ';
+ testWidth = this.textWidth(testLine);
+ if (testWidth > maxWidth && line.length > 0) {
+ this._renderText(p, line, x, y, finalMaxHeight);
+ line = words[n] + ' ';
+ y += p.textLeading();
+ } else {
+ line = testLine;
+ }
+ }
+
+ this._renderText(p, line, x, y, finalMaxHeight);
+ y += p.textLeading();
+ }
+ } else {
+ // Offset to account for vertically centering multiple lines of text - no
+ // need to adjust anything for vertical align top or baseline
+ var offset = 0,
+ vAlign = p.textAlign().vertical;
+ if (vAlign === constants.CENTER) {
+ offset = (cars.length - 1) * p.textLeading() / 2;
+ } else if (vAlign === constants.BOTTOM) {
+ offset = (cars.length - 1) * p.textLeading();
+ }
+
+ for (jj = 0; jj < cars.length; jj++) {
+ this._renderText(p, cars[jj], x, y - offset, finalMaxHeight);
+ y += p.textLeading();
+ }
+ }
+
+ if (baselineHacked) {
+ this.drawingContext.textBaseline = constants.BASELINE;
+ }
+
+ return p;
+};
+
+p5.Renderer2D.prototype._renderText = function(p, line, x, y, maxY) {
+ if (y >= maxY) {
+ return; // don't render lines beyond our maxY position
+ }
+
+ p.push(); // fix to #803
+
+ if (!this._isOpenType()) {
+ // a system/browser font
+
+ // no stroke unless specified by user
+ if (this._doStroke && this._strokeSet) {
+ this.drawingContext.strokeText(line, x, y);
+ }
+
+ if (this._doFill) {
+ // if fill hasn't been set by user, use default text fill
+ if (!this._fillSet) {
+ this._setFill(constants._DEFAULT_TEXT_FILL);
+ }
+
+ this.drawingContext.fillText(line, x, y);
+ }
+ } else {
+ // an opentype font, let it handle the rendering
+
+ this._textFont._renderPath(line, x, y, { renderer: this });
+ }
+
+ p.pop();
+
+ return p;
+};
+
+p5.Renderer2D.prototype.textWidth = function(s) {
+ if (this._isOpenType()) {
+ return this._textFont._textWidth(s, this._textSize);
+ }
+
+ return this.drawingContext.measureText(s).width;
+};
+
+p5.Renderer2D.prototype.textAlign = function(h, v) {
+ if (typeof h !== 'undefined') {
+ if (
+ h === constants.LEFT ||
+ h === constants.RIGHT ||
+ h === constants.CENTER
+ ) {
+ this.drawingContext.textAlign = h;
+ }
+
+ if (
+ v === constants.TOP ||
+ v === constants.BOTTOM ||
+ v === constants.CENTER ||
+ v === constants.BASELINE
+ ) {
+ if (v === constants.CENTER) {
+ this.drawingContext.textBaseline = constants._CTX_MIDDLE;
+ } else {
+ this.drawingContext.textBaseline = v;
+ }
+ }
+
+ return this._pInst;
+ } else {
+ var valign = this.drawingContext.textBaseline;
+
+ if (valign === constants._CTX_MIDDLE) {
+ valign = constants.CENTER;
+ }
+
+ return {
+ horizontal: this.drawingContext.textAlign,
+ vertical: valign
+ };
+ }
+};
+
+p5.Renderer2D.prototype._applyTextProperties = function() {
+ var font,
+ p = this._pInst;
+
+ this._setProperty('_textAscent', null);
+ this._setProperty('_textDescent', null);
+
+ font = this._textFont;
+
+ if (this._isOpenType()) {
+ font = this._textFont.font.familyName;
+ this._setProperty('_textStyle', this._textFont.font.styleName);
+ }
+
+ this.drawingContext.font =
+ (this._textStyle || 'normal') +
+ ' ' +
+ (this._textSize || 12) +
+ 'px ' +
+ (font || 'sans-serif');
+
+ return p;
+};
+
+//////////////////////////////////////////////
+// STRUCTURE
+//////////////////////////////////////////////
+
+// a push() operation is in progress.
+// the renderer should return a 'style' object that it wishes to
+// store on the push stack.
+// derived renderers should call the base class' push() method
+// to fetch the base style object.
+p5.Renderer2D.prototype.push = function() {
+ this.drawingContext.save();
+
+ // get the base renderer style
+ return p5.Renderer.prototype.push.apply(this);
+};
+
+// a pop() operation is in progress
+// the renderer is passed the 'style' object that it returned
+// from its push() method.
+// derived renderers should pass this object to their base
+// class' pop method
+p5.Renderer2D.prototype.pop = function(style) {
+ this.drawingContext.restore();
+ // Re-cache the fill / stroke state
+ this._cachedFillStyle = this.drawingContext.fillStyle;
+ this._cachedStrokeStyle = this.drawingContext.strokeStyle;
+
+ p5.Renderer.prototype.pop.call(this, style);
+};
+
+module.exports = p5.Renderer2D;
+
+},{"../image/filters":41,"./canvas":20,"./constants":21,"./core":22,"./p5.Renderer":29}],31:[function(_dereq_,module,exports){
+/**
+ * @module Rendering
+ * @submodule Rendering
+ * @for p5
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+var constants = _dereq_('./constants');
+_dereq_('./p5.Graphics');
+_dereq_('./p5.Renderer2D');
+_dereq_('../webgl/p5.RendererGL');
+var defaultId = 'defaultCanvas0'; // this gets set again in createCanvas
+var defaultClass = 'p5Canvas';
+
+/**
+ * Creates a canvas element in the document, and sets the dimensions of it
+ * in pixels. This method should be called only once at the start of setup.
+ * Calling createCanvas more than once in a sketch will result in very
+ * unpredictable behavior. If you want more than one drawing canvas
+ * you could use createGraphics (hidden by default but it can be shown).
+ *
+ * The system variables width and height are set by the parameters passed
+ * to this function. If createCanvas() is not used, the window will be
+ * given a default size of 100x100 pixels.
+ *
+ * For more ways to position the canvas, see the
+ *
+ * positioning the canvas wiki page.
+ *
+ * @method createCanvas
+ * @param {Number} w width of the canvas
+ * @param {Number} h height of the canvas
+ * @param {Constant} [renderer] either P2D or WEBGL
+ * @return {p5.Renderer}
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 50);
+ * background(153);
+ * line(0, 0, width, height);
+ * }
+ *
+ *
+ *
+ * @alt
+ * Black line extending from top-left of canvas to bottom right.
+ *
+ */
+
+p5.prototype.createCanvas = function(w, h, renderer) {
+ p5._validateParameters('createCanvas', arguments);
+ //optional: renderer, otherwise defaults to p2d
+ var r = renderer || constants.P2D;
+ var c;
+
+ if (r === constants.WEBGL) {
+ c = document.getElementById(defaultId);
+ if (c) {
+ //if defaultCanvas already exists
+ c.parentNode.removeChild(c); //replace the existing defaultCanvas
+ var thisRenderer = this._renderer;
+ this._elements = this._elements.filter(function(e) {
+ return e !== thisRenderer;
+ });
+ }
+ c = document.createElement('canvas');
+ c.id = defaultId;
+ c.classList.add(defaultClass);
+ } else {
+ if (!this._defaultGraphicsCreated) {
+ c = document.createElement('canvas');
+ var i = 0;
+ while (document.getElementById('defaultCanvas' + i)) {
+ i++;
+ }
+ defaultId = 'defaultCanvas' + i;
+ c.id = defaultId;
+ c.classList.add(defaultClass);
+ } else {
+ // resize the default canvas if new one is created
+ c = this.canvas;
+ }
+ }
+
+ // set to invisible if still in setup (to prevent flashing with manipulate)
+ if (!this._setupDone) {
+ c.dataset.hidden = true; // tag to show later
+ c.style.visibility = 'hidden';
+ }
+
+ if (this._userNode) {
+ // user input node case
+ this._userNode.appendChild(c);
+ } else {
+ document.body.appendChild(c);
+ }
+
+ // Init our graphics renderer
+ //webgl mode
+ if (r === constants.WEBGL) {
+ this._setProperty('_renderer', new p5.RendererGL(c, this, true));
+ this._elements.push(this._renderer);
+ } else {
+ //P2D mode
+ if (!this._defaultGraphicsCreated) {
+ this._setProperty('_renderer', new p5.Renderer2D(c, this, true));
+ this._defaultGraphicsCreated = true;
+ this._elements.push(this._renderer);
+ }
+ }
+ this._renderer.resize(w, h);
+ this._renderer._applyDefaults();
+ return this._renderer;
+};
+
+/**
+ * Resizes the canvas to given width and height. The canvas will be cleared
+ * and draw will be called immediately, allowing the sketch to re-render itself
+ * in the resized canvas.
+ * @method resizeCanvas
+ * @param {Number} w width of the canvas
+ * @param {Number} h height of the canvas
+ * @param {Boolean} [noRedraw] don't redraw the canvas immediately
+ * @example
+ *
+ * function setup() {
+ * createCanvas(windowWidth, windowHeight);
+ * }
+ *
+ * function draw() {
+ * background(0, 100, 200);
+ * }
+ *
+ * function windowResized() {
+ * resizeCanvas(windowWidth, windowHeight);
+ * }
+ *
+ *
+ * @alt
+ * No image displayed.
+ *
+ */
+p5.prototype.resizeCanvas = function(w, h, noRedraw) {
+ p5._validateParameters('resizeCanvas', arguments);
+ if (this._renderer) {
+ // save canvas properties
+ var props = {};
+ for (var key in this.drawingContext) {
+ var val = this.drawingContext[key];
+ if (typeof val !== 'object' && typeof val !== 'function') {
+ props[key] = val;
+ }
+ }
+ this._renderer.resize(w, h);
+ // reset canvas properties
+ for (var savedKey in props) {
+ try {
+ this.drawingContext[savedKey] = props[savedKey];
+ } catch (err) {
+ // ignore read-only property errors
+ }
+ }
+ if (!noRedraw) {
+ this.redraw();
+ }
+ }
+};
+
+/**
+ * Removes the default canvas for a p5 sketch that doesn't
+ * require a canvas
+ * @method noCanvas
+ * @example
+ *
+ *
+ * function setup() {
+ * noCanvas();
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.prototype.noCanvas = function() {
+ if (this.canvas) {
+ this.canvas.parentNode.removeChild(this.canvas);
+ }
+};
+
+/**
+ * Creates and returns a new p5.Renderer object. Use this class if you need
+ * to draw into an off-screen graphics buffer. The two parameters define the
+ * width and height in pixels.
+ *
+ * @method createGraphics
+ * @param {Number} w width of the offscreen graphics buffer
+ * @param {Number} h height of the offscreen graphics buffer
+ * @param {Constant} [renderer] either P2D or WEBGL
+ * undefined defaults to p2d
+ * @return {p5.Graphics} offscreen graphics buffer
+ * @example
+ *
+ *
+ * var pg;
+ * function setup() {
+ * createCanvas(100, 100);
+ * pg = createGraphics(100, 100);
+ * }
+ * function draw() {
+ * background(200);
+ * pg.background(100);
+ * pg.noStroke();
+ * pg.ellipse(pg.width / 2, pg.height / 2, 50, 50);
+ * image(pg, 50, 50);
+ * image(pg, 0, 0, 50, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 4 grey squares alternating light and dark grey. White quarter circle mid-left.
+ *
+ */
+p5.prototype.createGraphics = function(w, h, renderer) {
+ p5._validateParameters('createGraphics', arguments);
+ return new p5.Graphics(w, h, renderer, this);
+};
+
+/**
+ * Blends the pixels in the display window according to the defined mode.
+ * There is a choice of the following modes to blend the source pixels (A)
+ * with the ones of pixels already in the display window (B):
+ *
+ * BLEND - linear interpolation of colours: C =
+ * A\*factor + B. This is the default blending mode.
+ * ADD - sum of A and B
+ * DARKEST - only the darkest colour succeeds: C =
+ * min(A\*factor, B).
+ * LIGHTEST - only the lightest colour succeeds: C =
+ * max(A\*factor, B).
+ * DIFFERENCE - subtract colors from underlying image.
+ * EXCLUSION - similar to DIFFERENCE, but less
+ * extreme.
+ * MULTIPLY - multiply the colors, result will always be
+ * darker.
+ * SCREEN - opposite multiply, uses inverse values of the
+ * colors.
+ * REPLACE - the pixels entirely replace the others and
+ * don't utilize alpha (transparency) values.
+ * OVERLAY - mix of MULTIPLY and SCREEN
+ * . Multiplies dark values, and screens light values.
+ * HARD_LIGHT - SCREEN when greater than 50%
+ * gray, MULTIPLY when lower.
+ * SOFT_LIGHT - mix of DARKEST and
+ * LIGHTEST. Works like OVERLAY, but not as harsh.
+ *
+ * DODGE - lightens light tones and increases contrast,
+ * ignores darks.
+ * BURN - darker areas are applied, increasing contrast,
+ * ignores lights.
+ *
+ *
+ * @method blendMode
+ * @param {Constant} mode blend mode to set for canvas.
+ * either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,
+ * EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
+ * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL
+ * @example
+ *
+ *
+ * blendMode(LIGHTEST);
+ * strokeWeight(30);
+ * stroke(80, 150, 255);
+ * line(25, 25, 75, 75);
+ * stroke(255, 50, 50);
+ * line(75, 25, 25, 75);
+ *
+ *
+ *
+ *
+ * blendMode(MULTIPLY);
+ * strokeWeight(30);
+ * stroke(80, 150, 255);
+ * line(25, 25, 75, 75);
+ * stroke(255, 50, 50);
+ * line(75, 25, 25, 75);
+ *
+ *
+ * @alt
+ * translucent image thick red & blue diagonal rounded lines intersecting center
+ * Thick red & blue diagonal rounded lines intersecting center. dark at overlap
+ *
+ */
+p5.prototype.blendMode = function(mode) {
+ p5._validateParameters('blendMode', arguments);
+ if (
+ mode === constants.BLEND ||
+ mode === constants.DARKEST ||
+ mode === constants.LIGHTEST ||
+ mode === constants.DIFFERENCE ||
+ mode === constants.MULTIPLY ||
+ mode === constants.EXCLUSION ||
+ mode === constants.SCREEN ||
+ mode === constants.REPLACE ||
+ mode === constants.OVERLAY ||
+ mode === constants.HARD_LIGHT ||
+ mode === constants.SOFT_LIGHT ||
+ mode === constants.DODGE ||
+ mode === constants.BURN ||
+ mode === constants.ADD ||
+ mode === constants.NORMAL
+ ) {
+ this._renderer.blendMode(mode);
+ } else {
+ throw new Error('Mode ' + mode + ' not recognized.');
+ }
+};
+
+module.exports = p5;
+
+},{"../webgl/p5.RendererGL":72,"./constants":21,"./core":22,"./p5.Graphics":28,"./p5.Renderer2D":30}],32:[function(_dereq_,module,exports){
+'use strict';
+
+// requestAnim shim layer by Paul Irish
+window.requestAnimationFrame = (function() {
+ return (
+ window.requestAnimationFrame ||
+ window.webkitRequestAnimationFrame ||
+ window.mozRequestAnimationFrame ||
+ window.oRequestAnimationFrame ||
+ window.msRequestAnimationFrame ||
+ function(callback, element) {
+ // should '60' here be framerate?
+ window.setTimeout(callback, 1000 / 60);
+ }
+ );
+})();
+
+// use window.performance() to get max fast and accurate time in milliseconds
+window.performance = window.performance || {};
+window.performance.now = (function() {
+ var load_date = Date.now();
+ return (
+ window.performance.now ||
+ window.performance.mozNow ||
+ window.performance.msNow ||
+ window.performance.oNow ||
+ window.performance.webkitNow ||
+ function() {
+ return Date.now() - load_date;
+ }
+ );
+})();
+
+/*
+// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
+// http://my.opera.com/emoller/blog/2011/12/20/
+// requestanimationframe-for-smart-er-animating
+// requestAnimationFrame polyfill by Erik Möller
+// fixes from Paul Irish and Tino Zijdel
+(function() {
+ var lastTime = 0;
+ var vendors = ['ms', 'moz', 'webkit', 'o'];
+ for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
+ window.requestAnimationFrame =
+ window[vendors[x]+'RequestAnimationFrame'];
+ window.cancelAnimationFrame =
+ window[vendors[x]+'CancelAnimationFrame'] ||
+ window[vendors[x]+'CancelRequestAnimationFrame'];
+ }
+
+ if (!window.requestAnimationFrame) {
+ window.requestAnimationFrame = function(callback, element) {
+ var currTime = new Date().getTime();
+ var timeToCall = Math.max(0, 16 - (currTime - lastTime));
+ var id = window.setTimeout(function()
+ { callback(currTime + timeToCall); }, timeToCall);
+ lastTime = currTime + timeToCall;
+ return id;
+ };
+ }
+
+ if (!window.cancelAnimationFrame) {
+ window.cancelAnimationFrame = function(id) {
+ clearTimeout(id);
+ };
+ }
+}());
+*/
+
+/**
+ * shim for Uint8ClampedArray.slice
+ * (allows arrayCopy to work with pixels[])
+ * with thanks to http://halfpapstudios.com/blog/tag/html5-canvas/
+ * Enumerable set to false to protect for...in from
+ * Uint8ClampedArray.prototype pollution.
+ */
+(function() {
+ 'use strict';
+ if (
+ typeof Uint8ClampedArray !== 'undefined' &&
+ !Uint8ClampedArray.prototype.slice
+ ) {
+ Object.defineProperty(Uint8ClampedArray.prototype, 'slice', {
+ value: Array.prototype.slice,
+ writable: true,
+ configurable: true,
+ enumerable: false
+ });
+ }
+})();
+
+},{}],33:[function(_dereq_,module,exports){
+/**
+ * @module Structure
+ * @submodule Structure
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+
+p5.prototype.exit = function() {
+ throw 'exit() not implemented, see remove()';
+};
+/**
+ * Stops p5.js from continuously executing the code within draw().
+ * If loop() is called, the code in draw() begins to run continuously again.
+ * If using noLoop() in setup(), it should be the last line inside the block.
+ *
+ * When noLoop() is used, it's not possible to manipulate or access the
+ * screen inside event handling functions such as mousePressed() or
+ * keyPressed(). Instead, use those functions to call redraw() or loop(),
+ * which will run draw(), which can update the screen properly. This means
+ * that when noLoop() has been called, no drawing can happen, and functions
+ * like saveFrame() or loadPixels() may not be used.
+ *
+ * Note that if the sketch is resized, redraw() will be called to update
+ * the sketch, even after noLoop() has been specified. Otherwise, the sketch
+ * would enter an odd state until loop() was called.
+ *
+ * @method noLoop
+ * @example
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * background(200);
+ * noLoop();
+ * }
+
+ * function draw() {
+ * line(10, 10, 90, 90);
+ * }
+ *
+ *
+ *
+ * var x = 0;
+ * function setup() {
+ * createCanvas(100, 100);
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * x = x + 0.1;
+ * if (x > width) {
+ * x = 0;
+ * }
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * noLoop();
+ * }
+ *
+ * function mouseReleased() {
+ * loop();
+ * }
+ *
+ *
+ * @alt
+ * 113 pixel long line extending from top-left to bottom right of canvas.
+ * horizontal line moves slowly from left. Loops but stops on mouse press.
+ *
+ */
+p5.prototype.noLoop = function() {
+ this._loop = false;
+};
+/**
+ * By default, p5.js loops through draw() continuously, executing the code
+ * within it. However, the draw() loop may be stopped by calling noLoop().
+ * In that case, the draw() loop can be resumed with loop().
+ *
+ * @method loop
+ * @example
+ *
+ * var x = 0;
+ * function setup() {
+ * createCanvas(100, 100);
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * x = x + 0.1;
+ * if (x > width) {
+ * x = 0;
+ * }
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * loop();
+ * }
+ *
+ * function mouseReleased() {
+ * noLoop();
+ * }
+ *
+ *
+ * @alt
+ * horizontal line moves slowly from left. Loops but stops on mouse press.
+ *
+ */
+
+p5.prototype.loop = function() {
+ this._loop = true;
+ this._draw();
+};
+
+function assign(dest, varArgs) {
+ for (var index = 1; index < arguments.length; index++) {
+ var src = arguments[index];
+ if (src != null) {
+ for (var key in src) {
+ if (src.hasOwnProperty(key)) {
+ dest[key] = src[key];
+ }
+ }
+ }
+ }
+}
+
+/**
+ * The push() function saves the current drawing style settings and
+ * transformations, while pop() restores these settings. Note that these
+ * functions are always used together. They allow you to change the style
+ * and transformation settings and later return to what you had. When a new
+ * state is started with push(), it builds on the current style and transform
+ * information. The push() and pop() functions can be embedded to provide
+ * more control. (See the second example for a demonstration.)
+ *
+ * push() stores information related to the current transformation state
+ * and style settings controlled by the following functions: fill(),
+ * stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),
+ * imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(),
+ * textFont(), textMode(), textSize(), textLeading().
+ *
+ * @method push
+ * @example
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * translate(50, 0);
+ * ellipse(0, 50, 33, 33); // Middle circle
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(33, 50, 33, 33); // Left-middle circle
+ *
+ * push(); // Start another new drawing state
+ * stroke(0, 102, 153);
+ * ellipse(66, 50, 33, 33); // Right-middle circle
+ * pop(); // Restore previous state
+ *
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ * @alt
+ * Gold ellipse + thick black outline @center 2 white ellipses on left and right.
+ * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.
+ *
+ */
+p5.prototype.push = function() {
+ this._styles.push({
+ props: {
+ _colorMode: this._colorMode
+ },
+ renderer: this._renderer.push()
+ });
+};
+
+/**
+ * The push() function saves the current drawing style settings and
+ * transformations, while pop() restores these settings. Note that these
+ * functions are always used together. They allow you to change the style
+ * and transformation settings and later return to what you had. When a new
+ * state is started with push(), it builds on the current style and transform
+ * information. The push() and pop() functions can be embedded to provide
+ * more control. (See the second example for a demonstration.)
+ *
+ * push() stores information related to the current transformation state
+ * and style settings controlled by the following functions: fill(),
+ * stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(),
+ * imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(),
+ * textFont(), textMode(), textSize(), textLeading().
+ *
+ * @method pop
+ * @example
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * translate(50, 0);
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(0, 50, 33, 33); // Middle circle
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ *
+ * ellipse(0, 50, 33, 33); // Left circle
+ *
+ * push(); // Start a new drawing state
+ * strokeWeight(10);
+ * fill(204, 153, 0);
+ * ellipse(33, 50, 33, 33); // Left-middle circle
+ *
+ * push(); // Start another new drawing state
+ * stroke(0, 102, 153);
+ * ellipse(66, 50, 33, 33); // Right-middle circle
+ * pop(); // Restore previous state
+ *
+ * pop(); // Restore original state
+ *
+ * ellipse(100, 50, 33, 33); // Right circle
+ *
+ *
+ *
+ * @alt
+ * Gold ellipse + thick black outline @center 2 white ellipses on left and right.
+ * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.
+ *
+ */
+p5.prototype.pop = function() {
+ var style = this._styles.pop();
+ if (style) {
+ this._renderer.pop(style.renderer);
+ assign(this, style.props);
+ } else {
+ console.warn('pop() was called without matching push()');
+ }
+};
+
+p5.prototype.pushStyle = function() {
+ throw new Error('pushStyle() not used, see push()');
+};
+
+p5.prototype.popStyle = function() {
+ throw new Error('popStyle() not used, see pop()');
+};
+
+/**
+ *
+ * Executes the code within draw() one time. This functions allows the
+ * program to update the display window only when necessary, for example
+ * when an event registered by mousePressed() or keyPressed() occurs.
+ *
+ * In structuring a program, it only makes sense to call redraw() within
+ * events such as mousePressed(). This is because redraw() does not run
+ * draw() immediately (it only sets a flag that indicates an update is
+ * needed).
+ *
+ * The redraw() function does not work properly when called inside draw().
+ * To enable/disable animations, use loop() and noLoop().
+ *
+ * In addition you can set the number of redraws per method call. Just
+ * add an integer as single parameter for the number of redraws.
+ *
+ * @method redraw
+ * @param {Integer} [n] Redraw for n-times. The default value is 1.
+ * @example
+ *
+ * var x = 0;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * x += 1;
+ * redraw();
+ * }
+ *
+ *
+ *
+ * var x = 0;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * x += 1;
+ * line(x, 0, x, height);
+ * }
+ *
+ * function mousePressed() {
+ * redraw(5);
+ * }
+ *
+ *
+ * @alt
+ * black line on far left of canvas
+ * black line on far left of canvas
+ *
+ */
+p5.prototype.redraw = function(n) {
+ this.resetMatrix();
+ if (this._renderer.isP3D) {
+ this._renderer._update();
+ }
+
+ var numberOfRedraws = parseInt(n);
+ if (isNaN(numberOfRedraws) || numberOfRedraws < 1) {
+ numberOfRedraws = 1;
+ }
+
+ var userSetup = this.setup || window.setup;
+ var userDraw = this.draw || window.draw;
+ if (typeof userDraw === 'function') {
+ if (typeof userSetup === 'undefined') {
+ this.scale(this._pixelDensity, this._pixelDensity);
+ }
+ var self = this;
+ var callMethod = function(f) {
+ f.call(self);
+ };
+ for (var idxRedraw = 0; idxRedraw < numberOfRedraws; idxRedraw++) {
+ this._setProperty('frameCount', this.frameCount + 1);
+ this._registeredMethods.pre.forEach(callMethod);
+ userDraw();
+ this._registeredMethods.post.forEach(callMethod);
+ }
+ }
+};
+
+p5.prototype.size = function() {
+ var s = 'size() is not a valid p5 function, to set the size of the ';
+ s += 'drawing canvas, please use createCanvas() instead';
+ throw s;
+};
+
+module.exports = p5;
+
+},{"./core":22}],34:[function(_dereq_,module,exports){
+/**
+ * @module Transform
+ * @submodule Transform
+ * @for p5
+ * @requires core
+ * @requires constants
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+
+/**
+ * Multiplies the current matrix by the one specified through the parameters.
+ * This is a powerful operation that can perform the equivalent of translate,
+ * scale, shear and rotate all at once. You can learn more about transformation
+ * matrices on
+ * Wikipedia.
+ *
+ * The naming of the arguments here follows the naming of the
+ * WHATWG specification and corresponds to a
+ * transformation matrix of the
+ * form:
+ *
+ * >
+ *
+ * @method applyMatrix
+ * @param {Number} a numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} b numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} c numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} d numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} e numbers which define the 2x3 matrix to be multiplied
+ * @param {Number} f numbers which define the 2x3 matrix to be multiplied
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * frameRate(10);
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * var step = frameCount % 20;
+ * background(200);
+ * // Equivalent to translate(x, y);
+ * applyMatrix(1, 0, 0, 1, 40 + step, 50);
+ * rect(0, 0, 50, 50);
+ * }
+ *
+ *
+ *
+ *
+ * function setup() {
+ * frameRate(10);
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * var step = frameCount % 20;
+ * background(200);
+ * translate(50, 50);
+ * // Equivalent to scale(x, y);
+ * applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);
+ * rect(0, 0, 50, 50);
+ * }
+ *
+ *
+ *
+ *
+ * function setup() {
+ * frameRate(10);
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * var step = frameCount % 20;
+ * var angle = map(step, 0, 20, 0, TWO_PI);
+ * var cos_a = cos(angle);
+ * var sin_a = sin(angle);
+ * background(200);
+ * translate(50, 50);
+ * // Equivalent to rotate(angle);
+ * applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);
+ * rect(0, 0, 50, 50);
+ * }
+ *
+ *
+ *
+ *
+ * function setup() {
+ * frameRate(10);
+ * rectMode(CENTER);
+ * }
+ *
+ * function draw() {
+ * var step = frameCount % 20;
+ * var angle = map(step, 0, 20, -PI / 4, PI / 4);
+ * background(200);
+ * translate(50, 50);
+ * // equivalent to shearX(angle);
+ * var shear_factor = 1 / tan(PI / 2 - angle);
+ * applyMatrix(1, 0, shear_factor, 1, 0, 0);
+ * rect(0, 0, 50, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * A rectangle translating to the right
+ * A rectangle shrinking to the center
+ * A rectangle rotating clockwise about the center
+ * A rectangle shearing
+ *
+ */
+p5.prototype.applyMatrix = function(a, b, c, d, e, f) {
+ this._renderer.applyMatrix(a, b, c, d, e, f);
+ return this;
+};
+
+p5.prototype.popMatrix = function() {
+ throw new Error('popMatrix() not used, see pop()');
+};
+
+p5.prototype.printMatrix = function() {
+ throw new Error('printMatrix() not implemented');
+};
+
+p5.prototype.pushMatrix = function() {
+ throw new Error('pushMatrix() not used, see push()');
+};
+
+/**
+ * Replaces the current matrix with the identity matrix.
+ *
+ * @method resetMatrix
+ * @chainable
+ * @example
+ *
+ *
+ * translate(50, 50);
+ * applyMatrix(0.5, 0.5, -0.5, 0.5, 0, 0);
+ * rect(0, 0, 20, 20);
+ * // Note that the translate is also reset.
+ * resetMatrix();
+ * rect(0, 0, 20, 20);
+ *
+ *
+ *
+ * @alt
+ * A rotated retangle in the center with another at the top left corner
+ *
+ */
+p5.prototype.resetMatrix = function() {
+ this._renderer.resetMatrix();
+ return this;
+};
+
+/**
+ * Rotates a shape the amount specified by the angle parameter. This
+ * function accounts for angleMode, so angles can be entered in either
+ * RADIANS or DEGREES.
+ *
+ * Objects are always rotated around their relative position to the
+ * origin and positive numbers rotate objects in a clockwise direction.
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulates the effect. For example, calling
+ * rotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI).
+ * All tranformations are reset when draw() begins again.
+ *
+ * Technically, rotate() multiplies the current transformation matrix
+ * by a rotation matrix. This function can be further controlled by
+ * the push() and pop().
+ *
+ * @method rotate
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @param {p5.Vector|Number[]} [axis] (in 3d) the axis to rotate around
+ * @chainable
+ * @example
+ *
+ *
+ * translate(width / 2, height / 2);
+ * rotate(PI / 3.0);
+ * rect(-26, -26, 52, 52);
+ *
+ *
+ *
+ * @alt
+ * white 52x52 rect with black outline at center rotated counter 45 degrees
+ *
+ */
+p5.prototype.rotate = function(angle, axis) {
+ p5._validateParameters('rotate', arguments);
+ this._renderer.rotate(this._toRadians(angle), axis);
+ return this;
+};
+
+/**
+ * Rotates around X axis.
+ * @method rotateX
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(255);
+ * rotateX(millis() / 1000);
+ * box();
+ * }
+ *
+ *
+ *
+ * @alt
+ * 3d box rotating around the x axis.
+ */
+p5.prototype.rotateX = function(angle) {
+ this._assert3d('rotateX');
+ p5._validateParameters('rotateX', arguments);
+ this._renderer.rotateX(this._toRadians(angle));
+ return this;
+};
+
+/**
+ * Rotates around Y axis.
+ * @method rotateY
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(255);
+ * rotateY(millis() / 1000);
+ * box();
+ * }
+ *
+ *
+ *
+ * @alt
+ * 3d box rotating around the y axis.
+ */
+p5.prototype.rotateY = function(angle) {
+ this._assert3d('rotateY');
+ p5._validateParameters('rotateY', arguments);
+ this._renderer.rotateY(this._toRadians(angle));
+ return this;
+};
+
+/**
+ * Rotates around Z axis. Webgl mode only.
+ * @method rotateZ
+ * @param {Number} angle the angle of rotation, specified in radians
+ * or degrees, depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ * function draw() {
+ * background(255);
+ * rotateZ(millis() / 1000);
+ * box();
+ * }
+ *
+ *
+ *
+ * @alt
+ * 3d box rotating around the z axis.
+ */
+p5.prototype.rotateZ = function(angle) {
+ this._assert3d('rotateZ');
+ p5._validateParameters('rotateZ', arguments);
+ this._renderer.rotateZ(this._toRadians(angle));
+ return this;
+};
+
+/**
+ * Increases or decreases the size of a shape by expanding and contracting
+ * vertices. Objects always scale from their relative origin to the
+ * coordinate system. Scale values are specified as decimal percentages.
+ * For example, the function call scale(2.0) increases the dimension of a
+ * shape by 200%.
+ *
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function multiply the effect. For example, calling scale(2.0)
+ * and then scale(1.5) is the same as scale(3.0). If scale() is called
+ * within draw(), the transformation is reset when the loop begins again.
+ *
+ * Using this function with the z parameter is only available in WEBGL mode.
+ * This function can be further controlled with push() and pop().
+ *
+ * @method scale
+ * @param {Number|p5.Vector|Number[]} s
+ * percent to scale the object, or percentage to
+ * scale the object in the x-axis if multiple arguments
+ * are given
+ * @param {Number} [y] percent to scale the object in the y-axis
+ * @param {Number} [z] percent to scale the object in the z-axis (webgl only)
+ * @chainable
+ * @example
+ *
+ *
+ * translate(width / 2, height / 2);
+ * rotate(PI / 3.0);
+ * rect(-26, -26, 52, 52);
+ *
+ *
+ *
+ *
+ *
+ * rect(30, 20, 50, 50);
+ * scale(0.5, 1.3);
+ * rect(30, 20, 50, 50);
+ *
+ *
+ *
+ * @alt
+ * white 52x52 rect with black outline at center rotated counter 45 degrees
+ * 2 white rects with black outline- 1 50x50 at center. other 25x65 bottom left
+ *
+ */
+/**
+ * @method scale
+ * @param {p5.Vector|Number[]} scales per-axis percents to scale the object
+ * @chainable
+ */
+p5.prototype.scale = function(x, y, z) {
+ p5._validateParameters('scale', arguments);
+ // Only check for Vector argument type if Vector is available
+ if (x instanceof p5.Vector) {
+ var v = x;
+ x = v.x;
+ y = v.y;
+ z = v.z;
+ } else if (x instanceof Array) {
+ var rg = x;
+ x = rg[0];
+ y = rg[1];
+ z = rg[2] || 1;
+ }
+ if (isNaN(y)) {
+ y = z = x;
+ } else if (isNaN(z)) {
+ z = 1;
+ }
+
+ this._renderer.scale.call(this._renderer, x, y, z);
+
+ return this;
+};
+
+/**
+ * Shears a shape around the x-axis the amount specified by the angle
+ * parameter. Angles should be specified in the current angleMode.
+ * Objects are always sheared around their relative position to the origin
+ * and positive numbers shear objects in a clockwise direction.
+ *
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulates the effect. For example, calling
+ * shearX(PI/2) and then shearX(PI/2) is the same as shearX(PI).
+ * If shearX() is called within the draw(), the transformation is reset when
+ * the loop begins again.
+ *
+ * Technically, shearX() multiplies the current transformation matrix by a
+ * rotation matrix. This function can be further controlled by the
+ * push() and pop() functions.
+ *
+ * @method shearX
+ * @param {Number} angle angle of shear specified in radians or degrees,
+ * depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * translate(width / 4, height / 4);
+ * shearX(PI / 4.0);
+ * rect(0, 0, 30, 30);
+ *
+ *
+ *
+ * @alt
+ * white irregular quadrilateral with black outline at top middle.
+ *
+ */
+p5.prototype.shearX = function(angle) {
+ p5._validateParameters('shearX', arguments);
+ this._renderer.shearX(this._toRadians(angle));
+ return this;
+};
+
+/**
+ * Shears a shape around the y-axis the amount specified by the angle
+ * parameter. Angles should be specified in the current angleMode. Objects
+ * are always sheared around their relative position to the origin and
+ * positive numbers shear objects in a clockwise direction.
+ *
+ * Transformations apply to everything that happens after and subsequent
+ * calls to the function accumulates the effect. For example, calling
+ * shearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If
+ * shearY() is called within the draw(), the transformation is reset when
+ * the loop begins again.
+ *
+ * Technically, shearY() multiplies the current transformation matrix by a
+ * rotation matrix. This function can be further controlled by the
+ * push() and pop() functions.
+ *
+ * @method shearY
+ * @param {Number} angle angle of shear specified in radians or degrees,
+ * depending on current angleMode
+ * @chainable
+ * @example
+ *
+ *
+ * translate(width / 4, height / 4);
+ * shearY(PI / 4.0);
+ * rect(0, 0, 30, 30);
+ *
+ *
+ *
+ * @alt
+ * white irregular quadrilateral with black outline at middle bottom.
+ *
+ */
+p5.prototype.shearY = function(angle) {
+ p5._validateParameters('shearY', arguments);
+ this._renderer.shearY(this._toRadians(angle));
+ return this;
+};
+
+/**
+ * Specifies an amount to displace objects within the display window.
+ * The x parameter specifies left/right translation, the y parameter
+ * specifies up/down translation.
+ *
+ * Transformations are cumulative and apply to everything that happens after
+ * and subsequent calls to the function accumulates the effect. For example,
+ * calling translate(50, 0) and then translate(20, 0) is the same as
+ * translate(70, 0). If translate() is called within draw(), the
+ * transformation is reset when the loop begins again. This function can be
+ * further controlled by using push() and pop().
+ *
+ * @method translate
+ * @param {Number} x left/right translation
+ * @param {Number} y up/down translation
+ * @param {Number} [z] forward/backward translation (webgl only)
+ * @chainable
+ * @example
+ *
+ *
+ * translate(30, 20);
+ * rect(0, 0, 55, 55);
+ *
+ *
+ *
+ *
+ *
+ * rect(0, 0, 55, 55); // Draw rect at original 0,0
+ * translate(30, 20);
+ * rect(0, 0, 55, 55); // Draw rect at new 0,0
+ * translate(14, 14);
+ * rect(0, 0, 55, 55); // Draw rect at new 0,0
+ *
+ *
+ *
+
+ *
+ *
+ * function draw() {
+ * background(200);
+ * rectMode(CENTER);
+ * translate(width / 2, height / 2);
+ * translate(p5.Vector.fromAngle(millis() / 1000, 40));
+ * rect(0, 0, 20, 20);
+ * }
+ *
+ *
+ *
+ * @alt
+ * white 55x55 rect with black outline at center right.
+ * 3 white 55x55 rects with black outlines at top-l, center-r and bottom-r.
+ * a 20x20 white rect moving in a circle around the canvas
+ *
+ */
+/**
+ * @method translate
+ * @param {p5.Vector} vector the vector to translate by
+ * @chainable
+ */
+p5.prototype.translate = function(x, y, z) {
+ p5._validateParameters('translate', arguments);
+ if (this._renderer.isP3D) {
+ this._renderer.translate(x, y, z);
+ } else {
+ this._renderer.translate(x, y);
+ }
+ return this;
+};
+
+module.exports = p5;
+
+},{"./core":22}],35:[function(_dereq_,module,exports){
+/**
+ * @module Shape
+ * @submodule Vertex
+ * @for p5
+ * @requires core
+ * @requires constants
+ */
+
+'use strict';
+
+var p5 = _dereq_('./core');
+var constants = _dereq_('./constants');
+var shapeKind = null;
+var vertices = [];
+var contourVertices = [];
+var isBezier = false;
+var isCurve = false;
+var isQuadratic = false;
+var isContour = false;
+var isFirstContour = true;
+
+/**
+ * Use the beginContour() and endContour() functions to create negative
+ * shapes within shapes such as the center of the letter 'O'. beginContour()
+ * begins recording vertices for the shape and endContour() stops recording.
+ * The vertices that define a negative shape must "wind" in the opposite
+ * direction from the exterior shape. First draw vertices for the exterior
+ * clockwise order, then for internal shapes, draw vertices
+ * shape in counter-clockwise.
+ *
+ * These functions can only be used within a beginShape()/endShape() pair and
+ * transformations such as translate(), rotate(), and scale() do not work
+ * within a beginContour()/endContour() pair. It is also not possible to use
+ * other shapes, such as ellipse() or rect() within.
+ *
+ * @method beginContour
+ * @chainable
+ * @example
+ *
+ *
+ * translate(50, 50);
+ * stroke(255, 0, 0);
+ * beginShape();
+ * // Exterior part of shape, clockwise winding
+ * vertex(-40, -40);
+ * vertex(40, -40);
+ * vertex(40, 40);
+ * vertex(-40, 40);
+ * // Interior part of shape, counter-clockwise winding
+ * beginContour();
+ * vertex(-20, -20);
+ * vertex(-20, 20);
+ * vertex(20, 20);
+ * vertex(20, -20);
+ * endContour();
+ * endShape(CLOSE);
+ *
+ *
+ *
+ * @alt
+ * white rect and smaller grey rect with red outlines in center of canvas.
+ *
+ */
+p5.prototype.beginContour = function() {
+ contourVertices = [];
+ isContour = true;
+ return this;
+};
+
+/**
+ * Using the beginShape() and endShape() functions allow creating more
+ * complex forms. beginShape() begins recording vertices for a shape and
+ * endShape() stops recording. The value of the kind parameter tells it which
+ * types of shapes to create from the provided vertices. With no mode
+ * specified, the shape can be any irregular polygon.
+ *
+ * The parameters available for beginShape() are POINTS, LINES, TRIANGLES,
+ * TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. After calling the
+ * beginShape() function, a series of vertex() commands must follow. To stop
+ * drawing the shape, call endShape(). Each shape will be outlined with the
+ * current stroke color and filled with the fill color.
+ *
+ * Transformations such as translate(), rotate(), and scale() do not work
+ * within beginShape(). It is also not possible to use other shapes, such as
+ * ellipse() or rect() within beginShape().
+ *
+ * @method beginShape
+ * @param {Constant} [kind] either POINTS, LINES, TRIANGLES, TRIANGLE_FAN
+ * TRIANGLE_STRIP, QUADS, or QUAD_STRIP
+ * @chainable
+ * @example
+ *
+ *
+ * beginShape();
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape(CLOSE);
+ *
+ *
+ *
+ *
+ *
+ * beginShape(POINTS);
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * beginShape(LINES);
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * noFill();
+ * beginShape();
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * noFill();
+ * beginShape();
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape(CLOSE);
+ *
+ *
+ *
+ *
+ *
+ * beginShape(TRIANGLES);
+ * vertex(30, 75);
+ * vertex(40, 20);
+ * vertex(50, 75);
+ * vertex(60, 20);
+ * vertex(70, 75);
+ * vertex(80, 20);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * beginShape(TRIANGLE_STRIP);
+ * vertex(30, 75);
+ * vertex(40, 20);
+ * vertex(50, 75);
+ * vertex(60, 20);
+ * vertex(70, 75);
+ * vertex(80, 20);
+ * vertex(90, 75);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * beginShape(TRIANGLE_FAN);
+ * vertex(57.5, 50);
+ * vertex(57.5, 15);
+ * vertex(92, 50);
+ * vertex(57.5, 85);
+ * vertex(22, 50);
+ * vertex(57.5, 15);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * beginShape(QUADS);
+ * vertex(30, 20);
+ * vertex(30, 75);
+ * vertex(50, 75);
+ * vertex(50, 20);
+ * vertex(65, 20);
+ * vertex(65, 75);
+ * vertex(85, 75);
+ * vertex(85, 20);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * beginShape(QUAD_STRIP);
+ * vertex(30, 20);
+ * vertex(30, 75);
+ * vertex(50, 20);
+ * vertex(50, 75);
+ * vertex(65, 20);
+ * vertex(65, 75);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * beginShape();
+ * vertex(20, 20);
+ * vertex(40, 20);
+ * vertex(40, 40);
+ * vertex(60, 40);
+ * vertex(60, 60);
+ * vertex(20, 60);
+ * endShape(CLOSE);
+ *
+ *
+ * @alt
+ * white square-shape with black outline in middle-right of canvas.
+ * 4 black points in a square shape in middle-right of canvas.
+ * 2 horizontal black lines. In the top-right and bottom-right of canvas.
+ * 3 line shape with horizontal on top, vertical in middle and horizontal bottom.
+ * square line shape in middle-right of canvas.
+ * 2 white triangle shapes mid-right canvas. left one pointing up and right down.
+ * 5 horizontal interlocking and alternating white triangles in mid-right canvas.
+ * 4 interlocking white triangles in 45 degree rotated square-shape.
+ * 2 white rectangle shapes in mid-right canvas. Both 20x55.
+ * 3 side-by-side white rectangles center rect is smaller in mid-right canvas.
+ * Thick white l-shape with black outline mid-top-left of canvas.
+ *
+ */
+p5.prototype.beginShape = function(kind) {
+ p5._validateParameters('beginShape', arguments);
+ if (this._renderer.isP3D) {
+ this._renderer.beginShape.apply(this._renderer, arguments);
+ } else {
+ if (
+ kind === constants.POINTS ||
+ kind === constants.LINES ||
+ kind === constants.TRIANGLES ||
+ kind === constants.TRIANGLE_FAN ||
+ kind === constants.TRIANGLE_STRIP ||
+ kind === constants.QUADS ||
+ kind === constants.QUAD_STRIP
+ ) {
+ shapeKind = kind;
+ } else {
+ shapeKind = null;
+ }
+
+ vertices = [];
+ contourVertices = [];
+ }
+ return this;
+};
+
+/**
+ * Specifies vertex coordinates for Bezier curves. Each call to
+ * bezierVertex() defines the position of two control points and
+ * one anchor point of a Bezier curve, adding a new segment to a
+ * line or shape.
+ *
+ * The first time bezierVertex() is used within a
+ * beginShape() call, it must be prefaced with a call to vertex()
+ * to set the first anchor point. This function must be used between
+ * beginShape() and endShape() and only when there is no MODE
+ * parameter specified to beginShape().
+ *
+ * @method bezierVertex
+ * @param {Number} x2 x-coordinate for the first control point
+ * @param {Number} y2 y-coordinate for the first control point
+ * @param {Number} x3 x-coordinate for the second control point
+ * @param {Number} y3 y-coordinate for the second control point
+ * @param {Number} x4 x-coordinate for the anchor point
+ * @param {Number} y4 y-coordinate for the anchor point
+ * @chainable
+ * @example
+ *
+ *
+ * strokeWeight(5);
+ * point(30, 20);
+ * point(80, 20);
+ * point(80, 75);
+ * point(30, 75);
+ *
+ * strokeWeight(1);
+ * noFill();
+ * beginShape();
+ * vertex(30, 20);
+ * bezierVertex(80, 20, 80, 75, 30, 75);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * strokeWeight(5);
+ * point(30, 20);
+ * point(80, 20);
+ * point(80, 75);
+ * point(30, 75);
+ *
+ * stroke(244, 122, 158);
+ * point(50, 80);
+ * point(60, 25);
+ * point(30, 20);
+ *
+ * stroke(0);
+ * strokeWeight(1);
+ * beginShape();
+ * vertex(30, 20);
+ * bezierVertex(80, 20, 80, 75, 30, 75);
+ * bezierVertex(50, 80, 60, 25, 30, 20);
+ * endShape();
+ *
+ *
+ *
+ * @alt
+ * crescent-shaped line in middle of canvas. Points facing left.
+ * white crescent shape in middle of canvas. Points facing left.
+ *
+ */
+p5.prototype.bezierVertex = function(x2, y2, x3, y3, x4, y4) {
+ p5._validateParameters('bezierVertex', arguments);
+ if (vertices.length === 0) {
+ throw 'vertex() must be used once before calling bezierVertex()';
+ } else {
+ isBezier = true;
+ var vert = [];
+ for (var i = 0; i < arguments.length; i++) {
+ vert[i] = arguments[i];
+ }
+ vert.isVert = false;
+ if (isContour) {
+ contourVertices.push(vert);
+ } else {
+ vertices.push(vert);
+ }
+ }
+ return this;
+};
+
+/**
+ * Specifies vertex coordinates for curves. This function may only
+ * be used between beginShape() and endShape() and only when there
+ * is no MODE parameter specified to beginShape().
+ *
+ * The first and last points in a series of curveVertex() lines will be used to
+ * guide the beginning and end of a the curve. A minimum of four
+ * points is required to draw a tiny curve between the second and
+ * third points. Adding a fifth point with curveVertex() will draw
+ * the curve between the second, third, and fourth points. The
+ * curveVertex() function is an implementation of Catmull-Rom
+ * splines.
+ *
+ * @method curveVertex
+ * @param {Number} x x-coordinate of the vertex
+ * @param {Number} y y-coordinate of the vertex
+ * @chainable
+ * @example
+ *
+ *
+ * strokeWeight(5);
+ * point(84, 91);
+ * point(68, 19);
+ * point(21, 17);
+ * point(32, 91);
+ * strokeWeight(1);
+ *
+ * noFill();
+ * beginShape();
+ * curveVertex(84, 91);
+ * curveVertex(84, 91);
+ * curveVertex(68, 19);
+ * curveVertex(21, 17);
+ * curveVertex(32, 91);
+ * curveVertex(32, 91);
+ * endShape();
+ *
+ *
+ *
+ *
+ * @alt
+ * Upside-down u-shape line, mid canvas. left point extends beyond canvas view.
+ *
+ */
+p5.prototype.curveVertex = function(x, y) {
+ p5._validateParameters('curveVertex', arguments);
+ isCurve = true;
+ this.vertex(x, y);
+ return this;
+};
+
+/**
+ * Use the beginContour() and endContour() functions to create negative
+ * shapes within shapes such as the center of the letter 'O'. beginContour()
+ * begins recording vertices for the shape and endContour() stops recording.
+ * The vertices that define a negative shape must "wind" in the opposite
+ * direction from the exterior shape. First draw vertices for the exterior
+ * clockwise order, then for internal shapes, draw vertices
+ * shape in counter-clockwise.
+ *
+ * These functions can only be used within a beginShape()/endShape() pair and
+ * transformations such as translate(), rotate(), and scale() do not work
+ * within a beginContour()/endContour() pair. It is also not possible to use
+ * other shapes, such as ellipse() or rect() within.
+ *
+ * @method endContour
+ * @chainable
+ * @example
+ *
+ *
+ * translate(50, 50);
+ * stroke(255, 0, 0);
+ * beginShape();
+ * // Exterior part of shape, clockwise winding
+ * vertex(-40, -40);
+ * vertex(40, -40);
+ * vertex(40, 40);
+ * vertex(-40, 40);
+ * // Interior part of shape, counter-clockwise winding
+ * beginContour();
+ * vertex(-20, -20);
+ * vertex(-20, 20);
+ * vertex(20, 20);
+ * vertex(20, -20);
+ * endContour();
+ * endShape(CLOSE);
+ *
+ *
+ *
+ * @alt
+ * white rect and smaller grey rect with red outlines in center of canvas.
+ *
+ */
+p5.prototype.endContour = function() {
+ var vert = contourVertices[0].slice(); // copy all data
+ vert.isVert = contourVertices[0].isVert;
+ vert.moveTo = false;
+ contourVertices.push(vert);
+
+ // prevent stray lines with multiple contours
+ if (isFirstContour) {
+ vertices.push(vertices[0]);
+ isFirstContour = false;
+ }
+
+ for (var i = 0; i < contourVertices.length; i++) {
+ vertices.push(contourVertices[i]);
+ }
+ return this;
+};
+
+/**
+ * The endShape() function is the companion to beginShape() and may only be
+ * called after beginShape(). When endshape() is called, all of image data
+ * defined since the previous call to beginShape() is written into the image
+ * buffer. The constant CLOSE as the value for the MODE parameter to close
+ * the shape (to connect the beginning and the end).
+ *
+ * @method endShape
+ * @param {Constant} [mode] use CLOSE to close the shape
+ * @chainable
+ * @example
+ *
+ *
+ * noFill();
+ *
+ * beginShape();
+ * vertex(20, 20);
+ * vertex(45, 20);
+ * vertex(45, 80);
+ * endShape(CLOSE);
+ *
+ * beginShape();
+ * vertex(50, 20);
+ * vertex(75, 20);
+ * vertex(75, 80);
+ * endShape();
+ *
+ *
+ *
+ * @alt
+ * Triangle line shape with smallest interior angle on bottom and upside-down L.
+ *
+ */
+p5.prototype.endShape = function(mode) {
+ p5._validateParameters('endShape', arguments);
+ if (this._renderer.isP3D) {
+ this._renderer.endShape(
+ mode,
+ isCurve,
+ isBezier,
+ isQuadratic,
+ isContour,
+ shapeKind
+ );
+ } else {
+ if (vertices.length === 0) {
+ return this;
+ }
+ if (!this._renderer._doStroke && !this._renderer._doFill) {
+ return this;
+ }
+
+ var closeShape = mode === constants.CLOSE;
+
+ // if the shape is closed, the first element is also the last element
+ if (closeShape && !isContour) {
+ vertices.push(vertices[0]);
+ }
+
+ this._renderer.endShape(
+ mode,
+ vertices,
+ isCurve,
+ isBezier,
+ isQuadratic,
+ isContour,
+ shapeKind
+ );
+
+ // Reset some settings
+ isCurve = false;
+ isBezier = false;
+ isQuadratic = false;
+ isContour = false;
+ isFirstContour = true;
+
+ // If the shape is closed, the first element was added as last element.
+ // We must remove it again to prevent the list of vertices from growing
+ // over successive calls to endShape(CLOSE)
+ if (closeShape) {
+ vertices.pop();
+ }
+ }
+ return this;
+};
+
+/**
+ * Specifies vertex coordinates for quadratic Bezier curves. Each call to
+ * quadraticVertex() defines the position of one control points and one
+ * anchor point of a Bezier curve, adding a new segment to a line or shape.
+ * The first time quadraticVertex() is used within a beginShape() call, it
+ * must be prefaced with a call to vertex() to set the first anchor point.
+ * This function must be used between beginShape() and endShape() and only
+ * when there is no MODE parameter specified to beginShape().
+ *
+ * @method quadraticVertex
+ * @param {Number} cx x-coordinate for the control point
+ * @param {Number} cy y-coordinate for the control point
+ * @param {Number} x3 x-coordinate for the anchor point
+ * @param {Number} y3 y-coordinate for the anchor point
+ * @chainable
+ * @example
+ *
+ *
+ * strokeWeight(5);
+ * point(20, 20);
+ * point(80, 20);
+ * point(50, 50);
+ *
+ * noFill();
+ * strokeWeight(1);
+ * beginShape();
+ * vertex(20, 20);
+ * quadraticVertex(80, 20, 50, 50);
+ * endShape();
+ *
+ *
+ *
+ *
+ *
+ * strokeWeight(5);
+ * point(20, 20);
+ * point(80, 20);
+ * point(50, 50);
+ *
+ * point(20, 80);
+ * point(80, 80);
+ * point(80, 60);
+ *
+ * noFill();
+ * strokeWeight(1);
+ * beginShape();
+ * vertex(20, 20);
+ * quadraticVertex(80, 20, 50, 50);
+ * quadraticVertex(20, 80, 80, 80);
+ * vertex(80, 60);
+ * endShape();
+ *
+ *
+ *
+ * @alt
+ * arched-shaped black line with 4 pixel thick stroke weight.
+ * backwards s-shaped black line with 4 pixel thick stroke weight.
+ *
+ */
+p5.prototype.quadraticVertex = function(cx, cy, x3, y3) {
+ p5._validateParameters('quadraticVertex', arguments);
+ //if we're drawing a contour, put the points into an
+ // array for inside drawing
+ if (this._contourInited) {
+ var pt = {};
+ pt.x = cx;
+ pt.y = cy;
+ pt.x3 = x3;
+ pt.y3 = y3;
+ pt.type = constants.QUADRATIC;
+ this._contourVertices.push(pt);
+
+ return this;
+ }
+ if (vertices.length > 0) {
+ isQuadratic = true;
+ var vert = [];
+ for (var i = 0; i < arguments.length; i++) {
+ vert[i] = arguments[i];
+ }
+ vert.isVert = false;
+ if (isContour) {
+ contourVertices.push(vert);
+ } else {
+ vertices.push(vert);
+ }
+ } else {
+ throw 'vertex() must be used once before calling quadraticVertex()';
+ }
+ return this;
+};
+
+/**
+ * All shapes are constructed by connecting a series of vertices. vertex()
+ * is used to specify the vertex coordinates for points, lines, triangles,
+ * quads, and polygons. It is used exclusively within the beginShape() and
+ * endShape() functions.
+ *
+ * @method vertex
+ * @param {Number} x x-coordinate of the vertex
+ * @param {Number} y y-coordinate of the vertex
+ * @chainable
+ * @example
+ *
+ *
+ * strokeWeight(3);
+ * beginShape(POINTS);
+ * vertex(30, 20);
+ * vertex(85, 20);
+ * vertex(85, 75);
+ * vertex(30, 75);
+ * endShape();
+ *
+ *
+ *
+ * @alt
+ * 4 black points in a square shape in middle-right of canvas.
+ *
+ *
+ *
+ * createCanvas(100, 100, WEBGL);
+ * background(240, 240, 240);
+ * fill(237, 34, 93);
+ * noStroke();
+ * beginShape();
+ * vertex(0, 35);
+ * vertex(35, 0);
+ * vertex(0, -35);
+ * vertex(-35, 0);
+ * endShape();
+ *
+ *
+ *
+ * @alt
+ * 4 points making a diamond shape
+ *
+ *
+ *
+ * createCanvas(100, 100, WEBGL);
+ * background(240, 240, 240);
+ * fill(237, 34, 93);
+ * noStroke();
+ * beginShape();
+ * vertex(-10, 10);
+ * vertex(0, 35);
+ * vertex(10, 10);
+ * vertex(35, 0);
+ * vertex(10, -8);
+ * vertex(0, -35);
+ * vertex(-10, -8);
+ * vertex(-35, 0);
+ * endShape();
+ *
+ *
+ *
+ * @alt
+ * 8 points making a star
+ *
+ *
+ *
+ * strokeWeight(3);
+ * stroke(237, 34, 93);
+ * beginShape(LINES);
+ * vertex(10, 35);
+ * vertex(90, 35);
+ * vertex(10, 65);
+ * vertex(90, 65);
+ * vertex(35, 10);
+ * vertex(35, 90);
+ * vertex(65, 10);
+ * vertex(65, 90);
+ * endShape();
+ *
+ *
+ *
+ * @alt
+ * 8 points making 4 lines
+ *
+ */
+/**
+ * @method vertex
+ * @param {Number} x
+ * @param {Number} y
+ * @param {Number} [z] z-coordinate of the vertex
+ * @param {Number} [u] the vertex's texture u-coordinate
+ * @param {Number} [v] the vertex's texture v-coordinate
+ */
+p5.prototype.vertex = function(x, y, moveTo, u, v) {
+ if (this._renderer.isP3D) {
+ this._renderer.vertex.apply(this._renderer, arguments);
+ } else {
+ var vert = [];
+ vert.isVert = true;
+ vert[0] = x;
+ vert[1] = y;
+ vert[2] = 0;
+ vert[3] = 0;
+ vert[4] = 0;
+ vert[5] = this._renderer._getFill();
+ vert[6] = this._renderer._getStroke();
+
+ if (moveTo) {
+ vert.moveTo = moveTo;
+ }
+ if (isContour) {
+ if (contourVertices.length === 0) {
+ vert.moveTo = true;
+ }
+ contourVertices.push(vert);
+ } else {
+ vertices.push(vert);
+ }
+ }
+ return this;
+};
+
+module.exports = p5;
+
+},{"./constants":21,"./core":22}],36:[function(_dereq_,module,exports){
+/**
+ * @module Data
+ * @submodule Dictionary
+ * @for p5.TypedDict
+ * @requires core
+ *
+ * This module defines the p5 methods for the p5 Dictionary classes
+ * these classes StringDict and NumberDict are for storing and working
+ * with key, value pairs
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+/**
+ *
+ * Creates a new instance of p5.StringDict using the key, value pair
+ * or object you provide.
+ *
+ * @method createStringDict
+ * @for p5
+ * @param {String} key
+ * @param {String} value
+ * @return {p5.StringDict}
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createStringDict('p5', 'js');
+ * print(myDictionary.hasKey('p5')); // logs true to console
+ * }
+ *
+ */
+/**
+ * @method createStringDict
+ * @param {Object} object object
+ * @return {p5.StringDict}
+ */
+
+p5.prototype.createStringDict = function(key, value) {
+ p5._validateParameters('createStringDict', arguments);
+ return new p5.StringDict(key, value);
+};
+
+/**
+ *
+ * Creates a new instance of p5.NumberDict using the key, value pair
+ * or object you provide.
+ *
+ * @method createNumberDict
+ * @for p5
+ * @param {Number} key
+ * @param {Number} value
+ * @return {p5.NumberDict}
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createNumberDict(100, 42);
+ * print(myDictionary.hasKey(100)); // logs true to console
+ * }
+ *
+ */
+/**
+ * @method createNumberDict
+ * @param {Object} object object
+ * @return {p5.NumberDict}
+ */
+
+p5.prototype.createNumberDict = function(key, value) {
+ p5._validateParameters('createNumberDict', arguments);
+ return new p5.NumberDict(key, value);
+};
+
+/**
+ *
+ * Base class for all p5.Dictionary types. More specifically
+ * typed Dictionary objects inherit from this
+ *
+ * @class p5.TypedDict
+ *
+ */
+
+p5.TypedDict = function(key, value) {
+ if (key instanceof Object) {
+ this.data = key;
+ } else {
+ this.data = {};
+ this.data[key] = value;
+ }
+ return this;
+};
+
+/**
+ * Returns the number of key-value pairs currently in Dictionary object
+ *
+ * @method size
+ * @return {Integer} the number of key-value pairs in Dictionary object
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createNumberDict(1, 10);
+ * myDictionary.create(2, 20);
+ * myDictionary.create(3, 30);
+ * print(myDictionary.size()); // value of amt is 3
+ * }
+ *
+ *
+ */
+p5.TypedDict.prototype.size = function() {
+ return Object.keys(this.data).length;
+};
+
+/**
+ * Returns true if key exists in Dictionary
+ * otherwise returns false
+ *
+ * @method hasKey
+ * @param {Number|String} key that you want to access
+ * @return {Boolean} whether that key exists in Dictionary
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createStringDict('p5', 'js');
+ * print(myDictionary.hasKey('p5')); // logs true to console
+ * }
+ *
+ *
+ */
+
+p5.TypedDict.prototype.hasKey = function(key) {
+ return this.data.hasOwnProperty(key);
+};
+
+/**
+ * Returns value stored at supplied key.
+ *
+ * @method get
+ * @param {Number|String} key that you want to access
+ * @return {Number|String} the value stored at that key
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createStringDict('p5', 'js');
+ * var myValue = myDictionary.get('p5');
+ * print(myValue === 'js'); // logs true to console
+ * }
+ *
+ *
+ */
+
+p5.TypedDict.prototype.get = function(key) {
+ if (this.data.hasOwnProperty(key)) {
+ return this.data[key];
+ } else {
+ console.log(key + ' does not exist in this Dictionary');
+ }
+};
+
+/**
+ * Changes the value of key if in it already exists in
+ * in the Dictionary otherwise makes a new key-value pair
+ *
+ * @method set
+ * @param {Number|String} key
+ * @param {Number|String} value
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createStringDict('p5', 'js');
+ * myDictionary.set('p5', 'JS');
+ * myDictionary.print();
+ * // above logs "key: p5 - value: JS" to console
+ * }
+ *
+ *
+ */
+
+p5.TypedDict.prototype.set = function(key, value) {
+ if (this._validate(value)) {
+ this.data[key] = value;
+ } else {
+ console.log('Those values dont work for this dictionary type.');
+ }
+};
+
+/**
+ * private helper function to handle the user passing objects in
+ * during construction or calls to create()
+ */
+
+p5.TypedDict.prototype._addObj = function(obj) {
+ for (var key in obj) {
+ this.set(key, obj[key]);
+ }
+};
+
+/**
+ * Creates a key-value pair in the Dictionary
+ *
+ * @method create
+ * @param {Number|String} key
+ * @param {Number|String} value
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createStringDict('p5', 'js');
+ * myDictionary.create('happy', 'coding');
+ * myDictionary.print();
+ * // above logs "key: p5 - value: js, key: happy - value: coding" to console
+ * }
+ *
+ */
+/**
+ * @method create
+ * @param {Object} obj key/value pair
+ */
+
+p5.TypedDict.prototype.create = function(key, value) {
+ if (key instanceof Object && typeof value === 'undefined') {
+ this._addObj(key);
+ } else if (typeof key !== 'undefined') {
+ this.set(key, value);
+ } else {
+ console.log(
+ 'In order to create a new Dictionary entry you must pass ' +
+ 'an object or a key, value pair'
+ );
+ }
+};
+
+/**
+ * Empties Dictionary of all key-value pairs
+ * @method clear
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createStringDict('p5', 'js');
+ * print(myDictionary.hasKey('p5')); // prints 'true'
+ * myDictionary.clear();
+ * print(myDictionary.hasKey('p5')); // prints 'false'
+ * }
+ *
+ *
+ */
+
+p5.TypedDict.prototype.clear = function() {
+ this.data = {};
+};
+
+/**
+ * Removes a key-value pair in the Dictionary
+ *
+ * @method remove
+ * @param {Number|String} key for the pair to remove
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createStringDict('p5', 'js');
+ * myDictionary.create('happy', 'coding');
+ * myDictionary.print();
+ * // above logs "key: p5 - value: js, key: happy - value: coding" to console
+ * myDictionary.remove('p5');
+ * myDictionary.print();
+ * // above logs "key: happy value: coding" to console
+ * }
+ *
+ *
+ */
+
+p5.TypedDict.prototype.remove = function(key) {
+ if (this.data.hasOwnProperty(key)) {
+ delete this.data[key];
+ } else {
+ throw key + ' does not exist in this Dictionary';
+ }
+};
+
+/**
+ * Logs the list of items currently in the Dictionary to the console
+ *
+ * @method print
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createStringDict('p5', 'js');
+ * myDictionary.create('happy', 'coding');
+ * myDictionary.print();
+ * // above logs "key: p5 - value: js, key: happy - value: coding" to console
+ * }
+ *
+ *
+ */
+
+p5.TypedDict.prototype.print = function() {
+ for (var item in this.data) {
+ console.log('key:' + item + ' value:' + this.data[item]);
+ }
+};
+
+/**
+ * Converts the Dictionary into a CSV file for local
+ * storage.
+ *
+ * @method saveTable
+ * @example
+ *
+ *
+ * createButton('save')
+ * .position(10, 10)
+ * .mousePressed(function() {
+ * createStringDict({
+ * john: 1940,
+ paul: 1942,
+ george: 1943,
+ ringo: 1940
+ * }).saveTable('beatles');
+ * });
+ *
+ *
+ */
+
+p5.TypedDict.prototype.saveTable = function(filename) {
+ var output = '';
+
+ for (var key in this.data) {
+ output += key + ',' + this.data[key] + '\n';
+ }
+
+ var blob = new Blob([output], { type: 'text/csv' });
+ p5.prototype.downloadFile(blob, filename || 'mycsv', 'csv');
+};
+
+/**
+ * Converts the Dictionary into a JSON file for local
+ * storage.
+ *
+ * @method saveJSON
+ * @example
+ *
+ *
+ * createButton('save')
+ * .position(10, 10)
+ * .mousePressed(function() {
+ * createStringDict({
+ * john: 1940,
+ paul: 1942,
+ george: 1943,
+ ringo: 1940
+ * }).saveJSON('beatles');
+ * });
+ *
+ *
+ */
+
+p5.TypedDict.prototype.saveJSON = function(filename, opt) {
+ p5.prototype.saveJSON(this.data, filename, opt);
+};
+
+/**
+ * private helper function to ensure that the user passed in valid
+ * values for the Dictionary type
+ */
+
+p5.TypedDict.prototype._validate = function(value) {
+ return true;
+};
+
+/**
+ *
+ * A Dictionary class for Strings.
+ *
+ *
+ * @class p5.StringDict
+ * @extends p5.TypedDict
+ *
+ */
+
+p5.StringDict = function() {
+ p5.TypedDict.apply(this, arguments);
+};
+
+p5.StringDict.prototype = Object.create(p5.TypedDict.prototype);
+
+p5.StringDict.prototype._validate = function(value) {
+ return typeof value === 'string';
+};
+
+/**
+ *
+ * A simple Dictionary class for Numbers.
+ *
+ *
+ * @class p5.NumberDict
+ * @extends p5.TypedDict
+ *
+ */
+
+p5.NumberDict = function() {
+ p5.TypedDict.apply(this, arguments);
+};
+
+p5.NumberDict.prototype = Object.create(p5.TypedDict.prototype);
+
+/**
+ * private helper function to ensure that the user passed in valid
+ * values for the Dictionary type
+ */
+
+p5.NumberDict.prototype._validate = function(value) {
+ return typeof value === 'number';
+};
+
+/**
+ * Add to a value stored at a certain key
+ * The sum is stored in that location in the Dictionary.
+ *
+ * @method add
+ * @param {Number} Key for value you wish to add to
+ * @param {Number} Amount to add to the value
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createNumberDict(2, 5);
+ * myDictionary.add(2, 2);
+ * console.log(myDictionary.get(2)); // logs 7 to console.
+ * }
+ *
+ *
+ *
+ */
+
+p5.NumberDict.prototype.add = function(key, amount) {
+ if (this.data.hasOwnProperty(key)) {
+ this.data[key] += amount;
+ } else {
+ console.log('The key - ' + key + ' does not exist in this dictionary.');
+ }
+};
+
+/**
+ * Subtract from a value stored at a certain key
+ * The difference is stored in that location in the Dictionary.
+ *
+ * @method sub
+ * @param {Number} Key for value you wish to subtract from
+ * @param {Number} Amount to subtract from the value
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createNumberDict(2, 5);
+ * myDictionary.sub(2, 2);
+ * console.log(myDictionary.get(2)); // logs 3 to console.
+ * }
+ *
+ *
+ *
+ */
+
+p5.NumberDict.prototype.sub = function(key, amount) {
+ this.add(key, -amount);
+};
+
+/**
+ * Multiply a value stored at a certain key
+ * The product is stored in that location in the Dictionary.
+ *
+ * @method mult
+ * @param {Number} Key for value you wish to multiply
+ * @param {Number} Amount to multiply the value by
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createNumberDict(2, 4);
+ * myDictionary.mult(2, 2);
+ * console.log(myDictionary.get(2)); // logs 8 to console.
+ * }
+ *
+ *
+ *
+ */
+
+p5.NumberDict.prototype.mult = function(key, amount) {
+ if (this.data.hasOwnProperty(key)) {
+ this.data[key] *= amount;
+ } else {
+ console.log('The key - ' + key + ' does not exist in this dictionary.');
+ }
+};
+
+/**
+ * Divide a value stored at a certain key
+ * The quotient is stored in that location in the Dictionary.
+ *
+ * @method div
+ * @param {Number} Key for value you wish to divide
+ * @param {Number} Amount to divide the value by
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createNumberDict(2, 8);
+ * myDictionary.div(2, 2);
+ * console.log(myDictionary.get(2)); // logs 4 to console.
+ * }
+ *
+ *
+ *
+ */
+
+p5.NumberDict.prototype.div = function(key, amount) {
+ if (this.data.hasOwnProperty(key)) {
+ this.data[key] /= amount;
+ } else {
+ console.log('The key - ' + key + ' does not exist in this dictionary.');
+ }
+};
+
+/**
+ * private helper function for finding lowest or highest value
+ * the argument 'flip' is used to flip the comparison arrow
+ * from 'less than' to 'greater than'
+ *
+ */
+
+p5.NumberDict.prototype._valueTest = function(flip) {
+ if (Object.keys(this.data).length === 0) {
+ throw 'Unable to search for a minimum or maximum value on an empty NumberDict';
+ } else if (Object.keys(this.data).length === 1) {
+ return this.data[Object.keys(this.data)[0]];
+ } else {
+ var result = this.data[Object.keys(this.data)[0]];
+ for (var key in this.data) {
+ if (this.data[key] * flip < result * flip) {
+ result = this.data[key];
+ }
+ }
+ return result;
+ }
+};
+
+/**
+ * Return the lowest value.
+ *
+ * @method minValue
+ * @return {Number}
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });
+ * var lowestValue = myDictionary.minValue(); // value is -10
+ * print(lowestValue);
+ * }
+ *
+ *
+ */
+
+p5.NumberDict.prototype.minValue = function() {
+ return this._valueTest(1);
+};
+
+/**
+ * Return the highest value.
+ *
+ * @method maxValue
+ * @return {Number}
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });
+ * var highestValue = myDictionary.maxValue(); // value is 3
+ * print(highestValue);
+ * }
+ *
+ *
+ */
+
+p5.NumberDict.prototype.maxValue = function() {
+ return this._valueTest(-1);
+};
+
+/**
+ * private helper function for finding lowest or highest key
+ * the argument 'flip' is used to flip the comparison arrow
+ * from 'less than' to 'greater than'
+ *
+ */
+
+p5.NumberDict.prototype._keyTest = function(flip) {
+ if (Object.keys(this.data).length === 0) {
+ throw 'Unable to use minValue on an empty NumberDict';
+ } else if (Object.keys(this.data).length === 1) {
+ return Object.keys(this.data)[0];
+ } else {
+ var result = Object.keys(this.data)[0];
+ for (var i = 1; i < Object.keys(this.data).length; i++) {
+ if (Object.keys(this.data)[i] * flip < result * flip) {
+ result = Object.keys(this.data)[i];
+ }
+ }
+ return result;
+ }
+};
+
+/**
+ * Return the lowest key.
+ *
+ * @method minKey
+ * @return {Number}
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });
+ * var lowestKey = myDictionary.minKey(); // value is 1.2
+ * print(lowestKey);
+ * }
+ *
+ *
+ */
+
+p5.NumberDict.prototype.minKey = function() {
+ return this._keyTest(1);
+};
+
+/**
+ * Return the highest key.
+ *
+ * @method maxKey
+ * @return {Number}
+ * @example
+ *
+ *
+ * function setup() {
+ * var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });
+ * var highestKey = myDictionary.maxKey(); // value is 4
+ * print(highestKey);
+ * }
+ *
+ *
+ */
+
+p5.NumberDict.prototype.maxKey = function() {
+ return this._keyTest(-1);
+};
+
+module.exports = p5.TypedDict;
+
+},{"../core/core":22}],37:[function(_dereq_,module,exports){
+/**
+ * @module Events
+ * @submodule Acceleration
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+/**
+ * The system variable deviceOrientation always contains the orientation of
+ * the device. The value of this variable will either be set 'landscape'
+ * or 'portrait'. If no data is available it will be set to 'undefined'.
+ * either LANDSCAPE or PORTRAIT.
+ *
+ * @property {Constant} deviceOrientation
+ * @readOnly
+ */
+p5.prototype.deviceOrientation = undefined;
+
+/**
+ * The system variable accelerationX always contains the acceleration of the
+ * device along the x axis. Value is represented as meters per second squared.
+ *
+ * @property {Number} accelerationX
+ * @readOnly
+ */
+p5.prototype.accelerationX = 0;
+
+/**
+ * The system variable accelerationY always contains the acceleration of the
+ * device along the y axis. Value is represented as meters per second squared.
+ *
+ * @property {Number} accelerationY
+ * @readOnly
+ */
+p5.prototype.accelerationY = 0;
+
+/**
+ * The system variable accelerationZ always contains the acceleration of the
+ * device along the z axis. Value is represented as meters per second squared.
+ *
+ * @property {Number} accelerationZ
+ * @readOnly
+ */
+p5.prototype.accelerationZ = 0;
+
+/**
+ * The system variable pAccelerationX always contains the acceleration of the
+ * device along the x axis in the frame previous to the current frame. Value
+ * is represented as meters per second squared.
+ *
+ * @property {Number} pAccelerationX
+ * @readOnly
+ */
+p5.prototype.pAccelerationX = 0;
+
+/**
+ * The system variable pAccelerationY always contains the acceleration of the
+ * device along the y axis in the frame previous to the current frame. Value
+ * is represented as meters per second squared.
+ *
+ * @property {Number} pAccelerationY
+ * @readOnly
+ */
+p5.prototype.pAccelerationY = 0;
+
+/**
+ * The system variable pAccelerationZ always contains the acceleration of the
+ * device along the z axis in the frame previous to the current frame. Value
+ * is represented as meters per second squared.
+ *
+ * @property {Number} pAccelerationZ
+ * @readOnly
+ */
+p5.prototype.pAccelerationZ = 0;
+
+/**
+ * _updatePAccelerations updates the pAcceleration values
+ *
+ * @private
+ */
+p5.prototype._updatePAccelerations = function() {
+ this._setProperty('pAccelerationX', this.accelerationX);
+ this._setProperty('pAccelerationY', this.accelerationY);
+ this._setProperty('pAccelerationZ', this.accelerationZ);
+};
+
+/**
+ * The system variable rotationX always contains the rotation of the
+ * device along the x axis. Value is represented as 0 to +/-180 degrees.
+ *
+ * Note: The order the rotations are called is important, ie. if used
+ * together, it must be called in the order Z-X-Y or there might be
+ * unexpected behaviour.
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * //rotateZ(radians(rotationZ));
+ * rotateX(radians(rotationX));
+ * //rotateY(radians(rotationY));
+ * box(200, 200, 200);
+ * }
+ *
+ *
+ *
+ * @property {Number} rotationX
+ * @readOnly
+ *
+ * @alt
+ * red horizontal line right, green vertical line bottom. black background.
+ *
+ */
+p5.prototype.rotationX = 0;
+
+/**
+ * The system variable rotationY always contains the rotation of the
+ * device along the y axis. Value is represented as 0 to +/-90 degrees.
+ *
+ * Note: The order the rotations are called is important, ie. if used
+ * together, it must be called in the order Z-X-Y or there might be
+ * unexpected behaviour.
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * //rotateZ(radians(rotationZ));
+ * //rotateX(radians(rotationX));
+ * rotateY(radians(rotationY));
+ * box(200, 200, 200);
+ * }
+ *
+ *
+ *
+ * @property {Number} rotationY
+ * @readOnly
+ *
+ * @alt
+ * red horizontal line right, green vertical line bottom. black background.
+ */
+p5.prototype.rotationY = 0;
+
+/**
+ * The system variable rotationZ always contains the rotation of the
+ * device along the z axis. Value is represented as 0 to 359 degrees.
+ *
+ * Unlike rotationX and rotationY, this variable is available for devices
+ * with a built-in compass only.
+ *
+ * Note: The order the rotations are called is important, ie. if used
+ * together, it must be called in the order Z-X-Y or there might be
+ * unexpected behaviour.
+ *
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * rotateZ(radians(rotationZ));
+ * //rotateX(radians(rotationX));
+ * //rotateY(radians(rotationY));
+ * box(200, 200, 200);
+ * }
+ *
+ *
+ *
+ * @property {Number} rotationZ
+ * @readOnly
+ *
+ * @alt
+ * red horizontal line right, green vertical line bottom. black background.
+ */
+p5.prototype.rotationZ = 0;
+
+/**
+ * The system variable pRotationX always contains the rotation of the
+ * device along the x axis in the frame previous to the current frame. Value
+ * is represented as 0 to +/-180 degrees.
+ *
+ * pRotationX can also be used with rotationX to determine the rotate
+ * direction of the device along the X-axis.
+ * @example
+ *
+ *
+ * // A simple if statement looking at whether
+ * // rotationX - pRotationX < 0 is true or not will be
+ * // sufficient for determining the rotate direction
+ * // in most cases.
+ *
+ * // Some extra logic is needed to account for cases where
+ * // the angles wrap around.
+ * var rotateDirection = 'clockwise';
+ *
+ * // Simple range conversion to make things simpler.
+ * // This is not absolutely necessary but the logic
+ * // will be different in that case.
+ *
+ * var rX = rotationX + 180;
+ * var pRX = pRotationX + 180;
+ *
+ * if ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {
+ * rotateDirection = 'clockwise';
+ * } else if (rX - pRX < 0 || rX - pRX > 270) {
+ * rotateDirection = 'counter-clockwise';
+ * }
+ *
+ * print(rotateDirection);
+ *
+ *
+ *
+ * @alt
+ * no image to display.
+ *
+ *
+ * @property {Number} pRotationX
+ * @readOnly
+ */
+p5.prototype.pRotationX = 0;
+
+/**
+ * The system variable pRotationY always contains the rotation of the
+ * device along the y axis in the frame previous to the current frame. Value
+ * is represented as 0 to +/-90 degrees.
+ *
+ * pRotationY can also be used with rotationY to determine the rotate
+ * direction of the device along the Y-axis.
+ * @example
+ *
+ *
+ * // A simple if statement looking at whether
+ * // rotationY - pRotationY < 0 is true or not will be
+ * // sufficient for determining the rotate direction
+ * // in most cases.
+ *
+ * // Some extra logic is needed to account for cases where
+ * // the angles wrap around.
+ * var rotateDirection = 'clockwise';
+ *
+ * // Simple range conversion to make things simpler.
+ * // This is not absolutely necessary but the logic
+ * // will be different in that case.
+ *
+ * var rY = rotationY + 180;
+ * var pRY = pRotationY + 180;
+ *
+ * if ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {
+ * rotateDirection = 'clockwise';
+ * } else if (rY - pRY < 0 || rY - pRY > 270) {
+ * rotateDirection = 'counter-clockwise';
+ * }
+ * print(rotateDirection);
+ *
+ *
+ *
+ * @alt
+ * no image to display.
+ *
+ *
+ * @property {Number} pRotationY
+ * @readOnly
+ */
+p5.prototype.pRotationY = 0;
+
+/**
+ * The system variable pRotationZ always contains the rotation of the
+ * device along the z axis in the frame previous to the current frame. Value
+ * is represented as 0 to 359 degrees.
+ *
+ * pRotationZ can also be used with rotationZ to determine the rotate
+ * direction of the device along the Z-axis.
+ * @example
+ *
+ *
+ * // A simple if statement looking at whether
+ * // rotationZ - pRotationZ < 0 is true or not will be
+ * // sufficient for determining the rotate direction
+ * // in most cases.
+ *
+ * // Some extra logic is needed to account for cases where
+ * // the angles wrap around.
+ * var rotateDirection = 'clockwise';
+ *
+ * if (
+ * (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||
+ * rotationZ - pRotationZ < -270
+ * ) {
+ * rotateDirection = 'clockwise';
+ * } else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {
+ * rotateDirection = 'counter-clockwise';
+ * }
+ * print(rotateDirection);
+ *
+ *
+ *
+ * @alt
+ * no image to display.
+ *
+ *
+ * @property {Number} pRotationZ
+ * @readOnly
+ */
+p5.prototype.pRotationZ = 0;
+
+var startAngleX = 0;
+var startAngleY = 0;
+var startAngleZ = 0;
+
+var rotateDirectionX = 'clockwise';
+var rotateDirectionY = 'clockwise';
+var rotateDirectionZ = 'clockwise';
+
+var pRotateDirectionX;
+var pRotateDirectionY;
+var pRotateDirectionZ;
+
+p5.prototype._updatePRotations = function() {
+ this._setProperty('pRotationX', this.rotationX);
+ this._setProperty('pRotationY', this.rotationY);
+ this._setProperty('pRotationZ', this.rotationZ);
+};
+
+/**
+ * @property {String} turnAxis
+ * @readOnly
+ */
+p5.prototype.turnAxis = undefined;
+
+var move_threshold = 0.5;
+var shake_threshold = 30;
+
+/**
+ * The setMoveThreshold() function is used to set the movement threshold for
+ * the deviceMoved() function. The default threshold is set to 0.5.
+ *
+ * @method setMoveThreshold
+ * @param {number} value The threshold value
+ */
+p5.prototype.setMoveThreshold = function(val) {
+ p5._validateParameters('setMoveThreshold', arguments);
+ move_threshold = val;
+};
+
+/**
+ * The setShakeThreshold() function is used to set the movement threshold for
+ * the deviceShaken() function. The default threshold is set to 30.
+ *
+ * @method setShakeThreshold
+ * @param {number} value The threshold value
+ */
+p5.prototype.setShakeThreshold = function(val) {
+ p5._validateParameters('setShakeThreshold', arguments);
+ shake_threshold = val;
+};
+
+/**
+ * The deviceMoved() function is called when the device is moved by more than
+ * the threshold value along X, Y or Z axis. The default threshold is set to
+ * 0.5.
+ * @method deviceMoved
+ * @example
+ *
+ *
+ * // Run this example on a mobile device
+ * // Move the device around
+ * // to change the value.
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceMoved() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device moves
+ *
+ */
+
+/**
+ * The deviceTurned() function is called when the device rotates by
+ * more than 90 degrees continuously.
+ *
+ * The axis that triggers the deviceTurned() method is stored in the turnAxis
+ * variable. The deviceTurned() method can be locked to trigger on any axis:
+ * X, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'.
+ *
+ * @method deviceTurned
+ * @example
+ *
+ *
+ * // Run this example on a mobile device
+ * // Rotate the device by 90 degrees
+ * // to change the value.
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceTurned() {
+ * if (value === 0) {
+ * value = 255;
+ * } else if (value === 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ * // Run this example on a mobile device
+ * // Rotate the device by 90 degrees in the
+ * // X-axis to change the value.
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceTurned() {
+ * if (turnAxis === 'X') {
+ * if (value === 0) {
+ * value = 255;
+ * } else if (value === 255) {
+ * value = 0;
+ * }
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device turns
+ * 50x50 black rect in center of canvas. turns white on mobile when x-axis turns
+ *
+ */
+
+/**
+ * The deviceShaken() function is called when the device total acceleration
+ * changes of accelerationX and accelerationY values is more than
+ * the threshold value. The default threshold is set to 30.
+ * @method deviceShaken
+ * @example
+ *
+ *
+ * // Run this example on a mobile device
+ * // Shake the device to change the value.
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function deviceShaken() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect in center of canvas. turns white on mobile when device shakes
+ *
+ */
+
+p5.prototype._ondeviceorientation = function(e) {
+ this._updatePRotations();
+ this._setProperty('rotationX', e.beta);
+ this._setProperty('rotationY', e.gamma);
+ this._setProperty('rotationZ', e.alpha);
+ this._handleMotion();
+};
+p5.prototype._ondevicemotion = function(e) {
+ this._updatePAccelerations();
+ this._setProperty('accelerationX', e.acceleration.x * 2);
+ this._setProperty('accelerationY', e.acceleration.y * 2);
+ this._setProperty('accelerationZ', e.acceleration.z * 2);
+ this._handleMotion();
+};
+p5.prototype._handleMotion = function() {
+ if (window.orientation === 90 || window.orientation === -90) {
+ this._setProperty('deviceOrientation', 'landscape');
+ } else if (window.orientation === 0) {
+ this._setProperty('deviceOrientation', 'portrait');
+ } else if (window.orientation === undefined) {
+ this._setProperty('deviceOrientation', 'undefined');
+ }
+ var deviceMoved = this.deviceMoved || window.deviceMoved;
+ if (typeof deviceMoved === 'function') {
+ if (
+ Math.abs(this.accelerationX - this.pAccelerationX) > move_threshold ||
+ Math.abs(this.accelerationY - this.pAccelerationY) > move_threshold ||
+ Math.abs(this.accelerationZ - this.pAccelerationZ) > move_threshold
+ ) {
+ deviceMoved();
+ }
+ }
+ var deviceTurned = this.deviceTurned || window.deviceTurned;
+ if (typeof deviceTurned === 'function') {
+ // The angles given by rotationX etc is from range -180 to 180.
+ // The following will convert them to 0 to 360 for ease of calculation
+ // of cases when the angles wrapped around.
+ // _startAngleX will be converted back at the end and updated.
+ var wRX = this.rotationX + 180;
+ var wPRX = this.pRotationX + 180;
+ var wSAX = startAngleX + 180;
+ if ((wRX - wPRX > 0 && wRX - wPRX < 270) || wRX - wPRX < -270) {
+ rotateDirectionX = 'clockwise';
+ } else if (wRX - wPRX < 0 || wRX - wPRX > 270) {
+ rotateDirectionX = 'counter-clockwise';
+ }
+ if (rotateDirectionX !== pRotateDirectionX) {
+ wSAX = wRX;
+ }
+ if (Math.abs(wRX - wSAX) > 90 && Math.abs(wRX - wSAX) < 270) {
+ wSAX = wRX;
+ this._setProperty('turnAxis', 'X');
+ deviceTurned();
+ }
+ pRotateDirectionX = rotateDirectionX;
+ startAngleX = wSAX - 180;
+
+ // Y-axis is identical to X-axis except for changing some names.
+ var wRY = this.rotationY + 180;
+ var wPRY = this.pRotationY + 180;
+ var wSAY = startAngleY + 180;
+ if ((wRY - wPRY > 0 && wRY - wPRY < 270) || wRY - wPRY < -270) {
+ rotateDirectionY = 'clockwise';
+ } else if (wRY - wPRY < 0 || wRY - this.pRotationY > 270) {
+ rotateDirectionY = 'counter-clockwise';
+ }
+ if (rotateDirectionY !== pRotateDirectionY) {
+ wSAY = wRY;
+ }
+ if (Math.abs(wRY - wSAY) > 90 && Math.abs(wRY - wSAY) < 270) {
+ wSAY = wRY;
+ this._setProperty('turnAxis', 'Y');
+ deviceTurned();
+ }
+ pRotateDirectionY = rotateDirectionY;
+ startAngleY = wSAY - 180;
+
+ // Z-axis is already in the range 0 to 360
+ // so no conversion is needed.
+ if (
+ (this.rotationZ - this.pRotationZ > 0 &&
+ this.rotationZ - this.pRotationZ < 270) ||
+ this.rotationZ - this.pRotationZ < -270
+ ) {
+ rotateDirectionZ = 'clockwise';
+ } else if (
+ this.rotationZ - this.pRotationZ < 0 ||
+ this.rotationZ - this.pRotationZ > 270
+ ) {
+ rotateDirectionZ = 'counter-clockwise';
+ }
+ if (rotateDirectionZ !== pRotateDirectionZ) {
+ startAngleZ = this.rotationZ;
+ }
+ if (
+ Math.abs(this.rotationZ - startAngleZ) > 90 &&
+ Math.abs(this.rotationZ - startAngleZ) < 270
+ ) {
+ startAngleZ = this.rotationZ;
+ this._setProperty('turnAxis', 'Z');
+ deviceTurned();
+ }
+ pRotateDirectionZ = rotateDirectionZ;
+ this._setProperty('turnAxis', undefined);
+ }
+ var deviceShaken = this.deviceShaken || window.deviceShaken;
+ if (typeof deviceShaken === 'function') {
+ var accelerationChangeX;
+ var accelerationChangeY;
+ // Add accelerationChangeZ if acceleration change on Z is needed
+ if (this.pAccelerationX !== null) {
+ accelerationChangeX = Math.abs(this.accelerationX - this.pAccelerationX);
+ accelerationChangeY = Math.abs(this.accelerationY - this.pAccelerationY);
+ }
+ if (accelerationChangeX + accelerationChangeY > shake_threshold) {
+ deviceShaken();
+ }
+ }
+};
+
+module.exports = p5;
+
+},{"../core/core":22}],38:[function(_dereq_,module,exports){
+/**
+ * @module Events
+ * @submodule Keyboard
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+/**
+ * Holds the key codes of currently pressed keys.
+ * @private
+ */
+var downKeys = {};
+
+/**
+ * The boolean system variable keyIsPressed is true if any key is pressed
+ * and false if no keys are pressed.
+ *
+ * @property {Boolean} keyIsPressed
+ * @readOnly
+ * @example
+ *
+ *
+ * function draw() {
+ * if (keyIsPressed === true) {
+ * fill(0);
+ * } else {
+ * fill(255);
+ * }
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 white rect that turns black on keypress.
+ *
+ */
+p5.prototype.isKeyPressed = false;
+p5.prototype.keyIsPressed = false; // khan
+
+/**
+ * The system variable key always contains the value of the most recent
+ * key on the keyboard that was typed. To get the proper capitalization, it
+ * is best to use it within keyTyped(). For non-ASCII keys, use the keyCode
+ * variable.
+ *
+ * @property {String} key
+ * @readOnly
+ * @example
+ *
+ * // Click any key to display it!
+ * // (Not Guaranteed to be Case Sensitive)
+ * function setup() {
+ * fill(245, 123, 158);
+ * textSize(50);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * text(key, 33, 65); // Display last key pressed.
+ * }
+ *
+ *
+ * @alt
+ * canvas displays any key value that is pressed in pink font.
+ *
+ */
+p5.prototype.key = '';
+
+/**
+ * The variable keyCode is used to detect special keys such as BACKSPACE,
+ * DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW,
+ * DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.
+ * You can also check for custom keys by looking up the keyCode of any key
+ * on a site like this: keycode.info.
+ *
+ * @property {Integer} keyCode
+ * @readOnly
+ * @example
+ *
+ * var fillVal = 126;
+ * function draw() {
+ * fill(fillVal);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * function keyPressed() {
+ * if (keyCode === UP_ARROW) {
+ * fillVal = 255;
+ * } else if (keyCode === DOWN_ARROW) {
+ * fillVal = 0;
+ * }
+ * return false; // prevent default
+ * }
+ *
+ *
+ * @alt
+ * Grey rect center. turns white when up arrow pressed and black when down
+ *
+ */
+p5.prototype.keyCode = 0;
+
+/**
+ * The keyPressed() function is called once every time a key is pressed. The
+ * keyCode for the key that was pressed is stored in the keyCode variable.
+ *
+ * For non-ASCII keys, use the keyCode variable. You can check if the keyCode
+ * equals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,
+ * OPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.
+ *
+ * For ASCII keys that was pressed is stored in the key variable. However, it
+ * does not distinguish between uppercase and lowercase. For this reason, it
+ * is recommended to use keyTyped() to read the key variable, in which the
+ * case of the variable will be distinguished.
+ *
+ * Because of how operating systems handle key repeats, holding down a key
+ * may cause multiple calls to keyTyped() (and keyReleased() as well). The
+ * rate of repeat is set by the operating system and how each computer is
+ * configured.
+ * Browsers may have different default
+ * behaviors attached to various key events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method keyPressed
+ * @example
+ *
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyPressed() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyPressed() {
+ * if (keyCode === LEFT_ARROW) {
+ * value = 255;
+ * } else if (keyCode === RIGHT_ARROW) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ * function keyPressed() {
+ * // Do something
+ * return false; // prevent any default behaviour
+ * }
+ *
+ *
+ *
+ * @alt
+ * black rect center. turns white when key pressed and black when released
+ * black rect center. turns white when left arrow pressed and black when right.
+ *
+ */
+p5.prototype._onkeydown = function(e) {
+ if (downKeys[e.which]) {
+ // prevent multiple firings
+ return;
+ }
+ this._setProperty('isKeyPressed', true);
+ this._setProperty('keyIsPressed', true);
+ this._setProperty('keyCode', e.which);
+ downKeys[e.which] = true;
+ var key = String.fromCharCode(e.which);
+ if (!key) {
+ key = e.which;
+ }
+ this._setProperty('key', key);
+ var keyPressed = this.keyPressed || window.keyPressed;
+ if (typeof keyPressed === 'function' && !e.charCode) {
+ var executeDefault = keyPressed(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+};
+/**
+ * The keyReleased() function is called once every time a key is released.
+ * See key and keyCode for more information.
+ * Browsers may have different default
+ * behaviors attached to various key events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method keyReleased
+ * @example
+ *
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyReleased() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * return false; // prevent any default behavior
+ * }
+ *
+ *
+ *
+ * @alt
+ * black rect center. turns white when key pressed and black when pressed again
+ *
+ */
+p5.prototype._onkeyup = function(e) {
+ var keyReleased = this.keyReleased || window.keyReleased;
+ downKeys[e.which] = false;
+
+ if (!areDownKeys()) {
+ this._setProperty('isKeyPressed', false);
+ this._setProperty('keyIsPressed', false);
+ }
+
+ this._setProperty('_lastKeyCodeTyped', null);
+
+ var key = String.fromCharCode(e.which);
+ if (!key) {
+ key = e.which;
+ }
+ this._setProperty('key', key);
+ this._setProperty('keyCode', e.which);
+ if (typeof keyReleased === 'function') {
+ var executeDefault = keyReleased(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+};
+
+/**
+ * The keyTyped() function is called once every time a key is pressed, but
+ * action keys such as Ctrl, Shift, and Alt are ignored. The most recent
+ * key pressed will be stored in the key variable.
+ *
+ * Because of how operating systems handle key repeats, holding down a key
+ * will cause multiple calls to keyTyped() (and keyReleased() as well). The
+ * rate of repeat is set by the operating system and how each computer is
+ * configured.
+ * Browsers may have different default behaviors attached to various key
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method keyTyped
+ * @example
+ *
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function keyTyped() {
+ * if (key === 'a') {
+ * value = 255;
+ * } else if (key === 'b') {
+ * value = 0;
+ * }
+ * // uncomment to prevent any default behavior
+ * // return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black rect center. turns white when 'a' key typed and black when 'b' pressed
+ *
+ */
+p5.prototype._onkeypress = function(e) {
+ if (e.which === this._lastKeyCodeTyped) {
+ // prevent multiple firings
+ return;
+ }
+ this._setProperty('keyCode', e.which);
+ this._setProperty('_lastKeyCodeTyped', e.which); // track last keyCode
+ this._setProperty('key', String.fromCharCode(e.which));
+ var keyTyped = this.keyTyped || window.keyTyped;
+ if (typeof keyTyped === 'function') {
+ var executeDefault = keyTyped(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+};
+/**
+ * The onblur function is called when the user is no longer focused
+ * on the p5 element. Because the keyup events will not fire if the user is
+ * not focused on the element we must assume all keys currently down have
+ * been released.
+ */
+p5.prototype._onblur = function(e) {
+ downKeys = {};
+};
+
+/**
+ * The keyIsDown() function checks if the key is currently down, i.e. pressed.
+ * It can be used if you have an object that moves, and you want several keys
+ * to be able to affect its behaviour simultaneously, such as moving a
+ * sprite diagonally. You can put in any number representing the keyCode of
+ * the key, or use any of the variable keyCode names listed
+ * here.
+ *
+ * @method keyIsDown
+ * @param {Number} code The key to check for.
+ * @return {Boolean} whether key is down or not
+ * @example
+ *
+ * var x = 100;
+ * var y = 100;
+ *
+ * function setup() {
+ * createCanvas(512, 512);
+ * }
+ *
+ * function draw() {
+ * if (keyIsDown(LEFT_ARROW)) {
+ * x -= 5;
+ * }
+ *
+ * if (keyIsDown(RIGHT_ARROW)) {
+ * x += 5;
+ * }
+ *
+ * if (keyIsDown(UP_ARROW)) {
+ * y -= 5;
+ * }
+ *
+ * if (keyIsDown(DOWN_ARROW)) {
+ * y += 5;
+ * }
+ *
+ * clear();
+ * fill(255, 0, 0);
+ * ellipse(x, y, 50, 50);
+ * }
+ *
+ *
+ * @alt
+ * 50x50 red ellipse moves left, right, up and down with arrow presses.
+ *
+ */
+p5.prototype.keyIsDown = function(code) {
+ p5._validateParameters('keyIsDown', arguments);
+ return downKeys[code];
+};
+
+/**
+ * The checkDownKeys function returns a boolean true if any keys pressed
+ * and a false if no keys are currently pressed.
+
+ * Helps avoid instances where a multiple keys are pressed simultaneously and
+ * releasing a single key will then switch the
+ * keyIsPressed property to true.
+ * @private
+**/
+function areDownKeys() {
+ for (var key in downKeys) {
+ if (downKeys.hasOwnProperty(key) && downKeys[key] === true) {
+ return true;
+ }
+ }
+ return false;
+}
+
+module.exports = p5;
+
+},{"../core/core":22}],39:[function(_dereq_,module,exports){
+/**
+ * @module Events
+ * @submodule Mouse
+ * @for p5
+ * @requires core
+ * @requires constants
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+var constants = _dereq_('../core/constants');
+
+/*
+ * This is a flag which is false until the first time
+ * we receive a mouse event. The pmouseX and pmouseY
+ * values will match the mouseX and mouseY values until
+ * this interaction takes place.
+ */
+p5.prototype._hasMouseInteracted = false;
+
+/**
+ * The system variable mouseX always contains the current horizontal
+ * position of the mouse, relative to (0, 0) of the canvas. If touch is
+ * used instead of mouse input, mouseX will hold the x value of the most
+ * recent touch point.
+ *
+ * @property {Number} mouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas
+ * function draw() {
+ * background(244, 248, 252);
+ * line(mouseX, 0, mouseX, 100);
+ * }
+ *
+ *
+ *
+ * @alt
+ * horizontal black line moves left and right with mouse x-position
+ *
+ */
+p5.prototype.mouseX = 0;
+
+/**
+ * The system variable mouseY always contains the current vertical position
+ * of the mouse, relative to (0, 0) of the canvas. If touch is
+ * used instead of mouse input, mouseY will hold the y value of the most
+ * recent touch point.
+ *
+ * @property {Number} mouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas
+ * function draw() {
+ * background(244, 248, 252);
+ * line(0, mouseY, 100, mouseY);
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical black line moves up and down with mouse y-position
+ *
+ */
+p5.prototype.mouseY = 0;
+
+/**
+ * The system variable pmouseX always contains the horizontal position of
+ * the mouse or finger in the frame previous to the current frame, relative to
+ * (0, 0) of the canvas.
+ *
+ * @property {Number} pmouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * // Move the mouse across the canvas to leave a trail
+ * function setup() {
+ * //slow down the frameRate to make it more visible
+ * frameRate(10);
+ * }
+ *
+ * function draw() {
+ * background(244, 248, 252);
+ * line(mouseX, mouseY, pmouseX, pmouseY);
+ * print(pmouseX + ' -> ' + mouseX);
+ * }
+ *
+ *
+ *
+ * @alt
+ * line trail is created from cursor movements. faster movement make longer line.
+ *
+ */
+p5.prototype.pmouseX = 0;
+
+/**
+ * The system variable pmouseY always contains the vertical position of the
+ * mouse or finger in the frame previous to the current frame, relative to
+ * (0, 0) of the canvas.
+ *
+ * @property {Number} pmouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ * //draw a square only if the mouse is not moving
+ * if (mouseY === pmouseY && mouseX === pmouseX) {
+ * rect(20, 20, 60, 60);
+ * }
+ *
+ * print(pmouseY + ' -> ' + mouseY);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60x60 black rect center, fuschia background. rect flickers on mouse movement
+ *
+ */
+p5.prototype.pmouseY = 0;
+
+/**
+ * The system variable winMouseX always contains the current horizontal
+ * position of the mouse, relative to (0, 0) of the window.
+ *
+ * @property {Number} winMouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * var myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * }
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * //move the canvas to the horizontal mouse position
+ * //rela tive to the window
+ * myCanvas.position(winMouseX + 1, windowHeight / 2);
+ *
+ * //the y of the square is relative to the canvas
+ * rect(20, mouseY, 60, 60);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60x60 black rect y moves with mouse y and fuschia canvas moves with mouse x
+ *
+ */
+p5.prototype.winMouseX = 0;
+
+/**
+ * The system variable winMouseY always contains the current vertical
+ * position of the mouse, relative to (0, 0) of the window.
+ *
+ * @property {Number} winMouseY
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * var myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * }
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * //move the canvas to the vertical mouse position
+ * //rel ative to the window
+ * myCanvas.position(windowWidth / 2, winMouseY + 1);
+ *
+ * //the x of the square is relative to the canvas
+ * rect(mouseX, 20, 60, 60);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60x60 black rect x moves with mouse x and fuschia canvas y moves with mouse y
+ *
+ */
+p5.prototype.winMouseY = 0;
+
+/**
+ * The system variable pwinMouseX always contains the horizontal position
+ * of the mouse in the frame previous to the current frame, relative to
+ * (0, 0) of the window.
+ *
+ * @property {Number} pwinMouseX
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * var myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * noStroke();
+ * fill(237, 34, 93);
+ * }
+ *
+ * function draw() {
+ * clear();
+ * //the difference between previous and
+ * //current x position is the horizontal mouse speed
+ * var speed = abs(winMouseX - pwinMouseX);
+ * //change the size of the circle
+ * //according to the horizontal speed
+ * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
+ * //move the canvas to the mouse position
+ * myCanvas.position(winMouseX + 1, winMouseY + 1);
+ * }
+ *
+ *
+ *
+ * @alt
+ * fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed
+ *
+ */
+p5.prototype.pwinMouseX = 0;
+
+/**
+ * The system variable pwinMouseY always contains the vertical position of
+ * the mouse in the frame previous to the current frame, relative to (0, 0)
+ * of the window.
+ *
+ * @property {Number} pwinMouseY
+ * @readOnly
+ *
+ *
+ * @example
+ *
+ *
+ * var myCanvas;
+ *
+ * function setup() {
+ * //use a variable to store a pointer to the canvas
+ * myCanvas = createCanvas(100, 100);
+ * noStroke();
+ * fill(237, 34, 93);
+ * }
+ *
+ * function draw() {
+ * clear();
+ * //the difference between previous and
+ * //current y position is the vertical mouse speed
+ * var speed = abs(winMouseY - pwinMouseY);
+ * //change the size of the circle
+ * //according to the vertical speed
+ * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);
+ * //move the canvas to the mouse position
+ * myCanvas.position(winMouseX + 1, winMouseY + 1);
+ * }
+ *
+ *
+ *
+ * @alt
+ * fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed
+ *
+ */
+p5.prototype.pwinMouseY = 0;
+
+/**
+ * Processing automatically tracks if the mouse button is pressed and which
+ * button is pressed. The value of the system variable mouseButton is either
+ * LEFT, RIGHT, or CENTER depending on which button was pressed last.
+ * Warning: different browsers may track mouseButton differently.
+ *
+ * @property {Constant} mouseButton
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * if (mouseIsPressed) {
+ * if (mouseButton === LEFT) {
+ * ellipse(50, 50, 50, 50);
+ * }
+ * if (mouseButton === RIGHT) {
+ * rect(25, 25, 50, 50);
+ * }
+ * if (mouseButton === CENTER) {
+ * triangle(23, 75, 50, 20, 78, 75);
+ * }
+ * }
+ *
+ * print(mouseButton);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black ellipse appears on center of fuschia canvas on mouse click/press.
+ *
+ */
+p5.prototype.mouseButton = 0;
+
+/**
+ * The boolean system variable mouseIsPressed is true if the mouse is pressed
+ * and false if not.
+ *
+ * @property {Boolean} mouseIsPressed
+ * @readOnly
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ *
+ * if (mouseIsPressed) {
+ * ellipse(50, 50, 50, 50);
+ * } else {
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * print(mouseIsPressed);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect becomes ellipse with mouse click/press. fuschia background.
+ *
+ */
+p5.prototype.mouseIsPressed = false;
+
+p5.prototype._updateNextMouseCoords = function(e) {
+ if (this._curElement !== null && (!e.touches || e.touches.length > 0)) {
+ var mousePos = getMousePos(
+ this._curElement.elt,
+ this.width,
+ this.height,
+ e
+ );
+ this._setProperty('mouseX', mousePos.x);
+ this._setProperty('mouseY', mousePos.y);
+ this._setProperty('winMouseX', mousePos.winX);
+ this._setProperty('winMouseY', mousePos.winY);
+ }
+ if (!this._hasMouseInteracted) {
+ // For first draw, make previous and next equal
+ this._updateMouseCoords();
+ this._setProperty('_hasMouseInteracted', true);
+ }
+};
+
+p5.prototype._updateMouseCoords = function() {
+ this._setProperty('pmouseX', this.mouseX);
+ this._setProperty('pmouseY', this.mouseY);
+ this._setProperty('pwinMouseX', this.winMouseX);
+ this._setProperty('pwinMouseY', this.winMouseY);
+};
+
+function getMousePos(canvas, w, h, evt) {
+ if (evt && !evt.clientX) {
+ // use touches if touch and not mouse
+ if (evt.touches) {
+ evt = evt.touches[0];
+ } else if (evt.changedTouches) {
+ evt = evt.changedTouches[0];
+ }
+ }
+ var rect = canvas.getBoundingClientRect();
+ var sx = canvas.scrollWidth / w;
+ var sy = canvas.scrollHeight / h;
+ return {
+ x: (evt.clientX - rect.left) / sx,
+ y: (evt.clientY - rect.top) / sy,
+ winX: evt.clientX,
+ winY: evt.clientY,
+ id: evt.identifier
+ };
+}
+
+p5.prototype._setMouseButton = function(e) {
+ if (e.button === 1) {
+ this._setProperty('mouseButton', constants.CENTER);
+ } else if (e.button === 2) {
+ this._setProperty('mouseButton', constants.RIGHT);
+ } else {
+ this._setProperty('mouseButton', constants.LEFT);
+ }
+};
+
+/**
+ * The mouseMoved() function is called every time the mouse moves and a mouse
+ * button is not pressed.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mouseMoved
+ * @example
+ *
+ *
+ * // Move the mouse across the page
+ * // to change its value
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mouseMoved() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function mouseMoved() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect becomes lighter with mouse movements until white then resets
+ * no image displayed
+ *
+ */
+
+/**
+ * The mouseDragged() function is called once every time the mouse moves and
+ * a mouse button is pressed. If no mouseDragged() function is defined, the
+ * touchMoved() function will be called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mouseDragged
+ * @example
+ *
+ *
+ * // Drag the mouse across the page
+ * // to change its value
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mouseDragged() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function mouseDragged() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns lighter with mouse click and drag until white, resets
+ * no image displayed
+ *
+ */
+p5.prototype._onmousemove = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._updateNextMouseCoords(e);
+ if (!this.mouseIsPressed) {
+ if (typeof context.mouseMoved === 'function') {
+ executeDefault = context.mouseMoved(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ } else {
+ if (typeof context.mouseDragged === 'function') {
+ executeDefault = context.mouseDragged(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ } else if (typeof context.touchMoved === 'function') {
+ executeDefault = context.touchMoved(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+ }
+};
+
+/**
+ * The mousePressed() function is called once after every time a mouse button
+ * is pressed. The mouseButton variable (see the related reference entry)
+ * can be used to determine which button has been pressed. If no
+ * mousePressed() function is defined, the touchStarted() function will be
+ * called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mousePressed
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mousePressed() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function mousePressed() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse click/press.
+ * no image displayed
+ *
+ */
+p5.prototype._onmousedown = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._setProperty('mouseIsPressed', true);
+ this._setMouseButton(e);
+ this._updateNextMouseCoords(e);
+ if (typeof context.mousePressed === 'function') {
+ executeDefault = context.mousePressed(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ } else if (typeof context.touchStarted === 'function') {
+ executeDefault = context.touchStarted(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+};
+
+/**
+ * The mouseReleased() function is called every time a mouse button is
+ * released. If no mouseReleased() function is defined, the touchEnded()
+ * function will be called instead if it is defined.
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ *
+ * @method mouseReleased
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been clicked
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function mouseReleased() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function mouseReleased() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse click/press.
+ * no image displayed
+ *
+ */
+p5.prototype._onmouseup = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._setProperty('mouseIsPressed', false);
+ if (typeof context.mouseReleased === 'function') {
+ executeDefault = context.mouseReleased(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ } else if (typeof context.touchEnded === 'function') {
+ executeDefault = context.touchEnded(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+};
+
+p5.prototype._ondragend = p5.prototype._onmouseup;
+p5.prototype._ondragover = p5.prototype._onmousemove;
+
+/**
+ * The mouseClicked() function is called once after a mouse button has been
+ * pressed and then released.
+ * Browsers handle clicks differently, so this function is only guaranteed to be
+ * run when the left mouse button is clicked. To handle other mouse buttons
+ * being pressed or released, see mousePressed() or mouseReleased().
+ * Browsers may have different default
+ * behaviors attached to various mouse events. To prevent any default
+ * behavior for this event, add "return false" to the end of the method.
+ *
+ * @method mouseClicked
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been clicked
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * function mouseClicked() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function mouseClicked() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse click/press.
+ * no image displayed
+ *
+ */
+p5.prototype._onclick = function(e) {
+ var context = this._isGlobal ? window : this;
+ if (typeof context.mouseClicked === 'function') {
+ var executeDefault = context.mouseClicked(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+};
+
+/**
+ * The doubleClicked() function is executed every time a event
+ * listener has detected a dblclick event which is a part of the
+ * DOM L3 specification. The doubleClicked event is fired when a
+ * pointing device button (usually a mouse's primary button)
+ * is clicked twice on a single element. For more info on the
+ * dblclick event refer to mozilla's documentation here:
+ * https://developer.mozilla.org/en-US/docs/Web/Events/dblclick
+ *
+ * @method doubleClicked
+ * @example
+ *
+ *
+ * // Click within the image to change
+ * // the value of the rectangle
+ * // after the mouse has been double clicked
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * function doubleClicked() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function doubleClicked() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect turns white with mouse doubleClick/press.
+ * no image displayed
+ */
+
+p5.prototype._ondblclick = function(e) {
+ var context = this._isGlobal ? window : this;
+ if (typeof context.doubleClicked === 'function') {
+ var executeDefault = context.doubleClicked(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+};
+
+/**
+ * The function mouseWheel() is executed every time a vertical mouse wheel
+ * event is detected either triggered by an actual mouse wheel or by a
+ * touchpad.
+ * The event.delta property returns the amount the mouse wheel
+ * have scrolled. The values can be positive or negative depending on the
+ * scroll direction (on OS X with "natural" scrolling enabled, the signs
+ * are inverted).
+ * Browsers may have different default behaviors attached to various
+ * mouse events. To prevent any default behavior for this event, add
+ * "return false" to the end of the method.
+ * Due to the current support of the "wheel" event on Safari, the function
+ * may only work as expected if "return false" is included while using Safari.
+ *
+ * @method mouseWheel
+ *
+ * @example
+ *
+ *
+ * var pos = 25;
+ *
+ * function draw() {
+ * background(237, 34, 93);
+ * fill(0);
+ * rect(25, pos, 50, 50);
+ * }
+ *
+ * function mouseWheel(event) {
+ * print(event.delta);
+ * //move the square according to the vertical scroll amount
+ * pos += event.delta;
+ * //uncomment to block page scrolling
+ * //return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * black 50x50 rect moves up and down with vertical scroll. fuschia background
+ *
+ */
+p5.prototype._onwheel = function(e) {
+ var context = this._isGlobal ? window : this;
+ if (typeof context.mouseWheel === 'function') {
+ e.delta = e.deltaY;
+ var executeDefault = context.mouseWheel(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+};
+
+module.exports = p5;
+
+},{"../core/constants":21,"../core/core":22}],40:[function(_dereq_,module,exports){
+/**
+ * @module Events
+ * @submodule Touch
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+/**
+ * The system variable touches[] contains an array of the positions of all
+ * current touch points, relative to (0, 0) of the canvas, and IDs identifying a
+ * unique touch as it moves. Each element in the array is an object with x, y,
+ * and id properties.
+ *
+ * The touches[] array is not supported on Safari and IE on touch-based
+ * desktops (laptops).
+ *
+ * @property {Object[]} touches
+ * @readOnly
+ */
+p5.prototype.touches = [];
+
+p5.prototype._updateTouchCoords = function(e) {
+ if (this._curElement !== null) {
+ var touches = [];
+ for (var i = 0; i < e.touches.length; i++) {
+ touches[i] = getTouchInfo(
+ this._curElement.elt,
+ this.width,
+ this.height,
+ e,
+ i
+ );
+ }
+ this._setProperty('touches', touches);
+ }
+};
+
+function getTouchInfo(canvas, w, h, e, i) {
+ i = i || 0;
+ var rect = canvas.getBoundingClientRect();
+ var sx = canvas.scrollWidth / w;
+ var sy = canvas.scrollHeight / h;
+ var touch = e.touches[i] || e.changedTouches[i];
+ return {
+ x: (touch.clientX - rect.left) / sx,
+ y: (touch.clientY - rect.top) / sy,
+ winX: touch.clientX,
+ winY: touch.clientY,
+ id: touch.identifier
+ };
+}
+
+/**
+ * The touchStarted() function is called once after every time a touch is
+ * registered. If no touchStarted() function is defined, the mousePressed()
+ * function will be called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchStarted
+ * @example
+ *
+ *
+ * // Touch within the image to change
+ * // the value of the rectangle
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function touchStarted() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function touchStarted() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect turns white with touch event.
+ * no image displayed
+ */
+p5.prototype._ontouchstart = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._setProperty('mouseIsPressed', true);
+ this._updateTouchCoords(e);
+ this._updateNextMouseCoords(e);
+ if (typeof context.touchStarted === 'function') {
+ executeDefault = context.touchStarted(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ } else if (typeof context.mousePressed === 'function') {
+ executeDefault = context.mousePressed(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+};
+
+/**
+ * The touchMoved() function is called every time a touch move is registered.
+ * If no touchMoved() function is defined, the mouseDragged() function will
+ * be called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchMoved
+ * @example
+ *
+ *
+ * // Move your finger across the page
+ * // to change its value
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function touchMoved() {
+ * value = value + 5;
+ * if (value > 255) {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function touchMoved() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect turns lighter with touch until white. resets
+ * no image displayed
+ *
+ */
+p5.prototype._ontouchmove = function(e) {
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ this._updateTouchCoords(e);
+ this._updateNextMouseCoords(e);
+ if (typeof context.touchMoved === 'function') {
+ executeDefault = context.touchMoved(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ } else if (typeof context.mouseDragged === 'function') {
+ executeDefault = context.mouseDragged(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+};
+
+/**
+ * The touchEnded() function is called every time a touch ends. If no
+ * touchEnded() function is defined, the mouseReleased() function will be
+ * called instead if it is defined.
+ * Browsers may have different default behaviors attached to various touch
+ * events. To prevent any default behavior for this event, add "return false"
+ * to the end of the method.
+ *
+ * @method touchEnded
+ * @example
+ *
+ *
+ * // Release touch within the image to
+ * // change the value of the rectangle
+ *
+ * var value = 0;
+ * function draw() {
+ * fill(value);
+ * rect(25, 25, 50, 50);
+ * }
+ * function touchEnded() {
+ * if (value === 0) {
+ * value = 255;
+ * } else {
+ * value = 0;
+ * }
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function touchEnded() {
+ * ellipse(mouseX, mouseY, 5, 5);
+ * // prevent default
+ * return false;
+ * }
+ *
+ *
+ *
+ * @alt
+ * 50x50 black rect turns white with touch.
+ * no image displayed
+ *
+ */
+p5.prototype._ontouchend = function(e) {
+ this._setProperty('mouseIsPressed', false);
+ this._updateTouchCoords(e);
+ this._updateNextMouseCoords(e);
+ var context = this._isGlobal ? window : this;
+ var executeDefault;
+ if (typeof context.touchEnded === 'function') {
+ executeDefault = context.touchEnded(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ } else if (typeof context.mouseReleased === 'function') {
+ executeDefault = context.mouseReleased(e);
+ if (executeDefault === false) {
+ e.preventDefault();
+ }
+ }
+};
+
+module.exports = p5;
+
+},{"../core/core":22}],41:[function(_dereq_,module,exports){
+/*global ImageData:false */
+
+/**
+ * This module defines the filters for use with image buffers.
+ *
+ * This module is basically a collection of functions stored in an object
+ * as opposed to modules. The functions are destructive, modifying
+ * the passed in canvas rather than creating a copy.
+ *
+ * Generally speaking users of this module will use the Filters.apply method
+ * on a canvas to create an effect.
+ *
+ * A number of functions are borrowed/adapted from
+ * http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
+ * or the java processing implementation.
+ */
+
+'use strict';
+
+var Filters = {};
+
+/*
+ * Helper functions
+ */
+
+/**
+ * Returns the pixel buffer for a canvas
+ *
+ * @private
+ *
+ * @param {Canvas|ImageData} canvas the canvas to get pixels from
+ * @return {Uint8ClampedArray} a one-dimensional array containing
+ * the data in thc RGBA order, with integer
+ * values between 0 and 255
+ */
+Filters._toPixels = function(canvas) {
+ if (canvas instanceof ImageData) {
+ return canvas.data;
+ } else {
+ return canvas
+ .getContext('2d')
+ .getImageData(0, 0, canvas.width, canvas.height).data;
+ }
+};
+
+/**
+ * Returns a 32 bit number containing ARGB data at ith pixel in the
+ * 1D array containing pixels data.
+ *
+ * @private
+ *
+ * @param {Uint8ClampedArray} data array returned by _toPixels()
+ * @param {Integer} i index of a 1D Image Array
+ * @return {Integer} 32 bit integer value representing
+ * ARGB value.
+ */
+Filters._getARGB = function(data, i) {
+ var offset = i * 4;
+ return (
+ ((data[offset + 3] << 24) & 0xff000000) |
+ ((data[offset] << 16) & 0x00ff0000) |
+ ((data[offset + 1] << 8) & 0x0000ff00) |
+ (data[offset + 2] & 0x000000ff)
+ );
+};
+
+/**
+ * Modifies pixels RGBA values to values contained in the data object.
+ *
+ * @private
+ *
+ * @param {Uint8ClampedArray} pixels array returned by _toPixels()
+ * @param {Int32Array} data source 1D array where each value
+ * represents ARGB values
+ */
+Filters._setPixels = function(pixels, data) {
+ var offset = 0;
+ for (var i = 0, al = pixels.length; i < al; i++) {
+ offset = i * 4;
+ pixels[offset + 0] = (data[i] & 0x00ff0000) >>> 16;
+ pixels[offset + 1] = (data[i] & 0x0000ff00) >>> 8;
+ pixels[offset + 2] = data[i] & 0x000000ff;
+ pixels[offset + 3] = (data[i] & 0xff000000) >>> 24;
+ }
+};
+
+/**
+ * Returns the ImageData object for a canvas
+ * https://developer.mozilla.org/en-US/docs/Web/API/ImageData
+ *
+ * @private
+ *
+ * @param {Canvas|ImageData} canvas canvas to get image data from
+ * @return {ImageData} Holder of pixel data (and width and
+ * height) for a canvas
+ */
+Filters._toImageData = function(canvas) {
+ if (canvas instanceof ImageData) {
+ return canvas;
+ } else {
+ return canvas
+ .getContext('2d')
+ .getImageData(0, 0, canvas.width, canvas.height);
+ }
+};
+
+/**
+ * Returns a blank ImageData object.
+ *
+ * @private
+ *
+ * @param {Integer} width
+ * @param {Integer} height
+ * @return {ImageData}
+ */
+Filters._createImageData = function(width, height) {
+ Filters._tmpCanvas = document.createElement('canvas');
+ Filters._tmpCtx = Filters._tmpCanvas.getContext('2d');
+ return this._tmpCtx.createImageData(width, height);
+};
+
+/**
+ * Applys a filter function to a canvas.
+ *
+ * The difference between this and the actual filter functions defined below
+ * is that the filter functions generally modify the pixel buffer but do
+ * not actually put that data back to the canvas (where it would actually
+ * update what is visible). By contrast this method does make the changes
+ * actually visible in the canvas.
+ *
+ * The apply method is the method that callers of this module would generally
+ * use. It has been separated from the actual filters to support an advanced
+ * use case of creating a filter chain that executes without actually updating
+ * the canvas in between everystep.
+ *
+ * @private
+ * @param {HTMLCanvasElement} canvas [description]
+ * @param {function(ImageData,Object)} func [description]
+ * @param {Object} filterParam [description]
+ */
+Filters.apply = function(canvas, func, filterParam) {
+ var ctx = canvas.getContext('2d');
+ var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+
+ //Filters can either return a new ImageData object, or just modify
+ //the one they received.
+ var newImageData = func(imageData, filterParam);
+ if (newImageData instanceof ImageData) {
+ ctx.putImageData(newImageData, 0, 0, 0, 0, canvas.width, canvas.height);
+ } else {
+ ctx.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height);
+ }
+};
+
+/*
+ * Filters
+ */
+
+/**
+ * Converts the image to black and white pixels depending if they are above or
+ * below the threshold defined by the level parameter. The parameter must be
+ * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.
+ *
+ * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
+ *
+ * @private
+ * @param {Canvas} canvas
+ * @param {Float} level
+ */
+Filters.threshold = function(canvas, level) {
+ var pixels = Filters._toPixels(canvas);
+
+ if (level === undefined) {
+ level = 0.5;
+ }
+ var thresh = Math.floor(level * 255);
+
+ for (var i = 0; i < pixels.length; i += 4) {
+ var r = pixels[i];
+ var g = pixels[i + 1];
+ var b = pixels[i + 2];
+ var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ var val;
+ if (gray >= thresh) {
+ val = 255;
+ } else {
+ val = 0;
+ }
+ pixels[i] = pixels[i + 1] = pixels[i + 2] = val;
+ }
+};
+
+/**
+ * Converts any colors in the image to grayscale equivalents.
+ * No parameter is used.
+ *
+ * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/
+ *
+ * @private
+ * @param {Canvas} canvas
+ */
+Filters.gray = function(canvas) {
+ var pixels = Filters._toPixels(canvas);
+
+ for (var i = 0; i < pixels.length; i += 4) {
+ var r = pixels[i];
+ var g = pixels[i + 1];
+ var b = pixels[i + 2];
+
+ // CIE luminance for RGB
+ var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ pixels[i] = pixels[i + 1] = pixels[i + 2] = gray;
+ }
+};
+
+/**
+ * Sets the alpha channel to entirely opaque. No parameter is used.
+ *
+ * @private
+ * @param {Canvas} canvas
+ */
+Filters.opaque = function(canvas) {
+ var pixels = Filters._toPixels(canvas);
+
+ for (var i = 0; i < pixels.length; i += 4) {
+ pixels[i + 3] = 255;
+ }
+
+ return pixels;
+};
+
+/**
+ * Sets each pixel to its inverse value. No parameter is used.
+ * @private
+ * @param {Canvas} canvas
+ */
+Filters.invert = function(canvas) {
+ var pixels = Filters._toPixels(canvas);
+
+ for (var i = 0; i < pixels.length; i += 4) {
+ pixels[i] = 255 - pixels[i];
+ pixels[i + 1] = 255 - pixels[i + 1];
+ pixels[i + 2] = 255 - pixels[i + 2];
+ }
+};
+
+/**
+ * Limits each channel of the image to the number of colors specified as
+ * the parameter. The parameter can be set to values between 2 and 255, but
+ * results are most noticeable in the lower ranges.
+ *
+ * Adapted from java based processing implementation
+ *
+ * @private
+ * @param {Canvas} canvas
+ * @param {Integer} level
+ */
+Filters.posterize = function(canvas, level) {
+ var pixels = Filters._toPixels(canvas);
+
+ if (level < 2 || level > 255) {
+ throw new Error(
+ 'Level must be greater than 2 and less than 255 for posterize'
+ );
+ }
+
+ var levels1 = level - 1;
+ for (var i = 0; i < pixels.length; i += 4) {
+ var rlevel = pixels[i];
+ var glevel = pixels[i + 1];
+ var blevel = pixels[i + 2];
+
+ pixels[i] = ((rlevel * level) >> 8) * 255 / levels1;
+ pixels[i + 1] = ((glevel * level) >> 8) * 255 / levels1;
+ pixels[i + 2] = ((blevel * level) >> 8) * 255 / levels1;
+ }
+};
+
+/**
+ * reduces the bright areas in an image
+ * @private
+ * @param {Canvas} canvas
+ *
+ */
+Filters.dilate = function(canvas) {
+ var pixels = Filters._toPixels(canvas);
+ var currIdx = 0;
+ var maxIdx = pixels.length ? pixels.length / 4 : 0;
+ var out = new Int32Array(maxIdx);
+ var currRowIdx, maxRowIdx, colOrig, colOut, currLum;
+
+ var idxRight, idxLeft, idxUp, idxDown;
+ var colRight, colLeft, colUp, colDown;
+ var lumRight, lumLeft, lumUp, lumDown;
+
+ while (currIdx < maxIdx) {
+ currRowIdx = currIdx;
+ maxRowIdx = currIdx + canvas.width;
+ while (currIdx < maxRowIdx) {
+ colOrig = colOut = Filters._getARGB(pixels, currIdx);
+ idxLeft = currIdx - 1;
+ idxRight = currIdx + 1;
+ idxUp = currIdx - canvas.width;
+ idxDown = currIdx + canvas.width;
+
+ if (idxLeft < currRowIdx) {
+ idxLeft = currIdx;
+ }
+ if (idxRight >= maxRowIdx) {
+ idxRight = currIdx;
+ }
+ if (idxUp < 0) {
+ idxUp = 0;
+ }
+ if (idxDown >= maxIdx) {
+ idxDown = currIdx;
+ }
+ colUp = Filters._getARGB(pixels, idxUp);
+ colLeft = Filters._getARGB(pixels, idxLeft);
+ colDown = Filters._getARGB(pixels, idxDown);
+ colRight = Filters._getARGB(pixels, idxRight);
+
+ //compute luminance
+ currLum =
+ 77 * ((colOrig >> 16) & 0xff) +
+ 151 * ((colOrig >> 8) & 0xff) +
+ 28 * (colOrig & 0xff);
+ lumLeft =
+ 77 * ((colLeft >> 16) & 0xff) +
+ 151 * ((colLeft >> 8) & 0xff) +
+ 28 * (colLeft & 0xff);
+ lumRight =
+ 77 * ((colRight >> 16) & 0xff) +
+ 151 * ((colRight >> 8) & 0xff) +
+ 28 * (colRight & 0xff);
+ lumUp =
+ 77 * ((colUp >> 16) & 0xff) +
+ 151 * ((colUp >> 8) & 0xff) +
+ 28 * (colUp & 0xff);
+ lumDown =
+ 77 * ((colDown >> 16) & 0xff) +
+ 151 * ((colDown >> 8) & 0xff) +
+ 28 * (colDown & 0xff);
+
+ if (lumLeft > currLum) {
+ colOut = colLeft;
+ currLum = lumLeft;
+ }
+ if (lumRight > currLum) {
+ colOut = colRight;
+ currLum = lumRight;
+ }
+ if (lumUp > currLum) {
+ colOut = colUp;
+ currLum = lumUp;
+ }
+ if (lumDown > currLum) {
+ colOut = colDown;
+ currLum = lumDown;
+ }
+ out[currIdx++] = colOut;
+ }
+ }
+ Filters._setPixels(pixels, out);
+};
+
+/**
+ * increases the bright areas in an image
+ * @private
+ * @param {Canvas} canvas
+ *
+ */
+Filters.erode = function(canvas) {
+ var pixels = Filters._toPixels(canvas);
+ var currIdx = 0;
+ var maxIdx = pixels.length ? pixels.length / 4 : 0;
+ var out = new Int32Array(maxIdx);
+ var currRowIdx, maxRowIdx, colOrig, colOut, currLum;
+ var idxRight, idxLeft, idxUp, idxDown;
+ var colRight, colLeft, colUp, colDown;
+ var lumRight, lumLeft, lumUp, lumDown;
+
+ while (currIdx < maxIdx) {
+ currRowIdx = currIdx;
+ maxRowIdx = currIdx + canvas.width;
+ while (currIdx < maxRowIdx) {
+ colOrig = colOut = Filters._getARGB(pixels, currIdx);
+ idxLeft = currIdx - 1;
+ idxRight = currIdx + 1;
+ idxUp = currIdx - canvas.width;
+ idxDown = currIdx + canvas.width;
+
+ if (idxLeft < currRowIdx) {
+ idxLeft = currIdx;
+ }
+ if (idxRight >= maxRowIdx) {
+ idxRight = currIdx;
+ }
+ if (idxUp < 0) {
+ idxUp = 0;
+ }
+ if (idxDown >= maxIdx) {
+ idxDown = currIdx;
+ }
+ colUp = Filters._getARGB(pixels, idxUp);
+ colLeft = Filters._getARGB(pixels, idxLeft);
+ colDown = Filters._getARGB(pixels, idxDown);
+ colRight = Filters._getARGB(pixels, idxRight);
+
+ //compute luminance
+ currLum =
+ 77 * ((colOrig >> 16) & 0xff) +
+ 151 * ((colOrig >> 8) & 0xff) +
+ 28 * (colOrig & 0xff);
+ lumLeft =
+ 77 * ((colLeft >> 16) & 0xff) +
+ 151 * ((colLeft >> 8) & 0xff) +
+ 28 * (colLeft & 0xff);
+ lumRight =
+ 77 * ((colRight >> 16) & 0xff) +
+ 151 * ((colRight >> 8) & 0xff) +
+ 28 * (colRight & 0xff);
+ lumUp =
+ 77 * ((colUp >> 16) & 0xff) +
+ 151 * ((colUp >> 8) & 0xff) +
+ 28 * (colUp & 0xff);
+ lumDown =
+ 77 * ((colDown >> 16) & 0xff) +
+ 151 * ((colDown >> 8) & 0xff) +
+ 28 * (colDown & 0xff);
+
+ if (lumLeft < currLum) {
+ colOut = colLeft;
+ currLum = lumLeft;
+ }
+ if (lumRight < currLum) {
+ colOut = colRight;
+ currLum = lumRight;
+ }
+ if (lumUp < currLum) {
+ colOut = colUp;
+ currLum = lumUp;
+ }
+ if (lumDown < currLum) {
+ colOut = colDown;
+ currLum = lumDown;
+ }
+
+ out[currIdx++] = colOut;
+ }
+ }
+ Filters._setPixels(pixels, out);
+};
+
+// BLUR
+
+// internal kernel stuff for the gaussian blur filter
+var blurRadius;
+var blurKernelSize;
+var blurKernel;
+var blurMult;
+
+/*
+ * Port of https://github.com/processing/processing/blob/
+ * master/core/src/processing/core/PImage.java#L1250
+ *
+ * Optimized code for building the blur kernel.
+ * further optimized blur code (approx. 15% for radius=20)
+ * bigger speed gains for larger radii (~30%)
+ * added support for various image types (ALPHA, RGB, ARGB)
+ * [toxi 050728]
+ */
+function buildBlurKernel(r) {
+ var radius = (r * 3.5) | 0;
+ radius = radius < 1 ? 1 : radius < 248 ? radius : 248;
+
+ if (blurRadius !== radius) {
+ blurRadius = radius;
+ blurKernelSize = (1 + blurRadius) << 1;
+ blurKernel = new Int32Array(blurKernelSize);
+ blurMult = new Array(blurKernelSize);
+ for (var l = 0; l < blurKernelSize; l++) {
+ blurMult[l] = new Int32Array(256);
+ }
+
+ var bk, bki;
+ var bm, bmi;
+
+ for (var i = 1, radiusi = radius - 1; i < radius; i++) {
+ blurKernel[radius + i] = blurKernel[radiusi] = bki = radiusi * radiusi;
+ bm = blurMult[radius + i];
+ bmi = blurMult[radiusi--];
+ for (var j = 0; j < 256; j++) {
+ bm[j] = bmi[j] = bki * j;
+ }
+ }
+ bk = blurKernel[radius] = radius * radius;
+ bm = blurMult[radius];
+
+ for (var k = 0; k < 256; k++) {
+ bm[k] = bk * k;
+ }
+ }
+}
+
+// Port of https://github.com/processing/processing/blob/
+// master/core/src/processing/core/PImage.java#L1433
+function blurARGB(canvas, radius) {
+ var pixels = Filters._toPixels(canvas);
+ var width = canvas.width;
+ var height = canvas.height;
+ var numPackedPixels = width * height;
+ var argb = new Int32Array(numPackedPixels);
+ for (var j = 0; j < numPackedPixels; j++) {
+ argb[j] = Filters._getARGB(pixels, j);
+ }
+ var sum, cr, cg, cb, ca;
+ var read, ri, ym, ymi, bk0;
+ var a2 = new Int32Array(numPackedPixels);
+ var r2 = new Int32Array(numPackedPixels);
+ var g2 = new Int32Array(numPackedPixels);
+ var b2 = new Int32Array(numPackedPixels);
+ var yi = 0;
+ buildBlurKernel(radius);
+ var x, y, i;
+ var bm;
+ for (y = 0; y < height; y++) {
+ for (x = 0; x < width; x++) {
+ cb = cg = cr = ca = sum = 0;
+ read = x - blurRadius;
+ if (read < 0) {
+ bk0 = -read;
+ read = 0;
+ } else {
+ if (read >= width) {
+ break;
+ }
+ bk0 = 0;
+ }
+ for (i = bk0; i < blurKernelSize; i++) {
+ if (read >= width) {
+ break;
+ }
+ var c = argb[read + yi];
+ bm = blurMult[i];
+ ca += bm[(c & -16777216) >>> 24];
+ cr += bm[(c & 16711680) >> 16];
+ cg += bm[(c & 65280) >> 8];
+ cb += bm[c & 255];
+ sum += blurKernel[i];
+ read++;
+ }
+ ri = yi + x;
+ a2[ri] = ca / sum;
+ r2[ri] = cr / sum;
+ g2[ri] = cg / sum;
+ b2[ri] = cb / sum;
+ }
+ yi += width;
+ }
+ yi = 0;
+ ym = -blurRadius;
+ ymi = ym * width;
+ for (y = 0; y < height; y++) {
+ for (x = 0; x < width; x++) {
+ cb = cg = cr = ca = sum = 0;
+ if (ym < 0) {
+ bk0 = ri = -ym;
+ read = x;
+ } else {
+ if (ym >= height) {
+ break;
+ }
+ bk0 = 0;
+ ri = ym;
+ read = x + ymi;
+ }
+ for (i = bk0; i < blurKernelSize; i++) {
+ if (ri >= height) {
+ break;
+ }
+ bm = blurMult[i];
+ ca += bm[a2[read]];
+ cr += bm[r2[read]];
+ cg += bm[g2[read]];
+ cb += bm[b2[read]];
+ sum += blurKernel[i];
+ ri++;
+ read += width;
+ }
+ argb[x + yi] =
+ ((ca / sum) << 24) |
+ ((cr / sum) << 16) |
+ ((cg / sum) << 8) |
+ (cb / sum);
+ }
+ yi += width;
+ ymi += width;
+ ym++;
+ }
+ Filters._setPixels(pixels, argb);
+}
+
+Filters.blur = function(canvas, radius) {
+ blurARGB(canvas, radius);
+};
+
+module.exports = Filters;
+
+},{}],42:[function(_dereq_,module,exports){
+/**
+ * @module Image
+ * @submodule Image
+ * @for p5
+ * @requires core
+ */
+
+/**
+ * This module defines the p5 methods for the p5.Image class
+ * for drawing images to the main display canvas.
+ */
+'use strict';
+
+var p5 = _dereq_('../core/core'); // This is not global, but JSHint is not aware that // this module is implicitly enclosed with Browserify: this overrides the // redefined-global error and permits using the name "frames" for the array // of saved animation frames.
+
+/* global frames:true */ var frames = [];
+
+/**
+ * Creates a new p5.Image (the datatype for storing images). This provides a
+ * fresh buffer of pixels to play with. Set the size of the buffer with the
+ * width and height parameters.
+ *
+ * .pixels gives access to an array containing the values for all the pixels
+ * in the display window.
+ * These values are numbers. This array is the size (including an appropriate
+ * factor for the pixelDensity) of the display window x4,
+ * representing the R, G, B, A values in order for each pixel, moving from
+ * left to right across each row, then down each column. See .pixels for
+ * more info. It may also be simpler to use set() or get().
+ *
+ * Before accessing the pixels of an image, the data must loaded with the
+ * loadPixels() function. After the array data has been modified, the
+ * updatePixels() function must be run to update the changes.
+ *
+ * @method createImage
+ * @param {Integer} width width in pixels
+ * @param {Integer} height height in pixels
+ * @return {p5.Image} the p5.Image object
+ * @example
+ *
+ *
+ * var img = createImage(66, 66);
+ * img.loadPixels();
+ * for (var i = 0; i < img.width; i++) {
+ * for (var j = 0; j < img.height; j++) {
+ * img.set(i, j, color(0, 90, 102));
+ * }
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ *
+ *
+ *
+ *
+ *
+ * var img = createImage(66, 66);
+ * img.loadPixels();
+ * for (var i = 0; i < img.width; i++) {
+ * for (var j = 0; j < img.height; j++) {
+ * img.set(i, j, color(0, 90, 102, (i % img.width) * 2));
+ * }
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ * image(img, 34, 34);
+ *
+ *
+ *
+ *
+ *
+ * var pink = color(255, 102, 204);
+ * var img = createImage(66, 66);
+ * img.loadPixels();
+ * var d = pixelDensity();
+ * var halfImage = 4 * (width * d) * (height / 2 * d);
+ * for (var i = 0; i < halfImage; i += 4) {
+ * img.pixels[i] = red(pink);
+ * img.pixels[i + 1] = green(pink);
+ * img.pixels[i + 2] = blue(pink);
+ * img.pixels[i + 3] = alpha(pink);
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ *
+ *
+ *
+ * @alt
+ * 66x66 dark turquoise rect in center of canvas.
+ * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas
+ * no image displayed
+ *
+ */
+p5.prototype.createImage = function(width, height) {
+ p5._validateParameters('createImage', arguments);
+ return new p5.Image(width, height);
+};
+
+/**
+ * Save the current canvas as an image. In Safari, this will open the
+ * image in the window and the user must provide their own
+ * filename on save-as. Other browsers will either save the
+ * file immediately, or prompt the user with a dialogue window.
+ *
+ * @method saveCanvas
+ * @param {p5.Element|HTMLCanvasElement} selectedCanvas a variable
+ * representing a specific html5 canvas (optional)
+ * @param {String} [filename]
+ * @param {String} [extension] 'jpg' or 'png'
+ *
+ * @example
+ *
+ * function setup() {
+ * var c = createCanvas(100, 100);
+ * background(255, 0, 0);
+ * saveCanvas(c, 'myCanvas', 'jpg');
+ * }
+ *
+ *
+ * // note that this example has the same result as above
+ * // if no canvas is specified, defaults to main canvas
+ * function setup() {
+ * var c = createCanvas(100, 100);
+ * background(255, 0, 0);
+ * saveCanvas('myCanvas', 'jpg');
+ *
+ * // all of the following are valid
+ * saveCanvas(c, 'myCanvas', 'jpg');
+ * saveCanvas(c, 'myCanvas.jpg');
+ * saveCanvas(c, 'myCanvas');
+ * saveCanvas(c);
+ * saveCanvas('myCanvas', 'png');
+ * saveCanvas('myCanvas');
+ * saveCanvas();
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ * no image displayed
+ * no image displayed
+ */
+/**
+ * @method saveCanvas
+ * @param {String} [filename]
+ * @param {String} [extension]
+ */
+p5.prototype.saveCanvas = function() {
+ p5._validateParameters('saveCanvas', arguments);
+
+ // copy arguments to array
+ var args = [].slice.call(arguments);
+ var htmlCanvas, filename, extension;
+
+ if (arguments[0] instanceof HTMLCanvasElement) {
+ htmlCanvas = arguments[0];
+ args.shift();
+ } else if (arguments[0] instanceof p5.Element) {
+ htmlCanvas = arguments[0].elt;
+ args.shift();
+ } else {
+ htmlCanvas = this._curElement && this._curElement.elt;
+ }
+
+ if (args.length >= 1) {
+ filename = args[0];
+ }
+ if (args.length >= 2) {
+ extension = args[1];
+ }
+
+ extension =
+ extension ||
+ p5.prototype._checkFileExtension(filename, extension)[1] ||
+ 'png';
+
+ var mimeType;
+ switch (extension) {
+ default:
+ //case 'png':
+ mimeType = 'image/png';
+ break;
+ case 'jpeg':
+ case 'jpg':
+ mimeType = 'image/jpeg';
+ break;
+ }
+
+ htmlCanvas.toBlob(function(blob) {
+ p5.prototype.downloadFile(blob, filename, extension);
+ }, mimeType);
+};
+
+/**
+ * Capture a sequence of frames that can be used to create a movie.
+ * Accepts a callback. For example, you may wish to send the frames
+ * to a server where they can be stored or converted into a movie.
+ * If no callback is provided, the browser will pop up save dialogues in an
+ * attempt to download all of the images that have just been created. With the
+ * callback provided the image data isn't saved by default but instead passed
+ * as an argument to the callback function as an array of objects, with the
+ * size of array equal to the total number of frames.
+ *
+ * Note that saveFrames() will only save the first 15 frames of an animation.
+ * To export longer animations, you might look into a library like
+ * ccapture.js.
+ *
+ * @method saveFrames
+ * @param {String} filename
+ * @param {String} extension 'jpg' or 'png'
+ * @param {Number} duration Duration in seconds to save the frames for.
+ * @param {Number} framerate Framerate to save the frames in.
+ * @param {function(Array)} [callback] A callback function that will be executed
+ to handle the image data. This function
+ should accept an array as argument. The
+ array will contain the specified number of
+ frames of objects. Each object has three
+ properties: imageData - an
+ image/octet-stream, filename and extension.
+ * @example
+ *
+ * function draw() {
+ * background(mouseX);
+ * }
+ *
+ * function mousePressed() {
+ * saveFrames('out', 'png', 1, 25, function(data) {
+ * print(data);
+ * });
+ * }
+
+ *
+ * @alt
+ * canvas background goes from light to dark with mouse x.
+ *
+ */
+p5.prototype.saveFrames = function(fName, ext, _duration, _fps, callback) {
+ p5._validateParameters('saveFrames', arguments);
+ var duration = _duration || 3;
+ duration = p5.prototype.constrain(duration, 0, 15);
+ duration = duration * 1000;
+ var fps = _fps || 15;
+ fps = p5.prototype.constrain(fps, 0, 22);
+ var count = 0;
+
+ var makeFrame = p5.prototype._makeFrame;
+ var cnv = this._curElement.elt;
+ var frameFactory = setInterval(function() {
+ makeFrame(fName + count, ext, cnv);
+ count++;
+ }, 1000 / fps);
+
+ setTimeout(function() {
+ clearInterval(frameFactory);
+ if (callback) {
+ callback(frames);
+ } else {
+ for (var i = 0; i < frames.length; i++) {
+ var f = frames[i];
+ p5.prototype.downloadFile(f.imageData, f.filename, f.ext);
+ }
+ }
+ frames = []; // clear frames
+ }, duration + 0.01);
+};
+
+p5.prototype._makeFrame = function(filename, extension, _cnv) {
+ var cnv;
+ if (this) {
+ cnv = this._curElement.elt;
+ } else {
+ cnv = _cnv;
+ }
+ var mimeType;
+ if (!extension) {
+ extension = 'png';
+ mimeType = 'image/png';
+ } else {
+ switch (extension.toLowerCase()) {
+ case 'png':
+ mimeType = 'image/png';
+ break;
+ case 'jpeg':
+ mimeType = 'image/jpeg';
+ break;
+ case 'jpg':
+ mimeType = 'image/jpeg';
+ break;
+ default:
+ mimeType = 'image/png';
+ break;
+ }
+ }
+ var downloadMime = 'image/octet-stream';
+ var imageData = cnv.toDataURL(mimeType);
+ imageData = imageData.replace(mimeType, downloadMime);
+
+ var thisFrame = {};
+ thisFrame.imageData = imageData;
+ thisFrame.filename = filename;
+ thisFrame.ext = extension;
+ frames.push(thisFrame);
+};
+
+module.exports = p5;
+
+},{"../core/core":22}],43:[function(_dereq_,module,exports){
+/**
+ * @module Image
+ * @submodule Loading & Displaying
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+var Filters = _dereq_('./filters');
+var canvas = _dereq_('../core/canvas');
+var constants = _dereq_('../core/constants');
+
+_dereq_('../core/error_helpers');
+
+/**
+ * Loads an image from a path and creates a p5.Image from it.
+ *
+ * The image may not be immediately available for rendering
+ * If you want to ensure that the image is ready before doing
+ * anything with it, place the loadImage() call in preload().
+ * You may also supply a callback function to handle the image when it's ready.
+ *
+ * The path to the image should be relative to the HTML file
+ * that links in your sketch. Loading an image from a URL or other
+ * remote location may be blocked due to your browser's built-in
+ * security.
+ *
+ * @method loadImage
+ * @param {String} path Path of the image to be loaded
+ * @param {function(p5.Image)} [successCallback] Function to be called once
+ * the image is loaded. Will be passed the
+ * p5.Image.
+ * @param {function(Event)} [failureCallback] called with event error if
+ * the image fails to load.
+ * @return {p5.Image} the p5.Image object
+ * @example
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * }
+ *
+ *
+ *
+ *
+ * function setup() {
+ * // here we use a callback to display the image after loading
+ * loadImage('assets/laDefense.jpg', function(img) {
+ * image(img, 0, 0);
+ * });
+ * }
+ *
+ *
+ *
+ * @alt
+ * image of the underside of a white umbrella and grided ceililng above
+ * image of the underside of a white umbrella and grided ceililng above
+ *
+ */
+p5.prototype.loadImage = function(path, successCallback, failureCallback) {
+ p5._validateParameters('loadImage', arguments);
+ var img = new Image();
+ var pImg = new p5.Image(1, 1, this);
+
+ var self = this;
+ img.onload = function() {
+ pImg.width = pImg.canvas.width = img.width;
+ pImg.height = pImg.canvas.height = img.height;
+
+ // Draw the image into the backing canvas of the p5.Image
+ pImg.drawingContext.drawImage(img, 0, 0);
+ pImg.modified = true;
+
+ if (typeof successCallback === 'function') {
+ successCallback(pImg);
+ }
+
+ self._decrementPreload();
+ };
+ img.onerror = function(e) {
+ p5._friendlyFileLoadError(0, img.src);
+ if (typeof failureCallback === 'function') {
+ failureCallback(e);
+ }
+ };
+
+ //set crossOrigin in case image is served which CORS headers
+ //this will let us draw to canvas without tainting it.
+ //see https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image
+ // When using data-uris the file will be loaded locally
+ // so we don't need to worry about crossOrigin with base64 file types
+ if (path.indexOf('data:image/') !== 0) {
+ img.crossOrigin = 'Anonymous';
+ }
+
+ //start loading the image
+ img.src = path;
+
+ return pImg;
+};
+
+/**
+ * Validates clipping params. Per drawImage spec sWidth and sHight cannot be
+ * negative or greater than image intrinsic width and height
+ * @private
+ * @param {Number} sVal
+ * @param {Number} iVal
+ * @returns {Number}
+ * @private
+ */
+function _sAssign(sVal, iVal) {
+ if (sVal > 0 && sVal < iVal) {
+ return sVal;
+ } else {
+ return iVal;
+ }
+}
+
+/**
+ * Draw an image to the p5.js canvas.
+ *
+ * This function can be used with different numbers of parameters. The
+ * simplest use requires only three parameters: img, x, and y—where (x, y) is
+ * the position of the image. Two more parameters can optionally be added to
+ * specify the width and height of the image.
+ *
+ * This function can also be used with all eight Number parameters. To
+ * differentiate between all these parameters, p5.js uses the language of
+ * "destination rectangle" (which corresponds to "dx", "dy", etc.) and "source
+ * image" (which corresponds to "sx", "sy", etc.) below. Specifying the
+ * "source image" dimensions can be useful when you want to display a
+ * subsection of the source image instead of the whole thing. Here's a diagram
+ * to explain further:
+ *
+ *
+ * @method image
+ * @param {p5.Image|p5.Element} img the image to display
+ * @param {Number} x the x-coordinate of the top-left corner of the image
+ * @param {Number} y the y-coordinate of the top-left corner of the image
+ * @param {Number} [width] the width to draw the image
+ * @param {Number} [height] the height to draw the image
+ * @example
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * // Top-left corner of the img is at (0, 0)
+ * // Width and height are the img's original width and height
+ * image(img, 0, 0);
+ * }
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * background(50);
+ * // Top-left corner of the img is at (10, 10)
+ * // Width and height are 50 x 50
+ * image(img, 10, 10, 50, 50);
+ * }
+ *
+ *
+ *
+ *
+ * function setup() {
+ * // Here, we use a callback to display the image after loading
+ * loadImage('assets/laDefense.jpg', function(img) {
+ * image(img, 0, 0);
+ * });
+ * }
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/gradient.png');
+ * }
+ * function setup() {
+ * // 1. Background image
+ * // Top-left corner of the img is at (0, 0)
+ * // Width and height are the img's original width and height, 100 x 100
+ * image(img, 0, 0);
+ * // 2. Top right image
+ * // Top-left corner of destination rectangle is at (50, 0)
+ * // Destination rectangle width and height are 40 x 20
+ * // The next parameters are relative to the source image:
+ * // - Starting at position (50, 50) on the source image, capture a 50 x 50
+ * // subsection
+ * // - Draw this subsection to fill the dimensions of the destination rectangle
+ * image(img, 50, 0, 40, 20, 50, 50, 50, 50);
+ * }
+ *
+ *
+ * @alt
+ * image of the underside of a white umbrella and gridded ceiling above
+ * image of the underside of a white umbrella and gridded ceiling above
+ *
+ */
+/**
+ * @method image
+ * @param {p5.Image|p5.Element} img
+ * @param {Number} dx the x-coordinate of the destination
+ * rectangle in which to draw the source image
+ * @param {Number} dy the y-coordinate of the destination
+ * rectangle in which to draw the source image
+ * @param {Number} dWidth the width of the destination rectangle
+ * @param {Number} dHeight the height of the destination rectangle
+ * @param {Number} sx the x-coordinate of the subsection of the source
+ * image to draw into the destination rectangle
+ * @param {Number} sy the y-coordinate of the subsection of the source
+ * image to draw into the destination rectangle
+ * @param {Number} [sWidth] the width of the subsection of the
+ * source image to draw into the destination
+ * rectangle
+ * @param {Number} [sHeight] the height of the subsection of the
+ * source image to draw into the destination rectangle
+ */
+p5.prototype.image = function(
+ img,
+ dx,
+ dy,
+ dWidth,
+ dHeight,
+ sx,
+ sy,
+ sWidth,
+ sHeight
+) {
+ // set defaults per spec: https://goo.gl/3ykfOq
+
+ p5._validateParameters('image', arguments);
+
+ var defW = img.width;
+ var defH = img.height;
+
+ if (img.elt && img.elt.videoWidth && !img.canvas) {
+ // video no canvas
+ defW = img.elt.videoWidth;
+ defH = img.elt.videoHeight;
+ }
+
+ var _dx = dx;
+ var _dy = dy;
+ var _dw = dWidth || defW;
+ var _dh = dHeight || defH;
+ var _sx = sx || 0;
+ var _sy = sy || 0;
+ var _sw = sWidth || defW;
+ var _sh = sHeight || defH;
+
+ _sw = _sAssign(_sw, defW);
+ _sh = _sAssign(_sh, defH);
+
+ // This part needs cleanup and unit tests
+ // see issues https://github.com/processing/p5.js/issues/1741
+ // and https://github.com/processing/p5.js/issues/1673
+ var pd = 1;
+
+ if (img.elt && !img.canvas && img.elt.style.width) {
+ //if img is video and img.elt.size() has been used and
+ //no width passed to image()
+ if (img.elt.videoWidth && !dWidth) {
+ pd = img.elt.videoWidth;
+ } else {
+ //all other cases
+ pd = img.elt.width;
+ }
+ pd /= parseInt(img.elt.style.width, 10);
+ }
+
+ _sx *= pd;
+ _sy *= pd;
+ _sh *= pd;
+ _sw *= pd;
+
+ var vals = canvas.modeAdjust(_dx, _dy, _dw, _dh, this._renderer._imageMode);
+
+ // tint the image if there is a tint
+ this._renderer.image(img, _sx, _sy, _sw, _sh, vals.x, vals.y, vals.w, vals.h);
+};
+
+/**
+ * Sets the fill value for displaying images. Images can be tinted to
+ * specified colors or made transparent by including an alpha value.
+ *
+ * To apply transparency to an image without affecting its color, use
+ * white as the tint color and specify an alpha value. For instance,
+ * tint(255, 128) will make an image 50% transparent (assuming the default
+ * alpha range of 0-255, which can be changed with colorMode()).
+ *
+ * The value for the gray parameter must be less than or equal to the current
+ * maximum value as specified by colorMode(). The default maximum value is
+ * 255.
+ *
+ *
+ * @method tint
+ * @param {Number} v1 red or hue value relative to
+ * the current color range
+ * @param {Number} v2 green or saturation value
+ * relative to the current color range
+ * @param {Number} v3 blue or brightness value
+ * relative to the current color range
+ * @param {Number} [alpha]
+ *
+ * @example
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * tint(0, 153, 204); // Tint blue
+ * image(img, 50, 0);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * tint(0, 153, 204, 126); // Tint blue and set transparency
+ * image(img, 50, 0);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/laDefense.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * tint(255, 126); // Apply transparency without changing color
+ * image(img, 50, 0);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 2 side by side images of umbrella and ceiling, one image with blue tint
+ * Images of umbrella and ceiling, one half of image with blue tint
+ * 2 side by side images of umbrella and ceiling, one image translucent
+ *
+ */
+
+/**
+ * @method tint
+ * @param {String} value a color string
+ */
+
+/**
+ * @method tint
+ * @param {Number} gray a gray value
+ * @param {Number} [alpha]
+ */
+
+/**
+ * @method tint
+ * @param {Number[]} values an array containing the red,green,blue &
+ * and alpha components of the color
+ */
+
+/**
+ * @method tint
+ * @param {p5.Color} color the tint color
+ */
+p5.prototype.tint = function() {
+ p5._validateParameters('tint', arguments);
+ var c = this.color.apply(this, arguments);
+ this._renderer._tint = c.levels;
+};
+
+/**
+ * Removes the current fill value for displaying images and reverts to
+ * displaying images with their original hues.
+ *
+ * @method noTint
+ * @example
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * tint(0, 153, 204); // Tint blue
+ * image(img, 0, 0);
+ * noTint(); // Disable tint
+ * image(img, 50, 0);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 2 side by side images of bricks, left image with blue tint
+ *
+ */
+p5.prototype.noTint = function() {
+ this._renderer._tint = null;
+};
+
+/**
+ * Apply the current tint color to the input image, return the resulting
+ * canvas.
+ *
+ * @private
+ * @param {p5.Image} The image to be tinted
+ * @return {canvas} The resulting tinted canvas
+ *
+ */
+p5.prototype._getTintedImageCanvas = function(img) {
+ if (!img.canvas) {
+ return img;
+ }
+ var pixels = Filters._toPixels(img.canvas);
+ var tmpCanvas = document.createElement('canvas');
+ tmpCanvas.width = img.canvas.width;
+ tmpCanvas.height = img.canvas.height;
+ var tmpCtx = tmpCanvas.getContext('2d');
+ var id = tmpCtx.createImageData(img.canvas.width, img.canvas.height);
+ var newPixels = id.data;
+
+ for (var i = 0; i < pixels.length; i += 4) {
+ var r = pixels[i];
+ var g = pixels[i + 1];
+ var b = pixels[i + 2];
+ var a = pixels[i + 3];
+
+ newPixels[i] = r * this._renderer._tint[0] / 255;
+ newPixels[i + 1] = g * this._renderer._tint[1] / 255;
+ newPixels[i + 2] = b * this._renderer._tint[2] / 255;
+ newPixels[i + 3] = a * this._renderer._tint[3] / 255;
+ }
+
+ tmpCtx.putImageData(id, 0, 0);
+ return tmpCanvas;
+};
+
+/**
+ * Set image mode. Modifies the location from which images are drawn by
+ * changing the way in which parameters given to image() are interpreted.
+ * The default mode is imageMode(CORNER), which interprets the second and
+ * third parameters of image() as the upper-left corner of the image. If
+ * two additional parameters are specified, they are used to set the image's
+ * width and height.
+ *
+ * imageMode(CORNERS) interprets the second and third parameters of image()
+ * as the location of one corner, and the fourth and fifth parameters as the
+ * opposite corner.
+ *
+ * imageMode(CENTER) interprets the second and third parameters of image()
+ * as the image's center point. If two additional parameters are specified,
+ * they are used to set the image's width and height.
+ *
+ * @method imageMode
+ * @param {Constant} mode either CORNER, CORNERS, or CENTER
+ * @example
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * imageMode(CORNER);
+ * image(img, 10, 10, 50, 50);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * imageMode(CORNERS);
+ * image(img, 10, 10, 90, 40);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * imageMode(CENTER);
+ * image(img, 50, 50, 80, 80);
+ * }
+ *
+ *
+ *
+ * @alt
+ * small square image of bricks
+ * horizontal rectangle image of bricks
+ * large square image of bricks
+ *
+ */
+p5.prototype.imageMode = function(m) {
+ p5._validateParameters('imageMode', arguments);
+ if (
+ m === constants.CORNER ||
+ m === constants.CORNERS ||
+ m === constants.CENTER
+ ) {
+ this._renderer._imageMode = m;
+ }
+};
+
+module.exports = p5;
+
+},{"../core/canvas":20,"../core/constants":21,"../core/core":22,"../core/error_helpers":25,"./filters":41}],44:[function(_dereq_,module,exports){
+/**
+ * @module Image
+ * @submodule Image
+ * @requires core
+ * @requires constants
+ * @requires filters
+ */
+
+/**
+ * This module defines the p5.Image class and P5 methods for
+ * drawing images to the main display canvas.
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+var Filters = _dereq_('./filters');
+
+/*
+ * Class methods
+ */
+
+/**
+ * Creates a new p5.Image. A p5.Image is a canvas backed representation of an
+ * image.
+ *
+ * p5 can display .gif, .jpg and .png images. Images may be displayed
+ * in 2D and 3D space. Before an image is used, it must be loaded with the
+ * loadImage() function. The p5.Image class contains fields for the width and
+ * height of the image, as well as an array called pixels[] that contains the
+ * values for every pixel in the image.
+ *
+ * The methods described below allow easy access to the image's pixels and
+ * alpha channel and simplify the process of compositing.
+ *
+ * Before using the pixels[] array, be sure to use the loadPixels() method on
+ * the image to make sure that the pixel data is properly loaded.
+ * @example
+ *
+ * function setup() {
+ * var img = createImage(100, 100); // same as new p5.Image(100, 100);
+ * img.loadPixels();
+ * createCanvas(100, 100);
+ * background(0);
+ *
+ * // helper for writing color to array
+ * function writeColor(image, x, y, red, green, blue, alpha) {
+ * var index = (x + y * width) * 4;
+ * image.pixels[index] = red;
+ * image.pixels[index + 1] = green;
+ * image.pixels[index + 2] = blue;
+ * image.pixels[index + 3] = alpha;
+ * }
+ *
+ * var x, y;
+ * // fill with random colors
+ * for (y = 0; y < img.height; y++) {
+ * for (x = 0; x < img.width; x++) {
+ * var red = random(255);
+ * var green = random(255);
+ * var blue = random(255);
+ * var alpha = 255;
+ * writeColor(img, x, y, red, green, blue, alpha);
+ * }
+ * }
+ *
+ * // draw a red line
+ * y = 0;
+ * for (x = 0; x < img.width; x++) {
+ * writeColor(img, x, y, 255, 0, 0, 255);
+ * }
+ *
+ * // draw a green line
+ * y = img.height - 1;
+ * for (x = 0; x < img.width; x++) {
+ * writeColor(img, x, y, 0, 255, 0, 255);
+ * }
+ *
+ * img.updatePixels();
+ * image(img, 0, 0);
+ * }
+ *
+ *
+ *
+ * @class p5.Image
+ * @param {Number} width
+ * @param {Number} height
+ */
+p5.Image = function(width, height) {
+ /**
+ * Image width.
+ * @property {Number} width
+ * @readOnly
+ * @example
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * image(img, 0, 0);
+ * for (var i = 0; i < img.width; i++) {
+ * var c = img.get(i, img.height / 2);
+ * stroke(c);
+ * line(i, height / 2, i, height);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * rocky mountains in top and horizontal lines in corresponding colors in bottom.
+ *
+ */
+ this.width = width;
+ /**
+ * Image height.
+ * @property {Number} height
+ * @readOnly
+ * @example
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * image(img, 0, 0);
+ * for (var i = 0; i < img.height; i++) {
+ * var c = img.get(img.width / 2, i);
+ * stroke(c);
+ * line(0, i, width / 2, i);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * rocky mountains on right and vertical lines in corresponding colors on left.
+ *
+ */
+ this.height = height;
+ this.canvas = document.createElement('canvas');
+ this.canvas.width = this.width;
+ this.canvas.height = this.height;
+ this.drawingContext = this.canvas.getContext('2d');
+ this._pixelDensity = 1;
+ //used for webgl texturing only
+ this._modified = false;
+ /**
+ * Array containing the values for all the pixels in the display window.
+ * These values are numbers. This array is the size (include an appropriate
+ * factor for pixelDensity) of the display window x4,
+ * representing the R, G, B, A values in order for each pixel, moving from
+ * left to right across each row, then down each column. Retina and other
+ * high denisty displays may have more pixels[] (by a factor of
+ * pixelDensity^2).
+ * For example, if the image is 100x100 pixels, there will be 40,000. With
+ * pixelDensity = 2, there will be 160,000. The first four values
+ * (indices 0-3) in the array will be the R, G, B, A values of the pixel at
+ * (0, 0). The second four values (indices 4-7) will contain the R, G, B, A
+ * values of the pixel at (1, 0). More generally, to set values for a pixel
+ * at (x, y):
+ * ```javascript
+ * var d = pixelDensity();
+ * for (var i = 0; i < d; i++) {
+ * for (var j = 0; j < d; j++) {
+ * // loop over
+ * idx = 4 * ((y * d + j) * width * d + (x * d + i));
+ * pixels[idx] = r;
+ * pixels[idx+1] = g;
+ * pixels[idx+2] = b;
+ * pixels[idx+3] = a;
+ * }
+ * }
+ * ```
+ *
+ * Before accessing this array, the data must loaded with the loadPixels()
+ * function. After the array data has been modified, the updatePixels()
+ * function must be run to update the changes.
+ * @property {Number[]} pixels
+ * @example
+ *
+ *
+ * var img = createImage(66, 66);
+ * img.loadPixels();
+ * for (var i = 0; i < img.width; i++) {
+ * for (var j = 0; j < img.height; j++) {
+ * img.set(i, j, color(0, 90, 102));
+ * }
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ *
+ *
+ *
+ *
+ * var pink = color(255, 102, 204);
+ * var img = createImage(66, 66);
+ * img.loadPixels();
+ * for (var i = 0; i < 4 * (width * height / 2); i += 4) {
+ * img.pixels[i] = red(pink);
+ * img.pixels[i + 1] = green(pink);
+ * img.pixels[i + 2] = blue(pink);
+ * img.pixels[i + 3] = alpha(pink);
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ *
+ *
+ *
+ * @alt
+ * 66x66 turquoise rect in center of canvas
+ * 66x66 pink rect in center of canvas
+ *
+ */
+ this.pixels = [];
+};
+
+/**
+ * Helper fxn for sharing pixel methods
+ *
+ */
+p5.Image.prototype._setProperty = function(prop, value) {
+ this[prop] = value;
+ this.setModified(true);
+};
+
+/**
+ * Loads the pixels data for this image into the [pixels] attribute.
+ *
+ * @method loadPixels
+ * @example
+ *
+ * var myImage;
+ * var halfImage;
+ *
+ * function preload() {
+ * myImage = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * myImage.loadPixels();
+ * halfImage = 4 * width * height / 2;
+ * for (var i = 0; i < halfImage; i++) {
+ * myImage.pixels[i + halfImage] = myImage.pixels[i];
+ * }
+ * myImage.updatePixels();
+ * }
+ *
+ * function draw() {
+ * image(myImage, 0, 0);
+ * }
+ *
+ *
+ * @alt
+ * 2 images of rocky mountains vertically stacked
+ *
+ */
+p5.Image.prototype.loadPixels = function() {
+ p5.Renderer2D.prototype.loadPixels.call(this);
+ this.setModified(true);
+};
+
+/**
+ * Updates the backing canvas for this image with the contents of
+ * the [pixels] array.
+ *
+ * @method updatePixels
+ * @param {Integer} x x-offset of the target update area for the
+ * underlying canvas
+ * @param {Integer} y y-offset of the target update area for the
+ * underlying canvas
+ * @param {Integer} w height of the target update area for the
+ * underlying canvas
+ * @param {Integer} h height of the target update area for the
+ * underlying canvas
+ * @example
+ *
+ * var myImage;
+ * var halfImage;
+ *
+ * function preload() {
+ * myImage = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * myImage.loadPixels();
+ * halfImage = 4 * width * height / 2;
+ * for (var i = 0; i < halfImage; i++) {
+ * myImage.pixels[i + halfImage] = myImage.pixels[i];
+ * }
+ * myImage.updatePixels();
+ * }
+ *
+ * function draw() {
+ * image(myImage, 0, 0);
+ * }
+ *
+ *
+ * @alt
+ * 2 images of rocky mountains vertically stacked
+ *
+ */
+/**
+ * @method updatePixels
+ */
+p5.Image.prototype.updatePixels = function(x, y, w, h) {
+ p5.Renderer2D.prototype.updatePixels.call(this, x, y, w, h);
+ this.setModified(true);
+};
+
+/**
+ * Get a region of pixels from an image.
+ *
+ * If no params are passed, those whole image is returned,
+ * if x and y are the only params passed a single pixel is extracted
+ * if all params are passed a rectangle region is extracted and a p5.Image
+ * is returned.
+ *
+ * Returns undefined if the region is outside the bounds of the image
+ *
+ * @method get
+ * @param {Number} [x] x-coordinate of the pixel
+ * @param {Number} [y] y-coordinate of the pixel
+ * @param {Number} [w] width
+ * @param {Number} [h] height
+ * @return {Number[]|Color|p5.Image} color of pixel at x,y in array format
+ * [R, G, B, A] or p5.Image
+ * @example
+ *
+ * var myImage;
+ * var c;
+ *
+ * function preload() {
+ * myImage = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * background(myImage);
+ * noStroke();
+ * c = myImage.get(60, 90);
+ * fill(c);
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ * //get() returns color here
+ *
+ *
+ * @alt
+ * image of rocky mountains with 50x50 green rect in front
+ *
+ */
+p5.Image.prototype.get = function(x, y, w, h) {
+ return p5.Renderer2D.prototype.get.call(this, x, y, w, h);
+};
+
+/**
+ * Set the color of a single pixel or write an image into
+ * this p5.Image.
+ *
+ * Note that for a large number of pixels this will
+ * be slower than directly manipulating the pixels array
+ * and then calling updatePixels().
+ *
+ * @method set
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number|Number[]|Object} a grayscale value | pixel array |
+ * a p5.Color | image to copy
+ * @example
+ *
+ *
+ * var img = createImage(66, 66);
+ * img.loadPixels();
+ * for (var i = 0; i < img.width; i++) {
+ * for (var j = 0; j < img.height; j++) {
+ * img.set(i, j, color(0, 90, 102, (i % img.width) * 2));
+ * }
+ * }
+ * img.updatePixels();
+ * image(img, 17, 17);
+ * image(img, 34, 34);
+ *
+ *
+ *
+ * @alt
+ * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas
+ *
+ */
+p5.Image.prototype.set = function(x, y, imgOrCol) {
+ p5.Renderer2D.prototype.set.call(this, x, y, imgOrCol);
+ this.setModified(true);
+};
+
+/**
+ * Resize the image to a new width and height. To make the image scale
+ * proportionally, use 0 as the value for the wide or high parameter.
+ * For instance, to make the width of an image 150 pixels, and change
+ * the height using the same proportion, use resize(150, 0).
+ *
+ * @method resize
+ * @param {Number} width the resized image width
+ * @param {Number} height the resized image height
+ * @example
+ *
+ * var img;
+ *
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+
+ * function draw() {
+ * image(img, 0, 0);
+ * }
+ *
+ * function mousePressed() {
+ * img.resize(50, 100);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains. zoomed in
+ *
+ */
+p5.Image.prototype.resize = function(width, height) {
+ // Copy contents to a temporary canvas, resize the original
+ // and then copy back.
+ //
+ // There is a faster approach that involves just one copy and swapping the
+ // this.canvas reference. We could switch to that approach if (as i think
+ // is the case) there an expectation that the user would not hold a
+ // reference to the backing canvas of a p5.Image. But since we do not
+ // enforce that at the moment, I am leaving in the slower, but safer
+ // implementation.
+
+ // auto-resize
+ if (width === 0 && height === 0) {
+ width = this.canvas.width;
+ height = this.canvas.height;
+ } else if (width === 0) {
+ width = this.canvas.width * height / this.canvas.height;
+ } else if (height === 0) {
+ height = this.canvas.height * width / this.canvas.width;
+ }
+
+ width = Math.floor(width);
+ height = Math.floor(height);
+
+ var tempCanvas = document.createElement('canvas');
+ tempCanvas.width = width;
+ tempCanvas.height = height;
+ // prettier-ignore
+ tempCanvas.getContext('2d').drawImage(
+ this.canvas,
+ 0, 0, this.canvas.width, this.canvas.height,
+ 0, 0, tempCanvas.width, tempCanvas.height
+ );
+
+ // Resize the original canvas, which will clear its contents
+ this.canvas.width = this.width = width;
+ this.canvas.height = this.height = height;
+
+ //Copy the image back
+
+ // prettier-ignore
+ this.drawingContext.drawImage(
+ tempCanvas,
+ 0, 0, width, height,
+ 0, 0, width, height
+ );
+
+ if (this.pixels.length > 0) {
+ this.loadPixels();
+ }
+
+ this.setModified(true);
+};
+
+/**
+ * Copies a region of pixels from one image to another. If no
+ * srcImage is specified this is used as the source. If the source
+ * and destination regions aren't the same size, it will
+ * automatically resize source pixels to fit the specified
+ * target region.
+ *
+ * @method copy
+ * @param {p5.Image|p5.Element} srcImage source image
+ * @param {Integer} sx X coordinate of the source's upper left corner
+ * @param {Integer} sy Y coordinate of the source's upper left corner
+ * @param {Integer} sw source image width
+ * @param {Integer} sh source image height
+ * @param {Integer} dx X coordinate of the destination's upper left corner
+ * @param {Integer} dy Y coordinate of the destination's upper left corner
+ * @param {Integer} dw destination image width
+ * @param {Integer} dh destination image height
+ * @example
+ *
+ * var photo;
+ * var bricks;
+ * var x;
+ * var y;
+ *
+ * function preload() {
+ * photo = loadImage('assets/rockies.jpg');
+ * bricks = loadImage('assets/bricks.jpg');
+ * }
+ *
+ * function setup() {
+ * x = bricks.width / 2;
+ * y = bricks.height / 2;
+ * photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);
+ * image(photo, 0, 0);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains and smaller image on top of bricks at top left
+ *
+ */
+/**
+ * @method copy
+ * @param {Integer} sx
+ * @param {Integer} sy
+ * @param {Integer} sw
+ * @param {Integer} sh
+ * @param {Integer} dx
+ * @param {Integer} dy
+ * @param {Integer} dw
+ * @param {Integer} dh
+ */
+p5.Image.prototype.copy = function() {
+ var srcImage, sx, sy, sw, sh, dx, dy, dw, dh;
+ if (arguments.length === 9) {
+ srcImage = arguments[0];
+ sx = arguments[1];
+ sy = arguments[2];
+ sw = arguments[3];
+ sh = arguments[4];
+ dx = arguments[5];
+ dy = arguments[6];
+ dw = arguments[7];
+ dh = arguments[8];
+ } else if (arguments.length === 8) {
+ srcImage = this;
+ sx = arguments[0];
+ sy = arguments[1];
+ sw = arguments[2];
+ sh = arguments[3];
+ dx = arguments[4];
+ dy = arguments[5];
+ dw = arguments[6];
+ dh = arguments[7];
+ } else {
+ throw new Error('Signature not supported');
+ }
+ p5.Renderer2D._copyHelper(this, srcImage, sx, sy, sw, sh, dx, dy, dw, dh);
+};
+
+/**
+ * Masks part of an image from displaying by loading another
+ * image and using it's alpha channel as an alpha channel for
+ * this image.
+ *
+ * @method mask
+ * @param {p5.Image} srcImage source image
+ * @example
+ *
+ * var photo, maskImage;
+ * function preload() {
+ * photo = loadImage('assets/rockies.jpg');
+ * maskImage = loadImage('assets/mask2.png');
+ * }
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * photo.mask(maskImage);
+ * image(photo, 0, 0);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains with white at right
+ *
+ *
+ * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
+ *
+ */
+// TODO: - Accept an array of alpha values.
+// - Use other channels of an image. p5 uses the
+// blue channel (which feels kind of arbitrary). Note: at the
+// moment this method does not match native processings original
+// functionality exactly.
+p5.Image.prototype.mask = function(p5Image) {
+ if (p5Image === undefined) {
+ p5Image = this;
+ }
+ var currBlend = this.drawingContext.globalCompositeOperation;
+
+ var scaleFactor = 1;
+ if (p5Image instanceof p5.Renderer) {
+ scaleFactor = p5Image._pInst._pixelDensity;
+ }
+
+ var copyArgs = [
+ p5Image,
+ 0,
+ 0,
+ scaleFactor * p5Image.width,
+ scaleFactor * p5Image.height,
+ 0,
+ 0,
+ this.width,
+ this.height
+ ];
+
+ this.drawingContext.globalCompositeOperation = 'destination-in';
+ p5.Image.prototype.copy.apply(this, copyArgs);
+ this.drawingContext.globalCompositeOperation = currBlend;
+ this.setModified(true);
+};
+
+/**
+ * Applies an image filter to a p5.Image
+ *
+ * @method filter
+ * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT,
+ * POSTERIZE, BLUR, ERODE, DILATE or BLUR.
+ * See Filters.js for docs on
+ * each available filter
+ * @param {Number} [filterParam] an optional parameter unique
+ * to each filter, see above
+ * @example
+ *
+ * var photo1;
+ * var photo2;
+ *
+ * function preload() {
+ * photo1 = loadImage('assets/rockies.jpg');
+ * photo2 = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * photo2.filter('gray');
+ * image(photo1, 0, 0);
+ * image(photo2, width / 2, 0);
+ * }
+ *
+ *
+ * @alt
+ * 2 images of rocky mountains left one in color, right in black and white
+ *
+ */
+p5.Image.prototype.filter = function(operation, value) {
+ Filters.apply(this.canvas, Filters[operation.toLowerCase()], value);
+ this.setModified(true);
+};
+
+/**
+ * Copies a region of pixels from one image to another, using a specified
+ * blend mode to do the operation.
+ *
+ * @method blend
+ * @param {p5.Image} srcImage source image
+ * @param {Integer} sx X coordinate of the source's upper left corner
+ * @param {Integer} sy Y coordinate of the source's upper left corner
+ * @param {Integer} sw source image width
+ * @param {Integer} sh source image height
+ * @param {Integer} dx X coordinate of the destination's upper left corner
+ * @param {Integer} dy Y coordinate of the destination's upper left corner
+ * @param {Integer} dw destination image width
+ * @param {Integer} dh destination image height
+ * @param {Constant} blendMode the blend mode. either
+ * BLEND, DARKEST, LIGHTEST, DIFFERENCE,
+ * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
+ * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
+ *
+ * Available blend modes are: normal | multiply | screen | overlay |
+ * darken | lighten | color-dodge | color-burn | hard-light |
+ * soft-light | difference | exclusion | hue | saturation |
+ * color | luminosity
+ *
+ *
+ * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
+ * @example
+ *
+ * var mountains;
+ * var bricks;
+ *
+ * function preload() {
+ * mountains = loadImage('assets/rockies.jpg');
+ * bricks = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);
+ * image(mountains, 0, 0);
+ * image(bricks, 0, 0);
+ * }
+ *
+ *
+ * var mountains;
+ * var bricks;
+ *
+ * function preload() {
+ * mountains = loadImage('assets/rockies.jpg');
+ * bricks = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);
+ * image(mountains, 0, 0);
+ * image(bricks, 0, 0);
+ * }
+ *
+ *
+ * var mountains;
+ * var bricks;
+ *
+ * function preload() {
+ * mountains = loadImage('assets/rockies.jpg');
+ * bricks = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);
+ * image(mountains, 0, 0);
+ * image(bricks, 0, 0);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ *
+ */
+/**
+ * @method blend
+ * @param {Integer} sx
+ * @param {Integer} sy
+ * @param {Integer} sw
+ * @param {Integer} sh
+ * @param {Integer} dx
+ * @param {Integer} dy
+ * @param {Integer} dw
+ * @param {Integer} dh
+ * @param {Constant} blendMode
+ */
+p5.Image.prototype.blend = function() {
+ p5.prototype.blend.apply(this, arguments);
+ this.setModified(true);
+};
+
+/**
+ * helper method for web GL mode to indicate that an image has been
+ * changed or unchanged since last upload. gl texture upload will
+ * set this value to false after uploading the texture.
+ * @method setModified
+ * @param {boolean} val sets whether or not the image has been
+ * modified.
+ * @private
+ */
+p5.Image.prototype.setModified = function(val) {
+ this._modified = val; //enforce boolean?
+};
+
+/**
+ * helper method for web GL mode to figure out if the image
+ * has been modified and might need to be re-uploaded to texture
+ * memory between frames.
+ * @method isModified
+ * @private
+ * @return {boolean} a boolean indicating whether or not the
+ * image has been updated or modified since last texture upload.
+ */
+p5.Image.prototype.isModified = function() {
+ return this._modified;
+};
+
+/**
+ * Saves the image to a file and force the browser to download it.
+ * Accepts two strings for filename and file extension
+ * Supports png (default) and jpg.
+ *
+ * @method save
+ * @param {String} filename give your file a name
+ * @param {String} extension 'png' or 'jpg'
+ * @example
+ *
+ * var photo;
+ *
+ * function preload() {
+ * photo = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function draw() {
+ * image(photo, 0, 0);
+ * }
+ *
+ * function keyTyped() {
+ * if (key === 's') {
+ * photo.save('photo', 'png');
+ * }
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains.
+ *
+ */
+p5.Image.prototype.save = function(filename, extension) {
+ p5.prototype.saveCanvas(this.canvas, filename, extension);
+};
+
+module.exports = p5.Image;
+
+},{"../core/core":22,"./filters":41}],45:[function(_dereq_,module,exports){
+/**
+ * @module Image
+ * @submodule Pixels
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+var Filters = _dereq_('./filters');
+_dereq_('../color/p5.Color');
+
+/**
+ * Uint8ClampedArray
+ * containing the values for all the pixels in the display window.
+ * These values are numbers. This array is the size (include an appropriate
+ * factor for pixelDensity) of the display window x4,
+ * representing the R, G, B, A values in order for each pixel, moving from
+ * left to right across each row, then down each column. Retina and other
+ * high density displays will have more pixels[] (by a factor of
+ * pixelDensity^2).
+ * For example, if the image is 100x100 pixels, there will be 40,000. On a
+ * retina display, there will be 160,000.
+ *
+ * The first four values (indices 0-3) in the array will be the R, G, B, A
+ * values of the pixel at (0, 0). The second four values (indices 4-7) will
+ * contain the R, G, B, A values of the pixel at (1, 0). More generally, to
+ * set values for a pixel at (x, y):
+ * ```javascript
+ * var d = pixelDensity();
+ * for (var i = 0; i < d; i++) {
+ * for (var j = 0; j < d; j++) {
+ * // loop over
+ * idx = 4 * ((y * d + j) * width * d + (x * d + i));
+ * pixels[idx] = r;
+ * pixels[idx+1] = g;
+ * pixels[idx+2] = b;
+ * pixels[idx+3] = a;
+ * }
+ * }
+ * ```
+ * While the above method is complex, it is flexible enough to work with
+ * any pixelDensity. Note that set() will automatically take care of
+ * setting all the appropriate values in pixels[] for a given (x, y) at
+ * any pixelDensity, but the performance may not be as fast when lots of
+ * modifications are made to the pixel array.
+ *
+ * Before accessing this array, the data must loaded with the loadPixels()
+ * function. After the array data has been modified, the updatePixels()
+ * function must be run to update the changes.
+ *
+ * Note that this is not a standard javascript array. This means that
+ * standard javascript functions such as slice() or
+ * arrayCopy() do not
+ * work.
+ *
+ * @property {Number[]} pixels
+ * @example
+ *
+ *
+ * var pink = color(255, 102, 204);
+ * loadPixels();
+ * var d = pixelDensity();
+ * var halfImage = 4 * (width * d) * (height / 2 * d);
+ * for (var i = 0; i < halfImage; i += 4) {
+ * pixels[i] = red(pink);
+ * pixels[i + 1] = green(pink);
+ * pixels[i + 2] = blue(pink);
+ * pixels[i + 3] = alpha(pink);
+ * }
+ * updatePixels();
+ *
+ *
+ *
+ * @alt
+ * top half of canvas pink, bottom grey
+ *
+ */
+p5.prototype.pixels = [];
+
+/**
+ * Copies a region of pixels from one image to another, using a specified
+ * blend mode to do the operation.
+ *
+ * @method blend
+ * @param {p5.Image} srcImage source image
+ * @param {Integer} sx X coordinate of the source's upper left corner
+ * @param {Integer} sy Y coordinate of the source's upper left corner
+ * @param {Integer} sw source image width
+ * @param {Integer} sh source image height
+ * @param {Integer} dx X coordinate of the destination's upper left corner
+ * @param {Integer} dy Y coordinate of the destination's upper left corner
+ * @param {Integer} dw destination image width
+ * @param {Integer} dh destination image height
+ * @param {Constant} blendMode the blend mode. either
+ * BLEND, DARKEST, LIGHTEST, DIFFERENCE,
+ * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,
+ * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.
+ *
+ * @example
+ *
+ * var img0;
+ * var img1;
+ *
+ * function preload() {
+ * img0 = loadImage('assets/rockies.jpg');
+ * img1 = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * background(img0);
+ * image(img1, 0, 0);
+ * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);
+ * }
+ *
+ *
+ * var img0;
+ * var img1;
+ *
+ * function preload() {
+ * img0 = loadImage('assets/rockies.jpg');
+ * img1 = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * background(img0);
+ * image(img1, 0, 0);
+ * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);
+ * }
+ *
+ *
+ * var img0;
+ * var img1;
+ *
+ * function preload() {
+ * img0 = loadImage('assets/rockies.jpg');
+ * img1 = loadImage('assets/bricks_third.jpg');
+ * }
+ *
+ * function setup() {
+ * background(img0);
+ * image(img1, 0, 0);
+ * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ *
+ *
+ */
+/**
+ * @method blend
+ * @param {Integer} sx
+ * @param {Integer} sy
+ * @param {Integer} sw
+ * @param {Integer} sh
+ * @param {Integer} dx
+ * @param {Integer} dy
+ * @param {Integer} dw
+ * @param {Integer} dh
+ * @param {Constant} blendMode
+ */
+p5.prototype.blend = function() {
+ p5._validateParameters('blend', arguments);
+ if (this._renderer) {
+ this._renderer.blend.apply(this._renderer, arguments);
+ } else {
+ p5.Renderer2D.prototype.blend.apply(this, arguments);
+ }
+};
+
+/**
+ * Copies a region of the canvas to another region of the canvas
+ * and copies a region of pixels from an image used as the srcImg parameter
+ * into the canvas srcImage is specified this is used as the source. If
+ * the source and destination regions aren't the same size, it will
+ * automatically resize source pixels to fit the specified
+ * target region.
+ *
+ * @method copy
+ * @param {p5.Image|p5.Element} srcImage source image
+ * @param {Integer} sx X coordinate of the source's upper left corner
+ * @param {Integer} sy Y coordinate of the source's upper left corner
+ * @param {Integer} sw source image width
+ * @param {Integer} sh source image height
+ * @param {Integer} dx X coordinate of the destination's upper left corner
+ * @param {Integer} dy Y coordinate of the destination's upper left corner
+ * @param {Integer} dw destination image width
+ * @param {Integer} dh destination image height
+ *
+ * @example
+ *
+ * var img;
+ *
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * background(img);
+ * copy(img, 7, 22, 10, 10, 35, 25, 50, 50);
+ * stroke(255);
+ * noFill();
+ * // Rectangle shows area being copied
+ * rect(7, 22, 10, 10);
+ * }
+ *
+ *
+ * @alt
+ * image of rocky mountains. Brick images on left and right. Right overexposed
+ * image of rockies. Brickwall images on left and right. Right mortar transparent
+ * image of rockies. Brickwall images on left and right. Right translucent
+ *
+ */
+/**
+ * @method copy
+ * @param {Integer} sx
+ * @param {Integer} sy
+ * @param {Integer} sw
+ * @param {Integer} sh
+ * @param {Integer} dx
+ * @param {Integer} dy
+ * @param {Integer} dw
+ * @param {Integer} dh
+ */
+p5.prototype.copy = function() {
+ p5._validateParameters('copy', arguments);
+ p5.Renderer2D.prototype.copy.apply(this._renderer, arguments);
+};
+
+/**
+ * Applies a filter to the canvas.
+ *
+ *
+ * The presets options are:
+ *
+ *
+ * THRESHOLD
+ * Converts the image to black and white pixels depending if they are above or
+ * below the threshold defined by the level parameter. The parameter must be
+ * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.
+ *
+ *
+ * GRAY
+ * Converts any colors in the image to grayscale equivalents. No parameter
+ * is used.
+ *
+ *
+ * OPAQUE
+ * Sets the alpha channel to entirely opaque. No parameter is used.
+ *
+ *
+ * INVERT
+ * Sets each pixel to its inverse value. No parameter is used.
+ *
+ *
+ * POSTERIZE
+ * Limits each channel of the image to the number of colors specified as the
+ * parameter. The parameter can be set to values between 2 and 255, but
+ * results are most noticeable in the lower ranges.
+ *
+ *
+ * BLUR
+ * Executes a Gaussian blur with the level parameter specifying the extent
+ * of the blurring. If no parameter is used, the blur is equivalent to
+ * Gaussian blur of radius 1. Larger values increase the blur.
+ *
+ *
+ * ERODE
+ * Reduces the light areas. No parameter is used.
+ *
+ *
+ * DILATE
+ * Increases the light areas. No parameter is used.
+ *
+ * @method filter
+ * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT,
+ * POSTERIZE, BLUR, ERODE, DILATE or BLUR.
+ * See Filters.js for docs on
+ * each available filter
+ * @param {Number} [filterParam] an optional parameter unique
+ * to each filter, see above
+ *
+ * @example
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(THRESHOLD);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(GRAY);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(OPAQUE);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(INVERT);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(POSTERIZE, 3);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(DILATE);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(BLUR, 3);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/bricks.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * filter(ERODE);
+ * }
+ *
+ *
+ *
+ * @alt
+ * black and white image of a brick wall.
+ * greyscale image of a brickwall
+ * image of a brickwall
+ * jade colored image of a brickwall
+ * red and pink image of a brickwall
+ * image of a brickwall
+ * blurry image of a brickwall
+ * image of a brickwall
+ * image of a brickwall with less detail
+ *
+ */
+p5.prototype.filter = function(operation, value) {
+ p5._validateParameters('filter', arguments);
+ if (this.canvas !== undefined) {
+ Filters.apply(this.canvas, Filters[operation.toLowerCase()], value);
+ } else {
+ Filters.apply(this.elt, Filters[operation.toLowerCase()], value);
+ }
+};
+
+/**
+ * Returns an array of [R,G,B,A] values for any pixel or grabs a section of
+ * an image. If no parameters are specified, the entire image is returned.
+ * Use the x and y parameters to get the value of one pixel. Get a section of
+ * the display window by specifying additional w and h parameters. When
+ * getting an image, the x and y parameters define the coordinates for the
+ * upper-left corner of the image, regardless of the current imageMode().
+ *
+ * If the pixel requested is outside of the image window, [0,0,0,255] is
+ * returned. To get the numbers scaled according to the current color ranges
+ * and taking into account colorMode, use getColor instead of get.
+ *
+ * Getting the color of a single pixel with get(x, y) is easy, but not as fast
+ * as grabbing the data directly from pixels[]. The equivalent statement to
+ * get(x, y) using pixels[] with pixel density d is
+ *
+ * var x, y, d; // set these to the coordinates
+ * var off = (y * width + x) * d * 4;
+ * var components = [
+ * pixels[off],
+ * pixels[off + 1],
+ * pixels[off + 2],
+ * pixels[off + 3]
+ * ];
+ * print(components);
+ *
+ *
+ * See the reference for pixels[] for more information.
+ *
+ * @method get
+ * @param {Number} [x] x-coordinate of the pixel
+ * @param {Number} [y] y-coordinate of the pixel
+ * @param {Number} [w] width
+ * @param {Number} [h] height
+ * @return {Number[]|p5.Image} values of pixel at x,y in array format
+ * [R, G, B, A] or p5.Image
+ * @example
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * var c = get();
+ * image(c, width / 2, 0);
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ * function setup() {
+ * image(img, 0, 0);
+ * var c = get(50, 90);
+ * fill(c);
+ * noStroke();
+ * rect(25, 25, 50, 50);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 2 images of the rocky mountains, side-by-side
+ * Image of the rocky mountains with 50x50 green rect in center of canvas
+ *
+ */
+p5.prototype.get = function(x, y, w, h) {
+ return this._renderer.get(x, y, w, h);
+};
+
+/**
+ * Loads the pixel data for the display window into the pixels[] array. This
+ * function must always be called before reading from or writing to pixels[].
+ * Note that only changes made with set() or direct manipulation of pixels[]
+ * will occur.
+ *
+ * @method loadPixels
+ * @example
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * image(img, 0, 0);
+ * var d = pixelDensity();
+ * var halfImage = 4 * (img.width * d) * (img.height * d / 2);
+ * loadPixels();
+ * for (var i = 0; i < halfImage; i++) {
+ * pixels[i + halfImage] = pixels[i];
+ * }
+ * updatePixels();
+ * }
+ *
+ *
+ *
+ * @alt
+ * two images of the rocky mountains. one on top, one on bottom of canvas.
+ *
+ */
+p5.prototype.loadPixels = function() {
+ p5._validateParameters('loadPixels', arguments);
+ this._renderer.loadPixels();
+};
+
+/**
+ * Changes the color of any pixel, or writes an image directly to the
+ * display window.
+ * The x and y parameters specify the pixel to change and the c parameter
+ * specifies the color value. This can be a p5.Color object, or [R, G, B, A]
+ * pixel array. It can also be a single grayscale value.
+ * When setting an image, the x and y parameters define the coordinates for
+ * the upper-left corner of the image, regardless of the current imageMode().
+ *
+ *
+ * After using set(), you must call updatePixels() for your changes to appear.
+ * This should be called once all pixels have been set, and must be called before
+ * calling .get() or drawing the image.
+ *
+ * Setting the color of a single pixel with set(x, y) is easy, but not as
+ * fast as putting the data directly into pixels[]. Setting the pixels[]
+ * values directly may be complicated when working with a retina display,
+ * but will perform better when lots of pixels need to be set directly on
+ * every loop.
+ * See the reference for pixels[] for more information.
+ *
+ * @method set
+ * @param {Number} x x-coordinate of the pixel
+ * @param {Number} y y-coordinate of the pixel
+ * @param {Number|Number[]|Object} c insert a grayscale value | a pixel array |
+ * a p5.Color object | a p5.Image to copy
+ * @example
+ *
+ *
+ * var black = color(0);
+ * set(30, 20, black);
+ * set(85, 20, black);
+ * set(85, 75, black);
+ * set(30, 75, black);
+ * updatePixels();
+ *
+ *
+ *
+ *
+ *
+ * for (var i = 30; i < width - 15; i++) {
+ * for (var j = 20; j < height - 25; j++) {
+ * var c = color(204 - j, 153 - i, 0);
+ * set(i, j, c);
+ * }
+ * }
+ * updatePixels();
+ *
+ *
+ *
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * set(0, 0, img);
+ * updatePixels();
+ * line(0, 0, width, height);
+ * line(0, height, width, 0);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 4 black points in the shape of a square middle-right of canvas.
+ * square with orangey-brown gradient lightening at bottom right.
+ * image of the rocky mountains. with lines like an 'x' through the center.
+ */
+p5.prototype.set = function(x, y, imgOrCol) {
+ this._renderer.set(x, y, imgOrCol);
+};
+/**
+ * Updates the display window with the data in the pixels[] array.
+ * Use in conjunction with loadPixels(). If you're only reading pixels from
+ * the array, there's no need to call updatePixels() — updating is only
+ * necessary to apply changes. updatePixels() should be called anytime the
+ * pixels array is manipulated or set() is called, and only changes made with
+ * set() or direct changes to pixels[] will occur.
+ *
+ * @method updatePixels
+ * @param {Number} [x] x-coordinate of the upper-left corner of region
+ * to update
+ * @param {Number} [y] y-coordinate of the upper-left corner of region
+ * to update
+ * @param {Number} [w] width of region to update
+ * @param {Number} [h] height of region to update
+ * @example
+ *
+ *
+ * var img;
+ * function preload() {
+ * img = loadImage('assets/rockies.jpg');
+ * }
+ *
+ * function setup() {
+ * image(img, 0, 0);
+ * var d = pixelDensity();
+ * var halfImage = 4 * (img.width * d) * (img.height * d / 2);
+ * loadPixels();
+ * for (var i = 0; i < halfImage; i++) {
+ * pixels[i + halfImage] = pixels[i];
+ * }
+ * updatePixels();
+ * }
+ *
+ *
+ * @alt
+ * two images of the rocky mountains. one on top, one on bottom of canvas.
+ */
+p5.prototype.updatePixels = function(x, y, w, h) {
+ p5._validateParameters('updatePixels', arguments);
+ // graceful fail - if loadPixels() or set() has not been called, pixel
+ // array will be empty, ignore call to updatePixels()
+ if (this.pixels.length === 0) {
+ return;
+ }
+ this._renderer.updatePixels(x, y, w, h);
+};
+
+module.exports = p5;
+
+},{"../color/p5.Color":16,"../core/core":22,"./filters":41}],46:[function(_dereq_,module,exports){
+/**
+ * @module IO
+ * @submodule Input
+ * @for p5
+ * @requires core
+ */
+
+/* globals Request: false */
+/* globals Headers: false */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+_dereq_('whatwg-fetch');
+_dereq_('es6-promise').polyfill();
+var fetchJsonp = _dereq_('fetch-jsonp');
+_dereq_('../core/error_helpers');
+
+/**
+ * Loads a JSON file from a file or a URL, and returns an Object.
+ * Note that even if the JSON file contains an Array, an Object will be
+ * returned with index numbers as keys.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed. JSONP is supported via a polyfill and you
+ * can pass in as the second argument an object with definitions of the json
+ * callback following the syntax specified here.
+ *
+ * @method loadJSON
+ * @param {String} path name of the file or url to load
+ * @param {Object} [jsonpOptions] options object for jsonp related settings
+ * @param {String} [datatype] "json" or "jsonp"
+ * @param {function} [callback] function to be executed after
+ * loadJSON() completes, data is passed
+ * in as first argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @return {Object|Array} JSON data
+ * @example
+ *
+ * Calling loadJSON() inside preload() guarantees to complete the
+ * operation before setup() and draw() are called.
+ *
+ *
+ * // Examples use USGS Earthquake API:
+ * // https://earthquake.usgs.gov/fdsnws/event/1/#methods
+ * var earthquakes;
+ * function preload() {
+ * // Get the most recent earthquake in the database
+ * var url =
+ 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +
+ * 'summary/all_day.geojson';
+ * earthquakes = loadJSON(url);
+ * }
+ *
+ * function setup() {
+ * noLoop();
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * // Get the magnitude and name of the earthquake out of the loaded JSON
+ * var earthquakeMag = earthquakes.features[0].properties.mag;
+ * var earthquakeName = earthquakes.features[0].properties.place;
+ * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);
+ * textAlign(CENTER);
+ * text(earthquakeName, 0, height - 30, width, 30);
+ * }
+ *
+ *
+ *
+ * Outside of preload(), you may supply a callback function to handle the
+ * object:
+ *
+ * function setup() {
+ * noLoop();
+ * var url =
+ 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +
+ * 'summary/all_day.geojson';
+ * loadJSON(url, drawEarthquake);
+ * }
+ *
+ * function draw() {
+ * background(200);
+ * }
+ *
+ * function drawEarthquake(earthquakes) {
+ * // Get the magnitude and name of the earthquake out of the loaded JSON
+ * var earthquakeMag = earthquakes.features[0].properties.mag;
+ * var earthquakeName = earthquakes.features[0].properties.place;
+ * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);
+ * textAlign(CENTER);
+ * text(earthquakeName, 0, height - 30, width, 30);
+ * }
+ *
+ *
+ * @alt
+ * 50x50 ellipse that changes from black to white depending on the current humidity
+ * 50x50 ellipse that changes from black to white depending on the current humidity
+ *
+ */
+/**
+ * @method loadJSON
+ * @param {String} path
+ * @param {String} datatype
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ * @return {Object|Array}
+ */
+/**
+ * @method loadJSON
+ * @param {String} path
+ * @param {function} callback
+ * @param {function} [errorCallback]
+ * @return {Object|Array}
+ */
+p5.prototype.loadJSON = function() {
+ p5._validateParameters('loadJSON', arguments);
+ var path = arguments[0];
+ var callback;
+ var errorCallback;
+ var options;
+
+ var ret = {}; // object needed for preload
+ var t = 'json';
+
+ // check for explicit data type argument
+ for (var i = 1; i < arguments.length; i++) {
+ var arg = arguments[i];
+ if (typeof arg === 'string') {
+ if (arg === 'jsonp' || arg === 'json') {
+ t = arg;
+ }
+ } else if (typeof arg === 'function') {
+ if (!callback) {
+ callback = arg;
+ } else {
+ errorCallback = arg;
+ }
+ } else if (typeof arg === 'object' && arg.hasOwnProperty('jsonpCallback')) {
+ t = 'jsonp';
+ options = arg;
+ }
+ }
+
+ var self = this;
+ this.httpDo(
+ path,
+ 'GET',
+ options,
+ t,
+ function(resp) {
+ for (var k in resp) {
+ ret[k] = resp[k];
+ }
+ if (typeof callback !== 'undefined') {
+ callback(resp);
+ }
+
+ self._decrementPreload();
+ },
+ errorCallback
+ );
+
+ return ret;
+};
+
+/**
+ * Reads the contents of a file and creates a String array of its individual
+ * lines. If the name of the file is used as the parameter, as in the above
+ * example, the file must be located in the sketch directory/folder.
+ *
+ * Alternatively, the file maybe be loaded from anywhere on the local
+ * computer using an absolute path (something that starts with / on Unix and
+ * Linux, or a drive letter on Windows), or the filename parameter can be a
+ * URL for a file found on a network.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed.
+ *
+ * @method loadStrings
+ * @param {String} filename name of the file or url to load
+ * @param {function} [callback] function to be executed after loadStrings()
+ * completes, Array is passed in as first
+ * argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @return {String[]} Array of Strings
+ * @example
+ *
+ * Calling loadStrings() inside preload() guarantees to complete the
+ * operation before setup() and draw() are called.
+ *
+ *
+ * var result;
+ * function preload() {
+ * result = loadStrings('assets/test.txt');
+ * }
+
+ * function setup() {
+ * background(200);
+ * var ind = floor(random(result.length));
+ * text(result[ind], 10, 10, 80, 80);
+ * }
+ *
+ *
+ * Outside of preload(), you may supply a callback function to handle the
+ * object:
+ *
+ *
+ * function setup() {
+ * loadStrings('assets/test.txt', pickString);
+ * }
+ *
+ * function pickString(result) {
+ * background(200);
+ * var ind = floor(random(result.length));
+ * text(result[ind], 10, 10, 80, 80);
+ * }
+ *
+ *
+ * @alt
+ * randomly generated text from a file, for example "i smell like butter"
+ * randomly generated text from a file, for example "i have three feet"
+ *
+ */
+p5.prototype.loadStrings = function() {
+ p5._validateParameters('loadStrings', arguments);
+
+ var ret = [];
+ var callback, errorCallback;
+
+ for (var i = 1; i < arguments.length; i++) {
+ var arg = arguments[i];
+ if (typeof arg === 'function') {
+ if (typeof callback === 'undefined') {
+ callback = arg;
+ } else if (typeof errorCallback === 'undefined') {
+ errorCallback = arg;
+ }
+ }
+ }
+
+ var self = this;
+ p5.prototype.httpDo.call(
+ this,
+ arguments[0],
+ 'GET',
+ 'text',
+ function(data) {
+ var arr = data.match(/[^\r\n]+/g);
+ for (var k in arr) {
+ ret[k] = arr[k];
+ }
+
+ if (typeof callback !== 'undefined') {
+ callback(ret);
+ }
+
+ self._decrementPreload();
+ },
+ errorCallback
+ );
+
+ return ret;
+};
+
+/**
+ * Reads the contents of a file or URL and creates a p5.Table object with
+ * its values. If a file is specified, it must be located in the sketch's
+ * "data" folder. The filename parameter can also be a URL to a file found
+ * online. By default, the file is assumed to be comma-separated (in CSV
+ * format). Table only looks for a header row if the 'header' option is
+ * included.
+ *
+ * Possible options include:
+ *
+ * - csv - parse the table as comma-separated values
+ * - tsv - parse the table as tab-separated values
+ * - header - this table has a header (title) row
+ *
+ *
+ *
+ * When passing in multiple options, pass them in as separate parameters,
+ * seperated by commas. For example:
+ *
+ *
+ * loadTable('my_csv_file.csv', 'csv', 'header');
+ *
+ *
+ *
+ * All files loaded and saved use UTF-8 encoding.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed. Calling loadTable() inside preload()
+ * guarantees to complete the operation before setup() and draw() are called.
+ *
Outside of preload(), you may supply a callback function to handle the
+ * object:
+ *
+ *
+ * @method loadTable
+ * @param {String} filename name of the file or URL to load
+ * @param {String} options "header" "csv" "tsv"
+ * @param {function} [callback] function to be executed after
+ * loadTable() completes. On success, the
+ * Table object is passed in as the
+ * first argument.
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @return {Object} Table object containing data
+ *
+ * @example
+ *
+ *
+ * // Given the following CSV file called "mammals.csv"
+ * // located in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * //the file can be remote
+ * //table = loadTable("http://p5js.org/reference/assets/mammals.csv",
+ * // "csv", "header");
+ * }
+ *
+ * function setup() {
+ * //count the columns
+ * print(table.getRowCount() + ' total rows in table');
+ * print(table.getColumnCount() + ' total columns in table');
+ *
+ * print(table.getColumn('name'));
+ * //["Goat", "Leopard", "Zebra"]
+ *
+ * //cycle through the table
+ * for (var r = 0; r < table.getRowCount(); r++)
+ * for (var c = 0; c < table.getColumnCount(); c++) {
+ * print(table.getString(r, c));
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * randomly generated text from a file, for example "i smell like butter"
+ * randomly generated text from a file, for example "i have three feet"
+ *
+ */
+/**
+ * @method loadTable
+ * @param {String} filename
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ * @return {Object}
+ */
+p5.prototype.loadTable = function(path) {
+ var callback;
+ var errorCallback;
+ var options = [];
+ var header = false;
+ var ext = path.substring(path.lastIndexOf('.') + 1, path.length);
+ var sep = ',';
+ var separatorSet = false;
+
+ if (ext === 'tsv') {
+ //Only need to check extension is tsv because csv is default
+ sep = '\t';
+ }
+
+ for (var i = 1; i < arguments.length; i++) {
+ if (typeof arguments[i] === 'function') {
+ if (typeof callback === 'undefined') {
+ callback = arguments[i];
+ } else if (typeof errorCallback === 'undefined') {
+ errorCallback = arguments[i];
+ }
+ } else if (typeof arguments[i] === 'string') {
+ options.push(arguments[i]);
+ if (arguments[i] === 'header') {
+ header = true;
+ }
+ if (arguments[i] === 'csv') {
+ if (separatorSet) {
+ throw new Error('Cannot set multiple separator types.');
+ } else {
+ sep = ',';
+ separatorSet = true;
+ }
+ } else if (arguments[i] === 'tsv') {
+ if (separatorSet) {
+ throw new Error('Cannot set multiple separator types.');
+ } else {
+ sep = '\t';
+ separatorSet = true;
+ }
+ }
+ }
+ }
+
+ var t = new p5.Table();
+
+ var self = this;
+ this.httpDo(
+ path,
+ 'GET',
+ 'text',
+ function(resp) {
+ var state = {};
+
+ // define constants
+ var PRE_TOKEN = 0,
+ MID_TOKEN = 1,
+ POST_TOKEN = 2,
+ POST_RECORD = 4;
+
+ var QUOTE = '"',
+ CR = '\r',
+ LF = '\n';
+
+ var records = [];
+ var offset = 0;
+ var currentRecord = null;
+ var currentChar;
+
+ var tokenBegin = function() {
+ state.currentState = PRE_TOKEN;
+ state.token = '';
+ };
+
+ var tokenEnd = function() {
+ currentRecord.push(state.token);
+ tokenBegin();
+ };
+
+ var recordBegin = function() {
+ state.escaped = false;
+ currentRecord = [];
+ tokenBegin();
+ };
+
+ var recordEnd = function() {
+ state.currentState = POST_RECORD;
+ records.push(currentRecord);
+ currentRecord = null;
+ };
+
+ for (;;) {
+ currentChar = resp[offset++];
+
+ // EOF
+ if (currentChar == null) {
+ if (state.escaped) {
+ throw new Error('Unclosed quote in file.');
+ }
+ if (currentRecord) {
+ tokenEnd();
+ recordEnd();
+ break;
+ }
+ }
+ if (currentRecord === null) {
+ recordBegin();
+ }
+
+ // Handle opening quote
+ if (state.currentState === PRE_TOKEN) {
+ if (currentChar === QUOTE) {
+ state.escaped = true;
+ state.currentState = MID_TOKEN;
+ continue;
+ }
+ state.currentState = MID_TOKEN;
+ }
+
+ // mid-token and escaped, look for sequences and end quote
+ if (state.currentState === MID_TOKEN && state.escaped) {
+ if (currentChar === QUOTE) {
+ if (resp[offset] === QUOTE) {
+ state.token += QUOTE;
+ offset++;
+ } else {
+ state.escaped = false;
+ state.currentState = POST_TOKEN;
+ }
+ } else if (currentChar === CR) {
+ continue;
+ } else {
+ state.token += currentChar;
+ }
+ continue;
+ }
+
+ // fall-through: mid-token or post-token, not escaped
+ if (currentChar === CR) {
+ if (resp[offset] === LF) {
+ offset++;
+ }
+ tokenEnd();
+ recordEnd();
+ } else if (currentChar === LF) {
+ tokenEnd();
+ recordEnd();
+ } else if (currentChar === sep) {
+ tokenEnd();
+ } else if (state.currentState === MID_TOKEN) {
+ state.token += currentChar;
+ }
+ }
+
+ // set up column names
+ if (header) {
+ t.columns = records.shift();
+ } else {
+ for (i = 0; i < records[0].length; i++) {
+ t.columns[i] = 'null';
+ }
+ }
+ var row;
+ for (i = 0; i < records.length; i++) {
+ //Handles row of 'undefined' at end of some CSVs
+ if (records[i].length === 1) {
+ if (records[i][0] === 'undefined' || records[i][0] === '') {
+ continue;
+ }
+ }
+ row = new p5.TableRow();
+ row.arr = records[i];
+ row.obj = makeObject(records[i], t.columns);
+ t.addRow(row);
+ }
+ if (typeof callback === 'function') {
+ callback(t);
+ }
+
+ self._decrementPreload();
+ },
+ function(err) {
+ // Error handling
+ p5._friendlyFileLoadError(2, path);
+
+ if (errorCallback) {
+ errorCallback(err);
+ } else {
+ throw err;
+ }
+ }
+ );
+
+ return t;
+};
+
+// helper function to turn a row into a JSON object
+function makeObject(row, headers) {
+ var ret = {};
+ headers = headers || [];
+ if (typeof headers === 'undefined') {
+ for (var j = 0; j < row.length; j++) {
+ headers[j.toString()] = j;
+ }
+ }
+ for (var i = 0; i < headers.length; i++) {
+ var key = headers[i];
+ var val = row[i];
+ ret[key] = val;
+ }
+ return ret;
+}
+
+function parseXML(two) {
+ var one = new p5.XML();
+ var children = two.childNodes;
+ if (children && children.length) {
+ for (var i = 0; i < children.length; i++) {
+ var node = parseXML(children[i]);
+ one.addChild(node);
+ }
+ one.setName(two.nodeName);
+ one._setCont(two.textContent);
+ one._setAttributes(two);
+ for (var j = 0; j < one.children.length; j++) {
+ one.children[j].parent = one;
+ }
+ return one;
+ } else {
+ one.setName(two.nodeName);
+ one._setCont(two.textContent);
+ one._setAttributes(two);
+ return one;
+ }
+}
+
+/**
+ * Reads the contents of a file and creates an XML object with its values.
+ * If the name of the file is used as the parameter, as in the above example,
+ * the file must be located in the sketch directory/folder.
+ *
+ * Alternatively, the file maybe be loaded from anywhere on the local
+ * computer using an absolute path (something that starts with / on Unix and
+ * Linux, or a drive letter on Windows), or the filename parameter can be a
+ * URL for a file found on a network.
+ *
+ * This method is asynchronous, meaning it may not finish before the next
+ * line in your sketch is executed. Calling loadXML() inside preload()
+ * guarantees to complete the operation before setup() and draw() are called.
+ *
+ * Outside of preload(), you may supply a callback function to handle the
+ * object.
+ *
+ * @method loadXML
+ * @param {String} filename name of the file or URL to load
+ * @param {function} [callback] function to be executed after loadXML()
+ * completes, XML object is passed in as
+ * first argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @return {Object} XML object containing data
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var children = xml.getChildren('animal');
+ *
+ * for (var i = 0; i < children.length; i++) {
+ * var id = children[i].getNum('id');
+ * var coloring = children[i].getString('species');
+ * var name = children[i].getContent();
+ * print(id + ', ' + coloring + ', ' + name);
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // 0, Capra hircus, Goat
+ * // 1, Panthera pardus, Leopard
+ * // 2, Equus zebra, Zebra
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.prototype.loadXML = function() {
+ var ret = {};
+ var callback, errorCallback;
+
+ for (var i = 1; i < arguments.length; i++) {
+ var arg = arguments[i];
+ if (typeof arg === 'function') {
+ if (typeof callback === 'undefined') {
+ callback = arg;
+ } else if (typeof errorCallback === 'undefined') {
+ errorCallback = arg;
+ }
+ }
+ }
+
+ var self = this;
+ this.httpDo(
+ arguments[0],
+ 'GET',
+ 'xml',
+ function(xml) {
+ for (var key in xml) {
+ ret[key] = xml[key];
+ }
+ if (typeof callback !== 'undefined') {
+ callback(ret);
+ }
+
+ self._decrementPreload();
+ },
+ errorCallback
+ );
+
+ return ret;
+};
+
+/**
+ * @method loadBytes
+ * @param {string} file name of the file or URL to load
+ * @param {function} [callback] function to be executed after loadBytes()
+ * completes
+ * @param {function} [errorCallback] function to be executed if there
+ * is an error
+ * @returns {Object} an object whose 'bytes' property will be the loaded buffer
+ *
+ * @example
+ *
+ * var data;
+ *
+ * function preload() {
+ * data = loadBytes('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * for (var i = 0; i < 5; i++) {
+ * console.log(data.bytes[i].toString(16));
+ * }
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.prototype.loadBytes = function(file, callback, errorCallback) {
+ var ret = {};
+
+ var self = this;
+ this.httpDo(
+ file,
+ 'GET',
+ 'arrayBuffer',
+ function(arrayBuffer) {
+ ret.bytes = new Uint8Array(arrayBuffer);
+
+ if (typeof callback === 'function') {
+ callback(ret);
+ }
+
+ self._decrementPreload();
+ },
+ errorCallback
+ );
+ return ret;
+};
+
+/**
+ * Method for executing an HTTP GET request. If data type is not specified,
+ * p5 will try to guess based on the URL, defaulting to text. This is equivalent to
+ * calling httpDo(path, 'GET'). The 'binary' datatype will return
+ * a Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer
+ * which can be used to initialize typed arrays (such as Uint8Array).
+ *
+ * @method httpGet
+ * @param {String} path name of the file or url to load
+ * @param {String} [datatype] "json", "jsonp", "binary", "arrayBuffer",
+ * "xml", or "text"
+ * @param {Object|Boolean} [data] param data passed sent with request
+ * @param {function} [callback] function to be executed after
+ * httpGet() completes, data is passed in
+ * as first argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ * @example
+ *
+ * // Examples use USGS Earthquake API:
+ * // https://earthquake.usgs.gov/fdsnws/event/1/#methods
+ * var earthquakes;
+ * function preload() {
+ * // Get the most recent earthquake in the database
+ * var url =
+ 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +
+ * 'format=geojson&limit=1&orderby=time';
+ * httpGet(url, 'jsonp', false, function(response) {
+ * // when the HTTP request completes, populate the variable that holds the
+ * // earthquake data used in the visualization.
+ * earthquakes = response;
+ * });
+ * }
+ *
+ * function draw() {
+ * if (!earthquakes) {
+ * // Wait until the earthquake data has loaded before drawing.
+ * return;
+ * }
+ * background(200);
+ * // Get the magnitude and name of the earthquake out of the loaded JSON
+ * var earthquakeMag = earthquakes.features[0].properties.mag;
+ * var earthquakeName = earthquakes.features[0].properties.place;
+ * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);
+ * textAlign(CENTER);
+ * text(earthquakeName, 0, height - 30, width, 30);
+ * noLoop();
+ * }
+ *
+ */
+/**
+ * @method httpGet
+ * @param {String} path
+ * @param {Object|Boolean} data
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ */
+/**
+ * @method httpGet
+ * @param {String} path
+ * @param {function} callback
+ * @param {function} [errorCallback]
+ */
+p5.prototype.httpGet = function() {
+ p5._validateParameters('httpGet', arguments);
+
+ var args = Array.prototype.slice.call(arguments);
+ args.splice(1, 0, 'GET');
+ p5.prototype.httpDo.apply(this, args);
+};
+
+/**
+ * Method for executing an HTTP POST request. If data type is not specified,
+ * p5 will try to guess based on the URL, defaulting to text. This is equivalent to
+ * calling httpDo(path, 'POST').
+ *
+ * @method httpPost
+ * @param {String} path name of the file or url to load
+ * @param {String} [datatype] "json", "jsonp", "xml", or "text".
+ * If omitted, httpPost() will guess.
+ * @param {Object|Boolean} [data] param data passed sent with request
+ * @param {function} [callback] function to be executed after
+ * httpPost() completes, data is passed in
+ * as first argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ *
+ * @example
+ *
+ *
+ * // Examples use jsonplaceholder.typicode.com for a Mock Data API
+ *
+ * var url = 'https://jsonplaceholder.typicode.com/posts';
+ * var postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' };
+ *
+ * function setup() {
+ * createCanvas(800, 800);
+ * }
+ *
+ * function mousePressed() {
+ * // Pick new random color values
+ * var r = random(255);
+ * var g = random(255);
+ * var b = random(255);
+ *
+ * httpPost(url, 'json', postData, function(result) {
+ * strokeWeight(2);
+ * stroke(r, g, b);
+ * fill(r, g, b, 127);
+ * ellipse(mouseX, mouseY, 200, 200);
+ * text(result.body, mouseX, mouseY);
+ * });
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var url = 'https://invalidURL'; // A bad URL that will cause errors
+ * var postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' };
+ *
+ * function setup() {
+ * createCanvas(800, 800);
+ * }
+ *
+ * function mousePressed() {
+ * // Pick new random color values
+ * var r = random(255);
+ * var g = random(255);
+ * var b = random(255);
+ *
+ * httpPost(
+ * url,
+ * 'json',
+ * postData,
+ * function(result) {
+ * // ... won't be called
+ * },
+ * function(error) {
+ * strokeWeight(2);
+ * stroke(r, g, b);
+ * fill(r, g, b, 127);
+ * text(error.toString(), mouseX, mouseY);
+ * }
+ * );
+ * }
+ *
+ *
+ */
+/**
+ * @method httpPost
+ * @param {String} path
+ * @param {Object|Boolean} data
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ */
+/**
+ * @method httpPost
+ * @param {String} path
+ * @param {function} callback
+ * @param {function} [errorCallback]
+ */
+p5.prototype.httpPost = function() {
+ p5._validateParameters('httpPost', arguments);
+
+ var args = Array.prototype.slice.call(arguments);
+ args.splice(1, 0, 'POST');
+ p5.prototype.httpDo.apply(this, args);
+};
+
+/**
+ * Method for executing an HTTP request. If data type is not specified,
+ * p5 will try to guess based on the URL, defaulting to text.
+ * For more advanced use, you may also pass in the path as the first argument
+ * and a object as the second argument, the signature follows the one specified
+ * in the Fetch API specification.
+ *
+ * @method httpDo
+ * @param {String} path name of the file or url to load
+ * @param {String} [method] either "GET", "POST", or "PUT",
+ * defaults to "GET"
+ * @param {String} [datatype] "json", "jsonp", "xml", or "text"
+ * @param {Object} [data] param data passed sent with request
+ * @param {function} [callback] function to be executed after
+ * httpGet() completes, data is passed in
+ * as first argument
+ * @param {function} [errorCallback] function to be executed if
+ * there is an error, response is passed
+ * in as first argument
+ *
+ *
+ * @example
+ *
+ *
+ * // Examples use USGS Earthquake API:
+ * // https://earthquake.usgs.gov/fdsnws/event/1/#methods
+ *
+ * // displays an animation of all USGS earthquakes
+ * var earthquakes;
+ * var eqFeatureIndex = 0;
+ *
+ * function preload() {
+ * var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';
+ * httpDo(
+ * url,
+ * {
+ * method: 'GET',
+ * // Other Request options, like special headers for apis
+ * headers: { authorization: 'Bearer secretKey' }
+ * },
+ * function(res) {
+ * earthquakes = res;
+ * }
+ * );
+ * }
+ *
+ * function draw() {
+ * // wait until the data is loaded
+ * if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {
+ * return;
+ * }
+ * clear();
+ *
+ * var feature = earthquakes.features[eqFeatureIndex];
+ * var mag = feature.properties.mag;
+ * var rad = mag / 11 * ((width + height) / 2);
+ * fill(255, 0, 0, 100);
+ * ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);
+ *
+ * if (eqFeatureIndex >= earthquakes.features.length) {
+ * eqFeatureIndex = 0;
+ * } else {
+ * eqFeatureIndex += 1;
+ * }
+ * }
+ *
+ *
+ */
+/**
+ * @method httpDo
+ * @param {String} path
+ * @param {Object} options Request object options as documented in the
+ * "fetch" API
+ * reference
+ * @param {function} [callback]
+ * @param {function} [errorCallback]
+ */
+p5.prototype.httpDo = function() {
+ var type;
+ var callback;
+ var errorCallback;
+ var request;
+ var jsonpOptions = {};
+ var cbCount = 0;
+ var contentType = 'text/plain';
+ // Trim the callbacks off the end to get an idea of how many arguments are passed
+ for (var i = arguments.length - 1; i > 0; i--) {
+ if (typeof arguments[i] === 'function') {
+ cbCount++;
+ } else {
+ break;
+ }
+ }
+ // The number of arguments minus callbacks
+ var argsCount = arguments.length - cbCount;
+ var path = arguments[0];
+ if (
+ argsCount === 2 &&
+ typeof path === 'string' &&
+ typeof arguments[1] === 'object'
+ ) {
+ // Intended for more advanced use, pass in Request parameters directly
+ request = new Request(path, arguments[1]);
+ callback = arguments[2];
+ errorCallback = arguments[3];
+ } else {
+ // Provided with arguments
+ var method = 'GET';
+ var data;
+
+ for (var j = 1; j < arguments.length; j++) {
+ var a = arguments[j];
+ if (typeof a === 'string') {
+ if (a === 'GET' || a === 'POST' || a === 'PUT' || a === 'DELETE') {
+ method = a;
+ } else if (
+ a === 'json' ||
+ a === 'jsonp' ||
+ a === 'binary' ||
+ a === 'arrayBuffer' ||
+ a === 'xml' ||
+ a === 'text'
+ ) {
+ type = a;
+ } else {
+ data = a;
+ }
+ } else if (typeof a === 'number') {
+ data = a.toString();
+ } else if (typeof a === 'object') {
+ if (a.hasOwnProperty('jsonpCallback')) {
+ for (var attr in a) {
+ jsonpOptions[attr] = a[attr];
+ }
+ } else {
+ data = JSON.stringify(a);
+ contentType = 'application/json';
+ }
+ } else if (typeof a === 'function') {
+ if (!callback) {
+ callback = a;
+ } else {
+ errorCallback = a;
+ }
+ }
+ }
+
+ request = new Request(path, {
+ method: method,
+ mode: 'cors',
+ body: data,
+ headers: new Headers({
+ 'Content-Type': contentType
+ })
+ });
+ }
+
+ // do some sort of smart type checking
+ if (!type) {
+ if (path.indexOf('json') !== -1) {
+ type = 'json';
+ } else if (path.indexOf('xml') !== -1) {
+ type = 'xml';
+ } else {
+ type = 'text';
+ }
+ }
+
+ (type === 'jsonp' ? fetchJsonp(path, jsonpOptions) : fetch(request))
+ .then(function(res) {
+ if (!res.ok) throw res;
+
+ switch (type) {
+ case 'json':
+ return res.json();
+ case 'binary':
+ return res.blob();
+ case 'arrayBuffer':
+ return res.arrayBuffer();
+ case 'xml':
+ return res.text().then(function(text) {
+ var parser = new DOMParser();
+ var xml = parser.parseFromString(text, 'text/xml');
+ return parseXML(xml.documentElement);
+ });
+ default:
+ return res.text();
+ }
+ })
+ .then(callback || function() {})
+ .catch(errorCallback || console.error);
+};
+
+/**
+ * @module IO
+ * @submodule Output
+ * @for p5
+ */
+
+window.URL = window.URL || window.webkitURL;
+
+// private array of p5.PrintWriter objects
+p5.prototype._pWriters = [];
+
+/**
+ * @method createWriter
+ * @param {String} name name of the file to be created
+ * @param {String} [extension]
+ * @return {p5.PrintWriter}
+ * @example
+ *
+ *
+ * createButton('save')
+ * .position(10, 10)
+ * .mousePressed(function() {
+ * var writer = createWriter('squares.txt');
+ * for (var i = 0; i < 10; i++) {
+ * writer.print(i * i);
+ * }
+ * writer.close();
+ * writer.clear();
+ * });
+ *
+ *
+ */
+p5.prototype.createWriter = function(name, extension) {
+ var newPW;
+ // check that it doesn't already exist
+ for (var i in p5.prototype._pWriters) {
+ if (p5.prototype._pWriters[i].name === name) {
+ // if a p5.PrintWriter w/ this name already exists...
+ // return p5.prototype._pWriters[i]; // return it w/ contents intact.
+ // or, could return a new, empty one with a unique name:
+ newPW = new p5.PrintWriter(name + this.millis(), extension);
+ p5.prototype._pWriters.push(newPW);
+ return newPW;
+ }
+ }
+ newPW = new p5.PrintWriter(name, extension);
+ p5.prototype._pWriters.push(newPW);
+ return newPW;
+};
+
+/**
+ * @class p5.PrintWriter
+ * @param {String} filename
+ * @param {String} [extension]
+ */
+p5.PrintWriter = function(filename, extension) {
+ var self = this;
+ this.name = filename;
+ this.content = '';
+ //Changed to write because it was being overloaded by function below.
+ /**
+ * Writes data to the PrintWriter stream
+ * @method write
+ * @param {Array} data all data to be written by the PrintWriter
+ * @example
+ *
+ *
+ * // creates a file called 'newFile.txt'
+ * var writer = createWriter('newFile.txt');
+ * // write 'Hello world!'' to the file
+ * writer.write(['Hello world!']);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // creates a file called 'newFile2.txt'
+ * var writer = createWriter('newFile2.txt');
+ * // write 'apples,bananas,123' to the file
+ * writer.write(['apples', 'bananas', 123]);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // creates a file called 'newFile3.txt'
+ * var writer = createWriter('newFile3.txt');
+ * // write 'My name is: Teddy' to the file
+ * writer.write('My name is:');
+ * writer.write(' Teddy');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ */
+ this.write = function(data) {
+ this.content += data;
+ };
+ /**
+ * Writes data to the PrintWriter stream, and adds a new line at the end
+ * @method print
+ * @param {Array} data all data to be printed by the PrintWriter
+ * @example
+ *
+ *
+ * // creates a file called 'newFile.txt'
+ * var writer = createWriter('newFile.txt');
+ * // creates a file containing
+ * // My name is:
+ * // Teddy
+ * writer.print('My name is:');
+ * writer.print('Teddy');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * var writer;
+ *
+ * function setup() {
+ * createCanvas(400, 400);
+ * // create a PrintWriter
+ * writer = createWriter('newFile.txt');
+ * }
+ *
+ * function draw() {
+ * // print all mouseX and mouseY coordinates to the stream
+ * writer.print([mouseX, mouseY]);
+ * }
+ *
+ * function mouseClicked() {
+ * // close the PrintWriter and save the file
+ * writer.close();
+ * }
+ *
+ *
+ */
+ this.print = function(data) {
+ this.content += data + '\n';
+ };
+ /**
+ * Clears the data already written to the PrintWriter object
+ * @method clear
+ * @example
+ *
+ * // create writer object
+ * var writer = createWriter('newFile.txt');
+ * writer.write(['clear me']);
+ * // clear writer object here
+ * writer.clear();
+ * // close writer
+ * writer.close();
+ *
+ *
+ */
+ this.clear = function() {
+ this.content = '';
+ };
+ /**
+ * Closes the PrintWriter
+ * @method close
+ * @example
+ *
+ *
+ * // create a file called 'newFile.txt'
+ * var writer = createWriter('newFile.txt');
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ *
+ *
+ * // create a file called 'newFile2.txt'
+ * var writer = createWriter('newFile2.txt');
+ * // write some data to the file
+ * writer.write([100, 101, 102]);
+ * // close the PrintWriter and save the file
+ * writer.close();
+ *
+ *
+ */
+ this.close = function() {
+ // convert String to Array for the writeFile Blob
+ var arr = [];
+ arr.push(this.content);
+ p5.prototype.writeFile(arr, filename, extension);
+ // remove from _pWriters array and delete self
+ for (var i in p5.prototype._pWriters) {
+ if (p5.prototype._pWriters[i].name === this.name) {
+ // remove from _pWriters array
+ p5.prototype._pWriters.splice(i, 1);
+ }
+ }
+ self.clear();
+ self = {};
+ };
+};
+
+/**
+ * @module IO
+ * @submodule Output
+ * @for p5
+ */
+
+// object, filename, options --> saveJSON, saveStrings,
+// filename, [extension] [canvas] --> saveImage
+
+/**
+ * Save an image, text, json, csv, wav, or html. Prompts download to
+ * the client's computer. Note that it is not recommended to call save()
+ * within draw if it's looping, as the save() function will open a new save
+ * dialog every frame.
+ * The default behavior is to save the canvas as an image. You can
+ * optionally specify a filename.
+ * For example:
+ *
+ * save();
+ * save('myCanvas.jpg'); // save a specific canvas with a filename
+ *
+ *
+ * Alternately, the first parameter can be a pointer to a canvas
+ * p5.Element, an Array of Strings,
+ * an Array of JSON, a JSON object, a p5.Table, a p5.Image, or a
+ * p5.SoundFile (requires p5.sound). The second parameter is a filename
+ * (including extension). The third parameter is for options specific
+ * to this type of object. This method will save a file that fits the
+ * given paramaters. For example:
+ *
+ *
+ * // Saves canvas as an image
+ * save('myCanvas.jpg');
+ *
+ * // Saves pImage as a png image
+ * var img = createImage(10, 10);
+ * save(img, 'my.png');
+ *
+ * // Saves canvas as an image
+ * var cnv = createCanvas(100, 100);
+ * save(cnv, 'myCanvas.jpg');
+ *
+ * // Saves p5.Renderer object as an image
+ * var gb = createGraphics(100, 100);
+ * save(gb, 'myGraphics.jpg');
+ *
+ * var myTable = new p5.Table();
+ *
+ * // Saves table as html file
+ * save(myTable, 'myTable.html');
+ *
+ * // Comma Separated Values
+ * save(myTable, 'myTable.csv');
+ *
+ * // Tab Separated Values
+ * save(myTable, 'myTable.tsv');
+ *
+ * var myJSON = { a: 1, b: true };
+ *
+ * // Saves pretty JSON
+ * save(myJSON, 'my.json');
+ *
+ * // Optimizes JSON filesize
+ * save(myJSON, 'my.json', true);
+ *
+ * // Saves array of strings to a text file with line breaks after each item
+ * var arrayOfStrings = ['a', 'b'];
+ * save(arrayOfStrings, 'my.txt');
+ *
+ *
+ * @method save
+ * @param {Object|String} [objectOrFilename] If filename is provided, will
+ * save canvas as an image with
+ * either png or jpg extension
+ * depending on the filename.
+ * If object is provided, will
+ * save depending on the object
+ * and filename (see examples
+ * above).
+ * @param {String} [filename] If an object is provided as the first
+ * parameter, then the second parameter
+ * indicates the filename,
+ * and should include an appropriate
+ * file extension (see examples above).
+ * @param {Boolean|String} [options] Additional options depend on
+ * filetype. For example, when saving JSON,
+ * true indicates that the
+ * output will be optimized for filesize,
+ * rather than readability.
+ */
+p5.prototype.save = function(object, _filename, _options) {
+ // parse the arguments and figure out which things we are saving
+ var args = arguments;
+ // =================================================
+ // OPTION 1: saveCanvas...
+
+ // if no arguments are provided, save canvas
+ var cnv = this._curElement.elt;
+ if (args.length === 0) {
+ p5.prototype.saveCanvas(cnv);
+ return;
+ } else if (args[0] instanceof p5.Renderer || args[0] instanceof p5.Graphics) {
+ // otherwise, parse the arguments
+
+ // if first param is a p5Graphics, then saveCanvas
+ p5.prototype.saveCanvas(args[0].elt, args[1], args[2]);
+ return;
+ } else if (args.length === 1 && typeof args[0] === 'string') {
+ // if 1st param is String and only one arg, assume it is canvas filename
+ p5.prototype.saveCanvas(cnv, args[0]);
+ } else {
+ // =================================================
+ // OPTION 2: extension clarifies saveStrings vs. saveJSON
+ var extension = _checkFileExtension(args[1], args[2])[1];
+ switch (extension) {
+ case 'json':
+ p5.prototype.saveJSON(args[0], args[1], args[2]);
+ return;
+ case 'txt':
+ p5.prototype.saveStrings(args[0], args[1], args[2]);
+ return;
+ // =================================================
+ // OPTION 3: decide based on object...
+ default:
+ if (args[0] instanceof Array) {
+ p5.prototype.saveStrings(args[0], args[1], args[2]);
+ } else if (args[0] instanceof p5.Table) {
+ p5.prototype.saveTable(args[0], args[1], args[2]);
+ } else if (args[0] instanceof p5.Image) {
+ p5.prototype.saveCanvas(args[0].canvas, args[1]);
+ } else if (args[0] instanceof p5.SoundFile) {
+ p5.prototype.saveSound(args[0], args[1], args[2], args[3]);
+ }
+ }
+ }
+};
+
+/**
+ * Writes the contents of an Array or a JSON object to a .json file.
+ * The file saving process and location of the saved file will
+ * vary between web browsers.
+ *
+ * @method saveJSON
+ * @param {Array|Object} json
+ * @param {String} filename
+ * @param {Boolean} [optimize] If true, removes line breaks
+ * and spaces from the output
+ * file to optimize filesize
+ * (but not readability).
+ * @example
+ *
+ * var json = {}; // new JSON Object
+ *
+ * json.id = 0;
+ * json.species = 'Panthera leo';
+ * json.name = 'Lion';
+ *
+ * createButton('save')
+ * .position(10, 10)
+ * .mousePressed(function() {
+ * saveJSON(json, 'lion.json');
+ * });
+ *
+ * // saves the following to a file called "lion.json":
+ * // {
+ * // "id": 0,
+ * // "species": "Panthera leo",
+ * // "name": "Lion"
+ * // }
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.prototype.saveJSON = function(json, filename, opt) {
+ p5._validateParameters('saveJSON', arguments);
+ var stringify;
+ if (opt) {
+ stringify = JSON.stringify(json);
+ } else {
+ stringify = JSON.stringify(json, undefined, 2);
+ }
+ this.saveStrings(stringify.split('\n'), filename, 'json');
+};
+
+p5.prototype.saveJSONObject = p5.prototype.saveJSON;
+p5.prototype.saveJSONArray = p5.prototype.saveJSON;
+
+/**
+ * Writes an array of Strings to a text file, one line per String.
+ * The file saving process and location of the saved file will
+ * vary between web browsers.
+ *
+ * @method saveStrings
+ * @param {String[]} list string array to be written
+ * @param {String} filename filename for output
+ * @param {String} [extension] the filename's extension
+ * @example
+ *
+ * var words = 'apple bear cat dog';
+ *
+ * // .split() outputs an Array
+ * var list = split(words, ' ');
+ *
+ * createButton('save')
+ * .position(10, 10)
+ * .mousePressed(function() {
+ * saveStrings(list, 'nouns.txt');
+ * });
+ *
+ * // Saves the following to a file called 'nouns.txt':
+ * //
+ * // apple
+ * // bear
+ * // cat
+ * // dog
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.prototype.saveStrings = function(list, filename, extension) {
+ p5._validateParameters('saveStrings', arguments);
+ var ext = extension || 'txt';
+ var pWriter = this.createWriter(filename, ext);
+ for (var i = 0; i < list.length; i++) {
+ if (i < list.length - 1) {
+ pWriter.print(list[i]);
+ } else {
+ pWriter.print(list[i]);
+ }
+ }
+ pWriter.close();
+ pWriter.clear();
+};
+
+// =======
+// HELPERS
+// =======
+
+function escapeHelper(content) {
+ return content
+ .replace(/&/g, '&')
+ .replace(//g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, ''');
+}
+
+/**
+ * Writes the contents of a Table object to a file. Defaults to a
+ * text file with comma-separated-values ('csv') but can also
+ * use tab separation ('tsv'), or generate an HTML table ('html').
+ * The file saving process and location of the saved file will
+ * vary between web browsers.
+ *
+ * @method saveTable
+ * @param {p5.Table} Table the Table object to save to a file
+ * @param {String} filename the filename to which the Table should be saved
+ * @param {String} [options] can be one of "tsv", "csv", or "html"
+ * @example
+ *
+ * var table;
+ *
+ * function setup() {
+ * table = new p5.Table();
+ *
+ * table.addColumn('id');
+ * table.addColumn('species');
+ * table.addColumn('name');
+ *
+ * var newRow = table.addRow();
+ * newRow.setNum('id', table.getRowCount() - 1);
+ * newRow.setString('species', 'Panthera leo');
+ * newRow.setString('name', 'Lion');
+ *
+ * // To save, un-comment next line then click 'run'
+ * // saveTable(table, 'new.csv');
+ * }
+ *
+ * // Saves the following to a file called 'new.csv':
+ * // id,species,name
+ * // 0,Panthera leo,Lion
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.prototype.saveTable = function(table, filename, options) {
+ p5._validateParameters('saveTable', arguments);
+ var ext;
+ if (options === undefined) {
+ ext = filename.substring(filename.lastIndexOf('.') + 1, filename.length);
+ } else {
+ ext = options;
+ }
+ var pWriter = this.createWriter(filename, ext);
+
+ var header = table.columns;
+
+ var sep = ','; // default to CSV
+ if (ext === 'tsv') {
+ sep = '\t';
+ }
+ if (ext !== 'html') {
+ // make header if it has values
+ if (header[0] !== '0') {
+ for (var h = 0; h < header.length; h++) {
+ if (h < header.length - 1) {
+ pWriter.write(header[h] + sep);
+ } else {
+ pWriter.write(header[h]);
+ }
+ }
+ pWriter.write('\n');
+ }
+
+ // make rows
+ for (var i = 0; i < table.rows.length; i++) {
+ var j;
+ for (j = 0; j < table.rows[i].arr.length; j++) {
+ if (j < table.rows[i].arr.length - 1) {
+ pWriter.write(table.rows[i].arr[j] + sep);
+ } else if (i < table.rows.length - 1) {
+ pWriter.write(table.rows[i].arr[j]);
+ } else {
+ pWriter.write(table.rows[i].arr[j]);
+ }
+ }
+ pWriter.write('\n');
+ }
+ } else {
+ // otherwise, make HTML
+ pWriter.print('');
+ pWriter.print('');
+ var str = ' ';
+ pWriter.print(str);
+ pWriter.print('');
+
+ pWriter.print('');
+ pWriter.print(' ');
+
+ // make header if it has values
+ if (header[0] !== '0') {
+ pWriter.print(' ');
+ for (var k = 0; k < header.length; k++) {
+ var e = escapeHelper(header[k]);
+ pWriter.print(' | ' + e);
+ pWriter.print(' | ');
+ }
+ pWriter.print('
');
+ }
+
+ // make rows
+ for (var row = 0; row < table.rows.length; row++) {
+ pWriter.print(' ');
+ for (var col = 0; col < table.columns.length; col++) {
+ var entry = table.rows[row].getString(col);
+ var htmlEntry = escapeHelper(entry);
+ pWriter.print(' | ' + htmlEntry);
+ pWriter.print(' | ');
+ }
+ pWriter.print('
');
+ }
+ pWriter.print('
');
+ pWriter.print('');
+ pWriter.print('');
+ }
+ // close and clear the pWriter
+ pWriter.close();
+ pWriter.clear();
+}; // end saveTable()
+
+/**
+ * Generate a blob of file data as a url to prepare for download.
+ * Accepts an array of data, a filename, and an extension (optional).
+ * This is a private function because it does not do any formatting,
+ * but it is used by saveStrings, saveJSON, saveTable etc.
+ *
+ * @param {Array} dataToDownload
+ * @param {String} filename
+ * @param {String} [extension]
+ * @private
+ */
+p5.prototype.writeFile = function(dataToDownload, filename, extension) {
+ var type = 'application/octet-stream';
+ if (p5.prototype._isSafari()) {
+ type = 'text/plain';
+ }
+ var blob = new Blob(dataToDownload, {
+ type: type
+ });
+ p5.prototype.downloadFile(blob, filename, extension);
+};
+
+/**
+ * Forces download. Accepts a url to filedata/blob, a filename,
+ * and an extension (optional).
+ * This is a private function because it does not do any formatting,
+ * but it is used by saveStrings, saveJSON, saveTable etc.
+ *
+ * @method downloadFile
+ * @private
+ * @param {String|Blob} data either an href generated by createObjectURL,
+ * or a Blob object containing the data
+ * @param {String} [filename]
+ * @param {String} [extension]
+ */
+p5.prototype.downloadFile = function(data, fName, extension) {
+ var fx = _checkFileExtension(fName, extension);
+ var filename = fx[0];
+
+ if (data instanceof Blob) {
+ var fileSaver = _dereq_('file-saver');
+ fileSaver.saveAs(data, filename);
+ return;
+ }
+
+ var a = document.createElement('a');
+ a.href = data;
+ a.download = filename;
+
+ // Firefox requires the link to be added to the DOM before click()
+ a.onclick = function(e) {
+ destroyClickedElement(e);
+ e.stopPropagation();
+ };
+
+ a.style.display = 'none';
+ document.body.appendChild(a);
+
+ // Safari will open this file in the same page as a confusing Blob.
+ if (p5.prototype._isSafari()) {
+ var aText = 'Hello, Safari user! To download this file...\n';
+ aText += '1. Go to File --> Save As.\n';
+ aText += '2. Choose "Page Source" as the Format.\n';
+ aText += '3. Name it with this extension: ."' + fx[1] + '"';
+ alert(aText);
+ }
+ a.click();
+};
+
+/**
+ * Returns a file extension, or another string
+ * if the provided parameter has no extension.
+ *
+ * @param {String} filename
+ * @param {String} [extension]
+ * @return {String[]} [fileName, fileExtension]
+ *
+ * @private
+ */
+function _checkFileExtension(filename, extension) {
+ if (!extension || extension === true || extension === 'true') {
+ extension = '';
+ }
+ if (!filename) {
+ filename = 'untitled';
+ }
+ var ext = '';
+ // make sure the file will have a name, see if filename needs extension
+ if (filename && filename.indexOf('.') > -1) {
+ ext = filename.split('.').pop();
+ }
+ // append extension if it doesn't exist
+ if (extension) {
+ if (ext !== extension) {
+ ext = extension;
+ filename = filename + '.' + ext;
+ }
+ }
+ return [filename, ext];
+}
+p5.prototype._checkFileExtension = _checkFileExtension;
+
+/**
+ * Returns true if the browser is Safari, false if not.
+ * Safari makes trouble for downloading files.
+ *
+ * @return {Boolean} [description]
+ * @private
+ */
+p5.prototype._isSafari = function() {
+ var x = Object.prototype.toString.call(window.HTMLElement);
+ return x.indexOf('Constructor') > 0;
+};
+
+/**
+ * Helper function, a callback for download that deletes
+ * an invisible anchor element from the DOM once the file
+ * has been automatically downloaded.
+ *
+ * @private
+ */
+function destroyClickedElement(event) {
+ document.body.removeChild(event.target);
+}
+
+module.exports = p5;
+
+},{"../core/core":22,"../core/error_helpers":25,"es6-promise":5,"fetch-jsonp":6,"file-saver":7,"whatwg-fetch":12}],47:[function(_dereq_,module,exports){
+/**
+ * @module IO
+ * @submodule Table
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+/**
+ * Table Options
+ * Generic class for handling tabular data, typically from a
+ * CSV, TSV, or other sort of spreadsheet file.
+ * CSV files are
+ *
+ * comma separated values, often with the data in quotes. TSV
+ * files use tabs as separators, and usually don't bother with the
+ * quotes.
+ * File names should end with .csv if they're comma separated.
+ * A rough "spec" for CSV can be found
+ * here.
+ * To load files, use the loadTable method.
+ * To save tables to your computer, use the save method
+ * or the saveTable method.
+ *
+ * Possible options include:
+ *
+ * - csv - parse the table as comma-separated values
+ *
- tsv - parse the table as tab-separated values
+ *
- header - this table has a header (title) row
+ *
+ */
+
+/**
+ * Table objects store data with multiple rows and columns, much
+ * like in a traditional spreadsheet. Tables can be generated from
+ * scratch, dynamically, or using data from an existing file.
+ *
+ * @class p5.Table
+ * @constructor
+ * @param {p5.TableRow[]} [rows] An array of p5.TableRow objects
+ */
+p5.Table = function(rows) {
+ /**
+ * @property columns {String[]}
+ */
+ this.columns = [];
+
+ /**
+ * @property rows {p5.TableRow[]}
+ */
+ this.rows = [];
+};
+
+/**
+ * Use addRow() to add a new row of data to a p5.Table object. By default,
+ * an empty row is created. Typically, you would store a reference to
+ * the new row in a TableRow object (see newRow in the example above),
+ * and then set individual values using set().
+ *
+ * If a p5.TableRow object is included as a parameter, then that row is
+ * duplicated and added to the table.
+ *
+ * @method addRow
+ * @param {p5.TableRow} [row] row to be added to the table
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //add a row
+ * var newRow = table.addRow();
+ * newRow.setString('id', table.getRowCount() - 1);
+ * newRow.setString('species', 'Canis Lupus');
+ * newRow.setString('name', 'Wolf');
+ *
+ * //print the results
+ * for (var r = 0; r < table.getRowCount(); r++)
+ * for (var c = 0; c < table.getColumnCount(); c++)
+ * print(table.getString(r, c));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.addRow = function(row) {
+ // make sure it is a valid TableRow
+ var r = row || new p5.TableRow();
+
+ if (typeof r.arr === 'undefined' || typeof r.obj === 'undefined') {
+ //r = new p5.prototype.TableRow(r);
+ throw 'invalid TableRow: ' + r;
+ }
+ r.table = this;
+ this.rows.push(r);
+ return r;
+};
+
+/**
+ * Removes a row from the table object.
+ *
+ * @method removeRow
+ * @param {Integer} id ID number of the row to remove
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //remove the first row
+ * table.removeRow(0);
+ *
+ * //print the results
+ * for (var r = 0; r < table.getRowCount(); r++)
+ * for (var c = 0; c < table.getColumnCount(); c++)
+ * print(table.getString(r, c));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.removeRow = function(id) {
+ this.rows[id].table = null; // remove reference to table
+ var chunk = this.rows.splice(id + 1, this.rows.length);
+ this.rows.pop();
+ this.rows = this.rows.concat(chunk);
+};
+
+/**
+ * Returns a reference to the specified p5.TableRow. The reference
+ * can then be used to get and set values of the selected row.
+ *
+ * @method getRow
+ * @param {Integer} rowID ID number of the row to get
+ * @return {p5.TableRow} p5.TableRow object
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * var row = table.getRow(1);
+ * //print it column by column
+ * //note: a row is an object, not an array
+ * for (var c = 0; c < table.getColumnCount(); c++) {
+ * print(row.getString(c));
+ * }
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.getRow = function(r) {
+ return this.rows[r];
+};
+
+/**
+ * Gets all rows from the table. Returns an array of p5.TableRows.
+ *
+ * @method getRows
+ * @return {p5.TableRow[]} Array of p5.TableRows
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * var rows = table.getRows();
+ *
+ * //warning: rows is an array of objects
+ * for (var r = 0; r < rows.length; r++) {
+ * rows[r].set('name', 'Unicorn');
+ * }
+ *
+ * //print the results
+ * for (r = 0; r < table.getRowCount(); r++)
+ * for (var c = 0; c < table.getColumnCount(); c++)
+ * print(table.getString(r, c));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.getRows = function() {
+ return this.rows;
+};
+
+/**
+ * Finds the first row in the Table that contains the value
+ * provided, and returns a reference to that row. Even if
+ * multiple rows are possible matches, only the first matching
+ * row is returned. The column to search may be specified by
+ * either its ID or title.
+ *
+ * @method findRow
+ * @param {String} value The value to match
+ * @param {Integer|String} column ID number or title of the
+ * column to search
+ * @return {p5.TableRow}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //find the animal named zebra
+ * var row = table.findRow('Zebra', 'name');
+ * //find the corresponding species
+ * print(row.getString('species'));
+ * }
+ *
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.findRow = function(value, column) {
+ // try the Object
+ if (typeof column === 'string') {
+ for (var i = 0; i < this.rows.length; i++) {
+ if (this.rows[i].obj[column] === value) {
+ return this.rows[i];
+ }
+ }
+ } else {
+ // try the Array
+ for (var j = 0; j < this.rows.length; j++) {
+ if (this.rows[j].arr[column] === value) {
+ return this.rows[j];
+ }
+ }
+ }
+ // otherwise...
+ return null;
+};
+
+/**
+ * Finds the rows in the Table that contain the value
+ * provided, and returns references to those rows. Returns an
+ * Array, so for must be used to iterate through all the rows,
+ * as shown in the example above. The column to search may be
+ * specified by either its ID or title.
+ *
+ * @method findRows
+ * @param {String} value The value to match
+ * @param {Integer|String} column ID number or title of the
+ * column to search
+ * @return {p5.TableRow[]} An Array of TableRow objects
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //add another goat
+ * var newRow = table.addRow();
+ * newRow.setString('id', table.getRowCount() - 1);
+ * newRow.setString('species', 'Scape Goat');
+ * newRow.setString('name', 'Goat');
+ *
+ * //find the rows containing animals named Goat
+ * var rows = table.findRows('Goat', 'name');
+ * print(rows.length + ' Goats found');
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.findRows = function(value, column) {
+ var ret = [];
+ if (typeof column === 'string') {
+ for (var i = 0; i < this.rows.length; i++) {
+ if (this.rows[i].obj[column] === value) {
+ ret.push(this.rows[i]);
+ }
+ }
+ } else {
+ // try the Array
+ for (var j = 0; j < this.rows.length; j++) {
+ if (this.rows[j].arr[column] === value) {
+ ret.push(this.rows[j]);
+ }
+ }
+ }
+ return ret;
+};
+
+/**
+ * Finds the first row in the Table that matches the regular
+ * expression provided, and returns a reference to that row.
+ * Even if multiple rows are possible matches, only the first
+ * matching row is returned. The column to search may be
+ * specified by either its ID or title.
+ *
+ * @method matchRow
+ * @param {String|RegExp} regexp The regular expression to match
+ * @param {String|Integer} column The column ID (number) or
+ * title (string)
+ * @return {p5.TableRow} TableRow object
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //Search using specified regex on a given column, return TableRow object
+ * var mammal = table.matchRow(new RegExp('ant'), 1);
+ * print(mammal.getString(1));
+ * //Output "Panthera pardus"
+ * }
+ *
+ *
+ *
+ */
+p5.Table.prototype.matchRow = function(regexp, column) {
+ if (typeof column === 'number') {
+ for (var j = 0; j < this.rows.length; j++) {
+ if (this.rows[j].arr[column].match(regexp)) {
+ return this.rows[j];
+ }
+ }
+ } else {
+ for (var i = 0; i < this.rows.length; i++) {
+ if (this.rows[i].obj[column].match(regexp)) {
+ return this.rows[i];
+ }
+ }
+ }
+ return null;
+};
+
+/**
+ * Finds the rows in the Table that match the regular expression provided,
+ * and returns references to those rows. Returns an array, so for must be
+ * used to iterate through all the rows, as shown in the example. The
+ * column to search may be specified by either its ID or title.
+ *
+ * @method matchRows
+ * @param {String} regexp The regular expression to match
+ * @param {String|Integer} [column] The column ID (number) or
+ * title (string)
+ * @return {p5.TableRow[]} An Array of TableRow objects
+ * @example
+ *
+ *
+ * var table;
+ *
+ * function setup() {
+ * table = new p5.Table();
+ *
+ * table.addColumn('name');
+ * table.addColumn('type');
+ *
+ * var newRow = table.addRow();
+ * newRow.setString('name', 'Lion');
+ * newRow.setString('type', 'Mammal');
+ *
+ * newRow = table.addRow();
+ * newRow.setString('name', 'Snake');
+ * newRow.setString('type', 'Reptile');
+ *
+ * newRow = table.addRow();
+ * newRow.setString('name', 'Mosquito');
+ * newRow.setString('type', 'Insect');
+ *
+ * newRow = table.addRow();
+ * newRow.setString('name', 'Lizard');
+ * newRow.setString('type', 'Reptile');
+ *
+ * var rows = table.matchRows('R.*', 'type');
+ * for (var i = 0; i < rows.length; i++) {
+ * print(rows[i].getString('name') + ': ' + rows[i].getString('type'));
+ * }
+ * }
+ * // Sketch prints:
+ * // Snake: Reptile
+ * // Lizard: Reptile
+ *
+ *
+ */
+p5.Table.prototype.matchRows = function(regexp, column) {
+ var ret = [];
+ if (typeof column === 'number') {
+ for (var j = 0; j < this.rows.length; j++) {
+ if (this.rows[j].arr[column].match(regexp)) {
+ ret.push(this.rows[j]);
+ }
+ }
+ } else {
+ for (var i = 0; i < this.rows.length; i++) {
+ if (this.rows[i].obj[column].match(regexp)) {
+ ret.push(this.rows[i]);
+ }
+ }
+ }
+ return ret;
+};
+
+/**
+ * Retrieves all values in the specified column, and returns them
+ * as an array. The column may be specified by either its ID or title.
+ *
+ * @method getColumn
+ * @param {String|Number} column String or Number of the column to return
+ * @return {Array} Array of column values
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //getColumn returns an array that can be printed directly
+ * print(table.getColumn('species'));
+ * //outputs ["Capra hircus", "Panthera pardus", "Equus zebra"]
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.getColumn = function(value) {
+ var ret = [];
+ if (typeof value === 'string') {
+ for (var i = 0; i < this.rows.length; i++) {
+ ret.push(this.rows[i].obj[value]);
+ }
+ } else {
+ for (var j = 0; j < this.rows.length; j++) {
+ ret.push(this.rows[j].arr[value]);
+ }
+ }
+ return ret;
+};
+
+/**
+ * Removes all rows from a Table. While all rows are removed,
+ * columns and column titles are maintained.
+ *
+ * @method clearRows
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * table.clearRows();
+ * print(table.getRowCount() + ' total rows in table');
+ * print(table.getColumnCount() + ' total columns in table');
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.clearRows = function() {
+ delete this.rows;
+ this.rows = [];
+};
+
+/**
+ * Use addColumn() to add a new column to a Table object.
+ * Typically, you will want to specify a title, so the column
+ * may be easily referenced later by name. (If no title is
+ * specified, the new column's title will be null.)
+ *
+ * @method addColumn
+ * @param {String} [title] title of the given column
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * table.addColumn('carnivore');
+ * table.set(0, 'carnivore', 'no');
+ * table.set(1, 'carnivore', 'yes');
+ * table.set(2, 'carnivore', 'no');
+ *
+ * //print the results
+ * for (var r = 0; r < table.getRowCount(); r++)
+ * for (var c = 0; c < table.getColumnCount(); c++)
+ * print(table.getString(r, c));
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.addColumn = function(title) {
+ var t = title || null;
+ this.columns.push(t);
+};
+
+/**
+ * Returns the total number of columns in a Table.
+ *
+ * @method getColumnCount
+ * @return {Integer} Number of columns in this table
+ * @example
+ *
+ *
+ * // given the cvs file "blobs.csv" in /assets directory
+ * // ID, Name, Flavor, Shape, Color
+ * // Blob1, Blobby, Sweet, Blob, Pink
+ * // Blob2, Saddy, Savory, Blob, Blue
+ *
+ * var table;
+ *
+ * function preload() {
+ * table = loadTable('assets/blobs.csv');
+ * }
+ *
+ * function setup() {
+ * createCanvas(200, 100);
+ * textAlign(CENTER);
+ * background(255);
+ * }
+ *
+ * function draw() {
+ * var numOfColumn = table.getColumnCount();
+ * text('There are ' + numOfColumn + ' columns in the table.', 100, 50);
+ * }
+ *
+ *
+ */
+p5.Table.prototype.getColumnCount = function() {
+ return this.columns.length;
+};
+
+/**
+ * Returns the total number of rows in a Table.
+ *
+ * @method getRowCount
+ * @return {Integer} Number of rows in this table
+ * @example
+ *
+ *
+ * // given the cvs file "blobs.csv" in /assets directory
+ * //
+ * // ID, Name, Flavor, Shape, Color
+ * // Blob1, Blobby, Sweet, Blob, Pink
+ * // Blob2, Saddy, Savory, Blob, Blue
+ *
+ * var table;
+ *
+ * function preload() {
+ * table = loadTable('assets/blobs.csv');
+ * }
+ *
+ * function setup() {
+ * createCanvas(200, 100);
+ * textAlign(CENTER);
+ * background(255);
+ * }
+ *
+ * function draw() {
+ * text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);
+ * }
+ *
+ *
+ */
+p5.Table.prototype.getRowCount = function() {
+ return this.rows.length;
+};
+
+/**
+ * Removes any of the specified characters (or "tokens").
+ *
+ * If no column is specified, then the values in all columns and
+ * rows are processed. A specific column may be referenced by
+ * either its ID or title.
+ *
+ * @method removeTokens
+ * @param {String} chars String listing characters to be removed
+ * @param {String|Integer} [column] Column ID (number)
+ * or name (string)
+ *
+ * @example
+ *
+ * function setup() {
+ * var table = new p5.Table();
+ *
+ * table.addColumn('name');
+ * table.addColumn('type');
+ *
+ * var newRow = table.addRow();
+ * newRow.setString('name', ' $Lion ,');
+ * newRow.setString('type', ',,,Mammal');
+ *
+ * newRow = table.addRow();
+ * newRow.setString('name', '$Snake ');
+ * newRow.setString('type', ',,,Reptile');
+ *
+ * table.removeTokens(',$ ');
+ * print(table.getArray());
+ * }
+ *
+ * // prints:
+ * // 0 "Lion" "Mamal"
+ * // 1 "Snake" "Reptile"
+ *
+ */
+p5.Table.prototype.removeTokens = function(chars, column) {
+ var escape = function(s) {
+ return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
+ };
+ var charArray = [];
+ for (var i = 0; i < chars.length; i++) {
+ charArray.push(escape(chars.charAt(i)));
+ }
+ var regex = new RegExp(charArray.join('|'), 'g');
+
+ if (typeof column === 'undefined') {
+ for (var c = 0; c < this.columns.length; c++) {
+ for (var d = 0; d < this.rows.length; d++) {
+ var s = this.rows[d].arr[c];
+ s = s.replace(regex, '');
+ this.rows[d].arr[c] = s;
+ this.rows[d].obj[this.columns[c]] = s;
+ }
+ }
+ } else if (typeof column === 'string') {
+ for (var j = 0; j < this.rows.length; j++) {
+ var val = this.rows[j].obj[column];
+ val = val.replace(regex, '');
+ this.rows[j].obj[column] = val;
+ var pos = this.columns.indexOf(column);
+ this.rows[j].arr[pos] = val;
+ }
+ } else {
+ for (var k = 0; k < this.rows.length; k++) {
+ var str = this.rows[k].arr[column];
+ str = str.replace(regex, '');
+ this.rows[k].arr[column] = str;
+ this.rows[k].obj[this.columns[column]] = str;
+ }
+ }
+};
+
+/**
+ * Trims leading and trailing whitespace, such as spaces and tabs,
+ * from String table values. If no column is specified, then the
+ * values in all columns and rows are trimmed. A specific column
+ * may be referenced by either its ID or title.
+ *
+ * @method trim
+ * @param {String|Integer} [column] Column ID (number)
+ * or name (string)
+ * @example
+ *
+ * function setup() {
+ * var table = new p5.Table();
+ *
+ * table.addColumn('name');
+ * table.addColumn('type');
+ *
+ * var newRow = table.addRow();
+ * newRow.setString('name', ' Lion ,');
+ * newRow.setString('type', ' Mammal ');
+ *
+ * newRow = table.addRow();
+ * newRow.setString('name', ' Snake ');
+ * newRow.setString('type', ' Reptile ');
+ *
+ * table.trim();
+ * print(table.getArray());
+ * }
+ *
+ * // prints:
+ * // 0 "Lion" "Mamal"
+ * // 1 "Snake" "Reptile"
+ *
+ */
+p5.Table.prototype.trim = function(column) {
+ var regex = new RegExp(' ', 'g');
+
+ if (typeof column === 'undefined') {
+ for (var c = 0; c < this.columns.length; c++) {
+ for (var d = 0; d < this.rows.length; d++) {
+ var s = this.rows[d].arr[c];
+ s = s.replace(regex, '');
+ this.rows[d].arr[c] = s;
+ this.rows[d].obj[this.columns[c]] = s;
+ }
+ }
+ } else if (typeof column === 'string') {
+ for (var j = 0; j < this.rows.length; j++) {
+ var val = this.rows[j].obj[column];
+ val = val.replace(regex, '');
+ this.rows[j].obj[column] = val;
+ var pos = this.columns.indexOf(column);
+ this.rows[j].arr[pos] = val;
+ }
+ } else {
+ for (var k = 0; k < this.rows.length; k++) {
+ var str = this.rows[k].arr[column];
+ str = str.replace(regex, '');
+ this.rows[k].arr[column] = str;
+ this.rows[k].obj[this.columns[column]] = str;
+ }
+ }
+};
+
+/**
+ * Use removeColumn() to remove an existing column from a Table
+ * object. The column to be removed may be identified by either
+ * its title (a String) or its index value (an int).
+ * removeColumn(0) would remove the first column, removeColumn(1)
+ * would remove the second column, and so on.
+ *
+ * @method removeColumn
+ * @param {String|Integer} column columnName (string) or ID (number)
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * table.removeColumn('id');
+ * print(table.getColumnCount());
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.removeColumn = function(c) {
+ var cString;
+ var cNumber;
+ if (typeof c === 'string') {
+ // find the position of c in the columns
+ cString = c;
+ cNumber = this.columns.indexOf(c);
+ console.log('string');
+ } else {
+ cNumber = c;
+ cString = this.columns[c];
+ }
+
+ var chunk = this.columns.splice(cNumber + 1, this.columns.length);
+ this.columns.pop();
+ this.columns = this.columns.concat(chunk);
+
+ for (var i = 0; i < this.rows.length; i++) {
+ var tempR = this.rows[i].arr;
+ var chip = tempR.splice(cNumber + 1, tempR.length);
+ tempR.pop();
+ this.rows[i].arr = tempR.concat(chip);
+ delete this.rows[i].obj[cString];
+ }
+};
+
+/**
+ * Stores a value in the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified
+ * by either its ID or title.
+ *
+ * @method set
+ * @param {Integer} row row ID
+ * @param {String|Integer} column column ID (Number)
+ * or title (String)
+ * @param {String|Number} value value to assign
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * table.set(0, 'species', 'Canis Lupus');
+ * table.set(0, 'name', 'Wolf');
+ *
+ * //print the results
+ * for (var r = 0; r < table.getRowCount(); r++)
+ * for (var c = 0; c < table.getColumnCount(); c++)
+ * print(table.getString(r, c));
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.set = function(row, column, value) {
+ this.rows[row].set(column, value);
+};
+
+/**
+ * Stores a Float value in the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified
+ * by either its ID or title.
+ *
+ * @method setNum
+ * @param {Integer} row row ID
+ * @param {String|Integer} column column ID (Number)
+ * or title (String)
+ * @param {Number} value value to assign
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * table.setNum(1, 'id', 1);
+ *
+ * print(table.getColumn(0));
+ * //["0", 1, "2"]
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ */
+p5.Table.prototype.setNum = function(row, column, value) {
+ this.rows[row].setNum(column, value);
+};
+
+/**
+ * Stores a String value in the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified
+ * by either its ID or title.
+ *
+ * @method setString
+ * @param {Integer} row row ID
+ * @param {String|Integer} column column ID (Number)
+ * or title (String)
+ * @param {String} value value to assign
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * //add a row
+ * var newRow = table.addRow();
+ * newRow.setString('id', table.getRowCount() - 1);
+ * newRow.setString('species', 'Canis Lupus');
+ * newRow.setString('name', 'Wolf');
+ *
+ * print(table.getArray());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+p5.Table.prototype.setString = function(row, column, value) {
+ this.rows[row].setString(column, value);
+};
+
+/**
+ * Retrieves a value from the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified by
+ * either its ID or title.
+ *
+ * @method get
+ * @param {Integer} row row ID
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {String|Number}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * print(table.get(0, 1));
+ * //Capra hircus
+ * print(table.get(0, 'species'));
+ * //Capra hircus
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.get = function(row, column) {
+ return this.rows[row].get(column);
+};
+
+/**
+ * Retrieves a Float value from the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified by
+ * either its ID or title.
+ *
+ * @method getNum
+ * @param {Integer} row row ID
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {Number}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * print(table.getNum(1, 0) + 100);
+ * //id 1 + 100 = 101
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.getNum = function(row, column) {
+ return this.rows[row].getNum(column);
+};
+
+/**
+ * Retrieves a String value from the Table's specified row and column.
+ * The row is specified by its ID, while the column may be specified by
+ * either its ID or title.
+ *
+ * @method getString
+ * @param {Integer} row row ID
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {String}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * // table is comma separated value "CSV"
+ * // and has specifiying header for column labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * print(table.getString(0, 0)); // 0
+ * print(table.getString(0, 1)); // Capra hircus
+ * print(table.getString(0, 2)); // Goat
+ * print(table.getString(1, 0)); // 1
+ * print(table.getString(1, 1)); // Panthera pardus
+ * print(table.getString(1, 2)); // Leopard
+ * print(table.getString(2, 0)); // 2
+ * print(table.getString(2, 1)); // Equus zebra
+ * print(table.getString(2, 2)); // Zebra
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+
+p5.Table.prototype.getString = function(row, column) {
+ return this.rows[row].getString(column);
+};
+
+/**
+ * Retrieves all table data and returns as an object. If a column name is
+ * passed in, each row object will be stored with that attribute as its
+ * title.
+ *
+ * @method getObject
+ * @param {String} [headerColumn] Name of the column which should be used to
+ * title each row object (optional)
+ * @return {Object}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * var tableObject = table.getObject();
+ *
+ * print(tableObject);
+ * //outputs an object
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.getObject = function(headerColumn) {
+ var tableObject = {};
+ var obj, cPos, index;
+
+ for (var i = 0; i < this.rows.length; i++) {
+ obj = this.rows[i].obj;
+
+ if (typeof headerColumn === 'string') {
+ cPos = this.columns.indexOf(headerColumn); // index of columnID
+ if (cPos >= 0) {
+ index = obj[headerColumn];
+ tableObject[index] = obj;
+ } else {
+ throw 'This table has no column named "' + headerColumn + '"';
+ }
+ } else {
+ tableObject[i] = this.rows[i].obj;
+ }
+ }
+ return tableObject;
+};
+
+/**
+ * Retrieves all table data and returns it as a multidimensional array.
+ *
+ * @method getArray
+ * @return {Array}
+ *
+ * @example
+ *
+ *
+ * // Given the CSV file "mammals.csv"
+ * // in the project's "assets" folder
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leoperd
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * // table is comma separated value "CSV"
+ * // and has specifiying header for column labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * var tableArray = table.getArray();
+ * for (var i = 0; i < tableArray.length; i++) {
+ * print(tableArray[i]);
+ * }
+ * }
+ *
+ *
+ *
+ *@alt
+ * no image displayed
+ *
+ */
+p5.Table.prototype.getArray = function() {
+ var tableArray = [];
+ for (var i = 0; i < this.rows.length; i++) {
+ tableArray.push(this.rows[i].arr);
+ }
+ return tableArray;
+};
+
+module.exports = p5;
+
+},{"../core/core":22}],48:[function(_dereq_,module,exports){
+/**
+ * @module IO
+ * @submodule Table
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+/**
+ * A TableRow object represents a single row of data values,
+ * stored in columns, from a table.
+ *
+ * A Table Row contains both an ordered array, and an unordered
+ * JSON object.
+ *
+ * @class p5.TableRow
+ * @constructor
+ * @param {String} [str] optional: populate the row with a
+ * string of values, separated by the
+ * separator
+ * @param {String} [separator] comma separated values (csv) by default
+ */
+p5.TableRow = function(str, separator) {
+ var arr = [];
+ var obj = {};
+ if (str) {
+ separator = separator || ',';
+ arr = str.split(separator);
+ }
+ for (var i = 0; i < arr.length; i++) {
+ var key = i;
+ var val = arr[i];
+ obj[key] = val;
+ }
+ this.arr = arr;
+ this.obj = obj;
+ this.table = null;
+};
+
+/**
+ * Stores a value in the TableRow's specified column.
+ * The column may be specified by either its ID or title.
+ *
+ * @method set
+ * @param {String|Integer} column Column ID (Number)
+ * or Title (String)
+ * @param {String|Number} value The value to be stored
+ *
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * var rows = table.getRows();
+ * for (var r = 0; r < rows.length; r++) {
+ * rows[r].set('name', 'Unicorn');
+ * }
+ *
+ * //print the results
+ * print(table.getArray());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+p5.TableRow.prototype.set = function(column, value) {
+ // if typeof column is string, use .obj
+ if (typeof column === 'string') {
+ var cPos = this.table.columns.indexOf(column); // index of columnID
+ if (cPos >= 0) {
+ this.obj[column] = value;
+ this.arr[cPos] = value;
+ } else {
+ throw 'This table has no column named "' + column + '"';
+ }
+ } else {
+ // if typeof column is number, use .arr
+ if (column < this.table.columns.length) {
+ this.arr[column] = value;
+ var cTitle = this.table.columns[column];
+ this.obj[cTitle] = value;
+ } else {
+ throw 'Column #' + column + ' is out of the range of this table';
+ }
+ }
+};
+
+/**
+ * Stores a Float value in the TableRow's specified column.
+ * The column may be specified by either its ID or title.
+ *
+ * @method setNum
+ * @param {String|Integer} column Column ID (Number)
+ * or Title (String)
+ * @param {Number|String} value The value to be stored
+ * as a Float
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * var rows = table.getRows();
+ * for (var r = 0; r < rows.length; r++) {
+ * rows[r].setNum('id', r + 10);
+ * }
+ *
+ * print(table.getArray());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+p5.TableRow.prototype.setNum = function(column, value) {
+ var floatVal = parseFloat(value);
+ this.set(column, floatVal);
+};
+
+/**
+ * Stores a String value in the TableRow's specified column.
+ * The column may be specified by either its ID or title.
+ *
+ * @method setString
+ * @param {String|Integer} column Column ID (Number)
+ * or Title (String)
+ * @param {String|Number|Boolean|Object} value The value to be stored
+ * as a String
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * var rows = table.getRows();
+ * for (var r = 0; r < rows.length; r++) {
+ * var name = rows[r].getString('name');
+ * rows[r].setString('name', 'A ' + name + ' named George');
+ * }
+ *
+ * print(table.getArray());
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+p5.TableRow.prototype.setString = function(column, value) {
+ var stringVal = value.toString();
+ this.set(column, stringVal);
+};
+
+/**
+ * Retrieves a value from the TableRow's specified column.
+ * The column may be specified by either its ID or title.
+ *
+ * @method get
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {String|Number}
+ *
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * var names = [];
+ * var rows = table.getRows();
+ * for (var r = 0; r < rows.length; r++) {
+ * names.push(rows[r].get('name'));
+ * }
+ *
+ * print(names);
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+p5.TableRow.prototype.get = function(column) {
+ if (typeof column === 'string') {
+ return this.obj[column];
+ } else {
+ return this.arr[column];
+ }
+};
+
+/**
+ * Retrieves a Float value from the TableRow's specified
+ * column. The column may be specified by either its ID or
+ * title.
+ *
+ * @method getNum
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {Number} Float Floating point number
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * var rows = table.getRows();
+ * var minId = Infinity;
+ * var maxId = -Infinity;
+ * for (var r = 0; r < rows.length; r++) {
+ * var id = rows[r].getNum('id');
+ * minId = min(minId, id);
+ * maxId = min(maxId, id);
+ * }
+ * print('minimum id = ' + minId + ', maximum id = ' + maxId);
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+p5.TableRow.prototype.getNum = function(column) {
+ var ret;
+ if (typeof column === 'string') {
+ ret = parseFloat(this.obj[column]);
+ } else {
+ ret = parseFloat(this.arr[column]);
+ }
+
+ if (ret.toString() === 'NaN') {
+ throw 'Error: ' + this.obj[column] + ' is NaN (Not a Number)';
+ }
+ return ret;
+};
+
+/**
+ * Retrieves an String value from the TableRow's specified
+ * column. The column may be specified by either its ID or
+ * title.
+ *
+ * @method getString
+ * @param {String|Integer} column columnName (string) or
+ * ID (number)
+ * @return {String} String
+ * @example
+ *
+ * // Given the CSV file "mammals.csv" in the project's "assets" folder:
+ * //
+ * // id,species,name
+ * // 0,Capra hircus,Goat
+ * // 1,Panthera pardus,Leopard
+ * // 2,Equus zebra,Zebra
+ *
+ * var table;
+ *
+ * function preload() {
+ * //my table is comma separated value "csv"
+ * //and has a header specifying the columns labels
+ * table = loadTable('assets/mammals.csv', 'csv', 'header');
+ * }
+ *
+ * function setup() {
+ * var rows = table.getRows();
+ * var longest = '';
+ * for (var r = 0; r < rows.length; r++) {
+ * var species = rows[r].getString('species');
+ * if (longest.length < species.length) {
+ * longest = species;
+ * }
+ * }
+ *
+ * print('longest: ' + longest);
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ */
+p5.TableRow.prototype.getString = function(column) {
+ if (typeof column === 'string') {
+ return this.obj[column].toString();
+ } else {
+ return this.arr[column].toString();
+ }
+};
+
+module.exports = p5;
+
+},{"../core/core":22}],49:[function(_dereq_,module,exports){
+/**
+ * @module IO
+ * @submodule XML
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+/**
+ * XML is a representation of an XML object, able to parse XML code. Use
+ * loadXML() to load external XML files and create XML objects.
+ *
+ * @class p5.XML
+ * @constructor
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var children = xml.getChildren('animal');
+ *
+ * for (var i = 0; i < children.length; i++) {
+ * var id = children[i].getNum('id');
+ * var coloring = children[i].getString('species');
+ * var name = children[i].getContent();
+ * print(id + ', ' + coloring + ', ' + name);
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // 0, Capra hircus, Goat
+ * // 1, Panthera pardus, Leopard
+ * // 2, Equus zebra, Zebra
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.XML = function() {
+ this.name = null; //done
+ this.attributes = {}; //done
+ this.children = [];
+ this.parent = null;
+ this.content = null; //done
+};
+
+/**
+ * Gets a copy of the element's parent. Returns the parent as another
+ * p5.XML object.
+ *
+ * @method getParent
+ * @return {p5.XML} element parent
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var children = xml.getChildren('animal');
+ * var parent = children[1].getParent();
+ * print(parent.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ *
+ */
+p5.XML.prototype.getParent = function() {
+ return this.parent;
+};
+
+/**
+ * Gets the element's full name, which is returned as a String.
+ *
+ * @method getName
+ * @return {String} the name of the node
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ *
+ */
+p5.XML.prototype.getName = function() {
+ return this.name;
+};
+
+/**
+ * Sets the element's name, which is specified as a String.
+ *
+ * @method setName
+ * @param {String} the new name of the node
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.getName());
+ * xml.setName('fish');
+ * print(xml.getName());
+ * }
+ *
+ * // Sketch prints:
+ * // mammals
+ * // fish
+ *
+ */
+p5.XML.prototype.setName = function(name) {
+ this.name = name;
+};
+
+/**
+ * Checks whether or not the element has any children, and returns the result
+ * as a boolean.
+ *
+ * @method hasChildren
+ * @return {boolean}
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.hasChildren());
+ * }
+ *
+ * // Sketch prints:
+ * // true
+ *
+ */
+p5.XML.prototype.hasChildren = function() {
+ return this.children.length > 0;
+};
+
+/**
+ * Get the names of all of the element's children, and returns the names as an
+ * array of Strings. This is the same as looping through and calling getName()
+ * on each child element individually.
+ *
+ * @method listChildren
+ * @return {String[]} names of the children of the element
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * print(xml.listChildren());
+ * }
+ *
+ * // Sketch prints:
+ * // ["animal", "animal", "animal"]
+ *
+ */
+p5.XML.prototype.listChildren = function() {
+ return this.children.map(function(c) {
+ return c.name;
+ });
+};
+
+/**
+ * Returns all of the element's children as an array of p5.XML objects. When
+ * the name parameter is specified, then it will return all children that match
+ * that name.
+ *
+ * @method getChildren
+ * @param {String} [name] element name
+ * @return {p5.XML[]} children of the element
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var animals = xml.getChildren('animal');
+ *
+ * for (var i = 0; i < animals.length; i++) {
+ * print(animals[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Leopard"
+ * // "Zebra"
+ *
+ */
+p5.XML.prototype.getChildren = function(param) {
+ if (param) {
+ return this.children.filter(function(c) {
+ return c.name === param;
+ });
+ } else {
+ return this.children;
+ }
+};
+
+/**
+ * Returns the first of the element's children that matches the name parameter
+ * or the child of the given index.It returns undefined if no matching
+ * child is found.
+ *
+ * @method getChild
+ * @param {String|Integer} name element name or index
+ * @return {p5.XML}
+ * @example<animal
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ *
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var secondChild = xml.getChild(1);
+ * print(secondChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Leopard"
+ *
+ */
+p5.XML.prototype.getChild = function(param) {
+ if (typeof param === 'string') {
+ for (var i = 0; i < this.children.length; i++) {
+ var child = this.children[i];
+ if (child.name === param) return child;
+ }
+ } else {
+ return this.children[param];
+ }
+};
+
+/**
+ * Appends a new child to the element. The child can be specified with
+ * either a String, which will be used as the new tag's name, or as a
+ * reference to an existing p5.XML object.
+ * A reference to the newly created child is returned as an p5.XML object.
+ *
+ * @method addChild
+ * @param {p5.XML} node a p5.XML Object which will be the child to be added
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var child = new p5.XML();
+ * child.setAttribute('id', '3');
+ * child.setAttribute('species', 'Ornithorhynchus anatinus');
+ * child.setContent('Platypus');
+ * xml.addChild(child);
+ *
+ * var animals = xml.getChildren('animal');
+ * print(animals[animals.length - 1].getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Leopard"
+ * // "Zebra"
+ *
+ */
+p5.XML.prototype.addChild = function(node) {
+ if (node instanceof p5.XML) {
+ this.children.push(node);
+ } else {
+ // PEND
+ }
+};
+
+/**
+ * Removes the element specified by name or index.
+ *
+ * @method removeChild
+ * @param {String|Integer} name element name or index
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * xml.removeChild('animal');
+ * var children = xml.getChildren();
+ * for (var i = 0; i < children.length; i++) {
+ * print(children[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Leopard"
+ * // "Zebra"
+ *
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * xml.removeChild(1);
+ * var children = xml.getChildren();
+ * for (var i = 0; i < children.length; i++) {
+ * print(children[i].getContent());
+ * }
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Zebra"
+ *
+ */
+p5.XML.prototype.removeChild = function(param) {
+ var ind = -1;
+ if (typeof param === 'string') {
+ for (var i = 0; i < this.children.length; i++) {
+ if (this.children[i].name === param) {
+ ind = i;
+ break;
+ }
+ }
+ } else {
+ ind = param;
+ }
+ if (ind !== -1) {
+ this.children.splice(ind, 1);
+ }
+};
+
+/**
+ * Counts the specified element's number of attributes, returned as an Number.
+ *
+ * @method getAttributeCount
+ * @return {Integer}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var firstChild = xml.getChild('animal');
+ * print(firstChild.getAttributeCount());
+ * }
+ *
+ * // Sketch prints:
+ * // 2
+ *
+ */
+p5.XML.prototype.getAttributeCount = function() {
+ return Object.keys(this.attributes).length;
+};
+
+/**
+ * Gets all of the specified element's attributes, and returns them as an
+ * array of Strings.
+ *
+ * @method listAttributes
+ * @return {String[]} an array of strings containing the names of attributes
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var firstChild = xml.getChild('animal');
+ * print(firstChild.listAttributes());
+ * }
+ *
+ * // Sketch prints:
+ * // ["id", "species"]
+ *
+ */
+p5.XML.prototype.listAttributes = function() {
+ return Object.keys(this.attributes);
+};
+
+/**
+ * Checks whether or not an element has the specified attribute.
+ *
+ * @method hasAttribute
+ * @param {String} the attribute to be checked
+ * @return {boolean} true if attribute found else false
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var firstChild = xml.getChild('animal');
+ * print(firstChild.hasAttribute('species'));
+ * print(firstChild.hasAttribute('color'));
+ * }
+ *
+ * // Sketch prints:
+ * // true
+ * // false
+ *
+ */
+p5.XML.prototype.hasAttribute = function(name) {
+ return this.attributes[name] ? true : false;
+};
+
+/**
+ * Returns an attribute value of the element as an Number. If the defaultValue
+ * parameter is specified and the attribute doesn't exist, then defaultValue
+ * is returned. If no defaultValue is specified and the attribute doesn't
+ * exist, the value 0 is returned.
+ *
+ * @method getNum
+ * @param {String} name the non-null full name of the attribute
+ * @param {Number} [defaultValue] the default value of the attribute
+ * @return {Number}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var firstChild = xml.getChild('animal');
+ * print(firstChild.getNum('id'));
+ * }
+ *
+ * // Sketch prints:
+ * // 0
+ *
+ */
+p5.XML.prototype.getNum = function(name, defaultValue) {
+ return Number(this.attributes[name]) || defaultValue || 0;
+};
+
+/**
+ * Returns an attribute value of the element as an String. If the defaultValue
+ * parameter is specified and the attribute doesn't exist, then defaultValue
+ * is returned. If no defaultValue is specified and the attribute doesn't
+ * exist, null is returned.
+ *
+ * @method getString
+ * @param {String} name the non-null full name of the attribute
+ * @param {Number} [defaultValue] the default value of the attribute
+ * @return {String}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var firstChild = xml.getChild('animal');
+ * print(firstChild.getString('species'));
+ * }
+ *
+ * // Sketch prints:
+ * // "Capra hircus"
+ *
+ */
+p5.XML.prototype.getString = function(name, defaultValue) {
+ return String(this.attributes[name]) || defaultValue || null;
+};
+
+/**
+ * Sets the content of an element's attribute. The first parameter specifies
+ * the attribute name, while the second specifies the new content.
+ *
+ * @method setAttribute
+ * @param {String} name the full name of the attribute
+ * @param {Number|String|Boolean} value the value of the attribute
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var firstChild = xml.getChild('animal');
+ * print(firstChild.getString('species'));
+ * firstChild.setAttribute('species', 'Jamides zebra');
+ * print(firstChild.getString('species'));
+ * }
+ *
+ * // Sketch prints:
+ * // "Capra hircus"
+ * // "Jamides zebra"
+ *
+ */
+p5.XML.prototype.setAttribute = function(name, value) {
+ if (this.attributes[name]) {
+ this.attributes[name] = value;
+ }
+};
+
+/**
+ * Returns the content of an element. If there is no such content,
+ * defaultValue is returned if specified, otherwise null is returned.
+ *
+ * @method getContent
+ * @param {String} [defaultValue] value returned if no content is found
+ * @return {String}
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ *
+ */
+p5.XML.prototype.getContent = function(defaultValue) {
+ return this.content || defaultValue || null;
+};
+
+/**
+ * Sets the element's content.
+ *
+ * @method setContent
+ * @param {String} text the new content
+ * @example
+ *
+ * // The following short XML file called "mammals.xml" is parsed
+ * // in the code below.
+ * //
+ * //
+ * // <mammals>
+ * // <animal id="0" species="Capra hircus">Goat</animal>
+ * // <animal id="1" species="Panthera pardus">Leopard</animal>
+ * // <animal id="2" species="Equus zebra">Zebra</animal>
+ * // </mammals>
+ *
+ * var xml;
+ *
+ * function preload() {
+ * xml = loadXML('assets/mammals.xml');
+ * }
+ *
+ * function setup() {
+ * var firstChild = xml.getChild('animal');
+ * print(firstChild.getContent());
+ * firstChild.setContent('Mountain Goat');
+ * print(firstChild.getContent());
+ * }
+ *
+ * // Sketch prints:
+ * // "Goat"
+ * // "Mountain Goat"
+ *
+ */
+p5.XML.prototype.setContent = function(content) {
+ if (!this.children.length) {
+ this.content = content;
+ }
+};
+
+/* HELPERS */
+/**
+ * This method is called while the parsing of XML (when loadXML() is
+ * called). The difference between this method and the setContent()
+ * method defined later is that this one is used to set the content
+ * when the node in question has more nodes under it and so on and
+ * not directly text content. While in the other one is used when
+ * the node in question directly has text inside it.
+ *
+ */
+p5.XML.prototype._setCont = function(content) {
+ var str;
+ str = content;
+ str = str.replace(/\s\s+/g, ',');
+ //str = str.split(',');
+ this.content = str;
+};
+
+/**
+ * This method is called while the parsing of XML (when loadXML() is
+ * called). The XML node is passed and its attributes are stored in the
+ * p5.XML's attribute Object.
+ *
+ */
+p5.XML.prototype._setAttributes = function(node) {
+ var att = {};
+ var attributes = node.attributes;
+ if (attributes) {
+ for (var i = 0; i < attributes.length; i++) {
+ var attribute = attributes[i];
+ att[attribute.nodeName] = attribute.nodeValue;
+ }
+ }
+ this.attributes = att;
+};
+
+module.exports = p5;
+
+},{"../core/core":22}],50:[function(_dereq_,module,exports){
+/**
+ * @module Math
+ * @submodule Calculation
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+/**
+ * Calculates the absolute value (magnitude) of a number. Maps to Math.abs().
+ * The absolute value of a number is always positive.
+ *
+ * @method abs
+ * @param {Number} n number to compute
+ * @return {Number} absolute value of given number
+ * @example
+ *
+ * function setup() {
+ * var x = -3;
+ * var y = abs(x);
+ *
+ * print(x); // -3
+ * print(y); // 3
+ * }
+ *
+ *
+ * @alt
+ * no image displayed
+ *
+ */
+p5.prototype.abs = Math.abs;
+
+/**
+ * Calculates the closest int value that is greater than or equal to the
+ * value of the parameter. Maps to Math.ceil(). For example, ceil(9.03)
+ * returns the value 10.
+ *
+ * @method ceil
+ * @param {Number} n number to round up
+ * @return {Integer} rounded up number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * // map, mouseX between 0 and 5.
+ * var ax = map(mouseX, 0, 100, 0, 5);
+ * var ay = 66;
+ *
+ * //Get the ceiling of the mapped number.
+ * var bx = ceil(map(mouseX, 0, 100, 0, 5));
+ * var by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ * }
+ *
+ *
+ * @alt
+ * 2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals
+ *
+ */
+p5.prototype.ceil = Math.ceil;
+
+/**
+ * Constrains a value between a minimum and maximum value.
+ *
+ * @method constrain
+ * @param {Number} n number to constrain
+ * @param {Number} low minimum limit
+ * @param {Number} high maximum limit
+ * @return {Number} constrained number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ *
+ * var leftWall = 25;
+ * var rightWall = 75;
+ *
+ * // xm is just the mouseX, while
+ * // xc is the mouseX, but constrained
+ * // between the leftWall and rightWall!
+ * var xm = mouseX;
+ * var xc = constrain(mouseX, leftWall, rightWall);
+ *
+ * // Draw the walls.
+ * stroke(150);
+ * line(leftWall, 0, leftWall, height);
+ * line(rightWall, 0, rightWall, height);
+ *
+ * // Draw xm and xc as circles.
+ * noStroke();
+ * fill(150);
+ * ellipse(xm, 33, 9, 9); // Not Constrained
+ * fill(0);
+ * ellipse(xc, 66, 9, 9); // Constrained
+ * }
+ *
+ *
+ * @alt
+ * 2 vertical lines. 2 ellipses move with mouse X 1 does not move passed lines
+ *
+ */
+p5.prototype.constrain = function(n, low, high) {
+ p5._validateParameters('constrain', arguments);
+ return Math.max(Math.min(n, high), low);
+};
+
+/**
+ * Calculates the distance between two points.
+ *
+ * @method dist
+ * @param {Number} x1 x-coordinate of the first point
+ * @param {Number} y1 y-coordinate of the first point
+ * @param {Number} x2 x-coordinate of the second point
+ * @param {Number} y2 y-coordinate of the second point
+ * @return {Number} distance between the two points
+ *
+ * @example
+ *
+ * // Move your mouse inside the canvas to see the
+ * // change in distance between two points!
+ * function draw() {
+ * background(200);
+ * fill(0);
+ *
+ * var x1 = 10;
+ * var y1 = 90;
+ * var x2 = mouseX;
+ * var y2 = mouseY;
+ *
+ * line(x1, y1, x2, y2);
+ * ellipse(x1, y1, 7, 7);
+ * ellipse(x2, y2, 7, 7);
+ *
+ * // d is the length of the line
+ * // the distance from point 1 to point 2.
+ * var d = int(dist(x1, y1, x2, y2));
+ *
+ * // Let's write d along the line we are drawing!
+ * push();
+ * translate((x1 + x2) / 2, (y1 + y2) / 2);
+ * rotate(atan2(y2 - y1, x2 - x1));
+ * text(nfc(d, 1), 0, -5);
+ * pop();
+ * // Fancy!
+ * }
+ *
+ *
+ * @alt
+ * 2 ellipses joined by line. 1 ellipse moves with mouse X&Y. Distance displayed.
+ */
+/**
+ * @method dist
+ * @param {Number} x1
+ * @param {Number} y1
+ * @param {Number} z1 z-coordinate of the first point
+ * @param {Number} x2
+ * @param {Number} y2
+ * @param {Number} z2 z-coordinate of the second point
+ * @return {Number} distance between the two points
+ */
+p5.prototype.dist = function() {
+ p5._validateParameters('dist', arguments);
+ if (arguments.length === 4) {
+ //2D
+ return hypot(arguments[2] - arguments[0], arguments[3] - arguments[1]);
+ } else if (arguments.length === 6) {
+ //3D
+ return hypot(
+ arguments[3] - arguments[0],
+ arguments[4] - arguments[1],
+ arguments[5] - arguments[2]
+ );
+ }
+};
+
+/**
+ * Returns Euler's number e (2.71828...) raised to the power of the n
+ * parameter. Maps to Math.exp().
+ *
+ * @method exp
+ * @param {Number} n exponent to raise
+ * @return {Number} e^n
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // Compute the exp() function with a value between 0 and 2
+ * var xValue = map(mouseX, 0, width, 0, 2);
+ * var yValue = exp(xValue);
+ *
+ * var y = map(yValue, 0, 8, height, 0);
+ *
+ * var legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4);
+ * stroke(150);
+ * line(mouseX, y, mouseX, height);
+ * fill(0);
+ * text(legend, 5, 15);
+ * noStroke();
+ * ellipse(mouseX, y, 7, 7);
+ *
+ * // Draw the exp(x) curve,
+ * // over the domain of x from 0 to 2
+ * noFill();
+ * stroke(0);
+ * beginShape();
+ * for (var x = 0; x < width; x++) {
+ * xValue = map(x, 0, width, 0, 2);
+ * yValue = exp(xValue);
+ * y = map(yValue, 0, 8, height, 0);
+ * vertex(x, y);
+ * }
+ *
+ * endShape();
+ * line(0, 0, 0, height);
+ * line(0, height - 1, width, height - 1);
+ * }
+ *
+ *
+ * @alt
+ * ellipse moves along a curve with mouse x. e^n displayed.
+ *
+ */
+p5.prototype.exp = Math.exp;
+
+/**
+ * Calculates the closest int value that is less than or equal to the
+ * value of the parameter. Maps to Math.floor().
+ *
+ * @method floor
+ * @param {Number} n number to round down
+ * @return {Integer} rounded down number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * //map, mouseX between 0 and 5.
+ * var ax = map(mouseX, 0, 100, 0, 5);
+ * var ay = 66;
+ *
+ * //Get the floor of the mapped number.
+ * var bx = floor(map(mouseX, 0, 100, 0, 5));
+ * var by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ * }
+ *
+ *
+ * @alt
+ * 2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals
+ *
+ */
+p5.prototype.floor = Math.floor;
+
+/**
+ * Calculates a number between two numbers at a specific increment. The amt
+ * parameter is the amount to interpolate between the two values where 0.0
+ * equal to the first point, 0.1 is very near the first point, 0.5 is
+ * half-way in between, etc. The lerp function is convenient for creating
+ * motion along a straight path and for drawing dotted lines.
+ *
+ * @method lerp
+ * @param {Number} start first value
+ * @param {Number} stop second value
+ * @param {Number} amt number between 0.0 and 1.0
+ * @return {Number} lerped value
+ * @example
+ *
+ * function setup() {
+ * background(200);
+ * var a = 20;
+ * var b = 80;
+ * var c = lerp(a, b, 0.2);
+ * var d = lerp(a, b, 0.5);
+ * var e = lerp(a, b, 0.8);
+ *
+ * var y = 50;
+ *
+ * strokeWeight(5);
+ * stroke(0); // Draw the original points in black
+ * point(a, y);
+ * point(b, y);
+ *
+ * stroke(100); // Draw the lerp points in gray
+ * point(c, y);
+ * point(d, y);
+ * point(e, y);
+ * }
+ *
+ *
+ * @alt
+ * 5 points horizontally staggered mid-canvas. mid 3 are grey, outer black
+ *
+ */
+p5.prototype.lerp = function(start, stop, amt) {
+ p5._validateParameters('lerp', arguments);
+ return amt * (stop - start) + start;
+};
+
+/**
+ * Calculates the natural logarithm (the base-e logarithm) of a number. This
+ * function expects the n parameter to be a value greater than 0.0. Maps to
+ * Math.log().
+ *
+ * @method log
+ * @param {Number} n number greater than 0
+ * @return {Number} natural logarithm of n
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * var maxX = 2.8;
+ * var maxY = 1.5;
+ *
+ * // Compute the natural log of a value between 0 and maxX
+ * var xValue = map(mouseX, 0, width, 0, maxX);
+ * if (xValue > 0) {
+ // Cannot take the log of a negative number.
+ * var yValue = log(xValue);
+ * var y = map(yValue, -maxY, maxY, height, 0);
+ *
+ * // Display the calculation occurring.
+ * var legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3);
+ * stroke(150);
+ * line(mouseX, y, mouseX, height);
+ * fill(0);
+ * text(legend, 5, 15);
+ * noStroke();
+ * ellipse(mouseX, y, 7, 7);
+ * }
+ *
+ * // Draw the log(x) curve,
+ * // over the domain of x from 0 to maxX
+ * noFill();
+ * stroke(0);
+ * beginShape();
+ * for (var x = 0; x < width; x++) {
+ * xValue = map(x, 0, width, 0, maxX);
+ * yValue = log(xValue);
+ * y = map(yValue, -maxY, maxY, height, 0);
+ * vertex(x, y);
+ * }
+ * endShape();
+ * line(0, 0, 0, height);
+ * line(0, height / 2, width, height / 2);
+ * }
+ *
+ *
+ * @alt
+ * ellipse moves along a curve with mouse x. natural logarithm of n displayed.
+ *
+ */
+p5.prototype.log = Math.log;
+
+/**
+ * Calculates the magnitude (or length) of a vector. A vector is a direction
+ * in space commonly used in computer graphics and linear algebra. Because it
+ * has no "start" position, the magnitude of a vector can be thought of as
+ * the distance from the coordinate 0,0 to its x,y value. Therefore, mag() is
+ * a shortcut for writing dist(0, 0, x, y).
+ *
+ * @method mag
+ * @param {Number} a first value
+ * @param {Number} b second value
+ * @return {Number} magnitude of vector from (0,0) to (a,b)
+ * @example
+ *
+ * function setup() {
+ * var x1 = 20;
+ * var x2 = 80;
+ * var y1 = 30;
+ * var y2 = 70;
+ *
+ * line(0, 0, x1, y1);
+ * print(mag(x1, y1)); // Prints "36.05551275463989"
+ * line(0, 0, x2, y1);
+ * print(mag(x2, y1)); // Prints "85.44003745317531"
+ * line(0, 0, x1, y2);
+ * print(mag(x1, y2)); // Prints "72.80109889280519"
+ * line(0, 0, x2, y2);
+ * print(mag(x2, y2)); // Prints "106.3014581273465"
+ * }
+ *
+ *
+ * @alt
+ * 4 lines of different length radiate from top left of canvas.
+ *
+ */
+p5.prototype.mag = function(x, y) {
+ p5._validateParameters('mag', arguments);
+ return hypot(x, y);
+};
+
+/**
+ * Re-maps a number from one range to another.
+ *
+ * In the first example above, the number 25 is converted from a value in the
+ * range of 0 to 100 into a value that ranges from the left edge of the
+ * window (0) to the right edge (width).
+ *
+ * @method map
+ * @param {Number} value the incoming value to be converted
+ * @param {Number} start1 lower bound of the value's current range
+ * @param {Number} stop1 upper bound of the value's current range
+ * @param {Number} start2 lower bound of the value's target range
+ * @param {Number} stop2 upper bound of the value's target range
+ * @param {Boolean} [withinBounds] constrain the value to the newly mapped range
+ * @return {Number} remapped number
+ * @example
+ *
+ * var value = 25;
+ * var m = map(value, 0, 100, 0, width);
+ * ellipse(m, 50, 10, 10);
+
+ *
+ *
+ * function setup() {
+ * noStroke();
+ * }
+ *
+ * function draw() {
+ * background(204);
+ * var x1 = map(mouseX, 0, width, 25, 75);
+ * ellipse(x1, 25, 25, 25);
+ * //This ellipse is constrained to the 0-100 range
+ * //after setting withinBounds to true
+ * var x2 = map(mouseX, 0, width, 0, 100, true);
+ * ellipse(x2, 75, 25, 25);
+ * }
+
+ *
+ * @alt
+ * 10 by 10 white ellipse with in mid left canvas
+ * 2 25 by 25 white ellipses move with mouse x. Bottom has more range from X
+ *
+ */
+p5.prototype.map = function(n, start1, stop1, start2, stop2, withinBounds) {
+ p5._validateParameters('map', arguments);
+ var newval = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2;
+ if (!withinBounds) {
+ return newval;
+ }
+ if (start2 < stop2) {
+ return this.constrain(newval, start2, stop2);
+ } else {
+ return this.constrain(newval, stop2, start2);
+ }
+};
+
+/**
+ * Determines the largest value in a sequence of numbers, and then returns
+ * that value. max() accepts any number of Number parameters, or an Array
+ * of any length.
+ *
+ * @method max
+ * @param {Number} n0 Number to compare
+ * @param {Number} n1 Number to compare
+ * @return {Number} maximum Number
+ * @example
+ *
+ * function setup() {
+ * // Change the elements in the array and run the sketch
+ * // to show how max() works!
+ * var numArray = [2, 1, 5, 4, 8, 9];
+ * fill(0);
+ * noStroke();
+ * text('Array Elements', 0, 10);
+ * // Draw all numbers in the array
+ * var spacing = 15;
+ * var elemsY = 25;
+ * for (var i = 0; i < numArray.length; i++) {
+ * text(numArray[i], i * spacing, elemsY);
+ * }
+ * var maxX = 33;
+ * var maxY = 80;
+ * // Draw the Maximum value in the array.
+ * textSize(32);
+ * text(max(numArray), maxX, maxY);
+ * }
+ *
+ *
+ * @alt
+ * Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 9
+ *
+ */
+/**
+ * @method max
+ * @param {Number[]} nums Numbers to compare
+ * @return {Number}
+ */
+p5.prototype.max = function() {
+ p5._validateParameters('max', arguments);
+ if (arguments[0] instanceof Array) {
+ return Math.max.apply(null, arguments[0]);
+ } else {
+ return Math.max.apply(null, arguments);
+ }
+};
+
+/**
+ * Determines the smallest value in a sequence of numbers, and then returns
+ * that value. min() accepts any number of Number parameters, or an Array
+ * of any length.
+ *
+ * @method min
+ * @param {Number} n0 Number to compare
+ * @param {Number} n1 Number to compare
+ * @return {Number} minimum Number
+ * @example
+ *
+ * function setup() {
+ * // Change the elements in the array and run the sketch
+ * // to show how min() works!
+ * var numArray = [2, 1, 5, 4, 8, 9];
+ * fill(0);
+ * noStroke();
+ * text('Array Elements', 0, 10);
+ * // Draw all numbers in the array
+ * var spacing = 15;
+ * var elemsY = 25;
+ * for (var i = 0; i < numArray.length; i++) {
+ * text(numArray[i], i * spacing, elemsY);
+ * }
+ * var maxX = 33;
+ * var maxY = 80;
+ * // Draw the Minimum value in the array.
+ * textSize(32);
+ * text(min(numArray), maxX, maxY);
+ * }
+ *
+ *
+ * @alt
+ * Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 1
+ *
+ */
+/**
+ * @method min
+ * @param {Number[]} nums Numbers to compare
+ * @return {Number}
+ */
+p5.prototype.min = function() {
+ p5._validateParameters('min', arguments);
+ if (arguments[0] instanceof Array) {
+ return Math.min.apply(null, arguments[0]);
+ } else {
+ return Math.min.apply(null, arguments);
+ }
+};
+
+/**
+ * Normalizes a number from another range into a value between 0 and 1.
+ * Identical to map(value, low, high, 0, 1).
+ * Numbers outside of the range are not clamped to 0 and 1, because
+ * out-of-range values are often intentional and useful. (See the second
+ * example above.)
+ *
+ * @method norm
+ * @param {Number} value incoming value to be normalized
+ * @param {Number} start lower bound of the value's current range
+ * @param {Number} stop upper bound of the value's current range
+ * @return {Number} normalized number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * var currentNum = mouseX;
+ * var lowerBound = 0;
+ * var upperBound = width; //100;
+ * var normalized = norm(currentNum, lowerBound, upperBound);
+ * var lineY = 70;
+ * line(0, lineY, width, lineY);
+ * //Draw an ellipse mapped to the non-normalized value.
+ * noStroke();
+ * fill(50);
+ * var s = 7; // ellipse size
+ * ellipse(currentNum, lineY, s, s);
+ *
+ * // Draw the guide
+ * var guideY = lineY + 15;
+ * text('0', 0, guideY);
+ * textAlign(RIGHT);
+ * text('100', width, guideY);
+ *
+ * // Draw the normalized value
+ * textAlign(LEFT);
+ * fill(0);
+ * textSize(32);
+ * var normalY = 40;
+ * var normalX = 20;
+ * text(normalized, normalX, normalY);
+ * }
+ *
+ *
+ * @alt
+ * ellipse moves with mouse. 0 shown left & 100 right and updating values center
+ *
+ */
+p5.prototype.norm = function(n, start, stop) {
+ p5._validateParameters('norm', arguments);
+ return this.map(n, start, stop, 0, 1);
+};
+
+/**
+ * Facilitates exponential expressions. The pow() function is an efficient
+ * way of multiplying numbers by themselves (or their reciprocals) in large
+ * quantities. For example, pow(3, 5) is equivalent to the expression
+ * 3*3*3*3*3 and pow(3, -5) is equivalent to 1 / 3*3*3*3*3. Maps to
+ * Math.pow().
+ *
+ * @method pow
+ * @param {Number} n base of the exponential expression
+ * @param {Number} e power by which to raise the base
+ * @return {Number} n^e
+ * @example
+ *
+ * function setup() {
+ * //Exponentially increase the size of an ellipse.
+ * var eSize = 3; // Original Size
+ * var eLoc = 10; // Original Location
+ *
+ * ellipse(eLoc, eLoc, eSize, eSize);
+ *
+ * ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));
+ *
+ * ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));
+ *
+ * ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));
+ * }
+ *
+ *
+ * @alt
+ * small to large ellipses radiating from top left of canvas
+ *
+ */
+p5.prototype.pow = Math.pow;
+
+/**
+ * Calculates the integer closest to the n parameter. For example,
+ * round(133.8) returns the value 134. Maps to Math.round().
+ *
+ * @method round
+ * @param {Number} n number to round
+ * @return {Integer} rounded number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * //map, mouseX between 0 and 5.
+ * var ax = map(mouseX, 0, 100, 0, 5);
+ * var ay = 66;
+ *
+ * // Round the mapped number.
+ * var bx = round(map(mouseX, 0, 100, 0, 5));
+ * var by = 33;
+ *
+ * // Multiply the mapped numbers by 20 to more easily
+ * // see the changes.
+ * stroke(0);
+ * fill(0);
+ * line(0, ay, ax * 20, ay);
+ * line(0, by, bx * 20, by);
+ *
+ * // Reformat the float returned by map and draw it.
+ * noStroke();
+ * text(nfc(ax, 2), ax, ay - 5);
+ * text(nfc(bx, 1), bx, by - 5);
+ * }
+ *
+ *
+ * @alt
+ * horizontal center line squared values displayed on top and regular on bottom.
+ *
+ */
+p5.prototype.round = Math.round;
+
+/**
+ * Squares a number (multiplies a number by itself). The result is always a
+ * positive number, as multiplying two negative numbers always yields a
+ * positive result. For example, -1 * -1 = 1.
+ *
+ * @method sq
+ * @param {Number} n number to square
+ * @return {Number} squared number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * var eSize = 7;
+ * var x1 = map(mouseX, 0, width, 0, 10);
+ * var y1 = 80;
+ * var x2 = sq(x1);
+ * var y2 = 20;
+ *
+ * // Draw the non-squared.
+ * line(0, y1, width, y1);
+ * ellipse(x1, y1, eSize, eSize);
+ *
+ * // Draw the squared.
+ * line(0, y2, width, y2);
+ * ellipse(x2, y2, eSize, eSize);
+ *
+ * // Draw dividing line.
+ * stroke(100);
+ * line(0, height / 2, width, height / 2);
+ *
+ * // Draw text.
+ * var spacing = 15;
+ * noStroke();
+ * fill(0);
+ * text('x = ' + x1, 0, y1 + spacing);
+ * text('sq(x) = ' + x2, 0, y2 + spacing);
+ * }
+ *
+ *
+ * @alt
+ * horizontal center line squared values displayed on top and regular on bottom.
+ *
+ */
+p5.prototype.sq = function(n) {
+ return n * n;
+};
+
+/**
+ * Calculates the square root of a number. The square root of a number is
+ * always positive, even though there may be a valid negative root. The
+ * square root s of number a is such that s*s = a. It is the opposite of
+ * squaring. Maps to Math.sqrt().
+ *
+ * @method sqrt
+ * @param {Number} n non-negative number to square root
+ * @return {Number} square root of number
+ * @example
+ *
+ * function draw() {
+ * background(200);
+ * var eSize = 7;
+ * var x1 = mouseX;
+ * var y1 = 80;
+ * var x2 = sqrt(x1);
+ * var y2 = 20;
+ *
+ * // Draw the non-squared.
+ * line(0, y1, width, y1);
+ * ellipse(x1, y1, eSize, eSize);
+ *
+ * // Draw the squared.
+ * line(0, y2, width, y2);
+ * ellipse(x2, y2, eSize, eSize);
+ *
+ * // Draw dividing line.
+ * stroke(100);
+ * line(0, height / 2, width, height / 2);
+ *
+ * // Draw text.
+ * noStroke();
+ * fill(0);
+ * var spacing = 15;
+ * text('x = ' + x1, 0, y1 + spacing);
+ * text('sqrt(x) = ' + x2, 0, y2 + spacing);
+ * }
+ *
+ *
+ * @alt
+ * horizontal center line squareroot values displayed on top and regular on bottom.
+ *
+ */
+p5.prototype.sqrt = Math.sqrt;
+
+// Calculate the length of the hypotenuse of a right triangle
+// This won't under- or overflow in intermediate steps
+// https://en.wikipedia.org/wiki/Hypot
+function hypot(x, y, z) {
+ // Use the native implementation if it's available
+ if (typeof Math.hypot === 'function') {
+ return Math.hypot.apply(null, arguments);
+ }
+
+ // Otherwise use the V8 implementation
+ // https://github.com/v8/v8/blob/8cd3cf297287e581a49e487067f5cbd991b27123/src/js/math.js#L217
+ var length = arguments.length;
+ var args = [];
+ var max = 0;
+ for (var i = 0; i < length; i++) {
+ var n = arguments[i];
+ n = +n;
+ if (n === Infinity || n === -Infinity) {
+ return Infinity;
+ }
+ n = Math.abs(n);
+ if (n > max) {
+ max = n;
+ }
+ args[i] = n;
+ }
+
+ if (max === 0) {
+ max = 1;
+ }
+ var sum = 0;
+ var compensation = 0;
+ for (var j = 0; j < length; j++) {
+ var m = args[j] / max;
+ var summand = m * m - compensation;
+ var preliminary = sum + summand;
+ compensation = preliminary - sum - summand;
+ sum = preliminary;
+ }
+ return Math.sqrt(sum) * max;
+}
+
+module.exports = p5;
+
+},{"../core/core":22}],51:[function(_dereq_,module,exports){
+/**
+ * @module Math
+ * @submodule Math
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+/**
+ * Creates a new p5.Vector (the datatype for storing vectors). This provides a
+ * two or three dimensional vector, specifically a Euclidean (also known as
+ * geometric) vector. A vector is an entity that has both magnitude and
+ * direction.
+ *
+ * @method createVector
+ * @param {Number} [x] x component of the vector
+ * @param {Number} [y] y component of the vector
+ * @param {Number} [z] z component of the vector
+ * @return {p5.Vector}
+ * @example
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * noStroke();
+ * fill(255, 102, 204);
+ * }
+ *
+ * function draw() {
+ * background(255);
+ * pointLight(color(255), createVector(sin(millis() / 1000) * 20, -40, -10));
+ * scale(0.75);
+ * sphere();
+ * }
+ *
+ *
+ * @alt
+ * a purple sphere lit by a point light oscillating horizontally
+ */
+p5.prototype.createVector = function(x, y, z) {
+ if (this instanceof p5) {
+ return new p5.Vector(this, arguments);
+ } else {
+ return new p5.Vector(x, y, z);
+ }
+};
+
+module.exports = p5;
+
+},{"../core/core":22}],52:[function(_dereq_,module,exports){
+//////////////////////////////////////////////////////////////
+
+// http://mrl.nyu.edu/~perlin/noise/
+// Adapting from PApplet.java
+// which was adapted from toxi
+// which was adapted from the german demo group farbrausch
+// as used in their demo "art": http://www.farb-rausch.de/fr010src.zip
+
+// someday we might consider using "improved noise"
+// http://mrl.nyu.edu/~perlin/paper445.pdf
+// See: https://github.com/shiffman/The-Nature-of-Code-Examples-p5.js/
+// blob/master/introduction/Noise1D/noise.js
+
+/**
+ * @module Math
+ * @submodule Noise
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+var PERLIN_YWRAPB = 4;
+var PERLIN_YWRAP = 1 << PERLIN_YWRAPB;
+var PERLIN_ZWRAPB = 8;
+var PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB;
+var PERLIN_SIZE = 4095;
+
+var perlin_octaves = 4; // default to medium smooth
+var perlin_amp_falloff = 0.5; // 50% reduction/octave
+
+var scaled_cosine = function(i) {
+ return 0.5 * (1.0 - Math.cos(i * Math.PI));
+};
+
+var perlin; // will be initialized lazily by noise() or noiseSeed()
+
+/**
+ * Returns the Perlin noise value at specified coordinates. Perlin noise is
+ * a random sequence generator producing a more natural ordered, harmonic
+ * succession of numbers compared to the standard random() function.
+ * It was invented by Ken Perlin in the 1980s and been used since in
+ * graphical applications to produce procedural textures, natural motion,
+ * shapes, terrains etc.
The main difference to the
+ * random() function is that Perlin noise is defined in an infinite
+ * n-dimensional space where each pair of coordinates corresponds to a
+ * fixed semi-random value (fixed only for the lifespan of the program; see
+ * the noiseSeed() function). p5.js can compute 1D, 2D and 3D noise,
+ * depending on the number of coordinates given. The resulting value will
+ * always be between 0.0 and 1.0. The noise value can be animated by moving
+ * through the noise space as demonstrated in the example above. The 2nd
+ * and 3rd dimension can also be interpreted as time.
The actual
+ * noise is structured similar to an audio signal, in respect to the
+ * function's use of frequencies. Similar to the concept of harmonics in
+ * physics, perlin noise is computed over several octaves which are added
+ * together for the final result.
Another way to adjust the
+ * character of the resulting sequence is the scale of the input
+ * coordinates. As the function works within an infinite space the value of
+ * the coordinates doesn't matter as such, only the distance between
+ * successive coordinates does (eg. when using noise() within a
+ * loop). As a general rule the smaller the difference between coordinates,
+ * the smoother the resulting noise sequence will be. Steps of 0.005-0.03
+ * work best for most applications, but this will differ depending on use.
+ *
+ *
+ * @method noise
+ * @param {Number} x x-coordinate in noise space
+ * @param {Number} [y] y-coordinate in noise space
+ * @param {Number} [z] z-coordinate in noise space
+ * @return {Number} Perlin noise value (between 0 and 1) at specified
+ * coordinates
+ * @example
+ *
+ *
+ * var xoff = 0.0;
+ *
+ * function draw() {
+ * background(204);
+ * xoff = xoff + 0.01;
+ * var n = noise(xoff) * width;
+ * line(n, 0, n, height);
+ * }
+ *
+ *
+ *
+ * var noiseScale=0.02;
+ *
+ * function draw() {
+ * background(0);
+ * for (var x=0; x < width; x++) {
+ * var noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);
+ * stroke(noiseVal*255);
+ * line(x, mouseY+noiseVal*80, x, height);
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical line moves left to right with updating noise values.
+ * horizontal wave pattern effected by mouse x-position & updating noise values.
+ *
+ */
+
+p5.prototype.noise = function(x, y, z) {
+ y = y || 0;
+ z = z || 0;
+
+ if (perlin == null) {
+ perlin = new Array(PERLIN_SIZE + 1);
+ for (var i = 0; i < PERLIN_SIZE + 1; i++) {
+ perlin[i] = Math.random();
+ }
+ }
+
+ if (x < 0) {
+ x = -x;
+ }
+ if (y < 0) {
+ y = -y;
+ }
+ if (z < 0) {
+ z = -z;
+ }
+
+ var xi = Math.floor(x),
+ yi = Math.floor(y),
+ zi = Math.floor(z);
+ var xf = x - xi;
+ var yf = y - yi;
+ var zf = z - zi;
+ var rxf, ryf;
+
+ var r = 0;
+ var ampl = 0.5;
+
+ var n1, n2, n3;
+
+ for (var o = 0; o < perlin_octaves; o++) {
+ var of = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB);
+
+ rxf = scaled_cosine(xf);
+ ryf = scaled_cosine(yf);
+
+ n1 = perlin[of & PERLIN_SIZE];
+ n1 += rxf * (perlin[(of + 1) & PERLIN_SIZE] - n1);
+ n2 = perlin[(of + PERLIN_YWRAP) & PERLIN_SIZE];
+ n2 += rxf * (perlin[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2);
+ n1 += ryf * (n2 - n1);
+
+ of += PERLIN_ZWRAP;
+ n2 = perlin[of & PERLIN_SIZE];
+ n2 += rxf * (perlin[(of + 1) & PERLIN_SIZE] - n2);
+ n3 = perlin[(of + PERLIN_YWRAP) & PERLIN_SIZE];
+ n3 += rxf * (perlin[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3);
+ n2 += ryf * (n3 - n2);
+
+ n1 += scaled_cosine(zf) * (n2 - n1);
+
+ r += n1 * ampl;
+ ampl *= perlin_amp_falloff;
+ xi <<= 1;
+ xf *= 2;
+ yi <<= 1;
+ yf *= 2;
+ zi <<= 1;
+ zf *= 2;
+
+ if (xf >= 1.0) {
+ xi++;
+ xf--;
+ }
+ if (yf >= 1.0) {
+ yi++;
+ yf--;
+ }
+ if (zf >= 1.0) {
+ zi++;
+ zf--;
+ }
+ }
+ return r;
+};
+
+/**
+ *
+ * Adjusts the character and level of detail produced by the Perlin noise
+ * function. Similar to harmonics in physics, noise is computed over
+ * several octaves. Lower octaves contribute more to the output signal and
+ * as such define the overall intensity of the noise, whereas higher octaves
+ * create finer grained details in the noise sequence.
+ *
+ * By default, noise is computed over 4 octaves with each octave contributing
+ * exactly half than its predecessor, starting at 50% strength for the 1st
+ * octave. This falloff amount can be changed by adding an additional function
+ * parameter. Eg. a falloff factor of 0.75 means each octave will now have
+ * 75% impact (25% less) of the previous lower octave. Any value between
+ * 0.0 and 1.0 is valid, however note that values greater than 0.5 might
+ * result in greater than 1.0 values returned by noise().
+ *
+ * By changing these parameters, the signal created by the noise()
+ * function can be adapted to fit very specific needs and characteristics.
+ *
+ * @method noiseDetail
+ * @param {Number} lod number of octaves to be used by the noise
+ * @param {Number} falloff falloff factor for each octave
+ * @example
+ *
+ *
+ * var noiseVal;
+ * var noiseScale = 0.02;
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * }
+ *
+ * function draw() {
+ * background(0);
+ * for (var y = 0; y < height; y++) {
+ * for (var x = 0; x < width / 2; x++) {
+ * noiseDetail(2, 0.2);
+ * noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);
+ * stroke(noiseVal * 255);
+ * point(x, y);
+ * noiseDetail(8, 0.65);
+ * noiseVal = noise(
+ * (mouseX + x + width / 2) * noiseScale,
+ * (mouseY + y) * noiseScale
+ * );
+ * stroke(noiseVal * 255);
+ * point(x + width / 2, y);
+ * }
+ * }
+ * }
+ *
+ *
+ *
+ * @alt
+ * 2 vertical grey smokey patterns affected my mouse x-position and noise.
+ *
+ */
+p5.prototype.noiseDetail = function(lod, falloff) {
+ if (lod > 0) {
+ perlin_octaves = lod;
+ }
+ if (falloff > 0) {
+ perlin_amp_falloff = falloff;
+ }
+};
+
+/**
+ * Sets the seed value for noise(). By default, noise()
+ * produces different results each time the program is run. Set the
+ * value parameter to a constant to return the same pseudo-random
+ * numbers each time the software is run.
+ *
+ * @method noiseSeed
+ * @param {Number} seed the seed value
+ * @example
+ *
+ * var xoff = 0.0;
+ *
+ * function setup() {
+ * noiseSeed(99);
+ * stroke(0, 10);
+ * }
+ *
+ * function draw() {
+ * xoff = xoff + .01;
+ * var n = noise(xoff) * width;
+ * line(n, 0, n, height);
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical grey lines drawing in pattern affected by noise.
+ *
+ */
+p5.prototype.noiseSeed = function(seed) {
+ // Linear Congruential Generator
+ // Variant of a Lehman Generator
+ var lcg = (function() {
+ // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes
+ // m is basically chosen to be large (as it is the max period)
+ // and for its relationships to a and c
+ var m = 4294967296;
+ // a - 1 should be divisible by m's prime factors
+ var a = 1664525;
+ // c and m should be co-prime
+ var c = 1013904223;
+ var seed, z;
+ return {
+ setSeed: function(val) {
+ // pick a random seed if val is undefined or null
+ // the >>> 0 casts the seed to an unsigned 32-bit integer
+ z = seed = (val == null ? Math.random() * m : val) >>> 0;
+ },
+ getSeed: function() {
+ return seed;
+ },
+ rand: function() {
+ // define the recurrence relationship
+ z = (a * z + c) % m;
+ // return a float in [0, 1)
+ // if z = m then z / m = 0 therefore (z % m) / m < 1 always
+ return z / m;
+ }
+ };
+ })();
+
+ lcg.setSeed(seed);
+ perlin = new Array(PERLIN_SIZE + 1);
+ for (var i = 0; i < PERLIN_SIZE + 1; i++) {
+ perlin[i] = lcg.rand();
+ }
+};
+
+module.exports = p5;
+
+},{"../core/core":22}],53:[function(_dereq_,module,exports){
+/**
+ * @module Math
+ * @submodule Math
+ * @requires constants
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+var constants = _dereq_('../core/constants');
+
+/**
+ * A class to describe a two or three dimensional vector, specifically
+ * a Euclidean (also known as geometric) vector. A vector is an entity
+ * that has both magnitude and direction. The datatype, however, stores
+ * the components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude
+ * and direction can be accessed via the methods mag() and heading().
+ *
+ * In many of the p5.js examples, you will see p5.Vector used to describe a
+ * position, velocity, or acceleration. For example, if you consider a rectangle
+ * moving across the screen, at any given instant it has a position (a vector
+ * that points from the origin to its location), a velocity (the rate at which
+ * the object's position changes per time unit, expressed as a vector), and
+ * acceleration (the rate at which the object's velocity changes per time
+ * unit, expressed as a vector).
+ *
+ * Since vectors represent groupings of values, we cannot simply use
+ * traditional addition/multiplication/etc. Instead, we'll need to do some
+ * "vector" math, which is made easy by the methods inside the p5.Vector class.
+ *
+ * @class p5.Vector
+ * @param {Number} [x] x component of the vector
+ * @param {Number} [y] y component of the vector
+ * @param {Number} [z] z component of the vector
+ * @example
+ *
+ *
+ * var v1 = createVector(40, 50);
+ * var v2 = createVector(40, 50);
+ *
+ * ellipse(v1.x, v1.y, 50, 50);
+ * ellipse(v2.x, v2.y, 50, 50);
+ * v1.add(v2);
+ * ellipse(v1.x, v1.y, 50, 50);
+ *
+ *
+ *
+ * @alt
+ * 2 white ellipses. One center-left the other bottom right and off canvas
+ *
+ */
+p5.Vector = function Vector() {
+ var x, y, z;
+ // This is how it comes in with createVector()
+ if (arguments[0] instanceof p5) {
+ // save reference to p5 if passed in
+ this.p5 = arguments[0];
+ x = arguments[1][0] || 0;
+ y = arguments[1][1] || 0;
+ z = arguments[1][2] || 0;
+ // This is what we'll get with new p5.Vector()
+ } else {
+ x = arguments[0] || 0;
+ y = arguments[1] || 0;
+ z = arguments[2] || 0;
+ }
+ /**
+ * The x component of the vector
+ * @property x {Number}
+ */
+ this.x = x;
+ /**
+ * The y component of the vector
+ * @property y {Number}
+ */
+ this.y = y;
+ /**
+ * The z component of the vector
+ * @property z {Number}
+ */
+ this.z = z;
+};
+
+/**
+ * Returns a string representation of a vector v by calling String(v)
+ * or v.toString(). This method is useful for logging vectors in the
+ * console.
+ * @method toString
+ * @return {String}
+ * @example
+ *
+ *
+ * function setup() {
+ * var v = createVector(20, 30);
+ * print(String(v)); // prints "p5.Vector Object : [20, 30, 0]"
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(0, 0);
+ * var v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'black');
+ *
+ * noStroke();
+ * text(v1.toString(), 10, 25, 90, 75);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.prototype.toString = function p5VectorToString() {
+ return 'p5.Vector Object : [' + this.x + ', ' + this.y + ', ' + this.z + ']';
+};
+
+/**
+ * Sets the x, y, and z component of the vector using two or three separate
+ * variables, the data from a p5.Vector, or the values from a float array.
+ * @method set
+ * @param {Number} [x] the x component of the vector
+ * @param {Number} [y] the y component of the vector
+ * @param {Number} [z] the z component of the vector
+ * @chainable
+ * @example
+ *
+ *
+ * function setup() {
+ * var v = createVector(1, 2, 3);
+ * v.set(4, 5, 6); // Sets vector to [4, 5, 6]
+ *
+ * var v1 = createVector(0, 0, 0);
+ * var arr = [1, 2, 3];
+ * v1.set(arr); // Sets vector to [1, 2, 3]
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var v0, v1;
+ * function setup() {
+ * createCanvas(100, 100);
+ *
+ * v0 = createVector(0, 0);
+ * v1 = createVector(50, 50);
+ * }
+ *
+ * function draw() {
+ * background(240);
+ *
+ * drawArrow(v0, v1, 'black');
+ * v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1));
+ *
+ * noStroke();
+ * text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+/**
+ * @method set
+ * @param {p5.Vector|Number[]} value the vector to set
+ * @chainable
+ */
+p5.Vector.prototype.set = function set(x, y, z) {
+ if (x instanceof p5.Vector) {
+ this.x = x.x || 0;
+ this.y = x.y || 0;
+ this.z = x.z || 0;
+ return this;
+ }
+ if (x instanceof Array) {
+ this.x = x[0] || 0;
+ this.y = x[1] || 0;
+ this.z = x[2] || 0;
+ return this;
+ }
+ this.x = x || 0;
+ this.y = y || 0;
+ this.z = z || 0;
+ return this;
+};
+
+/**
+ * Gets a copy of the vector, returns a p5.Vector object.
+ *
+ * @method copy
+ * @return {p5.Vector} the copy of the p5.Vector object
+ * @example
+ *
+ *
+ * var v1 = createVector(1, 2, 3);
+ * var v2 = v1.copy();
+ * print(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z);
+ * // Prints "true"
+ *
+ *
+ */
+p5.Vector.prototype.copy = function copy() {
+ if (this.p5) {
+ return new p5.Vector(this.p5, [this.x, this.y, this.z]);
+ } else {
+ return new p5.Vector(this.x, this.y, this.z);
+ }
+};
+
+/**
+ * Adds x, y, and z components to a vector, adds one vector to another, or
+ * adds two independent vectors together. The version of the method that adds
+ * two vectors together is a static method and returns a p5.Vector, the others
+ * acts directly on the vector. See the examples for more context.
+ *
+ * @method add
+ * @param {Number} x the x component of the vector to be added
+ * @param {Number} [y] the y component of the vector to be added
+ * @param {Number} [z] the z component of the vector to be added
+ * @chainable
+ * @example
+ *
+ *
+ * var v = createVector(1, 2, 3);
+ * v.add(4, 5, 6);
+ * // v's components are set to [5, 7, 9]
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * var v1 = createVector(1, 2, 3);
+ * var v2 = createVector(2, 3, 4);
+ *
+ * var v3 = p5.Vector.add(v1, v2);
+ * // v3 has components [3, 5, 7]
+ * print(v3);
+ *
+ *
+ *
+ *
+ *
+ * // red vector + blue vector = purple vector
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(0, 0);
+ * var v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'red');
+ *
+ * var v2 = createVector(-30, 20);
+ * drawArrow(v1, v2, 'blue');
+ *
+ * var v3 = p5.Vector.add(v1, v2);
+ * drawArrow(v0, v3, 'purple');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+/**
+ * @method add
+ * @param {p5.Vector|Number[]} value the vector to add
+ * @chainable
+ */
+p5.Vector.prototype.add = function add(x, y, z) {
+ if (x instanceof p5.Vector) {
+ this.x += x.x || 0;
+ this.y += x.y || 0;
+ this.z += x.z || 0;
+ return this;
+ }
+ if (x instanceof Array) {
+ this.x += x[0] || 0;
+ this.y += x[1] || 0;
+ this.z += x[2] || 0;
+ return this;
+ }
+ this.x += x || 0;
+ this.y += y || 0;
+ this.z += z || 0;
+ return this;
+};
+
+/**
+ * Subtracts x, y, and z components from a vector, subtracts one vector from
+ * another, or subtracts two independent vectors. The version of the method
+ * that subtracts two vectors is a static method and returns a p5.Vector, the
+ * other acts directly on the vector. See the examples for more context.
+ *
+ * @method sub
+ * @param {Number} x the x component of the vector to subtract
+ * @param {Number} [y] the y component of the vector to subtract
+ * @param {Number} [z] the z component of the vector to subtract
+ * @chainable
+ * @example
+ *
+ *
+ * var v = createVector(4, 5, 6);
+ * v.sub(1, 1, 1);
+ * // v's components are set to [3, 4, 5]
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * var v1 = createVector(2, 3, 4);
+ * var v2 = createVector(1, 2, 3);
+ *
+ * var v3 = p5.Vector.sub(v1, v2);
+ * // v3 has components [1, 1, 1]
+ * print(v3);
+ *
+ *
+ *
+ *
+ *
+ * // red vector - blue vector = purple vector
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(0, 0);
+ * var v1 = createVector(70, 50);
+ * drawArrow(v0, v1, 'red');
+ *
+ * var v2 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * var v3 = p5.Vector.sub(v1, v2);
+ * drawArrow(v2, v3, 'purple');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+/**
+ * @method sub
+ * @param {p5.Vector|Number[]} value the vector to subtract
+ * @chainable
+ */
+p5.Vector.prototype.sub = function sub(x, y, z) {
+ if (x instanceof p5.Vector) {
+ this.x -= x.x || 0;
+ this.y -= x.y || 0;
+ this.z -= x.z || 0;
+ return this;
+ }
+ if (x instanceof Array) {
+ this.x -= x[0] || 0;
+ this.y -= x[1] || 0;
+ this.z -= x[2] || 0;
+ return this;
+ }
+ this.x -= x || 0;
+ this.y -= y || 0;
+ this.z -= z || 0;
+ return this;
+};
+
+/**
+ * Multiply the vector by a scalar. The static version of this method
+ * creates a new p5.Vector while the non static version acts on the vector
+ * directly. See the examples for more context.
+ *
+ * @method mult
+ * @param {Number} n the number to multiply with the vector
+ * @chainable
+ * @example
+ *
+ *
+ * var v = createVector(1, 2, 3);
+ * v.mult(2);
+ * // v's components are set to [2, 4, 6]
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * var v1 = createVector(1, 2, 3);
+ * var v2 = p5.Vector.mult(v1, 2);
+ * // v2 has components [2, 4, 6]
+ * print(v2);
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(50, 50);
+ * var v1 = createVector(25, -25);
+ * drawArrow(v0, v1, 'red');
+ *
+ * var num = map(mouseX, 0, width, -2, 2, true);
+ * var v2 = p5.Vector.mult(v1, num);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * noStroke();
+ * text('multiplied by ' + num.toFixed(2), 5, 90);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.prototype.mult = function mult(n) {
+ if (!(typeof n === 'number' && isFinite(n))) {
+ console.warn(
+ 'p5.Vector.prototype.mult:',
+ 'n is undefined or not a finite number'
+ );
+ return this;
+ }
+ this.x *= n;
+ this.y *= n;
+ this.z *= n;
+ return this;
+};
+
+/**
+ * Divide the vector by a scalar. The static version of this method creates a
+ * new p5.Vector while the non static version acts on the vector directly.
+ * See the examples for more context.
+ *
+ * @method div
+ * @param {number} n the number to divide the vector by
+ * @chainable
+ * @example
+ *
+ *
+ * var v = createVector(6, 4, 2);
+ * v.div(2); //v's components are set to [3, 2, 1]
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * var v1 = createVector(6, 4, 2);
+ * var v2 = p5.Vector.div(v1, 2);
+ * // v2 has components [3, 2, 1]
+ * print(v2);
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(0, 100);
+ * var v1 = createVector(50, -50);
+ * drawArrow(v0, v1, 'red');
+ *
+ * var num = map(mouseX, 0, width, 10, 0.5, true);
+ * var v2 = p5.Vector.div(v1, num);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * noStroke();
+ * text('divided by ' + num.toFixed(2), 10, 90);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.prototype.div = function div(n) {
+ if (!(typeof n === 'number' && isFinite(n))) {
+ console.warn(
+ 'p5.Vector.prototype.div:',
+ 'n is undefined or not a finite number'
+ );
+ return this;
+ }
+ if (n === 0) {
+ console.warn('p5.Vector.prototype.div:', 'divide by 0');
+ return this;
+ }
+ this.x /= n;
+ this.y /= n;
+ this.z /= n;
+ return this;
+};
+
+/**
+ * Calculates the magnitude (length) of the vector and returns the result as
+ * a float (this is simply the equation sqrt(x*x + y*y + z*z).)
+ *
+ * @method mag
+ * @return {Number} magnitude of the vector
+ * @example
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(0, 0);
+ * var v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'black');
+ *
+ * noStroke();
+ * text('vector length: ' + v1.mag().toFixed(2), 10, 70, 90, 30);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ *
+ *
+ * var v = createVector(20.0, 30.0, 40.0);
+ * var m = v.mag();
+ * print(m); // Prints "53.85164807134504"
+ *
+ *
+ */
+p5.Vector.prototype.mag = function mag() {
+ return Math.sqrt(this.magSq());
+};
+
+/**
+ * Calculates the squared magnitude of the vector and returns the result
+ * as a float (this is simply the equation (x*x + y*y + z*z).)
+ * Faster if the real length is not required in the
+ * case of comparing vectors, etc.
+ *
+ * @method magSq
+ * @return {number} squared magnitude of the vector
+ * @example
+ *
+ *
+ * // Static method
+ * var v1 = createVector(6, 4, 2);
+ * print(v1.magSq()); // Prints "56"
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(0, 0);
+ * var v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'black');
+ *
+ * noStroke();
+ * text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.prototype.magSq = function magSq() {
+ var x = this.x;
+ var y = this.y;
+ var z = this.z;
+ return x * x + y * y + z * z;
+};
+
+/**
+ * Calculates the dot product of two vectors. The version of the method
+ * that computes the dot product of two independent vectors is a static
+ * method. See the examples for more context.
+ *
+ *
+ * @method dot
+ * @param {Number} x x component of the vector
+ * @param {Number} [y] y component of the vector
+ * @param {Number} [z] z component of the vector
+ * @return {Number} the dot product
+ *
+ * @example
+ *
+ *
+ * var v1 = createVector(1, 2, 3);
+ * var v2 = createVector(2, 3, 4);
+ *
+ * print(v1.dot(v2)); // Prints "20"
+ *
+ *
+ *
+ *
+ *
+ * //Static method
+ * var v1 = createVector(1, 2, 3);
+ * var v2 = createVector(3, 2, 1);
+ * print(p5.Vector.dot(v1, v2)); // Prints "10"
+ *
+ *
+ */
+/**
+ * @method dot
+ * @param {p5.Vector} value value component of the vector or a p5.Vector
+ * @return {Number}
+ */
+p5.Vector.prototype.dot = function dot(x, y, z) {
+ if (x instanceof p5.Vector) {
+ return this.dot(x.x, x.y, x.z);
+ }
+ return this.x * (x || 0) + this.y * (y || 0) + this.z * (z || 0);
+};
+
+/**
+ * Calculates and returns a vector composed of the cross product between
+ * two vectors. Both the static and non static methods return a new p5.Vector.
+ * See the examples for more context.
+ *
+ * @method cross
+ * @param {p5.Vector} v p5.Vector to be crossed
+ * @return {p5.Vector} p5.Vector composed of cross product
+ * @example
+ *
+ *
+ * var v1 = createVector(1, 2, 3);
+ * var v2 = createVector(1, 2, 3);
+ *
+ * v1.cross(v2); // v's components are [0, 0, 0]
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * var v1 = createVector(1, 0, 0);
+ * var v2 = createVector(0, 1, 0);
+ *
+ * var crossProduct = p5.Vector.cross(v1, v2);
+ * // crossProduct has components [0, 0, 1]
+ * print(crossProduct);
+ *
+ *
+ */
+p5.Vector.prototype.cross = function cross(v) {
+ var x = this.y * v.z - this.z * v.y;
+ var y = this.z * v.x - this.x * v.z;
+ var z = this.x * v.y - this.y * v.x;
+ if (this.p5) {
+ return new p5.Vector(this.p5, [x, y, z]);
+ } else {
+ return new p5.Vector(x, y, z);
+ }
+};
+
+/**
+ * Calculates the Euclidean distance between two points (considering a
+ * point as a vector object).
+ *
+ * @method dist
+ * @param {p5.Vector} v the x, y, and z coordinates of a p5.Vector
+ * @return {Number} the distance
+ * @example
+ *
+ *
+ * var v1 = createVector(1, 0, 0);
+ * var v2 = createVector(0, 1, 0);
+ *
+ * var distance = v1.dist(v2); // distance is 1.4142...
+ * print(distance);
+ *
+ *
+ *
+ *
+ *
+ * // Static method
+ * var v1 = createVector(1, 0, 0);
+ * var v2 = createVector(0, 1, 0);
+ *
+ * var distance = p5.Vector.dist(v1, v2);
+ * // distance is 1.4142...
+ * print(distance);
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(0, 0);
+ *
+ * var v1 = createVector(70, 50);
+ * drawArrow(v0, v1, 'red');
+ *
+ * var v2 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * noStroke();
+ * text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.prototype.dist = function dist(v) {
+ return v
+ .copy()
+ .sub(this)
+ .mag();
+};
+
+/**
+ * Normalize the vector to length 1 (make it a unit vector).
+ *
+ * @method normalize
+ * @return {p5.Vector} normalized p5.Vector
+ * @example
+ *
+ *
+ * var v = createVector(10, 20, 2);
+ * // v has components [10.0, 20.0, 2.0]
+ * v.normalize();
+ * // v's components are set to
+ * // [0.4454354, 0.8908708, 0.089087084]
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(50, 50);
+ * var v1 = createVector(mouseX - 50, mouseY - 50);
+ *
+ * drawArrow(v0, v1, 'red');
+ * v1.normalize();
+ * drawArrow(v0, v1.mult(35), 'blue');
+ *
+ * noFill();
+ * ellipse(50, 50, 35 * 2);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.prototype.normalize = function normalize() {
+ var len = this.mag();
+ // here we multiply by the reciprocal instead of calling 'div()'
+ // since div duplicates this zero check.
+ if (len !== 0) this.mult(1 / len);
+ return this;
+};
+
+/**
+ * Limit the magnitude of this vector to the value used for the max
+ * parameter.
+ *
+ * @method limit
+ * @param {Number} max the maximum magnitude for the vector
+ * @chainable
+ * @example
+ *
+ *
+ * var v = createVector(10, 20, 2);
+ * // v has components [10.0, 20.0, 2.0]
+ * v.limit(5);
+ * // v's components are set to
+ * // [2.2271771, 4.4543543, 0.4454354]
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(50, 50);
+ * var v1 = createVector(mouseX - 50, mouseY - 50);
+ *
+ * drawArrow(v0, v1, 'red');
+ * drawArrow(v0, v1.limit(35), 'blue');
+ *
+ * noFill();
+ * ellipse(50, 50, 35 * 2);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.prototype.limit = function limit(max) {
+ var mSq = this.magSq();
+ if (mSq > max * max) {
+ this.div(Math.sqrt(mSq)) //normalize it
+ .mult(max);
+ }
+ return this;
+};
+
+/**
+ * Set the magnitude of this vector to the value used for the len
+ * parameter.
+ *
+ * @method setMag
+ * @param {number} len the new length for this vector
+ * @chainable
+ * @example
+ *
+ *
+ * var v = createVector(10, 20, 2);
+ * // v has components [10.0, 20.0, 2.0]
+ * v.setMag(10);
+ * // v's components are set to [6.0, 8.0, 0.0]
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(0, 0);
+ * var v1 = createVector(50, 50);
+ *
+ * drawArrow(v0, v1, 'red');
+ *
+ * var length = map(mouseX, 0, width, 0, 141, true);
+ * v1.setMag(length);
+ * drawArrow(v0, v1, 'blue');
+ *
+ * noStroke();
+ * text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.prototype.setMag = function setMag(n) {
+ return this.normalize().mult(n);
+};
+
+/**
+ * Calculate the angle of rotation for this vector (only 2D vectors)
+ *
+ * @method heading
+ * @return {Number} the angle of rotation
+ * @example
+ *
+ *
+ * function setup() {
+ * var v1 = createVector(30, 50);
+ * print(v1.heading()); // 1.0303768265243125
+ *
+ * v1 = createVector(40, 50);
+ * print(v1.heading()); // 0.8960553845713439
+ *
+ * v1 = createVector(30, 70);
+ * print(v1.heading()); // 1.1659045405098132
+ * }
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(50, 50);
+ * var v1 = createVector(mouseX - 50, mouseY - 50);
+ *
+ * drawArrow(v0, v1, 'black');
+ *
+ * var myHeading = v1.heading();
+ * noStroke();
+ * text(
+ * 'vector heading: ' +
+ * myHeading.toFixed(2) +
+ * ' radians or ' +
+ * degrees(myHeading).toFixed(2) +
+ * ' degrees',
+ * 10,
+ * 50,
+ * 90,
+ * 50
+ * );
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.prototype.heading = function heading() {
+ var h = Math.atan2(this.y, this.x);
+ if (this.p5) return this.p5._fromRadians(h);
+ return h;
+};
+
+/**
+ * Rotate the vector by an angle (only 2D vectors), magnitude remains the
+ * same
+ *
+ * @method rotate
+ * @param {number} angle the angle of rotation
+ * @chainable
+ * @example
+ *
+ *
+ * var v = createVector(10.0, 20.0);
+ * // v has components [10.0, 20.0, 0.0]
+ * v.rotate(HALF_PI);
+ * // v's components are set to [-20.0, 9.999999, 0.0]
+ *
+ *
+ *
+ *
+ *
+ * var angle = 0;
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(50, 50);
+ * var v1 = createVector(50, 0);
+ *
+ * drawArrow(v0, v1.rotate(angle), 'black');
+ * angle += 0.01;
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.prototype.rotate = function rotate(a) {
+ var newHeading = this.heading() + a;
+ if (this.p5) newHeading = this.p5._toRadians(newHeading);
+ var mag = this.mag();
+ this.x = Math.cos(newHeading) * mag;
+ this.y = Math.sin(newHeading) * mag;
+ return this;
+};
+
+/**
+ * Calculates and returns the angle (in radians) between two vectors.
+ * @method angleBetween
+ * @param {p5.Vector} the x, y, and z components of a p5.Vector
+ * @return {Number} the angle between (in radians)
+ * @example
+ *
+ *
+ * var v1 = createVector(1, 0, 0);
+ * var v2 = createVector(0, 1, 0);
+ *
+ * var angle = v1.angleBetween(v2);
+ * // angle is PI/2
+ * print(angle);
+ *
+ *
+ *
+ *
+ *
+ * function draw() {
+ * background(240);
+ * var v0 = createVector(50, 50);
+ *
+ * var v1 = createVector(50, 0);
+ * drawArrow(v0, v1, 'red');
+ *
+ * var v2 = createVector(mouseX - 50, mouseY - 50);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * var angleBetween = v1.angleBetween(v2);
+ * noStroke();
+ * text(
+ * 'angle between: ' +
+ * angleBetween.toFixed(2) +
+ * ' radians or ' +
+ * degrees(angleBetween).toFixed(2) +
+ * ' degrees',
+ * 10,
+ * 50,
+ * 90,
+ * 50
+ * );
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.prototype.angleBetween = function angleBetween(v) {
+ var dotmagmag = this.dot(v) / (this.mag() * v.mag());
+ // Mathematically speaking: the dotmagmag variable will be between -1 and 1
+ // inclusive. Practically though it could be slightly outside this range due
+ // to floating-point rounding issues. This can make Math.acos return NaN.
+ //
+ // Solution: we'll clamp the value to the -1,1 range
+ var angle = Math.acos(Math.min(1, Math.max(-1, dotmagmag)));
+ if (this.p5) return this.p5._fromRadians(angle);
+ return angle;
+};
+
+/**
+ * Linear interpolate the vector to another vector
+ *
+ * @method lerp
+ * @param {Number} x the x component
+ * @param {Number} y the y component
+ * @param {Number} z the z component
+ * @param {Number} amt the amount of interpolation; some value between 0.0
+ * (old vector) and 1.0 (new vector). 0.9 is very near
+ * the new vector. 0.5 is halfway in between.
+ * @chainable
+ *
+ * @example
+ *
+ *
+ * var v = createVector(1, 1, 0);
+ *
+ * v.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]
+ *
+ *
+ *
+ *
+ *
+ * var v1 = createVector(0, 0, 0);
+ * var v2 = createVector(100, 100, 0);
+ *
+ * var v3 = p5.Vector.lerp(v1, v2, 0.5);
+ * // v3 has components [50,50,0]
+ * print(v3);
+ *
+ *
+ *
+ *
+ *
+ * var step = 0.01;
+ * var amount = 0;
+ *
+ * function draw() {
+ * background(240);
+ * var v0 = createVector(0, 0);
+ *
+ * var v1 = createVector(mouseX, mouseY);
+ * drawArrow(v0, v1, 'red');
+ *
+ * var v2 = createVector(90, 90);
+ * drawArrow(v0, v2, 'blue');
+ *
+ * if (amount > 1 || amount < 0) {
+ * step *= -1;
+ * }
+ * amount += step;
+ * var v3 = p5.Vector.lerp(v1, v2, amount);
+ *
+ * drawArrow(v0, v3, 'purple');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+/**
+ * @method lerp
+ * @param {p5.Vector} v the p5.Vector to lerp to
+ * @param {Number} amt
+ * @chainable
+ */
+p5.Vector.prototype.lerp = function lerp(x, y, z, amt) {
+ if (x instanceof p5.Vector) {
+ return this.lerp(x.x, x.y, x.z, y);
+ }
+ this.x += (x - this.x) * amt || 0;
+ this.y += (y - this.y) * amt || 0;
+ this.z += (z - this.z) * amt || 0;
+ return this;
+};
+
+/**
+ * Return a representation of this vector as a float array. This is only
+ * for temporary use. If used in any other fashion, the contents should be
+ * copied by using the p5.Vector.copy() method to copy into your own
+ * array.
+ *
+ * @method array
+ * @return {Number[]} an Array with the 3 values
+ * @example
+ *
+ *
+ * function setup() {
+ * var v = createVector(20, 30);
+ * print(v.array()); // Prints : Array [20, 30, 0]
+ * }
+ *
+ *
+ *
+ *
+ *
+ * var v = createVector(10.0, 20.0, 30.0);
+ * var f = v.array();
+ * print(f[0]); // Prints "10.0"
+ * print(f[1]); // Prints "20.0"
+ * print(f[2]); // Prints "30.0"
+ *
+ *
+ */
+p5.Vector.prototype.array = function array() {
+ return [this.x || 0, this.y || 0, this.z || 0];
+};
+
+/**
+ * Equality check against a p5.Vector
+ *
+ * @method equals
+ * @param {Number} [x] the x component of the vector
+ * @param {Number} [y] the y component of the vector
+ * @param {Number} [z] the z component of the vector
+ * @return {Boolean} whether the vectors are equals
+ * @example
+ *
+ *
+ * var v1 = createVector(5, 10, 20);
+ * var v2 = createVector(5, 10, 20);
+ * var v3 = createVector(13, 10, 19);
+ *
+ * print(v1.equals(v2.x, v2.y, v2.z)); // true
+ * print(v1.equals(v3.x, v3.y, v3.z)); // false
+ *
+ *
+ *
+ *
+ *
+ * var v1 = createVector(10.0, 20.0, 30.0);
+ * var v2 = createVector(10.0, 20.0, 30.0);
+ * var v3 = createVector(0.0, 0.0, 0.0);
+ * print(v1.equals(v2)); // true
+ * print(v1.equals(v3)); // false
+ *
+ *
+ */
+/**
+ * @method equals
+ * @param {p5.Vector|Array} value the vector to compare
+ * @return {Boolean}
+ */
+p5.Vector.prototype.equals = function equals(x, y, z) {
+ var a, b, c;
+ if (x instanceof p5.Vector) {
+ a = x.x || 0;
+ b = x.y || 0;
+ c = x.z || 0;
+ } else if (x instanceof Array) {
+ a = x[0] || 0;
+ b = x[1] || 0;
+ c = x[2] || 0;
+ } else {
+ a = x || 0;
+ b = y || 0;
+ c = z || 0;
+ }
+ return this.x === a && this.y === b && this.z === c;
+};
+
+// Static Methods
+
+/**
+ * Make a new 2D vector from an angle
+ *
+ * @method fromAngle
+ * @static
+ * @param {Number} angle the desired angle, in radians
+ * @param {Number} [length] the length of the new vector (defaults to 1)
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * function draw() {
+ * background(200);
+ *
+ * // Create a variable, proportional to the mouseX,
+ * // varying from 0-360, to represent an angle in degrees.
+ * angleMode(DEGREES);
+ * var myDegrees = map(mouseX, 0, width, 0, 360);
+ *
+ * // Display that variable in an onscreen text.
+ * // (Note the nfc() function to truncate additional decimal places,
+ * // and the "\xB0" character for the degree symbol.)
+ * var readout = 'angle = ' + nfc(myDegrees, 1) + '\xB0';
+ * noStroke();
+ * fill(0);
+ * text(readout, 5, 15);
+ *
+ * // Create a p5.Vector using the fromAngle function,
+ * // and extract its x and y components.
+ * var v = p5.Vector.fromAngle(radians(myDegrees), 30);
+ * var vx = v.x;
+ * var vy = v.y;
+ *
+ * push();
+ * translate(width / 2, height / 2);
+ * noFill();
+ * stroke(150);
+ * line(0, 0, 30, 0);
+ * stroke(0);
+ * line(0, 0, vx, vy);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.fromAngle = function fromAngle(angle, length) {
+ if (typeof length === 'undefined') {
+ length = 1;
+ }
+ return new p5.Vector(length * Math.cos(angle), length * Math.sin(angle), 0);
+};
+
+/**
+ * Make a new 3D vector from a pair of ISO spherical angles
+ *
+ * @method fromAngles
+ * @static
+ * @param {Number} theta the polar angle, in radians (zero is up)
+ * @param {Number} phi the azimuthal angle, in radians
+ * (zero is out of the screen)
+ * @param {Number} [length] the length of the new vector (defaults to 1)
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * function setup() {
+ * createCanvas(100, 100, WEBGL);
+ * fill(255);
+ * noStroke();
+ * }
+ * function draw() {
+ * background(255);
+ *
+ * var t = millis() / 1000;
+ *
+ * // add three point lights
+ * pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));
+ * pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));
+ * pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));
+ *
+ * sphere(35);
+ * }
+ *
+ *
+ */
+p5.Vector.fromAngles = function(theta, phi, length) {
+ if (typeof length === 'undefined') {
+ length = 1;
+ }
+ var cosPhi = Math.cos(phi);
+ var sinPhi = Math.sin(phi);
+ var cosTheta = Math.cos(theta);
+ var sinTheta = Math.sin(theta);
+
+ return new p5.Vector(
+ length * sinTheta * sinPhi,
+ -length * cosTheta,
+ length * sinTheta * cosPhi
+ );
+};
+
+/**
+ * Make a new 2D unit vector from a random angle
+ *
+ * @method random2D
+ * @static
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * var v = p5.Vector.random2D();
+ * // May make v's attributes something like:
+ * // [0.61554617, -0.51195765, 0.0] or
+ * // [-0.4695841, -0.14366731, 0.0] or
+ * // [0.6091097, -0.22805278, 0.0]
+ * print(v);
+ *
+ *
+ *
+ *
+ *
+ * function setup() {
+ * frameRate(1);
+ * }
+ *
+ * function draw() {
+ * background(240);
+ *
+ * var v0 = createVector(50, 50);
+ * var v1 = p5.Vector.random2D();
+ * drawArrow(v0, v1.mult(50), 'black');
+ * }
+ *
+ * // draw an arrow for a vector at a given base position
+ * function drawArrow(base, vec, myColor) {
+ * push();
+ * stroke(myColor);
+ * strokeWeight(3);
+ * fill(myColor);
+ * translate(base.x, base.y);
+ * line(0, 0, vec.x, vec.y);
+ * rotate(vec.heading());
+ * var arrowSize = 7;
+ * translate(vec.mag() - arrowSize, 0);
+ * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);
+ * pop();
+ * }
+ *
+ *
+ */
+p5.Vector.random2D = function random2D() {
+ return this.fromAngle(Math.random() * constants.TWO_PI);
+};
+
+/**
+ * Make a new random 3D unit vector.
+ *
+ * @method random3D
+ * @static
+ * @return {p5.Vector} the new p5.Vector object
+ * @example
+ *
+ *
+ * var v = p5.Vector.random3D();
+ * // May make v's attributes something like:
+ * // [0.61554617, -0.51195765, 0.599168] or
+ * // [-0.4695841, -0.14366731, -0.8711202] or
+ * // [0.6091097, -0.22805278, -0.7595902]
+ * print(v);
+ *
+ *
+ */
+p5.Vector.random3D = function random3D() {
+ var angle = Math.random() * constants.TWO_PI;
+ var vz = Math.random() * 2 - 1;
+ var vzBase = Math.sqrt(1 - vz * vz);
+ var vx = vzBase * Math.cos(angle);
+ var vy = vzBase * Math.sin(angle);
+ return new p5.Vector(vx, vy, vz);
+};
+
+// Adds two vectors together and returns a new one.
+/**
+ * @method add
+ * @static
+ * @param {p5.Vector} v1 a p5.Vector to add
+ * @param {p5.Vector} v2 a p5.Vector to add
+ * @param {p5.Vector} target the vector to receive the result
+ */
+/**
+ * @method add
+ * @static
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} v2
+ * @return {p5.Vector} the resulting p5.Vector
+ *
+ */
+
+p5.Vector.add = function add(v1, v2, target) {
+ if (!target) {
+ target = v1.copy();
+ } else {
+ target.set(v1);
+ }
+ target.add(v2);
+ return target;
+};
+
+/*
+ * Subtracts one p5.Vector from another and returns a new one. The second
+ * vector (v2) is subtracted from the first (v1), resulting in v1-v2.
+ */
+/**
+ * @method sub
+ * @static
+ * @param {p5.Vector} v1 a p5.Vector to subtract from
+ * @param {p5.Vector} v2 a p5.Vector to subtract
+ * @param {p5.Vector} target if undefined a new vector will be created
+ */
+/**
+ * @method sub
+ * @static
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} v2
+ * @return {p5.Vector} the resulting p5.Vector
+ */
+
+p5.Vector.sub = function sub(v1, v2, target) {
+ if (!target) {
+ target = v1.copy();
+ } else {
+ target.set(v1);
+ }
+ target.sub(v2);
+ return target;
+};
+
+/**
+ * Multiplies a vector by a scalar and returns a new vector.
+ */
+/**
+ * @method mult
+ * @static
+ * @param {p5.Vector} v the vector to multiply
+ * @param {Number} n
+ * @param {p5.Vector} target if undefined a new vector will be created
+ */
+/**
+ * @method mult
+ * @static
+ * @param {p5.Vector} v
+ * @param {Number} n
+ * @return {p5.Vector} the resulting new p5.Vector
+ */
+p5.Vector.mult = function mult(v, n, target) {
+ if (!target) {
+ target = v.copy();
+ } else {
+ target.set(v);
+ }
+ target.mult(n);
+ return target;
+};
+
+/**
+ * Divides a vector by a scalar and returns a new vector.
+ */
+/**
+ * @method div
+ * @static
+ * @param {p5.Vector} v the vector to divide
+ * @param {Number} n
+ * @param {p5.Vector} target if undefined a new vector will be created
+ */
+/**
+ * @method div
+ * @static
+ * @param {p5.Vector} v
+ * @param {Number} n
+ * @return {p5.Vector} the resulting new p5.Vector
+ */
+p5.Vector.div = function div(v, n, target) {
+ if (!target) {
+ target = v.copy();
+ } else {
+ target.set(v);
+ }
+ target.div(n);
+ return target;
+};
+
+/**
+ * Calculates the dot product of two vectors.
+ */
+/**
+ * @method dot
+ * @static
+ * @param {p5.Vector} v1 the first p5.Vector
+ * @param {p5.Vector} v2 the second p5.Vector
+ * @return {Number} the dot product
+ */
+p5.Vector.dot = function dot(v1, v2) {
+ return v1.dot(v2);
+};
+
+/**
+ * Calculates the cross product of two vectors.
+ */
+/**
+ * @method cross
+ * @static
+ * @param {p5.Vector} v1 the first p5.Vector
+ * @param {p5.Vector} v2 the second p5.Vector
+ * @return {Number} the cross product
+ */
+p5.Vector.cross = function cross(v1, v2) {
+ return v1.cross(v2);
+};
+
+/**
+ * Calculates the Euclidean distance between two points (considering a
+ * point as a vector object).
+ */
+/**
+ * @method dist
+ * @static
+ * @param {p5.Vector} v1 the first p5.Vector
+ * @param {p5.Vector} v2 the second p5.Vector
+ * @return {Number} the distance
+ */
+p5.Vector.dist = function dist(v1, v2) {
+ return v1.dist(v2);
+};
+
+/**
+ * Linear interpolate a vector to another vector and return the result as a
+ * new vector.
+ */
+/**
+ * @method lerp
+ * @static
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} v2
+ * @param {Number} amt
+ * @param {p5.Vector} target if undefined a new vector will be created
+ */
+/**
+ * @method lerp
+ * @static
+ * @param {p5.Vector} v1
+ * @param {p5.Vector} v2
+ * @param {Number} amt
+ * @return {Number} the lerped value
+ */
+p5.Vector.lerp = function lerp(v1, v2, amt, target) {
+ if (!target) {
+ target = v1.copy();
+ } else {
+ target.set(v1);
+ }
+ target.lerp(v2, amt);
+ return target;
+};
+
+/**
+ * @method mag
+ * @param {p5.Vector} vecT the vector to return the magnitude of
+ * @return {Number} the magnitude of vecT
+ * @static
+ */
+p5.Vector.mag = function mag(vecT) {
+ var x = vecT.x,
+ y = vecT.y,
+ z = vecT.z;
+ var magSq = x * x + y * y + z * z;
+ return Math.sqrt(magSq);
+};
+
+module.exports = p5.Vector;
+
+},{"../core/constants":21,"../core/core":22}],54:[function(_dereq_,module,exports){
+/**
+ * @module Math
+ * @submodule Random
+ * @for p5
+ * @requires core
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+
+var seeded = false;
+var previous = false;
+var y2 = 0;
+
+// Linear Congruential Generator
+// Variant of a Lehman Generator
+var lcg = (function() {
+ // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes
+ // m is basically chosen to be large (as it is the max period)
+ // and for its relationships to a and c
+ var m = 4294967296,
+ // a - 1 should be divisible by m's prime factors
+ a = 1664525,
+ // c and m should be co-prime
+ c = 1013904223,
+ seed,
+ z;
+ return {
+ setSeed: function(val) {
+ // pick a random seed if val is undefined or null
+ // the >>> 0 casts the seed to an unsigned 32-bit integer
+ z = seed = (val == null ? Math.random() * m : val) >>> 0;
+ },
+ getSeed: function() {
+ return seed;
+ },
+ rand: function() {
+ // define the recurrence relationship
+ z = (a * z + c) % m;
+ // return a float in [0, 1)
+ // if z = m then z / m = 0 therefore (z % m) / m < 1 always
+ return z / m;
+ }
+ };
+})();
+
+/**
+ * Sets the seed value for random().
+ *
+ * By default, random() produces different results each time the program
+ * is run. Set the seed parameter to a constant to return the same
+ * pseudo-random numbers each time the software is run.
+ *
+ * @method randomSeed
+ * @param {Number} seed the seed value
+ * @example
+ *
+ *
+ * randomSeed(99);
+ * for (var i = 0; i < 100; i++) {
+ * var r = random(0, 255);
+ * stroke(r);
+ * line(i, 0, i, 100);
+ * }
+ *
+ *
+ *
+ * @alt
+ * many vertical lines drawn in white, black or grey.
+ *
+ */
+p5.prototype.randomSeed = function(seed) {
+ lcg.setSeed(seed);
+ seeded = true;
+ previous = false;
+};
+
+/**
+ * Return a random floating-point number.
+ *
+ * Takes either 0, 1 or 2 arguments.
+ *
+ * If no argument is given, returns a random number from 0
+ * up to (but not including) 1.
+ *
+ * If one argument is given and it is a number, returns a random number from 0
+ * up to (but not including) the number.
+ *
+ * If one argument is given and it is an array, returns a random element from
+ * that array.
+ *
+ * If two arguments are given, returns a random number from the
+ * first argument up to (but not including) the second argument.
+ *
+ * @method random
+ * @param {Number} [min] the lower bound (inclusive)
+ * @param {Number} [max] the upper bound (exclusive)
+ * @return {Number} the random number
+ * @example
+ *
+ *
+ * for (var i = 0; i < 100; i++) {
+ * var r = random(50);
+ * stroke(r * 5);
+ * line(50, i, 50 + r, i);
+ * }
+ *
+ *
+ *
+ *
+ * for (var i = 0; i < 100; i++) {
+ * var r = random(-50, 50);
+ * line(50, i, 50 + r, i);
+ * }
+ *
+ *
+ *
+ *
+ * // Get a random element from an array using the random(Array) syntax
+ * var words = ['apple', 'bear', 'cat', 'dog'];
+ * var word = random(words); // select random word
+ * text(word, 10, 50); // draw the word
+ *
+ *
+ *
+ * @alt
+ * 100 horizontal lines from center canvas to right. size+fill change each time
+ * 100 horizontal lines from center of canvas. height & side change each render
+ * word displayed at random. Either apple, bear, cat, or dog
+ *
+ */
+/**
+ * @method random
+ * @param {Array} choices the array to choose from
+ * @return {*} the random element from the array
+ * @example
+ */
+p5.prototype.random = function(min, max) {
+ var rand;
+
+ if (seeded) {
+ rand = lcg.rand();
+ } else {
+ rand = Math.random();
+ }
+ if (typeof min === 'undefined') {
+ return rand;
+ } else if (typeof max === 'undefined') {
+ if (min instanceof Array) {
+ return min[Math.floor(rand * min.length)];
+ } else {
+ return rand * min;
+ }
+ } else {
+ if (min > max) {
+ var tmp = min;
+ min = max;
+ max = tmp;
+ }
+
+ return rand * (max - min) + min;
+ }
+};
+
+/**
+ *
+ * Returns a random number fitting a Gaussian, or
+ * normal, distribution. There is theoretically no minimum or maximum
+ * value that randomGaussian() might return. Rather, there is
+ * just a very low probability that values far from the mean will be
+ * returned; and a higher probability that numbers near the mean will
+ * be returned.
+ *
+ * Takes either 0, 1 or 2 arguments.
+ * If no args, returns a mean of 0 and standard deviation of 1.
+ * If one arg, that arg is the mean (standard deviation is 1).
+ * If two args, first is mean, second is standard deviation.
+ *
+ * @method randomGaussian
+ * @param {Number} mean the mean
+ * @param {Number} sd the standard deviation
+ * @return {Number} the random number
+ * @example
+ *
+ *
+ * for (var y = 0; y < 100; y++) {
+ * var x = randomGaussian(50, 15);
+ * line(50, y, x, y);
+ * }
+ *
+ *
+ *
+ *
+ * var distribution = new Array(360);
+ *
+ * function setup() {
+ * createCanvas(100, 100);
+ * for (var i = 0; i < distribution.length; i++) {
+ * distribution[i] = floor(randomGaussian(0, 15));
+ * }
+ * }
+ *
+ * function draw() {
+ * background(204);
+ *
+ * translate(width / 2, width / 2);
+ *
+ * for (var i = 0; i < distribution.length; i++) {
+ * rotate(TWO_PI / distribution.length);
+ * stroke(0);
+ * var dist = abs(distribution[i]);
+ * line(0, 0, dist, 0);
+ * }
+ * }
+ *
+ *
+ * @alt
+ * 100 horizontal lines from center of canvas. height & side change each render
+ * black lines radiate from center of canvas. size determined each render
+ */
+p5.prototype.randomGaussian = function(mean, sd) {
+ var y1, x1, x2, w;
+ if (previous) {
+ y1 = y2;
+ previous = false;
+ } else {
+ do {
+ x1 = this.random(2) - 1;
+ x2 = this.random(2) - 1;
+ w = x1 * x1 + x2 * x2;
+ } while (w >= 1);
+ w = Math.sqrt(-2 * Math.log(w) / w);
+ y1 = x1 * w;
+ y2 = x2 * w;
+ previous = true;
+ }
+
+ var m = mean || 0;
+ var s = sd || 1;
+ return y1 * s + m;
+};
+
+module.exports = p5;
+
+},{"../core/core":22}],55:[function(_dereq_,module,exports){
+/**
+ * @module Math
+ * @submodule Trigonometry
+ * @for p5
+ * @requires core
+ * @requires constants
+ */
+
+'use strict';
+
+var p5 = _dereq_('../core/core');
+var constants = _dereq_('../core/constants');
+
+/*
+ * all DEGREES/RADIANS conversion should be done in the p5 instance
+ * if possible, using the p5._toRadians(), p5._fromRadians() methods.
+ */
+p5.prototype._angleMode = constants.RADIANS;
+
+/**
+ * The inverse of cos(), returns the arc cosine of a value. This function
+ * expects the values in the range of -1 to 1 and values are returned in
+ * the range 0 to PI (3.1415927).
+ *
+ * @method acos
+ * @param {Number} value the value whose arc cosine is to be returned
+ * @return {Number} the arc cosine of the given value
+ *
+ * @example
+ *
+ *
+ * var a = PI;
+ * var c = cos(a);
+ * var ac = acos(c);
+ * // Prints: "3.1415927 : -1.0 : 3.1415927"
+ * print(a + ' : ' + c + ' : ' + ac);
+ *
+ *
+ *
+ *
+ *
+ * var a = PI + PI / 4.0;
+ * var c = cos(a);
+ * var ac = acos(c);
+ * // Prints: "3.926991 : -0.70710665 : 2.3561943"
+ * print(a + ' : ' + c + ' : ' + ac);
+ *
+ *
+ */
+p5.prototype.acos = function(ratio) {
+ return this._fromRadians(Math.acos(ratio));
+};
+
+/**
+ * The inverse of sin(), returns the arc sine of a value. This function
+ * expects the values in the range of -1 to 1 and values are returned
+ * in the range -PI/2 to PI/2.
+ *
+ * @method asin
+ * @param {Number} value the value whose arc sine is to be returned
+ * @return {Number} the arc sine of the given value
+ *
+ * @example
+ *
+ *
+ * var a = PI + PI / 3;
+ * var s = sin(a);
+ * var as = asin(s);
+ * // Prints: "1.0471976 : 0.86602545 : 1.0471976"
+ * print(a + ' : ' + s + ' : ' + as);
+ *
+ *
+ *
+ *
+ *
+ * var a = PI + PI / 3.0;
+ * var s = sin(a);
+ * var as = asin(s);
+ * // Prints: "4.1887903 : -0.86602545 : -1.0471976"
+ * print(a + ' : ' + s + ' : ' + as);
+ *
+ *
+ *
+ */
+p5.prototype.asin = function(ratio) {
+ return this._fromRadians(Math.asin(ratio));
+};
+
+/**
+ * The inverse of tan(), returns the arc tangent of a value. This function
+ * expects the values in the range of -Infinity to Infinity (exclusive) and
+ * values are returned in the range -PI/2 to PI/2.
+ *
+ * @method atan
+ * @param {Number} value the value whose arc tangent is to be returned
+ * @return {Number} the arc tangent of the given value
+ *
+ * @example
+ *
+ *
+ * var a = PI + PI / 3;
+ * var t = tan(a);
+ * var at = atan(t);
+ * // Prints: "1.0471976 : 1.7320509 : 1.0471976"
+ * print(a + ' : ' + t + ' : ' + at);
+ *
+ *
+ *
+ *
+ *
+ * var a = PI + PI / 3.0;
+ * var t = tan(a);
+ * var at = atan(t);
+ * // Prints: "4.1887903 : 1.7320513 : 1.0471977"
+ * print(a + ' : ' + t + ' : ' + at);
+ *
+ *
+ *
+ */
+p5.prototype.atan = function(ratio) {
+ return this._fromRadians(Math.atan(ratio));
+};
+
+/**
+ * Calculates the angle (in radians) from a specified point to the coordinate
+ * origin as measured from the positive x-axis. Values are returned as a
+ * float in the range from PI to -PI. The atan2() function is most often used
+ * for orienting geometry to the position of the cursor.
+ *
+ * Note: The y-coordinate of the point is the first parameter, and the
+ * x-coordinate is the second parameter, due the the structure of calculating
+ * the tangent.
+ *
+ * @method atan2
+ * @param {Number} y y-coordinate of the point
+ * @param {Number} x x-coordinate of the point
+ * @return {Number} the arc tangent of the given point
+ *
+ * @example
+ *
+ *
+ * function draw() {
+ * background(204);
+ * translate(width / 2, height / 2);
+ * var a = atan2(mouseY - height / 2, mouseX - width / 2);
+ * rotate(a);
+ * rect(-30, -5, 60, 10);
+ * }
+ *
+ *
+ *
+ * @alt
+ * 60 by 10 rect at center of canvas rotates with mouse movements
+ *
+ */
+p5.prototype.atan2 = function(y, x) {
+ return this._fromRadians(Math.atan2(y, x));
+};
+
+/**
+ * Calculates the cosine of an angle. This function takes into account the
+ * current angleMode. Values are returned in the range -1 to 1.
+ *
+ * @method cos
+ * @param {Number} angle the angle
+ * @return {Number} the cosine of the angle
+ *
+ * @example
+ *
+ *
+ * var a = 0.0;
+ * var inc = TWO_PI / 25.0;
+ * for (var i = 0; i < 25; i++) {
+ * line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);
+ * a = a + inc;
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical black lines form wave patterns, extend-down on left and right side
+ *
+ */
+p5.prototype.cos = function(angle) {
+ return Math.cos(this._toRadians(angle));
+};
+
+/**
+ * Calculates the sine of an angle. This function takes into account the
+ * current angleMode. Values are returned in the range -1 to 1.
+ *
+ * @method sin
+ * @param {Number} angle the angle
+ * @return {Number} the sine of the angle
+ *
+ * @example
+ *
+ *
+ * var a = 0.0;
+ * var inc = TWO_PI / 25.0;
+ * for (var i = 0; i < 25; i++) {
+ * line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);
+ * a = a + inc;
+ * }
+ *
+ *
+ *
+ * @alt
+ * vertical black lines extend down and up from center to form wave pattern
+ *
+ */
+p5.prototype.sin = function(angle) {
+ return Math.sin(this._toRadians(angle));
+};
+
+/**
+ * Calculates the tangent of an angle. This function takes into account
+ * the current angleMode. Values are returned in the range -1 to 1.
+ *
+ * @method tan
+ * @param {Number} angle the angle
+ * @return {Number} the tangent of the angle
+ *
+ * @example
+ *