-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpng2prg.go
1404 lines (1296 loc) · 37.5 KB
/
png2prg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package png2prg provides png/gif/jpg to c64 .prg conversion.
// A single png2prg instance cannot be used concurrently, but each instance is standalone, many can be used in parallel.
package png2prg
import (
"bytes"
_ "embed"
"fmt"
"image"
"image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/staD020/TSCrunch"
"github.com/staD020/sid"
)
const (
Version = "1.9.4-dev"
displayerJumpTo = "$0828"
MaxColors = 16
MaxChars = 256
MaxECMChars = 64
FullScreenChars = 1000
FullScreenWidth = 320
FullScreenHeight = 200
ViceFullScreenWidth = 384
ViceFullScreenHeight = 272
SpriteWidth = 24
SpriteHeight = 21
BitmapAddress = 0x2000
BitmapScreenRAMAddress = 0x3f40
BitmapColorRAMAddress = 0x4328
CharsetScreenRAMAddress = 0x2800
CharsetColorRAMAddress = 0x2c00
)
// An Options struct contains all settings to be used for an instance of png2prg.
// The default empty/false settings are in general fine.
// You may want to set Quiet to suppress logging to stdout and Display to true if you want include the displayer.
type Options struct {
OutFile string
TargetDir string
Verbose bool
VeryVerbose bool
Quiet bool
Display bool
BruteForce bool
NumWorkers int
NoPackChars bool
NoPackEmptyChar bool
ForcePackEmptyChar bool
NoPrevCharColors bool
NoBitpairCounters bool
NoCrunch bool
Symbols bool
AlternativeFade bool
NoFade bool
BitpairColorsString string
NoGuess bool
GraphicsMode string
Interlace bool
D016Offset int
ForceBorderColor int
IncludeSID string
NoAnimation bool
FrameDelay int
WaitSeconds int
ForceXOffset int
ForceYOffset int
CurrentGraphicsType GraphicsType
Trd bool // has side effect of enforcing screenram colors in level area
}
func (o Options) NoFadeByte() byte {
if o.NoFade {
return 1
}
return 0
}
type RGB struct {
R, G, B byte
}
func (r RGB) String() string {
return fmt.Sprintf("RGB{%#02x, %#02x, %#02x}", r.R, r.G, r.B)
}
type ColorInfo struct {
ColorIndex byte
RGB RGB
}
func (c ColorInfo) String() string {
//return fmt.Sprintf("{%d, #%02x%02x%02x}", c.ColorIndex, int(c.RGB.R), int(c.RGB.G), int(c.RGB.B))
return fmt.Sprintf("{%d, %s},", c.ColorIndex, c.RGB)
}
// A GraphicsType represents a supported c64 graphics type.
type GraphicsType byte
const (
unknownGraphicsType GraphicsType = iota
singleColorBitmap
multiColorBitmap
singleColorCharset
multiColorCharset
singleColorSprites
multiColorSprites
multiColorInterlaceBitmap // https://csdb.dk/release/?id=3961
mixedCharset
petsciiCharset
ecmCharset
)
func StringToGraphicsType(s string) GraphicsType {
switch s {
case "koala":
return multiColorBitmap
case "hires":
return singleColorBitmap
case "sccharset":
return singleColorCharset
case "mccharset":
return multiColorCharset
case "scsprites":
return singleColorSprites
case "mcsprites":
return multiColorSprites
case "mcibitmap":
return multiColorInterlaceBitmap
case "mixedcharset":
return mixedCharset
case "petscii":
return petsciiCharset
case "ecm":
return ecmCharset
}
return unknownGraphicsType
}
func (t GraphicsType) String() string {
switch t {
case singleColorBitmap:
return "hires"
case multiColorBitmap:
return "koala"
case singleColorCharset:
return "singlecolor charset"
case multiColorCharset:
return "multicolor charset"
case singleColorSprites:
return "singlecolor sprites"
case multiColorSprites:
return "multicolor sprites"
case multiColorInterlaceBitmap:
return "mcibitmap"
case mixedCharset:
return "mixed charset"
case petsciiCharset:
return "petscii"
case ecmCharset:
return "ecm"
default:
return "unknown"
}
}
type bitpairColors []byte
func (b bitpairColors) String() (s string) {
for i, v := range b {
s = s + strconv.Itoa(int(v))
if i < len(b)-1 {
s += ","
}
}
return s
}
// A PalletMap contains mapping from RGB colors to their c64 colorindexes.
type PaletteMap map[RGB]byte
func (m PaletteMap) RGB(c64Color byte) RGB {
for rgb, col := range m {
if col == c64Color {
return rgb
}
}
log.Printf("c64Color %v not found in palette %v", c64Color, m)
return RGB{}
}
func (m PaletteMap) devString() string {
reverse := [MaxColors]*RGB{}
for r, c := range m {
r := r
reverse[c] = &r
}
s := ""
for c, r := range reverse {
if r == nil {
continue
}
s += fmt.Sprintf("{%d, %s}, ", c, *r)
}
return strings.TrimSuffix(s, ", ")
}
func (m PaletteMap) String() string {
reverse := [MaxColors]*RGB{}
for r, c := range m {
r := r
reverse[c] = &r
}
s := ""
for c, r := range reverse {
if r == nil {
continue
}
s += fmt.Sprintf("{%d, #%02x%02x%02x}, ", c, int(r.R), int(r.G), int(r.B))
}
return strings.TrimSuffix(s, ", ")
}
type sourceImage struct {
sourceFilename string
opt Options
image image.Image
xOffset int
yOffset int
width int
height int
palette PaletteMap
colors []RGB
charColors [1000]PaletteMap
backgroundCandidates PaletteMap
backgroundColor ColorInfo
borderColor ColorInfo
preferredBitpairColors bitpairColors
ecmColors bitpairColors
graphicsType GraphicsType
c64color2bitpairCache [1000]map[byte]byte
c64colorBitpairCount [MaxColors]map[byte]int
}
type MultiColorChar struct {
CharIndex int
Bitmap [8]byte
BackgroundColor byte
ScreenColor byte
D800Color byte
}
type SingleColorChar struct {
CharIndex int
Bitmap [8]byte
ScreenColor byte
D800Color byte
}
type Koala struct {
SourceFilename string
Bitmap [8000]byte
ScreenColor [1000]byte
D800Color [1000]byte
BackgroundColor byte
BorderColor byte
opt Options
}
type c64Symbol struct {
key string
value int
}
type Symbolser interface {
Symbols() []c64Symbol
}
func (img Koala) Symbols() []c64Symbol {
return []c64Symbol{
{"bitmap", BitmapAddress},
{"screenram", BitmapScreenRAMAddress},
{"colorram", BitmapColorRAMAddress},
{"d020color", int(img.BorderColor)},
{"d021color", int(img.BackgroundColor)},
}
}
type Hires struct {
SourceFilename string
Bitmap [8000]byte
ScreenColor [1000]byte
BorderColor byte
opt Options
}
func (img Hires) Symbols() []c64Symbol {
return []c64Symbol{
{"bitmap", BitmapAddress},
{"screenram", BitmapScreenRAMAddress},
{"d020color", int(img.BorderColor)},
}
}
type MultiColorCharset struct {
SourceFilename string
Bitmap [0x800]byte
Screen [1000]byte
D800Color [1000]byte
CharColor byte
BorderColor byte
BackgroundColor byte
D022Color byte
D023Color byte
opt Options
}
func (img MultiColorCharset) Symbols() []c64Symbol {
return []c64Symbol{
{"bitmap", BitmapAddress},
{"screenram", CharsetScreenRAMAddress},
{"charcolor", int(img.CharColor)},
{"d020color", int(img.BorderColor)},
{"d021color", int(img.BackgroundColor)},
{"d022color", int(img.D022Color)},
{"d023color", int(img.D023Color)},
}
}
func (c MultiColorCharset) UsedChars() int {
max := byte(0)
for _, v := range c.Screen {
if v > max {
max = v
}
}
// check for empty chars too, this is for animations
empty := charBytes{}
emptyCount := 0
for i := 0; i < MaxChars; i++ {
cb := charBytes{}
for j := 0; j < 8; j++ {
cb[j] = c.Bitmap[i*8+j]
}
if cb == empty {
emptyCount++
if emptyCount > 1 && i > int(max) {
return i
}
}
}
return (int(max) + 1)
}
func (c MultiColorCharset) CharBytes() (cbs []charBytes) {
used := c.UsedChars()
for i := 0; i < used; i++ {
cb := charBytes{}
for j := 0; j < 8; j++ {
cb[j] = c.Bitmap[(i*8)+j]
}
cbs = append(cbs, cb)
}
return cbs
}
type SingleColorCharset struct {
SourceFilename string
Bitmap [0x800]byte
Screen [1000]byte
D800Color [1000]byte
BackgroundColor byte
BorderColor byte
used int
opt Options
}
func (img SingleColorCharset) Symbols() []c64Symbol {
return []c64Symbol{
{"bitmap", BitmapAddress},
{"screenram", CharsetScreenRAMAddress},
{"colorram", CharsetColorRAMAddress},
{"d020color", int(img.BorderColor)},
{"d021color", int(img.BackgroundColor)},
}
}
func (c SingleColorCharset) UsedChars() int {
max := byte(0)
for _, v := range c.Screen {
if v > max {
max = v
}
}
// check for empty chars too, this is for animations
empty := charBytes{}
emptyCount := 0
for i := 0; i < MaxChars; i++ {
cb := charBytes{}
for j := 0; j < 8; j++ {
cb[j] = c.Bitmap[i*8+j]
}
if cb == empty {
emptyCount++
if emptyCount > 1 && i > int(max) {
return i
}
}
}
return (int(max) + 1)
}
func (c SingleColorCharset) CharBytes() (cbs []charBytes) {
used := c.UsedChars()
for i := 0; i < used; i++ {
cb := charBytes{}
for j := 0; j < 8; j++ {
cb[j] = c.Bitmap[(i*8)+j]
}
cbs = append(cbs, cb)
}
return cbs
}
type MixedCharset struct {
SourceFilename string
Bitmap [0x800]byte
Screen [1000]byte
D800Color [1000]byte
BorderColor byte
BackgroundColor byte
D022Color byte
D023Color byte
opt Options
}
func (img MixedCharset) Symbols() []c64Symbol {
return []c64Symbol{
{"bitmap", BitmapAddress},
{"screenram", CharsetScreenRAMAddress},
{"colorram", CharsetColorRAMAddress},
{"d020color", int(img.BorderColor)},
{"d021color", int(img.BackgroundColor)},
{"d022color", int(img.D022Color)},
{"d023color", int(img.D023Color)},
}
}
func (c MixedCharset) UsedChars() int {
max := byte(0)
for _, v := range c.Screen {
if v > max {
max = v
}
}
// check for empty chars too, this is for animations
empty := charBytes{}
emptyCount := 0
for i := 0; i < MaxChars; i++ {
cb := charBytes{}
for j := 0; j < 8; j++ {
cb[j] = c.Bitmap[i*8+j]
}
if cb == empty {
emptyCount++
if emptyCount > 1 && i > int(max) {
return i
}
}
}
return (int(max) + 1)
}
func (c MixedCharset) CharBytes() (cbs []charBytes) {
used := c.UsedChars()
for i := 0; i < used; i++ {
cb := charBytes{}
for j := 0; j < 8; j++ {
cb[j] = c.Bitmap[(i*8)+j]
}
cbs = append(cbs, cb)
}
return cbs
}
type PETSCIICharset struct {
SourceFilename string
Lowercase byte // 0 = uppercase, 1 = lowercase
Screen [1000]byte
D800Color [1000]byte
BackgroundColor byte
BorderColor byte
opt Options
}
func (img PETSCIICharset) Symbols() []c64Symbol {
return []c64Symbol{
{"screenram", CharsetScreenRAMAddress},
{"colorram", CharsetColorRAMAddress},
{"d020color", int(img.BorderColor)},
{"d021color", int(img.BackgroundColor)},
}
}
type ECMCharset struct {
SourceFilename string
Bitmap [0x200]byte
Screen [1000]byte
D800Color [1000]byte
BorderColor byte
BackgroundColor byte
D022Color byte
D023Color byte
D024Color byte
opt Options
}
func (img ECMCharset) Symbols() []c64Symbol {
return []c64Symbol{
{"bitmap", BitmapAddress},
{"screenram", CharsetScreenRAMAddress},
{"colorram", CharsetColorRAMAddress},
{"d020color", int(img.BorderColor)},
{"d021color", int(img.BackgroundColor)},
{"d022color", int(img.D022Color)},
{"d023color", int(img.D023Color)},
{"d024color", int(img.D024Color)},
}
}
type SingleColorSprites struct {
SourceFilename string
Bitmap []byte
SpriteColor byte
BackgroundColor byte
Columns byte
Rows byte
opt Options
}
func (img SingleColorSprites) Symbols() []c64Symbol {
return []c64Symbol{
{"bitmap", BitmapAddress},
{"columns", int(img.Columns)},
{"rows", int(img.Rows)},
{"spritecolor", int(img.SpriteColor)},
{"d021color", int(img.BackgroundColor)},
}
}
type MultiColorSprites struct {
SourceFilename string
Bitmap []byte
SpriteColor byte
BackgroundColor byte
D025Color byte
D026Color byte
Columns byte
Rows byte
opt Options
}
func (img MultiColorSprites) Symbols() []c64Symbol {
return []c64Symbol{
{"bitmap", BitmapAddress},
{"columns", int(img.Columns)},
{"rows", int(img.Rows)},
{"spritecolor", int(img.SpriteColor)},
{"d021color", int(img.BackgroundColor)},
{"d025color", int(img.D025Color)},
{"d026color", int(img.D026Color)},
}
}
var displayers = make(map[GraphicsType][]byte, 0)
var displayersAlternative = make(map[GraphicsType][]byte, 0)
//go:embed "display_koala.prg"
var koalaDisplay []byte
//go:embed "display_hires.prg"
var hiresDisplay []byte
//go:embed "display_mc_charset.prg"
var mcCharsetDisplay []byte
//go:embed "display_mc_charset_anim.prg"
var mcCharsetDisplayAnim []byte
//go:embed "display_mc_charset_multi.prg"
var mcCharsetDisplayMulti []byte
//go:embed "display_sc_charset.prg"
var scCharsetDisplay []byte
//go:embed "display_sc_charset_anim.prg"
var scCharsetDisplayAnim []byte
//go:embed "display_sc_charset_multi.prg"
var scCharsetDisplayMulti []byte
//go:embed "display_mc_sprites.prg"
var mcSpritesDisplay []byte
//go:embed "display_sc_sprites.prg"
var scSpritesDisplay []byte
//go:embed "display_koala_anim.prg"
var koalaDisplayAnim []byte
//go:embed "display_koala_anim_alternative.prg"
var koalaDisplayAnimAlternative []byte
//go:embed "display_hires_anim.prg"
var hiresDisplayAnim []byte
//go:embed "display_mci_bitmap.prg"
var mciBitmapDisplay []byte
//go:embed "display_mixed_charset.prg"
var mixedCharsetDisplay []byte
//go:embed "display_petscii_charset.prg"
var petsciiCharsetDisplay []byte
//go:embed "display_petscii_charset_anim.prg"
var petsciiCharsetDisplayAnim []byte
//go:embed "display_ecm_charset.prg"
var ecmCharsetDisplay []byte
//go:embed "tools/rom_charset_lowercase.prg"
var romCharsetLowercasePrg []byte
//go:embed "tools/rom_charset_uppercase.prg"
var romCharsetUppercasePrg []byte
func init() {
displayers[multiColorBitmap] = koalaDisplay
displayers[singleColorBitmap] = hiresDisplay
displayers[multiColorCharset] = mcCharsetDisplay
displayers[singleColorCharset] = scCharsetDisplay
displayers[multiColorSprites] = mcSpritesDisplay
displayers[singleColorSprites] = scSpritesDisplay
displayers[multiColorInterlaceBitmap] = mciBitmapDisplay
displayers[mixedCharset] = mixedCharsetDisplay
displayers[petsciiCharset] = petsciiCharsetDisplay
displayers[ecmCharset] = ecmCharsetDisplay
}
// newHeader returns a copy of the displayer code for GraphicsType t as a byte slice in .prg format.
func (t GraphicsType) newHeader() []byte {
bin := make([]byte, len(displayers[t]))
copy(bin, displayers[t])
return bin
}
// A Converter implements the io.WriterTo interface.
type Converter struct {
opt Options
images []sourceImage
Symbols []c64Symbol
FinalGraphicsType GraphicsType
}
// New processes the input pngs and the returns the Converter.
// Returns an error if any of the images have non-supported dimensions.
// Generally a single image is used as input. For animations an animated gif or multiple .pngs will do the trick.
//
// The returned Converter implements the io.WriterTo interface.
func New(opt Options, pngs ...io.Reader) (*Converter, error) {
if opt.ForceBorderColor > 15 {
log.Printf("-force-border-color %d is not correct, only values 0-15 are allowed, now using default.", opt.ForceBorderColor)
opt.ForceBorderColor = -1
}
if opt.GraphicsMode != "" && opt.CurrentGraphicsType == unknownGraphicsType {
opt.CurrentGraphicsType = StringToGraphicsType(opt.GraphicsMode)
}
c := &Converter{opt: opt}
for index, ir := range pngs {
ii, err := NewSourceImages(opt, index, ir)
if err != nil {
return c, fmt.Errorf("NewSourceImages failed: %w", err)
}
c.images = append(c.images, ii...)
}
return c, nil
}
// NewSourceImages decodes r into one or more sourceImages and returns them.
// Also validates the resolution of the images.
// Generally imgs contain 1 image, unless an animated .gif was supplied in r.
func NewSourceImages(opt Options, index int, r io.Reader) (imgs []sourceImage, err error) {
path := fmt.Sprintf("png2prg_%02d", index)
if n, isNamer := r.(interface{ Name() string }); isNamer {
path = n.Name()
}
bin, err := io.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("io.ReadAll %q failed: %w", path, err)
}
// try gif first
if g, err := gif.DecodeAll(bytes.NewReader(bin)); err == nil {
if opt.Verbose {
log.Printf("file %q has %d frames", path, len(g.Image))
}
for i, rawImage := range g.Image {
if opt.VeryVerbose {
log.Printf("processing frame %d", i)
}
img := sourceImage{
sourceFilename: path,
opt: opt,
image: rawImage,
}
if err = img.setPreferredBitpairColors(opt.BitpairColorsString); err != nil {
return nil, fmt.Errorf("setPreferredBitpairColors %q failed: %w", opt.BitpairColorsString, err)
}
switch {
case i == 0:
if err = img.checkBounds(); err != nil {
return nil, fmt.Errorf("img.checkBounds failed %q frame %d: %w", path, i, err)
}
case i > 0:
img.xOffset, img.yOffset = imgs[0].xOffset, imgs[0].yOffset
img.width, img.height = imgs[0].width, imgs[0].height
}
imgs = append(imgs, img)
}
return imgs, nil
}
// should be png or jpg
img := sourceImage{
sourceFilename: path,
opt: opt,
}
if err = img.setPreferredBitpairColors(opt.BitpairColorsString); err != nil {
return nil, fmt.Errorf("setPreferredBitpairColors %q failed: %w", opt.BitpairColorsString, err)
}
if img.image, _, err = image.Decode(bytes.NewReader(bin)); err != nil {
return nil, fmt.Errorf("image.Decode failed: %w", err)
}
if err = img.checkBounds(); err != nil {
return nil, fmt.Errorf("img.checkBounds failed: %w", err)
}
imgs = append(imgs, img)
return imgs, nil
}
// NewSourceImage returns a new sourceImage after bounds check.
func NewSourceImage(opt Options, index int, in image.Image) (img sourceImage, err error) {
img = sourceImage{
sourceFilename: fmt.Sprintf("png2prg_%02d", index),
opt: opt,
image: in,
}
if err = img.setPreferredBitpairColors(opt.BitpairColorsString); err != nil {
return img, fmt.Errorf("setPreferredBitpairColors %q failed: %w", opt.BitpairColorsString, err)
}
if err = img.checkBounds(); err != nil {
return img, fmt.Errorf("img.checkBounds failed: %w", err)
}
return img, nil
}
// NewFromPath is the convenience New method when input images are on disk.
// See New for detais.
func NewFromPath(opt Options, filenames ...string) (*Converter, error) {
in := make([]io.Reader, 0, len(filenames))
for _, path := range filenames {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("os.Open failed: %w", err)
}
defer f.Close()
in = append(in, f)
}
return New(opt, in...)
}
func (c *Converter) SortedColors() []byte {
bpc := c.images[0].preferredBitpairColors
if c.opt.Verbose {
log.Printf("-bpc %s", bpc)
}
_, _, sumColors := c.images[0].countColors()
type sumcol struct {
col byte
count int
}
sc := []sumcol{}
for col, count := range sumColors {
sc = append(sc, sumcol{col: byte(col), count: count})
}
sort.Slice(sc, func(i, j int) bool { return sc[i].count > sc[j].count })
result := make([]byte, len(sc))
for i, scol := range sc {
result[i] = scol.col
}
if c.opt.Verbose {
log.Printf("result: %v", result)
}
return result
}
// WriteTo processes the image(s) and writes the resulting .prg to w.
// Returns error when analysis or conversion fails.
func (c *Converter) WriteTo(w io.Writer) (n int64, err error) {
if len(c.images) == 0 {
return 0, fmt.Errorf("no images found")
}
img := &c.images[0]
if c.opt.Verbose {
log.Printf("processing file %q", img.sourceFilename)
}
defer func() {
if len(c.images) == 1 {
c.FinalGraphicsType = img.graphicsType
}
}()
if err = img.analyze(); err != nil {
return 0, fmt.Errorf("analyze %q failed: %w", img.sourceFilename, err)
}
if (len(c.images) == 1 && img.graphicsType == multiColorInterlaceBitmap) || (len(c.images) == 2 && c.opt.Interlace) {
if !c.opt.Quiet {
fmt.Printf("interlace mode\n")
}
var rgba0, rgba1 *image.RGBA
if img.graphicsType == multiColorInterlaceBitmap {
rgba0, rgba1 = img.SplitInterlace()
c.opt.ForceBorderColor = int(img.borderColor.ColorIndex)
if !c.opt.Quiet {
fmt.Println("interlaced pic was split")
}
c.opt.CurrentGraphicsType = multiColorBitmap
c.opt.GraphicsMode = multiColorBitmap.String()
i0, err := NewSourceImage(c.opt, 0, rgba0)
if err != nil {
return n, fmt.Errorf("NewSourceImages %q failed: %w", img.sourceFilename, err)
}
i1, err := NewSourceImage(c.opt, 1, rgba1)
if err != nil {
return n, fmt.Errorf("NewSourceImages %q failed: %w", img.sourceFilename, err)
}
c.images = []sourceImage{i0, i1}
}
if err = c.images[0].analyze(); err != nil {
return n, fmt.Errorf("analyze %q failed: %w", c.images[0].sourceFilename, err)
}
if err = c.images[1].analyze(); err != nil {
return n, fmt.Errorf("analyze %q failed: %w", c.images[1].sourceFilename, err)
}
c.FinalGraphicsType = img.graphicsType
return c.WriteInterlaceTo(w)
}
if len(c.images) > 1 {
return c.WriteAnimationTo(w)
}
bruteforce := func(gfxtype GraphicsType, maxColors int) error {
if !c.opt.BruteForce {
return nil
}
if err = c.BruteForceBitpairColors(gfxtype, maxColors); err != nil {
return fmt.Errorf("BruteForceBitpairColors %q failed: %w", img.sourceFilename, err)
}
if err = img.setPreferredBitpairColors(c.opt.BitpairColorsString); err != nil {
return fmt.Errorf("img.setPreferredBitpairColors %q failed: %w", c.opt.BitpairColorsString, err)
}
return nil
}
var wt io.WriterTo
switch img.graphicsType {
case multiColorBitmap:
if err = bruteforce(multiColorBitmap, 4); err != nil {
return 0, err
}
if wt, err = img.Koala(); err != nil {
return 0, fmt.Errorf("img.Koala %q failed: %w", img.sourceFilename, err)
}
case singleColorBitmap:
if err = bruteforce(singleColorBitmap, 2); err != nil {
return 0, err
}
if wt, err = img.Hires(); err != nil {
return 0, fmt.Errorf("img.Hires %q failed: %w", img.sourceFilename, err)
}
case singleColorCharset:
if c.opt.GraphicsMode != "" {
if wt, err = img.SingleColorCharset(nil); err != nil {
return 0, fmt.Errorf("img.SingleColorCharset %q failed: %w", img.sourceFilename, err)
}
} else {
if wt, err = img.PETSCIICharset(); err != nil {
if wt, err = img.SingleColorCharset(nil); err != nil {
fmt.Printf("falling back to %s because img.SingleColorCharset %q failed: %v\n", singleColorBitmap, img.sourceFilename, err)
img.graphicsType = singleColorBitmap
if err = bruteforce(singleColorBitmap, 2); err != nil {
return 0, err
}
if wt, err = img.Hires(); err != nil {
return 0, fmt.Errorf("img.Hires %q failed: %w", img.sourceFilename, err)
}
}
} else if !c.opt.Quiet {
fmt.Printf("detected petscii\n")
img.graphicsType = petsciiCharset
}
}
case petsciiCharset:
if wt, err = img.PETSCIICharset(); err != nil {
return 0, fmt.Errorf("img.PETSCIICharset %q failed: %w", img.sourceFilename, err)
}
case ecmCharset:
if wt, err = img.ECMCharset(nil); err != nil {
if c.opt.GraphicsMode != "" {
return 0, fmt.Errorf("img.ECMCharset %q failed: %w", img.sourceFilename, err)
}
fmt.Printf("falling back to %s because img.ECMCharset %q failed: %v\n", singleColorBitmap, img.sourceFilename, err)
img.graphicsType = singleColorBitmap
if err = bruteforce(singleColorBitmap, 2); err != nil {
return 0, err
}
if wt, err = img.Hires(); err != nil {
return 0, fmt.Errorf("img.Hires %q failed: %w", img.sourceFilename, err)
}
}
case multiColorCharset:
if err = bruteforce(multiColorCharset, 4); err != nil {
if c.opt.GraphicsMode != "" {
return 0, fmt.Errorf("img.MultiColorCharset %q failed: %w", img.sourceFilename, err)
}
fmt.Printf("falling back to %s because bruteforce %q failed: %v\n", multiColorBitmap, img.sourceFilename, err)
img.graphicsType = multiColorBitmap
err = img.findBackgroundColor()
if err != nil {
return 0, fmt.Errorf("findBackgroundColor %q failed: %w", img.sourceFilename, err)
}
if err = bruteforce(multiColorBitmap, 4); err != nil {
return 0, err
}
if wt, err = img.Koala(); err != nil {
return 0, fmt.Errorf("img.Koala %q failed: %w", img.sourceFilename, err)
}
}
if wt, err = img.MultiColorCharset(nil); err != nil {
if c.opt.GraphicsMode != "" {
return 0, fmt.Errorf("img.MultiColorCharset %q failed: %w", img.sourceFilename, err)
}
fmt.Printf("falling back to %s because img.MultiColorCharset %q failed: %v\n", multiColorBitmap, img.sourceFilename, err)
img.graphicsType = multiColorBitmap
err = img.findBackgroundColor()
if err != nil {
return 0, fmt.Errorf("findBackgroundColor %q failed: %w", img.sourceFilename, err)
}
if err = bruteforce(multiColorBitmap, 4); err != nil {
return 0, err
}
if wt, err = img.Koala(); err != nil {
return 0, fmt.Errorf("img.Koala %q failed: %w", img.sourceFilename, err)
}
}
case singleColorSprites:
if wt, err = img.SingleColorSprites(); err != nil {
return 0, fmt.Errorf("img.SingleColorSprites %q failed: %w", img.sourceFilename, err)
}
case multiColorSprites:
if wt, err = img.MultiColorSprites(); err != nil {
return 0, fmt.Errorf("img.MultiColorSprites %q failed: %w", img.sourceFilename, err)
}
case mixedCharset:
if err = bruteforce(mixedCharset, 4); err != nil {
if c.opt.GraphicsMode != "" {
return 0, fmt.Errorf("img.MixedCharset %q failed: %w", img.sourceFilename, err)
}
fmt.Printf("falling back to %s because bruteforce %s for %q failed: %v\n", multiColorBitmap, mixedCharset, img.sourceFilename, err)
img.graphicsType = multiColorBitmap
img.findBackgroundColorCandidates(false)
if err = img.findBackgroundColor(); err != nil {
return 0, fmt.Errorf("img.findBackgroundColor %q failed: %w", img.sourceFilename, err)