view clojure/com/aurellem/run/image.clj @ 512:7ba07a6adb0c

going to correct premium stupdity.
author Robert McIntyre <rlm@mit.edu>
date Fri, 22 Jun 2012 18:38:22 -0500
parents 964957680c11
children 3dbb863eb801
line wrap: on
line source
1 (ns com.aurellem.run.image
2 (:use (com.aurellem.gb saves gb-driver util constants
3 items vbm characters money
4 rlm-assembly))
5 (:use (com.aurellem.run util music title save-corruption
6 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 be
15 ;; simple.
17 ;; use background tiles? they provide greater color depth than
18 ;; sprites, and can still be scrolled, so why not?
20 ;; could also use sprites to get 3 more colors per tile for a total of
21 ;; 7 colors per tile, although not for all tiles...
25 ;; want a function to
27 ;; 1. read an image
28 ;; 2. split into a grid of 8x8 pixels
29 ;; 3. convert all RGB colors to gb-RGB colors
30 ;; 4. determine efficient color palletes for the image
31 ;; 5. output efficient assembly code to draw the image to the gb
32 ;; 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-and
65 0xFF
66 (+
67 r
68 (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 (flatten
84 [0x3E ;; load literal to A
85 data
86 0xEA ;; load A into target
87 (reverse (disect-bytes-2 target))]))
89 (defn begin-sequential-palette-write
90 [palette-num palette-select-address]
91 (assert (<= 0 palette-num max-palettes))
92 (assert
93 (or (= palette-select-address bg-palette-select)
94 (= palette-select-address obj-palette-select)))
95 (let [palette-write-data
96 (Integer/parseInt
97 (str "1" ;; auto increment
98 "0" ;; not used
99 (format
100 "%03d"
101 (Integer/parseInt
102 (Integer/toBinaryString palette-num) 10))
103 "00" ;; color num
104 "0" ;; H/L
105 ) 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 (flatten
111 [(begin-sequential-palette-write 0 palette-select)
113 0x21 ;; target address to HL
114 (reverse (disect-bytes-2 palette-data))
117 (for [palette palettes]
118 (map (fn [byte]
119 [0x3E ;; literal to A
120 byte
121 0x77]) ;; A -> (HL)
123 (flatten
124 (map #(gb-rgb->bits (get palette % [0 0 0]))
125 (range 4)))))]))
128 (defn display-one-color
129 "Displayes a single color onto the gameboy screen. Input rgb in
130 gameboy rgb."
131 ([state [r g b]]
132 ;; construct a kernel that displays a single color
133 (let
134 [palettes (repeat 8 [[r g b] [r g b] [r g b] [r g b]])
135 kernel-address 0xC000
136 kernel
137 [0xF3 ;; disable interrupts
138 (clear-music-registers)
139 (frame-metronome)
140 ;;(set-palettes
141 ;; obj-palette-select obj-palette-data palettes)
142 (set-palettes
143 bg-palette-select bg-palette-data palettes)
144 (infinite-loop)]]
145 (-> (set-memory-range state
146 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-rgb
164 (first (pixels
165 (run-moves
166 (display-one-color
167 (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-colors
177 (for [r (range 32)
178 g (range 32)
179 b (range 32)]
180 [r g b])]
181 (zipmap gb-colors
182 (map gb-rgb->vga-rgb
183 gb-colors))))
185 (import java.io.FileWriter)
187 (def gb-color-map-file
188 (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-str
193 (.replace
194 (str
195 (into (sorted-map) (generate-gb-color-map)))
196 "," ",\n")]
197 (println out-str))))
199 (def gb-color-map
200 (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 (vec
210 (reduce
211 concat
212 (map (partial
213 sort-by
214 (fn [[r g b]]
215 (let [s (max r g b)
216 det
217 (cond
218 (= s r)
219 (+ -1000 (- g) b)
220 (= s b)
221 (+ (- r) g)
222 (= s g)
223 (+ 1000 (- b) r))]
224 det)))
225 (partition
226 68 68 []
227 (sort-by
228 (fn euclidean-distance [[r g b]]
229 (Math/sqrt (+ (* r r) (* g g) (* b b))))
230 (filter
231 (fn [[r g b]]
232 (= (max r g b) b ))
234 (seq (set (vals gb-color-map)))))))))
235 ;;view (cortex.sense/view-image)
236 target (File. user-home "proj/vba-clojure/gb-color-map-unique.png")]
237 (dorun (for [x (range 68) y (range 69)]
238 (let [[r g b] (get pix (+ x (* 68 y)) [0 0 0])
239 rgb (+ (bit-shift-left r 16)
240 (bit-shift-left g 8)
241 b)]
242 (.setRGB im x y rgb))))
243 ;;(view im)
244 (doto
245 (.next (ImageIO/getImageWritersByFormatName "png"))
246 (.setOutput (FileImageOutputStream. target))
247 (.write (IIOImage. im nil nil))
248 (.dispose))
249 im))
251 (defn gen-gb-color-image*! []
252 (let [im (BufferedImage. 213 213 BufferedImage/TYPE_INT_RGB)
253 squares
254 (vec
255 (for [r (range 32)]
256 (vec
257 (for [b (range 32) g (range 32)]
258 (gb-color-map [r g b])))))
259 ;;view (cortex.sense/view-image)
260 target (File. user-home "proj/vba-clojure/gb-color-map.png")]
262 (dorun
263 (for [s-index (range 32)]
264 (dorun
265 (for [x (range 32) y (range 32)]
267 (let [[r g b] ((squares s-index) (+ x (* 32 y)))
268 rgb (+ (bit-shift-left r 16)
269 (bit-shift-left g 8)
270 b)]
271 (.setRGB im
272 (+ 3 (* 35 (rem s-index 6)) x)
273 (+ 3 (* 35 (int (/ s-index 6))) y)
274 rgb))))))
275 ;;(view im)
276 (doto
277 (.next (ImageIO/getImageWritersByFormatName "png"))
278 (.setOutput (FileImageOutputStream. target))
279 (.write (IIOImage. im nil nil))
280 (.dispose))
281 im))
283 (def test-image
284 (ImageIO/read
285 (File. user-home "/proj/vba-clojure/images/test-gb-image.png")))
287 (defn rgb->triplet [rgb]
288 (let [r (bit-shift-right (bit-and rgb 0xFF0000) 16)
289 g (bit-shift-right (bit-and rgb 0xFF00) 8)
290 b (bit-and rgb 0xFF)]
291 [r g b]))
293 (def reverse-gb-color-map
294 (zipmap (vals gb-color-map)
295 (keys gb-color-map)))
297 (defn vga-rgb->gb-rgb [[r g b]]
298 (reverse-gb-color-map [r g b]))
300 (defn gb-tiles [^BufferedImage image]
301 (for [tile (range 360)]
302 (for [x (range 8) y (range 8)]
303 (vga-rgb->gb-rgb
304 (rgb->triplet
305 (.getRGB image (+ x (* 8 (rem tile 20)))
306 (+ y (* 8 (int (/ tile 20))))))))))
308 (defn tile->palette [tile]
309 (vec (sort (set tile))))
311 (require 'clojure.set)
313 (defn absorb-contract [objs]
314 (reduce
315 (fn [accepted new-element]
316 (if (some
317 (fn [obj]
318 (clojure.set/subset? (set new-element) (set obj)))
319 accepted)
320 accepted
321 (conj accepted new-element)))
322 []
323 (sort-by (comp - count) objs)))
325 (defn palettes [^BufferedImage image]
326 (let [palettes (map tile->palette (gb-tiles image))
327 unique-palettes (absorb-contract (set palettes))]
328 unique-palettes))
330 (defn tile-pallete
331 "find the first appropirate palette for the tile in the
332 provided list of palettes."
333 [tile palettes]
334 (let [tile-colors (set tile)]
335 (swank.util/find-first
336 #(clojure.set/subset? tile-colors (set %))
337 palettes)))
340 (defn image->gb-image
341 "Returns the image in a format amenable to the gameboy's
342 internal representation. The format is:
343 {:width -- width of the image
344 :height -- height of the image
345 :palettes -- vector of all the palettes the image
346 needs, in proper order
347 :tiles -- vector of all the tiles the image needs,
348 in proper order. A tile is 64 palette
349 indices.
350 :data -- vector of pairs of the format:
351 [tile-index, palette-index]
352 in row-oriented order}"
353 [^BufferedImage image]
354 (let [image-palettes (palettes image)
355 palette-index (zipmap
356 image-palettes
357 (range (count image-palettes)))
358 tiles (gb-tiles image)
359 unique-tiles (vec (distinct tiles))
360 tile-index (zipmap unique-tiles
361 (range (count unique-tiles)))]
362 {:width (.getWidth image)
363 :height (.getHeight image)
364 :palettes image-palettes
365 :tiles
366 (vec
367 (for [tile unique-tiles]
368 (let [colors
369 (vec (tile-pallete tile image-palettes))
370 color-index
371 (zipmap colors (range (count colors)))]
372 (mapv color-index tile))))
373 :data
374 (vec
375 (for [tile tiles]
376 (let [tile-colors (set (tile->palette tile))]
377 [(tile-index tile)
378 (palette-index
379 (tile-pallete tile image-palettes))])))}))
381 (defn wait-until-v-blank
382 "Modified version of frame-metronome. waits untill LY == 144,
383 indicating start of v-blank period."
384 []
385 (let [timing-loop
386 [0x01 ; \
387 0x44 ; | load 0xFF44 into BC
388 0xFF ; /
389 0x0A] ;; (BC) -> A, now A = LY (vertical line coord)
390 continue-if-144
391 [0xFE
392 144 ;; compare LY (in A) with 144
393 0x20 ;; jump back to beginning if LY != 144 (not-v-blank)
394 (->signed-8-bit
395 (+ -4 (- (count timing-loop))))]]
396 (concat timing-loop continue-if-144)))
398 (def bg-character-data 0x9000)
400 (defn gb-tile->bytes
401 "Tile is a vector of 64 numbers between 0 and 3 that
402 represent a single 8x8 color tile in the GB screen.
403 It gets bit-packed into to 16 8-bit numbers in the following
404 form:
406 0-low 1-low ... 7-low
407 0-high 1-high ... 7-high
408 .
409 .
410 .
411 55-low ........ 63-low
412 55-high ........ 63-high"
413 [tile]
414 (let [row->bits
415 (fn [row]
416 (mapv
417 (fn [row*]
418 (Integer/parseInt (apply str row*) 2))
419 [(map #(bit-and 0x01 %) row)
420 (map #(bit-shift-right (bit-and 0x02 %) 1)
421 row)]))]
422 (vec
423 (flatten
424 (map row->bits
425 (partition 8 tile))))))
427 (defn write-data
428 "Efficient assembly to write a sequence of values to
429 memory, starting at a target address."
430 [base-address target-address data]
431 (let [len (count data)
432 program-length 21] ;; change this if program length
433 ;; below changes!
434 (flatten
435 [0x21 ;; load data address start into HL
436 (reverse (disect-bytes-2 (+ base-address program-length)))
438 0x01 ;; load target address into BC
439 (reverse (disect-bytes-2 target-address))
441 0x11 ;; load len into DE
442 (reverse (disect-bytes-2 len))
445 ;; data x-fer loop start
446 0x2A ;; (HL) -> A; HL++;
447 0x02 ;; A -> (BC);
448 0x03 ;; INC BC;
449 0x1B ;; DEC DE
451 0xAF
452 0xB2 ;; (OR D E) -> A
453 0xB3
456 0x20 ;; if DE is not now 0,
457 (->signed-8-bit -9) ;; GOTO start
459 0xC3
460 (reverse
461 (disect-bytes-2
462 (+ len base-address program-length)))
463 data])))
465 (defn write-image
466 "Assume the image data is 160x144 pixels specified as 360 blocks."
467 [base-address target-address image-data]
469 (let [len (count image-data)
470 gen-program
471 (fn [program-length]
472 (flatten
473 [0x21 ;; load data address start into HL
474 (reverse
475 (disect-bytes-2 (+ base-address program-length)))
477 0x01 ;; load target address into BC
478 (reverse (disect-bytes-2 target-address))
480 0x1E ;; total-rows (18) -> E
481 1
483 0x16 ;; total columns (20) -> D
484 20
486 ;; wite one block (8x8 pixels) to screen.
487 0x3E
488 16 ;; load 16 into A
490 0xF5 ;; push A
492 ;; data x-fer loop start
493 0x2A ;; (HL) -> A; HL++;
494 0x02 ;; A -> (BC);
495 0x03 ;; INC BC;
498 0xF1 ;; pop A
500 0x3D ;; dec A
501 0x20 ;;
502 (->signed-8-bit -8) ;; continue writing block
504 0x15 ;; dec D
505 0x20
506 (->signed-8-bit -13) ;; continue writing row
508 ;; row is complete, advance to next row
509 ;; HL += 192
511 0xC5 ;; push BC
513 0x06 ;; 0 -> B
514 0
516 0x0E
517 0 ;; 192 -> C
519 0x09 ;; HL + BC -> HL
521 0xC1 ;; pop BC
523 0x1D ;; dec E
524 0x20
525 (->signed-8-bit -23) ;; contunue writing picture
527 0xC3
528 (reverse
529 (disect-bytes-2
530 (+ len base-address program-length)))]))]
531 (flatten (concat
532 (gen-program (count (gen-program 0)))
533 image-data))))
535 (defn test-write-data []
536 (let [test-data (concat (range 256)
537 (reverse (range 256)))
538 base-address 0xC000
539 target-address 0xD000
541 test-kernel
542 (flatten
543 [0xF3 ;; disable interrupts
544 (write-data (+ 1 base-address)
545 target-address test-data)
546 (infinite-loop)])]
547 (assert
548 (= test-data
549 (-> (mid-game)
550 tick tick tick
551 (set-memory-range base-address test-kernel)
552 (PC! base-address)
553 (run-moves (repeat 100 []))
554 (memory)
555 vec
556 (subvec target-address
557 (+ target-address
558 (count test-data))))))))
560 (def LCD-bank-select-address 0xFF4F)
562 (def BG-1-address 0x9800)
563 (def BG-2-address 0x9C00)
564 (def character-data-address 0x8000)
566 (def LCD-control-register 0xFF40)
567 (def STAT-register 0xFF41)
569 (def SCX-register 0xFF42)
570 (def SCY-register 0xFF43)
572 (defn select-LCD-bank [n]
573 (assert (or (= n 0) (= n 1)))
574 (write-byte LCD-bank-select-address n))
576 (defn write-image* [_ _ _] [])
578 (defn display-image-kernel [base-address ^BufferedImage image]
579 (let [gb-image (image->gb-image image)
581 A [(clear-music-registers)
583 ;; [X] disable LCD protection circuit.
584 (write-byte LCD-control-register 0x00)
585 ;; now we can write to all video RAM anytime with
586 ;; impunity.
588 ;; [ ] We're only using background palettes; just set the
589 ;; minimum required bg palettes for this image, starting
590 ;; with palette #0.
592 (set-palettes bg-palette-select bg-palette-data
593 (:palettes gb-image))
595 ;; [X] switch to bank 0 to set BG character data.
596 (select-LCD-bank 0)
597 ;; [X] set SCX and SCY to 0
598 (write-byte SCX-register 0)
599 (write-byte SCY-register 0)
600 ]
601 A (flatten A)
603 B [;; [X] write minimum amount of tiles to BG character
604 ;; section
605 (write-data
606 (+ base-address (count A))
607 character-data-address
608 (flatten
609 (map gb-tile->bytes (:tiles gb-image))))]
610 B (flatten B)
613 C [;; [ ] write image to the screen in terms of tiles
614 (write-image
615 (+ base-address (+ (count A) (count B)))
616 BG-1-address
617 (map first (:data gb-image)))]
619 C (flatten C)
621 D [;; [ ] specifiy pallets for each character
622 (select-LCD-bank 1)
623 (write-image
624 (+ base-address (+ (count A) (count B) (count C)))
625 BG-1-address
626 (map second (:data gb-image)))
629 ;; [X] reactivate the LCD display
630 ;; we're using only BG images, located at
631 ;; BG-1 (0x9800), with background character data
632 ;; stored starting at 0x8000
634 (write-byte
635 LCD-control-register
636 (Integer/parseInt
637 (str
638 "1" ;; LCDC on/off
639 "0" ;; Window code area
640 "0" ;; Windowing on?
641 "1" ;; BG tile base (1 = 0x8000)
642 "0" ;; BG-1 or BG-2 ?
643 "0" ;; OBJ-block composition
644 "0" ;; OBJ-on flag
645 "1") ;; no-effect
646 2))
648 (infinite-loop)]
649 D (flatten D)]
651 (concat A B C D)))
653 (defn display-image [#^BufferedImage image]
654 (let [kernel-address 0xB000]
655 (-> (tick (tick (tick (mid-game))))
656 (set-memory-range
657 kernel-address
658 (display-image-kernel kernel-address image))
659 (PC! kernel-address))))