Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap" rel="stylesheet">

<h1>Corona Simulator</h1>
<main>
  <section class="legend">
    <div class="legend-color healthy"></div>
    <div id="legend-healthy"> Healthy</div>
    <div class="legend-color infected"></div>
    <div id="legend-infected">Infected</div>
    <div class="legend-color immune"></div>
    <div id="legend-immune">Immune</div>
    <div class="legend-color dead"></div>
    <div id="legend-dead">Dead</div>
  </section>
  <section class="buttons">
    <button type="button" class="button" onclick="reset()">Reset</button>
    <label class="switch">
      <input type="checkbox" name="use-js" id="use-js" onchange="reloadLang()">
      <span class="slider button">
        <div id="active-lang">Rust</div>
      </span>
    </label>
    <button type="button" class="next button" onclick="advance()">Next Day</button>
    <button id="start-stop-button" type="button" class="start button" onclick="startStop()">Start Simulation</button>
  </section>
  <section>
    <form id="settings" class="config-form">
      <label for="width">Width:</label>
      <input type="number" name="width" value="20" min="0" title="Number of cells in row" onchange="reloadSettings()">
      <label for="height">Height:</label>
      <input type="number" name="height" value="5" min="0" title="Number of cells in column" onchange="reloadSettings()">
      <label for="radius">Radius:</label>
      <input type="number" name="radius" value="2" min="0" title="How many cells the virus can spread in a single day" onchange="reloadSettings()">
      <label for="infection_rate">Infection Rate:</label>
      <input type="number" name="infection_rate" value="0.02" step="0.0001" min="0.0" max="1.0" title="Chance that a person is infected by a single infected patient in the infection radius." onchange="reloadSettings()">
      <label for="death_rate">Death Rate:</label>
      <input type="number" name="death_rate" value="0.03" step="0.01" min="0.0" max="1.0" title="Chance that an infected person dies in a day." onchange="reloadSettings()">
      <label for="recovery">Days until recovered:</label>
      <input type="number" name="recovery" value="10" min="1" max="20" title="Chance that an infected person dies in a day." onchange="reloadSettings()">
      <label for="delay">Simulation delay:</label>
      <input type="number" name="delay" value="300" min="1" title="Delay between simulation steps in ms.">
    </form>
  </section>
  <!-- Dynamic JS will be inserted here -->
</main>
<footer>
  2020 - WASM Demo App by Jakob Meier - <a target="_blank" href="https://github.com/jakmeier/covid-sim">Source Code</a>
</footer>
              
            
!

CSS

              
                body {
  text-align: center;
  background-color: #e1aa7d;
  font-family: "Josefin Sans", Arial, Helvetica, sans-serif;
}

main {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-areas: "legend buttons form" "humans humans humans";
  width: 100%;
}

.config-form {
  grid-area: form;
  display: grid;
  grid-template-columns: min-content minmax(max-content, 200px);
  align-items: center;
  justify-content: center;
  grid-gap: 10px;
  margin: 20px;
}

.buttons {
  grid-area: buttons;
  display: grid;
  grid-template-areas: "reset slider" "next next" "start start";
  grid-template-rows: 90px auto;
  grid-template-columns: 1fr 1fr;
  justify-content: center;
  justify-items: center;
  grid-gap: 0 10px;
  height: 100%;
  align-content: space-around;
}

.next {
  grid-area: next;
}

.start {
  grid-area: start;
}

.buttons button {
  margin: 10px;
  font-size: xx-large;
  width: 100%;
  height: 70px;
}

.button {
  border-radius: 1em;
  background-color: #b6d094;
  border-style: solid;
  border-color: #2e2836;
  border-width: 2px;
  color: black;
}

#active-lang {
  margin: 20px;
}

input {
  background-color: #b6d094;
  border-color: #2e2836;
}

.legend {
  grid-area: legend;
  display: grid;
  justify-content: center;
  grid-template-columns: min-content min-content;
  justify-items: start;
  align-items: center;
}

.legend-color {
  width: 3em;
  height: 3em;
  margin: 0.5em;
}

.container {
  margin-top: 20px;
  grid-area: humans;
  display: grid;
  grid-gap: 1px;
}

.human {
  width: 100%;
  padding-top: 100%;
}

.healthy {
  background-color: #be8a60;
}

.infected {
  background-color: #6a2e35;
}

.immune {
  background-color: #b6d094;
}

.dead {
  background-color: #2e2836;
}

/* Slider, adapted from https://www.w3schools.com/howto/howto_css_switch.asp */

/* The switch - the box around the slider */

.switch {
  position: relative;
  display: inline-block;
  width: 100%;
  height: 100%;
  font-size: xx-large;
}

/* Hide default HTML checkbox */

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* The slider */

.slider {
  position: absolute;
  top: 10px;
  left: 0;
  right: 0;
  bottom: 10px;
  -webkit-transition: 0.4s;
  transition: 0.4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 50px;
  width: 50px;
  left: 10px;
  bottom: 10px;
  background-color: white;
  -webkit-transition: 0.4s;
  transition: 0.4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #be8a60;
}

input:checked + .slider:before {
  left: calc(100% - 60px);
}

footer {
  margin-top: 50px;
  height: 200px;
}

@media (max-width: 1200px) {
  main {
    grid-template-columns: 1fr 1fr;
    grid-template-areas: "form legend" "buttons buttons" "humans humans";
  }
}

@media (max-width: 800px) {
  main {
    grid-template-columns: 1fr;
    grid-template-areas: "form" "legend" "buttons" "humans";
  }
  .legend {
    grid-template-columns: min-content max-content min-content max-content;
  }
}

              
            
!

JS

              
                // Note: The code pen code is slightly adapted compared to the source code show in my repository at https://github.com/jakmeier/covid-sim/. 
// The reason is that here we are not using a bundler (WebPack).

// For the CodePen, I used `wasm-pack publish` to publish a package to npm.
//   1) wasm-pack build --scope jakmeier --target web
//   2) wasm-pack pack
//   3) wasm-pack publish --access public
//
// Here, we are loading this package through a public CDN. (Thanks unpkg!)
// The default export of the package gives access to a init() function that will load the WASM module.
import init, { Simulation } from "https://unpkg.com/@jakmeier/wasm-covid-sim@1.0.0/wasm_covid_sim.js";

// Note that the CDN that Skypack CDB, which CodePen uses by default, does not work. It does not export the wasm file at the time I was testing it.
// FAILS:
// import init, {Simulation} from 'https://cdn.skypack.dev/@jakmeier/wasm-covid-sim@1.0.0';

const HEALTHY = 0;
const INFECTED_DAY_0 = 1;
const INFECTED_DAY_MAX = 64;
const IMMUNE = 100;
const DEAD = 101;

let humans;
let htmlNodes;
let container;
let simulation;

let jsSimulation;
let rustSimulation;
let useJs = false;

let healthy = 0;
let infected = 0;
let immune = 0;
let dead = 0;


init()
  .then(() => {
    if (document.readyState != "loading") {
      main();
    } else {
      document.addEventListener("DOMContentLoaded", main);
    }
  })
  .catch((e) => console.log("failed loading wasm", e));

function main() {
  const mainElement = document.getElementsByTagName("main")[0];
  container = document.createElement("div");
  container.classList.add("container");
  mainElement.appendChild(container);

  rustSimulation = new Simulation();
  jsSimulation = new JsSimulation();
  simulation = rustSimulation;
  humans = new Uint8Array();

  reloadSettings();
  updateView();

  // Advance on space bar
  document.addEventListener("keydown", (evt) => {
    if (evt.key === " ") {
      advance();
    }
  });

  // Make functions globally available for onclick handler on button
  window.advance = advance;
  window.startStop = startStop;
  window.reloadSettings = reloadSettings;
  window.reloadLang = reloadLang;
  window.reset = reset;
}

function reloadSettings() {
  const form = document.getElementById("settings");
  const data = new FormData(form);
  const w = parseInt(data.get("width"));
  const h = parseInt(data.get("height"));
  const radius = parseInt(data.get("radius"));
  const recoveryDays = parseInt(data.get("recovery"));
  const infectionRate = parseFloat(data.get("infection_rate"));
  const deathRate = parseFloat(data.get("death_rate"));

  if (w * h != humans.length) {
    // Replace current state, set all values to 0 (HEALTHY)
    humans = new Uint8Array(w * h);
    generateHtmlNodes(w, h);
  }

  jsSimulation.reconfigure(
    w,
    h,
    radius,
    recoveryDays,
    infectionRate,
    deathRate
  );
  rustSimulation.reconfigure(
    w,
    h,
    radius,
    recoveryDays,
    infectionRate,
    deathRate
  );
}

function reloadLang() {
  useJs = document.getElementById("use-js").checked;
  if (useJs) {
    simulation = jsSimulation;
    document.getElementById("active-lang").textContent = "JS";
  } else {
    simulation = rustSimulation;
    document.getElementById("active-lang").textContent = "Rust";
  }
}

function reset() {
  humans = new Uint8Array(humans.length);
  htmlNodes.forEach((node) => {
    node.classList.add("healthy");
    node.classList.remove("infected");
    node.classList.remove("dead");
    node.classList.remove("immune");
  });
  // Infect patient 0
  setState(Math.floor(humans.length / 2), INFECTED_DAY_0);
  updateView();
}

function advance() {
    let newState = new Uint8Array(humans.length);
    const t0 = performance.now();
    simulation.next_day(humans, newState);
    const t1 = performance.now();
    for (let i = 0; i < htmlNodes.length; i++) {
        if (newState[i] != humans[i]) {
            setState(i, newState[i]);
        }
    }
    updateView();
    humans = newState;
    const t2 = performance.now();
    if (useJs) {
        console.log(`Updated in ${t2 - t0}ms  (${t1 - t0}ms computing in JS, ${t2 - t1}ms DOM updates in JS)`);
    } else {
        console.log(`Updated in ${t2 - t0}ms  (${t1 - t0}ms computing in Rust, ${t2 - t1}ms DOM updates in JS)`);
    }
}

let handle;
let isRunning = false;
function startStop() {
    const form = document.getElementById("settings");
    let simulationDelay = form.elements["delay"].value;
    if (isRunning) {
        clearInterval(handle);
        document.getElementById("start-stop-button").innerText = "Start Simulation";
    } else {
        handle = setInterval(advance, simulationDelay);
        document.getElementById("start-stop-button").innerText = "Stop Simulation";
    }
    isRunning = !isRunning;
}

function generateHtmlNodes(w, h) {
  const t0 = performance.now();
  while (container.firstChild) {
    container.removeChild(container.lastChild);
  }
  container.style.gridTemplateColumns = `repeat(${w},1fr)`;
  htmlNodes = [];
  for (let y = 0; y < h; y++) {
    for (let x = 0; x < w; x++) {
      const cell = document.createElement("div");
      cell.classList.add("human");
      cell.classList.add("healthy");
      cell.addEventListener("click", () => toggleInfected(x + y * w));
      container.appendChild(cell);
      htmlNodes.push(cell);
    }
  }
  const t1 = performance.now();
  console.log(`Created HTML nodes in ${t1 - t0}ms`);

  healthy = w * h;
  infected = 0;
  immune = 0;
  dead = 0;
  
  // Infect patient 0
  setState(Math.floor(humans.length / 2), INFECTED_DAY_0);
}

function updateView() {
  document.getElementById("legend-healthy").innerText = `Healthy (${healthy})`;
  document.getElementById(
    "legend-infected"
  ).innerText = `Infected (${infected})`;
  document.getElementById("legend-immune").innerText = `Immune (${immune})`;
  document.getElementById("legend-dead").innerText = `Dead (${dead})`;
}

function setState(i, state) {
  // Remove old class
  if (humans[i] == HEALTHY) {
    htmlNodes[i].classList.remove("healthy");
    healthy -= 1;
  } else if (humans[i] >= INFECTED_DAY_0 && humans[i] <= INFECTED_DAY_MAX) {
    htmlNodes[i].classList.remove("infected");
    infected -= 1;
  } else if (humans[i] == IMMUNE) {
    htmlNodes[i].classList.remove("immune");
    immune -= 1;
  } else if (humans[i] == DEAD) {
    htmlNodes[i].classList.remove("dead");
    dead -= 1;
  }

  // Add new class
  if (state == HEALTHY) {
    htmlNodes[i].classList.add("healthy");
    healthy += 1;
  } else if (state >= INFECTED_DAY_0 && state <= INFECTED_DAY_MAX) {
    htmlNodes[i].classList.add("infected");
    infected += 1;
  } else if (state == IMMUNE) {
    htmlNodes[i].classList.add("immune");
    immune += 1;
  } else if (state == DEAD) {
    htmlNodes[i].classList.add("dead");
    dead += 1;
  }
  humans[i] = state;
}

function toggleInfected(index) {
  if (humans[index] == HEALTHY) {
    setState(index, INFECTED_DAY_0);
  } else {
    setState(index, HEALTHY);
  }
  updateView();
}

/***************
 * lib.js
 ***************/
// Mirroring the behaviour of lib.rs in JavaScript for measuring the performance difference.
class JsSimulation {
  constructor(name, year) {
    this.w = 0;
    this.h = 0;
    this.recovery = 0;
    this.infection_rate = 0.0;
    this.death_rate = 0.0;
  }
  reconfigure(w, h, radius, recovery, infection_rate, death_rate) {
    this.w = w;
    this.h = h;
    this.radius = radius;
    this.recovery = recovery;
    this.infection_rate = infection_rate;
    this.death_rate = death_rate;
  }
  next_day(input, output) {
    for (let x = 0; x < this.w; x++) {
      for (let y = 0; y < this.h; y++) {
        const current = this.get(input, x, y);
        let next = current;
        if (current == HEALTHY) {
          if (this.chance_to_catch_covid_today(input, x, y) > Math.random()) {
            next = INFECTED_DAY_0 + 1;
          }
        } else if (current >= INFECTED_DAY_0 && current <= INFECTED_DAY_MAX) {
          if (this.death_rate > Math.random()) {
            next = DEAD;
          } else if (
            current >= INFECTED_DAY_0 &&
            current <= INFECTED_DAY_MAX &&
            current - INFECTED_DAY_0 >= this.recovery
          ) {
            next = IMMUNE;
          } else {
            next = current + 1;
          }
        }
        this.set(output, x, y, next);
      }
    }
  }
  chance_to_catch_covid_today(input, x, y) {
    let infected_neighbours = 0;
    const start_x = Math.max(0, x - this.radius);
    const start_y = Math.max(0, y - this.radius);
    const end_x = Math.min(x + this.radius + 1, this.w);
    const end_y = Math.min(y + this.radius + 1, this.h);
    for (let j = start_y; j < end_y; j++) {
      for (let i = start_x; i < end_x; i++) {
        const neighbour = this.get(input, i, j);
        if (neighbour >= INFECTED_DAY_0 && neighbour <= INFECTED_DAY_MAX) {
          infected_neighbours += 1;
        }
      }
    }
    let p_healthy = Math.pow(1.0 - this.infection_rate, infected_neighbours);
    return 1.0 - p_healthy;
  }
  get(input, x, y) {
    return input[x + y * this.w];
  }
  set(output, x, y, status) {
    output[x + y * this.w] = status;
  }
}

              
            
!
999px

Console