Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

Retro-Go: Game & Watch with LCD-Game-Emulator

Mason3638c5af4d68162
diff --git a/games/retrogo/Makefile b/games/retrogo/Makefile
index 0ebea4ba..316eec49 100644
--- a/games/retrogo/Makefile
+++ b/games/retrogo/Makefile
@@ -21,9 +21,10 @@ GB_SRC = $(addprefix src/gb/,cpu.c hw.c mem.c lcdc.c rtc.c lcd.c gb.c)
NES_SRC = $(addprefix src/nes/,nes6502.c nes_ppu.c nes_mmc.c mmclist.c nes_apu.c nes.c) \
$(sort $(wildcard src/nes/mappers/*.c))
SMS_SRC = src/sms/z80.c src/sms/sms.c src/sms/coleco_bios.c
-CORE_SRC = $(GB_SRC) $(NES_SRC) $(SMS_SRC)
+GW_SRC = $(addprefix src/gw/,gw.c gw_state.c gw_system.c sm510base.c sm510core.c sm510op.c sm511core.c sm500core.c sm500op.c sm5acore.c)
+CORE_SRC = $(GB_SRC) $(NES_SRC) $(SMS_SRC) $(GW_SRC)
APP_SRC = src/main.c src/romtable.c src/pack.c
-CORE_H = $(wildcard src/*.h src/gb/*.h src/nes/*.h src/sms/*.h)
+CORE_H = $(wildcard src/*.h src/gb/*.h src/nes/*.h src/sms/*.h src/gw/*.h)
HEADERS = $(CORE_H) ../common/epsilon_app.h ../common/epsilon_files.h ../common/np_text.h \
../../launcher/src/gfx.h ../../launcher/src/np.h ../../launcher/src/font.h
diff --git a/games/retrogo/src/gw/LICENSE b/games/retrogo/src/gw/LICENSE
new file mode 100644
index 00000000..f288702d
--- /dev/null
+++ b/games/retrogo/src/gw/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/games/retrogo/src/gw/gw.c b/games/retrogo/src/gw/gw.c
new file mode 100644
index 00000000..870619fb
--- /dev/null
+++ b/games/retrogo/src/gw/gw.c
@@ -0,0 +1,260 @@
+/* The Game & Watch for Retro-Go's screens: LCD-Game-Emulator's machine (gw_system.c, the SM5xx
+ * processors) fed from a .gw file read in place, and its LCD drawn a band of lines at a time.
+ *
+ * LCD-Game-Emulator draws the whole 320 x 240 screen into a frame buffer: the background picture,
+ * then each segment that is on, its pixels multiplied with what is under them. The calculator
+ * hasn't the RAM for that frame, so here the same is done for 16 lines at a time, and only when a
+ * segment changed. The segment rules (which RAM bits light which segment, the 2, 4 and 8-bit
+ * pixels, the transparent colour) are gw_graphic.c's.
+ *
+ * Based on LCD-Game-Emulator by bzhxx (GPL-3.0-or-later, see LICENSE). */
+#include <string.h>
+#include "gw.h"
+#include "gw_type_defs.h"
+#include "gw_system.h"
+#include "gw_romloader.h"
+#include "gw_graphic.h"
+#include "sm510.h"
+#include "sm500.h"
+
+/* (gw_state.c: the processor's fixed setup kept at the start and put back after a state) */
+void gw_chip_keep(void);
+void gw_chip_fix(void);
+
+/* the file's parts, in flash (gw_romloader.h) */
+gwromheader_t gw_head;
+unsigned short *gw_background;
+unsigned char *gw_segments;
+unsigned short *gw_segments_x, *gw_segments_y, *gw_segments_width, *gw_segments_height;
+unsigned int *gw_segments_offset;
+unsigned char *gw_program, *gw_melody;
+unsigned int *gw_keyboard;
+
+#define BAND 16
+static uint16_t *band; /* BAND lines of the picture (rg_alloc) */
+static uint8_t seg_on[256], seg_drawn[256];
+static bool drawn_once;
+static int bpp; /* the segments' pixels: 2, 4 or 8 bits */
+static bool sm500; /* an SM500 or SM5A: its LCD is driven from its O pins */
+static uint32_t nsegs; /* the segments the file has */
+static int pad_now, keys_now, soft; /* soft: B+Time (bit 10) or B+Game (bit 11) held */
+
+static uint32_t rd32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; }
+
+int gw_load(const uint8_t *data, uint32_t size) {
+ if (size < sizeof(gwromheader_t) || memcmp(data, "SM5", 3)) return RG_ERR_ROM;
+ memcpy(&gw_head, data, sizeof gw_head);
+ /* every part inside the file, the keyboard (the last) ending it */
+ const unsigned *parts = &gw_head.background_pixel;
+ for (int i = 0; i < 20; i += 2) {
+ uint32_t at = parts[i], n = parts[i + 1];
+ if (at > size || n > size - at) return RG_ERR_ROM;
+ }
+ if (gw_head.keyboard + gw_head.keyboard_size != size || gw_head.keyboard_size < 40 || !gw_head.program_size ||
+ gw_head.background_pixel_size != GW_WIDTH * GW_HEIGHT * 2 || (gw_head.background_pixel & 1) ||
+ (gw_head.segments_offset & 3) || (gw_head.keyboard & 3) || ((gw_head.segments_x | gw_head.segments_y |
+ gw_head.segments_width | gw_head.segments_height) & 1))
+ return RG_ERR_ROM; /* (a JPEG background, or not a .gw file at all) */
+ uint8_t *rom = (uint8_t *)(uintptr_t)data;
+ gw_background = (unsigned short *)(void *)(rom + gw_head.background_pixel);
+ gw_segments = rom + gw_head.segments_pixel;
+ gw_segments_x = (unsigned short *)(void *)(rom + gw_head.segments_x);
+ gw_segments_y = (unsigned short *)(void *)(rom + gw_head.segments_y);
+ gw_segments_width = (unsigned short *)(void *)(rom + gw_head.segments_width);
+ gw_segments_height = (unsigned short *)(void *)(rom + gw_head.segments_height);
+ gw_segments_offset = (unsigned int *)(void *)(rom + gw_head.segments_offset);
+ gw_program = rom + gw_head.program;
+ gw_melody = gw_head.melody_size ? rom + gw_head.melody : NULL;
+ gw_keyboard = (unsigned int *)(void *)(rom + gw_head.keyboard);
+ /* the segments: each one's place inside the screen and its pixels inside the file */
+ bpp = gw_head.flags & FLAG_SEGMENTS_2BITS ? 2 : gw_head.flags & FLAG_SEGMENTS_4BITS ? 4 : 8;
+ nsegs = gw_head.segments_offset_size / 4;
+ for (int a = 0; a < 4; a++) {
+ uint32_t n = (a == 0 ? gw_head.segments_x_size : a == 1 ? gw_head.segments_y_size
+ : a == 2 ? gw_head.segments_width_size : gw_head.segments_height_size) / 2;
+ if (n < nsegs) nsegs = n;
+ }
+ if (nsegs > 256) nsegs = 256;
+ for (uint32_t s = 0; s < nsegs; s++) {
+ uint32_t x = gw_segments_x[s], y = gw_segments_y[s], w = gw_segments_width[s], h = gw_segments_height[s];
+ uint64_t end = bpp == 8 ? rd32((const uint8_t *)&gw_segments_offset[s]) + (uint64_t)w * h
+ : bpp == 4 ? (rd32((const uint8_t *)&gw_segments_offset[s]) + (uint64_t)w * h + 1) / 2
+ : (rd32((const uint8_t *)&gw_segments_offset[s]) + (uint64_t)w * h + 3) / 4;
+ if (x + w > GW_WIDTH || y + h > GW_HEIGHT || end > gw_head.segments_pixel_size) return RG_ERR_ROM;
+ }
+ sm500 = !strncmp(gw_head.cpu_name, ROM_CPU_SM500, 5) || !strncmp(gw_head.cpu_name, ROM_CPU_SM5A, 5);
+ if (gw_melody && gw_head.melody_size < 0x100) return RG_ERR_ROM;
+ rg_alloc_reset();
+ if (!gw_system_config()) return RG_ERR_MAPPER; /* (a processor it doesn't have) */
+ band = rg_alloc(GW_WIDTH * BAND * 2);
+ if (!band) return RG_ERR_MEMORY;
+ gw_system_sound_init();
+ gw_system_start();
+ gw_chip_keep();
+ gw_reset(true);
+ return RG_OK;
+}
+
+/* the buttons LCD-Game-Emulator reads: left, up, right, down, A, B, Time, Game, then B+Time and
+ B+Game as the console's shortcuts (bits 10 and 11) */
+unsigned int gw_get_buttons(void) {
+ unsigned b = 0;
+ if (pad_now & RG_PAD_LEFT) b |= GW_BUTTON_LEFT;
+ if (pad_now & RG_PAD_UP) b |= GW_BUTTON_UP;
+ if (pad_now & RG_PAD_RIGHT) b |= GW_BUTTON_RIGHT;
+ if (pad_now & RG_PAD_DOWN) b |= GW_BUTTON_DOWN;
+ if (pad_now & RG_PAD_A) b |= GW_BUTTON_A;
+ if (pad_now & RG_PAD_B) b |= GW_BUTTON_B;
+ if (keys_now & GW_KEY_TIME) b |= GW_BUTTON_TIME;
+ if (keys_now & GW_KEY_GAME_A) b |= GW_BUTTON_GAME;
+ return b | (unsigned)soft;
+}
+
+void gw_set_pad(int pad, int keys) {
+ pad_now = pad, keys_now = keys;
+ soft = keys & GW_KEY_ALARM ? 1 << 10 : keys & GW_KEY_GAME_B ? 1 << 11 : 0;
+}
+
+int gw_keys(void) {
+ int k = 0;
+ for (int s = 0; s < 8; s++)
+ for (int i = 0; i < 4; i++) {
+ unsigned v = (rd32((const uint8_t *)&gw_keyboard[s]) >> (8 * i)) & 0xFF;
+ if (v == GW_BUTTON_GAME) k |= GW_KEY_GAME_A;
+ if (v == GW_BUTTON_TIME) k |= GW_KEY_TIME;
+ if (v == GW_BUTTON_B + GW_BUTTON_GAME) k |= GW_KEY_GAME_B;
+ if (v == GW_BUTTON_B + GW_BUTTON_TIME) k |= GW_KEY_ALARM;
+ }
+ return k;
+}
+
+static void run(int cycles, int times) {
+ for (int i = 0; i < times; i++) gw_system_run(cycles);
+}
+
+void gw_reset(bool hard) {
+ gw_system_reset();
+ memset(seg_drawn, 0, sizeof seg_drawn), drawn_once = false;
+ if (!hard) return;
+ /* as Retro-Go starts one: the watch let run out of its setting mode, set, and running (the
+ calculator has no clock for apps: 12:00) */
+ int pad = pad_now, keys = keys_now;
+ gw_set_pad(0, 0);
+ run(GW_SYSTEM_CYCLES, GW_REFRESH_RATE * 2);
+ gw_set_pad(0, GW_KEY_TIME);
+ run(GW_SYSTEM_CYCLES, GW_REFRESH_RATE / 2);
+ gw_set_pad(0, 0);
+ run(GW_SYSTEM_CYCLES, GW_REFRESH_RATE * 2);
+ gw_system_set_time((gw_time_t){12, 0, 0});
+ run(GW_SYSTEM_CYCLES, GW_REFRESH_RATE);
+ gw_set_pad(RG_PAD_A, 0); /* (some games want A) */
+ run(GW_SYSTEM_CYCLES, GW_REFRESH_RATE / 2);
+ gw_set_pad(0, 0);
+ run(GW_SYSTEM_CYCLES, GW_REFRESH_RATE);
+ gw_set_pad(pad, keys);
+}
+
+/* ---- which segments are on (gw_graphic.c's two LCD controllers) */
+static void segments_sm510(void) {
+ bool blank = m_bc || !m_bp, defl = flag_lcd_deflicker_level != 0;
+ for (int y = 0; y < NB_SEGS_ROW; y++) {
+ uint8_t a = (defl ? gw_ram_state : gw_ram)[ADD_SEGA_BASE + y] & 0xf;
+ uint8_t b = (defl ? gw_ram_state : gw_ram)[ADD_SEGB_BASE + y] & 0xf;
+ uint8_t c = (defl ? gw_ram_state : gw_ram)[ADD_SEGC_BASE + y] & 0xf;
+ for (int z = 0; z < NB_SEGS_COL; z++) {
+ int p = 4 * y + z;
+ seg_on[p] = !blank && (a >> z & 1);
+ seg_on[p + 64] = !blank && (b >> z & 1);
+ seg_on[p + 192] = !blank && (c >> z & 1);
+ }
+ }
+ uint8_t blink = (m_div & 0x4000) ? m_y : 0;
+ for (int z = 0; z < NB_SEGS_COL; z++) {
+ seg_on[128 + z] = !blank && ((m_l & ~blink) >> z & 1);
+ seg_on[132 + z] = !blank && ((m_x & ~blink) >> z & 1);
+ }
+}
+static void segments_sm500(void) {
+ bool defl = flag_lcd_deflicker_level != 0;
+ for (int h = 0; h < 2; h++)
+ for (int o = 0; o < m_o_pins && o < 9; o++) {
+ uint8_t seg = defl ? (h ? m_ox_state[o] : m_o_state[o]) : (h ? m_ox[o] : m_o[o]);
+ for (int k = 0; k < 4; k++)
+ if (8 * o + 2 * k + h < 256) seg_on[8 * o + 2 * k + h] = m_bp && (seg >> k & 1);
+ }
+}
+
+/* (gw_system.c's hooks into gw_graphic.c: the LCD is drawn here instead) */
+void gw_gfx_init(void) { flag_lcd_deflicker_level = (gw_head.flags & FLAG_LCD_DEFLICKER_MASK) >> 6; }
+void gw_gfx_sm500_rendering(uint16 *framebuffer) { (void)framebuffer; }
+void gw_gfx_sm510_rendering(uint16 *framebuffer) { (void)framebuffer; }
+
+/* rgb_multiply_8bits: the background's colour dimmed by the segment's pixel */
+static inline uint16_t multiply(uint32_t bg, uint32_t sg) {
+ uint32_t r = ((bg >> 11) * sg) >> 8, g = (((bg >> 5) & 63) * sg) >> 8, b = ((bg & 31) * sg) >> 8;
+ return (uint16_t)(r << 11 | g << 5 | b);
+}
+
+/* lines [y0, y1) of the screen into band */
+static void draw_band(int y0, int y1) {
+ bool inverted = gw_head.flags & FLAG_RENDERING_LCD_INVERTED;
+ uint8_t clear = inverted ? 0x00 : 0xFF; /* (the segments' transparent pixel) */
+ if (inverted) memset(band, 0, (size_t)(y1 - y0) * GW_WIDTH * 2);
+ else memcpy(band, gw_background + y0 * GW_WIDTH, (size_t)(y1 - y0) * GW_WIDTH * 2);
+ for (uint32_t s = 0; s < nsegs; s++) {
+ if (!seg_on[s]) continue;
+ int sx = gw_segments_x[s], sy = gw_segments_y[s], w = gw_segments_width[s], h = gw_segments_height[s];
+ int ys = sy > y0 ? sy : y0, ye = sy + h < y1 ? sy + h : y1;
+ if (ys >= ye || !w) continue;
+ uint32_t off = rd32((const uint8_t *)&gw_segments_offset[s]);
+ for (int y = ys; y < ye; y++) {
+ uint16_t *row = band + (y - y0) * GW_WIDTH + sx;
+ const uint16_t *mix = inverted ? gw_background + y * GW_WIDTH + sx : row;
+ uint32_t idx = (uint32_t)(y - sy) * (uint32_t)w;
+ for (int x = 0; x < w; x++, idx++) {
+ uint8_t px;
+ if (bpp == 8) {
+ px = gw_segments[off + idx];
+ } else if (bpp == 4) {
+ uint32_t i = (off & 1) + idx;
+ px = (i & 1) ? (uint8_t)(gw_segments[(off >> 1) + (i >> 1)] << 4) : gw_segments[(off >> 1) + (i >> 1)] & 0xF0;
+ px |= px >> 4;
+ } else {
+ uint32_t i = (off & 3) + idx;
+ uint8_t v = (gw_segments[(off >> 2) + (i >> 2)] >> (2 * (i & 3))) & 3;
+ px = (uint8_t)(v | v << 2 | v << 4 | v << 6);
+ if (px != clear && !px) px = 39; /* (black lets a little through) */
+ }
+ if (px != clear) row[x] = multiply(mix[x], px);
+ }
+ }
+ }
+}
+
+static void draw(void) {
+ for (int y = 0; y < GW_HEIGHT; y += BAND) {
+ draw_band(y, y + BAND);
+ for (int j = 0; j < BAND; j++) rg_line(y + j, band + j * GW_WIDTH);
+ }
+}
+
+void gw_run_frame(bool want) {
+ run(GW_SYSTEM_CYCLES, 2);
+ if (!want) return;
+ if (sm500) segments_sm500();
+ else segments_sm510();
+ if (drawn_once && !memcmp(seg_on, seg_drawn, sizeof seg_on)) return;
+ memcpy(seg_drawn, seg_on, sizeof seg_on), drawn_once = true;
+ draw();
+}
+
+void gw_redraw(void) { draw(); }
+
+int gw_state_chunks(rg_chunk_t *out) {
+ out[0] = (rg_chunk_t){&sm510, sizeof sm510};
+ return 1;
+}
+void gw_state_loaded(void) {
+ gw_chip_fix();
+ drawn_once = false;
+}
diff --git a/games/retrogo/src/gw/gw.h b/games/retrogo/src/gw/gw.h
new file mode 100644
index 00000000..ef3e14d9
--- /dev/null
+++ b/games/retrogo/src/gw/gw.h
@@ -0,0 +1,28 @@
+/* Nintendo's Game & Watch and the other LCD games, as LCD-Game-Emulator runs them (gw_system.c and
+ * the Sharp SM5xx processors), from the .gw files LCD-Game-Shrinker makes, read in place. */
+#ifndef GW_H
+#define GW_H
+#include "../rg.h"
+
+#define GW_WIDTH 320
+#define GW_HEIGHT 240
+
+/* the game's buttons, beyond the pad's (rg.h): the console's own */
+enum { GW_KEY_GAME_A = 1, GW_KEY_GAME_B = 2, GW_KEY_TIME = 4, GW_KEY_ALARM = 8 };
+
+/* a .gw file as LCD-Game-Shrinker writes it, not packed (tools/romtable.py and NumPlay Studio
+ unpack the LZ4 ones). RG_OK or an RG_ERR_ code. */
+int gw_load(const uint8_t *data, uint32_t size);
+/* hard: as a new game, the watch set and running; otherwise the ACL button (the processor reset) */
+void gw_reset(bool hard);
+/* a 64th of a second (two of the emulator's 128 Hz steps); the picture drawn only if a segment changed */
+void gw_run_frame(bool draw);
+/* the pad (RG_PAD_*) and the console's buttons (GW_KEY_*) held */
+void gw_set_pad(int pad, int keys);
+/* the console's buttons this game has (GW_KEY_*) */
+int gw_keys(void);
+/* the picture again, line by line through rg_line */
+void gw_redraw(void);
+int gw_state_chunks(rg_chunk_t *out);
+void gw_state_loaded(void);
+#endif
diff --git a/games/retrogo/src/gw/gw_graphic.h b/games/retrogo/src/gw/gw_graphic.h
new file mode 100644
index 00000000..a72b48a1
--- /dev/null
+++ b/games/retrogo/src/gw/gw_graphic.h
@@ -0,0 +1,45 @@
+/*
+
+This program implements the graphics rendering for the different variation
+of SM510 family microcomputer.
+
+This program is free software: you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free Software
+Foundation, either version 3 of the License, or (at your option) any later
+version.
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+You should have received a copy of the GNU General Public License along with
+this program. If not, see <http://www.gnu.org/licenses/>.
+
+__author__ = "bzhxx"
+__contact__ = "https://github.com/bzhxx"
+__license__ = "GPLv3"
+
+*/
+
+#ifndef _GW_GRAPHIC_H_
+#define _GW_GRAPHIC_H_
+
+/****************************/
+// H1..4
+#define NB_SEGS_COL 4
+
+//a1...a16
+#define NB_SEGS_ROW 16
+
+//a,b,c
+#define NB_SEGS_BUS 3
+
+//a,b,c base address
+#define ADD_SEGA_BASE 0x60
+#define ADD_SEGB_BASE 0x70
+#define ADD_SEGC_BASE 0x50
+
+/* Function prototypes */
+void gw_gfx_init();
+void gw_gfx_sm500_rendering(uint16 *framebuffer);
+void gw_gfx_sm510_rendering(uint16 *framebuffer);
+
+#endif /* _GW_GRAPHIC_H_ */
diff --git a/games/retrogo/src/gw/gw_romloader.h b/games/retrogo/src/gw/gw_romloader.h
new file mode 100644
index 00000000..3775de90
--- /dev/null
+++ b/games/retrogo/src/gw/gw_romloader.h
@@ -0,0 +1,151 @@
+/*
+
+This program permits to load ROM generated by LCD-Game-Shrinker.
+
+This program is free software: you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free Software
+Foundation, either version 3 of the License, or (at your option) any later
+version.
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+You should have received a copy of the GNU General Public License along with
+this program. If not, see <http://www.gnu.org/licenses/>.
+
+__author__ = "bzhxx"
+__contact__ = "https://github.com/bzhxx"
+__license__ = "GPLv3"
+
+*/
+
+#ifndef _GW_ROMLOADER_H_
+#define _GW_ROMLOADER_H_
+
+
+#define ZLIB_MAGIC "ZLIB"
+#define LZMA_MAGIC "LZMA"
+
+/* Different CPU 4bits from SHARP */
+#define ROM_CPU_SM5A "SM5A_"
+#define ROM_CPU_SM500 "SM500"
+#define ROM_CPU_SM510 "SM510"
+#define ROM_CPU_SM511 "SM511"
+#define ROM_CPU_SM512 "SM512"
+#define ROM_CPU_SM520 "SM520"
+#define ROM_CPU_SM530 "SM530"
+
+/* flags in ROM file */
+// use to check 'flag_rendering_lcd_inverted' bit0 in rom_head.flags
+// use to check 'flag_segments_4bits' bit4 in rom_head.flags
+// use to check 'flag_background_jpeg' bit5 in rom_head.flags
+// use to check 'flag_segments_2bits' bit8 in rom_head.flags
+#define FLAG_RENDERING_LCD_INVERTED 0x01
+#define FLAG_SEGMENTS_4BITS 0x10
+#define FLAG_SEGMENTS_2BITS 0x100
+#define FLAG_BACKGROUND_JPEG 0x20
+
+// use to determine the piezo buzzer mode bits1..3 in rom_head.flags
+
+#define FLAG_SOUND_MASK 0xE
+
+#define FLAG_SOUND_R1_PIEZO 1 << 1
+#define FLAG_SOUND_R2_PIEZO 2 << 1
+#define FLAG_SOUND_R1R2_PIEZO 3 << 1
+#define FLAG_SOUND_R1S1_PIEZO 4 << 1
+#define FLAG_SOUND_S1R1_PIEZO 5 << 1
+
+// use to determine the LCD deflicker mode bits6.7 in rom_head.flags
+#define FLAG_LCD_DEFLICKER_MASK 0xC0
+
+#define FLAG_LCD_DEFLICKER_OFF 0x00
+#define FLAG_LCD_DEFLICKER_1 0x40
+#define FLAG_LCD_DEFLICKER_2 0x80
+#define FLAG_LCD_DEFLICKER_3 0xC0
+
+/* ADD ROM SUPPORT */
+/* Large memory to store all objects from external flash */
+extern unsigned char *GW_ROM;
+
+/* ROM in RAM : objects pointers */
+extern unsigned char *gw_rom_base;
+extern unsigned short *gw_background;
+extern unsigned char *gw_segments;
+extern unsigned short *gw_segments_x;
+extern unsigned short *gw_segments_y;
+extern unsigned short *gw_segments_width;
+extern unsigned short *gw_segments_height;
+extern unsigned int *gw_segments_offset;
+extern unsigned char *gw_program;
+extern unsigned char *gw_melody;
+extern unsigned int *gw_keyboard;
+
+/* ROM header */
+typedef struct gwromheader_s
+{
+ /* Name of the sharp microcomputers to emulate */
+ char cpu_name[8] ;
+
+ /* Signature of the original ROM name (8 last characters) */
+ /* used to check coherency with save */
+
+ char rom_signature[8] ;
+
+ /* Address counter time used by the program to manage it RTC */
+ unsigned char time_hour_address_msb;
+ unsigned char time_hour_address_lsb;
+ unsigned char time_min_address_msb ;
+ unsigned char time_min_address_lsb ;
+ unsigned char time_sec_address_msb ;
+ unsigned char time_sec_address_lsb ;
+ unsigned char time_hour_msb_pm;
+
+ /* spare reserved for futur used */
+ unsigned char byte_spare1 ;
+
+ /* Flags to describe hardware : buzzer and lcd deflicker filter */
+ unsigned int flags ;
+
+ /* Background pixels 320x240 RGB565 */
+ unsigned int background_pixel ;
+ unsigned int background_pixel_size ;
+
+ /* Segments pixels packed Maximum size 320x240 RGB565 */
+ unsigned int segments_pixel ;
+ unsigned int segments_pixel_size ;
+
+ /* Segments offset and dimensions : x,y,height,width */
+ unsigned int segments_offset ;
+ unsigned int segments_offset_size ;
+ unsigned int segments_x ;
+ unsigned int segments_x_size ;
+ unsigned int segments_y ;
+ unsigned int segments_y_size ;
+ unsigned int segments_height ;
+ unsigned int segments_height_size ;
+ unsigned int segments_width ;
+ unsigned int segments_width_size ;
+
+ /* Melody */
+ unsigned int melody ;
+ unsigned int melody_size ;
+
+ /* CPU program */
+ unsigned int program ;
+ unsigned int program_size ;
+
+ /* CPU keyboard mapping */
+ unsigned int keyboard ;
+ unsigned int keyboard_size ;
+
+ /* TODO Add support for dual vertical screen */
+ // hook on segments to monitor
+ // 2nd background set when the hook select the upper screen
+ // 2nd segments set when the hook select the upper screen
+
+} gwromheader_t;
+
+extern gwromheader_t gw_head;
+
+bool gw_romloader();
+
+#endif /* _GW_ROMLOADER_H_ */
diff --git a/games/retrogo/src/gw/gw_state.c b/games/retrogo/src/gw/gw_state.c
new file mode 100644
index 00000000..5b01d85f
--- /dev/null
+++ b/games/retrogo/src/gw/gw_state.c
@@ -0,0 +1,28 @@
+/* A save state is the SM5xx processor's registers and RAM (sm510_t). Whatever a state file
+ * holds, the processor's fixed setup (its widths, masks, stack, pins) stays as it started, and
+ * its registers inside it: no read outside its RAM or its program. */
+#include "gw_type_defs.h"
+#define GW_NO_SM510_DEFINES
+#include "sm510.h"
+
+static sm510_t chip; /* the processor as it started */
+
+void gw_chip_keep(void) { chip = sm510; }
+
+void gw_chip_fix(void) {
+ sm510_t *c = &sm510;
+ c->m_prgwidth = chip.m_prgwidth, c->m_datawidth = chip.m_datawidth;
+ c->m_prgmask = chip.m_prgmask, c->m_datamask = chip.m_datamask;
+ c->m_stack_levels = chip.m_stack_levels, c->m_r_mask_option = chip.m_r_mask_option;
+ c->m_o_pins = chip.m_o_pins, c->flag_lcd_deflicker_level = chip.flag_lcd_deflicker_level;
+ if (c->m_clk_div != 2 && c->m_clk_div != 4) c->m_clk_div = chip.m_clk_div;
+ c->m_pc &= (u16)chip.m_prgmask, c->m_prev_pc &= (u16)chip.m_prgmask;
+ for (int i = 0; i < 4; i++) c->m_stack[i] &= (u16)chip.m_prgmask;
+ c->m_icount = 0;
+ c->m_acc &= 15, c->m_bl &= 15, c->m_bm &= 15, c->m_c &= 1;
+ c->m_cn &= 1, c->m_mx &= 1, c->m_cb &= 1;
+ for (int i = 0; i < 128; i++) c->gw_ram[i] &= 15, c->gw_ram_state[i] &= 15;
+ /* (the flags read as the bytes they are: a bool holding anything but 0 or 1 isn't one) */
+#define FLAG(f) c->f = *(const volatile unsigned char *)&c->f != 0
+ FLAG(m_sbm), FLAG(m_sbl), FLAG(m_skip), FLAG(m_k_active), FLAG(m_halt), FLAG(m_1s), FLAG(m_bc), FLAG(m_rsub);
+}
diff --git a/games/retrogo/src/gw/gw_system.c b/games/retrogo/src/gw/gw_system.c
new file mode 100644
index 00000000..1724f60e
--- /dev/null
+++ b/games/retrogo/src/gw/gw_system.c
@@ -0,0 +1,936 @@
+/*
+
+This program implements the main functions to use the LCD Game emulator.
+It implements also sound buzzer and keyboard functions.
+
+This program is free software: you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free Software
+Foundation, either version 3 of the License, or (at your option) any later
+version.
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+You should have received a copy of the GNU General Public License along with
+this program. If not, see <http://www.gnu.org/licenses/>.
+
+__author__ = "bzhxx"
+__contact__ = "https://github.com/bzhxx"
+__license__ = "GPLv3"
+
+*/
+#include <stdio.h>
+#include <stdbool.h>
+#include <string.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#define GW_NO_SM510_DEFINES
+
+/* Emulated system */
+#include "sm510.h"
+#include "sm500.h"
+#include "gw_romloader.h"
+#include "gw_system.h"
+#include "gw_graphic.h"
+
+static void (*device_reset)();
+static void (*device_start)();
+static void (*device_run)();
+static void (*device_blit)(unsigned short *active_framebuffer);
+
+static unsigned char previous_dpad;
+static bool gw_keyboard_multikey[8];
+
+/* map functions and custom configuration */
+bool gw_system_config()
+{
+
+ /* Supported System */
+ /* SM500 SM5A(kb1013vk12) SM510 SM511 SM512 */
+
+ /* init graphics parameters */
+ gw_gfx_init();
+
+ /* parse keyboard mapping to detect DPAD multi-key mode */
+ // determine if there is a multi-key configuration (number of keys > 4)
+ // for some game joypad is used with combination
+ // LEFT_UP, LEFT_DOWN, RIGHT_UP and RIGH_DOWN
+ // in this case, 2 bits are returned by the HAL as a dual key pressed
+ // here, we try to detect this configuration.
+
+ // Parse all keys configuration
+ // S1..S8
+ // set a flag if it's single key mode or mulyi-key mode
+
+ for (int i = 0; i < 8; i++)
+ {
+
+ /* By default it's not multikey */
+ gw_keyboard_multikey[i] = false;
+
+ un32 score = 0;
+
+ /* 4 combination to find */
+ un8 K1 = gw_keyboard[i] & 0xFF;
+ un8 K2 = (gw_keyboard[i] >> 8) & 0xFF;
+ un8 K3 = (gw_keyboard[i] >> 16) & 0xFF;
+ un8 K4 = (gw_keyboard[i] >> 24) & 0xFF;
+
+ un8 C1 = GW_BUTTON_LEFT + GW_BUTTON_UP;
+ un8 C2 = GW_BUTTON_LEFT + GW_BUTTON_DOWN;
+ un8 C3 = GW_BUTTON_RIGHT + GW_BUTTON_UP;
+ un8 C4 = GW_BUTTON_RIGHT + GW_BUTTON_DOWN;
+
+ if (K1 == C1)
+ score++;
+ else if (K2 == C1)
+ score++;
+ else if (K3 == C1)
+ score++;
+ else if (K4 == C1)
+ score++;
+
+ if (K1 == C2)
+ score++;
+ else if (K2 == C2)
+ score++;
+ else if (K3 == C2)
+ score++;
+ else if (K4 == C2)
+ score++;
+
+ if (K1 == C3)
+ score++;
+ else if (K2 == C3)
+ score++;
+ else if (K3 == C3)
+ score++;
+ else if (K4 == C3)
+ score++;
+
+ if (K1 == C4)
+ score++;
+ else if (K2 == C4)
+ score++;
+ else if (K3 == C4)
+ score++;
+ else if (K4 == C4)
+ score++;
+
+ /* 4 combinations are found ? */
+ if (score == 4)
+ gw_keyboard_multikey[i] = true;
+ }
+
+ /* init dpad to default position */
+ previous_dpad = 0;
+
+ /* depending on the CPU, set functions pointers */
+
+ // SM500
+ if (strncmp(gw_head.cpu_name, ROM_CPU_SM500, 5) == 0)
+ {
+ device_start = sm500_device_start;
+ device_reset = sm500_device_reset;
+ device_run = sm500_execute_run;
+ device_blit = gw_gfx_sm500_rendering;
+ return true;
+ }
+
+ // SM5A
+ if (strncmp(gw_head.cpu_name, ROM_CPU_SM5A, 5) == 0)
+ {
+ device_start = sm5a_device_start;
+ device_reset = sm5a_device_reset;
+ device_run = sm5a_execute_run;
+ device_blit = gw_gfx_sm500_rendering;
+ return true;
+ }
+
+ // SM510
+ if (strncmp(gw_head.cpu_name, ROM_CPU_SM510, 5) == 0)
+ {
+ device_start = sm510_device_start;
+ device_reset = sm510_device_reset;
+ device_run = sm510_execute_run;
+ device_blit = gw_gfx_sm510_rendering;
+ return true;
+ }
+
+ // SM511
+ if (strncmp(gw_head.cpu_name, ROM_CPU_SM511, 5) == 0)
+ {
+ device_start = sm510_device_start;
+ device_reset = sm511_device_reset;
+ device_run = sm511_execute_run;
+ device_blit = gw_gfx_sm510_rendering;
+ return (sm511_init_melody(gw_melody));
+ }
+
+ // SM512
+ if (strncmp(gw_head.cpu_name, ROM_CPU_SM512, 5) == 0)
+ {
+ device_start = sm510_device_start;
+ device_reset = sm511_device_reset;
+ device_run = sm511_execute_run;
+ device_blit = gw_gfx_sm510_rendering;
+ return (sm511_init_melody(gw_melody));
+ }
+
+ return false;
+}
+
+void gw_system_reset() { device_reset(); }
+void gw_system_start() { device_start(); }
+void gw_system_blit(unsigned short *active_framebuffer) { device_blit(active_framebuffer); }
+
+/******** Audio functions *******************/
+static unsigned char mspeaker_data = 0;
+static int gw_audio_buffer_idx = 0;
+
+/* Audio buffer */
+unsigned char gw_audio_buffer[GW_AUDIO_BUFFER_LENGTH * 2];
+bool gw_audio_buffer_copied;
+
+void gw_system_sound_init()
+{
+ /* Init Sound */
+ /* clear shared audio buffer with emulator */
+ memset(gw_audio_buffer, 0, sizeof(gw_audio_buffer));
+ gw_audio_buffer_copied = false;
+
+ gw_audio_buffer_idx = 0;
+ mspeaker_data = 0;
+}
+
+static void gw_system_sound_melody(unsigned char data)
+{
+ if (gw_audio_buffer_copied)
+ {
+ gw_audio_buffer_copied = false;
+
+ gw_audio_buffer_idx = gw_audio_buffer_idx - GW_AUDIO_BUFFER_LENGTH;
+
+ if (gw_audio_buffer_idx < 0)
+ gw_audio_buffer_idx = 0;
+
+ // check if some samples have to be copied from the previous loop cycles
+ if (gw_audio_buffer_idx != 0)
+ {
+ for (int i = 0; i < gw_audio_buffer_idx; i++)
+ gw_audio_buffer[i] = gw_audio_buffer[i + GW_AUDIO_BUFFER_LENGTH];
+ }
+ }
+
+ // SM511 R pin is melody output
+ if (gw_melody != 0)
+
+ mspeaker_data = data;
+
+ // Piezo buzzer
+ else
+ {
+
+ switch (gw_head.flags & FLAG_SOUND_MASK)
+ {
+ // R1 to piezo
+ case FLAG_SOUND_R1_PIEZO:
+ mspeaker_data = data & 1;
+ break;
+
+ // R2 to piezo
+ case FLAG_SOUND_R2_PIEZO:
+ mspeaker_data = data >> 1 & 1;
+ break;
+
+ // R1&R2 to piezo
+ case FLAG_SOUND_R1R2_PIEZO:
+ mspeaker_data = data & 3;
+ break;
+
+ // R1(+S1) to piezo
+ case FLAG_SOUND_R1S1_PIEZO:
+ mspeaker_data = (sm510.m_s_out & ~1) | (data & 1);
+ break;
+
+ // S1(+R1) to piezo, other to input mux
+ case FLAG_SOUND_S1R1_PIEZO:
+ mspeaker_data = (sm510.m_s_out & ~2) | (data << 1 & 2);
+ break;
+
+ // R1 to piezo
+ default:
+ mspeaker_data = data & 1;
+ }
+ }
+
+ if (gw_audio_buffer_idx >= GW_AUDIO_BUFFER_LENGTH * 2)
+ return;
+
+ gw_audio_buffer[gw_audio_buffer_idx] = mspeaker_data;
+
+ gw_audio_buffer_idx++;
+}
+
+void gw_writeR(unsigned char data) { gw_system_sound_melody(data); };
+
+/******** Keys functions **********************/
+/*
+ S[8]xK[4],B and BA keys input function
+ 8 buttons, state known using gw_get_buttons()
+ gw_get_buttons() : returns
+ left | (up << 1) | (right << 2) | (down << 3) |
+ (a << 4) | (b << 5) | (time << 6) | (game << 7) |
+ (pause << 8) | (power << 9)
+
+ We use only 8bits LSB, pause and power are ignored
+
+*/
+
+// default value is 1 (Pull-up)
+unsigned char gw_readB()
+{
+
+ unsigned int keys_pressed = gw_get_buttons() & 0xff;
+
+ if (keys_pressed == 0)
+ return 1;
+
+ if (gw_keyboard[9] & keys_pressed)
+ return 0;
+
+ return 1;
+}
+
+// default value is 1 (Pull-up)
+unsigned char gw_readBA()
+{
+
+ unsigned int keys_pressed = gw_get_buttons() & 0xff;
+
+ if (keys_pressed == 0)
+ return 1;
+
+ if (gw_keyboard[8] & keys_pressed)
+ return 0;
+
+ return 1;
+}
+
+/*
+Patch to improve gameplay of "green House" when it's in rotated view
+
+# A specific custom keyboard is implemented for "Green House" when screen is rotated.
+# It permits to play in rotate view with DPAD only.
+# According to the character postion, the Button A is emulated over DPAD keys press.
+# ~ ~ ~ ~
+# A B C D E
+# ~ F ~
+# ~ G ~
+# H I J
+#
+#In positions :
+# A, H : LEFT or UP emulates Button A
+# B, D : UP emulates Button A
+# E, J : RIGHT or UP emulates Button A
+# C,F,G,I :ignore
+#
+#SM51X series: output to x.y.z, where:
+ # x = group a/b/bs/c (0/1/2/3)
+ # y = segment 1-16 (0-15)
+ # z = common H1-H4 (0-3)
+
+# CPU RAM display
+# 0X50.. 0X5F : c1..c16 (base=80)
+# 0X60.. 0X6F : a1..a16 (base=96)
+# 0X70.. 0X7F : b1..b16 (base=112)
+
+# Position: segment : RAM MASk
+# A h1b7 1.6.0 118 0x1
+# B h1b12 1.11.0 123 0x1
+# C h1a13 0.12.0 108 0x1
+# D h1b13 1.12.0 124 0x1
+# E h1a15 0.14.0 110 0x1
+# F h3b3 1.2.2 114 0x4
+# G h2b3 1.2.1 114 0x2
+# H h1a4 0.3.0 99 0x1
+# I h1b3 1.2.0 114 0x1
+# J h1a3 0.2.0 98 0x1
+*/
+
+static unsigned int patch_gnw_ghouse_keys_rotated_view(unsigned int keys_pressed) {
+
+ // check if it's in rotated view by checking the keys mapping
+ // K1 = rom.BTN_DOWN
+ // K2 = rom.BTN_RIGHT
+ // K3 = rom.BTN_UP
+ // K4 = rom.BTN_LEFT
+ // rom.BTN_DATA[rom.S2] = K1 | (K2 << 8) | (K3 << 16) | (K4 << 24)
+
+ if ( gw_keyboard[1] != ( (GW_BUTTON_LEFT << 24) + (GW_BUTTON_RIGHT << 8) + (GW_BUTTON_UP << 16) + GW_BUTTON_DOWN) ) return keys_pressed;
+
+ // Check position CFGI
+ if (sm510.gw_ram[108] & 0x1) return keys_pressed;
+ if (sm510.gw_ram[114] & 0x4) return keys_pressed;
+ if (sm510.gw_ram[114] & 0x2) return keys_pressed;
+ if (sm510.gw_ram[114] & 0x1) return keys_pressed;
+
+ // Check position AH
+ if ( (sm510.gw_ram[118] & 0x1) | (sm510.gw_ram[99] & 0x1) ) {
+ if ( (keys_pressed & (GW_BUTTON_RIGHT+GW_BUTTON_UP) ) )
+ keys_pressed = GW_BUTTON_A;
+ }
+ // Check position BD
+ if ( (sm510.gw_ram[123] & 0x1) | (sm510.gw_ram[124] & 0x1) ) {
+ if ( (keys_pressed & GW_BUTTON_RIGHT) )
+ keys_pressed = GW_BUTTON_A;
+ }
+ // Check position EJ
+ if ( (sm510.gw_ram[110] & 0x1) | (sm510.gw_ram[98] & 0x1) ) {
+ if ( (keys_pressed & (GW_BUTTON_RIGHT+GW_BUTTON_DOWN)) )
+ keys_pressed = GW_BUTTON_A;
+ }
+
+ return keys_pressed;
+}
+
+// default value is 0 (Pull-down)
+unsigned char gw_readK(unsigned char io_S)
+{
+
+ unsigned char io_K = 0;
+ static unsigned int dpad_shortcut_diagonal_pressed = 0;
+ static unsigned int dpad_shortcut_diagonal_hold = 0;
+
+ unsigned int gw_buttons = gw_get_buttons();
+
+ unsigned int keys_pressed = gw_buttons & 0xff;
+
+ unsigned int key_soft_value = 0;
+
+ const unsigned int KEY_SOFT_TIME = GW_BUTTON_B + GW_BUTTON_TIME;
+ const unsigned int KEY_SOFT_ALARM = GW_BUTTON_B + GW_BUTTON_GAME;
+
+ if ((gw_buttons >> 10) & 1)
+ {
+ keys_pressed = 0;
+ key_soft_value = KEY_SOFT_TIME;
+ }
+ if ((gw_buttons >> 11) & 1)
+ {
+ keys_pressed = 0;
+ key_soft_value = KEY_SOFT_ALARM;
+ }
+
+ if (keys_pressed == KEY_SOFT_ALARM) {
+ key_soft_value = KEY_SOFT_ALARM;
+ keys_pressed = 0;
+ }
+
+ if (keys_pressed == KEY_SOFT_TIME) {
+ key_soft_value = KEY_SOFT_TIME;
+ keys_pressed = 0;
+ }
+
+
+ /* Hack to improve gameplay for "Green House" in rotated view */
+ if (memcmp(gw_head.rom_signature, "w_ghouse", 8) == 0 ) keys_pressed = patch_gnw_ghouse_keys_rotated_view(keys_pressed);
+ /**********************************************/
+
+ /* monitor A button as diagonal shortcut when pressed */
+ if ((keys_pressed & GW_BUTTON_A) != 0) dpad_shortcut_diagonal_pressed = 1;
+ if ( (keys_pressed & GW_BUTTON_A) == 0) {
+ dpad_shortcut_diagonal_hold = 0;
+ dpad_shortcut_diagonal_pressed = 0;
+ }
+
+ if ((keys_pressed == 0) & (key_soft_value == 0))
+ return 0;
+
+ for (int Sx = 0; Sx < 8; Sx++)
+ {
+
+ //case of R/S output is not used to poll buttons (used R2 or S2 configuration)
+ if (io_S == 0) io_S = 2;
+
+ if (((io_S >> Sx) & 0x1) != 0)
+ {
+ // DPAD multi-key with relative change and shortcut
+ if (gw_keyboard_multikey[Sx])
+ {
+
+ // keep only relevant DPAD keys
+ keys_pressed = keys_pressed & (GW_BUTTON_LEFT + GW_BUTTON_RIGHT + GW_BUTTON_UP + GW_BUTTON_DOWN);
+
+ // manage when a single key is pressed but the emulated game expects only diagonal keys combination
+ // reuse the previous DPAD value (previous_dpad) and add a complementary key
+
+ if ((dpad_shortcut_diagonal_pressed == 1) & (dpad_shortcut_diagonal_hold == 0))
+ {
+ dpad_shortcut_diagonal_hold = 1;
+ keys_pressed = ~previous_dpad &
+ (GW_BUTTON_LEFT + GW_BUTTON_RIGHT + GW_BUTTON_UP + GW_BUTTON_DOWN);
+ }
+
+ if (keys_pressed == GW_BUTTON_LEFT)
+ keys_pressed = (previous_dpad & (GW_BUTTON_UP + GW_BUTTON_DOWN)) | GW_BUTTON_LEFT;
+
+ if (keys_pressed == GW_BUTTON_RIGHT)
+ keys_pressed = (previous_dpad & (GW_BUTTON_UP + GW_BUTTON_DOWN)) | GW_BUTTON_RIGHT;
+
+ if (keys_pressed == GW_BUTTON_DOWN)
+ keys_pressed = (previous_dpad & (GW_BUTTON_LEFT + GW_BUTTON_RIGHT)) | GW_BUTTON_DOWN;
+
+ if (keys_pressed == GW_BUTTON_UP)
+ keys_pressed = (previous_dpad & (GW_BUTTON_LEFT + GW_BUTTON_RIGHT)) | GW_BUTTON_UP;
+
+ if ((gw_keyboard[Sx] & GW_MASK_K1) == keys_pressed)
+ {
+ io_K |= 0x1;
+ previous_dpad = keys_pressed;
+ }
+
+ // perform key checking (exclusively, all keys shall match)
+ if ((gw_keyboard[Sx] & GW_MASK_K2) == (keys_pressed << 8))
+ {
+ io_K |= 0x2;
+ previous_dpad = keys_pressed;
+ }
+
+ if ((gw_keyboard[Sx] & GW_MASK_K3) == (keys_pressed << 16))
+ {
+ io_K |= 0x4;
+ previous_dpad = keys_pressed;
+ }
+
+ if ((gw_keyboard[Sx] & GW_MASK_K4) == (keys_pressed << 24))
+ {
+ io_K |= 0x8;
+ previous_dpad = keys_pressed;
+ }
+
+ // (Non DPAD case) perform key checking (at least one key shall match)
+ }
+ else
+ {
+
+ // check soft keys
+ if ( key_soft_value != 0 )
+ {
+ if (((gw_keyboard[Sx] & GW_MASK_K1) == (key_soft_value)))
+ io_K |= 0x1;
+ if (((gw_keyboard[Sx] & GW_MASK_K2) == (key_soft_value << 8)))
+ io_K |= 0x2;
+ if (((gw_keyboard[Sx] & GW_MASK_K3) == (key_soft_value << 16)))
+ io_K |= 0x4;
+ if (((gw_keyboard[Sx] & GW_MASK_K4) == (key_soft_value << 24)))
+ io_K |= 0x8;
+ }
+
+ // check hardware keys excluding soft keys
+ else
+ {
+ if (((gw_keyboard[Sx] & GW_MASK_K1) & (keys_pressed)) != 0)
+ if ( ( (gw_keyboard[Sx] & GW_MASK_K1) != (KEY_SOFT_ALARM) ) & ( (gw_keyboard[Sx] & GW_MASK_K1) != (KEY_SOFT_TIME) ) )
+ io_K |= 0x1;
+
+ if (((gw_keyboard[Sx] & GW_MASK_K2) & (keys_pressed << 8)) != 0)
+ if ( ( (gw_keyboard[Sx] & GW_MASK_K2) != (KEY_SOFT_ALARM << 8) ) & ( (gw_keyboard[Sx] & GW_MASK_K2) != (KEY_SOFT_TIME << 8) ) )
+
+ io_K |= 0x2;
+ if (((gw_keyboard[Sx] & GW_MASK_K3) & (keys_pressed << 16)) != 0)
+ if ( ( (gw_keyboard[Sx] & GW_MASK_K3) != (KEY_SOFT_ALARM << 16) ) & ( (gw_keyboard[Sx] & GW_MASK_K3) != (KEY_SOFT_TIME << 16) ) )
+
+ io_K |= 0x4;
+ if (((gw_keyboard[Sx] & GW_MASK_K4) & (keys_pressed << 24)) != 0)
+ if ( ( (gw_keyboard[Sx] & GW_MASK_K4) != (KEY_SOFT_ALARM << 24) ) & ( (gw_keyboard[Sx] & GW_MASK_K4) != (KEY_SOFT_TIME << 24) ) )
+
+ io_K |= 0x8;
+ }
+ }
+ }
+ //case of R/S output is not used to poll buttons (used R2 or S2 configuration)
+ // same algorithm as previously
+/* if (io_S == 0)
+ {
+ //dpad and shortcut
+ if (gw_keyboard_multikey[1])
+ {
+
+ // keep only relevant DPAD keys
+ keys_pressed = keys_pressed & (GW_BUTTON_LEFT + GW_BUTTON_RIGHT + GW_BUTTON_UP + GW_BUTTON_DOWN);
+
+ // manage when a single key is pressed but the emulated game expects only diagonal keys combination
+ // reuse the previous DPAD value (previous_dpad) and add a complementary key
+
+ if ( (dpad_shortcut_diagonal_pressed == 1 ) & (dpad_shortcut_diagonal_hold == 0)) {
+ dpad_shortcut_diagonal_hold = 1;
+ // toogle dpad values to move in diagonal
+ keys_pressed = ~previous_dpad & \
+ (GW_BUTTON_LEFT + GW_BUTTON_RIGHT + GW_BUTTON_UP + GW_BUTTON_DOWN);
+
+ }
+
+ if (keys_pressed == GW_BUTTON_LEFT)
+ keys_pressed = (previous_dpad & (GW_BUTTON_UP + GW_BUTTON_DOWN)) | GW_BUTTON_LEFT;
+
+ if (keys_pressed == GW_BUTTON_RIGHT)
+ keys_pressed = (previous_dpad & (GW_BUTTON_UP + GW_BUTTON_DOWN)) | GW_BUTTON_RIGHT;
+
+ if (keys_pressed == GW_BUTTON_DOWN)
+ keys_pressed = (previous_dpad & (GW_BUTTON_LEFT + GW_BUTTON_RIGHT)) | GW_BUTTON_DOWN;
+
+ if (keys_pressed == GW_BUTTON_UP)
+ keys_pressed = (previous_dpad & (GW_BUTTON_LEFT + GW_BUTTON_RIGHT)) | GW_BUTTON_UP;
+
+ if ((gw_keyboard[1] & GW_MASK_K1) == keys_pressed)
+ {
+ io_K |= 0x1;
+ previous_dpad = keys_pressed;
+ }
+ if ((gw_keyboard[1] & GW_MASK_K2) == (keys_pressed << 8))
+ {
+ io_K |= 0x2;
+ previous_dpad = keys_pressed;
+ }
+ if ((gw_keyboard[1] & GW_MASK_K3) == (keys_pressed << 16))
+ {
+ io_K |= 0x4;
+ previous_dpad = keys_pressed;
+ }
+ if ((gw_keyboard[1] & GW_MASK_K4) == (keys_pressed << 24))
+ {
+ io_K |= 0x8;
+ previous_dpad = keys_pressed;
+ }
+ }
+ else
+ {
+
+ // check soft key
+ if (key_soft_value)
+ {
+
+ if (((gw_keyboard[1] & GW_MASK_K1) == (key_soft_value)))
+ io_K |= 0x1;
+ if (((gw_keyboard[1] & GW_MASK_K2) == (key_soft_value << 8)))
+ io_K |= 0x2;
+ if (((gw_keyboard[1] & GW_MASK_K3) == (key_soft_value << 16)))
+ io_K |= 0x4;
+ if (((gw_keyboard[1] & GW_MASK_K4) == (key_soft_value << 24)))
+ io_K |= 0x8;
+ }
+ else
+ {
+ if ( (gw_keyboard[1] != KEY_SOFT_TIME) | (gw_keyboard[1] !=KEY_SOFT_ALARM) ) {
+ if (((gw_keyboard[1] & GW_MASK_K1) & (keys_pressed)) != 0)
+ io_K |= 0x1;
+ if (((gw_keyboard[1] & GW_MASK_K2) & (keys_pressed << 8)) != 0)
+ io_K |= 0x2;
+ if (((gw_keyboard[1] & GW_MASK_K3) & (keys_pressed << 16)) != 0)
+ io_K |= 0x4;
+ if (((gw_keyboard[1] & GW_MASK_K4) & (keys_pressed << 24)) != 0)
+ io_K |= 0x8;
+ }
+ }
+ }
+ } */
+ }
+
+ return io_K & 0xf;
+}
+
+/* external function use to execute some clock cycles */
+int gw_system_run(int clock_cycles)
+{
+ // check if a key is pressed to wakeup the system
+ // set K input lines active state
+ sm510.m_k_active = (gw_get_buttons() != 0);
+
+ //1 CPU operation in 2 clock cycles
+ if (sm510.m_clk_div == 2)
+ sm510.m_icount += (clock_cycles / 2);
+
+ //1 CPU operation in 4 clock cycles
+ if (sm510.m_clk_div == 4)
+ sm510.m_icount += (clock_cycles / 4);
+
+ device_run();
+
+ // return cycles really executed according to divider
+ return sm510.m_icount * sm510.m_clk_div;
+}
+
+/* Shutdown gw */
+void gw_system_shutdown(void)
+{
+ /* change audio frequency to default audio clock */
+ //gw_set_audio_frequency(48000);
+}
+
+static gw_state_t save_state;
+
+/* save state */
+bool gw_state_save(void *dest_ptr)
+{
+ /* add header and signature */
+ memcpy(&save_state.magic_word, GW_MAGIC_WORD, 8);
+ memcpy(&save_state.rom_signature, &gw_head.rom_signature, 8);
+
+ /* dump all variables from sm510base.c */
+
+ // internal RAM 128x4 bits
+ memcpy(&save_state.gw_ram, &sm510.gw_ram, sizeof(sm510.gw_ram));
+ memcpy(&save_state.gw_ram_state, &sm510.gw_ram_state, sizeof(sm510.gw_ram_state));
+
+ //program counter, opcode,...
+ save_state.m_pc = sm510.m_pc;
+ save_state.m_prev_pc = sm510.m_prev_pc;
+ save_state.m_op = sm510.m_op;
+ save_state.m_prev_op = sm510.m_prev_op;
+
+ save_state.m_param = sm510.m_param;
+ save_state.m_stack_levels = sm510.m_stack_levels;
+ memcpy(save_state.m_stack, &sm510.m_stack, sizeof(sm510.m_stack));
+ save_state.m_icount = sm510.m_icount;
+
+ save_state.m_acc = sm510.m_acc;
+ save_state.m_bl = sm510.m_bl;
+ save_state.m_bm = sm510.m_bm;
+ save_state.m_c = sm510.m_c;
+ save_state.m_w = sm510.m_w;
+ save_state.m_s_out = sm510.m_s_out;
+ save_state.m_r = sm510.m_r;
+ save_state.m_r_out = sm510.m_r_out;
+
+ save_state.bool_m_k_active = (un8)sm510.m_k_active;
+ save_state.bool_m_halt = (un8)sm510.m_halt;
+ save_state.bool_m_sbm = (un8)sm510.m_sbm;
+ save_state.bool_m_sbl = (un8)sm510.m_sbl;
+ save_state.bool_m_skip = (un8)sm510.m_skip;
+
+ // freerun time counter
+ save_state.m_div = sm510.m_div;
+ save_state.bool_m_1s = (un8)sm510.m_1s;
+ save_state.m_clk_div = sm510.m_clk_div;
+
+ // melody controller
+ save_state.m_r_mask_option = sm510.m_r_mask_option;
+ save_state.m_melody_rd = sm510.m_melody_rd;
+ save_state.m_melody_step_count = sm510.m_melody_step_count;
+ save_state.m_melody_duty_count = sm510.m_melody_duty_count;
+ save_state.m_melody_duty_index = sm510.m_melody_duty_index;
+ save_state.m_melody_address = sm510.m_melody_address;
+
+ // lcd driver
+ save_state.m_l = sm510.m_l;
+ save_state.m_x = sm510.m_x;
+ save_state.m_y = sm510.m_y;
+ save_state.m_bp = sm510.m_bp;
+ save_state.bool_m_bc = (un8)sm510.m_bc;
+
+ // SM500 internals
+ save_state.m_o_pins = sm510.m_o_pins;
+ memcpy(&save_state.m_ox, &sm510.m_ox, sizeof(sm510.m_ox));
+ memcpy(&save_state.m_o, &sm510.m_o, sizeof(sm510.m_o));
+ memcpy(&save_state.m_ox_state, &sm510.m_ox_state, sizeof(sm510.m_ox_state));
+ memcpy(&save_state.m_o_state, &sm510.m_o_state, sizeof(sm510.m_o_state));
+
+ save_state.m_cn = sm510.m_cn;
+ save_state.m_mx = sm510.m_mx;
+
+ save_state.m_cb = sm510.m_cb;
+ save_state.m_s = sm510.m_s;
+ save_state.bool_m_rsub = (un8)sm510.m_rsub;
+
+ /* save state */
+ memcpy(dest_ptr, &save_state, sizeof(save_state));
+ return true;
+}
+
+/* load state */
+bool gw_state_load(void *src_ptr)
+{
+
+ memcpy(&save_state, src_ptr, sizeof(save_state));
+
+ /* Check header and signature */
+ if (memcmp(&save_state.magic_word, GW_MAGIC_WORD, 8) != 0)
+ return false;
+ if (memcmp(&save_state.rom_signature, &gw_head.rom_signature, 8) != 0)
+ return false; // 16
+
+ /* set all variables from sm510base.c */
+
+ // internal RAM 128x4 bits
+ memcpy(&sm510.gw_ram, &save_state.gw_ram, sizeof(sm510.gw_ram));
+ memcpy(&sm510.gw_ram_state, &save_state.gw_ram_state, sizeof(sm510.gw_ram_state));
+
+ //program counter, opcode
+ sm510.m_pc = save_state.m_pc;
+ sm510.m_prev_pc = save_state.m_prev_pc;
+ sm510.m_op = save_state.m_op;
+ sm510.m_prev_op = save_state.m_prev_op;
+
+ sm510.m_param = save_state.m_param;
+ sm510.m_stack_levels = save_state.m_stack_levels;
+ memcpy(sm510.m_stack, &save_state.m_stack, sizeof(sm510.m_stack));
+ sm510.m_icount = save_state.m_icount;
+
+ sm510.m_acc = save_state.m_acc;
+ sm510.m_bl = save_state.m_bl;
+ sm510.m_bm = save_state.m_bm;
+ sm510.m_c = save_state.m_c;
+ sm510.m_w = save_state.m_w;
+ sm510.m_s_out = save_state.m_s_out;
+ sm510.m_r = save_state.m_r;
+ sm510.m_r_out = save_state.m_r_out;
+
+ sm510.m_k_active = (bool)save_state.bool_m_k_active;
+ sm510.m_halt = (bool)save_state.bool_m_halt;
+ sm510.m_sbm = (bool)save_state.bool_m_sbm;
+ sm510.m_sbl = (bool)save_state.bool_m_sbl;
+ sm510.m_skip = (bool)save_state.bool_m_skip;
+
+ // melody controller
+ sm510.m_r_mask_option = save_state.m_r_mask_option;
+ sm510.m_melody_rd = save_state.m_melody_rd;
+ sm510.m_melody_step_count = save_state.m_melody_step_count;
+ sm510.m_melody_duty_count = save_state.m_melody_duty_count;
+ sm510.m_melody_duty_index = save_state.m_melody_duty_index;
+ sm510.m_melody_address = save_state.m_melody_address;
+
+ // freerun time counter
+ sm510.m_clk_div = save_state.m_clk_div;
+ sm510.m_div = save_state.m_div;
+ sm510.m_1s = (bool)save_state.bool_m_1s;
+ sm510.m_melody_duty_index = save_state.m_melody_duty_index;
+ sm510.m_melody_address = save_state.m_melody_address;
+
+ // lcd driver
+ sm510.m_l = save_state.m_l;
+ sm510.m_x = save_state.m_x;
+ sm510.m_y = save_state.m_y;
+ sm510.m_bp = save_state.m_bp;
+ sm510.m_bc = (bool)save_state.bool_m_bc;
+
+ // SM500 internals
+ sm510.m_o_pins = save_state.m_o_pins;
+ memcpy(&sm510.m_ox, &save_state.m_ox, sizeof(sm510.m_ox));
+ memcpy(&sm510.m_o, &save_state.m_o, sizeof(sm510.m_o));
+ memcpy(&sm510.m_ox_state, &save_state.m_ox_state, sizeof(sm510.m_ox_state));
+ memcpy(&sm510.m_o_state, &save_state.m_o_state, sizeof(sm510.m_o_state));
+
+ sm510.m_cn = save_state.m_cn;
+ sm510.m_mx = save_state.m_mx;
+
+ sm510.m_cb = save_state.m_cb;
+ sm510.m_s = save_state.m_s;
+ sm510.m_rsub = (bool)save_state.bool_m_rsub;
+
+ return true;
+}
+
+gw_time_t gw_system_get_time()
+{
+ gw_time_t time = {0};
+
+ /* Rom hour is not set ? */
+ if ((gw_head.time_hour_address_msb == 0) && (gw_head.time_hour_address_lsb == 0)) {
+
+ // return time.hours > 24 to indicate the feature is not support
+ time.hours = 127;
+ return time;
+ }
+
+ // AM/PM is not supported
+ if (gw_head.time_hour_msb_pm == 0) {
+
+ // return time.hours > 24 to indicate the feature is not support
+ time.hours = 127;
+ return time;
+ }
+
+ unsigned int hour_msb;
+ unsigned int hour_lsb;
+ unsigned int pm_flag;
+
+
+ hour_msb = sm510.gw_ram[gw_head.time_hour_address_msb];
+ hour_lsb = sm510.gw_ram[gw_head.time_hour_address_lsb];
+ pm_flag = gw_head.time_hour_msb_pm;
+
+ /* Minutes */
+ time.minutes = (sm510.gw_ram[gw_head.time_min_address_msb] * 10) + \
+ sm510.gw_ram[gw_head.time_min_address_lsb];
+
+ /* Seconds */
+ time.seconds = (sm510.gw_ram[gw_head.time_sec_address_msb] * 10) + \
+ sm510.gw_ram[gw_head.time_sec_address_lsb];
+
+ //PM
+ if (hour_msb & pm_flag) {
+ hour_msb = hour_msb & ~pm_flag;
+
+ // PM12
+ if ( (hour_msb == 1) && (hour_lsb == 2) ) time.hours = 12;
+
+ // PM1 <-> PM11
+ else time.hours = (10 * hour_msb) + 12 + hour_lsb;
+
+ //AM
+ } else {
+ // AM12
+ if ( (hour_msb == 1) && (hour_lsb == 2) ) time.hours = 0;
+
+ // AM1 <-> AM11
+ else time.hours = (10 * hour_msb) + hour_lsb;
+ }
+
+ return time;
+
+}
+
+void gw_system_set_time(gw_time_t time)
+{
+ /* Rom hour is not set ? */
+ if ((gw_head.time_hour_address_msb == 0) & (gw_head.time_hour_address_lsb == 0))
+ return;
+
+ /* Hours */
+ // AM1 <-> AM11
+ if ((time.hours > 0) && (time.hours < 12))
+ {
+ sm510.gw_ram[gw_head.time_hour_address_msb] = time.hours / 10;
+ sm510.gw_ram[gw_head.time_hour_address_lsb] = time.hours % 10;
+ }
+
+ // AM12
+ if (time.hours == 0)
+ {
+ sm510.gw_ram[gw_head.time_hour_address_msb] = 1;
+ sm510.gw_ram[gw_head.time_hour_address_lsb] = 2;
+ }
+
+ // PM12
+ if (time.hours == 12)
+ {
+ sm510.gw_ram[gw_head.time_hour_address_msb] = gw_head.time_hour_msb_pm + 1;
+ sm510.gw_ram[gw_head.time_hour_address_lsb] = 2;
+ }
+
+ // PM1 <-> PM11
+ if (time.hours > 12)
+ {
+ sm510.gw_ram[gw_head.time_hour_address_msb] = gw_head.time_hour_msb_pm + ((time.hours - 12) / 10);
+ sm510.gw_ram[gw_head.time_hour_address_lsb] = (time.hours - 12) % 10;
+ }
+
+ /* Minutes */
+ sm510.gw_ram[gw_head.time_min_address_msb] = time.minutes / 10;
+ sm510.gw_ram[gw_head.time_min_address_lsb] = time.minutes % 10;
+
+ /* Seconds */
+ sm510.gw_ram[gw_head.time_sec_address_msb] = time.seconds / 10;
+ sm510.gw_ram[gw_head.time_sec_address_lsb] = time.seconds % 10;
+}
\ No newline at end of file
diff --git a/games/retrogo/src/gw/gw_system.h b/games/retrogo/src/gw/gw_system.h
new file mode 100644
index 00000000..3b8c01ef
--- /dev/null
+++ b/games/retrogo/src/gw/gw_system.h
@@ -0,0 +1,173 @@
+/*
+
+This program implements the main functions to use the LCD Game emulator.
+It implements also sound buzzer and keyboard functions.
+
+This program is free software: you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free Software
+Foundation, either version 3 of the License, or (at your option) any later
+version.
+This program is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+You should have received a copy of the GNU General Public License along with
+this program. If not, see <http://www.gnu.org/licenses/>.
+
+__author__ = "bzhxx"
+__contact__ = "https://github.com/bzhxx"
+__license__ = "GPLv3"
+
+*/
+#ifndef _GW_SYSTEM_H_
+#define _GW_SYSTEM_H_
+
+#include "gw_type_defs.h"
+
+#define GW_SCREEN_WIDTH 320
+#define GW_SCREEN_HEIGHT 240
+
+/* refresh rate 128Hz */
+#define GW_REFRESH_RATE 128
+
+/* System clock = Audio clock = 32768Hz */
+#define GW_SYS_FREQ 32768U
+#define GW_AUDIO_FREQ GW_SYS_FREQ
+
+#define GW_AUDIO_BUFFER_LENGTH (GW_AUDIO_FREQ / GW_REFRESH_RATE)
+
+/* emulated system : number of clock cycles per loop */
+#define GW_SYSTEM_CYCLES (GW_AUDIO_FREQ / GW_REFRESH_RATE)
+
+/* Main API to emulate the system */
+
+// Configure, start and reset (in this order)
+bool gw_system_config();
+void gw_system_start();
+void gw_system_reset();
+
+// Run some clock cycles and refresh the display
+int gw_system_run(int clock_cycles);
+void gw_system_blit(unsigned short *active_framebuffer);
+
+// Audio init
+void gw_system_sound_init();
+
+// ROM loader
+bool gw_system_romload();
+
+// get buttons state
+unsigned int gw_get_buttons();
+
+bool gw_state_load(void *src_ptr);
+bool gw_state_save(void *dest_ptr);
+
+typedef struct gw_time_s
+{
+ unsigned char hours; // 24 format
+ unsigned char minutes;
+ unsigned char seconds;
+} gw_time_t;
+
+void gw_system_set_time(gw_time_t time);
+gw_time_t gw_system_get_time();
+
+/* shared audio buffer between host and emulator */
+extern unsigned char gw_audio_buffer[GW_AUDIO_BUFFER_LENGTH * 2];
+extern bool gw_audio_buffer_copied;
+
+/* Output of emulated system */
+void gw_writeR(unsigned char data);
+
+/* Input of emulated system */
+unsigned char gw_readK(unsigned char S);
+unsigned char gw_readBA();
+unsigned char gw_readB();
+
+#define GW_BUTTON_LEFT 1
+#define GW_BUTTON_UP (1 << 1)
+#define GW_BUTTON_RIGHT (1 << 2)
+#define GW_BUTTON_DOWN (1 << 3)
+#define GW_BUTTON_A (1 << 4)
+#define GW_BUTTON_B (1 << 5)
+#define GW_BUTTON_TIME (1 << 6)
+#define GW_BUTTON_GAME (1 << 7)
+
+#define GW_MASK_K1 0x000000ff
+#define GW_MASK_K2 0x0000ff00
+#define GW_MASK_K3 0x00ff0000
+#define GW_MASK_K4 0xff000000
+
+/* Game & Watch Magic word for save file */
+#define GW_MAGIC_WORD "G&WS\x00\x00\x00\x05"
+
+/* Game & Watch Save state */
+typedef struct gw_state_s
+{
+ /* Magic work to check if it's Game & Watch Save structure */
+ char magic_word[8];
+
+ /* Signature of the original ROM name (8 last characters) */
+ /* used to check coherency with save */
+ char rom_signature[8];
+
+ // internal RAM 128x4 bits
+ un8 gw_ram[128];
+ un8 gw_ram_state[128];
+
+ u16 m_pc, m_prev_pc;
+ u16 m_op, m_prev_op;
+ u8 m_param;
+ int m_stack_levels;
+ u16 m_stack[4]; // max 4
+ int m_icount;
+
+ u8 m_acc;
+ u8 m_bl;
+ u8 m_bm;
+ u8 bool_m_sbm;
+ u8 bool_m_sbl;
+ u8 m_c;
+ u8 bool_m_skip;
+ u8 m_w, m_s_out;
+ u8 m_r, m_r_out;
+ int m_r_mask_option;
+ u8 bool_m_k_active;
+ u8 bool_m_halt;
+ int m_clk_div;
+
+ // melody controller
+ u8 m_melody_rd;
+ u8 m_melody_step_count;
+ u8 m_melody_duty_count;
+ u8 m_melody_duty_index;
+ u8 m_melody_address;
+
+ // freerun time counter
+ u16 m_div;
+ u8 bool_m_1s;
+
+ // lcd driver
+ u8 flag_lcd_deflicker_level;
+ u8 m_l, m_x;
+ u8 m_y;
+ u8 m_bp;
+ u8 bool_m_bc;
+
+ // SM500 internals
+ int m_o_pins; // number of 4-bit O pins
+ u8 m_ox[9]; // W' latch, max 9
+ u8 m_o[9]; // W latch
+ u8 m_ox_state[9]; // W' latch, max 9
+ u8 m_o_state[9]; // W latch
+
+ u8 m_cn;
+ u8 m_mx;
+ u8 trs_field;
+
+ u8 m_cb;
+ u8 m_s;
+ u8 bool_m_rsub;
+
+} gw_state_t;
+
+#endif /* _GW_SYSTEM_H_ */
diff --git a/games/retrogo/src/gw/gw_type_defs.h b/games/retrogo/src/gw/gw_type_defs.h
new file mode 100644
index 00000000..586531f3
--- /dev/null
+++ b/games/retrogo/src/gw/gw_type_defs.h
@@ -0,0 +1,19 @@
+#ifndef __GW_TYPE_DEFS_H__
+#define __GW_TYPE_DEFS_H__
+
+typedef unsigned char byte;
+typedef unsigned char un8,u8,uint8;
+typedef unsigned short un16,u16,uint16;
+typedef unsigned int un32,u32,uint32;
+typedef signed char n8;
+typedef signed short n16;
+typedef signed int n32;
+typedef un16 word;
+typedef word addr;
+
+#include <stdio.h>
+#include <stdbool.h>
+#include <string.h>
+#include <stdlib.h>
+
+#endif
diff --git a/games/retrogo/src/gw/sm500.h b/games/retrogo/src/gw/sm500.h
new file mode 100644
index 00000000..ee9dace1
--- /dev/null
+++ b/games/retrogo/src/gw/sm500.h
@@ -0,0 +1,118 @@
+// license:BSD-3-Clause
+// copyright-holders:hap
+// modded by bzhxx
+/*
+
+ Sharp SM500 MCU family cores
+
+*/
+
+#ifndef _SM500_H_
+#define _SM500_H_
+
+#pragma once
+
+#include "gw_type_defs.h"
+
+// device-level SM5A/SM500 API
+void sm500_device_start();
+void sm500_device_reset();
+void sm500_execute_run();
+
+void sm500_get_opcode_param();
+void sm500_div_timer(int nb_inst);
+void sm500_update_segments_state();
+
+void sm500_reset_vector();
+void sm500_wakeup_vector();
+bool sm500_wake_me_up();
+
+void shift_w();
+u8 get_digit();
+void set_su(u8 su);
+u8 get_su();
+int get_trs_field();
+
+//variation SM5A
+void sm5a_device_start();
+void sm5a_device_reset();
+void sm5a_execute_run();
+
+// opcode handlers for SM5A,SM500
+// other opcodes are also used from SM510
+
+/*Start of list */
+
+void sm500_op_lax();
+void sm500_op_adx();
+void sm500_op_rm();
+void sm500_op_sm();
+void sm500_op_exc();
+void sm500_op_exci();
+void sm500_op_lda();
+void sm500_op_excd();
+void sm500_op_tmi();
+void sm500_op_skip();
+void sm500_op_atr();
+void sm500_op_add();
+void sm500_op_add11();
+void sm500_op_coma();
+void sm500_op_exbla();
+
+void sm500_op_tal();
+void sm500_op_tb();
+void sm500_op_tc();
+void sm500_op_tam();
+void sm500_op_tis();
+
+void sm500_op_ta0();
+void sm500_op_tabl();
+
+// custom
+void sm500_op_lbl();
+
+void sm500_op_rc();
+void sm500_op_sc();
+void sm500_op_kta();
+
+void sm500_op_decb();
+
+void sm500_op_rtn1();
+
+void sm500_op_cend();
+void sm500_op_dta();
+void sm500_op_illegal();
+
+/*End of OP list : SM510 */
+
+// SM500 specific instruction or deviation
+void sm500_op_lb();
+void sm500_op_incb(); //SM510
+void sm500_op_sbm(); //SM510
+void sm500_op_rbm();
+
+void sm500_op_comcb();
+void sm500_op_rtn0(); //SM510
+void sm500_op_ssr();
+void sm500_op_tr();
+void sm500_op_trs();
+
+void sm500_op_atbp(); //SM510
+void sm500_op_ptw(); //SM510
+void sm500_op_tw();
+void sm500_op_pdtw();
+void sm500_op_dtw();
+void sm500_op_wr(); //SM510
+void sm500_op_ws(); //SM510
+
+void sm500_op_ats();
+void sm500_op_exksa();
+void sm500_op_exkfa();
+
+void sm500_op_idiv(); //SM510
+
+void sm500_op_rmf();
+void sm500_op_smf();
+void sm500_op_comcn();
+
+#endif // _SM500_H_
diff --git a/games/retrogo/src/gw/sm500core.c b/games/retrogo/src/gw/sm500core.c
new file mode 100644
index 00000000..2af20b8d
--- /dev/null
+++ b/games/retrogo/src/gw/sm500core.c
@@ -0,0 +1,409 @@
+// license:BSD-3-Clause
+// copyright-holders:hap
+// modded by bzhxx
+/*
+
+ Sharp SM500 MCU core implementation
+
+ TODO:
+ - EXKSA, EXKFA opcodes
+ - unknown which O group is which W output, guessed for now (segments and H should be ok)
+
+*/
+
+#include "gw_type_defs.h"
+#include "sm510.h"
+#include "sm500.h"
+
+//-------------------------------------------------
+// device_start - device-specific startup
+//-------------------------------------------------
+
+void sm500_device_start()
+{
+ // common init (not everything is used though)
+ sm510_device_start();
+
+ // init/zerofill
+ memset(m_ox, 0, sizeof(m_ox));
+ memset(m_o, 0, sizeof(m_o));
+
+ memset(m_ox_state, 0, sizeof(m_ox_state));
+ memset(m_o_state, 0, sizeof(m_o_state));
+
+ m_stack_levels = 1; /* stack levels */
+
+ /* o group pins */
+ m_o_pins = 7;
+
+ /* prg width */
+ m_prgwidth = 11;
+
+ /*data width */
+ m_datawidth = 6;
+
+ m_prgmask = (1 << m_prgwidth) - 1;
+ m_datamask = (1 << m_datawidth) - 1;
+
+ trs_field = 0;
+
+ m_cn = 0;
+ m_mx = 0;
+ m_cb = 0;
+ m_s = 0;
+ m_rsub = false;
+
+ m_r_mask_option = RMASK_DIRECT;
+
+ // register for savestates
+ // save_item(NAME(m_ox));
+ // save_item(NAME(m_o));
+ // save_item(NAME(m_cn));
+ // save_item(NAME(m_mx));
+ // save_item(NAME(m_cb));
+ // save_item(NAME(m_s));
+ // save_item(NAME(m_rsub));
+}
+
+//-------------------------------------------------
+// device_reset - device-specific reset
+//-------------------------------------------------
+
+void sm500_device_reset()
+{
+
+ // common reset
+ sm510_device_reset();
+
+ // SM500 specific
+ sm500_reset_vector();
+ m_prev_pc = m_pc;
+ push_stack();
+ sm500_op_idiv();
+ m_1s = true;
+ m_cb = 0;
+ m_rsub = false;
+ m_r = 0xff;
+}
+
+//-------------------------------------------------
+// buzzer controller
+//-------------------------------------------------
+
+static inline void sm500_clock_melody()
+{
+ // R1 from divider or direct control, R2-R4 generic outputs
+ u8 mask = (m_r_mask_option == RMASK_DIRECT) ? 1 : (m_div >> m_r_mask_option & 1);
+ u8 out = (mask & ~m_r) | (~m_r & 0xe);
+
+ m_r_out = out;
+ m_write_r(m_r_out);
+
+ // output to R pins
+
+ // if (out != m_r_out)
+ // {
+ // m_write_r(m_r_out);
+ // m_r_out = out;
+ // }
+}
+
+//-------------------------------------------------
+// execute
+//-------------------------------------------------
+inline bool sm500_wake_me_up()
+{
+ // in halt mode, wake up after 1S signal or K input
+ if (m_k_active || m_1s)
+ {
+ // note: official doc warns that Bl/Bm and the stack are undefined
+ // after waking up, but we leave it unchanged
+ m_halt = false;
+ sm500_wakeup_vector();
+
+ return true;
+ }
+ else
+ return false;
+}
+
+/********** 1 second timer *********/
+
+static inline void sm500_div_timer_cb()
+{
+ m_div = (m_div + 1) & 0x7fff;
+
+ // 1S signal on overflow(falling edge of F1)
+ if (m_div == 0)
+ {
+ m_1s = true;
+
+ /* refresh LCD segments state every seconds under sleep mode */
+ if (m_halt)
+ sm500_update_segments_state();
+ }
+
+ sm500_clock_melody();
+}
+
+inline void sm500_div_timer(int nb_inst)
+{
+ if (nb_inst > 0)
+ for (int toctoc = 0; toctoc < m_clk_div * nb_inst; toctoc++)
+ sm500_div_timer_cb();
+}
+
+void sm500_get_opcode_param()
+{
+ // LBL and prefix opcodes are 2 bytes
+ if (m_op == 0x5e || m_op == 0x5f)
+ {
+ m_icount--;
+
+ m_param = read_byte_program(m_pc);
+
+ increment_pc();
+ }
+}
+
+void sm500_execute_one()
+{
+ switch (m_op & 0xf0)
+ {
+ case 0x20:
+ sm500_op_lax();
+ break;
+ case 0x30:
+ if (m_op == 0x30)
+ sm500_op_ats(); // !
+ else
+ sm500_op_adx();
+ break;
+ case 0x40:
+ sm500_op_lb();
+ break;
+ case 0x70:
+ sm500_op_ssr();
+ break;
+
+ case 0x80:
+ case 0x90:
+ case 0xa0:
+ case 0xb0:
+ sm500_op_tr();
+ break;
+ case 0xc0:
+ case 0xd0:
+ case 0xe0:
+ case 0xf0:
+ sm500_op_trs();
+ break;
+
+ default:
+ switch (m_op & 0xfc)
+ {
+ case 0x04:
+ sm500_op_rm();
+ break;
+ case 0x0c:
+ sm500_op_sm();
+ break;
+ case 0x10:
+ sm500_op_exc();
+ break;
+ case 0x14:
+ sm500_op_exci();
+ break;
+ case 0x18:
+ sm500_op_lda();
+ break;
+ case 0x1c:
+ sm500_op_excd();
+ break;
+ case 0x54:
+ sm500_op_tmi();
+ break; // TM
+
+ default:
+ switch (m_op)
+ {
+ case 0x00:
+ sm500_op_skip();
+ break;
+ case 0x01:
+ sm500_op_atr();
+ break;
+ case 0x02:
+ sm500_op_exksa();
+ break;
+ case 0x03:
+ sm500_op_atbp();
+ break;
+ case 0x08:
+ sm500_op_add();
+ break;
+ case 0x09:
+ sm500_op_add11();
+ break; // ADDC
+ case 0x0a:
+ sm500_op_coma();
+ break;
+ case 0x0b:
+ sm500_op_exbla();
+ break;
+
+ case 0x50:
+ sm500_op_tal();
+ break; // TA
+ case 0x51:
+ sm500_op_tb();
+ break;
+ case 0x52:
+ sm500_op_tc();
+ break;
+ case 0x53:
+ sm500_op_tam();
+ break;
+ case 0x58:
+ sm500_op_tis();
+ break; // TG
+ case 0x59:
+ sm500_op_ptw();
+ break;
+ case 0x5a:
+ sm500_op_ta0();
+ break;
+ case 0x5b:
+ sm500_op_tabl();
+ break;
+ case 0x5c:
+ sm500_op_tw();
+ break;
+ case 0x5d:
+ sm500_op_dtw();
+ break;
+ case 0x5f:
+ sm500_op_lbl();
+ break;
+
+ case 0x60:
+ sm500_op_comcn();
+ break;
+ case 0x61:
+ sm500_op_pdtw();
+ break;
+ case 0x62:
+ sm500_op_wr();
+ break;
+ case 0x63:
+ sm500_op_ws();
+ break;
+ case 0x64:
+ sm500_op_incb();
+ break;
+ case 0x65:
+ sm500_op_idiv();
+ break;
+ case 0x66:
+ sm500_op_rc();
+ break;
+ case 0x67:
+ sm500_op_sc();
+ break;
+ case 0x68:
+ sm500_op_rmf();
+ break;
+ case 0x69:
+ sm500_op_smf();
+ break;
+ case 0x6a:
+ sm500_op_kta();
+ break;
+ case 0x6b:
+ sm500_op_exkfa();
+ break;
+ case 0x6c:
+ sm500_op_decb();
+ break;
+ case 0x6d:
+ sm500_op_comcb();
+ break;
+ case 0x6e:
+ sm500_op_rtn0();
+ break; // RTN
+ case 0x6f:
+ sm500_op_rtn1();
+ break; // RTNS
+
+ // extended opcodes
+ case 0x5e:
+ m_op = m_op << 8 | m_param;
+ switch (m_param)
+ {
+ case 0x00:
+ sm500_op_cend();
+ break;
+ case 0x04:
+ sm500_op_dta();
+ break;
+
+ default:
+ sm500_op_illegal();
+ break;
+ }
+ break; // 0x5e
+
+ default:
+ sm500_op_illegal();
+ break;
+ }
+ break; // 0xff
+ }
+ break; // 0xfc
+
+ } // big switch
+}
+
+
+void sm500_execute_run()
+{
+ int reamining_icount = m_icount;
+
+ while (m_icount > 0)
+ {
+ m_icount--;
+
+ if (m_halt && !sm500_wake_me_up())
+ {
+ sm500_div_timer(reamining_icount);
+
+ // got nothing to do
+ m_icount = 0;
+ return;
+ }
+
+ // remember previous state
+ m_prev_op = m_op;
+ m_prev_pc = m_pc;
+
+ // fetch next opcode
+ m_op = read_byte_program(m_pc);
+
+ increment_pc();
+ sm500_get_opcode_param();
+
+ // handle opcode if it's not skipped
+ if (m_skip)
+ {
+ m_skip = false;
+ m_op = 0; // fake nop
+ }
+ else
+ sm500_execute_one();
+
+ // clock: spent time
+ sm500_div_timer(reamining_icount - m_icount);
+
+ reamining_icount = m_icount;
+ }
+}
\ No newline at end of file
diff --git a/games/retrogo/src/gw/sm500op.c b/games/retrogo/src/gw/sm500op.c
new file mode 100644
index 00000000..79bd03d0
--- /dev/null
+++ b/games/retrogo/src/gw/sm500op.c
@@ -0,0 +1,354 @@
+// license:BSD-3-Clause
+// copyright-holders:hap, Igor
+// modded by bzhxx
+
+// SM500 shared opcode handlers
+
+#include "gw_type_defs.h"
+#include "gw_system.h"
+#include "sm510.h"
+#include "sm500.h"
+
+// internal helpers
+
+//-------------------------------------------------
+// Vector table reset & wakeup
+//-------------------------------------------------
+
+void sm500_reset_vector() { do_branch(0, 0xf, 0); }
+void sm500_wakeup_vector() { m_cb = 0; do_branch(0, 0, 0); }
+
+void set_su(u8 su) { m_stack[0] = (m_stack[0] & ~0x3c0) | (su << 6 & 0x3c0); }
+u8 get_su() { return m_stack[0] >> 6 & 0xf; }
+
+// return 1 if SM5A or 0 if SM500
+int get_trs_field() { return trs_field; }
+
+void shift_w()
+{
+ // shifts internal W' latches
+ for (int i = 0; i < (m_o_pins-1); i++)
+ m_ox[i] = m_ox[i + 1];
+}
+
+/* to prevent from glich on display
+ [Alternative to MAME, // 1kHz display decay]
+ we mirror the output mo mox when the segments are
+ considered stable.
+ Typically, when the input are polled by
+ the functions : aplha,beta,K1..K4
+ TA:sm500_op_tal()
+ TB:sm500_op_tb()
+ KTA:sm500_op_kta()
+ optionally return function:rtn()
+ depending on flag_force_refresh_display from ROM flags
+*/
+
+void sm500_update_segments_state()
+{
+ // // Mirror the Outputs as segments states
+ for (int i = 0; i < m_o_pins; i++) {
+
+ m_o_state[i] = m_o[i];
+ m_ox_state[i] = m_ox[i];
+ }
+
+}
+
+u8 get_digit()
+{
+ // default digit segments PLA
+ static const u8 lut_digits[0x20] =
+ {
+ 0xe, 0x0, 0xc, 0x8, 0x2, 0xa, 0xe, 0x2, 0xe, 0xa, 0x0, 0x0, 0x2, 0xa, 0x2, 0x2,
+ 0xb, 0x9, 0x7, 0xf, 0xd, 0xe, 0xe, 0xb, 0xf, 0xf, 0x4, 0x0, 0xd, 0xe, 0x4, 0x0
+ };
+
+ return lut_digits[m_cn << 4 | m_acc] | (~m_cn & m_mx);
+}
+
+// instruction set
+
+// RAM address instructions
+
+void sm500_op_lb()
+{
+ // LB x: load BM/BL with 4-bit immediate value (partial)
+ m_bm = m_op & 3;
+ m_bl = (m_op >> 2 & 3) | ((m_op & 0xc) ? 8 : 0);
+}
+
+void sm500_op_incb()
+{
+ // INCB: increment BL, but overflow on 3rd bit!
+ m_bl = (m_bl + 1) & 0xf;
+ m_skip = (m_bl == 8);
+}
+
+void sm500_op_decb()
+{
+ // DECB: decrement BL, skip next on overflow
+ m_bl = (m_bl - 1) & 0xf;
+ m_skip = (m_bl == 0xf);
+}
+
+void sm500_op_sbm()
+{
+ // SBM: set RAM address high bit
+ m_bm |= 4;
+}
+
+void sm500_op_rbm()
+{
+ // RBM: reset RAM address high bit
+ m_bm &= ~4;
+}
+
+
+// ROM address instructions
+
+void sm500_op_comcb()
+{
+ // COMCB: complement CB
+ m_cb ^= 1;
+}
+
+void sm500_op_rtn0()
+{
+ if (flag_lcd_deflicker_level < 2 )
+ sm500_update_segments_state();
+
+ // RTN0: return from subroutine
+ pop_stack();
+ m_rsub = false;
+}
+
+void sm500_op_rtn1()
+{
+ // RTN0(RTN): return from subroutine
+ sm500_op_rtn0();
+ m_skip = true;
+}
+
+void sm500_op_ssr()
+{
+ // SSR x: set stack upper bits, also sets E flag for next opcode
+ set_su(m_op & 0xf);
+}
+
+void sm500_op_tr()
+{
+ // TR x: jump (long or short)
+ m_pc = (m_pc & ~0x3f) | (m_op & 0x3f);
+ if (!m_rsub)
+ do_branch(m_cb, get_su(), m_pc & 0x3f);
+}
+
+void sm500_op_trs()
+{
+
+ // TRS x: call subroutine
+ if (!m_rsub)
+ {
+ m_rsub = true;
+ u8 su = get_su();
+ push_stack();
+ do_branch(get_trs_field(), 0, m_op & 0x3f);
+
+ // E flag was set?
+ if ((m_prev_op & 0xf0) == 0x70)
+ do_branch(m_cb, su, m_pc & 0x3f);
+ }
+ else
+ m_pc = (m_pc & ~0xff) | (m_op << 2 & 0xc0) | (m_op & 0xf);
+}
+
+
+// Data transfer instructions
+void sm500_op_exc()
+{
+ // EXC x: exchange ACC with RAM, xor BM with x
+ u8 a = m_acc;
+ m_acc = ram_r();
+ ram_w(a);
+ m_bm ^= (m_op & 3);
+}
+
+void sm500_op_exci()
+{
+ // EXCI x: EXC x, INCB
+ sm500_op_exc();
+ sm500_op_incb();
+}
+
+void sm500_op_excd()
+{
+ // EXCD x: EXC x, DECB
+ sm500_op_exc();
+ sm500_op_decb();
+}
+
+void sm500_op_atbp()
+{
+ // ATBP: same as SM510, and set CN with ACC3
+ // ATBP: output ACC to BP(internal LCD backplate signal)
+ m_bp = m_acc & 1;
+ m_cn = m_acc >> 3 & 1;
+}
+
+void sm500_op_ptw()
+{
+ // PTW: partial transfer W' to W
+ m_o[m_o_pins-1] = m_ox[m_o_pins-1];
+ m_o[m_o_pins-2] = m_ox[m_o_pins-2];
+}
+
+void sm500_op_tw()
+{
+ // TW: transfer W' to W
+ for (int i = 0; i < m_o_pins; i++)
+ m_o[i] = m_ox[i];
+}
+
+void sm500_op_pdtw()
+{
+ // PDTW: partial shift digit into W'
+ m_ox[m_o_pins-2] = m_ox[m_o_pins-1];
+ m_ox[m_o_pins-1] = get_digit();
+}
+
+void sm500_op_dtw()
+{
+ // DTW: shift digit into W'
+ shift_w();
+ m_ox[m_o_pins-1] = get_digit();
+}
+
+void sm500_op_wr()
+{
+ // WR: shift ACC into W', reset last bit
+ shift_w();
+ m_ox[m_o_pins-1] = m_acc & 7;
+}
+
+void sm500_op_ws()
+{
+ // WR: shift ACC into W', set last bit
+ shift_w();
+ m_ox[m_o_pins-1] = m_acc | 8;
+}
+
+
+// I/O instructions
+void sm500_op_kta()
+{
+
+ //copy all segments states
+ sm500_update_segments_state();
+
+ // KTA: input K to ACC
+ //m_acc = gw_readK(~m_r & 0xf) & 0xf;
+ m_acc = gw_readK(m_r_out & 0xf) & 0xf;
+}
+
+void sm500_op_ats()
+{
+ // ATS: transfer ACC to S
+ m_s = m_acc;
+}
+
+void sm500_op_exksa()
+{
+ // EXKSA: x
+}
+
+void sm500_op_exkfa()
+{
+ // EXKFA: x
+}
+
+
+// Divider manipulation instructions
+
+void sm500_op_idiv()
+{
+ // IDIV: reset divider low 9 bits
+ m_div &= 0x3f;
+}
+
+
+// Bit manipulation instructions
+
+void sm500_op_rmf()
+{
+ // RMF: reset m' flag, also clears ACC
+ m_mx = 0;
+ m_acc = 0;
+}
+
+void sm500_op_smf()
+{
+ // SMF: set m' flag
+ m_mx = 1;
+}
+
+void sm500_op_comcn()
+{
+ // COMCN: complement CN flag
+ m_cn ^= 1;
+}
+
+void sm500_op_lax() { sm510_op_lax(); }
+void sm500_op_adx() { sm510_op_adx(); }
+void sm500_op_rm() { sm510_op_rm(); }
+void sm500_op_sm() { sm510_op_sm(); }
+//void sm500_op_exc() { sm510_op_exc(); }
+//void sm500_op_exci() { sm510_op_exci(); }
+void sm500_op_lda() { sm510_op_lda(); }
+//void sm500_op_excd() { sm510_op_excd(); }
+void sm500_op_tmi() { sm510_op_tmi(); }
+void sm500_op_skip() { sm510_op_skip(); }
+void sm500_op_atr() { sm510_op_atr(); }
+void sm500_op_add() { sm510_op_add(); }
+void sm500_op_add11() { sm510_op_add11(); }
+void sm500_op_coma() { sm510_op_coma(); }
+void sm500_op_exbla() { sm510_op_exbla(); }
+
+void sm500_op_tal() {
+ //copy all segments states
+ sm500_update_segments_state();
+
+ //sm510_op_tal();
+ // TAL: skip next if BA pin is set
+ m_skip = (m_read_ba() != 0);
+ }
+
+void sm500_op_tb() {
+ //copy all segments states
+ sm500_update_segments_state();
+
+ //sm510_op_tb();
+ // TB: skip next if B(beta) pin is set
+ m_skip = (m_read_b() != 0);
+ }
+
+void sm500_op_tc() { sm510_op_tc(); }
+void sm500_op_tam() { sm510_op_tam(); }
+void sm500_op_tis() { sm510_op_tis(); }
+
+void sm500_op_ta0() { sm510_op_ta0(); }
+void sm500_op_tabl() { sm510_op_tabl(); }
+
+void sm500_op_lbl() { sm510_op_lbl(); }
+
+void sm500_op_rc() { sm510_op_rc(); }
+void sm500_op_sc() { sm510_op_sc(); }
+
+// void sm500_op_kta() { sm510_op_kta(); }
+// void sm500_op_decb() { sm510_op_decb(); }
+// void sm500_op_rtn1() { sm510_op_rtn1(); }
+
+void sm500_op_cend() { sm510_op_cend(); }
+void sm500_op_dta() { sm510_op_dta(); }
+void sm500_op_illegal() { sm510_op_illegal(); }
+
\ No newline at end of file
diff --git a/games/retrogo/src/gw/sm510.h b/games/retrogo/src/gw/sm510.h
new file mode 100644
index 00000000..92efa6f5
--- /dev/null
+++ b/games/retrogo/src/gw/sm510.h
@@ -0,0 +1,258 @@
+// license:BSD-3-Clause
+// copyright-holders:hap
+// modded by bzhxx
+/*
+
+ Sharp SM510 MCU family cores
+
+*/
+
+#ifndef _SM510_H_
+#define _SM510_H_
+
+#pragma once
+
+#include "gw_type_defs.h"
+
+#define RMASK_DIRECT -1
+
+/* SM510 */
+void sm510_device_start();
+void sm510_device_reset();
+void sm510_execute_run();
+bool sm510_wake_me_up();
+void sm510_update_segments_state();
+void sm510_reset_vector();
+void sm510_wakeup_vector(); // after halt
+
+
+/* SM511 variation */
+void sm511_device_reset();
+void sm511_execute_run();
+bool sm511_init_melody(un8 *gw_melody);
+
+/*misc internal helpers for SM5XX microcomputer family */
+void pop_stack();
+void push_stack();
+void do_branch(u8 pu, u8 pm, u8 pl);
+u8 bitmask(u16 param);
+void increment_pc();
+void update_w_latch();
+extern u8 ram_r();
+extern void ram_w(u8 data);
+
+/*
+I/O
+inputs : K, B, BA
+outputs : S & R
+*/
+extern un8 m_read_k();
+
+extern un8 m_read_ba();
+
+extern un8 m_read_b();
+
+extern void m_write_s(un8);
+
+extern void m_write_r(un8);
+
+un8 read_byte_program(un16 rom_address);
+un8 readb(un8 ram_address);
+void writeb(un8 ram_address, un8 ram_data);
+
+//-------------------------------------------------------------
+// CPUs memory, registers & settings
+//-------------------------------------------------------------
+typedef struct
+{
+ un8 gw_ram[128];
+ un8 gw_ram_state[128];
+
+ int m_prgwidth;
+ int m_datawidth;
+ int m_prgmask;
+ int m_datamask;
+
+ u16 m_pc, m_prev_pc;
+ u16 m_op, m_prev_op;
+ u8 m_param;
+ int m_stack_levels;
+ u16 m_stack[4]; // max 4
+ int m_icount;
+
+ u8 m_acc;
+ u8 m_bl;
+ u8 m_bm;
+ bool m_sbm;
+ bool m_sbl;
+ u8 m_c;
+ bool m_skip;
+ u8 m_w,m_s_out;
+ u8 m_r, m_r_out;
+ int m_r_mask_option;
+ bool m_k_active;
+ bool m_halt;
+ int m_clk_div;
+
+// melody controller
+ u8 m_melody_rd;
+ u8 m_melody_step_count;
+ u8 m_melody_duty_count;
+ u8 m_melody_duty_index;
+ u8 m_melody_address;
+
+// freerun time counter
+ u16 m_div;
+ bool m_1s;
+
+// lcd driver
+ u8 m_l, m_x;
+ u8 m_y;
+ u8 m_bp;
+ bool m_bc;
+
+//sm500 internals
+ int m_o_pins; // number of 4-bit O pins
+ u8 m_ox[9]; // W' latch, max 9
+ u8 m_o[9]; // W latch
+ u8 m_ox_state[9]; // W' latch, max 9
+ u8 m_o_state[9]; // W latch
+
+ u8 m_cn;
+ u8 m_mx;
+ u8 trs_field;
+
+ u8 m_cb;
+ u8 m_s;
+ bool m_rsub;
+
+/* LCD deflicker filter level */
+/*
+0 : filter is disabled
+1 : refreshed on keys polling and call subroutine return
+2 : refreshed on keys polling only
+*/
+ u8 flag_lcd_deflicker_level;
+} sm510_t;
+
+extern sm510_t sm510;
+
+#ifndef GW_NO_SM510_DEFINES
+#define gw_ram sm510.gw_ram
+#define gw_ram_state sm510.gw_ram_state
+#define m_prgwidth sm510.m_prgwidth
+#define m_datawidth sm510.m_datawidth
+#define m_prgmask sm510.m_prgmask
+#define m_datamask sm510.m_datamask
+#define m_pc sm510.m_pc
+#define m_prev_pc sm510.m_prev_pc
+#define m_op sm510.m_op
+#define m_prev_op sm510.m_prev_op
+#define m_param sm510.m_param
+#define m_stack_levels sm510.m_stack_levels
+#define m_stack sm510.m_stack
+#define m_icount sm510.m_icount
+#define m_acc sm510.m_acc
+#define m_bl sm510.m_bl
+#define m_bm sm510.m_bm
+#define m_sbm sm510.m_sbm
+#define m_sbl sm510.m_sbl
+#define m_c sm510.m_c
+#define m_skip sm510.m_skip
+#define m_w sm510.m_w
+#define m_s_out sm510.m_s_out
+#define m_r sm510.m_r
+#define m_r_out sm510.m_r_out
+#define m_r_mask_option sm510.m_r_mask_option
+#define m_k_active sm510.m_k_active
+#define m_halt sm510.m_halt
+#define m_clk_div sm510.m_clk_div
+#define m_melody_rd sm510.m_melody_rd
+#define m_melody_step_count sm510.m_melody_step_count
+#define m_melody_duty_count sm510.m_melody_duty_count
+#define m_melody_duty_index sm510.m_melody_duty_index
+#define m_melody_address sm510.m_melody_address
+#define m_div sm510.m_div
+#define m_1s sm510.m_1s
+#define m_l sm510.m_l
+#define m_x sm510.m_x
+#define m_y sm510.m_y
+#define m_bp sm510.m_bp
+#define m_bc sm510.m_bc
+#define m_o_pins sm510.m_o_pins
+#define m_ox sm510.m_ox
+#define m_o sm510.m_o
+#define m_ox_state sm510.m_ox_state
+#define m_o_state sm510.m_o_state
+#define m_cn sm510.m_cn
+#define m_mx sm510.m_mx
+#define trs_field sm510.trs_field
+#define m_cb sm510.m_cb
+#define m_s sm510.m_s
+#define m_rsub sm510.m_rsub
+#define flag_lcd_deflicker_level sm510.flag_lcd_deflicker_level
+#endif
+
+// opcode handlers used by all CPUs
+void sm510_op_lbl();
+void sm510_op_lb();
+void sm510_op_sbl();
+void sm510_op_sbm();
+void sm510_op_exbla();
+void sm510_op_incb();
+void sm510_op_decb();
+void sm510_op_atpl();
+void sm510_op_rtn0();
+void sm510_op_rtn1();
+void sm510_op_tl();
+void sm510_op_tml();
+void sm510_op_tm();
+void sm510_op_t();
+void sm510_op_exc();
+void sm510_op_bdc();
+void sm510_op_exci();
+void sm510_op_excd();
+void sm510_op_lda();
+void sm510_op_lax();
+void sm510_op_ptw();
+void sm510_op_wr();
+void sm510_op_ws();
+void sm510_op_kta();
+void sm510_op_atbp();
+void sm510_op_atx();
+void sm510_op_atl();
+void sm510_op_atfc();
+void sm510_op_atr();
+void sm510_op_add();
+void sm510_op_add11();
+void sm510_op_adx();
+void sm510_op_coma();
+void sm510_op_rot();
+void sm510_op_rc();
+void sm510_op_sc();
+void sm510_op_tb();
+void sm510_op_tc();
+void sm510_op_tam();
+void sm510_op_tmi();
+void sm510_op_ta0();
+void sm510_op_tabl();
+void sm510_op_tis();
+void sm510_op_tal();
+void sm510_op_tf1();
+void sm510_op_tf4();
+void sm510_op_rm();
+void sm510_op_sm();
+void sm510_op_pre();
+void sm510_op_sme();
+void sm510_op_rme();
+void sm510_op_tmel();
+void sm510_op_skip();
+void sm510_op_cend();
+void sm510_op_idiv();
+void sm510_op_dr();
+void sm510_op_dta();
+void sm510_op_clklo();
+void sm510_op_clkhi();
+void sm510_op_illegal();
+
+#endif // _SM510_H_
diff --git a/games/retrogo/src/gw/sm510base.c b/games/retrogo/src/gw/sm510base.c
new file mode 100644
index 00000000..5beb180f
--- /dev/null
+++ b/games/retrogo/src/gw/sm510base.c
@@ -0,0 +1,141 @@
+// license:BSD-3-Clause
+// copyright-holders:hap
+// modded by bzhxx
+/*
+
+ Sharp SM5xx family, using SM510 as parent device
+
+ References:
+ - 1986 Sharp Semiconductor Data Book
+ - 1990 Sharp Microcomputers Data Book
+ - 1996 Sharp Microcomputer Databook
+ - KB1013VK1-2/KB1013VK4-2 manual
+
+ Default external frequency of these is 32.768kHz, forwarding a clockrate in the
+ MAME machine config is optional. Newer revisions can have an internal oscillator.
+
+*/
+
+#include "gw_type_defs.h"
+#include "gw_romloader.h"
+#include "gw_system.h"
+#include "sm510.h"
+
+sm510_t sm510;
+
+void update_w_latch() { m_write_s(m_w); } // W is connected directly to S
+
+//-------------------------------------------------
+// internal helpers to access memories
+//-------------------------------------------------
+//-------------------------------------------------
+// Memory access SM5xx family
+//-------------------------------------------------
+u8 ram_r()
+{
+ int blh = (m_sbl) ? 8 : 0; // from SBL (optional)
+ int bmh = (m_sbm) ? (1 << (m_datawidth - 1)) : 0; // from SBM
+ u8 address = (bmh | blh | m_bm << 4 | m_bl) & m_datamask;
+
+ if ((m_stack_levels == 1) & (address > 0x4f))
+ address &= 0x4f;
+
+ return readb(address) & 0xf;
+}
+
+void ram_w(u8 data)
+{
+ int blh = (m_sbl) ? 8 : 0; // from SBL (optional)
+ int bmh = (m_sbm) ? (1 << (m_datawidth - 1)) : 0; // from SBM
+ u8 address = (bmh | blh | m_bm << 4 | m_bl) & m_datamask;
+
+ if ((m_stack_levels == 1) & (address > 0x4f))
+ address &= 0x4f;
+
+ writeb(address, data & 0xf);
+}
+
+//-------------------------------------------------
+// Stack push & pop access SM5xx family
+//-------------------------------------------------
+
+void pop_stack()
+{
+ m_pc = m_stack[0] & m_prgmask;
+ for (int i = 0; i < m_stack_levels - 1; i++)
+ m_stack[i] = m_stack[i + 1];
+}
+
+void push_stack()
+{
+ for (int i = m_stack_levels - 1; i >= 1; i--)
+ m_stack[i] = m_stack[i - 1];
+ m_stack[0] = m_pc;
+}
+
+void do_branch(u8 pu, u8 pm, u8 pl)
+{
+ // set new PC(Pu/Pm/Pl)
+ m_pc = ((pu << 10) | (pm << 6 & 0x3c0) | (pl & 0x03f)) & m_prgmask;
+}
+
+u8 bitmask(u16 param)
+{
+ // bitmask from immediate opcode param
+ return 1 << (param & 3);
+}
+
+// External Memory functions */
+/*****************************/
+un8 read_byte_program(un16 rom_address)
+{
+ /* (NumPlay: nothing read past the program the file has) */
+ return rom_address < gw_head.program_size ? gw_program[rom_address] : 0;
+}
+
+un8 readb(un8 ram_address)
+{
+ return gw_ram[ram_address];
+}
+
+void writeb(un8 ram_address,un8 ram_data)
+{
+ gw_ram[ram_address] = ram_data;
+}
+// External IO functions */
+/*************************/
+
+inline un8 m_read_k()
+{
+ return gw_readK(m_s_out);
+}
+
+inline un8 m_read_ba()
+{
+ return gw_readBA();
+}
+
+inline un8 m_read_b()
+{
+ return gw_readB();
+}
+
+inline void m_write_s(un8 data)
+{
+ m_s_out = data;
+}
+inline void m_write_r(un8 data)
+{
+ gw_writeR(data);
+}
+
+//------------------------------------------------
+// Program counter
+//-------------------------------------------------
+inline void increment_pc()
+{
+ // PL(program counter low 6 bits) is a simple LFSR: newbit = (bit0==bit1)
+ // PU,PM(high bits) specify page, PL specifies steps within page
+ int feed = ((m_pc >> 1 ^ m_pc) & 1) ? 0 : 0x20;
+ m_pc = feed | (m_pc >> 1 & 0x1f) | (m_pc & ~0x3f);
+}
diff --git a/games/retrogo/src/gw/sm510core.c b/games/retrogo/src/gw/sm510core.c
new file mode 100644
index 00000000..84eed1f1
--- /dev/null
+++ b/games/retrogo/src/gw/sm510core.c
@@ -0,0 +1,296 @@
+// license:BSD-3-Clause
+// copyright-holders:hap
+// modded by bzhxx
+
+/*
+
+ Sharp SM510 MCU core implementation
+
+*/
+#include "gw_type_defs.h"
+#include "gw_romloader.h"
+#include "gw_system.h"
+#include "sm510.h"
+
+//-------------------------------------------------
+// device_start - device-specific startup
+//-------------------------------------------------
+void sm510_device_start()
+{
+ m_prgwidth = 12;
+ m_datawidth = 7;
+ m_prgmask = (1 << m_prgwidth) - 1;
+ m_datamask = (1 << m_datawidth) - 1;
+
+ // init/zerofill
+ memset(m_stack, 0, sizeof(m_stack));
+ memset(gw_ram, 0, sizeof(gw_ram));
+ memset(gw_ram_state, 0, sizeof(gw_ram_state));
+ m_stack_levels=2;
+ m_pc = 0;
+ m_prev_pc = 0;
+ m_op = 0;
+ m_prev_op = 0;
+ m_param = 0;
+ m_acc = 0;
+ m_bl = 0;
+ m_bm = 0;
+ m_sbl = false;
+ m_sbm = false;
+ m_c = 0;
+ m_skip = false;
+ m_w = 0;
+ m_s_out = 0;
+ m_r = 0;
+ m_r_out = 0;
+ m_div = 0;
+ m_1s = false;
+ m_k_active = false;
+ m_l = 0;
+ m_x = 0;
+ m_y = 0;
+ m_bp = 0;
+ m_bc = false;
+ m_halt = false;
+ m_melody_rd = 0;
+ m_melody_step_count = 0;
+ m_melody_duty_count = 0;
+ m_melody_duty_index = 0;
+ m_melody_address = 0;
+ m_clk_div = 2; // 16kHz
+ m_icount = 0;
+
+ m_r_mask_option = 2;
+
+}
+
+//-------------------------------------------------
+// device_reset - device-specific reset
+//-------------------------------------------------
+void sm510_device_reset()
+{
+ // ACL
+ m_skip = false;
+ m_halt = false;
+ m_sbl = false;
+ m_sbm = false;
+ m_op = m_prev_op = 0;
+ sm510_reset_vector();
+ m_prev_pc = m_pc;
+
+ // lcd is on (Bp on, BC off, bs(y) off)
+ m_bp = 1;
+ m_bc = false;
+ m_y = 0;
+
+ m_r = m_r_out = 0;
+}
+
+//-------------------------------------------------
+// buzzer controller
+//-------------------------------------------------
+static inline void sm510_clock_melody()
+{
+ u8 out = 0;
+
+ if (m_r_mask_option == RMASK_DIRECT)
+ {
+ // direct output
+ out = m_r & 3;
+ }
+ else
+ {
+ // from divider, R2 inverse phase
+ out = m_div >> m_r_mask_option & 1;
+ out |= (out << 1 ^ 2);
+ out &= m_r;
+ }
+
+ m_r_out = out;
+ m_write_r(m_r_out);
+}
+
+void sm510_init_melody(){ }
+
+//-------------------------------------------------
+// wake up routine
+//-------------------------------------------------
+
+inline bool sm510_wake_me_up()
+{
+ // in halt mode, wake up after 1S signal or K input
+ if (m_k_active || m_1s)
+ {
+ // note: official doc warns that Bl/Bm and the stack are undefined
+ // after waking up, but we leave it unchanged
+ m_halt = false;
+ sm510_wakeup_vector();
+
+ return true;
+ }
+ else
+ return false;
+}
+
+/********** 1 second timer *********/
+static inline void sm510_div_timer_cb()
+{
+ m_div = (m_div + 1) & 0x7fff;
+
+ // 1S signal on overflow(falling edge of F1)
+ if (m_div == 0){
+ m_1s = true;
+
+ /* refresh LCD segments state every seconds under sleep mode */
+ if (m_halt) sm510_update_segments_state();
+ }
+
+ sm510_clock_melody();
+}
+
+static inline void sm510_div_timer(int nb_inst)
+{
+ if (nb_inst > 0)
+ for ( int toctoc=0; toctoc < m_clk_div*nb_inst; toctoc++ )
+ sm510_div_timer_cb();
+}
+
+/*************************************/
+
+static inline void sm510_get_opcode_param()
+{
+ // LBL, TL, TML opcodes are 2 bytes
+ if (m_op == 0x5f || (m_op & 0xf0) == 0x70)
+ {
+ m_icount--;
+
+ m_param = read_byte_program(m_pc);
+
+ increment_pc();
+ }
+}
+
+void sm510_execute_one()
+{
+ switch (m_op & 0xf0)
+ {
+ case 0x20: sm510_op_lax(); break;
+ case 0x30: sm510_op_adx(); break;
+ case 0x40: sm510_op_lb(); break;
+
+ case 0x80: case 0x90: case 0xa0: case 0xb0:
+ sm510_op_t(); break;
+ case 0xc0: case 0xd0: case 0xe0: case 0xf0:
+ sm510_op_tm(); break;
+
+ default:
+ switch (m_op & 0xfc)
+ {
+ case 0x04: sm510_op_rm(); break;
+ case 0x0c: sm510_op_sm(); break;
+ case 0x10: sm510_op_exc(); break;
+ case 0x14: sm510_op_exci(); break;
+ case 0x18: sm510_op_lda(); break;
+ case 0x1c: sm510_op_excd(); break;
+ case 0x54: sm510_op_tmi(); break;
+ case 0x70: case 0x74: case 0x78: sm510_op_tl(); break;
+ case 0x7c: sm510_op_tml(); break;
+
+ default:
+ switch (m_op)
+ {
+ case 0x00: sm510_op_skip(); break;
+ case 0x01: sm510_op_atbp(); break;
+ case 0x02: sm510_op_sbm(); break;
+ case 0x03: sm510_op_atpl(); break;
+ case 0x08: sm510_op_add(); break;
+ case 0x09: sm510_op_add11(); break;
+ case 0x0a: sm510_op_coma(); break;
+ case 0x0b: sm510_op_exbla(); break;
+
+ case 0x51: sm510_op_tb(); break;
+ case 0x52: sm510_op_tc(); break;
+ case 0x53: sm510_op_tam(); break;
+ case 0x58: sm510_op_tis(); break;
+ case 0x59: sm510_op_atl(); break;
+ case 0x5a: sm510_op_ta0(); break;
+ case 0x5b: sm510_op_tabl(); break;
+ case 0x5d: sm510_op_cend(); break;
+ case 0x5e: sm510_op_tal(); break;
+ case 0x5f: sm510_op_lbl(); break;
+
+ case 0x60: sm510_op_atfc(); break;
+ case 0x61: sm510_op_atr(); break;
+ case 0x62: sm510_op_wr(); break;
+ case 0x63: sm510_op_ws(); break;
+ case 0x64: sm510_op_incb(); break;
+ case 0x65: sm510_op_idiv(); break;
+ case 0x66: sm510_op_rc(); break;
+ case 0x67: sm510_op_sc(); break;
+ case 0x68: sm510_op_tf1(); break;
+ case 0x69: sm510_op_tf4(); break;
+ case 0x6a: sm510_op_kta(); break;
+ case 0x6b: sm510_op_rot(); break;
+ case 0x6c: sm510_op_decb(); break;
+ case 0x6d: sm510_op_bdc(); break;
+ case 0x6e: sm510_op_rtn0(); break;
+ case 0x6f: sm510_op_rtn1(); break;
+
+ default: sm510_op_illegal(); break;
+ }
+ break; // 0xff
+
+ }
+ break; // 0xfc
+
+ } // big switch
+
+ // BM high bit is only valid for 1 step
+ m_sbm = (m_op == 0x02);
+}
+
+//-------------------------------------------------
+// execute
+//-------------------------------------------------
+void sm510_execute_run()
+{
+ int reamining_icount = m_icount;
+
+ while (m_icount > 0)
+ {
+ m_icount--;
+
+ if (m_halt && !sm510_wake_me_up())
+ {
+ sm510_div_timer(reamining_icount);
+
+ // got nothing to do
+ m_icount = 0;
+ return;
+ }
+
+ // remember previous state
+ m_prev_op = m_op;
+ m_prev_pc = m_pc;
+
+ // fetch next opcode
+ m_op = read_byte_program(m_pc);
+
+ increment_pc();
+ sm510_get_opcode_param();
+
+ // handle opcode if it's not skipped
+ if (m_skip)
+ {
+ m_skip = false;
+ m_op = 0; // fake nop
+ }
+ else
+ sm510_execute_one();
+
+ // clock: spent time
+ sm510_div_timer(reamining_icount-m_icount);
+
+ reamining_icount=m_icount;
+ }
+}
diff --git a/games/retrogo/src/gw/sm510op.c b/games/retrogo/src/gw/sm510op.c
new file mode 100644
index 00000000..1e56f04a
--- /dev/null
+++ b/games/retrogo/src/gw/sm510op.c
@@ -0,0 +1,461 @@
+// license:BSD-3-Clause
+// copyright-holders:hap
+// modded by bzhxx
+
+// SM510 shared opcode handlers
+
+#include "gw_type_defs.h"
+#include "sm510.h"
+#include <assert.h>
+
+// internal helpers
+
+//-------------------------------------------------
+// Vector table reset & wakeup
+//-------------------------------------------------
+
+void sm510_reset_vector() { do_branch(3, 7, 0); }
+void sm510_wakeup_vector() { do_branch(1, 0, 0); } // after halt
+
+
+
+/* to prevent from glich on display
+ [Alternative to MAME, // 1kHz display decay]
+ we mirror the output mo mox when the segments are
+ considered stable.
+ Typically, when the input are polled by
+ the functions : aplha,beta,K1..K4
+ TA:sm500_op_tal()
+ TB:sm500_op_tb()
+ KTA:sm500_op_kta()
+ optionally return function:rtn()
+ depending on flag_force_refresh_display from ROM flags
+*/
+
+void sm510_update_segments_state()
+{
+ // Mirror the RAM memory as segments states
+ for (int address = 0; address < 128; address++)
+ gw_ram_state[address] = gw_ram[address];
+};
+
+// instruction set
+
+// RAM address instructions
+
+void sm510_op_lb()
+{
+ // LB x: load BM/BL with 4-bit immediate value (partial)
+ m_bm = (m_bm & 4) | (m_op & 3);
+ m_bl = (m_op >> 2 & 3) | ((m_op & 0xc) ? 0xc : 0);
+}
+
+void sm510_op_lbl()
+{
+ // LBL xy: load BM/BL with 8-bit immediate value
+ m_bl = m_param & 0xf;
+ m_bm = (m_param & m_datamask) >> 4;
+}
+
+void sm510_op_sbl()
+{
+ // SBL: set BL high bit for next opcode - handled in execute_one()
+}
+
+void sm510_op_sbm()
+{
+ // SBM: set BM high bit for next opcode - handled in execute_one()
+}
+
+void sm510_op_exbla()
+{
+ // EXBLA: exchange BL with ACC
+ u8 a = m_acc;
+ m_acc = m_bl;
+ m_bl = a;
+}
+
+void sm510_op_incb()
+{
+ // INCB: increment BL, skip next on overflow
+ m_bl = (m_bl + 1) & 0xf;
+ m_skip = (m_bl == 0);
+}
+
+void sm510_op_decb()
+{
+ // DECB: decrement BL, skip next on overflow
+ m_bl = (m_bl - 1) & 0xf;
+ m_skip = (m_bl == 0xf);
+}
+
+// ROM address instructions
+
+void sm510_op_atpl()
+{
+ // ATPL: load Pl(PC low bits) with ACC
+ m_pc = (m_prev_pc & ~0xf) | m_acc;
+}
+
+void sm510_op_rtn0()
+{
+ if (flag_lcd_deflicker_level < 2)
+ sm510_update_segments_state();
+
+ // RTN0: return from subroutine
+ pop_stack();
+}
+
+void sm510_op_rtn1()
+{
+ // RTN1: return from subroutine, skip next
+ sm510_op_rtn0();
+ m_skip = true;
+}
+
+void sm510_op_t()
+{
+ // T xy: jump(transfer) within current page
+ m_pc = (m_pc & ~0x3f) | (m_op & 0x3f);
+}
+
+void sm510_op_tl()
+{
+ // TL xyz: long jump
+ do_branch(m_param >> 6 & 3, m_op & 0xf, m_param & 0x3f);
+}
+
+void sm510_op_tml()
+{
+
+ // TML xyz: long call
+ push_stack();
+ do_branch(m_param >> 6 & 3, m_op & 3, m_param & 0x3f);
+}
+
+void sm510_op_tm()
+{
+
+ // TM x: indirect subroutine call, pointers(IDX) are on page 0
+ m_icount--;
+
+ push_stack();
+ u8 idx = read_byte_program(m_op & 0x3f);
+ do_branch(idx >> 6 & 3, 4, idx & 0x3f);
+}
+
+// Data transfer instructions
+
+void sm510_op_exc()
+{
+ // EXC x: exchange ACC with RAM, xor BM with x
+ u8 a = m_acc;
+ m_acc = ram_r();
+ ram_w(a);
+ m_bm ^= (m_op & 3);
+}
+
+void sm510_op_bdc()
+{
+ // BDC: enable LCD bleeder current with C
+ m_bc = (m_c != 0);
+}
+
+void sm510_op_exci()
+{
+ // EXCI x: EXC x, INCB
+ sm510_op_exc();
+ sm510_op_incb();
+}
+
+void sm510_op_excd()
+{
+ // EXCD x: EXC x, DECB
+ sm510_op_exc();
+ sm510_op_decb();
+}
+
+void sm510_op_lda()
+{
+ // LDA x: load ACC with RAM, xor BM with x
+ m_acc = ram_r();
+ m_bm ^= (m_op & 3);
+}
+
+void sm510_op_lax()
+{
+ // LAX x: load ACC with immediate value, skip any next LAX
+ if ((m_op & ~0xf) != (m_prev_op & ~0xf))
+ m_acc = m_op & 0xf;
+}
+
+void sm510_op_ptw()
+{
+ // PTW: output W latch
+ m_write_s(m_w);
+}
+
+void sm510_op_wr()
+{
+ // WR: shift 0 into W
+ m_w = m_w << 1 | 0;
+ update_w_latch();
+}
+
+void sm510_op_ws()
+{
+ // WS: shift 1 into W
+ m_w = m_w << 1 | 1;
+ update_w_latch();
+}
+
+// I/O instructions
+
+void sm510_op_kta()
+{
+
+ sm510_update_segments_state();
+
+ // KTA: input K to ACC
+ m_acc = m_read_k() & 0xf;
+}
+
+void sm510_op_atbp()
+{
+ // ATBP: output ACC to BP(internal LCD backplate signal)
+ m_bp = m_acc & 1;
+}
+
+void sm510_op_atx()
+{
+ // ATX: output ACC to X
+ m_x = m_acc;
+}
+
+void sm510_op_atl()
+{
+ // ATL: output ACC to L
+ m_l = m_acc;
+}
+
+void sm510_op_atfc()
+{
+ // ATFC: output ACC to Y
+ m_y = m_acc;
+}
+
+void sm510_op_atr()
+{
+ // ATR: output ACC to R
+ m_r = m_acc;
+ //sm510_clock_melody();
+}
+
+// Arithmetic instructions
+
+void sm510_op_add()
+{
+ // ADD: add RAM to ACC
+ m_acc = (m_acc + ram_r()) & 0xf;
+}
+
+void sm510_op_add11()
+{
+ // ADD11: add RAM and carry to ACC and carry, skip next on carry
+ m_acc += ram_r() + m_c;
+ m_c = m_acc >> 4 & 1;
+ m_skip = (m_c == 1);
+ m_acc &= 0xf;
+}
+
+void sm510_op_adx()
+{
+ // ADX x: add immediate value to ACC, skip next on carry except if x = 10
+ m_acc += (m_op & 0xf);
+ m_skip = ((m_op & 0xf) != 10 && (m_acc & 0x10) != 0);
+ m_acc &= 0xf;
+}
+
+void sm510_op_coma()
+{
+ // COMA: complement ACC
+ m_acc ^= 0xf;
+}
+
+void sm510_op_rot()
+{
+ // ROT: rotate ACC right through carry
+ u8 c = m_acc & 1;
+ m_acc = m_acc >> 1 | m_c << 3;
+ m_c = c;
+}
+
+void sm510_op_rc()
+{
+ // RC: reset carry
+ m_c = 0;
+}
+
+void sm510_op_sc()
+{
+ // SC: set carry
+ m_c = 1;
+}
+
+// Test instructions
+
+void sm510_op_tb()
+{
+ sm510_update_segments_state();
+
+ // TB: skip next if B(beta) pin is set
+ m_skip = (m_read_b() != 0);
+}
+
+void sm510_op_tc()
+{
+ // TC: skip next if no carry
+ m_skip = !m_c;
+}
+
+void sm510_op_tam()
+{
+ // TAM: skip next if ACC equals RAM
+ m_skip = (m_acc == ram_r());
+}
+
+void sm510_op_tmi()
+{
+ // TMI x: skip next if RAM bit is set
+ m_skip = ((ram_r() & bitmask(m_op)) != 0);
+}
+
+void sm510_op_ta0()
+{
+ // TA0: skip next if ACC is clear
+ m_skip = !m_acc;
+}
+
+void sm510_op_tabl()
+{
+ // TABL: skip next if ACC equals BL
+ m_skip = (m_acc == m_bl);
+}
+
+void sm510_op_tis()
+{
+ // TIS: skip next if 1S(gamma flag) is clear, reset it after
+ m_skip = !m_1s;
+ m_1s = false;
+}
+
+void sm510_op_tal()
+{
+ sm510_update_segments_state();
+
+ // TAL: skip next if BA pin is set
+ m_skip = (m_read_ba() != 0);
+}
+
+void sm510_op_tf1()
+{
+ // TF1: skip next if divider F1(d14) is set
+ m_skip = ((m_div & 0x4000) != 0);
+}
+
+void sm510_op_tf4()
+{
+ // TF4: skip next if divider F4(d11) is set
+ m_skip = ((m_div & 0x0800) != 0);
+}
+
+// Bit manipulation instructions
+
+void sm510_op_rm()
+{
+ // RM x: reset RAM bit
+ ram_w(ram_r() & ~bitmask(m_op));
+}
+
+void sm510_op_sm()
+{
+ // SM x: set RAM bit
+ ram_w(ram_r() | bitmask(m_op));
+}
+
+// Melody control instructions
+
+void sm510_op_pre()
+{
+ // PRE x: melody ROM pointer preset
+ m_melody_address = m_param;
+ m_melody_step_count = 0;
+}
+
+void sm510_op_sme()
+{
+
+ // SME: set melody enable
+ m_melody_rd |= 1;
+}
+
+void sm510_op_rme()
+{
+ // RME: reset melody enable
+ m_melody_rd &= ~1;
+}
+
+void sm510_op_tmel()
+{
+ // TMEL: skip next if melody stop flag is set, reset it
+ m_skip = ((m_melody_rd & 2) != 0);
+ m_melody_rd &= ~2;
+}
+
+// Special instructions
+
+void sm510_op_skip()
+{
+ // SKIP: no operation
+}
+
+void sm510_op_cend()
+{
+ // CEND: stop clock (halt the cpu and go into low-power mode)
+ m_halt = true;
+}
+
+void sm510_op_idiv()
+{
+ // IDIV: reset divider
+ m_div = 0;
+}
+
+void sm510_op_dr()
+{
+ // DR: reset divider low 8 bits
+ m_div &= 0x7f;
+}
+
+void sm510_op_dta()
+{
+ // DTA: transfer divider low 4 bits to ACC
+ m_acc = m_div >> 11 & 0xf;
+}
+
+void sm510_op_clklo()
+{
+ // CLKLO*: select 8kHz instruction clock (*unknown mnemonic)
+ m_clk_div = 4;
+}
+
+void sm510_op_clkhi()
+{
+ // CLKHI*: select 16kHz instruction clock (*unknown mnemonic)
+ m_clk_div = 2;
+}
+
+void sm510_op_illegal()
+{
+ /* (NumPlay: an unknown opcode does nothing, as on the chip, instead of stopping) */
+}
diff --git a/games/retrogo/src/gw/sm511core.c b/games/retrogo/src/gw/sm511core.c
new file mode 100644
index 00000000..d1494068
--- /dev/null
+++ b/games/retrogo/src/gw/sm511core.c
@@ -0,0 +1,286 @@
+// license:BSD-3-Clause
+// copyright-holders:hap
+// modded by bzhxx
+
+/*
+
+ Sharp SM511 MCU core implementation
+
+ TODO:
+ - verify undocumented/guessed opcodes:
+ * $01 is guessed as DIV to ACC transfer, unknown which bits
+ * $5d is certainly CEND
+ * $65 is certainly divider reset, but not sure if it behaves same as on SM510
+ * $6036 and $6037 may be instruction timing? (16kHz and 8kHz), mnemonics unknown
+
+*/
+#include <assert.h>
+
+#include "gw_type_defs.h"
+#include "sm510.h"
+
+un8 *melody_rom;
+
+//-------------------------------------------------
+// melody controller
+//-------------------------------------------------
+static inline void sm511_clock_melody()
+{
+ if (!melody_rom)
+ return;
+
+ // tone cycle table (SM511/SM512 datasheet fig.5)
+ // cmd 0 = rest, 1 = stop, > 13 = illegal(inactive?)
+ static const u8 lut_tone_cycles[4*16] =
+ {
+ 0, 0, 7, 8, 8, 9, 9, 10,11,11,12,13,14,14, 0, 0,
+ 0, 0, 8, 8, 9, 9, 10,11,11,12,13,13,14,15, 0, 0,
+ 0, 0, 8, 8, 9, 9, 10,10,11,12,12,13,14,15, 0, 0,
+ 0, 0, 8, 9, 9, 10,10,11,11,12,13,14,14,15, 0, 0,
+ };
+
+ u8 cmd = melody_rom[m_melody_address] & 0x3f;
+ u8 out = 0;
+
+ // clock duty cycle if tone is active
+ if ((cmd & 0xf) >= 2 && (cmd & 0xf) <= 13)
+ {
+ out = m_melody_duty_index & m_melody_rd & 1;
+ m_melody_duty_count++;
+ int index = m_melody_duty_index << 4 | (cmd & 0xf);
+ int shift = ~cmd >> 4 & 1; // OCT
+
+ if (m_melody_duty_count >= (lut_tone_cycles[index] << shift))
+ {
+ m_melody_duty_count = 0;
+ m_melody_duty_index = (m_melody_duty_index + 1) & 3;
+ }
+ }
+ else if ((cmd & 0xf) == 1)
+ {
+ // set melody stop flag
+ m_melody_rd |= 2;
+ }
+
+ // clock time base on F8(d7)
+ if ((m_div & 0x7f) == 0)
+ {
+ u8 mask = (cmd & 0x20) ? 0x1f : 0x0f;
+ m_melody_step_count = (m_melody_step_count + 1) & mask;
+
+ if (m_melody_step_count == 0)
+ m_melody_address++;
+ }
+
+ m_r_out = out;
+ m_write_r(m_r_out);
+}
+
+bool sm511_init_melody(un8 *gw_melody)
+{
+ if (!gw_melody)
+ return false;
+
+ melody_rom = gw_melody;
+
+ // verify melody rom
+ for (int i = 0; i < 0x100; i++)
+ {
+ u8 data = melody_rom[i];
+ if (data & 0xc0 || (data & 0x0f) > 13)
+ return false;
+ }
+ return true;
+}
+//-------------------------------------------------
+// device_reset - device-specific reset
+//-------------------------------------------------
+void sm511_device_reset()
+{
+ sm510_device_reset();
+
+ m_melody_rd &= ~1;
+ m_clk_div = 4; // 8kHz
+}
+
+/********** 1 second timer *********/
+static inline void sm511_div_timer_cb()
+{
+ m_div = (m_div + 1) & 0x7fff;
+
+ // 1S signal on overflow(falling edge of F1)
+ if (m_div == 0){
+
+ m_1s = true;
+
+ /* refresh LCD segments state every seconds under sleep mode */
+ if (m_halt) sm510_update_segments_state();
+
+ }
+
+
+ sm511_clock_melody();
+}
+
+/********** 1 second timer *********/
+static inline void sm511_div_timer(int nb_inst)
+{
+ if (nb_inst > 0)
+ for (int toctoc=0; toctoc < m_clk_div*nb_inst; toctoc++ )
+ sm511_div_timer_cb();
+}
+
+
+void sm511_execute_one()
+{
+ switch (m_op & 0xf0)
+ {
+ case 0x20: sm510_op_lax(); break;
+ case 0x30: sm510_op_adx(); break;
+ case 0x40: sm510_op_lb(); break;
+ case 0x70: sm510_op_tl(); break;
+
+ case 0x80: case 0x90: case 0xa0: case 0xb0:
+ sm510_op_t(); break;
+ case 0xc0: case 0xd0: case 0xe0: case 0xf0:
+ sm510_op_tm(); break;
+
+ default:
+ switch (m_op & 0xfc)
+ {
+ case 0x04: sm510_op_rm(); break;
+ case 0x0c: sm510_op_sm(); break;
+ case 0x10: sm510_op_exc(); break;
+ case 0x14: sm510_op_exci(); break;
+ case 0x18: sm510_op_lda(); break;
+ case 0x1c: sm510_op_excd(); break;
+ case 0x54: sm510_op_tmi(); break;
+ case 0x68: sm510_op_tml(); break;
+
+ default:
+ switch (m_op)
+ {
+ case 0x00: sm510_op_rot(); break;
+ case 0x01: sm510_op_dta(); break;
+ case 0x02: sm510_op_sbm(); break;
+ case 0x03: sm510_op_atpl(); break;
+ case 0x08: sm510_op_add(); break;
+ case 0x09: sm510_op_add11(); break;
+ case 0x0a: sm510_op_coma(); break;
+ case 0x0b: sm510_op_exbla(); break;
+
+ case 0x50: sm510_op_kta(); break;
+ case 0x51: sm510_op_tb(); break;
+ case 0x52: sm510_op_tc(); break;
+ case 0x53: sm510_op_tam(); break;
+ case 0x58: sm510_op_tis(); break;
+ case 0x59: sm510_op_atl(); break;
+ case 0x5a: sm510_op_ta0(); break;
+ case 0x5b: sm510_op_tabl(); break;
+ case 0x5c: sm510_op_atx(); break;
+ case 0x5d: sm510_op_cend(); break;
+ case 0x5e: sm510_op_tal(); break;
+ case 0x5f: sm510_op_lbl(); break;
+
+ case 0x61: sm510_op_pre(); break;
+ case 0x62: sm510_op_wr(); break;
+ case 0x63: sm510_op_ws(); break;
+ case 0x64: sm510_op_incb(); break;
+ case 0x65: sm510_op_dr(); break;
+ case 0x66: sm510_op_rc(); break;
+ case 0x67: sm510_op_sc(); break;
+ case 0x6c: sm510_op_decb(); break;
+ case 0x6d: sm510_op_ptw(); break;
+ case 0x6e: sm510_op_rtn0(); break;
+ case 0x6f: sm510_op_rtn1(); break;
+
+ // extended opcodes
+ case 0x60:
+ m_op = m_op << 8 | m_param;
+ switch (m_param)
+ {
+ case 0x30: sm510_op_rme(); break;
+ case 0x31: sm510_op_sme(); break;
+ case 0x32: sm510_op_tmel(); break;
+ case 0x33: sm510_op_atfc(); break;
+ case 0x34: sm510_op_bdc(); break;
+ case 0x35: sm510_op_atbp(); break;
+ case 0x36: sm510_op_clkhi(); break;
+ case 0x37: sm510_op_clklo(); break;
+
+ default: sm510_op_illegal(); break;
+ }
+ break; // 0x60
+
+ default: sm510_op_illegal(); break;
+ }
+ break; // 0xff
+
+ }
+ break; // 0xfc
+
+ } // big switch
+
+ // BM high bit is only valid for 1 step
+ m_sbm = (m_op == 0x02);
+}
+
+static inline void sm511_get_opcode_param()
+{
+ // LBL, PRE, TL, TML and prefix opcodes are 2 bytes
+ if ((m_op >= 0x5f && m_op <= 0x61) || (m_op & 0xf0) == 0x70 || (m_op & 0xfc) == 0x68)
+ {
+ m_icount--;
+
+ m_param = read_byte_program(m_pc);
+
+ increment_pc();
+ }
+}
+
+//-------------------------------------------------
+// execute
+//-------------------------------------------------
+void sm511_execute_run()
+{
+ int reamining_icount = m_icount;
+
+ while (m_icount > 0)
+ {
+ m_icount--;
+
+ if (m_halt && !sm510_wake_me_up())
+ {
+ sm511_div_timer(reamining_icount);
+
+ // got nothing to do
+ m_icount = 0;
+ return;
+ }
+
+ // remember previous state
+ m_prev_op = m_op;
+ m_prev_pc = m_pc;
+
+ // fetch next opcode
+ m_op = read_byte_program(m_pc);
+
+ increment_pc();
+ sm511_get_opcode_param();
+
+ // handle opcode if it's not skipped
+ if (m_skip)
+ {
+ m_skip = false;
+ m_op = 0; // fake nop
+ }
+ else
+ sm511_execute_one();
+
+ // clock: spent time
+ sm511_div_timer(reamining_icount-m_icount);
+
+ reamining_icount=m_icount;
+
+ }
+}
diff --git a/games/retrogo/src/gw/sm5acore.c b/games/retrogo/src/gw/sm5acore.c
new file mode 100644
index 00000000..8b68560a
--- /dev/null
+++ b/games/retrogo/src/gw/sm5acore.c
@@ -0,0 +1,314 @@
+// license:BSD-3-Clause
+// copyright-holders:hap, Igor
+// modded bzhxx
+/*
+
+ Sharp SM5A MCU core implementation
+
+*/
+
+#include "gw_type_defs.h"
+#include "sm510.h"
+#include "sm500.h"
+
+void sm5a_device_start()
+{
+ // common init (not everything is used though)
+ sm510_device_start();
+
+ // init/zerofill
+ memset(m_ox, 0, sizeof(m_ox));
+ memset(m_o, 0, sizeof(m_o));
+
+ memset(m_ox_state, 0, sizeof(m_ox_state));
+ memset(m_o_state, 0, sizeof(m_o_state));
+
+ /* stack levels */
+ m_stack_levels = 1;
+
+ /* o group pins */
+ m_o_pins = 9;
+
+ /* prg width */
+ m_prgwidth = 11;
+
+ /*data width */
+ m_datawidth = 7;
+
+ m_prgmask = (1 << m_prgwidth) - 1;
+ m_datamask = (1 << m_datawidth) - 1;
+
+ trs_field = 1;
+
+ m_cn = 0;
+ m_mx = 0;
+ m_cb = 0;
+ m_s = 0;
+ m_rsub = false;
+
+ m_r_mask_option = RMASK_DIRECT;
+}
+
+//-------------------------------------------------
+// device_reset - device-specific reset
+//-------------------------------------------------
+
+void sm5a_device_reset()
+{
+ // common reset
+ sm510_device_reset();
+
+ // SM500 specific
+ sm500_reset_vector();
+ m_prev_pc = m_pc;
+ push_stack();
+ sm500_op_idiv();
+ m_1s = true;
+ m_cb = 0;
+ m_rsub = false;
+ m_r = 0xff;
+ m_r_out = 0;
+}
+
+void sm5a_execute_one()
+{
+
+ switch (m_op & 0xf0)
+ {
+ case 0x20:
+ sm500_op_lax();
+ break;
+ case 0x30:
+ sm500_op_adx();
+ break;
+ case 0x40:
+ sm500_op_lb();
+ break;
+ case 0x70:
+ sm500_op_ssr();
+ break;
+
+ case 0x80:
+ case 0x90:
+ case 0xa0:
+ case 0xb0:
+ sm500_op_tr();
+ break;
+ case 0xc0:
+ case 0xd0:
+ case 0xe0:
+ case 0xf0:
+ sm500_op_trs();
+ break;
+
+ default:
+ switch (m_op & 0xfc)
+ {
+ case 0x04:
+ sm500_op_rm();
+ break;
+ case 0x0c:
+ sm500_op_sm();
+ break;
+ case 0x10:
+ sm500_op_exc();
+ break;
+ case 0x14:
+ sm500_op_exci();
+ break;
+ case 0x18:
+ sm500_op_lda();
+ break;
+ case 0x1c:
+ sm500_op_excd();
+ break;
+ case 0x54:
+ sm500_op_tmi();
+ break;
+
+ default:
+ switch (m_op)
+ {
+ case 0x00:
+ sm500_op_skip();
+ break;
+ case 0x01:
+ sm500_op_atr();
+ break;
+ case 0x02:
+ sm500_op_sbm();
+ break;
+ case 0x03:
+ sm500_op_atbp();
+ break;
+ case 0x08:
+ sm500_op_add();
+ break;
+ case 0x09:
+ sm500_op_add11();
+ break;
+ case 0x0a:
+ sm500_op_coma();
+ break;
+ case 0x0b:
+ sm500_op_exbla();
+ break;
+
+ case 0x50:
+ sm500_op_tal();
+ break;
+ case 0x51:
+ sm500_op_tb();
+ break;
+ case 0x52:
+ sm500_op_tc();
+ break;
+ case 0x53:
+ sm500_op_tam();
+ break;
+ case 0x58:
+ sm500_op_tis();
+ break;
+ case 0x59:
+ sm500_op_ptw();
+ break;
+ case 0x5a:
+ sm500_op_ta0();
+ break;
+ case 0x5b:
+ sm500_op_tabl();
+ break;
+ case 0x5c:
+ sm500_op_tw();
+ break;
+ case 0x5d:
+ sm500_op_dtw();
+ break;
+ case 0x5f:
+ sm500_op_lbl();
+ break;
+
+ case 0x60:
+ sm500_op_comcn();
+ break;
+ case 0x61:
+ sm500_op_pdtw();
+ break;
+ case 0x62:
+ sm500_op_wr();
+ break;
+ case 0x63:
+ sm500_op_ws();
+ break;
+ case 0x64:
+ sm500_op_incb();
+ break;
+ case 0x65:
+ sm500_op_idiv();
+ break;
+ case 0x66:
+ sm500_op_rc();
+ break;
+ case 0x67:
+ sm500_op_sc();
+ break;
+ case 0x68:
+ sm500_op_rmf();
+ break;
+ case 0x69:
+ sm500_op_smf();
+ break;
+ case 0x6a:
+ sm500_op_kta();
+ break;
+ case 0x6b:
+ sm500_op_rbm();
+ break;
+ case 0x6c:
+ sm500_op_decb();
+ break;
+ case 0x6d:
+ sm500_op_comcb();
+ break;
+ case 0x6e:
+ sm500_op_rtn0();
+ break;
+ case 0x6f:
+ sm500_op_rtn1();
+ break;
+
+ // extended opcodes
+ case 0x5e:
+ m_op = m_op << 8 | m_param;
+ switch (m_param)
+ {
+ case 0x00:
+ sm500_op_cend();
+ break;
+ case 0x04:
+ sm500_op_dta();
+ break;
+
+ default:
+ sm500_op_illegal();
+ break;
+ }
+ break; // 0x5e
+
+ default:
+ sm500_op_illegal();
+ break;
+ }
+ break; // 0xff
+ }
+ break; // 0xfc
+
+ } // big switch
+}
+
+//-------------------------------------------------
+// execute
+//-------------------------------------------------
+void sm5a_execute_run()
+{
+ int reamining_icount = m_icount;
+
+ while (m_icount > 0)
+ {
+ m_icount--;
+
+ if (m_halt && !sm500_wake_me_up())
+ {
+
+ sm500_div_timer(reamining_icount);
+
+ // got nothing to do
+ m_icount = 0;
+ return;
+ }
+
+ // remember previous state
+ m_prev_op = m_op;
+ m_prev_pc = m_pc;
+
+ // fetch next opcode
+ m_op = read_byte_program(m_pc);
+
+ increment_pc();
+ sm500_get_opcode_param();
+
+ // handle opcode if it's not skipped
+ if (m_skip)
+ {
+ m_skip = false;
+ m_op = 0; // fake nop
+ }
+ else
+ sm5a_execute_one();
+
+ // clock: spent time
+ sm500_div_timer(reamining_icount - m_icount);
+
+ reamining_icount = m_icount;
+ }
+}
diff --git a/games/retrogo/src/main.c b/games/retrogo/src/main.c
index 2994579c..b38d86d6 100644
--- a/games/retrogo/src/main.c
+++ b/games/retrogo/src/main.c
@@ -24,6 +24,7 @@
#include "gb/gb.h"
#include "nes/nes_core.h"
#include "sms/sms.h"
+#include "gw/gw.h"
#if NP_MODULE /* (np_file_read, np_file_write, np_storage_delete: NumPlay's, launcher/src/np.h) */
#define np_app_begin()
@@ -98,10 +99,15 @@ static struct {
uint8_t tab, browse;
uint8_t cursor[8]; /* each system's game chosen (room for the systems to come) */
uint8_t keys[8]; /* the calculator's key for each of the pad's buttons, in pad_bits' order */
+ uint8_t cursor_more[4]; /* (version 3) the game chosen of the systems from 8: Game & Watch, Mega Drive */
+ uint8_t md_z80; /* (version 3) the Mega Drive's Z80 run (Retro-Go's "Z80 emulation") */
+ uint8_t spare[3];
} cfg;
#define CFG_NAME "retrogo.cfg"
#define CFG_V1_SIZE 19 /* (version 1: the same up to the five systems' games, without the keys) */
-_Static_assert(RG_SYS_COUNT <= 8, "cfg.cursor");
+#define CFG_V2_SIZE 35 /* (version 2: up to the keys) */
+_Static_assert(RG_SYS_COUNT <= 12, "cfg.cursor_more");
+static uint8_t *cursor_of(int sys) { return sys < 8 ? &cfg.cursor[sys] : &cfg.cursor_more[sys - 8]; }
/* ------------------------------------------------------------ the keys */
/* the pad's buttons: the D-pad, then A, B, Select and Start */
@@ -135,27 +141,30 @@ static bool keys_ok(const uint8_t *k) {
static void cfg_defaults(void) {
memset(&cfg, 0, sizeof cfg);
- cfg.magic = 'R', cfg.version = 2;
+ cfg.magic = 'R', cfg.version = 3;
cfg.scaling = SCALE_FIT, cfg.speed = 1;
cfg.gb_palette = GB_PAL_DMG, cfg.nes_palette = NES_PAL_NTSC;
cfg.overscan = 1, cfg.crop_sides = 0, cfg.sprite_limit = 1, cfg.autosave = 10;
memcpy(cfg.keys, default_keys, sizeof cfg.keys);
+ cfg.md_z80 = 1;
}
static void cfg_load(void) {
uint32_t len = 0;
const uint8_t *d = np_file_read(CFG_NAME, &len);
cfg_defaults();
- if (!d || d[0] != 'R' || (!(len == sizeof cfg && d[1] == 2) && !(len == CFG_V1_SIZE && d[1] == 1))) return;
+ if (!d || d[0] != 'R' ||
+ (!(len == sizeof cfg && d[1] == 3) && !(len == CFG_V2_SIZE && d[1] == 2) && !(len == CFG_V1_SIZE && d[1] == 1)))
+ return;
memcpy(&cfg, d, len);
- cfg.version = 2;
+ cfg.version = 3;
if (!keys_ok(cfg.keys)) memcpy(cfg.keys, default_keys, sizeof cfg.keys);
/* whatever it holds, settings Retro-Go has */
if (cfg.scaling >= SCALE_COUNT) cfg.scaling = SCALE_FIT;
if (cfg.speed > 4) cfg.speed = 1;
if (cfg.gb_palette >= GB_PAL_COUNT) cfg.gb_palette = 0;
if (cfg.nes_palette >= NES_PAL_COUNT) cfg.nes_palette = 0;
- cfg.overscan &= 1, cfg.sprite_limit &= 1, cfg.browse &= 1;
+ cfg.overscan &= 1, cfg.sprite_limit &= 1, cfg.browse &= 1, cfg.md_z80 &= 1;
if (cfg.crop_sides > 2) cfg.crop_sides = 0;
if (cfg.autosave > 99) cfg.autosave = 10;
}
@@ -166,13 +175,14 @@ static void cfg_save(void) { np_file_write(CFG_NAME, &cfg, sizeof cfg); }
static rg_rom_t roms[RG_MAX_ROMS];
static int nroms;
/* Retro-Go's tabs, in its order */
-static const uint8_t tab_order[] = {RG_SYS_NES, RG_SYS_GB, RG_SYS_GBC, RG_SYS_SMS, RG_SYS_GG, RG_SYS_SG, RG_SYS_CV};
+static const uint8_t tab_order[] = {RG_SYS_NES, RG_SYS_GB, RG_SYS_GBC, RG_SYS_SMS, RG_SYS_GG, RG_SYS_SG, RG_SYS_CV, RG_SYS_GW, RG_SYS_MD};
static uint8_t tabs[sizeof tab_order], ntabs;
-static const char *const sys_short[RG_SYS_COUNT] = {"", "GB", "GBC", "NES", "SMS", "GG", "SG", "COL"};
+static const char *const sys_short[RG_SYS_COUNT] = {"", "GB", "GBC", "NES", "SMS", "GG", "SG", "COL", "GW", "MD"};
/* the tab's banner: the maker, then the system, as Retro-Go's banners show them */
-static const char *const sys_maker[RG_SYS_COUNT] = {"", "Nintendo", "Nintendo", "Nintendo", "SEGA", "SEGA", "SEGA", "Coleco"};
+static const char *const sys_maker[RG_SYS_COUNT] = {"", "Nintendo", "Nintendo", "Nintendo", "SEGA", "SEGA", "SEGA", "Coleco", "Nintendo", "SEGA"};
static const char *const sys_model[RG_SYS_COUNT] = {"Retro-Go", "Game Boy", "Game Boy Color", "Entertainment System",
- "Master System", "Game Gear", "SG-1000", "ColecoVision"};
+ "Master System", "Game Gear", "SG-1000", "ColecoVision",
+ "Game & Watch", "Mega Drive"};
static bool is_sega(int sys) { return sys == RG_SYS_SMS || sys == RG_SYS_GG || sys == RG_SYS_SG; }
static bool is_z80(int sys) { return is_sega(sys) || sys == RG_SYS_CV; } /* (the Master System's machine runs them) */
@@ -264,7 +274,7 @@ static struct {
int src_x, src_y, src_w, src_h; /* the part of the core's picture shown */
int x, y, w, h; /* where, on the screen */
} view;
-static uint8_t xmap[SCREEN_W]; /* screen column -> picture column */
+static uint16_t xmap[SCREEN_W]; /* screen column -> picture column */
static uint8_t row_first[241]; /* picture row -> its first screen row */
static uint32_t line_sum[240]; /* each picture row as it was last pushed (Retro-Go's partial updates) */
static bool redraw_all;
@@ -308,6 +318,7 @@ void rg_line(int y, const uint16_t *px) {
/* the picture's place for the game running (Retro-Go's update_viewport_scaling) */
static int sys_now;
+#define KEYLINE_H 16
static void set_view(void) {
int sx = 0, sy = 0, sw = 160, sh = 144;
if (sys_now == RG_SYS_NES) {
@@ -316,6 +327,8 @@ static void set_view(void) {
sw = NES_WIDTH - 2 * sx, sh = NES_HEIGHT - 2 * sy;
} else if (is_z80(sys_now)) {
sms_view(&sx, &sy, &sw, &sh); /* (the Game Gear's screen, or the taller pictures of some games) */
+ } else if (sys_now == RG_SYS_GW) {
+ sw = GW_WIDTH, sh = GW_HEIGHT;
}
view.src_x = sx, view.src_y = sy, view.src_w = sw, view.src_h = sh;
int w = sw, h = sh;
@@ -328,7 +341,9 @@ static void set_view(void) {
w &= ~1, h &= ~1;
view.w = NP_MIN(w, SCREEN_W), view.h = NP_MIN(h, SCREEN_H);
view.x = (SCREEN_W - view.w) / 2, view.y = (SCREEN_H - view.h) / 2;
- for (int x = 0; x < view.w; x++) xmap[x] = (uint8_t)(x * sw / view.w);
+ if (sys_now == RG_SYS_GW && cfg.scaling == SCALE_FIT) /* (the Game & Watch's keys in a line below its LCD) */
+ view.h = SCREEN_H - KEYLINE_H, view.w = (view.h * 4 / 3) & ~1, view.x = (SCREEN_W - view.w) / 2, view.y = 0;
+ for (int x = 0; x < view.w; x++) xmap[x] = (uint16_t)(x * sw / view.w);
for (int y = 0; y <= sh; y++) row_first[y] = (uint8_t)((y * view.h + sh - 1) / sh);
redraw_all = true;
}
@@ -361,6 +376,13 @@ static const shape_t cv_shape[] = { /* the console, its cartridge slot and vents
static const shape_t gg_shape[] = {
{-140, -62, 140, 62, 40, 0}, {-56, -46, 56, 40, 6, 1}, {-112, -12, -84, 0, 2, 1}, {-104, -20, -92, 8, 2, 1},
{84, -8, 100, 8, 8, 1}, {106, -18, 122, -2, 8, 1}};
+static const shape_t gw_shape[] = { /* the wide Game & Watch: its LCD, the cross on the left, Time and Game, A on the right */
+ {-140, -72, 140, 72, 10, 0}, {-78, -52, 78, 44, 4, 1}, {-122, -6, -94, 4, 1, 1}, {-113, -15, -103, 13, 1, 1},
+ {-26, 54, -6, 60, 2, 1}, {6, 54, 26, 60, 2, 1}, {96, -6, 120, 18, 12, 1}};
+static const shape_t md_shape[] = { /* the Mega Drive: its body, the round top with the slot, its vents and buttons */
+ {-150, -50, 150, 50, 14, 0}, {-70, -42, 70, 42, 42, 1}, {-40, -6, 40, 2, 2, 0},
+ {-136, -30, -90, -26, 1, 1}, {-136, -18, -90, -14, 1, 1}, {-136, -6, -90, -2, 1, 1},
+ {92, 16, 112, 26, 3, 1}, {118, 16, 138, 26, 3, 1}};
static const look_t looks[RG_SYS_COUNT] = {
{0x202020, 0x303030, "", gb_shape, 0},
{0xE8811F, 0xDF6C10, "1989", gb_shape, sizeof gb_shape / sizeof gb_shape[0]},
@@ -370,6 +392,8 @@ static const look_t looks[RG_SYS_COUNT] = {
{0x0EA186, 0x13BC9D, "1990", gg_shape, sizeof gg_shape / sizeof gg_shape[0]},
{0xC0392B, 0xA93226, "1983", sg_shape, sizeof sg_shape / sizeof sg_shape[0]},
{0x2C3E50, 0x22313F, "1982", cv_shape, sizeof cv_shape / sizeof cv_shape[0]},
+ {0xB8932E, 0xA17F22, "1980", gw_shape, sizeof gw_shape / sizeof gw_shape[0]},
+ {0x2D2D2D, 0x3E3E3E, "1988", md_shape, sizeof md_shape / sizeof md_shape[0]},
};
static bool in_shape(const shape_t *s, int u, int v) {
@@ -414,7 +438,13 @@ static void header(int sys, int y) {
gfx_rrect(1, y + 1, LOGO_W - 2, HEADER_H - 2, 4, WHITE, 256);
gfx_rrect_outline(1, y + 1, LOGO_W - 2, HEADER_H - 2, 4, 1, HEX(0x9AA0A6), 256);
/* a little console: the body, its screen or its pad */
- if (sys == RG_SYS_NES || sys == RG_SYS_SMS || sys == RG_SYS_SG || sys == RG_SYS_CV) {
+ if (sys == RG_SYS_GW) { /* (a little Game & Watch: wide, its LCD, the cross and a button) */
+ gfx_rrect(5, y + 7, 36, 23, 3, gfx_rgb(l->bg), 256);
+ gfx_fill(14, y + 10, 18, 13, HEX(0xC8C8A8));
+ gfx_fill(7, y + 17, 5, 1, HEX(0x303030));
+ gfx_fill(9, y + 15, 1, 5, HEX(0x303030));
+ gfx_circle(37, y + 18, 2, HEX(0xA0204A), 256);
+ } else if (sys == RG_SYS_NES || sys == RG_SYS_SMS || sys == RG_SYS_SG || sys == RG_SYS_CV || sys == RG_SYS_MD) {
gfx_fill(7, y + 11, 32, 15, HEX(0x8C8C8C));
gfx_fill(7, y + 22, 32, 4, HEX(0x3C3C3C));
gfx_fill(10, y + 14, 12, 4, HEX(0xD8D8D8));
@@ -748,27 +778,30 @@ static int session_slot = -1; /* the slot this game was loaded from or sa
static int frameskip = 1, skip; /* Retro-Go's frame skipping */
static uint32_t autosave_at; /* when the battery save is due, 0 none */
-/* the three emulators: gnuboy, nofrendo, and the Master System's (for the Game Gear and the SG-1000 too) */
-enum { CORE_GB, CORE_NES, CORE_SMS };
+/* the emulators: gnuboy, nofrendo, the Master System's (for the Game Gear, the SG-1000 and the
+ ColecoVision too) and LCD-Game-Emulator */
+enum { CORE_GB, CORE_NES, CORE_SMS, CORE_GW };
static int core;
static bool is_gb(void) { return core == CORE_GB; }
static int core_chunks(rg_chunk_t *c) {
- return core == CORE_GB ? gb_state_chunks(c) : core == CORE_NES ? nes_state_chunks(c) : sms_state_chunks(c);
+ return core == CORE_GB ? gb_state_chunks(c) : core == CORE_NES ? nes_state_chunks(c) : core == CORE_GW ? gw_state_chunks(c)
+ : sms_state_chunks(c);
}
/* the battery RAM, NULL if none (a Sega cartridge's only once the game has turned it on) */
static uint8_t *core_sram(uint32_t *size) {
+ if (core == CORE_GW) return *size = 0, NULL; /* (no battery RAM: the state is the save) */
if (core == CORE_SMS) return sms_sram(size);
return core == CORE_GB ? gb_sram(size) : nes_sram(size);
}
static bool core_sram_dirty(void) {
- return core == CORE_GB ? gb_sram_dirty() : core == CORE_NES ? nes_sram_dirty() : sms_sram_dirty();
+ return core == CORE_GB ? gb_sram_dirty() : core == CORE_NES ? nes_sram_dirty() : core == CORE_SMS && sms_sram_dirty();
}
static void core_sram_saved(void) {
if (core == CORE_GB) gb_sram_saved();
else if (core == CORE_NES) nes_sram_saved();
- else sms_sram_saved();
+ else if (core == CORE_SMS) sms_sram_saved();
}
static void core_redraw(void) {
@@ -776,6 +809,7 @@ static void core_redraw(void) {
pend_n = 0;
if (core == CORE_GB) gb_redraw();
else if (core == CORE_NES) nes_redraw();
+ else if (core == CORE_GW) gw_redraw();
else sms_redraw();
flush();
redraw_all = false;
@@ -853,6 +887,7 @@ static bool state_load(int slot) {
if (r > 0) {
if (core == CORE_GB) gb_state_loaded();
else if (core == CORE_NES) nes_state_loaded();
+ else if (core == CORE_GW) gw_state_loaded();
else sms_state_loaded();
last_slot = session_slot = slot, skip = 0;
return true;
@@ -867,6 +902,7 @@ static bool state_load(int slot) {
static void core_reset(bool hard) {
if (core == CORE_GB) gb_reset(hard);
else if (core == CORE_NES) nes_reset_machine(hard);
+ else if (core == CORE_GW) gw_reset(hard); /* (soft: the ACL button) */
else sms_reset(hard);
skip = 0;
}
@@ -891,6 +927,10 @@ static const char *button_name(int k) {
static const char *const cv[] = {T("Joystick"), T("Left button"), T("Right button"), NULL, NULL};
return cv[k];
}
+ if (sys_now == RG_SYS_GW) { /* (Retro-Go's: Select is Time, Start is Game) */
+ static const char *const gw[] = {T("D-pad"), "A", "B", T("Time"), T("Game A")};
+ return gw[k];
+ }
if (!sega) return names[k];
static const char *const sms[] = {T("D-pad"), "2", "1", NULL, T("Pause")};
return k == 4 && sys_now == RG_SYS_GG ? T("Start") : sms[k];
@@ -925,8 +965,31 @@ static void borders_scene(void *ctx) {
gfx_text_right(&np_font_small, view.x - 6, y + 9, keys[i][1], WHITE, 256);
}
}
+/* the Game & Watch's own buttons on the calculator's digits, those the game has (gw_keys) */
+static const struct { uint8_t key, gw; const char *name; } gw_buttons[] = {
+ {eadk_key_one, GW_KEY_GAME_A, T("Game A")}, {eadk_key_two, GW_KEY_GAME_B, T("Game B")},
+ {eadk_key_three, GW_KEY_TIME, T("Time")}, {eadk_key_four, GW_KEY_ALARM, T("Alarm")}};
+static void keyline_scene(void *ctx) {
+ (void)ctx;
+ int y = SCREEN_H - KEYLINE_H;
+ gfx_fill(0, y, SCREEN_W, KEYLINE_H, BLACK);
+ const char *k[6][2];
+ int n = 0, have = gw_keys(), w = 0;
+ for (unsigned i = 0; i < sizeof gw_buttons / sizeof gw_buttons[0]; i++)
+ if (have & gw_buttons[i].gw) k[n][0] = key_names[gw_buttons[i].key], k[n++][1] = gw_buttons[i].name;
+ k[n][0] = "0", k[n++][1] = "ACL";
+ k[n][0] = T("Backspace"), k[n++][1] = T("menu");
+ for (int i = 0; i < n; i++) w += gfx_text_width(&np_font_small, k[i][0]) + gfx_text_width(&np_font_small, k[i][1]) + 4;
+ int gap = NP_MIN(16, NP_MAX(6, (SCREEN_W - 8 - w) / NP_MAX(1, n - 1))), x = NP_MAX(4, (SCREEN_W - w - gap * (n - 1)) / 2);
+ for (int i = 0; i < n; i++) { /* (gfx_text gives the pen's place after the text) */
+ x = gfx_text(&np_font_small, x, y + 11, k[i][0], WHITE, 256) + 4;
+ x = gfx_text(&np_font_small, x, y + 11, k[i][1], HEX(0x9AA0A6), 256) + gap;
+ }
+}
static void game_screen(void) {
- if (view.y > 0) fill_screen(0, 0, SCREEN_W, view.y, BLACK), fill_screen(0, view.y + view.h, SCREEN_W, SCREEN_H - view.y - view.h, BLACK);
+ if (sys_now == RG_SYS_GW && view.y + view.h < SCREEN_H) render_rect(keyline_scene, NULL, 0, view.y + view.h, SCREEN_W, SCREEN_H);
+ else if (view.y > 0) fill_screen(0, view.y + view.h, SCREEN_W, SCREEN_H - view.y - view.h, BLACK);
+ if (view.y > 0) fill_screen(0, 0, SCREEN_W, view.y, BLACK);
if (view.x > 0) {
render_rect(borders_scene, NULL, 0, view.y, view.x, view.y + view.h);
fill_screen(view.x + view.w, view.y, SCREEN_W - view.x - view.w, view.h, BLACK);
@@ -1070,6 +1133,7 @@ static int emulator_options_cb(item_t *it, int ev) {
static int options_menu(void) {
item_t items[] = {OPTION(T("Scaling"), scaling_cb, 0), OPTION(T("Speed"), speed_cb, 0),
{1, T("Emulator options"), "", IT_NORMAL, 0, emulator_options_cb, 0}};
+ if (core == CORE_GW) items[2].flags = IT_DISABLED; /* (nothing to set) */
int r = dialog_run(T("Options"), items, game ? 3 : 1, 0);
cfg_save();
return r;
@@ -1108,7 +1172,7 @@ static int default_keys_cb(item_t *it, int ev) {
return CB_NONE;
}
static int controls(void) {
- item_t items[9];
+ item_t items[11];
for (int i = 0; i < 5; i++) {
const char *label = button_name(i);
items[i] = (item_t){0, label ? label : "", "", label ? IT_NORMAL : IT_HIDDEN, 1, key_cb, i ? i + 3 : 0};
@@ -1117,11 +1181,16 @@ static int controls(void) {
items[3] = (item_t){0, T("Keypad"), "", IT_MESSAGE, 1, NULL, 0}, strcpy(items[3].value, T("0 to 9"));
items[4] = (item_t){0, T("* and #"), "", IT_MESSAGE, 1, NULL, 0}, strcpy(items[4].value, T("x and /"));
}
- items[5] = (item_t){0, T("Menu"), "", IT_MESSAGE, 1, NULL, 0}, strcpy(items[5].value, T("Backspace"));
- items[6] = (item_t){0, T("Quit"), "", IT_MESSAGE, 1, NULL, 0}, strcpy(items[6].value, T("Home (saves)"));
- items[7] = (item_t){0, T("Default keys"), "", IT_NORMAL, 0, default_keys_cb, 0};
- items[8] = (item_t)ITEM(1, T("OK"));
- int r = dialog_run(T("Controls"), items, 9, 8);
+ int n = 5;
+ if (sys_now == RG_SYS_GW && game) { /* (its own buttons on the digits; Select and Start are Time and Game A too) */
+ items[n] = (item_t){0, T("Game A, B, Time, Alarm"), "", IT_MESSAGE, 1, NULL, 0}, strcpy(items[n++].value, "1 2 3 4");
+ items[n] = (item_t){0, "ACL", "", IT_MESSAGE, 1, NULL, 0}, strcpy(items[n++].value, "0");
+ }
+ items[n] = (item_t){0, T("Menu"), "", IT_MESSAGE, 1, NULL, 0}, strcpy(items[n++].value, T("Backspace"));
+ items[n] = (item_t){0, T("Quit"), "", IT_MESSAGE, 1, NULL, 0}, strcpy(items[n++].value, T("Home (saves)"));
+ items[n++] = (item_t){0, T("Default keys"), "", IT_NORMAL, 0, default_keys_cb, 0};
+ items[n++] = (item_t)ITEM(1, T("OK"));
+ int r = dialog_run(T("Controls"), items, n, n - 1);
cfg_save();
return r;
}
@@ -1130,9 +1199,10 @@ static int about(void) {
item_t items[] = {
{0, T("Retro-Go"), "ducalex", IT_MESSAGE, 1, NULL, 0}, {0, "Game Boy", "gnuboy", IT_MESSAGE, 1, NULL, 0},
{0, "NES", "nofrendo", IT_MESSAGE, 1, NULL, 0}, {0, "SMS, GG, SG, COL", T("z80 by superzazu"), IT_MESSAGE, 1, NULL, 0},
+ {0, "Game & Watch", "LCD-Game-Emulator", IT_MESSAGE, 1, NULL, 0},
{0, T("Port"), "NumPlay", IT_MESSAGE, 1, NULL, 0}, MESSAGE(T("Not affiliated with Retro-Go")),
ITEM(1, T("OK"))};
- return dialog_run(T("About Retro-Go"), items, 7, 6);
+ return dialog_run(T("About Retro-Go"), items, 8, 7);
}
/* Retro-Go's save slots: 0 to 3; the slot, DLG_BACK or DLG_HOME */
@@ -1230,11 +1300,12 @@ uint32_t perf_frames, perf_drawn;
static int play(const rg_rom_t *r, int slot) {
sys_now = r->system;
- core = sys_now == RG_SYS_NES ? CORE_NES : is_z80(sys_now) ? CORE_SMS : CORE_GB;
+ core = sys_now == RG_SYS_NES ? CORE_NES : is_z80(sys_now) ? CORE_SMS : sys_now == RG_SYS_GW ? CORE_GW : CORE_GB;
game = r;
game_crc = rom_crc(r);
int err = core == CORE_GB ? gb_load(r->data, r->size)
: core == CORE_NES ? nes_load(r->data, r->size)
+ : core == CORE_GW ? gw_load(r->data, r->size)
: sms_load(r->data, r->size, game_crc,
sys_now == RG_SYS_GG ? SMS_GG
: sys_now == RG_SYS_SG ? SMS_SG
@@ -1266,7 +1337,8 @@ static int play(const rg_rom_t *r, int slot) {
/* a frame: the Game Boy's 70224 clocks at 4.194304 MHz, the NES's 29780.5 at 1.789773 MHz, the
Master System's 59736 at 3.579545 MHz (or 50 a second) */
- const uint32_t frame_us = core == CORE_GB ? 16742 : core == CORE_NES ? 16639 : sms_frame_us();
+ const uint32_t frame_us = core == CORE_GB ? 16742 : core == CORE_NES ? 16639 : core == CORE_GW ? 15625 : sms_frame_us();
+ bool acl_held = false;
uint32_t next_us = millis() * 1000u, second = millis(), frames = 0, busy = 0;
int result = GAME_ON;
frameskip = NP_MAX(1, cfg.speed * 3 / 2), skip = 0, autosave_at = 0;
@@ -1300,10 +1372,21 @@ static int play(const rg_rom_t *r, int slot) {
if ((k & KEY(pad_keys[i])) && !memchr(cfg.keys, pad_keys[i], sizeof cfg.keys)) key = i;
sms_set_keypad(key);
}
+ int gw_keys_held = 0;
+ if (core == CORE_GW) { /* the console's buttons: Start and 1 Game A, Select and 3 Time, 2 Game B, 4 Alarm; 0 ACL */
+ if (pad & RG_PAD_START) gw_keys_held |= GW_KEY_GAME_A;
+ if (pad & RG_PAD_SELECT) gw_keys_held |= GW_KEY_TIME;
+ for (unsigned i = 0; i < sizeof gw_buttons / sizeof gw_buttons[0]; i++)
+ if ((k & KEY(gw_buttons[i].key)) && !memchr(cfg.keys, gw_buttons[i].key, sizeof cfg.keys)) gw_keys_held |= gw_buttons[i].gw;
+ bool acl = (k & KEY(eadk_key_zero)) && !memchr(cfg.keys, eadk_key_zero, sizeof cfg.keys);
+ if (acl && !acl_held) gw_reset(false);
+ acl_held = acl;
+ }
uint32_t t0 = millis();
bool draw = skip == 0;
if (core == CORE_GB) gb_set_pad(pad), gb_run_frame(draw);
else if (core == CORE_NES) nes_set_pad(pad), nes_run_frame(draw);
+ else if (core == CORE_GW) gw_set_pad(pad, gw_keys_held), gw_run_frame(draw);
else sms_set_pad(pad), sms_run_frame(draw);
if (draw) flush(), redraw_all = false, perf_drawn++;
if (core == CORE_SMS) { /* (a game that changes the picture's height) */
@@ -1359,11 +1442,11 @@ static void picker_scene(void *ctx) {
#ifdef NP_PORT
const char *const lines[] = {T("Welcome to Retro-Go!"), "", "Add games to this folder:", rg_port_folder_shown(),
T("Game Boy, Game Boy Color, NES,"), T("Master System, Game Gear, SG-1000,"),
- T("ColecoVision."), T("Home: quit")};
+ T("ColecoVision, Game & Watch."), T("Home: quit")};
#else
static const char *const lines[] = {T("Welcome to Retro-Go!"), "", T("Add games on NumPlay's"),
T("customizer website:"), T("Game Boy, Game Boy Color, NES,"), T("Master System, Game Gear, SG-1000,"),
- T("ColecoVision."), T("Home: quit")};
+ T("ColecoVision, Game & Watch."), T("Home: quit")};
#endif
for (int i = 0; i < 8; i++) gfx_text(&np_font_body, 8, 80 + 18 * i, lines[i], i ? 0xAD55 : WHITE, 256);
return;
@@ -1477,7 +1560,7 @@ int main(void) {
if (tab_count(tab_order[i])) tabs[ntabs++] = tab_order[i];
tab = cfg.tab < ntabs ? cfg.tab : 0;
browse = cfg.browse;
- cursor = ntabs ? tab_first(tabs[tab]) + NP_MIN(cfg.cursor[tabs[tab]], tab_count(tabs[tab]) - 1) : 0;
+ cursor = ntabs ? tab_first(tabs[tab]) + NP_MIN(*cursor_of(tabs[tab]), tab_count(tabs[tab]) - 1) : 0;
restore_behind = launcher_menu_redraw;
picker_draw();
wait_release();
@@ -1513,7 +1596,7 @@ int main(void) {
if (hit & KEY(eadk_key_right)) change = 1;
if (hit & KEY(eadk_key_back)) browse = false, redraw = true;
if (hit & (KEY(eadk_key_ok) | KEY(eadk_key_exe))) {
- cfg.tab = (uint8_t)tab, cfg.browse = browse, cfg.cursor[sys] = (uint8_t)(cursor - first);
+ cfg.tab = (uint8_t)tab, cfg.browse = browse, *cursor_of(sys) = (uint8_t)(cursor - first);
wait_release();
int r = file_menu(&roms[cursor]);
restore_behind = launcher_menu_redraw;
@@ -1524,17 +1607,17 @@ int main(void) {
}
}
if (change && ntabs > 1) {
- cfg.cursor[sys] = (uint8_t)(cursor - first);
+ *cursor_of(sys) = (uint8_t)(cursor - first);
tab = (tab + change + ntabs) % ntabs;
sys = tabs[tab];
- cursor = tab_first(sys) + NP_MIN(cfg.cursor[sys], tab_count(sys) - 1);
+ cursor = tab_first(sys) + NP_MIN(*cursor_of(sys), tab_count(sys) - 1);
redraw = true;
}
if (redraw) picker_draw();
}
if (ntabs) {
int sys = tabs[tab];
- cfg.tab = (uint8_t)tab, cfg.browse = browse, cfg.cursor[sys] = (uint8_t)(cursor - tab_first(sys));
+ cfg.tab = (uint8_t)tab, cfg.browse = browse, *cursor_of(sys) = (uint8_t)(cursor - tab_first(sys));
}
cfg_save();
gfx_buf = their_strip;
diff --git a/games/retrogo/src/romtable.h b/games/retrogo/src/romtable.h
index e3f029e4..7b690a31 100644
--- a/games/retrogo/src/romtable.h
+++ b/games/retrogo/src/romtable.h
@@ -11,7 +11,7 @@
#define RG_ROMS_NAME 40
#define RG_MAX_ROMS 96
-enum { RG_SYS_GB = 1, RG_SYS_GBC, RG_SYS_NES, RG_SYS_SMS, RG_SYS_GG, RG_SYS_SG, RG_SYS_CV, RG_SYS_COUNT };
+enum { RG_SYS_GB = 1, RG_SYS_GBC, RG_SYS_NES, RG_SYS_SMS, RG_SYS_GG, RG_SYS_SG, RG_SYS_CV, RG_SYS_GW, RG_SYS_MD, RG_SYS_COUNT };
typedef struct {
const uint8_t *data;
diff --git a/games/retrogo/tests/gwrom.py b/games/retrogo/tests/gwrom.py
new file mode 100644
index 00000000..8650cb05
--- /dev/null
+++ b/games/retrogo/tests/gwrom.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""A .gw file made here, as LCD-Game-Shrinker lays them out, for the Game & Watch tests (no real
+Game & Watch game may be shared): an SM510 program that lights segments b1 (all four), c1 (two of
+four) and, while the K1 to K4 keys are held (left, right, Game, Time), the four a1 segments.
+
+ gwrom.py OUT.gw [--lz4] the file (--lz4: packed as LCD-Game-Shrinker packs them)
+ gwrom.py OUT.gw --expect KEYS OUT.ppm also the picture the screen must show with those
+ GW buttons held (left 1, right 4, Game 128, Time 64)"""
+import struct
+import sys
+
+W, H = 320, 240
+BTN_LEFT, BTN_RIGHT, BTN_A, BTN_B, BTN_TIME, BTN_GAME = 0x1, 0x4, 0x10, 0x20, 0x40, 0x80
+
+
+def background():
+ px = []
+ for y in range(H):
+ for x in range(W):
+ r, g, b = (x * 31) // (W - 1), (y * 63) // (H - 1), ((x + y) * 31) // (W + H - 2)
+ px.append(r << 11 | g << 5 | b)
+ return px
+
+
+# segment number -> (x, y, w, h); a1 H1..H4 = 0..3, b1 H1..H4 = 64..67, c1 H1..H4 = 192..195
+SEGS = {}
+for k in range(4):
+ SEGS[k] = (10 + 75 * k, 20, 60, 40)
+ SEGS[64 + k] = (10 + 75 * k, 90, 60, 30)
+ SEGS[192 + k] = (10 + 75 * k, 150, 60, 50)
+
+
+def seg_pixel(s, i, j):
+ """the segment's 8-bit pixel: 0xFF (white) lets the background through"""
+ if (i + j) % 7 == 0:
+ return 0xFF
+ return (s * 37 + i * 3 + j) & 0x7F
+
+
+def program():
+ """the SM510's program from its reset vector (page 0xDC0), its steps placed in the order its
+ program counter (an LFSR) goes"""
+ ops = [0x5F, 0x70, 0x2F, 0x10, # LBL 70h, LAX 15, EXC: b1 = 1111
+ 0x5F, 0x50, 0x25, 0x10, # LBL 50h, LAX 5, EXC: c1 = 0101
+ 0x5F, 0x60, 0x6A, 0x10] # loop: LBL 60h, KTA, EXC: a1 = the K keys
+ rom = bytearray(4096)
+ pc, order = 0xDC0, []
+ for _ in range(len(ops) + 1):
+ order.append(pc)
+ feed = 0 if ((pc >> 1 ^ pc) & 1) else 0x20
+ pc = feed | (pc >> 1 & 0x1F) | (pc & ~0x3F)
+ for at, op in zip(order, ops):
+ rom[at] = op
+ rom[order[len(ops)]] = 0x80 | (order[8] & 0x3F) # T loop
+ return bytes(rom)
+
+
+def build():
+ bg = background()
+ nseg = 256
+ xs, ys, ws, hs, offs = [0] * nseg, [0] * nseg, [0] * nseg, [0] * nseg, [0] * nseg
+ pixels = bytearray()
+ for s, (x, y, w, h) in sorted(SEGS.items()):
+ xs[s], ys[s], ws[s], hs[s], offs[s] = x, y, w, h, len(pixels)
+ pixels += bytes(seg_pixel(s, i, j) for j in range(h) for i in range(w))
+ keyboard = [0] * 10
+ keyboard[1] = BTN_LEFT | BTN_RIGHT << 8 | BTN_GAME << 16 | BTN_TIME << 24 # S2: K1..K4
+ keyboard[2] = (BTN_B + BTN_GAME) # S3: Game B
+ parts = [struct.pack(f"<{W * H}H", *bg), bytes(pixels), struct.pack(f"<{nseg}I", *offs),
+ struct.pack(f"<{nseg}H", *xs), struct.pack(f"<{nseg}H", *ys), struct.pack(f"<{nseg}H", *hs),
+ struct.pack(f"<{nseg}H", *ws), b"", program(), struct.pack("<10I", *keyboard)]
+ head_size = 8 + 8 + 8 + 4 + 80
+ body, table = bytearray(), []
+ for p in parts:
+ body += bytes(-(head_size + len(body)) % 4)
+ table += [head_size + len(body) if p else 0, len(p)]
+ body += p
+ head = struct.pack("<8s8s8BI20I", b"SM510\0\0\0", b"w_test01", *([0] * 8), 0, *table)
+ return head + bytes(body), bg, xs, ys, ws, hs
+
+
+def expect(keys):
+ _, bg, xs, ys, ws, hs = build()
+ out = list(bg)
+ on = [64, 65, 66, 67, 192, 194]
+ on += [k for k, b in enumerate((BTN_LEFT, BTN_RIGHT, BTN_GAME, BTN_TIME)) if keys & b]
+ for s in sorted(on):
+ x0, y0, w, h = SEGS[s]
+ for j in range(h):
+ for i in range(w):
+ p = seg_pixel(s, i, j)
+ if p == 0xFF:
+ continue
+ c = out[(y0 + j) * W + x0 + i]
+ r, g, b = ((c >> 11) * p) >> 8, (((c >> 5) & 63) * p) >> 8, ((c & 31) * p) >> 8
+ out[(y0 + j) * W + x0 + i] = r << 11 | g << 5 | b
+ return out
+
+
+def ppm(path, px):
+ with open(path, "wb") as f:
+ f.write(b"P6\n%d %d\n255\n" % (W, H))
+ for c in px:
+ f.write(bytes(((c >> 11) << 3 | (c >> 13), ((c >> 5) & 63) << 2 | ((c >> 9) & 3), (c & 31) << 3 | ((c >> 2) & 7))))
+
+
+def lz4_frame(data):
+ """an LZ4 frame of uncompressed blocks (what an LZ4 reader must take as well as packed ones)"""
+ out = bytearray(b"\x04\x22\x4d\x18")
+ flg, bd = 0x60, 0x70 # version 1, independent blocks; 4 MB blocks
+ out += bytes((flg, bd, 0x73)) # (header checksum byte: not checked by the readers here)
+ for k in range(0, len(data), 4 << 20):
+ blk = data[k:k + (4 << 20)]
+ out += struct.pack("<I", len(blk) | 0x80000000) + blk
+ out += b"\0\0\0\0"
+ return bytes(out)
+
+
+def main():
+ out = sys.argv[1]
+ data = build()[0]
+ if "--lz4" in sys.argv:
+ data = lz4_frame(data)
+ open(out, "wb").write(data)
+ if "--expect" in sys.argv:
+ i = sys.argv.index("--expect")
+ ppm(sys.argv[i + 2], expect(int(sys.argv[i + 1])))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/games/retrogo/tests/host_core.c b/games/retrogo/tests/host_core.c
index b46b6cfa..b9192807 100644
--- a/games/retrogo/tests/host_core.c
+++ b/games/retrogo/tests/host_core.c
@@ -1,7 +1,7 @@
/* Retro-Go's emulators on a computer: runs a ROM for some frames, with random keys if asked,
* and writes the last frame as a PPM picture.
* host_core ROM FRAMES OUT.ppm [SEED] [SCRIPT] (SEED: random pad presses; 0 for none)
- * The system comes from the file's extension (.gb .gbc .nes .sms .gg .sg .col). */
+ * The system comes from the file's extension (.gb .gbc .nes .sms .gg .sg .col .gw). */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -10,14 +10,16 @@
#include "../src/gb/gb.h"
#include "../src/nes/nes_core.h"
#include "../src/sms/sms.h"
+#include "../src/gw/gw.h"
static uint8_t heap[RG_HEAP_SIZE] __attribute__((aligned(8)));
static uint32_t used;
bool rg_drawing = true;
-static uint16_t frame[256 * 240];
+#define FW 320 /* (the widest picture: the Game & Watch's) */
+static uint16_t frame[FW * 240];
static int lines_seen;
/* the three emulators behind the same few calls */
-static enum { GB, NES, SMS } kind;
+static enum { GB, NES, SMS, GW } kind;
void *rg_alloc(uint32_t size) {
size = (size + 7) & ~7u;
@@ -34,7 +36,7 @@ void rg_line(int y, const uint16_t *px) {
fprintf(stderr, "line %d out of the picture\n", y);
abort();
}
- memcpy(frame + y * 256, px, (size_t)(kind == GB ? 160 : 256) * 2);
+ memcpy(frame + y * FW, px, (size_t)(kind == GB ? 160 : kind == GW ? 320 : 256) * 2);
lines_seen++;
}
@@ -65,14 +67,23 @@ static uint32_t crc32(const uint8_t *p, uint32_t n) {
return ~c;
}
-static void set_pad(int p) { kind == NES ? nes_set_pad(p) : kind == SMS ? sms_set_pad(p) : gb_set_pad(p); }
-static void run_frame(void) { kind == NES ? nes_run_frame(true) : kind == SMS ? sms_run_frame(true) : gb_run_frame(true); }
-static int chunks(rg_chunk_t *c) { return kind == NES ? nes_state_chunks(c) : kind == SMS ? sms_state_chunks(c) : gb_state_chunks(c); }
-static void loaded(void) { kind == NES ? nes_state_loaded() : kind == SMS ? sms_state_loaded() : gb_state_loaded(); }
-static void redraw(void) { kind == NES ? nes_redraw() : kind == SMS ? sms_redraw() : gb_redraw(); }
+/* (the Game & Watch: the pad in the low byte, its console's buttons, GW_KEY_*, in the next) */
+static void set_pad(int p) {
+ kind == NES ? nes_set_pad(p) : kind == SMS ? sms_set_pad(p) : kind == GW ? gw_set_pad(p & 0xFF, p >> 8) : gb_set_pad(p);
+}
+static void run_frame(void) {
+ kind == NES ? nes_run_frame(true) : kind == SMS ? sms_run_frame(true) : kind == GW ? gw_run_frame(true) : gb_run_frame(true);
+}
+static int chunks(rg_chunk_t *c) {
+ return kind == NES ? nes_state_chunks(c) : kind == SMS ? sms_state_chunks(c) : kind == GW ? gw_state_chunks(c) : gb_state_chunks(c);
+}
+static void loaded(void) {
+ kind == NES ? nes_state_loaded() : kind == SMS ? sms_state_loaded() : kind == GW ? gw_state_loaded() : gb_state_loaded();
+}
+static void redraw(void) { kind == NES ? nes_redraw() : kind == SMS ? sms_redraw() : kind == GW ? gw_redraw() : gb_redraw(); }
static void view(int *x, int *y, int *w, int *h) {
if (kind == SMS) sms_view(x, y, w, h);
- else *x = 0, *y = 0, *w = kind == NES ? 256 : 160, *h = kind == NES ? 240 : 144;
+ else *x = 0, *y = 0, *w = kind == NES ? 256 : kind == GW ? 320 : 160, *h = kind == GB ? 144 : 240;
}
int main(int argc, char **argv) {
@@ -84,8 +95,10 @@ int main(int argc, char **argv) {
unsigned seed = argc > 4 ? (unsigned)atoi(argv[4]) : 0;
const char *ext = strrchr(argv[1], '.');
bool col = ext && !strcmp(ext, ".col");
- kind = ext && !strcmp(ext, ".nes") ? NES : ext && (!strcmp(ext, ".sms") || !strcmp(ext, ".gg") || !strcmp(ext, ".sg") || col) ? SMS : GB;
+ kind = ext && !strcmp(ext, ".nes") ? NES : ext && (!strcmp(ext, ".sms") || !strcmp(ext, ".gg") || !strcmp(ext, ".sg") || col) ? SMS
+ : ext && !strcmp(ext, ".gw") ? GW : GB;
int r = kind == NES ? nes_load(rom, size)
+ : kind == GW ? gw_load(rom, size)
: kind == SMS ? sms_load(rom, size, crc32(rom, size),
!strcmp(ext, ".gg") ? SMS_GG : !strcmp(ext, ".sg") ? SMS_SG : col ? SMS_CV : SMS_SMS)
: gb_load(rom, size);
@@ -118,7 +131,7 @@ int main(int argc, char **argv) {
static uint8_t copy[RG_HEAP_SIZE + 65536];
uint32_t at = 0;
for (int i = 0; i < n; i++) memcpy(copy + at, parts[i].at, parts[i].size), at += parts[i].size;
- static uint16_t first[256 * 240];
+ static uint16_t first[FW * 240];
for (int pass = 0; pass < 2; pass++) {
if (pass) {
n = chunks(parts);
@@ -148,19 +161,19 @@ int main(int argc, char **argv) {
view(&vx, &vy, &vw, &vh);
}
if (getenv("REDRAW")) {
- static uint16_t last[256 * 240];
+ static uint16_t last[FW * 240];
memcpy(last, frame, sizeof last);
redraw();
int differ = 0;
for (int y = vy; y < vy + vh; y++)
- for (int x = vx; x < vx + vw; x++) differ += last[y * 256 + x] != frame[y * 256 + x];
+ for (int x = vx; x < vx + vw; x++) differ += last[y * FW + x] != frame[y * FW + x];
printf("redraw: %d pixels differ\n", differ);
}
FILE *o = fopen(argv[3], "wb");
fprintf(o, "P6\n%d %d\n255\n", vw, vh);
for (int y = vy; y < vy + vh; y++)
for (int x = vx; x < vx + vw; x++) {
- uint16_t c = frame[y * 256 + x];
+ uint16_t c = frame[y * FW + x];
fputc((c >> 11) << 3 | (c >> 13), o);
fputc(((c >> 5) & 63) << 2 | ((c >> 9) & 3), o);
fputc((c & 31) << 3 | ((c >> 2) & 7), o);
diff --git a/tools/romtable.py b/tools/romtable.py
index 492f0ebf..d072760b 100644
--- a/tools/romtable.py
+++ b/tools/romtable.py
@@ -5,7 +5,8 @@ The table (the customizer website makes the same one; games/retrogo reads it in
is one read-only section, .rodata.np_roms, 4-byte aligned, global symbol np_roms:
u32 magic 0x4D52504E ("NPRM"), u32 version 1, u32 count;
count entries of 52 bytes: u32 offset (from the start of np_roms to the ROM's bytes), u32 size,
- u8 system (1 Game Boy, 2 Game Boy Color, 3 NES, 4 Master System, 5 Game Gear, 6 SG-1000, 7 ColecoVision), u8 reserved[3]
+ u8 system (1 Game Boy, 2 Game Boy Color, 3 NES, 4 Master System, 5 Game Gear, 6 SG-1000, 7 ColecoVision,
+ 8 Game & Watch, 9 Mega Drive), u8 reserved[3]
(zero), char name[40] (UTF-8, zero-padded);
then the ROMs' bytes, each starting 4-byte aligned.
All numbers are little-endian. To be the same byte for byte as the website's for the same files:
@@ -13,7 +14,13 @@ All numbers are little-endian. To be the same byte for byte as the website's for
each next one at the end of the one before rounded up to a multiple of 4, zeros in between;
- the table ends with the last ROM's bytes, then zeros up to a multiple of 4 (no ROMs: the 12-byte
header with count 0);
-- the system comes from the file's extension, in any case: .gb 1, .gbc 2, .nes 3, .sms 4, .gg 5, .sg 6, .col 7;
+- the system comes from the file's extension, in any case: .gb 1, .gbc 2, .nes 3, .sms 4, .gg 5, .sg 6, .col 7,
+ .gw 8, .md .gen .bin .smd 9;
+- the bytes are the file's, but: Game Boy and Sega 8-bit files lose their padding (trim below); a .gw
+ file packed with LZ4 (an LZ4 frame, as LCD-Game-Shrinker writes them) is unpacked; a Mega Drive
+ game is made plain (an .smd file's 512-byte header dropped and its 16 KB blocks put back in order,
+ as gwenesis does) and its bytes swapped in pairs (the emulator reads its 16-bit words as they are,
+ on a little-endian processor), padded with a zero to an even size;
- the name is the file's name without its last extension, its UTF-8 bytes cut to the longest
start of at most 40 bytes that ends on a whole letter, zero-padded to 40 (no ending zero when it
takes all 40).
@@ -29,7 +36,84 @@ import struct
import sys
MAGIC, VERSION, ENTRY, NAME = 0x4D52504E, 1, 52, 40
-SYSTEMS = {".gb": 1, ".gbc": 2, ".nes": 3, ".sms": 4, ".gg": 5, ".sg": 6, ".col": 7}
+SYSTEMS = {".gb": 1, ".gbc": 2, ".nes": 3, ".sms": 4, ".gg": 5, ".sg": 6, ".col": 7, ".gw": 8,
+ ".md": 9, ".gen": 9, ".bin": 9, ".smd": 9}
+
+
+def lz4_unpack(data):
+ """an LZ4 frame's bytes (its block and content checksums not checked)"""
+ if data[:4] != b"\x04\x22\x4d\x18":
+ return data
+ flg = data[4]
+ i = 7 + (8 if flg & 0x08 else 0) + (4 if flg & 0x01 else 0)
+ out = bytearray()
+ while i + 4 <= len(data):
+ n = struct.unpack_from("<I", data, i)[0]
+ i += 4
+ if n == 0:
+ break
+ raw, n = n & 0x80000000, n & 0x7FFFFFFF
+ blk = data[i:i + n]
+ i += n + (4 if flg & 0x10 else 0)
+ if raw:
+ out += blk
+ continue
+ j = 0
+ while j < len(blk):
+ tok = blk[j]
+ j += 1
+ lit = tok >> 4
+ if lit == 15:
+ while True:
+ b = blk[j]
+ j += 1
+ lit += b
+ if b != 255:
+ break
+ out += blk[j:j + lit]
+ j += lit
+ if j >= len(blk):
+ break
+ off = blk[j] | blk[j + 1] << 8
+ j += 2
+ ml = (tok & 15) + 4
+ if (tok & 15) == 15:
+ while True:
+ b = blk[j]
+ j += 1
+ ml += b
+ if b != 255:
+ break
+ if not 0 < off <= len(out):
+ sys.exit("romtable: a broken LZ4 file")
+ for _ in range(ml):
+ out.append(out[-off])
+ return bytes(out)
+
+
+def mega_drive(data, smd):
+ """a Mega Drive game as gwenesis reads it in place: plain (not .smd), its bytes swapped in pairs"""
+ if (smd or (len(data) > 0x200 and data[1] == 3 and data[8] == 0xAA and data[9] == 0xBB)) and len(data) % 0x4000 == 0x200:
+ body, plain = data[0x200:], bytearray()
+ for k in range(0, len(body), 0x4000):
+ blk = body[k:k + 0x4000]
+ for j in range(0x2000):
+ plain += bytes((blk[0x2000 + j], blk[j]))
+ data = bytes(plain)
+ if len(data) % 2:
+ data += b"\0"
+ swapped = bytearray(len(data))
+ swapped[0::2], swapped[1::2] = data[1::2], data[0::2]
+ return bytes(swapped)
+
+
+def rom_bytes(path, system):
+ data = open(path, "rb").read()
+ if system == 8:
+ return lz4_unpack(data)
+ if system == 9:
+ return mega_drive(data, path.lower().endswith(".smd"))
+ return trim(data, system)
def entry_name(path):
@@ -60,8 +144,8 @@ def table(paths):
for p in paths:
ext = os.path.splitext(p)[1].lower()
if ext not in SYSTEMS:
- sys.exit(f"romtable: {p}: not a .gb, .gbc, .nes, .sms, .gg, .sg or .col file")
- roms.append((trim(open(p, "rb").read(), SYSTEMS[ext]), SYSTEMS[ext], entry_name(p)))
+ sys.exit(f"romtable: {p}: not a .gb, .gbc, .nes, .sms, .gg, .sg, .col, .gw, .md, .gen, .bin or .smd file")
+ roms.append((rom_bytes(p, SYSTEMS[ext]), SYSTEMS[ext], entry_name(p)))
out = bytearray(struct.pack("<III", MAGIC, VERSION, len(roms)))
out += bytes(ENTRY * len(roms))
for i, (data, system, name) in enumerate(roms):