Mercurial > vba-clojure
view clojure/com/aurellem/run/image.clj @ 511:964957680c11
got an image to display, but it doesn't tile correctly.
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Fri, 22 Jun 2012 15:03:41 -0500 |
parents | b9814e3114e4 |
children | 7ba07a6adb0c |
line wrap: on
line source
1 (ns com.aurellem.run.image2 (:use (com.aurellem.gb saves gb-driver util constants3 items vbm characters money4 rlm-assembly))5 (:use (com.aurellem.run util music title save-corruption6 bootstrap-0 bootstrap-1))7 (:require clojure.string)8 (:import [com.aurellem.gb.gb_driver SaveState])9 (:import java.io.File))11 ;; want to display an image onto the screen.12 ;; probably will be the six ponies, possibly with scrolling.14 ;; probably don't need hi-color mode since the images shuld be15 ;; simple.17 ;; use background tiles? they provide greater color depth than18 ;; sprites, and can still be scrolled, so why not?20 ;; could also use sprites to get 3 more colors per tile for a total of21 ;; 7 colors per tile, although not for all tiles...25 ;; want a function to27 ;; 1. read an image28 ;; 2. split into a grid of 8x8 pixels29 ;; 3. convert all RGB colors to gb-RGB colors30 ;; 4. determine efficient color palletes for the image31 ;; 5. output efficient assembly code to draw the image to the gb32 ;; screen.46 (def image-program-target 0xB000)48 (def display-width 160)49 (def display-height 144)53 ;{:r :g :b }55 (def character-data 0x8000)56 (def character-data-end 0x97FF)61 (def BG-data-1 0x9800)63 (def BG-data-2 0x9C00)65 (def OAM 0xFE00)69 (def video-bank-select-register 0xFF4F)71 (defn gb-rgb->bits [[r g b]]72 (assert (<= 0 r 31))73 (assert (<= 0 g 31))74 (assert (<= 0 b 31))75 [(bit-and76 0xFF77 (+78 r79 (bit-shift-left g 5)))80 (+81 (bit-shift-right g 3)82 (bit-shift-left b 2))])85 (def bg-palette-select 0xFF68)86 (def bg-palette-data 0xFF69)88 (def obj-palette-select 0xFF6A)89 (def obj-palette-data 0xFF6B)91 (def max-palettes 8)93 (defn write-byte [target data]94 (flatten95 [0x3E ;; load literal to A96 data97 0xEA ;; load A into target98 (reverse (disect-bytes-2 target))]))100 (defn begin-sequential-palette-write101 [palette-num palette-select-address]102 (assert (<= 0 palette-num max-palettes))103 (assert104 (or (= palette-select-address bg-palette-select)105 (= palette-select-address obj-palette-select)))106 (let [palette-write-data107 (Integer/parseInt108 (str "1" ;; auto increment109 "0" ;; not used110 (format111 "%03d"112 (Integer/parseInt113 (Integer/toBinaryString palette-num) 10))114 "00" ;; color num115 "0" ;; H/L116 ) 2)]117 (write-byte palette-select-address palette-write-data)))119 (defn set-palettes [palette-select palette-data palettes]120 (assert (<= (count palettes)) max-palettes)121 (flatten122 [(begin-sequential-palette-write 0 palette-select)124 0x21 ;; target address to HL125 (reverse (disect-bytes-2 palette-data))128 (for [palette palettes]129 (map (fn [byte]130 [0x3E ;; literal to A131 byte132 0x77]) ;; A -> (HL)134 (flatten135 (map #(gb-rgb->bits (get palette % [0 0 0]))136 (range 4)))))]))139 (defn display-one-color140 "Displayes a single color onto the gameboy screen. Input rgb in141 gameboy rgb."142 ([state [r g b]]143 ;; construct a kernel that displays a single color144 (let145 [palettes (repeat 8 [[r g b] [r g b] [r g b] [r g b]])146 kernel-address 0xC000147 kernel148 [0xF3 ;; disable interrupts149 (clear-music-registers)150 (frame-metronome)151 ;;(set-palettes152 ;; obj-palette-select obj-palette-data palettes)153 (set-palettes154 bg-palette-select bg-palette-data palettes)155 (infinite-loop)]]156 (-> (set-memory-range state157 kernel-address (flatten kernel))158 (PC! kernel-address))))159 ([[r g b]]160 (display-one-color @current-state [r g b])))162 ;;(require 'cortex.sense)163 (import java.awt.image.BufferedImage)165 ;; (defn show-screenshot []166 ;; (let [im (BufferedImage. 160 144 BufferedImage/TYPE_INT_RGB)167 ;; pix (vec (pixels))168 ;; view (cortex.sense/view-image)]169 ;; (dorun (for [x (range 160) y (range 144)]170 ;; (.setRGB im x y (pix (+ x (* 160 y))))))171 ;; (view im)))173 (defn gb-rgb->vga-rgb [[r g b]]174 (let [vga-rgb175 (first (pixels176 (run-moves177 (display-one-color178 (tick @current-state)179 [r g b])180 [[][]])))]181 [(bit-shift-right (bit-and vga-rgb 0xFF0000) 16)182 (bit-shift-right (bit-and vga-rgb 0xFF00) 8)183 (bit-and vga-rgb 0xFF)]))185 (defn generate-gb-color-map []186 (set-state! (mid-game))187 (let [gb-colors188 (for [r (range 32)189 g (range 32)190 b (range 32)]191 [r g b])]192 (zipmap gb-colors193 (map gb-rgb->vga-rgb194 gb-colors))))196 (import java.io.FileWriter)198 (def gb-color-map-file199 (File. user-home "proj/vba-clojure/gb-color-map"))201 (defn write-gb-color-map! []202 (binding [*out*(FileWriter. gb-color-map-file)]203 (let [out-str204 (.replace205 (str206 (into (sorted-map) (generate-gb-color-map)))207 "," ",\n")]208 (println out-str))))210 (def gb-color-map211 (read-string (slurp gb-color-map-file)))213 (import javax.imageio.stream.FileImageOutputStream)214 (import '(javax.imageio ImageWriteParam IIOImage ImageIO))217 (defn gen-gb-color-image! []218 (let [im (BufferedImage. 68 69 BufferedImage/TYPE_INT_RGB)219 pix (vec221 (reduce222 concat223 (map (partial224 sort-by225 (fn [[r g b]]226 (let [s (max r g b)227 det228 (cond229 (= s r)230 (+ -1000 (- g) b)231 (= s b)232 (+ (- r) g)233 (= s g)234 (+ 1000 (- b) r))]235 det)))236 (partition237 68 68 []238 (sort-by239 (fn euclidean-distance [[r g b]]240 (Math/sqrt (+ (* r r) (* g g) (* b b))))241 (filter242 (fn [[r g b]]243 (= (max r g b) b ))245 (seq (set (vals gb-color-map)))))))))246 ;;view (cortex.sense/view-image)247 target (File. user-home "proj/vba-clojure/gb-color-map-unique.png")]248 (dorun (for [x (range 68) y (range 69)]249 (let [[r g b] (get pix (+ x (* 68 y)) [0 0 0])250 rgb (+ (bit-shift-left r 16)251 (bit-shift-left g 8)252 b)]253 (.setRGB im x y rgb))))254 ;;(view im)255 (doto256 (.next (ImageIO/getImageWritersByFormatName "png"))257 (.setOutput (FileImageOutputStream. target))258 (.write (IIOImage. im nil nil))259 (.dispose))260 im))262 (defn gen-gb-color-image*! []263 (let [im (BufferedImage. 213 213 BufferedImage/TYPE_INT_RGB)264 squares265 (vec266 (for [r (range 32)]267 (vec268 (for [b (range 32) g (range 32)]269 (gb-color-map [r g b])))))270 ;;view (cortex.sense/view-image)271 target (File. user-home "proj/vba-clojure/gb-color-map.png")]273 (dorun274 (for [s-index (range 32)]275 (dorun276 (for [x (range 32) y (range 32)]278 (let [[r g b] ((squares s-index) (+ x (* 32 y)))279 rgb (+ (bit-shift-left r 16)280 (bit-shift-left g 8)281 b)]282 (.setRGB im283 (+ 3 (* 35 (rem s-index 6)) x)284 (+ 3 (* 35 (int (/ s-index 6))) y)285 rgb))))))286 ;;(view im)287 (doto288 (.next (ImageIO/getImageWritersByFormatName "png"))289 (.setOutput (FileImageOutputStream. target))290 (.write (IIOImage. im nil nil))291 (.dispose))292 im))294 (def test-image295 (ImageIO/read296 (File. user-home "/proj/vba-clojure/images/test-gb-image.png")))298 (defn rgb->triplet [rgb]299 (let [r (bit-shift-right (bit-and rgb 0xFF0000) 16)300 g (bit-shift-right (bit-and rgb 0xFF00) 8)301 b (bit-and rgb 0xFF)]302 [r g b]))304 (def reverse-gb-color-map305 (zipmap (vals gb-color-map)306 (keys gb-color-map)))308 (defn vga-rgb->gb-rgb [[r g b]]309 (reverse-gb-color-map [r g b]))311 (defn gb-tiles [^BufferedImage image]312 (for [tile (range 360)]313 (for [x (range 8) y (range 8)]314 (vga-rgb->gb-rgb315 (rgb->triplet316 (.getRGB image (+ x (* 8 (rem tile 20)))317 (+ y (* 8 (int (/ tile 20))))))))))319 (defn tile->palette [tile]320 (vec (sort (set tile))))322 (require 'clojure.set)324 (defn absorb-contract [objs]325 (reduce326 (fn [accepted new-element]327 (if (some328 (fn [obj]329 (clojure.set/subset? (set new-element) (set obj)))330 accepted)331 accepted332 (conj accepted new-element)))333 []334 (sort-by (comp - count) objs)))336 (defn absorb-combine-4 [objs]338 )340 (defn palettes [^BufferedImage image]341 (let [palettes (map tile->palette (gb-tiles image))342 unique-palettes (absorb-contract (set palettes))]343 unique-palettes))345 (defn tile-pallete346 "find the first appropirate palette for the tile in the347 provided list of palettes."348 [tile palettes]349 (let [tile-colors (set tile)]350 (swank.util/find-first351 #(clojure.set/subset? tile-colors (set %))352 palettes)))355 (defn image->gb-image356 "Returns the image in a format amenable to the gameboy's357 internal representation. The format is:358 {:width -- width of the image359 :height -- height of the image360 :palettes -- vector of all the palettes the image361 needs, in proper order362 :tiles -- vector of all the tiles the image needs,363 in proper order. A tile is 64 palette364 indices.365 :data -- vector of pairs of the format:366 [tile-index, palette-index]367 in row-oriented order}"368 [^BufferedImage image]369 (let [image-palettes (palettes image)370 palette-index (zipmap371 image-palettes372 (range (count image-palettes)))373 tiles (gb-tiles image)374 unique-tiles (vec (distinct tiles))375 tile-index (zipmap unique-tiles376 (range (count unique-tiles)))]377 {:width (.getWidth image)378 :height (.getHeight image)379 :palettes image-palettes380 :tiles381 (vec382 (for [tile unique-tiles]383 (let [colors384 (vec (tile-pallete tile image-palettes))385 color-index386 (zipmap colors (range (count colors)))]387 (mapv color-index tile))))388 :data389 (vec390 (for [tile tiles]391 (let [tile-colors (set (tile->palette tile))]392 [(tile-index tile)393 (palette-index394 (tile-pallete tile image-palettes))])))}))398 (defn wait-until-v-blank399 "Modified version of frame-metronome. waits untill LY == 144,400 indicating start of v-blank period."401 []402 (let [timing-loop403 [0x01 ; \404 0x44 ; | load 0xFF44 into BC405 0xFF ; /406 0x0A] ;; (BC) -> A, now A = LY (vertical line coord)407 continue-if-144408 [0xFE409 144 ;; compare LY (in A) with 144410 0x20 ;; jump back to beginning if LY != 144 (not-v-blank)411 (->signed-8-bit412 (+ -4 (- (count timing-loop))))]]413 (concat timing-loop continue-if-144)))416 (def bg-character-data 0x9000)418 (defn gb-tile->bytes419 "Tile is a vector of 64 numbers between 0 and 3 that420 represent a single 8x8 color tile in the GB screen.421 It gets bit-packed into to 16 8-bit numbers in the following422 form:424 0-low 1-low ... 7-low425 0-high 1-high ... 7-high426 .427 .428 .429 55-low ........ 63-low430 55-high ........ 63-high"431 [tile]432 (let [row->bits433 (fn [row]434 (mapv435 (fn [row*]436 (Integer/parseInt (apply str row*) 2))437 [(map #(bit-and 0x01 %) row)438 (map #(bit-shift-right (bit-and 0x02 %) 1)439 row)]))]440 (vec441 (flatten442 (map row->bits443 (partition 8 tile))))))446 (defn write-data447 "Efficient assembly to write a sequence of values to448 memory, starting at a target address."449 [base-address target-address data]450 (let [len (count data)451 program-length 21] ;; change this if program length452 ;; below changes!454 (flatten455 [0x21 ;; load data address start into HL456 (reverse (disect-bytes-2 (+ base-address program-length)))458 0x01 ;; load target address into BC459 (reverse (disect-bytes-2 target-address))461 0x11 ;; load len into DE462 (reverse (disect-bytes-2 len))465 ;; data x-fer loop start466 0x2A ;; (HL) -> A; HL++;467 0x02 ;; A -> (BC);468 0x03 ;; INC BC;469 0x1B ;; DEC DE471 0xAF472 0xB2 ;; (OR D E) -> A473 0xB3476 0x20 ;; if DE is not now 0,477 (->signed-8-bit -9) ;; GOTO start479 0xC3480 (reverse481 (disect-bytes-2482 (+ len base-address program-length)))483 data])))486 (defn test-write-data []487 (let [test-data (concat (range 256)488 (reverse (range 256)))489 base-address 0xC000490 target-address 0xD000492 test-kernel493 (flatten494 [0xF3 ;; disable interrupts495 (write-data (+ 1 base-address)496 target-address test-data)497 (infinite-loop)])]498 (assert499 (= test-data500 (-> (mid-game)501 tick tick tick502 (set-memory-range base-address test-kernel)503 (PC! base-address)504 (run-moves (repeat 100 []))505 (memory)506 vec507 (subvec target-address508 (+ target-address509 (count test-data))))))))511 (def LCD-bank-select-address 0xFF4F)513 (def BG-1-address 0x9800)514 (def BG-2-address 0x9C00)515 (def character-data-address 0x8000)517 (def LCD-control-register 0xFF40)518 (def STAT-register 0xFF41)520 (def SCX-register 0xFF42)521 (def SCY-register 0xFF43)523 (defn select-LCD-bank [n]524 (assert (or (= n 0) (= n 1)))525 (write-byte LCD-bank-select-address n))527 (defn display-image-kernel [base-address ^BufferedImage image]528 (let [gb-image (image->gb-image image)530 A [(clear-music-registers)532 ;; [X] disable LCD protection circuit.533 (write-byte LCD-control-register 0x00)534 ;; now we can write to all video RAM anytime with535 ;; impunity.537 ;; we're only using background palettes; just set the538 ;; minimum required bg palettes for this image,539 ;; starting with palette #0.541 (set-palettes bg-palette-select bg-palette-data542 (:palettes gb-image))544 ;; [X] switch to bank 0 to set BG character data.545 (select-LCD-bank 0)547 ;; [X] set SCX and SCY to 0548 (write-byte SCX-register 0)549 (write-byte SCY-register 0)551 ]552 A (flatten A)554 B [;; [X] write minimum amount of tiles to BG character555 ;; section556 (write-data557 (+ base-address (count A))558 character-data-address559 (flatten560 (map gb-tile->bytes (:tiles gb-image))))]561 B (flatten B)564 C [;; [ ] write image to the screen in terms of tiles565 (write-data566 (+ base-address (+ (count A) (count B)))567 BG-1-address568 (map first (:data gb-image)))]570 C (flatten C)572 D [;; [ ] specifiy pallets for each character573 (select-LCD-bank 1)574 (write-data575 (+ base-address (+ (count A) (count B) (count C)))576 BG-1-address577 (map second (:data gb-image)))580 ;; [X] reactivate the LCD display581 ;; we're using only BG images, located at582 ;; BG-1 (0x9800), with background character data583 ;; stored starting at 0x8000585 (write-byte586 LCD-control-register587 (Integer/parseInt588 (str589 "1" ;; LCDC on/off590 "0" ;; Window code area591 "0" ;; Windowing on?592 "1" ;; BG tile base (1 = 0x8000)593 "0" ;; BG-1 or BG-2 ?594 "0" ;; OBJ-block composition595 "0" ;; OBJ-on flag596 "1") ;; no-effect597 2))600 (infinite-loop)]601 D (flatten D)]603 (concat A B C D)))606 (defn display-image [#^BufferedImage image]607 (let [kernel-address 0xB000]608 (-> (tick (tick (tick (mid-game))))609 (set-memory-range610 kernel-address611 (display-image-kernel kernel-address image))612 (PC! kernel-address))))