package main // Radar for the weather flyout: a small map centered on the ZIP code with the // last hour or so of rain radar over it, played as a loop. // // Radar pictures come from RainViewer (rainviewer.com, free, no account): a list // of the latest frames, then one picture tile per frame. The map under them is // Esri's dark gray map (gray base plus a layer of place names). Both are lists // of square tiles on the same world grid, so a window around the ZIP code is // cut out of the tiles and each radar frame is laid over the map. // // Nothing here runs until the panel is opened, and it all happens on a // background goroutine; the finished frames are plain pixel arrays that the // panel draws straight to the screen. import ( "bytes" "fmt" "image" "image/color" "image/draw" _ "image/jpeg" _ "image/png" "math" "sync" "time" ) const ( radarW = 520 // pixels in a finished frame; 520 by 250 matches the panel's 312 by 150 picture radarH = 250 radarFrames = 8 // the newest eight frames, 10 minutes apart radarFresh = 5 * time.Minute // One world pixel grid serves everything: 65536 pixels around the globe. That is // RainViewer's 512 pixel tiles at zoom 7 and Esri's 256 pixel tiles at zoom 8. radarWorld = 65536.0 radarTileRV = 512 radarZoomRV = 7 radarTileMap = 256 radarZoomMap = 8 ) type radarState struct { key string // the place these frames are for frames [][]byte times []time.Time loading bool err string fetched time.Time } var ( rdMu sync.Mutex rd radarState rdGen int rdIdx int // which frame is on screen; touched only by the panel's own thread ) func radarSnapshot() radarState { rdMu.Lock() defer rdMu.Unlock() return rd } // radarEnsure starts a radar download if there is none for this place yet, or // the one we have is old. Called when the panel opens and when a forecast lands. func radarEnsure(force bool) { s := wxSnapshot() if !s.ok { return } key := fmt.Sprintf("%.3f,%.3f", s.lat, s.lon) rdMu.Lock() same := rd.key == key switch { case same && rd.loading && !force: rdMu.Unlock() return case same && len(rd.frames) > 0 && time.Since(rd.fetched) < radarFresh && !force: rdMu.Unlock() return case same && rd.err != "" && len(rd.frames) == 0 && time.Since(rd.fetched) < time.Minute && !force: rdMu.Unlock() // it just failed; don't hammer the service return } if !same { rd = radarState{key: key} } rd.loading = true rd.err = "" rdGen++ gen := rdGen rdMu.Unlock() go radarFetch(key, s.lat, s.lon, gen) } func radarFinish(gen int, key string, frames [][]byte, times []time.Time, errText string) { rdMu.Lock() if gen != rdGen || rd.key != key { rdMu.Unlock() return } rd.loading = false rd.fetched = time.Now() if frames != nil { rd.frames, rd.times, rd.err = frames, times, "" } else { rd.err = errText } rdMu.Unlock() weatherNotify() } // worldPixel is where a place falls on the 65536 pixel world grid (Web Mercator). func worldPixel(lat, lon float64) (x, y float64) { x = (lon + 180) / 360 * radarWorld r := lat * math.Pi / 180 y = (1 - math.Log(math.Tan(r)+1/math.Cos(r))/math.Pi) / 2 * radarWorld return } type tileJob struct { url string img image.Image err error } // fetchTiles downloads a set of tile pictures, a few at a time. func fetchTiles(jobs []*tileJob) { var wg sync.WaitGroup sem := make(chan struct{}, 6) for _, j := range jobs { wg.Add(1) sem <- struct{}{} go func(j *tileJob) { defer wg.Done() defer func() { <-sem }() defer func() { if r := recover(); r != nil { j.err = fmt.Errorf("tile failed") } }() b, err := wxGetBytes(j.url) if err != nil { j.err = err return } j.img, _, j.err = image.Decode(bytes.NewReader(b)) }(j) } wg.Wait() } func radarFetch(key string, lat, lon float64, gen int) { defer func() { if r := recover(); r != nil { radarFinish(gen, key, nil, nil, "The radar lookup failed.") } }() // 1. The list of radar frames. var idx struct { Host string `json:"host"` Radar struct { Past []struct { Time int64 `json:"time"` Path string `json:"path"` } `json:"past"` } `json:"radar"` } if _, err := wxGetJSON("https://api.rainviewer.com/public/weather-maps.json", &idx); err != nil || idx.Host == "" || len(idx.Radar.Past) == 0 { radarFinish(gen, key, nil, nil, "Radar isn't available right now.") return } past := idx.Radar.Past if len(past) > radarFrames { past = past[len(past)-radarFrames:] } // 2. Which tiles cover a window centered on the place. cx, cy := worldPixel(lat, lon) x0 := int(math.Floor(cx - radarW/2)) y0 := int(math.Floor(cy - radarH/2)) span := func(a, b int, size int) (lo, hi int) { lo = int(math.Floor(float64(a) / float64(size))) hi = int(math.Floor(float64(b) / float64(size))) return } // 3. The map: gray base plus place names, from tiles 256 pixels wide at zoom 8. base := image.NewRGBA(image.Rect(0, 0, radarW, radarH)) draw.Draw(base, base.Bounds(), image.NewUniform(color.RGBA{34, 34, 38, 255}), image.Point{}, draw.Src) mx0, mx1 := span(x0, x0+radarW-1, radarTileMap) my0, my1 := span(y0, y0+radarH-1, radarTileMap) type placed struct { job *tileJob ox, oy int } var mapTiles []placed var jobs []*tileJob for _, layer := range []string{"World_Dark_Gray_Base", "World_Dark_Gray_Reference"} { for ty := my0; ty <= my1; ty++ { for tx := mx0; tx <= mx1; tx++ { j := &tileJob{url: fmt.Sprintf("https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/%s/MapServer/tile/%d/%d/%d", layer, radarZoomMap, ty, tx)} mapTiles = append(mapTiles, placed{j, tx*radarTileMap - x0, ty*radarTileMap - y0}) jobs = append(jobs, j) } } } // 4. Every radar frame's tiles, 512 pixels wide at zoom 7. rx0, rx1 := span(x0, x0+radarW-1, radarTileRV) ry0, ry1 := span(y0, y0+radarH-1, radarTileRV) type frameTiles struct { t time.Time tiles []placed } frames := make([]frameTiles, len(past)) for i, p := range past { frames[i].t = time.Unix(p.Time, 0) for ty := ry0; ty <= ry1; ty++ { for tx := rx0; tx <= rx1; tx++ { j := &tileJob{url: fmt.Sprintf("%s%s/%d/%d/%d/%d/2/1_1.png", idx.Host, p.Path, radarTileRV, radarZoomRV, tx, ty)} frames[i].tiles = append(frames[i].tiles, placed{j, tx*radarTileRV - x0, ty*radarTileRV - y0}) jobs = append(jobs, j) } } } fetchTiles(jobs) // The map must have come through; a missing radar frame is just skipped. for _, m := range mapTiles { if m.job.err != nil || m.job.img == nil { radarFinish(gen, key, nil, nil, "The map for radar didn't load.") return } b := m.job.img.Bounds() draw.Draw(base, image.Rect(m.ox, m.oy, m.ox+b.Dx(), m.oy+b.Dy()), m.job.img, b.Min, draw.Over) } alpha := &image.Uniform{color.Alpha{A: 215}} var out [][]byte var times []time.Time for _, f := range frames { layer := image.NewRGBA(base.Bounds()) good := true for _, t := range f.tiles { if t.job.err != nil || t.job.img == nil { good = false break } b := t.job.img.Bounds() draw.Draw(layer, image.Rect(t.ox, t.oy, t.ox+b.Dx(), t.oy+b.Dy()), t.job.img, b.Min, draw.Over) } if !good { continue } comp := image.NewRGBA(base.Bounds()) copy(comp.Pix, base.Pix) draw.DrawMask(comp, comp.Bounds(), layer, image.Point{}, alpha, image.Point{}, draw.Over) // Windows wants blue, green, red order. bgra := make([]byte, len(comp.Pix)) for i := 0; i+3 < len(comp.Pix); i += 4 { bgra[i], bgra[i+1], bgra[i+2], bgra[i+3] = comp.Pix[i+2], comp.Pix[i+1], comp.Pix[i], 255 } out = append(out, bgra) times = append(times, f.t) } if len(out) == 0 { radarFinish(gen, key, nil, nil, "Radar isn't available right now.") return } radarFinish(gen, key, out, times, "") }