File: kernel.js

package info (click to toggle)
axiom 20170501-4
  • links: PTS
  • area: main
  • in suites: buster
  • size: 1,048,504 kB
  • sloc: lisp: 3,600; makefile: 505; cpp: 223; ansic: 138; sh: 96
file content (266 lines) | stat: -rw-r--r-- 9,039 bytes parent folder | download | duplicates (15)
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
//
//  kernel.js - version 0.91
//  a graph vizualization toolkit
//
//  Copyright (c) 2011 Samizdat Drafting Co.
//  Physics code derived from springy.js, copyright (c) 2010 Dennis Hotson
// 
//  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.
//

//
// kernel.js
//
// run-loop manager for physics and tween updates
//
    
  var Kernel = function(pSystem){
    // in chrome, web workers aren't available to pages with file:// urls
    var chrome_local_file = window.location.protocol == "file:" &&
                            navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    var USE_WORKER = (window.Worker !== undefined && !chrome_local_file)    
    
    var _physics = null
    var _tween = null
    var _fpsWindow = [] // for keeping track of the actual frame rate
    _fpsWindow.last = new Date()
    var _screenInterval = null
    var _attached = null

    var _tickInterval = null
    var _lastTick = null
    var _paused = false
    
    var that = {
      system:pSystem,
      tween:null,
      nodes:{},

      init:function(){ 
        if (typeof(Tween)!='undefined') _tween = Tween()
        else if (typeof(arbor.Tween)!='undefined') _tween = arbor.Tween()
        else _tween = {busy:function(){return false},
                       tick:function(){return true},
                       to:function(){ trace('Please include arbor-tween.js to enable tweens'); _tween.to=function(){}; return} }
        that.tween = _tween
        var params = pSystem.parameters()
                
        if(USE_WORKER){
          trace('arbor.js/web-workers',params)
          _screenInterval = setInterval(that.screenUpdate, params.timeout)

          _physics = new Worker(arbor_path()+'physics/worker.js')
          _physics.onmessage = that.workerMsg
          _physics.onerror = function(e){ trace('physics:',e) }
          _physics.postMessage({type:"physics", 
                                physics:objmerge(params, 
                                                {timeout:Math.ceil(params.timeout)}) })
        }else{
          trace('arbor.js/single-threaded',params)
          _physics = Physics(params.dt, params.stiffness, params.repulsion, params.friction, that.system._updateGeometry, params.integrator)
          that.start()
        }

        return that
      },

      //
      // updates from the ParticleSystem
      graphChanged:function(changes){
        // a node or edge was added or deleted
        if (USE_WORKER) _physics.postMessage({type:"changes","changes":changes})
        else _physics._update(changes)
        that.start() // <- is this just to kick things off in the non-worker mode? (yes)
      },

      particleModified:function(id, mods){
        // a particle's position or mass is changed
        // trace('mod',objkeys(mods))
        if (USE_WORKER) _physics.postMessage({type:"modify", id:id, mods:mods})
        else _physics.modifyNode(id, mods)
        that.start() // <- is this just to kick things off in the non-worker mode? (yes)
      },

      physicsModified:function(param){

        // intercept changes to the framerate in case we're using a worker and
        // managing our own draw timer
        if (!isNaN(param.timeout)){
          if (USE_WORKER){
            clearInterval(_screenInterval)
            _screenInterval = setInterval(that.screenUpdate, param.timeout)
          }else{
            // clear the old interval then let the call to .start set the new one
            clearInterval(_tickInterval)
            _tickInterval=null
          }
        }

        // a change to the physics parameters 
        if (USE_WORKER) _physics.postMessage({type:'sys',param:param})
        else _physics.modifyPhysics(param)
        that.start() // <- is this just to kick things off in the non-worker mode? (yes)
      },
      
      workerMsg:function(e){
        var type = e.data.type
        if (type=='geometry'){
          that.workerUpdate(e.data)
        }else{
          trace('physics:',e.data)
        }
      },
      _lastPositions:null,
      workerUpdate:function(data){
        that._lastPositions = data
        that._lastBounds = data.bounds
      },
      

      // 
      // the main render loop when running in web worker mode
      _lastFrametime:new Date().valueOf(),
      _lastBounds:null,
      _currentRenderer:null,
      screenUpdate:function(){        
        var now = new Date().valueOf()
        
        var shouldRedraw = false
        if (that._lastPositions!==null){
          that.system._updateGeometry(that._lastPositions)
          that._lastPositions = null
          shouldRedraw = true
        }
        
        if (_tween && _tween.busy()) shouldRedraw = true

        if (that.system._updateBounds(that._lastBounds)) shouldRedraw=true
        

        if (shouldRedraw){
          var render = that.system.renderer
          if (render!==undefined){
            if (render !== _attached){
               render.init(that.system)
               _attached = render
            }          
            
            if (_tween) _tween.tick()
            render.redraw()

            var prevFrame = _fpsWindow.last
            _fpsWindow.last = new Date()
            _fpsWindow.push(_fpsWindow.last-prevFrame)
            if (_fpsWindow.length>50) _fpsWindow.shift()
          }
        }
      },

      // 
      // the main render loop when running in non-worker mode
      physicsUpdate:function(){
        if (_tween) _tween.tick()
        _physics.tick()

        var stillActive = that.system._updateBounds()
        if (_tween && _tween.busy()) stillActive = true

        var render = that.system.renderer
        var now = new Date()        
        var render = that.system.renderer
        if (render!==undefined){
          if (render !== _attached){
            render.init(that.system)
            _attached = render
          }          
          render.redraw({timestamp:now})
        }

        var prevFrame = _fpsWindow.last
        _fpsWindow.last = now
        _fpsWindow.push(_fpsWindow.last-prevFrame)
        if (_fpsWindow.length>50) _fpsWindow.shift()

        // but stop the simulation when energy of the system goes below a threshold
        var sysEnergy = _physics.systemEnergy()
        if ((sysEnergy.mean + sysEnergy.max)/2 < 0.05){
          if (_lastTick===null) _lastTick=new Date().valueOf()
          if (new Date().valueOf()-_lastTick>1000){
            // trace('stopping')
            clearInterval(_tickInterval)
            _tickInterval = null
          }else{
            // trace('pausing')
          }
        }else{
          // trace('continuing')
          _lastTick = null
        }
      },


      fps:function(newTargetFPS){
        if (newTargetFPS!==undefined){
          var timeout = 1000/Math.max(1,targetFps)
          that.physicsModified({timeout:timeout})
        }
        
        var totInterv = 0
        for (var i=0, j=_fpsWindow.length; i<j; i++) totInterv+=_fpsWindow[i]
        var meanIntev = totInterv/Math.max(1,_fpsWindow.length)
        if (!isNaN(meanIntev)) return Math.round(1000/meanIntev)
        else return 0
      },

      // 
      // start/stop simulation
      // 
      start:function(unpause){
      	if (_tickInterval !== null) return; // already running
        if (_paused && !unpause) return; // we've been .stopped before, wait for unpause
        _paused = false
        
        if (USE_WORKER){
           _physics.postMessage({type:"start"})
        }else{
          _lastTick = null
          _tickInterval = setInterval(that.physicsUpdate, 
                                      that.system.parameters().timeout)
        }
      },
      stop:function(){
        _paused = true
        if (USE_WORKER){
           _physics.postMessage({type:"stop"})
        }else{
          if (_tickInterval!==null){
            clearInterval(_tickInterval)
            _tickInterval = null
          }
        }
      
      }
    }
    
    return that.init()    
  }