Mercurial > vba-clojure
view clojure/com/aurellem/run/image.clj @ 520:fe2b9a1fe919
reduced colors in pinkie pie mark to exactly 4.
author | Robert McIntyre <rlm@mit.edu> |
---|---|
date | Sat, 23 Jun 2012 17:22:32 -0500 |
parents | fd1ae0047a1a |
children | 5596cd4a3fc6 |
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.35 (def image-program-target 0xB000)37 (def display-width 160)38 (def display-height 144)42 ;{:r :g :b }44 (def character-data 0x8000)45 (def character-data-end 0x97FF)50 (def BG-data-1 0x9800)52 (def BG-data-2 0x9C00)54 (def OAM 0xFE00)58 (def video-bank-select-register 0xFF4F)60 (defn gb-rgb->bits [[r g b]]61 (assert (<= 0 r 31))62 (assert (<= 0 g 31))63 (assert (<= 0 b 31))64 [(bit-and65 0xFF66 (+67 r68 (bit-shift-left g 5)))69 (+70 (bit-shift-right g 3)71 (bit-shift-left b 2))])74 (def bg-palette-select 0xFF68)75 (def bg-palette-data 0xFF69)77 (def obj-palette-select 0xFF6A)78 (def obj-palette-data 0xFF6B)80 (def max-palettes 8)82 (defn write-byte [target data]83 (flatten84 [0x3E ;; load literal to A85 data86 0xEA ;; load A into target87 (reverse (disect-bytes-2 target))]))89 (defn begin-sequential-palette-write90 [palette-num palette-select-address]91 (assert (<= 0 palette-num max-palettes))92 (assert93 (or (= palette-select-address bg-palette-select)94 (= palette-select-address obj-palette-select)))95 (let [palette-write-data96 (Integer/parseInt97 (str "1" ;; auto increment98 "0" ;; not used99 (format100 "%03d"101 (Integer/parseInt102 (Integer/toBinaryString palette-num) 10))103 "00" ;; color num104 "0" ;; H/L105 ) 2)]106 (write-byte palette-select-address palette-write-data)))108 (defn set-palettes [palette-select palette-data palettes]109 (assert (<= (count palettes)) max-palettes)110 (flatten111 [(begin-sequential-palette-write 0 palette-select)113 0x21 ;; target address to HL114 (reverse (disect-bytes-2 palette-data))117 (for [palette palettes]118 (map (fn [byte]119 [0x3E ;; literal to A120 byte121 0x77]) ;; A -> (HL)123 (flatten124 (map #(gb-rgb->bits (get palette % [0 0 0]))125 (range 4)))))]))128 (defn display-one-color129 "Displayes a single color onto the gameboy screen. Input rgb in130 gameboy rgb."131 ([state [r g b]]132 ;; construct a kernel that displays a single color133 (let134 [palettes (repeat 8 [[r g b] [r g b] [r g b] [r g b]])135 kernel-address 0xC000136 kernel137 [0xF3 ;; disable interrupts138 (clear-music-registers)139 (frame-metronome)140 ;;(set-palettes141 ;; obj-palette-select obj-palette-data palettes)142 (set-palettes143 bg-palette-select bg-palette-data palettes)144 (infinite-loop)]]145 (-> (set-memory-range state146 kernel-address (flatten kernel))147 (PC! kernel-address))))148 ([[r g b]]149 (display-one-color @current-state [r g b])))151 ;;(require 'cortex.sense)152 (import java.awt.image.BufferedImage)154 ;; (defn show-screenshot []155 ;; (let [im (BufferedImage. 160 144 BufferedImage/TYPE_INT_RGB)156 ;; pix (vec (pixels))157 ;; view (cortex.sense/view-image)]158 ;; (dorun (for [x (range 160) y (range 144)]159 ;; (.setRGB im x y (pix (+ x (* 160 y))))))160 ;; (view im)))162 (defn gb-rgb->vga-rgb [[r g b]]163 (let [vga-rgb164 (first (pixels165 (run-moves166 (display-one-color167 (tick @current-state)168 [r g b])169 [[][]])))]170 [(bit-shift-right (bit-and vga-rgb 0xFF0000) 16)171 (bit-shift-right (bit-and vga-rgb 0xFF00) 8)172 (bit-and vga-rgb 0xFF)]))174 (defn generate-gb-color-map []175 (set-state! (mid-game))176 (let [gb-colors177 (for [r (range 32)178 g (range 32)179 b (range 32)]180 [r g b])]181 (zipmap gb-colors182 (map gb-rgb->vga-rgb183 gb-colors))))185 (import java.io.FileWriter)187 (def gb-color-map-file188 (File. user-home "proj/vba-clojure/gb-color-map"))190 (defn write-gb-color-map! []191 (binding [*out*(FileWriter. gb-color-map-file)]192 (let [out-str193 (.replace194 (str195 (into (sorted-map) (generate-gb-color-map)))196 "," ",\n")]197 (println out-str))))199 (def gb-color-map200 (read-string (slurp gb-color-map-file)))202 (import javax.imageio.stream.FileImageOutputStream)203 (import '(javax.imageio ImageWriteParam IIOImage ImageIO))206 (defn gen-gb-color-image! []207 (let [im (BufferedImage. 68 69 BufferedImage/TYPE_INT_RGB)208 pix (vec210 (reduce211 concat212 (map (partial213 sort-by214 (fn [[r g b]]215 (let [s (max r g b)216 det217 (cond218 (= s r)219 (+ -1000 (- g) b)220 (= s b)221 (+ (- r) g)222 (= s g)223 (+ 1000 (- b) r))]224 det)))225 (partition226 68 68 []227 (sort-by228 (fn euclidean-distance [[r g b]]229 (Math/sqrt (+ (* r r) (* g g) (* b b))))230 (filter231 (fn [[r g b]]232 (= (max r g b) b ))234 (seq (set (vals gb-color-map)))))))))235 ;;view (cortex.sense/view-image)236 target237 (File. user-home "proj/vba-clojure/gb-color-map-unique.png")]238 (dorun (for [x (range 68) y (range 69)]239 (let [[r g b] (get pix (+ x (* 68 y)) [0 0 0])240 rgb (+ (bit-shift-left r 16)241 (bit-shift-left g 8)242 b)]243 (.setRGB im x y rgb))))244 ;;(view im)245 (doto246 (.next (ImageIO/getImageWritersByFormatName "png"))247 (.setOutput (FileImageOutputStream. target))248 (.write (IIOImage. im nil nil))249 (.dispose))250 im))252 (defn gen-gb-color-image*! []253 (let [im (BufferedImage. 213 213 BufferedImage/TYPE_INT_RGB)254 squares255 (vec256 (for [r (range 32)]257 (vec258 (for [b (range 32) g (range 32)]259 (gb-color-map [r g b])))))260 ;;view (cortex.sense/view-image)261 target (File. user-home "proj/vba-clojure/gb-color-map.png")]263 (dorun264 (for [s-index (range 32)]265 (dorun266 (for [x (range 32) y (range 32)]268 (let [[r g b] ((squares s-index) (+ x (* 32 y)))269 rgb (+ (bit-shift-left r 16)270 (bit-shift-left g 8)271 b)]272 (.setRGB im273 (+ 3 (* 35 (rem s-index 6)) x)274 (+ 3 (* 35 (int (/ s-index 6))) y)275 rgb))))))276 ;;(view im)277 (doto278 (.next (ImageIO/getImageWritersByFormatName "png"))279 (.setOutput (FileImageOutputStream. target))280 (.write (IIOImage. im nil nil))281 (.dispose))282 im))284 (defn gen-gimp-palette! []285 (let [target286 (File. user-home "proj/vba-clojure/Gameboy-Color.gpl")]287 (spit288 target289 (apply290 str291 (concat292 ["GIMP Palette\n"293 "Name: GameBoy\n"294 "#\n"]295 (map (fn [[r g b]]296 (format "%3d %3d %3d\n" r g b))297 (sort (set (vals gb-color-map)))))))))299 (def test-image300 (ImageIO/read301 (File. user-home "/proj/vba-clojure/images/test-gb-image.png")))303 (def test-image-2304 (ImageIO/read305 (File. user-home "/proj/vba-clojure/images/test-gb-image-2.png")))307 (def test-image-color308 (ImageIO/read309 (File. user-home "/proj/vba-clojure/images/colors-test.png")))311 (def pinkie-pie-mark312 (ImageIO/read313 (File. user-home "/proj/vba-clojure/images/pinkie-pie-cutie-mark.png")))316 (defn rgb->triplet [rgb]317 (let [r (bit-shift-right (bit-and rgb 0xFF0000) 16)318 g (bit-shift-right (bit-and rgb 0xFF00) 8)319 b (bit-and rgb 0xFF)]320 [r g b]))322 (def reverse-gb-color-map323 (zipmap (vals gb-color-map)324 (keys gb-color-map)))326 (defn vga-rgb->gb-rgb [[r g b]]327 (reverse-gb-color-map [r g b]))329 (defn gb-tiles [^BufferedImage image]330 (for [tile (range 360)]331 (for [y (range 8) x (range 8)]332 (vga-rgb->gb-rgb333 (rgb->triplet334 (.getRGB image (+ x (* 8 (rem tile 20)))335 (+ y (* 8 (int (/ tile 20))))))))))337 (defn tile->palette [tile]338 (vec (sort (set tile))))340 (require 'clojure.set)342 (defn absorb-contract [objs]343 (reduce344 (fn [accepted new-element]345 (if (some346 (fn [obj]347 (clojure.set/subset? (set new-element) (set obj)))348 accepted)349 accepted350 (conj accepted new-element)))351 []352 (sort-by (comp - count) objs)))354 (defn palettes [^BufferedImage image]355 (let [palettes (map tile->palette (gb-tiles image))356 unique-palettes (absorb-contract (set palettes))]357 unique-palettes))359 (defn tile-pallete360 "find the first appropirate palette for the tile in the361 provided list of palettes."362 [tile palettes]363 (let [tile-colors (set tile)]364 (swank.util/find-first365 #(clojure.set/subset? tile-colors (set %))366 palettes)))369 (defn image->gb-image370 "Returns the image in a format amenable to the gameboy's371 internal representation. The format is:372 {:width -- width of the image373 :height -- height of the image374 :palettes -- vector of all the palettes the image375 needs, in proper order376 :tiles -- vector of all the tiles the image needs,377 in proper order. A tile is 64 palette378 indices.379 :data -- vector of pairs of the format:380 [tile-index, palette-index]381 in row-oriented order}"382 [^BufferedImage image]383 (let [image-palettes (palettes image)384 palette-index (zipmap385 image-palettes386 (range (count image-palettes)))387 tiles (gb-tiles image)388 unique-tiles (vec (distinct tiles))389 tile-index (zipmap unique-tiles390 (range (count unique-tiles)))]391 {:width (.getWidth image)392 :height (.getHeight image)393 :palettes image-palettes394 :tiles395 (vec396 (for [tile unique-tiles]397 (let [colors398 (vec (tile-pallete tile image-palettes))399 color-index400 (zipmap colors (range (count colors)))]401 (mapv color-index tile))))402 :data403 (vec404 (for [tile tiles]405 (let [tile-colors (set (tile->palette tile))]406 [(tile-index tile)407 (palette-index408 (tile-pallete tile image-palettes))])))}))410 (defn wait-until-v-blank411 "Modified version of frame-metronome. waits untill LY == 144,412 indicating start of v-blank period."413 []414 (let [timing-loop415 [0x01 ; \416 0x44 ; | load 0xFF44 into BC417 0xFF ; /418 0x0A] ;; (BC) -> A, now A = LY (vertical line coord)419 continue-if-144420 [0xFE421 144 ;; compare LY (in A) with 144422 0x20 ;; jump back to beginning if LY != 144 (not-v-blank)423 (->signed-8-bit424 (+ -4 (- (count timing-loop))))]]425 (concat timing-loop continue-if-144)))427 (def bg-character-data 0x9000)429 (defn gb-tile->bytes430 "Tile is a vector of 64 numbers between 0 and 3 that431 represent a single 8x8 color tile in the GB screen.432 It gets bit-packed into to 16 8-bit numbers in the following433 form:435 0-low 1-low ... 7-low436 0-high 1-high ... 7-high437 .438 .439 .440 55-low ........ 63-low441 55-high ........ 63-high"442 [tile]443 (let [row->bits444 (fn [row]445 (mapv446 (fn [row*]447 (Integer/parseInt (apply str row*) 2))448 [(map #(bit-and 0x01 %) row)449 (map #(bit-shift-right (bit-and 0x02 %) 1)450 row)]))]451 (vec452 (flatten453 (map row->bits454 (partition 8 tile))))))456 (defn write-data457 "Efficient assembly to write a sequence of values to458 memory, starting at a target address."459 [base-address target-address data]460 (let [len (count data)461 program-length 21] ;; change this if program length462 ;; below changes!463 (flatten464 [0x21 ;; load data address start into HL465 (reverse (disect-bytes-2 (+ base-address program-length)))467 0x01 ;; load target address into BC468 (reverse (disect-bytes-2 target-address))470 0x11 ;; load len into DE471 (reverse (disect-bytes-2 len))474 ;; data x-fer loop start475 0x2A ;; (HL) -> A; HL++;476 0x02 ;; A -> (BC);477 0x03 ;; INC BC;478 0x1B ;; DEC DE480 0xAF481 0xB2 ;; (OR D E) -> A482 0xB3485 0x20 ;; if DE is not now 0,486 (->signed-8-bit -9) ;; GOTO start488 0xC3489 (reverse490 (disect-bytes-2491 (+ len base-address program-length)))492 data])))494 (defn write-image495 "Assume the image data is specified as 360 blocks."496 [base-address target-address image-data]498 (let [len (count image-data)499 gen-program500 (fn [program-length]501 (flatten502 [0x01 ;; load data address start into BC503 (reverse504 (disect-bytes-2 (+ base-address program-length)))506 0x21 ;; load target address into HL507 (reverse (disect-bytes-2 target-address))509 0x1E ;; total-rows (18) -> E510 18512 0x16 ;; total columns (20) -> D513 20515 ;; data x-fer loop start516 0x0A ;; (BC) -> A;517 0x03 ;; INC BC;518 0x22 ;; A -> (HL); HL++;522 0x15 ;; dec D523 0x20524 (->signed-8-bit -6) ;; continue writing row526 ;; row is complete, advance to next row527 ;; HL += 12529 0xC5 ;; push BC531 0x06 ;; 0 -> B532 0534 0x0E535 12 ;; 12 -> C537 0x09 ;; HL + BC -> HL539 0xC1 ;; pop BC541 0x1D ;; dec E542 0x20543 (->signed-8-bit -18) ;; contunue writing image545 0xC3546 (reverse547 (disect-bytes-2548 (+ len base-address program-length)))]))]549 (flatten (concat550 (gen-program (count (gen-program 0)))551 image-data))))553 (defn test-write-data []554 (let [test-data (concat (range 256)555 (reverse (range 256)))556 base-address 0xC000557 target-address 0xD000559 test-kernel560 (flatten561 [0xF3 ;; disable interrupts562 (write-data (+ 1 base-address)563 target-address test-data)564 (infinite-loop)])]565 (assert566 (= test-data567 (-> (mid-game)568 tick tick tick569 (set-memory-range base-address test-kernel)570 (PC! base-address)571 (run-moves (repeat 100 []))572 (memory)573 vec574 (subvec target-address575 (+ target-address576 (count test-data))))))))578 (def LCD-bank-select-address 0xFF4F)580 (def BG-1-address 0x9800)581 (def BG-2-address 0x9C00)582 (def character-data-address 0x8000)584 (def LCD-control-register 0xFF40)585 (def STAT-register 0xFF41)587 (def SCX-register 0xFF42)588 (def SCY-register 0xFF43)590 (defn select-LCD-bank [n]591 (assert (or (= n 0) (= n 1)))592 (write-byte LCD-bank-select-address n))594 (defn write-image* [_ _ _] [])596 (defn display-image-kernel [base-address ^BufferedImage image]597 (let [gb-image (image->gb-image image)599 A [(clear-music-registers)601 ;; [X] disable LCD protection circuit.602 (write-byte LCD-control-register 0x00)603 ;; now we can write to all video RAM anytime with604 ;; impunity.606 ;; [ ] We're only using background palettes; just set the607 ;; minimum required bg palettes for this image, starting608 ;; with palette #0.610 (set-palettes bg-palette-select bg-palette-data611 (:palettes gb-image))613 ;; [X] switch to bank 0 to set BG character data.614 (select-LCD-bank 0)615 ;; [X] set SCX and SCY to 0616 (write-byte SCX-register 0)617 (write-byte SCY-register 0)618 ]619 A (flatten A)621 B [;; [X] write minimum amount of tiles to BG character622 ;; section623 (write-data624 (+ base-address (count A))625 character-data-address626 (flatten627 (map gb-tile->bytes (:tiles gb-image))))628 (select-LCD-bank 0)]629 B (flatten B)632 C [;; [X] write image to the screen in terms of tiles633 (write-image634 (+ base-address (+ (count A) (count B)))635 BG-1-address636 (map first (:data gb-image)))637 (select-LCD-bank 1)]639 C (flatten C)641 D [;; [X] specifiy pallets for each character642 (write-image643 (+ base-address (+ (count A) (count B) (count C)))644 BG-1-address645 (map second (:data gb-image)))648 ;; [X] reactivate the LCD display649 ;; we're using only BG images, located at650 ;; BG-1 (0x9800), with background character data651 ;; stored starting at 0x8000653 (write-byte654 LCD-control-register655 (Integer/parseInt656 (str657 "1" ;; LCDC on/off658 "0" ;; Window code area659 "0" ;; Windowing on?660 "1" ;; BG tile base (1 = 0x8000)661 "0" ;; BG-1 or BG-2 ?662 "0" ;; OBJ-block composition663 "0" ;; OBJ-on flag664 "1") ;; no-effect665 2))667 (infinite-loop)]668 D (flatten D)]670 (concat A B C D)))672 (defn display-image [#^BufferedImage image]673 (let [kernel-address 0xB000]674 (-> (tick (tick (tick (mid-game))))675 (set-memory-range676 kernel-address677 (display-image-kernel kernel-address image))678 (PC! kernel-address))))