commit 63c36ebe1c059f286b5c54db06e31492be656f4c Author: Pascal Engélibert Date: Sat Sep 26 23:37:19 2026 +0200 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..ba18a6f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,313 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "argp" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca6b2169f9679af5b5ed7780941555a03d795fec86996d8605b28f63195acb" +dependencies = [ + "argp_derive", +] + +[[package]] +name = "argp_derive" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad1eb5de915b522348ebd6690c0e12f905b37797c2dc18a267027e7d422e8ad6" +dependencies = [ + "proc-macro2", + "pulldown-cmark", + "quote", + "syn", +] + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "bytemuck" +version = "1.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "getopts" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "packing" +version = "0.1.0" +dependencies = [ + "png", + "skrivan", +] + +[[package]] +name = "pixglyph" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47945e80a49d08350e4a007ac4294c6498d23956c18ea5e6ff480dc93d31643c" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pulldown-cmark" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57206b407293d2bcd3af849ce869d52068623f19e1b5ff8e8778e3309439682b" +dependencies = [ + "bitflags", + "getopts", + "memchr", + "unicase", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rustybuzz" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" +dependencies = [ + "bitflags", + "bytemuck", + "core_maths", + "log", + "smallvec", + "ttf-parser", + "unicode-bidi-mirroring", + "unicode-ccc", + "unicode-properties", + "unicode-script", +] + +[[package]] +name = "simd-adler32" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" + +[[package]] +name = "skrivan" +version = "0.1.0" +dependencies = [ + "bytemuck", + "utf8-decode", +] + +[[package]] +name = "skrivan-cli" +version = "0.1.0" +dependencies = [ + "argp", + "pixglyph", + "png", + "rustybuzz", + "skrivan", +] + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] + +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + +[[package]] +name = "unicode-bidi-mirroring" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfa6e8c60bb66d49db113e0125ee8711b7647b5579dc7f5f19c42357ed039fe" + +[[package]] +name = "unicode-ccc" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "unicode-script" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "utf8-decode" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7932c10aa1600e9ddee027024aa9c0d397a103478253bf3fd6cea6dd03161b8a" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..3666efa --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,3 @@ +[workspace] +members = ["examples/packing","skrivan", "skrivan-cli"] +resolver = "3" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero 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. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d8f30f0 --- /dev/null +++ b/README.md @@ -0,0 +1,40 @@ +# Skrivañ + +This is: +* a CLI tool to render a subset of a TTF/OTF/AAT font to PNG, and produce a custom-format character-to-positions map; +* a lightweight crate to load such a map and render text to textures (or just iterate on glyphs and let you do the rendering). + +Ideal for making a lightweight 2D game. All the hard work and big dependencies are done before compiling the game. No TTF to include, only an image and a small binary file. Rendering text is simply associating characters to positions on the font texture, like a tilemap. Glyphs can be fed to a vertex shader easily. + +Not yet features: +* alignment (currently only left alignment is supported) +* wordwrap + +Not planned: +* Smart kerning algorithms, hyphenation, and other LaTeX-grade stuff. +* Subpixel antialiasing (antialiasing is computed only for the base texture, not when rendering text) + +Similar tools already exist, but: +* the best ones, like harfbuzz, are quite heavy (we use harfbuzz for rendering). +* the lightest ones are made for embedded or Gameboy. +* other ones need the TTF at runtime. + +## Example + +```rust + +``` + +## Name + +"Skrivañ" is the Breton infinitive verb "to write". Pronounce skree.vã, with a nasalized "a". + +## License + +[Support me via LiberaPay](https://liberapay.com/tuxmain/donate) + +GNU AGPL v3, CopyLeft 2026 Pascal Engélibert [(why copyleft?)](https://txmn.tk/blog/why-copyleft/) + +This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3 of the License. +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 Affero General Public License for more details. +You should have received a copy of the GNU Affero General Public License along with this program. If not, see https://www.gnu.org/licenses/. diff --git a/examples/packing/Cargo.toml b/examples/packing/Cargo.toml new file mode 100644 index 0000000..6cc78f8 --- /dev/null +++ b/examples/packing/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "packing" +version = "0.1.0" +edition = "2024" + +[dependencies] +png = "0.18" +skrivan = { path = "../../skrivan" } diff --git a/examples/packing/src/main.rs b/examples/packing/src/main.rs new file mode 100644 index 0000000..b61b901 --- /dev/null +++ b/examples/packing/src/main.rs @@ -0,0 +1,49 @@ +fn main() { + //let mut rects = Vec::new(); + //for i in 0..10 { + // rects.push((16+i*11%8, 16+i*9%8)); + // rects.push((50+i*13%20, 14+i*7%10)); + // rects.push((10+i*11%9, 63+i*17%10)); + //} + //bench("test", (512, 512), &rects); +} + +/*fn bench(name: &str, size: (u32, u32), rects: &[(u32, u32)]) { + let mut packer = skrivan::packer::Packer::new(512, 512); + let start = std::time::Instant::now(); + for (i, rect) in rects.iter().enumerate() { + assert!(packer.insert(i, rect.0, rect.1)); + packer.display(); + } + let dur = start.elapsed(); + let mut bitmap = vec![0; (size.0*size.1*4) as usize]; + let mut full = 0; + let mut max_x = 0; + let mut max_y = 0; + for i in 0..rects.len() { + let rect = packer.get(i).unwrap(); + for y in rect.y..rect.y+rect.h { + for x in rect.x..rect.x+rect.w { + bitmap[((y*size.0+x)*4) as usize] = (rect.x * 101) as u8; + bitmap[((y*size.0+x)*4+1) as usize] = (rect.y * 101) as u8; + bitmap[((y*size.0+x)*4+2) as usize] = ((rect.x+rect.y+64) * 101) as u8; + bitmap[((y*size.0+x)*4+3) as usize] = 255; + } + } + full += rect.w*rect.h; + max_x = max_x.max(rect.x+rect.w); + max_y = max_y.max(rect.y+rect.h); + } + let output = std::fs::File::create(format!("/dev/shm/bench-{name}.png")).unwrap(); + let writer = &mut std::io::BufWriter::new(output); + let mut encoder = png::Encoder::new( + writer, + size.0, + size.1, + ); + encoder.set_color(png::ColorType::Rgba); + let mut writer = encoder.write_header().unwrap(); + writer.write_image_data(&bitmap).unwrap(); + writer.finish().unwrap(); + println!("{name}:\tfill={} time={}ms", full as f32/(max_x*max_y) as f32, dur.as_secs_f32()*1000.0); +}*/ diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..26b2841 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,9 @@ +hard_tabs = true +newline_style = "Unix" +imports_granularity = "Crate" + +unstable_features = true +format_code_in_doc_comments = true +format_macro_bodies = true +format_macro_matchers = true +format_strings = true diff --git a/skrivan-cli/Cargo.toml b/skrivan-cli/Cargo.toml new file mode 100644 index 0000000..435d1ab --- /dev/null +++ b/skrivan-cli/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "skrivan-cli" +version = "0.1.0" +edition = "2024" + +[dependencies] +argp = "0.4.1" +pixglyph = "0.6" +png = "0.18" +rustybuzz = "0.20" +skrivan = { path = "../skrivan" } diff --git a/skrivan-cli/src/main.rs b/skrivan-cli/src/main.rs new file mode 100644 index 0000000..90c6661 --- /dev/null +++ b/skrivan-cli/src/main.rs @@ -0,0 +1,123 @@ +use skrivan::{Atlas, Glyph}; + +use std::{ + collections::{HashMap, HashSet}, + io::Write, +}; + +/// Render fonts to PNG altas and parsable char-to-coordinate map. +/// +/// The input text file may contain multiple times the same characters, +/// they will be rendered only once. +/// Newlines and space characters are ignored. +/// +/// Skrivañ, CopyLeft 2026 tuxmain (GNU AGPL v3) +#[derive(argp::FromArgs)] +struct Cli { + /// Path to the font file (TTF, OTF, AAT) + #[argp(positional)] + font: String, + /// Path to a text file containing the characters that will be rendered + #[argp(positional)] + text: String, + /// Path to the output image file + #[argp(positional)] + image: String, + /// Path to the output atlas file + #[argp(positional)] + atlas: String, + /// Font size + #[argp(positional)] + size: f32, + /// Maximum width of the image + #[argp(option, short = 'w', default = "256")] + width: u32, +} + +fn main() { + let cli: Cli = argp::parse_args_or_exit(argp::DEFAULT); + + let font_data = std::fs::read(cli.font).expect("Cannot read font file"); + let face = rustybuzz::ttf_parser::Face::parse(&font_data, 0).expect("Cannot parse font"); + + let mut charset = HashSet::new(); + let mut chars = HashMap::new(); + let mut buffer = rustybuzz::UnicodeBuffer::new(); + let text = std::fs::read_to_string(cli.text).expect("Cannot read text file"); + for (i, c) in text.char_indices() { + if c.is_whitespace() { + continue; + } + if charset.insert(c) { + buffer.add(c, i as u32); + chars.insert(i, c); + } + } + + let shape = rustybuzz::shape(&rustybuzz::Face::from_face(face.clone()), &[], buffer); + + let mut bitmaps = HashMap::new(); + let mut max_w = 0; + let mut max_h = 0; + for c in shape.glyph_infos() { + if let Some(glyph) = + pixglyph::Glyph::load(&face, rustybuzz::ttf_parser::GlyphId(c.glyph_id as u16)) + { + let bitmap = glyph.rasterize(0., 0., cli.size); + max_w = max_w.max(bitmap.width); + max_h = max_h.max(bitmap.height); + bitmaps.insert(chars[&(c.cluster as usize)], bitmap); + dbg!(chars[&(c.cluster as usize)]); + } + } + + let mut atlas = Atlas { + charmap: HashMap::new(), + }; + let image_width = cli.width as usize; + let mut pixels = Vec::new(); + let mut x: u32 = 0; + let mut y: u32 = 0; + for (c, bitmap) in bitmaps { + if x + bitmap.width >= image_width as _ { + x = 0; + y += max_h; + } + if pixels.len() <= image_width * y as usize { + pixels.extend_from_slice(&vec![0; image_width * max_h as usize]); + } + atlas.charmap.insert( + c, + Glyph { + x, + y, + w: bitmap.width, + h: bitmap.height, + offset_x: bitmap.left, + offset_y: bitmap.top, + }, + ); + for by in 0..bitmap.height { + for bx in 0..bitmap.width { + pixels[((y + by) * image_width as u32 + x + bx) as usize] = + bitmap.coverage[(by * bitmap.width + bx) as usize]; + } + } + x += bitmap.width; + } + + let output = std::fs::File::create(cli.image).expect("Cannot open output image file"); + let writer = &mut std::io::BufWriter::new(output); + let mut encoder = png::Encoder::new( + writer, + image_width as u32, + (pixels.len() / image_width) as u32, + ); + encoder.set_color(png::ColorType::Grayscale); + let mut writer = encoder.write_header().unwrap(); + writer.write_image_data(&pixels).unwrap(); + writer.finish().unwrap(); + + let mut output = std::fs::File::create(cli.atlas).expect("Cannot open output atlas file"); + output.write_all(&atlas.serialize()).unwrap(); +} diff --git a/skrivan/Cargo.toml b/skrivan/Cargo.toml new file mode 100644 index 0000000..fa94a1b --- /dev/null +++ b/skrivan/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "skrivan" +version = "0.1.0" +edition = "2024" + +[dependencies] +# std has so many functions to decode UTF-8, but nothing just to decode a single char! +utf8-decode = "2" + +# Optional +bytemuck = { version = "1.25.0", features = ["derive"], optional = true } + +[features] +# Might help if passing glyphs to a WGPU vertex shader. +bytemuck = ["dep:bytemuck"] diff --git a/skrivan/src/lib.rs b/skrivan/src/lib.rs new file mode 100644 index 0000000..4390096 --- /dev/null +++ b/skrivan/src/lib.rs @@ -0,0 +1,231 @@ +#![warn(missing_docs)] +#![deny(non_ascii_idents)] +#![deny(unnameable_types)] +#![deny(unreachable_pub)] +#![deny(unsafe_code)] +#![deny(unstable_features)] +#![warn(unused_qualifications)] +#![allow(clippy::tabs_in_doc_comments)] + +//! TODO + +use std::{collections::HashMap, str::Chars}; + +/// Settings for rendering a font +#[derive(Clone, Debug)] +pub struct FontSettings<'a, T> { + /// Whitespace width + pub space_w: u32, + /// Vertical offset between text lines + pub line_h: u32, + /// Maximum width of the rendered text rectangle + pub width: u32, + /// Some texture containing the font + pub font_texture: &'a [T], + /// Width of the font texture + pub font_texture_width: u32, + /// Bytes per pixel on the textures (e.g. 4 for RGBA) + /// + /// Must be the same on font texture and render texture. + pub bytes_per_pixel: usize, + /// Offset of the font texture in the entire texture + /// + /// Allows to store multiple fonts (or other things) in the same texture. + pub font_texture_offset: (u32, u32), +} + +/// Description of the mapping between characters and positions on the font texture +#[derive(Clone)] +pub struct Atlas { + /// Character map + pub charmap: HashMap, +} + +/// A glyph on the font texture +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Glyph { + /// X position on the font texture + pub x: u32, + /// Y position on the font texture + pub y: u32, + /// Width + pub w: u32, + /// Height + pub h: u32, + /// X offset relative to the position, at which it should be rendered + pub offset_x: i32, + /// Y offset relative to the position, at which it should be rendered + pub offset_y: i32, +} + +/// Atlas deserialization error +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum DeserializeError { + /// Format is invalid + InvalidFormat, + /// Encountered invalid UTF-8 character + Utf8(utf8_decode::Utf8Error), +} + +impl Atlas { + /// Build an atlas from its byte encoding + pub fn deserialize(data: &[u8]) -> Result { + let mut charmap = HashMap::new(); + + let mut offset = 0; + while let Some((c, _len)) = + utf8_decode::try_decode_char(data, &mut offset).map_err(DeserializeError::Utf8)? + { + if data.len() - offset < 8 { + return Err(DeserializeError::InvalidFormat); + } + let glyph = Glyph { + x: u16::from_be_bytes(data[offset..offset + 2].try_into().expect("unreachable")) + as u32, + y: u16::from_be_bytes( + data[offset + 2..offset + 4] + .try_into() + .expect("unreachable"), + ) as u32, + w: data[offset + 4] as u32, + h: data[offset + 5] as u32, + offset_x: i8::from_be_bytes([data[offset + 6]]) as i32, + offset_y: i8::from_be_bytes([data[offset + 7]]) as i32, + }; + charmap.insert(c, glyph); + offset += 8; + } + Ok(Self { charmap }) + } + + /// Encode an atlas to bytes + pub fn serialize(&self) -> Vec { + let mut output = Vec::new(); + for (c, glyph) in self.charmap.iter() { + let c_len = c.len_utf8(); + output.extend(std::iter::repeat_n(0, c_len + 8)); + let mut offset = output.len() - 8 - c_len; + c.encode_utf8(&mut output[offset..]); + offset += c_len; + output[offset..offset + 2].copy_from_slice(&(glyph.x as u16).to_be_bytes()); + output[offset + 2..offset + 4].copy_from_slice(&(glyph.y as u16).to_be_bytes()); + output[offset + 4..offset + 5].copy_from_slice(&(glyph.w as u8).to_be_bytes()); + output[offset + 5..offset + 6].copy_from_slice(&(glyph.h as u8).to_be_bytes()); + output[offset + 6..offset + 7].copy_from_slice(&(glyph.offset_x as i8).to_be_bytes()); + output[offset + 7..offset + 8].copy_from_slice(&(glyph.offset_y as i8).to_be_bytes()); + } + output + } + + /// Shape a text using the font (i.e. compute render position for each glyph) + pub fn shape<'a, T>(&'a self, font_settings: &'a FontSettings<'a, T>, text: &'a str) -> Shaper<'a, T> { + Shaper { + font_settings, + atlas: self, + chars: text.chars(), + x: 0, + y: 0, + } + } +} + +/// Mapping of a rectangle from font atlas to a render texture (usable in a vertex shader) +#[derive(Copy, Clone, Debug)] +#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))] +#[repr(C)] +pub struct TextureMap { + /// X position on the font texture + pub atlas_x: u32, + /// Y position on the font texture + pub atlas_y: u32, + /// X position on the render texture + pub render_x: i32, + /// Y position on the render texture + pub render_y: i32, + /// Width + pub w: u32, + /// Height + pub h: u32, +} + +/// Iterator on glyphs to be rendered +pub struct Shaper<'a, T> { + font_settings: &'a FontSettings<'a, T>, + atlas: &'a Atlas, + chars: Chars<'a>, + x: u32, + y: u32, +} + +impl<'a, T> Iterator for Shaper<'a, T> { + type Item = TextureMap; + // TODO wordwrap + // TODO alignment + fn next(&mut self) -> Option { + loop { + let c = self.chars.next()?; + if c == '\r' { + self.x = 0; + continue; + } + if c == '\n' { + self.x = 0; + self.y += self.font_settings.line_h; + continue; + } + if c.is_whitespace() { + self.x += self.font_settings.space_w; + continue; + } + let Some(glyph) = self.atlas.charmap.get(&c) else { + self.x += self.font_settings.space_w; + continue; + }; + if self.x + glyph.w > self.font_settings.width { + self.x = 0; + self.y += self.font_settings.line_h; + } + let texture_map = TextureMap { + atlas_x: glyph.x, + atlas_y: glyph.y, + render_x: self.x as i32 + glyph.offset_x, + render_y: self.y as i32 + glyph.offset_y, + w: glyph.w, + h: glyph.h, + }; + self.x += glyph.w; + return Some(texture_map); + } + } +} + +impl<'a, T: Copy> Shaper<'a, T> { + // TODO blend + // TODO alignment + /// Directly render the text to a texture + /// + /// If you want to do the rendering yourself (e.g. to control blending or to use GPU), + /// use the iterator instead. + pub fn render( + self, + texture: &mut [T], + texture_width: u32, + text_pos: (u32, u32), + ) { + let font_settings = self.font_settings; + for texture_map in self { + let byte_len = texture_map.w as usize * font_settings.bytes_per_pixel; + for y in 0..texture_map.h { + let index = (((text_pos.1 + y).strict_add_signed(texture_map.render_y)) * texture_width + + text_pos.0) + .strict_add_signed(texture_map.render_x) as usize + * font_settings.bytes_per_pixel; + let font_index = ((font_settings.font_texture_offset.1 + texture_map.atlas_y + y) * font_settings.font_texture_width + + font_settings.font_texture_offset.0 + texture_map.atlas_x) as usize + * font_settings.bytes_per_pixel; + texture[index..index + byte_len] + .copy_from_slice(&font_settings.font_texture[font_index..font_index + byte_len]); + } + } + } +} diff --git a/skrivan/src/packer.rs b/skrivan/src/packer.rs new file mode 100644 index 0000000..a5a72ab --- /dev/null +++ b/skrivan/src/packer.rs @@ -0,0 +1,187 @@ +use std::{collections::HashMap, iter::repeat_n}; + +pub struct Packer { + tree: HashMap, Node>, + next_key: u64, +} + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum Key { + Branch(u64), + Leaf(K), +} + +/*pub enum Node { + Branch(Branch), + Leaf(Leaf), +}*/ + +#[derive(Clone)] +pub struct Node { + x: u32, + y: u32, + w: u32, + h: u32, + parent: u64, + node_type: NodeType, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NodeType { + EmptyLeaf, + FullLeaf, + Branch(Key, Key), +} + +/*pub struct Branch { + x: u32, + y: u32, + w: u32, + h: u32, + children: Option<(Key, Key)>, +} + +pub struct Leaf { + x: u32, + y: u32, + w: u32, + h: u32, +}*/ + +impl Packer { + pub fn new(w: u32, h: u32) -> Self { + let mut tree = HashMap::new(); + tree.insert(Key::Branch(0), Node { + x: 0, y: 0, w, h, node_type: NodeType::EmptyLeaf, parent: 0, + }); + Self {tree, next_key: 1} + } + + pub fn insert(&mut self, key: K, w: u32, h: u32) -> bool { + const STACK_LEN: usize = 16; + let mut stack = [(Key::Branch(0), 0u8); STACK_LEN]; + let mut stack_top = 0; + loop { + println!("Loop: {stack_top}"); + let node = self.tree.get_mut(&stack[stack_top].0).expect("invalid internal state"); + if node.w < w || node.h < h { + if stack_top == 0 { + // No room left + return false + } + stack_top -= 1; + println!("No room, going back"); + continue + } + match node.node_type.clone() { + NodeType::EmptyLeaf => { + println!("Empty"); + node.node_type = NodeType::Branch(Key::Branch(self.next_key), Key::Branch(self.next_key+1)); + let Key::Branch(parent) = stack[stack_top].0 else {unreachable!()}; + let node = node.clone(); + self.tree.insert(Key::Branch(self.next_key), Node { x: node.x, y: node.y, w: w, h: node.h, node_type: NodeType::Branch(Key::Leaf(key), Key::Branch(self.next_key+2)), parent }); + self.tree.insert(Key::Branch(self.next_key+1), Node { x: node.x+w, y: node.y, w: node.w-w, h: node.h, node_type: NodeType::EmptyLeaf, parent: self.next_key }); + self.tree.insert(Key::Branch(self.next_key+2), Node { x: node.x, y: node.y+h, w: w, h: node.h-h, node_type: NodeType::EmptyLeaf, parent: self.next_key }); + self.tree.insert(Key::Leaf(key), Node { x: node.x, y: node.y, w, h, node_type: NodeType::FullLeaf, parent }); + self.next_key += 3; + return true + } + NodeType::FullLeaf => { + println!("Full"); + if stack_top == 0 { + // No room left + return false + } + stack_top -= 1; + } + NodeType::Branch(k1, k2) => { + println!("Branch"); + if stack_top == STACK_LEN-1 { + // Too much recursion + stack_top -= 1; + println!("Too much recursion"); + continue + } + if stack[stack_top].1 < 2 { + println!("Deep sibling"); + if stack[stack_top].1 == 0 { + println!("Deep sibling 0"); + stack[stack_top+1] = (k1, 0); + } + else if stack[stack_top].1 == 1 { + println!("Deep sibling 1"); + stack[stack_top+1] = (k2, 0); + } + stack[stack_top].1 += 1; + stack_top += 1; + } else { + println!("Branch going back"); + if stack_top == 0 { + // Finished? + return false + } + stack_top -= 1; + } + } + } + } + } + + /*pub fn remove(&mut self, key: K) -> bool { + let mut k = Key::Leaf(key); + if let Some(leaf) = self.tree.remove(&k) { + let mut parent = leaf.parent; + loop { + let branch = self.tree.get_mut(&Key::Branch(parent)).expect("invalid internal state"); + match branch.node_type.clone() { + NodeType::Branch(k1, k2) => { + let sibling_key = + if k1 == k { + k2 + } else { + k1 + }; + let sibling = self.tree.get() + } + _ => unreachable!(), + } + } + true + } else { + false + } + }*/ + + pub fn get(&self, key: K) -> Option { + self.tree.get(&Key::Leaf(key)).map(|n| Rect { x: n.x, y: n.y, w: n.w, h: n.h }) + } + + pub fn display(&self) { + self.display_internal(Key::Branch(0), 0); + } + + fn display_internal(&self, key: Key, level: usize) { + let node = self.tree.get(&key).unwrap(); + match node.node_type.clone() { + NodeType::Branch(k1, k2) => { + println!("{}Branch {}:{} {}:{}", repeat_n(' ', level).collect::(), node.x, node.y, node.w, node.h); + self.display_internal(k1, level+1); + self.display_internal(k2, level+1); + } + NodeType::EmptyLeaf => { + println!("{}Empty {}:{} {}:{}", repeat_n(' ', level).collect::(), node.x, node.y, node.w, node.h); + } + NodeType::FullLeaf => { + println!("{}Full {}:{} {}:{}", repeat_n(' ', level).collect::(), node.x, node.y, node.w, node.h); + } + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Rect { + pub x: u32, + pub y: u32, + pub w: u32, + pub h: u32, +}