├── .gitignore
├── .npmignore
├── LICENSE
├── README.md
├── biome.json
├── config
├── file-names.json
├── file-names.properties
├── map-file-names.json
└── map-keys.json
├── package-lock.json
├── package.json
├── packed
├── main_file_cache.dat0
├── main_file_cache.dat1
├── main_file_cache.dat2
├── main_file_cache.idx0
├── main_file_cache.idx1
├── main_file_cache.idx10
├── main_file_cache.idx11
├── main_file_cache.idx12
├── main_file_cache.idx2
├── main_file_cache.idx255
├── main_file_cache.idx3
├── main_file_cache.idx4
├── main_file_cache.idx5
├── main_file_cache.idx6
├── main_file_cache.idx7
├── main_file_cache.idx8
└── main_file_cache.idx9
├── src
├── filestore
│ ├── archive.ts
│ ├── data
│ │ ├── chunk.ts
│ │ ├── compression.ts
│ │ ├── filestore-loader.ts
│ │ └── index.ts
│ ├── file-data.ts
│ ├── file-index.ts
│ ├── filestore.ts
│ ├── index.ts
│ ├── stores
│ │ ├── binary-store.ts
│ │ ├── config-store.ts
│ │ ├── configs
│ │ │ ├── index.ts
│ │ │ ├── item-store.ts
│ │ │ ├── npc-store.ts
│ │ │ ├── object-store.ts
│ │ │ └── varbit-store.ts
│ │ ├── font-store.ts
│ │ ├── index.ts
│ │ ├── jingle-store.ts
│ │ ├── model-store.ts
│ │ ├── music-store.ts
│ │ ├── region-store.ts
│ │ ├── sound-store.ts
│ │ ├── sprite-store.ts
│ │ ├── texture-store.ts
│ │ └── widget-store.ts
│ └── util
│ │ ├── index.ts
│ │ ├── name-hash.ts
│ │ ├── png.ts
│ │ └── xtea.ts
├── index.ts
└── run.ts
└── tsconfig.json
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | .DS_Store
3 | /dist
4 | /lib
5 | /cache
6 | /data
7 | /output
8 | /stores
9 | /packed
10 | /unpacked
11 |
12 | # Log files
13 | npm-debug.log*
14 | yarn-debug.log*
15 | yarn-error.log*
16 |
17 | # Editor directories and files
18 | .idea
19 | .vscode
20 | *.suo
21 | *.ntvs*
22 | *.njsproj
23 | *.sln
24 | *.sw?
25 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | /tsconfig.json
2 | /src
3 | /.idea
4 | /packed
5 | /config
6 | /unpacked
7 | /output
8 | /dist
9 | /stores
10 | /dist/run.*
11 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://discord.gg/5P74nSh)
2 |
3 | [](https://github.com/runejs/)
4 |
5 | # Filestore
6 |
7 | Tools for managing the RuneScape indexed filestore used with RuneJS.
8 |
9 | ## Archives
10 |
11 | ### Binary
12 |
13 | Holds miscellaneous binary files that don't fit into other archives, including the game client title screen background image.
14 |
15 | `BinaryStore` files are all named with their extensions included, if applicable.
16 |
17 | ### Config
18 |
19 | The `ConfigStore` contains various archives holding configuration files:
20 |
21 | #### Item Configs
22 |
23 | `ItemStore` holds files with game item data relevant to the game client.
24 |
25 | #### NPC Configs
26 |
27 | `NpcStore` files work similarly to `ItemStore`, but contain game NPC information instead.
28 |
29 | #### Object Configs
30 |
31 | `ObjectStore` files contain game object details.
32 |
33 | ### Sounds (.wav)
34 |
35 | The `SoundStore` contains various `.wav` files for game sounds.
36 |
37 | ### Jingles (.ogg)
38 |
39 | The `SoundStore` contains `.ogg` files for various minor game songs; level up songs, quest completion jingle, etc.
40 |
41 | ### Music (.midi)
42 |
43 | `MusicStore` contains a list of `.mid` MIDI song files used to play game songs with a MIDI player.
44 |
45 | Most MIDI files within the store have specific names that match the name of that song.
46 |
47 | ### Regions
48 |
49 | `RegionStore` files contain map tile and landscape object definitions for all game map regions.
50 |
51 | These files are named with the format `m{regionX}_{regionY}` for map tile files and `l{regionX}_{regionY}` for landscape object files.
52 |
53 | ### Models
54 |
55 | `ModelStore` contains information about individual game model files along with several rendering helper methods for implementing applications.
56 |
57 | ### Sprites
58 |
59 | `SpriteStore` files are either single sprite/image, or archives of related game sprites. Files returned are of type `SpritePack`, which will contain one or more `Sprite` objects with indexed pixel data that can be converted directly to PNG format or base64 encoded via the included API.
60 |
61 | ### UI Interfaces
62 |
63 | `WidgetStore` files hold details on every different game interface widget that is available. Placement, type, options, sprites used, etc.
64 |
--------------------------------------------------------------------------------
/biome.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
3 | "vcs": {
4 | "enabled": true,
5 | "clientKind": "git",
6 | "useIgnoreFile": true
7 | },
8 | "files": {
9 | "ignoreUnknown": false,
10 | "ignore": []
11 | },
12 | "formatter": {
13 | "enabled": true,
14 | "indentStyle": "space",
15 | "indentWidth": 4
16 | },
17 | "organizeImports": {
18 | "enabled": true
19 | },
20 | "linter": {
21 | "enabled": true,
22 | "rules": {
23 | "recommended": true,
24 | "complexity": {
25 | "recommended": true,
26 | "noForEach": "off"
27 | }
28 | }
29 | },
30 | "javascript": {
31 | "formatter": {
32 | "quoteStyle": "single"
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@runejs/filestore",
3 | "version": "0.17.0",
4 | "description": "Tools for managing the RuneJS filestore.",
5 | "main": "lib/index.js",
6 | "types": "lib/index.d.ts",
7 | "scripts": {
8 | "build": "tsc",
9 | "clean": "rimraf lib",
10 | "lint": "biome lint",
11 | "lint:fix": "biome lint --write",
12 | "format": "biome format",
13 | "format:fix": "biome format --write",
14 | "fin": "npm run lint:fix && npm run format:fix",
15 | "start": "ts-node src/run.ts",
16 | "package": "rimraf lib && npm i && npm run build && npm publish --dry-run"
17 | },
18 | "repository": {
19 | "type": "git",
20 | "url": "git+ssh://git@github.com/runejs/filestore.git"
21 | },
22 | "keywords": [
23 | "runejs",
24 | "runescape",
25 | "typescript",
26 | "filestore",
27 | "cache",
28 | "js5"
29 | ],
30 | "author": "Tynarus",
31 | "license": "GPL-3.0",
32 | "bugs": {
33 | "url": "https://github.com/runejs/filestore/issues"
34 | },
35 | "homepage": "https://github.com/runejs/filestore#readme",
36 | "peerDependencies": {
37 | "@runejs/common": "2.0.2-beta.3",
38 | "tslib": "2.8.1",
39 | "typescript": "5.7.3"
40 | },
41 | "dependencies": {
42 | "@runejs/common": "2.0.2-beta.3",
43 | "canvas": "^3.1.0",
44 | "pngjs": "^7.0.0",
45 | "properties-parser": "^0.6.0",
46 | "seek-bzip": "^2.0.0",
47 | "tslib": "2.8.1"
48 | },
49 | "devDependencies": {
50 | "@biomejs/biome": "1.9.4",
51 | "@types/node": "^22.10.10",
52 | "@types/pngjs": "^6.0.5",
53 | "rimraf": "^6.0.1",
54 | "ts-node": "^10.9.2",
55 | "typescript": "5.7.3"
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/packed/main_file_cache.dat0:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.dat0
--------------------------------------------------------------------------------
/packed/main_file_cache.dat1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.dat1
--------------------------------------------------------------------------------
/packed/main_file_cache.dat2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.dat2
--------------------------------------------------------------------------------
/packed/main_file_cache.idx0:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx0
--------------------------------------------------------------------------------
/packed/main_file_cache.idx1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx1
--------------------------------------------------------------------------------
/packed/main_file_cache.idx10:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx10
--------------------------------------------------------------------------------
/packed/main_file_cache.idx11:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx11
--------------------------------------------------------------------------------
/packed/main_file_cache.idx12:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx12
--------------------------------------------------------------------------------
/packed/main_file_cache.idx2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx2
--------------------------------------------------------------------------------
/packed/main_file_cache.idx255:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx255
--------------------------------------------------------------------------------
/packed/main_file_cache.idx3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx3
--------------------------------------------------------------------------------
/packed/main_file_cache.idx4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx4
--------------------------------------------------------------------------------
/packed/main_file_cache.idx5:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx5
--------------------------------------------------------------------------------
/packed/main_file_cache.idx6:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx6
--------------------------------------------------------------------------------
/packed/main_file_cache.idx7:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx7
--------------------------------------------------------------------------------
/packed/main_file_cache.idx8:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx8
--------------------------------------------------------------------------------
/packed/main_file_cache.idx9:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/runejs/filestore/32521c2f99ee3fc46a6d1182cfb78e8db653e803/packed/main_file_cache.idx9
--------------------------------------------------------------------------------
/src/filestore/archive.ts:
--------------------------------------------------------------------------------
1 | import { ByteBuffer } from '@runejs/common';
2 |
3 | import { FileData } from './file-data';
4 | import type { FileIndex } from './file-index';
5 | import {
6 | type FilestoreChannels,
7 | readIndexedDataChunk,
8 | decompress,
9 | } from './data';
10 |
11 | export class Archive extends FileData {
12 | /**
13 | * A map of files housed within this Archive.
14 | */
15 | public files: Map;
16 |
17 | /**
18 | * The type of file, either an `archive` or a plain `file`.
19 | */
20 | public type: 'archive' | 'file' = 'archive';
21 |
22 | private decoded = false;
23 |
24 | /**
25 | * Creates a new `Archive` object.
26 | * @param id The ID of the Archive within it's File Index.
27 | * @param index The File Index that this Archive belongs to.
28 | * @param filestoreChannels The main filestore channel for data access.
29 | */
30 | public constructor(
31 | id: number,
32 | index: FileIndex,
33 | filestoreChannels: FilestoreChannels,
34 | );
35 |
36 | /**
37 | * Creates a new `Archive` object.
38 | * @param fileData Data about a file that's being recognized as an Archive.
39 | * @param index The File Index that this Archive belongs to.
40 | * @param filestoreChannels The main filestore channel for data access.
41 | */
42 | public constructor(
43 | fileData: FileData,
44 | index: FileIndex,
45 | filestoreChannels: FilestoreChannels,
46 | );
47 |
48 | public constructor(
49 | idOrFileData: number | FileData,
50 | index: FileIndex,
51 | filestoreChannels: FilestoreChannels,
52 | ) {
53 | super(
54 | typeof idOrFileData === 'number'
55 | ? idOrFileData
56 | : idOrFileData.fileId,
57 | index,
58 | filestoreChannels,
59 | );
60 |
61 | if (typeof idOrFileData !== 'number') {
62 | const fileData = idOrFileData as FileData;
63 | const { content, nameHash, crc, whirlpool, version, compression } =
64 | fileData;
65 | this.content = content;
66 | this.nameHash = nameHash;
67 | this.crc = crc;
68 | this.whirlpool = whirlpool;
69 | this.version = version;
70 | this.compression = compression;
71 | }
72 |
73 | this.files = new Map();
74 | }
75 |
76 | /**
77 | * Fetches a file from this Archive by ID.
78 | * @param fileId The ID of the file to find.
79 | */
80 | public getFile(fileId: number): FileData | null {
81 | return this.files.get(fileId) || null;
82 | }
83 |
84 | /**
85 | * Decodes the packed Archive files from the filestore on disk.
86 | */
87 | public decodeArchiveFiles(): void {
88 | if (this.decoded) {
89 | return;
90 | }
91 |
92 | const archiveEntry = readIndexedDataChunk(
93 | this.fileId,
94 | this.index.indexId,
95 | this.filestoreChannels,
96 | );
97 | const { compression, version, buffer } = decompress(
98 | archiveEntry.dataFile,
99 | );
100 | const archiveSize = this.files.size;
101 |
102 | this.content = buffer;
103 |
104 | this.version = version;
105 | this.content = buffer;
106 | this.compression = compression;
107 | this.files.clear();
108 | buffer.readerIndex = buffer.length - 1;
109 | const chunkCount = buffer.get('BYTE', 'UNSIGNED');
110 |
111 | const chunkSizes: number[][] = new Array(chunkCount).fill(
112 | new Array(archiveSize),
113 | );
114 | const sizes: number[] = new Array(archiveSize).fill(0);
115 | buffer.readerIndex = buffer.length - 1 - chunkCount * archiveSize * 4;
116 | for (let chunk = 0; chunk < chunkCount; chunk++) {
117 | let chunkSize = 0;
118 | for (let id = 0; id < archiveSize; id++) {
119 | const delta = buffer.get('INT');
120 | chunkSize += delta;
121 |
122 | chunkSizes[chunk][id] = chunkSize;
123 | sizes[id] += chunkSize;
124 | }
125 | }
126 |
127 | for (let id = 0; id < archiveSize; id++) {
128 | const fileData = new FileData(
129 | id,
130 | this.index,
131 | this.filestoreChannels,
132 | );
133 | fileData.content = new ByteBuffer(sizes[id]);
134 | this.files.set(id, fileData);
135 | }
136 |
137 | buffer.readerIndex = 0;
138 |
139 | for (let chunk = 0; chunk < chunkCount; chunk++) {
140 | for (let id = 0; id < archiveSize; id++) {
141 | const chunkSize = chunkSizes[chunk][id];
142 | this.files
143 | .get(id)
144 | .content.putBytes(
145 | buffer.getSlice(buffer.readerIndex, chunkSize),
146 | );
147 | buffer.copy(
148 | this.files.get(id).content,
149 | 0,
150 | buffer.readerIndex,
151 | buffer.readerIndex + chunkSize,
152 | );
153 | buffer.readerIndex = buffer.readerIndex + chunkSize;
154 | }
155 | }
156 |
157 | this.decoded = true;
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/src/filestore/data/chunk.ts:
--------------------------------------------------------------------------------
1 | import { ByteBuffer } from '@runejs/common';
2 |
3 | import type { FilestoreChannels } from './filestore-loader';
4 |
5 | export const indexFileLength = 6;
6 | export const dataChunkLength = 512;
7 | export const sectorLength = 520;
8 |
9 | export interface IndexChunk {
10 | readonly indexId: number;
11 | readonly fileId: number;
12 | readonly size: number;
13 | readonly sector: number;
14 | }
15 |
16 | export interface IndexedDataChunk {
17 | indexFile: IndexChunk;
18 | dataFile: ByteBuffer;
19 | }
20 |
21 | export const readIndexedDataChunk = (
22 | fileId: number,
23 | indexId: number,
24 | channels: FilestoreChannels,
25 | ): IndexedDataChunk => {
26 | const indexFile = readIndexChunk(
27 | fileId,
28 | indexId,
29 | indexId === 255
30 | ? channels.metaChannel
31 | : channels.indexChannels[indexId],
32 | );
33 | if (!indexFile) {
34 | throw new Error(
35 | `Error parsing index file for file ID ${fileId} in index ${indexId}.`,
36 | );
37 | }
38 |
39 | const dataFile = readDataChunk(fileId, indexFile, channels.dataChannel);
40 | if (!dataFile) {
41 | throw new Error(
42 | `Error parsing data file for file ID ${fileId} in index ${indexId}.`,
43 | );
44 | }
45 |
46 | return { indexFile, dataFile };
47 | };
48 |
49 | export const readIndexChunk = (
50 | fileId: number,
51 | indexId: number,
52 | indexChannel: ByteBuffer,
53 | ): IndexChunk => {
54 | const ptr = fileId * indexFileLength;
55 | if (ptr < 0 || ptr >= indexChannel.length) {
56 | throw new Error('File Not Found');
57 | }
58 |
59 | const buf = new ByteBuffer(indexFileLength);
60 | indexChannel.copy(buf, 0, ptr, ptr + indexFileLength);
61 |
62 | if (buf.readable !== indexFileLength) {
63 | throw new Error(
64 | `Not Enough Readable Index Data: Buffer contains ${buf.readable} but needed ${indexFileLength}`,
65 | );
66 | }
67 |
68 | const size = buf.get('INT24');
69 | const sector = buf.get('INT24');
70 | return { indexId, fileId, size, sector };
71 | };
72 |
73 | export const writeIndexChunk = (
74 | indexChunk: IndexChunk,
75 | indexChannel: ByteBuffer,
76 | ): void => {
77 | const indexBuffer = new ByteBuffer(indexFileLength);
78 | indexBuffer.put(indexChunk.size, 'INT24');
79 | indexBuffer.put(indexChunk.sector, 'INT24');
80 |
81 | indexChannel.writerIndex = indexChunk.indexId * indexFileLength;
82 | indexChannel.putBytes(indexBuffer);
83 | };
84 |
85 | export const readDataChunk = (
86 | fileId: number,
87 | indexFile: IndexChunk,
88 | dataChannel: ByteBuffer,
89 | ): ByteBuffer => {
90 | const data = new ByteBuffer(indexFile.size);
91 |
92 | let chunk = 0;
93 | let remaining = indexFile.size;
94 | let ptr = indexFile.sector * sectorLength;
95 |
96 | do {
97 | const buf = new ByteBuffer(sectorLength);
98 | dataChannel.copy(buf, 0, ptr, ptr + sectorLength);
99 |
100 | if (buf.readable !== sectorLength) {
101 | throw new Error(
102 | `Not Enough Readable Sector Data: Buffer contains ${buf.readable} but needed ${sectorLength}`,
103 | );
104 | }
105 |
106 | const sectorId = buf.get('SHORT', 'UNSIGNED');
107 | const sectorChunk = buf.get('SHORT', 'UNSIGNED');
108 | const nextSector = buf.get('INT24');
109 | const sectorIndex = buf.get('BYTE', 'UNSIGNED');
110 | const sectorData = new ByteBuffer(dataChunkLength);
111 | buf.copy(
112 | sectorData,
113 | 0,
114 | buf.readerIndex,
115 | buf.readerIndex + dataChunkLength,
116 | );
117 |
118 | if (remaining > dataChunkLength) {
119 | sectorData.copy(data, data.writerIndex, 0, dataChunkLength);
120 | data.writerIndex = data.writerIndex + dataChunkLength;
121 | remaining -= dataChunkLength;
122 |
123 | if (sectorIndex !== indexFile.indexId) {
124 | throw new Error('File type mismatch.');
125 | }
126 |
127 | if (sectorId !== fileId) {
128 | throw new Error('File id mismatch.');
129 | }
130 |
131 | if (sectorChunk !== chunk++) {
132 | throw new Error('Chunk mismatch.');
133 | }
134 |
135 | ptr = nextSector * sectorLength;
136 | } else {
137 | sectorData.copy(data, data.writerIndex, 0, remaining);
138 | data.writerIndex = data.writerIndex + remaining;
139 | remaining = 0;
140 | }
141 | } while (remaining > 0);
142 |
143 | return data;
144 | };
145 |
146 | export const writeDataChunk = (
147 | indexId: number,
148 | fileId: number,
149 | fileBuffer: ByteBuffer,
150 | filestoreChannels: FilestoreChannels,
151 | ): void => {
152 | let sector: number;
153 |
154 | const writeBuffer = new ByteBuffer(sectorLength);
155 |
156 | sector =
157 | (filestoreChannels.dataChannel.length + (sectorLength - 1)) /
158 | sectorLength;
159 | if (sector === 0) {
160 | sector = 1;
161 | }
162 |
163 | for (let i = 0; fileBuffer.readable > 0; i++) {
164 | let nextSector = 0;
165 | let writableDataLength = 0;
166 |
167 | if (nextSector === 0) {
168 | nextSector =
169 | (filestoreChannels.dataChannel.length + (sectorLength - 1)) /
170 | sectorLength;
171 | if (nextSector === 0) {
172 | nextSector++;
173 | }
174 |
175 | if (nextSector === sector) {
176 | nextSector++;
177 | }
178 | }
179 |
180 | let writableMax: number;
181 |
182 | if (0xffff < fileId) {
183 | writableMax = 510;
184 | writeBuffer.put(fileId, 'INT');
185 | } else {
186 | writableMax = 512;
187 | writeBuffer.put(fileId, 'SHORT');
188 | }
189 |
190 | if (fileBuffer.readable <= writableMax) {
191 | nextSector = 0;
192 | }
193 |
194 | writeBuffer.put(i, 'SHORT');
195 | writeBuffer.put(nextSector, 'INT24');
196 | writeBuffer.put(indexId);
197 |
198 | filestoreChannels.dataChannel.writerIndex = sectorLength * sector;
199 |
200 | // Ensure space
201 | if (
202 | filestoreChannels.dataChannel.length <
203 | filestoreChannels.dataChannel.writerIndex + writeBuffer.length
204 | ) {
205 | const newBuffer = new ByteBuffer(
206 | filestoreChannels.dataChannel.writerIndex + writeBuffer.length,
207 | );
208 | filestoreChannels.dataChannel.copy(
209 | newBuffer,
210 | 0,
211 | 0,
212 | filestoreChannels.dataChannel.length,
213 | );
214 | newBuffer.writerIndex = filestoreChannels.dataChannel.writerIndex;
215 | filestoreChannels.dataChannel = newBuffer;
216 | }
217 |
218 | // Write the header
219 | filestoreChannels.dataChannel.putBytes(writeBuffer.getSlice(0, 8));
220 |
221 | writableDataLength = fileBuffer.readable;
222 | if (writableDataLength > writableMax) {
223 | writableDataLength = writableMax;
224 | }
225 |
226 | writeBuffer.putBytes(
227 | fileBuffer.getSlice(fileBuffer.readerIndex, writableDataLength),
228 | );
229 | fileBuffer.readerIndex += writableDataLength;
230 |
231 | // Ensure space
232 | if (
233 | filestoreChannels.dataChannel.length <
234 | filestoreChannels.dataChannel.writerIndex + writeBuffer.length
235 | ) {
236 | const newBuffer = new ByteBuffer(
237 | filestoreChannels.dataChannel.writerIndex + writeBuffer.length,
238 | );
239 | filestoreChannels.dataChannel.copy(
240 | newBuffer,
241 | 0,
242 | 0,
243 | filestoreChannels.dataChannel.length,
244 | );
245 | newBuffer.writerIndex = filestoreChannels.dataChannel.writerIndex;
246 | filestoreChannels.dataChannel = newBuffer;
247 | }
248 |
249 | // Write the sector
250 | filestoreChannels.dataChannel.putBytes(
251 | writeBuffer.getSlice(
252 | writeBuffer.readerIndex,
253 | writeBuffer.length - writeBuffer.readerIndex,
254 | ),
255 | );
256 |
257 | sector = nextSector;
258 | }
259 | };
260 |
--------------------------------------------------------------------------------
/src/filestore/data/compression.ts:
--------------------------------------------------------------------------------
1 | import { ByteBuffer } from '@runejs/common';
2 | import { gunzipSync } from 'node:zlib';
3 | const seekBzip = require('seek-bzip');
4 |
5 | export function decompress(
6 | buffer: ByteBuffer,
7 | keys?: number[],
8 | ): { compression: number; buffer: ByteBuffer; version: number } {
9 | if (!buffer || buffer.length === 0) {
10 | return { compression: -1, buffer: null, version: -1 };
11 | }
12 |
13 | const compression = buffer.get('BYTE', 'UNSIGNED');
14 | const compressedLength = buffer.get('INT');
15 |
16 | if (
17 | keys &&
18 | keys.length === 4 &&
19 | (keys[0] !== 0 || keys[1] !== 0 || keys[2] !== 0 || keys[3] !== 0)
20 | ) {
21 | const readerIndex = buffer.readerIndex;
22 | let lengthOffset = readerIndex;
23 | if (buffer.length - (compressedLength + readerIndex + 4) >= 2) {
24 | lengthOffset += 2;
25 | }
26 | const decryptedData = decryptXtea(
27 | buffer,
28 | keys,
29 | buffer.length - lengthOffset,
30 | );
31 | decryptedData.copy(buffer, readerIndex, 0);
32 | buffer.readerIndex = readerIndex;
33 | }
34 |
35 | if (compression === 0) {
36 | // Uncompressed file
37 | const data = new ByteBuffer(compressedLength);
38 | buffer.copy(data, 0, buffer.readerIndex, compressedLength);
39 | const decryptedData = decryptXtea(data, keys, compressedLength);
40 | buffer.readerIndex = buffer.readerIndex + compressedLength;
41 |
42 | let version = -1;
43 | if (buffer.readable >= 2) {
44 | version = buffer.get('SHORT');
45 | }
46 |
47 | return { compression, buffer: decryptedData, version };
48 | }
49 | // Compressed file
50 | const uncompressedLength = buffer.get('INT');
51 | if (uncompressedLength < 0) {
52 | throw new Error('Invalid uncompressed length');
53 | }
54 |
55 | const decryptedData = new ByteBuffer(
56 | compression === 1
57 | ? uncompressedLength
58 | : buffer.length - buffer.readerIndex + 2,
59 | );
60 | buffer.copy(decryptedData, 0, buffer.readerIndex);
61 |
62 | let decompressed: ByteBuffer;
63 | if (compression === 1) {
64 | // BZIP2
65 | decompressed = decompressBzip(decryptedData);
66 | } else if (compression === 2) {
67 | // GZIP
68 | decompressed = new ByteBuffer(gunzipSync(decryptedData));
69 | } else {
70 | throw new Error('Invalid compression type');
71 | }
72 |
73 | buffer.readerIndex = buffer.readerIndex + compressedLength;
74 |
75 | if (decompressed.length !== uncompressedLength) {
76 | throw new Error('Length mismatch');
77 | }
78 |
79 | let version = -1;
80 | if (buffer.readable >= 2) {
81 | version = buffer.get('SHORT');
82 | }
83 |
84 | return { compression, buffer: decompressed, version };
85 | }
86 |
87 | export function decryptXtea(
88 | input: ByteBuffer,
89 | keys: number[],
90 | length: number,
91 | ): ByteBuffer {
92 | if (!keys || keys.length === 0) {
93 | return input;
94 | }
95 |
96 | const output = new ByteBuffer(length);
97 | const numBlocks = Math.floor(length / 8);
98 |
99 | for (let block = 0; block < numBlocks; block++) {
100 | let v0 = input.get('INT');
101 | let v1 = input.get('INT');
102 | let sum = 0x9e3779b9 * 32;
103 |
104 | for (let i = 0; i < 32; i++) {
105 | v1 -=
106 | ((toInt(v0 << 4) ^ toInt(v0 >>> 5)) + v0) ^
107 | (sum + keys[(sum >>> 11) & 3]);
108 | v1 = toInt(v1);
109 |
110 | sum -= 0x9e3779b9;
111 |
112 | v0 -=
113 | ((toInt(v1 << 4) ^ toInt(v1 >>> 5)) + v1) ^
114 | (sum + keys[sum & 3]);
115 | v0 = toInt(v0);
116 | }
117 |
118 | output.put(v0, 'INT');
119 | output.put(v1, 'INT');
120 | }
121 |
122 | input.copy(output, output.writerIndex, input.readerIndex);
123 | return output;
124 | }
125 |
126 | function toInt(value): number {
127 | return value | 0;
128 | }
129 |
130 | export function decompressBzip(data: ByteBuffer): ByteBuffer {
131 | const buffer = Buffer.alloc(data.length + 4);
132 | data.copy(buffer, 4);
133 | buffer[0] = 'B'.charCodeAt(0);
134 | buffer[1] = 'Z'.charCodeAt(0);
135 | buffer[2] = 'h'.charCodeAt(0);
136 | buffer[3] = '1'.charCodeAt(0);
137 |
138 | return new ByteBuffer(seekBzip.decode(buffer));
139 | }
140 |
--------------------------------------------------------------------------------
/src/filestore/data/filestore-loader.ts:
--------------------------------------------------------------------------------
1 | import { ByteBuffer } from '@runejs/common';
2 | import { readFileSync } from 'node:fs';
3 | import { join } from 'node:path';
4 |
5 | export interface FilestoreChannels {
6 | dataChannel: ByteBuffer;
7 | indexChannels: ByteBuffer[];
8 | metaChannel: ByteBuffer;
9 | }
10 |
11 | export const loadFilestore = (dir: string): FilestoreChannels => {
12 | const dataChannel = new ByteBuffer(
13 | readFileSync(join(dir, 'main_file_cache.dat2')),
14 | );
15 | const indexChannels = [];
16 |
17 | for (let i = 0; i < 254; i++) {
18 | try {
19 | const index = new ByteBuffer(
20 | readFileSync(join(dir, `main_file_cache.idx${i}`)),
21 | );
22 | indexChannels.push(index);
23 | } catch (error) {
24 | break;
25 | }
26 | }
27 |
28 | const metaChannel = new ByteBuffer(
29 | readFileSync(join(dir, 'main_file_cache.idx255')),
30 | );
31 |
32 | return {
33 | dataChannel,
34 | indexChannels,
35 | metaChannel,
36 | };
37 | };
38 |
--------------------------------------------------------------------------------
/src/filestore/data/index.ts:
--------------------------------------------------------------------------------
1 | export * from './chunk';
2 | export * from './compression';
3 | export * from './filestore-loader';
4 |
--------------------------------------------------------------------------------
/src/filestore/file-data.ts:
--------------------------------------------------------------------------------
1 | import { ByteBuffer } from '@runejs/common';
2 |
3 | import {
4 | decompress,
5 | readIndexedDataChunk,
6 | type FilestoreChannels,
7 | } from './data';
8 | import type { FileIndex } from './file-index';
9 |
10 | export class FileData {
11 | /**
12 | * The ID of this file within it's File Index.
13 | */
14 | public readonly fileId: number;
15 |
16 | /**
17 | * The File Index that this file belongs to.
18 | */
19 | public readonly index: FileIndex;
20 |
21 | /**
22 | * A numeric hash of the file's name.
23 | */
24 | public nameHash: number;
25 |
26 | /**
27 | * A buffer of the file's raw data.
28 | */
29 | public content: ByteBuffer;
30 |
31 | /**
32 | * CRC value of the file's data.
33 | */
34 | public crc: number;
35 |
36 | /**
37 | * Whirlpool value of the file's data.
38 | */
39 | public whirlpool: ByteBuffer = new ByteBuffer(64);
40 |
41 | /**
42 | * Version number of the file.
43 | */
44 | public version: number;
45 |
46 | /**
47 | * The compression method used by the file in storage.
48 | */
49 | public compression: number;
50 |
51 | /**
52 | * The type of file, either an `archive` or a plain `file`.
53 | */
54 | public type: 'archive' | 'file' = 'file';
55 |
56 | protected readonly filestoreChannels: FilestoreChannels;
57 | private decompressed = false;
58 |
59 | /**
60 | * Creates a new `FileData` object.
61 | * @param fileId The ID of the file within it's File Index.
62 | * @param index The File Index that this file belongs to.
63 | * @param filestoreChannels The main filestore channel for data access.
64 | */
65 | public constructor(
66 | fileId: number,
67 | index: FileIndex,
68 | filestoreChannels: FilestoreChannels,
69 | ) {
70 | this.fileId = fileId;
71 | this.index = index;
72 | this.filestoreChannels = filestoreChannels;
73 | }
74 |
75 | /**
76 | * Reads the file's raw data from the main disk filestore and decompresses it.
77 | * @param keys The XTEA keys.
78 | * @returns The decompressed file data buffer.
79 | */
80 | public decompress(keys?: number[]): ByteBuffer {
81 | if (this.decompressed) {
82 | this.content.readerIndex = 0;
83 | this.content.writerIndex = 0;
84 | return this.content;
85 | }
86 |
87 | this.decompressed = true;
88 | const archiveEntry = readIndexedDataChunk(
89 | this.fileId,
90 | this.index.indexId,
91 | this.filestoreChannels,
92 | );
93 | const { buffer } = decompress(archiveEntry?.dataFile, keys);
94 | this.content = buffer;
95 | return this.content;
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/filestore/file-index.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 |
3 | import { Archive } from './archive';
4 | import { FileData } from './file-data';
5 | import {
6 | type FilestoreChannels,
7 | readIndexedDataChunk,
8 | decompress,
9 | } from './data';
10 | import { hash } from './util';
11 |
12 | const NAME_FLAG = 0x01;
13 | const WHIRLPOOL_FLAG = 0x02;
14 |
15 | /**
16 | * String representations of numeric index ids.
17 | */
18 | export type IndexId =
19 | | 'configs'
20 | | 'sprites'
21 | | 'music'
22 | | 'jingles'
23 | | 'sounds'
24 | | 'binary'
25 | | 'widgets'
26 | | 'regions'
27 | | 'models'
28 | | 'textures'
29 | | 'scripts'
30 | | 'frames'
31 | | 'skeletons';
32 |
33 | /**
34 | * A map of unique index keys to numeric ids.
35 | */
36 | export const indexIdMap: { [key: string]: number } = {
37 | skeletons: 0,
38 | frames: 1,
39 | configs: 2,
40 | widgets: 3,
41 | sounds: 4,
42 | regions: 5,
43 | music: 6,
44 | models: 7,
45 | sprites: 8,
46 | textures: 9,
47 | binary: 10,
48 | jingles: 11,
49 | scripts: 12,
50 | };
51 |
52 | /**
53 | * Finds the corresponding string index key for the given numeric id.
54 | * @param index The numeric index id to find the name of.
55 | */
56 | export const getIndexId = (index: number): IndexId => {
57 | const ids: string[] = Object.keys(indexIdMap);
58 | for (const id of ids) {
59 | if (indexIdMap[id] === index) {
60 | return id as IndexId;
61 | }
62 | }
63 |
64 | return null;
65 | };
66 |
67 | export class FileIndex {
68 | /**
69 | * The ID of this File Index.
70 | */
71 | public readonly indexId: number;
72 |
73 | /**
74 | * The file format used by the File Index.
75 | */
76 | public format: number;
77 |
78 | /**
79 | * The current version of the File Index, if versioned.
80 | */
81 | public version: number;
82 |
83 | /**
84 | * The method used by the File Index for data compression.
85 | */
86 | public compression: number;
87 |
88 | /**
89 | * Additional settings and information about the File Index (name & whirlpool information).
90 | */
91 | public settings: number;
92 |
93 | /**
94 | * A map of all files housed within this File Index. Values are either an `Archive` or `FileData` object.
95 | */
96 | public files: Map = new Map<
97 | number,
98 | Archive | FileData
99 | >();
100 |
101 | private readonly filestoreChannels: FilestoreChannels;
102 |
103 | /**
104 | * Creates a new File Index with the specified index ID and filestore channel.
105 | * @param indexId The ID of this File Index.
106 | * @param filestoreChannels The main filestore channel for data access.
107 | */
108 | public constructor(indexId: number, filestoreChannels: FilestoreChannels) {
109 | this.indexId = indexId;
110 | this.filestoreChannels = filestoreChannels;
111 | }
112 |
113 | /**
114 | * Fetches a single file from this index.
115 | * @param fileId The ID of the file to fetch.
116 | * @returns The requested FileData object, or null if no matching file was found.
117 | */
118 | public getFile(fileId: number): FileData | null;
119 |
120 | /**
121 | * Fetches a single file from this index.
122 | * @param fileName The name of the file to fetch.
123 | * @returns The requested FileData object, or null if no matching file was found.
124 | */
125 | public getFile(fileName: string): FileData | null;
126 |
127 | /**
128 | * Fetches a single file from this index.
129 | * @param fileIdOrName The ID or name of the file to fetch.
130 | * @param keys The XTEA keys.
131 | * @returns The requested FileData object, or null if no matching file was found.
132 | */
133 | public getFile(
134 | fileIdOrName: number | string,
135 | keys?: number[],
136 | ): FileData | null;
137 | public getFile(
138 | fileIdOrName: number | string,
139 | keys?: number[],
140 | ): FileData | null {
141 | let fileData: FileData;
142 |
143 | if (typeof fileIdOrName === 'string') {
144 | fileData = this.findByName(fileIdOrName) as FileData;
145 | } else {
146 | const archiveId = fileIdOrName as number;
147 | fileData = this.files.get(archiveId) as FileData;
148 | }
149 |
150 | if (!fileData) {
151 | return null;
152 | }
153 |
154 | if (fileData.type === 'archive') {
155 | logger.error(fileData);
156 | throw new Error(
157 | `Requested item ${fileIdOrName} in index ${this.indexId} is of type Archive, not FileData.`,
158 | );
159 | }
160 |
161 | try {
162 | fileData.decompress(keys);
163 | } catch (e) {
164 | logger.warn(
165 | `Unable to decompress file ${fileIdOrName} in index ${this.indexId} with keys ${keys}`,
166 | );
167 | return null;
168 | }
169 |
170 | return fileData;
171 | }
172 |
173 | /**
174 | * Fetches an archive from this index.
175 | * @param archiveId The ID of the archive to fetch.
176 | * @returns The requested Archive object, or null if no Archive was found.
177 | */
178 | public getArchive(archiveId: number): Archive | null;
179 |
180 | /**
181 | * Fetches an archive from this index.
182 | * @param archiveName The name of the archive to fetch.
183 | * @returns The requested Archive object, or null if no Archive was found.
184 | */
185 | public getArchive(archiveName: string): Archive | null;
186 |
187 | /**
188 | * Fetches an archive from this index.
189 | * @param archiveIdOrName The ID or name of the archive to fetch.
190 | * @returns The requested Archive object, or null if no Archive was found.
191 | */
192 | public getArchive(archiveIdOrName: number | string): Archive | null;
193 | public getArchive(archiveIdOrName: number | string): Archive | null {
194 | let archive: Archive;
195 |
196 | if (typeof archiveIdOrName === 'string') {
197 | archive = this.findByName(archiveIdOrName) as Archive;
198 | } else {
199 | const archiveId = archiveIdOrName as number;
200 | archive = this.files.get(archiveId) as Archive;
201 | }
202 |
203 | if (!archive) {
204 | return null;
205 | }
206 |
207 | if (archive.type === 'file') {
208 | throw new Error(
209 | `Requested item ${archiveIdOrName} in index ${this.indexId} is of type FileData, not Archive.`,
210 | );
211 | }
212 |
213 | archive.decodeArchiveFiles();
214 |
215 | return archive;
216 | }
217 |
218 | /**
219 | * Fetches an archive or file from this index by name.
220 | * @param fileName The name of the archive or file to search for.
221 | * @returns An Archive or FileData object, or null if no matching files were found with the specified name.
222 | */
223 | public findByName(fileName: string): Archive | FileData | null {
224 | const indexFileCount = this.files.size;
225 | const nameHash = hash(fileName);
226 | for (let fileId = 0; fileId < indexFileCount; fileId++) {
227 | const item = this.files.get(fileId);
228 | if (item?.nameHash === nameHash) {
229 | return item;
230 | }
231 | }
232 |
233 | return null;
234 | }
235 |
236 | /**
237 | * Decodes the packed index file data from the filestore on disk.
238 | */
239 | public decodeIndex(): void {
240 | const indexEntry = readIndexedDataChunk(
241 | this.indexId,
242 | 255,
243 | this.filestoreChannels,
244 | );
245 | const { compression, version, buffer } = decompress(
246 | indexEntry.dataFile,
247 | );
248 |
249 | this.version = version;
250 | this.compression = compression;
251 |
252 | /* file header */
253 | this.format = buffer.get('BYTE', 'UNSIGNED');
254 | if (this.format >= 6) {
255 | this.version = buffer.get('INT');
256 | }
257 | this.settings = buffer.get('BYTE', 'UNSIGNED');
258 |
259 | /* file ids */
260 | const fileCount = buffer.get('SHORT', 'UNSIGNED');
261 | const ids: number[] = new Array(fileCount);
262 | let accumulator = 0;
263 | let size = -1;
264 | for (let i = 0; i < ids.length; i++) {
265 | const delta = buffer.get('SHORT', 'UNSIGNED');
266 | ids[i] = accumulator += delta;
267 | if (ids[i] > size) {
268 | size = ids[i];
269 | }
270 | }
271 |
272 | size++;
273 |
274 | for (const id of ids) {
275 | this.files.set(id, new FileData(id, this, this.filestoreChannels));
276 | }
277 |
278 | /* read the name hashes if present */
279 | if ((this.settings & NAME_FLAG) !== 0) {
280 | for (const id of ids) {
281 | const nameHash = buffer.get('INT');
282 | this.files.get(id).nameHash = nameHash;
283 | }
284 | }
285 |
286 | /* read the crc values */
287 | for (const id of ids) {
288 | this.files.get(id).crc = buffer.get('INT');
289 | }
290 |
291 | /* read the whirlpool values */
292 | if ((this.settings & WHIRLPOOL_FLAG) !== 0) {
293 | for (const id of ids) {
294 | buffer.copy(
295 | this.files.get(id).whirlpool,
296 | 0,
297 | buffer.readerIndex,
298 | buffer.readerIndex + 64,
299 | );
300 | buffer.readerIndex = buffer.readerIndex + 64;
301 | }
302 | }
303 |
304 | /* read the version numbers */
305 | for (const id of ids) {
306 | this.files.get(id).version = buffer.get('INT');
307 | }
308 |
309 | /* read the child sizes */
310 | const members: number[][] = new Array(size).fill([]);
311 | for (const id of ids) {
312 | members[id] = new Array(buffer.get('SHORT', 'UNSIGNED'));
313 | }
314 |
315 | /* read the child ids */
316 | for (const id of ids) {
317 | accumulator = 0;
318 | size = -1;
319 |
320 | for (let i = 0; i < members[id].length; i++) {
321 | const delta = buffer.get('SHORT', 'UNSIGNED');
322 | members[id][i] = accumulator += delta;
323 | if (members[id][i] > size) {
324 | size = members[id][i];
325 | }
326 | }
327 |
328 | size++;
329 |
330 | /* allocate specific entries within the array */
331 | const file = this.files.get(id);
332 | if (members[id].length > 1) {
333 | if (file.type === 'file') {
334 | this.files.set(
335 | id,
336 | new Archive(file, this, this.filestoreChannels),
337 | );
338 | }
339 |
340 | const archive = this.files.get(id) as Archive;
341 |
342 | for (const childId of members[id]) {
343 | archive.files.set(
344 | childId,
345 | new FileData(childId, this, this.filestoreChannels),
346 | );
347 | }
348 | }
349 | }
350 |
351 | /* read the child name hashes */
352 | if ((this.settings & NAME_FLAG) !== 0) {
353 | for (const id of ids) {
354 | const archive = this.files.get(id) as Archive;
355 | for (const childId of members[id]) {
356 | const nameHash = buffer.get('INT');
357 | if (archive?.files?.get(childId)) {
358 | archive.files.get(childId).nameHash = nameHash;
359 | }
360 | }
361 | }
362 | }
363 | }
364 | }
365 |
--------------------------------------------------------------------------------
/src/filestore/filestore.ts:
--------------------------------------------------------------------------------
1 | import { type FilestoreChannels, loadFilestore } from './data';
2 | import { FileIndex, type IndexId, indexIdMap } from './file-index';
3 | import { getFileNames } from './util';
4 | import {
5 | SpriteStore,
6 | MusicStore,
7 | BinaryStore,
8 | JingleStore,
9 | SoundStore,
10 | RegionStore,
11 | ConfigStore,
12 | ModelStore,
13 | WidgetStore,
14 | FontStore,
15 | TextureStore,
16 | type ItemStore,
17 | type NpcStore,
18 | type ObjectStore,
19 | type XteaDefinition,
20 | type VarbitStore,
21 | } from './stores';
22 |
23 | export let fileNames: { [key: string]: string | null };
24 |
25 | export const getFileName = (nameHash: number): string | null => {
26 | return fileNames[nameHash.toString()] || nameHash.toString();
27 | };
28 |
29 | export class Filestore {
30 | public readonly filestoreDir: string;
31 | public readonly configDir: string;
32 |
33 | public readonly binaryStore: BinaryStore;
34 | public readonly configStore: ConfigStore;
35 | public readonly fontStore: FontStore;
36 | public readonly jingleStore: JingleStore;
37 | public readonly modelStore: ModelStore;
38 | public readonly musicStore: MusicStore;
39 | public readonly regionStore: RegionStore;
40 | public readonly soundStore: SoundStore;
41 | public readonly spriteStore: SpriteStore;
42 | public readonly widgetStore: WidgetStore;
43 | public readonly textureStore: TextureStore;
44 |
45 | public readonly channels: FilestoreChannels;
46 |
47 | public readonly indexes = new Map();
48 |
49 | public constructor(
50 | filestoreDir: string,
51 | options?: {
52 | configDir?: string;
53 | xteas?: { [key: number]: XteaDefinition };
54 | },
55 | ) {
56 | this.filestoreDir = filestoreDir;
57 | this.configDir = options?.configDir || filestoreDir;
58 | this.channels = loadFilestore(filestoreDir);
59 |
60 | fileNames = getFileNames(this.configDir);
61 |
62 | this.binaryStore = new BinaryStore(this);
63 | this.configStore = new ConfigStore(this);
64 | this.fontStore = new FontStore(this);
65 | this.jingleStore = new JingleStore(this);
66 | this.modelStore = new ModelStore(this);
67 | this.musicStore = new MusicStore(this);
68 | this.regionStore = new RegionStore(this, options?.xteas);
69 | this.soundStore = new SoundStore(this);
70 | this.spriteStore = new SpriteStore(this);
71 | this.widgetStore = new WidgetStore(this);
72 | this.textureStore = new TextureStore(this);
73 |
74 | this.fontStore.loadFonts();
75 | }
76 |
77 | /**
78 | * Fetches the specified File Index.
79 | * @param indexId The string or numberic ID of the File Index to find.
80 | */
81 | public getIndex(inputIndexId: number | IndexId): FileIndex {
82 | let indexId = inputIndexId;
83 | if (typeof indexId !== 'number') {
84 | indexId = indexIdMap[indexId];
85 | }
86 |
87 | if (!this.indexes.has(indexId)) {
88 | const archiveIndex = new FileIndex(indexId, this.channels);
89 | archiveIndex.decodeIndex();
90 | this.indexes.set(indexId, archiveIndex);
91 | return archiveIndex;
92 | }
93 | return this.indexes.get(indexId);
94 | }
95 |
96 | public get itemStore(): ItemStore {
97 | return this.configStore?.itemStore;
98 | }
99 |
100 | public get varbitStore(): VarbitStore {
101 | return this.configStore?.varbitStore;
102 | }
103 |
104 | public get npcStore(): NpcStore {
105 | return this.configStore?.npcStore;
106 | }
107 |
108 | public get objectStore(): ObjectStore {
109 | return this.configStore?.objectStore;
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/src/filestore/index.ts:
--------------------------------------------------------------------------------
1 | export * from './archive';
2 | export * from './file-data';
3 | export * from './file-index';
4 | export * from './filestore';
5 |
6 | export * from './data';
7 | export * from './stores';
8 | export * from './util';
9 |
--------------------------------------------------------------------------------
/src/filestore/stores/binary-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 | import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3 |
4 | import { type Filestore, getFileName } from '../filestore';
5 | import type { FileData } from '../file-data';
6 |
7 | /**
8 | * Controls misc binary file storage.
9 | */
10 | export class BinaryStore {
11 | public constructor(private fileStore: Filestore) {}
12 |
13 | /**
14 | * Writes the specified file or all binary files to the disk.
15 | * @param binaryFile [optional] The file to write to disk. Writes all stored binary files to disk if not provided.
16 | */
17 | public async writeToDisk(binaryFile?: FileData): Promise {
18 | if (!binaryFile) {
19 | // Write all files
20 | const binaryFiles: FileData[] = this.decodeBinaryFileStore();
21 | binaryFiles.forEach(async (file) => this.writeToDisk(file));
22 | } else {
23 | // Write single file
24 | return new Promise((resolve, reject) => {
25 | try {
26 | const fileName = getFileName(binaryFile.nameHash).replace(
27 | / /g,
28 | '_',
29 | );
30 | if (!existsSync('./unpacked/binary')) {
31 | mkdirSync('./unpacked/binary');
32 | }
33 | writeFileSync(
34 | `./unpacked/binary/${binaryFile.fileId}_${fileName}`,
35 | Buffer.from(binaryFile.content),
36 | );
37 | resolve();
38 | } catch (error) {
39 | reject(error);
40 | }
41 | });
42 | }
43 | }
44 |
45 | /**
46 | * Fetches the specified binary file.
47 | * @param nameOrId The name or ID of the binary file.
48 | * @returns The binary FileData object, or null if the file is not found.
49 | */
50 | public getBinaryFile(nameOrId: string | number): FileData | null {
51 | if (!nameOrId) {
52 | return null;
53 | }
54 |
55 | const binaryIndex = this.fileStore.getIndex('binary');
56 | return binaryIndex.getFile(nameOrId) || null;
57 | }
58 |
59 | /**
60 | * Decodes all binary files within the binary store.
61 | * @returns The list of decoded files from the binary store.
62 | */
63 | public decodeBinaryFileStore(): FileData[] {
64 | const binaryIndex = this.fileStore.getIndex('binary');
65 | const binaryFileCount = binaryIndex.files.size;
66 | const binaryFiles: FileData[] = new Array(binaryFileCount);
67 |
68 | for (
69 | let binaryFileId = 0;
70 | binaryFileId < binaryFileCount;
71 | binaryFileId++
72 | ) {
73 | const fileData = binaryIndex.getFile(binaryFileId);
74 | if (!fileData) {
75 | binaryFiles[binaryFileId] = null;
76 | logger.warn(
77 | `No file found for binary file ID ${binaryFileId}.`,
78 | );
79 | continue;
80 | }
81 |
82 | binaryFiles[binaryFileId] = fileData;
83 | }
84 |
85 | return binaryFiles;
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/filestore/stores/config-store.ts:
--------------------------------------------------------------------------------
1 | import type { Filestore } from '../filestore';
2 | import type { FileIndex } from '../file-index';
3 | import type { Archive } from '../archive';
4 | import { NpcStore, ObjectStore, ItemStore, VarbitStore } from './configs';
5 |
6 | /**
7 | * String representations of config file/archive ids.
8 | */
9 | export type ConfigId =
10 | | 'character'
11 | | 'objects'
12 | | 'npcs'
13 | | 'items'
14 | | 'animations'
15 | | 'graphics'
16 | | 'varbits';
17 |
18 | /**
19 | * A map of unique config keys to file/archive ids within the config store.
20 | */
21 | export const configIdMap: { [key: string]: number } = {
22 | character: 3,
23 | objects: 6,
24 | npcs: 9,
25 | items: 10,
26 | animations: 12,
27 | graphics: 13,
28 | varbits: 14,
29 | };
30 |
31 | /**
32 | * Finds the corresponding string config key for the given numeric id.
33 | * @param config The numeric config file/archive id to find the name of.
34 | */
35 | export const getConfigId = (config: number): ConfigId => {
36 | const ids: string[] = Object.keys(configIdMap);
37 | for (const id of ids) {
38 | if (configIdMap[id] === config) {
39 | return id as ConfigId;
40 | }
41 | }
42 |
43 | return null;
44 | };
45 |
46 | /**
47 | * Contains various configuration related Archives.
48 | */
49 | export class ConfigStore {
50 | /**
51 | * A Store used to access the Item Archive, containing details about every game item.
52 | */
53 | public readonly itemStore: ItemStore;
54 |
55 | /**
56 | * A Store used to access the Npc Archive, containing details about every game npc.
57 | */
58 | public readonly npcStore: NpcStore;
59 |
60 | /**
61 | * A Store used to access the Object Archive, containing details about every game object.
62 | */
63 | public readonly objectStore: ObjectStore;
64 |
65 | /**
66 | * A Store used to access the Varbit Archive, containing details about every game varbit.
67 | */
68 | public readonly varbitStore: VarbitStore;
69 |
70 | /**
71 | * The configuration file/archive index.
72 | */
73 | public readonly configIndex: FileIndex;
74 |
75 | public constructor(private fileStore: Filestore) {
76 | this.configIndex = fileStore.getIndex('configs');
77 | this.itemStore = new ItemStore(this);
78 | this.npcStore = new NpcStore(this);
79 | this.objectStore = new ObjectStore(this);
80 | this.varbitStore = new VarbitStore(this);
81 | }
82 |
83 | public getArchive(inputConfigId: ConfigId | number): Archive {
84 | let configId = inputConfigId;
85 | if (typeof configId !== 'number') {
86 | configId = configIdMap[configId];
87 | }
88 |
89 | return this.configIndex.getArchive(configId);
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/filestore/stores/configs/index.ts:
--------------------------------------------------------------------------------
1 | export * from './item-store';
2 | export * from './npc-store';
3 | export * from './object-store';
4 | export * from './varbit-store';
5 |
--------------------------------------------------------------------------------
/src/filestore/stores/configs/item-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 | import { ByteBuffer } from '@runejs/common';
3 |
4 | import type { Archive } from '../../archive';
5 | import type { ConfigStore } from '../config-store';
6 | import type { FileData } from '../../file-data';
7 |
8 | /**
9 | * Contains game client need-to-know level information about a single game item.
10 | */
11 | export class ItemConfig {
12 | gameId: number;
13 | name: string | null = null;
14 | stackable?: boolean;
15 | value = 0;
16 | members?: boolean;
17 | worldOptions?: string[];
18 | widgetOptions?: string[];
19 | tradable?: boolean;
20 | teamId?: number;
21 | replacedColors?: [number, number][]; // [ originalColor, newColor ][]
22 | replacedTextures?: [number, number][];
23 | bankNoteId?: number;
24 | bankNoteTemplate?: number;
25 | stackableAmounts?: number[];
26 | stackableIds?: number[];
27 |
28 | /**
29 | * 2d modelling information for this item.
30 | */
31 | model2d: {
32 | widgetModel?: number;
33 | zoom?: number;
34 | rotationX?: number;
35 | rotationY?: number;
36 | rotationZ?: number;
37 | offsetX?: number;
38 | offsetY?: number;
39 | } = {};
40 |
41 | /**
42 | * 3d modelling information for this item.
43 | */
44 | model3d: {
45 | maleModels: [number, number, number];
46 | maleHeadModels: [number, number];
47 | maleModelOffset?: number;
48 | femaleModels: [number, number, number];
49 | femaleHeadModels: [number, number];
50 | femaleModelOffset?: number;
51 | } = {
52 | maleModels: [-1, -1, -1],
53 | maleHeadModels: [-1, -1],
54 | femaleModels: [-1, -1, -1],
55 | femaleHeadModels: [-1, -1],
56 | };
57 |
58 | /**
59 | * Additional rendering details.
60 | */
61 | rendering: {
62 | resizeX?: number;
63 | resizeY?: number;
64 | resizeZ?: number;
65 | ambient?: number;
66 | contrast?: number;
67 | } = {};
68 | }
69 |
70 | /**
71 | * Controls files within the Item Archive of the configuration index.
72 | */
73 | export class ItemStore {
74 | /**
75 | * The Item Archive, containing details about every game item.
76 | */
77 | public readonly itemArchive: Archive;
78 |
79 | public constructor(private configStore: ConfigStore) {
80 | this.itemArchive = this.configStore.getArchive('items');
81 | }
82 |
83 | /**
84 | * Fetches the ItemConfig object for the specified item game id.
85 | * @param itemId The game id of the item to find.
86 | */
87 | public getItem(itemId: number): ItemConfig | null {
88 | const itemArchive = this.itemArchive;
89 |
90 | if (!itemArchive) {
91 | logger.error('Item archive not found.');
92 | return null;
93 | }
94 |
95 | const itemFile = itemArchive.getFile(itemId) || null;
96 |
97 | if (!itemFile) {
98 | logger.error('Item file not found.');
99 | return null;
100 | }
101 |
102 | return this.decodeItemFile(itemFile);
103 | }
104 |
105 | public encodeItemFile(item: ItemConfig): ByteBuffer {
106 | const buffer = new ByteBuffer(5000);
107 |
108 | const putOpcode = (opcode: number): ByteBuffer => {
109 | buffer.put(opcode);
110 | return buffer;
111 | };
112 |
113 | if (item.model2d.widgetModel !== undefined) {
114 | putOpcode(1).put(item.model2d.widgetModel, 'SHORT');
115 | }
116 |
117 | if (item.name) {
118 | putOpcode(2).putString(item.name);
119 | }
120 |
121 | putOpcode(4).put(item.model2d.zoom, 'SHORT');
122 | putOpcode(5).put(item.model2d.rotationX, 'SHORT');
123 | putOpcode(6).put(item.model2d.rotationY, 'SHORT');
124 | putOpcode(7).put(item.model2d.offsetX, 'SHORT');
125 | putOpcode(8).put(item.model2d.offsetY, 'SHORT');
126 |
127 | if (item.stackable) {
128 | putOpcode(11);
129 | }
130 |
131 | putOpcode(12).put(item.value, 'INT');
132 |
133 | if (item.members) {
134 | putOpcode(16);
135 | }
136 |
137 | if (
138 | item.model3d.maleModels[0] !== -1 ||
139 | item.model3d.maleModelOffset !== undefined
140 | ) {
141 | putOpcode(23)
142 | .put(item.model3d.maleModels[0], 'SHORT')
143 | .put(item.model3d.maleModelOffset);
144 | }
145 |
146 | if (item.model3d.maleModels[1] !== -1) {
147 | putOpcode(24).put(item.model3d.maleModels[1], 'SHORT');
148 | }
149 |
150 | if (
151 | item.model3d.femaleModels[0] !== -1 ||
152 | item.model3d.femaleModelOffset !== undefined
153 | ) {
154 | putOpcode(25)
155 | .put(item.model3d.femaleModels[0], 'SHORT')
156 | .put(item.model3d.femaleModelOffset);
157 | }
158 |
159 | if (item.model3d.femaleModels[1] !== -1) {
160 | putOpcode(26).put(item.model3d.femaleModels[1], 'SHORT');
161 | }
162 |
163 | if (item.worldOptions && item.worldOptions.length !== 0) {
164 | for (let i = 0; i < 5; i++) {
165 | if (item.worldOptions[i]) {
166 | putOpcode(30 + i).putString(item.worldOptions[i]);
167 | }
168 | }
169 | }
170 |
171 | if (item.widgetOptions && item.widgetOptions.length !== 0) {
172 | for (let i = 0; i < 5; i++) {
173 | if (item.widgetOptions[i]) {
174 | putOpcode(35 + i).putString(item.widgetOptions[i]);
175 | }
176 | }
177 | }
178 |
179 | if (item.replacedColors && item.replacedColors.length !== 0) {
180 | putOpcode(40).put(item.replacedColors.length);
181 | for (const [oldColor, newColor] of item.replacedColors) {
182 | buffer.put(oldColor, 'SHORT').put(newColor, 'SHORT');
183 | }
184 | }
185 |
186 | if (item.replacedTextures && item.replacedTextures.length !== 0) {
187 | putOpcode(41).put(item.replacedTextures.length);
188 | for (const [oldTexture, newTexture] of item.replacedTextures) {
189 | buffer.put(oldTexture, 'SHORT').put(newTexture, 'SHORT');
190 | }
191 | }
192 |
193 | if (item.tradable) {
194 | putOpcode(65);
195 | }
196 |
197 | if (item.model3d.maleModels[2] !== -1) {
198 | putOpcode(78).put(item.model3d.maleModels[2], 'SHORT');
199 | }
200 |
201 | if (item.model3d.femaleModels[2] !== -1) {
202 | putOpcode(79).put(item.model3d.femaleModels[2], 'SHORT');
203 | }
204 |
205 | if (item.model3d.maleHeadModels[0] !== -1) {
206 | putOpcode(90).put(item.model3d.maleHeadModels[0], 'SHORT');
207 | }
208 |
209 | if (item.model3d.femaleHeadModels[0] !== -1) {
210 | putOpcode(91).put(item.model3d.femaleHeadModels[0], 'SHORT');
211 | }
212 |
213 | putOpcode(95).put(item.model2d.rotationZ, 'SHORT');
214 |
215 | if (item.bankNoteId) {
216 | putOpcode(97).put(item.bankNoteId, 'SHORT');
217 | }
218 |
219 | if (item.bankNoteTemplate) {
220 | putOpcode(98).put(item.bankNoteTemplate, 'SHORT');
221 | }
222 |
223 | if (item.stackableIds && item.stackableIds.length !== 0) {
224 | for (let i = 0; i < 10; i++) {
225 | putOpcode(100 + i)
226 | .put(item.stackableIds[i], 'SHORT')
227 | .put(item.stackableAmounts[i], 'SHORT');
228 | }
229 | }
230 |
231 | putOpcode(110).put(item.rendering.resizeX, 'SHORT');
232 |
233 | putOpcode(111).put(item.rendering.resizeY, 'SHORT');
234 |
235 | putOpcode(112).put(item.rendering.resizeZ, 'SHORT');
236 |
237 | putOpcode(113).put(item.rendering.ambient);
238 |
239 | putOpcode(114).put(item.rendering.contrast);
240 |
241 | putOpcode(115).put(item.teamId);
242 |
243 | putOpcode(0);
244 |
245 | return buffer.getSlice(0, buffer.writerIndex);
246 | }
247 |
248 | /**
249 | * Parses a raw item data file into a readable ItemConfig object.
250 | * @param itemFile The raw file-store item data.
251 | */
252 | public decodeItemFile(itemFile: FileData): ItemConfig {
253 | const itemConfig = new ItemConfig();
254 |
255 | const buffer = itemFile.content;
256 | itemConfig.gameId = itemFile.fileId;
257 |
258 | let run = true;
259 |
260 | while (run) {
261 | const opcode = buffer.get('BYTE', 'UNSIGNED');
262 | if (opcode === 0) {
263 | run = false;
264 | break;
265 | }
266 |
267 | if (opcode === 1) {
268 | itemConfig.model2d.widgetModel = buffer.get(
269 | 'SHORT',
270 | 'UNSIGNED',
271 | );
272 | } else if (opcode === 2) {
273 | itemConfig.name = buffer.getString();
274 | } else if (opcode === 4) {
275 | itemConfig.model2d.zoom = buffer.get('SHORT', 'UNSIGNED');
276 | } else if (opcode === 5) {
277 | itemConfig.model2d.rotationX = buffer.get('SHORT', 'UNSIGNED');
278 | } else if (opcode === 6) {
279 | itemConfig.model2d.rotationY = buffer.get('SHORT', 'UNSIGNED');
280 | } else if (opcode === 7) {
281 | itemConfig.model2d.offsetX = buffer.get('SHORT', 'UNSIGNED');
282 | if (itemConfig.model2d.offsetX > 32767) {
283 | itemConfig.model2d.offsetX -= 65536;
284 | }
285 | } else if (opcode === 8) {
286 | itemConfig.model2d.offsetY = buffer.get('SHORT', 'UNSIGNED');
287 | if (itemConfig.model2d.offsetY > 32767) {
288 | itemConfig.model2d.offsetY -= 65536;
289 | }
290 | } else if (opcode === 11) {
291 | itemConfig.stackable = true;
292 | } else if (opcode === 12) {
293 | itemConfig.value = buffer.get('INT');
294 | } else if (opcode === 16) {
295 | itemConfig.members = true;
296 | } else if (opcode === 23) {
297 | itemConfig.model3d.maleModels[0] = buffer.get(
298 | 'SHORT',
299 | 'UNSIGNED',
300 | );
301 | itemConfig.model3d.maleModelOffset = buffer.get(
302 | 'BYTE',
303 | 'UNSIGNED',
304 | );
305 | } else if (opcode === 24) {
306 | itemConfig.model3d.maleModels[1] = buffer.get(
307 | 'SHORT',
308 | 'UNSIGNED',
309 | );
310 | } else if (opcode === 25) {
311 | itemConfig.model3d.femaleModels[0] = buffer.get(
312 | 'SHORT',
313 | 'UNSIGNED',
314 | );
315 | itemConfig.model3d.femaleModelOffset = buffer.get(
316 | 'BYTE',
317 | 'UNSIGNED',
318 | );
319 | } else if (opcode === 26) {
320 | itemConfig.model3d.femaleModels[1] = buffer.get(
321 | 'SHORT',
322 | 'UNSIGNED',
323 | );
324 | } else if (opcode >= 30 && opcode < 35) {
325 | if (!itemConfig.worldOptions) {
326 | itemConfig.worldOptions = new Array(5).fill(null);
327 | }
328 |
329 | itemConfig.worldOptions[opcode - 30] = buffer.getString();
330 |
331 | if (
332 | itemConfig.worldOptions[opcode - 30] === 'Hidden' ||
333 | itemConfig.worldOptions[opcode - 30] === 'hidden'
334 | ) {
335 | itemConfig.worldOptions[opcode - 30] = null;
336 | }
337 | } else if (opcode >= 35 && opcode < 40) {
338 | if (!itemConfig.widgetOptions) {
339 | itemConfig.widgetOptions = new Array(5).fill(null);
340 | }
341 |
342 | itemConfig.widgetOptions[opcode - 35] = buffer.getString();
343 |
344 | if (
345 | itemConfig.widgetOptions[opcode - 35] === 'Hidden' ||
346 | itemConfig.widgetOptions[opcode - 35] === 'hidden'
347 | ) {
348 | itemConfig.widgetOptions[opcode - 35] = null;
349 | }
350 | } else if (opcode === 40) {
351 | const colorCount = buffer.get('BYTE', 'UNSIGNED');
352 | itemConfig.replacedColors = new Array(colorCount);
353 | itemConfig.replacedColors.fill([-1, -1]);
354 |
355 | for (
356 | let colorIndex = 0;
357 | colorIndex < colorCount;
358 | colorIndex++
359 | ) {
360 | itemConfig.replacedColors[colorIndex][0] = buffer.get(
361 | 'SHORT',
362 | 'UNSIGNED',
363 | );
364 | itemConfig.replacedColors[colorIndex][1] = buffer.get(
365 | 'SHORT',
366 | 'UNSIGNED',
367 | );
368 | }
369 | } else if (opcode === 41) {
370 | const textureCount = buffer.get('BYTE', 'UNSIGNED');
371 | itemConfig.replacedTextures = new Array(textureCount);
372 | itemConfig.replacedTextures.fill([-1, -1]);
373 |
374 | for (
375 | let textureIndex = 0;
376 | textureIndex < textureCount;
377 | textureIndex++
378 | ) {
379 | itemConfig.replacedTextures[textureIndex][0] = buffer.get(
380 | 'SHORT',
381 | 'UNSIGNED',
382 | );
383 | itemConfig.replacedTextures[textureIndex][1] = buffer.get(
384 | 'SHORT',
385 | 'UNSIGNED',
386 | );
387 | }
388 | } else if (opcode === 65) {
389 | itemConfig.tradable = true;
390 | } else if (opcode === 78) {
391 | itemConfig.model3d.maleModels[2] = buffer.get(
392 | 'SHORT',
393 | 'UNSIGNED',
394 | );
395 | } else if (opcode === 79) {
396 | itemConfig.model3d.femaleModels[2] = buffer.get(
397 | 'SHORT',
398 | 'UNSIGNED',
399 | );
400 | } else if (opcode === 90) {
401 | itemConfig.model3d.maleHeadModels[0] = buffer.get(
402 | 'SHORT',
403 | 'UNSIGNED',
404 | );
405 | } else if (opcode === 91) {
406 | itemConfig.model3d.femaleHeadModels[0] = buffer.get(
407 | 'SHORT',
408 | 'UNSIGNED',
409 | );
410 | } else if (opcode === 92) {
411 | itemConfig.model3d.maleHeadModels[1] = buffer.get(
412 | 'SHORT',
413 | 'UNSIGNED',
414 | );
415 | } else if (opcode === 93) {
416 | itemConfig.model3d.femaleHeadModels[1] = buffer.get(
417 | 'SHORT',
418 | 'UNSIGNED',
419 | );
420 | } else if (opcode === 95) {
421 | itemConfig.model2d.rotationZ = buffer.get('SHORT', 'UNSIGNED');
422 | } else if (opcode === 97) {
423 | itemConfig.bankNoteId = buffer.get('SHORT', 'UNSIGNED');
424 | } else if (opcode === 98) {
425 | itemConfig.bankNoteTemplate = buffer.get('SHORT', 'UNSIGNED');
426 | } else if (opcode >= 100 && opcode < 110) {
427 | if (!itemConfig.stackableIds) {
428 | itemConfig.stackableAmounts = new Array(10);
429 | itemConfig.stackableIds = new Array(10);
430 | }
431 | itemConfig.stackableIds[opcode - 100] = buffer.get(
432 | 'SHORT',
433 | 'UNSIGNED',
434 | );
435 | itemConfig.stackableAmounts[opcode - 100] = buffer.get(
436 | 'SHORT',
437 | 'UNSIGNED',
438 | );
439 | } else if (opcode === 110) {
440 | itemConfig.rendering.resizeX = buffer.get('SHORT', 'UNSIGNED');
441 | } else if (opcode === 111) {
442 | itemConfig.rendering.resizeY = buffer.get('SHORT', 'UNSIGNED');
443 | } else if (opcode === 112) {
444 | itemConfig.rendering.resizeZ = buffer.get('SHORT', 'UNSIGNED');
445 | } else if (opcode === 113) {
446 | itemConfig.rendering.ambient = buffer.get('BYTE');
447 | } else if (opcode === 114) {
448 | itemConfig.rendering.contrast = buffer.get('BYTE');
449 | } else if (opcode === 115) {
450 | itemConfig.teamId = buffer.get('BYTE', 'UNSIGNED');
451 | }
452 | }
453 |
454 | itemFile.content.readerIndex = 0;
455 | return itemConfig;
456 | }
457 |
458 | /**
459 | * Decodes every item file within the item archive and returns
460 | * the resulting ItemConfig array.
461 | */
462 | public decodeItemStore(): ItemConfig[] {
463 | if (!this.itemArchive) {
464 | logger.error('Item archive not found.');
465 | return null;
466 | }
467 |
468 | const itemCount = this.itemArchive.files.size;
469 | const itemList: ItemConfig[] = new Array(itemCount);
470 |
471 | for (let itemId = 0; itemId < itemCount; itemId++) {
472 | const itemFile = this.itemArchive.getFile(itemId) || null;
473 |
474 | if (!itemFile) {
475 | logger.error('Item file not found.');
476 | return null;
477 | }
478 |
479 | itemList[itemId] = this.decodeItemFile(itemFile);
480 | }
481 |
482 | return itemList;
483 | }
484 | }
485 |
--------------------------------------------------------------------------------
/src/filestore/stores/configs/npc-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 |
3 | import type { Archive } from '../../archive';
4 | import type { ConfigStore } from '../config-store';
5 | import type { FileData } from '../../file-data';
6 |
7 | /**
8 | * Contains game client need-to-know level information about a single game npc.
9 | */
10 | export class NpcConfig {
11 | gameId: number;
12 | name: string | null = null;
13 | animations: {
14 | stand: number;
15 | walk: number;
16 | turnAround: number;
17 | turnRight: number;
18 | turnLeft: number;
19 | } = {
20 | stand: -1,
21 | walk: -1,
22 | turnAround: -1,
23 | turnRight: -1,
24 | turnLeft: -1,
25 | };
26 | options?: string[];
27 | minimapVisible = true;
28 | combatLevel = -1;
29 | headIcon = -1;
30 | clickable = true;
31 | turnDegrees = 32;
32 | varbitId = -1;
33 | settingId = -1;
34 | parentId?: number;
35 | childrenIds?: number[];
36 |
37 | /**
38 | * 3d modelling information for this npc.
39 | */
40 | model: {
41 | models?: number[];
42 | headModels?: number[];
43 | } = {};
44 |
45 | /**
46 | * Additional rendering details.
47 | */
48 | rendering: {
49 | boundary: number;
50 | sizeX: number;
51 | sizeY: number;
52 | renderPriority: boolean;
53 | } = {
54 | boundary: 1,
55 | sizeX: 128,
56 | sizeY: 128,
57 | renderPriority: false,
58 | };
59 | }
60 |
61 | /**
62 | * Controls files within the NPC Archive of the configuration index.
63 | */
64 | export class NpcStore {
65 | /**
66 | * The NPC Archive, containing details about every game NPC.
67 | */
68 | public readonly npcArchive: Archive;
69 | private readonly children: Map = new Map();
70 |
71 | public constructor(private configStore: ConfigStore) {
72 | this.npcArchive = this.configStore.getArchive('npcs');
73 | }
74 |
75 | /**
76 | * Fetches the NpcConfig object for the specified npc game id.
77 | * @param npcId The game id of the npc to find.
78 | */
79 | public getNpc(npcId: number): NpcConfig | null {
80 | const npcArchive = this.npcArchive;
81 |
82 | if (!npcArchive) {
83 | logger.error('Npc archive not found.');
84 | return null;
85 | }
86 |
87 | const npcFile = npcArchive.getFile(npcId) || null;
88 |
89 | if (!npcFile) {
90 | logger.error('Npc file not found.');
91 | return null;
92 | }
93 |
94 | return this.decodeNpcFile(npcFile);
95 | }
96 |
97 | /**
98 | * Parses a raw npc data file into a readable NpcConfig object.
99 | * @param npcFile The raw file-store npc data.
100 | */
101 | public decodeNpcFile(npcFile: FileData): NpcConfig {
102 | const npcConfig = new NpcConfig();
103 |
104 | const buffer = npcFile.content;
105 | npcConfig.gameId = npcFile.fileId;
106 |
107 | let run = true;
108 |
109 | while (run) {
110 | const opcode = buffer.get('BYTE', 'UNSIGNED');
111 | if (opcode === 0) {
112 | run = false;
113 | break;
114 | }
115 |
116 | if (opcode === 1) {
117 | const length = buffer.get('BYTE', 'UNSIGNED');
118 | npcConfig.model.models = new Array(length);
119 | for (let idx = 0; idx < length; ++idx) {
120 | npcConfig.model.models[idx] = buffer.get(
121 | 'SHORT',
122 | 'UNSIGNED',
123 | );
124 | }
125 | } else if (opcode === 2) {
126 | npcConfig.name = buffer.getString();
127 | } else if (opcode === 12) {
128 | npcConfig.rendering.boundary = buffer.get('BYTE', 'UNSIGNED');
129 | } else if (opcode === 13) {
130 | npcConfig.animations.stand = buffer.get('SHORT', 'UNSIGNED');
131 | } else if (opcode === 14) {
132 | npcConfig.animations.walk = buffer.get('SHORT', 'UNSIGNED');
133 | } else if (opcode === 15) {
134 | buffer.get('SHORT', 'UNSIGNED'); // junk
135 | } else if (opcode === 16) {
136 | buffer.get('SHORT', 'UNSIGNED'); // junk
137 | } else if (opcode === 17) {
138 | npcConfig.animations.walk = buffer.get('SHORT', 'UNSIGNED');
139 | npcConfig.animations.turnAround = buffer.get(
140 | 'SHORT',
141 | 'UNSIGNED',
142 | );
143 | npcConfig.animations.turnRight = buffer.get(
144 | 'SHORT',
145 | 'UNSIGNED',
146 | );
147 | npcConfig.animations.turnLeft = buffer.get('SHORT', 'UNSIGNED');
148 | } else if (opcode >= 30 && opcode < 35) {
149 | if (!npcConfig.options) {
150 | npcConfig.options = new Array(5).fill(null);
151 | }
152 |
153 | const option = buffer.getString();
154 | npcConfig.options[opcode - 30] =
155 | option.toLowerCase() === 'hidden' ? null : option;
156 | } else if (opcode === 40) {
157 | // Model color replacement
158 | const length = buffer.get('BYTE', 'UNSIGNED');
159 | for (let i = 0; i < length; i++) {
160 | buffer.get('SHORT', 'UNSIGNED');
161 | buffer.get('SHORT', 'UNSIGNED');
162 | }
163 | } else if (opcode === 60) {
164 | const length = buffer.get('BYTE', 'UNSIGNED');
165 | npcConfig.model.headModels = new Array(length);
166 | for (let i = 0; length > i; i++) {
167 | npcConfig.model.headModels[i] = buffer.get(
168 | 'SHORT',
169 | 'UNSIGNED',
170 | );
171 | }
172 | } else if (opcode === 93) {
173 | npcConfig.minimapVisible = false;
174 | } else if (opcode === 95) {
175 | npcConfig.combatLevel = buffer.get('SHORT', 'UNSIGNED');
176 | } else if (opcode === 97) {
177 | npcConfig.rendering.sizeX = buffer.get('SHORT', 'UNSIGNED');
178 | } else if (opcode === 98) {
179 | npcConfig.rendering.sizeY = buffer.get('SHORT', 'UNSIGNED');
180 | } else if (opcode === 99) {
181 | npcConfig.rendering.renderPriority = true;
182 | } else if (opcode === 100) {
183 | const ambient = buffer.get('BYTE');
184 | } else if (opcode === 101) {
185 | const contrast = buffer.get('BYTE') * 5;
186 | } else if (opcode === 102) {
187 | npcConfig.headIcon = buffer.get('SHORT', 'UNSIGNED');
188 | } else if (opcode === 103) {
189 | npcConfig.turnDegrees = buffer.get('SHORT', 'UNSIGNED');
190 | } else if (opcode === 106) {
191 | npcConfig.varbitId = buffer.get('SHORT', 'UNSIGNED');
192 | npcConfig.settingId = buffer.get('SHORT', 'UNSIGNED');
193 | if (npcConfig.varbitId === 65535) {
194 | npcConfig.varbitId = -1;
195 | }
196 | if (npcConfig.settingId === 65535) {
197 | npcConfig.settingId = -1;
198 | }
199 | npcConfig.childrenIds = [];
200 | const childCount = buffer.get('BYTE', 'UNSIGNED');
201 | for (let i = 0; childCount >= i; i++) {
202 | npcConfig.childrenIds[i] = buffer.get('SHORT', 'UNSIGNED');
203 | if (npcConfig.childrenIds[i] === 0xffff) {
204 | npcConfig.childrenIds[i] = -1;
205 | }
206 | }
207 | } else if (opcode === 107) {
208 | npcConfig.clickable = false;
209 | }
210 | }
211 |
212 | npcFile.content.readerIndex = 0;
213 | return npcConfig;
214 | }
215 |
216 | /**
217 | * Decodes every npc file within the npc archive and returns
218 | * the resulting NpcConfig array.
219 | */
220 | public decodeNpcStore(): NpcConfig[] {
221 | if (!this.npcArchive) {
222 | logger.error('Npc archive not found.');
223 | return null;
224 | }
225 |
226 | const npcCount = this.npcArchive.files.size;
227 | const npcList: NpcConfig[] = new Array(npcCount);
228 |
229 | for (let npcId = 0; npcId < npcCount; npcId++) {
230 | const npcFile = this.npcArchive.getFile(npcId) || null;
231 |
232 | if (!npcFile) {
233 | logger.error('Npc file not found.');
234 | return null;
235 | }
236 |
237 | npcList[npcId] = this.decodeNpcFile(npcFile);
238 |
239 | if (npcList[npcId].childrenIds) {
240 | this.children.set(
241 | npcList[npcId].gameId,
242 | npcList[npcId].childrenIds,
243 | );
244 | }
245 | }
246 |
247 | for (const childrenEntry of this.children.entries()) {
248 | const parentId = childrenEntry[0];
249 | const childrenIds = childrenEntry[1];
250 |
251 | for (const childId of childrenIds) {
252 | if (npcList[childId]) {
253 | npcList[childId].parentId = parentId;
254 | }
255 | }
256 | }
257 |
258 | return npcList;
259 | }
260 | }
261 |
--------------------------------------------------------------------------------
/src/filestore/stores/configs/object-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 | import type { Archive } from '../../archive';
3 | import type { ConfigStore } from '../config-store';
4 | import type { FileData } from '../../file-data';
5 |
6 | /**
7 | * Contains game client need-to-know level information about a single game object.
8 | */
9 | export class ObjectConfig {
10 | gameId: number;
11 | name: string | null = null;
12 |
13 | solid = true;
14 | nonWalkable = true;
15 | hasOptions = false;
16 | options: string[];
17 | walkable: boolean;
18 | configChangeDest?: number[];
19 | configId = -1;
20 | varbitId = -1;
21 | supportsItems = false;
22 |
23 | /**
24 | * 3d modelling information for this object.
25 | */
26 | model: {
27 | models?: number[];
28 | } = {};
29 |
30 | /**
31 | * Additional rendering details.
32 | */
33 | rendering: {
34 | objectModels?: number[];
35 | objectModelTypes?: number[];
36 | ambient: number;
37 | contrast: number;
38 | recolorToReplace?: number[];
39 | recolorToFind?: number[];
40 | rotated: boolean;
41 | castsShadow: boolean;
42 | modelSizeX: number;
43 | modelSizeY: number;
44 | modelSizeHeight: number;
45 | mapSceneID: number;
46 | obstructsGround: boolean;
47 | hollow: boolean;
48 | adjustToTerrain: boolean;
49 | nonFlatShading: boolean;
50 | animationId: number;
51 | face: number;
52 | translateX: number;
53 | translateY: number;
54 | translateLevel: number;
55 | sizeX: number;
56 | sizeY: number;
57 | } = {
58 | face: 0,
59 | translateX: 0,
60 | translateY: 0,
61 | translateLevel: 0,
62 | adjustToTerrain: false,
63 | nonFlatShading: false,
64 | animationId: -1,
65 | sizeX: 1,
66 | sizeY: 1,
67 | hollow: false,
68 | obstructsGround: false,
69 | mapSceneID: -1,
70 | modelSizeY: 128,
71 | modelSizeHeight: 128,
72 | modelSizeX: 128,
73 | castsShadow: true,
74 | rotated: false,
75 | contrast: 0,
76 | ambient: 0,
77 | };
78 | icon?: number;
79 | wall = false;
80 | }
81 |
82 | /**
83 | * Controls files within the Object Archive of the configuration index.
84 | */
85 | export class ObjectStore {
86 | /**
87 | * The Object Archive, containing details about every game object.
88 | */
89 | public readonly objectArchive: Archive;
90 |
91 | public constructor(private configStore: ConfigStore) {
92 | this.objectArchive = this.configStore.getArchive('objects');
93 | }
94 |
95 | /**
96 | * Fetches the ObjectConfig object for the specified object game id.
97 | * @param objectId The game id of the object to find.
98 | */
99 | public getObject(objectId: number): ObjectConfig | null {
100 | const objectArchive = this.objectArchive;
101 |
102 | if (!objectArchive) {
103 | logger.error('Object archive not found.');
104 | return null;
105 | }
106 |
107 | const objectFile = objectArchive.getFile(objectId) || null;
108 |
109 | if (!objectFile) {
110 | logger.error('Object file not found.');
111 | return null;
112 | }
113 |
114 | return this.decodeObjectFile(objectFile);
115 | }
116 |
117 | /**
118 | * Parses a raw game object data file into a readable ObjectConfig object.
119 | * @param objectFile The raw file-store game object data.
120 | */
121 | public decodeObjectFile(objectFile: FileData): ObjectConfig {
122 | const objectConfig = new ObjectConfig();
123 |
124 | const buffer = objectFile.content;
125 | objectConfig.gameId = objectFile.fileId;
126 |
127 | let run = true;
128 |
129 | while (run) {
130 | const opcode = buffer.get('BYTE', 'UNSIGNED');
131 | if (opcode === 0) {
132 | run = false;
133 | break;
134 | }
135 |
136 | if (opcode === 1) {
137 | const length = buffer.get('BYTE', 'UNSIGNED');
138 | if (length > 0) {
139 | if (objectConfig.rendering.objectModels == null) {
140 | objectConfig.rendering.objectModels = [];
141 | objectConfig.rendering.objectModelTypes = [];
142 | for (let index = 0; length > index; index++) {
143 | objectConfig.rendering.objectModels[index] =
144 | buffer.get('SHORT', 'UNSIGNED'); // model id
145 | objectConfig.rendering.objectModelTypes[index] =
146 | buffer.get('BYTE', 'UNSIGNED'); // model type
147 | }
148 | } else {
149 | buffer.readerIndex += length * 3;
150 | }
151 | }
152 | } else if (opcode === 2) {
153 | objectConfig.name = buffer.getString();
154 | } else if (opcode === 5) {
155 | const length = buffer.get('BYTE', 'UNSIGNED');
156 | if (length > 0) {
157 | if (objectConfig.rendering.objectModels == null) {
158 | objectConfig.rendering.objectModels = [];
159 | objectConfig.rendering.objectModelTypes = null;
160 | for (let index = 0; length > index; index++) {
161 | objectConfig.rendering.objectModels[index] =
162 | buffer.get('SHORT', 'UNSIGNED'); // model id
163 | }
164 | } else {
165 | buffer.readerIndex += length * 2;
166 | }
167 | }
168 | } else if (opcode === 14) {
169 | objectConfig.rendering.sizeX = buffer.get('BYTE', 'UNSIGNED');
170 | } else if (opcode === 15) {
171 | objectConfig.rendering.sizeY = buffer.get('BYTE', 'UNSIGNED');
172 | } else if (opcode === 17) {
173 | objectConfig.solid = false;
174 | } else if (opcode === 18) {
175 | objectConfig.walkable = false;
176 | } else if (opcode === 19) {
177 | objectConfig.hasOptions = buffer.get('BYTE', 'UNSIGNED') === 1;
178 | } else if (opcode === 21) {
179 | objectConfig.rendering.adjustToTerrain = true;
180 | } else if (opcode === 22) {
181 | objectConfig.rendering.nonFlatShading = true;
182 | } else if (opcode === 23) {
183 | objectConfig.wall = true;
184 | } else if (opcode === 24) {
185 | objectConfig.rendering.animationId = buffer.get(
186 | 'SHORT',
187 | 'UNSIGNED',
188 | );
189 | if (objectConfig.rendering.animationId === 0xffff) {
190 | objectConfig.rendering.animationId = -1;
191 | }
192 | } else if (opcode === 28) {
193 | buffer.get('BYTE', 'UNSIGNED');
194 | } else if (opcode === 29) {
195 | objectConfig.rendering.ambient = buffer.get('BYTE');
196 | } else if (opcode === 39) {
197 | objectConfig.rendering.contrast = 5 * buffer.get('BYTE');
198 | } else if (opcode >= 30 && opcode < 35) {
199 | if (!objectConfig.options) {
200 | objectConfig.options = new Array(5).fill(null);
201 | }
202 |
203 | const option = buffer.getString();
204 | objectConfig.options[opcode - 30] =
205 | option.toLowerCase() === 'hidden' ? null : option;
206 | } else if (opcode === 40) {
207 | const length = buffer.get('BYTE', 'UNSIGNED');
208 | objectConfig.rendering.recolorToFind = [];
209 | objectConfig.rendering.recolorToReplace = [];
210 | for (let index = 0; index < length; index++) {
211 | objectConfig.rendering.recolorToFind[index] = buffer.get(
212 | 'SHORT',
213 | 'UNSIGNED',
214 | ); // old color
215 | objectConfig.rendering.recolorToReplace[index] = buffer.get(
216 | 'SHORT',
217 | 'UNSIGNED',
218 | ); // new color
219 | }
220 | } else if (opcode === 60) {
221 | objectConfig.icon = buffer.get('SHORT', 'UNSIGNED'); // ??
222 | } else if (opcode === 62) {
223 | objectConfig.rendering.rotated = true;
224 | } else if (opcode === 64) {
225 | objectConfig.rendering.castsShadow = false;
226 | } else if (opcode === 65) {
227 | objectConfig.rendering.modelSizeX = buffer.get(
228 | 'SHORT',
229 | 'UNSIGNED',
230 | ); // modelSizeX
231 | } else if (opcode === 66) {
232 | objectConfig.rendering.modelSizeHeight = buffer.get(
233 | 'SHORT',
234 | 'UNSIGNED',
235 | ); // modelSizeHeight
236 | } else if (opcode === 67) {
237 | objectConfig.rendering.modelSizeY = buffer.get(
238 | 'SHORT',
239 | 'UNSIGNED',
240 | ); // modelSizeY
241 | } else if (opcode === 68) {
242 | objectConfig.rendering.mapSceneID = buffer.get(
243 | 'SHORT',
244 | 'UNSIGNED',
245 | ); // mapSceneID
246 | } else if (opcode === 69) {
247 | objectConfig.rendering.face = buffer.get('BYTE', 'UNSIGNED');
248 | } else if (opcode === 70) {
249 | objectConfig.rendering.translateX = buffer.get('SHORT');
250 | } else if (opcode === 71) {
251 | objectConfig.rendering.translateY = buffer.get('SHORT');
252 | } else if (opcode === 72) {
253 | objectConfig.rendering.translateLevel = buffer.get('SHORT');
254 | } else if (opcode === 73) {
255 | objectConfig.rendering.obstructsGround = true;
256 | } else if (opcode === 74) {
257 | objectConfig.rendering.hollow = true;
258 | } else if (opcode === 75) {
259 | objectConfig.supportsItems =
260 | buffer.get('BYTE', 'UNSIGNED') === 1; // anInt2533
261 | } else if (opcode === 77) {
262 | objectConfig.varbitId = buffer.get('SHORT', 'UNSIGNED'); // varbit id
263 | if (objectConfig.varbitId === 0xffff) {
264 | objectConfig.varbitId = -1;
265 | }
266 | objectConfig.configId = buffer.get('SHORT', 'UNSIGNED'); // settings id
267 | if (objectConfig.configId === 0xffff) {
268 | objectConfig.configId = -1;
269 | }
270 | const length = buffer.get('BYTE', 'UNSIGNED');
271 | objectConfig.configChangeDest = [];
272 | for (let index = 0; index <= length; ++index) {
273 | objectConfig.configChangeDest[index] = buffer.get(
274 | 'SHORT',
275 | 'UNSIGNED',
276 | );
277 | if (0xffff === objectConfig.configChangeDest[index]) {
278 | objectConfig.configChangeDest[index] = -1;
279 | }
280 | }
281 | } else if (opcode === 78) {
282 | buffer.get('SHORT', 'UNSIGNED'); // anInt2513
283 | buffer.get('BYTE', 'UNSIGNED'); // anInt2502
284 | } else if (opcode === 79) {
285 | buffer.get('SHORT', 'UNSIGNED'); // anInt2499
286 | buffer.get('SHORT', 'UNSIGNED'); // anInt2542
287 | buffer.get('BYTE', 'UNSIGNED'); // anInt2502
288 | const length = buffer.get('BYTE', 'UNSIGNED');
289 | for (let index = 0; index < length; ++index) {
290 | buffer.get('SHORT', 'UNSIGNED'); // anIntArray2523[index]
291 | }
292 | }
293 | }
294 |
295 | objectFile.content.readerIndex = 0;
296 | return objectConfig;
297 | }
298 |
299 | /**
300 | * Decodes every object file within the object archive and returns
301 | * the resulting ObjectConfig array.
302 | */
303 | public decodeObjectStore(): ObjectConfig[] {
304 | if (!this.objectArchive) {
305 | logger.error('Object archive not found.');
306 | return null;
307 | }
308 |
309 | const objectCount = this.objectArchive.files.size;
310 | const objectList: ObjectConfig[] = new Array(objectCount);
311 |
312 | for (let objectId = 0; objectId < objectCount; objectId++) {
313 | const objectFile = this.objectArchive.getFile(objectId) || null;
314 |
315 | if (!objectFile) {
316 | logger.error('Object file not found.');
317 | return null;
318 | }
319 |
320 | objectList[objectId] = this.decodeObjectFile(objectFile);
321 | }
322 |
323 | return objectList;
324 | }
325 | }
326 |
--------------------------------------------------------------------------------
/src/filestore/stores/configs/varbit-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 | import type { Archive } from '../../archive';
3 | import type { ConfigStore } from '../config-store';
4 | import type { FileData } from '../../file-data';
5 |
6 | /**
7 | * Contains game client need-to-know level information about a single varbit.
8 | */
9 | export class VarbitConfig {
10 | gameId: number;
11 | index: number;
12 | leastSignificantBit: number;
13 | mostSignificantBit: number;
14 | }
15 |
16 | /**
17 | * Controls files within the Varbit Archive of the configuration index.
18 | */
19 | export class VarbitStore {
20 | /**
21 | * The Varbit Archive, containing details about every game varbit.
22 | */
23 | public readonly varbitArchive: Archive;
24 |
25 | public constructor(private configStore: ConfigStore) {
26 | this.varbitArchive = this.configStore.getArchive('varbits');
27 | }
28 |
29 | /**
30 | * Fetches the VarbitConfig object for the specified varbit game id.
31 | * @param varbitId The game id of the varbit to find.
32 | */
33 | public getVarbit(varbitId: number): VarbitConfig | null {
34 | const varbitArchive = this.varbitArchive;
35 |
36 | if (!varbitArchive) {
37 | logger.error('Varbit archive not found.');
38 | return null;
39 | }
40 |
41 | const varbitFile = varbitArchive.getFile(varbitId) || null;
42 |
43 | if (!varbitFile) {
44 | logger.error('Varbit file not found.');
45 | return null;
46 | }
47 |
48 | return this.decodeVarbitFile(varbitFile);
49 | }
50 |
51 | /**
52 | * Parses a raw varbit data file into a readable VarbitConfig object.
53 | * @param varbitFile The raw file-store varbit data.
54 | */
55 | public decodeVarbitFile(varbitFile: FileData): VarbitConfig {
56 | const varbitConfig = new VarbitConfig();
57 |
58 | const buffer = varbitFile.content;
59 | varbitConfig.gameId = varbitFile.fileId;
60 |
61 | let run = true;
62 |
63 | while (run) {
64 | const opcode = buffer.get('BYTE', 'UNSIGNED');
65 | if (opcode === 0) {
66 | run = false;
67 | break;
68 | }
69 | if (opcode === 1) {
70 | varbitConfig.index = buffer.get('SHORT', 'UNSIGNED');
71 | varbitConfig.leastSignificantBit = buffer.get(
72 | 'BYTE',
73 | 'UNSIGNED',
74 | );
75 | varbitConfig.mostSignificantBit = buffer.get(
76 | 'BYTE',
77 | 'UNSIGNED',
78 | );
79 | }
80 | }
81 |
82 | varbitFile.content.readerIndex = 0;
83 | return varbitConfig;
84 | }
85 |
86 | /**
87 | * Decodes every varbit file within the varbit archive and returns
88 | * the resulting VarbitConfig array.
89 | */
90 | public decodeVarbitStore(): VarbitConfig[] {
91 | if (!this.varbitArchive) {
92 | logger.error('Varbit archive not found.');
93 | return null;
94 | }
95 |
96 | const varbitCount = this.varbitArchive.files.size;
97 | const varbitList: VarbitConfig[] = new Array(varbitCount);
98 |
99 | for (let varbitId = 0; varbitId < varbitCount; varbitId++) {
100 | const varbitFile = this.varbitArchive.getFile(varbitId) || null;
101 |
102 | if (!varbitFile) {
103 | logger.error('Varbit file not found.');
104 | return null;
105 | }
106 |
107 | varbitList[varbitId] = this.decodeVarbitFile(varbitFile);
108 | }
109 |
110 | return varbitList;
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/src/filestore/stores/font-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 | import { createCanvas, createImageData } from 'canvas';
3 |
4 | import type { Filestore } from '../filestore';
5 | import {
6 | type SpritePack,
7 | type SpriteStore,
8 | type Sprite,
9 | toRgb,
10 | } from './sprite-store';
11 |
12 | /**
13 | * A list of game font file names.
14 | */
15 | export enum FontName {
16 | p11_full = 'p11_full',
17 | p12_full = 'p12_full',
18 | b12_full = 'b12_full',
19 | q8_full = 'q8_full',
20 |
21 | // Lunar alphabets only work with capital letters from A-Z
22 | lunar_alphabet = 'lunar_alphabet',
23 | lunar_alphabet_lrg = 'lunar_alphabet_lrg',
24 | }
25 |
26 | export const fontNames: FontName[] = [
27 | FontName.p11_full,
28 | FontName.p12_full,
29 | FontName.b12_full,
30 | FontName.q8_full,
31 | FontName.lunar_alphabet,
32 | FontName.lunar_alphabet_lrg,
33 | ];
34 |
35 | export class Font {
36 | /**
37 | * The `SpritePack` containing this `Font`'s various character glypth.
38 | */
39 | public readonly spritePack: SpritePack;
40 |
41 | public constructor(
42 | public readonly name: string,
43 | private readonly spriteStore: SpriteStore,
44 | ) {
45 | this.spritePack = this.spriteStore.getSpritePack(this.name);
46 | this.spritePack?.decode();
47 | }
48 |
49 | /**
50 | * Draws the given string and returns it as a base64 encoded PNG image string.
51 | * @param string The string to draw.
52 | * @param textColor The color to draw the text in.
53 | * @returns A base64 encoded PNG image.
54 | */
55 | public drawString(string: string, textColor = 0xffffff): string {
56 | const stringWidth = this.getStringWidth(string);
57 | const stringHeight = this.getStringHeight(string);
58 | const characters = string.split('');
59 |
60 | const canvas = createCanvas(stringWidth, stringHeight);
61 | const context = canvas.getContext('2d');
62 |
63 | let x = 0;
64 | for (const char of characters) {
65 | const charPixels = this.getCharPixels(char, textColor);
66 | const charWidth = this.getCharWidth(char);
67 | const charHeight = this.getCharHeight(char);
68 | const charSprite = this.getSprite(char);
69 | const imageData = createImageData(
70 | charPixels,
71 | charWidth,
72 | charHeight,
73 | );
74 |
75 | const y = charSprite.offsetY;
76 | context.putImageData(imageData, x, y);
77 | x += charSprite.width;
78 | }
79 |
80 | return canvas.toDataURL('image/png');
81 | }
82 |
83 | /**
84 | * Fetches all of the pixels of a character glyph in `Uint8ClampedArray` rgba pixel format.
85 | * @param char The character or character code to get the pixels of.
86 | * @param color The color to set the character's pixels to. Defaults to white.
87 | */
88 | public getCharPixels(
89 | char: string | number,
90 | color = 0xffffff,
91 | ): Uint8ClampedArray | null {
92 | const sprite = this.getSprite(char);
93 | if (!sprite) {
94 | return null;
95 | }
96 |
97 | const pixels = sprite.getPixels();
98 |
99 | for (let x = 0; x < sprite.width; x++) {
100 | for (let y = 0; y < sprite.height; y++) {
101 | const i = (sprite.width * y + x) << 2;
102 |
103 | if (pixels[i] !== 0) {
104 | const [r, g, b] = toRgb(color);
105 |
106 | pixels[i] = r;
107 | pixels[i + 1] = g;
108 | pixels[i + 2] = b;
109 | pixels[i + 3] = 255;
110 | } else {
111 | pixels[i] = 0;
112 | pixels[i + 1] = 0;
113 | pixels[i + 2] = 0;
114 | pixels[i + 3] = 0;
115 | }
116 | }
117 | }
118 |
119 | return pixels;
120 | }
121 |
122 | /**
123 | * Finds and returns the height of the the specified string.
124 | * @param string The string to find the height of.
125 | */
126 | public getStringHeight(string: string): number {
127 | // We set the default font height to uppercase A for reference
128 | let height = this.getCharHeight('A');
129 |
130 | if (height === 0) {
131 | throw new Error("Default height couldn't be defined!");
132 | }
133 |
134 | for (const char of string.split('')) {
135 | const sprite = this.getSprite(char);
136 | if (!sprite) {
137 | continue;
138 | }
139 |
140 | // Character is above the standard line of text, for example ' characters
141 | if (sprite.offsetY < 0) {
142 | height = height + Math.abs(sprite.offsetY);
143 | continue;
144 | }
145 |
146 | // Add the offset to the char height to check for overflowing characters like g, y, j, etc
147 | const charHeight = sprite.height + sprite.offsetY;
148 | height = Math.max(height, charHeight);
149 | }
150 |
151 | return height;
152 | }
153 |
154 | /**
155 | * Calculates the total width of all character glyphs within the specified string.
156 | * @param string The string to find the width of.
157 | */
158 | public getStringWidth(string: string): number {
159 | const widths = string
160 | .split('')
161 | .map((stringChar) => this.getCharWidth(stringChar));
162 | return widths.reduce((a, b) => a + b, 0);
163 | }
164 |
165 | /**
166 | * Gets the glyph height for the specified character or character code.
167 | * @param char The character or character code to get the height of.
168 | */
169 | public getCharHeight(char: string | number): number {
170 | return this.getSprite(char)?.height || 0;
171 | }
172 |
173 | /**
174 | * Gets the glyph width for the specified character or character code.
175 | * @param char The character or character code to get the width of.
176 | */
177 | public getCharWidth(char: string | number): number {
178 | return this.getSprite(char)?.width || 0;
179 | }
180 |
181 | /**
182 | * Gets the `Sprite` for the specified character or character code.
183 | * @param char The character or character code to get the sprite glyph for.
184 | */
185 | public getSprite(inputChar: string | number): Sprite | null {
186 | let char = inputChar;
187 | if (typeof char === 'string') {
188 | char = char.charCodeAt(0);
189 | }
190 |
191 | try {
192 | return this.spritePack.sprites[char] || null;
193 | } catch (error) {
194 | logger.error(`Error loading glyph ${char}`, error);
195 | return null;
196 | }
197 | }
198 | }
199 |
200 | /**
201 | * Contains information and tools for the game's fonts.
202 | */
203 | export class FontStore {
204 | /**
205 | * A map of loaded game fonts by name.
206 | */
207 | public readonly fonts: Map;
208 |
209 | public constructor(private readonly filestore: Filestore) {
210 | this.fonts = new Map();
211 | }
212 |
213 | /**
214 | * Load the list of registered game fonts and their associated Sprite Packs.
215 | */
216 | public loadFonts(): FontStore {
217 | for (const fontName of fontNames) {
218 | this.fonts.set(
219 | fontName,
220 | new Font(fontName, this.filestore.spriteStore),
221 | );
222 | }
223 |
224 | return this;
225 | }
226 |
227 | /**
228 | * Fetches a font by its file name
229 | */
230 | public getFontByName(fontName: FontName): Font {
231 | return this.fonts.get(fontName);
232 | }
233 |
234 | /**
235 | * Fetches a font by its ID
236 | */
237 | public getFontById(spriteId: number): Font {
238 | return Array.from(this.fonts.values()).find(
239 | (e) => e.spritePack.packId === spriteId,
240 | );
241 | }
242 | }
243 |
--------------------------------------------------------------------------------
/src/filestore/stores/index.ts:
--------------------------------------------------------------------------------
1 | export * from './binary-store';
2 | export * from './config-store';
3 | export * from './font-store';
4 | export * from './jingle-store';
5 | export * from './model-store';
6 | export * from './music-store';
7 | export * from './region-store';
8 | export * from './sound-store';
9 | export * from './sprite-store';
10 | export * from './texture-store';
11 | export * from './widget-store';
12 |
13 | export * from './configs';
14 |
--------------------------------------------------------------------------------
/src/filestore/stores/jingle-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 | import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3 |
4 | import type { Filestore } from '../filestore';
5 | import type { FileData } from '../file-data';
6 |
7 | /**
8 | * A single OGG file object.
9 | */
10 | export class OggFile {
11 | public constructor(public readonly fileData: FileData) {}
12 |
13 | /**
14 | * Writes this unpacked OGG file to the disk under `./unpacked/ogg/{oggId}.ogg`
15 | */
16 | public async writeToDisk(): Promise {
17 | return new Promise((resolve, reject) => {
18 | try {
19 | if (!existsSync('./unpacked/ogg')) {
20 | mkdirSync('./unpacked/ogg');
21 | }
22 | const data = this.fileData.decompress();
23 | writeFileSync(
24 | `./unpacked/ogg/${this.fileId}.ogg`,
25 | Buffer.from(data),
26 | );
27 | resolve();
28 | } catch (error) {
29 | reject(error);
30 | }
31 | });
32 | }
33 |
34 | public get fileId(): number {
35 | return this.fileData?.fileId || -1;
36 | }
37 | }
38 |
39 | /**
40 | * Controls short jingle (.ogg) file storage.
41 | */
42 | export class JingleStore {
43 | public constructor(private fileStore: Filestore) {}
44 |
45 | /**
46 | * Writes all unpacked OGG files to the disk under `./unpacked/ogg/`
47 | */
48 | public async writeToDisk(): Promise {
49 | const files = this.decodeJingleStore();
50 | for (const ogg of files) {
51 | try {
52 | await ogg.writeToDisk();
53 | } catch (e) {
54 | logger.error(e);
55 | }
56 | }
57 | }
58 |
59 | /**
60 | * Decodes the specified OGG file.
61 | * @param id The ID of the OGG file.
62 | * @returns The decoded OggFile object, or null if the file is not found.
63 | */
64 | public getOgg(id: number): OggFile | null {
65 | if (id === undefined || id === null) {
66 | return null;
67 | }
68 |
69 | const oggArchiveIndex = this.fileStore.getIndex('jingles');
70 | const fileData = oggArchiveIndex.getFile(id);
71 | return fileData ? new OggFile(fileData) : null;
72 | }
73 |
74 | /**
75 | * Decodes all OGG files within the filestore.
76 | * @returns The list of decoded OggFile objects from the OGG store.
77 | */
78 | public decodeJingleStore(): OggFile[] {
79 | const oggArchiveIndex = this.fileStore.getIndex('jingles');
80 | const fileCount = oggArchiveIndex.files.size;
81 | const oggFiles: OggFile[] = new Array(fileCount);
82 |
83 | for (let oggId = 0; oggId < fileCount; oggId++) {
84 | try {
85 | const fileData = oggArchiveIndex.getFile(oggId);
86 | if (!fileData) {
87 | oggFiles[oggId] = null;
88 | logger.warn(`No file found for OGG ID ${oggId}.`);
89 | continue;
90 | }
91 |
92 | oggFiles[oggId] = new OggFile(fileData);
93 | } catch (e) {
94 | oggFiles[oggId] = null;
95 | logger.error(`Error parsing OGG ID ${oggId}.`);
96 | logger.error(e);
97 | }
98 | }
99 |
100 | return oggFiles;
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/src/filestore/stores/music-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 | import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3 |
4 | import { type Filestore, getFileName } from '../filestore';
5 | import type { FileData } from '../file-data';
6 |
7 | /**
8 | * A single MIDI file object.
9 | */
10 | export class MidiFile {
11 | public constructor(public readonly fileData: FileData) {}
12 |
13 | /**
14 | * Writes this unpacked MIDI file to the disk under `./unpacked/midi/{midiFileName}.mid`
15 | */
16 | public async writeToDisk(): Promise {
17 | return new Promise((resolve, reject) => {
18 | try {
19 | const fileName = getFileName(this.fileData.nameHash).replace(
20 | / /g,
21 | '_',
22 | );
23 | if (!existsSync('./unpacked/midi')) {
24 | mkdirSync('./unpacked/midi');
25 | }
26 | const data = this.fileData.decompress();
27 | writeFileSync(
28 | `./unpacked/midi/${this.fileId}_${fileName}.mid`,
29 | Buffer.from(data),
30 | );
31 | resolve();
32 | } catch (error) {
33 | reject(error);
34 | }
35 | });
36 | }
37 |
38 | public get fileId(): number {
39 | return this.fileData?.fileId || -1;
40 | }
41 | }
42 |
43 | /**
44 | * Controls MIDI file storage.
45 | */
46 | export class MusicStore {
47 | public constructor(private fileStore: Filestore) {}
48 |
49 | /**
50 | * Writes all unpacked MIDI files to the disk under `./unpacked/midi/`
51 | */
52 | public async writeToDisk(): Promise {
53 | const files = this.decodeMusicStore();
54 | for (const midi of files) {
55 | try {
56 | await midi.writeToDisk();
57 | } catch (e) {
58 | logger.error(e);
59 | }
60 | }
61 | }
62 |
63 | /**
64 | * Decodes the specified midi file.
65 | * @param nameOrId The name or ID of the midi file.
66 | * @returns The decoded MidiFile object, or null if the file is not found.
67 | */
68 | public getMidi(nameOrId: string | number): MidiFile | null {
69 | if (!nameOrId) {
70 | return null;
71 | }
72 |
73 | const midiArchiveIndex = this.fileStore.getIndex('music');
74 | const fileData = midiArchiveIndex.getFile(nameOrId);
75 |
76 | return fileData ? new MidiFile(fileData) : null;
77 | }
78 |
79 | /**
80 | * Decodes all midi files within the filestore.
81 | * @returns The list of decoded MidiFile objects from the midi store.
82 | */
83 | public decodeMusicStore(): MidiFile[] {
84 | const midiArchiveIndex = this.fileStore.getIndex('music');
85 | const fileCount = midiArchiveIndex.files.size;
86 | const midiFiles: MidiFile[] = new Array(fileCount);
87 |
88 | for (let midiId = 0; midiId < fileCount; midiId++) {
89 | try {
90 | const fileData = midiArchiveIndex.getFile(midiId);
91 | if (!fileData) {
92 | midiFiles[midiId] = null;
93 | logger.warn(`No file found for midi ID ${midiId}.`);
94 | continue;
95 | }
96 |
97 | midiFiles[midiId] = new MidiFile(fileData);
98 | } catch (e) {
99 | midiFiles[midiId] = null;
100 | logger.error(`Error parsing midi ID ${midiId}.`);
101 | logger.error(e);
102 | }
103 | }
104 |
105 | return midiFiles;
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/src/filestore/stores/region-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 | import { readFileSync } from 'node:fs';
3 | import path from 'node:path';
4 |
5 | import type { Filestore } from '../filestore';
6 | import type { FileIndex } from '../file-index';
7 |
8 | export const maxRegions = 32768;
9 |
10 | export interface MapFile {
11 | fileId: number;
12 | regionX: number;
13 | regionY: number;
14 | tileHeights: number[][][];
15 | tileSettings: Uint8Array[][];
16 | tileOverlayIds: Uint8Array[][];
17 | tileOverlayPaths: Uint8Array[][];
18 | tileOverlayOrientations: Uint8Array[][];
19 | tileUnderlayIds: Uint8Array[][];
20 | }
21 |
22 | export interface LandscapeObject {
23 | objectId: number;
24 | x: number;
25 | y: number;
26 | level: number;
27 | type: number;
28 | orientation: number;
29 | }
30 |
31 | export interface LandscapeFile {
32 | fileId: number;
33 | regionX: number;
34 | regionY: number;
35 | landscapeObjects: LandscapeObject[];
36 | }
37 |
38 | export interface Region {
39 | regionX: number;
40 | regionY: number;
41 | mapFile: MapFile;
42 | landscapeFile: LandscapeFile | null;
43 | }
44 |
45 | export interface XteaDefinition {
46 | archive: number;
47 | group: number;
48 | name_hash: number;
49 | name: string;
50 | mapsquare: number;
51 | key: [number, number, number, number];
52 | }
53 |
54 | export type TileArray = Uint8Array[][];
55 |
56 | export class RegionStore {
57 | public readonly xteas: { [key: number]: XteaDefinition } = {};
58 |
59 | private readonly regionIndex: FileIndex;
60 |
61 | public constructor(
62 | private fileStore: Filestore,
63 | xteas?: { [p: number]: XteaDefinition },
64 | ) {
65 | this.regionIndex = this.fileStore.getIndex('regions');
66 | if (xteas) {
67 | this.xteas = xteas;
68 | } else {
69 | const array = JSON.parse(
70 | readFileSync(
71 | path.join(this.fileStore.configDir, 'map-keys.json'),
72 | 'utf8',
73 | ),
74 | );
75 | for (let i = 0; i < array.length; i++) {
76 | const object: XteaDefinition = array[i];
77 | this.xteas[object.name] = object;
78 | }
79 | }
80 | }
81 |
82 | public getMapKeys(regionX: number, regionY: number): number[] {
83 | return this.xteas[`l${regionX}_${regionY}`]?.key || [0, 0, 0, 0];
84 | }
85 |
86 | public getRegion(regionX: number, regionY: number): Region | null {
87 | const mapFile = this.getMapFile(regionX, regionY);
88 | if (!mapFile) {
89 | return null;
90 | }
91 |
92 | const landscapeFile = this.getLandscapeFile(regionX, regionY) || null;
93 |
94 | return { regionX, regionY, mapFile, landscapeFile };
95 | }
96 |
97 | public getLandscapeFile(
98 | regionX: number,
99 | regionY: number,
100 | ): LandscapeFile | null {
101 | const keys = this.getMapKeys(regionX, regionY);
102 |
103 | const landscapeFile = this.regionIndex.getFile(
104 | `l${regionX}_${regionY}`,
105 | keys,
106 | );
107 | if (!landscapeFile) {
108 | logger.warn(
109 | `Landscape file not found for region ${regionX},${regionY}`,
110 | );
111 | return null;
112 | }
113 |
114 | const landscapeObjects = [];
115 |
116 | let objectId = -1;
117 | landscapeFile.content.readerIndex = 0;
118 |
119 | let objectLoop = true;
120 |
121 | while (objectLoop) {
122 | const objectIdOffset = landscapeFile.content.get('SMART_SHORT');
123 |
124 | if (objectIdOffset === 0) {
125 | objectLoop = false;
126 | break;
127 | }
128 |
129 | objectId += objectIdOffset;
130 | let objectPositionInfo = 0;
131 |
132 | let positionLoop = true;
133 |
134 | while (positionLoop) {
135 | const objectPositionInfoOffset =
136 | landscapeFile.content.get('SMART_SHORT');
137 |
138 | if (objectPositionInfoOffset === 0) {
139 | positionLoop = false;
140 | break;
141 | }
142 |
143 | objectPositionInfo += objectPositionInfoOffset - 1;
144 |
145 | const worldX = (regionX & 0xff) * 64;
146 | const worldY = regionY * 64;
147 | const x = ((objectPositionInfo >> 6) & 0x3f) + worldX;
148 | const y = (objectPositionInfo & 0x3f) + worldY;
149 | const level = (objectPositionInfo >> 12) & 0x3;
150 | const objectMetadata = landscapeFile.content.get(
151 | 'BYTE',
152 | 'UNSIGNED',
153 | );
154 | const type = objectMetadata >> 2;
155 | const orientation = objectMetadata & 0x3;
156 |
157 | landscapeObjects.push({
158 | objectId,
159 | x,
160 | y,
161 | level,
162 | type,
163 | orientation,
164 | });
165 | }
166 | }
167 |
168 | return {
169 | fileId: landscapeFile.fileId,
170 | regionX,
171 | regionY,
172 | landscapeObjects,
173 | };
174 | }
175 |
176 | public getMapFile(regionX: number, regionY: number): MapFile | null {
177 | const mapFile = this.regionIndex.getFile(`m${regionX}_${regionY}`);
178 | if (!mapFile) {
179 | logger.warn(`Map file not found for region ${regionX},${regionY}`);
180 | return null;
181 | }
182 |
183 | const tileHeights: number[][][] = new Array(4);
184 | const tileSettings: TileArray = new Array(4);
185 | const tileOverlayIds: TileArray = new Array(4);
186 | const tileOverlayPaths: TileArray = new Array(4);
187 | const tileOverlayOrientations: TileArray = new Array(4);
188 | const tileUnderlayIds: TileArray = new Array(4);
189 |
190 | const buffer = mapFile.content;
191 | buffer.readerIndex = 0;
192 |
193 | for (let level = 0; level < 4; level++) {
194 | tileHeights[level] = new Array(64);
195 | tileSettings[level] = new Array(64);
196 | tileOverlayIds[level] = new Array(64);
197 | tileOverlayPaths[level] = new Array(64);
198 | tileOverlayOrientations[level] = new Array(64);
199 | tileUnderlayIds[level] = new Array(64);
200 |
201 | for (let x = 0; x < 64; x++) {
202 | tileHeights[level][x] = new Array(64);
203 | tileSettings[level][x] = new Uint8Array(64);
204 | tileOverlayIds[level][x] = new Uint8Array(64);
205 | tileOverlayPaths[level][x] = new Uint8Array(64);
206 | tileOverlayOrientations[level][x] = new Uint8Array(64);
207 | tileUnderlayIds[level][x] = new Uint8Array(64);
208 |
209 | for (let y = 0; y < 64; y++) {
210 | tileSettings[level][x][y] = 0;
211 |
212 | let run = true;
213 |
214 | while (run) {
215 | const opcode = buffer.get('BYTE', 'UNSIGNED');
216 |
217 | if (opcode === 0) {
218 | run = false;
219 | break;
220 | }
221 | if (opcode === 1) {
222 | tileHeights[level][x][y] = buffer.get(
223 | 'BYTE',
224 | 'UNSIGNED',
225 | );
226 | run = false;
227 | break;
228 | }
229 | if (opcode <= 49) {
230 | tileOverlayIds[level][x][y] = buffer.get('BYTE');
231 | tileOverlayPaths[level][x][y] = (opcode - 2) / 4;
232 | tileOverlayOrientations[level][x][y] =
233 | (opcode - 2) & 3;
234 | } else if (opcode <= 81) {
235 | tileSettings[level][x][y] = opcode - 49;
236 | } else {
237 | tileUnderlayIds[level][x][y] = opcode - 81;
238 | }
239 | }
240 | }
241 | }
242 | }
243 |
244 | return {
245 | fileId: mapFile.fileId,
246 | regionX,
247 | regionY,
248 | tileHeights,
249 | tileOverlayIds,
250 | tileOverlayOrientations,
251 | tileOverlayPaths,
252 | tileSettings,
253 | tileUnderlayIds,
254 | };
255 | }
256 | }
257 |
--------------------------------------------------------------------------------
/src/filestore/stores/sound-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 | import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3 |
4 | import type { Filestore } from '../filestore';
5 | import type { FileData } from '../file-data';
6 |
7 | /**
8 | * A single sound file object.
9 | */
10 | export class SoundFile {
11 | public constructor(public readonly fileData: FileData) {}
12 |
13 | /**
14 | * Writes this unpacked sound file to the disk under `./unpacked/sounds/{soundId}.wav`
15 | */
16 | public async writeToDisk(): Promise {
17 | return new Promise((resolve, reject) => {
18 | try {
19 | if (!existsSync('./unpacked/sounds')) {
20 | mkdirSync('./unpacked/sounds');
21 | }
22 | const data = this.fileData.decompress();
23 | writeFileSync(
24 | `./unpacked/sounds/${this.fileId}.wav`,
25 | Buffer.from(data),
26 | );
27 | resolve();
28 | } catch (error) {
29 | reject(error);
30 | }
31 | });
32 | }
33 |
34 | public get fileId(): number {
35 | return this.fileData?.fileId || -1;
36 | }
37 | }
38 |
39 | /**
40 | * Controls sound file storage.
41 | */
42 | export class SoundStore {
43 | public constructor(private fileStore: Filestore) {}
44 |
45 | /**
46 | * Writes all unpacked WAV files to the disk under `./unpacked/sounds/`
47 | */
48 | public async writeToDisk(): Promise {
49 | const files = this.decodeSoundStore();
50 | for (const wav of files) {
51 | try {
52 | await wav.writeToDisk();
53 | } catch (e) {
54 | logger.error(e);
55 | }
56 | }
57 | }
58 |
59 | /**
60 | * Decodes the specified sound file.
61 | * @param id The ID of the sound file.
62 | * @returns The decoded SoundFile object, or null if the file is not found.
63 | */
64 | public getSound(id: number): SoundFile | null {
65 | if (id === undefined || id === null) {
66 | return null;
67 | }
68 |
69 | const soundArchiveIndex = this.fileStore.getIndex('sounds');
70 | const fileData = soundArchiveIndex.getFile(id);
71 | return fileData ? new SoundFile(fileData) : null;
72 | }
73 |
74 | /**
75 | * Decodes all WAV files within the filestore.
76 | * @returns The list of decoded SoundFile objects from the sound store.
77 | */
78 | public decodeSoundStore(): SoundFile[] {
79 | const soundArchiveIndex = this.fileStore.getIndex('sounds');
80 | const fileCount = soundArchiveIndex.files.size;
81 | const soundFiles: SoundFile[] = new Array(fileCount);
82 |
83 | for (let soundId = 0; soundId < fileCount; soundId++) {
84 | try {
85 | const fileData = soundArchiveIndex.getFile(soundId);
86 | if (!fileData) {
87 | soundFiles[soundId] = null;
88 | logger.warn(`No file found for sound ID ${soundId}.`);
89 | continue;
90 | }
91 |
92 | soundFiles[soundId] = new SoundFile(fileData);
93 | } catch (e) {
94 | soundFiles[soundId] = null;
95 | logger.error(`Error parsing sound ID ${soundId}.`);
96 | logger.error(e);
97 | }
98 | }
99 |
100 | return soundFiles;
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/src/filestore/stores/sprite-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 | import { existsSync, mkdirSync, rmdirSync, writeFileSync } from 'node:fs';
3 | import { PNG } from 'pngjs';
4 |
5 | import { type Filestore, getFileName } from '../filestore';
6 | import type { FileData } from '../file-data';
7 | import { pngToBase64 } from '../util';
8 |
9 | export function toRgb(inputNum: number): number[] {
10 | let num = inputNum;
11 | num >>>= 0;
12 | const b = num & 0xff;
13 | const g = (num & 0xff00) >>> 8;
14 | const r = (num & 0xff0000) >>> 16;
15 | return [r, g, b];
16 | }
17 |
18 | /**
19 | * A single Sprite within a SpritePack.
20 | */
21 | export class Sprite {
22 | spriteId: number;
23 | maxWidth: number;
24 | maxHeight: number;
25 | offsetX: number;
26 | offsetY: number;
27 | width: number;
28 | height: number;
29 | pixelIdx: number[];
30 | palette: number[];
31 | pixels: number[];
32 |
33 | public constructor(spriteId: number, width: number, height: number) {
34 | this.spriteId = spriteId;
35 | this.maxWidth = this.width = width;
36 | this.maxHeight = this.height = height;
37 | }
38 |
39 | public resizeToLibSize() {
40 | if (this.width !== this.maxWidth || this.height !== this.maxHeight) {
41 | const resizedPixels = new Array(this.maxWidth * this.maxHeight);
42 | let pixelCount = 0;
43 | for (let y = 0; y < this.height; y++) {
44 | for (let x = 0; x < this.width; x++) {
45 | resizedPixels[
46 | x + this.offsetX + (y + this.offsetY) * this.maxWidth
47 | ] = this.pixelIdx[pixelCount++];
48 | }
49 | }
50 | this.pixelIdx = resizedPixels;
51 | this.width = this.maxWidth;
52 | this.height = this.maxHeight;
53 | this.offsetX = 0;
54 | this.offsetY = 0;
55 | }
56 | }
57 |
58 | /**
59 | * First converts the Sprite into a base64 PNG image.
60 | */
61 | public async toBase64(): Promise {
62 | return await pngToBase64(this.toPng());
63 | }
64 |
65 | /**
66 | * Converts the Sprite into a PNG image and returns the resulting PNG object.
67 | */
68 | public toPng(): PNG {
69 | const png = new PNG({
70 | width: this.width,
71 | height: this.height,
72 | filterType: -1,
73 | });
74 |
75 | for (let x = 0; x < this.width; x++) {
76 | for (let y = 0; y < this.height; y++) {
77 | const pixel = this.pixels[this.width * y + x];
78 | const [r, g, b] = toRgb(pixel);
79 | const pngIndex = (this.width * y + x) << 2;
80 |
81 | png.data[pngIndex] = r;
82 | png.data[pngIndex + 1] = g;
83 | png.data[pngIndex + 2] = b;
84 | png.data[pngIndex + 3] = pixel >> 24;
85 | }
86 | }
87 |
88 | return png;
89 | }
90 |
91 | /**
92 | * Converts the Sprite's pixels into a Uint8ClampedArray.
93 | */
94 | public getPixels(): Uint8ClampedArray {
95 | return new Uint8ClampedArray(this.toPng().data);
96 | }
97 | }
98 |
99 | /**
100 | * A package of one or many Sprite objects.
101 | */
102 | export class SpritePack {
103 | private _sprites: Sprite[];
104 |
105 | public constructor(public readonly fileData: FileData) {}
106 |
107 | public async writeToDisk(): Promise {
108 | return new Promise((resolve, reject) => {
109 | try {
110 | const fileName = getFileName(this.fileData.nameHash).replace(
111 | / /g,
112 | '_',
113 | );
114 |
115 | if (!existsSync('./unpacked/sprite-packs')) {
116 | mkdirSync('./unpacked/sprite-packs');
117 | }
118 |
119 | if (this._sprites.length > 1) {
120 | if (
121 | !existsSync(
122 | `./unpacked/sprite-packs/${this.fileData.fileId}_${fileName}`,
123 | )
124 | ) {
125 | mkdirSync(
126 | `./unpacked/sprite-packs/${this.fileData.fileId}_${fileName}`,
127 | );
128 | }
129 |
130 | for (let i = 0; i < this._sprites.length; i++) {
131 | try {
132 | const sprite = this._sprites[i];
133 |
134 | let png: PNG;
135 | if (!sprite) {
136 | png = new PNG({
137 | width: 1,
138 | height: 1,
139 | fill: false,
140 | bgColor: {
141 | red: 0,
142 | green: 0,
143 | blue: 0,
144 | },
145 | });
146 | } else {
147 | png = sprite.toPng();
148 | }
149 |
150 | png.pack();
151 |
152 | const pngBuffer = PNG.sync.write(png);
153 | writeFileSync(
154 | `./unpacked/sprite-packs/${this.fileData.fileId}_${fileName}/${i}.png`,
155 | pngBuffer,
156 | );
157 | } catch (e) {
158 | logger.error('Error writing sprite to disk', e);
159 | }
160 | }
161 | } else if (this._sprites.length === 1) {
162 | const sprite = this._sprites[0];
163 | if (!sprite) {
164 | reject('No sprite data found.');
165 | } else {
166 | const png = sprite.toPng();
167 | png.pack();
168 |
169 | const pngBuffer = PNG.sync.write(png);
170 |
171 | writeFileSync(
172 | `./unpacked/sprite-packs/${this.fileData.fileId}_${fileName}.png`,
173 | pngBuffer,
174 | );
175 | }
176 | }
177 | resolve();
178 | } catch (error) {
179 | reject(error);
180 | }
181 | });
182 | }
183 |
184 | /**
185 | * Decodes the sprite pack file.
186 | */
187 | public decode(): SpritePack {
188 | const buffer = this.fileData.decompress();
189 |
190 | if (buffer.length === 0) {
191 | throw new Error(
192 | `Empty file content for Sprite Pack ${this.fileData.fileId}.`,
193 | );
194 | }
195 | buffer.readerIndex = buffer.length - 2;
196 | const spriteCount = buffer.get('SHORT', 'UNSIGNED');
197 | const sprites: Sprite[] = new Array(spriteCount);
198 |
199 | buffer.readerIndex = buffer.length - 7 - spriteCount * 8;
200 | const width = buffer.get('SHORT', 'UNSIGNED');
201 | const height = buffer.get('SHORT', 'UNSIGNED');
202 | const paletteLength = buffer.get('BYTE', 'UNSIGNED') + 1;
203 |
204 | for (let i = 0; i < spriteCount; i++) {
205 | sprites[i] = new Sprite(i, width, height);
206 | }
207 |
208 | for (let i = 0; i < spriteCount; i++) {
209 | sprites[i].offsetX = buffer.get('SHORT', 'UNSIGNED');
210 | }
211 | for (let i = 0; i < spriteCount; i++) {
212 | sprites[i].offsetY = buffer.get('SHORT', 'UNSIGNED');
213 | }
214 | for (let i = 0; i < spriteCount; i++) {
215 | sprites[i].width = buffer.get('SHORT', 'UNSIGNED');
216 | }
217 | for (let i = 0; i < spriteCount; i++) {
218 | sprites[i].height = buffer.get('SHORT', 'UNSIGNED');
219 | }
220 |
221 | buffer.readerIndex =
222 | buffer.length - 7 - spriteCount * 8 - (paletteLength - 1) * 3;
223 | const palette: number[] = new Array(paletteLength);
224 |
225 | for (let i = 1; i < paletteLength; i++) {
226 | palette[i] = buffer.get('INT24');
227 |
228 | if (palette[i] === 0) {
229 | palette[i] = 1;
230 | }
231 | }
232 |
233 | buffer.readerIndex = 0;
234 |
235 | for (let i = 0; i < spriteCount; i++) {
236 | const sprite = sprites[i];
237 | const spriteWidth = sprite.width;
238 | const spriteHeight = sprite.height;
239 | const dimension = spriteWidth * spriteHeight;
240 | const pixelPaletteIndicies: number[] = new Array(dimension);
241 | const pixelAlphas: number[] = new Array(dimension);
242 | sprite.palette = palette;
243 |
244 | const flags = buffer.get('BYTE', 'UNSIGNED');
245 |
246 | if ((flags & 0b01) === 0) {
247 | for (let j = 0; j < dimension; j++) {
248 | pixelPaletteIndicies[j] = buffer.get('BYTE');
249 | }
250 | } else {
251 | for (let x = 0; x < spriteWidth; x++) {
252 | for (let y = 0; y < spriteHeight; y++) {
253 | pixelPaletteIndicies[spriteWidth * y + x] =
254 | buffer.get('BYTE');
255 | }
256 | }
257 | }
258 |
259 | if ((flags & 0b10) === 0) {
260 | for (let j = 0; j < dimension; j++) {
261 | const index = pixelPaletteIndicies[j];
262 | if (index !== 0) {
263 | pixelAlphas[j] = 0xff;
264 | }
265 | }
266 | } else {
267 | if ((flags & 0b01) === 0) {
268 | for (let j = 0; j < dimension; j++) {
269 | pixelAlphas[j] = buffer.get('BYTE');
270 | }
271 | } else {
272 | for (let x = 0; x < spriteWidth; x++) {
273 | for (let y = 0; y < spriteHeight; y++) {
274 | pixelAlphas[spriteWidth * y + x] =
275 | buffer.get('BYTE');
276 | }
277 | }
278 | }
279 | }
280 |
281 | sprite.pixelIdx = pixelPaletteIndicies;
282 | sprite.pixels = new Array(dimension);
283 |
284 | for (let j = 0; j < dimension; j++) {
285 | const index = pixelPaletteIndicies[j] & 0xff;
286 | sprite.pixels[j] = palette[index] | (pixelAlphas[j] << 24);
287 | }
288 | }
289 |
290 | this._sprites = sprites;
291 |
292 | return this;
293 | }
294 |
295 | public get sprites(): Sprite[] {
296 | return this._sprites;
297 | }
298 |
299 | public get packId(): number {
300 | return this.fileData?.fileId || -1;
301 | }
302 | }
303 |
304 | /**
305 | * Controls SpritePack file storage.
306 | */
307 | export class SpriteStore {
308 | public constructor(private fileStore: Filestore) {}
309 |
310 | public async writeToDisk(): Promise {
311 | rmdirSync('./unpacked/sprite-packs', { recursive: true });
312 | const spritePacks = this.decodeSpriteStore();
313 | for (const spritePack of spritePacks) {
314 | try {
315 | await spritePack.writeToDisk();
316 | } catch (e) {
317 | logger.error(
318 | `Error writing spritepack ${spritePack.packId} to disk.`,
319 | );
320 | logger.error(e);
321 | }
322 | }
323 | }
324 |
325 | /**
326 | * Decodes the specified sprite pack.
327 | * @param fileName The name of the sprite pack file.
328 | * @returns The decoded SpritePack object, or null if the file is not found.
329 | */
330 | public getSpritePack(fileName: string): SpritePack | null;
331 |
332 | /**
333 | * Decodes the specified sprite pack.
334 | * @param id The ID of the sprite pack file.
335 | * @returns The decoded SpritePack object, or null if the file is not found.
336 | */
337 | public getSpritePack(id: number): SpritePack | null;
338 |
339 | /**
340 | * Decodes the specified sprite pack.
341 | * @param nameOrId The name or ID of the sprite pack file.
342 | * @returns The decoded SpritePack object, or null if the file is not found.
343 | */
344 | public getSpritePack(nameOrId: string | number): SpritePack | null {
345 | if (!nameOrId) {
346 | return null;
347 | }
348 |
349 | const spritePackIndex = this.fileStore.getIndex('sprites');
350 | const fileData = spritePackIndex.getFile(nameOrId) || null;
351 | return fileData ? new SpritePack(fileData) : null;
352 | }
353 |
354 | /**
355 | * Decodes all sprite packs within the filestore.
356 | * @returns The list of decoded SpritePack objects from the sprite store.
357 | */
358 | public decodeSpriteStore(): SpritePack[] {
359 | const spritePackIndex = this.fileStore.getIndex('sprites');
360 | const packCount = spritePackIndex.files.size;
361 | const spritePacks: SpritePack[] = new Array(packCount);
362 |
363 | for (let spritePackId = 0; spritePackId < packCount; spritePackId++) {
364 | const fileData = spritePackIndex.getFile(spritePackId);
365 | if (!fileData) {
366 | spritePacks[spritePackId] = null;
367 | logger.warn(
368 | `No file found for sprite pack ID ${spritePackId}.`,
369 | );
370 | continue;
371 | }
372 |
373 | const spritePack = new SpritePack(fileData);
374 | spritePack.decode();
375 | spritePacks[spritePackId] = spritePack;
376 | }
377 |
378 | return spritePacks;
379 | }
380 | }
381 |
--------------------------------------------------------------------------------
/src/filestore/stores/texture-store.ts:
--------------------------------------------------------------------------------
1 | import { logger } from '@runejs/common';
2 | import { PNG } from 'pngjs';
3 | import { existsSync, mkdirSync, rmdirSync, writeFileSync } from 'node:fs';
4 |
5 | import type { Filestore } from '../filestore';
6 | import { type SpriteStore, toRgb } from './sprite-store';
7 | import { ColorUtils } from './model-store';
8 | import { pngToBase64 } from '../util';
9 |
10 | export class Texture {
11 | public static readonly LOW_MEMORY_TEXTURE_SIZE = 64;
12 | public static readonly HIGH_MEMORY_TEXTURE_SIZE = 128;
13 | private static TEXTURE_SIZE = Texture.HIGH_MEMORY_TEXTURE_SIZE;
14 | private static TEXTURE_INTENSITY = 0.7;
15 | private static pixelsBuffer: number[];
16 |
17 | id: number;
18 |
19 | rgb: number;
20 | opaque: boolean;
21 | spriteIds: number[];
22 | renderTypes: number[];
23 | anIntArray2138: number[];
24 | colors: number[];
25 | direction: number;
26 | speed: number;
27 |
28 | pixels: number[];
29 |
30 | size: number;
31 |
32 | public static setSize(size: number) {
33 | Texture.TEXTURE_SIZE = size;
34 | }
35 |
36 | public static setIntensity(intensity: number) {
37 | Texture.TEXTURE_INTENSITY = intensity;
38 | }
39 |
40 | public generatePixels(spriteStore: SpriteStore): boolean {
41 | if (this.pixels) {
42 | return true;
43 | }
44 | const size = Texture.TEXTURE_SIZE;
45 | this.size = size;
46 | const spritePacks = [];
47 | for (let i = 0; i < this.spriteIds.length; i++) {
48 | const spritePack = spriteStore.getSpritePack(this.spriteIds[i]);
49 | if (spritePack == null) {
50 | return false;
51 | }
52 | spritePack.decode();
53 | spritePacks.push(spritePack);
54 | }
55 | const colorCount = size * size;
56 | this.pixels = new Array(colorCount * 4);
57 | for (let i = 0; i < this.spriteIds.length; i++) {
58 | const sprite = spritePacks[i].sprites[0];
59 | sprite.resizeToLibSize();
60 | const spritePixels = sprite.pixelIdx;
61 | const spritePalette = sprite.palette;
62 | const color = this.colors[i];
63 | if ((color & ~0xffffff) === 50331648) {
64 | const i_15_ = color & 0xff00ff;
65 | const i_16_ = (color >> 8) & 0xff;
66 | for (let j = 0; j < spritePalette.length; j++) {
67 | let i_18_ = spritePalette[j];
68 | if ((i_18_ & 0xffff) === i_18_ >> 8) {
69 | i_18_ &= 0xff;
70 | spritePalette[j] =
71 | (((i_15_ * i_18_) >> 8) & 0xff00ff) |
72 | ((i_16_ * i_18_) & 0xff00);
73 | }
74 | }
75 | }
76 | for (let j = 0; j < spritePalette.length; j++) {
77 | spritePalette[j] = ColorUtils.method707(
78 | spritePalette[j],
79 | Texture.TEXTURE_INTENSITY,
80 | );
81 | }
82 | let renderType: number;
83 | if (i === 0) {
84 | renderType = 0;
85 | } else {
86 | renderType = this.renderTypes[i - 1];
87 | }
88 | if (renderType === 0) {
89 | if (sprite.width === size) {
90 | for (let j = 0; j < colorCount; j++) {
91 | this.pixels[j] = spritePalette[spritePixels[j] & 0xff];
92 | }
93 | } else if (sprite.width === 64 && size === 128) {
94 | let index = 0;
95 | for (let i_23_ = 0; i_23_ < size; i_23_++) {
96 | for (let i_24_ = 0; i_24_ < size; i_24_++) {
97 | this.pixels[index++] =
98 | spritePalette[
99 | spritePixels[
100 | (i_24_ >> 1) + ((i_23_ >> 1) << 6)
101 | ] & 0xff
102 | ];
103 | }
104 | }
105 | } else if (sprite.width === 128 && size === 64) {
106 | let index = 0;
107 | for (let i_26_ = 0; i_26_ < size; i_26_++) {
108 | for (let i_27_ = 0; i_27_ < size; i_27_++) {
109 | this.pixels[index++] =
110 | spritePalette[
111 | spritePixels[
112 | (i_27_ << 1) + ((i_26_ << 1) << 7)
113 | ] & 0xff
114 | ];
115 | }
116 | }
117 | } else {
118 | throw new Error();
119 | }
120 | }
121 | }
122 | for (let i = 0; i < colorCount; i++) {
123 | this.pixels[i] &= 0xf8f8ff;
124 | const i_29_ = this.pixels[i];
125 | this.pixels[i + colorCount] = (i_29_ - (i_29_ >>> 3)) & 0xf8f8ff;
126 | this.pixels[i + colorCount + colorCount] =
127 | (i_29_ - (i_29_ >>> 2)) & 0xf8f8ff;
128 | this.pixels[i + colorCount + colorCount + colorCount] =
129 | (i_29_ - (i_29_ >>> 2) - (i_29_ >>> 3)) & 0xf8f8ff;
130 | }
131 | return true;
132 | }
133 |
134 | public animate(gameTick: number) {
135 | if (this.pixels != null) {
136 | if (this.direction === 1 || this.direction === 3) {
137 | if (
138 | Texture.pixelsBuffer == null ||
139 | Texture.pixelsBuffer.length < this.pixels.length
140 | ) {
141 | Texture.pixelsBuffer = new Array(this.pixels.length);
142 | }
143 | let size: number;
144 | if (this.pixels.length === 16384) {
145 | size = 64;
146 | } else {
147 | size = 128;
148 | }
149 | const colorCount = this.pixels.length / 4;
150 | let textureSpeed = size * gameTick * this.speed;
151 | const colorCountMin1 = colorCount - 1;
152 | if (this.direction === 1) {
153 | textureSpeed = -textureSpeed;
154 | }
155 | for (let i = 0; i < colorCount; i++) {
156 | const i_4_ = (i + textureSpeed) & colorCountMin1;
157 | Texture.pixelsBuffer[i] = this.pixels[i_4_];
158 | Texture.pixelsBuffer[i + colorCount] =
159 | this.pixels[i_4_ + colorCount];
160 | Texture.pixelsBuffer[i + colorCount + colorCount] =
161 | this.pixels[i_4_ + colorCount + colorCount];
162 | Texture.pixelsBuffer[
163 | i + colorCount + colorCount + colorCount
164 | ] =
165 | this.pixels[
166 | i_4_ + colorCount + colorCount + colorCount
167 | ];
168 | }
169 | const is = this.pixels;
170 | this.pixels = Texture.pixelsBuffer;
171 | Texture.pixelsBuffer = is;
172 | }
173 | if (this.direction === 2 || this.direction === 4) {
174 | if (
175 | Texture.pixelsBuffer == null ||
176 | Texture.pixelsBuffer.length < this.pixels.length
177 | ) {
178 | Texture.pixelsBuffer = new Array(this.pixels.length);
179 | }
180 | let size: number;
181 | if (this.pixels.length === 16384) {
182 | size = 64;
183 | } else {
184 | size = 128;
185 | }
186 | const colorCount = this.pixels.length / 4;
187 | let textureSpeed = gameTick * this.speed;
188 | const sizeMin1 = size - 1;
189 | if (this.direction === 2) {
190 | textureSpeed = -textureSpeed;
191 | }
192 | for (let x = 0; x < colorCount; x += size) {
193 | for (let y = 0; y < size; y++) {
194 | const i_10_ = x + y;
195 | const i_11_ = x + ((y + textureSpeed) & sizeMin1);
196 | Texture.pixelsBuffer[i_10_] = this.pixels[i_11_];
197 | Texture.pixelsBuffer[i_10_ + colorCount] =
198 | this.pixels[i_11_ + colorCount];
199 | Texture.pixelsBuffer[i_10_ + colorCount + colorCount] =
200 | this.pixels[i_11_ + colorCount + colorCount];
201 | Texture.pixelsBuffer[
202 | i_10_ + colorCount + colorCount + colorCount
203 | ] =
204 | this.pixels[
205 | i_11_ + colorCount + colorCount + colorCount
206 | ];
207 | }
208 | }
209 | const is = this.pixels;
210 | this.pixels = Texture.pixelsBuffer;
211 | Texture.pixelsBuffer = is;
212 | }
213 | }
214 | }
215 |
216 | public resetPixels() {
217 | this.pixels = null;
218 | }
219 |
220 | public async writeToDisk(): Promise {
221 | return new Promise((resolve, reject) => {
222 | try {
223 | const path = './unpacked/textures';
224 | if (!existsSync(path)) {
225 | mkdirSync(path);
226 | }
227 | const png = this.toPng();
228 | png.pack();
229 | const pngBuffer = PNG.sync.write(png);
230 | writeFileSync(`${path}/${this.id}.png`, pngBuffer);
231 | resolve();
232 | } catch (e) {
233 | reject(e);
234 | }
235 | });
236 | }
237 |
238 | /**
239 | * Converts the Texture into a base64 PNG image.
240 | */
241 | public async toBase64(): Promise {
242 | return await pngToBase64(this.toPng());
243 | }
244 |
245 | /**
246 | * Converts the Texture into a PNG image and returns the resulting PNG object.
247 | */
248 | public toPng(): PNG {
249 | const size = this.size;
250 | const png = new PNG({
251 | width: size,
252 | height: size,
253 | filterType: -1,
254 | });
255 |
256 | for (let x = 0; x < size; x++) {
257 | for (let y = 0; y < size; y++) {
258 | const pixel = this.pixels[size * y + x];
259 | const [r, g, b] = toRgb(pixel);
260 | const pngIndex = (size * y + x) << 2;
261 |
262 | png.data[pngIndex] = r;
263 | png.data[pngIndex + 1] = g;
264 | png.data[pngIndex + 2] = b;
265 | png.data[pngIndex + 3] = pixel === 0 ? 0 : 255;
266 | }
267 | }
268 |
269 | return png;
270 | }
271 | }
272 |
273 | export class TextureStore {
274 | public constructor(private fileStore: Filestore) {}
275 |
276 | public async writeToDisk(): Promise {
277 | rmdirSync('./unpacked/textures', { recursive: true });
278 | const ids = this.fileStore
279 | .getIndex('textures')
280 | .getArchive(0)
281 | .files.keys();
282 | for (const id of ids) {
283 | try {
284 | const texture = this.getTexture(id);
285 | texture.generatePixels(this.fileStore.spriteStore);
286 | await texture.writeToDisk();
287 | } catch (e) {
288 | logger.error(`Error writing texture ${id} to disk.`);
289 | logger.error(e);
290 | }
291 | }
292 | }
293 |
294 | public getTexture(id: number): Texture | null {
295 | if (!id && id !== 0) {
296 | logger.warn(`Invalid texture id specified: ${id}`);
297 | return null;
298 | }
299 | const file = this.fileStore
300 | .getIndex('textures')
301 | .getArchive(0)
302 | .getFile(id);
303 | if (file == null) {
304 | logger.warn(`Texture file ${id} not found`);
305 | return null;
306 | }
307 | const buffer = file.content;
308 | buffer.readerIndex = 0;
309 | const texture = new Texture();
310 | texture.id = id;
311 | texture.rgb = buffer.get('SHORT', 'UNSIGNED');
312 | texture.opaque = buffer.get('BYTE', 'UNSIGNED') === 1;
313 | const spritesCount = buffer.get('BYTE', 'UNSIGNED');
314 | if (spritesCount < 1 || spritesCount > 4) {
315 | throw new Error();
316 | }
317 | texture.spriteIds = new Array(spritesCount);
318 | for (let i = 0; i < spritesCount; i++) {
319 | texture.spriteIds[i] = buffer.get('SHORT', 'UNSIGNED');
320 | }
321 | if (spritesCount > 1) {
322 | texture.renderTypes = new Array(spritesCount - 1);
323 | for (let i = 0; i < spritesCount - 1; i++) {
324 | texture.renderTypes[i] = buffer.get('BYTE', 'UNSIGNED');
325 | }
326 | }
327 | if (spritesCount > 1) {
328 | texture.anIntArray2138 = new Array(spritesCount - 1);
329 | for (let i = 0; i < spritesCount - 1; i++) {
330 | texture.anIntArray2138[i] = buffer.get('BYTE', 'UNSIGNED');
331 | }
332 | }
333 | texture.colors = new Array(spritesCount);
334 | for (let i = 0; i < spritesCount; i++) {
335 | texture.colors[i] = buffer.get('INT');
336 | }
337 | texture.direction = buffer.get('BYTE', 'UNSIGNED');
338 | texture.speed = buffer.get('BYTE', 'UNSIGNED');
339 | texture.pixels = null;
340 | return texture;
341 | }
342 |
343 | public getTexturePixels(id: number): number[] | null {
344 | const texture = this.getTexture(id);
345 | if (texture == null) {
346 | return null;
347 | }
348 | if (texture.pixels != null) {
349 | return texture.pixels;
350 | }
351 | const generated = texture.generatePixels(this.fileStore.spriteStore);
352 | if (!generated) {
353 | return null;
354 | }
355 | if (texture.rgb === 0) {
356 | texture.resetPixels();
357 | } else {
358 | //texture.anInt2137--; // TODO Find out why this?
359 | }
360 | return texture.pixels;
361 | }
362 |
363 | public getTextureRgb(id: number): number {
364 | const texture = this.getTexture(id);
365 | if (texture == null) {
366 | return 0;
367 | }
368 | return texture.rgb;
369 | }
370 |
371 | public isTextureOpaque(id: number): boolean {
372 | const texture = this.getTexture(id);
373 | if (texture == null) {
374 | return false;
375 | }
376 | return texture.opaque;
377 | }
378 |
379 | // this only works if textures are cached
380 | public isTextureLowMemory(id: number): boolean {
381 | const texture = this.getTexture(id);
382 | if (texture == null) {
383 | return false;
384 | }
385 | texture.generatePixels(this.fileStore.spriteStore);
386 | return texture.size === Texture.LOW_MEMORY_TEXTURE_SIZE;
387 | }
388 | }
389 |
--------------------------------------------------------------------------------
/src/filestore/stores/widget-store.ts:
--------------------------------------------------------------------------------
1 | import { ByteBuffer } from '@runejs/common';
2 |
3 | import type { FileIndex } from '../file-index';
4 | import type { Filestore } from '../filestore';
5 | import type { FileData } from '../file-data';
6 | import type { Archive } from '../archive';
7 | import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
8 | import { logger } from '@runejs/common';
9 |
10 | export abstract class WidgetBase {
11 | public id: number;
12 | public parentId: number;
13 | public type: number;
14 | public format: number;
15 | public originalX: number;
16 | public originalY: number;
17 | public x: number;
18 | public y: number;
19 | public width: number;
20 | public height: number;
21 | public menuType: number;
22 | public contentType: number;
23 | public opacity: number;
24 | public hidden: boolean;
25 | public targetVerb: string;
26 | public spellName: string;
27 | public clickMask: number;
28 | public hintText: string;
29 | public hoveredSiblingId: number;
30 | public alternateOperators: number[];
31 | public alternateRhs: number[];
32 | public cs1: number[][];
33 | public hasListeners: boolean;
34 |
35 | /**
36 | * Writes this unpacked widget file to the disk under `./unpacked/widgets/{widgetId}_widget.json`
37 | */
38 | public async writeToDisk(): Promise {
39 | return new Promise((resolve, reject) => {
40 | try {
41 | if (!existsSync('./unpacked/widgets')) {
42 | mkdirSync('./unpacked/widgets');
43 | }
44 |
45 | const { id } = this;
46 |
47 | writeFileSync(
48 | `./unpacked/widgets/${id}.json`,
49 | JSON.stringify(this, null, 4),
50 | );
51 |
52 | resolve();
53 | } catch (error) {
54 | reject(error);
55 | }
56 | });
57 | }
58 | }
59 |
60 | export class ParentWidget extends WidgetBase {
61 | public children: WidgetBase[];
62 |
63 | public constructor(id: number) {
64 | super();
65 | this.id = id;
66 | }
67 | }
68 |
69 | export class ContainerWidget extends WidgetBase {
70 | public type = 0;
71 | public scrollHeight: number;
72 | public scrollPosition: number;
73 | public scrollWidth: number;
74 | public children?: WidgetBase[];
75 | }
76 |
77 | export class TextWidget extends WidgetBase {
78 | type = 1;
79 | textAlignmentX: number;
80 | textAlignmentY: number;
81 | lineHeight: number;
82 | fontId: number;
83 | textShadowed: boolean;
84 | textColor: number;
85 | }
86 |
87 | export class InteractableItemWidget extends WidgetBase {
88 | type = 2;
89 | items: number[];
90 | itemAmounts: number[];
91 | itemSwapable: boolean;
92 | isInventory: boolean;
93 | itemUsable: boolean;
94 | itemDeletesDraged: boolean;
95 | itemSpritePadsX: number;
96 | itemSpritePadsY: number;
97 | imageX: number[];
98 | imageY: number[];
99 | images: number[];
100 | options: string[];
101 | }
102 |
103 | export class RectangleWidget extends WidgetBase {
104 | type = 3;
105 | filled: boolean;
106 | textColor: number;
107 | alternateTextColor: number;
108 | hoveredTextColor: number;
109 | alternateHoveredTextColor: number;
110 | }
111 |
112 | export class LinkWidget extends WidgetBase {
113 | type = 4;
114 | textAlignmentX: number;
115 | textAlignmentY: number;
116 | lineHeight: number;
117 | fontId: number;
118 | textShadowed: boolean;
119 | text: string;
120 | alternateText: string;
121 | textColor: number;
122 | alternateTextColor: number;
123 | hoveredTextColor: number;
124 | alternateHoveredTextColor: number;
125 | }
126 |
127 | export class SpriteWidget extends WidgetBase {
128 | type = 5;
129 | spriteId: number;
130 | alternateSpriteId: number;
131 |
132 | textureId: number;
133 | tiled: boolean;
134 | }
135 |
136 | export class ModelWidget extends WidgetBase {
137 | type = 6;
138 | modelType: number;
139 | modelId: number;
140 | alternateModelType: number;
141 | alternateModelId: number;
142 | animation: number;
143 | alternateAnimation: number;
144 | modelZoom: number;
145 | rotationX: number;
146 | rotationY: number;
147 | rotationZ: number;
148 | offsetX: number;
149 | offsetY: number;
150 | orthogonal: boolean;
151 | }
152 |
153 | export class StaticItemWidget extends WidgetBase {
154 | type = 7;
155 | items: number[];
156 | itemAmounts: number[];
157 | isInventory: boolean;
158 | itemSpritePadsX: number;
159 | itemSpritePadsY: number;
160 | options: string[];
161 | textAlignmentX: number;
162 | fontId: number;
163 | textShadowed: boolean;
164 | textColor: number;
165 | }
166 |
167 | export class TooltipWidget extends WidgetBase {
168 | type = 8;
169 | text: string;
170 | }
171 |
172 | export class LineWidget extends WidgetBase {
173 | type = 9;
174 | lineWidth: number;
175 | textColor: number;
176 | }
177 |
178 | /**
179 | * Controls game interface widget file format and storage.
180 | */
181 | export class WidgetStore {
182 | /**
183 | * The main file index of the widget store.
184 | */
185 | public readonly widgetFileIndex: FileIndex;
186 |
187 | public constructor(private fileStore: Filestore) {
188 | this.widgetFileIndex = fileStore.getIndex('widgets');
189 | }
190 |
191 | /**
192 | * Writes all unpacked widget files to the disk under `./unpacked/widgets/`
193 | */
194 | public async writeToDisk(): Promise {
195 | const widgets = this.decodeWidgetStore();
196 | for (const widget of widgets) {
197 | try {
198 | await widget.writeToDisk();
199 | } catch (e) {
200 | logger.error(e);
201 | }
202 | }
203 | }
204 |
205 | /**
206 | * Decodes the specified widget file.
207 | * @param id The numeric ID of the widget file to decode.
208 | */
209 | public decodeWidget(id: number): WidgetBase {
210 | const file = this.widgetFileIndex.files.get(id);
211 | if (file.type === 'file') {
212 | return this.decodeWidgetFile(id, file);
213 | }
214 | if (file.type === 'archive') {
215 | const widgetParent = new ParentWidget(id);
216 | const archive: Archive = file as Archive;
217 | archive.decodeArchiveFiles();
218 | const widgetChildFiles: FileData[] = Array.from(
219 | archive.files.values(),
220 | );
221 | widgetParent.children = new Array(widgetChildFiles.length);
222 | for (let i = 0; i < widgetChildFiles.length; i++) {
223 | widgetParent.children[i] = this.decodeWidgetFile(
224 | i,
225 | widgetChildFiles[i],
226 | );
227 | }
228 |
229 | return widgetParent;
230 | }
231 | }
232 |
233 | /**
234 | * Decodes the specified widget file, first determining if it is in the new or older widget format.
235 | * @param id The numeric ID of the widget file to decode.
236 | * @param widgetFile The file data of the widget file to decode.
237 | */
238 | public decodeWidgetFile(
239 | id: number,
240 | widgetFile: FileData | Archive,
241 | ): WidgetBase {
242 | if (!widgetFile.content) {
243 | widgetFile.decompress();
244 | }
245 |
246 | const content = widgetFile.content;
247 | if (content[0] === -1) {
248 | return this.decodeWidgetFormat2(id, content);
249 | }
250 | return this.decodeWidgetFormat1(id, content);
251 | }
252 |
253 | /**
254 | * Decodes all widget files within the filestore.
255 | * @returns The list of decoded WidgetBase objects from the widget store.
256 | */
257 | public decodeWidgetStore(): WidgetBase[] {
258 | const widgetCount = this.widgetFileIndex.files.size;
259 | const widgets: WidgetBase[] = new Array(widgetCount);
260 | for (let widgetId = 0; widgetId < widgetCount; widgetId++) {
261 | try {
262 | widgets[widgetId] = this.decodeWidget(widgetId);
263 | } catch (error) {
264 | logger.error(`Error decoding widget ${widgetId}:`);
265 | logger.error(error);
266 | }
267 | }
268 |
269 | return widgets;
270 | }
271 |
272 | public createWidget(widgetType: number): WidgetBase {
273 | let widget: WidgetBase;
274 |
275 | if (widgetType === 0) {
276 | widget = new ContainerWidget();
277 | } else if (widgetType === 1) {
278 | widget = new TextWidget();
279 | } else if (widgetType === 2) {
280 | widget = new InteractableItemWidget();
281 | } else if (widgetType === 3) {
282 | widget = new RectangleWidget();
283 | } else if (widgetType === 4) {
284 | widget = new LinkWidget();
285 | } else if (widgetType === 5) {
286 | widget = new SpriteWidget();
287 | } else if (widgetType === 6) {
288 | widget = new ModelWidget();
289 | } else if (widgetType === 7) {
290 | widget = new StaticItemWidget();
291 | } else if (widgetType === 8) {
292 | widget = new TooltipWidget();
293 | } else if (widgetType === 9) {
294 | widget = new LineWidget();
295 | }
296 |
297 | return widget;
298 | }
299 |
300 | public decodeWidgetFormat2(
301 | widgetId: number,
302 | inputBuffer: ByteBuffer,
303 | ): WidgetBase {
304 | const buffer = new ByteBuffer(inputBuffer);
305 |
306 | buffer.readerIndex = 1; // skip the first byte for the new format
307 |
308 | const widgetType = buffer.get('BYTE');
309 | const widget: WidgetBase = this.createWidget(widgetType);
310 |
311 | widget.id = widgetId;
312 | widget.format = 2;
313 |
314 | widget.contentType = buffer.get('SHORT', 'UNSIGNED');
315 | widget.originalX = buffer.get('SHORT');
316 | widget.originalY = buffer.get('SHORT');
317 | widget.width = buffer.get('SHORT', 'UNSIGNED');
318 |
319 | widget.x = widget.originalX;
320 | widget.y = widget.originalY;
321 |
322 | if (widget instanceof LineWidget) {
323 | widget.height = buffer.get('SHORT');
324 | } else {
325 | widget.height = buffer.get('SHORT', 'UNSIGNED');
326 | }
327 |
328 | widget.parentId = buffer.get('SHORT', 'UNSIGNED');
329 | if (widget.parentId === 0xffff) {
330 | widget.parentId = -1;
331 | }
332 |
333 | widget.hidden = buffer.get('BYTE', 'UNSIGNED') === 1;
334 | widget.hasListeners = buffer.get('BYTE', 'UNSIGNED') === 1;
335 |
336 | if (widget instanceof ContainerWidget) {
337 | widget.scrollWidth = buffer.get('SHORT', 'UNSIGNED');
338 | widget.scrollPosition = buffer.get('SHORT', 'UNSIGNED');
339 | }
340 |
341 | if (widget instanceof SpriteWidget) {
342 | widget.spriteId = buffer.get('INT');
343 | widget.textureId = buffer.get('SHORT', 'UNSIGNED');
344 | widget.tiled = buffer.get('BYTE', 'UNSIGNED') === 1;
345 | widget.opacity = buffer.get('BYTE', 'UNSIGNED');
346 | }
347 |
348 | if (widget instanceof ModelWidget) {
349 | widget.modelType = 1;
350 | widget.modelId = buffer.get('SHORT', 'UNSIGNED');
351 | widget.offsetX = buffer.get('SHORT');
352 | widget.offsetY = buffer.get('SHORT');
353 | widget.rotationX = buffer.get('SHORT', 'UNSIGNED');
354 | widget.rotationZ = buffer.get('SHORT', 'UNSIGNED');
355 | widget.rotationY = buffer.get('SHORT', 'UNSIGNED');
356 | widget.modelZoom = buffer.get('SHORT', 'UNSIGNED');
357 | widget.animation = buffer.get('SHORT', 'UNSIGNED');
358 | widget.orthogonal = buffer.get('BYTE', 'UNSIGNED') === 1;
359 |
360 | if (widget.animation === 65535) {
361 | widget.animation = -1;
362 | }
363 |
364 | if (widget.modelId === 65535) {
365 | widget.modelId = -1;
366 | }
367 | }
368 |
369 | if (widget instanceof LinkWidget) {
370 | widget.fontId = buffer.get('SHORT', 'UNSIGNED');
371 | widget.text = buffer.getString();
372 | widget.lineHeight = buffer.get('BYTE', 'UNSIGNED');
373 | widget.textAlignmentX = buffer.get('BYTE', 'UNSIGNED');
374 | widget.textAlignmentY = buffer.get('BYTE', 'UNSIGNED');
375 | widget.textShadowed = buffer.get('BYTE', 'UNSIGNED') === 1;
376 | widget.textColor = buffer.get('INT');
377 | }
378 |
379 | if (widget instanceof RectangleWidget) {
380 | widget.textColor = buffer.get('INT');
381 | widget.filled = buffer.get('BYTE', 'UNSIGNED') === 1;
382 | widget.opacity = buffer.get('BYTE', 'UNSIGNED');
383 | }
384 |
385 | if (widget instanceof LineWidget) {
386 | widget.lineWidth = buffer.get('BYTE', 'UNSIGNED');
387 | widget.textColor = buffer.get('INT');
388 | }
389 |
390 | if (widget.hasListeners) {
391 | // @TODO decode listeners
392 | }
393 |
394 | return widget;
395 | }
396 |
397 | public decodeWidgetFormat1(
398 | widgetId: number,
399 | inputBuffer: ByteBuffer,
400 | ): WidgetBase {
401 | const buffer = new ByteBuffer(inputBuffer);
402 |
403 | const widgetType = buffer.get('BYTE');
404 | const widget: WidgetBase = this.createWidget(widgetType);
405 |
406 | widget.id = widgetId;
407 | widget.format = 1;
408 |
409 | widget.menuType = buffer.get('BYTE', 'UNSIGNED');
410 | widget.contentType = buffer.get('SHORT', 'UNSIGNED');
411 | widget.originalX = buffer.get('SHORT');
412 | widget.originalY = buffer.get('SHORT');
413 | widget.width = buffer.get('SHORT', 'UNSIGNED');
414 | widget.height = buffer.get('SHORT', 'UNSIGNED');
415 | widget.opacity = buffer.get('BYTE', 'UNSIGNED');
416 | widget.parentId = buffer.get('SHORT', 'UNSIGNED');
417 | widget.hoveredSiblingId = buffer.get('SHORT', 'UNSIGNED');
418 |
419 | widget.x = widget.originalX;
420 | widget.y = widget.originalY;
421 |
422 | if (widget.parentId === 0xffff) {
423 | widget.parentId = -1;
424 | }
425 |
426 | if (widget.hoveredSiblingId === 0xffff) {
427 | // 0xffff === 65535
428 | widget.hoveredSiblingId = -1;
429 | }
430 |
431 | const alternateCount = buffer.get('BYTE', 'UNSIGNED');
432 |
433 | if (alternateCount > 0) {
434 | widget.alternateOperators = new Array(alternateCount);
435 | widget.alternateRhs = new Array(alternateCount);
436 | for (let i = 0; alternateCount > i; i++) {
437 | widget.alternateOperators[i] = buffer.get('BYTE', 'UNSIGNED');
438 | widget.alternateRhs[i] = buffer.get('SHORT', 'UNSIGNED');
439 | }
440 | }
441 |
442 | const clientScriptCount = buffer.get('BYTE', 'UNSIGNED');
443 |
444 | if (clientScriptCount > 0) {
445 | widget.cs1 = new Array(clientScriptCount);
446 |
447 | for (let csIndex = 0; csIndex < clientScriptCount; csIndex++) {
448 | const k = buffer.get('SHORT', 'UNSIGNED');
449 | widget.cs1[csIndex] = new Array(k);
450 |
451 | for (let j = 0; k > j; j++) {
452 | widget.cs1[csIndex][j] = buffer.get('SHORT', 'UNSIGNED');
453 | if (widget.cs1[csIndex][j] === 65535) {
454 | widget.cs1[csIndex][j] = -1;
455 | }
456 | }
457 | }
458 | }
459 |
460 | if (widget instanceof ContainerWidget) {
461 | widget.scrollHeight = buffer.get('SHORT', 'UNSIGNED');
462 | widget.hidden = buffer.get('BYTE', 'UNSIGNED') === 1;
463 | }
464 |
465 | if (widget instanceof TextWidget) {
466 | buffer.get('SHORT', 'UNSIGNED'); // @TODO look into these at some point
467 | buffer.get('BYTE', 'UNSIGNED');
468 | }
469 |
470 | if (widget instanceof InteractableItemWidget) {
471 | widget.items = new Array(widget.height * widget.width);
472 | widget.itemAmounts = new Array(widget.height * widget.width);
473 | widget.itemSwapable = buffer.get('BYTE', 'UNSIGNED') === 1;
474 | widget.isInventory = buffer.get('BYTE', 'UNSIGNED') === 1;
475 | widget.itemUsable = buffer.get('BYTE', 'UNSIGNED') === 1;
476 | widget.itemDeletesDraged = buffer.get('BYTE', 'UNSIGNED') === 1;
477 | widget.itemSpritePadsX = buffer.get('BYTE', 'UNSIGNED');
478 | widget.itemSpritePadsY = buffer.get('BYTE', 'UNSIGNED');
479 | widget.imageX = new Array(20);
480 | widget.imageY = new Array(20);
481 | widget.images = new Array(20);
482 |
483 | for (let sprite = 0; sprite < 20; sprite++) {
484 | const hasSprite = buffer.get('BYTE', 'UNSIGNED');
485 | if (hasSprite === 1) {
486 | widget.images[sprite] = buffer.get('SHORT');
487 | widget.imageX[sprite] = buffer.get('SHORT');
488 | widget.imageY[sprite] = buffer.get('INT');
489 | } else {
490 | widget.imageY[sprite] = -1;
491 | }
492 | }
493 |
494 | widget.options = new Array(5);
495 |
496 | for (let i = 0; i < 5; i++) {
497 | widget.options[i] = buffer.getString();
498 | if (widget.options[i].length === 0) {
499 | widget.options[i] = null;
500 | }
501 | }
502 | }
503 |
504 | if (widget instanceof RectangleWidget) {
505 | widget.filled = buffer.get('BYTE', 'UNSIGNED') === 1;
506 | }
507 |
508 | if (widget instanceof LinkWidget || widget instanceof TextWidget) {
509 | widget.textAlignmentX = buffer.get('BYTE', 'UNSIGNED');
510 | widget.textAlignmentY = buffer.get('BYTE', 'UNSIGNED');
511 | widget.lineHeight = buffer.get('BYTE', 'UNSIGNED');
512 | widget.fontId = buffer.get('SHORT', 'UNSIGNED');
513 | widget.textShadowed = buffer.get('BYTE', 'UNSIGNED') === 1;
514 | }
515 |
516 | if (widget instanceof LinkWidget) {
517 | widget.text = buffer.getString();
518 | widget.alternateText = buffer.getString();
519 | }
520 |
521 | if (
522 | widget instanceof TextWidget ||
523 | widget instanceof RectangleWidget ||
524 | widget instanceof LinkWidget
525 | ) {
526 | widget.textColor = buffer.get('INT');
527 | }
528 |
529 | if (widget instanceof RectangleWidget || widget instanceof LinkWidget) {
530 | widget.alternateTextColor = buffer.get('INT');
531 | widget.hoveredTextColor = buffer.get('INT');
532 | widget.alternateHoveredTextColor = buffer.get('INT');
533 | }
534 |
535 | if (widget instanceof SpriteWidget) {
536 | widget.spriteId = buffer.get('INT');
537 | widget.alternateSpriteId = buffer.get('INT');
538 | }
539 |
540 | if (widget instanceof ModelWidget) {
541 | widget.modelType = 1;
542 | widget.alternateModelType = 1;
543 | widget.modelId = buffer.get('SHORT', 'UNSIGNED');
544 | widget.alternateModelId = buffer.get('SHORT', 'UNSIGNED');
545 | widget.animation = buffer.get('SHORT', 'UNSIGNED');
546 | widget.alternateAnimation = buffer.get('SHORT', 'UNSIGNED');
547 | widget.modelZoom = buffer.get('SHORT', 'UNSIGNED');
548 | widget.rotationX = buffer.get('SHORT', 'UNSIGNED');
549 | widget.rotationY = buffer.get('SHORT', 'UNSIGNED');
550 |
551 | if (widget.modelId === 0xffff) {
552 | widget.modelId = -1;
553 | }
554 |
555 | if (widget.alternateModelId === 0xffff) {
556 | widget.alternateModelId = -1;
557 | }
558 |
559 | if (widget.animation === 0xffff) {
560 | widget.animation = -1;
561 | }
562 |
563 | if (widget.alternateAnimation === 0xffff) {
564 | widget.alternateAnimation = -1;
565 | }
566 | }
567 |
568 | if (widget instanceof StaticItemWidget) {
569 | widget.items = new Array(widget.width * widget.height);
570 | widget.itemAmounts = new Array(widget.width * widget.height);
571 | widget.textAlignmentX = buffer.get('BYTE', 'UNSIGNED');
572 | widget.fontId = buffer.get('SHORT', 'UNSIGNED');
573 | widget.textShadowed = buffer.get('BYTE', 'UNSIGNED') === 1;
574 | widget.textColor = buffer.get('INT');
575 | widget.itemSpritePadsX = buffer.get('SHORT');
576 | widget.itemSpritePadsY = buffer.get('SHORT');
577 | widget.isInventory = buffer.get('BYTE', 'UNSIGNED') === 1;
578 |
579 | widget.options = new Array(5);
580 |
581 | for (let i = 0; i < 5; i++) {
582 | widget.options[i] = buffer.getString();
583 | if (widget.options[i].length === 0) {
584 | widget.options[i] = null;
585 | }
586 | }
587 | }
588 |
589 | if (widget instanceof TooltipWidget) {
590 | widget.text = buffer.getString();
591 | }
592 |
593 | if (widget.menuType === 2 || widget instanceof InteractableItemWidget) {
594 | widget.targetVerb = buffer.getString();
595 | widget.spellName = buffer.getString();
596 | widget.clickMask = buffer.get('SHORT', 'UNSIGNED');
597 | }
598 |
599 | if (
600 | widget.menuType === 1 ||
601 | widget.menuType === 4 ||
602 | widget.menuType === 5 ||
603 | widget.menuType === 6
604 | ) {
605 | widget.hintText = buffer.getString();
606 |
607 | if (widget.hintText.length === 0) {
608 | if (widget.menuType === 1) {
609 | widget.hintText = 'Ok';
610 | } else if (widget.menuType === 4 || widget.menuType === 5) {
611 | widget.hintText = 'Select';
612 | } else if (widget.menuType === 6) {
613 | widget.hintText = 'Continue';
614 | }
615 | }
616 | }
617 |
618 | return widget;
619 | }
620 | }
621 |
--------------------------------------------------------------------------------
/src/filestore/util/index.ts:
--------------------------------------------------------------------------------
1 | export * from './name-hash';
2 | export * from './xtea';
3 | export * from './png';
4 |
--------------------------------------------------------------------------------
/src/filestore/util/name-hash.ts:
--------------------------------------------------------------------------------
1 | import { readFileSync } from 'node:fs';
2 | import { join } from 'node:path';
3 | const parser = require('properties-parser');
4 |
5 | export function hash(name: string): number {
6 | let hash = 0;
7 | for (let i = 0; i < name.length; i++) {
8 | hash = (Math.imul(31, hash) + name.charCodeAt(i)) | 0;
9 | }
10 |
11 | return hash;
12 | }
13 |
14 | export function getFileNames(dir: string) {
15 | return parser.parse(readFileSync(join(dir, 'file-names.properties')));
16 | }
17 |
--------------------------------------------------------------------------------
/src/filestore/util/png.ts:
--------------------------------------------------------------------------------
1 | import type { PNG } from 'pngjs';
2 |
3 | export const pngToBase64 = async (png: PNG): Promise => {
4 | const chunks = [];
5 |
6 | png.pack();
7 | png.on('data', (chunk) => chunks.push(chunk));
8 |
9 | return await new Promise((resolve) => {
10 | png.on('end', () => resolve(Buffer.concat(chunks).toString('base64')));
11 | });
12 | };
13 |
--------------------------------------------------------------------------------
/src/filestore/util/xtea.ts:
--------------------------------------------------------------------------------
1 | import type { XteaDefinition } from '../stores';
2 | import { loadConfigurationFiles } from '@runejs/common/fs';
3 |
4 | export type XteaRegionMap = { [key: number]: XteaRegion };
5 |
6 | export class XteaRegion implements XteaDefinition {
7 | public mapsquare: number;
8 | public key: [number, number, number, number];
9 | public archive: number;
10 | public group: number;
11 | public name: string;
12 | public name_hash: number;
13 |
14 | public constructor(
15 | mapsquare: number,
16 | key: [number, number, number, number],
17 | archive: number,
18 | group: number,
19 | name: string,
20 | name_hash: number,
21 | ) {
22 | this.mapsquare = mapsquare;
23 | this.key = key;
24 | this.archive = archive;
25 | this.group = group;
26 | this.name = name;
27 | this.name_hash = name_hash;
28 | }
29 | }
30 |
31 | export const createXteaRegion = (config: XteaDefinition): XteaRegion =>
32 | new XteaRegion(
33 | config.mapsquare,
34 | config.key,
35 | config.archive,
36 | config.group,
37 | config.name,
38 | config.name_hash,
39 | );
40 |
41 | export const loadXteaRegionFiles = async (
42 | path: string,
43 | ): Promise => {
44 | const regions: XteaRegionMap = {};
45 | const files = await loadConfigurationFiles(path);
46 | for (const file of files) {
47 | for (const region of file) {
48 | const xteaRegion = createXteaRegion(region);
49 | regions[xteaRegion.name] = xteaRegion;
50 | }
51 | }
52 | return regions;
53 | };
54 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | export * from './filestore';
2 |
--------------------------------------------------------------------------------
/src/run.ts:
--------------------------------------------------------------------------------
1 | import { Filestore } from './filestore';
2 | import { logger } from '@runejs/common';
3 |
4 | const fileStore = new Filestore('./packed', { configDir: './config' });
5 | const region = fileStore.regionStore.getLandscapeFile(50, 44);
6 | logger.info(JSON.stringify(region, null, 2));
7 |
8 | fileStore.widgetStore.writeToDisk();
9 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "commonjs",
4 | "target": "ESNext",
5 | "jsx": "preserve",
6 | "importHelpers": true,
7 | "moduleResolution": "node",
8 | "experimentalDecorators": true,
9 | "esModuleInterop": true,
10 | "allowSyntheticDefaultImports": true,
11 | "sourceMap": false,
12 | "baseUrl": ".",
13 | "allowJs": true,
14 | "declaration": true,
15 | "outDir": "./lib",
16 | "types": ["node"]
17 | },
18 | "include": ["src/**/*.ts"],
19 | "exclude": ["node_modules"]
20 | }
21 |
--------------------------------------------------------------------------------