-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrabs.js
108 lines (94 loc) · 2.42 KB
/
crabs.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
'use strict'
var log = function(level, msg) {
var levelNames = ['DEBUG', 'INFO', 'WARN', 'ERR']
if (levelNames[level]) {
console.log(levelNames[level] + ': ' + msg)
} else {
console.log('UNKNOWN: ' + msg)
}
}
log.DEBUG = 0
log.INFO = 1
log.WARN = 2
log.ERR = 3
var time = function(t, f) {
var start = performance.now()
f()
var end = performance.now()
t = end - start
}
function Crabs(canvas, ui) {
this.canvas = canvas
this.uiCanvas = ui
this.ids = []
this.lastId = -1
this.physics = new Physics()
this.renderer = new Renderer()
this.ui = new UI()
this.components = [this.physics, this.ui, this.renderer]
this.hooks = [this.ui, new TestUI()]
this.paused = false
this.width = canvas.width
this.height = canvas.height
this.init = function() {
var me = this
var events = ['mousemove', 'mousedown', 'mouseup', 'click', 'keypress']
events.forEach(function(name) {
var listeners = me.hooks.filter(function(l) {
return typeof(l[name]) != 'undefined'
})
log(log.INFO, 'adding hooks for ' + name + ': ' + listeners)
ui.addEventListener(name, function(e) {
listeners.forEach(function(l) {
l[name](me, e)
})
})
})
this.resize()
}
this.go = function() {
if (!this.paused) {
this.components.forEach(function(c) {
c.run(crabs)
})
var me = this
window.requestAnimationFrame(function() {
me.go()
})
}
// log(log.INFO, 'frame')
}
this.resize = function() {
var w = window.innerWidth, h = window.innerHeight
log(log.DEBUG, 'resize ' + w + ', ' + h)
this.width = w
this.height = h
canvas.width = w
canvas.height = h
ui.width = w
ui.height = h
this.components.forEach(function(c) {
c.resize(this)
})
this.renderer.run(this)
}
this.addMass = function(pos, vel) {
var newIdNum = this.lastId + 1
var newId = newIdNum.toString()
this.ids.push(newId)
var ret = this.physics.addMass(newId, pos, vel, this.physics.DEFAULT_MASS)
this.lastId = newIdNum
return ret
}
this.addSpring = function(m0, m1, r, k) {
var newIdNum = this.lastId + 1
var newId = newIdNum.toString()
this.ids.push(newId)
var ret = this.physics.addSpring(newId, m0, m1, r, k)
this.lastId = newIdNum
return ret
}
this.addMuscle = function(s, r, a, p) {
return this.physics.addMuscle(s, r, a, p)
}
}