<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <title>Paint-In-Time 2</title>
  <style>
    .gradient {
      position: absolute;
      width: 800px;
      height: 600px;
      opacity: 0.4;
    }
  </style>
</head>
<body>
  <div id="grid">
  </div>
</body>
<script>

// Only allow painting a tiny slice of the frame - here, 15ms.
var kFrameBudgetMs = 14;
var kDivCount = 10;
var kMaxTime = 20 * 1000;

var gCrazyCounter = 0;
var gIterations = 0;
var gStart;
var gDivs = [];

function GetColor() {
  var color = GetColor.kColors[GetColor.Index];
  GetColor.Index++;
  GetColor.Index = (GetColor.Index % GetColor.kColors.length);
  return color;
}
GetColor.Index = 0;
GetColor.kColors = ["red", "white", "green", "yellow", "orange", "brown"];

function RadialGradient(offset) {
  this.colors = [GetColor(), GetColor()];
  this.percents = [0 + offset, 20 + offset];
  this.toStyle = function() {
    return "radial-gradient(" +
      this.colors[0] + " " + this.percents[0] + "%, " +
      this.colors[1] + " " + this.percents[1] + "%)";
  };
  this.advance = function() {
    this.percents[0] += 1;
    this.percents[0] %= 80;
    this.percents[1] = this.percents[0] + 20;
  };
}

function runFrame() {
  var start = performance.now();

  // Spin loop.
  while (performance.now() - start < kFrameBudgetMs)
    gCrazyCounter++;

  for (var i = 0; i < gDivs.length; i++) {
    var info = gDivs[i];
    info.gradient.advance();
    info.element.style.background = info.gradient.toStyle();
  }

  gIterations++;

  if (performance.now() - gStart >= kMaxTime) {
    if (window.tpRecordTime) {
      window.tpRecordTime(gIterations);
    }
    return;
  }

  TalosContentProfiler.mark("rasterflood_gradient", true, start);

  window.requestAnimationFrame(runFrame);
}

function setup() {
  var root = document.getElementById("grid");
  for (var i = 0; i < kDivCount; i++) {
    var gradient = new RadialGradient(i * 10 / 2);

    var div = document.createElement("div");
    var info = {};
    info.element = div;
    info.gradient = gradient;

    div.classList.add("gradient");
    div.style.left = "10px";
    div.style.top = "10px";
    div.style.background = gradient.toStyle();
    root.appendChild(div);

    gDivs.push(info);
  }
}

function startTest() {
  setup();
  gStart = performance.now();
  window.requestAnimationFrame(runFrame);
}

addEventListener("load", function() {
  try {
    TalosContentProfiler.resume("rasterflood_gradient.html loaded", true).then(() => {
      startTest();
    });
  } catch (e) {
    TalosContentProfiler.resume("rasterflood_gradient.html loaded", true);
    startTest();
  }
});
</script>
<script type="text/javascript" src="resource://talos-powers/TalosContentProfiler.js"></script>
</html>
