From ea4ec101150b3e4d83e4db2612821a95bef73d19 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 30 Sep 2026 05:46:33 +0000 Subject: [PATCH 1/7] docs: update progress [skip ci] --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 99fd18b5..fe725570 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 88.96% | 79.07% | 56.92% | 88.24% | +| 88.96% | 79.07% | 56.95% | 88.24% | -units 752/1027 complete, functions 11492/12563 matched. +units 758/1027 complete, functions 11493/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data -- 2.49.1 From 9ea683dd613b793b1f01d50c55fba41463e77908 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:54:06 -0500 Subject: [PATCH 2/7] eZiText: zi8match, zi8getc2, zikorean, zi8dawg (worker 1f628177) (#338) --- README.md | 4 +- libs/RVLMiddleware/eZiText/src/clib/zi8dawg.c | 430 +++++++++ .../RVLMiddleware/eZiText/src/clib/zi8getc2.c | 735 +++++++++++++++ .../RVLMiddleware/eZiText/src/clib/zi8match.c | 876 ++++++++++++++++++ .../RVLMiddleware/eZiText/src/clib/zikorean.c | 423 +++++++++ tools/decomp-assist/zi8dawg.attempts.md | 33 + tools/decomp-assist/zi8getc2.attempts.md | 46 + tools/decomp-assist/zi8match.attempts.md | 25 + tools/decomp-assist/zikorean.attempts.md | 10 + 9 files changed, 2580 insertions(+), 2 deletions(-) create mode 100644 libs/RVLMiddleware/eZiText/src/clib/zi8dawg.c create mode 100644 libs/RVLMiddleware/eZiText/src/clib/zi8getc2.c create mode 100644 libs/RVLMiddleware/eZiText/src/clib/zi8match.c create mode 100644 libs/RVLMiddleware/eZiText/src/clib/zikorean.c create mode 100644 tools/decomp-assist/zi8dawg.attempts.md create mode 100644 tools/decomp-assist/zi8getc2.attempts.md create mode 100644 tools/decomp-assist/zi8match.attempts.md create mode 100644 tools/decomp-assist/zikorean.attempts.md diff --git a/README.md b/README.md index fe725570..1356447f 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 88.96% | 79.07% | 56.95% | 88.24% | +| 89.61% | 79.32% | 56.95% | 88.27% | -units 758/1027 complete, functions 11493/12563 matched. +units 758/1027 complete, functions 11514/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/libs/RVLMiddleware/eZiText/src/clib/zi8dawg.c b/libs/RVLMiddleware/eZiText/src/clib/zi8dawg.c new file mode 100644 index 00000000..d00aa87f --- /dev/null +++ b/libs/RVLMiddleware/eZiText/src/clib/zi8dawg.c @@ -0,0 +1,430 @@ +#include +#include +#include + +ziU32 Zi8GetTableSize(ziU8 language, ziU8 table, ziPtr work); +ziU32 Zi8GetTableAddress(ziU8 language, ziU8 table, ziPtr work); +ziU16 Zi8GetTableCount(ziU8 language, ziU8 table, ziPtr work); +ziU8* ZiDAWGGetGraph(zi8DawgCtx* context); +ziU8* ZiDAWGGetGraphInfo(zi8DawgCtx* context, ziU8* table, ziS16* keys); +ziU32 ZiDAWGgetCHARattribute(zi8DawgCtx* context, ziU8* graph, ziPtr work); +ziU8 ZiDAWGgetEOWattribute(ziU8* graph); +ziU8* ZiDAWGGetChild(ziU8* graph); +ziU8* ZiDAWGGetSibling(ziU8* graph); + +ziU32 Zi8MatchROMdata0(ziWChar* elements, ziU32 count, ziU8 language, + ziWChar* output, ziU16 capacity, ziU8 mode, ziU8 status, + ziU8 graphTable, ziU8 keyTable, ziU8 acceptPrefix, + ziU8* prefixLength, zi8DawgCtx* context, ziU8* search, + ziPtr __zi8_work_data) { + ziBool searching; + ziS32 tableSize; + ziU8* graph; + ziS16 key; + ziU8 endOfWord; + zi8DawgRec* current; + ziU16 index; + ziU16 depth; + zi8DawgRec* records = context->recs; + ziU8 result = 0; + ziU32 keyCount; + ziU8* table; + ziS16 keys[3]; + + if (language != context->lang || graphTable != context->key) { + records[0].key = 0; + } + if ((ziU8)count != 1 || mode == 0 || graphTable != 0xe) { + if (status != 0) { + if (records[context->cnt - 1].node == (ziU8*)context->unk_0x338) goto finish_graph; + for (index = 0; (ziU16)index < (ziU8)count; index++) { + if (records[(ziU16)index].key != elements[(ziU16)index] && + (records[(ziU16)index].attr & 0xffff) != elements[(ziU16)index]) goto finish_graph; + } + if (mode == 1) acceptPrefix = 0; + } else { + if (ZI_WORK->unk_0x141E == 0 || graphTable != 0xc || + (tableSize = Zi8GetTableSize(language, ZI_WORK->unk_0x141E, ZI_WORK)) == 0) { + tableSize = Zi8GetTableSize(language, graphTable, ZI_WORK); + if (tableSize == 0) { + Zi8LogError(0x961, ZI_WORK); + goto finish_graph; + } + table = (ziU8*)Zi8GetTableAddress(language, graphTable, ZI_WORK); + } else { + table = (ziU8*)Zi8GetTableAddress(language, ZI_WORK->unk_0x141E, ZI_WORK); + keyTable = ZI_WORK->unk_0x141E + 1; + } + context->table = table; + context->cap = (((ziU16)context->table[2] << 8) + (ziU16)context->table[3]) / 3; + context->p08 = context->table + 4; + context->p0C = context->table + context->cap * 2 + 4; + context->lang = language; + context->key = graphTable; + index = 0; + while ((ziU16)index < (ziU8)count && records[(ziU16)index].key == elements[(ziU16)index]) { + index++; + } + if ((ziU16)index < 2) { + key = Zi8GetTableSize(language, keyTable, ZI_WORK); + if (key == 0 || ZI_WORK->userKeys[language] != 0) { + graph = ZiDAWGGetGraph(context); + records[0].node = graph; + context->unk_0x338 = 0; + context->p14 = 0; + } else { + index = 0; + while (1) { + if ((ziU8)count < 2) keyCount = (ziU8)count; + else keyCount = 2; + if (keyCount <= (ziU16)index) break; + key = Zi8ConvertWC2Key(elements[(ziU16)index], language, ZI_WORK); + keys[(ziU16)index] = key; + if (keys[(ziU16)index] == 0) keys[(ziU16)index] = elements[(ziU16)index]; + index++; + } + keys[(ziU16)index] = 0; + table = (ziU8*)Zi8GetTableAddress(language, keyTable, ZI_WORK); + context->p14 = table + 2; + records[0].node = ZiDAWGGetGraphInfo(context, table + context->cap * 2 + 2, keys); + } + records[0].key = 0; + if (records[0].node == 0) goto finish_graph; + } else { + records[0].node = records[(ziU16)index - 1].back; + } + context->cnt = 1; + search[1] = count; + search[0] = 0; + if (mode == 1) { + search[0] = 1; + acceptPrefix = 0; + } else if (mode == 0 && acceptPrefix == 0) { + search[1]++; + } + } + searching = 1; + depth = context->cnt; + while ((current = &records[depth - 1], searching) && context->cnt != 0 && + current->node != (ziU8*)context->unk_0x338 && context->cnt <= capacity) { + current->attr = ZiDAWGgetCHARattribute(context, current->node, ZI_WORK); + if ((ziU8)count < context->cnt) { +check_word: + if (context->cnt < search[1]) goto descend; + if (search[0] == 0 || context->cnt <= search[1]) { + if (acceptPrefix != 0 || (endOfWord = ZiDAWGgetEOWattribute(current->node)) != 0) { + for (depth = 0; depth < context->cnt; depth++) { + output[depth] = records[depth].attr; + } + result = context->cnt; + searching = 0; + if (acceptPrefix != 0) goto next_sibling; + } + if (search[0] == 0 || context->cnt < search[1]) goto descend; + } +next_sibling: + while (context->cnt != 0) { + graph = ZiDAWGGetSibling(records[context->cnt - 1].node); + records[context->cnt - 1].node = graph; + if (records[context->cnt - 1].node != 0) break; + context->cnt--; + } + } else { + if (context->p14 == 0) { + key = Zi8ConvertWC2Key(current->attr & 0xffff, language, ZI_WORK); + } else { + key = (ziU16)context->p14[(current->attr >> 24) * 2] * 0x100 + + (ziU16)context->p14[(current->attr >> 24) * 2 + 1]; + } + if (key != elements[context->cnt - 1] && + (current->attr & 0xffff) != elements[context->cnt - 1]) goto next_sibling; + if (current->key != elements[context->cnt - 1]) { + current->key = elements[context->cnt - 1]; + current->back = records[0].node; + depth = context->cnt; + records[depth].key = 0; + } + if (prefixLength != 0 && *prefixLength < context->cnt && + (endOfWord = ZiDAWGgetEOWattribute(current->node)) != 0) { + *prefixLength = context->cnt; + for (depth = 0; depth < context->cnt; depth++) output[depth] = records[depth].attr; + } + if ((ziU8)count <= context->cnt) goto check_word; +descend: + graph = ZiDAWGGetChild(records[context->cnt - 1].node); + records[context->cnt].node = graph; + if (records[context->cnt].node == 0) goto next_sibling; + context->cnt++; + if (ZI_WORK->unk_0x141F < context->cnt) ZI_WORK->unk_0x141F = context->cnt; + } + depth = context->cnt; + } + } +finish_graph: + return result; +} +ziU8* NextDawgGroup(ziU8* group, ziU8 language, ziPtr __zi8_work_data) +{ + if (Zi8GetTableSize(language,0x1c,ZI_WORK) != 0) { + if (group == 0) { + group = (ziU8*)Zi8GetTableAddress(language,0x1c,ZI_WORK); + if (group == 0) { + Zi8LogError(0x962,ZI_WORK); + return 0; + } + if (ZI_WORK->unk_0x141D == 0) { + return group; + } + } + while (group[0] != 0xff || group[1] != 0xff) { + group = group + 1; + } + group = group + 2; + if (group[0] == 0xff) { + Zi8LogError(0x963,ZI_WORK); + return 0; + } + return group; + } + Zi8LogError(0x961,ZI_WORK); + return 0; +} + +unsigned int Zi8MatchROMdata1(ziWChar *elements, ziU8 count, ziU8 language, ziWChar *output, ziU16 capacity, ziU8 mode, unsigned int status, ziU32 groupIndex, char *group, ziU8 acceptPrefix, ziPtr __zi8_work_data) +{ + unsigned int result; + ziU32 tableAddress; + + result = 0; + if ((status & 0xff) == 0) { + ZI_WORK->unk_0x1764 = (ziU8*)group; + if (ZI_WORK->unk_0x1764 == 0) { + if (Zi8GetTableSize(language & 0xff,0xb,ZI_WORK) != 0) { + tableAddress = Zi8GetTableAddress(language & 0xff,0xb,ZI_WORK); + ZI_WORK->unk_0x1764 = (ziU8*)tableAddress; + } + } + if (ZI_WORK->unk_0x1764 != 0) { + for (; (*ZI_WORK->unk_0x1764 != 0xff && ((groupIndex & 0xff) != 0)); + groupIndex = groupIndex - 1) { + while (*ZI_WORK->unk_0x1764 != 0xff) { + ZI_WORK->unk_0x1764 += 2; + } + ZI_WORK->unk_0x1764++; + } + } + } + if (ZI_WORK->unk_0x1764 == 0) { + result = Zi8MatchROMdata0(elements,count,language & 0xff,output,capacity & 0xffff, + mode & 0xff,status & 0xff,0,1,acceptPrefix,0,&ZI_WORK->dawgCtx, + ZI_WORK->unk_0x1760,ZI_WORK); + } + else { + while (*ZI_WORK->unk_0x1764 != 0xff) { + result = Zi8MatchROMdata0(elements,count,language & 0xff,output, + capacity & 0xffff,mode & 0xff,status & 0xff, + *ZI_WORK->unk_0x1764, + ZI_WORK->unk_0x1764[1],acceptPrefix,0, + &ZI_WORK->dawgCtx,ZI_WORK->unk_0x1760,ZI_WORK); + if ((result & 0xff) != 0) break; + ZI_WORK->unk_0x1764 += 2; + status = 0; + } + } + return result; +} + +unsigned int Zi8MatchROMdata2(ziWChar *elements, unsigned int count, unsigned int language, ziWChar *output, unsigned int capacity, unsigned int mode, unsigned int status, ziU8 reservedMode, ziU8 *group, ziU8 acceptPrefix, ziPtr __zi8_work_data) +{ + ziU16 character; + unsigned int result; + ziU8 prefixCount; + unsigned int index; + unsigned int remaining; + + result = 0; + if (reservedMode != 0) return 0; + if ((status & 0xff) == 0) { + ZI_WORK->unk_0x1768 = 0; + ZI_WORK->unk_0x17EA = 0; + if ((((group == 0) || (*group != '\f')) || ((language & 0xff) != 10)) || + (ZI_WORK->unk_0x141C == '\0')) { + ZI_WORK->unk_0x141E = 0; + } + else { + ZI_WORK->unk_0x141E = 0x10; + } + } +search_segment: + ZI_WORK->unk_0x141F = 1; + result = Zi8MatchROMdata1(elements + (unsigned int)ZI_WORK->unk_0x17EA, + count - ZI_WORK->unk_0x17EA & 0xff,language & 0xff, + &ZI_WORK->unk_0x17F4[ZI_WORK->unk_0x17EA], + capacity & 0xffff,mode & 0xff,status & 0xff, + ZI_WORK->unk_0x1768,(char *)group,acceptPrefix,ZI_WORK); + if ((result & 0xff) == 0) { + if ((((status & 0xff) != 0) || ((count & 0xff) == 1)) || + (((mode & 0xff) == 1 && + ((ZI_WORK->unk_0x1768 == 0 && + (prefixCount = Zi8MatchROMdata1(elements + (unsigned int)ZI_WORK->unk_0x17EA, + count - ZI_WORK->unk_0x17EA & 0xff,language & 0xff, + &ZI_WORK->unk_0x17F4[ZI_WORK->unk_0x17EA], + capacity & 0xffff,0,status & 0xff, + ZI_WORK->unk_0x1768,(char *)group,acceptPrefix,ZI_WORK), + prefixCount != '\0')))))) goto finish_segments; + index = Zi8GetTableCount(language & 0xff,0x1f,ZI_WORK); + if ((index & 4) == 0) { + for (index = 0; (index & 0xff) < (count & 0xff); index = index + 1) { + if (elements[index & 0xff] == 0xeff1) goto finish_segments; + } + } + if ((capacity & 0xffff) < (unsigned int)ZI_WORK->unk_0x141F) goto finish_segments; + prefixCount = ZI_WORK->unk_0x141F; + for (; prefixCount != 0; prefixCount--) { + result = Zi8MatchROMdata1(elements + (unsigned int)ZI_WORK->unk_0x17EA,prefixCount, + language & 0xff, + &ZI_WORK->unk_0x17F4[ZI_WORK->unk_0x17EA], + capacity & 0xffff,1,0,ZI_WORK->unk_0x1768,(char *)group, + acceptPrefix,ZI_WORK); + if ((result & 0xff) != 0) break; + } + if (prefixCount == 0) goto finish_segments; + ZI_WORK->unk_0x17EA = ZI_WORK->unk_0x17EA + ((ziU16)result & 0xff); + if ((unsigned int)ZI_WORK->unk_0x17EA == (count & 0xff)) { + result = 0; + goto finish_segments; + } + ZI_WORK->unk_0x1768 = ZI_WORK->unk_0x1768 + 1; + status = 0; + ZI_WORK->unk_0x141E = 0; + if ((ZI_WORK->dawgCtx.key == 0) && ((language & 0xff) == 10)) { + for (result = 0; (result & 0xff) < (unsigned int)ZI_WORK->unk_0x17EA; result = result + 1) { + character = ZI_WORK->unk_0x17F4[result & 0xff]; + if (character == 0x6f) { +select_vowel_table: + ZI_WORK->unk_0x141E = 0x10; + break; + } + if (character < 0x6f) { + if (character == 0x61) goto select_vowel_table; + } + else if (character == 0x75) goto select_vowel_table; + } + } + goto search_segment; + } + for (remaining = ZI_WORK->unk_0x17EA + result & 0xff; (remaining & 0xff) != 0; + remaining = remaining - 1) { + output[(remaining & 0xff) - 1] = ZI_WORK->unk_0x17F4[(remaining & 0xff) - 1]; + } + result = result + ZI_WORK->unk_0x17EA & 0xff; +finish_segments: + return result; +} + +ziU8 Zi8MatchROMdata(ziWChar *elements, ziU8 count, ziU8 language, ziWChar *output, ziU16 capacity, ziU8 mode, ziU8 status, ziU8 reservedMode, ziU8 acceptPrefix, ziPtr __zi8_work_data) +{ + ziU16 *input; + ziU8* group; + int tableSize; + ziU8 found; + unsigned int elementCount; + unsigned int result; + + input = (ziU16 *)elements; + elementCount = (unsigned int)count; + result = 0; + if ((capacity & 0xffff) < (elementCount & 0xff)) { + Zi8LogError(0x321,ZI_WORK); + } + else if ((status & 0xff) == 2) { + Zi8LogError(100,ZI_WORK); + } + else { + if ((status & 0xff) == 0) { + ZI_WORK->unk_0x17EC = 0; + group = NextDawgGroup(0,language & 0xff,ZI_WORK); + ZI_WORK->unk_0x17F0 = group; + } + else if (ZI_WORK->unk_0x17EC != '\0') { + Zi8LogError(100,ZI_WORK); + goto finish_match; + } + tableSize = Zi8GetTableSize(language & 0xff,0x1c,ZI_WORK); + if (tableSize == 0) { + result = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff, + mode & 0xff,status & 0xff,reservedMode & 0xff,0,acceptPrefix,ZI_WORK); + } + else { + while (((ZI_WORK->unk_0x17F0 != 0 && + (result = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff, + mode & 0xff,status & 0xff,reservedMode & 0xff, + (ziU8 *)ZI_WORK->unk_0x17F0,acceptPrefix,ZI_WORK), + (result & 0xff) == 0)) && + ((status = 0, 1 < (elementCount & 0xff) || ((language & 0xff) != 0x36))))) { + group = NextDawgGroup(ZI_WORK->unk_0x17F0,language & 0xff,ZI_WORK); + ZI_WORK->unk_0x17F0 = group; + } + } + if (((((result & 0xff) == 0) && ((status & 0xff) == 0)) && ((mode & 0xff) == 1)) && + (((elementCount & 0xff) == 1 && ((capacity & 0xffff) != 0)))) { + ZI_WORK->unk_0x17EC = 1; + if (tableSize == 0) { + found = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff,0, + status & 0xff,reservedMode & 0xff,0,acceptPrefix,ZI_WORK); + if (found != '\0') { + *output = *input; + result = 1; + } + } + else { + group = NextDawgGroup(0,language & 0xff,ZI_WORK); + ZI_WORK->unk_0x17F0 = group; + while (ZI_WORK->unk_0x17F0 != 0) { + found = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff,0, + status & 0xff,reservedMode & 0xff,(ziU8 *)ZI_WORK->unk_0x17F0, + acceptPrefix,ZI_WORK); + if (found != '\0') { + *output = *input; + result = 1; + break; + } + group = NextDawgGroup(ZI_WORK->unk_0x17F0,language & 0xff,ZI_WORK); + ZI_WORK->unk_0x17F0 = group; + } + } + } + Zi8LogError(100,ZI_WORK); + } +finish_match: + return (ziU8)result; +} + +void Zi8SyllablesROMdata(ziWChar *elements, ziU8 count, ziU8 language, ziWChar *output, ziU16 capacity, ziU8 status, ziU8* prefixLength, ziU8 reverseOrder, ziPtr __zi8_work_data) +{ + ziU32 keyTable; + ziU8 graphTable; + + graphTable = 0x1a; + keyTable = 0x1b; + if (prefixLength != 0) { + *prefixLength = 0; + } + if (reverseOrder != 0) { + graphTable = 0x18; + keyTable = 0x19; + } + if (Zi8GetTableSize(language & 0xff,graphTable,ZI_WORK) == 0) { + if (graphTable == 0x1a) { + graphTable = 0x18; + keyTable = 0x19; + } + else { + graphTable = 0x1a; + keyTable = 0x1b; + } + } + Zi8MatchROMdata0(elements,count,language & 0xff,output,capacity,1,status,graphTable,keyTable,0,(ziU8 *)prefixLength, + &ZI_WORK->dawgCtx,ZI_WORK->unk_0x1760,ZI_WORK); + return; +} diff --git a/libs/RVLMiddleware/eZiText/src/clib/zi8getc2.c b/libs/RVLMiddleware/eZiText/src/clib/zi8getc2.c new file mode 100644 index 00000000..20828518 --- /dev/null +++ b/libs/RVLMiddleware/eZiText/src/clib/zi8getc2.c @@ -0,0 +1,735 @@ +#include +#include +#include + +typedef struct { + ziU8 countOnly; + ziU8 maxWordLength; + ziU8 lookupMode; + ziU8 suffixOnly; + ziU8 controls[8]; + ziU32 maxCount; + ziU16 capacity; + ziU8 minWordLength; + ziU8 flags; + ziU16 candidateCapacity; + ziU8 checkOnly; + ziU8 reserved; +} ZiCandidateOptions; + +const ziU8 Zi8SOdefaultArray[16] = {1, 4, 3, 2, 1, 8, 7, 6, 5, 0}; +const ziFuzzyPYPairs Zi8PYdefaultFuzzyPairs = {0, 1, 1, 1, 1, 1, 1}; +const ziFuzzyZYPairs Zi8ZYdefaultFuzzyPairs = {0}; + +ziU8 Zi8GetFormatVersion(ziU8 language, ziPtr work); +ziU32 Zi8GetTableAddress(ziU8 language, ziU8 table, ziPtr work); +ziU16 Zi8GetTableCount(ziU8 language, ziU8 table, ziPtr work); +ziU16 Zi8GetVersion(ziPtr work); +ziU16 Zi8GetOEMID(ziPtr work); +ziU16 Zi8GetBuildID(ziPtr work); +void Zi8Memcpy(ziU8* destination, ziU8* source, ziS32 count); +ziU32 Zi8GetCandidatesOrCount(ziGetParam* parameters, ZiCandidateOptions* options, ziPtr work); + +ziBool Zi8ZHsetPYfuzzyPairs(ziFuzzyPYPairs pairs ZI_NEED_WORK) { + if (pairs.ziDefault) { + ZI_WORK->unk_0x1B28.word = *(const ziU32*)&Zi8PYdefaultFuzzyPairs; + } else { + ZI_WORK->unk_0x1B28.word = *(ziU32*)&pairs; + } + return 1; +} + +ziBool Zi8ZHsetZYfuzzyPairs(ziFuzzyZYPairs pairs ZI_NEED_WORK) { + if (pairs.ziDefault) { + ZI_WORK->unk_0x1B2C.word = *(const ziU32*)&Zi8ZYdefaultFuzzyPairs; + } else { + ZI_WORK->unk_0x1B2C.word = *(ziU32*)&pairs; + } + return 1; +} + +ziBool Zi8SetLatinSearchOrder(ziU8* searchArray, ziU8 searchSize ZI_NEED_WORK) { + if (searchArray == 0 || *searchArray == 0) { + ZI_WORK->unk_0x1410 = (ziU32)Zi8SOdefaultArray; + ZI_WORK->unk_0x1418 = 9; + } else { + ZI_WORK->unk_0x1410 = (ziU32)searchArray; + ZI_WORK->unk_0x1418 = searchSize; + } + return 1; +} + +ziU16 Zi8GetGlobalDataSize(void) { + return sizeof(struct __zi8_work_data_s); +} + +static ziU16 Zi8GetDataSignature(ziU8* destination, ziU16 capacity, ziU8 language, ziPtr work) { + ziU8* signature; + ziU16 length; + if (language == 1) { + if (Zi8GetFormatVersion(1, work) < 8) { + Zi8LogError(0x26f, work); + return 0; + } + length = 0x1e; + } else { + length = 3; + } + signature = (ziU8*)Zi8GetTableAddress(language, (ziU8)length, work); + length = Zi8GetTableCount(language, (ziU8)length, work); + if (length == 0 || length > capacity) { + Zi8LogError(0x961, work); + return 0; + } + Zi8Memcpy(destination, signature, length); + destination[length] = 0; + Zi8LogError(100, work); + return length; +} + +static ziU16 Zi8GetEngineSignature(ziU8* destination, ziPtr work) { + ziU16 index = 0; + ziU16 major; + ziU16 minor; + ziU16 number; + destination[index++] = 'v'; + major = (Zi8GetVersion(work) & 0xff00) >> 8; + minor = Zi8GetVersion(work) & 0xff; + destination[index++] = (ziU8)(major / 10 + '0'); + destination[index++] = (ziU8)(major % 10 + '0'); + destination[index++] = (ziU8)(minor / 10 + '0'); + destination[index++] = (ziU8)(minor % 10 + '0'); + destination[index++] = 'o'; + number = Zi8GetOEMID(work); + destination[index++] = (ziU8)(number / 100 + '0'); + destination[index++] = (ziU8)((number % 100) / 10 + '0'); + destination[index++] = (ziU8)((number % 100) % 10 + '0'); + destination[index++] = 'b'; + number = Zi8GetBuildID(work); + destination[index++] = (ziU8)(number / 100 + '0'); + destination[index++] = (ziU8)((number % 100) / 10 + '0'); + destination[index++] = (ziU8)((number % 100) % 10 + '0'); + destination[index] = 0; + return index; +} + +static ziBool Zi8AlphaSignature(ziGetParam* parameters, ziBool countOnly ZI_NEED_WORK) { + ziU16 secondLength; + ziU16 firstLength; + ziU8* second; + ziU8* first; + ziU8 engine[32]; + ziU8 dictionary[56]; + ziU16 length; + ziU16 candidateCount; + ziWChar* output = parameters->candidates; + second = 0; + firstLength = 0; + secondLength = 0; + Zi8LogError(100, ZI_WORK); + parameters->letters = 0; + length = Zi8GetDataSignature(dictionary, 0x20, parameters->language, ZI_WORK); + if (length == 0 || length < parameters->elementCount) { + first = engine; + } else { + first = dictionary; + second = engine; + firstLength = length; + } + length = Zi8GetEngineSignature(engine, ZI_WORK); + if (length < parameters->elementCount) { + if (firstLength == 0) { + Zi8ReplaceLastError(500, ZI_WORK); + return 0; + } + second = 0; + candidateCount = 1; + } else if (firstLength == 0) { + candidateCount = 1; + firstLength = length; + } else { + candidateCount = 2; + secondLength = length; + } + if (parameters->firstCandidate < candidateCount) { + candidateCount -= parameters->firstCandidate; + if (!countOnly) { + if (parameters->maxCandidates < candidateCount) { + candidateCount = parameters->maxCandidates; + } + parameters->letters = candidateCount; + if (!(parameters->getOptions & 0x80)) { + ZI_WORK->unk_0x538 = parameters->language; + parameters->candidates[0] = 0xfff0; + output = (ziWChar*)&ZI_WORK->unk_0x338; + } + if (parameters->firstCandidate != 0) { + first = second; + firstLength = secondLength; + } + if (ZI_WORK->unk_0x0A < firstLength) { + firstLength = ZI_WORK->unk_0x0A; + } + if ((parameters->elementCount < ZI_WORK->unk_0x140C[0] || + (parameters->getOptions & 0x7e) == 2) && + parameters->elementCount < firstLength) { + firstLength = parameters->elementCount; + } + while (firstLength-- != 0) { + *output++ = *first++; + } + *output++ = 0; + if (parameters->letters == 2) { + if (ZI_WORK->unk_0x0A < secondLength) { + secondLength = ZI_WORK->unk_0x0A; + } + if ((parameters->elementCount < ZI_WORK->unk_0x140C[0] || + (parameters->getOptions & 0x7e) == 2) && + parameters->elementCount < secondLength) { + secondLength = parameters->elementCount; + } + while (secondLength-- != 0) { + *output++ = *second++; + } + *output++ = 0; + } + *output = 0; + ZI_WORK->unk_0x0A = 0xff; + return 1; + } + parameters->letters = candidateCount; + ZI_WORK->unk_0x0A = 0xff; + return 1; + } + Zi8ReplaceLastError(501, ZI_WORK); + return 0; +} + +static ziBool Zi8ZhSignature(ziGetParam* parameters, ziBool countOnly ZI_NEED_WORK) { + ziWChar* output = parameters->candidates; + ziU8* current = 0; + ziU16 copied; + ziU8 engine[32]; + ziU8 dictionary[64]; + ziU16 dataLength; + ziU32 engineLength; + ziU32 candidateCount; + ziU8 available; + Zi8LogError(100, ZI_WORK); + parameters->letters = 0; + dataLength = Zi8GetDataSignature(dictionary, 0x20, parameters->language, ZI_WORK); + engineLength = Zi8GetEngineSignature(engine, ZI_WORK); + if (!(parameters->context & 0x10)) { + candidateCount = dataLength + engineLength; + } else { + candidateCount = dataLength != 0; + if (engineLength != 0) candidateCount++; + } + if (parameters->firstCandidate < candidateCount) { + available = candidateCount - parameters->firstCandidate; + if (!countOnly) { + if (parameters->maxCandidates < (ziU16)(candidateCount - parameters->firstCandidate)) { + available = parameters->maxCandidates; + } + parameters->letters = available; + if (!(parameters->context & 0x10)) { + copied = 0; + if (dataLength != 0) { + if (parameters->firstCandidate < dataLength) { + candidateCount = dataLength - parameters->firstCandidate; + current = dictionary + parameters->firstCandidate; + } else { + candidateCount = 0; + } + if (parameters->letters < candidateCount) candidateCount = parameters->letters; + copied = candidateCount; + while (candidateCount-- != 0) *output++ = *current++; + } + current = engine; + if (dataLength <= parameters->firstCandidate) { + dataLength += engineLength - parameters->firstCandidate; + current += engineLength - dataLength; + engineLength = dataLength; + } + if ((int)(parameters->letters - copied) < (int)engineLength) { + engineLength = parameters->letters - copied; + } + while (engineLength-- != 0) *output++ = *current++; + } else { + if (parameters->firstCandidate == 0 && dataLength != 0) { + current = dictionary; + } else { + if (parameters->firstCandidate != 0 && dataLength == 0) { + Zi8ReplaceLastError(500, ZI_WORK); + return 0; + } + current = engine; + dataLength = engineLength; + } + while (dataLength-- != 0) *output++ = *current++; + *output = 0x20; + if (parameters->letters == 2) { + current = engine; + while (++output, engineLength-- != 0) *output = *current++; + *output = 0x20; + } + } + return 1; + } + parameters->letters = available; + ZI_WORK->unk_0x0A = 0xff; + return 1; + } + Zi8ReplaceLastError(502, ZI_WORK); + return 0; +} + +ziU8 _Zi8GetCandidates(ziGetParam* parameters ZI_NEED_WORK) { + ZiCandidateOptions options = {0}; + options.capacity = ZI_WORK->unk_0x141A; + return Zi8GetCandidatesOrCount(parameters, &options, ZI_WORK); +} + +ziU8 _Zi8CheckCandidates(ziGetParam* parameters ZI_NEED_WORK) { + ZiCandidateOptions options = {0}; + options.capacity = ZI_WORK->unk_0x141A; + options.flags = 1; + return Zi8GetCandidatesOrCount(parameters, &options, ZI_WORK); +} +ziU8 Zi8LangSupported(ziU8 language, ziPtr work); +ziBool Zi8IsCharacter(ziWChar character, ziPtr work); +ziU8 Zi8GetCharInfo(ziWChar character, ziWChar* output, ziU8 capacity, ziU8 type, ziPtr work); +ziU8 Zi8GetKOcandidates(ziGetParam* parameters, ziPtr options, ziPtr work); +ziU8 Zi8GetKoreanCandidates(ziGetParam* parameters, ziPtr options, ziPtr work); +ziU8 Zi8Punctuation(ziGetParam* parameters, ziPtr options, ziPtr work); +ziU8 Zi8GetChineseCandidates(ziGetParam* parameters, ziPtr options, ziPtr work); +ziU8 Zi8Get1KeyPressCandidates(ziGetParam* parameters, ziPtr options, ziPtr work); +ziU8 Zi8Get1KeyPressSpelling(ziGetParam* parameters, ziPtr options, ziPtr work); +ziU8 Zi8GetSyllablesCandidates(ziGetParam* parameters, ziPtr options, ziPtr work); +ziU8 Zi8AlphaGetCandidates(ziGetParam* parameters, ziPtr options, ziPtr work); + +ziU32 Zi8GetCandidatesOrCount(ziGetParam* parameters, ZiCandidateOptions* options ZI_NEED_WORK) { + + ziU8 savedElementCount; + ziU16 savedCharacter; + ziWChar* savedElements; + ziBool restoreCandidates; + char signatureFound; + ziU8 elementCount; + int error; + unsigned int candidateCount; + ziU8 savedOptions; + ziWChar* savedCandidates; + ziU16 characterInfo [32]; + + error = 0; + savedOptions = 0; + savedCandidates = 0; + restoreCandidates = 0; + if (options->lookupMode == '\0') { + if (((ZI_WORK->unk_0x00 == '\t') && (parameters->elementCount != 0)) && + ((((ziS16)parameters->elements[parameters->elementCount - 1] == -0x1008 && + (signatureFound = Zi8AlphaSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')) || + (((ziS16)parameters->elements[parameters->elementCount - 1] == -0x10fc && + (signatureFound = Zi8ZhSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')))))) { + candidateCount = (unsigned int)parameters->letters; + if (options->countOnly != '\0') { + parameters->letters = 0; + } + Zi8LogError(100,ZI_WORK); + goto finishCandidates; + } + if ((parameters->elementCount == 1) && (parameters->firstCandidate == 0)) { + elementCount = parameters->language; + if (elementCount == 0x11) goto latinSequence; + if (elementCount < 0x11) { + if (elementCount == 1) { + if ((ZI_WORK->unk_0x00 == '\0') || (ZI_WORK->unk_0x01 == options->countOnly)) { + switch(ZI_WORK->unk_0x00) { + case '\0': + if ((ziS16)parameters->elements[0] == -0x10fc) { + ZI_WORK->unk_0x01 = options->countOnly; + ZI_WORK->unk_0x00 = '\x01'; + } + break; + case '\x01': + case '\x03': + case '\x05': + case '\a': + if ((ziS16)parameters->elements[0] == -0x10ff) { + ZI_WORK->unk_0x00 = ZI_WORK->unk_0x00 + '\x01'; + } + else { + ZI_WORK->unk_0x00 = '\0'; + } + break; + case '\x02': + case '\x04': + case '\x06': + if ((ziS16)parameters->elements[0] == -0x10fc) { + ZI_WORK->unk_0x00 = ZI_WORK->unk_0x00 + '\x01'; + } + else { + ZI_WORK->unk_0x00 = '\0'; + } + break; + case '\b': + case '\t': + if (((ziS16)parameters->elements[0] == -0x10fc) && + (signatureFound = Zi8ZhSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')) { + ZI_WORK->unk_0x00 = '\t'; + candidateCount = (unsigned int)parameters->letters; + if (options->countOnly != '\0') { + parameters->letters = 0; + } + Zi8LogError(100,ZI_WORK); + goto finishCandidates; + } + default: + ZI_WORK->unk_0x00 = '\0'; + } + if ((ZI_WORK->unk_0x00 == '\0') && ((ziS16)parameters->elements[0] == -0x10fc)) { + ZI_WORK->unk_0x00 = '\x01'; + } + } + } + else if ((elementCount == 0) || (elementCount < 0x10)) goto latinSequence; + } + else if (elementCount < 0x77) { + if (0x12 < elementCount) { +latinSequence: + if ((ZI_WORK->unk_0x00 == '\0') || (ZI_WORK->unk_0x01 == options->countOnly)) { + switch(ZI_WORK->unk_0x00) { + case '\0': + if ((ziS16)parameters->elements[0] == -0x100e) { + ZI_WORK->unk_0x01 = options->countOnly; + ZI_WORK->unk_0x00 = '\x01'; + } + break; + case '\x01': + if ((ziS16)parameters->elements[0] == -0x100d) { + ZI_WORK->unk_0x00 = '\x02'; + } + else { + ZI_WORK->unk_0x00 = '\0'; + } + break; + case '\x02': + if ((ziS16)parameters->elements[0] == -0x100b) { + ZI_WORK->unk_0x00 = '\x03'; + } + else { + ZI_WORK->unk_0x00 = '\0'; + } + break; + case '\x03': + if ((ziS16)parameters->elements[0] == -0x1009) { + ZI_WORK->unk_0x00 = '\x04'; + } + else { + ZI_WORK->unk_0x00 = '\0'; + } + break; + case '\x04': + if ((ziS16)parameters->elements[0] == -0x1008) { + ZI_WORK->unk_0x00 = '\x05'; + } + else { + ZI_WORK->unk_0x00 = '\0'; + } + break; + case '\x05': + if ((ziS16)parameters->elements[0] == -0x1007) { + ZI_WORK->unk_0x00 = '\x06'; + } + else { + ZI_WORK->unk_0x00 = '\0'; + } + break; + case '\x06': + if ((ziS16)parameters->elements[0] == -0x100e) { + ZI_WORK->unk_0x00 = '\a'; + } + else { + ZI_WORK->unk_0x00 = '\0'; + } + break; + case '\a': + if ((ziS16)parameters->elements[0] == -0x100b) { + ZI_WORK->unk_0x00 = '\b'; + } + else { + ZI_WORK->unk_0x00 = '\0'; + } + break; + case '\b': + case '\t': + if (((ziS16)parameters->elements[0] == -0x1008) && + (signatureFound = Zi8AlphaSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')) { + ZI_WORK->unk_0x00 = '\t'; + candidateCount = (unsigned int)parameters->letters; + if (options->countOnly != '\0') { + parameters->letters = 0; + } + Zi8LogError(100,ZI_WORK); + goto finishCandidates; + } + default: + ZI_WORK->unk_0x00 = '\0'; + } + if ((ZI_WORK->unk_0x00 == '\0') && ((ziS16)parameters->elements[0] == -0x100e)) { + ZI_WORK->unk_0x00 = '\x01'; + } + } + } + } + else if (0x7d < elementCount) goto latinSequence; + } + else if (1 < parameters->elementCount) { + ZI_WORK->unk_0x00 = '\0'; + } + } + ZI_WORK->unk_0x18 = parameters->subLanguage; + elementCount = Zi8GetFormatVersion(1,ZI_WORK); + ZI_WORK->unk_0x16 = elementCount & 2; + options->maxCount = ZI_WORK->unk_0x10; + options->maxWordLength = ZI_WORK->unk_0x0A; + ZI_WORK->unk_0x0A = -1; + signatureFound = Zi8LangSupported(parameters->language,ZI_WORK); + if (signatureFound == '\0') { + Zi8LogError(0x163,ZI_WORK); + candidateCount = 0; + } + else { + if (parameters->language == 0x10) { + error = 0x2c1; + candidateCount = 0; + } + else if (parameters->language == 0x12) { + if ((parameters->elementCount == 0) || (0xeff0 < parameters->elements[0])) { + candidateCount = Zi8GetKOcandidates(parameters,options,ZI_WORK); + } + else { + candidateCount = Zi8GetKoreanCandidates(parameters,options,ZI_WORK); + } + } + else if ((parameters->language == 1) && ((parameters->context & 8) != 0)) { + candidateCount = Zi8Punctuation(parameters,options,ZI_WORK); + error = 100; + } + else if ((parameters->language == 1) && + ((((parameters->getOptions & 0xbf) == 4 && (parameters->elementCount != 0)) && + (signatureFound = Zi8IsCharacter(parameters->elements[0],ZI_WORK), signatureFound != '\0')))) { + elementCount = Zi8GetCharInfo(parameters->elements[0],characterInfo,0x10,1,ZI_WORK); + if (elementCount == 0) { + parameters->unk_0x20 = 0; + parameters->count = 0; + parameters->letters = 0; + candidateCount = 0; + error = 900; + } + else { + if ((0xf330 < characterInfo[elementCount - 1]) && (characterInfo[elementCount - 1] < 0xf336)) { + characterInfo[elementCount - 1] = 0xf360; + } + savedElements = parameters->elements; + parameters->elements = characterInfo; + savedElementCount = parameters->elementCount; + parameters->elementCount = elementCount; + elementCount = parameters->getMode; + parameters->getMode = 1; + candidateCount = Zi8GetChineseCandidates(parameters,options,ZI_WORK); + parameters->elements = savedElements; + parameters->elementCount = savedElementCount; + parameters->getMode = elementCount; + parameters->count = 1; + } + } + else if ((parameters->language == 1) && (parameters->getMode == 0xf)) { + error = 0x2d0; + candidateCount = 0; + } + else if ((parameters->language == 1) && ((parameters->getMode == 3 || (parameters->getMode == 4)))) { + if ((parameters->getOptions & 0x80) == 0) { + if (parameters->elementCount == 0) { + candidateCount = Zi8GetChineseCandidates(parameters,options,ZI_WORK); + } + else { + candidateCount = Zi8Get1KeyPressCandidates(parameters,options,ZI_WORK); + } + } + else { + candidateCount = Zi8Get1KeyPressSpelling(parameters,options,ZI_WORK); + } + } + else if ((parameters->language == 1) && + ((((parameters->getMode == 7 || (parameters->getMode == 8)) || (parameters->getMode == 10)) || (parameters->getMode == 9)))) { + if (ZI_WORK->unk_0x16 == '\0') { + error = 0x708; + candidateCount = 0; + } + else { + candidateCount = Zi8GetChineseCandidates(parameters,options,ZI_WORK); + } + } + else if ((parameters->language == 1) && ((parameters->getMode == 0xb || (parameters->getMode == 0xe)))) { + error = 0x2ee; + candidateCount = 0; + } + else if (parameters->language == 1) { + candidateCount = Zi8GetChineseCandidates(parameters,options,ZI_WORK); + if ((((candidateCount == 0) && ((parameters->getOptions & 0x20) == 0)) && ((parameters->getMode == 1 && (parameters->elementCount != 0)))) + && ((((ziS16)parameters->elements[parameters->elementCount - 1] == -0xc86 || + ((ziS16)parameters->elements[parameters->elementCount - 1] == -0xc9d)) || + ((ziS16)parameters->elements[parameters->elementCount - 1] == -0xc8d)))) { + savedCharacter = parameters->elements[parameters->elementCount]; + elementCount = parameters->elementCount; + parameters->elements[elementCount] = 0xf368; + parameters->elementCount = elementCount + 1; + candidateCount = Zi8GetChineseCandidates(parameters,options,ZI_WORK); + elementCount = parameters->elementCount; + parameters->elementCount = elementCount - 1; + parameters->elements[(ziU8)(elementCount - 1)] = savedCharacter; + } + } + else { + ZI_WORK->unk_0x538 = parameters->language; + restoreCandidates = (parameters->getOptions & 0x80) == 0; + if (restoreCandidates) { + savedOptions = parameters->getOptions; + savedCandidates = parameters->candidates; + parameters->getOptions = parameters->getOptions | 0x81; + parameters->candidates = (ziWChar*)&ZI_WORK->unk_0x338; + options->capacity = 0x100; + } + if (parameters->getMode == 2) { + candidateCount = Zi8GetTableCount(parameters->language,0x1f,ZI_WORK); + if ((candidateCount & 0x200) == 0) { + error = 0x44c; + candidateCount = 0; + } + else { + candidateCount = Zi8GetSyllablesCandidates(parameters,options,ZI_WORK); + } + } + else { + candidateCount = Zi8AlphaGetCandidates(parameters,options,ZI_WORK); + } + } + if (restoreCandidates) { + parameters->getOptions = savedOptions; + parameters->candidates = savedCandidates; + for (elementCount = 0; elementCount < parameters->letters; elementCount = elementCount + 1) { + parameters->candidates[elementCount] = elementCount - 0x10; + } + } + if (error != 0) { + Zi8LogError(error,ZI_WORK); + } + } +finishCandidates: + return candidateCount; +} + +void Zi8InitDupWordBuf(ziPtr __zi8_work_data) { + ZI_WORK->unk_0x539 = 0; +} + +ziBool Zi8IsDupWChar(ziWChar character ZI_NEED_WORK) { + ziBool duplicate = 0; + ziU16* buffer = ZI_WORK->unk_0x57A; + unsigned int index; + ziU16 position; + if (ZI_WORK->unk_0x539 == 0) { + buffer[0] = 2; + buffer[1] = character; + ZI_WORK->unk_0x539 = 1; + Zi8LogError(0x8fd, ZI_WORK); + return 0; + } + for (index = ZI_WORK->unk_0x539; index != 0; index--) { + if (character == buffer[index]) { + duplicate = 1; + break; + } + } + ZI_WORK->unk_0x539++; + position = *buffer; + buffer[position] = character; + *buffer = ++position; + if (*buffer > 100) { + *buffer = 2; + buffer[1] = character; + ZI_WORK->unk_0x539 = 1; + } + Zi8LogError(100, ZI_WORK); + return duplicate; +} + +ziBool Zi8IsDupWordW(ziWChar* word, ziU8 length ZI_NEED_WORK) { + ziU8 slot; + ziU32 duplicate = 0; + unsigned int position; + int index; + int character; + if (word == 0 || length == 0) { + Zi8LogError(300, ZI_WORK); + return 0; + } + if (length > 20) { + word += length - 20; + length = 20; + } + for (index = 0; index < ZI_WORK->unk_0x539; index++) { + slot = ZI_WORK->unk_0x53A[index]; + for (character = 0; character < length; character++) { + if (word[character] != ZI_WORK->unk_0x57A[slot * 21 + character]) break; + } + if (character >= length && ZI_WORK->unk_0x57A[slot * 21 + character] == 0) { + duplicate = 1; + break; + } + } + if (!duplicate) { + if (ZI_WORK->unk_0x539 < 64) { + position = ZI_WORK->unk_0x539; + ZI_WORK->unk_0x53A[ZI_WORK->unk_0x539] = ZI_WORK->unk_0x539; + ZI_WORK->unk_0x539++; + } else { + slot = ZI_WORK->unk_0x53A[0]; + position = slot; + for (index = 1; index < ZI_WORK->unk_0x539; index++) { + ZI_WORK->unk_0x53A[index - 1] = ZI_WORK->unk_0x53A[index]; + } + ZI_WORK->unk_0x53A[index - 1] = slot; + } + } else { + slot = ZI_WORK->unk_0x53A[index]; + position = slot; + for (; index < ZI_WORK->unk_0x539 - 1; index++) { + ZI_WORK->unk_0x53A[index] = ZI_WORK->unk_0x53A[index + 1]; + } + ZI_WORK->unk_0x53A[index] = slot; + } + for (index = 0; index < length; index++) { + ZI_WORK->unk_0x57A[position * 21 + index] = word[index]; + } + ZI_WORK->unk_0x57A[position * 21 + index] = 0; + Zi8LogError(100, ZI_WORK); + return duplicate; +} + +void Zi8Memset(ziU8* destination, ziU32 value, ziS32 count) { + ziS32 index; + for (index = 0; index < count; index++) destination[index] = (ziU8)value; +} + +void Zi8Memcpy(ziU8* destination, ziU8* source, ziS32 count) { + ziS32 index; + for (index = 0; index < count; index++) destination[index] = source[index]; +} + +ziBool Zi8SetMaxWordLength(ziU8 length ZI_NEED_WORK) { + ZI_WORK->unk_0x0A = length; + return 1; +} diff --git a/libs/RVLMiddleware/eZiText/src/clib/zi8match.c b/libs/RVLMiddleware/eZiText/src/clib/zi8match.c new file mode 100644 index 00000000..dea41717 --- /dev/null +++ b/libs/RVLMiddleware/eZiText/src/clib/zi8match.c @@ -0,0 +1,876 @@ +#include +#include + +extern ziU32 Zi8GetTableAddress(ziU8 lang, ziU8 tableIdx ZI_NEED_WORK); + +const ziU8 Zi8PinyinInitials[0x1C] = { + 0x00, 0x3C, 0x98, 0x02, 0x00, 0x38, 0x34, 0x3B, 0x00, 0x06, 0x37, 0x2B, + 0x0C, 0x26, 0x00, 0x3F, 0x09, 0x2C, 0x9A, 0x05, 0x00, 0x00, 0x11, 0x0A, + 0x0D, 0x9C, 0x00, 0x00 +}; +const ziU8 Zi8BpmfInitials[0x24] = { + 0x3C, 0x3F, 0x0C, 0x38, 0x02, 0x05, 0x26, 0x2B, 0x34, 0x37, 0x3B, 0x06, + 0x09, 0x0A, 0x1D, 0x19, 0x1B, 0x2C, 0x1C, 0x18, 0x1A, 0x01, 0x02, 0x03, + 0x05, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0E, 0x0D, 0x0F, 0x04, 0x00, 0x00 +}; +const ziU8 Zi8PinyinFinals[0x36][8] = { + {0x0F, 0xFF, 0x00, 0x00, 0x3C, 0x28, 0x00, 0x00}, + {0x0F, 0x00, 0x00, 0x00, 0x3F, 0x2B, 0x00, 0x00}, + {0x0F, 0x0E, 0xFF, 0x00, 0x3F, 0x28, 0x00, 0x00}, + {0x0F, 0x0E, 0x07, 0x00, 0x3F, 0x28, 0x00, 0x00}, + {0x0F, 0x15, 0x00, 0x00, 0x3F, 0x2A, 0x00, 0x00}, + {0x09, 0xFF, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00}, + {0x09, 0x00, 0x00, 0x00, 0x3F, 0x08, 0x00, 0x00}, + {0x09, 0x01, 0xFF, 0x00, 0x38, 0x00, 0x00, 0x00}, + {0x09, 0x01, 0x00, 0x00, 0x3F, 0x04, 0x00, 0x00}, + {0x09, 0x01, 0x0F, 0x00, 0x3F, 0x01, 0x00, 0x00}, + {0x09, 0x01, 0x0E, 0xFF, 0x3E, 0x02, 0x00, 0x00}, + {0x09, 0x01, 0x0E, 0x00, 0x3F, 0x02, 0x00, 0x00}, + {0x09, 0x01, 0x0E, 0x07, 0x3F, 0x03, 0x00, 0x00}, + {0x09, 0x05, 0x00, 0x00, 0x3F, 0x09, 0x00, 0x00}, + {0x09, 0x15, 0x00, 0x00, 0x3F, 0x0B, 0x00, 0x00}, + {0x09, 0x0E, 0xFF, 0x00, 0x3E, 0x0C, 0x00, 0x00}, + {0x09, 0x0E, 0x00, 0x00, 0x3F, 0x0C, 0x00, 0x00}, + {0x09, 0x0E, 0x07, 0x00, 0x3F, 0x0D, 0x00, 0x00}, + {0x09, 0x0F, 0xFF, 0x00, 0x3E, 0x0E, 0x00, 0x00}, + {0x09, 0x0F, 0x15, 0x00, 0x3F, 0x0E, 0x00, 0x00}, + {0x09, 0x0F, 0x0E, 0xFF, 0x3F, 0x0F, 0x00, 0x00}, + {0x09, 0x0F, 0x0E, 0x07, 0x3F, 0x0F, 0x00, 0x00}, + {0x15, 0xFF, 0x00, 0x00, 0x30, 0x10, 0x00, 0x00}, + {0x15, 0x00, 0x00, 0x00, 0x3F, 0x18, 0x00, 0x00}, + {0x15, 0x01, 0xFF, 0x00, 0x38, 0x10, 0x00, 0x00}, + {0x15, 0x01, 0x00, 0x00, 0x3F, 0x17, 0x00, 0x00}, + {0x15, 0x01, 0x0E, 0xFF, 0x3E, 0x10, 0x00, 0x00}, + {0x15, 0x01, 0x0E, 0x00, 0x3F, 0x10, 0x00, 0x00}, + {0x15, 0x01, 0x0E, 0x07, 0x3F, 0x11, 0x00, 0x00}, + {0x15, 0x01, 0x09, 0x00, 0x3F, 0x13, 0x00, 0x00}, + {0x15, 0x0E, 0x00, 0x00, 0x3F, 0x1C, 0x00, 0x00}, + {0x15, 0x09, 0x00, 0x00, 0x3F, 0x1D, 0x00, 0x00}, + {0x15, 0x0F, 0x00, 0x00, 0x3F, 0x1E, 0x00, 0x00}, + {0x15, 0x05, 0x00, 0x00, 0x3F, 0x1F, 0x00, 0x00}, + {0x01, 0xFF, 0x00, 0x00, 0x38, 0x20, 0x00, 0x00}, + {0x01, 0x00, 0x00, 0x00, 0x3F, 0x23, 0x00, 0x00}, + {0x01, 0x0E, 0xFF, 0x00, 0x3E, 0x20, 0x00, 0x00}, + {0x01, 0x0E, 0x00, 0x00, 0x3F, 0x20, 0x00, 0x00}, + {0x01, 0x0E, 0x07, 0x00, 0x3F, 0x21, 0x00, 0x00}, + {0x01, 0x09, 0x00, 0x00, 0x3F, 0x25, 0x00, 0x00}, + {0x01, 0x0F, 0x00, 0x00, 0x3F, 0x26, 0x00, 0x00}, + {0x05, 0xFF, 0x00, 0x00, 0x38, 0x30, 0x00, 0x00}, + {0x05, 0x00, 0x00, 0x00, 0x3F, 0x34, 0x00, 0x00}, + {0x05, 0x0E, 0xFF, 0x00, 0x3E, 0x30, 0x00, 0x00}, + {0x05, 0x0E, 0x00, 0x00, 0x3F, 0x30, 0x00, 0x00}, + {0x05, 0x0E, 0x07, 0x00, 0x3F, 0x31, 0x00, 0x00}, + {0x05, 0x09, 0x00, 0x00, 0x3F, 0x35, 0x00, 0x00}, + {0x05, 0x12, 0x00, 0x00, 0x3F, 0x33, 0x00, 0x00}, + {0x16, 0xFF, 0x00, 0x00, 0x3C, 0x38, 0x00, 0x00}, + {0x16, 0x00, 0x00, 0x00, 0x3F, 0x38, 0x00, 0x00}, + {0x16, 0x01, 0xFF, 0x00, 0x3F, 0x39, 0x00, 0x00}, + {0x16, 0x01, 0x0E, 0x00, 0x3F, 0x39, 0x00, 0x00}, + {0x16, 0x05, 0x00, 0x00, 0x3F, 0x1F, 0x00, 0x00}, + {0x16, 0x0E, 0x00, 0x00, 0x3F, 0x3B, 0x00, 0x00} +}; +const ziU8 nodeHeaderTable[0x20] = { + 0x00, 0x10, 0x00, 0x01, 0x00, 0x03, 0x00, 0x14, 0x00, 0x05, 0x00, 0x07, + 0x00, 0x1C, 0x00, 0x0D, 0x00, 0x0F, 0x00, 0x11, 0x00, 0x13, 0x00, 0x15, + 0x00, 0x17, 0x00, 0x1D, 0x00, 0x1F, 0x00, 0x35 +}; + +ziBool Zi8PriMatchNextChar(ziU8* node, ziU8 mask0, ziU8 value0, ziU8 mask1, ziU8 value1, ziU8 mask2, ziU8 value2, ziU8 mask3, ziU8 value3, ziU16* count, ziU8** result, ziU16* code ZI_NEED_WORK) { + ziU16 remaining = *count; + while (remaining-- != 0) { + if ((value0 == (node[0] & mask0)) && (value3 == (node[3] & mask3)) && (value2 == (node[2] & mask2)) && (value1 == (node[1] & mask1))) { + *result = node; + *code = ((ziU16)node[6] << 8) + (ziU16)node[7]; + *count = remaining; + Zi8LogError(0x64, ZI_WORK); + return 1; + } + node += 0xC; + } + Zi8LogError(0x12E, ZI_WORK); + return 0; +} + +ziBool Zi8ExactMatchNextChar(ziU8* node, ziU8 mask0, ziU8 value0, ziU8 mask1, ziU8 value1, ziU8 mask2, ziU8 value2, ziU8 mask3, ziU8 value3, ziU16* count, ziU8** result, ziU16* code ZI_NEED_WORK) { + ziU16 remaining = *count; + ziU8* current = node; + while (remaining-- != 0) { + if ((value0 == (current[0] & mask0)) && (value3 == (current[3] & mask3)) && (value2 == (current[2] & mask2)) && (value1 == (current[1] & mask1))) { + *result = current; + *code = ((ziU16)current[6] << 8) + (ziU16)current[7]; + *count = remaining; + Zi8LogError(0x64, ZI_WORK); + return 1; + } + current += 0xC; + } + Zi8LogError(0x12E, ZI_WORK); + return 0; +} + +ziU32 Zi8SecMatchChar(ziPtr nodeAddress, ziU8* dictionaryAddress, ziMatchParam* match, ziU16* code ZI_NEED_WORK) { + ziBool isPartial = 0; + ziU16 matchCode; + ziU8* data; + ziU8 value; + struct { + ziU8 remaining; + ziU8 dataIndex; + ziU16 targetCode; + } state; + + if (match->field22 != 0) { + state.targetCode = match->field22; + matchCode = ((ziU16)(((ziU8*)nodeAddress)[4] & 3) << 8) | ((ziU8*)nodeAddress)[5]; + value = 0; + while (value++ < 6) { + if (state.targetCode == matchCode) { + break; + } + matchCode = ((ziU16)(*(dictionaryAddress + matchCode * 8 + 6) & 3) << 8) | *(dictionaryAddress + matchCode * 8 + 7); + if (matchCode == 0) { + break; + } + } + if (state.targetCode != matchCode) { + return 0; + } + } + + data = (ziU8*)Zi8GetTableAddress(1, 1, ZI_WORK); + data += ((ziU8*)nodeAddress)[0xB] + (((ziU8*)nodeAddress)[0xA] << 8) + ((((ziU8*)nodeAddress)[9] & 0xF) << 16); + if (ZI_WORK->unk_0x16 != 0) { + switch (data[0] & 7) { + case 2: + data += 2; + break; + case 3: + case 4: + data += 3; + break; + case 5: + data += 4; + break; + default: + data++; + break; + } + } + + value = data[0]; + value = (value >> 4) & 7; + if (value * 2 + 10 < match->length) { + return 0; + } + if (match->length < 9) { + if (match->length == 8) { + if ((data[0] & 0xF) == 0xF) { + isPartial = 1; + } + } else if ((match->length & 1) != 0) { + if ((((ziU8*)nodeAddress)[match->length >> 1] & 0xF) == 0xF) { + isPartial = 1; + } + } else { + if ((((ziU8*)nodeAddress)[match->length >> 1] & 0xF0) == 0xF0) { + isPartial = 1; + } + } + if (match->length > 2) { + if ((match->length & 1) != 0) { + if (((((ziU8*)nodeAddress)[(match->length - 1) >> 1] & 0xF0) == 0) || ((((ziU8*)nodeAddress)[(match->length - 1) >> 1] & 0xF0) == 0xF0)) { + return 0; + } + } else { + if (((((ziU8*)nodeAddress)[(match->length - 1) >> 1] & 0xF) == 0) || ((((ziU8*)nodeAddress)[(match->length - 1) >> 1] & 0xF) == 0xF)) { + return 0; + } + } + } + if (code != 0) { + *code = ((ziU16)((ziU8*)nodeAddress)[6] << 8) + (ziU16)((ziU8*)nodeAddress)[7]; + } + if (isPartial) { + return 2; + } + return 1; + } + + if ((match->length & 1) != 0) { + if (((data[((match->length - 1) >> 1) - 4] & 0xF0) == 0) || ((data[((match->length - 1) >> 1) - 4] & 0xF0) == 0xF0)) { + return 0; + } + } else { + if (((data[((match->length - 1) >> 1) - 4] & 0xF) == 0) || ((data[((match->length - 1) >> 1) - 4] & 0xF) == 0xF)) { + return 0; + } + } + + state.dataIndex = 4; + state.remaining = ((match->length + 1) >> 1) - 4; + if (((ziU8)value + 1) < (int)state.remaining) { + return 0; + } + if ((match->length & 1) != 0) { + if ((data[(match->length >> 1) - 4] & 0xF) == 0xF) { + isPartial = 1; + } + } else { + if ((data[(match->length >> 1) - 4] & 0xF0) == 0xF0) { + isPartial = 1; + } + } + if (match->count == 0) { + while (state.remaining != 0) { + if ((data[0] & match->arr1[state.dataIndex]) != match->arrD[state.dataIndex]) { + return 0; + } + state.dataIndex++; + state.remaining--; + data++; + } + } + if (code != 0) { + *code = ((ziU16)((ziU8*)nodeAddress)[6] << 8) + (ziU16)((ziU8*)nodeAddress)[7]; + } + if (isPartial) { + return 2; + } + return 1; +} + +ziBool Zi8PriMatchNextComp(ziU8* node, ziU8 mask0, ziU8 value0, ziU8 mask1, ziU8 value1, ziU8 mask2, ziU8 value2, ziU8 mask3, ziU8 value3, ziU16* count, ziU8** result ZI_NEED_WORK) { + ziU16 remaining = *count; + while (remaining-- != 0) { + if ((value0 == (node[0] & mask0)) && (value1 == (node[1] & mask1)) && (value2 == (node[2] & mask2)) && (value3 == (node[3] & mask3))) { + *result = node; + *count = remaining; + Zi8LogError(0x64, ZI_WORK); + return 1; + } + node += 8; + } + Zi8LogError(0x12E, ZI_WORK); + return 0; +} + +ziBool Zi8SecMatchComp(ziPtr nodeAddress, ziMatchParam* matchAddress, ziPtr dictionaryAddress) { + int chainIndex; + ziU16 matchCode; + ziU16 targetCode; + + if (matchAddress->field22 != 0) { + targetCode = matchAddress->field22; + matchCode = ((ziU16)(((ziU8*)nodeAddress)[6] & 3) << 8) | ((ziU8*)nodeAddress)[7]; + chainIndex = 0; + while (chainIndex++ < 6) { + if (targetCode == matchCode) { + break; + } + matchCode = ((ziU16)(*((ziU8*)dictionaryAddress + matchCode * 8 + 6) & 3) << 8) | *((ziU8*)dictionaryAddress + matchCode * 8 + 7); + if (matchCode == 0) { + break; + } + } + if (targetCode != matchCode) { + return 0; + } + } + if (matchAddress->length > 8) { + if ((int)((ziU8*)nodeAddress)[5] < (int)(matchAddress->length - 2)) { + return 0; + } + } else if ((int)((ziU8*)nodeAddress)[5] < (int)(matchAddress->length - 1)) { + return 0; + } + return 1; +} + +extern ziU16 Zi8MatchAltSound(ziPtr soundTable, ziU16 soundCode, ziPtr pCodeTable, ziU16 index, ziU16 mask, ziU16 value, ziU8 flag ZI_NEED_WORK); +ziU16 Zi8GetPCode(ziU8* table, ziU8* node); + +ziBool Zi8MatchPhonetic(ziPtr pCodeTable, ziPtr dictionary, ziPtr soundTable, ziU16 soundCode, ziU32 tableAddress, ziU8* node, ziU16* masks, ziU16* values, ziU16* count, ziU8** resultNode, ziU8** stringOffset, ziS8 partialMode, ziU8 strictMode, ziU8 numParts, ziU16 partMask, ziU16 partValue, ziU8 flag, ziU8 altMode, ziU16 initialCode, ziU16* resultCode, ziU8 lastMode ZI_NEED_WORK) { + ziBool hasString; + ziU32 matchedParts; + ziU32 altModeActive; + ziU8 partCode; + ziU8 partCount; + ziU8 partIndex; + ziU16 soundIndex; + ziU16 remaining; + ziU16 code; + ziU16 dictionaryIndex; + ziU8 nextCode; + ziU8* sound; + ziU8* nextPart; + + if (*stringOffset != 0) { + hasString = 1; + } else { + hasString = 0; + } + if (*count == 0) { + remaining = 1; + } else { + remaining = *count; + } + matchedParts = 0; + altModeActive = altMode; + if ((lastMode != 0) && (numParts > 1)) { + altModeActive = 1; + } + while (remaining-- != 0) { + if ((node[0] & flag) != 0) { + code = Zi8GetPCode((ziU8*)pCodeTable, node); + if ((*values != (code & *masks)) && (altModeActive == 0) && ((node[0] & 0x80) != 0)) { + if (*count != 0) { + soundIndex = (initialCode - remaining) - 1; + } else { + soundIndex = initialCode; + } + code = Zi8MatchAltSound(soundTable, soundCode, pCodeTable, soundIndex, *masks, *values, flag, ZI_WORK); + } + if ((*values == (code & *masks)) && (partValue != (code & partMask))) { + matchedParts = 1; + sound = (ziU8*)((tableAddress + ((node[9] & 0xF) * 0x10000)) + node[0xB] + node[0xA] * 0x100); + if (ZI_WORK->unk_0x16 != 0) { + switch (sound[0] & 7) { + case 2: + sound += 2; + break; + case 3: + case 4: + sound += 3; + break; + case 5: + sound += 4; + break; + default: + sound++; + break; + } + } + if ((sound[0] & 0x80) != 0) { + sound += ((sound[0] & 0x7F) >> 4) + 1; + } else if (numParts > 1) { + goto next_node; + } + if (((ziU8)matchedParts == numParts) || (numParts == 0)) { + *resultNode = node; + *resultCode = ((ziU16)node[6] << 8) + node[7]; + *count = remaining; + return 1; + } + do { + nextCode = *sound++; + partCount = nextCode & 0xF; + if ((nextCode & flag) == 0) { + for (; partCount != 0; partCount--) { + for (sound++; (*sound & 0x80) == 0; sound += 2) { + } + sound++; + } + } + for (; partCount != 0; partCount--) { + partIndex = 1; + if (hasString && (*stringOffset < sound)) { + hasString = 0; + } + nextPart = sound; + if (!hasString) { + *stringOffset = sound; + } + do { + partCode = nextPart[1]; + dictionaryIndex = ((ziU16)partCode << 8) | nextPart[0]; + sound = nextPart + 2; + if (hasString) { + goto phonetic_skip; + } + code = Zi8GetPCode((ziU8*)pCodeTable, (ziU8*)dictionary + (dictionaryIndex & 0x7FFF) * 0xC); + if (((code & masks[partIndex]) != values[partIndex]) && (altModeActive == 0) && (((ziU8*)dictionary)[(dictionaryIndex & 0x7FFF) * 0xC] & 0x80) != 0) { + code = Zi8MatchAltSound(soundTable, soundCode, pCodeTable, dictionaryIndex & 0x7FFF, masks[partIndex], values[partIndex], flag, ZI_WORK); + } + if ((code & masks[partIndex]) != values[partIndex]) { + goto phonetic_skip; + } + partIndex++; + if (partIndex == numParts) { + if ((partialMode != 0) && ((strictMode == 0 && (partCode & 0x80) != 0) || (strictMode != 0 && (partCode & 0x80) == 0))) { + goto phonetic_skip; + } + *resultNode = node; + code = ((ziU16)node[6] << 8) + node[7]; + *resultCode = code; + *count = remaining; + return 1; + } + nextPart = sound; + } while ((partCode & 0x80) == 0); + continue; +phonetic_skip: + if ((partCode & 0x80) == 0) { + nextPart += 3; + while ((*nextPart & 0x80) == 0) { + nextPart += 2; + } + sound = nextPart + 1; + } + } + } while ((nextCode & 0x80) == 0); + } + } +next_node: + node += 0xC; + } + return 0; +} + +ziBool Zi8GetPyFinal(ziU8* pinyin, ziU8* initial, ziU8* final); + +ziU8 Zi8GetPyPhonetic(ziWChar* text, ziU8 count, ziU16* initial, ziU16* final, ziU8* resultCount, ziU16* bestInitial, ziU16* bestFinal ZI_NEED_WORK) { + ziU8 firstInitial; + ziU8 pyFinal; + ziU8 pyInitial; + ziU8 convertedCount; + ziBool partial; + ziU8 result; + ziU8 outputIndex; + ziU8 partCount; + ziU16 value; + ziU8 index; + ziWChar converted[256]; + ziWChar* current; + ziU8 pinyin[12]; + + current = converted; + result = 0; + *resultCount = 0; + if (count == 0) { + Zi8LogError(0x135, ZI_WORK); + return 0; + } + convertedCount = 0; + for (index = 0; index < count; index++) { + if (((text[index] >= 0xF341) && (text[index] <= 0xF35A)) || ((text[index] >= 0x41) && (text[index] <= 0x5A))) { + if ((convertedCount != 0) && (current[convertedCount - 1] != 0xF360) && (current[convertedCount - 1] != 0x27)) { + current[convertedCount] = 0x27; + convertedCount++; + } + current[convertedCount] = (text[index] & 0xFF) + 0x20; + } else { + current[convertedCount] = text[index]; + } + convertedCount++; + } + + count = convertedCount; + outputIndex = 0; + *bestInitial = 0; + *bestFinal = 0; + while ((outputIndex < 0x10) && (count != 0)) { + initial[outputIndex] = 0; + final[outputIndex] = 0; + value = *current; + if (value < 0x61) { + goto check_pinyin_extension; + } + if (value <= 0x7A) { + goto pinyin_ascii; + } +check_pinyin_extension: + if (value < 0xF361) { + goto invalid_pinyin; + } + if (value <= 0xF37A) { + value += 0xC9F; + goto pinyin_initial; + } +invalid_pinyin: + initial[0] = 0xFFFF; + final[0] = 0xFFFF; + *bestInitial = 0xFFFF; + *bestFinal = 0xFFFF; + return 1; +pinyin_ascii: + value -= 0x61; +pinyin_initial: + firstInitial = Zi8PinyinInitials[value]; + if (firstInitial != 0) { + if (outputIndex == 0) { + *resultCount = *resultCount + 1; + } + result++; + initial[outputIndex] = 0x7E00; + final[outputIndex] = (ziU16)firstInitial << 9; + *bestInitial = initial[outputIndex]; + *bestFinal = final[outputIndex]; + count--; + if (count == 0) { + break; + } + current += 1; + if (((firstInitial & 0x80) != 0) && ((current[0] == 0x68) || (current[0] == 0xF368))) { + if (outputIndex == 0) { + *resultCount = *resultCount + 1; + } + final[outputIndex] += 0x200; + *bestInitial = initial[outputIndex]; + *bestFinal = final[outputIndex]; + count--; + if (count == 0) { + break; + } + current += 1; + } + } else if ((*current == 0xF369) || (*current == 0x69)) { + goto invalid_pinyin; + } + partial = 0; + for (index = 0; index < 4; index++) { + pinyin[index] = 0; + } + index = 0; + do { + while (1) { + if (index > 3) { + goto finish_final; + } + value = *current; + if ((value == 0x27) || (value == 0xF360) || (value == 0x20)) { + if (index != 0) { + partial = 1; + } + goto finish_final; + } + if ((value > 0xF330) && (value < 0xF336)) { + if (index != 0) { + partial = 1; + } + goto finish_final; + } + if ((value < 0x61) || (value > 0x7A)) { + if (value < 0xF361) { + goto finish_final; + } + value += 0xC9F; + if (value > 0x19) { + if (outputIndex == 0) { + *resultCount = *resultCount + 1; + } + goto finish_final; + } + } else { + value -= 0x61; + } + pinyin[index] = (ziU8)value + 1; + if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) == 0) { + break; + } + if (outputIndex == 0) { + *resultCount = *resultCount + 1; + } + current++; + index++; + count--; + if (count == 0) { + goto finish_final; + } + } + if (index > 2) { + pinyin[index] = 0; + partial = 1; + break; + } + pinyin[index + 1] = 0xFF; + if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) == 0) { + pinyin[index + 1] = 0; + pinyin[index] = 0; + partial = 1; + break; + } + if (outputIndex == 0) { + *resultCount = *resultCount + 1; + } + pinyin[index + 1] = 0; + current++; + index++; + count--; + } while (count != 0); + +finish_final: + if ((index > 3) && (count != 0) && ((*current == 0x27) || (*current == 0xF360) || (*current == 0x20))) { + if (outputIndex == 0) { + *resultCount = *resultCount + 1; + } + current++; + count--; + } + if (index > 3) { + partial = 1; + } + if (!partial) { + pinyin[index] = 0xFF; + if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) == 0) { + pinyin[index] = 0; + if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) != 0) { + if (firstInitial == 0) { + result++; + initial[outputIndex] = 0x7E00; + final[outputIndex] = 0x200; + } + initial[outputIndex] |= (ziU16)pyInitial << 3; + final[outputIndex] |= (ziU16)pyFinal << 3; + *bestInitial = initial[outputIndex]; + *bestFinal = final[outputIndex]; + } + } else { + if (firstInitial == 0) { + result++; + initial[outputIndex] = 0x7E00; + final[outputIndex] = 0x200; + } + initial[outputIndex] |= (ziU16)pyInitial << 3; + final[outputIndex] |= (ziU16)pyFinal << 3; + *bestInitial = initial[outputIndex]; + *bestFinal = final[outputIndex]; + if ((outputIndex == 0) && (count == 0)) { + pinyin[index] = 0; + if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) != 0) { + if (firstInitial == 0) { + *bestInitial = 0x7E00; + *bestFinal = 0x200; + } + *bestInitial |= (ziU16)pyInitial << 3; + *bestFinal |= (ziU16)pyFinal << 3; + } + } + } + } else { + if (Zi8GetPyFinal(pinyin, &pyInitial, &pyFinal) != 0) { + if (firstInitial == 0) { + result++; + initial[outputIndex] = 0x7E00; + final[outputIndex] = 0x200; + } + initial[outputIndex] |= (ziU16)pyInitial << 3; + final[outputIndex] |= (ziU16)pyFinal << 3; + *bestInitial = initial[outputIndex]; + *bestFinal = final[outputIndex]; + } else { + if ((index != 0) && (count != 0)) { + goto invalid_pinyin; + } + } + } + convertedCount = count; + if (count != 0) { + value = *current; + if ((value == 0x27) || (value == 0xF360) || (value == 0x20)) { + current++; + convertedCount = count - 1; + if (outputIndex == 0) { + *resultCount = *resultCount + 1; + } + } else if ((value > 0xF330) && ((ziU16)(value + 0xCCF) < 5)) { + initial[outputIndex] |= 7; + final[outputIndex] |= value + 0xCD0; + *bestInitial = initial[outputIndex]; + *bestFinal = final[outputIndex]; + convertedCount = count - 1; + current++; + if (outputIndex == 0) { + *resultCount = *resultCount + 1; + } + if ((convertedCount != 0) && ((*current == 0x27) || (*current == 0xF360) || (*current == 0x20))) { + convertedCount = count - 2; + current++; + if (outputIndex == 0) { + *resultCount = *resultCount + 1; + } + } + } + } + count = convertedCount; + outputIndex++; + } + if ((*resultCount > 1) && (text[*resultCount - 1] > 0xF340) && (text[*resultCount - 1] < 0xF35B)) { + *resultCount = *resultCount - 1; + } + return result; + +} + +ziBool Zi8GetPyFinal(ziU8* pinyin, ziU8* initial, ziU8* final) { + ziU8 index = 0; + ziU8 row; + row = 0; + goto check_row; +scan_row: + while (index < 4) { + if (pinyin[index] != Zi8PinyinFinals[row][index]) { + break; + } + index++; + } + if (index < 4) { + goto next_row; + } + *initial = Zi8PinyinFinals[row][4]; + *final = Zi8PinyinFinals[row][5]; + return 1; +next_row: + row++; + index = 0; +check_row: + if (row < 0x36) { + goto scan_row; + } + return 0; +} + +ziS32 Zi8GetBpmfPhonetic(ziWChar* text, ziU8 count, ziU16* initial, ziU16* final, ziU16* bestInitial, ziU16* bestFinal ZI_NEED_WORK) { + ziU16 value; + ziU32 resultCount = 0; + + Zi8LogError(0x64, ZI_WORK); + if (count == 0) { + Zi8ReplaceLastError(0x135, ZI_WORK); + return 0; + } + value = text[0]; + if (value < 0xF305) { + Zi8ReplaceLastError(0x154, ZI_WORK); + return 0; + } + value -= 0xF305; + if (value >= 0x25) { + Zi8ReplaceLastError(0x154, ZI_WORK); + return 0; + } + if (value < 0x15) { + *initial = 0x7E00; + *final = ((ziU16)Zi8BpmfInitials[value] & 0x7F) << 9; + resultCount++; + count--; + if (count == 0) { + *bestInitial = *initial; + *bestFinal = *final; + if ((value >= 0xE) && (value <= 0x14)) { + *bestInitial |= 0x1F8; + *bestFinal |= 0x38; + } + return resultCount; + } + text++; + if (*text == 0xF360) { + resultCount++; + count--; + if (count == 0) { + return resultCount; + } + Zi8ReplaceLastError(0x156, ZI_WORK); + return 0; + } + } else { + *initial = 0x7E00; + *final = 0x200; + } + + value = *text - 0xF305; + switch ((ziS32)value) { + case 0x22: + goto bpmf_value_22; + case 0x23: + goto bpmf_value_23; + case 0x24: + goto bpmf_value_24; + default: + goto set_bpmf_initial; + } +bpmf_value_22: + *final |= 0x80; + *initial |= 0x180; + resultCount++; + count--; + if (count == 0) { + *bestInitial = *initial | 0x78; + *bestFinal = *final | 0x38; + return resultCount; + } + text++; + goto after_bpmf_initial; +bpmf_value_23: + *final |= 0x100; + *initial |= 0x180; + resultCount++; + count--; + if (count == 0) { + *bestInitial = *initial | 0x78; + *bestFinal = *final | 0x38; + return resultCount; + } + text++; + goto after_bpmf_initial; +bpmf_value_24: + *final |= 0x180; + *initial |= 0x180; + resultCount++; + count--; + if (count == 0) { + *bestInitial = *initial | 0x78; + *bestFinal = *final | 0x38; + return resultCount; + } + text++; + goto after_bpmf_initial; +set_bpmf_initial: + if ((*text < 0xF331) || (*text > 0xF335)) { + *initial |= 0x180; + } +after_bpmf_initial: + + value = *text - 0xF305; + if ((value > 0x14) && (value < 0x22)) { + *final |= (ziU16)Zi8BpmfInitials[value] << 3; + *initial |= 0x78; + resultCount++; + count--; + if (count == 0) { + *bestInitial = *initial; + *bestFinal = *final; + return resultCount; + } + text++; + } else if ((*text < 0xF331) || (*text > 0xF335) || ((*initial & 0x180) == 0x180)) { + *final |= 0x38; + *initial |= 0x78; + } + + value = *text; + if (value < 0xF331) { + Zi8ReplaceLastError(0x155, ZI_WORK); + return 0; + } + value -= 0xF330; + if (value > 5) { + Zi8ReplaceLastError(0x155, ZI_WORK); + return 0; + } + *initial |= 7; + *final |= value; + *bestInitial = *initial; + *bestFinal = *final; + resultCount++; + count--; + if (count != 0) { + Zi8ReplaceLastError(0x157, ZI_WORK); + return 0; + } + return resultCount; +} + +ziU16 Zi8GetPCode(ziU8* table, ziU8* node) { + ziU16 index = ((ziU16)node[8] << 2) | (((ziU16)node[9] & 0x80) >> 6); + return ((((ziU16)node[9] >> 4) & 7) | (ziU16)table[index] | ((ziU16)table[index + 1] << 8)); +} diff --git a/libs/RVLMiddleware/eZiText/src/clib/zikorean.c b/libs/RVLMiddleware/eZiText/src/clib/zikorean.c new file mode 100644 index 00000000..dfab9f19 --- /dev/null +++ b/libs/RVLMiddleware/eZiText/src/clib/zikorean.c @@ -0,0 +1,423 @@ +#include +#include + +ziU32 Zi8GetTableAddress(ziU8 lang, ziU8 tableIdx, ziPtr workData); +ziU16 Zi8GetTableCount(ziU8 lang, ziU8 tableIdx, ziPtr workData); + +ziU8 Zi8_814813FC(ziWChar character, ziU8* result, ziU16* index, ziPtr workData) { + ziU16 i; + ziU8* table; + + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 5, workData); + i = 0; + while (table[i] != 0) { + if (character == table[i]) { + *index = i; + *result = table[i]; + Zi8LogError(0x64, workData); + return 1; + } + i++; + } + Zi8LogError(0x2A8, workData); + return 0; +} + +ziU8 Zi8_81481E6C(ziU16* resultIndex, ziU16* input, ziU8 type, ziU16 count, ziPtr workData); + +ziU8 Zi8GetKoreanCandidates(ziGetParam* params, ziU8* argument, + ziPtr workData) { + struct { + ziU8 characterIndex; + ziU8 matched; + ziU8 elementIndex; + ziU8 reserved; + ziU16 index; + ziU16 currentCandidate; + ziU16 inputIndex; + ziU16 nextIndex; + ziU16 tableCount31; + ziU16 tableCount6; + ziU16 tableCount3; + ziU16 tableCount0; + ziU8* table31; + ziU8* table2; + ziU8* table1; + } state; + ziU16 buffer[100]; + ziU8 result; + ziU16 currentCharacter; + ziU8* selectedTable; + + state.nextIndex = 0; + result = 0; + state.characterIndex = 0xFF; + state.currentCandidate = params->firstCandidate; + params->unk_0x20 = 0; + params->count = 0; + params->letters = 0; + if ((argument != 0) && (*argument != 0)) { + Zi8LogError(0x7D0, workData); + return 0; + } + if ((params->elementCount == 0) || (params->elementCount > 100)) { + Zi8LogError(0x64, workData); + return 0; + } + + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 4, workData); + state.table1 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 1, workData); + state.table2 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 2, workData); + state.table31 = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x31, workData); + state.tableCount0 = Zi8GetTableCount(ZI8_LANG_KO, 0, workData); + state.tableCount3 = Zi8GetTableCount(ZI8_LANG_KO, 3, workData); + state.tableCount6 = Zi8GetTableCount(ZI8_LANG_KO, 6, workData); + state.tableCount31 = Zi8GetTableCount(ZI8_LANG_KO, 0x31, workData); + + for (state.elementIndex = 0; state.elementIndex < params->elementCount; + state.elementIndex++) { + currentCharacter = params->elements[state.elementIndex]; + + if ((currentCharacter >= 0x61) && (currentCharacter <= 0x7A)) { + buffer[state.elementIndex] = state.table1[(currentCharacter - 0x61) * 2]; + } else if ((currentCharacter >= 0x41) && (currentCharacter <= 0x5A)) { + buffer[state.elementIndex] = state.table1[(currentCharacter - 0x41) * 2 + 1]; + } else { + state.matched = 0; + for (; state.table2[state.matched * 3] != 0; state.matched++) { + if (currentCharacter == state.table2[state.matched * 3]) break; + } + if (state.table2[(state.matched * 3)] == 0) { + Zi8LogError(0x161, workData); + return 0; + } + buffer[state.elementIndex] = + (state.table2[(state.matched * 3) + 1] << 8) | + state.table2[(state.matched * 3) + 2]; + } + } + + for (currentCharacter = 0; currentCharacter < state.elementIndex; currentCharacter++) { + state.inputIndex = 0; + if (Zi8_814813FC(buffer[currentCharacter], (ziU8*)&state.characterIndex, + (ziU16*)&state.inputIndex, workData) == 0) { + state.matched = 0; + } else { + state.matched = Zi8_81481E6C((ziU16*)&state.nextIndex, + &buffer[currentCharacter + 1], + state.characterIndex, + (state.elementIndex - currentCharacter) - 1, + workData); + if ((((struct __zi8_work_data_s*)workData)->unk_0x1B30 == 1) && (state.characterIndex < 0x1F)) { + switch (state.characterIndex) { + case 1: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1E, workData); + break; + case 2: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1F, workData); + break; + case 4: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x20, workData); + break; + case 7: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x21, workData); + break; + case 8: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x22, workData); + break; + case 9: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x23, workData); + break; + case 0x11: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x24, workData); + break; + case 0x12: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x25, workData); + break; + case 0x13: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x26, workData); + break; + case 0x15: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x27, workData); + break; + case 0x16: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x28, workData); + break; + case 0x17: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x29, workData); + break; + case 0x18: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2A, workData); + break; + case 0x19: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2B, workData); + break; + case 0x1A: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2C, workData); + break; + case 0x1B: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2D, workData); + break; + case 0x1C: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2E, workData); + break; + case 0x1D: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x2F, workData); + break; + case 0x1E: + selectedTable = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x30, workData); + break; + default: + break; + } + } + } + if (state.matched == 0) { + if (state.currentCandidate == 0) { + for (state.index = 0; state.index < state.tableCount31; state.index++) { + if (((ziU16)state.table31[(state.index * 3)] == buffer[currentCharacter]) && + ((ziU16)state.table31[(state.index * 3) + 1] == buffer[currentCharacter + 1])) { + if (currentCharacter == 0) { + params->count = 1; + } + params->candidates[result] = + state.tableCount0 + state.table31[(state.index * 3) + 2]; + result++; + currentCharacter++; + break; + } + } + if (state.index == state.tableCount31) { + params->candidates[result] = buffer[currentCharacter]; + if (buffer[currentCharacter] < 0xFF) { + if (currentCharacter == 0) { + params->count = 1; + } + params->candidates[result] += state.tableCount0; + result++; + } + } + } else { + state.index = 0; + while ((state.index < state.tableCount31) && + (((ziU16)state.table31[(state.index * 3)] != buffer[currentCharacter]) || + ((ziU16)state.table31[(state.index * 3) + 1] != buffer[currentCharacter + 1]))) { + state.index++; + } + if (state.index == state.tableCount31) { + state.currentCandidate--; + } + if (currentCharacter == 0) { + params->count = 1; + } + } + } else { + if (state.tableCount6 == 0) { + state.nextIndex += state.inputIndex * state.tableCount3; + } + if (state.currentCandidate == 0) { + params->candidates[result] = + (selectedTable[state.nextIndex * 2] << 8) | selectedTable[state.nextIndex * 2 + 1]; + if ((state.tableCount6 != 0) && (((struct __zi8_work_data_s*)workData)->unk_0x1B30 == 0)) { + params->candidates[result] += state.inputIndex * state.tableCount3; + } + result++; + } else { + state.currentCandidate--; + } + if (currentCharacter == 0) { + params->count = state.matched + 1; + } + currentCharacter += state.matched; + } + if (result >= params->maxCandidates) { + break; + } + } + params->letters = result; + Zi8LogError(0x64, workData); + return result; +} + +ziU8 Zi8_81481E6C(ziU16* resultIndex, ziU16* input, ziU8 type, ziU16 count, ziPtr workData) { + ziU16 nestedScratch; + ziU16 nestedIndexStorage; + ziU16 index1; + ziU16 index2; + ziU16 index3; + ziU16 index4; + ziU16 firstCharacter; + ziU16 tableCount; + ziU8 mappedCharacter; + ziU8* table; + + firstCharacter = input[0]; + mappedCharacter = 0xFF; + if (((struct __zi8_work_data_s*)workData)->unk_0x1B30 == 0) { + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 3, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 3, workData); + } else { + switch (type) { + case 1: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0xB, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0xB, workData); + break; + case 2: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0xC, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0xC, workData); + break; + case 4: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0xD, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0xD, workData); + break; + case 7: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0xE, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0xE, workData); + break; + case 8: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0xF, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0xF, workData); + break; + case 9: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x10, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x10, workData); + break; + case 0x11: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x11, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x11, workData); + break; + case 0x12: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x12, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x12, workData); + break; + case 0x13: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x13, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x13, workData); + break; + case 0x15: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x14, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x14, workData); + break; + case 0x16: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x15, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x15, workData); + break; + case 0x17: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x16, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x16, workData); + break; + case 0x18: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x17, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x17, workData); + break; + case 0x19: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x18, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x18, workData); + break; + case 0x1A: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x19, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x19, workData); + break; + case 0x1B: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1A, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x1A, workData); + break; + case 0x1C: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1B, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x1B, workData); + break; + case 0x1D: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1C, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x1C, workData); + break; + case 0x1E: + table = (ziU8*)Zi8GetTableAddress(ZI8_LANG_KO, 0x1D, workData); + tableCount = Zi8GetTableCount(ZI8_LANG_KO, 0x1D, workData); + break; + } + } + *resultIndex = 0; + if ((count < 1) || (firstCharacter >= 0xFF)) { + return 0; + } + + index1 = *resultIndex; + for (; index1 < tableCount; index1++) { + if (table[index1 * 4] >= firstCharacter) { + break; + } + } + if ((index1 >= tableCount) || (firstCharacter != table[index1 * 4])) { + return 0; + } + if ((count < 2) || ((firstCharacter = input[1]) >= 0xFF)) { + *resultIndex = index1; + return 1; + } + + index2 = index1; + for (; index2 < tableCount; index2++) { + if ((table + index2 * 4)[1] >= firstCharacter) { + break; + } + } + if ((index2 >= tableCount) || (firstCharacter != (table + index2 * 4)[1]) || + (input[0] != table[index2 * 4])) { + *resultIndex = index1; + return 1; + } + if ((count < 3) || ((firstCharacter = input[2]) >= 0xFF)) { + *resultIndex = index2; + return 2; + } + + index3 = index2; + for (; index3 < tableCount; index3++) { + if ((table + index3 * 4)[2] >= firstCharacter) { + break; + } + } + if ((index3 >= tableCount) || (firstCharacter != (table + index3 * 4)[2]) || + (input[1] != (table + index3 * 4)[1]) || (input[0] != table[index3 * 4])) { + if ((Zi8_814813FC(input[1], &mappedCharacter, &nestedScratch, workData) != 0) && + (Zi8_81481E6C(&nestedIndexStorage, input + 2, mappedCharacter, 1, workData) != 0)) { + *resultIndex = index1; + return 1; + } + *resultIndex = index2; + return 2; + } + if ((count < 4) || ((firstCharacter = input[3]) >= 0xFF)) { + *resultIndex = index3; + return 3; + } + + index4 = index3; + for (; index4 < tableCount; index4++) { + if ((table + index4 * 4)[3] >= firstCharacter) { + break; + } + } + if ((index4 >= tableCount) || (firstCharacter != (table + index4 * 4)[3]) || + (input[2] != (table + index4 * 4)[2]) || (input[1] != (table + index4 * 4)[1]) || + (input[0] != table[index4 * 4])) { + if ((Zi8_814813FC(input[2], &mappedCharacter, &nestedScratch, workData) != 0) && + (Zi8_81481E6C(&nestedIndexStorage, input + 3, mappedCharacter, 1, workData) != 0)) { + *resultIndex = index2; + return 2; + } + *resultIndex = index3; + return 3; + } + if ((count < 5) || ((firstCharacter = input[4]) >= 0xFF)) { + *resultIndex = index4; + return 4; + } + if ((Zi8_814813FC(input[3], &mappedCharacter, &nestedScratch, workData) != 0) && + (Zi8_81481E6C(&nestedIndexStorage, input + 4, mappedCharacter, 1, workData) != 0)) { + *resultIndex = index3; + return 3; + } + *resultIndex = index4; + return 4; +} diff --git a/tools/decomp-assist/zi8dawg.attempts.md b/tools/decomp-assist/zi8dawg.attempts.md new file mode 100644 index 00000000..11d8cb01 --- /dev/null +++ b/tools/decomp-assist/zi8dawg.attempts.md @@ -0,0 +1,33 @@ +Reconstructed all six functions. NextDawgGroup matches 68/68 instructions; +Zi8SyllablesROMdata matches 66/66. Neither unit has a .data string pool; +pool_diff.py raises KeyError, and the gate confirms identical empty pools. + +Zi8MatchROMdata0: +1. Three-key buffer, full-width incoming count: 30.915709%, 537/522 instructions. +2. Status branch inversion and common failure exit: 44.220306%, 531/522. +3. U16 path index and explicit header byte composition: 45.16092%, 533/522. +Retained attempt 3. Graph traversal, field access and register allocation differ. +The key buffer holds at most two converted keys and a terminator, not the +forty entries inferred by Ghidra from neighboring stack storage. + +Zi8MatchROMdata1: +1. Byte-sized group index: 98.203125%, 130/128 instructions. +2. Assign returned table address directly to the workspace: 98.47656%, 127/128. +3. Scalar table address local with pointer conversion at assignment: 99.765625%, +128/128, 5 differences. Retained attempt 3; r26/r27 allocation differs. + +Zi8MatchROMdata2: +1. Narrow count/language/capacity/mode/status parameters: 258/236 instructions. +2. Byte-sized result and output count: 265/236. +3. Full-width parameters and a counted prefix loop: 249/236. +Objdiff reports no fuzzy percentage for this function in all three builds. +Retained attempt 3. Instruction count, segment control flow and allocation differ. +Corrected the unsigned wide-character sentinel comparison to 0xeff1. + +Zi8MatchROMdata: +1. Unsigned candidate result from the segment helper: 65.77665%, 225/197. +2. Full-width entry point result: 65.34518%, 225/197. +3. Full-width incoming count, remove its alias: 61.335026%, 234/197. +Retained the attempt 1 body. With the retained full-width segment-helper +signature it measures 58.106598%, 237/197 instructions. Group iteration and +fallback control flow differ. diff --git a/tools/decomp-assist/zi8getc2.attempts.md b/tools/decomp-assist/zi8getc2.attempts.md new file mode 100644 index 00000000..aa0ca26a --- /dev/null +++ b/tools/decomp-assist/zi8getc2.attempts.md @@ -0,0 +1,46 @@ +Reconstructed all 17 functions in target order. Empty string pools are identical. +Exact: fuzzy setters, Latin search order, global size, both candidate wrappers, +duplicate-buffer initialization, memset, memcpy and maximum word length. + +Zi8GetDataSignature: +1. length > capacity instead of capacity < length: 99.05797%, 69/69 instructions. +2. Reuse table selector as U16 length: 99.347824%, 69/69, 9 differences. +3. Reorder locals and widen return: 98.478264%, 69/69, 10 differences. +Retained attempt 2. Only saved register assignment differs. + +Zi8GetEngineSignature: +1. Separate OEM/build locals: 95.85268%, 219/224 instructions. +2. Explicit quotient/remainder arithmetic: 95.71875%, 219/224. +3. Reordered major/minor locals and reused identifier value: 95.58036%, 219/224. +Retained reconstruction, 95.95982%; minor version is held in a register instead +of a stack slot, with a different saved-register frame. + +Zi8AlphaSignature: +1. Counted for loops instead of postdecrement while: 63.64706%, 191/204. +2. U32 candidate count: 63.887257%, 188/204. +3. Widen helper return types and restore U16 candidate count: 63.32353%, 189/204. +Retained reconstruction, 67.61275%, 188/204; stack locals and control flow differ. + +Zi8ZhSignature: +1. U32 candidate count: 25.711538%, 209/208. +2. U32 engine length: 29.216347%, 202/208. +3. Widen helper returns and restore U16 lengths: 22.509615%, 212/208. +Retained attempt 2; integer promotion, loops and allocation differ. + +Zi8GetCandidatesOrCount: +1. Unsigned signature result: 74.48703%, 760/694. +2. U8 result count: 74.85447%, 764/694. +3. Restore full-width count with widened signature helper returns: 75.452446%, 756/694. +Retained reconstruction, 75.64553%, 754/694; branch layout and allocation differ. + +Zi8IsDupWChar: +1. U16 position increment: 99.20635%, 63/63, 9 differences. +2. Signed position with explicit U16 index: 96.666664%, 64/63. +3. U32 position and signed duplicate flag: 96.666664%, 64/63. +Retained attempt 1; character, duplicate and position register allocation differs. + +Zi8IsDupWordW: +1. Unsigned duplicate flag: 85.76259%, 140/139. +2. Explicit loop break: 90.22302%, 140/139. +3. U8 cache position: 88.78417%, 142/139. +Retained attempt 2; loop layout and cache index allocation differ. diff --git a/tools/decomp-assist/zi8match.attempts.md b/tools/decomp-assist/zi8match.attempts.md new file mode 100644 index 00000000..55ba6f66 --- /dev/null +++ b/tools/decomp-assist/zi8match.attempts.md @@ -0,0 +1,25 @@ +Zi8PriMatchNextChar, Zi8ExactMatchNextChar, Zi8SecMatchChar, +Zi8PriMatchNextComp, Zi8SecMatchComp and Zi8GetPCode match on reconstruction. +The unit has no .data string pool; pool_diff.py raises KeyError, gate confirms identical empty pools. + +Zi8MatchPhonetic: reconstructed dictionary index separately from phonetic code. +1. Byte-sized match/alternate state: 359/363 instructions, 77.62259%. +2. Inverted remaining-count initialization: 359/363, 77.242424%. +3. Direct alternate parameter and numParts == 1: 348/363, 72.46832%. +Retained 359/363, 77.66942%; stack layout, control flow and allocation differ. + +Zi8GetPyPhonetic: +1. Four-byte pinyin buffer: 726/718, 75.158775%. +2. U16 spelling index: 726/718, 74.785515%. +3. Int spelling index: 701/718, 72.214485%. +Retained 726/718, 75.160164%; branch structure and allocation differ. + +Zi8GetPyFinal: +1. Shared final-row pointer: 58/53, 62.28302%. +2. Reordered index/row declarations: 53/53, 99.245285%, 8 instruction differences. +3. U16 row index: 53/53, 98.86793%, 12 differences. +Retained 53/53, 99.245285%; r6/r7 allocation in result loads differs. + +Zi8GetBpmfPhonetic: +1. Deferred result initialization: 309/309, 99.23948%. +2. Unsigned result counter and direct text subtraction: 309/309, 100%, diffs 0. diff --git a/tools/decomp-assist/zikorean.attempts.md b/tools/decomp-assist/zikorean.attempts.md new file mode 100644 index 00000000..eb429692 --- /dev/null +++ b/tools/decomp-assist/zikorean.attempts.md @@ -0,0 +1,10 @@ +Both table helpers match exactly on reconstruction: Zi8_814813FC 49/49 +instructions, Zi8_81481E6C 629/629. Both have ctxdiff diffs 0. +The string pools are empty and identical. + +Zi8GetKoreanCandidates: +1. For loop with an explicit break in character mapping: 68.13893%, 629/619 instructions. +2. Full-width result and character index: 67.34895%, 600/619. +3. Typed three-byte character/sequence records: 66.96769%, 629/619. +Retained attempt 1. The main routine still differs in stack state, loop structure +and register allocation. No register/volatile keywords were retained. -- 2.49.1 From 856a31f8c997ca669e8f6251726a3d00d8163b9a Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:55:53 -0500 Subject: [PATCH 3/7] MSL: printf, wprintf, ansi_fp, time, scanf, strtold (worker 969bc2aa) (#339) --- README.md | 4 +- configure.py | 12 +- libs/MSL/include/internal/format_runtime.h | 41 + libs/MSL/matching-attempts.log | 43 + libs/MSL/src/MSL_Common/printf.c | 1360 ++++++++++++++++++++ libs/MSL/src/MSL_Common/scanf.c | 817 ++++++++++++ libs/MSL/src/MSL_Common/strtold.c | 659 ++++++++++ libs/MSL/src/MSL_Common/time.c | 721 +++++++++++ libs/MSL/src/MSL_Common/wprintf.c | 1320 +++++++++++++++++++ libs/MSL/src/MSL_Common_Embedded/ansi_fp.c | 671 ++++++++++ 10 files changed, 5640 insertions(+), 8 deletions(-) create mode 100644 libs/MSL/include/internal/format_runtime.h create mode 100644 libs/MSL/matching-attempts.log create mode 100644 libs/MSL/src/MSL_Common/printf.c create mode 100644 libs/MSL/src/MSL_Common/scanf.c create mode 100644 libs/MSL/src/MSL_Common/strtold.c create mode 100644 libs/MSL/src/MSL_Common/time.c create mode 100644 libs/MSL/src/MSL_Common/wprintf.c create mode 100644 libs/MSL/src/MSL_Common_Embedded/ansi_fp.c diff --git a/README.md b/README.md index 1356447f..5daee4e1 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 89.61% | 79.32% | 56.95% | 88.27% | +| 90.99% | 80.50% | 56.95% | 88.40% | -units 758/1027 complete, functions 11514/12563 matched. +units 758/1027 complete, functions 11561/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/configure.py b/configure.py index 8d4df0d8..60fa17b4 100644 --- a/configure.py +++ b/configure.py @@ -1944,7 +1944,7 @@ config.libs = [ Object(Matching, "MSL_Common/alloc.c"), Object(Matching, "MSL_Common/errno.c"), Object(Matching, "MSL_Common/ansi_files.c"), - Object(NonMatching, "MSL_Common_Embedded/ansi_fp.c"), + Object(NonMatching, "MSL_Common_Embedded/ansi_fp.c", extra_cflags=["-Cpp_exceptions on"]), Object(Matching, "MSL_Common/ctype.c"), Object(NonMatching, "MSL_Common/locale.c"), Object(Matching, "MSL_Common/arith.c", extra_cflags=["-Cpp_exceptions on"]), @@ -1958,19 +1958,19 @@ config.libs = [ Object(Matching, "MSL_Common/mem_funcs.c"), Object(Matching, "MSL_Common/math_api.c"), Object(Matching, "MSL_Common/misc_io.c"), - Object(NonMatching, "MSL_Common/printf.c"), + Object(NonMatching, "MSL_Common/printf.c", extra_cflags=["-Cpp_exceptions on"]), Object(Matching, "MSL_Common/qsort.c", extra_cflags=["-Cpp_exceptions on"]), Object(Matching, "MSL_Common/rand.c"), - Object(NonMatching, "MSL_Common/scanf.c"), + Object(NonMatching, "MSL_Common/scanf.c", extra_cflags=["-Cpp_exceptions on"]), Object(Matching, "MSL_Common/signal.c", extra_cflags=["-Cpp_exceptions on"]), Object(Matching, "MSL_Common/string.c"), Object(Matching, "MSL_Common/float.c"), - Object(NonMatching, "MSL_Common/strtold.c"), + Object(NonMatching, "MSL_Common/strtold.c", extra_cflags=["-Cpp_exceptions on"]), Object(Matching, "MSL_Common/strtoul.c", extra_cflags=["-Cpp_exceptions on"]), - Object(NonMatching, "MSL_Common/time.c"), + Object(NonMatching, "MSL_Common/time.c", extra_cflags=["-Cpp_exceptions on"]), Object(Matching, "MSL_Common/wctype.c"), Object(Matching, "MSL_Common/wmem.c"), - Object(NonMatching, "MSL_Common/wprintf.c"), + Object(NonMatching, "MSL_Common/wprintf.c", extra_cflags=["-Cpp_exceptions on"]), Object(Matching, "MSL_Common/wstring.c"), Object(Matching, "MSL_Common/wchar_io.c"), Object(Matching, "PPC_EABI/time.dolphin.c"), diff --git a/libs/MSL/include/internal/format_runtime.h b/libs/MSL/include/internal/format_runtime.h new file mode 100644 index 00000000..786304fe --- /dev/null +++ b/libs/MSL/include/internal/format_runtime.h @@ -0,0 +1,41 @@ +#ifndef MSL_FORMAT_RUNTIME_H +#define MSL_FORMAT_RUNTIME_H +#include +#include +#include +#include +#include +#include +#include +#include +#define SIGDIGLEN 36 +#define LDBL_MANT_DIG 53 +#define LDBL_MAX_EXP 1024 +#define LDBL_MIN_EXP (-1021) +#define DBL_MAX 1.7976931348623157e308 +#define DBL_MIN 2.2250738585072014e-308 +#define DBL_EPSILON 2.2204460492503131e-16 +#define EOF (-1) +typedef long ptrdiff_t; +typedef long long intmax_t; +typedef unsigned long long uintmax_t; +typedef struct { + char sign; + short exp; + struct { unsigned char length; unsigned char text[SIGDIGLEN]; } sig; +} decimal; +typedef struct { char style; short digits; } decform; +enum __ReadProcActions { __GetAChar, __UngetAChar, __TestForError }; +typedef struct { char* CharStr; size_t MaxCharCount; size_t CharsWritten; } __OutStrCtrl; +typedef struct { char* NextChar; int NullCharDetected; } __InStrCtrl; +void __num2dec(const decform*, double, decimal*); +double __dec2num(const decimal*); +size_t __fwrite(const void*, size_t, size_t, FILE*); +int __StringRead(void*, int, int); +unsigned long __strtoul(int, int, int (*)(void*, int, int), void*, int*, int*, int*); +unsigned long long __strtoull(int, int, int (*)(void*, int, int), void*, int*, int*, int*); +long double __strtold(int, int (*)(void*, int, int), void*, int*, int*); +int wctomb(char*, wchar_t); +double nan(const char*); +#define signbit(x) __signbitd(x) +#endif diff --git a/libs/MSL/matching-attempts.log b/libs/MSL/matching-attempts.log new file mode 100644 index 00000000..d2de1d6a --- /dev/null +++ b/libs/MSL/matching-attempts.log @@ -0,0 +1,43 @@ +MSL restoration, 43U, baseline 0 exact functions and 0 matched code/data in all six units. +Sources: zeldaret/tp MSL printf/wprintf; public Mario Strikers Charged MSL decimal/scanning/strtold references in /tmp/mscharged-new; time reference experiments in /tmp. All measurements were rebuilt locally. + +printf long2str: corrected 32-bit minimum constant; 138/138 instructions, zero differences. +printf float2str: removed unnecessary short narrowing from exponent update; 500/500 instructions, zero differences. +printf double2hex: +1. Deferred output pointer initialization until after width validation: 242/242, 97 differences. +2. Moved output pointer declaration after decimal: 242/242, same 97 differences. +3. Copied incoming format into a local format: 244/242 and larger frame; rejected. +4. Reconstructed the actual zero-value path and ordinary literal 0x0p0 from target assembly. +5. Corrected unconditional exponent subtraction and explicit byte narrowing based on target assembly. Remaining struct argument copies use floating loads/stores instead of integer loads/stores; conversion-loop scheduling differs. +printf __pformatter: +1. Moved format declaration after buffers: 535/535, same 321 differences. +2. Initialized format to zero: 540/535, additional stores; rejected. +3. Copied parsed format before dispatch, with both locals declared at function entry: 515/535 after target semantic fixes, larger frame; rejected. +4. Removed hex-prefix zero-fill handling absent from this binary. Remaining mismatch is by-value struct copy code generation; target has 535 instructions, source 511. + +wprintf double2hex: +1. Used the Charged reference implementation: 246/242, different frame/scheduling; rejected. +2. Deferred output pointer initialization: 243/242, register and copy differences remained. +3. Moved output pointer declaration after decimal: 243/242, unchanged differences. +4. Reconstructed zero-value output and unconditional exponent subtraction from target assembly. Explicit byte narrowing improved conversion instructions; struct-copy and loop scheduling remain open. +wprintf __wpformatter: +1. Initialized local format: 596/593, additional stores; rejected. +2. Moved format declaration after buffers: 591/593, changed scheduling; rejected. +3. Copied parsed format before dispatch: 595/593, larger frame; rejected. +4. Corrected the imported narrow Pascal-string branch to read and advance its actual input pointer, eliminating an uninitialized output-pointer read. +5. Removed hex-prefix zero-fill handling absent from the target. Remaining struct-copy code generation and register scheduling differ. +wprintf __wStringWrite: used the real callback result from wmemcpy; 27/27 instructions, zero differences. + +ansi_fp: all ten functions have zero ctxdiff differences. Exception metadata enabled for this unit, using the same setting as matching MSL siblings. Code 6512/6512 and data 780/780. + +time strftime: +1. Assigned default calendar fields individually: 906/913, scheduling differences; rejected. +2. Initialized the default calendar at declaration: 913/913, 34 remaining string-offset differences; retained. +3. Moved format-pointer declaration before locale: 913/913, 76 differences; rejected. +4. Replaced imported pooled-string address arithmetic with ordinary literals. Reconstructed real asctime/ctime formatting to account for the original literals, rather than retaining fake calls with missing format arguments. +5. With ordinary source-token order restored, strftime has 913/913 instructions and zero ctxdiff differences. Keeping the shared asctime result local to asctime restored the target BSS symbols; exception records for the additional real library functions still differ at unit level. No padding or forced placement was added. + +scanf: all four functions have zero ctxdiff differences, code 5484/5484 and data 388/388. The formatter retains its actual secure-mode parameter. +strtold: __strtold has 1277/1277 instructions and strtod 44/44, both zero differences. Removed the imported inline qualifier from the public strtod wrapper so the real target symbol is emitted. Code 5284/5284 and data 112/112. + +Exception metadata settings change only owned NonMatching units; configure.py status flags remain NonMatching. Clean gates require the original DOL SHA1 and zero baseline regressions. Raw instruction-exact counts can be lower than objdiff exact counts because the varargs conditional branch to an external register-save helper is compared without relocation normalization by gate.py. These counts are reported separately; they were not patched or hidden. diff --git a/libs/MSL/src/MSL_Common/printf.c b/libs/MSL/src/MSL_Common/printf.c new file mode 100644 index 00000000..51c0d272 --- /dev/null +++ b/libs/MSL/src/MSL_Common/printf.c @@ -0,0 +1,1360 @@ +#include + + + + + + + + + + + + + +#define LDBL_MANT_DIG 53 + +#define TARGET_FLOAT_BITS 64 +#define TARGET_FLOAT_BYTES (TARGET_FLOAT_BITS / 8) +#define TARGET_FLOAT_MAX_EXP LDBL_MAX_EXP +#define TARGET_FLOAT_MANT_DIG LDBL_MANT_DIG +#define TARGET_FLOAT_IMPLICIT_J_BIT 1 +#define TARGET_FLOAT_MANT_BITS (TARGET_FLOAT_MANT_DIG - TARGET_FLOAT_IMPLICIT_J_BIT) +#define TARGET_FLOAT_EXP_BITS (TARGET_FLOAT_BITS - TARGET_FLOAT_MANT_BITS - 1) + + + +enum justification_options { left_justification, right_justification, zero_fill }; + +enum sign_options { only_minus, sign_always, space_holder }; + +enum argument_options { + normal_argument, + char_argument, + short_argument, + long_argument, + long_long_argument, + wchar_argument, + + intmax_argument, + size_t_argument, + ptrdiff_argument, + + long_double_argument, +}; + +typedef struct { + unsigned char justification_options; + unsigned char sign_options; + unsigned char precision_specified; + unsigned char alternate_form; + unsigned char argument_options; + unsigned char conversion_char; + int field_width; + int precision; +} print_format; + +static const char* parse_format(const char* format_string, va_list* arg, print_format* format) { + print_format f; + const char* s = format_string; + int c; + int flag_found; + f.justification_options = right_justification; + f.sign_options = only_minus; + f.precision_specified = 0; + f.alternate_form = 0; + f.argument_options = normal_argument; + f.field_width = 0; + f.precision = 0; + + if ((c = *++s) == '%') { + f.conversion_char = c; + *format = f; + return s + 1; + } + + for (;;) { + flag_found = 1; + + switch (c) { + case '-': + f.justification_options = left_justification; + break; + case '+': + f.sign_options = sign_always; + break; + case ' ': + if (f.sign_options != sign_always) { + f.sign_options = space_holder; + } + break; + case '#': + f.alternate_form = 1; + break; + case '0': + if (f.justification_options != left_justification) { + f.justification_options = zero_fill; + } + break; + default: + flag_found = 0; + break; + } + + if (flag_found) { + c = *++s; + } else { + break; + } + } + + if (c == '*') { + if ((f.field_width = va_arg(*arg, int)) < 0) { + f.justification_options = left_justification; + f.field_width = -f.field_width; + } + + c = *++s; + } else { + while (isdigit(c)) { + f.field_width = (f.field_width * 10) + (c - '0'); + c = *++s; + } + } + + if (f.field_width > 509) { + f.conversion_char = 0xFF; + *format = f; + return s + 1; + } + + if (c == '.') { + f.precision_specified = 1; + + if ((c = *++s) == '*') { + if ((f.precision = va_arg(*arg, int)) < 0) { + f.precision_specified = 0; + } + + c = *++s; + } else { + while (isdigit(c)) { + f.precision = (f.precision * 10) + (c - '0'); + c = *++s; + } + } + } + + flag_found = 1; + + switch (c) { + case 'h': + f.argument_options = short_argument; + + if (s[1] == 'h') { + f.argument_options = char_argument; + c = *++s; + } + + break; + + case 'l': + f.argument_options = long_argument; + + if (s[1] == 'l') { + f.argument_options = long_long_argument; + c = *++s; + } + break; + case 'L': + f.argument_options = long_double_argument; + break; + case 'j': + f.argument_options = intmax_argument; + break; + case 't': + f.argument_options = ptrdiff_argument; + break; + case 'z': + f.argument_options = size_t_argument; + break; + default: + flag_found = 0; + break; + } + + if (flag_found) { + c = *++s; + } + + f.conversion_char = c; + + switch (c) { + case 'd': + case 'i': + case 'u': + case 'o': + case 'x': + case 'X': + if (f.argument_options == long_double_argument) { + f.conversion_char = 0xFF; + break; + } + + if (!f.precision_specified) { + f.precision = 1; + } else if (f.justification_options == zero_fill) { + f.justification_options = right_justification; + } + break; + + case 'f': + case 'F': + if (f.argument_options == short_argument + || f.argument_options == intmax_argument + || f.argument_options == size_t_argument + || f.argument_options == ptrdiff_argument + || f.argument_options == long_long_argument) + { + f.conversion_char = 0xFF; + break; + } + + if (!f.precision_specified) { + f.precision = 6; + } + break; + + case 'a': + case 'A': + if (!f.precision_specified) { + f.precision = 0xD; + } + + if (f.argument_options == short_argument + || f.argument_options == intmax_argument + || f.argument_options == size_t_argument + || f.argument_options == ptrdiff_argument + || f.argument_options == long_long_argument + || f.argument_options == char_argument) + { + f.conversion_char = 0xFF; + } + + break; + + case 'g': + case 'G': + if (!f.precision) { + f.precision = 1; + } + + case 'e': + case 'E': + if (f.argument_options == short_argument + || f.argument_options == intmax_argument + || f.argument_options == size_t_argument + || f.argument_options == ptrdiff_argument + || f.argument_options == long_long_argument + || f.argument_options == char_argument) + { + f.conversion_char = 0xFF; + break; + } + + if (!f.precision_specified) { + f.precision = 6; + } + break; + + case 'p': + f.conversion_char = 'x'; + f.alternate_form = 1; + f.argument_options = long_argument; + f.precision = 8; + break; + + case 'c': + if (f.argument_options == long_argument) { + f.argument_options = wchar_argument; + } else { + if (f.precision_specified || f.argument_options != normal_argument) { + f.conversion_char = 0xFF; + } + } + + break; + + case 's': + if (f.argument_options == long_argument) { + f.argument_options = wchar_argument; + } else { + if (f.argument_options != normal_argument) { + f.conversion_char = 0xFF; + } + } + + break; + + case 'n': + if (f.argument_options == long_double_argument) { + f.conversion_char = 0xFF; + } + + break; + + default: + f.conversion_char = 0xFF; + break; + } + + *format = f; + return s + 1; +} + +static char* long2str(signed long num, char* buff, print_format format) { + unsigned long unsigned_num, base; + char* p; + int n, digits; + int minus = 0; + unsigned_num = num; + minus = 0; + + p = buff; + *--p = 0; + digits = 0; + + if (!num && !format.precision && !(format.alternate_form && format.conversion_char == 'o')) { + return p; + } + + switch (format.conversion_char) { + case 'd': + case 'i': + base = 10; + + if (num < 0) { + if (num != 0x80000000L) + unsigned_num = -unsigned_num; + + minus = 1; + } + break; + + case 'o': + base = 8; + format.sign_options = only_minus; + break; + + case 'u': + base = 10; + format.sign_options = only_minus; + break; + + case 'x': + case 'X': + base = 16; + format.sign_options = only_minus; + break; + } + + do { + n = unsigned_num % base; + unsigned_num /= base; + + if (n < 10) { + n += '0'; + } else { + n -= 10; + + if (format.conversion_char == 'x') { + n += 'a'; + } else { + n += 'A'; + } + } + + *--p = n; + ++digits; + } while (unsigned_num != 0); + + if (base == 8 && format.alternate_form && *p != '0') { + *--p = '0'; + ++digits; + } + + if (format.justification_options == zero_fill) { + format.precision = format.field_width; + + if (minus || format.sign_options != only_minus) + --format.precision; + + if (base == 16 && format.alternate_form) + format.precision -= 2; + } + + if (buff - p + format.precision > 509) + return (0); + + while (digits < format.precision) { + *--p = '0'; + ++digits; + } + + if (base == 16 && format.alternate_form) { + *--p = format.conversion_char; + *--p = '0'; + } + + if (minus) { + *--p = '-'; + } else if (format.sign_options == sign_always) { + *--p = '+'; + } else if (format.sign_options == space_holder) { + *--p = ' '; + } + + return p; +} + +static char* longlong2str(signed long long num, char* pBuf, print_format fmt) { + unsigned long long unsigned_num, base; + char* p; + int n, digits; + int minus = 0; + unsigned_num = num; + minus = 0; + p = pBuf; + *--p = 0; + digits = 0; + + if (!num && !fmt.precision && !(fmt.alternate_form && fmt.conversion_char == 'o')) { + return p; + } + + switch (fmt.conversion_char) { + case 'd': + case 'i': + base = 10; + + if (num < 0) { + if (num != 0x8000000000000000LL) + unsigned_num = -unsigned_num; + + minus = 1; + } + break; + case 'o': + base = 8; + fmt.sign_options = only_minus; + break; + case 'u': + base = 10; + fmt.sign_options = only_minus; + break; + case 'x': + case 'X': + base = 16; + fmt.sign_options = only_minus; + break; + } + + do { + n = unsigned_num % base; + unsigned_num /= base; + + if (n < 10) { + n += '0'; + } else { + n -= 10; + if (fmt.conversion_char == 'x') { + n += 'a'; + } else { + n += 'A'; + } + } + + *--p = n; + ++digits; + } while (unsigned_num != 0); + + if (base == 8 && fmt.alternate_form && *p != '0') { + *--p = '0'; + ++digits; + } + + if (fmt.justification_options == zero_fill) { + fmt.precision = fmt.field_width; + + if (minus || fmt.sign_options != only_minus) { + --fmt.precision; + } + + if (base == 16 && fmt.alternate_form) { + fmt.precision -= 2; + } + } + + if (pBuf - p + fmt.precision > 509) { + return 0; + } + + while (digits < fmt.precision) { + *--p = '0'; + ++digits; + } + + if (base == 16 && fmt.alternate_form) { + *--p = fmt.conversion_char; + *--p = '0'; + } + + if (minus) { + *--p = '-'; + } else if (fmt.sign_options == sign_always) { + *--p = '+'; + } else if (fmt.sign_options == space_holder) { + *--p = ' '; + } + + return p; +} + +static char* double2hex(long double num, char* buff, print_format format) { + char *p; + unsigned char *q; + unsigned char working_byte; + int expbits, expmask; + unsigned snum; + long exp; + print_format exp_format; + int hex_precision; + int mantissa_bit; + decform form; + decimal dec; + int radix_marker; + + radix_marker = *(unsigned char *)(__lconv).decimal_point; + p = buff; + + if (format.precision > 509) { + return 0; + } + + form.style = (char)0; + form.digits = 0x20; + __num2dec(&form, num, &dec); + + if (fabs(num) == 0.0) { + p = buff - 6; + strcpy(p, "0x0p0"); + return p; + } + if (*dec.sig.text == 'I') { + if (dec.sign) { + p = buff - 5; + if (format.conversion_char == 'A') strcpy(p, "-INF"); + else strcpy(p, "-inf"); + } + else { + p = buff - 4; + if (format.conversion_char == 'A') strcpy(p, "INF"); + else strcpy(p, "inf"); + } + + return p; + } else if (*dec.sig.text == 'N') { + if (dec.sign) { + p = buff - 5; + if (format.conversion_char == 'A') strcpy(p, "-NAN"); + else strcpy(p, "-nan"); + } + else { + p = buff - 4; + if (format.conversion_char == 'A') strcpy(p, "NAN"); + else strcpy(p, "nan"); + } + + return p; + } + + exp_format.justification_options = right_justification; + exp_format.sign_options = sign_always; + exp_format.precision_specified = 0; + exp_format.alternate_form = 0; + exp_format.argument_options = normal_argument; + exp_format.field_width = 0; + exp_format.precision = 1; + exp_format.conversion_char = 'd'; + + expbits = 11; + expmask = 0x7FF; + + snum = ((unsigned char *)&num)[0] << 25; + if (TARGET_FLOAT_EXP_BITS > 7) + snum |= ((unsigned char *)&num)[1] << 17; + if (TARGET_FLOAT_EXP_BITS > 15) + snum |= ((unsigned char *)&num)[2] << 9; + if (TARGET_FLOAT_EXP_BITS > 23) + snum |= ((unsigned char *)&num)[3] << 1; + + snum = (snum >> (32 - expbits)) & expmask; + + exp = snum - 0x3FF; + + p = long2str(exp, buff, exp_format); + if (format.conversion_char == 'a') + *--p = 'p'; + else + *--p = 'P'; + q = (unsigned char *)# + + if (TARGET_FLOAT_IMPLICIT_J_BIT) { + mantissa_bit = (1 + expbits + format.precision * 4) - 1; + } + else { + mantissa_bit = (1 + expbits + format.precision * 4) - 4; + } + + for (hex_precision = format.precision; hex_precision >= 1; hex_precision--) { + if (mantissa_bit < 64) { + int mantissa_byte; + + mantissa_byte = mantissa_bit >> 3; + working_byte = (*(q + mantissa_byte)) >> (7 - (mantissa_bit & 7)); + + if ((mantissa_bit & ~7) != ((mantissa_bit - 4) & ~7)) { + working_byte |= (unsigned char)(((*(q + (mantissa_byte - 1))) << 8) >> (7 - ((mantissa_bit) & 7))); + } + + if (!TARGET_FLOAT_IMPLICIT_J_BIT) { + if (mantissa_bit == 1 + expbits) { + *--p = radix_marker; + working_byte &= 0x1; + } + } + + if ((working_byte &= 0xF) < 10) { + working_byte = (unsigned char)(working_byte + '0'); + } + else + if (format.conversion_char == 'a') { + working_byte = (unsigned char)(working_byte + 'a' - 10); + } + else { + working_byte = (unsigned char)(working_byte + 'A' - 10); + } + } + else { + working_byte = '0'; + } + + *--p = working_byte; + mantissa_bit -= 4; + } + + if (TARGET_FLOAT_IMPLICIT_J_BIT){ + if (format.precision || format.alternate_form) { + *--p = radix_marker; + } + + *--p = '1'; + } + + if (format.conversion_char == 'a') { + *--p = 'x'; + } + else { + *--p = 'X'; + } + + *--p = '0'; + + if (dec.sign) { + *--p = '-'; + } + else if (format.sign_options == sign_always) { + *--p = '+'; + } + else if (format.sign_options == space_holder) { + *--p = ' '; + } + + return p; +} + +static void round_decimal(decimal* dec, int new_length) { + char c; + char* p; + int carry; + + if (new_length < 0) { + return_zero: + dec->exp = 0; + dec->sig.length = 1; + *dec->sig.text = '0'; + return; + } + + if (new_length >= dec->sig.length) { + return; + } + + p = (char*)dec->sig.text + new_length + 1; + c = *--p - '0'; + + if (c == 5) { + char* q = &((char*)dec->sig.text)[dec->sig.length]; + + while (--q > p && *q == '0') + ; + carry = (q == p) ? p[-1] & 1 : 1; + } else { + carry = (c > 5); + } + + while (new_length != 0) { + c = *--p - '0' + carry; + + if ((carry = (c > 9)) != 0 || c == 0) { + --new_length; + } else { + *p = c + '0'; + break; + } + } + + if (carry != 0) { + dec->exp += 1; + dec->sig.length = 1; + *dec->sig.text = '1'; + return; + } else if (new_length == 0) { + goto return_zero; + } + + dec->sig.length = new_length; +} + +static char* float2str(long double num, char* buff, print_format format) { + decimal dec; + decform form; + char* p; + char* q; + int n, digits, sign; + int int_digits, frac_digits; + int radix_marker; + + radix_marker = *(unsigned char*)__lconv.decimal_point; + + if (format.precision > 509) { + return 0; + } + + form.style = 0; + form.digits = 0x20; + __num2dec(&form, num, &dec); + p = (char*)dec.sig.text + dec.sig.length; + + while (dec.sig.length > 1 && *--p == '0') { + --dec.sig.length; + ++dec.exp; + } + + switch (*dec.sig.text) { + case '0': + dec.exp = 0; + break; + case 'I': + if (num < 0) { + p = buff - 5; + + if (isupper(format.conversion_char)) { + strcpy(p, "-INF"); + } else { + strcpy(p, "-inf"); + } + } else { + p = buff - 4; + if (isupper(format.conversion_char)) { + strcpy(p, "INF"); + } else { + strcpy(p, "inf"); + } + } + + return p; + + case 'N': + if (dec.sign) { + p = buff - 5; + + if (isupper(format.conversion_char)) { + strcpy(p, "-NAN"); + } else { + strcpy(p, "-nan"); + } + } else { + p = buff - 4; + if (isupper(format.conversion_char)) { + strcpy(p, "NAN"); + } else { + strcpy(p, "nan"); + } + } + + return p; + } + + dec.exp += dec.sig.length - 1; + + p = buff; + *--p = 0; + + switch (format.conversion_char) { + case 'g': + case 'G': + + if (dec.sig.length > format.precision) { + round_decimal(&dec, format.precision); + } + + if (dec.exp < -4 || dec.exp >= format.precision) { + if (format.alternate_form) { + --format.precision; + } else { + format.precision = dec.sig.length - 1; + } + + if (format.conversion_char == 'g') { + format.conversion_char = 'e'; + } else { + format.conversion_char = 'E'; + } + + goto e_format; + } + + if (format.alternate_form) { + format.precision -= dec.exp + 1; + } else { + if ((format.precision = dec.sig.length - (dec.exp + 1)) < 0) { + format.precision = 0; + } + } + + goto f_format; + + case 'e': + case 'E': + e_format: + + if (dec.sig.length > format.precision + 1) { + round_decimal(&dec, format.precision + 1); + } + + n = dec.exp; + sign = '+'; + + if (n < 0) { + n = -n; + sign = '-'; + } + + for (digits = 0; n || digits < 2; ++digits) { + *--p = n % 10 + '0'; + n /= 10; + } + + *--p = sign; + *--p = format.conversion_char; + + if (buff - p + format.precision > 509) { + return 0; + } + + if (dec.sig.length < format.precision + 1) { + for (n = format.precision + 1 - dec.sig.length + 1; --n;) { + *--p = '0'; + } + } + + for (n = dec.sig.length, q = (char*)dec.sig.text + dec.sig.length; --n;) { + *--p = *--q; + } + + if (format.precision || format.alternate_form) { + *--p = radix_marker; + } + + *--p = *dec.sig.text; + + if (dec.sign) + *--p = '-'; + else if (format.sign_options == sign_always) + *--p = '+'; + else if (format.sign_options == space_holder) + *--p = ' '; + + break; + + case 'f': + case 'F': + f_format: + + if ((frac_digits = -dec.exp + dec.sig.length - 1) < 0) + frac_digits = 0; + + if (frac_digits > format.precision) { + round_decimal(&dec, dec.sig.length - (frac_digits - format.precision)); + + if ((frac_digits = -dec.exp + dec.sig.length - 1) < 0) + frac_digits = 0; + } + + if ((int_digits = dec.exp + 1) < 0) + int_digits = 0; + + if (int_digits + frac_digits > 509) + return 0; + + q = (char*)dec.sig.text + dec.sig.length; + + for (digits = 0; digits < (format.precision - frac_digits); ++digits) + *--p = '0'; + + for (digits = 0; digits < frac_digits && digits < dec.sig.length; ++digits) + *--p = *--q; + + for (; digits < frac_digits; ++digits) + *--p = '0'; + + if (format.precision || format.alternate_form) + *--p = radix_marker; + + if (int_digits) { + for (digits = 0; digits < int_digits - dec.sig.length; ++digits) { + *--p = '0'; + } + + for (; digits < int_digits; ++digits) { + *--p = *--q; + } + } else { + *--p = '0'; + } + + if (dec.sign) { + *--p = '-'; + } else if (format.sign_options == sign_always) { + *--p = '+'; + } else if (format.sign_options == space_holder) { + *--p = ' '; + } + + break; + } + + return p; +} + +int __pformatter(void* (*WriteProc)(void*, const char*, size_t), void* WriteProcArg, + const char* format_str, va_list arg + + ) +{ + int num_chars, chars_written, field_width; + const char* format_ptr; + const char* curr_format; + print_format format; + signed long long_num; + signed long long long_long_num; + long double long_double_num; + char buff[512]; + char* buff_ptr; + char* string_end; + char fill_char = ' '; + + format_ptr = format_str; + chars_written = 0; + + while (*format_ptr) { + if (!(curr_format = strchr(format_ptr, '%'))) { + num_chars = strlen(format_ptr); + chars_written += num_chars; + + if (num_chars && !(*WriteProc)(WriteProcArg, format_ptr, num_chars)) { + return -1; + } + + break; + } + + num_chars = curr_format - format_ptr; + chars_written += num_chars; + + if (num_chars && !(*WriteProc)(WriteProcArg, format_ptr, num_chars)) { + return -1; + } + + format_ptr = curr_format; + format_ptr = parse_format(format_ptr, (va_list*)arg, &format); + + switch (format.conversion_char) { + case 'd': + case 'i': + if (format.argument_options == long_argument) { + long_num = va_arg(arg, signed long); + } else if (format.argument_options == long_long_argument) { + long_long_num = va_arg(arg, signed long long); + } + else if (format.argument_options == intmax_argument) { + long_long_num = va_arg(arg, intmax_t); + } + else if (format.argument_options == size_t_argument) { + long_num = va_arg(arg, size_t); + } + else if (format.argument_options == ptrdiff_argument) { + long_num = va_arg(arg, ptrdiff_t); + } + else { + long_num = va_arg(arg, int); + } + + if (format.argument_options == short_argument) { + long_num = (signed short)long_num; + } + + if (format.argument_options == char_argument) { + long_num = (signed char)long_num; + } + + if ((format.argument_options == long_long_argument) + || format.argument_options == intmax_argument + ) + { + if (!(buff_ptr = longlong2str(long_long_num, buff + 512, format))) { + goto conversion_error; + } + } else { + if (!(buff_ptr = long2str(long_num, buff + 512, format))) { + goto conversion_error; + } + } + + num_chars = buff + 512 - 1 - buff_ptr; + break; + + case 'o': + case 'u': + case 'x': + case 'X': + if (format.argument_options == long_argument) { + long_num = va_arg(arg, unsigned long); + } else if (format.argument_options == long_long_argument) { + long_long_num = va_arg(arg, signed long long); + } + else if (format.argument_options == intmax_argument) { + long_long_num = va_arg(arg, intmax_t); + } + else if (format.argument_options == size_t_argument) { + long_num = va_arg(arg, size_t); + } + else if (format.argument_options == ptrdiff_argument) { + long_num = va_arg(arg, ptrdiff_t); + } + else { + long_num = va_arg(arg, unsigned int); + } + + if (format.argument_options == short_argument) { + long_num = (unsigned short)long_num; + } + + if (format.argument_options == char_argument) { + long_num = (unsigned char)long_num; + } + + if ((format.argument_options == long_long_argument) + || format.argument_options == intmax_argument + ) + { + if (!(buff_ptr = longlong2str(long_long_num, buff + 512, format))) { + goto conversion_error; + } + } else { + if (!(buff_ptr = long2str(long_num, buff + 512, format))) { + goto conversion_error; + } + } + + num_chars = buff + 512 - 1 - buff_ptr; + break; + + case 'f': + case 'F': + case 'e': + case 'E': + case 'g': + case 'G': + if (format.argument_options == long_double_argument) { + long_double_num = va_arg(arg, long double); + } else { + long_double_num = va_arg(arg, double); + } + + if (!(buff_ptr = float2str(long_double_num, buff + 512, format))) { + goto conversion_error; + } + + num_chars = buff + 512 - 1 - buff_ptr; + break; + + case 'a': + case 'A': + if (format.argument_options == long_double_argument) { + long_double_num = va_arg(arg, long double); + } else { + long_double_num = va_arg(arg, double); + } + + if (!(buff_ptr = double2hex(long_double_num, buff + 512, format))) { + goto conversion_error; + } + + num_chars = buff + 512 - 1 - buff_ptr; + break; + + case 's': + if (format.argument_options == wchar_argument) { + wchar_t* wcs_ptr = va_arg(arg, wchar_t*); + + if (wcs_ptr == NULL) { + wcs_ptr = L""; + } + + if ((num_chars = wcstombs(buff, wcs_ptr, sizeof(buff))) < 0) { + goto conversion_error; + } + + buff_ptr = &buff[0]; + } else { + buff_ptr = va_arg(arg, char*); + } + + if (buff_ptr == NULL) { + buff_ptr = ""; + } + + if (format.alternate_form) { + num_chars = (unsigned char)*buff_ptr++; + + if (format.precision_specified && num_chars > format.precision) { + num_chars = format.precision; + } + } else if (format.precision_specified) { + num_chars = format.precision; + + if ((string_end = (char*)memchr((unsigned char*)buff_ptr, 0, num_chars)) != 0) { + num_chars = string_end - buff_ptr; + } + } else { + num_chars = strlen(buff_ptr); + } + + break; + + case 'n': + buff_ptr = va_arg(arg, char*); + + switch (format.argument_options) { + case normal_argument: + *(int*)buff_ptr = chars_written; + break; + case short_argument: + *(signed short*)buff_ptr = chars_written; + break; + case long_argument: + *(signed long*)buff_ptr = chars_written; + break; + case intmax_argument: + *(intmax_t*)buff_ptr = chars_written; + break; + case size_t_argument: + *(size_t*)buff_ptr = chars_written; + break; + case ptrdiff_argument: + *(ptrdiff_t*)buff_ptr = chars_written; + break; + case long_long_argument: + *(signed long long*)buff_ptr = chars_written; + break; + } + + continue; + + case 'c': + buff_ptr = buff; + *buff_ptr = va_arg(arg, int); + num_chars = 1; + break; + + case '%': + buff_ptr = buff; + *buff_ptr = '%'; + num_chars = 1; + break; + + case 0xFF: + default: + conversion_error: + num_chars = strlen(curr_format); + chars_written += num_chars; + + if (num_chars && !(*WriteProc)(WriteProcArg, curr_format, num_chars)) { + return -1; + } + + return chars_written; + break; + } + + field_width = num_chars; + + if (format.justification_options != left_justification) { + fill_char = (format.justification_options == zero_fill) ? '0' : ' '; + + if (((*buff_ptr == '+') || (*buff_ptr == '-') || (*buff_ptr == ' ')) && + (fill_char == '0')) + { + if ((*WriteProc)(WriteProcArg, buff_ptr, 1) == 0) { + return -1; + } + + ++buff_ptr; + num_chars--; + } + + while (field_width < format.field_width) { + if ((*WriteProc)(WriteProcArg, &fill_char, 1) == 0) { + return -1; + } + + ++field_width; + } + } + + if (num_chars && !(*WriteProc)(WriteProcArg, buff_ptr, num_chars)) { + return -1; + } + + if (format.justification_options == left_justification) { + while (field_width < format.field_width) { + char blank = ' '; + + if ((*WriteProc)(WriteProcArg, &blank, 1) == 0) { + return -1; + } + + ++field_width; + } + } + + chars_written += field_width; + } + + return chars_written; +} + +void* __FileWrite(void* pFile, const char* pBuffer, size_t char_num) { + return (__fwrite(pBuffer, 1, char_num, (FILE*)pFile) == char_num ? pFile : 0); +} + +void* __StringWrite(void* pCtrl, const char* pBuffer, size_t char_num) { + size_t chars; + __OutStrCtrl* ctrl = (__OutStrCtrl*)pCtrl; + void* res; + + chars = ((ctrl->CharsWritten + char_num) <= ctrl->MaxCharCount) ? + char_num : + ctrl->MaxCharCount - ctrl->CharsWritten; + res = memcpy(ctrl->CharStr + ctrl->CharsWritten, pBuffer, chars); + ctrl->CharsWritten += chars; + return (void*)1; +} + +int printf(const char* format, ...) { + int res; + + if (fwide(stdout, -1) >= 0) { + return -1; + } + { + va_list args; + va_start(args, format); + res = __pformatter(&__FileWrite, (void*)stdout, format, args); + } + return res; +} + +int fprintf(FILE* file, const char* format, ...) { + int res; + + if (fwide(file, -1) >= 0) { + return -1; + } + { + va_list args; + va_start(args, format); + res = __pformatter(&__FileWrite, (void*)file, format, args); + } + return res; +} + +int vprintf(const char* format, va_list arg) { + int ret; + + if (fwide(stdout, -1) >= 0) { + return -1; + } + ret = __pformatter(&__FileWrite, (void*)stdout, format, arg); + return ret; +} + +int vsnprintf(char* s, size_t n, const char* fmt, va_list args) { + int end; + __OutStrCtrl osc; + osc.CharStr = s; + osc.MaxCharCount = n; + osc.CharsWritten = 0; + + end = __pformatter(&__StringWrite, &osc, fmt, args); + + if (s) { + if (end < n) { + s[end] = '\0'; + } else { + if (n > 0) { + s[n - 1] = '\0'; + } + } + } + + return end; +} + +int vsprintf(char *s, const char *format, va_list arg) { + return vsnprintf(s, 0xFFFFFFFF, format, arg); +} + +int snprintf(char* s, size_t n, const char* format, ...) { + va_list args; + va_start(args, format); + return vsnprintf(s, n, format, args); +} + +int sprintf(char* s, const char* format, ...) { + va_list args; + va_start(args, format); + return vsnprintf(s, 0xFFFFFFFF, format, args); +} diff --git a/libs/MSL/src/MSL_Common/scanf.c b/libs/MSL/src/MSL_Common/scanf.c new file mode 100644 index 00000000..96a2f325 --- /dev/null +++ b/libs/MSL/src/MSL_Common/scanf.c @@ -0,0 +1,817 @@ +#include + + + + + + + + + + +typedef long long intmax_t; + +enum argument_options { + normal_argument, + char_argument, + short_argument, + long_argument, + intmax_argument, + size_t_argument, + ptrdiff_argument, + long_long_argument, + double_argument, + long_double_argument, + wchar_argument +}; + +typedef unsigned char char_map[32]; + +typedef struct { + unsigned char suppress_assignment; + unsigned char field_width_specified; + unsigned char argument_options; + unsigned char conversion_char; + int field_width; + char_map char_set; +} scan_format; + +#define set_char_map(map, ch) map[(unsigned char)ch >> 3] |= (1 << (ch & 7)) +#define tst_char_map(map, ch) (map[(unsigned char)ch >> 3] & (1 << (ch & 7))) + +static const char* parse_format(const char* format_string, scan_format* format) { + const char* s = format_string; + int c; + int flag_found, invert; + scan_format f = {0, 0, normal_argument, 0, 2147483647, {0}}; + + if (((c = *++s) == '%')) { + f.conversion_char = c; + *format = f; + return s + 1; + } + + if (c == '*') { + f.suppress_assignment = 1; + c = *++s; + } + + if (isdigit(c)) { + f.field_width = 0; + + do { + f.field_width = (f.field_width * 10) + (c - '0'); + c = *++s; + } while (isdigit(c)); + + if (f.field_width == 0) { + f.conversion_char = 0xFF; + *format = f; + return s + 1; + } + + f.field_width_specified = 1; + } + + flag_found = 1; + + switch (c) { + case 'h': + f.argument_options = short_argument; + + if (s[1] == 'h') { + f.argument_options = char_argument; + c = *++s; + } + + break; + case 'l': + f.argument_options = long_argument; + + if (s[1] == 'l') { + f.argument_options = long_long_argument; + c = *++s; + } + + break; + case 'L': + f.argument_options = long_double_argument; + break; + + case 'j': + f.argument_options = intmax_argument; + break; + case 'z': + f.argument_options = size_t_argument; + break; + case 't': + f.argument_options = ptrdiff_argument; + break; + default: + flag_found = 0; + } + + if (flag_found) { + c = *++s; + } + + f.conversion_char = c; + + switch (c) { + case 'd': + case 'i': + case 'u': + case 'o': + case 'x': + case 'X': + if (f.argument_options == long_double_argument) { + f.conversion_char = 0xFF; + break; + } + + break; + + case 'a': + case 'A': + case 'f': + case 'F': + case 'e': + case 'E': + case 'g': + case 'G': + if (f.argument_options == char_argument || f.argument_options == short_argument || + f.argument_options == intmax_argument || f.argument_options == size_t_argument || + f.argument_options == ptrdiff_argument || f.argument_options == long_long_argument) { + f.conversion_char = 0xFF; + break; + } + + if (f.argument_options == long_argument) { + f.argument_options = double_argument; + } + + break; + + case 'p': + f.argument_options = long_argument; + f.conversion_char = 'x'; + break; + + case 'c': + if (f.argument_options == long_argument) { + f.argument_options = wchar_argument; + } else { + if (f.argument_options != normal_argument) { + f.conversion_char = 0xFF; + } + } + + break; + + case 's': + if (f.argument_options == long_argument) { + f.argument_options = wchar_argument; + } else { + if (f.argument_options != normal_argument) { + f.conversion_char = 0xFF; + } + } + + { + int i; + unsigned char* p; + + for (i = sizeof(f.char_set), p = f.char_set; i; --i) { + *p++ = 0xFF; + } + + f.char_set[1] = 0xC1; + f.char_set[4] = 0xFE; + } + + break; + + case 'n': + break; + + case '[': + if (f.argument_options == long_argument) { + f.argument_options = wchar_argument; + } else { + if (f.argument_options != normal_argument) { + f.conversion_char = 0xFF; + } + } + + c = *++s; + invert = 0; + + if (c == '^') { + invert = 1; + c = *++s; + } + + if (c == ']') { + set_char_map(f.char_set, ']'); + c = *++s; + } + + while (c && c != ']') { + int d; + set_char_map(f.char_set, c); + + if (*(s + 1) == '-' && (d = *(s + 2)) != 0 && d != ']') { + while (++c <= d) { + set_char_map(f.char_set, c); + } + + c = *(s += 3); + } else { + c = *++s; + } + } + + if (!c) { + f.conversion_char = 0xFF; + break; + } + + if (invert) { + int i; + unsigned char* p; + + for (i = sizeof(f.char_set), p = f.char_set; i; --i, ++p) { + *p = ~*p; + } + + break; + } + + break; + default: + f.conversion_char = 0xFF; + break; + } + + *format = f; + return s + 1; +} + +int __sformatter(int (*ReadProc)(void*, int, int), void* ReadProcArg, const char* format_str, va_list arg, + int is_secure) { + int num_chars, chars_read, items_assigned, conversions; + int base, negative, overflow; + int rval; + const char* format_ptr; + char format_char; + char c; + scan_format format; + long long_num; + unsigned long u_long_num; + long long long_long_num = 0; + unsigned long long u_long_long_num; + long double long_double_num; + char* arg_ptr; + int elem_valid; + size_t elem_maxsize; + int match_failure = 0; + int terminate = 0; + + format_ptr = format_str; + chars_read = 0; + items_assigned = 0; + conversions = 0; + + while (!terminate && (format_char = *format_ptr) != 0) { + if (isspace(format_char)) { + do { + format_char = *++format_ptr; + } while (isspace(format_char)); + + if (!match_failure) { + while (isspace(c = (*ReadProc)(ReadProcArg, 0, __GetAChar))) { + ++chars_read; + } + + (*ReadProc)(ReadProcArg, c, __UngetAChar); + } + continue; + } + + if ((format_char != '%') && (!match_failure)) { + if ((c = (*ReadProc)(ReadProcArg, 0, __GetAChar)) != (unsigned char)format_char) { + (*ReadProc)(ReadProcArg, c, __UngetAChar); + if (!is_secure) { + goto exit; + } else { + match_failure = 1; + ++format_ptr; + continue; + } + } + + chars_read++; + format_ptr++; + + continue; + } + + format_ptr = parse_format(format_ptr, &format); + + if (!format.suppress_assignment && format.conversion_char != '%') { + arg_ptr = va_arg(arg, char*); + } else { + arg_ptr = 0; + } + + if ((format.conversion_char != 'n') && (!match_failure) && (*ReadProc)(ReadProcArg, 0, __TestForError)) { + if (!is_secure) { + goto exit; + } else { + match_failure = 1; + } + } + + switch (format.conversion_char) { + case 'd': + base = 10; + goto signed_int; + case 'i': + base = 0; + signed_int: + + if (match_failure) { + long_num = 0; + long_long_num = 0; + } else { + if ((format.argument_options == long_long_argument) || + (format.argument_options == intmax_argument)) { + u_long_long_num = __strtoull(base, format.field_width, ReadProc, ReadProcArg, &num_chars, + &negative, &overflow); + } else { + u_long_num = __strtoul(base, format.field_width, ReadProc, ReadProcArg, &num_chars, &negative, + &overflow); + } + + if (!num_chars) { + if (!is_secure) { + goto exit; + } else { + match_failure = 1; + long_num = 0; + long_long_num = 0; + goto signed_int_assign; + } + } + + chars_read += num_chars; + + if ((format.argument_options == long_long_argument) || + (format.argument_options == intmax_argument)) { + long_long_num = (negative ? -u_long_long_num : u_long_long_num); + } else { + long_num = (negative ? -u_long_num : u_long_num); + } + } + + signed_int_assign: + + if (arg_ptr) { + switch (format.argument_options) { + case normal_argument: + *(int*)arg_ptr = long_num; + break; + case char_argument: + *(signed char*)arg_ptr = long_num; + break; + case short_argument: + *(short*)arg_ptr = long_num; + break; + case long_argument: + *(long*)arg_ptr = long_num; + break; + case intmax_argument: + *(intmax_t*)arg_ptr = long_long_num; + break; + case size_t_argument: + *(size_t*)arg_ptr = long_num; + break; + case ptrdiff_argument: + *(ptrdiff_t*)arg_ptr = long_num; + break; + case long_long_argument: + *(long long*)arg_ptr = long_long_num; + break; + } + if (!match_failure) { + items_assigned++; + } + } + + conversions++; + break; + case 'o': + base = 8; + goto unsigned_int; + case 'u': + base = 10; + goto unsigned_int; + case 'x': + case 'X': + base = 16; + unsigned_int: + + if (match_failure) { + u_long_num = 0; + u_long_long_num = 0; + } else { + if ((format.argument_options == long_long_argument) || + (format.argument_options == intmax_argument)) { + u_long_long_num = __strtoull(base, format.field_width, ReadProc, ReadProcArg, &num_chars, + &negative, &overflow); + } else { + u_long_num = __strtoul(base, format.field_width, ReadProc, ReadProcArg, &num_chars, &negative, + &overflow); + } + + if (!num_chars) { + if (!is_secure) { + goto exit; + } else { + match_failure = 1; + u_long_num = 0; + u_long_long_num = 0; + goto unsigned_int_assign; + } + } + + chars_read += num_chars; + + if (negative) { + if (format.argument_options == long_long_argument) { + u_long_long_num = -u_long_long_num; + } else { + u_long_num = -u_long_num; + } + } + } + + unsigned_int_assign: + + if (arg_ptr) { + switch (format.argument_options) { + case normal_argument: + *(unsigned int*)arg_ptr = u_long_num; + break; + case char_argument: + *(unsigned char*)arg_ptr = u_long_num; + break; + case short_argument: + *(unsigned short*)arg_ptr = u_long_num; + break; + case long_argument: + *(unsigned long*)arg_ptr = u_long_num; + break; + case intmax_argument: + *(intmax_t*)arg_ptr = u_long_long_num; + break; + case size_t_argument: + *(size_t*)arg_ptr = u_long_num; + break; + case ptrdiff_argument: + *(ptrdiff_t*)arg_ptr = u_long_num; + break; + case long_long_argument: + *(unsigned long long*)arg_ptr = u_long_long_num; + break; + } + + if (!match_failure) { + items_assigned++; + } + } + + conversions++; + break; + case 'a': + case 'A': + case 'f': + case 'F': + case 'e': + case 'E': + case 'g': + case 'G': + flt: + if (match_failure) { + long_double_num = NAN; + } else { + long_double_num = __strtold(format.field_width, ReadProc, ReadProcArg, &num_chars, &overflow); + + if (!num_chars) { + if (!is_secure) { + goto exit; + } else { + match_failure = 1; + long_double_num = NAN; + goto assign_float; + } + } + + chars_read += num_chars; + } + + assign_float: + + if (arg_ptr) { + switch (format.argument_options) { + case normal_argument: + *(float*)arg_ptr = long_double_num; + break; + case double_argument: + *(double*)arg_ptr = long_double_num; + break; + case long_double_argument: + *(long double*)arg_ptr = long_double_num; + break; + } + + if (!match_failure) { + items_assigned++; + } + } + + conversions++; + break; + + case 'c': + + if (!format.field_width_specified) { + format.field_width = 1; + } + + if (arg_ptr) { + if (is_secure) { + elem_valid = 1; + elem_maxsize = va_arg(arg, size_t); + } + + num_chars = 0; + + if (match_failure) { + if (elem_maxsize > 0) { + *arg_ptr = 0; + } + continue; + } else { + char* arg_start = arg_ptr; + + while (format.field_width-- && + (!is_secure || ((elem_valid = (elem_maxsize > num_chars)) != 0)) && + ((rval = ((*ReadProc)(ReadProcArg, 0, __GetAChar))) != -1)) { + c = rval; + + if (format.argument_options == wchar_argument) { + mbtowc(((wchar_t*)arg_ptr), (char*)(&c), 1); + arg_ptr += sizeof(char); + } else { + *arg_ptr++ = c; + } + num_chars++; + } + + c = rval; + if (!num_chars || (is_secure && !elem_valid)) { + if (!is_secure) { + goto exit; + } else { + match_failure = 1; + if (elem_maxsize > 0) { + *arg_start = 0; + } + continue; + } + } + + chars_read += num_chars; + + items_assigned++; + } + } else { + num_chars = 0; + + while (format.field_width-- && ((rval = ((*ReadProc)(ReadProcArg, 0, __GetAChar))) != -1)) { + c = rval; + num_chars++; + } + c = rval; + if (!num_chars) { + goto exit; + } + } + + conversions++; + break; + + case '%': + if (match_failure) { + continue; + } else { + while (isspace(c = (*ReadProc)(ReadProcArg, 0, __GetAChar))) { + chars_read++; + } + + if (c != '%') { + (*ReadProc)(ReadProcArg, c, __UngetAChar); + if (!is_secure) { + goto exit; + } else { + match_failure = 1; + continue; + } + } + + chars_read++; + } + break; + + case 's': + if (!match_failure) { + c = (*ReadProc)(ReadProcArg, 0, __GetAChar); + while (isspace(c)) { + chars_read++; + c = (*ReadProc)(ReadProcArg, 0, __GetAChar); + } + + (*ReadProc)(ReadProcArg, c, __UngetAChar); + } + case '[': + if (arg_ptr) { + if (is_secure) { + elem_valid = 1; + elem_maxsize = va_arg(arg, size_t) - 1; + } + + num_chars = 0; + + if (match_failure) { + if (elem_maxsize > 0) { + *arg_ptr = 0; + } + continue; + } else { + char* arg_start = arg_ptr; + + while (format.field_width-- && + (!is_secure || ((elem_valid = (elem_maxsize >= num_chars)) != 0)) && + ((rval = ((*ReadProc)(ReadProcArg, 0, __GetAChar))) != -1)) { + c = rval; + + if (!tst_char_map(format.char_set, c)) { + break; + } + + if (format.argument_options == wchar_argument) { + mbtowc(((wchar_t*)arg_ptr), (char*)&c, 1); + arg_ptr = (char*)((wchar_t*)arg_ptr + 1); + } else { + *arg_ptr++ = c; + } + num_chars++; + } + c = rval; + + if (!num_chars || (is_secure && !elem_valid)) { + (*ReadProc)(ReadProcArg, c, __UngetAChar); + if (!is_secure) { + goto exit; + } else { + match_failure = 1; + if (elem_maxsize > 0) { + *arg_start = 0; + } + continue; + } + } + + chars_read += num_chars; + + if (format.argument_options == wchar_argument) { + *(wchar_t*)arg_ptr = L'\0'; + } else { + *arg_ptr = 0; + } + + items_assigned++; + } + } else { + num_chars = 0; + + while (format.field_width-- && ((rval = ((*ReadProc)(ReadProcArg, 0, __GetAChar))) != -1)) { + c = rval; + if (!tst_char_map(format.char_set, c)) { + break; + } + + num_chars++; + } + c = rval; + + if (!num_chars) { + (*ReadProc)(ReadProcArg, c, __UngetAChar); + break; + } + chars_read += num_chars; + } + + if (format.field_width >= 0) { + (*ReadProc)(ReadProcArg, c, __UngetAChar); + } + + conversions++; + break; + case 'n': + if (arg_ptr) { + switch (format.argument_options) { + case normal_argument: + *(int*)arg_ptr = chars_read; + break; + case short_argument: + *(short*)arg_ptr = chars_read; + break; + case long_argument: + *(long*)arg_ptr = chars_read; + break; + case char_argument: + *(char*)arg_ptr = chars_read; + break; + case long_long_argument: + *(long long*)arg_ptr = chars_read; + break; + } + } + continue; + case 0xFF: + default: + goto exit; + } + } + +exit: + + if ((*ReadProc)(ReadProcArg, 0, __TestForError) && conversions == 0) { + return -1; + } + + return items_assigned; +} + +int __StringRead(void* pPtr, int ch, int act) { + char ret; + __InStrCtrl* Iscp = (__InStrCtrl*)pPtr; + + switch (act) { + case __GetAChar: + ret = *(Iscp->NextChar); + + if (ret == '\0') { + Iscp->NullCharDetected = 1; + return -1; + } else { + Iscp->NextChar++; + return (unsigned char)ret; + } + + case __UngetAChar: + if (Iscp->NullCharDetected == 0) { + Iscp->NextChar--; + } else { + Iscp->NullCharDetected = 0; + } + + return ch; + + case __TestForError: + return Iscp->NullCharDetected; + } + + return 0; +} + +inline int vsscanf(const char* s, const char* format, va_list arg) { + __InStrCtrl isc; + isc.NextChar = (char*)s; + + if ((s == 0) || (*isc.NextChar == '\0')) { + return -1; + } + + isc.NullCharDetected = 0; + return __sformatter(&__StringRead, (void*)&isc, format, arg, 0); +} + +int sscanf(const char* s, const char* pFormat, ...) { + va_list args; + va_start(args, pFormat); + return vsscanf(s, pFormat, args); +} + diff --git a/libs/MSL/src/MSL_Common/strtold.c b/libs/MSL/src/MSL_Common/strtold.c new file mode 100644 index 00000000..b163388f --- /dev/null +++ b/libs/MSL/src/MSL_Common/strtold.c @@ -0,0 +1,659 @@ +#include +#define DBL_MAX_10_EXP 308 +#define DBL_MIN_10_EXP (-307) +#define LDBL_MIN DBL_MIN +#define LDBL_MAX DBL_MAX + + + + + + + + + + +#define TARGET_FLOAT_BITS 64 +#define TARGET_FLOAT_BYTES (TARGET_FLOAT_BITS / 8) +#define TARGET_FLOAT_MAX_EXP LDBL_MAX_EXP +#define TARGET_FLOAT_MANT_DIG LDBL_MANT_DIG +#define TARGET_FLOAT_IMPLICIT_J_BIT 1 +#define TARGET_FLOAT_MANT_BITS (TARGET_FLOAT_MANT_DIG - TARGET_FLOAT_IMPLICIT_J_BIT) +#define TARGET_FLOAT_EXP_BITS (TARGET_FLOAT_BITS - TARGET_FLOAT_MANT_BITS - 1) + +enum scan_states { + start = 0x0001, + sig_start = 0x0002, + leading_sig_zeroes = 0x0004, + int_digit_loop = 0x0008, + frac_start = 0x0010, + frac_digit_loop = 0x0020, + sig_end = 0x0040, + exp_start = 0x0080, + leading_exp_digit = 0x0100, + leading_exp_zeroes = 0x0200, + exp_digit_loop = 0x0400, + finished = 0x0800, + failure = 0x1000, + nan_state = 0x2000, + infin_state = 0x4000, + hex_state = 0x8000 +}; + +enum hex_scan_states { + not_hex = 0x0000, + hex_start = 0x0001, + hex_leading_sig_zeroes = 0x0002, + hex_int_digit_loop = 0x0004, + hex_frac_digit_loop = 0x0008, + hex_sig_end = 0x0010, + hex_exp_start = 0x0020, + hex_leading_exp_digit = 0x0040, + hex_leading_exp_zeroes = 0x0080, + hex_exp_digit_loop = 0x0100 +}; + +#define final_state(scan_state) (scan_state & (finished | failure)) +#define success(scan_state) \ + (scan_state & \ + (leading_sig_zeroes | int_digit_loop | frac_digit_loop | leading_exp_zeroes | exp_digit_loop | finished)) +#define hex_success(count, scan_state) \ + (count - 1 > 2 && scan_state & (hex_leading_sig_zeroes | hex_int_digit_loop | hex_frac_digit_loop | \ + hex_leading_exp_zeroes | hex_exp_digit_loop)) + +#define fetch() (count++, (*ReadProc)(ReadProcArg, 0, __GetAChar)) +#define unfetch(c) (*ReadProc)(ReadProcArg, c, __UngetAChar) + +long double __strtold(int max_width, int (*ReadProc)(void*, int, int), void* ReadProcArg, int* chars_scanned, + int* overflow) { + int scan_state = start; + int hex_scan_state = not_hex; + int count = 0; + int spaces = 0; + int c; + decimal d = {0, 0, {0, ""}}; + int sig_negative = 0; + int exp_negative = 0; + long exp_value = 0; + int exp_adjust = 0; + long double result = 0.0; + int sign_detected = 0; + int radix_marker = *(unsigned char*)(__lconv).decimal_point; + + unsigned char* chptr; + unsigned char mantissa[TARGET_FLOAT_BYTES]; + unsigned mantissa_digits; + unsigned long exponent = 0; + + int ui; + unsigned char uch, uch1; + int NibbleIndex; + int expsign = 0; + int exp_digits = 0; + unsigned intdigits = 0; + + *overflow = 0; + c = fetch(); + + while (count <= max_width && c != -1 && !final_state(scan_state)) { + switch (scan_state) { + case start: + if (isspace(c)) { + c = fetch(); + count--; + spaces++; + break; + } + + switch (toupper(c)) { + case '-': + sig_negative = 1; + + case '+': + c = fetch(); + sign_detected = 1; + break; + case 'I': + c = fetch(); + scan_state = infin_state; + break; + + case 'N': + c = fetch(); + scan_state = nan_state; + break; + + default: + scan_state = sig_start; + break; + } + break; + + case infin_state: { + int i = 1; + char model[] = "INFINITY"; + + while ((i < 8) && (toupper(c) == model[i])) { + i++; + c = fetch(); + } + + if ((i == 3) || (i == 8)) { + if (sig_negative) { + result = (float)-(double)INFINITY; + } else { + result = INFINITY; + } + + *chars_scanned = spaces + i + sign_detected; + return result; + } else { + scan_state = failure; + } + + break; + } + + case nan_state: { + int i = 1, j = 0; + char model[] = "NAN("; + char nan_arg[32] = ""; + while ((i < 4) && (toupper(c) == model[i])) { + i++; + c = fetch(); + } + + if ((i == 3) || (i == 4)) { + if (i == 4) { + while ((j < 32) && (isdigit(c) || isalpha(c) || (c == radix_marker))) { + nan_arg[j++] = (char)c; + c = fetch(); + } + + if (c != ')') { + scan_state = failure; + break; + } else { + j++; + } + } + nan_arg[j] = '\0'; + + if (sig_negative) { + result = -nan(nan_arg); + } else { + result = nan(nan_arg); + } + + *chars_scanned = spaces + i + j + sign_detected; + return result; + } else { + scan_state = failure; + } + break; + } + + case sig_start: + if (c == radix_marker) { + scan_state = frac_start; + c = fetch(); + break; + } + if (!isdigit(c)) { + scan_state = failure; + break; + } + + if (c == '0') { + c = fetch(); + if (toupper(c) == 'X') { + scan_state = hex_state; + hex_scan_state = hex_start; + } else { + scan_state = leading_sig_zeroes; + } + break; + } + + scan_state = int_digit_loop; + break; + + case leading_sig_zeroes: + if (c == '0') { + c = fetch(); + + break; + } + scan_state = int_digit_loop; + break; + + case int_digit_loop: + if (!isdigit(c)) { + if (c == radix_marker) { + scan_state = frac_digit_loop; + c = fetch(); + } else { + scan_state = sig_end; + } + break; + } + if (d.sig.length < 20) { + d.sig.text[d.sig.length++] = (unsigned char)c; + } else { + exp_adjust++; + } + + c = fetch(); + break; + + case frac_start: + if (!isdigit(c)) { + scan_state = failure; + break; + } + + scan_state = frac_digit_loop; + break; + + case frac_digit_loop: + if (!isdigit(c)) { + scan_state = sig_end; + break; + } + + if (d.sig.length < 20) { + if (c != '0' || d.sig.length) { + d.sig.text[d.sig.length++] = (unsigned char)c; + } + + exp_adjust--; + } + c = fetch(); + break; + + case sig_end: + if (toupper(c) == 'E') { + scan_state = exp_start; + c = fetch(); + break; + } + scan_state = finished; + break; + + case exp_start: + if (c == '+') { + c = fetch(); + } else if (c == '-') { + c = fetch(); + exp_negative = 1; + } + + scan_state = leading_exp_digit; + break; + + case leading_exp_digit: + if (!isdigit(c)) { + scan_state = failure; + break; + } + + if (c == '0') { + scan_state = leading_exp_zeroes; + c = fetch(); + break; + } + + scan_state = exp_digit_loop; + break; + + case leading_exp_zeroes: + if (c == '0') { + c = fetch(); + break; + } + + scan_state = exp_digit_loop; + break; + + case exp_digit_loop: + if (!isdigit(c)) { + scan_state = finished; + break; + } + + exp_value = exp_value * 10 + (c - '0'); + if (exp_value > 0x7FFF) { + *overflow = 1; + } + + c = fetch(); + break; + + case hex_state: { + switch (hex_scan_state) { + case hex_start: + memset(mantissa, 0, sizeof(mantissa)); + chptr = mantissa; + mantissa_digits = (53 + 3) / 4; + intdigits = 0; + NibbleIndex = 0; + hex_scan_state = hex_leading_sig_zeroes; + c = fetch(); + break; + + case hex_leading_sig_zeroes: + if (c == '0') { + c = fetch(); + break; + } + + hex_scan_state = hex_int_digit_loop; + break; + + case hex_int_digit_loop: + if (!isxdigit(c)) { + if (c == radix_marker) { + hex_scan_state = hex_frac_digit_loop; + c = fetch(); + } + + else { + hex_scan_state = hex_sig_end; + } + break; + } + + if (intdigits < mantissa_digits) { + intdigits++; + uch = *(chptr + NibbleIndex / 2); + + ui = toupper(c); + if (ui >= 'A') { + ui = ui - 'A' + 10; + } else { + ui -= '0'; + } + + uch1 = (unsigned char)ui; + + if ((NibbleIndex % 2) != 0) { + uch |= uch1; + } else { + uch |= (unsigned char)(uch1 << 4); + } + + *(chptr + NibbleIndex++ / 2) = uch; + c = fetch(); + } + + else { + c = fetch(); + } + + break; + + case hex_frac_digit_loop: + if (!isxdigit(c)) { + hex_scan_state = hex_sig_end; + break; + } + + if (intdigits < mantissa_digits) { + uch = *(chptr + NibbleIndex / 2); + ui = toupper(c); + + if (ui >= 'A') { + ui = ui - 'A' + 10; + } else { + ui -= '0'; + } + + uch1 = (unsigned char)ui; + + if ((NibbleIndex % 2) != 0) { + uch |= uch1; + } else { + uch |= (unsigned char)(uch1 << 4); + } + + *(chptr + NibbleIndex++ / 2) = uch; + c = fetch(); + } else { + c = fetch(); + } + break; + + case hex_sig_end: + if (toupper(c) == 'P') { + hex_scan_state = hex_exp_start; + exp_digits++; + c = fetch(); + } else { + scan_state = finished; + } + + break; + + case hex_exp_start: + exp_digits++; + if (c == '-') { + expsign = 1; + } else if (c != '+') { + c = unfetch(c); + count--; + exp_digits--; + } + + hex_scan_state = hex_leading_exp_digit; + c = fetch(); + break; + + case hex_leading_exp_digit: + if (!isdigit(c)) { + scan_state = failure; + break; + } + + if (c == '0') { + exp_digits++; + hex_scan_state = hex_leading_exp_zeroes; + c = fetch(); + break; + } + + hex_scan_state = hex_exp_digit_loop; + break; + + case hex_leading_exp_zeroes: + if (c == '0') { + c = fetch(); + break; + } + + hex_scan_state = hex_exp_digit_loop; + break; + + case hex_exp_digit_loop: + if (!isdigit(c)) { + scan_state = finished; + break; + } + + exponent = exponent * 10 + (c - '0'); + + if (exp_value > SHRT_MAX) { + *overflow = 1; + } + + exp_digits++; + c = fetch(); + + break; + } + } break; + } + } + + if (scan_state != 32768 ? !success(scan_state) : !hex_success(count, hex_scan_state)) { + count = 0; + *chars_scanned = 0; + } else { + count--; + *chars_scanned = count + spaces; + } + + unfetch(c); + + if (hex_scan_state == not_hex) { + if (exp_negative) { + exp_value = -exp_value; + } + + { + int n = d.sig.length; + unsigned char* p = &d.sig.text[n]; + + while (n-- && *--p == '0') { + exp_adjust++; + } + + d.sig.length = (unsigned char)(n + 1); + + if (d.sig.length == 0) { + d.sig.text[d.sig.length++] = '0'; + } + } + + exp_value += exp_adjust; + + if (exp_value < -0x8000 || exp_value > 0x7FFF) { + *overflow = 1; + } + + if (*overflow) { + if (exp_negative) { + return 0.0; + } else { + return sig_negative ? -HUGE_VAL : HUGE_VAL; + } + } + + d.exp = (short)exp_value; + + result = __dec2num(&d); + + if (result != 0.0 && result < LDBL_MIN) { + *overflow = 1; + } else if (result > LDBL_MAX) { + *overflow = 1; + result = HUGE_VAL; + } + + if (sig_negative && success(scan_state)) { + result = -result; + } + + return result; + } else { + unsigned mantissa_bit, dbl_bit; + unsigned one_bit; + long double dbl_bits_storage; + unsigned char* dbl_bits = (unsigned char*)&dbl_bits_storage; + + if (expsign) { + exponent = -exponent; + } + + exponent += intdigits * 4; + + one_bit = 0; + while (one_bit < 4 && !(mantissa[0] & (0x80 >> one_bit))) { + one_bit++; + exponent--; + } + + if (TARGET_FLOAT_IMPLICIT_J_BIT) { + one_bit++; + } + + if (one_bit) { + unsigned char carry = 0; + for (chptr = mantissa + sizeof(mantissa) - 1; chptr >= mantissa; chptr--) { + unsigned char a = *chptr; + *chptr = (unsigned char)((a << one_bit) | carry); + carry = (unsigned char)(a >> (8 - one_bit)); + } + } + + memset(dbl_bits, 0, sizeof(dbl_bits_storage)); + dbl_bit = (TARGET_FLOAT_BITS - TARGET_FLOAT_MANT_BITS); + + for (mantissa_bit = 0; mantissa_bit < TARGET_FLOAT_MANT_BITS; mantissa_bit += 8) { + unsigned char ui = mantissa[mantissa_bit >> 3]; + int halfbits; + + if (mantissa_bit + 8 > TARGET_FLOAT_MANT_BITS) { + ui &= 0xff << (TARGET_FLOAT_MANT_BITS - mantissa_bit); + } + + halfbits = (dbl_bit & 7); + dbl_bits[dbl_bit >> 3] |= (unsigned char)(ui >> halfbits); + dbl_bit += 8; + dbl_bits[dbl_bit >> 3] |= (unsigned char)(ui << (8 - halfbits)); + } + + exponent += TARGET_FLOAT_MAX_EXP - 2; + + if ((exponent & ~(TARGET_FLOAT_MAX_EXP * 2 - 1))) { + *overflow = 1; + return 0.0; + } + + exponent <<= 32 - TARGET_FLOAT_EXP_BITS; + + dbl_bits[0] |= exponent >> 25; + + if (TARGET_FLOAT_EXP_BITS > 7) { + dbl_bits[1] |= exponent >> 17; + } + + if (TARGET_FLOAT_EXP_BITS > 15) { + dbl_bits[2] |= exponent >> 9; + } + + if (TARGET_FLOAT_EXP_BITS > 23) { + dbl_bits[3] |= exponent >> 1; + } + + if (sig_negative) { + dbl_bits[0] |= 0x80; + } + + result = *(long double*)dbl_bits; + + return result; + } +} + +double strtod(const char* str, char** end) { + __InStrCtrl isc; + double value, abs_value; + int count, overflow; + + isc.NextChar = (char*)str; + isc.NullCharDetected = 0; + value = __strtold(INT_MAX, &__StringRead, (void*)&isc, &count, &overflow); + + if (end) { + *end = (char*)str + count; + } + + abs_value = fabs(value); + if (overflow || (value != 0.0 && (abs_value < DBL_MIN || abs_value > DBL_MAX))) { + errno = ERANGE; + } + + return value; +} + + diff --git a/libs/MSL/src/MSL_Common/time.c b/libs/MSL/src/MSL_Common/time.c new file mode 100644 index 00000000..445b0630 --- /dev/null +++ b/libs/MSL/src/MSL_Common/time.c @@ -0,0 +1,721 @@ +#include +#include +#include +#include +#include +#include +#include + + + +typedef struct tm { + int tm_sec; + int tm_min; + int tm_hour; + int tm_mday; + int tm_mon; + int tm_year; + int tm_wday; + int tm_yday; + int tm_isdst; +} tm; + +extern int __msl_mod(int, int); +extern div_t __msl_div(long, long); +extern int __msl_add(int*, int); +extern int __msl_ladd(long*, long); +extern int __msl_lmul(long*, long); + +static int __leap_year(int year) { + return __msl_mod(year, 4) == 0 && (__msl_mod(year, 100) != 0 || __msl_mod(year, 400) == 100); +} + +static int leap_days(int year, int month) { + int n; + div_t q; + + q = div(year, 4); + n = q.quot; + + q = div(year, 100); + n -= q.quot; + + if (year < 100) { + q = __msl_div(year + 899, 1000); + n += q.quot; + } else { + q = __msl_div(year - 100, 1000); + n += q.quot + 1; + } + + if (__leap_year(year)) { + if (year < 0) { + if (month > 1) { + n++; + } + } else if (month <= 1) { + n--; + } + } + + return n; +} + +#define seconds_per_minute (60L) +#define seconds_per_hour (60L * seconds_per_minute) +#define seconds_per_day (24L * seconds_per_hour) +#define seconds_1900_to_1970 (((365 * 70UL) + 17) * 24 * 60 * 60) + +const short __msl_month_to_days[2][13] = { + {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}, + {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366} +}; + +extern int __isdst(void); +extern time_t __get_time(void); +extern int __to_gm_time(time_t*); + +void __msl_time2tm(time_t in_time, tm* tm) { + unsigned long years, months, days, seconds; + int is_leap_year; + unsigned long time = in_time + seconds_1900_to_1970; + + if (!tm) { + return; + } + + tm->tm_isdst = __isdst(); + + days = time / seconds_per_day; + seconds = time % seconds_per_day; + + tm->tm_wday = (days + 1) % 7; + years = 0; + + for (;;) { + unsigned long days_this_year = __leap_year(years) ? 366 : 365; + + if (days < days_this_year) { + break; + } + + days -= days_this_year; + years += 1; + } + + tm->tm_year = years; + tm->tm_yday = days; + + months = 0; + is_leap_year = __leap_year(years); + + for (;;) { + unsigned long days_thru_this_month = __msl_month_to_days[is_leap_year][months + 1]; + + if (days < days_thru_this_month) { + days -= __msl_month_to_days[is_leap_year][months]; + break; + } + + ++months; + } + + tm->tm_mon = months; + tm->tm_mday = days + 1; + tm->tm_hour = seconds / seconds_per_hour; + seconds %= seconds_per_hour; + tm->tm_min = seconds / seconds_per_minute; + tm->tm_sec = seconds % seconds_per_minute; +} + +static int adjust(int* x, int y, int* z) { + div_t q; + + q = __msl_div(*x, y); + *x = q.rem; + return __msl_add(z, q.quot); +} + +static int __tm2time(tm* tm, time_t* time) { + long days; + time_t seconds, day_secs; + + if (!tm || !time) { + return 0; + } + + --tm->tm_mday; + + if (!adjust(&tm->tm_sec, 60, &tm->tm_min)) { + goto no_exit; + } + if (!adjust(&tm->tm_min, 60, &tm->tm_hour)) { + goto no_exit; + } + if (!adjust(&tm->tm_hour, 24, &tm->tm_mday)) { + goto no_exit; + } + if (!adjust(&tm->tm_mon, 12, &tm->tm_year)) { + goto no_exit; + } + + days = tm->tm_year; + + if (!__msl_lmul(&days, 365)) { + goto no_exit; + } + if (!__msl_ladd(&days, leap_days(tm->tm_year, tm->tm_mon))) { + goto no_exit; + } + if (!__msl_ladd(&days, __msl_month_to_days[0][tm->tm_mon])) { + goto no_exit; + } + if (!__msl_ladd(&days, tm->tm_mday)) { + goto no_exit; + } + if (days < 0 || days > (ULONG_MAX / seconds_per_day)) { + goto no_exit; + } + + day_secs = days * seconds_per_day; + seconds = (tm->tm_hour * seconds_per_hour) + (tm->tm_min * seconds_per_minute) + tm->tm_sec; + + if (seconds > ULONG_MAX - day_secs) { + goto no_exit; + } + + seconds += day_secs; + seconds -= seconds_1900_to_1970; + *time = seconds; + + __msl_time2tm(seconds, tm); + return 1; + +no_exit: + return 0; +} + +extern clock_t __get_clock(void); + +clock_t clock(void) { + return __get_clock(); +} + +time_t mktime(tm* timeptr) { + struct tm tm = *timeptr; + time_t time; + + if (!__tm2time(&tm, &time)) { + return (time_t)-1; + } + + *timeptr = tm; + return time; +} + +static void clear_tm(struct tm* tm) { + tm->tm_sec = 0; + tm->tm_min = 0; + tm->tm_hour = 0; + tm->tm_mday = 1; + tm->tm_mon = 0; + tm->tm_year = 0; + tm->tm_wday = 1; + tm->tm_yday = 0; + tm->tm_isdst = -1; +} + +static char* find_name(const char* names, int index) { + static char extracted_name[32]; + int i; + const char* start = names; + const char* end; + + for (i = 0; i <= index; i++) { + end = strchr(start, '|'); + if (i == index) { + if (end == NULL) { + strcpy(extracted_name, start); + } else { + strncpy(extracted_name, start, end - start); + extracted_name[end - start] = '\0'; + } + break; + } + start = end + 1; + } + + return extracted_name; +} + +char* asctime(const struct tm* timeptr) { + static char asctime_result[26]; + char* result = asctime_result; + if (!timeptr) { + strcpy(result, "xxx xxx xx xx:xx:xx xxxx\n"); + } else { + char day[4]; + char month[4]; + strncpy(day, find_name(_current_locale.time_cmpt_ptr->Day_Names, timeptr->tm_wday * 2), 3); + day[3] = 0; + strncpy(month, find_name(_current_locale.time_cmpt_ptr->MonthNames, timeptr->tm_mon * 2), 3); + month[3] = 0; + sprintf(result, "%s %s%3d %.2d:%.2d:%.2d %d\n", day, month, timeptr->tm_mday, + timeptr->tm_hour, timeptr->tm_min, timeptr->tm_sec, timeptr->tm_year + 1900); + } + return result; +} + +struct tm* localtime(const time_t* timer); + +char* ctime(const time_t* timer) { + struct tm* calendar = localtime(timer); + char* result = asctime(calendar); + char day[4]; + char month[4]; + strncpy(day, find_name(_current_locale.time_cmpt_ptr->Day_Names, calendar->tm_wday * 2), 3); + day[3] = 0; + strncpy(month, find_name(_current_locale.time_cmpt_ptr->MonthNames, calendar->tm_mon * 2), 3); + month[3] = 0; + sprintf(result, "%.3s %.3s %2d %.2d:%.2d:%.2d %4d\n", day, month, + calendar->tm_mday, calendar->tm_hour, calendar->tm_min, calendar->tm_sec, + calendar->tm_year + 1900); + return result; +} + +static time_t time(time_t* timer) { + time_t result = __get_time(); + + if (timer) { + *timer = result; + } + + return result; +} + +static struct tm* gmtime(const time_t* timer) { + static struct tm gmtime_tm; + time_t time; + + if (!timer) { + clear_tm(&gmtime_tm); + return &gmtime_tm; + } + + time = *timer; + if (!__to_gm_time(&time)) { + return NULL; + } + + __msl_time2tm(time, &gmtime_tm); + gmtime_tm.tm_isdst = 0; + return &gmtime_tm; +} + +struct tm* localtime(const time_t* timer) { + static struct tm localtime_tm; + + if (!timer) { + clear_tm(&localtime_tm); + localtime_tm.tm_isdst = __isdst(); + return &localtime_tm; + } else { + __msl_time2tm(*timer, &localtime_tm); + localtime_tm.tm_isdst = __isdst(); + return &localtime_tm; + } +} + +static int emit(char* str, size_t size, size_t* max_size, const char* format_str, ...) { + va_list args; + va_start(args, format_str); + + if (size > *max_size) { + return 0; + } + + *max_size -= size; + return vsprintf(str, format_str, args); +} + +time_t __MSL_ISO8601NewYear(int year) { + struct tm ts0; + time_t timeval; + short StartMday[7] = {2, 3, 4, 29, 30, 31, 1}; + + ts0.tm_sec = 0; + ts0.tm_min = 0; + ts0.tm_hour = 0; + ts0.tm_mon = 0; + ts0.tm_isdst = -1; + ts0.tm_mday = 0; + ts0.tm_wday = 7; + ts0.tm_year = year; + while ((ts0.tm_wday != 0) && (ts0.tm_mday <= 7)) { + ts0.tm_mday++; + timeval = mktime(&ts0); + } + ts0.tm_mday = StartMday[ts0.tm_mday - 1]; + if (ts0.tm_mday >= 29) { + ts0.tm_mon = 11; + ts0.tm_year--; + } + return mktime(&ts0); +} + +static double difftime(time_t time1, time_t time0) { + time_t diff; + + if (time1 >= time0) { + return time1 - time0; + } + + diff = time0 - time1; + return -(double)diff; +} + +extern const double msl_seconds_per_day; +extern const double msl_days_per_week; +extern const double msl_seconds_per_minute; + +int __MSL_ISO8601Week(const struct tm* tmptr, int* WYear) { + struct WeekYear { + int Year; + time_t Start; + }; + struct WeekYear LastYear, ThisYear, NextYear; + struct WeekYear* WyPtr; + struct tm Localtm = *tmptr; + double Days; + int WeekNo; + time_t GivenTimeVal; + + LastYear.Year = tmptr->tm_year - 1; + LastYear.Start = __MSL_ISO8601NewYear(LastYear.Year); + ThisYear.Year = tmptr->tm_year; + ThisYear.Start = __MSL_ISO8601NewYear(ThisYear.Year); + NextYear.Year = tmptr->tm_year + 1; + NextYear.Start = __MSL_ISO8601NewYear(NextYear.Year); + + GivenTimeVal = mktime(&Localtm); + if ((LastYear.Start <= GivenTimeVal) && (GivenTimeVal < ThisYear.Start)) { + WyPtr = &LastYear; + } else if ((ThisYear.Start <= GivenTimeVal) && (GivenTimeVal < NextYear.Start)) { + WyPtr = &ThisYear; + } else { + WyPtr = &NextYear; + } + *WYear = WyPtr->Year; + { + double diff; + + if (GivenTimeVal >= WyPtr->Start) { + diff = (double)(GivenTimeVal - WyPtr->Start); + } else { + diff = -(double)(WyPtr->Start - GivenTimeVal); + } + Days = diff / msl_seconds_per_day; + } + WeekNo = (int)(Days / msl_days_per_week) + 1; + return WeekNo; +} + +static int week_num(const struct tm* tm, int starting_day) { + int days = tm->tm_yday; + + days -= __msl_mod(tm->tm_wday - starting_day, 7); + + if (days < 0) { + return 0; + } + + return (days / 7) + 1; +} + + + +static int emit_string(char* str, size_t size, size_t* max_size, const char* value) { + return emit(str, size, max_size, "%s", value); +} + + +size_t strftime(char* str, size_t max_size, const char* format_str, const struct tm* timeptr) { + char name[32]; + size_t num_chars, chars_written, space_remaining; + struct __locale* locale = &_current_locale; + const char* format_ptr; + const char* curr_format; + int n, ISO8601Year, ISO8601WeekNo; + struct tm tm; + struct tm defaults = {0, 0, 0, 1, 0, 0, 1, 0, -1}; + + if ((space_remaining = --max_size) <= 0) { + return 0; + } + + + tm = defaults; + + if (timeptr) { + tm = *timeptr; + + if (mktime(&tm) == (time_t)-1) { + tm = defaults; + } + } + + format_ptr = format_str; + chars_written = 0; + + while (*format_ptr) { + if (!(curr_format = strchr(format_ptr, '%'))) { + if ((num_chars = strlen(format_ptr)) != 0) { + if (num_chars <= space_remaining) { + memcpy(str, format_ptr, num_chars); + + chars_written += num_chars; + str += num_chars; + space_remaining -= num_chars; + } else { + return 0; + } + } + break; + } + + if ((num_chars = curr_format - format_ptr) != 0) { + if (num_chars <= space_remaining) { + memcpy(str, format_ptr, num_chars); + + chars_written += num_chars; + str += num_chars; + space_remaining -= num_chars; + } else { + return 0; + } + } + + format_ptr = curr_format; + if (format_ptr[1] == 'E' || format_ptr[1] == 'O') { + ++format_ptr; + } + + switch (*++format_ptr) { + case 'a': + strcpy(name, find_name(locale->time_cmpt_ptr->Day_Names, tm.tm_wday * 2)); + num_chars = emit_string(str, strlen(name), &space_remaining, name); + break; + + case 'A': + strcpy(name, find_name(locale->time_cmpt_ptr->Day_Names, tm.tm_wday * 2 + 1)); + num_chars = emit_string(str, strlen(name), &space_remaining, name); + break; + + case 'b': + case 'h': { + num_chars = + emit(str, 3, &space_remaining, "%.3s", + find_name(locale->time_cmpt_ptr->MonthNames, tm.tm_mon * 2)); + break; + } + + case 'B': + strcpy(name, find_name(locale->time_cmpt_ptr->MonthNames, tm.tm_mon * 2 + 1)); + num_chars = emit_string(str, strlen(name), &space_remaining, name); + break; + + case 'c': + num_chars = strftime(str, space_remaining + 1, locale->time_cmpt_ptr->DateTime_Format, &tm); + space_remaining -= num_chars; + break; + + case 'd': + num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_mday); + break; + + case 'D': + num_chars = strftime(str, space_remaining + 1, "%m/%d/%y", &tm); + break; + + case 'e': + num_chars = emit(str, 2, &space_remaining, "%2d", tm.tm_mday); + break; + + case 'F': + num_chars = + emit(str, 10, &space_remaining, "%.4d-%.2d-%.2d", tm.tm_year + 1900, tm.tm_mon + 1, + tm.tm_mday); + break; + + case 'g': + ISO8601WeekNo = __MSL_ISO8601Week(timeptr, &ISO8601Year); + num_chars = emit(str, 2, &space_remaining, "%.2d", ISO8601Year % 100); + break; + + case 'G': + ISO8601WeekNo = __MSL_ISO8601Week(timeptr, &ISO8601Year); + num_chars = emit(str, 4, &space_remaining, "%.4d", ISO8601Year + 1900); + break; + + case 'H': + num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_hour); + break; + + case 'I': + num_chars = emit(str, 2, &space_remaining, "%.2d", + (n = tm.tm_hour % 12) ? n : 12); + break; + + case 'j': + num_chars = emit(str, 3, &space_remaining, "%.3d", tm.tm_yday + 1); + break; + + case 'm': + num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_mon + 1); + break; + + case 'M': + num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_min); + break; + + case 'n': + num_chars = emit(str, 2, &space_remaining, "\n"); + break; + + case 'p': { + char* name; + + name = find_name(locale->time_cmpt_ptr->am_pm, tm.tm_hour < 12 ? 0 : 1); + num_chars = emit_string(str, strlen(name), &space_remaining, name); + break; + } + + case 'r': + num_chars = strftime(str, space_remaining + 1, locale->time_cmpt_ptr->Twelve_hr_format, &tm); + space_remaining -= num_chars; + break; + + case 'R': + num_chars = strftime(str, space_remaining + 1, "%H:%M", &tm); + space_remaining -= num_chars; + break; + + case 'S': + num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_sec); + break; + + case 't': + num_chars = emit(str, 2, &space_remaining, "\t"); + break; + + case 'T': + num_chars = strftime(str, space_remaining + 1, "%H:%M:%S", &tm); + space_remaining -= num_chars; + break; + + case 'u': + if (tm.tm_wday == 0) { + num_chars = emit(str, 1, &space_remaining, "7"); + } else { + num_chars = emit(str, 1, &space_remaining, "%.1d", tm.tm_wday); + } + break; + + case 'U': + num_chars = emit(str, 2, &space_remaining, "%.2d", week_num(&tm, 0)); + break; + + case 'V': + ISO8601WeekNo = __MSL_ISO8601Week(timeptr, &ISO8601Year); + num_chars = emit(str, 2, &space_remaining, "%.2d", ISO8601WeekNo); + break; + + case 'w': + num_chars = emit(str, 1, &space_remaining, "%.1d", tm.tm_wday); + break; + + case 'W': + num_chars = emit(str, 2, &space_remaining, "%.2d", week_num(&tm, 1)); + break; + + case 'x': + num_chars = strftime(str, space_remaining + 1, locale->time_cmpt_ptr->Date_Format, &tm); + space_remaining -= num_chars; + break; + + case 'X': + num_chars = strftime(str, space_remaining + 1, locale->time_cmpt_ptr->Time_Format, &tm); + space_remaining -= num_chars; + break; + + case 'y': + case 'C': + num_chars = emit(str, 2, &space_remaining, "%.2d", tm.tm_year % 100); + break; + + case 'Y': + num_chars = emit(str, 4, &space_remaining, "%.4d", tm.tm_year + 1900); + break; + + case 'z': { + time_t local, utc, now; + struct tm localtm, *utctmptr; + double diff, diffmins, diffhours; + + now = time(NULL); + utctmptr = gmtime(&now); + if (utctmptr == NULL) { + num_chars = emit(str, 4, &space_remaining, "0000"); + } else { + localtm = *localtime(&now); + local = mktime(&localtm); + utc = mktime(utctmptr); + diff = difftime(local, utc); + diffhours = (int)diff / 3600; + diffmins = __abs(diff / msl_seconds_per_minute - msl_seconds_per_minute * diffhours); + num_chars = emit(str, 5, &space_remaining, "%+03.0f%02.0f", diffhours, diffmins); + } + break; + } + + case 'Z': { + char* TimeZone = locale->time_cmpt_ptr->TimeZone; + + if (*TimeZone == '\0') { + num_chars = 0; + *str = '\0'; + } else { + num_chars = emit_string(str, strlen(TimeZone), &space_remaining, TimeZone); + } + break; + } + + case '%': + num_chars = emit(str, 2, &space_remaining, "%%", *format_ptr); + break; + + default: + num_chars = emit(str, 2, &space_remaining, "%%%c", *format_ptr); + break; + } + + if (!num_chars) { + return 0; + } + + chars_written += num_chars; + str += num_chars; + ++format_ptr; + } + + *str = 0; + if (max_size < chars_written) { + return 0; + } else { + return chars_written; + } +} + +const double msl_seconds_per_day = 86400.0; +const double msl_days_per_week = 7.0; +const double msl_seconds_per_minute = 60.0; diff --git a/libs/MSL/src/MSL_Common/wprintf.c b/libs/MSL/src/MSL_Common/wprintf.c new file mode 100644 index 00000000..76dbf504 --- /dev/null +++ b/libs/MSL/src/MSL_Common/wprintf.c @@ -0,0 +1,1320 @@ +#include +typedef struct { wchar_t* wCharStr; size_t MaxCharCount; size_t CharsWritten; } __wOutStrCtrl; + + + + + + + + + + + + + +#define LDBL_MANT_DIG 53 + +#define TARGET_FLOAT_BITS 64 +#define TARGET_FLOAT_BYTES (TARGET_FLOAT_BITS / 8) +#define TARGET_FLOAT_MAX_EXP LDBL_MAX_EXP +#define TARGET_FLOAT_MANT_DIG LDBL_MANT_DIG +#define TARGET_FLOAT_IMPLICIT_J_BIT 1 +#define TARGET_FLOAT_MANT_BITS (TARGET_FLOAT_MANT_DIG - TARGET_FLOAT_IMPLICIT_J_BIT) +#define TARGET_FLOAT_EXP_BITS (TARGET_FLOAT_BITS - TARGET_FLOAT_MANT_BITS - 1) + +enum justification_options { left_justification, right_justification, zero_fill }; + +enum sign_options { only_minus, sign_always, space_holder }; + +enum argument_options { + normal_argument, + char_argument, + short_argument, + long_argument, + long_long_argument, + wchar_argument, + + intmax_argument, + size_t_argument, + ptrdiff_argument, + + long_double_argument, +}; + +typedef struct { + unsigned char justification_options; + unsigned char sign_options; + unsigned char precision_specified; + unsigned char alternate_form; + unsigned char argument_options; + wchar_t conversion_char; + int field_width; + int precision; +} print_format; + + + +static const wchar_t* parse_format(const wchar_t* format_string, va_list* arg, print_format* format) { + print_format f; + const wchar_t* s = format_string; + wchar_t c; + int flag_found; + f.justification_options = right_justification; + f.sign_options = only_minus; + f.precision_specified = 0; + f.alternate_form = 0; + f.argument_options = normal_argument; + f.field_width = 0; + f.precision = 0; + + if ((c = *++s) == '%') { + f.conversion_char = c; + *format = f; + return s + 1; + } + + while (1) { + flag_found = 1; + + switch (c) { + case '-': + f.justification_options = left_justification; + break; + case '+': + f.sign_options = sign_always; + break; + case ' ': + if (f.sign_options != sign_always) { + f.sign_options = space_holder; + } + break; + case '#': + f.alternate_form = 1; + break; + case '0': + if (f.justification_options != left_justification) { + f.justification_options = zero_fill; + } + break; + default: + flag_found = 0; + break; + } + + if (flag_found) { + c = *++s; + } else { + break; + } + } + + if (c == '*') { + if ((f.field_width = va_arg(*arg, int)) < 0) { + f.justification_options = left_justification; + f.field_width = -f.field_width; + } + + c = *++s; + } else { + while ((c >= 0x100 ? 0 : _current_locale.ctype_cmpt_ptr->wctype_map_ptr[c] & 0x8) != 0) { + f.field_width = f.field_width * 10 + (c - '0'); + c = *++s; + } + } + + if (f.field_width > 509) { + f.conversion_char = 0xFFFF; + *format = f; + return s + 1; + } + + if (c == '.') { + f.precision_specified = 1; + + if ((c = *++s) == '*') { + if ((f.precision = va_arg(*arg, int)) < 0) { + f.precision_specified = 0; + } + + c = *++s; + } else { + while ((c >= 0x100 ? 0 : _current_locale.ctype_cmpt_ptr->wctype_map_ptr[c] & 0x8) != 0) + { + f.precision = f.precision * 10 + (c - '0'); + c = *++s; + } + } + } + + flag_found = 1; + + switch (c) { + case 'h': + f.argument_options = short_argument; + + if (s[1] == 'h') { + f.argument_options = char_argument; + c = *++s; + } + + break; + + case 'l': + f.argument_options = long_argument; + + if (s[1] == 'l') { + f.argument_options = long_long_argument; + c = *++s; + } + break; + case 'L': + f.argument_options = long_double_argument; + break; + case 'j': + f.argument_options = intmax_argument; + break; + case 't': + f.argument_options = ptrdiff_argument; + break; + case 'z': + f.argument_options = size_t_argument; + break; + default: + flag_found = 0; + break; + } + + if (flag_found) { + c = *++s; + } + + switch (f.conversion_char = c) { + case 'd': + case 'i': + case 'u': + case 'o': + case 'x': + case 'X': + if (f.argument_options == long_double_argument) { + f.argument_options = 4; + } + + if (!f.precision_specified) { + f.precision = 1; + } else if (f.justification_options == zero_fill) { + f.justification_options = right_justification; + } + break; + + case 'f': + case 'F': + if (f.argument_options == short_argument || f.argument_options == intmax_argument || + f.argument_options == size_t_argument || f.argument_options == ptrdiff_argument || + f.argument_options == long_long_argument) + { + f.conversion_char = 0xFFFF; + break; + } + + if (!f.precision_specified) { + f.precision = 6; + } + break; + + case 'a': + case 'A': + if (!f.precision_specified) { + f.precision = 0xD; + } + + if (f.argument_options == short_argument || f.argument_options == intmax_argument || + f.argument_options == size_t_argument || f.argument_options == ptrdiff_argument || + f.argument_options == long_long_argument || f.argument_options == char_argument) + { + f.conversion_char = 0xFFFF; + } + + break; + + case 'g': + case 'G': + if (!f.precision) { + f.precision = 1; + } + + case 'e': + case 'E': + if (f.argument_options == short_argument || f.argument_options == intmax_argument || + f.argument_options == size_t_argument || f.argument_options == ptrdiff_argument || + f.argument_options == long_long_argument || f.argument_options == char_argument) + { + f.conversion_char = 0xFFFF; + break; + } + + if (!f.precision_specified) { + f.precision = 6; + } + break; + + case 'p': + f.argument_options = long_argument; + f.alternate_form = 1; + f.conversion_char = 'x'; + f.precision = 8; + break; + + case 'c': + if (f.argument_options == long_argument) { + f.argument_options = wchar_argument; + } else { + if (f.precision_specified || f.argument_options != normal_argument) { + f.conversion_char = 0xFFFF; + } + } + + break; + + case 's': + if (f.argument_options == long_argument) { + f.argument_options = wchar_argument; + } else { + if (f.argument_options != normal_argument) { + f.conversion_char = 0xFFFF; + } + } + + break; + + case 'n': + if (f.argument_options == long_double_argument) { + f.argument_options = 0x4; + } + + break; + + default: + f.conversion_char = 0xFFFF; + break; + } + + *format = f; + return s + 1; +} + +static wchar_t* long2str(signed long num, wchar_t* buff, print_format format) { + unsigned long unsigned_num, base; + wchar_t* p; + int n, digits; + int minus = 0; + unsigned_num = num; + minus = 0; + + p = buff; + *--p = 0; + digits = 0; + + if (!num && !format.precision && !(format.alternate_form && format.conversion_char == 'o')) { + return p; + } + + switch (format.conversion_char) { + case 'd': + case 'i': + base = 10; + + if (num < 0) { + if (num != 0x80000000L) { + unsigned_num = -unsigned_num; + } + + minus = 1; + } + break; + + case 'o': + base = 8; + format.sign_options = only_minus; + break; + + case 'u': + base = 10; + format.sign_options = only_minus; + break; + + case 'x': + case 'X': + base = 16; + format.sign_options = only_minus; + break; + } + + do { + n = unsigned_num % base; + unsigned_num /= base; + + if (n < 10) { + n += '0'; + } else { + n -= 10; + + if (format.conversion_char == 'x') { + n += 'a'; + } else { + n += 'A'; + } + } + + *--p = n; + ++digits; + } while (unsigned_num != 0); + + if (base == 8 && format.alternate_form && *p != '0') { + *--p = '0'; + ++digits; + } + + if (format.justification_options == zero_fill) { + format.precision = format.field_width; + + if (minus || format.sign_options != only_minus) + --format.precision; + + if (base == 16 && format.alternate_form) + format.precision -= 2; + } + + if (buff - p + format.precision > 509) + return 0; + + while (digits < format.precision) { + *--p = '0'; + ++digits; + } + + if (base == 16 && format.alternate_form) { + *--p = format.conversion_char; + *--p = '0'; + } + + if (minus) { + *--p = '-'; + } else if (format.sign_options == sign_always) { + *--p = '+'; + } else if (format.sign_options == space_holder) { + *--p = ' '; + } + + return p; +} + +static wchar_t* longlong2str(signed long long num, wchar_t* pBuf, print_format fmt) { + unsigned long long unsigned_num, base; + wchar_t* p; + int n, digits; + int minus = 0; + unsigned_num = num; + minus = 0; + p = pBuf; + *--p = 0; + digits = 0; + + if (!num && !fmt.precision && !(fmt.alternate_form && fmt.conversion_char == 'o')) { + return p; + } + + switch (fmt.conversion_char) { + case 'd': + case 'i': + base = 10; + + if (num < 0) { + if (num != 0x8000000000000000LL) { + unsigned_num = -unsigned_num; + } + + minus = 1; + } + break; + case 'o': + base = 8; + fmt.sign_options = only_minus; + break; + case 'u': + base = 10; + fmt.sign_options = only_minus; + break; + case 'x': + case 'X': + base = 16; + fmt.sign_options = only_minus; + break; + } + + do { + n = unsigned_num % base; + unsigned_num /= base; + + if (n < 10) { + n += '0'; + } else { + n -= 10; + if (fmt.conversion_char == 'x') { + n += 'a'; + } else { + n += 'A'; + } + } + + *--p = n; + ++digits; + } while (unsigned_num != 0); + + if (base == 8 && fmt.alternate_form && *p != '0') { + *--p = '0'; + ++digits; + } + + if (fmt.justification_options == zero_fill) { + fmt.precision = fmt.field_width; + + if (minus || fmt.sign_options != only_minus) { + --fmt.precision; + } + + if (base == 16 && fmt.alternate_form) { + fmt.precision -= 2; + } + } + + if (pBuf - p + fmt.precision > 509) { + return 0; + } + + while (digits < fmt.precision) { + *--p = '0'; + ++digits; + } + + if (base == 16 && fmt.alternate_form) { + *--p = fmt.conversion_char; + *--p = '0'; + } + + if (minus) { + *--p = '-'; + } else if (fmt.sign_options == sign_always) { + *--p = '+'; + } else if (fmt.sign_options == space_holder) { + *--p = ' '; + } + + return p; +} + +static wchar_t* double2hex(long double num, wchar_t* buff, print_format format) { + wchar_t *p; + unsigned char *q; + unsigned char working_byte; + int expbits, expmask; + unsigned snum; + long exp; + print_format exp_format; + int hex_precision; + int mantissa_bit; + decform form; + decimal dec; + int radix_marker; + + radix_marker = *(unsigned char *)(__lconv).decimal_point; + p = buff; + + if (format.precision > 509) { + return 0; + } + + form.style = (char)0; + form.digits = 0x20; + __num2dec(&form, num, &dec); + + if (fabs(num) == 0.0) { + p = buff - 6; + wcscpy(p, L"0x0p0"); + return p; + } + if (*dec.sig.text == 'I') { + if (dec.sign) { + p = buff - 5; + if (format.conversion_char == 'A') wcscpy(p, L"-INF"); + else wcscpy(p, L"-inf"); + } + else { + p = buff - 4; + if (format.conversion_char == 'A') wcscpy(p, L"INF"); + else wcscpy(p, L"inf"); + } + + return p; + } else if (*dec.sig.text == 'N') { + if (dec.sign) { + p = buff - 5; + if (format.conversion_char == 'A') wcscpy(p, L"-NAN"); + else wcscpy(p, L"-nan"); + } + else { + p = buff - 4; + if (format.conversion_char == 'A') wcscpy(p, L"NAN"); + else wcscpy(p, L"nan"); + } + + return p; + } + + exp_format.justification_options = right_justification; + exp_format.sign_options = sign_always; + exp_format.precision_specified = 0; + exp_format.alternate_form = 0; + exp_format.argument_options = normal_argument; + exp_format.field_width = 0; + exp_format.precision = 1; + exp_format.conversion_char = 'd'; + + expbits = 11; + expmask = 0x7FF; + + snum = ((unsigned char *)&num)[0] << 25; + if (TARGET_FLOAT_EXP_BITS > 7) + snum |= ((unsigned char *)&num)[1] << 17; + if (TARGET_FLOAT_EXP_BITS > 15) + snum |= ((unsigned char *)&num)[2] << 9; + if (TARGET_FLOAT_EXP_BITS > 23) + snum |= ((unsigned char *)&num)[3] << 1; + + snum = (snum >> (32 - expbits)) & expmask; + + exp = snum - 0x3FF; + + p = long2str(exp, buff, exp_format); + if (format.conversion_char == 'a') + *--p = 'p'; + else + *--p = 'P'; + q = (unsigned char *)# + + if (TARGET_FLOAT_IMPLICIT_J_BIT) { + mantissa_bit = (1 + expbits + format.precision * 4) - 1; + } + else { + mantissa_bit = (1 + expbits + format.precision * 4) - 4; + } + + for (hex_precision = format.precision; hex_precision >= 1; hex_precision--) { + if (mantissa_bit < 64) { + int mantissa_byte; + + mantissa_byte = mantissa_bit >> 3; + working_byte = (*(q + mantissa_byte)) >> (7 - (mantissa_bit & 7)); + + if ((mantissa_bit & ~7) != ((mantissa_bit - 4) & ~7)) { + working_byte |= (unsigned char)(((*(q + (mantissa_byte - 1))) << 8) >> (7 - ((mantissa_bit) & 7))); + } + + if (!TARGET_FLOAT_IMPLICIT_J_BIT) { + if (mantissa_bit == 1 + expbits) { + *--p = radix_marker; + working_byte &= 0x1; + } + } + + if ((working_byte &= 0xF) < 10) { + working_byte = (unsigned char)(working_byte + '0'); + } + else + if (format.conversion_char == 'a') { + working_byte = (unsigned char)(working_byte + 'a' - 10); + } + else { + working_byte = (unsigned char)(working_byte + 'A' - 10); + } + } + else { + working_byte = '0'; + } + + *--p = working_byte; + mantissa_bit -= 4; + } + + if (TARGET_FLOAT_IMPLICIT_J_BIT){ + if (format.precision || format.alternate_form) { + *--p = radix_marker; + } + + *--p = '1'; + } + + if (format.conversion_char == 'a') { + *--p = 'x'; + } + else { + *--p = 'X'; + } + + *--p = '0'; + + if (dec.sign) { + *--p = '-'; + } + else if (format.sign_options == sign_always) { + *--p = '+'; + } + else if (format.sign_options == space_holder) { + *--p = ' '; + } + + return p; +} + +static void round_decimal(decimal* dec, int new_length) { + char c; + char* p; + int carry; + + if (new_length < 0) { + return_zero: + dec->exp = 0; + dec->sig.length = 1; + *dec->sig.text = '0'; + return; + } + + if (new_length >= dec->sig.length) { + return; + } + + p = (char*)dec->sig.text + new_length + 1; + c = *--p - '0'; + + if (c == 5) { + char* q = &((char*)dec->sig.text)[dec->sig.length]; + + while (--q > p && *q == '0') + ; + carry = q == p ? p[-1] & 1 : 1; + } else { + carry = c > 5; + } + + while (new_length != 0) { + c = *--p - '0' + carry; + + if ((carry = (c > 9)) != 0 || c == 0) { + --new_length; + } else { + *p = c + '0'; + break; + } + } + + if (carry != 0) { + dec->exp += 1; + dec->sig.length = 1; + *dec->sig.text = '1'; + return; + } else if (new_length == 0) { + goto return_zero; + } + + dec->sig.length = new_length; +} + +static wchar_t* float2str(double num, wchar_t* buff, print_format format) { + char out_buf[512]; + decimal dec; + decform form; + wchar_t* p; + char* p2; + wchar_t c; + char* p3; + unsigned char* q; + int n, digits, sign; + int int_digits, frac_digits; + int radix_marker; + int used_bytes; + + radix_marker = *(unsigned char*)__lconv.decimal_point; + + if (format.precision > 509) { + return 0; + } + + form.style = 0; + form.digits = 0x20; + __num2dec(&form, num, &dec); + p3 = (char*)(dec.sig.text + dec.sig.length); + + while (dec.sig.length > 1 && *--p3 == '0') { + --dec.sig.length; + ++dec.exp; + } + + switch (*dec.sig.text) { + case '0': + dec.exp = 0; + break; + case 'I': + if (num < 0) { + c = format.conversion_char; + p = buff - 5; + + if ((c >= 0x100 ? 0 : _current_locale.ctype_cmpt_ptr->wctype_map_ptr[c] & 0x200) != 0) { + wcscpy(p, L"-INF"); + } else { + wcscpy(p, L"-inf"); + } + } else { + c = format.conversion_char; + p = buff - 4; + if ((c >= 0x100 ? 0 : _current_locale.ctype_cmpt_ptr->wctype_map_ptr[c] & 0x200) != 0) { + wcscpy(p, L"INF"); + } else { + wcscpy(p, L"inf"); + } + } + + return p; + + case 'N': + if (dec.sign) { + c = format.conversion_char; + p = buff - 5; + if ((c >= 0x100 ? 0 : _current_locale.ctype_cmpt_ptr->wctype_map_ptr[c] & 0x200) != 0) { + wcscpy(p, L"-NAN"); + } else { + wcscpy(p, L"-nan"); + } + } else { + c = format.conversion_char; + p = buff - 4; + if ((c >= 0x100 ? 0 : _current_locale.ctype_cmpt_ptr->wctype_map_ptr[c] & 0x200) != 0) { + wcscpy(p, L"NAN"); + } else { + wcscpy(p, L"nan"); + } + } + + return p; + } + + dec.exp += dec.sig.length - 1; + + p2 = out_buf + sizeof(out_buf); + *--p2 = 0; + + switch (format.conversion_char) { + case 'g': + case 'G': + + if (dec.sig.length > format.precision) { + round_decimal(&dec, format.precision); + } + + if (dec.exp < -4 || dec.exp >= format.precision) { + if (format.alternate_form) { + --format.precision; + } else { + format.precision = dec.sig.length - 1; + } + + if (format.conversion_char == 'g') { + format.conversion_char = 'e'; + } else { + format.conversion_char = 'E'; + } + + goto e_format; + } + + if (format.alternate_form) { + format.precision -= dec.exp + 1; + } else { + if ((format.precision = dec.sig.length - (dec.exp + 1)) < 0) { + format.precision = 0; + } + } + + goto f_format; + + case 'e': + case 'E': + e_format: + + if (dec.sig.length > format.precision + 1) { + round_decimal(&dec, format.precision + 1); + } + + n = dec.exp; + sign = '+'; + + if (n < 0) { + n = -n; + sign = '-'; + } + + for (digits = 0; n || digits < 2; ++digits) { + *--p2 = n % 10 + '0'; + n /= 10; + } + + *--p2 = sign; + *--p2 = format.conversion_char; + + used_bytes = (long)out_buf - (long)p2; + if (used_bytes + format.precision > 0x1FD) { + return NULL; + } + + if (dec.sig.length < format.precision + 1) { + for (n = format.precision + 1 - dec.sig.length + 1; --n;) { + *--p2 = '0'; + } + } + + for (n = dec.sig.length, q = (dec.sig.text + dec.sig.length); --n;) { + *--p2 = *--q; + } + + if (format.precision || format.alternate_form) { + *--p2 = radix_marker; + } + + *--p2 = *dec.sig.text; + + if (dec.sign) + *--p2 = '-'; + else if (format.sign_options == sign_always) + *--p2 = '+'; + else if (format.sign_options == space_holder) + *--p2 = ' '; + + break; + + case 'f': + case 'F': + f_format: + + if ((frac_digits = -dec.exp + dec.sig.length - 1) < 0) + frac_digits = 0; + + if (frac_digits > format.precision) { + round_decimal(&dec, dec.sig.length - (frac_digits - format.precision)); + + if ((frac_digits = -dec.exp + dec.sig.length - 1) < 0) + frac_digits = 0; + } + + if ((int_digits = dec.exp + 1) < 0) + int_digits = 0; + + if (int_digits + frac_digits > 509) + return 0; + + q = dec.sig.text + dec.sig.length; + + for (digits = 0; digits < (format.precision - frac_digits); ++digits) + *--p2 = '0'; + + for (digits = 0; digits < frac_digits && digits < dec.sig.length; ++digits) + *--p2 = *--q; + + for (; digits < frac_digits; ++digits) + *--p2 = '0'; + + if (format.precision || format.alternate_form) + *--p2 = radix_marker; + + if (int_digits) { + for (digits = 0; digits < int_digits - dec.sig.length; ++digits) { + *--p2 = '0'; + } + + for (; digits < int_digits; ++digits) { + *--p2 = *--q; + } + } else { + *--p2 = '0'; + } + + if (dec.sign) { + *--p2 = '-'; + } else if (format.sign_options == sign_always) { + *--p2 = '+'; + } else if (format.sign_options == space_holder) { + *--p2 = ' '; + } + + break; + } + + p = buff - strlen((char*)p2) - 1; + mbstowcs(p, p2, strlen((char*)p2)); + + return p; +} + +static int __wpformatter(void* (*write_proc)(void*, const wchar_t*, size_t), + void* proc_data, const wchar_t* fmt, + va_list args) { + int num_chars, chars_written, field_width; + const wchar_t* format_ptr; + const wchar_t* curr_format; + print_format format; + signed long long_num; + signed long long long_long_num; + long double long_double_num; + wchar_t buff[512]; + wchar_t* buff_ptr; + const wchar_t* string_end; + wchar_t fill_char = ' '; + + format_ptr = fmt; + chars_written = 0; + + while (*format_ptr) { + if (!(curr_format = wcschr((wchar_t*)format_ptr, L'%'))) { + num_chars = wcslen(format_ptr); + chars_written += num_chars; + + if (num_chars && !(*write_proc)(proc_data, format_ptr, num_chars)) { + return -1; + } + + break; + } + + num_chars = curr_format - format_ptr; + chars_written += num_chars; + + if (num_chars && !(*write_proc)(proc_data, format_ptr, num_chars)) { + return -1; + } + + format_ptr = curr_format; + format_ptr = parse_format(format_ptr, (va_list*)args, &format); + + switch (format.conversion_char) { + case 'd': + case 'i': + if (format.argument_options == long_argument) { + long_num = va_arg(args, signed long); + } else if (format.argument_options == long_long_argument) { + long_long_num = va_arg(args, signed long long); + } else if (format.argument_options == intmax_argument) { + long_long_num = va_arg(args, intmax_t); + } else if (format.argument_options == size_t_argument) { + long_num = va_arg(args, size_t); + } else if (format.argument_options == ptrdiff_argument) { + long_num = va_arg(args, ptrdiff_t); + } else { + long_num = va_arg(args, int); + } + + if (format.argument_options == short_argument) { + long_num = (signed short)long_num; + } + + if (format.argument_options == long_long_argument || + format.argument_options == intmax_argument) + { + if (!(buff_ptr = longlong2str(long_long_num, buff + 512, format))) { + goto conversion_error; + } + } else { + if (!(buff_ptr = long2str(long_num, buff + 512, format))) { + goto conversion_error; + } + } + + num_chars = buff + 512 - 1 - buff_ptr; + break; + + case 'o': + case 'u': + case 'x': + case 'X': + if (format.argument_options == long_argument) { + long_num = va_arg(args, unsigned long); + } else if (format.argument_options == long_long_argument) { + long_long_num = va_arg(args, signed long long); + } + else if (format.argument_options == intmax_argument) { + long_long_num = va_arg(args, intmax_t); + } + else if (format.argument_options == size_t_argument) { + long_num = va_arg(args, size_t); + } + else if (format.argument_options == ptrdiff_argument) { + long_num = va_arg(args, ptrdiff_t); + } + else { + long_num = va_arg(args, unsigned int); + } + + if (format.argument_options == short_argument) { + long_num = (unsigned short)long_num; + } + + if ((format.argument_options == long_long_argument) + || format.argument_options == intmax_argument + ) + { + if (!(buff_ptr = longlong2str(long_long_num, buff + 512, format))) { + goto conversion_error; + } + } else { + if (!(buff_ptr = long2str(long_num, buff + 512, format))) { + goto conversion_error; + } + } + + num_chars = buff + 512 - 1 - buff_ptr; + break; + + case 'f': + case 'F': + case 'e': + case 'E': + case 'g': + case 'G': + if (format.argument_options == long_double_argument) { + long_double_num = va_arg(args, long double); + } else { + long_double_num = va_arg(args, double); + } + + if (!(buff_ptr = float2str(long_double_num, buff + 512, format))) { + goto conversion_error; + } + + num_chars = buff + 512 - 1 - buff_ptr; + break; + + case 'a': + case 'A': + if (format.argument_options == long_double_argument) { + long_double_num = va_arg(args, long double); + } else { + long_double_num = va_arg(args, double); + } + + if (!(buff_ptr = double2hex(long_double_num, buff + 512, format))) { + goto conversion_error; + } + + num_chars = buff + 512 - 1 - buff_ptr; + break; + + case 's': + if (format.argument_options == wchar_argument) { + wchar_t* wcs_ptr = va_arg(args, wchar_t*); + + if (wcs_ptr == NULL) { + wcs_ptr = L""; + } + + if (format.alternate_form) { + num_chars = (unsigned char)*wcs_ptr++; + + if (format.precision_specified && num_chars > format.precision) { + num_chars = format.precision; + } + } else if (format.precision_specified) { + num_chars = format.precision; + + if ((string_end = wmemchr((wchar_t*)wcs_ptr, 0, num_chars)) != 0) { + num_chars = string_end - wcs_ptr; + } + + } else { + num_chars = wcslen(wcs_ptr); + } + + buff_ptr = wcs_ptr; + break; + } else { + const char* wcs_ptr = (const char*)va_arg(args, wchar_t*); + + if (wcs_ptr == NULL) { + wcs_ptr = ""; + } + + if (format.alternate_form) { + num_chars = (unsigned char)*wcs_ptr++; + + if (format.precision_specified && num_chars > format.precision) { + num_chars = format.precision; + } + } else if (format.precision_specified) { + num_chars = format.precision; + + if ((string_end = (const wchar_t*)memchr(wcs_ptr, 0, num_chars)) != 0) { + num_chars = (long)string_end - (long)wcs_ptr; + } + } else { + num_chars = strlen(wcs_ptr); + } + + if ((num_chars = mbstowcs(buff, wcs_ptr, num_chars)) < 0) { + goto conversion_error; + } + + buff_ptr = buff; + } + + break; + + case 'n': + + buff_ptr = va_arg(args, wchar_t*); + + switch (format.argument_options) { + case normal_argument: + *(int*)buff_ptr = chars_written; + break; + case short_argument: + *(signed short*)buff_ptr = chars_written; + break; + case long_argument: + *(signed long*)buff_ptr = chars_written; + break; + case intmax_argument: + *(intmax_t*)buff_ptr = chars_written; + break; + case size_t_argument: + *(size_t*)buff_ptr = chars_written; + break; + case ptrdiff_argument: + *(ptrdiff_t*)buff_ptr = chars_written; + break; + case long_long_argument: + *(signed long long*)buff_ptr = chars_written; + break; + } + + continue; + + case 'c': + buff_ptr = buff; + if (format.argument_options == wchar_argument) { + *buff_ptr = va_arg(args, long); + num_chars = 1; + } else { + char s; + s = va_arg(args, int); + num_chars = mbtowc(buff_ptr, &s, 1); + } + break; + + case '%': + buff_ptr = buff; + *buff_ptr = '%'; + num_chars = 1; + break; + + case 0xFF: + default: + conversion_error: + num_chars = wcslen(curr_format); + chars_written += num_chars; + + if (num_chars && !(*write_proc)(proc_data, curr_format, num_chars)) { + return -1; + } + + return chars_written; + break; + } + + field_width = num_chars; + + if (format.justification_options != left_justification) { + fill_char = (format.justification_options == zero_fill) ? '0' : ' '; + + if (((*buff_ptr == '+') || (*buff_ptr == '-') || (*buff_ptr == ' ')) && + (fill_char == '0')) + { + if ((*write_proc)(proc_data, buff_ptr, 1) == 0) { + return -1; + } + + ++buff_ptr; + num_chars--; + } + + while (field_width < format.field_width) { + if ((*write_proc)(proc_data, (wchar_t*)&fill_char, 1) == 0) { + return -1; + } + + ++field_width; + } + } + + if (num_chars && !(*write_proc)(proc_data, buff_ptr, num_chars)) { + return -1; + } + + if (format.justification_options == left_justification) { + while (field_width < format.field_width) { + wchar_t blank = L' '; + + if ((*write_proc)(proc_data, (wchar_t*)&blank, 1) == 0) { + return -1; + } + + ++field_width; + } + } + + chars_written += field_width; + } + + return chars_written; +} + +void* __wStringWrite(void* wosc, const wchar_t* buffer, size_t numchars) { + size_t tobewritten; + void* res; + __wOutStrCtrl* wOscp = (__wOutStrCtrl*)wosc; + tobewritten = ((wOscp->CharsWritten + numchars) <= wOscp->MaxCharCount) ? numchars : wOscp->MaxCharCount - wOscp->CharsWritten; + res = (void*)wmemcpy(wOscp->wCharStr + wOscp->CharsWritten, buffer, tobewritten); + wOscp->CharsWritten += tobewritten; + return res; +} + +int swprintf(wchar_t *dst, size_t maxlen, const wchar_t *fmt, ...) { + int written; + va_list args; + __wOutStrCtrl ctx; + + ctx.wCharStr = dst; + + va_start(args, fmt); + ctx.MaxCharCount = maxlen; + ctx.CharsWritten = 0; + written = __wpformatter(__wStringWrite, &ctx, fmt, args); + va_end(args); + + if (written >= 0) { + if ((size_t)written < maxlen) { + dst[written] = '\0'; + return written; + } + dst[maxlen - 1] = '\0'; + return -1; + } + return written; +} + + diff --git a/libs/MSL/src/MSL_Common_Embedded/ansi_fp.c b/libs/MSL/src/MSL_Common_Embedded/ansi_fp.c new file mode 100644 index 00000000..aebc6288 --- /dev/null +++ b/libs/MSL/src/MSL_Common_Embedded/ansi_fp.c @@ -0,0 +1,671 @@ +#include +#define LDBL_MAX DBL_MAX + + + +typedef unsigned long long d_int; + +static inline int __count_trailing_zerol(unsigned long x) { return 32 - __cntlzw(~x & (x - 1)); } + +static int __count_trailing_zero(double n) { + unsigned long* array = (unsigned long*)&n; + + unsigned long hi = array[0] | 0x100000; + unsigned long lo = array[1]; + int zeros = __count_trailing_zerol(lo); + + if (lo == 0) { + return 32 + __count_trailing_zerol(hi); + } + return zeros; +} + +static int __must_round(const decimal* d, int digits) { + unsigned char const* i = d->sig.text + digits; + + if (*i > 5) { + return 1; + } + + if (*i < 5) { + return -1; + } + + { + unsigned char const* e = d->sig.text + d->sig.length; + + for (i++; i < e; i++) { + if (*i != 0) { + return 1; + } + } + } + + if (d->sig.text[digits - 1] & 1) { + return 1; + } + + return -1; +} + +static void __dorounddecup(decimal* d, int digits) { + unsigned char* b = d->sig.text; + unsigned char* i = b + digits - 1; + + while (1) { + if (*i < 9) { + *i += 1; + break; + } + if (i == b) { + *i = 1; + d->exp++; + break; + } + *i-- = 0; + } +} + +static void __rounddec(decimal* d, int digits) { + if (digits > 0 && digits < d->sig.length) { + int unkBool = __must_round(d, digits); + d->sig.length = digits; + + if (unkBool >= 0) { + __dorounddecup(d, digits); + } + } +} + +static void __ull2dec(decimal* result, unsigned long long val) { + result->sign = 0; + result->sig.length = 0; + + for (; val != 0; val /= 10) { + result->sig.text[result->sig.length++] = (unsigned char)(val % 10); + } + + { + unsigned char* i = result->sig.text; + unsigned char* j = result->sig.text + result->sig.length; + + for (; i < --j; ++i) { + unsigned char t = *i; + *i = *j; + *j = t; + } + } + + result->exp = result->sig.length - 1; +} + +static void __timesdec(decimal* result, const decimal* x, const decimal* y) { + unsigned long accumulator = 0; + unsigned char mantissa[SIGDIGLEN * 2]; + int i = x->sig.length + y->sig.length - 1; + unsigned char* pDigit; + unsigned char* ip = mantissa + i + 1; + unsigned char* ep = ip; + + result->sign = 0; + + for (; i > 0; i--) { + int k = y->sig.length - 1; + int j = i - k - 1; + int l; + int t; + const unsigned char* jp; + const unsigned char* kp; + + if (j < 0) { + j = 0; + k = i - 1; + } + + jp = x->sig.text + j; + kp = y->sig.text + k; + l = k + 1; + t = x->sig.length - j; + + if (l > t) + l = t; + + for (; l > 0; l--, jp++, kp--) { + accumulator += *jp * *kp; + } + + *--ip = (unsigned char)(accumulator % 10); + accumulator /= 10; + } + + result->exp = (short)(x->exp + y->exp); + + if (accumulator) { + *--ip = (unsigned char)(accumulator); + result->exp++; + } + + for (i = 0; i < SIGDIGLEN && ip < ep; i++, ip++) { + result->sig.text[i] = *ip; + } + result->sig.length = (unsigned char)(i); + + if (ip < ep && *ip >= 5) { + if (*ip == 5) { + unsigned char* jp = ip + 1; + for (; jp < ep; jp++) { + if (*jp != 0) + goto round; + } + if ((ip[-1] & 1) == 0) + return; + } + round: + __dorounddecup(result, result->sig.length); + } +} + +static void __str2dec(decimal* d, const char* s, short exp) { + int i; + + d->exp = exp; + d->sign = 0; + + for (i = 0; i < SIGDIGLEN && *s;) { + d->sig.text[i++] = *s++ - '0'; + } + d->sig.length = i; + + if (*s != 0) { + if (*s < 5) + return; + if (*s > 5) + goto round; + + { + const char* p = s + 1; + + for (; *p != 0; p++) { + if (*p != '0') + goto round; + } + + if ((d->sig.text[i - 1] & 1) == 0) + return; + } + round: + __dorounddecup(d, d->sig.length); + } +} + +static void __two_exp(decimal* result, long exp) { + switch (exp) { + case -64: + __str2dec(result, "542101086242752217003726400434970855712890625", -20); + return; + case -53: + __str2dec(result, "11102230246251565404236316680908203125", -16); + return; + case -32: + __str2dec(result, "23283064365386962890625", -10); + return; + case -16: + __str2dec(result, "152587890625", -5); + return; + case -8: + __str2dec(result, "390625", -3); + return; + case -7: + __str2dec(result, "78125", -3); + return; + case -6: + __str2dec(result, "15625", -2); + return; + case -5: + __str2dec(result, "3125", -2); + return; + case -4: + __str2dec(result, "625", -2); + return; + case -3: + __str2dec(result, "125", -1); + return; + case -2: + __str2dec(result, "25", -1); + return; + case -1: + __str2dec(result, "5", -1); + return; + case 0: + __str2dec(result, "1", 0); + return; + case 1: + __str2dec(result, "2", 0); + return; + case 2: + __str2dec(result, "4", 0); + return; + case 3: + __str2dec(result, "8", 0); + return; + case 4: + __str2dec(result, "16", 1); + return; + case 5: + __str2dec(result, "32", 1); + return; + case 6: + __str2dec(result, "64", 1); + return; + case 7: + __str2dec(result, "128", 2); + return; + case 8: + __str2dec(result, "256", 2); + return; + } + + { + decimal x2, temp; + + __two_exp(&x2, exp / 2); + __timesdec(result, &x2, &x2); + + if (exp & 1) { + temp = *result; + if (exp > 0) { + __str2dec(&x2, "2", 0); + } else { + __str2dec(&x2, "5", -1); + } + __timesdec(result, &temp, &x2); + } + } +} + +static int __equals_dec(const decimal* x, const decimal* y) { + if (x->sig.text[0] == 0) { + return y->sig.text[0] == 0; + } + + if (y->sig.text[0] == 0) { + return x->sig.text[0] == 0; + } + + if (x->exp == y->exp) { + int i; + int l = x->sig.length; + + if (l > y->sig.length) { + l = y->sig.length; + } + + for (i = 0; i < l; i++) { + if (x->sig.text[i] != y->sig.text[i]) { + return 0; + } + } + + if (l == x->sig.length) { + x = y; + } + + for (; i < x->sig.length; i++) { + if (x->sig.text[i] != 0) { + return 0; + } + } + + return 1; + } + return 0; +} + +static int __less_dec(const decimal* x, const decimal* y) { + if (x->sig.text[0] == 0) { + unsigned char leading_digit = y->sig.text[0]; + return ((unsigned long)(-leading_digit | leading_digit) >> 31); + } + + if (y->sig.text[0] == 0) { + return 0; + } + + if (x->exp == y->exp) { + int i; + int l = x->sig.length; + + if (l > y->sig.length) { + l = y->sig.length; + } + + for (i = 0; i < l; i++) { + if (x->sig.text[i] < y->sig.text[i]) { + return 1; + } else if (y->sig.text[i] < x->sig.text[i]) { + return 0; + } + } + + if (l == x->sig.length) { + for (; i < y->sig.length; i++) { + if (y->sig.text[i] != 0) { + return 1; + } + } + } + return 0; + } + + return x->exp < y->exp; +} + +static void __minus_dec(decimal* z, const decimal* x, const decimal* y) { + int zlen, dexp; + unsigned char *ib, *i, *ie; + unsigned char const *jb, *j, *jn; + + *z = *x; + + if (y->sig.text[0] == 0) + return; + + zlen = z->sig.length; + if (zlen < y->sig.length) + zlen = y->sig.length; + + dexp = z->exp - y->exp; + zlen += dexp; + + if (zlen > SIGDIGLEN) + zlen = SIGDIGLEN; + + while (z->sig.length < zlen) { + z->sig.text[z->sig.length++] = 0; + } + + ib = z->sig.text; + i = ib + zlen; + + if (y->sig.length + dexp < zlen) { + i = ib + (y->sig.length + dexp); + } + + jb = y->sig.text; + j = jb + (i - ib - dexp); + jn = j; + + while (i > ib && j > jb) { + i--; + j--; + if (*i < *j) { + unsigned char* k = i - 1; + while (*k == 0) + k--; + while (k != i) { + --*k; + *++k += 10; + } + } + *i -= *j; + } + + if (jn - jb < y->sig.length) { + int round_down = 0; + if (*jn < 5) + round_down = 1; + else if (*jn == 5) { + unsigned char const* ibPtr = y->sig.text + y->sig.length; + + for (j = jn + 1; j < ibPtr; j++) { + if (*j != 0) + goto done; + } + i = ib + (jn - jb) + dexp - 1; + if (*i & 1) + round_down = 1; + } + if (round_down) { + if (*i < 1) { + unsigned char* k = i - 1; + while (*k == 0) + k--; + while (k != i) { + --*k; + *++k += 10; + } + } + *i -= 1; + } + } +done: + for (i = ib; *i == 0; ++i) {} + + if (i > ib) { + unsigned char dl = (unsigned char)(i - ib); + z->exp -= dl; + ie = ib + z->sig.length; + for (; i < ie; ++i, ++ib) + *ib = *i; + z->sig.length -= dl; + } + + ib = z->sig.text; + for (i = ib + z->sig.length; i > ib;) { + i--; + if (*i != 0) + break; + } + z->sig.length = (unsigned char)(i - ib + 1); +} + +static void __num2dec_internal(decimal* d, double x) { + signed char sign = (signed char)(__signbitd(x) != 0); + + if (x == 0) { + d->sign = sign; + d->exp = 0; + d->sig.length = 1; + d->sig.text[0] = 0; + return; + } + + if (!isfinite(x)) { + d->sign = sign; + d->exp = 0; + d->sig.length = 1; + d->sig.text[0] = fpclassify(x) == 1 ? 'N' : 'I'; + return; + } + + if (sign != 0) { + x = -x; + } + + { + int exp; + double frac = frexp(x, &exp); + int num_bits_extract = LDBL_MANT_DIG - __count_trailing_zero(frac); + decimal int_d, pow2_d; + + __two_exp(&pow2_d, exp - num_bits_extract); + __ull2dec(&int_d, ldexp(frac, num_bits_extract)); + __timesdec(d, &int_d, &pow2_d); + d->sign = sign; + } +} + +void __num2dec(const decform* form, double x, decimal* d) { + short digits = form->digits; + int i; + __num2dec_internal(d, x); + + if (d->sig.text[0] > 9) { + return; + } + + if (digits > SIGDIGLEN) { + digits = SIGDIGLEN; + } + + __rounddec(d, digits); + + while (d->sig.length < digits) { + d->sig.text[d->sig.length++] = 0; + } + + d->exp -= d->sig.length - 1; + + for (i = 0; i < d->sig.length; i++) { + d->sig.text[i] += '0'; + } +} + +double __dec2num(const decimal* d) { + if (d->sig.length <= 0) { + return copysign(0.0, d->sign == 0 ? 1.0 : -1.0); + } + + switch (d->sig.text[0]) { + case '0': + return copysign(0.0, d->sign == 0 ? 1.0 : -1.0); + case 'I': + return copysign((double)INFINITY, d->sign == 0 ? 1.0 : -1.0); + case 'N': { + double result; + d_int* ll = (d_int*)&result; + + *ll = 0x7FF0000000000000; + if (d->sign) + *ll |= 0x8000000000000000; + *ll |= 0x8000000000000; + + return result; + } + } + + { + static double pow_10[8] = {1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8}; + + decimal dec = *d; + unsigned char* i = dec.sig.text; + unsigned char* e = i + dec.sig.length; + double first_guess; + int exponent; + + for (; i < e; ++i) + *i -= '0'; + dec.exp += dec.sig.length - 1; + exponent = dec.exp; + + { + decimal max; + + __str2dec(&max, "179769313486231580793728714053034151", 308); + if (__less_dec(&max, &dec)) { + return copysign((double)INFINITY, d->sign == 0 ? 1.0 : -1.0); + } + } + + i = dec.sig.text; + first_guess = *i++; + + while (i < e) { + unsigned long ival = 0; + int j; + double temp1, temp2; + int ndig = (int)(e - i) % 8; + + if (ndig == 0) + ndig = 8; + + for (j = 0; j < ndig; ++j, ++i) { + ival = ival * 10 + *i; + } + + temp1 = first_guess * pow_10[ndig - 1]; + temp2 = temp1 + ival; + + if (ival != 0 && temp1 == temp2) + break; + + first_guess = temp2; + exponent -= ndig; + } + + if (exponent < 0) { + first_guess /= pow(5.0, -exponent); + } else { + first_guess *= pow(5.0, exponent); + } + + first_guess = ldexp(first_guess, exponent); + + if (fpclassify(first_guess) == 2) { + first_guess = LDBL_MAX; + } + + { + decimal feedback1, feedback2, difflow, diffhigh; + double next_guess; + d_int* ull = (d_int*)&next_guess; + int guessed_low = 0; + + __num2dec_internal(&feedback1, first_guess); + + if (__equals_dec(&feedback1, &dec)) { + goto done; + } + if (__less_dec(&feedback1, &dec)) { + guessed_low = 1; + } + + next_guess = first_guess; + + while (1) { + if (guessed_low) { + ++*ull; + if (fpclassify(next_guess) == 2) { + goto done; + } + } else { + --*ull; + } + + __num2dec_internal(&feedback2, next_guess); + if (guessed_low && !__less_dec(&feedback2, &dec)) { + break; + } else if (!guessed_low && !__less_dec(&dec, &feedback2)) { + difflow = feedback1; + feedback1 = feedback2; + feedback2 = difflow; + { + double temp = first_guess; + first_guess = next_guess; + next_guess = temp; + } + break; + } + feedback1 = feedback2; + first_guess = next_guess; + } + + __minus_dec(&difflow, &dec, &feedback1); + __minus_dec(&diffhigh, &feedback2, &dec); + + if (__equals_dec(&difflow, &diffhigh)) { + if (*(unsigned long long*)&first_guess & 1) { + first_guess = next_guess; + } + } else if (!__less_dec(&difflow, &diffhigh)) { + first_guess = next_guess; + } + } + done: + if (dec.sign) { + first_guess = -first_guess; + } + return first_guess; + } +} + -- 2.49.1 From eaee2295cc48b49eafee6073fd4301f56de02da7 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:04:27 -0500 Subject: [PATCH 4/7] vi3in1 15/18, kbd_lib 12/21, iplMemoryCardManager (worker feba9540) (#340) --- README.md | 4 +- libs/RVL_SDK/src/kbd/kbd_lib.c | 947 ++++++++++++++++++ libs/RVL_SDK/src/vi/vi3in1.c | 719 +++++++++++++ src/scene/memoryCard/iplMemoryCardManager.cpp | 457 +++++++++ .../iplMemoryCardManager.attempts.md | 107 ++ tools/decomp-assist/kbd_lib.attempts.md | 66 ++ tools/decomp-assist/vi3in1.attempts.md | 21 + 7 files changed, 2319 insertions(+), 2 deletions(-) create mode 100644 libs/RVL_SDK/src/kbd/kbd_lib.c create mode 100644 libs/RVL_SDK/src/vi/vi3in1.c create mode 100644 src/scene/memoryCard/iplMemoryCardManager.cpp create mode 100644 tools/decomp-assist/iplMemoryCardManager.attempts.md create mode 100644 tools/decomp-assist/kbd_lib.attempts.md create mode 100644 tools/decomp-assist/vi3in1.attempts.md diff --git a/README.md b/README.md index 5daee4e1..585b5e32 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 90.99% | 80.50% | 56.95% | 88.40% | +| 91.56% | 80.70% | 56.95% | 88.70% | -units 758/1027 complete, functions 11561/12563 matched. +units 758/1027 complete, functions 11604/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/libs/RVL_SDK/src/kbd/kbd_lib.c b/libs/RVL_SDK/src/kbd/kbd_lib.c new file mode 100644 index 00000000..5e43d176 --- /dev/null +++ b/libs/RVL_SDK/src/kbd/kbd_lib.c @@ -0,0 +1,947 @@ +#include +#include +#include +#include +#include + +typedef union { + u32 value; + struct { + u32 locks : 26; + u32 physical : 6; + } bits; +} KBDModifierState; + +typedef struct { + u8 codeCount; + u8 flags; + u16* keyMap; + u16* modifierMap; + u8 lockIndex; + u8 shiftIndex; + u8 altIndex; + u8 maxCode; + u8 keypadMap[8]; + u8 keypadCount; +} KBDKeyMap; + +typedef union { + KBDKeyMap maps[36]; + u8 storage[0x400]; +} KBDKeyMapTable; + +typedef struct { + u8 channel; + u8 code; + u32 state; + u32 modifiers; + u16 translated; +} KBDKeyEventData; + +typedef struct { + u8 channel; + s32 country; + u32 flags; + void* device; + u8 modifiers; + u8 reportReserved; + u8 keys[6]; + KBDKeyEventData events[32]; + u8 writeIndex; + u8 readIndex; + u32 lockProcessing; + u32 modState; + u8 lockCount[6]; + u16 repeatDelay; + u16 repeatInterval; + u8 repeatKey; + OSAlarm alarm; + u32 lockState; +} KBDChannel; + +typedef struct { + u32 callbackAddress; + void* callbackArg; +} KBDLEDCallbackData; + +const char* __KBDVersion = + "<< RVL_SDK - KBD \trelease build: Apr 20 2010 11:21:43 (0x4199_60831) >>"; + +static BOOL kbdInitialized; +static USBKBDAttachCallback kbdDevAttachCallback; +static USBKBDDetachCallback kbdDevDetachCallback; +static void (*kbdKeyCallback)(KBDKeyEventData* event); + +KBDKeyMapTable kbdKeyMaps; +typedef struct { + u32 device; + u8 leds; + u32 transfer[4]; + USBKBDCmdLEDCallback callback; + void* callbackArg; +} KBDLEDCommand; + +KBDLEDCommand kbdCmdBuf[12]; +KBDChannel kbdData[4]; +KBDLEDCallbackData kbdLCBuf[12]; + +u16 kbdKeyMapUS_International[500] = { + 0x00FF, 0x0061, 0x0041, 0x00E1, 0x00C1, 0x003F, 0x0062, 0x0042, 0x0000, 0x0000, + 0x003F, 0x0063, 0x0043, 0x00A9, 0x00A2, 0x00FF, 0x0064, 0x0044, 0x00F0, 0x00D0, + 0x00FF, 0x0065, 0x0045, 0x00E9, 0x00C9, 0x003F, 0x0066, 0x0046, 0x0000, 0x0000, + 0x003F, 0x0067, 0x0047, 0x0000, 0x0000, 0x003F, 0x0068, 0x0048, 0x0000, 0x0000, + 0x00FF, 0x0069, 0x0049, 0x00ED, 0x00CD, 0x003F, 0x006A, 0x004A, 0x0000, 0x0000, + 0x003F, 0x006B, 0x004B, 0x0000, 0x0000, 0x00FF, 0x006C, 0x004C, 0x00F8, 0x00D8, + 0x003F, 0x006D, 0x004D, 0x00B5, 0x0000, 0x00FF, 0x006E, 0x004E, 0x00F1, 0x00D1, + 0x00FF, 0x006F, 0x004F, 0x00F3, 0x00D3, 0x00FF, 0x0070, 0x0050, 0x00F6, 0x00D6, + 0x00FF, 0x0071, 0x0051, 0x00E4, 0x00C4, 0x003F, 0x0072, 0x0052, 0x00AE, 0x0000, + 0x003F, 0x0073, 0x0053, 0x00DF, 0x00A7, 0x00FF, 0x0074, 0x0054, 0x00FE, 0x00DE, + 0x00FF, 0x0075, 0x0055, 0x00FA, 0x00DA, 0x003F, 0x0076, 0x0056, 0x0000, 0x0000, + 0x00FF, 0x0077, 0x0057, 0x00E5, 0x00C5, 0x003F, 0x0078, 0x0058, 0x0000, 0x0000, + 0x00FF, 0x0079, 0x0059, 0x00FC, 0x00DC, 0x00FF, 0x007A, 0x005A, 0x00E6, 0x00C6, + 0x0000, 0x0031, 0x0021, 0x00A1, 0x00B9, 0x0000, 0x0032, 0x0040, 0x00B2, 0x0000, + 0x0000, 0x0033, 0x0023, 0x00B3, 0x0000, 0x0000, 0x0034, 0x0024, 0x00A4, 0x00A3, + 0x0000, 0x0035, 0x0025, 0x20AC, 0x0000, 0x0000, 0x0036, 0x0302, 0x00BC, 0x0000, + 0x0000, 0x0037, 0x0026, 0x00BD, 0x0000, 0x0000, 0x0038, 0x002A, 0x00BE, 0x0000, + 0x0000, 0x0039, 0x0028, 0x2018, 0x0000, 0x0000, 0x0030, 0x0029, 0x2019, 0x0000, + 0x0000, 0xF1CD, 0xF1CD, 0xF1CD, 0xF1CD, 0x0000, 0xF1DB, 0xF1DB, 0xF1DB, 0xF1DB, + 0x0000, 0xF1C8, 0xF1C8, 0xF1C8, 0xF1C8, 0x0000, 0xF1C9, 0xF1C9, 0xF1C9, 0xF1C9, + 0x0000, 0x0020, 0x0020, 0x0020, 0x0020, 0x0000, 0x002D, 0x005F, 0x00A5, 0x0000, + 0x0000, 0x003D, 0x002B, 0x00D7, 0x00F7, 0x0000, 0x005B, 0x007B, 0x00AB, 0x0000, + 0x0000, 0x005D, 0x007D, 0x00BB, 0x0000, 0x0000, 0x005C, 0x007C, 0x00AC, 0x00A6, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x003B, 0x003A, 0x00B6, 0x00B0, + 0x0000, 0x030D, 0x030E, 0x00B4, 0x00A8, 0x0000, 0x0300, 0x0303, 0x0000, 0x0000, + 0x00C0, 0x002C, 0x003C, 0x00E7, 0x00C7, 0x0000, 0x002E, 0x003E, 0x0000, 0x0000, + 0x0000, 0x002F, 0x003F, 0x00BF, 0x0000, 0xC000, 0xF008, 0xF008, 0xF008, 0xF008, + 0x0000, 0xF061, 0xF061, 0xF061, 0xF061, 0x0000, 0xF062, 0xF062, 0xF062, 0xF062, + 0x0000, 0xF063, 0xF063, 0xF063, 0xF063, 0x0000, 0xF064, 0xF064, 0xF064, 0xF064, + 0x0000, 0xF065, 0xF065, 0xF065, 0xF065, 0x0000, 0xF066, 0xF066, 0xF066, 0xF066, + 0x0000, 0xF067, 0xF067, 0xF067, 0xF067, 0x0000, 0xF068, 0xF068, 0xF068, 0xF068, + 0x0000, 0xF069, 0xF069, 0xF069, 0xF069, 0x0000, 0xF06A, 0xF06A, 0xF06A, 0xF06A, + 0x0000, 0xF06B, 0xF06B, 0xF06B, 0xF06B, 0x0000, 0xF06C, 0xF06C, 0xF06C, 0xF06C, + 0xC000, 0xF020, 0xF020, 0xF020, 0xF020, 0xC000, 0xF021, 0xF021, 0xF021, 0xF021, + 0xC000, 0xF022, 0xF022, 0xF022, 0xF022, 0x0000, 0xF1B0, 0xF1B0, 0xF1B0, 0xF1B0, + 0x0000, 0xF1B7, 0xF1B7, 0xF1B7, 0xF1B7, 0x0000, 0xF1B9, 0xF1B9, 0xF1B9, 0xF1B9, + 0x0000, 0xF1AE, 0xF1AE, 0xF1AE, 0xF1AE, 0x0000, 0xF1B1, 0xF1B1, 0xF1B1, 0xF1B1, + 0x0000, 0xF1B3, 0xF1B3, 0xF1B3, 0xF1B3, 0x0000, 0xF1B6, 0xF1B6, 0xF1B6, 0xF1B6, + 0x0000, 0xF1B4, 0xF1B4, 0xF1B4, 0xF1B4, 0x0000, 0xF1B2, 0xF1B2, 0xF1B2, 0xF1B2, + 0x0000, 0xF1B8, 0xF1B8, 0xF1B8, 0xF1B8, 0xC000, 0xF007, 0xF007, 0xF007, 0xF007, + 0x0000, 0xF12F, 0xF12F, 0xF12F, 0xF12F, 0x0000, 0xF12A, 0xF12A, 0xF12A, 0xF12A, + 0x0000, 0xF12D, 0xF12D, 0xF12D, 0xF12D, 0x0000, 0xF12B, 0xF12B, 0xF12B, 0xF12B, + 0x0000, 0xF10D, 0xF10D, 0xF10D, 0xF10D, 0x80FF, 0xF171, 0xF131, 0x0000, 0x0000, + 0x80FF, 0xF172, 0xF132, 0x0000, 0x0000, 0x80FF, 0xF173, 0xF133, 0x0000, 0x0000, + 0x80FF, 0xF174, 0xF134, 0x0000, 0x0000, 0x80FF, 0xF175, 0xF135, 0x0000, 0x0000, + 0x80FF, 0xF176, 0xF136, 0x0000, 0x0000, 0x80FF, 0xF177, 0xF137, 0x0000, 0x0000, + 0x80FF, 0xF178, 0xF138, 0x0000, 0x0000, 0x80FF, 0xF179, 0xF139, 0x0000, 0x0000, + 0x80FF, 0xF170, 0xF130, 0x0000, 0x0000, 0x80FF, 0xF16E, 0xF12E, 0x0000, 0x0000, + 0x0000, 0x005C, 0x007C, 0x0000, 0x0000, 0xC000, 0xF02F, 0xF02F, 0xF02F, 0xF02F, + 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xF13D, 0xF13D, 0xF13D, 0xF13D +}; + +u16 kbdModifierMapUS_International[40] = { + 0xC000, 0xF000, 0xF000, 0xF000, 0xF000, 0xC000, 0xF001, 0xF001, 0xF001, 0xF001, + 0xC000, 0xF002, 0xF002, 0xF002, 0xF002, 0xC000, 0xF003, 0xF003, 0xF003, 0xF003, + 0xC000, 0xF000, 0xF000, 0xF000, 0xF000, 0xC000, 0xF001, 0xF001, 0xF001, 0xF001, + 0xC000, 0xF005, 0xF005, 0xF005, 0xF005, 0xC000, 0xF003, 0xF003, 0xF003, 0xF003 +}; + +static u16 noRepeatKeys[7] = {0xf006, 0xf008, 0xf007, 0xf021, 0xf020, 0xf022, 0xf02f}; + +USBKBDErr KBDSetModState(u32 channel, u32 value); +USBKBDErr KBDResetChannel(u32 channel); +u16 KBDTranslateHidCode(u32 keyCode, u32 modifiers, s32 country); + +static void kbdAttachHandler(void* device); +static void kbdDetachHandler(void* device); +static void kbdEventHandler(void* device, char* report); +static void kbdRepeatHandler(OSAlarm* alarm, OSContext* context); +static void kbdProcKey(u32 key, u32 state, u32 channel); +static void kbdProcMod(u32 key, u32 state, u32 channel); +static void kbdSendKey(KBDKeyEventData* event); +static void kbd_led_handler(BOOL success, void* callbackArg); + +static void kbdAttachHandler(void* device) { + u32 channel; + channel = 0; + + for (channel = 0; channel < 4; channel++) { + if (kbdData[(u8)channel].device == NULL) { + break; + } + } + + if (channel != 4) { + u8 event[1]; + + kbdData[channel].device = device; + kbdData[channel].flags &= ~1; + KBDResetChannel(channel); + VIResetDimmingCount(); + + if (kbdDevAttachCallback != NULL) { + event[0] = (u8)channel; + kbdDevAttachCallback(event); + } + } +} + +static void kbdDetachHandler(void* device) { + u32 channel; + channel = 0; + + for (channel = 0; channel < 4; channel++) { + if (device == kbdData[(u8)channel].device) { + break; + } + } + + if (channel != 4) { + u8 event[1]; + + kbdData[channel].device = NULL; + kbdData[channel].flags |= 1; + + if (kbdDevDetachCallback != NULL) { + event[0] = (u8)channel; + kbdDevDetachCallback(event); + } + + KBDResetChannel(channel); + } +} + +static void kbdEventHandler(void* device, char* report) { + u32 channel; + channel = 0; + + for (channel = 0; channel < 4; channel++) { + if (device == kbdData[(u8)channel].device) { + break; + } + } + + if (channel != 4) { + KBDChannel* data; + u8* bytes; + u8 status; + data = &kbdData[channel]; + bytes = (u8*)report; + status = bytes[2]; + + if ((u8)(bytes[2] + 0xff) <= 2) { + OSCancelAlarm(&data->alarm); + + if (bytes[2] == 1) { + data->flags |= 2; + } else { + data->flags |= 4; + } + } else { + s32 i; + u32 mask; + data->flags = 0; + VIResetDimmingCount(); + + + for (i = 0, mask = 1; i < 8; i++, mask <<= 1) { + if ((data->modifiers & (u8)mask) != 0) { + if ((bytes[0] & (u8)mask) == 0) { + kbdProcKey((u8)(i + 0xe0), 0, channel); + } + } else if ((bytes[0] & (u8)mask) != 0) { + kbdProcKey((u8)(i + 0xe0), 1, channel); + } + } + + + for (i = 0; i < 6; i++) { + u8 key; + s32 j; + key = data->keys[(s8)i]; + j = 0; + + if (key != 0) { + for (j = 0; j < 6; j++) { + if (key == bytes[j + 2]) { + break; + } + } + + if (j == 6) { + kbdProcKey(key, 0, channel); + data->keys[(s8)i] = 0; + } + } + } + + + for (i = 0; i < 6; i++) { + u8 key; + s32 j; + key = bytes[(s8)i + 2]; + j = 0; + + if (key != 0) { + for (j = 0; j < 6; j++) { + if (key == data->keys[j]) { + break; + } + } + + if (j == 6) { + kbdProcKey(key, 1, channel); + } + } + } + + data->modifiers = bytes[0]; + data->keys[0] = bytes[2]; + data->keys[1] = bytes[3]; + data->keys[2] = bytes[4]; + data->keys[3] = bytes[5]; + data->keys[4] = bytes[6]; + data->keys[5] = bytes[7]; + } + } +} + +static void kbdRepeatHandler(OSAlarm* alarm, OSContext* context) { + KBDChannel* data; + data = (KBDChannel*)OSGetAlarmUserData(alarm); + + kbdProcKey(data->repeatKey, 3, data->channel); +} + +static inline USBKBDErr kbdGetModState(u32 channel, u32* modifiers) { + if (!kbdInitialized) { + return 2; + } + if (channel >= 4 || modifiers == NULL) { + return 4; + } + *modifiers = kbdData[channel].modState; + return 0; +} + +static void kbdProcKey(u32 key, u32 pressed, u32 channel) { + KBDChannel* data; + KBDKeyMap* map; + s32 keyCount; + s32 i; + u32 j; + u16 translated; + OSTime timeout; + KBDKeyEventData event; + data = &kbdData[channel]; + + event.channel = channel; + event.state = pressed; + event.modifiers = 0; + kbdGetModState(channel, &event.modifiers); + map = &kbdKeyMaps.maps[data->country]; + keyCount = map->keypadCount; + for (i = 0; i < keyCount; i++) { + if (key == map->keypadMap[i * 2]) { + key = map->keypadMap[i * 2 + 1]; + break; + } + } + event.code = key; + translated = KBDTranslateHidCode(key, event.modifiers, + data->country); + event.translated = translated; + if ((translated == 0xF000) || (translated == 0xF001) || + (translated == 0xF002) || (translated == 0xF003) || + (translated == 0xF004) || (translated == 0xF005) || + (translated == 0xF006) || (translated == 0xF007) || + (translated == 0xF008) || (translated == 0xF021)) { + kbdProcMod(translated, pressed, channel); + if ((translated != 0xF006) && (translated != 0xF007) && + (translated != 0xF008) && (translated != 0xF021)) { + kbdSendKey(&event); + return; + } + } + if ((pressed & 1) == 0) { + if (key == data->repeatKey) { + OSCancelAlarm(&data->alarm); + } + kbdSendKey(&event); + return; + } + OSCancelAlarm(&data->alarm); + for (j = 0; j < 7; j++) { + if (translated == noRepeatKeys[j]) { + break; + } + } + if (j == 7) { + data->repeatKey = key; + if (data->repeatDelay != 0) { + if ((pressed & 2) != 0) { + timeout = data->repeatInterval * (OS_TIMER_CLOCK / 1000); + } else { + timeout = data->repeatDelay * (OS_TIMER_CLOCK / 1000); + } + OSSetAlarm(&data->alarm, timeout, kbdRepeatHandler); + } + } + event.translated = translated; + kbdSendKey(&event); +} + +static void kbdProcMod(u32 key, u32 pressed, u32 channel) { + KBDChannel* data; + s8 delta; + u8 flags; + u32 state; + u32 finalState; + s8 value; + data = &kbdData[channel]; + delta = (pressed & 1) != 0 ? 1 : -1; + flags = kbdKeyMaps.maps[data->country].flags; + state = 0; + + kbdGetModState(channel, &state); + switch (key) { + case 0xF001: + if (data->lockState != 0) { + if ((pressed & 1) != 0) { + state ^= 2; + } + } else { + value = data->lockCount[1] + delta; + data->lockCount[1] = value; + state = (state & 0xFFFFFFFD) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1E & 2); + } + break; + case 0xF005: + if (data->lockState != 0) { + if ((pressed & 1) != 0) { + state ^= 0x20; + } + } else { + value = data->lockCount[4] + delta; + data->lockCount[4] = value; + state = (state & 0xFFFFFFDF) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1A & 0x20); + } + break; + case 0xF000: + if (data->lockState != 0) { + if ((pressed & 1) != 0) { + state ^= 1; + } + } else { + value = data->lockCount[0] + delta; + data->lockCount[0] = value; + state = (state & 0xFFFFFFFE) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1F); + } + break; + case 0xF008: + if (((pressed & 1) != 0) && (data->lockProcessing != 0)) { + state ^= 0x200; + } + break; + case 0xF007: + if (((pressed & 1) != 0) && (data->lockProcessing != 0)) { + state ^= 0x100; + } + break; + case 0xF006: + if (((pressed & 1) != 0) && (data->lockProcessing != 0)) { + u32 oldState; + u32 lockState; + oldState = state; + lockState = oldState & 0xC0; + switch (lockState) { + case 0: + if ((flags & 1) == 1) { + state = oldState | 0x40; + } + break; + case 0x40: + { + state = oldState & 0xFFFFFFBF; + if ((flags & 4) == 4) { + state = oldState & 0xFFFFFFBF | 0x80; + } + } + break; + case 0x80: + state = oldState & 0xFFFFFF7F; + break; + case 0xC0: + state = oldState & 0xFFFFFF3F; + break; + } + } + break; + case 0xF002: + if (data->lockState != 0) { + if ((pressed & 1) != 0) { + state ^= 4; + } + } else { + value = data->lockCount[2] + delta; + data->lockCount[2] = value; + state = (state & 0xFFFFFFFB) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1D & 4); + } + break; + case 0xF003: + if (data->lockState != 0) { + if ((pressed & 1) != 0) { + state ^= 8; + } + } else { + value = data->lockCount[3] + delta; + data->lockCount[3] = value; + state = (state & 0xFFFFFFF7) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1C & 8); + } + break; + case 0xF004: + if (data->lockState != 0) { + if ((pressed & 1) != 0) { + state ^= 0x10; + } + } else { + value = data->lockCount[5] + delta; + data->lockCount[5] = value; + state = (state & 0xFFFFFFEF) | ((-(u32)(u8)value | (u32)(u8)value) >> 0x1B & 0x10); + } + break; + case 0xF021: + if (((pressed & 1) != 0) && (data->lockProcessing != 0)) { + state ^= 0x400; + } + break; + } + finalState = state | 0x1000; + KBDSetModState(channel, finalState); +} + +static void kbdSendKey(KBDKeyEventData* event) { + KBDChannel* data; + u8 head; + u8 tail; + u8 next; + if (kbdKeyCallback != NULL) { + kbdKeyCallback(event); + } + data = &kbdData[event->channel]; + tail = data->readIndex; + head = data->writeIndex; + if (head != tail) { + next = (head + 1) % 0x20; + if (next == tail) { + data->events[head].channel = event->channel; + data->events[data->writeIndex].code = 0xff; + data->events[data->writeIndex].state = 0; + data->events[data->writeIndex].modifiers = 0; + data->events[data->writeIndex].translated = 0; + } else { + data->events[head] = *event; + if (data->readIndex == 0x20) { + data->readIndex = data->writeIndex; + } + } + data->writeIndex = next; + } +} + +static void kbd_led_handler(BOOL success, void* callbackArg) { + u32 index; + u32 result; + u32 callbackAddress; + index = (u32)callbackArg; + callbackAddress = kbdLCBuf[index].callbackAddress; + + kbdCmdBuf[index].device = 0; + if (callbackAddress == 0) { + return; + } + switch (success) { + case TRUE: + result = 0; + break; + default: + result = 7; + break; + } + ((USBKBDCmdLEDCallback)kbdLCBuf[index].callbackAddress)(result, kbdLCBuf[index].callbackArg); +} + +USBKBDErr KBDSetLedsAsync(u32 channel, u32 leds, USBKBDCmdLEDCallback callback, void* callbackArg) { + u32 index; + BOOL interrupts; + USBKBDErr result; + if (!kbdInitialized) { + return 2; + } + if (channel >= 4) { + return 4; + } + if ((s32)kbdData[channel].flags == 1 || (s32)kbdData[channel].flags == 4) { + return 5; + } + leds &= 0xff; + interrupts = OSDisableInterrupts(); + for (index = 0; index < 12; index++) { + if (kbdCmdBuf[index].device == 0) { + kbdCmdBuf[index].device = (u32)kbdData[channel].device; + break; + } + } + OSRestoreInterrupts(interrupts); + if (index == 12) { + return 7; + } + kbdLCBuf[index].callbackAddress = (u32)callback; + kbdLCBuf[index].callbackArg = callbackArg; + result = USBKBDSetLEDAsync((u32)kbdData[channel].device, leds, + (USBKBDCmdLEDAsync*)&kbdCmdBuf[index], + kbd_led_handler, (void*)index); + if (result != 0) { + return 7; + } + return 0; +} + +USBKBDErr KBDSetLeds(u32 channel, u32 leds) { + u32 index; + BOOL interrupts; + USBKBDErr result; + if (!kbdInitialized) { + return 2; + } + if (channel >= 4) { + return 4; + } + if ((s32)kbdData[channel].flags == 1 || (s32)kbdData[channel].flags == 4) { + return 5; + } + leds &= 0xff; + interrupts = OSDisableInterrupts(); + for (index = 0; index < 12; index++) { + if (kbdCmdBuf[index].device == 0) { + kbdCmdBuf[index].device = (u32)kbdData[channel].device; + break; + } + } + OSRestoreInterrupts(interrupts); + if (index == 12) { + return 7; + } + result = USBKBDSetLED((u32)kbdData[channel].device, leds, + (USBKBDCmdLED*)&kbdCmdBuf[index]); + kbdCmdBuf[index].device = 0; + if (result != 0) { + return 7; + } + return 0; +} + +void kbdInitMap(u32 country, u8 codeCount, u8 flags, u16* keyMap, u16* modifierMap, + u8 lockIndex, u8 shiftIndex, u8 altIndex, u8 maxCode, s32 keypadType) { + KBDKeyMap* map; + map = &kbdKeyMaps.maps[country]; + + map->codeCount = codeCount; + map->flags = flags; + map->keyMap = keyMap; + map->modifierMap = modifierMap; + map->lockIndex = lockIndex; + map->shiftIndex = shiftIndex; + map->altIndex = altIndex; + map->maxCode = maxCode; + + switch (keypadType) { + case 0: + map->keypadMap[0] = 0x32; + map->keypadMap[1] = 0x31; + map->keypadCount = 1; + break; + case 1: + map->keypadMap[0] = 0x31; + map->keypadMap[1] = 0x32; + map->keypadMap[2] = 0x94; + map->keypadMap[3] = 0x35; + map->keypadCount = 2; + break; + case 2: + map->keypadMap[0] = 0x31; + map->keypadMap[1] = 0x32; + map->keypadCount = 1; + break; + } +} + +void kbdInitMapIntl(void) { + kbdInitMap(0, 5, 0x30, kbdKeyMapUS_International, + kbdModifierMapUS_International, 0, 0, 3, 100, 0); +} + +USBKBDErr KBDInit(void) { + USBKBDErr result; + u32 i; + + if (kbdInitialized) { + return 3; + } + OSRegisterVersion(__KBDVersion); + kbdInitialized = TRUE; + + + for (i = 0; i < 4; i++) { + KBDChannel* data; + data = &kbdData[(u8)i]; + + data->channel = (u8)i; + data->country = 0x21; + data->flags = 1; + data->device = NULL; + data->lockProcessing = 1; + data->repeatDelay = 500; + data->repeatInterval = 0x21; + data->lockState = 0; + + OSCreateAlarm(&data->alarm); + OSSetAlarmUserData(&data->alarm, data); + KBDResetChannel((u8)i); + } + + if (USBKBDInitialize(kbdAttachHandler, kbdDetachHandler) != 0) { + result = 1; + } else { + result = USBKBDRegisterEventCallback(kbdEventHandler); + result = (USBKBDErr)((-(u32)result | (u32)result) >> 31); + } + + + return result; +} + +USBKBDAttachCallback KBDSetAttachCallback(USBKBDAttachCallback callback) { + USBKBDAttachCallback previous = kbdDevAttachCallback; + + kbdDevAttachCallback = callback; + return previous; +} + +USBKBDDetachCallback KBDSetDetachCallback(USBKBDDetachCallback callback) { + USBKBDDetachCallback previous = kbdDevDetachCallback; + + kbdDevDetachCallback = callback; + return previous; +} + +void (*KBDSetKeyCallback(void (*callback)(KBDKeyEventData* event)))(KBDKeyEventData* event) { + void (*previous)(KBDKeyEventData* event) = kbdKeyCallback; + + kbdKeyCallback = callback; + return previous; +} + +USBKBDErr KBDResetChannel(u32 channel) { + if (!kbdInitialized) { + return 2; + } + + if (channel >= 4) { + return 4; + } + { + KBDChannel* data; + data = &kbdData[channel]; + + data->modifiers = 0; + data->keys[0] = 0; + data->keys[1] = 0; + data->keys[2] = 0; + data->keys[3] = 0; + data->keys[4] = 0; + data->keys[5] = 0; + data->readIndex = 0x20; + KBDSetModState(channel, 0x1000); + data->lockCount[0] = 0; + data->lockCount[1] = 0; + data->lockCount[2] = 0; + data->lockCount[3] = 0; + data->lockCount[4] = 0; + data->lockCount[5] = 0; + data->repeatKey = 0; + OSCancelAlarm(&data->alarm); + return 0; + } +} + +USBKBDErr KBDSetCountry(u32 channel, s32 country) { + if (!kbdInitialized) { + return 2; + } + if (channel >= 4) { + return 4; + } + if (country > 0x23) { + return 4; + } + if (kbdKeyMaps.maps[country].codeCount == 0) { + return 4; + } + kbdData[channel].country = country; + KBDResetChannel(channel); + return 0; +} + +USBKBDErr KBDSetLockProcessing(u32 channel, u32 value) { + if (!kbdInitialized) { + return 2; + } + + if (channel >= 4) { + return 4; + } + + kbdData[channel].lockProcessing = value; + return 0; +} + +USBKBDErr KBDSetModState(u32 channel, u32 value) { + if (!kbdInitialized) { + return 2; + } + if (channel >= 4) { + return 4; + } + if ((value & 0x1000) != 0) { + kbdData[channel].modState = value & ~0x1000; + } else { + BOOL interrupts; + KBDModifierState* state; + KBDModifierState oldState; + KBDModifierState newState; + interrupts = OSDisableInterrupts(); + state = (KBDModifierState*)&kbdData[channel].modState; + newState.value = value & 0xfc0; + oldState = *state; + newState.bits.physical = oldState.bits.physical; + *state = newState; + OSRestoreInterrupts(interrupts); + } + return 0; +} + +u16 KBDTranslateHidCode(u32 keyCode, u32 modifiers, s32 country) { + KBDKeyMap* map; + u16* table; + u32 keyIndex; + u16 entry; + u32 mask; + u32 offset; + s32 group; + u32 shiftFlag; + u32 shift; + + if (kbdInitialized == FALSE) { + return 0xFFFF; + } + if (country >= 0x24) { + return 0xFFFF; + } + + map = &kbdKeyMaps.maps[country]; + + if (map->codeCount == 0) { + return 0; + } + + if (keyCode < 4) { + return 0xFFFF; + } + + + if ((s32)keyCode < (s32)map->maxCode + 4) { + keyIndex = (u8)(keyCode - 4); + table = map->keyMap; + } else { + if (keyCode >= 0xE0 && keyCode <= 0xE7) { + keyIndex = (u8)(keyCode - 0xe0); + table = map->modifierMap; + } else { + return 0; + } + } + + keyIndex = (keyIndex & 0xFF) * map->codeCount; + entry = table[keyIndex]; + mask = entry & 0xC000; + + if (mask == 0xC000) { + group = 1; + offset = 0; + } else { + if ((modifiers & 0x20) == 0 && (modifiers & 5) != 5) { + if ((modifiers & 0x40) == 0) { + if ((modifiers & 0x80) == 0) { + group = 1; + shiftFlag = 1; + } else { + group = map->shiftIndex; + shiftFlag = 0x10; + } + } else { + group = map->lockIndex; + shiftFlag = 4; + } + } else { + group = map->altIndex; + shiftFlag = 0x40; + } + + if ((modifiers & 0x800) == 0 && (modifiers & 0x1D) != 0) { + offset = 0; + } else { + shift = (modifiers >> 1) & 1; + offset = (shiftFlag << shift) & 0xFFFF; + + if (mask == 0 && (offset & entry) != 0) { + offset = shift ^ ((modifiers >> 9) & 1); + } else if (mask == 0x8000 && (offset & entry) != 0) { + offset = 0; + if ((modifiers & 0x100) != 0 && shift == 0) { + offset = 1; + } + } else { + offset = shift; + if (mask == 0x4000 && group == 1 && (modifiers & 0x200) != 0) { + group = map->lockIndex; + } + } + } + + if (offset == 0) { + if (group == map->altIndex && (map->flags & 0x10) == 0) { + return 0; + } + if (group == map->lockIndex && (map->flags & 1) == 0) { + return 0; + } + if (group == map->shiftIndex && (map->flags & 4) == 0) { + return 0; + } + } else { + if (group == map->altIndex && (map->flags & 0x20) == 0) { + return 0; + } + if (group == map->lockIndex && (map->flags & 2) == 0) { + return 0; + } + if (group == map->shiftIndex && (map->flags & 8) == 0) { + return 0; + } + } + + } + + return table[keyIndex + offset + group]; + +} diff --git a/libs/RVL_SDK/src/vi/vi3in1.c b/libs/RVL_SDK/src/vi/vi3in1.c new file mode 100644 index 00000000..1b56acf0 --- /dev/null +++ b/libs/RVL_SDK/src/vi/vi3in1.c @@ -0,0 +1,719 @@ +#include +#include +#include + +static u16 gammaSet[31][17] = { + {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}, + {0x0000, 0x0000, 0x0000, 0x0030, 0x0397, 0x3b49, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1000, 0x1000, 0x1000, 0x1080, 0x1b80, 0xeb00}, + {0x0000, 0x0028, 0x005a, 0x02db, 0x0d8d, 0x3049, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1000, 0x1040, 0x1100, 0x1880, 0x4200, 0xeb00}, + {0x0000, 0x007a, 0x023c, 0x076d, 0x129c, 0x2724, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1000, 0x10c0, 0x1580, 0x2900, 0x6200, 0xeb00}, + {0x004e, 0x0199, 0x052d, 0x0b24, 0x1429, 0x20a4, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1040, 0x12c0, 0x1dc0, 0x3b00, 0x78c0, 0xeb00}, + {0x00ec, 0x03d7, 0x0800, 0x0d9e, 0x143e, 0x1bdb, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x10c0, 0x16c0, 0x27c0, 0x4b80, 0x8980, 0xeb00}, + {0x0276, 0x0666, 0x0a96, 0x0ef3, 0x13ac, 0x1849, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1200, 0x1c00, 0x3280, 0x59c0, 0x9600, 0xeb00}, + {0x04ec, 0x08f5, 0x0c96, 0x0fcf, 0x12c6, 0x1580, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1400, 0x2200, 0x3cc0, 0x6640, 0x9fc0, 0xeb00}, + {0x0800, 0x0bae, 0x0e00, 0x1030, 0x11cb, 0x1349, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1680, 0x28c0, 0x4680, 0x7100, 0xa780, 0xeb00}, + {0x0bb1, 0x0e14, 0x0f2d, 0x1018, 0x10e5, 0x1180, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x1980, 0x2f80, 0x4fc0, 0x7a00, 0xadc0, 0xeb00}, + {0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1020, 0x4060, 0x80a0, 0xeb00, 0x1000, 0x2000, 0x4000, 0x6000, 0x8000, 0xa000, 0xeb00}, + {0x14ec, 0x11c2, 0x1078, 0x0fb6, 0x0f2f, 0x0eb6, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x2100, 0x3cc0, 0x5fc0, 0x8900, 0xb780, 0xeb00}, + {0x19d8, 0x1333, 0x10d2, 0x0f6d, 0x0e5e, 0x0da4, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x2500, 0x4300, 0x66c0, 0x8f40, 0xbb40, 0xeb00}, + {0x1ec4, 0x147a, 0x110f, 0x0f0c, 0x0da1, 0x0cb6, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x2900, 0x4900, 0x6d40, 0x94c0, 0xbe80, 0xeb00}, + {0x2400, 0x1570, 0x110f, 0x0eaa, 0x0d0f, 0x0bdb, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x2d40, 0x4ec0, 0x7300, 0x9980, 0xc180, 0xeb00}, + {0x293b, 0x163d, 0x110f, 0x0e30, 0x0c7d, 0x0b24, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x3180, 0x5440, 0x7880, 0x9dc0, 0xc400, 0xeb00}, + {0x2e27, 0x170a, 0x10d2, 0x0de7, 0x0beb, 0x0a80, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x3580, 0x5980, 0x7d40, 0xa1c0, 0xc640, 0xeb00}, + {0x3362, 0x175c, 0x10d2, 0x0d6d, 0x0b6d, 0x09ed, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x39c0, 0x5e40, 0x8200, 0xa540, 0xc840, 0xeb00}, + {0x384e, 0x17ae, 0x10b4, 0x0d0c, 0x0af0, 0x096d, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x3dc0, 0x62c0, 0x8640, 0xa880, 0xca00, 0xeb00}, + {0x3d3b, 0x1800, 0x105a, 0x0cc3, 0x0a72, 0x0900, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x41c0, 0x6740, 0x8a00, 0xab80, 0xcb80, 0xeb00}, + {0x41d8, 0x1828, 0x103c, 0x0c49, 0x0a1f, 0x0892, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x4580, 0x6b40, 0x8dc0, 0xae00, 0xcd00, 0xeb00}, + {0x4676, 0x1851, 0x0fe1, 0x0c00, 0x09b6, 0x0836, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x4940, 0x6f40, 0x9100, 0xb080, 0xce40, 0xeb00}, + {0x4ac4, 0x187a, 0x0fa5, 0x0b9e, 0x0963, 0x07db, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x4cc0, 0x7300, 0x9440, 0xb2c0, 0xcf80, 0xeb00}, + {0x4f13, 0x1851, 0x0f69, 0x0b6d, 0x090f, 0x0780, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x5040, 0x7640, 0x9700, 0xb500, 0xd0c0, 0xeb00}, + {0x5313, 0x187a, 0x0f0f, 0x0b24, 0x08bc, 0x0736, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x5380, 0x79c0, 0x99c0, 0xb700, 0xd1c0, 0xeb00}, + {0x5713, 0x1851, 0x0ef0, 0x0ac3, 0x087d, 0x06ed, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x56c0, 0x7cc0, 0x9c80, 0xb8c0, 0xd2c0, 0xeb00}, + {0x5b13, 0x1828, 0x0e96, 0x0a92, 0x0829, 0x06b6, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x5a00, 0x7fc0, 0x9ec0, 0xba80, 0xd380, 0xeb00}, + {0x5ec4, 0x1800, 0x0e78, 0x0a30, 0x0800, 0x066d, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x5d00, 0x8280, 0xa140, 0xbc00, 0xd480, 0xeb00}, + {0x6276, 0x17d7, 0x0e1e, 0x0a00, 0x07c1, 0x0636, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x6000, 0x8540, 0xa340, 0xbd80, 0xd540, 0xeb00}, + {0x65d8, 0x17ae, 0x0de1, 0x09cf, 0x0782, 0x0600, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x62c0, 0x87c0, 0xa540, 0xbf00, 0xd600, 0xeb00}, + {0x693b, 0x1785, 0x0da5, 0x0986, 0x0743, 0x05db, 0x101d, 0x3658, 0x82b3, 0xeb00, 0x1000, 0x6580, 0x8a40, 0xa740, 0xc040, 0xd680, 0xeb00} +}; + +static u8 VINtscACPType1[0x1a] = { + 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8, + 0x00, 0x00, 0x0f, 0x0f, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +static u8 VINtscACPType2[0x1a] = { + 0x3e, 0x1d, 0x11, 0x25, 0x11, 0x01, 0x07, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8, + 0x00, 0x00, 0x0f, 0x0f, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x00 +}; + +static u8 VINtscACPType3[0x1a] = { + 0x3e, 0x17, 0x15, 0x21, 0x15, 0x05, 0x05, 0x02, 0x1b, 0x1b, 0x24, 0x07, 0xf8, + 0x00, 0x00, 0x0f, 0x0f, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x00 +}; + +static u8 VIPalACPType1[0x1a] = { + 0x36, 0x1a, 0x22, 0x2a, 0x22, 0x05, 0x02, 0x00, 0x1c, 0x3d, 0x14, 0x03, 0xfe, + 0x01, 0x54, 0xfe, 0x7e, 0x60, 0x00, 0x08, 0x00, 0x04, 0x07, 0x01, 0x55, 0x01 +}; + +static u8 VIPalACPType2[0x1a] = { + 0x36, 0x1a, 0x22, 0x2a, 0x22, 0x05, 0x02, 0x00, 0x1c, 0x3d, 0x14, 0x03, 0xfe, + 0x01, 0x54, 0xfe, 0x7e, 0x60, 0x00, 0x08, 0x00, 0x04, 0x07, 0x01, 0x55, 0x01 +}; + +static u8 VIPalACPType3[0x1a] = { + 0x36, 0x1a, 0x22, 0x2a, 0x22, 0x05, 0x02, 0x00, 0x1c, 0x3d, 0x14, 0x03, 0xfe, + 0x01, 0x54, 0xfe, 0x7e, 0x60, 0x00, 0x08, 0x00, 0x04, 0x07, 0x01, 0x55, 0x01 +}; + +static u8 VIEurgb60ACPType1[0x1a] = { + 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8, + 0x00, 0x00, 0x1e, 0x1e, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 +}; + +static u8 VIEurgb60ACPType2[0x1a] = { + 0x36, 0x1d, 0x11, 0x25, 0x11, 0x01, 0x07, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8, + 0x00, 0x00, 0x1e, 0x1e, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x01 +}; + +static u8 VIEurgb60ACPType3[0x1a] = { + 0x36, 0x17, 0x15, 0x21, 0x15, 0x05, 0x05, 0x02, 0x1b, 0x1b, 0x24, 0x07, 0xf8, + 0x00, 0x00, 0x1e, 0x1e, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x01 +}; + +static u8 VIMpalACPType1[0x1a] = { + 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8, + 0x00, 0x00, 0x0f, 0x0f, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +static u8 VIMpalACPType2[0x1a] = { + 0x36, 0x1d, 0x11, 0x25, 0x11, 0x01, 0x07, 0x00, 0x1b, 0x1b, 0x24, 0x07, 0xf8, + 0x00, 0x00, 0x0f, 0x0f, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x00 +}; + +static u8 VIMpalACPType3[0x1a] = { + 0x36, 0x17, 0x15, 0x21, 0x15, 0x05, 0x05, 0x02, 0x1b, 0x1b, 0x24, 0x07, 0xf8, + 0x00, 0x00, 0x0f, 0x0f, 0x60, 0x01, 0x0a, 0x00, 0x05, 0x04, 0x03, 0xff, 0x00 +}; + +u8 VIProgressiveACPType[0x1a] = { + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + + +void __VISendI2CData(u8 dev, u8* data, u8 length); +void WaitMicroTime(u32 time); +void __VISetYUVSEL(u8 value); +void __VISetGammaImm(u16* gamma); +void __VISetRevolutionMode(void); +void __VISetRevolutionModeSimple(void); +void VISetMacrovision(s32 type); + +#define COPY_ACP(dst, src) \ + do { \ + u32 copyIndex; \ + u8* destination = (dst); \ + const u8* source = (src); \ + for (copyIndex = 0; copyIndex < 0x1a; copyIndex++) { \ + destination[copyIndex + 1] = source[copyIndex]; \ + } \ + destination[0] = 0x40; \ + } while (0) + +static u8 __wd0 = 0xff; +static u8 __wd1 = 0xff; +static u8 __wd2 = 0xff; +static u8 __gp1 = 0xff; +static u8 __gp2 = 0xff; +static u8 __gp3 = 0xff; +static u8 __gp4 = 0xff; +static u8 __cc1 = 0xff; +static u8 __cc2 = 0xff; +static u8 __cc3 = 0xff; +static u8 __cc4 = 0xff; +static u32 __tvType = 0xff; +static u8 __filter = 0xff; +u8 VIZeroACPType[0x1a]; +static s32 Vdac_Flag_Region; +static s32 __type; +static s32 __gamma; +static s32 __level; +u32 Vdac_Flag_Changed_816991E0; + +void __VISetVolume(u8 wd0, u8 wd1) { + u8 data[3]; + + data[0] = 0x71; + data[1] = wd0; + data[2] = wd1; + __VISendI2CData(0xe0, data, 3); + WaitMicroTime(2); +} + +void __VISetYUVSEL(u8 value) { + s32 region = *(s32*)0x800000cc; + u8 data[2]; + + if (region != 2) { + if (region < 2) { + if (region == 0) { + goto region0; + } + if (region >= 0) { + goto region2; + } + } else { + switch (region) { + case 5: + goto region2; + default: + goto regionDefault; + } + } + goto regionDefault; + } + goto region1; +region2: + Vdac_Flag_Region = 2; + goto send; +region1: + Vdac_Flag_Region = 1; + goto send; +region0: + Vdac_Flag_Region = 0; + goto send; +regionDefault: + Vdac_Flag_Region = 0; + goto send; +send: + data[0] = 1; + data[1] = (value << 5) | Vdac_Flag_Region; + __VISendI2CData(0xe0, data, 2); + WaitMicroTime(2); +} + +void __VISetFilter4EURGB60(u8 value) { + u8 data[2]; + + data[0] = 0x6e; + data[1] = value; + __VISendI2CData(0xe0, data, 2); + WaitMicroTime(2); +} + +void __VISetCGMS(void) { + u8 data[3]; + + data[0] = 5; + data[1] = (__wd1 & 0xf) << 2 | __wd0 & 3; + data[2] = __wd2; + __VISendI2CData(0xe0, data, 3); + WaitMicroTime(2); +} + +void __VISetWSS(void) { + u8 data[3]; + + data[0] = 8; + data[1] = (__gp2 & 0xf) << 4 | __gp1 & 0xf; + data[2] = (__gp4 & 7) << 3 | __gp3 & 7; + __VISendI2CData(0xe0, data, 3); + WaitMicroTime(2); +} + +void __VISetClosedCaption(void) { + u8 data[5]; + + data[0] = 0x7a; + data[1] = __cc1 & 0x7f; + data[2] = __cc2 & 0x7f; + data[3] = __cc3 & 0x7f; + data[4] = __cc4 & 0x7f; + __VISendI2CData(0xe0, data, 5); + WaitMicroTime(2); +} + +void __VISetMacrovision(void) { + switch (__type) { + case 2: + switch (__tvType) { + case 0: { + u8 data[0x1b]; + COPY_ACP(data, VINtscACPType1); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + case 1: { + u8 data[0x1b]; + COPY_ACP(data, VIPalACPType1); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + case 2: { + u8 data[0x1b]; + COPY_ACP(data, VIMpalACPType1); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + case 5: { + u8 data[0x1b]; + COPY_ACP(data, VIEurgb60ACPType1); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + } + break; + case 3: + switch (__tvType) { + case 0: { + u8 data[0x1b]; + COPY_ACP(data, VINtscACPType2); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + case 1: { + u8 data[0x1b]; + COPY_ACP(data, VIPalACPType2); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + case 2: { + u8 data[0x1b]; + COPY_ACP(data, VIMpalACPType2); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + case 5: { + u8 data[0x1b]; + COPY_ACP(data, VIEurgb60ACPType2); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + } + break; + case 4: + switch (__tvType) { + case 0: { + u8 data[0x1b]; + COPY_ACP(data, VINtscACPType3); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + case 1: { + u8 data[0x1b]; + COPY_ACP(data, VIPalACPType3); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + case 2: { + u8 data[0x1b]; + COPY_ACP(data, VIMpalACPType3); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + case 5: { + u8 data[0x1b]; + COPY_ACP(data, VIEurgb60ACPType3); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + } + break; + case 1: { + u8 data[0x1b]; + COPY_ACP(data, VIZeroACPType); + __VISendI2CData(0xe0, data, 0x1b); + WaitMicroTime(2); + break; + } + } +} + +void VISetMacrovision(s32 type) { + u8 oldType; + u8 oldWd2; + u8 oldWd0; + u8 mode; + u32 volume; + u8 newType; + u8 newWd2; + s32 tvFormat; + + mode = 0; + volume = 0; + oldWd0 = __wd0; + oldType = __wd1; + oldWd2 = __wd2; + newType = oldType; + if (type == 3) { + goto type3; + } + if (type < 3) { + if (type == 1) { + goto type1; + } else if (type >= 1) { + goto type2; + } + goto done; + } + if (type >= 5) { + goto done; + } + goto type5; +type1: + mode = 0; + volume = 0; + goto done; +type2: + mode = 2; + volume = 3; + newType = 0; + goto done; +type3: + mode = 1; + volume = 3; + newType = 0; + goto done; +type5: + mode = 3; + volume = 3; + newType = 0; +done: + volume |= oldWd2 & 0xf0; + newWd2 = volume | mode << 2; + if ((oldType != newType) || (oldWd2 != newWd2)) { + __wd0 = oldWd0; + __wd1 = newType; + __wd2 = newWd2; + Vdac_Flag_Changed_816991E0 |= 1; + } + tvFormat = VIGetTvFormat(); + if ((__type != type) || (__tvType != tvFormat)) { + __type = type; + __tvType = tvFormat; + Vdac_Flag_Changed_816991E0 |= 8; + } +} + +void __VISetGammaImm(u16* gamma) { + u8 data[0x23]; + + data[0] = 0x10; + data[1] = ((u32)gamma[0] << 16) >> 24; + data[2] = gamma[0]; + data[3] = ((u32)gamma[1] << 16) >> 24; + data[4] = gamma[1]; + data[5] = ((u32)gamma[2] << 16) >> 24; + data[6] = gamma[2]; + data[7] = ((u32)gamma[3] << 16) >> 24; + data[8] = gamma[3]; + data[9] = ((u32)gamma[4] << 16) >> 24; + data[10] = gamma[4]; + data[11] = ((u32)gamma[5] << 16) >> 24; + data[12] = gamma[5]; + data[13] = ((u8*)gamma)[12]; + data[14] = ((u8*)gamma)[13]; + data[15] = ((u8*)gamma)[14]; + data[16] = ((u8*)gamma)[15]; + data[17] = ((u8*)gamma)[16]; + data[18] = ((u8*)gamma)[17]; + data[19] = ((u8*)gamma)[18]; + data[20] = ((u32)gamma[10] << 16) >> 24; + data[21] = gamma[10] & 0xc0; + data[22] = ((u32)gamma[11] << 16) >> 24; + data[23] = gamma[11] & 0xc0; + data[24] = ((u32)gamma[12] << 16) >> 24; + data[25] = gamma[12] & 0xc0; + data[26] = ((u32)gamma[13] << 16) >> 24; + data[27] = gamma[13] & 0xc0; + data[28] = ((u32)gamma[14] << 16) >> 24; + data[29] = gamma[14] & 0xc0; + data[30] = ((u32)gamma[15] << 16) >> 24; + data[31] = gamma[15] & 0xc0; + data[32] = ((u32)gamma[16] << 16) >> 24; + data[33] = gamma[16] & 0xc0; + __VISendI2CData(0xe0, data, 0x22); + WaitMicroTime(2); +} +void __VISetGamma(void) { + __VISetGammaImm(gammaSet[__gamma]); +} + +void __VISetTrapFilter(void) { + u8 data[2]; + + data[0] = 3; + if (__filter == 1) { + data[1] = 0; + } else { + data[1] = 1; + } + __VISendI2CData(0xe0, data, 2); + WaitMicroTime(2); +} + +void VISetTrapFilter(BOOL filter) { + if (__filter == (u32)filter) { + return; + } + __filter = filter; + Vdac_Flag_Changed_816991E0 |= 0x20; +} + +void __VISetRGBOverDrive(void) { + u8 data[2]; + + if (Vdac_Flag_Region == 3) { + data[0] = 10; + data[1] = __level << 1 | 1; + __VISendI2CData(0xe0, data, 2); + WaitMicroTime(2); + } else { + data[0] = 10; + data[1] = 0; + __VISendI2CData(0xe0, data, 2); + WaitMicroTime(2); + } +} + +void VISetRGBModeImm(void) { + Vdac_Flag_Changed_816991E0 |= 0x80; +} + +void __VISetRGBModeImm(void) { + u8 data[2]; + + Vdac_Flag_Region = 3; + data[0] = 1; + data[1] = 3; + __VISendI2CData(0xe0, data, 2); + WaitMicroTime(2); +} + +void __VISetRevolutionMode(void) { + u8 resetCommand[2]; + u8 powerCommand[2]; + u8 clockCommand[2]; + u8 outputCommand[2]; + u8 volumeCommand[3]; + u8 syncCommand[2]; + u8 enableCommand[2]; + + resetCommand[0] = 4; + resetCommand[1] = 0; + __VISendI2CData(0xe0, resetCommand, 2); + WaitMicroTime(2); + powerCommand[0] = 0x6a; + powerCommand[1] = 1; + __VISendI2CData(0xe0, powerCommand, 2); + WaitMicroTime(2); + clockCommand[0] = 0x65; + clockCommand[1] = 1; + __VISendI2CData(0xe0, clockCommand, 2); + WaitMicroTime(2); + __VISetYUVSEL(VIGetDTVStatus()); + outputCommand[0] = 0; + outputCommand[1] = 0; + __VISendI2CData(0xe0, outputCommand, 2); + WaitMicroTime(2); + volumeCommand[0] = 0x71; + volumeCommand[1] = 0x8e; + volumeCommand[2] = 0x8e; + __VISendI2CData(0xe0, volumeCommand, 3); + WaitMicroTime(2); + syncCommand[0] = 2; + syncCommand[1] = 7; + __VISendI2CData(0xe0, syncCommand, 2); + WaitMicroTime(2); + if ((__wd0 != 0) || (__wd1 != 0) || (__wd2 != 0)) { + __wd0 = 0; + __wd1 = 0; + __wd2 = 0; + Vdac_Flag_Changed_816991E0 |= 1; + } + if ((__gp1 != 0) || (__gp2 != 0) || (__gp3 != 0) || (__gp4 != 0)) { + __gp1 = 0; + __gp2 = 0; + __gp3 = 0; + __gp4 = 0; + Vdac_Flag_Changed_816991E0 |= 2; + } + if ((__cc1 != 0) || (__cc2 != 0) || (__cc3 != 0) || (__cc4 != 0)) { + __cc1 = 0; + __cc2 = 0; + __cc3 = 0; + __cc4 = 0; + Vdac_Flag_Changed_816991E0 |= 4; + } + VISetMacrovision(1); + if (__filter != 0) { + __filter = 0; + Vdac_Flag_Changed_816991E0 |= 0x20; + } + if (__level != 0) { + __level = 0; + Vdac_Flag_Changed_816991E0 |= 0x40; + } + if (__gamma != 10) { + __gamma = 10; + Vdac_Flag_Changed_816991E0 |= 0x10; + } + VIFlush(); + VIWaitForRetrace(); + enableCommand[0] = 4; + enableCommand[1] = 1; + __VISendI2CData(0xe0, enableCommand, 2); + WaitMicroTime(2); +} + +void __VISetRevolutionModeSimple(void) { + u32 i; + u8 powerCommand[2]; + u8 clockCommand[2]; + u8 outputCommand[2]; + u8 volumeCommand[3]; + u8 syncCommand[2]; + u8 cgmsCommand[3]; + u8 wssCommand[3]; + u8 captionCommand[5]; + u8 acpCommand[0x1c]; + u8 driveCommand[2]; + u8 filterCommand[2]; + + powerCommand[0] = 0x6a; + powerCommand[1] = 1; + __VISendI2CData(0xe0, powerCommand, 2); + WaitMicroTime(2); + clockCommand[0] = 0x65; + clockCommand[1] = 1; + __VISendI2CData(0xe0, clockCommand, 2); + WaitMicroTime(2); + __VISetYUVSEL(VIGetDTVStatus()); + outputCommand[0] = 0; + outputCommand[1] = 0; + __VISendI2CData(0xe0, outputCommand, 2); + WaitMicroTime(2); + volumeCommand[0] = 0x71; + volumeCommand[1] = 0x8e; + volumeCommand[2] = 0x8e; + __VISendI2CData(0xe0, volumeCommand, 3); + WaitMicroTime(2); + syncCommand[0] = 2; + syncCommand[1] = 7; + __VISendI2CData(0xe0, syncCommand, 2); + WaitMicroTime(2); + __wd0 = 0; + __wd1 = 0; + __wd2 = 0; + cgmsCommand[0] = 5; + cgmsCommand[1] = 0; + cgmsCommand[2] = 0; + __VISendI2CData(0xe0, cgmsCommand, 3); + WaitMicroTime(2); + if ((__gp1 != 0) || (__gp2 != 0) || (__gp3 != 0) || (__gp4 != 0)) { + __gp1 = 0; + __gp2 = 0; + __gp3 = 0; + __gp4 = 0; + Vdac_Flag_Changed_816991E0 |= 2; + } + wssCommand[0] = 8; + wssCommand[1] = (__gp2 & 0xf) << 4 | __gp1 & 0xf; + wssCommand[2] = (__gp4 & 7) << 3 | __gp3 & 7; + __VISendI2CData(0xe0, wssCommand, 3); + WaitMicroTime(2); + if ((__cc1 != 0) || (__cc2 != 0) || (__cc3 != 0) || (__cc4 != 0)) { + __cc1 = 0; + __cc2 = 0; + __cc3 = 0; + __cc4 = 0; + Vdac_Flag_Changed_816991E0 |= 4; + } + captionCommand[0] = 0x7a; + captionCommand[1] = __cc1 & 0x7f; + captionCommand[2] = __cc2 & 0x7f; + captionCommand[3] = __cc3 & 0x7f; + captionCommand[4] = __cc4 & 0x7f; + __VISendI2CData(0xe0, captionCommand, 5); + WaitMicroTime(2); + for (i = 0; i < 0x1a; i++) { + acpCommand[i + 1] = VIZeroACPType[i]; + } + acpCommand[0] = 0x40; + __VISendI2CData(0xe0, acpCommand, 0x1b); + WaitMicroTime(2); + if (__level != 0) { + __level = 0; + Vdac_Flag_Changed_816991E0 |= 0x40; + } + if (Vdac_Flag_Region == 3) { + driveCommand[0] = 10; + driveCommand[1] = __level << 1 | 1; + __VISendI2CData(0xe0, driveCommand, 2); + WaitMicroTime(2); + } else { + driveCommand[0] = 10; + driveCommand[1] = 0; + __VISendI2CData(0xe0, driveCommand, 2); + WaitMicroTime(2); + } + filterCommand[0] = 3; + filterCommand[1] = 1; + __VISendI2CData(0xe0, filterCommand, 2); + WaitMicroTime(2); + __VISetGammaImm(gammaSet[10]); +} + +void __VIInit3in1(VITVMode mode) { + u8 data[2]; + s32 value = (u32)mode >> 2; + u32 flag; + + if (value == 2) { + goto region1; + } + if (value < 2) { + if (value == 0) { + goto region0; + } + if (value >= 0) { + goto region2; + } + goto regionDefault; + } + if (value == 5) { + goto region2; + } + goto regionDefault; +region0: + flag = 0; + goto send; +region1: + flag = 1; + goto send; +region2: + flag = 2; + goto send; +regionDefault: + flag = 0; +send: + Vdac_Flag_Region = flag; + data[0] = 1; + data[1] = flag; + __VISendI2CData(0xe0, data, 2); + WaitMicroTime(2); + __VISetRevolutionMode(); +} diff --git a/src/scene/memoryCard/iplMemoryCardManager.cpp b/src/scene/memoryCard/iplMemoryCardManager.cpp new file mode 100644 index 00000000..791872d2 --- /dev/null +++ b/src/scene/memoryCard/iplMemoryCardManager.cpp @@ -0,0 +1,457 @@ +#include "scene/memoryCard/iplMemoryCardManager.h" +#include "utility/iplCharacterCode.h" +#include +#include +#include +#include + +struct MemoryCardSortEntry { + u32 fileNo; + u32 flags; + s64 key; +}; + +extern "C" int iplMemoryCardManager_813CD034(const void* first, const void* second) { + const MemoryCardSortEntry* a = static_cast(first); + const MemoryCardSortEntry* b = static_cast(second); + s64 bKey = b->key; + s64 aKey = a->key; + if (bKey < aKey) { + return 1; + } + if (aKey < bKey) { + return -1; + } + u32 bIndex = b->fileNo; + u32 aIndex = a->fileNo; + if (aIndex > bIndex) { + return 1; + } + return -(int)(aIndex < bIndex); +} + +namespace ipl { +namespace scene { + +typedef memorycard::FileInfo CardDirectory[0x7f]; +typedef memorycard::IconState CardIcons[0x7f]; + +void MemoryCardManager::calc() { + memorycard::probeCard(); + update_change_cardstate(0); + update_change_cardstate(1); + update_icon_anm(); +} + +bool MemoryCardManager::isSlotReady(u8 slot) { + memorycard::CardState* states = memorycard::getCardSlotState(); + return states[slot].state == 4; +} + +bool MemoryCardManager::isSlotNoCard(u8 slot) { + memorycard::CardState* states = memorycard::getCardSlotState(); + return states[slot].state == 0; +} + +long MemoryCardManager::isSlotWrongDevice(u8 slot) { + memorycard::CardState* states = memorycard::getCardSlotState(); + int result = 1; + memorycard::CardState* state = &states[slot]; + bool isWrong = true; + bool isUnsupported = true; + bool isUnformatted = true; + bool isInvalid = true; + if (state->state != 5 && state->state != 6) { + isInvalid = false; + } + if (!isInvalid && state->state != 7) { + isUnformatted = false; + } + if (!isUnformatted && state->state != 8) { + isUnsupported = false; + } + if (!isUnsupported && state->state != 9) { + isWrong = false; + } + if (!isWrong && state->state != 10) { + result = 0; + } + return result; +} + +void MemoryCardManager::sort_file_array(u8 slot) { + CardDirectory* dirs = reinterpret_cast(memorycard::getCardDirState()); + memorycard::FileInfo* directory = &dirs[slot][0]; + for (long file = 0; file < 0x7f; file++) { + if (directory[file].fileNo != 0) { + mFile[slot][file].fileNo = file; + mFile[slot][file].sortKey = directory[file].key; + mFile[slot][file].unk_0x08 = 0; + } else { + mFile[slot][file].fileNo = file; + mFile[slot][file].sortKey = -1 - file; + mFile[slot][file].unk_0x08 = 0; + } + } + qsort(mFile[slot], 0x7f, sizeof(MCFile), iplMemoryCardManager_813CD034); +} + +void MemoryCardManager::sendCardCmdMove(u8 slot, s16 index) { + u32 file = mFile[slot][index].fileNo; + mLastCmd = 2; + if (isDistSlot(slot, NULL)) { + memorycard::sendCardMoveCmd(slot, file); + mLastResult = -0x15; + mLastCmd = 3; + } else { + mLastResult = -0x17; + } +} + +void MemoryCardManager::sendCardCmdCopy(u8 slot, s16 index) { + u32 file = mFile[slot][index].fileNo; + if (isDistSlot(slot, NULL)) { + memorycard::sendCardCopyCmd(slot, file); + mLastResult = -0x15; + mLastCmd = 2; + } else { + mLastResult = -0x17; + } +} + +void MemoryCardManager::sendCardCmdDelete(u8 slot, s16 index) { + memorycard::sendCardDeleteCmd(slot, mFile[slot][index].fileNo); + mLastResult = -0x15; + mLastCmd = 4; +} + +void MemoryCardManager::sendCardCmdFormat(u8 slot) { + memorycard::sendCardFormatCmd(slot); + mLastResult = -0x15; + mLastCmd = 1; +} + +bool MemoryCardManager::isDistSlot(u8 slot, long* state) { + u32 other = slot ^ 1; + memorycard::CardState* states = memorycard::getCardSlotState(); + if (state != NULL) { + *state = states[other].state; + } + if (states[other].state == 4) { + return true; + } + return false; +} + +bool MemoryCardManager::isMoveEnable(u8 slot, u32 index, long* code) { + CardDirectory* dirs = reinterpret_cast(memorycard::getCardDirState()); + memorycard::CardState* states = memorycard::getCardSlotState(); + bool enabled = false; + int file = mFile[slot][index].fileNo; + memorycard::FileInfo* dir = NULL; + memorycard::CardState* destination = NULL; + long result = file; + if (isDistSlot(slot, NULL) && + ((dir = &dirs[slot][file])->canMove != 0) && + states[slot].key == (destination = &states[slot ^ 1])->key && + destination->freeBlocks >= dir->size && destination->unk_0x0E != 0 && + dir->unk_0x06 == 0) { + result = -0x15; + enabled = true; + } else { + long destinationState = 0; + if (!isDistSlot(slot, &destinationState)) { + if (destinationState == 0) { + result = -0x17; + } else if (destinationState == 5 || destinationState == 7 || destinationState == 9) { + result = -0x16; + } else { + result = -0x1c; + } + } else if ((dir = &dirs[slot][file])->canMove == 0) { + result = -0x1a; + } else if (states[slot].key != (destination = &states[slot ^ 1])->key) { + result = -0x1b; + } else if (destination->freeBlocks < dir->size || destination->unk_0x0E == 0) { + result = -0x19; + } else if (dir->unk_0x06 != 0) { + result = -0x18; + } + } + if (code != NULL) { + *code = result; + } + return enabled; +} + +bool MemoryCardManager::isCopyEnable(u8 slot, u32 index, long* code) { + CardDirectory* dirs = reinterpret_cast(memorycard::getCardDirState()); + memorycard::CardState* states = memorycard::getCardSlotState(); + bool enabled = false; + int file = mFile[slot][index].fileNo; + memorycard::FileInfo* dir = NULL; + memorycard::CardState* destination = NULL; + long result = file; + if (isDistSlot(slot, NULL) && + ((dir = &dirs[slot][file])->canCopy != 0) && + states[slot].key == (destination = &states[slot ^ 1])->key && + destination->freeBlocks >= dir->size && destination->unk_0x0E != 0 && + dir->unk_0x06 == 0) { + result = -0x15; + enabled = true; + } else { + long destinationState = 0; + if (!isDistSlot(slot, &destinationState)) { + if (destinationState == 0) { + result = -0x17; + } else if (destinationState == 5 || destinationState == 7 || destinationState == 9) { + result = -0x16; + } else { + result = -0x1c; + } + } else if ((dir = &dirs[slot][file])->canCopy == 0) { + result = -0x1a; + } else if (states[slot].key != (destination = &states[slot ^ 1])->key) { + result = -0x1b; + } else if (destination->freeBlocks < dir->size || destination->unk_0x0E == 0) { + result = -0x19; + } else if (dir->unk_0x06 != 0) { + result = -0x18; + } + } + if (code != NULL) { + *code = result; + } + return enabled; +} + +bool MemoryCardManager::isIconValidate(u8 slot, s16 index) { + u32 cardSlot = slot; + if (cardSlot > 1 || index < 0 || index >= 0x7f) { + return false; + } + CardDirectory* dirs = reinterpret_cast(memorycard::getCardDirState()); + if (mFile[cardSlot][index].fileNo >= 0x7f) { + return false; + } + return dirs[cardSlot][mFile[cardSlot][index].fileNo].fileNo != 0; +} + +bool MemoryCardManager::isBannerEnable(u8 slot, s16 index) { + CardIcons* icons = reinterpret_cast(memorycard::getIconStateArray()); + u32 file = mFile[slot][index].fileNo; + memorycard::IconState* icon = &icons[slot][file]; + u8 enabled = icon->bannerEnable; + return enabled != 0; +} + +void MemoryCardManager::update_icon_anm() { + CardIcons* icons = reinterpret_cast(memorycard::getIconStateArray()); + CardDirectory* dirs = reinterpret_cast(memorycard::getCardDirState()); + int slot = 0; + do { + int index = 0; + for (int remaining = 0x7f; remaining > 0; remaining--, index++) { + u32 file = mFile[slot][index].fileNo; + if (file < 0x7f && dirs[slot][file].fileNo != 0) { + memorycard::IconState* icon = &icons[slot][file]; + s16 frame = mFileCell[slot][file].iconAnmCounter + icon->anmDelta; + mFileCell[slot][file].iconAnmCounter = frame; + if (frame >= icon->anmMax) { + if (icon->anmType == 4) { + mFileCell[slot][file].iconAnmCounter = icon->anmMax - icon->unk_0x07 - 1; + icon->anmDelta = -1; + } else { + mFileCell[slot][file].iconAnmCounter = 0; + icon->anmDelta = 1; + } + } + if (mFileCell[slot][file].iconAnmCounter < 0) { + if (icon->anmType == 4) { + mFileCell[slot][file].iconAnmCounter = icon->unk_0x06; + } else { + mFileCell[slot][file].iconAnmCounter = 0; + } + icon->anmDelta = 1; + } + } + } + slot++; + } while (slot < 2); +} + +void MemoryCardManager::update_file_array(u8 slot) { + memorycard::CardState* states = memorycard::getCardSlotState(); + states[slot].changed = 0; + sort_file_array(slot); + long command = mLastCmd; + if ((u32)(command - 1) <= 3) { + if (mLastResult == -0x15) { + mLastResult = memorycard::getCardLastCMDFCmdResult(); + } + if (mLastResult == 0) { + switch (mLastCmd) { + case 3: + mpEventHandler->onMemEvent(2, slot); + mLastCmd = 6; + break; + case 2: + mpEventHandler->onMemEvent(1, slot); + mLastCmd = 5; + break; + case 4: + mpEventHandler->onMemEvent(3, slot); + mLastCmd = 7; + break; + case 1: + mpEventHandler->onMemEvent(4, slot); + mLastCmd = 8; + break; + } + } + } +} + +void MemCardEventHandler::onMemEvent(long event, u8 slot) { +} + +void MemoryCardManager::update_change_cardstate(u8 slot) { + memorycard::CardState* states = memorycard::getCardSlotState(); + if (states[slot].changed == 1) { + if (states[slot].state == 4) { + update_file_array(slot); + } else if (states[slot].state == 8 || states[slot].state == 6) { + mpEventHandler->onMemEvent(0, slot); + states[slot].changed = 0; + } + if (mLastResult == 0 && memorycard::getCardLastSendCmd() == 9 && + slot == memorycard::getCardLastSrcSlot()) { + mpEventHandler->onMemEvent(5, slot); + states[slot].changed = 0; + for (int file = 0; file < 0x7f; file++) { + mFile[slot][file].fileNo = -1; + mFile[slot][file].sortKey = -1; + mFile[slot][file].unk_0x08 = 0; + mFileCell[slot][file].iconAnmCounter = 0; + wmemset(mFileCell[slot][file].comment[0], 0, 0x40); + } + } + } + if (states[slot].state != 4 && states[slot].state != 6 && states[slot].state != 8) { + mpEventHandler->onMemEvent(6, slot); + } +} + +GXTexObj* MemoryCardManager::create_icon(u8 slot, s16 index) { + CardIcons* icons = reinterpret_cast(memorycard::getIconStateArray()); + int total = 0; + int file = mFile[slot][index].fileNo; + s16 frame = 0; + do { + u32 shift = frame; + frame++; + total += ((icons[slot][file].anmFrameBits >> ((shift & 0x1f) << 1)) & 3) * 4; + if (mFileCell[slot][file].iconAnmCounter <= total) { + break; + } + } while (frame < 9); + return _create_icon(slot, file, frame - 1); +} + +GXTexObj* MemoryCardManager::create_icon(u8 slot, s16 index, long start) { + memorycard::getIconStateArray(); + int file = mFile[slot][index].fileNo; + return _create_icon(slot, file, 0); +} + +GXTexObj* MemoryCardManager::_create_icon(u8 slot, s16 file, long start) { + CardDirectory* dirs = reinterpret_cast(memorycard::getCardDirState()); + if (dirs[slot][file].fileNo == 0) { + return NULL; + } + CardIcons* icons = reinterpret_cast(memorycard::getIconStateArray()); + memorycard::IconState* icon = &icons[slot][file]; + if ((int)icon->iconFmt[start] == GX_TF_RGB5A3) { + GXInitTexObj(&mFileCell[slot][file].icon, reinterpret_cast(icon) + icon->iconOffset[start], 0x20, 0x20, GX_TF_RGB5A3, GX_CLAMP, GX_CLAMP, GX_FALSE); + GXLoadTexObj(&mFileCell[slot][file].icon, GX_TEXMAP0); + } else if ((int)icon->iconFmt[start] == GX_TF_C8) { + GXInitTexObjCI(&mFileCell[slot][file].icon, reinterpret_cast(icon) + icon->iconOffset[start], 0x20, 0x20, GX_TF_C8, GX_CLAMP, GX_CLAMP, GX_FALSE, GX_TLUT0); + GXInitTlutObj(&mFileCell[slot][file].iconTlut, reinterpret_cast(icon) + icon->iconTlutOffset, GX_TL_RGB5A3, 0x100); + GXLoadTlut(&mFileCell[slot][file].iconTlut, GX_TLUT0); + GXLoadTexObj(&mFileCell[slot][file].icon, GX_TEXMAP0); + } else { + return NULL; + } + return &mFileCell[slot][file].icon; +} + +const wchar_t* MemoryCardManager::getComment(u8 slot, s16 index, int which) { + int file = mFile[slot][index].fileNo; + wchar_t* dest = mFileCell[slot][file].comment[which]; + wmemset(dest, 0, 0x40); + char comment[33] = {0}; + const char* comments = memorycard::getIconComment(slot, file); + memcpy(comment, comments + which * 0x20, 0x20); + char* end = comment + 0x1f; + char* tail = end; + for (; *end == ' ' || *end == '\n' || *end == 0;) { + *tail = 0; + end--; + tail--; + } + if (SCGetLanguage() == 0) { + utility::CharacterCode::shiftJISToUTF16(dest, reinterpret_cast(comment), 0x20); + for (int pos = 0x1f; dest[pos] == 0x20 || dest[pos] == 0x3000 || dest[pos] == 10 || dest[pos] == 0; pos--) { + dest[pos] = 0; + } + } else { + utility::CharacterCode::ANSIToUTF16(dest, reinterpret_cast(comment), 0x20); + } + bool found = false; + int count = 0; + while (dest[count] != 0 && count < 0x20) { + if (found) { + dest[count] = 0; + } else if (dest[count] == 10 || dest[count] == 0xd0a) { + dest[count] = 0; + found = true; + } + count++; + } + return dest; +} + +GXTexObj* MemoryCardManager::create_banner(u8 slot, s16 index) { + CardDirectory* dirs = reinterpret_cast(memorycard::getCardDirState()); + CardIcons* icons = reinterpret_cast(memorycard::getIconStateArray()); + int file = mFile[slot][index].fileNo; + memorycard::IconState* icon = &icons[slot][file]; + if (dirs[slot][file].fileNo == 0 || !icon->bannerEnable) { + return NULL; + } + if ((int)icon->bannerType == GX_TF_RGB5A3) { + GXInitTexObj(&mFileCell[slot][file].banner, reinterpret_cast(icon) + icon->bannerOffset, + 0x60, 0x20, GX_TF_RGB5A3, GX_CLAMP, GX_CLAMP, GX_FALSE); + GXLoadTexObj(&mFileCell[slot][file].banner, GX_TEXMAP0); + } else if ((int)icon->bannerType == GX_TF_C8) { + GXInitTexObjCI(&mFileCell[slot][file].banner, reinterpret_cast(icon) + icon->bannerOffset, + 0x60, 0x20, GX_TF_C8, GX_CLAMP, GX_CLAMP, GX_FALSE, GX_TLUT0); + GXInitTlutObj(&mFileCell[slot][file].bannerTlut, reinterpret_cast(icon) + icon->bannerTlutOffset, GX_TL_RGB5A3, 0x100); + GXLoadTlut(&mFileCell[slot][file].bannerTlut, GX_TLUT0); + GXLoadTexObj(&mFileCell[slot][file].banner, GX_TEXMAP0); + } + return &mFileCell[slot][file].banner; +} + +u16 MemoryCardManager::getBlocks(u8 slot, s16 index) { + CardDirectory* dirs = reinterpret_cast(memorycard::getCardDirState()); + return dirs[slot][mFile[slot][index].fileNo].size; +} + +u16 MemoryCardManager::getFreeBlocks(u8 slot) { + memorycard::CardState* states = memorycard::getCardSlotState(); + return states[slot].freeBlocks; +} + +} +} diff --git a/tools/decomp-assist/iplMemoryCardManager.attempts.md b/tools/decomp-assist/iplMemoryCardManager.attempts.md new file mode 100644 index 00000000..7020ae30 --- /dev/null +++ b/tools/decomp-assist/iplMemoryCardManager.attempts.md @@ -0,0 +1,107 @@ +# iplMemoryCardManager attempts + +All 26 functions implemented in target object order. Shared headers unchanged. +Target and source have no .data string pool. All destination buffers and state locals are initialized. +Final retained variants combine the best readable implementations from the measured waves. + +## sort_file_array +1. Cached file-array pointer and flat directory lookup. +2. Typed directory arrays and pointer indexing. +3. Direct member indexing, removing cached file-array pointer. +4. Signed long loop counter; identical register allocation. +Measured waves 1-4, objdiff percent: 72.745094, 72.745094, 98.13725, 98.13725. +Final instruction evidence: +`src 0xcc base 0xcc insns 51/51; diffs 15: [12, 14, 17, 19, 20, 23, 24, 25, 26, 27, 29, 31, 32, 33, 38]` + + +## isMoveEnable +1. Flat directory lookup and early rejection. +2. Typed directory array and lookup inside the ready guard. +3. Success-first permission branch and initialized destination-state local. +Measured waves 1-4, objdiff percent: 71.08475, 87.78814, 91.39831, 91.39831. +Final instruction evidence: +`src 0x1e0 base 0x1d8 insns 120/118; --- insert mine 13:13 base 13:14` + + +## isCopyEnable +1. Flat directory lookup and early rejection. +2. Typed directory array and lookup inside the ready guard. +3. Success-first permission branch and initialized destination-state local. +Measured waves 1-4, objdiff percent: 71.08475, 87.78814, 91.39831, 91.39831. +Final instruction evidence: +`src 0x1e0 base 0x1d8 insns 120/118; --- insert mine 13:13 base 13:14` + + +## isBannerEnable +1. Flat icon lookup. +2. Typed slot/file icon array. +3. Named result local; identical epilogue schedule. +Measured waves 1-4, objdiff percent: 91.30769, 92.30769, 92.30769, 92.30769. +Final instruction evidence: +`src 0x68 base 0x68 insns 26/26; diffs 8: [11, 12, 13, 14, 15, 16, 17, 18]` + + +## update_icon_anm +1. Cached animation-counter pointer and ascending frame loop. +2. Direct cell-member indexing. +3. Descending frame-count loop and separately named delta. +Measured waves 1-4, objdiff percent: 87.53571, 95.15476, 96.78571, 96.78571. +Final instruction evidence: +`src 0x14c base 0x150 insns 83/84; --- replace mine 10:11 base 10:11` + + +## update_file_array +1. Direct unsigned subtraction expression compared with three. +2. Named signed command local before the unsigned subtraction; identical allocation. +3. Named unsigned command after subtraction, compared with four; worse register allocation. +Retained attempt 2. +Measured waves 1-4, objdiff percent: 99.72222, 99.72222, 99.655556, 99.72222. +Final instruction evidence: +`src 0x168 base 0x168 insns 90/90; diffs 4: [15, 16, 17, 20]` + + +## create_icon +1. Unsigned masked frame shift. +2. Signed frame counter and less-than-nine loop bound. +3. Signed unmasked shift and less-than-or-equal-eight bound. +Measured waves 1-4, objdiff percent: 82.23529, 86.84314, 86.17647, 86.84314. +Final instruction evidence: +`src 0xc8 base 0xcc insns 50/51; --- replace mine 16:18 base 16:18` + + +## _create_icon +1. Cached cell and texture pointers. +2. Direct member expressions for each texture call. +3. Branch-local texture pointer. +4. Direct member expressions and signed format comparisons. +Measured waves 1-4, objdiff percent: 46.9, 83.95, 79.15, 85.15. +Final instruction evidence: +`src 0x184 base 0x190 insns 97/100; --- replace mine 5:9 base 5:9` + + +## getComment +1. Indexed byte clear loop. +2. Pointer-increment byte clear loop. +3. Initialized local character array; closer initialization sequence. +Measured waves 1-4, objdiff percent: 77.93496, 78.097565, 79.42277, 79.42277. +Final instruction evidence: +`src 0x1c0 base 0x1ec insns 112/123; --- replace mine 0:1 base 0:1` + + +## create_banner +1. Cached cell pointer and early return. +2. Direct member texture expressions and compound rejection condition. +3. Nested success guards and named texture pointer; worse schedule. +4. Direct member expressions and signed format comparisons. +Measured waves 1-4, objdiff percent: 50.603775, 76.31132, 55.679245, 78.669815. +Final instruction evidence: +`src 0x19c base 0x1a8 insns 103/106; --- replace mine 0:1 base 0:1` + + +## getBlocks +1. Flat directory lookup and cached file number. +2. Direct typed slot/file directory lookup. +3. Named directory pointer and result local; worse epilogue schedule. +Measured waves 1-4, objdiff percent: 74.96, 92.0, 91.0, 92.0. +Final instruction evidence: +`src 0x64 base 0x64 insns 25/25; diffs 9: [11, 12, 13, 14, 15, 16, 17, 18, 19]` diff --git a/tools/decomp-assist/kbd_lib.attempts.md b/tools/decomp-assist/kbd_lib.attempts.md new file mode 100644 index 00000000..a77f98dc --- /dev/null +++ b/tools/decomp-assist/kbd_lib.attempts.md @@ -0,0 +1,66 @@ +# kbd_lib attempts + +All 21 functions implemented in object order. Shared headers unchanged. +All modifier destinations are initialized; no volatile or register declarations were added. +Pools identical. Command reservation preserves the device marker until completion. + +## kbdEventHandler +1. Compound search and unsigned report loops. +2. Byte channel search and for/break key scans. +3. Signed scan indices and byte mask. +4. Status reload after alarm; branch inversion; word mask. +Measured waves 1-6, objdiff percent: 63.822582, 65.145164, 73.053764, 73.268814, 98.81183, 99.10215. +Instruction diffs retained in /tmp/sol-low-kbd-final-ctx.txt. + +## kbdProcKey +1. Range predicate; mapped byte local; repeat loop. +2. Explicit modifier keys; signed map loop; initialized getter destination. +3. Getter result handling with preloaded destination. +Measured waves 1-6, objdiff percent: 52.11628, 62.15116, 62.15116, 97.5, 97.5, 89.91279. +Instruction diffs retained in /tmp/sol-low-kbd-final-ctx.txt. + +## kbdProcMod +1. Ascending cases and delta counters. +2. Object-order cases; getter/setter calls; unsigned count fields. +3. Boolean count expressions instead of word-sign masks. +Measured waves 1-6, objdiff percent: 29.371094, 29.371094, 27.867188, 81.50391, 81.50391, 75.78125. +Instruction diffs retained in /tmp/sol-low-kbd-final-ctx.txt. + +## kbd_led_handler +1. Ternary result and callback pointer. +2. Switch result and numeric callback table. +3. Inverted if/else result. +Measured waves 1-6, objdiff percent: 22.16, 22.16, 70.0, 70.0, 70.0, 43.76. +Instruction diffs retained in /tmp/sol-low-kbd-final-ctx.txt. + +## KBDSetLedsAsync +1. Compound free-command scan. +2. For/break scan and device reservation. +3. Guard returns, delayed channel lookup and explicit result checks. +Measured waves 1-6, objdiff percent: 60.4321, 60.4321, 60.444443, 66.03704, 66.03704, 73.02469. +Instruction diffs retained in /tmp/sol-low-kbd-final-ctx.txt. + +## KBDSetLeds +1. Compound free-command scan. +2. For/break scan and device reservation. +3. Guard returns, delayed channel lookup and explicit result checks. +Measured waves 1-6, objdiff percent: 48.49367, 48.49367, 48.49367, 61.481014, 61.481014, 70.91139. +Instruction diffs retained in /tmp/sol-low-kbd-final-ctx.txt. + +## KBDSetModState +1. Negative flag branch; direct scalar masks. +2. Positive flag branch; named masked value. +3. Bitfield state copy through a field pointer. +Measured waves 1-6, objdiff percent: 50.690475, 94.04762, 94.04762, 94.04762, 94.04762, 98.690475. +Instruction diffs retained in /tmp/sol-low-kbd-final-ctx.txt. + +## KBDTranslateHidCode +1. Unsigned groups and final stateIndex. +2. Signed group and separate table selection. +3. Word mask, byte cast within each table branch. +Measured waves 1-6, objdiff percent: 79.152435, 79.152435, 82.54878, 82.54878, 82.54878, 86.29878. +Instruction diffs retained in /tmp/sol-low-kbd-final-ctx.txt. + +## Final gate discrepancy +KBDResetChannel has objdiff 100.0% and identical 176-byte instruction contents. +The gate reports 12/21 instead of 13/21 because odiff.dis treats the first CR1 conditional-branch operand as an immediate and subtracts the different symbol offsets. Both disputed branch instruction words are identical. Tools were left unchanged. diff --git a/tools/decomp-assist/vi3in1.attempts.md b/tools/decomp-assist/vi3in1.attempts.md new file mode 100644 index 00000000..056c21fc --- /dev/null +++ b/tools/decomp-assist/vi3in1.attempts.md @@ -0,0 +1,21 @@ +# vi3in1 attempts + +All 18 functions implemented in object order; first build matched 15 exactly. +String pools identical. Data 1512/1512 bytes in objdiff. + +## __VISetMacrovision +1. Indexed 26-byte copy loop, literal command byte after copy: 864/866 instructions, 94.26905%. Missing saved r28; copy pointer and bytes allocated to different registers. +2. Pointer increment loop: same 864/866 instruction diff. +3. Explicit byte assignments: 889/866 instructions, 37.678986%; excessive live byte values increased the stack frame. Rejected. +4. Structured switches and branch-local command arrays: same 864/866 diff. Retained for readability. + +## VISetMacrovision +1. Literal byte loads and separate volume update: 68/68 instructions, 7 differences, 99.48529%. Load and intermediate registers differ. +2. Reordered old-byte loads and combined OR expression: 68/68, 22 differences. Rejected. +3. Reordered declarations: 68/68, 10 differences. Rejected. +4. Separate old-byte declaration order and reversed OR operands: 68/68, 24 differences. Rejected. Retained attempt 1. + +## __VISetRevolutionModeSimple +1. Indexed ACP copy, original assignment order: 265/267 instructions, 96.82022%; saved constant register and byte-copy allocation differ. +2. Masked WSS operands and command-first caption assignment: 265/267; WSS and caption differences removed. Retained. +3. Explicit ACP byte copies: 266/267, 78.92135%; enlarged frame and save set. Rejected. -- 2.49.1 From 2060db15f6f93684aed26b656f69e49d2016d9f5 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:17:04 -0500 Subject: [PATCH 5/7] MSL: locale data, file_io 4/4 (worker f5f4a391) (#341) --- README.md | 4 +- libs/MSL/matching-attempts.log | 45 +++++++++ libs/MSL/src/MSL_Common/file_io.c | 160 ++++++++++++++++++++++++++++++ libs/MSL/src/MSL_Common/locale.c | 123 +++++++++++++++++++++++ libs/MSL/src/MSL_Common/printf.c | 2 +- 5 files changed, 331 insertions(+), 3 deletions(-) create mode 100644 libs/MSL/src/MSL_Common/file_io.c create mode 100644 libs/MSL/src/MSL_Common/locale.c diff --git a/README.md b/README.md index 585b5e32..698c1922 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 91.56% | 80.70% | 56.95% | 88.70% | +| 91.59% | 80.73% | 56.95% | 88.75% | -units 758/1027 complete, functions 11604/12563 matched. +units 758/1027 complete, functions 11608/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/libs/MSL/matching-attempts.log b/libs/MSL/matching-attempts.log index d2de1d6a..4cfcb0df 100644 --- a/libs/MSL/matching-attempts.log +++ b/libs/MSL/matching-attempts.log @@ -41,3 +41,48 @@ scanf: all four functions have zero ctxdiff differences, code 5484/5484 and data strtold: __strtold has 1277/1277 instructions and strtod 44/44, both zero differences. Removed the imported inline qualifier from the public strtod wrapper so the real target symbol is emitted. Code 5284/5284 and data 112/112. Exception metadata settings change only owned NonMatching units; configure.py status flags remain NonMatching. Clean gates require the original DOL SHA1 and zero baseline regressions. Raw instruction-exact counts can be lower than objdiff exact counts because the varargs conditional branch to an external register-save helper is compared without relocation normalization by gate.py. These counts are reported separately; they were not patched or hidden. +printf::double2hex: aggregate exponent format initialized at declaration: 238/242 instructions, 227 positional diffs; restored. +printf::double2hex: initialize exponent integer fields before byte flags: 241/242 instructions, 127 positional diffs; restored. +printf::double2hex: use integer nibble temporary with explicit final narrowing: 239/242 instructions, 123 positional diffs; restored. +printf::__pformatter: move parsed format declaration after output buffer: 511/535 instructions, 367 positional diffs; restored. +printf::__pformatter: initialize parsed format before first parse: 516/535 instructions, 505 positional diffs; restored. +printf::__pformatter: separate next-format pointer from parsed cursor: 511/535 instructions, 367 positional diffs; restored. +wprintf::double2hex: aggregate exponent format initialized at declaration: 238/242 instructions, 227 positional diffs; restored. +wprintf::double2hex: initialize exponent integer fields before byte flags: 241/242 instructions, 127 positional diffs; restored. +wprintf::double2hex: use integer nibble temporary with explicit final narrowing: 239/242 instructions, 123 positional diffs; restored. +wprintf::__wpformatter: move parsed format declaration after output buffer: 567/593 instructions, 519 positional diffs; restored. +wprintf::__wpformatter: initialize parsed format before first parse: 572/593 instructions, 562 positional diffs; restored. +wprintf::__wpformatter: separate next-format pointer from parsed cursor: 567/593 instructions, 519 positional diffs; restored. +printf::printf: finish varargs lifetime with va_end: compile rejected: ninja: build stopped: subcommand failed.; restored. +printf::printf: return through named result temporary: compile rejected: ninja: build stopped: subcommand failed.; restored. +printf::printf: move va_start to first actual formatting use: 50/50 instructions, 1 positional diffs; restored. +printf::fprintf: finish varargs lifetime with va_end: compile rejected: ninja: build stopped: subcommand failed.; restored. +printf::fprintf: return through named result temporary: compile rejected: ninja: build stopped: subcommand failed.; restored. +printf::fprintf: move va_start to first actual formatting use: 49/49 instructions, 1 positional diffs; restored. +printf::printf: finish varargs lifetime / initialize controller first: 50/50 instructions, 1 positional diffs; restored. +printf::printf: hoist argument list / named result: 50/50 instructions, 1 positional diffs; restored. +printf::printf: argument-list pointer / delay va_start: 50/50 instructions, 1 positional diffs; restored. +printf::fprintf: finish varargs lifetime / initialize controller first: 49/49 instructions, 1 positional diffs; restored. +printf::fprintf: hoist argument list / named result: 49/49 instructions, 1 positional diffs; restored. +printf::fprintf: argument-list pointer / delay va_start: 49/49 instructions, 1 positional diffs; restored. +printf::snprintf: finish varargs lifetime / initialize controller first: 54/54 instructions, 1 positional diffs; restored. +printf::snprintf: hoist argument list / named result: 54/54 instructions, 1 positional diffs; restored. +printf::snprintf: argument-list pointer / delay va_start: 54/54 instructions, 1 positional diffs; restored. +printf::sprintf: finish varargs lifetime / initialize controller first: 52/52 instructions, 1 positional diffs; restored. +printf::sprintf: hoist argument list / named result: 52/52 instructions, 1 positional diffs; restored. +printf::sprintf: argument-list pointer / delay va_start: 52/52 instructions, 1 positional diffs; restored. +wprintf::swprintf: finish varargs lifetime / initialize controller first: 55/55 instructions, 1 positional diffs; restored. +wprintf::swprintf: hoist argument list / named result: 55/55 instructions, 1 positional diffs; restored. +wprintf::swprintf: argument-list pointer / delay va_start: 55/55 instructions, 11 positional diffs; restored. +time::emit: finish varargs lifetime / initialize controller first: 43/43 instructions, 1 positional diffs; restored. +time::emit: hoist argument list / named result: 43/43 instructions, 1 positional diffs; restored. +time::emit: argument-list pointer / delay va_start: 42/43 instructions, 34 positional diffs; restored. + +printf data: 139/148 relocation entries agree by target function and addend; dispatch-table entries in the unmatched formatter still differ. Generated jump-table data is retained, without manual entries or symbol mappings. +wprintf data: 139/148 relocation entries agree by target function and addend; dispatch-table entries in the unmatched formatter still differ. Generated jump-table data is retained, without manual entries or symbol mappings. +printf double2hex: moved exponent-format initialization after exponent extraction: 241/242 instructions; FP aggregate copies remained; restored. +wprintf double2hex: moved exponent-format initialization after exponent extraction: 241/242 instructions; FP aggregate copies remained; restored. +printf data: changed zero comparison literal to long double, matching the argument type and sharing its zero constant with float2str. .sdata2 now 8 bytes, 100%, versus 16 emitted bytes previously. Instruction scores unchanged. +time data: literal pool, calendar tables and BSS already agree. Target has nine exception-index records; source includes exception records for real public asctime/ctime functions absent in the extracted target. Retained the functions rather than suppressing output. +locale: restored the C locale components, collation table and ordinary literals in source order; all 792 data bytes exact. No target code functions exist. +file_io: implemented fclose, fflush, __msl_strnicmp and __msl_itoa in object order using FILE fields and named arithmetic temporaries; all four have zero ctxdiff differences, 928 code bytes and 60 metadata bytes exact. diff --git a/libs/MSL/src/MSL_Common/file_io.c b/libs/MSL/src/MSL_Common/file_io.c new file mode 100644 index 00000000..4cbdbb23 --- /dev/null +++ b/libs/MSL/src/MSL_Common/file_io.c @@ -0,0 +1,160 @@ +#include +#include +#include +#include + +enum file_kinds { file_closed, file_disk, file_console, file_unavailable }; +enum io_states { neutral, writing, reading, rereading }; +enum io_modes { io_read = 1, io_write = 2, io_append = 4 }; +extern int __flush_all(void); +extern int __flush_buffer(FILE*, size_t*); + +#pragma exceptions on + +int fclose(FILE* file) +{ + int flush_result, close_result; + + if (file == NULL) + return -1; + if (file->mode.file_kind == file_closed) + return 0; + + flush_result = fflush(file); + + close_result = (*file->close_proc)(file->handle); + + file->mode.file_kind = file_closed; + file->handle = 0; + + if (file->state.free_buffer) + free((FILE*)file->buffer); + return (flush_result || close_result) ? -1 : 0; +} + +int fflush(FILE* file) +{ + int pos; + + if (file == NULL) + { + return __flush_all(); + } + + if (file->state.error != 0 || file->mode.file_kind == file_closed) + { + return -1; + } + + if (file->mode.io_mode == io_read) + { + return 0; + } + + if (file->state.io_state >= rereading) + { + file->state.io_state = reading; + } + + if (file->state.io_state == reading) + { + file->buffer_len = 0; + } + + if (file->state.io_state != writing) + { + file->state.io_state = neutral; + return 0; + } + + if (file->mode.file_kind != file_disk) + { + pos = 0; + } + else + { + pos = ftell(file); + } + + if (__flush_buffer(file, NULL) != 0) + { + file->state.error = 1; + file->buffer_len = 0; + return -1; + } + + file->state.io_state = neutral; + file->pos = pos; + file->buffer_len = 0; + return 0; +} + +int __msl_strnicmp(const char* str1, const char* str2, int n) +{ + int i; + char c1, c2; + + for (i = 0; i < n; i++) + { + c1 = tolower(*str1++); + c2 = tolower(*str2++); + + if (c1 < c2) + return -1; + + if (c1 > c2) + return 1; + + if (c1 == '\0') + return 0; + } + + return 0; +} + +char* __msl_itoa(int value, char* str, unsigned int base) +{ + int negative; + int length; + char c; + int start; + int end; + + negative = 0; + length = 0; + + if (value < 0) + { + value = -value; + negative = 1; + } + + do + { + int digit = value % base; + + if (digit > 9) + str[length++] = digit + 0x37; + else + str[length++] = digit + 0x30; + + value /= base; + } while (value != 0); + + if (negative != 0) + str[length++] = '-'; + + str[length++] = '\0'; + + start = 0; + end = strlen(str) - 1; + + while (start < end) + { + c = str[start]; + str[start++] = str[end]; + str[end--] = c; + } + + return str; +} diff --git a/libs/MSL/src/MSL_Common/locale.c b/libs/MSL/src/MSL_Common/locale.c new file mode 100644 index 00000000..6bee5dc5 --- /dev/null +++ b/libs/MSL/src/MSL_Common/locale.c @@ -0,0 +1,123 @@ +#include +#include +#include + +extern int __mbtowc_noconv(wchar_t*, const char*, size_t); +extern int __wctomb_noconv(char*, wchar_t); + +struct lconv __lconv = { + ".", + "", + "", + "", + "", + "", + "", + "", + "", + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + "", + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, +}; + +extern const unsigned short __ctype_mapC[256]; +extern const unsigned char __upper_mapC[256]; +extern const unsigned char __lower_mapC[256]; +extern const unsigned short __wctype_mapC[256]; +extern const wchar_t __wupper_mapC[256]; +extern const wchar_t __wlower_mapC[256]; + +struct _loc_ctype_cmpt _loc_ctyp_C = { + "C", + __ctype_mapC, + __upper_mapC, + __lower_mapC, + __wctype_mapC, + __wupper_mapC, + __wlower_mapC, + __mbtowc_noconv, + __wctomb_noconv +}; + +unsigned short char_coll_tableC[96] = { + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 17, 18, 19, 20, 21, 22, 23, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, + 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 24, 25, 26, 27, 28, 0, 44, 46, 48, 50, 52, 54, 56, + 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 29, 30, 31, 32, 0, +}; + +struct _loc_coll_cmpt _loc_coll_C = { + "C", + ' ', + 110, + 0, + char_coll_tableC, + NULL +}; + +struct _loc_mon_cmpt _loc_mon_C = { + "C", + "", + "", + "", + "", + "", + "", + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + "", + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX, + CHAR_MAX +}; + +struct _loc_num_cmpt _loc_num_C = { + "C", + ".", + "", + "" +}; + +struct _loc_time_cmpt _loc_tim_C = { + "C", + "AM|PM", + "%a %b %e %T %Y", + "%I:%M:%S %p", + "%m/%d/%y", + "%T", + "Sun|Sunday|Mon|Monday|Tue|Tuesday|Wed|Wednesday|Thu|Thursday|Fri|Friday|Sat|Saturday", + "Jan|January|Feb|February|Mar|March|Apr|April|May|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|" + "November|Dec|December", + "" +}; + +struct __locale _current_locale = { + NULL, + "C", + &_loc_coll_C, + &_loc_ctyp_C, + &_loc_mon_C, + &_loc_num_C, + &_loc_tim_C +}; diff --git a/libs/MSL/src/MSL_Common/printf.c b/libs/MSL/src/MSL_Common/printf.c index 51c0d272..f19fa672 100644 --- a/libs/MSL/src/MSL_Common/printf.c +++ b/libs/MSL/src/MSL_Common/printf.c @@ -545,7 +545,7 @@ static char* double2hex(long double num, char* buff, print_format format) { form.digits = 0x20; __num2dec(&form, num, &dec); - if (fabs(num) == 0.0) { + if (fabs(num) == 0.0L) { p = buff - 6; strcpy(p, "0x0p0"); return p; -- 2.49.1 From 88ab8325dbc4d0e0498433c4e611ff2612b118d5 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:23:32 -0500 Subject: [PATCH 6/7] eZiText round 2: zi8getc2 11/17 (worker 2384260a) (#342) --- README.md | 4 +- libs/RVLMiddleware/eZiText/src/clib/zi8dawg.c | 27 ++---- .../RVLMiddleware/eZiText/src/clib/zi8getc2.c | 92 +++++++++---------- .../RVLMiddleware/eZiText/src/clib/zikorean.c | 2 +- tools/decomp-assist/zi8dawg.attempts.md | 39 ++++++++ tools/decomp-assist/zi8getc2.attempts.md | 59 ++++++++++++ tools/decomp-assist/zi8match.attempts.md | 29 ++++++ tools/decomp-assist/zikorean.attempts.md | 15 +++ 8 files changed, 200 insertions(+), 67 deletions(-) diff --git a/README.md b/README.md index 698c1922..8bbdde80 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 91.59% | 80.73% | 56.95% | 88.75% | +| 91.60% | 80.76% | 56.95% | 88.75% | -units 758/1027 complete, functions 11608/12563 matched. +units 758/1027 complete, functions 11609/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/libs/RVLMiddleware/eZiText/src/clib/zi8dawg.c b/libs/RVLMiddleware/eZiText/src/clib/zi8dawg.c index d00aa87f..3283d646 100644 --- a/libs/RVLMiddleware/eZiText/src/clib/zi8dawg.c +++ b/libs/RVLMiddleware/eZiText/src/clib/zi8dawg.c @@ -20,7 +20,7 @@ ziU32 Zi8MatchROMdata0(ziWChar* elements, ziU32 count, ziU8 language, ziBool searching; ziS32 tableSize; ziU8* graph; - ziS16 key; + ziU16 key; ziU8 endOfWord; zi8DawgRec* current; ziU16 index; @@ -29,7 +29,7 @@ ziU32 Zi8MatchROMdata0(ziWChar* elements, ziU32 count, ziU8 language, ziU8 result = 0; ziU32 keyCount; ziU8* table; - ziS16 keys[3]; + ziU16 keys[3]; if (language != context->lang || graphTable != context->key) { records[0].key = 0; @@ -86,7 +86,7 @@ ziU32 Zi8MatchROMdata0(ziWChar* elements, ziU32 count, ziU8 language, keys[(ziU16)index] = 0; table = (ziU8*)Zi8GetTableAddress(language, keyTable, ZI_WORK); context->p14 = table + 2; - records[0].node = ZiDAWGGetGraphInfo(context, table + context->cap * 2 + 2, keys); + records[0].node = ZiDAWGGetGraphInfo(context, table + context->cap * 2 + 2, (ziS16*)keys); } records[0].key = 0; if (records[0].node == 0) goto finish_graph; @@ -300,15 +300,10 @@ search_segment: if ((ZI_WORK->dawgCtx.key == 0) && ((language & 0xff) == 10)) { for (result = 0; (result & 0xff) < (unsigned int)ZI_WORK->unk_0x17EA; result = result + 1) { character = ZI_WORK->unk_0x17F4[result & 0xff]; - if (character == 0x6f) { -select_vowel_table: + if (character == 0x61 || character == 0x6f || character == 0x75) { ZI_WORK->unk_0x141E = 0x10; break; } - if (character < 0x6f) { - if (character == 0x61) goto select_vowel_table; - } - else if (character == 0x75) goto select_vowel_table; } } goto search_segment; @@ -324,14 +319,12 @@ finish_segments: ziU8 Zi8MatchROMdata(ziWChar *elements, ziU8 count, ziU8 language, ziWChar *output, ziU16 capacity, ziU8 mode, ziU8 status, ziU8 reservedMode, ziU8 acceptPrefix, ziPtr __zi8_work_data) { - ziU16 *input; ziU8* group; int tableSize; ziU8 found; unsigned int elementCount; unsigned int result; - input = (ziU16 *)elements; elementCount = (unsigned int)count; result = 0; if ((capacity & 0xffff) < (elementCount & 0xff)) { @@ -352,12 +345,12 @@ ziU8 Zi8MatchROMdata(ziWChar *elements, ziU8 count, ziU8 language, ziWChar *outp } tableSize = Zi8GetTableSize(language & 0xff,0x1c,ZI_WORK); if (tableSize == 0) { - result = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff, + result = Zi8MatchROMdata2(elements,elementCount & 0xff,language & 0xff,output,capacity & 0xffff, mode & 0xff,status & 0xff,reservedMode & 0xff,0,acceptPrefix,ZI_WORK); } else { while (((ZI_WORK->unk_0x17F0 != 0 && - (result = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff, + (result = Zi8MatchROMdata2(elements,elementCount & 0xff,language & 0xff,output,capacity & 0xffff, mode & 0xff,status & 0xff,reservedMode & 0xff, (ziU8 *)ZI_WORK->unk_0x17F0,acceptPrefix,ZI_WORK), (result & 0xff) == 0)) && @@ -370,10 +363,10 @@ ziU8 Zi8MatchROMdata(ziWChar *elements, ziU8 count, ziU8 language, ziWChar *outp (((elementCount & 0xff) == 1 && ((capacity & 0xffff) != 0)))) { ZI_WORK->unk_0x17EC = 1; if (tableSize == 0) { - found = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff,0, + found = Zi8MatchROMdata2(elements,elementCount & 0xff,language & 0xff,output,capacity & 0xffff,0, status & 0xff,reservedMode & 0xff,0,acceptPrefix,ZI_WORK); if (found != '\0') { - *output = *input; + *output = *elements; result = 1; } } @@ -381,11 +374,11 @@ ziU8 Zi8MatchROMdata(ziWChar *elements, ziU8 count, ziU8 language, ziWChar *outp group = NextDawgGroup(0,language & 0xff,ZI_WORK); ZI_WORK->unk_0x17F0 = group; while (ZI_WORK->unk_0x17F0 != 0) { - found = Zi8MatchROMdata2(input,elementCount & 0xff,language & 0xff,output,capacity & 0xffff,0, + found = Zi8MatchROMdata2(elements,elementCount & 0xff,language & 0xff,output,capacity & 0xffff,0, status & 0xff,reservedMode & 0xff,(ziU8 *)ZI_WORK->unk_0x17F0, acceptPrefix,ZI_WORK); if (found != '\0') { - *output = *input; + *output = *elements; result = 1; break; } diff --git a/libs/RVLMiddleware/eZiText/src/clib/zi8getc2.c b/libs/RVLMiddleware/eZiText/src/clib/zi8getc2.c index 20828518..0dd1046e 100644 --- a/libs/RVLMiddleware/eZiText/src/clib/zi8getc2.c +++ b/libs/RVLMiddleware/eZiText/src/clib/zi8getc2.c @@ -89,16 +89,15 @@ static ziU16 Zi8GetDataSignature(ziU8* destination, ziU16 capacity, ziU8 languag static ziU16 Zi8GetEngineSignature(ziU8* destination, ziPtr work) { ziU16 index = 0; - ziU16 major; - ziU16 minor; + struct { ziU16 minor; } version; ziU16 number; destination[index++] = 'v'; - major = (Zi8GetVersion(work) & 0xff00) >> 8; - minor = Zi8GetVersion(work) & 0xff; - destination[index++] = (ziU8)(major / 10 + '0'); - destination[index++] = (ziU8)(major % 10 + '0'); - destination[index++] = (ziU8)(minor / 10 + '0'); - destination[index++] = (ziU8)(minor % 10 + '0'); + number = (Zi8GetVersion(work) & 0xff00) >> 8; + version.minor = Zi8GetVersion(work) & 0xff; + destination[index++] = (ziU8)(number / 10 + '0'); + destination[index++] = (ziU8)(number % 10 + '0'); + destination[index++] = (ziU8)(version.minor / 10 + '0'); + destination[index++] = (ziU8)(version.minor % 10 + '0'); destination[index++] = 'o'; number = Zi8GetOEMID(work); destination[index++] = (ziU8)(number / 100 + '0'); @@ -119,7 +118,7 @@ static ziBool Zi8AlphaSignature(ziGetParam* parameters, ziBool countOnly ZI_NEED ziU8* second; ziU8* first; ziU8 engine[32]; - ziU8 dictionary[56]; + ziU8 dictionary[32]; ziU16 length; ziU16 candidateCount; ziWChar* output = parameters->candidates; @@ -210,7 +209,7 @@ static ziBool Zi8ZhSignature(ziGetParam* parameters, ziBool countOnly ZI_NEED_WO ziU8* current = 0; ziU16 copied; ziU8 engine[32]; - ziU8 dictionary[64]; + ziU8 dictionary[32]; ziU16 dataLength; ziU32 engineLength; ziU32 candidateCount; @@ -314,13 +313,13 @@ ziU32 Zi8GetCandidatesOrCount(ziGetParam* parameters, ZiCandidateOptions* option ziU16 savedCharacter; ziWChar* savedElements; ziBool restoreCandidates; - char signatureFound; ziU8 elementCount; int error; unsigned int candidateCount; ziU8 savedOptions; ziWChar* savedCandidates; - ziU16 characterInfo [32]; + ziU16 characterInfo[16]; + ziU16 lastInfoCharacter; error = 0; savedOptions = 0; @@ -328,10 +327,10 @@ ziU32 Zi8GetCandidatesOrCount(ziGetParam* parameters, ZiCandidateOptions* option restoreCandidates = 0; if (options->lookupMode == '\0') { if (((ZI_WORK->unk_0x00 == '\t') && (parameters->elementCount != 0)) && - ((((ziS16)parameters->elements[parameters->elementCount - 1] == -0x1008 && - (signatureFound = Zi8AlphaSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')) || - (((ziS16)parameters->elements[parameters->elementCount - 1] == -0x10fc && - (signatureFound = Zi8ZhSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')))))) { + (((parameters->elements[parameters->elementCount - 1] == 0xEFF8 && + ((ziU8)Zi8AlphaSignature(parameters,options->countOnly,ZI_WORK) != 0)) || + ((parameters->elements[parameters->elementCount - 1] == 0xEF04 && + ((ziU8)Zi8ZhSignature(parameters,options->countOnly,ZI_WORK) != 0)))))) { candidateCount = (unsigned int)parameters->letters; if (options->countOnly != '\0') { parameters->letters = 0; @@ -347,7 +346,7 @@ ziU32 Zi8GetCandidatesOrCount(ziGetParam* parameters, ZiCandidateOptions* option if ((ZI_WORK->unk_0x00 == '\0') || (ZI_WORK->unk_0x01 == options->countOnly)) { switch(ZI_WORK->unk_0x00) { case '\0': - if ((ziS16)parameters->elements[0] == -0x10fc) { + if (parameters->elements[0] == 0xEF04) { ZI_WORK->unk_0x01 = options->countOnly; ZI_WORK->unk_0x00 = '\x01'; } @@ -356,7 +355,7 @@ ziU32 Zi8GetCandidatesOrCount(ziGetParam* parameters, ZiCandidateOptions* option case '\x03': case '\x05': case '\a': - if ((ziS16)parameters->elements[0] == -0x10ff) { + if (parameters->elements[0] == 0xEF01) { ZI_WORK->unk_0x00 = ZI_WORK->unk_0x00 + '\x01'; } else { @@ -366,7 +365,7 @@ ziU32 Zi8GetCandidatesOrCount(ziGetParam* parameters, ZiCandidateOptions* option case '\x02': case '\x04': case '\x06': - if ((ziS16)parameters->elements[0] == -0x10fc) { + if (parameters->elements[0] == 0xEF04) { ZI_WORK->unk_0x00 = ZI_WORK->unk_0x00 + '\x01'; } else { @@ -375,8 +374,8 @@ ziU32 Zi8GetCandidatesOrCount(ziGetParam* parameters, ZiCandidateOptions* option break; case '\b': case '\t': - if (((ziS16)parameters->elements[0] == -0x10fc) && - (signatureFound = Zi8ZhSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')) { + if ((parameters->elements[0] == 0xEF04) && + ((ziU8)Zi8ZhSignature(parameters,options->countOnly,ZI_WORK) != 0)) { ZI_WORK->unk_0x00 = '\t'; candidateCount = (unsigned int)parameters->letters; if (options->countOnly != '\0') { @@ -388,7 +387,7 @@ ziU32 Zi8GetCandidatesOrCount(ziGetParam* parameters, ZiCandidateOptions* option default: ZI_WORK->unk_0x00 = '\0'; } - if ((ZI_WORK->unk_0x00 == '\0') && ((ziS16)parameters->elements[0] == -0x10fc)) { + if ((ZI_WORK->unk_0x00 == '\0') && (parameters->elements[0] == 0xEF04)) { ZI_WORK->unk_0x00 = '\x01'; } } @@ -401,13 +400,13 @@ latinSequence: if ((ZI_WORK->unk_0x00 == '\0') || (ZI_WORK->unk_0x01 == options->countOnly)) { switch(ZI_WORK->unk_0x00) { case '\0': - if ((ziS16)parameters->elements[0] == -0x100e) { + if (parameters->elements[0] == 0xEFF2) { ZI_WORK->unk_0x01 = options->countOnly; ZI_WORK->unk_0x00 = '\x01'; } break; case '\x01': - if ((ziS16)parameters->elements[0] == -0x100d) { + if (parameters->elements[0] == 0xEFF3) { ZI_WORK->unk_0x00 = '\x02'; } else { @@ -415,7 +414,7 @@ latinSequence: } break; case '\x02': - if ((ziS16)parameters->elements[0] == -0x100b) { + if (parameters->elements[0] == 0xEFF5) { ZI_WORK->unk_0x00 = '\x03'; } else { @@ -423,7 +422,7 @@ latinSequence: } break; case '\x03': - if ((ziS16)parameters->elements[0] == -0x1009) { + if (parameters->elements[0] == 0xEFF7) { ZI_WORK->unk_0x00 = '\x04'; } else { @@ -431,7 +430,7 @@ latinSequence: } break; case '\x04': - if ((ziS16)parameters->elements[0] == -0x1008) { + if (parameters->elements[0] == 0xEFF8) { ZI_WORK->unk_0x00 = '\x05'; } else { @@ -439,7 +438,7 @@ latinSequence: } break; case '\x05': - if ((ziS16)parameters->elements[0] == -0x1007) { + if (parameters->elements[0] == 0xEFF9) { ZI_WORK->unk_0x00 = '\x06'; } else { @@ -447,7 +446,7 @@ latinSequence: } break; case '\x06': - if ((ziS16)parameters->elements[0] == -0x100e) { + if (parameters->elements[0] == 0xEFF2) { ZI_WORK->unk_0x00 = '\a'; } else { @@ -455,7 +454,7 @@ latinSequence: } break; case '\a': - if ((ziS16)parameters->elements[0] == -0x100b) { + if (parameters->elements[0] == 0xEFF5) { ZI_WORK->unk_0x00 = '\b'; } else { @@ -464,8 +463,8 @@ latinSequence: break; case '\b': case '\t': - if (((ziS16)parameters->elements[0] == -0x1008) && - (signatureFound = Zi8AlphaSignature(parameters,options->countOnly,ZI_WORK), signatureFound != '\0')) { + if ((parameters->elements[0] == 0xEFF8) && + ((ziU8)Zi8AlphaSignature(parameters,options->countOnly,ZI_WORK) != 0)) { ZI_WORK->unk_0x00 = '\t'; candidateCount = (unsigned int)parameters->letters; if (options->countOnly != '\0') { @@ -477,7 +476,7 @@ latinSequence: default: ZI_WORK->unk_0x00 = '\0'; } - if ((ZI_WORK->unk_0x00 == '\0') && ((ziS16)parameters->elements[0] == -0x100e)) { + if ((ZI_WORK->unk_0x00 == '\0') && (parameters->elements[0] == 0xEFF2)) { ZI_WORK->unk_0x00 = '\x01'; } } @@ -495,8 +494,7 @@ latinSequence: options->maxCount = ZI_WORK->unk_0x10; options->maxWordLength = ZI_WORK->unk_0x0A; ZI_WORK->unk_0x0A = -1; - signatureFound = Zi8LangSupported(parameters->language,ZI_WORK); - if (signatureFound == '\0') { + if ((ziU8)Zi8LangSupported(parameters->language,ZI_WORK) == 0) { Zi8LogError(0x163,ZI_WORK); candidateCount = 0; } @@ -519,7 +517,7 @@ latinSequence: } else if ((parameters->language == 1) && ((((parameters->getOptions & 0xbf) == 4 && (parameters->elementCount != 0)) && - (signatureFound = Zi8IsCharacter(parameters->elements[0],ZI_WORK), signatureFound != '\0')))) { + ((ziU8)Zi8IsCharacter(parameters->elements[0],ZI_WORK) != 0)))) { elementCount = Zi8GetCharInfo(parameters->elements[0],characterInfo,0x10,1,ZI_WORK); if (elementCount == 0) { parameters->unk_0x20 = 0; @@ -529,7 +527,8 @@ latinSequence: error = 900; } else { - if ((0xf330 < characterInfo[elementCount - 1]) && (characterInfo[elementCount - 1] < 0xf336)) { + lastInfoCharacter = characterInfo[elementCount - 1]; + if ((0xf330 < lastInfoCharacter) && (lastInfoCharacter < 0xf336)) { characterInfo[elementCount - 1] = 0xf360; } savedElements = parameters->elements; @@ -579,9 +578,9 @@ latinSequence: else if (parameters->language == 1) { candidateCount = Zi8GetChineseCandidates(parameters,options,ZI_WORK); if ((((candidateCount == 0) && ((parameters->getOptions & 0x20) == 0)) && ((parameters->getMode == 1 && (parameters->elementCount != 0)))) - && ((((ziS16)parameters->elements[parameters->elementCount - 1] == -0xc86 || - ((ziS16)parameters->elements[parameters->elementCount - 1] == -0xc9d)) || - ((ziS16)parameters->elements[parameters->elementCount - 1] == -0xc8d)))) { + && (((parameters->elements[parameters->elementCount - 1] == 0xF37A || + (parameters->elements[parameters->elementCount - 1] == 0xF363)) || + (parameters->elements[parameters->elementCount - 1] == 0xF373)))) { savedCharacter = parameters->elements[parameters->elementCount]; elementCount = parameters->elementCount; parameters->elements[elementCount] = 0xf368; @@ -636,10 +635,11 @@ void Zi8InitDupWordBuf(ziPtr __zi8_work_data) { } ziBool Zi8IsDupWChar(ziWChar character ZI_NEED_WORK) { - ziBool duplicate = 0; - ziU16* buffer = ZI_WORK->unk_0x57A; + ziBool duplicate; + ziU16* buffer; unsigned int index; - ziU16 position; + duplicate = 0; + buffer = ZI_WORK->unk_0x57A; if (ZI_WORK->unk_0x539 == 0) { buffer[0] = 2; buffer[1] = character; @@ -654,9 +654,7 @@ ziBool Zi8IsDupWChar(ziWChar character ZI_NEED_WORK) { } } ZI_WORK->unk_0x539++; - position = *buffer; - buffer[position] = character; - *buffer = ++position; + buffer[(*buffer)++] = character; if (*buffer > 100) { *buffer = 2; buffer[1] = character; @@ -668,7 +666,7 @@ ziBool Zi8IsDupWChar(ziWChar character ZI_NEED_WORK) { ziBool Zi8IsDupWordW(ziWChar* word, ziU8 length ZI_NEED_WORK) { ziU8 slot; - ziU32 duplicate = 0; + ziBool duplicate = 0; unsigned int position; int index; int character; diff --git a/libs/RVLMiddleware/eZiText/src/clib/zikorean.c b/libs/RVLMiddleware/eZiText/src/clib/zikorean.c index dfab9f19..889b4f25 100644 --- a/libs/RVLMiddleware/eZiText/src/clib/zikorean.c +++ b/libs/RVLMiddleware/eZiText/src/clib/zikorean.c @@ -45,7 +45,7 @@ ziU8 Zi8GetKoreanCandidates(ziGetParam* params, ziU8* argument, ziU8* table1; } state; ziU16 buffer[100]; - ziU8 result; + unsigned int result; ziU16 currentCharacter; ziU8* selectedTable; diff --git a/tools/decomp-assist/zi8dawg.attempts.md b/tools/decomp-assist/zi8dawg.attempts.md index 11d8cb01..8d0a2659 100644 --- a/tools/decomp-assist/zi8dawg.attempts.md +++ b/tools/decomp-assist/zi8dawg.attempts.md @@ -31,3 +31,42 @@ Zi8MatchROMdata: Retained the attempt 1 body. With the retained full-width segment-helper signature it measures 58.106598%, 237/197 instructions. Group iteration and fallback control flow differ. + +Continuation on merged baseline (2/6 exact, code 536/4868, data 0/120). + +Zi8MatchROMdata0 (baseline 45.16092%, 533/522): +1. Byte incoming count: 45.672413%, 532/522. +2. Unsigned converted key and key buffer: 47.754787%, 531/522. +3. Group capacity, status and result into traversal state: + 47.77203%, 534/522; first draft placed assignments before declarations and + did not compile, then corrected declaration order. +Retained unsigned keys. Target has no extsh operations, and Zi8ConvertWC2Key +returns ziWChar. Did not retain the traversal state for a negligible fuzzy gain +with three more instructions. Graph traversal and stack allocation still differ. + +Zi8MatchROMdata1 (baseline 99.765625%, 128/128, 5 differences): +1. Move group decrement to loop entry: 97.46094%, 129/128. +2. Typed table-address pointer: unchanged 99.765625%, 128/128. +3. Byte status parameter: 98.984375%, 129/128. +4. Group table address into table state: 96.671875%, 129/128. +Also tried an unsigned group parameter; rejected the compile failure caused by +existing char-pointer callers rather than changing other functions for the trial. +Retained baseline: r26/r27 assignments differ. + +Zi8MatchROMdata2 (baseline 249/236): +1. Signed remaining-output cursor: 249/236. +2. Byte status parameter: 253/236. +3. Direct a/o/u vowel condition: 245/236. +Retained direct vowel test. Objdiff omits this function's fuzzy percentage in all +these reports; it is not 100%. Segment loops, narrowing and allocation differ. + +Zi8MatchROMdata (baseline 58.106598%, 237/197): +1. U16 result: 55.055836%, 238/197. +2. Remove redundant input-pointer alias: 61.563454%, 234/197. +3. Unsigned table size: unchanged 58.106598%, 237/197. +Retained alias removal; fallback and group iteration branches differ. + +Data audit: no .data/.rodata/.sdata content or strings. Source and target have +48-byte .extab and 72-byte .extabindex sections. Their mismatches derive from +unmatched function frames/sizes; no fabricated metadata added. Gate confirms +identical empty pools (pool_diff itself expects a .data section and raises KeyError). diff --git a/tools/decomp-assist/zi8getc2.attempts.md b/tools/decomp-assist/zi8getc2.attempts.md index aa0ca26a..f91d6ac1 100644 --- a/tools/decomp-assist/zi8getc2.attempts.md +++ b/tools/decomp-assist/zi8getc2.attempts.md @@ -44,3 +44,62 @@ Zi8IsDupWordW: 2. Explicit loop break: 90.22302%, 140/139. 3. U8 cache position: 88.78417%, 142/139. Retained attempt 2; loop layout and cache index allocation differ. + +Continuation on merged baseline (10/17 exact, code 484/6888, data 24/332). + +Zi8GetDataSignature (baseline 99.347824%, 69/69, 9 differences): +1. Keep table address as U32 until memcpy: unchanged. +2. Generic destination parameter with typed output alias: 97.072464%, 70/69. +3. Successful length branch first with error fallthrough: 81.73913%, 69/69. +Retained baseline: saved register allocation only. + +Zi8GetEngineSignature: +1. Reuse numeric value for major, OEM and build: 96.02679%, 219/224. +2. Store minor version as a member of version state: 100%, 224/224, ctxdiff 0. +3. Two-component version array: 99.98661%, 224/224, 3 differences. +4. Unsigned output index: 87.52232%, 205/224. +Retained version state and reused number; this is the new instruction-exact function. + +Zi8AlphaSignature: +1. Dictionary buffer sized for the passed 32-byte capacity: 67.61275%, 188/204. +2. Group signature pointers, lengths and countOnly state: 59.32353%, 213/204. +3. Invert the dictionary eligibility branch with grouped state: + 62.656864%, 213/204. +Retained capacity-sized buffer; stack locals and branches still differ. + +Zi8ZhSignature: +1. Dictionary buffer sized for passed capacity: 29.225962%, 202/208. +2. U16 lengths/count and explicit presence increments: 26.26923%, 212/208. +3. Group countOnly and available state with U16 lengths/count: + 21.259615%, 214/208. +Retained capacity-sized buffer; promotions, stack state and loops differ. + +Zi8GetCandidatesOrCount: +1. Unsigned UTF16 sentinel comparisons and signature result: 81.198845%, 740/694. +2. Direct signature tests, sixteen-character info buffer: 84.46254%, 717/694. +3. Direct language/character helper tests: 85.65274%, 709/694. +4. Name and reuse final character-info character: 86.7536%, 707/694. +Retained these improvements; dispatch branches and saved stack state still differ. + +Zi8IsDupWChar: +1. U32 buffer position with U16 count/index conversions: 96.031746%, 65/63. +2. Unsigned position and direct count increment: 97.53968%, 64/63. +3. Append with buffer[(*buffer)++]: 99.36508%, 63/63, 8 differences. +4. Unsigned result flag: 98.492065%, 63/63, extra return narrowing. +5. Separate buffer/result declarations from initialization: unchanged 99.36508%. +Retained postincrement append and separate initialization; character/result +register assignments are swapped. + +Zi8IsDupWordW: +1. Unsigned loop indices: 87.84892%, 140/139. +2. Typed twenty-one-character cache records: 82.51798%, 141/139. +3. Boolean duplicate flag: 91.33813%, 141/139. +Retained boolean flag; cache loop layout and allocation remain different. + +Data audit: 16-byte search-order .rodata is identical. Both .data sections are +80-byte switch tables whose entries depend on unmatched dispatch branches. +Original .sdata2 is 8 bytes (4-byte fuzzy pair plus section-end zeros), source +4 bytes. Original zero fuzzy symbol/.sbss2 is 8 bytes, current header type and +source object are 4. Both section alignments are 8. The current shared headers +do not explain the extra trailing bytes; no fake padding or shared ABI edits. +Empty string pools remain identical. diff --git a/tools/decomp-assist/zi8match.attempts.md b/tools/decomp-assist/zi8match.attempts.md index 55ba6f66..68ccc2db 100644 --- a/tools/decomp-assist/zi8match.attempts.md +++ b/tools/decomp-assist/zi8match.attempts.md @@ -23,3 +23,32 @@ Retained 53/53, 99.245285%; r6/r7 allocation in result loads differs. Zi8GetBpmfPhonetic: 1. Deferred result initialization: 309/309, 99.23948%. 2. Unsigned result counter and direct text subtraction: 309/309, 100%, diffs 0. + +Continuation on merged baseline (7/10 exact, code 3720/8256, data 608/728). + +Zi8GetPyFinal (baseline 99.245285%, 53/53, 8 differences): +1. Reverse byte-pointer addition in final output access: unchanged. +2. Widen row to unsigned int, narrow output table index: 95.0%, 51/53. +3. Typed eight-byte final records with spelling/initial/final/flags fields: + 99.245285%, 53/53, same eight allocation differences; table remains 528 bytes. +4. Flat object byte indexing with row stride: 99.0566%, 53/53. +Retained baseline: only r6/r7 address-expression allocation differs. + +Zi8MatchPhonetic (baseline 77.66942%, 359/363): +1. Byte match/alternate flags and signed remaining count: 75.242424%, 362/363. +2. Group match flags and remaining count into semantic search state: + 72.7989%, 356/363. +3. Typed twelve-byte dictionary records rather than byte-stride indexing: + 77.694214%, 358/363. +Retained baseline: control flow, stack layout and instruction count differ. + +Zi8GetPyPhonetic (baseline 75.160164%, 726/718): +1. Integer partial flag and U32 result: 73.678276%, 727/718. +2. Structured letter/extension range checks: unchanged 75.160164%, 726/718. +3. Initialize converted count at declaration; allow worst-case separator expansion + in conversion buffer, narrow per-syllable buffer: 75.0%, 726/718. +Retained baseline: conversion branches, frame and allocation differ. + +Data audit: .rodata 528 bytes is identical; .extab 80 bytes is identical. +Remaining .extabindex differences follow unmatched function sizes. Empty pools +remain identical. No data-address objects or configuration changes added. diff --git a/tools/decomp-assist/zikorean.attempts.md b/tools/decomp-assist/zikorean.attempts.md index eb429692..756d5292 100644 --- a/tools/decomp-assist/zikorean.attempts.md +++ b/tools/decomp-assist/zikorean.attempts.md @@ -8,3 +8,18 @@ Zi8GetKoreanCandidates: 3. Typed three-byte character/sequence records: 66.96769%, 629/619. Retained attempt 1. The main routine still differs in stack state, loop structure and register allocation. No register/volatile keywords were retained. + +Continuation on merged baseline (2/3 exact, code 2712/5188, data 24/348). + +Zi8GetKoreanCandidates (baseline 68.13893%, 629/619): +1. Full-width candidate result: 68.76414%, 623/619. +2. Full-width character/loop cursor: 68.021%, 605/619. +3. Typed three-byte character mapping records: 67.266556%, 624/619. +Retained full-width result; candidate branches and stack/access allocation differ. + +Data audit: source contains the two natural 31-entry switch tables in function +order, 248 bytes. Original .data is 288 bytes; its final 40-byte table references +Zi8_81483118, owned by zkokeyp (.text 8148302C..8148447C), outside this unit. +This is a split ownership problem, not a missing Korean function. Changing splits +or manually placing that foreign table is outside this task. Remaining owned +table relocations depend on unmatched function branch offsets. Empty pools match. -- 2.49.1 From 3d716e151868886050e35f8374d66bde8eccebbc Mon Sep 17 00:00:00 2001 From: devin Date: Wed, 30 Sep 2026 06:25:47 +0000 Subject: [PATCH 7/7] axfx: link AXFXReverbHiExpDpl2 + AXFXReverbStdExp (objdiff 100%) Co-Authored-By: wch --- configure.py | 4 +- .../include/revolution/axfx/AXFXCommon.h | 9 + .../revolution/axfx/AXFXReverbHiExpDpl2.h | 6 +- .../revolution/axfx/AXFXReverbStdExp.h | 4 +- libs/RVL_SDK/src/axfx/AXFXReverbHiExpDpl2.c | 461 ++++++++++++++++++ libs/RVL_SDK/src/axfx/AXFXReverbStd.c | 2 +- libs/RVL_SDK/src/axfx/AXFXReverbStdExp.c | 397 +++++++++++++++ 7 files changed, 875 insertions(+), 8 deletions(-) create mode 100644 libs/RVL_SDK/src/axfx/AXFXReverbHiExpDpl2.c create mode 100644 libs/RVL_SDK/src/axfx/AXFXReverbStdExp.c diff --git a/configure.py b/configure.py index 8d4df0d8..c6b69f11 100644 --- a/configure.py +++ b/configure.py @@ -1448,10 +1448,10 @@ config.libs = [ Object(Matching, "axfx/AXFXReverbHi.c"), Object(Matching, "axfx/AXFXReverbHiDpl2.c"), Object(Matching, "axfx/AXFXReverbHiExp.c"), - Object(NonMatching, "axfx/AXFXReverbHiExpDpl2.c"), + Object(Matching, "axfx/AXFXReverbHiExpDpl2.c"), Object(Matching, "axfx/AXFXDelay.c"), Object(Matching, "axfx/AXFXReverbStd.c"), - Object(NonMatching, "axfx/AXFXReverbStdExp.c"), + Object(Matching, "axfx/AXFXReverbStdExp.c"), Object(Matching, "axfx/AXFXChorus.c"), Object(NonMatching, "axfx/AXFXChorusExp.c"), Object(Matching, "axfx/AXFXLfoTable.c"), diff --git a/libs/RVL_SDK/include/revolution/axfx/AXFXCommon.h b/libs/RVL_SDK/include/revolution/axfx/AXFXCommon.h index 51dcaa39..4457c2f1 100644 --- a/libs/RVL_SDK/include/revolution/axfx/AXFXCommon.h +++ b/libs/RVL_SDK/include/revolution/axfx/AXFXCommon.h @@ -7,6 +7,8 @@ extern "C" { #endif +#define AXFX_STEREO_CHANNEL_MAX 3 + typedef struct AXFX_BUS { s32* left; // 0x00 s32* right; // 0x04 @@ -19,6 +21,13 @@ typedef struct AXFX_BUFFERUPDATE { s32* surround; // 0x08 } AXFX_BUFFERUPDATE; +typedef struct AXFX_BUS_DPL2 { + s32* left; // 0x00 + s32* right; // 0x04 + s32* left_surround; // 0x08 + s32* right_surround; // 0x0C +} AXFX_BUS_DPL2; + typedef struct AXFX_BUFFERUPDATE_DPL2 { s32* left; // 0x00 s32* right; // 0x04 diff --git a/libs/RVL_SDK/include/revolution/axfx/AXFXReverbHiExpDpl2.h b/libs/RVL_SDK/include/revolution/axfx/AXFXReverbHiExpDpl2.h index 6c9d7cb0..1b723fb7 100644 --- a/libs/RVL_SDK/include/revolution/axfx/AXFXReverbHiExpDpl2.h +++ b/libs/RVL_SDK/include/revolution/axfx/AXFXReverbHiExpDpl2.h @@ -49,13 +49,13 @@ typedef struct AXFX_REVERBHI_EXP_DPL2 { f32 crosstalk; // 0x15C f32 earlyGain; // 0x160 f32 fusedGain; // 0x164 - AXFX_BUS* busIn; // 0x168 - AXFX_BUS* busOut; // 0x16C + AXFX_BUS_DPL2* busIn; // 0x168 + AXFX_BUS_DPL2* busOut; // 0x16C f32 outGain; // 0x170 f32 sendGain; // 0x174 } AXFX_REVERBHI_EXP_DPL2; -u32 AXFXReverbHiExpGetMemSizeDpl2(const AXFX_REVERBHI_EXP_DPL2* fx); +u32 AXFXReverbHiExpGetMemSizeDpl2(AXFX_REVERBHI_EXP_DPL2* fx); BOOL AXFXReverbHiExpInitDpl2(AXFX_REVERBHI_EXP_DPL2* fx); void AXFXReverbHiExpShutdownDpl2(AXFX_REVERBHI_EXP_DPL2* fx); BOOL AXFXReverbHiExpSettingsDpl2(AXFX_REVERBHI_EXP_DPL2* fx); diff --git a/libs/RVL_SDK/include/revolution/axfx/AXFXReverbStdExp.h b/libs/RVL_SDK/include/revolution/axfx/AXFXReverbStdExp.h index 3d4bf8b4..5fa4c1fc 100644 --- a/libs/RVL_SDK/include/revolution/axfx/AXFXReverbStdExp.h +++ b/libs/RVL_SDK/include/revolution/axfx/AXFXReverbStdExp.h @@ -49,11 +49,11 @@ typedef struct AXFX_REVERBSTD_EXP { f32 sendGain; // 0xE4 } AXFX_REVERBSTD_EXP; -u32 AXFXReverbStdExpGetMemSize(const AXFX_REVERBSTD_EXP* fx); +u32 AXFXReverbStdExpGetMemSize(AXFX_REVERBSTD_EXP* fx); BOOL AXFXReverbStdExpInit(AXFX_REVERBSTD_EXP* fx); void AXFXReverbStdExpShutdown(AXFX_REVERBSTD_EXP* fx); BOOL AXFXReverbStdExpSettings(AXFX_REVERBSTD_EXP* fx); -void AXFXReverbStdExpCallback(void* chans, AXFX_REVERBSTD_EXP* context); +void AXFXReverbStdExpCallback(AXFX_BUS* update, AXFX_REVERBSTD_EXP* fx); #ifdef __cplusplus } diff --git a/libs/RVL_SDK/src/axfx/AXFXReverbHiExpDpl2.c b/libs/RVL_SDK/src/axfx/AXFXReverbHiExpDpl2.c new file mode 100644 index 00000000..6532e529 --- /dev/null +++ b/libs/RVL_SDK/src/axfx/AXFXReverbHiExpDpl2.c @@ -0,0 +1,461 @@ +#include +#include +#include +#include +#include + +#include +#include + +static BOOL __AllocDelayLine(AXFX_REVERBHI_EXP_DPL2* fx); +static void __BzeroDelayLines(AXFX_REVERBHI_EXP_DPL2* fx); +static void __FreeDelayLine(AXFX_REVERBHI_EXP_DPL2* fx); +static BOOL __InitParams(AXFX_REVERBHI_EXP_DPL2* fx); + +static u32 __EarlySizeTable[8][3] = {{157, 479, 829}, {317, 809, 1117}, {479, 941, 1487}, {641, 1259, 1949}, + {797, 1667, 2579}, {967, 1901, 2903}, {1123, 2179, 3413}, {1279, 2477, 3889}}; + +static f32 __EarlyCoefTable[8][3] = {{0.4f, -1.0f, 0.3f}, {0.5f, -0.95f, 0.3f}, {0.6f, -0.9f, 0.3f}, {0.75f, -0.85f, 0.3f}, + {-0.9f, 0.8f, 0.3f}, {-1.0f, 0.7f, 0.3f}, {-1.0f, 0.7f, 0.3f}, {-1.0f, 0.7f, 0.3f}}; + +static u32 __FilterSizeTable[7][9] = {{1789, 1999, 2333, 433, 149, 47, 73, 67, 71}, {149, 293, 449, 251, 103, 47, 73, 67, 71}, + {947, 1361, 1531, 433, 137, 47, 73, 67, 71}, {1279, 1531, 1973, 509, 149, 47, 73, 67, 71}, + {1531, 1847, 2297, 563, 179, 47, 73, 67, 71}, {1823, 2357, 2693, 571, 137, 47, 73, 67, 71}, + {1823, 2357, 2693, 571, 179, 47, 73, 67, 71}}; + +u32 AXFXReverbHiExpGetMemSizeDpl2(AXFX_REVERBHI_EXP_DPL2* fx) { + u32 sum = 0; + u32 i = 0; + + sum += __EarlySizeTable[7][2]; + sum += (int)(fx->preDelayTimeMax * 32000); + + for (i = 0; i < 5; i++) { + sum += __FilterSizeTable[6][i]; + } + + sum *= 4; + + for (i = 5; i < 9; i++) { + sum += __FilterSizeTable[6][i]; + } + + sum *= 4; + + return sum; +} + +BOOL AXFXReverbHiExpInitDpl2(AXFX_REVERBHI_EXP_DPL2* fx) { + u32 ch, i; + BOOL result = TRUE; + BOOL mask = OSDisableInterrupts(); + + if (AXGetMode() != AX_OUTPUT_DPL2) { + OSRestoreInterrupts(mask); + return FALSE; + } + + fx->active = 1; + + if (fx->preDelayTimeMax < 0.0f) { + AXFXReverbHiExpShutdownDpl2(fx); + OSRestoreInterrupts(mask); + return FALSE; + } + + fx->earlyMaxLength = __EarlySizeTable[8 - 1][2]; + fx->preDelayMaxLength = (u32)(fx->preDelayTimeMax * 32000); + + for (i = 0; i < 3; i++) { + fx->combMaxLength[i] = __FilterSizeTable[6][i]; + } + + for (i = 0; i < 2; i++) { + fx->allpassMaxLength[i] = __FilterSizeTable[6][3 + i]; + } + + for (ch = 0; ch < 4; ch++) { + fx->lastAllpassMaxLength[ch] = __FilterSizeTable[6][5 + ch]; + } + + result = __AllocDelayLine(fx); + if (result == FALSE) { + AXFXReverbHiExpShutdownDpl2(fx); + OSRestoreInterrupts(mask); + return FALSE; + } + + __BzeroDelayLines(fx); + result = __InitParams(fx); + if (result == FALSE) { + AXFXReverbHiExpShutdownDpl2(fx); + OSRestoreInterrupts(mask); + return FALSE; + } + + fx->active &= ~1; + OSRestoreInterrupts(mask); + return TRUE; +} + +BOOL AXFXReverbHiExpSettingsDpl2(AXFX_REVERBHI_EXP_DPL2* fx) { + BOOL mask = OSDisableInterrupts(); + fx->active = fx->active | 1; + AXFXReverbHiExpShutdownDpl2(fx); + + if (!AXFXReverbHiExpInitDpl2(fx)) { + AXFXReverbHiExpShutdownDpl2(fx); + OSRestoreInterrupts(mask); + return FALSE; + } else { + fx->active |= 2; + fx->active &= ~1; + OSRestoreInterrupts(mask); + return TRUE; + } + +} + +void AXFXReverbHiExpShutdownDpl2(AXFX_REVERBHI_EXP_DPL2* fx) { + BOOL mask = OSDisableInterrupts(); + fx->active |= 1; + __FreeDelayLine(fx); + OSRestoreInterrupts(mask); +} + +void AXFXReverbHiExpCallbackDpl2(AXFX_BUFFERUPDATE_DPL2* bufferUpdate, AXFX_REVERBHI_EXP_DPL2* fx) { + u32 ch, i; + u32 samp; + s32* input[4]; + f32 data; + f32 output[4]; + f32* earlyLine; + f32 earlyOut; + f32* preDelayLine; + f32 preDelayOut; + f32 filterOut; + f32* combLine; + f32 combOutOne; + f32* allpass; + f32 outTmp; + f32 allpassIn; + f32 allpassCoef; + f32 lpfOut; + f32 lpfCoef1; + f32 lpfCoef2; + f32 fusedOut[4]; + f32 fusedGain; + f32 crosstalkGain; + f32 crosstalkL; + f32 crosstalkR; + f32 crosstalkLs; + f32 crosstalkRs; + s32* inBusData[4]; + s32* outBusData[4]; + + if (fx->active != 0) { + fx->active &= ~2; + return; + } + + input[0] = bufferUpdate->left; + input[1] = bufferUpdate->right; + input[2] = bufferUpdate->left_surround; + input[3] = bufferUpdate->right_surround; + + if (fx->busIn != NULL) { + inBusData[0] = fx->busIn->left; + inBusData[1] = fx->busIn->right; + inBusData[2] = fx->busIn->left_surround; + inBusData[3] = fx->busIn->right_surround; + } + + if (fx->busOut != NULL) { + outBusData[0] = fx->busOut->left; + outBusData[1] = fx->busOut->right; + outBusData[2] = fx->busOut->left_surround; + outBusData[3] = fx->busOut->right_surround; + } + + lpfCoef1 = 1.0f - fx->lpfCoef; + lpfCoef2 = fx->lpfCoef; + allpassCoef = fx->allpassCoef; + fusedGain = fx->fusedGain * 0.6f; + crosstalkGain = fx->crosstalk * 0.333333f; + + for (samp = 0; samp < 96; samp++) { + for (ch = 0; ch < 4; ch++) { + if (fx->busIn != NULL) { + data = (f32)(*(input[ch]) + *(inBusData[ch]++)); + } else { + data = (f32)(*input[ch]); + } + + earlyLine = fx->earlyLine[ch]; + earlyOut = earlyLine[fx->earlyPos[0]] * fx->earlyCoef[0] + earlyLine[fx->earlyPos[1]] * fx->earlyCoef[1] + + earlyLine[fx->earlyPos[2]] * fx->earlyCoef[2]; + + earlyLine[fx->earlyPos[2]] = data; + + if (fx->preDelayLength != 0) { + preDelayLine = fx->preDelayLine[ch]; + preDelayOut = preDelayLine[fx->preDelayPos]; + preDelayLine[fx->preDelayPos] = data; + } else { + preDelayOut = data; + } + + filterOut = 0.0f; + for (i = 0; i < 3; i++) { + combLine = fx->combLine[ch][i]; + combOutOne = combLine[fx->combPos[i]]; + combLine[fx->combPos[i]] = preDelayOut + (combOutOne * fx->combCoef[i]); + filterOut += combOutOne; + } + + for (i = 0; i < 2; i++) { + allpass = fx->allpassLine[ch][i]; + outTmp = allpass[fx->allpassPos[i]]; + allpassIn = filterOut + outTmp * allpassCoef; + allpass[fx->allpassPos[i]] = allpassIn; + filterOut = outTmp - allpassIn * allpassCoef; + } + + lpfOut = lpfCoef1 * filterOut + lpfCoef2 * fx->lastLpfOut[ch]; + fx->lastLpfOut[ch] = lpfOut; + allpass = fx->lastAllpassLine[ch]; + outTmp = allpass[fx->lastAllpassPos[ch]]; + allpassIn = lpfOut + outTmp * allpassCoef; + allpass[fx->lastAllpassPos[ch]] = allpassIn; + fusedOut[ch] = outTmp - allpassIn * allpassCoef; + if (++fx->lastAllpassPos[ch] >= fx->lastAllpassLength[ch]) { + fx->lastAllpassPos[ch] = 0; + } + + fusedOut[ch] *= fusedGain; + fusedOut[ch] += earlyOut; + } + + crosstalkL = fusedOut[1] + fusedOut[2] + fusedOut[3]; + crosstalkR = fusedOut[0] + fusedOut[2] + fusedOut[3]; + crosstalkLs = fusedOut[0] + fusedOut[1] + fusedOut[3]; + crosstalkRs = fusedOut[0] + fusedOut[1] + fusedOut[2]; + + output[0] = fusedOut[0] + crosstalkL * crosstalkGain; + output[1] = fusedOut[1] + crosstalkR * crosstalkGain; + output[2] = fusedOut[2] + crosstalkLs * crosstalkGain; + output[3] = fusedOut[3] + crosstalkRs * crosstalkGain; + + *(input[0]++) = (s32)(output[0] * fx->outGain); + *(input[1]++) = (s32)(output[1] * fx->outGain); + *(input[2]++) = (s32)(output[2] * fx->outGain); + *(input[3]++) = (s32)(output[3] * fx->outGain); + + if (fx->busOut != NULL) { + *(outBusData[0]++) = (s32)(output[0] * fx->sendGain); + *(outBusData[1]++) = (s32)(output[1] * fx->sendGain); + *(outBusData[2]++) = (s32)(output[2] * fx->sendGain); + *(outBusData[3]++) = (s32)(output[3] * fx->sendGain); + } + + for (i = 0; i < 3; i++) { + if (++fx->earlyPos[i] >= fx->earlyLength) { + fx->earlyPos[i] = 0; + } + } + + if (fx->preDelayLength != 0) { + if (++fx->preDelayPos >= fx->preDelayLength) { + fx->preDelayPos = 0; + } + } + + for (i = 0; i < 3; i++) { + if (++fx->combPos[i] >= fx->combLength[i]) { + fx->combPos[i] = 0; + } + } + + for (i = 0; i < 2; i++) { + if (++fx->allpassPos[i] >= fx->allpassLength[i]) { + fx->allpassPos[i] = 0; + } + } + } +} + +static BOOL __AllocDelayLine(AXFX_REVERBHI_EXP_DPL2* fx) { + u32 ch, i; + + for (ch = 0; ch < 4; ch++) { + fx->earlyLine[ch] = (f32*)__AXFXAlloc(sizeof(f32) * fx->earlyMaxLength); + if (fx->earlyLine[ch] == NULL) + return FALSE; + + if (fx->preDelayMaxLength != 0) { + fx->preDelayLine[ch] = (f32*)__AXFXAlloc(sizeof(f32) * fx->preDelayMaxLength); + if (fx->preDelayLine[ch] == NULL) + return FALSE; + } else { + fx->preDelayLine[ch] = NULL; + } + + for (i = 0; i < 3; i++) { + fx->combLine[ch][i] = (f32*)__AXFXAlloc(sizeof(f32) * fx->combMaxLength[i]); + if (fx->combLine[ch][i] == NULL) + return FALSE; + } + + for (i = 0; i < 2; i++) { + fx->allpassLine[ch][i] = (f32*)__AXFXAlloc(sizeof(f32) * fx->allpassMaxLength[i]); + if (fx->allpassLine[ch][i] == NULL) + return FALSE; + } + + fx->lastAllpassLine[ch] = (f32*)__AXFXAlloc(sizeof(f32) * fx->lastAllpassMaxLength[ch]); + if (fx->lastAllpassLine[ch] == NULL) + return FALSE; + } + + return TRUE; +} + +static void __BzeroDelayLines(AXFX_REVERBHI_EXP_DPL2* fx) { + u32 ch, i; + + for (ch = 0; ch < 4; ch++) { + if (fx->earlyLine[ch] != NULL) { + memset(fx->earlyLine[ch], 0, sizeof(f32) * fx->earlyMaxLength); + } + + if (fx->preDelayLine[ch] != NULL) { + memset(fx->preDelayLine[ch], 0, sizeof(f32) * fx->preDelayMaxLength); + } + + for (i = 0; i < 3; i++) { + if (fx->combLine[ch][i] != NULL) { + memset(fx->combLine[ch][i], 0, sizeof(f32) * fx->combMaxLength[i]); + } + } + + for (i = 0; i < 2; i++) { + if (fx->allpassLine[ch][i] != NULL) { + memset(fx->allpassLine[ch][i], 0, sizeof(f32) * fx->allpassMaxLength[i]); + } + } + + if (fx->lastAllpassLine[ch] != NULL) { + memset(fx->lastAllpassLine[ch], 0, sizeof(f32) * fx->lastAllpassMaxLength[ch]); + } + } +} + +static void __FreeDelayLine(AXFX_REVERBHI_EXP_DPL2* fx) { + u32 ch, i; + + for (ch = 0; ch < 4; ch++) { + if (fx->earlyLine[ch] != NULL) { + __AXFXFree(fx->earlyLine[ch]); + fx->earlyLine[ch] = NULL; + } + + if (fx->preDelayLine[ch] != NULL) { + __AXFXFree(fx->preDelayLine[ch]); + fx->preDelayLine[ch] = NULL; + } + + for (i = 0; i < 3; i++) { + if (fx->combLine[ch][i] != NULL) { + __AXFXFree(fx->combLine[ch][i]); + fx->combLine[ch][i] = NULL; + } + } + + for (i = 0; i < 2; i++) { + if (fx->allpassLine[ch][i] != NULL) { + __AXFXFree(fx->allpassLine[ch][i]); + fx->allpassLine[ch][i] = NULL; + } + } + + if (fx->lastAllpassLine[ch] != NULL) { + __AXFXFree(fx->lastAllpassLine[ch]); + fx->lastAllpassLine[ch] = NULL; + } + } +} + +DECOMP_FORCE_LITERAL(AXFXReverbHiExpDpl2_c, -3.0f, 10.0); + +static BOOL __InitParams(AXFX_REVERBHI_EXP_DPL2* reverb) { + u32 ch, i; + + if (reverb->earlyMode >= 8) + return FALSE; + + if (reverb->preDelayTime < 0.0f || reverb->preDelayTime > reverb->preDelayTimeMax) + return FALSE; + + if (reverb->fusedMode >= 6) + return FALSE; + + if (reverb->fusedTime < 0.0f) + return FALSE; + + if (reverb->coloration < 0.0f || reverb->coloration > 1.0f) + return FALSE; + + if (reverb->damping < 0.0f || reverb->damping > 1.0f) + return FALSE; + + if (reverb->crosstalk < 0.0f || reverb->crosstalk > 1.0f) + return FALSE; + + if (reverb->earlyGain < 0.0f || reverb->earlyGain > 1.0f) + return FALSE; + + if (reverb->fusedGain < 0.0f || reverb->fusedGain > 1.0f) + return FALSE; + + if (reverb->outGain < 0.0f || reverb->outGain > 1.0f) + return FALSE; + + if (reverb->sendGain < 0.0f || reverb->sendGain > 1.0f) + return FALSE; + + reverb->earlyLength = __EarlySizeTable[reverb->earlyMode][2]; + for (i = 0; i < 3; i++) { + reverb->earlyPos[i] = reverb->earlyLength - __EarlySizeTable[reverb->earlyMode][i]; + reverb->earlyCoef[i] = __EarlyCoefTable[reverb->earlyMode][i] * reverb->earlyGain * 0.6f; + } + + reverb->preDelayPos = 0; + reverb->preDelayLength = (u32)(reverb->preDelayTime * (f32)32000); + + for (i = 0; i < 3; i++) { + reverb->combPos[i] = 0; + reverb->combLength[i] = __FilterSizeTable[reverb->fusedMode][i]; + reverb->combCoef[i] = pow(10.0f, (-3.0f * (f32)(reverb->combLength[i]) / (f32)(reverb->fusedTime * 32000))); + } + + for (i = 0; i < 2; i++) { + reverb->allpassPos[i] = 0; + reverb->allpassLength[i] = __FilterSizeTable[reverb->fusedMode][3 + i]; + } + + for (ch = 0; ch < 4; ch++) { + reverb->lastAllpassPos[ch] = 0; + reverb->lastAllpassLength[ch] = __FilterSizeTable[reverb->fusedMode][5 + ch]; + } + + reverb->allpassCoef = reverb->coloration; + reverb->lpfCoef = 1.0f - reverb->damping; + if (reverb->lpfCoef > 0.95f) + reverb->lpfCoef = 0.95f; + + for (ch = 0; ch < 4; ch++) { + reverb->lastLpfOut[ch] = 0.0f; + } + + return TRUE; +} diff --git a/libs/RVL_SDK/src/axfx/AXFXReverbStd.c b/libs/RVL_SDK/src/axfx/AXFXReverbStd.c index e7d5f86a..6b0b8975 100644 --- a/libs/RVL_SDK/src/axfx/AXFXReverbStd.c +++ b/libs/RVL_SDK/src/axfx/AXFXReverbStd.c @@ -23,7 +23,7 @@ BOOL AXFXReverbStdSettings(AXFX_REVERBSTD* fx) { } void AXFXReverbStdCallback(void* chans, void* context) { - AXFXReverbStdExpCallback((AXFX_BUFFERUPDATE*)chans, (AXFX_REVERBSTD_EXP*)context); + AXFXReverbStdExpCallback((AXFX_BUS*)chans, (AXFX_REVERBSTD_EXP*)context); } static void __ParamConvert(AXFX_REVERBSTD* fx) { diff --git a/libs/RVL_SDK/src/axfx/AXFXReverbStdExp.c b/libs/RVL_SDK/src/axfx/AXFXReverbStdExp.c new file mode 100644 index 00000000..c4875c42 --- /dev/null +++ b/libs/RVL_SDK/src/axfx/AXFXReverbStdExp.c @@ -0,0 +1,397 @@ +#include +#include +#include +#include +#include + +#include +#include + +static BOOL __AllocDelayLine(AXFX_REVERBSTD_EXP* fx); +static void __BzeroDelayLines(AXFX_REVERBSTD_EXP* fx); +static void __FreeDelayLine(AXFX_REVERBSTD_EXP* fx); +static BOOL __InitParams(AXFX_REVERBSTD_EXP* fx); + +static u32 __EarlySizeTable[8] = {163, 317, 479, 641, 797, 967, 1123, 1283}; + +static u32 __FilterSizeTable[7][4] = {{1789, 1999, 433, 149}, {149, 293, 251, 103}, {947, 1361, 433, 137}, + {1279, 1531, 509, 149}, {1531, 1847, 563, 179}, {1823, 2357, 571, 137}, + {1823, 2357, 571, 179}}; + +u32 AXFXReverbStdExpGetMemSize(AXFX_REVERBSTD_EXP* fx) { + u32 sum = 0; + u32 i = 0; + + sum += __EarlySizeTable[7]; + sum += (int)(fx->preDelayTimeMax * 32000); + + for (i = 0; i < 4; i++) { + sum += __FilterSizeTable[6][i]; + } + + sum *= 3; + sum *= 4; + + return sum; +} + +BOOL AXFXReverbStdExpInit(AXFX_REVERBSTD_EXP* fx) { + u32 ch, i; + BOOL result = TRUE; + BOOL mask = OSDisableInterrupts(); + + fx->active = 1; + + if (fx->preDelayTimeMax < 0.0f) { + AXFXReverbStdExpShutdown(fx); + OSRestoreInterrupts(mask); + return FALSE; + } + + fx->earlyMaxLength = __EarlySizeTable[8 - 1]; + fx->preDelayMaxLength = (u32)(fx->preDelayTimeMax * 32000); + + for (i = 0; i < 2; i++) { + fx->combMaxLength[i] = __FilterSizeTable[6][i]; + } + + for (i = 0; i < 2; i++) { + fx->allpassMaxLength[i] = __FilterSizeTable[6][2 + i]; + } + + result = __AllocDelayLine(fx); + if (result == FALSE) { + AXFXReverbStdExpShutdown(fx); + OSRestoreInterrupts(mask); + return FALSE; + } + + __BzeroDelayLines(fx); + result = __InitParams(fx); + if (result == FALSE) { + AXFXReverbStdExpShutdown(fx); + OSRestoreInterrupts(mask); + return FALSE; + } + + fx->active &= ~1; + OSRestoreInterrupts(mask); + return TRUE; +} + +BOOL AXFXReverbStdExpSettings(AXFX_REVERBSTD_EXP* fx) { + BOOL mask = OSDisableInterrupts(); + fx->active = fx->active | 1; + AXFXReverbStdExpShutdown(fx); + + if (!AXFXReverbStdExpInit(fx)) { + AXFXReverbStdExpShutdown(fx); + OSRestoreInterrupts(mask); + return FALSE; + } else { + fx->active |= 2; + fx->active &= ~1; + OSRestoreInterrupts(mask); + return TRUE; + } + +} + +void AXFXReverbStdExpShutdown(AXFX_REVERBSTD_EXP* fx) { + BOOL mask = OSDisableInterrupts(); + fx->active |= 1; + __FreeDelayLine(fx); + OSRestoreInterrupts(mask); +} + + +void AXFXReverbStdExpCallback(AXFX_BUS* bus, AXFX_REVERBSTD_EXP* reverb) { + u32 i, j; + + s32* busParam[AXFX_STEREO_CHANNEL_MAX]; + s32* busIn[AXFX_STEREO_CHANNEL_MAX]; + s32* busOut[AXFX_STEREO_CHANNEL_MAX]; + u32 earlyPos; + u32 preDelayPos; + u32 combPos0; + u32 combPos1; + u32 allpassPos0; + u32 allpassPos1; + f32 sp64; + f32 sp60; + f32* earlyLine; + f32 sp58; + f32 earlyCoef; + f32* preDelayLine; + f32 sp4C; + f32* combLine0; + f32* combLine1; + f32 sp40; + f32 sp3C; + f32 sp38; + f32 combCoef0; + f32 combCoef1; + f32 sp2C; + f32 sp28; + f32 sp24; + f32 sp20; + f32 allpassCoef; + f32 sp18; + f32 sp14; + f32 lpfCoef; + f32 spC; + f32 sp8; + f32* allpassLine; + + if (reverb->active != 0) { + reverb->active &= ~2; + return; + } + busParam[AX_STEREO_L] = bus->left; + busParam[AX_STEREO_R] = bus->right; + busParam[AX_STEREO_S] = bus->surround; + if (reverb->busIn) { + busIn[AX_STEREO_L] = reverb->busIn->left; + busIn[AX_STEREO_R] = reverb->busIn->right; + busIn[AX_STEREO_S] = reverb->busIn->surround; + } + if (reverb->busOut) { + busOut[AX_STEREO_L] = reverb->busOut->left; + busOut[AX_STEREO_R] = reverb->busOut->right; + busOut[AX_STEREO_S] = reverb->busOut->surround; + } + sp14 = 1.0f - reverb->lpfCoef; + lpfCoef = reverb->lpfCoef; + earlyCoef = reverb->earlyCoef; + combCoef0 = reverb->combCoef[0]; + combCoef1 = reverb->combCoef[1]; + allpassCoef = reverb->allpassCoef; + spC = 0.6f * reverb->earlyGain; + sp8 = 0.6f * reverb->fusedGain; + + for (i = 0; i < 96; i++) { + earlyPos = reverb->earlyPos; + preDelayPos = reverb->preDelayPos; + combPos0 = reverb->combPos[0]; + combPos1 = reverb->combPos[1]; + allpassPos0 = reverb->allpassPos[0]; + allpassPos1 = reverb->allpassPos[1]; + + for (j = 0; j < AXFX_STEREO_CHANNEL_MAX; j++) { + if (reverb->busIn) { + sp64 = *busParam[j] + *busIn[j]++; + } else { + sp64 = *busParam[j]; + } + earlyLine = reverb->earlyLine[j]; + sp58 = earlyLine[earlyPos]; + earlyLine[earlyPos] = sp64 + (sp58 * earlyCoef); + if (reverb->preDelayLength != 0) { + preDelayLine = reverb->preDelayLine[j]; + sp4C = preDelayLine[preDelayPos]; + preDelayLine[preDelayPos] = sp64; + } else { + sp4C = sp64; + } + combLine0 = reverb->combLine[j][0]; + sp40 = combLine0[combPos0]; + combLine0[combPos0] = sp4C + (sp40 * combCoef0); + combLine1 = reverb->combLine[j][1]; + sp3C = combLine1[combPos1]; + combLine1[combPos1] = sp4C + (sp3C * combCoef1); + sp38 = sp40 + sp3C; + allpassLine = reverb->allpassLine[j][0]; + sp2C = allpassLine[allpassPos0]; + sp28 = sp38 + (sp2C * allpassCoef); + allpassLine[allpassPos0] = sp28; + sp24 = sp2C - (sp28 * allpassCoef); + sp18 = (sp14 * sp24) + (lpfCoef * reverb->lastLpfOut[j]); + reverb->lastLpfOut[j] = sp18; + allpassLine = reverb->allpassLine[j][1]; + sp2C = allpassLine[allpassPos1]; + sp28 = sp18 + (sp2C * allpassCoef); + allpassLine[allpassPos1] = sp28; + sp20 = sp2C - (sp28 * allpassCoef); + sp60 = (sp58 * spC) + (sp20 * sp8); + *busParam[j]++ = (sp60 * reverb->outGain); + if (reverb->busOut) { + *busOut[j]++ = (sp60 * reverb->sendGain); + } + } + if (++reverb->earlyPos >= reverb->earlyLength) { + reverb->earlyPos = 0; + } + if (reverb->preDelayLength != 0) { + if (++reverb->preDelayPos >= reverb->preDelayLength) { + reverb->preDelayPos = 0; + } + } + if (++reverb->combPos[0] >= reverb->combLength[0]) { + reverb->combPos[0] = 0; + } + if (++reverb->combPos[1] >= reverb->combLength[1]) { + reverb->combPos[1] = 0; + } + if (++reverb->allpassPos[0] >= reverb->allpassLength[0]) { + reverb->allpassPos[0] = 0; + } + if (++reverb->allpassPos[1] >= reverb->allpassLength[1]) { + reverb->allpassPos[1] = 0; + } + } +} + +static BOOL __AllocDelayLine(AXFX_REVERBSTD_EXP* fx) { + u32 ch, i; + + for (ch = 0; ch < 3; ch++) { + fx->earlyLine[ch] = (f32*)__AXFXAlloc(sizeof(f32) * fx->earlyMaxLength); + if (fx->earlyLine[ch] == NULL) + return FALSE; + + if (fx->preDelayMaxLength) { + fx->preDelayLine[ch] = (f32*)__AXFXAlloc(sizeof(f32) * fx->preDelayMaxLength); + if (fx->preDelayLine[ch] == NULL) + return FALSE; + } else { + fx->preDelayLine[ch] = NULL; + } + + for (i = 0; i < 2; i++) { + fx->combLine[ch][i] = (f32*)__AXFXAlloc(sizeof(f32) * fx->combMaxLength[i]); + if (fx->combLine[ch][i] == NULL) + return FALSE; + } + + for (i = 0; i < 2; i++) { + fx->allpassLine[ch][i] = (f32*)__AXFXAlloc(sizeof(f32) * fx->allpassMaxLength[i]); + if (fx->allpassLine[ch][i] == NULL) + return FALSE; + } + } + + return TRUE; +} + +static void __BzeroDelayLines(AXFX_REVERBSTD_EXP* fx) { + u32 ch, i; + + for (ch = 0; ch < 3; ch++) { + if (fx->earlyLine[ch]) + memset(fx->earlyLine[ch], 0, sizeof(f32) * fx->earlyMaxLength); + + if (fx->preDelayLine[ch]) + memset(fx->preDelayLine[ch], 0, sizeof(f32) * fx->preDelayMaxLength); + + for (i = 0; i < 2; i++) { + if (fx->combLine[ch][i]) + memset(fx->combLine[ch][i], 0, sizeof(f32) * fx->combMaxLength[i]); + } + + for (i = 0; i < 2; i++) { + if (fx->allpassLine[ch][i]) + memset(fx->allpassLine[ch][i], 0, sizeof(f32) * fx->allpassMaxLength[i]); + } + } +} + +static void __FreeDelayLine(AXFX_REVERBSTD_EXP* fx) { + u32 ch, i; + + for (ch = 0; ch < 3; ch++) { + if (fx->earlyLine[ch]) { + __AXFXFree(fx->earlyLine[ch]); + fx->earlyLine[ch] = NULL; + } + + if (fx->preDelayLine[ch]) { + __AXFXFree(fx->preDelayLine[ch]); + fx->preDelayLine[ch] = NULL; + } + + for (i = 0; i < 2; i++) { + if (fx->combLine[ch][i]) { + __AXFXFree(fx->combLine[ch][i]); + fx->combLine[ch][i] = NULL; + } + } + + for (i = 0; i < 2; i++) { + if (fx->allpassLine[ch][i]) { + __AXFXFree(fx->allpassLine[ch][i]); + fx->allpassLine[ch][i] = NULL; + } + } + } +} + + +static BOOL __InitParams(AXFX_REVERBSTD_EXP* fx) { + u32 i; + + if (fx->earlyMode >= 8) + return FALSE; + + if (fx->preDelayTime < 0.0f || fx->preDelayTime > fx->preDelayTimeMax) + return FALSE; + + if (fx->fusedMode >= 6) + return FALSE; + + if (fx->fusedTime < 0.0f) + return FALSE; + + if (fx->coloration < 0.0f || fx->coloration > 1.0f) + return FALSE; + + if (fx->damping < 0.0f || fx->damping > 1.0f) + return FALSE; + + if (fx->earlyGain < 0.0f || fx->earlyGain > 1.0f) + return FALSE; + + if (fx->fusedGain < 0.0f || fx->fusedGain > 1.0f) + return FALSE; + + if (fx->outGain < 0.0f || fx->outGain > 1.0f) + return FALSE; + + if (fx->sendGain < 0.0f || fx->sendGain > 1.0f) + return FALSE; + + fx->earlyPos = 0; + fx->earlyLength = __EarlySizeTable[fx->earlyMode]; + if (fx->earlyMode <= 3) { + fx->earlyCoef = -0.33f; + } else { + fx->earlyCoef = 0.33f; + } + + fx->preDelayPos = 0; + fx->preDelayLength = (u32)(fx->preDelayTime * 32000); + + for (i = 0; i < 2; i++) { + f32 t; + fx->combPos[i] = 0; + fx->combLength[i] = __FilterSizeTable[fx->fusedMode][i]; + t = -3.0f * (f32)(fx->combLength[i]) / (f32)(fx->fusedTime * 32000); + fx->combCoef[i] = pow(10.0f, t); + } + + fx->allpassPos[0] = 0; + fx->allpassLength[0] = __FilterSizeTable[fx->fusedMode][2]; + fx->allpassPos[1] = 0; + fx->allpassLength[1] = __FilterSizeTable[fx->fusedMode][3]; + + fx->allpassCoef = fx->coloration; + fx->lpfCoef = 1.0f - fx->damping; + if (fx->lpfCoef > 0.95f) { + fx->lpfCoef = 0.95f; + } + + fx->lastLpfOut[0] = 0.0f; + fx->lastLpfOut[1] = 0.0f; + fx->lastLpfOut[2] = 0.0f; + + return TRUE; +} -- 2.49.1