From 70e33fe135e393d32aab6fe9a69aadb99d67e862 Mon Sep 17 00:00:00 2001 From: Marty Oehme Date: Sat, 7 Jul 2018 19:08:26 +0200 Subject: [PATCH] Fix Rendering when no Changes occured Rendering checks a dirty flag which gets set whenever a cell updates by changing their state. --- lib/src/Cell.dart | 5 +++++ lib/src/Grid.dart | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/lib/src/Cell.dart b/lib/src/Cell.dart index 3111708..5301fb6 100644 --- a/lib/src/Cell.dart +++ b/lib/src/Cell.dart @@ -6,11 +6,16 @@ class Cell { List surviveRules = new List(); List birthRules = new List(); + /// For determining if render updates are necessary in [Grid].render() function + bool dirty = false; + Cell([bool state = false]) : this.state = state; void advanceState() { this.state = this.nextState; this.nextState = false; + + this.dirty = true; } void update(int neighbors) { diff --git a/lib/src/Grid.dart b/lib/src/Grid.dart index 154283e..b0d7e9f 100644 --- a/lib/src/Grid.dart +++ b/lib/src/Grid.dart @@ -8,6 +8,8 @@ class Grid { final int h; final List> map; + bool _dirty = true; + Grid(int w, int h) : this.w = w, this.h = h, @@ -82,6 +84,7 @@ class Grid { for (int x = 0; x < w; x++) { // DEFAULTS TO CONWAY GAME OF LIFE RANGE OF ONE map[y][x].update(getSurroundingNeighbors(x, y, 1)); + if (!_dirty && map[y][x].dirty) _dirty = true; } } for (int y = 0; y < h; y++) { @@ -110,6 +113,9 @@ class Grid { } void render(html.CanvasElement canvas, [num interp]) { + // only renders if any cells changed between renders + if (!_dirty) return; + html.CanvasRenderingContext2D ctx = canvas.getContext('2d'); int brickW = (canvas.width ~/ map[0].length); int brickH = (canvas.height ~/ map.length); @@ -124,5 +130,7 @@ class Grid { ctx.fillRect(x * brickW, y * brickH, brickW, brickH); } } + + _dirty = false; } }