summaryrefslogtreecommitdiff
path: root/js/shader.js
blob: a8559ba858ad4b9e99c1dcb2205fea82f43c4563 (plain)
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
function shader (x,y,t,d) {}

var shader_build = function(){
  var fn_str = document.getElementById('shader').value
  if (!fn_str.length) fn_str = ""
  try {
    var fn = new Function('x','y','t','d', fn_str)
    shader = fn
    shade = shade_error_handling
  } catch (e) {
    try {
      acorn.parse(fn_str)
    } catch(e){ //e.loc = {column: 0, line: 1} line is 1-based
      error_highlight.on(e.loc.line-1)
    }
    throw Error ("Shader compilation error")
  }
}

var r,g,b,a;
var w, h, actual_w, actual_h;
function shade_no_error_handling(frame, t){
  if (! t || isNaN(t)) throw Error ("No time specified")
  if (! frame) throw Error ("No frame specified")

  var imgData = frame.ctx.getImageData(0,0,w,h)
  var data = imgData.data
  var clone = frame.cloneData.data  
  var realw = w, realh = h, v, index

  for (var x = 0; x < w; x++) {
    for (var y = 0; y < h; y++) {
      q = 4*(y*w+x)
      r = data[q], g = data[q+1], b = data[q+2], a = data[q+3]
      result = shader(x,y,t,clone)
      data[q] = r
      data[q+1] = g
      data[q+2] = b
      data[q+3] = a
      w = realw, h = realh
    }
  }
  cc.putImageData(imgData,0,0)
}

var chrome_stack_regexp = /<anonymous>:([0-9]+)/;
var firefox_stack_regexp = /:([0-9]+)$/;

function shade_error_handling(frame, t){
  if (! t || isNaN(t)) throw Error ("No time specified")
  if (! frame || ! frame.ctx || ! frame.cloneData) throw Error ("No frame specified")

  var imgData = frame.ctx.getImageData(0,0,w,h)
  var data = imgData.data
  var clone = frame.cloneData.data

  try {
    var realw = w, realh = h, v, index

    for (var x = 0; x < w; x++) {
      for (var y = 0; y < h; y++) {
        q = 4*(y*w+x)
        r = data[q], g = data[q+1], b = data[q+2], a = data[q+3]
        result = shader(x,y,t,clone)
        data[q] = r
        data[q+1] = g
        data[q+2] = b
        data[q+3] = a
        w = realw, h = realh
      }
    }
  }
  catch(e){
    var lines = (e.stack + "").split('\n')
    if (lines[0].substr(0,10) === "anonymous@") { // firefox
      var matches = lines[0].match(firefox_stack_regexp)
      if (matches.length > 1)
        error_highlight.on(parseInt(matches[1]) - 5)

    } else if (lines.length > 1) { // attempt chrome match
      var matches = lines[1].match(chrome_stack_regexp)
      if (matches && matches.length > 1)
        error_highlight.on(parseInt(matches[1]) - 3)
    }
    
    // console.log(e.stack)
    throw Error ("Shader execution error")
  }
  cc.putImageData(imgData,0,0)
  shade = shade_no_error_handling
  error_highlight.off()
}

shade = shade_error_handling