├── .gitignore
├── LICENSE
├── README.md
├── lib
├── __init__.py
├── console.py
├── fla
│ ├── README.md
│ ├── __init__.py
│ ├── dat
│ │ ├── __init__.py
│ │ └── bitmap.py
│ ├── dom
│ │ ├── __init__.py
│ │ ├── bitmap_instance.py
│ │ ├── bitmap_item.py
│ │ ├── document.py
│ │ ├── dynamic_text.py
│ │ ├── folder_item.py
│ │ ├── frame.py
│ │ ├── group.py
│ │ ├── layer.py
│ │ ├── shape.py
│ │ ├── static_text.py
│ │ ├── symbol_instance.py
│ │ ├── symbol_item.py
│ │ ├── text_attrs.py
│ │ ├── text_run.py
│ │ └── timeline.py
│ ├── edge
│ │ ├── __init__.py
│ │ └── edge.py
│ ├── fill
│ │ ├── __init__.py
│ │ ├── bitmap_fill.py
│ │ ├── fill_style.py
│ │ ├── gradient_entry.py
│ │ ├── linear_gradient.py
│ │ ├── radial_gradient.py
│ │ └── solid_color.py
│ ├── filter
│ │ ├── __init__.py
│ │ ├── drop_shadow_filter.py
│ │ └── glow_filter.py
│ ├── geom
│ │ ├── __init__.py
│ │ ├── color.py
│ │ ├── color_transform.py
│ │ ├── matrix.py
│ │ └── point.py
│ └── stroke
│ │ ├── __init__.py
│ │ ├── solid_stroke.py
│ │ └── stroke_style.py
├── sc
│ ├── README.md
│ ├── __init__.py
│ ├── matrix_bank.py
│ ├── movieclip.py
│ ├── resource.py
│ ├── shape.py
│ ├── swf.py
│ ├── text_field.py
│ ├── texture.py
│ └── writable.py
├── sc_import.py
├── scwmake_credit
│ ├── DOMDocument.xml
│ ├── META-INF
│ │ └── metadata.xml
│ ├── MobileSettings.xml
│ ├── PublishSettings.xml
│ ├── bin
│ │ └── SymDepend.cache
│ └── scwmake_credit.xfl
└── utils
│ ├── __init__.py
│ ├── reader.py
│ └── writer.py
├── main.py
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | assets
3 | __pycache__
--------------------------------------------------------------------------------
/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 | SC (Deprecated)
2 |
3 | This repository is deprecated. See https://github.com/scwmake for newer version of this tool.
4 |
5 | Supercell SWF (Flash) file format decompiler and compiler. Supercell's games using .sc files for almost all 2D graphics (UI, VFX, particles, characters facial animations, etc.).
6 |
7 | Please follow the Supercell fan content policy - http://supercell.com/fan-content-policy!
8 |
9 | ## Credits
10 | Tool created by Fred-31 and DaniilSV. Inspired by XCoder and Supercell-Extractor.
11 |
12 | ## About
13 |
14 | **THE RELEASE IS PREMATURE AND THE TOOL IS NOT FULLY COMPLETED (REPOSITORY IS OPEN DUE TO THE CURRENT CIRCUMSTANCES) !!!**
15 |
16 | This tool is designed to import and export 2D assets (`*.sc`, `*_dl.sc`, `*_tex.sc` files) from Supercell games using Adobe Animate 2019. At the moment, the tool is very slow when working with large files (so we do not advise you to import large files like ui.sc if you have a weak PC, 8Gb RAM and fast CPU is recommended ). Maybe we rewrite it with C++ or C# in future...
17 |
18 | There are also a lot of bugs and errors in the tool, if you find them, please let us know in Issues or our Discord server!
19 |
20 | ## Installation and Requirements
21 | - Python 3.10+ or newer version.
22 | - Execute ```pip install -r requirements.txt``` command in tool directory after installing Python.
23 | - Adobe Animate 2019 (2019 is recommended because it's more optimized than 2022!).
24 | - TexturePacker (for getting and saving sprite sheets/texture atlases).
25 |
26 | ## How To Use
27 |
28 | Leak... not implemented...
29 |
30 | ~~Please **WATCH ALL THE VIDEOS BELOW** before using this tool!~~
31 |
32 | ~~1. Converting `.sc` to Adobe Animate project file.~~
33 | ~~2. Organizing your Adobe Animate project.~~
34 | ~~3. Saving your Adobe Animate project for converting it to `.sc` file.~~
35 | ~~4. Creating sprite sheets/texture atlases in TexturePacker.~~
36 | ~~5. Converting Adobe Animate project to `.sc` file.~~
37 |
38 | ## TODO
39 | - Add TexturePacker projects support.
40 | - Refactor some code in ```lib/sc```.
41 | - Write code in ```lib/fla```.
42 | - Add ```sc_export.py``` functional.
43 | - Rewrite it with C++ or C# in future...
44 |
45 | Hi Garlfin and Vorono4ka!
46 |
--------------------------------------------------------------------------------
/lib/__init__.py:
--------------------------------------------------------------------------------
1 |
2 | from lib.sc_import import sc_to_fla
3 | #from lib.sc_export import fla_to_sc
4 |
--------------------------------------------------------------------------------
/lib/console.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | import colorama
4 |
5 | import platform
6 |
7 | from shutil import get_terminal_size
8 |
9 | if platform.system() == "Windows":
10 | colorama.init()
11 |
12 | def Time(seconds):
13 | des = ('msec', 'sec', 'min', 'hours')
14 | temp = []
15 | temp.append('%s %s'%(str(float(seconds)).split('.')[1][:3], des[0]))
16 | seconds = int(seconds)
17 | temp.append(f'{seconds % 60} {des[1]}')
18 |
19 | seconds //= 60
20 | while seconds:
21 | if len(temp) == 3:
22 | temp.append(f'{seconds % 60} {des[3]}')
23 | break
24 |
25 | temp.append(f'{seconds % 60} {des[len(temp)]}')
26 | seconds //= 60
27 |
28 | return ' '.join(temp[::-1])
29 |
30 | class Console:
31 | @staticmethod
32 | def title(message):
33 | print(colorama.Fore.GREEN + message.center(get_terminal_size().columns) + colorama.Style.RESET_ALL)
34 | @staticmethod
35 | def info(message: str):
36 | print(colorama.Fore.GREEN + f"[INFO] {message}" + colorama.Style.RESET_ALL)
37 |
38 | @staticmethod
39 | def warning(message: str):
40 | print(colorama.Fore.MAGENTA + f"[WARNING] {message}" + colorama.Style.RESET_ALL)
41 |
42 | @staticmethod
43 | def error(message: str):
44 | print(colorama.Fore.RED + f"[ERROR] {message}" + colorama.Style.RESET_ALL)
45 |
46 | @staticmethod
47 | def progress_bar(message, current, total, start=0, end=100):
48 | sys.stdout.write(colorama.Fore.GREEN + f"\r[{((current + 1) * end + start) // total + start}%] {message}" + colorama.Style.RESET_ALL)
49 |
--------------------------------------------------------------------------------
/lib/fla/README.md:
--------------------------------------------------------------------------------
1 | # Adobe Animate FLA file format
2 |
3 | Module for working with Adobe Animate `.fla` file format. Made by Fred-31 (Pavel Sokov).
4 | Done by ~50%.
5 |
--------------------------------------------------------------------------------
/lib/fla/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from shutil import rmtree
4 |
5 | from zipfile import ZipFile
6 | from zipfile import BadZipfile
7 |
8 | from lib.fla.dom.document import DOMDocument
9 | from lib.fla.dom.folder_item import DOMFolderItem
10 | from lib.fla.dom.bitmap_item import DOMBitmapItem
11 | from lib.fla.dom.symbol_item import DOMSymbolItem
12 | from lib.fla.dom.timeline import DOMTimeline
13 | from lib.fla.dom.layer import DOMLayer
14 | from lib.fla.dom.frame import DOMFrame
15 | from lib.fla.dom.group import DOMGroup
16 | from lib.fla.dom.bitmap_instance import DOMBitmapInstance
17 | from lib.fla.dom.symbol_instance import DOMSymbolInstance
18 | from lib.fla.dom.shape import DOMShape
19 | from lib.fla.dom.static_text import DOMStaticText
20 | from lib.fla.dom.dynamic_text import DOMDynamicText
21 | from lib.fla.dom.text_run import DOMTextRun
22 | from lib.fla.dom.text_attrs import DOMTextAttrs
23 |
24 | from lib.fla.fill.fill_style import FillStyle
25 | from lib.fla.fill.solid_color import SolidColor
26 | from lib.fla.fill.gradient_entry import GradientEntry
27 | from lib.fla.fill.linear_gradient import LinearGradient
28 | from lib.fla.fill.radial_gradient import RadialGradient
29 | from lib.fla.fill.bitmap_fill import BitmapFill
30 |
31 | from lib.fla.stroke.stroke_style import StrokeStyle
32 | from lib.fla.stroke.solid_stroke import SolidStroke
33 |
34 | from lib.fla.edge.edge import Edge
35 |
36 | from lib.fla.filter.glow_filter import GlowFilter
37 | from lib.fla.filter.drop_shadow_filter import DrowShadowFilter
38 |
39 | from lib.fla.geom.point import Point
40 | from lib.fla.geom.matrix import Matrix
41 | from lib.fla.geom.color_transform import ColorTransform
42 | from lib.fla.geom.color import Color
43 |
44 | from lib.fla.dat.bitmap import Bitmap
45 |
46 | import io
47 | import struct
48 | # TODO move to custom zip/fla reader
49 |
50 |
51 | class XFL:
52 | @staticmethod
53 | def load(projectpath: str):
54 | if os.path.isfile(projectpath):
55 | if os.path.splitext(projectpath)[1] != ".fla":
56 | raise Exception(f"File is not \".fla\": {projectpath}")
57 |
58 | fla_file = open(projectpath, "rb")
59 | folder = os.path.splitext(projectpath)[0]
60 |
61 | try:
62 | with ZipFile(fla_file, 'r') as file:
63 | file.extractall(folder)
64 |
65 | except BadZipfile:
66 | EOCD_FORMAT = "<4s4H2LH"
67 | EOCD_SIZE = 22
68 | CDIR_SIZE_CORRECTION = 54
69 |
70 | real_seek = fla_file.seek
71 | real_read = fla_file.read
72 |
73 | def fake_seek(self, offset, whence=io.SEEK_SET):
74 | if offset == -EOCD_SIZE and whence == io.SEEK_END:
75 | # Perform the seek and get the zip's total size
76 | zip_size = EOCD_SIZE + real_seek(offset, whence)
77 | eocd_data = self.read()
78 | eocd = list(struct.unpack(EOCD_FORMAT, eocd_data))
79 | cdir_size = eocd[5]
80 | cdir_offset = eocd[6]
81 |
82 | # Assuming the central dir offset is right, is the size wrong?
83 | actual_cdir_size = zip_size - cdir_offset - EOCD_SIZE
84 | delta = cdir_size - actual_cdir_size
85 | if delta == CDIR_SIZE_CORRECTION:
86 | eocd[5] -= CDIR_SIZE_CORRECTION
87 | eocd_data = struct.pack(EOCD_FORMAT, *eocd)
88 | elif delta != 0:
89 | raise Exception(
90 | f"Central directory size is off by an unexpected amount: {delta}"
91 | )
92 |
93 | self.seek = real_seek
94 |
95 | # Fake the next read() to return `eocd_data`
96 | def fake_read(self, size=-1):
97 | if size != -1:
98 | # We expect read() to be called with no arguments
99 | raise Exception(f"Expected size of -1, not {size}")
100 | self.read = real_read
101 | return eocd_data
102 |
103 | self.read = fake_read.__get__(self)
104 | else:
105 | return real_seek(offset, whence)
106 |
107 | # __get__ turns a function into a method: https://stackoverflow.com/a/46757134
108 | fla_file.seek = fake_seek.__get__(fla_file)
109 |
110 | with ZipFile(fla_file, 'r') as file:
111 | file.extractall(folder)
112 |
113 | return XFL.load(folder)
114 |
115 | elif os.path.isdir(projectpath):
116 | document = DOMDocument()
117 | document.load(projectpath)
118 | return document
119 |
120 | raise Exception(f"Project does not exist: {projectpath}")
121 |
122 | @staticmethod
123 | def save(document: DOMDocument):
124 | filepath = document.filepath + ".fla"
125 |
126 | projectpath = document.filepath
127 |
128 | if not os.path.exists(projectpath):
129 | os.mkdir(projectpath)
130 |
131 | document.save()
132 |
133 | with ZipFile(filepath, 'w') as file:
134 | for root, _, files in os.walk(projectpath):
135 | for filename in files:
136 | file.write(os.path.join(root, filename),
137 | os.path.relpath(os.path.join(root, filename), os.path.join(projectpath, '')))
138 |
139 | rmtree(projectpath)
140 |
--------------------------------------------------------------------------------
/lib/fla/dat/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sc-workshop/SC/fe797f56b7fe71196a8673184007e00e3f69be05/lib/fla/dat/__init__.py
--------------------------------------------------------------------------------
/lib/fla/dat/bitmap.py:
--------------------------------------------------------------------------------
1 | from zlib import decompress, compress
2 |
3 | import numpy as np
4 |
5 | from lib.utils import BinaryWriter
6 | from lib.utils import BinaryReader
7 |
8 | from PIL import Image
9 |
10 |
11 | class Bitmap:
12 | @staticmethod
13 | def load(filepath: str):
14 | with open(filepath, 'rb') as file:
15 | content = file.read()
16 |
17 | stream = BinaryReader(content)
18 |
19 | magic = stream.read_short()
20 |
21 | if magic != 1283:
22 | raise Exception(f"Bad \".dat\" file: {filepath}")
23 |
24 | stream.skip(2) # row data length
25 |
26 | width = stream.read_ushort()
27 | height = stream.read_ushort()
28 |
29 | stream.skip(4) # unknown
30 | stream.skip(4) # width in twips
31 |
32 | stream.skip(4) # unknown
33 | stream.skip(4) # height in twips
34 |
35 | flags = stream.read_uchar()
36 | compression = stream.read_bool()
37 |
38 | header = bytes()
39 | if compression:
40 | header_length = stream.read_ushort()
41 | header = stream.read(header_length)
42 |
43 | alpha = (flags & 1) != 0
44 |
45 | image_binary_data = bytes()
46 | while True:
47 | data_block_size = stream.read_ushort()
48 |
49 | if data_block_size == 0:
50 | break
51 |
52 | image_binary_data += stream.read(data_block_size)
53 |
54 | mode = 4 if alpha else 3
55 |
56 | if compression:
57 | image_binary_data = decompress(header + image_binary_data)
58 |
59 | array = np.frombuffer(image_binary_data, np.uint8)
60 | img = Image.fromarray(np.uint8(array))
61 | return img
62 |
63 | @staticmethod
64 | def save(filepath: str, image: Image, compression: bool = True):
65 | if image.mode == "LA":
66 | image = image.convert("RGBA")
67 |
68 | if image.mode == "L":
69 | image = image.convert("RGB")
70 |
71 | width, height = image.size
72 | alpha = image.mode == "RGBA"
73 |
74 | loaded = image.load()
75 | image_binary_data = []
76 |
77 | for y in range(height):
78 | for x in range(width):
79 | pixel = loaded[x, y]
80 |
81 | if alpha:
82 | r, g, b, a = pixel
83 | image_binary_data.append(b << 24 | g << 16 | r << 8 | a)
84 | else:
85 | r, g, b = pixel
86 | image_binary_data.append(b << 24 | g << 16 | r << 8)
87 |
88 | image_binary_data = np.array(image_binary_data, dtype=" None:
12 | # attributes
13 | self.name: str = None
14 | self.library_item_name = library_item_name
15 |
16 | # elements
17 | self.matrix: Matrix = None
18 | self.transformation_point: Point = None
19 |
20 | def load(self, xml: Element):
21 | if "name" in xml.attrib:
22 | self.name = xml.attrib["name"]
23 |
24 | if "libraryItemName" in xml.attrib:
25 | self.library_item_name = xml.attrib["libraryItemName"]
26 |
27 | matrix = xml.find("./xfl:matrix", NAMESPACES)
28 | if matrix is not None:
29 | for matrix_element in matrix:
30 | self.matrix = Matrix()
31 | self.matrix.load(matrix_element)
32 |
33 | transformation_point = xml.find("./xfl:transformationPoint", NAMESPACES)
34 | if transformation_point is not None:
35 | for point_element in transformation_point:
36 | self.transformation_point = Point()
37 | self.transformation_point.load(point_element)
38 |
39 | def save(self):
40 | xml = Element("DOMBitmapInstance")
41 |
42 | if self.name is not None:
43 | xml.attrib["name"] = str(self.name)
44 |
45 | if self.library_item_name is not None:
46 | xml.attrib["libraryItemName"] = str(self.library_item_name)
47 |
48 | if self.matrix is not None:
49 | matrix = SubElement(xml, "matrix")
50 | matrix.append(self.matrix.save())
51 |
52 | if self.transformation_point is not None:
53 | transformation_point = SubElement(xml, "transformationPoint")
54 | transformation_point.append(self.transformation_point.save())
55 |
56 | return xml
57 |
--------------------------------------------------------------------------------
/lib/fla/dom/bitmap_item.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from PIL import Image
4 |
5 |
6 | class DOMBitmapItem:
7 | def __init__(self, name: str = None, bitmap_data_href: str = None) -> None:
8 | self.image: Image = None
9 |
10 | # attributes
11 | self.name = name
12 | self.bitmap_data_href = bitmap_data_href
13 | self.source_external_filepath: str = None
14 | self.quality: int = None
15 | self.use_imported_jpeg_data: bool = None
16 | self.compression_type: str = None
17 | self.allow_smoothing: bool = True
18 |
19 | def load(self, xml: Element):
20 | if "name" in xml.attrib:
21 | self.name = xml.attrib["name"]
22 |
23 | if "bitmapDataHRef" in xml.attrib:
24 | self.bitmap_data_href = xml.attrib["bitmapDataHRef"]
25 |
26 | if "sourceExternalFilepath" in xml.attrib:
27 | self.source_external_filepath = xml.attrib["sourceExternalFilepath"]
28 |
29 | if "quality" in xml.attrib:
30 | self.quality = xml.attrib["quality"]
31 |
32 | if "useImportedJPEGData" in xml.attrib:
33 | self.use_imported_jpeg_data = xml.attrib["useImportedJPEGData"] == "true"
34 |
35 | if "compressionType" in xml.attrib:
36 | self.compression_type = xml.attrib["compressionType"]
37 |
38 | if "allowSmoothing" in xml.attrib:
39 | self.allow_smoothing = xml.attrib["allowSmoothing"] == "true"
40 |
41 | def save(self):
42 | xml = Element("DOMBitmapItem")
43 |
44 | if self.name is not None:
45 | xml.attrib["name"] = str(self.name)
46 |
47 | if self.bitmap_data_href is not None:
48 | xml.attrib["bitmapDataHRef"] = str(self.bitmap_data_href)
49 |
50 | if self.source_external_filepath is not None:
51 | xml.attrib["sourceExternalFilepath"] = str(self.source_external_filepath)
52 |
53 | if self.quality is not None:
54 | xml.attrib["quality"] = str(self.quality)
55 |
56 | if self.use_imported_jpeg_data is not None:
57 | xml.attrib["useImportedJPEGData"] = "true" if self.use_imported_jpeg_data else "false"
58 |
59 | if self.compression_type is not None:
60 | xml.attrib["compressionType"] = str(self.compression_type)
61 |
62 | if self.allow_smoothing:
63 | xml.attrib["allowSmoothing"] = "true" if self.allow_smoothing else "false"
64 |
65 | return xml
66 |
--------------------------------------------------------------------------------
/lib/fla/dom/document.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from lxml.etree import *
4 | from shutil import rmtree
5 |
6 | from PIL import Image
7 |
8 | from .folder_item import DOMFolderItem
9 | from .bitmap_item import DOMBitmapItem
10 | from .symbol_item import DOMSymbolItem
11 | from .timeline import DOMTimeline
12 |
13 | from ..dat.bitmap import Bitmap
14 |
15 | from . import NAMESPACES
16 |
17 | from lib.console import Console
18 |
19 | class folders(list):
20 | def __init__(self, library: str):
21 | self.library = library
22 |
23 | def add(self, folder_item):
24 | if isinstance(folder_item, DOMFolderItem):
25 | os.makedirs(os.path.join(self.library, folder_item.name), exist_ok=True)
26 | self.append(folder_item)
27 |
28 | def delete(self, index):
29 | object = self[index]
30 | rmtree(os.path.join(self.library, object.name))
31 | del self[index]
32 |
33 | class symbols(dict):
34 | def __init__(self, library: str):
35 | self.library = library
36 |
37 | def add(self, key, value):
38 | path = os.path.join(self.library, str(key) + ".xml")
39 | value.save(path)
40 |
41 | self[key] = path
42 |
43 | def get(self, key):
44 | symbol = DOMSymbolItem()
45 | symbol.load(self[key])
46 | return symbol
47 |
48 |
49 | class DOMDocument:
50 | def __init__(self, filepath: str) -> None:
51 | # class fields
52 | self.filepath = filepath
53 |
54 | # attributes
55 | self.xfl_version: float = 2.971
56 | self.creator_info: str = "Generated with XFL Python module by Pavel Sokov (GIHUB: github.com/Fred-31)"
57 |
58 | self.width: int = 1280
59 | self.height: int = 720
60 | self.frame_rate: int = 30
61 |
62 | self.current_timeline: int = 1
63 | self.background_color: int = 0x666666
64 |
65 | # elements
66 | self.folders = folders(self.librarypath)
67 | self.media: dict = {}
68 | self.symbols = symbols(self.librarypath)
69 | self.timelines: list = []
70 |
71 | if not os.path.exists(self.binarypath):
72 | os.mkdir(self.binarypath)
73 |
74 | if not os.path.exists(self.librarypath):
75 | os.mkdir(self.librarypath)
76 |
77 | @property
78 | def librarypath(self):
79 | path = f"{self.filepath}/LIBRARY"
80 | if not os.path.exists(path):
81 | os.makedirs(path)
82 | return path
83 |
84 | @property
85 | def binarypath(self):
86 | path = f"{self.filepath}/bin"
87 | if not os.path.exists(path):
88 | os.makedirs(path)
89 | return path
90 |
91 | def load(self):
92 | parsed = parse(os.path.join(self.filepath, "DOMDocument.xml"))
93 | xml = parsed.getroot()
94 |
95 | if "xflVersion" in xml.attrib:
96 | self.xfl_version = float(xml.attrib["xflVersion"])
97 |
98 | if "creatorInfo" in xml.attrib:
99 | self.creator_info = xml.attrib["creatorInfo"]
100 |
101 | if "width" in xml.attrib:
102 | self.width = int(xml.attrib["width"])
103 |
104 | if "height" in xml.attrib:
105 | self.height = int(xml.attrib["height"])
106 |
107 | if "frameRate" in xml.attrib:
108 | self.frame_rate = int(xml.attrib["frameRate"])
109 |
110 | if "currentTimeline" in xml.attrib:
111 | self.current_timeline = int(xml.attrib["currentTimeline"])
112 |
113 | if "backgroundColor" in xml.attrib:
114 | self.background_color = int(xml.attrib["backgroundColor"].replace("#", "0x"), 0)
115 |
116 | folders = xml.find("./xfl:folders", NAMESPACES)
117 | media = xml.find("./xfl:media", NAMESPACES)
118 | symbols = xml.find("./xfl:symbols", NAMESPACES)
119 | timelines = xml.find("./xfl:timelines", NAMESPACES)
120 |
121 | if folders is not None:
122 | for folder_element in folders:
123 | folder = DOMFolderItem()
124 | folder.load(folder_element)
125 | self.folders.append(folder)
126 |
127 | if media is not None:
128 | for media_element in media:
129 | bitmap = DOMBitmapItem()
130 | bitmap.load(media_element)
131 |
132 | if bitmap.bitmap_data_href is not None:
133 | bitmap.image = Bitmap.load(os.path.join(self.binarypath, bitmap.bitmap_data_href))
134 |
135 | # TODO: external source image loading
136 | if bitmap.source_external_filepath is not None:
137 | bitmap.image = Image.open(os.path.join(self.filepath, os.path.normpath(bitmap.source_external_filepath)))
138 |
139 | self.media[bitmap.name] = bitmap
140 |
141 | if symbols is not None:
142 | for symbol_element in symbols:
143 | symbol = DOMSymbolItem()
144 | symbol.load(os.path.join(self.librarypath, symbol_element.attrib["href"]))
145 | self.symbols[symbol.name] = os.path.join(self.librarypath, symbol_element.attrib["href"])
146 |
147 | if timelines is not None:
148 | for timeline_element in timelines:
149 | timeline = DOMTimeline()
150 | timeline.load(timeline_element)
151 | self.timelines.append(timeline)
152 |
153 | def save(self):
154 | for folder in self.folders:
155 | if folder.name is not None and folder.name != "":
156 | if not os.path.exists(os.path.join(self.librarypath, folder.name)):
157 | os.mkdir(os.path.join(self.librarypath, folder.name))
158 | XSI = "http://www.w3.org/2001/XMLSchema-instance"
159 | xml = Element("DOMDocument", {"xmlns": NAMESPACES["xfl"]}, nsmap={'xsi': NAMESPACES["xsi"]})
160 |
161 | if self.xfl_version is not None:
162 | xml.attrib["xflVersion"] = str(self.xfl_version)
163 |
164 | if self.creator_info is not None and self.creator_info != "":
165 | xml.attrib["creatorInfo"] = str(self.creator_info)
166 |
167 | if self.width is not None:
168 | xml.attrib["width"] = str(self.width)
169 |
170 | if self.height is not None:
171 | xml.attrib["height"] = str(self.height)
172 |
173 | if self.frame_rate is not None:
174 | xml.attrib["frameRate"] = str(self.frame_rate)
175 |
176 | if self.current_timeline is not None:
177 | xml.attrib["currentTimeline"] = str(self.current_timeline)
178 |
179 | if self.background_color is not None:
180 | xml.attrib["backgroundColor"] = "#" + str(hex(self.background_color).lstrip("0x").zfill(6))
181 |
182 | folders = SubElement(xml, "folders")
183 | media = SubElement(xml, "media")
184 | symbols = SubElement(xml, "symbols")
185 | timelines = SubElement(xml, "timelines")
186 |
187 | for folder in self.folders:
188 | if folder.name is not None and folder.name != "":
189 | folders.append(folder.save())
190 |
191 | for i, media_name in enumerate(self.media):
192 | medium = self.media[media_name]
193 | media.append(medium.save())
194 |
195 | # TODO: external source image saving
196 | if medium.source_external_filepath is not None:
197 | medium.image.save(os.path.join(self.filepath, os.path.normpath(medium.source_external_filepath)), "PNG")
198 |
199 | if medium.image is not None:
200 | Bitmap.save(os.path.join(self.binarypath, medium.bitmap_data_href), medium.image)
201 |
202 | Console.progress_bar("Adobe binary images saving...", i, len(self.media))
203 | print()
204 |
205 | for symbol_name, symbol in self.symbols.items():
206 | include = Element("Include")
207 | include.attrib["href"] = str(symbol_name) + ".xml"
208 |
209 | symbols.append(include)
210 |
211 | for timeline in self.timelines:
212 | timelines.append(timeline.save())
213 |
214 | ElementTree(xml).write(os.path.join(self.filepath, "DOMDocument.xml"))
215 |
216 | with open(os.path.join(self.filepath, os.path.basename(self.filepath) + ".xfl"), 'w') as file:
217 | file.write("PROXY-CS5")
218 |
--------------------------------------------------------------------------------
/lib/fla/dom/dynamic_text.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from .text_run import DOMTextRun
4 |
5 | from ..filter.glow_filter import GlowFilter
6 | from ..filter.drop_shadow_filter import DrowShadowFilter
7 |
8 | from ..geom.matrix import Matrix
9 | from ..geom.color import Color
10 |
11 | from . import NAMESPACES
12 |
13 |
14 | class DOMDynamicText:
15 | def __init__(self, name: str = None) -> None:
16 | # attributes
17 | self.name = name
18 |
19 | self.line_type: str = None
20 |
21 | self.width: float = None
22 | self.height: float = None
23 | self.top: float = 0.0
24 | self.left: float = 0.0
25 |
26 | self.is_selectable: bool = None
27 |
28 | # elements
29 | self.text_runs: list = []
30 |
31 | self.matrix: Matrix = None
32 | self.color: Color = None
33 |
34 | self.filters: list = []
35 |
36 | def load(self, xml: Element):
37 | if "name" in xml.attrib:
38 | self.name = xml.attrib["name"]
39 |
40 | if "width" in xml.attrib:
41 | self.width = float(xml.attrib["width"])
42 |
43 | if "height" in xml.attrib:
44 | self.height = float(xml.attrib["height"])
45 |
46 | if "isSelectable" in xml.attrib:
47 | self.is_selectable = xml.attrib["isSelectable"] == "true"
48 |
49 | if "lineType" in xml.attrib:
50 | self.line_type = xml.attrib["lineType"]
51 |
52 | text_runs = xml.find("./xfl:textRuns", NAMESPACES)
53 | if text_runs is not None:
54 | for text_run_element in text_runs:
55 | text_run = DOMTextRun()
56 | text_run.load(text_run_element)
57 | self.text_runs.append(text_run)
58 |
59 | filters = xml.find("./xfl:filters", NAMESPACES)
60 | if filters is not None:
61 | for filter in filters:
62 | if filter.tag.startswith("GlowFilter"):
63 | glow_filter = GlowFilter()
64 | glow_filter.load(filter)
65 | self.filters.append(glow_filter)
66 |
67 | elif filter.tag.startswith("DrowShadowFilter"):
68 | shadow_filter = DrowShadowFilter()
69 | shadow_filter.load(filter)
70 | self.filters.append(shadow_filter)
71 |
72 | matrix = xml.find("./xfl:matrix", NAMESPACES)
73 | if matrix is not None:
74 | for matrix_element in matrix:
75 | self.matrix = Matrix()
76 | self.matrix.load(matrix_element)
77 |
78 | color = xml.find("./xfl:color", NAMESPACES)
79 | if color is not None:
80 | for color_element in color:
81 | self.color = Color()
82 | self.color.load(color_element)
83 |
84 | if "top" in xml.attrib:
85 | self.top = float(xml.attrib["top"])
86 |
87 | if "left" in xml.attrib:
88 | self.left = float(xml.attrib["left"])
89 |
90 | def save(self):
91 | xml = Element("DOMDynamicText")
92 |
93 | if self.name is not None:
94 | xml.attrib["name"] = str(self.name)
95 |
96 | if self.width is not None:
97 | xml.attrib["width"] = str(self.width)
98 |
99 | if self.height is not None:
100 | xml.attrib["height"] = str(self.height)
101 |
102 | if self.is_selectable is not None:
103 | xml.attrib["isSelectable"] = "true" if self.is_selectable else "false"
104 |
105 | text_runs = SubElement(xml, "textRuns")
106 | for text_run in self.text_runs:
107 | text_runs.append(text_run.save())
108 |
109 | if self.filters:
110 | filters = SubElement(xml, "filters")
111 | for filter in self.filters:
112 | filters.append(filter.save())
113 |
114 | if self.matrix is not None:
115 | matrix = SubElement(xml, "matrix")
116 | matrix.append(self.matrix.save())
117 |
118 | if self.color is not None:
119 | color = SubElement(xml, "color")
120 | color.append(self.color.save())
121 |
122 | if self.top:
123 | xml.attrib["top"] = str(self.top)
124 |
125 | if self.left:
126 | xml.attrib["left"] = str(self.left)
127 |
128 | return xml
129 |
--------------------------------------------------------------------------------
/lib/fla/dom/folder_item.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 |
4 | class DOMFolderItem:
5 | def __init__(self, name: str = None) -> None:
6 | # attributes
7 | self.name = name
8 | self.item_id: str = None
9 | self.is_expanded: bool = False
10 |
11 | def load(self, xml: Element):
12 | if "name" in xml.attrib:
13 | self.name = xml.attrib["name"]
14 |
15 | if "itemID" in xml.attrib:
16 | self.item_id = xml.attrib["itemID"]
17 |
18 | if "isExpanded" in xml.attrib:
19 | self.is_expanded = xml.attrib["isExpanded"] == "true"
20 |
21 | def save(self):
22 | xml = Element("DOMFolderItem")
23 |
24 | if self.name is not None:
25 | xml.attrib["name"] = str(self.name)
26 |
27 | if self.item_id is not None:
28 | xml.attrib["itemID"] = str(self.item_id)
29 |
30 | if self.is_expanded is not None:
31 | xml.attrib["isExpanded"] = "true" if self.is_expanded else "false"
32 |
33 | return xml
34 |
--------------------------------------------------------------------------------
/lib/fla/dom/frame.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from enum import Enum
4 |
5 | from . import NAMESPACES
6 |
7 | from .bitmap_instance import DOMBitmapInstance
8 | from .symbol_instance import DOMSymbolInstance
9 | from .shape import DOMShape
10 | from .group import DOMGroup
11 | from .static_text import DOMStaticText
12 | from .dynamic_text import DOMDynamicText
13 | from ..geom.color import Color
14 |
15 |
16 | class KeyMode(Enum):
17 | KEY_MODE_NORMAL = 9728
18 | KEY_MODE_CLASSIC_TWEEN = 22017
19 | KEY_MODE_SHAPE_TWEEN = 17922
20 | KEY_MODE_MOTION_TWEEN = 8195
21 | KEY_MODE_SHAPE_LAYERS = 8192
22 |
23 |
24 | class DOMFrame:
25 | def __init__(self, index: int = None, duration: int = 1, name: str = None, label_type: str = None, key_mode: int = None) -> None:
26 | # attributes
27 | self.name = name
28 | self.label_type = label_type
29 |
30 | self.index = index
31 | self.duration = duration
32 |
33 | self.key_mode = key_mode
34 | self.blend_mode: str = None
35 |
36 | self.tween_type: str = None
37 |
38 | # self.motion_object = None # TODO: motion objects and tweens
39 |
40 | # elements
41 | self.elements: list = []
42 | self.script: str = None
43 |
44 | self.frame_color: Color = None
45 |
46 | def load(self, xml: Element):
47 | if "name" in xml.attrib:
48 | self.name = xml.attrib["name"]
49 |
50 | if "labelType" in xml.attrib:
51 | self.label_type = xml.attrib["labelType"]
52 |
53 | if "index" in xml.attrib:
54 | self.index = int(xml.attrib["index"])
55 |
56 | if "duration" in xml.attrib:
57 | self.duration = int(xml.attrib["duration"])
58 |
59 | if "keyMode" in xml.attrib:
60 | self.key_mode = int(xml.attrib["keyMode"])
61 |
62 | if "blendMode" in xml.attrib:
63 | self.blend_mode = xml.attrib["blendMode"]
64 |
65 | if "tweenType" in xml.attrib:
66 | self.tween_type = xml.attrib["tweenType"]
67 |
68 | script = xml.find("./xfl:Actionscript", NAMESPACES)
69 |
70 | if script is not None:
71 | for element in script:
72 | if element.tag == "script":
73 | if str(element.text).startswith("![CDATA["):
74 | self.script = element.text[7:len(element.text) - 2]
75 |
76 | elements = xml.find("./xfl:elements", NAMESPACES)
77 |
78 | if elements is not None:
79 | for element in elements:
80 | if element.tag.endswith("DOMBitmapInstance"):
81 | bitmap_instance = DOMBitmapInstance()
82 | bitmap_instance.load(element)
83 | self.elements.append(bitmap_instance)
84 |
85 | elif element.tag.endswith("DOMSymbolInstance"):
86 | symbol_instance = DOMSymbolInstance()
87 | symbol_instance.load(element)
88 | self.elements.append(symbol_instance)
89 |
90 | elif element.tag.endswith("DOMShape"):
91 | shape = DOMShape()
92 | shape.load(element)
93 | self.elements.append(shape)
94 |
95 | elif element.tag.endswith("DOMStaticText"):
96 | static_text = DOMStaticText()
97 | static_text.load(element)
98 | self.elements.append(static_text)
99 |
100 | elif element.tag.endswith("DOMDynamicText"):
101 | dynamic_text = DOMDynamicText()
102 | dynamic_text.load(element)
103 | self.elements.append(dynamic_text)
104 |
105 | elif element.tag.endswith("DOMGroup"):
106 | group = DOMGroup()
107 | group.load(element)
108 | self.elements.append(group)
109 |
110 | self.frame_color = xml.find("./xfl:frameColor", NAMESPACES)
111 | if self.frame_color is not None:
112 | for color_element in self.frame_color:
113 | self.color = Color()
114 | self.color.load(color_element)
115 |
116 | def save(self):
117 | xml = Element("DOMFrame")
118 |
119 | if self.name is not None:
120 | xml.attrib["name"] = str(self.name)
121 |
122 | if self.label_type is not None:
123 | xml.attrib["labelType"] = str(self.label_type)
124 |
125 | if self.index is not None:
126 | xml.attrib["index"] = str(self.index)
127 |
128 | if self.duration != 1:
129 | xml.attrib["duration"] = str(self.duration)
130 |
131 | if self.key_mode is not None:
132 | xml.attrib["keyMode"] = str(self.key_mode)
133 |
134 | if self.blend_mode is not None:
135 | xml.attrib["blendMode"] = str(self.blend_mode)
136 |
137 | if self.tween_type is not None:
138 | xml.attrib["tweenType"] = str(self.tween_type)
139 |
140 | if self.script is not None:
141 | action_script = SubElement(xml, "Actionscript")
142 | script = SubElement(action_script, "script")
143 | script.text = self.script
144 |
145 | elements = SubElement(xml, "elements")
146 | for element in self.elements:
147 | elements.append(element.save())
148 |
149 | return xml
--------------------------------------------------------------------------------
/lib/fla/dom/group.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from .bitmap_instance import DOMBitmapInstance
4 | from .symbol_instance import DOMSymbolInstance
5 | from .shape import DOMShape
6 | from .static_text import DOMStaticText
7 | from .dynamic_text import DOMDynamicText
8 |
9 | from ..geom.matrix import Matrix
10 |
11 | from . import NAMESPACES
12 |
13 |
14 | class DOMGroup:
15 | def __init__(self):
16 | # elements
17 | self.members: list = []
18 | self.matrix: Matrix = None
19 |
20 | def load(self, xml: Element):
21 | matrix = xml.find("./xfl:matrix", NAMESPACES)
22 | if matrix is not None:
23 | for matrix_element in matrix:
24 | self.matrix = Matrix()
25 | self.matrix.load(matrix_element)
26 |
27 | for member in xml.find("./xfl:members", NAMESPACES):
28 | if member.tag.endswith("DOMBitmapInstance"):
29 | bitmap_instance = DOMBitmapInstance()
30 | bitmap_instance.load(member)
31 | self.members.append(bitmap_instance)
32 |
33 | elif member.tag.endswith("DOMSymbolInstance"):
34 | symbol_instance = DOMSymbolInstance()
35 | symbol_instance.load(member)
36 | self.members.append(symbol_instance)
37 |
38 | elif member.tag.endswith("DOMShape"):
39 | shape = DOMShape()
40 | shape.load(member)
41 | self.members.append(shape)
42 |
43 | elif member.tag.endswith("DOMStaticText"):
44 | static_text = DOMStaticText()
45 | static_text.load(member)
46 | self.members.append(static_text)
47 |
48 | elif member.tag.endswith("DOMDynamicText"):
49 | dynamic_text = DOMDynamicText()
50 | dynamic_text.load(member)
51 | self.members.append(dynamic_text)
52 |
53 | elif member.tag.endswith("DOMGroup"):
54 | group = DOMGroup()
55 | group.load(member)
56 | self.members.append(group)
57 |
58 | def save(self):
59 | xml = Element("DOMGroup")
60 |
61 | if self.matrix is not None:
62 | matrix = SubElement(xml, "matrix")
63 | matrix.append(self.matrix.save())
64 |
65 | members = SubElement(xml, "members")
66 | for member in self.members:
67 | members.append(member.save())
68 |
69 | return xml
70 |
--------------------------------------------------------------------------------
/lib/fla/dom/layer.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from . import NAMESPACES
4 | from .frame import DOMFrame
5 |
6 |
7 | class DOMLayer:
8 | def __init__(self, name: str = None, auto_named: bool = None, color: int = None, layer_type: str = None, parent_layer_index: int = None, current: bool = None) -> None:
9 | # attributes
10 | self.name = name
11 | self.auto_named = auto_named
12 |
13 | self.color = color
14 |
15 | self.layer_type = layer_type
16 | self.parent_layer_index = parent_layer_index
17 |
18 | self.current = current
19 | self.is_selected: bool = None
20 | self.is_locked: bool = None
21 |
22 | self.animation_type: str = None
23 |
24 | # elements
25 | self.frames: list = []
26 |
27 | def load(self, xml: Element):
28 | if "name" in xml.attrib:
29 | self.name = xml.attrib["name"]
30 |
31 | if "autoNamed" in xml.attrib:
32 | self.auto_named = xml.attrib["autoNamed"] == "true"
33 |
34 | if "color" in xml.attrib:
35 | self.color = int(xml.attrib["color"].replace("#", "0x"), 0)
36 |
37 | if "layerType" in xml.attrib:
38 | self.layer_type = xml.attrib["layerType"]
39 |
40 | if "parentLayerIndex" in xml.attrib:
41 | self.parent_layer_index = int(xml.attrib["parentLayerIndex"])
42 |
43 | if "current" in xml.attrib:
44 | self.current = xml.attrib["current"] == "true"
45 |
46 | if "isSelected" in xml.attrib:
47 | self.is_selected = xml.attrib["isSelected"] == "true"
48 |
49 | if "locked" in xml.attrib:
50 | self.is_locked = xml.attrib["locked"] == "true"
51 |
52 | if "animationType" in xml.attrib:
53 | self.animation_type = xml.attrib["animationType"]
54 |
55 | frames = xml.find("./xfl:frames", NAMESPACES)
56 | if frames is not None:
57 | for frame_element in frames:
58 | frame = DOMFrame()
59 | frame.load(frame_element)
60 | self.frames.append(frame)
61 |
62 | def save(self):
63 | xml = Element("DOMLayer")
64 |
65 | if self.name is not None:
66 | xml.attrib["name"] = str(self.name)
67 |
68 | if self.auto_named is not None:
69 | xml.attrib["autoNamed"] = "true" if self.auto_named else "false"
70 |
71 | if self.color is not None:
72 | xml.attrib["color"] = "#" + str(hex(self.color).lstrip("0x").zfill(6))
73 |
74 | if self.layer_type is not None:
75 | xml.attrib["layerType"] = str(self.layer_type)
76 |
77 | if self.parent_layer_index is not None:
78 | xml.attrib["parentLayerIndex"] = str(self.parent_layer_index)
79 |
80 | if self.current is not None:
81 | xml.attrib["current"] = "true" if self.current else "false"
82 |
83 | if self.is_selected is not None:
84 | xml.attrib["isSelected"] = "true" if self.is_selected else "false"
85 |
86 | if self.is_locked is not None:
87 | xml.attrib["locked"] = "true" if self.is_locked else "false"
88 |
89 | if self.animation_type is not None:
90 | xml.attrib["animationType"] = str(self.animation_type)
91 |
92 | frames = SubElement(xml, "frames")
93 | for frame in self.frames:
94 | frames.append(frame.save())
95 |
96 | return xml
97 |
--------------------------------------------------------------------------------
/lib/fla/dom/shape.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from ..edge.edge import Edge
4 | from ..fill.fill_style import FillStyle
5 | from ..stroke.stroke_style import StrokeStyle
6 |
7 | from ..geom.matrix import Matrix
8 |
9 | from . import NAMESPACES
10 |
11 |
12 | class DOMShape:
13 | def __init__(self) -> None:
14 | # attributes
15 | self.is_drawing_object: bool = False
16 |
17 | # elements
18 | self.edges: list = []
19 | self.fills: list = []
20 | self.strokes: list = []
21 | self.matrix: Matrix = None
22 |
23 | def load(self, xml: Element):
24 | if "isDrawingObject" in xml.attrib:
25 | self.is_drawing_object = xml.attrib["isDrawingObject"] == "true"
26 |
27 | fills = xml.find("./xfl:fills", NAMESPACES)
28 | strokes = xml.find("./xfl:strokes", NAMESPACES)
29 | edges = xml.find("./xfl:edges", NAMESPACES)
30 |
31 | matrix = xml.find("./xfl:matrix", NAMESPACES)
32 | if matrix is not None:
33 | for matrix_element in matrix:
34 | self.matrix = Matrix()
35 | self.matrix.load(matrix_element)
36 |
37 | if fills is not None:
38 | for fill_element in fills:
39 | fill = FillStyle()
40 | fill.load(fill_element)
41 | self.fills.append(fill)
42 |
43 | if strokes is not None:
44 | for stroke_element in strokes:
45 | stroke = StrokeStyle()
46 | stroke.load(stroke_element)
47 | self.strokes.append(stroke)
48 |
49 | if edges is not None:
50 | for edge_element in edges:
51 | edge = Edge()
52 | edge.load(edge_element)
53 |
54 | if edge.edges is not None and edge.edges != "":
55 | self.edges.append(edge)
56 |
57 | def save(self):
58 | xml = Element("DOMShape")
59 |
60 | if self.is_drawing_object:
61 | xml.attrib["isDrawingObject"] = str(self.is_drawing_object).lower()
62 |
63 | fills = SubElement(xml, "fills")
64 | strokes = SubElement(xml, "strokes")
65 | edges = SubElement(xml, "edges")
66 |
67 | if self.matrix is not None:
68 | matrix = SubElement(xml, "matrix")
69 | matrix.append(self.matrix.save())
70 |
71 | for fill in self.fills:
72 | fills.append(fill.save())
73 |
74 | for stroke in self.strokes:
75 | strokes.append(stroke.save())
76 |
77 | for edge in self.edges:
78 | edges.append(edge.save())
79 |
80 | return xml
81 |
--------------------------------------------------------------------------------
/lib/fla/dom/static_text.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from .text_run import DOMTextRun
4 |
5 | from ..filter.glow_filter import GlowFilter
6 | from ..filter.drop_shadow_filter import DrowShadowFilter
7 |
8 | from ..geom.matrix import Matrix
9 | from ..geom.color import Color
10 |
11 | from . import NAMESPACES
12 |
13 |
14 | class DOMStaticText:
15 | def __init__(self) -> None:
16 | # attributes
17 | self.width: float = None
18 | self.height: float = None
19 |
20 | self.is_selectable: bool = None
21 |
22 | # elements
23 | self.text_runs: list = []
24 |
25 | self.filters: list = []
26 |
27 | self.matrix: Matrix = None
28 | self.color: Color = None
29 |
30 | def load(self, xml: Element):
31 | if "width" in xml.attrib:
32 | self.width = float(xml.attrib["width"])
33 |
34 | if "height" in xml.attrib:
35 | self.height = float(xml.attrib["height"])
36 |
37 | if "isSelectable" in xml.attrib:
38 | self.is_selectable = xml.attrib["isSelectable"] == "true"
39 |
40 | text_runs = xml.find("./xfl:textRuns", NAMESPACES)
41 | if text_runs is not None:
42 | for text_run_element in text_runs:
43 | text_run = DOMTextRun()
44 | text_run.load(text_run_element)
45 | self.text_runs.append(text_run)
46 |
47 | filters = xml.find("./xfl:filters", NAMESPACES)
48 | if filters is not None:
49 | for filter in filters:
50 | if filter.tag.startswith("GlowFilter"):
51 | glow_filter = GlowFilter()
52 | glow_filter.load(filter)
53 | self.filters.append(glow_filter)
54 |
55 | elif filter.tag.startswith("DrowShadowFilter"):
56 | shadow_filter = DrowShadowFilter()
57 | shadow_filter.load(filter)
58 | self.filters.append(shadow_filter)
59 |
60 | matrix = xml.find("./xfl:matrix", NAMESPACES)
61 | if matrix is not None:
62 | for matrix_element in matrix:
63 | self.matrix = Matrix()
64 | self.matrix.load(matrix_element)
65 |
66 | color = xml.find("./xfl:color", NAMESPACES)
67 | if color is not None:
68 | for color_element in color:
69 | self.color = Color()
70 | self.color.load(color_element)
71 |
72 | def save(self):
73 | xml = Element("DOMStaticText")
74 |
75 | if self.width is not None:
76 | xml.attrib["width"] = str(self.width)
77 |
78 | if self.height is not None:
79 | xml.attrib["height"] = str(self.height)
80 |
81 | if self.is_selectable is not None:
82 | xml.attrib["isSelectable"] = "true" if self.is_selectable else "false"
83 |
84 | text_runs = SubElement(xml, "textRuns")
85 | for text_run in self.text_runs:
86 | text_runs.append(text_run.save())
87 |
88 | if self.filters:
89 | filters = SubElement(xml, "filters")
90 | for filter in self.filters:
91 | filters.append(filter.save())
92 |
93 | if self.matrix is not None:
94 | matrix = SubElement(xml, "matrix")
95 | matrix.append(self.matrix.save())
96 |
97 | if self.color is not None:
98 | color = SubElement(xml, "color")
99 | color.append(self.color.save())
100 |
101 | return xml
102 |
--------------------------------------------------------------------------------
/lib/fla/dom/symbol_instance.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from ..geom.matrix import Matrix
4 | from ..geom.color import Color
5 | from ..geom.point import Point
6 |
7 | from . import NAMESPACES
8 |
9 |
10 | class DOMSymbolInstance:
11 | def __init__(self, name: str = None, library_item_name: str = None, loop: str = None) -> None:
12 | # attributes
13 | self.name = name
14 | self.library_item_name = library_item_name
15 | self.blend_mode: str = None
16 | self.type: str = None
17 |
18 | self.loop = loop
19 |
20 | # elements
21 | self.matrix: Matrix = None
22 | self.color: Color = None
23 | self.transformation_point: Point = None
24 |
25 | def load(self, xml: Element):
26 | if "name" in xml.attrib:
27 | self.name = xml.attrib["name"]
28 |
29 | if "libraryItemName" in xml.attrib:
30 | self.library_item_name = xml.attrib["libraryItemName"]
31 |
32 | if "blendMode" in xml.attrib:
33 | self.blend_mode = xml.attrib["blendMode"]
34 |
35 | if "loop" in xml.attrib:
36 | self.loop = xml.attrib["loop"]
37 |
38 | if "symbolType" in xml.attrib:
39 | self.type = xml.attrib["symbolType"]
40 |
41 | matrix = xml.find("./xfl:matrix", NAMESPACES)
42 | if matrix is not None:
43 | for matrix_element in matrix:
44 | self.matrix = Matrix()
45 | self.matrix.load(matrix_element)
46 |
47 | color = xml.find("./xfl:color", NAMESPACES)
48 | if color is not None:
49 | for color_element in color:
50 | self.color = Color()
51 | self.color.load(color_element)
52 |
53 | transformation_point = xml.find("./xfl:transformationPoint", NAMESPACES)
54 | if transformation_point is not None:
55 | for point_element in transformation_point:
56 | self.transformation_point = Point()
57 | self.transformation_point.load(point_element)
58 |
59 | def save(self):
60 | xml = Element("DOMSymbolInstance")
61 |
62 | if self.name is not None:
63 | xml.attrib["name"] = str(self.name)
64 |
65 | if self.library_item_name is not None:
66 | xml.attrib["libraryItemName"] = str(self.library_item_name)
67 |
68 | if self.blend_mode is not None:
69 | xml.attrib["blendMode"] = str(self.blend_mode)
70 |
71 | if self.loop is not None:
72 | xml.attrib["loop"] = str(self.loop)
73 |
74 | if self.type is not None:
75 | xml.attrib["symbolType"] = str(self.type)
76 |
77 | if self.matrix is not None:
78 | matrix = SubElement(xml, "matrix")
79 | matrix.append(self.matrix.save())
80 |
81 | if self.color is not None:
82 | color = SubElement(xml, "color")
83 | color.append(self.color.save())
84 |
85 | if self.transformation_point is not None:
86 | transformation_point = SubElement(xml, "transformationPoint")
87 | transformation_point.append(self.transformation_point.save())
88 |
89 | return xml
90 |
--------------------------------------------------------------------------------
/lib/fla/dom/symbol_item.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from . import NAMESPACES
4 | from .timeline import DOMTimeline
5 |
6 |
7 | class DOMSymbolItem:
8 | def __init__(self, name: str = None, symbol_type: str = None) -> None:
9 | # attributes
10 | self.name = name
11 | self.item_id: str = None
12 | self.symbol_type = symbol_type
13 |
14 | self.scale_grid_left: float = None
15 | self.scale_grid_top: float = None
16 | self.scale_grid_right: float = None
17 | self.scale_grid_bottom: float = None
18 |
19 | # elements
20 | self.timeline: DOMTimeline = DOMTimeline()
21 |
22 | def load(self, filepath: str):
23 | parsed = parse(filepath)
24 | xml = parsed.getroot()
25 |
26 | if "name" in xml.attrib:
27 | self.name = xml.attrib["name"]
28 |
29 | if "itemID" in xml.attrib:
30 | self.item_id = xml.attrib["itemID"]
31 |
32 | if "symbolType" in xml.attrib:
33 | self.symbol_type = xml.attrib["symbolType"]
34 |
35 | if "scaleGridLeft" in xml.attrib:
36 | self.scale_grid_left = float(xml.attrib["scaleGridLeft"])
37 |
38 | if "scaleGridTop" in xml.attrib:
39 | self.scale_grid_top = float(xml.attrib["scaleGridTop"])
40 |
41 | if "scaleGridRight" in xml.attrib:
42 | self.scale_grid_right = float(xml.attrib["scaleGridRight"])
43 |
44 | if "scaleGridBottom" in xml.attrib:
45 | self.scale_grid_bottom = float(xml.attrib["scaleGridBottom"])
46 |
47 | timelines = xml.find("./xfl:timeline", NAMESPACES)
48 | if timelines is not None:
49 | for timeline in timelines:
50 | self.timeline = DOMTimeline()
51 | self.timeline.load(timeline)
52 |
53 | def save(self, filepath: str):
54 | xml = Element("DOMSymbolItem", {"xmlns": NAMESPACES["xfl"]}, nsmap={'xsi': NAMESPACES["xsi"]})
55 |
56 | if self.name is not None:
57 | xml.attrib["name"] = str(self.name)
58 |
59 | if self.item_id is not None:
60 | xml.attrib["itemID"] = str(self.item_id)
61 |
62 | if self.symbol_type is not None:
63 | xml.attrib["symbolType"] = str(self.symbol_type)
64 |
65 | if self.scale_grid_left is not None:
66 | xml.attrib["scaleGridLeft"] = str(self.scale_grid_left)
67 |
68 | if self.scale_grid_top is not None:
69 | xml.attrib["scaleGridTop"] = str(self.scale_grid_top)
70 |
71 | if self.scale_grid_right is not None:
72 | xml.attrib["scaleGridRight"] = str(self.scale_grid_right)
73 |
74 | if self.scale_grid_bottom is not None:
75 | xml.attrib["scaleGridBottom"] = str(self.scale_grid_bottom)
76 |
77 | timeline = SubElement(xml, "timeline")
78 | if self.timeline is not None:
79 | timeline.append(self.timeline.save())
80 |
81 |
82 | ElementTree(xml).write(filepath, pretty_print=True)
83 |
--------------------------------------------------------------------------------
/lib/fla/dom/text_attrs.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 |
4 | class DOMTextAttrs:
5 | def __init__(self) -> None:
6 | # attributes
7 | self.face: str = None
8 |
9 | self.size: float = 0
10 | self.bitmap_size: int = 0
11 |
12 | self.left_margin: float = 0
13 | self.right_margin: float = 0
14 |
15 | self.indent: float = 0.0
16 | self.line_spacing: float = 0.0
17 | self.letter_spacing: int = 0
18 | self.line_height: float = 0.0
19 |
20 | self.alias_text: bool = False
21 | self.auto_kern: bool = True
22 |
23 | self.alignment: str = None
24 |
25 | self.fill_color: int = 0x000000
26 | self.alpha: float = 1
27 |
28 | def load(self, xml: Element):
29 | if "face" in xml.attrib:
30 | self.face = xml.attrib["face"]
31 |
32 | if "size" in xml.attrib:
33 | self.size = float(xml.attrib["size"])
34 |
35 | if "bitmapSize" in xml.attrib:
36 | self.bitmap_size = int(xml.attrib["bitmapSize"])
37 |
38 | if "leftMargin" in xml.attrib:
39 | self.left_margin = float(xml.attrib["leftMargin"])
40 |
41 | if "rightMargin" in xml.attrib:
42 | self.right_margin = float(xml.attrib["rightMargin"])
43 |
44 | if "aliasText" in xml.attrib:
45 | self.alias_text = xml.attrib["aliasText"] == "true"
46 |
47 | if "alignment" in xml.attrib:
48 | self.alignment = xml.attrib["alignment"]
49 |
50 | if "fillColor" in xml.attrib:
51 | self.fill_color = int(xml.attrib["fillColor"].replace("#", "0x"), 0)
52 |
53 | if "alpha" in xml.attrib:
54 | self.alpha = float(xml.attrib["alpha"])
55 | def save(self):
56 | xml = Element("DOMTextAttrs")
57 |
58 | if self.face is not None and self.face != "":
59 | xml.attrib["face"] = str(self.face)
60 |
61 | if self.size is not None:
62 | xml.attrib["size"] = str(self.size)
63 |
64 | if self.bitmap_size is not None:
65 | xml.attrib["bitmapSize"] = str(self.bitmap_size)
66 |
67 | if self.left_margin is not None:
68 | xml.attrib["leftMargin"] = str(self.left_margin)
69 |
70 | if self.right_margin is not None:
71 | xml.attrib["rightMargin"] = str(self.right_margin)
72 |
73 | if self.alias_text is not None:
74 | xml.attrib["aliasText"] = "true" if self.alias_text else "false"
75 |
76 | if self.alignment is not None:
77 | xml.attrib["alignment"] = str(self.alignment)
78 |
79 | if self.fill_color is not None:
80 | xml.attrib["fillColor"] = "#" + str(hex(self.fill_color).lstrip("0x").zfill(6))
81 |
82 | if self.alpha is not None:
83 | xml.attrib["alpha"] = str(self.alpha)
84 |
85 | return xml
86 |
--------------------------------------------------------------------------------
/lib/fla/dom/text_run.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from .text_attrs import DOMTextAttrs
4 |
5 | from . import NAMESPACES
6 |
7 |
8 | class DOMTextRun:
9 | def __init__(self, characters: str = None) -> None:
10 | # elements
11 | self.characters = characters
12 | self.text_attrs: list = []
13 |
14 | def load(self, xml: Element):
15 | characters = xml.find("./xfl:characters", NAMESPACES)
16 | if characters is not None:
17 | self.characters = characters.text
18 |
19 | text_attrs = xml.find("./xfl:textAttrs", NAMESPACES)
20 | if text_attrs is not None:
21 | for text_attr_element in text_attrs:
22 | text_attr = DOMTextAttrs()
23 | text_attr.load(text_attr_element)
24 | self.text_attrs.append(text_attr)
25 |
26 | def save(self):
27 | xml = Element("DOMTextRun")
28 |
29 | if self.characters is not None and self.characters != "":
30 | SubElement(xml, "characters").text = str(self.characters)
31 |
32 | text_attrs = SubElement(xml, "textAttrs")
33 | for text_attr in self.text_attrs:
34 | text_attrs.append(text_attr.save())
35 |
36 | return xml
37 |
--------------------------------------------------------------------------------
/lib/fla/dom/timeline.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from . import NAMESPACES
4 | from .layer import DOMLayer
5 |
6 |
7 | class DOMTimeline:
8 | def __init__(self, name: str = None) -> None:
9 | # attributes
10 | self.name = name
11 |
12 | # elements
13 | self.layers: list = []
14 |
15 | def load(self, xml: Element):
16 | if "name" in xml.attrib:
17 | self.name = xml.attrib["name"]
18 |
19 | layers = xml.find("./xfl:layers", NAMESPACES)
20 | if layers is not None:
21 | for layer_element in layers:
22 | layer = DOMLayer()
23 | layer.load(layer_element)
24 | self.layers.append(layer)
25 |
26 | def save(self):
27 | xml = Element("DOMTimeline")
28 |
29 | if self.name is not None:
30 | xml.attrib["name"] = str(self.name)
31 |
32 | layers = SubElement(xml, "layers")
33 | for layer in self.layers:
34 | layers.append(layer.save())
35 |
36 | return xml
37 |
--------------------------------------------------------------------------------
/lib/fla/edge/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sc-workshop/SC/fe797f56b7fe71196a8673184007e00e3f69be05/lib/fla/edge/__init__.py
--------------------------------------------------------------------------------
/lib/fla/edge/edge.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 |
4 | class Edge:
5 | def __init__(self) -> None:
6 | # attributes
7 | self.edges: str = None # TODO: abstract it to draw commands
8 | self.fill_style0: int = None
9 | self.fill_style1: int = None
10 | self.stroke_style: int = None
11 |
12 | def load(self, xml: Element):
13 | if "edges" in xml.attrib:
14 | self.edges = xml.attrib["edges"]
15 |
16 | if "fillStyle0" in xml.attrib:
17 | self.fill_style0 = int(xml.attrib["fillStyle0"])
18 |
19 | if "fillStyle1" in xml.attrib:
20 | self.fill_style1 = int(xml.attrib["fillStyle1"])
21 |
22 | if "strokeStyle" in xml.attrib:
23 | self.stroke_style = int(xml.attrib["strokeStyle"])
24 |
25 | def save(self):
26 | xml = Element("Edge")
27 |
28 | if self.edges is not None and self.edges != "":
29 | xml.attrib["edges"] = str(self.edges)
30 |
31 | if self.fill_style0 is not None:
32 | xml.attrib["fillStyle0"] = str(self.fill_style0)
33 |
34 | if self.fill_style1 is not None:
35 | xml.attrib["fillStyle1"] = str(self.fill_style1)
36 |
37 | if self.stroke_style is not None:
38 | xml.attrib["strokeStyle"] = str(self.stroke_style)
39 |
40 | return xml
41 |
--------------------------------------------------------------------------------
/lib/fla/fill/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sc-workshop/SC/fe797f56b7fe71196a8673184007e00e3f69be05/lib/fla/fill/__init__.py
--------------------------------------------------------------------------------
/lib/fla/fill/bitmap_fill.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 | from ..geom.matrix import Matrix
3 |
4 | from ..dom import NAMESPACES
5 |
6 |
7 | class BitmapFill:
8 | def __init__(self, path: str = None) -> None:
9 | # attributes
10 | self.path = path
11 | self.matrix: Matrix = None
12 |
13 | def load(self, xml: Element):
14 | if "bitmapPath" in xml.attrib:
15 | self.path = xml.attrib["bitmapPath"]
16 |
17 | matrix = xml.find("./xfl:matrix", NAMESPACES)
18 | if matrix is not None:
19 | for matrix_element in matrix:
20 | self.matrix = Matrix()
21 | self.matrix.load(matrix_element)
22 |
23 | def save(self):
24 | xml = Element("BitmapFill")
25 |
26 | if self.path is not None:
27 | xml.attrib["bitmapPath"] = str(self.path)
28 |
29 | if self.matrix is not None:
30 | matrix = SubElement(xml, "matrix")
31 | matrix.append(self.matrix.save())
32 |
33 | return xml
34 |
--------------------------------------------------------------------------------
/lib/fla/fill/fill_style.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from .solid_color import SolidColor
4 | from .linear_gradient import LinearGradient
5 | from .radial_gradient import RadialGradient
6 | from .bitmap_fill import BitmapFill
7 |
8 | from ..dom import NAMESPACES
9 |
10 |
11 | class FillStyle:
12 | def __init__(self, index: int = None) -> None:
13 | # attributes
14 | self.index = index
15 |
16 | # elements
17 | self.data = None
18 |
19 | def load(self, xml: Element):
20 | if "index" in xml.attrib:
21 | self.index = int(xml.attrib["index"])
22 |
23 | solid_color = xml.find("./xfl:SolidColor", NAMESPACES)
24 | if solid_color is not None:
25 | self.data = SolidColor()
26 | self.data.load(solid_color)
27 |
28 | linear_gradient = xml.find("./xfl:LinearGradient", NAMESPACES)
29 | if linear_gradient is not None:
30 | self.data = LinearGradient()
31 | self.data.load(linear_gradient)
32 |
33 | radial_gradient = xml.find("./xfl:RadialGradient", NAMESPACES)
34 | if radial_gradient is not None:
35 | self.data = RadialGradient()
36 | self.data.load(radial_gradient)
37 |
38 | bitmap_fill = xml.find("./xfl:BitmapFill", NAMESPACES)
39 | if bitmap_fill is not None:
40 | self.data = BitmapFill()
41 | self.data.load(bitmap_fill)
42 |
43 | def save(self):
44 | xml = Element("FillStyle")
45 |
46 | if self.index is not None:
47 | xml.attrib["index"] = str(self.index)
48 |
49 | if self.data is not None and isinstance(self.data, (SolidColor, LinearGradient, RadialGradient, BitmapFill)):
50 | xml.append(self.data.save())
51 |
52 | return xml
53 |
--------------------------------------------------------------------------------
/lib/fla/fill/gradient_entry.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 |
4 | class GradientEntry:
5 | def __init__(self, color: int = None, ratio: float = None) -> None:
6 | # attributes
7 | self.color = color
8 | self.ratio = ratio
9 |
10 | def load(self, xml: Element):
11 | if "color" in xml.attrib:
12 | self.color = int(xml.attrib["color"].replace("#", "0x"), 0)
13 |
14 | if "ratio" in xml.attrib:
15 | self.ratio = float(xml.attrib["ratio"])
16 |
17 | def save(self):
18 | xml = Element("GradientEntry")
19 |
20 | if self.color is not None:
21 | xml.attrib["color"] = "#" + str(hex(self.color).lstrip("0x").zfill(6))
22 |
23 | if self.ratio is not None:
24 | xml.attrib["ratio"] = str(self.ratio)
25 |
26 | return xml
27 |
--------------------------------------------------------------------------------
/lib/fla/fill/linear_gradient.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from .gradient_entry import GradientEntry
4 | from ..geom.matrix import Matrix
5 |
6 | from ..dom import NAMESPACES
7 |
8 |
9 | class LinearGradient:
10 | def __init__(self, spread_method: str = None) -> None:
11 | # attributes
12 | self.spread_method = spread_method
13 |
14 | # elements
15 | self.matrix: Matrix = None
16 | self.entries: list = []
17 |
18 | def load(self, xml: Element):
19 | if "spreadMethod" in xml.attrib:
20 | self.spread_method = xml.attrib["spreadMethod"]
21 |
22 | matrix = xml.find("./xfl:matrix", NAMESPACES)
23 | if matrix is not None:
24 | for matrix_element in matrix:
25 | self.matrix = Matrix()
26 | self.matrix.load(matrix_element)
27 |
28 | entries = xml.findall("./xfl:GradientEntry", NAMESPACES)
29 | for entrie_element in entries:
30 | entrie = GradientEntry()
31 | entrie.load(entrie_element)
32 | self.entries.append(entrie)
33 |
34 | def save(self):
35 | xml = Element("LinearGradient")
36 |
37 | if self.spread_method is not None:
38 | xml.attrib["spreadMethod"] = str(self.spread_method)
39 |
40 | if self.matrix is not None:
41 | matrix = SubElement(xml, "matrix")
42 | matrix.append(self.matrix.save())
43 |
44 | for entrie in self.entries:
45 | xml.append(entrie.save())
46 |
47 | return xml
48 |
--------------------------------------------------------------------------------
/lib/fla/fill/radial_gradient.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from .gradient_entry import GradientEntry
4 | from ..geom.matrix import Matrix
5 |
6 | from ..dom import NAMESPACES
7 |
8 |
9 | class RadialGradient:
10 | def __init__(self, spread_method: str = None) -> None:
11 | # attributes
12 | self.spread_method = spread_method
13 |
14 | # elements
15 | self.matrix: Matrix = None
16 | self.entries: list = []
17 |
18 | def load(self, xml: Element):
19 | if "spreadMethod" in xml.attrib:
20 | self.spread_method = xml.attrib["spreadMethod"]
21 |
22 | matrix = xml.find("./xfl:matrix", NAMESPACES)
23 | if matrix is not None:
24 | for matrix_element in matrix:
25 | self.matrix = Matrix()
26 | self.matrix.load(matrix_element)
27 |
28 | entries = xml.findall("./xfl:GradientEntry", NAMESPACES)
29 | for entrie_element in entries:
30 | entrie = GradientEntry()
31 | entrie.load(entrie_element)
32 | self.entries.append(entrie)
33 |
34 | def save(self):
35 | xml = Element("RadialGradient")
36 |
37 | if self.spread_method is not None:
38 | xml.attrib["spreadMethod"] = str(self.spread_method)
39 |
40 | if self.matrix is not None:
41 | matrix = SubElement(xml, "matrix")
42 | matrix.append(self.matrix.save())
43 |
44 | for entrie in self.entries:
45 | xml.append(entrie.save())
46 |
47 | return xml
48 |
--------------------------------------------------------------------------------
/lib/fla/fill/solid_color.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 |
4 | class SolidColor:
5 | def __init__(self, color: int = None, alpha: float = None) -> None:
6 | # attributes
7 | self.color = color
8 | self.alpha = alpha
9 |
10 | def load(self, xml: Element):
11 | if "color" in xml.attrib:
12 | self.color = int(xml.attrib["color"].replace("#", "0x"), 0)
13 |
14 | if "alpha" in xml.attrib:
15 | self.alpha = float(xml.attrib["alpha"])
16 |
17 | def save(self):
18 | xml = Element("SolidColor")
19 |
20 | if self.color is not None:
21 | xml.attrib["color"] = "#" + str(hex(self.color).lstrip("0x").zfill(6))
22 |
23 | if self.alpha is not None:
24 | xml.attrib["alpha"] = str(self.alpha)
25 |
26 | return xml
27 |
--------------------------------------------------------------------------------
/lib/fla/filter/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sc-workshop/SC/fe797f56b7fe71196a8673184007e00e3f69be05/lib/fla/filter/__init__.py
--------------------------------------------------------------------------------
/lib/fla/filter/drop_shadow_filter.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 |
4 | class DrowShadowFilter:
5 | def __init__(self) -> None:
6 | # attributes
7 | self.color: int = 0
8 |
9 | self.strength: float = 0
10 |
11 | self.blur_x: int = None
12 | self.blur_y: int = None
13 |
14 | self.angle: float = 0.0
15 | self.distance: int = 0
16 |
17 | def load(self, xml: Element):
18 | if "color" in xml.attrib:
19 | self.color = int(str(xml.attrib["color"]).replace("#", "0x"), 0)
20 |
21 | if "strength" in xml.attrib:
22 | self.strength = float(xml.attrib["strength"])
23 |
24 | if "blurX" in xml.attrib:
25 | self.blur_x = int(xml.attrib["blurX"])
26 |
27 | if "blurY" in xml.attrib:
28 | self.blur_y = int(xml.attrib["blurY"])
29 |
30 | if "angle" in xml.attrib:
31 | self.angle = float(xml.attrib["angle"])
32 |
33 | if "distance" in xml.attrib:
34 | self.distance = int(xml.attrib["distance"])
35 |
36 | def save(self):
37 | xml = Element("DrowShadowFilter")
38 |
39 | if self.color is not None:
40 | xml.attrib["color"] = "#" + str(hex(self.color).lstrip("0x").zfill(6))
41 |
42 | if self.strength is not None:
43 | xml.attrib["strength"] = str(self.strength)
44 |
45 | if self.blur_x is not None:
46 | xml.attrib["blurX"] = str(self.blur_x)
47 |
48 | if self.blur_y is not None:
49 | xml.attrib["blurY"] = str(self.blur_y)
50 |
51 | if self.angle is not None:
52 | xml.attrib["angle"] = str(self.angle)
53 |
54 | if self.distance is not None:
55 | xml.attrib["distance"] = str(self.distance)
56 |
57 | return xml
58 |
--------------------------------------------------------------------------------
/lib/fla/filter/glow_filter.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 |
4 | class GlowFilter:
5 | def __init__(self) -> None:
6 | # attributes
7 | self.color: int = 0
8 |
9 | self.strength: int = 0
10 |
11 | self.blur_x: int = None
12 | self.blur_y: int = None
13 |
14 | def load(self, xml: Element):
15 | if "color" in xml.attrib:
16 | self.color = int(str(xml.attrib["color"]).replace("#", "0x"), 0)
17 |
18 | if "strength" in xml.attrib:
19 | self.strength = int(xml.attrib["strength"])
20 |
21 | if "blurX" in xml.attrib:
22 | self.blur_x = int(xml.attrib["blurX"])
23 |
24 | if "blurY" in xml.attrib:
25 | self.blur_y = int(xml.attrib["blurY"])
26 |
27 | def save(self):
28 | xml = Element("GlowFilter")
29 |
30 | if self.color is not None:
31 | xml.attrib["color"] = "#" + str(hex(self.color).lstrip("0x").zfill(6))
32 |
33 | if self.strength is not None:
34 | xml.attrib["strength"] = str(self.strength)
35 |
36 | if self.blur_x is not None:
37 | xml.attrib["blurX"] = str(self.blur_x)
38 |
39 | if self.blur_y is not None:
40 | xml.attrib["blurY"] = str(self.blur_y)
41 |
42 | return xml
43 |
--------------------------------------------------------------------------------
/lib/fla/geom/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sc-workshop/SC/fe797f56b7fe71196a8673184007e00e3f69be05/lib/fla/geom/__init__.py
--------------------------------------------------------------------------------
/lib/fla/geom/color.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from .color_transform import ColorTransform
4 |
5 |
6 | class Color(ColorTransform):
7 | def __init__(self) -> None:
8 | super().__init__()
9 |
10 | def load(self, xml: Element):
11 | if "redMultiplier" in xml.attrib:
12 | self.red_multiplier = float(xml.attrib["redMultiplier"])
13 |
14 | if "redOffset" in xml.attrib:
15 | self.red_offset = int(xml.attrib["redOffset"])
16 |
17 | if "greenMultiplier" in xml.attrib:
18 | self.green_multiplier = float(xml.attrib["greenMultiplier"])
19 |
20 | if "greenOffset" in xml.attrib:
21 | self.green_offset = int(xml.attrib["greenOffset"])
22 |
23 | if "blueMultiplier" in xml.attrib:
24 | self.blue_multiplier = float(xml.attrib["blueMultiplier"])
25 |
26 | if "blueOffset" in xml.attrib:
27 | self.blue_offset = int(xml.attrib["blueOffset"])
28 |
29 | if "alphaMultiplier" in xml.attrib:
30 | self.alpha_multiplier = float(xml.attrib["alphaMultiplier"])
31 |
32 | if "alphaOffset" in xml.attrib:
33 | self.alpha_offset = int(xml.attrib["alphaOffset"])
34 |
35 | if "tintColor" in xml.attrib:
36 | self.red_multiplier = 0
37 | self.green_multiplier = 0
38 | self.blue_multiplier = 0
39 |
40 | color = int(xml.attrib["tintColor"].replace("#", "0x"), 0)
41 |
42 | self.red_offset = (color & 0xFF0000) >> 16
43 | self.green_offset = (color & 0x00FF00) >> 8
44 | self.blue_offset = (color & 0x0000FF) >> 0
45 |
46 | if "tintMultiplier" in xml.attrib:
47 | multiplier = 1 - float(xml.attrib["tintMultiplier"])
48 |
49 | self.red_multiplier = multiplier
50 | self.green_multiplier = multiplier
51 | self.blue_multiplier = multiplier
52 |
53 | def save(self):
54 | xml = Element("Color")
55 |
56 | if self.red_multiplier is not None:
57 | xml.attrib["redMultiplier"] = str(self.red_multiplier)
58 |
59 | if self.red_offset is not None:
60 | xml.attrib["redOffset"] = str(self.red_offset)
61 |
62 | if self.green_multiplier is not None:
63 | xml.attrib["greenMultiplier"] = str(self.green_multiplier)
64 |
65 | if self.green_offset is not None:
66 | xml.attrib["greenOffset"] = str(self.green_offset)
67 |
68 | if self.blue_multiplier is not None:
69 | xml.attrib["blueMultiplier"] = str(self.blue_multiplier)
70 |
71 | if self.blue_offset is not None:
72 | xml.attrib["blueOffset"] = str(self.blue_offset)
73 |
74 | if self.alpha_multiplier is not None:
75 | xml.attrib["alphaMultiplier"] = str(self.alpha_multiplier)
76 |
77 | if self.alpha_offset is not None:
78 | xml.attrib["alphaOffset"] = str(self.alpha_offset)
79 |
80 | return xml
81 |
--------------------------------------------------------------------------------
/lib/fla/geom/color_transform.py:
--------------------------------------------------------------------------------
1 | class ColorTransform:
2 | def __init__(self) -> None:
3 | self.red_multiplier: float = 1
4 | self.red_offset: int = 0
5 |
6 | self.green_multiplier: float = 1
7 | self.green_offset: int = 0
8 |
9 | self.blue_multiplier: float = 1
10 | self.blue_offset: int = 0
11 |
12 | self.alpha_multiplier: float = 1
13 | self.alpha_offset: int = 0
14 |
--------------------------------------------------------------------------------
/lib/fla/geom/matrix.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 |
4 | class Matrix:
5 | def __init__(self, a: float = 1.0, b: float = 0.0, c: float = 0.0, d: float = 1.0, tx: float = 0.0, ty: float = 0.0) -> None:
6 | # attributes
7 | self.a = a
8 | self.b = b
9 | self.c = c
10 | self.d = d
11 | self.tx = tx
12 | self.ty = ty
13 |
14 | def load(self, xml: Element):
15 | if "a" in xml.attrib:
16 | self.a = float(xml.attrib["a"])
17 |
18 | if "b" in xml.attrib:
19 | self.b = float(xml.attrib["b"])
20 |
21 | if "c" in xml.attrib:
22 | self.c = float(xml.attrib["c"])
23 |
24 | if "d" in xml.attrib:
25 | self.d = float(xml.attrib["d"])
26 |
27 | if "tx" in xml.attrib:
28 | self.tx = float(xml.attrib["tx"])
29 |
30 | if "ty" in xml.attrib:
31 | self.ty = float(xml.attrib["ty"])
32 |
33 | def save(self):
34 | xml = Element("Matrix")
35 |
36 | if float(self.a) != 1.0:
37 | xml.attrib["a"] = str(self.a)
38 |
39 | if self.b:
40 | xml.attrib["b"] = str(self.b)
41 |
42 | if self.c:
43 | xml.attrib["c"] = str(self.c)
44 |
45 | if float(self.d) != 1.0:
46 | xml.attrib["d"] = str(self.d)
47 |
48 | if self.tx:
49 | xml.attrib["tx"] = str(self.tx)
50 |
51 | if self.ty:
52 | xml.attrib["ty"] = str(self.ty)
53 |
54 | return xml
55 |
--------------------------------------------------------------------------------
/lib/fla/geom/point.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 |
4 | class Point:
5 | def __init__(self, x: float = 0.0, y: float = 0.0) -> None:
6 | # attributes
7 | self.x = x
8 | self.y = y
9 |
10 | def load(self, xml: Element):
11 | if "x" in xml.attrib:
12 | self.x = float(xml.attrib["x"])
13 |
14 | if "y" in xml.attrib:
15 | self.y = float(xml.attrib["y"])
16 |
17 | def save(self):
18 | xml = Element("Point")
19 |
20 | if self.x is not None and self.x != 0.0:
21 | xml.attrib["x"] = str(self.x)
22 |
23 | if self.y is not None and self.y != 0.0:
24 | xml.attrib["y"] = str(self.y)
25 |
26 | return xml
27 |
--------------------------------------------------------------------------------
/lib/fla/stroke/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sc-workshop/SC/fe797f56b7fe71196a8673184007e00e3f69be05/lib/fla/stroke/__init__.py
--------------------------------------------------------------------------------
/lib/fla/stroke/solid_stroke.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from ..fill.solid_color import SolidColor
4 |
5 | from ..dom import NAMESPACES
6 |
7 |
8 | class SolidStroke:
9 | def __init__(self, scale_mode: str = None, weight: float = None) -> None:
10 | # attributes
11 | self.scale_mode = scale_mode
12 | self.weight = weight
13 |
14 | # elements
15 | self.fill: SolidColor = None
16 |
17 | def load(self, xml: Element):
18 | if "scaleMode" in xml.attrib:
19 | self.scale_mode = xml.attrib["scaleMode"]
20 |
21 | if "weight" in xml.attrib:
22 | self.weight = float(xml.attrib["weight"])
23 |
24 | fill = xml.find("./xfl:fill", NAMESPACES)
25 | solid_color = fill.find("./xfl:SolidColor", NAMESPACES)
26 |
27 | if solid_color is not None:
28 | self.fill = SolidColor()
29 | self.fill.load(solid_color)
30 |
31 | def save(self):
32 | xml = Element("SolidStroke")
33 |
34 | if self.scale_mode is not None:
35 | xml.attrib["scaleMode"] = str(self.scale_mode)
36 |
37 | if self.weight is not None:
38 | xml.attrib["weight"] = str(self.weight)
39 |
40 | if self.fill is not None:
41 | fill = SubElement(xml, "fill")
42 | fill.append(self.fill.save())
43 |
44 | return xml
45 |
--------------------------------------------------------------------------------
/lib/fla/stroke/stroke_style.py:
--------------------------------------------------------------------------------
1 | from lxml.etree import *
2 |
3 | from .solid_stroke import SolidStroke
4 |
5 | from ..dom import NAMESPACES
6 |
7 |
8 | class StrokeStyle:
9 | def __init__(self, index: int = None) -> None:
10 | self.data: SolidStroke = None
11 | self.index = index
12 |
13 | def load(self, xml: Element):
14 | if "index" in xml.attrib:
15 | self.index = int(xml.attrib["index"])
16 |
17 | solid_stroke = xml.find("./xfl:SolidStroke", NAMESPACES)
18 | if solid_stroke is not None:
19 | self.data = SolidStroke()
20 | self.data.load(solid_stroke)
21 |
22 | def save(self):
23 | xml = Element("StrokeStyle")
24 |
25 | if self.index is not None:
26 | xml.attrib["index"] = str(self.index)
27 |
28 | if self.data is not None:
29 | xml.append(self.data.save())
30 |
31 | return xml
32 |
--------------------------------------------------------------------------------
/lib/sc/README.md:
--------------------------------------------------------------------------------
1 | # Supercell SC file format
2 |
3 | Module for working with Supercell `.sc` file format. Made by Fred-31 (Pavel Sokov).
4 | Done by ~90%. Need some refactoring.
5 |
--------------------------------------------------------------------------------
/lib/sc/__init__.py:
--------------------------------------------------------------------------------
1 |
2 | from lib.sc.swf import SupercellSWF
3 | from lib.sc.texture import SWFTexture
4 | from lib.sc.shape import Shape, ShapeDrawBitmapCommand
5 | from lib.sc.text_field import TextField
6 | from lib.sc.matrix_bank import MatrixBank
7 | from lib.sc.movieclip import Modifier, MovieClipModifier, MovieClip, MovieClipFrame
8 |
--------------------------------------------------------------------------------
/lib/sc/matrix_bank.py:
--------------------------------------------------------------------------------
1 | from .writable import Writable
2 | import numpy
3 |
4 | class Color:
5 | def __init__(self,
6 | r_add: float = 0.0,
7 | g_add: float = 0.0,
8 | b_add: float = 0.0,
9 | a_mul: float = 1.0,
10 | r_mul: float = 1.0,
11 | g_mul: float = 1.0,
12 | b_mul: float = 1.0) -> None:
13 |
14 | self.r_add = r_add
15 | self.g_add = g_add
16 | self.b_add = b_add
17 |
18 | self.a_mul = a_mul
19 | self.r_mul = r_mul
20 | self.g_mul = g_mul
21 | self.b_mul = b_mul
22 |
23 | def load(self, swf, tag):
24 | self.r_add = swf.reader.read_uchar()
25 | self.g_add = swf.reader.read_uchar()
26 | self.b_add = swf.reader.read_uchar()
27 |
28 | self.a_mul = swf.reader.read_uchar() / 255
29 | self.r_mul = swf.reader.read_uchar() / 255
30 | self.g_mul = swf.reader.read_uchar() / 255
31 | self.b_mul = swf.reader.read_uchar() / 255
32 |
33 | def save(self, swf):
34 | swf.writer.write_uchar(9)
35 | swf.writer.write_int(7)
36 |
37 | swf.writer.write_uchar(round(self.r_add))
38 | swf.writer.write_uchar(round(self.g_add))
39 | swf.writer.write_uchar(round(self.b_add))
40 |
41 | swf.writer.write_uchar(round(self.a_mul * 255))
42 | swf.writer.write_uchar(round(self.r_mul * 255))
43 | swf.writer.write_uchar(round(self.g_mul * 255))
44 | swf.writer.write_uchar(round(self.b_mul * 255))
45 |
46 | class Matrix:
47 | def __init__(self,
48 | a: int = 1,
49 | b: int = 0,
50 | c: int = 0,
51 | d: int = 1,
52 | tx: int = 0,
53 | ty: int = 0) -> None:
54 | self.a = a
55 | self.b = b
56 | self.c = c
57 | self.d = d
58 | self.tx = tx
59 | self.ty = ty
60 |
61 | def load(self, swf, tag):
62 | divider = 1024 if tag == 8 else 65535
63 |
64 | self.a = swf.reader.read_int() / divider # scale x
65 | self.b = swf.reader.read_int() / divider # rotation x
66 | self.c = swf.reader.read_int() / divider # rotation y
67 | self.d = swf.reader.read_int() / divider # scale y
68 |
69 | self.tx = swf.reader.read_twip() # position x
70 | self.ty = swf.reader.read_twip() # position y
71 |
72 | def save(self, swf):
73 | swf.writer.write_uchar(8)
74 | swf.writer.write_int(24)
75 |
76 | swf.writer.write_int(int(round(self.a * 1024)))
77 | swf.writer.write_int(int(round(self.b * 1024)))
78 | swf.writer.write_int(int(round(self.c * 1024)))
79 | swf.writer.write_int(int(round(self.d * 1024)))
80 |
81 | swf.writer.write_twip(self.tx)
82 | swf.writer.write_twip(self.ty)
83 |
84 | def __eq__(a, b):
85 | if type(a) == type(b):
86 | if a.a == b.a and a.b == b.b and a.c == b.c and a.d == b.d and a.tx == b.tx and a.ty == b.ty:
87 | return True
88 |
89 | return False
90 |
91 |
92 | class MatrixBank(Writable):
93 | def __init__(self) -> None:
94 | self.index: int = 0
95 |
96 | self.matrices: list = []
97 | self.color_transforms: list = []
98 |
99 | self.matrices_count: int = 0
100 | self.color_transforms_count: int = 0
101 |
102 | def available_for_matrix(self, count=0):
103 | if len(self.matrices) >= 65534 - count:
104 | return False
105 | return True
106 |
107 | def available_for_colors(self, count=0):
108 | if len(self.color_transforms) >= 65534 - count:
109 | return False
110 | return True
111 |
112 | def get_matrix(self, matrix: Matrix):
113 | if isinstance(matrix, list):
114 | matrix = Matrix(matrix[0],
115 | matrix[1],
116 | matrix[2],
117 | matrix[3],
118 | matrix[4],
119 | matrix[5])
120 | elif isinstance(matrix, dict):
121 | matrix = Matrix(matrix["a"],
122 | matrix["b"],
123 | matrix["c"],
124 | matrix["d"],
125 | matrix["tx"],
126 | matrix["ty"])
127 |
128 | if matrix not in self.matrices:
129 | self.matrices.append(matrix)
130 |
131 | return self.matrices.index(matrix)
132 |
133 | def get_color_transform(self, color_transform: list):
134 | if color_transform not in self.color_transforms:
135 | self.color_transforms.append(color_transform)
136 |
137 | return self.color_transforms.index(color_transform)
138 |
139 | def load(self, swf):
140 | self.matrices_count = swf.reader.read_ushort()
141 | self.color_transforms_count = swf.reader.read_ushort()
142 |
143 | self.matrices = [_class() for _class in [Matrix] * self.matrices_count]
144 | self.color_transforms= [_class() for _class in [Color] * self.color_transforms_count]
145 |
146 | def save(self):
147 | super().save()
148 |
149 | self.write_ushort(len(self.matrices))
150 | self.write_ushort(len(self.color_transforms))
151 |
152 | return 42, self.buffer
153 |
--------------------------------------------------------------------------------
/lib/sc/movieclip.py:
--------------------------------------------------------------------------------
1 | from enum import Enum
2 |
3 | from lib.console import Console
4 |
5 | from .writable import Writable
6 |
7 |
8 | # all blend modes used in Supercell games
9 | BLENDMODES = [
10 | None, # "mix" by default
11 | None, # something like "mix" + "multiply"
12 | None, # "layer"
13 | "multiply",
14 | "screen",
15 | None, # "lighten"
16 | None, # "darken"
17 | None, # "difference"
18 | "add"
19 | ]
20 |
21 |
22 | class Modifier(Enum):
23 | Mask = 38
24 | Masked = 39
25 | Unmasked = 40
26 |
27 | class MovieClipModifier(Writable):
28 | def __init__(self) -> None:
29 | super().__init__()
30 |
31 | self.modifier: Modifier = Modifier.Mask
32 |
33 | def load(self, swf, tag: int):
34 | self.modifier = Modifier(tag)
35 |
36 | return swf.reader.read_ushort()
37 |
38 | def save(self, id: int):
39 | super().save()
40 |
41 | self.write_ushort(id)
42 |
43 | tag = self.modifier.value
44 |
45 | return tag, self.buffer
46 |
47 | def __eq__(a, b):
48 | if type(a) == type(b):
49 | if a.modifier == b.modifier:
50 | return True
51 |
52 | return False
53 |
54 |
55 | class MovieClip(Writable):
56 |
57 | MOVIECLIP_END_FRAME_TAG = 0
58 |
59 | MOVIECLIP_FRAME_TAGS = (5, 11)
60 | MOVIECLIP_SCALING_GRID_TAG = 31
61 | MOVIECLIP_MATRIX_BANK_TAG = 41
62 |
63 | def __init__(self) -> None:
64 | super().__init__()
65 |
66 | self.frame_rate: int = 30
67 | self.binds: list = []
68 | self.frames: list = []
69 |
70 | self.nine_slice: list = []
71 | self.matrix_bank: int = 0
72 |
73 | def load(self, swf, tag: int):
74 | id = swf.reader.read_ushort()
75 |
76 | self.frame_rate = swf.reader.read_uchar()
77 | frames_count = swf.reader.read_ushort()
78 | self.frames = [_class() for _class in [MovieClipFrame] * frames_count]
79 |
80 | if tag in (3, 14):
81 | Console.error("Tags MovieClip and MovieClip4 is unsupported! Aborting...")
82 | raise TypeError()
83 |
84 |
85 | frame_elements = []
86 | frame_elements_count = swf.reader.read_int()
87 | for x in range(frame_elements_count):
88 | bind_index = swf.reader.read_ushort()
89 | matrix_index = swf.reader.read_ushort()
90 | color_index = swf.reader.read_ushort()
91 |
92 | frame_elements.append({
93 | "bind": bind_index,
94 | "matrix": matrix_index,
95 | "color": color_index
96 | })
97 |
98 | binds_count = swf.reader.read_ushort()
99 |
100 | for x in range(binds_count):
101 | self.binds.append({
102 | "id": swf.reader.read_ushort(),
103 | "blend": BLENDMODES[0]
104 | })
105 |
106 | if tag in (12, 35):
107 | for x in range(binds_count):
108 | blend_index = swf.reader.read_uchar() & 0x3F
109 | # reversed = (bind_index >> 6) & 1 # TODO: blend modes
110 | self.binds[x]["blend"] = BLENDMODES[blend_index]
111 |
112 | for x in range(binds_count):
113 | self.binds[x]["name"] = swf.reader.read_ascii()
114 |
115 | frames_loaded = 0
116 | frame_elements_offset = 0
117 | while True:
118 | frame_tag = swf.reader.read_uchar()
119 | frame_tag_length = swf.reader.read_int()
120 |
121 | if frame_tag == MovieClip.MOVIECLIP_END_FRAME_TAG:
122 | break
123 |
124 | if frame_tag in MovieClip.MOVIECLIP_FRAME_TAGS:
125 | if frame_tag == 5:
126 | Console.error("Tag MovieClipFrame is unsupported! Aborting...")
127 | raise TypeError()
128 |
129 | elements_count = self.frames[frames_loaded].load(swf)
130 |
131 | for x in range(elements_count):
132 | self.frames[frames_loaded].elements.append(frame_elements[frame_elements_offset + x])
133 | frame_elements_offset += elements_count
134 |
135 | frames_loaded += 1
136 | continue
137 |
138 | elif frame_tag == MovieClip.MOVIECLIP_SCALING_GRID_TAG:
139 | self.nine_slice = [swf.reader.read_twip() for _ in range(4)]
140 | continue
141 |
142 | elif frame_tag == MovieClip.MOVIECLIP_MATRIX_BANK_TAG:
143 | self.matrix_bank = swf.reader.read_uchar()
144 | continue
145 |
146 | Console.warning(f"MovieClip {self.id} has unknown frame tag {frame_tag} with length {frame_tag_length}! Skipping...")
147 | swf.reader.skip(frame_tag_length)
148 |
149 | return id
150 |
151 | def save(self, id: int, ids: list):
152 | super().save()
153 |
154 | self.write_ushort(id)
155 | self.write_uchar(self.frame_rate)
156 | self.write_ushort(len(self.frames))
157 |
158 | frame_elements = []
159 | for frame in self.frames:
160 | for element in frame.elements:
161 | frame_elements.append(element)
162 |
163 | self.write_int(len(frame_elements))
164 | for element in frame_elements:
165 | self.write_ushort(element["bind"])
166 | self.write_ushort(element["matrix"])
167 | self.write_ushort(element["color"])
168 |
169 | self.write_ushort(len(self.binds))
170 |
171 | for bind in self.binds:
172 | self.write_ushort(ids[bind["id"]])
173 |
174 | for bind in self.binds:
175 | self.write_uchar(BLENDMODES.index(bind["blend"]) & 0x3F)
176 |
177 | for bind in self.binds:
178 | self.write_ascii(bind["name"])
179 |
180 | if self.matrix_bank > 0:
181 | self.write_uchar(41)
182 | self.write_int(1)
183 | self.write_uchar(self.matrix_bank)
184 |
185 | for frame in self.frames:
186 | tag_frame, buffer = frame.save()
187 |
188 | self.write_uchar(tag_frame)
189 | self.write_int(len(buffer))
190 | self.write(buffer)
191 |
192 | if self.nine_slice:
193 | self.write_uchar(31)
194 | self.write_int(16)
195 |
196 | x, y, width, height = self.nine_slice
197 | self.write_twip(x)
198 | self.write_twip(y)
199 | self.write_twip(width)
200 | self.write_twip(height)
201 |
202 | self.write(bytes(5)) # end tag for frame tags array
203 |
204 | # TODO: add support for tag 35 (idk where difference, but it's also used in games)
205 | return 12, self.buffer
206 |
207 | def __eq__(a, b):
208 | if type(a) == type(b):
209 | if a.frame_rate == b.frame_rate\
210 | and a.binds == b.binds\
211 | and a.frames == b.frames\
212 | and a.nine_slice == b.nine_slice\
213 | and a.matrix_bank == b.matrix_bank:
214 | return True
215 |
216 | return False
217 | class MovieClipFrame(Writable):
218 | def __init__(self) -> None:
219 | self.elements: list = []
220 | self.name: str = None
221 |
222 | def load(self, swf):
223 | elements_count = swf.reader.read_ushort()
224 | self.name = swf.reader.read_ascii()
225 |
226 | return elements_count
227 |
228 | def save(self):
229 | super().save()
230 |
231 | self.write_ushort(len(self.elements))
232 | self.write_ascii(self.name)
233 |
234 | return 11, self.buffer
235 |
236 | def __eq__(a, b):
237 | if a.name == b.name\
238 | and a.elements == b.elements:
239 | return False
240 |
--------------------------------------------------------------------------------
/lib/sc/resource.py:
--------------------------------------------------------------------------------
1 | class Resource:
2 | def __init__(self) -> None:
3 | self.id: int = -1
4 |
--------------------------------------------------------------------------------
/lib/sc/shape.py:
--------------------------------------------------------------------------------
1 | from math import ceil, degrees, radians, atan2, cos, sin
2 |
3 | from lib.console import Console
4 |
5 | from .writable import Writable
6 |
7 | import numpy as np
8 | from PIL import Image, ImageDraw
9 |
10 | from affine6p import estimate
11 |
12 |
13 | def get_size(coords):
14 | left = min(x for x, _ in coords)
15 | top = min(y for _, y in coords)
16 | right = max(x for x, _ in coords)
17 | bottom = max(y for _, y in coords)
18 |
19 | return right - left or 1, bottom - top or 1
20 |
21 |
22 | class Shape(Writable):
23 | SHAAPE_END_COMMAND_TAG = 0
24 |
25 | SHAAPE_DRAW_BITMAP_COMMAND_TAGS = (4, 17, 22)
26 | SHAPE_DRAW_COLOR_FILL_COMMAND_TAG = 6
27 |
28 | def __init__(self) -> None:
29 | super().__init__()
30 |
31 | self.bitmaps: list = []
32 |
33 | def load(self, swf, tag: int):
34 | id = swf.reader.read_ushort()
35 |
36 | bitmaps_count = swf.reader.read_ushort()
37 | self.bitmaps = [_class() for _class in [ShapeDrawBitmapCommand] * bitmaps_count]
38 |
39 | points_count = 4 * bitmaps_count
40 | if tag == 18:
41 | points_count = swf.reader.read_ushort()
42 |
43 | bitmaps_loaded = 0
44 | while True:
45 | bitmap_tag = swf.reader.read_uchar()
46 | bitmap_tag_length = swf.reader.read_int()
47 |
48 | if bitmap_tag == Shape.SHAAPE_END_COMMAND_TAG:
49 | break
50 |
51 | if bitmap_tag in Shape.SHAAPE_DRAW_BITMAP_COMMAND_TAGS:
52 | self.bitmaps[bitmaps_loaded].load(swf, bitmap_tag)
53 | bitmaps_loaded += 1
54 | continue
55 |
56 | elif tag == Shape.SHAPE_DRAW_COLOR_FILL_COMMAND_TAG:
57 | Console.error("Tag ShapeDrawColorFillCommand is unsupported! Aborting...")
58 | raise TypeError()
59 |
60 | Console.warning(
61 | f"Shape {self.id} has unknown command tag {bitmap_tag} with length {bitmap_tag_length}! Skipping...")
62 | swf.reader.skip(bitmap_tag_length)
63 |
64 | return id
65 |
66 | def save(self, swf, id: int):
67 | super().save()
68 |
69 | self.write_ushort(id)
70 | self.write_ushort(len(self.bitmaps))
71 |
72 | points_count = 0
73 | max_rects_count = 0
74 | for bitmap in self.bitmaps:
75 | points_count += len(bitmap.xy_coords)
76 | if bitmap.max_rects:
77 | max_rects_count += 1
78 |
79 | tag = 2 if max_rects_count == len(self.bitmaps) else 18
80 |
81 | # allocator?
82 | if tag == 18:
83 | self.write_ushort(points_count)
84 |
85 | for bitmap in self.bitmaps:
86 | tag_bitmap, buffer = bitmap.save(swf)
87 |
88 | self.write_uchar(tag_bitmap)
89 | self.write_int(len(buffer))
90 | self.write(buffer)
91 |
92 | self.write(bytes(5)) # end tag for bitmap tags array
93 |
94 | return tag, self.buffer
95 |
96 | def __eq__(a, b):
97 | if type(a) == type(b):
98 | if a.bitmaps == b.bitmaps:
99 | return True
100 | return False
101 |
102 |
103 | class ShapeDrawBitmapCommand(Writable):
104 | def __init__(self) -> None:
105 | self.texture_index: int = -1
106 | self.uv_coords: list = []
107 | self.xy_coords: list = []
108 |
109 | self.max_rects: bool = False
110 |
111 | def load(self, swf, tag: int):
112 | self.texture_index = swf.reader.read_uchar()
113 |
114 | self.max_rects = tag == 4
115 | points_count = 4 if self.max_rects else swf.reader.read_uchar()
116 |
117 | for i in range(points_count):
118 | x = swf.reader.read_twip()
119 | y = swf.reader.read_twip()
120 | self.xy_coords.append([x, y])
121 |
122 | for i in range(points_count):
123 | w = swf.reader.read_ushort()
124 | h = swf.reader.read_ushort()
125 |
126 | if tag == 22:
127 | w = w / 0xFFFF * swf.textures[self.texture_index].width
128 | h = h / 0xFFFF * swf.textures[self.texture_index].height
129 |
130 | u, v = [ceil(i) for i in [w, h]]
131 |
132 | self.uv_coords.append([u, v])
133 | def save(self, swf):
134 | super().save()
135 |
136 | tag = 4 if self.max_rects else 22
137 | points_count = 4 if self.max_rects else len(self.xy_coords)
138 |
139 | self.write_uchar(self.texture_index)
140 |
141 | if not self.max_rects:
142 | self.write_uchar(points_count)
143 |
144 | if (swf.textures[self.texture_index].mag_filter, swf.textures[self.texture_index].min_filter) == (
145 | "GL_NEAREST", "GL_NEAREST") and not self.max_rects:
146 | tag = 17
147 |
148 | for coord in self.xy_coords[:points_count]:
149 | x, y = coord
150 |
151 | self.write_twip(x)
152 | self.write_twip(y)
153 |
154 | for coord in self.uv_coords[:points_count]:
155 | u, v = coord
156 |
157 | if tag == 22:
158 | u *= 0xFFFF / swf.textures[self.texture_index].width
159 | v *= 0xFFFF / swf.textures[self.texture_index].height
160 |
161 | self.write_ushort(int(u))
162 | self.write_ushort(int(v))
163 |
164 | return tag, self.buffer
165 |
166 | def get_image(self, swf) -> Image:
167 | texture = swf.textures[self.texture_index]
168 | image = texture.get_image()
169 |
170 | w, h = self.get_size(self.uv_coords)
171 | if w == 0:
172 | w = 1
173 | if h == 0:
174 | h = 1
175 |
176 | if w + h == 2:
177 | x, y = self.uv_coords[-1]
178 | return Image.new(texture.image.mode, (1, 1), texture.image.getpixel((x, y)))
179 |
180 | mask = Image.new("L", (texture.width, texture.height), 0)
181 |
182 | color = 255
183 | ImageDraw.Draw(mask).polygon([(x, y) for x, y in self.uv_coords], fill=color)
184 |
185 | left = min(x for x, _ in self.uv_coords)
186 | top = min(y for _, y in self.uv_coords)
187 | right = max(x for x, _ in self.uv_coords)
188 | bottom = max(y for _, y in self.uv_coords)
189 |
190 | if w == 1:
191 | right += 1
192 | if h == 1:
193 | bottom += 1
194 |
195 | bbox = left, top, right, bottom
196 |
197 | sprite = Image.new(image.mode, (w, h))
198 | sprite.paste(image.crop(bbox), (0, 0), mask.crop(bbox))
199 |
200 | return sprite
201 |
202 | def get_matrix(self, custom_uv_coords: list = None, use_nearest: bool = False):
203 | uv_coords = custom_uv_coords or self.uv_coords
204 |
205 | rotation = 0
206 | mirroring = False
207 | if use_nearest:
208 | rotation, mirroring = self.get_rotation(use_nearest)
209 |
210 | rad = radians(rotation)
211 |
212 | uv_coords = [
213 | np.array(
214 | (
215 | (np.cos(rad), -np.sin(rad)),
216 | (np.sin(rad), np.cos(rad))
217 | )
218 | ).dot(point).tolist() for point in self.uv_coords
219 | ]
220 |
221 | uv_coords = [[round(x), round(y)] for x, y in uv_coords]
222 |
223 | if mirroring:
224 | uv_coords = [[-x, y] for x, y, in uv_coords]
225 |
226 | sprite_box = []
227 |
228 | for idx in range(len(uv_coords)):
229 | if idx == 0:
230 | sprite_box.append([0, 0])
231 | else:
232 | x_distance = uv_coords[idx][0] - uv_coords[idx - 1][0]
233 | y_distance = uv_coords[idx][1] - uv_coords[idx - 1][1]
234 |
235 | sprite_box.append([round(sprite_box[idx - 1][0] + x_distance, 3),
236 | round(sprite_box[idx - 1][1] + y_distance, 3)])
237 |
238 | if sprite_box[idx][0] < 0:
239 | sprite_box = [[x - sprite_box[idx][0], y] for x, y in sprite_box]
240 |
241 | if sprite_box[idx][1] < 0:
242 | sprite_box = [[x, y - sprite_box[idx][1]] for x, y in sprite_box]
243 |
244 | w, h = self.get_size(uv_coords)
245 | if w == 0 or h == 0:
246 | sprite_box = self.get_right_uv(False, sprite_box)
247 |
248 | transform = estimate(sprite_box, self.xy_coords)
249 |
250 | return transform, sprite_box, rotation, mirroring
251 | @staticmethod
252 | def scale_around(point, center, scale):
253 | c_x, c_y = center
254 | x, y = point
255 | sx, sy = scale
256 | return [round(((x - c_x) * sx)), round(((y - c_y) * sy))]
257 | @staticmethod
258 | def move_by_angle(point, angle, distance):
259 | x, y = point
260 |
261 | x += distance * sin(angle)
262 | y += distance * cos(angle)
263 |
264 | return [round(x) or 0, round(y) or 0]
265 | @staticmethod
266 | def find_angle(p1, p2):
267 | x1, y1 = p1
268 | x2, y2 = p2
269 | dX = x2 - x1
270 | dY = y2 - y1
271 | rads = atan2(-dY, dX)
272 | return degrees(rads)
273 | def get_right_uv(self, inside: bool, custom: list = None):
274 | coords = custom if custom is not None else self.uv_coords
275 |
276 | res = coords.copy()
277 | w, h = ShapeDrawBitmapCommand.get_size(coords)
278 |
279 | if not inside and w == 0 or h == 0:
280 | unique_points = [list(x) for x in set(tuple(x) for x in coords)]
281 | for index, point in enumerate(unique_points):
282 | if coords[0] == coords[1]:
283 | point_idx = index + 1
284 | else:
285 | point_idx = 3 - (list(reversed(res)).index(point))
286 |
287 | res[point_idx] = [res[point_idx][0] + (1 if w == 0 else 0),
288 | res[point_idx][1] + (1 if h == 0 else 0)]
289 |
290 | return res
291 | else:
292 | if len(coords) <= 4:
293 | w_m = (w + 2) if inside else (w - 2 if w > 2 else 0)
294 | h_m = (h + 2) if inside else (h - 2 if h > 2 else 0)
295 |
296 | c_x, c_y = [sum([x for x, _ in coords]) / len(coords), sum([y for _, y in coords]) / len(coords)]
297 |
298 | return [[round((w_m / w) * (x - c_x) + c_x), round((h_m / h) * (y - c_y) + c_y)] for x, y in coords]
299 |
300 | for i, point in enumerate(coords):
301 | if i == 0:
302 | last = len(coords) - 1
303 | else:
304 | last = i - 1
305 |
306 | angle = radians(self.find_angle(coords[last], coords[i]) - 45)
307 |
308 | res[i] = self.move_by_angle(coords[i], angle, -1 if inside else 1)
309 |
310 | return res
311 | def get_translation(self, centroid: bool = False):
312 | if centroid:
313 | x_coords = [x for x, _ in self.xy_coords]
314 | y_coords = [y for y, _ in self.xy_coords]
315 |
316 | size = len(self.xy_coords)
317 |
318 | x = sum(x_coords) / size
319 | y = sum(y_coords) / size
320 |
321 | return x, y
322 |
323 | left = min(x for x, _ in self.xy_coords)
324 | top = min(y for _, y in self.xy_coords)
325 |
326 | return left, top
327 |
328 | def get_rotation(self, nearest: bool = False):
329 | def is_clockwise(points):
330 | points_sum = 0
331 | for x in range(len(points)):
332 | x1, y1 = points[(x + 1) % len(points)]
333 | x2, y2 = points[x]
334 | points_sum += (x1 - x2) * (y1 + y2)
335 | return points_sum < 0
336 |
337 | uv_cw = is_clockwise(self.uv_coords)
338 | xy_cw = is_clockwise(self.xy_coords)
339 |
340 | mirroring = not (uv_cw == xy_cw)
341 |
342 | dx = self.xy_coords[1][0] - self.xy_coords[0][0]
343 | dy = self.xy_coords[1][1] - self.xy_coords[0][1]
344 | du = self.uv_coords[1][0] - self.uv_coords[0][0]
345 | dv = self.uv_coords[1][1] - self.uv_coords[0][1]
346 |
347 | angle_xy = degrees(atan2(dy, dx) + 360) % 360
348 | angle_uv = degrees(atan2(dv, du) + 360) % 360
349 |
350 | angle = (angle_xy - angle_uv + 360) % 360
351 |
352 | if mirroring:
353 | angle -= 180
354 |
355 | if nearest:
356 | angle = round(angle / 90) * 90
357 |
358 | return angle, mirroring
359 |
360 | @staticmethod
361 | def get_size(coords):
362 | left = min(coord[0] for coord in coords)
363 | top = min(coord[1] for coord in coords)
364 | right = max(coord[0] for coord in coords)
365 | bottom = max(coord[1] for coord in coords)
366 |
367 | return right - left, bottom - top
368 |
369 | def get_scale(self):
370 | uv_x, uv_y = self.get_size(self.uv_coords)
371 | xy_x, xy_y = self.get_size(self.xy_coords)
372 |
373 | return uv_x / xy_x, uv_y / xy_y
374 |
375 | def __eq__(a, b):
376 | if a.max_rects == b.max_rects\
377 | and a.uv_coords == b.uv_coords\
378 | and a.xy_coords == b.xy_coords\
379 | and a.texture_index == b.texture_index:
380 | return True
381 | return False
382 |
--------------------------------------------------------------------------------
/lib/sc/swf.py:
--------------------------------------------------------------------------------
1 | import copy
2 | import os
3 |
4 | from lib.utils import BinaryReader, BinaryWriter
5 |
6 |
7 | from .texture import SWFTexture
8 | from .shape import Shape
9 | from .text_field import TextField
10 | from .matrix_bank import MatrixBank, Matrix
11 | from .movieclip import MovieClipModifier, MovieClip
12 |
13 | from sc_compression.signatures import Signatures
14 | from sc_compression import Decompressor, Compressor
15 |
16 | from lib.console import Console
17 | class SupercellSWF:
18 |
19 | TEXTURE_EXTENSION = "_tex.sc"
20 |
21 | END_TAG = 0
22 |
23 | USE_LOWRES_TEXTURE_TAG = 23
24 | USE_EXTERNAL_TEXTURE_TAG = 26
25 | USE_UNCOMMON_RESOLUTION_TAG = 30
26 | TEXTURE_POSTFIXS_TAG = 32
27 |
28 | MOVIECLIP_MODIFIERS_COUNT_TAG = 37
29 | MOVIECLIP_MODIFIER_TAGS = (38, 39, 40)
30 |
31 | TEXTURE_TAGS = (1, 16, 19, 24, 27, 28, 29, 34)
32 |
33 | SHAPE_TAGS = (2, 18)
34 |
35 | TEXT_FIELD_TAGS = (7, 15, 20, 21, 25, 33, 43, 44)
36 |
37 | MATRIX_BANK_TAG = 42
38 | MATRIX_TAGS = (8, 36)
39 | COLOR_TRANSFORM_TAG = 9
40 |
41 | MOVIECLIP_TAGS = (3, 10, 12, 14, 35)
42 |
43 | def __init__(self) -> None:
44 | self.filename: str = None
45 |
46 | self.use_uncommon_texture: bool = False
47 | self.use_lowres_texture: bool = False
48 |
49 | self.textures_count: int = 0
50 | self.movieclip_modifiers_count: int = 0
51 | self.shapes_count: int = 0
52 | self.text_fields_count: int = 0
53 | self.movieclips_count: int = 0
54 |
55 | self.has_external_texture: bool = None
56 |
57 | self.textures: list = []
58 | self.matrix_banks: list = [MatrixBank()]
59 | self.resources: dict = {}
60 |
61 | self.exports: dict = {}
62 |
63 | self.highres_texture_postfix: str = "_highres"
64 | self.lowres_texture_postfix: str = "_lowres"
65 |
66 | self.reader: BinaryReader = None
67 | self.writer: BinaryWriter = None
68 |
69 | def load(self, filepath: str):
70 | Console.info(f"Reading {filepath} SupercellFlash asset file...")
71 | print()
72 |
73 | self.filename = filepath
74 |
75 | self.load_internal(filepath, False)
76 |
77 | if self.has_external_texture:
78 | texture_filename = os.path.splitext(self.filename)[0] + self.TEXTURE_EXTENSION
79 | highres_path = f"{os.path.splitext(self.filename)[0]}{self.highres_texture_postfix}{self.TEXTURE_EXTENSION}"
80 | lowres_path = f"{os.path.splitext(self.filename)[0]}{self.lowres_texture_postfix}{self.TEXTURE_EXTENSION}"
81 |
82 | if self.use_uncommon_texture:
83 | if os.path.isfile(highres_path):
84 | self.load_internal(highres_path, True)
85 | elif os.path.isfile(lowres_path):
86 | Console.warning(f"Cannot find higrhes texture file {highres_path} for {self.filename}. Skipping...")
87 | self.load_internal(lowres_path, True)
88 | else:
89 | Console.error(
90 | f"Cannot find any external texture file asset for {self.filename}! Textures not loaded! Aborting...")
91 | raise TypeError()
92 |
93 | else:
94 | if self.use_lowres_texture:
95 | if not os.path.exists(texture_filename) and os.path.exists(lowres_path):
96 | Console.info(
97 | f"Cannot find external texture file {texture_filename} for {self.filename}! Loading lowres texture asset...")
98 | self.load_internal(lowres_path, True)
99 |
100 | if os.path.exists(texture_filename):
101 | self.load_internal(texture_filename, True)
102 | else:
103 | Console.error(f"Cannot find external texture file {texture_filename} for {self.filename}! Textures not loaded! Aborting...")
104 | raise TypeError()
105 |
106 |
107 |
108 | def load_internal(self, filepath: str, is_texture: bool):
109 | with open(filepath, 'rb') as file:
110 | compressed = file.read().split(b"START")[0] # TODO: Vorono4ka, fix your sc-compression please...
111 |
112 | decompressor = Decompressor()
113 | self.reader = BinaryReader(decompressor.decompress(compressed))
114 |
115 | if not is_texture:
116 | Console.info("Reading main asset file...")
117 |
118 | self.shapes_count = self.reader.read_ushort()
119 | self.movieclips_count = self.reader.read_ushort()
120 | self.textures_count = self.reader.read_ushort()
121 | self.text_fields_count = self.reader.read_ushort()
122 |
123 | self.matrix_banks[-1].load(self)
124 |
125 | self.reader.skip(5) # unused
126 |
127 | exports_count = self.reader.read_ushort()
128 |
129 | export_ids = [self.reader.read_ushort() for x in range(exports_count)]
130 | self.exports = {id: [] for id in export_ids}
131 |
132 | for export_id in export_ids:
133 | export_name = self.reader.read_ascii()
134 |
135 | self.exports[export_id].append(export_name)
136 |
137 | print()
138 |
139 | self.textures = [_class() for _class in [SWFTexture] * self.textures_count]
140 |
141 | else:
142 | Console.info("Reading external texture asset file...")
143 | print()
144 |
145 | self.load_tags()
146 |
147 | def load_tags(self):
148 | has_external_texture = False
149 |
150 | textures_loaded = 0
151 |
152 | matrices_loaded = 0
153 | color_transforms_loaded = 0
154 |
155 | movieclip_modifiers_loaded = 0
156 | shapes_loaded = 0
157 | text_fields_loaded = 0
158 | movieclips_loaded = 0
159 |
160 | while True:
161 | tag = self.reader.read_uchar()
162 | tag_length = self.reader.read_int()
163 |
164 | if tag == SupercellSWF.END_TAG:
165 | print()
166 | Console.info("End tag.")
167 | print()
168 | Console.info("Reading completed.")
169 |
170 | break
171 |
172 | if tag == SupercellSWF.USE_LOWRES_TEXTURE_TAG:
173 | self.use_lowres_texture = True
174 |
175 | continue
176 |
177 | elif tag == SupercellSWF.USE_EXTERNAL_TEXTURE_TAG:
178 | has_external_texture = True
179 | self.has_external_texture = True
180 | continue
181 |
182 | elif tag == SupercellSWF.USE_UNCOMMON_RESOLUTION_TAG:
183 | self.use_uncommon_texture = True
184 | self.use_lowres_texture = True
185 |
186 | continue
187 |
188 | elif tag == SupercellSWF.TEXTURE_POSTFIXS_TAG:
189 | self.highres_texture_postfix = self.reader.read_ascii()
190 | self.lowres_texture_postfix = self.reader.read_ascii()
191 | continue
192 |
193 | elif tag in SupercellSWF.TEXTURE_TAGS:
194 | self.textures[textures_loaded].load(self, tag, has_external_texture)
195 |
196 | textures_loaded += 1
197 | if textures_loaded > self.textures_count:
198 | Console.error("Trying to load too many SWFTextures! Aborting...")
199 | raise TypeError()
200 |
201 | continue
202 |
203 | elif tag == SupercellSWF.MOVIECLIP_MODIFIERS_COUNT_TAG:
204 | self.movieclip_modifiers_count = self.reader.read_ushort()
205 | continue
206 |
207 | elif tag in SupercellSWF.MOVIECLIP_MODIFIER_TAGS:
208 | movieclip_modifier = MovieClipModifier()
209 | id = movieclip_modifier.load(self, tag)
210 |
211 | self.resources[id] = movieclip_modifier
212 |
213 | movieclip_modifiers_loaded += 1
214 | if movieclip_modifiers_loaded > self.movieclip_modifiers_count:
215 | Console.error("Trying to load too many MovieClipModifiers! Aborting...")
216 | raise TypeError()
217 |
218 | continue
219 |
220 | elif tag in SupercellSWF.SHAPE_TAGS:
221 | Console.progress_bar("Shapes loading...", shapes_loaded, self.shapes_count)
222 | shape = Shape()
223 | id = shape.load(self, tag)
224 |
225 | self.resources[id] = shape
226 |
227 | shapes_loaded += 1
228 | if shapes_loaded > self.shapes_count:
229 | Console.error("Trying to load too many Shapes! Aborting...")
230 | raise TypeError()
231 |
232 | continue
233 |
234 | elif tag in SupercellSWF.TEXT_FIELD_TAGS:
235 | Console.progress_bar("Text fields loading...", text_fields_loaded, self.text_fields_count)
236 | text_field = TextField()
237 | id = text_field.load(self, tag)
238 |
239 | self.resources[id] = text_field
240 |
241 | text_fields_loaded += 1
242 | if text_fields_loaded > self.text_fields_count:
243 | Console.error("Trying to load too many TextFields! Aborting...")
244 | raise TypeError()
245 |
246 | continue
247 |
248 | elif tag == SupercellSWF.MATRIX_BANK_TAG:
249 | matrix_bank = MatrixBank()
250 | matrix_bank.index = len(self.matrix_banks)
251 | matrix_bank.load(self)
252 | self.matrix_banks.append(matrix_bank)
253 |
254 | matrices_loaded = 0
255 | color_transforms_loaded = 0
256 | continue
257 |
258 | elif tag in SupercellSWF.MATRIX_TAGS:
259 | Console.progress_bar("Matrices loading...", matrices_loaded, self.matrix_banks[-1].matrices_count)
260 |
261 | self.matrix_banks[-1].matrices[matrices_loaded].load(self, tag)
262 |
263 | matrices_loaded += 1
264 | if matrices_loaded == self.matrix_banks[-1].matrices_count:
265 | print()
266 |
267 | continue
268 |
269 | elif tag == SupercellSWF.COLOR_TRANSFORM_TAG:
270 | Console.progress_bar("ColorTransforms loading...", color_transforms_loaded, self.matrix_banks[-1].color_transforms_count)
271 |
272 | self.matrix_banks[-1].color_transforms[color_transforms_loaded].load(self, tag)
273 |
274 | color_transforms_loaded += 1
275 | if color_transforms_loaded == self.matrix_banks[-1].color_transforms_count:
276 | print()
277 |
278 | continue
279 |
280 | elif tag in SupercellSWF.MOVIECLIP_TAGS:
281 | Console.progress_bar("Movieclip loading...", movieclips_loaded, self.movieclips_count)
282 | movieclip = MovieClip()
283 | id = movieclip.load(self, tag)
284 |
285 | self.resources[id] = movieclip
286 |
287 | movieclips_loaded += 1
288 | if movieclips_loaded > self.movieclips_count:
289 | Console.error("Trying to load too many MovieClips! Aborting...")
290 | raise TypeError()
291 |
292 | continue
293 |
294 | Console.warning(f"{self.filename} has unknown tag {tag} with length {tag_length}! Skipped...")
295 | self.reader.skip(tag_length)
296 |
297 | def save(self, filepath: str):
298 | Console.info(f"Writing {filepath} SupercellFlash asset file...")
299 | print()
300 |
301 | self.filename = filepath
302 |
303 | self.save_internal(filepath, False, False)
304 |
305 | if self.has_external_texture:
306 | texture_filename = os.path.splitext(self.filename)[0] + self.TEXTURE_EXTENSION
307 | highres_path = f"{os.path.splitext(self.filename)[0]}{self.highres_texture_postfix}{self.TEXTURE_EXTENSION}"
308 | lowres_path = f"{os.path.splitext(self.filename)[0]}{self.lowres_texture_postfix}{self.TEXTURE_EXTENSION}"
309 |
310 | if self.use_uncommon_texture:
311 | self.save_internal(highres_path, True, False)
312 |
313 | else:
314 | self.save_internal(texture_filename, True, False)
315 |
316 | if self.use_lowres_texture:
317 | self.save_internal(lowres_path, True, True)
318 |
319 | def save_internal(self, filepath: str, is_texture: bool, is_lowres: bool):
320 | self.writer = BinaryWriter()
321 |
322 | sorted_resources_id = []
323 | sorted_resources = []
324 | id_list = {}
325 |
326 | if not is_texture:
327 | Console.info("Writing main asset file...")
328 |
329 | self.textures_count = len(self.textures)
330 | self.shapes_count = 0
331 | self.movieclips_count = 0
332 | self.text_fields_count = 0
333 | self.movieclip_modifiers_count = 0
334 |
335 | for resource in self.resources.values():
336 | if isinstance(resource, Shape):
337 | self.shapes_count += 1
338 | if isinstance(resource, MovieClip):
339 | self.movieclips_count += 1
340 | if isinstance(resource, TextField):
341 | self.text_fields_count += 1
342 | if isinstance(resource, MovieClipModifier):
343 | self.movieclip_modifiers_count += 1
344 |
345 | self.writer.write_ushort(self.shapes_count)
346 | self.writer.write_ushort(self.movieclips_count)
347 | self.writer.write_ushort(self.textures_count)
348 | self.writer.write_ushort(self.text_fields_count)
349 |
350 | if not self.matrix_banks:
351 | self.matrix_banks.append(MatrixBank())
352 |
353 | matrix_bank = self.matrix_banks[0]
354 | _, data = matrix_bank.save()
355 | self.writer.write(data)
356 |
357 | self.writer.write(bytes(5)) # unused
358 |
359 | data_struct = [MovieClipModifier,
360 | Shape,
361 | TextField,
362 | MatrixBank,
363 | MovieClip]
364 | Console.info("Resource filtering...")
365 |
366 | resources = {}
367 |
368 | id_counter = 0
369 | for identifer, resource in self.resources.items():
370 | resource_values = list(resources.values())
371 | if resource in resource_values:
372 | id_list[identifer] = resources.items()[resource_values.index(resource)]
373 | else:
374 | resources[identifer] = resource
375 | id_list[identifer] = id_counter
376 | id_counter += 1
377 |
378 | resources_keys = list(resources)
379 | resources_values = list(resources.values())
380 |
381 | sorted_resources_id = []
382 | sorted_resources = (resources_values + sorted(self.matrix_banks, key= lambda x: x.index))
383 | sorted_resources.sort(key=lambda x: data_struct.index(type(x)))
384 |
385 | for resource in sorted_resources:
386 | if resource in resources_values:
387 | sorted_resources_id.append(resources_keys[resources_values.index(resource)])
388 | else:
389 | sorted_resources_id.append(None)
390 |
391 | export_ids = []
392 | export_names = []
393 | for export_id in self.exports:
394 | for export_name in self.exports[export_id]:
395 | export_ids.append(id_list[export_id])
396 | export_names.append(export_name)
397 |
398 | self.writer.write_ushort(len(export_ids))
399 |
400 | for export_id in export_ids:
401 | self.writer.write_ushort(export_id)
402 |
403 | for export_name in export_names:
404 | self.writer.write_ascii(export_name)
405 |
406 | else:
407 | Console.info("Writing external texture asset file...")
408 | print()
409 |
410 | self.save_tags((sorted_resources_id, sorted_resources), id_list, is_texture, is_lowres)
411 | print()
412 |
413 | with open(filepath, 'wb') as file:
414 | Console.info("File compressing...")
415 | compressor = Compressor()
416 | compressed = compressor.compress(self.writer.buffer, Signatures.SC, 1)
417 | Console.info("Writing to file..")
418 | file.write(compressed)
419 |
420 | Console.info("Writing completed.")
421 |
422 | def save_tags(self, resources, id_list, is_texture: bool, is_lowres: bool):
423 | written_shapes = 0
424 | written_movieclips = 0
425 | written_fields = 0
426 | def save_tag(tag, data):
427 | self.writer.write_uchar(tag)
428 | self.writer.write_int(len(data))
429 | self.writer.write(data)
430 |
431 | if is_texture:
432 | for texture in self.textures:
433 | texture = copy.deepcopy(texture)
434 | if is_lowres:
435 | Console.info("Writing lowres texture asset...")
436 | sheet = texture.get_image()
437 | w, h = sheet.size
438 | texture.set_image(sheet.resize((int(w / 2), int(h / 2))))
439 |
440 | tag, data = texture.save(False)
441 | save_tag(tag, data)
442 | return
443 |
444 | if self.use_uncommon_texture:
445 | save_tag(SupercellSWF.USE_UNCOMMON_RESOLUTION_TAG, bytes())
446 |
447 | if self.has_external_texture:
448 | save_tag(SupercellSWF.USE_EXTERNAL_TEXTURE_TAG, bytes())
449 |
450 | if not self.use_uncommon_texture and self.use_lowres_texture:
451 | save_tag(SupercellSWF.USE_LOWRES_TEXTURE_TAG, bytes())
452 |
453 | for texture in self.textures:
454 | if self.has_external_texture:
455 | texture = copy.deepcopy(texture)
456 | texture.linear = False
457 |
458 | tag, data = texture.save(self.has_external_texture)
459 | save_tag(tag, data)
460 |
461 | if self.movieclip_modifiers_count:
462 | save_tag(37, (self.movieclip_modifiers_count).to_bytes(2, "little"))
463 |
464 | ids, resources = resources
465 | for (identifer, resource) in zip(ids, resources):
466 | if isinstance(resource, MovieClipModifier):
467 | tag, data = resource.save(id_list[identifer])
468 | save_tag(tag, data)
469 |
470 | elif isinstance(resource, Shape):
471 | Console.progress_bar("Shapes writing...", written_shapes, self.shapes_count)
472 | tag, data = resource.save(self, id_list[identifer])
473 | save_tag(tag, data)
474 | written_shapes += 1
475 | if written_shapes == self.shapes_count:
476 | print()
477 |
478 | elif isinstance(resource, TextField):
479 | Console.progress_bar("Text fields writing...", written_fields, self.text_fields_count)
480 | tag, data = resource.save(id_list[identifer])
481 | save_tag(tag, data)
482 | written_fields += 1
483 | if written_fields == self.text_fields_count:
484 | print()
485 |
486 | elif isinstance(resource, MatrixBank):
487 | written_transforms = 0
488 | if resource.index > 0:
489 | tag, data = resource.save()
490 | save_tag(tag, data)
491 |
492 | for matrix in resource.matrices:
493 | Console.progress_bar(f"Matrices bank {resource.index} writing...", written_transforms, len(resource.matrices))
494 |
495 | matrix.save(self)
496 |
497 | written_transforms += 1
498 | print()
499 | written_transforms = 0
500 | for color_transform in resource.color_transforms:
501 | Console.progress_bar(f"Colors bank {resource.index} writing...", written_transforms,
502 | len(resource.color_transforms))
503 | color_transform.save(self)
504 |
505 | written_transforms += 1
506 | print()
507 |
508 | elif isinstance(resource, MovieClip):
509 | Console.progress_bar("Movieclips writing...", written_movieclips, self.movieclips_count)
510 | tag, data = resource.save(id_list[identifer], id_list)
511 | save_tag(tag, data)
512 | written_movieclips += 1
513 | if written_movieclips == self.movieclips_count:
514 | print()
515 |
516 |
517 | self.writer.write(bytes(5)) # end tag
518 |
--------------------------------------------------------------------------------
/lib/sc/text_field.py:
--------------------------------------------------------------------------------
1 | from .writable import Writable
2 |
3 | class TextField(Writable):
4 | def __init__(self) -> None:
5 | super().__init__()
6 |
7 | self.font_name: str = None
8 | self.font_color: int = -1
9 | self.outline_color: int = None # -1
10 | self.font_size: int = 0
11 | self.font_align: int = 0
12 |
13 | self.bold: bool = False
14 | self.italic: bool = False
15 | self.multiline: bool = False
16 | self.outline: bool = False
17 |
18 | self.left_corner: int = 0
19 | self.top_corner: int = 0
20 | self.right_corner: int = 0
21 | self.bottom_corner: int = 0
22 |
23 | self.text: str = None
24 |
25 | self.flag1: bool = None # False
26 | self.flag2: bool = None # False
27 | self.flag3: bool = None # False
28 |
29 | self.c1: int = None # 0
30 | self.c2: int = None # 0
31 |
32 | def load(self, swf, tag: int):
33 | id = swf.reader.read_ushort()
34 |
35 | self.font_name = swf.reader.read_ascii()
36 | self.font_color = swf.reader.read_int()
37 |
38 | self.bold = swf.reader.read_bool()
39 | self.italic = swf.reader.read_bool()
40 | self.multiline = swf.reader.read_bool()
41 | swf.reader.read_bool() # unused
42 |
43 | self.font_align = swf.reader.read_uchar()
44 | self.font_size = swf.reader.read_uchar()
45 |
46 | self.top_corner = swf.reader.read_short()
47 | self.bottom_corner = swf.reader.read_short()
48 | self.left_corner = swf.reader.read_short()
49 | self.right_corner = swf.reader.read_short()
50 |
51 | self.outline = swf.reader.read_bool()
52 | self.text = swf.reader.read_ascii()
53 |
54 | if tag == 7:
55 | return id
56 |
57 | self.flag1 = swf.reader.read_bool()
58 |
59 | if tag > 15:
60 | self.flag2 = tag != 25
61 |
62 | if tag > 20:
63 | self.outline_color = swf.reader.read_int()
64 |
65 | if tag > 25:
66 | self.c1 = swf.reader.read_short()
67 | swf.reader.read_short() # unused
68 |
69 | if tag > 33:
70 | self.c2 = swf.reader.read_short()
71 |
72 | if tag > 43:
73 | self.flag3 = swf.reader.read_bool()
74 |
75 | return id
76 |
77 | def save(self, id: int):
78 | super().save()
79 |
80 | tag = 7
81 |
82 | self.write_ushort(id)
83 |
84 | self.write_ascii(self.font_name)
85 | self.write_int(self.font_color)
86 |
87 | self.write_bool(self.bold)
88 | self.write_bool(self.italic)
89 | self.write_bool(self.multiline)
90 | self.write_bool(False) # unused
91 |
92 | self.write_uchar(self.font_align)
93 | self.write_uchar(self.font_size)
94 |
95 | self.write_short(self.top_corner)
96 | self.write_short(self.bottom_corner)
97 | self.write_short(self.left_corner)
98 | self.write_short(self.right_corner)
99 |
100 | self.write_bool(self.outline)
101 | self.write_ascii(self.text)
102 |
103 | if self.flag1 is not None:
104 | tag = 15
105 | self.write_bool(self.flag1)
106 |
107 | if self.flag2 is not None:
108 | if self.flag2:
109 | tag = 20
110 | else:
111 | if self.outline_color is not None:
112 | tag = 21
113 | self.write_int(self.outline_color)
114 |
115 | if self.c1 is not None:
116 | tag = 25
117 | self.write_short(self.c1)
118 | self.write_short(0) # unused
119 |
120 | if self.c2 is not None:
121 | tag = 33
122 | self.write_short(self.c2)
123 |
124 | if self.flag3 is not None:
125 | tag = 43
126 | if self.flag3:
127 | tag = 44
128 | self.write_bool(self.flag3)
129 |
130 | return tag, self.buffer
131 |
132 | def __eq__(a, b):
133 | if type(a) == type(b):
134 | if a.font_name == b.font_name\
135 | and a.font_color == b.font_color\
136 | and a.outline_color == b.outline_color\
137 | and a.font_size == b.font_size\
138 | and a.font_size == b.font_size\
139 | and a.font_align == b.font_align\
140 | and a.bold == b.bold\
141 | and a.italic == b.italic\
142 | and a.multiline == b.multiline\
143 | and a.left_corner == b.left_corner\
144 | and a.top_corner == b.top_corner\
145 | and a.right_corner == b.right_corner\
146 | and a.bottom_corner == b.bottom_corner\
147 | and a.text == b.text\
148 | and a.flag1 == b.flag1\
149 | and a.flag2 == b.flag2\
150 | and a.flag3 == b.flag3\
151 | and a.c1 == b.c1\
152 | and a.c2 == b.c2:
153 | return True
154 | return False
155 |
--------------------------------------------------------------------------------
/lib/sc/texture.py:
--------------------------------------------------------------------------------
1 | from .writable import Writable
2 |
3 | from PIL import Image
4 |
5 | from lib.console import Console
6 |
7 | PACKER_FILTER_TABLE = {
8 | "LINEAR": "GL_LINEAR",
9 | "NEAREST": "GL_NEAREST",
10 | "MIPMAP": "GL_LINEAR_MIPMAP_NEAREST"
11 | }
12 |
13 | PACKER_PIXEL_TYPES =[
14 | "RGBA8888",
15 | "BGRA8888",
16 | "RGBA4444",
17 | "RGBA5551",
18 | "RGB565",
19 | "RGBA8888",
20 | "ALPHA_INTENSITY",
21 | "RGBA8888",
22 | "RGBA8888",
23 | "ALPHA"
24 | ]
25 |
26 | MODES_TABLE = {
27 | "GL_RGBA": "RGBA",
28 | "GL_RGB": "RGB",
29 | "GL_LUMINANCE_ALPHA": "LA",
30 | "GL_LUMINANCE": "L"
31 | }
32 |
33 | CHANNLES_TABLE = {
34 | "RGBA": 4,
35 | "RGB": 3,
36 | "LA": 2,
37 | "L": 1
38 | }
39 |
40 | PIXEL_TYPES = [
41 | "GL_UNSIGNED_BYTE",
42 | "GL_UNSIGNED_BYTE",
43 | "GL_UNSIGNED_SHORT_4_4_4_4",
44 | "GL_UNSIGNED_SHORT_5_5_5_1",
45 | "GL_UNSIGNED_SHORT_5_6_5",
46 | "GL_UNSIGNED_BYTE",
47 | "GL_UNSIGNED_BYTE",
48 | "GL_UNSIGNED_BYTE",
49 | "GL_UNSIGNED_BYTE",
50 | "GL_UNSIGNED_SHORT_4_4_4_4",
51 | "GL_UNSIGNED_BYTE"
52 | ]
53 |
54 | PIXEL_FORMATS = [
55 | "GL_RGBA",
56 | "GL_RGBA",
57 | "GL_RGBA",
58 | "GL_RGBA",
59 | "GL_RGB",
60 | "GL_RGBA",
61 | "GL_LUMINANCE_ALPHA",
62 | "GL_RGBA",
63 | "GL_RGBA",
64 | "GL_RGBA",
65 | "GL_LUMINANCE"
66 | ]
67 |
68 | PIXEL_INTERNAL_FORMATS = [
69 | "GL_RGBA8",
70 | "GL_RGBA8",
71 | "GL_RGBA4",
72 | "GL_RGB5_A1",
73 | "GL_RGB565",
74 | "GL_RGBA8",
75 | "GL_LUMINANCE8_ALPHA8",
76 | "GL_RGBA8",
77 | "GL_RGBA8",
78 | "GL_RGBA4",
79 | "GL_LUMINANCE8"
80 | ]
81 |
82 | def read_rgba8(swf):
83 | r = swf.reader.read_uchar()
84 | g = swf.reader.read_uchar()
85 | b = swf.reader.read_uchar()
86 | a = swf.reader.read_uchar()
87 | return r, g, b, a
88 |
89 |
90 | def read_rgba4(swf):
91 | p = swf.reader.read_ushort()
92 | r = ((p >> 12) & 15) << 4
93 | g = ((p >> 8) & 15) << 4
94 | b = ((p >> 4) & 15) << 4
95 | a = (p & 15) << 4
96 | return r, g, b, a
97 |
98 |
99 | def read_rgb5_a1(swf):
100 | p = swf.reader.read_ushort()
101 | r = ((p >> 11) & 31) << 3
102 | g = ((p >> 6) & 31) << 3
103 | b = ((p >> 1) & 31) << 3
104 | a = (p & 255) << 7
105 | return r, g, b, a
106 |
107 |
108 | def read_rgb565(swf):
109 | p = swf.reader.read_ushort()
110 | r = ((p >> 11) & 31) << 3
111 | g = ((p >> 5) & 63) << 2
112 | b = (p & 31) << 3
113 | return r, g, b
114 |
115 |
116 | def read_luminance8_alpha8(swf):
117 | a = swf.reader.read_uchar()
118 | l = swf.reader.read_uchar()
119 | return l, a
120 |
121 |
122 | def read_luminance8(swf):
123 | return swf.reader.read_uchar()
124 |
125 |
126 | def write_rgba8(swf, pixel):
127 | r, g, b, a = pixel
128 | swf.write_uchar(r)
129 | swf.write_uchar(g)
130 | swf.write_uchar(b)
131 | swf.write_uchar(a)
132 |
133 |
134 | def write_rgba4(swf, pixel):
135 | r, g, b, a = pixel
136 | swf.write_ushort(a >> 4 | b >> 4 << 4 | g >> 4 << 8 | r >> 4 << 12)
137 |
138 |
139 | def write_rgb5_a1(swf, pixel):
140 | r, g, b, a = pixel
141 | swf.write_ushort(a >> 7 | b >> 3 << 1 | g >> 3 << 6 | r >> 3 << 11)
142 |
143 |
144 | def write_rgb565(swf, pixel):
145 | r, g, b = pixel
146 | swf.write_ushort(int(b >> 3 | g >> 2 << 5 | r >> 3 << 11))
147 |
148 |
149 | def write_luminance8_alpha8(swf, pixel):
150 | l, a = pixel
151 | swf.write_ushort(l << 8 | a)
152 |
153 |
154 | def write_luminance8(swf, pixel):
155 | swf.write_uchar(int(pixel))
156 |
157 |
158 | PIXEL_READ_FUNCTIONS = {
159 | "GL_RGBA8": read_rgba8,
160 | "GL_RGBA4": read_rgba4,
161 | "GL_RGB5_A1": read_rgb5_a1,
162 | "GL_RGB565": read_rgb565,
163 | "GL_LUMINANCE8_ALPHA8": read_luminance8_alpha8,
164 | "GL_LUMINANCE8": read_luminance8
165 | }
166 |
167 | PIXEL_WRITE_FUNCTIONS = {
168 | "GL_RGBA8": write_rgba8,
169 | "GL_RGBA4": write_rgba4,
170 | "GL_RGB5_A1": write_rgb5_a1,
171 | "GL_RGB565": write_rgb565,
172 | "GL_LUMINANCE8_ALPHA8": write_luminance8_alpha8,
173 | "GL_LUMINANCE8": write_luminance8
174 | }
175 |
176 |
177 | class SWFTexture(Writable):
178 | def __init__(self) -> None:
179 | self.channels: int = 4
180 |
181 | self.pixel_format: str = "GL_RGBA"
182 | self.pixel_internal_format: str = "GL_RGBA8"
183 | self.pixel_type: str = "GL_UNSIGNED_BYTE"
184 |
185 | self.mag_filter: str = "GL_LINEAR"
186 | self.min_filter: str = "GL_NEAREST"
187 |
188 | self.linear: bool = True
189 | self.downscaling: bool = True
190 |
191 | self.width: int = 0
192 | self.height: int = 0
193 |
194 | self._image: Image = None
195 |
196 | def load(self, swf, tag: int, has_external_texture: bool):
197 | pixel_type_index = swf.reader.read_uchar()
198 |
199 | self.pixel_format = PIXEL_FORMATS[pixel_type_index]
200 | self.pixel_internal_format = PIXEL_INTERNAL_FORMATS[pixel_type_index]
201 | self.pixel_type = PIXEL_TYPES[pixel_type_index]
202 |
203 | self.mag_filter = "GL_LINEAR"
204 | self.min_filter = "GL_NEAREST"
205 | if tag in [16, 19, 29]:
206 | self.mag_filter = "GL_LINEAR"
207 | self.min_filter = "GL_LINEAR_MIPMAP_NEAREST"
208 | elif tag == 34:
209 | self.mag_filter = "GL_NEAREST"
210 | self.min_filter = "GL_NEAREST"
211 |
212 | self.linear = tag not in [27, 28, 29]
213 | self.downscaling = tag in [1, 16, 28, 29]
214 |
215 | self.width = swf.reader.read_ushort()
216 | self.height = swf.reader.read_ushort()
217 |
218 | if not has_external_texture:
219 | Console.info(
220 | f"SWFTexture: {self.width}x{self.height} - Format: {self.pixel_type} {self.pixel_format} {self.pixel_internal_format}")
221 |
222 | self._image = Image.new(MODES_TABLE[self.pixel_format], (self.width, self.height))
223 | loaded = self._image.load()
224 |
225 | self.channels = CHANNLES_TABLE[self._image.mode]
226 |
227 | read_pixel = PIXEL_READ_FUNCTIONS[self.pixel_internal_format]
228 |
229 | if self.linear:
230 | for y in range(self.height):
231 | for x in range(self.width):
232 | loaded[x, y] = read_pixel(swf)
233 |
234 | Console.progress_bar("Loading texture data...", y, self.height)
235 | print()
236 |
237 | else:
238 | block_size = 32
239 |
240 | x_blocks = self.width // block_size
241 | y_blocks = self.height // block_size
242 |
243 | for y_block in range(y_blocks + 1):
244 | for x_block in range(x_blocks + 1):
245 | for y in range(block_size):
246 | pixel_y = (y_block * block_size) + y
247 |
248 | if pixel_y >= self.height:
249 | break
250 |
251 | for x in range(block_size):
252 | pixel_x = (x_block * block_size) + x
253 |
254 | if pixel_x >= self.width:
255 | break
256 |
257 | loaded[pixel_x, pixel_y] = read_pixel(swf)
258 |
259 | Console.progress_bar("Loading splitted texture data...", y_block, y_blocks + 1)
260 | print()
261 |
262 | def save(self, has_external_texture: bool):
263 | super().save()
264 |
265 | pixel_type_index = PIXEL_INTERNAL_FORMATS.index(self.pixel_internal_format)
266 |
267 | tag = 1
268 | if (self.mag_filter, self.min_filter) == ("GL_LINEAR", "GL_NEAREST"):
269 | if not self.linear:
270 | tag = 27 if not self.downscaling else 28
271 | else:
272 | tag = 24 if not self.downscaling else 1
273 |
274 | if (self.mag_filter, self.min_filter) == ("GL_LINEAR", "GL_LINEAR_MIPMAP_NEAREST"):
275 | if not self.linear and not self.downscaling:
276 | tag = 29
277 | else:
278 | tag = 19 if not self.downscaling else 16
279 |
280 | if (self.mag_filter, self.min_filter) == ("GL_NEAREST", "GL_NEAREST"):
281 | tag = 34
282 |
283 | self.write_uchar(pixel_type_index)
284 |
285 | self.write_ushort(self.width)
286 | self.write_ushort(self.height)
287 |
288 | Console.info(
289 | f"SWFTexture: {self.width}x{self.height} - Format: {self.pixel_type} {self.pixel_format} {self.pixel_internal_format}")
290 |
291 | if not has_external_texture:
292 | loaded = self._image.load()
293 |
294 | write_pixel = PIXEL_WRITE_FUNCTIONS[self.pixel_internal_format]
295 |
296 | if not self.linear:
297 | loaded_clone = self._image.copy().load()
298 |
299 | def add_pixel(pixel: tuple):
300 | loaded[pixel_index % self.width, pixel_index // self.width] = pixel
301 |
302 | block_size = 32
303 |
304 | x_blocks = self.width // block_size
305 | y_blocks = self.height // block_size
306 |
307 | pixel_index = 0
308 | for y_block in range(y_blocks + 1):
309 | for x_block in range(x_blocks + 1):
310 | for y in range(block_size):
311 | pixel_y = (y_block * block_size) + y
312 |
313 | if pixel_y >= self.height:
314 | break
315 |
316 | for x in range(block_size):
317 | pixel_x = (x_block * block_size) + x
318 |
319 | if pixel_x >= self.width:
320 | break
321 |
322 | add_pixel(loaded_clone[pixel_x, pixel_y])
323 | pixel_index += 1
324 |
325 | loaded = loaded_clone
326 |
327 | for y in range(self.height):
328 | Console.progress_bar("Writing texture data...", y, self.height)
329 | for x in range(self.width):
330 | write_pixel(self, loaded[x, y])
331 |
332 | print()
333 |
334 | return tag, self.buffer
335 |
336 | def get_image(self):
337 | return self._image
338 | def set_image(self, img: Image):
339 | self._image = img
340 |
341 | self.channels = CHANNLES_TABLE[self._image.mode]
342 | self.width, self.height = self._image.size
343 |
344 | if self.channels == 4:
345 | self.pixel_format = "GL_RGBA"
346 |
347 | if self.pixel_type == "GL_UNSIGNED_BYTE":
348 | self.pixel_internal_format = "GL_RGBA8"
349 |
350 | elif self.pixel_type == "GL_UNSIGNED_SHORT_4_4_4_4":
351 | self.pixel_internal_format = "GL_RGBA4"
352 |
353 | else:
354 | self.pixel_internal_format = "GL_RGB5_A1"
355 |
356 | elif self.channels == 3:
357 | self.pixel_format = "GL_RGB"
358 | self.pixel_type = "GL_UNSIGNED_SHORT_5_6_5"
359 | self.pixel_internal_format = "GL_RGB565"
360 |
361 | elif self.channels == 2:
362 | self.pixel_format = "GL_LUMINANCE_ALPHA"
363 | self.pixel_type = "GL_UNSIGNED_BYTE"
364 | self.pixel_internal_format = "GL_LUMINANCE8_ALPHA8"
365 |
366 | else:
367 | self.pixel_format = "GL_LUMINANCE"
368 | self.pixel_type = "GL_UNSIGNED_BYTE"
369 | self.pixel_internal_format = "GL_LUMINANCE8"
370 |
371 |
372 |
--------------------------------------------------------------------------------
/lib/sc/writable.py:
--------------------------------------------------------------------------------
1 | from lib.utils import BinaryWriter
2 |
3 |
4 | class Writable(BinaryWriter):
5 | def __init__(self) -> None:
6 | pass
7 |
8 | def save(self):
9 | super().__init__()
10 |
--------------------------------------------------------------------------------
/lib/sc_import.py:
--------------------------------------------------------------------------------
1 | import copy
2 |
3 | from lib.console import Console
4 | from PIL import Image
5 |
6 | from lib.sc import *
7 | from lib.fla import *
8 |
9 | shape_bitmaps_uvs = []
10 | shape_bitmaps_twips = []
11 | shapes_with_nine_slices = {}
12 |
13 |
14 | def sc_to_fla(filepath):
15 | swf = SupercellSWF()
16 | swf.load(filepath)
17 |
18 | projectdir = os.path.splitext(swf.filename)[0]
19 |
20 | fla = prepare_document(projectdir)
21 |
22 | startup = DOMDocument("lib/scwmake_credit")
23 | startup.load()
24 |
25 | fla.timelines = startup.timelines
26 |
27 | proceed_resources(fla, swf)
28 |
29 | XFL.save(fla)
30 |
31 |
32 | def prepare_document(path):
33 | Console.info("Creating DOMDocument for Adobe Animate...")
34 |
35 | fla = DOMDocument(path)
36 |
37 | fla.xfl_version = 2.971
38 |
39 | fla.width = 1280
40 | fla.height = 720
41 | fla.frame_rate = 30
42 | fla.current_timeline = 1
43 |
44 | fla.background_color = 0x666666
45 |
46 | fla.creator_info = "File generated with SC tool by SCW Make! (VK: vk.com/scwmake, GITHUB: github.com/scwmake/SC)"
47 |
48 | fla.folders.add(DOMFolderItem("shapes"))
49 | fla.folders.add(DOMFolderItem("movieclips"))
50 | fla.folders.add(DOMFolderItem("exports"))
51 | fla.folders.add(DOMFolderItem("resources"))
52 |
53 | return fla
54 |
55 |
56 | def proceed_resources(fla, swf):
57 | resource_counter = 0
58 | for id, resource in swf.resources.items():
59 | Console.progress_bar("Converting SupercellFlash resources to Adobe Animate...", resource_counter,
60 | swf.movieclips_count + swf.shapes_count)
61 | if isinstance(resource, Shape):
62 | convert_shape(fla, swf, id, resource)
63 |
64 | elif isinstance(resource, MovieClip):
65 | export_names = swf.exports[id] if id in swf.exports else None
66 | convert_movieclip(fla, swf, id, resource, export_names)
67 | else:
68 | continue
69 | resource_counter += 1
70 |
71 | print()
72 |
73 | def convert_shape(fla, swf, id, shape):
74 | graphic = DOMSymbolItem(f"shapes/shape_{id}", "graphic")
75 | graphic.timeline.name = f"shape_{id}"
76 |
77 | for bitmap_index, bitmap in enumerate(reversed(shape.bitmaps)):
78 | layer = DOMLayer(f"shape_layer_{bitmap_index}", False)
79 | frame = DOMFrame(index=0)
80 |
81 | uv_coords = bitmap.uv_coords
82 | xy_coords = bitmap.xy_coords
83 |
84 | if uv_coords.count(uv_coords[0]) == len(uv_coords): # color fills is always 1x1
85 | color_fill = DOMShape()
86 | texture = swf.textures[bitmap.texture_index]
87 | image = texture.get_image()
88 |
89 | x, y = uv_coords[0]
90 | pixel = image.getpixel((int(x), int(y)))
91 |
92 | color = 0
93 | alpha = 1.0
94 |
95 | if len(pixel) in (4, 3):
96 | color |= pixel[0] << 16
97 | color |= (pixel[1] << 16) >> 8
98 | color |= pixel[2]
99 |
100 | if len(pixel) == 4:
101 | alpha = pixel[3] / 255
102 |
103 | elif len(pixel) in (2, 1):
104 | color |= pixel[0] << 16
105 | color |= (pixel[0] << 16) >> 8
106 | color |= pixel[0]
107 |
108 | if len(pixel) == 2:
109 | alpha = pixel[1] / 255
110 |
111 | color_fill_style = FillStyle(1)
112 | color_fill_style.data = SolidColor(color, alpha)
113 |
114 | final_edges = ""
115 | for x, curr in enumerate(xy_coords):
116 | nxt = xy_coords[(x + 1) % len(xy_coords)]
117 | final_edges += f"!{curr[0] * 20} {curr[1] * 20}|{nxt[0] * 20} {nxt[1] * 20}" # converting pixels to twips
118 |
119 | color_fill_edge = Edge()
120 | color_fill_edge.edges = final_edges
121 | color_fill_edge.fill_style1 = 1
122 |
123 | color_fill.fills.append(color_fill_style)
124 | color_fill.edges.append(color_fill_edge)
125 |
126 | frame.elements.append(color_fill)
127 |
128 | else:
129 | if uv_coords not in shape_bitmaps_uvs:
130 | shape_bitmaps_uvs.append(uv_coords)
131 |
132 | uvs_index = shape_bitmaps_uvs.index(uv_coords)
133 | resource_name = f"M {uvs_index}"
134 |
135 | matrix, twips, rotation, mirror = bitmap.get_matrix(use_nearest=True)
136 | shape_bitmaps_twips.append(twips)
137 |
138 | bitmap_item = DOMBitmapItem(f"resources/{uvs_index}", f"{resource_name}.dat")
139 |
140 | bitmap_item.quality = 100
141 | bitmap_item.use_imported_jpeg_data = False
142 | bitmap_item.allow_smoothing = swf.textures[bitmap.texture_index].linear != True
143 | bitmap_item.source_external_filepath = f"LIBRARY/resources/{uvs_index}.png"
144 |
145 | sprite = bitmap.get_image(swf)
146 | sprite = sprite.rotate(-rotation, expand = True)
147 | if mirror:
148 | sprite = sprite.transpose(Image.FLIP_LEFT_RIGHT)
149 | bitmap_item.image = sprite
150 |
151 | fla.media[uvs_index] = bitmap_item
152 |
153 | else:
154 | matrix, _, _, _ = bitmap.get_matrix(shape_bitmaps_twips[shape_bitmaps_uvs.index(uv_coords)])
155 |
156 | uvs_index = shape_bitmaps_uvs.index(uv_coords)
157 |
158 | bitmap_instance = DOMBitmapInstance()
159 | bitmap_instance.library_item_name = f"resources/{uvs_index}"
160 |
161 | a, c, b, d, tx, ty = matrix.params
162 | bitmap_instance.matrix = Matrix(a, b, c, d, tx, ty)
163 |
164 | frame.elements.append(bitmap_instance)
165 |
166 | layer.frames.append(frame)
167 | graphic.timeline.layers.append(layer)
168 |
169 | fla.symbols.add(graphic.name, graphic)
170 |
171 |
172 | def patch_shape_nine_slice(fla, id, shape):
173 | shape_slice = DOMGroup()
174 |
175 | shape_symbol = fla.symbols.get(f"shapes/shape_{id}")
176 |
177 | for l, layer in enumerate(shape_symbol.timeline.layers):
178 | for f, frame in enumerate(layer.frames):
179 | for e, element in enumerate(frame.elements):
180 | if isinstance(element, DOMBitmapInstance):
181 | element_media = fla.media[int(element.library_item_name.split("/")[1])]
182 | element_sprite = element_media.image
183 | w, h = element_sprite.size
184 |
185 | extrude_sprite = element_sprite.resize((w + 2, h + 2))
186 | extrude_sprite.paste(element_sprite, (1, 1))
187 | element_media.image = extrude_sprite
188 |
189 | sprite_twip = [[0, 0], [w, 0], [w, h], [0, h]]
190 |
191 | slice = DOMShape()
192 | slice.is_drawing_object = True
193 |
194 | edge_shape = ""
195 | for x, curr in enumerate(sprite_twip):
196 | nxt = sprite_twip[(x + 1) % len(sprite_twip)]
197 | edge_shape += f"!{round(curr[0] * 20)} {round(curr[1] * 20)}|{round(nxt[0] * 20)} {round(nxt[1] * 20)}"
198 |
199 | slice_style = FillStyle(1)
200 | slice_bitmap_fill = BitmapFill(element.library_item_name)
201 | slice_bitmap_fill.matrix = Matrix(20, 0, 0, 20, -1, -1)
202 | slice_style.data = slice_bitmap_fill
203 |
204 | slice_shape = Edge()
205 | slice_shape.edges = edge_shape
206 | slice_shape.fill_style1 = 1
207 |
208 | slice.fills.append(slice_style)
209 | slice.edges.append(slice_shape)
210 | slice.matrix = element.matrix
211 |
212 | shape_slice.members.append(slice)
213 |
214 | shape_symbol.timeline.layers[l].frames[f].elements[e] = slice
215 |
216 | shapes_with_nine_slices[id] = shape_slice
217 | return shape_slice
218 |
219 |
220 | def convert_movieclip(fla, swf, id, movieclip: MovieClip, export_names: list = None):
221 | movie = DOMSymbolItem()
222 |
223 | layers_instance = []
224 | layers_order = []
225 | symbols_instance = []
226 |
227 | masked_layers = {}
228 | masked_layers_order = {}
229 |
230 | # Prepearing layers
231 | for i, bind in enumerate(movieclip.binds):
232 | bind_resource = swf.resources[bind['id']]
233 | if isinstance(bind_resource, MovieClipModifier):
234 | layers_instance.append(None)
235 | symbols_instance.append(bind_resource)
236 | else:
237 | # Layers
238 | bind_layer = DOMLayer(f"Layer_{i}")
239 | if bind["name"]:
240 | bind_layer.name = bind["name"]
241 |
242 | # Layer order
243 | layers_order.append(i)
244 |
245 | # Symbols instance
246 | if isinstance(bind_resource, Shape):
247 | if movieclip.nine_slice:
248 | if id in shapes_with_nine_slices:
249 | bind_instance = shapes_with_nine_slices[id]
250 | else:
251 | bind_instance = patch_shape_nine_slice(fla, bind['id'], bind_resource)
252 |
253 | else:
254 | bind_instance = DOMSymbolInstance(library_item_name=f"shapes/shape_{bind['id']}")
255 |
256 | elif isinstance(bind_resource, MovieClip):
257 | if bind["id"] in swf.exports and f"movieclips/movieclip_{bind['id']}" not in fla.symbols:
258 | convert_movieclip(fla, swf, bind["id"], bind_resource)
259 |
260 | bind_instance = DOMSymbolInstance(name=bind["name"],
261 | library_item_name=f"movieclips/movieclip_{bind['id']}")
262 | bind_instance.blend_mode = bind['blend']
263 |
264 |
265 |
266 | elif isinstance(bind_resource, TextField):
267 | bind_instance = DOMDynamicText(name=bind["name"])
268 |
269 | bind_instance.width = bind_resource.left_corner - bind_resource.top_corner
270 | bind_instance.height = bind_resource.right_corner - bind_resource.bottom_corner
271 | bind_instance.top = bind_resource.bottom_corner
272 | bind_instance.left = bind_resource.top_corner
273 |
274 | if bind_resource.multiline:
275 | bind_instance.line_type = "multiline no wrap"
276 |
277 | text_run = DOMTextRun()
278 | text_attrs = DOMTextAttrs()
279 |
280 | match bind_resource.font_align:
281 | case 18:
282 | text_attrs.alignment = "center"
283 | case _:
284 | pass
285 |
286 | if bind_resource.text is not None:
287 | text_run.characters = bind_resource.text
288 |
289 | text_attrs.face = bind_resource.font_name
290 | text_attrs.size = bind_resource.font_size
291 | text_attrs.bitmap_size = bind_resource.font_size * 20
292 |
293 | if bind_resource.bold or bind_resource.italic:
294 | text_attrs.face += "-"
295 |
296 | if bind_resource.bold:
297 | text_attrs.face += "Bold"
298 |
299 | if bind_resource.italic:
300 | text_attrs.face += "Italic"
301 |
302 | text_attrs.fill_color = bind_resource.font_color & 0xFFFFFF00
303 | text_attrs.alpha = (bind_resource.font_color & 0x000000FF) / 255
304 |
305 | if bind_resource.outline_color:
306 | glow_filter = GlowFilter()
307 |
308 | glow_filter.blur_x = 2
309 | glow_filter.blur_y = 2
310 |
311 | glow_filter.color = bind_resource.outline_color & 0xFFFFFF00
312 |
313 | glow_filter.strength = 15
314 |
315 | if bind_resource.c1:
316 | glow_filter.strength = bind_resource.c1 / 65535
317 |
318 | bind_instance.filters.append(glow_filter)
319 |
320 | if bind_resource.c2:
321 | drop_shadow_filter = DrowShadowFilter()
322 |
323 | drop_shadow_filter.angle = (bind_resource.c2 / 65535) * 360
324 |
325 | drop_shadow_filter.blur_x = 4
326 | drop_shadow_filter.blur_y = 4
327 |
328 | drop_shadow_filter.distance = 4
329 |
330 | bind_instance.filters.append(drop_shadow_filter)
331 |
332 | text_run.text_attrs.append(text_attrs)
333 |
334 | bind_instance.text_runs.append(text_run)
335 |
336 | else:
337 | print("Unkwnown resource type")
338 | raise TypeError()
339 |
340 | symbols_instance.append(bind_instance)
341 | layers_instance.append(bind_layer)
342 |
343 | # Converting frames
344 | for i, frame in enumerate(movieclip.frames):
345 | elements = [element['bind'] for element in frame.elements]
346 | elements_idx = [element for element in elements if not isinstance(swf.resources[movieclip.binds[element]['id']], MovieClipModifier)]
347 |
348 | for element in elements_idx:
349 | for comparative in elements_idx:
350 | if comparative != element:
351 | element_pos = elements_idx.index(element)
352 | bind_pos = layers_order.index(element)
353 |
354 | comparative_pos = elements_idx.index(comparative)
355 | cmp_bind_pos = layers_order.index(comparative)
356 |
357 | frame_position = element_pos > comparative_pos # higher if True else lower
358 | binds_position = bind_pos > cmp_bind_pos
359 |
360 | if frame_position != binds_position:
361 | layers_order.insert(layers_order.index(element), layers_order.pop(cmp_bind_pos))
362 | mask = False
363 | masked = False
364 | mask_layer = None
365 | for layer_idx, curr_layer in enumerate(layers_instance):
366 | if curr_layer is None:
367 | modifer = symbols_instance[layer_idx].modifier
368 |
369 | if modifer == modifer.Mask:
370 | mask = True
371 | elif modifer == modifer.Masked:
372 | mask = False
373 | masked = True
374 | elif modifer == modifer.Unmasked:
375 | masked = False
376 | mask_layer = None
377 |
378 | else:
379 | if layer_idx in elements:
380 | if mask:
381 | curr_layer.layer_type = "mask"
382 | curr_layer.is_locked = True
383 | mask_layer = curr_layer
384 | elif masked:
385 | if mask_layer not in masked_layers:
386 | masked_layers[mask_layer] = []
387 | masked_layers_order[mask_layer] = []
388 |
389 | if curr_layer not in masked_layers[mask_layer]:
390 | masked_layers[mask_layer].append(curr_layer)
391 | masked_layers_order[mask_layer].append(masked_layers[mask_layer].index(curr_layer))
392 |
393 | element = frame.elements[elements.index(layer_idx)]
394 |
395 | if curr_layer.frames and i:
396 | if element in movieclip.frames[i-1].elements:
397 | curr_layer.frames[-1].duration += 1
398 | continue
399 |
400 | layer_frame = DOMFrame(i)
401 | instance = copy.deepcopy(symbols_instance[layer_idx])
402 |
403 |
404 | if element["matrix"] != 0xFFFF:
405 | m = swf.matrix_banks[movieclip.matrix_bank].matrices[element["matrix"]]
406 | instance.matrix = Matrix(m.a, m.b, m.c, m.d, m.tx, m.ty)
407 |
408 | if element["color"] != 0xFFFF:
409 | c = swf.matrix_banks[movieclip.matrix_bank].color_transforms[element["color"]]
410 | bind_color = Color()
411 | bind_color.red_offset = c.r_add
412 | bind_color.green_offset = c.g_add
413 | bind_color.blue_offset = c.b_add
414 | bind_color.alpha_offset = 0
415 | bind_color.red_multiplier = c.r_mul
416 | bind_color.green_multiplier = c.g_mul
417 | bind_color.blue_multiplier = c.b_mul
418 | bind_color.alpha_multiplier = c.a_mul
419 | instance.color = bind_color
420 |
421 | layer_frame.elements.append(instance)
422 | curr_layer.frames.append(layer_frame)
423 |
424 | else:
425 | if curr_layer.frames and len(curr_layer.frames[-1].elements) == 0:
426 | curr_layer.frames[-1].duration += 1
427 | else:
428 | curr_layer.frames.append(DOMFrame(i))
429 |
430 | layers_order = [o for o in layers_order if
431 | layers_instance[o] not in [masked_layers[order_key][value] for order_key, order_list in
432 | masked_layers_order.items() for value in order_list]]
433 |
434 | for idx in reversed(layers_order):
435 | movie.timeline.layers.append(layers_instance[idx])
436 |
437 | for layer_key in masked_layers_order:
438 | if layer_key is not None:
439 | for idx in masked_layers_order[layer_key]:
440 | mask_layer_index = movie.timeline.layers.index(layer_key)
441 | masked_layer = masked_layers[layer_key][idx]
442 | masked_layer.is_locked = True
443 | masked_layer.parent_layer_index = mask_layer_index
444 | movie.timeline.layers.insert(mask_layer_index + 1, masked_layer)
445 |
446 | if movieclip.nine_slice:
447 | x, y, width, height = movieclip.nine_slice
448 |
449 | movie.scale_grid_left = x
450 | movie.scale_grid_top = y
451 | movie.scale_grid_right = x + width
452 | movie.scale_grid_bottom = y + height
453 |
454 | if isinstance(export_names, list):
455 | for export in export_names:
456 | movie_instance = copy.deepcopy(movie)
457 | movie_instance.name = f"exports/{export}"
458 | movie_instance.timeline.name = export
459 | fla.symbols.add(movie_instance.name, movie_instance)
460 | return
461 |
462 | movie.name = f"movieclips/movieclip_{id}"
463 | movie.timeline.name = f"movieclip_{id}"
464 | fla.symbols.add(movie.name, movie)
465 |
--------------------------------------------------------------------------------
/lib/scwmake_credit/META-INF/metadata.xml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sc-workshop/SC/fe797f56b7fe71196a8673184007e00e3f69be05/lib/scwmake_credit/META-INF/metadata.xml
--------------------------------------------------------------------------------
/lib/scwmake_credit/MobileSettings.xml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sc-workshop/SC/fe797f56b7fe71196a8673184007e00e3f69be05/lib/scwmake_credit/MobileSettings.xml
--------------------------------------------------------------------------------
/lib/scwmake_credit/PublishSettings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 1
5 | 1
6 | 0
7 | 0
8 | 1
9 | 0
10 | 0
11 | 0
12 | 0
13 | 0
14 | 1
15 | 1
16 | 1
17 | 1
18 | 1
19 | 1
20 | 1
21 | 1
22 | 1
23 | scwmake_credit.swf
24 | scwmake_credit.exe
25 | scwmake_credit.app
26 | scwmake_credit.html
27 | scwmake_credit.gif
28 | scwmake_credit.jpg
29 | scwmake_credit.png
30 | scwmake_credit.swc
31 | scwmake_credit.oam
32 | 0
33 | 0
34 | 0
35 | 0
36 |
37 |
38 | 0
39 | 30,0,0,0;26,0,0,0;25,0,0,0;23,0,0,0;21,0,0,0;20,0,0,0;19,0,0,0;18,0,0,0;17,0,0,0;16,0,0,0;14,0,0,0;13,0,0,0;12,0,0,0;11,9,0,0;11,8,0,0;11,7,0,0;11,6,0,0;11,5,0,0;11,4,0,0;11,3,0,0;11,2,0,0;11,1,0,0;10,3,0,0;10,2,153,0;10,1,52,0;9,0,124,0;8,0,24,0;7,0,14,0;6,0,79,0;5,0,58,0;4,0,32,0;3,0,8,0;2,0,1,12;1,0,0,1;
40 | 1
41 | 1
42 | scwmake_credit_content.html
43 | scwmake_credit_alternate.html
44 | 0
45 |
46 | 1280
47 | 720
48 | 0
49 | 0
50 | 1
51 | 0
52 | 0
53 | 1
54 | 1
55 | 4
56 | 0
57 | 0
58 | 1
59 | 0
60 | C:\Users\User\AppData\Local\Adobe\Animate CC 2019\ru_RU\Configuration\HTML\Default.html
61 | 1
62 |
63 |
64 |
65 |
66 | 0
67 | 0
68 | 0
69 | 0
70 | 80
71 | 0
72 | 0
73 | 7
74 | 0
75 | 7
76 | 0
77 | 41
78 | FlashPlayer30.0
79 | 3
80 | 1
81 |
82 | .
83 | CONFIG::FLASH_AUTHORING="true";
84 | 0
85 |
86 | 1
87 | 0
88 | 1
89 | 0
90 | 0
91 | 0
92 | 0
93 |
94 | 2
95 | 4
96 | 4096
97 | AS3
98 | 1
99 | 1
100 | 0
101 | 15
102 | 1
103 | 0
104 | 4102
105 | rsl
106 | wrap
107 | $(AppConfig)/ActionScript 3.0/rsls/loader_animation.swf
108 |
109 |
110 | $(AppConfig)/ActionScript 3.0/libs
111 | merge
112 |
113 |
114 |
115 |
116 | 0
117 |
118 |
119 |
120 | 1280
121 | 720
122 | 0
123 | 4718592
124 | 0
125 | 80
126 | 1
127 |
128 |
129 | 1280
130 | 720
131 | 0
132 | 1
133 | 1
134 |
135 | 1
136 | 255
137 |
138 |
139 | 1280
140 | 720
141 | 1
142 | 1
143 | 24-битный с альфа-каналом
144 | 255
145 |
146 |
147 | 1280
148 | 720
149 | 1
150 | 0
151 |
152 | 0
153 |
154 |
155 | true
156 | scwmake_credit.zip
157 |
158 |
159 | true
160 | true
161 | false
162 | Untitled-1.svg
163 | images
164 | true
165 | false
166 | 0.1
167 |
168 |
169 | true
170 | Untitled-1.app
171 |
172 |
173 | true
174 | Untitled-1.exe
175 |
176 |
177 |
--------------------------------------------------------------------------------
/lib/scwmake_credit/bin/SymDepend.cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sc-workshop/SC/fe797f56b7fe71196a8673184007e00e3f69be05/lib/scwmake_credit/bin/SymDepend.cache
--------------------------------------------------------------------------------
/lib/scwmake_credit/scwmake_credit.xfl:
--------------------------------------------------------------------------------
1 | PROXY-CS5
--------------------------------------------------------------------------------
/lib/utils/__init__.py:
--------------------------------------------------------------------------------
1 | from .reader import BinaryReader
2 | from .writer import BinaryWriter
--------------------------------------------------------------------------------
/lib/utils/reader.py:
--------------------------------------------------------------------------------
1 | from io import BytesIO
2 |
3 |
4 | class BinaryReader(BytesIO):
5 | def __init__(self, initial_bytes: bytes) -> None:
6 | super().__init__(initial_bytes)
7 |
8 | def skip(self, size: int):
9 | self.read(size)
10 |
11 | def read_bool(self):
12 | return self.read_uchar() >= 1
13 |
14 | def read_char(self):
15 | return int.from_bytes(self.read(1), "little", signed=True)
16 |
17 | def read_uchar(self):
18 | return int.from_bytes(self.read(1), "little", signed=False)
19 |
20 | def read_short(self):
21 | return int.from_bytes(self.read(2), "little", signed=True)
22 |
23 | def read_ushort(self):
24 | return int.from_bytes(self.read(2), "little", signed=False)
25 |
26 | def read_int(self):
27 | return int.from_bytes(self.read(4), "little", signed=True)
28 |
29 | def read_ascii(self):
30 | size = self.read_uchar()
31 | if size != 0xFF:
32 | return self.read(size).decode('ascii')
33 | return None
34 |
35 | def read_twip(self):
36 | return self.read_int() / 20
37 |
--------------------------------------------------------------------------------
/lib/utils/writer.py:
--------------------------------------------------------------------------------
1 | from io import BytesIO
2 |
3 |
4 | class BinaryWriter(BytesIO):
5 | def __init__(self, initial_bytes: bytes = b"") -> None:
6 | super().__init__(initial_bytes)
7 |
8 | @property
9 | def buffer(self):
10 | return self.getvalue()
11 |
12 | def fill(self, size: int):
13 | self.write(b"\x00" * size)
14 |
15 | def write_bool(self, data: bool):
16 | self.write(int(data).to_bytes(1, "little"))
17 |
18 | def write_char(self, data: int):
19 | self.write(data.to_bytes(1, "little", signed=True))
20 |
21 | def write_uchar(self, data: int):
22 | self.write(data.to_bytes(1, "little", signed=False))
23 |
24 | def write_short(self, data: int):
25 | self.write(data.to_bytes(2, "little", signed=True))
26 |
27 | def write_ushort(self, data: int):
28 | self.write(data.to_bytes(2, "little", signed=False))
29 |
30 | def write_int(self, data: int):
31 | self.write(data.to_bytes(4, "little", signed=True))
32 |
33 | def write_ascii(self, data: str = None):
34 | if not data:
35 | self.write_uchar(0xFF)
36 | else:
37 | self.write_uchar(len(data))
38 | self.write(data.encode('ascii'))
39 |
40 | def write_twip(self, data: float):
41 | self.write_int(int(round(data * 20)))
42 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import time
4 | import argparse
5 |
6 | from sc_compression.signatures import Signatures
7 | from sc_compression import Decompressor, Compressor
8 |
9 | from lib.console import Console, Time
10 |
11 | def main():
12 | parser = argparse.ArgumentParser(description="SC tool by SCW Make - github.com/scwmake/SC")
13 |
14 | parser.add_argument("-d", "--decompile", help="Convert *.sc file to *.fla", type=str)
15 | parser.add_argument("-dx", "--decompress", help="Decompress *.sc files with Supercell compression", type=str)
16 | parser.add_argument("-cx", "--compress", help="Compress *.sc files with Supercell compression (LZMA | SC | version 1)", type=str)
17 |
18 | args = parser.parse_args()
19 |
20 | start_time = time.time()
21 |
22 | if args.decompile:
23 | from lib import sc_to_fla
24 | sc_to_fla(args.decompile)
25 |
26 | elif args.decompress:
27 | file = args.decompress
28 |
29 | decompressor = Decompressor()
30 | decompressed = decompressor.decompress(open(file, 'rb').read().split(b"START")[0])
31 |
32 | open(file + ".dec", 'wb').write(decompressed)
33 |
34 | elif args.compress:
35 | file = args.compress
36 |
37 | compressor = Compressor()
38 | compressed = compressor.compress(open(file, 'rb').read(), Signatures.SC, 1)
39 |
40 | open(file + ".cmp", 'wb').write(compressed)
41 |
42 |
43 | else:
44 | Console.title("SC tool by SCW Make - github.com/scwmake/SC")
45 | print("-d, --decompile : Convert *.sc file to *.fla")
46 | print("-dx, --decompress : Decompress *.sc files with Supercell compression")
47 | print("-cx, --compress : Compress *.sc files with Supercell compression (LZMA | SC | version 1)")
48 | exit(0)
49 |
50 | result_time = time.time() - start_time
51 |
52 | print(f"Done in {Time(result_time)} seconds!")
53 |
54 |
55 | if __name__ == "__main__":
56 | main()
57 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | sc-compression
2 | Pillow
3 | numpy
4 | affine6p
5 | colorama
6 | lxml
7 | ujson
--------------------------------------------------------------------------------