From 40f2e2ccc4aec1aa220fdfd22d9872fd967a81f3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Magalh=C3=A3es?= <joamag@gmail.com>
Date: Sun, 13 Nov 2022 20:03:15 +0000
Subject: [PATCH] feat: initial palette update operation

---
 examples/web/index.ts      | 21 ++++++++++++++-------
 examples/web/react/app.tsx |  4 +++-
 2 files changed, 17 insertions(+), 8 deletions(-)

diff --git a/examples/web/index.ts b/examples/web/index.ts
index 72242663..85367731 100644
--- a/examples/web/index.ts
+++ b/examples/web/index.ts
@@ -33,6 +33,11 @@ const BACKGROUNDS = [
     "3a5a40"
 ];
 
+const PALETTES = [
+    ["ffffff", "c0c0c0", "606060", "000000"],
+    ["b6a571", "8b7e56", "554d35", "201d13"]
+];
+
 const KEYS_NAME: Record<string, number> = {
     ArrowUp: PadKey.Up,
     ArrowDown: PadKey.Down,
@@ -73,6 +78,7 @@ class GameboyEmulator extends EmulatorBase implements Emulator {
     private fps: number = 0;
     private frameStart: number = new Date().getTime();
     private frameCount: number = 0;
+    private paletteIndex: number = 0;
 
     private romName: string | null = null;
     private romData: Uint8Array | null = null;
@@ -286,13 +292,8 @@ class GameboyEmulator extends EmulatorBase implements Emulator {
                 break;
         }
 
-        // @TODO replace this with something more flexible
-        this.gameBoy.set_palette_colors_ws([
-            "b6a571",
-            "8b7e56",
-            "554d35",
-            "201d13"
-        ]);
+        // runs the initial palette update operation
+        this.updatePalette();
 
         // resets the Game Boy engine to restore it into
         // a valid state ready to be used
@@ -464,6 +465,12 @@ class GameboyEmulator extends EmulatorBase implements Emulator {
         this.gameBoy?.key_lift(keyCode);
     }
 
+    updatePalette() {
+        this.gameBoy?.set_palette_colors_ws(PALETTES[this.paletteIndex]);
+        this.paletteIndex += 1;
+        this.paletteIndex %= PALETTES.length;
+    }
+
     benchmark(count = 50000000) {
         let cycles = 0;
         this.pause();
diff --git a/examples/web/react/app.tsx b/examples/web/react/app.tsx
index 111f3a0e..183910f3 100644
--- a/examples/web/react/app.tsx
+++ b/examples/web/react/app.tsx
@@ -222,6 +222,8 @@ export interface Emulator extends ObservableI {
 
     keyLift(key: string): void;
 
+    updatePalette(): void;
+
     /**
      * Runs a benchmark operation in the emulator, effectively
      * measuring the performance of it.
@@ -483,7 +485,7 @@ export const App: FC<AppProps> = ({
         setBackgroundIndex((backgroundIndex + 1) % backgrounds.length);
     };
     const onPaletteClick = () => {
-        console.info("palette");
+        emulator.updatePalette();
     };
     const onUploadFile = async (file: File) => {
         const arrayBuffer = await file.arrayBuffer();
-- 
GitLab