             .attr(@bar.rangeDir, (d,i) => (1-d.count/cmax)*width)
             .attr(@bar.rangeAttr, (d, i) => d.count/cmax*width)
 
-        
 class Canvas
 
     @width = 360

        if @collision() and @state is 0
            @setState(1)
            count[@bin] += 1
            console.log "count", count
        
        @d += @vel.mag()
        @pos.add @vel


    setVelocities: ->

        @velocity[0] = new Vector @vel0.x, @vel0.y
        @velocity[1] = (new Vector).polar(10, pi/2)        

        g = (u) -> ((u<0)*1.5 + (u>0)/2)*u + 0.375 
        h = (u) -> Math.floor(20*(u+0.5))

        @limit =  @yScale(g(@xScale.invert(@pos.x)))
        #console.log "???", h(@xScale.invert(@pos.x))
        @bin = Math.floor((@yScale.invert(@limit)+0.875)/2*20)
 
    collision: -> @pos.y > @limit



#==== Emitters ====

class Emitter

    maxPhotons: 4000
    rate: 0
    
    cy: Canvas.height/2  # Canvas center
    cx: Canvas.width/2  # Canvas center
    
    constructor: ->
        @photons = []

    emit: () ->
        unless @photons.length > @maxPhotons
            # emitPhoton defined in subclass
            # console.log "photons", @photons
            @photons.push(@emitPhoton()) for [0...@rate]
        @photons = @photons.filter (photon) => photon.visible()
        for photon in @photons
            photon.move()
            photon.draw()

class Sun extends Emitter

    x: 1
    l: 180
    
    constructor: ->
        #@velocity = new Vector 2, 0
        @velocity = new Vector  0, 2
        super()

    emitPhoton: ->
        #pos = new Vector @x, @cy + @l*(Math.random()-0.5)
        pos = new Vector @cx + @l*(Math.random()-0.5), 1
        new Sunlight(pos, @velocity)


#==== Simulation ====
 
class Simulation

    constructor: ->
        @sun = new Sun
        @sun.rate = 10
        @h = new Histo
        
    start: () ->

        @y = m*Math.sin(a)
        this


class Sunlight
    
    colors: ["#ff0", "#ff0"]
    sizes: [2, 5]
    w: Canvas.width
    h: Canvas.height
    O: -> new Vector 0, 0

    constructor: (@pos=@O(), g, q) ->

        # sim units -> screen units
        @xScale = d3.scale.linear()
            .domain([-1, 1])
            .range([0, @w])
        @yScale = d3.scale.linear()
            .domain([-1, 1])
            .range([@h, 0])

        # dynamics
        @d = 0
        @velocity = []
        @velocity[0] = new Vector 0, 2
        @velocity[1] = @O()
        @setCollision(g, q)
        @setState 0
        
    setState: (@state) ->
        return if @state<0
        @vel = @velocity[@state]
