-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.cpp
1610 lines (1421 loc) · 41.3 KB
/
main.cpp
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
// Convert an image to a TI compatible image
//
#define _WIN32_IE 0x0400
#include "stdafx.h"
#include <windows.h>
#include <wininet.h>
#include <shlobj.h>
#include <time.h>
#include <stdio.h>
#include <crtdbg.h>
#include "tipicview.h"
#include "D:\WORK\imgsource\4.0\islibs40_vs17_unicode\ISource.h"
#include "2passscale.h"
#include "TIPicViewDlg.h"
bool StretchHist;
void MYRGBTo8BitDithered(BYTE *pRGB, BYTE *p8Bit, MYRGBQUAD *mainpal, double dark);
#define MAXFILES 500000
int pixeloffset;
int heightoffset;
wchar_t szFiles[MAXFILES][256];
wchar_t *pTmp;
int iCnt, n, ret, errCount;
unsigned int idx1, idx2;
int ScaleMode;
wchar_t szFolder[256];
wchar_t szBuf[256];
unsigned int iWidth, iHeight;
unsigned int inWidth, inHeight;
unsigned int outWidth, outHeight;
unsigned int finalW, finalH;
int currentx;
int currenty;
int currentw;
int currenth;
int maxerrorcount;
HISSRC hSource, hDest;
HGLOBAL hBuffer, hBuffer2;
unsigned char buf8[256*192];
RGBQUAD winpal[256];
bool fFirstLoad=false;
bool fRand;
bool fVerbose = false;
extern int g_orderSlide;
extern int g_ctrlList;
extern int g_nFilter;
extern int g_PowerPaint;
extern int g_nPortraitMode;
extern int g_UsePerLinePalette;
extern int g_UseColorOnly;
extern int g_MatchColors;
extern double g_PercepR, g_PercepG, g_PercepB;
extern double g_LumaEmphasis;
extern double g_Gamma;
extern int g_Perceptual;
extern int g_Cartoon;
extern int g_UsePalette;
extern int g_GreyPalette;
extern int g_UseHalfMulticolor;
extern int g_MaxMultiDiff;
extern int g_MaxColDiff;
extern int g_OrderedDither;
extern int g_MapSize;
extern wchar_t *cmdFileIn; // from command line, makes a non-GUI mode
extern wchar_t *cmdFileOut;
extern HGLOBAL load_gif(wchar_t *filename, unsigned int *iWidth, unsigned int *iHeight);
MYRGBQUAD mainpal[256];
extern LPVOID pSharedPointer;
extern wchar_t szLastFilename[256]; // used to make sure we don't reload our own shared file
int instr(unsigned short *, char*);
bool ScalePic(int nFilter, int nPortraitMode);
void BuildFileList(wchar_t *szFolder);
BOOL ResizeRGBBiCubic(BYTE *pImgSrc, UINT32 uSrcWidthPix, UINT32 uSrcHeight, BYTE *pImgDest, UINT32 uDestWidthPix, UINT32 uDestHeight);
// BIG NOTE! WHITE IS INSERTED AS COLOR 0, and TRANSPARENT IS NOT PRESENT
// Furthermore, GREY is color 2! So, White, Black, Grey.
// This needs to be corrected when outputting the data.
MYRGBQUAD palinit16[256] = {
#if 0
// RacconLad's MSX palette from his flash games
226,226,226,0,
0,0,0,0,
161,161,161,0,
32,194,32,0,
97,226,97,0,
32,32,226,0,
64,97,226,0,
161,32,32,0,
64,194,226,0,
226,32,32,0,
226,97,97,0,
194,194,32,0,
194,194,129,0,
32,129,32,0,
194,64,161,0,
#elif 0
// calculated palette from datasheet
255,255,255,0,
0,0,0,0,
204,204,204,0,
71,183,59,0,
124,207,111,0,
93,78,255,0,
128,114,255,0,
182,98,71,0,
93,200,237,0,
215,107,72,0,
251,143,108,0,
195,205,65,0,
211,218,118,0,
62,159,47,0,
182,100,199,0,
#elif 0
// warmer palette measured from adam by http://junior.apk.net/~drushel/pub/coleco/twwmca/wk961201.html
// I have reason to think that the TI's palette is even darker. The output stages would
// change the video slightly, so the raw datasheet values are not necessarily right.
191,207,175,0,
0,16,0,0,
159,160,143,0,
16,191,0,0,
64,192,32,0,
64,63,255,0,
96,95,255,0,
160,80,16,0,
47,192,208,0,
207,79,15,0,
224,111,32,0,
160,175,0,0,
175,175,31,0,
16,144,0,0,
159,79,160,0,
#elif 0
// Classic99 palette - scaled to fill 0-255 fully 3% difference from unscaled
255, 255, 255, 0,
0, 0, 0, 0,
206, 206, 206, 0,
33, 206, 66, 0,
90, 222, 123, 0,
82, 82, 239, 0,
123, 115, 255, 0,
214, 82, 74, 0,
66, 239, 247, 0,
255, 82, 82, 0,
255, 123, 123, 0,
214, 198, 82, 0,
231, 206, 132, 0,
33, 181, 57, 0,
206, 90, 189, 0,
#else
// classic99 palette <-------- this one, normally
248, 248, 248, 0,
0, 0, 0, 0,
200, 200, 200, 0,
32, 200, 64, 0,
88, 216, 120, 0,
80, 80, 232, 0,
120, 112, 248, 0,
208, 80, 72, 0,
64, 232, 240, 0,
248, 80, 80, 0,
248, 120, 120, 0,
208, 192, 80, 0,
224, 200, 128, 0,
32, 176, 56, 0,
200, 88, 184, 0,
#endif
};
// remembers the default palette for the settings file
MYRGBQUAD defaultpalinit16[16];
// ordered dither threshold maps
// 3 and 8 didn't look very good due to color clash
double g_thresholdMap2x2[2][2] = {
0, 2,
3, 1
};
double g_thresholdMap4x4[4][4] = {
0, 8, 2, 10,
12, 4, 14, 6,
3, 11, 1, 9,
15, 7, 13, 5
};
unsigned char orig8[256*192];
CWnd *pWnd;
// simple wrapper for debug - command line mode is normally quiet unless verbose is set
void debug(wchar_t *s, ...) {
if ((cmdFileIn == NULL) || (fVerbose)) {
wchar_t buf[1024];
_vsnwprintf(buf, 1023, s, (char*)((&s)+1));
buf[1023]='\0';
OutputDebugString(buf);
printf("%S",buf);
}
}
// pBuf has the pattern table at 0, and the color table at 6144
// Memory is returned, or NULL
HGLOBAL ParsePixelData(unsigned char *pBuf, int palSize) {
unsigned char *pOut, *p8Out;
// now parse it up to 24 bit
HGLOBAL hGlob = GlobalAlloc(GPTR, 256*192*3);
if (NULL == hGlob) {
free(pBuf);
return NULL;
}
pOut=(unsigned char*)hGlob; // gives us the 24-bit source
p8Out=buf8; // and just copy the original into here too (TODO: might not work for palettes...)
for (int row=0; row<24; row++) {
for (int line=0; line<8; line++) {
for (int col=0; col<32; col++) {
int offset=(row*32+col)*8+line;
if (palSize == 0) {
int fg=((*(pBuf+6144+offset))>>4)&0x0f;
// remap white and grey from TI colors to internal colors, make transparent black
if (fg == 0) {
fg = 1 ;
} else if (fg == 15) {
fg=0;
} else if (fg == 14) {
fg=2;
} else if (fg > 1) {
fg++;
}
int bg=((*(pBuf+6144+offset)))&0x0f;
// remap white and grey from TI colors to internal colors, make transparent black
if (bg == 0) {
bg = 1 ;
} else if (bg == 15) {
bg=0;
} else if (bg == 14) {
bg=2;
} else if (bg > 1) {
bg++;
}
int pix=*(pBuf+offset);
// now we have 8 pixels
int bit=0x80;
for (int cnt=0; cnt<8; cnt++) {
if (pix&bit) {
*(pOut++)=palinit16[fg].rgbRed;
*(pOut++)=palinit16[fg].rgbGreen;
*(pOut++)=palinit16[fg].rgbBlue;
*(p8Out++)=fg;
} else {
*(pOut++)=palinit16[bg].rgbRed;
*(pOut++)=palinit16[bg].rgbGreen;
*(pOut++)=palinit16[bg].rgbBlue;
*(p8Out++)=bg;
}
bit>>=1;
}
} else {
// almost the same, but with custom colors
MYRGBQUAD FG;
MYRGBQUAD BG;
int fg=((*(pBuf+6144+offset))>>4)&0x0f;
int bg=((*(pBuf+6144+offset)))&0x0f;
int rowoff = palSize == 32 ? 0 : ((row*8)+line)*32;
FG.rgbRed = ((*(pBuf+6144*2+fg*2+rowoff))&0x0f)<<4;
FG.rgbGreen = ((*(pBuf+6144*2+fg*2+rowoff+1))&0xf0);
FG.rgbBlue = ((*(pBuf+6144*2+fg*2+rowoff+1))&0x0f)<<4;
BG.rgbRed = ((*(pBuf+6144*2+bg*2+rowoff))&0x0f)<<4;
BG.rgbGreen = ((*(pBuf+6144*2+bg*2+rowoff+1))&0xf0);
BG.rgbBlue = ((*(pBuf+6144*2+bg*2+rowoff+1))&0x0f)<<4;
int pix=*(pBuf+offset);
// now we have 8 pixels
int bit=0x80;
for (int cnt=0; cnt<8; cnt++) {
if (pix&bit) {
*(pOut++)=FG.rgbRed;
*(pOut++)=FG.rgbGreen;
*(pOut++)=FG.rgbBlue;
*(p8Out++)=fg;
} else {
*(pOut++)=BG.rgbRed;
*(pOut++)=BG.rgbGreen;
*(pOut++)=BG.rgbBlue;
*(p8Out++)=bg;
}
bit>>=1;
}
}
}
}
}
if (palSize > 0) {
memcpy(buf8, "NOT-TI-PIC", 10);
}
return hGlob;
}
// read a TI Artist into a 24-bit color buffer :)
// use palinit16[] about (remember only 15 colors there)
// We know the filename must end with .TIA[P|C] or _[P|C]
// TODO: can't load half-multicolor today...
// TODO: when loading scanline palette images, the re-converted image shifts.
// This means we aren't handling the palette right during conversion, probably.
HGLOBAL ReadTIArtist(CString csFile) {
HGLOBAL hGlob=NULL;
unsigned char identifier[128];
unsigned char *pBuf;
bool bHeader=true;
bool bRLE=false;
// first, check if it really is a TI Artist file
// make sure we are trying for the _P file first
if (csFile.Right(1).MakeUpper() == 'M') {
csFile=csFile.Left(csFile.GetLength()-1);
csFile+='P';
}
if (csFile.Right(1).MakeUpper() == 'C') {
csFile=csFile.Left(csFile.GetLength()-1);
csFile+='P';
}
FILE *fp=NULL;
_wfopen_s(&fp, csFile, _T("rb"));
if (NULL == fp) {
printf("Can't open %S\n", (LPCWSTR)csFile);
return NULL;
}
memset(identifier, 0, 128);
fread(identifier, 1, 128, fp);
// check header
if ((identifier[0]=='\x7') &&
(identifier[1]=='T') &&
(identifier[2]=='I') &&
(identifier[3]=='F') &&
(identifier[4]=='I') &&
(identifier[5]=='L') &&
(identifier[6]=='E') &&
(identifier[7]=='S') && // tag
(((identifier[10])&0x07)==1) && // PROGRAM (ignore protection)
(identifier[8]==0) && // size in sectors (6144 byte file)
(identifier[9]==0x18)) {
goto test2; // just to indicate okay, we don't read the header again after this
};
// v9t9 detection - kind of weak...
if ((isprint(identifier[0])) &&
(isprint(identifier[1]) || isspace(identifier[1])) &&
(isprint(identifier[2]) || isspace(identifier[2])) &&
(isprint(identifier[3]) || isspace(identifier[3])) &&
(isprint(identifier[4]) || isspace(identifier[4])) &&
(isprint(identifier[5]) || isspace(identifier[5])) &&
(isprint(identifier[6]) || isspace(identifier[6])) &&
(isprint(identifier[7]) || isspace(identifier[7])) &&
(isprint(identifier[8]) || isspace(identifier[8])) &&
(isprint(identifier[9]) || isspace(identifier[9])) && // filename
(((identifier[12])&0x07)==1) && // PROGRAM (ignore protection)
(identifier[14]==0) && // size in sectors (6144 byte file)
(identifier[15]==0x18)) {
goto test2; // just to indicate okay, we don't read the header again after this
}
// not a valid header - hold control to assume it's a raw file
if (0 == (GetAsyncKeyState(VK_CONTROL) & 0x8000)) {
printf("No TIFILES or V9T9 header - hold CONTROL to load a RAW file\n");
fclose(fp);
return NULL;
}
// else, fseek back since the header doesn't exist
printf("Holding CONTROL overrides lack of header.\n");
fseek(fp, 0, SEEK_SET);
bHeader=false;
test2:
pBuf=(unsigned char*)malloc(6144*3);
if (NULL == pBuf) {
printf("Can't allocate temporary buffer\n");
fclose(fp);
return NULL;
}
// allow for max size of a scanline-palette image
memset(pBuf, 0, 6144*3);
if (GetAsyncKeyState(VK_MENU) & 0x8000) {
printf("TI Artist file - Holding ALT assumes RLE encoding.\n");
bRLE=true;
// read as RLE
int p=0;
while ((!feof(fp)) && (p < 6144)) {
int x=fgetc(fp);
if (x&0x80) {
int y=fgetc(fp);
x&=0x7f;
while ((p<6144)&&((x--)>0)) {
pBuf[p++]=y;
}
} else {
while ((p<6144)&&((x--)>0)) {
pBuf[p++]=fgetc(fp);
}
}
}
} else {
printf("TI Artist file - hold ALT to assume RLE file\n");
// just read
fread(pBuf, 1, 6144, fp);
}
fclose(fp);
csFile=csFile.Left(csFile.GetLength()-1);
csFile+='C';
fp=NULL;
_wfopen_s(&fp, csFile, _T("rb"));
if (NULL == fp) {
printf("Can't open %S (mono file assumed)\n", (LPCWSTR)csFile);
memset(pBuf+6144, 0x1f, 6144);
} else {
// just assume the _c is the same as the _p
if (bHeader) {
fread(identifier, 1, 128, fp);
}
if (bRLE) {
// read as RLE
int p=0;
while ((!feof(fp)) && (p < 6144)) {
int x=fgetc(fp);
if (x&0x80) {
int y=fgetc(fp);
x&=0x7f;
while ((p<6144)&&((x--)>0)) {
pBuf[(p++)+6144]=y;
}
} else {
while ((p<6144)&&((x--)>0)) {
pBuf[(p++)+6144]=fgetc(fp);
}
}
}
} else {
// just read
fread(pBuf+6144, 1, 6144, fp);
}
fclose(fp);
}
// check for palette file
int palSize = 0;
csFile=csFile.Left(csFile.GetLength()-1);
csFile+='M';
fp=NULL;
_wfopen_s(&fp, csFile, _T("rb"));
if (NULL == fp) {
printf("Can't open %S (non-extended file assumed)\n", (LPCWSTR)csFile);
memset(pBuf+6144*2, 0, 6144);
} else {
// just assume the _c is the same as the _p
if (bHeader) {
fread(identifier, 1, 128, fp);
}
// if (bRLE) {
// // this is probably a bug, but at the moment palette files
// // are not compressed, even the big ones! ;)
// }
// just read - palette size indicates the type of image
// 6144 - scanline palette - 192 lines of 16 palette entries, each entry 16 bits (12 bits padded)
// 2048 - half multicolor - staggered multicolor PDT, see docs
// 32 - paletted bitmap - 16 palette entries, each 16 bits (12 bits padded)
palSize = fread(pBuf+6144*2, 1, 6144, fp);
fclose(fp);
}
// not supporting half-multicolor atm, that's a bigger parse)
if ((palSize != 0) && (palSize != 6144) && (palSize != 32)) {
printf("Unsupported palette type - ignoring\n");
palSize = 0;
}
hGlob = ParsePixelData(pBuf, palSize);
free(pBuf);
return hGlob;
}
// read an MSX SC2 TI Artist into a 24-bit color buffer :)
// use palinit16[] about (remember only 15 colors there)
HGLOBAL ReadSC2(CString csFile) {
HGLOBAL hGlob=NULL;
unsigned char *pBuf;
FILE *fp=NULL;
_wfopen_s(&fp, csFile, _T("rb"));
if (NULL == fp) {
printf("Can't open %S\n", (LPCWSTR)csFile);
return NULL;
}
pBuf=(unsigned char*)malloc(6144*3);
if (NULL == pBuf) {
printf("Can't allocate temporary buffer\n");
fclose(fp);
return NULL;
}
// allow for max size of a scanline-palette image
memset(pBuf, 0, 6144*3);
// set pointer to pattern table
fseek(fp, 7, SEEK_SET);
fread(pBuf, 1, 6144, fp);
// set pointer to color table
fseek(fp, 0x2007, SEEK_SET);
fread(pBuf+6144, 1, 6144, fp);
// all done
fclose(fp);
// no palette file associated
int palSize = 0;
hGlob = ParsePixelData(pBuf, palSize);
free(pBuf);
return hGlob;
}
// read a Coleco PP file
// use palinit16[] about (remember only 15 colors there)
HGLOBAL ReadPP(CString csFile) {
HGLOBAL hGlob=NULL;
unsigned char *pBuf;
FILE *fp=NULL;
_wfopen_s(&fp, csFile, _T("rb"));
if (NULL == fp) {
printf("Can't open %S\n", (LPCWSTR)csFile);
return NULL;
}
pBuf=(unsigned char*)malloc(6144*3);
if (NULL == pBuf) {
printf("Can't allocate temporary buffer\n");
fclose(fp);
return NULL;
}
// allow for max size of a scanline-palette image
memset(pBuf, 0, 6144*3);
memset(pBuf+6144, 0xf1, 6144); // default color table
// set pointer to pattern table
fseek(fp, 0, SEEK_SET);
fread(pBuf, 1, 0x1400, fp);
// set pointer to color table
fseek(fp, 0x1400, SEEK_SET);
fread(pBuf+6144, 1, 0x1400, fp);
// all done
fclose(fp);
// no palette file associated
int palSize = 0;
hGlob = ParsePixelData(pBuf, palSize);
free(pBuf);
return hGlob;
}
// read a Coleco PC file
// use palinit16[] about (remember only 15 colors there)
HGLOBAL ReadPC(CString csFile) {
HGLOBAL hGlob=NULL;
unsigned char *pBuf;
FILE *fp=NULL;
_wfopen_s(&fp, csFile, _T("rb"));
if (NULL == fp) {
printf("Can't open %S\n", (LPCWSTR)csFile);
return NULL;
}
pBuf=(unsigned char*)malloc(6144*3);
if (NULL == pBuf) {
printf("Can't allocate temporary buffer\n");
fclose(fp);
return NULL;
}
// allow for max size of a scanline-palette image
memset(pBuf, 0, 6144*3);
memset(pBuf+6144, 0xf1, 6144); // default color table
// set pointer to pattern table
fseek(fp, 0, SEEK_SET);
fread(pBuf, 1, 0x1800, fp);
// set pointer to color table
fseek(fp, 0x1800, SEEK_SET);
fread(pBuf+6144, 1, 0x1800, fp);
// all done
fclose(fp);
// no palette file associated
int palSize = 0;
hGlob = ParsePixelData(pBuf, palSize);
free(pBuf);
return hGlob;
}
// read a Coleco HGR file
// use palinit16[] about (remember only 15 colors there)
HGLOBAL ReadHGR(CString csFile) {
HGLOBAL hGlob=NULL;
unsigned char *pBuf;
FILE *fp=NULL;
_wfopen_s(&fp, csFile, _T("rb"));
if (NULL == fp) {
printf("Can't open %S\n", (LPCWSTR)csFile);
return NULL;
}
pBuf=(unsigned char*)malloc(6144*3);
if (NULL == pBuf) {
printf("Can't allocate temporary buffer\n");
fclose(fp);
return NULL;
}
// allow for max size of a scanline-palette image
memset(pBuf, 0, 6144*3);
memset(pBuf+6144, 0xf1, 6144); // default color table
// set pointer to pattern table
fseek(fp, 0x1415, SEEK_SET);
fread(pBuf, 1, 0x1400, fp);
// set pointer to color table
fseek(fp, 0x15, SEEK_SET);
fread(pBuf+6144, 1, 0x1400, fp);
// all done
fclose(fp);
// no palette file associated
int palSize = 0;
hGlob = ParsePixelData(pBuf, palSize);
free(pBuf);
return hGlob;
}
// handles invalid arguments to strcpy_s and strcat_s, etc
void app_handler(const wchar_t * expression,
const wchar_t * function,
const wchar_t * file,
unsigned int line,
uintptr_t pReserved) {
printf("Warning: path or string too long. Skipping.\n");
}
// using mainpal and a list of indexes, do a restricted search for closest color
// no need for perceptual matching here, we already chose the color and are
// really just checking for which brightness is closer
int mapRGB(int r, int g, int b, int *lst, int cnt) {
double mindist = ((255*255)+(255*255)+(255*255));
int best = 0;
for (int i2=0; i2<cnt; i2++) {
int col = lst[i2];
int rd = r-mainpal[col].rgbRed;
int gd = g-mainpal[col].rgbGreen;
int bd = b-mainpal[col].rgbBlue;
double dist = (rd*rd)+(gd*gd)+(bd*bd);
if (dist < mindist) {
mindist = dist;
best = col;
}
}
return best;
}
enum {
CRED,CGREEN,CBLUE,CMAGENTA,CYELLOW,CCYAN,CGREY
};
// returns the closest index in mainpal[] that matches the assumed intent of this color
// rgb must be 0-255. Return will be 0-14.
// The palette order is mixed from the default (first 3):
// 0- white, 1- black, 2- grey, 3- med green,
// 4- lt green, 5- dk blue, 6- lt blue, 7- dk red,
// 8- cyan, 9- med red 10- lt red, 11- dk yellow,
// 12- lt yellow, 13- dk green 14- magenta
int getCartoonColor(int r, int g, int b) {
// first, calculate what color we think this is. Math determined by hand
// and verified with fixed and random samples - it's close enough.
int maxscore = 0, maxtype = CGREY;
int out = 1;
int score, mscore, yscore, cscore;
// the scoring is fairly basic, but seems to work
score = r*2-g-b; if (score > maxscore) { maxscore = score; maxtype = CRED; }
score = g*2-r-b; if (score > maxscore) { maxscore = score; maxtype = CGREEN; }
score = b*2-r-g; if (score > maxscore) { maxscore = score; maxtype = CBLUE; }
mscore = (r+b)-g; if (mscore > maxscore) { maxscore = mscore; maxtype = CMAGENTA; }
cscore = (g+b)-r; if (cscore > maxscore) { maxscore = cscore; maxtype = CCYAN; }
yscore = (r+g)-b; if (yscore > maxscore) { maxscore = yscore; maxtype = CYELLOW; }
// grey tends to score high on m,c and y, so use those
score = yscore*2-abs(yscore-mscore)-abs(yscore-cscore); if (score >= maxscore) { maxscore = score; maxtype = CGREY; }
switch (maxtype) {
case CRED: { int lst[] = {7,9,10}; out=mapRGB(r,g,b, lst, 3); break; }
case CGREEN: { int lst[] = {13,3,4}; out=mapRGB(r,g,b, lst, 3); break; }
case CBLUE: { int lst[] = {5,6}; out=mapRGB(r,g,b, lst, 2); break; }
case CMAGENTA: { out=14; break; }
case CCYAN: { out=8; break; }
case CYELLOW: { int lst[] = {11,12}; out=mapRGB(r,g,b, lst, 2); break; }
case CGREY: { int lst[] = {1,2,0}; out=mapRGB(r,g,b, lst, 3); break; }
// no default - cover all cases
}
return out;
}
// Mode 0 - pass in a path, random image from that path
// Mode 1 - reload image - if pFile is NULL, use last from list, else use passed file
// Mode 2 - load specific image and remember it
// 'dark' is a value from 0-16 and is the amount to darken for ordered dither
void maincode(int mode, CString pFile, double dark)
{
// initialize
bool fArgsOK=true;
static bool fHaveFiles=false;
static bool initialized=false;
wchar_t szFileName[256];
static int nlastpick=-1;
int noldlast;
wchar_t szOldFN[256];
if (!initialized) {
IS40_Initialize("{887916EA-FAE3-12E2-19C1-8B0FC40F045F}"); // please do not reuse this key in other applications
srand((unsigned)time(NULL));
initialized=true;
pWnd=AfxGetMainWnd();
// I build this on the assumption that the _s string functions would just
// truncate and move on on long strings. that's untrue - they assert and fatal.
// We can override that for now like this:
#ifdef _DEBUG
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
#else
_CrtSetReportMode(_CRT_ASSERT, 0);
#endif
_set_invalid_parameter_handler(app_handler);
// TODO: I really have paths this long. I should fix this.
// update threshold maps - they're supposed to be fractional
for (int i1=0; i1<2; i1++) {
for (int i2=0; i2<2; i2++) {
g_thresholdMap2x2[i1][i2] /= (double)(4.0);
}
}
for (int i1=0; i1<4; i1++) {
for (int i2=0; i2<4; i2++) {
g_thresholdMap4x4[i1][i2] /= (double)(16.0);
}
}
}
if (mode == 0) {
// Set defaults
wcscpy_s(szFolder, 256, pFile);
}
iWidth=256;
iHeight=192;
if (g_PowerPaint) {
// fix sizes for scaling, we'll patch it up before we exit
iWidth = 240;
iHeight = 160;
}
fRand=false;
maxerrorcount=6;
if (mode == 0) {
if ((!fHaveFiles)&&(pFile.GetLength() > 0)) {
// get list of files
iCnt=0;
BuildFileList(szFolder);
printf("\n%d files found.\n", iCnt);
if (0==iCnt) {
printf("That's an error\n");
AfxMessageBox(_T("The 'rnd' function currently only works if you have a c:\\pics folder."));
return;
}
fHaveFiles=true;
}
}
// Used to fit the image into the remaining space
currentx=0;
currenty=0;
currentw=iWidth;
currenth=iHeight;
hBuffer2=NULL;
noldlast=nlastpick;
if (noldlast != -1) {
wcscpy_s(szOldFN, 256, szFiles[nlastpick]);
}
bool bIsTIArtist=false;
{
int cntdown;
errCount=0;
ScaleMode=-1;
// randomly choose one
tryagain:
bIsTIArtist=false;
hBuffer = NULL;
if (mode & 0x1000) {
// this means to generate a solid 12-bit color
hBuffer = GlobalAlloc(GPTR, 256*192*3);
if (NULL == hBuffer) {
printf("Failed to allocate memory for solid image.\n");
return;
}
for (int idx = 0; idx< 256*192*3; idx+=3) {
*((unsigned char*)hBuffer+idx) = ((mode&0xf00)>>8)|((mode&0xf00)>>4);
*((unsigned char*)hBuffer+idx+1) = ((mode&0xf0)>>4)|((mode&0xf0));
*((unsigned char*)hBuffer+idx+2) = ((mode&0xf)<<4)|((mode&0xf));
}
n=MAXFILES-1;
swprintf_s(szFiles[n], _T("RGB_0x%04X"), mode);
inWidth=256;
inHeight=192;
} else if ((1 == mode) || (2 == mode)) {
if ((pFile.IsEmpty()) && (-1 != nlastpick)) {
n=nlastpick;
} else {
if (pFile.IsEmpty()) {
return;
}
n=MAXFILES-1;
wcscpy_s(szFiles[n], 256, pFile);
}
} else {
if (nlastpick!=-1) {
wcscpy_s(szFiles[nlastpick],256, _T("")); // so we don't choose it again
}
pixeloffset=0;
heightoffset=0;
errCount++;
if (errCount>6) {
printf("Too many errors - stopping.\n");
if (noldlast != -1) {
wcscpy_s(szFiles[noldlast], 256, szOldFN);
nlastpick=noldlast;
}
return;
}
n=((rand()<<16)|rand())%iCnt;
cntdown=iCnt;
while (wcslen(szFiles[n]) == 0) {
n++;
if (n>=iCnt) n=0;
cntdown--;
if (cntdown == 0) {
printf("Ran out of images in the list, aborting.\n");
if (noldlast != -1) {
wcscpy_s(szFiles[noldlast], 256, szOldFN);
nlastpick=noldlast;
}
return;
}
}
}
wprintf(L"Chose #%d: %s\n", n, &szFiles[n][0]);
wcscpy_s(szFileName, 256, szFiles[n]);
nlastpick=n;
if (NULL != hBuffer) {
goto ohJustSkipTheLoad;
}
// dump the data into the shared memory, if available (and not from there)
wcsncpy(szLastFilename, szFileName, 255); // save the name locally first so we can compare
if ((pSharedPointer)&&((mode == 0)||(mode==2))) {
// we copy the first byte last to ensure it's atomic
memcpy((char*)pSharedPointer+sizeof(szFileName[0]), szFileName+1, sizeof(szFileName));
InterlockedExchange((volatile LONG*)pSharedPointer, *((LONG*)szFileName)); // actually writes 32-bits, but guaranteed execution across cores
}
// open the file
hSource=IS40_OpenFileSource(szFileName);
if (NULL==hSource) {
printf("Can't open image file.\n");
return;
}
// guess filetype
ret=IS40_GuessFileType(hSource);
IS40_Seek(hSource, 0, 0);
switch (ret)
{
case 1: //bmp
hBuffer=IS40_ReadBMP(hSource, &inWidth, &inHeight, 24, NULL, 0);
break;
case 2: //gif
IS40_CloseSource(hSource);
hSource=NULL;
hBuffer=load_gif(szFileName, &inWidth, &inHeight);
break;
case 3: //jpg
hBuffer=IS40_ReadJPG(hSource, &inWidth, &inHeight, 24, 0);
break;
case 4: //png
hBuffer=IS40_ReadPNG(hSource, &inWidth, &inHeight, 24, NULL, 0);
break;
case 5: //pcx
hBuffer=IS40_ReadPCX(hSource, &inWidth, &inHeight, 24, NULL, 0);
break;
case 6: //tif
hBuffer=IS40_ReadTIFF(hSource, &inWidth, &inHeight, 24, NULL, 0, 0);
break;
default:
hBuffer=NULL;
// is it TI Artist?
// TODO: load Coleco PC and PP files too
{
CString csTmp=szFileName;
if ((csTmp.Right(5).CompareNoCase(_T(".TIAP")) == 0) ||
(csTmp.Right(2).CompareNoCase(_T("_P")) == 0) ||
(csTmp.Right(5).CompareNoCase(_T(".TIAC")) == 0) ||
(csTmp.Right(2).CompareNoCase(_T("_C")) == 0) ||
(csTmp.Right(5).CompareNoCase(_T(".TIAM")) == 0) ||
(csTmp.Right(2).CompareNoCase(_T("_M")) == 0)) {
// might be! try it!
IS40_CloseSource(hSource);
hSource=NULL;
hBuffer=ReadTIArtist(csTmp);
inWidth=256;
inHeight=192;
}
if (csTmp.Right(4).CompareNoCase(_T(".SC2")) == 0) {
IS40_CloseSource(hSource);
hSource=NULL;
hBuffer=ReadSC2(csTmp);
inWidth=256;
inHeight=192;
}
if (csTmp.Right(3).CompareNoCase(_T(".PP")) == 0) {
IS40_CloseSource(hSource);
hSource=NULL;
hBuffer=ReadPP(csTmp);
inWidth=256;
inHeight=192;
}
if (csTmp.Right(3).CompareNoCase(_T(".PC")) == 0) {
IS40_CloseSource(hSource);
hSource=NULL;
hBuffer=ReadPC(csTmp);
inWidth=256;
inHeight=192;
}