줄바꿈을 LF로 통일
서버에서 바로 빌드하고 고칠 수 있게 저장소 줄바꿈을 LF로 맞췄습니다. CRLF로 들어가 있던 sh 빌드 스크립트도 이제 리눅스에서 그대로 돌아갑니다. 내용은 바뀌지 않았습니다.
This commit is contained in:
1 parent
40615838ac
commit
2d48091205
623 files changed
+501372
-501365
No files matched your search
+4731
-4731
File diff suppressed because it is too large.
Load diff
+140
-140
@@ -1,140 +1,140 @@
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const EN_MESSAGES={
|
||||
"복원 파일 검증에 실패했습니다. 다시 불러오세요.": "Restore file verification failed. Load it again.",
|
||||
"서버 요청에 실패했습니다.": "Server request failed.",
|
||||
"오프라인 실행: PC에만 저장합니다.": "Offline mode: saved to this PC only.",
|
||||
"서버 보유 기종을 확인하고 있습니다…": "Checking stored device editions…",
|
||||
"기종별 자동 보관이 꺼져 있습니다.": "Automatic edition backups are disabled.",
|
||||
"기종을 확인하지 못해 서버에는 보관하지 않았습니다. PC 파일을 보관하세요.": "Unknown edition. No server copy was stored. Keep your PC copy.",
|
||||
"같은 기종의 백업이 보관되어 있습니다.": "A backup for this edition is already stored.",
|
||||
"미확보 기종입니다. 서버에 비공개 백업을 먼저 저장하고 있습니다…": "Saving a private backup for this new edition…",
|
||||
"서버 백업 확인값이 일치하지 않습니다.": "Server backup checksum does not match.",
|
||||
" 비공개 백업 완료.": " private backup saved.",
|
||||
"서버 백업 실패: ": "Server backup failed: ",
|
||||
" 기종별 보관을 건너뜁니다.": " Edition backup skipped.",
|
||||
"내 보관함에도 저장하고 있습니다…": "Saving to My backups…",
|
||||
"개인 백업 확인값이 일치하지 않습니다.": "Private backup checksum does not match.",
|
||||
"내 보관함에 같은 파일이 이미 있습니다.": "This file is already in My backups.",
|
||||
"내 보관함 저장 완료.": "Saved to My backups.",
|
||||
" PC에도 다운로드합니다.": " Downloading a copy to your PC.",
|
||||
"\n개인 보관함 저장 확인 실패: ": "\nPrivate backup verification failed: ",
|
||||
" 개인 보관함 저장을 건너뜁니다.": " Private backup skipped.",
|
||||
"서버 우선 백업은 홈페이지에서 사용할 수 있습니다. 관리자 설정에 따라 홈페이지에서 다시 시도하세요.": "Server-first backup requires the website. Try again online using the configured backup policy.",
|
||||
"백업 방식을 확인하고 있습니다…": "Checking the backup policy…",
|
||||
"관리자 설정에 따라 PC에 저장합니다.": "Saving to this PC according to the backup policy.",
|
||||
"서버에 비공개로 저장하고 있습니다…": "Saving privately to the server…",
|
||||
"서버에서 백업을 내려받아 검증하고 있습니다…": "Downloading and verifying the server backup…",
|
||||
"서버 백업 다운로드에 실패했습니다. 브라우저의 쿠키 설정을 확인하세요.": "Could not download the server backup. Check your browser cookie settings.",
|
||||
"다운로드한 서버 백업의 검증에 실패했습니다.": "Downloaded server backup failed verification.",
|
||||
"서버 저장과 파일 검증을 완료했습니다. 다운로드할 수 있습니다. 임시 보관 기간은 ": "Server backup verified and ready to download. Temporary retention: ",
|
||||
"시간입니다.": " hours.",
|
||||
"서버 백업을 완료하지 못했습니다. ": "Server backup could not be completed. ",
|
||||
" 읽은 데이터는 현재 탭에 유지됩니다. 탭을 닫지 말고 서버 저장 재시도를 눌러 주세요.": " The read data remains in this tab. Keep the tab open and select Retry server backup.",
|
||||
"재시도할 백업이 없습니다.": "No backup to retry.",
|
||||
"백업 주소가 잘못되었습니다.": "Invalid backup address.",
|
||||
"내 보관함에 로그인한 뒤 파일을 다시 여세요.": "Log in to My backups and open the file again.",
|
||||
"내 보관함에서 해당 파일을 찾지 못했습니다.": "File not found in My backups.",
|
||||
"개인 백업을 불러오지 못했습니다.": "Could not load the private backup."
|
||||
};
|
||||
function message(text){return typeof document !== 'undefined' && document.documentElement.lang !== 'ko' ? (EN_MESSAGES[text] || text) : text;}
|
||||
|
||||
const C = [0, 0x70169E2C, 0x70169E2C, 0x70169E2C, 0x849633DB, 0x96CB83B8, 0x96CB83B8];
|
||||
const PAGES = [[0xD29000, [5, 6]], [0xD49000, [1, 2, 3, 4]], [0xEFD000, [1, 2, 3, 4, 5, 6]]];
|
||||
const u32 = (b, i) => new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(i, true);
|
||||
function pageEdition(b, ids) {
|
||||
if (b.length !== 4096) return 0;
|
||||
const id = u32(b, 0), tail = u32(b, 0xFF8);
|
||||
return ids.includes(id) && ((tail + id) >>> 0) === C[id] && u32(b, 0xFFC) === (~tail >>> 0) ? id : 0;
|
||||
}
|
||||
function edition(img) {
|
||||
if (img.length !== 0x1000000) return 0;
|
||||
for (const [off, ids] of PAGES) { const id = pageEdition(img.subarray(off, off + 4096), ids); if (id) return id; }
|
||||
return 0;
|
||||
}
|
||||
async function deviceEdition(dev) {
|
||||
for (const [off, ids] of PAGES) { const id = pageEdition(await dev.read(off, 4096), ids); if (id) return id; }
|
||||
return 0;
|
||||
}
|
||||
async function digest(img) {
|
||||
return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', img)), b => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
async function verify(img, item) {
|
||||
if (img.length !== 0x1000000 || img.length !== item.size || String.fromCharCode(...img.subarray(0, 8)) !== 'SONIXDEV' || edition(img) !== item.edition || await digest(img) !== item.sha256) throw new Error(message('복원 파일 검증에 실패했습니다. 다시 불러오세요.'));
|
||||
return img;
|
||||
}
|
||||
async function request(path, options = {}) {
|
||||
const r = await fetch(path, {cache: 'no-store', ...options, signal: AbortSignal.timeout(90000)});
|
||||
const result = await r.json();
|
||||
if (!r.ok) throw new Error(result.error || message('서버 요청에 실패했습니다.'));
|
||||
return result;
|
||||
}
|
||||
async function sharedBackup(img, report) {
|
||||
if (location.protocol === 'file:') return message('오프라인 실행: PC에만 저장합니다.');
|
||||
try {
|
||||
report(message('서버 보유 기종을 확인하고 있습니다…'));
|
||||
const state = await request('/api/backup-status');
|
||||
if (!state.enabled) return message('기종별 자동 보관이 꺼져 있습니다.');
|
||||
const id = edition(img);
|
||||
if (!id) return message('기종을 확인하지 못해 서버에는 보관하지 않았습니다. PC 파일을 보관하세요.');
|
||||
if (state.held.includes(id)) return message('같은 기종의 백업이 보관되어 있습니다.');
|
||||
report(message('미확보 기종입니다. 서버에 비공개 백업을 먼저 저장하고 있습니다…'));
|
||||
const result = await request('/api/backups', {method: 'POST', headers: {'Content-Type': 'application/octet-stream', 'X-Backup-Notice': 'shown'}, body: img});
|
||||
if (result.status === 'stored') {
|
||||
if (result.sha256 !== await digest(img)) throw new Error(message('서버 백업 확인값이 일치하지 않습니다.'));
|
||||
return result.name + message(' 비공개 백업 완료.');
|
||||
}
|
||||
return result.status === 'already-held' ? message('같은 기종의 백업이 보관되어 있습니다.') : message('기종별 자동 보관이 꺼져 있습니다.');
|
||||
} catch (error) { return message('서버 백업 실패: ') + error.message + message(' 기종별 보관을 건너뜁니다.'); }
|
||||
}
|
||||
async function backup(img, report) {
|
||||
const shared = await sharedBackup(img, report);
|
||||
if (location.protocol === 'file:') return shared;
|
||||
try {
|
||||
const me = await request('/api/member/me');
|
||||
if (!me.authenticated) return shared;
|
||||
report(message('내 보관함에도 저장하고 있습니다…'));
|
||||
const result = await request('/api/member/files', {method:'POST', headers:{'Content-Type':'application/octet-stream'}, body:img});
|
||||
if (result.sha256 !== await digest(img)) throw new Error(message('개인 백업 확인값이 일치하지 않습니다.'));
|
||||
return shared + '\n' + (result.status === 'duplicate' ? message('내 보관함에 같은 파일이 이미 있습니다.') : message('내 보관함 저장 완료.')) + message(' PC에도 다운로드합니다.');
|
||||
} catch (error) { return shared + message('\n개인 보관함 저장 확인 실패: ') + error.message + message(' 개인 보관함 저장을 건너뜁니다.'); }
|
||||
}
|
||||
// A failed transfer retains the complete dump in this tab for a user-initiated retry.
|
||||
let pending=null;
|
||||
async function deviceBackup(img, report, kind='rom') {
|
||||
if(location.protocol==='file:')throw Error(message('서버 우선 백업은 홈페이지에서 사용할 수 있습니다. 관리자 설정에 따라 홈페이지에서 다시 시도하세요.'));
|
||||
report(message('백업 방식을 확인하고 있습니다…'));
|
||||
const policy=await request('/api/backup-status');
|
||||
if(policy.mode==='local')return {img,message:kind==='rom'?await backup(img,report):message('관리자 설정에 따라 PC에 저장합니다.')};
|
||||
report(message('서버에 비공개로 저장하고 있습니다…'));
|
||||
const result=await request('/api/device-backups',{method:'POST',headers:{'Content-Type':'application/octet-stream','X-Backup-Kind':kind},body:img});
|
||||
const sha=await digest(img);
|
||||
if(result.sha256!==sha || result.size!==img.length || !/^\/api\/device-backups\/[a-f0-9]{32}$/.test(result.fileUrl))throw Error(message('서버 백업 확인값이 일치하지 않습니다.'));
|
||||
report(message('서버에서 백업을 내려받아 검증하고 있습니다…'));
|
||||
const response=await fetch(result.fileUrl,{cache:'no-store',signal:AbortSignal.timeout(90000)});
|
||||
if(!response.ok)throw Error(message('서버 백업 다운로드에 실패했습니다. 브라우저의 쿠키 설정을 확인하세요.'));
|
||||
const saved=new Uint8Array(await response.arrayBuffer());
|
||||
if(saved.length!==img.length || await digest(saved)!==sha)throw Error(message('다운로드한 서버 백업의 검증에 실패했습니다.'));
|
||||
if(kind==='rom')await backup(saved,report);
|
||||
return {img:saved,message:message('서버 저장과 파일 검증을 완료했습니다. 다운로드할 수 있습니다. 임시 보관 기간은 ')+policy.retentionHours+message('시간입니다.')};
|
||||
}
|
||||
async function deliver(img,name,download,report,kind='rom') {
|
||||
pending={img,name,download,report,kind};
|
||||
try{const result=await deviceBackup(img,report,kind);download(result.img,name);report(result.message);pending=null;return result.img;}
|
||||
catch(e){report(message('서버 백업을 완료하지 못했습니다. ')+e.message+message(' 읽은 데이터는 현재 탭에 유지됩니다. 탭을 닫지 말고 서버 저장 재시도를 눌러 주세요.'));throw e;}
|
||||
}
|
||||
async function retry(){if(!pending)throw Error(message('재시도할 백업이 없습니다.'));const p=pending;return deliver(p.img,p.name,p.download,p.report,p.kind);}
|
||||
async function memberFile(id) {
|
||||
if (!/^[a-f0-9]{32}$/.test(id)) throw new Error(message('백업 주소가 잘못되었습니다.'));
|
||||
const me = await request('/api/member/me');
|
||||
if (!me.authenticated) throw new Error(message('내 보관함에 로그인한 뒤 파일을 다시 여세요.'));
|
||||
const item = me.items.find(x => x.id === id);
|
||||
if (!item) throw new Error(message('내 보관함에서 해당 파일을 찾지 못했습니다.'));
|
||||
const response = await fetch(item.fileUrl, {cache:'no-store', signal:AbortSignal.timeout(90000)});
|
||||
if (!response.ok) throw new Error(message('개인 백업을 불러오지 못했습니다.'));
|
||||
const img = new Uint8Array(await response.arrayBuffer());
|
||||
await verify(img, item);
|
||||
return {img, item};
|
||||
}
|
||||
root.TamaArchive = {edition, deviceEdition, digest, verify, request, backup, deviceBackup, deliver, retry, hasPending:()=>!!pending, memberFile};
|
||||
})(window);
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const EN_MESSAGES={
|
||||
"복원 파일 검증에 실패했습니다. 다시 불러오세요.": "Restore file verification failed. Load it again.",
|
||||
"서버 요청에 실패했습니다.": "Server request failed.",
|
||||
"오프라인 실행: PC에만 저장합니다.": "Offline mode: saved to this PC only.",
|
||||
"서버 보유 기종을 확인하고 있습니다…": "Checking stored device editions…",
|
||||
"기종별 자동 보관이 꺼져 있습니다.": "Automatic edition backups are disabled.",
|
||||
"기종을 확인하지 못해 서버에는 보관하지 않았습니다. PC 파일을 보관하세요.": "Unknown edition. No server copy was stored. Keep your PC copy.",
|
||||
"같은 기종의 백업이 보관되어 있습니다.": "A backup for this edition is already stored.",
|
||||
"미확보 기종입니다. 서버에 비공개 백업을 먼저 저장하고 있습니다…": "Saving a private backup for this new edition…",
|
||||
"서버 백업 확인값이 일치하지 않습니다.": "Server backup checksum does not match.",
|
||||
" 비공개 백업 완료.": " private backup saved.",
|
||||
"서버 백업 실패: ": "Server backup failed: ",
|
||||
" 기종별 보관을 건너뜁니다.": " Edition backup skipped.",
|
||||
"내 보관함에도 저장하고 있습니다…": "Saving to My backups…",
|
||||
"개인 백업 확인값이 일치하지 않습니다.": "Private backup checksum does not match.",
|
||||
"내 보관함에 같은 파일이 이미 있습니다.": "This file is already in My backups.",
|
||||
"내 보관함 저장 완료.": "Saved to My backups.",
|
||||
" PC에도 다운로드합니다.": " Downloading a copy to your PC.",
|
||||
"\n개인 보관함 저장 확인 실패: ": "\nPrivate backup verification failed: ",
|
||||
" 개인 보관함 저장을 건너뜁니다.": " Private backup skipped.",
|
||||
"서버 우선 백업은 홈페이지에서 사용할 수 있습니다. 관리자 설정에 따라 홈페이지에서 다시 시도하세요.": "Server-first backup requires the website. Try again online using the configured backup policy.",
|
||||
"백업 방식을 확인하고 있습니다…": "Checking the backup policy…",
|
||||
"관리자 설정에 따라 PC에 저장합니다.": "Saving to this PC according to the backup policy.",
|
||||
"서버에 비공개로 저장하고 있습니다…": "Saving privately to the server…",
|
||||
"서버에서 백업을 내려받아 검증하고 있습니다…": "Downloading and verifying the server backup…",
|
||||
"서버 백업 다운로드에 실패했습니다. 브라우저의 쿠키 설정을 확인하세요.": "Could not download the server backup. Check your browser cookie settings.",
|
||||
"다운로드한 서버 백업의 검증에 실패했습니다.": "Downloaded server backup failed verification.",
|
||||
"서버 저장과 파일 검증을 완료했습니다. 다운로드할 수 있습니다. 임시 보관 기간은 ": "Server backup verified and ready to download. Temporary retention: ",
|
||||
"시간입니다.": " hours.",
|
||||
"서버 백업을 완료하지 못했습니다. ": "Server backup could not be completed. ",
|
||||
" 읽은 데이터는 현재 탭에 유지됩니다. 탭을 닫지 말고 서버 저장 재시도를 눌러 주세요.": " The read data remains in this tab. Keep the tab open and select Retry server backup.",
|
||||
"재시도할 백업이 없습니다.": "No backup to retry.",
|
||||
"백업 주소가 잘못되었습니다.": "Invalid backup address.",
|
||||
"내 보관함에 로그인한 뒤 파일을 다시 여세요.": "Log in to My backups and open the file again.",
|
||||
"내 보관함에서 해당 파일을 찾지 못했습니다.": "File not found in My backups.",
|
||||
"개인 백업을 불러오지 못했습니다.": "Could not load the private backup."
|
||||
};
|
||||
function message(text){return typeof document !== 'undefined' && document.documentElement.lang !== 'ko' ? (EN_MESSAGES[text] || text) : text;}
|
||||
|
||||
const C = [0, 0x70169E2C, 0x70169E2C, 0x70169E2C, 0x849633DB, 0x96CB83B8, 0x96CB83B8];
|
||||
const PAGES = [[0xD29000, [5, 6]], [0xD49000, [1, 2, 3, 4]], [0xEFD000, [1, 2, 3, 4, 5, 6]]];
|
||||
const u32 = (b, i) => new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(i, true);
|
||||
function pageEdition(b, ids) {
|
||||
if (b.length !== 4096) return 0;
|
||||
const id = u32(b, 0), tail = u32(b, 0xFF8);
|
||||
return ids.includes(id) && ((tail + id) >>> 0) === C[id] && u32(b, 0xFFC) === (~tail >>> 0) ? id : 0;
|
||||
}
|
||||
function edition(img) {
|
||||
if (img.length !== 0x1000000) return 0;
|
||||
for (const [off, ids] of PAGES) { const id = pageEdition(img.subarray(off, off + 4096), ids); if (id) return id; }
|
||||
return 0;
|
||||
}
|
||||
async function deviceEdition(dev) {
|
||||
for (const [off, ids] of PAGES) { const id = pageEdition(await dev.read(off, 4096), ids); if (id) return id; }
|
||||
return 0;
|
||||
}
|
||||
async function digest(img) {
|
||||
return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', img)), b => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
async function verify(img, item) {
|
||||
if (img.length !== 0x1000000 || img.length !== item.size || String.fromCharCode(...img.subarray(0, 8)) !== 'SONIXDEV' || edition(img) !== item.edition || await digest(img) !== item.sha256) throw new Error(message('복원 파일 검증에 실패했습니다. 다시 불러오세요.'));
|
||||
return img;
|
||||
}
|
||||
async function request(path, options = {}) {
|
||||
const r = await fetch(path, {cache: 'no-store', ...options, signal: AbortSignal.timeout(90000)});
|
||||
const result = await r.json();
|
||||
if (!r.ok) throw new Error(result.error || message('서버 요청에 실패했습니다.'));
|
||||
return result;
|
||||
}
|
||||
async function sharedBackup(img, report) {
|
||||
if (location.protocol === 'file:') return message('오프라인 실행: PC에만 저장합니다.');
|
||||
try {
|
||||
report(message('서버 보유 기종을 확인하고 있습니다…'));
|
||||
const state = await request('/api/backup-status');
|
||||
if (!state.enabled) return message('기종별 자동 보관이 꺼져 있습니다.');
|
||||
const id = edition(img);
|
||||
if (!id) return message('기종을 확인하지 못해 서버에는 보관하지 않았습니다. PC 파일을 보관하세요.');
|
||||
if (state.held.includes(id)) return message('같은 기종의 백업이 보관되어 있습니다.');
|
||||
report(message('미확보 기종입니다. 서버에 비공개 백업을 먼저 저장하고 있습니다…'));
|
||||
const result = await request('/api/backups', {method: 'POST', headers: {'Content-Type': 'application/octet-stream', 'X-Backup-Notice': 'shown'}, body: img});
|
||||
if (result.status === 'stored') {
|
||||
if (result.sha256 !== await digest(img)) throw new Error(message('서버 백업 확인값이 일치하지 않습니다.'));
|
||||
return result.name + message(' 비공개 백업 완료.');
|
||||
}
|
||||
return result.status === 'already-held' ? message('같은 기종의 백업이 보관되어 있습니다.') : message('기종별 자동 보관이 꺼져 있습니다.');
|
||||
} catch (error) { return message('서버 백업 실패: ') + error.message + message(' 기종별 보관을 건너뜁니다.'); }
|
||||
}
|
||||
async function backup(img, report) {
|
||||
const shared = await sharedBackup(img, report);
|
||||
if (location.protocol === 'file:') return shared;
|
||||
try {
|
||||
const me = await request('/api/member/me');
|
||||
if (!me.authenticated) return shared;
|
||||
report(message('내 보관함에도 저장하고 있습니다…'));
|
||||
const result = await request('/api/member/files', {method:'POST', headers:{'Content-Type':'application/octet-stream'}, body:img});
|
||||
if (result.sha256 !== await digest(img)) throw new Error(message('개인 백업 확인값이 일치하지 않습니다.'));
|
||||
return shared + '\n' + (result.status === 'duplicate' ? message('내 보관함에 같은 파일이 이미 있습니다.') : message('내 보관함 저장 완료.')) + message(' PC에도 다운로드합니다.');
|
||||
} catch (error) { return shared + message('\n개인 보관함 저장 확인 실패: ') + error.message + message(' 개인 보관함 저장을 건너뜁니다.'); }
|
||||
}
|
||||
// A failed transfer retains the complete dump in this tab for a user-initiated retry.
|
||||
let pending=null;
|
||||
async function deviceBackup(img, report, kind='rom') {
|
||||
if(location.protocol==='file:')throw Error(message('서버 우선 백업은 홈페이지에서 사용할 수 있습니다. 관리자 설정에 따라 홈페이지에서 다시 시도하세요.'));
|
||||
report(message('백업 방식을 확인하고 있습니다…'));
|
||||
const policy=await request('/api/backup-status');
|
||||
if(policy.mode==='local')return {img,message:kind==='rom'?await backup(img,report):message('관리자 설정에 따라 PC에 저장합니다.')};
|
||||
report(message('서버에 비공개로 저장하고 있습니다…'));
|
||||
const result=await request('/api/device-backups',{method:'POST',headers:{'Content-Type':'application/octet-stream','X-Backup-Kind':kind},body:img});
|
||||
const sha=await digest(img);
|
||||
if(result.sha256!==sha || result.size!==img.length || !/^\/api\/device-backups\/[a-f0-9]{32}$/.test(result.fileUrl))throw Error(message('서버 백업 확인값이 일치하지 않습니다.'));
|
||||
report(message('서버에서 백업을 내려받아 검증하고 있습니다…'));
|
||||
const response=await fetch(result.fileUrl,{cache:'no-store',signal:AbortSignal.timeout(90000)});
|
||||
if(!response.ok)throw Error(message('서버 백업 다운로드에 실패했습니다. 브라우저의 쿠키 설정을 확인하세요.'));
|
||||
const saved=new Uint8Array(await response.arrayBuffer());
|
||||
if(saved.length!==img.length || await digest(saved)!==sha)throw Error(message('다운로드한 서버 백업의 검증에 실패했습니다.'));
|
||||
if(kind==='rom')await backup(saved,report);
|
||||
return {img:saved,message:message('서버 저장과 파일 검증을 완료했습니다. 다운로드할 수 있습니다. 임시 보관 기간은 ')+policy.retentionHours+message('시간입니다.')};
|
||||
}
|
||||
async function deliver(img,name,download,report,kind='rom') {
|
||||
pending={img,name,download,report,kind};
|
||||
try{const result=await deviceBackup(img,report,kind);download(result.img,name);report(result.message);pending=null;return result.img;}
|
||||
catch(e){report(message('서버 백업을 완료하지 못했습니다. ')+e.message+message(' 읽은 데이터는 현재 탭에 유지됩니다. 탭을 닫지 말고 서버 저장 재시도를 눌러 주세요.'));throw e;}
|
||||
}
|
||||
async function retry(){if(!pending)throw Error(message('재시도할 백업이 없습니다.'));const p=pending;return deliver(p.img,p.name,p.download,p.report,p.kind);}
|
||||
async function memberFile(id) {
|
||||
if (!/^[a-f0-9]{32}$/.test(id)) throw new Error(message('백업 주소가 잘못되었습니다.'));
|
||||
const me = await request('/api/member/me');
|
||||
if (!me.authenticated) throw new Error(message('내 보관함에 로그인한 뒤 파일을 다시 여세요.'));
|
||||
const item = me.items.find(x => x.id === id);
|
||||
if (!item) throw new Error(message('내 보관함에서 해당 파일을 찾지 못했습니다.'));
|
||||
const response = await fetch(item.fileUrl, {cache:'no-store', signal:AbortSignal.timeout(90000)});
|
||||
if (!response.ok) throw new Error(message('개인 백업을 불러오지 못했습니다.'));
|
||||
const img = new Uint8Array(await response.arrayBuffer());
|
||||
await verify(img, item);
|
||||
return {img, item};
|
||||
}
|
||||
root.TamaArchive = {edition, deviceEdition, digest, verify, request, backup, deviceBackup, deliver, retry, hasPending:()=>!!pending, memberFile};
|
||||
})(window);
|
||||
+1360
-1360
File diff suppressed because it is too large.
Load diff
+536
-536
File diff suppressed because it is too large.
Load diff
+2276
-2276
File diff suppressed because it is too large.
Load diff
+86
-86
@@ -1,86 +1,86 @@
|
||||
const MSG_KO = [
|
||||
[/^no ARC2 archive at (\S+)$/, '$1에 ARC2 아카이브가 없습니다'],
|
||||
[/^unknown bpp (\S+)$/, '알 수 없는 색상 깊이: $1'],
|
||||
[/^subimage count does not match$/, '부분 이미지 개수가 다릅니다'],
|
||||
[/^subimage size does not match$/, '부분 이미지 크기가 다릅니다'],
|
||||
[/^eye image too detailed: (\d+) bytes, at most (\d+) allowed$/, '눈 이미지가 너무 큽니다: $1바이트, 최대 $2바이트'],
|
||||
[/^not a Paradise flash dump \(SONIXDEV header missing\)$/, '파라다이스 덤프가 아닙니다(SONIXDEV 헤더 없음)'],
|
||||
[/^unexpected asset archive \((\d+) files\)$/, '예상하지 못한 자료 구성(파일 $1개)'],
|
||||
[/^too big: assets would end at (\S+), free space ends at (\S+)$/, '데이터가 $1까지 필요하지만 여유 공간은 $2까지입니다'],
|
||||
[/^checksum wrong at (\S+)$/, '$1 체크섬 오류'],
|
||||
[/^(?:character )?sheet must be (\S+) px, got (\S+)$/, '시트 크기는 $1px여야 합니다(현재 $2)'],
|
||||
[/^no sprite package$/, '이미지 패키지가 없습니다'],
|
||||
[/^not a ZIP file$/, 'ZIP 파일이 아닙니다'],
|
||||
[/^unsupported ZIP compression in (.+)$/, '$1: 지원하지 않는 ZIP 압축 방식'],
|
||||
[/^firmware not recognised \(expected a 4 MB or 8 MB image of a colour Tamagotchi\)$/, '컬러 다마고치의 4 MB 또는 8 MB 펌웨어가 필요합니다'],
|
||||
[/^scene table not found$/, '장면 표를 찾지 못했습니다'],
|
||||
[/^firmware too big: (\d+) blocks$/, '펌웨어가 너무 큽니다: $1블록'],
|
||||
[/^no room for the spare pages$/, '여분 페이지를 넣을 공간이 없습니다'],
|
||||
[/^launcher template does not fit$/, '실행 프로그램 형식이 맞지 않습니다'],
|
||||
[/^the Paradise image must be 16 MB$/, '파라다이스 이미지 크기는 16 MB여야 합니다'],
|
||||
[/^home screen not found$/, '홈 화면을 찾지 못했습니다'],
|
||||
[/^area (\S+) is in use$/, '$1 영역이 사용 중입니다'],
|
||||
[/^emulator program too big$/, '에뮬레이터 프로그램이 너무 큽니다'],
|
||||
[/^program too big$/, '프로그램이 너무 큽니다'],
|
||||
[/^settings block missing in the program$/, '프로그램의 설정 영역이 없습니다'],
|
||||
[/^no emulator built in$/, '설치된 에뮬레이터가 없습니다'],
|
||||
[/^no download content in the file$/, '파일에 다운로드 콘텐츠가 없습니다'],
|
||||
[/^content checksum does not match$/, '콘텐츠 체크섬이 다릅니다'],
|
||||
[/^this content fits no store of this firmware$/, '이 펌웨어에 맞는 콘텐츠 저장 영역이 없습니다'],
|
||||
[/^content too big for its store$/, '콘텐츠가 저장 영역보다 큽니다'],
|
||||
[/^only for the 8 MB firmware$/, '8 MB 펌웨어에서만 지원합니다'],
|
||||
[/^no matching store$/, '맞는 저장 영역이 없습니다'],
|
||||
[/^already added$/, '이미 추가했습니다'],
|
||||
[/^(.+): all slots used, remove one first$/, '$1: 슬롯이 가득 찼습니다. 하나를 먼저 제거하세요'],
|
||||
[/^no such slot$/, '해당 슬롯이 없습니다'],
|
||||
[/^not a TG18 firmware \(8 MB\)$/, 'TG18 펌웨어(8 MB)가 아닙니다'],
|
||||
[/^not enough room: the firmware needs (\d+) blocks of 64 KB, (\d+) are free$/, '64 KB 블록 $1개가 필요하지만 $2개만 비어 있습니다'],
|
||||
[/^T18Emu program incomplete \(flash part missing\)$/, 'T18Emu 프로그램이 불완전합니다(플래시 부분 없음)'],
|
||||
[/^the menu is already built in$/, '본체 메뉴가 이미 설치되어 있습니다'],
|
||||
[/^more fields need a Tropical, Glacier or Jade Forest ROM with the original firmware$/, '지역 확장에는 원본 펌웨어의 트로피컬·글레이셔·제이드 포레스트 ROM이 필요합니다'],
|
||||
[/^rain pictures too big$/, '비 이미지가 너무 큽니다'],
|
||||
[/^unexpected Jade Forest data$/, '예상하지 못한 제이드 포레스트 데이터'],
|
||||
[/^helper page full$/, '보조 페이지가 가득 찼습니다'],
|
||||
[/^table (\S+) missing$/, '$1 표가 없습니다'],
|
||||
[/^the second ROM must be a Land, Water or Sky ROM$/, '두 번째 파일은 랜드·워터·스카이 ROM이어야 합니다'],
|
||||
[/^six fields program missing$/, '여섯 지역 프로그램이 없습니다'],
|
||||
[/^unexpected map picture$/, '예상하지 못한 지역 이미지'],
|
||||
[/^unexpected Land picture (\d+)$/, '예상하지 못한 랜드 이미지 $1'],
|
||||
[/^composite table full$/, '합성 이미지 표가 가득 찼습니다'],
|
||||
[/^menu program too old for six fields$/, '여섯 지역을 지원하지 않는 구버전 메뉴입니다'],
|
||||
[/^edition not recognised$/, '에디션을 인식하지 못했습니다'],
|
||||
[/^nothing chosen$/, '선택한 내용이 없습니다'],
|
||||
[/^no room for the launcher$/, '실행 프로그램을 넣을 공간이 없습니다'],
|
||||
[/^no room for the menu next to DOOM$/, 'DOOM과 함께 메뉴를 넣을 공간이 없습니다'],
|
||||
[/^no room for the saves next to DOOM$/, 'DOOM과 함께 저장 데이터를 넣을 공간이 없습니다'],
|
||||
[/^menu program too big$/, '본체 메뉴가 허용 용량을 초과합니다'],
|
||||
[/^the area for the menu is in use$/, '메뉴 영역이 사용 중입니다'],
|
||||
[/^no room for the saves$/, '저장 데이터를 넣을 공간이 없습니다'],
|
||||
[/^the area for the saves is in use$/, '저장 영역이 사용 중입니다'],
|
||||
[/^settings block of the menu missing$/, '메뉴의 설정 영역이 없습니다'],
|
||||
[/^the stored save of (.+) does not fit here$/, '$1의 저장이 이 영역에 맞지 않습니다'],
|
||||
[/^not a WAD file$/, 'WAD 파일이 아닙니다'],
|
||||
[/^no DOOM maps in the WAD \(DOOM 2 is not supported\)$/, 'WAD에 DOOM 지도가 없습니다(이 구성에서는 DOOM 2 미지원)'],
|
||||
[/^no picture$/, '이미지가 없습니다'],
|
||||
[/^broken$/, '손상된 데이터입니다'],
|
||||
[/^WAD conversion failed$/, 'WAD 변환 실패'],
|
||||
[/^the character data reaches (\S+), DOOM needs 0x830000 onwards$/, '캐릭터 데이터가 $1까지 사용합니다. DOOM은 0x830000 이후가 필요합니다'],
|
||||
[/^DOOM program too big$/, 'DOOM 프로그램이 너무 큽니다'],
|
||||
[/^WAD too big: (\d+) KB, room (\d+) KB \(try without music\)$/, 'WAD $1 KB, 여유 공간 $2 KB. 음악을 끄고 시도하세요'],
|
||||
[/^this DOOM has no key layout of its own yet$/, '이 DOOM은 개별 버튼 설정을 지원하지 않습니다'],
|
||||
[/^fire, forward and back need three different buttons$/, '발사·전진·후진은 서로 다른 버튼이어야 합니다'],
|
||||
[/^use needs its own button or the wheel$/, '사용은 별도의 버튼 또는 휠이어야 합니다'],
|
||||
[/^no room for the field saves next to this emulator firmware$/, '이 펌웨어와 함께 지역 저장을 넣을 공간이 없습니다'],
|
||||
[/^the character data reaches (\S+), the emulator needs 0x830000 onwards$/, '캐릭터 데이터가 $1까지 사용합니다. 에뮬레이터는 0x830000 이후가 필요합니다'],
|
||||
[/^the stored saves do not fit into the room for the fields$/, '보관한 저장이 지역 저장 공간을 초과합니다'],
|
||||
[/^unexpected planet table in the Land ROM$/, '랜드 ROM의 행성 표가 예상과 다릅니다'],
|
||||
[/^not a Paradise save \(\.tamasave\)$/, '파라다이스 저장(.tamasave)이 아닙니다'],
|
||||
[/^unknown save version (\S+)$/, '알 수 없는 저장 버전: $1'],
|
||||
[/^save is cut off$/, '저장 데이터가 잘렸습니다'],
|
||||
[/^no room for (.+) \((\d+) KB\)$/, '$1을 넣을 공간이 없습니다($2 KB)'],
|
||||
[/^no room for (.+)$/, '$1을 넣을 공간이 없습니다'],
|
||||
[/^only one T18Emu$/, 'T18Emu는 하나만 추가할 수 있습니다'],
|
||||
[/^T18Emu needs the area at 0x0F0000, the main program uses it: choose T18Emu in the Emulator tab$/, 'T18Emu가 필요한 0x0F0000 영역을 주 프로그램이 사용합니다. 에뮬레이터 탭에서 T18Emu를 선택하세요'],
|
||||
[/^(.+): only in a start device$/, '$1: 실행 전용 구성에서만 가능합니다'],
|
||||
[/^too many scenes$/, '장면이 너무 많습니다']
|
||||
];
|
||||
const MSG_KO = [
|
||||
[/^no ARC2 archive at (\S+)$/, '$1에 ARC2 아카이브가 없습니다'],
|
||||
[/^unknown bpp (\S+)$/, '알 수 없는 색상 깊이: $1'],
|
||||
[/^subimage count does not match$/, '부분 이미지 개수가 다릅니다'],
|
||||
[/^subimage size does not match$/, '부분 이미지 크기가 다릅니다'],
|
||||
[/^eye image too detailed: (\d+) bytes, at most (\d+) allowed$/, '눈 이미지가 너무 큽니다: $1바이트, 최대 $2바이트'],
|
||||
[/^not a Paradise flash dump \(SONIXDEV header missing\)$/, '파라다이스 덤프가 아닙니다(SONIXDEV 헤더 없음)'],
|
||||
[/^unexpected asset archive \((\d+) files\)$/, '예상하지 못한 자료 구성(파일 $1개)'],
|
||||
[/^too big: assets would end at (\S+), free space ends at (\S+)$/, '데이터가 $1까지 필요하지만 여유 공간은 $2까지입니다'],
|
||||
[/^checksum wrong at (\S+)$/, '$1 체크섬 오류'],
|
||||
[/^(?:character )?sheet must be (\S+) px, got (\S+)$/, '시트 크기는 $1px여야 합니다(현재 $2)'],
|
||||
[/^no sprite package$/, '이미지 패키지가 없습니다'],
|
||||
[/^not a ZIP file$/, 'ZIP 파일이 아닙니다'],
|
||||
[/^unsupported ZIP compression in (.+)$/, '$1: 지원하지 않는 ZIP 압축 방식'],
|
||||
[/^firmware not recognised \(expected a 4 MB or 8 MB image of a colour Tamagotchi\)$/, '컬러 다마고치의 4 MB 또는 8 MB 펌웨어가 필요합니다'],
|
||||
[/^scene table not found$/, '장면 표를 찾지 못했습니다'],
|
||||
[/^firmware too big: (\d+) blocks$/, '펌웨어가 너무 큽니다: $1블록'],
|
||||
[/^no room for the spare pages$/, '여분 페이지를 넣을 공간이 없습니다'],
|
||||
[/^launcher template does not fit$/, '실행 프로그램 형식이 맞지 않습니다'],
|
||||
[/^the Paradise image must be 16 MB$/, '파라다이스 이미지 크기는 16 MB여야 합니다'],
|
||||
[/^home screen not found$/, '홈 화면을 찾지 못했습니다'],
|
||||
[/^area (\S+) is in use$/, '$1 영역이 사용 중입니다'],
|
||||
[/^emulator program too big$/, '에뮬레이터 프로그램이 너무 큽니다'],
|
||||
[/^program too big$/, '프로그램이 너무 큽니다'],
|
||||
[/^settings block missing in the program$/, '프로그램의 설정 영역이 없습니다'],
|
||||
[/^no emulator built in$/, '설치된 에뮬레이터가 없습니다'],
|
||||
[/^no download content in the file$/, '파일에 다운로드 콘텐츠가 없습니다'],
|
||||
[/^content checksum does not match$/, '콘텐츠 체크섬이 다릅니다'],
|
||||
[/^this content fits no store of this firmware$/, '이 펌웨어에 맞는 콘텐츠 저장 영역이 없습니다'],
|
||||
[/^content too big for its store$/, '콘텐츠가 저장 영역보다 큽니다'],
|
||||
[/^only for the 8 MB firmware$/, '8 MB 펌웨어에서만 지원합니다'],
|
||||
[/^no matching store$/, '맞는 저장 영역이 없습니다'],
|
||||
[/^already added$/, '이미 추가했습니다'],
|
||||
[/^(.+): all slots used, remove one first$/, '$1: 슬롯이 가득 찼습니다. 하나를 먼저 제거하세요'],
|
||||
[/^no such slot$/, '해당 슬롯이 없습니다'],
|
||||
[/^not a TG18 firmware \(8 MB\)$/, 'TG18 펌웨어(8 MB)가 아닙니다'],
|
||||
[/^not enough room: the firmware needs (\d+) blocks of 64 KB, (\d+) are free$/, '64 KB 블록 $1개가 필요하지만 $2개만 비어 있습니다'],
|
||||
[/^T18Emu program incomplete \(flash part missing\)$/, 'T18Emu 프로그램이 불완전합니다(플래시 부분 없음)'],
|
||||
[/^the menu is already built in$/, '본체 메뉴가 이미 설치되어 있습니다'],
|
||||
[/^more fields need a Tropical, Glacier or Jade Forest ROM with the original firmware$/, '지역 확장에는 원본 펌웨어의 트로피컬·글레이셔·제이드 포레스트 ROM이 필요합니다'],
|
||||
[/^rain pictures too big$/, '비 이미지가 너무 큽니다'],
|
||||
[/^unexpected Jade Forest data$/, '예상하지 못한 제이드 포레스트 데이터'],
|
||||
[/^helper page full$/, '보조 페이지가 가득 찼습니다'],
|
||||
[/^table (\S+) missing$/, '$1 표가 없습니다'],
|
||||
[/^the second ROM must be a Land, Water or Sky ROM$/, '두 번째 파일은 랜드·워터·스카이 ROM이어야 합니다'],
|
||||
[/^six fields program missing$/, '여섯 지역 프로그램이 없습니다'],
|
||||
[/^unexpected map picture$/, '예상하지 못한 지역 이미지'],
|
||||
[/^unexpected Land picture (\d+)$/, '예상하지 못한 랜드 이미지 $1'],
|
||||
[/^composite table full$/, '합성 이미지 표가 가득 찼습니다'],
|
||||
[/^menu program too old for six fields$/, '여섯 지역을 지원하지 않는 구버전 메뉴입니다'],
|
||||
[/^edition not recognised$/, '에디션을 인식하지 못했습니다'],
|
||||
[/^nothing chosen$/, '선택한 내용이 없습니다'],
|
||||
[/^no room for the launcher$/, '실행 프로그램을 넣을 공간이 없습니다'],
|
||||
[/^no room for the menu next to DOOM$/, 'DOOM과 함께 메뉴를 넣을 공간이 없습니다'],
|
||||
[/^no room for the saves next to DOOM$/, 'DOOM과 함께 저장 데이터를 넣을 공간이 없습니다'],
|
||||
[/^menu program too big$/, '본체 메뉴가 허용 용량을 초과합니다'],
|
||||
[/^the area for the menu is in use$/, '메뉴 영역이 사용 중입니다'],
|
||||
[/^no room for the saves$/, '저장 데이터를 넣을 공간이 없습니다'],
|
||||
[/^the area for the saves is in use$/, '저장 영역이 사용 중입니다'],
|
||||
[/^settings block of the menu missing$/, '메뉴의 설정 영역이 없습니다'],
|
||||
[/^the stored save of (.+) does not fit here$/, '$1의 저장이 이 영역에 맞지 않습니다'],
|
||||
[/^not a WAD file$/, 'WAD 파일이 아닙니다'],
|
||||
[/^no DOOM maps in the WAD \(DOOM 2 is not supported\)$/, 'WAD에 DOOM 지도가 없습니다(이 구성에서는 DOOM 2 미지원)'],
|
||||
[/^no picture$/, '이미지가 없습니다'],
|
||||
[/^broken$/, '손상된 데이터입니다'],
|
||||
[/^WAD conversion failed$/, 'WAD 변환 실패'],
|
||||
[/^the character data reaches (\S+), DOOM needs 0x830000 onwards$/, '캐릭터 데이터가 $1까지 사용합니다. DOOM은 0x830000 이후가 필요합니다'],
|
||||
[/^DOOM program too big$/, 'DOOM 프로그램이 너무 큽니다'],
|
||||
[/^WAD too big: (\d+) KB, room (\d+) KB \(try without music\)$/, 'WAD $1 KB, 여유 공간 $2 KB. 음악을 끄고 시도하세요'],
|
||||
[/^this DOOM has no key layout of its own yet$/, '이 DOOM은 개별 버튼 설정을 지원하지 않습니다'],
|
||||
[/^fire, forward and back need three different buttons$/, '발사·전진·후진은 서로 다른 버튼이어야 합니다'],
|
||||
[/^use needs its own button or the wheel$/, '사용은 별도의 버튼 또는 휠이어야 합니다'],
|
||||
[/^no room for the field saves next to this emulator firmware$/, '이 펌웨어와 함께 지역 저장을 넣을 공간이 없습니다'],
|
||||
[/^the character data reaches (\S+), the emulator needs 0x830000 onwards$/, '캐릭터 데이터가 $1까지 사용합니다. 에뮬레이터는 0x830000 이후가 필요합니다'],
|
||||
[/^the stored saves do not fit into the room for the fields$/, '보관한 저장이 지역 저장 공간을 초과합니다'],
|
||||
[/^unexpected planet table in the Land ROM$/, '랜드 ROM의 행성 표가 예상과 다릅니다'],
|
||||
[/^not a Paradise save \(\.tamasave\)$/, '파라다이스 저장(.tamasave)이 아닙니다'],
|
||||
[/^unknown save version (\S+)$/, '알 수 없는 저장 버전: $1'],
|
||||
[/^save is cut off$/, '저장 데이터가 잘렸습니다'],
|
||||
[/^no room for (.+) \((\d+) KB\)$/, '$1을 넣을 공간이 없습니다($2 KB)'],
|
||||
[/^no room for (.+)$/, '$1을 넣을 공간이 없습니다'],
|
||||
[/^only one T18Emu$/, 'T18Emu는 하나만 추가할 수 있습니다'],
|
||||
[/^T18Emu needs the area at 0x0F0000, the main program uses it: choose T18Emu in the Emulator tab$/, 'T18Emu가 필요한 0x0F0000 영역을 주 프로그램이 사용합니다. 에뮬레이터 탭에서 T18Emu를 선택하세요'],
|
||||
[/^(.+): only in a start device$/, '$1: 실행 전용 구성에서만 가능합니다'],
|
||||
[/^too many scenes$/, '장면이 너무 많습니다']
|
||||
];
|
||||
+996
-996
File diff suppressed because it is too large.
Load diff
+1043
-1043
File diff suppressed because it is too large.
Load diff
+798
-798
File diff suppressed because it is too large.
Load diff
+757
-757
File diff suppressed because it is too large.
Load diff
+22
-22
@@ -1,22 +1,22 @@
|
||||
<!doctype html>
|
||||
<html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>기종별 원본 복원 · 다마고치 연구소</title>
|
||||
<meta name="description" content="관리자가 공개한 다마고치 파라다이스 기종별 백업을 확인하고 제이드 포레스트 원본으로 복원합니다.">
|
||||
<link rel="canonical" href="https://tama.itosm.co.kr/restore.html"><link rel="stylesheet" href="site.css"></head>
|
||||
<body><main><nav><a href="/">← 펌웨어 편집 도구</a><a href="account.html">회원가입·내 보관함</a><a href="about.html">서비스 소개</a><a href="guide.html">사용 안내</a></nav>
|
||||
<p class="eyebrow">TAMAGOTCHI PARADISE · RECOVERY</p><h1>기종별 백업으로 복원</h1>
|
||||
<p class="lead">관리자가 공개한 파일을 확인하고 백업 당시의 상태로 돌아갑니다.</p>
|
||||
<p id="restoreLogin">기종별 복원은 로그인 후 이용할 수 있습니다. <a href="account.html">회원가입·로그인</a></p><div id="restoreContent" hidden><section><h2>1. 복원할 백업 선택</h2><p>복원할 기종과 백업 날짜를 확인한 뒤 파일을 선택하세요. 복원하면 현재 ROM과 저장 데이터가 선택한 백업으로 교체됩니다.</p>
|
||||
<label for="catalog">공개 백업 / 로그인한 회원의 개인 백업</label><select id="catalog" disabled><option>목록을 불러오는 중…</option></select>
|
||||
<p id="details" class="hint"></p><button id="prepare" disabled>복원 파일 불러오기·검증</button><button id="download" disabled>검증한 파일 PC에 저장</button><p id="fileStatus" role="status"></p></section>
|
||||
<section><h2>2. 본체 연결</h2><p>PC의 Chrome 또는 Edge에서 UART 장치를 연결하세요. 본체의 <strong>다마 우주 → A → 통신 → 다운로드 → 다운로드</strong> 화면을 엽니다. 편집 도구가 장치를 사용 중이면 먼저 연결을 해제하거나 해당 탭을 닫으세요.</p>
|
||||
<p>복구 기능이 설치된 기기는 C를 누른 채 RESET을 짧게 눌렀다 놓으세요. 복구 화면이 나타나면 C를 놓고 연결합니다. 기록 중에는 RESET을 누르지 마세요.</p>
|
||||
<button id="connect">본체 연결</button><button id="disconnect" disabled>연결 해제</button><p id="deviceStatus" role="status">연결하지 않았습니다.</p>
|
||||
<button id="retryBackup" hidden>서버 저장 재시도</button><button id="backup" disabled>현재 ROM 추출·백업 후 다운로드</button></section>
|
||||
<section><h2>3. 선택한 백업으로 복원</h2><p class="warning">현재 펌웨어와 저장 데이터가 선택한 백업으로 교체됩니다.</p>
|
||||
<p>필요한 현재 상태는 위에서 먼저 백업하세요. 복원 중에는 전원과 케이블을 유지하세요.</p>
|
||||
<label class="check"><input type="checkbox" id="ack"> 현재 저장 데이터까지 교체되는 것을 확인했습니다.</label>
|
||||
<button id="restore" disabled>선택한 백업으로 본체 복원</button>
|
||||
<progress id="progress" max="100" value="0" aria-label="작업 진행률"></progress><p id="status" role="status" aria-live="polite">복원 파일과 본체를 준비하세요.</p></section>
|
||||
</div><footer>다마고치 연구소 · <a href="LICENSE.txt">GPL 라이선스</a></footer></main>
|
||||
<script>__FLASH__</script><script>__ARCHIVE__</script><script>__RESTORE__</script></body></html>
|
||||
<!doctype html>
|
||||
<html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>기종별 원본 복원 · 다마고치 연구소</title>
|
||||
<meta name="description" content="관리자가 공개한 다마고치 파라다이스 기종별 백업을 확인하고 제이드 포레스트 원본으로 복원합니다.">
|
||||
<link rel="canonical" href="https://tama.itosm.co.kr/restore.html"><link rel="stylesheet" href="site.css"></head>
|
||||
<body><main><nav><a href="/">← 펌웨어 편집 도구</a><a href="account.html">회원가입·내 보관함</a><a href="about.html">서비스 소개</a><a href="guide.html">사용 안내</a></nav>
|
||||
<p class="eyebrow">TAMAGOTCHI PARADISE · RECOVERY</p><h1>기종별 백업으로 복원</h1>
|
||||
<p class="lead">관리자가 공개한 파일을 확인하고 백업 당시의 상태로 돌아갑니다.</p>
|
||||
<p id="restoreLogin">기종별 복원은 로그인 후 이용할 수 있습니다. <a href="account.html">회원가입·로그인</a></p><div id="restoreContent" hidden><section><h2>1. 복원할 백업 선택</h2><p>복원할 기종과 백업 날짜를 확인한 뒤 파일을 선택하세요. 복원하면 현재 ROM과 저장 데이터가 선택한 백업으로 교체됩니다.</p>
|
||||
<label for="catalog">공개 백업 / 로그인한 회원의 개인 백업</label><select id="catalog" disabled><option>목록을 불러오는 중…</option></select>
|
||||
<p id="details" class="hint"></p><button id="prepare" disabled>복원 파일 불러오기·검증</button><button id="download" disabled>검증한 파일 PC에 저장</button><p id="fileStatus" role="status"></p></section>
|
||||
<section><h2>2. 본체 연결</h2><p>PC의 Chrome 또는 Edge에서 UART 장치를 연결하세요. 본체의 <strong>다마 우주 → A → 통신 → 다운로드 → 다운로드</strong> 화면을 엽니다. 편집 도구가 장치를 사용 중이면 먼저 연결을 해제하거나 해당 탭을 닫으세요.</p>
|
||||
<p>복구 기능이 설치된 기기는 C를 누른 채 RESET을 짧게 눌렀다 놓으세요. 복구 화면이 나타나면 C를 놓고 연결합니다. 기록 중에는 RESET을 누르지 마세요.</p>
|
||||
<button id="connect">본체 연결</button><button id="disconnect" disabled>연결 해제</button><p id="deviceStatus" role="status">연결하지 않았습니다.</p>
|
||||
<button id="retryBackup" hidden>서버 저장 재시도</button><button id="backup" disabled>현재 ROM 추출·백업 후 다운로드</button></section>
|
||||
<section><h2>3. 선택한 백업으로 복원</h2><p class="warning">현재 펌웨어와 저장 데이터가 선택한 백업으로 교체됩니다.</p>
|
||||
<p>필요한 현재 상태는 위에서 먼저 백업하세요. 복원 중에는 전원과 케이블을 유지하세요.</p>
|
||||
<label class="check"><input type="checkbox" id="ack"> 현재 저장 데이터까지 교체되는 것을 확인했습니다.</label>
|
||||
<button id="restore" disabled>선택한 백업으로 본체 복원</button>
|
||||
<progress id="progress" max="100" value="0" aria-label="작업 진행률"></progress><p id="status" role="status" aria-live="polite">복원 파일과 본체를 준비하세요.</p></section>
|
||||
</div><footer>다마고치 연구소 · <a href="LICENSE.txt">GPL 라이선스</a></footer></main>
|
||||
<script>__FLASH__</script><script>__ARCHIVE__</script><script>__RESTORE__</script></body></html>
|
||||
+109
-109
@@ -1,109 +1,109 @@
|
||||
'use strict';
|
||||
const $ = id => document.getElementById(id), A = window.TamaArchive, FL = window.ParamixFlash;
|
||||
let items = [], selected = null, image = null, io = null, dev = null, deviceId = 0, running = false, authenticated = false;
|
||||
function status(message) { $('status').textContent = message; }
|
||||
function render() {
|
||||
$('restoreContent').hidden = !authenticated; $('restoreLogin').hidden = authenticated;
|
||||
$('catalog').disabled = running || !items.length;
|
||||
$('prepare').disabled = running || !selected;
|
||||
$('download').disabled = running || !image;
|
||||
$('connect').disabled = running || !!io || !navigator.serial;
|
||||
$('disconnect').disabled = running || !io;
|
||||
$('backup').disabled = running || !dev || A.hasPending();
|
||||
$('retryBackup').hidden=!A.hasPending();$('retryBackup').disabled=running;
|
||||
$('ack').disabled = running;
|
||||
$('restore').disabled = running || !image || !dev || !deviceId || deviceId !== selected?.edition || !$('ack').checked;
|
||||
}
|
||||
async function task(fn) {
|
||||
if (running || !authenticated) return;
|
||||
running = true; render();
|
||||
try { await fn(); } catch (e) { status('작업 실패: ' + e.message); }
|
||||
finally { running = false; render(); }
|
||||
}
|
||||
function progress(phase, done, total) {
|
||||
$('progress').value = total ? done / total * 100 : 0;
|
||||
status(({load: '연결 프로그램 불러오기', read: '본체 읽기', compare: '파일 비교', write: '본체 기록', check: '기록 검증', prepare: '준비'}[phase] || '처리') + ' ' + Math.round(total ? done / total * 100 : 0) + '%');
|
||||
}
|
||||
function save(img, name) {
|
||||
const url = URL.createObjectURL(new Blob([img], {type: 'application/octet-stream'}));
|
||||
const a = document.createElement('a'); a.href = url; a.download = name; a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 30000);
|
||||
}
|
||||
function choose() {
|
||||
selected = items.find(x => (x.id || x.sha256) === $('catalog').value) || null;
|
||||
image = null; $('ack').checked = false; $('fileStatus').textContent = '';
|
||||
$('details').textContent = selected ? selected.name + ' · 16 MB · ' + (selected.sourceDate || selected.createdAt) + '\nSHA-256: ' + selected.sha256 : '';
|
||||
render();
|
||||
}
|
||||
$('catalog').onchange = choose;
|
||||
$('ack').onchange = render;
|
||||
$('prepare').onclick = () => task(async () => {
|
||||
image = null; $('fileStatus').textContent = '복원 파일을 불러와 확인하고 있습니다…';
|
||||
const response = await fetch(selected.fileUrl || '/api/file/' + selected.sha256, {cache: 'no-store', signal: AbortSignal.timeout(90000)});
|
||||
if (!response.ok) { $('fileStatus').textContent = '파일 불러오기 실패'; throw new Error('공개된 파일을 불러올 수 없습니다.'); }
|
||||
image = await A.verify(new Uint8Array(await response.arrayBuffer()), selected);
|
||||
$('fileStatus').textContent = '파일 확인을 마쳤습니다. 본체를 연결하고 복원을 진행하세요.';
|
||||
});
|
||||
$('download').onclick = () => { if (authenticated && image && !running) save(image, 'paradise-' + selected.slug + '-restore-' + selected.sha256.slice(0, 12) + '.bin'); };
|
||||
$('connect').onclick = async () => {
|
||||
if (!authenticated || running || io || !navigator.serial) return;
|
||||
// Keep requestPort in the user's click event for the browser permission chooser.
|
||||
let port;
|
||||
try { port = await navigator.serial.requestPort(); } catch (e) { status('기기 선택을 취소했습니다.'); return; }
|
||||
await task(async () => {
|
||||
try {
|
||||
io = await FL.serialOpen(port);
|
||||
const result = await FL.connect(io, FL.embedded(), {}, progress);
|
||||
dev = result.dev;
|
||||
deviceId = await A.deviceEdition(dev);
|
||||
if (dev.info.capacity !== 0x1000000) throw new Error('지원하지 않는 본체 용량입니다.');
|
||||
$('deviceStatus').textContent = deviceId ? '연결됨: ' + FL.EDITIONS[deviceId] : '연결됐지만 기종을 확인할 수 없습니다. 복원 기록은 차단됩니다.';
|
||||
status('선택한 파일과 본체 기종이 같아야 복원할 수 있습니다.');
|
||||
} catch (e) {
|
||||
if (io) await io.close().catch(() => {});
|
||||
io = null; dev = null; deviceId = 0; throw e;
|
||||
}
|
||||
});
|
||||
};
|
||||
$('disconnect').onclick = () => task(async () => { if (io) await io.close(); io = null; dev = null; deviceId = 0; $('deviceStatus').textContent = '연결 해제됨'; });
|
||||
$('backup').onclick = () => task(async () => {
|
||||
const current = await dev.dump(progress);
|
||||
const name='paradise-' + (FL.EDITIONS[A.edition(current)] || 'unknown').toLowerCase().replace(/ /g, '-') + '-' + new Date().toISOString().replace(/[:.]/g, '-') + '.bin';
|
||||
await A.deliver(current,name,save,status);
|
||||
});
|
||||
$('retryBackup').onclick=()=>task(()=>A.retry());
|
||||
$('restore').onclick = async () => {
|
||||
if (!authenticated || running || !image || !dev || !deviceId || deviceId !== selected?.edition || !$('ack').checked) return;
|
||||
if (!confirm(selected.label + '으로 복원합니다.\n현재 저장 데이터와 추가 메뉴가 교체됩니다.\n전원과 케이블을 유지하세요. 계속할까요?')) return;
|
||||
await task(async () => {
|
||||
await A.verify(image, selected);
|
||||
if (await A.deviceEdition(dev) !== selected.edition) throw new Error('본체 기종이 선택한 백업과 다릅니다.');
|
||||
// Exact image restoration: no composition, save merging or rescue-code insertion.
|
||||
// The upstream writer verifies each committed sector and all 64 KB blocks.
|
||||
const result = await dev.write(image, {onlyChanged: true, keep: null}, progress);
|
||||
status('복원 기록·검증 완료 (' + result.written + '개 구역). 연결을 해제하고 본체 전원을 껐다 켜세요.');
|
||||
$('ack').checked = false;
|
||||
});
|
||||
};
|
||||
window.addEventListener('beforeunload', event => { if (running || A.hasPending()) { event.preventDefault(); event.returnValue = ''; } });
|
||||
if (!navigator.serial) $('deviceStatus').textContent = '본체 연결은 PC의 Chrome 또는 Edge에서 지원합니다. 파일 다운로드는 가능합니다.';
|
||||
render();
|
||||
async function refreshRestoreMembership() {
|
||||
if (running) return;
|
||||
try {
|
||||
const me = await A.request('/api/member/me');
|
||||
authenticated = !!me.authenticated;
|
||||
render();
|
||||
if (!authenticated) { items=[]; selected=null; image=null; $('ack').checked=false; return; }
|
||||
const result = await A.request('/api/catalog');
|
||||
items = result.items.concat(me.authenticated ? me.items.filter(x => x.edition).map(x => ({...x, label:'내 보관함 · '+x.label})) : []);
|
||||
$('catalog').replaceChildren();
|
||||
for (const item of items) { const opt = document.createElement('option'); opt.value = item.id || item.sha256; opt.textContent = item.label; $('catalog').appendChild(opt); }
|
||||
const requested = new URLSearchParams(location.search).get('backup');
|
||||
if (requested && items.some(x => x.id === requested)) $('catalog').value = requested;
|
||||
if (!items.length) { const opt = document.createElement('option'); opt.textContent = '공개된 백업이 없습니다.'; $('catalog').appendChild(opt); }
|
||||
choose();
|
||||
} catch(e) { authenticated=false; render(); status(e.message); }
|
||||
}
|
||||
refreshRestoreMembership();
|
||||
window.addEventListener('focus', refreshRestoreMembership);
|
||||
'use strict';
|
||||
const $ = id => document.getElementById(id), A = window.TamaArchive, FL = window.ParamixFlash;
|
||||
let items = [], selected = null, image = null, io = null, dev = null, deviceId = 0, running = false, authenticated = false;
|
||||
function status(message) { $('status').textContent = message; }
|
||||
function render() {
|
||||
$('restoreContent').hidden = !authenticated; $('restoreLogin').hidden = authenticated;
|
||||
$('catalog').disabled = running || !items.length;
|
||||
$('prepare').disabled = running || !selected;
|
||||
$('download').disabled = running || !image;
|
||||
$('connect').disabled = running || !!io || !navigator.serial;
|
||||
$('disconnect').disabled = running || !io;
|
||||
$('backup').disabled = running || !dev || A.hasPending();
|
||||
$('retryBackup').hidden=!A.hasPending();$('retryBackup').disabled=running;
|
||||
$('ack').disabled = running;
|
||||
$('restore').disabled = running || !image || !dev || !deviceId || deviceId !== selected?.edition || !$('ack').checked;
|
||||
}
|
||||
async function task(fn) {
|
||||
if (running || !authenticated) return;
|
||||
running = true; render();
|
||||
try { await fn(); } catch (e) { status('작업 실패: ' + e.message); }
|
||||
finally { running = false; render(); }
|
||||
}
|
||||
function progress(phase, done, total) {
|
||||
$('progress').value = total ? done / total * 100 : 0;
|
||||
status(({load: '연결 프로그램 불러오기', read: '본체 읽기', compare: '파일 비교', write: '본체 기록', check: '기록 검증', prepare: '준비'}[phase] || '처리') + ' ' + Math.round(total ? done / total * 100 : 0) + '%');
|
||||
}
|
||||
function save(img, name) {
|
||||
const url = URL.createObjectURL(new Blob([img], {type: 'application/octet-stream'}));
|
||||
const a = document.createElement('a'); a.href = url; a.download = name; a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 30000);
|
||||
}
|
||||
function choose() {
|
||||
selected = items.find(x => (x.id || x.sha256) === $('catalog').value) || null;
|
||||
image = null; $('ack').checked = false; $('fileStatus').textContent = '';
|
||||
$('details').textContent = selected ? selected.name + ' · 16 MB · ' + (selected.sourceDate || selected.createdAt) + '\nSHA-256: ' + selected.sha256 : '';
|
||||
render();
|
||||
}
|
||||
$('catalog').onchange = choose;
|
||||
$('ack').onchange = render;
|
||||
$('prepare').onclick = () => task(async () => {
|
||||
image = null; $('fileStatus').textContent = '복원 파일을 불러와 확인하고 있습니다…';
|
||||
const response = await fetch(selected.fileUrl || '/api/file/' + selected.sha256, {cache: 'no-store', signal: AbortSignal.timeout(90000)});
|
||||
if (!response.ok) { $('fileStatus').textContent = '파일 불러오기 실패'; throw new Error('공개된 파일을 불러올 수 없습니다.'); }
|
||||
image = await A.verify(new Uint8Array(await response.arrayBuffer()), selected);
|
||||
$('fileStatus').textContent = '파일 확인을 마쳤습니다. 본체를 연결하고 복원을 진행하세요.';
|
||||
});
|
||||
$('download').onclick = () => { if (authenticated && image && !running) save(image, 'paradise-' + selected.slug + '-restore-' + selected.sha256.slice(0, 12) + '.bin'); };
|
||||
$('connect').onclick = async () => {
|
||||
if (!authenticated || running || io || !navigator.serial) return;
|
||||
// Keep requestPort in the user's click event for the browser permission chooser.
|
||||
let port;
|
||||
try { port = await navigator.serial.requestPort(); } catch (e) { status('기기 선택을 취소했습니다.'); return; }
|
||||
await task(async () => {
|
||||
try {
|
||||
io = await FL.serialOpen(port);
|
||||
const result = await FL.connect(io, FL.embedded(), {}, progress);
|
||||
dev = result.dev;
|
||||
deviceId = await A.deviceEdition(dev);
|
||||
if (dev.info.capacity !== 0x1000000) throw new Error('지원하지 않는 본체 용량입니다.');
|
||||
$('deviceStatus').textContent = deviceId ? '연결됨: ' + FL.EDITIONS[deviceId] : '연결됐지만 기종을 확인할 수 없습니다. 복원 기록은 차단됩니다.';
|
||||
status('선택한 파일과 본체 기종이 같아야 복원할 수 있습니다.');
|
||||
} catch (e) {
|
||||
if (io) await io.close().catch(() => {});
|
||||
io = null; dev = null; deviceId = 0; throw e;
|
||||
}
|
||||
});
|
||||
};
|
||||
$('disconnect').onclick = () => task(async () => { if (io) await io.close(); io = null; dev = null; deviceId = 0; $('deviceStatus').textContent = '연결 해제됨'; });
|
||||
$('backup').onclick = () => task(async () => {
|
||||
const current = await dev.dump(progress);
|
||||
const name='paradise-' + (FL.EDITIONS[A.edition(current)] || 'unknown').toLowerCase().replace(/ /g, '-') + '-' + new Date().toISOString().replace(/[:.]/g, '-') + '.bin';
|
||||
await A.deliver(current,name,save,status);
|
||||
});
|
||||
$('retryBackup').onclick=()=>task(()=>A.retry());
|
||||
$('restore').onclick = async () => {
|
||||
if (!authenticated || running || !image || !dev || !deviceId || deviceId !== selected?.edition || !$('ack').checked) return;
|
||||
if (!confirm(selected.label + '으로 복원합니다.\n현재 저장 데이터와 추가 메뉴가 교체됩니다.\n전원과 케이블을 유지하세요. 계속할까요?')) return;
|
||||
await task(async () => {
|
||||
await A.verify(image, selected);
|
||||
if (await A.deviceEdition(dev) !== selected.edition) throw new Error('본체 기종이 선택한 백업과 다릅니다.');
|
||||
// Exact image restoration: no composition, save merging or rescue-code insertion.
|
||||
// The upstream writer verifies each committed sector and all 64 KB blocks.
|
||||
const result = await dev.write(image, {onlyChanged: true, keep: null}, progress);
|
||||
status('복원 기록·검증 완료 (' + result.written + '개 구역). 연결을 해제하고 본체 전원을 껐다 켜세요.');
|
||||
$('ack').checked = false;
|
||||
});
|
||||
};
|
||||
window.addEventListener('beforeunload', event => { if (running || A.hasPending()) { event.preventDefault(); event.returnValue = ''; } });
|
||||
if (!navigator.serial) $('deviceStatus').textContent = '본체 연결은 PC의 Chrome 또는 Edge에서 지원합니다. 파일 다운로드는 가능합니다.';
|
||||
render();
|
||||
async function refreshRestoreMembership() {
|
||||
if (running) return;
|
||||
try {
|
||||
const me = await A.request('/api/member/me');
|
||||
authenticated = !!me.authenticated;
|
||||
render();
|
||||
if (!authenticated) { items=[]; selected=null; image=null; $('ack').checked=false; return; }
|
||||
const result = await A.request('/api/catalog');
|
||||
items = result.items.concat(me.authenticated ? me.items.filter(x => x.edition).map(x => ({...x, label:'내 보관함 · '+x.label})) : []);
|
||||
$('catalog').replaceChildren();
|
||||
for (const item of items) { const opt = document.createElement('option'); opt.value = item.id || item.sha256; opt.textContent = item.label; $('catalog').appendChild(opt); }
|
||||
const requested = new URLSearchParams(location.search).get('backup');
|
||||
if (requested && items.some(x => x.id === requested)) $('catalog').value = requested;
|
||||
if (!items.length) { const opt = document.createElement('option'); opt.textContent = '공개된 백업이 없습니다.'; $('catalog').appendChild(opt); }
|
||||
choose();
|
||||
} catch(e) { authenticated=false; render(); status(e.message); }
|
||||
}
|
||||
refreshRestoreMembership();
|
||||
window.addEventListener('focus', refreshRestoreMembership);
|
||||
+347
-347
@@ -1,347 +1,347 @@
|
||||
/*
|
||||
* Paramix Studio: save games in and out of the Paradise.
|
||||
*
|
||||
* Paradise: the game keeps its progress in the flash after the edition ID page
|
||||
* (0xD4A000, Tropical/Glacier 0xD2A000) up to 0xF00000. Exported as a
|
||||
* .tamasave (format 3 of the TamaParadise app): every page of that region,
|
||||
* the seconds counter of the device and an armed wake alarm, so the app
|
||||
* continues instead of starting like a fresh battery. Behind the pages a
|
||||
* Paramix trailer ("PMXE", edition, region) that the app ignores and the
|
||||
* Studio uses to refuse a save of another edition.
|
||||
*
|
||||
* TamaEmu: the guest's own save is its flash. Exported as the raw image the
|
||||
* TamaEmu app uses (.sav, 4 MB or 8 MB; named after the app's device: plus-color, idl, ps, 4u): packed blocks plus the spare pages
|
||||
* the emulator wrote. Importing a .sav works like choosing a firmware.
|
||||
*
|
||||
* Author: mameise
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
|
||||
const PAGE = 0x1000;
|
||||
const MAGIC = 'TAMASAVE', VERSION = 3, TRAILER = 0x45584D50; // "PMXE"
|
||||
const SET_A = 0xEFE000, SET_B = 0xEFF000, REGION_END = 0xF00000;
|
||||
const u16 = (b, o) => b[o] | (b[o + 1] << 8);
|
||||
const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0;
|
||||
function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; }
|
||||
|
||||
/** Edition 5/6 (Tropical, Glacier) keep their ID page lower. */
|
||||
function idPage(edition) { return edition === 5 || edition === 6 ? 0xD29000 : 0xD49000; }
|
||||
function region(edition) { return [idPage(edition) + PAGE, REGION_END]; }
|
||||
function family(edition) { return edition === 5 || edition === 6 ? 'gen3' : edition === 4 ? 'jade' : 'gen1'; }
|
||||
|
||||
/* Settings block: CRC-16/ARC over bytes 4..4095 at 0, its inverse at 2. */
|
||||
function crc16arc(d, from, to) {
|
||||
let c = 0;
|
||||
for (let i = from; i < to; i++) { c ^= d[i]; for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xA001 : c >>> 1; }
|
||||
return c;
|
||||
}
|
||||
function settingsOk(p) { const c = crc16arc(p, 4, PAGE); return u16(p, 0) === c && u16(p, 2) === (~c & 0xFFFF); }
|
||||
|
||||
// ---------------------------------------------------------------- Paradise
|
||||
/** Pages of the save region from a 16 MB image (all of them, empty ones too). */
|
||||
function paraFromImage(img, edition) {
|
||||
const [a, b] = region(edition), pages = new Map();
|
||||
for (let p = a; p < b; p += PAGE) pages.set(p, img.slice(p, p + PAGE));
|
||||
return pages;
|
||||
}
|
||||
/**
|
||||
* .tamasave from pages (Map address -> 4 KB). clock: { counter, ctrl } of the device or null.
|
||||
*/
|
||||
function paraEncode(pages, edition, clock, now = Math.floor(Date.now() / 1000)) {
|
||||
const counter = clock ? clock.counter >>> 0 : 0;
|
||||
const alarm = counter ? counter - 1 : 0, status = counter ? 0x100 : 0; // armed, as the app does when it puts the console away
|
||||
// the always powered system registers as the app stores them (clock and PLL as the firmware sets them)
|
||||
const regs = counter ? [[0x000, 0xC051], [0x004, 0xA55A0000], [0x00C, 4], [0x010, 0], [0x018, 0x21], [0x020, 0x42], [0x050, 0],
|
||||
[0x100, 0x157EB7], [0x108, 0], [0x10C, 0x1FFFFD], [0x110, 0], [0x200, clock.ctrl & 0x80 ? clock.ctrl >>> 0 : 0xE0], [0x204, 0],
|
||||
[0x210, 0], [0x214, 0], [0x218, 0], [0x230, alarm], [0x234, status], [0x300, 0x10]] : [];
|
||||
const list = [...pages.keys()].sort((x, y) => x - y);
|
||||
const size = 36 + 8 * regs.length + 4 + list.reduce((n, a) => n + 8 + pages.get(a).length, 0) + 16;
|
||||
const out = new Uint8Array(size);
|
||||
for (let i = 0; i < 8; i++) out[i] = MAGIC.charCodeAt(i);
|
||||
w32(out, 8, VERSION);
|
||||
w32(out, 12, counter ? now : 0); w32(out, 16, 0); // u64 time stamp (seconds since 1970)
|
||||
w32(out, 20, counter); w32(out, 24, alarm); w32(out, 28, status); w32(out, 32, regs.length);
|
||||
let o = 36;
|
||||
for (const [k, v] of regs) { w32(out, o, k); w32(out, o + 4, v); o += 8; }
|
||||
w32(out, o, list.length); o += 4;
|
||||
for (const a of list) { const d = pages.get(a); w32(out, o, a / PAGE); w32(out, o + 4, d.length); out.set(d, o + 8); o += 8 + d.length; }
|
||||
w32(out, o, TRAILER); w32(out, o + 4, edition); w32(out, o + 8, region(edition)[0]); w32(out, o + 12, region(edition)[1]);
|
||||
return out;
|
||||
}
|
||||
/** Write a decoded save back as it was (time stamp, clock, registers kept). */
|
||||
function paraWrite(save, edition) {
|
||||
const regs = save.regs || [], list = [...save.pages.keys()].sort((x, y) => x - y);
|
||||
const size = 36 + 8 * regs.length + 4 + list.reduce((n, a) => n + 8 + save.pages.get(a).length, 0) + 16;
|
||||
const out = new Uint8Array(size);
|
||||
for (let i = 0; i < 8; i++) out[i] = MAGIC.charCodeAt(i);
|
||||
w32(out, 8, VERSION);
|
||||
w32(out, 12, save.stamp % 4294967296); w32(out, 16, Math.floor(save.stamp / 4294967296));
|
||||
w32(out, 20, save.counter); w32(out, 24, save.alarm); w32(out, 28, save.status); w32(out, 32, regs.length);
|
||||
let o = 36;
|
||||
for (const [k, v] of regs) { w32(out, o, k); w32(out, o + 4, v); o += 8; }
|
||||
w32(out, o, list.length); o += 4;
|
||||
for (const a of list) { const d = save.pages.get(a); w32(out, o, a / PAGE); w32(out, o + 4, d.length); out.set(d, o + 8); o += 8 + d.length; }
|
||||
const ed = edition || save.edition;
|
||||
w32(out, o, TRAILER); w32(out, o + 4, ed); w32(out, o + 8, region(ed)[0]); w32(out, o + 12, region(ed)[1]);
|
||||
return out;
|
||||
}
|
||||
/** Read a .tamasave (format 3). Throws on anything else. */
|
||||
function paraDecode(b) {
|
||||
if (b.length < 40 || String.fromCharCode(...b.subarray(0, 8)) !== MAGIC) throw new Error('not a Paradise save (.tamasave)');
|
||||
if (u32(b, 8) !== VERSION) throw new Error('unknown save version ' + u32(b, 8));
|
||||
const stamp = u32(b, 12) + u32(b, 16) * 4294967296, counter = u32(b, 20), alarm = u32(b, 24), status = u32(b, 28);
|
||||
const nr = u32(b, 32); let o = 36;
|
||||
const regs = [];
|
||||
for (let i = 0; i < nr; i++) { if (o + 8 > b.length) throw new Error('save is cut off'); regs.push([u32(b, o), u32(b, o + 4)]); o += 8; }
|
||||
if (o + 4 > b.length) throw new Error('save is cut off');
|
||||
const np = u32(b, o); o += 4;
|
||||
const pages = new Map();
|
||||
for (let i = 0; i < np; i++) {
|
||||
if (o + 8 > b.length) throw new Error('save is cut off');
|
||||
const a = u32(b, o) * PAGE, n = u32(b, o + 4); o += 8;
|
||||
if (o + n > b.length) throw new Error('save is cut off');
|
||||
pages.set(a, b.slice(o, o + n)); o += n;
|
||||
}
|
||||
let edition = 0;
|
||||
if (o + 16 <= b.length && u32(b, o) === TRAILER) edition = u32(b, o + 4);
|
||||
return { stamp, counter, alarm, status, regs, pages, edition };
|
||||
}
|
||||
/**
|
||||
* Can this save go onto a device of this edition? Returns { errors, warnings, pages (only the
|
||||
* save region, full 4 KB), complete }.
|
||||
*/
|
||||
function paraCheck(save, edition) {
|
||||
const errors = [], warnings = [], [a, b] = region(edition), pages = new Map();
|
||||
if (save.edition && save.edition !== edition) errors.push({ code: 'saveOtherEd', p: { s: save.edition, d: edition } });
|
||||
let outside = 0;
|
||||
for (const [p, d] of save.pages) {
|
||||
if (p < a || p >= b || d.length !== PAGE) { outside++; continue; }
|
||||
pages.set(p, d);
|
||||
}
|
||||
if (outside) warnings.push({ code: 'saveOutside', p: { n: outside } });
|
||||
const sa = pages.get(SET_A), sb = pages.get(SET_B);
|
||||
const set = sa && settingsOk(sa) ? sa : sb && settingsOk(sb) ? sb : null;
|
||||
if (!set) errors.push({ code: 'saveNoSettings' });
|
||||
else if ((u16(set, 12) === 0x016D) !== (family(edition) === 'gen3')) errors.push({ code: 'saveFamily' });
|
||||
let complete = true;
|
||||
for (let p = a; p < b; p += PAGE) if (!pages.has(p)) { complete = false; break; }
|
||||
if (!complete) warnings.push({ code: 'saveIncomplete' });
|
||||
return { errors, warnings, pages, complete };
|
||||
}
|
||||
/** Seconds counter to set on the device: the saved one plus the time since. */
|
||||
function paraClock(save, now = Math.floor(Date.now() / 1000)) {
|
||||
if (!save.counter || !save.stamp) return null;
|
||||
return (save.counter + Math.max(0, now - save.stamp)) >>> 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- change a Paradise save (1.6.8)
|
||||
// The pet in the settings block: +4/+6 character, +0x10 sickness, +0x18 bits 2..4 stage, +0x1C hunger 0..6,
|
||||
// +0x1D happiness 0..20. Planet level: low nibble = level, high nibble = level already celebrated.
|
||||
const PET = { gen1: { tama: 0x104, level: 0x7C }, jade: { tama: 0x108, level: 0x7C }, gen3: { tama: 0x114, level: 0x88 } };
|
||||
function paraSettings(save) { for (const a of [SET_A, SET_B]) { const p = save.pages.get(a); if (p && p.length === PAGE && settingsOk(p)) return p; } return null; }
|
||||
/** What the save says about the pet: { level, id, stage, hunger, happy, sick } or null. */
|
||||
function paraPet(save, edition) {
|
||||
const p = paraSettings(save), o = PET[family(edition)]; if (!p || !o) return null;
|
||||
const t = o.tama;
|
||||
const color=p[t+0x19]&31;
|
||||
return { level: p[o.level] & 15, id: u16(p, t + 4), stage: (p[t + 0x18] >> 2) & 7, color:color<16?color:-1, hunger: p[t + 0x1C], happy: p[t + 0x1D], sick: p[t + 0x10] };
|
||||
}
|
||||
/**
|
||||
* Changed copy of the save. A character change requires the complete native genes
|
||||
* package from the ROM. Only the current pet's slot is replaced; friends are preserved.
|
||||
*/
|
||||
function paraAppearance(save){
|
||||
const old=paraPet(save,save.edition)?.id;
|
||||
for(const[a,p]of [...save.pages].sort((a,b)=>a[0]-b[0])){
|
||||
const n=u32(p,0x10c);if(u32(p,8)!==1||u16(p,12)!==4017||u16(p,0x10a)!==old||n<0x1d34||n>0x4000||u32(p,0x118)!==0x1d34)continue;
|
||||
const b=new Uint8Array(0x4000);for(let i=0;i<0x4000;i+=PAGE){if(!save.pages.has(a+i))return null;b.set(save.pages.get(a+i),i);}return b.slice(0,n);
|
||||
}return null;
|
||||
}
|
||||
function paraPetSet(save, edition, ch) {
|
||||
const p0 = paraSettings(save), o = PET[family(edition)];
|
||||
if (!p0 || !o) throw new Error('the save has no settings block');
|
||||
const t = o.tama, p = p0.slice(), pages = new Map(save.pages);
|
||||
const old = u16(p, t + 4);
|
||||
if (ch.level !== undefined) { const v = Math.max(0, Math.min(10, ch.level | 0)), now = p[o.level] & 15; p[o.level] = v > now ? (p[o.level] & 0xF0) | v : (v << 4) | v; }
|
||||
if (ch.id || ch.color!==undefined) {
|
||||
const target=ch.id||old,color=ch.color??-1;
|
||||
if(!Number.isInteger(color)||color< -1||color>15)throw Error('Invalid character color');
|
||||
if(ch.id){p[t + 4] = ch.id & 255; p[t + 5] = ch.id >> 8; p[t + 6] = ch.id & 255; p[t + 7] = ch.id >> 8;}
|
||||
if (ch.stage) p[t + 0x18] = (p[t + 0x18] & ~0x1C) | ((ch.stage & 7) << 2);
|
||||
let ghost=ch.ghost;
|
||||
if(!(ghost instanceof Uint8Array)||ghost.length<0x1d34||ghost.length>0x4000||u32(ghost,8)!==1||u16(ghost,0x10a)!==target||u32(ghost,0x10c)!==ghost.length||((u32(ghost,0)+u32(ghost,4))>>>0)!==0||(color>=0&&ghost[16]!==color))throw Error('Character appearance data is missing or invalid');
|
||||
let found=false;
|
||||
for(const [a,d] of [...save.pages].sort((a,b)=>a[0]-b[0])){
|
||||
if(a===SET_A||a===SET_B||d.length!==PAGE||u32(d,8)!==1||u16(d,12)!==4017||((u32(d,0)+u32(d,4))>>>0)!==0)continue;
|
||||
const n=u32(d,0x10c);if(n<0x1d34||n>0x4000||u32(d,0x118)!==0x1d34)continue;
|
||||
if(u16(d,0x10a)!==old&&u16(d,14)!==old)throw Error('Current character genes do not match this save');
|
||||
if(!ch.id){
|
||||
const current=new Uint8Array(0x4000);for(let i=0;i<0x4000;i+=PAGE){const pg=save.pages.get(a+i);if(!pg)throw Error('Current character slot is incomplete');current.set(pg,i);}
|
||||
const next=current.slice(0,n);next[16]=ghost[16];next.set(ghost.subarray(0x140,0x180),0x140);ghost=next;
|
||||
let sum=0;for(let i=8;i<0x180;i+=4)sum=(sum+u32(ghost,i))>>>0;for(let i=0x600;i<ghost.length;i+=4)sum=(sum+u32(ghost,i))>>>0;w32(ghost,0,sum);w32(ghost,4,-sum>>>0);
|
||||
}
|
||||
for(let i=0;i<0x4000;i+=PAGE){if(a+i>=SET_A||!save.pages.has(a+i))throw Error('Current character slot is incomplete');const pg=new Uint8Array(PAGE);pg.fill(255);pg.set(ghost.subarray(i,i+PAGE));pages.set(a+i,pg);}
|
||||
found=true;break;
|
||||
}
|
||||
if(!found)throw Error('Current character appearance data was not found');
|
||||
p[t+0x19]=(p[t+0x19]&0xe0)|(color<0?31:color);
|
||||
|
||||
}
|
||||
for(const [key,off,max]of [['hunger',0x1C,6],['happy',0x1D,20],['sick',0x10,1]]){
|
||||
if(ch[key]!==undefined){if(!Number.isInteger(ch[key])||ch[key]<0||ch[key]>max)throw Error('저장 데이터 값의 범위를 확인하세요.');p[t+off]=ch[key];}
|
||||
}
|
||||
if (ch.care) { p[t + 0x1C] = 6; p[t + 0x1D] = 20; p[t + 0x10] = 0; }
|
||||
const c = crc16arc(p, 4, PAGE); p[0] = c & 255; p[1] = c >> 8; p[2] = ~c & 255; p[3] = (~c >> 8) & 255;
|
||||
pages.set(SET_A, p); pages.set(SET_B, p.slice());
|
||||
return Object.assign({}, save, { pages });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- TamaEmu
|
||||
const APP_CFG = 0xA0140, PMXC = 0x43584D50, PG_MAGIC = 0x50584D50, PG_MAX = 64;
|
||||
const KINDS = { 0: { dev: 'pc', size: 0x400000, app: 'plus-color' }, 1: { dev: 'idl', size: 0x800000, app: 'idl' },
|
||||
2: { dev: 'ps', size: 0x800000, app: 'ps' }, 3: { dev: '4u', size: 0x800000, app: '4u' }, 4: { dev: '4u-plain', size: 0x800000, app: '4u-plain' } };
|
||||
/** Settings block of the emulator in an image (or the 4 KB sector at 0xA0000). */
|
||||
function emuCfg(sec, base = 0xA0000) {
|
||||
const c = APP_CFG - base;
|
||||
if (u32(sec, c) !== PMXC) return null;
|
||||
const v = u32(sec, c + 4), kind = u32(sec, c + 20);
|
||||
if (!KINDS[kind]) return null;
|
||||
return { version: v, guestOff: u32(sec, c + 8), guestSize: u32(sec, c + 12), saveOff: u32(sec, c + 16), kind, map: sec.slice(c + 24, c + 152), spareEnd: v >= 3 ? u32(sec, c + 152) : 0, lzOff: v >= 5 ? u32(sec, c + 160) : 0, ...KINDS[kind] };
|
||||
}
|
||||
/**
|
||||
* Guest flash (the .sav of the TamaEmu app) from the packed firmware and the spare pages.
|
||||
* read(addr, len) gives bytes of the Paradise flash (sync or async).
|
||||
*/
|
||||
function lzDec(s, n) { // LZ4 block (as emu.js)
|
||||
const d = new Uint8Array(n).fill(0xFF); let ip = 0, op = 0;
|
||||
for (;;) {
|
||||
const t = s[ip++]; let l = t >> 4;
|
||||
if (l === 15) { let x; do { x = s[ip++]; l += x; } while (x === 255); }
|
||||
while (l-- > 0 && op < n) d[op++] = s[ip++];
|
||||
if (op >= n || ip >= s.length) return d;
|
||||
const o = s[ip] | (s[ip + 1] << 8); ip += 2; let m = (t & 15) + 4;
|
||||
if ((t & 15) === 15) { let x; do { x = s[ip++]; m += x; } while (x === 255); }
|
||||
while (m-- > 0 && op < n) { d[op] = d[op - o]; op++; }
|
||||
}
|
||||
}
|
||||
/* 1.7.3 test21 LZ_GONE: TamaEmu notes behind its page table which packed blocks the pet erased (four words, then
|
||||
* their xor with 0x454E4F47). Those blocks read empty, apart from the parts in spare pages (written after this). */
|
||||
function lzGoneApply(t, o, g, size) {
|
||||
if (t.length < o + 20) return;
|
||||
let x = 0x454E4F47; for (let i = 0; i < 4; i++) x = (x ^ u32(t, o + 4 * i)) >>> 0;
|
||||
if (x !== u32(t, o + 16)) return;
|
||||
for (let b = 0; b < 128 && (b << 16) < size; b++) if ((u32(t, o + 4 * (b >> 5)) >>> (b & 31)) & 1) g.fill(0xFF, b << 16, (b + 1) << 16);
|
||||
}
|
||||
async function emuGuestAsync(read, cfg, progress) {
|
||||
const out = new Uint8Array(cfg.size).fill(0xFF), nb = cfg.size >> 16;
|
||||
let done = 0; const todo = [...cfg.map.subarray(0, nb)].filter((k) => k !== 0xFF).length;
|
||||
for (let b = 0; b < nb; b++) {
|
||||
let k = cfg.map[b];
|
||||
if (k === 0xFF) continue;
|
||||
if (k === 0xFE) k = b;
|
||||
out.set(new Uint8Array(await read(cfg.guestOff + (k << 16), 0x10000)), b << 16);
|
||||
if (progress) progress('read', ++done, todo);
|
||||
}
|
||||
// 1.7.3 GUEST_LZ: the packed cold blocks (LZ4 parts of 1 KB, see emu.js lzPack)
|
||||
if (cfg.lzOff) {
|
||||
const t = new Uint8Array(await read(cfg.lzOff, 512));
|
||||
for (let b = 0; b < nb; b++) {
|
||||
const lp = u32(t, 4 * b); if (!lp || cfg.map[b] !== 0xFF) continue;
|
||||
const l = new Uint8Array(await read(cfg.lzOff + lp, 65 * 4)), a0 = u32(l, 0), z0 = u32(l, 256);
|
||||
const raw = z0 > a0 ? new Uint8Array(await read(cfg.lzOff + a0, z0 - a0)) : new Uint8Array(0);
|
||||
for (let k = 0; k < 64; k++) {
|
||||
const a = u32(l, 4 * k) - a0, z = u32(l, 4 * k + 4) - a0, at = (b << 16) + k * 0x400;
|
||||
if (z === a) continue;
|
||||
out.set(z - a >= 0x400 ? raw.subarray(a, a + 0x400) : lzDec(raw.subarray(a, z), 0x400), at);
|
||||
}
|
||||
}
|
||||
}
|
||||
// spare pages (8 KB parts the guest wrote into blocks that are empty in the firmware)
|
||||
if (cfg.spareEnd) {
|
||||
const lo = (cfg.guestOff + cfg.guestSize + 0x1FFF) & ~0x1FFF, hi = cfg.spareEnd & ~0x1FFF;
|
||||
if (hi >= lo + 0x4000) {
|
||||
const data = lo + 0x2000; let n = (hi - data) >> 13; if (n > PG_MAX) n = PG_MAX;
|
||||
const t = new Uint8Array(await read(lo, 16 + 2 * PG_MAX + 20));
|
||||
let x = (PG_MAGIC ^ Math.imul(n, 0x9E3779B1)) >>> 0;
|
||||
for (let i = 0; i < PG_MAX; i++) x = (((x << 5) | (x >>> 27)) ^ u16(t, 16 + 2 * i)) >>> 0;
|
||||
if (u32(t, 0) === PG_MAGIC && u32(t, 4) === n && u32(t, 8) === x) {
|
||||
lzGoneApply(t, 16 + 2 * PG_MAX, out, cfg.size); // 1.7.3 test21 LZ_GONE: packed blocks the pet erased
|
||||
for (let i = 0; i < n; i++) {
|
||||
const v = u16(t, 16 + 2 * i);
|
||||
if (v === 0xFFFF || (v << 13) >= cfg.size) continue;
|
||||
if (cfg.map[(v << 13) >> 16] !== 0xFF) continue; // only blocks that are empty in the firmware
|
||||
out.set(new Uint8Array(await read(data + (i << 13), 0x2000)), v << 13);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- T7Emu
|
||||
/*
|
||||
* The pet's EEPROM (4 KB) in the ROM: two slots of 8 KB from 0x0C1000 (header sector:
|
||||
* "T7EE", sequence, page mask, checksum; then the pages). The T7Emu app keeps it as
|
||||
* save.bin: page mask (2 bytes) and the 16 pages, 4098 bytes. Same content, so it can go back and forth.
|
||||
*/
|
||||
const T7_EE = 0xC1000, T7_EE_MAGIC = 0x45453754, T7_SAVE_LEN = 4098;
|
||||
function t7Sum(b, o) { let s = 0x7E7E; for (let i = 0; i < 4096; i++) s = (Math.imul(s, 31) + b[o + i]) >>> 0; return s; }
|
||||
// test27: up to test26 the T7Emu could write its pages 2 bytes off (the flash DMA takes words, its buffer lay at ...2):
|
||||
// 2 other bytes first, the pages without their last 2. The header sum is over the right pages, so such a slot is found.
|
||||
function t7Sum2(b, o) { let s = 0x7E7E; for (let i = 2; i < 4096; i++) s = (Math.imul(s, 31) + b[o + i]) >>> 0; return Math.imul(Math.imul(s, 31) >>> 0, 31) >>> 0; }
|
||||
function t7Slot(img, at) {
|
||||
if (u32(img, at) !== T7_EE_MAGIC) return null;
|
||||
const sum = u32(img, at + 12), sh = sum === t7Sum(img, at + 0x1000) ? 0 : sum === t7Sum2(img, at + 0x1000) ? 2 : -1;
|
||||
if (sh < 0) return null;
|
||||
return { seq: u32(img, at + 4), have: u32(img, at + 8) & 0xFFFF, at, sh };
|
||||
}
|
||||
function t7Newest(img, ee = T7_EE) { const a = t7Slot(img, ee), b = t7Slot(img, ee + 0x2000); if (a && b) return ((a.seq - b.seq) | 0) > 0 ? a : b; return a || b; }
|
||||
/** save.bin of the T7Emu app from a 16 MB image (null: the pet has no save yet). base: save area of
|
||||
* the T7Emu (0x0C0000, a further one from 1.6.0 its own). */
|
||||
function t7SaveOut(img, base = 0xC0000) {
|
||||
const s = t7Newest(img, base + 0x1000); if (!s) return null;
|
||||
const out = new Uint8Array(T7_SAVE_LEN); out[0] = s.have & 255; out[1] = s.have >> 8;
|
||||
out.set(img.subarray(s.at + 0x1000 + s.sh, s.at + 0x2000), 2); // shifted slot: the last 2 bytes stay 0
|
||||
return out;
|
||||
}
|
||||
function t7SaveCheck(b) { return b && b.length === T7_SAVE_LEN; }
|
||||
/** save.bin into the image: into the older slot, as the device does. Returns a new image. */
|
||||
function t7SaveIn(img, save, base = 0xC0000) {
|
||||
if (!t7SaveCheck(save)) throw new Error('not a T7Emu save (save.bin, 4098 bytes)');
|
||||
const ee = base + 0x1000, out = new Uint8Array(img), cur = t7Newest(img, ee);
|
||||
const at = cur && cur.at === ee ? ee + 0x2000 : ee;
|
||||
out.fill(0xFF, at, at + 0x2000);
|
||||
out.set(save.subarray(2), at + 0x1000);
|
||||
w32(out, at, T7_EE_MAGIC); w32(out, at + 4, cur ? (cur.seq + 1) >>> 0 : 1); w32(out, at + 8, save[0] | (save[1] << 8)); w32(out, at + 12, t7Sum(out, at + 0x1000));
|
||||
out.fill(0xFF, base, base + 0x1000); // the running session belongs to the old pet
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Merge explicit edits into the writer's freshly preserved device save. */
|
||||
function keepEdits(base, edition, names, changes, expectedId, progress) {
|
||||
return async function(dev, image, changed, moves) {
|
||||
const result=await base(dev,image,changed,moves), before=result.image, out=before.slice();
|
||||
if(changes && Object.keys(changes).length){
|
||||
const save={pages:paraFromImage(out,edition),edition};
|
||||
const pet=paraPet(save,edition);
|
||||
if(!pet || (expectedId && pet.id!==expectedId))throw Error('본체의 다마고치가 편집을 시작했을 때와 다릅니다. 본체를 다시 읽고 수정하세요.');
|
||||
const next=paraPetSet(save,edition,changes);
|
||||
for(const [a,d]of next.pages)if(d.length===4096)out.set(d,a);
|
||||
}
|
||||
if(progress){
|
||||
const P=root.ParamixProgress, info=P.profile(out,edition);
|
||||
const next=P.apply({pages:paraFromImage(out,edition),edition},info,progress);
|
||||
for(const a of [SET_A,SET_B])out.set(next.pages.get(a),a);
|
||||
}
|
||||
if(names && names.size)globalThis.ParamixCore.koreanPetNames(out,edition,names);
|
||||
const updated=new Set();
|
||||
for(let a=0;a<out.length;a+=4096){
|
||||
for(let i=a;i<a+4096;i++)if(out[i]!==before[i]){updated.add(a);changed.add(a);break;}
|
||||
}
|
||||
return {...result,image:out,protectedSectors:result.protectedSectors.filter(a=>!updated.has(a))};
|
||||
};
|
||||
}
|
||||
root.ParamixSaves = { paraAppearance, keepEdits, paraPet, paraPetSet, paraWrite, t7SaveOut, t7SaveIn, t7SaveCheck, T7_EE, idPage, region, family, settingsOk, crc16arc, paraFromImage, paraEncode, paraDecode, paraCheck, paraClock, emuCfg, emuGuestAsync, lzGoneApply, KINDS };
|
||||
if (typeof module !== 'undefined') module.exports = root.ParamixSaves;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
/*
|
||||
* Paramix Studio: save games in and out of the Paradise.
|
||||
*
|
||||
* Paradise: the game keeps its progress in the flash after the edition ID page
|
||||
* (0xD4A000, Tropical/Glacier 0xD2A000) up to 0xF00000. Exported as a
|
||||
* .tamasave (format 3 of the TamaParadise app): every page of that region,
|
||||
* the seconds counter of the device and an armed wake alarm, so the app
|
||||
* continues instead of starting like a fresh battery. Behind the pages a
|
||||
* Paramix trailer ("PMXE", edition, region) that the app ignores and the
|
||||
* Studio uses to refuse a save of another edition.
|
||||
*
|
||||
* TamaEmu: the guest's own save is its flash. Exported as the raw image the
|
||||
* TamaEmu app uses (.sav, 4 MB or 8 MB; named after the app's device: plus-color, idl, ps, 4u): packed blocks plus the spare pages
|
||||
* the emulator wrote. Importing a .sav works like choosing a firmware.
|
||||
*
|
||||
* Author: mameise
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
|
||||
const PAGE = 0x1000;
|
||||
const MAGIC = 'TAMASAVE', VERSION = 3, TRAILER = 0x45584D50; // "PMXE"
|
||||
const SET_A = 0xEFE000, SET_B = 0xEFF000, REGION_END = 0xF00000;
|
||||
const u16 = (b, o) => b[o] | (b[o + 1] << 8);
|
||||
const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0;
|
||||
function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; }
|
||||
|
||||
/** Edition 5/6 (Tropical, Glacier) keep their ID page lower. */
|
||||
function idPage(edition) { return edition === 5 || edition === 6 ? 0xD29000 : 0xD49000; }
|
||||
function region(edition) { return [idPage(edition) + PAGE, REGION_END]; }
|
||||
function family(edition) { return edition === 5 || edition === 6 ? 'gen3' : edition === 4 ? 'jade' : 'gen1'; }
|
||||
|
||||
/* Settings block: CRC-16/ARC over bytes 4..4095 at 0, its inverse at 2. */
|
||||
function crc16arc(d, from, to) {
|
||||
let c = 0;
|
||||
for (let i = from; i < to; i++) { c ^= d[i]; for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xA001 : c >>> 1; }
|
||||
return c;
|
||||
}
|
||||
function settingsOk(p) { const c = crc16arc(p, 4, PAGE); return u16(p, 0) === c && u16(p, 2) === (~c & 0xFFFF); }
|
||||
|
||||
// ---------------------------------------------------------------- Paradise
|
||||
/** Pages of the save region from a 16 MB image (all of them, empty ones too). */
|
||||
function paraFromImage(img, edition) {
|
||||
const [a, b] = region(edition), pages = new Map();
|
||||
for (let p = a; p < b; p += PAGE) pages.set(p, img.slice(p, p + PAGE));
|
||||
return pages;
|
||||
}
|
||||
/**
|
||||
* .tamasave from pages (Map address -> 4 KB). clock: { counter, ctrl } of the device or null.
|
||||
*/
|
||||
function paraEncode(pages, edition, clock, now = Math.floor(Date.now() / 1000)) {
|
||||
const counter = clock ? clock.counter >>> 0 : 0;
|
||||
const alarm = counter ? counter - 1 : 0, status = counter ? 0x100 : 0; // armed, as the app does when it puts the console away
|
||||
// the always powered system registers as the app stores them (clock and PLL as the firmware sets them)
|
||||
const regs = counter ? [[0x000, 0xC051], [0x004, 0xA55A0000], [0x00C, 4], [0x010, 0], [0x018, 0x21], [0x020, 0x42], [0x050, 0],
|
||||
[0x100, 0x157EB7], [0x108, 0], [0x10C, 0x1FFFFD], [0x110, 0], [0x200, clock.ctrl & 0x80 ? clock.ctrl >>> 0 : 0xE0], [0x204, 0],
|
||||
[0x210, 0], [0x214, 0], [0x218, 0], [0x230, alarm], [0x234, status], [0x300, 0x10]] : [];
|
||||
const list = [...pages.keys()].sort((x, y) => x - y);
|
||||
const size = 36 + 8 * regs.length + 4 + list.reduce((n, a) => n + 8 + pages.get(a).length, 0) + 16;
|
||||
const out = new Uint8Array(size);
|
||||
for (let i = 0; i < 8; i++) out[i] = MAGIC.charCodeAt(i);
|
||||
w32(out, 8, VERSION);
|
||||
w32(out, 12, counter ? now : 0); w32(out, 16, 0); // u64 time stamp (seconds since 1970)
|
||||
w32(out, 20, counter); w32(out, 24, alarm); w32(out, 28, status); w32(out, 32, regs.length);
|
||||
let o = 36;
|
||||
for (const [k, v] of regs) { w32(out, o, k); w32(out, o + 4, v); o += 8; }
|
||||
w32(out, o, list.length); o += 4;
|
||||
for (const a of list) { const d = pages.get(a); w32(out, o, a / PAGE); w32(out, o + 4, d.length); out.set(d, o + 8); o += 8 + d.length; }
|
||||
w32(out, o, TRAILER); w32(out, o + 4, edition); w32(out, o + 8, region(edition)[0]); w32(out, o + 12, region(edition)[1]);
|
||||
return out;
|
||||
}
|
||||
/** Write a decoded save back as it was (time stamp, clock, registers kept). */
|
||||
function paraWrite(save, edition) {
|
||||
const regs = save.regs || [], list = [...save.pages.keys()].sort((x, y) => x - y);
|
||||
const size = 36 + 8 * regs.length + 4 + list.reduce((n, a) => n + 8 + save.pages.get(a).length, 0) + 16;
|
||||
const out = new Uint8Array(size);
|
||||
for (let i = 0; i < 8; i++) out[i] = MAGIC.charCodeAt(i);
|
||||
w32(out, 8, VERSION);
|
||||
w32(out, 12, save.stamp % 4294967296); w32(out, 16, Math.floor(save.stamp / 4294967296));
|
||||
w32(out, 20, save.counter); w32(out, 24, save.alarm); w32(out, 28, save.status); w32(out, 32, regs.length);
|
||||
let o = 36;
|
||||
for (const [k, v] of regs) { w32(out, o, k); w32(out, o + 4, v); o += 8; }
|
||||
w32(out, o, list.length); o += 4;
|
||||
for (const a of list) { const d = save.pages.get(a); w32(out, o, a / PAGE); w32(out, o + 4, d.length); out.set(d, o + 8); o += 8 + d.length; }
|
||||
const ed = edition || save.edition;
|
||||
w32(out, o, TRAILER); w32(out, o + 4, ed); w32(out, o + 8, region(ed)[0]); w32(out, o + 12, region(ed)[1]);
|
||||
return out;
|
||||
}
|
||||
/** Read a .tamasave (format 3). Throws on anything else. */
|
||||
function paraDecode(b) {
|
||||
if (b.length < 40 || String.fromCharCode(...b.subarray(0, 8)) !== MAGIC) throw new Error('not a Paradise save (.tamasave)');
|
||||
if (u32(b, 8) !== VERSION) throw new Error('unknown save version ' + u32(b, 8));
|
||||
const stamp = u32(b, 12) + u32(b, 16) * 4294967296, counter = u32(b, 20), alarm = u32(b, 24), status = u32(b, 28);
|
||||
const nr = u32(b, 32); let o = 36;
|
||||
const regs = [];
|
||||
for (let i = 0; i < nr; i++) { if (o + 8 > b.length) throw new Error('save is cut off'); regs.push([u32(b, o), u32(b, o + 4)]); o += 8; }
|
||||
if (o + 4 > b.length) throw new Error('save is cut off');
|
||||
const np = u32(b, o); o += 4;
|
||||
const pages = new Map();
|
||||
for (let i = 0; i < np; i++) {
|
||||
if (o + 8 > b.length) throw new Error('save is cut off');
|
||||
const a = u32(b, o) * PAGE, n = u32(b, o + 4); o += 8;
|
||||
if (o + n > b.length) throw new Error('save is cut off');
|
||||
pages.set(a, b.slice(o, o + n)); o += n;
|
||||
}
|
||||
let edition = 0;
|
||||
if (o + 16 <= b.length && u32(b, o) === TRAILER) edition = u32(b, o + 4);
|
||||
return { stamp, counter, alarm, status, regs, pages, edition };
|
||||
}
|
||||
/**
|
||||
* Can this save go onto a device of this edition? Returns { errors, warnings, pages (only the
|
||||
* save region, full 4 KB), complete }.
|
||||
*/
|
||||
function paraCheck(save, edition) {
|
||||
const errors = [], warnings = [], [a, b] = region(edition), pages = new Map();
|
||||
if (save.edition && save.edition !== edition) errors.push({ code: 'saveOtherEd', p: { s: save.edition, d: edition } });
|
||||
let outside = 0;
|
||||
for (const [p, d] of save.pages) {
|
||||
if (p < a || p >= b || d.length !== PAGE) { outside++; continue; }
|
||||
pages.set(p, d);
|
||||
}
|
||||
if (outside) warnings.push({ code: 'saveOutside', p: { n: outside } });
|
||||
const sa = pages.get(SET_A), sb = pages.get(SET_B);
|
||||
const set = sa && settingsOk(sa) ? sa : sb && settingsOk(sb) ? sb : null;
|
||||
if (!set) errors.push({ code: 'saveNoSettings' });
|
||||
else if ((u16(set, 12) === 0x016D) !== (family(edition) === 'gen3')) errors.push({ code: 'saveFamily' });
|
||||
let complete = true;
|
||||
for (let p = a; p < b; p += PAGE) if (!pages.has(p)) { complete = false; break; }
|
||||
if (!complete) warnings.push({ code: 'saveIncomplete' });
|
||||
return { errors, warnings, pages, complete };
|
||||
}
|
||||
/** Seconds counter to set on the device: the saved one plus the time since. */
|
||||
function paraClock(save, now = Math.floor(Date.now() / 1000)) {
|
||||
if (!save.counter || !save.stamp) return null;
|
||||
return (save.counter + Math.max(0, now - save.stamp)) >>> 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- change a Paradise save (1.6.8)
|
||||
// The pet in the settings block: +4/+6 character, +0x10 sickness, +0x18 bits 2..4 stage, +0x1C hunger 0..6,
|
||||
// +0x1D happiness 0..20. Planet level: low nibble = level, high nibble = level already celebrated.
|
||||
const PET = { gen1: { tama: 0x104, level: 0x7C }, jade: { tama: 0x108, level: 0x7C }, gen3: { tama: 0x114, level: 0x88 } };
|
||||
function paraSettings(save) { for (const a of [SET_A, SET_B]) { const p = save.pages.get(a); if (p && p.length === PAGE && settingsOk(p)) return p; } return null; }
|
||||
/** What the save says about the pet: { level, id, stage, hunger, happy, sick } or null. */
|
||||
function paraPet(save, edition) {
|
||||
const p = paraSettings(save), o = PET[family(edition)]; if (!p || !o) return null;
|
||||
const t = o.tama;
|
||||
const color=p[t+0x19]&31;
|
||||
return { level: p[o.level] & 15, id: u16(p, t + 4), stage: (p[t + 0x18] >> 2) & 7, color:color<16?color:-1, hunger: p[t + 0x1C], happy: p[t + 0x1D], sick: p[t + 0x10] };
|
||||
}
|
||||
/**
|
||||
* Changed copy of the save. A character change requires the complete native genes
|
||||
* package from the ROM. Only the current pet's slot is replaced; friends are preserved.
|
||||
*/
|
||||
function paraAppearance(save){
|
||||
const old=paraPet(save,save.edition)?.id;
|
||||
for(const[a,p]of [...save.pages].sort((a,b)=>a[0]-b[0])){
|
||||
const n=u32(p,0x10c);if(u32(p,8)!==1||u16(p,12)!==4017||u16(p,0x10a)!==old||n<0x1d34||n>0x4000||u32(p,0x118)!==0x1d34)continue;
|
||||
const b=new Uint8Array(0x4000);for(let i=0;i<0x4000;i+=PAGE){if(!save.pages.has(a+i))return null;b.set(save.pages.get(a+i),i);}return b.slice(0,n);
|
||||
}return null;
|
||||
}
|
||||
function paraPetSet(save, edition, ch) {
|
||||
const p0 = paraSettings(save), o = PET[family(edition)];
|
||||
if (!p0 || !o) throw new Error('the save has no settings block');
|
||||
const t = o.tama, p = p0.slice(), pages = new Map(save.pages);
|
||||
const old = u16(p, t + 4);
|
||||
if (ch.level !== undefined) { const v = Math.max(0, Math.min(10, ch.level | 0)), now = p[o.level] & 15; p[o.level] = v > now ? (p[o.level] & 0xF0) | v : (v << 4) | v; }
|
||||
if (ch.id || ch.color!==undefined) {
|
||||
const target=ch.id||old,color=ch.color??-1;
|
||||
if(!Number.isInteger(color)||color< -1||color>15)throw Error('Invalid character color');
|
||||
if(ch.id){p[t + 4] = ch.id & 255; p[t + 5] = ch.id >> 8; p[t + 6] = ch.id & 255; p[t + 7] = ch.id >> 8;}
|
||||
if (ch.stage) p[t + 0x18] = (p[t + 0x18] & ~0x1C) | ((ch.stage & 7) << 2);
|
||||
let ghost=ch.ghost;
|
||||
if(!(ghost instanceof Uint8Array)||ghost.length<0x1d34||ghost.length>0x4000||u32(ghost,8)!==1||u16(ghost,0x10a)!==target||u32(ghost,0x10c)!==ghost.length||((u32(ghost,0)+u32(ghost,4))>>>0)!==0||(color>=0&&ghost[16]!==color))throw Error('Character appearance data is missing or invalid');
|
||||
let found=false;
|
||||
for(const [a,d] of [...save.pages].sort((a,b)=>a[0]-b[0])){
|
||||
if(a===SET_A||a===SET_B||d.length!==PAGE||u32(d,8)!==1||u16(d,12)!==4017||((u32(d,0)+u32(d,4))>>>0)!==0)continue;
|
||||
const n=u32(d,0x10c);if(n<0x1d34||n>0x4000||u32(d,0x118)!==0x1d34)continue;
|
||||
if(u16(d,0x10a)!==old&&u16(d,14)!==old)throw Error('Current character genes do not match this save');
|
||||
if(!ch.id){
|
||||
const current=new Uint8Array(0x4000);for(let i=0;i<0x4000;i+=PAGE){const pg=save.pages.get(a+i);if(!pg)throw Error('Current character slot is incomplete');current.set(pg,i);}
|
||||
const next=current.slice(0,n);next[16]=ghost[16];next.set(ghost.subarray(0x140,0x180),0x140);ghost=next;
|
||||
let sum=0;for(let i=8;i<0x180;i+=4)sum=(sum+u32(ghost,i))>>>0;for(let i=0x600;i<ghost.length;i+=4)sum=(sum+u32(ghost,i))>>>0;w32(ghost,0,sum);w32(ghost,4,-sum>>>0);
|
||||
}
|
||||
for(let i=0;i<0x4000;i+=PAGE){if(a+i>=SET_A||!save.pages.has(a+i))throw Error('Current character slot is incomplete');const pg=new Uint8Array(PAGE);pg.fill(255);pg.set(ghost.subarray(i,i+PAGE));pages.set(a+i,pg);}
|
||||
found=true;break;
|
||||
}
|
||||
if(!found)throw Error('Current character appearance data was not found');
|
||||
p[t+0x19]=(p[t+0x19]&0xe0)|(color<0?31:color);
|
||||
|
||||
}
|
||||
for(const [key,off,max]of [['hunger',0x1C,6],['happy',0x1D,20],['sick',0x10,1]]){
|
||||
if(ch[key]!==undefined){if(!Number.isInteger(ch[key])||ch[key]<0||ch[key]>max)throw Error('저장 데이터 값의 범위를 확인하세요.');p[t+off]=ch[key];}
|
||||
}
|
||||
if (ch.care) { p[t + 0x1C] = 6; p[t + 0x1D] = 20; p[t + 0x10] = 0; }
|
||||
const c = crc16arc(p, 4, PAGE); p[0] = c & 255; p[1] = c >> 8; p[2] = ~c & 255; p[3] = (~c >> 8) & 255;
|
||||
pages.set(SET_A, p); pages.set(SET_B, p.slice());
|
||||
return Object.assign({}, save, { pages });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- TamaEmu
|
||||
const APP_CFG = 0xA0140, PMXC = 0x43584D50, PG_MAGIC = 0x50584D50, PG_MAX = 64;
|
||||
const KINDS = { 0: { dev: 'pc', size: 0x400000, app: 'plus-color' }, 1: { dev: 'idl', size: 0x800000, app: 'idl' },
|
||||
2: { dev: 'ps', size: 0x800000, app: 'ps' }, 3: { dev: '4u', size: 0x800000, app: '4u' }, 4: { dev: '4u-plain', size: 0x800000, app: '4u-plain' } };
|
||||
/** Settings block of the emulator in an image (or the 4 KB sector at 0xA0000). */
|
||||
function emuCfg(sec, base = 0xA0000) {
|
||||
const c = APP_CFG - base;
|
||||
if (u32(sec, c) !== PMXC) return null;
|
||||
const v = u32(sec, c + 4), kind = u32(sec, c + 20);
|
||||
if (!KINDS[kind]) return null;
|
||||
return { version: v, guestOff: u32(sec, c + 8), guestSize: u32(sec, c + 12), saveOff: u32(sec, c + 16), kind, map: sec.slice(c + 24, c + 152), spareEnd: v >= 3 ? u32(sec, c + 152) : 0, lzOff: v >= 5 ? u32(sec, c + 160) : 0, ...KINDS[kind] };
|
||||
}
|
||||
/**
|
||||
* Guest flash (the .sav of the TamaEmu app) from the packed firmware and the spare pages.
|
||||
* read(addr, len) gives bytes of the Paradise flash (sync or async).
|
||||
*/
|
||||
function lzDec(s, n) { // LZ4 block (as emu.js)
|
||||
const d = new Uint8Array(n).fill(0xFF); let ip = 0, op = 0;
|
||||
for (;;) {
|
||||
const t = s[ip++]; let l = t >> 4;
|
||||
if (l === 15) { let x; do { x = s[ip++]; l += x; } while (x === 255); }
|
||||
while (l-- > 0 && op < n) d[op++] = s[ip++];
|
||||
if (op >= n || ip >= s.length) return d;
|
||||
const o = s[ip] | (s[ip + 1] << 8); ip += 2; let m = (t & 15) + 4;
|
||||
if ((t & 15) === 15) { let x; do { x = s[ip++]; m += x; } while (x === 255); }
|
||||
while (m-- > 0 && op < n) { d[op] = d[op - o]; op++; }
|
||||
}
|
||||
}
|
||||
/* 1.7.3 test21 LZ_GONE: TamaEmu notes behind its page table which packed blocks the pet erased (four words, then
|
||||
* their xor with 0x454E4F47). Those blocks read empty, apart from the parts in spare pages (written after this). */
|
||||
function lzGoneApply(t, o, g, size) {
|
||||
if (t.length < o + 20) return;
|
||||
let x = 0x454E4F47; for (let i = 0; i < 4; i++) x = (x ^ u32(t, o + 4 * i)) >>> 0;
|
||||
if (x !== u32(t, o + 16)) return;
|
||||
for (let b = 0; b < 128 && (b << 16) < size; b++) if ((u32(t, o + 4 * (b >> 5)) >>> (b & 31)) & 1) g.fill(0xFF, b << 16, (b + 1) << 16);
|
||||
}
|
||||
async function emuGuestAsync(read, cfg, progress) {
|
||||
const out = new Uint8Array(cfg.size).fill(0xFF), nb = cfg.size >> 16;
|
||||
let done = 0; const todo = [...cfg.map.subarray(0, nb)].filter((k) => k !== 0xFF).length;
|
||||
for (let b = 0; b < nb; b++) {
|
||||
let k = cfg.map[b];
|
||||
if (k === 0xFF) continue;
|
||||
if (k === 0xFE) k = b;
|
||||
out.set(new Uint8Array(await read(cfg.guestOff + (k << 16), 0x10000)), b << 16);
|
||||
if (progress) progress('read', ++done, todo);
|
||||
}
|
||||
// 1.7.3 GUEST_LZ: the packed cold blocks (LZ4 parts of 1 KB, see emu.js lzPack)
|
||||
if (cfg.lzOff) {
|
||||
const t = new Uint8Array(await read(cfg.lzOff, 512));
|
||||
for (let b = 0; b < nb; b++) {
|
||||
const lp = u32(t, 4 * b); if (!lp || cfg.map[b] !== 0xFF) continue;
|
||||
const l = new Uint8Array(await read(cfg.lzOff + lp, 65 * 4)), a0 = u32(l, 0), z0 = u32(l, 256);
|
||||
const raw = z0 > a0 ? new Uint8Array(await read(cfg.lzOff + a0, z0 - a0)) : new Uint8Array(0);
|
||||
for (let k = 0; k < 64; k++) {
|
||||
const a = u32(l, 4 * k) - a0, z = u32(l, 4 * k + 4) - a0, at = (b << 16) + k * 0x400;
|
||||
if (z === a) continue;
|
||||
out.set(z - a >= 0x400 ? raw.subarray(a, a + 0x400) : lzDec(raw.subarray(a, z), 0x400), at);
|
||||
}
|
||||
}
|
||||
}
|
||||
// spare pages (8 KB parts the guest wrote into blocks that are empty in the firmware)
|
||||
if (cfg.spareEnd) {
|
||||
const lo = (cfg.guestOff + cfg.guestSize + 0x1FFF) & ~0x1FFF, hi = cfg.spareEnd & ~0x1FFF;
|
||||
if (hi >= lo + 0x4000) {
|
||||
const data = lo + 0x2000; let n = (hi - data) >> 13; if (n > PG_MAX) n = PG_MAX;
|
||||
const t = new Uint8Array(await read(lo, 16 + 2 * PG_MAX + 20));
|
||||
let x = (PG_MAGIC ^ Math.imul(n, 0x9E3779B1)) >>> 0;
|
||||
for (let i = 0; i < PG_MAX; i++) x = (((x << 5) | (x >>> 27)) ^ u16(t, 16 + 2 * i)) >>> 0;
|
||||
if (u32(t, 0) === PG_MAGIC && u32(t, 4) === n && u32(t, 8) === x) {
|
||||
lzGoneApply(t, 16 + 2 * PG_MAX, out, cfg.size); // 1.7.3 test21 LZ_GONE: packed blocks the pet erased
|
||||
for (let i = 0; i < n; i++) {
|
||||
const v = u16(t, 16 + 2 * i);
|
||||
if (v === 0xFFFF || (v << 13) >= cfg.size) continue;
|
||||
if (cfg.map[(v << 13) >> 16] !== 0xFF) continue; // only blocks that are empty in the firmware
|
||||
out.set(new Uint8Array(await read(data + (i << 13), 0x2000)), v << 13);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- T7Emu
|
||||
/*
|
||||
* The pet's EEPROM (4 KB) in the ROM: two slots of 8 KB from 0x0C1000 (header sector:
|
||||
* "T7EE", sequence, page mask, checksum; then the pages). The T7Emu app keeps it as
|
||||
* save.bin: page mask (2 bytes) and the 16 pages, 4098 bytes. Same content, so it can go back and forth.
|
||||
*/
|
||||
const T7_EE = 0xC1000, T7_EE_MAGIC = 0x45453754, T7_SAVE_LEN = 4098;
|
||||
function t7Sum(b, o) { let s = 0x7E7E; for (let i = 0; i < 4096; i++) s = (Math.imul(s, 31) + b[o + i]) >>> 0; return s; }
|
||||
// test27: up to test26 the T7Emu could write its pages 2 bytes off (the flash DMA takes words, its buffer lay at ...2):
|
||||
// 2 other bytes first, the pages without their last 2. The header sum is over the right pages, so such a slot is found.
|
||||
function t7Sum2(b, o) { let s = 0x7E7E; for (let i = 2; i < 4096; i++) s = (Math.imul(s, 31) + b[o + i]) >>> 0; return Math.imul(Math.imul(s, 31) >>> 0, 31) >>> 0; }
|
||||
function t7Slot(img, at) {
|
||||
if (u32(img, at) !== T7_EE_MAGIC) return null;
|
||||
const sum = u32(img, at + 12), sh = sum === t7Sum(img, at + 0x1000) ? 0 : sum === t7Sum2(img, at + 0x1000) ? 2 : -1;
|
||||
if (sh < 0) return null;
|
||||
return { seq: u32(img, at + 4), have: u32(img, at + 8) & 0xFFFF, at, sh };
|
||||
}
|
||||
function t7Newest(img, ee = T7_EE) { const a = t7Slot(img, ee), b = t7Slot(img, ee + 0x2000); if (a && b) return ((a.seq - b.seq) | 0) > 0 ? a : b; return a || b; }
|
||||
/** save.bin of the T7Emu app from a 16 MB image (null: the pet has no save yet). base: save area of
|
||||
* the T7Emu (0x0C0000, a further one from 1.6.0 its own). */
|
||||
function t7SaveOut(img, base = 0xC0000) {
|
||||
const s = t7Newest(img, base + 0x1000); if (!s) return null;
|
||||
const out = new Uint8Array(T7_SAVE_LEN); out[0] = s.have & 255; out[1] = s.have >> 8;
|
||||
out.set(img.subarray(s.at + 0x1000 + s.sh, s.at + 0x2000), 2); // shifted slot: the last 2 bytes stay 0
|
||||
return out;
|
||||
}
|
||||
function t7SaveCheck(b) { return b && b.length === T7_SAVE_LEN; }
|
||||
/** save.bin into the image: into the older slot, as the device does. Returns a new image. */
|
||||
function t7SaveIn(img, save, base = 0xC0000) {
|
||||
if (!t7SaveCheck(save)) throw new Error('not a T7Emu save (save.bin, 4098 bytes)');
|
||||
const ee = base + 0x1000, out = new Uint8Array(img), cur = t7Newest(img, ee);
|
||||
const at = cur && cur.at === ee ? ee + 0x2000 : ee;
|
||||
out.fill(0xFF, at, at + 0x2000);
|
||||
out.set(save.subarray(2), at + 0x1000);
|
||||
w32(out, at, T7_EE_MAGIC); w32(out, at + 4, cur ? (cur.seq + 1) >>> 0 : 1); w32(out, at + 8, save[0] | (save[1] << 8)); w32(out, at + 12, t7Sum(out, at + 0x1000));
|
||||
out.fill(0xFF, base, base + 0x1000); // the running session belongs to the old pet
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Merge explicit edits into the writer's freshly preserved device save. */
|
||||
function keepEdits(base, edition, names, changes, expectedId, progress) {
|
||||
return async function(dev, image, changed, moves) {
|
||||
const result=await base(dev,image,changed,moves), before=result.image, out=before.slice();
|
||||
if(changes && Object.keys(changes).length){
|
||||
const save={pages:paraFromImage(out,edition),edition};
|
||||
const pet=paraPet(save,edition);
|
||||
if(!pet || (expectedId && pet.id!==expectedId))throw Error('본체의 다마고치가 편집을 시작했을 때와 다릅니다. 본체를 다시 읽고 수정하세요.');
|
||||
const next=paraPetSet(save,edition,changes);
|
||||
for(const [a,d]of next.pages)if(d.length===4096)out.set(d,a);
|
||||
}
|
||||
if(progress){
|
||||
const P=root.ParamixProgress, info=P.profile(out,edition);
|
||||
const next=P.apply({pages:paraFromImage(out,edition),edition},info,progress);
|
||||
for(const a of [SET_A,SET_B])out.set(next.pages.get(a),a);
|
||||
}
|
||||
if(names && names.size)globalThis.ParamixCore.koreanPetNames(out,edition,names);
|
||||
const updated=new Set();
|
||||
for(let a=0;a<out.length;a+=4096){
|
||||
for(let i=a;i<a+4096;i++)if(out[i]!==before[i]){updated.add(a);changed.add(a);break;}
|
||||
}
|
||||
return {...result,image:out,protectedSectors:result.protectedSectors.filter(a=>!updated.has(a))};
|
||||
};
|
||||
}
|
||||
root.ParamixSaves = { paraAppearance, keepEdits, paraPet, paraPetSet, paraWrite, t7SaveOut, t7SaveIn, t7SaveCheck, T7_EE, idPage, region, family, settingsOk, crc16arc, paraFromImage, paraEncode, paraDecode, paraCheck, paraClock, emuCfg, emuGuestAsync, lzGoneApply, KINDS };
|
||||
if (typeof module !== 'undefined') module.exports = root.ParamixSaves;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
+1049
-1049
File diff suppressed because it is too large.
Load diff
+213
-213
@@ -1,213 +1,213 @@
|
||||
/*
|
||||
* Paramix Studio 1.6.9: simulated playdate partner for the Tamagotchi Paradise.
|
||||
*
|
||||
* The Paradise talks on its contacts (UART, 460800 8-N-1) with the "TCP" protocol described by GMMan
|
||||
* (tama-para-research, protocols/tcp.md and playdate.md). The Studio plays the other device: the player
|
||||
* starts a playdate on the Paradise and presses B there, so the Paradise is the initiator and we answer.
|
||||
*
|
||||
* Flow as recipient (measured with two emulated consoles):
|
||||
* < PKT 2 session ID (type bit 4), 2 random bytes
|
||||
* < PKT 131092 ghost package + planet screenshot + playdate data (0x20014 bytes)
|
||||
* > PKT 131092 our answer: their own package with the chosen edition (rom_type) and our own IDs
|
||||
* < PKT 2 friendship level
|
||||
* ECHO REQ / ECHO REP while the animation runs
|
||||
* < PKT 4 play result (u16 result, bit 0 of the next u16: breeding possible)
|
||||
* with breeding: we answer "BREED 0" and "SYNC 1" (we never breed)
|
||||
*
|
||||
* No game data is in here: the visitor is a copy of the player's own Tama, only the edition and the IDs
|
||||
* are ours. The chunks use the same link key as the flash app loader (src/flash.js). Transport free:
|
||||
* send(bytes) out, feed(bytes) in, so the same code runs in the test.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const ED = { land: 1, water: 2, sky: 3, jade: 4, tropics: 5, glacier: 6 };
|
||||
const PD = 0x20000; // playdate data in the phase 1 packet
|
||||
const enc = (s) => new TextEncoder().encode(s);
|
||||
|
||||
function crc16(d) {
|
||||
let c = 0;
|
||||
for (let i = 0; i < d.length; i++) { c ^= d[i]; for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xA001 : c >>> 1; }
|
||||
return c;
|
||||
}
|
||||
async function sha256(u) {
|
||||
const c = (root.crypto && root.crypto.subtle) ? root.crypto : (typeof require === 'function' ? require('crypto').webcrypto : null);
|
||||
return new Uint8Array(await c.subtle.digest('SHA-256', u));
|
||||
}
|
||||
async function keystream(nonce, key) {
|
||||
const m = new Uint8Array(4 + key.length); m.set(nonce, 0); m.set(key, 4);
|
||||
return sha256(m);
|
||||
}
|
||||
/* encrypt and decrypt are the same: XOR with the keystream, each key byte becomes 2k+1 after use */
|
||||
async function crypt(nonce, key, data) {
|
||||
const k = await keystream(nonce, key), out = new Uint8Array(data.length);
|
||||
for (let i = 0; i < data.length; i++) { const j = i & 31; out[i] = data[i] ^ k[j]; k[j] = (k[j] * 2 + 1) & 255; }
|
||||
return out;
|
||||
}
|
||||
function rnd4() {
|
||||
const n = new Uint8Array(4);
|
||||
if (root.crypto && root.crypto.getRandomValues) root.crypto.getRandomValues(n);
|
||||
else for (let i = 0; i < 4; i++) n[i] = Math.random() * 256 | 0;
|
||||
return n;
|
||||
}
|
||||
const u32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
|
||||
const w16 = (b, o, v) => { b[o] = v & 255; b[o + 1] = v >> 8 & 255; };
|
||||
const w32 = (b, o, v) => { b[o] = v & 255; b[o + 1] = v >> 8 & 255; b[o + 2] = v >> 16 & 255; b[o + 3] = v >>> 24; };
|
||||
|
||||
/* the link key: 32 characters, as text or as the bytes of the key file */
|
||||
function parseKey(x) {
|
||||
let s = typeof x === 'string' ? x : new TextDecoder('latin1').decode(x);
|
||||
s = s.trim();
|
||||
if (!/^[\x21-\x7e]{16,64}$/.test(s)) return null;
|
||||
return enc(s);
|
||||
}
|
||||
|
||||
/*
|
||||
* opts: { edition: 'water' | 1..6, key: Uint8Array, send: async (Uint8Array) => {}, log: (event, info) => {} }
|
||||
* Returns { feed(Uint8Array), stop(), state }.
|
||||
* log events: 'start', 'packet' {kind}, 'sent', 'result' {result, breed}, 'done', 'error' {text}
|
||||
*/
|
||||
function createVisitor(opts) {
|
||||
const ed = typeof opts.edition === 'number' ? opts.edition : ED[String(opts.edition).toLowerCase()];
|
||||
if (!ed) throw new Error('unknown edition');
|
||||
const key = opts.key, log = opts.log || (() => {});
|
||||
const st = { phase: 'wait', sid: 0, got: 0, stopped: false, result: null };
|
||||
let buf = new Uint8Array(0);
|
||||
let need = 0; // > 0: a chunk of this size is expected
|
||||
let rx = null; // packet coming in
|
||||
let tx = null; // packet going out
|
||||
let echo = null, queue = Promise.resolve();
|
||||
const out = (s) => opts.send(typeof s === 'string' ? enc(s) : s);
|
||||
const line = (s) => out(s + '\r\n');
|
||||
|
||||
function idle(on) {
|
||||
clearInterval(echo); echo = null;
|
||||
// the other device pings every 3 to 4 s while nothing is sent; we do the same so it sees us
|
||||
if (on && !st.stopped) echo = setInterval(() => { if (!tx && !rx && !need) line('ECHO REQ').catch(() => {}); }, 3000);
|
||||
}
|
||||
async function sendPacket(data, type) {
|
||||
tx = { data, type, idx: 0, n: Math.ceil(data.length / 0x1000), tries: 0, done: null };
|
||||
const p = new Promise((res, rej) => { tx.done = res; tx.fail = rej; });
|
||||
await line('PKT ' + data.length);
|
||||
tx.timer = setTimeout(retryPkt, 2000);
|
||||
return p;
|
||||
}
|
||||
function retryPkt() {
|
||||
if (!tx || st.stopped) return;
|
||||
if (++tx.tries >= 3) { const f = tx.fail; tx = null; line('CAN').catch(() => {}); f(new Error('no ACK')); return; }
|
||||
line('PKT ' + tx.data.length).catch(() => {}); tx.timer = setTimeout(retryPkt, 2000);
|
||||
}
|
||||
async function sendChunk() {
|
||||
const i = tx.idx, d = tx.data.subarray(i * 0x1000, Math.min(tx.data.length, (i + 1) * 0x1000));
|
||||
const p = new Uint8Array(12 + d.length);
|
||||
w32(p, 0, st.sid); p[4] = 0x54; p[5] = 0x43; p[6] = 0x50; p[7] = tx.type; p[8] = i; p[9] = 255 - i; w16(p, 10, crc16(d)); p.set(d, 12);
|
||||
const n = rnd4(), c = await crypt(n, key, p), all = new Uint8Array(4 + c.length);
|
||||
all.set(n, 0); all.set(c, 4);
|
||||
clearTimeout(tx.timer); tx.timer = setTimeout(() => { if (tx && ++tx.tries < 3) sendChunk().catch(() => {}); else if (tx) { const f = tx.fail; tx = null; f(new Error('no ACK for a chunk')); } }, 5000);
|
||||
await out(all);
|
||||
}
|
||||
function onAck() {
|
||||
if (!tx) return;
|
||||
tx.tries = 0;
|
||||
if (tx.started) tx.idx++;
|
||||
tx.started = true;
|
||||
if (tx.idx >= tx.n) { clearTimeout(tx.timer); const d = tx.done; tx = null; d(); return; }
|
||||
sendChunk().catch((e) => fail(e));
|
||||
}
|
||||
|
||||
function answer(their) {
|
||||
if (their.length < PD + 0x14) return null;
|
||||
const a = their.slice();
|
||||
w16(a, PD, 0); // force_send_away: never
|
||||
w16(a, PD + 2, ed); // rom_type: the chosen edition
|
||||
w32(a, PD + 4, 0x504D5800 | ed); // device UID of the simulated device ("PMX" + edition)
|
||||
w32(a, PD + 8, (u32(their, PD + 8) ^ 0x5A5A0000 ^ ed) >>> 0); // character UID: theirs, changed
|
||||
return a;
|
||||
}
|
||||
async function packet(d, type) {
|
||||
st.got++;
|
||||
if (type & 0x10) { log('packet', { kind: 'session' }); return; }
|
||||
if (d.length === 0x20014) {
|
||||
log('packet', { kind: 'data', ed: u32(d, PD) >>> 16 });
|
||||
st.phase = 'send';
|
||||
const a = answer(d);
|
||||
await new Promise((r) => setTimeout(r, 150)); // the other device also waits a moment before it answers
|
||||
await sendPacket(a, type & 15);
|
||||
st.phase = 'play'; log('sent', {}); idle(true);
|
||||
return;
|
||||
}
|
||||
if (d.length === 2) { log('packet', { kind: 'friendship', level: d[0] | d[1] << 8 }); return; }
|
||||
if (d.length === 4) {
|
||||
const result = d[0] | d[1] << 8, breed = !!(d[2] & 1);
|
||||
st.result = result; log('result', { result, breed });
|
||||
if (breed) { await line('BREED 0'); await line('SYNC 1'); return; }
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
log('packet', { kind: 'other', n: d.length });
|
||||
}
|
||||
function finish() { if (st.phase === 'done') return; st.phase = 'done'; idle(false); log('done', { result: st.result }); }
|
||||
function fail(e) { if (st.stopped) return; idle(false); st.phase = 'error'; log('error', { text: e && e.message || String(e) }); }
|
||||
|
||||
async function chunk(c) {
|
||||
const n = c.subarray(0, 4), p = await crypt(n, key, c.subarray(4));
|
||||
const sid = u32(p, 0), type = p[7], idx = p[8], crc = p[10] | p[11] << 8, d = p.subarray(12);
|
||||
const ok = p[4] === 0x54 && p[5] === 0x43 && p[6] === 0x50 && p[9] === 255 - idx && crc16(d) === crc && (!st.sid || (type & 0x10) || sid === st.sid);
|
||||
if (!ok) { need = c.length; await line('NAK'); if (!st.badKey && p[4] !== 0x54) { st.badKey = true; log('error', { text: 'key' }); } return; }
|
||||
if (idx !== rx.idx) { need = c.length; await line('ENQ ' + rx.idx); return; }
|
||||
if (type & 0x10) st.sid = sid;
|
||||
rx.data.set(d, rx.off); rx.off += d.length; rx.idx++;
|
||||
const left = rx.n - rx.off;
|
||||
need = left > 0 ? 16 + Math.min(0x1000, left) : 0;
|
||||
await line('ACK');
|
||||
if (!left) { const r = rx; rx = null; packet(r.data, type).catch(fail); }
|
||||
}
|
||||
async function command(s) {
|
||||
const w = s.trim().split(/\s+/);
|
||||
if (!w[0]) return;
|
||||
if (w[0] === 'PKT') {
|
||||
const n = +w[1];
|
||||
if (!(n > 0 && n <= 0x100000)) return;
|
||||
if (st.phase === 'wait' && !st.started) { st.started = true; log('start', {}); }
|
||||
rx = { n, off: 0, idx: 0, data: new Uint8Array(n) };
|
||||
need = 16 + Math.min(0x1000, n);
|
||||
await line('ACK');
|
||||
return;
|
||||
}
|
||||
if (w[0] === 'ACK') { onAck(); return; }
|
||||
if (w[0] === 'NAK') { if (tx && tx.started) sendChunk().catch(fail); return; }
|
||||
if (w[0] === 'ENQ') { if (tx) { tx.idx = +w[1] || 0; tx.started = true; sendChunk().catch(fail); } return; }
|
||||
if (w[0] === 'CAN') { if (tx) { const f = tx.fail; tx = null; f(new Error('cancelled by the Paradise')); } else if (st.phase !== 'done') fail(new Error('cancelled by the Paradise')); return; }
|
||||
if (w[0] === 'ECHO') { if (w[1] === 'REQ') await line('ECHO REP'); return; }
|
||||
if (w[0] === 'SYNC') return; // we sent ours with BREED 0
|
||||
}
|
||||
async function pump() {
|
||||
for (;;) {
|
||||
if (need) {
|
||||
if (buf.length < need) return;
|
||||
const c = buf.slice(0, need); buf = buf.slice(need); need = 0;
|
||||
await chunk(c);
|
||||
continue;
|
||||
}
|
||||
let j = -1;
|
||||
for (let i = 0; i + 1 < buf.length; i++) if (buf[i] === 13 && buf[i + 1] === 10) { j = i; break; }
|
||||
if (j < 0) { if (buf.length > 256) buf = buf.slice(buf.length - 64); return; }
|
||||
const s = new TextDecoder('latin1').decode(buf.subarray(0, j)); buf = buf.slice(j + 2);
|
||||
await command(s);
|
||||
}
|
||||
}
|
||||
return {
|
||||
state: st,
|
||||
feed(bytes) {
|
||||
if (st.stopped) return queue;
|
||||
const b = new Uint8Array(buf.length + bytes.length); b.set(buf, 0); b.set(bytes, buf.length); buf = b;
|
||||
queue = queue.then(pump).catch(fail);
|
||||
return queue;
|
||||
},
|
||||
stop() { st.stopped = true; idle(false); if (tx) clearTimeout(tx.timer); tx = null; rx = null; },
|
||||
};
|
||||
}
|
||||
|
||||
const api = { ED, createVisitor, parseKey, crypt, crc16 };
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.ParamixVisit = api;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
/*
|
||||
* Paramix Studio 1.6.9: simulated playdate partner for the Tamagotchi Paradise.
|
||||
*
|
||||
* The Paradise talks on its contacts (UART, 460800 8-N-1) with the "TCP" protocol described by GMMan
|
||||
* (tama-para-research, protocols/tcp.md and playdate.md). The Studio plays the other device: the player
|
||||
* starts a playdate on the Paradise and presses B there, so the Paradise is the initiator and we answer.
|
||||
*
|
||||
* Flow as recipient (measured with two emulated consoles):
|
||||
* < PKT 2 session ID (type bit 4), 2 random bytes
|
||||
* < PKT 131092 ghost package + planet screenshot + playdate data (0x20014 bytes)
|
||||
* > PKT 131092 our answer: their own package with the chosen edition (rom_type) and our own IDs
|
||||
* < PKT 2 friendship level
|
||||
* ECHO REQ / ECHO REP while the animation runs
|
||||
* < PKT 4 play result (u16 result, bit 0 of the next u16: breeding possible)
|
||||
* with breeding: we answer "BREED 0" and "SYNC 1" (we never breed)
|
||||
*
|
||||
* No game data is in here: the visitor is a copy of the player's own Tama, only the edition and the IDs
|
||||
* are ours. The chunks use the same link key as the flash app loader (src/flash.js). Transport free:
|
||||
* send(bytes) out, feed(bytes) in, so the same code runs in the test.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const ED = { land: 1, water: 2, sky: 3, jade: 4, tropics: 5, glacier: 6 };
|
||||
const PD = 0x20000; // playdate data in the phase 1 packet
|
||||
const enc = (s) => new TextEncoder().encode(s);
|
||||
|
||||
function crc16(d) {
|
||||
let c = 0;
|
||||
for (let i = 0; i < d.length; i++) { c ^= d[i]; for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xA001 : c >>> 1; }
|
||||
return c;
|
||||
}
|
||||
async function sha256(u) {
|
||||
const c = (root.crypto && root.crypto.subtle) ? root.crypto : (typeof require === 'function' ? require('crypto').webcrypto : null);
|
||||
return new Uint8Array(await c.subtle.digest('SHA-256', u));
|
||||
}
|
||||
async function keystream(nonce, key) {
|
||||
const m = new Uint8Array(4 + key.length); m.set(nonce, 0); m.set(key, 4);
|
||||
return sha256(m);
|
||||
}
|
||||
/* encrypt and decrypt are the same: XOR with the keystream, each key byte becomes 2k+1 after use */
|
||||
async function crypt(nonce, key, data) {
|
||||
const k = await keystream(nonce, key), out = new Uint8Array(data.length);
|
||||
for (let i = 0; i < data.length; i++) { const j = i & 31; out[i] = data[i] ^ k[j]; k[j] = (k[j] * 2 + 1) & 255; }
|
||||
return out;
|
||||
}
|
||||
function rnd4() {
|
||||
const n = new Uint8Array(4);
|
||||
if (root.crypto && root.crypto.getRandomValues) root.crypto.getRandomValues(n);
|
||||
else for (let i = 0; i < 4; i++) n[i] = Math.random() * 256 | 0;
|
||||
return n;
|
||||
}
|
||||
const u32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
|
||||
const w16 = (b, o, v) => { b[o] = v & 255; b[o + 1] = v >> 8 & 255; };
|
||||
const w32 = (b, o, v) => { b[o] = v & 255; b[o + 1] = v >> 8 & 255; b[o + 2] = v >> 16 & 255; b[o + 3] = v >>> 24; };
|
||||
|
||||
/* the link key: 32 characters, as text or as the bytes of the key file */
|
||||
function parseKey(x) {
|
||||
let s = typeof x === 'string' ? x : new TextDecoder('latin1').decode(x);
|
||||
s = s.trim();
|
||||
if (!/^[\x21-\x7e]{16,64}$/.test(s)) return null;
|
||||
return enc(s);
|
||||
}
|
||||
|
||||
/*
|
||||
* opts: { edition: 'water' | 1..6, key: Uint8Array, send: async (Uint8Array) => {}, log: (event, info) => {} }
|
||||
* Returns { feed(Uint8Array), stop(), state }.
|
||||
* log events: 'start', 'packet' {kind}, 'sent', 'result' {result, breed}, 'done', 'error' {text}
|
||||
*/
|
||||
function createVisitor(opts) {
|
||||
const ed = typeof opts.edition === 'number' ? opts.edition : ED[String(opts.edition).toLowerCase()];
|
||||
if (!ed) throw new Error('unknown edition');
|
||||
const key = opts.key, log = opts.log || (() => {});
|
||||
const st = { phase: 'wait', sid: 0, got: 0, stopped: false, result: null };
|
||||
let buf = new Uint8Array(0);
|
||||
let need = 0; // > 0: a chunk of this size is expected
|
||||
let rx = null; // packet coming in
|
||||
let tx = null; // packet going out
|
||||
let echo = null, queue = Promise.resolve();
|
||||
const out = (s) => opts.send(typeof s === 'string' ? enc(s) : s);
|
||||
const line = (s) => out(s + '\r\n');
|
||||
|
||||
function idle(on) {
|
||||
clearInterval(echo); echo = null;
|
||||
// the other device pings every 3 to 4 s while nothing is sent; we do the same so it sees us
|
||||
if (on && !st.stopped) echo = setInterval(() => { if (!tx && !rx && !need) line('ECHO REQ').catch(() => {}); }, 3000);
|
||||
}
|
||||
async function sendPacket(data, type) {
|
||||
tx = { data, type, idx: 0, n: Math.ceil(data.length / 0x1000), tries: 0, done: null };
|
||||
const p = new Promise((res, rej) => { tx.done = res; tx.fail = rej; });
|
||||
await line('PKT ' + data.length);
|
||||
tx.timer = setTimeout(retryPkt, 2000);
|
||||
return p;
|
||||
}
|
||||
function retryPkt() {
|
||||
if (!tx || st.stopped) return;
|
||||
if (++tx.tries >= 3) { const f = tx.fail; tx = null; line('CAN').catch(() => {}); f(new Error('no ACK')); return; }
|
||||
line('PKT ' + tx.data.length).catch(() => {}); tx.timer = setTimeout(retryPkt, 2000);
|
||||
}
|
||||
async function sendChunk() {
|
||||
const i = tx.idx, d = tx.data.subarray(i * 0x1000, Math.min(tx.data.length, (i + 1) * 0x1000));
|
||||
const p = new Uint8Array(12 + d.length);
|
||||
w32(p, 0, st.sid); p[4] = 0x54; p[5] = 0x43; p[6] = 0x50; p[7] = tx.type; p[8] = i; p[9] = 255 - i; w16(p, 10, crc16(d)); p.set(d, 12);
|
||||
const n = rnd4(), c = await crypt(n, key, p), all = new Uint8Array(4 + c.length);
|
||||
all.set(n, 0); all.set(c, 4);
|
||||
clearTimeout(tx.timer); tx.timer = setTimeout(() => { if (tx && ++tx.tries < 3) sendChunk().catch(() => {}); else if (tx) { const f = tx.fail; tx = null; f(new Error('no ACK for a chunk')); } }, 5000);
|
||||
await out(all);
|
||||
}
|
||||
function onAck() {
|
||||
if (!tx) return;
|
||||
tx.tries = 0;
|
||||
if (tx.started) tx.idx++;
|
||||
tx.started = true;
|
||||
if (tx.idx >= tx.n) { clearTimeout(tx.timer); const d = tx.done; tx = null; d(); return; }
|
||||
sendChunk().catch((e) => fail(e));
|
||||
}
|
||||
|
||||
function answer(their) {
|
||||
if (their.length < PD + 0x14) return null;
|
||||
const a = their.slice();
|
||||
w16(a, PD, 0); // force_send_away: never
|
||||
w16(a, PD + 2, ed); // rom_type: the chosen edition
|
||||
w32(a, PD + 4, 0x504D5800 | ed); // device UID of the simulated device ("PMX" + edition)
|
||||
w32(a, PD + 8, (u32(their, PD + 8) ^ 0x5A5A0000 ^ ed) >>> 0); // character UID: theirs, changed
|
||||
return a;
|
||||
}
|
||||
async function packet(d, type) {
|
||||
st.got++;
|
||||
if (type & 0x10) { log('packet', { kind: 'session' }); return; }
|
||||
if (d.length === 0x20014) {
|
||||
log('packet', { kind: 'data', ed: u32(d, PD) >>> 16 });
|
||||
st.phase = 'send';
|
||||
const a = answer(d);
|
||||
await new Promise((r) => setTimeout(r, 150)); // the other device also waits a moment before it answers
|
||||
await sendPacket(a, type & 15);
|
||||
st.phase = 'play'; log('sent', {}); idle(true);
|
||||
return;
|
||||
}
|
||||
if (d.length === 2) { log('packet', { kind: 'friendship', level: d[0] | d[1] << 8 }); return; }
|
||||
if (d.length === 4) {
|
||||
const result = d[0] | d[1] << 8, breed = !!(d[2] & 1);
|
||||
st.result = result; log('result', { result, breed });
|
||||
if (breed) { await line('BREED 0'); await line('SYNC 1'); return; }
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
log('packet', { kind: 'other', n: d.length });
|
||||
}
|
||||
function finish() { if (st.phase === 'done') return; st.phase = 'done'; idle(false); log('done', { result: st.result }); }
|
||||
function fail(e) { if (st.stopped) return; idle(false); st.phase = 'error'; log('error', { text: e && e.message || String(e) }); }
|
||||
|
||||
async function chunk(c) {
|
||||
const n = c.subarray(0, 4), p = await crypt(n, key, c.subarray(4));
|
||||
const sid = u32(p, 0), type = p[7], idx = p[8], crc = p[10] | p[11] << 8, d = p.subarray(12);
|
||||
const ok = p[4] === 0x54 && p[5] === 0x43 && p[6] === 0x50 && p[9] === 255 - idx && crc16(d) === crc && (!st.sid || (type & 0x10) || sid === st.sid);
|
||||
if (!ok) { need = c.length; await line('NAK'); if (!st.badKey && p[4] !== 0x54) { st.badKey = true; log('error', { text: 'key' }); } return; }
|
||||
if (idx !== rx.idx) { need = c.length; await line('ENQ ' + rx.idx); return; }
|
||||
if (type & 0x10) st.sid = sid;
|
||||
rx.data.set(d, rx.off); rx.off += d.length; rx.idx++;
|
||||
const left = rx.n - rx.off;
|
||||
need = left > 0 ? 16 + Math.min(0x1000, left) : 0;
|
||||
await line('ACK');
|
||||
if (!left) { const r = rx; rx = null; packet(r.data, type).catch(fail); }
|
||||
}
|
||||
async function command(s) {
|
||||
const w = s.trim().split(/\s+/);
|
||||
if (!w[0]) return;
|
||||
if (w[0] === 'PKT') {
|
||||
const n = +w[1];
|
||||
if (!(n > 0 && n <= 0x100000)) return;
|
||||
if (st.phase === 'wait' && !st.started) { st.started = true; log('start', {}); }
|
||||
rx = { n, off: 0, idx: 0, data: new Uint8Array(n) };
|
||||
need = 16 + Math.min(0x1000, n);
|
||||
await line('ACK');
|
||||
return;
|
||||
}
|
||||
if (w[0] === 'ACK') { onAck(); return; }
|
||||
if (w[0] === 'NAK') { if (tx && tx.started) sendChunk().catch(fail); return; }
|
||||
if (w[0] === 'ENQ') { if (tx) { tx.idx = +w[1] || 0; tx.started = true; sendChunk().catch(fail); } return; }
|
||||
if (w[0] === 'CAN') { if (tx) { const f = tx.fail; tx = null; f(new Error('cancelled by the Paradise')); } else if (st.phase !== 'done') fail(new Error('cancelled by the Paradise')); return; }
|
||||
if (w[0] === 'ECHO') { if (w[1] === 'REQ') await line('ECHO REP'); return; }
|
||||
if (w[0] === 'SYNC') return; // we sent ours with BREED 0
|
||||
}
|
||||
async function pump() {
|
||||
for (;;) {
|
||||
if (need) {
|
||||
if (buf.length < need) return;
|
||||
const c = buf.slice(0, need); buf = buf.slice(need); need = 0;
|
||||
await chunk(c);
|
||||
continue;
|
||||
}
|
||||
let j = -1;
|
||||
for (let i = 0; i + 1 < buf.length; i++) if (buf[i] === 13 && buf[i + 1] === 10) { j = i; break; }
|
||||
if (j < 0) { if (buf.length > 256) buf = buf.slice(buf.length - 64); return; }
|
||||
const s = new TextDecoder('latin1').decode(buf.subarray(0, j)); buf = buf.slice(j + 2);
|
||||
await command(s);
|
||||
}
|
||||
}
|
||||
return {
|
||||
state: st,
|
||||
feed(bytes) {
|
||||
if (st.stopped) return queue;
|
||||
const b = new Uint8Array(buf.length + bytes.length); b.set(buf, 0); b.set(bytes, buf.length); buf = b;
|
||||
queue = queue.then(pump).catch(fail);
|
||||
return queue;
|
||||
},
|
||||
stop() { st.stopped = true; idle(false); if (tx) clearTimeout(tx.timer); tx = null; rx = null; },
|
||||
};
|
||||
}
|
||||
|
||||
const api = { ED, createVisitor, parseKey, crypt, crc16 };
|
||||
if (typeof module === 'object' && module.exports) module.exports = api;
|
||||
else root.ParamixVisit = api;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
+182
-182
@@ -1,182 +1,182 @@
|
||||
/*
|
||||
* Paramix Studio: Wolfenstein 3D for the Paradise, the data pack.
|
||||
* The user brings the game files (shareware .WL1 or full version .WL6); they never leave the computer.
|
||||
* The Studio only reads them in the browser and puts what the program needs into one pack for the flash.
|
||||
*
|
||||
* Pack "W3DP" (little endian, offsets from the start of the pack):
|
||||
* 0 'W3DP' 4 version (1) 8 flags (bit 0 shareware) 12 total length
|
||||
* 16 pages: count, first sprite, table offset (table: offset u32, length u32; walls 64x64 by columns, sprites as in VSWAP)
|
||||
* 28 maps: count, RLEW tag, table offset (table: offset u32 or 0; map header 38 bytes as in GAMEMAPS, plane starts
|
||||
* relative to the pack, planes Carmack + RLEW packed as in GAMEMAPS)
|
||||
* 40 sounds: count, table offset (PC speaker sounds: offset u32, length u32; data = u32 length, u16 priority, bytes)
|
||||
* 48 pics: count, table offset (table: offset u32, width u16, height u16; 8-bit, rows from the top)
|
||||
* 56 reserved 60 episodes
|
||||
* Pics: the range L_COLONPIC .. GETPSYCHEDPIC of the game (91 pics, same order in all versions; TITLEPIC is pic 43).
|
||||
* Spear of Destiny (.SOD, flags bit 1): the same 91 places taken from its own chunks (title from its two halves), then
|
||||
* its faces GODMODEFACE1..3, BJWAITING1..2, BJOUCH (pics 91..96). One episode of 21 floors.
|
||||
*
|
||||
* Author: mameise
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
|
||||
const u16 = (b, o) => b[o] | (b[o + 1] << 8);
|
||||
const s32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24));
|
||||
const u32 = (b, o) => s32(b, o) >>> 0;
|
||||
const u24 = (b, o) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16);
|
||||
function w16(b, o, v) { b[o] = v & 255; b[o + 1] = (v >> 8) & 255; }
|
||||
function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; }
|
||||
|
||||
const NUMSOUNDS = 87; // audiowl6.h LASTSOUND (shareware and full version)
|
||||
const NUMSOUNDS_SOD = 81; // audiosod.h
|
||||
// Spear of Destiny 1.4 (170 chunks): its chunk for each of the 91 places (gfxv_sod.h); TITLE (43) = TITLE1 above TITLE2
|
||||
// the game palette of SOD (sodpal.inc of Wolf4SDL, 6-bit RGB): its title has a palette of its own (TITLEPALETTE, chunk
|
||||
// 153), the program shows every pic with the game palette, so the title is taken to the nearest colours
|
||||
const SOD_PAL_B64 = 'AAAAAAAqACoAACoqKgAAKgAqKhUAKioqFRUVFRU/FT8VFT8/PxUVPxU/Pz8VPz8/Ozs7Nzc3NDQ0MDAwLS0tKioqJiYmIyMjHx8fHBwcGRkZFRUVEhISDg4OCwsLCAgIPwAAOwAAOAAANQAAMgAALwAALAAAKQAAJgAAIgAAHwAAHAAAGQAAFgAAEwAAEAAAPzY2Py4uPycnPx8fPxcXPxAQPwgIPwAAPyoXPyYQPyIIPx4AORsAMxgALRUAJxMAPz82Pz8uPz8nPz8fPz4XPz0QPz0IPz0AOTYAMzEALSsAJycAISEAHBsAFhUAEBAAND8XMT8QLT8IKD8AJDkAIDMAHS0AGCcANj82Lz8uJz8nID8fGD8XED8QCD8IAD8AAD8AADsAADgAADUAATIAAS8AASwAASkAASYAASIAAR8AARwAARkAARYAARMAARAANj8/Lj8/Jz8/Hz8+Fz8/ED8/CD8/AD8/ADk5ADMzAC0tACcnACEhABwcABYWABAQFy8/ECw/CCo/ACc/ACM5AB8zABstABcnNjY/Li8/Jyc/HyA/Fxg/EBA/CAk/AAE/AAA/AAA7AAA4AAA1AAAyAAAvAAAsAAApAAAmAAAiAAAfAAAcAAAZAAAWAAATAAAQCgoKPzgNPzUJPzMGPzACPy0AAA4AAAoAJgA5IAAzHQAtGAAnFAAhEQAcDQAWCgAQPzY/Py4/Pyc/Px8/Pxc/PxA/Pwg/PwA/OAA5MgAzLQAtJwAnIQAhGwAcFgAWEAAQPzo3Pzg0PzYxPzUvPzMsPzEpPy8nPy4kPywgPykcPycYPCUXOiMWNyIVNCAUMh8TLx4SLRwRKhoQKBkPJxgOJBcNIhYMIBQLHRMKGxIJFxAIFQ8HEg4GEAwGDgsFCggDGAAZABkZABgYAAAHAAALDAkEEgASFAAUAAANBwcHExMTFxcXEBAQDAwMDQ0NNj09Ljo6Jzc3HTIyEjAwCC0tCCwsACkpACYmACMjACEhAB8fAB4eAB0dABwcABsbJgAi';
|
||||
function b64(s) { if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(s, 'base64')); const t = atob(s), o = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) o[i] = t.charCodeAt(i); return o; }
|
||||
function toGamePal(px, pal) {
|
||||
const gp = b64(SOD_PAL_B64), map = new Uint8Array(256);
|
||||
for (let c = 0; c < 256; c++) {
|
||||
let best = 0, bd = 1e9;
|
||||
for (let j = 0; j < 256; j++) { const dr = pal[3 * c] - gp[3 * j], dg = pal[3 * c + 1] - gp[3 * j + 1], db = pal[3 * c + 2] - gp[3 * j + 2], d = 3 * dr * dr + 4 * dg * dg + 2 * db * db; if (d < bd) { bd = d; best = j; } }
|
||||
map[c] = best;
|
||||
}
|
||||
return px.map((v) => map[v]);
|
||||
}
|
||||
function sodChunk(k) {
|
||||
if (k <= 41) return 37 + k; // L_COLONPIC .. L_BJWINSPIC
|
||||
if (k >= 47 && k <= 87) return 54 + k; // KNIFEPIC .. GOTGATLINGPIC
|
||||
if (k >= 91) return 51 + k; // GODMODEFACE1PIC .. BJOUCHPIC
|
||||
return { 42: 90, 43: 79, 44: 91, 45: 92, 46: 29, 88: 142, 89: 148, 90: 149 }[k];
|
||||
}
|
||||
const PIC_FIRST = { 150: 44, 157: 56 }; // chunk of L_COLONPIC by number of chunks (Activision/GT 1.4, Apogee 1.4)
|
||||
const PIC_COUNT = 91; // L_COLONPIC .. GETPSYCHEDPIC
|
||||
// used by the program: STATUSBAR (42, its colour), TITLE (43), weapons, keys, digits, faces, PAUSED, GETPSYCHED (47..90)
|
||||
const PIC_USED = (k) => k === 42 || k === 43 || k >= 47;
|
||||
|
||||
const NEED = ['VSWAP', 'MAPHEAD', 'GAMEMAPS', 'AUDIOHED', 'AUDIOT', 'VGAHEAD', 'VGADICT', 'VGAGRAPH'];
|
||||
|
||||
/** files: { 'VSWAP.WL1': Uint8Array, ... } (any case). Returns { ext, files } of one complete set or throws. */
|
||||
function pickSet(files) {
|
||||
const by = {};
|
||||
for (const n of Object.keys(files)) {
|
||||
const m = /^([A-Za-z]+)\.(WL1|WL6|SOD)$/i.exec(n.replace(/^.*[\\/]/, ''));
|
||||
if (m) (by[m[2].toUpperCase()] = by[m[2].toUpperCase()] || {})[m[1].toUpperCase()] = files[n];
|
||||
}
|
||||
for (const ext of ['WL6', 'SOD', 'WL1']) {
|
||||
const s = by[ext]; if (!s) continue;
|
||||
const miss = NEED.filter((k) => !s[k]);
|
||||
if (!miss.length) return { ext, files: s };
|
||||
}
|
||||
const have = Object.keys(by);
|
||||
if (!have.length) throw new Error('no Wolfenstein 3D files (.WL1, .WL6 or .SOD)');
|
||||
const ext = have.includes('WL6') ? 'WL6' : have.includes('SOD') ? 'SOD' : 'WL1';
|
||||
throw new Error('missing: ' + NEED.filter((k) => !by[ext][k]).map((k) => k + '.' + ext).join(', '));
|
||||
}
|
||||
|
||||
function huffExpand(src, so, len, nodes) {
|
||||
const out = new Uint8Array(len); let o = 0, n = 254, i = so, val = src[i++], mask = 1;
|
||||
while (o < len) {
|
||||
const v = (val & mask) ? nodes[2 * n + 1] : nodes[2 * n];
|
||||
if (mask === 0x80) { val = src[i++]; mask = 1; } else mask <<= 1;
|
||||
if (v < 256) { out[o++] = v; n = 254; } else n = v - 256;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function readGraph(head, dict, graph) {
|
||||
const nchunks = Math.floor(head.length / 3);
|
||||
const nodes = new Uint16Array(255 * 2); for (let i = 0; i < 510; i++) nodes[i] = u16(dict, 2 * i);
|
||||
const pos = (c) => { const v = u24(head, 3 * c); return v === 0xFFFFFF ? -1 : v; };
|
||||
const chunk = (c, explicit) => {
|
||||
const p = pos(c); if (p < 0) return null;
|
||||
let q = c + 1; while (q < nchunks && pos(q) < 0) q++;
|
||||
const len = explicit !== undefined ? explicit : s32(graph, p);
|
||||
return huffExpand(graph, explicit !== undefined ? p : p + 4, len, nodes);
|
||||
};
|
||||
return { nchunks, chunk };
|
||||
}
|
||||
|
||||
function deplane(d, w, h) {
|
||||
const out = new Uint8Array(w * h), pw = w >> 2; let s = 0;
|
||||
for (let p = 0; p < 4; p++) for (let y = 0; y < h; y++) for (let x = 0; x < pw; x++) out[y * w + (x << 2) + p] = d[s++];
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Build the pack. files: complete set (see pickSet). */
|
||||
function build(files) {
|
||||
const { ext, files: f } = pickSet(files);
|
||||
const sod = ext === 'SOD', nsnd = sod ? NUMSOUNDS_SOD : NUMSOUNDS;
|
||||
const parts = []; let size = 64;
|
||||
const add = (b) => { const o = size; parts.push([o, b]); size += b.length; size = (size + 3) & ~3; return o; };
|
||||
const hdr = new Uint8Array(64);
|
||||
// pages (walls and sprites, no digitized sounds)
|
||||
const vs = f.VSWAP, nch = u16(vs, 0), spr = u16(vs, 2), snd = u16(vs, 4);
|
||||
// walls are 64 x 64 (4096 bytes); modified games (MacenWolf: 128 x 128) do not run with this program
|
||||
for (let i = 0; i < spr; i++) { const len = u16(vs, 6 + 4 * nch + 2 * i); if (len && len !== 4096) throw new Error('VSWAP.' + ext + ': walls not 64 x 64 (a modified game?), version 1.4 needed'); }
|
||||
const npages = snd, ptab = new Uint8Array(npages * 8);
|
||||
for (let i = 0; i < npages; i++) {
|
||||
const off = u32(vs, 6 + 4 * i), len = u16(vs, 6 + 4 * nch + 2 * i);
|
||||
if (!off || !len || off + len > vs.length) continue;
|
||||
w32(ptab, 8 * i, add(vs.subarray(off, off + len))); w32(ptab, 8 * i + 4, len);
|
||||
}
|
||||
w32(hdr, 16, npages); w32(hdr, 20, spr); w32(hdr, 24, add(ptab));
|
||||
// maps
|
||||
const mh = f.MAPHEAD, gm = f.GAMEMAPS, tag = u16(mh, 0);
|
||||
let nmaps = 0; const moff = [];
|
||||
for (let i = 0; 2 + 4 * i + 4 <= mh.length && i < 100; i++) { const o = s32(mh, 2 + 4 * i); moff.push(o > 0 && o + 38 <= gm.length ? o : 0); if (moff[i]) nmaps = i + 1; }
|
||||
const mtab = new Uint8Array(nmaps * 4);
|
||||
for (let i = 0; i < nmaps; i++) {
|
||||
const o = moff[i]; if (!o) continue;
|
||||
const h = new Uint8Array(gm.subarray(o, o + 38));
|
||||
const at = add(h);
|
||||
for (let p = 0; p < 3; p++) {
|
||||
const ps = s32(gm, o + 4 * p), pl = u16(gm, o + 12 + 2 * p);
|
||||
w32(h, 4 * p, ps > 0 && pl ? add(gm.subarray(ps, ps + pl)) : 0);
|
||||
}
|
||||
w32(mtab, 4 * i, at);
|
||||
}
|
||||
w32(hdr, 28, nmaps); w32(hdr, 32, tag); w32(hdr, 36, add(mtab));
|
||||
// PC speaker sounds
|
||||
const ah = f.AUDIOHED, at = f.AUDIOT, stab = new Uint8Array(nsnd * 8);
|
||||
for (let i = 0; i < nsnd && 4 * i + 8 <= ah.length; i++) {
|
||||
const a = u32(ah, 4 * i), b = u32(ah, 4 * i + 4);
|
||||
if (b > a && b <= at.length) { w32(stab, 8 * i, add(at.subarray(a, b))); w32(stab, 8 * i + 4, b - a); }
|
||||
}
|
||||
w32(hdr, 40, nsnd); w32(hdr, 44, add(stab));
|
||||
// pictures
|
||||
const g = readGraph(f.VGAHEAD, f.VGADICT, f.VGAGRAPH);
|
||||
const first = sod ? (g.nchunks === 170 ? 0 : undefined) : PIC_FIRST[g.nchunks];
|
||||
if (first === undefined) throw new Error('unknown version of VGAHEAD (' + g.nchunks + ' chunks)');
|
||||
const st = g.chunk(0); // STRUCTPIC: width, height of every pic from chunk 3
|
||||
const pics = []; for (let k = 0; k < PIC_COUNT + (sod ? 6 : 0); k++) pics.push(sod ? sodChunk(k) : first + k); // TITLEPIC is pic 43
|
||||
const pic = (c) => {
|
||||
const w = s16v(st, 4 * (c - 3)), h = s16v(st, 4 * (c - 3) + 2), d = g.chunk(c);
|
||||
if (!d || w <= 0 || h <= 0 || (w & 3) || d.length < w * h) return null;
|
||||
return { w, h, px: deplane(d, w, h) };
|
||||
};
|
||||
const xtab = new Uint8Array(pics.length * 8);
|
||||
pics.forEach((c, k) => {
|
||||
if (!PIC_USED(k)) return; // pictures the program never shows stay out (flash)
|
||||
let p = pic(c);
|
||||
if (p && sod && k === 43) { // the title of SOD comes in two halves
|
||||
const q = pic(c + 1);
|
||||
if (q && q.w === p.w) { const px = new Uint8Array(p.w * (p.h + q.h)); px.set(p.px); px.set(q.px, p.w * p.h); p = { w: p.w, h: p.h + q.h, px }; }
|
||||
const tp = g.chunk(153); // TITLEPALETTE
|
||||
if (tp && tp.length >= 768) p.px = toGamePal(p.px, tp);
|
||||
}
|
||||
if (!p) return;
|
||||
w32(xtab, 8 * k, add(p.px)); w16(xtab, 8 * k + 4, p.w); w16(xtab, 8 * k + 6, p.h);
|
||||
});
|
||||
w32(hdr, 48, pics.length); w32(hdr, 52, add(xtab));
|
||||
const episodes = sod ? 1 : Math.max(1, Math.floor(nmaps / 10));
|
||||
w32(hdr, 60, episodes);
|
||||
hdr.set([0x57, 0x33, 0x44, 0x50]); w32(hdr, 4, 1); w32(hdr, 8, (ext === 'WL1' ? 1 : 0) | (sod ? 2 : 0)); w32(hdr, 12, size);
|
||||
const out = new Uint8Array(size); out.set(hdr);
|
||||
for (const [o, b] of parts) out.set(b, o);
|
||||
return { pack: out, ext, maps: nmaps, episodes, sod };
|
||||
}
|
||||
function s16v(b, o) { const v = u16(b, o); return v > 32767 ? v - 65536 : v; }
|
||||
root.ParamixWolf = { pickSet, build, readGraph, NEED };
|
||||
if (typeof module !== 'undefined') module.exports = root.ParamixWolf;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
/*
|
||||
* Paramix Studio: Wolfenstein 3D for the Paradise, the data pack.
|
||||
* The user brings the game files (shareware .WL1 or full version .WL6); they never leave the computer.
|
||||
* The Studio only reads them in the browser and puts what the program needs into one pack for the flash.
|
||||
*
|
||||
* Pack "W3DP" (little endian, offsets from the start of the pack):
|
||||
* 0 'W3DP' 4 version (1) 8 flags (bit 0 shareware) 12 total length
|
||||
* 16 pages: count, first sprite, table offset (table: offset u32, length u32; walls 64x64 by columns, sprites as in VSWAP)
|
||||
* 28 maps: count, RLEW tag, table offset (table: offset u32 or 0; map header 38 bytes as in GAMEMAPS, plane starts
|
||||
* relative to the pack, planes Carmack + RLEW packed as in GAMEMAPS)
|
||||
* 40 sounds: count, table offset (PC speaker sounds: offset u32, length u32; data = u32 length, u16 priority, bytes)
|
||||
* 48 pics: count, table offset (table: offset u32, width u16, height u16; 8-bit, rows from the top)
|
||||
* 56 reserved 60 episodes
|
||||
* Pics: the range L_COLONPIC .. GETPSYCHEDPIC of the game (91 pics, same order in all versions; TITLEPIC is pic 43).
|
||||
* Spear of Destiny (.SOD, flags bit 1): the same 91 places taken from its own chunks (title from its two halves), then
|
||||
* its faces GODMODEFACE1..3, BJWAITING1..2, BJOUCH (pics 91..96). One episode of 21 floors.
|
||||
*
|
||||
* Author: mameise
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
|
||||
const u16 = (b, o) => b[o] | (b[o + 1] << 8);
|
||||
const s32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24));
|
||||
const u32 = (b, o) => s32(b, o) >>> 0;
|
||||
const u24 = (b, o) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16);
|
||||
function w16(b, o, v) { b[o] = v & 255; b[o + 1] = (v >> 8) & 255; }
|
||||
function w32(b, o, v) { b[o] = v & 255; b[o + 1] = (v >>> 8) & 255; b[o + 2] = (v >>> 16) & 255; b[o + 3] = (v >>> 24) & 255; }
|
||||
|
||||
const NUMSOUNDS = 87; // audiowl6.h LASTSOUND (shareware and full version)
|
||||
const NUMSOUNDS_SOD = 81; // audiosod.h
|
||||
// Spear of Destiny 1.4 (170 chunks): its chunk for each of the 91 places (gfxv_sod.h); TITLE (43) = TITLE1 above TITLE2
|
||||
// the game palette of SOD (sodpal.inc of Wolf4SDL, 6-bit RGB): its title has a palette of its own (TITLEPALETTE, chunk
|
||||
// 153), the program shows every pic with the game palette, so the title is taken to the nearest colours
|
||||
const SOD_PAL_B64 = 'AAAAAAAqACoAACoqKgAAKgAqKhUAKioqFRUVFRU/FT8VFT8/PxUVPxU/Pz8VPz8/Ozs7Nzc3NDQ0MDAwLS0tKioqJiYmIyMjHx8fHBwcGRkZFRUVEhISDg4OCwsLCAgIPwAAOwAAOAAANQAAMgAALwAALAAAKQAAJgAAIgAAHwAAHAAAGQAAFgAAEwAAEAAAPzY2Py4uPycnPx8fPxcXPxAQPwgIPwAAPyoXPyYQPyIIPx4AORsAMxgALRUAJxMAPz82Pz8uPz8nPz8fPz4XPz0QPz0IPz0AOTYAMzEALSsAJycAISEAHBsAFhUAEBAAND8XMT8QLT8IKD8AJDkAIDMAHS0AGCcANj82Lz8uJz8nID8fGD8XED8QCD8IAD8AAD8AADsAADgAADUAATIAAS8AASwAASkAASYAASIAAR8AARwAARkAARYAARMAARAANj8/Lj8/Jz8/Hz8+Fz8/ED8/CD8/AD8/ADk5ADMzAC0tACcnACEhABwcABYWABAQFy8/ECw/CCo/ACc/ACM5AB8zABstABcnNjY/Li8/Jyc/HyA/Fxg/EBA/CAk/AAE/AAA/AAA7AAA4AAA1AAAyAAAvAAAsAAApAAAmAAAiAAAfAAAcAAAZAAAWAAATAAAQCgoKPzgNPzUJPzMGPzACPy0AAA4AAAoAJgA5IAAzHQAtGAAnFAAhEQAcDQAWCgAQPzY/Py4/Pyc/Px8/Pxc/PxA/Pwg/PwA/OAA5MgAzLQAtJwAnIQAhGwAcFgAWEAAQPzo3Pzg0PzYxPzUvPzMsPzEpPy8nPy4kPywgPykcPycYPCUXOiMWNyIVNCAUMh8TLx4SLRwRKhoQKBkPJxgOJBcNIhYMIBQLHRMKGxIJFxAIFQ8HEg4GEAwGDgsFCggDGAAZABkZABgYAAAHAAALDAkEEgASFAAUAAANBwcHExMTFxcXEBAQDAwMDQ0NNj09Ljo6Jzc3HTIyEjAwCC0tCCwsACkpACYmACMjACEhAB8fAB4eAB0dABwcABsbJgAi';
|
||||
function b64(s) { if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(s, 'base64')); const t = atob(s), o = new Uint8Array(t.length); for (let i = 0; i < t.length; i++) o[i] = t.charCodeAt(i); return o; }
|
||||
function toGamePal(px, pal) {
|
||||
const gp = b64(SOD_PAL_B64), map = new Uint8Array(256);
|
||||
for (let c = 0; c < 256; c++) {
|
||||
let best = 0, bd = 1e9;
|
||||
for (let j = 0; j < 256; j++) { const dr = pal[3 * c] - gp[3 * j], dg = pal[3 * c + 1] - gp[3 * j + 1], db = pal[3 * c + 2] - gp[3 * j + 2], d = 3 * dr * dr + 4 * dg * dg + 2 * db * db; if (d < bd) { bd = d; best = j; } }
|
||||
map[c] = best;
|
||||
}
|
||||
return px.map((v) => map[v]);
|
||||
}
|
||||
function sodChunk(k) {
|
||||
if (k <= 41) return 37 + k; // L_COLONPIC .. L_BJWINSPIC
|
||||
if (k >= 47 && k <= 87) return 54 + k; // KNIFEPIC .. GOTGATLINGPIC
|
||||
if (k >= 91) return 51 + k; // GODMODEFACE1PIC .. BJOUCHPIC
|
||||
return { 42: 90, 43: 79, 44: 91, 45: 92, 46: 29, 88: 142, 89: 148, 90: 149 }[k];
|
||||
}
|
||||
const PIC_FIRST = { 150: 44, 157: 56 }; // chunk of L_COLONPIC by number of chunks (Activision/GT 1.4, Apogee 1.4)
|
||||
const PIC_COUNT = 91; // L_COLONPIC .. GETPSYCHEDPIC
|
||||
// used by the program: STATUSBAR (42, its colour), TITLE (43), weapons, keys, digits, faces, PAUSED, GETPSYCHED (47..90)
|
||||
const PIC_USED = (k) => k === 42 || k === 43 || k >= 47;
|
||||
|
||||
const NEED = ['VSWAP', 'MAPHEAD', 'GAMEMAPS', 'AUDIOHED', 'AUDIOT', 'VGAHEAD', 'VGADICT', 'VGAGRAPH'];
|
||||
|
||||
/** files: { 'VSWAP.WL1': Uint8Array, ... } (any case). Returns { ext, files } of one complete set or throws. */
|
||||
function pickSet(files) {
|
||||
const by = {};
|
||||
for (const n of Object.keys(files)) {
|
||||
const m = /^([A-Za-z]+)\.(WL1|WL6|SOD)$/i.exec(n.replace(/^.*[\\/]/, ''));
|
||||
if (m) (by[m[2].toUpperCase()] = by[m[2].toUpperCase()] || {})[m[1].toUpperCase()] = files[n];
|
||||
}
|
||||
for (const ext of ['WL6', 'SOD', 'WL1']) {
|
||||
const s = by[ext]; if (!s) continue;
|
||||
const miss = NEED.filter((k) => !s[k]);
|
||||
if (!miss.length) return { ext, files: s };
|
||||
}
|
||||
const have = Object.keys(by);
|
||||
if (!have.length) throw new Error('no Wolfenstein 3D files (.WL1, .WL6 or .SOD)');
|
||||
const ext = have.includes('WL6') ? 'WL6' : have.includes('SOD') ? 'SOD' : 'WL1';
|
||||
throw new Error('missing: ' + NEED.filter((k) => !by[ext][k]).map((k) => k + '.' + ext).join(', '));
|
||||
}
|
||||
|
||||
function huffExpand(src, so, len, nodes) {
|
||||
const out = new Uint8Array(len); let o = 0, n = 254, i = so, val = src[i++], mask = 1;
|
||||
while (o < len) {
|
||||
const v = (val & mask) ? nodes[2 * n + 1] : nodes[2 * n];
|
||||
if (mask === 0x80) { val = src[i++]; mask = 1; } else mask <<= 1;
|
||||
if (v < 256) { out[o++] = v; n = 254; } else n = v - 256;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function readGraph(head, dict, graph) {
|
||||
const nchunks = Math.floor(head.length / 3);
|
||||
const nodes = new Uint16Array(255 * 2); for (let i = 0; i < 510; i++) nodes[i] = u16(dict, 2 * i);
|
||||
const pos = (c) => { const v = u24(head, 3 * c); return v === 0xFFFFFF ? -1 : v; };
|
||||
const chunk = (c, explicit) => {
|
||||
const p = pos(c); if (p < 0) return null;
|
||||
let q = c + 1; while (q < nchunks && pos(q) < 0) q++;
|
||||
const len = explicit !== undefined ? explicit : s32(graph, p);
|
||||
return huffExpand(graph, explicit !== undefined ? p : p + 4, len, nodes);
|
||||
};
|
||||
return { nchunks, chunk };
|
||||
}
|
||||
|
||||
function deplane(d, w, h) {
|
||||
const out = new Uint8Array(w * h), pw = w >> 2; let s = 0;
|
||||
for (let p = 0; p < 4; p++) for (let y = 0; y < h; y++) for (let x = 0; x < pw; x++) out[y * w + (x << 2) + p] = d[s++];
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Build the pack. files: complete set (see pickSet). */
|
||||
function build(files) {
|
||||
const { ext, files: f } = pickSet(files);
|
||||
const sod = ext === 'SOD', nsnd = sod ? NUMSOUNDS_SOD : NUMSOUNDS;
|
||||
const parts = []; let size = 64;
|
||||
const add = (b) => { const o = size; parts.push([o, b]); size += b.length; size = (size + 3) & ~3; return o; };
|
||||
const hdr = new Uint8Array(64);
|
||||
// pages (walls and sprites, no digitized sounds)
|
||||
const vs = f.VSWAP, nch = u16(vs, 0), spr = u16(vs, 2), snd = u16(vs, 4);
|
||||
// walls are 64 x 64 (4096 bytes); modified games (MacenWolf: 128 x 128) do not run with this program
|
||||
for (let i = 0; i < spr; i++) { const len = u16(vs, 6 + 4 * nch + 2 * i); if (len && len !== 4096) throw new Error('VSWAP.' + ext + ': walls not 64 x 64 (a modified game?), version 1.4 needed'); }
|
||||
const npages = snd, ptab = new Uint8Array(npages * 8);
|
||||
for (let i = 0; i < npages; i++) {
|
||||
const off = u32(vs, 6 + 4 * i), len = u16(vs, 6 + 4 * nch + 2 * i);
|
||||
if (!off || !len || off + len > vs.length) continue;
|
||||
w32(ptab, 8 * i, add(vs.subarray(off, off + len))); w32(ptab, 8 * i + 4, len);
|
||||
}
|
||||
w32(hdr, 16, npages); w32(hdr, 20, spr); w32(hdr, 24, add(ptab));
|
||||
// maps
|
||||
const mh = f.MAPHEAD, gm = f.GAMEMAPS, tag = u16(mh, 0);
|
||||
let nmaps = 0; const moff = [];
|
||||
for (let i = 0; 2 + 4 * i + 4 <= mh.length && i < 100; i++) { const o = s32(mh, 2 + 4 * i); moff.push(o > 0 && o + 38 <= gm.length ? o : 0); if (moff[i]) nmaps = i + 1; }
|
||||
const mtab = new Uint8Array(nmaps * 4);
|
||||
for (let i = 0; i < nmaps; i++) {
|
||||
const o = moff[i]; if (!o) continue;
|
||||
const h = new Uint8Array(gm.subarray(o, o + 38));
|
||||
const at = add(h);
|
||||
for (let p = 0; p < 3; p++) {
|
||||
const ps = s32(gm, o + 4 * p), pl = u16(gm, o + 12 + 2 * p);
|
||||
w32(h, 4 * p, ps > 0 && pl ? add(gm.subarray(ps, ps + pl)) : 0);
|
||||
}
|
||||
w32(mtab, 4 * i, at);
|
||||
}
|
||||
w32(hdr, 28, nmaps); w32(hdr, 32, tag); w32(hdr, 36, add(mtab));
|
||||
// PC speaker sounds
|
||||
const ah = f.AUDIOHED, at = f.AUDIOT, stab = new Uint8Array(nsnd * 8);
|
||||
for (let i = 0; i < nsnd && 4 * i + 8 <= ah.length; i++) {
|
||||
const a = u32(ah, 4 * i), b = u32(ah, 4 * i + 4);
|
||||
if (b > a && b <= at.length) { w32(stab, 8 * i, add(at.subarray(a, b))); w32(stab, 8 * i + 4, b - a); }
|
||||
}
|
||||
w32(hdr, 40, nsnd); w32(hdr, 44, add(stab));
|
||||
// pictures
|
||||
const g = readGraph(f.VGAHEAD, f.VGADICT, f.VGAGRAPH);
|
||||
const first = sod ? (g.nchunks === 170 ? 0 : undefined) : PIC_FIRST[g.nchunks];
|
||||
if (first === undefined) throw new Error('unknown version of VGAHEAD (' + g.nchunks + ' chunks)');
|
||||
const st = g.chunk(0); // STRUCTPIC: width, height of every pic from chunk 3
|
||||
const pics = []; for (let k = 0; k < PIC_COUNT + (sod ? 6 : 0); k++) pics.push(sod ? sodChunk(k) : first + k); // TITLEPIC is pic 43
|
||||
const pic = (c) => {
|
||||
const w = s16v(st, 4 * (c - 3)), h = s16v(st, 4 * (c - 3) + 2), d = g.chunk(c);
|
||||
if (!d || w <= 0 || h <= 0 || (w & 3) || d.length < w * h) return null;
|
||||
return { w, h, px: deplane(d, w, h) };
|
||||
};
|
||||
const xtab = new Uint8Array(pics.length * 8);
|
||||
pics.forEach((c, k) => {
|
||||
if (!PIC_USED(k)) return; // pictures the program never shows stay out (flash)
|
||||
let p = pic(c);
|
||||
if (p && sod && k === 43) { // the title of SOD comes in two halves
|
||||
const q = pic(c + 1);
|
||||
if (q && q.w === p.w) { const px = new Uint8Array(p.w * (p.h + q.h)); px.set(p.px); px.set(q.px, p.w * p.h); p = { w: p.w, h: p.h + q.h, px }; }
|
||||
const tp = g.chunk(153); // TITLEPALETTE
|
||||
if (tp && tp.length >= 768) p.px = toGamePal(p.px, tp);
|
||||
}
|
||||
if (!p) return;
|
||||
w32(xtab, 8 * k, add(p.px)); w16(xtab, 8 * k + 4, p.w); w16(xtab, 8 * k + 6, p.h);
|
||||
});
|
||||
w32(hdr, 48, pics.length); w32(hdr, 52, add(xtab));
|
||||
const episodes = sod ? 1 : Math.max(1, Math.floor(nmaps / 10));
|
||||
w32(hdr, 60, episodes);
|
||||
hdr.set([0x57, 0x33, 0x44, 0x50]); w32(hdr, 4, 1); w32(hdr, 8, (ext === 'WL1' ? 1 : 0) | (sod ? 2 : 0)); w32(hdr, 12, size);
|
||||
const out = new Uint8Array(size); out.set(hdr);
|
||||
for (const [o, b] of parts) out.set(b, o);
|
||||
return { pack: out, ext, maps: nmaps, episodes, sod };
|
||||
}
|
||||
function s16v(b, o) { const v = u16(b, o); return v > 32767 ? v - 65536 : v; }
|
||||
root.ParamixWolf = { pickSet, build, readGraph, NEED };
|
||||
if (typeof module !== 'undefined') module.exports = root.ParamixWolf;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
Reference in new issue
Block a user